aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/devices.cpp
blob: 8f3011fef2bd4720a1f7b8462c50bbc8c66c7d53 (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
98
#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 <string_view>
#include <utility>

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

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

    interface_registry::init();

    root_bus = kstd::make_shared<kernel::devices::root_bus>();
    register_device(root_bus);
    root_bus->init();
  }

  auto get_root_bus() -> kstd::shared_ptr<bus>
  {
    if (!root_bus)
    {
      kapi::system::panic("[OS:DEV] Root bus not initialized!");
    }
    return root_bus;
  }

  auto register_device(kstd::shared_ptr<device> device) -> bool
  {
    if (!device)
    {
      return false;
    }

    kstd::println("[OS:DEV] Registering device {}", device->name());

    auto found = device_tree.find(device->name());
    if (found != device_tree.end())
    {
      if (!found->second.expired())
      {
        return false;
      }

      found->second = device;
      return true;
    }

    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::shared_ptr<device>
  {
    auto found = device_tree.find(kstd::string{name});
    if (found == device_tree.end())
    {
      return nullptr;
    }

    return found->second.lock();
  }

}  // namespace kapi::devices

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

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