From 45bf10f2ac489cc8253eb2f145c569edc16fc45a Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 16 Nov 2026 10:20:33 +0100 Subject: kapi/memory: replace mmio_region API with mmio_window Previously, allocation and mapping of MMIO regions was a multi-step process. The MMIO region API required its users to track and manage the lifetime of an MMIO region allocation manually. The new MMIO window API simplifies this by providing a single-step mapping interface and automatic lifetime management. Additionally, the new API adds strict bounds and alignment checks, to ensure that all MMIO accesses are within the requested range. The new API enforces these constraints at runtime via a system panic. Other contract violations, such as zero-sized mappings, are handled via runtime error codes. The new kapi::memory::mmio_window preserves the in-page offset of the hardware base within the window and bases all accesses on this offset. This means no user intervention is required to handle hardware ranges that are not aligned to a natural page boundary. The original pointer adjustment logic has been moved into the mmio_window class. Previous consumers of the region API (x86_64 LAPIC, PCIe) have been updated to the new mmio_window API. The behavior of the PCIe scan implementation has changed in that no windows are kept alive beyond the execution of the scan, since there are no consumers that would require persistent MMIO windows. Tests for the new infrastructure have been added, including a test support seam to allow for deinitialization of the MMIO subsystem in tests. --- arch/x86_64/arch/drivers/cpu/lapic.cpp | 30 +-- arch/x86_64/arch/drivers/cpu/lapic.hpp | 4 +- kapi/kapi/memory.hpp | 46 +--- kapi/kapi/memory/mmio.hpp | 187 ++++++++++++++++ kapi/kapi/test_support/memory.hpp | 11 + kernel/CMakeLists.txt | 1 + kernel/kapi/memory.cpp | 87 -------- kernel/kapi/memory/mmio.cpp | 192 ++++++++++++++++ kernel/kapi/memory/mmio.tests.cpp | 392 +++++++++++++++++++++++++++++++++ kernel/kernel/devices/pci_express.cpp | 60 ++--- 10 files changed, 818 insertions(+), 192 deletions(-) create mode 100644 kapi/kapi/memory/mmio.hpp create mode 100644 kapi/kapi/test_support/memory.hpp create mode 100644 kernel/kapi/memory/mmio.cpp create mode 100644 kernel/kapi/memory/mmio.tests.cpp diff --git a/arch/x86_64/arch/drivers/cpu/lapic.cpp b/arch/x86_64/arch/drivers/cpu/lapic.cpp index 02d2f529..996b99c5 100644 --- a/arch/x86_64/arch/drivers/cpu/lapic.cpp +++ b/arch/x86_64/arch/drivers/cpu/lapic.cpp @@ -118,27 +118,20 @@ namespace arch::drivers::cpu auto guard = kstd::lock_guard{m_lock}; - if (!m_is_mapped) + if (!m_mmio_window) { - auto const page_count = (mmio->size + kapi::memory::page_size - 1_B) / kapi::memory::page_size; - auto mmio_region = kapi::memory::allocate_mmio_region(page_count); + auto const mmio_size = mmio->size; + auto const mmio_base = kapi::memory::physical_address{mmio->start}; + auto mmio_window = + kapi::memory::mmio_window::map(mmio_base, mmio_size, kapi::memory::mmio_window::access::writable); - if (!mmio_region) - { - return kstd::failure(mmio_region.error()); - } - - if (auto result = kapi::memory::map_mmio_region(*mmio_region, kapi::memory::physical_address{mmio->start}, - kapi::memory::page_mapper::flags::writable); - !result) + if (!mmio_window) { kstd::println(kstd::print_sink::stderr, "[ARCH:DRV] LAPIC {} MMIO mapping failed!", signature->hardware_id()); - kapi::memory::release_mmio_region(*mmio_region); - return kstd::failure(result.error()); + return kstd::failure(mmio_window.error()); } - m_mapped_region = *mmio_region; - m_is_mapped = true; + m_mmio_window = std::move(*mmio_window); } if (signature->is_bsp()) @@ -170,15 +163,12 @@ namespace arch::drivers::cpu auto lapic::read_register(registers id) const -> std::uint32_t { - auto reg = - static_cast>(m_mapped_region.first + std::to_underlying(id)); - return *reg; + return m_mmio_window->read(kstd::bytes(std::to_underlying(id))); } auto lapic::write_register(registers id, std::uint32_t value) -> void { - auto reg = static_cast>(m_mapped_region.first + std::to_underlying(id)); - *reg = value; + m_mmio_window->write(kstd::bytes(std::to_underlying(id)), value); } auto lapic::query_facet(kapi::capabilities::facet_id facet) -> kstd::observer_ptr diff --git a/arch/x86_64/arch/drivers/cpu/lapic.hpp b/arch/x86_64/arch/drivers/cpu/lapic.hpp index 52533d9a..e0b3bb71 100644 --- a/arch/x86_64/arch/drivers/cpu/lapic.hpp +++ b/arch/x86_64/arch/drivers/cpu/lapic.hpp @@ -13,6 +13,7 @@ #include #include +#include #include namespace arch::drivers::cpu @@ -37,8 +38,7 @@ namespace arch::drivers::cpu auto write_register(registers id, std::uint32_t value) -> void; mutable kapi::tracked_mutex m_lock{}; - kapi::memory::mmio_region m_mapped_region{}; - bool m_is_mapped{}; + std::optional m_mmio_window{}; }; } // namespace arch::drivers::cpu diff --git a/kapi/kapi/memory.hpp b/kapi/kapi/memory.hpp index ece85203..2abad38e 100644 --- a/kapi/kapi/memory.hpp +++ b/kapi/kapi/memory.hpp @@ -6,11 +6,11 @@ #include // IWYU pragma: export #include // IWYU pragma: export #include // IWYU pragma: export +#include // IWYU pragma: export #include // IWYU pragma: export #include // IWYU pragma: export #include -#include #include #include @@ -19,8 +19,6 @@ namespace kapi::memory { - using mmio_region = std::pair; - //! @addtogroup kapi-memory-kernel-defined //! @{ @@ -86,48 +84,6 @@ namespace kapi::memory //! @return The frame the page was previously mapped to. [[nodiscard]] auto unmap(page page) -> frame; - //! Initialize the Memory-mapped I/O region system. - //! - //! @param base The base address for the MMIO region. - //! @param page_count The number of pages the MMIO region is spans. - auto init_mmio(linear_address base, std::size_t page_count) -> void; - - //! Allocate a Memory-mapped I/O region of the given size. - //! - //! @warning This function will panic if the MMIO system has not been initialized! - //! - //! @param page_count The number of pages to allocate. - //! @return The newly allocated MMIO region on success, an error otherwise. - auto allocate_mmio_region(std::size_t page_count) -> kstd::result; - - //! Map a region of Memory-mapped I/O address space to a given hardware address using the given flags. - //! - //! @warning This function will panic if no page mapper has been registered, or the page has already been mapped. - //! - //! @warning This function will not ensure that the frame is not already in use. - //! - //! @warning This function will panic if an attempt is made to map an MMIO region as executable. - //! - //! This function will always set the @p uncached, @p global, and @p supervisor_only flags. - //! - //! @param region The region to map. This region must cover the in-page offset of hw_base plus the range to be - //! accessed. - //! @param hw_base The base of the hardware region. - //! @param flags The flags to apply. - //! @return A pointer into the mapped region, including any frame offset, on success, an error otherwise, in which - //! case any partial mappings have been rolled back. - auto map_mmio_region(mmio_region region, physical_address hw_base, page_mapper::flags flags = {}) - -> kstd::result>; - - //! Release (unmap and free) a Memory-mapped I/O region. - //! - //! This function is tolerant of partially mapped regions and will unmap any mapped pages within the region before - //! releasing the MMIO region. - //! - //! @warning This function will panic if the MMIO system has not been initialized! - //! @param region The region to release. - auto release_mmio_region(mmio_region region) -> void; - //! @} //! @addtogroup kapi-memory-platform-defined diff --git a/kapi/kapi/memory/mmio.hpp b/kapi/kapi/memory/mmio.hpp new file mode 100644 index 00000000..f1a7c6dc --- /dev/null +++ b/kapi/kapi/memory/mmio.hpp @@ -0,0 +1,187 @@ +#ifndef TEACHOS_KAPI_MEMORY_MMIO_HPP +#define TEACHOS_KAPI_MEMORY_MMIO_HPP + +// IWYU pragma: private, include + +#include + +#include +#include +#include + +#include +#include + +namespace kapi::memory +{ + + //! This concept models the requirements for a type to be used as a MMIO datum. + //! + //! A valid MMIO datum type must be an unsigned integral type, excluding bool, and must have a size of 1, 2, 4, or 8 + //! bytes. + template + concept mmio_datum = requires { + requires std::unsigned_integral; + requires(!std::same_as); + requires(sizeof(ValueType) == 1 || sizeof(ValueType) == 2 || sizeof(ValueType) == 4 || sizeof(ValueType) == 8); + }; + + //! @addtogroup kapi-memory-kernel-defined + //! @{ + + //! A window into memory-mapped I/O (MMIO) space. + //! + //! This structure represents a contiguous region of MMIO space that can be accessed according to the specified access + //! mode. The only permitted operations are read or write operations that access a single MMIO datum (see mmio_datum) + //! at a time. + //! + //! This type is move-only. A moved-from window is considered to have a size of zero and a base of null. All accesses + //! to a moved-from window are invalid and will panic. Destruction of a moved-from window does not change any mappings + //! or allocations. + struct mmio_window + { + //! The access mode for the MMIO window. + enum struct access : bool + { + //! The window can only be read from. + read_only, + //! The window can read from and written to. + writable, + }; + + //! Create a new MMIO window with the given properties. + //! + //! This function creates a new MMIO window of the specified size for the specified hardware MMIO address. The + //! mapping will always be created with the @p uncached, @p global, and @p supervisor_only page flags set. Depending + //! on the value of @p mode, the @p writable page flag will be set or not. The mapping covers every page containing + //! the requested range; accesses are nevertheless bounds-checked against @p size. All reads and writes are offset + //! from the page-aligned base address according to the in-page offset of the hardware base address. + //! + //! @warning This function will panic if the MMIO subsystem has not been initialized. + //! + //! @param hw_base The physical base address of the MMIO region. + //! @param size The size of this MMIO window. The size must not be zero. + //! @param mode The access mode for the MMIO region. + //! @return A new MMIO window on success, an error otherwise. + [[nodiscard]] auto static map(physical_address hw_base, kstd::bytes size, access mode) -> kstd::result; + + mmio_window(mmio_window const &) = delete; + + //! Move-construct a new MMIO window from an existing one. + //! + //! The moved-from window will be left with a zero-sized state and a base of null. All accesses to the moved-from + //! window are invalid and will panic. + mmio_window(mmio_window && other) noexcept; + + //! Destroy this MMIO window and release its resources. + //! + //! This will unmap the MMIO window and release any associated resources. If the window has been moved from, this + //! operation does nothing. + ~mmio_window(); + + auto operator=(mmio_window const &) -> mmio_window & = delete; + + //! Move-assign an existing MMIO window to this one. + //! + //! The moved-from window will be left with a zero-sized state and a base of null. All accesses to the moved-from + //! window are invalid and will panic. If this window has been previously mapped, it will be unmapped and its + //! resources released. + //! + //! Assigning a window to itself is safe and has no effect. + auto operator=(mmio_window && other) noexcept -> mmio_window &; + + //! Read a value, at a given offset, from this MMIO window. + //! + //! @warning This function will panic if the offset is out of bounds. + //! + //! @warning This function will panic if the operation would result in an unaligned access. The check is performed + //! against the absolute address (including the in-page offset). + //! + //! @warning This function will panic if this window has been moved from. + //! + //! @tparam ValueType The type of value to read from the MMIO window. + //! @param offset The offset within the MMIO window to read from. + //! @return The value read from the MMIO window. + template + [[nodiscard]] auto read(kstd::bytes offset) const -> ValueType + { + assert_valid_access(offset, kstd::size_of()); + auto read_pointer = reinterpret_cast(m_data_base.get() + offset.value); + return *read_pointer; + } + + //! Write a value, at a given offset, to this MMIO window. + //! + //! @warning This function will panic if the offset is out of bounds. + //! + //! @warning This function will panic if this window is read-only. + //! + //! @warning This function will panic if the operation would result in an unaligned access. The check is performed + //! against the absolute address (including the in-page offset). + //! + //! @warning This function will panic if this window has been moved from. + //! + //! @tparam ValueType The type of value to write to the MMIO window. + //! @param offset The offset within the MMIO window to write to. + //! @param value The value to write to the MMIO window. + template + auto write(kstd::bytes offset, ValueType value) -> void + { + assert_valid_access(offset, kstd::size_of()); + assert_writable(); + auto write_pointer = reinterpret_cast(m_data_base.get() + offset.value); + *write_pointer = value; + } + + private: + //! Construct a new MMIO window with the given mapping base, data base, size, and access mode. + //! + //! @param mapping_base The linear base address for the MMIO window. + //! @param data_base The offset adjusted base address for the MMIO window, as returned by the page mapper. + //! @param size The accessible size of the MMIO window. + //! @param mode The access mode of the MMIO window. + mmio_window(linear_address mapping_base, kstd::observer_ptr data_base, kstd::bytes size, access mode); + + //! Check if an access at the given offset and size is valid for this MMIO window. + //! + //! @warning This function will panic if the access is out of bounds. + //! + //! @warning This function will panic if the operation would result in an unaligned access. The check is performed + //! against the absolute address (including the in-page offset). + //! + //! @warning This function will panic if this window has been moved from. + //! + //! @param offset The offset within the MMIO window to check. + //! @param size The size of the access to check. + auto assert_valid_access(kstd::bytes offset, kstd::bytes size) const -> void; + + //! Check if this MMIO window is writable. + //! + //! @warning This function will panic if the window is not writable. + //! + auto assert_writable() const -> void; + + //! Release the resources associated with this MMIO window. + auto release() -> void; + + //! The linear base address of this MMIO window. + linear_address m_mapping_base; + //! The offset adjusted base address of this MMIO window. + kstd::observer_ptr m_data_base; + //! The accessible size of this MMIO window. + kstd::bytes m_data_size; + //! The access mode of this MMIO window. + access m_mode; + }; + + //! Initialize the Memory-mapped I/O region system. + //! + //! @param base The base address for the MMIO region. + //! @param page_count The number of pages the MMIO region spans. + auto init_mmio(linear_address base, std::size_t page_count) -> void; + + //! @} + +} // namespace kapi::memory + +#endif diff --git a/kapi/kapi/test_support/memory.hpp b/kapi/kapi/test_support/memory.hpp new file mode 100644 index 00000000..33c02bb9 --- /dev/null +++ b/kapi/kapi/test_support/memory.hpp @@ -0,0 +1,11 @@ +#ifndef TEACHOS_KAPI_TEST_SUPPORT_MEMORY_HPP +#define TEACHOS_KAPI_TEST_SUPPORT_MEMORY_HPP + +namespace kapi::test_support::memory +{ + + auto deinit_mmio() -> void; + +} // namespace kapi::test_support::memory + +#endif diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index a8be3850..705f3a85 100644 --- a/kernel/CMakeLists.txt +++ b/kernel/CMakeLists.txt @@ -23,6 +23,7 @@ target_sources("kernel_lib" PRIVATE "kapi/filesystem.cpp" "kapi/interrupts.cpp" "kapi/memory.cpp" + "kapi/memory/mmio.cpp" "kapi/system.cpp" "kapi/tracked_mutex.cpp" diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index 12e9e23f..4160092d 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -1,14 +1,11 @@ #include #include -#include #include #include #include -#include -#include #include #include @@ -67,23 +64,10 @@ namespace kapi::memory constinit bad_frame_allocator bad_frame_allocator::instance{}; constinit bad_page_mapper bad_page_mapper::instance{}; auto constinit allocator = std::optional{}; - auto constinit mmio_allocator = std::optional{}; constinit auto active_frame_allocator = static_cast(&bad_frame_allocator::instance); constinit auto active_page_mapper = static_cast(&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 & @@ -165,75 +149,4 @@ namespace kapi::memory 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 - { - 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> - { - // 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); - auto frame_offset = hw_base.raw() % frame::size.value; - - 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 + frame_offset); - } - - 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 diff --git a/kernel/kapi/memory/mmio.cpp b/kernel/kapi/memory/mmio.cpp new file mode 100644 index 00000000..be99d9d7 --- /dev/null +++ b/kernel/kapi/memory/mmio.cpp @@ -0,0 +1,192 @@ +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace kstd::units_literals; + +namespace kapi::memory +{ + + namespace + { + auto constinit mmio_allocator = std::optional{}; + + auto unmap_range(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. + std::ignore = memory::unmap(current_page); + } + } + + constexpr auto determine_page_count(std::size_t in_page_offset, kstd::bytes size) -> std::size_t + { + return (kstd::bytes{in_page_offset} + size - 1_B) / page_size + 1; + } + } // namespace + + auto mmio_window::map(physical_address hw_base, kstd::bytes size, access mode) -> kstd::result + { + if (!mmio_allocator) + { + kapi::system::panic("[OS:MEM] Tried to map an MMIO window before the MMIO subsystem was initialized!"); + } + + if (size == 0_B || size.value - 1 > std::numeric_limits::max() - hw_base.raw()) + { + return kstd::failure(make_error_code(kstd::errc::invalid_argument)); + } + + auto const in_page_offset = hw_base.raw() % frame::size.value; + auto const page_count = determine_page_count(in_page_offset, size); + auto const virtual_base = mmio_allocator->allocate(page_count); + + if (!virtual_base) + { + return kstd::failure(make_error_code(kstd::errc::not_enough_memory)); + } + + auto const first_page = page::containing(virtual_base.value()); + auto const first_frame = frame::containing(hw_base); + auto const base_flags = mode == access::read_only ? page_mapper::flags::empty : page_mapper::flags::writable; + auto const flags = + base_flags | page_mapper::flags::uncached | page_mapper::flags::supervisor_only | page_mapper::flags::global; + + auto const first_mapping = memory::map(first_page, first_frame, flags); + + if (!first_mapping) + { + mmio_allocator->release(virtual_base.value()); + return kstd::failure(make_error_code(kstd::errc::not_enough_memory)); + } + + for (auto index = 1uz; index < page_count; ++index) + { + auto const page = first_page + index; + auto const frame = first_frame + index; + auto const mapping = memory::map(page, frame, flags); + + if (!mapping) + { + unmap_range(first_page, index); + mmio_allocator->release(virtual_base.value()); + return kstd::failure(make_error_code(kstd::errc::not_enough_memory)); + } + } + + auto const linear_base = linear_address{virtual_base.value()}; + auto const data_base = first_mapping + in_page_offset; + + return kstd::success(mmio_window{linear_base, data_base, size, mode}); + } + + mmio_window::mmio_window(mmio_window && other) noexcept + : m_mapping_base(std::exchange(other.m_mapping_base, linear_address{})) + , m_data_base(std::exchange(other.m_data_base, nullptr)) + , m_data_size(std::exchange(other.m_data_size, 0_B)) + , m_mode(std::exchange(other.m_mode, access::read_only)) + {} + + auto mmio_window::operator=(mmio_window && other) noexcept -> mmio_window & + { + if (this != &other) + { + release(); + m_mapping_base = std::exchange(other.m_mapping_base, linear_address{}); + m_data_base = std::exchange(other.m_data_base, nullptr); + m_data_size = std::exchange(other.m_data_size, 0_B); + m_mode = std::exchange(other.m_mode, access::read_only); + } + return *this; + } + + mmio_window::~mmio_window() + { + release(); + } + + mmio_window::mmio_window(linear_address mapping_base, kstd::observer_ptr data_base, kstd::bytes size, + access mode) + : m_mapping_base(mapping_base) + , m_data_base(data_base) + , m_data_size(size) + , m_mode(mode) + {} + + auto mmio_window::assert_valid_access(kstd::bytes offset, kstd::bytes size) const -> void + { + if (!m_data_base) + { + system::panic("[OS:MEM] MMIO window has been moved from!"); + } + + if (size > m_data_size || offset > m_data_size - size) + { + system::panic("[OS:MEM] Tried to access {} bytes at offset {} in MMIO window of size {}", size, offset, + m_data_size); + } + + auto const address = m_data_base.get() + offset.value; + if (reinterpret_cast(address) % size.value) + { + system::panic("[OS:MEM] Unaligned {} access in MMIO operation at {:#018x}!", size, address); + } + } + + auto mmio_window::assert_writable() const -> void + { + if (m_mode != access::writable) + { + system::panic("[OS:MEM] Attempted to write to a read-only MMIO window!"); + } + } + + auto mmio_window::release() -> void + { + if (m_data_base) + { + auto const first_page = page::containing(m_mapping_base); + auto const in_page_offset = reinterpret_cast(m_data_base.get()) % page::size.value; + auto const page_count = determine_page_count(in_page_offset, m_data_size); + unmap_range(first_page, page_count); + mmio_allocator->release(m_mapping_base); + } + } + + auto init_mmio(linear_address base, std::size_t page_count) -> void + { + mmio_allocator.emplace(base, page_count); + } + +} // namespace kapi::memory + +namespace kapi::test_support::memory +{ + + auto deinit_mmio() -> void + { + kapi::memory::mmio_allocator.reset(); + } + +} // namespace kapi::test_support::memory diff --git a/kernel/kapi/memory/mmio.tests.cpp b/kernel/kapi/memory/mmio.tests.cpp new file mode 100644 index 00000000..e9aeacdb --- /dev/null +++ b/kernel/kapi/memory/mmio.tests.cpp @@ -0,0 +1,392 @@ +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +// NOLINTBEGIN(readability-magic-numbers) + +namespace +{ + using kapi::memory::mmio_window; + using access = kapi::memory::mmio_window::access; + using halt = kernel::tests::cpu::halt; + + //! A hardware range to map + struct window_layout + { + std::uint64_t hw_base; + std::uint64_t hw_size; + }; + + //! The first and last offsets (inclusive) at which an access of a given width is both in bounds and naturally aligned + //! with respect to the *hardware* address. + struct slots + { + std::uint64_t first; + std::uint64_t last; + }; + + constexpr auto slots_for(window_layout layout, std::uint64_t width) -> slots + { + auto const first = (width - layout.hw_base % width) % width; + auto const latest_start = layout.hw_size - width; + auto const last = latest_start - (layout.hw_base + latest_start) % width; + return {first, last}; + } + + //! Map a window that needs every page of the MMIO pool. + auto map_pool_sized() -> kstd::result + { + return mmio_window::map(kapi::memory::physical_address{}, kernel::tests::memory::mmio_pool_size, access::read_only); + } +} // namespace + +TEMPLATE_TEST_CASE("Scenario: MMIO window accesses", "[memory][mmio]", std::uint8_t, std::uint16_t, std::uint32_t, + std::uint64_t) +{ + constexpr auto width = sizeof(TestType); + + auto const layout = GENERATE(values({ + {0x1000, 0x100}, // aligned hw base == true && hw size == sub-page && boundary crossed == false + {0x1000, 0x1000}, // aligned hw base == true && hw size == one page && boundary crossed == false + {0x1000, 0x2000}, // aligned hw base == true && hw size == multi-page && boundary crossed == false + {0x1000, 0x102}, // aligned hw base == true && hw size == sub-page && boundary crossed == true + {0x1001, 0x100}, // aligned hw base == false && hw size == sub-page && boundary crossed == false + {0x1001, 0x1000}, // aligned hw base == false && hw size == one page && boundary crossed == false + {0x1ff8, 0x10}, // aligned hw base == false && hw size == sub-page && boundary crossed == true + })); + + INFO("hw_base = " << layout.hw_base << ", hw_size = " << layout.hw_size); + + auto const slot = slots_for(layout, width); + auto const hw_base = kapi::memory::physical_address{layout.hw_base}; + auto const hw_size = kstd::bytes{layout.hw_size}; + + GIVEN("a writable window") + { + auto window = mmio_window::map(hw_base, hw_size, access::writable); + REQUIRE(window); + + WHEN("writing to the first and last valid slot") + { + // The last slot touches the last byte of the range, which for page crossing layouts lives on the second page. + auto const first_value = static_cast(0x1122'3344'5566'7788ULL); + auto const last_value = static_cast(0x99aa'bbcc'ddee'ff00ULL); + + window->write(kstd::bytes{slot.first}, first_value); + window->write(kstd::bytes{slot.last}, last_value); + + THEN("the values can be read back correctly") + { + CHECK(window->read(kstd::bytes{slot.first}) == first_value); + CHECK(window->read(kstd::bytes{slot.last}) == last_value); + } + } + + WHEN("writing out of bounds but otherwise aligned") + { + // slot.last + width is aligned, and either straddles or lies past the end, so only the bounds check can fire. + CHECK_THROWS_AS(window->write(kstd::bytes{slot.last + width}, TestType{}), halt); + } + + WHEN("writing misaligned but otherwise in bounds") + { + if constexpr (width > 1) + { + CHECK_THROWS_AS(window->write(kstd::bytes{slot.first + 1}, TestType{}), halt); + } + } + } + + GIVEN("a read-only window") + { + auto window = mmio_window::map(hw_base, hw_size, access::read_only); + REQUIRE(window); + + THEN("reads at the first and last valid slot are allowed") + { + CHECK_NOTHROW(window->read(kstd::bytes{slot.first})); + CHECK_NOTHROW(window->read(kstd::bytes{slot.last})); + } + + THEN("aligned, in bounds write is rejected") + { + CHECK_THROWS_AS(window->write(kstd::bytes{slot.first}, TestType{}), halt); + } + + THEN("reading an aligned but out of bounds offset is rejected") + { + CHECK_THROWS_AS(window->read(kstd::bytes{slot.last + width}), halt); + } + + THEN("in bounds but misaligned read is rejected") + { + if constexpr (width > 1) + { + CHECK_THROWS_AS(window->read(kstd::bytes{slot.first + 1}), halt); + } + } + + THEN("reading at exactly the window size is rejected") + { + CHECK_THROWS_AS(window->read(hw_size), halt); + } + + THEN("reading offsets close to the largest representable value is rejected") + { + constexpr auto max_offset = std::numeric_limits::max(); + CHECK_THROWS_AS(window->read(kstd::bytes{max_offset}), halt); + CHECK_THROWS_AS(window->read(kstd::bytes{max_offset - width + 1}), halt); + } + } +} + +SCENARIO("MMIO windows over overlapping hardware ranges", "[memory][mmio]") +{ + GIVEN("a writable window") + { + auto second = mmio_window::map(kapi::memory::physical_address{0x1800}, kstd::bytes{0x1000}, access::writable); + REQUIRE(second); + + AND_GIVEN("another writable window whose hardware range overlaps the first") + { + auto first = mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{0x1000}, access::writable); + REQUIRE(first); + + WHEN("a value is written through one window") + { + // Hardware address 0x1800 is offset 0x800 in the first window and offset 0 in the second. + first->write(kstd::bytes{0x800}, 0xcafe'f00d); + + THEN("the value is visible through the other window") + { + CHECK(second->read(kstd::bytes{0}) == 0xcafe'f00d); + } + } + } + + AND_GIVEN("another window that is destroyed again") + { + { + auto first = mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{0x1000}, access::writable); + REQUIRE(first); + first->write(kstd::bytes{0x800}, 0xcafe'f00d); + } + + THEN("the remaining window is still usable and observes the value") + { + CHECK(second->read(kstd::bytes{0}) == 0xcafe'f00d); + } + } + } +} + +SCENARIO("MMIO window creation errors", "[memory][mmio]") +{ + GIVEN("an initialized MMIO subsystem") + { + WHEN("mapping a window of size zero") + { + auto window = mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{0}, access::read_only); + + THEN("the mapping fails with invalid_argument") + { + REQUIRE(!window); + CHECK(window.error() == kstd::errc::invalid_argument); + } + } + + WHEN("mapping a window that would wrap around the end of the physical address space") + { + auto window = mmio_window::map(kapi::memory::physical_address{std::numeric_limits::max()}, + kstd::bytes{2}, access::read_only); + + THEN("the mapping fails with invalid_argument") + { + REQUIRE(!window); + CHECK(window.error() == kstd::errc::invalid_argument); + } + } + + WHEN("mapping a window that needs the whole MMIO pool") + { + auto window = map_pool_sized(); + + THEN("the mapping succeeds") + { + REQUIRE(window); + } + + AND_WHEN("mapping another window while the pool is exhausted") + { + REQUIRE(window); + auto other = mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{1}, access::read_only); + + THEN("the mapping fails with not_enough_memory") + { + REQUIRE(!other); + CHECK(other.error() == kstd::errc::not_enough_memory); + } + } + } + + WHEN("the page mapper rejects the first page of a window") + { + auto failed = mmio_window::map(kapi::memory::physical_address{kernel::tests::memory::mmio_size.value}, + kstd::bytes{0x100}, access::read_only); + + THEN("the mapping fails") + { + REQUIRE(!failed); + } + + THEN("the reserved linear range has been given back") + { + auto window = map_pool_sized(); + CHECK(window); + } + } + + WHEN("the page mapper rejects the second page of a window") + { + auto const last_page = kernel::tests::memory::mmio_size - kapi::memory::page::size; + auto failed = + mmio_window::map(kapi::memory::physical_address{last_page.value}, kstd::bytes{0x2000}, access::read_only); + + THEN("the mapping fails") + { + REQUIRE(!failed); + } + + THEN("everything acquired for it has been given back") + { + auto window = map_pool_sized(); + CHECK(window); + } + } + } +} + +SCENARIO("MMIO window lifetime", "[memory][mmio]") +{ + GIVEN("a window of the entire MMIO pool that is destroyed again") + { + { + auto window = map_pool_sized(); + REQUIRE(window); + } + + THEN("the entire pool can be mapped again") + { + auto window = map_pool_sized(); + CHECK(window); + } + } + + GIVEN("an unaligned window that spans two pages and is destroyed again") + { + { + auto window = mmio_window::map(kapi::memory::physical_address{0x1001}, kstd::bytes{0x1000}, access::read_only); + REQUIRE(window); + } + + THEN("the entire pool can be mapped again") + { + auto window = map_pool_sized(); + CHECK(window); + } + } + + GIVEN("a writable window") + { + auto original = mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{0x100}, access::writable); + REQUIRE(original); + original->write(kstd::bytes{0}, 0x1234'5678); + + WHEN("it is move-constructed into another window") + { + auto moved = std::move(original.value()); + + THEN("the new window refers to the same hardware range") + { + CHECK(moved.read(kstd::bytes{0}) == 0x1234'5678); + } + + THEN("the moved-from window rejects all accesses") + { + CHECK_THROWS_AS(original->read(kstd::bytes{0}), halt); + CHECK_THROWS_AS(original->write(kstd::bytes{0}, 0), halt); + } + } + + WHEN("it is move-assigned over another window") + { + auto target = mmio_window::map(kapi::memory::physical_address{0x2000}, kstd::bytes{0x100}, access::writable); + REQUIRE(target); + + target.value() = std::move(original.value()); + + THEN("the target refers to the hardware range of the source") + { + CHECK(target->read(kstd::bytes{0}) == 0x1234'5678); + } + + THEN("the moved-from window rejects all accesses") + { + CHECK_THROWS_AS(original->read(kstd::bytes{0}), halt); + } + + THEN("the resources previously held by the target have been released") + { + auto const almost_everything = kernel::tests::memory::mmio_pool_size - kapi::memory::page::size; + auto big = mmio_window::map(kapi::memory::physical_address{}, almost_everything, access::read_only); + CHECK(big); + } + } + + WHEN("it is move-assigned to itself") + { + auto & reference = original.value(); + reference = std::move(original.value()); + + THEN("it remains usable") + { + CHECK(original->read(kstd::bytes{0}) == 0x1234'5678); + } + } + } +} + +SCENARIO("MMIO windows without an initialized MMIO subsystem", "[memory][mmio]") +{ + GIVEN("an uninitialized MMIO subsystem") + { + kapi::test_support::memory::deinit_mmio(); + + WHEN("mapping a window") + { + THEN("the system panics") + { + CHECK_THROWS_AS(mmio_window::map(kapi::memory::physical_address{0x1000}, kstd::bytes{0x100}, access::read_only), + halt); + } + } + } +} + +// NOLINTEND(readability-magic-numbers) diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index 4bd09306..46ed2c1c 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -3,8 +3,8 @@ #include #include -#include #include +#include #include #include @@ -20,16 +20,15 @@ namespace kernel::devices { std::uint16_t vendor_id{}; std::uint16_t device_id{}; - std::uint16_t volatile command{}; - std::uint16_t volatile status{}; + std::uint16_t command{}; + std::uint16_t status{}; std::uint8_t revision_id{}; std::uint8_t programming_interface{}; std::uint8_t subclass{}; std::uint8_t class_code{}; std::uint8_t cache_line_size{}; std::uint8_t latency_timer{}; - std::uint8_t header_type : 7 {}; - bool multifunction_device : 1 {}; + std::uint8_t header_type{}; std::uint8_t built_in_self_test{}; }; @@ -49,61 +48,46 @@ namespace kernel::devices for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) { auto bus_pages = devices_per_bus * functions_per_device; - auto bus_mmio_region = kapi::memory::allocate_mmio_region(bus_pages); - - if (!bus_mmio_region) - { - kstd::println("[OS:DEV] Failed to allocate MMIO region for bus {}", bus); - continue; - } - auto bus_address = kapi::memory::physical_address{segment_base + (bus << bus_address_shift)}; - auto bus_config = kapi::memory::map_mmio_region(*bus_mmio_region, bus_address); + auto bus_window = kapi::memory::mmio_window::map(bus_address, bus_pages * kapi::memory::page::size, + kapi::memory::mmio_window::access::read_only); - if (!bus_config) + if (!bus_window) { - kstd::println("[OS:DEV] Failed to map MMIO region for bus {}", bus); - kapi::memory::release_mmio_region(*bus_mmio_region); + kstd::println("[OS:DEV] Failed to map MMIO window for bus {}", bus); continue; } - auto has_devices = false; - for (auto device = 0; device < devices_per_bus; ++device) { - auto device_base = *bus_config + (device << device_address_shift); - auto device_config = reinterpret_pointer_cast(device_base); - - if (device_config->vendor_id == invalid_vendor_id) + auto device_vendor_id = bus_window->read( + kstd::bytes((device << device_address_shift) + offsetof(pcie_config_space_header, vendor_id))); + if (device_vendor_id == invalid_vendor_id) { continue; } - has_devices = true; - - auto function_count = (device_config->multifunction_device) ? functions_per_device : 1; + auto device_header_type = bus_window->read( + kstd::bytes((device << device_address_shift) + offsetof(pcie_config_space_header, header_type))); + auto function_count = (device_header_type & 0x80) ? functions_per_device : 1; for (auto function = 0; function < function_count; ++function) { - auto function_base = device_base + (function << function_address_shift); - auto function_config = reinterpret_pointer_cast(function_base); - - auto vendor_id = function_config->vendor_id; - if (vendor_id == invalid_vendor_id) + auto function_vendor_id = bus_window->read( + kstd::bytes((device << device_address_shift) + (function << function_address_shift) + + offsetof(pcie_config_space_header, vendor_id))); + if (function_vendor_id == invalid_vendor_id) { continue; } - auto device_id = function_config->device_id; + auto function_device_id = bus_window->read( + kstd::bytes((device << device_address_shift) + (function << function_address_shift) + + offsetof(pcie_config_space_header, device_id))); kstd::println("[OS:DEV] Detected PCI Express device: {:04x}:{:02x}:{:02x}.{:1} [{:04x}:{:04x}]", - segment.group_number, bus, device, function, vendor_id, device_id); + segment.group_number, bus, device, function, function_vendor_id, function_device_id); } } - - if (!has_devices) - { - kapi::memory::release_mmio_region(*bus_mmio_region); - } } } -- cgit v1.2.3