diff --git a/.github/workflows/hardware-workspace.yml b/.github/workflows/hardware-workspace.yml index b3fe6226a..da5e32ab0 100644 --- a/.github/workflows/hardware-workspace.yml +++ b/.github/workflows/hardware-workspace.yml @@ -1,34 +1,41 @@ -name: Reaper Hardware Workspace v1 +name: Reaper Linux UIO Physical MMIO on: push: branches: [main, "feat/**", "integration/**"] paths: - - "selfhost/hardware_workspace.rpr" - - "tests/hardware_workspace_conformance.rpr" - - "tests/test_hardware_workspace.py" + - "include/reaper/hardware.h" + - "include/reaper/hardware_uio.h" + - "src/hardware.c" + - "src/hardware_uio.c" + - "tests/test_hardware.c" + - "tests/test_hardware_uio.c" + - "CMakeLists.txt" - ".github/workflows/hardware-workspace.yml" pull_request: paths: - - "selfhost/hardware_workspace.rpr" - - "tests/hardware_workspace_conformance.rpr" - - "tests/test_hardware_workspace.py" + - "include/reaper/hardware.h" + - "include/reaper/hardware_uio.h" + - "src/hardware.c" + - "src/hardware_uio.c" + - "tests/test_hardware.c" + - "tests/test_hardware_uio.c" + - "CMakeLists.txt" - ".github/workflows/hardware-workspace.yml" permissions: contents: read jobs: - conformance: - name: Execute Reaper hardware contracts + linux-uio: + name: Build and test Linux physical MMIO transport runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 10 steps: - uses: actions/checkout@v7 - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - name: Compile the hardware test harness - run: python -m py_compile tests/test_hardware_workspace.py - - name: Execute Reaper-native hardware contract fixtures - run: python -m unittest tests.test_hardware_workspace -v + - name: Configure native C17 build and UIO tests + run: cmake -S . -B build-uio -DCMAKE_BUILD_TYPE=Release -DREAPER_BUILD_TESTS=ON + - name: Build UIO backend and checked MMIO tests + run: cmake --build build-uio --parallel --target reaper-hardware-tests reaper-hardware-uio-tests + - name: Execute fake-bus and file-backed physical MMIO tests + run: ctest --test-dir build-uio --output-on-failure -R '^native-hardware(-uio)?$' diff --git a/CMakeLists.txt b/CMakeLists.txt index c849065df..81d0850eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,12 +10,17 @@ set(CMAKE_C_EXTENSIONS OFF) add_library(reaper_hardware STATIC src/hardware.c) target_include_directories(reaper_hardware PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_library(reaper_hardware_uio STATIC src/hardware_uio.c) + target_include_directories(reaper_hardware_uio PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(reaper_hardware_uio PUBLIC reaper_hardware) + set_target_properties(reaper_hardware_uio PROPERTIES POSITION_INDEPENDENT_CODE ON) + target_compile_options(reaper_hardware_uio PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) +endif() + add_library(reaper_locale_tag STATIC src/locale_tag.c) target_include_directories(reaper_locale_tag PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) -add_library(reaper_evolution STATIC src/evolution.c) -target_include_directories(reaper_evolution PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - add_library(reaper_token_catalog STATIC src/token_catalog.c) target_include_directories(reaper_token_catalog PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) @@ -52,9 +57,6 @@ reaper_add_source_module(reaper_frontend_objects src/ast_json.c ) -add_library(reaper_snapshot_audit STATIC src/snapshot_audit.c) -target_include_directories(reaper_snapshot_audit PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - reaper_add_source_module(reaper_data_objects src/harw.c src/harw_value.c @@ -77,18 +79,6 @@ reaper_add_source_module(reaper_architecture_services_objects # dependency verification. # Static leaves extracted from the broader object groups after verifying their # public-header and symbol dependencies. The aggregate remains a compatibility target. -add_library(reaper_locale_tag STATIC src/locale_tag.c) -target_include_directories(reaper_locale_tag PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - -add_library(reaper_capability_suite STATIC src/capability_suite.c) -target_include_directories(reaper_capability_suite PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) -if(UNIX) - target_link_libraries(reaper_capability_suite PUBLIC m) -endif() - -add_library(reaper_hardware STATIC src/hardware.c) -target_include_directories(reaper_hardware PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) - add_library(reaper_system_features STATIC src/system_features.c) target_include_directories(reaper_system_features PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) @@ -129,6 +119,9 @@ add_library(reaper_core STATIC ) target_include_directories(reaper_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(reaper_core PUBLIC reaper_division reaper_locale_tag reaper_capability_suite reaper_hardware reaper_system_features reaper_evolution reaper_lineage reaper_architecture reaper_snapshot_audit) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_link_libraries(reaper_core PUBLIC reaper_hardware_uio) +endif() if(UNIX) target_link_libraries(reaper_core PUBLIC m) endif() @@ -316,6 +309,15 @@ if(REAPER_BUILD_TESTS) target_link_libraries(reaper-hardware-tests PRIVATE reaper_core) reaper_enable_native_test_assertions(reaper-hardware-tests) add_test(NAME native-hardware COMMAND reaper-hardware-tests) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_executable(reaper-hardware-uio-tests tests/test_hardware_uio.c src/hardware_uio.c) + target_include_directories(reaper-hardware-uio-tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_compile_definitions(reaper-hardware-uio-tests PRIVATE REAPER_HW_UIO_TESTING=1) + target_link_libraries(reaper-hardware-uio-tests PRIVATE reaper_hardware) + target_compile_options(reaper-hardware-uio-tests PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) + reaper_enable_native_test_assertions(reaper-hardware-uio-tests) + add_test(NAME native-hardware-uio COMMAND reaper-hardware-uio-tests) + endif() add_executable(reaper-hw-graph-tests tests/test_hw_graph.c) target_link_libraries(reaper-hw-graph-tests PRIVATE reaper_core) add_test(NAME native-hardware-graph COMMAND reaper-hw-graph-tests) @@ -449,6 +451,10 @@ install(TARGETS reaper_ffi_shared RUNTIME DESTINATION bin ARCHIVE DESTINATION lib ) +install(TARGETS reaper_hardware ARCHIVE DESTINATION lib) install(TARGETS reaper_system ARCHIVE DESTINATION lib) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + install(TARGETS reaper_hardware_uio ARCHIVE DESTINATION lib) +endif() install(TARGETS reaper_dabi64_desktop ARCHIVE DESTINATION lib) -install(FILES include/reaper/ffi.h include/reaper/system.h include/reaper/intrinsics.h include/reaper/dabi64_desktop.h include/reaper/architecture.h include/reaper/snapshot_audit.h include/reaper/system_features.h include/reaper/godra.h include/reaper/locale_tag.h include/reaper/linguistic_system.h include/reaper/harw.h include/reaper/harw_value.h include/reaper/harw_context.h DESTINATION include/reaper) +install(FILES include/reaper/ffi.h include/reaper/system.h include/reaper/intrinsics.h include/reaper/dabi64_desktop.h include/reaper/architecture.h include/reaper/snapshot_audit.h include/reaper/system_features.h include/reaper/godra.h include/reaper/locale_tag.h include/reaper/linguistic_system.h include/reaper/harw.h include/reaper/harw_value.h include/reaper/harw_context.h include/reaper/hardware.h include/reaper/hardware_uio.h DESTINATION include/reaper) diff --git a/docs/EMBEDDED_C_WORKBENCH.md b/docs/EMBEDDED_C_WORKBENCH.md index 1506323d2..b18f22335 100644 --- a/docs/EMBEDDED_C_WORKBENCH.md +++ b/docs/EMBEDDED_C_WORKBENCH.md @@ -1,6 +1,6 @@ # Embedded C workbench -Reference MCU profiles, FLASH/SRAM budgets and starter templates are advisory. MMIO is simulated only. No firmware, bootloader, physical register or device is flashed or written. Verify vendor documentation before hardware use. +Reference MCU profiles, FLASH/SRAM budgets and starter templates remain advisory. A Linux UIO physical MMIO backend is now available for peripherals exported by a reviewed UIO kernel driver; the native fake-bus API remains available for tests. This does not add MCU probe programming, firmware flashing, bootloader writes, interrupts or DMA. Verify the vendor memory map and driver configuration before accessing hardware. ## Processor/kernel control model @@ -16,3 +16,8 @@ The native core now exposes a checked MMIO descriptor and host-adapter API in in The versioned, executable Reaper contract is in `selfhost/hardware_workspace.rpr`; its schema, exact data shapes and trust boundaries are documented in [HARDWARE_WORKSPACE_V1.md](HARDWARE_WORKSPACE_V1.md). It validates target triples and ABI metadata, typed peripheral/register manifests, non-overlapping Flash/SRAM/ROM/MMIO/reserved/DMA maps, linker-section placement, stack/heap/static/IRQ/DMA budgets, typed inspection-IR projections, simulator argv plans, captured register/memory snapshots, and per-project authorization preflight. The contract suite runs as `python -m unittest tests.test_hardware_workspace -v`. This remains a policy/validation layer: it does not run a compiler, launch QEMU, connect a probe, map physical addresses, flash firmware, or enforce privileged OS/driver authorization. + + +## Linux UIO physical backend + +On Linux, include/reaper/hardware_uio.h and src/hardware_uio.c implement a real UIO-backed MMIO transport for reviewed UIO_MEM_PHYS drivers. The backend checks the character-device major/minor identity, requires expected_base = sysfs addr + offset, limits expected_size to size - offset, maps only the pages intersecting the grant, and rejects writes unless REAPER_HW_CAP_MMIO_WRITE is explicitly granted and the process can open the node writable. The sysfs ABI does not expose map memory type, so audit the selected driver's registration before use. No /dev/mem fallback. See [Linux UIO physical MMIO backend](LINUX_UIO_HARDWARE_BACKEND.md). Hosted CI uses a file-backed mapping, not a physical board. diff --git a/docs/HARDWARE_LANGUAGE.md b/docs/HARDWARE_LANGUAGE.md index 3e2ac502a..ba3f76acf 100644 --- a/docs/HARDWARE_LANGUAGE.md +++ b/docs/HARDWARE_LANGUAGE.md @@ -33,8 +33,8 @@ The language is not allowed to imply that user-space code can safely access arbi | Native compiler | scalar AOT subset emits C17 and invokes a host GCC/Clang-compatible compiler | no full native parity, no direct ELF/PE/Mach-O emitter | | C17 core | native lexer, expression parser, owned AST, checked integer IR, constant folding and limited lowering | IR and parser cover only a small subset | | QCS | separate hardware-domain lexer/parser and JSON AST | design/validation frontend, not device execution | -| Embedded workbench | MCU profiles, Flash/SRAM maps, linker-script generation and cross-compiler process invocation | no board flashing or physical MMIO | -| Reaper-native Hardware Workspace v1 | Reaper-source contracts for target tuples, typed manifests, section maps, budgets, inspection IR, simulator plans, debug snapshots and authorization preflight | no target-qualified backend, live probe, physical MMIO or OS authorization | +| Embedded workbench | MCU profiles, Flash/SRAM maps, linker-script generation, cross-compiler process plans and Linux UIO physical MMIO transport | UIO-backed MMIO only; no MCU probe, flashing, interrupts or DMA | +| Reaper-native Hardware Workspace v1 | Reaper-source contracts for target tuples, typed manifests, section maps, budgets, inspection IR, simulator plans, debug snapshots and authorization preflight | contracts remain policy metadata; see Linux UIO native transport below | | Studio | Windows editor/debugger foundation plus a Systems/Hardware overview showing MCU profiles and current access limits | no live device inspector or complete hardware IDE | | Native capability catalogue | versioned module and operation descriptions with a small set of C primitives | catalogue entries are not automatically executable handlers | @@ -113,7 +113,9 @@ The C API in include/reaper/hardware.h provides: - capability checks before read/write callbacks; - a host-supplied bus adapter, enabling deterministic fake-device tests. -The API does **not** map physical memory, execute privileged instructions, register real interrupts, allocate DMA memory or communicate with a real device by itself. A trusted OS driver/HAL must supply the adapter and enforce platform-specific mapping, cache, barrier and privilege rules. W1C/W1S writes are passed as explicit values; clients must not implement them as an implicit read-modify-write sequence. +The Linux UIO backend in include/reaper/hardware_uio.h and src/hardware_uio.c now supplies a physical MMIO bus for a reviewed UIO map. It verifies the /dev/uioN character-device identity against sysfs, pins the expected physical base and size, bounds every access, honours the selected read/write grant and applies target-specific I/O barriers. It never falls back to /dev/mem. See [Linux UIO physical MMIO backend](LINUX_UIO_HARDWARE_BACKEND.md). + +The backend does **not** flash firmware, speak SWD/JTAG, enumerate CMSIS-DAP/J-Link/ST-Link probes, register interrupts, allocate/synchronize DMA memory or enforce a cryptographic per-project broker. The kernel UIO driver owns the physical mapping and memory attributes; OS device-node permissions remain the effective privilege boundary. W1C/W1S writes are passed as explicit values; clients must not implement them as an implicit read-modify-write sequence. ## Current native hardware graph planner @@ -213,4 +215,4 @@ The downstream DuckOS integration is specified separately in [DUCKOS_SYSTEM_SERV The Reaper-native contract module is `selfhost/hardware_workspace.rpr`; its versioned data shapes, checks and evidence boundaries are documented in [HARDWARE_WORKSPACE_V1.md](HARDWARE_WORKSPACE_V1.md). The new conformance fixture executes the contracts with the reference runtime and checks valid and rejected project descriptions. This adds executable validation for target/triple/ABI tuples, typed peripheral registers, region/section layout, resource budgets, annotated inspection IR, shell-free simulator plans, captured debugger data, and project authorization preflight. -This is not a claim of live device access or completed compiler backends. The native C MMIO API remains the separate checked bus-adapter surface; this Reaper module does not perform physical mapping. QEMU plans are not launched, snapshots are supplied by adapters, and the host OS/driver remains the actual privilege authority. +This is not a claim of live device access or completed compiler backends. The Reaper-source policy module does not itself perform physical mapping. A separate Linux native C transport now provides bounded UIO-backed MMIO for reviewed UIO_MEM_PHYS kernel drivers; see [Linux UIO physical MMIO backend](LINUX_UIO_HARDWARE_BACKEND.md). The UIO sysfs ABI does not expose map memory type, so the selected kernel driver must be audited before use. This does not add MCU probe programming, firmware flashing, interrupts or DMA. QEMU plans are not launched, snapshots are supplied by adapters, and the host OS/driver remains the actual privilege authority. diff --git a/docs/HARDWARE_WORKSPACE_V1.md b/docs/HARDWARE_WORKSPACE_V1.md index ca967307a..b5dbbd8e7 100644 --- a/docs/HARDWARE_WORKSPACE_V1.md +++ b/docs/HARDWARE_WORKSPACE_V1.md @@ -62,4 +62,4 @@ The fixtures cover valid STM32F0-style target/project data and negative cases fo ## Explicit non-claims -This milestone does not implement physical MMIO mapping, board flashing, firmware deployment, interrupt registration, DMA transfer, privileged driver loading, vendor-probe discovery, or live target debugging. It does not claim that every target in the existing advisory MCU catalogue has an installed cross-compiler. A future host adapter must separately prove executable path resolution, target/ABI compatibility, process lifecycle, privilege checks, audit persistence and hardware-in-the-loop qualification before any live action is enabled. +The Reaper-source policy module itself does not perform physical MMIO mapping, board flashing, firmware deployment, interrupt registration, DMA transfer, privileged driver loading, vendor-probe discovery, or live target debugging. A separate Linux native C transport is now available for UIO-exported MMIO maps; see [Linux UIO physical MMIO backend](LINUX_UIO_HARDWARE_BACKEND.md). That transport still requires a reviewed kernel UIO driver, exact map identity, OS device-node permissions and board-specific hardware-in-the-loop qualification. The repository does not claim that every target in the advisory MCU catalogue has an installed cross-compiler or a physical transport. diff --git a/docs/LINUX_UIO_HARDWARE_BACKEND.md b/docs/LINUX_UIO_HARDWARE_BACKEND.md new file mode 100644 index 000000000..f852734fa --- /dev/null +++ b/docs/LINUX_UIO_HARDWARE_BACKEND.md @@ -0,0 +1,121 @@ +# Linux UIO physical MMIO backend + +**Status:** Linux UIO transport implemented; hardware-in-the-loop qualification is board-specific and not claimed by repository CI. +**Native API:** include/reaper/hardware_uio.h +**Implementation:** src/hardware_uio.c +**Tests:** tests/test_hardware_uio.c + +## What this backend does + +The Linux backend connects the existing checked ReaperHwBus descriptor API to a memory region exported by a Linux UIO character device. It performs real volatile 8-, 16-, 32- and (on 64-bit hosts) 64-bit MMIO loads/stores through the UIO mapping. + +Before mapping, it verifies all of the following: + +- the path is exactly /dev/uioN, not an arbitrary file or /dev/mem; +- the opened object is a character device; +- its major:minor identity matches /sys/class/uio/uioN/dev; +- the selected UIO map has a page-aligned address and page-multiple size; +- the project's expected_base equals sysfs addr + offset; +- the granted byte count fits within sysfs size - offset; +- only the pages intersecting the granted range are mapped; +- the resulting map is at most 64 MiB; +- the caller provides an explicit non-zero capability mask. + +Each access is checked again against the selected physical base and size. The bus adapter also independently checks the read/write capability. Endian conversion is performed at the width requested by the register descriptor. Ordered accesses use CPU I/O barriers on x86_64, ARMv7+/AArch64 and RISC-V. On other Linux architectures, only relaxed access ordering is accepted; acquire/release/seq-cst requests fail closed. + +The backend consumes the existing ReaperHwRegion and ReaperHwRegister contracts. Width, alignment, register access mode, required capability bits and read/write memory-order validation remain enforced by reaper_hw_read / reaper_hw_write before the physical callback executes. + +## Build + +Linux only: + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREAPER_BUILD_TESTS=ON +cmake --build build --parallel +ctest --test-dir build --output-on-failure -R 'native-hardware(-uio)?' +``` + +The UIO test suite uses an unlinked temporary file as a memory-backed device. It exercises actual mmap access, byte order, width, ordering, read-only capability enforcement, map bounds and rejection of unapproved device paths. It does not open or write a physical device in CI. + +## Device setup + +A platform-specific kernel driver must first register the device as UIO and expose a map under /sys/class/uio/uioN/maps/mapM. The driver owns the safe physical resource reservation and the map's memory attributes. The host administrator must then grant the intended process access to /dev/uioN using the platform's normal device-permission mechanism (for example a narrowly scoped udev rule). + +Inspect the identity and map metadata before creating the Reaper project grant: + +```sh +cat /sys/class/uio/uio0/name +cat /sys/class/uio/uio0/dev +cat /sys/class/uio/uio0/maps/map0/addr +cat /sys/class/uio/uio0/maps/map0/size +cat /sys/class/uio/uio0/maps/map0/offset +stat -c '%F %t:%T %n' /dev/uio0 +``` + +Do not grant broad access to every UIO node. Grant only the node and map belonging to the intended peripheral, and use a read-only device-node permission where inspection is sufficient. + +## Native C usage + +The example below intentionally grants read capability only. The expected base and size must come from a reviewed board manifest and must match the selected UIO driver's sysfs map. + +```c +#include "reaper/hardware.h" +#include "reaper/hardware_uio.h" + +#include +#include + +int main(void) { + ReaperHwUioConfig config = { + .device_path = "/dev/uio0", + .map_index = 0, + .expected_base = UINT64_C(0x48000000), + .expected_size = UINT64_C(0x1000), + .granted_capabilities = REAPER_HW_CAP_MMIO_READ + }; + ReaperHwUio *uio = NULL; + ReaperHwBus bus = {0}; + ReaperHwRegion region = {0}; + ReaperHwRegister id = { + .name = "DEVICE_ID", + .offset = 0x00, + .width_bits = 32, + .access = REAPER_HW_ACCESS_READ_ONLY, + .endian = REAPER_HW_ENDIAN_LITTLE, + .required_capabilities = 0 + }; + ReaperHwError error = {0}; + uint64_t value = 0; + + if (reaper_hw_uio_open(&config, &uio, &error) != REAPER_HW_OK) { + fprintf(stderr, "UIO open failed: %s\n", error.message); + return 1; + } + if (reaper_hw_uio_get_region(uio, ®ion, &error) != REAPER_HW_OK || + reaper_hw_uio_get_bus(uio, &bus, &error) != REAPER_HW_OK || + reaper_hw_read(&bus, ®ion, &id, config.granted_capabilities, + REAPER_HW_ORDER_ACQUIRE, &value, &error) != REAPER_HW_OK) { + fprintf(stderr, "MMIO read failed: %s\n", error.message); + reaper_hw_uio_close(uio); + return 1; + } + + printf("DEVICE_ID = 0x%08llx\n", (unsigned long long)value); + reaper_hw_uio_close(uio); + return 0; +} +``` + +To enable writes, the host must opt in by including REAPER_HW_CAP_MMIO_WRITE in the grant and the process must have write permission to the selected UIO node. This is deliberately not the default. The register descriptor must independently permit the write. W1C/W1S writes are sent directly as the caller-supplied mask; the backend never performs an implicit read-modify-write. + +## Trust boundary and limits + +- The UIO sysfs ABI does not expose the kernel map's uio_mem.memtype. Audit the selected driver and use this physical transport only when it registers the map as UIO_MEM_PHYS. Standard uio_pci_generic and uio_pdrv_genirq drivers use UIO_MEM_PHYS; a custom UIO_MEM_LOGICAL/ UIO_MEM_VIRTUAL map is not a physical MMIO transport. +- Linux UIO and the kernel driver are the mapping/physical-resource boundary. The Reaper library does not elevate privileges. +- The granted_capabilities field is a host-supplied grant, not a cryptographic project identity or an authorization broker. The OS device-node permissions remain the effective process boundary. A future broker must validate the project manifest and persist the audit record before granting a writable UIO descriptor. +- /dev/mem, arbitrary physical-address mappings, kernel module loading, board flashing and bootloader writes are not implemented. +- This backend does not enumerate MCU debug probes, speak CMSIS-DAP/J-Link/ST-Link, execute SWD/JTAG transactions, manage interrupts or allocate/synchronize DMA buffers. +- UIO memory attributes and hardware barriers still depend on the selected kernel driver and CPU/platform. A board is not qualified merely because the UIO map opens. +- CI uses a file-backed mapping test; no physical board is attached to hosted runners. + +The first supported physical transport is therefore **Linux UIO-backed MMIO for devices whose reviewed kernel driver exposes a UIO map**. MCU probe and firmware-programming support require separate transports and their own authorization/qualification gates. diff --git a/docs/README.md b/docs/README.md index de0b1d290..456207d9a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,6 +22,7 @@ The Python tree-walk runtime is a temporary compatibility implementation and dif - [Reaper System Features](REAPER_SYSTEM_FEATURES_V1.md) — bounded systems-language contracts and maturity. - [DABI64 Desktop Host](DABI64_DESKTOP_HOST_V1.md) — desktop ABI and host-provider boundary. - [Hardware Workspace v1](HARDWARE_WORKSPACE_V1.md) — executable Reaper contracts for target profiles, manifests, memory maps, resource budgets, inspection IR, simulator plans, captured debugging and authorization preflight. +- [Linux UIO Hardware Backend](LINUX_UIO_HARDWARE_BACKEND.md) — bounded Linux physical MMIO transport for UIO-exported device maps, with explicit access grants. ## Developer experience diff --git a/docs/REAPER_IDE.md b/docs/REAPER_IDE.md index f2bcd48c1..c03b6379c 100644 --- a/docs/REAPER_IDE.md +++ b/docs/REAPER_IDE.md @@ -102,3 +102,10 @@ Do not present target selection, live register inspection, firmware flashing, or The executable v1 contracts live in [HARDWARE_WORKSPACE_V1.md](HARDWARE_WORKSPACE_V1.md) and selfhost/hardware_workspace.rpr. The Reaper source validates target tuples, MCU manifests, memory maps and linker-section placements, resource ceilings, annotated inspection IR, simulator argv plans, captured debugger snapshots, and hardware authorization preflight records. The regression fixtures are Reaper source executed by tests/test_hardware_workspace.py. The implementation is intentionally not a privileged adapter: it does not map physical addresses, execute QEMU, connect to a debug probe, flash a board, or enforce OS-level authorization. The compiler inspector consumes an explicit inspection interchange rather than claiming that the current native backend emits all typed ownership/effect data. See the contract document for exact data shapes and verification boundaries. + + +## Linux UIO physical MMIO transport + +The checked native C MMIO descriptors now have a Linux UIO transport in `include/reaper/hardware_uio.h` and `src/hardware_uio.c`. It opens one explicitly named `/dev/uioN`, verifies the character-device identity and selected sysfs map, derives the granted physical range from `addr + offset` and `size - offset`, and maps only the pages needed for that grant. Writes require an explicit `REAPER_HW_CAP_MMIO_WRITE` grant and writable device-node permissions; there is no `/dev/mem` fallback. + +This is a native host transport, not a Reaper-language built-in and not a generic MCU programmer. The selected kernel driver must be reviewed to confirm it registers a `UIO_MEM_PHYS` map; UIO sysfs does not expose the memory type. The transport does not add SWD/JTAG, CMSIS-DAP, ST-Link/J-Link, flashing, interrupts or DMA. CI uses a file-backed mapping and does not claim hardware-in-the-loop qualification. See [Linux UIO physical MMIO backend](LINUX_UIO_HARDWARE_BACKEND.md). diff --git a/include/reaper/hardware_uio.h b/include/reaper/hardware_uio.h new file mode 100644 index 000000000..ac94f379c --- /dev/null +++ b/include/reaper/hardware_uio.h @@ -0,0 +1,72 @@ +#ifndef REAPER_HARDWARE_UIO_H +#define REAPER_HARDWARE_UIO_H + +#include "reaper/hardware.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__linux__) + +/* + * Linux UIO-backed physical MMIO transport. + * + * Access is restricted to one named /dev/uioN device and one map whose + * physical base is verified against sysfs. The caller must separately obtain + * OS device-node permissions and pass an explicit capability grant. + * + * The default grant is read-only. No /dev/mem fallback is provided. + */ +typedef struct ReaperHwUio ReaperHwUio; + +typedef struct { + const char *device_path; /* Exactly /dev/uioN */ + uint32_t map_index; + uint64_t expected_base; /* Must match sysfs mapN/addr + mapN/offset */ + uint64_t expected_size; /* Non-zero, <= sysfs mapN/size - mapN/offset */ + uint32_t granted_capabilities; /* READ by default; WRITE must be explicit */ +} ReaperHwUioConfig; + +ReaperHwStatus reaper_hw_uio_open( + const ReaperHwUioConfig *config, + ReaperHwUio **out_uio, + ReaperHwError *error +); + +ReaperHwStatus reaper_hw_uio_get_region( + const ReaperHwUio *uio, + ReaperHwRegion *region, + ReaperHwError *error +); + +ReaperHwStatus reaper_hw_uio_get_bus( + ReaperHwUio *uio, + ReaperHwBus *bus, + ReaperHwError *error +); + +void reaper_hw_uio_close(ReaperHwUio *uio); + +#ifdef REAPER_HW_UIO_TESTING +/* Test-only anonymous-file attachment. Never exported by the production library. */ +ReaperHwStatus reaper_hw_uio_test_bind( + int backing_fd, + uint64_t physical_base, + size_t region_size, + size_t page_offset, + uint32_t granted_capabilities, + ReaperHwUio **out_uio, + ReaperHwError *error +); +#endif + +#endif /* __linux__ */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware_uio.c b/src/hardware_uio.c new file mode 100644 index 000000000..871389a80 --- /dev/null +++ b/src/hardware_uio.c @@ -0,0 +1,629 @@ +#define _GNU_SOURCE 1 + +#include "reaper/hardware_uio.h" + +#if defined(__linux__) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define REAPER_HW_UIO_SYSFS_ROOT "/sys/class/uio" +#define REAPER_HW_UIO_MAX_MAP_BYTES (UINT64_C(64) * UINT64_C(1024) * UINT64_C(1024)) +#define REAPER_HW_UIO_MAX_ATTRIBUTE 96U + +#if defined(__x86_64__) || defined(__aarch64__) || \ + (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || \ + defined(__riscv) +#define REAPER_HW_UIO_HAS_IO_BARRIER 1 +#else +#define REAPER_HW_UIO_HAS_IO_BARRIER 0 +#endif + +struct ReaperHwUio { + int fd; + void *mapping; + size_t mapping_length; + volatile uint8_t *register_base; + uint64_t physical_base; + uint64_t region_size; + uint32_t granted_capabilities; +}; + +static ReaperHwStatus uio_fail( + ReaperHwError *error, + ReaperHwStatus status, + uint64_t address, + const char *message +) { + if (error != NULL) { + error->status = status; + error->address = address; + (void)snprintf(error->message, sizeof error->message, "%s", message); + } + return status; +} + +static ReaperHwStatus uio_fail_errno( + ReaperHwError *error, + ReaperHwStatus status, + uint64_t address, + const char *operation +) { + char message[160]; + (void)snprintf(message, sizeof message, "%s: %s", operation, strerror(errno)); + return uio_fail(error, status, address, message); +} + +static void uio_clear_error(ReaperHwError *error) { + if (error != NULL) { + error->status = REAPER_HW_OK; + error->address = 0; + error->message[0] = '\0'; + } +} + +static bool valid_capabilities(uint32_t capabilities) { + const uint32_t allowed = REAPER_HW_CAP_MMIO_READ | REAPER_HW_CAP_MMIO_WRITE; + return capabilities != 0U && (capabilities & ~allowed) == 0U; +} + +static bool parse_uio_device(const char *path, unsigned *device_index) { + static const char prefix[] = "/dev/uio"; + const char *cursor; + unsigned value = 0U; + + if (path == NULL || device_index == NULL || + strncmp(path, prefix, sizeof prefix - 1U) != 0) + return false; + + cursor = path + sizeof prefix - 1U; + if (*cursor == '\0') return false; + for (; *cursor != '\0'; ++cursor) { + unsigned digit; + if (*cursor < '0' || *cursor > '9') return false; + digit = (unsigned)(*cursor - '0'); + if (value > (UINT_MAX - digit) / 10U) return false; + value = value * 10U + digit; + } + *device_index = value; + return true; +} + +static bool read_sysfs_device_number( + unsigned device_index, + unsigned *device_major, + unsigned *device_minor +) { + char path[160]; + char buffer[64]; + char *cursor; + char *end = NULL; + unsigned long parsed_major; + unsigned long parsed_minor; + ssize_t length; + int fd; + size_t index; + + if (device_major == NULL || device_minor == NULL) return false; + if (snprintf(path, sizeof path, "%s/uio%u/dev", + REAPER_HW_UIO_SYSFS_ROOT, device_index) >= (int)sizeof path) + return false; + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + length = read(fd, buffer, sizeof buffer - 1U); + (void)close(fd); + if (length <= 0) return false; + buffer[(size_t)length] = '\0'; + + errno = 0; + parsed_major = strtoul(buffer, &end, 10); + if (errno != 0 || end == buffer || *end != ':') return false; + cursor = end + 1; + errno = 0; + parsed_minor = strtoul(cursor, &end, 10); + if (errno != 0 || end == cursor || + parsed_major > UINT_MAX || parsed_minor > UINT_MAX) + return false; + for (index = (size_t)(end - buffer); index < (size_t)length; ++index) { + if (buffer[index] != ' ' && buffer[index] != '\t' && + buffer[index] != '\r' && buffer[index] != '\n') + return false; + } + *device_major = (unsigned)parsed_major; + *device_minor = (unsigned)parsed_minor; + return true; +} + +static bool read_sysfs_u64( + unsigned device_index, + uint32_t map_index, + const char *attribute, + uint64_t *value +) { + char path[256]; + char buffer[REAPER_HW_UIO_MAX_ATTRIBUTE]; + char *end = NULL; + unsigned long long parsed; + ssize_t length; + int fd; + size_t index; + + if (value == NULL) return false; + if (snprintf(path, sizeof path, "%s/uio%u/maps/map%u/%s", + REAPER_HW_UIO_SYSFS_ROOT, device_index, map_index, attribute) + >= (int)sizeof path) + return false; + + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + length = read(fd, buffer, sizeof buffer - 1U); + { + const int saved_errno = errno; + (void)close(fd); + errno = saved_errno; + } + if (length <= 0) return false; + buffer[(size_t)length] = '\0'; + + errno = 0; + parsed = strtoull(buffer, &end, 0); + if (errno != 0 || end == buffer) return false; + for (index = (size_t)(end - buffer); index < (size_t)length; ++index) { + if (buffer[index] != ' ' && buffer[index] != '\t' && + buffer[index] != '\r' && buffer[index] != '\n') + return false; + } + *value = (uint64_t)parsed; + return true; +} + +static uint64_t byte_swap(uint64_t value, uint8_t width_bits) { + switch (width_bits) { + case 8: + return value & UINT64_C(0xff); + case 16: + return (uint64_t)__builtin_bswap16((uint16_t)value); + case 32: + return (uint64_t)__builtin_bswap32((uint32_t)value); + case 64: + return __builtin_bswap64(value); + default: + return value; + } +} + +static bool host_is_little_endian(void) { + const uint16_t marker = UINT16_C(1); + return *((const uint8_t *)&marker) == UINT8_C(1); +} + +static uint64_t convert_endian( + uint64_t value, + uint8_t width_bits, + ReaperHwEndian endian +) { + bool device_little; + if (endian == REAPER_HW_ENDIAN_NATIVE) return value; + device_little = endian == REAPER_HW_ENDIAN_LITTLE; + return device_little == host_is_little_endian() + ? value : byte_swap(value, width_bits); +} + +static bool valid_uio_read_order(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_RELAXED) return true; +#if REAPER_HW_UIO_HAS_IO_BARRIER + return order == REAPER_HW_ORDER_ACQUIRE || + order == REAPER_HW_ORDER_SEQ_CST; +#else + return false; +#endif +} + +static bool valid_uio_write_order(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_RELAXED) return true; +#if REAPER_HW_UIO_HAS_IO_BARRIER + return order == REAPER_HW_ORDER_RELEASE || + order == REAPER_HW_ORDER_SEQ_CST; +#else + return false; +#endif +} + +static bool valid_uio_endian(ReaperHwEndian endian) { + return endian == REAPER_HW_ENDIAN_NATIVE || + endian == REAPER_HW_ENDIAN_LITTLE || + endian == REAPER_HW_ENDIAN_BIG; +} + +static bool address_to_offset( + const ReaperHwUio *uio, + uint64_t address, + uint8_t width_bits, + size_t *offset +) { + uint64_t width_bytes; + uint64_t relative; + + if (uio == NULL || offset == NULL) return false; + switch (width_bits) { + case 8: width_bytes = 1U; break; + case 16: width_bytes = 2U; break; + case 32: width_bytes = 4U; break; + case 64: width_bytes = 8U; break; + default: return false; + } + if (address < uio->physical_base) return false; + relative = address - uio->physical_base; + if (relative > uio->region_size || + width_bytes > uio->region_size - relative || + relative > (uint64_t)SIZE_MAX) + return false; + if ((address % width_bytes) != 0U) return false; + *offset = (size_t)relative; + return true; +} + +static void device_io_barrier(void) { +#if defined(__aarch64__) + __asm__ volatile("dmb osh" ::: "memory"); +#elif defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 + __asm__ volatile("dmb" ::: "memory"); +#elif defined(__riscv) + __asm__ volatile("fence iorw, iorw" ::: "memory"); +#elif defined(__x86_64__) + __asm__ volatile("mfence" ::: "memory"); +#else + atomic_thread_fence(memory_order_seq_cst); +#endif +} + +static void device_read_barrier_before(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_SEQ_CST) device_io_barrier(); +} + +static void device_read_barrier_after(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_ACQUIRE || order == REAPER_HW_ORDER_SEQ_CST) + device_io_barrier(); +} + +static void device_write_barrier_before(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_RELEASE || order == REAPER_HW_ORDER_SEQ_CST) + device_io_barrier(); +} + +static void device_write_barrier_after(ReaperHwMemoryOrder order) { + if (order == REAPER_HW_ORDER_SEQ_CST) device_io_barrier(); +} + +static int uio_bus_read( + void *context, + ReaperHwSpace space, + uint64_t address, + uint8_t width_bits, + ReaperHwEndian endian, + ReaperHwMemoryOrder order, + uint64_t *value +) { + ReaperHwUio *uio = (ReaperHwUio *)context; + size_t offset; + volatile uint8_t *p; + uint64_t raw; + + if (uio == NULL || value == NULL || space != REAPER_HW_SPACE_MMIO || + (uio->granted_capabilities & REAPER_HW_CAP_MMIO_READ) == 0U || + !valid_uio_read_order(order) || !valid_uio_endian(endian) || + !address_to_offset(uio, address, width_bits, &offset)) + return 0; + + if (width_bits == 64 && sizeof(uintptr_t) < 8U) return 0; + device_read_barrier_before(order); + p = uio->register_base + offset; + switch (width_bits) { + case 8: raw = *(volatile uint8_t *)p; break; + case 16: raw = *(volatile uint16_t *)p; break; + case 32: raw = *(volatile uint32_t *)p; break; + case 64: raw = *(volatile uint64_t *)p; break; + default: return 0; + } + device_read_barrier_after(order); + *value = convert_endian(raw, width_bits, endian); + return 1; +} + +static int uio_bus_write( + void *context, + ReaperHwSpace space, + uint64_t address, + uint8_t width_bits, + ReaperHwEndian endian, + ReaperHwMemoryOrder order, + uint64_t value +) { + ReaperHwUio *uio = (ReaperHwUio *)context; + size_t offset; + volatile uint8_t *p; + uint64_t raw; + + if (uio == NULL || space != REAPER_HW_SPACE_MMIO || + (uio->granted_capabilities & REAPER_HW_CAP_MMIO_WRITE) == 0U || + !valid_uio_write_order(order) || !valid_uio_endian(endian) || + !address_to_offset(uio, address, width_bits, &offset)) + return 0; + + if (width_bits == 64U && sizeof(uintptr_t) < 8U) return 0; + p = uio->register_base + offset; + raw = convert_endian(value, width_bits, endian); + device_write_barrier_before(order); + switch (width_bits) { + case 8: *(volatile uint8_t *)p = (uint8_t)raw; break; + case 16: *(volatile uint16_t *)p = (uint16_t)raw; break; + case 32: *(volatile uint32_t *)p = (uint32_t)raw; break; + case 64: *(volatile uint64_t *)p = raw; break; + default: return 0; + } + device_write_barrier_after(order); + return 1; +} + +static ReaperHwStatus create_mapping( + int fd, + uint64_t physical_base, + uint64_t region_size, + size_t mapping_length, + size_t page_offset, + uint32_t capabilities, + off_t file_offset, + ReaperHwUio **out_uio, + ReaperHwError *error +) { + ReaperHwUio *uio; + void *mapping; + int map_protection = PROT_READ; + + if (out_uio == NULL || *out_uio != NULL || fd < 0 || + region_size == 0U || !valid_capabilities(capabilities) || + mapping_length == 0U || page_offset >= mapping_length || + region_size > (uint64_t)(mapping_length - page_offset)) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, physical_base, + "invalid UIO mapping arguments"); + + if ((capabilities & REAPER_HW_CAP_MMIO_WRITE) != 0U) + map_protection |= PROT_WRITE; + + mapping = mmap(NULL, mapping_length, map_protection, MAP_SHARED, fd, file_offset); + if (mapping == MAP_FAILED) + return uio_fail_errno(error, REAPER_HW_BUS_FAILURE, physical_base, + "mmap UIO region"); + + uio = (ReaperHwUio *)calloc(1U, sizeof *uio); + if (uio == NULL) { + (void)munmap(mapping, mapping_length); + return uio_fail(error, REAPER_HW_BUS_FAILURE, physical_base, + "allocate UIO adapter state"); + } + + uio->fd = fd; + uio->mapping = mapping; + uio->mapping_length = mapping_length; + uio->register_base = (volatile uint8_t *)mapping + page_offset; + uio->physical_base = physical_base; + uio->region_size = region_size; + uio->granted_capabilities = capabilities; + *out_uio = uio; + uio_clear_error(error); + return REAPER_HW_OK; +} + +ReaperHwStatus reaper_hw_uio_open( + const ReaperHwUioConfig *config, + ReaperHwUio **out_uio, + ReaperHwError *error +) { + unsigned device_index; + uint64_t sysfs_base = 0U; + uint64_t sysfs_size = 0U; + uint64_t page_offset = 0U; + uint64_t map_length; + uint64_t file_offset; + long page_size; + int fd; + struct stat metadata; + ReaperHwStatus status; + + uio_clear_error(error); + if (out_uio == NULL) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, 0U, + "UIO output handle is required"); + if (*out_uio != NULL) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, 0U, + "UIO output handle must be NULL"); + if (config == NULL || !parse_uio_device(config->device_path, &device_index) || + config->expected_size == 0U || + config->expected_size > REAPER_HW_UIO_MAX_MAP_BYTES || + config->expected_size > UINT64_MAX - config->expected_base || + !valid_capabilities(config->granted_capabilities)) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, 0U, + "expected /dev/uioN, bounded range and explicit capabilities"); + + fd = open(config->device_path, + ((config->granted_capabilities & REAPER_HW_CAP_MMIO_WRITE) != 0U + ? O_RDWR : O_RDONLY) | O_CLOEXEC | O_NOFOLLOW); + if (fd < 0) + return uio_fail_errno(error, REAPER_HW_ACCESS_DENIED, config->expected_base, + "open UIO device"); + if (fstat(fd, &metadata) != 0 || !S_ISCHR(metadata.st_mode)) { + (void)close(fd); + return uio_fail(error, REAPER_HW_ACCESS_DENIED, config->expected_base, + "UIO path is not a character device"); + } + { + unsigned sysfs_major = 0U; + unsigned sysfs_minor = 0U; + if (!read_sysfs_device_number(device_index, &sysfs_major, &sysfs_minor) || + sysfs_major != major(metadata.st_rdev) || + sysfs_minor != minor(metadata.st_rdev)) { + (void)close(fd); + return uio_fail(error, REAPER_HW_ACCESS_DENIED, config->expected_base, + "opened UIO character device does not match sysfs identity"); + } + } + if (!read_sysfs_u64(device_index, config->map_index, "addr", &sysfs_base) || + !read_sysfs_u64(device_index, config->map_index, "size", &sysfs_size) || + !read_sysfs_u64(device_index, config->map_index, "offset", &page_offset)) { + (void)close(fd); + return uio_fail(error, REAPER_HW_BUS_FAILURE, config->expected_base, + "cannot read UIO map identity from sysfs"); + } + + page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0 || page_offset >= (uint64_t)page_size) { + (void)close(fd); + return uio_fail(error, REAPER_HW_INVALID_REGION, config->expected_base, + "UIO map offset is not a valid page offset"); + } + if (sysfs_base % (uint64_t)page_size != 0U || + sysfs_size == 0U || sysfs_size % (uint64_t)page_size != 0U || + page_offset >= (uint64_t)page_size || + sysfs_base > UINT64_MAX - page_offset || + sysfs_base + page_offset != config->expected_base || + page_offset >= sysfs_size || + config->expected_size > sysfs_size - page_offset) { + (void)close(fd); + return uio_fail(error, REAPER_HW_ACCESS_DENIED, config->expected_base, + "UIO map is not a page-aligned physical map or its granted range does not match sysfs"); + } + + /* Map only the pages intersecting the explicitly granted resource. + UIO reports a page-aligned map base; offset identifies the real + resource start within the first page. */ + if (config->expected_size > UINT64_MAX - page_offset || + page_offset + config->expected_size > + UINT64_MAX - ((uint64_t)page_size - 1U)) { + (void)close(fd); + return uio_fail(error, REAPER_HW_INVALID_REGION, config->expected_base, + "granted UIO range overflows the mmap length"); + } + map_length = ((page_offset + config->expected_size + + (uint64_t)page_size - 1U) / + (uint64_t)page_size) * (uint64_t)page_size; + if (map_length > sysfs_size || + map_length > REAPER_HW_UIO_MAX_MAP_BYTES || + map_length > (uint64_t)SIZE_MAX) { + (void)close(fd); + return uio_fail(error, REAPER_HW_INVALID_REGION, config->expected_base, + "granted UIO pages exceed the bounded sysfs map"); + } + if ((uint64_t)config->map_index > + (uint64_t)INT64_MAX / (uint64_t)page_size) { + (void)close(fd); + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, config->expected_base, + "UIO map index overflows the mmap file offset"); + } + file_offset = (uint64_t)config->map_index * (uint64_t)page_size; + { + const off_t mmap_offset = (off_t)file_offset; + if (mmap_offset < 0 || (uint64_t)mmap_offset != file_offset) { + (void)close(fd); + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, config->expected_base, + "UIO map index does not fit the host mmap offset type"); + } + + status = create_mapping(fd, config->expected_base, config->expected_size, + (size_t)map_length, (size_t)page_offset, + config->granted_capabilities, mmap_offset, + out_uio, error); + } + if (status != REAPER_HW_OK) { + (void)close(fd); + return status; + } + return REAPER_HW_OK; +} + +ReaperHwStatus reaper_hw_uio_get_region( + const ReaperHwUio *uio, + ReaperHwRegion *region, + ReaperHwError *error +) { + uio_clear_error(error); + if (uio == NULL || region == NULL) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, 0U, + "UIO handle and region output are required"); + region->base = uio->physical_base; + region->size = uio->region_size; + region->space = REAPER_HW_SPACE_MMIO; + return REAPER_HW_OK; +} + +ReaperHwStatus reaper_hw_uio_get_bus( + ReaperHwUio *uio, + ReaperHwBus *bus, + ReaperHwError *error +) { + uio_clear_error(error); + if (uio == NULL || bus == NULL) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, 0U, + "UIO handle and bus output are required"); + bus->context = uio; + bus->read = uio_bus_read; + bus->write = uio_bus_write; + return REAPER_HW_OK; +} + +void reaper_hw_uio_close(ReaperHwUio *uio) { + if (uio == NULL) return; + if (uio->mapping != NULL && uio->mapping != MAP_FAILED) + (void)munmap(uio->mapping, uio->mapping_length); + if (uio->fd >= 0) (void)close(uio->fd); + memset(uio, 0, sizeof *uio); + free(uio); +} + +#ifdef REAPER_HW_UIO_TESTING +ReaperHwStatus reaper_hw_uio_test_bind( + int backing_fd, + uint64_t physical_base, + size_t region_size, + size_t page_offset, + uint32_t granted_capabilities, + ReaperHwUio **out_uio, + ReaperHwError *error +) { + long page_size = sysconf(_SC_PAGESIZE); + int fd; + size_t mapping_length; + + uio_clear_error(error); + if (page_size <= 0 || page_offset >= (size_t)page_size || + region_size == 0U || region_size > REAPER_HW_UIO_MAX_MAP_BYTES || + region_size > SIZE_MAX - page_offset) + return uio_fail(error, REAPER_HW_INVALID_ARGUMENT, physical_base, + "invalid test mapping range"); + mapping_length = region_size + page_offset; + fd = fcntl(backing_fd, F_DUPFD_CLOEXEC, 0); + if (fd < 0) + return uio_fail_errno(error, REAPER_HW_BUS_FAILURE, physical_base, + "duplicate test backing file"); + { + ReaperHwStatus status = create_mapping(fd, physical_base, region_size, + mapping_length, page_offset, + granted_capabilities, 0, out_uio, error); + if (status != REAPER_HW_OK) (void)close(fd); + return status; + } +} +#endif + +#endif /* __linux__ */ diff --git a/tests/test_hardware_uio.c b/tests/test_hardware_uio.c new file mode 100644 index 000000000..c82369fb0 --- /dev/null +++ b/tests/test_hardware_uio.c @@ -0,0 +1,164 @@ +#define _GNU_SOURCE 1 +#define REAPER_HW_UIO_TESTING 1 + +#include "reaper/hardware.h" +#include "reaper/hardware_uio.h" + +#include +#include +#include +#include +#include +#include +#include + +static int make_backing_file(void) { + char path[] = "/tmp/reaper-uio-test-XXXXXX"; + int fd = mkstemp(path); + assert(fd >= 0); + assert(unlink(path) == 0); + assert(ftruncate(fd, 4096) == 0); + return fd; +} + +static void test_physical_register_access_and_endian(void) { + int fd = make_backing_file(); + ReaperHwUio *uio = NULL; + ReaperHwError error = {0}; + ReaperHwBus bus = {0}; + ReaperHwRegion region = {0}; + const uint32_t grants = REAPER_HW_CAP_MMIO_READ | REAPER_HW_CAP_MMIO_WRITE; + ReaperHwRegister reg32 = { + "DATA", 0x10, 32, REAPER_HW_ACCESS_READ_WRITE, + REAPER_HW_ENDIAN_LITTLE, 0 + }; + ReaperHwRegister reg16 = { + "CONTROL", 0x20, 16, REAPER_HW_ACCESS_READ_WRITE, + REAPER_HW_ENDIAN_BIG, 0 + }; + uint64_t value = 0; + + assert(reaper_hw_uio_test_bind(fd, UINT64_C(0x40000000), 256U, 16U, + grants, &uio, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_region(uio, ®ion, &error) == REAPER_HW_OK); + assert(region.base == UINT64_C(0x40000000)); + assert(region.size == 256U); + assert(region.space == REAPER_HW_SPACE_MMIO); + assert(reaper_hw_uio_get_bus(uio, &bus, &error) == REAPER_HW_OK); + + assert(reaper_hw_write(&bus, ®ion, ®32, grants, + REAPER_HW_ORDER_RELEASE, UINT64_C(0x1234ABCD), + &error) == REAPER_HW_OK); + assert(reaper_hw_read(&bus, ®ion, ®32, grants, + REAPER_HW_ORDER_ACQUIRE, &value, &error) == REAPER_HW_OK); + assert(value == UINT64_C(0x1234ABCD)); + { + uint8_t bytes[4] = {0}; + assert(pread(fd, bytes, sizeof bytes, 32) == (ssize_t)sizeof bytes); + assert(bytes[0] == 0xCDU && bytes[1] == 0xABU && + bytes[2] == 0x34U && bytes[3] == 0x12U); + } + + assert(reaper_hw_write(&bus, ®ion, ®16, grants, + REAPER_HW_ORDER_SEQ_CST, UINT64_C(0x1122), + &error) == REAPER_HW_OK); + assert(reaper_hw_read(&bus, ®ion, ®16, grants, + REAPER_HW_ORDER_SEQ_CST, &value, &error) == REAPER_HW_OK); + assert(value == UINT64_C(0x1122)); + { + uint8_t bytes[2] = {0}; + assert(pread(fd, bytes, sizeof bytes, 48) == (ssize_t)sizeof bytes); + assert(bytes[0] == 0x11U && bytes[1] == 0x22U); + } + + reaper_hw_uio_close(uio); + assert(close(fd) == 0); +} + +static void test_capability_is_enforced_by_transport(void) { + int fd = make_backing_file(); + ReaperHwUio *uio = NULL; + ReaperHwError error = {0}; + ReaperHwBus bus = {0}; + ReaperHwRegion region = {0}; + ReaperHwRegister reg = { + "WRITE_GUARDED", 0, 32, REAPER_HW_ACCESS_READ_WRITE, + REAPER_HW_ENDIAN_NATIVE, 0 + }; + const uint32_t read_only = REAPER_HW_CAP_MMIO_READ; + + assert(reaper_hw_uio_test_bind(fd, UINT64_C(0x50000000), 128U, 0U, + read_only, &uio, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_region(uio, ®ion, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_bus(uio, &bus, &error) == REAPER_HW_OK); + assert(reaper_hw_write(&bus, ®ion, ®, + REAPER_HW_CAP_MMIO_WRITE, REAPER_HW_ORDER_RELEASE, + UINT64_C(0xDEADBEEF), &error) == REAPER_HW_BUS_FAILURE); + reaper_hw_uio_close(uio); + assert(close(fd) == 0); +} + +static void test_transport_rejects_out_of_map_and_unapproved_device_paths(void) { + int fd = make_backing_file(); + ReaperHwUio *uio = NULL; + ReaperHwError error = {0}; + ReaperHwBus bus = {0}; + ReaperHwRegion region = {0}; + ReaperHwUio *opened = NULL; + ReaperHwUioConfig config = { + "/tmp/anything", 0U, UINT64_C(0x60000000), 128U, + REAPER_HW_CAP_MMIO_READ + }; + uint64_t value = 0; + + assert(reaper_hw_uio_test_bind(fd, UINT64_C(0x60000000), 128U, 0U, + REAPER_HW_CAP_MMIO_READ, + &uio, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_region(uio, ®ion, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_bus(uio, &bus, &error) == REAPER_HW_OK); + assert(bus.read(bus.context, REAPER_HW_SPACE_MMIO, + UINT64_C(0x60000080), 32, REAPER_HW_ENDIAN_NATIVE, + REAPER_HW_ORDER_RELAXED, &value) == 0); + assert(reaper_hw_uio_open(&config, &opened, &error) == REAPER_HW_INVALID_ARGUMENT); + assert(opened == NULL); + reaper_hw_uio_close(uio); + assert(close(fd) == 0); +} + +static void test_read_only_transport_can_read(void) { + int fd = make_backing_file(); + ReaperHwUio *uio = NULL; + ReaperHwError error = {0}; + ReaperHwBus bus = {0}; + ReaperHwRegion region = {0}; + ReaperHwRegister reg = { + "ID", 0, 32, REAPER_HW_ACCESS_READ_ONLY, + REAPER_HW_ENDIAN_NATIVE, 0 + }; + uint64_t value = 0; + const uint32_t read_only = REAPER_HW_CAP_MMIO_READ; + + assert(reaper_hw_uio_test_bind(fd, UINT64_C(0x70000000), 128U, 0U, + read_only, &uio, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_region(uio, ®ion, &error) == REAPER_HW_OK); + assert(reaper_hw_uio_get_bus(uio, &bus, &error) == REAPER_HW_OK); + assert(reaper_hw_read(&bus, ®ion, ®, read_only, + REAPER_HW_ORDER_ACQUIRE, &value, &error) == REAPER_HW_OK); + assert(bus.read(bus.context, REAPER_HW_SPACE_MMIO, region.base, + 32, REAPER_HW_ENDIAN_NATIVE, REAPER_HW_ORDER_RELEASE, + &value) == 0); + assert(bus.read(bus.context, REAPER_HW_SPACE_MMIO, region.base, + 32, (ReaperHwEndian)99, REAPER_HW_ORDER_RELAXED, + &value) == 0); + reaper_hw_uio_close(uio); + assert(close(fd) == 0); +} + +int main(void) { + test_physical_register_access_and_endian(); + test_capability_is_enforced_by_transport(); + test_transport_rejects_out_of_map_and_unapproved_device_paths(); + test_read_only_transport_can_read(); + puts("Linux UIO physical MMIO backend tests passed"); + return 0; +}