Skip to content

Commit 9dc1001

Browse files
committed
Refactor module
1 parent 3e0e19f commit 9dc1001

File tree

11 files changed

+118
-104
lines changed

11 files changed

+118
-104
lines changed

src/sys/fs/block_device.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ impl BlockDeviceIO for MemBlockDevice {
8686
}
8787

8888
pub fn mount_mem() {
89-
let mem = sys::allocator::memory_size() / 2; // Half the allocatable memory
89+
let mem = sys::mem::memory_size() / 2; // Half the allocatable memory
9090
let len = mem / super::BLOCK_SIZE; // TODO: take a size argument
9191
let dev = MemBlockDevice::new(len);
9292
*BLOCK_DEVICE.lock() = Some(BlockDevice::Mem(dev));

src/sys/idt.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ extern "x86-interrupt" fn page_fault_handler(
138138
};
139139

140140
if error_code.contains(PageFaultErrorCode::CAUSED_BY_WRITE) {
141-
if sys::allocator::alloc_pages(&mut mapper, addr, 1).is_err() {
141+
if sys::mem::alloc_pages(&mut mapper, addr, 1).is_err() {
142142
printk!(
143143
"{}Error:{} Could not allocate page at {:#X}\n",
144144
csi_color, csi_reset, addr
@@ -154,7 +154,7 @@ extern "x86-interrupt" fn page_fault_handler(
154154
// longer a simple clone of the kernel page table. Currently a process
155155
// is executed from its kernel address that is shared with the process.
156156
let start = (addr / 4096) * 4096;
157-
if sys::allocator::alloc_pages(&mut mapper, start, 4096).is_ok() {
157+
if sys::mem::alloc_pages(&mut mapper, start, 4096).is_ok() {
158158
if sys::process::is_userspace(start) {
159159
let code_addr = sys::process::code_addr();
160160
let src = (code_addr + start) as *mut u8;

src/sys/mem/heap.rs

+8-82
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
11
use crate::sys;
22

3-
use alloc::slice::SliceIndex;
4-
use alloc::sync::Arc;
5-
use alloc::vec;
6-
use alloc::vec::Vec;
73
use core::cmp;
8-
use core::ops::{Index, IndexMut};
94
use linked_list_allocator::LockedHeap;
10-
use spin::Mutex;
115
use x86_64::structures::paging::{
126
mapper::MapToError, page::PageRangeInclusive,
137
FrameAllocator, Mapper, OffsetPageTable, Page, PageTableFlags, Size4KiB,
@@ -19,18 +13,18 @@ static ALLOCATOR: LockedHeap = LockedHeap::empty();
1913

2014
pub const HEAP_START: u64 = 0x4444_4444_0000;
2115

22-
fn max_memory() -> u64 {
16+
fn max_memory() -> usize {
2317
// Default to 32 MB
24-
option_env!("MOROS_MEMORY").unwrap_or("32").parse::<u64>().unwrap() << 20
18+
option_env!("MOROS_MEMORY").unwrap_or("32").parse::<usize>().unwrap() << 20
2519
}
2620

2721
pub fn init_heap() -> Result<(), MapToError<Size4KiB>> {
28-
let mapper = sys::mem::mapper();
29-
let mut frame_allocator = sys::mem::frame_allocator();
22+
let mapper = super::mapper();
23+
let mut frame_allocator = super::frame_allocator();
3024

3125
// Use half of the memory for the heap caped to 16 MB by default
3226
// because the allocator is slow.
33-
let heap_size = cmp::min(sys::mem::memory_size(), max_memory()) / 2;
27+
let heap_size = (cmp::min(super::memory_size(), max_memory()) / 2) as u64;
3428
let heap_start = VirtAddr::new(HEAP_START);
3529
sys::process::init_process_addr(HEAP_START + heap_size);
3630

@@ -117,83 +111,15 @@ pub fn free_pages(mapper: &mut OffsetPageTable, addr: u64, size: usize) {
117111
}
118112
}
119113

120-
#[derive(Clone)]
121-
pub struct PhysBuf {
122-
buf: Arc<Mutex<Vec<u8>>>,
123-
}
124-
125-
impl PhysBuf {
126-
pub fn new(len: usize) -> Self {
127-
Self::from(vec![0; len])
128-
}
129-
130-
// Realloc vec until it uses a chunk of contiguous physical memory
131-
fn from(vec: Vec<u8>) -> Self {
132-
let buffer_end = vec.len() - 1;
133-
let memory_end = phys_addr(&vec[buffer_end]) - phys_addr(&vec[0]);
134-
if buffer_end == memory_end as usize {
135-
Self {
136-
buf: Arc::new(Mutex::new(vec)),
137-
}
138-
} else {
139-
Self::from(vec.clone()) // Clone vec and try again
140-
}
141-
}
142-
143-
pub fn addr(&self) -> u64 {
144-
phys_addr(&self.buf.lock()[0])
145-
}
146-
}
147-
148-
pub fn phys_addr(ptr: *const u8) -> u64 {
149-
let virt_addr = VirtAddr::new(ptr as u64);
150-
let phys_addr = sys::mem::virt_to_phys(virt_addr).unwrap();
151-
phys_addr.as_u64()
152-
}
153-
154-
impl<I: SliceIndex<[u8]>> Index<I> for PhysBuf {
155-
type Output = I::Output;
156-
157-
#[inline]
158-
fn index(&self, index: I) -> &Self::Output {
159-
Index::index(&**self, index)
160-
}
161-
}
162-
163-
impl<I: SliceIndex<[u8]>> IndexMut<I> for PhysBuf {
164-
#[inline]
165-
fn index_mut(&mut self, index: I) -> &mut Self::Output {
166-
IndexMut::index_mut(&mut **self, index)
167-
}
168-
}
169-
170-
impl core::ops::Deref for PhysBuf {
171-
type Target = [u8];
172-
173-
fn deref(&self) -> &[u8] {
174-
let vec = self.buf.lock();
175-
unsafe { alloc::slice::from_raw_parts(vec.as_ptr(), vec.len()) }
176-
}
177-
}
178-
179-
impl core::ops::DerefMut for PhysBuf {
180-
fn deref_mut(&mut self) -> &mut [u8] {
181-
let mut vec = self.buf.lock();
182-
unsafe {
183-
alloc::slice::from_raw_parts_mut(vec.as_mut_ptr(), vec.len())
184-
}
185-
}
186-
}
187-
188-
pub fn memory_size() -> usize {
114+
pub fn heap_size() -> usize {
189115
ALLOCATOR.lock().size()
190116
}
191117

192-
pub fn memory_used() -> usize {
118+
pub fn heap_used() -> usize {
193119
ALLOCATOR.lock().used()
194120
}
195121

196-
pub fn memory_free() -> usize {
122+
pub fn heap_free() -> usize {
197123
ALLOCATOR.lock().free()
198124
}
199125

src/sys/mem/mod.rs

+19-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1+
mod heap;
2+
mod phys;
3+
4+
pub use heap::{alloc_pages, free_pages};
5+
pub use phys::{phys_addr, PhysBuf};
6+
17
use crate::sys;
28
use bootloader::bootinfo::{BootInfo, MemoryMap, MemoryRegionType};
3-
use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
9+
use core::sync::atomic::{AtomicUsize, Ordering};
410
//use x86_64::instructions::interrupts;
511
use x86_64::registers::control::Cr3;
612
use x86_64::structures::paging::{
@@ -11,7 +17,7 @@ use x86_64::{PhysAddr, VirtAddr};
1117
pub static mut PHYS_MEM_OFFSET: Option<u64> = None;
1218
static mut MEMORY_MAP: Option<&MemoryMap> = None;
1319
static mut MAPPER: Option<OffsetPageTable<'static>> = None;
14-
static MEMORY_SIZE: AtomicU64 = AtomicU64::new(0);
20+
static MEMORY_SIZE: AtomicUsize = AtomicUsize::new(0);
1521
static ALLOCATED_FRAMES: AtomicUsize = AtomicUsize::new(0);
1622

1723
pub fn init(boot_info: &'static BootInfo) {
@@ -46,7 +52,7 @@ pub fn init(boot_info: &'static BootInfo) {
4652
memory_size += (320 - 256 - 16) << 10;
4753

4854
log!("RAM {} MB", memory_size >> 20);
49-
MEMORY_SIZE.store(memory_size, Ordering::Relaxed);
55+
MEMORY_SIZE.store(memory_size as usize, Ordering::Relaxed);
5056

5157
let phys_mem_offset = boot_info.physical_memory_offset;
5258

@@ -59,7 +65,7 @@ pub fn init(boot_info: &'static BootInfo) {
5965
))
6066
};
6167

62-
sys::allocator::init_heap().expect("heap initialization failed");
68+
heap::init_heap().expect("heap initialization failed");
6369
//});
6470
sys::idt::clear_irq_mask(1);
6571
}
@@ -68,10 +74,18 @@ pub fn mapper() -> &'static mut OffsetPageTable<'static> {
6874
unsafe { sys::mem::MAPPER.as_mut().unwrap() }
6975
}
7076

71-
pub fn memory_size() -> u64 {
77+
pub fn memory_size() -> usize {
7278
MEMORY_SIZE.load(Ordering::Relaxed)
7379
}
7480

81+
pub fn memory_used() -> usize {
82+
(memory_size() - heap::heap_size()) + heap::heap_used()
83+
}
84+
85+
pub fn memory_free() -> usize {
86+
(memory_size() - heap::heap_size()) + heap::heap_free()
87+
}
88+
7589
pub fn phys_to_virt(addr: PhysAddr) -> VirtAddr {
7690
let phys_mem_offset = unsafe {
7791
PHYS_MEM_OFFSET.unwrap()

src/sys/mem/phys.rs

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
use alloc::slice::SliceIndex;
2+
use alloc::sync::Arc;
3+
use alloc::vec;
4+
use alloc::vec::Vec;
5+
use core::ops::{Index, IndexMut};
6+
use spin::Mutex;
7+
use x86_64::VirtAddr;
8+
9+
#[derive(Clone)]
10+
pub struct PhysBuf {
11+
buf: Arc<Mutex<Vec<u8>>>,
12+
}
13+
14+
impl PhysBuf {
15+
pub fn new(len: usize) -> Self {
16+
Self::from(vec![0; len])
17+
}
18+
19+
// Realloc vec until it uses a chunk of contiguous physical memory
20+
fn from(vec: Vec<u8>) -> Self {
21+
let buffer_end = vec.len() - 1;
22+
let memory_end = phys_addr(&vec[buffer_end]) - phys_addr(&vec[0]);
23+
if buffer_end == memory_end as usize {
24+
Self {
25+
buf: Arc::new(Mutex::new(vec)),
26+
}
27+
} else {
28+
Self::from(vec.clone()) // Clone vec and try again
29+
}
30+
}
31+
32+
pub fn addr(&self) -> u64 {
33+
phys_addr(&self.buf.lock()[0])
34+
}
35+
}
36+
37+
impl<I: SliceIndex<[u8]>> Index<I> for PhysBuf {
38+
type Output = I::Output;
39+
40+
#[inline]
41+
fn index(&self, index: I) -> &Self::Output {
42+
Index::index(&**self, index)
43+
}
44+
}
45+
46+
impl<I: SliceIndex<[u8]>> IndexMut<I> for PhysBuf {
47+
#[inline]
48+
fn index_mut(&mut self, index: I) -> &mut Self::Output {
49+
IndexMut::index_mut(&mut **self, index)
50+
}
51+
}
52+
53+
impl core::ops::Deref for PhysBuf {
54+
type Target = [u8];
55+
56+
fn deref(&self) -> &[u8] {
57+
let vec = self.buf.lock();
58+
unsafe { alloc::slice::from_raw_parts(vec.as_ptr(), vec.len()) }
59+
}
60+
}
61+
62+
impl core::ops::DerefMut for PhysBuf {
63+
fn deref_mut(&mut self) -> &mut [u8] {
64+
let mut vec = self.buf.lock();
65+
unsafe {
66+
alloc::slice::from_raw_parts_mut(vec.as_mut_ptr(), vec.len())
67+
}
68+
}
69+
}
70+
71+
pub fn phys_addr(ptr: *const u8) -> u64 {
72+
let virt_addr = VirtAddr::new(ptr as u64);
73+
let phys_addr = super::virt_to_phys(virt_addr).unwrap();
74+
phys_addr.as_u64()
75+
}

src/sys/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ macro_rules! log {
3838
}
3939

4040
pub mod acpi;
41-
pub mod allocator;
4241
pub mod ata;
4342
pub mod clock;
4443
pub mod cmos;

src/sys/net/nic/e1000.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::sys;
2-
use crate::sys::allocator::PhysBuf;
2+
use crate::sys::mem::PhysBuf;
33
use crate::sys::net::{EthernetDeviceIO, Config, Stats};
44
use spin::Mutex;
55

@@ -209,7 +209,7 @@ impl Device {
209209
}
210210

211211
let ptr = ptr::addr_of!(rx_descs[0]) as *const u8;
212-
let phys_addr = sys::allocator::phys_addr(ptr);
212+
let phys_addr = sys::mem::phys_addr(ptr);
213213

214214
// Ring address and length
215215
self.write(REG_RDBAL, phys_addr.get_bits(0..32) as u32);
@@ -235,7 +235,7 @@ impl Device {
235235
}
236236

237237
let ptr = ptr::addr_of!(tx_descs[0]) as *const _;
238-
let phys_addr = sys::allocator::phys_addr(ptr);
238+
let phys_addr = sys::mem::phys_addr(ptr);
239239

240240
// Ring address and length
241241
self.write(REG_TDBAL, phys_addr.get_bits(0..32) as u32);
@@ -352,7 +352,7 @@ impl Device {
352352
let rx_descs = self.rx_descs.lock();
353353
for i in 0..RX_BUFFERS_COUNT {
354354
let ptr = ptr::addr_of!(rx_descs[i]) as *const u8;
355-
let phy = sys::allocator::phys_addr(ptr);
355+
let phy = sys::mem::phys_addr(ptr);
356356
debug!(
357357
"NET E1000: [{}] {:?} ({:#X} -> {:#X})",
358358
i, rx_descs[i], ptr as u64, phy
@@ -363,7 +363,7 @@ impl Device {
363363
let tx_descs = self.tx_descs.lock();
364364
for i in 0..TX_BUFFERS_COUNT {
365365
let ptr = ptr::addr_of!(tx_descs[i]) as *const u8;
366-
let phy = sys::allocator::phys_addr(ptr);
366+
let phy = sys::mem::phys_addr(ptr);
367367
debug!(
368368
"NET E1000: [{}] {:?} ({:#X} -> {:#X})",
369369
i, tx_descs[i], ptr as u64, phy

src/sys/net/nic/pcnet.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::sys;
2-
use crate::sys::allocator::PhysBuf;
2+
use crate::sys::mem::PhysBuf;
33
use crate::sys::net::{Config, EthernetDeviceIO, Stats};
44

55
use alloc::sync::Arc;

src/sys/net/nic/rtl8139.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::sys::allocator::PhysBuf;
1+
use crate::sys::mem::PhysBuf;
22
use crate::sys::net::{Config, EthernetDeviceIO, Stats};
33

44
use alloc::sync::Arc;

src/sys/process.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ impl Process {
431431

432432
// Copy args to user memory
433433
let args_addr = self.code_addr + (self.stack_addr - self.code_addr) / 2;
434-
sys::allocator::alloc_pages(&mut mapper, args_addr, 1).
434+
sys::mem::alloc_pages(&mut mapper, args_addr, 1).
435435
expect("proc args alloc");
436436
let args: &[&str] = unsafe {
437437
let ptr = ptr_from_addr(args_ptr as u64) as usize;
@@ -508,13 +508,13 @@ impl Process {
508508
let mut mapper = self.mapper();
509509

510510
let size = MAX_PROC_SIZE;
511-
sys::allocator::free_pages(&mut mapper, self.code_addr, size);
511+
sys::mem::free_pages(&mut mapper, self.code_addr, size);
512512

513513
let addr = USER_ADDR;
514514
match mapper.translate(VirtAddr::new(addr)) {
515515
TranslateResult::Mapped { frame: _, offset: _, flags } => {
516516
if flags.contains(PageTableFlags::USER_ACCESSIBLE) {
517-
sys::allocator::free_pages(&mut mapper, addr, size);
517+
sys::mem::free_pages(&mut mapper, addr, size);
518518
}
519519
}
520520
_ => {}
@@ -526,7 +526,7 @@ fn load_binary(
526526
mapper: &mut OffsetPageTable, addr: u64, size: usize, buf: &[u8]
527527
) -> Result<(), ()> {
528528
debug_assert!(size >= buf.len());
529-
sys::allocator::alloc_pages(mapper, addr, size)?;
529+
sys::mem::alloc_pages(mapper, addr, size)?;
530530
let src = buf.as_ptr();
531531
let dst = addr as *mut u8;
532532
unsafe {

src/usr/memory.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ fn usage(args: &[&str]) -> Result<(), ExitCode> {
7272
}
7373
}
7474
}
75-
let size = sys::allocator::memory_size();
76-
let used = sys::allocator::memory_used();
75+
let size = sys::mem::memory_size();
76+
let used = sys::mem::memory_used();
7777
let free = size - used;
7878
let width = [size, used, free].iter().fold(0, |acc, num|
7979
core::cmp::max(acc, unit.format(*num).len())

0 commit comments

Comments
 (0)