aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/devices.cpp
blob: b2911b025675f264d0ffb63c40e692468feb2a8a (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
91
92
93
94
95
96
97
#include "kapi/devices.hpp"

#include "kapi/acpi.hpp"
#include "kapi/system.hpp"

#include "kernel/devices/cpu.hpp"
#include "kernel/devices/root_bus.hpp"

#include <kstd/flat_map>
#include <kstd/memory>
#include <kstd/print>

#include <atomic>
#include <cstddef>
#include <optional>
#include <string_view>
#include <utility>

namespace kapi::devices
{

  namespace
  {
    auto constinit next_major_number = std::atomic_size_t{1};
    auto constinit root_bus = std::optional<kernel::devices::root_bus>{};
    auto constinit device_tree = kstd::flat_map<std::pair<std::size_t, std::size_t>, kstd::observer_ptr<device>>{};
  }  // namespace

  auto init() -> void
  {
    auto static is_initialized = std::atomic_flag{};
    if (is_initialized.test_and_set())
    {
      return;
    }

    auto & bus = root_bus.emplace();
    register_device(bus);
    bus.init();

    auto madt = kapi::acpi::get_table("APIC");
    if (madt)
    {
      auto cpu_major = allocate_major_number();
      auto cpu = kstd::make_unique<kernel::devices::cpu>(cpu_major);
      bus.add_child(std::move(cpu));
    }
  }

  auto get_root_bus() -> bus &
  {
    if (!root_bus.has_value())
    {
      kapi::system::panic("[OS:DEV] Root bus not initialized!");
    }
    return *root_bus;
  }

  auto allocate_major_number() -> std::size_t
  {
    return next_major_number++;
  }

  auto register_device(device & device) -> bool
  {
    kstd::println("[OS:DEV] Registering device {}@{}:{}", device.name(), device.major(), device.minor());
    return device_tree.emplace(std::pair{device.major(), device.minor()}, &device).second;
  }

  auto unregister_device(device &) -> bool
  {
    kstd::println("[OS:DEV] TODO: implement device deregistration");
    return false;
  }

  auto find_device(std::size_t major, std::size_t minor) -> kstd::observer_ptr<device>
  {
    if (device_tree.contains(std::pair{major, minor}))
    {
      return device_tree.at(std::pair{major, minor});
    }
    return nullptr;
  }

  auto find_device(std::string_view name) -> kstd::observer_ptr<device>
  {
    for (auto const & [key, value] : device_tree)
    {
      if (value->name() == name)
      {
        return value;
      }
    }
    return nullptr;
  }

}  // namespace kapi::devices