From 92d56752bac86346dd532f0ec05873e897c36ff1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 17:32:32 +0200 Subject: [PATCH 1/9] use pointer address formatter instead of casting To print addresses of objects, use address pointer formatter directly instead of casting to other types to print. --- src/arch/aarch64/kernel/interrupts.rs | 2 +- src/arch/x86_64/kernel/mmio.rs | 11 ++++------- src/mm/freelist.rs | 16 +++++----------- 3 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/arch/aarch64/kernel/interrupts.rs b/src/arch/aarch64/kernel/interrupts.rs index 591cc5a64b..683d3dc7b3 100644 --- a/src/arch/aarch64/kernel/interrupts.rs +++ b/src/arch/aarch64/kernel/interrupts.rs @@ -190,7 +190,7 @@ pub(crate) extern "C" fn do_sync(state: &State) { // add page fault handler - error!("Current stack pointer {:#x}", state as *const _ as u64); + error!("Current stack pointer {state:p}"); error!("Unable to handle page fault at {:#x}", far); error!("Exception return address {:#x}", ELR_EL1.get()); error!("Thread ID register {:#x}", TPIDR_EL0.get()); diff --git a/src/arch/x86_64/kernel/mmio.rs b/src/arch/x86_64/kernel/mmio.rs index f3cdda926a..4f6d4c98c2 100644 --- a/src/arch/x86_64/kernel/mmio.rs +++ b/src/arch/x86_64/kernel/mmio.rs @@ -74,7 +74,7 @@ pub fn detect_network() -> Result<&'static mut MmioRegisterLayout, &'static str> let version = mmio.get_version(); if magic != MAGIC_VALUE { - trace!("It's not a MMIO-device at {:#X}", mmio as *const _ as usize); + trace!("It's not a MMIO-device at {mmio:p}"); continue; } @@ -84,20 +84,17 @@ pub fn detect_network() -> Result<&'static mut MmioRegisterLayout, &'static str> } // We found a MMIO-device (whose 512-bit address in this structure). - trace!("Found a MMIO-device at {:#X}", mmio as *const _ as usize); + trace!("Found a MMIO-device at {mmio:p}"); // Verify the device-ID to find the network card let id = mmio.get_device_id(); if id != DevId::VIRTIO_DEV_ID_NET { - trace!( - "It's not a network card at {:#X}", - mmio as *const _ as usize - ); + trace!("It's not a network card at {mmio:p}"); continue; } - info!("Found network card at {:#X}", mmio as *const _ as usize); + info!("Found network card at {mmio:p}"); crate::arch::mm::physicalmem::reserve( PhysAddr::from(current_address.align_down(BasePageSize::SIZE as usize)), diff --git a/src/mm/freelist.rs b/src/mm/freelist.rs index 3102754589..2b11721976 100644 --- a/src/mm/freelist.rs +++ b/src/mm/freelist.rs @@ -33,11 +33,7 @@ impl FreeList { } pub fn allocate(&mut self, size: usize, alignment: Option) -> Result { - trace!( - "Allocating {} bytes from Free List {:#X}", - size, - self as *const Self as usize - ); + trace!("Allocating {} bytes from Free List {self:p}", size); let new_size = if let Some(align) = alignment { size + align @@ -90,10 +86,9 @@ impl FreeList { #[cfg(all(target_arch = "x86_64", not(feature = "pci")))] pub fn reserve(&mut self, address: usize, size: usize) -> Result<(), AllocError> { trace!( - "Try to reserve {} bytes at {:#X} from Free List {:#X}", + "Try to reserve {} bytes at {:#X} from Free List {self:p}", size, - address, - self as *const Self as usize + address ); // Find a region in the Free List that has at least the requested size. @@ -119,10 +114,9 @@ impl FreeList { pub fn deallocate(&mut self, address: usize, size: usize) { trace!( - "Deallocating {} bytes at {:#X} from Free List {:#X}", + "Deallocating {} bytes at {:#X} from Free List {self:p}", size, - address, - self as *const Self as usize + address ); let end = address + size; From 64ea080c7010a84896e03ee126f09be43a8026f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 17:53:13 +0200 Subject: [PATCH 2/9] use from_{ref,mut} to get pointers from references Using these functions makes the intent clearer and increases readability --- src/arch/aarch64/kernel/mod.rs | 4 ++-- src/arch/aarch64/kernel/switch.rs | 2 +- src/arch/aarch64/mm/paging.rs | 2 +- src/arch/x86_64/kernel/acpi.rs | 4 ++-- src/arch/x86_64/kernel/apic.rs | 2 +- src/arch/x86_64/kernel/processor.rs | 10 +++++----- src/arch/x86_64/kernel/scheduler.rs | 2 +- src/arch/x86_64/kernel/switch.rs | 2 +- src/drivers/virtio/transport/mmio.rs | 6 +++--- src/drivers/virtio/virtqueue/mod.rs | 21 +++++++++++---------- src/drivers/virtio/virtqueue/packed.rs | 4 ++-- src/drivers/virtio/virtqueue/split.rs | 2 +- src/fd/mod.rs | 5 +++-- src/lib.rs | 1 + src/scheduler/mod.rs | 3 ++- src/syscalls/interfaces/uhyve.rs | 6 +++--- 16 files changed, 40 insertions(+), 36 deletions(-) diff --git a/src/arch/aarch64/kernel/mod.rs b/src/arch/aarch64/kernel/mod.rs index dd20cc063a..018fdd1677 100644 --- a/src/arch/aarch64/kernel/mod.rs +++ b/src/arch/aarch64/kernel/mod.rs @@ -13,8 +13,8 @@ pub mod switch; pub mod systemtime; use core::arch::global_asm; -use core::str; use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use core::{ptr, str}; use hermit_entry::boot_info::{BootInfo, RawBootInfo}; @@ -52,7 +52,7 @@ pub fn raw_boot_info() -> &'static RawBootInfo { } pub fn get_boot_info_address() -> VirtAddr { - VirtAddr(raw_boot_info() as *const _ as u64) + VirtAddr(ptr::from_ref(raw_boot_info()).addr() as u64) } pub fn is_uhyve_with_pci() -> bool { diff --git a/src/arch/aarch64/kernel/switch.rs b/src/arch/aarch64/kernel/switch.rs index 662c005815..b59dd87569 100644 --- a/src/arch/aarch64/kernel/switch.rs +++ b/src/arch/aarch64/kernel/switch.rs @@ -15,7 +15,7 @@ macro_rules! kernel_function_impl { let mut reg = 0_usize; // SAFETY: $A is smaller than usize and directly fits in a register // Since f takes $A as argument via C calling convention, any opper bytes do not matter. - ptr::write(&mut reg as *mut _ as _, $arg); + ptr::write(ptr::from_mut(&mut reg) as _, $arg); reg }; )* diff --git a/src/arch/aarch64/mm/paging.rs b/src/arch/aarch64/mm/paging.rs index ea0a2c34b6..09a86c082f 100644 --- a/src/arch/aarch64/mm/paging.rs +++ b/src/arch/aarch64/mm/paging.rs @@ -517,7 +517,7 @@ where // Calculate the address of the subtable. let index = page.table_index::(); - let table_address = self as *const PageTable as usize; + let table_address = core::ptr::from_ref(self).addr(); let subtable_address = (table_address << PAGE_MAP_BITS) & !(usize::MAX << 48) | (index << PAGE_BITS); unsafe { &mut *(subtable_address as *mut PageTable) } diff --git a/src/arch/x86_64/kernel/acpi.rs b/src/arch/x86_64/kernel/acpi.rs index 6469c5e440..eb634ec4c1 100644 --- a/src/arch/x86_64/kernel/acpi.rs +++ b/src/arch/x86_64/kernel/acpi.rs @@ -140,7 +140,7 @@ impl<'a> AcpiTable<'a> { } pub fn header_start_address(&self) -> usize { - self.header as *const _ as usize + ptr::from_ref(self.header).addr() } pub fn table_start_address(&self) -> usize { @@ -395,7 +395,7 @@ fn parse_fadt(fadt: AcpiTable<'_>) { // In that case, it shall be preferred over the I/O port specified in pm1a_cnt_blk. // As all PM1 control registers are supposed to be in I/O space, we can simply check the address_space field // of x_pm1a_cnt_blk to determine the validity of x_pm1a_cnt_blk. - let x_pm1a_cnt_blk_field_address = &fadt_table.x_pm1a_cnt_blk as *const _ as usize; + let x_pm1a_cnt_blk_field_address = ptr::from_ref(&fadt_table.x_pm1a_cnt_blk).addr(); let pm1a_cnt_blk = if x_pm1a_cnt_blk_field_address < fadt.table_end_address() && fadt_table.x_pm1a_cnt_blk.address_space == GENERIC_ADDRESS_IO_SPACE { diff --git a/src/arch/x86_64/kernel/apic.rs b/src/arch/x86_64/kernel/apic.rs index 78b0a48198..f86f28888e 100644 --- a/src/arch/x86_64/kernel/apic.rs +++ b/src/arch/x86_64/kernel/apic.rs @@ -729,7 +729,7 @@ pub fn boot_application_processors() { ); ptr::write_unaligned( (SMP_BOOT_CODE_ADDRESS + SMP_BOOT_CODE_OFFSET_BOOTINFO).as_mut_ptr(), - raw_boot_info() as *const _ as u64, + ptr::from_ref(raw_boot_info()).addr() as u64, ); } diff --git a/src/arch/x86_64/kernel/processor.rs b/src/arch/x86_64/kernel/processor.rs index d1de318a70..742a360d2c 100644 --- a/src/arch/x86_64/kernel/processor.rs +++ b/src/arch/x86_64/kernel/processor.rs @@ -8,7 +8,7 @@ use core::convert::Infallible; use core::hint::spin_loop; use core::num::NonZeroU32; use core::sync::atomic::{AtomicU64, Ordering}; -use core::{fmt, u32}; +use core::{fmt, ptr, u32}; use hermit_entry::boot_info::PlatformInfo; use hermit_sync::Lazy; @@ -221,7 +221,7 @@ impl FPUState { pub fn restore(&self) { if supports_xsave() { unsafe { - _xrstor(self as *const _ as _, u64::MAX); + _xrstor(ptr::from_ref(self) as _, u64::MAX); } } else { self.restore_common(); @@ -231,7 +231,7 @@ impl FPUState { pub fn save(&mut self) { if supports_xsave() { unsafe { - _xsave(self as *mut _ as _, u64::MAX); + _xsave(ptr::from_mut(self) as _, u64::MAX); } } else { self.save_common(); @@ -240,13 +240,13 @@ impl FPUState { pub fn restore_common(&self) { unsafe { - _fxrstor(self as *const _ as _); + _fxrstor(ptr::from_ref(self) as _); } } pub fn save_common(&mut self) { unsafe { - _fxsave(self as *mut _ as _); + _fxsave(ptr::from_mut(self) as _); asm!("fnclex", options(nomem, nostack)); } } diff --git a/src/arch/x86_64/kernel/scheduler.rs b/src/arch/x86_64/kernel/scheduler.rs index 10fb48708b..10d4de1d80 100644 --- a/src/arch/x86_64/kernel/scheduler.rs +++ b/src/arch/x86_64/kernel/scheduler.rs @@ -342,7 +342,7 @@ impl TaskFrame for Task { ptr::write_bytes(stack.as_mut_ptr::(), 0, mem::size_of::()); if let Some(tls) = &self.tls { - (*state).fs = tls.thread_ptr() as *const _ as u64; + (*state).fs = ptr::from_ref(tls.thread_ptr()).addr() as u64; } (*state).rip = task_start as usize as u64; (*state).rdi = func as usize as u64; diff --git a/src/arch/x86_64/kernel/switch.rs b/src/arch/x86_64/kernel/switch.rs index 0b6294cb4a..eb9b19f7f5 100644 --- a/src/arch/x86_64/kernel/switch.rs +++ b/src/arch/x86_64/kernel/switch.rs @@ -166,7 +166,7 @@ macro_rules! kernel_function_impl { let mut reg = 0_usize; // SAFETY: $A is smaller than usize and directly fits in a register // Since f takes $A as argument via C calling convention, any opper bytes do not matter. - ptr::write(&mut reg as *mut _ as _, $arg); + ptr::write(ptr::from_mut(&mut reg) as _, $arg); reg }; )* diff --git a/src/drivers/virtio/transport/mmio.rs b/src/drivers/virtio/transport/mmio.rs index 4dc4ec00b2..3c899cc980 100644 --- a/src/drivers/virtio/transport/mmio.rs +++ b/src/drivers/virtio/transport/mmio.rs @@ -8,7 +8,7 @@ use core::intrinsics::unaligned_volatile_store; use core::ptr::{read_volatile, write_volatile}; use core::result::Result; use core::sync::atomic::{fence, Ordering}; -use core::u8; +use core::{ptr, u8}; #[cfg(any(feature = "tcp", feature = "udp"))] use crate::arch::kernel::interrupts::*; @@ -251,7 +251,7 @@ pub struct NotifCfg { impl NotifCfg { pub fn new(registers: &mut MmioRegisterLayout) -> Self { - let raw = &mut registers.queue_notify as *mut u32; + let raw = ptr::from_mut(&mut registers.queue_notify); NotifCfg { queue_notify: raw } } @@ -332,7 +332,7 @@ pub struct IsrStatus { impl IsrStatus { pub fn new(registers: &mut MmioRegisterLayout) -> Self { - let ptr = &mut registers.interrupt_status as *mut _; + let ptr = ptr::from_mut(&mut registers.interrupt_status); let raw: &'static mut IsrStatusRaw = unsafe { &mut *(ptr as *mut IsrStatusRaw) }; IsrStatus { raw } diff --git a/src/drivers/virtio/virtqueue/mod.rs b/src/drivers/virtio/virtqueue/mod.rs index 1f55af7ae2..e65e8bc1e5 100644 --- a/src/drivers/virtio/virtqueue/mod.rs +++ b/src/drivers/virtio/virtqueue/mod.rs @@ -19,6 +19,7 @@ use alloc::rc::Rc; use alloc::vec::Vec; use core::cell::RefCell; use core::ops::{BitAnd, Deref, DerefMut}; +use core::ptr; use align_address::Align; use zerocopy::AsBytes; @@ -145,8 +146,8 @@ impl Virtq { pub fn check_bounds(data: &T) -> bool { let slice = data.as_slice_u8(); - let start_virt = (&slice[0] as *const u8) as usize; - let end_virt = (&slice[slice.len() - 1] as *const u8) as usize; + let start_virt = ptr::from_ref(slice.first().unwrap()).addr(); + let end_virt = ptr::from_ref(slice.last().unwrap()).addr(); let end_phy_calc = paging::virt_to_phys(VirtAddr::from(start_virt)) + (slice.len() - 1); let end_phy = paging::virt_to_phys(VirtAddr::from(end_virt)); @@ -165,8 +166,8 @@ impl Virtq { /// Slices provided to the Queue must pass this test, otherwise the queue /// currently panics. pub fn check_bounds_slice(slice: &[u8]) -> bool { - let start_virt = (&slice[0] as *const u8) as usize; - let end_virt = (&slice[slice.len() - 1] as *const u8) as usize; + let start_virt = ptr::from_ref(slice.first().unwrap()).addr(); + let end_virt = ptr::from_ref(slice.last().unwrap()).addr(); let end_phy_calc = paging::virt_to_phys(VirtAddr::from(start_virt)) + (slice.len() - 1); let end_phy = paging::virt_to_phys(VirtAddr::from(end_virt)); @@ -547,7 +548,7 @@ pub trait AsSliceU8 { /// * The slice must serialize the actual structure the device expects, as the queue will use /// the addresses of the slice in order to refer to the structure. fn as_slice_u8(&self) -> &[u8] { - unsafe { core::slice::from_raw_parts((self as *const _) as *const u8, self.len()) } + unsafe { core::slice::from_raw_parts(ptr::from_ref(self) as *const u8, self.len()) } } /// Returns a mutable slice of the given structure. @@ -557,7 +558,7 @@ pub trait AsSliceU8 { /// * The slice must serialize the actual structure the device expects, as the queue will use /// the addresses of the slice in order to refer to the structure. fn as_slice_u8_mut(&mut self) -> &mut [u8] { - unsafe { core::slice::from_raw_parts_mut((self as *const _) as *mut u8, self.len()) } + unsafe { core::slice::from_raw_parts_mut(ptr::from_mut(self) as *mut u8, self.len()) } } } @@ -2189,8 +2190,8 @@ impl MemPool { assert!(!slice.is_empty()); // Assert descriptor does not cross a page barrier - let start_virt = (&slice[0] as *const u8) as usize; - let end_virt = (&slice[slice.len() - 1] as *const u8) as usize; + let start_virt = ptr::from_ref(slice.first().unwrap()).addr(); + let end_virt = ptr::from_ref(slice.last().unwrap()).addr(); let end_phy_calc = paging::virt_to_phys(VirtAddr::from(start_virt)) + (slice.len() - 1); let end_phy = paging::virt_to_phys(VirtAddr::from(end_virt)); @@ -2231,8 +2232,8 @@ impl MemPool { assert!(!slice.is_empty()); // Assert descriptor does not cross a page barrier - let start_virt = (&slice[0] as *const u8) as usize; - let end_virt = (&slice[slice.len() - 1] as *const u8) as usize; + let start_virt = ptr::from_ref(slice.first().unwrap()).addr(); + let end_virt = ptr::from_ref(slice.last().unwrap()).addr(); let end_phy_calc = paging::virt_to_phys(VirtAddr::from(start_virt)) + (slice.len() - 1); let end_phy = paging::virt_to_phys(VirtAddr::from(end_virt)); diff --git a/src/drivers/virtio/virtqueue/packed.rs b/src/drivers/virtio/virtqueue/packed.rs index 736f3453b6..121da5a1d7 100644 --- a/src/drivers/virtio/virtqueue/packed.rs +++ b/src/drivers/virtio/virtqueue/packed.rs @@ -150,7 +150,7 @@ impl DescriptorRing { // Turn the raw pointer into a Pinned again, which will hold ownership of the Token queue.borrow_mut().push_back(Transfer { - transfer_tkn: Some(Pinned::from_raw(tkn as *mut TransferToken)), + transfer_tkn: Some(Pinned::from_raw(ptr::from_mut(tkn))), }); } None => tkn.state = TransferState::Finished, @@ -542,7 +542,7 @@ impl<'a> ReadCtrl<'a> { (None, None) => unreachable!("Empty Transfers are not allowed..."), } - Some(tkn as *mut TransferToken) + Some(ptr::from_mut(tkn)) } else { None } diff --git a/src/drivers/virtio/virtqueue/split.rs b/src/drivers/virtio/virtqueue/split.rs index 308d72e307..9655c0168d 100644 --- a/src/drivers/virtio/virtqueue/split.rs +++ b/src/drivers/virtio/virtqueue/split.rs @@ -220,7 +220,7 @@ impl DescrRing { // Turn the raw pointer into a Pinned again, which will hold ownership of the Token queue.borrow_mut().push_back(Transfer { - transfer_tkn: Some(Pinned::from_raw(tkn as *mut TransferToken)), + transfer_tkn: Some(Pinned::from_raw(ptr::from_mut(tkn))), }); } None => tkn.state = TransferState::Finished, diff --git a/src/fd/mod.rs b/src/fd/mod.rs index 3632b1fab4..4c329a980d 100644 --- a/src/fd/mod.rs +++ b/src/fd/mod.rs @@ -1,5 +1,6 @@ use alloc::sync::Arc; use core::ffi::{c_void, CStr}; +use core::ptr; use core::sync::atomic::{AtomicI32, Ordering}; use ahash::RandomState; @@ -136,7 +137,7 @@ impl SysLseek { #[inline] #[cfg(target_arch = "x86_64")] fn uhyve_send(port: u16, data: &mut T) { - let ptr = VirtAddr(data as *mut _ as u64); + let ptr = VirtAddr(ptr::from_mut(data).addr() as u64); let physical_address = paging::virtual_to_physical(ptr).unwrap(); unsafe { @@ -150,7 +151,7 @@ fn uhyve_send(port: u16, data: &mut T) { fn uhyve_send(port: u16, data: &mut T) { use core::arch::asm; - let ptr = VirtAddr(data as *mut _ as u64); + let ptr = VirtAddr(ptr::from_mut(data).addr() as u64); let physical_address = paging::virtual_to_physical(ptr).unwrap(); unsafe { diff --git a/src/lib.rs b/src/lib.rs index ca374b651c..c6a9e2b4ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,7 @@ #![feature(noop_waker)] #![feature(pointer_byte_offsets)] #![feature(pointer_is_aligned)] +#![feature(ptr_from_ref)] #![cfg_attr(target_arch = "aarch64", feature(specialization))] #![feature(strict_provenance)] #![cfg_attr(target_os = "none", no_std)] diff --git a/src/scheduler/mod.rs b/src/scheduler/mod.rs index b939d08e0e..65432edf03 100644 --- a/src/scheduler/mod.rs +++ b/src/scheduler/mod.rs @@ -4,6 +4,7 @@ use alloc::rc::Rc; #[cfg(feature = "smp")] use alloc::vec::Vec; use core::cell::RefCell; +use core::ptr; use core::sync::atomic::{AtomicU32, Ordering}; use crossbeam_utils::Backoff; @@ -583,7 +584,7 @@ impl PerCoreScheduler { let mut borrowed = self.current_task.borrow_mut(); ( borrowed.id, - &mut borrowed.last_stack_pointer as *mut _ as *mut usize, + ptr::from_mut(&mut borrowed.last_stack_pointer) as *mut usize, borrowed.prio, borrowed.status, ) diff --git a/src/syscalls/interfaces/uhyve.rs b/src/syscalls/interfaces/uhyve.rs index 3efd3e9a48..2b0725fcc5 100644 --- a/src/syscalls/interfaces/uhyve.rs +++ b/src/syscalls/interfaces/uhyve.rs @@ -1,7 +1,7 @@ use alloc::alloc::{alloc, Layout}; use alloc::boxed::Box; use alloc::vec::Vec; -use core::mem; +use core::{mem, ptr}; #[cfg(target_arch = "x86_64")] use x86::io::*; @@ -29,7 +29,7 @@ extern "C" { #[inline] #[cfg(target_arch = "x86_64")] pub(crate) fn uhyve_send(port: u16, data: &mut T) { - let ptr = VirtAddr(data as *mut _ as u64); + let ptr = VirtAddr(ptr::from_mut(data).addr() as u64); let physical_address = paging::virtual_to_physical(ptr).unwrap(); unsafe { @@ -43,7 +43,7 @@ pub(crate) fn uhyve_send(port: u16, data: &mut T) { pub(crate) fn uhyve_send(port: u16, data: &mut T) { use core::arch::asm; - let ptr = VirtAddr(data as *mut _ as u64); + let ptr = VirtAddr(ptr::from_mut(data).addr() as u64); let physical_address = paging::virtual_to_physical(ptr).unwrap(); unsafe { From 4c677ad453ca9e043979c8fd87485078a78d14f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 17:54:45 +0200 Subject: [PATCH 3/9] use appropriate null pointer constructor instead of casting --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c6a9e2b4ac..75f7bb5b12 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,7 +137,7 @@ pub(crate) extern "C" fn __sys_malloc(size: usize, align: usize) -> *mut u8 { "__sys_malloc called with size {:#x}, align {:#x} is an invalid layout!", size, align ); - return core::ptr::null::<*mut u8>() as *mut u8; + return core::ptr::null_mut(); } let layout = layout_res.unwrap(); let ptr = unsafe { ALLOCATOR.alloc(layout) }; @@ -185,7 +185,7 @@ pub(crate) extern "C" fn __sys_realloc( "__sys_realloc called with ptr {:p}, size {:#x}, align {:#x}, new_size {:#x} is an invalid layout!", ptr, size, align, new_size ); - return core::ptr::null::<*mut u8>() as *mut u8; + return core::ptr::null_mut(); } let layout = layout_res.unwrap(); let new_ptr = ALLOCATOR.realloc(ptr, layout, new_size); From 8cb6cc153c050c78cf0b4f98ec8306013b4afd01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 17:56:06 +0200 Subject: [PATCH 4/9] fix typo --- src/arch/aarch64/kernel/pci.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/arch/aarch64/kernel/pci.rs b/src/arch/aarch64/kernel/pci.rs index 20835cd1ba..4c6695e66e 100644 --- a/src/arch/aarch64/kernel/pci.rs +++ b/src/arch/aarch64/kernel/pci.rs @@ -22,7 +22,7 @@ pub(crate) struct PciConfigRegion(VirtAddr); impl PciConfigRegion { pub const fn new(addr: VirtAddr) -> Self { - assert!(addr.as_u64() & 0xFFFFFFF == 0, "Unaligend PCI Config Space"); + assert!(addr.as_u64() & 0xFFFFFFF == 0, "Unaligned PCI Config Space"); Self(addr) } } From ae3d7b83321f4f829fb19be4c590dfac064e59f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 18:20:26 +0200 Subject: [PATCH 5/9] use as_ptr on slices instead of casting --- src/drivers/virtio/virtqueue/mod.rs | 4 ++-- src/mm/allocator.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/drivers/virtio/virtqueue/mod.rs b/src/drivers/virtio/virtqueue/mod.rs index e65e8bc1e5..eb6d36f60e 100644 --- a/src/drivers/virtio/virtqueue/mod.rs +++ b/src/drivers/virtio/virtqueue/mod.rs @@ -2203,7 +2203,7 @@ impl MemPool { }; Ok(MemDescr { - ptr: (&slice[0] as *const u8) as *mut u8, + ptr: slice.as_ptr() as *mut _, len: slice.len(), _init_len: slice.len(), _mem_len: slice.len(), @@ -2240,7 +2240,7 @@ impl MemPool { assert_eq!(end_phy, end_phy_calc); MemDescr { - ptr: (&slice[0] as *const u8) as *mut u8, + ptr: slice.as_ptr() as *mut _, len: slice.len(), _init_len: slice.len(), _mem_len: slice.len(), diff --git a/src/mm/allocator.rs b/src/mm/allocator.rs index 236b5677ad..dbe1d8d419 100644 --- a/src/mm/allocator.rs +++ b/src/mm/allocator.rs @@ -59,7 +59,7 @@ mod tests { let mut arena: [u8; ARENA_SIZE] = [0; ARENA_SIZE]; let allocator: LockedAllocator = LockedAllocator::new(); unsafe { - allocator.init(&mut arena as *mut [u8] as *mut u8, ARENA_SIZE); + allocator.init(arena.as_mut_ptr(), ARENA_SIZE); } let layout = Layout::from_size_align(1, 1).unwrap(); From eff46b59172a1e136ffb919deed7c42e577b2b1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 18:26:59 +0200 Subject: [PATCH 6/9] remove redundant cast --- src/drivers/virtio/virtqueue/split.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/drivers/virtio/virtqueue/split.rs b/src/drivers/virtio/virtqueue/split.rs index 9655c0168d..9e94e57c25 100644 --- a/src/drivers/virtio/virtqueue/split.rs +++ b/src/drivers/virtio/virtqueue/split.rs @@ -429,7 +429,7 @@ impl SplitVq { flags: &mut *(used_raw as *mut u16), index: used_raw.offset(2) as *mut u16, ring: core::slice::from_raw_parts_mut( - (used_raw.offset(4) as *const _) as *mut UsedElem, + used_raw.offset(4) as *mut UsedElem, size as usize, ), event: &mut *(used_raw.offset(4 + 8 * (size as isize)) as *mut u16), From 2497095652629c1c5e5defde0773744d2544ed11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 18:27:34 +0200 Subject: [PATCH 7/9] use slice::from_ptr_range instead of length calc --- src/arch/x86_64/kernel/acpi.rs | 6 +++--- src/lib.rs | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/arch/x86_64/kernel/acpi.rs b/src/arch/x86_64/kernel/acpi.rs index eb634ec4c1..569b655732 100644 --- a/src/arch/x86_64/kernel/acpi.rs +++ b/src/arch/x86_64/kernel/acpi.rs @@ -338,9 +338,9 @@ fn search_s5_in_table(table: AcpiTable<'_>) { // Get the AML code. // As we do not implement an AML interpreter, we search through the bytecode. let aml = unsafe { - slice::from_raw_parts( - table.table_start_address() as *const u8, - table.table_end_address() - table.table_start_address(), + slice::from_ptr_range( + ptr::from_exposed_addr(table.table_start_address()) + ..ptr::from_exposed_addr(table.table_end_address()), ) }; diff --git a/src/lib.rs b/src/lib.rs index 75f7bb5b12..e8c00d5fec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ #![feature(pointer_byte_offsets)] #![feature(pointer_is_aligned)] #![feature(ptr_from_ref)] +#![feature(slice_from_ptr_range)] #![cfg_attr(target_arch = "aarch64", feature(specialization))] #![feature(strict_provenance)] #![cfg_attr(target_os = "none", no_std)] From c52b9fb754a016e39a116c3bc977b49c56e4c179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 18:30:00 +0200 Subject: [PATCH 8/9] factor common PCI-e address calculation out --- src/arch/aarch64/kernel/pci.rs | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/arch/aarch64/kernel/pci.rs b/src/arch/aarch64/kernel/pci.rs index 4c6695e66e..b4e0ba3062 100644 --- a/src/arch/aarch64/kernel/pci.rs +++ b/src/arch/aarch64/kernel/pci.rs @@ -25,6 +25,16 @@ impl PciConfigRegion { assert!(addr.as_u64() & 0xFFFFFFF == 0, "Unaligned PCI Config Space"); Self(addr) } + + #[inline] + fn addr_from_offset(&self, pci_addr: PciAddress, offset: u16) -> usize { + assert!(offset & 0xF000 == 0, "Invalid offset"); + (u64::from(pci_addr.bus()) << 20 + | u64::from(pci_addr.device()) << 15 + | u64::from(pci_addr.function()) << 12 + | (u64::from(offset) & 0xFFF) + | self.0.as_u64()) as usize + } } impl ConfigRegionAccess for PciConfigRegion { @@ -36,27 +46,15 @@ impl ConfigRegionAccess for PciConfigRegion { #[inline] unsafe fn read(&self, pci_addr: PciAddress, offset: u16) -> u32 { - assert!(offset & 0xF000 == 0, "Inavlid offset"); - let addr = u64::from(pci_addr.bus()) << 20 - | u64::from(pci_addr.device()) << 15 - | u64::from(pci_addr.function()) << 12 - | (u64::from(offset) & 0xFFF) - | self.0.as_u64(); - unsafe { - crate::drivers::pci::from_pci_endian(core::ptr::read_volatile(addr as *const u32)) - } + let ptr = core::ptr::from_exposed_addr(self.addr_from_offset(pci_addr, offset)); + unsafe { crate::drivers::pci::from_pci_endian(core::ptr::read_volatile(ptr)) } } #[inline] unsafe fn write(&self, pci_addr: PciAddress, offset: u16, value: u32) { - assert!(offset & 0xF000 == 0, "Inavlid offset"); - let addr = u64::from(pci_addr.bus()) << 20 - | u64::from(pci_addr.device()) << 15 - | u64::from(pci_addr.function()) << 12 - | (u64::from(offset) & 0xFFF) - | self.0.as_u64(); + let ptr = core::ptr::from_exposed_addr_mut(self.addr_from_offset(pci_addr, offset)); unsafe { - core::ptr::write_volatile(addr as *mut u32, value.to_le()); + core::ptr::write_volatile(ptr, value.to_le()); } } } From 614c41c2d6d81318846352c4a84fd45bb86d3290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9Fatay=20Yi=C4=9Fit=20=C5=9Eahin?= Date: Tue, 24 Oct 2023 18:31:32 +0200 Subject: [PATCH 9/9] use from_exposed_addr instead of casting Using this function makes it clear that the casted object is an exposed address, rather than a reference or another pointer. --- src/arch/aarch64/kernel/interrupts.rs | 7 +++++-- src/arch/aarch64/kernel/mod.rs | 6 ++++-- src/arch/aarch64/kernel/pci.rs | 6 ++++-- src/arch/aarch64/kernel/processor.rs | 6 ++++-- src/arch/aarch64/kernel/serial.rs | 2 +- src/arch/aarch64/kernel/systemtime.rs | 6 ++++-- src/arch/aarch64/mm/paging.rs | 2 +- src/arch/x86_64/kernel/acpi.rs | 16 ++++++++++------ src/arch/x86_64/kernel/apic.rs | 25 +++++++++++++------------ src/arch/x86_64/kernel/mmio.rs | 8 ++++---- src/drivers/net/virtio_mmio.rs | 3 ++- src/drivers/virtio/transport/pci.rs | 13 +++++++------ src/drivers/virtio/virtqueue/mod.rs | 4 ++-- src/drivers/virtio/virtqueue/packed.rs | 14 +++++++------- src/drivers/virtio/virtqueue/split.rs | 17 +++++++++-------- src/syscalls/condvar.rs | 20 ++++++++++---------- src/syscalls/interfaces/uhyve.rs | 12 ++++++------ 17 files changed, 93 insertions(+), 74 deletions(-) diff --git a/src/arch/aarch64/kernel/interrupts.rs b/src/arch/aarch64/kernel/interrupts.rs index 683d3dc7b3..29e092aa10 100644 --- a/src/arch/aarch64/kernel/interrupts.rs +++ b/src/arch/aarch64/kernel/interrupts.rs @@ -1,6 +1,7 @@ use alloc::collections::BTreeMap; use alloc::vec::Vec; use core::arch::asm; +use core::ptr; use core::sync::atomic::{AtomicU64, Ordering}; use aarch64::regs::*; @@ -231,8 +232,10 @@ pub(crate) fn init() { info!("Intialize generic interrupt controller"); let dtb = unsafe { - Dtb::from_raw(boot_info().hardware_info.device_tree.unwrap().get() as *const u8) - .expect(".dtb file has invalid header") + Dtb::from_raw(ptr::from_exposed_addr( + boot_info().hardware_info.device_tree.unwrap().get() as usize, + )) + .expect(".dtb file has invalid header") }; let reg = dtb.get_property("/intc", "reg").unwrap(); diff --git a/src/arch/aarch64/kernel/mod.rs b/src/arch/aarch64/kernel/mod.rs index 018fdd1677..4399c3fd78 100644 --- a/src/arch/aarch64/kernel/mod.rs +++ b/src/arch/aarch64/kernel/mod.rs @@ -93,8 +93,10 @@ pub fn get_processor_count() -> u32 { pub fn args() -> Option<&'static str> { let dtb = unsafe { - hermit_dtb::Dtb::from_raw(boot_info().hardware_info.device_tree.unwrap().get() as *const u8) - .expect(".dtb file has invalid header") + hermit_dtb::Dtb::from_raw(ptr::from_exposed_addr( + boot_info().hardware_info.device_tree.unwrap().get() as usize, + )) + .expect(".dtb file has invalid header") }; dtb.get_property("/chosen", "bootargs") diff --git a/src/arch/aarch64/kernel/pci.rs b/src/arch/aarch64/kernel/pci.rs index b4e0ba3062..c8945ae0ac 100644 --- a/src/arch/aarch64/kernel/pci.rs +++ b/src/arch/aarch64/kernel/pci.rs @@ -228,8 +228,10 @@ fn detect_interrupt( pub fn init() { let dtb = unsafe { - Dtb::from_raw(boot_info().hardware_info.device_tree.unwrap().get() as *const u8) - .expect(".dtb file has invalid header") + Dtb::from_raw(core::ptr::from_exposed_addr( + boot_info().hardware_info.device_tree.unwrap().get() as usize, + )) + .expect(".dtb file has invalid header") }; for node in dtb.enum_subnodes("/") { diff --git a/src/arch/aarch64/kernel/processor.rs b/src/arch/aarch64/kernel/processor.rs index 2a0999639a..d204614f6f 100644 --- a/src/arch/aarch64/kernel/processor.rs +++ b/src/arch/aarch64/kernel/processor.rs @@ -244,8 +244,10 @@ pub fn set_oneshot_timer(wakeup_time: Option) { pub fn print_information() { let dtb = unsafe { - Dtb::from_raw(boot_info().hardware_info.device_tree.unwrap().get() as *const u8) - .expect(".dtb file has invalid header") + Dtb::from_raw(core::ptr::from_exposed_addr( + boot_info().hardware_info.device_tree.unwrap().get() as usize, + )) + .expect(".dtb file has invalid header") }; let reg = dtb diff --git a/src/arch/aarch64/kernel/serial.rs b/src/arch/aarch64/kernel/serial.rs index 72095f02a5..0c13f4db15 100644 --- a/src/arch/aarch64/kernel/serial.rs +++ b/src/arch/aarch64/kernel/serial.rs @@ -10,7 +10,7 @@ impl SerialPort { } pub fn write_byte(&self, byte: u8) { - let port = self.port_address as *mut u8; + let port = core::ptr::from_exposed_addr_mut::(self.port_address as usize); // LF newline characters need to be extended to CRLF over a real serial port. if byte == b'\n' { diff --git a/src/arch/aarch64/kernel/systemtime.rs b/src/arch/aarch64/kernel/systemtime.rs index a1c43ea4f2..68bc4fac81 100644 --- a/src/arch/aarch64/kernel/systemtime.rs +++ b/src/arch/aarch64/kernel/systemtime.rs @@ -50,8 +50,10 @@ pub fn get_boot_time() -> u64 { pub fn init() { let dtb = unsafe { - Dtb::from_raw(boot_info().hardware_info.device_tree.unwrap().get() as *const u8) - .expect(".dtb file has invalid header") + Dtb::from_raw(core::ptr::from_exposed_addr( + boot_info().hardware_info.device_tree.unwrap().get() as usize, + )) + .expect(".dtb file has invalid header") }; for node in dtb.enum_subnodes("/") { diff --git a/src/arch/aarch64/mm/paging.rs b/src/arch/aarch64/mm/paging.rs index 09a86c082f..90b09a647f 100644 --- a/src/arch/aarch64/mm/paging.rs +++ b/src/arch/aarch64/mm/paging.rs @@ -520,7 +520,7 @@ where let table_address = core::ptr::from_ref(self).addr(); let subtable_address = (table_address << PAGE_MAP_BITS) & !(usize::MAX << 48) | (index << PAGE_BITS); - unsafe { &mut *(subtable_address as *mut PageTable) } + unsafe { &mut *(ptr::from_exposed_addr_mut(subtable_address)) } } /// Maps a continuous range of pages. diff --git a/src/arch/x86_64/kernel/acpi.rs b/src/arch/x86_64/kernel/acpi.rs index 569b655732..b1df202352 100644 --- a/src/arch/x86_64/kernel/acpi.rs +++ b/src/arch/x86_64/kernel/acpi.rs @@ -237,7 +237,7 @@ struct AcpiFadt { /// (wrapping) sum over all table fields equals zero. fn verify_checksum(start_address: usize, length: usize) -> Result<(), ()> { // Get a slice over all bytes of the structure that are considered for the checksum. - let slice = unsafe { slice::from_raw_parts(start_address as *const u8, length) }; + let slice = unsafe { slice::from_raw_parts(ptr::from_exposed_addr(start_address), length) }; // Perform a wrapping sum over these bytes. let checksum = slice.iter().fold(0, |acc: u8, x| acc.wrapping_add(*x)); @@ -269,7 +269,7 @@ fn detect_rsdp(start_address: PhysAddr, end_address: PhysAddr) -> Result<&'stati } // Verify the signature to find out if this is really an ACPI RSDP. - let rsdp = unsafe { &*(current_address as *const AcpiRsdp) }; + let rsdp = unsafe { &*(ptr::from_exposed_addr::(current_address)) }; if &rsdp.signature != b"RSD PTR " { continue; } @@ -389,7 +389,7 @@ fn parse_fadt(fadt: AcpiTable<'_>) { // Get us a reference to the actual fields of the FADT table. // Note that not all fields may be accessible depending on the ACPI revision of the computer. // Always check fadt.table_end_address() when accessing an optional field! - let fadt_table = unsafe { &*(fadt.table_start_address() as *const AcpiFadt) }; + let fadt_table = unsafe { &*ptr::from_exposed_addr::(fadt.table_start_address()) }; // Check if the FADT is large enough to hold an x_pm1a_cnt_blk field and if this field is non-zero. // In that case, it shall be preferred over the I/O port specified in pm1a_cnt_blk. @@ -485,12 +485,16 @@ pub fn init() { // Depending on the RSDP revision, either an XSDT or an RSDT has been chosen above. // The XSDT contains 64-bit pointers whereas the RSDT has 32-bit pointers. let table_physical_address = if rsdp.revision >= 2 { - let address = PhysAddr(unsafe { ptr::read_unaligned(current_address as *const u64) }); + let address = PhysAddr(unsafe { + ptr::read_unaligned(ptr::from_exposed_addr::(current_address)) + }); current_address += mem::size_of::(); address } else { - let address = - PhysAddr((unsafe { ptr::read_unaligned(current_address as *const u32) }).into()); + let address = PhysAddr( + (unsafe { ptr::read_unaligned(ptr::from_exposed_addr::(current_address)) }) + .into(), + ); current_address += mem::size_of::(); address }; diff --git a/src/arch/x86_64/kernel/apic.rs b/src/arch/x86_64/kernel/apic.rs index f86f28888e..367b51d21b 100644 --- a/src/arch/x86_64/kernel/apic.rs +++ b/src/arch/x86_64/kernel/apic.rs @@ -2,10 +2,8 @@ use alloc::vec::Vec; #[cfg(feature = "smp")] use core::arch::x86_64::_mm_mfence; use core::hint::spin_loop; -#[cfg(feature = "smp")] -use core::ptr; use core::sync::atomic::Ordering; -use core::{cmp, fmt, mem, u32}; +use core::{cmp, fmt, mem, ptr, u32}; use align_address::Align; #[cfg(feature = "smp")] @@ -267,21 +265,23 @@ fn detect_from_acpi() -> Result { fn detect_from_acpi() -> Result { // Get the Multiple APIC Description Table (MADT) from the ACPI information and its specific table header. let madt = acpi::get_madt().ok_or(())?; - let madt_header = unsafe { &*(madt.table_start_address() as *const AcpiMadtHeader) }; + let madt_header = + unsafe { &*(ptr::from_exposed_addr::(madt.table_start_address())) }; // Jump to the actual table entries (after the table header). let mut current_address = madt.table_start_address() + mem::size_of::(); // Loop through all table entries. while current_address < madt.table_end_address() { - let record = unsafe { &*(current_address as *const AcpiMadtRecordHeader) }; + let record = unsafe { &*(ptr::from_exposed_addr::(current_address)) }; current_address += mem::size_of::(); match record.entry_type { 0 => { // Processor Local APIC - let processor_local_apic_record = - unsafe { &*(current_address as *const ProcessorLocalApicRecord) }; + let processor_local_apic_record = unsafe { + &*(ptr::from_exposed_addr::(current_address)) + }; debug!( "Found Processor Local APIC record: {}", processor_local_apic_record @@ -293,7 +293,8 @@ fn detect_from_acpi() -> Result { } 1 => { // I/O APIC - let ioapic_record = unsafe { &*(current_address as *const IoApicRecord) }; + let ioapic_record = + unsafe { &*(ptr::from_exposed_addr::(current_address)) }; debug!("Found I/O APIC record: {}", ioapic_record); init_ioapic_address(PhysAddr(ioapic_record.address.into())); @@ -379,7 +380,7 @@ fn detect_from_mp() -> Result { let mut addr: usize = virtual_address.as_usize() | (mp_float.mp_config as usize & (BasePageSize::SIZE as usize - 1)); - let mp_config: &ApicConfigTable = unsafe { &*(addr as *const ApicConfigTable) }; + let mp_config: &ApicConfigTable = unsafe { &*(ptr::from_exposed_addr(addr)) }; if mp_config.signature != MP_CONFIG_SIGNATURE { warn!("Invalid MP config table"); virtualmem::deallocate(virtual_address, BasePageSize::SIZE as usize); @@ -395,11 +396,11 @@ fn detect_from_mp() -> Result { // entries starts directly after the config table addr += mem::size_of::(); for _i in 0..mp_config.entry_count { - match unsafe { *(addr as *const u8) } { + match unsafe { *(ptr::from_exposed_addr(addr)) } { // CPU entry 0 => { let cpu_entry: &ApicProcessorEntry = - unsafe { &*(addr as *const ApicProcessorEntry) }; + unsafe { &*(ptr::from_exposed_addr(addr)) }; if cpu_entry.cpu_flags & 0x01 == 0x01 { add_local_apic_id(cpu_entry.id); } @@ -407,7 +408,7 @@ fn detect_from_mp() -> Result { } // IO-APIC entry 2 => { - let io_entry: &ApicIoEntry = unsafe { &*(addr as *const ApicIoEntry) }; + let io_entry: &ApicIoEntry = unsafe { &*(ptr::from_exposed_addr(addr)) }; let ioapic = PhysAddr(io_entry.addr.into()); info!("Found IOAPIC at 0x{:p}", ioapic); diff --git a/src/arch/x86_64/kernel/mmio.rs b/src/arch/x86_64/kernel/mmio.rs index 4f6d4c98c2..4aa9fa9ba4 100644 --- a/src/arch/x86_64/kernel/mmio.rs +++ b/src/arch/x86_64/kernel/mmio.rs @@ -1,5 +1,5 @@ use alloc::vec::Vec; -use core::str; +use core::{ptr, str}; use align_address::Align; use hermit_sync::{without_interrupts, InterruptTicketMutex}; @@ -65,9 +65,9 @@ pub fn detect_network() -> Result<&'static mut MmioRegisterLayout, &'static str> // Verify the first register value to find out if this is really an MMIO magic-value. let mmio = unsafe { - &mut *((virtual_address.as_usize() - | (current_address & (BasePageSize::SIZE as usize - 1))) - as *mut MmioRegisterLayout) + &mut *(ptr::from_exposed_addr_mut::( + virtual_address.as_usize() | (current_address & (BasePageSize::SIZE as usize - 1)), + )) }; let magic = mmio.get_magic_value(); diff --git a/src/drivers/net/virtio_mmio.rs b/src/drivers/net/virtio_mmio.rs index 386309fa79..a954042965 100644 --- a/src/drivers/net/virtio_mmio.rs +++ b/src/drivers/net/virtio_mmio.rs @@ -6,6 +6,7 @@ use alloc::collections::VecDeque; use alloc::rc::Rc; use alloc::vec::Vec; use core::cell::RefCell; +use core::ptr; use core::ptr::read_volatile; use core::str::FromStr; use core::sync::atomic::{fence, Ordering}; @@ -115,7 +116,7 @@ impl VirtioNetDriver { irq: u8, ) -> Result { let dev_cfg_raw: &'static NetDevCfgRaw = - unsafe { &*(((registers as *const _ as usize) + 0xFC) as *const NetDevCfgRaw) }; + unsafe { &*(ptr::from_exposed_addr(ptr::from_ref(registers).addr() + 0xFC)) }; let dev_cfg = NetDevCfg { raw: dev_cfg_raw, dev_id, diff --git a/src/drivers/virtio/transport/pci.rs b/src/drivers/virtio/transport/pci.rs index d8df4e4648..d581ef6a8b 100644 --- a/src/drivers/virtio/transport/pci.rs +++ b/src/drivers/virtio/transport/pci.rs @@ -5,9 +5,9 @@ use alloc::vec::Vec; use core::intrinsics::unaligned_volatile_store; -use core::mem; use core::result::Result; use core::sync::atomic::{fence, Ordering}; +use core::{mem, ptr}; #[cfg(all(not(feature = "rtl8139"), any(feature = "tcp", feature = "udp")))] use crate::arch::kernel::interrupts::*; @@ -163,10 +163,11 @@ pub fn map_dev_cfg(cap: &PciCap) -> Option<&'static mut T> { return None; } - let virt_addr_raw: VirtMemAddr = cap.bar_addr() + cap.offset(); + let virt_addr_raw = cap.bar_addr() + cap.offset(); // Create mutable reference to the PCI structure in PCI memory - let dev_cfg: &'static mut T = unsafe { &mut *(usize::from(virt_addr_raw) as *mut T) }; + let dev_cfg: &'static mut T = + unsafe { &mut *(ptr::from_exposed_addr_mut(virt_addr_raw.into())) }; Some(dev_cfg) } @@ -623,7 +624,7 @@ impl ComCfgRaw { // Create mutable reference to the PCI structure in PCI memory let com_cfg_raw: &mut ComCfgRaw = - unsafe { &mut *(usize::from(virt_addr_raw) as *mut ComCfgRaw) }; + unsafe { &mut *(ptr::from_exposed_addr_mut(virt_addr_raw.into())) }; Some(com_cfg_raw) } @@ -816,7 +817,7 @@ impl IsrStatusRaw { // Create mutable reference to the PCI structure in the devices memory area let isr_stat_raw: &mut IsrStatusRaw = - unsafe { &mut *(usize::from(virt_addr_raw) as *mut IsrStatusRaw) }; + unsafe { &mut *(ptr::from_exposed_addr_mut(virt_addr_raw.into())) }; Some(isr_stat_raw) } @@ -925,7 +926,7 @@ impl ShMemCfg { MemLen::from((u64::from(length_high) << 32) ^ u64::from(cap.origin.cap_struct.length)); let virt_addr_raw = cap.bar.mem_addr + offset; - let raw_ptr = usize::from(virt_addr_raw) as *mut u8; + let raw_ptr = ptr::from_exposed_addr_mut::(virt_addr_raw.into()); // Zero initialize shared memory area unsafe { diff --git a/src/drivers/virtio/virtqueue/mod.rs b/src/drivers/virtio/virtqueue/mod.rs index eb6d36f60e..c234b50cd5 100644 --- a/src/drivers/virtio/virtqueue/mod.rs +++ b/src/drivers/virtio/virtqueue/mod.rs @@ -2272,7 +2272,7 @@ impl MemPool { // Allocate heap memory via a vec, leak and cast let _mem_len = len.align_up(BasePageSize::SIZE as usize); - let ptr = (crate::mm::allocate(_mem_len, true).0 as *const u8) as *mut u8; + let ptr = ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); // Assert descriptor does not cross a page barrier let start_virt = ptr as usize; @@ -2307,7 +2307,7 @@ impl MemPool { // Allocate heap memory via a vec, leak and cast let _mem_len = len.align_up(BasePageSize::SIZE as usize); - let ptr = (crate::mm::allocate(_mem_len, true).0 as *const u8) as *mut u8; + let ptr = ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); // Assert descriptor does not cross a page barrier let start_virt = ptr as usize; diff --git a/src/drivers/virtio/virtqueue/packed.rs b/src/drivers/virtio/virtqueue/packed.rs index 121da5a1d7..49680eb746 100644 --- a/src/drivers/virtio/virtqueue/packed.rs +++ b/src/drivers/virtio/virtqueue/packed.rs @@ -110,7 +110,7 @@ impl DescriptorRing { // Allocate heap memory via a vec, leak and cast let _mem_len = (size * core::mem::size_of::()).align_up(BasePageSize::SIZE as usize); - let ptr = (crate::mm::allocate(_mem_len, true).0 as *const Descriptor) as *mut Descriptor; + let ptr = ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); let ring: &'static mut [Descriptor] = unsafe { core::slice::from_raw_parts_mut(ptr, size) }; @@ -1251,9 +1251,9 @@ impl PackedVq { let _mem_len = core::mem::size_of::().align_up(BasePageSize::SIZE as usize); let drv_event_ptr = - (crate::mm::allocate(_mem_len, true).0 as *const EventSuppr) as *mut EventSuppr; + ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); let dev_event_ptr = - (crate::mm::allocate(_mem_len, true).0 as *const EventSuppr) as *mut EventSuppr; + ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); // Provide memory areas of the queues data structures to the device vq_handler.set_ring_addr(paging::virt_to_phys(VirtAddr::from( @@ -1277,11 +1277,11 @@ impl PackedVq { raw: dev_event, }; - let mut notif_ctrl = NotifCtrl::new( - (notif_cfg.base() + let mut notif_ctrl = NotifCtrl::new(ptr::from_exposed_addr_mut( + notif_cfg.base() + usize::try_from(vq_handler.notif_off()).unwrap() - + usize::try_from(notif_cfg.multiplier()).unwrap()) as *mut usize, - ); + + usize::try_from(notif_cfg.multiplier()).unwrap(), + )); if feats & Features::VIRTIO_F_NOTIFICATION_DATA == Features::VIRTIO_F_NOTIFICATION_DATA { notif_ctrl.enable_notif_data(); diff --git a/src/drivers/virtio/virtqueue/split.rs b/src/drivers/virtio/virtqueue/split.rs index 9e94e57c25..4cbb76ab6a 100644 --- a/src/drivers/virtio/virtqueue/split.rs +++ b/src/drivers/virtio/virtqueue/split.rs @@ -394,17 +394,18 @@ impl SplitVq { // Allocate heap memory via a vec, leak and cast let _mem_len = (size as usize * core::mem::size_of::()) .align_up(BasePageSize::SIZE as usize); - let table_raw = - (crate::mm::allocate(_mem_len, true).0 as *const Descriptor) as *mut Descriptor; + let table_raw = ptr::from_exposed_addr_mut(crate::mm::allocate(_mem_len, true).0 as usize); let descr_table = DescrTable { raw: unsafe { core::slice::from_raw_parts_mut(table_raw, size as usize) }, }; let _mem_len = (6 + (size as usize * 2)).align_up(BasePageSize::SIZE as usize); - let avail_raw = (crate::mm::allocate(_mem_len, true).0 as *const u8) as *mut u8; + let avail_raw = + ptr::from_exposed_addr_mut::(crate::mm::allocate(_mem_len, true).0 as usize); let _mem_len = (6 + (size as usize * 8)).align_up(BasePageSize::SIZE as usize); - let used_raw = (crate::mm::allocate(_mem_len, true).0 as *const u8) as *mut u8; + let used_raw = + ptr::from_exposed_addr_mut::(crate::mm::allocate(_mem_len, true).0 as usize); let avail_ring = unsafe { AvailRing { @@ -456,11 +457,11 @@ impl SplitVq { used_ring, }; - let notif_ctrl = NotifCtrl::new( - (notif_cfg.base() + let notif_ctrl = NotifCtrl::new(ptr::from_exposed_addr_mut( + notif_cfg.base() + usize::try_from(vq_handler.notif_off()).unwrap() - + usize::try_from(notif_cfg.multiplier()).unwrap()) as *mut usize, - ); + + usize::try_from(notif_cfg.multiplier()).unwrap(), + )); // Initialize new memory pool. let mem_pool = Rc::new(MemPool::new(size)); diff --git a/src/syscalls/condvar.rs b/src/syscalls/condvar.rs index 873113c7a8..1ec6f6e994 100644 --- a/src/syscalls/condvar.rs +++ b/src/syscalls/condvar.rs @@ -2,8 +2,8 @@ // "Implementing Condition Variables with Semaphores" use alloc::boxed::Box; -use core::mem; use core::sync::atomic::{AtomicIsize, Ordering}; +use core::{mem, ptr}; use crate::synch::semaphore::Semaphore; @@ -25,14 +25,14 @@ impl CondQueue { extern "C" fn __sys_destroy_queue(ptr: usize) -> i32 { unsafe { - let id = ptr as *mut usize; + let id = ptr::from_exposed_addr_mut::(ptr); if id.is_null() { debug!("sys_wait: invalid address to condition variable"); return -1; } if *id != 0 { - let cond = Box::from_raw((*id) as *mut CondQueue); + let cond = Box::from_raw(ptr::from_exposed_addr_mut::(*id)); mem::drop(cond); } @@ -47,7 +47,7 @@ pub unsafe extern "C" fn sys_destroy_queue(ptr: usize) -> i32 { extern "C" fn __sys_notify(ptr: usize, count: i32) -> i32 { unsafe { - let id = ptr as *const usize; + let id = ptr::from_exposed_addr::(ptr); if id.is_null() { // invalid argument @@ -60,7 +60,7 @@ extern "C" fn __sys_notify(ptr: usize, count: i32) -> i32 { return -1; } - let cond = &mut *((*id) as *mut CondQueue); + let cond = &mut *(ptr::from_exposed_addr_mut::(*id)); if count < 0 { // Wake up all task that has been waiting for this condition variable @@ -88,7 +88,7 @@ pub unsafe extern "C" fn sys_notify(ptr: usize, count: i32) -> i32 { extern "C" fn __sys_init_queue(ptr: usize) -> i32 { unsafe { - let id = ptr as *mut usize; + let id = ptr::from_exposed_addr_mut::(ptr); if id.is_null() { debug!("sys_init_queue: invalid address to condition variable"); return -1; @@ -111,7 +111,7 @@ pub unsafe extern "C" fn sys_init_queue(ptr: usize) -> i32 { extern "C" fn __sys_add_queue(ptr: usize, timeout_ns: i64) -> i32 { unsafe { - let id = ptr as *mut usize; + let id = ptr::from_exposed_addr_mut::(ptr); if id.is_null() { debug!("sys_add_queue: invalid address to condition variable"); return -1; @@ -124,7 +124,7 @@ extern "C" fn __sys_add_queue(ptr: usize, timeout_ns: i64) -> i32 { } if timeout_ns <= 0 { - let cond = &mut *((*id) as *mut CondQueue); + let cond = &mut *(ptr::from_exposed_addr_mut::(*id)); cond.counter.fetch_add(1, Ordering::SeqCst); 0 @@ -143,7 +143,7 @@ pub unsafe extern "C" fn sys_add_queue(ptr: usize, timeout_ns: i64) -> i32 { extern "C" fn __sys_wait(ptr: usize) -> i32 { unsafe { - let id = ptr as *mut usize; + let id = ptr::from_exposed_addr_mut::(ptr); if id.is_null() { debug!("sys_wait: invalid address to condition variable"); return -1; @@ -154,7 +154,7 @@ extern "C" fn __sys_wait(ptr: usize) -> i32 { return -1; } - let cond = &mut *((*id) as *mut CondQueue); + let cond = &mut *(ptr::from_exposed_addr_mut::(*id)); cond.sem1.acquire(None); cond.sem2.release(); diff --git a/src/syscalls/interfaces/uhyve.rs b/src/syscalls/interfaces/uhyve.rs index 2b0725fcc5..a19c2e3873 100644 --- a/src/syscalls/interfaces/uhyve.rs +++ b/src/syscalls/interfaces/uhyve.rs @@ -148,11 +148,11 @@ impl SyscallInterface for Uhyve { argv.push(unsafe { alloc(layout).cast_const() }); - argv_phy.push( + argv_phy.push(ptr::from_exposed_addr::( paging::virtual_to_physical(VirtAddr(argv[i] as u64)) .unwrap() - .as_u64() as *const u8, - ); + .as_usize(), + )); } // create array to receive the environment @@ -164,11 +164,11 @@ impl SyscallInterface for Uhyve { .unwrap(); env.push(unsafe { alloc(layout).cast_const() }); - env_phy.push( + env_phy.push(ptr::from_exposed_addr::( paging::virtual_to_physical(VirtAddr(env[i] as u64)) .unwrap() - .as_u64() as *const u8, - ); + .as_usize(), + )); } // ask uhyve for the environment