Compare commits

..

3 Commits

Author SHA1 Message Date
Robert Lucas
31dbcf833c Merge f894fb15d5 into 4f6558c021 2025-01-16 00:11:54 +00:00
Robert-M-Lucas
f894fb15d5 cargo fmt 2025-01-01 14:30:55 +00:00
Robert-M-Lucas
38aab28025 Correcting many_boxes_long_lived that BumpAllocator should fail, when it currently succeeds with cargo test -r 2025-01-01 14:23:57 +00:00
21 changed files with 115 additions and 482 deletions

156
Cargo.lock generated
View File

@@ -1,44 +1,29 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 3
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]] [[package]]
name = "bit_field" name = "bit_field"
version = "0.10.2" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61" checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "bitflags"
version = "2.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a65b545ab31d687cff52899d4890855fec459eb6afe0da6417b8a18da87aa29"
[[package]] [[package]]
name = "blog_os" name = "blog_os"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"bootloader", "bootloader",
"conquer-once",
"crossbeam-queue",
"futures-util",
"lazy_static", "lazy_static",
"linked_list_allocator", "linked_list_allocator",
"pc-keyboard", "pc-keyboard",
"pic8259", "pic8259",
"spin 0.5.2", "spin",
"uart_16550", "uart_16550",
"volatile 0.2.7", "volatile 0.2.7",
"x86_64", "x86_64",
@@ -46,89 +31,34 @@ dependencies = [
[[package]] [[package]]
name = "bootloader" name = "bootloader"
version = "0.9.33" version = "0.9.29"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bdfddac270bbdd45903296bc1caf29a7fdce6b326aaf0bbab7f04c5f98b7447" checksum = "365861702868e2a37b4247aaecc7bd8f4389baec8d025497ad8ba7ff37ee9440"
[[package]]
name = "conquer-once"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96eb12fb69466716fbae9009d389e6a30830ae8975e170eff2d2cff579f9efa3"
dependencies = [
"conquer-util",
]
[[package]]
name = "conquer-util"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "654fb2472cc369d311c547103a1fa81d467bef370ae7a0680f65939895b1182a"
[[package]]
name = "crossbeam-queue"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "futures-core"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-task"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"pin-utils",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.5.0" version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [ dependencies = [
"spin 0.9.8", "spin",
] ]
[[package]] [[package]]
name = "linked_list_allocator" name = "linked_list_allocator"
version = "0.9.1" version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "549ce1740e46b291953c4340adcd74c59bcf4308f4cac050fd33ba91b7168f4a" checksum = "d0b725207570aa16096962d0b20c79f8a543df2280bd3c903022b9b0b4d7ea68"
dependencies = [ dependencies = [
"spinning_top", "spinning_top",
] ]
[[package]] [[package]]
name = "lock_api" name = "lock_api"
version = "0.4.13" version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb"
dependencies = [ dependencies = [
"autocfg",
"scopeguard", "scopeguard",
] ]
@@ -140,36 +70,18 @@ checksum = "ed089a1fbffe3337a1a345501c981f1eb1e47e69de5a40e852433e12953c3174"
[[package]] [[package]]
name = "pic8259" name = "pic8259"
version = "0.10.4" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb844b5b01db1e0b17938685738f113bfc903846f18932b378bc0eabfa40e194" checksum = "08cc920d83ee33c0f9b73aa441e75468bf2d10c959a3eb6260cf720b05ac91a1"
dependencies = [ dependencies = [
"x86_64", "x86_64",
] ]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]] [[package]]
name = "spin" name = "spin"
@@ -177,29 +89,22 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]] [[package]]
name = "spinning_top" name = "spinning_top"
version = "0.2.5" version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b9eb1a2f4c41445a3a0ff9abc5221c5fcd28e1f13cd7c0397706f9ac938ddb0" checksum = "75adad84ee84b521fb2cca2d4fd0f1dab1d8d026bda3c5bea4ca63b5f9f9293c"
dependencies = [ dependencies = [
"lock_api", "lock_api",
] ]
[[package]] [[package]]
name = "uart_16550" name = "uart_16550"
version = "0.2.19" version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "614ff2a87880d4bd4374722268598a970bbad05ced8bf630439417347254ab2e" checksum = "503a6c0e6d82daa87985e662d120c0176b09587c92a68db22781b28ae95405dd"
dependencies = [ dependencies = [
"bitflags 1.3.2", "bitflags",
"rustversion",
"x86_64", "x86_64",
] ]
@@ -211,18 +116,17 @@ checksum = "f6b06ad3ed06fef1713569d547cdbdb439eafed76341820fb0e0344f29a41945"
[[package]] [[package]]
name = "volatile" name = "volatile"
version = "0.4.6" version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "442887c63f2c839b346c192d047a7c87e73d0689c9157b00b53dcc27dd5ea793" checksum = "e4c2dbd44eb8b53973357e6e207e370f0c1059990df850aca1eca8947cf464f0"
[[package]] [[package]]
name = "x86_64" name = "x86_64"
version = "0.14.13" version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c101112411baafbb4bf8d33e4c4a80ab5b02d74d2612331c61e8192fc9710491" checksum = "fb611915c917c6296d11e23f71ff1ecfe49c5766daba92cd3df52df6b58285b6"
dependencies = [ dependencies = [
"bit_field", "bit_field",
"bitflags 2.9.2", "bitflags",
"rustversion", "volatile 0.4.4",
"volatile 0.4.6",
] ]

View File

@@ -2,7 +2,7 @@
name = "blog_os" name = "blog_os"
version = "0.1.0" version = "0.1.0"
authors = ["Philipp Oppermann <dev@phil-opp.com>"] authors = ["Philipp Oppermann <dev@phil-opp.com>"]
edition = "2024" edition = "2018"
[[test]] [[test]]
name = "should_panic" name = "should_panic"
@@ -26,24 +26,6 @@ linked_list_allocator = "0.9.0"
version = "1.0" version = "1.0"
features = ["spin_no_std"] features = ["spin_no_std"]
[[bin]]
name = "blog_os"
test = true
bench = false
[dependencies.crossbeam-queue]
version = "0.3.11"
default-features = false
features = ["alloc"]
[dependencies.conquer-once]
version = "0.2.0"
default-features = false
[dependencies.futures-util]
version = "0.3.4"
default-features = false
features = ["alloc"]
[package.metadata.bootimage] [package.metadata.bootimage]
test-args = [ test-args = [

View File

@@ -1,10 +1,10 @@
# Blog OS (Async/Await) # Blog OS (Allocator Designs)
[![Build Status](https://github.com/phil-opp/blog_os/workflows/Code/badge.svg?branch=post-12)](https://github.com/phil-opp/blog_os/actions?query=workflow%3A%22Code%22+branch%3Apost-12) [![Build Status](https://github.com/phil-opp/blog_os/workflows/Code/badge.svg?branch=post-11)](https://github.com/phil-opp/blog_os/actions?query=workflow%3A%22Code%22+branch%3Apost-11)
This repository contains the source code for the [Async/Await][post] post of the [Writing an OS in Rust](https://os.phil-opp.com) series. This repository contains the source code for the [Allocator Designs][post] post of the [Writing an OS in Rust](https://os.phil-opp.com) series.
[post]: https://os.phil-opp.com/async-await/ [post]: https://os.phil-opp.com/allocator-designs/
**Check out the [master branch](https://github.com/phil-opp/blog_os) for more information.** **Check out the [master branch](https://github.com/phil-opp/blog_os) for more information.**

View File

@@ -2,10 +2,10 @@ use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr::null_mut; use core::ptr::null_mut;
use fixed_size_block::FixedSizeBlockAllocator; use fixed_size_block::FixedSizeBlockAllocator;
use x86_64::{ use x86_64::{
VirtAddr,
structures::paging::{ structures::paging::{
FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB, mapper::MapToError, mapper::MapToError, FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB,
}, },
VirtAddr,
}; };
pub mod bump; pub mod bump;

View File

@@ -1,4 +1,4 @@
use super::{Locked, align_up}; use super::{align_up, Locked};
use alloc::alloc::{GlobalAlloc, Layout}; use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr; use core::ptr;

View File

@@ -44,9 +44,7 @@ impl FixedSizeBlockAllocator {
/// heap bounds are valid and that the heap is unused. This method must be /// heap bounds are valid and that the heap is unused. This method must be
/// called only once. /// called only once.
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) { pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
unsafe { self.fallback_allocator.init(heap_start, heap_size);
self.fallback_allocator.init(heap_start, heap_size);
}
} }
/// Allocates using the fallback allocator. /// Allocates using the fallback allocator.
@@ -93,16 +91,12 @@ unsafe impl GlobalAlloc for Locked<FixedSizeBlockAllocator> {
assert!(mem::size_of::<ListNode>() <= BLOCK_SIZES[index]); assert!(mem::size_of::<ListNode>() <= BLOCK_SIZES[index]);
assert!(mem::align_of::<ListNode>() <= BLOCK_SIZES[index]); assert!(mem::align_of::<ListNode>() <= BLOCK_SIZES[index]);
let new_node_ptr = ptr as *mut ListNode; let new_node_ptr = ptr as *mut ListNode;
unsafe { new_node_ptr.write(new_node);
new_node_ptr.write(new_node); allocator.list_heads[index] = Some(&mut *new_node_ptr);
allocator.list_heads[index] = Some(&mut *new_node_ptr);
}
} }
None => { None => {
let ptr = NonNull::new(ptr).unwrap(); let ptr = NonNull::new(ptr).unwrap();
unsafe { allocator.fallback_allocator.deallocate(ptr, layout);
allocator.fallback_allocator.deallocate(ptr, layout);
}
} }
} }
} }

View File

@@ -1,4 +1,4 @@
use super::{Locked, align_up}; use super::{align_up, Locked};
use alloc::alloc::{GlobalAlloc, Layout}; use alloc::alloc::{GlobalAlloc, Layout};
use core::{mem, ptr}; use core::{mem, ptr};
@@ -39,9 +39,7 @@ impl LinkedListAllocator {
/// heap bounds are valid and that the heap is unused. This method must be /// heap bounds are valid and that the heap is unused. This method must be
/// called only once. /// called only once.
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) { pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
unsafe { self.add_free_region(heap_start, heap_size);
self.add_free_region(heap_start, heap_size);
}
} }
/// Adds the given memory region to the front of the list. /// Adds the given memory region to the front of the list.
@@ -54,10 +52,8 @@ impl LinkedListAllocator {
let mut node = ListNode::new(size); let mut node = ListNode::new(size);
node.next = self.head.next.take(); node.next = self.head.next.take();
let node_ptr = addr as *mut ListNode; let node_ptr = addr as *mut ListNode;
unsafe { node_ptr.write(node);
node_ptr.write(node); self.head.next = Some(&mut *node_ptr)
self.head.next = Some(&mut *node_ptr);
}
} }
/// Looks for a free region with the given size and alignment and removes /// Looks for a free region with the given size and alignment and removes
@@ -132,9 +128,7 @@ unsafe impl GlobalAlloc for Locked<LinkedListAllocator> {
let alloc_end = alloc_start.checked_add(size).expect("overflow"); let alloc_end = alloc_start.checked_add(size).expect("overflow");
let excess_size = region.end_addr() - alloc_end; let excess_size = region.end_addr() - alloc_end;
if excess_size > 0 { if excess_size > 0 {
unsafe { allocator.add_free_region(alloc_end, excess_size);
allocator.add_free_region(alloc_end, excess_size);
}
} }
alloc_start as *mut u8 alloc_start as *mut u8
} else { } else {
@@ -146,6 +140,6 @@ unsafe impl GlobalAlloc for Locked<LinkedListAllocator> {
// perform layout adjustments // perform layout adjustments
let (size, _) = LinkedListAllocator::size_align(layout); let (size, _) = LinkedListAllocator::size_align(layout);
unsafe { self.lock().add_free_region(ptr as usize, size) } self.lock().add_free_region(ptr as usize, size)
} }
} }

View File

@@ -1,7 +1,7 @@
use lazy_static::lazy_static; use lazy_static::lazy_static;
use x86_64::VirtAddr;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector}; use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment; use x86_64::structures::tss::TaskStateSegment;
use x86_64::VirtAddr;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
@@ -41,7 +41,7 @@ struct Selectors {
} }
pub fn init() { pub fn init() {
use x86_64::instructions::segmentation::{CS, Segment}; use x86_64::instructions::segmentation::{Segment, CS};
use x86_64::instructions::tables::load_tss; use x86_64::instructions::tables::load_tss;
GDT.0.load(); GDT.0.load();

View File

@@ -80,11 +80,31 @@ extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFr
} }
extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) { extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
use pc_keyboard::{layouts, DecodedKey, HandleControl, Keyboard, ScancodeSet1};
use spin::Mutex;
use x86_64::instructions::port::Port; use x86_64::instructions::port::Port;
lazy_static! {
static ref KEYBOARD: Mutex<Keyboard<layouts::Us104Key, ScancodeSet1>> =
Mutex::new(Keyboard::new(
ScancodeSet1::new(),
layouts::Us104Key,
HandleControl::Ignore
));
}
let mut keyboard = KEYBOARD.lock();
let mut port = Port::new(0x60); let mut port = Port::new(0x60);
let scancode: u8 = unsafe { port.read() }; let scancode: u8 = unsafe { port.read() };
crate::task::keyboard::add_scancode(scancode); if let Ok(Some(key_event)) = keyboard.add_byte(scancode) {
if let Some(key) = keyboard.process_keyevent(key_event) {
match key {
DecodedKey::Unicode(character) => print!("{}", character),
DecodedKey::RawKey(key) => print!("{:?}", key),
}
}
}
unsafe { unsafe {
PICS.lock() PICS.lock()

View File

@@ -13,7 +13,6 @@ pub mod gdt;
pub mod interrupts; pub mod interrupts;
pub mod memory; pub mod memory;
pub mod serial; pub mod serial;
pub mod task;
pub mod vga_buffer; pub mod vga_buffer;
pub fn init() { pub fn init() {
@@ -75,7 +74,7 @@ pub fn hlt_loop() -> ! {
} }
#[cfg(test)] #[cfg(test)]
use bootloader::{BootInfo, entry_point}; use bootloader::{entry_point, BootInfo};
#[cfg(test)] #[cfg(test)]
entry_point!(test_kernel_main); entry_point!(test_kernel_main);

View File

@@ -6,9 +6,9 @@
extern crate alloc; extern crate alloc;
use alloc::{boxed::Box, rc::Rc, vec, vec::Vec};
use blog_os::println; use blog_os::println;
use blog_os::task::{Task, executor::Executor, keyboard}; use bootloader::{entry_point, BootInfo};
use bootloader::{BootInfo, entry_point};
use core::panic::PanicInfo; use core::panic::PanicInfo;
entry_point!(kernel_main); entry_point!(kernel_main);
@@ -27,13 +27,35 @@ fn kernel_main(boot_info: &'static BootInfo) -> ! {
allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed"); allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed");
// allocate a number on the heap
let heap_value = Box::new(41);
println!("heap_value at {:p}", heap_value);
// create a dynamically sized vector
let mut vec = Vec::new();
for i in 0..500 {
vec.push(i);
}
println!("vec at {:p}", vec.as_slice());
// create a reference counted vector -> will be freed when count reaches 0
let reference_counted = Rc::new(vec![1, 2, 3]);
let cloned_reference = reference_counted.clone();
println!(
"current reference count is {}",
Rc::strong_count(&cloned_reference)
);
core::mem::drop(reference_counted);
println!(
"reference count is {} now",
Rc::strong_count(&cloned_reference)
);
#[cfg(test)] #[cfg(test)]
test_main(); test_main();
let mut executor = Executor::new(); println!("It did not crash!");
executor.spawn(Task::new(example_task())); blog_os::hlt_loop();
executor.spawn(Task::new(keyboard::print_keypresses()));
executor.run();
} }
/// This function is called on panic. /// This function is called on panic.
@@ -50,15 +72,6 @@ fn panic(info: &PanicInfo) -> ! {
blog_os::test_panic_handler(info) blog_os::test_panic_handler(info)
} }
async fn async_number() -> u32 {
42
}
async fn example_task() {
let number = async_number().await;
println!("async number: {}", number);
}
#[test_case] #[test_case]
fn trivial_assertion() { fn trivial_assertion() {
assert_eq!(1, 1); assert_eq!(1, 1);

View File

@@ -1,7 +1,7 @@
use bootloader::bootinfo::{MemoryMap, MemoryRegionType}; use bootloader::bootinfo::{MemoryMap, MemoryRegionType};
use x86_64::{ use x86_64::{
PhysAddr, VirtAddr,
structures::paging::{FrameAllocator, OffsetPageTable, PageTable, PhysFrame, Size4KiB}, structures::paging::{FrameAllocator, OffsetPageTable, PageTable, PhysFrame, Size4KiB},
PhysAddr, VirtAddr,
}; };
/// Initialize a new OffsetPageTable. /// Initialize a new OffsetPageTable.
@@ -11,10 +11,8 @@ use x86_64::{
/// `physical_memory_offset`. Also, this function must be only called once /// `physical_memory_offset`. Also, this function must be only called once
/// to avoid aliasing `&mut` references (which is undefined behavior). /// to avoid aliasing `&mut` references (which is undefined behavior).
pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> { pub unsafe fn init(physical_memory_offset: VirtAddr) -> OffsetPageTable<'static> {
unsafe { let level_4_table = active_level_4_table(physical_memory_offset);
let level_4_table = active_level_4_table(physical_memory_offset); OffsetPageTable::new(level_4_table, physical_memory_offset)
OffsetPageTable::new(level_4_table, physical_memory_offset)
}
} }
/// Returns a mutable reference to the active level 4 table. /// Returns a mutable reference to the active level 4 table.
@@ -32,7 +30,7 @@ unsafe fn active_level_4_table(physical_memory_offset: VirtAddr) -> &'static mut
let virt = physical_memory_offset + phys.as_u64(); let virt = physical_memory_offset + phys.as_u64();
let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); let page_table_ptr: *mut PageTable = virt.as_mut_ptr();
unsafe { &mut *page_table_ptr } &mut *page_table_ptr // unsafe
} }
/// A FrameAllocator that always returns `None`. /// A FrameAllocator that always returns `None`.

View File

@@ -1,102 +0,0 @@
use super::{Task, TaskId};
use alloc::{collections::BTreeMap, sync::Arc, task::Wake};
use core::task::{Context, Poll, Waker};
use crossbeam_queue::ArrayQueue;
pub struct Executor {
tasks: BTreeMap<TaskId, Task>,
task_queue: Arc<ArrayQueue<TaskId>>,
waker_cache: BTreeMap<TaskId, Waker>,
}
impl Executor {
pub fn new() -> Self {
Executor {
tasks: BTreeMap::new(),
task_queue: Arc::new(ArrayQueue::new(100)),
waker_cache: BTreeMap::new(),
}
}
pub fn spawn(&mut self, task: Task) {
let task_id = task.id;
if self.tasks.insert(task.id, task).is_some() {
panic!("task with same ID already in tasks");
}
self.task_queue.push(task_id).expect("queue full");
}
pub fn run(&mut self) -> ! {
loop {
self.run_ready_tasks();
self.sleep_if_idle();
}
}
fn run_ready_tasks(&mut self) {
// destructure `self` to avoid borrow checker errors
let Self {
tasks,
task_queue,
waker_cache,
} = self;
while let Some(task_id) = task_queue.pop() {
let task = match tasks.get_mut(&task_id) {
Some(task) => task,
None => continue, // task no longer exists
};
let waker = waker_cache
.entry(task_id)
.or_insert_with(|| TaskWaker::new(task_id, task_queue.clone()));
let mut context = Context::from_waker(waker);
match task.poll(&mut context) {
Poll::Ready(()) => {
// task done -> remove it and its cached waker
tasks.remove(&task_id);
waker_cache.remove(&task_id);
}
Poll::Pending => {}
}
}
}
fn sleep_if_idle(&self) {
use x86_64::instructions::interrupts::{self, enable_and_hlt};
interrupts::disable();
if self.task_queue.is_empty() {
enable_and_hlt();
} else {
interrupts::enable();
}
}
}
struct TaskWaker {
task_id: TaskId,
task_queue: Arc<ArrayQueue<TaskId>>,
}
impl TaskWaker {
fn new(task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>) -> Waker {
Waker::from(Arc::new(TaskWaker {
task_id,
task_queue,
}))
}
fn wake_task(&self) {
self.task_queue.push(self.task_id).expect("task_queue full");
}
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.wake_task();
}
fn wake_by_ref(self: &Arc<Self>) {
self.wake_task();
}
}

View File

@@ -1,87 +0,0 @@
use crate::{print, println};
use conquer_once::spin::OnceCell;
use core::{
pin::Pin,
task::{Context, Poll},
};
use crossbeam_queue::ArrayQueue;
use futures_util::{
stream::{Stream, StreamExt},
task::AtomicWaker,
};
use pc_keyboard::{DecodedKey, HandleControl, Keyboard, ScancodeSet1, layouts};
static SCANCODE_QUEUE: OnceCell<ArrayQueue<u8>> = OnceCell::uninit();
static WAKER: AtomicWaker = AtomicWaker::new();
/// Called by the keyboard interrupt handler
///
/// Must not block or allocate.
pub(crate) fn add_scancode(scancode: u8) {
if let Ok(queue) = SCANCODE_QUEUE.try_get() {
if let Err(_) = queue.push(scancode) {
println!("WARNING: scancode queue full; dropping keyboard input");
} else {
WAKER.wake();
}
} else {
println!("WARNING: scancode queue uninitialized");
}
}
pub struct ScancodeStream {
_private: (),
}
impl ScancodeStream {
pub fn new() -> Self {
SCANCODE_QUEUE
.try_init_once(|| ArrayQueue::new(100))
.expect("ScancodeStream::new should only be called once");
ScancodeStream { _private: () }
}
}
impl Stream for ScancodeStream {
type Item = u8;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<u8>> {
let queue = SCANCODE_QUEUE
.try_get()
.expect("scancode queue not initialized");
// fast path
if let Some(scancode) = queue.pop() {
return Poll::Ready(Some(scancode));
}
WAKER.register(&cx.waker());
match queue.pop() {
Some(scancode) => {
WAKER.take();
Poll::Ready(Some(scancode))
}
None => Poll::Pending,
}
}
}
pub async fn print_keypresses() {
let mut scancodes = ScancodeStream::new();
let mut keyboard = Keyboard::new(
ScancodeSet1::new(),
layouts::Us104Key,
HandleControl::Ignore,
);
while let Some(scancode) = scancodes.next().await {
if let Ok(Some(key_event)) = keyboard.add_byte(scancode) {
if let Some(key) = keyboard.process_keyevent(key_event) {
match key {
DecodedKey::Unicode(character) => print!("{}", character),
DecodedKey::RawKey(key) => print!("{:?}", key),
}
}
}
}
}

View File

@@ -1,39 +0,0 @@
use alloc::boxed::Box;
use core::{
future::Future,
pin::Pin,
sync::atomic::{AtomicU64, Ordering},
task::{Context, Poll},
};
pub mod executor;
pub mod keyboard;
pub mod simple_executor;
pub struct Task {
id: TaskId,
future: Pin<Box<dyn Future<Output = ()>>>,
}
impl Task {
pub fn new(future: impl Future<Output = ()> + 'static) -> Task {
Task {
id: TaskId::new(),
future: Box::pin(future),
}
}
fn poll(&mut self, context: &mut Context) -> Poll<()> {
self.future.as_mut().poll(context)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TaskId(u64);
impl TaskId {
fn new() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}

View File

@@ -1,44 +0,0 @@
use super::Task;
use alloc::collections::VecDeque;
use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
pub struct SimpleExecutor {
task_queue: VecDeque<Task>,
}
impl SimpleExecutor {
pub fn new() -> SimpleExecutor {
SimpleExecutor {
task_queue: VecDeque::new(),
}
}
pub fn spawn(&mut self, task: Task) {
self.task_queue.push_back(task)
}
pub fn run(&mut self) {
while let Some(mut task) = self.task_queue.pop_front() {
let waker = dummy_waker();
let mut context = Context::from_waker(&waker);
match task.poll(&mut context) {
Poll::Ready(()) => {} // task done
Poll::Pending => self.task_queue.push_back(task),
}
}
}
}
fn dummy_raw_waker() -> RawWaker {
fn no_op(_: *const ()) {}
fn clone(_: *const ()) -> RawWaker {
dummy_raw_waker()
}
let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
RawWaker::new(0 as *const (), vtable)
}
fn dummy_waker() -> Waker {
unsafe { Waker::from_raw(dummy_raw_waker()) }
}

View File

@@ -7,7 +7,7 @@
use blog_os::println; use blog_os::println;
use core::panic::PanicInfo; use core::panic::PanicInfo;
#[unsafe(no_mangle)] // don't mangle the name of this function #[no_mangle] // don't mangle the name of this function
pub extern "C" fn _start() -> ! { pub extern "C" fn _start() -> ! {
test_main(); test_main();

View File

@@ -8,7 +8,8 @@ extern crate alloc;
use alloc::{boxed::Box, vec::Vec}; use alloc::{boxed::Box, vec::Vec};
use blog_os::allocator::HEAP_SIZE; use blog_os::allocator::HEAP_SIZE;
use bootloader::{BootInfo, entry_point}; use bootloader::{entry_point, BootInfo};
use core::hint::black_box;
use core::panic::PanicInfo; use core::panic::PanicInfo;
entry_point!(main); entry_point!(main);
@@ -61,6 +62,7 @@ fn many_boxes_long_lived() {
let x = Box::new(i); let x = Box::new(i);
assert_eq!(*x, i); assert_eq!(*x, i);
} }
black_box(&long_lived); // new - ensures long_lived isn't optimized away
assert_eq!(*long_lived, 1); // new assert_eq!(*long_lived, 1); // new
} }

View File

@@ -1,10 +1,10 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
use blog_os::{QemuExitCode, exit_qemu, serial_print, serial_println}; use blog_os::{exit_qemu, serial_print, serial_println, QemuExitCode};
use core::panic::PanicInfo; use core::panic::PanicInfo;
#[unsafe(no_mangle)] #[no_mangle]
pub extern "C" fn _start() -> ! { pub extern "C" fn _start() -> ! {
should_fail(); should_fail();
serial_println!("[test did not panic]"); serial_println!("[test did not panic]");

View File

@@ -2,12 +2,12 @@
#![no_main] #![no_main]
#![feature(abi_x86_interrupt)] #![feature(abi_x86_interrupt)]
use blog_os::{QemuExitCode, exit_qemu, serial_print, serial_println}; use blog_os::{exit_qemu, serial_print, serial_println, QemuExitCode};
use core::panic::PanicInfo; use core::panic::PanicInfo;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame}; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
#[unsafe(no_mangle)] #[no_mangle]
pub extern "C" fn _start() -> ! { pub extern "C" fn _start() -> ! {
serial_print!("stack_overflow::stack_overflow...\t"); serial_print!("stack_overflow::stack_overflow...\t");

View File

@@ -3,14 +3,13 @@
"data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128", "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128",
"arch": "x86_64", "arch": "x86_64",
"target-endian": "little", "target-endian": "little",
"target-pointer-width": 64, "target-pointer-width": "64",
"target-c-int-width": 32, "target-c-int-width": "32",
"os": "none", "os": "none",
"executables": true, "executables": true,
"linker-flavor": "ld.lld", "linker-flavor": "ld.lld",
"linker": "rust-lld", "linker": "rust-lld",
"panic-strategy": "abort", "panic-strategy": "abort",
"disable-redzone": true, "disable-redzone": true,
"features": "-mmx,-sse,+soft-float", "features": "-mmx,-sse,+soft-float"
"rustc-abi": "x86-softfloat"
} }