diff --git a/Makefile b/Makefile index 1fb4e61..a8e6bf3 100644 --- a/Makefile +++ b/Makefile @@ -76,6 +76,8 @@ HOST_ONLY_TEST_SRCS := \ tests/host/file_syscalls_test.cpp \ tests/host/syscall_helpers_test.cpp \ tests/host/process_subsystem_test.cpp \ + tests/host/cpio_duration_test.cpp \ + tests/host/virtio_blk_test.cpp \ drivers/dummy/DummyDriver.cpp \ tests/host/socket_syscall_test.cpp \ tests/host/gicv2_test.cpp \ diff --git a/tests/host/cpio_duration_test.cpp b/tests/host/cpio_duration_test.cpp new file mode 100644 index 0000000..0b55359 --- /dev/null +++ b/tests/host/cpio_duration_test.cpp @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: GPL-3.0-only +// Copyright (c) 2026 Marco Buschini + +#include "fs/cpio.hpp" +#include "time/Duration.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace Kernel::FS; +using namespace Kernel::Time; + +void write_hex8(char* dst, uint32_t val) noexcept { + static constexpr char kHex[] = "0123456789abcdef"; + for (size_t i = 0U; i < 8U; ++i) { + dst[7U - i] = kHex[val & 0xFU]; + val >>= 4U; + } +} + +void append_cpio_entry(std::vector& buf, const char* magic, std::string_view name, + uint32_t mode, const void* payload, uint32_t payload_size, + bool include_nul = true) noexcept { + CpioNewcHeader hdr{}; + std::fill_n(reinterpret_cast(&hdr), sizeof(hdr), '0'); + std::memcpy(hdr.c_magic, magic, 6U); + write_hex8(hdr.c_mode, mode); + write_hex8(hdr.c_filesize, payload_size); + const auto namesize = static_cast(name.size() + 1U); + write_hex8(hdr.c_namesize, namesize); + + const auto* hdr_bytes = reinterpret_cast(&hdr); + buf.insert(buf.end(), hdr_bytes, hdr_bytes + sizeof(hdr)); + + for (char ch : name) { + buf.push_back(static_cast(ch)); + } + buf.push_back(include_nul ? 0U : static_cast('X')); + + while ((buf.size() & 3U) != 0U) { + buf.push_back(0U); + } + + if (payload != nullptr && payload_size > 0U) { + const auto* data = static_cast(payload); + buf.insert(buf.end(), data, data + payload_size); + while ((buf.size() & 3U) != 0U) { + buf.push_back(0U); + } + } +} + +TEST_CASE("CpioArchive status strings, validation, lookup, and error paths", "[fs][cpio]") { + CHECK(std::strcmp(cpio_status_str(CpioStatus::Success), "Success") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::ArchiveTooSmall), "ArchiveTooSmall") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::InvalidMagic), "InvalidMagic") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::MalformedHeader), "MalformedHeader") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::CorruptedPadding), "CorruptedPadding") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::PathTooLong), "PathTooLong") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::FileNotFound), "FileNotFound") == 0); + CHECK(std::strcmp(cpio_status_str(CpioStatus::UnexpectedEndOfArchive), + "UnexpectedEndOfArchive") == 0); + + CpioEntry entry{}; + CHECK_FALSE(CpioArchive(nullptr, 128U).is_valid()); + CHECK_FALSE(CpioArchive("070701", 6U).is_valid()); + CHECK(cpio_lookup(nullptr, 0U, "a", entry) == CpioStatus::ArchiveTooSmall); + + std::array bad_hdr{}; + std::memset(bad_hdr.data(), '0', bad_hdr.size()); + std::memcpy(bad_hdr.data(), "070703", 6U); + CHECK_FALSE(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), "a", entry) == CpioStatus::InvalidMagic); + + std::memcpy(bad_hdr.data(), "07070X", 6U); + CHECK_FALSE(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + std::memcpy(bad_hdr.data(), "070702", 6U); + CHECK(CpioArchive(bad_hdr.data(), bad_hdr.size()).is_valid()); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), nullptr, entry) == CpioStatus::FileNotFound); + CHECK(cpio_lookup(bad_hdr.data(), bad_hdr.size(), "", entry) == CpioStatus::FileNotFound); + + // Valid archive with dir, regular file (070702), symlink, and TRAILER!!! + std::vector archive; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, "bin", CPIO_MODE_DIR | 0755U, nullptr, 0U); + const char file_data[] = "hello"; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_CRC, "./bin/hello", CPIO_MODE_REGULAR | 0644U, + file_data, 5U); + const char link_target[] = "/bin/hello"; + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, "bin/hi", CPIO_MODE_SYMLINK | 0777U, + link_target, 10U); + append_cpio_entry(archive, CPIO_NEWC_MAGIC_NOCRC, CPIO_TRAILER_NAME, 0U, nullptr, 0U); + + CHECK(cpio_lookup(archive.data(), archive.size(), "/bin", entry) == CpioStatus::Success); + CHECK(entry.is_directory); + CHECK_FALSE(entry.is_regular_file); + + CHECK(cpio_lookup(archive.data(), archive.size(), "bin/hello", entry) == CpioStatus::Success); + CHECK(entry.is_regular_file); + CHECK(entry.size == 5U); + CHECK(std::memcmp(entry.data, "hello", 5U) == 0); + + CHECK(cpio_lookup(archive.data(), archive.size(), "bin/hi", entry) == CpioStatus::Success); + CHECK_FALSE(entry.is_directory); + CHECK_FALSE(entry.is_regular_file); + + CHECK(cpio_lookup(archive.data(), archive.size(), "missing", entry) == + CpioStatus::FileNotFound); + + // Void callback path in for_each + size_t count = 0U; + const CpioArchive valid_arch(archive.data(), archive.size()); + CHECK(valid_arch.for_each([&](const CpioEntry&) { ++count; }) == CpioStatus::Success); + CHECK(count == 3U); + + // Truncated archive without TRAILER!!! propagates UnexpectedEndOfArchive + std::vector no_trailer; + append_cpio_entry(no_trailer, CPIO_NEWC_MAGIC_NOCRC, "a", CPIO_MODE_REGULAR, "x", 1U); + CHECK(cpio_lookup(no_trailer.data(), no_trailer.size(), "missing", entry) == + CpioStatus::UnexpectedEndOfArchive); + CHECK(CpioArchive(no_trailer.data(), no_trailer.size() - 1U).for_each([](const CpioEntry&) { + }) == CpioStatus::UnexpectedEndOfArchive); + + // Bad hex in header + std::vector bad_hex = no_trailer; + bad_hex[offsetof(CpioNewcHeader, c_namesize)] = 'z'; + CHECK(CpioArchive(bad_hex.data(), bad_hex.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + + // namesize == 0 and namesize >= 4096 + std::vector zero_name = no_trailer; + write_hex8(reinterpret_cast(zero_name.data() + offsetof(CpioNewcHeader, c_namesize)), + 0U); + CHECK(CpioArchive(zero_name.data(), zero_name.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + write_hex8(reinterpret_cast(zero_name.data() + offsetof(CpioNewcHeader, c_namesize)), + 4096U); + CHECK(CpioArchive(zero_name.data(), zero_name.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::PathTooLong); + + // Non-null-terminated name + std::vector no_nul; + append_cpio_entry(no_nul, CPIO_NEWC_MAGIC_NOCRC, "ab", CPIO_MODE_REGULAR, nullptr, 0U, false); + CHECK(CpioArchive(no_nul.data(), no_nul.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::MalformedHeader); + + // Corrupted name padding (name "ab" -> 110 + 3 = 113 bytes + 3 bytes padding to 116) + std::vector bad_pad; + append_cpio_entry(bad_pad, CPIO_NEWC_MAGIC_NOCRC, "ab", CPIO_MODE_REGULAR, nullptr, 0U); + bad_pad[sizeof(CpioNewcHeader) + 3U] = 0xAAU; + CHECK(CpioArchive(bad_pad.data(), bad_pad.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::CorruptedPadding); + + // Corrupted payload padding (payload "x" -> 1 byte + 3 bytes padding) + std::vector bad_pay_pad = no_trailer; + bad_pay_pad[bad_pay_pad.size() - 1U] = 0x55U; + CHECK(CpioArchive(bad_pay_pad.data(), bad_pay_pad.size()).for_each([](const CpioEntry&) {}) == + CpioStatus::CorruptedPadding); +} + +TEST_CASE("Duration conversions, ticks, timespec, and overflow guards", "[time][duration]") { + const Duration z = Duration::zero(); + CHECK(z.is_zero()); + CHECK(z.nanoseconds() == 0ULL); + CHECK(z.to_timer_ticks(1000ULL) == 0ULL); + + const Duration us = Duration::from_microseconds(1500ULL); + CHECK_FALSE(us.is_zero()); + CHECK(us.nanoseconds() == 1500000ULL); + + const Duration ns = Duration::from_nanoseconds(2500000500ULL); + const linux_timespec ts = ns.to_linux_timespec(); + CHECK(ts.tv_sec == 2); + CHECK(ts.tv_nsec == 500000500); + + const linux_timeval tv = ns.to_linux_timeval(); + CHECK(tv.tv_sec == 2); + CHECK(tv.tv_usec == 500000); + + // from_ticks (runtime inputs so constexpr functions execute at runtime) + volatile uint64_t zero_u = 0ULL; + volatile uint64_t ticks_val = 1500ULL; + volatile uint64_t freq_val = 1000ULL; + CHECK(Duration::from_ticks(ticks_val, zero_u).is_zero()); + CHECK(Duration::from_ticks(zero_u, freq_val).is_zero()); + const Duration t_dur = Duration::from_ticks(ticks_val, freq_val); + CHECK(t_dur.nanoseconds() == 1500000000ULL); + + // to_timer_ticks (including rounding up sub-second remainder) + volatile uint64_t one_ns = 1ULL; + volatile uint64_t two_s_ns = 2000000000ULL; + CHECK(Duration::from_nanoseconds(one_ns).to_timer_ticks(zero_u) == 0ULL); + CHECK(Duration::from_nanoseconds(one_ns).to_timer_ticks(freq_val) == 1ULL); + CHECK(Duration::from_nanoseconds(two_s_ns).to_timer_ticks(freq_val) == 2000ULL); + + // from_linux_timespec validation & overflow + Duration out{}; + volatile int64_t neg_val = -1; + volatile int64_t sec_over = INT64_MAX; + volatile int64_t nsec_bad = static_cast(Duration::NS_PER_SEC); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = neg_val, .tv_nsec = 0}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = 0, .tv_nsec = neg_val}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = 0, .tv_nsec = nsec_bad}, out)); + CHECK_FALSE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = sec_over, .tv_nsec = 0}, out)); + + volatile int64_t sec_ok = 3; + volatile int64_t nsec_ok = 250; + REQUIRE( + Duration::from_linux_timespec(linux_timespec{.tv_sec = sec_ok, .tv_nsec = nsec_ok}, out)); + CHECK(out.nanoseconds() == 3000000250ULL); +} + +} // namespace diff --git a/tests/host/fdt_test.cpp b/tests/host/fdt_test.cpp index 8983050..ed99980 100644 --- a/tests/host/fdt_test.cpp +++ b/tests/host/fdt_test.cpp @@ -16,10 +16,18 @@ constexpr uint32_t FDT_MAGIC = 0xD00DFEEDU; constexpr uint32_t FDT_BEGIN_NODE = 0x00000001U; constexpr uint32_t FDT_END_NODE = 0x00000002U; constexpr uint32_t FDT_PROP = 0x00000003U; +constexpr uint32_t FDT_NOP = 0x00000004U; constexpr uint32_t FDT_END = 0x00000009U; class SyntheticDtbBuilder { public: + void add_nop() noexcept { push_be32(FDT_NOP); } + + void add_memreserve(uint64_t addr, uint64_t size) noexcept { + REQUIRE(m_rsv_count < m_rsv.size()); + m_rsv[m_rsv_count++] = RsvEntry{.addr = addr, .size = size}; + } + void begin_node(std::string_view name) noexcept { push_be32(FDT_BEGIN_NODE); for (char chr : name) { @@ -61,13 +69,25 @@ class SyntheticDtbBuilder { align4(); } + void prop_raw(std::string_view name, const void* data, size_t len) noexcept { + const uint32_t nameoff = add_string(name); + push_be32(FDT_PROP); + push_be32(static_cast(len)); + push_be32(nameoff); + const auto* bytes = static_cast(data); + for (size_t idx = 0U; idx < len; ++idx) { + push_byte(bytes[idx]); + } + align4(); + } + uintptr_t finalize() noexcept { push_be32(FDT_END); constexpr size_t HEADER_SIZE = 40U; - constexpr size_t RSVMAP_SIZE = 16U; // Empty terminator (0, 0) + const size_t rsvmap_size = (m_rsv_count + 1U) * 16U; // entries + (0, 0) terminator const size_t off_rsvmap = HEADER_SIZE; - const size_t off_struct = off_rsvmap + RSVMAP_SIZE; + const size_t off_struct = off_rsvmap + rsvmap_size; const size_t off_strings = off_struct + m_struct_len; const size_t total_size = off_strings + m_strings_len; REQUIRE(total_size <= m_blob.size()); @@ -84,11 +104,19 @@ class SyntheticDtbBuilder { write_be32(m_blob.data() + 32U, static_cast(m_strings_len)); write_be32(m_blob.data() + 36U, static_cast(m_struct_len)); + for (size_t i = 0U; i < m_rsv_count; ++i) { + write_be64(m_blob.data() + off_rsvmap + (i * 16U), m_rsv[i].addr); + write_be64(m_blob.data() + off_rsvmap + (i * 16U) + 8U, m_rsv[i].size); + } + std::memcpy(m_blob.data() + off_struct, m_struct.data(), m_struct_len); std::memcpy(m_blob.data() + off_strings, m_strings.data(), m_strings_len); return reinterpret_cast(m_blob.data()); } + uint8_t* blob_data() noexcept { return m_blob.data(); } + static void patch_be32(uint8_t* dst, uint32_t val) noexcept { write_be32(dst, val); } + private: static void write_be32(uint8_t* dst, uint32_t val) noexcept { dst[0] = static_cast((val >> 24U) & 0xFFU); @@ -97,6 +125,11 @@ class SyntheticDtbBuilder { dst[3] = static_cast(val & 0xFFU); } + static void write_be64(uint8_t* dst, uint64_t val) noexcept { + write_be32(dst, static_cast(val >> 32U)); + write_be32(dst + 4U, static_cast(val & 0xFFFFFFFFULL)); + } + void push_byte(uint8_t byte_val) noexcept { REQUIRE(m_struct_len < m_struct.size()); m_struct[m_struct_len++] = byte_val; @@ -125,6 +158,13 @@ class SyntheticDtbBuilder { return offset; } + struct RsvEntry { + uint64_t addr{0ULL}; + uint64_t size{0ULL}; + }; + + std::array m_rsv{}; + size_t m_rsv_count{0U}; std::array m_struct{}; size_t m_struct_len{0U}; std::array m_strings{}; @@ -199,4 +239,207 @@ TEST_CASE("FDT virtio enumeration handles null or corrupt DTB safely", "[fdt][vi Kernel::Boot::VirtioMmioList devices{}; CHECK_FALSE(Kernel::Boot::find_virtio_mmio_devices(0U, devices)); CHECK(devices.count == 0U); + CHECK(Kernel::Boot::find_virtio_mmio_devices(0U).count == 0U); +} + +TEST_CASE("FDT validates headers and rejects malformed offsets", "[fdt][header]") { + CHECK_FALSE(Kernel::Boot::validate_header(0U)); + + SyntheticDtbBuilder builder{}; + builder.begin_node(""); + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + size_t totalsize = 0U; + REQUIRE(Kernel::Boot::validate_header(dtb_paddr, &totalsize)); + CHECK(totalsize >= 40U); + REQUIRE(Kernel::Boot::validate_header(dtb_paddr, nullptr)); + + // Bad magic + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 0U, 0xDEADBEEFU); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 0U, FDT_MAGIC); + + // totalsize too small + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 4U, 16U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 4U, static_cast(totalsize)); + + // off_dt_struct out of bounds + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, 56U); + + // off_dt_strings out of bounds + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, static_cast(totalsize)); + + // off_mem_rsvmap out of bounds and < FDT_HEADER_SIZE + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 16U, + static_cast(totalsize + 4U)); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 16U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 8U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); + SyntheticDtbBuilder::patch_be32(builder.blob_data() + 12U, 8U); + CHECK_FALSE(Kernel::Boot::validate_header(dtb_paddr)); +} + +TEST_CASE("FDT parses memory regions, reservations, initrd, and fw_cfg", "[fdt][memory]") { + // Null DTB fallback behavior + const Kernel::Boot::MemoryMap fallback = Kernel::Boot::find_memory_regions(0U); + CHECK(fallback.count == 1U); + CHECK(fallback.total_usable_bytes > 0U); + CHECK(Kernel::Boot::find_memory_reservations(0U).count == 0U); + CHECK_FALSE(Kernel::Boot::find_initrd(0U).valid); + CHECK_FALSE(Kernel::Boot::find_fw_cfg_device(0U).valid); + + // 64-bit memory regions (overlapping + separate + disabled + device_type), reservations, 64-bit + // initrd, fw_cfg + SyntheticDtbBuilder builder{}; + builder.add_memreserve(0x40000000ULL, 0x10000ULL); + builder.add_memreserve(0x41000000ULL, 0ULL); // zero-size ignored + builder.add_memreserve(0x42000000ULL, 0x20000ULL); + + builder.begin_node(""); + builder.add_nop(); + builder.prop_u32("#address-cells", 2U); + builder.prop_u32("#size-cells", 2U); + + // Memory node 1 (out of order, overlaps node 2) + builder.begin_node("memory@41000000"); + const uint32_t mem1[4] = {0U, 0x41000000U, 0U, 0x01000000U}; + builder.prop_u32_array("reg", mem1, 4U); + builder.end_node(); + + // Memory node 2 (via device_type = "memory") + builder.begin_node("ram-bank"); + builder.prop_string("device_type", "memory"); + const uint32_t mem2[4] = {0U, 0x40000000U, 0U, 0x01200000U}; + builder.prop_u32_array("reg", mem2, 4U); + builder.end_node(); + + // Separate memory node 3 + builder.begin_node("memory@50000000"); + const uint32_t mem3[4] = {0U, 0x50000000U, 0U, 0x00800000U}; + builder.prop_u32_array("reg", mem3, 4U); + builder.end_node(); + + // Disabled memory node (ignored) + builder.begin_node("memory@60000000"); + builder.prop_string("status", "disabled"); + const uint32_t mem_dis[4] = {0U, 0x60000000U, 0U, 0x01000000U}; + builder.prop_u32_array("reg", mem_dis, 4U); + builder.end_node(); + + // chosen node with 64-bit initrd bounds + builder.begin_node("chosen"); + builder.add_nop(); + const uint32_t initrd_start[2] = {0U, 0x44000000U}; + const uint32_t initrd_end[2] = {0U, 0x44100000U}; + builder.prop_u32_array("linux,initrd-start", initrd_start, 2U); + builder.prop_u32_array("linux,initrd-end", initrd_end, 2U); + builder.end_node(); + + // Disabled fw_cfg then valid fw_cfg + builder.begin_node("fw-cfg@9010000"); + builder.prop_string("compatible", "qemu,fw-cfg-mmio"); + builder.prop_string("status", "fail"); + const uint32_t fw_dis[4] = {0U, 0x09010000U, 0U, 0x18U}; + builder.prop_u32_array("reg", fw_dis, 4U); + builder.end_node(); + + builder.begin_node("fw-cfg@9020000"); + builder.prop_string("compatible", "qemu,fw-cfg-mmio"); + const uint32_t fw_reg[4] = {0U, 0x09020000U, 0U, 0x18U}; + builder.prop_u32_array("reg", fw_reg, 4U); + builder.end_node(); + + // Virtio with PPI + 1-cell IRQ + compatible list + builder.begin_node("virtio_mmio@a000200"); + const char compat_list[] = "vendor,custom\0virtio,mmio"; + builder.prop_raw("compatible", compat_list, sizeof(compat_list)); + const uint32_t vreg[4] = {0U, 0x0A000200U, 0U, 0x200U}; + builder.prop_u32_array("reg", vreg, 4U); + const uint32_t ppi_irq[3] = {1U, 11U, 4U}; // PPI 11 -> INTID 27 + builder.prop_u32_array("interrupts", ppi_irq, 3U); + builder.end_node(); + + builder.begin_node("virtio_mmio@a000600"); + builder.prop_string("compatible", "virtio,mmio"); + const uint32_t vreg2[4] = {0U, 0x0A000600U, 0U, 0x200U}; + builder.prop_u32_array("reg", vreg2, 4U); + builder.prop_u32("interrupts", 20U); // 1-cell SPI 20 -> INTID 52 + builder.end_node(); + + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + Kernel::Boot::MemoryMap mmap{}; + REQUIRE(Kernel::Boot::find_memory_regions(dtb_paddr, mmap)); + REQUIRE(mmap.count == 2U); + CHECK(mmap.regions[0].base_paddr == 0x40000000ULL); + CHECK(mmap.regions[0].size == 0x02000000U); // 0x40000000..0x42000000 merged + CHECK(mmap.regions[1].base_paddr == 0x50000000ULL); + CHECK(mmap.min_paddr == 0x40000000ULL); + CHECK(mmap.max_paddr == 0x50800000ULL); + CHECK(mmap.total_usable_bytes == 0x02800000U); + + const Kernel::Boot::ReserveMap rsv = Kernel::Boot::find_memory_reservations(dtb_paddr); + REQUIRE(rsv.count == 2U); + CHECK(rsv.entries[0].base_paddr == 0x40000000ULL); + CHECK(rsv.entries[0].size == 0x10000U); + CHECK(rsv.entries[1].base_paddr == 0x42000000ULL); + + const Kernel::Boot::InitrdLocation initrd = Kernel::Boot::find_initrd(dtb_paddr); + REQUIRE(initrd.valid); + CHECK(initrd.start_paddr == 0x44000000ULL); + CHECK(initrd.end_paddr == 0x44100000ULL); + CHECK(initrd.size == 0x100000U); + + const Kernel::Boot::FwCfgDevice fw = Kernel::Boot::find_fw_cfg_device(dtb_paddr); + REQUIRE(fw.valid); + CHECK(fw.base_paddr == 0x09020000ULL); + CHECK(fw.size == 0x18U); + + const Kernel::Boot::VirtioMmioList vlist = Kernel::Boot::find_virtio_mmio_devices(dtb_paddr); + REQUIRE(vlist.count == 2U); + CHECK(vlist.devices[0].irq_intid == 27U); + CHECK(vlist.devices[1].irq_intid == 52U); +} + +TEST_CASE("FDT handles 32-bit cells, invalid initrd, and empty memory fallback", "[fdt][cells]") { + SyntheticDtbBuilder builder{}; + builder.begin_node(""); + builder.prop_u32("#address-cells", 1U); + builder.prop_u32("#size-cells", 1U); + + builder.begin_node("chosen@0"); + builder.prop_u32("linux,initrd-start", 0x45000000U); + builder.prop_u32("linux,initrd-end", 0x45000000U); // end <= start -> invalid + builder.end_node(); + + builder.begin_node("virtio_mmio@a000000"); + builder.prop_string("compatible", "virtio,mmio"); + const uint32_t vreg[2] = {0x0A000000U, 0x200U}; + builder.prop_u32_array("reg", vreg, 2U); + builder.end_node(); + + builder.end_node(); + const uintptr_t dtb_paddr = builder.finalize(); + + // No memory nodes -> falls back to platform RAM base + FALLBACK_RAM_SIZE + const Kernel::Boot::MemoryMap mmap = Kernel::Boot::find_memory_regions(dtb_paddr); + CHECK(mmap.count == 1U); + CHECK_FALSE(Kernel::Boot::find_initrd(dtb_paddr).valid); + + const Kernel::Boot::VirtioMmioList vlist = Kernel::Boot::find_virtio_mmio_devices(dtb_paddr); + REQUIRE(vlist.count == 1U); + CHECK(vlist.devices[0].base_paddr == 0x0A000000ULL); + CHECK(vlist.devices[0].size == 0x200U); + CHECK_FALSE(vlist.devices[0].has_irq); } \ No newline at end of file diff --git a/tests/host/virtio_blk_test.cpp b/tests/host/virtio_blk_test.cpp index dccc70d..5e3859b 100644 --- a/tests/host/virtio_blk_test.cpp +++ b/tests/host/virtio_blk_test.cpp @@ -59,9 +59,9 @@ struct RecordedRequest { class SimulatedVirtioBlkBackend { public: explicit SimulatedVirtioBlkBackend(uint64_t capacity_sectors, uint16_t max_queue_size = 64U) - : m_storage(static_cast(capacity_sectors) * 512U, 0U), + : m_mmio_paddr(Kernel::MM::alloc_frame()), + m_storage(static_cast(capacity_sectors) * 512U, 0U), m_capacity_sectors(capacity_sectors) { - m_mmio_paddr = Kernel::MM::alloc_frame(); REQUIRE(m_mmio_paddr != 0U); m_mmio_regs = reinterpret_cast(Kernel::MM::phys_to_virt(m_mmio_paddr)); std::memset(const_cast(m_mmio_regs), 0, Arch::AArch64::PAGE_SIZE); @@ -81,6 +81,11 @@ class SimulatedVirtioBlkBackend { } } + SimulatedVirtioBlkBackend(const SimulatedVirtioBlkBackend&) = delete; + SimulatedVirtioBlkBackend& operator=(const SimulatedVirtioBlkBackend&) = delete; + SimulatedVirtioBlkBackend(SimulatedVirtioBlkBackend&&) = delete; + SimulatedVirtioBlkBackend& operator=(SimulatedVirtioBlkBackend&&) = delete; + void attach(VirtioBlkDevice& dev) noexcept { dev.set_host_notify_callback(&SimulatedVirtioBlkBackend::on_notify, this); } @@ -94,6 +99,7 @@ class SimulatedVirtioBlkBackend { } void set_forced_status(uint8_t status) noexcept { m_forced_status = status; } + void set_deferred_irq(bool deferred) noexcept { m_deferred_irq = deferred; } [[nodiscard]] const std::vector& history() const noexcept { return m_history; } [[nodiscard]] const std::vector& storage() const noexcept { return m_storage; } @@ -182,18 +188,22 @@ class SimulatedVirtioBlkBackend { } write_reg32(MMIO_INTERRUPT_STATUS, VIRTIO_MMIO_INT_VRING); - driver.handle_irq(); - CHECK(read_reg32(MMIO_INTERRUPT_STATUS) == 0U); + if (!m_deferred_irq) { + driver.handle_irq(); + CHECK((read_reg32(0x064U) & VIRTIO_MMIO_INT_VRING) != 0U); + write_reg32(MMIO_INTERRUPT_STATUS, 0U); + } } uintptr_t m_mmio_paddr{0U}; volatile uint8_t* m_mmio_regs{nullptr}; - std::vector m_storage{}; + std::vector m_storage; uint64_t m_capacity_sectors{0ULL}; uint16_t m_last_avail_idx{0U}; uint16_t m_used_idx{0U}; uint8_t m_forced_status{VIRTIO_BLK_S_OK}; - std::vector m_history{}; + bool m_deferred_irq{false}; + std::vector m_history; }; } // namespace @@ -245,9 +255,9 @@ TEST_CASE("VirtioBlkDevice 3-descriptor chains, LBA offsets, and error translati CHECK(wr.desc1_flags == VRING_DESC_F_NEXT); // WRITE clear for writes CHECK(wr.desc2_flags == VRING_DESC_F_WRITE); - CHECK(std::memcmp(backend.storage().data() + 4U * 512U, tx.data(), 1024U) == 0); - CHECK(backend.storage()[3U * 512U + 511U] == 0U); - CHECK(backend.storage()[6U * 512U] == 0U); + CHECK(std::memcmp(backend.storage().data() + (size_t{4U} * 512U), tx.data(), 1024U) == 0); + CHECK(backend.storage()[(size_t{3U} * 512U) + 511U] == 0U); + CHECK(backend.storage()[size_t{6U} * 512U] == 0U); std::array rx{}; REQUIRE(blk.read_sectors(4ULL, 2U, rx.data()) == 0); @@ -285,4 +295,104 @@ TEST_CASE("VirtioBlkDevice 3-descriptor chains, LBA offsets, and error translati blk.shutdown(); } + + SECTION("exercises bind_from_bus, init/bind errors, multi-chunk I/O, and IRQ edge cases") { + // Uninitialized operations fail with -EINVAL + VirtioBlkDevice uninit_blk{}; + std::array scratch{}; + CHECK(uninit_blk.read_sectors(0ULL, 1U, scratch.data()) == -EINVAL); + CHECK(uninit_blk.write_sectors(0ULL, 1U, scratch.data()) == -EINVAL); + CHECK(uninit_blk.flush() == -EINVAL); + uninit_blk.handle_irq(); // null/uninitialized slot + VirtioBlkDevice::irq_trampoline(0U, nullptr); + + // init() fails on invalid magic + SimulatedVirtioBlkBackend bad_magic(/*capacity_sectors=*/8ULL); + bad_magic.write_reg32(MMIO_MAGIC_VALUE, 0U); + CHECK_FALSE(uninit_blk.init(bad_magic.mmio_paddr())); + + // init() fails on zero capacity + SimulatedVirtioBlkBackend zero_cap(/*capacity_sectors=*/0ULL); + CHECK_FALSE(uninit_blk.init(zero_cap.mmio_paddr())); + + // bind() fails on wrong device_id and zero queue size + VirtioMmioSlot slot{}; + SimulatedVirtioBlkBackend wrong_dev(/*capacity_sectors=*/8ULL); + wrong_dev.write_reg32(MMIO_DEVICE_ID, VIRTIO_DEV_ID_NET); + REQUIRE(slot.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 0U, + .base_paddr = wrong_dev.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + CHECK_FALSE(VirtioBlkDevice::bind_from_bus(slot, nullptr)); + CHECK_FALSE(VirtioBlkDevice::bind_from_bus(slot, &uninit_blk)); + + SimulatedVirtioBlkBackend zero_q(/*capacity_sectors=*/8ULL, /*max_queue_size=*/0U); + VirtioMmioSlot slot_zq{}; + REQUIRE(slot_zq.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 1U, + .base_paddr = zero_q.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + CHECK_FALSE(uninit_blk.bind(slot_zq)); + + // Valid bind_from_bus, re-bind, re-init, multi-chunk (> MAX_SECTORS_PER_CHUNK), and + // deferred IRQ + SimulatedVirtioBlkBackend backend(/*capacity_sectors=*/16ULL); + backend.write_reg32(MMIO_DEVICE_FEATURES, 1U); + VirtioMmioSlot valid_slot{}; + REQUIRE(valid_slot.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 2U, + .base_paddr = backend.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + REQUIRE(VirtioBlkDevice::bind_from_bus(valid_slot, &uninit_blk)); + + SimulatedVirtioBlkBackend backend2(/*capacity_sectors=*/16ULL); + backend2.write_reg32(MMIO_DEVICE_FEATURES, 1U); + VirtioMmioSlot valid_slot2{}; + REQUIRE(valid_slot2.probe_slot(VirtioMmioSlotConfig{ + .slot_index = 3U, + .base_paddr = backend2.mmio_paddr(), + .region_size = Arch::AArch64::PAGE_SIZE, + .spi_irq = 0U, + })); + REQUIRE(uninit_blk.bind(valid_slot2)); // re-bind shuts down cleanly + + SimulatedVirtioBlkBackend backend3(/*capacity_sectors=*/16ULL); + backend3.write_reg32(MMIO_DEVICE_FEATURES, 1U); + REQUIRE(uninit_blk.init(backend3.mmio_paddr())); // re-init shuts down cleanly + + backend3.attach(uninit_blk); + backend3.set_deferred_irq(true); + + constexpr size_t kMultiCount = 8U; // > MAX_SECTORS_PER_CHUNK (7) + std::array multi_tx{}; + for (size_t i = 0U; i < multi_tx.size(); ++i) { + multi_tx[i] = static_cast(i & 0xFFU); + } + REQUIRE(uninit_blk.write_sectors(0ULL, kMultiCount, multi_tx.data()) == 0); + + std::array multi_rx{}; + REQUIRE(uninit_blk.read_sectors(0ULL, kMultiCount, multi_rx.data()) == 0); + CHECK(std::memcmp(multi_rx.data(), multi_tx.data(), multi_tx.size()) == 0); + + // Flush OK & unknown status -> -EIO + CHECK(uninit_blk.flush() == 0); + backend3.set_forced_status(0x7FU); + CHECK(uninit_blk.write_sectors(0ULL, 1U, multi_tx.data()) == -EIO); + CHECK(uninit_blk.read_sectors(0ULL, 1U, multi_rx.data()) == -EIO); + + // handle_irq with 0 and non-VRING status, plus irq_trampoline + backend3.write_reg32(MMIO_INTERRUPT_STATUS, 0U); + uninit_blk.handle_irq(); + backend3.write_reg32(MMIO_INTERRUPT_STATUS, VIRTIO_MMIO_INT_CONFIG); + VirtioBlkDevice::irq_trampoline(0U, &uninit_blk); + CHECK((backend3.read_reg32(0x064U) & VIRTIO_MMIO_INT_CONFIG) != 0U); + + uninit_blk.shutdown(); + } } \ No newline at end of file