rstubs/
main.rs

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
//! Rust version of the StuBS Kernel
//!
//! The assignments are documented in the [assignments] module.
#![doc = include_str!("../README.md")]
// don't link the Rust standard library
#![no_std]
#![no_main]
// unstable features
#![feature(abi_x86_interrupt)]
#![feature(let_chains)]
#![feature(naked_functions)]
// warnings
#![allow(static_mut_refs)]
#![allow(clippy::assertions_on_constants)]
#![allow(clippy::redundant_pattern_matching)]
#![allow(clippy::mut_from_ref)]
#![allow(clippy::new_without_default)]

use core::arch::naked_asm;
use core::panic::PanicInfo;
use core::sync::atomic::AtomicU32;

use multiboot as mb;

#[macro_use]
mod device;
#[macro_use]
mod arch;

mod assignments;
mod gdt;
#[cfg(feature = "graphics")]
mod graphics;
mod interrupts;
mod multiboot;
mod threading;
mod user;
mod util;

use device::cga::Window;
use device::{KEYBOARD, SERIAL};

use crate::arch::acpi::Acpi;
#[cfg(feature = "smp")]
use crate::arch::smp;
use crate::arch::{cpu, int};
use crate::device::{DBG, KOUT};
use crate::gdt::GDT_PTR;
use crate::interrupts::guard::GUARD;
use crate::threading::Thread;

/// Maximal number of cores the OS supports.
#[cfg(feature = "smp")]
const MAX_CPUS: usize = 4;
#[cfg(not(feature = "smp"))]
const MAX_CPUS: usize = 1;

/// Multiboot flags
#[cfg(not(feature = "graphics"))]
const FLAGS: u32 = mb::Header::PAGE_ALIGN | mb::Header::MEM_INFO;
#[cfg(feature = "graphics")]
const FLAGS: u32 = mb::Header::PAGE_ALIGN | mb::Header::MEM_INFO | mb::Header::VIDEO_MODE;

const SCREEN_WIDTH: usize = 1280;
const SCREEN_HEIGHT: usize = 1024;

/// Multiboot header, used by QEMU/Grub
#[link_section = ".multiboot"]
#[no_mangle]
pub static MBOOT: mb::Header = mb::Header::new(FLAGS, SCREEN_WIDTH as _, SCREEN_HEIGHT as _, 32);

/// Pointer to the multiboot header.
static mut MBOOT_PTR: u32 = 0;

#[allow(unused)]
extern "C" {
    /// Start address of the loaded kernel code.
    static KERNEL_BEGIN: u8;
    /// End address of the loaded kernel code.
    static KERNEL_END: u8;
}

/// The stack size for the init and thread stacks.
///
/// Note: If you create objects, they are usually allocated on the stack first
/// before beeing moved or copied elswhere.
const STACK_SIZE: usize = 32 * 1024;
/// Stack offset (changes between cores)
static STACK_OFFSET: AtomicU32 = AtomicU32::new(0);

/// Stacks for each core, used for initialization (set before calling kmain).
///
/// It is also reused for the idle threads.
static mut INIT_STACKS: [[u32; STACK_SIZE / 4]; MAX_CPUS] = [[0; STACK_SIZE / 4]; MAX_CPUS];

/// Entry point (protected mode), which enables segmentation
#[naked]
#[no_mangle]
#[link_section = ".inittext"]
pub unsafe extern "C" fn start() -> ! {
    naked_asm!(
        // Save multiboot state
        "mov {MBOOT_PTR}, ebx",
        // Global descriptor table
        "lgdt {GDT_PTR}",
        // Jump to second stage and enable segmentation
        "ljmp 0x8, offset {start_high}",
        MBOOT_PTR = sym MBOOT_PTR,
        GDT_PTR = sym GDT_PTR,
        start_high = sym start_high,
    )
}

/// Second stage, which prepares the stack
#[naked]
#[no_mangle]
unsafe extern "C" fn start_high() -> ! {
    naked_asm!(
        // Prep segment registers
        "mov ax, 0x10",
        "mov ds, ax",
        "mov es, ax",
        "mov fs, ax",
        "mov gs, ax",
        "mov ss, ax",
        // Prepare init stack
        "mov eax, {STACK_SIZE}",
        // Atomically increment stack pointer, to prevent sharing the stack on multiple cores
        "lock xadd {STACK_OFFSET}, eax",
        "add eax, {STACK_SIZE}",
        "lea esp, {INIT_STACKS}",
        "add esp, eax",
        // Clear direction flag for string operations
        "cld",
        "call {main}",
        STACK_SIZE = const STACK_SIZE,
        STACK_OFFSET = sym STACK_OFFSET,
        INIT_STACKS = sym INIT_STACKS,
        main = sym main,
    )
}

/// Main function that is called for every core
extern "C" fn main() -> ! {
    if cpu::online() == 0 {
        SERIAL.lock().init();
    }

    serial!("core id: {} ({:08b})", cpu::id(), cpu::online());

    // boot processor only
    let mut g = if cpu::online() == 0 {
        serial!(
            "code: {:x?}",
            &raw const KERNEL_BEGIN..&raw const KERNEL_END
        );

        Window::whole().clear();
        DBG.lock().clear();
        KOUT.lock().clear();
        println!("Hello World!");

        // TODO: BST B1 - Init gdt and tss

        // Load system tables and setup interrupt controllers
        let acpi = Acpi::load().unwrap();
        serial!("global int");
        #[allow(unused_variables)]
        let cpus = interrupts::setup_global(acpi);

        interrupts::setup_local();

        unsafe { KEYBOARD.init() };

        // Enter L1/2, the scheduler leaves this layer
        // This also synchronizes with other cores
        let mut g = GUARD.enter();

        #[cfg(feature = "smp")]
        if cpus > 1 {
            serial!("boot cores");
            smp::boot();
            // Wait for cores to be online
            while cpu::online().count_ones() < cpus as u32 {
                core::hint::spin_loop();
            }
        }

        // Setup threads
        serial!("Loading apps");
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::app_action));
        g.scheduler.add(Thread::new(user::keyboard_action));
        g.scheduler.add(Thread::new(user::init_action));

        #[cfg(feature = "graphics")]
        g.scheduler.add(Thread::new(graphics::app));
        g
    } else {
        interrupts::setup_local();

        // Enter L1/2, the scheduler leaves this layer
        GUARD.enter()
    };

    int::enable(true);
    // TODO: BSB B2 - Enable paging

    serial!("Scheduler starting...");
    g.scheduler.schedule();
}

/// This function is called on panic.
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    serial!(force: "{info}");
    debug!("{info}");
    loop {
        int::enable(false);
        cpu::halt();
    }
}