aboutsummaryrefslogtreecommitdiff
path: root/arch/x86_64/src/context_switching/main.cpp
blob: 008da2fd05c33efbbcfc8bf12d6d3a4969fa3b41 (plain)
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
#include "arch/context_switching/main.hpp"

#include "arch/boot/pointers.hpp"
#include "arch/exception_handling/assert.hpp"
#include "arch/kernel/cpu/if.hpp"
#include "arch/kernel/cpu/jmp.hpp"
#include "arch/kernel/cpu/tr.hpp"

namespace teachos::arch::context_switching
{
  auto initialize_descriptor_tables() -> descriptor_tables
  {
    kernel::cpu::clear_interrupt_flag();
    decltype(auto) global_descriptor_table = segment_descriptor_table::initialize_global_descriptor_table();
    decltype(auto) interrupt_descriptor_table = interrupt_descriptor_table::initialize_interrupt_descriptor_table();

    kernel::cpu::far_pointer pointer{&boot::reload_segment_register,
                                     1 * sizeof(segment_descriptor_table::segment_descriptor)};
    asm volatile("rex64 lcall *%[far_function_pointer]" : : [far_function_pointer] "m"(pointer));

    // Load task state segment descriptor from the last element in the global descriptor table, done by calculating
    // offset in bytes to the start of the segment descriptor (5 * 16) = 80
    uint16_t const tss_selector =
        (global_descriptor_table.size() - 1) * sizeof(segment_descriptor_table::segment_descriptor);
    kernel::cpu::load_task_register(tss_selector);

    auto const stored_task_register = kernel::cpu::store_task_register();
    arch::exception_handling::assert(tss_selector == stored_task_register,
                                     "[Global Descriptor Table] Loaded TR value is not the same as the stored value.");

    // FIXME: We currently cannot enable interrupts, since for some reason, we will later run into what looks like a GP
    // and triple fault.
    // @MTO: SOMETIMES i get past a breakpoint here???? seems to happen when i actually pause before (f.e. inside the
    // idt). NEVER happened when stepping through quickly. Can you reproduce this?
    kernel::cpu::set_interrupt_flag();

    descriptor_tables tables = {global_descriptor_table, interrupt_descriptor_table};
    return tables;
  }
}  // namespace teachos::arch::context_switching