Skip to content

Commit

Permalink
Merge pull request #964 from cagatay-y/cast-elimination
Browse files Browse the repository at this point in the history
Minimize casts to pointers
  • Loading branch information
mkroening authored Oct 25, 2023
2 parents 5289013 + 614c41c commit d42f1b1
Show file tree
Hide file tree
Showing 27 changed files with 168 additions and 155 deletions.
9 changes: 6 additions & 3 deletions src/arch/aarch64/kernel/interrupts.rs
Original file line number Diff line number Diff line change
@@ -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::*;
Expand Down Expand Up @@ -190,7 +191,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());
Expand Down Expand Up @@ -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();
Expand Down
10 changes: 6 additions & 4 deletions src/arch/aarch64/kernel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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")
Expand Down
38 changes: 19 additions & 19 deletions src/arch/aarch64/kernel/pci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,19 @@ 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)
}

#[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 {
Expand All @@ -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());
}
}
}
Expand Down Expand Up @@ -230,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("/") {
Expand Down
6 changes: 4 additions & 2 deletions src/arch/aarch64/kernel/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,10 @@ pub fn set_oneshot_timer(wakeup_time: Option<u64>) {

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
Expand Down
2 changes: 1 addition & 1 deletion src/arch/aarch64/kernel/serial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<u8>(self.port_address as usize);

// LF newline characters need to be extended to CRLF over a real serial port.
if byte == b'\n' {
Expand Down
2 changes: 1 addition & 1 deletion src/arch/aarch64/kernel/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
};
)*
Expand Down
6 changes: 4 additions & 2 deletions src/arch/aarch64/kernel/systemtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("/") {
Expand Down
4 changes: 2 additions & 2 deletions src/arch/aarch64/mm/paging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,10 +517,10 @@ where

// Calculate the address of the subtable.
let index = page.table_index::<L>();
let table_address = self as *const PageTable<L> 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<L::SubtableLevel>) }
unsafe { &mut *(ptr::from_exposed_addr_mut(subtable_address)) }
}

/// Maps a continuous range of pages.
Expand Down
26 changes: 15 additions & 11 deletions src/arch/x86_64/kernel/acpi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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::<AcpiRsdp>(current_address)) };
if &rsdp.signature != b"RSD PTR " {
continue;
}
Expand Down Expand Up @@ -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()),
)
};

Expand Down Expand Up @@ -389,13 +389,13 @@ 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::<AcpiFadt>(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.
// 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
{
Expand Down Expand Up @@ -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::<u64>(current_address))
});
current_address += mem::size_of::<u64>();
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::<u32>(current_address)) })
.into(),
);
current_address += mem::size_of::<u32>();
address
};
Expand Down
27 changes: 14 additions & 13 deletions src/arch/x86_64/kernel/apic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -267,21 +265,23 @@ fn detect_from_acpi() -> Result<PhysAddr, ()> {
fn detect_from_acpi() -> Result<PhysAddr, ()> {
// 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::<AcpiMadtHeader>(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::<AcpiMadtHeader>();

// 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::<AcpiMadtRecordHeader>(current_address)) };
current_address += mem::size_of::<AcpiMadtRecordHeader>();

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::<ProcessorLocalApicRecord>(current_address))
};
debug!(
"Found Processor Local APIC record: {}",
processor_local_apic_record
Expand All @@ -293,7 +293,8 @@ fn detect_from_acpi() -> Result<PhysAddr, ()> {
}
1 => {
// I/O APIC
let ioapic_record = unsafe { &*(current_address as *const IoApicRecord) };
let ioapic_record =
unsafe { &*(ptr::from_exposed_addr::<IoApicRecord>(current_address)) };
debug!("Found I/O APIC record: {}", ioapic_record);

init_ioapic_address(PhysAddr(ioapic_record.address.into()));
Expand Down Expand Up @@ -379,7 +380,7 @@ fn detect_from_mp() -> Result<PhysAddr, ()> {

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);
Expand All @@ -395,19 +396,19 @@ fn detect_from_mp() -> Result<PhysAddr, ()> {
// entries starts directly after the config table
addr += mem::size_of::<ApicConfigTable>();
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);
}
addr += mem::size_of::<ApicProcessorEntry>();
}
// 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);

Expand Down Expand Up @@ -729,7 +730,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,
);
}

Expand Down
Loading

0 comments on commit d42f1b1

Please sign in to comment.