Skip to content

Commit

Permalink
use from_exposed_addr instead of casting
Browse files Browse the repository at this point in the history
Using this function makes it clear that the casted object is an exposed
address, rather than a reference or another pointer.
  • Loading branch information
cagatay-y committed Oct 25, 2023
1 parent c52b9fb commit 614c41c
Show file tree
Hide file tree
Showing 17 changed files with 93 additions and 74 deletions.
7 changes: 5 additions & 2 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 @@ -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
6 changes: 4 additions & 2 deletions src/arch/aarch64/kernel/mod.rs
Original file line number Diff line number Diff line change
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
6 changes: 4 additions & 2 deletions src/arch/aarch64/kernel/pci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("/") {
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
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
2 changes: 1 addition & 1 deletion src/arch/aarch64/mm/paging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<L::SubtableLevel>) }
unsafe { &mut *(ptr::from_exposed_addr_mut(subtable_address)) }
}

/// Maps a continuous range of pages.
Expand Down
16 changes: 10 additions & 6 deletions src/arch/x86_64/kernel/acpi.rs
Original file line number Diff line number Diff line change
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 @@ -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::<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.
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
25 changes: 13 additions & 12 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
8 changes: 4 additions & 4 deletions src/arch/x86_64/kernel/mmio.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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::<MmioRegisterLayout>(
virtual_address.as_usize() | (current_address & (BasePageSize::SIZE as usize - 1)),
))
};

let magic = mmio.get_magic_value();
Expand Down
3 changes: 2 additions & 1 deletion src/drivers/net/virtio_mmio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -115,7 +116,7 @@ impl VirtioNetDriver {
irq: u8,
) -> Result<Self, VirtioNetError> {
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,
Expand Down
13 changes: 7 additions & 6 deletions src/drivers/virtio/transport/pci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -163,10 +163,11 @@ pub fn map_dev_cfg<T>(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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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::<u8>(virt_addr_raw.into());

// Zero initialize shared memory area
unsafe {
Expand Down
4 changes: 2 additions & 2 deletions src/drivers/virtio/virtqueue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
14 changes: 7 additions & 7 deletions src/drivers/virtio/virtqueue/packed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl DescriptorRing {
// Allocate heap memory via a vec, leak and cast
let _mem_len =
(size * core::mem::size_of::<Descriptor>()).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) };

Expand Down Expand Up @@ -1251,9 +1251,9 @@ impl PackedVq {
let _mem_len = core::mem::size_of::<EventSuppr>().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(
Expand All @@ -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();
Expand Down
Loading

0 comments on commit 614c41c

Please sign in to comment.