aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/devices.cpp
blob: c0b738e86e1de69864462623b44cdaa0fc97be1d (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
#include "kapi/devices.hpp"

#include "kapi/system.hpp"

#include "kernel/devices/root_bus.hpp"

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

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

namespace kapi::devices
{

  namespace
  {
    auto constinit next_major_number = std::atomic_size_t{0};
    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 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;
  }

}  // namespace kapi::devices