Skip to main content

strat9_kernel/arch/x86_64/
tss.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Task State Segment (TSS) for Strat9-OS
24//!
25//! The TSS is required for:
26//! - Interrupt Stack Table (IST) entries for safe exception handling
27//! - Ring 3 -> Ring 0 stack switching (privilege_stack_table[0] = rsp0)
28
29use core::{
30    mem::MaybeUninit,
31    panic::Location,
32    sync::atomic::{AtomicBool, Ordering},
33};
34use x86_64::{structures::tss::TaskStateSegment, VirtAddr};
35
36#[repr(C, packed)]
37struct DescriptorTableRegister {
38    limit: u16,
39    base: u64,
40}
41
42#[derive(Clone, Copy, Debug)]
43pub struct LoadedTssInfo {
44    pub tr_selector: u16,
45    pub tss_base: u64,
46    pub rsp0: u64,
47}
48
49/// IST index used for the double fault handler
50pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
51
52/// IST stack size (20 KB)
53const IST_STACK_SIZE: usize = 4096 * 5;
54
55/// Static IST stacks for double fault handler (per-CPU)
56static mut IST_STACKS: [[u8; IST_STACK_SIZE]; crate::arch::x86_64::percpu::MAX_CPUS] =
57    [[0; IST_STACK_SIZE]; crate::arch::x86_64::percpu::MAX_CPUS];
58
59/// Per-CPU TSS storage
60static mut TSS: [MaybeUninit<TaskStateSegment>; crate::arch::x86_64::percpu::MAX_CPUS] =
61    [const { MaybeUninit::uninit() }; crate::arch::x86_64::percpu::MAX_CPUS];
62
63static TSS_INIT: [AtomicBool; crate::arch::x86_64::percpu::MAX_CPUS] =
64    [const { AtomicBool::new(false) }; crate::arch::x86_64::percpu::MAX_CPUS];
65
66/// Initialize the TSS with IST entries
67///
68/// Must be called before `gdt::init()` since the GDT references the TSS.
69pub fn init() {
70    init_cpu(0);
71}
72
73/// Initialize the TSS for a given CPU index.
74pub fn init_cpu(cpu_index: usize) {
75    // Bounds check: prevent OOB access into static arrays before any unsafe.
76    assert!(
77        cpu_index < crate::arch::x86_64::percpu::MAX_CPUS,
78        "TSS init_cpu: cpu_index {} >= MAX_CPUS {}",
79        cpu_index,
80        crate::arch::x86_64::percpu::MAX_CPUS,
81    );
82    // SAFETY: Called during init (BSP) or AP bring-up before interrupts are enabled on that CPU.
83    unsafe {
84        let stack_ptr = &raw const IST_STACKS[cpu_index] as *const u8;
85        let stack_end = VirtAddr::from_ptr(stack_ptr) + IST_STACK_SIZE as u64;
86        let mut tss = TaskStateSegment::new();
87        tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = stack_end;
88
89        TSS[cpu_index].write(tss);
90        TSS_INIT[cpu_index].store(true, Ordering::Release);
91
92        let _ist_addr = VirtAddr::from_ptr(stack_ptr);
93        // Raw e9 output : format_args! + Port write hangs before IDT is loaded.
94        for &b in b"TSS init OK\n" {
95            core::arch::asm!("out 0xe9, al", in("al") b, options(nomem, nostack));
96        }
97    }
98}
99
100/// Get a reference to the TSS for a given CPU index (for GDT descriptor creation).
101pub fn tss_for(cpu_index: usize) -> &'static TaskStateSegment {
102    assert!(
103        cpu_index < crate::arch::x86_64::percpu::MAX_CPUS,
104        "tss_for: cpu_index {} >= MAX_CPUS",
105        cpu_index,
106    );
107    if !TSS_INIT[cpu_index].load(Ordering::Acquire) {
108        panic!("TSS for CPU{} not initialized", cpu_index);
109    }
110    // SAFETY: TSS was initialized in init_cpu and lives for 'static.
111    unsafe { &*TSS[cpu_index].as_ptr() }
112}
113
114/// Return TSS.rsp0 for a specific CPU, if its TSS is initialized.
115pub fn kernel_stack_for(cpu_index: usize) -> Option<VirtAddr> {
116    if cpu_index >= crate::arch::x86_64::percpu::MAX_CPUS {
117        return None;
118    }
119    if !TSS_INIT[cpu_index].load(Ordering::Acquire) {
120        return None;
121    }
122    // SAFETY: The TSS for this CPU is initialized and lives for the whole kernel lifetime.
123    unsafe {
124        let tss = &*TSS[cpu_index].as_ptr();
125        Some(tss.privilege_stack_table[0])
126    }
127}
128
129/// Read the TSS currently loaded in TR by decoding the live GDT entry.
130pub fn loaded_tss_info() -> Option<LoadedTssInfo> {
131    let mut gdtr = DescriptorTableRegister { limit: 0, base: 0 };
132    let tr_selector: u16;
133    // SAFETY: `sgdt`/`str` are privileged register reads with no side effect.
134    unsafe {
135        core::arch::asm!(
136            "sgdt [{}]",
137            in(reg) &mut gdtr,
138            options(nostack, preserves_flags),
139        );
140        core::arch::asm!(
141            "str {0:x}",
142            out(reg) tr_selector,
143            options(nostack, nomem, preserves_flags),
144        );
145    }
146
147    if tr_selector == 0 {
148        return None;
149    }
150
151    let entry_offset = (tr_selector & !0x7) as usize;
152    if entry_offset + 16 > gdtr.limit as usize + 1 {
153        return None;
154    }
155
156    // SAFETY: The GDTR base/limit were read from the CPU and bounds-checked above.
157    let (low, high) = unsafe {
158        let entry_ptr = (gdtr.base + entry_offset as u64) as *const u64;
159        (
160            core::ptr::read_unaligned(entry_ptr),
161            core::ptr::read_unaligned(entry_ptr.add(1)),
162        )
163    };
164
165    let base_low =
166        ((low >> 16) & 0xFFFF) | (((low >> 32) & 0xFF) << 16) | (((low >> 56) & 0xFF) << 24);
167    let tss_base = base_low | (high << 32);
168    if tss_base == 0 {
169        return None;
170    }
171
172    // SAFETY: The live TSS base comes from the CPU's TSS descriptor.
173    let rsp0 = unsafe {
174        let tss = &*(tss_base as *const TaskStateSegment);
175        tss.privilege_stack_table[0].as_u64()
176    };
177
178    Some(LoadedTssInfo {
179        tr_selector,
180        tss_base,
181        rsp0,
182    })
183}
184
185/// Update TSS.rsp0 : the kernel stack pointer used when transitioning
186/// from Ring 3 to Ring 0 on interrupt/syscall.
187///
188/// Called on every context switch to point to the new task's kernel stack top.
189#[track_caller]
190pub fn set_kernel_stack(stack_top: VirtAddr) {
191    let cpu_index = crate::arch::x86_64::percpu::current_cpu_index();
192    set_kernel_stack_for(cpu_index, stack_top);
193}
194
195/// Update TSS.rsp0 for a specific CPU index.
196#[track_caller]
197pub fn set_kernel_stack_for(cpu_index: usize, stack_top: VirtAddr) {
198    if cpu_index >= crate::arch::x86_64::percpu::MAX_CPUS {
199        log::warn!("set_kernel_stack_for: cpu_index {} out of range", cpu_index);
200        return;
201    }
202    // SAFETY: privilege_stack_table[0] is a VirtAddr (u64), writes are atomic on x86_64.
203    // Called with interrupts disabled or from the scheduler with lock held.
204    if !TSS_INIT[cpu_index].load(Ordering::Acquire) {
205        return;
206    }
207    let caller = Location::caller();
208    unsafe {
209        let tss = &raw mut *TSS[cpu_index].as_mut_ptr();
210        let old_stack_top = (*tss).privilege_stack_table[0];
211        (*tss).privilege_stack_table[0] = stack_top;
212        if crate::debug_cfg::E9_TRACE_TSS {
213            crate::e9_println!(
214                "[tss-set] cpu={} old={:#x} new={:#x} caller={}:{}",
215                cpu_index,
216                old_stack_top.as_u64(),
217                stack_top.as_u64(),
218                caller.file(),
219                caller.line()
220            );
221        }
222    }
223}