aboutsummaryrefslogtreecommitdiff
path: root/arch/x86_64/kapi/cpu.cpp
blob: b19ba2144c76b606cb7356a01a1d427eb02625c4 (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
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
#include "kapi/cpu.hpp"

#include "kapi/system.hpp"

#include "arch/cpu/initialization.hpp"

#include <kstd/print>
#include <kstd/vector>

#include <array>
#include <atomic>
#include <cstdint>

namespace kapi::cpu
{

  namespace
  {
    constexpr auto irq_offset = 32uz;
    auto constinit interrupt_handlers = std::array<kstd::vector<interrupt_handler *>, 256 - irq_offset>{};
  }  // namespace

  auto init() -> void
  {
    auto static constinit is_initialized = std::atomic_flag{};

    if (is_initialized.test_and_set())
    {
      system::panic("[x86_64] CPU has already been initialized.");
    }

    arch::cpu::initialize_descriptors();
    arch::cpu::initialize_legacy_interrupts();
  }

  auto halt() -> void
  {
    asm volatile("1: hlt\njmp 1b");
    __builtin_unreachable();
  }

  auto enable_interrupts() -> void
  {
    asm volatile("sti");
  }

  auto disable_interrupts() -> void
  {
    asm volatile("cli");
  }

  auto register_interrupt_handler(std::uint32_t irq_number, interrupt_handler & handler) -> void
  {
    if (irq_number < irq_offset)
    {
      system::panic("[x86_64:CPU] IRQ number must be in range [32, 255].");
    }

    interrupt_handlers[irq_number - irq_offset].push_back(&handler);
  }

  auto unregister_interrupt_handler(std::uint32_t irq_number, [[maybe_unused]] interrupt_handler & handler) -> void
  {
    if (irq_number < irq_offset)
    {
      system::panic("[x86_64:CPU] IRQ number must be in range [32, 255].");
    }

    kstd::println("[x86_64:CPU] TODO: support erasure from vector.");
  }

  auto dispatch_interrupt(std::uint32_t irq_number) -> status
  {
    if (irq_number < irq_offset)
    {
      return status::unhandled;
    }

    for (auto handler : interrupt_handlers[irq_number - irq_offset])
    {
      if (handler && handler->handle_interrupt(irq_number) == status::handled)
      {
        return status::handled;
      }
    }

    return status::unhandled;
  }

}  // namespace kapi::cpu