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

#include <kernel/devices/root_bus.hpp>

#include <kapi/system.hpp>
#include <kapi/test_support/devices.hpp>

#include <kstd/flat_map.hpp>
#include <kstd/memory.hpp>
#include <kstd/print.hpp>
#include <kstd/string.hpp>

#include <optional>
#include <string_view>
#include <utility>

namespace kapi::devices
{
  namespace
  {
    auto constinit root_bus = std::optional<kernel::devices::root_bus>{};
    auto constinit device_tree = kstd::flat_map<kstd::string, kstd::observer_ptr<device>>{};
  }  // namespace

  auto init() -> void
  {
    if (root_bus.has_value())
    {
      kapi::system::panic("[OS:DEV] The device subsystem has already been initialized");
    }

    interface_registry::init();

    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 register_device(device & device) -> bool
  {
    kstd::println("[OS:DEV] Registering device {}", device.name());
    return device_tree.emplace(device.name(), &device).second;
  }

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

  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

namespace kapi::test_support::devices
{
  auto deinit() -> void
  {
    deinit_interface_registry();

    kapi::devices::root_bus.reset();
  }
}  // namespace kapi::test_support::devices