aboutsummaryrefslogtreecommitdiff
path: root/kernel/kapi/memory.cpp
blob: 83b32f0de8fdb76bc6e7d188c08c7c67aa21ec70 (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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#include <kapi/memory.hpp>

#include <kernel/memory/bitmap_allocator.hpp>
#include <kernel/memory/mmio_allocator.hpp>

#include <kapi/system.hpp>

#include <kstd/memory.hpp>
#include <kstd/print.hpp>
#include <kstd/result.hpp>
#include <kstd/system_error.hpp>
#include <kstd/units.hpp>

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <ranges>
#include <span>
#include <utility>

namespace kapi::memory
{

  namespace
  {
    struct bad_frame_allocator final : public frame_allocator
    {
      bad_frame_allocator static instance;

      auto allocate_many(std::size_t) noexcept -> std::optional<std::pair<frame, std::size_t>> override
      {
        system::panic("[OS:MEM] Tried to allocate frames without an active allocator.");
      }

      auto mark_used(frame) -> void override
      {
        system::panic("[OS:MEM] Tried to mark frame as used without an active allocator.");
      }

      auto release_many(std::pair<frame, std::size_t>) -> void override
      {
        system::panic("[OS:MEM] Tried to release frames without an active allocator.");
      }
    };

    struct bad_page_mapper final : public page_mapper
    {
      bad_page_mapper static instance;

      auto map(page, frame, flags) -> kstd::observer_ptr<std::byte> override
      {
        system::panic("[OS:MEM] Tried to map a page without an active mapper.");
      }

      auto unmap(page) -> kapi::memory::frame override
      {
        system::panic("[OS:MEM] Tried to unmap a page without an active mapper.");
      }

      auto try_unmap(page) noexcept -> std::optional<kapi::memory::frame> override
      {
        return std::nullopt;
      }
    };

    constinit bad_frame_allocator bad_frame_allocator::instance{};
    constinit bad_page_mapper bad_page_mapper::instance{};
    auto constinit allocator = std::optional<kernel::memory::bitmap_frame_allocator>{};
    auto constinit mmio_allocator = std::optional<kernel::memory::mmio_allocator>{};

    constinit auto active_frame_allocator = static_cast<frame_allocator *>(&bad_frame_allocator::instance);
    constinit auto active_page_mapper = static_cast<page_mapper *>(&bad_page_mapper::instance);

    auto unmap_range_if_mapped(page start, std::size_t count) -> void
    {
      for (auto page_index = 0uz; page_index < count; ++page_index)
      {
        auto const current_page = start + page_index;

        // NOTE: We ignore the returned frame, since it has never been allocated by any kernel code. Rather, this frame
        // corresponds to a frame which is "always present" since it is an abstraction of a memory mapped device,
        // provided by the firmware. Additionally, we use try unmap to avoid panicking if the page was not mapped.
        std::ignore = active_page_mapper->try_unmap(current_page);
      }
    }
  }  // namespace

  auto get_frame_allocator() -> frame_allocator &
  {
    return *active_frame_allocator;
  }

  auto set_frame_allocator(frame_allocator & allocator) -> std::optional<frame_allocator *>
  {
    if (&allocator == active_frame_allocator)
    {
      return {};
    }
    return std::exchange(active_frame_allocator, &allocator);
  }

  auto set_page_mapper(page_mapper & mapper) -> std::optional<page_mapper *>
  {
    if (&mapper == active_page_mapper)
    {
      return {};
    }
    return std::exchange(active_page_mapper, &mapper);
  }

  auto allocate_frame() -> std::optional<frame>
  {
    return get_frame_allocator().allocate();
  }

  auto allocate_many_frames(std::size_t count) -> std::optional<std::pair<frame, std::size_t>>
  {
    return get_frame_allocator().allocate_many(count);
  }

  auto map(page page, frame frame, page_mapper::flags flags) -> kstd::observer_ptr<std::byte>
  {
    return active_page_mapper->map(page, frame, flags);
  }

  auto unmap(page page) -> frame
  {
    return active_page_mapper->unmap(page);
  }

  auto init_pmm(std::size_t frame_count, void (&handoff_handler)(frame_allocator &)) -> void
  {
    using namespace kstd::units_literals;

    auto const bitmap_bytes = kstd::bytes{(frame_count + 7uz) / 8uz};
    auto const bitmap_pages = (bitmap_bytes + page::size - 1_B) / page::size;

    auto const bitmap_frames = allocate_many_frames(bitmap_pages);
    if (!bitmap_frames)
    {
      system::panic("[OS:MEM] Not enough memory for bitmap allocator!");
    }

    auto const flags = page_mapper::flags::writable | page_mapper::flags::supervisor_only | page_mapper::flags::global;
    auto bitmap_ptr = kstd::observer_ptr<std::uint64_t>{nullptr};

    std::ranges::for_each(std::views::iota(0uz, bitmap_pages), [&](auto index) {
      auto page = page::containing(pmm_metadata_base + index * page::size);
      auto frame = memory::frame(bitmap_frames->first.number() + index);
      auto mapped = active_page_mapper->map(page, frame, flags);
      if (!bitmap_ptr)
      {
        bitmap_ptr = reinterpret_pointer_cast<std::uint64_t>(mapped);
      }
    });

    auto bitmap = std::span{bitmap_ptr.get(),
                            (bitmap_bytes + kstd::size_of<std::uint64_t>() - 1_B) / kstd::size_of<std::uint64_t>()};

    allocator.emplace(bitmap, frame_count);

    handoff_handler(allocator.value());
    set_frame_allocator(allocator.value());
    kstd::println("[OS:MEM] Physical memory manager initialized.");
  }

  auto init_mmio(linear_address base, std::size_t page_count) -> void
  {
    mmio_allocator.emplace(base, page_count);
  }

  auto allocate_mmio_region(std::size_t page_count) -> kstd::result<mmio_region>
  {
    if (!mmio_allocator)
    {
      system::panic("[OS:MEM] MMIO allocator not initialized!");
    }

    return mmio_allocator->allocate(page_count).transform([&](auto base) -> mmio_region { return {base, page_count}; });
  }

  auto map_mmio_region(mmio_region region, physical_address hw_base, page_mapper::flags flags)
      -> kstd::result<kstd::observer_ptr<std::byte>>
  {
    // Ensure that the MMIO region is not mapped as executable. Asking for an executable mapping of an MMIO region is a
    // logical error, not a runtime issue.
    if ((flags & page_mapper::flags::executable) != page_mapper::flags::empty)
    {
      system::panic("[OS:MEM] Attempt to map MMIO region at {:#018x} as executable!", region.first);
    }

    auto [start, count] = region;

    auto start_page = page::containing(start);
    auto start_frame = frame::containing(hw_base);

    flags |= page_mapper::flags::uncached | page_mapper::flags::supervisor_only | page_mapper::flags::global;

    auto first_mapped_page = map(start_page, start_frame, flags);

    if (!first_mapped_page)
    {
      return kstd::failure(make_error_code(kstd::errc::not_enough_memory));
    }

    for (auto page_index = 1uz; page_index < count; ++page_index)
    {
      auto page = start_page + page_index;
      auto frame = start_frame + page_index;
      auto mapped = map(page, frame, flags);

      if (!mapped)
      {
        unmap_range_if_mapped(start_page, page_index);
        return kstd::failure(make_error_code(kstd::errc::not_enough_memory));
      }
    }

    return kstd::success(first_mapped_page);
  }

  auto release_mmio_region(mmio_region region) -> void
  {
    if (!mmio_allocator)
    {
      system::panic("[OS:MEM] MMIO allocator not initialized!");
    }

    auto start_address = region.first;
    auto start_page = kapi::memory::page::containing(start_address);

    unmap_range_if_mapped(start_page, region.second);

    mmio_allocator->release(region.first);
  }

}  // namespace kapi::memory