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

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

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

#include <algorithm>
#include <span>
#include <utility>

namespace kapi::devices
{
  bus::bus(kstd::string const & name)
      : device{name}
  {}

  auto bus::init() -> bool
  {
    if (m_init_was_called.test_and_set())
    {
      kstd::println(kstd::print_sink::stderr, "[OS:DEV] Bus {} already initialized", name());
      return true;
    }

    if (!enumerate())
    {
      kstd::println(kstd::print_sink::stderr, "[OS:DEV] Bus {} enumeration failed", name());
      return false;
    }

    auto child_status = std::ranges::fold_left(m_devices, true, [&](bool acc, auto & child) -> bool {
      kstd::println("[OS:DEV] Initializing child device {}@{}", child->name(), name());
      return child->init() && acc;
    });

    m_initialized.test_and_set();

    return child_status;
  }

  auto bus::add_child(kstd::shared_ptr<device> child) -> void
  {
    child->set_parent(kstd::static_pointer_cast<bus>(shared_from_this()));

    if (!kapi::devices::register_device(child))
    {
      kapi::system::panic("[OS:DEV] Failed to register child device {}", child->name());
    }

    auto & attached = m_devices.emplace_back(std::move(child));
    attached->set_state(state::present);

    driver_registry::get().device_attached(attached);

    if (m_initialized.test())
    {
      kstd::println("[OS:DEV] Initializing child device {}@{}", attached->name(), name());
      if (!attached->init())
      {
        kapi::system::panic("[OS:DEV] Failed to initialize child device");
      }
    }
  }

  [[nodiscard]] auto bus::children() const -> std::span<kstd::shared_ptr<device> const>
  {
    return {m_devices.data(), m_devices.size()};
  }

  auto bus::protocol() -> struct bus_protocol *
  {
    return nullptr;
  }

  auto bus::enumerate() -> bool
  {
    return true;
  }

}  // namespace kapi::devices