From 27a58a338ad2f61a063df02488fc497405afc492 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Thu, 12 Nov 2026 22:46:57 +0100 Subject: dev/pcie: implement initial detection --- kernel/CMakeLists.txt | 1 + kernel/kernel/devices/pci_express.cpp | 30 ++++++++++++++++++++++++++++++ kernel/kernel/devices/pci_express.hpp | 14 ++++++++++++++ kernel/kernel/main.cpp | 4 ++++ 4 files changed, 49 insertions(+) create mode 100644 kernel/kernel/devices/pci_express.cpp create mode 100644 kernel/kernel/devices/pci_express.hpp (limited to 'kernel') diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index e105ae62..a8be3850 100644 --- a/kernel/CMakeLists.txt +++ b/kernel/CMakeLists.txt @@ -42,6 +42,7 @@ target_sources("kernel_lib" PRIVATE # Device Subsystem "kernel/devices/block_device_utils.cpp" "kernel/devices/init.cpp" + "kernel/devices/pci_express.cpp" "kernel/devices/pseudo.cpp" "kernel/devices/storage.cpp" diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp new file mode 100644 index 00000000..2fcb17b5 --- /dev/null +++ b/kernel/kernel/devices/pci_express.cpp @@ -0,0 +1,30 @@ +#include + +#include + +#include + +namespace kernel::devices +{ + + auto init_pci_express_devices() -> void + { + auto segments = kapi::devices::get_pci_express_segment_descriptors(); + + if (segments.empty()) + { + return; + } + + kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", segments.size()); + for (auto & segment : segments) + { + kstd::println("[OS:DEV] PCI Express segment: \n" + "\tECAM base address = {:#018x}\n" + "\tFirst bus = {:#04x}\n" + "\tLast bus = {:#04x}", + segment.base_address, segment.first_bus, segment.last_bus); + } + } + +} // namespace kernel::devices \ No newline at end of file diff --git a/kernel/kernel/devices/pci_express.hpp b/kernel/kernel/devices/pci_express.hpp new file mode 100644 index 00000000..596791b1 --- /dev/null +++ b/kernel/kernel/devices/pci_express.hpp @@ -0,0 +1,14 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP + +namespace kernel::devices +{ + + //! Initialize all PCI Express devices in the system. + //! + //! This function scans and initializes all PCI Express devices present in the system. + auto init_pci_express_devices() -> void; + +} // namespace kernel::devices + +#endif \ No newline at end of file diff --git a/kernel/kernel/main.cpp b/kernel/kernel/main.cpp index bbbd46c0..47db0537 100644 --- a/kernel/kernel/main.cpp +++ b/kernel/kernel/main.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -296,6 +297,9 @@ auto main() -> int kapi::interrupts::enabled(true); kstd::println("[OS] Interrupts enabled."); + kernel::devices::init_pci_express_devices(); + kstd::println("[OS] PCI Express devices initialized."); + auto modules_bus = kernel::devices::storage::init(); kstd::println("[OS] Storage subsystem initialized."); -- cgit v1.2.3 From 1cd8cd46eb330319d3c615601358a4406ce89de8 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Thu, 12 Nov 2026 23:57:50 +0100 Subject: dev/pcie: implement basic enumeration algorithm --- kernel/kernel/devices/pci_express.cpp | 68 ++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 5 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index 2fcb17b5..a4bfb8c0 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -1,12 +1,74 @@ #include #include +#include +#include #include +#include + +#include +#include namespace kernel::devices { + namespace + { + constexpr auto static invalid_vendor_id = 0xffff; + + constexpr auto static devices_per_bus = 32; + constexpr auto static functions_per_device = 8; + + constexpr auto static bus_address_shift = 20; + constexpr auto static device_address_shift = 15; + constexpr auto static function_address_shift = 12; + } // namespace + + auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void + { + auto segment_base = kapi::memory::physical_address{segment.base_address}; + auto segment_bus_count = segment.last_bus - segment.first_bus + 1; + auto segment_mmio_pages = segment_bus_count * devices_per_bus * functions_per_device; + auto segment_config_region = kapi::memory::allocate_mmio_region(segment_mmio_pages); + auto segment_config_space = kapi::memory::map_mmio_region(segment_config_region, segment_base); + + kstd::println("[OS:DEV] Enumerating PCI Express segment [{:#018x} - {:#018x}]", segment_config_region.first.raw(), + (segment_config_region.first + segment_mmio_pages * kapi::memory::page_size).raw()); + + for (auto bus = static_cast(segment.first_bus); bus <= segment.last_bus; ++bus) + { + auto bus_base = segment_config_space + (bus << bus_address_shift); + + for (auto device = 0; device < devices_per_bus; ++device) + { + auto device_base = bus_base + (device << device_address_shift); + auto device_config = reinterpret_pointer_cast(device_base); + + if (*device_config == invalid_vendor_id) + { + continue; + } + + for (auto function = 0; function < functions_per_device; ++function) + { + auto function_base = device_base + (function << function_address_shift); + auto function_config = reinterpret_pointer_cast(function_base); + + auto vendor_id = *function_config; + if (vendor_id == invalid_vendor_id) + { + continue; + } + + auto device_id = *(function_config + 1); + kstd::println("[OS:DEV] Detected PCI Express device: {:02x}:{:02x}.{:1} [{:04x}:{:04x}]", bus, device, + function, vendor_id, device_id); + } + } + } + } + auto init_pci_express_devices() -> void { auto segments = kapi::devices::get_pci_express_segment_descriptors(); @@ -19,11 +81,7 @@ namespace kernel::devices kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", segments.size()); for (auto & segment : segments) { - kstd::println("[OS:DEV] PCI Express segment: \n" - "\tECAM base address = {:#018x}\n" - "\tFirst bus = {:#04x}\n" - "\tLast bus = {:#04x}", - segment.base_address, segment.first_bus, segment.last_bus); + enumerate(segment); } } -- cgit v1.2.3 From 625b3e37fde23ecd3106281af07991c46931aa7c Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 06:56:24 +0100 Subject: tests: fix test build --- kernel/kernel/test_support/kapi/devices.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 kernel/kernel/test_support/kapi/devices.cpp (limited to 'kernel') diff --git a/kernel/kernel/test_support/kapi/devices.cpp b/kernel/kernel/test_support/kapi/devices.cpp new file mode 100644 index 00000000..bd590796 --- /dev/null +++ b/kernel/kernel/test_support/kapi/devices.cpp @@ -0,0 +1,13 @@ +#include + +#include + +namespace kapi::devices +{ + + auto get_pci_express_segment_descriptors() -> kstd::vector + { + return {}; + } + +} // namespace kapi::devices \ No newline at end of file -- cgit v1.2.3 From c0e5d076cfdeddde0a83197e2ebcee2df17934f8 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 07:09:06 +0100 Subject: dev/pcie: extend segment descriptor --- kernel/kernel/devices/pci_express.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index a4bfb8c0..3522f7df 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -28,15 +28,14 @@ namespace kernel::devices auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void { auto segment_base = kapi::memory::physical_address{segment.base_address}; - auto segment_bus_count = segment.last_bus - segment.first_bus + 1; - auto segment_mmio_pages = segment_bus_count * devices_per_bus * functions_per_device; + auto segment_mmio_pages = segment.bus_count * devices_per_bus * functions_per_device; auto segment_config_region = kapi::memory::allocate_mmio_region(segment_mmio_pages); auto segment_config_space = kapi::memory::map_mmio_region(segment_config_region, segment_base); kstd::println("[OS:DEV] Enumerating PCI Express segment [{:#018x} - {:#018x}]", segment_config_region.first.raw(), (segment_config_region.first + segment_mmio_pages * kapi::memory::page_size).raw()); - for (auto bus = static_cast(segment.first_bus); bus <= segment.last_bus; ++bus) + for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) { auto bus_base = segment_config_space + (bus << bus_address_shift); @@ -62,8 +61,8 @@ namespace kernel::devices } auto device_id = *(function_config + 1); - kstd::println("[OS:DEV] Detected PCI Express device: {:02x}:{:02x}.{:1} [{:04x}:{:04x}]", bus, device, - function, vendor_id, 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); } } } -- cgit v1.2.3 From 32a0bc18a741f5599e6447add4cd69a6e25a31be Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 08:07:23 +0100 Subject: dev/pcie: introduce config space type --- kernel/kernel/devices/pci_express.cpp | 18 ++++++++++-------- kernel/kernel/devices/pci_express.hpp | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index 3522f7df..4557f523 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -8,7 +8,6 @@ #include #include -#include namespace kernel::devices { @@ -37,30 +36,33 @@ namespace kernel::devices for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) { - auto bus_base = segment_config_space + (bus << bus_address_shift); + auto relative_bus_number = bus - segment.first_bus; + auto bus_base = segment_config_space + (relative_bus_number << bus_address_shift); for (auto device = 0; device < devices_per_bus; ++device) { auto device_base = bus_base + (device << device_address_shift); - auto device_config = reinterpret_pointer_cast(device_base); + auto device_config = reinterpret_pointer_cast(device_base); - if (*device_config == invalid_vendor_id) + if (device_config->vendor_id == invalid_vendor_id) { continue; } - for (auto function = 0; function < functions_per_device; ++function) + auto function_count = (device_config->multifunction_device) ? 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 function_config = reinterpret_pointer_cast(function_base); - auto vendor_id = *function_config; + auto vendor_id = function_config->vendor_id; if (vendor_id == invalid_vendor_id) { continue; } - auto device_id = *(function_config + 1); + auto device_id = function_config->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); } diff --git a/kernel/kernel/devices/pci_express.hpp b/kernel/kernel/devices/pci_express.hpp index 596791b1..6b687c38 100644 --- a/kernel/kernel/devices/pci_express.hpp +++ b/kernel/kernel/devices/pci_express.hpp @@ -1,9 +1,27 @@ #ifndef TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP #define TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP +#include namespace kernel::devices { + struct pcie_config_space_header + { + std::uint16_t vendor_id{}; + std::uint16_t device_id{}; + std::uint16_t volatile command{}; + std::uint16_t volatile 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 built_in_self_test{}; + }; + //! Initialize all PCI Express devices in the system. //! //! This function scans and initializes all PCI Express devices present in the system. -- cgit v1.2.3 From 60ba364ec3c458b6bcf3d048781c8dd88937cd0e Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 11:40:07 +0100 Subject: kapi/memory: fix page unmap logic Previously, the page mapper was expected to automatically free all frames that had become unused. However, this only works if all mappings refer to plain memory frames. In the case of MMIO frames, the mapper would still try to release the frame via the global frame allocator, which is incorrect, leading to undefined behavior in the worst case. This problem was discovered during work the PCI/PCIe subsystem, since we want to unmap any unused buses during enumeration. --- kernel/kapi/memory.cpp | 8 ++++---- kernel/kernel/memory/bitmap_allocator.cpp | 9 +++++++++ kernel/kernel/test_support/page_mapper.cpp | 18 +++++++++++------- kernel/kernel/test_support/page_mapper.hpp | 5 +++-- 4 files changed, 27 insertions(+), 13 deletions(-) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index 666910ba..c1b48ea3 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -51,14 +51,14 @@ namespace kapi::memory system::panic("[OS:MEM] Tried to map a page without an active mapper."); } - auto unmap(page) -> void override + 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 -> bool override + auto try_unmap(page) noexcept -> std::optional override { - return false; + return std::nullopt; } }; @@ -109,7 +109,7 @@ namespace kapi::memory return active_page_mapper->map(page, frame, flags); } - auto unmap(page page) -> void + auto unmap(page page) -> frame { return active_page_mapper->unmap(page); } diff --git a/kernel/kernel/memory/bitmap_allocator.cpp b/kernel/kernel/memory/bitmap_allocator.cpp index a4e6a8ca..5bee3a82 100644 --- a/kernel/kernel/memory/bitmap_allocator.cpp +++ b/kernel/kernel/memory/bitmap_allocator.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -128,6 +129,14 @@ namespace kernel::memory constexpr auto bits_per_word = 64uz; auto entry_entry = index / bits_per_word; auto entry_offset = index % bits_per_word; + + if (entry_entry >= m_bitmap.size()) + { + kapi::system::panic( + "[OS:MEM] Tried to release frame '{}', which is outside the bounds of the bitmap range '[0-{}]!", index, + m_bitmap.size() * 64uz - 1); + } + m_bitmap[entry_entry] &= ~(1uz << entry_offset); } diff --git a/kernel/kernel/test_support/page_mapper.cpp b/kernel/kernel/test_support/page_mapper.cpp index 808e0810..dd11c8b3 100644 --- a/kernel/kernel/test_support/page_mapper.cpp +++ b/kernel/kernel/test_support/page_mapper.cpp @@ -7,6 +7,7 @@ #include #include +#include #include namespace kernel::tests @@ -48,24 +49,27 @@ namespace kernel::tests return nullptr; } - auto page_mapper::unmap(kapi::memory::page page) -> void + auto page_mapper::unmap(kapi::memory::page page) -> kapi::memory::frame { - if (!try_unmap(page)) + auto frame = try_unmap(page); + if (!frame) { auto error = std::format("Page {} was never mapped!", page.number()); throw std::invalid_argument{error}; } + return *frame; } - auto page_mapper::try_unmap(kapi::memory::page page) noexcept -> bool + auto page_mapper::try_unmap(kapi::memory::page page) noexcept -> std::optional { - if (page_mappings.contains(page.number())) + if (auto it = page_mappings.find(page.number()); it != page_mappings.end()) { - page_mappings.erase(page.number()); - return true; + auto frame = it->second; + page_mappings.erase(it); + return frame; } - return false; + return {}; } } // namespace kernel::tests \ No newline at end of file diff --git a/kernel/kernel/test_support/page_mapper.hpp b/kernel/kernel/test_support/page_mapper.hpp index c38eeaf3..df0bb154 100644 --- a/kernel/kernel/test_support/page_mapper.hpp +++ b/kernel/kernel/test_support/page_mapper.hpp @@ -10,6 +10,7 @@ #include #include +#include #include namespace kernel::tests @@ -33,10 +34,10 @@ namespace kernel::tests //! @copydoc kapi::memory::page_mapper::unmap //! //! @throws std::invalid_argument if the page has not been mapped. - auto unmap(kapi::memory::page page) -> void override; + auto unmap(kapi::memory::page page) -> kapi::memory::frame override; //! @copydoc kapi::memory::page_mapper::try_unmap - auto try_unmap(kapi::memory::page page) noexcept -> bool override; + auto try_unmap(kapi::memory::page page) noexcept -> std::optional override; //! The simulated memory. kernel::tests::simulated_memory memory; -- cgit v1.2.3 From e5c8bf2146bf17fe051f86708e7fd7f2b366b0ed Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 11:48:29 +0100 Subject: kapi/memory: unmap MMIO regions on release --- kernel/kapi/memory.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index c1b48ea3..cdc01512 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -182,6 +182,16 @@ namespace kapi::memory auto release_mmio_region(mmio_region region) -> void { + for (auto page_index = 0uz; page_index < region.second; ++page_index) + { + auto page_address = region.first + page_index * kapi::memory::page_size; + auto page = kapi::memory::page::containing(page_address); + + // 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 = kapi::memory::unmap(page); + } mmio_allocator->release(region.first); } -- cgit v1.2.3 From 0bbeeb2341f43ec533ce485cb3c62a0dbffd4864 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 11:49:31 +0100 Subject: dev/pcie: release absent MMIO regions during enum --- kernel/kernel/devices/pci_express.cpp | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index 4557f523..3fae618a 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -27,21 +27,20 @@ namespace kernel::devices auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void { auto segment_base = kapi::memory::physical_address{segment.base_address}; - auto segment_mmio_pages = segment.bus_count * devices_per_bus * functions_per_device; - auto segment_config_region = kapi::memory::allocate_mmio_region(segment_mmio_pages); - auto segment_config_space = kapi::memory::map_mmio_region(segment_config_region, segment_base); - - kstd::println("[OS:DEV] Enumerating PCI Express segment [{:#018x} - {:#018x}]", segment_config_region.first.raw(), - (segment_config_region.first + segment_mmio_pages * kapi::memory::page_size).raw()); for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) { - auto relative_bus_number = bus - segment.first_bus; - auto bus_base = segment_config_space + (relative_bus_number << bus_address_shift); + auto bus_pages = devices_per_bus * functions_per_device; + auto bus_mmio_region = kapi::memory::allocate_mmio_region(bus_pages); + + 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 has_devices = false; for (auto device = 0; device < devices_per_bus; ++device) { - auto device_base = bus_base + (device << device_address_shift); + 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) @@ -49,6 +48,8 @@ namespace kernel::devices continue; } + has_devices = true; + auto function_count = (device_config->multifunction_device) ? functions_per_device : 1; for (auto function = 0; function < function_count; ++function) @@ -67,6 +68,11 @@ namespace kernel::devices segment.group_number, bus, device, function, vendor_id, device_id); } } + + if (!has_devices) + { + kapi::memory::release_mmio_region(bus_mmio_region); + } } } -- cgit v1.2.3 From 9f17d8e8aca9742e334777504588a344840593fc Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 13:23:59 +0100 Subject: dev/pcie: hide implementation details --- kernel/kernel/devices/pci_express.cpp | 92 +++++++++++++++++++++-------------- kernel/kernel/devices/pci_express.hpp | 18 ------- 2 files changed, 56 insertions(+), 54 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index 3fae618a..e2c13f08 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -8,12 +8,31 @@ #include #include +#include namespace kernel::devices { namespace { + + struct pcie_config_space_header + { + std::uint16_t vendor_id{}; + std::uint16_t device_id{}; + std::uint16_t volatile command{}; + std::uint16_t volatile 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 built_in_self_test{}; + }; + constexpr auto static invalid_vendor_id = 0xffff; constexpr auto static devices_per_bus = 32; @@ -22,59 +41,60 @@ namespace kernel::devices constexpr auto static bus_address_shift = 20; constexpr auto static device_address_shift = 15; constexpr auto static function_address_shift = 12; - } // namespace - - auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void - { - auto segment_base = kapi::memory::physical_address{segment.base_address}; - for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) + auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void { - auto bus_pages = devices_per_bus * functions_per_device; - auto bus_mmio_region = kapi::memory::allocate_mmio_region(bus_pages); + auto segment_base = kapi::memory::physical_address{segment.base_address}; - 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 has_devices = false; - - for (auto device = 0; device < devices_per_bus; ++device) + for (auto bus = static_cast(segment.first_bus); bus < segment.first_bus + segment.bus_count; ++bus) { - 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) - { - continue; - } + auto bus_pages = devices_per_bus * functions_per_device; + auto bus_mmio_region = kapi::memory::allocate_mmio_region(bus_pages); - has_devices = true; + 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 function_count = (device_config->multifunction_device) ? functions_per_device : 1; + auto has_devices = false; - for (auto function = 0; function < function_count; ++function) + for (auto device = 0; device < devices_per_bus; ++device) { - auto function_base = device_base + (function << function_address_shift); - auto function_config = reinterpret_pointer_cast(function_base); + auto device_base = bus_config + (device << device_address_shift); + auto device_config = reinterpret_pointer_cast(device_base); - auto vendor_id = function_config->vendor_id; - if (vendor_id == invalid_vendor_id) + if (device_config->vendor_id == invalid_vendor_id) { continue; } - auto device_id = function_config->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); + has_devices = true; + + auto function_count = (device_config->multifunction_device) ? 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) + { + continue; + } + + auto device_id = function_config->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); + } } - } - if (!has_devices) - { - kapi::memory::release_mmio_region(bus_mmio_region); + if (!has_devices) + { + kapi::memory::release_mmio_region(bus_mmio_region); + } } } - } + + } // namespace auto init_pci_express_devices() -> void { diff --git a/kernel/kernel/devices/pci_express.hpp b/kernel/kernel/devices/pci_express.hpp index 6b687c38..596791b1 100644 --- a/kernel/kernel/devices/pci_express.hpp +++ b/kernel/kernel/devices/pci_express.hpp @@ -1,27 +1,9 @@ #ifndef TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP #define TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP -#include namespace kernel::devices { - struct pcie_config_space_header - { - std::uint16_t vendor_id{}; - std::uint16_t device_id{}; - std::uint16_t volatile command{}; - std::uint16_t volatile 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 built_in_self_test{}; - }; - //! Initialize all PCI Express devices in the system. //! //! This function scans and initializes all PCI Express devices present in the system. -- cgit v1.2.3 From 9a1f24148e2b61ef1f9d54c0285aba7213b14a0c Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 13 Nov 2026 13:25:30 +0100 Subject: kapi/memory: map MMIO regions more securely --- kernel/kapi/memory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index cdc01512..ee8b45f0 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -167,7 +167,7 @@ namespace kapi::memory auto start_page = page::containing(region.first); auto start_frame = frame::containing(hw_base); - flags |= page_mapper::flags::uncached; + flags |= page_mapper::flags::uncached | page_mapper::flags::supervisor_only | page_mapper::flags::global; auto start = map(start_page, start_frame, flags); -- cgit v1.2.3 From 1071297ee44d5102feb92b7a5d5ceb44e90622b7 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Sat, 14 Nov 2026 17:20:53 +0100 Subject: memory: improve MMIO allocation/mapping robustness --- kernel/kapi/memory.cpp | 79 +++++++++++++++++++++++---------- kernel/kernel/devices/pci_express.cpp | 19 ++++++-- kernel/kernel/memory/mmio_allocator.cpp | 14 +++--- kernel/kernel/memory/mmio_allocator.hpp | 4 +- 4 files changed, 81 insertions(+), 35 deletions(-) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index ee8b45f0..65f9f319 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -7,6 +7,8 @@ #include #include +#include +#include #include #include @@ -66,10 +68,23 @@ namespace kapi::memory constinit bad_page_mapper bad_page_mapper::instance{}; auto constinit allocator = std::optional{}; auto constinit mmio_allocator = std::optional{}; - } // namespace - constinit auto static active_frame_allocator = static_cast(&bad_frame_allocator::instance); - constinit auto static active_page_mapper = static_cast(&bad_page_mapper::instance); + 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 & { @@ -155,43 +170,61 @@ namespace kapi::memory mmio_allocator.emplace(base, page_count); } - auto allocate_mmio_region(std::size_t page_count) -> mmio_region + auto allocate_mmio_region(std::size_t page_count) -> kstd::result { - auto region = mmio_allocator->allocate(page_count); - return {region, page_count}; + 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::observer_ptr + -> kstd::result> { - auto start_page = page::containing(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 start = map(start_page, start_frame, flags); + auto first_mapped_page = map(start_page, start_frame, flags); - std::ranges::for_each(std::views::iota(1uz, region.second), [&](auto index) { - auto page = page::containing(region.first + index * page::size); - auto frame = frame::containing(hw_base + index * page::size); - map(page, 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 start; + return kstd::success(first_mapped_page); } auto release_mmio_region(mmio_region region) -> void { - for (auto page_index = 0uz; page_index < region.second; ++page_index) + if (!mmio_allocator) { - auto page_address = region.first + page_index * kapi::memory::page_size; - auto page = kapi::memory::page::containing(page_address); - - // 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 = kapi::memory::unmap(page); + 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); } diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp index e2c13f08..4bd09306 100644 --- a/kernel/kernel/devices/pci_express.cpp +++ b/kernel/kernel/devices/pci_express.cpp @@ -51,14 +51,27 @@ namespace kernel::devices 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_config = kapi::memory::map_mmio_region(*bus_mmio_region, bus_address); + + if (!bus_config) + { + kstd::println("[OS:DEV] Failed to map MMIO region for bus {}", bus); + kapi::memory::release_mmio_region(*bus_mmio_region); + 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_base = *bus_config + (device << device_address_shift); auto device_config = reinterpret_pointer_cast(device_base); if (device_config->vendor_id == invalid_vendor_id) @@ -89,7 +102,7 @@ namespace kernel::devices if (!has_devices) { - kapi::memory::release_mmio_region(bus_mmio_region); + kapi::memory::release_mmio_region(*bus_mmio_region); } } } diff --git a/kernel/kernel/memory/mmio_allocator.cpp b/kernel/kernel/memory/mmio_allocator.cpp index 17f436f8..49cb31e9 100644 --- a/kernel/kernel/memory/mmio_allocator.cpp +++ b/kernel/kernel/memory/mmio_allocator.cpp @@ -1,9 +1,10 @@ #include #include -#include #include +#include +#include #include #include @@ -16,11 +17,11 @@ namespace kernel::memory : m_head{make_node(base, pages, nullptr, nullptr, true)} {} - auto mmio_allocator::allocate(std::size_t count) -> kapi::memory::linear_address + auto mmio_allocator::allocate(std::size_t count) -> kstd::result { - if (count == 0 || !m_head) + if (count == 0) { - return {}; + return kstd::failure(make_error_code(kstd::errc::invalid_argument)); } auto current = m_head; @@ -42,13 +43,12 @@ namespace kernel::memory } current->is_free = false; - return current->base; + return kstd::success(current->base); } current = current->next; } - kapi::system::panic("[OS:MEM] MMIO alloctor out of memory!"); - return {}; + return kstd::failure(make_error_code(kstd::errc::not_enough_memory)); } auto mmio_allocator::release(kapi::memory::linear_address base) -> void diff --git a/kernel/kernel/memory/mmio_allocator.hpp b/kernel/kernel/memory/mmio_allocator.hpp index 862188fa..268ca40b 100644 --- a/kernel/kernel/memory/mmio_allocator.hpp +++ b/kernel/kernel/memory/mmio_allocator.hpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include @@ -15,7 +15,7 @@ namespace kernel::memory { mmio_allocator(kapi::memory::linear_address base, std::size_t pages); - [[nodiscard]] auto allocate(std::size_t page_count) -> kapi::memory::linear_address; + [[nodiscard]] auto allocate(std::size_t page_count) -> kstd::result; auto release(kapi::memory::linear_address base) -> void; private: -- cgit v1.2.3 From dc5edf2193c14b17939ba9afe9eef4a907da053f Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Sat, 14 Nov 2026 17:54:57 +0100 Subject: memory: harden MMIO mappings and update docs. --- kernel/kapi/memory.cpp | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index 65f9f319..83b32f0d 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -183,6 +183,13 @@ namespace kapi::memory 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); -- cgit v1.2.3 From 9a17b94c3cc3397152092da7f40a17682440fd78 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Sat, 14 Nov 2026 19:03:39 +0100 Subject: kapi/memory: carry hw_base offset forward in mapping --- kernel/kapi/memory.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'kernel') diff --git a/kernel/kapi/memory.cpp b/kernel/kapi/memory.cpp index 83b32f0d..12e9e23f 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -194,6 +194,7 @@ namespace kapi::memory 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; @@ -217,7 +218,7 @@ namespace kapi::memory } } - return kstd::success(first_mapped_page); + return kstd::success(first_mapped_page + frame_offset); } auto release_mmio_region(mmio_region region) -> void -- cgit v1.2.3 From 9d14461a5fbc4493bf6c28456490194febdecb6b Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Sun, 15 Nov 2026 11:09:51 +0100 Subject: tests: add support for MMIO mapping --- kernel/kernel/test_support/kapi/memory.cpp | 14 +-- kernel/kernel/test_support/memory.hpp | 24 ++++ kernel/kernel/test_support/page_mapper.cpp | 80 ++++++++----- kernel/kernel/test_support/page_mapper.hpp | 24 +++- kernel/kernel/test_support/page_mapper.tests.cpp | 125 +++++++++++++++++++++ kernel/kernel/test_support/simulated_memory.cpp | 5 +- kernel/kernel/test_support/simulated_memory.hpp | 4 +- .../kernel/test_support/state_reset_listener.cpp | 1 + 8 files changed, 233 insertions(+), 44 deletions(-) create mode 100644 kernel/kernel/test_support/page_mapper.tests.cpp (limited to 'kernel') diff --git a/kernel/kernel/test_support/kapi/memory.cpp b/kernel/kernel/test_support/kapi/memory.cpp index e554145d..78b24f43 100644 --- a/kernel/kernel/test_support/kapi/memory.cpp +++ b/kernel/kernel/test_support/kapi/memory.cpp @@ -1,21 +1,16 @@ #include #include +#include #include #include -#include - #include namespace { - //! The size of the simulated RAM. - constexpr auto physical_size = kstd::MiB(32u); - constexpr auto virtual_size = kstd::GiB(1u); - - constexpr auto number_of_frames = physical_size / kapi::memory::frame::size; + constexpr auto number_of_frames = kernel::tests::memory::physical_size / kapi::memory::frame::size; auto constinit bump_allocator = std::optional{}; auto constinit test_mapper = std::optional{}; @@ -38,12 +33,13 @@ namespace kapi::memory auto init() -> void { bump_allocator.emplace(); - test_mapper.emplace(physical_size, virtual_size); + test_mapper.emplace(kernel::tests::memory::physical_size, kernel::tests::memory::virtual_size, + kernel::tests::memory::mmio_size, kernel::tests::memory::mmio_virtual_size); old_allocator = set_frame_allocator(*bump_allocator); old_mapper = set_page_mapper(*test_mapper); - init_pmm(physical_size / frame::size, handoff_to_kernel_pmm); + init_pmm(kernel::tests::memory::physical_size / frame::size, handoff_to_kernel_pmm); } } // namespace kapi::memory diff --git a/kernel/kernel/test_support/memory.hpp b/kernel/kernel/test_support/memory.hpp index 21030a41..8565a53a 100644 --- a/kernel/kernel/test_support/memory.hpp +++ b/kernel/kernel/test_support/memory.hpp @@ -3,9 +3,33 @@ #include +#include + namespace kernel::tests::memory { + //! The physical size of the simulated RAM. + constexpr auto physical_size = kstd::MiB(32u); + + //! The virtual size in the test environment corresponding to the simulated RAM. + constexpr auto virtual_size = kstd::GiB(1u); + + //! The physical size of the simulated MMIO region. + //! + //! Any hardware addresses used in tests must lie within the region of [0, mmio_size) + constexpr auto mmio_size = kstd::MiB(4u); + + //! The size of the virtual address pool managed by the MMIO allocator. + //! + //! Any virtual addresses used for MMIO mappings must lie within the region of [kapi::memory::mmio_base, + //! kapi::memory::mmio_base + mmio_pool_size) + constexpr auto mmio_pool_size = kstd::MiB(4u); + + //! The virtual size in the test environment corresponding to the MMIO region. + constexpr auto mmio_virtual_size = mmio_pool_size; + + static_assert(mmio_virtual_size >= mmio_pool_size); + //! Deinitialize the memory subsystem. auto deinit() -> void; diff --git a/kernel/kernel/test_support/page_mapper.cpp b/kernel/kernel/test_support/page_mapper.cpp index dd11c8b3..fea2e4f1 100644 --- a/kernel/kernel/test_support/page_mapper.cpp +++ b/kernel/kernel/test_support/page_mapper.cpp @@ -13,37 +13,18 @@ namespace kernel::tests { - page_mapper::page_mapper(kstd::bytes physical_size, kstd::bytes virtual_size) - : memory{physical_size, virtual_size} + page_mapper::page_mapper(kstd::bytes ram_size, kstd::bytes ram_virtual_size, kstd::bytes mmio_size, + kstd::bytes mmio_virtual_size) + : memory{"Simulated Main Memory", ram_size, ram_virtual_size} + , mmio{"Simulated MMIO Region", mmio_size, mmio_virtual_size} {} auto page_mapper::map(kapi::memory::page page, kapi::memory::frame frame, flags) -> kstd::observer_ptr { - auto result = page_mappings.insert({page.number(), frame}); - if (!result.second) + if (auto mapped = do_map(page, frame)) { - auto error = std::format("Page {} was already mapped!", page.number()); - throw std::invalid_argument{error}; - } - - auto page_address = page.start_address(); - auto virtual_base = memory.virtual_base(); - auto virtual_end = virtual_base + memory.virtual_size(); - - if (page_address >= virtual_base && page_address < virtual_end) - { - auto virtual_target = static_cast(page_address); - auto physical_offset = frame.number() * kapi::memory::frame::size; - return memory.map(kapi::memory::page::size, virtual_target, physical_offset.value); - } - else if (page_address >= kapi::memory::mmio_base) - { - throw std::runtime_error("MMIO mapping not yet supported in testing!"); - } - else if (page_address >= kapi::memory::higher_half_direct_map_base) - { - auto offset = frame.number() * kapi::memory::frame::size; - return kstd::observer_ptr{memory.physical_base().get() + offset}; + page_mappings.insert({page.number(), frame}); + return mapped; } return nullptr; @@ -72,4 +53,49 @@ namespace kernel::tests return {}; } -} // namespace kernel::tests \ No newline at end of file + auto page_mapper::do_map(kapi::memory::page page, kapi::memory::frame frame) -> kstd::observer_ptr + { + auto page_address = page.start_address(); + auto virtual_base = memory.virtual_base(); + auto virtual_end = virtual_base + memory.virtual_size(); + auto physical_offset = frame.number() * kapi::memory::frame::size; + + if (page_mappings.contains(page.number())) + { + throw std::invalid_argument{std::format("Page {} was already mapped!", page.number())}; + } + + if (page_address >= virtual_base && page_address < virtual_end) + { + if (physical_offset + kapi::memory::page::size > memory.physical_size()) + { + return nullptr; + } + + auto virtual_target = static_cast(page_address); + return memory.map(kapi::memory::page::size, virtual_target, physical_offset.value); + } + else if (page_address >= kapi::memory::mmio_base && page_address < kapi::memory::mmio_base + mmio.virtual_size()) + { + if (physical_offset + kapi::memory::page::size > mmio.physical_size()) + { + return nullptr; + } + + auto virtual_target = static_cast(mmio.virtual_base() + (page_address - kapi::memory::mmio_base)); + return mmio.map(kapi::memory::page::size, virtual_target, physical_offset.value); + } + else if (page_address >= kapi::memory::higher_half_direct_map_base && page_address < kapi::memory::mmio_base) + { + if (physical_offset + kapi::memory::page::size > memory.physical_size()) + { + return nullptr; + } + + return kstd::observer_ptr{memory.physical_base().get() + physical_offset.value}; + } + + return nullptr; + } + +} // namespace kernel::tests diff --git a/kernel/kernel/test_support/page_mapper.hpp b/kernel/kernel/test_support/page_mapper.hpp index df0bb154..fa601b7e 100644 --- a/kernel/kernel/test_support/page_mapper.hpp +++ b/kernel/kernel/test_support/page_mapper.hpp @@ -20,15 +20,18 @@ namespace kernel::tests { //! Construct a new page mapper. //! - //! @param physical_size The size of the physical memory. - //! @param virtual_size The size of the virtual address space. - page_mapper(kstd::bytes physical_size, kstd::bytes virtual_size); + //! @param ram_size The size of the physical memory. + //! @param ram_virtual_size The size of the virtual address space. + //! @param mmio_size Size of the simulated device physical address space. + //! @param mmio_virtual_size Size of the linear window backing the MMIO region. + page_mapper(kstd::bytes ram_size, kstd::bytes ram_virtual_size, kstd::bytes mmio_size, + kstd::bytes mmio_virtual_size); //! @copydoc kapi::memory::page_mapper::map //! //! @throws std::invalid_argument if the page has already been mapped. - //! @throws std::runtime_error if the page cannot be mapped. //! @throws std::runtime_error if the underlying simulated memory cannot map the page. + //! @return A pointer to the mapped memory or nullptr if the mapping failed. auto map(kapi::memory::page page, kapi::memory::frame frame, flags flags) -> kstd::observer_ptr override; //! @copydoc kapi::memory::page_mapper::unmap @@ -42,10 +45,21 @@ namespace kernel::tests //! The simulated memory. kernel::tests::simulated_memory memory; + //! The simulated MMIO region. + kernel::tests::simulated_memory mmio; + //! The simplified page table entries. std::unordered_map page_mappings; + + private: + //! Perform the actual mapping of a page to a frame. + //! + //! @param page The page to map. + //! @param frame The frame to map the page to. + //! @return A pointer to the mapped memory, or nullptr if the mapping failed. + auto do_map(kapi::memory::page page, kapi::memory::frame frame) -> kstd::observer_ptr; }; } // namespace kernel::tests -#endif \ No newline at end of file +#endif diff --git a/kernel/kernel/test_support/page_mapper.tests.cpp b/kernel/kernel/test_support/page_mapper.tests.cpp new file mode 100644 index 00000000..ab065887 --- /dev/null +++ b/kernel/kernel/test_support/page_mapper.tests.cpp @@ -0,0 +1,125 @@ +#include + +#include + +#include + +#include + +#include + +#include +#include + +SCENARIO("MMIO page mapping", "[smoke][memory]") +{ + GIVEN("A page mapper") + { + auto mapper = + kernel::tests::page_mapper{kernel::tests::memory::physical_size, kernel::tests::memory::virtual_size, + kernel::tests::memory::mmio_size, kernel::tests::memory::mmio_virtual_size}; + + WHEN("mapping two pages to the same MMIO frame") + { + auto first_page = kapi::memory::page::containing(kapi::memory::mmio_base); + auto second_page = kapi::memory::page::containing(kapi::memory::mmio_base) + 1; + + auto frame = kapi::memory::frame{0x00}; + auto first_mapping = mapper.map(first_page, frame, kapi::memory::page_mapper::flags::writable); + auto second_mapping = mapper.map(second_page, frame, kapi::memory::page_mapper::flags::writable); + + REQUIRE(first_mapping != second_mapping); + + THEN("a write through one mapping shows up in the other mapping") + { + *first_mapping = std::byte{0x10}; + CHECK(*second_mapping == std::byte{0x10}); + } + } + + WHEN("trying to map a page outside the allowed physical ranges") + { + auto page = kapi::memory::page::containing(kapi::memory::mmio_base); + auto frame = kapi::memory::frame::containing(kapi::memory::physical_address{kernel::tests::memory::mmio_size}); + auto mapping = mapper.map(page, frame, kapi::memory::page_mapper::flags::writable); + + THEN("the returned pointer is nullptr") + { + CHECK(mapping == nullptr); + } + + THEN("no mapping is recorded") + { + CHECK(mapper.page_mappings.empty()); + } + + AND_WHEN("trying to map that same page to a valid frame") + { + auto retry_frame = kapi::memory::frame{0x00}; + auto retry_mapping = mapper.map(page, retry_frame, kapi::memory::page_mapper::flags::writable); + + THEN("the returned pointer is not nullptr") + { + CHECK(retry_mapping != nullptr); + } + } + } + + WHEN("trying to map a page to the last valid frame") + { + auto page = kapi::memory::page::containing(kapi::memory::mmio_base); + auto frame = kapi::memory::frame{kernel::tests::memory::mmio_size / kapi::memory::frame::size - 1}; + auto mapping = mapper.map(page, frame, kapi::memory::page_mapper::flags::writable); + + THEN("the returned pointer is not nullptr") + { + CHECK(mapping != nullptr); + } + } + + WHEN("a page is already mapped") + { + auto first_frame = kapi::memory::frame{0x00}; + auto second_frame = kapi::memory::frame{0x01}; + auto page = kapi::memory::page::containing(kapi::memory::mmio_base); + + auto first_mapping = mapper.map(page, first_frame, kapi::memory::page_mapper::flags::writable); + REQUIRE(first_mapping != nullptr); + + *first_mapping = std::byte{0x10}; + + THEN("there is one page mapping") + { + CHECK(mapper.page_mappings.size() == 1); + } + + THEN("trying to map the same page again throws") + { + CHECK_THROWS_AS(mapper.map(page, second_frame, kapi::memory::page_mapper::flags::writable), + std::invalid_argument); + + AND_THEN("data can still be read from the first mapping") + { + CHECK(*first_mapping == std::byte{0x10}); + } + + AND_THEN("there is still only one page mapping") + { + CHECK(mapper.page_mappings.size() == 1); + } + } + } + + WHEN("trying to map a page beyond the allowed virtual range") + { + auto page = kapi::memory::page::containing(kapi::memory::mmio_base + kernel::tests::memory::mmio_virtual_size); + auto frame = kapi::memory::frame{0}; + auto mapping = mapper.map(page, frame, kapi::memory::page_mapper::flags::writable); + + THEN("the returned pointer is nullptr") + { + CHECK(mapping == nullptr); + } + } + } +} diff --git a/kernel/kernel/test_support/simulated_memory.cpp b/kernel/kernel/test_support/simulated_memory.cpp index 4255eed0..b6c3c4d9 100644 --- a/kernel/kernel/test_support/simulated_memory.cpp +++ b/kernel/kernel/test_support/simulated_memory.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -18,8 +19,8 @@ namespace kernel::tests { - simulated_memory::simulated_memory(kstd::bytes physical_size, kstd::bytes virtual_size) - : m_descriptor{memfd_create("teachos_simulated_memory", 0)} + simulated_memory::simulated_memory(std::string const & name, kstd::bytes physical_size, kstd::bytes virtual_size) + : m_descriptor{memfd_create(name.c_str(), 0)} , m_physical_size{physical_size} , m_virtual_size{virtual_size} { diff --git a/kernel/kernel/test_support/simulated_memory.hpp b/kernel/kernel/test_support/simulated_memory.hpp index e6161437..128ef715 100644 --- a/kernel/kernel/test_support/simulated_memory.hpp +++ b/kernel/kernel/test_support/simulated_memory.hpp @@ -7,6 +7,7 @@ #include #include +#include #include @@ -22,9 +23,10 @@ namespace kernel::tests struct simulated_memory { //! Construct a new simulated memory device. + //! @param name The name of the simulated memory device. //! @param physical_size The size of the physical memory. //! @param virtual_size The size of the virtual address space. - simulated_memory(kstd::bytes physical_size, kstd::bytes virtual_size); + simulated_memory(std::string const & name, kstd::bytes physical_size, kstd::bytes virtual_size); //! Destroy this device ~simulated_memory(); diff --git a/kernel/kernel/test_support/state_reset_listener.cpp b/kernel/kernel/test_support/state_reset_listener.cpp index e7d17219..fb1b23a5 100644 --- a/kernel/kernel/test_support/state_reset_listener.cpp +++ b/kernel/kernel/test_support/state_reset_listener.cpp @@ -37,6 +37,7 @@ struct state_reset_listener : Catch::EventListenerBase kapi::cio::init(); kapi::cpu::init(); kapi::memory::init(); + kapi::memory::init_mmio(kapi::memory::mmio_base, kernel::tests::memory::mmio_pool_size / kapi::memory::page::size); kapi::devices::init(); kernel::drivers::init(); -- cgit v1.2.3 From a15cd3183c35534561644bb1f615beb824ca6817 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 16 Nov 2026 10:19:08 +0100 Subject: kapi/memory: add a destructor to mmio_allocator In testing, the mmio_allocator gets replaced for every scenario requiring all heap allocations to be properly cleaned up before the replacement. --- kernel/kernel/memory/mmio_allocator.cpp | 11 +++++++++++ kernel/kernel/memory/mmio_allocator.hpp | 2 ++ 2 files changed, 13 insertions(+) (limited to 'kernel') diff --git a/kernel/kernel/memory/mmio_allocator.cpp b/kernel/kernel/memory/mmio_allocator.cpp index 49cb31e9..05cf35e4 100644 --- a/kernel/kernel/memory/mmio_allocator.cpp +++ b/kernel/kernel/memory/mmio_allocator.cpp @@ -17,6 +17,17 @@ namespace kernel::memory : m_head{make_node(base, pages, nullptr, nullptr, true)} {} + mmio_allocator::~mmio_allocator() + { + auto current = m_head; + while (current) + { + auto next = current->next; + destroy_node(current); + current = next; + } + } + auto mmio_allocator::allocate(std::size_t count) -> kstd::result { if (count == 0) diff --git a/kernel/kernel/memory/mmio_allocator.hpp b/kernel/kernel/memory/mmio_allocator.hpp index 268ca40b..4cb9d407 100644 --- a/kernel/kernel/memory/mmio_allocator.hpp +++ b/kernel/kernel/memory/mmio_allocator.hpp @@ -15,6 +15,8 @@ namespace kernel::memory { mmio_allocator(kapi::memory::linear_address base, std::size_t pages); + ~mmio_allocator(); + [[nodiscard]] auto allocate(std::size_t page_count) -> kstd::result; auto release(kapi::memory::linear_address base) -> void; -- cgit v1.2.3 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. --- 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 ++---- 5 files changed, 607 insertions(+), 125 deletions(-) create mode 100644 kernel/kapi/memory/mmio.cpp create mode 100644 kernel/kapi/memory/mmio.tests.cpp (limited to 'kernel') 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 From a42ab28f65e3ef5926137ddf4c62b188c33ca440 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 16 Nov 2026 15:50:15 +0100 Subject: kernel/devices: introduce PCI ecam_segment abstraction Previously, ECAM access was implemented "in-place" inside the PCI scan function. This meant that any checks were ad-hoc and not easily reusable or testable. Therefore, this change introduces a dedicated, reusable abstraction for ECAM segment access. It validates segment descriptors received from the platform and ensures no out-of-bounds buses are accessed at runtime. Construction of an ecam_segment will always succeed. If the firmware or platform data does not describe a valid segment, the ecam_segment will behave as if it had a size of zero, with a kernel log indicating the invalid segment. Attempting to map a bus that is out-of-bounds for a given ecam_segment will return a runtime error. If the system's MMIO space is insufficient to accommodate the mapping of a valid bus in an ecam_segment, a runtime error will be returned. Furthermore, this change introduces the kernel::devices::pci namespace. PCI initialization and scanning functionality, previously hosted in kernel/kernel/devices/pci_express.{cpp,hpp}, has been relocated and renamed to kernel/kernel/devices/pci/init.{cpp,hpp}. The initialization function of the PCI subsystem has been renamed from kernel::devices::init_pci_express_devices to kernel::devices::pci::init. The observable behavior of the PCI scan remains unchanged. Tests have been added to validate the behavior of ecam_segment against its contract. --- kernel/CMakeLists.txt | 3 +- kernel/kernel/devices/pci/ecam_segment.cpp | 59 +++++ kernel/kernel/devices/pci/ecam_segment.hpp | 77 ++++++ kernel/kernel/devices/pci/ecam_segment.tests.cpp | 317 +++++++++++++++++++++++ kernel/kernel/devices/pci/init.cpp | 83 ++++++ kernel/kernel/devices/pci/init.hpp | 14 + kernel/kernel/devices/pci/registers.hpp | 51 ++++ kernel/kernel/devices/pci_express.cpp | 112 -------- kernel/kernel/devices/pci_express.hpp | 14 - kernel/kernel/main.cpp | 4 +- 10 files changed, 605 insertions(+), 129 deletions(-) create mode 100644 kernel/kernel/devices/pci/ecam_segment.cpp create mode 100644 kernel/kernel/devices/pci/ecam_segment.hpp create mode 100644 kernel/kernel/devices/pci/ecam_segment.tests.cpp create mode 100644 kernel/kernel/devices/pci/init.cpp create mode 100644 kernel/kernel/devices/pci/init.hpp create mode 100644 kernel/kernel/devices/pci/registers.hpp delete mode 100644 kernel/kernel/devices/pci_express.cpp delete mode 100644 kernel/kernel/devices/pci_express.hpp (limited to 'kernel') diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index 705f3a85..df65ed20 100644 --- a/kernel/CMakeLists.txt +++ b/kernel/CMakeLists.txt @@ -43,7 +43,8 @@ target_sources("kernel_lib" PRIVATE # Device Subsystem "kernel/devices/block_device_utils.cpp" "kernel/devices/init.cpp" - "kernel/devices/pci_express.cpp" + "kernel/devices/pci/ecam_segment.cpp" + "kernel/devices/pci/init.cpp" "kernel/devices/pseudo.cpp" "kernel/devices/storage.cpp" diff --git a/kernel/kernel/devices/pci/ecam_segment.cpp b/kernel/kernel/devices/pci/ecam_segment.cpp new file mode 100644 index 00000000..5464ec4b --- /dev/null +++ b/kernel/kernel/devices/pci/ecam_segment.cpp @@ -0,0 +1,59 @@ +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include + +namespace kernel::devices::pci +{ + + ecam_segment::ecam_segment(kapi::devices::pcie_segment_descriptor const & descriptor) + : m_base{descriptor.base_address} + , m_count{descriptor.bus_count} + , m_group{descriptor.group_number} + , m_start{descriptor.first_bus} + { + if (m_count > 256uz - m_start) + { + kstd::println(kstd::print_sink::stderr, "[OS:DEV] Invalid PCI bus count '{}' for start bus '{}'", + descriptor.bus_count, m_start); + m_count = 0; + } + } + + auto ecam_segment::contains(std::size_t bus) const noexcept -> bool + { + return bus >= m_start && bus < (m_start + m_count); + } + + auto ecam_segment::first_bus() const noexcept -> std::uint8_t + { + return m_start; + } + + auto ecam_segment::group() const noexcept -> std::uint16_t + { + return m_group; + } + + auto ecam_segment::map_bus(std::uint8_t bus) const -> kstd::result + { + if (!contains(bus)) + { + return kstd::failure(make_error_code(kstd::errc::invalid_argument)); + } + + return kapi::memory::mmio_window::map(m_base + bus * mmio_window_per_bus, mmio_window_per_bus, + kapi::memory::mmio_window::access::read_only); + } + +} // namespace kernel::devices::pci diff --git a/kernel/kernel/devices/pci/ecam_segment.hpp b/kernel/kernel/devices/pci/ecam_segment.hpp new file mode 100644 index 00000000..8f9e18bd --- /dev/null +++ b/kernel/kernel/devices/pci/ecam_segment.hpp @@ -0,0 +1,77 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_ECAM_SEGMENT_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_ECAM_SEGMENT_HPP + +#include + +#include +#include + +#include +#include + +#include +#include + +namespace kernel::devices::pci +{ + + //! An ECAM (Enhanced Configuration Access Mechanism) segment representing the configuration space of a PCI segment. + struct ecam_segment + { + //! Construct a new ECAM segment from a PCIe segment descriptor provided by the platform. + explicit ecam_segment(kapi::devices::pcie_segment_descriptor const & descriptor); + + //! Check if this ECAM segment contains the given bus number. + //! + //! @param bus The bus number to check. + //! @return @p true iff. the bus is within this segment, false otherwise. + [[nodiscard]] auto contains(std::size_t bus) const noexcept -> bool; + + //! Get the number of the first bus in this ECAM segment. + //! + //! @return The number of the first bus. + [[nodiscard]] auto first_bus() const noexcept -> std::uint8_t; + + //! Get the PCI segment group number of this ECAM segment. + //! + //! @return The PCI segment group number. + [[nodiscard]] auto group() const noexcept -> std::uint16_t; + + //! Create an MMIO mapping for the configuration space of the given bus. + //! + //! @warning This function will panic if the MMIO subsystem has not been initialized. + //! + //! @param bus The bus number to map. + //! @return An MMIO window for the bus if successful, an error otherwise. + [[nodiscard]] auto map_bus(std::uint8_t bus) const -> kstd::result; + + private: + //! The hardware base address of the segment. + kapi::memory::physical_address m_base; + //! The number of buses in the segment. + std::size_t m_count; + //! The PCI segment group number. + std::uint16_t m_group; + //! The starting bus number of the segment. + std::uint8_t m_start; + }; + + //! Calculate the offset of a specific device function inside the configuration space of a bus. + //! + //! @param device The device number. + //! @param function The function number. + //! @return The byte offset of the function within the device's configuration space. + constexpr auto function_offset(std::uint8_t device, std::uint8_t function) noexcept -> kstd::bytes + { + return kstd::bytes((device << device_address_shift) + (function << function_address_shift)); + } + + static_assert(function_offset(0, 0) == kstd::bytes{0}); + static_assert(function_offset(1, 0) == kstd::bytes{0x8000}); + static_assert(function_offset(0, 1) == kstd::bytes{0x1000}); + // NOLINTNEXTLINE(readability-magic-numbers) + static_assert(function_offset(devices_per_bus - 1, functions_per_device - 1) == kstd::bytes{0xFF000}); + +} // namespace kernel::devices::pci + +#endif diff --git a/kernel/kernel/devices/pci/ecam_segment.tests.cpp b/kernel/kernel/devices/pci/ecam_segment.tests.cpp new file mode 100644 index 00000000..513ce6d1 --- /dev/null +++ b/kernel/kernel/devices/pci/ecam_segment.tests.cpp @@ -0,0 +1,317 @@ +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include + +namespace +{ + constexpr auto ecam_test_base = kapi::memory::physical_address{}; + + struct test_descriptor_data + { + std::uint8_t first_bus; + std::size_t bus_count; + }; +} // namespace + +SCENARIO("ECAM segment basic operations", "[devices][pci][ecam]") +{ + GIVEN("A valid segment group descriptor") + { + auto const test_data = GENERATE(test_descriptor_data{0, 256}, // maximum bus count + test_descriptor_data{255, 1}, // single bus + test_descriptor_data{16, 32} // multiple buses, far from the edge + ); + + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 3, + .first_bus = test_data.first_bus, + .bus_count = test_data.bus_count, + }; + + WHEN("constructing an ECAM segment with the descriptor") + { + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("the segment contains its buses") + { + for (std::size_t bus = descriptor.first_bus; bus < descriptor.first_bus + descriptor.bus_count; ++bus) + { + REQUIRE(segment.contains(bus)); + } + } + + THEN("the segment does not contain buses beyond its last bus") + { + for (std::size_t bus = descriptor.first_bus + descriptor.bus_count; bus < 256 + 1; ++bus) + { + REQUIRE_FALSE(segment.contains(bus)); + } + } + + THEN("the segment does not contain any buses before its first bus") + { + for (std::size_t bus = 0; bus < descriptor.first_bus; ++bus) + { + REQUIRE_FALSE(segment.contains(bus)); + } + } + + THEN("the segment group is correct") + { + REQUIRE(segment.group() == descriptor.group_number); + } + + THEN("the first bus is correct") + { + REQUIRE(segment.first_bus() == descriptor.first_bus); + } + } + } + + GIVEN("A segment with zero buses") + { + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 0, + .first_bus = 64, + .bus_count = 0, + }; + + WHEN("constructing an ECAM segment with the descriptor") + { + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("the segment does not contain any buses") + { + for (std::size_t bus = 0; bus < 256; ++bus) + { + REQUIRE_FALSE(segment.contains(bus)); + } + } + } + } + + GIVEN("An invalid segment group descriptor") + { + auto const test_data = + GENERATE(test_descriptor_data{255, 2}, // too many buses + test_descriptor_data{1, 256}, // too many buses + test_descriptor_data{0, std::numeric_limits::max()} // way too many buses + ); + + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 0, + .first_bus = test_data.first_bus, + .bus_count = test_data.bus_count, + }; + + WHEN("constructing an ECAM segment with the descriptor") + { + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("the segment does not contain any buses") + { + for (std::size_t bus = 0; bus < 256; ++bus) + { + REQUIRE_FALSE(segment.contains(bus)); + } + } + } + } +} + +SCENARIO("ECAM segment mapping", "[devices][pci][ecam]") +{ + GIVEN("A valid, non-empty segment") + { + constexpr auto descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 0, + .first_bus = 1, + .bus_count = (kernel::tests::memory::mmio_size / kernel::devices::pci::mmio_window_per_bus) - 1, + }; + + STATIC_REQUIRE(descriptor.bus_count > 0); + + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("all of its buses can be mapped") + { + for (std::size_t bus = descriptor.first_bus; bus < descriptor.first_bus + descriptor.bus_count; ++bus) + { + REQUIRE(segment.map_bus(bus)); + } + } + + THEN("buses outside the segment cannot be mapped") + { + auto const lower_result = segment.map_bus(descriptor.first_bus + descriptor.bus_count); + REQUIRE_FALSE(lower_result); + REQUIRE(lower_result.error() == kstd::errc::invalid_argument); + + auto const upper_result = segment.map_bus(descriptor.first_bus - 1); + REQUIRE_FALSE(upper_result); + REQUIRE(upper_result.error() == kstd::errc::invalid_argument); + } + + WHEN("there is data to read") + { + // We calculate the base address ourselves to ensure we don't rely on potentially faulty constants. + // + // Each device's ECAM space is 4 KiB * 8 [functions per devices] large. + // Each bus' ECAM space is 32 [max devices per bus] * [device ECAM space size] large. + // A bus' ECAM space starts at the base address of the segment + [bus number] * [bus ECAM space size] + // Therefore we get: + constexpr auto bytes_per_device = kstd::KiB(4u) * 8; + constexpr auto bytes_per_bus = 32 * bytes_per_device; + constexpr auto hw_base = ecam_test_base + (descriptor.first_bus * bytes_per_bus); + + auto data_window = + kapi::memory::mmio_window::map(hw_base, bytes_per_bus, kapi::memory::mmio_window::access::writable); + + REQUIRE(data_window); + + data_window->write(kstd::bytes{0}, 0x1000); + data_window->write(kstd::bytes{2}, 0x2000); + data_window->write(kstd::bytes{4}, 0x4000); + + THEN("the data can be read back correctly") + { + auto bus = segment.map_bus(descriptor.first_bus); + + REQUIRE(bus->read(kstd::bytes{0}) == 0x1000); + REQUIRE(bus->read(kstd::bytes{2}) == 0x2000); + REQUIRE(bus->read(kstd::bytes{4}) == 0x4000); + } + } + } + + GIVEN("A valid, non-empty segment at a non-zero base address") + { + constexpr auto non_zero_base = ecam_test_base + kstd::MiB(1u); + + constexpr auto descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = non_zero_base, + .group_number = 0, + .first_bus = 1, + .bus_count = (kernel::tests::memory::mmio_size / kernel::devices::pci::mmio_window_per_bus) - 2, + }; + + STATIC_REQUIRE(descriptor.bus_count > 0); + + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + WHEN("there is data to read") + { + // We calculate the base address ourselves to ensure we don't rely on potentially faulty constants. + // + // Each device's ECAM space is 4 KiB * 8 [functions per devices] large. + // Each bus' ECAM space is 32 [max devices per bus] * [device ECAM space size] large. + // A bus' ECAM space starts at the base address of the segment + [bus number] * [bus ECAM space size] + // Therefore we get: + constexpr auto bytes_per_device = kstd::KiB(4u) * 8; + constexpr auto bytes_per_bus = 32 * bytes_per_device; + constexpr auto hw_base = non_zero_base + (descriptor.first_bus * bytes_per_bus); + + auto data_window = + kapi::memory::mmio_window::map(hw_base, bytes_per_bus, kapi::memory::mmio_window::access::writable); + + REQUIRE(data_window); + + data_window->write(kstd::bytes{0}, 0x1000); + data_window->write(kstd::bytes{2}, 0x2000); + data_window->write(kstd::bytes{4}, 0x4000); + + THEN("the data can be read back correctly") + { + auto bus = segment.map_bus(descriptor.first_bus); + + REQUIRE(bus->read(kstd::bytes{0}) == 0x1000); + REQUIRE(bus->read(kstd::bytes{2}) == 0x2000); + REQUIRE(bus->read(kstd::bytes{4}) == 0x4000); + } + } + } + + GIVEN("A valid segment whose buses fall outside the device space") + { + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base + kernel::tests::memory::mmio_size, + .group_number = 0, + .first_bus = (kernel::tests::memory::mmio_size / kernel::devices::pci::mmio_window_per_bus) / 2, + .bus_count = 256 - ((kernel::tests::memory::mmio_size / kernel::devices::pci::mmio_window_per_bus) / 2), + }; + + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("no buses can be mapped") + { + for (std::size_t bus = descriptor.first_bus; bus < descriptor.first_bus + descriptor.bus_count; ++bus) + { + auto const result = segment.map_bus(bus); + REQUIRE_FALSE(result); + REQUIRE(result.error() == kstd::errc::not_enough_memory); + } + } + } + + GIVEN("An empty segment") + { + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 0, + .first_bus = 0, + .bus_count = 0, + }; + + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("no buses can be mapped") + { + for (std::size_t bus = 0; bus < 256; ++bus) + { + auto const result = segment.map_bus(bus); + REQUIRE_FALSE(result); + REQUIRE(result.error() == kstd::errc::invalid_argument); + } + } + } + + GIVEN("An invalid segment") + { + auto const descriptor = kapi::devices::pcie_segment_descriptor{ + .base_address = ecam_test_base, + .group_number = 0, + .first_bus = 255, + .bus_count = 2, + }; + + auto const segment = kernel::devices::pci::ecam_segment{descriptor}; + + THEN("no buses can be mapped") + { + for (std::size_t bus = 0; bus < 256; ++bus) + { + auto const result = segment.map_bus(bus); + REQUIRE_FALSE(result); + REQUIRE(result.error() == kstd::errc::invalid_argument); + } + } + } +} diff --git a/kernel/kernel/devices/pci/init.cpp b/kernel/kernel/devices/pci/init.cpp new file mode 100644 index 00000000..05f5e7d1 --- /dev/null +++ b/kernel/kernel/devices/pci/init.cpp @@ -0,0 +1,83 @@ +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include + +namespace kernel::devices::pci +{ + + namespace + { + + auto enumerate(kapi::devices::pcie_segment_descriptor const & descriptor) -> void + { + auto segment = ecam_segment{descriptor}; + + for (std::size_t bus = segment.first_bus(); segment.contains(bus); ++bus) + { + // Note: ecam_segment::contains(...) == true guarantees the bus number fits in a uint8_t + auto bus_window = segment.map_bus(static_cast(bus)); + + if (!bus_window) + { + kstd::println("[OS:DEV] Failed to map MMIO window for bus {}", bus); + continue; + } + + for (std::uint8_t device = 0; device < devices_per_bus; ++device) + { + auto device_base = function_offset(device, 0); + auto device_vendor_id = bus_window->read(device_base + vendor_id_register_offset); + if (device_vendor_id == invalid_vendor_id) + { + continue; + } + + auto device_header_type = bus_window->read(device_base + header_type_register_offset); + auto function_count = (device_header_type & 0x80) ? functions_per_device : 1u; + + for (std::uint8_t function = 0; function < function_count; ++function) + { + auto function_base = function_offset(device, function); + auto function_vendor_id = bus_window->read(function_base + vendor_id_register_offset); + if (function_vendor_id == invalid_vendor_id) + { + continue; + } + + auto function_device_id = bus_window->read(function_base + device_id_register_offset); + kstd::println("[OS:DEV] Detected PCI Express device: {:04x}:{:02x}:{:02x}.{:1} [{:04x}:{:04x}]", + segment.group(), bus, device, function, function_vendor_id, function_device_id); + } + } + } + } + + } // namespace + + auto init() -> void + { + auto segments = kapi::devices::get_pci_express_segment_descriptors(); + + if (segments.empty()) + { + return; + } + + kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", segments.size()); + for (auto & segment : segments) + { + enumerate(segment); + } + } + +} // namespace kernel::devices::pci diff --git a/kernel/kernel/devices/pci/init.hpp b/kernel/kernel/devices/pci/init.hpp new file mode 100644 index 00000000..8a49acbc --- /dev/null +++ b/kernel/kernel/devices/pci/init.hpp @@ -0,0 +1,14 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_INIT_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_INIT_HPP + +namespace kernel::devices::pci +{ + + //! Initialize all PCI/PCIe devices in the system. + //! + //! This function scans and initializes all PCI and PCI Express devices present in the system. + auto init() -> void; + +} // namespace kernel::devices::pci + +#endif diff --git a/kernel/kernel/devices/pci/registers.hpp b/kernel/kernel/devices/pci/registers.hpp new file mode 100644 index 00000000..2e426be1 --- /dev/null +++ b/kernel/kernel/devices/pci/registers.hpp @@ -0,0 +1,51 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_REGISTERS_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_REGISTERS_HPP + +#include + +#include + +namespace kernel::devices::pci +{ + + //! The maximum number of devices per PCI bus. + constexpr auto inline devices_per_bus = 32u; + + //! The maximum number of functions per PCI device. + constexpr auto inline functions_per_device = 8u; + + //! The size of the configuration space for a single PCI function. + constexpr auto inline config_space_per_function = kstd::KiB(4u); + + //! The size of the MMIO window for a single PCI bus. + constexpr auto inline mmio_window_per_bus = devices_per_bus * functions_per_device * config_space_per_function; + + //! The number of bits to shift the bus number when creating a PCI window address. + constexpr auto inline bus_address_shift = 20u; + + //! The number of bits to shift the device number when creating a PCI window address. + constexpr auto inline device_address_shift = 15u; + + //! The number of bits to shift the function number when creating a PCI window address. + constexpr auto inline function_address_shift = 12u; + + static_assert(config_space_per_function * devices_per_bus * functions_per_device == mmio_window_per_bus); + static_assert(kstd::bytes{1 << bus_address_shift} == mmio_window_per_bus); + static_assert(kstd::bytes{1 << device_address_shift} == functions_per_device * config_space_per_function); + static_assert(kstd::bytes{1 << function_address_shift} == config_space_per_function); + + //! The vendor ID value indicating an invalid or non-existent device. + constexpr auto inline invalid_vendor_id = std::uint16_t{0xffff}; + + //! The offset of the vendor ID register within the PCI configuration space. + constexpr auto inline vendor_id_register_offset = kstd::bytes{0x00}; + + //! The offset of the device ID register within the PCI configuration space. + constexpr auto inline device_id_register_offset = kstd::bytes{0x02}; + + //! The offset of the header type register within the PCI configuration space. + constexpr auto inline header_type_register_offset = kstd::bytes{0x0e}; + +} // namespace kernel::devices::pci + +#endif diff --git a/kernel/kernel/devices/pci_express.cpp b/kernel/kernel/devices/pci_express.cpp deleted file mode 100644 index 46ed2c1c..00000000 --- a/kernel/kernel/devices/pci_express.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include - -#include -#include - -#include -#include -#include - -#include -#include - -namespace kernel::devices -{ - - namespace - { - - struct pcie_config_space_header - { - std::uint16_t vendor_id{}; - std::uint16_t device_id{}; - 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{}; - std::uint8_t built_in_self_test{}; - }; - - constexpr auto static invalid_vendor_id = 0xffff; - - constexpr auto static devices_per_bus = 32; - constexpr auto static functions_per_device = 8; - - constexpr auto static bus_address_shift = 20; - constexpr auto static device_address_shift = 15; - constexpr auto static function_address_shift = 12; - - auto enumerate(kapi::devices::pcie_segment_descriptor const & segment) -> void - { - auto segment_base = kapi::memory::physical_address{segment.base_address}; - - 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_address = kapi::memory::physical_address{segment_base + (bus << bus_address_shift)}; - 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_window) - { - kstd::println("[OS:DEV] Failed to map MMIO window for bus {}", bus); - continue; - } - - for (auto device = 0; device < devices_per_bus; ++device) - { - 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; - } - - 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_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 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, function_vendor_id, function_device_id); - } - } - } - } - - } // namespace - - auto init_pci_express_devices() -> void - { - auto segments = kapi::devices::get_pci_express_segment_descriptors(); - - if (segments.empty()) - { - return; - } - - kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", segments.size()); - for (auto & segment : segments) - { - enumerate(segment); - } - } - -} // namespace kernel::devices \ No newline at end of file diff --git a/kernel/kernel/devices/pci_express.hpp b/kernel/kernel/devices/pci_express.hpp deleted file mode 100644 index 596791b1..00000000 --- a/kernel/kernel/devices/pci_express.hpp +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP -#define TEACHOS_KERNEL_DEVICES_PCI_EXPRESS_HPP - -namespace kernel::devices -{ - - //! Initialize all PCI Express devices in the system. - //! - //! This function scans and initializes all PCI Express devices present in the system. - auto init_pci_express_devices() -> void; - -} // namespace kernel::devices - -#endif \ No newline at end of file diff --git a/kernel/kernel/main.cpp b/kernel/kernel/main.cpp index 47db0537..ea55451f 100644 --- a/kernel/kernel/main.cpp +++ b/kernel/kernel/main.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -297,7 +297,7 @@ auto main() -> int kapi::interrupts::enabled(true); kstd::println("[OS] Interrupts enabled."); - kernel::devices::init_pci_express_devices(); + kernel::devices::pci::init(); kstd::println("[OS] PCI Express devices initialized."); auto modules_bus = kernel::devices::storage::init(); -- cgit v1.2.3 From 0dfdb6c4f4aa428d6e1951958edafd82b87a0af8 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 16 Nov 2026 17:32:59 +0100 Subject: kernel/devices: introduce PCI function_address A PCI function is identified system-wide by its segment group, bus, device and function number. This identifier is represented by the new function_address type. It encapsulates the identifying 4-tuple (segment group, bus, device, function). This allows the kernel to reference a specific PCI function unambiguously within the system. The type is comparable and ordered by that tuple and formats as 'ssss:bb:dd.f'. The ordering is lexicographical based on the tuple (segment group, bus, device, function). Unit tests for the API surface of function_address are included. --- kernel/kernel/devices/pci/function_address.hpp | 61 +++++++++++++++ .../kernel/devices/pci/function_address.tests.cpp | 89 ++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 kernel/kernel/devices/pci/function_address.hpp create mode 100644 kernel/kernel/devices/pci/function_address.tests.cpp (limited to 'kernel') diff --git a/kernel/kernel/devices/pci/function_address.hpp b/kernel/kernel/devices/pci/function_address.hpp new file mode 100644 index 00000000..c4b0888b --- /dev/null +++ b/kernel/kernel/devices/pci/function_address.hpp @@ -0,0 +1,61 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_ADDRESS_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_ADDRESS_HPP + +#include + +#include +#include +#include +#include +#include + +namespace kernel::devices::pci +{ + + //! The address of a PCI function within the system. + struct function_address + { + //! Compare two function addresses for ordering. + constexpr auto friend operator<=>(function_address const & lhs, function_address const & rhs) noexcept + -> std::strong_ordering = default; + + //! The PCI segment group this function belongs to. + std::uint16_t segment_group{}; + //! The PCI bus this function belongs to. + std::uint8_t bus{}; + //! The PCI device this function belongs to. + //! + //! The valid range for the PCI device number is [0, 31]. + std::uint8_t device{}; + //! The PCI function number within the device. + //! + //! The valid range for the PCI function number is [0, 7]. + std::uint8_t function{}; + }; + +} // namespace kernel::devices::pci + +template<> +struct kstd::formatter +{ + constexpr auto parse(kstd::format_parse_context & context) -> kstd::format_parse_context::iterator + { + auto it = context.begin(); + if (it != context.end() && *it != '}') + { + bits::format::error("Invalid specifier for function_address."); + } + return it; + } + + auto format(kernel::devices::pci::function_address const & address, kstd::format_context & context) const -> void + { + constexpr auto output_length = 32; + auto buffer = std::array{}; + auto [span, length] = kstd::format_to(std::span{buffer}, "{:04x}:{:02x}:{:02x}.{:1x}", address.segment_group, + address.bus, address.device, address.function); + context.push(std::string_view{span.data(), length}); + } +}; + +#endif diff --git a/kernel/kernel/devices/pci/function_address.tests.cpp b/kernel/kernel/devices/pci/function_address.tests.cpp new file mode 100644 index 00000000..ae9ccfff --- /dev/null +++ b/kernel/kernel/devices/pci/function_address.tests.cpp @@ -0,0 +1,89 @@ +#include + +#include + +#include + +#include + +// NOLINTBEGIN(readability-magic-numbers) + +SCENARIO("PCI Function Address formatting") +{ + GIVEN("A zeroed PCI function address") + { + kernel::devices::pci::function_address address{}; + + THEN("The address is formatted as 0000:00:00.0") + { + REQUIRE(kstd::format("{}", address) == "0000:00:00.0"); + } + } + + GIVEN("A non-zero PCI function address") + { + kernel::devices::pci::function_address address{}; + address.segment_group = 0xabcd; + address.bus = 0xff; + address.device = 0x1f; + address.function = 7; + + THEN("The address is formatted correctly") + { + REQUIRE(kstd::format("{}", address) == "abcd:ff:1f.7"); + } + } +} + +SCENARIO("PCI Function Address comparison") +{ + GIVEN("Two identical PCI function addresses") + { + kernel::devices::pci::function_address address1{.segment_group = 1, .bus = 16, .device = 3, .function = 4}; + kernel::devices::pci::function_address address2{.segment_group = 1, .bus = 16, .device = 3, .function = 4}; + + THEN("they compare equal") + { + REQUIRE(address1 == address2); + } + + THEN("they are ordered as equal") + { + REQUIRE((address1 <=> address2) == std::strong_ordering::equal); + } + } + + GIVEN("Different PCI function addresses that differ in the function field") + { + kernel::devices::pci::function_address address1{.segment_group = 1, .bus = 16, .device = 3, .function = 4}; + kernel::devices::pci::function_address address2{.segment_group = 1, .bus = 16, .device = 3, .function = 5}; + + THEN("They are not equal") + { + REQUIRE(address1 != address2); + } + + THEN("They are ordered correctly") + { + REQUIRE(address1 < address2); + } + } + + GIVEN("Different PCI function addresses that differ in the bus field") + { + kernel::devices::pci::function_address address1{.segment_group = 1, .bus = 16, .device = 3, .function = 4}; + kernel::devices::pci::function_address address2{.segment_group = 1, .bus = 32, .device = 3, .function = 4}; + + THEN("They are not equal") + { + REQUIRE(address1 != address2); + } + + THEN("They are ordered correctly") + { + REQUIRE(address1 < address2); + } + } +} + +// NOLINTEND(readability-magic-numbers) -- cgit v1.2.3 From 05115c3961d316fd52409a753a88dd573cab4860 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 16 Nov 2026 17:41:05 +0100 Subject: kernel/devices: introduce PCI function_info Besides address information, each PCI function also has associated metadata. The function_info type carries the standard metadata for a PCI function: vendor and device IDs, the class code 3-tuple, and the header type. A bus scan reads those values when enumerating the PCI ECAM data, and returns it. The header type of the is stored in its raw form, encoding both the type of the PCI function header, as well as the multi-function flag. function_info provides two functions (type() and is_multifunction()) to extract those pieces of information from the raw header type value. In addition to the type extraction function, this change introduces an enumeration type (kernel::devices::pci::header_type) representing the standardized type values for PCI function headers. Unknown function types are presented as opaque values. Unit tests for derived attributes of a PCI function are provided. --- kernel/kernel/devices/pci/function_info.hpp | 72 +++++++++++ kernel/kernel/devices/pci/function_info.tests.cpp | 138 ++++++++++++++++++++++ 2 files changed, 210 insertions(+) create mode 100644 kernel/kernel/devices/pci/function_info.hpp create mode 100644 kernel/kernel/devices/pci/function_info.tests.cpp (limited to 'kernel') diff --git a/kernel/kernel/devices/pci/function_info.hpp b/kernel/kernel/devices/pci/function_info.hpp new file mode 100644 index 00000000..199716f5 --- /dev/null +++ b/kernel/kernel/devices/pci/function_info.hpp @@ -0,0 +1,72 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_INFO_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_INFO_HPP + +#include + +#include + +namespace kernel::devices::pci +{ + + //! The type of PCI header. + //! + //! This enumeration represents the possible types of PCI headers that a PCI function can have. The values correspond + //! to the encoding in the raw header type field, with the multifunction bit masked out. Devices may report + //! non-standard header types. + enum struct header_type : std::uint8_t + { + //! The device is an ordinary PCI endpoint device. + endpoint = 0, + //! The device is a PCI-to-PCI bridge. + pci_to_pci_bridge = 1, + //! The device is a CardBus bridge. + cardbus_bridge = 2 + }; + + //! Information about a PCI function. + struct function_info + { + //! Returns the header type of the PCI function. + //! + //! @note The value returned by this function may be outside the defined enumerator values of @p header_type, if the + //! underlying hardware encodes a non-standard header type. + //! + //! @return The header type of the PCI function, with the multifunction bit masked out. + [[nodiscard]] constexpr auto type() const noexcept -> header_type + { + constexpr auto bits_0_to_6 = 0x7F; + return static_cast(raw_header_type & bits_0_to_6); + } + + //! Returns whether the PCI function is part of a multifunction device. + //! + //! @note The read bit only represents the multifunction indicator when read from function 0 of a device. + //! + //! @return @p true iff the PCI function is part of a multifunction device, @p false otherwise. + [[nodiscard]] constexpr auto is_multifunction() const noexcept -> bool + { + constexpr auto bit_7 = 0x80; + return (raw_header_type & bit_7) != 0; + } + + //! The address of the PCI function described by this structure. + function_address address{}; + //! The vendor ID of the PCI function. + std::uint16_t vendor_id{}; + //! The device ID of the PCI function. + std::uint16_t device_id{}; + //! The revision of the PCI function. + std::uint8_t revision{}; + //! The programming interface of the PCI function. + std::uint8_t programming_interface{}; + //! The subclass code of the PCI function. + std::uint8_t subclass_code{}; + //! The class code of the PCI function. + std::uint8_t class_code{}; + //! The raw (encoded) header type of the PCI function. + std::uint8_t raw_header_type{}; + }; + +} // namespace kernel::devices::pci + +#endif diff --git a/kernel/kernel/devices/pci/function_info.tests.cpp b/kernel/kernel/devices/pci/function_info.tests.cpp new file mode 100644 index 00000000..91e838e7 --- /dev/null +++ b/kernel/kernel/devices/pci/function_info.tests.cpp @@ -0,0 +1,138 @@ +#include + +#include + +// NOLINTBEGIN(readability-magic-numbers) + +SCENARIO("PCI Function Info derived properties") +{ + GIVEN("A function of a single-function PCI device that is a basic endpoint") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x00; + + THEN("it is not a multifunction device") + { + REQUIRE_FALSE(info.is_multifunction()); + } + + THEN("it is a basic endpoint") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::endpoint); + } + } + + GIVEN("A function of a multifunction PCI device that is a basic endpoint") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x80; + + THEN("it is recognized as a multifunction device") + { + REQUIRE(info.is_multifunction()); + } + + THEN("it is a basic endpoint") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::endpoint); + } + } + + GIVEN("A function of a single-function PCI device that is a PCI-to-PCI bridge") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x01; + + THEN("it is recognized as not a multifunction device") + { + REQUIRE_FALSE(info.is_multifunction()); + } + + THEN("it is a PCI-to-PCI bridge") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::pci_to_pci_bridge); + } + } + + GIVEN("A function of a multifunction PCI device that is a PCI-to-PCI bridge") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x81; + + THEN("it is recognized as a multifunction device") + { + REQUIRE(info.is_multifunction()); + } + + THEN("it is a PCI-to-PCI bridge") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::pci_to_pci_bridge); + } + } + + GIVEN("A function of a single-function PCI device that is a CardBus bridge") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x02; + + THEN("it is recognized as not a multifunction device") + { + REQUIRE_FALSE(info.is_multifunction()); + } + + THEN("it is a CardBus bridge") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::cardbus_bridge); + } + } + + GIVEN("A function of a multifunction PCI device that is a CardBus bridge") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x82; + + THEN("it is recognized as a multifunction device") + { + REQUIRE(info.is_multifunction()); + } + + THEN("it is a CardBus bridge") + { + REQUIRE(info.type() == kernel::devices::pci::header_type::cardbus_bridge); + } + } + + GIVEN("A function of a single-function PCI device that is an unknown type") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0x7f; + + THEN("it is recognized as not a multifunction device") + { + REQUIRE_FALSE(info.is_multifunction()); + } + + THEN("it is an unknown type") + { + REQUIRE(info.type() == static_cast(0x7f)); + } + } + + GIVEN("A function of a multifunction PCI device that is an unknown type") + { + kernel::devices::pci::function_info info{}; + info.raw_header_type = 0xff; + + THEN("it is recognized as a multifunction device") + { + REQUIRE(info.is_multifunction()); + } + + THEN("it is an unknown type") + { + REQUIRE(info.type() == static_cast(0x7f)); + } + } +} + +// NOLINTEND(readability-magic-numbers) -- cgit v1.2.3 From 2f9972781b66fd350f1975b2975f8998d5d07f13 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Wed, 18 Nov 2026 08:39:07 +0100 Subject: kernel/devices: extract bus scanning implementation This change extracts the PCI bus scanning logic, which previously was hidden inside an anonymous namespace, into a dedicated function. This allows for the implementation to be tested independently. --- kernel/CMakeLists.txt | 1 + kernel/kernel/devices/pci/init.cpp | 76 ++-- kernel/kernel/devices/pci/registers.hpp | 12 + kernel/kernel/devices/pci/scan.cpp | 97 +++++ kernel/kernel/devices/pci/scan.hpp | 29 ++ kernel/kernel/devices/pci/scan.tests.cpp | 449 +++++++++++++++++++++ .../test_support/devices/pci/ecam_builder.cpp | 106 +++++ .../test_support/devices/pci/ecam_builder.hpp | 124 ++++++ .../devices/pci/ecam_builder.tests.cpp | 162 ++++++++ 9 files changed, 1006 insertions(+), 50 deletions(-) create mode 100644 kernel/kernel/devices/pci/scan.cpp create mode 100644 kernel/kernel/devices/pci/scan.hpp create mode 100644 kernel/kernel/devices/pci/scan.tests.cpp create mode 100644 kernel/kernel/test_support/devices/pci/ecam_builder.cpp create mode 100644 kernel/kernel/test_support/devices/pci/ecam_builder.hpp create mode 100644 kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp (limited to 'kernel') diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index df65ed20..7f418c61 100644 --- a/kernel/CMakeLists.txt +++ b/kernel/CMakeLists.txt @@ -45,6 +45,7 @@ target_sources("kernel_lib" PRIVATE "kernel/devices/init.cpp" "kernel/devices/pci/ecam_segment.cpp" "kernel/devices/pci/init.cpp" + "kernel/devices/pci/scan.cpp" "kernel/devices/pseudo.cpp" "kernel/devices/storage.cpp" diff --git a/kernel/kernel/devices/pci/init.cpp b/kernel/kernel/devices/pci/init.cpp index 05f5e7d1..6abf758c 100644 --- a/kernel/kernel/devices/pci/init.cpp +++ b/kernel/kernel/devices/pci/init.cpp @@ -1,12 +1,13 @@ #include #include -#include +#include +#include #include -#include #include +#include #include #include @@ -15,68 +16,43 @@ namespace kernel::devices::pci { - namespace + auto init() -> void { + auto descriptors = kapi::devices::get_pci_express_segment_descriptors(); + + if (descriptors.empty()) + { + return; + } + + kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", descriptors.size()); - auto enumerate(kapi::devices::pcie_segment_descriptor const & descriptor) -> void + for (auto const & descriptor : descriptors) { auto segment = ecam_segment{descriptor}; for (std::size_t bus = segment.first_bus(); segment.contains(bus); ++bus) { - // Note: ecam_segment::contains(...) == true guarantees the bus number fits in a uint8_t - auto bus_window = segment.map_bus(static_cast(bus)); - - if (!bus_window) + auto functions = scan_bus(segment, static_cast(bus)); + if (!functions) { - kstd::println("[OS:DEV] Failed to map MMIO window for bus {}", bus); - continue; - } - - for (std::uint8_t device = 0; device < devices_per_bus; ++device) - { - auto device_base = function_offset(device, 0); - auto device_vendor_id = bus_window->read(device_base + vendor_id_register_offset); - if (device_vendor_id == invalid_vendor_id) + if (functions.error() == kstd::errc::not_enough_memory) { - continue; + kstd::println(kstd::print_sink::stderr, "[OS:DEV] Failed to map MMIO window for bus {}", bus); } - - auto device_header_type = bus_window->read(device_base + header_type_register_offset); - auto function_count = (device_header_type & 0x80) ? functions_per_device : 1u; - - for (std::uint8_t function = 0; function < function_count; ++function) + else { - auto function_base = function_offset(device, function); - auto function_vendor_id = bus_window->read(function_base + vendor_id_register_offset); - if (function_vendor_id == invalid_vendor_id) - { - continue; - } - - auto function_device_id = bus_window->read(function_base + device_id_register_offset); - kstd::println("[OS:DEV] Detected PCI Express device: {:04x}:{:02x}:{:02x}.{:1} [{:04x}:{:04x}]", - segment.group(), bus, device, function, function_vendor_id, function_device_id); + kstd::println(kstd::print_sink::stderr, "[OS:DEV] Failed to scan bus {}: {}", bus, functions.error()); } + continue; } - } - } - - } // namespace - - auto init() -> void - { - auto segments = kapi::devices::get_pci_express_segment_descriptors(); - - if (segments.empty()) - { - return; - } - kstd::println("[OS:DEV] Detected number of PCI Express segments: {}", segments.size()); - for (auto & segment : segments) - { - enumerate(segment); + for (auto const & function : *functions) + { + kstd::println("[OS:DEV] Detected PCI Express device: {} [{:04x}:{:04x}]", function.address, + function.vendor_id, function.device_id); + } + } } } diff --git a/kernel/kernel/devices/pci/registers.hpp b/kernel/kernel/devices/pci/registers.hpp index 2e426be1..98136070 100644 --- a/kernel/kernel/devices/pci/registers.hpp +++ b/kernel/kernel/devices/pci/registers.hpp @@ -43,6 +43,18 @@ namespace kernel::devices::pci //! The offset of the device ID register within the PCI configuration space. constexpr auto inline device_id_register_offset = kstd::bytes{0x02}; + //! The offset of the revision ID register within the PCI configuration space. + constexpr auto inline revision_id_register_offset = kstd::bytes{0x08}; + + //! The offset of the programming interface register within the PCI configuration space. + constexpr auto inline programming_interface_register_offset = kstd::bytes{0x09}; + + //! The offset of the subclass register within the PCI configuration space. + constexpr auto inline subclass_register_offset = kstd::bytes{0x0a}; + + //! The offset of the class code register within the PCI configuration space. + constexpr auto inline class_code_register_offset = kstd::bytes{0x0b}; + //! The offset of the header type register within the PCI configuration space. constexpr auto inline header_type_register_offset = kstd::bytes{0x0e}; diff --git a/kernel/kernel/devices/pci/scan.cpp b/kernel/kernel/devices/pci/scan.cpp new file mode 100644 index 00000000..1cad8b4e --- /dev/null +++ b/kernel/kernel/devices/pci/scan.cpp @@ -0,0 +1,97 @@ +#include + +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +namespace kernel::devices::pci +{ + + namespace + { + + auto read_function(kapi::memory::mmio_window const & ecam_window, std::uint16_t group, std::uint8_t bus, + std::uint8_t device, std::uint8_t number) -> std::optional + { + auto offset = function_offset(device, number); + + auto vendor_id = ecam_window.read(offset + vendor_id_register_offset); + if (vendor_id == invalid_vendor_id) + { + return std::nullopt; + } + + auto device_id = ecam_window.read(offset + device_id_register_offset); + auto revision = ecam_window.read(offset + revision_id_register_offset); + auto programming_interface = ecam_window.read(offset + programming_interface_register_offset); + auto class_code = ecam_window.read(offset + class_code_register_offset); + auto subclass = ecam_window.read(offset + subclass_register_offset); + auto header_type = ecam_window.read(offset + header_type_register_offset); + + return function_info{ + .address = {.segment_group = group, .bus = bus, .device = device, .function = number}, + .vendor_id = vendor_id, + .device_id = device_id, + .revision = revision, + .programming_interface = programming_interface, + .subclass_code = subclass, + .class_code = class_code, + .raw_header_type = header_type + }; + } + + } // namespace + + auto scan_bus(ecam_segment const & segment, std::uint8_t bus_number) -> kstd::result> + { + auto bus = segment.map_bus(bus_number); + + if (!bus) + { + return kstd::failure(bus.error()); + } + + auto functions = kstd::vector{}; + + for (std::uint8_t device = 0; device < devices_per_bus; ++device) + { + for (std::uint8_t function = 0; function < functions_per_device; ++function) + { + auto maybe_function = read_function(*bus, segment.group(), bus_number, device, function); + if (!maybe_function) + { + // According to the PCI specification, a valid device must have a function 0. + if (function == 0) + { + break; + } + continue; + } + + functions.push_back(*maybe_function); + + // The "multifunction" bit is only valid for function 0, otherwise it should be ignored. + if (function == 0) + { + auto is_multifunction_device = maybe_function->is_multifunction(); + if (!is_multifunction_device) + { + break; + } + } + } + } + + return kstd::success(std::move(functions)); + } + +} // namespace kernel::devices::pci diff --git a/kernel/kernel/devices/pci/scan.hpp b/kernel/kernel/devices/pci/scan.hpp new file mode 100644 index 00000000..1c10d979 --- /dev/null +++ b/kernel/kernel/devices/pci/scan.hpp @@ -0,0 +1,29 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_SCAN_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_SCAN_HPP + +#include +#include + +#include +#include + +#include + +namespace kernel::devices::pci +{ + + //! Scan a given PCI bus within a given ECAM segment. + //! + //! This function scans the specified PCI bus within the given ECAM segment for available functions. All found + //! functions are returned in ascending address order. Functions violating the PCI specification area + //! + //! @param segment The ECAM segment to scan. + //! @param bus_number The PCI bus number to scan. + //! @return A vector of function_info objects representing the functions found on the bus on success, an error + //! otherwise + [[nodiscard]] auto scan_bus(ecam_segment const & segment, std::uint8_t bus_number) + -> kstd::result>; + +} // namespace kernel::devices::pci + +#endif diff --git a/kernel/kernel/devices/pci/scan.tests.cpp b/kernel/kernel/devices/pci/scan.tests.cpp new file mode 100644 index 00000000..8915e2e0 --- /dev/null +++ b/kernel/kernel/devices/pci/scan.tests.cpp @@ -0,0 +1,449 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include + +#include + +using kernel::tests::devices::pci::ecam_builder; + +namespace +{ + constexpr auto test_ecam_base = kapi::memory::physical_address{}; + + constexpr auto vendor_id_ati = 0x1002; + constexpr auto vendor_id_amd = 0x1022; + + constexpr auto device_id_radeon_ai_pro_r9700 = 0x7551; + constexpr auto device_id_fch_sata_controller = 0x7901; + constexpr auto device_id_hdmi_dp_audio_controller = 0xab40; + + constexpr auto programming_interface_vga_controller = 0x00; + constexpr auto programming_interface_ahci_controller = 0x01; + constexpr auto programming_interface_hda_compatible_controller = 0x00; + + constexpr auto revision_id_c0 = 0xc0; + constexpr auto revision_id_51 = 0x51; + + constexpr auto subclass_code_vga_compatible_controller = 0x00; + constexpr auto subclass_code_audio_device = 0x03; + constexpr auto subclass_code_ahci_controller = 0x06; + + constexpr auto class_code_mass_storage_controller = 0x01; + constexpr auto class_code_multimedia_controller = 0x04; + constexpr auto class_code_display_controller = 0x03; + + constexpr auto header_type_multifunction = 0x80; + constexpr auto header_type_endpoint = 0x00; + + constexpr auto distinct_vendor_id = 0x1234; + constexpr auto distinct_device_id = 0x5678; + constexpr auto distinct_revision_id = 0x11; + constexpr auto distinct_programming_interface = 0x22; + constexpr auto distinct_subclass_code = 0x33; + constexpr auto distinct_class_code = 0x44; + + constexpr auto devices_per_bus = 32; + + auto build_amd_fch_sata_controller(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + { + builder.function(bus, device, 0) + .vendor_id(vendor_id_amd) + .device_id(device_id_fch_sata_controller) + .revision_id(revision_id_51) + .programming_interface(programming_interface_ahci_controller) + .subclass_code(subclass_code_ahci_controller) + .class_code(class_code_mass_storage_controller) + .header_type(header_type_endpoint); + } + + auto build_amd_ai_pro_r9700(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + { + builder.function(bus, device, 0) + .vendor_id(vendor_id_ati) + .device_id(device_id_radeon_ai_pro_r9700) + .revision_id(revision_id_c0) + .programming_interface(programming_interface_vga_controller) + .subclass_code(subclass_code_vga_compatible_controller) + .class_code(class_code_display_controller) + .header_type(header_type_multifunction | header_type_endpoint) + .function(bus, device, 1) + .vendor_id(vendor_id_ati) + .device_id(device_id_hdmi_dp_audio_controller) + .programming_interface(programming_interface_hda_compatible_controller) + .subclass_code(subclass_code_audio_device) + .class_code(class_code_multimedia_controller) + .header_type(header_type_endpoint); + } + + auto build_amd_ai_pro_r9700_disjoint(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + { + builder.function(bus, device, 0) + .vendor_id(vendor_id_ati) + .device_id(device_id_radeon_ai_pro_r9700) + .revision_id(revision_id_c0) + .programming_interface(programming_interface_vga_controller) + .subclass_code(subclass_code_vga_compatible_controller) + .class_code(class_code_display_controller) + .header_type(header_type_multifunction | header_type_endpoint) + .function(bus, device, 2) + .vendor_id(vendor_id_ati) + .device_id(device_id_hdmi_dp_audio_controller) + .programming_interface(programming_interface_hda_compatible_controller) + .subclass_code(subclass_code_audio_device) + .class_code(class_code_multimedia_controller) + .header_type(header_type_endpoint) + .function(bus, device, 7) + .vendor_id(vendor_id_ati) + .device_id(device_id_hdmi_dp_audio_controller) + .programming_interface(programming_interface_hda_compatible_controller) + .subclass_code(subclass_code_audio_device) + .class_code(class_code_multimedia_controller) + .header_type(header_type_endpoint); + } + + auto build_corrupt_single_function_device(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + { + builder.function(bus, device, 1) + .vendor_id(vendor_id_amd) + .device_id(device_id_fch_sata_controller) + .revision_id(revision_id_51) + .programming_interface(programming_interface_ahci_controller) + .subclass_code(subclass_code_ahci_controller) + .class_code(class_code_mass_storage_controller) + .header_type(header_type_endpoint); + } + + auto build_single_function_device_with_stray_function(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + { + build_amd_fch_sata_controller(builder, bus, device); + builder.function(bus, device, 1) + .vendor_id(vendor_id_amd) + .device_id(device_id_fch_sata_controller) + .header_type(header_type_endpoint); + } + + auto make_ecam_segment(std::uint16_t group, std::uint8_t first_bus, std::uint8_t bus_count) + -> kernel::devices::pci::ecam_segment + { + auto descriptor = kapi::devices::pcie_segment_descriptor{.base_address = test_ecam_base, + .group_number = group, + .first_bus = first_bus, + .bus_count = bus_count}; + return kernel::devices::pci::ecam_segment{descriptor}; + } + + auto make_oob_ecam_segment(std::uint16_t group, std::uint8_t first_bus, std::uint8_t bus_count) + -> kernel::devices::pci::ecam_segment + { + auto descriptor = + kapi::devices::pcie_segment_descriptor{.base_address = test_ecam_base + kernel::tests::memory::mmio_size, + .group_number = group, + .first_bus = first_bus, + .bus_count = bus_count}; + return kernel::devices::pci::ecam_segment{descriptor}; + } +} // namespace + +SCENARIO("Scanning PCI buses") +{ + GIVEN("An empty PCI bus") + { + auto builder = ecam_builder{}; + builder.clear(0); + + THEN("scanning the bus finds no devices") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->empty()); + } + } + + GIVEN("A PCI bus with a single single-function device") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_amd_fch_sata_controller(builder, 0, 1); + + THEN("scanning the bus finds the single function") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 1); + + auto const & device = devices->at(0); + + REQUIRE(device.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 1, .function = 0}); + REQUIRE(device.vendor_id == vendor_id_amd); + REQUIRE(device.device_id == device_id_fch_sata_controller); + REQUIRE(device.class_code == class_code_mass_storage_controller); + REQUIRE(device.subclass_code == subclass_code_ahci_controller); + REQUIRE(device.programming_interface == programming_interface_ahci_controller); + REQUIRE(device.revision == revision_id_51); + REQUIRE(device.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(!device.is_multifunction()); + } + } + + GIVEN("A PCI bus with a single multi-function device") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_amd_ai_pro_r9700(builder, 0, 2); + + THEN("scanning the bus finds all functions of the multi-function device") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 2); + + auto const & first = devices->at(0); + + REQUIRE(first.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 2, .function = 0}); + REQUIRE(first.vendor_id == vendor_id_ati); + REQUIRE(first.device_id == device_id_radeon_ai_pro_r9700); + REQUIRE(first.class_code == class_code_display_controller); + REQUIRE(first.subclass_code == subclass_code_vga_compatible_controller); + REQUIRE(first.programming_interface == programming_interface_vga_controller); + REQUIRE(first.revision == revision_id_c0); + REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(first.is_multifunction()); + + auto const & second = devices->at(1); + + REQUIRE(second.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 2, .function = 1}); + REQUIRE(second.vendor_id == vendor_id_ati); + REQUIRE(second.device_id == device_id_hdmi_dp_audio_controller); + REQUIRE(second.class_code == class_code_multimedia_controller); + REQUIRE(second.subclass_code == subclass_code_audio_device); + REQUIRE(second.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(second.type() == kernel::devices::pci::header_type::endpoint); + } + } + + GIVEN("A PCI bus with a single multi-function device with disjoint functions") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_amd_ai_pro_r9700_disjoint(builder, 0, 0); + + THEN("scanning the bus finds all functions of the multi-function device") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 3); + + auto const & first = devices->at(0); + + REQUIRE(first.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 0}); + REQUIRE(first.vendor_id == vendor_id_ati); + REQUIRE(first.device_id == device_id_radeon_ai_pro_r9700); + REQUIRE(first.class_code == class_code_display_controller); + REQUIRE(first.subclass_code == subclass_code_vga_compatible_controller); + REQUIRE(first.programming_interface == programming_interface_vga_controller); + REQUIRE(first.revision == revision_id_c0); + REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(first.is_multifunction()); + + auto const & second = devices->at(1); + + REQUIRE(second.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 2}); + REQUIRE(second.vendor_id == vendor_id_ati); + REQUIRE(second.device_id == device_id_hdmi_dp_audio_controller); + REQUIRE(second.class_code == class_code_multimedia_controller); + REQUIRE(second.subclass_code == subclass_code_audio_device); + REQUIRE(second.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(second.type() == kernel::devices::pci::header_type::endpoint); + + auto const & third = devices->at(2); + + REQUIRE(third.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 7}); + REQUIRE(third.vendor_id == vendor_id_ati); + REQUIRE(third.device_id == device_id_hdmi_dp_audio_controller); + REQUIRE(third.class_code == class_code_multimedia_controller); + REQUIRE(third.subclass_code == subclass_code_audio_device); + REQUIRE(third.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(third.type() == kernel::devices::pci::header_type::endpoint); + } + } + + GIVEN("A PCI bus with a single corrupt single-function device") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_corrupt_single_function_device(builder, 0, 3); + + THEN("scanning the bus finds no devices") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->empty()); + } + } + + GIVEN("A PCI bus with two single-function devices at the extremes") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_amd_fch_sata_controller(builder, 0, 0); + build_amd_fch_sata_controller(builder, 0, devices_per_bus - 1); + + THEN("scanning the bus finds both devices") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 2); + + auto const & first = devices->at(0); + + REQUIRE(first.address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 0}); + REQUIRE(first.vendor_id == vendor_id_amd); + REQUIRE(first.device_id == device_id_fch_sata_controller); + REQUIRE(first.class_code == class_code_mass_storage_controller); + REQUIRE(first.subclass_code == subclass_code_ahci_controller); + REQUIRE(first.programming_interface == programming_interface_ahci_controller); + REQUIRE(first.revision == revision_id_51); + REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(!first.is_multifunction()); + + auto const & last = devices->at(1); + + REQUIRE(last.address == kernel::devices::pci::function_address{.segment_group = 0, + .bus = 0, + .device = devices_per_bus - 1, + .function = 0}); + REQUIRE(last.vendor_id == vendor_id_amd); + REQUIRE(last.device_id == device_id_fch_sata_controller); + REQUIRE(last.class_code == class_code_mass_storage_controller); + REQUIRE(last.subclass_code == subclass_code_ahci_controller); + REQUIRE(last.programming_interface == programming_interface_ahci_controller); + REQUIRE(last.revision == revision_id_51); + REQUIRE(last.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(!last.is_multifunction()); + } + } + + GIVEN("A PCI function with a different value in every identification register") + { + auto builder = ecam_builder{}; + builder.clear(0); + builder.function(0, 4, 0) + .vendor_id(distinct_vendor_id) + .device_id(distinct_device_id) + .revision_id(distinct_revision_id) + .programming_interface(distinct_programming_interface) + .subclass_code(distinct_subclass_code) + .class_code(distinct_class_code) + .header_type(header_type_endpoint); + + THEN("each register is read into the matching field") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 1); + + auto const & function = devices->at(0); + + REQUIRE(function.vendor_id == distinct_vendor_id); + REQUIRE(function.device_id == distinct_device_id); + REQUIRE(function.revision == distinct_revision_id); + REQUIRE(function.programming_interface == distinct_programming_interface); + REQUIRE(function.subclass_code == distinct_subclass_code); + REQUIRE(function.class_code == distinct_class_code); + } + } + + GIVEN("A PCI bus with a single-function device and a stray function 1 next to it") + { + auto builder = ecam_builder{}; + builder.clear(0); + build_single_function_device_with_stray_function(builder, 0, 6); + + THEN("scanning the bus finds only function 0") + { + auto ecam_segment = make_ecam_segment(0, 0, 255); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(devices); + REQUIRE(devices->size() == 1); + + REQUIRE(devices->at(0).address == + kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 6, .function = 0}); + } + } + + GIVEN("A device on a bus other than bus 0 in a segment group other than 0") + { + auto builder = ecam_builder{}; + builder.clear(2); + build_amd_fch_sata_controller(builder, 2, 5); + + THEN("the address of the function carries the segment group and the bus") + { + auto ecam_segment = make_ecam_segment(3, 0, 4); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 2); + + REQUIRE(devices); + REQUIRE(devices->size() == 1); + + REQUIRE(devices->at(0).address == + kernel::devices::pci::function_address{.segment_group = 3, .bus = 2, .device = 5, .function = 0}); + } + } + + GIVEN("A bus number outside the segment") + { + THEN("scanning fails with Invalid Argument") + { + auto ecam_segment = make_ecam_segment(0, 0, 32); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 64); + + REQUIRE(!devices); + REQUIRE(devices.error() == kstd::errc::invalid_argument); + } + } + + GIVEN("A bus outside the MMIO space") + { + THEN("scanning fails with Not Enough Memory") + { + auto ecam_segment = make_oob_ecam_segment(0, 0, 32); + auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + + REQUIRE(!devices); + REQUIRE(devices.error() == kstd::errc::not_enough_memory); + } + } +} diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.cpp b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp new file mode 100644 index 00000000..78b0b32c --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp @@ -0,0 +1,106 @@ +#include + +#include + +#include + +#include + +#include +#include + +using kapi::memory::mmio_window; + +namespace kernel::tests::devices::pci +{ + + ecam_builder::function_builder::function_builder(ecam_builder & root, std::uint8_t bus, std::uint8_t device, + std::uint8_t number) + : m_root(&root) + , m_window(root.window_for(bus, device, number)) + {} + + auto ecam_builder::function_builder::vendor_id(std::uint16_t id) -> function_builder & + { + m_window.write(vendor_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::device_id(std::uint16_t id) -> function_builder & + { + m_window.write(device_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::class_code(std::uint8_t code) -> function_builder & + { + m_window.write(class_code_offset, code); + return *this; + } + + auto ecam_builder::function_builder::header_type(std::uint8_t type) -> function_builder & + { + m_window.write(header_type_offset, type); + return *this; + } + + auto ecam_builder::function_builder::subclass_code(std::uint8_t id) -> function_builder & + { + m_window.write(subclass_code_offset, id); + return *this; + } + + auto ecam_builder::function_builder::programming_interface(std::uint8_t id) -> function_builder & + { + m_window.write(programming_interface_offset, id); + return *this; + } + + auto ecam_builder::function_builder::revision_id(std::uint8_t id) -> function_builder & + { + m_window.write(revision_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::function(std::uint8_t bus, std::uint8_t device, std::uint8_t number) + -> function_builder + { + return m_root->function(bus, device, number); + } + + auto ecam_builder::clear(std::uint8_t bus) -> void + { + for (std::uint8_t device_number = 0; device_number < max_devices_per_bus; ++device_number) + { + for (std::uint8_t function_number = 0; function_number < max_functions_per_device; ++function_number) + { + auto window = window_for(bus, device_number, function_number); + for (auto offset = kstd::bytes{0}; offset < pci_function_size; offset += kstd::bytes{8}) + { + window.write(offset, pci_clear_pattern); + } + } + } + } + + auto ecam_builder::function(std::uint8_t bus, std::uint8_t device, std::uint8_t number) -> function_builder + { + return function_builder(*this, bus, device, number); + } + + auto ecam_builder::window_for(std::uint8_t bus_number, std::uint8_t device_number, std::uint8_t function_number) + -> kapi::memory::mmio_window + { + REQUIRE(device_number < max_devices_per_bus); + REQUIRE(function_number < max_functions_per_device); + + auto address = base + ((bus_number << bus_number_address_shift) | (device_number << device_number_address_shift) | + (function_number << function_number_address_shift)); + auto window = mmio_window::map(address, pci_function_size, mmio_window::access::writable); + + REQUIRE(window); + + return std::move(*window); + } + +} // namespace kernel::tests::devices::pci diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.hpp b/kernel/kernel/test_support/devices/pci/ecam_builder.hpp new file mode 100644 index 00000000..31334959 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.hpp @@ -0,0 +1,124 @@ +#ifndef TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_BUILDER_HPP +#define TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_BUILDER_HPP + +#include + +#include + +#include + +namespace kernel::tests::devices::pci +{ + + //! A builder for constructing PCI ECAM data for testing purposes. + struct ecam_builder + { + constexpr auto static pci_clear_pattern = 0xffff'ffff'ffff'ffff; + + constexpr auto static bus_number_address_shift = 20; + constexpr auto static device_number_address_shift = 15; + constexpr auto static function_number_address_shift = 12; + + constexpr auto static max_devices_per_bus = 32; + constexpr auto static max_functions_per_device = 8; + constexpr auto static pci_function_size = kstd::KiB(4u); + + constexpr auto static vendor_id_offset = kstd::bytes{0x00}; + constexpr auto static device_id_offset = kstd::bytes{0x02}; + constexpr auto static revision_id_offset = kstd::bytes{0x08}; + constexpr auto static programming_interface_offset = kstd::bytes{0x09}; + constexpr auto static subclass_code_offset = kstd::bytes{0x0a}; + constexpr auto static class_code_offset = kstd::bytes{0x0b}; + constexpr auto static header_type_offset = kstd::bytes{0x0e}; + + struct function_builder + { + explicit function_builder(ecam_builder & root, std::uint8_t bus, std::uint8_t device, std::uint8_t number); + + function_builder(function_builder const &) = delete; + auto operator=(function_builder const &) -> function_builder & = delete; + function_builder(function_builder &&) = delete; + auto operator=(function_builder &&) -> function_builder & = delete; + + //! Set the vendor ID for this function. + //! + //! @param id The vendor ID to set. + //! @return A reference to this function builder. + auto vendor_id(std::uint16_t id) -> function_builder &; + + //! Set the device ID for this function. + //! + //! @param id The device ID to set. + //! @return A reference to this function builder. + auto device_id(std::uint16_t id) -> function_builder &; + + //! Set the class code for this function. + //! + //! @param code The class code to set. + //! @return A reference to this function builder. + auto class_code(std::uint8_t code) -> function_builder &; + + //! Set the header type for this function. + //! + //! @param type The header type to set. + //! @return A reference to this function builder. + auto header_type(std::uint8_t type) -> function_builder &; + + //! Set the subclass code for this function. + //! + //! @param id The subclass code to set. + //! @return A reference to this function builder. + auto subclass_code(std::uint8_t id) -> function_builder &; + + //! Set the programming interface for this function. + //! + //! @param id The programming interface to set. + //! @return A reference to this function builder. + auto programming_interface(std::uint8_t id) -> function_builder &; + + //! Set the revision ID for this function. + //! + //! @param id The revision ID to set. + //! @return A reference to this function builder. + auto revision_id(std::uint8_t id) -> function_builder &; + + //! Begin building another function. + //! + //! @param bus The bus number the device is attached to. + //! @param device The device number on the bus. + //! @param number The function number of the device. + //! @return A function builder for the specified function. + [[nodiscard]] auto function(std::uint8_t bus, std::uint8_t device, std::uint8_t number) -> function_builder; + + private: + ecam_builder * m_root; + kapi::memory::mmio_window m_window; + }; + + //! Fill a full bus ECAM space with 0xff + auto clear(std::uint8_t bus) -> void; + + //! Begin building a function on the specified bus and device. + //! + //! @param bus The bus number the device is attached to. + //! @param device The device number on the bus. + //! @param number The function number of the device. + //! @return A function builder for the specified function. + [[nodiscard]] auto function(std::uint8_t bus, std::uint8_t device, std::uint8_t number) -> function_builder; + + kapi::memory::physical_address base; + + private: + //! Create an MMIO window for the specified bus, device, and function number. + //! + //! @param bus_number The bus number the device is attached to. + //! @param device_number The number of the device on the bus. + //! @param function_number The number of the function on the device. + //! @return An MMIO window into the ECAM space for the specified function. + [[nodiscard]] auto window_for(std::uint8_t bus_number, std::uint8_t device_number, std::uint8_t function_number) + -> kapi::memory::mmio_window; + }; + +} // namespace kernel::tests::devices::pci + +#endif // TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_BUILDER_HPP diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp b/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp new file mode 100644 index 00000000..0ca6af69 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp @@ -0,0 +1,162 @@ +#include + +#include + +#include + +#include +#include + +#include +#include + +using kernel::tests::devices::pci::ecam_builder; +using mmio_window = kapi::memory::mmio_window; + +namespace +{ + constexpr auto test_ecam_base = kapi::memory::physical_address{}; + constexpr auto bytes_per_function = kstd::KiB(4u); + constexpr auto bytes_per_device = 8 * bytes_per_function; + constexpr auto bytes_per_bus = 32 * bytes_per_device; + + constexpr auto test_vendor = 0x1234; + constexpr auto test_device = 0x5678; + + constexpr auto test_class_display_ctrl = 0x03; + constexpr auto test_subclass_vga = 0x00; + constexpr auto test_prog_if_8514 = 0x01; + constexpr auto test_revision = 0x04; + constexpr auto test_header_type_endpoint = 0x00; + constexpr auto test_multifunction = 0x80; +} // namespace + +SCENARIO("Building PCI ECAM structures using the ecam_builder", "[smoke][devices][pci]") +{ + GIVEN("An ECAM builder") + { + ecam_builder builder{.base = test_ecam_base}; + + WHEN("clearing a bus") + { + builder.clear(1); + + THEN("the previous bus is unaffected") + { + auto base = test_ecam_base; + auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(kstd::bytes{}) == 0); + REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0); + } + + THEN("the bus is cleared") + { + auto base = test_ecam_base + bytes_per_bus; + auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(kstd::bytes{}) == 0xffff'ffff); + REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0xffff'ffff); + } + + THEN("the next bus is unaffected") + { + auto base = test_ecam_base + 2 * bytes_per_bus; + auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(kstd::bytes{}) == 0); + REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0); + } + } + + WHEN("building a function") + { + auto const [bus, device, function] = GENERATE(std::tuple{1, 0, 0}, std::tuple{1, 2, 1}, std::tuple{3, 31, 7}); + + builder.clear(1); + + builder.function(bus, device, function) + .vendor_id(test_vendor) + .device_id(test_device) + .class_code(test_class_display_ctrl) + .subclass_code(test_subclass_vga) + .programming_interface(test_prog_if_8514) + .header_type(test_header_type_endpoint | test_multifunction) + .revision_id(test_revision); + + THEN("the values are written correctly") + { + auto base = test_ecam_base + bus * bytes_per_bus + device * bytes_per_device + function * bytes_per_function; + auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window->read(ecam_builder::device_id_offset) == test_device); + REQUIRE(window->read(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window->read(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window->read(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window->read(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window->read(ecam_builder::header_type_offset) == + (test_header_type_endpoint | test_multifunction)); + } + } + + WHEN("chaining function builders") + { + auto const [bus, device, function] = GENERATE(std::tuple{1, 2, 1}, std::tuple{3, 31, 7}); + + builder.clear(1); + + builder.function(1, 0, 0) + .vendor_id(0) + .device_id(0) + .class_code(0) + .subclass_code(0) + .programming_interface(0) + .header_type(0) + .revision_id(0) + .function(bus, device, function) + .vendor_id(test_vendor) + .device_id(test_device) + .class_code(test_class_display_ctrl) + .subclass_code(test_subclass_vga) + .programming_interface(test_prog_if_8514) + .header_type(test_header_type_endpoint | test_multifunction) + .revision_id(test_revision); + + THEN("the values are written correctly") + { + auto base = test_ecam_base + bus * bytes_per_bus + device * bytes_per_device + function * bytes_per_function; + auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window->read(ecam_builder::device_id_offset) == test_device); + REQUIRE(window->read(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window->read(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window->read(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window->read(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window->read(ecam_builder::header_type_offset) == + (test_header_type_endpoint | test_multifunction)); + } + + THEN("the first function is unchanged") + { + auto base = test_ecam_base + bytes_per_bus; + auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); + REQUIRE(window); + + REQUIRE(window->read(ecam_builder::vendor_id_offset) == 0); + REQUIRE(window->read(ecam_builder::device_id_offset) == 0); + REQUIRE(window->read(ecam_builder::class_code_offset) == 0); + REQUIRE(window->read(ecam_builder::subclass_code_offset) == 0); + REQUIRE(window->read(ecam_builder::programming_interface_offset) == 0); + REQUIRE(window->read(ecam_builder::revision_id_offset) == 0); + REQUIRE(window->read(ecam_builder::header_type_offset) == 0); + } + } + } +} -- cgit v1.2.3 From 3a628ca1fcc1799c55de2635024ac178961cf702 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 23 Nov 2026 12:19:54 +0100 Subject: tests: let ecam_builder set bridge bus numbers This change extends the ecam_builder to support additional configuration data for PCI bridges, namely the secondary and subordinate bus numbers. This extension is required to support upcoming PCI bridge walk tests by allowing the tests to configure PCI bridge topologies. The builder test reads both of the new bus numbers to verify they are set correctly. Additionally, this change introduces a new test support function in kstd, called require_ok. require_ok asserts that a kstd::result contains a success value and moves that value out of the result. In the case of a failed result, the source location of the require_ok call as well as the error message are reported and the test case is aborted. Both ecam_builder::window_for and the ecam_builder tests use this new function. --- .../test_support/devices/pci/ecam_builder.cpp | 17 ++++- .../test_support/devices/pci/ecam_builder.hpp | 14 ++++ .../devices/pci/ecam_builder.tests.cpp | 88 +++++++++++----------- 3 files changed, 73 insertions(+), 46 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.cpp b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp index 78b0b32c..a9bb1256 100644 --- a/kernel/kernel/test_support/devices/pci/ecam_builder.cpp +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp @@ -2,6 +2,7 @@ #include +#include #include #include @@ -62,6 +63,18 @@ namespace kernel::tests::devices::pci return *this; } + auto ecam_builder::function_builder::secondary_bus(std::uint8_t id) -> function_builder & + { + m_window.write(secondary_bus_offset, id); + return *this; + } + + auto ecam_builder::function_builder::subordinate_bus(std::uint8_t id) -> function_builder & + { + m_window.write(subordinate_bus_offset, id); + return *this; + } + auto ecam_builder::function_builder::function(std::uint8_t bus, std::uint8_t device, std::uint8_t number) -> function_builder { @@ -98,9 +111,7 @@ namespace kernel::tests::devices::pci (function_number << function_number_address_shift)); auto window = mmio_window::map(address, pci_function_size, mmio_window::access::writable); - REQUIRE(window); - - return std::move(*window); + return kstd::tests::require_ok(std::move(window)); } } // namespace kernel::tests::devices::pci diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.hpp b/kernel/kernel/test_support/devices/pci/ecam_builder.hpp index 31334959..3c0cf036 100644 --- a/kernel/kernel/test_support/devices/pci/ecam_builder.hpp +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.hpp @@ -30,6 +30,8 @@ namespace kernel::tests::devices::pci constexpr auto static subclass_code_offset = kstd::bytes{0x0a}; constexpr auto static class_code_offset = kstd::bytes{0x0b}; constexpr auto static header_type_offset = kstd::bytes{0x0e}; + constexpr auto static secondary_bus_offset = kstd::bytes{0x19}; + constexpr auto static subordinate_bus_offset = kstd::bytes{0x1a}; struct function_builder { @@ -82,6 +84,18 @@ namespace kernel::tests::devices::pci //! @return A reference to this function builder. auto revision_id(std::uint8_t id) -> function_builder &; + //! Set the secondary bus number for this function. + //! + //! @param id The secondary bus number to set. + //! @return A reference to this function builder. + auto secondary_bus(std::uint8_t id) -> function_builder &; + + //! Set the subordinate bus number for this function. + //! + //! @param id The subordinate bus number to set. + //! @return A reference to this function builder. + auto subordinate_bus(std::uint8_t id) -> function_builder &; + //! Begin building another function. //! //! @param bus The bus number the device is attached to. diff --git a/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp b/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp index 0ca6af69..3b300581 100644 --- a/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp @@ -2,6 +2,7 @@ #include +#include #include #include @@ -12,6 +13,7 @@ using kernel::tests::devices::pci::ecam_builder; using mmio_window = kapi::memory::mmio_window; +using kstd::tests::require_ok; namespace { @@ -29,6 +31,8 @@ namespace constexpr auto test_revision = 0x04; constexpr auto test_header_type_endpoint = 0x00; constexpr auto test_multifunction = 0x80; + constexpr auto test_secondary_bus = 0xa0; + constexpr auto test_subordinate_bus = 0xa1; } // namespace SCENARIO("Building PCI ECAM structures using the ecam_builder", "[smoke][devices][pci]") @@ -44,31 +48,28 @@ SCENARIO("Building PCI ECAM structures using the ecam_builder", "[smoke][devices THEN("the previous bus is unaffected") { auto base = test_ecam_base; - auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); - REQUIRE(window); + auto window = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); - REQUIRE(window->read(kstd::bytes{}) == 0); - REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0); + REQUIRE(window.read(kstd::bytes{}) == 0); + REQUIRE(window.read(bytes_per_bus - kstd::bytes{4}) == 0); } THEN("the bus is cleared") { auto base = test_ecam_base + bytes_per_bus; - auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); - REQUIRE(window); + auto window = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); - REQUIRE(window->read(kstd::bytes{}) == 0xffff'ffff); - REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0xffff'ffff); + REQUIRE(window.read(kstd::bytes{}) == 0xffff'ffff); + REQUIRE(window.read(bytes_per_bus - kstd::bytes{4}) == 0xffff'ffff); } THEN("the next bus is unaffected") { auto base = test_ecam_base + 2 * bytes_per_bus; - auto window = mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only); - REQUIRE(window); + auto window = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); - REQUIRE(window->read(kstd::bytes{}) == 0); - REQUIRE(window->read(bytes_per_bus - kstd::bytes{4}) == 0); + REQUIRE(window.read(kstd::bytes{}) == 0); + REQUIRE(window.read(bytes_per_bus - kstd::bytes{4}) == 0); } } @@ -85,22 +86,25 @@ SCENARIO("Building PCI ECAM structures using the ecam_builder", "[smoke][devices .subclass_code(test_subclass_vga) .programming_interface(test_prog_if_8514) .header_type(test_header_type_endpoint | test_multifunction) - .revision_id(test_revision); + .revision_id(test_revision) + .secondary_bus(test_secondary_bus) + .subordinate_bus(test_subordinate_bus); THEN("the values are written correctly") { auto base = test_ecam_base + bus * bytes_per_bus + device * bytes_per_device + function * bytes_per_function; - auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); - REQUIRE(window); - - REQUIRE(window->read(ecam_builder::vendor_id_offset) == test_vendor); - REQUIRE(window->read(ecam_builder::device_id_offset) == test_device); - REQUIRE(window->read(ecam_builder::class_code_offset) == test_class_display_ctrl); - REQUIRE(window->read(ecam_builder::subclass_code_offset) == test_subclass_vga); - REQUIRE(window->read(ecam_builder::programming_interface_offset) == test_prog_if_8514); - REQUIRE(window->read(ecam_builder::revision_id_offset) == test_revision); - REQUIRE(window->read(ecam_builder::header_type_offset) == + auto window = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window.read(ecam_builder::device_id_offset) == test_device); + REQUIRE(window.read(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window.read(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window.read(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window.read(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window.read(ecam_builder::header_type_offset) == (test_header_type_endpoint | test_multifunction)); + REQUIRE(window.read(ecam_builder::secondary_bus_offset) == test_secondary_bus); + REQUIRE(window.read(ecam_builder::subordinate_bus_offset) == test_subordinate_bus); } } @@ -130,32 +134,30 @@ SCENARIO("Building PCI ECAM structures using the ecam_builder", "[smoke][devices THEN("the values are written correctly") { auto base = test_ecam_base + bus * bytes_per_bus + device * bytes_per_device + function * bytes_per_function; - auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); - REQUIRE(window); - - REQUIRE(window->read(ecam_builder::vendor_id_offset) == test_vendor); - REQUIRE(window->read(ecam_builder::device_id_offset) == test_device); - REQUIRE(window->read(ecam_builder::class_code_offset) == test_class_display_ctrl); - REQUIRE(window->read(ecam_builder::subclass_code_offset) == test_subclass_vga); - REQUIRE(window->read(ecam_builder::programming_interface_offset) == test_prog_if_8514); - REQUIRE(window->read(ecam_builder::revision_id_offset) == test_revision); - REQUIRE(window->read(ecam_builder::header_type_offset) == + auto window = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window.read(ecam_builder::device_id_offset) == test_device); + REQUIRE(window.read(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window.read(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window.read(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window.read(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window.read(ecam_builder::header_type_offset) == (test_header_type_endpoint | test_multifunction)); } THEN("the first function is unchanged") { auto base = test_ecam_base + bytes_per_bus; - auto window = mmio_window::map(base, bytes_per_function, mmio_window::access::read_only); - REQUIRE(window); - - REQUIRE(window->read(ecam_builder::vendor_id_offset) == 0); - REQUIRE(window->read(ecam_builder::device_id_offset) == 0); - REQUIRE(window->read(ecam_builder::class_code_offset) == 0); - REQUIRE(window->read(ecam_builder::subclass_code_offset) == 0); - REQUIRE(window->read(ecam_builder::programming_interface_offset) == 0); - REQUIRE(window->read(ecam_builder::revision_id_offset) == 0); - REQUIRE(window->read(ecam_builder::header_type_offset) == 0); + auto window = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read(ecam_builder::vendor_id_offset) == 0); + REQUIRE(window.read(ecam_builder::device_id_offset) == 0); + REQUIRE(window.read(ecam_builder::class_code_offset) == 0); + REQUIRE(window.read(ecam_builder::subclass_code_offset) == 0); + REQUIRE(window.read(ecam_builder::programming_interface_offset) == 0); + REQUIRE(window.read(ecam_builder::revision_id_offset) == 0); + REQUIRE(window.read(ecam_builder::header_type_offset) == 0); } } } -- cgit v1.2.3 From 9232d36e9d4bf1329602ca5f6460eff699f24764 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 23 Nov 2026 12:43:50 +0100 Subject: tests: introduce ecam_fixture for PCI scan tests This change introduces the ecam_fixture to support and simplify writing of PCI scan tests. The ecam_fixture ensures that every leaf starts out with an empty ECAM space by filling the MMIO space with 0xff to ensure all vendor IDs read as 0xffff (the invalid vendor ID). The fixture uses the new kernel::tests::memory::fill_mmio seam function, via simulated_memory::fill, to fill the MMIO space. Clearing four buses per leaf through the builder made the scan scenario take about 3.2 s. Filling the backing memory brings it to about 38 ms. In support of the new fixture type, this change also introduces the following vocabulary additions in kernel::tests::devices::pci: - function_spec - ecam_fixture::place - ecam_fixture::endpoint - ecam_fixture::bridge - ecam_fixture::multifunction - ecam_fixture::make_descriptor - function_location - addresses - addresses_of The existing scan tests now use the ecam_fixture and the new vocabulary additions in their implementation. The function factories of the test suite now return function_spec objects to describe the PCI functions and allow them to be adjusted inside a test case using the new vocabulary functions. --- kernel/kernel/devices/pci/scan.tests.cpp | 319 ++++++++------------- .../test_support/devices/pci/ecam_fixture.cpp | 64 +++++ .../test_support/devices/pci/ecam_fixture.hpp | 73 +++++ .../devices/pci/function_addresses.cpp | 30 ++ .../devices/pci/function_addresses.hpp | 40 +++ .../test_support/devices/pci/function_spec.hpp | 26 ++ kernel/kernel/test_support/kapi/memory.cpp | 8 +- kernel/kernel/test_support/memory.hpp | 9 +- kernel/kernel/test_support/simulated_memory.cpp | 9 +- kernel/kernel/test_support/simulated_memory.hpp | 7 +- 10 files changed, 386 insertions(+), 199 deletions(-) create mode 100644 kernel/kernel/test_support/devices/pci/ecam_fixture.cpp create mode 100644 kernel/kernel/test_support/devices/pci/ecam_fixture.hpp create mode 100644 kernel/kernel/test_support/devices/pci/function_addresses.cpp create mode 100644 kernel/kernel/test_support/devices/pci/function_addresses.hpp create mode 100644 kernel/kernel/test_support/devices/pci/function_spec.hpp (limited to 'kernel') diff --git a/kernel/kernel/devices/pci/scan.tests.cpp b/kernel/kernel/devices/pci/scan.tests.cpp index 8915e2e0..c5c2e6d6 100644 --- a/kernel/kernel/devices/pci/scan.tests.cpp +++ b/kernel/kernel/devices/pci/scan.tests.cpp @@ -3,24 +3,26 @@ #include #include #include -#include +#include +#include #include #include -#include #include +#include #include #include -using kernel::tests::devices::pci::ecam_builder; +using kernel::devices::pci::ecam_segment; +using kernel::devices::pci::function_address; +using kernel::tests::devices::pci::function_spec; +using kstd::tests::require_ok; namespace { - constexpr auto test_ecam_base = kapi::memory::physical_address{}; - constexpr auto vendor_id_ati = 0x1002; constexpr auto vendor_id_amd = 0x1022; @@ -43,7 +45,6 @@ namespace constexpr auto class_code_multimedia_controller = 0x04; constexpr auto class_code_display_controller = 0x03; - constexpr auto header_type_multifunction = 0x80; constexpr auto header_type_endpoint = 0x00; constexpr auto distinct_vendor_id = 0x1234; @@ -55,141 +56,80 @@ namespace constexpr auto devices_per_bus = 32; - auto build_amd_fch_sata_controller(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) - { - builder.function(bus, device, 0) - .vendor_id(vendor_id_amd) - .device_id(device_id_fch_sata_controller) - .revision_id(revision_id_51) - .programming_interface(programming_interface_ahci_controller) - .subclass_code(subclass_code_ahci_controller) - .class_code(class_code_mass_storage_controller) - .header_type(header_type_endpoint); - } - - auto build_amd_ai_pro_r9700(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) - { - builder.function(bus, device, 0) - .vendor_id(vendor_id_ati) - .device_id(device_id_radeon_ai_pro_r9700) - .revision_id(revision_id_c0) - .programming_interface(programming_interface_vga_controller) - .subclass_code(subclass_code_vga_compatible_controller) - .class_code(class_code_display_controller) - .header_type(header_type_multifunction | header_type_endpoint) - .function(bus, device, 1) - .vendor_id(vendor_id_ati) - .device_id(device_id_hdmi_dp_audio_controller) - .programming_interface(programming_interface_hda_compatible_controller) - .subclass_code(subclass_code_audio_device) - .class_code(class_code_multimedia_controller) - .header_type(header_type_endpoint); - } - - auto build_amd_ai_pro_r9700_disjoint(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + auto amd_fch_sata_controller(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 0) -> function_spec { - builder.function(bus, device, 0) - .vendor_id(vendor_id_ati) - .device_id(device_id_radeon_ai_pro_r9700) - .revision_id(revision_id_c0) - .programming_interface(programming_interface_vga_controller) - .subclass_code(subclass_code_vga_compatible_controller) - .class_code(class_code_display_controller) - .header_type(header_type_multifunction | header_type_endpoint) - .function(bus, device, 2) - .vendor_id(vendor_id_ati) - .device_id(device_id_hdmi_dp_audio_controller) - .programming_interface(programming_interface_hda_compatible_controller) - .subclass_code(subclass_code_audio_device) - .class_code(class_code_multimedia_controller) - .header_type(header_type_endpoint) - .function(bus, device, 7) - .vendor_id(vendor_id_ati) - .device_id(device_id_hdmi_dp_audio_controller) - .programming_interface(programming_interface_hda_compatible_controller) - .subclass_code(subclass_code_audio_device) - .class_code(class_code_multimedia_controller) - .header_type(header_type_endpoint); + return function_spec{ + .bus = bus, + .device = device, + .function = function, + .vendor_id = vendor_id_amd, + .device_id = device_id_fch_sata_controller, + .class_code = class_code_mass_storage_controller, + .subclass_code = subclass_code_ahci_controller, + .programming_interface = programming_interface_ahci_controller, + .revision = revision_id_51, + }; } - auto build_corrupt_single_function_device(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + auto amd_ai_pro_r9700_vga(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 0) -> function_spec { - builder.function(bus, device, 1) - .vendor_id(vendor_id_amd) - .device_id(device_id_fch_sata_controller) - .revision_id(revision_id_51) - .programming_interface(programming_interface_ahci_controller) - .subclass_code(subclass_code_ahci_controller) - .class_code(class_code_mass_storage_controller) - .header_type(header_type_endpoint); + return function_spec{ + .bus = bus, + .device = device, + .function = function, + .vendor_id = vendor_id_ati, + .device_id = device_id_radeon_ai_pro_r9700, + .class_code = class_code_display_controller, + .subclass_code = subclass_code_vga_compatible_controller, + .programming_interface = programming_interface_vga_controller, + .revision = revision_id_c0, + }; } - auto build_single_function_device_with_stray_function(ecam_builder & builder, std::uint8_t bus, std::uint8_t device) + auto amd_ai_pro_r9700_audio(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 1) -> function_spec { - build_amd_fch_sata_controller(builder, bus, device); - builder.function(bus, device, 1) - .vendor_id(vendor_id_amd) - .device_id(device_id_fch_sata_controller) - .header_type(header_type_endpoint); + return function_spec{ + .bus = bus, + .device = device, + .function = function, + .vendor_id = vendor_id_ati, + .device_id = device_id_hdmi_dp_audio_controller, + .class_code = class_code_multimedia_controller, + .subclass_code = subclass_code_audio_device, + .programming_interface = programming_interface_hda_compatible_controller, + .revision = revision_id_c0, + }; } - auto make_ecam_segment(std::uint16_t group, std::uint8_t first_bus, std::uint8_t bus_count) - -> kernel::devices::pci::ecam_segment - { - auto descriptor = kapi::devices::pcie_segment_descriptor{.base_address = test_ecam_base, - .group_number = group, - .first_bus = first_bus, - .bus_count = bus_count}; - return kernel::devices::pci::ecam_segment{descriptor}; - } - - auto make_oob_ecam_segment(std::uint16_t group, std::uint8_t first_bus, std::uint8_t bus_count) - -> kernel::devices::pci::ecam_segment - { - auto descriptor = - kapi::devices::pcie_segment_descriptor{.base_address = test_ecam_base + kernel::tests::memory::mmio_size, - .group_number = group, - .first_bus = first_bus, - .bus_count = bus_count}; - return kernel::devices::pci::ecam_segment{descriptor}; - } } // namespace -SCENARIO("Scanning PCI buses") +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Scanning PCI buses", "[devices][pci]") { GIVEN("An empty PCI bus") { - auto builder = ecam_builder{}; - builder.clear(0); - THEN("scanning the bus finds no devices") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->empty()); + REQUIRE(devices.empty()); } } GIVEN("A PCI bus with a single single-function device") { - auto builder = ecam_builder{}; - builder.clear(0); - build_amd_fch_sata_controller(builder, 0, 1); + place(endpoint(amd_fch_sata_controller(0, 1))); THEN("scanning the bus finds the single function") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->size() == 1); + REQUIRE(devices.size() == 1); - auto const & device = devices->at(0); + auto const & device = devices.at(0); - REQUIRE(device.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 1, .function = 0}); + REQUIRE(device.address == function_address{.segment_group = 0, .bus = 0, .device = 1, .function = 0}); REQUIRE(device.vendor_id == vendor_id_amd); REQUIRE(device.device_id == device_id_fch_sata_controller); REQUIRE(device.class_code == class_code_mass_storage_controller); @@ -203,22 +143,22 @@ SCENARIO("Scanning PCI buses") GIVEN("A PCI bus with a single multi-function device") { - auto builder = ecam_builder{}; - builder.clear(0); - build_amd_ai_pro_r9700(builder, 0, 2); + constexpr auto bus = std::uint8_t{0}; + constexpr auto device = std::uint8_t{2}; + + place(multifunction(endpoint(amd_ai_pro_r9700_vga(bus, device)))); + place(endpoint(amd_ai_pro_r9700_audio(bus, device))); THEN("scanning the bus finds all functions of the multi-function device") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->size() == 2); + REQUIRE(devices.size() == 2); - auto const & first = devices->at(0); + auto const & first = devices.at(0); - REQUIRE(first.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 2, .function = 0}); + REQUIRE(first.address == function_address{.segment_group = 0, .bus = bus, .device = device, .function = 0}); REQUIRE(first.vendor_id == vendor_id_ati); REQUIRE(first.device_id == device_id_radeon_ai_pro_r9700); REQUIRE(first.class_code == class_code_display_controller); @@ -228,37 +168,38 @@ SCENARIO("Scanning PCI buses") REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); REQUIRE(first.is_multifunction()); - auto const & second = devices->at(1); + auto const & second = devices.at(1); - REQUIRE(second.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 2, .function = 1}); + REQUIRE(second.address == function_address{.segment_group = 0, .bus = bus, .device = device, .function = 1}); REQUIRE(second.vendor_id == vendor_id_ati); REQUIRE(second.device_id == device_id_hdmi_dp_audio_controller); REQUIRE(second.class_code == class_code_multimedia_controller); REQUIRE(second.subclass_code == subclass_code_audio_device); REQUIRE(second.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(second.revision == revision_id_c0); REQUIRE(second.type() == kernel::devices::pci::header_type::endpoint); } } GIVEN("A PCI bus with a single multi-function device with disjoint functions") { - auto builder = ecam_builder{}; - builder.clear(0); - build_amd_ai_pro_r9700_disjoint(builder, 0, 0); + constexpr auto bus = std::uint8_t{0}; + constexpr auto device = std::uint8_t{0}; + + place(multifunction(endpoint(amd_ai_pro_r9700_vga(bus, device)))); + place(endpoint(amd_ai_pro_r9700_audio(bus, device, 2))); + place(endpoint(amd_ai_pro_r9700_audio(bus, device, 7))); THEN("scanning the bus finds all functions of the multi-function device") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, bus)); - REQUIRE(devices); - REQUIRE(devices->size() == 3); + REQUIRE(devices.size() == 3); - auto const & first = devices->at(0); + auto const & first = devices.at(0); - REQUIRE(first.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 0}); + REQUIRE(first.address == function_address{.segment_group = 0, .bus = bus, .device = device, .function = 0}); REQUIRE(first.vendor_id == vendor_id_ati); REQUIRE(first.device_id == device_id_radeon_ai_pro_r9700); REQUIRE(first.class_code == class_code_display_controller); @@ -268,65 +209,60 @@ SCENARIO("Scanning PCI buses") REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); REQUIRE(first.is_multifunction()); - auto const & second = devices->at(1); + auto const & second = devices.at(1); - REQUIRE(second.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 2}); + REQUIRE(second.address == function_address{.segment_group = 0, .bus = bus, .device = device, .function = 2}); REQUIRE(second.vendor_id == vendor_id_ati); REQUIRE(second.device_id == device_id_hdmi_dp_audio_controller); REQUIRE(second.class_code == class_code_multimedia_controller); REQUIRE(second.subclass_code == subclass_code_audio_device); REQUIRE(second.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(second.revision == revision_id_c0); REQUIRE(second.type() == kernel::devices::pci::header_type::endpoint); - auto const & third = devices->at(2); + auto const & third = devices.at(2); - REQUIRE(third.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 7}); + REQUIRE(third.address == function_address{.segment_group = 0, .bus = bus, .device = device, .function = 7}); REQUIRE(third.vendor_id == vendor_id_ati); REQUIRE(third.device_id == device_id_hdmi_dp_audio_controller); REQUIRE(third.class_code == class_code_multimedia_controller); REQUIRE(third.subclass_code == subclass_code_audio_device); REQUIRE(third.programming_interface == programming_interface_hda_compatible_controller); + REQUIRE(third.revision == revision_id_c0); REQUIRE(third.type() == kernel::devices::pci::header_type::endpoint); } } GIVEN("A PCI bus with a single corrupt single-function device") { - auto builder = ecam_builder{}; - builder.clear(0); - build_corrupt_single_function_device(builder, 0, 3); + place(endpoint(amd_fch_sata_controller(0, 3, 1))); THEN("scanning the bus finds no devices") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->empty()); + REQUIRE(devices.empty()); } } GIVEN("A PCI bus with two single-function devices at the extremes") { - auto builder = ecam_builder{}; - builder.clear(0); - build_amd_fch_sata_controller(builder, 0, 0); - build_amd_fch_sata_controller(builder, 0, devices_per_bus - 1); + constexpr auto bus = std::uint8_t{0}; + + place(endpoint(amd_fch_sata_controller(bus, 0))); + place(endpoint(amd_fch_sata_controller(bus, devices_per_bus - 1))); THEN("scanning the bus finds both devices") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->size() == 2); + REQUIRE(devices.size() == 2); - auto const & first = devices->at(0); + auto const & first = devices.at(0); - REQUIRE(first.address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 0}); + REQUIRE(first.address == function_address{.segment_group = 0, .bus = bus, .device = 0, .function = 0}); REQUIRE(first.vendor_id == vendor_id_amd); REQUIRE(first.device_id == device_id_fch_sata_controller); REQUIRE(first.class_code == class_code_mass_storage_controller); @@ -336,12 +272,10 @@ SCENARIO("Scanning PCI buses") REQUIRE(first.type() == kernel::devices::pci::header_type::endpoint); REQUIRE(!first.is_multifunction()); - auto const & last = devices->at(1); + auto const & last = devices.at(1); - REQUIRE(last.address == kernel::devices::pci::function_address{.segment_group = 0, - .bus = 0, - .device = devices_per_bus - 1, - .function = 0}); + REQUIRE(last.address == + function_address{.segment_group = 0, .bus = bus, .device = devices_per_bus - 1, .function = 0}); REQUIRE(last.vendor_id == vendor_id_amd); REQUIRE(last.device_id == device_id_fch_sata_controller); REQUIRE(last.class_code == class_code_mass_storage_controller); @@ -355,8 +289,6 @@ SCENARIO("Scanning PCI buses") GIVEN("A PCI function with a different value in every identification register") { - auto builder = ecam_builder{}; - builder.clear(0); builder.function(0, 4, 0) .vendor_id(distinct_vendor_id) .device_id(distinct_device_id) @@ -368,13 +300,12 @@ SCENARIO("Scanning PCI buses") THEN("each register is read into the matching field") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->size() == 1); + REQUIRE(devices.size() == 1); - auto const & function = devices->at(0); + auto const & function = devices.at(0); REQUIRE(function.vendor_id == distinct_vendor_id); REQUIRE(function.device_id == distinct_device_id); @@ -387,39 +318,36 @@ SCENARIO("Scanning PCI buses") GIVEN("A PCI bus with a single-function device and a stray function 1 next to it") { - auto builder = ecam_builder{}; - builder.clear(0); - build_single_function_device_with_stray_function(builder, 0, 6); + constexpr auto bus = std::uint8_t{0u}; + constexpr auto device = std::uint8_t{6u}; + + place(endpoint(amd_fch_sata_controller(bus, device, 0))); + place(endpoint(amd_fch_sata_controller(bus, device, 1))); THEN("scanning the bus finds only function 0") { - auto ecam_segment = make_ecam_segment(0, 0, 255); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); - REQUIRE(devices); - REQUIRE(devices->size() == 1); + REQUIRE(devices.size() == 1); - REQUIRE(devices->at(0).address == - kernel::devices::pci::function_address{.segment_group = 0, .bus = 0, .device = 6, .function = 0}); + REQUIRE(devices.at(0).address == + function_address{.segment_group = 0, .bus = bus, .device = device, .function = 0}); } } GIVEN("A device on a bus other than bus 0 in a segment group other than 0") { - auto builder = ecam_builder{}; - builder.clear(2); - build_amd_fch_sata_controller(builder, 2, 5); + place(amd_fch_sata_controller(2, 5)); THEN("the address of the function carries the segment group and the bus") { - auto ecam_segment = make_ecam_segment(3, 0, 4); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 2); + auto segment = ecam_segment{make_descriptor(3, 0, 4)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 2)); - REQUIRE(devices); - REQUIRE(devices->size() == 1); + REQUIRE(devices.size() == 1); - REQUIRE(devices->at(0).address == - kernel::devices::pci::function_address{.segment_group = 3, .bus = 2, .device = 5, .function = 0}); + REQUIRE(devices.at(0).address == function_address{.segment_group = 3, .bus = 2, .device = 5, .function = 0}); } } @@ -427,8 +355,8 @@ SCENARIO("Scanning PCI buses") { THEN("scanning fails with Invalid Argument") { - auto ecam_segment = make_ecam_segment(0, 0, 32); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 64); + auto segment = ecam_segment{make_descriptor(0, 0, 32)}; + auto devices = kernel::devices::pci::scan_bus(segment, 64); REQUIRE(!devices); REQUIRE(devices.error() == kstd::errc::invalid_argument); @@ -439,8 +367,11 @@ SCENARIO("Scanning PCI buses") { THEN("scanning fails with Not Enough Memory") { - auto ecam_segment = make_oob_ecam_segment(0, 0, 32); - auto devices = kernel::devices::pci::scan_bus(ecam_segment, 0); + auto descriptor = make_descriptor(0, 0, 32); + descriptor.base_address = builder.base + kernel::tests::memory::mmio_size; + + auto segment = ecam_segment{descriptor}; + auto devices = kernel::devices::pci::scan_bus(segment, 0); REQUIRE(!devices); REQUIRE(devices.error() == kstd::errc::not_enough_memory); diff --git a/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp b/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp new file mode 100644 index 00000000..402d5eb3 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp @@ -0,0 +1,64 @@ +#include + +#include +#include + +#include + +#include +#include + +namespace kernel::tests::devices::pci +{ + + auto ecam_fixture::endpoint(function_spec spec) -> function_spec + { + spec.header_type &= 0x80; + return spec; + } + + auto ecam_fixture::bridge(function_spec spec, std::uint8_t secondary, std::uint8_t subordinate) -> function_spec + { + spec.header_type = (spec.header_type & 0x80) | 0x01; + spec.class_code = 0x06; + spec.subclass_code = 0x04; + spec.secondary_bus = secondary; + spec.subordinate_bus = subordinate; + return spec; + } + + auto ecam_fixture::multifunction(function_spec spec) -> function_spec + { + spec.header_type |= 0x80; + return spec; + } + + ecam_fixture::ecam_fixture() + { + kernel::tests::memory::fill_mmio(std::byte{0xff}); + } + + auto ecam_fixture::make_descriptor(std::uint16_t group, std::uint8_t first_bus, std::size_t count) + -> kapi::devices::pcie_segment_descriptor + { + return kapi::devices::pcie_segment_descriptor{.base_address = builder.base, + .group_number = group, + .first_bus = first_bus, + .bus_count = count}; + } + + auto ecam_fixture::place(function_spec const & spec) -> void + { + builder.function(spec.bus, spec.device, spec.function) + .vendor_id(spec.vendor_id) + .device_id(spec.device_id) + .class_code(spec.class_code) + .subclass_code(spec.subclass_code) + .programming_interface(spec.programming_interface) + .revision_id(spec.revision) + .header_type(spec.header_type) + .secondary_bus(spec.secondary_bus) + .subordinate_bus(spec.subordinate_bus); + } + +} // namespace kernel::tests::devices::pci diff --git a/kernel/kernel/test_support/devices/pci/ecam_fixture.hpp b/kernel/kernel/test_support/devices/pci/ecam_fixture.hpp new file mode 100644 index 00000000..adbadb76 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_fixture.hpp @@ -0,0 +1,73 @@ +#ifndef TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_FIXTURE_HPP +#define TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_FIXTURE_HPP + +#include +#include +#include + +#include + +#include + +#include +#include +#include + +namespace kernel::tests::devices::pci +{ + + struct ecam_fixture + { + //! The maximum number of PCI buses supported by this fixture. + //! + //! The value scales with the amount of available simulated MMIO space. + constexpr auto static max_number_of_buses = std::min(kernel::tests::memory::mmio_size / kstd::MiB(1u), 256uz); + + //! Apply the "endpoint" type to the given function specification. + //! + //! @param spec The function specification to modify. + //! @return The modified function specification. + [[nodiscard]] auto static endpoint(function_spec spec = {}) -> function_spec; + + //! Apply the "bridge" type to the given function specification. + //! + //! @param spec The function specification to modify. + //! @param secondary The secondary bus number for the bridge. + //! @param subordinate The subordinate bus number for the bridge. + //! @return The modified function specification. + [[nodiscard]] auto static bridge(function_spec spec, std::uint8_t secondary, std::uint8_t subordinate) + -> function_spec; + + //! Apply the "multifunction" flag to the given function specification. + //! + //! @param spec The function specification to modify. + //! @return The modified function specification. + [[nodiscard]] auto static multifunction(function_spec spec) -> function_spec; + + //! Construct a new ECAM fixture. + //! + //! This constructor clears all MMIO memory. + ecam_fixture(); + + //! Create a new PCI segment descriptor. + //! + //! @param group The PCI segment group number. + //! @param first_bus The first bus number in the segment. + //! @param count The number of buses in the segment. + //! @return The constructed PCI segment descriptor. + [[nodiscard]] auto make_descriptor(std::uint16_t group = 0, std::uint8_t first_bus = 0, + std::size_t count = max_number_of_buses) + -> kapi::devices::pcie_segment_descriptor; + + //! Place a PCI function according to the given specification. + //! + //! @param spec The function specification describing the PCI function to place. + auto place(function_spec const & spec) -> void; + + //! The ECAM builder used to construct the PCI configuration space. + ecam_builder builder{}; + }; + +} // namespace kernel::tests::devices::pci + +#endif diff --git a/kernel/kernel/test_support/devices/pci/function_addresses.cpp b/kernel/kernel/test_support/devices/pci/function_addresses.cpp new file mode 100644 index 00000000..bdc93b7f --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/function_addresses.cpp @@ -0,0 +1,30 @@ +#include + +#include +#include + +#include + +#include +#include +#include +#include + +namespace kernel::tests::devices::pci +{ + + auto addresses(kstd::vector const & functions) + -> std::vector + { + return {std::from_range, std::views::transform(functions, [](auto const & info) { return info.address; })}; + } + + auto addresses_of(std::initializer_list list, std::uint16_t group) + -> std::vector + { + return {std::from_range, std::views::transform(list, [group](auto const & loc) { + return kernel::devices::pci::function_address{group, loc.bus, loc.device, loc.function}; + })}; + } + +} // namespace kernel::tests::devices::pci diff --git a/kernel/kernel/test_support/devices/pci/function_addresses.hpp b/kernel/kernel/test_support/devices/pci/function_addresses.hpp new file mode 100644 index 00000000..64fff6e5 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/function_addresses.hpp @@ -0,0 +1,40 @@ +#ifndef TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_FUNCTION_ADDRESSES_HPP +#define TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_FUNCTION_ADDRESSES_HPP + +#include +#include + +#include + +#include +#include +#include + +namespace kernel::tests::devices::pci +{ + + struct function_location + { + std::uint8_t bus{}; + std::uint8_t device{}; + std::uint8_t function{}; + }; + + //! Extract the function addresses from a list of function info structures. + //! + //! @param functions The list of function info structures. + //! @return A vector of function addresses corresponding to the input functions. + auto addresses(kstd::vector const & functions) + -> std::vector; + + //! Create a list of function addresses from a list of function locations. + //! + //! @param list The list of function locations. + //! @param group The group identifier to use for all function addresses. + //! @return A vector of function addresses corresponding to the input locations. + auto addresses_of(std::initializer_list list, std::uint16_t group = 0) + -> std::vector; + +} // namespace kernel::tests::devices::pci + +#endif diff --git a/kernel/kernel/test_support/devices/pci/function_spec.hpp b/kernel/kernel/test_support/devices/pci/function_spec.hpp new file mode 100644 index 00000000..e240322a --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/function_spec.hpp @@ -0,0 +1,26 @@ +#ifndef TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_FUNCTION_SPEC_HPP +#define TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_FUNCTION_SPEC_HPP + +#include +namespace kernel::tests::devices::pci +{ + + struct function_spec + { + std::uint8_t bus{}; + std::uint8_t device{}; + std::uint8_t function{}; + std::uint16_t vendor_id{0x1234}; // NOLINT(readability-magic-numbers) + std::uint16_t device_id{0x5678}; // NOLINT(readability-magic-numbers) + std::uint8_t class_code{}; + std::uint8_t subclass_code{}; + std::uint8_t programming_interface{}; + std::uint8_t revision{}; + std::uint8_t header_type{}; + std::uint8_t secondary_bus{}; + std::uint8_t subordinate_bus{}; + }; + +} // namespace kernel::tests::devices::pci + +#endif diff --git a/kernel/kernel/test_support/kapi/memory.cpp b/kernel/kernel/test_support/kapi/memory.cpp index 78b24f43..75f987bd 100644 --- a/kernel/kernel/test_support/kapi/memory.cpp +++ b/kernel/kernel/test_support/kapi/memory.cpp @@ -6,6 +6,7 @@ #include +#include #include namespace @@ -67,4 +68,9 @@ namespace kernel::tests::memory return test_mapper->memory.virtual_base(); } -} // namespace kernel::tests::memory \ No newline at end of file + auto fill_mmio(std::byte value) -> void + { + test_mapper->mmio.fill(value); + } + +} // namespace kernel::tests::memory diff --git a/kernel/kernel/test_support/memory.hpp b/kernel/kernel/test_support/memory.hpp index 8565a53a..87530ce5 100644 --- a/kernel/kernel/test_support/memory.hpp +++ b/kernel/kernel/test_support/memory.hpp @@ -5,6 +5,8 @@ #include +#include + namespace kernel::tests::memory { @@ -33,6 +35,11 @@ namespace kernel::tests::memory //! Deinitialize the memory subsystem. auto deinit() -> void; + //! Fill MMIO memory with the given value. + //! + //! @param value The bit pattern to fill the MMIO memory with. + auto fill_mmio(std::byte value) -> void; + //! Get the virtual base address of the simulated system. //! //! Since we do not have direct access to an actual MMU, we simulate the virtual address space by mapping the @@ -43,4 +50,4 @@ namespace kernel::tests::memory } // namespace kernel::tests::memory -#endif \ No newline at end of file +#endif diff --git a/kernel/kernel/test_support/simulated_memory.cpp b/kernel/kernel/test_support/simulated_memory.cpp index b6c3c4d9..e7ad125b 100644 --- a/kernel/kernel/test_support/simulated_memory.cpp +++ b/kernel/kernel/test_support/simulated_memory.cpp @@ -65,7 +65,12 @@ namespace kernel::tests auto simulated_memory::clear() -> void { - std::memset(m_physical_base.get(), 0, m_physical_size.value); + fill(std::byte{0x00}); + } + + auto simulated_memory::fill(std::byte value) -> void + { + std::memset(m_physical_base.get(), static_cast(value), m_physical_size.value); } auto simulated_memory::physical_base() noexcept -> kstd::observer_ptr @@ -105,4 +110,4 @@ namespace kernel::tests return kstd::observer_ptr{static_cast(mapped_ptr)}; } -} // namespace kernel::tests \ No newline at end of file +} // namespace kernel::tests diff --git a/kernel/kernel/test_support/simulated_memory.hpp b/kernel/kernel/test_support/simulated_memory.hpp index 128ef715..87a606d7 100644 --- a/kernel/kernel/test_support/simulated_memory.hpp +++ b/kernel/kernel/test_support/simulated_memory.hpp @@ -34,6 +34,11 @@ namespace kernel::tests //! Clear the contents of the physical memory of this device. auto clear() -> void; + //! Fill the contents of the physical memory of this device with the given value. + //! + //! @param value The bit pattern to fill the memory with. + auto fill(std::byte value) -> void; + //! Get the base address of the physical memory of this device. [[nodiscard]] auto physical_base() noexcept -> kstd::observer_ptr; @@ -67,4 +72,4 @@ namespace kernel::tests } // namespace kernel::tests -#endif \ No newline at end of file +#endif -- cgit v1.2.3 From f19e0ed7f403b22c7e4845bbc3fafd84cc44be3b Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 23 Nov 2026 18:46:47 +0100 Subject: kernel/devices: record PCI bridge information in scan Previously, no special handling was implemented when encountering PCI-to-PCI bridges, thus neither the secondary nor the subordinate bus numbers were recorded. This change extends the function_info type by two fields: secondary_bus and subordinate_bus, in preparation for the upcoming depth-first PCI bus scan. The fields are only read from ECAM space if the PCI function is a PCI-to-PCI bridge (including multifunction bridges), as reported by function_info::type. In all other cases, including CardBus bridges, the fields are set to zero. This change also includes the required constants in registers.hpp. The tests are extended to check that the secondary_bus and subordinate_bus fields are only read for PCI-to-PCI bridges, and left as zero otherwise. --- kernel/kernel/devices/pci/function_info.hpp | 4 ++ kernel/kernel/devices/pci/registers.hpp | 6 ++ kernel/kernel/devices/pci/scan.cpp | 10 +++- kernel/kernel/devices/pci/scan.tests.cpp | 90 +++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 1 deletion(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci/function_info.hpp b/kernel/kernel/devices/pci/function_info.hpp index 199716f5..3e71430e 100644 --- a/kernel/kernel/devices/pci/function_info.hpp +++ b/kernel/kernel/devices/pci/function_info.hpp @@ -65,6 +65,10 @@ namespace kernel::devices::pci std::uint8_t class_code{}; //! The raw (encoded) header type of the PCI function. std::uint8_t raw_header_type{}; + //! The bus attached downstream of this PCI function, if it is a PCI-to-PCI bridge, zero otherwise + std::uint8_t secondary_bus{}; + //! The highest bus number attached downstream of this PCI function, if it is a PCI-to-PCI bridge, zero otherwise. + std::uint8_t subordinate_bus{}; }; } // namespace kernel::devices::pci diff --git a/kernel/kernel/devices/pci/registers.hpp b/kernel/kernel/devices/pci/registers.hpp index 98136070..1caa0baf 100644 --- a/kernel/kernel/devices/pci/registers.hpp +++ b/kernel/kernel/devices/pci/registers.hpp @@ -58,6 +58,12 @@ namespace kernel::devices::pci //! The offset of the header type register within the PCI configuration space. constexpr auto inline header_type_register_offset = kstd::bytes{0x0e}; + //! The offset of the secondary bus register within the PCI configuration space. + constexpr auto inline secondary_bus_register_offset = kstd::bytes{0x19}; + + //! The offset of the subordinate bus register within the PCI configuration space. + constexpr auto inline subordinate_bus_register_offset = kstd::bytes{0x1a}; + } // namespace kernel::devices::pci #endif diff --git a/kernel/kernel/devices/pci/scan.cpp b/kernel/kernel/devices/pci/scan.cpp index 1cad8b4e..da3523ec 100644 --- a/kernel/kernel/devices/pci/scan.cpp +++ b/kernel/kernel/devices/pci/scan.cpp @@ -37,7 +37,7 @@ namespace kernel::devices::pci auto subclass = ecam_window.read(offset + subclass_register_offset); auto header_type = ecam_window.read(offset + header_type_register_offset); - return function_info{ + auto info = function_info{ .address = {.segment_group = group, .bus = bus, .device = device, .function = number}, .vendor_id = vendor_id, .device_id = device_id, @@ -47,6 +47,14 @@ namespace kernel::devices::pci .class_code = class_code, .raw_header_type = header_type }; + + if (info.type() == header_type::pci_to_pci_bridge) + { + info.secondary_bus = ecam_window.read(offset + secondary_bus_register_offset); + info.subordinate_bus = ecam_window.read(offset + subordinate_bus_register_offset); + } + + return info; } } // namespace diff --git a/kernel/kernel/devices/pci/scan.tests.cpp b/kernel/kernel/devices/pci/scan.tests.cpp index c5c2e6d6..ca370533 100644 --- a/kernel/kernel/devices/pci/scan.tests.cpp +++ b/kernel/kernel/devices/pci/scan.tests.cpp @@ -46,6 +46,7 @@ namespace constexpr auto class_code_display_controller = 0x03; constexpr auto header_type_endpoint = 0x00; + constexpr auto header_type_cardbus_bridge = 0x02; constexpr auto distinct_vendor_id = 0x1234; constexpr auto distinct_device_id = 0x5678; @@ -53,6 +54,8 @@ namespace constexpr auto distinct_programming_interface = 0x22; constexpr auto distinct_subclass_code = 0x33; constexpr auto distinct_class_code = 0x44; + constexpr auto distinct_secondary_bus = 0x21; + constexpr auto distinct_subordinate_bus = 0x42; constexpr auto devices_per_bus = 32; @@ -378,3 +381,90 @@ SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Scanning PCI buses", } } } + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Reading bridge bus numbers while scanning PCI buses", + "[devices][pci]") +{ + GIVEN("A PCI-to-PCI bridge with distinct secondary and subordinate bus numbers") + { + place(bridge({.bus = 0, .device = 3}, distinct_secondary_bus, distinct_subordinate_bus)); + + THEN("scanning the bus reports both bus numbers") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(functions.size() == 1); + + auto const & function = functions.at(0); + + REQUIRE(function.type() == kernel::devices::pci::header_type::pci_to_pci_bridge); + REQUIRE(!function.is_multifunction()); + REQUIRE(function.secondary_bus == distinct_secondary_bus); + REQUIRE(function.subordinate_bus == distinct_subordinate_bus); + } + } + + GIVEN("A multi-function PCI-to-PCI bridge") + { + place(multifunction(bridge({.bus = 0, .device = 3}, distinct_secondary_bus, distinct_subordinate_bus))); + + THEN("the multifunction bit does not prevent reading the bus numbers") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(functions.size() == 1); + + auto const & function = functions.at(0); + + REQUIRE(function.type() == kernel::devices::pci::header_type::pci_to_pci_bridge); + REQUIRE(function.is_multifunction()); + REQUIRE(function.secondary_bus == distinct_secondary_bus); + REQUIRE(function.subordinate_bus == distinct_subordinate_bus); + } + } + + GIVEN("An endpoint with non-zero bytes where a bridge would keep its bus numbers") + { + place(endpoint( + {.bus = 0, .device = 3, .secondary_bus = distinct_secondary_bus, .subordinate_bus = distinct_subordinate_bus})); + + THEN("scanning the bus reports zero for both bus numbers") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(functions.size() == 1); + + auto const & function = functions.at(0); + + REQUIRE(function.type() == kernel::devices::pci::header_type::endpoint); + REQUIRE(function.secondary_bus == 0); + REQUIRE(function.subordinate_bus == 0); + } + } + + GIVEN("A CardBus bridge with non-zero bytes where a PCI-to-PCI bridge would keep its bus numbers") + { + place({.bus = 0, + .device = 3, + .header_type = header_type_cardbus_bridge, + .secondary_bus = distinct_secondary_bus, + .subordinate_bus = distinct_subordinate_bus}); + + THEN("scanning the bus reports zero for both bus numbers") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(functions.size() == 1); + + auto const & function = functions.at(0); + + REQUIRE(function.type() == kernel::devices::pci::header_type::cardbus_bridge); + REQUIRE(function.secondary_bus == 0); + REQUIRE(function.subordinate_bus == 0); + } + } +} -- cgit v1.2.3 From c0c6b4a536a825e996fb11f4ae26625253cc0d18 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Mon, 23 Nov 2026 21:38:52 +0100 Subject: kernel/devices: implement depth-first PCI scan This change introduces a new depth-first PCI scan algorithm. This new algorithm is implemented in kernel::devices::pci::scan_segment. The scan traverse the PCI hierarchy by following bridges before moving on to the next device function. The result is a vector that presents the data so that each bridge directly precedes its subordinate devices in the vector. During the traversal, the following preconditions are checked before descending into subordinate devices. - The bridge has a non-zero secondary bus number. - The segment contains the bridge's secondary bus number. - The secondary bus number is greater than the primary bus number. - The subordinate bus range is greater or equal to the secondary bus number. If any of these preconditions are not met, the scan will does not descend down the detected bridge, and a kernel warning is issued. If a bus on a segment has already been scanned, it will not be scanned again and a kernel warning is issued. Additionally, this change transitions the PCI initialization to use the new depth-first scan algorithm, ensuring that the PCI hierarchy is traversed in a consistent and predictable manner. The change adds a set of tests to verify the contract established for scan_segment, including ensuring the correct kernel warnings are issued when preconditions are not met. To support the testing of error messages, the ecam_fixture clears the kernel log buffer before each leaf. A new function, kernel::tests::require_log_message, is introduced to assert the presence of specific log messages in the kernel log buffer. --- kernel/kernel/devices/pci/init.cpp | 34 +- kernel/kernel/devices/pci/scan.cpp | 83 ++++ kernel/kernel/devices/pci/scan.hpp | 15 + kernel/kernel/devices/pci/scan.tests.cpp | 477 +++++++++++++++++++++ kernel/kernel/test_support/cio.hpp | 14 +- .../test_support/devices/pci/ecam_fixture.cpp | 2 + kernel/kernel/test_support/kapi/cio.cpp | 22 +- 7 files changed, 621 insertions(+), 26 deletions(-) (limited to 'kernel') diff --git a/kernel/kernel/devices/pci/init.cpp b/kernel/kernel/devices/pci/init.cpp index 6abf758c..f3efaa87 100644 --- a/kernel/kernel/devices/pci/init.cpp +++ b/kernel/kernel/devices/pci/init.cpp @@ -7,12 +7,8 @@ #include #include -#include #include -#include -#include - namespace kernel::devices::pci { @@ -30,28 +26,18 @@ namespace kernel::devices::pci for (auto const & descriptor : descriptors) { auto segment = ecam_segment{descriptor}; + auto functions = scan_segment(segment); + if (!functions) + { + kstd::println(kstd::print_sink::stderr, "[OS:DEV] Failed to scan segment {}: {}", segment.group(), + functions.error()); + continue; + } - for (std::size_t bus = segment.first_bus(); segment.contains(bus); ++bus) + for (auto const & function : *functions) { - auto functions = scan_bus(segment, static_cast(bus)); - if (!functions) - { - if (functions.error() == kstd::errc::not_enough_memory) - { - kstd::println(kstd::print_sink::stderr, "[OS:DEV] Failed to map MMIO window for bus {}", bus); - } - else - { - kstd::println(kstd::print_sink::stderr, "[OS:DEV] Failed to scan bus {}: {}", bus, functions.error()); - } - continue; - } - - for (auto const & function : *functions) - { - kstd::println("[OS:DEV] Detected PCI Express device: {} [{:04x}:{:04x}]", function.address, - function.vendor_id, function.device_id); - } + kstd::println("[OS:DEV] Detected PCI Express device: {} [{:04x}:{:04x}]", function.address, function.vendor_id, + function.device_id); } } } diff --git a/kernel/kernel/devices/pci/scan.cpp b/kernel/kernel/devices/pci/scan.cpp index da3523ec..0ff7d03e 100644 --- a/kernel/kernel/devices/pci/scan.cpp +++ b/kernel/kernel/devices/pci/scan.cpp @@ -6,10 +6,13 @@ #include +#include #include #include +#include #include +#include #include #include @@ -102,4 +105,84 @@ namespace kernel::devices::pci return kstd::success(std::move(functions)); } + auto scan_segment(ecam_segment const & segment) -> kstd::result> + { + auto root_bus = segment.first_bus(); + if (!segment.contains(root_bus)) + { + return kstd::vector{}; + } + + auto functions = scan_bus(segment, root_bus); + if (!functions) + { + return kstd::failure(functions.error()); + } + + auto scanned_buses = std::bitset::max() + 1>{}; + scanned_buses[root_bus] = true; + + for (auto function = 0uz; function < functions->size(); ++function) + { + auto maybe_bridge = functions->at(function); + if (maybe_bridge.type() != header_type::pci_to_pci_bridge) + { + continue; + } + + auto secondary_bus = maybe_bridge.secondary_bus; + auto subordinate_bus = maybe_bridge.subordinate_bus; + + if (!secondary_bus) + { + kstd::println(kstd::print_sink::stderr, "[OS:DEV] ignoring bridge {} with 0 secondary bus", + maybe_bridge.address); + continue; + } + + if (!segment.contains(secondary_bus)) + { + kstd::println(kstd::print_sink::stderr, "[OS:DEV] ignoring bridge {} with secondary bus {} outside of segment", + maybe_bridge.address, secondary_bus); + continue; + } + + if (secondary_bus <= maybe_bridge.address.bus) + { + kstd::println( + kstd::print_sink::stderr, + "[OS:DEV] ignoring bridge {} with secondary bus {} not greater than the bus the bridge is attached to {}", + maybe_bridge.address, secondary_bus, maybe_bridge.address.bus); + continue; + } + + if (subordinate_bus < secondary_bus) + { + kstd::println(kstd::print_sink::stderr, + "[OS:DEV] ignoring bridge {} with subordinate bus {} less than secondary bus {}", + maybe_bridge.address, subordinate_bus, secondary_bus); + continue; + } + + if (scanned_buses[secondary_bus]) + { + kstd::println(kstd::print_sink::stderr, + "[OS:DEV] ignoring bridge {} with secondary bus {} that has already been scanned", + maybe_bridge.address, secondary_bus); + continue; + } + scanned_buses[secondary_bus] = true; + + auto children = scan_bus(segment, secondary_bus); + if (!children) + { + return kstd::failure(children.error()); + } + + functions->insert_range(functions->begin() + function + 1, std::move(*children)); + } + + return functions; + } + } // namespace kernel::devices::pci diff --git a/kernel/kernel/devices/pci/scan.hpp b/kernel/kernel/devices/pci/scan.hpp index 1c10d979..799a1c09 100644 --- a/kernel/kernel/devices/pci/scan.hpp +++ b/kernel/kernel/devices/pci/scan.hpp @@ -24,6 +24,21 @@ namespace kernel::devices::pci [[nodiscard]] auto scan_bus(ecam_segment const & segment, std::uint8_t bus_number) -> kstd::result>; + //! Scan an entire ECAM segment for available PCI functions. + //! + //! This function recursively scans all buses within the given ECAM segment for available functions. All found + //! functions are returned in topological order, bridges before their children, children in ascending address order. + //! Functions violating the PCI specification are ignored. + //! + //! @note This function currently assumes that there is a single root bus per ECAM segment. Furthermore, it assumes + //! the root bus for a segment is the first bus in that segment. Proper handling of multiple root buses requires an + //! AML interpreter to process the _CRS resource description. + //! + //! @param segment The ECAM segment to scan. + //! @return A vector of function_info objects representing the functions found in the segment on success, an error + //! otherwise + [[nodiscard]] auto scan_segment(ecam_segment const & segment) -> kstd::result>; + } // namespace kernel::devices::pci #endif diff --git a/kernel/kernel/devices/pci/scan.tests.cpp b/kernel/kernel/devices/pci/scan.tests.cpp index ca370533..455a25c5 100644 --- a/kernel/kernel/devices/pci/scan.tests.cpp +++ b/kernel/kernel/devices/pci/scan.tests.cpp @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include #include @@ -14,10 +16,16 @@ #include +#include #include +#include using kernel::devices::pci::ecam_segment; using kernel::devices::pci::function_address; +using kernel::devices::pci::scan_segment; +using kernel::tests::cio::require_log_message; +using kernel::tests::devices::pci::addresses; +using kernel::tests::devices::pci::addresses_of; using kernel::tests::devices::pci::function_spec; using kstd::tests::require_ok; @@ -58,6 +66,7 @@ namespace constexpr auto distinct_subordinate_bus = 0x42; constexpr auto devices_per_bus = 32; + constexpr auto functions_per_device = 8; auto amd_fch_sata_controller(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 0) -> function_spec { @@ -468,3 +477,471 @@ SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Reading bridge bus n } } } + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Walking the bridges of a PCI segment", "[devices][pci]") +{ + GIVEN("A root bus without bridges") + { + place({.bus = 0, .device = 0}); + place({.bus = 0, .device = 1}); + + THEN("the walk finds exactly the functions of the root bus") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {0, 1, 0} + })); + } + } + + GIVEN("A bridge with nothing behind it") + { + place(bridge({.bus = 0, .device = 1}, 1, 1)); + + THEN("the walk finds only the bridge") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 1, 0} + })); + } + } + + GIVEN("A bridge with an endpoint behind it") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place({.bus = 1, .device = 0}); + + THEN("the endpoint follows its bridge") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0} + })); + } + } + + GIVEN("A chain of bridges across all four buses and an endpoint next to the first bridge") + { + place(bridge({.bus = 0, .device = 0}, 1, 3)); + place({.bus = 0, .device = 1}); + place(bridge({.bus = 1, .device = 0}, 2, 3)); + place(bridge({.bus = 2, .device = 0}, 3, 3)); + place({.bus = 3, .device = 0}); + + THEN("the whole chain is listed before the endpoint next to its first bridge") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {2, 0, 0}, + {3, 0, 0}, + {0, 1, 0} + })); + } + } + + GIVEN("Two sibling bridges with an endpoint behind each") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place(bridge({.bus = 0, .device = 1}, 2, 2)); + place({.bus = 1, .device = 0}); + place({.bus = 2, .device = 0}); + + THEN("each bridge is followed by its own subtree before the next sibling") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {0, 1, 0}, + {2, 0, 0} + })); + } + } + + GIVEN("An endpoint on the root bus between two bridges") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place({.bus = 0, .device = 1}); + place(bridge({.bus = 0, .device = 2}, 2, 2)); + place({.bus = 1, .device = 0}); + place({.bus = 2, .device = 0}); + + THEN("the functions of the root bus keep their address order around the subtrees") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {0, 1, 0}, + {0, 2, 0}, + {2, 0, 0} + })); + } + } + + GIVEN("A nested bridge with an endpoint next to it on the same bus") + { + place(bridge({.bus = 0, .device = 0}, 1, 2)); + place(bridge({.bus = 1, .device = 0}, 2, 2)); + place({.bus = 1, .device = 1}); + place({.bus = 2, .device = 0}); + + THEN("the nested subtree is listed before the endpoint that follows its bridge") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {2, 0, 0}, + {1, 1, 0} + })); + } + } + + GIVEN("A segment that starts at bus 1 with a function on bus 0") + { + place({.bus = 0, .device = 0}); + place({.bus = 1, .device = 0}); + place(bridge({.bus = 1, .device = 1}, 2, 2)); + place({.bus = 2, .device = 0}); + + THEN("the walk starts at the first bus of the segment and ignores bus 0") + { + auto segment = ecam_segment{make_descriptor(0, 1, 3)}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {1, 0, 0}, + {1, 1, 0}, + {2, 0, 0} + })); + } + } + + GIVEN("A segment with a segment group other than 0 and a bridge") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place({.bus = 1, .device = 0}); + + THEN("the functions behind the bridge carry the segment group as well") + { + auto segment = ecam_segment{make_descriptor(5, 0, 4)}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of( + { + {0, 0, 0}, + {1, 0, 0} + }, + 5)); + } + } + + GIVEN("A bridge whose subordinate bus number exceeds the buses it leads to") + { + place(bridge({.bus = 0, .device = 0}, 1, 3)); + place({.bus = 1, .device = 0}); + place({.bus = 2, .device = 0}); + place({.bus = 3, .device = 0}); + + THEN("only the secondary bus is scanned") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0} + })); + } + } + + GIVEN("A function on a bus that no bridge leads to") + { + place({.bus = 0, .device = 0}); + place({.bus = 1, .device = 0}); + + THEN("the function is not found") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0} + })); + } + } + + GIVEN("A segment that is empty because its bus count is invalid") + { + place({.bus = 0, .device = 0}); + + THEN("the walk succeeds and finds nothing") + { + auto segment = ecam_segment{make_descriptor(0, 0, 257)}; // NOLINT(readability-magic-numbers) + auto functions = require_ok(scan_segment(segment)); + + require_log_message("[OS:DEV] Invalid PCI bus count '257' for start bus '0'"); + + REQUIRE(functions.empty()); + } + } +} + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Walking a PCI segment with invalid bridges", + "[devices][pci]") +{ + GIVEN("A bridge without a secondary bus number") + { + place(bridge({.bus = 0, .device = 0}, 0, 0)); + place({.bus = 0, .device = 1}); + + THEN("the bridge is skipped and the rest of its bus is still listed") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message("[OS:DEV] ignoring bridge 0000:00:00.0 with 0 secondary bus"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {0, 1, 0} + })); + } + } + + GIVEN("A bridge whose secondary bus lies outside the segment") + { + place(bridge({.bus = 0, .device = 0}, 3, 3)); + place({.bus = 0, .device = 1}); + place({.bus = 3, .device = 0}); + + THEN("the bridge is skipped instead of failing the walk") + { + auto segment = ecam_segment{make_descriptor(0, 0, 2)}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message("[OS:DEV] ignoring bridge 0000:00:00.0 with secondary bus 3 outside of segment"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {0, 1, 0} + })); + } + } + + GIVEN("A bridge on bus 2 whose secondary bus is below its own bus and has not been scanned") + { + place(bridge({.bus = 0, .device = 0}, 2, 2)); + place(bridge({.bus = 2, .device = 0}, 1, 1)); + place({.bus = 1, .device = 0}); + + THEN("the bridge is skipped and the lower bus is never scanned") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message( + "[OS:DEV] ignoring bridge 0000:02:00.0 with secondary bus 1 not greater than the bus the bridge " + "is attached to 2"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {2, 0, 0} + })); + } + } + + GIVEN("A bridge on bus 1 whose secondary bus is its own bus") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place(bridge({.bus = 1, .device = 0}, 1, 1)); + place({.bus = 1, .device = 1}); + + THEN("the bridge is skipped and no function is listed twice") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message( + "[OS:DEV] ignoring bridge 0000:01:00.0 with secondary bus 1 not greater than the bus the bridge " + "is attached to 1"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {1, 1, 0} + })); + } + } + + GIVEN("A bridge whose subordinate bus is below its secondary bus, followed by a valid bridge") + { + place(bridge({.bus = 0, .device = 0}, 1, 0)); + place({.bus = 1, .device = 0}); + place(bridge({.bus = 0, .device = 1}, 2, 2)); + place({.bus = 2, .device = 0}); + + THEN("only the invalid bridge is skipped") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message("[OS:DEV] ignoring bridge 0000:00:00.0 with subordinate bus 0 less than secondary bus 1"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {0, 1, 0}, + {2, 0, 0} + })); + } + } + + GIVEN("Two bridges that lead to the same bus") + { + place(bridge({.bus = 0, .device = 0}, 1, 1)); + place(bridge({.bus = 0, .device = 1}, 1, 1)); + place({.bus = 1, .device = 0}); + + THEN("the bus is listed once, behind the first bridge") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + require_log_message("[OS:DEV] ignoring bridge 0000:00:01.0 with secondary bus 1 that has already been scanned"); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {1, 0, 0}, + {0, 1, 0} + })); + } + } + + GIVEN("A CardBus bridge with non-zero bytes where a PCI-to-PCI bridge would keep its bus numbers") + { + place({.bus = 0, .device = 0, .header_type = header_type_cardbus_bridge, .secondary_bus = 1, .subordinate_bus = 1}); + place({.bus = 0, .device = 1}); + place({.bus = 1, .device = 0}); + + THEN("the CardBus bridge is listed but not descended into") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + + REQUIRE(addresses(functions) == addresses_of({ + {0, 0, 0}, + {0, 1, 0} + })); + } + } +} + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Failing to walk a PCI segment", "[devices][pci]") +{ + GIVEN("A segment whose root bus lies outside the MMIO space") + { + THEN("the walk fails with Not Enough Memory") + { + auto descriptor = make_descriptor(0, 0, 32); + descriptor.base_address = builder.base + kernel::tests::memory::mmio_size; + + auto segment = ecam_segment{descriptor}; + auto functions = scan_segment(segment); + + REQUIRE(!functions); + REQUIRE(functions.error() == kstd::errc::not_enough_memory); + } + } + + GIVEN("A bridge whose secondary bus is inside the segment but outside the MMIO space") + { + place(bridge({.bus = 0, .device = 0}, 4, 4)); + place({.bus = 0, .device = 1}); + + THEN("the walk fails with Not Enough Memory instead of returning a partial list") + { + auto segment = ecam_segment{make_descriptor(0, 0, 8)}; + auto functions = scan_segment(segment); + + REQUIRE(!functions); + REQUIRE(functions.error() == kstd::errc::not_enough_memory); + } + } +} + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Walking a PCI segment with more than 256 functions", + "[devices][pci]") +{ + auto fill_root_bus = [this](bool last_function_is_bridge) { + for (auto device = std::uint8_t{0}; device < devices_per_bus; ++device) + { + place(multifunction(endpoint(amd_fch_sata_controller(0, device, 0)))); + + for (auto function = std::uint8_t{1}; function < functions_per_device; ++function) + { + if (last_function_is_bridge && device == devices_per_bus - 1 && function == functions_per_device - 1) + { + place(bridge({.bus = 0, .device = device, .function = function}, 1, 1)); + } + else + { + place(endpoint(amd_fch_sata_controller(0, device, function))); + } + } + } + }; + + GIVEN("A root bus on which every function of every device is present") + { + fill_root_bus(false); + + THEN("the walk lists all 256 functions in address order") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + auto found = addresses(functions); + + REQUIRE(found.size() == 256); + REQUIRE(std::ranges::is_sorted(found)); + REQUIRE(found.front() == function_address{.segment_group = 0, .bus = 0, .device = 0, .function = 0}); + REQUIRE(found.back() == function_address{.segment_group = 0, .bus = 0, .device = 31, .function = 7}); + } + } + + GIVEN("A full root bus whose very last function is a bridge to a bus with an endpoint") + { + fill_root_bus(true); + place({.bus = 1, .device = 0}); + + THEN("the walk still descends into the bridge and lists 257 functions") + { + auto segment = ecam_segment{make_descriptor()}; + auto functions = require_ok(scan_segment(segment)); + auto found = addresses(functions); + + REQUIRE(found.size() == 257); + REQUIRE(found.at(255) == function_address{.segment_group = 0, .bus = 0, .device = 31, .function = 7}); + REQUIRE(found.at(256) == function_address{.segment_group = 0, .bus = 1, .device = 0, .function = 0}); + } + } +} diff --git a/kernel/kernel/test_support/cio.hpp b/kernel/kernel/test_support/cio.hpp index 71564727..cd42a0ae 100644 --- a/kernel/kernel/test_support/cio.hpp +++ b/kernel/kernel/test_support/cio.hpp @@ -5,7 +5,10 @@ #include +#include #include +#include +#include #include namespace kernel::tests::cio @@ -37,6 +40,15 @@ namespace kernel::tests::cio //! @throws std::runtime_error if no output device has been registered. //! @return The currently active device's log buffer. [[nodiscard]] auto log_buffer() -> kernel::tests::log_buffer &; + + //! Require that a specific message exists in the log buffer. + //! + //! @param message The message to require. + //! @param starting_at The position to start the search at. + //! @param where The source location where this requirement is checked. + //! @return The position of the message in the flat messages string. + auto require_log_message(std::string const & message, std::size_t starting_at = 0, + std::source_location where = std::source_location::current()) -> std::size_t; } // namespace kernel::tests::cio -#endif \ No newline at end of file +#endif diff --git a/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp b/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp index 402d5eb3..28f0694a 100644 --- a/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp +++ b/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp @@ -1,5 +1,6 @@ #include +#include #include #include @@ -36,6 +37,7 @@ namespace kernel::tests::devices::pci ecam_fixture::ecam_fixture() { kernel::tests::memory::fill_mmio(std::byte{0xff}); + kernel::tests::cio::log_buffer().clear(); } auto ecam_fixture::make_descriptor(std::uint16_t group, std::uint8_t first_bus, std::size_t count) diff --git a/kernel/kernel/test_support/kapi/cio.cpp b/kernel/kernel/test_support/kapi/cio.cpp index 98bc99d7..701eb043 100644 --- a/kernel/kernel/test_support/kapi/cio.cpp +++ b/kernel/kernel/test_support/kapi/cio.cpp @@ -4,9 +4,14 @@ #include +#include + #include +#include #include +#include #include +#include namespace { @@ -51,4 +56,19 @@ namespace kernel::tests::cio return device->log_buffer(); } -} // namespace kernel::tests::cio \ No newline at end of file + auto require_log_message(std::string const & message, std::size_t starting_at, std::source_location where) + -> std::size_t + { + auto all = kernel::tests::cio::log_buffer().flat_messages(); + auto found = all.find(message, starting_at); + + if (found == std::string::npos) + { + FAIL("expected message \"" << message << "\" in log\n" + << all << " (at " << where.file_name() << ":" << where.line() << ")"); + } + + return found; + } + +} // namespace kernel::tests::cio -- cgit v1.2.3