1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
#![no_std] #![no_main]
extern crate alloc;
use alloc::{boxed::Box, rc::Rc, vec, vec::Vec};
use bootloader::{BootInfo, entry_point};
use core::panic::PanicInfo;
use rust_kernel::task::{Task, executor::Executor, keyboard};
use rust_kernel::{allocator, fs, kprintln, memory, println, process, serial_println, thread};
use rust_kernel::vga_buffer;
use x86_64::{VirtAddr, structures::paging::{Page, Translate}};
entry_point!(kernel_main);
fn kernel_main(boot_info: &'static BootInfo) -> ! {
kprintln!("Hello from Tyler's Rust kernel!");
rust_kernel::init();
x86_64::instructions::interrupts::int3();
kprintln!("Survived the breakpoint, still running.");
#[cfg(feature = "stack-overflow")]
{
serial_println!("Overflowing the stack on purpose...");
stack_overflow();
}
paging_demo(boot_info);
thread::spawn("A", thread_a);
thread::spawn("B", thread_b);
thread::spawn("C", thread_c);
kprintln!("[thread] spawned threads A, B, C (status on the top line)");
fs::init();
let (pci_devices, storage_log) = rust_kernel::init_storage();
for d in &pci_devices {
serial_println!(
"[pci] {:02x}:{:02x}.{} {:04x}:{:04x} {}",
d.bus, d.device, d.function, d.vendor_id, d.device_id, d.class_name()
);
}
kprintln!("[pci] {} devices on the PCI bus", pci_devices.len());
for line in &storage_log {
kprintln!("[disk] {}", line);
}
for (path, fs_type) in fs::mounts() {
serial_println!("[vfs] mounted {} at {}", fs_type, path);
}
const BIN: &str = "/mnt/disk0/bin";
if fs::lookup(BIN).is_err() {
kprintln!("[process] no {} -- was QEMU started with the disk image?", BIN);
}
let programs = [
"hello", "evil", "spin", "demo", "echo", ];
for name in programs {
let path = alloc::format!("{}/{}", BIN, name);
if let Err(e) = process::spawn_path(&path, process::SpawnArgs::kernel(name)) {
kprintln!("[process] could not start {}: {:?}", path, e);
}
}
let mut executor = Executor::new();
executor.spawn(Task::new(example_task()));
executor.spawn(Task::new(keyboard::print_keypresses()));
kprintln!("Type a line + Enter: the echo program (ring 3) reads it");
executor.run(); }
async fn async_number() -> u32 {
42
}
async fn example_task() {
let number = async_number().await;
kprintln!("[async] async number: {}", number);
for i in 1..=3 {
rust_kernel::task::yield_now().await; serial_println!("[async] example task step {} (after yield)", i);
}
}
fn counter_thread(name: &str, period_ticks: u64, col: usize) {
for n in 1u64.. {
if n <= 5 {
serial_println!("[thread {}] count {}", name, n);
}
vga_buffer::print_at(0, col, format_args!(" {}:{:>5} ", name, n));
thread::sleep_ticks(period_ticks); }
}
fn thread_a() {
counter_thread("A", 5, 0);
}
fn thread_b() {
counter_thread("B", 7, 10);
}
fn thread_c() {
let mut count: u64 = 0;
for round in 1..=5 {
for _ in 0..2_000_000 {
count = core::hint::black_box(count + 1); }
serial_println!("[thread C] busy loop round {} (count = {})", round, count);
vga_buffer::print_at(0, 20, format_args!(" C:{:>5} ", round));
}
serial_println!("[thread {}] done, exiting", thread::current_name());
vga_buffer::print_at(0, 20, format_args!(" C: done "));
}
fn paging_demo(boot_info: &'static BootInfo) {
use x86_64::registers::control::Cr3;
let (level_4_frame, _) = Cr3::read();
kprintln!("[paging] CR3 (level 4 table) at phys {:#x}", level_4_frame.start_address().as_u64());
#[cfg(feature = "page-fault")]
{
kprintln!("[paging] writing to unmapped address 0xdeadbeaf...");
unsafe { *(0xdeadbeaf as *mut u8) = 42 }; }
let phys_mem_offset = VirtAddr::new(boot_info.physical_memory_offset);
serial_println!("[paging] physical memory mapped at virt {:#x}", phys_mem_offset.as_u64());
serial_println!(
"[memory] {} memory map regions, {} KiB usable RAM",
boot_info.memory_map.iter().count(),
memory::usable_memory_bytes(&boot_info.memory_map) / 1024
);
let mut mapper = unsafe { memory::init(phys_mem_offset) };
let mut frame_allocator = unsafe { memory::BootInfoFrameAllocator::init(&boot_info.memory_map) };
let addresses = [
0xb8000, 0x201008, 0x0100_0020_1a10, boot_info.physical_memory_offset, ];
for &address in &addresses {
let virt = VirtAddr::new(address);
let phys = mapper.translate_addr(virt);
serial_println!("[paging] translate {:?} -> {:?}", virt, phys);
}
let page = Page::containing_address(VirtAddr::new(0xdeadbeaf000));
memory::create_example_mapping(page, &mut mapper, &mut frame_allocator);
let page_ptr: *mut u64 = page.start_address().as_mut_ptr();
unsafe { page_ptr.offset(400).write_volatile(0x_f021_f077_f065_f04e) };
kprintln!("[paging] mapped page 0xdeadbeaf000 -> VGA frame, wrote \"New!\" through it");
allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed");
kprintln!(
"[heap] {} KiB heap at {:#x} (fixed-size-block allocator)",
allocator::HEAP_SIZE / 1024,
allocator::HEAP_START
);
let heap_value = Box::new(41);
kprintln!("[heap] Box::new(41) = {} at {:p}", heap_value, heap_value);
let mut vec = Vec::new();
for i in 0..500 {
vec.push(i);
}
let sum: u64 = vec.iter().sum();
kprintln!("[heap] Vec of 500 numbers at {:p}, sum = {}", vec.as_ptr(), sum);
let reference_counted = Rc::new(vec![1, 2, 3]);
let cloned_reference = reference_counted.clone();
kprintln!("[heap] Rc count after clone = {}", Rc::strong_count(&cloned_reference));
core::mem::drop(reference_counted);
kprintln!("[heap] Rc count after drop = {}", Rc::strong_count(&cloned_reference));
memory::init_frame_allocator(frame_allocator);
}
#[cfg(feature = "stack-overflow")]
#[allow(unconditional_recursion)]
fn stack_overflow() {
stack_overflow();
unsafe { core::ptr::read_volatile(&0u8) };
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("{}", info);
serial_println!("KERNEL PANIC: {}", info);
#[cfg(feature = "headless")]
rust_kernel::exit_qemu(rust_kernel::QemuExitCode::Failed);
rust_kernel::hlt_loop();
}
|