Fix clippy and compiler warings

This commit is contained in:
Jianfeng Jiang 2023-09-04 11:04:42 +08:00 committed by Tate, Hongliang Tian
parent 20a90426a0
commit 9ca64c281e
156 changed files with 539 additions and 603 deletions

View File

@ -57,7 +57,7 @@ docs:
check:
@cargo fmt --check # Check Rust format issues
@cargo kclippy # Check common programming mistakes
@cargo kclippy -- -D warnings # Make build fail if any warnings are found by rustc and clippy
clean:
@cargo clean

View File

@ -2,7 +2,6 @@
use core::arch::x86_64::{_fxrstor, _fxsave};
use core::fmt::Debug;
use core::mem::MaybeUninit;
use trapframe::{GeneralRegs, UserContext as RawUserContext};
@ -87,7 +86,7 @@ impl UserContextApiInternal for UserContext {
}
}
};
call_irq_callback_functions(&self.into_trap_frame());
call_irq_callback_functions(&self.as_trap_frame());
}
crate::arch::irq::enable_local();
@ -103,7 +102,7 @@ impl UserContextApiInternal for UserContext {
}
}
fn into_trap_frame(&self) -> trapframe::TrapFrame {
fn as_trap_frame(&self) -> trapframe::TrapFrame {
trapframe::TrapFrame {
rax: self.user_context.general.rax,
rbx: self.user_context.general.rbx,
@ -350,7 +349,7 @@ impl FpRegs {
let ptr = unsafe { alloc::alloc::alloc(layout) } as usize;
debug!("ptr = 0x{:x}", ptr);
unsafe {
_fxsave((&mut self.buf.data).as_mut_ptr() as *mut u8);
_fxsave(self.buf.data.as_mut_ptr());
}
debug!("save fpregs success");
self.is_valid = true;
@ -365,7 +364,7 @@ impl FpRegs {
/// It is the caller's responsibility to ensure that the source slice contains
/// data that is in xsave/xrstor format. The slice must have a length of 512 bytes.
pub unsafe fn save_from_slice(&mut self, src: &[u8]) {
(&mut self.buf.data).copy_from_slice(src);
self.buf.data.copy_from_slice(src);
self.is_valid = true;
}
@ -388,7 +387,7 @@ impl FpRegs {
pub fn restore(&self) {
debug!("restore fpregs");
assert!(self.is_valid);
unsafe { _fxrstor((&self.buf.data).as_ptr()) };
unsafe { _fxrstor(self.buf.data.as_ptr()) };
debug!("restore fpregs success");
}

View File

@ -33,7 +33,7 @@ impl<T, A> IoPort<T, A> {
/// a privileged operation.
pub const unsafe fn new(port: u16) -> Self {
Self {
port: port,
port,
value_marker: PhantomData,
access_marker: PhantomData,
}

View File

@ -26,6 +26,7 @@ static SERIAL_MODEM_CTRL: IoPort<u8, WriteOnlyAccess> =
static SERIAL_LINE_STS: IoPort<u8, ReadWriteAccess> = unsafe { IoPort::new(SERIAL_DATA_PORT + 5) };
static CONSOLE_IRQ_CALLBACK: Once<SpinLock<IrqLine>> = Once::new();
#[allow(clippy::type_complexity)]
static SERIAL_INPUT_CALLBACKS: SpinLock<Vec<Arc<dyn Fn(u8) + Send + Sync + 'static>>> =
SpinLock::new(Vec::new());

View File

@ -49,7 +49,7 @@ pub enum ContextTableError {
impl RootTable {
pub fn new() -> Self {
Self {
root_frame: VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false))
root_frame: VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false))
.unwrap()
.pop()
.unwrap(),
@ -128,7 +128,7 @@ impl RootTable {
let bus_entry = context_table
.entries_frame
.read_val::<ContextEntry>(
(device_id.device as usize * 8 + device_id.function as usize) as usize
(device_id.device as usize * 8 + device_id.function as usize)
* size_of::<ContextEntry>(),
)
.unwrap();
@ -141,7 +141,7 @@ impl RootTable {
context_table
.entries_frame
.write_val::<ContextEntry>(
(device_id.device as usize * 8 + device_id.function as usize) as usize
(device_id.device as usize * 8 + device_id.function as usize)
* size_of::<ContextEntry>(),
&entry,
)
@ -237,7 +237,7 @@ pub struct ContextTable {
impl ContextTable {
fn new() -> Self {
Self {
entries_frame: VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false))
entries_frame: VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false))
.unwrap()
.pop()
.unwrap(),
@ -256,8 +256,7 @@ impl ContextTable {
let bus_entry = self
.entries_frame
.read_val::<ContextEntry>(
(device.device as usize * 8 + device.function as usize) as usize
* size_of::<ContextEntry>(),
(device.device as usize * 8 + device.function as usize) * size_of::<ContextEntry>(),
)
.unwrap();
@ -270,7 +269,7 @@ impl ContextTable {
let entry = ContextEntry(address as u128 | 3 | 0x1_0000_0000_0000_0000);
self.entries_frame
.write_val::<ContextEntry>(
(device.device as usize * 8 + device.function as usize) as usize
(device.device as usize * 8 + device.function as usize)
* size_of::<ContextEntry>(),
&entry,
)
@ -298,7 +297,7 @@ impl ContextTable {
paddr,
PageTableFlags::WRITABLE | PageTableFlags::READABLE | PageTableFlags::LAST_PAGE,
)
.map_err(|err| ContextTableError::ModificationError(err))
.map_err(ContextTableError::ModificationError)
}
fn unmap(&mut self, device: PciDeviceLocation, vaddr: Vaddr) -> Result<(), ContextTableError> {
@ -308,6 +307,6 @@ impl ContextTable {
self.get_or_create_page_table(device)
.unmap(vaddr)
.map_err(|err| ContextTableError::ModificationError(err))
.map_err(ContextTableError::ModificationError)
}
}

View File

@ -116,7 +116,7 @@ impl FaultRecording {
pub fn pasid_value(&self) -> u32 {
// bit 123:104
((self.0 & 0xF_FFFF0_0000_0000_0000_0000_0000_0000) >> 104) as u32
((self.0 & 0x00FF_FFF0_0000_0000_0000_0000_0000_0000) >> 104) as u32
}
pub fn fault_reason(&self) -> u8 {
@ -165,6 +165,7 @@ pub enum FaultRequestType {
#[derive(Debug)]
#[repr(u8)]
#[allow(clippy::enum_variant_names)]
pub enum FaultAddressType {
UntranslatedRequest = 0,
TranslationRequest = 1,
@ -201,6 +202,6 @@ pub(super) unsafe fn init(base_register_vaddr: Vaddr) {
fn iommu_page_fault_handler(frame: &TrapFrame) {
let fault_event = FAULT_EVENT_REGS.get().unwrap();
let index = (fault_event.status().bits & FaultStatus::FRI.bits) >> 8;
let recording = FaultRecording(*(&fault_event.recordings[index as usize].read()));
let recording = FaultRecording(fault_event.recordings[index as usize].read());
info!("Catch iommu page fault, recording:{:x?}", recording)
}

View File

@ -44,9 +44,8 @@ impl RemappingRegisters {
let base_address = {
let mut addr = 0;
for remapping in dmar.remapping_iter() {
match remapping {
Remapping::Drhd(drhd) => addr = drhd.register_base_addr(),
_ => {}
if let Remapping::Drhd(drhd) = remapping {
addr = drhd.register_base_addr()
}
}
if addr == 0 {
@ -110,7 +109,7 @@ bitflags! {
/// 6 => 16-bit domain-ids with support for up to 64K domains.
/// 7 => Reserved.
/// ```
const ND = 0x7 << 0;
const ND = 0x7;
/// Required Write-Buffer Flushing.
const RWBF = 1 << 4;
/// Protected Low-Memory Region

View File

@ -126,7 +126,7 @@ impl PageTableEntryTrait for PageTableEntry {
// bit 47~12
type F = PageTableFlags;
fn new(paddr: crate::vm::Paddr, flags: PageTableFlags) -> Self {
Self(((paddr & Self::PHYS_MASK) as u64 | flags.bits) as u64)
Self((paddr & Self::PHYS_MASK) as u64 | flags.bits)
}
fn paddr(&self) -> crate::vm::Paddr {
@ -150,7 +150,7 @@ impl PageTableEntryTrait for PageTableEntry {
}
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!(level >= 1 && level <= 5);
debug_assert!((1..=5).contains(&level));
va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
}
}

View File

@ -72,6 +72,7 @@ impl IrqLine {
///
/// This function is marked unsafe as manipulating interrupt lines is
/// considered a dangerous operation.
#[allow(clippy::redundant_allocation)]
pub unsafe fn acquire(irq_num: u8) -> Arc<&'static Self> {
Arc::new(IRQ_LIST.get().unwrap().get(irq_num as usize).unwrap())
}
@ -126,7 +127,7 @@ impl Drop for IrqCallbackHandle {
.unwrap()
.callback_list
.lock();
a.retain(|item| if (*item).id == self.id { false } else { true });
a.retain(|item| item.id != self.id);
ID_ALLOCATOR.lock().dealloc(self.id);
}
}

View File

@ -34,6 +34,7 @@ pub enum Remapping {
#[derive(Debug, Clone, Copy)]
#[repr(u16)]
#[allow(clippy::upper_case_acronyms)]
pub enum RemappingType {
DRHD = 0,
RMRR = 1,
@ -65,14 +66,9 @@ impl Dmar {
let acpi_table_lock = super::ACPI_TABLES.get().unwrap().lock();
// Safety: The DmarHeader is the header for the DMAR structure, it fits all the field described in Intel manual.
let dmar_mapping = unsafe {
if let Some(temp) = acpi_table_lock
acpi_table_lock
.get_sdt::<DmarHeader>(Signature::DMAR)
.unwrap()
{
temp
} else {
return None;
}
.unwrap()?
};
let physical_address = dmar_mapping.physical_start();
@ -93,9 +89,9 @@ impl Dmar {
unsafe {
while remain_length > 0 {
// Common header: type: u16, length: u16
let length = *dmar_slice[index as usize + 2..index as usize + 4].as_ptr() as usize;
let typ = *dmar_slice[index as usize..index as usize + 2].as_ptr() as usize;
let bytes = &&dmar_slice[index as usize..index as usize + length];
let length = *dmar_slice[index + 2..index + 4].as_ptr() as usize;
let typ = *dmar_slice[index..index + 2].as_ptr() as usize;
let bytes = &&dmar_slice[index..index + length];
let remapping = match typ {
0 => Remapping::Drhd(Drhd::from_bytes(bytes)),
1 => Remapping::Rmrr(Rmrr::from_bytes(bytes)),
@ -119,7 +115,7 @@ impl Dmar {
Some(Dmar {
header: *dmar_mapping,
remapping_structures: remapping_structures,
remapping_structures,
})
}

View File

@ -94,13 +94,13 @@ impl AcpiHandler for AcpiMemoryHandler {
pub fn init() {
let acpi_tables = match boot::acpi_arg().to_owned() {
BootloaderAcpiArg::Rsdp(addr) => unsafe {
AcpiTables::from_rsdp(AcpiMemoryHandler {}, addr as usize).unwrap()
AcpiTables::from_rsdp(AcpiMemoryHandler {}, addr).unwrap()
},
BootloaderAcpiArg::Rsdt(addr) => unsafe {
AcpiTables::from_rsdt(AcpiMemoryHandler {}, 0, addr as usize).unwrap()
AcpiTables::from_rsdt(AcpiMemoryHandler {}, 0, addr).unwrap()
},
BootloaderAcpiArg::Xsdt(addr) => unsafe {
AcpiTables::from_rsdt(AcpiMemoryHandler {}, 1, addr as usize).unwrap()
AcpiTables::from_rsdt(AcpiMemoryHandler {}, 1, addr).unwrap()
},
};

View File

@ -250,8 +250,7 @@ impl Rhsa {
pub unsafe fn from_bytes(bytes: &[u8]) -> Self {
let length = u16_from_slice(&bytes[2..4]) as u32;
debug_assert_eq!(length, bytes.len() as u32);
let result = *(bytes.as_ptr() as *const Self);
result
*(bytes.as_ptr() as *const Self)
}
}

View File

@ -52,8 +52,7 @@ pub fn init() {
acpi::InterruptModel::Unknown => panic!("not found APIC in ACPI Table"),
acpi::InterruptModel::Apic(apic) => {
apic.io_apics
.iter()
.next()
.first()
.expect("There must be at least one IO APIC")
.address
}

View File

@ -27,7 +27,7 @@ impl X2Apic {
unsafe {
// Enable x2APIC mode globally
let mut base = rdmsr(IA32_APIC_BASE);
base = base | 0b1100_0000_0000; // Enable x2APIC and xAPIC
base |= 0b1100_0000_0000; // Enable x2APIC and xAPIC
wrmsr(IA32_APIC_BASE, base);
// Set SVR, Enable APIC and set Spurious Vector to 15 (Reserved irq number)

View File

@ -49,6 +49,10 @@ pub fn tlb_flush(vaddr: Vaddr) {
#[repr(C)]
pub struct PageTableEntry(usize);
/// ## Safety
///
/// Changing the level 4 page table is unsafe, because it's possible to violate memory safety by
/// changing the page mapping.
pub unsafe fn activate_page_table(root_paddr: Paddr, flags: x86_64::registers::control::Cr3Flags) {
x86_64::registers::control::Cr3::write(
PhysFrame::from_start_address(x86_64::PhysAddr::new(root_paddr as u64)).unwrap(),
@ -67,9 +71,9 @@ pub fn init() {
// Cancel mapping in lowest addresses.
p4[0].clear();
let mut map_pte = ALL_MAPPED_PTE.lock();
for i in 0..512 {
if p4[i].flags().contains(PageTableFlags::PRESENT) {
map_pte.insert(i, p4[i]);
for (i, p4_i) in p4.iter().enumerate().take(512) {
if p4_i.flags().contains(PageTableFlags::PRESENT) {
map_pte.insert(i, *p4_i);
}
}
}
@ -166,7 +170,7 @@ impl PageTableEntryTrait for PageTableEntry {
Self((paddr & Self::PHYS_ADDR_MASK) | flags.bits)
}
fn paddr(&self) -> Paddr {
self.0 as usize & Self::PHYS_ADDR_MASK
self.0 & Self::PHYS_ADDR_MASK
}
fn flags(&self) -> PageTableFlags {
PageTableFlags::from_bits_truncate(self.0)
@ -184,7 +188,7 @@ impl PageTableEntryTrait for PageTableEntry {
}
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!(level >= 1 && level <= 5);
debug_assert!((1..=5).contains(&level));
va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
}
}

View File

@ -1,7 +1,6 @@
use core::arch::x86_64::_rdtsc;
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::boxed::Box;
use alloc::sync::Arc;
use log::info;
use spin::Once;
@ -83,7 +82,6 @@ fn periodic_mode_init() {
}
x86_64::instructions::interrupts::disable();
drop(a);
drop(handle);
fn init_function(trap_frame: &TrapFrame) {
static mut IN_TIME: u8 = 0;

View File

@ -32,7 +32,7 @@ pub struct KCmdlineArg {
impl KCmdlineArg {
/// Get the path of the initprocess.
pub fn get_initproc_path(&self) -> Option<&str> {
self.initproc.path.as_ref().map(|s| s.as_str())
self.initproc.path.as_deref()
}
/// Get the argument vector(argv) of the initprocess.
pub fn get_initproc_argv(&self) -> &Vec<CString> {
@ -85,7 +85,7 @@ impl From<&str> for KCmdlineArg {
// KernelArg => Arg "\s+" KernelArg | %empty
// InitArg => Arg "\s+" InitArg | %empty
if kcmdline_end {
if result.initproc.path == None {
if result.initproc.path.is_none() {
panic!("Initproc arguments provided but no initproc path specified!");
}
result.initproc.argv.push(CString::new(arg).unwrap());
@ -96,7 +96,7 @@ impl From<&str> for KCmdlineArg {
continue;
}
// Arg => Entry | Entry "=" Value
let arg_pattern: Vec<_> = arg.split("=").collect();
let arg_pattern: Vec<_> = arg.split('=').collect();
let (entry, value) = match arg_pattern.len() {
1 => (arg_pattern[0], None),
2 => (arg_pattern[0], Some(arg_pattern[1])),
@ -105,7 +105,7 @@ impl From<&str> for KCmdlineArg {
}
};
// Entry => Module "." ModuleOptionName | KernelOptionName
let entry_pattern: Vec<_> = entry.split(".").collect();
let entry_pattern: Vec<_> = entry.split('.').collect();
let (node, option) = match entry_pattern.len() {
1 => (None, entry_pattern[0]),
2 => (Some(entry_pattern[0]), entry_pattern[1]),
@ -145,16 +145,13 @@ impl From<&str> for KCmdlineArg {
}
} else {
// There is no value, the entry is only a option.
match option {
_ => {
// If the option is not recognized, it is passed to the initproc.
// Pattern 'option' without value is treated as the init argument.
let argv_entry = CString::new(option.to_string()).unwrap();
result.initproc.argv.push(argv_entry);
}
}
}
}
result
}

View File

@ -36,11 +36,7 @@ pub struct MemoryRegion {
impl MemoryRegion {
/// Construct a page aligned memory region.
pub fn new(base: usize, len: usize, typ: MemoryRegionType) -> Self {
MemoryRegion {
base: base,
len: len,
typ: typ,
}
MemoryRegion { base, len, typ }
}
/// The physical address of the base of the region.
@ -53,6 +49,10 @@ impl MemoryRegion {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The type of the region.
pub fn typ(&self) -> MemoryRegionType {
self.typ
@ -86,8 +86,7 @@ impl MemoryRegion {
} else {
vec![*self]
}
} else {
if self.base < t.base + t.len {
} else if self.base < t.base + t.len {
if self.base + self.len > t.base + t.len {
vec![MemoryRegion {
base: t.base + t.len,
@ -101,5 +100,4 @@ impl MemoryRegion {
vec![*self]
}
}
}
}

View File

@ -25,6 +25,7 @@ pub trait PciDriver: Sync + Send + Debug {
///
/// Once a device is matched and claimed by a driver,
/// it won't be fed to another driver for probing.
#[allow(clippy::result_large_err)]
fn probe(
&self,
device: PciCommonDevice,
@ -69,7 +70,7 @@ impl PciBus {
pub(super) fn register_common_device(&mut self, mut common_device: PciCommonDevice) {
debug!("Find pci common devices:{:x?}", common_device);
let device_id = common_device.device_id().clone();
let device_id = *common_device.device_id();
for driver in self.drivers.iter() {
common_device = match driver.probe(common_device) {
Ok(device) => {

View File

@ -31,9 +31,9 @@ impl Clone for CapabilityMsixData {
fn clone(&self) -> Self {
let new_vec = self.irqs.clone().to_vec();
Self {
loc: self.loc.clone(),
ptr: self.ptr.clone(),
table_size: self.table_size.clone(),
loc: self.loc,
ptr: self.ptr,
table_size: self.table_size,
table_bar: self.table_bar.clone(),
pending_table_bar: self.pending_table_bar.clone(),
irqs: new_vec,
@ -99,7 +99,7 @@ impl CapabilityMsixData {
.unwrap();
table_bar
.io_mem()
.write_val((16 * i + 12) as usize + table_offset, &(1 as u32))
.write_val((16 * i + 12) as usize + table_offset, &1_u32)
.unwrap();
}
@ -115,13 +115,13 @@ impl CapabilityMsixData {
}
Self {
loc: dev.location().clone(),
loc: *dev.location(),
ptr: cap_ptr,
table_size: (dev.location().read16(cap_ptr + 2) & 0b11_1111_1111) + 1,
table_bar,
pending_table_bar: pba_bar,
irqs,
table_offset: table_offset,
table_offset,
pending_table_offset: pba_offset,
}
}
@ -146,7 +146,7 @@ impl CapabilityMsixData {
// Enable this msix vector
self.table_bar
.io_mem()
.write_val((16 * index + 12) as usize + self.table_offset, &(0 as u32))
.write_val((16 * index + 12) as usize + self.table_offset, &0_u32)
.unwrap();
}

View File

@ -13,7 +13,7 @@ pub struct CapabilityVndrData {
impl CapabilityVndrData {
pub(super) fn new(dev: &PciCommonDevice, cap_ptr: u16, length: u16) -> Self {
Self {
location: dev.location().clone(),
location: *dev.location(),
cap_ptr,
length,
}
@ -23,6 +23,10 @@ impl CapabilityVndrData {
self.length
}
pub fn is_empty(&self) -> bool {
self.length == 0
}
pub fn read8(&self, offset: u16) -> Result<u8> {
self.check_range(offset)?;
Ok(self.location.read8(self.cap_ptr + offset))
@ -30,7 +34,8 @@ impl CapabilityVndrData {
pub fn write8(&self, offset: u16, value: u8) -> Result<()> {
self.check_range(offset)?;
Ok(self.location.write8(self.cap_ptr + offset, value))
self.location.write8(self.cap_ptr + offset, value);
Ok(())
}
pub fn read16(&self, offset: u16) -> Result<u16> {
@ -40,7 +45,8 @@ impl CapabilityVndrData {
pub fn write16(&self, offset: u16, value: u16) -> Result<()> {
self.check_range(offset)?;
Ok(self.location.write16(self.cap_ptr + offset, value))
self.location.write16(self.cap_ptr + offset, value);
Ok(())
}
pub fn read32(&self, offset: u16) -> Result<u32> {
@ -50,7 +56,8 @@ impl CapabilityVndrData {
pub fn write32(&self, offset: u16, value: u32) -> Result<()> {
self.check_range(offset)?;
Ok(self.location.write32(self.cap_ptr + offset, value))
self.location.write32(self.cap_ptr + offset, value);
Ok(())
}
#[inline]

View File

@ -153,7 +153,7 @@ impl MemoryBar {
};
// length
let size = !(len_encoded & !0xF).wrapping_add(1);
let prefetchable = if raw & 0b1000 == 0 { false } else { true };
let prefetchable = raw & 0b1000 != 0;
// The BAR is located in I/O memory region
Ok(MemoryBar {
base,

View File

@ -110,8 +110,7 @@ impl BarManager {
let mut idx = 0;
let mut bars = [None, None, None, None, None, None];
while idx < max {
match Bar::new(location, idx) {
Ok(bar) => {
if let Ok(bar) = Bar::new(location, idx) {
let mut idx_step = 0;
match &bar {
Bar::Memory(memory_bar) => {
@ -124,9 +123,6 @@ impl BarManager {
bars[idx as usize] = Some((bar, true));
idx += idx_step;
}
// ignore for now
Err(_) => {}
}
idx += 1;
}
Self { bars }

View File

@ -38,7 +38,7 @@ macro_rules! cpu_local {
// multiple declarations
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => {
$(#[$attr])* $vis static $name: CpuLocal<$t> = unsafe { CpuLocal::new($init) };
crate::cpu_local!($($rest)*);
$crate::cpu_local!($($rest)*);
};
// single declaration
@ -66,6 +66,7 @@ unsafe impl<T> Sync for CpuLocal<T> {}
impl<T> CpuLocal<T> {
/// Initialize CPU-local object
/// Developer cannot construct a valid CpuLocal object arbitrarily
#[allow(clippy::missing_safety_doc)]
pub const unsafe fn new(val: T) -> Self {
Self(UnsafeCell::new(val))
}

View File

@ -70,11 +70,10 @@ fn invoke_c_init_funcs() {
fn __sinit_array();
fn __einit_array();
}
let call_len = (__einit_array as u64 - __sinit_array as u64) / 8;
let call_len = (__einit_array as usize - __sinit_array as usize) / 8;
for i in 0..call_len {
unsafe {
let address = (__sinit_array as u64 + 8 * i) as *const u64;
let function = address as *const fn();
let function = (__sinit_array as usize + 8 * i) as *const fn();
(*function)();
}
}
@ -96,7 +95,7 @@ pub(crate) const fn zero<T>() -> T {
}
pub trait Testable {
fn run(&self) -> ();
fn run(&self);
}
impl<T> Testable for T

View File

@ -83,17 +83,17 @@ impl AtomicBits {
}
/// Get an iterator for the bits.
pub fn iter<'a>(&'a self) -> Iter<'a> {
pub fn iter(&self) -> Iter<'_> {
Iter::new(self)
}
/// Get an iterator that gives the positions of all 1s in the bits.
pub fn iter_ones<'a>(&'a self) -> OnesIter<'a> {
pub fn iter_ones(&self) -> OnesIter<'_> {
OnesIter::new(self)
}
/// Get an iterator that gives the positions of all 0s in the bits.
pub fn iter_zeroes<'a>(&'a self) -> ZeroesIter<'a> {
pub fn iter_zeroes(&self) -> ZeroesIter<'_> {
ZeroesIter::new(self)
}
}

View File

@ -31,7 +31,7 @@ impl<T> Mutex<T> {
/// Try Acquire the mutex immedidately.
pub fn try_lock(&self) -> Option<MutexGuard<T>> {
self.acquire_lock().then(|| MutexGuard { mutex: &self })
self.acquire_lock().then_some(MutexGuard { mutex: self })
}
/// Release the mutex and wake up one thread which is blocked on this mutex.

View File

@ -70,7 +70,7 @@ impl<T> RwLock<T> {
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER) == 0 {
Some(RwLockReadGuard {
inner: &self,
inner: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
})
} else {
@ -88,7 +88,7 @@ impl<T> RwLock<T> {
.is_ok()
{
Some(RwLockWriteGuard {
inner: &self,
inner: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
})
} else {
@ -130,7 +130,7 @@ impl<T> RwLock<T> {
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER) == 0 {
Some(RwLockReadGuard {
inner: &self,
inner: self,
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {
@ -148,7 +148,7 @@ impl<T> RwLock<T> {
.is_ok()
{
Some(RwLockWriteGuard {
inner: &self,
inner: self,
inner_guard: InnerGuard::PreemptGuard(guard),
})
} else {

View File

@ -25,7 +25,7 @@ const MAX_READER: usize = WRITER >> 1;
impl<T> RwMutex<T> {
/// Creates a new `RwMutex`.
pub fn new(val: T) -> Self {
pub const fn new(val: T) -> Self {
Self {
val: UnsafeCell::new(val),
lock: AtomicUsize::new(0),
@ -47,7 +47,7 @@ impl<T> RwMutex<T> {
pub fn try_read(&self) -> Option<RwMutexReadGuard<T>> {
let lock = self.lock.fetch_add(READER, Acquire);
if lock & (WRITER | MAX_READER) == 0 {
Some(RwMutexReadGuard { inner: &self })
Some(RwMutexReadGuard { inner: self })
} else {
self.lock.fetch_sub(READER, Release);
None
@ -61,7 +61,7 @@ impl<T> RwMutex<T> {
.compare_exchange(0, WRITER, Acquire, Relaxed)
.is_ok()
{
Some(RwMutexWriteGuard { inner: &self })
Some(RwMutexWriteGuard { inner: self })
} else {
None
}

View File

@ -31,7 +31,7 @@ impl<T> SpinLock<T> {
let guard = disable_local();
self.acquire_lock();
SpinLockGuard {
lock: &self,
lock: self,
inner_guard: InnerGuard::IrqGuard(guard),
}
}
@ -41,12 +41,12 @@ impl<T> SpinLock<T> {
let irq_guard = disable_local();
if self.try_acquire_lock() {
let lock_guard = SpinLockGuard {
lock: &self,
lock: self,
inner_guard: InnerGuard::IrqGuard(irq_guard),
};
return Some(lock_guard);
}
return None;
None
}
/// Acquire the spin lock without disabling local IRQs.
@ -61,7 +61,7 @@ impl<T> SpinLock<T> {
let guard = disable_preempt();
self.acquire_lock();
SpinLockGuard {
lock: &self,
lock: self,
inner_guard: InnerGuard::PreemptGuard(guard),
}
}
@ -71,12 +71,12 @@ impl<T> SpinLock<T> {
let guard = disable_preempt();
if self.try_acquire_lock() {
let lock_guard = SpinLockGuard {
lock: &self,
lock: self,
inner_guard: InnerGuard::PreemptGuard(guard),
};
return Some(lock_guard);
}
return None;
None
}
/// Access the spin lock, otherwise busy waiting

View File

@ -17,7 +17,6 @@ pub struct WaitQueue {
}
impl WaitQueue {
/// Creates a new instance.
pub const fn new() -> Self {
WaitQueue {
waiters: SpinLock::new(VecDeque::new()),

View File

@ -13,7 +13,6 @@ use super::{
};
use alloc::sync::Arc;
use lazy_static::lazy_static;
use log::warn;
pub struct Processor {
current: Option<Arc<Task>>,
@ -83,17 +82,18 @@ pub fn switch_to_task(next_task: Arc<Task>) {
let current_task_option = current_task();
let next_task_cx_ptr = &next_task.inner_ctx() as *const TaskContext;
let current_task: Arc<Task>;
let current_task_cx_ptr = if current_task_option.is_none() {
PROCESSOR.lock().get_idle_task_cx_ptr()
} else {
current_task = current_task_option.unwrap();
let current_task_cx_ptr = match current_task_option {
None => PROCESSOR.lock().get_idle_task_cx_ptr(),
Some(current_task) => {
if current_task.status() == TaskStatus::Runnable {
GLOBAL_SCHEDULER
.lock_irq_disabled()
.enqueue(current_task.clone());
}
&mut current_task.inner_exclusive_access().ctx as *mut TaskContext
}
};
// change the current task to the next task
PROCESSOR.lock().current = Some(next_task.clone());

View File

@ -44,7 +44,7 @@ impl KernelStack {
pub fn new() -> Result<Self> {
Ok(Self {
frame: VmFrameVec::allocate(
&VmAllocOptions::new(KERNEL_STACK_SIZE / PAGE_SIZE).is_contiguous(true),
VmAllocOptions::new(KERNEL_STACK_SIZE / PAGE_SIZE).is_contiguous(true),
)?,
})
}

View File

@ -12,11 +12,7 @@ extern "sysv64" fn trap_handler(f: &mut TrapFrame) {
}
pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame) {
let irq_line = IRQ_LIST
.get()
.unwrap()
.get(trap_frame.trap_num as usize)
.unwrap();
let irq_line = IRQ_LIST.get().unwrap().get(trap_frame.trap_num).unwrap();
let callback_functions = irq_line.callback_list();
for callback_function in callback_functions.iter() {
callback_function.call(trap_frame);

View File

@ -13,6 +13,7 @@ use trapframe::TrapFrame;
#[must_use]
pub struct IrqLine {
irq_num: u8,
#[allow(clippy::redundant_allocation)]
irq: Arc<&'static irq::IrqLine>,
callbacks: Vec<IrqCallbackHandle>,
}
@ -68,7 +69,7 @@ impl IrqLine {
impl Clone for IrqLine {
fn clone(&self) -> Self {
Self {
irq_num: self.irq_num.clone(),
irq_num: self.irq_num,
irq: self.irq.clone(),
callbacks: Vec::new(),
}

View File

@ -54,7 +54,7 @@ pub(crate) trait UserContextApiInternal {
fn execute(&mut self) -> UserEvent;
/// Use the information inside CpuContext to build a trapframe
fn into_trap_frame(&self) -> TrapFrame;
fn as_trap_frame(&self) -> TrapFrame;
}
/// The common interface that every CPU architecture-specific `CpuContext` implements.

View File

@ -23,7 +23,7 @@ impl RecycleAllocator {
current: start,
recycled: Vec::new(),
skip: Vec::new(),
max: max,
max,
}
}
@ -82,13 +82,11 @@ impl RecycleAllocator {
self.skip.push(target);
true
}
} else {
if self.recycled.contains(&target) {
} else if self.recycled.contains(&target) {
self.recycled.retain(|value| *value != target);
true
} else {
false
}
}
}
}

View File

@ -123,11 +123,6 @@ impl VmFrameVec {
self.0.iter()
}
/// Return IntoIterator for internal frames
pub fn into_iter(self) -> alloc::vec::IntoIter<VmFrame> {
self.0.into_iter()
}
/// Returns the number of frames.
pub fn len(&self) -> usize {
self.0.len()
@ -150,6 +145,16 @@ impl VmFrameVec {
}
}
impl IntoIterator for VmFrameVec {
type Item = VmFrame;
type IntoIter = alloc::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl VmIo for VmFrameVec {
fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
let mut start = offset;
@ -362,6 +367,7 @@ impl VmFrame {
// FIXME: need a sound reason for creating a mutable reference
// for getting the content of the frame.
#[allow(clippy::mut_from_ref)]
#[allow(clippy::missing_safety_doc)]
pub unsafe fn as_slice(&self) -> &mut [u8] {
core::slice::from_raw_parts_mut(
super::paddr_to_vaddr(self.start_paddr()) as *mut u8,

View File

@ -57,7 +57,7 @@ pub(crate) unsafe fn dealloc(index: usize) {
FRAME_ALLOCATOR.get().unwrap().lock().dealloc(index, 1);
}
pub(crate) fn init(regions: &Vec<MemoryRegion>) {
pub(crate) fn init(regions: &[MemoryRegion]) {
let mut allocator = FrameAllocator::<32>::new();
for region in regions.iter() {
if region.typ() == MemoryRegionType::Usable {

View File

@ -67,14 +67,16 @@ unsafe impl<const ORDER: usize> GlobalAlloc for LockedHeapWithRescue<ORDER> {
}
// Avoid locking self.heap when calling rescue.
if (self.rescue)(&self, &layout).is_err() {
return 0 as *mut u8;
if (self.rescue)(self, &layout).is_err() {
return core::ptr::null_mut::<u8>();
}
self.heap
.lock()
.alloc(layout)
.map_or(0 as *mut u8, |allocation| allocation.as_ptr())
.map_or(core::ptr::null_mut::<u8>(), |allocation| {
allocation.as_ptr()
})
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {

View File

@ -28,12 +28,8 @@ pub struct MemorySet {
areas: BTreeMap<Vaddr, MapArea>,
}
impl MapArea {
pub fn mapped_size(&self) -> usize {
self.size
}
pub fn clone(&self) -> Self {
impl Clone for MapArea {
fn clone(&self) -> Self {
let mut mapper = BTreeMap::new();
for (&va, old) in &self.mapper {
let new = frame_allocator::alloc(VmFrameFlags::empty()).unwrap();
@ -49,6 +45,12 @@ impl MapArea {
mapper,
}
}
}
impl MapArea {
pub fn mapped_size(&self) -> usize {
self.size
}
/// This function will map the vitural address to the given physical frames
pub fn new(
@ -69,7 +71,7 @@ impl MapArea {
size,
mapper: BTreeMap::new(),
};
let mut current_va = start_va.clone();
let mut current_va = start_va;
let page_size = size / PAGE_SIZE;
let mut phy_frame_iter = physical_frames.iter();
@ -149,6 +151,12 @@ impl MapArea {
}
}
impl Default for MemorySet {
fn default() -> Self {
Self::new()
}
}
impl MemorySet {
pub fn map(&mut self, area: MapArea) {
if area.size > 0 {

View File

@ -15,7 +15,7 @@ mod offset;
pub(crate) mod page_table;
mod space;
use crate::config::{PAGE_SIZE, PHYS_OFFSET};
use crate::config::{KERNEL_OFFSET, PAGE_SIZE, PHYS_OFFSET};
pub use self::frame::{VmAllocOptions, VmFrame, VmFrameVec, VmFrameVecIter};
pub use self::io::VmIo;
@ -38,7 +38,7 @@ pub trait HasPaddr {
}
pub fn vaddr_to_paddr(va: Vaddr) -> Option<Paddr> {
if va >= crate::config::PHYS_OFFSET && va <= crate::config::KERNEL_OFFSET {
if (PHYS_OFFSET..=KERNEL_OFFSET).contains(&va) {
// can use offset to get the physical address
Some(va - PHYS_OFFSET)
} else {
@ -67,7 +67,7 @@ pub(crate) fn init() {
let mut framebuffer_regions = Vec::new();
for i in memory_regions.iter() {
if i.typ() == MemoryRegionType::Framebuffer {
framebuffer_regions.push(i.clone());
framebuffer_regions.push(*i);
}
}
FRAMEBUFFER_REGIONS.call_once(|| framebuffer_regions);

View File

@ -89,6 +89,7 @@ pub struct PageTableConfig {
#[derive(Debug, Clone, Copy)]
#[repr(usize)]
#[allow(clippy::enum_variant_names)]
pub enum AddressWidth {
Level3PageTable = 3,
Level4PageTable = 4,
@ -190,7 +191,7 @@ impl<T: PageTableEntryTrait> PageTable<T> {
return None;
}
// Create next table
let frame = VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false))
let frame = VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false))
.unwrap()
.pop()
.unwrap();

View File

@ -36,6 +36,7 @@ impl VmSpace {
}
}
/// Activate the page table, load root physical address to cr3
#[allow(clippy::missing_safety_doc)]
pub unsafe fn activate(&self) {
#[cfg(target_arch = "x86_64")]
crate::arch::x86::mm::activate_page_table(
@ -188,7 +189,7 @@ impl VmMapOptions {
///
/// The default value of this option is `None`.
pub fn addr(&mut self, addr: Option<Vaddr>) -> &mut Self {
if addr == None {
if addr.is_none() {
return self;
}
self.addr = Some(addr.unwrap());

View File

@ -39,8 +39,7 @@ impl phy::RxToken for RxToken {
F: FnOnce(&mut [u8]) -> R,
{
let packet_but = self.0.packet_mut();
let res = f(packet_but);
res
f(packet_but)
}
}

View File

@ -91,7 +91,7 @@ pub fn handle_recv_irq(name: &String) {
}
}
pub fn all_devices() -> Vec<(String, Arc<SpinLock<Box<dyn NetworkDevice>>>)> {
pub fn all_devices() -> Vec<(String, NetworkDeviceRef)> {
let lock = COMPONENT.get().unwrap().devices.lock();
let mut vec = Vec::new();
for (name, (_, device)) in lock.iter() {
@ -112,17 +112,12 @@ fn init() -> Result<(), ComponentInitError> {
Ok(())
}
type NetDeviceIrqHandlerListRef = Arc<SpinLock<Vec<Arc<dyn NetDeviceIrqHandler>>>>;
type NetworkDeviceRef = Arc<SpinLock<Box<dyn NetworkDevice>>>;
struct Component {
/// Device list, the key is device name, value is (callbacks, device);
devices: SpinLock<
BTreeMap<
String,
(
Arc<SpinLock<Vec<Arc<dyn NetDeviceIrqHandler>>>>,
Arc<SpinLock<Box<dyn NetworkDevice>>>,
),
>,
>,
devices: SpinLock<BTreeMap<String, (NetDeviceIrqHandlerListRef, NetworkDeviceRef)>>,
}
impl Component {

View File

@ -26,7 +26,7 @@ pub fn is_updating() -> bool {
pub fn read() -> SystemTime {
update_time();
READ_TIME.lock().clone()
*READ_TIME.lock()
}
/// read year,month,day and other data
@ -34,22 +34,21 @@ pub fn read() -> SystemTime {
fn update_time() {
let mut last_time: SystemTime;
let register_b: u8;
let mut lock = READ_TIME.lock();
lock.update_from_rtc();
last_time = lock.clone();
last_time = *lock;
lock.update_from_rtc();
while *lock != last_time {
last_time = lock.clone();
last_time = *lock;
lock.update_from_rtc();
}
register_b = get_cmos(0x0B);
let register_b: u8 = get_cmos(0x0B);
lock.convert_bcd_to_binary(register_b);
lock.convert_12_hour_to_24_hour(register_b);

View File

@ -9,7 +9,7 @@ use pod::Pod;
use crate::transport::VirtioTransport;
pub const BLK_SIZE: usize = 512;
pub static DEVICE_NAME: &'static str = "Virtio-Block";
pub static DEVICE_NAME: &str = "Virtio-Block";
bitflags! {
/// features for virtio block device
@ -112,7 +112,7 @@ pub struct VirtioBlkTopology {
}
impl VirtioBlkConfig {
pub(self) fn new(transport: &mut dyn VirtioTransport) -> SafePtr<Self, IoMem> {
pub(self) fn new(transport: &dyn VirtioTransport) -> SafePtr<Self, IoMem> {
let memory = transport.device_config_memory();
SafePtr::new(memory, 0)
}

View File

@ -63,6 +63,7 @@ pub struct InputDevice {
event_queue: SpinLock<VirtQueue>,
status_queue: VirtQueue,
event_buf: SpinLock<Box<[InputEvent; QUEUE_SIZE as usize]>>,
#[allow(clippy::type_complexity)]
callbacks: SpinLock<Vec<Arc<dyn Fn(DecodeType) + Send + Sync + 'static>>>,
transport: Box<dyn VirtioTransport>,
}
@ -161,7 +162,7 @@ impl InputDevice {
.write(&(select as u8))
.unwrap();
field_ptr!(&self.config, VirtioInputConfig, subsel)
.write(&(subsel as u8))
.write(&subsel)
.unwrap();
let size = field_ptr!(&self.config, VirtioInputConfig, size)
.read()

View File

@ -30,7 +30,7 @@ use jinux_frame::io_mem::IoMem;
use jinux_util::safe_ptr::SafePtr;
use pod::Pod;
pub static DEVICE_NAME: &'static str = "Virtio-Input";
pub static DEVICE_NAME: &str = "Virtio-Input";
/// Select value used for [`VirtIOInput::query_config_select()`].
#[repr(u8)]
@ -72,7 +72,7 @@ pub struct VirtioInputConfig {
}
impl VirtioInputConfig {
pub(self) fn new(transport: &mut dyn VirtioTransport) -> SafePtr<Self, IoMem> {
pub(self) fn new(transport: &dyn VirtioTransport) -> SafePtr<Self, IoMem> {
let memory = transport.device_config_memory();
SafePtr::new(memory, 0)
}

View File

@ -71,7 +71,7 @@ pub struct VirtioNetConfig {
}
impl VirtioNetConfig {
pub(super) fn new(transport: &mut dyn VirtioTransport) -> SafePtr<Self, IoMem> {
pub(super) fn new(transport: &dyn VirtioTransport) -> SafePtr<Self, IoMem> {
let memory = transport.device_config_memory();
SafePtr::new(memory, 0)
}

View File

@ -60,7 +60,7 @@ impl NetworkDevice {
let mut rx_buffers = SlotVec::new();
for i in 0..QUEUE_SIZE {
let mut rx_buffer = RxBuffer::new(RX_BUFFER_LEN, size_of::<VirtioNetHdr>());
let token = recv_queue.add(&[], &mut [rx_buffer.buf_mut()])?;
let token = recv_queue.add(&[], &[rx_buffer.buf_mut()])?;
assert_eq!(i, token);
assert_eq!(rx_buffers.put(rx_buffer) as u16, i);
}
@ -109,7 +109,7 @@ impl NetworkDevice {
fn add_rx_buffer(&mut self, mut rx_buffer: RxBuffer) -> Result<(), VirtioNetError> {
let token = self
.recv_queue
.add(&[], &mut [rx_buffer.buf_mut()])
.add(&[], &[rx_buffer.buf_mut()])
.map_err(queue_to_network_error)?;
assert!(self.rx_buffers.put_at(token as usize, rx_buffer).is_none());
if self.recv_queue.should_notify() {
@ -140,7 +140,7 @@ impl NetworkDevice {
let header = VirtioNetHdr::default();
let token = self
.send_queue
.add(&[header.as_bytes(), tx_buffer.buf()], &mut [])
.add(&[header.as_bytes(), tx_buffer.buf()], &[])
.map_err(queue_to_network_error)?;
if self.send_queue.should_notify() {

View File

@ -2,4 +2,4 @@ pub mod config;
pub mod device;
pub mod header;
pub static DEVICE_NAME: &'static str = "Virtio-Net";
pub static DEVICE_NAME: &str = "Virtio-Net";

View File

@ -67,21 +67,21 @@ impl VirtQueue {
}
let descriptor_ptr: SafePtr<Descriptor, VmFrame> = SafePtr::new(
VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true))
VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true))
.unwrap()
.pop()
.unwrap(),
0,
);
let avail_ring_ptr: SafePtr<AvailRing, VmFrame> = SafePtr::new(
VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true))
VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true))
.unwrap()
.pop()
.unwrap(),
0,
);
let used_ring_ptr: SafePtr<UsedRing, VmFrame> = SafePtr::new(
VmFrameVec::allocate(&VmAllocOptions::new(1).uninit(false).can_dma(true))
VmFrameVec::allocate(VmAllocOptions::new(1).uninit(false).can_dma(true))
.unwrap()
.pop()
.unwrap(),
@ -311,6 +311,7 @@ pub struct Descriptor {
}
#[inline]
#[allow(clippy::type_complexity)]
fn set_buf(ptr: &SafePtr<Descriptor, &VmFrame, TRightSet<TRights![Dup, Write]>>, buf: &[u8]) {
let va = buf.as_ptr() as usize;
let pa = jinux_frame::vm::vaddr_to_paddr(va).unwrap();
@ -323,7 +324,7 @@ fn set_buf(ptr: &SafePtr<Descriptor, &VmFrame, TRightSet<TRights![Dup, Write]>>,
}
bitflags! {
/// Descriptor flags
#[derive(Pod)]
#[derive(Pod, Default)]
#[repr(C)]
struct DescFlags: u16 {
const NEXT = 1;
@ -331,13 +332,6 @@ bitflags! {
const INDIRECT = 4;
}
}
impl Default for DescFlags {
fn default() -> Self {
Self {
bits: Default::default(),
}
}
}
/// The driver uses the available ring to offer buffers to the device:
/// each ring entry refers to the head of a descriptor chain.

View File

@ -7,6 +7,7 @@ use jinux_frame::bus::pci::{
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
#[allow(clippy::enum_variant_names)]
pub enum VirtioPciCpabilityType {
CommonCfg = 1,
NotifyCfg = 2,
@ -72,16 +73,15 @@ impl VirtioPciCapabilityData {
let mut io_bar = None;
let mut memory_bar = None;
match bar_manager.bar(bar) {
Some(bar) => match bar {
if let Some(bar) = bar_manager.bar(bar) {
match bar {
Bar::Memory(memory) => {
memory_bar = Some(memory);
}
Bar::Io(io) => {
io_bar = Some(io);
}
},
None => {}
}
};
Self {
cfg_type,

View File

@ -49,7 +49,7 @@ pub struct VirtioPciTransport {
impl PciDevice for VirtioPciDevice {
fn device_id(&self) -> PciDeviceId {
self.device_id.clone()
self.device_id
}
}
@ -78,13 +78,13 @@ impl VirtioTransport for VirtioPciTransport {
return Err(VirtioTransportError::InvalidArgs);
}
field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select)
.write(&(idx as u16))
.write(&idx)
.unwrap();
debug_assert_eq!(
field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select)
.read()
.unwrap(),
idx as u16
idx
);
field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_size)
@ -189,13 +189,13 @@ impl VirtioTransport for VirtioPciTransport {
fn max_queue_size(&self, idx: u16) -> Result<u16, crate::transport::VirtioTransportError> {
field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select)
.write(&(idx as u16))
.write(&idx)
.unwrap();
debug_assert_eq!(
field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_select)
.read()
.unwrap(),
idx as u16
idx
);
Ok(field_ptr!(&self.common_cfg, VirtioPciCommonCfg, queue_size)
@ -250,6 +250,7 @@ impl VirtioPciTransport {
&self.device
}
#[allow(clippy::result_large_err)]
pub(super) fn new(
common_device: PciCommonDevice,
) -> Result<Self, (PciDriverProbeError, PciCommonDevice)> {
@ -280,8 +281,7 @@ impl VirtioPciTransport {
for cap in common_device.capabilities().iter() {
match cap.capability_data() {
CapabilityData::Vndr(vendor) => {
let data =
VirtioPciCapabilityData::new(common_device.bar_manager(), vendor.clone());
let data = VirtioPciCapabilityData::new(common_device.bar_manager(), *vendor);
match data.typ() {
VirtioPciCpabilityType::CommonCfg => {
common_cfg = Some(VirtioPciCommonCfg::new(&data));
@ -317,7 +317,7 @@ impl VirtioPciTransport {
let common_cfg = common_cfg.unwrap();
let device_cfg = device_cfg.unwrap();
let msix_manager = VirtioMsixManager::new(msix);
let device_id = common_device.device_id().clone();
let device_id = *common_device.device_id();
Ok(Self {
common_device,
common_cfg,

View File

@ -30,7 +30,7 @@ pub fn component_generate() -> Vec<ComponentInfo> {
let mut component_packages = vec![];
let workspace_root = metadata["workspace_root"].as_str().unwrap();
let workspace_root = String::from_str(workspace_root).unwrap().replace("\\", "/");
let workspace_root = String::from_str(workspace_root).unwrap().replace('\\', "/");
let comps_name = get_components_name(&workspace_root, &metadata["packages"]);
for package in metadata["packages"].members_mut() {
@ -78,7 +78,7 @@ pub fn component_generate() -> Vec<ComponentInfo> {
// remove the last character
let mut path1 = paths.pop().unwrap().to_string();
path1.pop();
if path1.starts_with("/") {
if path1.starts_with('/') {
path1.remove(0);
}
path1
@ -101,7 +101,7 @@ pub fn get_component_toml_path() -> TokenStream {
let workspace_root = metadata["workspace_root"].as_str().unwrap();
let mut workspace_root = String::from_str(workspace_root)
.unwrap()
.replace("\\", "/")
.replace('\\', "/")
.add("/")
.add(COMPONENT_FILE_NAME)
.add("\"");
@ -141,10 +141,10 @@ fn get_components_name(workspace_root: &String, packages: &JsonValue) -> Vec<Str
}
/// read component file, return all the components name
fn read_component_file(workspace_root: &String) -> Vec<String> {
fn read_component_file(workspace_root: &str) -> Vec<String> {
let component_toml: toml::Value = {
let mut component_file_path = workspace_root.clone();
component_file_path.push_str("/");
let mut component_file_path = workspace_root.to_owned();
component_file_path.push('/');
component_file_path.push_str(COMPONENT_FILE_NAME);
let mut file = File::open(component_file_path)
.expect("Components.toml file not found, please check if the file exists");
@ -179,7 +179,7 @@ fn calculate_priority(
node_name: String,
) -> u16 {
if prioritys.contains_key(&node_name) {
return prioritys.get(&node_name).unwrap().clone();
return *prioritys.get(&node_name).unwrap();
}
let package = &package_mapping[&node_name];
@ -209,7 +209,5 @@ fn metadata() -> json::JsonValue {
}
let output = String::from_utf8(output.stdout).unwrap();
let parsed = json::parse(&output).unwrap();
parsed
json::parse(&output).unwrap()
}

View File

@ -4,7 +4,6 @@
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
#![feature(once_cell)]
extern crate alloc;
@ -132,7 +131,7 @@ fn match_and_call(
for registry in inventory::iter::<ComponentRegistry> {
// relative/path/to/comps/pci/src/lib.rs
let mut str: String = registry.path.to_owned();
str = str.replace("\\", "/");
str = str.replace('\\', "/");
// relative/path/to/comps/pci
// There are two cases, one in the test folder and one in the src folder.
// There may be multiple directories within the folder.
@ -148,7 +147,7 @@ fn match_and_call(
} else {
panic!("The path of {} cannot recognized by component system", str);
}
str = str.trim_end_matches("/").to_owned();
str = str.trim_end_matches('/').to_owned();
let mut info = components
.remove(&str)
@ -159,7 +158,7 @@ fn match_and_call(
debug!("Remain componets:{components:?}");
if components.len() != 0 {
if !components.is_empty() {
info!("Exists components that are not initialized");
}

View File

@ -68,7 +68,7 @@ where
type Item<'a> = Result<CpioEntry<'a, R>>;
/// Stops if reaches to the trailer entry or encounters an error.
fn next<'a>(self: &'a mut Self) -> Option<Self::Item<'a>> {
fn next(&mut self) -> Option<Self::Item<'_>> {
// Stop to iterate entries if encounters an error.
if self.is_error {
return None;
@ -159,7 +159,7 @@ where
while send_len < data_len {
let len = min(buffer.len(), data_len - send_len);
self.reader.read_exact(&mut buffer[..len])?;
writer.write_all(&mut buffer[..len])?;
writer.write_all(&buffer[..len])?;
send_len += len;
}
if self.data_padding_len > 0 {
@ -170,7 +170,7 @@ where
}
pub fn is_trailer(&self) -> bool {
&self.name == TRAILER_NAME
self.name == TRAILER_NAME
}
}

View File

@ -36,7 +36,7 @@ fn impl_try_from(
} else {
panic!(
"{} does not have invalid repr to implement TryFromInt.",
ident.to_string()
ident
);
};

View File

@ -83,13 +83,13 @@ fn is_generic_param(ident: Ident, generic_params: &Punctuated<GenericParam, Comm
match generic_param {
GenericParam::Type(type_param) => {
let type_param_ident = type_param.ident.clone();
if ident.to_string() == type_param_ident.to_string() {
if ident == type_param_ident {
return true;
}
}
GenericParam::Const(const_param) => {
let const_param_ident = const_param.ident.clone();
if ident.to_string() == const_param_ident.to_string() {
if const_param_ident == ident {
return true;
}
}

View File

@ -3,6 +3,7 @@ use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType};
use crate::prelude::*;
#[allow(clippy::module_inception)]
mod pty;
pub use pty::{PtyMaster, PtySlave};

View File

@ -88,7 +88,7 @@ impl PtyMaster {
impl FileLike for PtyMaster {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
// TODO: deal with nonblocking read
if buf.len() == 0 {
if buf.is_empty() {
return Ok(0);
}
@ -261,7 +261,7 @@ impl Device for PtySlave {
}
fn id(&self) -> crate::fs::device::DeviceId {
DeviceId::new(88, self.index() as u32)
DeviceId::new(88, self.index())
}
fn read(&self, buf: &mut [u8]) -> Result<usize> {

View File

@ -22,7 +22,7 @@ pub struct TtyDriver {
}
impl TtyDriver {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
ttys: SpinLock::new(Vec::new()),
}

View File

@ -31,6 +31,7 @@ pub struct LineDiscipline {
pollee: Pollee,
}
#[derive(Default)]
pub struct CurrentLine {
buffer: StaticRb<u8, BUFFER_CAPACITY>,
}
@ -66,6 +67,12 @@ impl CurrentLine {
}
}
impl Default for LineDiscipline {
fn default() -> Self {
Self::new()
}
}
impl LineDiscipline {
/// Create a new line discipline
pub fn new() -> Self {
@ -120,7 +127,7 @@ impl LineDiscipline {
}
}
if item >= 0x20 && item < 0x7f {
if (0x20..0x7f).contains(&item) {
// Printable character
self.current_line.lock_irq_disabled().push_char(item);
}
@ -174,7 +181,7 @@ impl LineDiscipline {
let backspace: &str = core::str::from_utf8(&[b'\x08', b' ', b'\x08']).unwrap();
echo_callback(backspace);
}
item if 0x20 <= item && item < 0x7f => print!("{}", char::from(item)),
item if (0x20..0x7f).contains(&item) => print!("{}", char::from(item)),
item if 0 < item && item < 0x20 && termios.contains_echo_ctl() => {
// The unprintable chars between 1-31 are mapped to ctrl characters between 65-95.
// e.g., 0x3 is mapped to 0x43, which is C. So, we will print ^C when 0x3 is met.
@ -263,25 +270,25 @@ impl LineDiscipline {
return 0;
}
let mut read_len = 0;
for i in 0..max_read_len {
for dst_i in dst.iter_mut().take(max_read_len) {
if let Some(next_char) = buffer.pop() {
let termios = self.termios.lock_irq_disabled();
if termios.is_canonical_mode() {
// canonical mode, read until meet new line
if meet_new_line(next_char, &termios) {
if !should_not_be_read(next_char, &termios) {
dst[i] = next_char;
*dst_i = next_char;
read_len += 1;
}
break;
} else {
dst[i] = next_char;
*dst_i = next_char;
read_len += 1;
}
} else {
// raw mode
// FIXME: avoid addtional bound check
dst[i] = next_char;
*dst_i = next_char;
read_len += 1;
}
} else {
@ -333,7 +340,7 @@ impl LineDiscipline {
self.foreground
.lock_irq_disabled()
.upgrade()
.and_then(|foreground| Some(foreground.pgid()))
.map(|foreground| foreground.pgid())
}
/// whether there is buffered data
@ -359,7 +366,7 @@ impl LineDiscipline {
}
pub fn window_size(&self) -> WinSize {
self.winsize.lock().clone()
*self.winsize.lock()
}
pub fn set_window_size(&self, winsize: WinSize) {
@ -384,9 +391,5 @@ fn meet_new_line(item: u8, termios: &KernelTermios) -> bool {
/// The special char should not be read by reading process
fn should_not_be_read(item: u8, termios: &KernelTermios) -> bool {
if item == *termios.get_special_char(CC_C_CHAR::VEOF) {
true
} else {
false
}
item == *termios.get_special_char(CC_C_CHAR::VEOF)
}

View File

@ -188,21 +188,21 @@ impl CC_C_CHAR {
match self {
CC_C_CHAR::VINTR => control_character('C'),
CC_C_CHAR::VQUIT => control_character('\\'),
CC_C_CHAR::VERASE => '\x7f' as u8,
CC_C_CHAR::VERASE => b'\x7f',
CC_C_CHAR::VKILL => control_character('U'),
CC_C_CHAR::VEOF => control_character('D'),
CC_C_CHAR::VTIME => '\0' as u8,
CC_C_CHAR::VTIME => b'\0',
CC_C_CHAR::VMIN => 1,
CC_C_CHAR::VSWTC => '\0' as u8,
CC_C_CHAR::VSWTC => b'\0',
CC_C_CHAR::VSTART => control_character('Q'),
CC_C_CHAR::VSTOP => control_character('S'),
CC_C_CHAR::VSUSP => control_character('Z'),
CC_C_CHAR::VEOL => '\0' as u8,
CC_C_CHAR::VEOL => b'\0',
CC_C_CHAR::VREPRINT => control_character('R'),
CC_C_CHAR::VDISCARD => control_character('O'),
CC_C_CHAR::VWERASE => control_character('W'),
CC_C_CHAR::VLNEXT => control_character('V'),
CC_C_CHAR::VEOL2 => '\0' as u8,
CC_C_CHAR::VEOL2 => b'\0',
}
}
}
@ -218,8 +218,8 @@ pub struct KernelTermios {
c_cc: [CcT; KERNEL_NCCS],
}
impl KernelTermios {
pub fn default() -> Self {
impl Default for KernelTermios {
fn default() -> Self {
let mut termios = Self {
c_iflags: C_IFLAGS::default(),
c_oflags: C_OFLAGS::default(),
@ -247,7 +247,9 @@ impl KernelTermios {
*termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.default_char();
termios
}
}
impl KernelTermios {
pub fn get_special_char(&self, cc_c_char: CC_C_CHAR) -> &CcT {
&self.c_cc[cc_c_char as usize]
}
@ -292,8 +294,8 @@ impl KernelTermios {
}
const fn control_character(c: char) -> u8 {
debug_assert!(c as u8 >= 'A' as u8);
c as u8 - 'A' as u8 + 1u8
debug_assert!(c as u8 >= b'A');
c as u8 - b'A' + 1u8
}
#[derive(Debug, Clone, Copy, Default, Pod)]

View File

@ -268,13 +268,13 @@ impl From<int_to_c_enum::TryFromIntError> for Error {
#[macro_export]
macro_rules! return_errno {
($errno: expr) => {
return core::prelude::v1::Err(crate::error::Error::new($errno))
return Err($crate::error::Error::new($errno))
};
}
#[macro_export]
macro_rules! return_errno_with_message {
($errno: expr, $message: expr) => {
return core::prelude::v1::Err(crate::error::Error::with_message($errno, $message))
return Err($crate::error::Error::with_message($errno, $message))
};
}

View File

@ -1,3 +1,4 @@
#[allow(clippy::module_inception)]
mod events;
mod observer;
mod subject;

View File

@ -14,13 +14,12 @@ pub struct Subject<E: Events, F: EventsFilter<E> = ()> {
}
impl<E: Events, F: EventsFilter<E>> Subject<E, F> {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
observers: Mutex::new(BTreeMap::new()),
num_observers: AtomicUsize::new(0),
}
}
/// Register an observer.
///
/// A registered observer will get notified through its `on_events` method.

View File

@ -79,9 +79,9 @@ impl Debug for DeviceId {
}
}
impl Into<u64> for DeviceId {
fn into(self) -> u64 {
self.0
impl From<DeviceId> for u64 {
fn from(value: DeviceId) -> Self {
value.0
}
}

View File

@ -43,13 +43,12 @@ pub struct DevPts {
impl DevPts {
pub fn new() -> Arc<Self> {
let sb = SuperBlock::new(DEVPTS_MAGIC, BLOCK_SIZE, NAME_MAX);
let devpts = Arc::new_cyclic(|weak_self| Self {
Arc::new_cyclic(|weak_self| Self {
root: RootInode::new(weak_self.clone(), &sb),
sb,
index_alloc: Mutex::new(IdAlloc::with_capacity(MAX_PTY_NUM)),
this: weak_self.clone(),
});
devpts
})
}
/// Create the master and slave pair.
@ -194,7 +193,7 @@ impl Inode for RootInode {
// Read the slaves.
let slaves = self.slaves.read();
let start_offset = offset.clone();
let start_offset = *offset;
for (idx, (name, node)) in slaves
.idxes_and_items()
.map(|(idx, (name, node))| (idx + 3, (name, node)))
@ -239,7 +238,7 @@ impl Inode for RootInode {
.slaves
.read()
.idxes_and_items()
.find(|(_, (child_name, _))| child_name == &slave)
.find(|(_, (child_name, _))| child_name == slave)
.map(|(_, (_, node))| node.clone())
.ok_or(Error::new(Errno::ENOENT))?,
};

View File

@ -17,7 +17,7 @@ pub struct FileTable {
}
impl FileTable {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
table: SlotVec::new(),
subject: Subject::new(),

View File

@ -23,6 +23,12 @@ impl Clone for FsResolver {
}
}
impl Default for FsResolver {
fn default() -> Self {
Self::new()
}
}
impl FsResolver {
pub fn new() -> Self {
Self {
@ -86,14 +92,13 @@ impl FsResolver {
}
let (dir_dentry, file_name) =
self.lookup_dir_and_base_name_inner(path, follow_tail_link)?;
if file_name.ends_with("/") {
if file_name.ends_with('/') {
return_errno_with_message!(Errno::EISDIR, "path refers to a directory");
}
if !dir_dentry.vnode().inode_mode().is_writable() {
return_errno_with_message!(Errno::EACCES, "file cannot be created");
}
let new_dentry = dir_dentry.create(&file_name, InodeType::File, inode_mode)?;
new_dentry
dir_dentry.create(&file_name, InodeType::File, inode_mode)?
}
Err(e) => return Err(e),
};
@ -148,7 +153,7 @@ impl FsResolver {
relative_path: &str,
follow_tail_link: bool,
) -> Result<Arc<Dentry>> {
debug_assert!(!relative_path.starts_with("/"));
debug_assert!(!relative_path.starts_with('/'));
if relative_path.len() > PATH_MAX {
return_errno_with_message!(Errno::ENAMETOOLONG, "path is too long");
@ -195,11 +200,11 @@ impl FsResolver {
};
// Change the dentry and relative path according to symlink
if link_path_remain.starts_with("/") {
if link_path_remain.starts_with('/') {
dentry = self.root.clone();
}
link_path.clear();
link_path.push_str(&link_path_remain.trim_start_matches('/'));
link_path.push_str(link_path_remain.trim_start_matches('/'));
relative_path = &link_path;
follows += 1;
} else {
@ -269,20 +274,20 @@ impl FsResolver {
// Dereference the tail symlinks if needed
loop {
match dir_dentry.lookup(&base_name.trim_end_matches('/')) {
match dir_dentry.lookup(base_name.trim_end_matches('/')) {
Ok(dentry) if dentry.vnode().inode_type() == InodeType::SymLink => {
let link = {
let mut link = dentry.vnode().read_link()?;
if link.is_empty() {
return_errno_with_message!(Errno::ENOENT, "invalid symlink");
}
if base_name.ends_with("/") && !link.ends_with("/") {
if base_name.ends_with('/') && !link.ends_with('/') {
link += "/";
}
link
};
let (dir, file_name) = split_path(&link);
if dir.starts_with("/") {
if dir.starts_with('/') {
dir_dentry =
self.lookup_from_parent(&self.root, dir.trim_start_matches('/'), true)?;
base_name = String::from(file_name);
@ -326,7 +331,7 @@ impl<'a> FsPath<'a> {
return_errno_with_message!(Errno::ENAMETOOLONG, "path name too long");
}
let fs_path_inner = if path.starts_with("/") {
let fs_path_inner = if path.starts_with('/') {
FsPathInner::Absolute(path)
} else if dirfd >= 0 {
if path.is_empty() {

View File

@ -53,7 +53,7 @@ impl InodeHandle<Rights> {
impl Clone for InodeHandle<Rights> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
Self(self.0.clone(), self.1)
}
}

View File

@ -43,8 +43,7 @@ impl ProcFS {
}
pub(in crate::fs::procfs) fn alloc_id(&self) -> usize {
let next_id = self.inode_allocator.fetch_add(1, Ordering::SeqCst);
next_id
self.inode_allocator.fetch_add(1, Ordering::SeqCst)
}
}

View File

@ -151,6 +151,7 @@ impl OptionalBuilder {
self
}
#[allow(clippy::type_complexity)]
pub fn build(self) -> Result<(Arc<dyn FileSystem>, Option<Weak<dyn Inode>>, bool)> {
if self.parent.is_none() && self.fs.is_none() {
return_errno_with_message!(Errno::EINVAL, "must have parent or fs");

View File

@ -124,7 +124,7 @@ impl<D: DirOps + 'static> Inode for ProcDir<D> {
// Read the normal child entries.
self.inner.populate_children(self.this.clone());
let cached_children = self.cached_children.read();
let start_offset = offset.clone();
let start_offset = *offset;
for (idx, (name, child)) in cached_children
.idxes_and_items()
.map(|(idx, (name, child))| (idx + 2, (name, child)))

View File

@ -157,6 +157,7 @@ impl Inode_ {
}
}
#[allow(clippy::large_enum_variant)]
enum Inner {
Dir(DirEntry),
File,
@ -232,8 +233,7 @@ impl DirEntry {
} else {
self.children
.iter()
.find(|(child, _)| child == &Str256::from(name))
.is_some()
.any(|(child, _)| child == &Str256::from(name))
}
}
@ -292,7 +292,7 @@ impl DirEntry {
*idx += 1;
}
// Read the normal child entries.
let start_idx = idx.clone();
let start_idx = *idx;
for (offset, (name, child)) in self
.children
.idxes_and_items()

View File

@ -15,17 +15,11 @@ pub enum AccessMode {
impl AccessMode {
pub fn is_readable(&self) -> bool {
match *self {
AccessMode::O_RDONLY | AccessMode::O_RDWR => true,
_ => false,
}
matches!(*self, AccessMode::O_RDONLY | AccessMode::O_RDWR)
}
pub fn is_writable(&self) -> bool {
match *self {
AccessMode::O_WRONLY | AccessMode::O_RDWR => true,
_ => false,
}
matches!(*self, AccessMode::O_WRONLY | AccessMode::O_RDWR)
}
}

View File

@ -162,7 +162,7 @@ impl<T: Copy> Producer<T> {
return_errno!(Errno::EPIPE);
}
if buf.len() == 0 {
if buf.is_empty() {
return Ok(0);
}
@ -249,7 +249,7 @@ impl<T: Copy> Consumer<T> {
if self.is_shutdown() {
return_errno!(Errno::EPIPE);
}
if buf.len() == 0 {
if buf.is_empty() {
return Ok(0);
}

View File

@ -58,7 +58,7 @@ impl Dentry {
if !self.is_mountpoint() {
return self.this();
}
match self.mount_node().get(&self) {
match self.mount_node().get(self) {
Some(child_mount) => child_mount.root_dentry().overlaid_dentry(),
None => self.this(),
}
@ -126,7 +126,7 @@ impl Dentry {
/// Get the DentryKey.
pub fn key(&self) -> DentryKey {
DentryKey::new(&self)
DentryKey::new(self)
}
/// Get the vnode.
@ -331,7 +331,7 @@ impl Dentry {
Some(dentry) => {
children.delete_dentry(old_name);
dentry.set_name_and_parent(new_name, self.this());
children.insert_dentry(&dentry);
children.insert_dentry(dentry);
}
None => {
children.delete_dentry(new_name);
@ -343,7 +343,7 @@ impl Dentry {
return_errno_with_message!(Errno::EXDEV, "cannot cross mount");
}
let (mut self_children, mut new_dir_children) =
write_lock_children_on_two_dentries(&self, &new_dir);
write_lock_children_on_two_dentries(self, new_dir);
let old_dentry = self_children.find_dentry_with_checking_mountpoint(old_name)?;
let _ = new_dir_children.find_dentry_with_checking_mountpoint(new_name)?;
self.vnode.rename(old_name, &new_dir.vnode, new_name)?;
@ -351,7 +351,7 @@ impl Dentry {
Some(dentry) => {
self_children.delete_dentry(old_name);
dentry.set_name_and_parent(new_name, new_dir.this());
new_dir_children.insert_dentry(&dentry);
new_dir_children.insert_dentry(dentry);
}
None => {
new_dir_children.delete_dentry(new_name);
@ -473,7 +473,7 @@ impl Dentry {
}
}
debug_assert!(path.starts_with("/"));
debug_assert!(path.starts_with('/'));
path
}
}

View File

@ -14,11 +14,7 @@ pub trait DirEntryVecExt {
impl DirEntryVecExt for SlotVec<(String, Arc<dyn Inode>)> {
fn put_entry_if_not_found(&mut self, name: &str, f: impl Fn() -> Arc<dyn Inode>) {
if self
.iter()
.find(|(child_name, _)| child_name == name)
.is_none()
{
if !self.iter().any(|(child_name, _)| child_name == name) {
let inode = f();
self.put((String::from(name), inode));
}

View File

@ -23,23 +23,17 @@ pub enum InodeType {
impl InodeType {
pub fn support_read(&self) -> bool {
match self {
InodeType::File
| InodeType::Socket
| InodeType::CharDevice
| InodeType::BlockDevice => true,
_ => false,
}
matches!(
self,
InodeType::File | InodeType::Socket | InodeType::CharDevice | InodeType::BlockDevice
)
}
pub fn support_write(&self) -> bool {
match self {
InodeType::File
| InodeType::Socket
| InodeType::CharDevice
| InodeType::BlockDevice => true,
_ => false,
}
matches!(
self,
InodeType::File | InodeType::Socket | InodeType::CharDevice | InodeType::BlockDevice
)
}
pub fn is_reguler_file(&self) -> bool {
@ -232,6 +226,10 @@ impl Metadata {
pub trait Inode: Any + Sync + Send {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn resize(&self, new_size: usize);
fn metadata(&self) -> Metadata;

View File

@ -106,13 +106,11 @@ impl Pager for PageCacheManager {
let page_idx = offset / PAGE_SIZE;
let mut pages = self.pages.lock();
if let Some(page) = pages.pop(&page_idx) {
match page.state() {
PageState::Dirty => self
.backed_inode
if let PageState::Dirty = page.state() {
self.backed_inode
.upgrade()
.unwrap()
.write_page(page_idx, &page.frame())?,
_ => (),
.write_page(page_idx, &page.frame())?
}
} else {
warn!("page {} is not in page cache, do nothing", page_idx);

View File

@ -53,8 +53,7 @@ impl Pollee {
self.register_poller(poller.unwrap(), mask);
// It is important to check events again to handle race conditions
let revents = self.events() & mask;
revents
self.events() & mask
}
fn register_poller(&self, poller: &Poller, mask: IoEvents) {
@ -139,6 +138,12 @@ struct PollerInner {
pollees: Mutex<BTreeMap<KeyableWeak<PolleeInner>, ()>>,
}
impl Default for Poller {
fn default() -> Self {
Self::new()
}
}
impl Poller {
/// Constructs a new `Poller`.
pub fn new() -> Self {

View File

@ -235,6 +235,10 @@ impl Vnode {
self.inner.read().inode.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn atime(&self) -> Duration {
self.inner.read().inode.atime()
}
@ -257,7 +261,7 @@ impl Vnode {
pub fn writer(&self, from_offset: usize) -> VnodeWriter {
VnodeWriter {
inner: &self,
inner: self,
offset: from_offset,
}
}

View File

@ -15,6 +15,7 @@ pub struct AnyUnboundSocket {
pollee: Pollee,
}
#[allow(clippy::large_enum_variant)]
pub(super) enum AnyRawSocket {
Tcp(RawTcpSocket),
Udp(RawUdpSocket),

View File

@ -2,6 +2,7 @@ use core::sync::atomic::{AtomicU64, Ordering};
use super::Ipv4Address;
use crate::prelude::*;
use alloc::collections::btree_map::Entry;
use keyable_arc::KeyableWeak;
use smoltcp::{
iface::{SocketHandle, SocketSet},
@ -62,8 +63,8 @@ impl IfaceCommon {
fn alloc_ephemeral_port(&self) -> Result<u16> {
let mut used_ports = self.used_ports.write();
for port in IP_LOCAL_PORT_START..=IP_LOCAL_PORT_END {
if !used_ports.contains_key(&port) {
used_ports.insert(port, 0);
if let Entry::Vacant(e) = used_ports.entry(port) {
e.insert(0);
return Ok(port);
}
}
@ -74,7 +75,7 @@ impl IfaceCommon {
let mut used_ports = self.used_ports.write();
if let Some(used_times) = used_ports.get_mut(&port) {
if *used_times == 0 || can_reuse {
*used_times = *used_times + 1;
*used_times += 1;
} else {
return_errno_with_message!(Errno::EADDRINUSE, "cannot bind port");
}
@ -163,7 +164,7 @@ impl IfaceCommon {
}
fn insert_bound_socket(&self, socket: &Arc<AnyBoundSocket>) -> Result<()> {
let weak_ref = KeyableWeak::from(Arc::downgrade(&socket));
let weak_ref = KeyableWeak::from(Arc::downgrade(socket));
let mut bound_sockets = self.bound_sockets.write();
if bound_sockets.contains(&weak_ref) {
return_errno_with_message!(Errno::EINVAL, "the socket is already bound");

View File

@ -28,7 +28,7 @@ impl IfaceLoopback {
let config = Config::new();
let mut interface = smoltcp::iface::Interface::new(config, &mut loopback);
interface.update_ip_addrs(|ip_addrs| {
debug_assert!(ip_addrs.len() == 0);
debug_assert!(ip_addrs.is_empty());
let ip_addr = IpCidr::new(LOOPBACK_ADDRESS, LOOPBACK_ADDRESS_PREFIX_LEN);
ip_addrs.push(ip_addr).unwrap();
});

View File

@ -21,22 +21,16 @@ impl BindPortConfig {
} else {
Self::Specified(port)
}
} else {
if can_reuse {
} else if can_reuse {
return_errno_with_message!(Errno::EINVAL, "invalid bind port config");
} else {
Self::Ephemeral
}
};
Ok(config)
}
pub(super) fn can_reuse(&self) -> bool {
if let Self::CanReuse(_) = self {
true
} else {
false
}
matches!(self, Self::CanReuse(_))
}
pub(super) fn port(&self) -> Option<u16> {

View File

@ -19,7 +19,7 @@ pub struct IfaceVirtio {
impl IfaceVirtio {
pub fn new() -> Arc<Self> {
let mut virtio_net = jinux_network::get_device(&(DEVICE_NAME).to_string()).unwrap();
let virtio_net = jinux_network::get_device(&(DEVICE_NAME).to_string()).unwrap();
let interface = {
let mac_addr = virtio_net.lock().mac_addr();
let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0);
@ -33,7 +33,7 @@ impl IfaceVirtio {
};
let mut interface = smoltcp::iface::Interface::new(config, &mut **virtio_net.lock());
interface.update_ip_addrs(|ip_addrs| {
debug_assert!(ip_addrs.len() == 0);
debug_assert!(ip_addrs.is_empty());
ip_addrs.push(ip_addr).unwrap();
});
interface

View File

@ -37,11 +37,7 @@ enum Inner {
impl Inner {
fn is_bound(&self) -> bool {
if let Inner::Bound { .. } = self {
true
} else {
false
}
matches!(self, Inner::Bound { .. })
}
fn bind(&mut self, endpoint: IpEndpoint) -> Result<()> {
@ -91,7 +87,7 @@ impl Inner {
remote_endpoint, ..
} = self
{
remote_endpoint.clone()
*remote_endpoint
} else {
None
}

View File

@ -72,7 +72,7 @@ impl Inner {
fn bound_socket(&self) -> Option<&Arc<AnyBoundSocket>> {
match self {
Inner::Bound(bound_socket) => Some(&bound_socket),
Inner::Bound(bound_socket) => Some(bound_socket),
Inner::Connecting { bound_socket, .. } => Some(bound_socket),
_ => None,
}
@ -96,8 +96,7 @@ impl Inner {
fn local_endpoint(&self) -> Option<IpEndpoint> {
self.bound_socket()
.map(|socket| socket.local_endpoint())
.flatten()
.and_then(|socket| socket.local_endpoint())
}
fn remote_endpoint(&self) -> Option<IpEndpoint> {

View File

@ -105,7 +105,7 @@ impl ListenStream {
backlog_socket.poll(mask, poller);
}
}
return IoEvents::empty();
IoEvents::empty()
}
fn bound_socket(&self) -> Arc<AnyBoundSocket> {

View File

@ -52,7 +52,7 @@ impl Endpoint {
}
pub(super) fn peer_addr(&self) -> Option<UnixSocketAddrBound> {
self.0.peer.upgrade().map(|peer| peer.addr()).flatten()
self.0.peer.upgrade().and_then(|peer| peer.addr())
}
pub(super) fn is_nonblocking(&self) -> bool {

View File

@ -205,7 +205,7 @@ fn create_keyable_inode(dentry: &Arc<Dentry>) -> KeyableWeak<dyn Inode> {
}
pub(super) fn unregister_backlog(addr: &UnixSocketAddrBound) {
BACKLOG_TABLE.remove_backlog(&addr);
BACKLOG_TABLE.remove_backlog(addr);
}
pub(super) fn push_incoming(

View File

@ -2,6 +2,6 @@ mod connected;
mod endpoint;
mod init;
mod listener;
mod stream;
mod socket;
pub use stream::UnixStreamSocket;
pub use socket::UnixStreamSocket;

View File

@ -233,10 +233,8 @@ impl Socket for UnixStreamSocket {
};
match connected.peer_addr() {
None => return Ok(SocketAddr::Unix(UnixSocketAddr::Path(String::new()))),
Some(peer_addr) => {
return Ok(SocketAddr::from(peer_addr.clone()));
}
None => Ok(SocketAddr::Unix(UnixSocketAddr::Path(String::new()))),
Some(peer_addr) => Ok(SocketAddr::from(peer_addr.clone())),
}
}
@ -295,5 +293,5 @@ fn lookup_socket_file(path: &str) -> Result<Arc<Dentry>> {
if !dentry.inode_mode().is_readable() || !dentry.inode_mode().is_writable() {
return_errno_with_message!(Errno::EACCES, "the socket cannot be read or written")
}
return Ok(dentry);
Ok(dentry)
}

View File

@ -28,7 +28,7 @@ pub(crate) use pod::Pod;
#[macro_export]
macro_rules! current {
() => {
crate::process::Process::current()
$crate::process::Process::current()
};
}
@ -36,7 +36,7 @@ macro_rules! current {
#[macro_export]
macro_rules! current_thread {
() => {
crate::thread::Thread::current()
$crate::thread::Thread::current()
};
}

View File

@ -178,7 +178,7 @@ fn clone_child_thread(parent_context: UserContext, clone_args: CloneArgs) -> Res
// inherit sigmask from current thread
let current_thread = current_thread!();
let current_posix_thread = current_thread.as_posix_thread().unwrap();
let sig_mask = current_posix_thread.sig_mask().lock().clone();
let sig_mask = *current_posix_thread.sig_mask().lock();
let is_main_thread = child_tid == current.pid();
let thread_builder = PosixThreadBuilder::new(child_tid, child_user_space)
.process(Arc::downgrade(&current))
@ -241,7 +241,7 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re
// inherit parent's sig mask
let current_thread = current_thread!();
let posix_thread = current_thread.as_posix_thread().unwrap();
let child_sig_mask = posix_thread.sig_mask().lock().clone();
let child_sig_mask = *posix_thread.sig_mask().lock();
let child_tid = allocate_tid();
let mut child_thread_builder = PosixThreadBuilder::new(child_tid, child_user_space)
@ -338,7 +338,7 @@ fn clone_cpu_context(
tls: u64,
clone_flags: CloneFlags,
) -> UserContext {
let mut child_context = parent_context.clone();
let mut child_context = parent_context;
// The return value of child thread is zero
child_context.set_rax(0);
@ -390,7 +390,7 @@ fn clone_sighand(
if clone_flags.contains(CloneFlags::CLONE_SIGHAND) {
parent_sig_dispositions.clone()
} else {
Arc::new(Mutex::new(parent_sig_dispositions.lock().clone()))
Arc::new(Mutex::new(*parent_sig_dispositions.lock()))
}
}

Some files were not shown because too many files have changed in this diff Show More