diff options
Diffstat (limited to 'kernel')
40 files changed, 3729 insertions, 111 deletions
diff --git a/kernel/CMakeLists.txt b/kernel/CMakeLists.txt index e105ae62..7f418c61 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" @@ -42,6 +43,9 @@ target_sources("kernel_lib" PRIVATE # Device Subsystem "kernel/devices/block_device_utils.cpp" "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/kapi/memory.cpp b/kernel/kapi/memory.cpp index 666910ba..4160092d 100644 --- a/kernel/kapi/memory.cpp +++ b/kernel/kapi/memory.cpp @@ -1,7 +1,6 @@ #include <kapi/memory.hpp> #include <kernel/memory/bitmap_allocator.hpp> -#include <kernel/memory/mmio_allocator.hpp> #include <kapi/system.hpp> @@ -51,25 +50,25 @@ 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<kapi::memory::frame> override { - return false; + return std::nullopt; } }; constinit bad_frame_allocator bad_frame_allocator::instance{}; constinit bad_page_mapper bad_page_mapper::instance{}; auto constinit allocator = std::optional<kernel::memory::bitmap_frame_allocator>{}; - auto constinit mmio_allocator = std::optional<kernel::memory::mmio_allocator>{}; - } // namespace - constinit auto static active_frame_allocator = static_cast<frame_allocator *>(&bad_frame_allocator::instance); - constinit auto static active_page_mapper = static_cast<page_mapper *>(&bad_page_mapper::instance); + constinit auto active_frame_allocator = static_cast<frame_allocator *>(&bad_frame_allocator::instance); + constinit auto active_page_mapper = static_cast<page_mapper *>(&bad_page_mapper::instance); + + } // namespace auto get_frame_allocator() -> frame_allocator & { @@ -109,7 +108,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); } @@ -150,39 +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) -> mmio_region - { - auto region = mmio_allocator->allocate(page_count); - return {region, page_count}; - } - - auto map_mmio_region(mmio_region region, physical_address hw_base, page_mapper::flags flags) - -> kstd::observer_ptr<std::byte> - { - auto start_page = page::containing(region.first); - auto start_frame = frame::containing(hw_base); - - flags |= page_mapper::flags::uncached; - - auto start = 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); - }); - - return start; - } - - auto release_mmio_region(mmio_region region) -> void - { - 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 <kapi/memory/mmio.hpp> + +#include <kernel/memory/mmio_allocator.hpp> + +#include <kapi/memory.hpp> +#include <kapi/system.hpp> +#include <kapi/test_support/memory.hpp> + +#include <kstd/memory.hpp> +#include <kstd/result.hpp> +#include <kstd/system_error.hpp> +#include <kstd/units.hpp> + +#include <cstddef> +#include <cstdint> +#include <limits> +#include <optional> +#include <tuple> +#include <utility> + +using namespace kstd::units_literals; + +namespace kapi::memory +{ + + namespace + { + auto constinit mmio_allocator = std::optional<kernel::memory::mmio_allocator>{}; + + 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<mmio_window> + { + 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<std::uint64_t>::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<std::byte> 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<std::uintptr_t>(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<std::uintptr_t>(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 <kernel/test_support/cpu.hpp> +#include <kernel/test_support/memory.hpp> + +#include <kapi/memory.hpp> +#include <kapi/test_support/memory.hpp> + +#include <kstd/result.hpp> +#include <kstd/system_error.hpp> +#include <kstd/units.hpp> + +#include <catch2/catch_message.hpp> +#include <catch2/catch_template_test_macros.hpp> +#include <catch2/catch_test_macros.hpp> +#include <catch2/generators/catch_generators.hpp> + +#include <cstddef> +#include <cstdint> +#include <limits> +#include <utility> + +// 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<mmio_window> + { + 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<window_layout>({ + {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<TestType>(0x1122'3344'5566'7788ULL); + auto const last_value = static_cast<TestType>(0x99aa'bbcc'ddee'ff00ULL); + + window->write<TestType>(kstd::bytes{slot.first}, first_value); + window->write<TestType>(kstd::bytes{slot.last}, last_value); + + THEN("the values can be read back correctly") + { + CHECK(window->read<TestType>(kstd::bytes{slot.first}) == first_value); + CHECK(window->read<TestType>(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<TestType>(kstd::bytes{slot.last + width}, TestType{}), halt); + } + + WHEN("writing misaligned but otherwise in bounds") + { + if constexpr (width > 1) + { + CHECK_THROWS_AS(window->write<TestType>(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<TestType>(kstd::bytes{slot.first})); + CHECK_NOTHROW(window->read<TestType>(kstd::bytes{slot.last})); + } + + THEN("aligned, in bounds write is rejected") + { + CHECK_THROWS_AS(window->write<TestType>(kstd::bytes{slot.first}, TestType{}), halt); + } + + THEN("reading an aligned but out of bounds offset is rejected") + { + CHECK_THROWS_AS(window->read<TestType>(kstd::bytes{slot.last + width}), halt); + } + + THEN("in bounds but misaligned read is rejected") + { + if constexpr (width > 1) + { + CHECK_THROWS_AS(window->read<TestType>(kstd::bytes{slot.first + 1}), halt); + } + } + + THEN("reading at exactly the window size is rejected") + { + CHECK_THROWS_AS(window->read<TestType>(hw_size), halt); + } + + THEN("reading offsets close to the largest representable value is rejected") + { + constexpr auto max_offset = std::numeric_limits<std::size_t>::max(); + CHECK_THROWS_AS(window->read<TestType>(kstd::bytes{max_offset}), halt); + CHECK_THROWS_AS(window->read<TestType>(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<std::uint32_t>(kstd::bytes{0x800}, 0xcafe'f00d); + + THEN("the value is visible through the other window") + { + CHECK(second->read<std::uint32_t>(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<std::uint32_t>(kstd::bytes{0x800}, 0xcafe'f00d); + } + + THEN("the remaining window is still usable and observes the value") + { + CHECK(second->read<std::uint32_t>(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<std::uint64_t>::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<std::uint32_t>(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<std::uint32_t>(kstd::bytes{0}) == 0x1234'5678); + } + + THEN("the moved-from window rejects all accesses") + { + CHECK_THROWS_AS(original->read<std::uint32_t>(kstd::bytes{0}), halt); + CHECK_THROWS_AS(original->write<std::uint32_t>(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<std::uint32_t>(kstd::bytes{0}) == 0x1234'5678); + } + + THEN("the moved-from window rejects all accesses") + { + CHECK_THROWS_AS(original->read<std::uint32_t>(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<std::uint32_t>(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/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 <kernel/devices/pci/ecam_segment.hpp> + +#include <kernel/devices/pci/registers.hpp> + +#include <kapi/devices.hpp> +#include <kapi/memory.hpp> + +#include <kstd/print.hpp> +#include <kstd/result.hpp> +#include <kstd/system_error.hpp> +#include <kstd/units.hpp> + +#include <cstddef> +#include <cstdint> + +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<kapi::memory::mmio_window> + { + 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 <kernel/devices/pci/registers.hpp> + +#include <kapi/devices.hpp> +#include <kapi/memory.hpp> + +#include <kstd/result.hpp> +#include <kstd/units.hpp> + +#include <cstddef> +#include <cstdint> + +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<kapi::memory::mmio_window>; + + 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 <kernel/devices/pci/ecam_segment.hpp> + +#include <kernel/devices/pci/registers.hpp> +#include <kernel/test_support/memory.hpp> + +#include <kapi/devices.hpp> +#include <kapi/memory.hpp> + +#include <kstd/system_error.hpp> +#include <kstd/units.hpp> + +#include <catch2/catch_test_macros.hpp> +#include <catch2/generators/catch_generators.hpp> + +#include <cstddef> +#include <cstdint> +#include <limits> + +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<std::size_t>::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<std::uint16_t>(kstd::bytes{0}, 0x1000); + data_window->write<std::uint16_t>(kstd::bytes{2}, 0x2000); + data_window->write<std::uint16_t>(kstd::bytes{4}, 0x4000); + + THEN("the data can be read back correctly") + { + auto bus = segment.map_bus(descriptor.first_bus); + + REQUIRE(bus->read<std::uint16_t>(kstd::bytes{0}) == 0x1000); + REQUIRE(bus->read<std::uint16_t>(kstd::bytes{2}) == 0x2000); + REQUIRE(bus->read<std::uint16_t>(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<std::uint16_t>(kstd::bytes{0}, 0x1000); + data_window->write<std::uint16_t>(kstd::bytes{2}, 0x2000); + data_window->write<std::uint16_t>(kstd::bytes{4}, 0x4000); + + THEN("the data can be read back correctly") + { + auto bus = segment.map_bus(descriptor.first_bus); + + REQUIRE(bus->read<std::uint16_t>(kstd::bytes{0}) == 0x1000); + REQUIRE(bus->read<std::uint16_t>(kstd::bytes{2}) == 0x2000); + REQUIRE(bus->read<std::uint16_t>(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/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 <kstd/format.hpp> + +#include <array> +#include <compare> +#include <cstdint> +#include <span> +#include <string_view> + +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<kernel::devices::pci::function_address> +{ + 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<char, output_length>{}; + 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 <kernel/devices/pci/function_address.hpp> + +#include <kstd/format.hpp> + +#include <catch2/catch_test_macros.hpp> + +#include <compare> + +// 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) diff --git a/kernel/kernel/devices/pci/function_info.hpp b/kernel/kernel/devices/pci/function_info.hpp new file mode 100644 index 00000000..3e71430e --- /dev/null +++ b/kernel/kernel/devices/pci/function_info.hpp @@ -0,0 +1,76 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_INFO_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_FUNCTION_INFO_HPP + +#include <kernel/devices/pci/function_address.hpp> + +#include <cstdint> + +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<header_type>(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{}; + //! 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 + +#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 <kernel/devices/pci/function_info.hpp> + +#include <catch2/catch_test_macros.hpp> + +// 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<kernel::devices::pci::header_type>(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<kernel::devices::pci::header_type>(0x7f)); + } + } +} + +// NOLINTEND(readability-magic-numbers) diff --git a/kernel/kernel/devices/pci/init.cpp b/kernel/kernel/devices/pci/init.cpp new file mode 100644 index 00000000..f3efaa87 --- /dev/null +++ b/kernel/kernel/devices/pci/init.cpp @@ -0,0 +1,45 @@ +#include <kernel/devices/pci/init.hpp> + +#include <kernel/devices/pci/ecam_segment.hpp> +#include <kernel/devices/pci/function_info.hpp> +#include <kernel/devices/pci/scan.hpp> + +#include <kapi/devices.hpp> + +#include <kstd/print.hpp> +#include <kstd/vector.hpp> + +namespace kernel::devices::pci +{ + + 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()); + + 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 (auto const & function : *functions) + { + kstd::println("[OS:DEV] Detected PCI Express device: {} [{:04x}:{:04x}]", function.address, function.vendor_id, + function.device_id); + } + } + } + +} // 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..1caa0baf --- /dev/null +++ b/kernel/kernel/devices/pci/registers.hpp @@ -0,0 +1,69 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_REGISTERS_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_REGISTERS_HPP + +#include <kstd/units.hpp> + +#include <cstdint> + +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 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}; + + //! 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 new file mode 100644 index 00000000..0ff7d03e --- /dev/null +++ b/kernel/kernel/devices/pci/scan.cpp @@ -0,0 +1,188 @@ +#include <kernel/devices/pci/scan.hpp> + +#include <kernel/devices/pci/ecam_segment.hpp> +#include <kernel/devices/pci/function_info.hpp> +#include <kernel/devices/pci/registers.hpp> + +#include <kapi/memory.hpp> + +#include <kstd/print.hpp> +#include <kstd/result.hpp> +#include <kstd/vector.hpp> + +#include <bitset> +#include <cstdint> +#include <limits> +#include <optional> +#include <utility> + +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<function_info> + { + auto offset = function_offset(device, number); + + auto vendor_id = ecam_window.read<std::uint16_t>(offset + vendor_id_register_offset); + if (vendor_id == invalid_vendor_id) + { + return std::nullopt; + } + + auto device_id = ecam_window.read<std::uint16_t>(offset + device_id_register_offset); + auto revision = ecam_window.read<std::uint8_t>(offset + revision_id_register_offset); + auto programming_interface = ecam_window.read<std::uint8_t>(offset + programming_interface_register_offset); + auto class_code = ecam_window.read<std::uint8_t>(offset + class_code_register_offset); + auto subclass = ecam_window.read<std::uint8_t>(offset + subclass_register_offset); + auto header_type = ecam_window.read<std::uint8_t>(offset + header_type_register_offset); + + auto info = 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 + }; + + if (info.type() == header_type::pci_to_pci_bridge) + { + info.secondary_bus = ecam_window.read<std::uint8_t>(offset + secondary_bus_register_offset); + info.subordinate_bus = ecam_window.read<std::uint8_t>(offset + subordinate_bus_register_offset); + } + + return info; + } + + } // namespace + + auto scan_bus(ecam_segment const & segment, std::uint8_t bus_number) -> kstd::result<kstd::vector<function_info>> + { + auto bus = segment.map_bus(bus_number); + + if (!bus) + { + return kstd::failure(bus.error()); + } + + auto functions = kstd::vector<function_info>{}; + + 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)); + } + + auto scan_segment(ecam_segment const & segment) -> kstd::result<kstd::vector<function_info>> + { + auto root_bus = segment.first_bus(); + if (!segment.contains(root_bus)) + { + return kstd::vector<function_info>{}; + } + + auto functions = scan_bus(segment, root_bus); + if (!functions) + { + return kstd::failure(functions.error()); + } + + auto scanned_buses = std::bitset<std::numeric_limits<std::uint8_t>::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 new file mode 100644 index 00000000..799a1c09 --- /dev/null +++ b/kernel/kernel/devices/pci/scan.hpp @@ -0,0 +1,44 @@ +#ifndef TEACHOS_KERNEL_DEVICES_PCI_SCAN_HPP +#define TEACHOS_KERNEL_DEVICES_PCI_SCAN_HPP + +#include <kernel/devices/pci/ecam_segment.hpp> +#include <kernel/devices/pci/function_info.hpp> + +#include <kstd/result.hpp> +#include <kstd/vector.hpp> + +#include <cstdint> + +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<kstd::vector<function_info>>; + + //! 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<kstd::vector<function_info>>; + +} // 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..455a25c5 --- /dev/null +++ b/kernel/kernel/devices/pci/scan.tests.cpp @@ -0,0 +1,947 @@ +#include <kernel/devices/pci/scan.hpp> + +#include <kernel/devices/pci/ecam_segment.hpp> +#include <kernel/devices/pci/function_address.hpp> +#include <kernel/devices/pci/function_info.hpp> +#include <kernel/test_support/cio.hpp> +#include <kernel/test_support/devices/pci/ecam_fixture.hpp> +#include <kernel/test_support/devices/pci/function_addresses.hpp> +#include <kernel/test_support/devices/pci/function_spec.hpp> +#include <kernel/test_support/memory.hpp> + +#include <kapi/devices.hpp> + +#include <kstd/system_error.hpp> +#include <kstd/test_support/result.hpp> + +#include <catch2/catch_test_macros.hpp> + +#include <algorithm> +#include <cstdint> +#include <string> + +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; + +namespace +{ + 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_endpoint = 0x00; + constexpr auto header_type_cardbus_bridge = 0x02; + + 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 distinct_secondary_bus = 0x21; + 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 + { + 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 amd_ai_pro_r9700_vga(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 0) -> function_spec + { + 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 amd_ai_pro_r9700_audio(std::uint8_t bus, std::uint8_t device, std::uint8_t function = 1) -> function_spec + { + 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, + }; + } + +} // namespace + +SCENARIO_METHOD(kernel::tests::devices::pci::ecam_fixture, "Scanning PCI buses", "[devices][pci]") +{ + GIVEN("An empty PCI bus") + { + THEN("scanning the bus finds no devices") + { + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.empty()); + } + } + + GIVEN("A PCI bus with a single single-function device") + { + place(endpoint(amd_fch_sata_controller(0, 1))); + + THEN("scanning the bus finds the single function") + { + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.size() == 1); + + auto const & device = devices.at(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); + 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") + { + 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 segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.size() == 2); + + auto const & first = devices.at(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); + 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 == 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") + { + 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 segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, bus)); + + REQUIRE(devices.size() == 3); + + auto const & first = devices.at(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); + 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 == 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); + + 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") + { + place(endpoint(amd_fch_sata_controller(0, 3, 1))); + + THEN("scanning the bus finds no devices") + { + auto segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.empty()); + } + } + + GIVEN("A PCI bus with two single-function devices at the extremes") + { + 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 segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.size() == 2); + + auto const & first = devices.at(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); + 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 == + 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); + 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") + { + 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 segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + 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") + { + 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 segment = ecam_segment{make_descriptor(0, 0)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 0)); + + REQUIRE(devices.size() == 1); + + 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") + { + place(amd_fch_sata_controller(2, 5)); + + THEN("the address of the function carries the segment group and the bus") + { + auto segment = ecam_segment{make_descriptor(3, 0, 4)}; + auto devices = require_ok(kernel::devices::pci::scan_bus(segment, 2)); + + REQUIRE(devices.size() == 1); + + REQUIRE(devices.at(0).address == 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 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); + } + } + + GIVEN("A bus outside the MMIO space") + { + THEN("scanning 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 devices = kernel::devices::pci::scan_bus(segment, 0); + + REQUIRE(!devices); + REQUIRE(devices.error() == kstd::errc::not_enough_memory); + } + } +} + +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); + } + } +} + +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/main.cpp b/kernel/kernel/main.cpp index bbbd46c0..ea55451f 100644 --- a/kernel/kernel/main.cpp +++ b/kernel/kernel/main.cpp @@ -1,4 +1,5 @@ #include <kernel/devices/init.hpp> +#include <kernel/devices/pci/init.hpp> #include <kernel/devices/storage.hpp> #include <kernel/drivers/init.hpp> #include <kernel/memory.hpp> @@ -296,6 +297,9 @@ auto main() -> int kapi::interrupts::enabled(true); kstd::println("[OS] Interrupts enabled."); + kernel::devices::pci::init(); + kstd::println("[OS] PCI Express devices initialized."); + auto modules_bus = kernel::devices::storage::init(); kstd::println("[OS] Storage subsystem initialized."); 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 <kernel/memory/bitmap_allocator.hpp> #include <kapi/memory.hpp> +#include <kapi/system.hpp> #include <algorithm> #include <cstddef> @@ -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/memory/mmio_allocator.cpp b/kernel/kernel/memory/mmio_allocator.cpp index 17f436f8..05cf35e4 100644 --- a/kernel/kernel/memory/mmio_allocator.cpp +++ b/kernel/kernel/memory/mmio_allocator.cpp @@ -1,9 +1,10 @@ #include <kernel/memory/mmio_allocator.hpp> #include <kapi/memory.hpp> -#include <kapi/system.hpp> #include <kstd/allocator.hpp> +#include <kstd/result.hpp> +#include <kstd/system_error.hpp> #include <cstddef> #include <memory> @@ -16,11 +17,22 @@ namespace kernel::memory : m_head{make_node(base, pages, nullptr, nullptr, true)} {} - auto mmio_allocator::allocate(std::size_t count) -> kapi::memory::linear_address + mmio_allocator::~mmio_allocator() { - if (count == 0 || !m_head) + 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<kapi::memory::linear_address> + { + if (count == 0) { - return {}; + return kstd::failure(make_error_code(kstd::errc::invalid_argument)); } auto current = m_head; @@ -42,13 +54,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..4cb9d407 100644 --- a/kernel/kernel/memory/mmio_allocator.hpp +++ b/kernel/kernel/memory/mmio_allocator.hpp @@ -4,7 +4,7 @@ #include <kapi/memory.hpp> #include <kstd/allocator.hpp> -#include <kstd/memory.hpp> +#include <kstd/result.hpp> #include <cstddef> @@ -15,7 +15,9 @@ 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; + ~mmio_allocator(); + + [[nodiscard]] auto allocate(std::size_t page_count) -> kstd::result<kapi::memory::linear_address>; auto release(kapi::memory::linear_address base) -> void; private: 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 <kapi/cio.hpp> +#include <cstddef> #include <mutex> +#include <source_location> +#include <string> #include <string_view> 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_builder.cpp b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp new file mode 100644 index 00000000..a9bb1256 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.cpp @@ -0,0 +1,117 @@ +#include <kernel/test_support/devices/pci/ecam_builder.hpp> + +#include <kapi/memory.hpp> + +#include <kstd/test_support/result.hpp> +#include <kstd/units.hpp> + +#include <catch2/catch_test_macros.hpp> + +#include <cstdint> +#include <utility> + +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<std::uint16_t>(vendor_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::device_id(std::uint16_t id) -> function_builder & + { + m_window.write<std::uint16_t>(device_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::class_code(std::uint8_t code) -> function_builder & + { + m_window.write<std::uint8_t>(class_code_offset, code); + return *this; + } + + auto ecam_builder::function_builder::header_type(std::uint8_t type) -> function_builder & + { + m_window.write<std::uint8_t>(header_type_offset, type); + return *this; + } + + auto ecam_builder::function_builder::subclass_code(std::uint8_t id) -> function_builder & + { + m_window.write<std::uint8_t>(subclass_code_offset, id); + return *this; + } + + auto ecam_builder::function_builder::programming_interface(std::uint8_t id) -> function_builder & + { + m_window.write<std::uint8_t>(programming_interface_offset, id); + return *this; + } + + auto ecam_builder::function_builder::revision_id(std::uint8_t id) -> function_builder & + { + m_window.write<std::uint8_t>(revision_id_offset, id); + return *this; + } + + auto ecam_builder::function_builder::secondary_bus(std::uint8_t id) -> function_builder & + { + m_window.write<std::uint8_t>(secondary_bus_offset, id); + return *this; + } + + auto ecam_builder::function_builder::subordinate_bus(std::uint8_t id) -> function_builder & + { + m_window.write<std::uint8_t>(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 + { + 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<std::uint64_t>(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); + + 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 new file mode 100644 index 00000000..3c0cf036 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.hpp @@ -0,0 +1,138 @@ +#ifndef TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_BUILDER_HPP +#define TEACHOS_KERNEL_TEST_SUPPORT_DEVICES_PCI_ECAM_BUILDER_HPP + +#include <kapi/memory.hpp> + +#include <kstd/units.hpp> + +#include <cstdint> + +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}; + constexpr auto static secondary_bus_offset = kstd::bytes{0x19}; + constexpr auto static subordinate_bus_offset = kstd::bytes{0x1a}; + + 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 &; + + //! 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. + //! @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..3b300581 --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_builder.tests.cpp @@ -0,0 +1,164 @@ +#include <kernel/test_support/devices/pci/ecam_builder.hpp> + +#include <kapi/memory.hpp> + +#include <kstd/test_support/result.hpp> +#include <kstd/units.hpp> + +#include <catch2/catch_test_macros.hpp> +#include <catch2/generators/catch_generators.hpp> + +#include <cstdint> +#include <tuple> + +using kernel::tests::devices::pci::ecam_builder; +using mmio_window = kapi::memory::mmio_window; +using kstd::tests::require_ok; + +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; + 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]") +{ + 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 = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint32_t>(kstd::bytes{}) == 0); + REQUIRE(window.read<std::uint32_t>(bytes_per_bus - kstd::bytes{4}) == 0); + } + + THEN("the bus is cleared") + { + auto base = test_ecam_base + bytes_per_bus; + auto window = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint32_t>(kstd::bytes{}) == 0xffff'ffff); + REQUIRE(window.read<std::uint32_t>(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 = require_ok(mmio_window::map(base, bytes_per_bus, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint32_t>(kstd::bytes{}) == 0); + REQUIRE(window.read<std::uint32_t>(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) + .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 = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint16_t>(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window.read<std::uint16_t>(ecam_builder::device_id_offset) == test_device); + REQUIRE(window.read<std::uint8_t>(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window.read<std::uint8_t>(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window.read<std::uint8_t>(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window.read<std::uint8_t>(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window.read<std::uint8_t>(ecam_builder::header_type_offset) == + (test_header_type_endpoint | test_multifunction)); + REQUIRE(window.read<std::uint8_t>(ecam_builder::secondary_bus_offset) == test_secondary_bus); + REQUIRE(window.read<std::uint8_t>(ecam_builder::subordinate_bus_offset) == test_subordinate_bus); + } + } + + 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 = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint16_t>(ecam_builder::vendor_id_offset) == test_vendor); + REQUIRE(window.read<std::uint16_t>(ecam_builder::device_id_offset) == test_device); + REQUIRE(window.read<std::uint8_t>(ecam_builder::class_code_offset) == test_class_display_ctrl); + REQUIRE(window.read<std::uint8_t>(ecam_builder::subclass_code_offset) == test_subclass_vga); + REQUIRE(window.read<std::uint8_t>(ecam_builder::programming_interface_offset) == test_prog_if_8514); + REQUIRE(window.read<std::uint8_t>(ecam_builder::revision_id_offset) == test_revision); + REQUIRE(window.read<std::uint8_t>(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 = require_ok(mmio_window::map(base, bytes_per_function, mmio_window::access::read_only)); + + REQUIRE(window.read<std::uint16_t>(ecam_builder::vendor_id_offset) == 0); + REQUIRE(window.read<std::uint16_t>(ecam_builder::device_id_offset) == 0); + REQUIRE(window.read<std::uint8_t>(ecam_builder::class_code_offset) == 0); + REQUIRE(window.read<std::uint8_t>(ecam_builder::subclass_code_offset) == 0); + REQUIRE(window.read<std::uint8_t>(ecam_builder::programming_interface_offset) == 0); + REQUIRE(window.read<std::uint8_t>(ecam_builder::revision_id_offset) == 0); + REQUIRE(window.read<std::uint8_t>(ecam_builder::header_type_offset) == 0); + } + } + } +} 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..28f0694a --- /dev/null +++ b/kernel/kernel/test_support/devices/pci/ecam_fixture.cpp @@ -0,0 +1,66 @@ +#include <kernel/test_support/devices/pci/ecam_fixture.hpp> + +#include <kernel/test_support/cio.hpp> +#include <kernel/test_support/devices/pci/function_spec.hpp> +#include <kernel/test_support/memory.hpp> + +#include <kapi/devices.hpp> + +#include <cstddef> +#include <cstdint> + +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}); + kernel::tests::cio::log_buffer().clear(); + } + + 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 <kernel/test_support/devices/pci/ecam_builder.hpp> +#include <kernel/test_support/devices/pci/function_spec.hpp> +#include <kernel/test_support/memory.hpp> + +#include <kapi/devices.hpp> + +#include <kstd/units.hpp> + +#include <algorithm> +#include <cstddef> +#include <cstdint> + +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 <kernel/test_support/devices/pci/function_addresses.hpp> + +#include <kernel/devices/pci/function_address.hpp> +#include <kernel/devices/pci/function_info.hpp> + +#include <kstd/vector.hpp> + +#include <cstdint> +#include <initializer_list> +#include <ranges> +#include <vector> + +namespace kernel::tests::devices::pci +{ + + auto addresses(kstd::vector<kernel::devices::pci::function_info> const & functions) + -> std::vector<kernel::devices::pci::function_address> + { + return {std::from_range, std::views::transform(functions, [](auto const & info) { return info.address; })}; + } + + auto addresses_of(std::initializer_list<function_location> list, std::uint16_t group) + -> std::vector<kernel::devices::pci::function_address> + { + 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 <kernel/devices/pci/function_address.hpp> +#include <kernel/devices/pci/function_info.hpp> + +#include <kstd/vector.hpp> + +#include <cstdint> +#include <initializer_list> +#include <vector> + +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<kernel::devices::pci::function_info> const & functions) + -> std::vector<kernel::devices::pci::function_address>; + + //! 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<function_location> list, std::uint16_t group = 0) + -> std::vector<kernel::devices::pci::function_address>; + +} // 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 <cstdint> +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/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 <kapi/cio.hpp> +#include <catch2/catch_test_macros.hpp> + #include <atomic> +#include <cstddef> #include <optional> +#include <source_location> #include <stdexcept> +#include <string> 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 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 <kapi/devices.hpp> + +#include <kstd/vector.hpp> + +namespace kapi::devices +{ + + auto get_pci_express_segment_descriptors() -> kstd::vector<pcie_segment_descriptor> + { + return {}; + } + +} // namespace kapi::devices
\ No newline at end of file diff --git a/kernel/kernel/test_support/kapi/memory.cpp b/kernel/kernel/test_support/kapi/memory.cpp index e554145d..75f987bd 100644 --- a/kernel/kernel/test_support/kapi/memory.cpp +++ b/kernel/kernel/test_support/kapi/memory.cpp @@ -1,21 +1,17 @@ #include <kapi/memory.hpp> #include <kernel/test_support/bump_frame_allocator.hpp> +#include <kernel/test_support/memory.hpp> #include <kernel/test_support/page_mapper.hpp> #include <kapi/memory.hpp> -#include <kstd/units.hpp> - +#include <cstddef> #include <optional> 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<kernel::tests::bump_frame_allocator>{}; auto constinit test_mapper = std::optional<kernel::tests::page_mapper>{}; @@ -38,12 +34,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 @@ -71,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 21030a41..87530ce5 100644 --- a/kernel/kernel/test_support/memory.hpp +++ b/kernel/kernel/test_support/memory.hpp @@ -3,12 +3,43 @@ #include <kapi/memory.hpp> +#include <kstd/units.hpp> + +#include <cstddef> + 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; + //! 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 @@ -19,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/page_mapper.cpp b/kernel/kernel/test_support/page_mapper.cpp index 808e0810..fea2e4f1 100644 --- a/kernel/kernel/test_support/page_mapper.cpp +++ b/kernel/kernel/test_support/page_mapper.cpp @@ -7,65 +7,95 @@ #include <cstddef> #include <format> +#include <optional> #include <stdexcept> 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<std::byte> { - 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()); + page_mappings.insert({page.number(), frame}); + return mapped; + } + + return nullptr; + } + + auto page_mapper::unmap(kapi::memory::page page) -> kapi::memory::frame + { + 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 -> std::optional<kapi::memory::frame> + { + if (auto it = page_mappings.find(page.number()); it != page_mappings.end()) + { + auto frame = it->second; + page_mappings.erase(it); + return frame; + } + + return {}; + } + + auto page_mapper::do_map(kapi::memory::page page, kapi::memory::frame frame) -> kstd::observer_ptr<std::byte> + { 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<std::byte *>(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) + else if (page_address >= kapi::memory::mmio_base && page_address < kapi::memory::mmio_base + mmio.virtual_size()) { - 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}; - } + if (physical_offset + kapi::memory::page::size > mmio.physical_size()) + { + return nullptr; + } - return nullptr; - } - - auto page_mapper::unmap(kapi::memory::page page) -> void - { - if (!try_unmap(page)) - { - auto error = std::format("Page {} was never mapped!", page.number()); - throw std::invalid_argument{error}; + auto virtual_target = static_cast<std::byte *>(mmio.virtual_base() + (page_address - kapi::memory::mmio_base)); + return mmio.map(kapi::memory::page::size, virtual_target, physical_offset.value); } - } - - auto page_mapper::try_unmap(kapi::memory::page page) noexcept -> bool - { - if (page_mappings.contains(page.number())) + else if (page_address >= kapi::memory::higher_half_direct_map_base && page_address < kapi::memory::mmio_base) { - page_mappings.erase(page.number()); - return true; + if (physical_offset + kapi::memory::page::size > memory.physical_size()) + { + return nullptr; + } + + return kstd::observer_ptr{memory.physical_base().get() + physical_offset.value}; } - return false; + return nullptr; } -} // namespace kernel::tests
\ No newline at end of file +} // namespace kernel::tests diff --git a/kernel/kernel/test_support/page_mapper.hpp b/kernel/kernel/test_support/page_mapper.hpp index c38eeaf3..fa601b7e 100644 --- a/kernel/kernel/test_support/page_mapper.hpp +++ b/kernel/kernel/test_support/page_mapper.hpp @@ -10,6 +10,7 @@ #include <cstddef> #include <cstdint> +#include <optional> #include <unordered_map> namespace kernel::tests @@ -19,32 +20,46 @@ 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<std::byte> override; //! @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<kapi::memory::frame> override; //! 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<std::uint64_t, kapi::memory::frame> 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<std::byte>; }; } // 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 <kernel/test_support/page_mapper.hpp> + +#include <kernel/test_support/memory.hpp> + +#include <kapi/memory.hpp> + +#include <kstd/units.hpp> + +#include <catch2/catch_test_macros.hpp> + +#include <cstddef> +#include <stdexcept> + +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..e7ad125b 100644 --- a/kernel/kernel/test_support/simulated_memory.cpp +++ b/kernel/kernel/test_support/simulated_memory.cpp @@ -10,6 +10,7 @@ #include <cstring> #include <format> #include <stdexcept> +#include <string> #include <unistd.h> #include <sys/mman.h> @@ -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} { @@ -64,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<int>(value), m_physical_size.value); } auto simulated_memory::physical_base() noexcept -> kstd::observer_ptr<std::byte> @@ -104,4 +110,4 @@ namespace kernel::tests return kstd::observer_ptr{static_cast<std::byte *>(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 e6161437..87a606d7 100644 --- a/kernel/kernel/test_support/simulated_memory.hpp +++ b/kernel/kernel/test_support/simulated_memory.hpp @@ -7,6 +7,7 @@ #include <kstd/units.hpp> #include <cstddef> +#include <string> #include <sys/types.h> @@ -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(); @@ -32,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<std::byte>; @@ -65,4 +72,4 @@ namespace kernel::tests } // namespace kernel::tests -#endif
\ No newline at end of file +#endif 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(); |
