Resolve a huge portion of the clippy lints

This commit is contained in:
Speedy_Lex
2025-10-06 12:30:23 +00:00
committed by Jeremy Soller
parent db8fb14614
commit 0931a7f49f
57 changed files with 451 additions and 509 deletions
+1
View File
@@ -23,6 +23,7 @@ fn parse_kconfig(arch: &str) -> Option<()> {
.as_table()
.unwrap();
#[expect(clippy::format_collect)] // TODO: remove once version is bumped
let features_list = altfeatures
.keys()
.map(|feat| format!(", {feat:?}"))
+6 -9
View File
@@ -2,9 +2,12 @@ use core::{mem, ptr};
use core::ptr::{read_volatile, write_volatile};
use crate::memory::{map_device_memory, PhysicalAddress, PAGE_SIZE};
use crate::{
find_one_sdt,
memory::{map_device_memory, PhysicalAddress, PAGE_SIZE},
};
use super::{find_sdt, sdt::Sdt, GenericAddressStructure, ACPI_TABLE};
use super::{sdt::Sdt, GenericAddressStructure, ACPI_TABLE};
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
@@ -24,13 +27,7 @@ pub struct Hpet {
impl Hpet {
pub fn init() {
let hpet_sdt = find_sdt("HPET");
let hpet = if hpet_sdt.len() == 1 {
Hpet::new(hpet_sdt[0])
} else {
println!("Unable to find HPET");
return;
};
let hpet = Hpet::new(find_one_sdt!("HPET"));
if let Some(hpet) = hpet {
println!(" HPET: {:X}", hpet.hpet_number);
+84 -91
View File
@@ -46,117 +46,110 @@ pub(super) fn init(madt: Madt) {
result.flush();
// Write trampoline, make sure TRAMPOLINE page is free for use
for i in 0..TRAMPOLINE_DATA.len() {
for (i, val) in TRAMPOLINE_DATA.iter().enumerate() {
unsafe {
(*((TRAMPOLINE as *mut u8).add(i) as *const AtomicU8))
.store(TRAMPOLINE_DATA[i], Ordering::SeqCst);
.store(*val, Ordering::SeqCst);
}
}
for madt_entry in madt.iter() {
println!(" {:x?}", madt_entry);
match madt_entry {
MadtEntry::LocalApic(ap_local_apic) => {
if u32::from(ap_local_apic.id) == me.get() {
println!(" This is my local APIC");
} else {
if ap_local_apic.flags & 1 == 1 {
let cpu_id = LogicalCpuId::next();
if let MadtEntry::LocalApic(ap_local_apic) = madt_entry {
if u32::from(ap_local_apic.id) == me.get() {
println!(" This is my local APIC");
} else if ap_local_apic.flags & 1 == 1 {
let cpu_id = LogicalCpuId::next();
// Allocate a stack
let stack_start = allocate_p2frame(4)
.expect("no more frames in acpi stack_start")
.base()
.data()
+ crate::PHYS_OFFSET;
let stack_end = stack_start + (PAGE_SIZE << 4);
// Allocate a stack
let stack_start = allocate_p2frame(4)
.expect("no more frames in acpi stack_start")
.base()
.data()
+ crate::PHYS_OFFSET;
let stack_end = stack_start + (PAGE_SIZE << 4);
let pcr_ptr =
crate::arch::gdt::allocate_and_init_pcr(cpu_id, stack_end);
let pcr_ptr = crate::arch::gdt::allocate_and_init_pcr(cpu_id, stack_end);
let idt_ptr = crate::arch::idt::allocate_and_init_idt(cpu_id);
let idt_ptr = crate::arch::idt::allocate_and_init_idt(cpu_id);
let args = KernelArgsAp {
cpu_id,
page_table: page_table_physaddr,
pcr_ptr,
idt_ptr,
};
let args = KernelArgsAp {
cpu_id,
page_table: page_table_physaddr,
pcr_ptr,
idt_ptr,
};
let ap_ready = (TRAMPOLINE + 8) as *mut u64;
let ap_args_ptr = unsafe { ap_ready.add(1) };
let ap_page_table = unsafe { ap_ready.add(2) };
let ap_stack_end = unsafe { ap_ready.add(3) };
let ap_code = unsafe { ap_ready.add(4) };
let ap_ready = (TRAMPOLINE + 8) as *mut u64;
let ap_args_ptr = unsafe { ap_ready.add(1) };
let ap_page_table = unsafe { ap_ready.add(2) };
let ap_stack_end = unsafe { ap_ready.add(3) };
let ap_code = unsafe { ap_ready.add(4) };
// Set the ap_ready to 0, volatile
unsafe {
ap_ready.write(0);
ap_args_ptr.write(&args as *const _ as u64);
ap_page_table.write(page_table_physaddr as u64);
ap_stack_end.write(stack_end as u64);
ap_code.write(kstart_ap as u64);
// Set the ap_ready to 0, volatile
unsafe {
ap_ready.write(0);
ap_args_ptr.write(&args as *const _ as u64);
ap_page_table.write(page_table_physaddr as u64);
ap_stack_end.write(stack_end as u64);
#[expect(clippy::fn_to_numeric_cast)]
ap_code.write(kstart_ap as u64);
// TODO: Is this necessary (this fence)?
core::arch::asm!("");
};
AP_READY.store(false, Ordering::SeqCst);
// TODO: Is this necessary (this fence)?
core::arch::asm!("");
};
AP_READY.store(false, Ordering::SeqCst);
print!(
" AP {} APIC {}:",
ap_local_apic.processor, ap_local_apic.id
);
print!(
" AP {} APIC {}:",
ap_local_apic.processor, ap_local_apic.id
);
// Send INIT IPI
{
let mut icr = 0x4500;
if local_apic.x2 {
icr |= u64::from(ap_local_apic.id) << 32;
} else {
icr |= u64::from(ap_local_apic.id) << 56;
}
print!(" IPI...");
local_apic.set_icr(icr);
}
// Send START IPI
{
//Start at 0x0800:0000 => 0x8000. Hopefully the bootloader code is still there
let ap_segment = (TRAMPOLINE >> 12) & 0xFF;
let mut icr = 0x4600 | ap_segment as u64;
if local_apic.x2 {
icr |= u64::from(ap_local_apic.id) << 32;
} else {
icr |= u64::from(ap_local_apic.id) << 56;
}
print!(" SIPI...");
local_apic.set_icr(icr);
}
// Wait for trampoline ready
print!(" Wait...");
while unsafe { (*ap_ready.cast::<AtomicU8>()).load(Ordering::SeqCst) }
== 0
{
hint::spin_loop();
}
print!(" Trampoline...");
while !AP_READY.load(Ordering::SeqCst) {
hint::spin_loop();
}
println!(" Ready");
unsafe {
RmmA::invalidate_all();
}
// Send INIT IPI
{
let mut icr = 0x4500;
if local_apic.x2 {
icr |= u64::from(ap_local_apic.id) << 32;
} else {
println!(" CPU Disabled");
icr |= u64::from(ap_local_apic.id) << 56;
}
print!(" IPI...");
local_apic.set_icr(icr);
}
// Send START IPI
{
//Start at 0x0800:0000 => 0x8000. Hopefully the bootloader code is still there
let ap_segment = (TRAMPOLINE >> 12) & 0xFF;
let mut icr = 0x4600 | ap_segment as u64;
if local_apic.x2 {
icr |= u64::from(ap_local_apic.id) << 32;
} else {
icr |= u64::from(ap_local_apic.id) << 56;
}
print!(" SIPI...");
local_apic.set_icr(icr);
}
// Wait for trampoline ready
print!(" Wait...");
while unsafe { (*ap_ready.cast::<AtomicU8>()).load(Ordering::SeqCst) } == 0 {
hint::spin_loop();
}
print!(" Trampoline...");
while !AP_READY.load(Ordering::SeqCst) {
hint::spin_loop();
}
println!(" Ready");
unsafe {
RmmA::invalidate_all();
}
} else {
println!(" CPU Disabled");
}
_ => (),
}
}
+3 -8
View File
@@ -1,6 +1,7 @@
use core::{cell::SyncUnsafeCell, mem};
use super::{find_sdt, sdt::Sdt};
use super::sdt::Sdt;
use crate::find_one_sdt;
/// The Multiple APIC Descriptor Table
#[derive(Clone, Copy, Debug)]
@@ -30,13 +31,7 @@ pub const FLAG_PCAT: u32 = 1;
impl Madt {
pub fn init() {
let madt_sdt = find_sdt("APIC");
let madt = if madt_sdt.len() == 1 {
Madt::new(madt_sdt[0])
} else {
println!("Unable to find MADT");
return;
};
let madt = Madt::new(find_one_sdt!("APIC"));
if let Some(madt) = madt {
// safe because no APs have been started yet.
+20 -2
View File
@@ -11,7 +11,7 @@ use crate::{
paging::{PageFlags, PhysicalAddress, RmmA, RmmArch},
};
use self::{hpet::Hpet, madt::Madt, rsdp::RSDP, rsdt::Rsdt, rxsdt::Rxsdt, sdt::Sdt, xsdt::Xsdt};
use self::{hpet::Hpet, madt::Madt, rsdp::Rsdp, rsdt::Rsdt, rxsdt::Rxsdt, sdt::Sdt, xsdt::Xsdt};
#[cfg(target_arch = "aarch64")]
mod gtdt;
@@ -100,7 +100,7 @@ pub unsafe fn init(already_supplied_rsdp: Option<*const u8>) {
}
// Search for RSDP
let rsdp_opt = RSDP::get_rsdp(&mut KernelMapper::lock(), already_supplied_rsdp);
let rsdp_opt = Rsdp::get_rsdp(&mut KernelMapper::lock(), already_supplied_rsdp);
if let Some(rsdp) = rsdp_opt {
info!("SDT address: {:#x}", rsdp.sdt_address());
@@ -192,6 +192,24 @@ pub fn find_sdt(name: &str) -> Vec<&'static Sdt> {
sdts
}
#[macro_export]
macro_rules! find_one_sdt {
($name:expr) => {{
use $crate::acpi::find_sdt;
match find_sdt($name).as_slice() {
[] => {
println!("Unable to find {}", $name);
return;
}
[x] => *x,
x => {
println!("{} {} found, expected 1", x.len(), $name);
return;
}
}
}};
}
pub fn get_sdt_signature(sdt: &'static Sdt) -> SdtSignature {
let signature =
String::from_utf8(sdt.signature.to_vec()).expect("Error converting signature to string");
+9 -9
View File
@@ -6,7 +6,7 @@ use crate::{
/// RSDP
#[derive(Copy, Clone, Debug)]
#[repr(C, packed)]
pub struct RSDP {
pub struct Rsdp {
signature: [u8; 8],
_checksum: u8,
_oemid: [u8; 6],
@@ -18,15 +18,15 @@ pub struct RSDP {
_reserved: [u8; 3],
}
impl RSDP {
fn get_already_supplied_rsdp(rsdp_ptr: *const u8) -> RSDP {
impl Rsdp {
fn get_already_supplied_rsdp(rsdp_ptr: *const u8) -> Rsdp {
// TODO: Validate
unsafe { *(rsdp_ptr as *const RSDP) }
unsafe { *(rsdp_ptr as *const Rsdp) }
}
pub fn get_rsdp(
mapper: &mut KernelMapper,
already_supplied_rsdp: Option<*const u8>,
) -> Option<RSDP> {
) -> Option<Rsdp> {
if let Some(rsdp_ptr) = already_supplied_rsdp {
Some(Self::get_already_supplied_rsdp(rsdp_ptr))
} else {
@@ -34,7 +34,7 @@ impl RSDP {
}
}
/// Search for the RSDP
pub fn get_rsdp_by_searching(mapper: &mut KernelMapper) -> Option<RSDP> {
pub fn get_rsdp_by_searching(mapper: &mut KernelMapper) -> Option<Rsdp> {
let start_addr = 0xE_0000;
let end_addr = 0xF_FFFF;
@@ -55,12 +55,12 @@ impl RSDP {
}
}
RSDP::search(start_addr, end_addr)
Rsdp::search(start_addr, end_addr)
}
fn search(start_addr: usize, end_addr: usize) -> Option<RSDP> {
fn search(start_addr: usize, end_addr: usize) -> Option<Rsdp> {
for i in 0..(end_addr + 1 - start_addr) / 16 {
let rsdp = unsafe { &*((start_addr + i * 16) as *const RSDP) };
let rsdp = unsafe { &*((start_addr + i * 16) as *const Rsdp) };
if &rsdp.signature == b"RSD PTR " {
return Some(*rsdp);
}
+1 -5
View File
@@ -24,10 +24,6 @@ impl Sdt {
pub fn data_len(&self) -> usize {
let total_size = self.length as usize;
let header_size = mem::size_of::<Sdt>();
if total_size >= header_size {
total_size - header_size
} else {
0
}
total_size.saturating_sub(header_size)
}
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub unsafe fn early_init(bsp: bool) {
return;
}
overwrite(&relocs, enable);
overwrite(relocs, enable);
if cfg!(not(feature = "self_modifying")) {
assert!(
+1 -1
View File
@@ -403,7 +403,7 @@ macro_rules! interrupt_stack {
inner = sym inner,
IA32_GS_BASE = const(x86::msr::IA32_GS_BASE),
PCR_GDT_OFFSET = const(core::mem::offset_of!(crate::gdt::ProcessorControlRegion, gdt)),
PCR_GDT_OFFSET = const(core::mem::offset_of!($crate::gdt::ProcessorControlRegion, gdt)),
);
}
};
+1
View File
@@ -26,6 +26,7 @@ pub unsafe fn init() {
let star_high = u32::from(syscall_cs_ss_base) | (u32::from(sysret_cs_ss_base) << 16);
msr::wrmsr(msr::IA32_STAR, u64::from(star_high) << 32);
#[expect(clippy::fn_to_numeric_cast)]
msr::wrmsr(msr::IA32_LSTAR, syscall_instruction as u64);
// DF needs to be cleared, required by the compiler ABI. If DF were not part of FMASK,
+1 -1
View File
@@ -25,5 +25,5 @@ pub fn feature_info() -> FeatureInfo {
#[cfg_attr(not(target_arch = "x86_64"), expect(dead_code))]
pub fn has_ext_feat(feat: impl FnOnce(ExtendedFeatures) -> bool) -> bool {
cpuid().get_extended_feature_info().map_or(false, feat)
cpuid().get_extended_feature_info().is_some_and(feat)
}
+1 -1
View File
@@ -95,7 +95,7 @@ unsafe fn debug_caps(hpet: &mut Hpet) {
);
// The NUM_TIM_CAP field contains the index of the last timer.
// Add 1 to get the amount of timers.
trace!(" timers: {}", (capability >> 8) as u8 & 0x1F + 1);
trace!(" timers: {}", ((capability >> 8) as u8 & 0x1F) + 1);
let t0_capabilities = hpet.read_u64(T0_CONFIG_CAPABILITY_OFFSET);
trace!(
+1 -1
View File
@@ -176,7 +176,7 @@ impl fmt::Debug for IoApic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
struct RedirTable<'a>(&'a Mutex<IoApicRegs>);
impl<'a> fmt::Debug for RedirTable<'a> {
impl fmt::Debug for RedirTable<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut guard = self.0.lock();
+3 -3
View File
@@ -70,7 +70,7 @@ impl LocalApic {
self.address = virtaddr.data();
self.x2 = cpuid()
.get_feature_info()
.map_or(false, |feature_info| feature_info.has_x2apic());
.is_some_and(|feature_info| feature_info.has_x2apic());
if !self.x2 {
info!("Detected xAPIC at {:#x}", physaddr.data());
@@ -93,7 +93,7 @@ impl LocalApic {
unsafe fn init_ap(&mut self) {
unsafe {
if self.x2 {
wrmsr(IA32_APIC_BASE, rdmsr(IA32_APIC_BASE) | 1 << 10);
wrmsr(IA32_APIC_BASE, rdmsr(IA32_APIC_BASE) | (1 << 10));
wrmsr(IA32_X2APIC_SIVR, 0x100);
} else {
self.write(0xF0, 0x100);
@@ -138,7 +138,7 @@ impl LocalApic {
if self.x2 {
unsafe { rdmsr(IA32_X2APIC_ICR) }
} else {
unsafe { (self.read(0x310) as u64) << 32 | self.read(0x300) as u64 }
unsafe { ((self.read(0x310) as u64) << 32) | self.read(0x300) as u64 }
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ pub fn get_kvm_support() -> &'static Option<KvmSupport> {
pub unsafe fn init() -> bool {
unsafe {
let cpuid = crate::cpuid::cpuid();
if !cpuid.get_feature_info().map_or(false, |f| f.has_tsc()) {
if !cpuid.get_feature_info().is_some_and(|f| f.has_tsc()) {
return false;
}
+7 -4
View File
@@ -73,7 +73,7 @@ static IDTS: RwLock<HashMap<LogicalCpuId, &'static mut Idt>> =
#[inline]
pub fn is_reserved(cpu_id: LogicalCpuId, index: u8) -> bool {
if cpu_id == LogicalCpuId::BSP {
return unsafe { (&*INIT_BSP_IDT.get()).is_reserved(index) };
return unsafe { (*INIT_BSP_IDT.get()).is_reserved(index) };
}
IDTS.read().get(&cpu_id).unwrap().is_reserved(index)
@@ -82,7 +82,7 @@ pub fn is_reserved(cpu_id: LogicalCpuId, index: u8) -> bool {
#[inline]
pub fn set_reserved(cpu_id: LogicalCpuId, index: u8, reserved: bool) {
if cpu_id == LogicalCpuId::BSP {
unsafe { (&*INIT_BSP_IDT.get()).set_reserved(index, reserved) };
unsafe { (*INIT_BSP_IDT.get()).set_reserved(index, reserved) };
return;
}
@@ -210,8 +210,11 @@ fn init_generic(cpu_id: LogicalCpuId, idt: &mut Idt, backup_stack_end: usize) {
#[cfg(target_arch = "x86_64")]
for i in 0..224 {
current_idt[i + 32]
.set_func(unsafe { mem::transmute(__generic_interrupts_start as usize + i * 8) });
current_idt[i + 32].set_func(unsafe {
mem::transmute::<usize, unsafe extern "C" fn()>(
__generic_interrupts_start as usize + i * 8,
)
});
}
// reserve bits 31:0, i.e. the first 32 interrupts, which are reserved for exceptions
+1 -1
View File
@@ -27,7 +27,7 @@ impl StackTrace {
let fp = *(self.fp as *const usize);
let pc_ptr = fp.checked_add(mem::size_of::<usize>())?;
Some(Self {
fp: fp,
fp,
pc_ptr: pc_ptr as *const usize,
})
}
+2 -2
View File
@@ -28,12 +28,12 @@ pub fn ipi(kind: IpiKind, target: IpiTarget) {
#[cfg(feature = "profiling")]
if matches!(kind, IpiKind::Profile) {
let icr = (target as u64) << 18 | 1 << 14 | 0b100 << 8;
let icr = ((target as u64) << 18) | (1 << 14) | (0b100 << 8);
unsafe { the_local_apic().set_icr(icr) };
return;
}
let icr = (target as u64) << 18 | 1 << 14 | (kind as u64);
let icr = ((target as u64) << 18) | (1 << 14) | (kind as u64);
unsafe { the_local_apic().set_icr(icr) };
}
+7 -7
View File
@@ -52,13 +52,13 @@ unsafe fn init_pat() {
msr::wrmsr(
msr::IA32_PAT,
pat7 << 56
| pat6 << 48
| pat5 << 40
| pat4 << 32
| pat3 << 24
| pat2 << 16
| pat1 << 8
(pat7 << 56)
| (pat6 << 48)
| (pat5 << 40)
| (pat4 << 32)
| (pat3 << 24)
| (pat2 << 16)
| (pat1 << 8)
| pat0,
);
}
+1 -1
View File
@@ -25,7 +25,7 @@ use crate::{
/// Test of zero values in BSS.
static BSS_TEST_ZERO: SyncUnsafeCell<usize> = SyncUnsafeCell::new(0);
/// Test of non-zero values in data.
static DATA_TEST_NONZERO: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::max_value());
static DATA_TEST_NONZERO: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::MAX);
pub static AP_READY: AtomicBool = AtomicBool::new(false);
static BSP_READY: AtomicBool = AtomicBool::new(false);
+3 -1
View File
@@ -10,13 +10,15 @@ pub struct AlignedBox<T: ?Sized, const ALIGN: usize> {
unsafe impl<T: Send + ?Sized, const ALIGN: usize> Send for AlignedBox<T, ALIGN> {}
unsafe impl<T: Sync + ?Sized, const ALIGN: usize> Sync for AlignedBox<T, ALIGN> {}
/// # Safety
/// All types implementing this trait must be valid when zeroed
pub unsafe trait ValidForZero {}
unsafe impl<const N: usize> ValidForZero for [u8; N] {}
unsafe impl ValidForZero for u8 {}
impl<T: ?Sized, const ALIGN: usize> AlignedBox<T, ALIGN> {
fn layout(&self) -> Layout {
layout_upgrade_align(Layout::for_value::<T>(&*self), ALIGN)
layout_upgrade_align(Layout::for_value::<T>(self), ALIGN)
}
}
const fn layout_upgrade_align(layout: Layout, align: usize) -> Layout {
+3 -3
View File
@@ -103,7 +103,7 @@ impl Context {
// Zero-initialize InterruptStack registers.
stack_top = stack_top.sub(INT_REGS_SIZE);
stack_top.write_bytes(0_u8, INT_REGS_SIZE);
(&mut *stack_top.cast::<InterruptStack>()).init();
(*stack_top.cast::<InterruptStack>()).init();
stack_top = stack_top.sub(core::mem::size_of::<usize>());
stack_top
@@ -199,10 +199,10 @@ impl super::Context {
&& RmmA::virt_is_valid(VirtualAddress::new(regs.gsbase as usize))
{
unsafe {
x86::msr::wrmsr(x86::msr::IA32_FS_BASE, regs.fsbase as u64);
x86::msr::wrmsr(x86::msr::IA32_FS_BASE, regs.fsbase);
// We have to write to KERNEL_GSBASE, because when the kernel returns to
// userspace, it will have executed SWAPGS first.
x86::msr::wrmsr(x86::msr::IA32_KERNEL_GSBASE, regs.gsbase as u64);
x86::msr::wrmsr(x86::msr::IA32_KERNEL_GSBASE, regs.gsbase);
}
self.arch.fsbase = regs.fsbase as usize;
self.arch.gsbase = regs.gsbase as usize;
+12 -17
View File
@@ -329,7 +329,7 @@ impl Context {
&mut self,
addr_space: Option<Arc<AddrSpaceWrapper>>,
) -> Option<Arc<AddrSpaceWrapper>> {
if let (&Some(ref old), &Some(ref new)) = (&self.addr_space, &addr_space)
if let (Some(old), Some(new)) = (&self.addr_space, &addr_space)
&& Arc::ptr_eq(old, new)
{
return addr_space;
@@ -341,7 +341,7 @@ impl Context {
if let Some(ref prev_addrsp) = self.addr_space {
assert!(Arc::ptr_eq(
&this_percpu.current_addrsp.borrow().as_ref().unwrap(),
this_percpu.current_addrsp.borrow().as_ref().unwrap(),
prev_addrsp
));
prev_addrsp
@@ -383,18 +383,14 @@ impl Context {
if !self.can_access_regs() {
return None;
}
let Some(ref kstack) = self.kstack else {
return None;
};
let kstack = self.kstack.as_ref()?;
Some(unsafe { &*kstack.initial_top().sub(size_of::<InterruptStack>()).cast() })
}
pub fn regs_mut(&mut self) -> Option<&mut InterruptStack> {
if !self.can_access_regs() {
return None;
}
let Some(ref mut kstack) = self.kstack else {
return None;
};
let kstack = self.kstack.as_ref()?;
Some(unsafe { &mut *kstack.initial_top().sub(size_of::<InterruptStack>()).cast() })
}
pub fn sigcontrol(&mut self) -> Option<(&Sigcontrol, &SigProcControl, &mut SignalState)> {
@@ -514,14 +510,13 @@ impl Drop for BorrowedHtBuf {
};
//TODO: do not allow drop so lock token can be passed in
let mut token = unsafe { CleanLockToken::new() };
match context.write(token.token()) {
mut context => {
*(if self.head_and_not_tail {
&mut context.syscall_head
} else {
&mut context.syscall_tail
}) = SyscallFrame::Free(inner);
}
let mut context = context.write(token.token());
{
*(if self.head_and_not_tail {
&mut context.syscall_head
} else {
&mut context.syscall_tail
}) = SyscallFrame::Free(inner);
}
}
}
@@ -811,7 +806,7 @@ impl FdTbl {
let desc = context_fd.description.read();
desc.scheme == scheme_id && desc.number == scheme_number
})
.map(|fd| fd.clone())
.cloned()
.ok_or(Error::new(EBADF))
}
+12 -11
View File
@@ -61,8 +61,9 @@ impl UnmapResult {
return Ok(());
};
let (scheme_id, number) = match description.write() {
ref desc => (desc.scheme, desc.number),
let (scheme_id, number) = {
let desc = description.write();
(desc.scheme, desc.number)
};
let scheme_opt = scheme::schemes(token.token()).get(scheme_id).cloned();
@@ -177,7 +178,7 @@ impl AddrSpaceWrapper {
} => continue,
Provider::PhysBorrowed { base } => Grant::physmap(
base.clone(),
base,
PageSpan::new(grant_base, grant_info.page_count),
grant_info.flags,
&mut new.inner.get_mut().table.utable,
@@ -221,7 +222,7 @@ impl AddrSpaceWrapper {
src_base,
..
} => Grant::borrow_grant(
Arc::clone(&address_space),
Arc::clone(address_space),
src_base,
grant_base,
grant_info,
@@ -1995,9 +1996,7 @@ impl Grant {
Provider::AllocatedShared { .. } => Provider::AllocatedShared {
is_pinned_userscheme_borrow: false,
},
Provider::PhysBorrowed { base } => {
Provider::PhysBorrowed { base: base.clone() }
}
Provider::PhysBorrowed { base } => Provider::PhysBorrowed { base },
Provider::FmapBorrowed { ref file_ref, .. } => Provider::FmapBorrowed {
file_ref: file_ref.clone(),
pin_refcount: 0,
@@ -2097,7 +2096,7 @@ impl GrantInfo {
)
}
pub fn can_extract(&self, unpin: bool) -> bool {
!(self.is_pinned() && !unpin)
(!self.is_pinned() || unpin)
| matches!(
self.provider,
Provider::Allocated {
@@ -2617,8 +2616,9 @@ fn correct_inner<'l>(
drop(flusher);
drop(addr_space_guard);
let (scheme_id, scheme_number) = match file_ref.description.read() {
ref desc => (desc.scheme, desc.number),
let (scheme_id, scheme_number) = {
let desc = &file_ref.description.read();
(desc.scheme, desc.number)
};
let user_inner = scheme::schemes(token.token())
.get(scheme_id)
@@ -2742,7 +2742,7 @@ fn handle_free_action(base: Frame, phys_contiguous_count: Option<NonZeroUsize>)
let Some(info) = get_page_info(base) else {
return;
};
if info.remove_ref() == None {
if info.remove_ref().is_none() {
unsafe {
deallocate_frame(base);
}
@@ -2800,6 +2800,7 @@ impl<'guard, 'addrsp> Flusher<'guard, 'addrsp> {
pub fn flush(&mut self) {
let pages = core::mem::take(&mut self.state.pagequeue);
#[expect(clippy::bool_comparison)]
if pages.is_empty() && core::mem::replace(&mut self.state.dirty, false) == false {
return;
}
+3 -5
View File
@@ -73,14 +73,12 @@ pub use self::arch::empty_cr3;
static CONTEXTS: RwLock<L1, BTreeSet<ContextRef>> = RwLock::new(BTreeSet::new());
/// Get the global schemes list, const
pub fn contexts<'a>(token: LockToken<'a, L0>) -> RwLockReadGuard<'a, L1, BTreeSet<ContextRef>> {
pub fn contexts(token: LockToken<'_, L0>) -> RwLockReadGuard<'_, L1, BTreeSet<ContextRef>> {
CONTEXTS.read(token)
}
/// Get the global schemes list, mutable
pub fn contexts_mut<'a>(
token: LockToken<'a, L0>,
) -> RwLockWriteGuard<'a, L1, BTreeSet<ContextRef>> {
pub fn contexts_mut(token: LockToken<'_, L0>) -> RwLockWriteGuard<'_, L1, BTreeSet<ContextRef>> {
CONTEXTS.write(token)
}
@@ -115,7 +113,7 @@ pub fn init(token: &mut CleanLockToken) {
pub fn current() -> Arc<ContextLock> {
PercpuBlock::current()
.switch_internals
.with_context(|context| Arc::clone(context))
.with_context(Arc::clone)
}
pub fn try_current() -> Option<Arc<ContextLock>> {
PercpuBlock::current()
+4 -5
View File
@@ -1,6 +1,6 @@
///! This module provides a context-switching mechanism that utilizes a simple round-robin scheduler.
///! The scheduler iterates over available contexts, selecting the next context to run, while
///! handling process states and synchronization.
//! This module provides a context-switching mechanism that utilizes a simple round-robin scheduler.
//! The scheduler iterates over available contexts, selecting the next context to run, while
//! handling process states and synchronization.
use core::{
cell::{Cell, RefCell},
hint, mem,
@@ -16,7 +16,6 @@ use crate::{
cpu_set::LogicalCpuId,
cpu_stats,
percpu::PercpuBlock,
ptrace,
sync::CleanLockToken,
time,
};
@@ -208,7 +207,7 @@ pub fn switch(token: &mut CleanLockToken) -> SwitchResult {
// Check if the context is runnable and can be switched to.
if let UpdateResult::CanSwitch =
unsafe { update_runnable(&mut *next_context_guard, cpu_id) }
unsafe { update_runnable(&mut next_context_guard, cpu_id) }
{
// Store locks for previous and next context and break out from loop
// for the switch
+1 -1
View File
@@ -30,7 +30,7 @@ fn init_registry() -> Mutex<L1, Registry> {
}
/// Get the global timeouts list
fn registry<'a>(token: LockToken<'a, L0>) -> MutexGuard<'a, L1, Registry> {
fn registry(token: LockToken<'_, L0>) -> MutexGuard<'_, L1, Registry> {
REGISTRY.call_once(init_registry).lock(token)
}
+12 -16
View File
@@ -1,6 +1,7 @@
use core::sync::atomic::{AtomicUsize, Ordering};
use alloc::string::{String, ToString};
use core::{
fmt::Display,
sync::atomic::{AtomicUsize, Ordering},
};
use crate::CPU_COUNT;
@@ -60,12 +61,10 @@ fn parts(id: LogicalCpuId) -> (usize, u32) {
}
impl LogicalCpuSet {
pub const fn empty() -> Self {
const ZEROES: AtomicUsize = AtomicUsize::new(0);
Self([ZEROES; SET_WORDS])
Self([const { AtomicUsize::new(0) }; SET_WORDS])
}
pub const fn all() -> Self {
const ONES: AtomicUsize = AtomicUsize::new(!0);
Self([ONES; SET_WORDS])
Self([const { AtomicUsize::new(!0) }; SET_WORDS])
}
pub fn contains(&mut self, id: LogicalCpuId) -> bool {
let (word, bit) = parts(id);
@@ -91,7 +90,7 @@ impl LogicalCpuSet {
// TODO: Will this be optimized away?
self.0.iter_mut().enumerate().flat_map(move |(i, w)| {
(0..usize::BITS).filter_map(move |b| {
if *w.get_mut() & 1 << b != 0 {
if *w.get_mut() & (1 << b) != 0 {
Some(LogicalCpuId::new(i as u32 * usize::BITS + b))
} else {
None
@@ -101,27 +100,24 @@ impl LogicalCpuSet {
}
}
impl ToString for LogicalCpuSet {
fn to_string(&self) -> String {
use core::fmt::Write;
impl Display for LogicalCpuSet {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let cpu_count = crate::cpu_count();
let mut ret = String::new();
let raw = self.to_raw();
let words = raw.get(..(cpu_count / usize::BITS) as usize).unwrap_or(&[]);
for (i, word) in words.iter().enumerate() {
if i != 0 {
write!(ret, "_").unwrap();
write!(f, "_")?;
}
let word = if i == words.len() - 1 {
*word & ((1_usize << (cpu_count % usize::BITS)) - 1)
} else {
*word
};
write!(ret, "{word:x}").unwrap();
write!(f, "{word:x}")?;
}
ret
Ok(())
}
}
+7 -7
View File
@@ -136,14 +136,14 @@ impl CpuStatsData {
}
}
impl Into<CpuStatsData> for &CpuStats {
fn into(self) -> CpuStatsData {
impl From<&CpuStats> for CpuStatsData {
fn from(val: &CpuStats) -> Self {
CpuStatsData {
user: self.user.load(Ordering::Relaxed),
nice: self.nice.load(Ordering::Relaxed),
kernel: self.kernel.load(Ordering::Relaxed),
idle: self.idle.load(Ordering::Relaxed),
irq: self.irq.load(Ordering::Relaxed),
user: val.user.load(Ordering::Relaxed),
nice: val.nice.load(Ordering::Relaxed),
kernel: val.kernel.load(Ordering::Relaxed),
idle: val.idle.load(Ordering::Relaxed),
irq: val.irq.load(Ordering::Relaxed),
}
}
}
+11 -11
View File
@@ -87,31 +87,31 @@ where
//TODO: Cleanup
// FIXME: Fix UB if unaligned
// Disable all interrupts
(&mut *addr_of_mut!(self.int_en)).write(0x00.into());
(*addr_of_mut!(self.int_en)).write(0x00.into());
// Set baud rate divisor
(&mut *addr_of_mut!(self.line_ctrl)).write(0x80.into());
(*addr_of_mut!(self.line_ctrl)).write(0x80.into());
// Set divisor to 1 (115200 baud)
(&mut *addr_of_mut!(self.data)).write(0x01.into());
(&mut *addr_of_mut!(self.int_en)).write(0x00.into());
(*addr_of_mut!(self.data)).write(0x01.into());
(*addr_of_mut!(self.int_en)).write(0x00.into());
// Use 8 data bits, no parity, one stop bit
(&mut *addr_of_mut!(self.line_ctrl)).write(0x03.into());
(*addr_of_mut!(self.line_ctrl)).write(0x03.into());
// Enable and clear FIFOs with 14-byte threshold
(&mut *addr_of_mut!(self.fifo_ctrl)).write(0xC7.into());
(*addr_of_mut!(self.fifo_ctrl)).write(0xC7.into());
// Enable loopback
(&mut *addr_of_mut!(self.modem_ctrl)).write(0x10.into());
(*addr_of_mut!(self.modem_ctrl)).write(0x10.into());
// Perform loopback test with even/odd pattern
for &byte in &[0x55, 0xAA] {
(&mut *addr_of_mut!(self.data)).write(byte.into());
if (&mut *addr_of_mut!(self.data)).read() != byte.into() {
(*addr_of_mut!(self.data)).write(byte.into());
if (*addr_of_mut!(self.data)).read() != byte.into() {
return Err(());
}
}
// Enable DTR, RTS, OUT1, and OUT2, disable loopback
(&mut *addr_of_mut!(self.modem_ctrl)).write(0x0F.into());
(*addr_of_mut!(self.modem_ctrl)).write(0x0F.into());
// Enable receive interrupt
(&mut *addr_of_mut!(self.int_en)).write(0x01.into());
(*addr_of_mut!(self.int_en)).write(0x01.into());
}
Ok(())
+2 -2
View File
@@ -117,7 +117,7 @@ pub struct SerialPort {
impl SerialPort {
pub const fn new(base: usize, cts_event_walkaround: bool) -> SerialPort {
SerialPort {
base: base,
base,
data_reg: 0x00,
rcv_stat_reg: 0x04,
flag_reg: 0x18,
@@ -133,7 +133,7 @@ impl SerialPort {
dma_ctrl_reg: 0x48,
ifls: 0x12, // RX4_8 | TX4_8
fifo_size: 32,
cts_event_walkaround: cts_event_walkaround,
cts_event_walkaround,
}
}
+3 -3
View File
@@ -94,12 +94,12 @@ fn init_queues() -> RwLock<L1, EventQueueList> {
}
/// Get the event queues list, const
pub fn queues<'a>(token: LockToken<'a, L0>) -> RwLockReadGuard<'a, L1, EventQueueList> {
pub fn queues(token: LockToken<'_, L0>) -> RwLockReadGuard<'_, L1, EventQueueList> {
QUEUES.call_once(init_queues).read(token)
}
/// Get the event queues list, mutable
pub fn queues_mut<'a>(token: LockToken<'a, L0>) -> RwLockWriteGuard<'a, L1, EventQueueList> {
pub fn queues_mut(token: LockToken<'_, L0>) -> RwLockWriteGuard<'_, L1, EventQueueList> {
QUEUES.call_once(init_queues).write(token)
}
@@ -138,7 +138,7 @@ pub fn registry_mut() -> spin::RwLockWriteGuard<'static, Registry> {
pub fn register(reg_key: RegKey, queue_key: QueueKey, flags: EventFlags) {
let mut registry = registry_mut();
let entry = registry.entry(reg_key).or_insert_with(|| HashMap::new());
let entry = registry.entry(reg_key).or_default();
if flags.is_empty() {
entry.remove(&queue_key);
+1 -1
View File
@@ -67,7 +67,7 @@ impl<'a> Writer<'a> {
}
}
impl<'a> fmt::Write for Writer<'a> {
impl fmt::Write for Writer<'_> {
fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
self.write(s.as_bytes(), true);
Ok(())
+2 -2
View File
@@ -17,8 +17,8 @@
#![allow(clippy::or_fun_call)]
// This is needed in some cases, like for syscall
#![allow(clippy::too_many_arguments)]
// There is no harm in this being done
#![allow(clippy::useless_format)]
// Used to allow stuff like 1 << 0 and 1 * 1024 * 1024
#![allow(clippy::identity_op)]
// TODO: address ocurrances and then deny
#![warn(clippy::not_unsafe_ptr_arg_deref)]
// TODO: address ocurrances and then deny
+7 -10
View File
@@ -74,15 +74,12 @@ pub fn allocate_p2frame_complex(
) -> Option<(Frame, usize)> {
let mut freelist = FREELIST.lock();
let Some((frame_order, frame)) = freelist
let (frame_order, frame) = freelist
.for_orders
.iter()
.enumerate()
.skip(min_order as usize)
.find_map(|(i, f)| f.map(|f| (i as u32, f)))
else {
return None;
};
.find_map(|(i, f)| f.map(|f| (i as u32, f)))?;
let info = get_page_info(frame)
.unwrap_or_else(|| panic!("no page info for allocated frame {frame:?}"))
@@ -183,7 +180,7 @@ pub unsafe fn deallocate_p2frame(orig_frame: Frame, order: u32) {
break;
}
debug_assert!(
!(sib_info.next().order() > merge_order),
(sib_info.next().order() <= merge_order),
"sibling page has unaligned order or contains current page"
);
//info!("MERGED {lo:?} WITH {hi:?} ORDER {order}");
@@ -195,7 +192,7 @@ pub unsafe fn deallocate_p2frame(orig_frame: Frame, order: u32) {
debug_assert!(sib_info
.next()
.frame()
.map_or(true, |f| f.is_aligned_to_order(merge_order)));
.is_none_or(|f| f.is_aligned_to_order(merge_order)));
debug_assert_eq!(sib_info.next().order(), merge_order);
freelist.for_orders[merge_order as usize] = sib_info.next().frame();
}
@@ -385,7 +382,7 @@ impl Drop for RaiiFrame {
if get_page_info(self.inner)
.expect("RaiiFrame lacking PageInfo")
.remove_ref()
== None
.is_none()
{
unsafe {
deallocate_frame(self.inner);
@@ -866,7 +863,7 @@ impl PageInfoFree<'_> {
fn set_next(&self, next: P2Frame) {
debug_assert!(next
.frame()
.map_or(true, |f| f.is_aligned_to_order(next.order())));
.is_none_or(|f| f.is_aligned_to_order(next.order())));
self.next.store(next.0, Ordering::Relaxed)
}
fn prev(&self) -> P2Frame {
@@ -875,7 +872,7 @@ impl PageInfoFree<'_> {
fn set_prev(&self, prev: P2Frame) {
debug_assert!(prev
.frame()
.map_or(true, |f| f.is_aligned_to_order(prev.order())));
.is_none_or(|f| f.is_aligned_to_order(prev.order())));
self.prev.store(prev.0, Ordering::Relaxed)
}
fn mark_used(&self) {
+7 -6
View File
@@ -47,9 +47,8 @@ pub struct PercpuBlock {
pub stats: CpuStats,
}
const NULL: AtomicPtr<PercpuBlock> = AtomicPtr::new(core::ptr::null_mut());
static ALL_PERCPU_BLOCKS: [AtomicPtr<PercpuBlock>; MAX_CPU_COUNT as usize] =
[NULL; MAX_CPU_COUNT as usize];
[const { AtomicPtr::new(core::ptr::null_mut()) }; MAX_CPU_COUNT as usize];
#[allow(unused)]
pub unsafe fn init_tlb_shootdown(id: LogicalCpuId, block: *mut PercpuBlock) {
@@ -89,6 +88,7 @@ pub fn shootdown_tlb_ipi(target: Option<LogicalCpuId>) {
warn!("Trying to TLB shootdown a CPU that doesn't exist or isn't initialized.");
return;
};
#[expect(clippy::bool_comparison)]
while percpublock
.wants_tlb_shootdown
.swap(true, Ordering::Release)
@@ -101,7 +101,7 @@ pub fn shootdown_tlb_ipi(target: Option<LogicalCpuId>) {
}
}
crate::ipi::ipi_single(crate::ipi::IpiKind::Tlb, &percpublock);
crate::ipi::ipi_single(crate::ipi::IpiKind::Tlb, percpublock);
} else {
for id in 0..crate::cpu_count() {
// TODO: Optimize: use global counter and percpu ack counters, send IPI using
@@ -112,6 +112,7 @@ pub fn shootdown_tlb_ipi(target: Option<LogicalCpuId>) {
}
impl PercpuBlock {
pub fn maybe_handle_tlb_shootdown(&self) {
#[expect(clippy::bool_comparison)]
if self.wants_tlb_shootdown.swap(false, Ordering::Relaxed) == false {
return;
}
@@ -121,7 +122,7 @@ impl PercpuBlock {
crate::paging::RmmA::invalidate_all();
}
if let &Some(ref addrsp) = &*self.current_addrsp.borrow() {
if let Some(addrsp) = &*self.current_addrsp.borrow() {
addrsp.tlb_ack.fetch_add(1, Ordering::Release);
}
}
@@ -134,7 +135,7 @@ pub unsafe fn switch_arch_hook() {
let next_addrsp = percpu.new_addrsp_tmp.take();
let retain_pgtbl = match (&*cur_addrsp, &next_addrsp) {
(&Some(ref p), &Some(ref n)) => Arc::ptr_eq(p, n),
(Some(p), Some(n)) => Arc::ptr_eq(p, n),
(Some(_), None) | (None, Some(_)) => false,
(None, None) => true,
};
@@ -142,7 +143,7 @@ pub unsafe fn switch_arch_hook() {
// If we are not switching to a different address space, we can simply return early.
return;
}
if let &Some(ref prev_addrsp) = &*cur_addrsp {
if let Some(prev_addrsp) = &*cur_addrsp {
prev_addrsp
.acquire_read()
.used_by
+1 -1
View File
@@ -300,7 +300,7 @@ impl KernelScheme for AcpiScheme {
Stat {
st_mode: MODE_FILE,
st_size: data.len().try_into().unwrap_or(u64::max_value()),
st_size: data.len().try_into().unwrap_or(u64::MAX),
..Default::default()
}
}
+54 -56
View File
@@ -78,7 +78,7 @@ enum Handle {
Bsp,
}
impl Handle {
fn as_irq_handle<'a>(&'a self) -> Option<(&'a AtomicUsize, u8)> {
fn as_irq_handle(&self) -> Option<(&AtomicUsize, u8)> {
match self {
&Self::Irq { ref ack, irq } => Some((ack, irq)),
_ => None,
@@ -245,63 +245,61 @@ impl crate::scheme::KernelScheme for IrqScheme {
}
(Handle::TopLevel, InternalFlags::POSITIONED)
} else {
if path_str == "bsp" {
(Handle::Bsp, InternalFlags::empty())
} else if path_str.starts_with("cpu-") {
let path_str = &path_str[4..];
let cpu_id = u8::from_str_radix(&path_str[..2], 16).or(Err(Error::new(ENOENT)))?;
let path_str = path_str[2..].trim_end_matches('/');
} else if path_str == "bsp" {
(Handle::Bsp, InternalFlags::empty())
} else if path_str.starts_with("cpu-") {
let path_str = &path_str[4..];
let cpu_id = u8::from_str_radix(&path_str[..2], 16).or(Err(Error::new(ENOENT)))?;
let path_str = path_str[2..].trim_end_matches('/');
if path_str.is_empty() {
(
Handle::Avail(LogicalCpuId::new(cpu_id.into())),
InternalFlags::POSITIONED,
)
} else if path_str.starts_with('/') {
let path_str = &path_str[1..];
Self::open_ext_irq(flags, LogicalCpuId::new(cpu_id.into()), path_str)?
} else {
return Err(Error::new(ENOENT));
}
} else if cfg!(dtb) && path_str.starts_with("phandle-") {
#[cfg(dtb)]
unsafe {
let (phandle_str, path_str) =
path_str[8..].split_once('/').unwrap_or((path_str, ""));
let phandle = usize::from_str(phandle_str).or(Err(Error::new(ENOENT)))?;
if path_str.is_empty() {
let has_any = IRQ_CHIP.irq_iter_for(phandle as u32).next().is_some();
if has_any {
let data = String::new();
(
Handle::Phandle(phandle as u8, data.into_bytes()),
InternalFlags::POSITIONED,
)
} else {
return Err(Error::new(ENOENT));
}
} else {
Self::open_phandle_irq(flags, phandle, path_str)?
}
}
#[cfg(not(dtb))]
panic!("")
} else if let Ok(plain_irq_number) = u8::from_str(path_str) {
if plain_irq_number < BASE_IRQ_COUNT {
(
Handle::Irq {
ack: AtomicUsize::new(0),
irq: plain_irq_number,
},
InternalFlags::empty(),
)
} else {
return Err(Error::new(ENOENT));
}
if path_str.is_empty() {
(
Handle::Avail(LogicalCpuId::new(cpu_id.into())),
InternalFlags::POSITIONED,
)
} else if path_str.starts_with('/') {
let path_str = &path_str[1..];
Self::open_ext_irq(flags, LogicalCpuId::new(cpu_id.into()), path_str)?
} else {
return Err(Error::new(ENOENT));
}
} else if cfg!(dtb) && path_str.starts_with("phandle-") {
#[cfg(dtb)]
unsafe {
let (phandle_str, path_str) =
path_str[8..].split_once('/').unwrap_or((path_str, ""));
let phandle = usize::from_str(phandle_str).or(Err(Error::new(ENOENT)))?;
if path_str.is_empty() {
let has_any = IRQ_CHIP.irq_iter_for(phandle as u32).next().is_some();
if has_any {
let data = String::new();
(
Handle::Phandle(phandle as u8, data.into_bytes()),
InternalFlags::POSITIONED,
)
} else {
return Err(Error::new(ENOENT));
}
} else {
Self::open_phandle_irq(flags, phandle, path_str)?
}
}
#[cfg(not(dtb))]
panic!("")
} else if let Ok(plain_irq_number) = u8::from_str(path_str) {
if plain_irq_number < BASE_IRQ_COUNT {
(
Handle::Irq {
ack: AtomicUsize::new(0),
irq: plain_irq_number,
},
InternalFlags::empty(),
)
} else {
return Err(Error::new(ENOENT));
}
} else {
return Err(Error::new(ENOENT));
};
let fd = NEXT_FD.fetch_add(1, Ordering::Relaxed);
HANDLES.write(token.token()).insert(fd, handle);
@@ -474,14 +472,14 @@ impl crate::scheme::KernelScheme for IrqScheme {
Handle::Avail(cpu_id) => Stat {
st_mode: MODE_DIR | 0o700,
st_size: 0,
st_ino: INO_AVAIL | u64::from(cpu_id.get()) << 32,
st_ino: INO_AVAIL | (u64::from(cpu_id.get()) << 32),
st_nlink: 2,
..Default::default()
},
Handle::Phandle(phandle, ref buf) => Stat {
st_mode: MODE_DIR | 0o700,
st_size: buf.len() as u64,
st_ino: INO_PHANDLE | u64::from(phandle) << 32,
st_ino: INO_PHANDLE | (u64::from(phandle) << 32),
st_nlink: 2,
..Default::default()
},
+1 -1
View File
@@ -91,7 +91,7 @@ impl MemoryScheme {
}
let page = addr_space.acquire_write().mmap(
&addr_space,
addr_space,
(map.address != 0).then_some(span.base),
page_count,
map.flags,
+2 -2
View File
@@ -370,12 +370,12 @@ fn init_schemes() -> RwLock<L1, SchemeList> {
}
/// Get the global schemes list, const
pub fn schemes<'a>(token: LockToken<'a, L0>) -> RwLockReadGuard<'a, L1, SchemeList> {
pub fn schemes(token: LockToken<'_, L0>) -> RwLockReadGuard<'_, L1, SchemeList> {
SCHEMES.call_once(init_schemes).read(token)
}
/// Get the global schemes list, mutable
pub fn schemes_mut<'a>(token: LockToken<'a, L0>) -> RwLockWriteGuard<'a, L1, SchemeList> {
pub fn schemes_mut(token: LockToken<'_, L0>) -> RwLockWriteGuard<'_, L1, SchemeList> {
SCHEMES.call_once(init_schemes).write(token)
}
+37 -50
View File
@@ -55,7 +55,7 @@ fn try_stop_context<T>(
callback: impl FnOnce(&mut Context) -> Result<T>,
) -> Result<T> {
if context::is_current(&context_ref) {
return callback(&mut *context_ref.write(token.token()));
return callback(&mut context_ref.write(token.token()));
}
// Stop process
let (prev_status, mut running) = {
@@ -85,7 +85,7 @@ fn try_stop_context<T>(
"process can't have been restarted, we stopped it!"
);
let ret = callback(&mut *context);
let ret = callback(&mut context);
context.status = prev_status;
@@ -401,11 +401,9 @@ impl KernelScheme for ProcScheme {
token: &mut CleanLockToken,
) -> Result<EventFlags> {
let handles = HANDLES.read(token.token());
let handle = handles.get(&id).ok_or(Error::new(EBADF))?;
let _handle = handles.get(&id).ok_or(Error::new(EBADF))?;
match handle {
_ => Ok(EventFlags::empty()),
}
Ok(EventFlags::empty())
}
fn close(&self, id: usize, token: &mut CleanLockToken) -> Result<()> {
@@ -491,7 +489,7 @@ impl KernelScheme for ProcScheme {
// TODO: Validate flags
let result_base = if consume {
dst_addr_space.r#move(
Some((&addrspace, &mut *src_addr_space)),
Some((addrspace, &mut *src_addr_space)),
src_span,
requested_dst_base,
src_page_count.get(),
@@ -501,15 +499,15 @@ impl KernelScheme for ProcScheme {
} else {
let mut dst_addrsp_guard = dst_addr_space.acquire_write();
dst_addrsp_guard.mmap(
&dst_addr_space,
dst_addr_space,
requested_dst_base,
src_page_count,
map.flags,
&mut notify_files,
|dst_page, _, dst_mapper, flusher| {
Ok(Grant::borrow(
Grant::borrow(
Arc::clone(addrspace),
&mut *src_addr_space,
&mut src_addr_space,
src_span.base,
dst_page,
src_span.count,
@@ -519,7 +517,7 @@ impl KernelScheme for ProcScheme {
true,
true,
false,
)?)
)
},
)?
};
@@ -577,9 +575,8 @@ impl KernelScheme for ProcScheme {
handles.get(&id).ok_or(Error::new(EBADF))?.clone()
};
match handle {
Handle { context, kind } => kind.kreadoff(id, context, buf, offset, token),
}
let Handle { context, kind } = handle;
kind.kreadoff(id, context, buf, offset, token)
}
fn kcall(
&self,
@@ -600,7 +597,7 @@ impl KernelScheme for ProcScheme {
return Err(Error::new(EBADF));
};
let verb: u8 = (*metadata.get(0).ok_or(Error::new(EINVAL))?)
let verb: u8 = (*metadata.first().ok_or(Error::new(EINVAL))?)
.try_into()
.map_err(|_| Error::new(EINVAL))?;
let verb = ProcSchemeVerb::try_from_raw(verb).ok_or(Error::new(EINVAL))?;
@@ -630,9 +627,8 @@ impl KernelScheme for ProcScheme {
handle.clone()
};
match handle {
Handle { context, kind } => kind.kwriteoff(id, context, buf, token),
}
let Handle { context, kind } = handle;
kind.kwriteoff(id, context, buf, token)
}
fn kfstat(&self, id: usize, buffer: UserSliceWo, token: &mut CleanLockToken) -> Result<()> {
let handles = HANDLES.read(token.token());
@@ -776,20 +772,14 @@ impl KernelScheme for ProcScheme {
let page = Page::containing_address(VirtualAddress::new(page_addr));
match addrspace
.acquire_read()
.grants
.contains(page)
.ok_or(Error::new(EINVAL))?
{
(_, info) => {
return Ok(OpenResult::External(
info.file_ref()
.map(|r| Arc::clone(&r.description))
.ok_or(Error::new(EBADF))?,
))
}
}
let read_lock = addrspace.acquire_read();
let (_, info) =
read_lock.grants.contains(page).ok_or(Error::new(EINVAL))?;
return Ok(OpenResult::External(
info.file_ref()
.map(|r| Arc::clone(&r.description))
.ok_or(Error::new(EBADF))?,
));
}
_ => return Err(Error::new(EINVAL)),
@@ -805,15 +795,12 @@ impl KernelScheme for ProcScheme {
}
}
fn extract_scheme_number(fd: usize, token: &mut CleanLockToken) -> Result<(KernelSchemes, usize)> {
let (scheme_id, number) = match &*context::current()
let file_descriptor = context::current()
.read(token.token())
.get_file(FileHandle::from(fd))
.ok_or(Error::new(EBADF))?
.description
.read()
{
desc => (desc.scheme, desc.number),
};
.ok_or(Error::new(EBADF))?;
let desc = file_descriptor.description.read();
let (scheme_id, number) = (desc.scheme, desc.number);
let scheme = scheme::schemes(token.token())
.get(scheme_id)
.ok_or(Error::new(ENODEV))?
@@ -904,7 +891,7 @@ impl ContextHandle {
// Ignore the rare case of floating point
// registers being uninitiated
let _ = context.set_fx_regs(regs);
context.set_fx_regs(regs);
Ok(mem::size_of::<FloatRegisters>())
})
@@ -996,7 +983,7 @@ impl ContextHandle {
*status = Status::Runnable;
Ok(buf.len())
}
_ => return Err(Error::new(EINVAL)),
_ => Err(Error::new(EINVAL)),
},
ContextHandle::Filetable { .. } | ContextHandle::NewFiletable { .. } => {
Err(Error::new(EBADF))
@@ -1024,10 +1011,10 @@ impl ContextHandle {
},
..
} => {
let ft = Arc::clone(&filetable);
let ft = Arc::clone(filetable);
*entry.get_mut() = Handle {
kind: ContextHandle::Filetable {
filetable: Arc::downgrade(&filetable),
filetable: Arc::downgrade(filetable),
data: data.clone(),
},
context: Arc::clone(&context),
@@ -1103,7 +1090,7 @@ impl ContextHandle {
match context_verb {
// TODO: lwp_park/lwp_unpark for bypassing procmgr?
ContextVerb::Unstop | ContextVerb::Stop if !privileged => {
return Err(Error::new(EPERM))
Err(Error::new(EPERM))
}
ContextVerb::Stop => {
let mut guard = context.write(token.token());
@@ -1257,7 +1244,7 @@ impl ContextHandle {
buf.copy_common_bytes_from_slice(src_buf)
}
&ContextHandle::AddrSpace { ref addrspace } => {
ContextHandle::AddrSpace { addrspace } => {
let Ok(offset) = usize::try_from(offset) else {
return Ok(0);
};
@@ -1295,7 +1282,7 @@ impl ContextHandle {
}
ContextHandle::Filetable { data, .. } => read_from(buf, &data, offset),
&ContextHandle::MmapMinAddr(ref addrspace) => {
ContextHandle::MmapMinAddr(addrspace) => {
buf.write_usize(addrspace.acquire_read().mmap_min)?;
Ok(mem::size_of::<usize>())
}
@@ -1339,9 +1326,9 @@ impl ContextHandle {
}
ContextHandle::Attr => {
let mut debug_name = [0; 32];
let (euid, egid, ens, pid, name) = match context.read(token.token()) {
ref c => (c.euid, c.egid, c.ens.get() as u32, c.pid as u32, c.name),
};
let c = &context.read(token.token());
let (euid, egid, ens, pid, name) =
(c.euid, c.egid, c.ens.get() as u32, c.pid as u32, c.name);
let min = name.len().min(debug_name.len());
debug_name[..min].copy_from_slice(&name.as_bytes()[..min]);
buf.copy_common_bytes_from_slice(&ProcSchemeAttrs {
@@ -1368,7 +1355,7 @@ impl ContextHandle {
// TODO: Find a better way to switch address spaces, since they also require switching
// the instruction and stack pointer. Maybe remove `<pid>/regs` altogether and replace it
// with `<pid>/ctx`
_ => return Err(Error::new(EBADF)),
_ => Err(Error::new(EBADF)),
}
}
}
+5 -11
View File
@@ -151,13 +151,10 @@ impl KernelScheme for RootScheme {
handles
.iter()
.find_map(|(_id, handle)| {
match handle {
Handle::Scheme(inner) => {
if path == inner.name.as_ref() {
return Some(inner.clone());
}
if let Handle::Scheme(inner) = handle {
if path == inner.name.as_ref() {
return Some(inner.clone());
}
_ => (),
}
None
})
@@ -248,11 +245,8 @@ impl KernelScheme for RootScheme {
.write(token.token())
.remove(&file)
.ok_or(Error::new(EBADF))?;
match handle {
Handle::Scheme(inner) => {
scheme::schemes_mut(token.token()).remove(inner.scheme_id);
}
_ => (),
if let Handle::Scheme(inner) = handle {
scheme::schemes_mut(token.token()).remove(inner.scheme_id);
}
Ok(())
}
+2 -2
View File
@@ -13,13 +13,13 @@ pub fn resource(token: &mut CleanLockToken) -> Result<Vec<u8>> {
let (contexts, mut token) = contexts.token_split();
for context_lock in contexts.iter().filter_map(|r| r.upgrade()) {
let context = context_lock.read(token.token());
rows.push((context.pid, context.name.clone(), context.status_reason));
rows.push((context.pid, context.name, context.status_reason));
}
}
rows.sort_by_key(|row| row.0);
for row in rows.iter() {
let id: usize = row.0.into();
let id: usize = row.0;
let name = &row.1;
let _ = writeln!(string, "{}: {}", id, name);
+1 -5
View File
@@ -26,11 +26,7 @@ fn inner(fpath_user: UserSliceRw, token: &mut CleanLockToken) -> Result<Vec<u8>>
let (contexts, mut token) = contexts.token_split();
for context_ref in contexts.iter().filter_map(|r| r.upgrade()) {
let context = context_ref.read(token.token());
rows.push((
context.pid,
context.name.clone(),
context.files.read().clone(),
));
rows.push((context.pid, context.name, context.files.read().clone()));
}
}
rows.sort_by_key(|row| row.0);
+3 -5
View File
@@ -68,7 +68,7 @@ static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
static HANDLES: RwLock<L1, HashMap<usize, Handle>> =
RwLock::new(HashMap::with_hasher(DefaultHashBuilder::new()));
const FILES: &[(&'static str, Kind)] = &[
const FILES: &[(&str, Kind)] = &[
("block", Rd(block::resource)),
("context", Rd(context::resource)),
("cpu", Rd(cpu::resource)),
@@ -206,9 +206,7 @@ impl KernelScheme for SysScheme {
.get(&id)
.ok_or(Error::new(EBADF))?
{
Handle::TopLevel | Handle::Resource { data: None, .. } => {
return Err(Error::new(EISDIR))
}
Handle::TopLevel | Handle::Resource { data: None, .. } => Err(Error::new(EISDIR)),
&Handle::Resource {
data: Some(ref data),
..
@@ -267,7 +265,7 @@ impl KernelScheme for SysScheme {
.get(&id)
.ok_or(Error::new(EBADF))?
{
Handle::Resource { .. } => return Err(Error::new(ENOTDIR)),
Handle::Resource { .. } => Err(Error::new(ENOTDIR)),
Handle::TopLevel => {
let mut buf = DirentBuf::new(buf, header_size).ok_or(Error::new(EIO))?;
for (this_idx, (name, _)) in FILES.iter().enumerate().skip(first_index) {
+1 -1
View File
@@ -13,7 +13,7 @@ pub fn resource(token: &mut CleanLockToken) -> Result<Vec<u8>> {
let (contexts, mut token) = contexts.token_split();
for context_ref in contexts.iter().filter_map(|r| r.upgrade()) {
let context = context_ref.read(token.token());
rows.push((context.pid, context.name.clone(), context.current_syscall()));
rows.push((context.pid, context.name, context.current_syscall()));
}
}
rows.sort_by_key(|row| row.0);
+35 -46
View File
@@ -8,7 +8,6 @@ use core::{
mem::size_of,
num::NonZeroUsize,
sync::atomic::{AtomicBool, Ordering},
usize,
};
use slab::Slab;
use spin::{Mutex, RwLock};
@@ -307,11 +306,9 @@ impl UserInner {
{
let current_context = context::current();
{
current_context
.write(token.token())
.block("UserScheme::call")
};
current_context
.write(token.token())
.block("UserScheme::call");
{
let mut states = self.states.lock();
states[sqe.tag as usize] = State::Waiting {
@@ -372,11 +369,9 @@ impl UserInner {
drop(states);
maybe_eintr?;
{
context::current()
.write(token.token())
.block("UserInner::call")
};
context::current()
.write(token.token())
.block("UserInner::call");
}
// spurious wakeup
State::Waiting {
@@ -407,11 +402,9 @@ impl UserInner {
token,
);
event::trigger(self.root_id, self.handle_id, EVENT_READ);
{
context::current()
.write(token.token())
.block("UserInner::call")
};
context::current()
.write(token.token())
.block("UserInner::call");
}
// invalid state
@@ -469,9 +462,9 @@ impl UserInner {
ONE,
PROT_READ,
|dst_page, flags, mapper, flusher| {
Ok(Grant::allocated_shared_one_page(
Grant::allocated_shared_one_page(
tail_frame, dst_page, flags, mapper, flusher, is_pinned,
)?)
)
},
)?
};
@@ -612,9 +605,9 @@ impl UserInner {
&mut Vec::new(),
move |dst_page, page_flags, mapper, flusher| {
let is_pinned = true;
Ok(Grant::allocated_shared_one_page(
Grant::allocated_shared_one_page(
frame, dst_page, page_flags, mapper, flusher, is_pinned,
)?)
)
},
)?;
@@ -664,9 +657,9 @@ impl UserInner {
// unmap them is to respond to the scheme socket.
let is_pinned_userscheme_borrow = true;
Ok(Grant::borrow(
Grant::borrow(
Arc::clone(&cur_space_lock),
&mut *cur_space_lock.acquire_write(),
&mut cur_space_lock.acquire_write(),
first_middle_src_page,
dst_page,
middle_page_count.get(),
@@ -676,7 +669,7 @@ impl UserInner {
eager,
allow_phys,
is_pinned_userscheme_borrow,
)?)
)
},
)?;
}
@@ -709,9 +702,9 @@ impl UserInner {
&mut Vec::new(),
move |dst_page, page_flags, mapper, flusher| {
let is_pinned = true;
Ok(Grant::allocated_shared_one_page(
Grant::allocated_shared_one_page(
frame, dst_page, page_flags, mapper, flusher, is_pinned,
)?)
)
},
)?;
@@ -751,7 +744,7 @@ impl UserInner {
let block = !(nonblock || self.unmounting.load(Ordering::SeqCst));
if self.v2 {
return match self
match self
.todo
.receive_into_user(buf, block, "UserInner::read (v2)", token)
{
@@ -762,7 +755,7 @@ impl UserInner {
// If there were no requests and O_NONBLOCK was used (EAGAIN), or some other error
// occurred, return that.
Err(error) => Err(error),
};
}
} else {
let mut bytes_read = 0;
@@ -983,7 +976,7 @@ impl UserInner {
}),
token,
)?,
ParsedCqe::ResponseWithMultipleFds { tag, num_fds } => {
ParsedCqe::ResponseWithMultipleFds { tag, num_fds: _ } => {
self.respond(tag, Response::MultipleFds(None), token)?;
}
ParsedCqe::ObtainFd {
@@ -1081,11 +1074,11 @@ impl UserInner {
{
let mut context = context.write(token.token());
match context.status {
Status::HardBlocked {
reason: HardBlockedReason::AwaitingMmap { .. },
} => context.status = Status::Runnable,
_ => (),
if let Status::HardBlocked {
reason: HardBlockedReason::AwaitingMmap { .. },
} = context.status
{
context.status = Status::Runnable
}
context.fmap_ret = Some(Frame::containing(frame));
}
@@ -1150,9 +1143,7 @@ impl UserInner {
match context.upgrade() {
Some(context) => {
{
context.write(token.token()).unblock()
};
context.write(token.token()).unblock();
*o = State::Responded(response);
}
_ => {
@@ -1741,12 +1732,10 @@ impl KernelScheme for UserScheme {
fn fchown(&self, file: usize, uid: u32, gid: u32, token: &mut CleanLockToken) -> Result<()> {
{
match context::current().read(token.token()) {
ref cx => {
if cx.euid != 0 && (uid != cx.euid || gid != cx.egid) {
return Err(Error::new(EPERM));
}
}
let ctx = context::current();
let cx = &ctx.read(token.token());
if cx.euid != 0 && (uid != cx.euid || gid != cx.egid) {
return Err(Error::new(EPERM));
}
}
@@ -2146,7 +2135,7 @@ impl KernelScheme for UserScheme {
let len = dst.len().min(metadata.len());
dst[..len].copy_from_slice(&metadata[..len]);
}
let res = inner.call_extended_inner(None, sqe, &mut address.span(), token)?;
let res = inner.call_extended_inner(None, sqe, address.span(), token)?;
match res {
Response::Regular(res, _) => Error::demux(res),
@@ -2263,7 +2252,7 @@ fn uid_gid_hack_merge([uid, gid]: [u32; 2]) -> u64 {
u64::from(uid) | (u64::from(gid) << 32)
}
fn current_uid_gid(token: &mut CleanLockToken) -> [u32; 2] {
match context::current().read(token.token()) {
ref p => [p.euid, p.egid],
}
let ctx = context::current();
let p = &ctx.read(token.token());
[p.euid, p.egid]
}
+4 -7
View File
@@ -102,7 +102,7 @@ impl MemoryMap {
}
fn iter(&self) -> Iter<MemoryEntry> {
return self.entries[0..self.size].iter();
self.entries[0..self.size].iter()
}
pub fn free(&self) -> impl Iterator<Item = &MemoryEntry> {
@@ -386,7 +386,7 @@ unsafe fn map_memory<A: Arch>(areas: &[MemoryArea], mut bump_allocator: &mut Bum
let (phys, virt, size) = *FRAMEBUFFER.lock();
let pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
let pages = size.div_ceil(PAGE_SIZE);
for i in 0..pages {
let phys = PhysicalAddress::new(phys + i * PAGE_SIZE);
let virt = VirtualAddress::new(virt + i * PAGE_SIZE);
@@ -449,7 +449,7 @@ pub unsafe fn init(args: &KernelArgs, low_limit: Option<usize>, high_limit: Opti
}
}
info!("Memory: {} MB", (size + (MEGABYTE - 1)) / MEGABYTE);
info!("Memory: {} MB", size.div_ceil(MEGABYTE));
// Create a basic allocator for the first pages
let mut bump_allocator = BumpAllocator::<CurrentRmmArch>::new(areas, 0);
@@ -458,10 +458,7 @@ pub unsafe fn init(args: &KernelArgs, low_limit: Option<usize>, high_limit: Opti
// Create the physical memory map
let offset = bump_allocator.offset();
info!(
"Permanently used: {} KB",
(offset + (KILOBYTE - 1)) / KILOBYTE
);
info!("Permanently used: {} KB", offset.div_ceil(KILOBYTE));
crate::memory::init_mm(bump_allocator);
}
+9 -12
View File
@@ -225,13 +225,10 @@ impl<L: Level, T> Mutex<L, T> {
&'a self,
lock_token: LockToken<'a, LP>,
) -> Option<MutexGuard<'a, L, T>> {
match self.inner.try_lock() {
Some(inner) => Some(MutexGuard {
inner,
lock_token: LockToken::downgraded(lock_token),
}),
None => None,
}
self.inner.try_lock().map(|inner| MutexGuard {
inner,
lock_token: LockToken::downgraded(lock_token),
})
}
/// Consumes this Mutex, returning the underlying data.
@@ -356,7 +353,7 @@ pub struct RwLockWriteGuard<'a, L: Level, T> {
lock_token: LockToken<'a, L>,
}
impl<'a, L: Level, T> RwLockWriteGuard<'a, L, T> {
impl<L: Level, T> RwLockWriteGuard<'_, L, T> {
/// Split the guard into two parts, the first a mutable reference to the held content
/// the second a [`LockToken`] that can be used for further locking
pub fn token_split(&mut self) -> (&mut T, LockToken<'_, L>) {
@@ -364,7 +361,7 @@ impl<'a, L: Level, T> RwLockWriteGuard<'a, L, T> {
}
}
impl<'a, L: Level, T> core::ops::Deref for RwLockWriteGuard<'a, L, T> {
impl<L: Level, T> core::ops::Deref for RwLockWriteGuard<'_, L, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
@@ -372,7 +369,7 @@ impl<'a, L: Level, T> core::ops::Deref for RwLockWriteGuard<'a, L, T> {
}
}
impl<'a, L: Level, T> core::ops::DerefMut for RwLockWriteGuard<'a, L, T> {
impl<L: Level, T> core::ops::DerefMut for RwLockWriteGuard<'_, L, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner.deref_mut()
}
@@ -384,7 +381,7 @@ pub struct RwLockReadGuard<'a, L: Level, T> {
lock_token: LockToken<'a, L>,
}
impl<'a, L: Level, T> RwLockReadGuard<'a, L, T> {
impl<L: Level, T> RwLockReadGuard<'_, L, T> {
/// Split the guard into two parts, the first a reference to the held content
/// the second a [`LockToken`] that can be used for further locking
pub fn token_split(&mut self) -> (&T, LockToken<'_, L>) {
@@ -392,7 +389,7 @@ impl<'a, L: Level, T> RwLockReadGuard<'a, L, T> {
}
}
impl<'a, L: Level, T> core::ops::Deref for RwLockReadGuard<'a, L, T> {
impl<L: Level, T> core::ops::Deref for RwLockReadGuard<'_, L, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
+2 -8
View File
@@ -82,16 +82,10 @@ impl<T> WaitQueue<T> {
let (s1, s2) = inner.as_slices();
let s1_bytes = unsafe {
core::slice::from_raw_parts(
s1.as_ptr().cast::<u8>(),
s1.len() * core::mem::size_of::<T>(),
)
core::slice::from_raw_parts(s1.as_ptr().cast::<u8>(), core::mem::size_of_val(s1))
};
let s2_bytes = unsafe {
core::slice::from_raw_parts(
s2.as_ptr().cast::<u8>(),
s2.len() * core::mem::size_of::<T>(),
)
core::slice::from_raw_parts(s2.as_ptr().cast::<u8>(), core::mem::size_of_val(s2))
};
let mut bytes_copied = buf.copy_common_bytes_from_slice(s1_bytes)?;
+6 -4
View File
@@ -1,5 +1,5 @@
use alloc::{string::String, vec::Vec};
use core::{ascii, mem};
use core::{ascii, fmt::Debug, mem};
use super::{
copy_path_to_buf,
@@ -13,7 +13,7 @@ use crate::{sync::CleanLockToken, syscall::error::Result};
struct ByteStr<'a>(&'a [u8]);
impl<'a> ::core::fmt::Debug for ByteStr<'a> {
impl Debug for ByteStr<'_> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "\"")?;
for i in self.0 {
@@ -61,13 +61,13 @@ pub fn format_call(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) -
SYS_DUP => format!(
"dup({}, {:?})",
b,
debug_buf(c, d).as_ref().map(|b| ByteStr(&*b)),
debug_buf(c, d).as_ref().map(|b| ByteStr(b)),
),
SYS_DUP2 => format!(
"dup2({}, {}, {:?})",
b,
c,
debug_buf(d, e).as_ref().map(|b| ByteStr(&*b)),
debug_buf(d, e).as_ref().map(|b| ByteStr(b)),
),
SYS_SENDFD => format!("sendfd({}, {}, {:#0x} {:#0x} {:#0x})", b, c, d, e, f,),
SYS_READ => format!("read({}, {:#X}, {})", b, c, d),
@@ -222,6 +222,8 @@ pub fn debug_start([a, b, c, d, e, f]: [usize; 6], token: &mut CleanLockToken) {
return;
}
#[expect(clippy::overly_complex_bool_expr)]
#[expect(clippy::needless_bool)]
let do_debug = if false
&& crate::context::current()
.read(token.token())
+31 -33
View File
@@ -76,8 +76,10 @@ fn is_legacy(path_buf: &String) -> bool {
/// Open syscall
pub fn open(raw_path: UserSliceRo, flags: usize, token: &mut CleanLockToken) -> Result<FileHandle> {
let (pid, uid, gid, scheme_ns) = match context::current().read(token.token()) {
ref cx => (cx.pid.into(), cx.euid, cx.egid, cx.ens),
let (pid, uid, gid, scheme_ns) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.pid, cx.euid, cx.egid, cx.ens)
};
// TODO: BorrowedHtBuf!
@@ -91,7 +93,7 @@ pub fn open(raw_path: UserSliceRo, flags: usize, token: &mut CleanLockToken) ->
// Display a deprecation warning for any usage of the legacy scheme syntax (scheme:/path)
// FIXME remove entries from this list as the respective programs get updated
if path_buf.contains(':') && !is_legacy(&path_buf) {
let name = context::current().read(token.token()).name.clone();
let name = context::current().read(token.token()).name;
if name.contains("cosmic") && (path_buf == "event:" || path_buf.starts_with("time:")) {
// FIXME cosmic apps likely need crate updates
} else {
@@ -200,8 +202,10 @@ pub fn openat(
}
/// rmdir syscall
pub fn rmdir(raw_path: UserSliceRo, token: &mut CleanLockToken) -> Result<()> {
let (scheme_ns, caller_ctx) = match context::current().read(token.token()) {
ref cx => (cx.ens, cx.caller_ctx()),
let (scheme_ns, caller_ctx) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.ens, cx.caller_ctx())
};
/*
@@ -224,8 +228,10 @@ pub fn rmdir(raw_path: UserSliceRo, token: &mut CleanLockToken) -> Result<()> {
/// Unlink syscall
pub fn unlink(raw_path: UserSliceRo, token: &mut CleanLockToken) -> Result<()> {
let (scheme_ns, caller_ctx) = match context::current().read(token.token()) {
ref cx => (cx.ens, cx.caller_ctx()),
let (scheme_ns, caller_ctx) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.ens, cx.caller_ctx())
};
/*
let mut path_buf = BorrowedHtBuf::head()?;
@@ -424,14 +430,9 @@ fn fdwrite_inner(
let (scheme, number) = {
let current_lock = context::current();
let current = current_lock.read(token.token());
match current
.get_file(socket)
.ok_or(Error::new(EBADF))?
.description
.read()
{
ref desc => (desc.scheme, desc.number),
}
let file_descriptor = current.get_file(socket).ok_or(Error::new(EBADF))?;
let desc = &file_descriptor.description.read();
(desc.scheme, desc.number)
};
let scheme = scheme::schemes(token.token())
.get(scheme)
@@ -483,14 +484,9 @@ fn call_fdread(
let (scheme, number) = {
let current_lock = context::current();
let current = current_lock.read(token.token());
match current
.get_file(fd)
.ok_or(Error::new(EBADF))?
.description
.read()
{
ref desc => (desc.scheme, desc.number),
}
let file_descriptor = current.get_file(fd).ok_or(Error::new(EBADF))?;
let desc = file_descriptor.description.read();
(desc.scheme, desc.number)
};
let scheme = scheme::schemes(token.token())
.get(scheme)
@@ -588,8 +584,10 @@ pub fn fcntl(fd: FileHandle, cmd: usize, arg: usize, token: &mut CleanLockToken)
}
pub fn flink(fd: FileHandle, raw_path: UserSliceRo, token: &mut CleanLockToken) -> Result<()> {
let (caller_ctx, scheme_ns) = match context::current().read(token.token()) {
ref cx => (cx.caller_ctx(), cx.ens),
let (caller_ctx, scheme_ns) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.caller_ctx(), cx.ens)
};
let file = context::current()
.read(token.token())
@@ -622,8 +620,10 @@ pub fn flink(fd: FileHandle, raw_path: UserSliceRo, token: &mut CleanLockToken)
}
pub fn frename(fd: FileHandle, raw_path: UserSliceRo, token: &mut CleanLockToken) -> Result<()> {
let (caller_ctx, scheme_ns) = match context::current().read(token.token()) {
ref cx => (cx.caller_ctx(), cx.ens),
let (caller_ctx, scheme_ns) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.caller_ctx(), cx.ens)
};
let file = context::current()
.read(token.token())
@@ -844,9 +844,8 @@ pub fn sys_read(fd: FileHandle, buf: UserSliceWo, token: &mut CleanLockToken) ->
))
})?;
if desc.internal_flags.contains(InternalFlags::POSITIONED) {
match desc_arc.write().offset {
ref mut offset => *offset = offset.saturating_add(bytes_read as u64),
}
let offset = &mut desc_arc.write().offset;
*offset = offset.saturating_add(bytes_read as u64)
}
Ok(bytes_read)
}
@@ -865,9 +864,8 @@ pub fn sys_write(fd: FileHandle, buf: UserSliceRo, token: &mut CleanLockToken) -
))
})?;
if desc.internal_flags.contains(InternalFlags::POSITIONED) {
match desc_arc.write().offset {
ref mut offset => *offset = offset.saturating_add(bytes_written as u64),
}
let offset = &mut desc_arc.write().offset;
*offset = offset.saturating_add(bytes_written as u64)
}
Ok(bytes_written)
}
+2 -4
View File
@@ -83,7 +83,7 @@ pub fn futex(
let addr_space_guard = current_addrsp.acquire_read();
let target_virtaddr = VirtualAddress::new(addr);
let target_physaddr = validate_and_translate_virt(&*addr_space_guard, target_virtaddr)
let target_physaddr = validate_and_translate_virt(&addr_space_guard, target_virtaddr)
.ok_or(Error::new(EFAULT))?;
match op {
@@ -128,9 +128,7 @@ pub fn futex(
return Err(Error::new(EINVAL));
}
(
u64::from(unsafe {
(*(addr as *const AtomicU64)).load(Ordering::SeqCst)
}),
unsafe { (*(addr as *const AtomicU64)).load(Ordering::SeqCst) },
val as u64,
)
}
+1 -1
View File
@@ -233,7 +233,7 @@ pub fn syscall(
),
SYS_MREMAP => mremap(b, c, d, e, f, token),
_ => return Err(Error::new(ENOSYS)),
_ => Err(Error::new(ENOSYS)),
}
}
+4 -2
View File
@@ -8,8 +8,10 @@ use super::{
};
pub fn mkns(mut user_buf: UserSliceRo, token: &mut CleanLockToken) -> Result<usize> {
let (uid, from) = match context::current().read(token.token()) {
ref cx => (cx.euid, cx.ens),
let (uid, from) = {
let ctx = context::current();
let cx = &ctx.read(token.token());
(cx.euid, cx.ens)
};
// TODO: Lift this restriction later?
+7 -8
View File
@@ -52,7 +52,7 @@ pub fn exit_this_context(excp: Option<syscall::Exception>, token: &mut CleanLock
guard.owner_proc_id
};
if let Some(owner) = owner {
let _ = event::trigger(
event::trigger(
GlobalSchemes::Proc.scheme_id(),
owner.get(),
EventFlags::EVENT_READ,
@@ -129,15 +129,14 @@ pub unsafe fn usermode_bootstrap(bootstrap: &Bootstrap, token: &mut CleanLockTok
// Start in a minimal environment without any stack.
match context::current()
.write(token.token())
let ctx = context::current();
let mut lock = ctx.write(token.token());
let regs = &mut lock
.regs_mut()
.expect("bootstrap needs registers to be available")
.expect("bootstrap needs registers to be available");
{
ref mut regs => {
regs.init();
regs.set_instr_pointer(bootstrap_entry.try_into().unwrap());
}
regs.init();
regs.set_instr_pointer(bootstrap_entry.try_into().unwrap());
}
}
+1 -1
View File
@@ -159,7 +159,7 @@ impl<const WRITE: bool> UserSlice<true, WRITE> {
impl<const READ: bool> UserSlice<READ, true> {
pub fn copy_from_slice(self, slice: &[u8]) -> Result<()> {
// A zero sized slice will like have 0x1 as address
debug_assert!(is_kernel_mem(slice) || slice.len() == 0);
debug_assert!(is_kernel_mem(slice) || slice.is_empty());
if self.len != slice.len() {
return Err(Error::new(EINVAL));