From 5cf18d3cbbfce963af732b43d7cb2587f8ee8d33 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:44:43 +0000 Subject: [PATCH] feat(gpu): integrate sealed native compiler and resource cuts --- Cargo.lock | 7 + Cargo.toml | 1 + crates/stela-drivers/Cargo.toml | 26 +- crates/stela-drivers/build.rs | 112 +- crates/stela-drivers/build/intel.rs | 202 ++ crates/stela-drivers/src/gpu/amd.rs | 8 + .../stela-drivers/src/gpu/amd/amdgpu/Makefile | 2 + .../gpu/amd/amdgpu/amdgpu_apu_flags_core.h | 70 + .../src/gpu/amd/amdgpu/amdgpu_device.c | 107 +- .../src/gpu/amd/amdgpu/amdgpu_discovery.c | 754 +++---- .../src/gpu/amd/amdgpu/amdgpu_discovery.h | 3 +- .../amd/amdgpu/amdgpu_discovery_file_core.h | 53 + .../gpu/amd/amdgpu/amdgpu_discovery_ip_core.h | 308 +++ .../amd/amdgpu/amdgpu_discovery_source_core.h | 142 ++ .../amd/amdgpu/amdgpu_discovery_tmr_core.h | 159 ++ .../amd/amdgpu/amdgpu_discovery_tmr_limits.h | 28 + .../src/gpu/amd/amdgpu/amdgpu_doorbell_mgr.c | 18 +- .../src/gpu/amd/amdgpu/amdgpu_drv.c | 1144 +---------- .../src/gpu/amd/amdgpu/amdgpu_ip.h | 57 +- .../amd/amdgpu/amdgpu_ip_instance_limits.h | 29 + .../src/gpu/amd/amdgpu/amdgpu_ip_limits.h | 32 + .../src/gpu/amd/amdgpu/amdgpu_ip_types.h | 80 + .../gpu/amd/amdgpu/amdgpu_mm_access_core.h | 73 + .../gpu/amd/amdgpu/amdgpu_pci_match_core.h | 1210 ++++++++++++ .../src/gpu/amd/amdgpu/amdgpu_sdma.h | 2 +- .../src/gpu/amd/amdgpu/amdgpu_vcn.h | 2 +- .../src/gpu/amd/amdgpu/amdgpu_virt.c | 24 +- .../src/gpu/amd/amdgpu/amdgpu_virt.h | 5 +- .../amd/amdgpu/amdgpu_virt_bootstrap_core.h | 62 + .../src/gpu/amd/amdgpu/amdgpu_vpe.h | 2 +- crates/stela-drivers/src/gpu/amd/discovery.rs | 689 +++++++ .../src/gpu/amd/include/amd_chip_flags.h | 48 + .../src/gpu/amd/include/amd_shared.h | 22 +- .../src/gpu/amd/include/discovery.h | 32 +- .../stela-drivers/src/gpu/amd/native_mmio.rs | 586 ++++++ crates/stela-drivers/src/gpu/amd/pci.rs | 278 +++ .../stela-drivers/src/gpu/amd/stela/Makefile | 304 +++ .../src/gpu/amd/stela/air_compile.c | 419 ++++ .../src/gpu/amd/stela/air_compile.h | 136 ++ .../stela-drivers/src/gpu/amd/stela/compute.c | 2 +- .../stela-drivers/src/gpu/amd/stela/compute.h | 4 +- .../src/gpu/amd/stela/discovery_binary.c | 331 ++++ .../src/gpu/amd/stela/discovery_binary.h | 84 + .../src/gpu/amd/stela/discovery_file.c | 12 + .../src/gpu/amd/stela/discovery_file.h | 11 + .../src/gpu/amd/stela/discovery_ip.c | 82 + .../src/gpu/amd/stela/discovery_ip.h | 25 + .../src/gpu/amd/stela/discovery_tmr.c | 93 + .../src/gpu/amd/stela/discovery_tmr.h | 34 + .../src/gpu/amd/stela/native_bar.c | 48 + .../src/gpu/amd/stela/native_bar.h | 110 ++ .../src/gpu/amd/stela/pci_match.c | 106 + .../src/gpu/amd/stela/pci_match.h | 59 + .../stela-drivers/src/gpu/amd/stela/vram_mm.c | 53 + .../stela-drivers/src/gpu/amd/stela/vram_mm.h | 41 + .../src/gpu/amd/tests/air_compile.c | 731 +++++++ .../src/gpu/amd/tests/compute_test.c | 5 + .../src/gpu/amd/tests/discovery.rs | 143 ++ .../src/gpu/amd/tests/discovery_binary_test.c | 452 +++++ .../src/gpu/amd/tests/discovery_file.c | 100 + .../src/gpu/amd/tests/discovery_file.rs | 541 +++++ .../gpu/amd/tests/discovery_file_reference.h | 74 + .../src/gpu/amd/tests/discovery_ip.c | 249 +++ .../src/gpu/amd/tests/discovery_ip.rs | 217 ++ .../src/gpu/amd/tests/discovery_ip_fixture.c | 13 + .../gpu/amd/tests/discovery_ip_reference.h | 283 +++ .../src/gpu/amd/tests/discovery_reference.h | 1182 +++++++++++ .../gpu/amd/tests/discovery_refresh_test.c | 218 +++ .../src/gpu/amd/tests/discovery_tmr.c | 203 ++ .../src/gpu/amd/tests/discovery_tmr_fixture.c | 12 + .../gpu/amd/tests/discovery_tmr_reference.h | 114 ++ .../src/gpu/amd/tests/discovery_tmr_test_io.h | 4 + .../amd/tests/discovery_tmr_virt_reference.h | 63 + .../src/gpu/amd/tests/native_bar_test.c | 283 +++ .../src/gpu/amd/tests/native_mmio.rs | 570 ++++++ crates/stela-drivers/src/gpu/amd/tests/pci.rs | 217 ++ .../src/gpu/amd/tests/pci_match.c | 294 +++ .../src/gpu/amd/tests/pci_reference.h | 1737 +++++++++++++++++ .../stela-drivers/src/gpu/amd/tests/vram.rs | 65 + .../stela-drivers/src/gpu/amd/tests/vram_mm.c | 185 ++ .../src/gpu/amd/tests/vram_mm_reference.h | 70 + .../src/gpu/amd/tests/vram_mm_test_io.h | 10 + crates/stela-drivers/src/gpu/amd/vram.rs | 73 + .../common/linux/include/drm/amd_asic_type.h | 8 + .../gpu/common/linux/include/linux/rbtree.h | 10 +- .../linux/include/linux/rbtree_augmented.h | 8 +- .../common/linux/include/linux/rbtree_types.h | 11 +- .../src/gpu/common/mesa/meson.options | 6 + .../gpu/common/mesa/src/stela/air_metadata.c | 727 +++++++ .../gpu/common/mesa/src/stela/air_metadata.h | 150 ++ .../gpu/common/mesa/src/stela/air_to_nir.c | 410 +--- .../gpu/common/mesa/src/stela/air_to_nir.h | 39 +- .../common/mesa/src/stela/air_to_nir_test.c | 242 +++ .../src/gpu/common/mesa/src/stela/meson.build | 128 +- crates/stela-drivers/src/gpu/intel.rs | 6 + .../stela-drivers/src/gpu/intel/activation.rs | 697 +++++++ .../stela-drivers/src/gpu/intel/firmware.rs | 508 +++++ crates/stela-drivers/src/gpu/intel/ggtt.rs | 125 ++ .../stela-drivers/src/gpu/intel/guc_reset.rs | 42 + crates/stela-drivers/src/gpu/intel/pat.rs | 48 + .../src/gpu/intel/stela/Makefile | 370 ++++ .../src/gpu/intel/stela/activation.c | 314 +++ .../src/gpu/intel/stela/activation.h | 69 + .../src/gpu/intel/stela/firmware.c | 232 +++ .../src/gpu/intel/stela/firmware.h | 90 + .../src/gpu/intel/stela/ggtt_probe.c | 63 + .../src/gpu/intel/stela/ggtt_probe.h | 30 + .../src/gpu/intel/stela/guc_reset.c | 119 ++ .../src/gpu/intel/stela/guc_reset.h | 23 + .../src/gpu/intel/stela/hosted/air_compile.c | 375 ++++ .../src/gpu/intel/stela/hosted/air_compile.h | 131 ++ .../gpu/intel/stela/hosted/air_validate_elk.c | 11 + .../stela-drivers/src/gpu/intel/stela/pat.c | 71 + .../stela-drivers/src/gpu/intel/stela/pat.h | 23 + .../src/gpu/intel/stela/tests/activation.c | 241 +++ .../src/gpu/intel/stela/tests/activation.rs | 1073 ++++++++++ .../gpu/intel/stela/tests/activation_donor.c | 66 + .../gpu/intel/stela/tests/activation_donor.h | 9 + .../src/gpu/intel/stela/tests/air_compile.c | 760 ++++++++ .../src/gpu/intel/stela/tests/firmware.c | 184 ++ .../src/gpu/intel/stela/tests/firmware.rs | 453 +++++ .../gpu/intel/stela/tests/firmware_donor.c | 101 + .../gpu/intel/stela/tests/firmware_donor.h | 16 + .../src/gpu/intel/stela/tests/ggtt_probe.c | 79 + .../gpu/intel/stela/tests/ggtt_probe_donor.c | 27 + .../gpu/intel/stela/tests/ggtt_probe_donor.h | 8 + .../src/gpu/intel/stela/tests/guc_reset.c | 272 +++ .../gpu/intel/stela/tests/guc_reset_bind.h | 23 + .../gpu/intel/stela/tests/guc_reset_donor.c | 4 + .../gpu/intel/stela/tests/guc_reset_linux.c | 4 + .../gpu/intel/stela/tests/guc_reset_model.h | 31 + .../src/gpu/intel/stela/tests/huc_firmware.c | 181 ++ .../intel/stela/tests/huc_firmware_donor.c | 56 + .../src/gpu/intel/stela/tests/pat.c | 111 ++ .../src/gpu/intel/stela/tests/pat_donor.c | 99 + .../src/gpu/intel/stela/tests/pat_donor.h | 16 + .../src/gpu/intel/stela/tests/rbtree.c | 155 ++ .../src/gpu/intel/stela/tests/rbtree.mk | 63 + .../src/gpu/intel/stela/tests/rbtree_abi.c | 19 + .../gpu/intel/stela/tests/rbtree_algorithm.c | 4 + .../src/gpu/intel/stela/tests/rbtree_bind.h | 33 + .../src/gpu/intel/stela/tests/wopcm.c | 136 ++ .../src/gpu/intel/stela/tests/wopcm.rs | 153 ++ .../src/gpu/intel/stela/tests/wopcm_donor.c | 83 + .../src/gpu/intel/stela/tests/wopcm_donor.h | 25 + .../src/gpu/intel/stela/tests/wopcm_owned.c | 162 ++ .../stela-drivers/src/gpu/intel/stela/wopcm.c | 126 ++ .../stela-drivers/src/gpu/intel/stela/wopcm.h | 32 + crates/stela-drivers/src/gpu/intel/wopcm.rs | 117 ++ .../src/gpu/intel/xe/abi/uc_fw_abi.h | 5 + .../src/gpu/intel/xe/regs/xe_guc_regs.h | 7 + .../src/gpu/intel/xe/regs/xe_reg_defs.h | 51 +- .../src/gpu/intel/xe/regs/xe_reg_type.h | 55 + .../src/gpu/intel/xe/xe_cache_level.h | 13 + .../src/gpu/intel/xe/xe_device_types.h | 2 +- .../src/gpu/intel/xe/xe_engine_ids.h | 54 + .../src/gpu/intel/xe/xe_force_wake.c | 91 +- .../src/gpu/intel/xe/xe_force_wake.h | 6 +- .../src/gpu/intel/xe/xe_force_wake_core.h | 78 + .../gpu/intel/xe/xe_force_wake_domain_types.h | 81 + .../src/gpu/intel/xe/xe_force_wake_gt.h | 30 + .../src/gpu/intel/xe/xe_force_wake_types.h | 73 +- .../stela-drivers/src/gpu/intel/xe/xe_ggtt.c | 24 +- .../src/gpu/intel/xe/xe_ggtt_probe_core.h | 44 + .../src/gpu/intel/xe/xe_gt_type.h | 12 + .../src/gpu/intel/xe/xe_gt_types.h | 6 +- .../stela-drivers/src/gpu/intel/xe/xe_guc.c | 88 +- .../stela-drivers/src/gpu/intel/xe/xe_guc.h | 8 +- .../src/gpu/intel/xe/xe_guc_reset_core.h | 129 ++ .../stela-drivers/src/gpu/intel/xe/xe_huc.c | 3 +- .../src/gpu/intel/xe/xe_huc_role.h | 10 + .../src/gpu/intel/xe/xe_hw_engine_types.h | 47 +- .../stela-drivers/src/gpu/intel/xe/xe_mmio.c | 86 +- .../src/gpu/intel/xe/xe_mmio_poll.h | 57 + .../src/gpu/intel/xe/xe_mmio_verify.h | 21 + .../stela-drivers/src/gpu/intel/xe/xe_pat.c | 371 +--- .../stela-drivers/src/gpu/intel/xe/xe_pat.h | 8 + .../src/gpu/intel/xe/xe_pat_program.h | 25 + .../src/gpu/intel/xe/xe_pat_select.h | 132 ++ .../src/gpu/intel/xe/xe_pat_tables.h | 238 +++ .../stela-drivers/src/gpu/intel/xe/xe_pci.c | 527 +---- .../src/gpu/intel/xe/xe_pci_device_info.h | 492 +++++ .../src/gpu/intel/xe/xe_pci_runtime.h | 65 + .../src/gpu/intel/xe/xe_pci_types.h | 6 + .../src/gpu/intel/xe/xe_pt_types.h | 9 +- .../src/gpu/intel/xe/xe_scalar_types.h | 26 + .../stela-drivers/src/gpu/intel/xe/xe_uc_fw.c | 438 +---- .../src/gpu/intel/xe/xe_uc_fw_catalog.h | 145 ++ .../src/gpu/intel/xe/xe_uc_fw_cpd.h | 144 ++ .../src/gpu/intel/xe/xe_uc_fw_css.h | 132 ++ .../src/gpu/intel/xe/xe_uc_fw_types.h | 4 + .../src/gpu/intel/xe/xe_uc_fw_version.h | 12 + .../stela-drivers/src/gpu/intel/xe/xe_wopcm.c | 265 +-- .../src/gpu/intel/xe/xe_wopcm_core.h | 230 +++ .../src/gpu/intel/xe/xe_wopcm_size.h | 24 + .../src/gpu/intel/xe/xe_wopcm_types.h | 4 + crates/stela-drivers/src/gpu/macos/Makefile | 23 +- .../src/gpu/macos/task_memory.cpp | 65 + .../stela-drivers/src/gpu/macos/task_memory.h | 56 + .../gpu/macos/tests/task_memory_contract.cpp | 233 +++ .../src/gpu/metal/compiler/library_assembly.c | 503 +++++ .../src/gpu/metal/compiler/library_assembly.h | 79 + .../metal/compiler/tests/library_assembly.c | 486 +++++ .../gpu/metal/compiler/tests/threadgroup.c | 72 + .../metal/compiler/tests/threadgroup_nir.c | 123 ++ .../src/gpu/metal/compiler/threadgroup.c | 71 + .../src/gpu/metal/compiler/threadgroup.h | 65 + .../src/gpu/metal/input/Cargo.toml | 15 + .../stela-drivers/src/gpu/metal/input/input.h | 101 + .../stela-drivers/src/gpu/metal/input/lib.rs | 530 +++++ .../src/gpu/metal/input/tests.rs | 427 ++++ .../src/gpu/metal/input/tests/abi.c | 47 + .../src/gpu/metal/input/tests/inspect.c | 76 + crates/stela-drivers/src/gpu/metal/library.rs | 20 + .../src/gpu/metal/macos/Makefile | 28 + .../src/gpu/metal/macos/library.m | 463 +++++ .../src/gpu/metal/macos/library_internal.h | 53 + .../src/gpu/metal/macos/library_manifest.h | 53 + crates/stela-drivers/src/gpu/nvidia.rs | 3 + .../stela-drivers/src/gpu/nvidia/firmware.rs | 178 ++ .../src/gpu/nvidia/firmware/tests.rs | 359 ++++ crates/stela-drivers/src/gpu/nvidia/mmio.rs | 422 ++++ .../src/gpu/nvidia/page_geometry.rs | 132 ++ .../src/gpu/nvidia/page_geometry/tests.rs | 137 ++ .../stela-drivers/src/gpu/nvidia/services.rs | 36 +- .../src/gpu/nvidia/services/tests.rs | 64 + .../gpu/nvidia/src/nvidia-modeset/Makefile | 4 + .../src/nvidia-modeset/include/nvkms-types.h | 32 +- .../src/gpu/nvidia/src/nvidia/Makefile | 13 +- .../src/gpu/nvidia/stela/firmware.h | 27 + .../src/gpu/nvidia/stela/hosted/air_compile.c | 336 ++++ .../src/gpu/nvidia/stela/hosted/air_compile.h | 140 ++ .../stela-drivers/src/gpu/nvidia/stela/mmio.h | 36 + .../src/gpu/nvidia/stela/page_geometry.h | 18 + .../src/gpu/nvidia/stela/services.h | 4 +- .../src/gpu/nvidia/stela/stela_firmware.c | 53 + .../src/gpu/nvidia/stela/stela_mmio.c | 15 + .../src/gpu/nvidia/stela/stela_nvkms_memory.c | 53 + .../gpu/nvidia/stela/stela_nvkms_primitives.c | 54 + .../gpu/nvidia/stela/stela_nvlink_memory.c | 47 + .../nvidia/stela/stela_nvlink_primitives.c | 44 + .../nvidia/stela/stela_nvswitch_primitives.c | 61 + .../src/gpu/nvidia/stela/stela_ordering.c | 40 + .../gpu/nvidia/stela/stela_page_geometry.c | 29 + .../src/gpu/nvidia/stela/stela_primitives.c | 46 + .../src/gpu/nvidia/stela/stela_primitives.h | 27 + .../src/gpu/nvidia/stela/tests/air_compile.c | 727 +++++++ .../src/gpu/nvidia/stela/tests/lut_access.c | 113 ++ .../src/gpu/nvidia/stela/tests/lut_heap.rs | 41 + .../src/gpu/nvidia/stela/tests/lut_layout.c | 51 + .../src/gpu/nvidia/stela/tests/mmio.rs | 732 +++++++ .../src/gpu/nvidia/stela/tests/nvkms_memory.c | 223 +++ .../gpu/nvidia/stela/tests/nvlink_memory.c | 52 + .../nvidia/stela/tests/nvswitch_primitives.c | 109 ++ .../src/gpu/nvidia/stela/tests/ordering.c | 15 + .../gpu/nvidia/stela/tests/page_geometry.c | 69 + .../gpu/nvidia/stela/tests/record_layout.c | 182 ++ crates/stela-drivers/src/gpu/nvidia/tests.rs | 362 ++++ crates/stela-drivers/src/net/igc.rs | 2 +- crates/stela-drivers/src/net/realtek.rs | 2 +- crates/stela-drivers/src/usb/xhci.rs | 2 +- xtask/src/boot.rs | 3 +- xtask/src/gpu.rs | 8 +- xtask/src/gpu/amd.rs | 50 + xtask/src/gpu/intel.rs | 32 + xtask/src/gpu/macos.rs | 173 +- xtask/src/gpu/macos/library.rs | 137 ++ xtask/src/gpu/mesa.rs | 103 + xtask/src/gpu/mesa/library.rs | 363 ++++ xtask/src/gpu/mesa/threadgroup.rs | 5 + xtask/src/gpu/nvidia.rs | 14 + xtask/src/gpu/nvidia/layout.rs | 158 ++ xtask/src/gpu/nvidia/lut.rs | 238 +++ xtask/src/gpu/nvidia/memory.rs | 86 + xtask/src/gpu/nvidia/ordering.rs | 129 ++ xtask/src/gpu/nvidia/page_geometry.rs | 119 ++ xtask/src/gpu/nvidia/primitives.rs | 104 + 277 files changed, 37047 insertions(+), 4181 deletions(-) create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_limits.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_types.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_mm_access_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_pci_match_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h create mode 100644 crates/stela-drivers/src/gpu/amd/discovery.rs create mode 100644 crates/stela-drivers/src/gpu/amd/include/amd_chip_flags.h create mode 100644 crates/stela-drivers/src/gpu/amd/native_mmio.rs create mode 100644 crates/stela-drivers/src/gpu/amd/pci.rs create mode 100644 crates/stela-drivers/src/gpu/amd/stela/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/air_compile.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_binary.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_binary.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_file.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_file.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_ip.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_ip.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/native_bar.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/native_bar.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/pci_match.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/pci_match.h create mode 100644 crates/stela-drivers/src/gpu/amd/stela/vram_mm.c create mode 100644 crates/stela-drivers/src/gpu/amd/stela/vram_mm.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_binary_test.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_file.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_file.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_file_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_ip.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_ip.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_ip_fixture.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_ip_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_refresh_test.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_tmr.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_fixture.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_test_io.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_virt_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/native_bar_test.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/native_mmio.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/pci.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/pci_match.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/pci_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/vram.rs create mode 100644 crates/stela-drivers/src/gpu/amd/tests/vram_mm.c create mode 100644 crates/stela-drivers/src/gpu/amd/tests/vram_mm_reference.h create mode 100644 crates/stela-drivers/src/gpu/amd/tests/vram_mm_test_io.h create mode 100644 crates/stela-drivers/src/gpu/amd/vram.rs create mode 100644 crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.c create mode 100644 crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.h create mode 100644 crates/stela-drivers/src/gpu/intel/activation.rs create mode 100644 crates/stela-drivers/src/gpu/intel/firmware.rs create mode 100644 crates/stela-drivers/src/gpu/intel/ggtt.rs create mode 100644 crates/stela-drivers/src/gpu/intel/guc_reset.rs create mode 100644 crates/stela-drivers/src/gpu/intel/pat.rs create mode 100644 crates/stela-drivers/src/gpu/intel/stela/activation.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/activation.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/firmware.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/firmware.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/guc_reset.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/guc_reset.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/hosted/air_validate_elk.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/pat.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/pat.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/activation.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/activation.rs create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/firmware.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/firmware.rs create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_bind.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_linux.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_model.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/pat.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.mk create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_abi.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_algorithm.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_bind.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.rs create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.h create mode 100644 crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_owned.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/wopcm.c create mode 100644 crates/stela-drivers/src/gpu/intel/stela/wopcm.h create mode 100644 crates/stela-drivers/src/gpu/intel/wopcm.rs create mode 100644 crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_type.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_cache_level.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_engine_ids.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_core.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_domain_types.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_gt.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_ggtt_probe_core.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_gt_type.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_guc_reset_core.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_huc_role.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_mmio_poll.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_mmio_verify.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_pat_program.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_pat_select.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_pat_tables.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_pci_device_info.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_pci_runtime.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_scalar_types.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_catalog.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_cpd.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_css.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_version.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_core.h create mode 100644 crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_size.h create mode 100644 crates/stela-drivers/src/gpu/macos/task_memory.cpp create mode 100644 crates/stela-drivers/src/gpu/macos/task_memory.h create mode 100644 crates/stela-drivers/src/gpu/macos/tests/task_memory_contract.cpp create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/library_assembly.c create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/library_assembly.h create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/tests/library_assembly.c create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup.c create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup_nir.c create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/threadgroup.c create mode 100644 crates/stela-drivers/src/gpu/metal/compiler/threadgroup.h create mode 100644 crates/stela-drivers/src/gpu/metal/input/Cargo.toml create mode 100644 crates/stela-drivers/src/gpu/metal/input/input.h create mode 100644 crates/stela-drivers/src/gpu/metal/input/lib.rs create mode 100644 crates/stela-drivers/src/gpu/metal/input/tests.rs create mode 100644 crates/stela-drivers/src/gpu/metal/input/tests/abi.c create mode 100644 crates/stela-drivers/src/gpu/metal/input/tests/inspect.c create mode 100644 crates/stela-drivers/src/gpu/metal/macos/Makefile create mode 100644 crates/stela-drivers/src/gpu/metal/macos/library.m create mode 100644 crates/stela-drivers/src/gpu/metal/macos/library_internal.h create mode 100644 crates/stela-drivers/src/gpu/metal/macos/library_manifest.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/firmware.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/firmware/tests.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/mmio.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/page_geometry.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/page_geometry/tests.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/firmware.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/mmio.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/page_geometry.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_firmware.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_mmio.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_memory.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_primitives.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_memory.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_primitives.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_nvswitch_primitives.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_ordering.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_page_geometry.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.h create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/air_compile.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_access.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_heap.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_layout.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/mmio.rs create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/nvkms_memory.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/nvlink_memory.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/nvswitch_primitives.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/ordering.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/page_geometry.c create mode 100644 crates/stela-drivers/src/gpu/nvidia/stela/tests/record_layout.c create mode 100644 xtask/src/gpu/amd.rs create mode 100644 xtask/src/gpu/intel.rs create mode 100644 xtask/src/gpu/macos/library.rs create mode 100644 xtask/src/gpu/mesa/library.rs create mode 100644 xtask/src/gpu/nvidia/layout.rs create mode 100644 xtask/src/gpu/nvidia/lut.rs create mode 100644 xtask/src/gpu/nvidia/memory.rs create mode 100644 xtask/src/gpu/nvidia/ordering.rs create mode 100644 xtask/src/gpu/nvidia/page_geometry.rs create mode 100644 xtask/src/gpu/nvidia/primitives.rs diff --git a/Cargo.lock b/Cargo.lock index fe41377a93..bff03c989a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1622,6 +1622,13 @@ dependencies = [ "walkdir", ] +[[package]] +name = "stela-metal-input" +version = "0.1.0" +dependencies = [ + "sha2", +] + [[package]] name = "stela-runtime" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 6d41362626..259c8a1980 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "crates/stela-loader", "crates/stela-compiler", "crates/stela-drivers", + "crates/stela-drivers/src/gpu/metal/input", "crates/stela-runtime", "xtask", ] diff --git a/crates/stela-drivers/Cargo.toml b/crates/stela-drivers/Cargo.toml index 29ddcd7fb9..81607716bd 100644 --- a/crates/stela-drivers/Cargo.toml +++ b/crates/stela-drivers/Cargo.toml @@ -6,11 +6,6 @@ edition.workspace = true # GPL/ISC notices and the Intel shared initialization also retains BSD terms. license = "MIT AND BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND BSD-3-Clause-Clear AND ISC" -[dependencies] -sha2 = { version = "0.10", default-features = false } -# Fallible native mapping metadata; the maintained owner supports alloc-only UEFI. -triomphe = { version = "=0.1.16", default-features = false } - [lints] workspace = true @@ -23,13 +18,32 @@ ram-disk = [] nvidia-port = ["dep:cc"] # Native Xe command/page-table support; not an initialized Intel GPU driver. intel-port = ["dep:cc"] -# Native CPU page-entry updates; requires the real GPU mapping/GMC owner. +# Native AMD page-entry and BAR support; requires real mapping/GMC owners. amd-port = ["dep:cc"] # Hosted AMD encoder build; its C runtime is not yet ported to UEFI. amd-commands = [] # Shared Metal library input validation, independent of a physical GPU backend. metal = [] +[dependencies] +sha2 = { version = "0.10", default-features = false } +# Fallible native mapping metadata; the maintained owner supports alloc-only UEFI. +triomphe = { version = "=0.1.16", default-features = false } [build-dependencies] cc = { version = "1", optional = true } + +[[test]] +name = "nvidia_mmio" +path = "src/gpu/nvidia/stela/tests/mmio.rs" +required-features = ["nvidia-port"] + +[[test]] +name = "amd_native_mmio" +path = "src/gpu/amd/tests/native_mmio.rs" +required-features = ["amd-port"] + +[[test]] +name = "intel_activation" +path = "src/gpu/intel/stela/tests/activation.rs" +required-features = ["intel-port"] diff --git a/crates/stela-drivers/build.rs b/crates/stela-drivers/build.rs index 00f405de97..1c54472934 100644 --- a/crates/stela-drivers/build.rs +++ b/crates/stela-drivers/build.rs @@ -20,7 +20,31 @@ fn main() { #[cfg(feature = "amd-port")] { let mut build = native::configure(); - build.file("src/gpu/amd/stela/vm_cpu.c").std("c11"); + build + .file("src/gpu/amd/stela/vm_cpu.c") + .file("src/gpu/amd/stela/native_bar.c") + .file("src/gpu/amd/stela/discovery_binary.c") + .file("src/gpu/amd/stela/discovery_file.c") + .file("src/gpu/amd/stela/discovery_tmr.c") + .file("src/gpu/amd/stela/vram_mm.c") + .include("src/gpu/common/linux/include") + .std("c11"); + // Preserve the original IP walk's signed counter semantics locally. + native::configure() + .file("src/gpu/amd/stela/discovery_ip.c") + .include("src/gpu/common/linux/include") + .flag("-fwrapv") + .std("c11") + .compile("stela-amd-ip"); + // Only the original PCI table's shorthand initializers and ARRAY_SIZE + // comparison need these warning exceptions; other native TUs keep them. + native::configure() + .file("src/gpu/amd/stela/pci_match.c") + .include("src/gpu/common/linux/include") + .flag("-Wno-missing-field-initializers") + .flag("-Wno-sign-compare") + .std("c11") + .compile("stela-amd-pci"); // Build the pure C ABI/original-value test helper separately. Only the // cfg(test) Rust link attribute selects it; production links the port. let mut model = native::configure(); @@ -29,11 +53,44 @@ fn main() { .std("c11") .cargo_metadata(false) .compile("stela-amd-vm-test"); + // The donor model uses hosted assertions/stdio; production policy is + // freestanding and builds above for both the host and UEFI targets. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("uefi") { + let mut bars = native::configure(); + bars.file("src/gpu/amd/tests/native_bar_test.c") + .include("src/gpu/common/linux/include") + .define("STELA_AMD_BAR_TEST_LIBRARY", None) + .flag("-Wno-unused-function") + .std("c11") + .cargo_metadata(false) + .compile("stela-amd-bar-test"); + } for path in [ "src/gpu/amd/stela", "src/gpu/amd/amdgpu/amdgpu_vm_cpu_entries.h", "src/gpu/amd/amdgpu/amdgpu_gmc_pte.h", + "src/gpu/amd/amdgpu/amdgpu_mm_access_core.h", + "src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h", + "src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h", + "src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h", + "src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h", + "src/gpu/amd/amdgpu/amdgpu_ip_types.h", + "src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h", + "src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h", + "src/gpu/amd/amdgpu/amdgpu_pci_match_core.h", + "src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h", + "src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h", + "src/gpu/amd/include/amd_chip_flags.h", + "src/gpu/amd/include/asic_reg/bif/bif_4_1_d.h", "src/gpu/amd/tests/vm_ram_test.c", + "src/gpu/amd/tests/native_bar_test.c", + "src/gpu/common/linux/include/drm/amd_asic_type.h", + "src/gpu/amd/include/discovery.h", + "src/gpu/amd/include/soc15_hw_ip.h", + "src/gpu/amd/amdgpu/amdgpu_ip_limits.h", + "src/gpu/common/linux/include/uapi/linux/stddef.h", + "src/gpu/common/linux/include/linux/device-id/pci.h", + "src/gpu/common/linux/include/linux/pci_ids.h", ] { println!("cargo:rerun-if-changed={path}"); } @@ -54,6 +111,26 @@ fn main() { #[cfg(feature = "nvidia-port")] fn nvidia() { let source = "src/gpu/nvidia"; + let version_mk = format!("{source}/version.mk"); + let version = std::fs::read_to_string(&version_mk).expect("read NVIDIA version.mk"); + let version = version + .lines() + .find_map(|line| line.strip_prefix("NVIDIA_VERSION = ")) + .expect("NVIDIA_VERSION in retained version.mk"); + assert!( + version + .bytes() + .all(|byte| byte.is_ascii_digit() || byte == b'.') + ); + let generated = + std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("nvidia-include"); + std::fs::create_dir_all(&generated).expect("create NVIDIA generated include"); + std::fs::write( + generated.join("version.h"), + format!("#define NVIDIA_VERSION \"{version}\"\n"), + ) + .expect("generate NVIDIA version.h"); + println!("cargo:rerun-if-changed={version_mk}"); let mut build = native::configure(); build .define("NV_STELA", None) @@ -61,15 +138,46 @@ fn nvidia() { .file(format!("{source}/stela/memory.c")) .file(format!("{source}/stela/stela_ram_mapping.c")) .file(format!("{source}/stela/stela_pages.c")) + .file(format!("{source}/stela/stela_page_geometry.c")) + .file(format!("{source}/stela/stela_ordering.c")) + .file(format!("{source}/stela/stela_mmio.c")) + .file(format!("{source}/stela/stela_firmware.c")) + .file(format!("{source}/stela/stela_primitives.c")) + .file(format!("{source}/stela/stela_nvlink_primitives.c")) + .file(format!("{source}/stela/stela_nvswitch_primitives.c")) + .file(format!("{source}/stela/stela_nvlink_memory.c")) + .file(format!("{source}/stela/stela_nvkms_primitives.c")) + .file(format!("{source}/stela/stela_nvkms_memory.c")) + .include(&generated) .include(format!("{source}/stela")) .include(format!("{source}/src/common/sdk/nvidia/inc")) .include(format!("{source}/src/nvidia/arch/nvalloc/unix/include")) .include(format!("{source}/src/nvidia/arch/nvalloc/common/inc")) - .include(format!("{source}/src/nvidia/inc/kernel")); + .include(format!("{source}/src/nvidia/inc/kernel")) + .include(format!("{source}/src/common/inc")) + .include(format!("{source}/src/common/inc/swref")) + .include(format!("{source}/src/common/uproc/os/common/include")) + .include(format!("{source}/src/common/nvlink/interface")) + .include(format!("{source}/src/common/unix/common/inc")) + .include(format!("{source}/src/nvidia-modeset/os-interface/include")) + .include(format!("{source}/src/nvidia-modeset/kapi/interface")) + .include(format!("{source}/src/nvidia-modeset/interface")); println!("cargo:rerun-if-changed={source}/stela"); println!("cargo:rerun-if-changed={source}/src/common/sdk/nvidia/inc"); println!("cargo:rerun-if-changed={source}/src/nvidia/arch/nvalloc/unix/include"); println!("cargo:rerun-if-changed={source}/src/nvidia/arch/nvalloc/common/inc"); println!("cargo:rerun-if-changed={source}/src/nvidia/inc/kernel/os"); + println!("cargo:rerun-if-changed={source}/src/common/inc/nvctassert.h"); + println!("cargo:rerun-if-changed={source}/src/common/inc/swref/published/nv_arch.h"); + println!("cargo:rerun-if-changed={source}/src/common/uproc/os/common/include/libelf.h"); + for directory in [ + "src/common/nvlink/interface", + "src/common/unix/common/inc", + "src/nvidia-modeset/os-interface/include", + "src/nvidia-modeset/kapi/interface", + "src/nvidia-modeset/interface", + ] { + println!("cargo:rerun-if-changed={source}/{directory}"); + } build.compile("stela-nvidia-port"); } diff --git a/crates/stela-drivers/build/intel.rs b/crates/stela-drivers/build/intel.rs index b6bc44a686..10a7e424d6 100644 --- a/crates/stela-drivers/build/intel.rs +++ b/crates/stela-drivers/build/intel.rs @@ -8,10 +8,17 @@ pub fn configure(build: &mut cc::Build) { build .define("STELA_NATIVE", None) .include(format!("{source}/xe")) + .include("src/gpu/common/linux/include") .file(format!("{source}/xe/xe_pt_walk.c")) .file(format!("{source}/stela/pt_walk.c")) .file(format!("{source}/stela/commands.c")) .file(format!("{source}/stela/ct.c")) + .file(format!("{source}/stela/activation.c")) + .file(format!("{source}/stela/guc_reset.c")) + .file(format!("{source}/stela/firmware.c")) + .file(format!("{source}/stela/wopcm.c")) + .file(format!("{source}/stela/ggtt_probe.c")) + .file(format!("{source}/stela/pat.c")) .file(format!("{source}/stela/i915_commands.c")); for path in [ "stela", @@ -21,17 +28,166 @@ pub fn configure(build: &mut cc::Build) { "xe/xe_guc_ct_message.h", "xe/abi", "xe/regs/xe_guc_ct_regs.h", + "xe/xe_pci_device_info.h", + "xe/xe_pci_runtime.h", + "xe/xe_pci_types.h", + "xe/xe_platform_types.h", + "xe/xe_engine_ids.h", + "xe/xe_scalar_types.h", + "xe/xe_gt_type.h", + "xe/xe_cache_level.h", + "xe/xe_pat.h", + "xe/xe_pat_tables.h", + "xe/xe_pat_select.h", + "xe/xe_pat_program.h", + "xe/xe_uc_fw_catalog.h", + "xe/xe_uc_fw_css.h", + "xe/xe_uc_fw_cpd.h", + "xe/xe_uc_fw_types.h", + "xe/xe_uc_fw_version.h", + "xe/xe_wopcm_core.h", + "xe/xe_wopcm_size.h", + "xe/xe_ggtt_probe_core.h", + "xe/regs/xe_gtt_defs.h", + "xe/xe_wopcm_types.h", + "xe/xe_mmio_verify.h", + "xe/xe_huc_role.h", + "xe/regs/xe_guc_regs.h", + "xe/xe_force_wake_core.h", + "xe/xe_force_wake_gt.h", + "xe/xe_force_wake_domain_types.h", + "xe/xe_mmio_poll.h", + "xe/xe_guc_reset_core.h", + "xe/xe_gen_wa_oob.c", + "xe/xe_wa_oob.rules", + "xe/regs/xe_gt_regs.h", + "xe/regs/xe_regs.h", + "xe/regs/xe_reg_defs.h", + "xe/regs/xe_reg_type.h", "i915/gt/intel_gpu_commands.h", "i915/gt/intel_batch_emit.h", ] { println!("cargo:rerun-if-changed={source}/{path}"); } + println!("cargo:rerun-if-changed=src/gpu/common/linux/include/drm/intel/pciids.h"); + println!("cargo:rerun-if-changed=src/gpu/common/linux/include/vdso/align.h"); + println!("cargo:rerun-if-changed=src/gpu/common/linux/include/vdso/const.h"); println!("cargo:rerun-if-env-changed=STELA_GPU_PYTHON"); let output = PathBuf::from(env::var_os("OUT_DIR").expect("Cargo supplies OUT_DIR")); let python = PathBuf::from(env::var_os("STELA_GPU_PYTHON").unwrap_or_else(|| "python3".into())); + configure_ggtt(build, &output); + configure_pat(build, &output); + configure_guc_reset(build, &output); configure_dispatch(build, &output, &python); } +/// Use the unchanged original host generator and its complete rule input. +/// The native reset TU verifies that this actual WA excludes its admitted GTs. +fn configure_guc_reset(build: &mut cc::Build, output: &std::path::Path) { + use std::{env, fs, process::Command}; + let source = "src/gpu/intel/xe"; + let output = output.join("intel-guc-reset"); + fs::create_dir_all(&output).expect("create GuC reset generation directory"); + let host = env::var("HOST").expect("Cargo supplies host triple"); + let generator = output.join(if host.contains("windows") { + "xe_gen_wa_oob.exe" + } else { + "xe_gen_wa_oob" + }); + let compiler = cc::Build::new() + .host(&host) + .target(&host) + .cargo_metadata(false) + .get_compiler(); + let result = compiler + .to_command() + .args(["-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror"]) + .arg(format!("{source}/xe_gen_wa_oob.c")) + .arg("-o") + .arg(&generator) + .output() + .expect("compile original GuC WA generator"); + assert!( + result.status.success(), + "original GuC WA generator compilation failed: {}", + String::from_utf8_lossy(&result.stderr) + ); + let generated = output.join("xe_wa_oob.c"); + let result = Command::new(&generator) + .arg(format!("{source}/xe_wa_oob.rules")) + .arg(&generated) + .arg(output.join("xe_wa_oob.h")) + .output() + .expect("run original GuC WA generator"); + assert!( + result.status.success(), + "original GuC WA generation failed: {}", + String::from_utf8_lossy(&result.stderr) + ); + let contents = fs::read_to_string(generated).expect("read original GuC WA output"); + let start = "{ XE_RTP_NAME(\"14025883347\"),"; + assert_eq!( + contents.matches(start).count(), + 1, + "changed original GuC reset WA entry" + ); + let (_, entry) = contents.split_once(start).expect("original reset WA entry"); + let (entry, _) = entry + .split_once(") },") + .expect("original reset WA terminator"); + fs::write( + output.join("guc_reset_wa.inc"), + format!("{start}{entry}) }},\n"), + ) + .expect("write original reset WA entry"); + build.include(output); +} + +/// Retain the original compile-time checks without importing Linux services. +/// Address selection still uses the actual drm/intel/pick.h implementation. +fn configure_pat(build: &mut cc::Build, output: &std::path::Path) { + use std::fs; + let compiler = "src/gpu/common/linux/include/linux/compiler.h"; + let bug = "src/gpu/common/linux/include/linux/build_bug.h"; + let source = fs::read_to_string(compiler).expect("read original compile-time definitions"); + let mut header = format!( + "{}\n", + source.lines().next().expect("original compiler license") + ); + for (path, name, required) in [ + (compiler, "__BUILD_BUG_ON_ZERO_MSG", "_Static_assert"), + (compiler, "__is_constexpr", ""), + (bug, "BUILD_BUG_ON_ZERO", ""), + ] { + println!("cargo:rerun-if-changed={path}"); + let source = fs::read_to_string(path).expect("read original compile-time macro"); + let lines: Vec<_> = source.lines().collect(); + let prefix = format!("#define {name}("); + let matches: Vec<_> = lines + .iter() + .enumerate() + .filter(|(_, line)| line.starts_with(&prefix) && line.contains(required)) + .collect(); + assert_eq!(matches.len(), 1, "changed original PAT macro {name}"); + let mut index = matches[0].0; + loop { + let line = lines.get(index).expect("unterminated original PAT macro"); + header.push_str(line); + header.push('\n'); + if !line.trim_end().ends_with('\\') { + break; + } + index += 1; + } + } + println!("cargo:rerun-if-changed=src/gpu/common/linux/include/drm/intel/pick.h"); + let output = output.join("intel-pat"); + fs::create_dir_all(&output).expect("create PAT compile-time output directory"); + fs::write(output.join("pat_compile_defs.h"), header) + .expect("write original PAT compile-time macros"); + build.include(output); +} + fn configure_dispatch(build: &mut cc::Build, output: &std::path::Path, python: &std::path::Path) { use std::{fs, process::Command}; @@ -82,3 +238,49 @@ fn configure_dispatch(build: &mut cc::Build, output: &std::path::Path, python: & println!("cargo:rerun-if-changed={genxml}"); println!("cargo:rerun-if-changed=src/gpu/common/mesa/src/util/bitpack_uint.h"); } + +/// Copy only the nine original scalar definitions needed by the native probe. +/// The full headers require Linux services; no hardware values are mirrored. +fn configure_ggtt(build: &mut cc::Build, output: &std::path::Path) { + use std::fs; + let original = "src/gpu/common/linux/include/drm/intel/i915_drm.h"; + let drm = fs::read_to_string(original).expect("read original Intel GMCH definitions"); + let mut header = drm + .split_once("#ifndef _I915_DRM_H_") + .expect("original Intel header guard") + .0 + .to_owned(); + for (path, names) in [ + ( + original, + ["SNB_GMCH_CTRL", "BDW_GMCH_GGMS_SHIFT", "BDW_GMCH_GGMS_MASK"], + ), + ( + "src/gpu/intel/xe/xe_bo.h", + ["XE_PTE_SHIFT", "XE_PAGE_SIZE", "XE_PTE_MASK"], + ), + ( + "src/gpu/common/linux/include/linux/sizes.h", + ["SZ_1M", "SZ_8M", "SZ_2M"], + ), + ] { + println!("cargo:rerun-if-changed={path}"); + let source = fs::read_to_string(path).expect("read original GGTT scalar header"); + for name in names { + let mut lines = source.lines().filter(|line| { + let mut words = line.split_whitespace(); + words.next() == Some("#define") && words.next() == Some(name) + }); + header.push_str(lines.next().expect("missing original GGTT scalar define")); + header.push('\n'); + assert!( + lines.next().is_none(), + "duplicate original GGTT define {name}" + ); + } + } + let output = output.join("intel-ggtt"); + fs::create_dir_all(&output).expect("create GGTT scalar output directory"); + fs::write(output.join("ggtt_probe_defs.h"), header).expect("write original GGTT scalar header"); + build.include(output); +} diff --git a/crates/stela-drivers/src/gpu/amd.rs b/crates/stela-drivers/src/gpu/amd.rs index c27794d700..ee67121e3c 100644 --- a/crates/stela-drivers/src/gpu/amd.rs +++ b/crates/stela-drivers/src/gpu/amd.rs @@ -5,5 +5,13 @@ mod commands; #[cfg(feature = "amd-commands")] pub use commands::*; +#[cfg(feature = "amd-port")] +pub mod discovery; +#[cfg(feature = "amd-port")] +pub mod native_mmio; +#[cfg(feature = "amd-port")] +pub mod pci; #[cfg(feature = "amd-port")] pub mod vm; +#[cfg(feature = "amd-port")] +pub mod vram; diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/Makefile b/crates/stela-drivers/src/gpu/amd/amdgpu/Makefile index ba80542ead..d5ea56efbf 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/Makefile +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/Makefile @@ -49,6 +49,8 @@ subdir-ccflags-y += -Wno-override-init subdir-ccflags-$(CONFIG_DRM_AMDGPU_WERROR) += -Werror amdgpu-y := amdgpu_drv.o +# Pure discovery validation shared with the native attachment path. +amdgpu-y += ../stela/discovery_binary.o # add KMS driver amdgpu-y += amdgpu_device.o amdgpu_reg_access.o amdgpu_doorbell_mgr.o amdgpu_kms.o \ diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h new file mode 100644 index 0000000000..c068d02ad8 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_apu_flags_core.h @@ -0,0 +1,70 @@ +/* + * Copyright 2008 Advanced Micro Devices, Inc. + * Copyright 2008 Red Hat Inc. + * Copyright 2009 Jerome Glisse. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Dave Airlie + * Alex Deucher + * Jerome Glisse + */ + +#ifndef AMDGPU_APU_FLAGS_CORE_H +#define AMDGPU_APU_FLAGS_CORE_H +#include "../../common/linux/include/drm/amd_asic_type.h" +#include "../include/amd_chip_flags.h" +static inline unsigned long amdgpu_initial_apu_flags(unsigned long flags, + enum amd_asic_type asic_type, unsigned short device, unsigned long apu_flags) +{ + if (!(flags & AMD_IS_APU) || + asic_type < CHIP_RAVEN) + return apu_flags; + + switch (asic_type) { + case CHIP_RAVEN: + if (device == 0x15dd) + apu_flags |= AMD_APU_IS_RAVEN; + if (device == 0x15d8) + apu_flags |= AMD_APU_IS_PICASSO; + break; + case CHIP_RENOIR: + if ((device == 0x1636) || + (device == 0x164c)) + apu_flags |= AMD_APU_IS_RENOIR; + else + apu_flags |= AMD_APU_IS_GREEN_SARDINE; + break; + case CHIP_VANGOGH: + apu_flags |= AMD_APU_IS_VANGOGH; + break; + case CHIP_YELLOW_CARP: + break; + case CHIP_CYAN_SKILLFISH: + if ((device == 0x13FE) || + (device == 0x143F)) + apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2; + break; + default: + break; + } + + return apu_flags; +} +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_device.c b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_device.c index e84b75c03c..49ddc7ece7 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_device.c +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_device.c @@ -48,6 +48,9 @@ #include #include #include "amdgpu.h" +#include "amdgpu_apu_flags_core.h" +#include "amdgpu_discovery_source_core.h" +#include "../stela/native_bar.h" #include "amdgpu_trace.h" #include "amdgpu_i2c.h" #include "atom.h" @@ -696,6 +699,22 @@ bool amdgpu_device_supports_smart_shift(struct amdgpu_device *adev) * VRAM access helper functions */ +#include "amdgpu_mm_access_core.h" + +static uint32_t amdgpu_mm_access_read32(void *context, uint32_t reg) +{ + struct amdgpu_device *adev = context; + + return RREG32_NO_KIQ(reg); +} + +static void amdgpu_mm_access_write32(void *context, uint32_t reg, uint32_t value) +{ + struct amdgpu_device *adev = context; + + WREG32_NO_KIQ(reg, value); +} + /** * amdgpu_device_mm_access - access vram by MM_INDEX/MM_DATA * @@ -708,10 +727,10 @@ bool amdgpu_device_supports_smart_shift(struct amdgpu_device *adev) void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos, void *buf, size_t size, bool write) { + static const struct amdgpu_mm_access_ops ops = { + amdgpu_mm_access_read32, amdgpu_mm_access_write32, + }; unsigned long flags; - uint32_t hi = ~0, tmp = 0; - uint32_t *data = buf; - uint64_t last; int idx; if (!drm_dev_enter(adev_to_drm(adev), &idx)) @@ -725,19 +744,7 @@ void amdgpu_device_mm_access(struct amdgpu_device *adev, loff_t pos, } spin_lock_irqsave(&adev->mmio_idx_lock, flags); - for (last = pos + size; pos < last; pos += 4) { - tmp = pos >> 31; - - WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000); - if (tmp != hi) { - WREG32_NO_KIQ(mmMM_INDEX_HI, tmp); - hi = tmp; - } - if (write) - WREG32_NO_KIQ(mmMM_DATA, *data++); - else - *data++ = RREG32_NO_KIQ(mmMM_DATA); - } + amdgpu_mm_access_core(&ops, adev, pos, buf, size, write); spin_unlock_irqrestore(&adev->mmio_idx_lock, flags); drm_dev_exit(idx); @@ -1559,38 +1566,8 @@ def_value: static int amdgpu_device_init_apu_flags(struct amdgpu_device *adev) { - if (!(adev->flags & AMD_IS_APU) || - adev->asic_type < CHIP_RAVEN) - return 0; - - switch (adev->asic_type) { - case CHIP_RAVEN: - if (adev->pdev->device == 0x15dd) - adev->apu_flags |= AMD_APU_IS_RAVEN; - if (adev->pdev->device == 0x15d8) - adev->apu_flags |= AMD_APU_IS_PICASSO; - break; - case CHIP_RENOIR: - if ((adev->pdev->device == 0x1636) || - (adev->pdev->device == 0x164c)) - adev->apu_flags |= AMD_APU_IS_RENOIR; - else - adev->apu_flags |= AMD_APU_IS_GREEN_SARDINE; - break; - case CHIP_VANGOGH: - adev->apu_flags |= AMD_APU_IS_VANGOGH; - break; - case CHIP_YELLOW_CARP: - break; - case CHIP_CYAN_SKILLFISH: - if ((adev->pdev->device == 0x13FE) || - (adev->pdev->device == 0x143F)) - adev->apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2; - break; - default: - break; - } - + adev->apu_flags = amdgpu_initial_apu_flags(adev->flags, adev->asic_type, + adev->pdev->device, adev->apu_flags); return 0; } @@ -2020,13 +1997,9 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) return r; } - switch (adev->asic_type) { + switch (amdgpu_initial_ip_path(adev->asic_type)) { #ifdef CONFIG_DRM_AMDGPU_SI - case CHIP_VERDE: - case CHIP_TAHITI: - case CHIP_PITCAIRN: - case CHIP_OLAND: - case CHIP_HAINAN: + case AMDGPU_INITIAL_IP_SI: adev->family = AMDGPU_FAMILY_SI; r = si_set_ip_blocks(adev); if (r) @@ -2034,11 +2007,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) break; #endif #ifdef CONFIG_DRM_AMDGPU_CIK - case CHIP_BONAIRE: - case CHIP_HAWAII: - case CHIP_KAVERI: - case CHIP_KABINI: - case CHIP_MULLINS: + case AMDGPU_INITIAL_IP_CIK: if (adev->flags & AMD_IS_APU) adev->family = AMDGPU_FAMILY_KV; else @@ -2049,15 +2018,7 @@ static int amdgpu_device_ip_early_init(struct amdgpu_device *adev) return r; break; #endif - case CHIP_TOPAZ: - case CHIP_TONGA: - case CHIP_FIJI: - case CHIP_POLARIS10: - case CHIP_POLARIS11: - case CHIP_POLARIS12: - case CHIP_VEGAM: - case CHIP_CARRIZO: - case CHIP_STONEY: + case AMDGPU_INITIAL_IP_VI: if (adev->flags & AMD_IS_APU) adev->family = AMDGPU_FAMILY_CZ; else @@ -3894,13 +3855,9 @@ int amdgpu_device_init(struct amdgpu_device *adev, /* Registers mapping */ /* TODO: block userspace mapping of io register */ - if (adev->asic_type >= CHIP_BONAIRE) { - adev->rmmio_base = pci_resource_start(adev->pdev, 5); - adev->rmmio_size = pci_resource_len(adev->pdev, 5); - } else { - adev->rmmio_base = pci_resource_start(adev->pdev, 2); - adev->rmmio_size = pci_resource_len(adev->pdev, 2); - } + i = amdgpu_native_register_bar(adev->asic_type); + adev->rmmio_base = pci_resource_start(adev->pdev, i); + adev->rmmio_size = pci_resource_len(adev->pdev, i); for (i = 0; i < AMD_IP_BLOCK_TYPE_NUM; i++) atomic_set(&adev->pm.pwr_state[i], POWER_STATE_UNKNOWN); diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.c b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.c index 47e0680ed7..bf576e089d 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.c +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.c @@ -24,9 +24,12 @@ #include #include "amdgpu.h" +#include "amdgpu_discovery_source_core.h" +#include "amdgpu_discovery_file_core.h" #include "amdgpu_discovery.h" #include "soc15_hw_ip.h" #include "discovery.h" +#include "../stela/discovery_binary.h" #include "amdgpu_ras.h" #include "soc15.h" @@ -137,16 +140,12 @@ MODULE_FIRMWARE("amdgpu/arcturus_ip_discovery.bin"); MODULE_FIRMWARE("amdgpu/aldebaran_ip_discovery.bin"); /* Note: These registers are consistent across all the SOCs */ +#include "amdgpu_discovery_tmr_core.h" #define mmIP_DISCOVERY_VERSION 0x16A00 -#define mmRCC_CONFIG_MEMSIZE 0xde3 -#define mmMP0_SMN_C2PMSG_33 0x16061 #define mmMM_INDEX 0x0 #define mmMM_INDEX_HI 0x6 #define mmMM_DATA 0x1 -#define mmDRIVER_SCRATCH_0 0x94 -#define mmDRIVER_SCRATCH_1 0x95 -#define mmDRIVER_SCRATCH_2 0x96 static const char *hw_id_names[HW_ID_MAX] = { [MP1_HWID] = "MP1", @@ -230,126 +229,98 @@ static const char *hw_id_names[HW_ID_MAX] = { [AIGC_HWID] = "AIGC", }; -static int hw_id_map[MAX_HWIP] = { - [GC_HWIP] = GC_HWID, - [HDP_HWIP] = HDP_HWID, - [SDMA0_HWIP] = SDMA0_HWID, - [SDMA1_HWIP] = SDMA1_HWID, - [SDMA2_HWIP] = SDMA2_HWID, - [SDMA3_HWIP] = SDMA3_HWID, - [LSDMA_HWIP] = LSDMA_HWID, - [MMHUB_HWIP] = MMHUB_HWID, - [ATHUB_HWIP] = ATHUB_HWID, - [NBIO_HWIP] = NBIF_HWID, - [MP0_HWIP] = MP0_HWID, - [MP1_HWIP] = MP1_HWID, - [UVD_HWIP] = UVD_HWID, - [VCE_HWIP] = VCE_HWID, - [DF_HWIP] = DF_HWID, - [DCE_HWIP] = DMU_HWID, - [OSSSYS_HWIP] = OSSSYS_HWID, - [SMUIO_HWIP] = SMUIO_HWID, - [PWR_HWIP] = PWR_HWID, - [NBIF_HWIP] = NBIF_HWID, - [THM_HWIP] = THM_HWID, - [CLK_HWIP] = CLKA_HWID, - [UMC_HWIP] = UMC_HWID, - [XGMI_HWIP] = XGMI_HWID, - [DCI_HWIP] = DCI_HWID, - [PCIE_HWIP] = PCIE_HWID, - [VPE_HWIP] = VPE_HWID, - [ISP_HWIP] = ISP_HWID, - [ATU_HWIP] = ATU_HWID, -}; +#include "amdgpu_discovery_ip_core.h" -static int amdgpu_discovery_get_tmr_info(struct amdgpu_device *adev, - bool *is_tmr_in_sysmem) +static void amdgpu_discovery_ip_debug(void *context, const char *format, ...) { - u64 vram_size, tmr_offset, tmr_size; - u32 msg, tmr_offset_lo, tmr_offset_hi; - int i, ret; + va_list args; + struct va_format vaf = { .fmt = format, .va = &args }; + (void)context; + va_start(args, format); + DRM_DEBUG("%pV", &vaf); + va_end(args); +} +static void amdgpu_discovery_ip_drm_error(void *context, const char *format, ...) +{ + va_list args; + struct va_format vaf = { .fmt = format, .va = &args }; + (void)context; + va_start(args, format); + DRM_ERROR("%pV", &vaf); + va_end(args); +} +static void amdgpu_discovery_ip_error(void *context, const char *format, ...) +{ + struct amdgpu_device *adev = context; + va_list args; + struct va_format vaf = { .fmt = format, .va = &args }; + va_start(args, format); + dev_err(adev->dev, "%pV", &vaf); + va_end(args); +} +static void amdgpu_discovery_ip_bind(void *context, unsigned hw_ip, unsigned instance, + uint32_t *base, unsigned count) +{ + struct amdgpu_device *adev = context; + (void)count; + adev->reg_offset[hw_ip][instance] = base; +} - if (!amdgpu_sriov_vf(adev)) { - /* It can take up to two second for IFWI init to complete on some dGPUs, - * but generally it should be in the 60-100ms range. Normally this starts - * as soon as the device gets power so by the time the OS loads this has long - * completed. However, when a card is hotplugged via e.g., USB4, we need to - * wait for this to complete. Once the C2PMSG is updated, we can - * continue. - */ - for (i = 0; i < 2000; i++) { - msg = RREG32(mmMP0_SMN_C2PMSG_33); - if (msg & 0x80000000) - break; - msleep(1); - } - } - vram_size = RREG32(mmRCC_CONFIG_MEMSIZE); - if (vram_size == U32_MAX) - return -ENXIO; - else if (!vram_size) - *is_tmr_in_sysmem = true; - else - *is_tmr_in_sysmem = false; - - /* init the default tmr size and offset */ - adev->discovery.size = DISCOVERY_TMR_SIZE; - if (vram_size) - adev->discovery.offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET; - - if (amdgpu_sriov_vf(adev)) { - if (adev->virt.is_dynamic_crit_regn_enabled) { - adev->discovery.offset = - adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset; - adev->discovery.size = - adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10; - if (!adev->discovery.size) - return -EINVAL; - } else { - goto out; - } - } else { - if (adev->discovery.offset) { - u32 signature; - - /* If VRAM holds a valid discovery signature at the default - * discovery offset, use it as-is. - */ - amdgpu_device_vram_access(adev, adev->discovery.offset, - &signature, sizeof(signature), - false); - if (le32_to_cpu(signature) == BINARY_SIGNATURE) - goto out; - } - - tmr_size = RREG32(mmDRIVER_SCRATCH_2); - if (tmr_size) { - /* It's preferred to transition to PSP mailbox reg interface - * for both bare-metal and passthrough if available */ - adev->discovery.size = (u32)tmr_size; - tmr_offset_lo = RREG32(mmDRIVER_SCRATCH_0); - tmr_offset_hi = RREG32(mmDRIVER_SCRATCH_1); - adev->discovery.offset = ((u64)le32_to_cpu(tmr_offset_hi) << 32 | - le32_to_cpu(tmr_offset_lo)); - } else if (!vram_size) { - /* fall back to apci approach to query tmr offset if vram_size is 0 */ - ret = amdgpu_acpi_get_tmr_info(adev, &tmr_offset, &tmr_size); - if (ret) - return ret; - adev->discovery.size = DISCOVERY_TMR_SIZE; - adev->discovery.offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET; - } - } -out: - adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL); - if (!adev->discovery.bin) - return -ENOMEM; - adev->discovery.debugfs_blob.data = adev->discovery.bin; - adev->discovery.debugfs_blob.size = adev->discovery.size; - - return 0; +static uint32_t amdgpu_discovery_tmr_read32(void *context, uint32_t reg) +{ + struct amdgpu_device *adev = context; + return RREG32(reg); +} +static void amdgpu_discovery_tmr_sleep_ms(void *context, unsigned milliseconds) +{ + (void)context; + msleep(milliseconds); +} +static int amdgpu_discovery_tmr_read_vram(void *context, uint64_t offset, + uint32_t *data, size_t size) +{ + amdgpu_device_vram_access(context, offset, data, size, false); + /* The original transport is void; this reports no additional local error, + * not device acknowledgement. All original hardware guards remain in it. */ + return 0; +} +static int amdgpu_discovery_tmr_acpi(void *context, uint64_t *offset, uint64_t *size) +{ + return amdgpu_acpi_get_tmr_info(context, offset, size); +} +static int amdgpu_discovery_get_tmr_info(struct amdgpu_device *adev, + bool *is_tmr_in_sysmem) +{ + const struct amdgpu_discovery_tmr_ops ops = { + amdgpu_discovery_tmr_read32, amdgpu_discovery_tmr_sleep_ms, + amdgpu_discovery_tmr_read_vram, amdgpu_discovery_tmr_acpi, + }; + struct amdgpu_discovery_tmr_state state = { + .offset = adev->discovery.offset, + .size = adev->discovery.size, + .is_sysmem = false, + }; + bool is_vf = amdgpu_sriov_vf(adev); + bool dynamic = is_vf && adev->virt.is_dynamic_crit_regn_enabled; + int ret = amdgpu_discovery_tmr_query_core(&ops, adev, is_vf, dynamic, + dynamic ? adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset : 0, + dynamic ? adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10 : 0, + &state); + /* Preserve the original policy's partial device/output updates on error. */ + adev->discovery.offset = state.offset; + adev->discovery.size = state.size; + if (state.has_memory_size) + *is_tmr_in_sysmem = state.is_sysmem; + if (ret) + return ret; + adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL); + if (!adev->discovery.bin) + return -ENOMEM; + adev->discovery.debugfs_blob.data = adev->discovery.bin; + adev->discovery.debugfs_blob.size = adev->discovery.size; + return 0; } static int amdgpu_discovery_read_binary_from_sysmem(struct amdgpu_device *adev, uint8_t *binary) @@ -409,24 +380,25 @@ static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev, return r; } - if (fw->size > adev->discovery.size) { + switch (amdgpu_discovery_file_validate(fw->data, fw->size, + adev->discovery.size)) { + case AMDGPU_DISCOVERY_FILE_TOO_LARGE: dev_err(adev->dev, "ip discovery firmware \"%s\" too large (%zu > %u)\n", fw_name, fw->size, adev->discovery.size); release_firmware(fw); return -EINVAL; - } - - /* Ensure the firmware is at least large enough to contain the - * binary header fields. - */ - if (fw->size < offsetof(struct binary_header, binary_size) + - sizeof(((struct binary_header *)0)->binary_size)) { + case AMDGPU_DISCOVERY_FILE_TOO_SMALL: dev_err(adev->dev, "ip discovery firmware \"%s\" too small (%zu)\n", fw_name, fw->size); release_firmware(fw); return -EINVAL; + case AMDGPU_DISCOVERY_FILE_INVALID: + release_firmware(fw); + return -EINVAL; + case AMDGPU_DISCOVERY_FILE_OK: + break; } memcpy((u8 *)binary, (u8 *)fw->data, fw->size); @@ -435,17 +407,6 @@ static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev, return 0; } -static uint16_t amdgpu_discovery_calculate_checksum(uint8_t *data, uint32_t size) -{ - uint16_t checksum = 0; - int i; - - for (i = 0; i < size; i++) - checksum += data[i]; - - return checksum; -} - static inline bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev, uint8_t *data, uint32_t size, uint16_t expected) @@ -463,14 +424,6 @@ static inline bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev, return true; } -static inline bool amdgpu_discovery_verify_binary_signature(uint8_t *binary) -{ - struct binary_header *bhdr; - bhdr = (struct binary_header *)binary; - - return (le32_to_cpu(bhdr->binary_signature) == BINARY_SIGNATURE); -} - static void amdgpu_discovery_harvest_config_quirk(struct amdgpu_device *adev) { /* @@ -529,151 +482,32 @@ static const char *amdgpu_discovery_get_fw_name(struct amdgpu_device *adev) if (amdgpu_discovery == 2) { /* Assume there is valid discovery TMR in VRAM even if binary is sideloaded */ adev->discovery.reserve_tmr = true; - return "amdgpu/ip_discovery.bin"; - } - - switch (adev->asic_type) { - case CHIP_VEGA10: - return "amdgpu/vega10_ip_discovery.bin"; - case CHIP_VEGA12: - return "amdgpu/vega12_ip_discovery.bin"; - case CHIP_RAVEN: - if (adev->apu_flags & AMD_APU_IS_RAVEN2) - return "amdgpu/raven2_ip_discovery.bin"; - else if (adev->apu_flags & AMD_APU_IS_PICASSO) - return "amdgpu/picasso_ip_discovery.bin"; - else - return "amdgpu/raven_ip_discovery.bin"; - case CHIP_VEGA20: - return "amdgpu/vega20_ip_discovery.bin"; - case CHIP_ARCTURUS: - return "amdgpu/arcturus_ip_discovery.bin"; - case CHIP_ALDEBARAN: - return "amdgpu/aldebaran_ip_discovery.bin"; - default: - return NULL; } + return amdgpu_discovery_fw_name(adev->asic_type, adev->apu_flags, + amdgpu_discovery); } static int amdgpu_discovery_get_table_info(struct amdgpu_device *adev, struct table_info **info, uint16_t table_id) { - struct binary_header *bhdr = - (struct binary_header *)adev->discovery.bin; - struct binary_header_v2 *bhdrv2; + const struct table_info *entry; - switch (bhdr->version_major) { - case 2: - bhdrv2 = (struct binary_header_v2 *)adev->discovery.bin; - *info = &bhdrv2->table_list[table_id]; - break; - case 1: - case 0: - *info = &bhdr->table_list[table_id]; - break; - default: - dev_err(adev->dev, "Invalid ip discovery table version %d\n",bhdr->version_major); + entry = amdgpu_discovery_binary_table(adev->discovery.bin, + adev->discovery.size, table_id); + if (!entry) return -EINVAL; - } - - return 0; -} - -static int amdgpu_discovery_table_check(struct amdgpu_device *adev, - uint8_t *discovery_bin, - uint16_t table_id) -{ - int r, act_val, exp_val, table_size; - uint16_t offset, checksum; - struct table_info *info; - bool check_table = true; - char *table_name; - - r = amdgpu_discovery_get_table_info(adev, &info, table_id); - if (r) - return r; - offset = le16_to_cpu(info->offset); - checksum = le16_to_cpu(info->checksum); - - switch (table_id) { - case IP_DISCOVERY: { - struct ip_discovery_header *ihdr = - (struct ip_discovery_header *)(discovery_bin + offset); - act_val = le32_to_cpu(ihdr->signature); - exp_val = DISCOVERY_TABLE_SIGNATURE; - table_size = le16_to_cpu(ihdr->size); - table_name = "data table"; - break; - } - case GC: { - struct gpu_info_header *ghdr = - (struct gpu_info_header *)(discovery_bin + offset); - act_val = le32_to_cpu(ghdr->table_id); - exp_val = GC_TABLE_ID; - table_size = le16_to_cpu(ghdr->size); - table_name = "gc table"; - break; - } - case HARVEST_INFO: { - struct harvest_info_header *hhdr = - (struct harvest_info_header *)(discovery_bin + offset); - act_val = le32_to_cpu(hhdr->signature); - exp_val = HARVEST_TABLE_SIGNATURE; - table_size = sizeof(struct harvest_table); - table_name = "harvest table"; - break; - } - case VCN_INFO: { - struct vcn_info_header *vhdr = - (struct vcn_info_header *)(discovery_bin + offset); - act_val = le32_to_cpu(vhdr->table_id); - exp_val = VCN_INFO_TABLE_ID; - table_size = le32_to_cpu(vhdr->size_bytes); - table_name = "vcn table"; - break; - } - case MALL_INFO: { - struct mall_info_header *mhdr = - (struct mall_info_header *)(discovery_bin + offset); - act_val = le32_to_cpu(mhdr->table_id); - exp_val = MALL_INFO_TABLE_ID; - table_size = le32_to_cpu(mhdr->size_bytes); - table_name = "mall table"; - check_table = false; - break; - } - default: - dev_err(adev->dev, "invalid ip discovery table id %d specified\n", table_id); - check_table = false; - break; - } - - if (check_table && offset) { - if (act_val != exp_val) { - dev_err(adev->dev, "invalid ip discovery %s signature\n", table_name); - return -EINVAL; - } - - if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, - table_size, checksum)) { - dev_err(adev->dev, "invalid ip discovery %s checksum\n", table_name); - return -EINVAL; - } - } - + /* The original private allocation remains mutable for register-base + * conversion. The checked directory lookup itself never mutates it. + */ + *info = (struct table_info *)entry; return 0; } static int amdgpu_discovery_init(struct amdgpu_device *adev) { - struct binary_header *bhdr; uint8_t *discovery_bin; const char *fw_name; - uint16_t offset; - uint16_t size; - uint16_t checksum; - uint16_t table_id; bool is_tmr_in_sysmem; int r; @@ -698,34 +532,16 @@ static int amdgpu_discovery_init(struct amdgpu_device *adev) goto out; } - /* check the ip discovery binary signature */ - if (!amdgpu_discovery_verify_binary_signature(discovery_bin)) { - dev_err(adev->dev, - "get invalid ip discovery binary signature\n"); + /* Validate the real private acquisition before any original table/IP + * walk or in-place register-base conversion can consume it. + */ + if (amdgpu_discovery_binary_validate(discovery_bin, adev->discovery.size) != + AMDGPU_DISCOVERY_BINARY_OK) { + dev_err(adev->dev, "invalid or out-of-bounds ip discovery binary\n"); r = -EINVAL; goto out; } - bhdr = (struct binary_header *)discovery_bin; - - offset = offsetof(struct binary_header, binary_checksum) + - sizeof(bhdr->binary_checksum); - size = le16_to_cpu(bhdr->binary_size) - offset; - checksum = le16_to_cpu(bhdr->binary_checksum); - - if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, size, - checksum)) { - dev_err(adev->dev, "invalid ip discovery binary checksum\n"); - r = -EINVAL; - goto out; - } - - for (table_id = 0; table_id <= MALL_INFO; table_id++) { - r = amdgpu_discovery_table_check(adev, discovery_bin, table_id); - if (r) - goto out; - } - return 0; out: @@ -749,27 +565,17 @@ void amdgpu_discovery_fini(struct amdgpu_device *adev) static int amdgpu_discovery_validate_ip(struct amdgpu_device *adev, uint8_t instance, uint16_t hw_id) { - if (instance >= HWIP_MAX_INSTANCE) { - dev_err(adev->dev, - "Unexpected instance_number (%d) from ip discovery blob\n", - instance); - return -EINVAL; - } - if (hw_id >= HW_ID_MAX) { - dev_err(adev->dev, - "Unexpected hw_id (%d) from ip discovery blob\n", - hw_id); - return -EINVAL; - } - - return 0; + const struct amdgpu_discovery_ip_ops ops = { + .context = adev, .error = amdgpu_discovery_ip_error, + }; + return amdgpu_discovery_ip_valid(&ops, instance, hw_id); } static void amdgpu_discovery_read_harvest_bit_per_ip(struct amdgpu_device *adev, uint32_t *vcn_harvest_count) { uint8_t *discovery_bin = adev->discovery.bin; - struct binary_header *bhdr; + struct table_info *info; struct ip_discovery_header *ihdr; struct die_header *dhdr; struct ip *ip; @@ -778,10 +584,11 @@ static void amdgpu_discovery_read_harvest_bit_per_ip(struct amdgpu_device *adev, uint8_t inst; int i, j; - bhdr = (struct binary_header *)discovery_bin; - ihdr = (struct ip_discovery_header - *)(discovery_bin + - le16_to_cpu(bhdr->table_list[IP_DISCOVERY].offset)); + if (amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY)) + return; + ihdr = (struct ip_discovery_header *)(discovery_bin + + le16_to_cpu(info->offset)); + num_dies = le16_to_cpu(ihdr->num_dies); /* scan harvest bit of all IP data structures */ @@ -1497,28 +1304,15 @@ void amdgpu_discovery_dump(struct amdgpu_device *adev, struct drm_printer *p) static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev) { - uint8_t num_base_address, subrev, variant; struct table_info *info; struct ip_discovery_header *ihdr; - struct die_header *dhdr; uint8_t *discovery_bin; - struct ip_v4 *ip; - uint16_t die_offset; - uint16_t ip_offset; - uint16_t num_dies; - uint32_t wafl_ver; - uint16_t num_ips; - uint16_t hw_id; - uint8_t inst; - int hw_ip; - int i, j, k; int r; r = amdgpu_discovery_init(adev); if (r) return r; discovery_bin = adev->discovery.bin; - wafl_ver = 0; adev->gfx.xcc_mask = 0; adev->sdma.sdma_mask = 0; adev->vcn.inst_mask = 0; @@ -1526,175 +1320,23 @@ static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev) r = amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY); if (r) return r; - ihdr = (struct ip_discovery_header - *)(discovery_bin + - le16_to_cpu(info->offset)); - num_dies = le16_to_cpu(ihdr->num_dies); - - DRM_DEBUG("number of dies: %d\n", num_dies); - - for (i = 0; i < num_dies; i++) { - die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); - dhdr = (struct die_header *)(discovery_bin + die_offset); - num_ips = le16_to_cpu(dhdr->num_ips); - ip_offset = die_offset + sizeof(*dhdr); - - if (le16_to_cpu(dhdr->die_id) != i) { - DRM_ERROR("invalid die id %d, expected %d\n", - le16_to_cpu(dhdr->die_id), i); - return -EINVAL; - } - - DRM_DEBUG("number of hardware IPs on die%d: %d\n", - le16_to_cpu(dhdr->die_id), num_ips); - - for (j = 0; j < num_ips; j++) { - ip = (struct ip_v4 *)(discovery_bin + ip_offset); - - inst = ip->instance_number; - hw_id = le16_to_cpu(ip->hw_id); - if (amdgpu_discovery_validate_ip(adev, inst, hw_id)) - goto next_ip; - - num_base_address = ip->num_base_address; - - DRM_DEBUG("%s(%d) #%d v%d.%d.%d:\n", - hw_id_names[le16_to_cpu(ip->hw_id)], - le16_to_cpu(ip->hw_id), - ip->instance_number, - ip->major, ip->minor, - ip->revision); - - if (le16_to_cpu(ip->hw_id) == VCN_HWID) { - /* Bit [5:0]: original revision value - * Bit [7:6]: en/decode capability: - * 0b00 : VCN function normally - * 0b10 : encode is disabled - * 0b01 : decode is disabled - */ - if (adev->vcn.num_vcn_inst < - AMDGPU_MAX_VCN_INSTANCES) { - adev->vcn.inst[adev->vcn.num_vcn_inst].vcn_config = - ip->revision & 0xc0; - adev->vcn.num_vcn_inst++; - adev->vcn.inst_mask |= - (1U << ip->instance_number); - adev->jpeg.inst_mask |= - (1U << ip->instance_number); - } else { - dev_err(adev->dev, "Too many VCN instances: %d vs %d\n", - adev->vcn.num_vcn_inst + 1, - AMDGPU_MAX_VCN_INSTANCES); - } - ip->revision &= ~0xc0; - } - if (le16_to_cpu(ip->hw_id) == SDMA0_HWID || - le16_to_cpu(ip->hw_id) == SDMA1_HWID || - le16_to_cpu(ip->hw_id) == SDMA2_HWID || - le16_to_cpu(ip->hw_id) == SDMA3_HWID) { - if (adev->sdma.num_instances < - AMDGPU_MAX_SDMA_INSTANCES) { - adev->sdma.num_instances++; - adev->sdma.sdma_mask |= - (1U << ip->instance_number); - } else { - dev_err(adev->dev, "Too many SDMA instances: %d vs %d\n", - adev->sdma.num_instances + 1, - AMDGPU_MAX_SDMA_INSTANCES); - } - } - - if (le16_to_cpu(ip->hw_id) == VPE_HWID) { - if (adev->vpe.num_instances < AMDGPU_MAX_VPE_INSTANCES) - adev->vpe.num_instances++; - else - dev_err(adev->dev, "Too many VPE instances: %d vs %d\n", - adev->vpe.num_instances + 1, - AMDGPU_MAX_VPE_INSTANCES); - } - - if (le16_to_cpu(ip->hw_id) == UMC_HWID) { - adev->gmc.num_umc++; - adev->umc.node_inst_num++; - } - - if (le16_to_cpu(ip->hw_id) == GC_HWID) - adev->gfx.xcc_mask |= - (1U << ip->instance_number); - - if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID) - wafl_ver = IP_VERSION_FULL(ip->major, ip->minor, - ip->revision, 0, 0); - - for (k = 0; k < num_base_address; k++) { - /* - * convert the endianness of base addresses in place, - * so that we don't need to convert them when accessing adev->reg_offset. - */ - if (ihdr->base_addr_64_bit) - /* Truncate the 64bit base address from ip discovery - * and only store lower 32bit ip base in reg_offset[]. - * Bits > 32 follows ASIC specific format, thus just - * discard them and handle it within specific ASIC. - * By this way reg_offset[] and related helpers can - * stay unchanged. - * The base address is in dwords, thus clear the - * highest 2 bits to store. - */ - ip->base_address[k] = - lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF; - else - ip->base_address[k] = le32_to_cpu(ip->base_address[k]); - DRM_DEBUG("\t0x%08x\n", ip->base_address[k]); - } - - for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) { - if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) && - hw_id_map[hw_ip] != 0) { - DRM_DEBUG("set register base offset for %s\n", - hw_id_names[le16_to_cpu(ip->hw_id)]); - adev->reg_offset[hw_ip][ip->instance_number] = - ip->base_address; - /* Instance support is somewhat inconsistent. - * SDMA is a good example. Sienna cichlid has 4 total - * SDMA instances, each enumerated separately (HWIDs - * 42, 43, 68, 69). Arcturus has 8 total SDMA instances, - * but they are enumerated as multiple instances of the - * same HWIDs (4x HWID 42, 4x HWID 43). UMC is another - * example. On most chips there are multiple instances - * with the same HWID. - */ - - if (ihdr->version < 3) { - subrev = 0; - variant = 0; - } else { - subrev = ip->sub_revision; - variant = ip->variant; - } - - adev->ip_versions[hw_ip] - [ip->instance_number] = - IP_VERSION_FULL(ip->major, - ip->minor, - ip->revision, - variant, - subrev); - } - } - -next_ip: - if (ihdr->base_addr_64_bit) - ip_offset += struct_size(ip, base_address_64, ip->num_base_address); - else - ip_offset += struct_size(ip, base_address, ip->num_base_address); - } - } - - if (wafl_ver && !adev->ip_versions[XGMI_HWIP][0]) - adev->ip_versions[XGMI_HWIP][0] = wafl_ver; - - return 0; + ihdr = (struct ip_discovery_header *)(discovery_bin + le16_to_cpu(info->offset)); + struct amdgpu_discovery_ip_targets targets = { + .xcc_mask = &adev->gfx.xcc_mask, .sdma_mask = &adev->sdma.sdma_mask, + .vcn_mask = &adev->vcn.inst_mask, .jpeg_mask = &adev->jpeg.inst_mask, + .vcn_count = &adev->vcn.num_vcn_inst, .sdma_count = &adev->sdma.num_instances, + .vpe_count = &adev->vpe.num_instances, .umc_count = &adev->gmc.num_umc, + .node_count = &adev->umc.node_inst_num, .ip_versions = adev->ip_versions, + }; + for (int i = 0; i < AMDGPU_MAX_VCN_INSTANCES; i++) + targets.vcn_config[i] = &adev->vcn.inst[i].vcn_config; + const struct amdgpu_discovery_ip_ops ops = { + .context = adev, .bind = amdgpu_discovery_ip_bind, + .debug = amdgpu_discovery_ip_debug, .error = amdgpu_discovery_ip_error, + .drm_error = amdgpu_discovery_ip_drm_error, + .hw_id_names = hw_id_names, + }; + return amdgpu_discovery_ip_walk(discovery_bin, ihdr, &targets, &ops); } static void amdgpu_discovery_harvest_ip(struct amdgpu_device *adev) @@ -1981,41 +1623,85 @@ union nps_info { static int amdgpu_discovery_refresh_nps_info(struct amdgpu_device *adev, union nps_info *nps_data) { - uint64_t vram_size, pos, offset; - struct nps_info_header *nhdr; - struct binary_header bhdr; - struct binary_header_v2 bhdrv2; - uint16_t checksum; + struct binary_header_v2 header __aligned(sizeof(u32)) = {0}; + struct binary_header_v2 observed_header __aligned(sizeof(u32)) = {0}; + struct table_info info __aligned(sizeof(u32)) = {0}; + struct table_info observed_info __aligned(sizeof(u32)) = {0}; + struct nps_info_header nhdr __aligned(sizeof(u32)) = {0}; + struct amdgpu_discovery_directory directory; + union nps_info data __aligned(sizeof(u32)) = {0}; + u64 pos, vram_size; + u32 memory_mib, size, read_size, count; + u16 offset; - vram_size = (uint64_t)RREG32(mmRCC_CONFIG_MEMSIZE) << 20; - pos = vram_size - DISCOVERY_TMR_OFFSET; - amdgpu_device_vram_access(adev, pos, &bhdr, sizeof(bhdr), false); - - switch (bhdr.version_major) { - case 2: - amdgpu_device_vram_access(adev, pos, &bhdrv2, sizeof(bhdrv2), false); - offset = le16_to_cpu(bhdrv2.table_list[NPS_INFO].offset); - checksum = le16_to_cpu(bhdrv2.table_list[NPS_INFO].checksum); - break; - case 1: - offset = le16_to_cpu(bhdr.table_list[NPS_INFO].offset); - checksum = le16_to_cpu(bhdr.table_list[NPS_INFO].checksum); - break; - default: + /* The original GMC reset caller serializes this live acquisition. Use + * the region actually acquired/reserved by discovery, including mailbox + * and dynamic offsets; never substitute VRAM-end minus a fixed offset. + * Sysmem-only discovery needs its own genuine acquisition path. */ + if (!nps_data || !adev->discovery.bin || !adev->discovery.reserve_tmr || + adev->discovery.size < sizeof(header) || + amdgpu_device_skip_hw_access(adev)) return -EINVAL; - } - - amdgpu_device_vram_access(adev, (pos + offset), nps_data, - sizeof(*nps_data), false); - - nhdr = (struct nps_info_header *)(nps_data); - if (!amdgpu_discovery_verify_checksum(adev, (uint8_t *)nps_data, - le32_to_cpu(nhdr->size_bytes), - checksum)) { - dev_err(adev->dev, "nps data refresh, checksum mismatch\n"); + memory_mib = RREG32(mmRCC_CONFIG_MEMSIZE); + if (!memory_mib || memory_mib == U32_MAX) + return -EINVAL; + vram_size = (u64)memory_mib << 20; + pos = adev->discovery.offset; + if (pos > vram_size || adev->discovery.size > vram_size - pos) return -EINVAL; - } + /* v2's flexible table_list is not part of this stack prefix. Read the + * single original entry only after validating its directory geometry. */ + amdgpu_device_vram_access(adev, pos, &header, sizeof(header), false); + if (le32_to_cpu(header.binary_signature) != BINARY_SIGNATURE || + (le16_to_cpu(header.version_major) != 1 && + le16_to_cpu(header.version_major) != 2) || + amdgpu_discovery_binary_directory((const u8 *)&header, sizeof(header), + adev->discovery.size, NPS_INFO, &directory)) + return -EINVAL; + amdgpu_device_vram_access(adev, pos + directory.entry_offset, &info, + sizeof(info), false); + offset = le16_to_cpu(info.offset); + if (!offset) + return -ENOENT; + if (offset < directory.directory_bytes || + offset > directory.binary_bytes || + sizeof(nhdr) > directory.binary_bytes - offset) + return -EINVAL; + amdgpu_device_vram_access(adev, pos + offset, &nhdr, sizeof(nhdr), false); + size = le32_to_cpu(nhdr.size_bytes); + if (le32_to_cpu(nhdr.table_id) != NPS_INFO_TABLE_ID || + le16_to_cpu(nhdr.version_major) != 1 || + size < offsetof(struct nps_info_v1_0, instance_info) || + size > sizeof(data) || size > directory.binary_bytes - offset) + return -EINVAL; + /* The original MM fallback transfers DWORDs even when the checksum span + * is not a multiple of four. Padding may only come from our retained + * region and must fit the private destination; it is never published. */ + read_size = (u32)ALIGN(size, sizeof(u32)); + if (read_size > sizeof(data) || read_size > adev->discovery.size - offset) + return -EINVAL; + amdgpu_device_vram_access(adev, pos + offset, &data, read_size, false); + memset((u8 *)&data + size, 0, sizeof(data) - size); + count = le32_to_cpu(data.v1.count); + if (memcmp(&data.v1.header, &nhdr, sizeof(nhdr)) || + count > NPS_INFO_TABLE_MAX_NUM_INSTANCES || + count > (size - offsetof(struct nps_info_v1_0, instance_info)) / + sizeof(struct nps_instance_info_v1_0) || + !amdgpu_discovery_verify_checksum(adev, (u8 *)&data, size, + le16_to_cpu(info.checksum))) + return -EINVAL; + + /* VRAM access has a void ABI. Initialized private buffers and bounded + * consistency/integrity checks do not invent a read-success result. */ + amdgpu_device_vram_access(adev, pos, &observed_header, + sizeof(observed_header), false); + amdgpu_device_vram_access(adev, pos + directory.entry_offset, + &observed_info, sizeof(observed_info), false); + if (memcmp(&header, &observed_header, sizeof(header)) || + memcmp(&info, &observed_info, sizeof(info))) + return -EINVAL; + *nps_data = data; return 0; } @@ -2842,7 +2528,7 @@ int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *adev) { int r; - switch (adev->asic_type) { + switch (amdgpu_discovery_static_asic(adev->asic_type)) { case CHIP_VEGA10: /* This is not fatal. We only need the discovery * binary for sysfs. We don't need it for a @@ -3048,7 +2734,7 @@ int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *adev) adev->ip_versions[XGMI_HWIP][0] = IP_VERSION(6, 1, 0); break; case CHIP_CYAN_SKILLFISH: - if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2) { + if (amdgpu_discovery_cyan_skillfish2(adev->apu_flags)) { r = amdgpu_discovery_reg_base_init(adev); if (r) return -EINVAL; diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.h index e0010f6a3e..672f5339a9 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery.h @@ -26,8 +26,7 @@ #include -#define DISCOVERY_TMR_SIZE (10 << 10) -#define DISCOVERY_TMR_OFFSET (64 << 10) +#include "amdgpu_discovery_tmr_limits.h" struct ip_discovery_top; struct drm_printer; diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h new file mode 100644 index 0000000000..a07bae8431 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_file_core.h @@ -0,0 +1,53 @@ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_DISCOVERY_FILE_CORE_H +#define AMDGPU_DISCOVERY_FILE_CORE_H +#include "../stela/discovery_binary.h" + +enum amdgpu_discovery_file_status { + AMDGPU_DISCOVERY_FILE_OK, + AMDGPU_DISCOVERY_FILE_TOO_LARGE, + AMDGPU_DISCOVERY_FILE_TOO_SMALL, + AMDGPU_DISCOVERY_FILE_INVALID, +}; +/* Actual preferred-file span before copy into the zeroed TMR-sized allocation. + * The original caller keeps request/log/copy/release and outer source policy. + * Readable immutable actual file bytes are required. No pointer retained. */ +static inline enum amdgpu_discovery_file_status +amdgpu_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity) +{ + if (bytes > capacity) + return AMDGPU_DISCOVERY_FILE_TOO_LARGE; + /* Ensure the firmware is at least large enough to contain the + * binary header fields. + */ + if (bytes < offsetof(struct binary_header, binary_size) + + sizeof(((struct binary_header *)0)->binary_size)) + return AMDGPU_DISCOVERY_FILE_TOO_SMALL; + /* A short file must not borrow zero-filled TMR padding as firmware data. */ + if (amdgpu_discovery_binary_validate(data, bytes) != AMDGPU_DISCOVERY_BINARY_OK) + return AMDGPU_DISCOVERY_FILE_INVALID; + return AMDGPU_DISCOVERY_FILE_OK; +} +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h new file mode 100644 index 0000000000..40f9a9e18d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_ip_core.h @@ -0,0 +1,308 @@ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_DISCOVERY_IP_CORE_H +#define AMDGPU_DISCOVERY_IP_CORE_H +#ifdef __KERNEL__ +#include +#include +#else +#include +#include +#include "../../common/linux/include/uapi/asm-generic/errno-base.h" +/* Native Stela owns these little-endian snapshots. */ +#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +#error "Native AMD discovery requires little-endian target" +#endif +#define le16_to_cpu(x) (x) +#define le32_to_cpu(x) (x) +#define le64_to_cpu(x) (x) +#define lower_32_bits(x) ((uint32_t)(x)) +#define struct_size(p, member, n) (sizeof(*(p)) + sizeof((p)->member[0]) * (n)) +#endif +#include "../include/discovery.h" +#include "../include/soc15_hw_ip.h" +#include "amdgpu_ip_types.h" +#include "amdgpu_ip_limits.h" +#include "amdgpu_ip_instance_limits.h" + +static int hw_id_map[MAX_HWIP] = { + [GC_HWIP] = GC_HWID, + [HDP_HWIP] = HDP_HWID, + [SDMA0_HWIP] = SDMA0_HWID, + [SDMA1_HWIP] = SDMA1_HWID, + [SDMA2_HWIP] = SDMA2_HWID, + [SDMA3_HWIP] = SDMA3_HWID, + [LSDMA_HWIP] = LSDMA_HWID, + [MMHUB_HWIP] = MMHUB_HWID, + [ATHUB_HWIP] = ATHUB_HWID, + [NBIO_HWIP] = NBIF_HWID, + [MP0_HWIP] = MP0_HWID, + [MP1_HWIP] = MP1_HWID, + [UVD_HWIP] = UVD_HWID, + [VCE_HWIP] = VCE_HWID, + [DF_HWIP] = DF_HWID, + [DCE_HWIP] = DMU_HWID, + [OSSSYS_HWIP] = OSSSYS_HWID, + [SMUIO_HWIP] = SMUIO_HWID, + [PWR_HWIP] = PWR_HWID, + [NBIF_HWIP] = NBIF_HWID, + [THM_HWIP] = THM_HWID, + [CLK_HWIP] = CLKA_HWID, + [UMC_HWIP] = UMC_HWID, + [XGMI_HWIP] = XGMI_HWID, + [DCI_HWIP] = DCI_HWID, + [PCIE_HWIP] = PCIE_HWID, + [VPE_HWIP] = VPE_HWID, + [ISP_HWIP] = ISP_HWID, + [ATU_HWIP] = ATU_HWID, +}; + +/* Direct pointers preserve actual original field types and intermediate writes. + * This is a bounded decode target, not an amdgpu_device or hardware owner. */ +struct amdgpu_discovery_ip_targets { + uint16_t *xcc_mask, *vcn_mask, *jpeg_mask; + uint32_t *sdma_mask, *vpe_count, *node_count; + int *sdma_count, *umc_count; + uint8_t *vcn_count, *vcn_config[AMDGPU_MAX_VCN_INSTANCES]; + uint32_t (*ip_versions)[HWIP_MAX_INSTANCE]; +}; +struct amdgpu_discovery_ip_ops { + void *context; + void (*bind)(void *context, unsigned hw_ip, unsigned instance, + uint32_t *base, unsigned count); + /* NULL diagnostic callbacks explicitly disable diagnostic output only. */ + void (*debug)(void *context, const char *format, ...); + void (*error)(void *context, const char *format, ...); + void (*drm_error)(void *context, const char *format, ...); + const char *const *hw_id_names; +}; +#define AMDGPU_IP_DEBUG(ops, ...) do { if ((ops)->debug) (ops)->debug((ops)->context, __VA_ARGS__); } while (0) +#define AMDGPU_IP_ERROR(ops, ...) do { if ((ops)->error) (ops)->error((ops)->context, __VA_ARGS__); } while (0) +#define AMDGPU_IP_DRM_ERROR(ops, ...) do { if ((ops)->drm_error) (ops)->drm_error((ops)->context, __VA_ARGS__); } while (0) + +static inline int amdgpu_discovery_ip_valid(const struct amdgpu_discovery_ip_ops *ops, + uint8_t instance, uint16_t hw_id) +{ + if (instance >= HWIP_MAX_INSTANCE) { + AMDGPU_IP_ERROR(ops, + "Unexpected instance_number (%d) from ip discovery blob\n", + instance); + return -EINVAL; + } + if (hw_id >= HW_ID_MAX) { + AMDGPU_IP_ERROR(ops, + "Unexpected hw_id (%d) from ip discovery blob\n", + hw_id); + return -EINVAL; + } + + return 0; +} + +/* Caller has validated immutable original geometry before its private copy is + * mutated. Run once; preserve original32/64 strides and packed accesses. Linux + * caller retains its acquisition/mask reset/table-error ordering and targets. */ +static inline int amdgpu_discovery_ip_walk(uint8_t *discovery_bin, + struct ip_discovery_header *ihdr, + const struct amdgpu_discovery_ip_targets *targets, + const struct amdgpu_discovery_ip_ops *ops) +{ + uint8_t num_base_address, subrev, variant; + struct die_header *dhdr; + struct ip_v4 *ip; + uint16_t die_offset, ip_offset, num_dies, num_ips, hw_id; + uint32_t wafl_ver = 0; + uint8_t inst; + int hw_ip, i, j, k; + num_dies = le16_to_cpu(ihdr->num_dies); + + AMDGPU_IP_DEBUG(ops, "number of dies: %d\n", num_dies); + + for (i = 0; i < num_dies; i++) { + die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); + dhdr = (struct die_header *)(discovery_bin + die_offset); + num_ips = le16_to_cpu(dhdr->num_ips); + ip_offset = die_offset + sizeof(*dhdr); + + if (le16_to_cpu(dhdr->die_id) != i) { + AMDGPU_IP_DRM_ERROR(ops, "invalid die id %d, expected %d\n", + le16_to_cpu(dhdr->die_id), i); + return -EINVAL; + } + + AMDGPU_IP_DEBUG(ops, "number of hardware IPs on die%d: %d\n", + le16_to_cpu(dhdr->die_id), num_ips); + + for (j = 0; j < num_ips; j++) { + ip = (struct ip_v4 *)(discovery_bin + ip_offset); + + inst = ip->instance_number; + hw_id = le16_to_cpu(ip->hw_id); + if (amdgpu_discovery_ip_valid(ops, inst, hw_id)) + goto next_ip; + + num_base_address = ip->num_base_address; + + AMDGPU_IP_DEBUG(ops, "%s(%d) #%d v%d.%d.%d:\n", + ops->hw_id_names[le16_to_cpu(ip->hw_id)], + le16_to_cpu(ip->hw_id), + ip->instance_number, + ip->major, ip->minor, + ip->revision); + + if (le16_to_cpu(ip->hw_id) == VCN_HWID) { + /* Bit [5:0]: original revision value + * Bit [7:6]: en/decode capability: + * 0b00 : VCN function normally + * 0b10 : encode is disabled + * 0b01 : decode is disabled + */ + if ((*targets->vcn_count) < + AMDGPU_MAX_VCN_INSTANCES) { + (*targets->vcn_config[(*targets->vcn_count)]) = + ip->revision & 0xc0; + (*targets->vcn_count)++; + (*targets->vcn_mask) |= + (1U << ip->instance_number); + (*targets->jpeg_mask) |= + (1U << ip->instance_number); + } else { + AMDGPU_IP_ERROR(ops, "Too many VCN instances: %d vs %d\n", + (*targets->vcn_count) + 1, + AMDGPU_MAX_VCN_INSTANCES); + } + ip->revision &= ~0xc0; + } + if (le16_to_cpu(ip->hw_id) == SDMA0_HWID || + le16_to_cpu(ip->hw_id) == SDMA1_HWID || + le16_to_cpu(ip->hw_id) == SDMA2_HWID || + le16_to_cpu(ip->hw_id) == SDMA3_HWID) { + if ((*targets->sdma_count) < + AMDGPU_MAX_SDMA_INSTANCES) { + (*targets->sdma_count)++; + (*targets->sdma_mask) |= + (1U << ip->instance_number); + } else { + AMDGPU_IP_ERROR(ops, "Too many SDMA instances: %d vs %d\n", + (*targets->sdma_count) + 1, + AMDGPU_MAX_SDMA_INSTANCES); + } + } + + if (le16_to_cpu(ip->hw_id) == VPE_HWID) { + if ((*targets->vpe_count) < AMDGPU_MAX_VPE_INSTANCES) + (*targets->vpe_count)++; + else + AMDGPU_IP_ERROR(ops, "Too many VPE instances: %d vs %d\n", + (*targets->vpe_count) + 1, + AMDGPU_MAX_VPE_INSTANCES); + } + + if (le16_to_cpu(ip->hw_id) == UMC_HWID) { + (*targets->umc_count)++; + (*targets->node_count)++; + } + + if (le16_to_cpu(ip->hw_id) == GC_HWID) + (*targets->xcc_mask) |= + (1U << ip->instance_number); + + if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID) + wafl_ver = IP_VERSION_FULL((uint32_t)ip->major, (uint32_t)ip->minor, + (uint32_t)ip->revision, 0, 0); + + for (k = 0; k < num_base_address; k++) { + /* + * convert the endianness of base addresses in place, + * so that we don't need to convert them when accessing adev->reg_offset. + */ + if (ihdr->base_addr_64_bit) + /* Truncate the 64bit base address from ip discovery + * and only store lower 32bit ip base in reg_offset[]. + * Bits > 32 follows ASIC specific format, thus just + * discard them and handle it within specific ASIC. + * By this way reg_offset[] and related helpers can + * stay unchanged. + * The base address is in dwords, thus clear the + * highest 2 bits to store. + */ + ip->base_address[k] = + lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF; + else + ip->base_address[k] = le32_to_cpu(ip->base_address[k]); + AMDGPU_IP_DEBUG(ops, "\t0x%08x\n", ip->base_address[k]); + } + + for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) { + if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) && + hw_id_map[hw_ip] != 0) { + AMDGPU_IP_DEBUG(ops, "set register base offset for %s\n", + ops->hw_id_names[le16_to_cpu(ip->hw_id)]); + ops->bind(ops->context, hw_ip, ip->instance_number, + ip->base_address, num_base_address); + /* Instance support is somewhat inconsistent. + * SDMA is a good example. Sienna cichlid has 4 total + * SDMA instances, each enumerated separately (HWIDs + * 42, 43, 68, 69). Arcturus has 8 total SDMA instances, + * but they are enumerated as multiple instances of the + * same HWIDs (4x HWID 42, 4x HWID 43). UMC is another + * example. On most chips there are multiple instances + * with the same HWID. + */ + + if (ihdr->version < 3) { + subrev = 0; + variant = 0; + } else { + subrev = ip->sub_revision; + variant = ip->variant; + } + + targets->ip_versions[hw_ip] + [ip->instance_number] = + IP_VERSION_FULL((uint32_t)ip->major, + (uint32_t)ip->minor, + (uint32_t)ip->revision, + variant, + subrev); + } + } + +next_ip: + if (ihdr->base_addr_64_bit) + ip_offset += struct_size(ip, base_address_64, ip->num_base_address); + else + ip_offset += struct_size(ip, base_address, ip->num_base_address); + } + } + + if (wafl_ver && !targets->ip_versions[XGMI_HWIP][0]) + targets->ip_versions[XGMI_HWIP][0] = wafl_ver; + + return 0; +} +#undef AMDGPU_IP_DEBUG +#undef AMDGPU_IP_ERROR +#undef AMDGPU_IP_DRM_ERROR +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h new file mode 100644 index 0000000000..1d41b61c52 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_source_core.h @@ -0,0 +1,142 @@ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + + +/* + * Copyright 2008 Advanced Micro Devices, Inc. + * Copyright 2008 Red Hat Inc. + * Copyright 2009 Jerome Glisse. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Dave Airlie + * Alex Deucher + * Jerome Glisse + */ + +#ifndef AMDGPU_DISCOVERY_SOURCE_CORE_H +#define AMDGPU_DISCOVERY_SOURCE_CORE_H +#include "../../common/linux/include/drm/amd_asic_type.h" +#include "../include/amd_chip_flags.h" +/* Exact original early-init case groups; SI/CIK build admission is separate. */ +enum amdgpu_initial_ip_path { + AMDGPU_INITIAL_IP_DISCOVERY, + AMDGPU_INITIAL_IP_SI, + AMDGPU_INITIAL_IP_CIK, + AMDGPU_INITIAL_IP_VI, +}; +static inline enum amdgpu_initial_ip_path amdgpu_initial_ip_path(enum amd_asic_type asic_type) +{ + switch (asic_type) { + case CHIP_VERDE: + case CHIP_TAHITI: + case CHIP_PITCAIRN: + case CHIP_OLAND: + case CHIP_HAINAN: + return AMDGPU_INITIAL_IP_SI; + case CHIP_BONAIRE: + case CHIP_HAWAII: + case CHIP_KAVERI: + case CHIP_KABINI: + case CHIP_MULLINS: + return AMDGPU_INITIAL_IP_CIK; + case CHIP_TOPAZ: + case CHIP_TONGA: + case CHIP_FIJI: + case CHIP_POLARIS10: + case CHIP_POLARIS11: + case CHIP_POLARIS12: + case CHIP_VEGAM: + case CHIP_CARRIZO: + case CHIP_STONEY: + return AMDGPU_INITIAL_IP_VI; + default: + return AMDGPU_INITIAL_IP_DISCOVERY; + } +} +/* The original switch has these static arms and one default dynamic arm. */ +static inline enum amd_asic_type amdgpu_discovery_static_asic(enum amd_asic_type asic_type) +{ + switch (asic_type) { + case CHIP_VEGA10: + case CHIP_VEGA12: + case CHIP_RAVEN: + case CHIP_VEGA20: + case CHIP_ARCTURUS: + case CHIP_ALDEBARAN: + case CHIP_CYAN_SKILLFISH: + return asic_type; + default: + return CHIP_LAST; + } +} +static inline int amdgpu_discovery_cyan_skillfish2(unsigned long apu_flags) +{ + return (apu_flags & AMD_APU_IS_CYAN_SKILLFISH2) != 0; +} +static inline const char *amdgpu_discovery_fw_name(enum amd_asic_type asic_type, + unsigned long apu_flags, int discovery_option) +{ + if (discovery_option == 2) { + return "amdgpu/ip_discovery.bin"; + } + + switch (asic_type) { + case CHIP_VEGA10: + return "amdgpu/vega10_ip_discovery.bin"; + case CHIP_VEGA12: + return "amdgpu/vega12_ip_discovery.bin"; + case CHIP_RAVEN: + if (apu_flags & AMD_APU_IS_RAVEN2) + return "amdgpu/raven2_ip_discovery.bin"; + else if (apu_flags & AMD_APU_IS_PICASSO) + return "amdgpu/picasso_ip_discovery.bin"; + else + return "amdgpu/raven_ip_discovery.bin"; + case CHIP_VEGA20: + return "amdgpu/vega20_ip_discovery.bin"; + case CHIP_ARCTURUS: + return "amdgpu/arcturus_ip_discovery.bin"; + case CHIP_ALDEBARAN: + return "amdgpu/aldebaran_ip_discovery.bin"; + default: + return NULL; + } +} +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h new file mode 100644 index 0000000000..3207b0a7d5 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_core.h @@ -0,0 +1,159 @@ +/* + * Copyright 2018 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_DISCOVERY_TMR_CORE_H +#define AMDGPU_DISCOVERY_TMR_CORE_H +#ifdef __KERNEL__ +#include +#include +#include +#define AMDGPU_TMR_U32_MAX U32_MAX +#define AMDGPU_TMR_ENXIO ENXIO +#define AMDGPU_TMR_EINVAL EINVAL +#define AMDGPU_TMR_LE32(value) le32_to_cpu(value) +#else +#include +#include +#include +#define AMDGPU_TMR_U32_MAX UINT32_MAX +#define AMDGPU_TMR_ENXIO 6 +#define AMDGPU_TMR_EINVAL 22 +#define AMDGPU_TMR_LE32(value) (value) /* Native consumer is x86-64 little endian. */ +#endif +#include "amdgpu_discovery_tmr_limits.h" +#include "../include/discovery.h" +/* These original bootstrap register offsets are consistent across the SoCs. */ +#define mmRCC_CONFIG_MEMSIZE 0xde3 +#define mmMP0_SMN_C2PMSG_33 0x16061 +#define mmDRIVER_SCRATCH_0 0x94 +#define mmDRIVER_SCRATCH_1 0x95 +#define mmDRIVER_SCRATCH_2 0x96 +struct amdgpu_discovery_tmr_state { + uint64_t offset; + uint32_t size; + bool is_sysmem; + bool has_memory_size; /* Original bool output is untouched on RCC all-ones. */ +}; +struct amdgpu_discovery_tmr_ops { + uint32_t (*read32)(void *, uint32_t); + void (*sleep_ms)(void *, unsigned); + /* Status covers caller preflight/services only. Original void VRAM reads + * have no transport acknowledgement; Linux invokes the actual void reader. */ + int (*read_vram)(void *, uint64_t, uint32_t *, size_t); + int (*acpi_tmr)(void *, uint64_t *, uint64_t *); +}; +/* Original ordered policy, including nonfatal IFWI poll exhaustion and partial + * state on error. All callbacks are real caller services, never optional stubs. + * Native callers must bound every register/range and retain the actual owner. + */ +static inline int amdgpu_discovery_tmr_query_core( + const struct amdgpu_discovery_tmr_ops *ops, void *context, + bool is_vf, bool dynamic_region, uint64_t critical_offset, + uint32_t critical_size, struct amdgpu_discovery_tmr_state *state) +{ + uint64_t vram_size, tmr_offset, tmr_size; + uint32_t msg, tmr_offset_lo, tmr_offset_hi; + int i, ret; + + if (!is_vf) { + /* It can take up to two second for IFWI init to complete on some dGPUs, + * but generally it should be in the 60-100ms range. Normally this starts + * as soon as the device gets power so by the time the OS loads this has long + * completed. However, when a card is hotplugged via e.g., USB4, we need to + * wait for this to complete. Once the C2PMSG is updated, we can + * continue. + */ + + for (i = 0; i < 2000; i++) { + msg = ops->read32(context, mmMP0_SMN_C2PMSG_33); + if (msg & 0x80000000) + break; + ops->sleep_ms(context, 1); + } + } + + vram_size = ops->read32(context, mmRCC_CONFIG_MEMSIZE); + if (vram_size == AMDGPU_TMR_U32_MAX) + return -AMDGPU_TMR_ENXIO; + else if (!vram_size) + state->is_sysmem = true; + else + state->is_sysmem = false; + + state->has_memory_size = true; + /* init the default tmr size and offset */ + state->size = DISCOVERY_TMR_SIZE; + if (vram_size) + state->offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET; + + if (is_vf) { + if (dynamic_region) { + state->offset = + critical_offset; + state->size = + critical_size; + if (!state->size) + return -AMDGPU_TMR_EINVAL; + } else { + goto out; + } + } else { + if (state->offset) { + uint32_t signature; + + /* If VRAM holds a valid discovery signature at the default + * discovery offset, use it as-is. + */ + ret = ops->read_vram(context, state->offset, &signature, sizeof(signature)); + if (ret) + return ret; + if (AMDGPU_TMR_LE32(signature) == BINARY_SIGNATURE) + goto out; + } + + tmr_size = ops->read32(context, mmDRIVER_SCRATCH_2); + if (tmr_size) { + /* It's preferred to transition to PSP mailbox reg interface + * for both bare-metal and passthrough if available */ + state->size = (uint32_t)tmr_size; + tmr_offset_lo = ops->read32(context, mmDRIVER_SCRATCH_0); + tmr_offset_hi = ops->read32(context, mmDRIVER_SCRATCH_1); + state->offset = ((uint64_t)AMDGPU_TMR_LE32(tmr_offset_hi) << 32 | + AMDGPU_TMR_LE32(tmr_offset_lo)); + } else if (!vram_size) { + /* fall back to apci approach to query tmr offset if vram_size is 0 */ + ret = ops->acpi_tmr(context, &tmr_offset, &tmr_size); + if (ret) + return ret; + state->size = DISCOVERY_TMR_SIZE; + state->offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET; + } + } +out: + return 0; +} +#undef AMDGPU_TMR_ENXIO +#undef AMDGPU_TMR_EINVAL +#undef AMDGPU_TMR_U32_MAX +#undef AMDGPU_TMR_LE32 +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h new file mode 100644 index 0000000000..0d108446c8 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_discovery_tmr_limits.h @@ -0,0 +1,28 @@ +/* + * Copyright 2018 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_DISCOVERY_TMR_LIMITS_H +#define AMDGPU_DISCOVERY_TMR_LIMITS_H +#define DISCOVERY_TMR_SIZE (10 << 10) +#define DISCOVERY_TMR_OFFSET (64 << 10) +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_doorbell_mgr.c b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_doorbell_mgr.c index bc78585673..395adaf323 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_doorbell_mgr.c +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_doorbell_mgr.c @@ -23,6 +23,7 @@ */ #include "amdgpu.h" +#include "../stela/native_bar.h" /** * amdgpu_mm_rdoorbell - read a doorbell dword @@ -156,7 +157,8 @@ int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev) return 0; /* Reserve first num_kernel_doorbells (page-aligned) for kernel ops */ - size = ALIGN(adev->doorbell.num_kernel_doorbells * sizeof(u32), PAGE_SIZE); + size = amdgpu_native_kernel_doorbell_storage_bytes(adev->doorbell.num_kernel_doorbells, + PAGE_SIZE); /* Allocate an extra page for MES kernel usages (ring test) */ adev->mes.db_start_dw_offset = size / sizeof(u32); @@ -211,21 +213,11 @@ int amdgpu_doorbell_init(struct amdgpu_device *adev) adev->doorbell.size = pci_resource_len(adev->pdev, 2); adev->doorbell.num_kernel_doorbells = - min_t(u32, adev->doorbell.size / sizeof(u32), - adev->doorbell_index.max_assignment + 1); + amdgpu_native_kernel_doorbell_count(adev->asic_type, adev->doorbell.size, + adev->doorbell_index.max_assignment); if (adev->doorbell.num_kernel_doorbells == 0) return -EINVAL; - /* - * For Vega, reserve and map two pages on doorbell BAR since SDMA - * paging queue doorbell use the second page. The - * AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the - * doorbells are in the first page. So with paging queue enabled, - * the max num_kernel_doorbells should + 1 page (0x400 in dword) - */ - if (adev->asic_type >= CHIP_VEGA10) - adev->doorbell.num_kernel_doorbells += 0x400; - return 0; } diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_drv.c b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_drv.c index 1aed121f4d..78057c93b5 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_drv.c +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_drv.c @@ -1125,1095 +1125,11 @@ module_param_named(hdmi_hpd_debounce_delay_ms, amdgpu_hdmi_hpd_debounce_delay_ms MODULE_PARM_DESC(ptl, "Enable PTL (-1 = auto, 0 = disable (default), 1 = enable, 2 = permanently disable)"); module_param_named(ptl, amdgpu_ptl, int, 0444); -/* These devices are not supported by amdgpu. - * They are supported by the mach64, r128, radeon drivers - */ -static const u16 amdgpu_unsupported_pciidlist[] = { - /* mach64 */ - 0x4354, - 0x4358, - 0x4554, - 0x4742, - 0x4744, - 0x4749, - 0x474C, - 0x474D, - 0x474E, - 0x474F, - 0x4750, - 0x4751, - 0x4752, - 0x4753, - 0x4754, - 0x4755, - 0x4756, - 0x4757, - 0x4758, - 0x4759, - 0x475A, - 0x4C42, - 0x4C44, - 0x4C47, - 0x4C49, - 0x4C4D, - 0x4C4E, - 0x4C50, - 0x4C51, - 0x4C52, - 0x4C53, - 0x5654, - 0x5655, - 0x5656, - /* r128 */ - 0x4c45, - 0x4c46, - 0x4d46, - 0x4d4c, - 0x5041, - 0x5042, - 0x5043, - 0x5044, - 0x5045, - 0x5046, - 0x5047, - 0x5048, - 0x5049, - 0x504A, - 0x504B, - 0x504C, - 0x504D, - 0x504E, - 0x504F, - 0x5050, - 0x5051, - 0x5052, - 0x5053, - 0x5054, - 0x5055, - 0x5056, - 0x5057, - 0x5058, - 0x5245, - 0x5246, - 0x5247, - 0x524b, - 0x524c, - 0x534d, - 0x5446, - 0x544C, - 0x5452, - /* radeon */ - 0x3150, - 0x3151, - 0x3152, - 0x3154, - 0x3155, - 0x3E50, - 0x3E54, - 0x4136, - 0x4137, - 0x4144, - 0x4145, - 0x4146, - 0x4147, - 0x4148, - 0x4149, - 0x414A, - 0x414B, - 0x4150, - 0x4151, - 0x4152, - 0x4153, - 0x4154, - 0x4155, - 0x4156, - 0x4237, - 0x4242, - 0x4336, - 0x4337, - 0x4437, - 0x4966, - 0x4967, - 0x4A48, - 0x4A49, - 0x4A4A, - 0x4A4B, - 0x4A4C, - 0x4A4D, - 0x4A4E, - 0x4A4F, - 0x4A50, - 0x4A54, - 0x4B48, - 0x4B49, - 0x4B4A, - 0x4B4B, - 0x4B4C, - 0x4C57, - 0x4C58, - 0x4C59, - 0x4C5A, - 0x4C64, - 0x4C66, - 0x4C67, - 0x4E44, - 0x4E45, - 0x4E46, - 0x4E47, - 0x4E48, - 0x4E49, - 0x4E4A, - 0x4E4B, - 0x4E50, - 0x4E51, - 0x4E52, - 0x4E53, - 0x4E54, - 0x4E56, - 0x5144, - 0x5145, - 0x5146, - 0x5147, - 0x5148, - 0x514C, - 0x514D, - 0x5157, - 0x5158, - 0x5159, - 0x515A, - 0x515E, - 0x5460, - 0x5462, - 0x5464, - 0x5548, - 0x5549, - 0x554A, - 0x554B, - 0x554C, - 0x554D, - 0x554E, - 0x554F, - 0x5550, - 0x5551, - 0x5552, - 0x5554, - 0x564A, - 0x564B, - 0x564F, - 0x5652, - 0x5653, - 0x5657, - 0x5834, - 0x5835, - 0x5954, - 0x5955, - 0x5974, - 0x5975, - 0x5960, - 0x5961, - 0x5962, - 0x5964, - 0x5965, - 0x5969, - 0x5a41, - 0x5a42, - 0x5a61, - 0x5a62, - 0x5b60, - 0x5b62, - 0x5b63, - 0x5b64, - 0x5b65, - 0x5c61, - 0x5c63, - 0x5d48, - 0x5d49, - 0x5d4a, - 0x5d4c, - 0x5d4d, - 0x5d4e, - 0x5d4f, - 0x5d50, - 0x5d52, - 0x5d57, - 0x5e48, - 0x5e4a, - 0x5e4b, - 0x5e4c, - 0x5e4d, - 0x5e4f, - 0x6700, - 0x6701, - 0x6702, - 0x6703, - 0x6704, - 0x6705, - 0x6706, - 0x6707, - 0x6708, - 0x6709, - 0x6718, - 0x6719, - 0x671c, - 0x671d, - 0x671f, - 0x6720, - 0x6721, - 0x6722, - 0x6723, - 0x6724, - 0x6725, - 0x6726, - 0x6727, - 0x6728, - 0x6729, - 0x6738, - 0x6739, - 0x673e, - 0x6740, - 0x6741, - 0x6742, - 0x6743, - 0x6744, - 0x6745, - 0x6746, - 0x6747, - 0x6748, - 0x6749, - 0x674A, - 0x6750, - 0x6751, - 0x6758, - 0x6759, - 0x675B, - 0x675D, - 0x675F, - 0x6760, - 0x6761, - 0x6762, - 0x6763, - 0x6764, - 0x6765, - 0x6766, - 0x6767, - 0x6768, - 0x6770, - 0x6771, - 0x6772, - 0x6778, - 0x6779, - 0x677B, - 0x6840, - 0x6841, - 0x6842, - 0x6843, - 0x6849, - 0x684C, - 0x6850, - 0x6858, - 0x6859, - 0x6880, - 0x6888, - 0x6889, - 0x688A, - 0x688C, - 0x688D, - 0x6898, - 0x6899, - 0x689b, - 0x689c, - 0x689d, - 0x689e, - 0x68a0, - 0x68a1, - 0x68a8, - 0x68a9, - 0x68b0, - 0x68b8, - 0x68b9, - 0x68ba, - 0x68be, - 0x68bf, - 0x68c0, - 0x68c1, - 0x68c7, - 0x68c8, - 0x68c9, - 0x68d8, - 0x68d9, - 0x68da, - 0x68de, - 0x68e0, - 0x68e1, - 0x68e4, - 0x68e5, - 0x68e8, - 0x68e9, - 0x68f1, - 0x68f2, - 0x68f8, - 0x68f9, - 0x68fa, - 0x68fe, - 0x7100, - 0x7101, - 0x7102, - 0x7103, - 0x7104, - 0x7105, - 0x7106, - 0x7108, - 0x7109, - 0x710A, - 0x710B, - 0x710C, - 0x710E, - 0x710F, - 0x7140, - 0x7141, - 0x7142, - 0x7143, - 0x7144, - 0x7145, - 0x7146, - 0x7147, - 0x7149, - 0x714A, - 0x714B, - 0x714C, - 0x714D, - 0x714E, - 0x714F, - 0x7151, - 0x7152, - 0x7153, - 0x715E, - 0x715F, - 0x7180, - 0x7181, - 0x7183, - 0x7186, - 0x7187, - 0x7188, - 0x718A, - 0x718B, - 0x718C, - 0x718D, - 0x718F, - 0x7193, - 0x7196, - 0x719B, - 0x719F, - 0x71C0, - 0x71C1, - 0x71C2, - 0x71C3, - 0x71C4, - 0x71C5, - 0x71C6, - 0x71C7, - 0x71CD, - 0x71CE, - 0x71D2, - 0x71D4, - 0x71D5, - 0x71D6, - 0x71DA, - 0x71DE, - 0x7200, - 0x7210, - 0x7211, - 0x7240, - 0x7243, - 0x7244, - 0x7245, - 0x7246, - 0x7247, - 0x7248, - 0x7249, - 0x724A, - 0x724B, - 0x724C, - 0x724D, - 0x724E, - 0x724F, - 0x7280, - 0x7281, - 0x7283, - 0x7284, - 0x7287, - 0x7288, - 0x7289, - 0x728B, - 0x728C, - 0x7290, - 0x7291, - 0x7293, - 0x7297, - 0x7834, - 0x7835, - 0x791e, - 0x791f, - 0x793f, - 0x7941, - 0x7942, - 0x796c, - 0x796d, - 0x796e, - 0x796f, - 0x9400, - 0x9401, - 0x9402, - 0x9403, - 0x9405, - 0x940A, - 0x940B, - 0x940F, - 0x94A0, - 0x94A1, - 0x94A3, - 0x94B1, - 0x94B3, - 0x94B4, - 0x94B5, - 0x94B9, - 0x9440, - 0x9441, - 0x9442, - 0x9443, - 0x9444, - 0x9446, - 0x944A, - 0x944B, - 0x944C, - 0x944E, - 0x9450, - 0x9452, - 0x9456, - 0x945A, - 0x945B, - 0x945E, - 0x9460, - 0x9462, - 0x946A, - 0x946B, - 0x947A, - 0x947B, - 0x9480, - 0x9487, - 0x9488, - 0x9489, - 0x948A, - 0x948F, - 0x9490, - 0x9491, - 0x9495, - 0x9498, - 0x949C, - 0x949E, - 0x949F, - 0x94C0, - 0x94C1, - 0x94C3, - 0x94C4, - 0x94C5, - 0x94C6, - 0x94C7, - 0x94C8, - 0x94C9, - 0x94CB, - 0x94CC, - 0x94CD, - 0x9500, - 0x9501, - 0x9504, - 0x9505, - 0x9506, - 0x9507, - 0x9508, - 0x9509, - 0x950F, - 0x9511, - 0x9515, - 0x9517, - 0x9519, - 0x9540, - 0x9541, - 0x9542, - 0x954E, - 0x954F, - 0x9552, - 0x9553, - 0x9555, - 0x9557, - 0x955f, - 0x9580, - 0x9581, - 0x9583, - 0x9586, - 0x9587, - 0x9588, - 0x9589, - 0x958A, - 0x958B, - 0x958C, - 0x958D, - 0x958E, - 0x958F, - 0x9590, - 0x9591, - 0x9593, - 0x9595, - 0x9596, - 0x9597, - 0x9598, - 0x9599, - 0x959B, - 0x95C0, - 0x95C2, - 0x95C4, - 0x95C5, - 0x95C6, - 0x95C7, - 0x95C9, - 0x95CC, - 0x95CD, - 0x95CE, - 0x95CF, - 0x9610, - 0x9611, - 0x9612, - 0x9613, - 0x9614, - 0x9615, - 0x9616, - 0x9640, - 0x9641, - 0x9642, - 0x9643, - 0x9644, - 0x9645, - 0x9647, - 0x9648, - 0x9649, - 0x964a, - 0x964b, - 0x964c, - 0x964e, - 0x964f, - 0x9710, - 0x9711, - 0x9712, - 0x9713, - 0x9714, - 0x9715, - 0x9802, - 0x9803, - 0x9804, - 0x9805, - 0x9806, - 0x9807, - 0x9808, - 0x9809, - 0x980A, - 0x9900, - 0x9901, - 0x9903, - 0x9904, - 0x9905, - 0x9906, - 0x9907, - 0x9908, - 0x9909, - 0x990A, - 0x990B, - 0x990C, - 0x990D, - 0x990E, - 0x990F, - 0x9910, - 0x9913, - 0x9917, - 0x9918, - 0x9919, - 0x9990, - 0x9991, - 0x9992, - 0x9993, - 0x9994, - 0x9995, - 0x9996, - 0x9997, - 0x9998, - 0x9999, - 0x999A, - 0x999B, - 0x999C, - 0x999D, - 0x99A0, - 0x99A2, - 0x99A4, - /* radeon secondary ids */ - 0x3171, - 0x3e70, - 0x4164, - 0x4165, - 0x4166, - 0x4168, - 0x4170, - 0x4171, - 0x4172, - 0x4173, - 0x496e, - 0x4a69, - 0x4a6a, - 0x4a6b, - 0x4a70, - 0x4a74, - 0x4b69, - 0x4b6b, - 0x4b6c, - 0x4c6e, - 0x4e64, - 0x4e65, - 0x4e66, - 0x4e67, - 0x4e68, - 0x4e69, - 0x4e6a, - 0x4e71, - 0x4f73, - 0x5569, - 0x556b, - 0x556d, - 0x556f, - 0x5571, - 0x5854, - 0x5874, - 0x5940, - 0x5941, - 0x5b70, - 0x5b72, - 0x5b73, - 0x5b74, - 0x5b75, - 0x5d44, - 0x5d45, - 0x5d6d, - 0x5d6f, - 0x5d72, - 0x5d77, - 0x5e6b, - 0x5e6d, - 0x7120, - 0x7124, - 0x7129, - 0x712e, - 0x712f, - 0x7162, - 0x7163, - 0x7166, - 0x7167, - 0x7172, - 0x7173, - 0x71a0, - 0x71a1, - 0x71a3, - 0x71a7, - 0x71bb, - 0x71e0, - 0x71e1, - 0x71e2, - 0x71e6, - 0x71e7, - 0x71f2, - 0x7269, - 0x726b, - 0x726e, - 0x72a0, - 0x72a8, - 0x72b1, - 0x72b3, - 0x793f, -}; - -static const struct pci_device_id pciidlist[] = { - {0x1002, 0x6780, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6784, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6788, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x678A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6790, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6791, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6792, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6798, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6799, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x679A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x679B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x679E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x679F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, - {0x1002, 0x6800, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, - {0x1002, 0x6801, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, - {0x1002, 0x6802, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, - {0x1002, 0x6806, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6808, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6809, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6810, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6811, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6816, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6817, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6818, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6819, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, - {0x1002, 0x6600, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6601, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6602, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6603, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6604, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6605, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6606, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6607, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6608, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, - {0x1002, 0x6610, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, - {0x1002, 0x6611, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, - {0x1002, 0x6613, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, - {0x1002, 0x6617, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6620, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6621, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6623, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, - {0x1002, 0x6631, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, - {0x1002, 0x6820, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6821, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6822, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6823, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6824, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6825, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6826, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6827, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6828, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x6829, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x682A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x682B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x682C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x682D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x682F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6830, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6831, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, - {0x1002, 0x6835, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x6837, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x6838, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x6839, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x683B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x683D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x683F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, - {0x1002, 0x6660, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - {0x1002, 0x6663, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - {0x1002, 0x6664, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - {0x1002, 0x6665, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - {0x1002, 0x6667, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - {0x1002, 0x666F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, - /* Kaveri */ - {0x1002, 0x1304, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x1305, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1306, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x1307, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1309, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x130F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1310, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1311, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1312, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1313, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1315, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1316, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x1317, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x1318, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x131B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x131C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - {0x1002, 0x131D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, - /* Bonaire */ - {0x1002, 0x6640, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, - {0x1002, 0x6641, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, - {0x1002, 0x6646, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, - {0x1002, 0x6647, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, - {0x1002, 0x6649, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x6650, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x6651, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x6658, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x665c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x665d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - {0x1002, 0x665f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, - /* Hawaii */ - {0x1002, 0x67A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67A8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67A9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67AA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67B0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67B1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67B8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67B9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67BA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - {0x1002, 0x67BE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, - /* Kabini */ - {0x1002, 0x9830, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9831, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x9832, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9833, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x9834, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9835, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x9836, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9837, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x9838, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9839, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x983a, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x983b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x983c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x983d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x983e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - {0x1002, 0x983f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, - /* mullins */ - {0x1002, 0x9850, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9851, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9852, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9853, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9854, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9855, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9856, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9857, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9858, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x9859, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - {0x1002, 0x985F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, - /* topaz */ - {0x1002, 0x6900, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, - {0x1002, 0x6901, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, - {0x1002, 0x6902, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, - {0x1002, 0x6903, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, - {0x1002, 0x6907, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, - /* tonga */ - {0x1002, 0x6920, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6921, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6928, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6929, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x692B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x692F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6930, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6938, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - {0x1002, 0x6939, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, - /* fiji */ - {0x1002, 0x7300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_FIJI}, - {0x1002, 0x730F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_FIJI}, - /* carrizo */ - {0x1002, 0x9870, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, - {0x1002, 0x9874, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, - {0x1002, 0x9875, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, - {0x1002, 0x9876, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, - {0x1002, 0x9877, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, - /* stoney */ - {0x1002, 0x98E4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_STONEY|AMD_IS_APU}, - /* Polaris11 */ - {0x1002, 0x67E0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67E3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67E8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67EB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67EF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67FF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67E1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67E7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - {0x1002, 0x67E9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, - /* Polaris10 */ - {0x1002, 0x67C0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67D0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67DF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67C9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67CA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67CC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x67CF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - {0x1002, 0x6FDF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, - /* Polaris12 */ - {0x1002, 0x6980, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6986, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6987, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6995, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x6997, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - {0x1002, 0x699F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, - /* VEGAM */ - {0x1002, 0x694C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, - {0x1002, 0x694E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, - {0x1002, 0x694F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, - /* Vega 10 */ - {0x1002, 0x6860, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6861, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6862, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6863, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6864, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6867, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6868, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x6869, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686a, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x686f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - {0x1002, 0x687f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, - /* Vega 12 */ - {0x1002, 0x69A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, - {0x1002, 0x69A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, - {0x1002, 0x69A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, - {0x1002, 0x69A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, - {0x1002, 0x69AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, - /* Vega 20 */ - {0x1002, 0x66A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66A4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66A7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - {0x1002, 0x66AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, - /* Raven */ - {0x1002, 0x15dd, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RAVEN|AMD_IS_APU}, - {0x1002, 0x15d8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RAVEN|AMD_IS_APU}, - /* Arcturus */ - {0x1002, 0x738C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, - {0x1002, 0x7388, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, - {0x1002, 0x738E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, - {0x1002, 0x7390, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, - /* Navi10 */ - {0x1002, 0x7310, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x7312, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x7318, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x7319, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x731A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x731B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x731E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - {0x1002, 0x731F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, - /* Navi14 */ - {0x1002, 0x7340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, - {0x1002, 0x7341, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, - {0x1002, 0x7347, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, - {0x1002, 0x734F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, - - /* Renoir */ - {0x1002, 0x15E7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, - {0x1002, 0x1636, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, - {0x1002, 0x1638, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, - {0x1002, 0x164C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, - - /* Navi12 */ - {0x1002, 0x7360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI12}, - {0x1002, 0x7362, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI12}, - - /* Sienna_Cichlid */ - {0x1002, 0x73A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A5, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73A9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73AB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73AC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73AD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73AE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - {0x1002, 0x73BF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, - - /* Yellow Carp */ - {0x1002, 0x164D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_YELLOW_CARP|AMD_IS_APU}, - {0x1002, 0x1681, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_YELLOW_CARP|AMD_IS_APU}, - - /* Navy_Flounder */ - {0x1002, 0x73C0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73C1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73C3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - {0x1002, 0x73DF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, - - /* DIMGREY_CAVEFISH */ - {0x1002, 0x73E0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73E1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73E2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73E3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73E8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73E9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73EA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73EB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73EC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73ED, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73EF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - {0x1002, 0x73FF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, - - /* Aldebaran */ - {0x1002, 0x7408, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, - {0x1002, 0x740C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, - {0x1002, 0x740F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, - {0x1002, 0x7410, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, - - /* CYAN_SKILLFISH */ - {0x1002, 0x13DB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x13F9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x13FA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x13FB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x13FC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x13FE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - {0x1002, 0x143F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, - - /* BEIGE_GOBY */ - {0x1002, 0x7420, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - {0x1002, 0x7421, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - {0x1002, 0x7422, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - {0x1002, 0x7423, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - {0x1002, 0x7424, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - {0x1002, 0x743F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, - - { PCI_DEVICE(0x1002, PCI_ANY_ID), - .class = PCI_CLASS_DISPLAY_VGA << 8, - .class_mask = 0xffffff, - .driver_data = CHIP_IP_DISCOVERY }, - - { PCI_DEVICE(0x1002, PCI_ANY_ID), - .class = PCI_CLASS_DISPLAY_OTHER << 8, - .class_mask = 0xffffff, - .driver_data = CHIP_IP_DISCOVERY }, - - { PCI_DEVICE(0x1002, PCI_ANY_ID), - .class = PCI_CLASS_ACCELERATOR_PROCESSING << 8, - .class_mask = 0xffffff, - .driver_data = CHIP_IP_DISCOVERY }, - - {0, 0, 0} -}; +/* Original PCI tables and policies shared with the native admission query. */ +#include "amdgpu_pci_match_core.h" MODULE_DEVICE_TABLE(pci, pciidlist); -static const struct amdgpu_asic_type_quirk asic_type_quirks[] = { - /* differentiate between P10 and P11 asics with the same DID */ - {0x67FF, 0xE3, CHIP_POLARIS10}, - {0x67FF, 0xE7, CHIP_POLARIS10}, - {0x67FF, 0xF3, CHIP_POLARIS10}, - {0x67FF, 0xF7, CHIP_POLARIS10}, -}; - static const struct drm_driver amdgpu_kms_driver; static void amdgpu_get_secondary_funcs(struct amdgpu_device *adev) @@ -2295,18 +1211,7 @@ static void amdgpu_init_debug_options(struct amdgpu_device *adev) static unsigned long amdgpu_fix_asic_type(struct pci_dev *pdev, unsigned long flags) { - int i; - - for (i = 0; i < ARRAY_SIZE(asic_type_quirks); i++) { - if (pdev->device == asic_type_quirks[i].device && - pdev->revision == asic_type_quirks[i].revision) { - flags &= ~AMD_ASIC_MASK; - flags |= asic_type_quirks[i].type; - break; - } - } - - return flags; + return amdgpu_pci_fix_asic_type(pdev->device, pdev->revision, flags); } static bool amdgpu_support_enabled(struct device *dev, @@ -2317,45 +1222,22 @@ static bool amdgpu_support_enabled(struct device *dev, int module_param = -1; bool radeon_support_built = IS_ENABLED(CONFIG_DRM_RADEON); bool amdgpu_support_built = false; - bool support_by_default = false; - switch (family) { - case CHIP_TAHITI: - case CHIP_PITCAIRN: - case CHIP_VERDE: - case CHIP_OLAND: - case CHIP_HAINAN: - gen = "SI"; - param = "si_support"; - module_param = amdgpu_si_support; - amdgpu_support_built = IS_ENABLED(CONFIG_DRM_AMDGPU_SI); - support_by_default = true; - break; - - case CHIP_BONAIRE: - case CHIP_HAWAII: - case CHIP_KAVERI: - case CHIP_KABINI: - case CHIP_MULLINS: - gen = "CIK"; - param = "cik_support"; - module_param = amdgpu_cik_support; - amdgpu_support_built = IS_ENABLED(CONFIG_DRM_AMDGPU_CIK); - support_by_default = true; - break; - - default: - /* All other chips are supported by amdgpu only */ + struct amdgpu_pci_support_policy policy; + if (!amdgpu_pci_support_policy(family, IS_ENABLED(CONFIG_DRM_AMDGPU_SI), + IS_ENABLED(CONFIG_DRM_AMDGPU_CIK), amdgpu_si_support, + amdgpu_cik_support, &policy)) return true; - } - + gen = policy.gen; + param = policy.param; + module_param = policy.module_param; + amdgpu_support_built = policy.support_built; if (!amdgpu_support_built) { dev_info(dev, "amdgpu built without %s support\n", gen); return false; } - if ((module_param == -1 && (support_by_default || !radeon_support_built)) || - module_param == 1) { + if (amdgpu_pci_support_allowed(&policy, radeon_support_built)) { if (radeon_support_built) dev_info(dev, "%s support provided by amdgpu.\n" "Use radeon.%s=1 amdgpu.%s=0 to override.\n", @@ -2399,7 +1281,7 @@ static int amdgpu_pci_probe(struct pci_dev *pdev, amdgpu_device_asic_has_dc_support(pdev, flags & AMD_ASIC_MASK)) supports_atomic = true; - if ((flags & AMD_EXP_HW_SUPPORT) && !amdgpu_exp_hw_support) { + if (!amdgpu_pci_experimental_allowed(flags, amdgpu_exp_hw_support)) { dev_info(&pdev->dev, "This hardware requires experimental hardware support.\n" "See modparam exp_hw_support\n"); return -ENODEV; diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip.h index 1d0df6d939..7d50d8aa78 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip.h @@ -25,64 +25,11 @@ #define __AMDGPU_IP_H__ #include "amd_shared.h" +#include "amdgpu_ip_limits.h" struct amdgpu_device; -/* Define the HW IP blocks will be used in driver , add more if necessary */ -enum amd_hw_ip_block_type { - GC_HWIP = 1, - HDP_HWIP, - SDMA0_HWIP, - SDMA1_HWIP, - SDMA2_HWIP, - SDMA3_HWIP, - SDMA4_HWIP, - SDMA5_HWIP, - SDMA6_HWIP, - SDMA7_HWIP, - LSDMA_HWIP, - MMHUB_HWIP, - ATHUB_HWIP, - NBIO_HWIP, - MP0_HWIP, - MP1_HWIP, - UVD_HWIP, - VCN_HWIP = UVD_HWIP, - JPEG_HWIP = VCN_HWIP, - VCN1_HWIP, - VCE_HWIP, - VPE_HWIP, - DF_HWIP, - DCE_HWIP, - OSSSYS_HWIP, - SMUIO_HWIP, - PWR_HWIP, - NBIF_HWIP, - THM_HWIP, - CLK_HWIP, - UMC_HWIP, - RSMU_HWIP, - XGMI_HWIP, - DCI_HWIP, - PCIE_HWIP, - ISP_HWIP, - ATU_HWIP, - AIGC_HWIP, - MAX_HWIP -}; - -#define HWIP_MAX_INSTANCE 48 - -#define HW_ID_MAX 300 -#define IP_VERSION_FULL(mj, mn, rv, var, srev) \ - (((mj) << 24) | ((mn) << 16) | ((rv) << 8) | ((var) << 4) | (srev)) -#define IP_VERSION(mj, mn, rv) IP_VERSION_FULL(mj, mn, rv, 0, 0) -#define IP_VERSION_MAJ(ver) ((ver) >> 24) -#define IP_VERSION_MIN(ver) (((ver) >> 16) & 0xFF) -#define IP_VERSION_REV(ver) (((ver) >> 8) & 0xFF) -#define IP_VERSION_VARIANT(ver) (((ver) >> 4) & 0xF) -#define IP_VERSION_SUBREV(ver) ((ver) & 0xF) -#define IP_VERSION_MAJ_MIN_REV(ver) ((ver) >> 8) +#include "amdgpu_ip_types.h" struct amdgpu_ip_map_info { /* Map of logical to actual dev instances/mask */ diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h new file mode 100644 index 0000000000..1f2072660c --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_instance_limits.h @@ -0,0 +1,29 @@ +/* + * Copyright 2025 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_IP_INSTANCE_LIMITS_H +#define AMDGPU_IP_INSTANCE_LIMITS_H +#define AMDGPU_MAX_VCN_INSTANCES 4 +#define AMDGPU_MAX_SDMA_INSTANCES 16 +#define AMDGPU_MAX_VPE_INSTANCES 2 +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_limits.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_limits.h new file mode 100644 index 0000000000..3dd19bbad8 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_limits.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2025 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_IP_LIMITS_H +#define AMDGPU_IP_LIMITS_H + +/* Original driver array bounds, shared by discovery and its consumers. */ +#define HWIP_MAX_INSTANCE 48 +#define HW_ID_MAX 300 + +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_types.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_types.h new file mode 100644 index 0000000000..d7dcffe79d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_ip_types.h @@ -0,0 +1,80 @@ +/* + * Copyright 2025 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_IP_TYPES_H +#define AMDGPU_IP_TYPES_H + +/* Define the HW IP blocks will be used in driver , add more if necessary */ +enum amd_hw_ip_block_type { + GC_HWIP = 1, + HDP_HWIP, + SDMA0_HWIP, + SDMA1_HWIP, + SDMA2_HWIP, + SDMA3_HWIP, + SDMA4_HWIP, + SDMA5_HWIP, + SDMA6_HWIP, + SDMA7_HWIP, + LSDMA_HWIP, + MMHUB_HWIP, + ATHUB_HWIP, + NBIO_HWIP, + MP0_HWIP, + MP1_HWIP, + UVD_HWIP, + VCN_HWIP = UVD_HWIP, + JPEG_HWIP = VCN_HWIP, + VCN1_HWIP, + VCE_HWIP, + VPE_HWIP, + DF_HWIP, + DCE_HWIP, + OSSSYS_HWIP, + SMUIO_HWIP, + PWR_HWIP, + NBIF_HWIP, + THM_HWIP, + CLK_HWIP, + UMC_HWIP, + RSMU_HWIP, + XGMI_HWIP, + DCI_HWIP, + PCIE_HWIP, + ISP_HWIP, + ATU_HWIP, + AIGC_HWIP, + MAX_HWIP +}; + +#define IP_VERSION_FULL(mj, mn, rv, var, srev) \ + (((mj) << 24) | ((mn) << 16) | ((rv) << 8) | ((var) << 4) | (srev)) +#define IP_VERSION(mj, mn, rv) IP_VERSION_FULL(mj, mn, rv, 0, 0) +#define IP_VERSION_MAJ(ver) ((ver) >> 24) +#define IP_VERSION_MIN(ver) (((ver) >> 16) & 0xFF) +#define IP_VERSION_REV(ver) (((ver) >> 8) & 0xFF) +#define IP_VERSION_VARIANT(ver) (((ver) >> 4) & 0xF) +#define IP_VERSION_SUBREV(ver) ((ver) & 0xF) +#define IP_VERSION_MAJ_MIN_REV(ver) ((ver) >> 8) + +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_mm_access_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_mm_access_core.h new file mode 100644 index 0000000000..04d28e8649 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_mm_access_core.h @@ -0,0 +1,73 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2008 Advanced Micro Devices, Inc. + * Copyright 2008 Red Hat Inc. + * Copyright 2009 Jerome Glisse. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Dave Airlie + * Alex Deucher + * Jerome Glisse + */ + +#ifndef AMDGPU_MM_ACCESS_CORE_H +#define AMDGPU_MM_ACCESS_CORE_H +#ifdef __KERNEL__ +#include +#else +#include +#include +#include +#endif +/* Callers include the original BIF register definitions. No default hardware + * access, lock, lifetime, allocator or synthetic device context is supplied. + * Original Linux wrapper retains drm_dev_enter and IRQ-safe MM-index locking; + * the native owner must provide genuine equivalent exclusion before entry. + */ +struct amdgpu_mm_access_ops { + uint32_t (*read32)(void *, uint32_t); + void (*write32)(void *, uint32_t, uint32_t); +}; +/* Preserve the original signed loff_t/unsigned last comparison and conversion; + * the native entry preflights the complete nonnegative signed range. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +static inline void amdgpu_mm_access_core(const struct amdgpu_mm_access_ops *ops, + void *context, int64_t pos, uint32_t *data, size_t size, bool write) +{ + uint32_t hi = ~0, tmp = 0; + uint64_t last; + for (last = pos + size; pos < last; pos += 4) { + tmp = pos >> 31; + + ops->write32(context, mmMM_INDEX, ((uint32_t)pos) | 0x80000000); + if (tmp != hi) { + ops->write32(context, mmMM_INDEX_HI, tmp); + hi = tmp; + } + if (write) + ops->write32(context, mmMM_DATA, *data++); + else + *data++ = ops->read32(context, mmMM_DATA); + } + +} +#pragma GCC diagnostic pop +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_pci_match_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_pci_match_core.h new file mode 100644 index 0000000000..141ced9ce9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_pci_match_core.h @@ -0,0 +1,1210 @@ +/* + * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef AMDGPU_PCI_MATCH_CORE_H +#define AMDGPU_PCI_MATCH_CORE_H +#ifdef __KERNEL__ +#include +#else +#include +#include +#include +/* Original pure PCI declarations, with their standard native scalar bindings. + * Tables are evaluated natively, never serialized as a Linux struct ABI. */ +typedef uint16_t u16; +typedef uint32_t __u32; +typedef unsigned long kernel_ulong_t; +#include "../../common/linux/include/linux/device-id/pci.h" +#include "../../common/linux/include/linux/pci_ids.h" +/* Exact original include/linux/pci.h PCI_DEVICE initializer. */ +#define PCI_DEVICE(vend,dev) \ + .vendor = (vend), .device = (dev), \ + .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID +#endif +#include "../../common/linux/include/drm/amd_asic_type.h" +#include "../include/amd_chip_flags.h" +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define AMDGPU_PCI_UNDEF_ARRAY_SIZE +#endif + +/* Exact retained original declarations and row order. */ +/* These devices are not supported by amdgpu. + * They are supported by the mach64, r128, radeon drivers + */ +static const u16 amdgpu_unsupported_pciidlist[] = { + /* mach64 */ + 0x4354, + 0x4358, + 0x4554, + 0x4742, + 0x4744, + 0x4749, + 0x474C, + 0x474D, + 0x474E, + 0x474F, + 0x4750, + 0x4751, + 0x4752, + 0x4753, + 0x4754, + 0x4755, + 0x4756, + 0x4757, + 0x4758, + 0x4759, + 0x475A, + 0x4C42, + 0x4C44, + 0x4C47, + 0x4C49, + 0x4C4D, + 0x4C4E, + 0x4C50, + 0x4C51, + 0x4C52, + 0x4C53, + 0x5654, + 0x5655, + 0x5656, + /* r128 */ + 0x4c45, + 0x4c46, + 0x4d46, + 0x4d4c, + 0x5041, + 0x5042, + 0x5043, + 0x5044, + 0x5045, + 0x5046, + 0x5047, + 0x5048, + 0x5049, + 0x504A, + 0x504B, + 0x504C, + 0x504D, + 0x504E, + 0x504F, + 0x5050, + 0x5051, + 0x5052, + 0x5053, + 0x5054, + 0x5055, + 0x5056, + 0x5057, + 0x5058, + 0x5245, + 0x5246, + 0x5247, + 0x524b, + 0x524c, + 0x534d, + 0x5446, + 0x544C, + 0x5452, + /* radeon */ + 0x3150, + 0x3151, + 0x3152, + 0x3154, + 0x3155, + 0x3E50, + 0x3E54, + 0x4136, + 0x4137, + 0x4144, + 0x4145, + 0x4146, + 0x4147, + 0x4148, + 0x4149, + 0x414A, + 0x414B, + 0x4150, + 0x4151, + 0x4152, + 0x4153, + 0x4154, + 0x4155, + 0x4156, + 0x4237, + 0x4242, + 0x4336, + 0x4337, + 0x4437, + 0x4966, + 0x4967, + 0x4A48, + 0x4A49, + 0x4A4A, + 0x4A4B, + 0x4A4C, + 0x4A4D, + 0x4A4E, + 0x4A4F, + 0x4A50, + 0x4A54, + 0x4B48, + 0x4B49, + 0x4B4A, + 0x4B4B, + 0x4B4C, + 0x4C57, + 0x4C58, + 0x4C59, + 0x4C5A, + 0x4C64, + 0x4C66, + 0x4C67, + 0x4E44, + 0x4E45, + 0x4E46, + 0x4E47, + 0x4E48, + 0x4E49, + 0x4E4A, + 0x4E4B, + 0x4E50, + 0x4E51, + 0x4E52, + 0x4E53, + 0x4E54, + 0x4E56, + 0x5144, + 0x5145, + 0x5146, + 0x5147, + 0x5148, + 0x514C, + 0x514D, + 0x5157, + 0x5158, + 0x5159, + 0x515A, + 0x515E, + 0x5460, + 0x5462, + 0x5464, + 0x5548, + 0x5549, + 0x554A, + 0x554B, + 0x554C, + 0x554D, + 0x554E, + 0x554F, + 0x5550, + 0x5551, + 0x5552, + 0x5554, + 0x564A, + 0x564B, + 0x564F, + 0x5652, + 0x5653, + 0x5657, + 0x5834, + 0x5835, + 0x5954, + 0x5955, + 0x5974, + 0x5975, + 0x5960, + 0x5961, + 0x5962, + 0x5964, + 0x5965, + 0x5969, + 0x5a41, + 0x5a42, + 0x5a61, + 0x5a62, + 0x5b60, + 0x5b62, + 0x5b63, + 0x5b64, + 0x5b65, + 0x5c61, + 0x5c63, + 0x5d48, + 0x5d49, + 0x5d4a, + 0x5d4c, + 0x5d4d, + 0x5d4e, + 0x5d4f, + 0x5d50, + 0x5d52, + 0x5d57, + 0x5e48, + 0x5e4a, + 0x5e4b, + 0x5e4c, + 0x5e4d, + 0x5e4f, + 0x6700, + 0x6701, + 0x6702, + 0x6703, + 0x6704, + 0x6705, + 0x6706, + 0x6707, + 0x6708, + 0x6709, + 0x6718, + 0x6719, + 0x671c, + 0x671d, + 0x671f, + 0x6720, + 0x6721, + 0x6722, + 0x6723, + 0x6724, + 0x6725, + 0x6726, + 0x6727, + 0x6728, + 0x6729, + 0x6738, + 0x6739, + 0x673e, + 0x6740, + 0x6741, + 0x6742, + 0x6743, + 0x6744, + 0x6745, + 0x6746, + 0x6747, + 0x6748, + 0x6749, + 0x674A, + 0x6750, + 0x6751, + 0x6758, + 0x6759, + 0x675B, + 0x675D, + 0x675F, + 0x6760, + 0x6761, + 0x6762, + 0x6763, + 0x6764, + 0x6765, + 0x6766, + 0x6767, + 0x6768, + 0x6770, + 0x6771, + 0x6772, + 0x6778, + 0x6779, + 0x677B, + 0x6840, + 0x6841, + 0x6842, + 0x6843, + 0x6849, + 0x684C, + 0x6850, + 0x6858, + 0x6859, + 0x6880, + 0x6888, + 0x6889, + 0x688A, + 0x688C, + 0x688D, + 0x6898, + 0x6899, + 0x689b, + 0x689c, + 0x689d, + 0x689e, + 0x68a0, + 0x68a1, + 0x68a8, + 0x68a9, + 0x68b0, + 0x68b8, + 0x68b9, + 0x68ba, + 0x68be, + 0x68bf, + 0x68c0, + 0x68c1, + 0x68c7, + 0x68c8, + 0x68c9, + 0x68d8, + 0x68d9, + 0x68da, + 0x68de, + 0x68e0, + 0x68e1, + 0x68e4, + 0x68e5, + 0x68e8, + 0x68e9, + 0x68f1, + 0x68f2, + 0x68f8, + 0x68f9, + 0x68fa, + 0x68fe, + 0x7100, + 0x7101, + 0x7102, + 0x7103, + 0x7104, + 0x7105, + 0x7106, + 0x7108, + 0x7109, + 0x710A, + 0x710B, + 0x710C, + 0x710E, + 0x710F, + 0x7140, + 0x7141, + 0x7142, + 0x7143, + 0x7144, + 0x7145, + 0x7146, + 0x7147, + 0x7149, + 0x714A, + 0x714B, + 0x714C, + 0x714D, + 0x714E, + 0x714F, + 0x7151, + 0x7152, + 0x7153, + 0x715E, + 0x715F, + 0x7180, + 0x7181, + 0x7183, + 0x7186, + 0x7187, + 0x7188, + 0x718A, + 0x718B, + 0x718C, + 0x718D, + 0x718F, + 0x7193, + 0x7196, + 0x719B, + 0x719F, + 0x71C0, + 0x71C1, + 0x71C2, + 0x71C3, + 0x71C4, + 0x71C5, + 0x71C6, + 0x71C7, + 0x71CD, + 0x71CE, + 0x71D2, + 0x71D4, + 0x71D5, + 0x71D6, + 0x71DA, + 0x71DE, + 0x7200, + 0x7210, + 0x7211, + 0x7240, + 0x7243, + 0x7244, + 0x7245, + 0x7246, + 0x7247, + 0x7248, + 0x7249, + 0x724A, + 0x724B, + 0x724C, + 0x724D, + 0x724E, + 0x724F, + 0x7280, + 0x7281, + 0x7283, + 0x7284, + 0x7287, + 0x7288, + 0x7289, + 0x728B, + 0x728C, + 0x7290, + 0x7291, + 0x7293, + 0x7297, + 0x7834, + 0x7835, + 0x791e, + 0x791f, + 0x793f, + 0x7941, + 0x7942, + 0x796c, + 0x796d, + 0x796e, + 0x796f, + 0x9400, + 0x9401, + 0x9402, + 0x9403, + 0x9405, + 0x940A, + 0x940B, + 0x940F, + 0x94A0, + 0x94A1, + 0x94A3, + 0x94B1, + 0x94B3, + 0x94B4, + 0x94B5, + 0x94B9, + 0x9440, + 0x9441, + 0x9442, + 0x9443, + 0x9444, + 0x9446, + 0x944A, + 0x944B, + 0x944C, + 0x944E, + 0x9450, + 0x9452, + 0x9456, + 0x945A, + 0x945B, + 0x945E, + 0x9460, + 0x9462, + 0x946A, + 0x946B, + 0x947A, + 0x947B, + 0x9480, + 0x9487, + 0x9488, + 0x9489, + 0x948A, + 0x948F, + 0x9490, + 0x9491, + 0x9495, + 0x9498, + 0x949C, + 0x949E, + 0x949F, + 0x94C0, + 0x94C1, + 0x94C3, + 0x94C4, + 0x94C5, + 0x94C6, + 0x94C7, + 0x94C8, + 0x94C9, + 0x94CB, + 0x94CC, + 0x94CD, + 0x9500, + 0x9501, + 0x9504, + 0x9505, + 0x9506, + 0x9507, + 0x9508, + 0x9509, + 0x950F, + 0x9511, + 0x9515, + 0x9517, + 0x9519, + 0x9540, + 0x9541, + 0x9542, + 0x954E, + 0x954F, + 0x9552, + 0x9553, + 0x9555, + 0x9557, + 0x955f, + 0x9580, + 0x9581, + 0x9583, + 0x9586, + 0x9587, + 0x9588, + 0x9589, + 0x958A, + 0x958B, + 0x958C, + 0x958D, + 0x958E, + 0x958F, + 0x9590, + 0x9591, + 0x9593, + 0x9595, + 0x9596, + 0x9597, + 0x9598, + 0x9599, + 0x959B, + 0x95C0, + 0x95C2, + 0x95C4, + 0x95C5, + 0x95C6, + 0x95C7, + 0x95C9, + 0x95CC, + 0x95CD, + 0x95CE, + 0x95CF, + 0x9610, + 0x9611, + 0x9612, + 0x9613, + 0x9614, + 0x9615, + 0x9616, + 0x9640, + 0x9641, + 0x9642, + 0x9643, + 0x9644, + 0x9645, + 0x9647, + 0x9648, + 0x9649, + 0x964a, + 0x964b, + 0x964c, + 0x964e, + 0x964f, + 0x9710, + 0x9711, + 0x9712, + 0x9713, + 0x9714, + 0x9715, + 0x9802, + 0x9803, + 0x9804, + 0x9805, + 0x9806, + 0x9807, + 0x9808, + 0x9809, + 0x980A, + 0x9900, + 0x9901, + 0x9903, + 0x9904, + 0x9905, + 0x9906, + 0x9907, + 0x9908, + 0x9909, + 0x990A, + 0x990B, + 0x990C, + 0x990D, + 0x990E, + 0x990F, + 0x9910, + 0x9913, + 0x9917, + 0x9918, + 0x9919, + 0x9990, + 0x9991, + 0x9992, + 0x9993, + 0x9994, + 0x9995, + 0x9996, + 0x9997, + 0x9998, + 0x9999, + 0x999A, + 0x999B, + 0x999C, + 0x999D, + 0x99A0, + 0x99A2, + 0x99A4, + /* radeon secondary ids */ + 0x3171, + 0x3e70, + 0x4164, + 0x4165, + 0x4166, + 0x4168, + 0x4170, + 0x4171, + 0x4172, + 0x4173, + 0x496e, + 0x4a69, + 0x4a6a, + 0x4a6b, + 0x4a70, + 0x4a74, + 0x4b69, + 0x4b6b, + 0x4b6c, + 0x4c6e, + 0x4e64, + 0x4e65, + 0x4e66, + 0x4e67, + 0x4e68, + 0x4e69, + 0x4e6a, + 0x4e71, + 0x4f73, + 0x5569, + 0x556b, + 0x556d, + 0x556f, + 0x5571, + 0x5854, + 0x5874, + 0x5940, + 0x5941, + 0x5b70, + 0x5b72, + 0x5b73, + 0x5b74, + 0x5b75, + 0x5d44, + 0x5d45, + 0x5d6d, + 0x5d6f, + 0x5d72, + 0x5d77, + 0x5e6b, + 0x5e6d, + 0x7120, + 0x7124, + 0x7129, + 0x712e, + 0x712f, + 0x7162, + 0x7163, + 0x7166, + 0x7167, + 0x7172, + 0x7173, + 0x71a0, + 0x71a1, + 0x71a3, + 0x71a7, + 0x71bb, + 0x71e0, + 0x71e1, + 0x71e2, + 0x71e6, + 0x71e7, + 0x71f2, + 0x7269, + 0x726b, + 0x726e, + 0x72a0, + 0x72a8, + 0x72b1, + 0x72b3, + 0x793f, +}; + +static const struct pci_device_id pciidlist[] = { + {0x1002, 0x6780, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6784, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6788, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x678A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6790, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6791, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6792, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6798, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6799, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x679A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x679B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x679E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x679F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TAHITI}, + {0x1002, 0x6800, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, + {0x1002, 0x6801, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, + {0x1002, 0x6802, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN|AMD_IS_MOBILITY}, + {0x1002, 0x6806, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6808, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6809, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6810, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6811, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6816, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6817, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6818, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6819, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_PITCAIRN}, + {0x1002, 0x6600, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6601, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6602, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6603, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6604, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6605, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6606, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6607, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6608, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, + {0x1002, 0x6610, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, + {0x1002, 0x6611, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, + {0x1002, 0x6613, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, + {0x1002, 0x6617, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6620, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6621, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6623, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND|AMD_IS_MOBILITY}, + {0x1002, 0x6631, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_OLAND}, + {0x1002, 0x6820, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6821, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6822, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6823, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6824, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6825, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6826, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6827, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6828, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x6829, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x682A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x682B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x682C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x682D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x682F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6830, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6831, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE|AMD_IS_MOBILITY}, + {0x1002, 0x6835, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x6837, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x6838, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x6839, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x683B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x683D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x683F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VERDE}, + {0x1002, 0x6660, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + {0x1002, 0x6663, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + {0x1002, 0x6664, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + {0x1002, 0x6665, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + {0x1002, 0x6667, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + {0x1002, 0x666F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAINAN|AMD_IS_MOBILITY}, + /* Kaveri */ + {0x1002, 0x1304, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x1305, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1306, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x1307, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1309, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x130F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1310, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1311, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1312, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1313, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1315, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1316, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x1317, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x1318, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x131B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x131C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + {0x1002, 0x131D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KAVERI|AMD_IS_APU}, + /* Bonaire */ + {0x1002, 0x6640, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, + {0x1002, 0x6641, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, + {0x1002, 0x6646, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, + {0x1002, 0x6647, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE|AMD_IS_MOBILITY}, + {0x1002, 0x6649, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x6650, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x6651, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x6658, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x665c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x665d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + {0x1002, 0x665f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BONAIRE}, + /* Hawaii */ + {0x1002, 0x67A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67A8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67A9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67AA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67B0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67B1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67B8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67B9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67BA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + {0x1002, 0x67BE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_HAWAII}, + /* Kabini */ + {0x1002, 0x9830, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9831, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x9832, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9833, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x9834, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9835, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x9836, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9837, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x9838, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9839, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x983a, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x983b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x983c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x983d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x983e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + {0x1002, 0x983f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_KABINI|AMD_IS_APU}, + /* mullins */ + {0x1002, 0x9850, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9851, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9852, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9853, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9854, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9855, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9856, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9857, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9858, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x9859, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + {0x1002, 0x985F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_MULLINS|AMD_IS_MOBILITY|AMD_IS_APU}, + /* topaz */ + {0x1002, 0x6900, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, + {0x1002, 0x6901, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, + {0x1002, 0x6902, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, + {0x1002, 0x6903, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, + {0x1002, 0x6907, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TOPAZ}, + /* tonga */ + {0x1002, 0x6920, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6921, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6928, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6929, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x692B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x692F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6930, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6938, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + {0x1002, 0x6939, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_TONGA}, + /* fiji */ + {0x1002, 0x7300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_FIJI}, + {0x1002, 0x730F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_FIJI}, + /* carrizo */ + {0x1002, 0x9870, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, + {0x1002, 0x9874, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, + {0x1002, 0x9875, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, + {0x1002, 0x9876, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, + {0x1002, 0x9877, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CARRIZO|AMD_IS_APU}, + /* stoney */ + {0x1002, 0x98E4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_STONEY|AMD_IS_APU}, + /* Polaris11 */ + {0x1002, 0x67E0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67E3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67E8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67EB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67EF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67FF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67E1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67E7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + {0x1002, 0x67E9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS11}, + /* Polaris10 */ + {0x1002, 0x67C0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67D0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67DF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67C9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67CA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67CC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x67CF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + {0x1002, 0x6FDF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS10}, + /* Polaris12 */ + {0x1002, 0x6980, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6986, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6987, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6995, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x6997, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + {0x1002, 0x699F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_POLARIS12}, + /* VEGAM */ + {0x1002, 0x694C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, + {0x1002, 0x694E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, + {0x1002, 0x694F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGAM}, + /* Vega 10 */ + {0x1002, 0x6860, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6861, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6862, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6863, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6864, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6867, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6868, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x6869, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686a, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686d, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x686f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + {0x1002, 0x687f, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA10}, + /* Vega 12 */ + {0x1002, 0x69A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, + {0x1002, 0x69A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, + {0x1002, 0x69A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, + {0x1002, 0x69A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, + {0x1002, 0x69AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA12}, + /* Vega 20 */ + {0x1002, 0x66A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66A4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66A7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + {0x1002, 0x66AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_VEGA20}, + /* Raven */ + {0x1002, 0x15dd, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RAVEN|AMD_IS_APU}, + {0x1002, 0x15d8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RAVEN|AMD_IS_APU}, + /* Arcturus */ + {0x1002, 0x738C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, + {0x1002, 0x7388, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, + {0x1002, 0x738E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, + {0x1002, 0x7390, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ARCTURUS}, + /* Navi10 */ + {0x1002, 0x7310, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x7312, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x7318, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x7319, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x731A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x731B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x731E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + {0x1002, 0x731F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI10}, + /* Navi14 */ + {0x1002, 0x7340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, + {0x1002, 0x7341, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, + {0x1002, 0x7347, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, + {0x1002, 0x734F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI14}, + + /* Renoir */ + {0x1002, 0x15E7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, + {0x1002, 0x1636, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, + {0x1002, 0x1638, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, + {0x1002, 0x164C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_RENOIR|AMD_IS_APU}, + + /* Navi12 */ + {0x1002, 0x7360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI12}, + {0x1002, 0x7362, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVI12}, + + /* Sienna_Cichlid */ + {0x1002, 0x73A0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A5, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73A9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73AB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73AC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73AD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73AE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73AF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + {0x1002, 0x73BF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_SIENNA_CICHLID}, + + /* Yellow Carp */ + {0x1002, 0x164D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_YELLOW_CARP|AMD_IS_APU}, + {0x1002, 0x1681, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_YELLOW_CARP|AMD_IS_APU}, + + /* Navy_Flounder */ + {0x1002, 0x73C0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73C1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73C3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + {0x1002, 0x73DF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_NAVY_FLOUNDER}, + + /* DIMGREY_CAVEFISH */ + {0x1002, 0x73E0, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73E1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73E2, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73E3, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73E8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73E9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73EA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73EB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73EC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73ED, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73EF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + {0x1002, 0x73FF, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_DIMGREY_CAVEFISH}, + + /* Aldebaran */ + {0x1002, 0x7408, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, + {0x1002, 0x740C, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, + {0x1002, 0x740F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, + {0x1002, 0x7410, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_ALDEBARAN}, + + /* CYAN_SKILLFISH */ + {0x1002, 0x13DB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x13F9, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x13FA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x13FB, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x13FC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x13FE, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + {0x1002, 0x143F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_CYAN_SKILLFISH|AMD_IS_APU}, + + /* BEIGE_GOBY */ + {0x1002, 0x7420, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + {0x1002, 0x7421, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + {0x1002, 0x7422, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + {0x1002, 0x7423, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + {0x1002, 0x7424, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + {0x1002, 0x743F, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CHIP_BEIGE_GOBY}, + + { PCI_DEVICE(0x1002, PCI_ANY_ID), + .class = PCI_CLASS_DISPLAY_VGA << 8, + .class_mask = 0xffffff, + .driver_data = CHIP_IP_DISCOVERY }, + + { PCI_DEVICE(0x1002, PCI_ANY_ID), + .class = PCI_CLASS_DISPLAY_OTHER << 8, + .class_mask = 0xffffff, + .driver_data = CHIP_IP_DISCOVERY }, + + { PCI_DEVICE(0x1002, PCI_ANY_ID), + .class = PCI_CLASS_ACCELERATOR_PROCESSING << 8, + .class_mask = 0xffffff, + .driver_data = CHIP_IP_DISCOVERY }, + + {0, 0, 0} +}; + +static const struct amdgpu_asic_type_quirk asic_type_quirks[] = { + /* differentiate between P10 and P11 asics with the same DID */ + {0x67FF, 0xE3, CHIP_POLARIS10}, + {0x67FF, 0xE7, CHIP_POLARIS10}, + {0x67FF, 0xF3, CHIP_POLARIS10}, + {0x67FF, 0xF7, CHIP_POLARIS10}, +}; + +static unsigned long amdgpu_pci_fix_asic_type(unsigned short device, unsigned char revision, unsigned long flags) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(asic_type_quirks); i++) { + if (device == asic_type_quirks[i].device && + revision == asic_type_quirks[i].revision) { + flags &= ~AMD_ASIC_MASK; + flags |= asic_type_quirks[i].type; + break; + } + } + + return flags; +} + +/* Exact original pre-allocation experimental predicate. */ +static inline bool amdgpu_pci_experimental_allowed(unsigned long flags, int option) +{ + return !((flags & AMD_EXP_HW_SUPPORT) && !option); +} + +/* Original amdgpu_support_enabled generation decision, without logging or + * runtime defaults. Actual build/module-policy inputs belong to the caller. */ +struct amdgpu_pci_support_policy { + const char *gen, *param; + int module_param; + bool support_built; + bool support_by_default; +}; +static inline bool amdgpu_pci_support_policy(enum amd_asic_type family, + bool si_built, bool cik_built, int si_support, int cik_support, + struct amdgpu_pci_support_policy *policy) +{ + switch (family) { + case CHIP_TAHITI: + case CHIP_PITCAIRN: + case CHIP_VERDE: + case CHIP_OLAND: + case CHIP_HAINAN: + *policy = (struct amdgpu_pci_support_policy){ + "SI", "si_support", si_support, si_built, true}; + return true; + case CHIP_BONAIRE: + case CHIP_HAWAII: + case CHIP_KAVERI: + case CHIP_KABINI: + case CHIP_MULLINS: + *policy = (struct amdgpu_pci_support_policy){ + "CIK", "cik_support", cik_support, cik_built, true}; + return true; + default: + return false; + } +} +static inline bool amdgpu_pci_support_allowed(const struct amdgpu_pci_support_policy *policy, + bool radeon_support_built) +{ + return policy->support_built && + ((policy->module_param == -1 && + (policy->support_by_default || !radeon_support_built)) || + policy->module_param == 1); +} +#ifdef AMDGPU_PCI_UNDEF_ARRAY_SIZE +#undef ARRAY_SIZE +#undef AMDGPU_PCI_UNDEF_ARRAY_SIZE +#endif +#ifndef __KERNEL__ +#undef PCI_DEVICE +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_sdma.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_sdma.h index 2bf3656097..9e4cf07a53 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_sdma.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_sdma.h @@ -26,7 +26,7 @@ #include "amdgpu_ras.h" /* max number of IP instances */ -#define AMDGPU_MAX_SDMA_INSTANCES 16 +#include "amdgpu_ip_instance_limits.h" enum amdgpu_sdma_irq { AMDGPU_SDMA_IRQ_INSTANCE0 = 0, diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vcn.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vcn.h index 82624b44e6..b0b643a147 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vcn.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vcn.h @@ -32,7 +32,7 @@ #define AMDGPU_VCN_FIRMWARE_OFFSET 256 #define AMDGPU_VCN_MAX_ENC_RINGS 3 -#define AMDGPU_MAX_VCN_INSTANCES 4 +#include "amdgpu_ip_instance_limits.h" #define AMDGPU_MAX_VCN_ENC_RINGS (AMDGPU_VCN_MAX_ENC_RINGS * AMDGPU_MAX_VCN_INSTANCES) #define AMDGPU_VCN_HARVEST_VCN0 (1 << 0) diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.c b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.c index 9e8f7d2b89..e07a553ed0 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.c +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.c @@ -902,25 +902,11 @@ static u32 amdgpu_virt_init_detect_asic(struct amdgpu_device *adev) { uint32_t reg; - switch (adev->asic_type) { - case CHIP_TONGA: - case CHIP_FIJI: - reg = RREG32(mmBIF_IOV_FUNC_IDENTIFIER); - break; - case CHIP_VEGA10: - case CHIP_VEGA20: - case CHIP_NAVI10: - case CHIP_NAVI12: - case CHIP_SIENNA_CICHLID: - case CHIP_ARCTURUS: - case CHIP_ALDEBARAN: - case CHIP_IP_DISCOVERY: - reg = RREG32(mmRCC_IOV_FUNC_IDENTIFIER); - break; - default: /* other chip doesn't support SRIOV */ - reg = 0; - break; - } + uint32_t identifier; + if (amdgpu_virt_bootstrap_iov_register(adev->asic_type, &identifier)) + reg = RREG32(identifier); + else + reg = 0; if (reg & 1) adev->virt.caps |= AMDGPU_SRIOV_CAPS_IS_VF; diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.h index d8500c3e48..4819680b32 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt.h @@ -56,10 +56,7 @@ #define AMDGPU_RLCG_VFI_STAT__INV_ADDR 0x3 #define AMDGPU_RLCG_VFI_STAT__ERR 0xFF -/* all asic after AI use this offset */ -#define mmRCC_IOV_FUNC_IDENTIFIER 0xDE5 -/* tonga/fiji use this offset */ -#define mmBIF_IOV_FUNC_IDENTIFIER 0x1503 +#include "amdgpu_virt_bootstrap_core.h" #define AMDGPU_VF2PF_UPDATE_MAX_RETRY_LIMIT 2 diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h new file mode 100644 index 0000000000..42cfe398b9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_virt_bootstrap_core.h @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef AMDGPU_VIRT_BOOTSTRAP_CORE_H +#define AMDGPU_VIRT_BOOTSTRAP_CORE_H +#ifdef __KERNEL__ +#include +#include +#else +#include +#include +#include "../../common/linux/include/drm/amd_asic_type.h" +#endif +/* all asic after AI use this offset */ +#define mmRCC_IOV_FUNC_IDENTIFIER 0xDE5 +/* tonga/fiji use this offset */ +#define mmBIF_IOV_FUNC_IDENTIFIER 0x1503 +/* Exact original selector only; no SR-IOV/PF capability or host-mode claim. */ +static inline bool amdgpu_virt_bootstrap_iov_register(enum amd_asic_type asic_type, + uint32_t *reg) +{ + switch (asic_type) { + case CHIP_TONGA: + case CHIP_FIJI: + *reg = mmBIF_IOV_FUNC_IDENTIFIER; + return true; + case CHIP_VEGA10: + case CHIP_VEGA20: + case CHIP_NAVI10: + case CHIP_NAVI12: + case CHIP_SIENNA_CICHLID: + case CHIP_ARCTURUS: + case CHIP_ALDEBARAN: + case CHIP_IP_DISCOVERY: + *reg = mmRCC_IOV_FUNC_IDENTIFIER; + return true; + default: /* other chip doesn't support SRIOV */ + return false; + } + +} +#endif diff --git a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vpe.h b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vpe.h index 5c9a9f59a0..92f3f5b732 100644 --- a/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vpe.h +++ b/crates/stela-drivers/src/gpu/amd/amdgpu/amdgpu_vpe.h @@ -27,7 +27,7 @@ #include "amdgpu_irq.h" #include "vpe_6_1_fw_if.h" -#define AMDGPU_MAX_VPE_INSTANCES 2 +#include "amdgpu_ip_instance_limits.h" struct amdgpu_vpe; diff --git a/crates/stela-drivers/src/gpu/amd/discovery.rs b/crates/stela-drivers/src/gpu/amd/discovery.rs new file mode 100644 index 0000000000..e9e833bf11 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/discovery.rs @@ -0,0 +1,689 @@ +//! Actual original PF GPU-VRAM discovery acquisition. System firmware RAM and +//! VF protocols remain unavailable until their genuine native owners exist. +use super::{ + native_mmio::{ + AttachedBars, DynamicHardware, Error as WindowError, FileSource, Identity, RegisterWindow, + }, + vram, +}; +use crate::Clock; + +// Exact private discovery_tmr.h enum ABI; C/Rust owner fixtures exercise both. +const TMR_VF_OWNER_UNAVAILABLE: c_int = 3; +const TMR_SYSTEM_OWNER_UNAVAILABLE: c_int = 4; +use alloc::vec::Vec; +use core::{ + ffi::{c_int, c_uint, c_void}, + marker::PhantomData, +}; + +#[derive(Debug, PartialEq, Eq)] +pub enum Error { + Window(WindowError), + ClockUnavailable, + /// Before a region is acquired; may follow real query reads/index writes. + Query(c_int), + VfOwnerUnavailable, + SystemFirmwareOwnerUnavailable, + /// Query already ran. Allocation failure never rolls back its effects. + PostQueryAllocation, + InvalidRegion, + Read(vram::Error), + Validation(c_int), + /// Snapshot already acquired; earlier register effects are not rolled back. + PostAcquireAllocation, + Decode(c_int), +} +#[repr(C)] +#[derive(Default)] +struct Region { + offset: u64, + vram_bytes: u64, + size: u32, + reserved: u32, +} +const _: () = assert!(size_of::() == 24); +const _: () = assert!(core::mem::offset_of!(Region, size) == 16); +unsafe extern "C" { + fn stela_amd_discovery_tmr_query( + registers: *mut c_void, + bytes: usize, + asic: u32, + context: *mut c_void, + sleep_ms: unsafe extern "C" fn(*mut c_void, c_uint), + out: &mut Region, + ) -> c_int; + fn amdgpu_discovery_binary_validate(binary: *const u8, bytes: usize) -> c_int; +} +unsafe extern "C" fn sleep_ms(context: *mut c_void, milliseconds: c_uint) { + // SAFETY: acquire lends this exact immutable Clock for the synchronous call. + let clock = unsafe { &*context.cast::() }; + clock.delay(u64::from(milliseconds) * 1000); +} + +/// Private immutable original bytes and the same actual device owner borrow. +/// No mutable view is exposed: original in-place register-base conversions must +/// use a separately owned working copy and retain these acquisition bytes. +/// A snapshot is not a TMR reservation, BO, authenticated firmware or GPU READY. +pub struct Snapshot<'owner> { + words: Vec, + region: Region, + identity: Identity, + _owner: PhantomData<&'owner ()>, +} +impl Snapshot<'_> { + pub fn bytes(&self) -> &[u8] { + // SAFETY: fully initialized private DWORD allocation; only immutable + // bytes exposed, exact logical extent, no device DMA into this buffer. + unsafe { + core::slice::from_raw_parts(self.words.as_ptr().cast(), self.region.size as usize) + } + } + pub fn identity(&self) -> Identity { + self.identity + } + pub fn vram_offset(&self) -> u64 { + self.region.offset + } + pub fn vram_bytes(&self) -> u64 { + self.region.vram_bytes + } +} + +/// Query the original TMR and acquire its actual PF GPU-VRAM snapshot. +/// All available register/service bounds are checked before first access; +/// mailbox-dependent memory bounds are checked after query and before copying. +/// Original void MM reads provide no transport acknowledgement. Only original +/// signature/checksums/geometry qualify the private bytes, never hardware state. +/// IFWI exhaustion remains nonfatal as in the original driver. +/// +/// # Safety +/// The original native owner has selected this discovery bootstrap path on the +/// actual matched ASIC. Preserve its static-IP/optional-file policy; this API +/// cannot bypass a preferred firmware source or admit another device family. +/// Caller holds genuine D0/bridge/reset/removal/MM-index/IRQ exclusion, actual +/// UC ordered MMIO semantics and allowed process/CPU context for the WHOLE +/// query/copy. No concurrent driver/firmware/device mutation may affect source +/// acquisition. The observed RCC extent and selected VRAM source must actually +/// be accessible in this epoch. Actual original TMR/VRAM ownership is retained; +/// this API creates no reservation and never substitutes host PA or DMA IOVA. +/// The same owner cannot reset/rebind/retire while the returned borrow is used. +/// `clock` is the mount's genuine calibrated elapsed-time clock, with its real +/// wait hook/context. The existing delay busy-waits; it is not scheduler sleep. +/// Unexpected access faults follow real platform retention/fail-stop policy; +/// no error or Drop can undo earlier register/index effects. +pub unsafe fn acquire<'owner>( + bars: &'owner AttachedBars<'_>, + clock: &Clock, +) -> Result, Error> { + if clock.ticks_per_microsecond == 0 { + return Err(Error::ClockUnavailable); + } + let window = bars.registers().map_err(Error::Window)?; + // SAFETY: this same borrowed original owner and full acquisition contract. + unsafe { acquire_window(&window, bars.identity(), clock) } +} + +unsafe fn query_storage<'owner>( + window: &RegisterWindow<'owner>, + identity: Identity, + clock: &Clock, +) -> Result, Error> { + if clock.ticks_per_microsecond == 0 { + return Err(Error::ClockUnavailable); + } + // SAFETY: original owner contract above; borrowed mapping retained throughout. + let registers = unsafe { window.native_base() }.map_err(Error::Window)?; + let mut region = Region::default(); + // SAFETY: exact scalar ABI and synchronous Clock borrow; native preflight + // precedes access. No borrowed pointer is retained by the original core. + let status = unsafe { + stela_amd_discovery_tmr_query( + registers.as_ptr().cast(), + window.bytes(), + identity.asic_type, + (clock as *const Clock).cast_mut().cast(), + sleep_ms, + &mut region, + ) + }; + match status { + 0 => {} + TMR_VF_OWNER_UNAVAILABLE => return Err(Error::VfOwnerUnavailable), + TMR_SYSTEM_OWNER_UNAVAILABLE => return Err(Error::SystemFirmwareOwnerUnavailable), + other => return Err(Error::Query(other)), + } + if region.reserved != 0 + || region.size == 0 + || !region.size.is_multiple_of(4) + || region.offset > region.vram_bytes + || u64::from(region.size) > region.vram_bytes - region.offset + { + return Err(Error::InvalidRegion); + } + let count = region.size as usize / size_of::(); + let mut words = Vec::new(); + words + .try_reserve_exact(count) + .map_err(|_| Error::PostQueryAllocation)?; + words.resize(count, 0); + Ok(Snapshot { + words, + region, + identity, + _owner: PhantomData, + }) +} + +unsafe fn acquire_window<'owner>( + window: &RegisterWindow<'owner>, + identity: Identity, + clock: &Clock, +) -> Result, Error> { + // SAFETY: exact same genuine owner/query exclusion contract as acquire. + let mut snapshot = unsafe { query_storage(window, identity, clock) }?; + // SAFETY: actual bounded original VRAM region and exclusive private CPU RAM. + unsafe { + vram::read( + window, + snapshot.region.vram_bytes, + snapshot.region.offset, + &mut snapshot.words, + ) + } + .map_err(Error::Read)?; + validate_snapshot(&snapshot)?; + Ok(snapshot) +} +fn validate_snapshot(snapshot: &Snapshot<'_>) -> Result<(), Error> { + // SAFETY: complete actual same-allocation private source bytes, immutable + // and fully initialized before the original bounded validator runs. + let status = unsafe { + amdgpu_discovery_binary_validate( + snapshot.words.as_ptr().cast(), + snapshot.region.size as usize, + ) + }; + if status != 0 { + return Err(Error::Validation(status)); + } + Ok(()) +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Binding { + offset: u32, + count: u32, +} +#[repr(C)] +#[derive(Clone, Copy)] +struct Shape { + hw_ip_count: u32, + instances: u32, +} +/// Original pre-harvest counts and masks, not final topology or Metal limits. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct IpCounts { + pub xcc_mask: u16, + pub vcn_mask: u16, + pub jpeg_mask: u16, + pub vcn_count: u8, + pub vcn_config: [u8; 4], + pub sdma_count: i32, + pub sdma_mask: u32, + pub vpe_count: u32, + pub umc_count: i32, + pub node_count: u32, +} +const _: () = assert!(size_of::() == 8); +const _: () = assert!(size_of::() == 8); +const _: () = assert!(size_of::() == 32); +const _: () = assert!(core::mem::offset_of!(IpCounts, sdma_count) == 12); +const _: () = assert!(core::mem::offset_of!(IpCounts, node_count) == 28); +unsafe extern "C" { + fn stela_amd_discovery_ip_shape() -> Shape; + fn stela_amd_discovery_ip_decode( + work: *mut u8, + bytes: usize, + versions: *mut u32, + version_count: usize, + bindings: *mut Binding, + binding_count: usize, + counts: &mut IpCounts, + ) -> c_int; +} + +/// Observed original IP/register facts. This retains the exact admitted source +/// owner, immutable acquisition bytes and one private once-converted copy. +/// No public constructor/conversion from Snapshot or raw bytes exists. +/// Register offsets are facts, not permission to bypass original register +/// routing, bounds, power/reset, firmware or device-context prerequisites. +struct IpData<'owner> { + snapshot: Snapshot<'owner>, + work: Vec, + versions: Vec, + bindings: Vec, + shape: Shape, + counts: IpCounts, +} +impl IpData<'_> { + fn source_bytes(&self) -> &[u8] { + self.snapshot.bytes() + } + fn identity(&self) -> Identity { + self.snapshot.identity() + } + fn counts(&self) -> IpCounts { + self.counts + } + fn slot(&self, hw_ip: u32, instance: u32) -> Option { + if hw_ip >= self.shape.hw_ip_count || instance >= self.shape.instances { + return None; + } + (hw_ip as usize) + .checked_mul(self.shape.instances as usize)? + .checked_add(instance as usize) + } + /// Original full version, including variant/subrevision. Zero remains an + /// original value; WAFLC may provide a version without a register binding. + fn version(&self, hw_ip: u32, instance: u32) -> Option { + self.versions.get(self.slot(hw_ip, instance)?).copied() + } + /// None is unbound/out of range; Some(0) is an original zero-segment binding. + fn register_count(&self, hw_ip: u32, instance: u32) -> Option { + let binding = self.bindings.get(self.slot(hw_ip, instance)?)?; + (binding.offset != u32::MAX).then_some(binding.count) + } + /// By-value unaligned-safe load from the private converted CPU allocation. + /// Never form a Rust &[u32] over the original packed base array. + fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option { + let binding = self.bindings.get(self.slot(hw_ip, instance)?)?; + if binding.offset == u32::MAX || segment >= binding.count { + return None; + } + let offset = (binding.offset as usize).checked_add((segment as usize).checked_mul(4)?)?; + let end = offset.checked_add(4)?; + let bytes = self.work.len().checked_mul(size_of::())?; + if end > bytes { + return None; + } + // SAFETY: checked complete initialized owned allocation, immutable CPU + // bytes only. No aliasing or device pointer enters this view. + let work = unsafe { core::slice::from_raw_parts(self.work.as_ptr().cast::(), bytes) }; + Some(u32::from_ne_bytes(work.get(offset..end)?.try_into().ok()?)) + } +} +fn storage(count: usize, value: T) -> Result, Error> { + let mut result = Vec::new(); + result + .try_reserve_exact(count) + .map_err(|_| Error::PostAcquireAllocation)?; + result.resize(count, value); + Ok(result) +} + +/// Acquire and decode only the original matched dynamic hardware route. +/// Static, preferred-file and manual-attachment routes refuse before effects. +/// This does not initialize NBIO/GMC or publish a working GPU/VM. +/// +/// # Safety +/// All genuine source/VRAM/reservation/context and full MM-index/D0/reset/IRQ +/// exclusion requirements of [`acquire`] apply. This exact canonical owner and +/// its real device/reset epoch remain valid through all returned facts. No +/// allocation/Drop undoes query/index effects or releases original TMR ownership. +pub unsafe fn acquire_dynamic_ip<'owner>( + bars: &'owner AttachedBars<'_>, + clock: &Clock, +) -> Result, Error> { + let owner = bars.dynamic_hardware().map_err(Error::Window)?; + // SAFETY: token holds this exact private admitted window and caller supplies + // the same genuine acquisition/reset/exclusion contract as acquire. + let snapshot = unsafe { acquire_window(owner.window(), owner.identity(), clock) }?; + let data = decode_ip(snapshot)?; + Ok(ObservedIp { + data, + _owner: owner, + }) +} +fn decode_ip(snapshot: Snapshot<'_>) -> Result, Error> { + let mut work = storage(snapshot.words.len(), 0u32)?; + work.copy_from_slice(&snapshot.words); + // SAFETY: original compiled storage shape, no device access or callback. + let shape = unsafe { stela_amd_discovery_ip_shape() }; + let cells = (shape.hw_ip_count as usize) + .checked_mul(shape.instances as usize) + .filter(|count| *count > 0) + .ok_or(Error::PostAcquireAllocation)?; + let mut versions = storage(cells, 0u32)?; + let mut bindings = storage(cells, Binding::default())?; + let mut counts = IpCounts::default(); + // SAFETY: exclusive complete disjoint CPU allocations, checked scalar ABI, + // original immutable bytes copied once. No raw pointer is retained by C. + let status = unsafe { + stela_amd_discovery_ip_decode( + work.as_mut_ptr().cast(), + snapshot.bytes().len(), + versions.as_mut_ptr(), + versions.len(), + bindings.as_mut_ptr(), + bindings.len(), + &mut counts, + ) + }; + if status != 0 { + return Err(Error::Decode(status)); + } + Ok(IpData { + snapshot, + work, + versions, + bindings, + shape, + counts, + }) +} + +/// Observed original hardware IP facts, retaining this privately admitted owner. +/// The raw source/once-converted work ownership and getter semantics are unchanged. +pub struct ObservedIp<'owner> { + data: IpData<'owner>, + _owner: DynamicHardware<'owner>, +} +impl ObservedIp<'_> { + pub fn source_bytes(&self) -> &[u8] { + self.data.source_bytes() + } + pub fn identity(&self) -> Identity { + self.data.identity() + } + pub fn counts(&self) -> IpCounts { + self.data.counts() + } + pub fn version(&self, hw_ip: u32, instance: u32) -> Option { + self.data.version(hw_ip, instance) + } + pub fn register_count(&self, hw_ip: u32, instance: u32) -> Option { + self.data.register_count(hw_ip, instance) + } + pub fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option { + self.data.register_base(hw_ip, instance, segment) + } +} + +/// Original outer cleanup required after a selected-file acquisition error. +/// This is a pending service requirement, never an executed status/read result. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum FileFailureDiagnostics { + /// Original option2 omits the version-register/RAS cleanup branch. + OmittedByOriginalOption2, + /// Original non-option2 checks real mmIP_DISCOVERY_VERSION and may query + /// actual RAS boot status. That device service has not run in this adapter. + DiscoveryVersionAndRasCheckRequired, +} +#[derive(Debug)] +pub enum FileSourceError { + Provider(crate::firmware::Error), + WrongImage, + Policy(c_int), + Region(Error), +} +#[derive(Debug)] +pub enum FileError { + Window(WindowError), + IdentityEncoding, + InvalidCatalogName, + InvalidNativePolicy, + /// Original query or zeroed storage failed before any provider request. + Acquire(Error), + /// File selection/read failed after query/allocation; no hardware fallback. + Source { + error: FileSourceError, + pending: FileFailureDiagnostics, + }, + /// Source already validated. Later native fact storage failed, with all + /// earlier query effects retained and no published IP result. + Ip(Error), +} + +// Fixed-width observed PCI labels only; no allocation or guessed GPU family. +struct FileLabel { + bytes: [u8; N], + used: usize, +} +impl FileLabel { + fn new() -> Self { + Self { + bytes: [0; N], + used: 0, + } + } + fn as_str(&self) -> &str { + // SAFETY: Write only copies complete valid UTF-8 strings below. + unsafe { core::str::from_utf8_unchecked(&self.bytes[..self.used]) } + } +} +impl core::fmt::Write for FileLabel { + fn write_str(&mut self, value: &str) -> core::fmt::Result { + let end = self + .used + .checked_add(value.len()) + .filter(|end| *end <= N) + .ok_or(core::fmt::Error)?; + self.bytes[self.used..end].copy_from_slice(value.as_bytes()); + self.used = end; + Ok(()) + } +} +unsafe extern "C" { + fn stela_amd_discovery_file_minimum() -> usize; + fn stela_amd_discovery_file_validate(data: *const u8, bytes: usize, capacity: u32) -> c_int; +} + +/// Original exact preferred-file request, minted from this same live privately +/// admitted BAR owner. No Image, Snapshot, path string, tuple or BDF constructor. +/// A request is not firmware authentication, TMR reservation or GPU readiness. +pub struct FileRequest<'owner> { + owner: FileSource<'owner>, + name: &'static str, + hardware: FileLabel<16>, + revision: FileLabel<40>, + minimum: usize, +} +impl<'owner> FileRequest<'owner> { + pub fn new(bars: &'owner AttachedBars<'_>) -> Result { + use core::fmt::Write; + let owner = bars.source_file().map_err(FileError::Window)?; + let name = owner + .filename() + .to_str() + .map_err(|_| FileError::InvalidCatalogName)?; + let mut hardware = FileLabel::new(); + let (vendor, device) = owner.hardware_ids(); + write!(hardware, "pci-{vendor:04x}-{device:04x}") + .map_err(|_| FileError::IdentityEncoding)?; + let mut revision = FileLabel::new(); + let (pci_revision, subvendor, subdevice) = owner.revision_ids(); + write!( + revision, + "pci-{pci_revision:02x};subsys-{subvendor:04x}-{subdevice:04x}" + ) + .map_err(|_| FileError::IdentityEncoding)?; + // SAFETY: actual original compiled header span, no device effects. + let minimum = unsafe { stela_amd_discovery_file_minimum() }; + if minimum == 0 { + return Err(FileError::InvalidNativePolicy); + } + Ok(Self { + owner, + name, + hardware, + revision, + minimum, + }) + } + pub fn name(&self) -> &str { + self.name + } + /// Exact manifest equality keys from actual observed PCI fields; not a + /// declaration that some other device/revision can use this firmware. + pub fn target(&self) -> crate::firmware::Target<'_> { + crate::firmware::Target { + driver: "amd-amdgpu-ip-discovery", + hardware: self.hardware.as_str(), + revision: self.revision.as_str(), + board: None, + } + } + pub fn requirement(&self) -> crate::firmware::Requirement<'_> { + crate::firmware::Requirement { + name: self.name(), + target: self.target(), + minimum_bytes: self.minimum, + } + } + fn source_error(&self, error: FileSourceError) -> FileError { + FileError::Source { + error, + pending: if self.owner.discovery_option() == 2 { + FileFailureDiagnostics::OmittedByOriginalOption2 + } else { + FileFailureDiagnostics::DiscoveryVersionAndRasCheckRequired + }, + } + } + + /// Acquire the selected file in original order: real TMR query -> normal + /// zeroed allocation -> exact provider request -> actual file bounds/checksum + /// -> copy/region validation. No preferred-source fallback occurs. + /// + /// # Safety + /// All genuine source/VRAM/TMR ownership, calibrated Clock and full D0/reset, + /// removal/MM-index/IRQ exclusion/context requirements of [`acquire`] hold + /// for the whole synchronous query/load/copy. Retain the same genuine device + /// owner/reset epoch through returned facts. A file + /// cannot bypass query/VF/system-memory services. Original option2 requests + /// TMR reservation but this adapter cannot create or assert that reservation. + /// Earlier query/index effects are never rolled back on provider/OOM/error. + /// A static inventory result does not run fixed-IP initialization or the + /// original outer version-register/RAS diagnostic service after failures. + pub unsafe fn acquire<'provider, P: crate::firmware::Provider + ?Sized>( + self, + provider: &'provider P, + clock: &Clock, + ) -> Result, FileError> { + // SAFETY: same retained admitted window and complete original contract. + let mut snapshot = + unsafe { query_storage(self.owner.window(), self.owner.identity(), clock) } + .map_err(FileError::Acquire)?; + let requirement = self.requirement(); + let image = provider + .load(requirement) + .map_err(|error| self.source_error(FileSourceError::Provider(error)))?; + if image.name() != requirement.name || image.target() != requirement.target { + return Err(self.source_error(FileSourceError::WrongImage)); + } + // SAFETY: actual immutable canonical image allocation and queried extent. + let status = unsafe { + stela_amd_discovery_file_validate( + image.bytes().as_ptr(), + image.bytes().len(), + snapshot.region.size, + ) + }; + if status != 0 { + return Err(self.source_error(FileSourceError::Policy(status))); + } + // SAFETY: complete initialized exclusive CPU Vec, no active aliases. + // Original file policy already checked actual bytes fit real capacity. + let destination = unsafe { + core::slice::from_raw_parts_mut( + snapshot.words.as_mut_ptr().cast::(), + snapshot.region.size as usize, + ) + }; + destination[..image.bytes().len()].copy_from_slice(image.bytes()); + validate_snapshot(&snapshot) + .map_err(|error| self.source_error(FileSourceError::Region(error)))?; + match self.owner.path() { + super::pci::IpPath::Dynamic => { + let data = decode_ip(snapshot).map_err(FileError::Ip)?; + Ok(SelectedFile::Dynamic(FileIp { + data, + image, + _owner: self.owner, + })) + } + super::pci::IpPath::SocStatic => Ok(SelectedFile::Static(FileInventory { + snapshot, + image, + _owner: self.owner, + })), + _ => Err(FileError::Window(WindowError::StaticInitializationRequired)), + } + } +} + +/// Actual privately selected path determines the result. Static inventory has +/// no conversion into dynamic IP facts or permission to override fixed tables. +pub enum SelectedFile<'owner, 'provider> { + Dynamic(FileIp<'owner, 'provider>), + Static(FileInventory<'owner, 'provider>), +} +/// Exact canonical Image and real acquired bytes for static optional inventory. +/// This does not run static register/IP setup or sanitize missing inventory. +pub struct FileInventory<'owner, 'provider> { + snapshot: Snapshot<'owner>, + image: crate::firmware::Image<'provider>, + _owner: FileSource<'owner>, +} +impl<'provider> FileInventory<'_, 'provider> { + pub fn image(&self) -> crate::firmware::Image<'provider> { + self.image + } + /// Copied file plus original zero-filled queried-region tail. Exact original + /// file bytes/hash/provenance remain separately available via image(). + pub fn acquired_bytes(&self) -> &[u8] { + self.snapshot.bytes() + } + pub fn identity(&self) -> Identity { + self.snapshot.identity() + } + pub fn vram_offset(&self) -> u64 { + self.snapshot.vram_offset() + } + pub fn vram_bytes(&self) -> u64 { + self.snapshot.vram_bytes() + } +} +/// Dynamic facts decoded by the SAME original decoder after selected-file +/// acquisition. Original Image/provider and actual device epoch remain borrowed. +pub struct FileIp<'owner, 'provider> { + data: IpData<'owner>, + image: crate::firmware::Image<'provider>, + _owner: FileSource<'owner>, +} +impl<'provider> FileIp<'_, 'provider> { + pub fn image(&self) -> crate::firmware::Image<'provider> { + self.image + } + pub fn acquired_bytes(&self) -> &[u8] { + self.data.source_bytes() + } + pub fn identity(&self) -> Identity { + self.data.identity() + } + pub fn counts(&self) -> IpCounts { + self.data.counts() + } + pub fn version(&self, hw_ip: u32, instance: u32) -> Option { + self.data.version(hw_ip, instance) + } + pub fn register_count(&self, hw_ip: u32, instance: u32) -> Option { + self.data.register_count(hw_ip, instance) + } + pub fn register_base(&self, hw_ip: u32, instance: u32, segment: u32) -> Option { + self.data.register_base(hw_ip, instance, segment) + } +} diff --git a/crates/stela-drivers/src/gpu/amd/include/amd_chip_flags.h b/crates/stela-drivers/src/gpu/amd/include/amd_chip_flags.h new file mode 100644 index 0000000000..48ca569fc4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/include/amd_chip_flags.h @@ -0,0 +1,48 @@ +/* + * Copyright 2015 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef AMD_CHIP_FLAGS_H +#define AMD_CHIP_FLAGS_H + +/* + * Chip flags + */ +enum amd_chip_flags { + AMD_ASIC_MASK = 0x0000ffffUL, + AMD_FLAGS_MASK = 0xffff0000UL, + AMD_IS_MOBILITY = 0x00010000UL, + AMD_IS_APU = 0x00020000UL, + AMD_IS_PX = 0x00040000UL, + AMD_EXP_HW_SUPPORT = 0x00080000UL, +}; + +enum amd_apu_flags { + AMD_APU_IS_RAVEN = 0x00000001UL, + AMD_APU_IS_RAVEN2 = 0x00000002UL, + AMD_APU_IS_PICASSO = 0x00000004UL, + AMD_APU_IS_RENOIR = 0x00000008UL, + AMD_APU_IS_GREEN_SARDINE = 0x00000010UL, + AMD_APU_IS_VANGOGH = 0x00000020UL, + AMD_APU_IS_CYAN_SKILLFISH2 = 0x00000040UL, +}; + +#endif diff --git a/crates/stela-drivers/src/gpu/amd/include/amd_shared.h b/crates/stela-drivers/src/gpu/amd/include/amd_shared.h index 3fd38323a8..daae538b1e 100644 --- a/crates/stela-drivers/src/gpu/amd/include/amd_shared.h +++ b/crates/stela-drivers/src/gpu/amd/include/amd_shared.h @@ -31,27 +31,7 @@ struct amdgpu_ip_block; -/* - * Chip flags - */ -enum amd_chip_flags { - AMD_ASIC_MASK = 0x0000ffffUL, - AMD_FLAGS_MASK = 0xffff0000UL, - AMD_IS_MOBILITY = 0x00010000UL, - AMD_IS_APU = 0x00020000UL, - AMD_IS_PX = 0x00040000UL, - AMD_EXP_HW_SUPPORT = 0x00080000UL, -}; - -enum amd_apu_flags { - AMD_APU_IS_RAVEN = 0x00000001UL, - AMD_APU_IS_RAVEN2 = 0x00000002UL, - AMD_APU_IS_PICASSO = 0x00000004UL, - AMD_APU_IS_RENOIR = 0x00000008UL, - AMD_APU_IS_GREEN_SARDINE = 0x00000010UL, - AMD_APU_IS_VANGOGH = 0x00000020UL, - AMD_APU_IS_CYAN_SKILLFISH2 = 0x00000040UL, -}; +#include "amd_chip_flags.h" /** * DOC: IP Blocks diff --git a/crates/stela-drivers/src/gpu/amd/include/discovery.h b/crates/stela-drivers/src/gpu/amd/include/discovery.h index 76c9f951bc..ff1d6b33f9 100644 --- a/crates/stela-drivers/src/gpu/amd/include/discovery.h +++ b/crates/stela-drivers/src/gpu/amd/include/discovery.h @@ -24,6 +24,20 @@ #ifndef _DISCOVERY_H_ #define _DISCOVERY_H_ +#ifdef __KERNEL__ +#include +#include +#else +#include +/* Original public flex-array declarations, with no Linux service shim. */ +#include "../../common/linux/include/uapi/linux/stddef.h" +#if !defined(__BYTE_ORDER__) || !defined(__ORDER_LITTLE_ENDIAN__) || !defined(__ORDER_BIG_ENDIAN__) +#error "Discovery format requires compiler byte-order definitions" +#elif __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ && __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__ +#error "Discovery format requires an explicit native byte order" +#endif +#endif + #define PSP_HEADER_SIZE 256 #define BINARY_SIGNATURE 0x28211407 #define DISCOVERY_TABLE_SIGNATURE 0x53445049 @@ -110,7 +124,8 @@ typedef struct ip uint8_t major; /* HCID Major */ uint8_t minor; /* HCID Minor */ uint8_t revision; /* HCID Revision */ -#if defined(__BIG_ENDIAN) +#if (defined(__KERNEL__) && defined(__BIG_ENDIAN)) || \ + (!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) uint8_t reserved : 4; /* Placeholder field */ uint8_t harvest : 4; /* Harvest */ #else @@ -128,7 +143,8 @@ typedef struct ip_v3 uint8_t major; /* Hardware ID.major version */ uint8_t minor; /* Hardware ID.minor version */ uint8_t revision; /* Hardware ID.revision version */ -#if defined(__BIG_ENDIAN) +#if (defined(__KERNEL__) && defined(__BIG_ENDIAN)) || \ + (!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) uint8_t variant : 4; /* HW variant */ uint8_t sub_revision : 4; /* HCID Sub-Revision */ #else @@ -145,17 +161,19 @@ typedef struct ip_v4 { uint8_t major; /* Hardware ID.major version */ uint8_t minor; /* Hardware ID.minor version */ uint8_t revision; /* Hardware ID.revision version */ -#if defined(LITTLEENDIAN_CPU) +#if defined(LITTLEENDIAN_CPU) || \ + (!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) uint8_t sub_revision : 4; /* HCID Sub-Revision */ uint8_t variant : 4; /* HW variant */ -#elif defined(BIGENDIAN_CPU) +#elif defined(BIGENDIAN_CPU) || \ + (!defined(__KERNEL__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) uint8_t variant : 4; /* HW variant */ uint8_t sub_revision : 4; /* HCID Sub-Revision */ #endif union { - DECLARE_FLEX_ARRAY(uint32_t, base_address); /* 32-bit Base Address list. Corresponds to the num_base_address field*/ - DECLARE_FLEX_ARRAY(uint64_t, base_address_64); /* 64-bit Base Address list. Corresponds to the num_base_address field*/ - } __packed; + __DECLARE_FLEX_ARRAY(uint32_t, base_address); /* 32-bit Base Address list. Corresponds to the num_base_address field*/ + __DECLARE_FLEX_ARRAY(uint64_t, base_address_64); /* 64-bit Base Address list. Corresponds to the num_base_address field*/ + } __attribute__((__packed__)); } ip_v4; typedef struct die_header diff --git a/crates/stela-drivers/src/gpu/amd/native_mmio.rs b/crates/stela-drivers/src/gpu/amd/native_mmio.rs new file mode 100644 index 0000000000..b0fa46c979 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/native_mmio.rs @@ -0,0 +1,586 @@ +//! Original AMDGPU BAR policy attached to the canonical native MMIO owner. +//! +//! No register access, doorbell write, firmware load or hardware activation is +//! performed here. Original AMDGPU register routing and device lifecycle remain +//! mandatory; this module only retains their real, bounded CPU windows. +use super::pci::{Admission, IpPath, MatchedFunction, Source}; +use crate::bus::{ + mmio::owned::{ + Authority, CacheAttribute, Error as MmioError, Mapping, MappingView, PAGE_BYTES, + PhysicalSpan, Protection, Resource, ResourceKind, + }, + pci::{Address, ConfigSpace, Function}, +}; +use core::{ffi::c_int, marker::PhantomData, ptr::NonNull}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + InvalidOwner, + AdmissionRequired, + StaticInitializationRequired, + FirmwareSourceRequired, + PreferredFileRequired, + InvalidRange, + Policy(c_int), + Mapping(MmioError), + IndirectRegisterRequired, + Retired, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Stage { + Preflight, + Registers, + Doorbells, +} + +/// Failure ownership is truthful even when attachment fails after a real map. +/// The canonical authority owns uncertain failed-map reservations internally. +/// `rollback` describes the already-installed, unpublished register window. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AttachError { + pub stage: Stage, + pub error: Error, + pub rollback: Rollback, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Rollback { + NotAttempted, + Retired, + /// Drop retained the real mapping/resource in canonical quarantine after + /// this failed retirement. No resource or native table was freed here. + Quarantined(MmioError), +} + +/// The actual resource owner, not a physical BAR tuple or a DMA allocation. +pub struct RegisterBar { + pub index: u8, + pub resource: Resource, +} + +/// Actual original kernel doorbell reservation within BAR2. The resource's +/// original backing must pin this allocation as well as the whole BAR through +/// acknowledged retirement or permanent canonical quarantine, including Drop. +/// `reserved_bytes` covers complete physical pages; `logical_dwords` is the +/// original post-MES-allocation extent, not the entire BAR's capacity. +pub struct KernelDoorbells { + pub index: u8, + pub resource: Resource, + pub offset: usize, + pub reserved_bytes: usize, + pub logical_dwords: u32, + pub max_assignment: u32, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Identity { + pub address: Address, + pub device: u16, + /// Original pciidlist match's driver flags; never a Metal feature mask. + pub original_flags: u32, + pub asic_type: u32, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Layout { + register_bar: u32, + kernel_doorbells: u32, + kernel_doorbell_bytes: u64, +} +const _: () = assert!(size_of::() == 16); +const _: () = assert!(core::mem::offset_of!(Layout, kernel_doorbell_bytes) == 8); + +unsafe extern "C" { + fn stela_amd_native_register_bar(asic_type: u32, bar: *mut u32) -> c_int; + fn stela_amd_native_bar_layout( + asic_type: u32, + doorbell_bar_bytes: u64, + max_assignment: u32, + page_bytes: u64, + layout: *mut Layout, + ) -> c_int; +} + +/// The lifetime also borrows the actual matched PCI function. ResourceBacking +/// retains the real resource/reset epoch; caller's original owner retains its +/// doorbell BO reservation and all C consumers through this borrow. +pub struct AttachedBars<'a> { + identity: Identity, + admission: Option, + registers: Mapping, + doorbells: Option, + logical_doorbell_bytes: usize, + active: bool, + _function: PhantomData<&'a ()>, +} + +fn preflight(error: Error) -> AttachError { + AttachError { + stage: Stage::Preflight, + error, + rollback: Rollback::NotAttempted, + } +} + +fn whole_pages(resource: &Resource, offset: usize, bytes: usize) -> Result<(), Error> { + let span = resource.physical_span(); + let offset = u64::try_from(offset).map_err(|_| Error::InvalidRange)?; + let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidRange)?; + let start = span + .start() + .checked_add(offset) + .ok_or(Error::InvalidRange)?; + let end = start.checked_add(bytes).ok_or(Error::InvalidRange)?; + if bytes == 0 + || !start.is_multiple_of(PAGE_BYTES) + || !bytes.is_multiple_of(PAGE_BYTES) + || start < span.start() + || end > span.end() + { + return Err(Error::InvalidRange); + } + Ok(()) +} + +fn query_layout(asic_type: u32, doorbells: Option<&KernelDoorbells>) -> Result { + if doorbells.is_some_and(|d| d.index != 2) { + return Err(Error::InvalidOwner); + } + let mut layout = Layout::default(); + // SAFETY: private C ABI has independent layout assertions and writes only + // initialized local outputs; original policies are allocation-free. + let status = unsafe { + match doorbells { + None => stela_amd_native_register_bar(asic_type, &mut layout.register_bar), + Some(d) => stela_amd_native_bar_layout( + asic_type, + d.resource.physical_span().bytes(), + d.max_assignment, + PAGE_BYTES, + &mut layout, + ), + } + }; + if status != 0 { + return Err(Error::Policy(status)); + } + Ok(layout) +} + +fn validate_doorbells( + registers: PhysicalSpan, + doorbells: &KernelDoorbells, + layout: Layout, +) -> Result { + let bytes = usize::try_from(layout.kernel_doorbell_bytes).map_err(|_| Error::InvalidRange)?; + if doorbells.logical_dwords != layout.kernel_doorbells + || bytes == 0 + || bytes > doorbells.reserved_bytes + { + return Err(Error::InvalidRange); + } + whole_pages( + &doorbells.resource, + doorbells.offset, + doorbells.reserved_bytes, + )?; + let span = doorbells.resource.physical_span(); + if registers.start() < span.end() && span.start() < registers.end() { + return Err(Error::InvalidOwner); + } + Ok(bytes) +} + +impl<'a> AttachedBars<'a> { + pub(super) fn source_file(&self) -> Result, Error> { + if !self.active { + return Err(Error::Retired); + } + let admission = self.admission.ok_or(Error::AdmissionRequired)?; + let Source::Firmware(filename) = admission.source() else { + return Err(Error::PreferredFileRequired); + }; + if !matches!(admission.path(), IpPath::Dynamic | IpPath::SocStatic) { + return Err(Error::StaticInitializationRequired); + } + Ok(FileSource { + window: self.registers()?, + identity: self.identity, + admission, + filename, + }) + } + + pub(super) fn dynamic_hardware(&self) -> Result, Error> { + if !self.active { + return Err(Error::Retired); + } + let admission = self.admission.ok_or(Error::AdmissionRequired)?; + if admission.path() != IpPath::Dynamic { + return Err(Error::StaticInitializationRequired); + } + if admission.source() != Source::Hardware { + return Err(Error::FirmwareSourceRequired); + } + Ok(DynamicHardware { + window: self.registers()?, + identity: self.identity, + }) + } + + /// Attach from the actual original normal PCI match. The private result is + /// retained on this exact mapping owner; the legacy manual unsafe path + /// cannot mint this admission. No firmware/static fallback or activation. + /// + /// # Safety + /// All actual resource/context/exclusion requirements of [`Self::attach`] + /// hold. The matched function and resources are from this same genuine + /// owner/reset epoch. Keep its original source/static plan; matching does + /// not acquire the selected firmware or implement static IP initialization. + pub unsafe fn attach_matched( + authority: &Authority, + matched: &'a MatchedFunction<'_, C>, + registers: RegisterBar, + doorbells: Option, + ) -> Result { + let admission = matched.admission(); + // SAFETY: actual owner/resource contract above; ASIC/flags are private + // outputs of original matching, not independently supplied labels. + let mut bars = unsafe { + Self::attach( + authority, + matched.function(), + admission.flags(), + admission.asic(), + registers, + doorbells, + ) + }?; + bars.admission = Some(admission); + Ok(bars) + } + + /// Original initialization/source plan of an actual matched attachment. + /// None means the older manual unsafe attachment has no such admission. + /// A dynamic hardware plan still requires genuine acquisition/validation. + pub fn original_plan(&self) -> Option<(IpPath, Source)> { + self.admission + .map(|admission| (admission.path(), admission.source())) + } + + /// Attach unpublished CPU windows for an actual original AMDGPU PCI match. + /// The display-only diagnostic inventory is intentionally not consulted. + /// + /// # Safety + /// `function`, `original_flags` and `asic_type` must describe the same real + /// original pciidlist match and original native device/reset epoch. Both + /// resources must be that function's assigned BARs, with live exclusive + /// reservations; no other driver or firmware may use them. `registers` + /// must be the complete original register BAR. `None` bootstraps registers + /// before original IP discovery/BO initialization; it never reports doors + /// or an initialized device. A supplied `doorbells` must describe the + /// actual original kernel BO reservation in BAR2, actual ASIC + /// max_assignment and post-allocation logical extent, including paging/MES + /// pages. The original owner must retain that suballocation and prevent + /// rebinding/reset/removal or C access after teardown begins, until every + /// borrowed window is released and retirement is acknowledged. No booleans + /// supplied here establish firmware, queue, power or device readiness. + /// Native process/deferred context and the canonical provider's rules apply. + pub unsafe fn attach( + authority: &Authority, + function: &'a Function, + original_flags: u32, + asic_type: u32, + registers: RegisterBar, + doorbells: Option, + ) -> Result { + if function.vendor != 0x1002 || registers.resource.kind() != ResourceKind::Registers { + return Err(preflight(Error::InvalidOwner)); + } + let layout = query_layout(asic_type, doorbells.as_ref()).map_err(preflight)?; + if u32::from(registers.index) != layout.register_bar { + return Err(preflight(Error::InvalidOwner)); + } + let register_bytes = usize::try_from(registers.resource.physical_span().bytes()) + .map_err(|_| preflight(Error::InvalidRange))?; + whole_pages(®isters.resource, 0, register_bytes).map_err(preflight)?; + let logical_doorbell_bytes = doorbells + .as_ref() + .map_or(Ok(0), |d| { + validate_doorbells(registers.resource.physical_span(), d, layout) + }) + .map_err(preflight)?; + let mut registers = authority + .map( + registers.resource, + 0, + register_bytes, + CacheAttribute::Uncached, + Protection::ReadWrite, + ) + .map_err(|error| AttachError { + stage: Stage::Registers, + error: Error::Mapping(error), + rollback: Rollback::NotAttempted, + })?; + let doorbell_mapping = match doorbells { + None => None, + Some(d) => match authority.map( + d.resource, + d.offset, + d.reserved_bytes, + CacheAttribute::Uncached, + Protection::ReadWrite, + ) { + Ok(mapping) => Some(mapping), + Err(error) => { + // SAFETY: no pointer/view was exposed and no CPU/device + // access occurred through this new unpublished mapping. + let rollback = match unsafe { registers.retire() } { + Ok(()) => Rollback::Retired, + Err(error) => Rollback::Quarantined(error), + }; + // Failed retire is retained by canonical Drop quarantine. + drop(registers); + return Err(AttachError { + stage: Stage::Doorbells, + error: Error::Mapping(error), + rollback, + }); + } + }, + }; + Ok(Self { + identity: Identity { + address: function.address, + device: function.device, + original_flags, + asic_type, + }, + admission: None, + registers, + doorbells: doorbell_mapping, + logical_doorbell_bytes, + active: true, + _function: PhantomData, + }) + } + + pub fn identity(&self) -> Identity { + self.identity + } + + /// Retained views may be held by the original native C owner independently + /// of this container; canonical retirement stays Busy until they drain. + pub fn registers(&self) -> Result, Error> { + if !self.active { + return Err(Error::Retired); + } + let bytes = self.registers.bytes().map_err(Error::Mapping)?; + Ok(RegisterWindow { + view: self.registers.view(0..bytes).map_err(Error::Mapping)?, + _owner: PhantomData, + }) + } + + pub fn doorbells(&self) -> Result>, Error> { + if !self.active { + return Err(Error::Retired); + } + self.doorbells + .as_ref() + .map(|mapping| { + Ok(DoorbellWindow { + view: mapping + .view(0..self.logical_doorbell_bytes) + .map_err(Error::Mapping)?, + _owner: PhantomData, + }) + }) + .transpose() + } + + pub fn register_physical_span(&self) -> Result { + self.registers.physical_span().map_err(Error::Mapping) + } + + /// Attach the real kernel reservation after original discovery/doorbell BO + /// creation, reusing the existing register mapping. Failure preserves that + /// published register owner; canonical failed-map quarantine still applies. + /// + /// # Safety + /// The reservation/backing, ASIC assignment and original owner must obey + /// `attach`'s same-device/reset-epoch and lifetime requirements. The backing + /// retains the actual BO suballocation even on permanent map quarantine. + /// Original device initialization remains serialized by its actual owner. + pub unsafe fn attach_kernel_doorbells( + &mut self, + authority: &Authority, + doorbells: KernelDoorbells, + ) -> Result<(), AttachError> { + if !self.active || self.doorbells.is_some() { + return Err(preflight(Error::InvalidOwner)); + } + let layout = query_layout(self.identity.asic_type, Some(&doorbells)).map_err(preflight)?; + let span = self.register_physical_span().map_err(preflight)?; + let bytes = validate_doorbells(span, &doorbells, layout).map_err(preflight)?; + let mapping = authority + .map( + doorbells.resource, + doorbells.offset, + doorbells.reserved_bytes, + CacheAttribute::Uncached, + Protection::ReadWrite, + ) + .map_err(|error| AttachError { + stage: Stage::Doorbells, + error: Error::Mapping(error), + rollback: Rollback::NotAttempted, + })?; + self.doorbells = Some(mapping); + self.logical_doorbell_bytes = bytes; + Ok(()) + } + + /// Retire only after real original consumers stop and posted accesses drain. + /// An error disables new windows and retains the exact mappings for retry; + /// Drop without acknowledged retirement uses canonical quarantine. + /// + /// # Safety + /// Every C/CPU/worker/IRQ consumer and original-owner access through all + /// obtained raw pointers must be stopped/drained, with no future access. + /// Caller proves device/reset exclusion, correct process/deferred context + /// and all canonical retirement requirements. This does not stop hardware. + pub unsafe fn retire(&mut self) -> Result<(), Error> { + self.active = false; + if let Some(mapping) = &mut self.doorbells { + // SAFETY: the caller supplies the real shared consumer drain. + unsafe { mapping.retire().map_err(Error::Mapping)? }; + self.doorbells = None; + } + // SAFETY: the same actual consumer drain and context proof apply. + unsafe { self.registers.retire().map_err(Error::Mapping) } + } +} + +/// Private proof of original dynamic/hardware selection on this exact live +/// mapping owner. No Clone or public constructor; public selection metadata and +/// arbitrary snapshots cannot create it. The canonical lease/borrow pins epoch. +pub(super) struct DynamicHardware<'owner> { + window: RegisterWindow<'owner>, + identity: Identity, +} +impl<'owner> DynamicHardware<'owner> { + pub(super) fn window(&self) -> &RegisterWindow<'owner> { + &self.window + } + pub(super) fn identity(&self) -> Identity { + self.identity + } +} + +/// Bounded register mapping only. Original RREG/WREG dispatch still owns +/// direct versus indirect PCIe/KIQ/RLCG/XCC routing and power/reset rules. +pub struct RegisterWindow<'a> { + view: MappingView, + _owner: PhantomData<&'a ()>, +} +impl RegisterWindow<'_> { + pub fn bytes(&self) -> usize { + self.view.bytes() + } + + /// Private native C bootstrap may borrow this exact rmmio pointer/size. + /// No Rust reference is formed, and no register is read or written. + /// + /// # Safety + /// The pointer must not escape this borrowed window's lifetime. All actual + /// accesses must use original AMDGPU register routing/width/order/reset + /// semantics. A pointer is not authority to bypass indirect/KIQ/XCC routes. + pub unsafe fn native_base(&self) -> Result, Error> { + self.view.address(0, self.bytes()).map_err(Error::Mapping) + } + + /// A checked direct DWORD location. An out-of-window register requires + /// original indirect dispatch, never a wrapped or widened MMIO access. + pub fn direct_dword(&self, register: u32) -> Result, Error> { + let offset = usize::try_from(register) + .ok() + .and_then(|r| r.checked_mul(4)) + .filter(|offset| offset.checked_add(4).is_some_and(|end| end <= self.bytes())) + .ok_or(Error::IndirectRegisterRequired)?; + let address = self.view.address(offset, 4).map_err(Error::Mapping)?; + if !(address.as_ptr() as usize).is_multiple_of(4) { + return Err(Error::InvalidRange); + } + Ok(address.cast()) + } +} + +pub struct DoorbellWindow<'a> { + view: MappingView, + _owner: PhantomData<&'a ()>, +} +impl DoorbellWindow<'_> { + pub fn bytes(&self) -> usize { + self.view.bytes() + } + + fn address(&self, index: u32, width: usize) -> Result, Error> { + let offset = usize::try_from(index) + .ok() + .and_then(|i| i.checked_mul(4)) + .ok_or(Error::InvalidRange)?; + let pointer = self.view.address(offset, width).map_err(Error::Mapping)?; + if !(pointer.as_ptr() as usize).is_multiple_of(width) { + return Err(Error::InvalidRange); + } + Ok(pointer) + } + + /// Original doorbell index is measured in DWORDs. Pointer access remains + /// unsafe and requires the original initialized ring/doorbell owner. + pub fn dword(&self, index: u32) -> Result, Error> { + self.address(index, 4).map(NonNull::cast) + } + + /// Keep the original native atomic 64-bit transaction; never synthesize + /// two DWORD doorbell writes. Both DWORDs and alignment are checked. + pub fn qword(&self, index: u32) -> Result, Error> { + self.address(index, 8).map(NonNull::cast) + } +} + +// Only actual selected Firmware admission on this same active owner can mint it. +// A path tuple, copied Identity, bare Image or manual attachment cannot do so. +pub(super) struct FileSource<'owner> { + window: RegisterWindow<'owner>, + identity: Identity, + admission: Admission, + filename: &'static core::ffi::CStr, +} +impl<'owner> FileSource<'owner> { + pub(super) fn window(&self) -> &RegisterWindow<'owner> { + &self.window + } + pub(super) fn identity(&self) -> Identity { + self.identity + } + pub(super) fn filename(&self) -> &'static core::ffi::CStr { + self.filename + } + pub(super) fn path(&self) -> IpPath { + self.admission.path() + } + pub(super) fn discovery_option(&self) -> i32 { + self.admission.discovery_option() + } + pub(super) fn hardware_ids(&self) -> (u16, u16) { + self.admission.firmware_hardware() + } + pub(super) fn revision_ids(&self) -> (u8, u16, u16) { + self.admission.firmware_revision() + } +} diff --git a/crates/stela-drivers/src/gpu/amd/pci.rs b/crates/stela-drivers/src/gpu/amd/pci.rs new file mode 100644 index 0000000000..77bf3f363d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/pci.rs @@ -0,0 +1,278 @@ +//! Original AMDGPU PCI matching and phase-specific discovery source selection. +//! This binds identity/policy to an actual borrowed PCI function; it neither +//! reserves resources nor establishes initialization, topology or GPU readiness. +use crate::bus::pci::{Address, ConfigSpace, Function}; +use core::ffi::{CStr, c_char, c_int}; + +/// Actual native build/user/platform policy corresponding to the original probe. +/// These are configuration inputs, not hardware readiness/capability booleans. +#[derive(Clone, Copy, Debug)] +pub struct Policy { + pub si_built: bool, + pub cik_built: bool, + pub radeon_built: bool, + pub si_support: i32, + pub cik_support: i32, + pub experimental: i32, + pub discovery: i32, + pub force_asic: i32, + pub memory_encrypted: bool, + pub firmware_drivers_only: bool, + pub modeset: i32, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Absent, + UnsupportedHeader, + IdentityChanged, + Native(c_int), + InvalidNativeResult, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum IpPath { + SiStatic, + CikStatic, + ViStatic, + /// Original per-ASIC versions/bases; optional discovery is inventory only. + SocStatic, + /// Original discovery consumer is required; source selection is independent. + Dynamic, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Source { + NotUsed, + Hardware, + /// Exact original preferred source; no fallback to hardware on failure. + Firmware(&'static CStr), +} +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct ConfigIdentity { + vendor: u32, + device: u32, + subvendor: u32, + subdevice: u32, + class_code: u32, + revision: u32, +} +#[repr(C)] +struct NativePolicy { + si_built: u32, + cik_built: u32, + radeon_built: u32, + si_support: i32, + cik_support: i32, + experimental: i32, + discovery: i32, + force_asic: i32, + memory_encrypted: u32, + firmware_drivers_only: u32, + modeset: i32, +} +#[repr(C)] +#[derive(Default)] +struct NativeMatch { + row: u32, + original_flags: u32, + asic_type: u32, + initial_apu_flags: u32, + ip_path: u32, + discovery_source: u32, + filename: *const c_char, +} +const _: () = assert!(size_of::() == 24); +const _: () = assert!(size_of::() == 44); +const _: () = assert!(size_of::() == 32); +const _: () = assert!(core::mem::offset_of!(NativeMatch, filename) == 24); +unsafe extern "C" { + fn stela_amd_pci_match( + identity: &ConfigIdentity, + policy: &NativePolicy, + out: &mut NativeMatch, + ) -> c_int; +} + +/// Private original result. Only actual config matching may construct this. +/// Kept with the real borrowed resource/reset owner by matched attachment. +#[derive(Clone, Copy, Debug)] +pub(super) struct Admission { + config: ConfigIdentity, + row: u32, + original_flags: u32, + asic_type: u32, + initial_apu_flags: u32, + path: IpPath, + source: Source, + discovery_option: i32, +} +impl Admission { + pub(super) fn flags(self) -> u32 { + self.original_flags + } + pub(super) fn asic(self) -> u32 { + self.asic_type + } + pub(super) fn path(self) -> IpPath { + self.path + } + pub(super) fn source(self) -> Source { + self.source + } + pub(super) fn discovery_option(self) -> i32 { + self.discovery_option + } + pub(super) fn firmware_hardware(self) -> (u16, u16) { + (self.config.vendor as u16, self.config.device as u16) + } + pub(super) fn firmware_revision(self) -> (u8, u16, u16) { + ( + self.config.revision as u8, + self.config.subvendor as u16, + self.config.subdevice as u16, + ) + } +} + +/// The original normal-table match and policy result for this exact function. +/// Borrowing prevents mutation/rebinding of its Function while this is retained. +/// Actual platform/resource exclusion remains an unsafe native-owner duty. +pub struct MatchedFunction<'function, C> { + function: &'function Function, + admission: Admission, +} +impl MatchedFunction<'_, C> { + pub fn address(&self) -> Address { + self.function.address + } + pub fn revision(&self) -> u8 { + self.admission.config.revision as u8 + } + pub fn subsystem_ids(&self) -> (u16, u16) { + ( + self.admission.config.subvendor as u16, + self.admission.config.subdevice as u16, + ) + } + pub fn matched_row(&self) -> u32 { + self.admission.row + } + pub fn original_flags(&self) -> u32 { + self.admission.original_flags + } + pub fn asic_type(&self) -> u32 { + self.admission.asic_type + } + /// Only flags established at original initial-APU stage. Modern wildcard + /// matches may be APUs; final classification follows genuine IP discovery. + pub fn initial_apu_flags(&self) -> u32 { + self.admission.initial_apu_flags + } + pub fn ip_path(&self) -> IpPath { + self.admission.path + } + pub fn source(&self) -> Source { + self.admission.source + } + pub(super) fn function(&self) -> &Function { + self.function + } + pub(super) fn admission(&self) -> Admission { + self.admission + } +} + +/// Read actual config and apply original normal-table probe/source decisions. +/// No config writes, allocation, hardware activation or firmware acquisition. +/// Linux dynamic IDs/driver_override and forced-ASIC debug paths do not produce +/// this result. Preferred files and static implementations remain explicit. +/// +/// # Safety +/// `function` is this native owner's genuine, accessible PCI function in the +/// retained device/reset epoch, with native config/reset/removal exclusion. +/// `policy` is the actual native build/user/platform policy at this probe stage; +/// memory-encryption/firmware-driver arbitration cannot be guessed to admit a +/// device. Existing native resources/firmware/PCI enable ownership is separate. +/// Keep the real owner/epoch stable through all returned dependent objects. +/// This API cannot turn a model ConfigSpace into actual hardware evidence. +pub unsafe fn identify( + function: &mut Function, + policy: Policy, +) -> Result, Error> { + let labels = (function.vendor, function.device, function.class); + let config = function.config(); + let ids = config.read32(0); + if ids as u16 == u16::MAX { + return Err(Error::Absent); + } + if config.read8(0x0e) & 0x7f != 0 { + return Err(Error::UnsupportedHeader); + } + let class_revision = config.read32(8); + let subsystem = config.read32(0x2c); + let observed = ConfigIdentity { + vendor: u32::from(ids as u16), + device: ids >> 16, + subvendor: u32::from(subsystem as u16), + subdevice: subsystem >> 16, + class_code: class_revision >> 8, + revision: class_revision & 0xff, + }; + let actual_class = [ + (class_revision >> 24) as u8, + (class_revision >> 16) as u8, + (class_revision >> 8) as u8, + ]; + if labels != (ids as u16, (ids >> 16) as u16, actual_class) { + return Err(Error::IdentityChanged); + } + let native_policy = NativePolicy { + si_built: u32::from(policy.si_built), + cik_built: u32::from(policy.cik_built), + radeon_built: u32::from(policy.radeon_built), + si_support: policy.si_support, + cik_support: policy.cik_support, + experimental: policy.experimental, + discovery: policy.discovery, + force_asic: policy.force_asic, + memory_encrypted: u32::from(policy.memory_encrypted), + firmware_drivers_only: u32::from(policy.firmware_drivers_only), + modeset: policy.modeset, + }; + let mut matched = NativeMatch::default(); + // SAFETY: exact independently asserted scalar ABI; no borrowed input retained. + let status = unsafe { stela_amd_pci_match(&observed, &native_policy, &mut matched) }; + if status != 0 { + return Err(Error::Native(status)); + } + let path = match matched.ip_path { + 0 => IpPath::SiStatic, + 1 => IpPath::CikStatic, + 2 => IpPath::ViStatic, + 3 => IpPath::SocStatic, + 4 => IpPath::Dynamic, + _ => return Err(Error::InvalidNativeResult), + }; + let source = match matched.discovery_source { + 0 if matched.filename.is_null() => Source::NotUsed, + 1 if matched.filename.is_null() => Source::Hardware, + 2 if !matched.filename.is_null() => { + // SAFETY: successful original C selector returns only its immutable + // static nul-terminated filename literal, linked for process lifetime. + Source::Firmware(unsafe { CStr::from_ptr(matched.filename) }) + } + _ => return Err(Error::InvalidNativeResult), + }; + Ok(MatchedFunction { + function, + admission: Admission { + config: observed, + row: matched.row, + original_flags: matched.original_flags, + asic_type: matched.asic_type, + initial_apu_flags: matched.initial_apu_flags, + path, + source, + discovery_option: policy.discovery, + }, + }) +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/Makefile b/crates/stela-drivers/src/gpu/amd/stela/Makefile index 11a92fef9c..b03edd370c 100644 --- a/crates/stela-drivers/src/gpu/amd/stela/Makefile +++ b/crates/stela-drivers/src/gpu/amd/stela/Makefile @@ -46,3 +46,307 @@ $(OUT_DIR)/vm_cpu.o: $(SOURCE)/vm_cpu.c $(VM_HEADERS) | $(OUT_DIR) $(OUT_DIR)/vm_cpu_uefi.obj: $(SOURCE)/vm_cpu.c $(VM_HEADERS) | $(OUT_DIR) $(CLANG) --target=x86_64-unknown-windows $(COMMON) $(CFLAGS) -ffreestanding \ -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Original BAR policy only: no PCI/MMIO access or native provider activation. +BAR_INCLUDE := -I$(SOURCE)/../../common/linux/include +BAR_HEADERS := $(SOURCE)/native_bar.h $(SOURCE)/../../common/linux/include/drm/amd_asic_type.h +BAR_INPUTS := $(SOURCE)/native_bar.c $(SOURCE)/../tests/native_bar_test.c +.PHONY: bar-test bar-sanitize bar-native bar-uefi +bar-test: $(OUT_DIR)/native_bar_test + "$<" +bar-sanitize: $(OUT_DIR)/native_bar_sanitize + ASAN_OPTIONS=detect_leaks=0 "$<" +bar-native: $(OUT_DIR)/native_bar.o + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +bar-uefi: $(OUT_DIR)/native_bar_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +$(OUT_DIR)/native_bar_test: $(BAR_INPUTS) $(BAR_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) $(BAR_INPUTS) -o "$@" +$(OUT_DIR)/native_bar_sanitize: $(BAR_INPUTS) $(BAR_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -O1 -fsanitize=address,undefined $(BAR_INPUTS) -o "$@" +$(OUT_DIR)/native_bar.o: $(SOURCE)/native_bar.c $(BAR_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -ffreestanding -fno-stack-protector \ + -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/native_bar_uefi.obj: $(SOURCE)/native_bar.c $(BAR_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows $(COMMON) $(CFLAGS) $(BAR_INCLUDE) -ffreestanding \ + -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Same original MM-index loop; CPU-only traces and actual bounded native entry. +VRAM_MM_HEADERS := $(SOURCE)/vram_mm.h $(SOURCE)/../amdgpu/amdgpu_mm_access_core.h \ + $(SOURCE)/../include/asic_reg/bif/bif_4_1_d.h +VRAM_MM_TEST := $(SOURCE)/../tests/vram_mm.c +.PHONY: vram-mm-test vram-mm-sanitize vram-mm-native vram-mm-uefi +vram-mm-test: $(OUT_DIR)/vram_mm_test + "$<" +vram-mm-sanitize: $(OUT_DIR)/vram_mm_sanitize + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" +vram-mm-native: $(OUT_DIR)/vram_mm.o + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +vram-mm-uefi: $(OUT_DIR)/vram_mm_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +$(OUT_DIR)/vram-mm-wrapper.inc: $(SOURCE)/../amdgpu/amdgpu_device.c | $(OUT_DIR) + sed -n '/^static uint32_t amdgpu_mm_access_read32(/,/^size_t amdgpu_device_aper_access(/{ /^size_t amdgpu_device_aper_access(/d; p; }' "$<" > "$@" + test -s "$@" +$(OUT_DIR)/vram-mm-instrumented.c: $(SOURCE)/vram_mm.c | $(OUT_DIR) + printf '%s\n' '#include "vram_mm_test_io.h"' > "$@" + sed -e 's/^stela_amd_vram_mm_read(/stela_amd_vram_mm_test_read(/' \ + -e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_test_io_read(pointer);/' \ + -e 's/\*pointer = value;/stela_amd_test_io_write(pointer, value);/' "$<" >> "$@" +$(OUT_DIR)/vram_mm_test: $(SOURCE)/vram_mm.c $(VRAM_MM_TEST) $(VRAM_MM_HEADERS) \ + $(SOURCE)/../tests/vram_mm_reference.h $(SOURCE)/../tests/vram_mm_test_io.h \ + $(OUT_DIR)/vram-mm-wrapper.inc $(OUT_DIR)/vram-mm-instrumented.c + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \ + $(SOURCE)/vram_mm.c $(OUT_DIR)/vram-mm-instrumented.c $(VRAM_MM_TEST) -o "$@" +$(OUT_DIR)/vram_mm_sanitize: $(SOURCE)/vram_mm.c $(VRAM_MM_TEST) $(VRAM_MM_HEADERS) \ + $(SOURCE)/../tests/vram_mm_reference.h $(SOURCE)/../tests/vram_mm_test_io.h \ + $(OUT_DIR)/vram-mm-wrapper.inc $(OUT_DIR)/vram-mm-instrumented.c + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests -O1 -fno-omit-frame-pointer \ + -fsanitize=address,undefined $(SOURCE)/vram_mm.c $(OUT_DIR)/vram-mm-instrumented.c $(VRAM_MM_TEST) -o "$@" +$(OUT_DIR)/vram_mm.o: $(SOURCE)/vram_mm.c $(VRAM_MM_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \ + -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/vram_mm_uefi.obj: $(SOURCE)/vram_mm.c $(VRAM_MM_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \ + -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Actual original TMR query, with CPU-only test I/O instrumentation. +TMR_HEADERS := $(SOURCE)/discovery_tmr.h $(SOURCE)/vram_mm.h \ + $(SOURCE)/../include/asic_reg/bif/bif_4_1_d.h \ + $(SOURCE)/../amdgpu/amdgpu_discovery_tmr_core.h \ + $(SOURCE)/../amdgpu/amdgpu_discovery_tmr_limits.h \ + $(SOURCE)/../amdgpu/amdgpu_virt_bootstrap_core.h \ + $(SOURCE)/discovery_binary.h $(SOURCE)/../include/discovery.h \ + $(SOURCE)/../amdgpu/amdgpu_ip_limits.h \ + $(SOURCE)/../../common/linux/include/uapi/linux/stddef.h \ + $(SOURCE)/../../common/linux/include/drm/amd_asic_type.h +.PHONY: tmr-test tmr-sanitize tmr-native tmr-uefi +tmr-test: $(OUT_DIR)/discovery_tmr_test + "$<" +tmr-sanitize: $(OUT_DIR)/discovery_tmr_sanitize + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" +tmr-native: $(OUT_DIR)/discovery_tmr.o + $(NM) -u "$<" >"$<.undefined" + test "$$(wc -l < "$<.undefined" | tr -d ' ')" = 1 + rg 'stela_amd_vram_mm_read' "$<.undefined" +tmr-uefi: $(OUT_DIR)/discovery_tmr_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test "$$(wc -l < "$<.undefined" | tr -d ' ')" = 1 + rg 'stela_amd_vram_mm_read' "$<.undefined" +$(OUT_DIR)/discovery-tmr-wrapper.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + sed -n '/^static uint32_t amdgpu_discovery_tmr_read32(/,/^static int amdgpu_discovery_read_binary_from_sysmem/{ /^static int amdgpu_discovery_read_binary_from_sysmem/d; p; }' "$<" > "$@" + test -s "$@" +$(OUT_DIR)/discovery-tmr-instrumented.c: $(SOURCE)/discovery_tmr.c | $(OUT_DIR) + printf '%s\n' '#include "discovery_tmr_test_io.h"' > "$@" + sed -e 's/^int stela_amd_discovery_tmr_query(/int stela_amd_discovery_tmr_test_query(/' \ + -e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_tmr_test_read(pointer);/' "$<" >> "$@" +$(OUT_DIR)/tmr-vram-instrumented.c: $(SOURCE)/vram_mm.c | $(OUT_DIR) + printf '%s\n' '#include "discovery_tmr_test_io.h"' > "$@" + sed -e 's/uint32_t value = \*pointer;/uint32_t value = stela_amd_tmr_test_read(pointer);/' \ + -e 's/\*pointer = value;/stela_amd_tmr_test_write(pointer, value);/' "$<" >> "$@" +TMR_TEST_INPUTS = $(SOURCE)/../tests/discovery_tmr.c \ + $(OUT_DIR)/discovery-tmr-instrumented.c $(OUT_DIR)/tmr-vram-instrumented.c +TMR_TEST_HEADERS := $(TMR_HEADERS) $(SOURCE)/../tests/discovery_tmr_reference.h \ + $(SOURCE)/../tests/discovery_tmr_virt_reference.h \ + $(SOURCE)/../tests/discovery_tmr_test_io.h +$(OUT_DIR)/discovery_tmr_test: $(TMR_TEST_INPUTS) $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \ + $(TMR_TEST_INPUTS) -o "$@" +$(OUT_DIR)/discovery_tmr_sanitize: $(TMR_TEST_INPUTS) $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -I$(SOURCE) -I$(SOURCE)/../tests \ + -O1 -fno-omit-frame-pointer -fsanitize=address,undefined $(TMR_TEST_INPUTS) -o "$@" +$(OUT_DIR)/discovery_tmr.o: $(SOURCE)/discovery_tmr.c $(TMR_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \ + -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/discovery_tmr_uefi.obj: $(SOURCE)/discovery_tmr.c $(TMR_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \ + -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Test-only same-process canonical RAM fixture objects; never linked in a driver. +.PHONY: tmr-ram-model +tmr-ram-model: $(OUT_DIR)/tmr-model.o $(OUT_DIR)/tmr-query-model.o \ + $(OUT_DIR)/tmr-vram-model.o $(OUT_DIR)/tmr-fixture.o $(OUT_DIR)/tmr-binary.o +$(OUT_DIR)/tmr-model.o: $(SOURCE)/../tests/discovery_tmr.c $(TMR_TEST_HEADERS) $(OUT_DIR)/discovery-tmr-wrapper.inc + $(CC) $(COMMON) $(CFLAGS) -DSTELA_TMR_RUST_MODEL -I$(OUT_DIR) -c "$<" -o "$@" +$(OUT_DIR)/tmr-query-model.o: $(OUT_DIR)/discovery-tmr-instrumented.c $(TMR_HEADERS) + $(CC) $(COMMON) $(CFLAGS) -I$(SOURCE) -I$(SOURCE)/../tests \ + -Dstela_amd_discovery_tmr_test_query=stela_amd_discovery_tmr_query -c "$<" -o "$@" +$(OUT_DIR)/tmr-vram-model.o: $(OUT_DIR)/tmr-vram-instrumented.c $(VRAM_MM_HEADERS) + $(CC) $(COMMON) $(CFLAGS) -I$(SOURCE) -I$(SOURCE)/../tests -c "$<" -o "$@" +$(OUT_DIR)/tmr-fixture.o: $(SOURCE)/../tests/discovery_tmr_fixture.c \ + $(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h $(TMR_HEADERS) + $(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@" +$(OUT_DIR)/tmr-binary.o: $(SOURCE)/discovery_binary.c $(TMR_HEADERS) $(SOURCE)/../include/soc15_hw_ip.h | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@" + +# Immutable discovery snapshots only; optional external files are CPU fixtures. +DISCOVERY_INPUTS ?= +DISCOVERY_HEADERS := $(SOURCE)/discovery_binary.h $(SOURCE)/../include/discovery.h \ + $(SOURCE)/../amdgpu/amdgpu_ip_limits.h $(SOURCE)/../include/soc15_hw_ip.h \ + $(SOURCE)/../../common/linux/include/uapi/linux/stddef.h +DISCOVERY_SOURCES := $(SOURCE)/discovery_binary.c $(SOURCE)/../tests/discovery_binary_test.c +DISCOVERY_TEST_HEADERS := $(DISCOVERY_HEADERS) $(SOURCE)/../tests/discovery_reference.h +.PHONY: discovery-test discovery-sanitize discovery-native discovery-uefi +discovery-test: $(OUT_DIR)/discovery_binary_test + "$<" $(DISCOVERY_INPUTS) +discovery-sanitize: $(OUT_DIR)/discovery_binary_sanitize + ASAN_OPTIONS=detect_leaks=0 "$<" $(DISCOVERY_INPUTS) +discovery-native: $(OUT_DIR)/discovery_binary.o + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +discovery-uefi: $(OUT_DIR)/discovery_binary_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +$(OUT_DIR)/discovery_binary_test: $(DISCOVERY_SOURCES) $(DISCOVERY_TEST_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -Wno-unused-function -fwrapv $(DISCOVERY_SOURCES) -o "$@" +$(OUT_DIR)/discovery_binary_sanitize: $(DISCOVERY_SOURCES) $(DISCOVERY_TEST_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -Wno-unused-function -fwrapv -O1 -fno-omit-frame-pointer \ + -fsanitize=address,undefined $(DISCOVERY_SOURCES) -o "$@" +$(OUT_DIR)/discovery_binary.o: $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector \ + -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/discovery_binary_uefi.obj: $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding \ + -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Compile the actual retained live-read function, not a copied replacement. +# Only acquisition/OS context is a bounded CPU model in the test fixture. +.PHONY: discovery-refresh-test discovery-refresh-sanitize +discovery-refresh-test: $(OUT_DIR)/discovery_refresh_test + "$<" +discovery-refresh-sanitize: $(OUT_DIR)/discovery_refresh_sanitize + ASAN_OPTIONS=detect_leaks=0 "$<" +$(OUT_DIR)/discovery-refresh.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + sed -n '/^static int amdgpu_discovery_refresh_nps_info(/,/^int amdgpu_discovery_get_nps_info(/{ /^int amdgpu_discovery_get_nps_info(/d; p; }' "$<" > "$@" + test -s "$@" +$(OUT_DIR)/discovery_refresh_test: $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) $(OUT_DIR)/discovery-refresh.inc + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c -o "$@" +$(OUT_DIR)/discovery_refresh_sanitize: $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c $(DISCOVERY_HEADERS) $(OUT_DIR)/discovery-refresh.inc + $(CC) $(COMMON) $(CFLAGS) -I$(OUT_DIR) -O1 -fsanitize=address,undefined $(SOURCE)/../tests/discovery_refresh_test.c $(SOURCE)/discovery_binary.c -o "$@" + +# Original PCI normal-table admission and source policy; no config/MMIO effects. +PCI_HEADERS := $(SOURCE)/pci_match.h $(SOURCE)/../amdgpu/amdgpu_pci_match_core.h \ + $(SOURCE)/../amdgpu/amdgpu_apu_flags_core.h $(SOURCE)/../amdgpu/amdgpu_discovery_source_core.h \ + $(SOURCE)/../include/amd_chip_flags.h \ + $(SOURCE)/../../common/linux/include/drm/amd_asic_type.h \ + $(SOURCE)/../../common/linux/include/linux/device-id/pci.h \ + $(SOURCE)/../../common/linux/include/linux/pci_ids.h +# Original table shorthand/ARRAY_SIZE conventions, as in the Linux consumer. +PCI_FLAGS := -Wno-missing-field-initializers -Wno-sign-compare +.PHONY: pci-test pci-sanitize pci-native pci-uefi +pci-test: $(OUT_DIR)/pci_match_test + "$<" +pci-sanitize: $(OUT_DIR)/pci_match_sanitize + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" +pci-native: $(OUT_DIR)/pci_match.o + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +pci-uefi: $(OUT_DIR)/pci_match_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test ! -s "$<.undefined" +$(OUT_DIR)/pci-linux-wrappers.inc: $(SOURCE)/../amdgpu/amdgpu_drv.c $(SOURCE)/../amdgpu/amdgpu_device.c $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + sed -n '/^static unsigned long amdgpu_fix_asic_type(/,/^static int amdgpu_pci_probe(/{ /^static int amdgpu_pci_probe(/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_drv.c" > "$@" + sed -n '/^static int amdgpu_device_init_apu_flags(/,/^\/\*\*/{ /^\/\*\*/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_device.c" >> "$@" + sed -n '/^static const char \*amdgpu_discovery_get_fw_name(/,/^static int amdgpu_discovery_get_table_info(/{ /^static int amdgpu_discovery_get_table_info(/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_discovery.c" >> "$@" + test -s "$@" +$(OUT_DIR)/pci_match_test: $(SOURCE)/../tests/pci_match.c $(SOURCE)/../tests/pci_reference.h $(SOURCE)/pci_match.c $(PCI_HEADERS) $(OUT_DIR)/pci-linux-wrappers.inc $(OUT_DIR)/pci-linux-paths.inc | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -I$(OUT_DIR) "$<" -o "$@" +$(OUT_DIR)/pci_match_sanitize: $(SOURCE)/../tests/pci_match.c $(SOURCE)/../tests/pci_reference.h $(SOURCE)/pci_match.c $(PCI_HEADERS) $(OUT_DIR)/pci-linux-wrappers.inc $(OUT_DIR)/pci-linux-paths.inc | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -I$(OUT_DIR) -O1 -fno-omit-frame-pointer -fsanitize=address,undefined "$<" -o "$@" +$(OUT_DIR)/pci_match.o: $(SOURCE)/pci_match.c $(PCI_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) $(PCI_FLAGS) -ffreestanding -fno-stack-protector \ + -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/pci_match_uefi.obj: $(SOURCE)/pci_match.c $(PCI_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) $(PCI_FLAGS) -ffreestanding \ + -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/pci-linux-paths.inc: $(SOURCE)/../amdgpu/amdgpu_device.c $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + printf '%s\n' 'static int linux_initial_path(struct amdgpu_device *adev) {' 'int r;' > "$@" + sed -n '/switch (amdgpu_initial_ip_path(/,/Check for IP version/{ /Check for IP version/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_device.c" >> "$@" + printf '%s\n' 'return 0;' '}' 'static int linux_discovery_path(struct amdgpu_device *adev) {' 'int r;' >> "$@" + sed -n '/switch (amdgpu_discovery_static_asic(/,/amdgpu_discovery_init_soc_config(adev)/{ /amdgpu_discovery_init_soc_config(adev)/d; p; }' "$(SOURCE)/../amdgpu/amdgpu_discovery.c" >> "$@" + printf '%s\n' 'return 0;' '}' >> "$@" + +IP_HEADERS := $(SOURCE)/discovery_ip.h $(SOURCE)/discovery_binary.h \ + $(SOURCE)/../amdgpu/amdgpu_discovery_ip_core.h $(SOURCE)/../amdgpu/amdgpu_ip_types.h \ + $(SOURCE)/../amdgpu/amdgpu_ip_instance_limits.h $(SOURCE)/../amdgpu/amdgpu_ip_limits.h \ + $(SOURCE)/../include/discovery.h $(SOURCE)/../include/soc15_hw_ip.h +.PHONY: ip-test ip-sanitize ip-native ip-uefi +ip-test: $(OUT_DIR)/discovery_ip_test + "$<" $(IP_INPUTS) +ip-sanitize: $(OUT_DIR)/discovery_ip_sanitize + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" $(IP_INPUTS) +ip-native: $(OUT_DIR)/discovery_ip.o + $(NM) -u "$<" >"$<.undefined" + test $$(wc -l <"$<.undefined") -eq 2 + rg 'amdgpu_discovery_binary_(table|validate)' "$<.undefined" +ip-uefi: $(OUT_DIR)/discovery_ip_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test $$(wc -l <"$<.undefined") -eq 2 + rg 'amdgpu_discovery_binary_(table|validate)' "$<.undefined" +$(OUT_DIR)/discovery-ip-linux.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + sed -n '/^static void amdgpu_discovery_ip_debug(/,/^static uint32_t amdgpu_discovery_tmr_read32(/{ /^static uint32_t amdgpu_discovery_tmr_read32(/d; p; }' "$<" > "$@" + sed -n '/^static int amdgpu_discovery_validate_ip(/,/^static void amdgpu_discovery_read_harvest_bit_per_ip(/{ /^static void amdgpu_discovery_read_harvest_bit_per_ip(/d; p; }' "$<" >> "$@" + sed -n '/^static int amdgpu_discovery_reg_base_init(/,/^static void amdgpu_discovery_harvest_ip(/{ /^static void amdgpu_discovery_harvest_ip(/d; p; }' "$<" >> "$@" +IP_TEST_SOURCES := $(SOURCE)/discovery_ip.c $(SOURCE)/discovery_binary.c \ + $(SOURCE)/../tests/discovery_ip.c $(SOURCE)/../tests/discovery_ip_fixture.c +IP_TEST_DEPS := $(IP_HEADERS) $(SOURCE)/../tests/discovery_ip_reference.h \ + $(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h \ + $(OUT_DIR)/discovery-ip-linux.inc +$(OUT_DIR)/discovery_ip_test: $(IP_TEST_SOURCES) $(IP_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -Wno-sign-compare -I$(OUT_DIR) $(IP_TEST_SOURCES) -o "$@" +$(OUT_DIR)/discovery_ip_sanitize: $(IP_TEST_SOURCES) $(IP_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -O1 -fwrapv -fno-omit-frame-pointer -fsanitize=address,undefined -Wno-sign-compare -I$(OUT_DIR) $(IP_TEST_SOURCES) -o "$@" +$(OUT_DIR)/discovery_ip.o: $(SOURCE)/discovery_ip.c $(IP_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/discovery_ip_uefi.obj: $(SOURCE)/discovery_ip.c $(IP_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -fwrapv -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +# Test-only independent frozen consumer for the canonical owned-source harness. +# Never linked into the production driver archive or used as a provider. +.PHONY: ip-ram-model +ip-ram-model: $(OUT_DIR)/ip-oracle.o $(OUT_DIR)/ip-fixture.o +$(OUT_DIR)/ip-oracle.o: $(IP_TEST_SOURCES) $(IP_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -Wno-sign-compare -DSTELA_IP_RUST_MODEL \ + -Dmain=stela_amd_ip_test_main -I$(OUT_DIR) -c "$(SOURCE)/../tests/discovery_ip.c" -o "$@" +$(OUT_DIR)/ip-fixture.o: $(SOURCE)/../tests/discovery_ip_fixture.c $(DISCOVERY_TEST_HEADERS) \ + $(SOURCE)/../tests/discovery_binary_test.c | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -c "$<" -o "$@" + +FILE_HEADERS := $(SOURCE)/discovery_file.h $(SOURCE)/../amdgpu/amdgpu_discovery_file_core.h $(DISCOVERY_HEADERS) +FILE_SOURCES := $(SOURCE)/discovery_file.c $(SOURCE)/discovery_binary.c \ + $(SOURCE)/../tests/discovery_file.c $(SOURCE)/../tests/discovery_ip_fixture.c +FILE_TEST_DEPS := $(FILE_HEADERS) $(SOURCE)/../tests/discovery_file_reference.h \ + $(SOURCE)/../tests/discovery_binary_test.c $(SOURCE)/../tests/discovery_reference.h \ + $(OUT_DIR)/discovery-file-linux.inc +.PHONY: file-test file-sanitize file-native file-uefi +file-test: $(OUT_DIR)/discovery_file_test + "$<" $(FILE_INPUTS) +file-sanitize: $(OUT_DIR)/discovery_file_sanitize + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$<" $(FILE_INPUTS) +file-native: $(OUT_DIR)/discovery_file.o + $(NM) -u "$<" >"$<.undefined" + test $$(wc -l <"$<.undefined") -eq 1 + rg 'amdgpu_discovery_binary_validate' "$<.undefined" +file-uefi: $(OUT_DIR)/discovery_file_uefi.obj + $(NM) -u "$<" >"$<.undefined" + test $$(wc -l <"$<.undefined") -eq 1 + rg 'amdgpu_discovery_binary_validate' "$<.undefined" +$(OUT_DIR)/discovery-file-linux.inc: $(SOURCE)/../amdgpu/amdgpu_discovery.c | $(OUT_DIR) + sed -n '/^static int amdgpu_discovery_read_binary_from_file(/,/^static inline bool amdgpu_discovery_verify_checksum(/{ /^static inline bool amdgpu_discovery_verify_checksum(/d; p; }' "$<" > "$@" +$(OUT_DIR)/discovery_file_test: $(FILE_SOURCES) $(FILE_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -I$(OUT_DIR) $(FILE_SOURCES) -o "$@" +$(OUT_DIR)/discovery_file_sanitize: $(FILE_SOURCES) $(FILE_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -O1 -fno-omit-frame-pointer -fsanitize=address,undefined -I$(OUT_DIR) $(FILE_SOURCES) -o "$@" +$(OUT_DIR)/discovery_file.o: $(SOURCE)/discovery_file.c $(FILE_HEADERS) | $(OUT_DIR) + $(CC) $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" +$(OUT_DIR)/discovery_file_uefi.obj: $(SOURCE)/discovery_file.c $(FILE_HEADERS) | $(OUT_DIR) + $(CLANG) --target=x86_64-unknown-windows-gnu $(COMMON) $(CFLAGS) -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only -c "$<" -o "$@" + +.PHONY: file-ram-model +file-ram-model: $(OUT_DIR)/file-oracle.o +$(OUT_DIR)/file-oracle.o: $(FILE_SOURCES) $(FILE_TEST_DEPS) + $(CC) $(COMMON) $(CFLAGS) -fwrapv -Dmain=stela_amd_file_test_main \ + -I$(OUT_DIR) -c "$(SOURCE)/../tests/discovery_file.c" -o "$@" diff --git a/crates/stela-drivers/src/gpu/amd/stela/air_compile.c b/crates/stela-drivers/src/gpu/amd/stela/air_compile.c new file mode 100644 index 0000000000..eb572fac53 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/air_compile.c @@ -0,0 +1,419 @@ +/* SPDX-License-Identifier: MIT */ +#include "air_compile.h" +#include "amd/common/ac_binary.h" +#include "amd/common/nir/ac_nir.h" +#include "amd/compiler/aco_interface.h" +#include "util/ralloc.h" +#include +#include +#include + +#define MAX_TEXT 4096u /* Same bounded reflection strings as library assembly. */ +#define MAX_CODE (64u * 1024u * 1024u) + +struct stela_amd_air_compilation { + struct stela_amd_compute_binary binary; + struct stela_amd_air_provenance provenance; + nir_shader_compiler_options nir_options; + struct ac_shader_args args; + struct ac_shader_config config; + struct stela_amd_air_binding bindings[STELA_AMD_AIR_MAX_BUFFERS]; + uint32_t binding_count; + void *metadata; + uint8_t *code; + bool type_reference, captured; + enum stela_amd_air_status capture_status; +}; + +static enum stela_amd_air_status +report(struct stela_amd_air_error *error, enum stela_amd_air_status status, + const char *detail) +{ + if (error) { + error->status = status; + snprintf(error->detail, sizeof(error->detail), "%s", detail); + } + return status; +} + +void +stela_amd_air_destroy(struct stela_amd_air_compilation **slot) +{ + if (!slot || !*slot) + return; + struct stela_amd_air_compilation *owner = *slot; + *slot = NULL; + ralloc_free((void *)owner->binary.shader); + if (owner->type_reference) + glsl_type_singleton_decref(); + free(owner->code); + free(owner->metadata); + free(owner); +} + +static bool +text_valid(const char *text, size_t length) +{ + return length <= MAX_TEXT && (!length || (text && !memchr(text, 0, length))); +} + +static char * +copy_text(char **cursor, const void *text, size_t length) +{ + if (!text) + return NULL; + char *result = *cursor; + if (length) + memcpy(result, text, length); + result[length] = 0; + *cursor += length + 1; + return result; +} + +static enum stela_amd_air_status +copy_provenance(struct stela_amd_air_compilation *owner, + const struct stela_metal_library_manifest *manifest, + const struct stela_metal_function_record *record, uint32_t selected, + struct stela_amd_air_error *error) +{ + if (!text_valid((const char *)record->name, record->name_bytes) || !record->name_bytes || + !text_valid((const char *)manifest->target, manifest->target_bytes) || !manifest->target_bytes || + record->argument_count > AIR_MAX_ARGUMENTS || + (record->argument_count && !record->arguments)) + return report(error, STELA_AMD_AIR_INVALID, "Unrepresentable selected entry metadata"); + size_t bytes = record->argument_count * sizeof(struct stela_air_argument_info) + + (size_t)record->name_bytes + (size_t)manifest->target_bytes + 2; + for (unsigned i = 0; i < record->argument_count; i++) { + const struct stela_air_argument_info *arg = &record->arguments[i]; + if (!text_valid(arg->name, arg->name_bytes) || !text_valid(arg->type_name, arg->type_name_bytes)) + return report(error, STELA_AMD_AIR_INVALID, "Unrepresentable argument strings"); + bytes += arg->name_bytes + arg->type_name_bytes + 2; + } + /* All additions are bounded by 128 arguments and 4096 bytes/string. */ + owner->metadata = malloc(bytes); + if (!owner->metadata) + return report(error, STELA_AMD_AIR_ALLOCATION, "Selected metadata allocation failed"); + struct stela_air_argument_info *args = owner->metadata; + char *cursor = (char *)(args + record->argument_count); + struct stela_amd_air_provenance *p = &owner->provenance; + p->input = manifest->input; + p->entry = record->entry; + p->selected_entry = selected; + p->entry_flags = record->flags; + p->library_flags = manifest->flags; + p->compiler_profile = manifest->compiler_profile; + p->request_language = manifest->request_language; + p->request_fast_math = manifest->request_fast_math; + p->build = manifest->build; + p->air_offset = record->air_offset; + p->air_bytes = record->air_bytes; + memcpy(p->air_sha256, record->air_sha256, 32); + memcpy(p->source_sha256, manifest->source_sha256, 32); + p->name = copy_text(&cursor, record->name, (size_t)record->name_bytes); + p->target = copy_text(&cursor, manifest->target, (size_t)manifest->target_bytes); + p->argument_count = record->argument_count; + p->arguments = args; + for (unsigned i = 0; i < record->argument_count; i++) { + args[i] = record->arguments[i]; + args[i].name = copy_text(&cursor, args[i].name, args[i].name_bytes); + args[i].type_name = copy_text(&cursor, args[i].type_name, args[i].type_name_bytes); + } + return STELA_AMD_AIR_OK; +} + +static enum stela_amd_air_status +prepare_args(struct stela_amd_air_compilation *owner, const struct radeon_info *info, + struct stela_amd_air_error *error) +{ + for (unsigned i = 0; i < owner->provenance.argument_count; i++) { + const struct stela_air_argument_info *arg = &owner->provenance.arguments[i]; + if (arg->kind == 2) + continue; /* Existing AIR frontend validates/lower the actual builtin. */ + if (arg->kind == 1 && arg->buffer.address_space == 3 && arg->plain_buffer_type) continue; + if (arg->kind != 1 || arg->buffer.address_space != 1 || !arg->plain_buffer_type) + return report(error, STELA_AMD_AIR_UNSUPPORTED, "Resource requires an unsupported binding specialization"); + if (owner->binding_count == STELA_AMD_AIR_MAX_BUFFERS) + return report(error, STELA_AMD_AIR_UNSUPPORTED, "More than eight AS1 address pairs"); + struct stela_amd_air_binding *binding = &owner->bindings[owner->binding_count++]; + binding->buffer = arg->buffer; + ac_add_arg(&owner->args, AC_ARG_SGPR, 2, AC_ARG_CONST_ADDR, &binding->argument); + } + for (unsigned axis = 0; axis < 3; axis++) { + if (info->gfx_level >= GFX12) + owner->args.workgroup_ids[axis].used = true; + else + ac_add_arg(&owner->args, AC_ARG_SGPR, 1, AC_ARG_VALUE, &owner->args.workgroup_ids[axis]); + } + if (info->gfx_level < GFX11) + ac_add_arg(&owner->args, AC_ARG_SGPR, 1, AC_ARG_VALUE, &owner->args.scratch_offset); + if (info->compiler_info.local_invocation_ids_packed) { + ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_ids_packed); + } else { + ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_x); + ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_y); + ac_add_arg(&owner->args, AC_ARG_VGPR, 1, AC_ARG_VALUE, &owner->args.local_invocation_id_z); + } + if (owner->args.num_sgprs_used > info->compiler_info.max_sgpr_alloc || + owner->args.num_vgprs_used > info->compiler_info.max_vgpr_alloc) + return report(error, STELA_AMD_AIR_UNSUPPORTED, "Argument layout exceeds actual device register limits"); + return STELA_AMD_AIR_OK; +} + +static nir_def * +bind_buffer(nir_builder *b, const struct stela_air_buffer *buffer, void *data) +{ + struct stela_amd_air_compilation *owner = data; + for (unsigned i = 0; i < owner->binding_count; i++) { + const struct stela_amd_air_binding *binding = &owner->bindings[i]; + if (binding->buffer.argument == buffer->argument && + binding->buffer.index == buffer->index && + binding->buffer.address_space == buffer->address_space && + binding->buffer.access == buffer->access && + binding->buffer.type_size == buffer->type_size && + binding->buffer.type_alignment == buffer->type_alignment) + return nir_pack_64_2x32(b, ac_nir_load_arg(b, &owner->args, binding->argument)); + } + return NULL; +} + +static bool +compiler_facts_valid(const struct radeon_info *info, unsigned wave) +{ + const struct ac_compiler_info *c = &info->compiler_info; + unsigned scale = wave == 32 ? 2 : 1; + /* Original ACO init_program stores these in uint16_t and doubles the + * physical VGPR count/allocation grain for wave32. Grains are NOT generally + * powers of two (e.g. SGPR108, VGPR12). Check before those conversions and + * the allocator's original division/alignment helpers. These are necessary + * representation checks, not authentication of caller-created device info. */ + return c->max_waves_per_simd && c->max_waves_per_simd <= UINT16_MAX && + c->num_simd_per_compute_unit && + c->num_physical_sgprs_per_simd && c->num_physical_sgprs_per_simd <= UINT16_MAX && + c->num_physical_wave64_vgprs_per_simd && c->num_physical_wave64_vgprs_per_simd <= UINT16_MAX / scale && + c->min_sgpr_alloc && c->min_sgpr_alloc <= c->max_sgpr_alloc && + c->max_sgpr_alloc <= c->num_physical_sgprs_per_simd && + c->sgpr_alloc_granularity && c->sgpr_alloc_granularity <= c->max_sgpr_alloc && + c->min_wave64_vgpr_alloc && c->min_wave64_vgpr_alloc <= c->max_vgpr_alloc && + c->max_vgpr_alloc <= c->num_physical_wave64_vgprs_per_simd && c->max_vgpr_alloc <= UINT16_MAX && + c->wave64_vgpr_alloc_granularity && c->wave64_vgpr_alloc_granularity <= UINT16_MAX / scale && + c->wave64_vgpr_encode_granularity && c->wave64_vgpr_encode_granularity <= c->max_vgpr_alloc && + c->lds_size_per_workgroup && c->lds_size_per_workgroup <= (info->gfx_level >= GFX7 ? 65536u : 32768u); +} + +static void +capture(void **private, const struct ac_shader_config *config, + const char *ir, unsigned ir_bytes, const char *assembly, unsigned assembly_bytes, + struct amd_stats *stats, uint32_t executable_bytes, const uint32_t *code, + uint32_t code_dw, const struct aco_symbol *symbols, unsigned symbol_count, + const struct ac_shader_debug_info *debug, unsigned debug_count) +{ + (void)ir; (void)ir_bytes; (void)assembly; (void)assembly_bytes; (void)stats; + (void)symbols; (void)debug; (void)debug_count; + struct stela_amd_air_compilation *owner = *private; + if (owner->captured || !config || !code || !code_dw || !executable_bytes || + code_dw > UINT32_MAX / 4 || executable_bytes > code_dw * 4 || executable_bytes % 4) { + owner->capture_status = STELA_AMD_AIR_BACKEND; + return; + } + owner->captured = true; + if (symbol_count) { + owner->capture_status = STELA_AMD_AIR_UNSUPPORTED; + return; + } + if (code_dw * 4 > owner->provenance.options.max_code_bytes) { + owner->capture_status = STELA_AMD_AIR_LIMIT; + return; + } + owner->code = malloc((size_t)code_dw * 4); + if (!owner->code) { + owner->capture_status = STELA_AMD_AIR_ALLOCATION; + return; + } + memcpy(owner->code, code, (size_t)code_dw * 4); + owner->config = *config; + owner->binary.executable_bytes = executable_bytes; + owner->binary.code_bytes = code_dw * 4; +} + +static bool bind_threadgroup(const struct stela_air_buffer *buffer, + struct stela_air_threadgroup_view *view, void *data) +{ + const struct stela_amd_air_compilation *owner = data; + const struct stela_metal_threadgroup_specialization *shared = &owner->provenance.threadgroup; + for (unsigned i = 0; i < shared->count; i++) { + const struct stela_metal_threadgroup_binding *binding = &shared->bindings[i]; + const struct stela_air_buffer *b = &binding->buffer; + if (b->argument == buffer->argument && b->index == buffer->index && + b->address_space == buffer->address_space && b->access == buffer->access && + b->type_size == buffer->type_size && b->type_alignment == buffer->type_alignment) { + *view = (struct stela_air_threadgroup_view){.size = binding->bytes, + .alignment = binding->alignment, .available_access = STELA_AIR_READ_WRITE}; + return true; + } + } + return false; +} +enum stela_amd_air_status +stela_amd_air_compile(const struct radeon_info *info, const struct stela_metal_assembly *library, + uint32_t selected, const struct stela_amd_air_options *options, + struct stela_amd_air_compilation **output, struct stela_amd_air_error *error) +{ + return stela_amd_air_compile_specialized(info, library, selected, options, NULL, output, error); +} +enum stela_amd_air_status +stela_amd_air_compile_specialized(const struct radeon_info *info, const struct stela_metal_assembly *library, + uint32_t selected, const struct stela_amd_air_options *options, + const struct stela_metal_threadgroup_request *request, + struct stela_amd_air_compilation **output, struct stela_amd_air_error *error) +{ + if (error) + memset(error, 0, sizeof(*error)); + if (!info || !library || !options || !output || *output || + options->size != sizeof(*options) || options->abi != STELA_AMD_AIR_ABI) + return report(error, STELA_AMD_AIR_INVALID, "Invalid local compiler ownership/ABI"); + if (!options->max_instructions || !options->max_code_bytes || options->max_code_bytes > MAX_CODE) + return report(error, STELA_AMD_AIR_LIMIT, "Explicit nonzero compiler/code budgets required"); + if ((options->wave_size != 32 && options->wave_size != 64) || + (options->fp_profile != STELA_AIR_FP_IEEE_DEFAULT && + options->fp_profile != STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41)) + return report(error, STELA_AMD_AIR_UNSUPPORTED, "Unsupported wave/FP profile"); + if (info->family < CHIP_TAHITI || info->family >= CHIP_LAST || + ac_get_gfx_level(info->family) != info->gfx_level || !aco_is_gpu_supported(info) || + (options->wave_size == 32 && info->gfx_level < GFX10)) + return report(error, STELA_AMD_AIR_UNSUPPORTED, "Target requires a different retained backend"); + struct stela_amd_raw_buffer_facts facts; + if (stela_amd_query_raw_buffer_facts(info, &facts) != STELA_AMD_BUFFER_OK || + !compiler_facts_valid(info, options->wave_size)) + return report(error, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE, "Actual initialized device/compiler facts required"); + const struct stela_metal_library_manifest *manifest = stela_metal_assembly_manifest(library); + if (!manifest || selected >= manifest->entry_count) + return report(error, STELA_AMD_AIR_INVALID, "Selected entry outside canonical library"); + const struct stela_metal_function_record *record = &manifest->entries[selected]; + struct stela_metal_input_view original = {.size = sizeof(original), .abi = STELA_METAL_INPUT_ABI}; + if (stela_metal_assembly_original(library, &original, NULL) != STELA_METAL_ASSEMBLY_OK || + record->air_offset > original.length || record->air_bytes > original.length - record->air_offset || + !record->air_bytes || record->air_bytes > AIR_MAX_BITCODE_BYTES) + return report(error, STELA_AMD_AIR_INVALID, "Invalid retained raw AIR span"); + struct stela_metal_threadgroup_specialization threadgroup; + enum stela_metal_threadgroup_status shared_status = stela_metal_threadgroup_normalize( + record->arguments, record->argument_count, request, info->compiler_info.lds_size_per_workgroup, &threadgroup); + if (shared_status != STELA_METAL_THREADGROUP_OK) + return report(error, shared_status == STELA_METAL_THREADGROUP_INVALID ? STELA_AMD_AIR_INVALID : + shared_status == STELA_METAL_THREADGROUP_LIMIT ? STELA_AMD_AIR_LIMIT : STELA_AMD_AIR_UNSUPPORTED, + "Resource requires a supported threadgroup binding specialization"); + struct stela_amd_air_compilation *owner = calloc(1, sizeof(*owner)); + if (!owner) + return report(error, STELA_AMD_AIR_ALLOCATION, "Compilation owner allocation failed"); + owner->provenance.options = *options; owner->provenance.threadgroup = threadgroup; + owner->provenance.compiler_info = info->compiler_info; + owner->provenance.pci_id = info->pci_id; + owner->provenance.pci_rev_id = info->pci_rev_id; + owner->provenance.has_graphics = info->has_graphics; + ac_nir_set_options(&info->compiler_info, false, &owner->nir_options); + uint64_t threads = 1; + for (unsigned axis = 0; axis < 3; axis++) { + unsigned count = options->workgroup_size[axis]; + if (!count || count > owner->nir_options.max_workgroup_invocations || + threads > owner->nir_options.max_workgroup_invocations / count) { + stela_amd_air_destroy(&owner); + return report(error, STELA_AMD_AIR_UNSUPPORTED, "Invalid/unsupported workgroup specialization"); + } + threads *= count; + } + enum stela_amd_air_status status = copy_provenance(owner, manifest, record, selected, error); + if (status == STELA_AMD_AIR_OK) + status = prepare_args(owner, info, error); + if (status != STELA_AMD_AIR_OK) { + stela_amd_air_destroy(&owner); + return status; + } + glsl_type_singleton_init_or_ref(); + owner->type_reference = true; + struct stela_air_options air = { + .workgroup_size = {options->workgroup_size[0], options->workgroup_size[1], options->workgroup_size[2]}, + .max_instructions = options->max_instructions, .bind_buffer = bind_buffer, + .binding_data = owner, .fp_profile = options->fp_profile, + .bind_threadgroup = threadgroup.count ? bind_threadgroup : NULL, + .max_threadgroup_bytes = info->compiler_info.lds_size_per_workgroup, + }; + struct stela_air_error air_error; + nir_shader *shader = stela_air_to_nir(original.bytes + record->air_offset, + (size_t)record->air_bytes, owner->provenance.name, &owner->nir_options, &air, &air_error); + if (!shader) { + if (error) + error->air = air_error; + stela_amd_air_destroy(&owner); + return report(error, STELA_AMD_AIR_FRONTEND, "Shared AIR frontend refused selected body/policy"); + } + owner->binary = (struct stela_amd_compute_binary) { + .shader = shader, .args = &owner->args, .config = &owner->config, + .family = info->family, .gfx_level = info->gfx_level, .wave_size = options->wave_size, + }; + const ac_nir_lower_intrinsics_to_args_options arg_options = { + .gfx_level = info->gfx_level, .hw_stage = AC_HW_COMPUTE_SHADER, + .wave_size = options->wave_size, .workgroup_size = (unsigned)threads, + }; + ac_nir_lower_intrinsics_to_args(shader, &owner->args, &arg_options); + ac_nir_lower_global_access(shader, info->gfx_level); + nir_lower_int64(shader); + bool progress; + do { + progress = nir_opt_constant_folding(shader); + progress |= nir_opt_copy_prop(shader); + progress |= nir_opt_algebraic(shader); + progress |= nir_opt_dce(shader); + } while (progress); + nir_lower_alu_width(shader, ac_nir_opt_vectorize_cb, &owner->binary.gfx_level); + nir_lower_load_const_to_scalar(shader); + nir_opt_copy_prop(shader); + nir_opt_dce(shader); + nir_shader_gather_info(shader, nir_shader_get_entrypoint(shader)); + nir_validate_shader(shader, "owned AIR to AMD compute ABI"); + const struct aco_compiler_options aco_options = { + .compiler_info = &info->compiler_info, .family = info->family, .gfx_level = info->gfx_level, + }; + const struct aco_shader_info aco_info = { + .hw_stage = AC_HW_COMPUTE_SHADER, + .lds_size = shader->info.shared_size, + .wave_size = (uint8_t)options->wave_size, + .workgroup_size = (unsigned)threads, + }; + void *private = owner; + aco_compile_shader(&aco_options, &aco_info, 1, &shader, &owner->args, capture, &private); + owner->provenance.aco_codegen_flags = aco_get_codegen_flags(); + status = owner->capture_status; + if (status == STELA_AMD_AIR_OK && (!owner->captured || !owner->code || !owner->config.num_vgprs)) + status = STELA_AMD_AIR_BACKEND; + if (status != STELA_AMD_AIR_OK) { + stela_amd_air_destroy(&owner); + return report(error, status, "Vendor output unavailable, unresolved, over budget or allocation failed"); + } + *output = owner; + return report(error, STELA_AMD_AIR_OK, ""); +} + +const struct stela_amd_compute_binary * +stela_amd_air_binary(const struct stela_amd_air_compilation *owner) +{ + return owner ? &owner->binary : NULL; +} + +const uint8_t * +stela_amd_air_code(const struct stela_amd_air_compilation *owner) +{ + return owner ? owner->code : NULL; +} + +const struct stela_amd_air_binding * +stela_amd_air_bindings(const struct stela_amd_air_compilation *owner, uint32_t *count) +{ + if (count) + *count = owner ? owner->binding_count : 0; + return owner ? owner->bindings : NULL; +} + +const struct stela_amd_air_provenance * +stela_amd_air_provenance(const struct stela_amd_air_compilation *owner) +{ + return owner ? &owner->provenance : NULL; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/air_compile.h b/crates/stela-drivers/src/gpu/amd/stela/air_compile.h new file mode 100644 index 0000000000..84faffe6f9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/air_compile.h @@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_AIR_COMPILE_H +#define STELA_AMD_AIR_COMPILE_H + +#include "compute.h" +#include "../../metal/compiler/library_assembly.h" +#include "stela/air_to_nir.h" +#include "../../metal/compiler/threadgroup.h" +#include "amd/common/ac_gpu_info.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define STELA_AMD_AIR_ABI 1u +#define STELA_AMD_AIR_MAX_BUFFERS 8u + +enum stela_amd_air_status { + STELA_AMD_AIR_OK, + STELA_AMD_AIR_INVALID, + STELA_AMD_AIR_UNSUPPORTED, + STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE, + STELA_AMD_AIR_LIMIT, + STELA_AMD_AIR_ALLOCATION, + STELA_AMD_AIR_FRONTEND, + STELA_AMD_AIR_BACKEND, +}; + +struct stela_amd_air_options { + uint32_t size, abi; + uint32_t wave_size, workgroup_size[3], max_instructions, max_code_bytes; + enum stela_air_fp_profile fp_profile; +}; + +struct stela_amd_air_error { + enum stela_amd_air_status status; + struct stela_air_error air; + char detail[256]; +}; + +/* Ordered as the actual user SGPR pairs consumed by compute.c. Metadata keeps + * Metal index, LLVM argument ordinal, required access and reflected alignment; + * neither a buffer VA nor a caller-created permission boolean is compiled in. + * At dispatch, the real resource owner must supply matching views/rights, + * lifetime, VM, residency and cache ordering through completion. */ +struct stela_amd_air_binding { + struct stela_air_buffer buffer; + struct ac_arg argument; +}; + +/* Immutable same-process facts, not an IPC/cache wire format. All strings and + * argument reflection below are copied from the selected canonical assembly. + * Input/module/raw offsets and hashes retain their original distinct scopes. + * Zero archive source/build fields remain absent; an FP policy NEVER fabricates + * source compiler provenance. The compiler/input owner must independently + * qualify the nondefault AIR FP profile, as required by air_to_nir.h. */ +struct stela_amd_air_provenance { + struct stela_metal_input_info input; + struct stela_metal_input_entry entry; + uint32_t selected_entry, entry_flags, library_flags, compiler_profile; + uint32_t request_language, request_fast_math, argument_count; + uint64_t air_offset, air_bytes; + uint8_t air_sha256[32], source_sha256[32]; + struct stela_msl_build_identity build; + const char *name, *target; + const struct stela_air_argument_info *arguments; + struct stela_amd_air_options options; + struct ac_compiler_info compiler_info; + uint32_t pci_id, pci_rev_id; + bool has_graphics; + uint64_t aco_codegen_flags; + struct stela_metal_threadgroup_specialization threadgroup; +}; + +struct stela_amd_air_compilation; + +/* Normal hosted compiler process only. info MUST be the actual initialized + * device/compiler facts from the matching retained Mesa build, not a family + * guessed from an Apple CPU or a test topology. This routine validates facts it + * consumes but cannot authenticate a caller-created radeon_info. Input owner, + * options and info are borrowed through this synchronous call only. No LLVM, + * assembly, options or device pointer survives success. + * + * Only ordinary AS1 buffer arguments (up to the existing eight address pairs), + * current shared frontend bodies and ACO-supported targets are admitted. Dynamic + * AS3 arguments require compile_specialized with exact requested byte lengths. + * Qualified static shared storage uses original NIR/ACO lowering + * if admitted by the canonical library owner. No function-constant overrides, + * descriptor/sampler/image ABI or compiler fallback is invented. + * + * Output MUST point to an empty sole-owning slot; every failure preserves it. + * Error is optional complete writable storage. All input/output/error storage + * must be valid, disjoint, and serialized against destruction/mutation. This + * wrapper reports its own allocation failures, not recovery from fatal/OOM + * inside LLVM/Mesa/ACO; the normal compiler-process owner supplies cancellation, + * watchdog and crash isolation. No global fault handler is installed. + */ +/* Exact dispatch-size specialization; existing compile() delegates with NULL. + * Request arrays are borrowed only during the call and copied into provenance. + * Backend shared totals include these rows plus static layout, never expose + * them as Metal staticThreadgroupMemoryLength or add dynamic bytes twice. + * stela_metal_threadgroup_matches checks values only, not resource ownership. */ +enum stela_amd_air_status stela_amd_air_compile_specialized( + const struct radeon_info *info, const struct stela_metal_assembly *library, + uint32_t selected_entry, const struct stela_amd_air_options *options, + const struct stela_metal_threadgroup_request *threadgroup, + struct stela_amd_air_compilation **output, struct stela_amd_air_error *error); + +enum stela_amd_air_status stela_amd_air_compile( + const struct radeon_info *info, const struct stela_metal_assembly *library, + uint32_t selected_entry, const struct stela_amd_air_options *options, + struct stela_amd_air_compilation **output, struct stela_amd_air_error *error); + +/* Borrowed immutable views last until the unique owner is destroyed. The code + * view covers complete code/data; binary.executable_bytes excludes trailing + * constants. Stable NIR/options/args/config backing makes binary usable by the + * existing stela_amd_build_compute_pipeline, once the real code/resource owner + * supplies the SAME initialized device/compiler facts and published allocation + * views. That owner retains device identity/epoch: these C pointers are not a + * replacement for its authenticated session or lifetime. Scratch/LDS + * requirements are actual compiler results, NOT resource readiness or a Metal + * pipeline state. No upload, relocation, allocation, submission or GPU access + * occurs here. Symbols currently refuse, rather than escaping unresolved. */ +const struct stela_amd_compute_binary *stela_amd_air_binary( + const struct stela_amd_air_compilation *owner); +const uint8_t *stela_amd_air_code(const struct stela_amd_air_compilation *owner); +const struct stela_amd_air_binding *stela_amd_air_bindings( + const struct stela_amd_air_compilation *owner, uint32_t *count); +const struct stela_amd_air_provenance *stela_amd_air_provenance( + const struct stela_amd_air_compilation *owner); +void stela_amd_air_destroy(struct stela_amd_air_compilation **owner); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/compute.c b/crates/stela-drivers/src/gpu/amd/stela/compute.c index 2e7f435332..1a73bf4608 100644 --- a/crates/stela-drivers/src/gpu/amd/stela/compute.c +++ b/crates/stela-drivers/src/gpu/amd/stela/compute.c @@ -92,7 +92,7 @@ stela_amd_build_compute_pipeline(const struct radeon_info *info, struct stela_amd_compute_pipeline *pipeline) { if (!info || !binary || !binary->shader || !binary->args || !binary->config || - !code || !pipeline || !bindings || !binding_count || binding_count > 8) + !code || !pipeline || (binding_count && !bindings) || binding_count > 8) return STELA_AMD_COMPUTE_INVALID; struct stela_amd_raw_buffer_facts facts; enum stela_amd_compute_status status = diff --git a/crates/stela-drivers/src/gpu/amd/stela/compute.h b/crates/stela-drivers/src/gpu/amd/stela/compute.h index a47b96942e..7423de7809 100644 --- a/crates/stela-drivers/src/gpu/amd/stela/compute.h +++ b/crates/stela-drivers/src/gpu/amd/stela/compute.h @@ -54,7 +54,9 @@ struct stela_amd_compute_binding { * code is its real, published code allocation/view with sufficient retained * prefetch padding and 256-byte program alignment. No allocation, upload, * shader replacement, cache flush, device initialization or submission occurs. - * Missing scratch/descriptor/sampler owners remain explicit refusals. + * Zero buffer bindings are valid when the actual argument layout requires no + * user address pairs; bindings may then be NULL. Missing required bindings or + * scratch/descriptor/sampler owners remain explicit refusals. * Output is unchanged on every error. */ enum stela_amd_compute_status diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.c b/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.c new file mode 100644 index 0000000000..2d950f5320 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.c @@ -0,0 +1,331 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "discovery_binary.h" +#include "../amdgpu/amdgpu_ip_limits.h" +#include "../include/soc15_hw_ip.h" + +_Static_assert(sizeof(struct binary_header) == 60, "original fixed directory ABI"); +_Static_assert(sizeof(struct binary_header_v2) == 16, "original variable directory ABI"); +_Static_assert(sizeof(struct ip_discovery_header) == 80, "original die directory ABI"); +_Static_assert(offsetof(struct ip_v4, base_address) == 8, "original IP32 prefix ABI"); +_Static_assert(offsetof(struct ip_v4, base_address_64) == 8, "original IP64 prefix ABI"); + +/* Original function body; const qualification only tightens the shared API. + * Preserve its signed loop exactly; validated callers bound size to u16. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +uint16_t amdgpu_discovery_calculate_checksum(const uint8_t *data, uint32_t size) +{ + uint16_t checksum = 0; + int i; + + for (i = 0; i < size; i++) + checksum += data[i]; + + return checksum; +} + +#pragma GCC diagnostic pop + +static uint16_t read16(const void *pointer) +{ + const uint8_t *p = pointer; + return (uint16_t)p[0] | (uint16_t)p[1] << 8; +} + +static uint32_t read32(const void *pointer) +{ + const uint8_t *p = pointer; + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | + (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} + +#define FIELD16(p, type, field) read16((p) + offsetof(struct type, field)) +#define FIELD32(p, type, field) read32((p) + offsetof(struct type, field)) + +static int fits(size_t bytes, size_t offset, size_t count) +{ + return offset <= bytes && count <= bytes - offset; +} + +/* Share directory geometry with bounded live refresh, without pretending a + * stack prefix contains the variable directory's trailing entries. */ +enum amdgpu_discovery_binary_status +amdgpu_discovery_binary_directory(const uint8_t *binary, size_t prefix_bytes, + size_t available_bytes, uint16_t id, + struct amdgpu_discovery_directory *output) +{ + if (!binary || !output) + return AMDGPU_DISCOVERY_BINARY_INVALID; + if (!fits(prefix_bytes, 0, offsetof(struct binary_header, table_list))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + size_t size = FIELD16(binary, binary_header, binary_size); + if (size > available_bytes) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + size_t offset, count; + switch (FIELD16(binary, binary_header, version_major)) { + case 0: + case 1: + offset = offsetof(struct binary_header, table_list); + count = TOTAL_TABLES; + break; + case 2: + if (!fits(prefix_bytes, 0, sizeof(struct binary_header_v2))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + offset = offsetof(struct binary_header_v2, table_list); + count = FIELD16(binary, binary_header_v2, num_tables); + break; + default: + return AMDGPU_DISCOVERY_BINARY_VERSION; + } + if (id >= count || !fits(size, offset, count * sizeof(struct table_info))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + *output = (struct amdgpu_discovery_directory){ + size, offset + count * sizeof(struct table_info), offset + id * sizeof(struct table_info) + }; + return AMDGPU_DISCOVERY_BINARY_OK; +} + +const struct table_info * +amdgpu_discovery_binary_table(const uint8_t *binary, size_t bytes, uint16_t id) +{ + struct amdgpu_discovery_directory directory; + if (amdgpu_discovery_binary_directory(binary, bytes, bytes, id, &directory)) + return NULL; + return (const struct table_info *)(binary + directory.entry_offset); +} + +struct span { + size_t offset, bytes; +}; + +static int disjoint(struct span a, struct span b) +{ + return a.offset + a.bytes <= b.offset || b.offset + b.bytes <= a.offset; +} + +static enum amdgpu_discovery_binary_status +ip_spans(const uint8_t *binary, struct span table, unsigned *umc_count) +{ + const uint8_t *header = binary + table.offset; + unsigned dies = FIELD16(header, ip_discovery_header, num_dies); + const struct ip_discovery_header *original = (const void *)header; + int wide = original->base_addr_64_bit; + if (dies > sizeof(original->die_info) / sizeof(original->die_info[0]) || + (wide && FIELD16(header, ip_discovery_header, version) < 4)) + return AMDGPU_DISCOVERY_BINARY_INVALID; + struct span previous[sizeof(original->die_info) / sizeof(original->die_info[0])]; + for (unsigned i = 0; i < dies; i++) { + const uint8_t *entry = header + offsetof(struct ip_discovery_header, die_info) + + i * sizeof(struct die_info); + size_t die = FIELD16(entry, die_info, die_offset); + if (die < table.offset + sizeof(struct ip_discovery_header) || + !fits(table.offset + table.bytes, die, sizeof(struct die_header))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + const uint8_t *dhdr = binary + die; + if (FIELD16(dhdr, die_header, die_id) != i) + return AMDGPU_DISCOVERY_BINARY_INVALID; + unsigned ips = FIELD16(dhdr, die_header, num_ips); + size_t position = die + sizeof(struct die_header); + for (unsigned j = 0; j < ips; j++) { + if (!fits(table.offset + table.bytes, position, + offsetof(struct ip_v4, base_address))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + const struct ip_v4 *ip = (const void *)(binary + position); + size_t bytes = offsetof(struct ip_v4, base_address) + + ip->num_base_address * (wide ? sizeof(uint64_t) : sizeof(uint32_t)); + if (!fits(table.offset + table.bytes, position, bytes)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + unsigned id = read16(&ip->hw_id); + /* Original validate_ip skips unknown/out-of-array IPs. Preserve that + * policy, but validate every entry's stride before the next walk. */ + if (ip->instance_number < HWIP_MAX_INSTANCE && id < HW_ID_MAX) { + if ((id == GC_HWID || id == VCN_HWID || id == SDMA0_HWID || + id == SDMA1_HWID || id == SDMA2_HWID || id == SDMA3_HWID) && + ip->instance_number >= 32) + return AMDGPU_DISCOVERY_BINARY_INVALID; + if (id == UMC_HWID) + (*umc_count)++; + } + position += bytes; + } + previous[i] = (struct span){die, position - die}; + for (unsigned k = 0; k < i; k++) { + if (!disjoint(previous[i], previous[k])) + return AMDGPU_DISCOVERY_BINARY_INVALID; + } + } + /* Original harvest mask computes (1ULL << node_inst_num) - 1. */ + return *umc_count < 64 ? AMDGPU_DISCOVERY_BINARY_OK : AMDGPU_DISCOVERY_BINARY_INVALID; +} + +static enum amdgpu_discovery_binary_status +consumer_span(const uint8_t *data, size_t size, unsigned id) +{ + size_t minimum = 0; + if (id == GC) { + if (!fits(size, 0, sizeof(struct gpu_info_header))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + unsigned major = FIELD16(data, gpu_info_header, version_major); + unsigned minor = FIELD16(data, gpu_info_header, version_minor); + if (major == 1) { + minimum = minor >= 3 ? sizeof(struct gc_info_v1_3) : + minor == 2 ? sizeof(struct gc_info_v1_2) : + minor == 1 ? sizeof(struct gc_info_v1_1) : sizeof(struct gc_info_v1_0); + if (!fits(size, 0, minimum)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + if (!FIELD32(data, gc_info_v1_0, gc_num_sa_per_se)) + return AMDGPU_DISCOVERY_BINARY_INVALID; + } else if (major == 2) { + minimum = minor == 1 ? sizeof(struct gc_info_v2_1) : sizeof(struct gc_info_v2_0); + if (!fits(size, 0, minimum)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + if (!FIELD32(data, gc_info_v2_0, gc_num_sh_per_se)) + return AMDGPU_DISCOVERY_BINARY_INVALID; + } + } else if (id == MALL_INFO) { + unsigned major = FIELD16(data, mall_info_header, version_major); + minimum = major == 1 ? sizeof(struct mall_info_v1_0) : + major == 2 ? sizeof(struct mall_info_v2_0) : sizeof(struct mall_info_header); + } else if (id == VCN_INFO) { + minimum = FIELD16(data, vcn_info_header, version_major) == 1 ? + sizeof(struct vcn_info_v1_0) : sizeof(struct vcn_info_header); + } + return fits(size, 0, minimum) ? AMDGPU_DISCOVERY_BINARY_OK : AMDGPU_DISCOVERY_BINARY_BOUNDS; +} + +enum amdgpu_discovery_binary_status +amdgpu_discovery_binary_validate(const uint8_t *binary, size_t bytes) +{ + if (!binary) + return AMDGPU_DISCOVERY_BINARY_INVALID; + if (!fits(bytes, 0, offsetof(struct binary_header, table_list))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + if (FIELD32(binary, binary_header, binary_signature) != BINARY_SIGNATURE) + return AMDGPU_DISCOVERY_BINARY_INVALID; + unsigned version = FIELD16(binary, binary_header, version_major); + if (version > 2) + return AMDGPU_DISCOVERY_BINARY_VERSION; + size_t size = FIELD16(binary, binary_header, binary_size); + size_t checksum_start = offsetof(struct binary_header, binary_checksum) + sizeof(uint16_t); + if (size < checksum_start || size > bytes) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + if (amdgpu_discovery_calculate_checksum(binary + checksum_start, size - checksum_start) != + FIELD16(binary, binary_header, binary_checksum)) + return AMDGPU_DISCOVERY_BINARY_CHECKSUM; + if (!amdgpu_discovery_binary_table(binary, size, MALL_INFO)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + size_t directory = version == 2 ? offsetof(struct binary_header_v2, table_list) + + FIELD16(binary, binary_header_v2, num_tables) * sizeof(struct table_info) : + sizeof(struct binary_header); + struct span tables[TOTAL_TABLES] = {{0}}; + unsigned umc_count = 0; + for (unsigned id = IP_DISCOVERY; id < TOTAL_TABLES; id++) { + const struct table_info *info = amdgpu_discovery_binary_table(binary, size, id); + if (!info) /* Optional NPS may be absent from a v2 counted directory. */ + continue; + size_t offset = read16(&info->offset); + if (!offset) { + if (id == IP_DISCOVERY) + return AMDGPU_DISCOVERY_BINARY_INVALID; + continue; + } + if (offset < directory || !fits(size, offset, sizeof(struct gpu_info_header))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + const uint8_t *data = binary + offset; + size_t length; + uint32_t expected, actual; + int checksum = 1; + switch (id) { + case IP_DISCOVERY: + actual = FIELD32(data, ip_discovery_header, signature); + expected = DISCOVERY_TABLE_SIGNATURE; + length = FIELD16(data, ip_discovery_header, size); + break; + case GC: + actual = FIELD32(data, gpu_info_header, table_id); + expected = GC_TABLE_ID; + length = FIELD32(data, gpu_info_header, size); + break; + case HARVEST_INFO: + actual = FIELD32(data, harvest_info_header, signature); + expected = HARVEST_TABLE_SIGNATURE; + length = sizeof(struct harvest_table); + break; + case VCN_INFO: + actual = FIELD32(data, vcn_info_header, table_id); + expected = VCN_INFO_TABLE_ID; + length = FIELD32(data, vcn_info_header, size_bytes); + break; + case MALL_INFO: + /* Original policy deliberately does not check MALL integrity. */ + actual = expected = 0; + length = FIELD32(data, mall_info_header, size_bytes); + checksum = 0; + break; + default: /* Original NPS integrity check is lazy and nonfatal. */ + actual = FIELD32(data, nps_info_header, table_id); + expected = actual; + length = actual == NPS_INFO_TABLE_ID ? FIELD32(data, nps_info_header, size_bytes) : + sizeof(struct nps_info_header); + checksum = 0; + break; + } + if (!fits(size, offset, length) || length < sizeof(struct gpu_info_header)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + if (checksum && (actual != expected)) + return AMDGPU_DISCOVERY_BINARY_INVALID; + if (checksum && amdgpu_discovery_calculate_checksum(data, length) != read16(&info->checksum)) + return AMDGPU_DISCOVERY_BINARY_CHECKSUM; + if (id == IP_DISCOVERY) { + if (length < sizeof(struct ip_discovery_header)) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + enum amdgpu_discovery_binary_status status = ip_spans(binary, (struct span){offset, length}, + &umc_count); + if (status) + return status; + } else if (id == NPS_INFO && actual == NPS_INFO_TABLE_ID && + amdgpu_discovery_calculate_checksum(data, length) == read16(&info->checksum) && + FIELD16(data, nps_info_header, version_major) == 1) { + if (length < offsetof(struct nps_info_v1_0, instance_info) || + FIELD32(data, nps_info_v1_0, count) > NPS_INFO_TABLE_MAX_NUM_INSTANCES || + !fits(length, offsetof(struct nps_info_v1_0, instance_info), + FIELD32(data, nps_info_v1_0, count) * sizeof(struct nps_instance_info_v1_0))) + return AMDGPU_DISCOVERY_BINARY_BOUNDS; + } else { + enum amdgpu_discovery_binary_status status = consumer_span(data, length, id); + if (status) + return status; + if (id == MALL_INFO && FIELD16(data, mall_info_header, version_major) == 1 && umc_count > 32) + return AMDGPU_DISCOVERY_BINARY_INVALID; + } + tables[id] = (struct span){offset, length}; + for (unsigned previous = 0; previous < id; previous++) { + if (tables[previous].bytes && !disjoint(tables[id], tables[previous])) + return AMDGPU_DISCOVERY_BINARY_INVALID; + } + } + return AMDGPU_DISCOVERY_BINARY_OK; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.h b/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.h new file mode 100644 index 0000000000..279fc11a8a --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_binary.h @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#ifndef STELA_AMD_DISCOVERY_BINARY_H +#define STELA_AMD_DISCOVERY_BINARY_H + +#ifdef __KERNEL__ +#include +#include +#else +#include +#include +#endif +#include "../include/discovery.h" + +enum amdgpu_discovery_binary_status { + AMDGPU_DISCOVERY_BINARY_OK, + AMDGPU_DISCOVERY_BINARY_INVALID, + AMDGPU_DISCOVERY_BINARY_BOUNDS, + AMDGPU_DISCOVERY_BINARY_VERSION, + AMDGPU_DISCOVERY_BINARY_CHECKSUM, +}; + +/* Original additive checksum algorithm. Every byte must be readable; size is + * bounded by INT_MAX. The full validator establishes its own stronger u16 span. + */ +uint16_t amdgpu_discovery_calculate_checksum(const uint8_t *data, uint32_t size); + +/* Directory geometry from the original fixed/v2-counted header. A bounded + * prefix is sufficient; available_bytes is the actual acquired region size. + * This neither reads an entry nor validates a table/checksum. Failure leaves + * the output unchanged. Live acquisition must retain its real reset owner. */ +struct amdgpu_discovery_directory { + size_t binary_bytes, directory_bytes, entry_offset; +}; +enum amdgpu_discovery_binary_status +amdgpu_discovery_binary_directory(const uint8_t *prefix, size_t prefix_bytes, + size_t available_bytes, uint16_t id, + struct amdgpu_discovery_directory *output); + +/* Checked original directory selection only, not full binary validation. + * The returned original format pointer borrows the actual snapshot's lifetime; + * NULL means malformed directory, missing table or unsupported binary version. + */ +const struct table_info * +amdgpu_discovery_binary_table(const uint8_t *binary, size_t bytes, uint16_t id); + +/* Validate a real readable immutable acquisition snapshot before original + * driver consumers run. No allocation, register/memory acquisition, device + * mutation, capability inference or hardware activation occurs here. + * + * Caller owns the actual TMR/firmware snapshot and excludes concurrent mutation + * throughout validation and handoff. Original reg-base initialization then + * intentionally mutates its private copy (endian/address conversion and VCN + * revision masking); the preflight does not authorize revalidation of that + * modified copy or concurrent untrusted access. Actual firmware/TMR ownership, + * device binding, VRAM/ACPI acquisition and original consumer lifecycle remain + * required. Optional NPS integrity policy remains lazy in the original caller. + */ +enum amdgpu_discovery_binary_status +amdgpu_discovery_binary_validate(const uint8_t *binary, size_t bytes); + +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_file.c b/crates/stela-drivers/src/gpu/amd/stela/discovery_file.c new file mode 100644 index 0000000000..329cdc2b9c --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_file.c @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: MIT */ +#include "discovery_file.h" +#include "../amdgpu/amdgpu_discovery_file_core.h" +int stela_amd_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity) +{ + return amdgpu_discovery_file_validate(data, bytes, capacity); +} +size_t stela_amd_discovery_file_minimum(void) +{ + return offsetof(struct binary_header, binary_size) + + sizeof(((struct binary_header *)0)->binary_size); +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_file.h b/crates/stela-drivers/src/gpu/amd/stela/discovery_file.h new file mode 100644 index 0000000000..edc54020db --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_file.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_DISCOVERY_FILE_H +#define STELA_AMD_DISCOVERY_FILE_H +#include +#include +/* Same status values as original shared bounded-file policy. Actual immutable + * readable file allocation only; capacity is the real queried TMR extent. + * No acquisition/admission/copy/allocator; no pointer retained or bytes changed. */ +size_t stela_amd_discovery_file_minimum(void); +int stela_amd_discovery_file_validate(const uint8_t *data, size_t bytes, uint32_t capacity); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.c b/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.c new file mode 100644 index 0000000000..b03a303487 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.c @@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: MIT */ +#include "discovery_ip.h" +#include "discovery_binary.h" +#include "../amdgpu/amdgpu_discovery_ip_core.h" + +_Static_assert(sizeof(int) == sizeof(int32_t), "original int fields"); +_Static_assert(sizeof(struct stela_amd_ip_binding) == 8, "IP binding ABI"); +_Static_assert(sizeof(struct stela_amd_ip_counts) == 32, "IP counts ABI"); +_Static_assert(offsetof(struct stela_amd_ip_counts, sdma_count) == 12, "IP int ABI"); +_Static_assert(offsetof(struct stela_amd_ip_counts, node_count) == 28, "IP node ABI"); +_Static_assert(AMDGPU_MAX_VCN_INSTANCES == 4, "explicit VCN configuration ABI"); + +struct stela_amd_ip_shape stela_amd_discovery_ip_shape(void) +{ + return (struct stela_amd_ip_shape){MAX_HWIP, HWIP_MAX_INSTANCE}; +} +struct binding_context { uintptr_t base; struct stela_amd_ip_binding *bindings; }; +static void bind(void *context, unsigned hw_ip, unsigned instance, uint32_t *base, unsigned count) +{ + struct binding_context *c = context; + /* Validated original geometry and private callback guarantee same allocation. + * Convert pointer representation only; never dereference packed u32*. */ + c->bindings[hw_ip * HWIP_MAX_INSTANCE + instance] = + (struct stela_amd_ip_binding){(uint32_t)((uintptr_t)base - c->base), count}; +} +static int range(const void *pointer, size_t bytes, uintptr_t *start, uintptr_t *end) +{ + *start = (uintptr_t)pointer; + if (!pointer || bytes > UINTPTR_MAX - *start) + return 0; + *end = *start + bytes; + return 1; +} +int stela_amd_discovery_ip_decode(uint8_t *work, size_t bytes, + uint32_t *versions, size_t version_count, + struct stela_amd_ip_binding *bindings, size_t binding_count, + struct stela_amd_ip_counts *counts) +{ + const size_t cells = MAX_HWIP * HWIP_MAX_INSTANCE; + uintptr_t start[4], end[4]; + if (version_count < cells || binding_count < cells || + (uintptr_t)versions % _Alignof(uint32_t) || + (uintptr_t)bindings % _Alignof(struct stela_amd_ip_binding) || + (uintptr_t)counts % _Alignof(struct stela_amd_ip_counts) || + !range(work, bytes, &start[0], &end[0]) || + !range(versions, cells * sizeof(*versions), &start[1], &end[1]) || + !range(bindings, cells * sizeof(*bindings), &start[2], &end[2]) || + !range(counts, sizeof(*counts), &start[3], &end[3])) + return -EINVAL; + for (unsigned i = 0; i < 4; i++) + for (unsigned j = i + 1; j < 4; j++) + if (start[i] < end[j] && start[j] < end[i]) + return -EINVAL; + int status = amdgpu_discovery_binary_validate(work, bytes); + if (status) + return -EINVAL; + const struct table_info *info = amdgpu_discovery_binary_table(work, bytes, IP_DISCOVERY); + if (!info) + return -EINVAL; + struct ip_discovery_header *ihdr = (void *)(work + le16_to_cpu(info->offset)); + /* All bounds/errors complete before the first output/working-copy write. */ + *counts = (struct stela_amd_ip_counts){0}; + for (size_t i = 0; i < cells; i++) { + versions[i] = 0; + bindings[i] = (struct stela_amd_ip_binding){UINT32_MAX, 0}; + } + struct binding_context context = {(uintptr_t)work, bindings}; + struct amdgpu_discovery_ip_targets targets = { + .xcc_mask=&counts->xcc_mask, .sdma_mask=&counts->sdma_mask, + .vcn_mask=&counts->vcn_mask, .jpeg_mask=&counts->jpeg_mask, + .vcn_count=&counts->vcn_count, .sdma_count=&counts->sdma_count, + .vpe_count=&counts->vpe_count, .umc_count=&counts->umc_count, + .node_count=&counts->node_count, + .ip_versions=(uint32_t (*)[HWIP_MAX_INSTANCE])versions, + }; + for (unsigned i = 0; i < AMDGPU_MAX_VCN_INSTANCES; i++) + targets.vcn_config[i] = &counts->vcn_config[i]; + const struct amdgpu_discovery_ip_ops ops = {.context=&context, .bind=bind}; + /* Validated die IDs/geometry make the original walk's only failure + * unreachable; no success/failure hardware hook or allocator exists. */ + return amdgpu_discovery_ip_walk(work, ihdr, &targets, &ops); +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.h b/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.h new file mode 100644 index 0000000000..f04616f294 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_ip.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_DISCOVERY_IP_H +#define STELA_AMD_DISCOVERY_IP_H +#include +#include +struct stela_amd_ip_binding { uint32_t offset, count; }; +struct stela_amd_ip_counts { + uint16_t xcc_mask, vcn_mask, jpeg_mask; + uint8_t vcn_count, vcn_config[4]; + int32_t sdma_count; + uint32_t sdma_mask, vpe_count; + int32_t umc_count; + uint32_t node_count; +}; +struct stela_amd_ip_shape { uint32_t hw_ip_count, instances; }; +struct stela_amd_ip_shape stela_amd_discovery_ip_shape(void); +/* One validated fresh private copy, run once. Not an acquisition/admission API. + * No pointer retained. All arrays are real disjoint CPU allocations. Error + * leaves work/output bytes untouched. Counts correspond to the original fresh + * zeroed device, before harvest/final topology. No device services performed. */ +int stela_amd_discovery_ip_decode(uint8_t *work, size_t bytes, + uint32_t *versions, size_t version_count, + struct stela_amd_ip_binding *bindings, size_t binding_count, + struct stela_amd_ip_counts *counts); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.c b/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.c new file mode 100644 index 0000000000..d0d71e9919 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.c @@ -0,0 +1,93 @@ +/* SPDX-License-Identifier: MIT */ +#include "discovery_tmr.h" +#include "discovery_binary.h" +#include "vram_mm.h" +#include "../include/asic_reg/bif/bif_4_1_d.h" +#include "../amdgpu/amdgpu_discovery_tmr_core.h" +#include "../amdgpu/amdgpu_virt_bootstrap_core.h" +#include +_Static_assert(sizeof(struct stela_amd_discovery_tmr) == 24, "TMR ABI"); +_Static_assert(offsetof(struct stela_amd_discovery_tmr, size) == 16, "TMR size ABI"); +struct native_tmr { + void *registers; + size_t bytes; + uint64_t vram_bytes; + void *sleep_context; + void (*sleep_ms)(void *, unsigned); +}; +static uint32_t read32(void *context, uint32_t reg) +{ + struct native_tmr *native = context; + volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)native->registers + reg * 4u); + atomic_signal_fence(memory_order_seq_cst); + uint32_t value = *pointer; + atomic_signal_fence(memory_order_seq_cst); + if (reg == mmRCC_CONFIG_MEMSIZE) + native->vram_bytes = (uint64_t)value << 20; + return value; +} +static void sleep_ms(void *context, unsigned milliseconds) +{ + struct native_tmr *native = context; + native->sleep_ms(native->sleep_context, milliseconds); +} +static int read_vram(void *context, uint64_t offset, uint32_t *data, size_t size) +{ + struct native_tmr *native = context; + return stela_amd_vram_mm_read(native->registers, native->bytes, + native->vram_bytes, offset, data, size) == STELA_AMD_VRAM_MM_OK + ? STELA_AMD_TMR_OK : STELA_AMD_TMR_BOUNDS; +} +static int acpi_tmr(void *context, uint64_t *offset, uint64_t *size) +{ + (void)context; (void)offset; (void)size; + /* Explicit missing actual ACPI/firmware owner, not a fabricated reply. */ + return STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE; +} +static bool direct_register(size_t bytes, uint32_t reg) +{ + return reg < bytes / sizeof(uint32_t); +} +int stela_amd_discovery_tmr_query(void *registers, size_t register_bytes, + uint32_t asic_type, void *sleep_context, + void (*sleep)(void *, unsigned), struct stela_amd_discovery_tmr *out) +{ + uintptr_t base = (uintptr_t)registers, destination = (uintptr_t)out; + if (!registers || base % sizeof(uint32_t) || !out || destination % _Alignof(struct stela_amd_discovery_tmr) || + !sleep || asic_type >= CHIP_LAST) + return STELA_AMD_TMR_INVALID; + if (register_bytes > PTRDIFF_MAX || register_bytes > UINTPTR_MAX - base || + sizeof(*out) > UINTPTR_MAX - destination || + (destination < base + register_bytes && base < destination + sizeof(*out))) + return STELA_AMD_TMR_BOUNDS; + uint32_t identifier = 0; + bool has_identifier = amdgpu_virt_bootstrap_iov_register(asic_type, &identifier); + const uint32_t required[] = {mmMP0_SMN_C2PMSG_33, mmRCC_CONFIG_MEMSIZE, + mmDRIVER_SCRATCH_0, mmDRIVER_SCRATCH_1, mmDRIVER_SCRATCH_2, + mmMM_INDEX, mmMM_DATA, mmMM_INDEX_HI}; + for (unsigned i = 0; i < sizeof(required) / sizeof(required[0]); ++i) + if (!direct_register(register_bytes, required[i])) + return STELA_AMD_TMR_BOUNDS; + if (has_identifier && !direct_register(register_bytes, identifier)) + return STELA_AMD_TMR_BOUNDS; + struct native_tmr native = {registers, register_bytes, 0, sleep_context, sleep}; + /* This is the original selector's actual hardware observation, not a guessed + * role from flags or a caller boolean. VF protocols remain original owners. */ + if (has_identifier && (read32(&native, identifier) & 1)) + return STELA_AMD_TMR_VF_OWNER_UNAVAILABLE; + static const struct amdgpu_discovery_tmr_ops ops = {read32, sleep_ms, read_vram, acpi_tmr}; + struct amdgpu_discovery_tmr_state state = {0}; + int status = amdgpu_discovery_tmr_query_core(&ops, &native, false, false, 0, 0, &state); + if (status) + return status; + if (state.is_sysmem) + return STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE; + if (!state.size || state.size % sizeof(uint32_t) || state.offset % sizeof(uint32_t) || + state.offset > native.vram_bytes || state.size > native.vram_bytes - state.offset) + return STELA_AMD_TMR_BOUNDS; + const struct stela_amd_discovery_tmr result = { + .offset = state.offset, .vram_bytes = native.vram_bytes, .size = state.size, + }; + *out = result; + return STELA_AMD_TMR_OK; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.h b/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.h new file mode 100644 index 0000000000..bbc38d19a9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/discovery_tmr.h @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_DISCOVERY_TMR_H +#define STELA_AMD_DISCOVERY_TMR_H +#include +#include +struct stela_amd_discovery_tmr { + uint64_t offset, vram_bytes; + uint32_t size, reserved; +}; +enum stela_amd_discovery_tmr_status { + STELA_AMD_TMR_OK = 0, + STELA_AMD_TMR_INVALID = 1, + STELA_AMD_TMR_BOUNDS = 2, + STELA_AMD_TMR_VF_OWNER_UNAVAILABLE = 3, + STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE = 4, +}; +/* Borrow the same actual canonical UC register mapping, matched original ASIC, + * D0/reset/removal/MM-index/IRQ exclusion and process context as vram_mm.h. + * The original discovery caller must have selected this bootstrap path; no + * SI/CIK/VI admission or preferred-file policy is inferred here. sleep_ms is + * mandatory real elapsed-time service, not an immediate/success callback. + * Actual direct register/owner/service bounds are checked before first I/O. + * Output unchanged on every error. Negative values are original errno status. + * A successful region is GPU VRAM, never a system physical/DMA/IOVA address. + * It is not a reservation, BO, firmware integrity or readiness proof. + * Real system-memory/VF owners are unavailable here and explicitly refused. + * After original reads/index writes there is no rollback; returned void reads + * carry no transport ACK. No pointer is retained. Output is exclusive CPU RAM, + * distinct from the register span, and all callbacks retain the same owner. + */ +int stela_amd_discovery_tmr_query(void *registers, size_t register_bytes, + uint32_t asic_type, void *sleep_context, + void (*sleep_ms)(void *, unsigned), struct stela_amd_discovery_tmr *out); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/native_bar.c b/crates/stela-drivers/src/gpu/amd/stela/native_bar.c new file mode 100644 index 0000000000..47cff50f31 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/native_bar.c @@ -0,0 +1,48 @@ +/* SPDX-License-Identifier: MIT */ +#include "native_bar.h" +#include +#include + +_Static_assert(sizeof(struct stela_amd_bar_layout) == 16, "BAR layout ABI"); +_Static_assert(offsetof(struct stela_amd_bar_layout, kernel_doorbell_bytes) == 8, "BAR bytes ABI"); + +enum stela_amd_bar_status +stela_amd_native_register_bar(uint32_t asic_type, uint32_t *bar) +{ + if (!bar || asic_type >= CHIP_LAST) + return STELA_AMD_BAR_INVALID; + *bar = amdgpu_native_register_bar((enum amd_asic_type)asic_type); + return STELA_AMD_BAR_OK; +} + +enum stela_amd_bar_status +stela_amd_native_bar_layout(uint32_t asic_type, uint64_t doorbell_bar_bytes, + uint32_t max_assignment, uint64_t page_bytes, + struct stela_amd_bar_layout *layout) +{ + if (!layout || asic_type >= CHIP_LAST || page_bytes < 4096 || + page_bytes > UINT32_MAX || (page_bytes & (page_bytes - 1))) + return STELA_AMD_BAR_INVALID; + const enum amd_asic_type asic = asic_type; + struct stela_amd_bar_layout result = {.register_bar = amdgpu_native_register_bar(asic)}; + if (asic < CHIP_BONAIRE) { + if (doorbell_bar_bytes || max_assignment) + return STELA_AMD_BAR_INVALID; + } else { + if (doorbell_bar_bytes < 4 || doorbell_bar_bytes / 4 > UINT32_MAX || + max_assignment == UINT32_MAX || + (asic >= CHIP_VEGA10 && max_assignment + 1 > UINT32_MAX - 0x400)) + return STELA_AMD_BAR_UNREPRESENTABLE; + const uint32_t count = amdgpu_native_kernel_doorbell_count(asic, doorbell_bar_bytes, + max_assignment); + const uint64_t bytes = amdgpu_native_kernel_doorbell_bytes(count, page_bytes); + /* The original kernel allocator's temporary size is int. Keep that + * producer's representable domain, and never acquire outside the BAR. */ + if (!count || bytes > INT_MAX || bytes > doorbell_bar_bytes) + return STELA_AMD_BAR_UNREPRESENTABLE; + result.kernel_doorbell_bytes = bytes; + result.kernel_doorbells = bytes / 4; + } + *layout = result; + return STELA_AMD_BAR_OK; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/native_bar.h b/crates/stela-drivers/src/gpu/amd/stela/native_bar.h new file mode 100644 index 0000000000..f21e7e91f2 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/native_bar.h @@ -0,0 +1,110 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2008, 2022 Advanced Micro Devices, Inc. + * Copyright 2008 Red Hat Inc. + * Copyright 2009 Jerome Glisse. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Dave Airlie + * Alex Deucher + * Jerome Glisse + */ +#ifndef STELA_AMD_NATIVE_BAR_H +#define STELA_AMD_NATIVE_BAR_H + +#ifdef __KERNEL__ +#include +#else +#include +#endif +#include + +/* Pure policies shared with original amdgpu_device/doorbell consumers. + * Callers retain original ASIC classification and actual doorbell assignment. + * Native entry preflights arithmetic before using the original expressions. + */ +static inline unsigned +amdgpu_native_register_bar(enum amd_asic_type asic_type) +{ + return asic_type >= CHIP_BONAIRE ? 5 : 2; +} + +static inline uint32_t +amdgpu_native_kernel_doorbell_count(enum amd_asic_type asic_type, + uint64_t bar_bytes, uint32_t max_assignment) +{ + uint32_t count = (uint32_t)(bar_bytes / sizeof(uint32_t)); + count = count < max_assignment + 1 ? count : max_assignment + 1; + if (!count) + return 0; + /* + * For Vega, reserve and map two pages on doorbell BAR since SDMA + * paging queue doorbell use the second page. The + * AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the + * doorbells are in the first page. So with paging queue enabled, + * the max num_kernel_doorbells should + 1 page (0x400 in dword) + */ + if (asic_type >= CHIP_VEGA10) + count += 0x400; + return count; +} + +static inline uint64_t +amdgpu_native_kernel_doorbell_storage_bytes(uint32_t count, uint64_t page_bytes) +{ + return ((uint64_t)count * sizeof(uint32_t) + page_bytes - 1) & ~(page_bytes - 1); +} + +static inline uint64_t +amdgpu_native_kernel_doorbell_bytes(uint32_t count, uint64_t page_bytes) +{ + uint64_t size = amdgpu_native_kernel_doorbell_storage_bytes(count, page_bytes); + /* Original extra page for MES kernel usages (ring test). */ + size += page_bytes; + return size; +} + +#ifndef __KERNEL__ +enum stela_amd_bar_status { + STELA_AMD_BAR_OK, + STELA_AMD_BAR_INVALID, + STELA_AMD_BAR_UNREPRESENTABLE, +}; + +struct stela_amd_bar_layout { + uint32_t register_bar; + uint32_t kernel_doorbells; /* Actual original post-allocation DWORD extent. */ + uint64_t kernel_doorbell_bytes; +}; + +/* Facts come from the original matched PCI function/ASIC and initialized + * doorbell-index owner; never Mesa family or display inventory inference. + * SI passes zero doorbell facts. CIK+ supplies its actual BAR and assignment. + * Output is unchanged on error. This query reserves/maps/writes nothing. + */ +enum stela_amd_bar_status +stela_amd_native_register_bar(uint32_t asic_type, uint32_t *bar); + +enum stela_amd_bar_status +stela_amd_native_bar_layout(uint32_t asic_type, uint64_t doorbell_bar_bytes, + uint32_t max_assignment, uint64_t page_bytes, + struct stela_amd_bar_layout *layout); +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/pci_match.c b/crates/stela-drivers/src/gpu/amd/stela/pci_match.c new file mode 100644 index 0000000000..8349425e7e --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/pci_match.c @@ -0,0 +1,106 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "pci_match.h" +#include "../amdgpu/amdgpu_pci_match_core.h" +#include "../amdgpu/amdgpu_apu_flags_core.h" +#include "../amdgpu/amdgpu_discovery_source_core.h" +#include + +_Static_assert(sizeof(struct stela_amd_pci_identity) == 24, "PCI identity ABI"); +_Static_assert(sizeof(struct stela_amd_pci_policy) == 44, "PCI policy ABI"); +_Static_assert(sizeof(struct stela_amd_pci_match) == 32, "PCI match ABI"); +_Static_assert(offsetof(struct stela_amd_pci_match, filename) == 24, "PCI filename ABI"); + +/* Exact Linux 8d3ae592 drivers/pci/pci.h:pci_match_one_device predicate, + * binding only original dev fields to this synchronous scalar query. */ +static const struct pci_device_id * +match_one(const struct pci_device_id *id, const struct stela_amd_pci_identity *dev) +{ + if ((id->vendor == (uint32_t)PCI_ANY_ID || id->vendor == dev->vendor) && + (id->device == (uint32_t)PCI_ANY_ID || id->device == dev->device) && + (id->subvendor == (uint32_t)PCI_ANY_ID || id->subvendor == dev->subvendor) && + (id->subdevice == (uint32_t)PCI_ANY_ID || id->subdevice == dev->subdevice) && + !((id->class ^ dev->class_code) & id->class_mask)) + return id; + return NULL; +} + +int +stela_amd_pci_match(const struct stela_amd_pci_identity *identity, + const struct stela_amd_pci_policy *policy, + struct stela_amd_pci_match *out) +{ + if (!identity || !policy || !out || identity->vendor > UINT16_MAX || + identity->device > UINT16_MAX || identity->subvendor > UINT16_MAX || + identity->subdevice > UINT16_MAX || identity->class_code > 0xffffff || + identity->revision > UINT8_MAX || policy->si_built > 1 || + policy->cik_built > 1 || policy->radeon_built > 1 || + policy->memory_encrypted > 1 || policy->firmware_drivers_only > 1) + return STELA_AMD_PCI_INVALID; + + const struct pci_device_id *id = pciidlist; + /* Original pci_match_id first-match/sentinel algorithm. */ + while (id->vendor || id->subvendor || id->class_mask) { + /* Original pci_match_device normal static-table route also skips + * override_only rows; dynamic IDs and driver_override are not this API. */ + if (match_one(id, identity) && !id->override_only) + break; + id++; + } + if (!(id->vendor || id->subvendor || id->class_mask)) + return STELA_AMD_PCI_NO_MATCH; + + if ((identity->class_code >> 8) == PCI_CLASS_DISPLAY_VGA || + (identity->class_code >> 8) == PCI_CLASS_DISPLAY_OTHER) { + if (policy->firmware_drivers_only && policy->modeset == -1) + return STELA_AMD_PCI_FIRMWARE_ONLY; + } + for (size_t i = 0; i < sizeof(amdgpu_unsupported_pciidlist) / + sizeof(amdgpu_unsupported_pciidlist[0]); i++) + if (amdgpu_unsupported_pciidlist[i] == identity->device) + return STELA_AMD_PCI_UNSUPPORTED_ID; + if (id->driver_data > UINT32_MAX) + return STELA_AMD_PCI_INVALID; + unsigned long flags = id->driver_data; + if (!amdgpu_pci_experimental_allowed(flags, policy->experimental)) + return STELA_AMD_PCI_EXPERIMENTAL_DISABLED; + flags = amdgpu_pci_fix_asic_type(identity->device, identity->revision, flags); + if (policy->memory_encrypted && (flags & AMD_ASIC_MASK) == CHIP_RAVEN) + return STELA_AMD_PCI_RAVEN_ENCRYPTION; + const enum amd_asic_type asic = flags & AMD_ASIC_MASK; + struct amdgpu_pci_support_policy support; + if (amdgpu_pci_support_policy(asic, policy->si_built, policy->cik_built, + policy->si_support, policy->cik_support, &support) && + !amdgpu_pci_support_allowed(&support, policy->radeon_built)) + return STELA_AMD_PCI_SUPPORT_DISABLED; + /* Original nonnegative in-range override is a separate debug path, not a + * native physical ASIC assertion. Invalid values are ignored originally. */ + if (policy->force_asic >= 0 && policy->force_asic < CHIP_LAST) + return STELA_AMD_PCI_OVERRIDE_UNAVAILABLE; + + struct stela_amd_pci_match result = { + .row = (uint32_t)(id - pciidlist), .original_flags = flags, .asic_type = asic, + .initial_apu_flags = amdgpu_initial_apu_flags(flags, asic, identity->device, 0), + .discovery_source = STELA_AMD_DISCOVERY_NOT_USED, + }; + switch (amdgpu_initial_ip_path(asic)) { + case AMDGPU_INITIAL_IP_SI: result.ip_path = STELA_AMD_IP_SI_STATIC; break; + case AMDGPU_INITIAL_IP_CIK: result.ip_path = STELA_AMD_IP_CIK_STATIC; break; + case AMDGPU_INITIAL_IP_VI: result.ip_path = STELA_AMD_IP_VI_STATIC; break; + case AMDGPU_INITIAL_IP_DISCOVERY: + result.ip_path = amdgpu_discovery_static_asic(asic) != CHIP_LAST && + !(asic == CHIP_CYAN_SKILLFISH && + amdgpu_discovery_cyan_skillfish2(result.initial_apu_flags)) + ? STELA_AMD_IP_SOC_STATIC : STELA_AMD_IP_DYNAMIC; + /* Original static CyanSkillfish never calls discovery_init, including + * option2. Other SOC-static arms acquire optional inventory only. */ + if (asic == CHIP_CYAN_SKILLFISH && result.ip_path == STELA_AMD_IP_SOC_STATIC) + break; + result.filename = amdgpu_discovery_fw_name(asic, result.initial_apu_flags, + policy->discovery); + result.discovery_source = result.filename ? STELA_AMD_DISCOVERY_FILE + : STELA_AMD_DISCOVERY_HARDWARE; + break; + } + *out = result; + return STELA_AMD_PCI_OK; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/pci_match.h b/crates/stela-drivers/src/gpu/amd/stela/pci_match.h new file mode 100644 index 0000000000..659daa75fb --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/pci_match.h @@ -0,0 +1,59 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_PCI_MATCH_H +#define STELA_AMD_PCI_MATCH_H +#include + +/* Actual type-0 configuration values; class is base/subclass/prog-if (24 bits). + * Header kind is checked by the Rust config owner before subsystem-ID reads. + * This is a scalar query ABI, not an alternate PCI/device/resource owner. */ +struct stela_amd_pci_identity { + uint32_t vendor, device, subvendor, subdevice, class_code, revision; +}; +struct stela_amd_pci_policy { + uint32_t si_built, cik_built, radeon_built; + int32_t si_support, cik_support, experimental, discovery, force_asic; + /* Actual original platform policy, not readiness/capability assertions. */ + uint32_t memory_encrypted, firmware_drivers_only; + int32_t modeset; +}; +enum stela_amd_pci_status { + STELA_AMD_PCI_OK, + STELA_AMD_PCI_INVALID, + STELA_AMD_PCI_NO_MATCH, + STELA_AMD_PCI_UNSUPPORTED_ID, + STELA_AMD_PCI_EXPERIMENTAL_DISABLED, + STELA_AMD_PCI_RAVEN_ENCRYPTION, + STELA_AMD_PCI_SUPPORT_DISABLED, + STELA_AMD_PCI_FIRMWARE_ONLY, + STELA_AMD_PCI_OVERRIDE_UNAVAILABLE, +}; +enum stela_amd_ip_path { + STELA_AMD_IP_SI_STATIC, + STELA_AMD_IP_CIK_STATIC, + STELA_AMD_IP_VI_STATIC, + STELA_AMD_IP_SOC_STATIC, + STELA_AMD_IP_DYNAMIC, +}; +enum stela_amd_discovery_source { + STELA_AMD_DISCOVERY_NOT_USED, + STELA_AMD_DISCOVERY_HARDWARE, + STELA_AMD_DISCOVERY_FILE, +}; +struct stela_amd_pci_match { + uint32_t row, original_flags, asic_type, initial_apu_flags; + uint32_t ip_path, discovery_source; + /* C static original filename; NULL for hardware/not-used. */ + const char *filename; +}; + +/* No allocation, config/MMIO access, publication or resource reservation. + * Genuine PCI/config and platform/build options are owner prerequisites. + * Normal retained table only: Linux dynamic IDs/driver_override and forced + * ASIC debug emulation do not establish this route. Output unchanged on error. + * A selected file is required by the dynamic path (optional inventory for the + * original static path); this result never authorizes substituting hardware. + */ +int stela_amd_pci_match(const struct stela_amd_pci_identity *identity, + const struct stela_amd_pci_policy *policy, + struct stela_amd_pci_match *out); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/stela/vram_mm.c b/crates/stela-drivers/src/gpu/amd/stela/vram_mm.c new file mode 100644 index 0000000000..bdf148dcbc --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/vram_mm.c @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: MIT */ +#include "vram_mm.h" +#include "../include/asic_reg/bif/bif_4_1_d.h" +#include "../amdgpu/amdgpu_mm_access_core.h" +#include + +static uint32_t read32(void *context, uint32_t reg) +{ + volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)context + reg * 4u); + /* Original x86 readl/writel carry a compiler memory clobber. Keep CPU + * buffer accesses ordered too; volatile alone only orders device accesses. + * UC/device ordering is still the real x86 platform owner's obligation. */ + atomic_signal_fence(memory_order_seq_cst); + uint32_t value = *pointer; + atomic_signal_fence(memory_order_seq_cst); + return value; +} +static void write32(void *context, uint32_t reg, uint32_t value) +{ + volatile uint32_t *pointer = (volatile uint32_t *)((uint8_t *)context + reg * 4u); + atomic_signal_fence(memory_order_seq_cst); + *pointer = value; + atomic_signal_fence(memory_order_seq_cst); +} + +enum stela_amd_vram_mm_status +stela_amd_vram_mm_read(void *registers, size_t register_bytes, + uint64_t vram_bytes, uint64_t position, + uint32_t *data, size_t size) +{ + uintptr_t base = (uintptr_t)registers, destination = (uintptr_t)data; + /* Every pointer addition and the original signed loff_t increment is bounded + * before entering the common loop. Actual allocation/lifetime and native + * owner/ordering proofs are the mandatory caller contract, not these ints. */ + if (!registers || base % sizeof(uint32_t) || position % sizeof(uint32_t) || + size % sizeof(uint32_t) || (size && (!data || destination % sizeof(uint32_t)))) + return STELA_AMD_VRAM_MM_INVALID; + if (register_bytes / sizeof(uint32_t) <= mmMM_INDEX || + register_bytes / sizeof(uint32_t) <= mmMM_DATA || + register_bytes / sizeof(uint32_t) <= mmMM_INDEX_HI || + register_bytes > (size_t)PTRDIFF_MAX || register_bytes > UINTPTR_MAX - base || + size > (size_t)PTRDIFF_MAX || (size && size > UINTPTR_MAX - destination) || + vram_bytes > INT64_MAX || position > vram_bytes || size > vram_bytes - position || + /* Original hi=~0 sentinel cannot initialize a first all-ones HI value. + * Do not guess prior hardware state or change the retained algorithm. */ + (size && (position >> 31) == UINT32_MAX)) + return STELA_AMD_VRAM_MM_BOUNDS; + if (size && destination < base + register_bytes && base < destination + size) + return STELA_AMD_VRAM_MM_INVALID; + static const struct amdgpu_mm_access_ops ops = {read32, write32}; + amdgpu_mm_access_core(&ops, registers, (int64_t)position, data, size, false); + return STELA_AMD_VRAM_MM_OK; +} diff --git a/crates/stela-drivers/src/gpu/amd/stela/vram_mm.h b/crates/stela-drivers/src/gpu/amd/stela/vram_mm.h new file mode 100644 index 0000000000..c03e1dd2b4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/stela/vram_mm.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AMD_VRAM_MM_H +#define STELA_AMD_VRAM_MM_H +#include +#include + +enum stela_amd_vram_mm_status { + STELA_AMD_VRAM_MM_OK, + STELA_AMD_VRAM_MM_INVALID, + STELA_AMD_VRAM_MM_BOUNDS, +}; + +/* Native x86-64 synchronous original NO_KIQ MM_INDEX/MM_DATA read only. OK means + * numeric preflight accepted and the original void transaction loop returned; + * it is NOT a transport acknowledgement or proof that VRAM bytes are valid. + * Discovery must still check its original signature/checksums and ownership. + * + * registers is the actual retained canonical UC register mapping of this same + * AMD device, not physical/guest memory. data is exclusive live CPU RAM for the + * complete indicated size; neither span may overlap. Both are DWORD aligned. + * The owner retains genuine D0/bridge/reset/removal and MM-index/IRQ exclusion, + * required native CPU/process context and ordered MMIO32 access semantics for + * the entire call. No new lock, mapping, allocator, provider or guard is made. + * vram_bytes is the actual accessible VRAM extent, not a host DMA/IOVA extent. + * Only these three original direct registers are accessed; other registers + * still require original PCIe/KIQ/RLCG/XCC dispatch. No pointer is retained. + * + * The first HI value must not equal the original all-ones cache sentinel. This + * is an original-loop representation restriction, not a guessed GPU capacity. + * All numeric errors leave registers/data untouched. An empty read performs no + * MMIO, but still validates the window and position. After index writes there + * is no rollback or failure-cleanup capability. Unexpected access faults must + * follow the real platform's fail-stop/owner-retention policy. No hardware + * status is invented for the original void transport. Callers serialize all + * borrowed window accesses and destruction; no Rust references alias MMIO. + */ +enum stela_amd_vram_mm_status +stela_amd_vram_mm_read(void *registers, size_t register_bytes, + uint64_t vram_bytes, uint64_t position, + uint32_t *data, size_t size); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/tests/air_compile.c b/crates/stela-drivers/src/gpu/amd/tests/air_compile.c new file mode 100644 index 0000000000..dd333f9907 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/air_compile.c @@ -0,0 +1,731 @@ +/* SPDX-License-Identifier: MIT */ +/* Hosted ownership/ABI and retained compiler tests only. Target/VM facts and + * upload addresses are CPU models; no initialized physical GPU is claimed. */ +#include "../stela/air_compile.h" +#include "amd/common/ac_binary.h" +#include "amd/common/ac_shader_util.h" +#include "amd/common/sid.h" +#include "amd/compiler/aco_interface.h" +#include "stela/air_test_fixture.h" +#include "util/mesa-blake3.h" +#include "util/ralloc.h" +#include +#include +#include +#include +#include +#include +#include + +#ifdef NDEBUG +#error "Owned compilation tests require active assertions" +#endif +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #x); abort(); } } while (0) + +/* Test-object-only renaming of the new owner's direct libc allocations. Mesa, + * LLVM, Rust and Foundation retain their original allocators. */ +static unsigned allocations, fail_allocation, live_allocations; +void *stela_amd_air_test_malloc(size_t size); +void *stela_amd_air_test_calloc(size_t count, size_t size); +void stela_amd_air_test_free(void *pointer); +void *stela_amd_air_test_malloc(size_t size) +{ + if (++allocations == fail_allocation) + return NULL; + void *p = malloc(size); + if (p) live_allocations++; + return p; +} +void *stela_amd_air_test_calloc(size_t count, size_t size) +{ + if (++allocations == fail_allocation) + return NULL; + void *p = calloc(count, size); + if (p) live_allocations++; + return p; +} +void stela_amd_air_test_free(void *pointer) +{ + if (pointer) { CHECK(live_allocations); live_allocations--; } + free(pointer); +} + +struct bytes { uint8_t *data; size_t size; }; +static void append(struct bytes *bytes, const void *data, size_t size) +{ + CHECK(size <= SIZE_MAX - bytes->size); + bytes->data = realloc(bytes->data, bytes->size + size); + CHECK(bytes->data); + memcpy(bytes->data + bytes->size, data, size); + bytes->size += size; +} +static void little(void *data, uint64_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; i++) ((uint8_t *)data)[i] = (uint8_t)(value >> (8 * i)); +} +static void tag(struct bytes *bytes, const char name[4], const void *data, size_t size) +{ + CHECK(size <= UINT16_MAX); + uint8_t length[2]; little(length, size, 2); + append(bytes, name, 4); append(bytes, length, 2); append(bytes, data, size); +} +static void digest(const void *bytes, size_t size, uint8_t output[32]) +{ + CHECK(size <= AIR_MAX_BITCODE_BYTES); + CC_SHA256(bytes, (CC_LONG)size, output); +} +/* Own one-entry framing fixture, never a second parser. The production Rust + * parser and shared inspector independently validate all original extents. */ +static struct bytes archive(const void *air, size_t size, const char *name, + unsigned air_minor, unsigned major, unsigned minor, + unsigned os_major, unsigned os_minor) +{ + struct bytes record = {0}; uint8_t prefix[4] = {0}, kind = 2, hash[32]; + append(&record, prefix, 4); tag(&record, "NAME", name, strlen(name) + 1); + tag(&record, "TYPE", &kind, 1); digest(air, size, hash); tag(&record, "HASH", hash, 32); + uint8_t length[8], offsets[24] = {0}, versions[8]; little(length, size, 8); + tag(&record, "MDSZ", length, 8); tag(&record, "OFFT", offsets, 24); + little(versions, 2, 2); little(versions + 2, air_minor, 2); + little(versions + 4, major, 2); little(versions + 6, minor, 2); + tag(&record, "VERS", versions, 8); append(&record, "ENDT", 4); little(record.data, record.size, 4); + uint8_t header[88] = {0}; memcpy(header, "MTLB", 4); + little(header + 4, 0x8001, 2); little(header + 6, 2, 2); little(header + 8, 9, 2); + header[11] = 0x81; little(header + 12, os_major, 2); little(header + 14, os_minor, 2); + size_t start = 92 + record.size; + little(header + 16, start + size, 8); little(header + 24, 88, 8); little(header + 32, record.size, 8); + little(header + 40, start, 8); little(header + 56, start, 8); + little(header + 72, start, 8); little(header + 80, size, 8); + struct bytes result = {0}; append(&result, header, sizeof(header)); + little(prefix, 1, 4); append(&result, prefix, 4); append(&result, record.data, record.size); + append(&result, air, size); free(record.data); return result; +} +static struct stela_metal_assembly *assemble(const struct bytes *bytes) +{ + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL; + enum stela_metal_assembly_status status = stela_metal_assemble_archive( + &options, bytes->data, bytes->size, &library, &error); + if (status) fprintf(stderr, "assembly refused: %u %s\n", status, error.detail); + CHECK(status == STELA_METAL_ASSEMBLY_OK && library); + return library; +} +static struct stela_metal_assembly *fixture(LLVMMemoryBufferRef air) +{ + struct bytes bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 8, 4, 0, 26, 7); + struct stela_metal_assembly *library = assemble(&bytes); free(bytes.data); return library; +} +static struct stela_metal_assembly *two_entries(LLVMMemoryBufferRef air) +{ + size_t size = LLVMGetBufferSize(air); + struct bytes a = archive(LLVMGetBufferStart(air), size, "kernel", 8, 4, 0, 26, 7); + struct bytes b = archive(LLVMGetBufferStart(air), size, "other", 8, 4, 0, 26, 7); + size_t a_record = a.size - 92 - size, b_record = b.size - 92 - size; + size_t start = 92 + a_record + b_record; + uint8_t header[88], count[4]; memcpy(header, a.data, sizeof(header)); + little(header + 16, start + size, 8); little(header + 32, a_record + b_record, 8); + little(header + 40, start, 8); little(header + 56, start, 8); little(header + 72, start, 8); + little(count, 2, 4); + struct bytes bytes = {0}; append(&bytes, header, sizeof(header)); append(&bytes, count, 4); + append(&bytes, a.data + 92, a_record); append(&bytes, b.data + 92, b_record); + append(&bytes, LLVMGetBufferStart(air), size); + struct stela_metal_assembly *library = assemble(&bytes); + free(a.data); free(b.data); free(bytes.data); return library; +} +static struct radeon_info model(enum radeon_family family, bool graphics) +{ + struct radeon_info info = { + .family = family, .gfx_level = ac_get_gfx_level(family), .has_graphics = graphics, + .num_cu = 8, .num_se = 2, .max_se = 2, .spi_cu_en = UINT32_MAX, + .max_good_cu_per_sa = 4, .max_sa_per_se = 1, + .virtual_address_max = UINT64_C(0x800000000000), .virtual_address_alignment = 4096, + .tcc_cache_line_size = 128, + }; + ac_fill_compiler_info(&info, NULL, false); + info.instr_prefetch_distance = info.gfx_level >= GFX11 ? 4 : 0; + return info; +} +static struct stela_amd_air_options options(unsigned wave) +{ + return (struct stela_amd_air_options) { + .size = sizeof(struct stela_amd_air_options), .abi = STELA_AMD_AIR_ABI, + .wave_size = wave, .workgroup_size = {32, 1, 1}, .max_instructions = 4096, + .max_code_bytes = 1024u * 1024u, + }; +} +static struct stela_amd_air_compilation *compile(const struct radeon_info *info, + struct stela_metal_assembly *library, const struct stela_amd_air_options *opts, + enum stela_amd_air_status expected) +{ + struct stela_amd_air_compilation *result = NULL; struct stela_amd_air_error error; +#ifdef STELA_AMD_AIR_ALLOC_TEST + unsigned baseline = live_allocations; +#endif + enum stela_amd_air_status status = stela_amd_air_compile(info, library, 0, opts, &result, &error); + if (status != expected) fprintf(stderr, "compile %s: %u expected %u: %s (AIR %u %s)\n", + ac_get_family_name(info->family), status, expected, error.detail, error.air.kind, error.air.detail); + CHECK(status == expected && error.status == status && (result != NULL) == (status == STELA_AMD_AIR_OK)); +#ifdef STELA_AMD_AIR_ALLOC_TEST + if (status != STELA_AMD_AIR_OK) CHECK(live_allocations == baseline); +#endif + return result; +} +static void destroy(struct stela_amd_air_compilation **owner) +{ + stela_amd_air_destroy(owner); CHECK(!*owner); + stela_amd_air_destroy(owner); stela_amd_air_destroy(NULL); +} +struct reference {const struct stela_amd_air_compilation *owner; unsigned count;}; +static void reference_binary(void **private, const struct ac_shader_config *config, + const char *ir, unsigned ir_size, const char *assembly, unsigned assembly_size, + struct amd_stats *stats, uint32_t exec_size, const uint32_t *code, uint32_t code_dw, + const struct aco_symbol *symbols, unsigned symbol_count, + const struct ac_shader_debug_info *debug, unsigned debug_count) +{ + (void)ir; (void)ir_size; (void)assembly; (void)assembly_size; (void)stats; + (void)symbols; (void)debug; (void)debug_count; + struct reference *ref = *private; + const struct stela_amd_compute_binary *binary = stela_amd_air_binary(ref->owner); + CHECK(!ref->count++ && !symbol_count && exec_size == binary->executable_bytes && code_dw * 4 == binary->code_bytes && + !memcmp(code, stela_amd_air_code(ref->owner), binary->code_bytes) && + !memcmp(config, binary->config, sizeof(*config))); +} +static uint32_t +register_word(const uint32_t *words, unsigned count, unsigned reg) +{ + for (unsigned cursor = 0; cursor < count;) { + const unsigned header = words[cursor], length = ((header >> 16) & 0x3fff) + 2; + CHECK(header >> 30 == 3 && length <= count - cursor && + ((header >> 8) & 255) == PKT3_SET_SH_REG && length >= 3); + const unsigned start = 0xb000 + 4 * words[cursor + 1]; + for (unsigned i = 2; i < length; i++) { + if (start + 4 * (i - 2) == reg) + return words[cursor + i]; + } + cursor += length; + } + CHECK(false); + return 0; +} + +static void validate_result(const struct radeon_info *info, struct stela_amd_air_compilation *owner, + const char *label) +{ + const struct stela_amd_compute_binary *binary = stela_amd_air_binary(owner); + const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner); + uint32_t count; const struct stela_amd_air_binding *bindings = stela_amd_air_bindings(owner, &count); + CHECK(binary && p && bindings && stela_amd_air_code(owner)); + CHECK(binary->code_bytes >= binary->executable_bytes && binary->executable_bytes > 0 && + binary->shader->options && binary->config->num_vgprs && binary->args->return_count == 0); + CHECK(binary->family == info->family && binary->gfx_level == info->gfx_level); + CHECK(!memcmp(&p->compiler_info, &info->compiler_info, sizeof(p->compiler_info))); + CHECK(p->pci_id == info->pci_id && p->pci_rev_id == info->pci_rev_id && p->has_graphics == info->has_graphics); + CHECK(binary->shader->options->max_workgroup_invocations >= 32 && p->name && p->target); + nir_validate_shader((nir_shader *)binary->shader, "retained owned compile result"); + /* Original backend callback is an independent byte/config oracle for the + * owner's copied result. Compile a real NIR clone through unchanged ACO; + * inspection below also happens after its temporary vectors are destroyed. */ + nir_shader *copy = nir_shader_clone(NULL, binary->shader); + CHECK(copy); + const struct aco_compiler_options opts = {.compiler_info = &info->compiler_info, + .family = info->family, .gfx_level = info->gfx_level}; + const struct aco_shader_info shader_info = {.hw_stage = AC_HW_COMPUTE_SHADER, + .lds_size = binary->shader->info.shared_size, + .wave_size = (uint8_t)binary->wave_size, .workgroup_size = + binary->shader->info.workgroup_size[0] * binary->shader->info.workgroup_size[1] * binary->shader->info.workgroup_size[2]}; + struct reference ref = {.owner = owner}; void *private = &ref; + aco_compile_shader(&opts, &shader_info, 1, ©, binary->args, reference_binary, &private); + CHECK(ref.count == 1); ralloc_free(copy); + struct stela_amd_compute_binding runtime[STELA_AMD_AIR_MAX_BUFFERS] = {0}; + bool seen[AC_MAX_ARGS] = {false}; + nir_foreach_function_impl(impl, (nir_shader *)binary->shader) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic == nir_intrinsic_load_scalar_arg_amd && nir_intrinsic_base(intr) < AC_MAX_ARGS) + seen[nir_intrinsic_base(intr)] = true; + } + } + } + for (unsigned i = 0; i < count; i++) { + struct ac_arg arg = bindings[i].argument; + CHECK(arg.used && arg.arg_index < binary->args->arg_count && + binary->args->args[arg.arg_index].file == AC_ARG_SGPR && + binary->args->args[arg.arg_index].offset == 2 * i && binary->args->args[arg.arg_index].size == 2); + runtime[i] = (struct stela_amd_compute_binding) {.argument = arg, + .view = {.allocation_va = UINT64_C(0x100000) + (uint64_t)i * 4096, + .allocation_bytes = 4096, .range = 4096, .required_alignment = bindings[i].buffer.type_alignment}}; + CHECK(bindings[i].buffer.address_space == 1 && bindings[i].buffer.type_alignment); + bool used = false; + for (unsigned a = 0; a < p->argument_count; a++) + if (p->arguments[a].buffer.argument == bindings[i].buffer.argument) used = p->arguments[a].used; + if (used) CHECK(seen[arg.arg_index]); + } + const unsigned padded = ac_align_shader_binary_for_prefetch(info->gfx_level, + info->instr_prefetch_distance, binary->code_bytes); + struct stela_amd_buffer_view code = {.allocation_va = UINT64_C(0x400000), + .allocation_bytes = padded, .range = padded, .required_alignment = 256}; + struct stela_amd_compute_pipeline pipeline; + enum stela_amd_compute_status status = stela_amd_build_compute_pipeline(info, binary, &code, runtime, count, &pipeline); + if (binary->config->scratch_bytes_per_wave) + CHECK(status == STELA_AMD_COMPUTE_RESOURCE_OWNER_UNAVAILABLE); + else if (count) + CHECK(status == STELA_AMD_COMPUTE_OK && pipeline.user_sgpr_count == 2 * count); + else { + CHECK(status == STELA_AMD_COMPUTE_OK && !pipeline.user_sgpr_count && + !G_00B84C_USER_SGPR(pipeline.rsrc2)); + struct stela_amd_compute_pipeline null_bindings; + CHECK(stela_amd_build_compute_pipeline(info, binary, &code, NULL, 0, &null_bindings) == STELA_AMD_COMPUTE_OK && + !memcmp(&pipeline, &null_bindings, sizeof(pipeline))); + uint32_t words[256], written; + CHECK(stela_amd_compute_pipeline(info, &pipeline, words, ARRAY_SIZE(words), &written) == STELA_AMD_COMMAND_OK && written); + bool resource_word = false; + for (unsigned cursor = 0; cursor < written;) { + const uint32_t header = words[cursor], length = ((header >> 16) & 0x3fff) + 2; + CHECK(header >> 30 == 3 && length <= written - cursor && length >= 3 && + ((header >> 8) & 255) == PKT3_SET_SH_REG); + const uint32_t start = 0xb000 + words[cursor + 1] * 4; + for (unsigned i = 2; i < length; i++) { + const uint32_t reg = start + (i - 2) * 4; + CHECK(reg < R_00B900_COMPUTE_USER_DATA_0 || reg >= R_00B900_COMPUTE_USER_DATA_0 + 4 * STELA_AMD_COMPUTE_USER_SGPRS); + if (reg == R_00B84C_COMPUTE_PGM_RSRC2) { + CHECK(words[cursor + i] == pipeline.rsrc2 && !G_00B84C_USER_SGPR(words[cursor + i])); + resource_word = true; + } + } + cursor += length; + } + CHECK(resource_word); + const struct stela_amd_compute_pipeline preserved = pipeline; + CHECK(stela_amd_build_compute_pipeline(info, binary, &code, NULL, 1, &pipeline) == STELA_AMD_COMPUTE_INVALID && + !memcmp(&pipeline, &preserved, sizeof(pipeline))); + struct ac_shader_config scratch = *binary->config; scratch.scratch_bytes_per_wave = 1024; + struct stela_amd_compute_binary unowned = *binary; unowned.config = &scratch; + CHECK(stela_amd_build_compute_pipeline(info, &unowned, &code, NULL, 0, &pipeline) == STELA_AMD_COMPUTE_RESOURCE_OWNER_UNAVAILABLE && + !memcmp(&pipeline, &preserved, sizeof(pipeline))); + } + CHECK(binary->config->lds_size == binary->shader->info.shared_size); + if (status == STELA_AMD_COMPUTE_OK) { + CHECK(G_00B84C_LDS_SIZE(pipeline.rsrc2) == ac_shader_encode_lds_size( + binary->shader->info.shared_size, info->gfx_level, MESA_SHADER_COMPUTE)); + uint32_t words[256], written; + CHECK(stela_amd_compute_pipeline(info, &pipeline, words, ARRAY_SIZE(words), &written) == STELA_AMD_COMMAND_OK); + CHECK(register_word(words, written, R_00B84C_COMPUTE_PGM_RSRC2) == pipeline.rsrc2); + const struct stela_amd_compute_pipeline preserved = pipeline; + struct ac_shader_config incompatible = *binary->config; + incompatible.lds_size = binary->shader->info.shared_size ? 0 : 1; + struct stela_amd_compute_binary wrong_lds = *binary; wrong_lds.config = &incompatible; + CHECK(stela_amd_build_compute_pipeline(info, &wrong_lds, &code, runtime, count, &pipeline) == STELA_AMD_COMPUTE_UNSUPPORTED && + !memcmp(&pipeline, &preserved, sizeof(pipeline))); + } + blake3_hash hash; char code_hash[BLAKE3_HEX_LEN]; + _mesa_blake3_compute(stela_amd_air_code(owner), binary->code_bytes, hash); _mesa_blake3_format(code_hash, hash); + printf("owned-air-aco input=%s target=%s.wave%u buffers=%u code_bytes=%u executable_bytes=%u code_blake3=%s " + "sgprs=%u vgprs=%u lds=%u scratch=%u float_mode=%u\n", label, ac_get_family_name(info->family), + binary->wave_size, count, binary->code_bytes, binary->executable_bytes, code_hash, binary->config->num_sgprs, + binary->config->num_vgprs, binary->config->lds_size, binary->config->scratch_bytes_per_wave, binary->config->float_mode); +} + +static void text_append(char *text, size_t capacity, const char *format, ...) +{ + size_t length = strlen(text); CHECK(length < capacity); + va_list args; va_start(args, format); int bytes = vsnprintf(text + length, capacity - length, format, args); + va_end(args); CHECK(bytes >= 0 && (size_t)bytes < capacity - length); +} +static LLVMMemoryBufferRef multibuffer(unsigned count) +{ + CHECK(count <= 9); + char prefix[4096] = "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v28-apple-macosx26.7.0\"\ndefine void @kernel(i32 %tid"; + char body[8192] = "%index = zext i32 %tid to i64\n", metadata[16384] = "}\n" + "!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5"; + for (unsigned i = 0; i < count; i++) { + text_append(prefix, sizeof(prefix), ", ptr addrspace(1) %%b%u", i); + text_append(body, sizeof(body), "%%p%u = getelementptr i32, ptr addrspace(1) %%b%u, i64 %%index\n" + "%%v%u = load i32, ptr addrspace(1) %%p%u, align 4\n" + "%%x%u = add i32 %%v%u, %u\nstore i32 %%x%u, ptr addrspace(1) %%p%u, align 4\n", + i, i, i, i, i, i, i + 1, i, i); + text_append(metadata, sizeof(metadata), ",!%u", i + 6); + } + text_append(prefix, sizeof(prefix), ") {\n"); text_append(body, sizeof(body), "ret void\n"); + text_append(metadata, sizeof(metadata), "}\n!5 = !{i32 0, !\"air.thread_position_in_grid\"," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n"); + for (unsigned i = 0; i < count; i++) + text_append(metadata, sizeof(metadata), "!%u = !{i32 %u, !\"air.buffer\", !\"air.location_index\", i32 %u, i32 1," + " !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4," + " !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"buffer%u\"}\n", + i + 6, i + 1, (i * 7 + 3) % 31, i); + return stela_air_test_custom_bitcode(prefix, body, metadata, ""); +} + +static void failures(struct stela_metal_assembly *library, const struct radeon_info *info) +{ + struct stela_amd_air_options valid = options(64), bad; + const struct {unsigned field, value; enum stela_amd_air_status status;} cases[] = { + {0, 0, STELA_AMD_AIR_INVALID}, {1, 0, STELA_AMD_AIR_INVALID}, + {2, 0, STELA_AMD_AIR_UNSUPPORTED}, {3, 0, STELA_AMD_AIR_UNSUPPORTED}, + {4, UINT32_MAX, STELA_AMD_AIR_UNSUPPORTED}, {5, 0, STELA_AMD_AIR_LIMIT}, + {6, 0, STELA_AMD_AIR_LIMIT}, {6, UINT32_MAX, STELA_AMD_AIR_LIMIT}, + }; + for (unsigned i = 0; i < ARRAY_SIZE(cases); i++) { + bad = valid; + switch (cases[i].field) { + case 0: bad.size = cases[i].value; break; case 1: bad.abi = cases[i].value; break; + case 2: bad.wave_size = cases[i].value; break; case 3: bad.workgroup_size[0] = cases[i].value; break; + case 4: bad.workgroup_size[2] = cases[i].value; break; case 5: bad.max_instructions = cases[i].value; break; + case 6: bad.max_code_bytes = cases[i].value; break; + } + CHECK(!compile(info, library, &bad, cases[i].status)); + } + bad = valid; bad.fp_profile = (enum stela_air_fp_profile)99; + CHECK(!compile(info, library, &bad, STELA_AMD_AIR_UNSUPPORTED)); + bad = valid; bad.max_code_bytes = 4; + CHECK(!compile(info, library, &bad, STELA_AMD_AIR_LIMIT)); + bad = valid; bad.max_instructions = 1; + CHECK(!compile(info, library, &bad, STELA_AMD_AIR_FRONTEND)); + struct radeon_info missing = *info; missing.virtual_address_max = 0; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + missing = *info; missing.compiler_info.max_sgpr_alloc = 1; + missing.compiler_info.min_sgpr_alloc = missing.compiler_info.sgpr_alloc_granularity = 1; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_UNSUPPORTED)); + missing = *info; missing.compiler_info.num_physical_sgprs_per_simd = 0; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + missing = *info; missing.compiler_info.num_physical_wave64_vgprs_per_simd = UINT32_MAX; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + missing = *info; missing.compiler_info.wave64_vgpr_alloc_granularity = 0; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + missing = *info; missing.compiler_info.lds_size_per_workgroup = UINT32_MAX; + CHECK(!compile(&missing, library, &valid, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + missing = *info; missing.compiler_info.num_physical_wave64_vgprs_per_simd = UINT16_MAX / 2 + 1; + bad = valid; bad.wave_size = 32; + CHECK(!compile(&missing, library, &bad, STELA_AMD_AIR_DEVICE_INFO_UNAVAILABLE)); + struct radeon_info cdna = model(CHIP_MI100, false); + CHECK(!compile(&cdna, library, &valid, STELA_AMD_AIR_UNSUPPORTED)); + struct radeon_info gfx121 = model(CHIP_GFX1210, true); + CHECK(!compile(&gfx121, library, &valid, STELA_AMD_AIR_UNSUPPORTED)); + struct stela_amd_air_error error; struct stela_amd_air_compilation *owner = NULL; + CHECK(stela_amd_air_compile(info, library, UINT32_MAX, &valid, &owner, &error) == STELA_AMD_AIR_INVALID && !owner); + owner = compile(info, library, &valid, STELA_AMD_AIR_OK); + struct stela_amd_air_compilation *same = owner; + CHECK(stela_amd_air_compile(info, library, 0, &valid, &owner, &error) == STELA_AMD_AIR_INVALID && owner == same); + destroy(&owner); +} +static void targets(struct stela_metal_assembly *library, enum stela_air_fp_profile profile, const char *label) +{ + const enum radeon_family families[] = {CHIP_TAHITI, CHIP_BONAIRE, CHIP_CARRIZO, CHIP_RAVEN, + CHIP_NAVI10, CHIP_REMBRANDT, CHIP_NAVI31, CHIP_STRIX1, CHIP_GFX1170, CHIP_GFX1201}; + for (unsigned i = 0; i < ARRAY_SIZE(families); i++) { + struct radeon_info info = model(families[i], true); + for (unsigned wave = info.gfx_level < GFX10 ? 64 : 32; wave <= 64; wave *= 2) { + struct stela_amd_air_options opts = options(wave); opts.fp_profile = profile; + struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); + validate_result(&info, owner, label); destroy(&owner); + } + } +} +static void original_tests(void) +{ + LLVMMemoryBufferRef air = stela_air_test_bitcode(stela_air_test_store_body, ""); + struct stela_metal_assembly *library = fixture(air); + LLVMDisposeMemoryBuffer(air); + targets(library, STELA_AIR_FP_IEEE_DEFAULT, "original-integer"); + struct radeon_info info = model(CHIP_NAVI31, true); + failures(library, &info); + struct stela_amd_air_options three_d = options(32); + three_d.workgroup_size[0] = 4; three_d.workgroup_size[1] = 2; three_d.workgroup_size[2] = 3; + struct stela_amd_air_compilation *specialized = compile(&info, library, &three_d, STELA_AMD_AIR_OK); + const struct stela_amd_air_provenance *specialization = stela_amd_air_provenance(specialized); + CHECK(!memcmp(&specialization->options, &three_d, sizeof(three_d))); + for (unsigned axis = 0; axis < 3; axis++) + CHECK(stela_amd_air_binary(specialized)->shader->info.workgroup_size[axis] == three_d.workgroup_size[axis]); + validate_result(&info, specialized, "3d-workgroup"); destroy(&specialized); + struct stela_amd_air_options opts = options(64); + struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); + const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(library); + const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner); + CHECK(!memcmp(&p->input, &m->input, sizeof(p->input)) && + !memcmp(&p->entry, &m->entries[0].entry, sizeof(p->entry)) && + !memcmp(p->air_sha256, m->entries[0].air_sha256, 32) && + p->air_offset == m->entries[0].air_offset && p->air_bytes == m->entries[0].air_bytes && + p->arguments[1].name != m->entries[0].arguments[1].name && + !strcmp(p->arguments[1].name, m->entries[0].arguments[1].name)); + stela_metal_assembly_destroy(&library); + CHECK(!strcmp(p->name, "kernel") && !strcmp(p->target, "air64_v28-apple-macosx26.7.0") && + !strcmp(p->arguments[1].type_name, "uint")); + /* Hold one shader/options/type reference across creation/destruction of a + * distinct owner: no borrowed assembly or prematurely released type state. */ + air = multibuffer(8); library = fixture(air); LLVMDisposeMemoryBuffer(air); + struct stela_amd_air_compilation *second = compile(&info, library, &opts, STELA_AMD_AIR_OK); + uint32_t count; const struct stela_amd_air_binding *bindings = stela_amd_air_bindings(second, &count); + CHECK(count == 8); + for (unsigned i = 0; i < count; i++) CHECK(bindings[i].buffer.index == (i * 7 + 3) % 31 && bindings[i].buffer.argument == i + 1); + validate_result(&info, second, "eight-buffer"); destroy(&second); + validate_result(&info, owner, "after-other-owner-destroy"); destroy(&owner); + stela_metal_assembly_destroy(&library); + const char *selected_metadata = "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n" + "!air.kernel = !{!2,!7}\n!0 = !{i32 2, i32 8, i32 0}\n" + "!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!2 = !{ptr @kernel, !3, !4}\n" + "!3 = !{}\n!4 = !{!5,!6}\n!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 13, i32 1, !\"air.write\"," + " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"result\"}\n!7 = !{ptr @other, !3, !4}\n"; + air = stela_air_test_custom_bitcode(stela_air_test_prefix, + "store i32 11, ptr addrspace(1) %out, align 4\nret void\n", selected_metadata, + "define void @other(i32 %tid, ptr addrspace(1) %out) {\nstore i32 99, ptr addrspace(1) %out, align 4\nret void\n}\n"); + library = two_entries(air); LLVMDisposeMemoryBuffer(air); + struct stela_amd_air_error selected_error; + CHECK(stela_amd_air_compile(&info, library, 1, &opts, &owner, &selected_error) == STELA_AMD_AIR_OK && owner); + stela_metal_assembly_destroy(&library); + p = stela_amd_air_provenance(owner); + CHECK(p->selected_entry == 1 && !strcmp(p->name, "other") && p->input.entry_count == 2 && + p->arguments[1].buffer.index == 13 && p->arguments[1].buffer.access == STELA_AIR_WRITE && + !p->arguments[0].name && p->arguments[0].name_bytes == 0); + unsigned selected_stores = 0; + nir_foreach_function_impl(impl, (nir_shader *)stela_amd_air_binary(owner)->shader) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); + if (intr->intrinsic == nir_intrinsic_store_global_amd || intr->intrinsic == nir_intrinsic_store_global) { + CHECK(nir_src_is_const(intr->src[0]) && nir_src_as_uint(intr->src[0]) == 99); selected_stores++; + } + } + } + } + CHECK(selected_stores == 1); validate_result(&info, owner, "selected-second-entry"); destroy(&owner); + air = multibuffer(9); library = fixture(air); LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_UNSUPPORTED)); stela_metal_assembly_destroy(&library); + air = stela_air_test_bitcode("call void @unsupported()\nret void\n", "declare void @unsupported()\n"); + library = fixture(air); LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_FRONTEND)); stela_metal_assembly_destroy(&library); + /* Original LLVM fixture with complete AS3 argument reflection and no module + * globals: distinguish this leaf's dispatch-specialization refusal from the + * canonical library owner's separate incomplete-global reflection refusal. */ + air = stela_air_test_custom_bitcode( + "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v29-apple-macosx27.2.0\"\n" + "define void @kernel(i32 %tid, ptr addrspace(3) %scratch) {\n", + "store i32 %tid, ptr addrspace(3) %scratch, align 4\nret void\n", + "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 9, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 1, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5,!6}\n" + "!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 7, i32 1, !\"air.read_write\"," + " !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"scratch\"}\n", ""); + struct bytes shared_bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 9, 4, 1, 27, 2); + library = assemble(&shared_bytes); free(shared_bytes.data); LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_UNSUPPORTED)); stela_metal_assembly_destroy(&library); + for (unsigned n = 0; n <= 8; n++) { + air = multibuffer(n); library = fixture(air); LLVMDisposeMemoryBuffer(air); + targets(library, STELA_AIR_FP_IEEE_DEFAULT, "generic-buffer-indices"); + stela_metal_assembly_destroy(&library); + } +#ifdef STELA_AMD_AIR_ALLOC_TEST + air = stela_air_test_bitcode(stela_air_test_store_body, ""); library = fixture(air); LLVMDisposeMemoryBuffer(air); + allocations = 0; owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); + unsigned total = allocations; CHECK(total == 3); destroy(&owner); + for (unsigned fail = 1; fail <= total; fail++) { + allocations = 0; fail_allocation = fail; + CHECK(!compile(&info, library, &opts, STELA_AMD_AIR_ALLOCATION) && !live_allocations); + } + fail_allocation = 0; owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); destroy(&owner); + stela_metal_assembly_destroy(&library); +#endif + CHECK(!stela_amd_air_binary(NULL) && !stela_amd_air_code(NULL) && !stela_amd_air_provenance(NULL)); + count = UINT32_MAX; CHECK(!stela_amd_air_bindings(NULL, &count) && !count); + puts("owned AMD AIR compiler lifetime, multi-buffer, producer and failure tests passed"); +} + +static struct bytes read_file(const char *path) +{ + FILE *f = fopen(path, "rb"); CHECK(f && !fseek(f, 0, SEEK_END)); long size = ftell(f); + CHECK(size > 0 && size <= AIR_MAX_BITCODE_BYTES && !fseek(f, 0, SEEK_SET)); + struct bytes b = {.data = malloc((size_t)size), .size = (size_t)size}; CHECK(b.data); + CHECK(fread(b.data, 1, b.size, f) == b.size && fgetc(f) == EOF && !ferror(f) && !fclose(f)); return b; +} +struct input_facts {const char *name; unsigned air_minor, major, minor, os_major, os_minor; bool found;}; +static bool facts(const struct stela_air_inspection *inspection, const struct stela_air_entry *entry, void *data) +{ + struct input_facts *f = data; + if (strlen(f->name) != entry->name_bytes || memcmp(f->name, entry->name, entry->name_bytes)) return true; + f->found = true; f->air_minor = inspection->air_minor; f->major = inspection->language_major; f->minor = inspection->language_minor; + CHECK(sscanf(inspection->target, "air64_v%*u-apple-macosx%u.%u.", &f->os_major, &f->os_minor) == 2); + return true; +} +static void real_input(int argc, char **argv) +{ + CHECK(argc == 4 || argc == 5); /* --input RAW_AIR ENTRY [qualified FP profile number] */ + struct bytes air = read_file(argv[2]); struct input_facts f = {.name = argv[3]}; struct stela_air_error error; + CHECK(stela_air_inspect(air.data, air.size, 256, facts, &f, &error) && f.found); + struct bytes bytes = archive(air.data, air.size, f.name, f.air_minor, f.major, f.minor, f.os_major, f.os_minor); + struct stela_metal_assembly *library = assemble(&bytes); free(air.data); free(bytes.data); + enum stela_air_fp_profile profile = argc == 5 ? (enum stela_air_fp_profile)strtoul(argv[4], NULL, 10) : STELA_AIR_FP_IEEE_DEFAULT; + targets(library, profile, "unchanged-original-file"); stela_metal_assembly_destroy(&library); +} +static void source_input(int argc, char **argv) +{ + CHECK(argc == 5); /* --source ORIGINAL_MSL ORIGINAL_ADAPTER_AIR INDEPENDENT_RECEIPT_IDENTITY_208_BYTES */ + struct bytes source = read_file(argv[2]), air = read_file(argv[3]), identity = read_file(argv[4]); CHECK(identity.size == 208); + struct stela_msl_output compiled = {.air = air.data, .air_bytes = air.size}; + memcpy(compiled.source_sha256, identity.data, 32); memcpy(compiled.air_sha256, identity.data + 32, 32); + memcpy(&compiled.build, identity.data + 64, sizeof(compiled.build)); + struct stela_msl_apple_config config = stela_msl_apple_default_config(); + struct stela_msl_request request = {.source = source.data, .source_bytes = source.size, .language_version = 0x40001, + .fast_math = true, .target_triple = "air64_v29-apple-macosx27.2.0"}; + struct stela_metal_assembly_options assembly_options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL; + CHECK(stela_metal_assemble_source(&assembly_options, &config, &request, &compiled, &library, &error) == STELA_METAL_ASSEMBLY_OK); + struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options opts = options(32); + opts.fp_profile = STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41; + struct stela_amd_air_compilation *owner = compile(&info, library, &opts, STELA_AMD_AIR_OK); + free(air.data); free(source.data); stela_metal_assembly_destroy(&library); + const struct stela_amd_air_provenance *p = stela_amd_air_provenance(owner); + CHECK(p->library_flags == STELA_METAL_LIBRARY_SOURCE_COMPILED && p->compiler_profile == config.profile && + p->request_language == 0x40001 && p->request_fast_math == 1 && + !memcmp(p->source_sha256, identity.data, 32) && !memcmp(p->input.original_sha256, identity.data + 32, 32) && + !memcmp(&p->build, identity.data + 64, sizeof(p->build))); + free(identity.data); validate_result(&info, owner, "original-source-owner"); destroy(&owner); +} +static void requested_threadgroups(int argc,char **argv,struct stela_metal_threadgroup_request_row *rows) +{ + CHECK(argc>=6&&argc-5<=(int)AIR_MAX_ARGUMENTS); + for(int i=5;i='0'&&argv[i][0]<='9'); + unsigned long long index=strtoull(argv[i],&end,10);CHECK(!errno&&index<=UINT32_MAX&&*end==':'); + const char *start=end+1;CHECK(*start>='0'&&*start<='9');errno=0; + unsigned long long bytes=strtoull(start,&end,10);CHECK(!errno&&!*end); + rows[i-5]=(struct stela_metal_threadgroup_request_row){.index=(uint32_t)index,.bytes=(uint64_t)bytes}; + } +} +static void threadgroup_input(int argc,char **argv) +{ + struct stela_metal_threadgroup_request_row rows[AIR_MAX_ARGUMENTS]={0};requested_threadgroups(argc,argv,rows); + char *end;errno=0;unsigned long workgroup=strtoul(argv[4],&end,10);CHECK(!errno&&!*end&&workgroup&&workgroup<=1024); + struct stela_metal_threadgroup_request request={.size=sizeof(request),.abi=STELA_METAL_THREADGROUP_ABI, + .count=(uint32_t)(argc-5),.rows=rows}; + struct bytes air=read_file(argv[2]);struct input_facts f={.name=argv[3]};struct stela_air_error air_error; + CHECK(stela_air_inspect(air.data,air.size,256,facts,&f,&air_error)&&f.found); + struct bytes bytes=archive(air.data,air.size,f.name,f.air_minor,f.major,f.minor,f.os_major,f.os_minor); + struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data); + const enum radeon_family families[]={CHIP_TAHITI,CHIP_BONAIRE,CHIP_CARRIZO,CHIP_RAVEN, + CHIP_NAVI10,CHIP_REMBRANDT,CHIP_NAVI31,CHIP_STRIX1,CHIP_GFX1170,CHIP_GFX1201}; + for(unsigned i=0;ithreadgroup.count==request.count&&stela_metal_threadgroup_matches(&p->threadgroup,&request)); + struct stela_metal_threadgroup_request_row saved[AIR_MAX_ARGUMENTS];memcpy(saved,rows,sizeof(rows)); + rows[0].bytes+=16;CHECK(!stela_metal_threadgroup_matches(&p->threadgroup,&request)); + memset(rows,0,sizeof(rows)); + CHECK(p->threadgroup.bindings[0].bytes&&p->threadgroup.bindings[0].alignment>=16); + memcpy(rows,saved,sizeof(rows));CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request)); + validate_result(&info,owner,"dispatch-threadgroup-specialization"); + printf("owned-threadgroup-aco target=%s.wave%u count=%u total_shared=%u",ac_get_family_name(info.family),wave, + p->threadgroup.count,stela_amd_air_binary(owner)->shader->info.shared_size); + for(unsigned r=0;rthreadgroup.count;r++)printf(" row=%u:%u:%llu:%u",p->threadgroup.bindings[r].buffer.argument, + p->threadgroup.bindings[r].buffer.index,(unsigned long long)p->threadgroup.bindings[r].bytes,p->threadgroup.bindings[r].alignment); + puts(""); + CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request));destroy(&owner); + } + } + stela_metal_assembly_destroy(&library); +} +static void shared_refusal(int argc, char **argv) +{ + CHECK(argc == 4); + struct bytes air = read_file(argv[2]); struct input_facts f = {.name = argv[3]}; struct stela_air_error air_error; + CHECK(stela_air_inspect(air.data, air.size, 256, facts, &f, &air_error) && f.found); + struct bytes bytes = archive(air.data, air.size, f.name, f.air_minor, f.major, f.minor, f.os_major, f.os_minor); + struct stela_metal_assembly_options opts = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL; + enum stela_metal_assembly_status status = stela_metal_assemble_archive(&opts, bytes.data, bytes.size, &library, &error); + if (status == STELA_METAL_ASSEMBLY_OK) { + struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options compile_options = options(32); + CHECK(!compile(&info, library, &compile_options, STELA_AMD_AIR_UNSUPPORTED)); + puts("shared input explicitly refused: dynamic AS3 dispatch specialization unavailable"); + } else { + CHECK(status == STELA_METAL_ASSEMBLY_REFLECTION && !library); + puts("shared input explicitly refused: canonical reflection incomplete"); + } + stela_metal_assembly_destroy(&library); free(bytes.data); free(air.data); +} +#ifdef STELA_AMD_AIR_CAPTURE_TEST +/* Deliberately invalid borrowed backend-output records, confined to this + * separately linked rejection test. No successful fake binary is published. */ +static unsigned bad_capture; +void stela_amd_air_bad_backend(const struct aco_compiler_options *options, + const struct aco_shader_info *info, unsigned count, nir_shader *const *shaders, + const struct ac_shader_args *args, aco_callback *callback, void **private); +void stela_amd_air_bad_backend(const struct aco_compiler_options *options, + const struct aco_shader_info *info, unsigned count, nir_shader *const *shaders, + const struct ac_shader_args *args, aco_callback *callback, void **private) +{ + (void)options; (void)info; (void)count; (void)shaders; (void)args; + struct ac_shader_config config = {.num_vgprs = 8, .num_sgprs = 8}; + const uint32_t invalid_test_bytes[2] = {0, 0}; + callback(private, bad_capture == 0 ? NULL : &config, NULL, 0, NULL, 0, NULL, + bad_capture == 2 ? 0 : bad_capture == 4 ? 12 : bad_capture == 5 ? 3 : 4, + bad_capture == 1 ? NULL : invalid_test_bytes, + bad_capture == 3 ? UINT32_MAX : 2, NULL, bad_capture == 6 ? 1 : 0, NULL, 0); + if (bad_capture == 7) callback(private, &config, NULL, 0, NULL, 0, NULL, 4, + invalid_test_bytes, 2, NULL, 0, NULL, 0); +} +static void invalid_capture_tests(void) +{ + LLVMMemoryBufferRef air = stela_air_test_bitcode(stela_air_test_store_body, ""); + struct stela_metal_assembly *library = fixture(air); LLVMDisposeMemoryBuffer(air); + struct radeon_info info = model(CHIP_NAVI31, true); struct stela_amd_air_options opts = options(32); + for (bad_capture = 0; bad_capture < 8; bad_capture++) { + CHECK(!compile(&info, library, &opts, + bad_capture == 6 ? STELA_AMD_AIR_UNSUPPORTED : STELA_AMD_AIR_BACKEND)); + } + stela_metal_assembly_destroy(&library); + puts("invalid borrowed backend-output records refused atomically; no fake code published"); +} +#endif +int main(int argc, char **argv) +{ +#ifdef STELA_AMD_AIR_CAPTURE_TEST + (void)argc; (void)argv; invalid_capture_tests(); +#else + if (argc == 1) original_tests(); + else if (!strcmp(argv[1], "--input")) real_input(argc, argv); + else if (!strcmp(argv[1], "--source")) source_input(argc, argv); + else if(!strcmp(argv[1],"--threadgroup"))threadgroup_input(argc,argv); + else if (!strcmp(argv[1], "--shared-refusal")) shared_refusal(argc, argv); + else CHECK(false); +#endif +#ifdef STELA_AMD_AIR_ALLOC_TEST + CHECK(!live_allocations); +#endif + return 0; +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/compute_test.c b/crates/stela-drivers/src/gpu/amd/tests/compute_test.c index 9e446e3eba..a890033696 100644 --- a/crates/stela-drivers/src/gpu/amd/tests/compute_test.c +++ b/crates/stela-drivers/src/gpu/amd/tests/compute_test.c @@ -333,6 +333,11 @@ test_compiled_target(enum radeon_family family, unsigned wave, bool llvm_backend assert(register_word(words, written, R_00B900_COMPUTE_USER_DATA_0) == result.user_sgprs[0]); const struct stela_amd_compute_pipeline preserved = result; + /* A zero-binding pipeline cannot discard the real shader's address ABI. */ + assert(stela_amd_build_compute_pipeline(&info, &binary, &code, NULL, 0, &result) != STELA_AMD_COMPUTE_OK); + assert(!memcmp(&result, &preserved, sizeof(result))); + assert(stela_amd_build_compute_pipeline(&info, &binary, &code, NULL, 1, &result) == STELA_AMD_COMPUTE_INVALID); + assert(!memcmp(&result, &preserved, sizeof(result))); struct stela_amd_compute_binary wrong_target = binary; wrong_target.family = CHIP_UNKNOWN; assert(stela_amd_build_compute_pipeline(&info, &wrong_target, &code, &binding, 1, &result) == diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery.rs b/crates/stela-drivers/src/gpu/amd/tests/discovery.rs new file mode 100644 index 0000000000..a77978151e --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery.rs @@ -0,0 +1,143 @@ +//! Child of the single-authority canonical test, with bounded generated C +//! leaf-I/O instrumentation. No physical GPU or production provider is used. +use super::native_mmio; +use super::*; +#[path = "../discovery.rs"] +mod discovery; +#[path = "../vram.rs"] +mod vram; +unsafe extern "C" { + fn stela_amd_tmr_fixture(size: &mut usize) -> *const u8; + fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize); + fn stela_amd_tmr_model_accesses() -> u32; + fn stela_amd_tmr_model_delay(); + fn stela_amd_tmr_model_vf(); + fn stela_amd_tmr_model_system(); + fn stela_amd_tmr_model_corrupt(); + fn stela_amd_tmr_model_end(); +} +pub(super) fn acquire_snapshot(authority: &Authority, pci: &Function) { + let (resource, drops) = resource(0x1200_0000, 0x60000, ResourceKind::Registers); + // SAFETY: isolated canonical RAM-only model, no physical state asserted. + let mut bars = unsafe { + AttachedBars::attach( + authority, + pci, + asic(2), + asic(2), + RegisterBar { index: 5, resource }, + None, + ) + } + .unwrap(); + let window = bars.registers().unwrap(); + let clock = stela_drivers::Clock { + ticks_per_microsecond: 1, + }; + let mut bytes = 0; + // SAFETY: actual immutable static CPU fixture, existing bounded generator. + let source = unsafe { stela_amd_tmr_fixture(&mut bytes) }; + let begin = || unsafe { + stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, bytes) + }; + begin(); + // Exercise the actual C-to-Rust elapsed-time callback once. This CPU + // model does not qualify calibration, scheduler sleep or physical timing. + unsafe { stela_amd_tmr_model_delay() }; + // SAFETY: production acquisition runs only the instrumented CPU fixture path; + // actual original algorithms execute with canonical model ownership/lifetime. + let snapshot = unsafe { discovery::acquire(&bars, &clock) }.unwrap(); + assert_eq!(snapshot.bytes(), unsafe { + core::slice::from_raw_parts(source, bytes) + }); + assert_eq!(snapshot.identity(), bars.identity()); + assert_eq!(snapshot.vram_bytes(), 64 << 20); + assert_eq!(snapshot.vram_offset(), (64 << 20) - 65536); + assert!(unsafe { stela_amd_tmr_model_accesses() } > bytes as u32 / 4); + drop(snapshot); + begin(); + unsafe { stela_amd_tmr_model_corrupt() }; + assert!(matches!( + unsafe { discovery::acquire(&bars, &clock) }, + Err(discovery::Error::Validation(_)) + )); + begin(); + allocation_failure::arm(); + // SAFETY: same controlled CPU fixture; only snapshot Vec allocation fails. + let failed = unsafe { discovery::acquire(&bars, &clock) }; + let consumed = allocation_failure::disarm(); + assert!(consumed); + assert!(matches!(failed, Err(discovery::Error::PostQueryAllocation))); + assert!(unsafe { stela_amd_tmr_model_accesses() } > 0); + begin(); + // SAFETY: zero clock is rejected before the actual query sees any register. + assert!(matches!( + unsafe { + discovery::acquire( + &bars, + &stela_drivers::Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(discovery::Error::ClockUnavailable) + )); + assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0); + unsafe { stela_amd_tmr_model_vf() }; + assert!(matches!( + unsafe { discovery::acquire(&bars, &clock) }, + Err(discovery::Error::VfOwnerUnavailable) + )); + begin(); + unsafe { stela_amd_tmr_model_system() }; + assert!(matches!( + unsafe { discovery::acquire(&bars, &clock) }, + Err(discovery::Error::SystemFirmwareOwnerUnavailable) + )); + unsafe { stela_amd_tmr_model_end() }; + drop(window); + // SAFETY: all CPU-only fixture accesses/views have ended before retirement. + unsafe { bars.retire() }.unwrap(); + drop(bars); + assert_eq!(drops.load(Ordering::Relaxed), 1); + println!( + "AMD TMR Rust/C: full retained validated snapshot equality, actual identity/extent, pre-I/O clock refusal, missing VF/sysmem owners; generated leaf-I/O RAM model only" + ); +} + +// Test-only System wrapper: arm exactly the current test thread's next +// allocation. It does not replace any production allocator/service. +mod allocation_failure { + use std::alloc::{GlobalAlloc, Layout, System}; + use std::cell::Cell; + thread_local! { static ARMED: Cell = const { Cell::new(false) }; } + thread_local! { static CONSUMED: Cell = const { Cell::new(false) }; } + struct FaultAllocator; + #[global_allocator] + static ALLOCATOR: FaultAllocator = FaultAllocator; + // SAFETY: exact System delegation except the explicit valid null OOM + // response; TLS access is allocation-free and bounded to this test thread. + unsafe impl GlobalAlloc for FaultAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if ARMED.try_with(|v| v.replace(false)).unwrap_or(false) { + let _ = CONSUMED.try_with(|v| v.set(true)); + core::ptr::null_mut() + } else { + // SAFETY: unchanged allocator request supplied by Rust. + unsafe { System.alloc(layout) } + } + } + unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { + // SAFETY: exact System allocation and original layout from Rust. + unsafe { System.dealloc(pointer, layout) } + } + } + pub fn arm() { + CONSUMED.with(|v| v.set(false)); + ARMED.with(|v| v.set(true)); + } + pub fn disarm() -> bool { + ARMED.with(|v| v.set(false)); + CONSUMED.with(Cell::get) + } +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_binary_test.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_binary_test.c new file mode 100644 index 0000000000..aed863fd57 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_binary_test.c @@ -0,0 +1,452 @@ +/* SPDX-License-Identifier: MIT */ +/* CPU-only original-driver metadata fixtures; no device or acquisition hooks. */ +#include "../stela/discovery_binary.h" +#include "../amdgpu/amdgpu_ip_limits.h" +#include "../include/soc15_hw_ip.h" +#include +#include +#include +#include +#include +#include + +static void reference_log(void *device, const char *format, ...) +{ + (void)device; + (void)format; +} + +/* Original Linux donors intentionally retain signed comparisons. Their native + * tests use Linux's signed-overflow policy (-fwrapv), not a rewritten policy. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +#include "discovery_reference.h" +#pragma GCC diagnostic pop + +struct fixture { + uint8_t binary[8192]; + size_t size, directory, offset[TOTAL_TABLES], length[TOTAL_TABLES]; + unsigned version, dies, wide; +}; +static unsigned comparisons, mutations, accepted_mutations, official; +static void put16(void *p, uint16_t value) +{ + uint8_t *bytes = p; + bytes[0] = value; + bytes[1] = value >> 8; +} +static void put32(void *p, uint32_t value) +{ + uint8_t *bytes = p; + for (unsigned i = 0; i < 4; i++) + bytes[i] = value >> (i * 8); +} +static void put64(void *p, uint64_t value) +{ + put32(p, value); + put32((uint8_t *)p + 4, value >> 32); +} +static struct table_info *directory_entry(struct fixture *f, unsigned id) +{ + return (void *)(f->binary + f->directory + id * sizeof(struct table_info)); +} +static void checksums(struct fixture *f) +{ + for (unsigned i = 0; i < TOTAL_TABLES; i++) { + if (f->length[i]) { + struct table_info *entry = directory_entry(f, i); + put16(&entry->checksum, donor_checksum(f->binary + f->offset[i], f->length[i])); + } + } + struct binary_header *h = (void *)f->binary; + size_t start = offsetof(struct binary_header, binary_checksum) + sizeof(h->binary_checksum); + put16(&h->binary_checksum, donor_checksum(f->binary + start, f->size - start)); +} +static void declare_table(struct fixture *f, unsigned id, size_t bytes) +{ + f->size = (f->size + 3) & ~(size_t)3; + assert(f->size + bytes <= sizeof(f->binary)); + f->offset[id] = f->size; + f->length[id] = bytes; + struct table_info *entry = directory_entry(f, id); + put16(&entry->offset, f->size); + put16(&entry->size, bytes); + f->size += bytes; +} +static size_t gfx_bytes(unsigned major, unsigned minor) +{ + if (major == 1) + return minor >= 3 ? sizeof(struct gc_info_v1_3) : + minor == 2 ? sizeof(struct gc_info_v1_2) : + minor == 1 ? sizeof(struct gc_info_v1_1) : sizeof(struct gc_info_v1_0); + return minor == 1 ? sizeof(struct gc_info_v2_1) : sizeof(struct gc_info_v2_0); +} +static struct fixture make_fixture(unsigned version, unsigned ip_version, unsigned wide, + unsigned gc_major, unsigned gc_minor, unsigned variant) +{ + struct fixture f = {.version = version, .dies = 2, .wide = wide}; + f.directory = version == 2 ? offsetof(struct binary_header_v2, table_list) : + offsetof(struct binary_header, table_list); + f.size = f.directory + TOTAL_TABLES * sizeof(struct table_info); + struct binary_header *header = (void *)f.binary; + put32(&header->binary_signature, BINARY_SIGNATURE); + put16(&header->version_major, version); + if (version == 2) + put16(&((struct binary_header_v2 *)header)->num_tables, TOTAL_TABLES); + struct { unsigned hwid, instance, bases, revision; } ips[] = { + {GC_HWID, 0, 4, 3}, {SDMA0_HWID, 0, 3, 1}, {SDMA1_HWID, 3, 2, 1}, + {VCN_HWID, 0, 2, 0x42}, {VCN_HWID, 1, 1, 0x82}, + {UMC_HWID, 0, 1, 1}, {UMC_HWID, 3, 2, 1}, {DMU_HWID, 0, 1, 1}, + {WAFLC_HWID, 0, 2, 5}, {HW_ID_MAX + 1, 1, 3, 1}, {GC_HWID, 255, 0, 1}, + }; + size_t ip_bytes = 0; + for (unsigned i = 0; i < sizeof(ips) / sizeof(ips[0]); i++) + ip_bytes += offsetof(struct ip_v4, base_address) + ips[i].bases * (wide ? 8 : 4); + declare_table(&f, IP_DISCOVERY, sizeof(struct ip_discovery_header) + + f.dies * (sizeof(struct die_header) + ip_bytes)); + struct ip_discovery_header *ip_header = (void *)(f.binary + f.offset[IP_DISCOVERY]); + put32(&ip_header->signature, DISCOVERY_TABLE_SIGNATURE); + put16(&ip_header->version, ip_version); + put16(&ip_header->size, f.length[IP_DISCOVERY]); + put16(&ip_header->num_dies, f.dies); + ip_header->base_addr_64_bit = wide; + size_t at = f.offset[IP_DISCOVERY] + sizeof(*ip_header); + for (unsigned d = 0; d < f.dies; d++) { + put16(&ip_header->die_info[d].die_id, d); + put16(&ip_header->die_info[d].die_offset, at); + struct die_header *die = (void *)(f.binary + at); + put16(&die->die_id, d); + put16(&die->num_ips, sizeof(ips) / sizeof(ips[0])); + at += sizeof(*die); + for (unsigned i = 0; i < sizeof(ips) / sizeof(ips[0]); i++) { + struct ip_v4 *ip = (void *)(f.binary + at); + put16(&ip->hw_id, ips[i].hwid); + ip->instance_number = ips[i].instance; + ip->num_base_address = ips[i].bases; + ip->major = i == 0 ? 9 : 4; + ip->minor = d; + ip->revision = ips[i].revision; + ip->variant = ip_version >= 3 ? 2 : 0; + ip->sub_revision = ip_version >= 3 ? 3 : 1; /* Original harvest nibble. */ + for (unsigned k = 0; k < ips[i].bases; k++) { + uint64_t address = 0xc0000100u + d * 0x4000 + i * 0x100 + k * 0x10; + if (wide) + put64(&ip->base_address_64[k], UINT64_C(0xabcde00000000) | address); + else + put32(&ip->base_address[k], address); + } + at += offsetof(struct ip_v4, base_address) + ips[i].bases * (wide ? 8 : 4); + } + } + declare_table(&f, GC, gfx_bytes(gc_major, gc_minor)); + struct gpu_info_header *gc = (void *)(f.binary + f.offset[GC]); + put32(&gc->table_id, GC_TABLE_ID); + put16(&gc->version_major, gc_major); + put16(&gc->version_minor, gc_minor); + put32(&gc->size, f.length[GC]); + for (size_t i = sizeof(*gc); i < f.length[GC]; i += 4) + put32((uint8_t *)gc + i, 4 + i / 4); + declare_table(&f, HARVEST_INFO, sizeof(struct harvest_table)); + struct harvest_table *harvest = (void *)(f.binary + f.offset[HARVEST_INFO]); + put32(&harvest->header.signature, HARVEST_TABLE_SIGNATURE); + put16(&harvest->list[0].hw_id, VCN_HWID); + harvest->list[0].number_instance = 1; + put16(&harvest->list[1].hw_id, UMC_HWID); + harvest->list[1].number_instance = 3; + declare_table(&f, VCN_INFO, sizeof(struct vcn_info_v1_0)); + struct vcn_info_v1_0 *vcn = (void *)(f.binary + f.offset[VCN_INFO]); + put32(&vcn->header.table_id, VCN_INFO_TABLE_ID); + put16(&vcn->header.version_major, 1); + put32(&vcn->header.size_bytes, f.length[VCN_INFO]); + put32(&vcn->num_of_instances, 4); + for (unsigned i = 0; i < VCN_INFO_TABLE_MAX_NUM_INSTANCES; i++) + put32(&vcn->instance_info[i].fuse_data.all_bits, i + 1); + declare_table(&f, MALL_INFO, sizeof(struct mall_info_v1_0)); + struct mall_info_v1_0 *mall = (void *)(f.binary + f.offset[MALL_INFO]); + put32(&mall->header.table_id, MALL_INFO_TABLE_ID); + put16(&mall->header.version_major, 1 + (variant & 1)); + put32(&mall->header.size_bytes, f.length[MALL_INFO]); + put32(&mall->mall_size_per_m, 1024); + put32(&mall->m_s_present, 1); + put32(&mall->m_half_use, 2); + declare_table(&f, NPS_INFO, sizeof(struct nps_info_v1_0)); + struct nps_info_v1_0 *nps = (void *)(f.binary + f.offset[NPS_INFO]); + put32(&nps->header.table_id, NPS_INFO_TABLE_ID); + put16(&nps->header.version_major, 1); + put32(&nps->header.size_bytes, f.length[NPS_INFO]); + put32(&nps->count, 2); + put64(&nps->instance_info[0].base_address, 0x1000); + put64(&nps->instance_info[0].limit_address, 0x1fff); + put64(&nps->instance_info[1].base_address, 0x4000); + put64(&nps->instance_info[1].limit_address, 0x8fff); + put16(&header->binary_size, f.size); + checksums(&f); + return f; +} + +static void normalize(struct amdgpu_device *device) +{ + for (unsigned ip = 0; ip < MAX_HWIP; ip++) { + for (unsigned i = 0; i < HWIP_MAX_INSTANCE; i++) { + if (device->reg_offset[ip][i]) { + size_t offset = (uint8_t *)device->reg_offset[ip][i] - device->discovery.bin; + device->reg_offset[ip][i] = (void *)(uintptr_t)(offset + 1); + } + } + } + device->discovery.bin = NULL; +} +static void compare_original(const uint8_t *binary, size_t bytes) +{ + uint8_t *left = malloc(bytes), *right = malloc(bytes); + assert(left && right); + memcpy(left, binary, bytes); + memcpy(right, binary, bytes); + struct amdgpu_device old, next; + memset(&old, 0, sizeof(old)); + memset(&next, 0, sizeof(next)); + old.discovery.bin = left; + next.discovery.bin = right; + old.discovery.size = next.discovery.size = bytes; + checked = 0; + assert(!reference_validation(&old)); + checked = 1; + assert(!reference_validation(&next)); + checked = 0; + assert(!amdgpu_discovery_reg_base_init(&old)); + checked = 1; + assert(!amdgpu_discovery_reg_base_init(&next)); + checked = 0; + int gfx = amdgpu_discovery_get_gfx_info(&old); + int mall = amdgpu_discovery_get_mall_info(&old); + int vcn = amdgpu_discovery_get_vcn_info(&old); + checked = 1; + assert(gfx == amdgpu_discovery_get_gfx_info(&next)); + assert(mall == amdgpu_discovery_get_mall_info(&next)); + assert(vcn == amdgpu_discovery_get_vcn_info(&next)); + unsigned left_count = 0, right_count = 0, left_umc = 0, right_umc = 0; + checked = 0; + amdgpu_discovery_read_from_harvest_table(&old, &left_count, &left_umc); + checked = 1; + amdgpu_discovery_read_from_harvest_table(&next, &right_count, &right_umc); + assert(left_count == right_count && left_umc == right_umc); + struct amdgpu_gmc_memrange old_ranges[NPS_INFO_TABLE_MAX_NUM_INSTANCES]; + struct amdgpu_gmc_memrange next_ranges[NPS_INFO_TABLE_MAX_NUM_INSTANCES]; + memset(old_ranges, 0x5a, sizeof(old_ranges)); + memset(next_ranges, 0x5a, sizeof(next_ranges)); + uint32_t old_type = UINT32_MAX, next_type = UINT32_MAX; + int old_count = NPS_INFO_TABLE_MAX_NUM_INSTANCES, next_count = old_count; + checked = 0; + int nps = amdgpu_discovery_get_nps_info(&old, &old_type, old_ranges, &old_count, false); + checked = 1; + assert(nps == amdgpu_discovery_get_nps_info(&next, &next_type, next_ranges, &next_count, false)); + assert(old_type == next_type && old_count == next_count); + assert(!memcmp(old_ranges, next_ranges, sizeof(old_ranges))); + assert(!memcmp(left, right, bytes)); + normalize(&old); + normalize(&next); + assert(!memcmp(&old, &next, sizeof(old))); + free(left); + free(right); + comparisons++; +} +static void harvest_lookup(void) +{ + for (unsigned version = 0; version <= 2; version++) { + struct fixture f = make_fixture(version, 2, 0, 1, 0, 0); + uint8_t old_bytes[sizeof(f.binary)], next_bytes[sizeof(f.binary)]; + memcpy(old_bytes, f.binary, sizeof(old_bytes)); + memcpy(next_bytes, f.binary, sizeof(next_bytes)); + struct amdgpu_device old, next; + memset(&old, 0, sizeof(old)); + memset(&next, 0, sizeof(next)); + old.discovery.bin = old_bytes; + next.discovery.bin = next_bytes; + old.discovery.size = next.discovery.size = f.size; + checked = 0; + assert(!amdgpu_discovery_reg_base_init(&old)); + checked = 1; + assert(!amdgpu_discovery_reg_base_init(&next)); + uint32_t count = 0; + checked_harvest(&next, &count); + assert(count == 4); + assert(next.vcn.harvest_config == 3 && next.vcn.inst_mask == 0); + assert(next.jpeg.inst_mask == 0 && next.harvest_ip_mask == AMD_HARVEST_IP_DMU_MASK); + if (version < 2) { + uint32_t old_count = 0; + checked = 0; + amdgpu_discovery_read_harvest_bit_per_ip(&old, &old_count); + assert(old_count == count); + normalize(&old); + normalize(&next); + assert(!memcmp(&old, &next, sizeof(old))); + } else { + /* Explicit corrected behavior: the old fixed directory would choose + * offset6 (num_tables), not this valid v2 IP offset64. Never execute + * that unsafe old walk as a successful native result. */ + const struct binary_header *fixed = (const void *)f.binary; + assert(fixed->table_list[IP_DISCOVERY].offset == TOTAL_TABLES); + assert(fixed->table_list[IP_DISCOVERY].offset != f.offset[IP_DISCOVERY]); + } + } +} + +static void boundary_layouts(void) +{ + struct fixture f = make_fixture(2, 4, 1, 2, 1, 1); + struct ip_discovery_header *ip = (void *)(f.binary + f.offset[IP_DISCOVERY]); + put16(&ip->num_dies, 16); + size_t at = f.offset[IP_DISCOVERY] + sizeof(*ip); + for (unsigned i = 0; i < 16; i++) { + put16(&ip->die_info[i].die_id, i); + put16(&ip->die_info[i].die_offset, at); + struct die_header *die = (void *)(f.binary + at); + put16(&die->die_id, i); + put16(&die->num_ips, 0); + at += sizeof(*die); + } + checksums(&f); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + compare_original(f.binary, f.size); + put16(&ip->num_dies, 0); + checksums(&f); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + compare_original(f.binary, f.size); + put16(&ip->num_dies, 1); + struct die_header *die = (void *)(f.binary + ip->die_info[0].die_offset); + put16(&die->num_ips, 63); + at = ip->die_info[0].die_offset + sizeof(*die); + for (unsigned i = 0; i < 64; i++) { + struct ip_v4 *entry = (void *)(f.binary + at); + memset(entry, 0, offsetof(struct ip_v4, base_address)); + put16(&entry->hw_id, UMC_HWID); + entry->instance_number = i % HWIP_MAX_INSTANCE; + at += offsetof(struct ip_v4, base_address); + } + checksums(&f); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + compare_original(f.binary, f.size); + put16(&die->num_ips, 64); + checksums(&f); + assert(amdgpu_discovery_binary_validate(f.binary, f.size) == AMDGPU_DISCOVERY_BINARY_INVALID); + mutations++; + /* Five real v2 directory entries are sufficient for original initialization; + * optional NPS directory access is now bounded instead of indexing past it. */ + f = make_fixture(2, 4, 0, 1, 0, 0); + put16(&((struct binary_header_v2 *)f.binary)->num_tables, 5); + checksums(&f); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + assert(!amdgpu_discovery_binary_table(f.binary, f.size, NPS_INFO)); +} + +static void refused(struct fixture *f) +{ + uint8_t saved[sizeof(f->binary)]; + memcpy(saved, f->binary, sizeof(saved)); + assert(amdgpu_discovery_binary_validate(f->binary, f->size) != AMDGPU_DISCOVERY_BINARY_OK); + assert(!memcmp(saved, f->binary, sizeof(saved))); + mutations++; +} +static void malformed(void) +{ + const struct fixture good = make_fixture(2, 4, 1, 1, 3, 0); + struct fixture f; + for (size_t bytes = 0; bytes < good.size; bytes++) { + uint8_t *shortened = malloc(bytes ? bytes : 1); + assert(shortened); + memcpy(shortened, good.binary, bytes); + assert(amdgpu_discovery_binary_validate(shortened, bytes)); + free(shortened); + mutations++; + } + for (unsigned which = 0; which < 22; which++) { + f = good; + struct binary_header *header = (void *)f.binary; + struct ip_discovery_header *ip = (void *)(f.binary + f.offset[IP_DISCOVERY]); + struct die_header *die = (void *)(f.binary + ip->die_info[0].die_offset); + struct ip_v4 *first = (void *)((uint8_t *)die + sizeof(*die)); + switch (which) { + case 0: put16(&header->binary_size, 9); break; + case 1: put16(&header->binary_size, UINT16_MAX); break; + case 2: put16(&header->version_major, 3); break; + case 3: put16(&((struct binary_header_v2 *)header)->num_tables, 4); break; + case 4: put16(&((struct binary_header_v2 *)header)->num_tables, UINT16_MAX); break; + case 5: put16(&directory_entry(&f, IP_DISCOVERY)->offset, 0); break; + case 6: put16(&directory_entry(&f, IP_DISCOVERY)->offset, f.size - 1); break; + case 7: put16(&ip->size, 79); break; + case 8: put16(&ip->size, UINT16_MAX); break; + case 9: put16(&ip->num_dies, 17); break; + case 10: put16(&ip->die_info[0].die_offset, 1); break; + case 11: put16(&ip->die_info[0].die_offset, f.size - 1); break; + case 12: put16(&die->die_id, 3); break; + case 13: put16(&die->num_ips, UINT16_MAX); break; + case 14: first->num_base_address = 255; break; + case 15: first->instance_number = 32; break; + case 16: put16(&ip->version, 2); break; + case 17: put32(f.binary + f.offset[GC] + offsetof(struct gc_info_v1_0, gc_num_sa_per_se), 0); break; + case 18: put32(f.binary + f.offset[GC] + offsetof(struct gpu_info_header, size), UINT32_MAX); break; + case 19: put32(f.binary + f.offset[VCN_INFO] + offsetof(struct vcn_info_header, size_bytes), 12); break; + case 20: put32(f.binary + f.offset[NPS_INFO] + offsetof(struct nps_info_v1_0, count), 13); break; + case 21: put16(&directory_entry(&f, GC)->offset, f.offset[IP_DISCOVERY]); break; + } + checksums(&f); /* Uses only builder-owned original spans, never mutated offsets. */ + refused(&f); + } + assert(amdgpu_discovery_binary_validate(NULL, 0) == AMDGPU_DISCOVERY_BINARY_INVALID); + /* Optional integrity failures retain original nonfatal/lazy policy. */ + f = good; + put16(&directory_entry(&f, NPS_INFO)->checksum, 0); + size_t start = offsetof(struct binary_header, binary_checksum) + 2; + put16(f.binary + offsetof(struct binary_header, binary_checksum), + donor_checksum(f.binary + start, f.size - start)); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + compare_original(f.binary, f.size); + /* Deterministic field/byte mutation with repaired original checksums. */ + for (unsigned i = 0; i < 4096; i++) { + f = good; + size_t at = (i * 127u + 37u) % f.size; + f.binary[at] ^= 1u << (i % 8); + checksums(&f); + uint8_t saved[sizeof(f.binary)]; + memcpy(saved, f.binary, sizeof(saved)); + enum amdgpu_discovery_binary_status result = amdgpu_discovery_binary_validate(f.binary, f.size); + assert(!memcmp(saved, f.binary, sizeof(saved))); + if (!result) { + compare_original(f.binary, f.size); + accepted_mutations++; + } + mutations++; + } +} +int main(int argc, char **argv) +{ + for (unsigned binary = 0; binary <= 2; binary++) { + for (unsigned layout = 1; layout <= 5; layout++) { + for (unsigned gfx = 0; gfx < 8; gfx++) { + for (unsigned variant = 0; variant < 2; variant++) { + struct fixture f = make_fixture(binary, layout == 5 ? 4 : layout, layout == 5, + gfx < 5 ? 1 : 2, gfx < 5 ? gfx : gfx - 5, variant); + assert(!amdgpu_discovery_binary_validate(f.binary, f.size)); + compare_original(f.binary, f.size); + } + } + } + } + harvest_lookup(); + boundary_layouts(); + malformed(); + for (int i = 1; i < argc; i++) { + FILE *file = fopen(argv[i], "rb"); + assert(file); + uint8_t bytes[UINT16_MAX + 1]; + size_t count = fread(bytes, 1, sizeof(bytes), file); + assert(!ferror(file) && feof(file) && count < sizeof(bytes)); + assert(!fclose(file)); + assert(!amdgpu_discovery_binary_validate(bytes, count)); + compare_original(bytes, count); + official++; + } + printf("AMD discovery: %u original consumer comparisons (%u external inputs), %u mutations/truncations (%u accepted); no hardware\n", + comparisons, official, mutations, accepted_mutations); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_file.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_file.c new file mode 100644 index 0000000000..ef07db8927 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_file.c @@ -0,0 +1,100 @@ +/* SPDX-License-Identifier: MIT */ +/* Actual whole Linux file wrapper vs frozen guarded original. CPU only. */ +#include "../stela/discovery_file.h" +#include "../amdgpu/amdgpu_discovery_file_core.h" +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; +struct firmware { size_t size; const uint8_t *data; }; +struct amdgpu_device { void *dev; unsigned ddev; struct { uint32_t size; } discovery; }; +static struct firmware image; +static int request_status, amdgpu_discovery; +static char trace[8192];static size_t used; +static unsigned comparisons; +static void event(const char *format,...) +{ + va_list a;va_start(a,format);int n=vsnprintf(trace+used,sizeof(trace)-used,format,a);va_end(a); + assert(n>=0&&(size_t)n=0&&(size_t)n=0&&(size_t)nbinary_size); + const uint32_t capacities[]={0,1,minimum-1,minimum,minimum+1,(uint32_t)bytes-1,(uint32_t)bytes,(uint32_t)bytes+1,65536}; + for(unsigned i=0;ibinary_size)); + assert(stela_amd_discovery_file_validate(NULL,0,0)==AMDGPU_DISCOVERY_FILE_TOO_SMALL); + assert(stela_amd_discovery_file_validate(NULL,20,0)==AMDGPU_DISCOVERY_FILE_TOO_LARGE); + assert(stela_amd_discovery_file_validate(NULL,20,20)==AMDGPU_DISCOVERY_FILE_INVALID); + printf("AMD selected-file: %u whole original/current request/log/copy/release comparisons; actual extent/zero-tail/error atomicity; CPU only\n",comparisons); + return 0; +} + +/* Test-only original packed-header query, no parallel Rust wire format. */ +size_t stela_amd_file_fixture_declared(const uint8_t *source,size_t bytes) +{ + assert(!amdgpu_discovery_binary_validate(source,bytes)); + const struct binary_header *header=(const void*)source; + return header->binary_size; +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_file.rs b/crates/stela-drivers/src/gpu/amd/tests/discovery_file.rs new file mode 100644 index 0000000000..1f7b78afcd --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_file.rs @@ -0,0 +1,541 @@ +//! Separate generated same-authority CPU harness, using actual production Rust, +//! canonical Catalog/Image and existing original MM leaf-I/O instrumentation. +use super::*; +use crate::{discovery, dynamic_ip_tests::allocation_failure, firmware, pci}; +use firmware::{Catalog, Provider}; +use sha2::{Digest, Sha256}; +use std::cell::Cell; + +unsafe extern "C" { + fn stela_amd_file_fixture_declared(source: *const u8, bytes: usize) -> usize; + fn stela_amd_tmr_fixture(bytes: &mut usize) -> *const u8; + fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize); + fn stela_amd_tmr_model_accesses() -> u32; + fn stela_amd_tmr_model_vf(); + fn stela_amd_tmr_model_system(); + fn stela_amd_tmr_model_end(); + fn stela_amd_ip_oracle( + source: *const u8, + bytes: usize, + counts: &mut discovery::IpCounts, + hwips: &mut u32, + instances: &mut u32, + ); + fn stela_amd_ip_oracle_fact(hwip: u32, instance: u32, segment: u32, kind: u32) -> u64; +} +struct FileConfig(u16); +impl ConfigSpace for FileConfig { + fn read32(&self, offset: u16) -> u32 { + match offset { + 0 => (u32::from(self.0) << 16) | 0x1002, + 8 => 0x1200_0045, + 12 => 0, + 44 => 0x5678_abcd, + _ => panic!("unexpected config read"), + } + } + fn write32(&mut self, _: u16, _: u32) { + panic!("no config writes") + } + fn write16(&mut self, _: u16, _: u16) { + panic!("no config writes") + } + fn write8(&mut self, _: u16, _: u8) { + panic!("no config writes") + } +} +fn policy(discovery: i32) -> pci::Policy { + pci::Policy { + si_built: true, + cik_built: true, + radeon_built: false, + si_support: -1, + cik_support: -1, + experimental: 0, + discovery, + force_asic: -1, + memory_encrypted: false, + firmware_drivers_only: false, + modeset: -1, + } +} +fn file_function(device: u16) -> Function { + Function::new( + Address { + segment: 4, + bus: 0x81, + device: 3, + function: 0, + }, + FileConfig(device), + ) + .unwrap() +} +fn make_catalog(request: &discovery::FileRequest<'_>, bytes: &[u8], member: &str) -> Catalog { + Catalog::from_handoff(vec![firmware::Resource { + name: request.name(), + target: request.target(), + provenance: firmware::Provenance { + source: "original CPU fixture", + revision: "immutable-input", + member, + license: "test-only", + }, + expected_length: bytes.len(), + expected_sha256: Sha256::digest(bytes).into(), + bytes: bytes.to_vec(), + }]) + .unwrap() +} +struct ObservedProvider<'a> { + catalog: &'a Catalog, + calls: Cell, + alternate: Option>, +} +impl Provider for ObservedProvider<'_> { + fn load( + &self, + requirement: firmware::Requirement<'_>, + ) -> Result, firmware::Error> { + assert!( + unsafe { stela_amd_tmr_model_accesses() } > 0, + "provider before original TMR query" + ); + self.calls.set(self.calls.get() + 1); + self.catalog.load(self.alternate.unwrap_or(requirement)) + } +} +fn make_provider(catalog: &Catalog) -> ObservedProvider<'_> { + ObservedProvider { + catalog, + calls: Cell::new(0), + alternate: None, + } +} +fn facts(ip: &discovery::FileIp<'_, '_>, bytes: &[u8]) { + assert_eq!(&ip.acquired_bytes()[..bytes.len()], bytes); + assert!(ip.acquired_bytes()[bytes.len()..].iter().all(|&v| v == 0)); + let mut expected = discovery::IpCounts::default(); + let (mut hwips, mut instances) = (0, 0); + unsafe { + stela_amd_ip_oracle( + ip.acquired_bytes().as_ptr(), + ip.acquired_bytes().len(), + &mut expected, + &mut hwips, + &mut instances, + ) + }; + assert_eq!(ip.counts(), expected); + for hwip in 0..hwips { + for instance in 0..instances { + assert_eq!( + ip.version(hwip, instance), + Some(unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 0) } as u32) + ); + let count = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 1) }; + if count == u64::MAX { + assert_eq!(ip.register_count(hwip, instance), None); + } else { + assert_eq!(ip.register_count(hwip, instance), Some(count as u32)); + for segment in 0..count as u32 { + assert_eq!( + ip.register_base(hwip, instance, segment), + Some( + unsafe { stela_amd_ip_oracle_fact(hwip, instance, segment, 2) } as u32 + ) + ); + } + assert_eq!(ip.register_base(hwip, instance, count as u32), None); + } + } + } +} +pub(super) fn selected_files(authority: &Authority) { + let mut function = file_function(0xffff); + // SAFETY: actual public Function observes immutable synthetic config only. + let matched = unsafe { pci::identify(&mut function, policy(2)) }.unwrap(); + assert_eq!(matched.ip_path(), pci::IpPath::Dynamic); + let (resource, drops) = super::resource(0x1400_0000, 0x60000, ResourceKind::Registers); + // SAFETY: canonical RAM-only owner, no genuine hardware activation claim. + let mut bars = unsafe { + AttachedBars::attach_matched( + authority, + &matched, + RegisterBar { index: 5, resource }, + None, + ) + } + .unwrap(); + let window = bars.registers().unwrap(); + let clock = Clock { + ticks_per_microsecond: 1, + }; + let mut size = 0; + let source = unsafe { stela_amd_tmr_fixture(&mut size) }; + let source_bytes = unsafe { core::slice::from_raw_parts(source, size) }; + let begin = || unsafe { + stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size) + }; + allocation_failure::arm(0); + let no_allocation = discovery::FileRequest::new(&bars).unwrap(); + drop(no_allocation); + assert!(!allocation_failure::disarm()); + let request = discovery::FileRequest::new(&bars).unwrap(); + assert_eq!(request.name(), "amdgpu/ip_discovery.bin"); + assert_eq!( + request.target(), + firmware::Target { + driver: "amd-amdgpu-ip-discovery", + hardware: "pci-1002-ffff", + revision: "pci-45;subsys-abcd-5678", + board: None + } + ); + let catalog = make_catalog(&request, source_bytes, "fixtures/ip-discovery.bin"); + let provider = make_provider(&catalog); + begin(); + // SAFETY: only the bounded generated C RAM leaf handles original MM I/O. + let discovery::SelectedFile::Dynamic(ip) = + unsafe { request.acquire(&provider, &clock) }.unwrap() + else { + panic!("dynamic admission became static") + }; + assert_eq!(provider.calls.get(), 1); + assert_eq!(ip.identity(), bars.identity()); + assert_eq!(ip.image().bytes(), source_bytes); + assert_eq!( + ip.image().sha256(), + <[u8; 32]>::from(Sha256::digest(source_bytes)) + ); + assert_eq!(ip.image().provenance().member, "fixtures/ip-discovery.bin"); + facts(&ip, source_bytes); + drop(ip); + // Fresh immutable real inputs exercise original file policy/decoder unchanged. + let mut real_inputs = 0; + if let Ok(paths) = std::env::var("STELA_AMD_DISCOVERY_INPUTS") { + for path in paths.lines() { + let bytes = std::fs::read(path).unwrap(); + let request = discovery::FileRequest::new(&bars).unwrap(); + let member = std::path::Path::new(path) + .file_name() + .unwrap() + .to_str() + .unwrap(); + let catalog = make_catalog(&request, &bytes, member); + let provider = make_provider(&catalog); + begin(); + let discovery::SelectedFile::Dynamic(ip) = + unsafe { request.acquire(&provider, &clock) }.unwrap() + else { + panic!("static") + }; + facts(&ip, &bytes); + assert_eq!(ip.image().bytes(), bytes); + assert_eq!(ip.image().provenance().member, member); + real_inputs += 1; + } + } + // Each actual native Vec OOM point: query-storage precedes provider load; + // the three IP allocations follow validated image acquisition. + for allocation in 0..4 { + begin(); + provider.calls.set(0); + let request = discovery::FileRequest::new(&bars).unwrap(); + allocation_failure::arm(allocation); + let error = unsafe { request.acquire(&provider, &clock) }.err().unwrap(); + assert!(allocation_failure::disarm()); + assert!(unsafe { stela_amd_tmr_model_accesses() } > 0); + assert!(matches!( + (allocation, error), + ( + 0, + discovery::FileError::Acquire(discovery::Error::PostQueryAllocation) + ) | ( + 1..=3, + discovery::FileError::Ip(discovery::Error::PostAcquireAllocation) + ) + )); + assert_eq!(provider.calls.get(), u32::from(allocation != 0)); + } + begin(); + provider.calls.set(0); + let error = unsafe { + discovery::FileRequest::new(&bars).unwrap().acquire( + &provider, + &Clock { + ticks_per_microsecond: 0, + }, + ) + } + .err() + .unwrap(); + assert!(matches!( + error, + discovery::FileError::Acquire(discovery::Error::ClockUnavailable) + )); + assert_eq!(provider.calls.get(), 0); + assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0); + for system in [false, true] { + begin(); + provider.calls.set(0); + unsafe { + if system { + stela_amd_tmr_model_system() + } else { + stela_amd_tmr_model_vf() + } + }; + let error = unsafe { + discovery::FileRequest::new(&bars) + .unwrap() + .acquire(&provider, &clock) + } + .err() + .unwrap(); + assert!(matches!( + error, + discovery::FileError::Acquire( + discovery::Error::VfOwnerUnavailable + | discovery::Error::SystemFirmwareOwnerUnavailable + ) + )); + assert_eq!(provider.calls.get(), 0); + } + let empty = Catalog::from_handoff(vec![]).unwrap(); + let missing = make_provider(&empty); + for fail_diagnostic_name in [false, true] { + begin(); + let request = discovery::FileRequest::new(&bars).unwrap(); + if fail_diagnostic_name { + allocation_failure::arm(1); + } + let error = unsafe { request.acquire(&missing, &clock) }.err().unwrap(); + if fail_diagnostic_name { + assert!(allocation_failure::disarm()); + } + let discovery::FileError::Source { + error: discovery::FileSourceError::Provider(error), + pending: discovery::FileFailureDiagnostics::OmittedByOriginalOption2, + } = error + else { + panic!("wrong source failure") + }; + assert_eq!(error.kind, firmware::ErrorKind::Missing); + if fail_diagnostic_name { + assert!(error.name.as_str().is_none()); + } + } + // A real canonical image returned for the wrong request is still refused. + let mut alternate = make_provider(&catalog); + alternate.alternate = Some(firmware::Requirement { + name: "amdgpu/ip_discovery.bin", + target: firmware::Target { + driver: "amd-amdgpu-ip-discovery", + hardware: "pci-1002-ffff", + revision: "pci-45;subsys-abcd-5678", + board: None, + }, + minimum_bytes: 1, + }); + // The alternate uses identical image here; verify it is accepted first. + begin(); + drop( + unsafe { + discovery::FileRequest::new(&bars) + .unwrap() + .acquire(&alternate, &clock) + } + .unwrap(), + ); + let other = Catalog::from_handoff(vec![firmware::Resource { + name: "other.bin", + target: firmware::Target { + driver: "other", + hardware: "other", + revision: "other", + board: None, + }, + provenance: firmware::Provenance { + source: "fixture", + revision: "1", + member: "other.bin", + license: "test", + }, + expected_length: source_bytes.len(), + expected_sha256: Sha256::digest(source_bytes).into(), + bytes: source_bytes.to_vec(), + }]) + .unwrap(); + let mut wrong = make_provider(&other); + wrong.alternate = Some(firmware::Requirement { + name: "other.bin", + target: firmware::Target { + driver: "other", + hardware: "other", + revision: "other", + board: None, + }, + minimum_bytes: 1, + }); + begin(); + assert!(matches!( + unsafe { + discovery::FileRequest::new(&bars) + .unwrap() + .acquire(&wrong, &clock) + }, + Err(discovery::FileError::Source { + error: discovery::FileSourceError::WrongImage, + .. + }) + )); + let other_target = firmware::Target { + driver: "amd-amdgpu-ip-discovery", + hardware: "pci-1002-ffff", + revision: "pci-46;subsys-abcd-5678", + board: None, + }; + let other_same_name = Catalog::from_handoff(vec![firmware::Resource { + name: "amdgpu/ip_discovery.bin", + target: other_target, + provenance: firmware::Provenance { + source: "fixture", + revision: "1", + member: "same-name.bin", + license: "test", + }, + expected_length: source_bytes.len(), + expected_sha256: Sha256::digest(source_bytes).into(), + bytes: source_bytes.to_vec(), + }]) + .unwrap(); + let mut wrong_target = make_provider(&other_same_name); + wrong_target.alternate = Some(firmware::Requirement { + name: "amdgpu/ip_discovery.bin", + target: other_target, + minimum_bytes: 1, + }); + begin(); + assert!(matches!( + unsafe { + discovery::FileRequest::new(&bars) + .unwrap() + .acquire(&wrong_target, &clock) + }, + Err(discovery::FileError::Source { + error: discovery::FileSourceError::WrongImage, + .. + }) + )); + // A valid manifest cannot hide invalid actual bytes or a too-large source. + let mut oversized = source_bytes.to_vec(); + oversized.extend_from_slice(&[0; 4]); + let mut corrupt = source_bytes.to_vec(); + corrupt[0] ^= 1; + for bytes in [&oversized[..], &corrupt[..]] { + let request = discovery::FileRequest::new(&bars).unwrap(); + let bad = make_catalog(&request, bytes, "bad.bin"); + let bad = make_provider(&bad); + begin(); + assert!(matches!( + unsafe { request.acquire(&bad, &clock) }, + Err(discovery::FileError::Source { + error: discovery::FileSourceError::Policy(_), + pending: discovery::FileFailureDiagnostics::OmittedByOriginalOption2 + }) + )); + } + let mut short = source_bytes.to_vec(); + // Original binary_size field comes from the actual retained packed header; + // fixture helper exposes it without copying a Rust wire-format definition. + let declared = unsafe { stela_amd_file_fixture_declared(source, size) }; + assert!(declared > 16 && declared <= short.len()); + short.truncate(declared - 1); + let request = discovery::FileRequest::new(&bars).unwrap(); + let short_catalog = make_catalog(&request, &short, "short.bin"); + let short_provider = make_provider(&short_catalog); + begin(); + assert!(matches!( + unsafe { request.acquire(&short_provider, &clock) }, + Err(discovery::FileError::Source { + error: discovery::FileSourceError::Policy(_), + .. + }) + )); + unsafe { stela_amd_tmr_model_end() }; + drop(window); + unsafe { bars.retire() }.unwrap(); + drop(bars); + assert_eq!(drops.load(Ordering::Relaxed), 1); + // Legacy static selected-file inventory never becomes dynamic facts. Missing + // optional inventory reports its still-pending original version/RAS check. + for option in [-1, 2] { + let mut function = file_function(0x6860); + let matched = unsafe { pci::identify(&mut function, policy(option)) }.unwrap(); + assert_eq!(matched.ip_path(), pci::IpPath::SocStatic); + let (resource, drops) = super::resource(0x1500_0000, 0x60000, ResourceKind::Registers); + let mut bars = unsafe { + AttachedBars::attach_matched( + authority, + &matched, + RegisterBar { index: 5, resource }, + None, + ) + } + .unwrap(); + let window = bars.registers().unwrap(); + let request = discovery::FileRequest::new(&bars).unwrap(); + assert_eq!( + request.name(), + if option == 2 { + "amdgpu/ip_discovery.bin" + } else { + "amdgpu/vega10_ip_discovery.bin" + } + ); + let good = make_catalog(&request, source_bytes, "static.bin"); + let good = make_provider(&good); + unsafe { + stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size) + }; + let discovery::SelectedFile::Static(inventory) = + unsafe { request.acquire(&good, &clock) }.unwrap() + else { + panic!("static inventory became dynamic") + }; + assert_eq!(inventory.acquired_bytes(), source_bytes); + assert_eq!(inventory.image().provenance().member, "static.bin"); + assert_eq!(inventory.identity(), bars.identity()); + drop(inventory); + unsafe { + stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, size) + }; + let error = unsafe { + discovery::FileRequest::new(&bars) + .unwrap() + .acquire(&missing, &clock) + } + .err() + .unwrap(); + let discovery::FileError::Source { pending, .. } = error else { + panic!("wrong static failure") + }; + assert_eq!( + pending, + if option == 2 { + discovery::FileFailureDiagnostics::OmittedByOriginalOption2 + } else { + discovery::FileFailureDiagnostics::DiscoveryVersionAndRasCheckRequired + } + ); + unsafe { stela_amd_tmr_model_end() }; + drop(window); + unsafe { bars.retire() }.unwrap(); + drop(bars); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } + println!( + "AMD selected-file Rust/C: actual admitted source/provider owners, query-before-load, retained image/provenance, same original facts, static inventory isolation, four Vec OOMs + provider diagnostic OOM, missing owners, pending original failure diagnostics; {real_inputs} unchanged real inputs; CPU only" + ); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_file_reference.h b/crates/stela-drivers/src/gpu/amd/tests/discovery_file_reference.h new file mode 100644 index 0000000000..2d0630bef1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_file_reference.h @@ -0,0 +1,74 @@ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Frozen a239 guarded original file consumer, test only. */ +#define amdgpu_discovery_read_binary_from_file original_read_file +static int amdgpu_discovery_read_binary_from_file(struct amdgpu_device *adev, + uint8_t *binary, + const char *fw_name) +{ + const struct firmware *fw; + int r; + + r = firmware_request_nowarn(&fw, fw_name, adev->dev); + if (r) { + if (amdgpu_discovery == 2) + dev_err(adev->dev, "can't load firmware \"%s\"\n", fw_name); + else + drm_info(&adev->ddev, "Optional firmware \"%s\" was not found\n", fw_name); + return r; + } + + if (fw->size > adev->discovery.size) { + dev_err(adev->dev, + "ip discovery firmware \"%s\" too large (%zu > %u)\n", + fw_name, fw->size, adev->discovery.size); + release_firmware(fw); + return -EINVAL; + } + + /* Ensure the firmware is at least large enough to contain the + * binary header fields. + */ + if (fw->size < offsetof(struct binary_header, binary_size) + + sizeof(((struct binary_header *)0)->binary_size)) { + dev_err(adev->dev, + "ip discovery firmware \"%s\" too small (%zu)\n", + fw_name, fw->size); + release_firmware(fw); + return -EINVAL; + } + + /* A short file must not borrow zero-filled TMR padding as firmware data. */ + if (amdgpu_discovery_binary_validate(fw->data, fw->size) != + AMDGPU_DISCOVERY_BINARY_OK) { + release_firmware(fw); + return -EINVAL; + } + + memcpy((u8 *)binary, (u8 *)fw->data, fw->size); + release_firmware(fw); + + return 0; +} +#undef amdgpu_discovery_read_binary_from_file diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.c new file mode 100644 index 0000000000..13398c4f91 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.c @@ -0,0 +1,249 @@ +/* SPDX-License-Identifier: MIT */ +/* Actual shared/current Linux consumer and independent frozen original oracle. */ +#include "../stela/discovery_ip.h" +#include "../stela/discovery_binary.h" +#include "../amdgpu/amdgpu_discovery_ip_core.h" +#include +#include +#include +#include +#include +#include +#include + +struct va_format { const char *fmt; va_list *va; }; +struct amdgpu_device { + void *dev; + struct { uint8_t *bin; size_t size; } discovery; + struct { uint16_t xcc_mask; } gfx; + struct { int num_instances; uint32_t sdma_mask; } sdma; + struct { uint8_t num_vcn_inst; struct {uint8_t vcn_config;} inst[AMDGPU_MAX_VCN_INSTANCES]; uint16_t inst_mask; } vcn; + struct {uint16_t inst_mask;} jpeg; + struct {uint32_t num_instances;} vpe; + struct {int num_umc;} gmc; + struct {uint32_t node_inst_num;} umc; + uint32_t *reg_offset[MAX_HWIP][HWIP_MAX_INSTANCE]; + uint32_t ip_versions[MAX_HWIP][HWIP_MAX_INSTANCE]; +}; +static const char *hw_id_names[HW_ID_MAX]; +static char logs[2][262144];static size_t log_at[2];static unsigned current; +static void log_message(const char *format, va_list args) +{ + if (!strcmp(format,"%pV")) { + struct va_format *vaf=va_arg(args,struct va_format *); + log_at[current]+=(size_t)vsnprintf(logs[current]+log_at[current],sizeof(logs[current])-log_at[current],vaf->fmt,*vaf->va); + } else log_at[current]+=(size_t)vsnprintf(logs[current]+log_at[current],sizeof(logs[current])-log_at[current],format,args); + assert(log_at[current]discovery.bin,a->discovery.size,id);return *out?0:-EINVAL;} +#include "discovery_ip_reference.h" +#include "discovery-ip-linux.inc" + +size_t stela_amd_ip_fixture(uint8_t *,size_t,unsigned,unsigned,unsigned); +static unsigned comparisons, native_cases, malformed; +static void seed(struct amdgpu_device *a,unsigned seed) +{ + a->gfx.xcc_mask=0xf1f1;a->vcn.inst_mask=0xfffa;a->jpeg.inst_mask=0xf0ff;a->sdma.sdma_mask=0xff00ff00; + a->vcn.num_vcn_inst=seed%5;a->sdma.num_instances=(int)seed-1; + a->vpe.num_instances=seed%3;a->gmc.num_umc=seed;a->umc.node_inst_num=seed; + for(unsigned i=0;ivcn.inst[i].vcn_config=(uint8_t)(seed+i); + a->ip_versions[XGMI_HWIP][0]=seed&1?0x09040100:0; + if(seed==8){a->vcn.num_vcn_inst=255;a->sdma.num_instances=INT_MAX; + a->vpe.num_instances=UINT32_MAX;a->gmc.num_umc=INT_MAX;a->umc.node_inst_num=UINT32_MAX;} +} +static void compare(const uint8_t *binary,size_t bytes,unsigned state) +{ + uint8_t *left=malloc(bytes),*right=malloc(bytes);assert(left&&right); + memcpy(left,binary,bytes);memcpy(right,binary,bytes); + struct amdgpu_device a={0},b={0};seed(&a,state);b=a; + a.discovery.bin=left;b.discovery.bin=right;a.discovery.size=b.discovery.size=bytes; + memset(logs,0,sizeof(logs));memset(log_at,0,sizeof(log_at));memset(acquisitions,0,sizeof(acquisitions));memset(lookups,0,sizeof(lookups)); + current=0;int expected=ip_donor_amdgpu_discovery_reg_base_init(&a); + current=1;int status=amdgpu_discovery_reg_base_init(&b); + assert(expected==status && acquisitions[0]==acquisitions[1]&&lookups[0]==lookups[1]); + assert(!memcmp(left,right,bytes));assert(log_at[0]==log_at[1]&&!memcmp(logs[0],logs[1],log_at[0])); + for(unsigned ip=0;ipoffset); + for(unsigned d=0;dnum_dies;d++){ + size_t pos=h->die_info[d].die_offset;const struct die_header *die=(const void*)(binary+pos);pos+=sizeof(*die); + for(unsigned n=0;nnum_ips;n++){ + const struct ip_v4 *ip=(const void*)(binary+pos); + if(pos+offsetof(struct ip_v4,base_address)==offset)return ip->num_base_address; + pos+=sizeof(*ip)+ip->num_base_address*(h->base_addr_64_bit?8:4); + } + } + assert(0);return 0; +} +static void native(const uint8_t *binary,size_t bytes) +{ + struct stela_amd_ip_shape shape=stela_amd_discovery_ip_shape();size_t cells=shape.hw_ip_count*shape.instances; + assert(shape.hw_ip_count==MAX_HWIP&&shape.instances==HWIP_MAX_INSTANCE); + uint8_t *work=malloc(bytes+1),*raw=malloc(bytes);uint32_t *versions=malloc(cells*4); + struct stela_amd_ip_binding *bindings=malloc(cells*sizeof(*bindings));assert(work&&raw&&versions&&bindings); + memcpy(work+1,binary,bytes);memcpy(raw,binary,bytes); // Entire allocation deliberately unaligned. + struct stela_amd_ip_counts counts; + int result=stela_amd_discovery_ip_decode(work+1,bytes,versions,cells,bindings,cells,&counts);assert(!result); + struct amdgpu_device a={0};a.discovery.bin=raw;a.discovery.size=bytes; + current=0;log_at[0]=0;assert(!ip_donor_amdgpu_discovery_reg_base_init(&a)); + assert(!memcmp(work+1,raw,bytes));assert(!memcmp(versions,a.ip_versions,cells*4)); + assert(counts.xcc_mask==a.gfx.xcc_mask&&counts.vcn_mask==a.vcn.inst_mask&&counts.jpeg_mask==a.jpeg.inst_mask); + assert(counts.vcn_count==a.vcn.num_vcn_inst&&counts.sdma_count==a.sdma.num_instances&&counts.sdma_mask==a.sdma.sdma_mask); + assert(counts.vpe_count==a.vpe.num_instances&&counts.umc_count==a.gmc.num_umc&&counts.node_count==a.umc.node_inst_num); + for(unsigned i=0;ioffset==(uintptr_t)a.reg_offset[ip][i]-(uintptr_t)raw);assert(b->count==count_for(binary,bytes,b->offset));} + else assert(b->offset==UINT32_MAX&&b->count==0); + } + free(work);free(raw);free(versions);free(bindings);native_cases++; +} +static void checksum(uint8_t *binary,size_t bytes) +{ + struct binary_header *h=(void*)binary; + for(unsigned i=0;isize)t->checksum=amdgpu_discovery_calculate_checksum(binary+t->offset,t->size); + } + size_t start=offsetof(struct binary_header,binary_checksum)+2; + h->binary_checksum=amdgpu_discovery_calculate_checksum(binary+start,h->binary_size-start); +} +static struct ip_v4 *record(uint8_t *binary,size_t bytes,unsigned die,unsigned index) +{ + const struct table_info *t=amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY); + struct ip_discovery_header *h=(void*)(binary+t->offset); + size_t pos=h->die_info[die].die_offset+sizeof(struct die_header); + for(unsigned i=0;inum_base_address*(h->base_addr_64_bit?8:4);} + return (void*)(binary+pos); +} +static void atomic_refusal(uint8_t *binary,size_t bytes,unsigned kind) +{ + struct stela_amd_ip_shape shape=stela_amd_discovery_ip_shape();size_t cells=shape.hw_ip_count*shape.instances; + uint8_t *raw=malloc(bytes?bytes:1);memcpy(raw,binary,bytes); + uint32_t *versions=malloc(cells*4);struct stela_amd_ip_binding *bindings=malloc(cells*sizeof(*bindings)); + struct stela_amd_ip_counts counts,before; + memset(versions,0xa5,cells*4);memset(bindings,0xa5,cells*sizeof(*bindings));memset(&counts,0xa5,sizeof(counts));before=counts; + uint32_t *vp=versions;struct stela_amd_ip_binding *bp=bindings;struct stela_amd_ip_counts *cp=&counts; + size_t vc=cells,bc=cells; + switch(kind){case 1:vc--;break;case 2:bc--;break;case 3:vp=NULL;break;case 4:bp=NULL;break;case 5:cp=NULL;break; + case 6:vp=(void*)((uint8_t*)versions+1);break;case 7:bp=(void*)((uint8_t*)bindings+1);break;case 8:cp=(void*)((uint8_t*)&counts+1);break; + case 9:vp=(void*)binary;break;case 10:cp=(void*)bindings;break;case 11:bp=(void*)versions;break;} + assert(stela_amd_discovery_ip_decode(binary,bytes,vp,vc,bp,bc,cp)); + assert(!memcmp(binary,raw,bytes)&&!memcmp(&counts,&before,sizeof(counts))); + for(size_t i=0;ioffset); + struct ip_v4 *ip=(void*)(binary+h->die_info[0].die_offset+sizeof(struct die_header)); + ip->major=255;ip->minor=254;ip->revision=253;checksum(binary,bytes);compare(binary,bytes,0);native(binary,bytes); + memcpy(binary,original,bytes); + for(unsigned variant=0;variant<5;variant++) { + memcpy(binary,original,bytes); + for(unsigned d=0;d<2;d++) { + if(variant==0){record(binary,bytes,d,0)->instance_number=31;record(binary,bytes,d,3)->instance_number=31;record(binary,bytes,d,2)->instance_number=31;} + if(variant==1){record(binary,bytes,d,2)->hw_id=NBIF_HWID;record(binary,bytes,d,2)->instance_number=0;record(binary,bytes,d,10)->hw_id=NBIF_HWID;record(binary,bytes,d,10)->instance_number=0;} + if(variant==2){struct ip_v4 *x=record(binary,bytes,d,9);x->hw_id=XGMI_HWID;x->instance_number=0;x->major=x->minor=x->revision=x->variant=x->sub_revision=0;} + if(variant==3)record(binary,bytes,d,7)->hw_id=VPE_HWID; + if(variant==4)record(binary,bytes,d,7)->hw_id=AUDIO_AZ_HWID; + } + if(variant==2){struct ip_v4 *w=record(binary,bytes,0,8);w->major=w->minor=w->revision=0;} + checksum(binary,bytes);assert(!amdgpu_discovery_binary_validate(binary,bytes)); + for(unsigned seed=0;seed<9;seed++)compare(binary,bytes,seed);native(binary,bytes); + } + memcpy(binary,original,bytes); + /* Preserve original partial first-die effects and global DRM error route. */ + struct ip_discovery_header *ph=(void*)(binary+amdgpu_discovery_binary_table(binary,bytes,IP_DISCOVERY)->offset); + ((struct die_header*)(binary+ph->die_info[1].die_offset))->die_id=5;checksum(binary,bytes); + compare(binary,bytes,0);atomic_refusal(binary,bytes,0); + memcpy(binary,original,bytes); + /* Original outer failures/partial masks remain in Linux caller. */ + acquisition_error=-EIO;compare(binary,bytes,0);acquisition_error=0; + table_error=-EINVAL;compare(binary,bytes,3);table_error=0; + } + for(int n=1;nxcc_mask=rust_oracle.gfx.xcc_mask;counts->vcn_mask=rust_oracle.vcn.inst_mask; + counts->jpeg_mask=rust_oracle.jpeg.inst_mask;counts->vcn_count=rust_oracle.vcn.num_vcn_inst; + for(unsigned i=0;ivcn_config[i]=rust_oracle.vcn.inst[i].vcn_config; + counts->sdma_count=rust_oracle.sdma.num_instances;counts->sdma_mask=rust_oracle.sdma.sdma_mask; + counts->vpe_count=rust_oracle.vpe.num_instances;counts->umc_count=rust_oracle.gmc.num_umc; + counts->node_count=rust_oracle.umc.node_inst_num; + *hwips=MAX_HWIP;*instances=HWIP_MAX_INSTANCE; +} +uint64_t stela_amd_ip_oracle_fact(unsigned hwip,unsigned instance,unsigned segment,unsigned kind) +{ + assert(hwip=count)return UINT64_MAX; + uint32_t value;memcpy(&value,(const uint8_t*)base+segment*4,4);return value; +} +#endif diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.rs b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.rs new file mode 100644 index 0000000000..2e41ad07ad --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip.rs @@ -0,0 +1,217 @@ +//! Child of the canonical single-authority test in a separate generated CPU +//! harness. Only the existing original C MM leaf is instrumented, never a +//! production provider. No physical PCI/GPU services are exercised. +use super::*; +use crate::{discovery, pci}; + +unsafe extern "C" { + fn stela_amd_tmr_fixture(bytes: &mut usize) -> *const u8; + fn stela_amd_tmr_model_begin(registers: *mut u32, bytes: *const u8, size: usize); + fn stela_amd_tmr_model_accesses() -> u32; + fn stela_amd_tmr_model_end(); + fn stela_amd_ip_oracle( + source: *const u8, + bytes: usize, + counts: &mut discovery::IpCounts, + hwips: &mut u32, + instances: &mut u32, + ); + fn stela_amd_ip_oracle_fact(hwip: u32, instance: u32, segment: u32, kind: u32) -> u64; +} +struct FixtureConfig; +impl ConfigSpace for FixtureConfig { + fn read32(&self, offset: u16) -> u32 { + match offset { + 0 => 0xffff_1002, + 8 => 0x1200_0045, + 12 => 0, + 44 => 0x5678_abcd, + _ => panic!("unexpected config read"), + } + } + fn write32(&mut self, _: u16, _: u32) { + panic!("no config writes") + } + fn write16(&mut self, _: u16, _: u16) { + panic!("no config writes") + } + fn write8(&mut self, _: u16, _: u8) { + panic!("no config writes") + } +} +pub(super) fn acquire_observed(authority: &Authority) { + let mut function = Function::new( + Address { + segment: 4, + bus: 0x81, + device: 2, + function: 0, + }, + FixtureConfig, + ) + .unwrap(); + let policy = pci::Policy { + si_built: true, + cik_built: true, + radeon_built: false, + si_support: -1, + cik_support: -1, + experimental: 0, + discovery: -1, + force_asic: -1, + memory_encrypted: false, + firmware_drivers_only: false, + modeset: -1, + }; + // SAFETY: actual public Function observes only immutable synthetic config. + let matched = unsafe { pci::identify(&mut function, policy) }.unwrap(); + assert_eq!(matched.ip_path(), pci::IpPath::Dynamic); + assert_eq!(matched.source(), pci::Source::Hardware); + let (resource, drops) = resource(0x1300_0000, 0x60000, ResourceKind::Registers); + // SAFETY: exact canonical RAM model resource, no physical admission claim. + let mut bars = unsafe { + AttachedBars::attach_matched( + authority, + &matched, + RegisterBar { index: 5, resource }, + None, + ) + } + .unwrap(); + let window = bars.registers().unwrap(); + let clock = Clock { + ticks_per_microsecond: 1, + }; + let mut bytes = 0; + // SAFETY: original-format immutable static CPU fixture, no firmware payload. + let source = unsafe { stela_amd_tmr_fixture(&mut bytes) }; + let begin = || unsafe { + stela_amd_tmr_model_begin(window.direct_dword(0).unwrap().as_ptr(), source, bytes) + }; + begin(); + // SAFETY: instrumented original MM query/copy runs only the bounded RAM + // fixture. The real production admission and ownership APIs are unchanged. + let observed = unsafe { discovery::acquire_dynamic_ip(&bars, &clock) }.unwrap(); + assert_eq!(observed.source_bytes(), unsafe { + core::slice::from_raw_parts(source, bytes) + }); + assert_eq!(observed.identity(), bars.identity()); + let mut counts = discovery::IpCounts::default(); + let (mut hwips, mut instances) = (0, 0); + // SAFETY: exact checked C/Rust ABI; independent frozen original consumer + // owns its distinct work copy and returns only scalar expected values. + unsafe { stela_amd_ip_oracle(source, bytes, &mut counts, &mut hwips, &mut instances) }; + assert_eq!(observed.counts(), counts); + let mut bound = 0; + for hwip in 0..hwips { + for instance in 0..instances { + let version = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 0) }; + assert_eq!(observed.version(hwip, instance), Some(version as u32)); + let count = unsafe { stela_amd_ip_oracle_fact(hwip, instance, 0, 1) }; + if count == u64::MAX { + assert_eq!(observed.register_count(hwip, instance), None); + } else { + bound += 1; + assert_eq!(observed.register_count(hwip, instance), Some(count as u32)); + for segment in 0..count as u32 { + let expected = unsafe { stela_amd_ip_oracle_fact(hwip, instance, segment, 2) }; + assert_eq!( + observed.register_base(hwip, instance, segment), + Some(expected as u32) + ); + } + assert_eq!(observed.register_base(hwip, instance, count as u32), None); + } + } + } + assert!(bound > 0); + assert_eq!(observed.version(hwips, 0), None); + assert_eq!(observed.version(0, instances), None); + assert_eq!(observed.register_base(u32::MAX, u32::MAX, u32::MAX), None); + assert!(unsafe { stela_amd_tmr_model_accesses() } > bytes as u32 / 4); + drop(observed); + // Each of four fallible production allocations is independently refused. + // Query/index effects remain real in this model, never falsely rolled back. + for allocation in 0..4 { + begin(); + allocation_failure::arm(allocation); + let failed = unsafe { discovery::acquire_dynamic_ip(&bars, &clock) }; + let consumed = allocation_failure::disarm(); + assert!(consumed); + assert!(matches!( + (allocation, failed), + (0, Err(discovery::Error::PostQueryAllocation)) + | (1..=3, Err(discovery::Error::PostAcquireAllocation)) + )); + assert!(unsafe { stela_amd_tmr_model_accesses() } > 0); + } + begin(); + assert!(matches!( + unsafe { + discovery::acquire_dynamic_ip( + &bars, + &Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(discovery::Error::ClockUnavailable) + )); + assert_eq!(unsafe { stela_amd_tmr_model_accesses() }, 0); + unsafe { stela_amd_tmr_model_end() }; + drop(window); + // SAFETY: all model consumers drained; failed unpublished copies dropped. + unsafe { bars.retire() }.unwrap(); + drop(bars); + assert_eq!(drops.load(Ordering::Relaxed), 1); + println!( + "AMD dynamic IP Rust/C: same admitted source owner; immutable raw bytes; every original version/binding/base/count; four allocation failures; CPU leaf-I/O model only" + ); +} + +pub(super) mod allocation_failure { + use std::alloc::{GlobalAlloc, Layout, System}; + use std::cell::Cell; + thread_local! { static REMAINING: Cell> = const { Cell::new(None) }; } + thread_local! { static CONSUMED: Cell = const { Cell::new(false) }; } + struct FaultAllocator; + #[global_allocator] + static ALLOCATOR: FaultAllocator = FaultAllocator; + // SAFETY: exact System delegation except one explicit valid null response; + // TLS is allocation-free and limited to this single harness thread. + unsafe impl GlobalAlloc for FaultAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let fail = REMAINING + .try_with(|value| match value.get() { + Some(0) => { + value.set(None); + true + } + Some(n) => { + value.set(Some(n - 1)); + false + } + None => false, + }) + .unwrap_or(false); + if fail { + let _ = CONSUMED.try_with(|v| v.set(true)); + core::ptr::null_mut() + } else { + unsafe { System.alloc(layout) } + } + } + unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { + // SAFETY: unmodified System allocation/layout from Rust. + unsafe { System.dealloc(pointer, layout) } + } + } + pub fn arm(before: usize) { + CONSUMED.with(|v| v.set(false)); + REMAINING.with(|v| v.set(Some(before))); + } + pub fn disarm() -> bool { + REMAINING.with(|v| v.set(None)); + CONSUMED.with(Cell::get) + } +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_fixture.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_fixture.c new file mode 100644 index 0000000000..c832634edd --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_fixture.c @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: MIT */ +/* Original existing CPU fixture generation, never a production firmware source. */ +#define main stela_amd_ip_existing_fixture_main +#include "discovery_binary_test.c" +#undef main +size_t stela_amd_ip_fixture(uint8_t *out, size_t capacity, unsigned version, + unsigned ip_version, unsigned wide) +{ + struct fixture f = make_fixture(version, ip_version, wide, 1, 3, 0); + assert(capacity >= f.size); + memcpy(out, f.binary, f.size); + return f.size; +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_reference.h b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_reference.h new file mode 100644 index 0000000000..d3a3241730 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_ip_reference.h @@ -0,0 +1,283 @@ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Frozen original consumer, exact92d3 body identical to Linux8d3ae592. + * Test-only real-field prototype, not a production device. */ +#define hw_id_map ip_donor_hw_id_map +#define amdgpu_discovery_validate_ip ip_donor_amdgpu_discovery_validate_ip +#define amdgpu_discovery_reg_base_init ip_donor_amdgpu_discovery_reg_base_init +static int hw_id_map[MAX_HWIP] = { + [GC_HWIP] = GC_HWID, + [HDP_HWIP] = HDP_HWID, + [SDMA0_HWIP] = SDMA0_HWID, + [SDMA1_HWIP] = SDMA1_HWID, + [SDMA2_HWIP] = SDMA2_HWID, + [SDMA3_HWIP] = SDMA3_HWID, + [LSDMA_HWIP] = LSDMA_HWID, + [MMHUB_HWIP] = MMHUB_HWID, + [ATHUB_HWIP] = ATHUB_HWID, + [NBIO_HWIP] = NBIF_HWID, + [MP0_HWIP] = MP0_HWID, + [MP1_HWIP] = MP1_HWID, + [UVD_HWIP] = UVD_HWID, + [VCE_HWIP] = VCE_HWID, + [DF_HWIP] = DF_HWID, + [DCE_HWIP] = DMU_HWID, + [OSSSYS_HWIP] = OSSSYS_HWID, + [SMUIO_HWIP] = SMUIO_HWID, + [PWR_HWIP] = PWR_HWID, + [NBIF_HWIP] = NBIF_HWID, + [THM_HWIP] = THM_HWID, + [CLK_HWIP] = CLKA_HWID, + [UMC_HWIP] = UMC_HWID, + [XGMI_HWIP] = XGMI_HWID, + [DCI_HWIP] = DCI_HWID, + [PCIE_HWIP] = PCIE_HWID, + [VPE_HWIP] = VPE_HWID, + [ISP_HWIP] = ISP_HWID, + [ATU_HWIP] = ATU_HWID, +}; + +static int amdgpu_discovery_validate_ip(struct amdgpu_device *adev, + uint8_t instance, uint16_t hw_id) +{ + if (instance >= HWIP_MAX_INSTANCE) { + dev_err(adev->dev, + "Unexpected instance_number (%d) from ip discovery blob\n", + instance); + return -EINVAL; + } + if (hw_id >= HW_ID_MAX) { + dev_err(adev->dev, + "Unexpected hw_id (%d) from ip discovery blob\n", + hw_id); + return -EINVAL; + } + + return 0; +} + +static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev) +{ + uint8_t num_base_address, subrev, variant; + struct table_info *info; + struct ip_discovery_header *ihdr; + struct die_header *dhdr; + uint8_t *discovery_bin; + struct ip_v4 *ip; + uint16_t die_offset; + uint16_t ip_offset; + uint16_t num_dies; + uint32_t wafl_ver; + uint16_t num_ips; + uint16_t hw_id; + uint8_t inst; + int hw_ip; + int i, j, k; + int r; + + r = amdgpu_discovery_init(adev); + if (r) + return r; + discovery_bin = adev->discovery.bin; + wafl_ver = 0; + adev->gfx.xcc_mask = 0; + adev->sdma.sdma_mask = 0; + adev->vcn.inst_mask = 0; + adev->jpeg.inst_mask = 0; + r = amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY); + if (r) + return r; + ihdr = (struct ip_discovery_header + *)(discovery_bin + + le16_to_cpu(info->offset)); + num_dies = le16_to_cpu(ihdr->num_dies); + + DRM_DEBUG("number of dies: %d\n", num_dies); + + for (i = 0; i < num_dies; i++) { + die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); + dhdr = (struct die_header *)(discovery_bin + die_offset); + num_ips = le16_to_cpu(dhdr->num_ips); + ip_offset = die_offset + sizeof(*dhdr); + + if (le16_to_cpu(dhdr->die_id) != i) { + DRM_ERROR("invalid die id %d, expected %d\n", + le16_to_cpu(dhdr->die_id), i); + return -EINVAL; + } + + DRM_DEBUG("number of hardware IPs on die%d: %d\n", + le16_to_cpu(dhdr->die_id), num_ips); + + for (j = 0; j < num_ips; j++) { + ip = (struct ip_v4 *)(discovery_bin + ip_offset); + + inst = ip->instance_number; + hw_id = le16_to_cpu(ip->hw_id); + if (amdgpu_discovery_validate_ip(adev, inst, hw_id)) + goto next_ip; + + num_base_address = ip->num_base_address; + + DRM_DEBUG("%s(%d) #%d v%d.%d.%d:\n", + hw_id_names[le16_to_cpu(ip->hw_id)], + le16_to_cpu(ip->hw_id), + ip->instance_number, + ip->major, ip->minor, + ip->revision); + + if (le16_to_cpu(ip->hw_id) == VCN_HWID) { + /* Bit [5:0]: original revision value + * Bit [7:6]: en/decode capability: + * 0b00 : VCN function normally + * 0b10 : encode is disabled + * 0b01 : decode is disabled + */ + if (adev->vcn.num_vcn_inst < + AMDGPU_MAX_VCN_INSTANCES) { + adev->vcn.inst[adev->vcn.num_vcn_inst].vcn_config = + ip->revision & 0xc0; + adev->vcn.num_vcn_inst++; + adev->vcn.inst_mask |= + (1U << ip->instance_number); + adev->jpeg.inst_mask |= + (1U << ip->instance_number); + } else { + dev_err(adev->dev, "Too many VCN instances: %d vs %d\n", + adev->vcn.num_vcn_inst + 1, + AMDGPU_MAX_VCN_INSTANCES); + } + ip->revision &= ~0xc0; + } + if (le16_to_cpu(ip->hw_id) == SDMA0_HWID || + le16_to_cpu(ip->hw_id) == SDMA1_HWID || + le16_to_cpu(ip->hw_id) == SDMA2_HWID || + le16_to_cpu(ip->hw_id) == SDMA3_HWID) { + if (adev->sdma.num_instances < + AMDGPU_MAX_SDMA_INSTANCES) { + adev->sdma.num_instances++; + adev->sdma.sdma_mask |= + (1U << ip->instance_number); + } else { + dev_err(adev->dev, "Too many SDMA instances: %d vs %d\n", + adev->sdma.num_instances + 1, + AMDGPU_MAX_SDMA_INSTANCES); + } + } + + if (le16_to_cpu(ip->hw_id) == VPE_HWID) { + if (adev->vpe.num_instances < AMDGPU_MAX_VPE_INSTANCES) + adev->vpe.num_instances++; + else + dev_err(adev->dev, "Too many VPE instances: %d vs %d\n", + adev->vpe.num_instances + 1, + AMDGPU_MAX_VPE_INSTANCES); + } + + if (le16_to_cpu(ip->hw_id) == UMC_HWID) { + adev->gmc.num_umc++; + adev->umc.node_inst_num++; + } + + if (le16_to_cpu(ip->hw_id) == GC_HWID) + adev->gfx.xcc_mask |= + (1U << ip->instance_number); + + if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID) + wafl_ver = IP_VERSION_FULL(ip->major, ip->minor, + ip->revision, 0, 0); + + for (k = 0; k < num_base_address; k++) { + /* + * convert the endianness of base addresses in place, + * so that we don't need to convert them when accessing adev->reg_offset. + */ + if (ihdr->base_addr_64_bit) + /* Truncate the 64bit base address from ip discovery + * and only store lower 32bit ip base in reg_offset[]. + * Bits > 32 follows ASIC specific format, thus just + * discard them and handle it within specific ASIC. + * By this way reg_offset[] and related helpers can + * stay unchanged. + * The base address is in dwords, thus clear the + * highest 2 bits to store. + */ + ip->base_address[k] = + lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF; + else + ip->base_address[k] = le32_to_cpu(ip->base_address[k]); + DRM_DEBUG("\t0x%08x\n", ip->base_address[k]); + } + + for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) { + if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) && + hw_id_map[hw_ip] != 0) { + DRM_DEBUG("set register base offset for %s\n", + hw_id_names[le16_to_cpu(ip->hw_id)]); + adev->reg_offset[hw_ip][ip->instance_number] = + ip->base_address; + /* Instance support is somewhat inconsistent. + * SDMA is a good example. Sienna cichlid has 4 total + * SDMA instances, each enumerated separately (HWIDs + * 42, 43, 68, 69). Arcturus has 8 total SDMA instances, + * but they are enumerated as multiple instances of the + * same HWIDs (4x HWID 42, 4x HWID 43). UMC is another + * example. On most chips there are multiple instances + * with the same HWID. + */ + + if (ihdr->version < 3) { + subrev = 0; + variant = 0; + } else { + subrev = ip->sub_revision; + variant = ip->variant; + } + + adev->ip_versions[hw_ip] + [ip->instance_number] = + IP_VERSION_FULL(ip->major, + ip->minor, + ip->revision, + variant, + subrev); + } + } + +next_ip: + if (ihdr->base_addr_64_bit) + ip_offset += struct_size(ip, base_address_64, ip->num_base_address); + else + ip_offset += struct_size(ip, base_address, ip->num_base_address); + } + } + + if (wafl_ver && !adev->ip_versions[XGMI_HWIP][0]) + adev->ip_versions[XGMI_HWIP][0] = wafl_ver; + + return 0; +} +#undef hw_id_map +#undef amdgpu_discovery_validate_ip +#undef amdgpu_discovery_reg_base_init diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_reference.h b/crates/stela-drivers/src/gpu/amd/tests/discovery_reference.h new file mode 100644 index 0000000000..3a5fe4bc01 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_reference.h @@ -0,0 +1,1182 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2018-2024 Advanced Micro Devices, Inc. All rights reserved. + * Copyright 2025 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* CPU-only model: unchanged original functions, not a production device. + * Linux8d3ae59288f1e7d58d76558a6ee96d533bc5019f; source SHA256 2a53ce988fe75f16a00bd010c5c199449596936d7869223e65fc39917ae52be8. */ + +enum amd_hw_ip_block_type { + GC_HWIP = 1, + HDP_HWIP, + SDMA0_HWIP, + SDMA1_HWIP, + SDMA2_HWIP, + SDMA3_HWIP, + SDMA4_HWIP, + SDMA5_HWIP, + SDMA6_HWIP, + SDMA7_HWIP, + LSDMA_HWIP, + MMHUB_HWIP, + ATHUB_HWIP, + NBIO_HWIP, + MP0_HWIP, + MP1_HWIP, + UVD_HWIP, + VCN_HWIP = UVD_HWIP, + JPEG_HWIP = VCN_HWIP, + VCN1_HWIP, + VCE_HWIP, + VPE_HWIP, + DF_HWIP, + DCE_HWIP, + OSSSYS_HWIP, + SMUIO_HWIP, + PWR_HWIP, + NBIF_HWIP, + THM_HWIP, + CLK_HWIP, + UMC_HWIP, + RSMU_HWIP, + XGMI_HWIP, + DCI_HWIP, + PCIE_HWIP, + ISP_HWIP, + ATU_HWIP, + AIGC_HWIP, + MAX_HWIP +}; +#define AMDGPU_MAX_VCN_INSTANCES 4 +#define AMDGPU_VCN_HARVEST_VCN0 (1 << 0) +#define AMDGPU_VCN_HARVEST_VCN1 (1 << 1) +#define AMDGPU_MAX_SDMA_INSTANCES 16 +#define AMDGPU_MAX_VPE_INSTANCES 2 + +#define le16_to_cpu(x) (x) +#define le32_to_cpu(x) (x) +#define le64_to_cpu(x) (x) +#define lower_32_bits(x) ((uint32_t)(x)) +#define struct_size(p, member, n) (sizeof(*(p)) + sizeof((p)->member[0]) * (n)) +#define IP_VERSION_FULL(mj, mn, rv, var, srev) \ + (((mj) << 24) | ((mn) << 16) | ((rv) << 8) | ((var) << 4) | (srev)) +#define BIT(n) (1UL << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define AMD_HARVEST_IP_DMU_MASK 0x4 +#define dev_err(...) reference_log(__VA_ARGS__) +#define dev_warn(...) reference_log(__VA_ARGS__) +#define dev_dbg(...) reference_log(__VA_ARGS__) +#define DRM_DEBUG(...) ((void)0) +#define DRM_ERROR(...) ((void)0) +#define DRM_INFO(...) ((void)0) +typedef uint32_t u32; +typedef uint16_t u16; +typedef uint8_t u8; +typedef uint64_t u64; +struct amdgpu_device { + void *dev, *ddev; + struct { uint8_t *bin; size_t size; } discovery; + struct { + uint32_t xcc_mask; + struct { + uint32_t double_offchip_lds_buf; + uint32_t gc_gl1c_per_sa; + uint32_t gc_gl1c_size_per_instance; + uint32_t gc_gl2c_per_gpu; + uint32_t gc_instruction_cache_line_size; + uint32_t gc_instruction_cache_size_per_sqc; + uint32_t gc_l1_data_cache_size_per_sqc; + uint32_t gc_l1_instruction_cache_size_per_sqc; + uint32_t gc_num_cu_per_sqc; + uint32_t gc_num_sdp_interface; + uint32_t gc_num_sqc_per_wgp; + uint32_t gc_num_tcp_per_sa; + uint32_t gc_num_tcp_per_wpg; + uint32_t gc_num_tcps; + uint32_t gc_scalar_data_cache_line_size; + uint32_t gc_scalar_data_cache_size_per_sqc; + uint32_t gc_tcc_cache_line_size; + uint32_t gc_tcc_size; + uint32_t gc_tcp_cache_line_size; + uint32_t gc_tcp_l1_size; + uint32_t gc_tcp_size_per_cu; + uint32_t gs_prim_buffer_depth; + uint32_t gs_vgt_table_depth; + uint32_t max_backends_per_se; + uint32_t max_cu_per_sh; + uint32_t max_gprs; + uint32_t max_gs_threads; + uint32_t max_sh_per_se; + uint32_t max_shader_engines; + uint32_t max_texture_channel_caches; + uint32_t num_packer_per_sc; + uint32_t num_sc_per_sh; + } config; + struct { + uint32_t lds_size; + uint32_t max_scratch_slots_per_cu; + uint32_t max_waves_per_simd; + uint32_t wave_front_size; + } cu_info; + } gfx; + struct { uint32_t num_instances, sdma_mask; } sdma; + struct { + uint32_t num_vcn_inst, inst_mask, harvest_config; + struct { uint32_t vcn_config, vcn_codec_disable_mask; } inst[AMDGPU_MAX_VCN_INSTANCES]; + } vcn; + struct { uint32_t inst_mask, harvest_config; } jpeg; + struct { uint32_t num_instances; } vpe; + struct { uint32_t num_umc, m_half_use; uint64_t mall_size; } gmc; + struct { uint32_t node_inst_num; uint64_t active_mask; } umc; + uint32_t harvest_ip_mask; + uint32_t *reg_offset[MAX_HWIP][HWIP_MAX_INSTANCE]; + uint32_t ip_versions[MAX_HWIP][HWIP_MAX_INSTANCE]; +}; +union gc_info { + struct gc_info_v1_0 v1; + struct gc_info_v1_1 v1_1; + struct gc_info_v1_2 v1_2; + struct gc_info_v1_3 v1_3; + struct gc_info_v2_0 v2; + struct gc_info_v2_1 v2_1; +}; +union mall_info { struct mall_info_v1_0 v1; struct mall_info_v2_0 v2; }; +union vcn_info { struct vcn_info_v1_0 v1; }; +static int checked; +static int reference_validation(struct amdgpu_device *adev); +static int fixture_table(struct amdgpu_device *adev, struct table_info **info, uint16_t id); +#define amdgpu_discovery_get_table_info fixture_table +#define amdgpu_discovery_init reference_validation +static int hw_id_map[MAX_HWIP] = { + [GC_HWIP] = GC_HWID, + [HDP_HWIP] = HDP_HWID, + [SDMA0_HWIP] = SDMA0_HWID, + [SDMA1_HWIP] = SDMA1_HWID, + [SDMA2_HWIP] = SDMA2_HWID, + [SDMA3_HWIP] = SDMA3_HWID, + [LSDMA_HWIP] = LSDMA_HWID, + [MMHUB_HWIP] = MMHUB_HWID, + [ATHUB_HWIP] = ATHUB_HWID, + [NBIO_HWIP] = NBIF_HWID, + [MP0_HWIP] = MP0_HWID, + [MP1_HWIP] = MP1_HWID, + [UVD_HWIP] = UVD_HWID, + [VCE_HWIP] = VCE_HWID, + [DF_HWIP] = DF_HWID, + [DCE_HWIP] = DMU_HWID, + [OSSSYS_HWIP] = OSSSYS_HWID, + [SMUIO_HWIP] = SMUIO_HWID, + [PWR_HWIP] = PWR_HWID, + [NBIF_HWIP] = NBIF_HWID, + [THM_HWIP] = THM_HWID, + [CLK_HWIP] = CLKA_HWID, + [UMC_HWIP] = UMC_HWID, + [XGMI_HWIP] = XGMI_HWID, + [DCI_HWIP] = DCI_HWID, + [PCIE_HWIP] = PCIE_HWID, + [VPE_HWIP] = VPE_HWID, + [ISP_HWIP] = ISP_HWID, + [ATU_HWIP] = ATU_HWID, +}; +#define amdgpu_discovery_calculate_checksum donor_checksum + +/* Original amdgpu_discovery_calculate_checksum SHA256 372aab607b140694bfdaad72d341f34e5232627c4c90575a11fa769482d47b44 */ +static uint16_t amdgpu_discovery_calculate_checksum(uint8_t *data, uint32_t size) +{ + uint16_t checksum = 0; + int i; + + for (i = 0; i < size; i++) + checksum += data[i]; + + return checksum; +} + + +/* Original amdgpu_discovery_verify_checksum SHA256 c035ae88a58005e267458c731d2857b70723250d0c892358b2b17c77637b6c35 */ +static inline bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev, + uint8_t *data, uint32_t size, + uint16_t expected) +{ + uint16_t calculated; + + calculated = amdgpu_discovery_calculate_checksum(data, size); + + if (calculated != expected) { + dev_err(adev->dev, "Discovery checksum failed: calc 0x%04x != exp 0x%04x, size %u.\n", + calculated, expected, size); + return false; + } + + return true; +} + + +/* Original amdgpu_discovery_verify_binary_signature SHA256 c82abb6e99bac7f1186a5389e76e023aa67bfdb22a112a9b35485d5e5077afa0 */ +static inline bool amdgpu_discovery_verify_binary_signature(uint8_t *binary) +{ + struct binary_header *bhdr; + bhdr = (struct binary_header *)binary; + + return (le32_to_cpu(bhdr->binary_signature) == BINARY_SIGNATURE); +} + + +static int donor_table(struct amdgpu_device *adev, + struct table_info **info, + uint16_t table_id) +{ + struct binary_header *bhdr = + (struct binary_header *)adev->discovery.bin; + struct binary_header_v2 *bhdrv2; + + switch (bhdr->version_major) { + case 2: + bhdrv2 = (struct binary_header_v2 *)adev->discovery.bin; + *info = &bhdrv2->table_list[table_id]; + break; + case 1: + case 0: + *info = &bhdr->table_list[table_id]; + break; + default: + dev_err(adev->dev, "Invalid ip discovery table version %d\n",bhdr->version_major); + return -EINVAL; + } + + return 0; +} + + +/* Original amdgpu_discovery_table_check SHA256 c9a06491e12cc34646f325f8269432b2b69a63e278f90ddb296e98034644df76 */ +static int amdgpu_discovery_table_check(struct amdgpu_device *adev, + uint8_t *discovery_bin, + uint16_t table_id) +{ + int r, act_val, exp_val, table_size; + uint16_t offset, checksum; + struct table_info *info; + bool check_table = true; + char *table_name; + + r = amdgpu_discovery_get_table_info(adev, &info, table_id); + if (r) + return r; + offset = le16_to_cpu(info->offset); + checksum = le16_to_cpu(info->checksum); + + switch (table_id) { + case IP_DISCOVERY: { + struct ip_discovery_header *ihdr = + (struct ip_discovery_header *)(discovery_bin + offset); + act_val = le32_to_cpu(ihdr->signature); + exp_val = DISCOVERY_TABLE_SIGNATURE; + table_size = le16_to_cpu(ihdr->size); + table_name = "data table"; + break; + } + case GC: { + struct gpu_info_header *ghdr = + (struct gpu_info_header *)(discovery_bin + offset); + act_val = le32_to_cpu(ghdr->table_id); + exp_val = GC_TABLE_ID; + table_size = le16_to_cpu(ghdr->size); + table_name = "gc table"; + break; + } + case HARVEST_INFO: { + struct harvest_info_header *hhdr = + (struct harvest_info_header *)(discovery_bin + offset); + act_val = le32_to_cpu(hhdr->signature); + exp_val = HARVEST_TABLE_SIGNATURE; + table_size = sizeof(struct harvest_table); + table_name = "harvest table"; + break; + } + case VCN_INFO: { + struct vcn_info_header *vhdr = + (struct vcn_info_header *)(discovery_bin + offset); + act_val = le32_to_cpu(vhdr->table_id); + exp_val = VCN_INFO_TABLE_ID; + table_size = le32_to_cpu(vhdr->size_bytes); + table_name = "vcn table"; + break; + } + case MALL_INFO: { + struct mall_info_header *mhdr = + (struct mall_info_header *)(discovery_bin + offset); + act_val = le32_to_cpu(mhdr->table_id); + exp_val = MALL_INFO_TABLE_ID; + table_size = le32_to_cpu(mhdr->size_bytes); + table_name = "mall table"; + check_table = false; + break; + } + default: + dev_err(adev->dev, "invalid ip discovery table id %d specified\n", table_id); + check_table = false; + break; + } + + if (check_table && offset) { + if (act_val != exp_val) { + dev_err(adev->dev, "invalid ip discovery %s signature\n", table_name); + return -EINVAL; + } + + if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, + table_size, checksum)) { + dev_err(adev->dev, "invalid ip discovery %s checksum\n", table_name); + return -EINVAL; + } + } + + return 0; +} + + +/* Original amdgpu_discovery_validate_ip SHA256 86be3ff15479a5f206add82800a9c9457b3f950323caff44bab04f08b78179a7 */ +static int amdgpu_discovery_validate_ip(struct amdgpu_device *adev, + uint8_t instance, uint16_t hw_id) +{ + if (instance >= HWIP_MAX_INSTANCE) { + dev_err(adev->dev, + "Unexpected instance_number (%d) from ip discovery blob\n", + instance); + return -EINVAL; + } + if (hw_id >= HW_ID_MAX) { + dev_err(adev->dev, + "Unexpected hw_id (%d) from ip discovery blob\n", + hw_id); + return -EINVAL; + } + + return 0; +} + + +/* Original amdgpu_discovery_reg_base_init SHA256 0a87709612fa439b0ed1fd44db839e36c5d9599c57ad6bead561e61424ff1453 */ +static int amdgpu_discovery_reg_base_init(struct amdgpu_device *adev) +{ + uint8_t num_base_address, subrev, variant; + struct table_info *info; + struct ip_discovery_header *ihdr; + struct die_header *dhdr; + uint8_t *discovery_bin; + struct ip_v4 *ip; + uint16_t die_offset; + uint16_t ip_offset; + uint16_t num_dies; + uint32_t wafl_ver; + uint16_t num_ips; + uint16_t hw_id; + uint8_t inst; + int hw_ip; + int i, j, k; + int r; + + r = amdgpu_discovery_init(adev); + if (r) + return r; + discovery_bin = adev->discovery.bin; + wafl_ver = 0; + adev->gfx.xcc_mask = 0; + adev->sdma.sdma_mask = 0; + adev->vcn.inst_mask = 0; + adev->jpeg.inst_mask = 0; + r = amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY); + if (r) + return r; + ihdr = (struct ip_discovery_header + *)(discovery_bin + + le16_to_cpu(info->offset)); + num_dies = le16_to_cpu(ihdr->num_dies); + + DRM_DEBUG("number of dies: %d\n", num_dies); + + for (i = 0; i < num_dies; i++) { + die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); + dhdr = (struct die_header *)(discovery_bin + die_offset); + num_ips = le16_to_cpu(dhdr->num_ips); + ip_offset = die_offset + sizeof(*dhdr); + + if (le16_to_cpu(dhdr->die_id) != i) { + DRM_ERROR("invalid die id %d, expected %d\n", + le16_to_cpu(dhdr->die_id), i); + return -EINVAL; + } + + DRM_DEBUG("number of hardware IPs on die%d: %d\n", + le16_to_cpu(dhdr->die_id), num_ips); + + for (j = 0; j < num_ips; j++) { + ip = (struct ip_v4 *)(discovery_bin + ip_offset); + + inst = ip->instance_number; + hw_id = le16_to_cpu(ip->hw_id); + if (amdgpu_discovery_validate_ip(adev, inst, hw_id)) + goto next_ip; + + num_base_address = ip->num_base_address; + + DRM_DEBUG("%s(%d) #%d v%d.%d.%d:\n", + hw_id_names[le16_to_cpu(ip->hw_id)], + le16_to_cpu(ip->hw_id), + ip->instance_number, + ip->major, ip->minor, + ip->revision); + + if (le16_to_cpu(ip->hw_id) == VCN_HWID) { + /* Bit [5:0]: original revision value + * Bit [7:6]: en/decode capability: + * 0b00 : VCN function normally + * 0b10 : encode is disabled + * 0b01 : decode is disabled + */ + if (adev->vcn.num_vcn_inst < + AMDGPU_MAX_VCN_INSTANCES) { + adev->vcn.inst[adev->vcn.num_vcn_inst].vcn_config = + ip->revision & 0xc0; + adev->vcn.num_vcn_inst++; + adev->vcn.inst_mask |= + (1U << ip->instance_number); + adev->jpeg.inst_mask |= + (1U << ip->instance_number); + } else { + dev_err(adev->dev, "Too many VCN instances: %d vs %d\n", + adev->vcn.num_vcn_inst + 1, + AMDGPU_MAX_VCN_INSTANCES); + } + ip->revision &= ~0xc0; + } + if (le16_to_cpu(ip->hw_id) == SDMA0_HWID || + le16_to_cpu(ip->hw_id) == SDMA1_HWID || + le16_to_cpu(ip->hw_id) == SDMA2_HWID || + le16_to_cpu(ip->hw_id) == SDMA3_HWID) { + if (adev->sdma.num_instances < + AMDGPU_MAX_SDMA_INSTANCES) { + adev->sdma.num_instances++; + adev->sdma.sdma_mask |= + (1U << ip->instance_number); + } else { + dev_err(adev->dev, "Too many SDMA instances: %d vs %d\n", + adev->sdma.num_instances + 1, + AMDGPU_MAX_SDMA_INSTANCES); + } + } + + if (le16_to_cpu(ip->hw_id) == VPE_HWID) { + if (adev->vpe.num_instances < AMDGPU_MAX_VPE_INSTANCES) + adev->vpe.num_instances++; + else + dev_err(adev->dev, "Too many VPE instances: %d vs %d\n", + adev->vpe.num_instances + 1, + AMDGPU_MAX_VPE_INSTANCES); + } + + if (le16_to_cpu(ip->hw_id) == UMC_HWID) { + adev->gmc.num_umc++; + adev->umc.node_inst_num++; + } + + if (le16_to_cpu(ip->hw_id) == GC_HWID) + adev->gfx.xcc_mask |= + (1U << ip->instance_number); + + if (!wafl_ver && le16_to_cpu(ip->hw_id) == WAFLC_HWID) + wafl_ver = IP_VERSION_FULL(ip->major, ip->minor, + ip->revision, 0, 0); + + for (k = 0; k < num_base_address; k++) { + /* + * convert the endianness of base addresses in place, + * so that we don't need to convert them when accessing adev->reg_offset. + */ + if (ihdr->base_addr_64_bit) + /* Truncate the 64bit base address from ip discovery + * and only store lower 32bit ip base in reg_offset[]. + * Bits > 32 follows ASIC specific format, thus just + * discard them and handle it within specific ASIC. + * By this way reg_offset[] and related helpers can + * stay unchanged. + * The base address is in dwords, thus clear the + * highest 2 bits to store. + */ + ip->base_address[k] = + lower_32_bits(le64_to_cpu(ip->base_address_64[k])) & 0x3FFFFFFF; + else + ip->base_address[k] = le32_to_cpu(ip->base_address[k]); + DRM_DEBUG("\t0x%08x\n", ip->base_address[k]); + } + + for (hw_ip = 0; hw_ip < MAX_HWIP; hw_ip++) { + if (hw_id_map[hw_ip] == le16_to_cpu(ip->hw_id) && + hw_id_map[hw_ip] != 0) { + DRM_DEBUG("set register base offset for %s\n", + hw_id_names[le16_to_cpu(ip->hw_id)]); + adev->reg_offset[hw_ip][ip->instance_number] = + ip->base_address; + /* Instance support is somewhat inconsistent. + * SDMA is a good example. Sienna cichlid has 4 total + * SDMA instances, each enumerated separately (HWIDs + * 42, 43, 68, 69). Arcturus has 8 total SDMA instances, + * but they are enumerated as multiple instances of the + * same HWIDs (4x HWID 42, 4x HWID 43). UMC is another + * example. On most chips there are multiple instances + * with the same HWID. + */ + + if (ihdr->version < 3) { + subrev = 0; + variant = 0; + } else { + subrev = ip->sub_revision; + variant = ip->variant; + } + + adev->ip_versions[hw_ip] + [ip->instance_number] = + IP_VERSION_FULL(ip->major, + ip->minor, + ip->revision, + variant, + subrev); + } + } + +next_ip: + if (ihdr->base_addr_64_bit) + ip_offset += struct_size(ip, base_address_64, ip->num_base_address); + else + ip_offset += struct_size(ip, base_address, ip->num_base_address); + } + } + + if (wafl_ver && !adev->ip_versions[XGMI_HWIP][0]) + adev->ip_versions[XGMI_HWIP][0] = wafl_ver; + + return 0; +} + + +/* Original amdgpu_discovery_read_harvest_bit_per_ip SHA256 c8959dbfe679bc3fa371ca0c379f4b8b9d7b471ad4362e7173b584a366b14a76 */ +static void amdgpu_discovery_read_harvest_bit_per_ip(struct amdgpu_device *adev, + uint32_t *vcn_harvest_count) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct binary_header *bhdr; + struct ip_discovery_header *ihdr; + struct die_header *dhdr; + struct ip *ip; + uint16_t die_offset, ip_offset, num_dies, num_ips; + uint16_t hw_id; + uint8_t inst; + int i, j; + + bhdr = (struct binary_header *)discovery_bin; + ihdr = (struct ip_discovery_header + *)(discovery_bin + + le16_to_cpu(bhdr->table_list[IP_DISCOVERY].offset)); + num_dies = le16_to_cpu(ihdr->num_dies); + + /* scan harvest bit of all IP data structures */ + for (i = 0; i < num_dies; i++) { + die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); + dhdr = (struct die_header *)(discovery_bin + die_offset); + num_ips = le16_to_cpu(dhdr->num_ips); + ip_offset = die_offset + sizeof(*dhdr); + + for (j = 0; j < num_ips; j++) { + ip = (struct ip *)(discovery_bin + ip_offset); + inst = ip->number_instance; + hw_id = le16_to_cpu(ip->hw_id); + if (amdgpu_discovery_validate_ip(adev, inst, hw_id)) + goto next_ip; + + if (ip->harvest == 1) { + switch (hw_id) { + case VCN_HWID: + (*vcn_harvest_count)++; + if (inst == 0) { + adev->vcn.harvest_config |= AMDGPU_VCN_HARVEST_VCN0; + adev->vcn.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN0; + adev->jpeg.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN0; + } else { + adev->vcn.harvest_config |= AMDGPU_VCN_HARVEST_VCN1; + adev->vcn.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN1; + adev->jpeg.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN1; + } + break; + case DMU_HWID: + adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK; + break; + default: + break; + } + } +next_ip: + ip_offset += struct_size(ip, base_address, + ip->num_base_address); + } + } +} + + +/* Original amdgpu_discovery_read_from_harvest_table SHA256 14ecf4f63472af489ca55eca624d5dd2a559756f1db7d626d86c9f49b3946b90 */ +static void amdgpu_discovery_read_from_harvest_table(struct amdgpu_device *adev, + uint32_t *vcn_harvest_count, + uint32_t *umc_harvest_count) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + struct harvest_table *harvest_info; + u16 offset; + int i; + u64 umc_harvest_config = 0; + + if (amdgpu_discovery_get_table_info(adev, &info, HARVEST_INFO)) + return; + offset = le16_to_cpu(info->offset); + + if (!offset) { + dev_err(adev->dev, "invalid harvest table offset\n"); + return; + } + + harvest_info = (struct harvest_table *)(discovery_bin + offset); + + for (i = 0; i < 32; i++) { + u16 hw_id = le16_to_cpu(harvest_info->list[i].hw_id); + u8 inst = harvest_info->list[i].number_instance; + + if (hw_id == 0) + break; + + if (inst >= 32) { + dev_warn(adev->dev, + "bogus harvest instance %u for hw_id %u\n", + inst, hw_id); + continue; + } + + switch (hw_id) { + case VCN_HWID: + (*vcn_harvest_count)++; + adev->vcn.harvest_config |= BIT(inst); + adev->jpeg.harvest_config |= BIT(inst); + + adev->vcn.inst_mask &= ~BIT(inst); + adev->jpeg.inst_mask &= ~BIT(inst); + break; + case DMU_HWID: + adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK; + break; + case UMC_HWID: + umc_harvest_config |= BIT_ULL(inst); + (*umc_harvest_count)++; + break; + case GC_HWID: + adev->gfx.xcc_mask &= ~BIT(inst); + break; + case SDMA0_HWID: + adev->sdma.sdma_mask &= ~BIT(inst); + break; +#if defined(CONFIG_DRM_AMD_ISP) + case ISP_HWID: + adev->isp.harvest_config |= ~BIT(inst); + break; +#endif + default: + break; + } + } + + adev->umc.active_mask = ((1ULL << adev->umc.node_inst_num) - 1ULL) & + ~umc_harvest_config; +} + + +/* Original amdgpu_discovery_get_gfx_info SHA256 5ea837ac1840d60ecd843136fa366c21803e8b6ebf2fb653f4db697a654a2757 */ +static int amdgpu_discovery_get_gfx_info(struct amdgpu_device *adev) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + union gc_info *gc_info; + u16 offset; + + if (!discovery_bin) { + DRM_ERROR("ip discovery uninitialized\n"); + return -EINVAL; + } + + if (amdgpu_discovery_get_table_info(adev, &info, GC)) + return -EINVAL; + offset = le16_to_cpu(info->offset); + + if (!offset) + return 0; + + gc_info = (union gc_info *)(discovery_bin + offset); + + switch (le16_to_cpu(gc_info->v1.header.version_major)) { + case 1: + adev->gfx.config.max_shader_engines = le32_to_cpu(gc_info->v1.gc_num_se); + adev->gfx.config.max_cu_per_sh = 2 * (le32_to_cpu(gc_info->v1.gc_num_wgp0_per_sa) + + le32_to_cpu(gc_info->v1.gc_num_wgp1_per_sa)); + adev->gfx.config.max_sh_per_se = le32_to_cpu(gc_info->v1.gc_num_sa_per_se); + adev->gfx.config.max_backends_per_se = le32_to_cpu(gc_info->v1.gc_num_rb_per_se); + adev->gfx.config.max_texture_channel_caches = le32_to_cpu(gc_info->v1.gc_num_gl2c); + adev->gfx.config.max_gprs = le32_to_cpu(gc_info->v1.gc_num_gprs); + adev->gfx.config.max_gs_threads = le32_to_cpu(gc_info->v1.gc_num_max_gs_thds); + adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gc_info->v1.gc_gs_table_depth); + adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gc_info->v1.gc_gsprim_buff_depth); + adev->gfx.config.double_offchip_lds_buf = le32_to_cpu(gc_info->v1.gc_double_offchip_lds_buffer); + adev->gfx.cu_info.wave_front_size = le32_to_cpu(gc_info->v1.gc_wave_size); + adev->gfx.cu_info.max_waves_per_simd = le32_to_cpu(gc_info->v1.gc_max_waves_per_simd); + adev->gfx.cu_info.max_scratch_slots_per_cu = le32_to_cpu(gc_info->v1.gc_max_scratch_slots_per_cu); + adev->gfx.cu_info.lds_size = le32_to_cpu(gc_info->v1.gc_lds_size); + adev->gfx.config.num_sc_per_sh = le32_to_cpu(gc_info->v1.gc_num_sc_per_se) / + le32_to_cpu(gc_info->v1.gc_num_sa_per_se); + adev->gfx.config.num_packer_per_sc = le32_to_cpu(gc_info->v1.gc_num_packer_per_sc); + if (le16_to_cpu(gc_info->v1.header.version_minor) >= 1) { + adev->gfx.config.gc_num_tcp_per_sa = le32_to_cpu(gc_info->v1_1.gc_num_tcp_per_sa); + adev->gfx.config.gc_num_sdp_interface = le32_to_cpu(gc_info->v1_1.gc_num_sdp_interface); + adev->gfx.config.gc_num_tcps = le32_to_cpu(gc_info->v1_1.gc_num_tcps); + } + if (le16_to_cpu(gc_info->v1.header.version_minor) >= 2) { + adev->gfx.config.gc_num_tcp_per_wpg = le32_to_cpu(gc_info->v1_2.gc_num_tcp_per_wpg); + adev->gfx.config.gc_tcp_l1_size = le32_to_cpu(gc_info->v1_2.gc_tcp_l1_size); + adev->gfx.config.gc_num_sqc_per_wgp = le32_to_cpu(gc_info->v1_2.gc_num_sqc_per_wgp); + adev->gfx.config.gc_l1_instruction_cache_size_per_sqc = le32_to_cpu(gc_info->v1_2.gc_l1_instruction_cache_size_per_sqc); + adev->gfx.config.gc_l1_data_cache_size_per_sqc = le32_to_cpu(gc_info->v1_2.gc_l1_data_cache_size_per_sqc); + adev->gfx.config.gc_gl1c_per_sa = le32_to_cpu(gc_info->v1_2.gc_gl1c_per_sa); + adev->gfx.config.gc_gl1c_size_per_instance = le32_to_cpu(gc_info->v1_2.gc_gl1c_size_per_instance); + adev->gfx.config.gc_gl2c_per_gpu = le32_to_cpu(gc_info->v1_2.gc_gl2c_per_gpu); + } + if (le16_to_cpu(gc_info->v1.header.version_minor) >= 3) { + adev->gfx.config.gc_tcp_size_per_cu = le32_to_cpu(gc_info->v1_3.gc_tcp_size_per_cu); + adev->gfx.config.gc_tcp_cache_line_size = le32_to_cpu(gc_info->v1_3.gc_tcp_cache_line_size); + adev->gfx.config.gc_instruction_cache_size_per_sqc = le32_to_cpu(gc_info->v1_3.gc_instruction_cache_size_per_sqc); + adev->gfx.config.gc_instruction_cache_line_size = le32_to_cpu(gc_info->v1_3.gc_instruction_cache_line_size); + adev->gfx.config.gc_scalar_data_cache_size_per_sqc = le32_to_cpu(gc_info->v1_3.gc_scalar_data_cache_size_per_sqc); + adev->gfx.config.gc_scalar_data_cache_line_size = le32_to_cpu(gc_info->v1_3.gc_scalar_data_cache_line_size); + adev->gfx.config.gc_tcc_size = le32_to_cpu(gc_info->v1_3.gc_tcc_size); + adev->gfx.config.gc_tcc_cache_line_size = le32_to_cpu(gc_info->v1_3.gc_tcc_cache_line_size); + } + break; + case 2: + adev->gfx.config.max_shader_engines = le32_to_cpu(gc_info->v2.gc_num_se); + adev->gfx.config.max_cu_per_sh = le32_to_cpu(gc_info->v2.gc_num_cu_per_sh); + adev->gfx.config.max_sh_per_se = le32_to_cpu(gc_info->v2.gc_num_sh_per_se); + adev->gfx.config.max_backends_per_se = le32_to_cpu(gc_info->v2.gc_num_rb_per_se); + adev->gfx.config.max_texture_channel_caches = le32_to_cpu(gc_info->v2.gc_num_tccs); + adev->gfx.config.max_gprs = le32_to_cpu(gc_info->v2.gc_num_gprs); + adev->gfx.config.max_gs_threads = le32_to_cpu(gc_info->v2.gc_num_max_gs_thds); + adev->gfx.config.gs_vgt_table_depth = le32_to_cpu(gc_info->v2.gc_gs_table_depth); + adev->gfx.config.gs_prim_buffer_depth = le32_to_cpu(gc_info->v2.gc_gsprim_buff_depth); + adev->gfx.config.double_offchip_lds_buf = le32_to_cpu(gc_info->v2.gc_double_offchip_lds_buffer); + adev->gfx.cu_info.wave_front_size = le32_to_cpu(gc_info->v2.gc_wave_size); + adev->gfx.cu_info.max_waves_per_simd = le32_to_cpu(gc_info->v2.gc_max_waves_per_simd); + adev->gfx.cu_info.max_scratch_slots_per_cu = le32_to_cpu(gc_info->v2.gc_max_scratch_slots_per_cu); + adev->gfx.cu_info.lds_size = le32_to_cpu(gc_info->v2.gc_lds_size); + adev->gfx.config.num_sc_per_sh = le32_to_cpu(gc_info->v2.gc_num_sc_per_se) / + le32_to_cpu(gc_info->v2.gc_num_sh_per_se); + adev->gfx.config.num_packer_per_sc = le32_to_cpu(gc_info->v2.gc_num_packer_per_sc); + if (le16_to_cpu(gc_info->v2.header.version_minor) == 1) { + adev->gfx.config.gc_num_tcp_per_sa = le32_to_cpu(gc_info->v2_1.gc_num_tcp_per_sh); + adev->gfx.config.gc_tcp_size_per_cu = le32_to_cpu(gc_info->v2_1.gc_tcp_size_per_cu); + adev->gfx.config.gc_num_sdp_interface = le32_to_cpu(gc_info->v2_1.gc_num_sdp_interface); /* per XCD */ + adev->gfx.config.gc_num_cu_per_sqc = le32_to_cpu(gc_info->v2_1.gc_num_cu_per_sqc); + adev->gfx.config.gc_l1_instruction_cache_size_per_sqc = le32_to_cpu(gc_info->v2_1.gc_instruction_cache_size_per_sqc); + adev->gfx.config.gc_l1_data_cache_size_per_sqc = le32_to_cpu(gc_info->v2_1.gc_scalar_data_cache_size_per_sqc); + adev->gfx.config.gc_tcc_size = le32_to_cpu(gc_info->v2_1.gc_tcc_size); /* per XCD */ + } + break; + default: + dev_err(adev->dev, + "Unhandled GC info table %d.%d\n", + le16_to_cpu(gc_info->v1.header.version_major), + le16_to_cpu(gc_info->v1.header.version_minor)); + return -EINVAL; + } + return 0; +} + + +/* Original amdgpu_discovery_get_mall_info SHA256 0ec5e667ccd6a14bc5db1c91a85db16898e79a2f1e08a602e28cd996ba76d114 */ +static int amdgpu_discovery_get_mall_info(struct amdgpu_device *adev) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + union mall_info *mall_info; + u32 u, mall_size_per_umc, m_s_present, half_use; + u64 mall_size; + u16 offset; + + if (!discovery_bin) { + DRM_ERROR("ip discovery uninitialized\n"); + return -EINVAL; + } + + if (amdgpu_discovery_get_table_info(adev, &info, MALL_INFO)) + return -EINVAL; + offset = le16_to_cpu(info->offset); + + if (!offset) + return 0; + + mall_info = (union mall_info *)(discovery_bin + offset); + + switch (le16_to_cpu(mall_info->v1.header.version_major)) { + case 1: + mall_size = 0; + mall_size_per_umc = le32_to_cpu(mall_info->v1.mall_size_per_m); + m_s_present = le32_to_cpu(mall_info->v1.m_s_present); + half_use = le32_to_cpu(mall_info->v1.m_half_use); + for (u = 0; u < adev->gmc.num_umc; u++) { + if (m_s_present & (1 << u)) + mall_size += mall_size_per_umc * 2; + else if (half_use & (1 << u)) + mall_size += mall_size_per_umc / 2; + else + mall_size += mall_size_per_umc; + } + adev->gmc.mall_size = mall_size; + adev->gmc.m_half_use = half_use; + break; + case 2: + mall_size_per_umc = le32_to_cpu(mall_info->v2.mall_size_per_umc); + adev->gmc.mall_size = (uint64_t)mall_size_per_umc * adev->gmc.num_umc; + break; + default: + dev_err(adev->dev, + "Unhandled MALL info table %d.%d\n", + le16_to_cpu(mall_info->v1.header.version_major), + le16_to_cpu(mall_info->v1.header.version_minor)); + return -EINVAL; + } + return 0; +} + + +/* Original amdgpu_discovery_get_vcn_info SHA256 e51c76188fc0c90a2fcd31a675ad77b1bf46895742187f2ba58138a9334eff31 */ +static int amdgpu_discovery_get_vcn_info(struct amdgpu_device *adev) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + union vcn_info *vcn_info; + u16 offset; + int v; + + if (!discovery_bin) { + DRM_ERROR("ip discovery uninitialized\n"); + return -EINVAL; + } + + /* num_vcn_inst is currently limited to AMDGPU_MAX_VCN_INSTANCES + * which is smaller than VCN_INFO_TABLE_MAX_NUM_INSTANCES + * but that may change in the future with new GPUs so keep this + * check for defensive purposes. + */ + if (adev->vcn.num_vcn_inst > VCN_INFO_TABLE_MAX_NUM_INSTANCES) { + dev_err(adev->dev, "invalid vcn instances\n"); + return -EINVAL; + } + + if (amdgpu_discovery_get_table_info(adev, &info, VCN_INFO)) + return -EINVAL; + offset = le16_to_cpu(info->offset); + + if (!offset) + return 0; + + vcn_info = (union vcn_info *)(discovery_bin + offset); + + switch (le16_to_cpu(vcn_info->v1.header.version_major)) { + case 1: + /* num_vcn_inst is currently limited to AMDGPU_MAX_VCN_INSTANCES + * so this won't overflow. + */ + for (v = 0; v < adev->vcn.num_vcn_inst; v++) { + adev->vcn.inst[v].vcn_codec_disable_mask = + le32_to_cpu(vcn_info->v1.instance_info[v].fuse_data.all_bits); + } + break; + default: + dev_err(adev->dev, + "Unhandled VCN info table %d.%d\n", + le16_to_cpu(vcn_info->v1.header.version_major), + le16_to_cpu(vcn_info->v1.header.version_minor)); + return -EINVAL; + } + return 0; +} + + +#undef amdgpu_discovery_calculate_checksum + +/* Intentional corrected v2 directory lookup only. */ +static void checked_harvest(struct amdgpu_device *adev, + uint32_t *vcn_harvest_count) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + struct ip_discovery_header *ihdr; + struct die_header *dhdr; + struct ip *ip; + uint16_t die_offset, ip_offset, num_dies, num_ips; + uint16_t hw_id; + uint8_t inst; + int i, j; + + if (amdgpu_discovery_get_table_info(adev, &info, IP_DISCOVERY)) + return; + ihdr = (struct ip_discovery_header *)(discovery_bin + + le16_to_cpu(info->offset)); + + num_dies = le16_to_cpu(ihdr->num_dies); + + /* scan harvest bit of all IP data structures */ + for (i = 0; i < num_dies; i++) { + die_offset = le16_to_cpu(ihdr->die_info[i].die_offset); + dhdr = (struct die_header *)(discovery_bin + die_offset); + num_ips = le16_to_cpu(dhdr->num_ips); + ip_offset = die_offset + sizeof(*dhdr); + + for (j = 0; j < num_ips; j++) { + ip = (struct ip *)(discovery_bin + ip_offset); + inst = ip->number_instance; + hw_id = le16_to_cpu(ip->hw_id); + if (amdgpu_discovery_validate_ip(adev, inst, hw_id)) + goto next_ip; + + if (ip->harvest == 1) { + switch (hw_id) { + case VCN_HWID: + (*vcn_harvest_count)++; + if (inst == 0) { + adev->vcn.harvest_config |= AMDGPU_VCN_HARVEST_VCN0; + adev->vcn.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN0; + adev->jpeg.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN0; + } else { + adev->vcn.harvest_config |= AMDGPU_VCN_HARVEST_VCN1; + adev->vcn.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN1; + adev->jpeg.inst_mask &= + ~AMDGPU_VCN_HARVEST_VCN1; + } + break; + case DMU_HWID: + adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK; + break; + default: + break; + } + } +next_ip: + ip_offset += struct_size(ip, base_address, + ip->num_base_address); + } + } +} + + +static int fixture_table(struct amdgpu_device *adev, struct table_info **info, uint16_t id) +{ + if (!checked) + return donor_table(adev, info, id); + const struct table_info *entry = amdgpu_discovery_binary_table(adev->discovery.bin, + adev->discovery.size, id); + if (!entry) + return -EINVAL; + *info = (struct table_info *)entry; + return 0; +} + +static int reference_validation(struct amdgpu_device *adev) +{ + if (checked) + return amdgpu_discovery_binary_validate(adev->discovery.bin, adev->discovery.size) ? -EINVAL : 0; + uint8_t *discovery_bin = adev->discovery.bin; + struct binary_header *bhdr; + uint16_t offset, size, checksum, table_id; + int r; + /* check the ip discovery binary signature */ + if (!amdgpu_discovery_verify_binary_signature(discovery_bin)) { + dev_err(adev->dev, + "get invalid ip discovery binary signature\n"); + r = -EINVAL; + return r; + } + + bhdr = (struct binary_header *)discovery_bin; + + offset = offsetof(struct binary_header, binary_checksum) + + sizeof(bhdr->binary_checksum); + size = le16_to_cpu(bhdr->binary_size) - offset; + checksum = le16_to_cpu(bhdr->binary_checksum); + + if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, size, + checksum)) { + dev_err(adev->dev, "invalid ip discovery binary checksum\n"); + r = -EINVAL; + return r; + } + + for (table_id = 0; table_id <= MALL_INFO; table_id++) { + r = amdgpu_discovery_table_check(adev, discovery_bin, table_id); + if (r) + return r; + } + + return 0; +} + +#undef amdgpu_discovery_get_table_info +#undef amdgpu_discovery_init + +/* NPS snapshot consumer only. Hardware refresh is deliberately unavailable in + * this CPU model and must never be called; its known stack-FAM bug is separate. */ +union nps_info { struct nps_info_v1_0 v1; }; +struct amdgpu_gmc_memrange { + uint64_t base_address, limit_address; + uint32_t flags; + int nid_mask; +}; +static int amdgpu_discovery_refresh_nps_info(struct amdgpu_device *adev, union nps_info *info) +{ + (void)adev; + (void)info; + assert(!"hardware refresh is outside the snapshot model"); + return -EINVAL; +} +#define amdgpu_discovery_get_table_info fixture_table + +static int amdgpu_discovery_verify_npsinfo(struct amdgpu_device *adev, + struct table_info *info) +{ + uint8_t *discovery_bin = adev->discovery.bin; + uint16_t checksum; + uint16_t offset; + + offset = le16_to_cpu(info->offset); + checksum = le16_to_cpu(info->checksum); + + struct nps_info_header *nhdr = + (struct nps_info_header *)(discovery_bin + offset); + + if (le32_to_cpu(nhdr->table_id) != NPS_INFO_TABLE_ID) { + dev_dbg(adev->dev, "invalid ip discovery nps info table id\n"); + return -EINVAL; + } + + if (!amdgpu_discovery_verify_checksum(adev, discovery_bin + offset, + le32_to_cpu(nhdr->size_bytes), + checksum)) { + dev_dbg(adev->dev, "invalid nps info data table checksum\n"); + return -EINVAL; + } + + return 0; +} + + +int amdgpu_discovery_get_nps_info(struct amdgpu_device *adev, + uint32_t *nps_type, + struct amdgpu_gmc_memrange *ranges, + int *range_cnt, bool refresh) +{ + uint8_t *discovery_bin = adev->discovery.bin; + struct table_info *info; + union nps_info *nps_info; + union nps_info nps_data; + u16 offset; + int i, r; + + if (!nps_type || !range_cnt || !ranges) + return -EINVAL; + + if (refresh) { + r = amdgpu_discovery_refresh_nps_info(adev, &nps_data); + if (r) + return r; + nps_info = &nps_data; + } else { + if (!discovery_bin) { + dev_err(adev->dev, + "fetch mem range failed, ip discovery uninitialized\n"); + return -EINVAL; + } + + if (amdgpu_discovery_get_table_info(adev, &info, NPS_INFO)) + return -EINVAL; + offset = le16_to_cpu(info->offset); + + if (!offset) + return -ENOENT; + + /* If verification fails, return as if NPS table doesn't exist */ + if (amdgpu_discovery_verify_npsinfo(adev, info)) + return -ENOENT; + + nps_info = (union nps_info *)(discovery_bin + offset); + } + + switch (le16_to_cpu(nps_info->v1.header.version_major)) { + case 1: + *nps_type = nps_info->v1.nps_type; + if (*range_cnt < nps_info->v1.count) { + dev_dbg(adev->dev, + "not enough space for nps ranges: %d < %d\n", + *range_cnt, nps_info->v1.count); + return -ENOSPC; + } + *range_cnt = nps_info->v1.count; + for (i = 0; i < *range_cnt; i++) { + ranges[i].base_address = + nps_info->v1.instance_info[i].base_address; + ranges[i].limit_address = + nps_info->v1.instance_info[i].limit_address; + ranges[i].nid_mask = -1; + ranges[i].flags = 0; + } + break; + default: + dev_err(adev->dev, "Unhandled NPS info table %d.%d\n", + le16_to_cpu(nps_info->v1.header.version_major), + le16_to_cpu(nps_info->v1.header.version_minor)); + return -EINVAL; + } + + return 0; +} + + +#undef amdgpu_discovery_get_table_info diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_refresh_test.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_refresh_test.c new file mode 100644 index 0000000000..cd7b197f1f --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_refresh_test.c @@ -0,0 +1,218 @@ +/* SPDX-License-Identifier: MIT */ +/* Actual retained refresh function compiled against a bounded CPU acquisition + * model. This is not a production amdgpu_device, MMIO or reset provider. */ +#ifdef NDEBUG +#error "discovery refresh checks require active assertions" +#endif +#include "../stela/discovery_binary.h" +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +typedef uint32_t u32; +typedef uint16_t u16; +typedef uint8_t u8; +typedef int64_t loff_t; +#define U32_MAX UINT32_MAX +#define __aligned(bytes) __attribute__((__aligned__(bytes))) +#define ALIGN(value, bytes) (((value) + (bytes) - 1) & ~((bytes) - 1)) +#define mmRCC_CONFIG_MEMSIZE 0 +#define DISCOVERY_TMR_OFFSET (64u * 1024u) +#define le16_to_cpu(x) (x) +#define le32_to_cpu(x) (x) +#define RREG32(reg) ((void)(reg), adev->memory_mib) +union nps_info { struct nps_info_v1_0 v1; }; +struct amdgpu_device { + struct { uint8_t *bin; uint64_t offset; size_t size; bool reserve_tmr; } discovery; + uint8_t vram[1024]; + uint64_t region; + uint32_t memory_mib; + bool skip, mm_fallback; + unsigned reads, omit_read, change_read; +}; +static bool amdgpu_device_skip_hw_access(struct amdgpu_device *adev) { return adev->skip; } +static void amdgpu_device_vram_access(struct amdgpu_device *adev, loff_t pos, + void *bytes, size_t size, bool write) +{ + assert(!write && pos >= 0 && (uint64_t)pos >= adev->region); + uint64_t offset = (uint64_t)pos - adev->region; + assert(offset <= adev->discovery.size && size <= adev->discovery.size - offset); + assert(offset <= sizeof(adev->vram) && size <= sizeof(adev->vram) - offset); + unsigned read = ++adev->reads; + assert(read <= 6); + if (adev->mm_fallback && ((pos & 3) || (size & 3))) return; + if (adev->mm_fallback) assert(!((uintptr_t)bytes & 3)); + if (read == adev->change_read) adev->vram[0] ^= 1; + if (read != adev->omit_read) memcpy(bytes, adev->vram + offset, size); +} +static bool amdgpu_discovery_verify_checksum(struct amdgpu_device *adev, + uint8_t *data, uint32_t bytes, + uint16_t expected) +{ + (void)adev; + assert(bytes <= sizeof(union nps_info)); + return amdgpu_discovery_calculate_checksum(data, bytes) == expected; +} +/* Generated from amdgpu_discovery.c by the Make dependency, without replacing + * its function body or importing Linux allocation/IO implementations. */ +#include "discovery-refresh.inc" + +static unsigned accepted, refused, mutation_accept, mutation_refuse, transfer_cases; +static void put16(void *pointer, uint16_t value) { memcpy(pointer, &value, sizeof(value)); } +static void put32(void *pointer, uint32_t value) { memcpy(pointer, &value, sizeof(value)); } +static size_t directory_offset(unsigned version) +{ + return version == 2 ? offsetof(struct binary_header_v2, table_list) : + offsetof(struct binary_header, table_list); +} +static struct table_info *entry(struct amdgpu_device *device, unsigned version) +{ + return (void *)(device->vram + directory_offset(version) + NPS_INFO * sizeof(struct table_info)); +} +static struct nps_info_v1_0 *nps(struct amdgpu_device *device) +{ + return (void *)(device->vram + 128); +} +static void checksum(struct amdgpu_device *device, unsigned version) +{ + put16(&entry(device,version)->checksum, + amdgpu_discovery_calculate_checksum((uint8_t *)nps(device),nps(device)->header.size_bytes)); +} +static struct amdgpu_device fixture(unsigned version, unsigned count, bool dynamic) +{ + struct amdgpu_device device = {0}; + device.memory_mib = 4; + device.region = dynamic ? 0x240000 : (4u << 20) - DISCOVERY_TMR_OFFSET; + device.discovery.offset = device.region; + device.discovery.size = sizeof(device.vram); + device.discovery.reserve_tmr = true; + /* Only non-NULL initialization evidence; never dereferenced by refresh. */ + device.discovery.bin = (uint8_t *)(uintptr_t)1; + struct binary_header_v2 *h = (void *)device.vram; + put32(&h->binary_signature,BINARY_SIGNATURE); + put16(&h->version_major,version); + put16(&h->binary_size,sizeof(device.vram)); + if (version == 2) put16(&h->num_tables,TOTAL_TABLES); + put16(&entry(&device,version)->offset,128); + put16(&entry(&device,version)->size,sizeof(struct nps_info_v1_0)); + struct nps_info_v1_0 *data = nps(&device); + data->header.table_id = NPS_INFO_TABLE_ID; + data->header.version_major = 1; + data->header.size_bytes = (uint32_t)(offsetof(struct nps_info_v1_0,instance_info) + + count * sizeof(struct nps_instance_info_v1_0)); + data->nps_type = 3; + data->count = count; + for (unsigned i = 0; i < count; i++) { + data->instance_info[i].base_address = (uint64_t)i << 24; + data->instance_info[i].limit_address = ((uint64_t)i + 1) << 24; + } + checksum(&device,version); + return device; +} +static void reject(struct amdgpu_device *device) +{ + union nps_info output, before; + memset(&output,0xa5,sizeof(output)); before = output; + assert(amdgpu_discovery_refresh_nps_info(device,&output) < 0); + assert(!memcmp(&output,&before,sizeof(output))); + refused++; +} +int main(void) +{ + for (unsigned version = 1; version <= 2; version++) { + for (unsigned count = 0; count <= NPS_INFO_TABLE_MAX_NUM_INSTANCES; count++) { + for (unsigned dynamic = 0; dynamic <= 1; dynamic++) { + struct amdgpu_device device = fixture(version,count,dynamic); + union nps_info output; + memset(&output,0xa5,sizeof(output)); + assert(!amdgpu_discovery_refresh_nps_info(&device,&output)); + assert(device.reads == 6); + assert(!memcmp(&output,nps(&device),nps(&device)->header.size_bytes)); + for (size_t i = nps(&device)->header.size_bytes; i < sizeof(output); i++) + assert(!((uint8_t *)&output)[i]); + accepted++; + } + } + for (unsigned omitted = 1; omitted <= 6; omitted++) { + struct amdgpu_device device = fixture(version,2,true); + device.omit_read = omitted; reject(&device); + } + struct amdgpu_device device; +#define RESET() (device = fixture(version,2,true)) + for (unsigned bytes = 20; bytes <= sizeof(union nps_info); bytes++) { + RESET(); device.mm_fallback = true; + nps(&device)->count = 0; + nps(&device)->header.size_bytes = bytes; + checksum(&device,version); + /* The padded transfer can exceed the declared binary span, but + * must stay in the actually acquired region. Checksum remains exact. */ + put16(device.vram + offsetof(struct binary_header,binary_size),128 + bytes); + union nps_info output; + assert(!amdgpu_discovery_refresh_nps_info(&device,&output)); + assert(output.v1.header.size_bytes == bytes && !output.v1.count); + for (size_t i = bytes; i < sizeof(output); i++) assert(!((uint8_t *)&output)[i]); + transfer_cases++; + } + RESET(); device.skip = true; reject(&device); assert(!device.reads); + RESET(); device.discovery.bin = NULL; reject(&device); assert(!device.reads); + RESET(); device.discovery.reserve_tmr = false; reject(&device); assert(!device.reads); + RESET(); device.memory_mib = 0; reject(&device); assert(!device.reads); + RESET(); device.memory_mib = U32_MAX; reject(&device); assert(!device.reads); + RESET(); device.discovery.offset = UINT64_MAX; reject(&device); assert(!device.reads); + RESET(); device.discovery.offset = (4u << 20) - 8; reject(&device); assert(!device.reads); + RESET(); device.discovery.size = 15; reject(&device); assert(!device.reads); + RESET(); device.vram[0] ^= 1; reject(&device); + RESET(); put16(device.vram + offsetof(struct binary_header,version_major),3); reject(&device); + RESET(); put16(device.vram + offsetof(struct binary_header,binary_size),1025); reject(&device); + RESET(); put16(device.vram + offsetof(struct binary_header,binary_size),16); reject(&device); + RESET(); put16(&entry(&device,version)->offset,0); reject(&device); + RESET(); put16(&entry(&device,version)->offset,8); reject(&device); + RESET(); put16(&entry(&device,version)->offset,1020); reject(&device); + RESET(); nps(&device)->header.table_id = 0; reject(&device); + RESET(); nps(&device)->header.version_major = 2; reject(&device); + const uint32_t invalid_sizes[] = {0, 12, 19, sizeof(union nps_info)+1, UINT32_MAX}; + for (size_t i = 0; i < sizeof(invalid_sizes)/sizeof(invalid_sizes[0]); i++) { + RESET(); nps(&device)->header.size_bytes = invalid_sizes[i]; reject(&device); + } + RESET(); nps(&device)->count = UINT32_MAX; checksum(&device,version); reject(&device); + RESET(); nps(&device)->count = 3; checksum(&device,version); reject(&device); + RESET(); entry(&device,version)->checksum ^= 1; reject(&device); + RESET(); device.change_read = 4; reject(&device); + RESET(); device.change_read = 5; reject(&device); + RESET(); nps(&device)->count = 0; nps(&device)->header.size_bytes = 21; + checksum(&device,version); device.discovery.size = 149; + put16(device.vram + offsetof(struct binary_header,binary_size),149); reject(&device); + if (version == 2) { + RESET(); put16(&((struct binary_header_v2 *)device.vram)->num_tables,NPS_INFO); reject(&device); + RESET(); put16(&((struct binary_header_v2 *)device.vram)->num_tables,UINT16_MAX); reject(&device); + } +#undef RESET + uint32_t state = 0x4e505300u + version; + for (unsigned i = 0; i < 4096; i++) { + device = fixture(version,NPS_INFO_TABLE_MAX_NUM_INSTANCES,true); + state = state * 1664525u + 1013904223u; + size_t at = (state >> 16) % sizeof(device.vram); + state = state * 1664525u + 1013904223u; + device.vram[at] ^= (uint8_t)(1u << (state >> 29)); + union nps_info output, before; + memset(&output,0xa5,sizeof(output)); before = output; + int status = amdgpu_discovery_refresh_nps_info(&device,&output); + if (status) { + assert(!memcmp(&output,&before,sizeof(output))); + mutation_refuse++; + } else { + assert(output.v1.header.table_id == NPS_INFO_TABLE_ID); + assert(output.v1.header.version_major == 1); + assert(output.v1.header.size_bytes <= sizeof(output)); + assert(output.v1.count <= NPS_INFO_TABLE_MAX_NUM_INSTANCES); + mutation_accept++; + } + } + } + printf("AMD actual refresh: %u accepted, %u refused, %u MM transfer sizes, mutations %u accepted/%u refused; bounded CPU acquisition model, no hardware\n", + accepted,refused,transfer_cases,mutation_accept,mutation_refuse); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr.c b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr.c new file mode 100644 index 0000000000..8ed8423fca --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr.c @@ -0,0 +1,203 @@ +/* SPDX-License-Identifier: MIT */ +/* Independent original ordered-policy and instrumented shipping-C RAM model. + * No callback below is a production provider or hardware-state claim. */ +#include "../stela/discovery_tmr.h" +#include "../stela/discovery_binary.h" +#include "../amdgpu/amdgpu_discovery_tmr_core.h" +#include "../amdgpu/amdgpu_virt_bootstrap_core.h" +#include +#include +#include +#include +#include +typedef uint32_t u32; +typedef uint64_t u64; +#define U32_MAX UINT32_MAX +#define le32_to_cpu(value) (value) +#define AMD_SRIOV_MSG_IPD_TABLE_ID 0 +#define GFP_KERNEL 0 +struct event { unsigned kind, reg; uint64_t value; size_t bytes; }; +struct model { + uint32_t regs[0x16062]; + struct event events[20000]; unsigned count, polls, ready_after; + uint32_t signature; int acpi_status; uint64_t acpi_offset, acpi_size; + bool oom, corrupt; + uint64_t mm_position; + const uint8_t *vram; size_t vram_size; uint64_t vram_offset; + volatile uint32_t *register_base; +}; +static struct model *active; +static void event(unsigned kind, unsigned reg, uint64_t value, size_t bytes) +{ + assert(active->count < sizeof(active->events)/sizeof(active->events[0])); + active->events[active->count++] = (struct event){kind,reg,value,bytes}; +} +static uint32_t model_read(uint32_t reg) +{ + uint32_t value=active->regs[reg]; + if(reg==mmMP0_SMN_C2PMSG_33) value=active->polls++ >= active->ready_after ? 0x80000000u : 0; + event(1,reg,value,4); return value; +} +struct amdgpu_device { + struct { uint64_t offset; uint32_t size; void *bin; + struct {void *data; size_t size;} debugfs_blob; } discovery; + enum amd_asic_type asic_type; + struct { uint32_t caps; bool is_vf, is_dynamic_crit_regn_enabled; + struct {uint64_t offset;uint32_t size_kb;} crit_regn_tbl[1]; } virt; +}; +#define amdgpu_sriov_vf(adev) ((adev)->virt.is_vf) +#define RREG32(reg) ((void)adev, model_read(reg)) +static void msleep(unsigned milliseconds) {event(2,0,milliseconds,0);} +static void amdgpu_device_vram_access(void *owner, uint64_t offset, void *data, size_t bytes, bool write) +{ (void)owner;assert(!write && bytes==4);event(3,0,offset,bytes);memcpy(data,&active->signature,4); } +static int amdgpu_acpi_get_tmr_info(void *owner, uint64_t *offset, uint64_t *size) +{ (void)owner;event(4,0,0,0);*offset=active->acpi_offset;*size=active->acpi_size;return active->acpi_status; } +static void *kzalloc(size_t size, int flags) +{ (void)flags;event(5,0,0,size);return active->oom ? NULL : calloc(1,size); } +#define amdgpu_discovery_get_tmr_info donor_get_tmr +#include "discovery_tmr_reference.h" +#undef amdgpu_discovery_get_tmr_info +#define amdgpu_discovery_get_tmr_info actual_get_tmr +#include "discovery-tmr-wrapper.inc" +#undef amdgpu_discovery_get_tmr_info + +#define AMDGPU_SRIOV_CAPS_IS_VF (1 << 2) +#define AMDGPU_SRIOV_CAPS_ENABLE_IOV (1 << 1) +#define AMDGPU_PASSTHROUGH_MODE (1 << 3) +static bool is_virtual_machine(void) {return false;} +static bool xen_initial_domain(void) {return false;} +#include "discovery_tmr_virt_reference.h" +static unsigned selector_cases; +static __attribute__((unused)) void selectors(void) +{ + for(unsigned a=0;aregister_base?active->register_base:active->regs), address=(uintptr_t)pointer; + assert(address>=base && address-baseregs) && (address-base)%4==0); + uint32_t reg=(uint32_t)((address-base)/4); + if(reg==1) { + event(6,reg,active->mm_position,4); + if(active->vram) {assert(active->mm_position>=active->vram_offset && active->mm_position-active->vram_offset+4<=active->vram_size);uint32_t v;memcpy(&v,active->vram+active->mm_position-active->vram_offset,4);if(active->corrupt && active->mm_position==active->vram_offset+32)v^=1;return v;} + return active->signature; + } + return model_read(reg); +} +void stela_amd_tmr_test_write(volatile uint32_t *pointer,uint32_t value) +{ + uintptr_t base=(uintptr_t)(active->register_base?active->register_base:active->regs),address=(uintptr_t)pointer; + assert(address>=base && address-baseregs) && (address-base)%4==0); + uint32_t reg=(uint32_t)((address-base)/4);assert(reg==0||reg==6); + event(7,reg,value,4); + if(reg==0) active->mm_position=(active->mm_position&~UINT64_C(0x7fffffff))|(value&0x7fffffff); + else active->mm_position=((uint64_t)value<<31)|(active->mm_position&UINT64_C(0x7fffffff)); +} +static void native_sleep(void *context,unsigned milliseconds) +{assert(context==active);msleep(milliseconds);} +extern int stela_amd_discovery_tmr_test_query(void *,size_t,uint32_t,void *,void(*)(void *,unsigned),struct stela_amd_discovery_tmr *); +static unsigned native_cases; +static __attribute__((unused)) void native_case(unsigned which) +{ + struct model m={.ready_after=0,.signature=BINARY_SIGNATURE};active=&m; + m.regs[mmRCC_CONFIG_MEMSIZE]=64; + struct stela_amd_discovery_tmr out,before;memset(&before,0xa5,sizeof(before));out=before; + size_t bytes=sizeof(m.regs);void *regs=m.regs;unsigned asic=CHIP_IP_DISCOVERY; + void(*sleep)(void *,unsigned)=native_sleep;int expected=0; + struct stela_amd_discovery_tmr *outp=&out; + switch(which) { + case 1:bytes-=1;expected=STELA_AMD_TMR_BOUNDS;break; + case 2:regs=NULL;expected=STELA_AMD_TMR_INVALID;break; + case 3:regs=(uint8_t*)regs+1;expected=STELA_AMD_TMR_INVALID;break; + case 4:bytes=SIZE_MAX;expected=STELA_AMD_TMR_BOUNDS;break; + case 5:sleep=NULL;expected=STELA_AMD_TMR_INVALID;break; + case 6:asic=CHIP_LAST;expected=STELA_AMD_TMR_INVALID;break; + case 7:m.regs[mmRCC_IOV_FUNC_IDENTIFIER]=1;expected=STELA_AMD_TMR_VF_OWNER_UNAVAILABLE;break; + case 8:m.regs[mmRCC_CONFIG_MEMSIZE]=UINT32_MAX;expected=-ENXIO;break; + case 9:m.regs[mmRCC_CONFIG_MEMSIZE]=0;expected=STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;break; + case 10:m.regs[mmRCC_CONFIG_MEMSIZE]=0;m.regs[mmDRIVER_SCRATCH_2]=1024;expected=STELA_AMD_TMR_SYSTEM_OWNER_UNAVAILABLE;break; + case 11:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=4096;break; + case 12:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1023;expected=STELA_AMD_TMR_BOUNDS;break; + case 13:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=4097;expected=STELA_AMD_TMR_BOUNDS;break; + case 14:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_1]=1;expected=STELA_AMD_TMR_BOUNDS;break; + case 15:m.ready_after=2000;break; + case 16:outp=NULL;expected=STELA_AMD_TMR_INVALID;break; + case 17:outp=(void*)((uint8_t*)&out+1);expected=STELA_AMD_TMR_INVALID;break; + case 18:outp=(void*)m.regs;expected=STELA_AMD_TMR_BOUNDS;break; + case 19:outp=(void*)(UINTPTR_MAX&~(uintptr_t)7);expected=STELA_AMD_TMR_BOUNDS;break; + case 20:regs=(void*)(UINTPTR_MAX&~(uintptr_t)3);expected=STELA_AMD_TMR_BOUNDS;break; + case 21:bytes=0;expected=STELA_AMD_TMR_BOUNDS;break; + case 22:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1024;m.regs[mmDRIVER_SCRATCH_0]=(64<<20)-1024;break; + case 23:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=1028;m.regs[mmDRIVER_SCRATCH_0]=(64<<20)-1024;expected=STELA_AMD_TMR_BOUNDS;break; + case 24:m.signature=0;m.regs[mmDRIVER_SCRATCH_2]=4;m.regs[mmDRIVER_SCRATCH_0]=UINT32_MAX-3;m.regs[mmDRIVER_SCRATCH_1]=UINT32_MAX;expected=STELA_AMD_TMR_BOUNDS;break; + } + int r=stela_amd_discovery_tmr_test_query(regs,bytes,asic,&m,sleep,outp); + assert(r==expected); + if(r) assert(!memcmp(&out,&before,sizeof(out))); + else {assert(out.size && out.offset+out.size<=out.vram_bytes && out.reserved==0);} + if((which>=1&&which<=6)||(which>=16&&which<=21))assert(m.count==0); + if(which==7)assert(m.count==1); + if(which==15)assert(m.polls==2000); /* No invented timeout/READY. */ + ++native_cases; +} +#ifndef STELA_TMR_RUST_MODEL +int main(void) +{ + selectors(); + for(unsigned i=0;i<256;i++)compare(i); + for(unsigned i=0;i<25;i++)native_case(i); + /* Selector fixture is exhaustive over actual original enum values. */ + for(unsigned a=0;adiscovery.size = DISCOVERY_TMR_SIZE; + if (vram_size) + adev->discovery.offset = (vram_size << 20) - DISCOVERY_TMR_OFFSET; + + if (amdgpu_sriov_vf(adev)) { + if (adev->virt.is_dynamic_crit_regn_enabled) { + adev->discovery.offset = + adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].offset; + adev->discovery.size = + adev->virt.crit_regn_tbl[AMD_SRIOV_MSG_IPD_TABLE_ID].size_kb << 10; + if (!adev->discovery.size) + return -EINVAL; + } else { + goto out; + } + } else { + if (adev->discovery.offset) { + u32 signature; + + /* If VRAM holds a valid discovery signature at the default + * discovery offset, use it as-is. + */ + amdgpu_device_vram_access(adev, adev->discovery.offset, + &signature, sizeof(signature), + false); + if (le32_to_cpu(signature) == BINARY_SIGNATURE) + goto out; + } + + tmr_size = RREG32(mmDRIVER_SCRATCH_2); + if (tmr_size) { + /* It's preferred to transition to PSP mailbox reg interface + * for both bare-metal and passthrough if available */ + adev->discovery.size = (u32)tmr_size; + tmr_offset_lo = RREG32(mmDRIVER_SCRATCH_0); + tmr_offset_hi = RREG32(mmDRIVER_SCRATCH_1); + adev->discovery.offset = ((u64)le32_to_cpu(tmr_offset_hi) << 32 | + le32_to_cpu(tmr_offset_lo)); + } else if (!vram_size) { + /* fall back to apci approach to query tmr offset if vram_size is 0 */ + ret = amdgpu_acpi_get_tmr_info(adev, &tmr_offset, &tmr_size); + if (ret) + return ret; + adev->discovery.size = DISCOVERY_TMR_SIZE; + adev->discovery.offset = tmr_offset + tmr_size - DISCOVERY_TMR_OFFSET; + } + } +out: + adev->discovery.bin = kzalloc(adev->discovery.size, GFP_KERNEL); + if (!adev->discovery.bin) + return -ENOMEM; + adev->discovery.debugfs_blob.data = adev->discovery.bin; + adev->discovery.debugfs_blob.size = adev->discovery.size; + + return 0; +} + diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_test_io.h b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_test_io.h new file mode 100644 index 0000000000..c49c38651b --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_test_io.h @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: MIT */ +#include +uint32_t stela_amd_tmr_test_read(const volatile uint32_t *); +void stela_amd_tmr_test_write(volatile uint32_t *, uint32_t); diff --git a/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_virt_reference.h b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_virt_reference.h new file mode 100644 index 0000000000..dcbbc98e2e --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/discovery_tmr_virt_reference.h @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/* Frozen original ASIC/IOV role observation, CPU test only. */ +static u32 amdgpu_virt_init_detect_asic(struct amdgpu_device *adev) +{ + uint32_t reg; + + switch (adev->asic_type) { + case CHIP_TONGA: + case CHIP_FIJI: + reg = RREG32(mmBIF_IOV_FUNC_IDENTIFIER); + break; + case CHIP_VEGA10: + case CHIP_VEGA20: + case CHIP_NAVI10: + case CHIP_NAVI12: + case CHIP_SIENNA_CICHLID: + case CHIP_ARCTURUS: + case CHIP_ALDEBARAN: + case CHIP_IP_DISCOVERY: + reg = RREG32(mmRCC_IOV_FUNC_IDENTIFIER); + break; + default: /* other chip doesn't support SRIOV */ + reg = 0; + break; + } + + if (reg & 1) + adev->virt.caps |= AMDGPU_SRIOV_CAPS_IS_VF; + + if (reg & 0x80000000) + adev->virt.caps |= AMDGPU_SRIOV_CAPS_ENABLE_IOV; + + if (!reg) { + /* passthrough mode exclus sriov mod */ + if (is_virtual_machine() && !xen_initial_domain()) + adev->virt.caps |= AMDGPU_PASSTHROUGH_MODE; + } + + return reg; +} + diff --git a/crates/stela-drivers/src/gpu/amd/tests/native_bar_test.c b/crates/stela-drivers/src/gpu/amd/tests/native_bar_test.c new file mode 100644 index 0000000000..b4d5bdfa4f --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/native_bar_test.c @@ -0,0 +1,283 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright 2008, 2022 Advanced Micro Devices, Inc. + * Copyright 2008 Red Hat Inc. + * Copyright 2009 Jerome Glisse. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Dave Airlie + * Alex Deucher + * Jerome Glisse + */ +/* CPU fixtures only: exact retained Linux policy donors with minimal model + * containers. These do not initialize a device or create production BOs. + */ +#include "../stela/native_bar.h" + +#ifdef __KERNEL__ +_Static_assert(sizeof(struct amdgpu_asic_type_quirk) == 6, "kernel quirk size"); +_Static_assert(__builtin_offsetof(struct amdgpu_asic_type_quirk, revision) == 2, + "kernel revision offset"); +_Static_assert(__builtin_offsetof(struct amdgpu_asic_type_quirk, type) == 4, + "kernel type offset"); +_Static_assert(sizeof(enum amd_asic_type) == 4, "kernel enum ABI"); +unsigned stela_amd_test_kernel_bar(enum amd_asic_type asic); +unsigned stela_amd_test_kernel_bar(enum amd_asic_type asic) +{ + return amdgpu_native_register_bar(asic); +} +#else +#include +#include +#include +#include +#include + +_Static_assert(sizeof(struct amdgpu_asic_type_quirk) == 6, "original quirk ABI"); +_Static_assert(offsetof(struct amdgpu_asic_type_quirk, revision) == 2, "revision ABI"); +_Static_assert(offsetof(struct amdgpu_asic_type_quirk, type) == 4, "type ABI"); +_Static_assert(sizeof(enum amd_asic_type) == 4, "original ASIC enum ABI"); + +typedef uint32_t u32; +struct pci_dev { + uint64_t base[6], bytes[6]; + unsigned flags; +}; +struct amdgpu_device { + enum amd_asic_type asic_type; + uint64_t rmmio_base, rmmio_size; + struct pci_dev *pdev; + void *dev; + struct { + uint64_t base, size; + uint32_t num_kernel_doorbells; + void *kernel_doorbells, *cpu_addr; + } doorbell; + struct { uint32_t max_assignment; } doorbell_index; + struct { unsigned db_start_dw_offset; } mes; +}; +static uint64_t fixture_page, allocation_bytes; +#define PAGE_SIZE fixture_page +#define IORESOURCE_UNSET 1 +#define AMDGPU_GEM_DOMAIN_DOORBELL 0x1234 +#define min_t(t, a, b) ((t)(a) < (t)(b) ? (t)(a) : (t)(b)) +#define ALIGN(v, a) (((v) + (a) - 1) & ~((a) - 1)) +#define dev_err(...) ((void)0) +static uint64_t pci_resource_start(struct pci_dev *p, unsigned n) +{ + assert(n < 6); + return p->base[n]; +} +static uint64_t pci_resource_len(struct pci_dev *p, unsigned n) +{ + assert(n < 6); + return p->bytes[n]; +} +static unsigned pci_resource_flags(struct pci_dev *p, unsigned n) +{ + assert(n == 2); + return p->flags; +} +static void amdgpu_asic_init_doorbell_index(struct amdgpu_device *a) +{ + (void)a; /* Fixture supplies the exact scalar assignment under comparison. */ +} +static int amdgpu_bo_create_kernel(struct amdgpu_device *a, uint64_t bytes, uint64_t alignment, + unsigned domain, void **bo, void *gpu, void **cpu) +{ + (void)a; + (void)bo; + (void)gpu; + (void)cpu; + assert(alignment == fixture_page && domain == AMDGPU_GEM_DOMAIN_DOORBELL); + allocation_bytes = bytes; + return 0; +} +/* Test-only symbol namespace: unchanged donor bodies below must never replace + * original production device entry points when the full driver is linked. */ +#define amdgpu_doorbell_init stela_amd_test_donor_doorbell_init +#define amdgpu_doorbell_create_kernel_doorbells stela_amd_test_donor_create_kernel_doorbells +int amdgpu_doorbell_init(struct amdgpu_device *adev); +int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev); +uint32_t stela_amd_test_original_asic(unsigned which); +uint32_t stela_amd_test_original_asic(unsigned which) +{ + const uint32_t values[] = {CHIP_TAHITI, CHIP_BONAIRE, CHIP_VEGA10, CHIP_IP_DISCOVERY}; + assert(which < sizeof(values) / sizeof(values[0])); + return values[which]; +} + +/* Original register selection SHA256 f0303f65c788eb07dc545ef9da651a5b41d95c0141af21e83638a06ed16e683a */ +static void donor_register_bar(struct amdgpu_device *adev) +{ + if (adev->asic_type >= CHIP_BONAIRE) { + adev->rmmio_base = pci_resource_start(adev->pdev, 5); + adev->rmmio_size = pci_resource_len(adev->pdev, 5); + } else { + adev->rmmio_base = pci_resource_start(adev->pdev, 2); + adev->rmmio_size = pci_resource_len(adev->pdev, 2); + } +} + +/* Original amdgpu_doorbell_create_kernel_doorbells SHA256 f0c7e8fcd31289c8718df9bd6bc6a410219e9be168d3492dc1f25ccaffa87193 */ +int amdgpu_doorbell_create_kernel_doorbells(struct amdgpu_device *adev) +{ + int r; + int size; + + /* SI HW does not have doorbells, skip allocation */ + if (adev->doorbell.num_kernel_doorbells == 0) + return 0; + + /* Reserve first num_kernel_doorbells (page-aligned) for kernel ops */ + size = ALIGN(adev->doorbell.num_kernel_doorbells * sizeof(u32), PAGE_SIZE); + + /* Allocate an extra page for MES kernel usages (ring test) */ + adev->mes.db_start_dw_offset = size / sizeof(u32); + size += PAGE_SIZE; + + r = amdgpu_bo_create_kernel(adev, + size, + PAGE_SIZE, + AMDGPU_GEM_DOMAIN_DOORBELL, + &adev->doorbell.kernel_doorbells, + NULL, + (void **)&adev->doorbell.cpu_addr); + if (r) { + dev_err(adev->dev, + "Failed to allocate kernel doorbells, err=%d\n", r); + return r; + } + + adev->doorbell.num_kernel_doorbells = size / sizeof(u32); + return 0; +} + +/* Original amdgpu_doorbell_init SHA256 acab9b44336a9785900012350b38d0c1da0c2ed235dcc988b7af8b104ba6d917 */ +int amdgpu_doorbell_init(struct amdgpu_device *adev) +{ + + /* No doorbell on SI hardware generation */ + if (adev->asic_type < CHIP_BONAIRE) { + adev->doorbell.base = 0; + adev->doorbell.size = 0; + adev->doorbell.num_kernel_doorbells = 0; + return 0; + } + + if (pci_resource_flags(adev->pdev, 2) & IORESOURCE_UNSET) + return -EINVAL; + + amdgpu_asic_init_doorbell_index(adev); + + /* doorbell bar mapping */ + adev->doorbell.base = pci_resource_start(adev->pdev, 2); + adev->doorbell.size = pci_resource_len(adev->pdev, 2); + + adev->doorbell.num_kernel_doorbells = + min_t(u32, adev->doorbell.size / sizeof(u32), + adev->doorbell_index.max_assignment + 1); + if (adev->doorbell.num_kernel_doorbells == 0) + return -EINVAL; + + /* + * For Vega, reserve and map two pages on doorbell BAR since SDMA + * paging queue doorbell use the second page. The + * AMDGPU_DOORBELL64_MAX_ASSIGNMENT definition assumes all the + * doorbells are in the first page. So with paging queue enabled, + * the max num_kernel_doorbells should + 1 page (0x400 in dword) + */ + if (adev->asic_type >= CHIP_VEGA10) + adev->doorbell.num_kernel_doorbells += 0x400; + + return 0; +} + +#ifndef STELA_AMD_BAR_TEST_LIBRARY +int main(void) +{ + unsigned cases = 0; + const uint32_t assignments[] = {0, 31, 255, 1023, 2047, 4095}; + const uint64_t pages[] = {4096, 65536}; + for (unsigned asic = 0; asic < CHIP_LAST; asic++) { + for (unsigned p = 0; p < 2; p++) { + for (unsigned m = 0; m < 6; m++) { + fixture_page = pages[p]; + struct pci_dev pci = { + .base = {0, 0, 0x100000, 0, 0, 0x200000}, + .bytes = {0, 0, 0x100000, 0, 0, 0x40000}, + }; + struct amdgpu_device device = { + .asic_type = asic, .pdev = &pci, .doorbell_index = {assignments[m]}, + }; + donor_register_bar(&device); + assert(!amdgpu_doorbell_init(&device)); + allocation_bytes = 0; + assert(!amdgpu_doorbell_create_kernel_doorbells(&device)); + struct stela_amd_bar_layout layout; + assert(stela_amd_native_bar_layout(asic, asic < CHIP_BONAIRE ? 0 : pci.bytes[2], + asic < CHIP_BONAIRE ? 0 : assignments[m], + fixture_page, &layout) == STELA_AMD_BAR_OK); + uint32_t bar = UINT32_MAX; + assert(stela_amd_native_register_bar(asic, &bar) == STELA_AMD_BAR_OK); + assert(bar == layout.register_bar); + assert(device.rmmio_base == pci.base[layout.register_bar]); + assert(device.rmmio_size == pci.bytes[layout.register_bar]); + assert(device.doorbell.num_kernel_doorbells == layout.kernel_doorbells); + assert(allocation_bytes == layout.kernel_doorbell_bytes); + if (layout.kernel_doorbells) + assert(device.mes.db_start_dw_offset * 4 == allocation_bytes - fixture_page); + cases++; + } + } + } + struct stela_amd_bar_layout output, saved; + memset(&output, 0xa5, sizeof(output)); + saved = output; + const struct { + uint32_t asic; + uint64_t bytes; + uint32_t max; + uint64_t page; + } bad[] = { + {CHIP_LAST, 65536, 1023, 4096}, {CHIP_BONAIRE, 65536, 1023, 0}, + {CHIP_BONAIRE, 65536, 1023, 8191}, {CHIP_BONAIRE, 65536, 1023, UINT64_MAX}, + {CHIP_BONAIRE, 0, 1023, 4096}, {CHIP_BONAIRE, 3, 1023, 4096}, + {CHIP_BONAIRE, UINT64_MAX, 1023, 4096}, {CHIP_BONAIRE, 65536, UINT32_MAX, 4096}, + {CHIP_VEGA10, 65536, UINT32_MAX - 1, 4096}, {CHIP_VEGA10, 4096, 1023, 4096}, + {CHIP_BONAIRE, UINT64_C(0xffffffff) * 4, UINT32_C(0x7ffffffe), 4096}, + {CHIP_TAHITI, 4096, 0, 4096}, {CHIP_TAHITI, 0, 1, 4096}, + }; + for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + assert(stela_amd_native_bar_layout(bad[i].asic, bad[i].bytes, bad[i].max, + bad[i].page, &output) != STELA_AMD_BAR_OK); + assert(!memcmp(&output, &saved, sizeof(output))); + } + assert(stela_amd_native_bar_layout(CHIP_TAHITI, 0, 0, 4096, NULL) == STELA_AMD_BAR_INVALID); + uint32_t bar = UINT32_MAX; + assert(stela_amd_native_register_bar(CHIP_LAST, &bar) == STELA_AMD_BAR_INVALID); + assert(bar == UINT32_MAX); + assert(stela_amd_native_register_bar(CHIP_TAHITI, NULL) == STELA_AMD_BAR_INVALID); + printf("AMD native BAR: %u exact original donor layouts, ABI and atomic bounds passed; no hardware\n", cases); + return 0; +} +#endif + +#endif /* !__KERNEL__ */ diff --git a/crates/stela-drivers/src/gpu/amd/tests/native_mmio.rs b/crates/stela-drivers/src/gpu/amd/tests/native_mmio.rs new file mode 100644 index 0000000000..690c4ee970 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/native_mmio.rs @@ -0,0 +1,570 @@ +//! Canonical-owner model in a separate test process: one real Authority::activate +//! call, immutable synthetic PCI/resources and actual native C policy/ABI. +//! No physical GPU, page table, cache-policy or hardware activation is modeled +//! as completed by a production adapter. +extern crate alloc; +#[path = "pci.rs"] +mod pci_tests; +#[path = "vram.rs"] +mod vram_tests; +use stela_drivers::{ + Clock, bus, + gpu::amd::{discovery, native_mmio, pci}, +}; + +use bus::{ + mmio::owned::{ + AddressSpace, Authority, CacheAttribute, Error as MmioError, InstalledMapping, MapFailure, + MapRequest, MappingPlatform, PhysicalSpan, Protection, Resource, ResourceBacking, + ResourceKind, + }, + pci::{Address, ConfigSpace, Function}, +}; +use native_mmio::{AttachedBars, Error, KernelDoorbells, RegisterBar, Rollback, Stage}; +use std::{ + alloc::{Layout, alloc_zeroed, dealloc}, + collections::BTreeMap, + ptr::NonNull, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, +}; + +#[link(name = "stela-amd-bar-test", kind = "static")] +unsafe extern "C" { + fn stela_amd_test_original_asic(which: u32) -> u32; +} +fn asic(which: u32) -> u32 { + // SAFETY: the C fixture returns an original header enum, no hardware call. + unsafe { stela_amd_test_original_asic(which) } +} + +struct Config; +impl ConfigSpace for Config { + fn read32(&self, offset: u16) -> u32 { + match offset { + 0 => 0x1234_1002, + 8 => 0x1200_0000, // Original matching is not restricted to display inventory. + _ => panic!("resource attachment must not probe or activate hardware"), + } + } + fn write32(&mut self, _: u16, _: u32) { + panic!("no PCI writes") + } + fn write16(&mut self, _: u16, _: u16) { + panic!("no PCI writes") + } + fn write8(&mut self, _: u16, _: u8) { + panic!("no PCI writes") + } +} +fn function() -> Function { + Function::new( + Address { + segment: 0, + bus: 1, + device: 0, + function: 0, + }, + Config, + ) + .unwrap() +} + +struct Backing { + span: PhysicalSpan, + kind: ResourceKind, + drops: Arc, +} +impl Drop for Backing { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::Relaxed); + } +} +// SAFETY: test-only exclusive immutable synthetic resource, retained by the +// canonical owner. It neither stands in for physical ownership nor drives a GPU. +unsafe impl ResourceBacking for Backing { + fn physical_span(&self) -> PhysicalSpan { + self.span + } + fn kind(&self) -> ResourceKind { + self.kind + } +} +fn resource(base: u64, bytes: u64, kind: ResourceKind) -> (Resource, Arc) { + let drops = Arc::new(AtomicUsize::new(0)); + let result = Resource::new(Box::new(Backing { + span: PhysicalSpan::new(base, bytes).unwrap(), + kind, + drops: Arc::clone(&drops), + })); + (result, drops) +} +fn registers(base: u64, bar: u8) -> RegisterBar { + RegisterBar { + index: bar, + resource: resource(base, 16384, ResourceKind::Registers).0, + } +} +fn doors(base: u64, modern: bool) -> KernelDoorbells { + KernelDoorbells { + index: 2, + resource: resource(base, 65536, ResourceKind::PrefetchableMemory).0, + offset: 4096, + reserved_bytes: if modern { 16384 } else { 8192 }, + logical_dwords: if modern { 3072 } else { 2048 }, + max_assignment: 1023, + } +} + +struct Allocation { + address: usize, + bytes: usize, +} +#[derive(Default)] +struct ModelState { + calls: usize, + unmaps: usize, + fail_map: usize, + fail_uncertain: bool, + fail_unmaps: usize, + next_token: u64, + allocations: BTreeMap, + requests: Vec, +} +#[derive(Default)] +struct Model(Mutex); +// SAFETY: isolated CPU model. Its own aligned allocation is exact and retained +// through acknowledged unmap or the canonical quarantine. No native root/cache +// implementation is claimed; production requires the actual mount provider. +unsafe impl MappingPlatform for Model { + fn check_context(&self, _: AddressSpace) -> Result<(), MmioError> { + Ok(()) + } + unsafe fn map( + &self, + resource: &Resource, + request: MapRequest, + ) -> Result { + assert_eq!(request.attribute, CacheAttribute::Uncached); + assert_eq!(request.protection, Protection::ReadWrite); + assert!(request.physical.start() >= resource.physical_span().start()); + assert!(request.physical.end() <= resource.physical_span().end()); + let mut state = self.0.lock().unwrap(); + state.calls += 1; + state.requests.push(request); + let failing = state.calls == state.fail_map; + if failing && !state.fail_uncertain { + return Err(MapFailure::Unchanged(MmioError::MappingFailed)); + } + let bytes = usize::try_from(request.physical.bytes()).unwrap(); + let layout = Layout::from_size_align(bytes, 4096).unwrap(); + // SAFETY: nonempty checked model allocation, retained below. + let address = NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap(); + state.next_token += 1; + let token = state.next_token; + state.allocations.insert( + token, + Allocation { + address: address.as_ptr() as usize, + bytes, + }, + ); + if failing { + return Err(MapFailure::Uncertain(MmioError::MappingFailed)); + } + Ok(InstalledMapping { + token, + cpu_base: address, + physical: request.physical, + attribute: request.attribute, + protection: request.protection, + }) + } + unsafe fn unmap( + &self, + request: MapRequest, + mapping: InstalledMapping, + ) -> Result<(), MmioError> { + let mut state = self.0.lock().unwrap(); + state.unmaps += 1; + assert_eq!(request.physical, mapping.physical); + if state.fail_unmaps != 0 { + state.fail_unmaps -= 1; + return Err(MmioError::UnmapFailed); + } + let allocation = state.allocations.remove(&mapping.token).unwrap(); + assert_eq!(allocation.address, mapping.cpu_base.as_ptr() as usize); + assert_eq!(allocation.bytes as u64, request.physical.bytes()); + // SAFETY: the caller's canonical model lease guarantees consumer drain; + // this exact allocation/token has been removed once, before deallocation. + unsafe { + dealloc( + allocation.address as *mut u8, + Layout::from_size_align(allocation.bytes, 4096).unwrap(), + ) + }; + Ok(()) + } +} + +#[test] +fn canonical_amd_attachment() { + let model = Arc::new(Model::default()); + // SAFETY: a single isolated CPU test process, complete empty model alias + // inventory and one canonical authority. This does not activate real MMIO. + let authority = unsafe { + Authority::activate( + model.clone(), + AddressSpace { + identity: 1, + physical_bits: 48, + virtual_bits: 48, + }, + Vec::new(), + ) + } + .unwrap(); + pci_tests::original_match(&authority, &model); + let pci = function(); + vram_tests::original_read(&authority, &pci); + + // SI: original BAR2 and no manufactured doorbell allocation. + // SAFETY: model function/enum/resources belong to this one isolated owner. + let mut si = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(0), + asic(0), + registers(0x100000, 2), + None, + ) + } + .unwrap(); + assert!(matches!( + unsafe { + discovery::acquire_dynamic_ip( + &si, + &Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(discovery::Error::Window(Error::AdmissionRequired)) + )); + assert_eq!(si.original_plan(), None); + assert_eq!(si.identity().address, pci.address); + assert_eq!(si.identity().device, pci.device); + assert_eq!(si.identity().asic_type, asic(0)); + assert_eq!(si.identity().original_flags, asic(0)); + assert_eq!(si.register_physical_span().unwrap().start(), 0x100000); + assert!(si.doorbells().unwrap().is_none()); + { + let window = si.registers().unwrap(); + assert_eq!(window.bytes(), 16384); + // SAFETY: pointer is only inspected and never retained outside borrow. + let base = unsafe { window.native_base() }.unwrap().as_ptr() as usize; + assert_eq!(window.direct_dword(0).unwrap().as_ptr() as usize, base); + assert_eq!( + window.direct_dword(4095).unwrap().as_ptr() as usize, + base + 16380 + ); + assert_eq!( + window.direct_dword(4096).unwrap_err(), + Error::IndirectRegisterRequired + ); + assert_eq!( + window.direct_dword(u32::MAX).unwrap_err(), + Error::IndirectRegisterRequired + ); + } + // SAFETY: model has no device/CPU/C consumer; all borrowed views ended. + unsafe { si.retire() }.unwrap(); + assert_eq!(si.registers().err(), Some(Error::Retired)); + assert_eq!(authority.status().unwrap().live, 0); + + // Actual boot ordering: registers precede discovery and kernel doorbell BO + // creation. Retain original C's register view while attaching doors later. + // SAFETY: same immutable synthetic original match and retained resource. + let mut staged = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(1), + asic(1), + registers(0x180000, 5), + None, + ) + } + .unwrap(); + let retained = staged.registers().unwrap(); + let pointer = retained.direct_dword(0).unwrap(); + assert!(staged.doorbells().unwrap().is_none()); + { + let mut state = model.0.lock().unwrap(); + state.fail_map = state.calls + 1; + } + // SAFETY: test-only original BO owner, unchanged injected doorbell failure. + let failed = + unsafe { staged.attach_kernel_doorbells(&authority, doors(0x190000, false)) }.unwrap_err(); + assert_eq!(failed.stage, Stage::Doorbells); + assert_eq!(failed.rollback, Rollback::NotAttempted); + assert_eq!(retained.direct_dword(0).unwrap(), pointer); + assert!(staged.doorbells().unwrap().is_none()); + // SAFETY: same original owner retries actual reservation after unchanged failure. + unsafe { staged.attach_kernel_doorbells(&authority, doors(0x190000, false)) }.unwrap(); + assert_eq!(staged.doorbells().unwrap().unwrap().bytes(), 8192); + assert_eq!(retained.direct_dword(0).unwrap(), pointer); + let register_maps = model + .0 + .lock() + .unwrap() + .requests + .iter() + .filter(|r| r.physical.start() == 0x180000) + .count(); + assert_eq!(register_maps, 1); + let before = model.0.lock().unwrap().calls; + // SAFETY: deliberately duplicate original reservation, rejected pre-map. + assert!(unsafe { staged.attach_kernel_doorbells(&authority, doors(0x1a0000, false)) }.is_err()); + assert_eq!(model.0.lock().unwrap().calls, before); + // SAFETY: model accesses stopped, but retained C view still pins its lease. + assert_eq!( + unsafe { staged.retire() }, + Err(Error::Mapping(MmioError::Busy)) + ); + drop(retained); + // SAFETY: all original model views drained; retry removes exact register lease. + unsafe { staged.retire() }.unwrap(); + assert_eq!(authority.status().unwrap().live, 0); + + // IP-discovery/Vega+ policy: actual logical extent includes paging+MES + // pages, distinct from the deliberately larger reserved physical span. + // SAFETY: the isolated model pins both original-role resources/reservation. + let mut modern = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(3), + asic(3), + registers(0x200000, 5), + Some(doors(0x300000, true)), + ) + } + .unwrap(); + { + let window = modern.doorbells().unwrap().unwrap(); + assert_eq!(window.bytes(), 12288); + assert!(window.dword(3071).is_ok()); + assert!(window.dword(3072).is_err()); + assert!(window.qword(3070).is_ok()); + assert!(window.qword(3071).is_err()); + assert!(window.qword(1).is_err()); + assert!(window.qword(u32::MAX).is_err()); + let requests = &model.0.lock().unwrap().requests; + let door = requests.last().unwrap(); + assert_eq!(door.physical.start(), 0x301000); + assert_eq!(door.physical.bytes(), 16384); + } + // Failed teardown blocks new views and retains exact canonical token for + // acknowledged retry rather than freeing or manufacturing completion. + model.0.lock().unwrap().fail_unmaps = 1; + // SAFETY: no real consumers or active views in this model. + assert_eq!( + unsafe { modern.retire() }, + Err(Error::Mapping(MmioError::UnmapFailed)) + ); + assert_eq!(modern.registers().err(), Some(Error::Retired)); + assert_eq!(modern.doorbells().err(), Some(Error::Retired)); + // SAFETY: original model drain still holds; retry targets retained token. + unsafe { modern.retire() }.unwrap(); + assert_eq!(authority.status().unwrap().live, 0); + + let calls = model.0.lock().unwrap().calls; + let malformed = [ + (4, asic(1), Some(doors(0x400000, false))), + (2, asic(0), Some(doors(0x400000, false))), + (5, u32::MAX, Some(doors(0x400000, false))), + ]; + for (bar, chip, door) in malformed { + // SAFETY: deliberately invalid model facts, expected refusal pre-map. + let error = unsafe { + AttachedBars::attach(&authority, &pci, chip, chip, registers(0x500000, bar), door) + } + .err() + .unwrap(); + assert_eq!(error.stage, Stage::Preflight); + assert_eq!(error.rollback, Rollback::NotAttempted); + } + for which in 0..8 { + let mut door = doors(0x600000, false); + match which { + 0 => door.offset += 1, + 1 => door.reserved_bytes -= 1, + 2 => door.logical_dwords += 1, + 3 => door.resource = resource(0x500000, 65536, ResourceKind::Registers).0, + 4 => door.reserved_bytes = 4096, + 5 => door.index = 0, + 6 => door.offset = 65536, + 7 => door.reserved_bytes = usize::MAX, + _ => unreachable!(), + } + // SAFETY: deliberately malformed isolated-owner input. + assert!( + unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(1), + asic(1), + registers(0x500000, 5), + Some(door), + ) + } + .is_err() + ); + } + // SAFETY: unaligned backing deliberately fails complete-page ownership. + assert!( + unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(0), + asic(0), + RegisterBar { + index: 2, + resource: resource(0x700001, 16384, ResourceKind::Registers).0, + }, + None, + ) + } + .is_err() + ); + assert_eq!(model.0.lock().unwrap().calls, calls); + + // Failed second map rolls back the first unpublished window exactly once. + model.0.lock().unwrap().fail_map = calls + 2; + // SAFETY: genuine isolated model ownership, platform injects unchanged error. + let error = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(1), + asic(1), + registers(0x800000, 5), + Some(doors(0x900000, false)), + ) + } + .err() + .unwrap(); + assert_eq!(error.stage, Stage::Doorbells); + assert_eq!(error.rollback, Rollback::Retired); + assert_eq!(authority.status().unwrap().live, 0); + + // Failed rollback leaves that real model allocation/owner quarantined. + { + let mut state = model.0.lock().unwrap(); + state.fail_map = state.calls + 2; + state.fail_unmaps = 1; + } + let (reg, reg_drops) = resource(0xa00000, 16384, ResourceKind::Registers); + let (door, door_drops) = resource(0xb00000, 65536, ResourceKind::Registers); + let mut kernel = doors(0xc00000, false); + kernel.resource = door; + // SAFETY: owned model resources; failed unmap must preserve exact backing. + let error = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(1), + asic(1), + RegisterBar { + index: 5, + resource: reg, + }, + Some(kernel), + ) + } + .err() + .unwrap(); + assert_eq!( + error.rollback, + Rollback::Quarantined(MmioError::UnmapFailed) + ); + assert_eq!(reg_drops.load(Ordering::Relaxed), 0); + assert_eq!(door_drops.load(Ordering::Relaxed), 1); + assert_eq!(authority.status().unwrap().quarantined, 1); + + // A primary uncertain map failure has no returned window to roll back; + // canonical ownership still quarantines its actual resource/allocation. + { + let mut state = model.0.lock().unwrap(); + state.fail_map = state.calls + 1; + state.fail_uncertain = true; + } + let (reg, reg_drops) = resource(0xd00000, 16384, ResourceKind::Registers); + // SAFETY: isolated model intentionally returns an uncertain partial map. + let error = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(0), + asic(0), + RegisterBar { + index: 2, + resource: reg, + }, + None, + ) + } + .err() + .unwrap(); + assert_eq!(error.stage, Stage::Registers); + assert_eq!(error.rollback, Rollback::NotAttempted); + assert_eq!(reg_drops.load(Ordering::Relaxed), 0); + assert_eq!(authority.status().unwrap().quarantined, 2); + // A late uncertain doorbell map cannot invalidate previously published + // RMMIO. The canonical owner retains only that uncertain doorbell backing. + // SAFETY: separate exact model resources; no hardware consumers. + let mut late = unsafe { + AttachedBars::attach( + &authority, + &pci, + asic(1), + asic(1), + registers(0xe00000, 5), + None, + ) + } + .unwrap(); + let retained = late.registers().unwrap(); + let pointer = retained.direct_dword(0).unwrap(); + let (reservation, drops) = resource(0xf00000, 65536, ResourceKind::Registers); + let mut kernel = doors(0xf00000, false); + kernel.resource = reservation; + { + let mut state = model.0.lock().unwrap(); + state.fail_map = state.calls + 1; + state.fail_uncertain = true; + } + // SAFETY: the model injects uncertain mapping, requiring retained ownership. + let failed = unsafe { late.attach_kernel_doorbells(&authority, kernel) }.unwrap_err(); + assert_eq!(failed.stage, Stage::Doorbells); + assert_eq!(failed.rollback, Rollback::NotAttempted); + assert_eq!(retained.direct_dword(0).unwrap(), pointer); + assert!(late.doorbells().unwrap().is_none()); + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert_eq!(authority.status().unwrap().quarantined, 3); + drop(retained); + // SAFETY: published register view drained; unrelated quarantine stays pinned. + unsafe { late.retire() }.unwrap(); + assert_eq!(authority.status().unwrap().live, 0); + assert_eq!(drops.load(Ordering::Relaxed), 0); + + println!( + "AMD native MMIO: original policy, canonical ownership/bounds/rollback/quarantine; no hardware" + ); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/pci.rs b/crates/stela-drivers/src/gpu/amd/tests/pci.rs new file mode 100644 index 0000000000..2224bcbca3 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/pci.rs @@ -0,0 +1,217 @@ +//! CPU-only original matching with actual public PCI/canonical ownership types. +use super::*; +use crate::pci::{Error as MatchError, IpPath, Policy, Source}; +use std::cell::Cell; + +struct ObservedConfig { + words: [u32; 16], + reads: Cell, +} +impl ConfigSpace for ObservedConfig { + fn read32(&self, offset: u16) -> u32 { + assert!(offset.is_multiple_of(4)); + self.reads.set(self.reads.get() | (1 << (offset / 4))); + self.words[usize::from(offset / 4)] + } + fn write32(&mut self, _: u16, _: u32) { + panic!("original admission performs no config writes") + } + fn write16(&mut self, _: u16, _: u16) { + panic!("original admission performs no config writes") + } + fn write8(&mut self, _: u16, _: u8) { + panic!("original admission performs no config writes") + } +} +fn observed(device: u16, class: u32, revision: u8) -> Function { + let mut words = [0; 16]; + words[0] = (u32::from(device) << 16) | 0x1002; + words[2] = (class << 8) | u32::from(revision); + words[11] = 0x5678_abcd; + Function::new( + Address { + segment: 4, + bus: 0x81, + device: 2, + function: 0, + }, + ObservedConfig { + words, + reads: Cell::new(0), + }, + ) + .unwrap() +} +fn policy() -> Policy { + Policy { + si_built: true, + cik_built: true, + radeon_built: false, + si_support: -1, + cik_support: -1, + experimental: 0, + discovery: -1, + force_asic: -1, + memory_encrypted: false, + firmware_drivers_only: false, + modeset: -1, + } +} + +pub fn original_match(authority: &Authority, model: &Arc) { + let mut function = observed(0xffff, 0x120000, 0x45); + // SAFETY: immutable synthetic config/build inputs, no physical hardware. + let matched = unsafe { crate::pci::identify(&mut function, policy()) }.unwrap(); + assert_eq!(matched.address().segment, 4); + assert_eq!(matched.revision(), 0x45); + assert_eq!(matched.subsystem_ids(), (0xabcd, 0x5678)); + assert_eq!(matched.ip_path(), IpPath::Dynamic); + assert_eq!(matched.source(), Source::Hardware); + assert_eq!(matched.initial_apu_flags(), 0); // Not proof of discrete hardware. + assert_eq!(matched.matched_row(), 310); // Exact third original wildcard. + // SAFETY: canonical model resources belong to this immutable function. + let mut bars = + unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1100000, 5), None) } + .unwrap(); + assert!(matches!( + unsafe { + crate::discovery::acquire_dynamic_ip( + &bars, + &Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(crate::discovery::Error::ClockUnavailable) + )); + assert_eq!(bars.identity().asic_type, matched.asic_type()); + assert_eq!(bars.identity().original_flags, matched.original_flags()); + assert_eq!( + bars.original_plan(), + Some((IpPath::Dynamic, Source::Hardware)) + ); + // SAFETY: no real effects/consumers, exact model mapping can retire. + unsafe { bars.retire() }.unwrap(); + drop(bars); + // Failed matched attachment retains the original truthful rollback behavior. + let calls = model.0.lock().unwrap().calls; + let error = + unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1200000, 2), None) } + .err() + .unwrap(); + assert_eq!(error.stage, Stage::Preflight); + assert_eq!(model.0.lock().unwrap().calls, calls); + { + let mut state = model.0.lock().unwrap(); + state.fail_map = state.calls + 1; + } + // SAFETY: explicit unchanged model map failure, no hardware resources. + let error = + unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1200000, 5), None) } + .err() + .unwrap(); + assert_eq!(error.stage, Stage::Registers); + assert_eq!(error.rollback, Rollback::NotAttempted); + model.0.lock().unwrap().fail_map = 0; + assert_eq!(authority.status().unwrap().live, 0); + assert_eq!( + function.config().reads.get(), + (1 << 0) | (1 << 2) | (1 << 3) | (1 << 11) + ); + + for (id, class, path, source) in [ + (0x6780, 0x020000, IpPath::SiStatic, Source::NotUsed), // class_mask0 + ( + 0x6860, + 0x120000, + IpPath::SocStatic, + Source::Firmware(c"amdgpu/vega10_ip_discovery.bin"), + ), + (0x13db, 0x020000, IpPath::SocStatic, Source::NotUsed), + (0x13fe, 0x020000, IpPath::Dynamic, Source::Hardware), + ] { + let mut function = observed(id, class, 0); + // SAFETY: immutable model corresponds to original initial probe stage. + let matched = unsafe { crate::pci::identify(&mut function, policy()) }.unwrap(); + assert_eq!(matched.ip_path(), path); + assert_eq!(matched.source(), source); + if path != IpPath::Dynamic { + let index = if path == IpPath::SiStatic { 2 } else { 5 }; + let mut bars = unsafe { + AttachedBars::attach_matched(authority, &matched, registers(0x1300000, index), None) + } + .unwrap(); + assert!(matches!( + unsafe { + crate::discovery::acquire_dynamic_ip( + &bars, + &Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(crate::discovery::Error::Window( + Error::StaticInitializationRequired + )) + )); + unsafe { bars.retire() }.unwrap(); + } + } + let mut function = observed(0xffff, 0x120000, 0); + let mut selected_file = policy(); + selected_file.discovery = 2; + // SAFETY: selected original file option on immutable CPU config model. + let matched = unsafe { crate::pci::identify(&mut function, selected_file) }.unwrap(); + assert_eq!( + matched.source(), + Source::Firmware(c"amdgpu/ip_discovery.bin") + ); + let mut bars = + unsafe { AttachedBars::attach_matched(authority, &matched, registers(0x1400000, 5), None) } + .unwrap(); + assert!(matches!( + unsafe { + crate::discovery::acquire_dynamic_ip( + &bars, + &Clock { + ticks_per_microsecond: 0, + }, + ) + }, + Err(crate::discovery::Error::Window( + Error::FirmwareSourceRequired + )) + )); + unsafe { bars.retire() }.unwrap(); + drop(bars); + // Matching creates no file, TMR reservation, hardware fallback or GPU state. + + let mut changed = observed(0xffff, 0x120000, 0); + changed.device = 0x6780; + // SAFETY: model deliberately corrupts public labels; actual config refuses it. + assert_eq!( + unsafe { crate::pci::identify(&mut changed, policy()) }.err(), + Some(MatchError::IdentityChanged) + ); + let mut bridge = observed(0xffff, 0x120000, 0); + bridge.config().words[3] = 1 << 16; + assert_eq!( + unsafe { crate::pci::identify(&mut bridge, policy()) }.err(), + Some(MatchError::UnsupportedHeader) + ); + assert_eq!(bridge.config().reads.get() & (1 << 11), 0); // Never wrong header subsystem layout. + let mut absent = observed(0xffff, 0x120000, 0); + absent.config().words[0] = u32::MAX; + assert_eq!( + unsafe { crate::pci::identify(&mut absent, policy()) }.err(), + Some(MatchError::Absent) + ); + let mut nonmatch = observed(0xffff, 0x020000, 0); + assert_eq!( + unsafe { crate::pci::identify(&mut nonmatch, policy()) }.err(), + Some(MatchError::Native(2)) + ); + println!( + "AMD matched attachment: real public types, accelerator/class0/file/static/refusals/rollback; CPU model only" + ); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/pci_match.c b/crates/stela-drivers/src/gpu/amd/tests/pci_match.c new file mode 100644 index 0000000000..35f4fd26f3 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/pci_match.c @@ -0,0 +1,294 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Actual production query/core plus independent frozen original donor. CPU only. */ +#include "../stela/pci_match.c" +#include +#include +#include +#include +#include + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define PCI_DEVICE(vend,dev) \ + .vendor = (vend), .device = (dev), .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID +#define CONFIG_DRM_AMDGPU_SI 1 +#define CONFIG_DRM_AMDGPU_CIK 1 +#define CONFIG_DRM_RADEON 1 +static bool build_si, build_cik, build_radeon; +#define IS_ENABLED(x) enabled_##x +#define enabled_CONFIG_DRM_AMDGPU_SI build_si +#define enabled_CONFIG_DRM_AMDGPU_CIK build_cik +#define enabled_CONFIG_DRM_RADEON build_radeon +struct device { int unused; }; +struct pci_dev { unsigned vendor, device, subsystem_vendor, subsystem_device, class, revision; struct device dev; }; +enum amd_hw_ip_block_type { + GC_HWIP = 1, + HDP_HWIP, + SDMA0_HWIP, + SDMA1_HWIP, + SDMA2_HWIP, + SDMA3_HWIP, + SDMA4_HWIP, + SDMA5_HWIP, + SDMA6_HWIP, + SDMA7_HWIP, + LSDMA_HWIP, + MMHUB_HWIP, + ATHUB_HWIP, + NBIO_HWIP, + MP0_HWIP, + MP1_HWIP, + UVD_HWIP, + VCN_HWIP = UVD_HWIP, + JPEG_HWIP = VCN_HWIP, + VCN1_HWIP, + VCE_HWIP, + VPE_HWIP, + DF_HWIP, + DCE_HWIP, + OSSSYS_HWIP, + SMUIO_HWIP, + PWR_HWIP, + NBIF_HWIP, + THM_HWIP, + CLK_HWIP, + UMC_HWIP, + RSMU_HWIP, + XGMI_HWIP, + DCI_HWIP, + PCIE_HWIP, + ISP_HWIP, + ATU_HWIP, + AIGC_HWIP, + MAX_HWIP +}; + +#define IP_VERSION(mj,mn,rv) (((unsigned)(mj)<<24)|((unsigned)(mn)<<16)|((unsigned)(rv)<<8)) +struct amdgpu_device { unsigned long flags; enum amd_asic_type asic_type; unsigned long apu_flags; struct pci_dev *pdev; struct { bool reserve_tmr; } discovery; unsigned family, num_ip_blocks; + struct { int num_instances; unsigned sdma_mask; } sdma; + struct { int num_umc; } gmc; struct { unsigned xcc_mask; } gfx; + struct { unsigned num_vcn_inst; } vcn; unsigned ip_versions[MAX_HWIP][48]; void *ddev; }; +struct drm_device; +static int amdgpu_discovery, amdgpu_si_support, amdgpu_cik_support; +static int amdgpu_exp_hw_support, amdgpu_modeset, amdgpu_virtual_display; +static bool encrypted, firmware_only; +static bool drm_firmware_drivers_only(void) { return firmware_only; } +#define CC_ATTR_MEM_ENCRYPT 1 +static bool cc_platform_has(int unused) { (void)unused; return encrypted; } +static bool amdgpu_device_asic_has_dc_support(struct pci_dev *p, unsigned f) { (void)p; (void)f; return false; } +static void dev_info(struct device *dev, const char *format, ...) { (void)dev; (void)format; } +#define ENOTSUPP 524 +static int selected_path; +#define AMDGPU_FAMILY_SI 1 +#define AMDGPU_FAMILY_KV 2 +#define AMDGPU_FAMILY_CI 3 +#define AMDGPU_FAMILY_CZ 4 +#define AMDGPU_FAMILY_VI 5 +static int si_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_SI; return 0; } +static int cik_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_CIK; return 0; } +static int vi_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_VI; return 0; } +static int amdgpu_discovery_set_ip_blocks(struct amdgpu_device *a) { (void)a; selected_path=AMDGPU_INITIAL_IP_DISCOVERY; return 0; } +static int acquisition_status, acquisition_calls; +static int amdgpu_discovery_init(struct amdgpu_device *a) { (void)a; acquisition_calls++; return acquisition_status; } +static int amdgpu_discovery_reg_base_init(struct amdgpu_device *a) { (void)a; acquisition_calls++; selected_path=STELA_AMD_IP_DYNAMIC; return acquisition_status; } +#define STATIC_INIT(name) static void name(struct amdgpu_device *a) { (void)a; selected_path=STELA_AMD_IP_SOC_STATIC; } +STATIC_INIT(vega10_reg_base_init) +STATIC_INIT(vega20_reg_base_init) +STATIC_INIT(arct_reg_base_init) +STATIC_INIT(aldebaran_reg_base_init) +STATIC_INIT(cyan_skillfish_reg_base_init) +static void amdgpu_discovery_harvest_ip(struct amdgpu_device *a) { (void)a; } +static void amdgpu_discovery_get_gfx_info(struct amdgpu_device *a) { (void)a; } +static void amdgpu_discovery_get_mall_info(struct amdgpu_device *a) { (void)a; } +static void amdgpu_discovery_get_vcn_info(struct amdgpu_device *a) { (void)a; } +static void drm_err(void *d, const char *f, ...) { (void)d; (void)f; } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-variable" +#pragma clang diagnostic ignored "-Wunused-but-set-variable" +#include "pci_reference.h" +#pragma clang diagnostic pop +#define amdgpu_fix_asic_type linux_amdgpu_fix_asic_type +#define amdgpu_support_enabled linux_amdgpu_support_enabled +#define amdgpu_device_init_apu_flags linux_amdgpu_device_init_apu_flags +#define amdgpu_discovery_get_fw_name linux_amdgpu_discovery_get_fw_name +#include "pci-linux-wrappers.inc" +#undef amdgpu_fix_asic_type +#undef amdgpu_support_enabled +#undef amdgpu_device_init_apu_flags +#undef amdgpu_discovery_get_fw_name +#include "pci-linux-paths.inc" + +static struct stela_amd_pci_policy policy(void) +{ + return (struct stela_amd_pci_policy){.si_built=1,.cik_built=1,.si_support=-1, + .cik_support=-1,.discovery=-1,.force_asic=-1,.modeset=-1}; +} +static void set_policy(struct stela_amd_pci_policy p) +{ + build_si=p.si_built;build_cik=p.cik_built;build_radeon=p.radeon_built; + amdgpu_si_support=p.si_support;amdgpu_cik_support=p.cik_support; + amdgpu_exp_hw_support=p.experimental;amdgpu_discovery=p.discovery; + amdgpu_modeset=p.modeset;encrypted=p.memory_encrypted;firmware_only=p.firmware_drivers_only; +} +static struct pci_dev device(struct stela_amd_pci_identity i) +{ + return (struct pci_dev){.vendor=i.vendor,.device=i.device,.subsystem_vendor=i.subvendor, + .subsystem_device=i.subdevice,.class=i.class_code,.revision=i.revision}; +} +static size_t comparisons; +static void compare(struct stela_amd_pci_identity i, struct stela_amd_pci_policy p) +{ + set_policy(p); + struct pci_dev dev=device(i); + struct stela_amd_pci_match out, before; + memset(&out,0xa5,sizeof(out));before=out; + const struct pci_device_id *ref=ref_pci_match_id(ref_pciidlist,&dev); + assert(linux_amdgpu_fix_asic_type(&dev,ref?ref->driver_data:0)==ref_amdgpu_fix_asic_type(&dev,ref?ref->driver_data:0)); + unsigned family=ref?ref->driver_data&AMD_ASIC_MASK:0; + assert(linux_amdgpu_support_enabled(&dev.dev,family)==ref_amdgpu_support_enabled(&dev.dev,family)); + unsigned long flags=0; + int expected=ref?ref_probe(&dev,ref,&flags):-ENODEV; + int status=stela_amd_pci_match(&i,&p,&out); + if (!expected && p.force_asic>=0 && p.force_asicdevice==UINT32_MAX?0xffff:id->device,0,0,id->class,0xe3}; + for (unsigned built=0;built<8;built++) + for (int option=-2;option<=2;option++) { + struct stela_amd_pci_policy q=policy(); + q.si_built=built&1;q.cik_built=(built>>1)&1;q.radeon_built=(built>>2)&1; + q.si_support=option;q.cik_support=option; + q.experimental=option;q.firmware_drivers_only=(unsigned)(option&1); + q.memory_encrypted=(unsigned)(option&1);q.modeset=option; + compare(i,q); + } + } + for (int option=-2;option<=2;option++) { + struct stela_amd_pci_policy q=policy();q.discovery=option; + compare((struct stela_amd_pci_identity){0x1002,0x13db,0,0,0x020000,0},q); + } + /* Original predicate semantics beyond today's ANY-subsystem table rows. */ + for (unsigned bits=0;bits<64;bits++) { + struct pci_device_id id={.vendor=bits&1?PCI_ANY_ID:0x1002,.device=bits&2?PCI_ANY_ID:0x1234, + .subvendor=bits&4?PCI_ANY_ID:0xabcd,.subdevice=bits&8?PCI_ANY_ID:0x5678, + .class=0x120003,.class_mask=bits&16?0xffff00:0xffffff}; + struct stela_amd_pci_identity i={0x1002,0x1234,0xabcd,0x5678,bits&32?0x120004:0x120003,0}; + struct pci_dev d=device(i); + assert((match_one(&id,&i)!=NULL)==(ref_pci_match_one_device(&id,&d)!=NULL)); + i.subvendor++;d=device(i); + assert((match_one(&id,&i)!=NULL)==(ref_pci_match_one_device(&id,&d)!=NULL)); + } + /* Every original source/APU state branch, including later RAVEN2 precedence + * and seeded flags, independently of current PCI row coverage. */ + for (unsigned asic=0;asicdevice == asic_type_quirks[i].device && + pdev->revision == asic_type_quirks[i].revision) { + flags &= ~AMD_ASIC_MASK; + flags |= asic_type_quirks[i].type; + break; + } + } + + return flags; +} + + +static bool amdgpu_support_enabled(struct device *dev, + const enum amd_asic_type family) +{ + const char *gen; + const char *param; + int module_param = -1; + bool radeon_support_built = IS_ENABLED(CONFIG_DRM_RADEON); + bool amdgpu_support_built = false; + bool support_by_default = false; + + switch (family) { + case CHIP_TAHITI: + case CHIP_PITCAIRN: + case CHIP_VERDE: + case CHIP_OLAND: + case CHIP_HAINAN: + gen = "SI"; + param = "si_support"; + module_param = amdgpu_si_support; + amdgpu_support_built = IS_ENABLED(CONFIG_DRM_AMDGPU_SI); + support_by_default = true; + break; + + case CHIP_BONAIRE: + case CHIP_HAWAII: + case CHIP_KAVERI: + case CHIP_KABINI: + case CHIP_MULLINS: + gen = "CIK"; + param = "cik_support"; + module_param = amdgpu_cik_support; + amdgpu_support_built = IS_ENABLED(CONFIG_DRM_AMDGPU_CIK); + support_by_default = true; + break; + + default: + /* All other chips are supported by amdgpu only */ + return true; + } + + if (!amdgpu_support_built) { + dev_info(dev, "amdgpu built without %s support\n", gen); + return false; + } + + if ((module_param == -1 && (support_by_default || !radeon_support_built)) || + module_param == 1) { + if (radeon_support_built) + dev_info(dev, "%s support provided by amdgpu.\n" + "Use radeon.%s=1 amdgpu.%s=0 to override.\n", + gen, param, param); + + return true; + } + + if (radeon_support_built) + dev_info(dev, "%s support provided by radeon.\n" + "Use radeon.%s=0 amdgpu.%s=1 to override.\n", + gen, param, param); + else if (module_param == 0) + dev_info(dev, "%s support disabled by module param\n", gen); + + return false; +} + + +static int amdgpu_device_init_apu_flags(struct amdgpu_device *adev) +{ + if (!(adev->flags & AMD_IS_APU) || + adev->asic_type < CHIP_RAVEN) + return 0; + + switch (adev->asic_type) { + case CHIP_RAVEN: + if (adev->pdev->device == 0x15dd) + adev->apu_flags |= AMD_APU_IS_RAVEN; + if (adev->pdev->device == 0x15d8) + adev->apu_flags |= AMD_APU_IS_PICASSO; + break; + case CHIP_RENOIR: + if ((adev->pdev->device == 0x1636) || + (adev->pdev->device == 0x164c)) + adev->apu_flags |= AMD_APU_IS_RENOIR; + else + adev->apu_flags |= AMD_APU_IS_GREEN_SARDINE; + break; + case CHIP_VANGOGH: + adev->apu_flags |= AMD_APU_IS_VANGOGH; + break; + case CHIP_YELLOW_CARP: + break; + case CHIP_CYAN_SKILLFISH: + if ((adev->pdev->device == 0x13FE) || + (adev->pdev->device == 0x143F)) + adev->apu_flags |= AMD_APU_IS_CYAN_SKILLFISH2; + break; + default: + break; + } + + return 0; +} + + +static const char *amdgpu_discovery_get_fw_name(struct amdgpu_device *adev) +{ + if (amdgpu_discovery == 2) { + /* Assume there is valid discovery TMR in VRAM even if binary is sideloaded */ + adev->discovery.reserve_tmr = true; + return "amdgpu/ip_discovery.bin"; + } + + switch (adev->asic_type) { + case CHIP_VEGA10: + return "amdgpu/vega10_ip_discovery.bin"; + case CHIP_VEGA12: + return "amdgpu/vega12_ip_discovery.bin"; + case CHIP_RAVEN: + if (adev->apu_flags & AMD_APU_IS_RAVEN2) + return "amdgpu/raven2_ip_discovery.bin"; + else if (adev->apu_flags & AMD_APU_IS_PICASSO) + return "amdgpu/picasso_ip_discovery.bin"; + else + return "amdgpu/raven_ip_discovery.bin"; + case CHIP_VEGA20: + return "amdgpu/vega20_ip_discovery.bin"; + case CHIP_ARCTURUS: + return "amdgpu/arcturus_ip_discovery.bin"; + case CHIP_ALDEBARAN: + return "amdgpu/aldebaran_ip_discovery.bin"; + default: + return NULL; + } +} + + +static inline const struct pci_device_id * +pci_match_one_device(const struct pci_device_id *id, const struct pci_dev *dev) +{ + if ((id->vendor == PCI_ANY_ID || id->vendor == dev->vendor) && + (id->device == PCI_ANY_ID || id->device == dev->device) && + (id->subvendor == PCI_ANY_ID || id->subvendor == dev->subsystem_vendor) && + (id->subdevice == PCI_ANY_ID || id->subdevice == dev->subsystem_device) && + !((id->class ^ dev->class) & id->class_mask)) + return id; + return NULL; +} + + +const struct pci_device_id *pci_match_id(const struct pci_device_id *ids, + struct pci_dev *dev) +{ + if (ids) { + while (ids->vendor || ids->subvendor || ids->class_mask) { + if (pci_match_one_device(ids, dev)) + return ids; + ids++; + } + } + return NULL; +} + + +static int ref_probe(struct pci_dev *pdev, const struct pci_device_id *ent, unsigned long *flags_out) +{ + struct drm_device *ddev; + struct amdgpu_device *adev; + unsigned long flags = ent->driver_data; + int ret, retry = 0, i; + bool supports_atomic = false; + + if ((pdev->class >> 8) == PCI_CLASS_DISPLAY_VGA || + (pdev->class >> 8) == PCI_CLASS_DISPLAY_OTHER) { + if (drm_firmware_drivers_only() && amdgpu_modeset == -1) + return -EINVAL; + } + + /* skip devices which are owned by radeon */ + for (i = 0; i < ARRAY_SIZE(amdgpu_unsupported_pciidlist); i++) { + if (amdgpu_unsupported_pciidlist[i] == pdev->device) + return -ENODEV; + } + + if (amdgpu_virtual_display || + amdgpu_device_asic_has_dc_support(pdev, flags & AMD_ASIC_MASK)) + supports_atomic = true; + + if ((flags & AMD_EXP_HW_SUPPORT) && !amdgpu_exp_hw_support) { + dev_info(&pdev->dev, "This hardware requires experimental hardware support.\n" + "See modparam exp_hw_support\n"); + return -ENODEV; + } + + flags = amdgpu_fix_asic_type(pdev, flags); + + /* Due to hardware bugs, S/G Display on raven requires a 1:1 IOMMU mapping, + * however, SME requires an indirect IOMMU mapping because the encryption + * bit is beyond the DMA mask of the chip. + */ + if (cc_platform_has(CC_ATTR_MEM_ENCRYPT) && + ((flags & AMD_ASIC_MASK) == CHIP_RAVEN)) { + dev_info(&pdev->dev, + "SME is not compatible with RAVEN\n"); + return -ENOTSUPP; + } + + if (!amdgpu_support_enabled(&pdev->dev, flags & AMD_ASIC_MASK)) + return -ENODEV; + + *flags_out = flags; + return 0; +} + +static int ref_initial_path(struct amdgpu_device *adev) +{ + int r; + switch (adev->asic_type) { +#ifdef CONFIG_DRM_AMDGPU_SI + case CHIP_VERDE: + case CHIP_TAHITI: + case CHIP_PITCAIRN: + case CHIP_OLAND: + case CHIP_HAINAN: + adev->family = AMDGPU_FAMILY_SI; + r = si_set_ip_blocks(adev); + if (r) + return r; + break; +#endif +#ifdef CONFIG_DRM_AMDGPU_CIK + case CHIP_BONAIRE: + case CHIP_HAWAII: + case CHIP_KAVERI: + case CHIP_KABINI: + case CHIP_MULLINS: + if (adev->flags & AMD_IS_APU) + adev->family = AMDGPU_FAMILY_KV; + else + adev->family = AMDGPU_FAMILY_CI; + + r = cik_set_ip_blocks(adev); + if (r) + return r; + break; +#endif + case CHIP_TOPAZ: + case CHIP_TONGA: + case CHIP_FIJI: + case CHIP_POLARIS10: + case CHIP_POLARIS11: + case CHIP_POLARIS12: + case CHIP_VEGAM: + case CHIP_CARRIZO: + case CHIP_STONEY: + if (adev->flags & AMD_IS_APU) + adev->family = AMDGPU_FAMILY_CZ; + else + adev->family = AMDGPU_FAMILY_VI; + + r = vi_set_ip_blocks(adev); + if (r) + return r; + break; + default: + r = amdgpu_discovery_set_ip_blocks(adev); + if (r) { + adev->num_ip_blocks = 0; + return r; + } + break; + } + + return 0; +} + +static int ref_discovery_path(struct amdgpu_device *adev) +{ + int r; + switch (adev->asic_type) { + case CHIP_VEGA10: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + vega10_reg_base_init(adev); + adev->sdma.num_instances = 2; + adev->sdma.sdma_mask = 3; + adev->gmc.num_umc = 4; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[SDMA1_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(2, 1, 0); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(6, 1, 0); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(6, 0, 0); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 0, 1); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(7, 0, 0); + adev->ip_versions[VCE_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[DCI_HWIP][0] = IP_VERSION(12, 0, 0); + break; + case CHIP_VEGA12: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + vega10_reg_base_init(adev); + adev->sdma.num_instances = 2; + adev->sdma.sdma_mask = 3; + adev->gmc.num_umc = 4; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 3, 0); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 3, 0); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 0, 1); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 0, 1); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 0, 1); + adev->ip_versions[SDMA1_HWIP][0] = IP_VERSION(4, 0, 1); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(2, 5, 0); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(6, 2, 0); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(6, 1, 0); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(9, 0, 0); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(9, 0, 1); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 2, 1); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(7, 0, 0); + adev->ip_versions[VCE_HWIP][0] = IP_VERSION(4, 0, 0); + adev->ip_versions[DCI_HWIP][0] = IP_VERSION(12, 0, 1); + break; + case CHIP_RAVEN: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + vega10_reg_base_init(adev); + adev->sdma.num_instances = 1; + adev->sdma.sdma_mask = 1; + adev->vcn.num_vcn_inst = 1; + adev->gmc.num_umc = 2; + adev->gfx.xcc_mask = 1; + if (adev->apu_flags & AMD_APU_IS_RAVEN2) { + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 2, 0); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 2, 0); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 1, 1); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 1, 1); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 1, 1); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(2, 1, 1); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(7, 0, 1); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(7, 5, 0); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(10, 0, 1); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(10, 0, 1); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(10, 1, 0); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(10, 0, 1); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 2, 2); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(1, 0, 1); + adev->ip_versions[DCE_HWIP][0] = IP_VERSION(1, 0, 1); + adev->ip_versions[ISP_HWIP][0] = IP_VERSION(2, 0, 0); + } else { + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 1, 0); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 1, 0); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 1, 0); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 1, 0); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 1, 0); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(2, 1, 0); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(7, 0, 0); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(7, 0, 0); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(10, 0, 0); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(10, 0, 0); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(10, 0, 0); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(10, 0, 0); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 1, 0); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(1, 0, 0); + adev->ip_versions[DCE_HWIP][0] = IP_VERSION(1, 0, 0); + adev->ip_versions[ISP_HWIP][0] = IP_VERSION(2, 0, 0); + } + break; + case CHIP_VEGA20: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + vega20_reg_base_init(adev); + adev->sdma.num_instances = 2; + adev->sdma.sdma_mask = 3; + adev->gmc.num_umc = 8; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 4, 0); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 4, 0); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 2, 0); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 2, 0); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 2, 0); + adev->ip_versions[SDMA1_HWIP][0] = IP_VERSION(4, 2, 0); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(3, 6, 0); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(7, 4, 0); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(6, 1, 1); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(11, 0, 2); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(11, 0, 2); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(11, 0, 2); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(11, 0, 2); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 4, 0); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(7, 2, 0); + adev->ip_versions[UVD_HWIP][1] = IP_VERSION(7, 2, 0); + adev->ip_versions[VCE_HWIP][0] = IP_VERSION(4, 1, 0); + adev->ip_versions[DCI_HWIP][0] = IP_VERSION(12, 1, 0); + break; + case CHIP_ARCTURUS: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + arct_reg_base_init(adev); + adev->sdma.num_instances = 8; + adev->sdma.sdma_mask = 0xff; + adev->vcn.num_vcn_inst = 2; + adev->gmc.num_umc = 8; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 4, 1); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 4, 1); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 2, 1); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 2, 1); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][0] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][1] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][2] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][3] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][4] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][5] = IP_VERSION(4, 2, 2); + adev->ip_versions[SDMA1_HWIP][6] = IP_VERSION(4, 2, 2); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(3, 6, 1); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(7, 4, 1); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(6, 1, 2); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(11, 0, 4); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(11, 0, 2); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(11, 0, 3); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(11, 0, 3); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 4, 1); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(2, 5, 0); + adev->ip_versions[UVD_HWIP][1] = IP_VERSION(2, 5, 0); + break; + case CHIP_ALDEBARAN: + /* This is not fatal. We only need the discovery + * binary for sysfs. We don't need it for a + * functional system. + */ + amdgpu_discovery_init(adev); + aldebaran_reg_base_init(adev); + adev->sdma.num_instances = 5; + adev->sdma.sdma_mask = 0x1f; + adev->vcn.num_vcn_inst = 2; + adev->gmc.num_umc = 4; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(9, 4, 2); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(9, 4, 2); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(4, 4, 0); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(4, 4, 0); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(4, 4, 0); + adev->ip_versions[SDMA0_HWIP][1] = IP_VERSION(4, 4, 0); + adev->ip_versions[SDMA0_HWIP][2] = IP_VERSION(4, 4, 0); + adev->ip_versions[SDMA0_HWIP][3] = IP_VERSION(4, 4, 0); + adev->ip_versions[SDMA0_HWIP][4] = IP_VERSION(4, 4, 0); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(3, 6, 2); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(7, 4, 4); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(6, 7, 0); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(13, 0, 2); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(13, 0, 2); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(13, 0, 2); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(13, 0, 2); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(9, 4, 2); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(2, 6, 0); + adev->ip_versions[UVD_HWIP][1] = IP_VERSION(2, 6, 0); + adev->ip_versions[XGMI_HWIP][0] = IP_VERSION(6, 1, 0); + break; + case CHIP_CYAN_SKILLFISH: + if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2) { + r = amdgpu_discovery_reg_base_init(adev); + if (r) + return -EINVAL; + + amdgpu_discovery_harvest_ip(adev); + amdgpu_discovery_get_gfx_info(adev); + amdgpu_discovery_get_mall_info(adev); + amdgpu_discovery_get_vcn_info(adev); + } else { + cyan_skillfish_reg_base_init(adev); + adev->sdma.num_instances = 2; + adev->sdma.sdma_mask = 3; + adev->gfx.xcc_mask = 1; + adev->ip_versions[MMHUB_HWIP][0] = IP_VERSION(2, 0, 3); + adev->ip_versions[ATHUB_HWIP][0] = IP_VERSION(2, 0, 3); + adev->ip_versions[OSSSYS_HWIP][0] = IP_VERSION(5, 0, 1); + adev->ip_versions[HDP_HWIP][0] = IP_VERSION(5, 0, 1); + adev->ip_versions[SDMA0_HWIP][0] = IP_VERSION(5, 0, 1); + adev->ip_versions[SDMA1_HWIP][1] = IP_VERSION(5, 0, 1); + adev->ip_versions[DF_HWIP][0] = IP_VERSION(3, 5, 0); + adev->ip_versions[NBIO_HWIP][0] = IP_VERSION(2, 1, 1); + adev->ip_versions[UMC_HWIP][0] = IP_VERSION(8, 1, 1); + adev->ip_versions[MP0_HWIP][0] = IP_VERSION(11, 0, 8); + adev->ip_versions[MP1_HWIP][0] = IP_VERSION(11, 0, 8); + adev->ip_versions[THM_HWIP][0] = IP_VERSION(11, 0, 1); + adev->ip_versions[SMUIO_HWIP][0] = IP_VERSION(11, 0, 8); + adev->ip_versions[GC_HWIP][0] = IP_VERSION(10, 1, 3); + adev->ip_versions[UVD_HWIP][0] = IP_VERSION(2, 0, 3); + } + break; + default: + r = amdgpu_discovery_reg_base_init(adev); + if (r) { + drm_err(&adev->ddev, "discovery failed: %d\n", r); + return r; + } + + amdgpu_discovery_harvest_ip(adev); + amdgpu_discovery_get_gfx_info(adev); + amdgpu_discovery_get_mall_info(adev); + amdgpu_discovery_get_vcn_info(adev); + break; + } + + return 0; +} + +#undef amdgpu_unsupported_pciidlist +#undef pciidlist +#undef asic_type_quirks +#undef amdgpu_fix_asic_type +#undef amdgpu_support_enabled +#undef amdgpu_device_init_apu_flags +#undef amdgpu_discovery_get_fw_name +#undef pci_match_one_device +#undef pci_match_id \ No newline at end of file diff --git a/crates/stela-drivers/src/gpu/amd/tests/vram.rs b/crates/stela-drivers/src/gpu/amd/tests/vram.rs new file mode 100644 index 0000000000..af95d22c77 --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/vram.rs @@ -0,0 +1,65 @@ +//! Child of the existing one-authority native_mmio test process. The actual C +//! entry accesses only this model's owned host RAM, never physical registers. +use super::*; +use stela_drivers::gpu::amd::vram; + +pub(super) fn original_read(authority: &Authority, pci: &Function) { + let (resource, drops) = resource(0x1100_0000, 16384, ResourceKind::Registers); + // SAFETY: genuine canonical ownership of this isolated RAM-only model; + // no physical device, D0/reset guard or hardware readiness is asserted. + let mut bars = unsafe { + AttachedBars::attach( + authority, + pci, + asic(0), + asic(0), + RegisterBar { index: 2, resource }, + None, + ) + } + .unwrap(); + let window = bars.registers().unwrap(); + let data = window.direct_dword(1).unwrap(); + // SAFETY: exclusively held real host-RAM allocation returned by the model + // mapping platform; seed its MM_DATA word, with no active Rust reference. + unsafe { data.as_ptr().write_volatile(0x5634_1234) }; + let mut output = [0x55aa_55aa; 4]; + // SAFETY: explicitly CPU-only register model, synchronized single test + // thread. C must reject the complete overflowing read before any access. + assert_eq!( + unsafe { vram::read(&window, 256, 252, &mut output) }, + Err(vram::Error::Preflight(2)) + ); + assert_eq!(output, [0x55aa_55aa; 4]); + // SAFETY: same exclusive RAM model. Native MM-index operations are real C + // volatile accesses to this allocation, not an emulated VRAM device. + unsafe { vram::read(&window, 0x8000_000c, 0x7fff_fffc, &mut output) }.unwrap(); + assert_eq!(output, [0x5634_1234; 4]); + // SAFETY: no other model accessor exists or runs concurrently. + assert_eq!( + unsafe { window.direct_dword(0).unwrap().as_ptr().read_volatile() }, + 0x8000_0008 + ); + // SAFETY: same bounded exclusively owned RAM words, no live references. + assert_eq!( + unsafe { window.direct_dword(6).unwrap().as_ptr().read_volatile() }, + 1 + ); + // All accesses have stopped. A borrowed view still prevents retirement; + // no platform unmap occurs until that exact lease is released. + // SAFETY: model accesses drained; this attempt must refuse as Busy. + assert_eq!( + unsafe { bars.retire() }, + Err(Error::Mapping(MmioError::Busy)) + ); + assert_eq!(drops.load(Ordering::Relaxed), 0); + drop(window); + // SAFETY: no view/pointer users remain and the same exact model owner is + // retained through the acknowledged canonical retirement retry. + unsafe { bars.retire() }.unwrap(); + drop(bars); + assert_eq!(drops.load(Ordering::Relaxed), 1); + println!( + "AMD VRAM Rust/C: same canonical window lease, atomic preflight and original low-register binding; CPU RAM only" + ); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/vram_mm.c b/crates/stela-drivers/src/gpu/amd/tests/vram_mm.c new file mode 100644 index 0000000000..4e22f1f96d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/vram_mm.c @@ -0,0 +1,185 @@ +/* SPDX-License-Identifier: MIT */ +/* Original frozen driver versus actual retained wrapper/shared core. Explicit + * CPU register/lifetime model only; no real VRAM, guard, PCI or MMIO provider. */ +#ifdef NDEBUG +#error "VRAM MM protocol tests require active assertions" +#endif +#include "../stela/vram_mm.h" +#include "vram_mm_test_io.h" +#include "../include/asic_reg/bif/bif_4_1_d.h" +#include "../amdgpu/amdgpu_mm_access_core.h" +#include +#include +#include +#include + +_Static_assert(sizeof(enum stela_amd_vram_mm_status) == 4, "native status ABI"); +_Static_assert(sizeof(size_t) == 8 && sizeof(void *) == 8, "native x86-64 ABI"); +static unsigned native_reads, native_writes; +uint32_t stela_amd_test_io_read(volatile uint32_t *pointer) +{ + native_reads++; return *pointer; +} +void stela_amd_test_io_write(volatile uint32_t *pointer, uint32_t value) +{ + native_writes++; *pointer=value; +} +struct event { uint32_t reg, value; bool write; }; +struct model { + uint32_t low, high; + struct event events[512]; + unsigned count, enter, exit, lock, unlock, diagnostics; + bool available; +}; +struct amdgpu_device { struct model *model; int mmio_idx_lock; }; +typedef int64_t loff_t; +static uint32_t pattern(uint64_t position) +{ + return (uint32_t)(position * UINT64_C(0x9e3779b97f4a7c15) ^ (position >> 32)) ^ 0x56abc012u; +} +static void record(struct model *m, uint32_t reg, uint32_t value, bool write) +{ + assert(m->lock == m->unlock+1 && m->count < 512); + m->events[m->count++] = (struct event){reg,value,write}; +} +static uint32_t model_read(struct model *m, uint32_t reg) +{ + assert(reg == mmMM_DATA); + uint64_t position = ((uint64_t)m->high << 31) | (m->low & 0x7fffffffu); + uint32_t value = pattern(position); + record(m,reg,value,false); return value; +} +static void model_write(struct model *m, uint32_t reg, uint32_t value) +{ + assert(reg == mmMM_INDEX || reg == mmMM_INDEX_HI || reg == mmMM_DATA); + record(m,reg,value,true); + if (reg == mmMM_INDEX) m->low = value; + if (reg == mmMM_INDEX_HI) m->high = value; +} +static bool enter(struct amdgpu_device *adev, int *index) +{ + adev->model->enter++; *index=0; return adev->model->available; +} +static struct model *active; +#define adev_to_drm(adev) (adev) +#define drm_dev_enter(adev, index) enter(adev,index) +#define drm_dev_exit(index) ((void)(index), active->exit++) +#define spin_lock_irqsave(lockptr, flags) ((void)(lockptr), (flags)=0, active->lock++) +#define spin_unlock_irqrestore(lockptr, flags) ((void)(lockptr), (void)(flags), active->unlock++) +#define IS_ALIGNED(value, alignment) (!((value) & ((alignment)-1))) +#define dev_err(...) ((void)active->diagnostics++) +#define WREG32_NO_KIQ(reg, value) model_write(adev->model,reg,value) +#define RREG32_NO_KIQ(reg) model_read(adev->model,reg) +#define amdgpu_device_mm_access frozen_mm_access +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wsign-compare" +#include "vram_mm_reference.h" +#pragma GCC diagnostic pop +#undef amdgpu_device_mm_access +/* Generated mechanically by the original Make recipe from the current actual + * Linux wrapper, including its real callback and service-call ordering. */ +#include "vram-mm-wrapper.inc" + +static void compare(const struct model *a, const struct model *b) +{ + assert(a->low==b->low && a->high==b->high && a->count==b->count); + assert(a->enter==b->enter && a->exit==b->exit && a->lock==b->lock && + a->unlock==b->unlock && a->diagnostics==b->diagnostics); + for (unsigned i=0; icount; i++) { + assert(a->events[i].reg==b->events[i].reg && + a->events[i].value==b->events[i].value && a->events[i].write==b->events[i].write); + } +} +static void traces(void) +{ + const uint64_t positions[] = {0,4,28,0x7ffffff8,0x80000000,0xfffffffc, + 0x100000000,0x17ffffff8,UINT64_C(0x123456787ffffff8), + UINT64_C(0x7fffffff7ffffffc),INT64_MAX-3}; + const size_t sizes[] = {0,4,8,12,64,128}; + unsigned cases=0; + for (unsigned a=0; a (uint64_t)INT64_MAX-positions[a]) continue; + for (unsigned write=0; write<2; write++) { + uint32_t before[32], after[32]; + for (unsigned i=0; i<32; i++) before[i]=after[i]=0x12345000u+i; + struct model old={.available=true,.high=0xdeadbeef}, fresh=old; + struct amdgpu_device original={&old,0}, current={&fresh,0}; + active=&old; frozen_mm_access(&original,(loff_t)positions[a],before,sizes[b],write!=0); + active=&fresh; amdgpu_device_mm_access(¤t,(loff_t)positions[a],after,sizes[b],write!=0); + compare(&old,&fresh); assert(!memcmp(before,after,sizeof(before))); + if (!write) for (size_t i=0; idev, "unaligned pos/size (pos=0x%llx, size=0x%zx)\n", + pos, size); + drm_dev_exit(idx); + return; + } + + spin_lock_irqsave(&adev->mmio_idx_lock, flags); + for (last = pos + size; pos < last; pos += 4) { + tmp = pos >> 31; + + WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)pos) | 0x80000000); + if (tmp != hi) { + WREG32_NO_KIQ(mmMM_INDEX_HI, tmp); + hi = tmp; + } + if (write) + WREG32_NO_KIQ(mmMM_DATA, *data++); + else + *data++ = RREG32_NO_KIQ(mmMM_DATA); + } + + spin_unlock_irqrestore(&adev->mmio_idx_lock, flags); + drm_dev_exit(idx); +} diff --git a/crates/stela-drivers/src/gpu/amd/tests/vram_mm_test_io.h b/crates/stela-drivers/src/gpu/amd/tests/vram_mm_test_io.h new file mode 100644 index 0000000000..bb2b8f4f4d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/tests/vram_mm_test_io.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: MIT */ +/* Test-object-only I/O instrumentation. No shipping source/provider hook. */ +#ifndef STELA_AMD_VRAM_MM_TEST_IO_H +#define STELA_AMD_VRAM_MM_TEST_IO_H +#include "../stela/vram_mm.h" +uint32_t stela_amd_test_io_read(volatile uint32_t *); +void stela_amd_test_io_write(volatile uint32_t *, uint32_t); +enum stela_amd_vram_mm_status +stela_amd_vram_mm_test_read(void *, size_t, uint64_t, uint64_t, uint32_t *, size_t); +#endif diff --git a/crates/stela-drivers/src/gpu/amd/vram.rs b/crates/stela-drivers/src/gpu/amd/vram.rs new file mode 100644 index 0000000000..0c0ceb5b3d --- /dev/null +++ b/crates/stela-drivers/src/gpu/amd/vram.rs @@ -0,0 +1,73 @@ +//! Native x86-64 MM-index VRAM reads through the canonical register lease. +//! No mapping, allocator, IRQ/reset guard, TMR ownership or GPU READY is created. +use super::native_mmio::{Error as WindowError, RegisterWindow}; +use core::ffi::{c_int, c_void}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Window(WindowError), + InvalidRange, + /// Numeric preflight failed before any register or destination effect. + Preflight(c_int), +} + +unsafe extern "C" { + fn stela_amd_vram_mm_read( + registers: *mut c_void, + register_bytes: usize, + vram_bytes: u64, + position: u64, + data: *mut u32, + size: usize, + ) -> c_int; +} + +/// Read through the exact original synchronous NO_KIQ MM-index protocol. +/// Success means the original void CPU transaction loop returned, not that a +/// device acknowledged the read or that the bytes satisfy discovery integrity. +/// The retained window is borrowed throughout; nothing allocates or escapes. +/// +/// # Safety +/// The caller holds the genuine same-device D0/bridge, reset/removal and +/// MM-index/IRQ exclusion for the WHOLE call, including every other firmware, +/// driver and C window user. Execution is on the owner's allowed native CPU and +/// process context. The canonical window must be UC with original ordered +/// MMIO32 semantics; these three original low direct registers must be valid on +/// the actual matched device. This does not permit bypassing indirect PCIe, +/// KIQ, RLCG or XCC routing elsewhere. `vram_bytes` is actual accessible GPU VRAM +/// in this epoch, not domain IOVA/host RAM or a guessed capacity. The caller +/// owns/excludes writes to the requested VRAM region (including actual TMR +/// reservation when reading discovery). Output is distinct exclusive CPU RAM. +/// Unexpected access faults require the platform's real fail-stop/retention +/// policy; neither this call nor Drop invents rollback after index writes. +pub unsafe fn read( + window: &RegisterWindow<'_>, + vram_bytes: u64, + position: u64, + output: &mut [u32], +) -> Result<(), Error> { + let size = output + .len() + .checked_mul(size_of::()) + .ok_or(Error::InvalidRange)?; + // SAFETY: the same borrowed retained lease and all genuine owner conditions + // are required by this unsafe API; the pointer never escapes this call. + let registers = unsafe { window.native_base() }.map_err(Error::Window)?; + // SAFETY: exclusive slice and same live canonical window, original C width + // and ABI; native code checks all numeric bounds before any register effect. + let status = unsafe { + stela_amd_vram_mm_read( + registers.as_ptr().cast(), + window.bytes(), + vram_bytes, + position, + output.as_mut_ptr(), + size, + ) + }; + if status == 0 { + Ok(()) + } else { + Err(Error::Preflight(status)) + } +} diff --git a/crates/stela-drivers/src/gpu/common/linux/include/drm/amd_asic_type.h b/crates/stela-drivers/src/gpu/common/linux/include/drm/amd_asic_type.h index 9be85b821a..a82b0acc06 100644 --- a/crates/stela-drivers/src/gpu/common/linux/include/drm/amd_asic_type.h +++ b/crates/stela-drivers/src/gpu/common/linux/include/drm/amd_asic_type.h @@ -23,7 +23,11 @@ #ifndef __AMD_ASIC_TYPE_H__ #define __AMD_ASIC_TYPE_H__ +#ifdef __KERNEL__ #include +#else +#include +#endif /* * Supported ASIC types @@ -73,7 +77,11 @@ extern const char *amdgpu_asic_name[]; struct amdgpu_asic_type_quirk { unsigned short device; /* PCI device ID */ +#ifdef __KERNEL__ u8 revision; /* revision ID */ +#else + uint8_t revision; /* revision ID */ +#endif unsigned short type; /* real ASIC type */ }; #endif /*__AMD_ASIC_TYPE_H__ */ diff --git a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree.h b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree.h index 48acdc3889..2ea2468f11 100644 --- a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree.h +++ b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree.h @@ -23,7 +23,7 @@ #include #include -#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~3)) +#define rb_parent(r) ((struct rb_node *)((r)->__rb_parent_color & ~(rb_parent_word_t)3)) #define rb_entry(ptr, type, member) container_of(ptr, type, member) @@ -31,9 +31,9 @@ /* 'empty' nodes are nodes that are known not to be inserted in an rbtree */ #define RB_EMPTY_NODE(node) \ - ((node)->__rb_parent_color == (unsigned long)(node)) + ((node)->__rb_parent_color == (rb_parent_word_t)(node)) #define RB_CLEAR_NODE(node) \ - ((node)->__rb_parent_color = (unsigned long)(node)) + ((node)->__rb_parent_color = (rb_parent_word_t)(node)) #define RB_EMPTY_LINKED_NODE(lnode) RB_EMPTY_NODE(&(lnode)->node) #define RB_CLEAR_LINKED_NODE(lnode) ({ \ @@ -92,7 +92,7 @@ extern void rb_replace_node_rcu(struct rb_node *victim, struct rb_node *new, static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) { - node->__rb_parent_color = (unsigned long)parent; + node->__rb_parent_color = (rb_parent_word_t)parent; node->rb_left = node->rb_right = NULL; *rb_link = node; @@ -101,7 +101,7 @@ static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, static inline void rb_link_node_rcu(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) { - node->__rb_parent_color = (unsigned long)parent; + node->__rb_parent_color = (rb_parent_word_t)parent; node->rb_left = node->rb_right = NULL; rcu_assign_pointer(*rb_link, node); diff --git a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_augmented.h b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_augmented.h index 6dbc5a1bf6..35266d7662 100644 --- a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_augmented.h +++ b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_augmented.h @@ -171,7 +171,7 @@ RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME, \ #define RB_RED 0 #define RB_BLACK 1 -#define __rb_parent(pc) ((struct rb_node *)(pc & ~3)) +#define __rb_parent(pc) ((struct rb_node *)(pc & ~(rb_parent_word_t)3)) #define __rb_color(pc) ((pc) & 1) #define __rb_is_black(pc) __rb_color(pc) @@ -182,13 +182,13 @@ RB_DECLARE_CALLBACKS(RBSTATIC, RBNAME, \ static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p) { - rb->__rb_parent_color = rb_color(rb) + (unsigned long)p; + rb->__rb_parent_color = rb_color(rb) + (rb_parent_word_t)p; } static inline void rb_set_parent_color(struct rb_node *rb, struct rb_node *p, int color) { - rb->__rb_parent_color = (unsigned long)p + color; + rb->__rb_parent_color = (rb_parent_word_t)p + color; } static inline void @@ -227,7 +227,7 @@ __rb_erase_augmented(struct rb_node *node, struct rb_root *root, struct rb_node *child = node->rb_right; struct rb_node *tmp = node->rb_left; struct rb_node *parent, *rebalance; - unsigned long pc; + rb_parent_word_t pc; if (!tmp) { /* diff --git a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_types.h b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_types.h index 3c7ae53e81..d7cb0fafee 100644 --- a/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_types.h +++ b/crates/stela-drivers/src/gpu/common/linux/include/linux/rbtree_types.h @@ -2,11 +2,18 @@ #ifndef _LINUX_RBTREE_TYPES_H #define _LINUX_RBTREE_TYPES_H +/* Native LLP64 targets must retain every pointer bit in the tagged word. */ +#ifdef STELA_NATIVE +typedef __UINTPTR_TYPE__ rb_parent_word_t; +#else +typedef unsigned long rb_parent_word_t; +#endif + struct rb_node { - unsigned long __rb_parent_color; + rb_parent_word_t __rb_parent_color; struct rb_node *rb_right; struct rb_node *rb_left; -} __attribute__((aligned(sizeof(long)))); +} __attribute__((aligned(sizeof(rb_parent_word_t)))); /* The alignment might seem pointless, but allegedly CRIS needs it */ struct rb_node_linked { diff --git a/crates/stela-drivers/src/gpu/common/mesa/meson.options b/crates/stela-drivers/src/gpu/common/mesa/meson.options index fe6bda9636..c61b031529 100644 --- a/crates/stela-drivers/src/gpu/common/mesa/meson.options +++ b/crates/stela-drivers/src/gpu/common/mesa/meson.options @@ -934,3 +934,9 @@ option( value : false, description : 'Build the retained AMD LLVM backend for Stela compiler targets (requires matching LLVM 23 development files)', ) +option( + 'stela-metal-input-library', + type : 'string', + value : '', + description : 'Matching hosted Rust input static library for the optional Darwin Metal library assembler', +) diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.c b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.c new file mode 100644 index 0000000000..2b43ccc1c2 --- /dev/null +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.c @@ -0,0 +1,727 @@ +/* SPDX-License-Identifier: MIT */ +#define STELA_AIR_METADATA_INTERNAL +#include "air_metadata.h" +#include "llvm-c/Analysis.h" +#include "llvm-c/BitReader.h" +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define MIN2(a,b) ((a) < (b) ? (a) : (b)) +static bool +fail(struct stela_air_metadata *t, enum stela_air_error_kind kind, const char *fmt, ...) +{ + if (t->error->kind == STELA_AIR_OK) { + t->error->kind = kind; + va_list args; + va_start(args, fmt); + vsnprintf(t->error->detail, sizeof(t->error->detail), fmt, args); + va_end(args); + } + return false; +} + +bool +stela_air_md_string(LLVMValueRef value, const char *expected) +{ + if (!value || !LLVMIsAMDString(value)) + return false; + unsigned length; + const char *string = LLVMGetMDString(value, &length); + return length == strlen(expected) && !memcmp(string, expected, length); +} + +bool +stela_air_md_uint(LLVMValueRef value, unsigned *number) +{ + if (!value || !LLVMIsAConstantInt(value) || + LLVMGetIntTypeWidth(LLVMTypeOf(value)) > 32) + return false; + *number = LLVMConstIntGetZExtValue(value); + return true; +} + +bool +stela_air_md_node(struct stela_air_metadata *t, LLVMValueRef node, LLVMValueRef *operands, + unsigned *count) +{ + if (!node || !LLVMIsAMDNode(node)) + return fail(t, STELA_AIR_METADATA, "expected AIR metadata node"); + *count = LLVMGetMDNodeNumOperands(node); + if (*count > AIR_MAX_METADATA_OPERANDS) + return fail(t, STELA_AIR_LIMIT, "AIR metadata operand budget exceeded"); + LLVMGetMDNodeOperands(node, operands); + return true; +} + +bool +stela_air_named_md(struct stela_air_metadata *t, const char *name, LLVMValueRef *operands, + unsigned *count) +{ + *count = LLVMGetNamedMetadataNumOperands(t->module, name); + if (*count > AIR_MAX_METADATA_OPERANDS) + return fail(t, STELA_AIR_LIMIT, "%s metadata budget exceeded", name); + LLVMGetNamedMetadataOperands(t->module, name, operands); + return true; +} + +bool +stela_air_metadata_shared_profile(struct stela_air_metadata *t) +{ + LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS], fields[AIR_MAX_METADATA_OPERANDS]; + unsigned count, fields_count; + if (t->air_minor != 9 || t->language_major != 4 || t->language_minor != 1 || + strcmp(LLVMGetTarget(t->module), "air64_v29-apple-macosx27.2.0") || + !stela_air_named_md(t, "llvm.ident", nodes, &count) || count != 1 || + !stela_air_md_node(t, nodes[0], fields, &fields_count) || fields_count != 1 || + !stela_air_md_string(fields[0], "Apple metal version 32023.922 (metalfe-32023.922.4)")) + return fail(t, STELA_AIR_METADATA, "shared-memory AIR/compiler profile is unqualified"); + if (LLVMPointerSizeForAS(t->layout, 3) != 8) + return fail(t, STELA_AIR_TARGET, "shared-memory AIR pointers require 64-bit layout"); + return true; +} + +static bool +shared_storage_size(struct stela_air_metadata *t, LLVMTypeRef type, unsigned depth, + uint64_t *size) +{ + if (depth == 32) + return fail(t, STELA_AIR_LIMIT, "shared storage type nesting exceeded"); + if (LLVMGetTypeKind(type) == LLVMArrayTypeKind) { + uint64_t element; + if (!shared_storage_size(t, LLVMGetElementType(type), depth + 1, &element)) + return false; + uint64_t length = LLVMGetArrayLength2(type); + if (!length || length > UINT32_MAX / element) + return fail(t, STELA_AIR_LIMIT, "shared storage array extent exceeded"); + } else { + LLVMTypeRef scalar = type; + if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) { + unsigned components = LLVMGetVectorSize(type); + if (components < 2 || components > 4) + return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays"); + scalar = LLVMGetElementType(type); + } + bool valid = LLVMGetTypeKind(scalar) == LLVMFloatTypeKind; + if (LLVMGetTypeKind(scalar) == LLVMIntegerTypeKind) { + unsigned bits = LLVMGetIntTypeWidth(scalar); + valid = bits == 8 || bits == 16 || bits == 32 || bits == 64; + } + if (!valid) + return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays"); + } + /* Aggregate extents were bounded before invoking fixed-size LLVM queries. */ + *size = LLVMABISizeOfType(t->layout, type); + return (*size && *size <= UINT32_MAX) || + fail(t, STELA_AIR_LIMIT, "shared storage allocation size exceeded"); +} + +bool +stela_air_metadata_shared_global(struct stela_air_metadata *t, LLVMValueRef global, + uint64_t *size, unsigned *alignment) +{ + const char *section = LLVMGetSection(global); + LLVMValueRef initializer = LLVMGetInitializer(global); + if (LLVMGetPointerAddressSpace(LLVMTypeOf(global)) != 3 || + LLVMGetLinkage(global) != LLVMInternalLinkage || LLVMIsThreadLocal(global) || + LLVMIsGlobalConstant(global) || LLVMIsExternallyInitialized(global) || + (section && *section) || !initializer || !LLVMIsUndef(initializer) || LLVMIsPoison(initializer)) + return fail(t, STELA_AIR_TARGET, "unsupported global/shared initializer or storage ABI"); + size_t metadata_count; + LLVMValueMetadataEntry *metadata = LLVMGlobalCopyAllMetadata(global, &metadata_count); + LLVMDisposeValueMetadataEntries(metadata); + if (metadata_count) + return fail(t, STELA_AIR_TARGET, "unsupported shared global metadata"); + LLVMTypeRef type = LLVMGlobalGetValueType(global); + if (!shared_storage_size(t, type, 0, size)) + return false; + *alignment = LLVMGetAlignment(global); + if (!*alignment) + *alignment = LLVMABIAlignmentOfType(t->layout, type); + return (*alignment && !(*alignment & (*alignment - 1))) || + fail(t, STELA_AIR_TYPE, "unsupported shared global alignment"); +} + +bool +stela_air_metadata_shared_globals(struct stela_air_metadata *t) +{ + unsigned count = 0; + for (LLVMValueRef global = LLVMGetFirstGlobal(t->module); global; + global = LLVMGetNextGlobal(global)) { + uint64_t size; + unsigned alignment; + if (++count > AIR_MAX_ARGUMENTS) + return fail(t, STELA_AIR_LIMIT, "shared global count exceeded"); + if (!stela_air_metadata_shared_global(t, global, &size, &alignment)) + return false; + } + return true; +} + +static bool +version_metadata(struct stela_air_metadata *t, const char *name, bool language) +{ + LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned count, fields_count, major, minor, patch; + if (!stela_air_named_md(t, name, nodes, &count) || count != 1 || + !stela_air_md_node(t, nodes[0], fields, &fields_count)) + return fail(t, STELA_AIR_METADATA, "missing or invalid %s", name); + unsigned base = language ? 1 : 0; + if (fields_count != base + 3 || (language && !stela_air_md_string(fields[0], "Metal")) || + !stela_air_md_uint(fields[base], &major) || !stela_air_md_uint(fields[base + 1], &minor) || + !stela_air_md_uint(fields[base + 2], &patch) || patch != 0) + return fail(t, STELA_AIR_METADATA, "invalid %s", name); + bool supported = language ? + ((major == 1 && minor >= 1 && minor <= 2) || + (major == 2 && minor <= 4) || (major == 3 && minor <= 2) || + (major == 4 && minor <= 1)) : (major == 2 && (minor == 8 || minor == 9)); + /* AIR 2.8 has only been observed with Metal 4.0 here. The AIR 2.9 + * combinations below come from actual independent compiler requests. */ + if (language && t->air_minor == 8) + supported &= major == 4 && minor == 0; + if (!supported) + return fail(t, STELA_AIR_METADATA, "unsupported %s %u.%u.%u", name, major, minor, patch); + if (!language) + t->air_minor = minor; + else { + t->language_major = major; + t->language_minor = minor; + } + return true; +} + +static bool +module_flags(struct stela_air_metadata *t) +{ + /* These are the LLVM IR serialized behavior values, not the smaller C API + * LLVMModuleFlagBehavior enum (which does not expose Max in LLVM 23). */ + enum { IR_FLAG_ERROR = 1, IR_FLAG_MAX = 7 }; + const char *keys[] = {"wchar_size", "frame-pointer", "air.max_device_buffers", + "air.max_constant_buffers", "air.max_threadgroup_buffers", "air.max_textures", + "air.max_read_write_textures", "air.max_samplers"}; + LLVMValueRef flags[AIR_MAX_METADATA_OPERANDS]; + unsigned count, seen = 0; + if (!stela_air_named_md(t, "llvm.module.flags", flags, &count)) + return false; + for (unsigned i = 0; i < count; i++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned field_count, behavior, value, key; + if (!stela_air_md_node(t, flags[i], fields, &field_count) || field_count != 3 || + !stela_air_md_uint(fields[0], &behavior) || !stela_air_md_uint(fields[2], &value)) + return fail(t, STELA_AIR_METADATA, "unsupported module flag shape"); + for (key = 0; key < ARRAY_SIZE(keys); key++) { + if (stela_air_md_string(fields[1], keys[key])) + break; + } + if (key == ARRAY_SIZE(keys) || (seen & (1u << key))) + return fail(t, STELA_AIR_METADATA, "unsupported/duplicate module flag"); + seen |= 1u << key; + if (behavior != (key == 0 ? IR_FLAG_ERROR : IR_FLAG_MAX) || + (key == 0 && value != 4) || (key == 1 && value > 2) || + (key >= 2 && !value)) + return fail(t, STELA_AIR_METADATA, "unsupported module flag value: %s", keys[key]); + if (key == 2) + t->max_device_buffers = value; + if (key == 4) + t->max_threadgroup_buffers = value; + } + /* No linking, CPU frame operations or source wchar operations occur in the + * implemented compute subset. Other resource kinds remain refused. + * Device/threadgroup location bounds are enforced below, never advertised as the + * hardware's actual Metal capability or silently removed from the input. */ + return true; +} + +bool +stela_air_metadata_validate(struct stela_air_metadata *t) +{ + for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node; + node = LLVMGetNextNamedMetadata(node)) { + size_t size; + const char *name = LLVMGetNamedMetadataName(node, &size); + const char *allowed[] = {"air.version", "air.language_version", + "air.compile_options", "air.kernel", "llvm.ident", + "llvm.module.flags"}; + bool found = false; + for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++) + found |= size == strlen(allowed[i]) && !memcmp(name, allowed[i], size); + if (!found) + return fail(t, STELA_AIR_METADATA, "unsupported module metadata: %.*s", + (int)MIN2(size, 160), name); + } + if (!version_metadata(t, "air.version", false) || + !version_metadata(t, "air.language_version", true) || !module_flags(t)) + return false; + LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; + unsigned count; + if (!stela_air_named_md(t, "air.compile_options", nodes, &count)) + return false; + unsigned seen = 0; + for (unsigned i = 0; i < count; i++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned fields_count; + if (!stela_air_md_node(t, nodes[i], fields, &fields_count) || fields_count != 1 || + !(stela_air_md_string(fields[0], "air.compile.denorms_disable") || + stela_air_md_string(fields[0], "air.compile.fast_math_enable") || + stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_enable") || + stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_disable"))) + return fail(t, STELA_AIR_METADATA, "unsupported AIR compile option"); + unsigned bit = stela_air_md_string(fields[0], "air.compile.denorms_disable") ? 1 : + stela_air_md_string(fields[0], "air.compile.fast_math_enable") ? 2 : 4; + if (seen & bit) + return fail(t, STELA_AIR_METADATA, "duplicate/conflicting AIR compile option"); + seen |= bit; + } + t->denorms_disable = seen & 1; + t->fast_math = seen & 2; + /* Arithmetic requires an explicit qualified FP policy for this private AIR + * option. Exact storage/shared access and integer operations do not depend + * on FP denorm mode. */ + return true; +} + +bool +stela_air_metadata_layout(struct stela_air_metadata *t) +{ + t->layout = LLVMGetModuleDataLayout(t->module); + const char *layout = LLVMGetDataLayoutStr(t->module); + if (!layout || !*layout || LLVMByteOrder(t->layout) != LLVMLittleEndian || + LLVMPointerSizeForAS(t->layout, 0) != 8 || LLVMPointerSizeForAS(t->layout, 1) != 8) + return fail(t, STELA_AIR_TARGET, "requires explicit little-endian 64-bit AIR layout"); + /* LLVM's C DataLayout API does not expose pointer-index width. Validate only + * that property here; actual allocation sizes/field offsets come from LLVM. + * Nonintegral/external-state pointers need a different NIR representation. */ + for (const char *part = layout; *part;) { + const char *end = strchr(part, '-'); + size_t length = end ? (size_t)(end - part) : strlen(part); + if ((length > 3 && !memcmp(part, "ni:", 3)) || (length && *part == 'P')) + return fail(t, STELA_AIR_TARGET, "unsupported nonintegral/program address-space layout"); + if (length && *part == 'p') { + unsigned colons = 0; + const char *last = NULL; + for (size_t i = 0; i < length; i++) { + if (part[i] == ':') { + colons++; + last = part + i + 1; + } + } + if (colons > 4 || (colons == 4 && + ((size_t)(part + length - last) != 2 || memcmp(last, "64", 2)))) + return fail(t, STELA_AIR_TARGET, "unsupported pointer-index width"); + } + part += length; + if (*part) + part++; + } + return true; +} + +/* This is only a conservative public-reflection classification. Unknown/struct + * types are NOT inferred to lack argument buffers. It changes no NIR admission. + * MSL argument buffers require structures; builtin scalar/vector buffer elements + * cannot describe such a structure. Exact IR/layout validation remains separate. */ +static enum stela_air_primitive +primitive_type(LLVMValueRef name, unsigned *components) +{ + const char *scalar[] = {"char", "uchar", "short", "ushort", "int", "uint", "long", "ulong", "float"}; + for (unsigned i = 0; i < ARRAY_SIZE(scalar); i++) { + for (unsigned n = 1; n <= 4; n++) { + char type[16]; + if (n == 1) + snprintf(type, sizeof(type), "%s", scalar[i]); + else + snprintf(type, sizeof(type), "%s%u", scalar[i], n); + if (stela_air_md_string(name, type)) { + *components = n; + return STELA_AIR_CHAR + i; + } + } + } + *components = 0; + return STELA_AIR_PRIMITIVE_UNKNOWN; +} + +/* This is reflection admission, not a change to executable/NIR admission. + * Reject unknown function metadata/string attributes and unqualified globals + * instead of claiming absent annotations/constants/static-resource reflection. + * The known internal undef AS3 storage ABI does not add a function argument; + * actual selected-entry allocation remains the original NIR compiler's work. The + * accepted strings are standard LLVM code-generation/FP attributes observed in + * the retained original AIR, not arbitrary app or compiler-name exceptions. */ +static bool +complete_reflection(struct stela_air_metadata *m, LLVMValueRef fn, + const struct stela_air_kernel *kernel) +{ + if (LLVMGetFirstGlobal(m->module)) { + /* Reflection incompleteness is observational, not an inspection failure. + * Keep executable/profile diagnostics local to this conservative query. */ + struct stela_air_error observed_error = {0}; + struct stela_air_metadata observed = *m; + observed.error = &observed_error; + if (!stela_air_metadata_shared_profile(&observed) || + !stela_air_metadata_shared_globals(&observed)) + return false; + } + size_t metadata_count; + LLVMValueMetadataEntry *metadata = LLVMGlobalCopyAllMetadata(fn, &metadata_count); + LLVMDisposeValueMetadataEntries(metadata); + if (metadata_count) + return false; + unsigned count = LLVMGetAttributeCountAtIndex(fn, LLVMAttributeFunctionIndex); + if (count > AIR_MAX_METADATA_OPERANDS) + return false; + LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS]; + LLVMGetAttributesAtIndex(fn, LLVMAttributeFunctionIndex, attributes); + const char *allowed[] = {"approx-func-fp-math", "frame-pointer", "min-legal-vector-width", + "no-builtins", "no-infs-fp-math", "no-nans-fp-math", "no-signed-zeros-fp-math", + "no-trapping-math", "stack-protector-buffer-size", "unsafe-fp-math"}; + for (unsigned a = 0; a < count; a++) { + if (!LLVMIsStringAttribute(attributes[a])) + continue; + unsigned bytes; + const char *key = LLVMGetStringAttributeKind(attributes[a], &bytes); + bool found = false; + for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++) + found |= bytes == strlen(allowed[i]) && !memcmp(key, allowed[i], bytes); + if (!found) + return false; + } + for (unsigned a = 0; a < kernel->count; a++) { + const struct stela_air_argument *arg = &kernel->arguments[a]; + if (!arg->is_buffer) + continue; + if (!arg->plain_buffer_type || !arg->name_bytes || arg->name_bytes > 4096 || + memchr(arg->name, 0, arg->name_bytes)) + return false; + unsigned scalar = arg->primitive <= STELA_AIR_UCHAR ? 1 : + arg->primitive <= STELA_AIR_USHORT ? 2 : + arg->primitive == STELA_AIR_LONG || arg->primitive == STELA_AIR_ULONG ? 8 : 4; + unsigned extent = scalar * (arg->type_components == 3 ? 4 : arg->type_components); + if (arg->buffer.type_size != extent || arg->buffer.type_alignment != extent) + return false; + /* Unknown parameter string attributes could carry unimplemented source + * reflection; only the observed AIR alias contract is recognized here. */ + count = LLVMGetAttributeCountAtIndex(fn, arg->buffer.argument + 1); + if (count > AIR_MAX_METADATA_OPERANDS) + return false; + LLVMGetAttributesAtIndex(fn, arg->buffer.argument + 1, attributes); + for (unsigned i = 0; i < count; i++) { + if (!LLVMIsStringAttribute(attributes[i])) + continue; + unsigned bytes; + const char *key = LLVMGetStringAttributeKind(attributes[i], &bytes); + if (bytes != strlen("air-buffer-no-alias") || memcmp(key, "air-buffer-no-alias", bytes)) + return false; + } + } + return true; +} + +bool +stela_air_metadata_kernel(struct stela_air_metadata *t, LLVMValueRef fn, + struct stela_air_kernel *kernel) +{ + if (!fn || LLVMIsDeclaration(fn) || LLVMGetFunctionCallConv(fn) != LLVMCCallConv || + LLVMGetTypeKind(LLVMGetReturnType(LLVMGlobalGetValueType(fn))) != LLVMVoidTypeKind || + LLVMIsFunctionVarArg(LLVMGlobalGetValueType(fn))) + return fail(t, STELA_AIR_ARGUMENT, "entry must be a defined nonvariadic void C-convention kernel"); + LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS], args_node = NULL; + unsigned kernel_count; + if (!stela_air_named_md(t, "air.kernel", kernels, &kernel_count)) + return false; + for (unsigned i = 0; i < kernel_count; i++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned count; + if (!stela_air_md_node(t, kernels[i], fields, &count) || count != 3) + return fail(t, STELA_AIR_METADATA, "invalid air.kernel descriptor"); + if (fields[0] == fn) { + LLVMValueRef outputs[AIR_MAX_METADATA_OPERANDS]; + unsigned output_count; + if (args_node || !stela_air_md_node(t, fields[1], outputs, &output_count) || output_count) + return fail(t, STELA_AIR_METADATA, "duplicate kernel or nonempty compute outputs"); + args_node = fields[2]; + } + } + if (!args_node) + return fail(t, STELA_AIR_METADATA, "entry is not an AIR compute kernel"); + unsigned argc = LLVMCountParams(fn); + if (argc > AIR_MAX_ARGUMENTS) + return fail(t, STELA_AIR_LIMIT, "AIR argument budget exceeded"); + LLVMValueRef args[AIR_MAX_METADATA_OPERANDS]; + unsigned count; + if (!stela_air_md_node(t, args_node, args, &count) || count != argc) + return fail(t, STELA_AIR_METADATA, "AIR argument descriptors do not match parameters"); + bool used[AIR_MAX_ARGUMENTS] = {false}; + bool buffer_indices[AIR_MAX_ARGUMENTS] = {false}; + bool shared_indices[AIR_MAX_ARGUMENTS] = {false}; + for (unsigned a = 0; a < argc; a++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned fields_count, index; + if (!stela_air_md_node(t, args[a], fields, &fields_count) || fields_count < 2 || + !stela_air_md_uint(fields[0], &index) || index >= argc || used[index]) + return fail(t, STELA_AIR_METADATA, "invalid/duplicate argument index"); + used[index] = true; + LLVMValueRef param = LLVMGetParam(fn, index); + unsigned attributes_count = LLVMGetAttributeCountAtIndex(fn, index + 1); + if (attributes_count > AIR_MAX_METADATA_OPERANDS) + return fail(t, STELA_AIR_LIMIT, "argument attribute budget exceeded"); + LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS]; + LLVMGetAttributesAtIndex(fn, index + 1, attributes); + const char *abi_attributes[] = {"sret", "byval", "byref", "inalloca", + "preallocated", "nest", "swiftself", "swifterror", "elementtype"}; + for (unsigned attribute = 0; attribute < attributes_count; attribute++) { + if (LLVMIsTypeAttribute(attributes[attribute])) + return fail(t, STELA_AIR_ARGUMENT, "unsupported typed parameter attribute"); + if (!LLVMIsEnumAttribute(attributes[attribute])) + continue; + unsigned kind = LLVMGetEnumAttributeKind(attributes[attribute]); + for (unsigned k = 0; k < ARRAY_SIZE(abi_attributes); k++) { + if (kind == LLVMGetEnumAttributeKindForName(abi_attributes[k], strlen(abi_attributes[k]))) + return fail(t, STELA_AIR_ARGUMENT, "unsupported parameter ABI attribute: %s", abi_attributes[k]); + } + } + bool buffer = stela_air_md_string(fields[1], "air.buffer"); + bool thread_id = stela_air_md_string(fields[1], "air.thread_position_in_grid"); + if (!buffer && !thread_id) + return fail(t, STELA_AIR_ARGUMENT, "unsupported AIR argument kind at %u", index); + struct stela_air_buffer desc = {.argument = index}; + bool has_location = false, has_as = false, has_size = false, has_align = false; + bool has_name = false, has_type_name = false; + enum stela_air_primitive primitive = STELA_AIR_PRIMITIVE_UNKNOWN; + unsigned type_components = 0; + const char *name = NULL, *type_name = NULL; + unsigned name_bytes = 0, type_name_bytes = 0; + for (unsigned f = 2; f < fields_count;) { + LLVMValueRef key = fields[f++]; + if (stela_air_md_string(key, "air.read") || stela_air_md_string(key, "air.write") || + stela_air_md_string(key, "air.read_write")) { + if (!buffer || desc.access) + return fail(t, STELA_AIR_METADATA, "duplicate/inapplicable buffer access"); + desc.access = stela_air_md_string(key, "air.read") ? STELA_AIR_READ : + stela_air_md_string(key, "air.write") ? STELA_AIR_WRITE : STELA_AIR_READ_WRITE; + } else if (stela_air_md_string(key, "air.location_index")) { + unsigned locations; + if (!buffer || has_location || f + 2 > fields_count || + !stela_air_md_uint(fields[f], &desc.index) || !stela_air_md_uint(fields[f + 1], &locations) || + locations != 1 || desc.index >= AIR_MAX_ARGUMENTS) + return fail(t, STELA_AIR_METADATA, "unsupported/duplicate buffer location"); + has_location = true; + f += 2; + } else if (stela_air_md_string(key, "air.address_space")) { + if (!buffer || has_as || f == fields_count || !stela_air_md_uint(fields[f++], &desc.address_space)) + return fail(t, STELA_AIR_METADATA, "invalid buffer address space"); + has_as = true; + } else if (stela_air_md_string(key, "air.arg_type_size") || stela_air_md_string(key, "air.arg_type_align_size")) { + bool alignment = stela_air_md_string(key, "air.arg_type_align_size"); + bool *present = alignment ? &has_align : &has_size; + unsigned *number = alignment ? &desc.type_alignment : &desc.type_size; + if (!buffer || *present || f == fields_count || !stela_air_md_uint(fields[f++], number) || + (alignment && (!*number || (*number & (*number - 1))))) + return fail(t, STELA_AIR_METADATA, "invalid argument size/alignment"); + *present = true; + } else if (stela_air_md_string(key, "air.arg_name") || stela_air_md_string(key, "air.arg_type_name")) { + bool *present = stela_air_md_string(key, "air.arg_name") ? &has_name : &has_type_name; + if (*present || f == fields_count || !fields[f] || !LLVMIsAMDString(fields[f])) + return fail(t, STELA_AIR_METADATA, "invalid argument reflection string"); + if (present == &has_type_name) { + primitive = primitive_type(fields[f], &type_components); + type_name = LLVMGetMDString(fields[f], &type_name_bytes); + } else { + name = LLVMGetMDString(fields[f], &name_bytes); + } + f++; + *present = true; + } else { + return fail(t, STELA_AIR_METADATA, "unsupported argument metadata at %u", index); + } + } + unsigned components = 0; + if (buffer) { + LLVMTypeRef type = LLVMTypeOf(param); + if (!has_location || !has_as || !desc.access || + (desc.address_space != 1 && desc.address_space != 3) || + LLVMGetTypeKind(type) != LLVMPointerTypeKind || + LLVMGetPointerAddressSpace(type) != desc.address_space) + return fail(t, STELA_AIR_ARGUMENT, "unsupported buffer %u", index); + bool shared = desc.address_space == 3; + bool *indices = shared ? shared_indices : buffer_indices; + unsigned limit = shared ? t->max_threadgroup_buffers : t->max_device_buffers; + if (indices[desc.index] || (limit && desc.index >= limit)) + return fail(t, STELA_AIR_METADATA, "duplicate buffer or location exceeds AIR module limit"); + indices[desc.index] = true; + if (shared && (!has_size || !has_align || !desc.type_size || !desc.type_alignment)) + return fail(t, STELA_AIR_ARGUMENT, "invalid/unbound threadgroup buffer %u", index); + } else { + LLVMTypeRef type = LLVMTypeOf(param); + components = 1; + if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) { + components = LLVMGetVectorSize(type); + if (components != 3) + return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position vector width"); + type = LLVMGetElementType(type); + } + if (LLVMGetTypeKind(type) != LLVMIntegerTypeKind || LLVMGetIntTypeWidth(type) != 32 || + (components != 1 && components != 3)) + return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position type"); + } + kernel->arguments[a] = (struct stela_air_argument) { + .value = param, .buffer = desc, .is_buffer = buffer, .components = components, + .plain_buffer_type = primitive != STELA_AIR_PRIMITIVE_UNKNOWN, + .name = name, .name_bytes = name_bytes, .type_name = type_name, .type_name_bytes = type_name_bytes, + .primitive = primitive, .type_components = type_components, .used = LLVMGetFirstUse(param) != NULL, + }; + } + kernel->count = argc; + return true; +} + +static void +inspection_diagnostic(LLVMDiagnosticInfoRef info, void *data) +{ + struct stela_air_metadata *m = data; + if (LLVMGetDiagInfoSeverity(info) != LLVMDSError) + return; + char *message = LLVMGetDiagInfoDescription(info); + fail(m, STELA_AIR_BITCODE, "%s", message ? message : "LLVM bitcode diagnostic"); + LLVMDisposeMessage(message); +} + +bool +stela_air_inspect(const void *bitcode, size_t size, unsigned max_entries, + stela_air_visit_entry visit, void *data, + struct stela_air_error *error) +{ + struct stela_air_error local = {0}; + if (!error) + error = &local; + *error = (struct stela_air_error){0}; + struct stela_air_metadata m = {.error = error}; + if (!bitcode || size < 4 || size > AIR_MAX_BITCODE_BYTES || + memcmp(bitcode, "BC\xc0\xde", 4) || !max_entries || + max_entries > AIR_MAX_METADATA_OPERANDS || !visit) + return fail(&m, STELA_AIR_INPUT, "invalid AIR inspection input/budget"); + unsigned major, minor, patch; + LLVMGetVersion(&major, &minor, &patch); + if (major != 23) + return fail(&m, STELA_AIR_LLVM_VERSION, "requires LLVM 23 C ABI, found %u.%u.%u", major, minor, patch); + LLVMContextRef context = LLVMContextCreate(); + if (!context) + return fail(&m, STELA_AIR_ALLOCATION, "LLVM context unavailable"); + LLVMContextSetDiagnosticHandler(context, inspection_diagnostic, &m); + LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(bitcode, size, "Metal input"); + if (!buffer) { + LLVMContextDispose(context); + return fail(&m, STELA_AIR_ALLOCATION, "LLVM buffer unavailable"); + } + bool parsed = !LLVMParseBitcodeInContext2(context, buffer, &m.module); + LLVMDisposeMemoryBuffer(buffer); + bool success = false; + struct decoded_entry { + LLVMValueRef fn; + const char *name; + size_t name_bytes; + struct stela_air_kernel kernel; + } *entries = NULL; + if (!parsed || error->kind != STELA_AIR_OK) { + fail(&m, STELA_AIR_BITCODE, "LLVM refused AIR bitcode"); + goto done; + } + char *verification = NULL; + if (LLVMVerifyModule(m.module, LLVMReturnStatusAction, &verification)) { + fail(&m, STELA_AIR_VERIFY, "%s", verification ? verification : "invalid LLVM module"); + LLVMDisposeMessage(verification); + goto done; + } + LLVMDisposeMessage(verification); + const char *target = LLVMGetTarget(m.module); + size_t assembly; + LLVMGetModuleInlineAsm(m.module, &assembly); + if (strncmp(target, "air64_v", 7) || assembly || LLVMGetFirstGlobalAlias(m.module) || + LLVMGetFirstGlobalIFunc(m.module)) { + fail(&m, STELA_AIR_TARGET, "unsupported target/globals/inline assembly"); + goto done; + } + if (!stela_air_metadata_layout(&m) || !stela_air_metadata_validate(&m)) + goto done; + char prefix[40]; + snprintf(prefix, sizeof(prefix), "air64_v2%u-apple-macosx", m.air_minor); + if (strncmp(target, prefix, strlen(prefix))) { + fail(&m, STELA_AIR_TARGET, "AIR version and target triple disagree"); + goto done; + } + LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS]; + unsigned count; + if (!stela_air_named_md(&m, "air.kernel", kernels, &count)) + goto done; + if (!count || count > max_entries) { + fail(&m, STELA_AIR_LIMIT, "no executable compute entries or entry budget exceeded"); + goto done; + } + entries = calloc(count, sizeof(*entries)); + if (!entries) { + fail(&m, STELA_AIR_ALLOCATION, "entry manifest allocation failed"); + goto done; + } + /* Validate the complete manifest BEFORE the first callback. A later invalid + * entry cannot publish a partially accepted library through this interface. */ + for (unsigned i = 0; i < count; i++) { + LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; + unsigned fields_count; + if (!stela_air_md_node(&m, kernels[i], fields, &fields_count) || fields_count != 3 || + !fields[0] || !LLVMIsAFunction(fields[0])) { + fail(&m, STELA_AIR_METADATA, "invalid AIR kernel manifest entry"); + goto done; + } + entries[i].fn = fields[0]; + entries[i].name = LLVMGetValueName2(fields[0], &entries[i].name_bytes); + if (!entries[i].name_bytes || entries[i].name_bytes > 4096 || + memchr(entries[i].name, 0, entries[i].name_bytes)) { + fail(&m, STELA_AIR_METADATA, "invalid/oversized AIR entry name"); + goto done; + } + for (unsigned j = 0; j < i; j++) { + if (entries[j].fn == entries[i].fn) { + fail(&m, STELA_AIR_METADATA, "duplicate AIR kernel manifest entry"); + goto done; + } + } + if (!stela_air_metadata_kernel(&m, entries[i].fn, &entries[i].kernel)) + goto done; + } + struct stela_air_inspection info = { + .target = target, .target_bytes = strlen(target), .air_minor = m.air_minor, + .language_major = m.language_major, .language_minor = m.language_minor, + .denorms_disable = m.denorms_disable, .fast_math = m.fast_math, + }; + for (unsigned i = 0; i < count; i++) { + struct stela_air_argument_info args[AIR_MAX_ARGUMENTS]; + for (unsigned a = 0; a < entries[i].kernel.count; a++) { + const struct stela_air_argument *arg = &entries[i].kernel.arguments[a]; + args[a] = (struct stela_air_argument_info) { + .buffer = arg->buffer, .kind = arg->is_buffer ? 1 : 2, .components = arg->components, + .plain_buffer_type = arg->plain_buffer_type, + .name = arg->name, .name_bytes = arg->name_bytes, + .type_name = arg->type_name, .type_name_bytes = arg->type_name_bytes, + .primitive = arg->primitive, .type_components = arg->type_components, .used = arg->used, + }; + } + struct stela_air_entry entry = { + .name = entries[i].name, .name_bytes = entries[i].name_bytes, + .argument_count = entries[i].kernel.count, .arguments = args, + .reflection_complete = complete_reflection(&m, entries[i].fn, &entries[i].kernel), + }; + if (!visit(&info, &entry, data)) { + fail(&m, STELA_AIR_LIMIT, "AIR manifest receiver refused entry"); + goto done; + } + } + success = true; +done: + free(entries); + if (m.module) + LLVMDisposeModule(m.module); + LLVMContextDispose(context); + return success; +} diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.h b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.h new file mode 100644 index 0000000000..db41c738a4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_metadata.h @@ -0,0 +1,150 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AIR_METADATA_H +#define STELA_AIR_METADATA_H +#include +#include +#include +#ifdef __cplusplus +extern "C" { +#endif + +#define AIR_MAX_ARGUMENTS 128 +#define AIR_MAX_METADATA_OPERANDS 256 +#define AIR_MAX_BITCODE_BYTES (64u * 1024u * 1024u) + +enum stela_air_error_kind { + STELA_AIR_OK, + STELA_AIR_INPUT, + STELA_AIR_LLVM_VERSION, + STELA_AIR_BITCODE, + STELA_AIR_VERIFY, + STELA_AIR_TARGET, + STELA_AIR_METADATA, + STELA_AIR_ARGUMENT, + STELA_AIR_CONTROL_FLOW, + STELA_AIR_INSTRUCTION, + STELA_AIR_TYPE, + STELA_AIR_MEMORY, + STELA_AIR_LIMIT, + STELA_AIR_ALLOCATION, +}; + +struct stela_air_error { + enum stela_air_error_kind kind; + unsigned instruction; /* Zero-based instruction ordinal, not source line. */ + char detail[256]; +}; + +enum stela_air_buffer_access { + STELA_AIR_READ = 1, + STELA_AIR_WRITE = 2, + STELA_AIR_READ_WRITE = 3, +}; + +struct stela_air_buffer { + unsigned argument; + unsigned index; /* air.location_index; not an LLVM parameter byte offset. */ + unsigned address_space; + enum stela_air_buffer_access access; + unsigned type_size; /* Zero when the input omits this optional reflection. */ + unsigned type_alignment; +}; + + +/* Borrowed callback views expire on callback return. Inspection validates LLVM, + * module/entry ABI and metadata, not executable-body support, bindings, GPU + * capability, or compiler provenance. Only actual air.kernel entries are + * exposed; unsupported metadata/stages remain explicit. */ +struct stela_air_inspection { + const char *target; + size_t target_bytes; + unsigned air_minor, language_major, language_minor; + bool denorms_disable, fast_math; +}; +enum stela_air_primitive { + STELA_AIR_PRIMITIVE_UNKNOWN, + STELA_AIR_CHAR, STELA_AIR_UCHAR, STELA_AIR_SHORT, STELA_AIR_USHORT, + STELA_AIR_INT, STELA_AIR_UINT, STELA_AIR_LONG, STELA_AIR_ULONG, STELA_AIR_FLOAT, +}; + +struct stela_air_argument_info { + struct stela_air_buffer buffer; + unsigned kind; /* 1=buffer, 2=thread_position_in_grid. */ + unsigned components; + bool plain_buffer_type; + const char *name, *type_name; + size_t name_bytes, type_name_bytes; + enum stela_air_primitive primitive; + unsigned type_components; /* 1..4 only for known reflected builtin types. */ + bool used; /* Actual uses in this AIR module, not a final machine-code liveness claim. */ +}; +struct stela_air_entry { + const char *name; + size_t name_bytes; + unsigned argument_count; + const struct stela_air_argument_info *arguments; + bool reflection_complete; /* Bounded plain-resource reflection; see README. */ +}; +typedef bool (*stela_air_visit_entry)(const struct stela_air_inspection *, + const struct stela_air_entry *, void *); +bool stela_air_inspect(const void *bitcode, size_t size, unsigned max_entries, + stela_air_visit_entry visit, void *data, + struct stela_air_error *error); +/* Compiler implementation only. Ordinary metadata consumers need no LLVM or + * NIR headers and receive no LLVM objects. Define before the first include. */ +#ifdef STELA_AIR_METADATA_INTERNAL +#include "llvm-c/Core.h" +#include "llvm-c/Target.h" +/* Shared decoder state, borrowed from the caller's real LLVM module. No NIR, + * resource mapping or GPU/Metal object is created by metadata inspection. */ +struct stela_air_metadata { + LLVMModuleRef module; + LLVMTargetDataRef layout; + struct stela_air_error *error; + unsigned air_minor, language_major, language_minor; + unsigned max_device_buffers, max_threadgroup_buffers; + bool denorms_disable, fast_math; +}; + +bool stela_air_md_string(LLVMValueRef value, const char *expected); +bool stela_air_md_uint(LLVMValueRef value, unsigned *number); +bool stela_air_md_node(struct stela_air_metadata *m, LLVMValueRef node, + LLVMValueRef *operands, unsigned *count); +bool stela_air_named_md(struct stela_air_metadata *m, const char *name, + LLVMValueRef *operands, unsigned *count); +bool stela_air_metadata_layout(struct stela_air_metadata *m); +bool stela_air_metadata_validate(struct stela_air_metadata *m); +/* One LLVM-only storage validator shared by conservative reflection and NIR. + * These describe the qualified ABI, not compiler provenance or GPU limits. + * No shared storage is allocated here; only actually used globals are lowered + * by the selected entry's original NIR path. Errors use m->error; observational + * consumers must supply their own local error state. */ +bool stela_air_metadata_shared_profile(struct stela_air_metadata *m); +bool stela_air_metadata_shared_global(struct stela_air_metadata *m, LLVMValueRef global, + uint64_t *size, unsigned *alignment); +bool stela_air_metadata_shared_globals(struct stela_air_metadata *m); + +struct stela_air_argument { + LLVMValueRef value; /* Borrowed, decoder/compiler internal only. */ + struct stela_air_buffer buffer; + bool is_buffer; + unsigned components; /* Scalar/uint3 thread-position input. */ + bool plain_buffer_type; /* Reflected MSL builtin scalar/vector, not a struct. */ + const char *name, *type_name; + size_t name_bytes, type_name_bytes; + enum stela_air_primitive primitive; + unsigned type_components; + bool used; +}; +struct stela_air_kernel { + unsigned count; + struct stela_air_argument arguments[AIR_MAX_ARGUMENTS]; +}; +bool stela_air_metadata_kernel(struct stela_air_metadata *m, LLVMValueRef fn, + struct stela_air_kernel *kernel); + +#endif +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.c b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.c index 47bf4abeca..06136b46eb 100644 --- a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.c +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: MIT */ +#define STELA_AIR_METADATA_INTERNAL #include "air_to_nir.h" #include "llvm-c/Analysis.h" #include "llvm-c/BitReader.h" @@ -10,9 +11,6 @@ #include #include -#define AIR_MAX_ARGUMENTS 128 -#define AIR_MAX_METADATA_OPERANDS 256 -#define AIR_MAX_BITCODE_BYTES (64u * 1024u * 1024u) #define AIR_MAX_BLOCKS 128 #define AIR_MAX_CONTROL_DEPTH 32 #define AIR_MAX_MERGE_PHIS 128 @@ -58,6 +56,7 @@ struct translator { LLVMContextRef context; LLVMModuleRef module; LLVMTargetDataRef layout; /* Borrowed from module. */ + struct stela_air_metadata metadata; nir_builder b; struct hash_table *values; const struct stela_air_options *options; @@ -101,171 +100,17 @@ diagnostic(LLVMDiagnosticInfoRef info, void *data) LLVMDisposeMessage(message); } +#define md_string stela_air_md_string +#define md_uint stela_air_md_uint static bool -md_string(LLVMValueRef value, const char *expected) +md_node(struct translator *t, LLVMValueRef node, LLVMValueRef *operands, unsigned *count) { - if (!value || !LLVMIsAMDString(value)) - return false; - unsigned length; - const char *string = LLVMGetMDString(value, &length); - return length == strlen(expected) && !memcmp(string, expected, length); + return stela_air_md_node(&t->metadata, node, operands, count); } - static bool -md_uint(LLVMValueRef value, unsigned *number) +named_md(struct translator *t, const char *name, LLVMValueRef *operands, unsigned *count) { - if (!value || !LLVMIsAConstantInt(value) || - LLVMGetIntTypeWidth(LLVMTypeOf(value)) > 32) - return false; - *number = LLVMConstIntGetZExtValue(value); - return true; -} - -static bool -md_node(struct translator *t, LLVMValueRef node, LLVMValueRef *operands, - unsigned *count) -{ - if (!node || !LLVMIsAMDNode(node)) - return fail(t, STELA_AIR_METADATA, "expected AIR metadata node"); - *count = LLVMGetMDNodeNumOperands(node); - if (*count > AIR_MAX_METADATA_OPERANDS) - return fail(t, STELA_AIR_LIMIT, "AIR metadata operand budget exceeded"); - LLVMGetMDNodeOperands(node, operands); - return true; -} - -static bool -named_md(struct translator *t, const char *name, LLVMValueRef *operands, - unsigned *count) -{ - *count = LLVMGetNamedMetadataNumOperands(t->module, name); - if (*count > AIR_MAX_METADATA_OPERANDS) - return fail(t, STELA_AIR_LIMIT, "%s metadata budget exceeded", name); - LLVMGetNamedMetadataOperands(t->module, name, operands); - return true; -} - -static bool -version_metadata(struct translator *t, const char *name, bool language) -{ - LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned count, fields_count, major, minor, patch; - if (!named_md(t, name, nodes, &count) || count != 1 || - !md_node(t, nodes[0], fields, &fields_count)) - return fail(t, STELA_AIR_METADATA, "missing or invalid %s", name); - unsigned base = language ? 1 : 0; - if (fields_count != base + 3 || (language && !md_string(fields[0], "Metal")) || - !md_uint(fields[base], &major) || !md_uint(fields[base + 1], &minor) || - !md_uint(fields[base + 2], &patch) || patch != 0) - return fail(t, STELA_AIR_METADATA, "invalid %s", name); - bool supported = language ? - ((major == 1 && minor >= 1 && minor <= 2) || - (major == 2 && minor <= 4) || (major == 3 && minor <= 2) || - (major == 4 && minor <= 1)) : (major == 2 && (minor == 8 || minor == 9)); - /* AIR 2.8 has only been observed with Metal 4.0 here. The AIR 2.9 - * combinations below come from actual independent compiler requests. */ - if (language && t->air_minor == 8) - supported &= major == 4 && minor == 0; - if (!supported) - return fail(t, STELA_AIR_METADATA, "unsupported %s %u.%u.%u", name, major, minor, patch); - if (!language) - t->air_minor = minor; - else { - t->language_major = major; - t->language_minor = minor; - } - return true; -} - -static bool -module_flags(struct translator *t) -{ - /* These are the LLVM IR serialized behavior values, not the smaller C API - * LLVMModuleFlagBehavior enum (which does not expose Max in LLVM 23). */ - enum { IR_FLAG_ERROR = 1, IR_FLAG_MAX = 7 }; - const char *keys[] = {"wchar_size", "frame-pointer", "air.max_device_buffers", - "air.max_constant_buffers", "air.max_threadgroup_buffers", "air.max_textures", - "air.max_read_write_textures", "air.max_samplers"}; - LLVMValueRef flags[AIR_MAX_METADATA_OPERANDS]; - unsigned count, seen = 0; - if (!named_md(t, "llvm.module.flags", flags, &count)) - return false; - for (unsigned i = 0; i < count; i++) { - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned field_count, behavior, value, key; - if (!md_node(t, flags[i], fields, &field_count) || field_count != 3 || - !md_uint(fields[0], &behavior) || !md_uint(fields[2], &value)) - return fail(t, STELA_AIR_METADATA, "unsupported module flag shape"); - for (key = 0; key < ARRAY_SIZE(keys); key++) { - if (md_string(fields[1], keys[key])) - break; - } - if (key == ARRAY_SIZE(keys) || (seen & (1u << key))) - return fail(t, STELA_AIR_METADATA, "unsupported/duplicate module flag"); - seen |= 1u << key; - if (behavior != (key == 0 ? IR_FLAG_ERROR : IR_FLAG_MAX) || - (key == 0 && value != 4) || (key == 1 && value > 2) || - (key >= 2 && !value)) - return fail(t, STELA_AIR_METADATA, "unsupported module flag value: %s", keys[key]); - if (key == 2) - t->max_device_buffers = value; - if (key == 4) - t->max_threadgroup_buffers = value; - } - /* No linking, CPU frame operations or source wchar operations occur in the - * implemented compute subset. Other resource kinds remain refused. - * Device/threadgroup location bounds are enforced below, never advertised as the - * hardware's actual Metal capability or silently removed from the input. */ - return true; -} - -static bool -module_metadata(struct translator *t) -{ - for (LLVMNamedMDNodeRef node = LLVMGetFirstNamedMetadata(t->module); node; - node = LLVMGetNextNamedMetadata(node)) { - size_t size; - const char *name = LLVMGetNamedMetadataName(node, &size); - const char *allowed[] = {"air.version", "air.language_version", - "air.compile_options", "air.kernel", "llvm.ident", - "llvm.module.flags"}; - bool found = false; - for (unsigned i = 0; i < ARRAY_SIZE(allowed); i++) - found |= size == strlen(allowed[i]) && !memcmp(name, allowed[i], size); - if (!found) - return fail(t, STELA_AIR_METADATA, "unsupported module metadata: %.*s", - (int)MIN2(size, 160), name); - } - if (!version_metadata(t, "air.version", false) || - !version_metadata(t, "air.language_version", true) || !module_flags(t)) - return false; - LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS]; - unsigned count; - if (!named_md(t, "air.compile_options", nodes, &count)) - return false; - unsigned seen = 0; - for (unsigned i = 0; i < count; i++) { - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned fields_count; - if (!md_node(t, nodes[i], fields, &fields_count) || fields_count != 1 || - !(md_string(fields[0], "air.compile.denorms_disable") || - md_string(fields[0], "air.compile.fast_math_enable") || - md_string(fields[0], "air.compile.framebuffer_fetch_enable") || - md_string(fields[0], "air.compile.framebuffer_fetch_disable"))) - return fail(t, STELA_AIR_METADATA, "unsupported AIR compile option"); - unsigned bit = md_string(fields[0], "air.compile.denorms_disable") ? 1 : - md_string(fields[0], "air.compile.fast_math_enable") ? 2 : 4; - if (seen & bit) - return fail(t, STELA_AIR_METADATA, "duplicate/conflicting AIR compile option"); - seen |= bit; - } - t->denorms_disable = seen & 1; - t->fast_math = seen & 2; - /* Arithmetic requires an explicit qualified FP policy for this private AIR - * option. Exact storage/shared access and integer operations do not depend - * on FP denorm mode. */ - return true; + return stela_air_named_md(&t->metadata, name, operands, count); } static bool @@ -426,127 +271,25 @@ get_value(struct translator *t, LLVMValueRef llvm) static bool kernel_arguments(struct translator *t, LLVMValueRef fn) { - LLVMValueRef kernels[AIR_MAX_METADATA_OPERANDS], args_node = NULL; - unsigned kernel_count; - if (!named_md(t, "air.kernel", kernels, &kernel_count)) + struct stela_air_kernel kernel; + if (!stela_air_metadata_kernel(&t->metadata, fn, &kernel)) return false; - for (unsigned i = 0; i < kernel_count; i++) { - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned count; - if (!md_node(t, kernels[i], fields, &count) || count != 3) - return fail(t, STELA_AIR_METADATA, "invalid air.kernel descriptor"); - if (fields[0] == fn) { - LLVMValueRef outputs[AIR_MAX_METADATA_OPERANDS]; - unsigned output_count; - if (args_node || !md_node(t, fields[1], outputs, &output_count) || output_count) - return fail(t, STELA_AIR_METADATA, "duplicate kernel or nonempty compute outputs"); - args_node = fields[2]; - } - } - if (!args_node) - return fail(t, STELA_AIR_METADATA, "entry is not an AIR compute kernel"); - unsigned argc = LLVMCountParams(fn); - if (argc > AIR_MAX_ARGUMENTS) - return fail(t, STELA_AIR_LIMIT, "AIR argument budget exceeded"); - LLVMValueRef args[AIR_MAX_METADATA_OPERANDS]; - unsigned count; - if (!md_node(t, args_node, args, &count) || count != argc) - return fail(t, STELA_AIR_METADATA, "AIR argument descriptors do not match parameters"); - bool used[AIR_MAX_ARGUMENTS] = {false}; - bool buffer_indices[AIR_MAX_ARGUMENTS] = {false}; - bool shared_indices[AIR_MAX_ARGUMENTS] = {false}; bool ssbo_slots[UINT8_MAX + 1] = {false}; - for (unsigned a = 0; a < argc; a++) { - LLVMValueRef fields[AIR_MAX_METADATA_OPERANDS]; - unsigned fields_count, index; - if (!md_node(t, args[a], fields, &fields_count) || fields_count < 2 || - !md_uint(fields[0], &index) || index >= argc || used[index]) - return fail(t, STELA_AIR_METADATA, "invalid/duplicate argument index"); - used[index] = true; - LLVMValueRef param = LLVMGetParam(fn, index); - unsigned attributes_count = LLVMGetAttributeCountAtIndex(fn, index + 1); - if (attributes_count > AIR_MAX_METADATA_OPERANDS) - return fail(t, STELA_AIR_LIMIT, "argument attribute budget exceeded"); - LLVMAttributeRef attributes[AIR_MAX_METADATA_OPERANDS]; - LLVMGetAttributesAtIndex(fn, index + 1, attributes); - const char *abi_attributes[] = {"sret", "byval", "byref", "inalloca", - "preallocated", "nest", "swiftself", "swifterror", "elementtype"}; - for (unsigned attribute = 0; attribute < attributes_count; attribute++) { - if (LLVMIsTypeAttribute(attributes[attribute])) - return fail(t, STELA_AIR_ARGUMENT, "unsupported typed parameter attribute"); - if (!LLVMIsEnumAttribute(attributes[attribute])) - continue; - unsigned kind = LLVMGetEnumAttributeKind(attributes[attribute]); - for (unsigned k = 0; k < ARRAY_SIZE(abi_attributes); k++) { - if (kind == LLVMGetEnumAttributeKindForName(abi_attributes[k], strlen(abi_attributes[k]))) - return fail(t, STELA_AIR_ARGUMENT, "unsupported parameter ABI attribute: %s", abi_attributes[k]); - } - } - bool buffer = md_string(fields[1], "air.buffer"); - bool thread_id = md_string(fields[1], "air.thread_position_in_grid"); - if (!buffer && !thread_id) - return fail(t, STELA_AIR_ARGUMENT, "unsupported AIR argument kind at %u", index); - struct stela_air_buffer desc = {.argument = index}; - bool has_location = false, has_as = false, has_size = false, has_align = false; - bool has_name = false, has_type_name = false; - for (unsigned f = 2; f < fields_count;) { - LLVMValueRef key = fields[f++]; - if (md_string(key, "air.read") || md_string(key, "air.write") || - md_string(key, "air.read_write")) { - if (!buffer || desc.access) - return fail(t, STELA_AIR_METADATA, "duplicate/inapplicable buffer access"); - desc.access = md_string(key, "air.read") ? STELA_AIR_READ : - md_string(key, "air.write") ? STELA_AIR_WRITE : STELA_AIR_READ_WRITE; - } else if (md_string(key, "air.location_index")) { - unsigned locations; - if (!buffer || has_location || f + 2 > fields_count || - !md_uint(fields[f], &desc.index) || !md_uint(fields[f + 1], &locations) || - locations != 1 || desc.index >= AIR_MAX_ARGUMENTS) - return fail(t, STELA_AIR_METADATA, "unsupported/duplicate buffer location"); - has_location = true; - f += 2; - } else if (md_string(key, "air.address_space")) { - if (!buffer || has_as || f == fields_count || !md_uint(fields[f++], &desc.address_space)) - return fail(t, STELA_AIR_METADATA, "invalid buffer address space"); - has_as = true; - } else if (md_string(key, "air.arg_type_size") || md_string(key, "air.arg_type_align_size")) { - bool alignment = md_string(key, "air.arg_type_align_size"); - bool *present = alignment ? &has_align : &has_size; - unsigned *number = alignment ? &desc.type_alignment : &desc.type_size; - if (!buffer || *present || f == fields_count || !md_uint(fields[f++], number) || - (alignment && (!*number || (*number & (*number - 1))))) - return fail(t, STELA_AIR_METADATA, "invalid argument size/alignment"); - *present = true; - } else if (md_string(key, "air.arg_name") || md_string(key, "air.arg_type_name")) { - bool *present = md_string(key, "air.arg_name") ? &has_name : &has_type_name; - if (*present || f == fields_count || !fields[f] || !LLVMIsAMDString(fields[f++])) - return fail(t, STELA_AIR_METADATA, "invalid argument reflection string"); - *present = true; - } else { - return fail(t, STELA_AIR_METADATA, "unsupported argument metadata at %u", index); - } - } + for (unsigned a = 0; a < kernel.count; a++) { + const struct stela_air_argument *argument = &kernel.arguments[a]; + LLVMValueRef param = argument->value; + struct stela_air_buffer desc = argument->buffer; + unsigned index = desc.argument, components = argument->components; + bool buffer = argument->is_buffer; nir_def *def; unsigned ssbo_slot = 0; nir_variable *shared = NULL; unsigned shared_size = 0; if (buffer) { - LLVMTypeRef type = LLVMTypeOf(param); - if (!has_location || !has_as || !desc.access || - (desc.address_space != 1 && desc.address_space != 3) || - LLVMGetTypeKind(type) != LLVMPointerTypeKind || - LLVMGetPointerAddressSpace(type) != desc.address_space) - return fail(t, STELA_AIR_ARGUMENT, "unsupported buffer %u", index); bool threadgroup = desc.address_space == 3; - bool *indices = threadgroup ? shared_indices : buffer_indices; - unsigned limit = threadgroup ? t->max_threadgroup_buffers : t->max_device_buffers; - if (indices[desc.index] || (limit && desc.index >= limit)) - return fail(t, STELA_AIR_METADATA, "duplicate buffer or location exceeds AIR module limit"); - indices[desc.index] = true; if (threadgroup) { struct stela_air_threadgroup_view view = {0}; - if (!has_size || !has_align || !desc.type_size || !desc.type_alignment || - !t->options->bind_threadgroup || + if (!t->options->bind_threadgroup || !t->options->bind_threadgroup(&desc, &view, t->options->binding_data) || view.size < desc.type_size || view.alignment < desc.type_alignment || view.available_access < STELA_AIR_READ || view.available_access > STELA_AIR_READ_WRITE || @@ -572,10 +315,6 @@ kernel_arguments(struct translator *t, LLVMValueRef fn) return fail(t, STELA_AIR_ARGUMENT, "binding callback refused/invalid buffer %u", index); } } else { - unsigned components, bits; - if (!shape(LLVMTypeOf(param), &components, &bits) || bits != 32 || - (components != 1 && components != 3)) - return fail(t, STELA_AIR_ARGUMENT, "unsupported thread-position type"); /* Metal's grid starts at zero, with no dispatch-base parameter. * Form its ID directly from existing NIR workgroup/local builtins; * a generic global-ID lowering may add an OpenCL/Vulkan base input. */ @@ -602,42 +341,6 @@ kernel_arguments(struct translator *t, LLVMValueRef fn) return true; } -static bool -address_layout(struct translator *t) -{ - t->layout = LLVMGetModuleDataLayout(t->module); - const char *layout = LLVMGetDataLayoutStr(t->module); - if (!layout || !*layout || LLVMByteOrder(t->layout) != LLVMLittleEndian || - LLVMPointerSizeForAS(t->layout, 0) != 8 || LLVMPointerSizeForAS(t->layout, 1) != 8) - return fail(t, STELA_AIR_TARGET, "requires explicit little-endian 64-bit AIR layout"); - /* LLVM's C DataLayout API does not expose pointer-index width. Validate only - * that property here; actual allocation sizes/field offsets come from LLVM. - * Nonintegral/external-state pointers need a different NIR representation. */ - for (const char *part = layout; *part;) { - const char *end = strchr(part, '-'); - size_t length = end ? (size_t)(end - part) : strlen(part); - if ((length > 3 && !memcmp(part, "ni:", 3)) || (length && *part == 'P')) - return fail(t, STELA_AIR_TARGET, "unsupported nonintegral/program address-space layout"); - if (length && *part == 'p') { - unsigned colons = 0; - const char *last = NULL; - for (size_t i = 0; i < length; i++) { - if (part[i] == ':') { - colons++; - last = part + i + 1; - } - } - if (colons > 4 || (colons == 4 && - ((size_t)(part + length - last) != 2 || memcmp(last, "64", 2)))) - return fail(t, STELA_AIR_TARGET, "unsupported pointer-index width"); - } - part += length; - if (*part) - part++; - } - return true; -} - static bool fixed_storage_type(struct translator *t, LLVMTypeRef type, unsigned depth, unsigned *budget) @@ -677,17 +380,7 @@ fixed_storage_type(struct translator *t, LLVMTypeRef type, unsigned depth, static bool shared_profile(struct translator *t) { - LLVMValueRef nodes[AIR_MAX_METADATA_OPERANDS], fields[AIR_MAX_METADATA_OPERANDS]; - unsigned count, fields_count; - if (t->air_minor != 9 || t->language_major != 4 || t->language_minor != 1 || - strcmp(LLVMGetTarget(t->module), "air64_v29-apple-macosx27.2.0") || - !named_md(t, "llvm.ident", nodes, &count) || count != 1 || - !md_node(t, nodes[0], fields, &fields_count) || fields_count != 1 || - !md_string(fields[0], "Apple metal version 32023.922 (metalfe-32023.922.4)")) - return fail(t, STELA_AIR_METADATA, "shared-memory AIR/compiler profile is unqualified"); - if (LLVMPointerSizeForAS(t->layout, 3) != 8) - return fail(t, STELA_AIR_TARGET, "shared-memory AIR pointers require 64-bit layout"); - return true; + return stela_air_metadata_shared_profile(&t->metadata); } static nir_variable * @@ -716,65 +409,17 @@ shared_resource(struct translator *t, uint64_t size, unsigned alignment) return var; } -static bool -shared_storage_size(struct translator *t, LLVMTypeRef type, unsigned depth, - uint64_t *size) -{ - if (depth == 32) - return fail(t, STELA_AIR_LIMIT, "shared storage type nesting exceeded"); - if (LLVMGetTypeKind(type) == LLVMArrayTypeKind) { - uint64_t element; - if (!shared_storage_size(t, LLVMGetElementType(type), depth + 1, &element)) - return false; - uint64_t length = LLVMGetArrayLength2(type); - if (!length || length > UINT32_MAX / element) - return fail(t, STELA_AIR_LIMIT, "shared storage array extent exceeded"); - } else { - unsigned components, bits; - if (!value_shape(type, &components, &bits) || bits < 8) - return fail(t, STELA_AIR_TYPE, "shared globals require fixed integer/FP32 scalar/vector arrays"); - } - /* Aggregate extents were bounded before invoking fixed-size LLVM queries. */ - *size = LLVMABISizeOfType(t->layout, type); - return (*size && *size <= UINT32_MAX) || - fail(t, STELA_AIR_LIMIT, "shared storage allocation size exceeded"); -} - static bool shared_global_info(struct translator *t, LLVMValueRef global, - uint64_t *size, unsigned *alignment) + uint64_t *size, unsigned *alignment) { - const char *section = LLVMGetSection(global); - LLVMValueRef initializer = LLVMGetInitializer(global); - if (LLVMGetPointerAddressSpace(LLVMTypeOf(global)) != 3 || - LLVMGetLinkage(global) != LLVMInternalLinkage || LLVMIsThreadLocal(global) || - LLVMIsGlobalConstant(global) || LLVMIsExternallyInitialized(global) || - (section && *section) || !initializer || !LLVMIsUndef(initializer) || LLVMIsPoison(initializer)) - return fail(t, STELA_AIR_TARGET, "unsupported global/shared initializer or storage ABI"); - LLVMTypeRef type = LLVMGlobalGetValueType(global); - if (!shared_storage_size(t, type, 0, size)) - return false; - *alignment = LLVMGetAlignment(global); - if (!*alignment) - *alignment = LLVMABIAlignmentOfType(t->layout, type); - return (*alignment && !(*alignment & (*alignment - 1))) || - fail(t, STELA_AIR_TYPE, "unsupported shared global alignment"); + return stela_air_metadata_shared_global(&t->metadata, global, size, alignment); } static bool shared_globals(struct translator *t) { - unsigned count = 0; - for (LLVMValueRef global = LLVMGetFirstGlobal(t->module); global; - global = LLVMGetNextGlobal(global)) { - uint64_t size; - unsigned alignment; - if (++count > AIR_MAX_ARGUMENTS) - return fail(t, STELA_AIR_LIMIT, "shared global count exceeded"); - if (!shared_global_info(t, global, &size, &alignment)) - return false; - } - return true; + return stela_air_metadata_shared_globals(&t->metadata); } static nir_def * @@ -1709,7 +1354,18 @@ stela_air_to_nir(const void *bitcode, size_t size, const char *entry, fail(&t, STELA_AIR_TARGET, "unsupported target/globals/inline assembly"); goto done; } - if (!address_layout(&t) || !module_metadata(&t) || !shared_globals(&t)) + t.metadata = (struct stela_air_metadata){.module = t.module, .error = error}; + if (!stela_air_metadata_layout(&t.metadata) || !stela_air_metadata_validate(&t.metadata)) + goto done; + t.layout = t.metadata.layout; + t.air_minor = t.metadata.air_minor; + t.language_major = t.metadata.language_major; + t.language_minor = t.metadata.language_minor; + t.max_device_buffers = t.metadata.max_device_buffers; + t.max_threadgroup_buffers = t.metadata.max_threadgroup_buffers; + t.denorms_disable = t.metadata.denorms_disable; + t.fast_math = t.metadata.fast_math; + if (!shared_globals(&t)) goto done; char target_prefix[40]; snprintf(target_prefix, sizeof(target_prefix), "air64_v2%u-apple-macosx", t.air_minor); diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.h b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.h index ff06868c17..ed3177b6e5 100644 --- a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.h +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir.h @@ -3,50 +3,13 @@ #define STELA_AIR_TO_NIR_H #include "compiler/nir/nir_builder.h" +#include "air_metadata.h" #include /* User-space compiler boundary. LLVM and Mesa must be built for this process's * architecture and linked with their normal runtime services. No GPU access, * IOKit call, Metal device registration, or command submission happens here. */ -enum stela_air_error_kind { - STELA_AIR_OK, - STELA_AIR_INPUT, - STELA_AIR_LLVM_VERSION, - STELA_AIR_BITCODE, - STELA_AIR_VERIFY, - STELA_AIR_TARGET, - STELA_AIR_METADATA, - STELA_AIR_ARGUMENT, - STELA_AIR_CONTROL_FLOW, - STELA_AIR_INSTRUCTION, - STELA_AIR_TYPE, - STELA_AIR_MEMORY, - STELA_AIR_LIMIT, - STELA_AIR_ALLOCATION, -}; - -struct stela_air_error { - enum stela_air_error_kind kind; - unsigned instruction; /* Zero-based instruction ordinal, not source line. */ - char detail[256]; -}; - -enum stela_air_buffer_access { - STELA_AIR_READ = 1, - STELA_AIR_WRITE = 2, - STELA_AIR_READ_WRITE = 3, -}; - -struct stela_air_buffer { - unsigned argument; - unsigned index; /* air.location_index; not an LLVM parameter byte offset. */ - unsigned address_space; - enum stela_air_buffer_access access; - unsigned type_size; /* Zero when the input omits this optional reflection. */ - unsigned type_alignment; -}; - /* Resolve a validated Metal buffer binding to a 64-bit device virtual address. * The caller owns resource lifetime, size/access validation, actual allocation, * residency and runtime argument ABI. Returning NULL refuses compilation. This diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir_test.c b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir_test.c index 9c9e445398..0f4036ee79 100644 --- a/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir_test.c +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/air_to_nir_test.c @@ -1759,11 +1759,253 @@ nak_codegen(const char *body, const char *label, bool ieee) } #endif +static bool +inspect_entry(const struct stela_air_inspection *info, const struct stela_air_entry *entry, void *data) +{ + unsigned *count = data; + CHECK(info->air_minor == 8 && info->language_major == 4 && info->language_minor == 0); + CHECK(info->denorms_disable && info->fast_math && info->target_bytes == strlen(info->target)); + CHECK(entry->name_bytes == 6 && !memcmp(entry->name, "kernel", 6) && entry->argument_count == 2); + CHECK(entry->reflection_complete); + const struct stela_air_argument_info *arg = &entry->arguments[1]; + CHECK(entry->arguments[0].kind == 2 && entry->arguments[0].components == 1); + CHECK(arg->kind == 1 && arg->buffer.argument == 1 && arg->buffer.index == 7 && + arg->buffer.address_space == 1 && arg->buffer.access == STELA_AIR_READ_WRITE && + arg->buffer.type_size == 4 && arg->buffer.type_alignment == 4 && arg->plain_buffer_type); + CHECK(arg->primitive == STELA_AIR_UINT && arg->type_components == 1 && + arg->name_bytes == 6 && !memcmp(arg->name, "output", 6) && + arg->type_name_bytes == 4 && !memcmp(arg->type_name, "uint", 4)); + (*count)++; + return true; +} + +struct reflection_expectation { + bool complete, used; + enum stela_air_primitive primitive; + unsigned components; +}; +static bool +inspect_reflection(const struct stela_air_inspection *info, const struct stela_air_entry *entry, void *data) +{ + (void)info; + const struct reflection_expectation *expected = data; + CHECK(entry->argument_count == 2); + const struct stela_air_argument_info *arg = &entry->arguments[1]; + CHECK(entry->reflection_complete == expected->complete && arg->used == expected->used && + arg->primitive == expected->primitive && arg->type_components == expected->components); + return true; +} +static void +reflection_inspection_case(const char *prefix, const char *body, const char *metadata, const char *extra, + bool complete, bool used, enum stela_air_primitive primitive, unsigned components) +{ + struct stela_air_error error; + struct reflection_expectation expected = {complete, used, primitive, components}; + LLVMMemoryBufferRef input = stela_air_test_custom_bitcode(prefix, body, metadata, extra); + CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, + inspect_reflection, &expected, &error)); + CHECK(error.kind == STELA_AIR_OK); + LLVMDisposeMemoryBuffer(input); +} +static void +reflection_inspection_tests(void) +{ + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, stela_air_test_metadata, + "", true, true, STELA_AIR_UINT, 1); + const char *scalars[] = {"char", "uchar", "short", "ushort", "int", "uint", "long", "ulong", "float"}; + const unsigned scalar_sizes[] = {1,1,2,2,4,4,8,8,4}; + for (unsigned scalar = 0; scalar < 9; scalar++) { + for (unsigned components = 1; components <= 4; components++) { + char reflected[96], layout[128]; + if (components == 1) + snprintf(reflected, sizeof(reflected), "!\"%s\", !\"air.arg_name\", !\"output\"", scalars[scalar]); + else + snprintf(reflected, sizeof(reflected), "!\"%s%u\", !\"air.arg_name\", !\"output\"", scalars[scalar], components); + unsigned extent = scalar_sizes[scalar] * (components == 3 ? 4 : components); + snprintf(layout, sizeof(layout), "!\"air.arg_type_size\", i32 %u, !\"air.arg_type_align_size\", i32 %u", extent, extent); + char *typed = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"", reflected); + char *sized = replace_once(typed, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4", layout); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, sized, + "", true, true, STELA_AIR_CHAR + scalar, components); + free(typed); free(sized); + } + } + /* AIR use facts are preserved even for a currently unused formal parameter. */ + reflection_inspection_case(stela_air_test_prefix, "ret void\n", stela_air_test_metadata, + "", true, false, STELA_AIR_UINT, 1); + char *metadata = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"", + "!\"UnqualifiedStructure\", !\"air.arg_name\", !\"output\""); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata, + "", false, true, STELA_AIR_PRIMITIVE_UNKNOWN, 0); + free(metadata); + metadata = replace_once(stela_air_test_metadata, ", !\"air.arg_name\", !\"output\"", ""); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata, + "", false, true, STELA_AIR_UINT, 1); + free(metadata); + metadata = replace_once(stela_air_test_metadata, "!\"output\"", "!\"out\\00put\""); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata, + "", false, true, STELA_AIR_UINT, 1); + free(metadata); + metadata = replace_once(stela_air_test_metadata, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4,", ""); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, metadata, + "", false, true, STELA_AIR_UINT, 1); + free(metadata); + /* MSL vector3 has four lanes of storage/alignment; no packed-layout guess. */ + metadata = replace_once(stela_air_test_metadata, "!\"uint\", !\"air.arg_name\", !\"output\"", + "!\"uint3\", !\"air.arg_name\", !\"output\""); + char *sized = replace_once(metadata, "!\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4", + "!\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16"); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, sized, + "", true, true, STELA_AIR_UINT, 3); + char *packed = replace_once(sized, "!\"air.arg_type_size\", i32 16", "!\"air.arg_type_size\", i32 12"); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, packed, + "", false, true, STELA_AIR_UINT, 3); + free(metadata); free(sized); free(packed); + char *prefix = replace_once(stela_air_test_prefix, " %out)", " \"unknown-reflection\" %out)"); + reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata, + "", false, true, STELA_AIR_UINT, 1); + free(prefix); + prefix = replace_once(stela_air_test_prefix, ") {", ") #0 {"); + reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata, + "attributes #0 = { \"unqualified-annotation\"=\"text\" }\n", false, true, STELA_AIR_UINT, 1); + free(prefix); + prefix = replace_once(stela_air_test_prefix, ") {", ") !custom !11 {"); + reflection_inspection_case(prefix, stela_air_test_store_body, stela_air_test_metadata, + "!11 = !{!\"annotation\"}\n", false, true, STELA_AIR_UINT, 1); + free(prefix); + reflection_inspection_case(stela_air_test_prefix, stela_air_test_store_body, stela_air_test_metadata, + "@unqualified = constant i32 1\n", false, true, STELA_AIR_UINT, 1); +} + +static void +shared_reflection_case(const char *extra, bool complete) +{ + LLVMMemoryBufferRef input = shared_bitcode("ret void\n", false, extra); + struct reflection_expectation expected = {complete, false, STELA_AIR_UINT, 1}; + struct stela_air_error error; + CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, + inspect_reflection, &expected, &error)); + /* A conservative absent-reflection result must not leak its local failure + * into otherwise successful original LLVM/module inspection. */ + CHECK(error.kind == STELA_AIR_OK && !error.detail[0]); + if (complete) { + struct shared_bindings bindings = {0}; + nir_shader *nir = shared_translate(input, &test_nir_options, &bindings, 0, &error); + CHECK(nir && !nir->info.shared_size && !bindings.shared); + check_shared_operations(nir, 0, 0, 0); + ralloc_free(nir); + } + LLVMDisposeMemoryBuffer(input); +} + +static void +shared_reflection_tests(void) +{ + const char *good[] = { + "@s = internal addrspace(3) global i8 undef, align 1\n", + "@s = internal addrspace(3) global <3 x i16> undef, align 8\n", + "@s = internal addrspace(3) global [3 x [4 x <4 x float>]] undef, align 16\n", + "@s = internal unnamed_addr addrspace(3) global [32 x i32] undef, align 4\n", + "@s = internal addrspace(3) global i64 undef\n", /* Original ABI alignment. */ + }; + for (unsigned i = 0; i < ARRAY_SIZE(good); i++) + shared_reflection_case(good[i], true); + const char *bad[] = { + "@s = internal addrspace(1) global i32 undef, align 4\n", + "@s = internal addrspace(3) constant i32 undef, align 4\n", + "@s = external addrspace(3) global i32\n", + "@s = internal thread_local addrspace(3) global i32 undef, align 4\n", + "@s = internal addrspace(3) externally_initialized global i32 undef, align 4\n", + "@s = internal addrspace(3) global i32 0, align 4\n", + "@s = internal addrspace(3) global i32 poison, align 4\n", + "@s = internal addrspace(3) global i32 undef, section \"unqualified\", align 4\n", + "@s = internal addrspace(3) global i32 undef, align 4, !custom !77\n!77 = !{!\"unqualified\"}\n", + "@s = internal addrspace(3) global [0 x i32] undef, align 4\n", + "@s = internal addrspace(3) global [4294967296 x i32] undef, align 4\n", + "@s = internal addrspace(3) global {i32,i32} undef, align 4\n", + "@s = internal addrspace(3) global half undef, align 2\n", + "@s = internal addrspace(3) global i1 undef, align 1\n", + "@s = internal addrspace(3) global <8 x i32> undef, align 32\n", + }; + for (unsigned i = 0; i < ARRAY_SIZE(bad); i++) + shared_reflection_case(bad[i], false); + shared_refusal("ret void\n", bad[8], STELA_AIR_TARGET); + /* Recursion/count are bounded before target-layout size/alignment queries. */ + char nested[1024] = "@s = internal addrspace(3) global "; + for (unsigned i = 0; i < 33; i++) strcat(nested, "[1 x "); + strcat(nested, "i32"); + for (unsigned i = 0; i < 33; i++) strcat(nested, "]"); + strcat(nested, " undef, align 4\n"); + shared_reflection_case(nested, false); + shared_refusal("ret void\n", nested, STELA_AIR_LIMIT); + char globals[16384] = {0}; + size_t used = 0; + for (unsigned i = 0; i <= AIR_MAX_ARGUMENTS; i++) { + int n = snprintf(globals + used, sizeof(globals) - used, + "@s%u = internal addrspace(3) global i32 undef, align 4\n", i); + CHECK(n > 0 && (size_t)n < sizeof(globals) - used); used += (size_t)n; + } + shared_reflection_case(globals, false); + shared_refusal("ret void\n", globals, STELA_AIR_LIMIT); + /* Old AIR2.8 unused shared globals still allocate nothing in the executable + * path; they cannot gain a new qualified reflection profile by this change. */ + reflection_inspection_case(stela_air_test_prefix, "ret void\n", stela_air_test_metadata, + good[3], false, false, STELA_AIR_UINT, 1); + LLVMMemoryBufferRef input = stela_air_test_bitcode("ret void\n", good[3]); + struct shared_bindings bindings = {0}; struct stela_air_error error; + nir_shader *nir = shared_translate(input, &test_nir_options, &bindings, 0, &error); + CHECK(nir && !nir->info.shared_size); ralloc_free(nir); LLVMDisposeMemoryBuffer(input); + puts("AIR static-shared reflection, observational diagnostics, bounds and unused-allocation tests passed"); +} + +static void +inspection_tests(void) +{ + struct stela_air_error error; + unsigned calls = 0; + LLVMMemoryBufferRef input = stela_air_test_bitcode(stela_air_test_store_body, ""); + CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error)); + CHECK(calls == 1 && error.kind == STELA_AIR_OK); + CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 0, inspect_entry, &calls, &error)); + CHECK(error.kind == STELA_AIR_INPUT && calls == 1); + LLVMDisposeMemoryBuffer(input); + char *metadata = replace_once(stela_air_test_metadata, "!air.kernel = !{!2}", "!air.kernel = !{!2, !2}"); + input = stela_air_test_custom_bitcode(stela_air_test_prefix, stela_air_test_store_body, metadata, ""); + calls = 0; + CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error)); + CHECK(error.kind == STELA_AIR_METADATA && calls == 0); /* No partial manifest. */ + LLVMDisposeMemoryBuffer(input); free(metadata); + metadata = replace_once(stela_air_test_metadata, "i32 7, i32 1", "i32 128, i32 1"); + input = stela_air_test_custom_bitcode(stela_air_test_prefix, stela_air_test_store_body, metadata, ""); + CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error)); + CHECK(error.kind == STELA_AIR_METADATA && calls == 0); + LLVMDisposeMemoryBuffer(input); free(metadata); + /* Preserve the original integer shape rule: a scalar or uint3 builtin, + * never a one-lane LLVM vector masquerading as a scalar argument. */ + char *prefix = replace_once(stela_air_test_prefix, "i32 %tid", "<1 x i32> %tid"); + input = stela_air_test_custom_bitcode(prefix, "ret void\n", stela_air_test_metadata, ""); + CHECK(!stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error)); + CHECK(error.kind == STELA_AIR_ARGUMENT && calls == 0); + nir_shader *invalid_shape = translate(input, &test_nir_options, 100, &error); + CHECK(!invalid_shape && error.kind == STELA_AIR_ARGUMENT); + LLVMDisposeMemoryBuffer(input); free(prefix); + /* Inspection is NOT a promise that a body/resource/pipeline can compile. */ + input = stela_air_test_bitcode("call void @unknown()\nret void\n", "declare void @unknown()\n"); + CHECK(stela_air_inspect(LLVMGetBufferStart(input), LLVMGetBufferSize(input), 8, inspect_entry, &calls, &error)); + CHECK(calls == 1); + nir_shader *nir = translate(input, &test_nir_options, 100, &error); + CHECK(!nir && error.kind == STELA_AIR_INSTRUCTION); + LLVMDisposeMemoryBuffer(input); +} + int main(void) { glsl_type_singleton_init_or_ref(); tests(); + inspection_tests(); + reflection_inspection_tests(); + shared_reflection_tests(); #ifdef STELA_AIR_TEST_NAK nak_codegen(stela_air_test_store_body, "integer", false); nak_codegen(conditional_body, "nested-conditional", false); diff --git a/crates/stela-drivers/src/gpu/common/mesa/src/stela/meson.build b/crates/stela-drivers/src/gpu/common/mesa/src/stela/meson.build index 8869f9ae96..d9837a233c 100644 --- a/crates/stela-drivers/src/gpu/common/mesa/src/stela/meson.build +++ b/crates/stela-drivers/src/gpu/common/mesa/src/stela/meson.build @@ -19,6 +19,20 @@ stela_apple_source_test = executable( ) test('stela_apple_source_boundary', stela_apple_source_test, suite : 'stela') +# Value normalization owns no LLVM, NIR or driver state. +stela_metal_threadgroup = static_library( + 'stela_metal_threadgroup', + '../../../../metal/compiler/threadgroup.c', + c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'], +) +stela_metal_threadgroup_test = executable( + 'stela_metal_threadgroup_test', + '../../../../metal/compiler/tests/threadgroup.c', + link_with : stela_metal_threadgroup, + c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'], +) +test('stela_metal_threadgroup_values', stela_metal_threadgroup_test, suite : 'stela') + if with_stela_amd_llvm stela_amd_llvm_float = static_library( 'stela_amd_llvm_float', @@ -52,16 +66,50 @@ if stela_air_llvm != '' ) stela_air = static_library( 'stela_air_to_nir', - 'air_to_nir.c', + ['air_to_nir.c', 'air_metadata.c'], include_directories : [inc_include, inc_src], dependencies : [idep_nir, idep_mesautil, stela_air_llvm_dep], c_args : ['-Werror'], ) + stela_metal_input = get_option('stela-metal-input-library') + if stela_metal_input != '' + if host_machine.system() != 'darwin' or not fs.is_absolute(stela_metal_input) or not fs.is_file(stela_metal_input) + error('Metal assembly requires a matching Darwin Rust input static library') + endif + stela_metal_assembly = static_library( + 'stela_metal_assembly', + '../../../../metal/compiler/library_assembly.c', + dependencies : [stela_air_llvm_dep], + c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'], + ) + # Ordinary archive extraction pulls the shared metadata inspector alone; + # this local owner does not depend on NIR or any vendor compiler backend. + stela_metal_assembly_test = executable( + 'stela_metal_assembly_test', + '../../../../metal/compiler/tests/library_assembly.c', + dependencies : [stela_air_llvm_dep, dependency('appleframeworks', modules : ['CoreFoundation'])], + link_with : [stela_metal_assembly, stela_air, stela_apple_source], + link_args : [stela_metal_input, '-lresolv', '-liconv'], + c_args : ['-Wall', '-Wextra', '-Werror', '-Wconversion'], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_metal_library_assembly', stela_metal_assembly_test, suite : 'stela') + endif idep_stela_air = declare_dependency( link_with : [stela_air], include_directories : include_directories('.'), dependencies : [idep_nir, idep_mesautil, stela_air_llvm_dep], ) + stela_metal_threadgroup_nir_test = executable( + 'stela_metal_threadgroup_nir_test', + '../../../../metal/compiler/tests/threadgroup_nir.c', + include_directories : [inc_include, inc_src], + dependencies : [idep_stela_air], + link_with : stela_metal_threadgroup, + c_args : ['-Wall', '-Wextra', '-Werror', '-Wno-missing-field-initializers'], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_metal_threadgroup_nir', stela_metal_threadgroup_nir_test, suite : 'stela') stela_air_test_dependencies = [idep_stela_air] stela_air_test_links = [] stela_air_test_args = ['-Werror'] @@ -226,6 +274,29 @@ if with_stela_nvidia build_rpath : fs.parent(stela_air_llvm), ) endif + if stela_air_llvm != '' and stela_metal_input != '' + stela_nv_air = static_library( + 'stela_nv_air', + '../../../../nvidia/stela/hosted/air_compile.c', + include_directories : [inc_include, inc_src, include_directories('../nouveau/headers')], + dependencies : [idep_stela_air, idep_nak, idep_nir_headers], + link_with : [stela_metal_assembly, stela_metal_threadgroup, _libnak_rs], + c_args : ['-Werror'], + ) + stela_nv_air_compile_test = executable( + 'stela_nv_air_compile_test', + '../../../../nvidia/stela/tests/air_compile.c', + include_directories : [inc_include, inc_src, + include_directories('../nouveau/headers', '../nouveau/headers/nvidia/classes')], + dependencies : [idep_stela_air, idep_nak, idep_nir_headers, + dependency('appleframeworks', modules : ['CoreFoundation'])], + link_with : [stela_nv_air, stela_nv_compute, stela_apple_source, _libnak_rs], + link_args : [stela_metal_input, '-lresolv', '-liconv'], + c_args : ['-Werror'], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_nv_air_owned', stela_nv_air_compile_test, suite : 'stela') + endif stela_nak_probe = executable( 'stela_nak_probe', 'nak_probe.c', @@ -443,6 +514,37 @@ if with_stela_intel ) test('stela_intel_legacy_compute_program', stela_intel_legacy_compute_program_probe, suite : 'stela') + if stela_air_llvm != '' and stela_metal_input != '' + stela_intel_air = static_library( + 'stela_intel_air', + ['../../../../intel/stela/hosted/air_compile.c', + '../../../../intel/stela/hosted/air_validate_elk.c'], + include_directories : [inc_include, inc_src, inc_intel], + dependencies : [idep_stela_air, idep_intel_compiler_brw, + idep_intel_compiler_elk, idep_intel_compiler_gen, + idep_intel_dev, idep_mesautil], + link_with : [stela_metal_assembly, stela_metal_threadgroup], + c_args : ['-Werror'], + ) + stela_intel_air_compile_test = executable( + 'stela_intel_air_compile_test', + '../../../../intel/stela/tests/air_compile.c', + include_directories : [inc_include, inc_src, inc_intel, + include_directories('../../../../intel/stela/hosted')], + dependencies : [idep_stela_air, idep_intel_compiler_brw, + idep_intel_compiler_elk, idep_intel_compiler_gen, + idep_intel_dev, idep_mesautil, + dependency('appleframeworks', modules : ['CoreFoundation'])], + link_with : [stela_intel_air, stela_intel_surface, + stela_intel_compute_policy, stela_intel_compute_native, + stela_intel_legacy_compute, stela_intel_gpgpu_native, + libisl, stela_apple_source], + link_args : [stela_metal_input, '-lresolv', '-liconv'] + stela_intel_policy_gc, + c_args : ['-Werror'], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_intel_air_owned', stela_intel_air_compile_test, suite : 'stela') + endif if stela_air_llvm != '' stela_intel_fp_controls_probe = executable( 'stela_intel_fp_controls_probe', @@ -643,6 +745,30 @@ if with_stela_amd c_args : ['-Werror', '-DSTELA_AMD_TEST_LLVM=' + (with_stela_amd_llvm ? '1' : '0')], ) test('stela_amd_compute', stela_amd_compute_probe, suite : 'stela') + if stela_air_llvm != '' and stela_metal_input != '' + stela_amd_air = static_library( + 'stela_amd_air', + '../../../../amd/stela/air_compile.c', + include_directories : [inc_include, inc_src, inc_amd, inc_amd_common], + dependencies : [idep_stela_air, idep_aco, idep_amd_generated_headers] + + (with_stela_amd_llvm ? [dep_llvm] : []), + link_with : [stela_metal_assembly, stela_metal_threadgroup, stela_amd_buffer, libamd_compiler_support], + c_args : ['-Werror'], + ) + stela_amd_air_compile_test = executable( + 'stela_amd_air_compile_test', + '../../../../amd/tests/air_compile.c', + include_directories : [inc_include, inc_src, inc_amd, inc_amd_common], + dependencies : [idep_stela_air, idep_aco, idep_amd_generated_headers, + dependency('appleframeworks', modules : ['CoreFoundation'])] + + (with_stela_amd_llvm ? [dep_llvm] : []), + link_with : [stela_amd_air, stela_amd_compute, stela_apple_source], + link_args : [stela_metal_input, '-lresolv', '-liconv'], + c_args : ['-Werror'], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_amd_air_owned', stela_amd_air_compile_test, suite : 'stela') + endif if stela_air_llvm != '' and with_stela_amd_llvm stela_amd_air_threadgroup_probe = executable( 'stela_amd_air_threadgroup_probe', diff --git a/crates/stela-drivers/src/gpu/intel.rs b/crates/stela-drivers/src/gpu/intel.rs index b9d5643d38..998f18bcc4 100644 --- a/crates/stela-drivers/src/gpu/intel.rs +++ b/crates/stela-drivers/src/gpu/intel.rs @@ -2,7 +2,13 @@ //! does not initialize a device, map GPU memory, submit jobs or expose Metal. use core::marker::PhantomData; +pub mod activation; pub mod ct_storage; +pub mod firmware; +pub mod ggtt; +pub mod guc_reset; +pub mod pat; +pub mod wopcm; /// The actual VM's supported width, supplied by the device/VM owner. #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/stela-drivers/src/gpu/intel/activation.rs b/crates/stela-drivers/src/gpu/intel/activation.rs new file mode 100644 index 0000000000..0f8112c17e --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/activation.rs @@ -0,0 +1,697 @@ +//! Native owned BAR0/device-facts/root-GT probe; not firmware or job readiness. +use crate::bus::mmio::owned::{ + Authority, CacheAttribute, Error as MappingError, Mapping, MappingView, Protection, Resource, + ResourceKind, +}; +use alloc::{alloc::alloc_zeroed, alloc::dealloc, boxed::Box}; +use core::{alloc::Layout, ffi::c_void, marker::PhantomData, ptr::NonNull}; +use triomphe::UniqueArc; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct PciIdentity { + pub vendor: u16, + pub device: u16, + pub class: u32, + pub revision: u8, + pub virtual_function: bool, + pub bar0_start: u64, + pub bar0_bytes: u64, +} + +/// Exclusive native PCI/power/bridge/reset epoch, supplied by the real mount. +/// No implementation or fallback is supplied by this GPU module. +/// +/// # Safety +/// Identity/resource metadata is immutable and describes the SAME actual PCI +/// function and exclusive reservation. The ResourceBacking must itself pin all +/// teardown-critical root/reset/power state: canonical failed-map quarantine +/// can retain it independently of this wrapper. This owner retains D0/bridge power, +/// excludes removal/relocation/other resets, every other driver/firmware access and all +/// IRQ/submission/DMA/CT users throughout this probe. GuC-only reset is an +/// explicit permitted operation within this exclusive actual epoch; it never +/// substitutes for draining an active driver or excluding other resets. These +/// prerequisites are not inferred from cleared software flags. `prepare` performs +/// required original device-WA and PCODE/lmem readiness, not a success flag in their place. +/// Ordered naturally-aligned MMIO32 operations must use the provided canonical +/// CPU pointer, honor original read-flush WA and posting/ordering semantics, +/// never conflate it with a physical/guest address and never fail/unwind. +/// The clock is qualified monotonic nonnegative nanoseconds, sufficiently below +/// i64::MAX for a 100ms deadline. Delay honors atomic/sleepable context. All calls +/// and final Drop occur on the allowed native CPU/process context; no callback +/// may reenter, activate guest services, or manufacture power/IRQ/coherence. +/// `finish` drains actual probe accesses/posted writes and prevents new accesses +/// but keeps ownership retained until the canonical mapping retires. Error +/// leaves the owner/reservations intact for retry/quarantine. Partial drain +/// effects on error are allowed; finish retries must safely complete that drain. +/// Once retirement begins no other device operations resume. `fatal` fail-stops. +pub unsafe trait ProbeOwner { + /// Check CPU/process/retained epoch without accessing BAR mappings. This + /// also runs during an uncertain-unmap retry when BAR access is forbidden. + fn check_context(&self) -> Result<(), i32>; + fn identity(&self) -> PciIdentity; + fn bar0(&self) -> Resource; + /// Actual same-function canonical configuration space, retained in this + /// exclusive power/reset epoch. Unsupported capability is an explicit Err. + fn config_space(&self) -> Result<&dyn crate::bus::pci::ConfigSpace, i32>; + /// # Safety + /// Live canonical UC GSM pointer, naturally aligned/bounded to eight bytes. + /// Perform one genuinely ordered 64-bit MMIO read with the original readq + /// semantics. No paired-32 fallback, guest access, unwind or fabricated value. + /// Err means the width/capability is unavailable before any read; actual + /// unexpected device-access faults obey the owner's fail-stop contract. + unsafe fn read64(&self, pointer: NonNull) -> Result; + /// Borrow the same retained UC register mapping for actual original + /// PCODE/lmem/WA preparation. Any retained view must be released by finish. + fn prepare( + &self, + registers: &MappingView, + platform: u32, + revision: u32, + discrete: bool, + ) -> Result<(), i32>; + /// # Safety + /// Pointer is a live canonical UC, aligned, bounded device register. + unsafe fn read32(&self, pointer: NonNull) -> u32; + /// # Safety + /// Same retained mapping and exclusive ordered-access contract as read32. + unsafe fn write32(&self, pointer: NonNull, value: u32); + fn now_ns(&self) -> i64; + fn delay_us(&self, minimum: u32, maximum: u32, atomic: bool); + fn report(&self, domains: u32, wake: bool, status: i32, value: u32); + fn finish(&self) -> Result<(), i32>; + fn fatal(&self) -> !; +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Mapping(MappingError), + InvalidOwner, + OutOfMemory, + InvalidLayout, + Native(i32), + Closing, + Awake, +} +impl From for Error { + fn from(value: MappingError) -> Self { + Self::Mapping(value) + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(C)] +pub struct Facts { + pub platform: u32, + pub subplatform: u32, + pub graphics_verx100: u32, + pub media_verx100: u32, + pub graphics_revision: u32, + pub media_revision: u32, + pub pci_revision: u32, + pub tile_count: u32, + pub dma_bits: u32, + pub va_bits: u32, + pub max_gt_per_tile: u32, + pub discrete: u32, + pub force_probe_required: u32, + pub gt_control: u32, + pub gt_ack: u32, + pub initialized: u32, + pub awake: u32, + pub has_llc: u32, + pub gt_type: u32, +} + +const _: () = assert!(core::mem::size_of::() == 76); +const _: () = assert!(core::mem::offset_of!(Facts, has_llc) == 68); +const _: () = assert!(core::mem::offset_of!(Facts, gt_type) == 72); +#[repr(C)] +struct Io { + check_context: extern "C" fn(*mut c_void) -> i32, + prepare: extern "C" fn(*mut c_void, u32, u32, bool) -> i32, + read32: extern "C" fn(*mut c_void, u32) -> u32, + write32: extern "C" fn(*mut c_void, u32, u32), + now_ns: extern "C" fn(*mut c_void) -> i64, + delay_us: extern "C" fn(*mut c_void, u32, u32, bool), + invariant: extern "C" fn(*mut c_void, bool), + report: extern "C" fn(*mut c_void, u32, bool, i32, u32), +} +unsafe extern "C" { + fn stela_intel_activation_guc_reset( + state: *mut c_void, + result: &mut super::guc_reset::NativeResult, + ) -> i32; + fn stela_intel_activation_pat(state: *mut c_void, result: &mut super::pat::NativeResult) + -> i32; + fn stela_intel_activation_wopcm( + state: *mut c_void, + bytes: *const u8, + size: usize, + output: &mut super::wopcm::NativeResult, + ) -> i32; + fn stela_intel_activation_size() -> usize; + fn stela_intel_activation_alignment() -> usize; + fn stela_intel_activation_match( + vendor: u32, + device: u32, + class: u32, + vf: bool, + force_probe: bool, + ) -> i32; + fn stela_intel_activation_init( + storage: *mut c_void, + bytes: usize, + io: &Io, + context: *mut c_void, + vendor: u32, + device: u32, + class: u32, + revision: u32, + bar_bytes: u64, + vf: bool, + force_probe: bool, + ) -> i32; + fn stela_intel_activation_facts(storage: *const c_void, facts: &mut Facts) -> i32; + fn stela_intel_activation_wake(storage: *mut c_void) -> i32; + fn stela_intel_activation_sleep(storage: *mut c_void) -> i32; +} + +struct State { + pointer: NonNull, + layout: Layout, +} +impl State { + fn new() -> Result { + // SAFETY: scalar layout queries have no context or device effects. + let layout = Layout::from_size_align(unsafe { stela_intel_activation_size() }, unsafe { + stela_intel_activation_alignment() + }) + .map_err(|_| Error::InvalidLayout)?; + if layout.size() == 0 { + return Err(Error::InvalidLayout); + } + // SAFETY: nonzero validated layout; standard allocator, no GPU allocator. + let pointer = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(Error::OutOfMemory)?; + Ok(Self { pointer, layout }) + } + fn pointer(&self) -> *mut c_void { + self.pointer.as_ptr().cast() + } +} +impl Drop for State { + fn drop(&mut self) { + // SAFETY: no C calls remain; exact original standard allocation/layout. + unsafe { dealloc(self.pointer.as_ptr(), self.layout) }; + } +} + +struct Context { + owner: Box, + view: Option, +} +impl Context { + fn pointer(&self, offset: u32) -> NonNull { + let pointer = self + .view + .as_ref() + .and_then(|v| v.address(offset as usize, 4).ok()); + match pointer { + Some(p) if (p.as_ptr() as usize).is_multiple_of(4) => p.cast(), + _ => self.owner.fatal(), + } + } +} +fn context<'a>(pointer: *mut c_void) -> &'a Context { + // SAFETY: private IO table is reachable only with its pinned unique context. + unsafe { &*pointer.cast::() } +} +extern "C" fn prepare(p: *mut c_void, platform: u32, revision: u32, discrete: bool) -> i32 { + let c = context(p); + let view = c.view.as_ref().unwrap_or_else(|| c.owner.fatal()); + c.owner + .prepare(view, platform, revision, discrete) + .err() + .map_or(0, |e| if e < 0 { e } else { -22 }) +} +extern "C" fn check_context(p: *mut c_void) -> i32 { + context(p) + .owner + .check_context() + .err() + .map_or(0, |e| if e < 0 { e } else { -22 }) +} +extern "C" fn read32(p: *mut c_void, offset: u32) -> u32 { + let c = context(p); + // SAFETY: retained bounded canonical view, actual owner, exclusive probe. + unsafe { c.owner.read32(c.pointer(offset)) } +} +extern "C" fn write32(p: *mut c_void, offset: u32, value: u32) { + let c = context(p); + // SAFETY: same ownership/order proof as read32, original access width32. + unsafe { c.owner.write32(c.pointer(offset), value) }; +} +extern "C" fn now_ns(p: *mut c_void) -> i64 { + context(p).owner.now_ns() +} +extern "C" fn delay_us(p: *mut c_void, min: u32, max: u32, atomic: bool) { + context(p).owner.delay_us(min, max, atomic); +} +extern "C" fn invariant(p: *mut c_void, valid: bool) { + if !valid { + context(p).owner.fatal(); + } +} +extern "C" fn report(p: *mut c_void, domains: u32, wake: bool, status: i32, value: u32) { + context(p).owner.report(domains, wake, status, value); +} +static IO: Io = Io { + check_context, + prepare, + read32, + write32, + now_ns, + delay_us, + invariant, + report, +}; + +struct Bundle { + state: State, + context: UniqueArc, + mapping: Mapping, +} +impl Bundle { + fn quarantine(self) { + let Self { + state, + context, + mapping, + } = self; + // Canonical Drop records/retains the mapping quarantine. Independently + // retain callback storage and the real power/reset owner as well. + drop(mapping); + core::mem::forget(context); + core::mem::forget(state); + } +} +/// No Send/Sync: one real CPU-affine exclusive probe, no firmware/IRQ/users. +/// Drop quarantines rather than inventing successful sleep/drain/unmap. +pub struct Device { + bundle: Option, + closing: bool, + drained: bool, + poisoned: bool, + awake: bool, + _affinity: PhantomData<*mut ()>, +} +impl Device { + pub fn open( + authority: &Authority, + owner: Box, + force_probe: bool, + ) -> Result { + let pci = owner.identity(); + owner.check_context().map_err(Error::Native)?; + // SAFETY: pure source-table policy; no mapping/owner/device effects. + let matched = unsafe { + stela_intel_activation_match( + u32::from(pci.vendor), + u32::from(pci.device), + pci.class, + pci.virtual_function, + force_probe, + ) + }; + if matched != 0 { + return Err(Error::Native(matched)); + } + let resource = owner.bar0(); + if resource.kind() != ResourceKind::Registers + || resource.physical_span().start() != pci.bar0_start + || resource.physical_span().bytes() != pci.bar0_bytes + || pci.class > 0xffffff + || pci.bar0_bytes < 16 * 1024 * 1024 + { + return Err(Error::InvalidOwner); + } + // Reserve only the actual register extent. GSM at BAR+8MiB has a + // separate same-resource grant/lease; mapping the entire BAR here would + // overlap it under the canonical mapping authority. + let bytes = 4 * 1024 * 1024; + let state = State::new()?; + // Reserve the maintained alloc-only owner before any mapping effect. + // Failure drops both the already reserved State and the original owner. + let mut context_storage = + UniqueArc::::try_new_uninit().map_err(|_| Error::OutOfMemory)?; + let context_address = + context_storage.write(Context { owner, view: None }) as *mut Context as usize; + // SAFETY: write initialized the complete Context exactly once. The + // UniqueArc conversion retains its allocation and stable C address. + let mut context = unsafe { UniqueArc::assume_init(context_storage) }; + debug_assert_eq!(context_address, &*context as *const Context as usize); + let mapping = match authority.map( + resource, + 0, + bytes, + CacheAttribute::Uncached, + Protection::ReadWrite, + ) { + Ok(mapping) => mapping, + Err(error) => { + // The canonical Error intentionally does not certify whether + // a failed provider call left mappings behind. Retain the + // actual power/reset epoch even for an ambiguous failure; + // no CPU access or fictitious rollback may follow it. + core::mem::forget(context); + return Err(error.into()); + } + }; + let view = match mapping.view(0..4 * 1024 * 1024) { + Ok(view) => view, + Err(e) => { + drop(mapping); + core::mem::forget(context); + return Err(e.into()); + } + }; + context.view = Some(view); + // SAFETY: allocated/aligned private storage; context/owner/Mapping pinned. + // C validates original table selection before MMIO; no object escapes. + let result = unsafe { + stela_intel_activation_init( + state.pointer(), + state.layout.size(), + &IO, + (&mut *context as *mut Context).cast(), + u32::from(pci.vendor), + u32::from(pci.device), + pci.class, + u32::from(pci.revision), + pci.bar0_bytes, + pci.virtual_function, + force_probe, + ) + }; + let bundle = Bundle { + state, + context, + mapping, + }; + if result != 0 { + // prepare may have had genuine hardware effects; no fake rollback. + bundle.quarantine(); + return Err(Error::Native(result)); + } + Ok(Self { + bundle: Some(bundle), + closing: false, + drained: false, + poisoned: false, + awake: false, + _affinity: PhantomData, + }) + } + fn live(&self) -> Result<&Bundle, Error> { + if self.closing { + return Err(Error::Closing); + } + self.bundle.as_ref().ok_or(Error::Closing) + } + pub fn facts(&self) -> Result { + let mut result = Facts::default(); + // SAFETY: live immutable C state and exact scalar output layout. + let status = + unsafe { stela_intel_activation_facts(self.live()?.state.pointer(), &mut result) }; + if status == 0 { + Ok(result) + } else { + Err(Error::Native(status)) + } + } + /// Issue the original direct XeLP PAT sequence in this exclusive live + /// root-primary epoch. No readback, ACK, CPU cache or BO state is implied. + pub fn program_pat(&mut self) -> Result, Error> { + let state = self.live()?.state.pointer(); + if !self.awake || self.poisoned { + return Err(Error::Awake); + } + let mut result = super::pat::NativeResult::default(); + // SAFETY: actual State retains same canonical view, descriptor/GT role, + // exclusive owner and acknowledged wake; stack output before effects. + let status = unsafe { stela_intel_activation_pat(state, &mut result) }; + if status != 0 { + if result.writes != 0 { + self.gsm_poison(); + } + return Err(Error::Native(status)); + } + Ok(super::pat::Programming::from_native(self, result)) + } + /// Explicit original GuC-only reset handshake under the actual owner's + /// exclusive no-DMA/no-IRQ/no-CT/no-submission epoch. This is not whole uC + /// sanitize, driver initialization, software job drain or firmware loading. + /// A failed exposed reset permanently closes and quarantines this epoch; + /// no retry, Drop, sleep or finish may release uncertain reset ownership. + pub fn reset_guc(&mut self) -> Result, Error> { + let state = self.live()?.state.pointer(); + if !self.awake || self.poisoned { + return Err(Error::Awake); + } + let mut result = super::guc_reset::NativeResult::default(); + // SAFETY: same actual owned State/view and stable Context; acknowledged + // GT wake, qualified clock/context and exclusive real epoch exclude all + // active users before entry. Stack metadata exists before any effect. + let status = unsafe { stela_intel_activation_guc_reset(state, &mut result) }; + if status != 0 { + if result.writes != 0 { + self.gsm_poison(); + } + return Err(Error::Native(status)); + } + Ok(super::guc_reset::Handshake::from_native(self, result)) + } + /// Acquire the original PF GSM geometry and a separate real same-BAR UC + /// mapping. Requires acknowledged root GT wake and actual config-space/ + /// mapping capabilities; establishes neither GGTT initialization nor PAT. + pub fn probe_gsm<'device>( + &'device mut self, + authority: &Authority, + ) -> Result, Error> { + self.live()?; + if !self.awake || self.poisoned { + return Err(Error::Awake); + } + let facts = self.facts()?; + let bundle = self.live()?; + bundle + .context + .owner + .check_context() + .map_err(Error::Native)?; + let mut offset = 0; + // SAFETY: original CPU-only policy; checked live device facts. + let config = + unsafe { super::ggtt::stela_intel_gsm_config(facts.graphics_verx100, &mut offset) }; + let gmch = match config { + 0 => bundle + .context + .owner + .config_space() + .map_err(Error::Native)? + .read16(offset), + 1 => 0, + error => return Err(Error::Native(error)), + }; + let identity = bundle.context.owner.identity(); + let geometry = + super::ggtt::Geometry::from_facts(facts, identity.bar0_bytes, config == 0, gmch)?; + let resource = bundle.context.owner.bar0(); + if resource.kind() != ResourceKind::Registers + || resource.physical_span().start() != identity.bar0_start + || resource.physical_span().bytes() != identity.bar0_bytes + { + return Err(Error::InvalidOwner); + } + let bytes = usize::try_from(geometry.gsm_bytes).map_err(|_| Error::InvalidOwner)?; + let offset = usize::try_from(geometry.gsm_offset).map_err(|_| Error::InvalidOwner)?; + let mapping = match authority.map( + resource, + offset, + bytes, + CacheAttribute::Uncached, + Protection::ReadOnly, + ) { + Ok(mapping) => mapping, + Err(error) => { + // Error does not certify a safe rollback. Existing backing and + // preallocated Context keep reset/power/forcewake pinned, with + // no allocation or device access in this uncertainty path. + self.gsm_poison(); + return Err(error.into()); + } + }; + let view = match mapping.view(0..bytes) { + Ok(view) => view, + Err(error) => { + self.gsm_poison(); + drop(mapping); // canonical quarantine; never assume unmap. + return Err(error.into()); + } + }; + Ok(super::ggtt::Probe::from_native( + self, geometry, mapping, view, + )) + } + pub(super) fn gsm_check_context(&self) -> Result<(), Error> { + self.bundle + .as_ref() + .ok_or(Error::Closing)? + .context + .owner + .check_context() + .map_err(Error::Native) + } + pub(super) fn gsm_poison(&mut self) { + self.closing = true; + self.poisoned = true; + } + pub(super) fn gsm_read64(&self, view: &MappingView, offset: usize) -> Result { + let bundle = self.live()?; + if !self.awake || self.poisoned { + return Err(Error::Awake); + } + bundle + .context + .owner + .check_context() + .map_err(Error::Native)?; + let pointer = view.address(offset, 8)?; + if !(pointer.as_ptr() as usize).is_multiple_of(8) { + return Err(Error::InvalidOwner); + } + // SAFETY: actual retained same-resource UC lease; checked complete width, + // original PTE index and native owner/context; exclusive Device borrow. + unsafe { bundle.context.owner.read64(pointer.cast()) }.map_err(Error::Native) + } + /// Original default GuC metadata request, bound to this retained live + /// native root main-GT owner. No firmware is uploaded or authenticated. + pub fn guc_firmware(&self) -> Result, super::firmware::Error> { + let identity = self.live()?.context.owner.identity(); + let facts = self.facts()?; + super::firmware::Request::from_native(self, identity, facts) + } + /// Original default HuC request, retaining this actual root main-GT owner. + /// Host parsing never establishes firmware availability or WOPCM readiness. + pub fn huc_firmware(&self) -> Result, super::firmware::Error> { + let identity = self.live()?.context.owner.identity(); + let facts = self.facts()?; + super::firmware::HucRequest::from_native(self, identity, facts) + } + /// Partition/read back actual root-GT WOPCM using the original algorithm. + /// Requires acknowledged wake. An exposed write failure permanently closes + /// this epoch and retains its canonical owner/view; no cleanup can release + /// forcewake/reset ownership. All result storage is on the stack before IO. + pub fn prepare_wopcm<'device, 'provider>( + &'device mut self, + provider: &'provider dyn crate::firmware::Provider, + ) -> Result, super::wopcm::Error> { + self.live()?; + if !self.awake || self.poisoned { + return Err(Error::Awake.into()); + } + let (image, metadata, identity, facts) = { + let request = self.guc_firmware()?; + let loaded = request.load(provider)?; + ( + loaded.image(), + loaded.metadata(), + loaded.identity(), + loaded.facts(), + ) + }; + let mut result = super::wopcm::NativeResult::default(); + // SAFETY: SAME private owned C state and actual immutable provider CPU + // span. C independently checks acknowledged GT/role/firmware bounds. + // Existing State/Context/mapping storage was reserved before all IO; + // no allocation or owner release follows an exposed failure. + let status = unsafe { + stela_intel_activation_wopcm( + self.live()?.state.pointer(), + image.bytes().as_ptr(), + image.bytes().len(), + &mut result, + ) + }; + if status != 0 { + if result.writes != 0 { + self.poisoned = true; + self.closing = true; + } + return Err(result.error(status)); + } + Ok(super::wopcm::Preparation::from_native( + self, image, metadata, identity, facts, result, + )) + } + pub fn wake(&mut self) -> Result<(), Error> { + let storage = self.live()?.state.pointer(); + if self.awake || self.poisoned { + return Err(Error::Awake); + } + // SAFETY: &mut plus CPU affinity and actual ProbeOwner exclude all users. + let status = unsafe { stela_intel_activation_wake(storage) }; + if status != 0 { + self.poisoned = true; + return Err(Error::Native(status)); + } + self.awake = true; + Ok(()) + } + pub fn sleep(&mut self) -> Result<(), Error> { + let storage = self.live()?.state.pointer(); + if !self.awake || self.poisoned { + return Err(Error::Awake); + } + // SAFETY: same actual exclusive native scope; no concurrent firmware. + let status = unsafe { stela_intel_activation_sleep(storage) }; + if status != 0 { + self.poisoned = true; + return Err(Error::Native(status)); + } + self.awake = false; + Ok(()) + } + pub fn retire(&mut self) -> Result<(), Error> { + if self.awake || self.poisoned { + return Err(Error::Awake); + } + let bundle = self.bundle.as_mut().ok_or(Error::Closing)?; + bundle + .context + .owner + .check_context() + .map_err(Error::Native)?; + // A real drain can have partial effects before returning an error. + // Freeze all public device/C operations BEFORE attempting it, retaining + // the live mapping/view and owners until the drain actually succeeds. + self.closing = true; + if !self.drained { + bundle.context.owner.finish().map_err(Error::Native)?; + self.drained = true; + // No future C/CPU accesses; release our view before actual unmap. + drop(bundle.context.view.take()); + } + // SAFETY: acknowledged sleep, actual owner drain, no IRQ/submission, + // CPU-affine &mut exclusion. Failed mappings stay retained for retry. + unsafe { bundle.mapping.retire()? }; + self.bundle = None; + Ok(()) + } +} +impl Drop for Device { + fn drop(&mut self) { + if let Some(bundle) = self.bundle.take() { + bundle.quarantine(); + } + } +} diff --git a/crates/stela-drivers/src/gpu/intel/firmware.rs b/crates/stela-drivers/src/gpu/intel/firmware.rs new file mode 100644 index 0000000000..8eec8456ad --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/firmware.rs @@ -0,0 +1,508 @@ +//! Provider-borrowed GuC/HuC metadata selected by a live native Xe device. +//! No BO, firmware status, authentication or hardware upload is established. +use super::activation::{self, Device, Facts, PciIdentity}; +use crate::firmware::{Image, Provider, Requirement, Target}; +use core::fmt::{self, Write}; + +const CSS_HEADER_BYTES: usize = 128; + +#[derive(Debug, PartialEq, Eq)] +pub enum Error { + Device(activation::Error), + Selection(i32), + InvalidNativeIdentity, + InvalidCatalogName, + IdentityEncoding, + Provider(crate::firmware::Error), + WrongImage, + HucAbsent(HucDisposition), + Parse { + status: i32, + diagnostics: Diagnostics, + }, +} +impl From for Error { + fn from(value: activation::Error) -> Self { + Self::Device(value) + } +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(C)] +pub struct Version { + pub major: u32, + pub minor: u32, + pub patch: u32, +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(transparent)] +pub struct Diagnostics(u32); +impl Diagnostics { + pub const GUC_TOO_OLD: u32 = 1 << 0; + pub const VERSION_MISMATCH: u32 = 1 << 1; + pub const RECOMMENDED_NEWER: u32 = 1 << 2; + pub const SHORT_HEADER: u32 = 1 << 3; + pub const HEADER_SIZE: u32 = 1 << 4; + pub const SHORT_IMAGE: u32 = 1 << 5; + pub const CPD_HEADER_LENGTH: u32 = 1 << 8; + pub const CPD_SHORT_IMAGE: u32 = 1 << 9; + pub const CPD_MISSING_MANIFEST: u32 = 1 << 10; + pub const UNREPRESENTABLE: u32 = 1 << 31; + pub fn bits(self) -> u32 { + self.0 + } +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(C)] +pub struct Metadata { + pub release: Version, + pub submission: Version, + pub ucode_bytes: u32, + pub rsa_bytes: u32, + pub upload_bytes: u32, + pub private_bytes: u32, + pub build_type: u32, + pub diagnostics: Diagnostics, +} +#[repr(C)] +struct Selection { + name: [u8; 64], + wanted: Version, + full_version: u32, +} +const _: () = assert!(core::mem::size_of::() == 80); +const _: () = assert!(core::mem::size_of::() == 48); +const _: () = assert!(core::mem::offset_of!(Selection, wanted) == 64); +const _: () = assert!(core::mem::offset_of!(Selection, full_version) == 76); +const _: () = assert!(core::mem::offset_of!(Metadata, submission) == 12); +const _: () = assert!(core::mem::offset_of!(Metadata, ucode_bytes) == 24); +const _: () = assert!(core::mem::offset_of!(Metadata, diagnostics) == 44); +unsafe extern "C" { + fn stela_intel_guc_select(platform: u32, output: &mut Selection) -> i32; + fn stela_intel_guc_parse( + platform: u32, + bytes: *const u8, + size: usize, + output: &mut Metadata, + diagnostics: &mut u32, + ) -> i32; +} + +// Only bounded Intel identity formatting; no allocation or general registry. +struct Label { + bytes: [u8; N], + used: usize, +} +impl Label { + fn new() -> Self { + Self { + bytes: [0; N], + used: 0, + } + } + fn as_str(&self) -> &str { + // SAFETY: only write_str copies valid UTF-8, preserving whole fragments. + unsafe { core::str::from_utf8_unchecked(&self.bytes[..self.used]) } + } +} +impl Write for Label { + fn write_str(&mut self, value: &str) -> fmt::Result { + let end = self + .used + .checked_add(value.len()) + .filter(|&v| v <= N) + .ok_or(fmt::Error)?; + self.bytes[self.used..end].copy_from_slice(value.as_bytes()); + self.used = end; + Ok(()) + } +} + +fn identity_labels(identity: PciIdentity, facts: Facts) -> Result<(Label<16>, Label<96>), Error> { + let mut hardware = Label::new(); + write!( + hardware, + "pci-{:04x}-{:04x}", + identity.vendor, identity.device + ) + .map_err(|_| Error::IdentityEncoding)?; + let mut revision = Label::new(); + write!( + revision, + "pci-{:02x};gfx-{}.{};media-{}.{};gt-main;tile-0", + identity.revision, + facts.graphics_verx100, + facts.graphics_revision, + facts.media_verx100, + facts.media_revision + ) + .map_err(|_| Error::IdentityEncoding)?; + Ok((hardware, revision)) +} + +/// Exact default request from the actual retained root main-GT device. +/// The setup manifest must use this same filename and exact target tuple. +pub struct Request<'device> { + device: &'device Device, + identity: PciIdentity, + facts: Facts, + selection: Selection, + name_bytes: usize, + hardware: Label<16>, + revision: Label<96>, +} +impl<'device> Request<'device> { + pub(super) fn from_native( + device: &'device Device, + identity: PciIdentity, + facts: Facts, + ) -> Result { + if identity.vendor != 0x8086 || identity.virtual_function || facts.graphics_verx100 == 0 { + return Err(Error::InvalidNativeIdentity); + } + let mut selection = Selection { + name: [0; 64], + wanted: Version::default(), + full_version: 0, + }; + // SAFETY: private scalar output, exact C layout; source catalog only. + let status = unsafe { stela_intel_guc_select(facts.platform, &mut selection) }; + if status != 0 { + return Err(Error::Selection(status)); + } + let name_bytes = selection + .name + .iter() + .position(|&v| v == 0) + .filter(|&n| n != 0) + .ok_or(Error::InvalidCatalogName)?; + core::str::from_utf8(&selection.name[..name_bytes]) + .map_err(|_| Error::InvalidCatalogName)?; + let (hardware, revision) = identity_labels(identity, facts)?; + Ok(Self { + device, + identity, + facts, + selection, + name_bytes, + hardware, + revision, + }) + } + pub fn name(&self) -> &str { + // SAFETY: constructor validates this immutable, private native copy. + unsafe { core::str::from_utf8_unchecked(&self.selection.name[..self.name_bytes]) } + } + pub fn wanted(&self) -> Version { + self.selection.wanted + } + pub fn full_version_required(&self) -> bool { + self.selection.full_version != 0 + } + pub fn target(&self) -> Target<'_> { + Target { + driver: "intel-xe-guc", + hardware: self.hardware.as_str(), + revision: self.revision.as_str(), + board: None, + } + } + pub fn requirement(&self) -> Requirement<'_> { + Requirement { + name: self.name(), + target: self.target(), + minimum_bytes: CSS_HEADER_BYTES, + } + } + pub fn load<'provider>( + &self, + provider: &'provider dyn Provider, + ) -> Result, Error> { + let image = provider.load(self.requirement()).map_err(Error::Provider)?; + // A safe third-party Provider cannot manufacture Image, but could + // delegate to a catalog using the wrong requirement. Recheck its reply. + if image.name() != self.name() || image.target() != self.target() { + return Err(Error::WrongImage); + } + let mut metadata = Metadata::default(); + let mut diagnostics = 0; + // SAFETY: provider-owned immutable single-allocation CPU slice; packed + // CSS ABI and checked native extents, exact output layout, no device IO. + let status = unsafe { + stela_intel_guc_parse( + self.facts.platform, + image.bytes().as_ptr(), + image.bytes().len(), + &mut metadata, + &mut diagnostics, + ) + }; + if status != 0 { + return Err(Error::Parse { + status, + diagnostics: Diagnostics(diagnostics), + }); + } + Ok(GucImage { + _device: self.device, + image, + identity: self.identity, + facts: self.facts, + wanted: self.wanted(), + metadata, + }) + } +} + +/// Format-checked host image with original provenance and borrowed lifetimes. +/// It is not authenticated, GGTT-pinned, loadable or running firmware. +pub struct GucImage<'device, 'provider> { + _device: &'device Device, + image: Image<'provider>, + identity: PciIdentity, + facts: Facts, + wanted: Version, + metadata: Metadata, +} +impl<'provider> GucImage<'_, 'provider> { + pub fn image(&self) -> Image<'provider> { + self.image + } + pub fn identity(&self) -> PciIdentity { + self.identity + } + pub fn facts(&self) -> Facts { + self.facts + } + pub fn wanted(&self) -> Version { + self.wanted + } + pub fn metadata(&self) -> Metadata { + self.metadata + } +} + +/// Original default catalog/GT-role disposition, never a load status. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HucDisposition { + Selected, + AbsentRole, + AbsentCatalog, +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(C)] +pub struct HucMetadata { + pub release: Version, + pub ucode_bytes: u32, + pub rsa_bytes: u32, + pub upload_bytes: u32, + pub css_offset: u32, + format: u32, + pub diagnostics: Diagnostics, +} +impl HucMetadata { + pub fn has_gsc_headers(self) -> bool { + self.format == 2 + } +} +#[repr(C)] +struct HucSelection { + disposition: u32, + name: [u8; 64], + wanted: Version, + full_version: u32, +} +const _: () = assert!(core::mem::size_of::() == 84); +const _: () = assert!(core::mem::offset_of!(HucSelection, wanted) == 68); +const _: () = assert!(core::mem::size_of::() == 36); +const _: () = assert!(core::mem::offset_of!(HucMetadata, css_offset) == 24); +const _: () = assert!(core::mem::offset_of!(HucMetadata, diagnostics) == 32); +unsafe extern "C" { + fn stela_intel_huc_select_default( + platform: u32, + graphics_verx100: u32, + media_gt: bool, + output: &mut HucSelection, + ) -> i32; + fn stela_intel_huc_parse( + platform: u32, + graphics_verx100: u32, + media_gt: bool, + bytes: *const u8, + size: usize, + output: &mut HucMetadata, + diagnostics: &mut u32, + ) -> i32; +} + +/// Actual retained root-main-GT default. Missing role/catalog never performs a +/// Provider lookup, while failure of a selected image remains a real error. +/// Every request borrows the same live Device; no copied identity is a device. +pub struct HucRequest<'device> { + device: &'device Device, + identity: PciIdentity, + facts: Facts, + selection: HucSelection, + disposition: HucDisposition, + name_bytes: usize, + hardware: Label<16>, + revision: Label<96>, +} +impl<'device> HucRequest<'device> { + pub(super) fn from_native( + device: &'device Device, + identity: PciIdentity, + facts: Facts, + ) -> Result { + if identity.vendor != 0x8086 || identity.virtual_function || facts.graphics_verx100 == 0 { + return Err(Error::InvalidNativeIdentity); + } + let mut selection = HucSelection { + disposition: 0, + name: [0; 64], + wanted: Version::default(), + full_version: 0, + }; + // SAFETY: actual device facts and exact private C scalar output layout. + let status = unsafe { + stela_intel_huc_select_default( + facts.platform, + facts.graphics_verx100, + false, + &mut selection, + ) + }; + if status != 0 { + return Err(Error::Selection(status)); + } + let disposition = match selection.disposition { + 1 => HucDisposition::Selected, + 2 => HucDisposition::AbsentRole, + 3 => HucDisposition::AbsentCatalog, + _ => return Err(Error::InvalidNativeIdentity), + }; + let name_bytes = if disposition == HucDisposition::Selected { + let n = selection + .name + .iter() + .position(|&v| v == 0) + .filter(|&n| n != 0) + .ok_or(Error::InvalidCatalogName)?; + core::str::from_utf8(&selection.name[..n]).map_err(|_| Error::InvalidCatalogName)?; + n + } else { + 0 + }; + let (hardware, revision) = identity_labels(identity, facts)?; + Ok(Self { + device, + identity, + facts, + selection, + disposition, + name_bytes, + hardware, + revision, + }) + } + pub fn disposition(&self) -> HucDisposition { + self.disposition + } + pub fn name(&self) -> Option<&str> { + (self.disposition == HucDisposition::Selected).then(|| { + // SAFETY: constructor validated the immutable private native copy. + unsafe { core::str::from_utf8_unchecked(&self.selection.name[..self.name_bytes]) } + }) + } + pub fn wanted(&self) -> Option { + self.name().map(|_| self.selection.wanted) + } + pub fn full_version_required(&self) -> bool { + self.selection.full_version != 0 + } + pub fn target(&self) -> Target<'_> { + Target { + driver: "intel-xe-huc", + hardware: self.hardware.as_str(), + revision: self.revision.as_str(), + board: None, + } + } + pub fn requirement(&self) -> Result, Error> { + Ok(Requirement { + name: self.name().ok_or(Error::HucAbsent(self.disposition))?, + target: self.target(), + minimum_bytes: CSS_HEADER_BYTES, + }) + } + pub fn load<'provider>( + &self, + provider: &'provider dyn Provider, + ) -> Result, Error> { + let requirement = self.requirement()?; + let image = provider.load(requirement).map_err(Error::Provider)?; + if image.name() != requirement.name || image.target() != requirement.target { + return Err(Error::WrongImage); + } + let mut metadata = HucMetadata::default(); + let mut diagnostics = 0; + // SAFETY: original immutable provider CPU span; checked packed parser + // and exact scalar output. No MMIO, BO status or device DMA is accessed. + let status = unsafe { + stela_intel_huc_parse( + self.facts.platform, + self.facts.graphics_verx100, + false, + image.bytes().as_ptr(), + image.bytes().len(), + &mut metadata, + &mut diagnostics, + ) + }; + if status != 0 { + return Err(Error::Parse { + status, + diagnostics: Diagnostics(diagnostics), + }); + } + Ok(HucImage { + _device: self.device, + image, + identity: self.identity, + facts: self.facts, + wanted: self.selection.wanted, + metadata, + }) + } +} + +/// Format-checked host HuC image retaining canonical provenance and the same +/// Device/provider borrows. This is neither cryptographic authentication nor +/// AVAILABLE/LOADABLE, BO/GGTT storage, DMA completion or WOPCM admission. +/// A later Device-owned bootstrap can retain the independent Image borrow +/// (like GuC preparation) before consuming mutable device ownership; no lifetime +/// erasure or replacement physical/native identity is needed. +pub struct HucImage<'device, 'provider> { + _device: &'device Device, + image: Image<'provider>, + identity: PciIdentity, + facts: Facts, + wanted: Version, + metadata: HucMetadata, +} +impl<'provider> HucImage<'_, 'provider> { + pub fn image(&self) -> Image<'provider> { + self.image + } + pub fn identity(&self) -> PciIdentity { + self.identity + } + pub fn facts(&self) -> Facts { + self.facts + } + pub fn wanted(&self) -> Version { + self.wanted + } + pub fn metadata(&self) -> HucMetadata { + self.metadata + } +} diff --git a/crates/stela-drivers/src/gpu/intel/ggtt.rs b/crates/stela-drivers/src/gpu/intel/ggtt.rs new file mode 100644 index 0000000000..c5bdbdd2f2 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/ggtt.rs @@ -0,0 +1,125 @@ +//! Owned read-only Xe PF GSM probe. No GGTT/PAT/BO initialization or PTE writes. +use super::activation::{Device, Error, Facts}; +use crate::bus::mmio::owned::{Mapping, MappingView}; + +/// Original immutable scalar geometry. It is not a mapping or allocation token. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(C)] +pub struct Geometry { + pub gsm_offset: u64, + pub gsm_bytes: u64, + pub ggtt_start: u64, + pub ggtt_bytes: u64, +} +const _: () = assert!(core::mem::size_of::() == 32); +const _: () = assert!(core::mem::offset_of!(Geometry, ggtt_start) == 16); +unsafe extern "C" { + pub(super) fn stela_intel_gsm_config(graphics_verx100: u32, offset: &mut u16) -> i32; + fn stela_intel_gsm_geometry( + platform: u32, + graphics_verx100: u32, + discrete: bool, + actual_bar_bytes: u64, + config_present: bool, + gmch: u16, + output: &mut Geometry, + ) -> i32; + fn stela_intel_gsm_pte_offset(geometry: &Geometry, address: u64, offset: &mut usize) -> i32; +} +impl Geometry { + pub(super) fn from_facts( + facts: Facts, + bar_bytes: u64, + present: bool, + gmch: u16, + ) -> Result { + let mut result = Self::default(); + // SAFETY: CPU-only original policy and complete scalar ABI; actual live + // device facts, whole BAR extent and same-function configuration input. + let status = unsafe { + stela_intel_gsm_geometry( + facts.platform, + facts.graphics_verx100, + facts.discrete != 0, + bar_bytes, + present, + gmch, + &mut result, + ) + }; + if status != 0 { + return Err(Error::Native(status)); + } + Ok(result) + } +} +/// Exclusive live Device borrow retains forcewake/reset/power throughout reads +/// and canonical teardown. No raw pointer escapes. Explicit successful retire +/// releases this lease before the caller can sleep/finish the Device. Drop or +/// uncertain teardown permanently poisons that epoch and quarantines ownership; +/// retry can retire the SAME mapping but can never reopen device operations. +pub struct Probe<'device> { + device: &'device mut Device, + geometry: Geometry, + mapping: Option, + view: Option, + closing: bool, +} +impl<'device> Probe<'device> { + pub(super) fn from_native( + device: &'device mut Device, + geometry: Geometry, + mapping: Mapping, + view: MappingView, + ) -> Self { + Self { + device, + geometry, + mapping: Some(mapping), + view: Some(view), + closing: false, + } + } + pub fn geometry(&self) -> Geometry { + self.geometry + } + /// Raw original readq result; does not validate PTE contents or readiness. + /// Address is an original GGTT page address, never an IOVA or CPU pointer. + pub fn read_pte(&self, address: u64) -> Result { + if self.closing { + return Err(Error::Closing); + } + let mut offset = 0; + // SAFETY: immutable native-produced geometry, checked original index and + // complete eight-byte span before pointer formation or owner access. + let status = unsafe { stela_intel_gsm_pte_offset(&self.geometry, address, &mut offset) }; + if status != 0 { + return Err(Error::Native(status)); + } + self.device + .gsm_read64(self.view.as_ref().ok_or(Error::Closing)?, offset) + } + pub fn retire(&mut self) -> Result<(), Error> { + self.device.gsm_check_context()?; // pure context check, including retries. + let mapping = self.mapping.as_mut().ok_or(Error::Closing)?; + self.closing = true; + drop(self.view.take()); + // SAFETY: no escaped pointers or firmware/DMA/IRQ users; exclusive actual + // owner remains awake/pinned, no outstanding CPU accesses after &mut. + if let Err(error) = unsafe { mapping.retire() } { + self.device.gsm_poison(); + return Err(error.into()); + } + self.mapping = None; + Ok(()) + } +} +impl Drop for Probe<'_> { + fn drop(&mut self) { + if self.mapping.is_some() { + self.device.gsm_poison(); + drop(self.view.take()); + drop(self.mapping.take()); // existing canonical quarantine. + } + } +} diff --git a/crates/stela-drivers/src/gpu/intel/guc_reset.rs b/crates/stela-drivers/src/gpu/intel/guc_reset.rs new file mode 100644 index 0000000000..c621e2ebee --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/guc_reset.rs @@ -0,0 +1,42 @@ +//! Observed original GuC-only hardware reset, retaining the actual Device epoch. +use super::activation::Device; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) struct NativeResult { + pub writes: u32, + pub warnings: u32, + pub gdrst: u32, + pub guc_status: u32, + pub ready_status: u32, + pub sram_status: u32, +} +const _: () = assert!(core::mem::size_of::() == 24); +const _: () = assert!(core::mem::offset_of!(NativeResult, guc_status) == 12); + +/// The original GDRST clear and MIA-in-reset observations from this explicit +/// operation. The exclusive borrow retains the same canonical owner and wake. +/// This does not implement `xe_uc_sanitize_reset` or establish whole-device DMA +/// quiescence, CT/job drain, firmware authentication or GGTT readiness. Drop +/// performs no reset, rollback, sleep or implicit cleanup. +pub struct Handshake<'device> { + _device: &'device mut Device, + result: NativeResult, +} +impl<'device> Handshake<'device> { + pub(super) fn from_native(device: &'device mut Device, result: NativeResult) -> Self { + Self { + _device: device, + result, + } + } + pub fn writes_issued(&self) -> u32 { + self.result.writes + } + pub fn gdrst_observed(&self) -> u32 { + self.result.gdrst + } + pub fn guc_status_observed(&self) -> u32 { + self.result.guc_status + } +} diff --git a/crates/stela-drivers/src/gpu/intel/pat.rs b/crates/stela-drivers/src/gpu/intel/pat.rs new file mode 100644 index 0000000000..c6976bc9cd --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/pat.rs @@ -0,0 +1,48 @@ +//! Original direct XeLP PAT writes, bound to a live actual Device epoch. +use super::activation::Device; +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) struct NativeResult { + pub writes: u32, + pub n_entries: u32, + pub cache_none: u16, + pub cache_wt: u16, + pub cache_wb: u16, + pub cache_none_compression: u16, + pub cache_wb_compression: u16, + pub reserved: u16, + pub entries: [u32; 4], +} +const _: () = assert!(core::mem::size_of::() == 36); +const _: () = assert!(core::mem::offset_of!(NativeResult, entries) == 20); +/// Exact original issued sequence and cache policy. The borrow retains the real +/// epoch; this is not an installed/ACK/READY, PTE, DMA or reset-survival token. +/// Drop performs no implicit rollback, sleep or cleanup. Subsequent bootstrap +/// must use this same Device, not a copied numeric index or success boolean. +pub struct Programming<'device> { + _device: &'device mut Device, + result: NativeResult, +} +impl<'device> Programming<'device> { + pub(super) fn from_native(device: &'device mut Device, result: NativeResult) -> Self { + Self { + _device: device, + result, + } + } + pub fn writes_issued(&self) -> u32 { + self.result.writes + } + pub fn entries(&self) -> &[u32; 4] { + &self.result.entries + } + pub fn cache_none(&self) -> u16 { + self.result.cache_none + } + pub fn cache_wt(&self) -> u16 { + self.result.cache_wt + } + pub fn cache_wb(&self) -> u16 { + self.result.cache_wb + } +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/Makefile b/crates/stela-drivers/src/gpu/intel/stela/Makefile index 37277bc6ab..fad772d7a8 100644 --- a/crates/stela-drivers/src/gpu/intel/stela/Makefile +++ b/crates/stela-drivers/src/gpu/intel/stela/Makefile @@ -37,6 +37,7 @@ COMPUTE_OBJECTS := $(addprefix $(BUILD)/compute-gen,$(addsuffix .o,$(COMPUTE_GEN HOST_COMPUTE_OBJECTS := $(addprefix $(BUILD)/host-compute-gen,$(addsuffix .o,$(COMPUTE_GENERATIONS))) .SECONDARY: $(COMPUTE_HEADERS) OBJECTS += $(BUILD)/compute_dispatch.o $(COMPUTE_OBJECTS) +OBJECTS += $(BUILD)/activation.o $(BUILD)/firmware.o $(BUILD)/wopcm.o $(BUILD)/ggtt_probe.o $(BUILD)/pat.o $(BUILD)/guc_reset.o PACKER_GENERATIONS := 120 125 200 300 350 I915_PACKER_GENERATIONS := 60 70 75 80 90 110 @@ -58,6 +59,51 @@ $(BUILD)/commands.o: $(SOURCE)/commands.c | $(BUILD) $(BUILD)/ct.o: $(SOURCE)/ct.c | $(BUILD) $(CC) $(CFLAGS) -MD -MP -c "$<" -o "$@" +ACTIVATION_HEADERS := $(SOURCE)/activation.h $(wildcard $(SOURCE)/../xe/xe_*core.h \ + $(SOURCE)/../xe/xe_*types.h $(SOURCE)/../xe/xe_pci*.h $(SOURCE)/../xe/xe_mmio_poll.h \ + $(SOURCE)/../xe/xe_engine_ids.h $(SOURCE)/../xe/xe_force_wake_gt.h $(SOURCE)/wopcm.h $(SOURCE)/pat.h $(SOURCE)/guc_reset.h \ + $(SOURCE)/../xe/regs/*.h) $(SOURCE)/../../common/linux/include/drm/intel/pciids.h +$(BUILD)/activation.o: $(SOURCE)/activation.c $(ACTIVATION_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" + +.PHONY: activation test-activation test-activation-donor +activation: $(BUILD)/activation.o + +$(BUILD)/activation-test: $(SOURCE)/tests/activation.c $(SOURCE)/activation.c $(ACTIVATION_HEADERS) $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include "$<" $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o -lpthread -o "$@" + +test-activation: $(BUILD)/activation-test + $(BUILD)/activation-test + +# Immutable pre-extraction source object; override deliberately when updating +# retained driver source. This compiles actual donor loop fragments, not a +# handwritten oracle or a second shipping algorithm. No Linux runtime shim. +ACTIVATION_DONOR_BLOB ?= 197e2197bd0a300e4e83e5653b07eb861b39c6e2 +$(BUILD)/activation-donor/donor-get.inc: | $(BUILD) + mkdir -p "$(BUILD)/activation-donor" + git -C "$(SOURCE)" show $(ACTIVATION_DONOR_BLOB) | \ + sed -n '/^\tref_rqst = (domains == XE_FORCEWAKE_ALL)/,/^\tspin_unlock_irqrestore/{ /^\tspin_.*irq/d; p; }' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/activation-donor/donor-put.inc: | $(BUILD) + mkdir -p "$(BUILD)/activation-donor" + git -C "$(SOURCE)" show $(ACTIVATION_DONOR_BLOB) | \ + sed -n '/^void xe_force_wake_put(/,/^const char \*xe_force_wake_domain_to_str/p' | \ + sed -n '/^\tfor_each_fw_domain_masked(domain, fw_ref/,/^\tspin_unlock_irqrestore/{ /^\tspin_.*irq/d; p; }' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/activation-donor-reference.o: $(SOURCE)/tests/activation_donor.c $(SOURCE)/tests/activation_donor.h $(ACTIVATION_HEADERS) \ + $(BUILD)/activation-donor/donor-get.inc $(BUILD)/activation-donor/donor-put.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/activation-donor -c "$<" -o "$@" +$(BUILD)/activation-donor-test: $(SOURCE)/tests/activation.c $(SOURCE)/activation.c $(ACTIVATION_HEADERS) \ + $(BUILD)/activation-donor-reference.o $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o \ + $(BUILD)/activation-donor/donor-get.inc $(BUILD)/activation-donor/donor-put.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -DSTELA_DONOR_CHECK \ + -I$(BUILD)/activation-donor -I$(SOURCE)/../../common/linux/include "$<" \ + $(BUILD)/activation-donor-reference.o $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o -lpthread -o "$@" +test-activation-donor: $(BUILD)/activation-donor-test + $(BUILD)/activation-donor-test + $(BUILD)/i915_commands.o: $(SOURCE)/i915_commands.c | $(BUILD) $(CC) $(CFLAGS) -MD -MP -c "$<" -o "$@" @@ -187,3 +233,327 @@ test: $(BUILD)/test-pt-walk $(BUILD)/test-commands $(BUILD)/test-ct $(BUILD)/tes -include $(OBJECTS:.o=.d) -include $(HOST_DISPATCH_OBJECTS:.o=.d) -include $(HOST_COMPUTE_OBJECTS:.o=.d) + +# Exact original GuC catalog/CSS algorithms; immutable metadata only, no upload. +FIRMWARE_HEADERS := $(SOURCE)/firmware.h $(SOURCE)/../xe/xe_scalar_types.h \ + $(SOURCE)/../xe/xe_platform_types.h $(SOURCE)/../xe/xe_gt_type.h $(SOURCE)/../xe/xe_huc_role.h \ + $(SOURCE)/../xe/xe_uc_fw_types.h $(SOURCE)/../xe/xe_uc_fw_catalog.h \ + $(SOURCE)/../xe/xe_uc_fw_css.h $(SOURCE)/../xe/xe_uc_fw_cpd.h $(SOURCE)/../xe/xe_uc_fw_version.h \ + $(SOURCE)/../xe/abi/uc_fw_abi.h +$(BUILD)/firmware.o: $(SOURCE)/firmware.c $(FIRMWARE_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -MD -MP -c "$<" -o "$@" +.PHONY: firmware test-firmware +firmware: $(BUILD)/firmware.o +FIRMWARE_DONOR_BLOB ?= 3f08a3b54062842f268da77f913aab57c3c09fb4 +$(BUILD)/firmware-donor/donor-fw-defs.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_DONOR_BLOB) | \ + sed -n '/^struct uc_fw_entry {/,/^XE_GUC_FIRMWARE_DEFS(XE_UC_MODULE_FIRMWARE,/p' | \ + sed '$$d' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/firmware-donor/donor-fw-select.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_DONOR_BLOB) | \ + sed -n '/^uc_fw_auto_select(/,/^}/p' | sed '1,2d;$$d' | \ + sed '/^\tstruct xe_gt \*gt =/d; /^\tenum xe_platform p =/d; s/gt->info.type/gt_type/g' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/firmware-donor/donor-fw-css.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_DONOR_BLOB) | \ + sed -n '/^static int guc_read_css_info(/,/^static bool is_cpd_header(/p' | sed '$$d' | \ + sed '/^\tstruct xe_gt \*gt =/d; /^\tstruct xe_device \*xe =/d' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/firmware-donor-reference.o: $(SOURCE)/tests/firmware_donor.c \ + $(SOURCE)/tests/firmware_donor.h $(FIRMWARE_HEADERS) \ + $(BUILD)/firmware-donor/donor-fw-defs.inc $(BUILD)/firmware-donor/donor-fw-select.inc \ + $(BUILD)/firmware-donor/donor-fw-css.inc $(BUILD)/firmware-donor/donor-fw-supported.inc \ + $(BUILD)/firmware-donor/donor-fw-default-status.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/firmware-donor -c "$<" -o "$@" +$(BUILD)/firmware-test: $(SOURCE)/tests/firmware.c $(SOURCE)/firmware.c \ + $(FIRMWARE_HEADERS) $(BUILD)/firmware-donor-reference.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) "$<" $(BUILD)/firmware-donor-reference.o -o "$@" +test-firmware: $(BUILD)/firmware-test + $(BUILD)/firmware-test + +WOPCM_HEADERS := $(SOURCE)/wopcm.h $(SOURCE)/activation.h $(SOURCE)/firmware.h \ + $(SOURCE)/../xe/xe_wopcm_core.h $(SOURCE)/../xe/xe_wopcm_size.h $(SOURCE)/../xe/xe_wopcm_types.h \ + $(SOURCE)/../xe/xe_huc_role.h $(SOURCE)/../xe/xe_mmio_verify.h \ + $(SOURCE)/../xe/regs/xe_guc_regs.h $(SOURCE)/../xe/xe_platform_types.h +$(BUILD)/wopcm.o: $(SOURCE)/wopcm.c $(WOPCM_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" +$(BUILD)/wopcm-host.o: $(SOURCE)/wopcm.c $(WOPCM_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" +$(BUILD)/firmware-host.o: $(SOURCE)/firmware.c $(FIRMWARE_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -MD -MP -c "$<" -o "$@" +.PHONY: wopcm +wopcm: $(BUILD)/activation.o $(BUILD)/firmware.o $(BUILD)/wopcm.o + +WOPCM_DONOR_BLOB ?= fe65ed246775d99973db5ac3552c40003cea9a55 +WOPCM_VERIFY_DONOR_BLOB ?= 8b251c4811472a047e238a9448cbc9d96511cb40 +WOPCM_HUC_DONOR_BLOB ?= 57afe21444b183f298a106e29f0e802d2ce343b3 +$(BUILD)/wopcm-donor/donor-wopcm-constants.inc: | $(BUILD) + mkdir -p "$(BUILD)/wopcm-donor" + git -C "$(SOURCE)" show $(WOPCM_DONOR_BLOB) | \ + sed -n '/^\/\* Default WOPCM size/,/^static inline struct xe_gt \*wopcm_to_gt/p' | \ + sed '$$d' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/wopcm-donor/donor-wopcm-body.inc: | $(BUILD) + mkdir -p "$(BUILD)/wopcm-donor" + git -C "$(SOURCE)" show $(WOPCM_DONOR_BLOB) | \ + sed -n '/^static u32 context_reserved_size/,/^ALLOW_ERROR_INJECTION/p' | sed '$$d' | \ + sed 's/struct xe_device \*/struct stela_wopcm_model */g; s/struct xe_gt \*/struct stela_wopcm_model */g; s/xe->info.platform/xe->platform/g; s/\>->mmio/gt/g; s/xe_uc_fw_get_upload_size(\>->uc.guc.fw)/gt->guc_fw_size/g; s/xe_uc_fw_get_upload_size(\>->uc.huc.fw)/gt->huc_fw_size/g; s/xe_uc_fw_is_available(\>->uc.huc.fw)/stela_wopcm_huc(gt)/g' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/wopcm-donor/donor-verify.inc: | $(BUILD) + mkdir -p "$(BUILD)/wopcm-donor" + git -C "$(SOURCE)" show $(WOPCM_VERIFY_DONOR_BLOB) | \ + sed -n '/^int xe_mmio_write32_and_verify(/,/^bool xe_mmio_in_range(/p' | sed '$$d' | \ + sed 's/struct xe_mmio \*/struct stela_wopcm_model */g' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/wopcm-donor/donor-huc-role.inc: | $(BUILD) + mkdir -p "$(BUILD)/wopcm-donor" + git -C "$(SOURCE)" show $(WOPCM_HUC_DONOR_BLOB) | \ + sed -n '/if (!xe_gt_is_media_type(gt) \&\& GRAPHICS_VERx100(xe) > 1255)/p' | \ + sed 's/if (/return (/; s/) {/);/; s/xe_gt_is_media_type(gt)/media_gt/g; s/GRAPHICS_VERx100(xe)/graphics_verx100/g' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/wopcm-donor-reference.o: $(SOURCE)/tests/wopcm_donor.c $(SOURCE)/tests/wopcm_donor.h \ + $(WOPCM_HEADERS) $(BUILD)/wopcm-donor/donor-wopcm-constants.inc \ + $(BUILD)/wopcm-donor/donor-wopcm-body.inc $(BUILD)/wopcm-donor/donor-verify.inc \ + $(BUILD)/wopcm-donor/donor-huc-role.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include \ + -I$(BUILD)/wopcm-donor -c "$<" -o "$@" +$(BUILD)/wopcm-test: $(SOURCE)/tests/wopcm.c $(SOURCE)/tests/wopcm_donor.h \ + $(WOPCM_HEADERS) $(BUILD)/wopcm-donor-reference.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include \ + "$<" $(BUILD)/wopcm-donor-reference.o -lpthread -o "$@" +.PHONY: test-wopcm +test-wopcm: $(BUILD)/wopcm-test + $(BUILD)/wopcm-test +$(BUILD)/activation-host.o: $(SOURCE)/activation.c $(ACTIVATION_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" +.PHONY: host-activation +host-activation: $(BUILD)/activation-host.o $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o +$(BUILD)/wopcm-owned-test: $(SOURCE)/tests/wopcm_owned.c $(SOURCE)/activation.c \ + $(ACTIVATION_HEADERS) $(WOPCM_HEADERS) $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(SOURCE)/../../common/linux/include \ + "$<" $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o $(BUILD)/guc_reset-host.o -lpthread -o "$@" +.PHONY: test-wopcm-owned +test-wopcm-owned: $(BUILD)/wopcm-owned-test + $(BUILD)/wopcm-owned-test +-include $(BUILD)/activation-host.d $(BUILD)/wopcm-host.d $(BUILD)/firmware-host.d + +FIRMWARE_SUPPORTED_DONOR_BLOB ?= f2d3a3e7208bc1d0351c4f544b006889267d81e4 +$(BUILD)/firmware-donor/donor-fw-supported.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_SUPPORTED_DONOR_BLOB) | \ + sed -n '/^static inline enum xe_uc_fw_status$$/,/^static inline bool xe_uc_fw_is_enabled(/p' | \ + sed '$$d' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/firmware-donor/donor-fw-default-status.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_DONOR_BLOB) | \ + sed -n '/^static int uc_fw_request(/,/^static void uc_fw_release(/p' | \ + sed -n '/^\txe_uc_fw_change_status(uc_fw, uc_fw->path ?$$/,/^\t\/\* an empty path means the firmware is disabled \*\//p' | \ + sed '$$d' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" + +# Same frozen original source as CSS/catalog, with only actual scalar context +# spellings and GSC security-output adapter changed; no fabricated Linux type. +$(BUILD)/firmware-donor/donor-fw-cpd.inc: | $(BUILD) + mkdir -p "$(BUILD)/firmware-donor" + git -C "$(SOURCE)" show $(FIRMWARE_DONOR_BLOB) | \ + sed -n '/^static bool is_cpd_header(/,/^static int parse_gsc_layout(/p' | sed '$$d' | \ + sed '/^ struct xe_gt \*gt =/d; /^ struct xe_device \*xe =/d; /struct xe_gsc \*gsc = container_of/d; s/xe->info.platform/active_platform/g; s/gsc->security_version/(*active_security)/g' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/huc-firmware-donor-reference.o: $(SOURCE)/tests/huc_firmware_donor.c \ + $(SOURCE)/tests/firmware_donor.h $(FIRMWARE_HEADERS) $(BUILD)/firmware-donor/donor-fw-cpd.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/firmware-donor -c "$<" -o "$@" +$(BUILD)/huc-firmware-test: $(SOURCE)/tests/huc_firmware.c $(SOURCE)/firmware.c \ + $(FIRMWARE_HEADERS) $(BUILD)/firmware-donor-reference.o $(BUILD)/huc-firmware-donor-reference.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) "$<" $(BUILD)/firmware-donor-reference.o $(BUILD)/huc-firmware-donor-reference.o -o "$@" +.PHONY: test-huc-firmware +test-huc-firmware: $(BUILD)/huc-firmware-test + $(BUILD)/huc-firmware-test + +GGTT_DEFS := $(BUILD)/ggtt/ggtt_probe_defs.h +GGTT_GMCH_SOURCE := $(SOURCE)/../../common/linux/include/drm/intel/i915_drm.h +GGTT_PAGE_SOURCE := $(SOURCE)/../xe/xe_bo.h +GGTT_SIZE_SOURCE := $(SOURCE)/../../common/linux/include/linux/sizes.h +GGTT_PROBE_HEADERS := $(SOURCE)/ggtt_probe.h $(SOURCE)/../xe/xe_ggtt_probe_core.h \ + $(SOURCE)/../xe/xe_wopcm_size.h $(SOURCE)/../xe/regs/xe_gtt_defs.h \ + $(SOURCE)/../xe/xe_scalar_types.h $(SOURCE)/../xe/xe_platform_types.h $(GGTT_DEFS) +$(GGTT_DEFS): $(GGTT_GMCH_SOURCE) $(GGTT_PAGE_SOURCE) $(GGTT_SIZE_SOURCE) | $(BUILD) + mkdir -p "$(BUILD)/ggtt" + sed -n '1,/^#ifndef _I915_DRM_H_/p' "$(GGTT_GMCH_SOURCE)" | sed '$$d' > "$@.tmp" + sed -n '/^#define SNB_GMCH_CTRL[[:space:]]/p; /^#define BDW_GMCH_GGMS_SHIFT[[:space:]]/p; /^#define BDW_GMCH_GGMS_MASK[[:space:]]/p' "$(GGTT_GMCH_SOURCE)" >> "$@.tmp" + sed -n '/^#define XE_PTE_SHIFT[[:space:]]/p; /^#define XE_PAGE_SIZE[[:space:]]/p; /^#define XE_PTE_MASK[[:space:]]/p' "$(GGTT_PAGE_SOURCE)" >> "$@.tmp" + sed -n '/^#define SZ_1M[[:space:]]/p; /^#define SZ_8M[[:space:]]/p; /^#define SZ_2M[[:space:]]/p' "$(GGTT_SIZE_SOURCE)" >> "$@.tmp" + test "$$(sed -n '/^#define /p' "$@.tmp" | wc -l | tr -d ' ')" = 9 + mv "$@.tmp" "$@" +$(BUILD)/ggtt_probe.o: $(SOURCE)/ggtt_probe.c $(GGTT_PROBE_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -I$(BUILD)/ggtt -MD -MP -c "$<" -o "$@" +$(BUILD)/ggtt_probe-host.o: $(SOURCE)/ggtt_probe.c $(GGTT_PROBE_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/ggtt -MD -MP -c "$<" -o "$@" +.PHONY: ggtt-probe ggtt-probe-headers host-ggtt-probe +ggtt-probe-headers: $(GGTT_DEFS) +ggtt-probe: $(BUILD)/ggtt_probe.o +host-ggtt-probe: $(BUILD)/ggtt_probe-host.o +-include $(BUILD)/ggtt_probe.d $(BUILD)/ggtt_probe-host.d + +# Frozen complete original Xe GGTT source. No fake Linux TU or MMIO provider: +# only unchanged scalar algorithms/assertions are compiled in the donor object. +GGTT_DONOR_BLOB ?= a351c578b17055b31d03f5cbf8ba06a71590c624 +$(BUILD)/ggtt/donor-gsm-decode.inc: | $(BUILD) + mkdir -p "$(BUILD)/ggtt" + git -C "$(SOURCE)" show $(GGTT_DONOR_BLOB) | \ + sed -n '/^static unsigned int probe_gsm_size(/,/^}/p' | \ + sed -n '/^\tggms = /,/^\treturn /p' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/ggtt/donor-pf-range.inc: | $(BUILD) + mkdir -p "$(BUILD)/ggtt" + git -C "$(SOURCE)" show $(GGTT_DONOR_BLOB) | \ + sed -n '/^\t\tggtt_start = wopcm;$$/,+1p' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/ggtt/donor-range-clamp.inc: | $(BUILD) + mkdir -p "$(BUILD)/ggtt" + git -C "$(SOURCE)" show $(GGTT_DONOR_BLOB) | \ + sed -n '/^\tif (ggtt_size + ggtt_start > GUC_GGTT_TOP)$$/,+1p' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/ggtt/donor-pte-index.inc: | $(BUILD) + mkdir -p "$(BUILD)/ggtt" + git -C "$(SOURCE)" show $(GGTT_DONOR_BLOB) | \ + sed -n '/^static u64 xe_ggtt_get_pte(/,/^}/p' | \ + sed -n '/^\txe_tile_assert/,/^\treturn /p' | \ + sed 's/xe_tile_assert(ggtt->tile, /assert(/g; s/ggtt->start/start/g; s/ggtt->size/size/g; s/readq(\&ggtt->gsm\[addr >> XE_PTE_SHIFT\])/addr >> XE_PTE_SHIFT/' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/ggtt-donor.o: $(SOURCE)/tests/ggtt_probe_donor.c $(SOURCE)/tests/ggtt_probe_donor.h \ + $(GGTT_PROBE_HEADERS) $(BUILD)/ggtt/donor-gsm-decode.inc $(BUILD)/ggtt/donor-pf-range.inc \ + $(BUILD)/ggtt/donor-range-clamp.inc $(BUILD)/ggtt/donor-pte-index.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/ggtt -c "$<" -o "$@" +$(BUILD)/ggtt-probe-test: $(SOURCE)/tests/ggtt_probe.c $(SOURCE)/tests/ggtt_probe_donor.h \ + $(GGTT_PROBE_HEADERS) $(BUILD)/ggtt-donor.o $(BUILD)/ggtt_probe-host.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/ggtt "$<" \ + $(BUILD)/ggtt-donor.o $(BUILD)/ggtt_probe-host.o -o "$@" +.PHONY: test-ggtt-probe +test-ggtt-probe: $(BUILD)/ggtt-probe-test + $(BUILD)/ggtt-probe-test + +# Exact Linux compile-time definitions only. Active _Static_assert is retained; +# actual pick.h supplies address math, without compiler/percpu/runtime imports. +PAT_COMPILE_DEFS := $(BUILD)/pat/pat_compile_defs.h +PAT_COMPILER := $(SOURCE)/../../common/linux/include/linux/compiler.h +PAT_BUILD_BUG := $(SOURCE)/../../common/linux/include/linux/build_bug.h +$(PAT_COMPILE_DEFS): $(PAT_COMPILER) $(PAT_BUILD_BUG) | $(BUILD) + mkdir -p "$(BUILD)/pat" + sed -n '1p' "$(PAT_COMPILER)" > "$@.tmp" + sed -n '/^#define __BUILD_BUG_ON_ZERO_MSG.*_Static_assert/p' "$(PAT_COMPILER)" >> "$@.tmp" + awk '/^#define __is_constexpr\(/ { active = 1 } active { print; if ($$0 !~ /\\$$/) exit }' "$(PAT_COMPILER)" >> "$@.tmp" + awk '/^#define BUILD_BUG_ON_ZERO\(/ { active = 1 } active { print; if ($$0 !~ /\\$$/) exit }' "$(PAT_BUILD_BUG)" >> "$@.tmp" + test "$$(sed -n '/^#define /p' "$@.tmp" | wc -l | tr -d ' ')" = 3 + rg '_Static_assert' "$@.tmp" >/dev/null + mv "$@.tmp" "$@" +PAT_HEADERS := $(SOURCE)/pat.h $(SOURCE)/activation.h $(SOURCE)/../xe/xe_pat.h \ + $(SOURCE)/../xe/xe_pat_tables.h $(SOURCE)/../xe/xe_pat_select.h \ + $(SOURCE)/../xe/xe_pat_program.h $(SOURCE)/../xe/xe_cache_level.h \ + $(SOURCE)/../xe/xe_gt_type.h $(PAT_COMPILE_DEFS) \ + $(SOURCE)/../../common/linux/include/drm/intel/pick.h +$(BUILD)/pat.o: $(SOURCE)/pat.c $(PAT_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -I$(BUILD)/pat -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" +$(BUILD)/pat-host.o: $(SOURCE)/pat.c $(PAT_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/pat -I$(SOURCE)/../../common/linux/include -MD -MP -c "$<" -o "$@" +.PHONY: pat host-pat pat-headers +pat: $(BUILD)/pat.o +host-pat: $(BUILD)/pat-host.o +pat-headers: $(PAT_COMPILE_DEFS) +-include $(BUILD)/pat.d $(BUILD)/pat-host.d +PAT_DONOR_BLOB ?= fad5b5a5ed4a0ca256a98168e4beda1dab3f5bd5 +$(BUILD)/pat/donor-pat-tables.inc: | $(BUILD) + mkdir -p "$(BUILD)/pat" + git -C "$(SOURCE)" show $(PAT_DONOR_BLOB) | sed -n '/^#define _PAT_ATS/,/^#define PAT_LABEL_LEN/{ /^#define PAT_LABEL_LEN/d; p; }' > "$@" + git -C "$(SOURCE)" show $(PAT_DONOR_BLOB) | sed -n '/^static const struct xe_pat_table_entry xelp_pat_table\[\]/,/^u16 xe_pat_index_get_coh_mode/{ /^u16 xe_pat_index_get_coh_mode/d; p; }' >> "$@" +$(BUILD)/pat/donor-pat-select.inc: | $(BUILD) + mkdir -p "$(BUILD)/pat" + git -C "$(SOURCE)" show $(PAT_DONOR_BLOB) | sed -n '/^void xe_pat_init_early(/,/^void xe_pat_init(/{ /^void xe_pat_init(/d; p; }' > "$@" +$(BUILD)/pat/donor-pat-program.inc: | $(BUILD) + mkdir -p "$(BUILD)/pat" + git -C "$(SOURCE)" show $(PAT_DONOR_BLOB) | sed -n '/^static void program_pat(/,/^static void program_pat_mcr(/{ /^static void program_pat_mcr(/d; p; }' > "$@" +PAT_DONOR_HEADERS := $(SOURCE)/tests/pat_donor.h $(PAT_HEADERS) \ + $(BUILD)/pat/donor-pat-tables.inc $(BUILD)/pat/donor-pat-select.inc $(BUILD)/pat/donor-pat-program.inc $(BUILD)/pat/current-pat-wrapper.inc +$(BUILD)/pat-donor.o: $(SOURCE)/tests/pat_donor.c $(PAT_DONOR_HEADERS) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/pat -I$(SOURCE)/../../common/linux/include -c "$<" -o "$@" +$(BUILD)/pat-test: $(SOURCE)/tests/pat.c $(PAT_DONOR_HEADERS) $(BUILD)/pat-donor.o $(BUILD)/pat-host.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/pat -I$(SOURCE)/../../common/linux/include "$<" $(BUILD)/pat-donor.o $(BUILD)/pat-host.o -o "$@" +.PHONY: test-pat +test-pat: $(BUILD)/pat-test + $(BUILD)/pat-test + +$(BUILD)/pat/current-pat-wrapper.inc: $(SOURCE)/../xe/xe_pat.c | $(BUILD) + mkdir -p "$(BUILD)/pat" + sed -n '/^#define XE_PAT_SELECT_WARN(/,/^void xe_pat_init(/{ /^void xe_pat_init(/d; p; }' "$<" > "$@" + +# Unmodified original OOB generator and complete output; select its actual reset +# entry for a compile-time exclusion proof, not a handwritten native WA table. +$(BUILD)/guc-reset/xe_gen_wa_oob: $(SOURCE)/../xe/xe_gen_wa_oob.c | $(BUILD) + mkdir -p "$(BUILD)/guc-reset" + $(HOST_CC) -std=gnu11 -O2 -Wall -Wextra -Werror "$<" -o "$@" +$(BUILD)/guc-reset/xe_wa_oob.c: $(SOURCE)/../xe/xe_wa_oob.rules $(BUILD)/guc-reset/xe_gen_wa_oob + $(BUILD)/guc-reset/xe_gen_wa_oob "$<" "$(BUILD)/guc-reset/xe_wa_oob.c" "$(BUILD)/guc-reset/xe_wa_oob.h" +$(BUILD)/guc-reset/guc_reset_wa.inc: $(BUILD)/guc-reset/xe_wa_oob.c + sed -n '/^{ XE_RTP_NAME("14025883347"),/,/) },/p' "$<" > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +GUC_RESET_HEADERS := $(SOURCE)/guc_reset.h $(SOURCE)/activation.h $(SOURCE)/../xe/xe_guc_reset_core.h \ + $(SOURCE)/../xe/xe_mmio_poll.h $(SOURCE)/../xe/xe_scalar_types.h $(SOURCE)/../xe/xe_gt_type.h \ + $(SOURCE)/../xe/xe_force_wake_domain_types.h $(SOURCE)/../xe/regs/xe_gt_regs.h \ + $(SOURCE)/../xe/regs/xe_guc_regs.h $(SOURCE)/../xe/abi/guc_errors_abi.h \ + $(BUILD)/guc-reset/guc_reset_wa.inc +$(BUILD)/guc_reset.o: $(SOURCE)/guc_reset.c $(GUC_RESET_HEADERS) | $(BUILD) + $(CC) $(CFLAGS) -I$(BUILD)/guc-reset -MD -MP -c "$<" -o "$@" +$(BUILD)/guc_reset-host.o: $(SOURCE)/guc_reset.c $(GUC_RESET_HEADERS) | $(BUILD) + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/guc-reset -MD -MP -c "$<" -o "$@" +.PHONY: guc-reset host-guc-reset +guc-reset: $(BUILD)/guc_reset.o +host-guc-reset: $(BUILD)/guc_reset-host.o +-include $(BUILD)/guc_reset.d $(BUILD)/guc_reset-host.d + +GUC_RESET_DONOR_BLOB ?= 4023700ff2a9678f6168d776b49c892adc8a58e5 +$(BUILD)/guc-reset/guc-reset-donor.inc: | $(BUILD) + mkdir -p "$(BUILD)/guc-reset" + git -C "$(SOURCE)" show $(GUC_RESET_DONOR_BLOB) | sed -n '/^static void guc_prevent_fw_dma_failure_on_reset(/,/^static void guc_prepare_xfer(/{ /^static void guc_prepare_xfer(/d; p; }' > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +$(BUILD)/guc-reset/guc-reset-linux.inc: $(SOURCE)/../xe/xe_guc.c | $(BUILD) + mkdir -p "$(BUILD)/guc-reset" + sed -n '/^#define XE_GUC_RESET_CONTEXT /,/^static void guc_prepare_xfer(/{ /^static void guc_prepare_xfer(/d; p; }' "$<" > "$@.tmp" + test -s "$@.tmp" + mv "$@.tmp" "$@" +GUC_RESET_TEST_HEADERS := $(SOURCE)/tests/guc_reset_model.h $(SOURCE)/tests/guc_reset_bind.h $(GUC_RESET_HEADERS) +$(BUILD)/guc-reset-donor.o: $(SOURCE)/tests/guc_reset_donor.c $(GUC_RESET_TEST_HEADERS) $(BUILD)/guc-reset/guc-reset-donor.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/guc-reset -c "$<" -o "$@" +$(BUILD)/guc-reset-linux.o: $(SOURCE)/tests/guc_reset_linux.c $(GUC_RESET_TEST_HEADERS) $(BUILD)/guc-reset/guc-reset-linux.inc + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/guc-reset -c "$<" -o "$@" +$(BUILD)/guc-reset-test: $(SOURCE)/tests/guc_reset.c $(GUC_RESET_TEST_HEADERS) $(BUILD)/guc-reset-donor.o \ + $(BUILD)/guc-reset-linux.o $(BUILD)/guc_reset-host.o $(BUILD)/activation-host.o \ + $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o + $(HOST_CC) $(HOST_CFLAGS) $(SANITIZE) -I$(BUILD)/guc-reset "$<" \ + $(BUILD)/guc-reset-donor.o $(BUILD)/guc-reset-linux.o $(BUILD)/guc_reset-host.o \ + $(BUILD)/activation-host.o $(BUILD)/wopcm-host.o $(BUILD)/firmware-host.o $(BUILD)/pat-host.o -o "$@" +.PHONY: test-guc-reset +test-guc-reset: $(BUILD)/guc-reset-test + $(BUILD)/guc-reset-test + +# Focused retained red-black tree pointer-width proof; no GPU activation. +include $(SOURCE)/tests/rbtree.mk diff --git a/crates/stela-drivers/src/gpu/intel/stela/activation.c b/crates/stela-drivers/src/gpu/intel/stela/activation.c new file mode 100644 index 0000000000..d8bb06f46e --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/activation.c @@ -0,0 +1,314 @@ +/* SPDX-License-Identifier: MIT */ +/* Owned native integration; original Xe notices remain in shared headers. */ +#include "activation.h" +#include "wopcm.h" +#include "pat.h" +#include "guc_reset.h" +#include "../xe/xe_gt_type.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_pci_types.h" +#include "../xe/xe_engine_ids.h" +#include "../xe/regs/xe_gt_regs.h" +#include "../xe/regs/xe_regs.h" +#include "../xe/xe_force_wake_domain_types.h" + +/* Port only scalar/diagnostic spelling. There is no kernel service shim. */ +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define __maybe_unused __attribute__((unused)) +#define __diag_push() +#define __diag_pop() +#define __diag_ignore_all(a, b) +#define for_each_if(condition) if (!(condition)) {} else +#define ffs(value) __builtin_ffs((int)(value)) +#define EIO 5 +#ifdef ETIMEDOUT +#undef ETIMEDOUT +#endif +#define ETIMEDOUT 110 +#include "../xe/xe_force_wake_core.h" +#include "../xe/xe_force_wake_gt.h" + +/* Same entire original ID/descriptor block, including class filters/order. + * This is a native table row, not a fabricated Linux pci_dev/device object. */ +struct stela_intel_pci_match { + uint32_t vendor, device, class, class_mask; + const struct xe_device_desc *driver_data; +}; +#define XE_PCI_ID_TYPE struct stela_intel_pci_match +#define INTEL_PCI_DEVICE(id, info) {.vendor = 0x8086, .device = (id), .driver_data = (info)} +#define INTEL_VGA_DEVICE(id, info) {.vendor = 0x8086, .device = (id), .class = 0x030000, \ + .class_mask = 0xff0000, .driver_data = (info)} +#include +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Winitializer-overrides" +#include "../xe/xe_pci_device_info.h" +#pragma clang diagnostic ignored "-Wsign-compare" +#include "../xe/xe_pci_runtime.h" +#pragma clang diagnostic pop + +struct stela_intel_activation { + const struct stela_intel_activation_io *io; + void *context; + uint64_t bar_bytes; + struct stela_intel_activation_facts facts; + struct xe_force_wake_domain domains[XE_FW_DOMAIN_ID_COUNT]; + int wait_error; + bool poisoned; + bool wopcm_uncertain; + bool wopcm_prepared; + bool pat_sequence_issued; + bool guc_reset_issued, guc_reset_uncertain; +}; + +size_t stela_intel_activation_size(void) { return sizeof(struct stela_intel_activation); } +size_t stela_intel_activation_alignment(void) { return _Alignof(struct stela_intel_activation); } + +static bool valid_io(const struct stela_intel_activation_io *io) +{ + return io && io->check_context && io->prepare && io->read32 && io->write32 && io->now_ns && io->delay_us && + io->invariant && io->report; +} +static int descriptor(uint32_t vendor, uint32_t device, uint32_t pci_class, + bool vf, bool force_probe, const struct xe_device_desc **out) +{ + if (vendor > UINT16_MAX || device > UINT16_MAX || pci_class > 0xffffff) return -22; + if (vf) return -95; + for (size_t i = 0; i < ARRAY_SIZE(pciidlist); ++i) { + const struct stela_intel_pci_match *row = &pciidlist[i]; + if (!row->driver_data) break; /* Original PCI table terminator. */ + if (row->vendor == vendor && row->device == device && + !((row->class ^ pci_class) & row->class_mask)) { + if (row->driver_data->require_force_probe && !force_probe) return -95; + *out = row->driver_data; + return 0; + } + } + return -19; +} +int stela_intel_activation_match(uint32_t vendor, uint32_t device, uint32_t pci_class, + bool vf, bool force_probe) +{ + const struct xe_device_desc *matched; + return descriptor(vendor, device, pci_class, vf, force_probe, &matched); +} + +static uint32_t read32(struct stela_intel_activation *state, struct xe_reg reg) +{ + state->io->invariant(state->context, !(reg.addr & 3) && (uint64_t)reg.addr + 4 <= SZ_4M); + return state->io->read32(state->context, reg.addr); +} + +static int64_t add_us(int64_t time, int64_t us) { return time + us * 1000; } +#define XE_MMIO_POLL_NAME poll32 +#define XE_MMIO_POLL_CONTEXT struct stela_intel_activation +#define XE_MMIO_POLL_TIME int64_t +#define XE_MMIO_POLL_NOW(mmio) ((mmio)->io->now_ns((mmio)->context)) +#define XE_MMIO_POLL_ADD_US add_us +#define XE_MMIO_POLL_READ read32 +#define XE_MMIO_POLL_BEFORE(a, b) ((a) < (b)) +#define XE_MMIO_POLL_AFTER(a, b) ((a) > (b)) +#define XE_MMIO_POLL_DELTA_US(a, b) (((a) - (b)) / 1000) +#define XE_MMIO_POLL_DELAY(mmio, wait, atomic) \ + (mmio)->io->delay_us((mmio)->context, (uint32_t)(wait), \ + (uint32_t)((atomic) ? (wait) : ((wait) << 1)), (atomic)) +#include "../xe/xe_mmio_poll.h" + +int stela_intel_activation_init(void *storage, size_t bytes, + const struct stela_intel_activation_io *io, void *context, uint32_t vendor, + uint32_t device, uint32_t pci_class, uint32_t revision, uint64_t bar_bytes, + bool vf, bool force_probe) +{ + if (!storage || bytes < sizeof(struct stela_intel_activation) || + (uintptr_t)storage % _Alignof(struct stela_intel_activation) || !valid_io(io) || + vendor > UINT16_MAX || device > UINT16_MAX || pci_class > 0xffffff || revision > UINT8_MAX) + return -22; + const struct xe_device_desc *desc = NULL; + int ret = descriptor(vendor, device, pci_class, vf, force_probe, &desc); + if (ret) return ret; + if (bar_bytes < 16 * 1024 * 1024) return -22; + ret = io->check_context(context); + if (ret) return ret; + ret = io->prepare(context, (uint32_t)desc->platform, revision, desc->is_dgfx); + if (ret) return ret; + int64_t time = io->now_ns(context); + if (time < 0 || time > INT64_MAX - INT64_C(100000000)) return -22; + struct stela_intel_activation candidate = {.io = io, .context = context, .bar_bytes = bar_bytes}; + const struct xe_ip *graphics = desc->pre_gmdid_graphics_ip, *media = desc->pre_gmdid_media_ip; + uint32_t graphics_revision = revision, media_revision = revision; + if (!graphics) { + uint32_t version, value = read32(&candidate, xe_pci_gmdid_register(false)); + if (value == UINT32_MAX) return -19; + xe_pci_decode_gmdid(value, &version, &graphics_revision); + graphics = find_graphics_ip(version); + if (!graphics) return -95; + value = read32(&candidate, xe_pci_gmdid_register(true)); + if (value == UINT32_MAX) return -19; + xe_pci_decode_gmdid(value, &version, &media_revision); + media = version ? find_media_ip(version) : NULL; + if (version && !media) return -95; + } + uint8_t tiles = (uint8_t)(1 + desc->max_remote_tiles); + if (tiles > 1) { + uint32_t value = read32(&candidate, XEHP_MTCFG_ADDR); + if (value == UINT32_MAX) return -19; + tiles = xe_pci_runtime_tile_count(tiles, value); + if (!tiles) return -19; + } + if ((uint64_t)tiles * 16 * 1024 * 1024 > bar_bytes) return -22; + const struct xe_subplatform_desc *sub = find_subplatform(desc, (u16)device); + candidate.facts = (struct stela_intel_activation_facts){ + .platform = (uint32_t)desc->platform, + .subplatform = sub ? (uint32_t)sub->subplatform : XE_SUBPLATFORM_NONE, + .graphics_verx100 = graphics->verx100, .media_verx100 = media ? media->verx100 : 0, + .graphics_revision = graphics_revision, .media_revision = media_revision, + .pci_revision = revision, .tile_count = tiles, .dma_bits = desc->dma_mask_size, + .va_bits = desc->va_bits, .max_gt_per_tile = desc->max_gt_per_tile, + .discrete = desc->is_dgfx, .force_probe_required = desc->require_force_probe, + .gt_control = FORCEWAKE_GT.addr, .gt_ack = xe_force_wake_gt_ack(graphics->verx100).addr, + .initialized = (uint32_t)XE_FW_GT, + .has_llc = desc->has_llc, + /* Same root-primary construction as original alloc_primary_gt; media + * IP discovery does not construct a separate media GT in this API. */ + .gt_type = XE_GT_TYPE_MAIN, + }; + xe_force_wake_domain_init(&candidate.domains[XE_FW_DOMAIN_ID_GT], XE_FW_DOMAIN_ID_GT, + FORCEWAKE_GT, xe_force_wake_gt_ack(graphics->verx100)); + *(struct stela_intel_activation *)storage = candidate; + return 0; +} + +int stela_intel_activation_facts(const struct stela_intel_activation *state, + struct stela_intel_activation_facts *facts) +{ + if (!state || !facts || !valid_io(state->io)) return -22; + if (state->wopcm_uncertain || state->guc_reset_uncertain) return -5; + int context_status = state->io->check_context(state->context); + if (context_status) return context_status; + *facts = state->facts; + return 0; +} + +static void control(void *context, struct xe_force_wake_domain *domain, bool wake) +{ + struct stela_intel_activation *state = context; + state->io->write32(state->context, domain->reg_ctl.addr, xe_force_wake_control(domain, wake)); +} +static int wait(void *context, struct xe_force_wake_domain *domain, bool wake) +{ + struct stela_intel_activation *state = context; + uint32_t value; + int status = poll32(state, domain->reg_ack, domain->val, wake ? domain->val : 0, + XE_FORCE_WAKE_ACK_TIMEOUT_MS * 1000, &value, true, true); + status = xe_force_wake_wait_status(status, value); + state->io->report(state->context, (uint32_t)XE_FW_GT, wake, status, value); + if (status) state->wait_error = status; + return status; +} +static void invariant(void *context, bool condition) +{ + struct stela_intel_activation *state = context; + state->io->invariant(state->context, condition); +} +static struct xe_force_wake_core core(struct stela_intel_activation *state) +{ + static const struct xe_force_wake_core_ops ops = {control, wait, invariant}; + return (struct xe_force_wake_core){state, &ops, state->facts.initialized, + &state->facts.awake, state->domains}; +} +int stela_intel_activation_wake(struct stela_intel_activation *state) +{ + if (!state || !valid_io(state->io)) return -22; + int context_status = state->io->check_context(state->context); + if (context_status) return context_status; + if (state->poisoned) return -5; + if (state->domains[XE_FW_DOMAIN_ID_GT].ref == UINT32_MAX) return -22; + struct xe_force_wake_core fw = core(state); + unsigned failed; + state->wait_error = 0; + unsigned ref = xe_force_wake_get_locked(&fw, (unsigned)XE_FW_GT, &failed); + if (failed || !ref) { state->poisoned = true; return state->wait_error ? state->wait_error : -110; } + return 0; +} +int stela_intel_activation_sleep(struct stela_intel_activation *state) +{ + if (!state || !valid_io(state->io)) return -22; + int context_status = state->io->check_context(state->context); + if (context_status) return context_status; + if (state->poisoned) return -5; + if (!state->domains[XE_FW_DOMAIN_ID_GT].ref) return -22; + struct xe_force_wake_core fw = core(state); + state->wait_error = 0; + if (xe_force_wake_put_locked(&fw, (unsigned)XE_FW_GT)) { + state->poisoned = true; return state->wait_error ? state->wait_error : -110; + } + return 0; +} + +void stela_intel_activation_assert_gt(struct stela_intel_activation *state) +{ + state->io->invariant(state->context, + !state->poisoned && !state->wopcm_uncertain && + state->domains[XE_FW_DOMAIN_ID_GT].ref > 0 && + (state->facts.awake & (uint32_t)XE_FW_GT) != 0); +} +int stela_intel_activation_wopcm(struct stela_intel_activation *state, + const uint8_t *bytes, size_t size, struct stela_intel_wopcm_result *out) +{ + if (!out) return -22; + *out = (struct stela_intel_wopcm_result){0}; + if (!state || !valid_io(state->io)) return -22; + if (state->poisoned || state->wopcm_uncertain) return -5; + if (state->wopcm_prepared) return -114; + if (!state->domains[XE_FW_DOMAIN_ID_GT].ref || + !(state->facts.awake & (uint32_t)XE_FW_GT)) return -22; + int status = state->io->check_context(state->context); + if (status) return status; + status = stela_intel_wopcm_prepare(state->io, state->context, state, + state->facts.platform, state->facts.graphics_verx100, state->facts.discrete != 0, + bytes, size, out); + if (status && out->writes) { + /* Writes can have partially locked the hardware. There is no rollback, + * sleep/drain/reset release or future access in this native epoch. */ + state->wopcm_uncertain = true; + state->poisoned = true; + } + if (!status) state->wopcm_prepared = true; + return status; +} + +int stela_intel_activation_pat(struct stela_intel_activation *state, + struct stela_intel_pat_result *out) +{ + if (!state || !out || !valid_io(state->io)) return -22; + if (state->poisoned || state->wopcm_uncertain) return -5; + if (state->pat_sequence_issued || state->wopcm_prepared) return -114; + if (!state->domains[XE_FW_DOMAIN_ID_GT].ref || + !(state->facts.awake & (uint32_t)XE_FW_GT)) return -22; + int status = state->io->check_context(state->context); + if (status) return status; + status = stela_intel_pat_program(state->io, state->context, &state->facts, out); + if (!status) state->pat_sequence_issued = true; /* Issued, never an ACK. */ + return status; +} + +int stela_intel_activation_guc_reset(struct stela_intel_activation *state, + struct stela_intel_guc_reset_result *out) +{ + if (!state || !out || !valid_io(state->io)) return -22; + if (state->poisoned || state->wopcm_uncertain || state->guc_reset_uncertain) return -5; + if (state->guc_reset_issued) return -114; + if (!state->domains[XE_FW_DOMAIN_ID_GT].ref || + !(state->facts.awake & (uint32_t)XE_FW_GT)) return -22; + int status = state->io->check_context(state->context); + if (status) return status; + struct stela_intel_guc_reset_result result = {0}; + status = stela_intel_guc_reset(state->io, state->context, state, &state->facts, &result); + if (status && result.writes) { + /* No safe sleep/drain/owner release after an uncertain reset effect. */ + state->guc_reset_uncertain = true; + state->poisoned = true; + } + if (!status) state->guc_reset_issued = true; + if (!status || result.writes) *out = result; + return status; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/activation.h b/crates/stela-drivers/src/gpu/intel/stela/activation.h new file mode 100644 index 0000000000..3c6a7a8a42 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/activation.h @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_ACTIVATION_H +#define STELA_INTEL_ACTIVATION_H +#include +#include +#include + +/* Native PF-only probe. All callbacks are mandatory real owner operations. + * prepare holds actual PCI D0/bridge/reset/exclusive/no-IRQ/no-DMA ownership, + * applies required original WA and PCODE/lmem readiness, and qualifies MMIO + * ordering and the monotonic nanosecond clock/sleep context. It may refuse; + * it is not a boolean substitute for those effects. Retain that owner and the + * canonical UC Mapping/View until explicit acknowledged retirement. No guest + * pointers or hardware activation occur merely by constructing this table. + * read/write access only bounded canonical UC CPU mappings, actual width32; + * writes order all required preceding accesses, reads honor original WA read + * flushing. delay preserves atomic vs sleepable context, never substitutes a + * 3-minute spin for a sleepable PCODE wait. invariant must fail-stop on false. + * now_ns is nonnegative, monotonic, and cannot approach INT64_MAX during the + * largest 100ms wait. All public calls require one real exclusive probe owner. + */ +struct stela_intel_activation_io { + int (*check_context)(void *); + int (*prepare)(void *, uint32_t platform, uint32_t pci_revision, bool discrete); + uint32_t (*read32)(void *, uint32_t offset); + void (*write32)(void *, uint32_t offset, uint32_t value); + int64_t (*now_ns)(void *); + void (*delay_us)(void *, uint32_t minimum, uint32_t maximum, bool atomic); + void (*invariant)(void *, bool); + void (*report)(void *, uint32_t domain_mask, bool wake, int status, uint32_t value); +}; + +struct stela_intel_activation_facts { + uint32_t platform, subplatform, graphics_verx100, media_verx100; + uint32_t graphics_revision, media_revision, pci_revision, tile_count; + uint32_t dma_bits, va_bits, max_gt_per_tile, discrete; + uint32_t force_probe_required, gt_control, gt_ack, initialized, awake; + uint32_t has_llc, gt_type; +}; +_Static_assert(sizeof(struct stela_intel_activation_facts) == 76, "device facts ABI"); +_Static_assert(offsetof(struct stela_intel_activation_facts, has_llc) == 68, "LLC ABI"); +_Static_assert(offsetof(struct stela_intel_activation_facts, gt_type) == 72, "GT role ABI"); +struct stela_intel_activation; + +size_t stela_intel_activation_size(void); +size_t stela_intel_activation_alignment(void); +/* Pure original PCI-table/force-probe selection, before claiming/mapping BARs. + * A match is not device readiness, discovery of runtime facts or Metal support. */ +int stela_intel_activation_match(uint32_t vendor, uint32_t device, uint32_t pci_class, + bool vf, bool force_probe); +/* Caller supplies owned, aligned host object storage. Outputs unchanged on + * error. bar_bytes is the entire actual reserved BAR0, never a guessed span. + * pci_class is the actual 24bit class tuple. VF always refuses. force_probe + * must be an explicit driver policy decision, never inferred from a match. + * Errors -22 invalid, -19 no match/unreliable MMIO, -95 unsupported, -110 ACK. + */ +int stela_intel_activation_init(void *storage, size_t bytes, + const struct stela_intel_activation_io *, void *context, uint32_t vendor, + uint32_t device, uint32_t pci_class, uint32_t revision, uint64_t bar_bytes, + bool vf, bool force_probe); +int stela_intel_activation_facts(const struct stela_intel_activation *, + struct stela_intel_activation_facts *); +int stela_intel_activation_wake(struct stela_intel_activation *); +/* Acknowledged sleep is required before releasing the power/mapping owner. + * Original sleep failure retains awake bits with ref0; failure remains a real + * non-retirable state until separately qualified recovery, never fake success. + */ +int stela_intel_activation_sleep(struct stela_intel_activation *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/firmware.c b/crates/stela-drivers/src/gpu/intel/stela/firmware.c new file mode 100644 index 0000000000..2a5aaefa47 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/firmware.c @@ -0,0 +1,232 @@ +/* SPDX-License-Identifier: MIT */ +/* Original Xe notices and policies remain in the shared headers. */ +#include "firmware.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_platform_types.h" +#include "../xe/xe_gt_type.h" +#include "../xe/xe_huc_role.h" +#include "../xe/xe_uc_fw_types.h" +#include "../xe/abi/uc_fw_abi.h" +_Static_assert(sizeof(struct gsc_cpd_header_v2) == 20, "original CPD header ABI"); +_Static_assert(sizeof(struct gsc_cpd_entry) == 24, "original CPD entry ABI"); +_Static_assert(sizeof(struct gsc_manifest_header) == 128, "original manifest ABI"); +_Static_assert(_Alignof(struct gsc_cpd_header_v2) == 1, "packed CPD marker access"); +_Static_assert(_Alignof(struct gsc_cpd_entry) == 1, "packed CPD entry access"); +_Static_assert(_Alignof(struct gsc_manifest_header) == 1, "packed manifest access"); +#include "../xe/xe_uc_fw_version.h" +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define __stringify_1(x) #x +#define __stringify(x) __stringify_1(x) +#define FIELD_GET(mask, value) REG_FIELD_GET(mask, value) +#define unlikely(value) __builtin_expect(!!(value), 0) +#define EINVAL 22 +#define ENOENT 2 +#define ENOEXEC 8 +#define ENODATA 61 +#define EPROTO 71 +/* Preserve original signed iteration / u32 metadata arithmetic unchanged. + * Native entry points validate indices and byte-size representability first. */ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wmissing-field-initializers" +#pragma clang diagnostic ignored "-Wshorten-64-to-32" +#include "../xe/xe_uc_fw_catalog.h" +#include "../xe/xe_uc_fw_css.h" +#pragma clang diagnostic pop + +static int select_default(uint32_t platform, struct xe_uc_fw *fw) +{ + if (!platform || platform > INT32_MAX) return -EINVAL; + fw->type = XE_UC_FW_TYPE_GUC; + xe_uc_fw_select_default((enum xe_platform)platform, XE_GT_TYPE_MAIN, fw); + return fw->path ? 0 : -ENOENT; +} +static int copy_selection(const struct xe_uc_fw *fw, uint8_t name[64], + uint32_t wanted[3], uint32_t *full_version) +{ + size_t n = 0; + while (fw->path[n]) { + if (n + 1 >= 64) return -36; + name[n] = (uint8_t)fw->path[n]; + ++n; + } + wanted[0] = fw->versions.wanted.major; + wanted[1] = fw->versions.wanted.minor; + wanted[2] = fw->versions.wanted.patch; + *full_version = fw->full_ver_required; + return 0; +} +int stela_intel_guc_select(uint32_t platform, struct stela_intel_guc_selection *out) +{ + if (!out) return -EINVAL; + struct xe_uc_fw fw = {0}; + int status = select_default(platform, &fw); + if (status) return status; + struct stela_intel_guc_selection result = {0}; + status = copy_selection(&fw, result.name, result.wanted, &result.full_version); + if (status) return status; + *out = result; + return 0; +} +int stela_intel_huc_select_default(uint32_t platform, uint32_t graphics_verx100, + bool media_gt, struct stela_intel_huc_default *out) +{ + if (!out || !platform || platform > INT32_MAX || !graphics_verx100) return -EINVAL; + struct stela_intel_huc_default result = {0}; + if (xe_huc_role_unsupported(media_gt, graphics_verx100)) { + result.disposition = STELA_INTEL_HUC_ABSENT_ROLE; + } else { + struct xe_uc_fw fw = {.type = XE_UC_FW_TYPE_HUC}; + xe_uc_fw_select_default((enum xe_platform)platform, + media_gt ? XE_GT_TYPE_MEDIA : XE_GT_TYPE_MAIN, &fw); + /* Original uc_fw_request: missing default path is NOT_SUPPORTED; + * only missing GuC is mandatory -ENOENT. No status is fabricated here. */ + if (!fw.path) result.disposition = STELA_INTEL_HUC_ABSENT_CATALOG; + else { + result.disposition = STELA_INTEL_HUC_SELECTED; + int status = copy_selection(&fw, result.name, result.wanted, &result.full_version); + if (status) return status; + } + } + *out = result; + return 0; +} +static void diagnostic(void *context, enum xe_uc_fw_css_diagnostic reason, + const struct xe_uc_fw *fw, size_t actual, size_t needed) +{ + (void)fw; (void)actual; (void)needed; + if ((unsigned)reason >= 32) __builtin_trap(); + *(uint32_t *)context |= UINT32_C(1) << (unsigned)reason; +} +static void invariant(void *context, bool condition) +{ + (void)context; + if (!condition) __builtin_trap(); +} +/* Original CSS type is packed; checked arithmetic precedes any narrowing in + * the original algorithm. This does not impose hardware RSA/WOPCM policy. */ +static int sizes_representable(const uint8_t *bytes, size_t size) +{ + if (size < sizeof(struct uc_css_header)) return 0; /* Original short-header diagnostic. */ + const struct uc_css_header *css = (const void *)bytes; + uint64_t rsa_header = (uint64_t)css->rsa_info.key_size_dw + + css->rsa_info.modulus_size_dw + css->rsa_info.exponent_size_dw; + if (css->header_size_dw < rsa_header || css->size_dw < css->header_size_dw) return -75; + uint64_t ucode = (uint64_t)(css->size_dw - css->header_size_dw) * sizeof(uint32_t); + uint64_t rsa = (uint64_t)css->rsa_info.key_size_dw * sizeof(uint32_t); + if (ucode + sizeof(struct uc_css_header) > UINT32_MAX || rsa > UINT32_MAX) return -75; + return 0; +} +int stela_intel_guc_parse(uint32_t platform, const uint8_t *bytes, size_t size, + struct stela_intel_guc_metadata *out, uint32_t *diagnostics) +{ + if (!diagnostics) return -EINVAL; + *diagnostics = 0; + if (!out || !bytes || size > PTRDIFF_MAX) return -EINVAL; + struct xe_uc_fw fw = {0}; + int status = select_default(platform, &fw); + if (status) return status; + status = sizes_representable(bytes, size); + if (status) { *diagnostics = STELA_INTEL_GUC_UNREPRESENTABLE; return status; } + const struct xe_uc_fw_css_ops ops = {diagnostics, diagnostic, invariant}; + status = xe_uc_fw_css_parse(&fw, bytes, size, &ops); + if (status) return status; + status = xe_uc_fw_css_check_version(&fw, &ops); + if (status) return status; + struct stela_intel_guc_metadata result = { + .release = {fw.versions.found[XE_UC_FW_VER_RELEASE].major, + fw.versions.found[XE_UC_FW_VER_RELEASE].minor, + fw.versions.found[XE_UC_FW_VER_RELEASE].patch}, + .submission = {fw.versions.found[XE_UC_FW_VER_COMPATIBILITY].major, + fw.versions.found[XE_UC_FW_VER_COMPATIBILITY].minor, + fw.versions.found[XE_UC_FW_VER_COMPATIBILITY].patch}, + .ucode_bytes = fw.ucode_size, .rsa_bytes = fw.rsa_size, + .upload_bytes = (uint32_t)sizeof(struct uc_css_header) + fw.ucode_size, + .private_bytes = fw.private_data_size, .build_type = fw.build_type, + .diagnostics = *diagnostics, + }; + *out = result; + return 0; +} + +/* The shared core calls equality only with these original literal names and + * includes their terminator. Native memcmp is bounded within the real 12-byte + * entry name, including malformed entries with no NUL. No string reimplementation. */ +static bool cpd_entry_equal(const void *entry, const char *name, size_t bytes) +{ + invariant(NULL, bytes > 0 && bytes <= sizeof(((struct gsc_cpd_entry *)0)->name)); + return !__builtin_memcmp(entry, name, bytes); +} +#define XE_UC_FW_CPD_ENTRY_EQUAL(entry, name, bytes) cpd_entry_equal(entry, name, bytes) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#include "../xe/xe_uc_fw_cpd.h" +#pragma clang diagnostic pop + +static void cpd_diagnostic(void *context, enum xe_uc_fw_cpd_diagnostic reason, + const struct xe_uc_fw *fw, size_t actual, size_t needed) +{ + (void)fw; (void)actual; (void)needed; + invariant(NULL, (unsigned)reason < 3); + *(uint32_t *)context |= UINT32_C(1) << (8 + (unsigned)reason); +} +static int huc_css(void *context, struct xe_uc_fw *fw, const void *bytes, size_t size) +{ + invariant(NULL, fw->type == XE_UC_FW_TYPE_HUC); + int status = sizes_representable(bytes, size); + if (status) { *(uint32_t *)context |= STELA_INTEL_GUC_UNREPRESENTABLE; return status; } + const struct xe_uc_fw_css_ops ops = {context, diagnostic, invariant}; + return xe_uc_fw_css_parse(fw, bytes, size, &ops); +} +/* The core's int loop index must not overflow on a representable complete + * entry table. Preserve the original short-table diagnostic/error otherwise. + * Header, entry and manifest types are genuinely packed; no aligned-u32 read. + * sizeof(full header) >= sizeof(marker) before is_cpd_header is evaluated. */ +static int cpd_representable(const uint8_t *bytes, size_t size) +{ + if (size < sizeof(struct gsc_cpd_header_v2) || !is_cpd_header(bytes)) return 0; + const struct gsc_cpd_header_v2 *header = (const void *)bytes; + if (header->header_length < sizeof(*header)) return 0; + uint64_t table = (uint64_t)header->header_length + + (uint64_t)header->num_of_entries * sizeof(struct gsc_cpd_entry); + if (table > size) return 0; + return header->num_of_entries > INT32_MAX ? -75 : 0; +} +int stela_intel_huc_parse(uint32_t platform, uint32_t graphics_verx100, bool media_gt, + const uint8_t *bytes, size_t size, struct stela_intel_huc_metadata *out, + uint32_t *diagnostics) +{ + if (!diagnostics) return -EINVAL; + *diagnostics = 0; + if (!bytes || !out || size > PTRDIFF_MAX) return -EINVAL; + struct stela_intel_huc_default selected; + int status = stela_intel_huc_select_default(platform, graphics_verx100, media_gt, &selected); + if (status) return status; + if (selected.disposition != STELA_INTEL_HUC_SELECTED) return -95; + /* Original HuC CPD/DMA parser explicitly does not support DG2's CSS-less + * GSC loading path. No selection alias or invented CSS is permitted. */ + if (platform == XE_DG2) return -95; + struct xe_uc_fw fw = {.type = XE_UC_FW_TYPE_HUC}; + xe_uc_fw_select_default((enum xe_platform)platform, + media_gt ? XE_GT_TYPE_MEDIA : XE_GT_TYPE_MAIN, &fw); + status = cpd_representable(bytes, size); + if (status) { *diagnostics = STELA_INTEL_GUC_UNREPRESENTABLE; return status; } + const struct xe_uc_fw_cpd_ops ops = {diagnostics, cpd_diagnostic, invariant, huc_css, NULL}; + status = xe_uc_fw_huc_parse(&fw, bytes, size, (enum xe_platform)platform, &ops); + if (status) return status; + const struct xe_uc_fw_css_ops css_ops = {diagnostics, diagnostic, invariant}; + status = xe_uc_fw_css_check_version(&fw, &css_ops); + if (status) return status; + struct stela_intel_huc_metadata result = { + .release = {fw.versions.found[XE_UC_FW_VER_RELEASE].major, + fw.versions.found[XE_UC_FW_VER_RELEASE].minor, + fw.versions.found[XE_UC_FW_VER_RELEASE].patch}, + .ucode_bytes = fw.ucode_size, .rsa_bytes = fw.rsa_size, + .upload_bytes = (uint32_t)sizeof(struct uc_css_header) + fw.ucode_size, + .css_offset = fw.css_offset, + .format = fw.has_gsc_headers ? STELA_INTEL_HUC_CPD_CSS : STELA_INTEL_HUC_CSS, + .diagnostics = *diagnostics, + }; + *out = result; + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/firmware.h b/crates/stela-drivers/src/gpu/intel/stela/firmware.h new file mode 100644 index 0000000000..a93f729ada --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/firmware.h @@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_FIRMWARE_H +#define STELA_INTEL_FIRMWARE_H +#include +#include +#include + +/* Default GuC/HuC selection and checked CSS/CPD metadata only. No result owns a + * GPU BO, address, firmware status, signature acceptance or hardware activity. */ +struct stela_intel_guc_selection { + uint8_t name[64]; + uint32_t wanted[3]; + uint32_t full_version; +}; +struct stela_intel_guc_metadata { + uint32_t release[3], submission[3]; + uint32_t ucode_bytes, rsa_bytes, upload_bytes, private_bytes, build_type; + uint32_t diagnostics; +}; +_Static_assert(sizeof(struct stela_intel_guc_selection) == 80, "selection ABI"); +_Static_assert(offsetof(struct stela_intel_guc_selection, wanted) == 64, "selection version ABI"); +_Static_assert(offsetof(struct stela_intel_guc_selection, full_version) == 76, "selection policy ABI"); +_Static_assert(sizeof(struct stela_intel_guc_metadata) == 48, "metadata ABI"); +_Static_assert(offsetof(struct stela_intel_guc_metadata, submission) == 12, "submission ABI"); +_Static_assert(offsetof(struct stela_intel_guc_metadata, ucode_bytes) == 24, "size ABI"); +_Static_assert(offsetof(struct stela_intel_guc_metadata, diagnostics) == 44, "diagnostic ABI"); +/* Default-selection disposition only; these are NOT xe_uc_fw load statuses. + * No provider lookup/failure, BO or availability state participates here. */ +enum stela_intel_huc_disposition { + STELA_INTEL_HUC_SELECTED = 1, + STELA_INTEL_HUC_ABSENT_ROLE, + STELA_INTEL_HUC_ABSENT_CATALOG, +}; +struct stela_intel_huc_default { + uint32_t disposition; + uint8_t name[64]; + uint32_t wanted[3], full_version; +}; +_Static_assert(sizeof(struct stela_intel_huc_default) == 84, "HuC selection ABI"); +_Static_assert(offsetof(struct stela_intel_huc_default, wanted) == 68, "HuC version ABI"); +/* Exact actual GT role + complete original default selector. No override mode. + * A selected path remains a genuine prerequisite even when Provider fails. + * Missing path is the original non-GuC NOT_SUPPORTED case, never AVAILABLE. + * Actual native facts supply these scalars; result alone is no GPU capability. + * Invalid input/error leaves the result unchanged. */ +int stela_intel_huc_select_default(uint32_t platform, uint32_t graphics_verx100, + bool media_gt, struct stela_intel_huc_default *); +enum stela_intel_guc_diagnostic { + STELA_INTEL_GUC_TOO_OLD = 1u << 0, + STELA_INTEL_GUC_VERSION_MISMATCH = 1u << 1, + STELA_INTEL_GUC_RECOMMENDED_NEWER = 1u << 2, + STELA_INTEL_GUC_SHORT_HEADER = 1u << 3, + STELA_INTEL_GUC_HEADER_SIZE = 1u << 4, + STELA_INTEL_GUC_SHORT_IMAGE = 1u << 5, +}; +#define STELA_INTEL_GUC_UNREPRESENTABLE UINT32_C(0x80000000) +/* Actual root-main-GT platform comes from the live native owner. Missing + * original entries fail -ENOENT; there are no newer-platform aliases. Outputs + * remain unchanged on error. This cold metadata path performs no allocation. */ +int stela_intel_guc_select(uint32_t platform, struct stela_intel_guc_selection *); +/* Borrowed immutable CPU image, never a guest/device/IOVA pointer. Full size + * refers to that same allocation. Result unchanged on error; diagnostics always + * describes this attempt, including accepted older recommended minor releases. + * Overflow preflight is deliberately stricter than unchecked u32 wrap arithmetic + * before invoking the original parser. Missing modulus/exponent stays allowed. + * SHA256/provenance are carried by canonical Provider, not authenticated here. */ +int stela_intel_guc_parse(uint32_t platform, const uint8_t *, size_t, + struct stela_intel_guc_metadata *, uint32_t *diagnostics); +struct stela_intel_huc_metadata { + uint32_t release[3]; + uint32_t ucode_bytes, rsa_bytes, upload_bytes, css_offset, format, diagnostics; +}; +enum stela_intel_huc_format { + STELA_INTEL_HUC_CSS = 1, + STELA_INTEL_HUC_CPD_CSS, +}; +#define STELA_INTEL_HUC_CPD_HEADER_LENGTH (UINT32_C(1) << 8) +#define STELA_INTEL_HUC_CPD_SHORT_IMAGE (UINT32_C(1) << 9) +#define STELA_INTEL_HUC_CPD_MISSING_MANIFEST (UINT32_C(1) << 10) +_Static_assert(sizeof(struct stela_intel_huc_metadata) == 36, "HuC metadata ABI"); +_Static_assert(offsetof(struct stela_intel_huc_metadata, css_offset) == 24, "HuC CSS subview ABI"); +_Static_assert(offsetof(struct stela_intel_huc_metadata, diagnostics) == 32, "HuC diagnostics ABI"); +/* Actual immutable provider CPU bytes, not BO-backed availability. Selects the + * actual default/role; absence returns -95. CPD malformed errors never become + * CSS fallback. Output unchanged on all errors; diagnostics describes attempt. + * Metadata is not signature/authentication/CRC acceptance or WOPCM readiness. */ +int stela_intel_huc_parse(uint32_t platform, uint32_t graphics_verx100, bool media_gt, + const uint8_t *, size_t, struct stela_intel_huc_metadata *, + uint32_t *diagnostics); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.c b/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.c new file mode 100644 index 0000000000..ea4faba80f --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.c @@ -0,0 +1,63 @@ +/* SPDX-License-Identifier: MIT */ +#include "ggtt_probe.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_platform_types.h" +/* Normal Make extracts only original scalar defines from retained headers; + * no duplicated hardware constants, Linux service shim or custom allocator. */ +#include "ggtt_probe_defs.h" +#include "../xe/regs/xe_gtt_defs.h" +#include "../xe/xe_wopcm_size.h" +static void invariant(void *context, bool condition) +{ + (void)context; + if (!condition) __builtin_trap(); +} +#define XE_GGTT_PROBE_ASSERT(context, condition) invariant(context, condition) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" +#include "../xe/xe_ggtt_probe_core.h" +#pragma clang diagnostic pop +int stela_intel_gsm_config(uint32_t graphics_verx100, uint16_t *offset) +{ + if (!offset || !graphics_verx100) return -22; + if (xe_ggtt_probe_fixed_gsm(graphics_verx100)) return 1; + *offset = SNB_GMCH_CTRL; + return 0; +} +int stela_intel_gsm_geometry(uint32_t platform, uint32_t graphics_verx100, bool discrete, + uint64_t actual_bar_bytes, bool config_present, uint16_t gmch_control, + struct stela_intel_gsm_geometry *out) +{ + if (!out || !platform || platform > INT32_MAX || !graphics_verx100) return -22; + unsigned int gsm_size; + if (xe_ggtt_probe_fixed_gsm(graphics_verx100)) + gsm_size = SZ_8M; + else { + if (!config_present) return -95; + gsm_size = xe_ggtt_probe_gsm_decode(gmch_control); + } + if (!gsm_size) return -12; /* Original no-preallocated-GSM refusal. */ + uint64_t offset = xe_ggtt_probe_gsm_offset(); + if (offset > actual_bar_bytes || gsm_size > actual_bar_bytes - offset) return -34; + uint64_t wopcm = xe_wopcm_default_size((enum xe_platform)platform, discrete); + if ((gsm_size / 8) * (uint64_t)XE_PAGE_SIZE <= wopcm) return -34; + struct stela_intel_gsm_geometry result = {.gsm_offset = offset, .gsm_bytes = gsm_size}; + xe_ggtt_probe_pf_range(gsm_size, wopcm, &result.ggtt_start, &result.ggtt_bytes); + xe_ggtt_probe_clamp_range(result.ggtt_start, &result.ggtt_bytes); + *out = result; + return 0; +} +int stela_intel_gsm_pte_offset(const struct stela_intel_gsm_geometry *geometry, + uint64_t address, size_t *out) +{ + if (!geometry || !out || !geometry->gsm_bytes || geometry->gsm_bytes % sizeof(uint64_t) || + geometry->gsm_bytes > PTRDIFF_MAX || !geometry->ggtt_bytes || + geometry->ggtt_start > GUC_GGTT_TOP || + geometry->ggtt_bytes > GUC_GGTT_TOP - geometry->ggtt_start || + (address & XE_PTE_MASK) || address >= geometry->ggtt_start + geometry->ggtt_bytes) + return -22; + uint64_t index = xe_ggtt_probe_pte_index(NULL, geometry->ggtt_start, geometry->ggtt_bytes, address); + if (index >= geometry->gsm_bytes / sizeof(uint64_t)) return -34; + *out = (size_t)index * sizeof(uint64_t); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.h b/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.h new file mode 100644 index 0000000000..f806f238a5 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/ggtt_probe.h @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_GGTT_PROBE_H +#define STELA_INTEL_GGTT_PROBE_H +#include +#include +#include +/* Scalar geometry only, never an allocation/ONLINE/PAT/firmware capability. + * Native physical entry binds these to an actual same-device owned GSM lease. */ +struct stela_intel_gsm_geometry { + uint64_t gsm_offset, gsm_bytes, ggtt_start, ggtt_bytes; +}; +_Static_assert(sizeof(struct stela_intel_gsm_geometry) == 32, "GSM geometry ABI"); +_Static_assert(offsetof(struct stela_intel_gsm_geometry, ggtt_start) == 16, "GGTT start ABI"); +/* 0: actual SAME-function PCI read16 at output offset is required. + * 1: original fixed-size policy, no PCI read required. Negative: invalid. + * Every error/no-config result preserves output. No PCI access occurs here. */ +int stela_intel_gsm_config(uint32_t graphics_verx100, uint16_t *offset); +/* Immutable actual Device facts and complete BAR extent supplied by the owned + * native caller. config_present attests only to its real canonical PCI read; + * this metadata function alone establishes no hardware/service ownership. + * All errors preserve output. No pointer formation or MMIO occurs here. */ +int stela_intel_gsm_geometry(uint32_t platform, uint32_t graphics_verx100, bool discrete, + uint64_t actual_bar_bytes, bool config_present, uint16_t gmch_control, + struct stela_intel_gsm_geometry *); +/* Original PTE index/assertion policy with checked CPU span before readq. + * Native owner must still read through actual ordered64 canonical MMIO. + * No reads/writes occur here; error leaves byte offset output unchanged. */ +int stela_intel_gsm_pte_offset(const struct stela_intel_gsm_geometry *, uint64_t address, + size_t *offset); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/guc_reset.c b/crates/stela-drivers/src/gpu/intel/stela/guc_reset.c new file mode 100644 index 0000000000..46b151daf3 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/guc_reset.c @@ -0,0 +1,119 @@ +/* SPDX-License-Identifier: MIT */ +#include "guc_reset.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_gt_type.h" +#include "../xe/xe_force_wake_domain_types.h" +#include "../xe/regs/xe_gt_regs.h" +#include "../xe/regs/xe_guc_regs.h" +#include "../xe/abi/guc_errors_abi.h" +#define EIO 5 +#define ETIMEDOUT 110 +#define FIELD_PREP(mask, value) REG_FIELD_PREP(mask, value) + +/* Qualification proof, not a copied WA selector. This is the unchanged entry + * emitted by the original OOB generator. Both original version-range branches + * must exclude EVERY version admitted below. A new clause/token or overlap is + * a hard compile failure requiring deliberate original-matcher qualification. */ +#define XE_RTP_NAME(name) 0 +#define XE_RTP_RULES(...) __VA_ARGS__ +#define STELA_GUC_RESET_RANGE(first, last) \ + sizeof(struct { _Static_assert((first) > 1210 && (last) >= (first), \ + "native XeLP admission must exclude the actual original reset WA"); char proof; }) +#define MEDIA_VERSION_RANGE(first, last) STELA_GUC_RESET_RANGE(first, last) +#define GRAPHICS_VERSION_RANGE(first, last) STELA_GUC_RESET_RANGE(first, last) +#define OR 0 +static const size_t wa_qualification[][4] __attribute__((unused)) = { +#include "guc_reset_wa.inc" +}; +_Static_assert(sizeof(wa_qualification) / sizeof(wa_qualification[0]) == 1, "one original reset WA entry"); +#undef OR +#undef GRAPHICS_VERSION_RANGE +#undef MEDIA_VERSION_RANGE +#undef STELA_GUC_RESET_RANGE +#undef XE_RTP_RULES +#undef XE_RTP_NAME + +struct native_reset { + const struct stela_intel_activation_io *io; + void *context; + struct stela_intel_activation *activation; + struct stela_intel_guc_reset_result *result; +}; +static u32 native_read(struct native_reset *native, struct xe_reg reg) +{ + native->io->invariant(native->context, !(reg.addr & 3) && reg.addr <= SZ_4M - 4); + u32 value = native->io->read32(native->context, reg.addr); + if (reg.addr == GDRST.addr) native->result->gdrst = value; + if (reg.addr == GUC_STATUS.addr) native->result->guc_status = value; + return value; +} +static void native_write(struct native_reset *native, struct xe_reg reg, u32 value) +{ + native->io->invariant(native->context, !(reg.addr & 3) && reg.addr <= SZ_4M - 4); + ++native->result->writes; /* Exposure recorded before actual owner callback. */ + native->io->write32(native->context, reg.addr, value); +} +static void native_rmw(struct native_reset *native, struct xe_reg reg, u32 clear, u32 set) +{ + u32 value = native_read(native, reg); + value &= ~clear; + value |= set; + native_write(native, reg, value); +} +static int64_t add_us(int64_t time, int64_t us) { return time + us * 1000; } +#define XE_MMIO_POLL_NAME native_poll +#define XE_MMIO_POLL_CONTEXT struct native_reset +#define XE_MMIO_POLL_TIME int64_t +#define XE_MMIO_POLL_NOW(mmio) ((mmio)->io->now_ns((mmio)->context)) +#define XE_MMIO_POLL_ADD_US add_us +#define XE_MMIO_POLL_READ native_read +#define XE_MMIO_POLL_BEFORE(a, b) ((a) < (b)) +#define XE_MMIO_POLL_AFTER(a, b) ((a) > (b)) +#define XE_MMIO_POLL_DELTA_US(a, b) (((a) - (b)) / 1000) +#define XE_MMIO_POLL_DELAY(mmio, wait, atomic) \ + (mmio)->io->delay_us((mmio)->context, (uint32_t)(wait), \ + (uint32_t)((atomic) ? (wait) : ((wait) << 1)), (atomic)) +#include "../xe/xe_mmio_poll.h" +#define XE_GUC_RESET_CONTEXT struct native_reset +#define XE_GUC_RESET_READ native_read +#define XE_GUC_RESET_WRITE native_write +#define XE_GUC_RESET_RMW native_rmw +#define XE_GUC_RESET_WAIT(n, reg, mask, value, timeout, out, atomic) \ + native_poll(n, reg, mask, value, timeout, out, atomic, true) +#define XE_GUC_RESET_ASSERT_HELD(n) stela_intel_activation_assert_gt((n)->activation) +#define XE_GUC_RESET_IS_VF(n) false +#define XE_GUC_RESET_VF_BOOTSTRAP(n) (-95) +/* Compile-time generated original-entry proof plus actual version preflight + * makes this false; no default for an unqualified modern/media/VF path. */ +#define XE_GUC_RESET_WA_14025883347(n) false +#define XE_GUC_RESET_WARN_READY(n, value) \ + ((n)->result->warnings |= 1u, (n)->result->ready_status = (value)) +#define XE_GUC_RESET_WARN_SRAM(n, value) \ + ((n)->result->warnings |= 2u, (n)->result->sram_status = (value)) +#define XE_GUC_RESET_ERROR_TIMEOUT(n, value) ((n)->result->gdrst = (value)) +#define XE_GUC_RESET_ERROR_STATUS(n, value) ((n)->result->guc_status = (value)) +#include "../xe/xe_guc_reset_core.h" + +int stela_intel_guc_reset(const struct stela_intel_activation_io *io, void *context, + struct stela_intel_activation *activation, const struct stela_intel_activation_facts *facts, + struct stela_intel_guc_reset_result *out) +{ + if (!io || !io->check_context || !io->read32 || !io->write32 || !io->now_ns || + !io->delay_us || !io->invariant || !activation || !facts || !out) return -22; + /* Current native method uses actual matched root-main XeLP facts, not CPU + * or a curated PCI list. The original whole modern/WA/VF policy is retained + * in the shared core but awaits its genuine owner/matcher prerequisites. */ + if (facts->gt_type != XE_GT_TYPE_MAIN || facts->tile_count != 1 || facts->max_gt_per_tile != 1 || + facts->graphics_verx100 < 1200 || facts->graphics_verx100 > 1210 || + facts->media_verx100 > 1210 || !(facts->initialized & XE_FW_GT) || + !(facts->awake & XE_FW_GT)) return -95; + int status = io->check_context(context); + if (status) return status; + int64_t now = io->now_ns(context); + if (now < 0 || now > INT64_MAX - INT64_C(100000000)) return -22; + struct stela_intel_guc_reset_result result = {0}; + struct native_reset native = {io, context, activation, &result}; + status = xe_guc_reset_core(&native); + *out = result; /* Actual failure observations must retain uncertain owner. */ + return status; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/guc_reset.h b/crates/stela-drivers/src/gpu/intel/stela/guc_reset.h new file mode 100644 index 0000000000..ba6e399c17 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/guc_reset.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_GUC_RESET_H +#define STELA_INTEL_GUC_RESET_H +#include "activation.h" +struct stela_intel_guc_reset_result { + uint32_t writes, warnings, gdrst, guc_status, ready_status, sram_status; +}; +_Static_assert(sizeof(struct stela_intel_guc_reset_result) == 24, "GuC reset result ABI"); +_Static_assert(offsetof(struct stela_intel_guc_reset_result, guc_status) == 12, "GuC status ABI"); +/* Explicit hardware handshake only; not xe_uc_sanitize_reset, firmware/CT/job + * state, a reset/recovery epoch or proof of whole-device DMA quiescence. + * Actual exclusive same-Device no-DMA/no-IRQ/no-CT/no-submission ownership, + * canonical UC view and acknowledged GT wake are required before entry. */ +int stela_intel_activation_guc_reset(struct stela_intel_activation *, + struct stela_intel_guc_reset_result *); +/* Private actual-State adapter. Error before I/O preserves output; an exposed + * failure returns exact observations/writes for permanent owner quarantine. + * No fallible operation or allocation follows register effects. */ +int stela_intel_guc_reset(const struct stela_intel_activation_io *, void *, + struct stela_intel_activation *, const struct stela_intel_activation_facts *, + struct stela_intel_guc_reset_result *); +void stela_intel_activation_assert_gt(struct stela_intel_activation *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.c b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.c new file mode 100644 index 0000000000..f6e1ecb539 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.c @@ -0,0 +1,375 @@ +/* SPDX-License-Identifier: MIT */ +#include "air_compile.h" +#include "fp_controls.h" +#include "intel/common/intel_compute_slm.h" +#include "intel/compiler/brw/brw_nir.h" +#include "intel/compiler/elk/elk_nir.h" +#include "intel/compiler/gen/gen.h" +#include "util/ralloc.h" +#include +#include +#include +#define MAX_TEXT 4096u +#define MAX_CODE (64u * 1024u * 1024u) +struct stela_intel_air_compilation { + struct stela_intel_air_provenance provenance; + struct stela_intel_air_binary binary; + nir_shader_compiler_options nir_options; + nir_shader *shader; + void *context, *work_context, *metadata; + struct brw_cs_prog_data brw; + struct elk_cs_prog_data elk; + struct stela_intel_air_binding bindings[AIR_MAX_ARGUMENTS]; + uint32_t binding_count; + bool type_reference; +}; +static enum stela_intel_air_status report(struct stela_intel_air_error *error, + enum stela_intel_air_status status, const char *detail) +{ + if (error) { error->status = status; snprintf(error->detail, sizeof(error->detail), "%s", detail); } + return status; +} +void stela_intel_air_destroy(struct stela_intel_air_compilation **slot) +{ + if (!slot || !*slot) return; + struct stela_intel_air_compilation *owner = *slot; *slot = NULL; + ralloc_free(owner->shader); ralloc_free(owner->work_context); ralloc_free(owner->context); + if (owner->type_reference) glsl_type_singleton_decref(); + free(owner->metadata); free(owner); +} +static bool text_valid(const char *text, size_t bytes) +{ + return bytes <= MAX_TEXT && (!bytes || (text && !memchr(text, 0, bytes))); +} +static char *copy_text(char **cursor, const void *text, size_t bytes) +{ + if (!text) return NULL; + char *result = *cursor; + memcpy(result, text, bytes); result[bytes] = 0; *cursor += bytes + 1; return result; +} +static enum stela_intel_air_status copy_provenance(struct stela_intel_air_compilation *owner, + const struct stela_metal_library_manifest *manifest, + const struct stela_metal_function_record *record, unsigned selected, + struct stela_intel_air_error *error) +{ + if (!text_valid((const char *)record->name, record->name_bytes) || !record->name_bytes || + !text_valid((const char *)manifest->target, manifest->target_bytes) || !manifest->target_bytes || + record->argument_count > AIR_MAX_ARGUMENTS || (record->argument_count && !record->arguments)) + return report(error, STELA_INTEL_AIR_INVALID, "Unrepresentable selected entry metadata"); + size_t bytes = record->argument_count * sizeof(struct stela_air_argument_info) + + (size_t)record->name_bytes + (size_t)manifest->target_bytes + 2 + + owner->provenance.policy.lowered_format_count * sizeof(uint32_t); + for (unsigned i = 0; i < record->argument_count; i++) { + const struct stela_air_argument_info *arg = &record->arguments[i]; + if (!text_valid(arg->name, arg->name_bytes) || !text_valid(arg->type_name, arg->type_name_bytes)) + return report(error, STELA_INTEL_AIR_INVALID, "Unrepresentable argument strings"); + bytes += arg->name_bytes + arg->type_name_bytes + 2; + } + /* Bounded before allocation by128 arguments and4096 bytes/string. */ + owner->metadata = malloc(bytes); + if (!owner->metadata) return report(error, STELA_INTEL_AIR_ALLOCATION, "Selected metadata allocation failed"); + struct stela_air_argument_info *args = owner->metadata; + uint32_t *formats = (uint32_t *)(args + record->argument_count); + unsigned count = owner->provenance.policy.lowered_format_count; + if (count) memcpy(formats, owner->provenance.policy.lowered_formats, count * sizeof(*formats)); + owner->provenance.policy.lowered_formats = count ? formats : NULL; + char *cursor = (char *)(formats + count); + struct stela_intel_air_provenance *p = &owner->provenance; + p->input = manifest->input; p->entry = record->entry; p->selected_entry = selected; + p->entry_flags = record->flags; p->library_flags = manifest->flags; p->compiler_profile = manifest->compiler_profile; + p->request_language = manifest->request_language; p->request_fast_math = manifest->request_fast_math; + p->build = manifest->build; p->air_offset = record->air_offset; p->air_bytes = record->air_bytes; + memcpy(p->air_sha256, record->air_sha256, 32); memcpy(p->source_sha256, manifest->source_sha256, 32); + p->name = copy_text(&cursor, record->name, (size_t)record->name_bytes); + p->target = copy_text(&cursor, manifest->target, (size_t)manifest->target_bytes); + p->argument_count = record->argument_count; p->arguments = args; + for (unsigned i = 0; i < record->argument_count; i++) { + args[i] = record->arguments[i]; + args[i].name = copy_text(&cursor, args[i].name, args[i].name_bytes); + args[i].type_name = copy_text(&cursor, args[i].type_name, args[i].type_name_bytes); + } + return STELA_INTEL_AIR_OK; +} +static bool bind_ssbo(const struct stela_air_buffer *buffer, unsigned *slot, void *data) +{ + struct stela_intel_air_compilation *owner = data; + for (unsigned i = 0; i < owner->binding_count; i++) { + const struct stela_air_buffer *b = &owner->bindings[i].buffer; + if (b->argument == buffer->argument && b->index == buffer->index && + b->address_space == buffer->address_space && b->access == buffer->access && + b->type_size == buffer->type_size && b->type_alignment == buffer->type_alignment) { + *slot = owner->bindings[i].slot; return true; + } + } + return false; +} +static enum stela_intel_air_status prepare_bindings(struct stela_intel_air_compilation *owner, + struct stela_intel_air_error *error) +{ + for (unsigned i = 0; i < owner->provenance.argument_count; i++) { + const struct stela_air_argument_info *arg = &owner->provenance.arguments[i]; + if (arg->kind == 2) continue; + if (arg->kind == 1 && arg->buffer.address_space == 3 && arg->plain_buffer_type) continue; + if (arg->kind != 1 || arg->buffer.address_space != 1 || !arg->plain_buffer_type) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Unsupported resource binding specialization"); + unsigned slot = owner->binding_count; + if (slot >= AIR_MAX_ARGUMENTS || slot >= UINT8_MAX) + return report(error, STELA_INTEL_AIR_LIMIT, "SSBO slot representation exceeded"); + owner->bindings[owner->binding_count++] = (struct stela_intel_air_binding){arg->buffer, slot}; + } + return STELA_INTEL_AIR_OK; +} +static bool device_valid(const struct intel_device_info *d, bool elk) +{ + if (!d || !d->slice_masks || !d->subslice_total || !d->num_thread_per_eu || + !d->max_cs_threads || !d->max_cs_workgroup_threads) return false; + if (elk) return d->verx10 == 70 || d->verx10 == 75 || d->verx10 == 80; + switch (d->verx10) { + case 90: case 110: case 120: case 125: case 200: case 300: case 350: return true; + default: return false; + } +} +/* Qualified Gen7 admission is aligned 32-bit shared I/O. Original ELK + * postprocessing may widen other inputs; do not duplicate it or enter an + * unqualified byte-scattered path (Gen7.5+). Inspect actual intrinsics after + * preprocessing/CS lowering, not declared AIR types. */ +static bool gen7_shared_io_supported(const struct intel_device_info *device, nir_shader *shader) +{ + if (device->verx10 != 70) return true; + nir_foreach_function_impl(impl, shader) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) continue; + nir_intrinsic_instr *in = nir_instr_as_intrinsic(instr); + unsigned bits; + if (in->intrinsic == nir_intrinsic_load_shared) bits = in->def.bit_size; + else if (in->intrinsic == nir_intrinsic_store_shared) bits = nir_src_bit_size(in->src[0]); + else continue; + if (bits != 32 || nir_intrinsic_align(in) < 4) return false; + } + } + } + return true; +} +static bool code_valid(struct stela_intel_air_compilation *owner, const struct elk_compiler *elk) +{ + if (elk) return stela_intel_air_validate_elk(elk, owner->binary.code, owner->binary.executable_bytes); + gen_decode_params decoded = {.devinfo = &owner->provenance.device, .raw_bytes = owner->binary.code, + .raw_bytes_size = (int)owner->binary.executable_bytes, .mem_ctx = owner->work_context}; + if (!gen_decode(&decoded)) return false; + gen_validate_params validation = {.devinfo = &owner->provenance.device, .insts = decoded.insts, + .num_insts = decoded.num_insts, .mem_ctx = owner->work_context}; + return gen_validate(&validation); +} +static enum stela_intel_air_status capture(struct stela_intel_air_compilation *owner, + const void *code, const char *message, const struct elk_compiler *elk, + struct stela_intel_air_error *error) +{ + unsigned bytes = elk ? owner->elk.base.program_size : owner->brw.base.program_size; + unsigned constants = elk ? owner->elk.base.const_data_size : owner->brw.base.const_data_size; + unsigned offset = elk ? owner->elk.base.const_data_offset : owner->brw.base.const_data_offset; + unsigned relocs = elk ? owner->elk.base.num_relocs : owner->brw.base.num_relocs; + const struct intel_shader_reloc *reloc = elk ? owner->elk.base.relocs : owner->brw.base.relocs; + mesa_shader_stage stage = elk ? owner->elk.base.stage : owner->brw.base.stage; + unsigned mask = elk ? owner->elk.prog_mask : owner->brw.prog_mask; + unsigned shared = elk ? owner->elk.base.total_shared : owner->brw.base.total_shared; + if (!code || message || !bytes || stage != MESA_SHADER_COMPUTE || !mask || (mask & ~7u) || + shared != owner->shader->info.shared_size || (relocs && !reloc) || + (offset > bytes || (constants && (!offset || constants > bytes - offset)))) + return report(error, STELA_INTEL_AIR_BACKEND, message ? message : "Original compiler output inconsistent"); + if (bytes > owner->provenance.options.max_code_bytes) + return report(error, STELA_INTEL_AIR_LIMIT, "Compiled resident code exceeds caller budget"); + unsigned executable = constants ? offset : bytes; + for (unsigned i = 0; i < 3; i++) { + unsigned local = elk ? owner->elk.local_size[i] : owner->brw.local_size[i]; + unsigned prog_offset = elk ? owner->elk.prog_offset[i] : owner->brw.prog_offset[i]; + if (local != owner->provenance.options.workgroup_size[i] || + ((mask & (1u << i)) && (prog_offset >= executable || (prog_offset & 63)))) + return report(error, STELA_INTEL_AIR_BACKEND, "Invalid original workgroup/SIMD code span"); + } + for (unsigned i = 0; i < relocs; i++) { + unsigned span; + if (reloc[i].type == INTEL_SHADER_RELOC_TYPE_U32) span = 4; + else if (reloc[i].type == INTEL_SHADER_RELOC_TYPE_MOV_IMM) span = 16; + else return report(error, STELA_INTEL_AIR_BACKEND, "Unknown original relocation type"); + if (reloc[i].offset % 8 || reloc[i].offset > executable || executable - reloc[i].offset < span) + return report(error, STELA_INTEL_AIR_BACKEND, "Original relocation exceeds executable span"); + } + owner->binary = (struct stela_intel_air_binary){.backend = elk ? STELA_INTEL_AIR_ELK : STELA_INTEL_AIR_BRW, + .code = code, .code_bytes = bytes, .executable_bytes = executable, + .brw = elk ? NULL : &owner->brw, .elk = elk ? &owner->elk : NULL}; + if (!code_valid(owner, elk)) return report(error, STELA_INTEL_AIR_BACKEND, "Original instruction validator refused code"); + /* Preserve only the original output allocations, not codegen objects + * containing borrowed ISA/callback pointers from the temporary context. */ + ralloc_steal(owner->context, (void *)code); + if (reloc) ralloc_steal(owner->context, (void *)reloc); + if (elk && owner->elk.base.param) ralloc_steal(owner->context, owner->elk.base.param); + return STELA_INTEL_AIR_OK; +} +static bool bind_threadgroup(const struct stela_air_buffer *buffer, + struct stela_air_threadgroup_view *view, void *data) +{ + const struct stela_intel_air_compilation *owner = data; + const struct stela_metal_threadgroup_specialization *shared = &owner->provenance.threadgroup; + for (unsigned i = 0; i < shared->count; i++) { + const struct stela_metal_threadgroup_binding *binding = &shared->bindings[i]; + const struct stela_air_buffer *b = &binding->buffer; + if (b->argument == buffer->argument && b->index == buffer->index && + b->address_space == buffer->address_space && b->access == buffer->access && + b->type_size == buffer->type_size && b->type_alignment == buffer->type_alignment) { + *view = (struct stela_air_threadgroup_view){.size = binding->bytes, + .alignment = binding->alignment, .available_access = STELA_AIR_READ_WRITE}; + return true; + } + } + return false; +} +enum stela_intel_air_status stela_intel_air_compile(const struct brw_compiler *brw, + const struct elk_compiler *elk, void *log_data, const struct stela_metal_assembly *library, uint32_t selected, + const struct stela_intel_air_options *options, struct stela_intel_air_compilation **output, + struct stela_intel_air_error *error) +{ + return stela_intel_air_compile_specialized(brw, elk, log_data, library, selected, options, NULL, output, error); +} +enum stela_intel_air_status stela_intel_air_compile_specialized(const struct brw_compiler *brw, + const struct elk_compiler *elk, void *log_data, const struct stela_metal_assembly *library, uint32_t selected, + const struct stela_intel_air_options *options, const struct stela_metal_threadgroup_request *request, + struct stela_intel_air_compilation **output, + struct stela_intel_air_error *error) +{ + if (error) memset(error, 0, sizeof(*error)); + if (!!brw == !!elk || !library || !options || !output || *output || + options->size != sizeof(*options) || options->abi != STELA_INTEL_AIR_ABI) + return report(error, STELA_INTEL_AIR_INVALID, "Invalid local ownership/compiler ABI"); + const struct intel_device_info *device = brw ? brw->devinfo : elk->devinfo; + if (!device_valid(device, elk != NULL) || (brw && (brw->isa.devinfo != device || + !brw->shader_debug_log || !brw->shader_perf_log || brw->num_lowered_storage_formats > ISL_NUM_FORMATS || + (brw->num_lowered_storage_formats && !brw->lowered_storage_formats))) || + (elk && (elk->isa.devinfo != device || !elk->shader_debug_log || !elk->shader_perf_log || + !elk->scalar_stage[MESA_SHADER_COMPUTE] || !elk->nir_options[MESA_SHADER_COMPUTE]))) + return report(error, STELA_INTEL_AIR_DEVICE, "Matching initialized device/ISA/compiler callbacks required"); + const nir_shader_compiler_options *actual_options = brw ? &brw->nir_options[MESA_SHADER_COMPUTE] : elk->nir_options[MESA_SHADER_COMPUTE]; + if (actual_options->cb_data) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Opaque NIR callback payload cannot have independent result ownership"); + /* Original brw_stage_has_packed_dispatch still asserts ver<=30 in this + * retained path. Do not reach it or infer Gen35 readiness from a device ID. */ + if (device->ver == 35) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Gen35 compiler/dispatch qualification hold"); + if (!options->max_instructions || !options->max_code_bytes || options->max_code_bytes > MAX_CODE) + return report(error, STELA_INTEL_AIR_LIMIT, "Explicit instruction/resident code budgets required"); + if ((options->fp_profile != STELA_AIR_FP_IEEE_DEFAULT && options->fp_profile != STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41) || + (options->subgroup_size && options->subgroup_size != 8 && options->subgroup_size != 16 && options->subgroup_size != 32) || + (options->subgroup_size == 8 && device->ver >= 20)) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Unsupported FP/subgroup specialization"); + uint64_t threads = 1; + for (unsigned i = 0; i < 3; i++) { + unsigned count = options->workgroup_size[i]; + if (!count || count > 1024 || threads > 1024 / count) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Invalid workgroup specialization"); + threads *= count; + } + if (threads > (uint64_t)device->max_cs_workgroup_threads * 32) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Workgroup exceeds actual compiler thread capacity"); + const struct stela_metal_library_manifest *manifest = stela_metal_assembly_manifest(library); + if (!manifest || manifest->size != sizeof(*manifest) || manifest->abi != STELA_METAL_LIBRARY_ABI || selected >= manifest->entry_count) + return report(error, STELA_INTEL_AIR_INVALID, "Invalid canonical selected entry"); + const struct stela_metal_function_record *record = &manifest->entries[selected]; + if (record->size != sizeof(*record) || record->abi != STELA_METAL_LIBRARY_ABI || !(record->flags & STELA_METAL_ENTRY_NO_CONSTANTS)) + return report(error, STELA_INTEL_AIR_UNSUPPORTED, "Unsupported entry/function constants"); + struct stela_metal_input_view original = {.size = sizeof(original), .abi = STELA_METAL_INPUT_ABI}; + if (stela_metal_assembly_original(library, &original, NULL) != STELA_METAL_ASSEMBLY_OK || + record->air_offset > original.length || record->air_bytes > original.length - record->air_offset || + !record->air_bytes || record->air_bytes > AIR_MAX_BITCODE_BYTES) + return report(error, STELA_INTEL_AIR_INVALID, "Invalid retained raw AIR span"); + struct stela_metal_threadgroup_specialization threadgroup; + enum stela_metal_threadgroup_status shared_status = stela_metal_threadgroup_normalize( + record->arguments, record->argument_count, request, intel_device_info_get_max_slm_size(device), &threadgroup); + if (shared_status != STELA_METAL_THREADGROUP_OK) + return report(error, shared_status == STELA_METAL_THREADGROUP_INVALID ? STELA_INTEL_AIR_INVALID : + shared_status == STELA_METAL_THREADGROUP_LIMIT ? STELA_INTEL_AIR_LIMIT : STELA_INTEL_AIR_UNSUPPORTED, + "Resource requires a supported threadgroup binding specialization"); + struct stela_intel_air_compilation *owner = calloc(1, sizeof(*owner)); + if (!owner) return report(error, STELA_INTEL_AIR_ALLOCATION, "Compilation owner allocation failed"); + owner->provenance.options = *options; owner->provenance.threadgroup = threadgroup; owner->provenance.device = *device; + struct stela_intel_air_policy *policy = &owner->provenance.policy; + if (brw) { + policy->precise_trig = brw->precise_trig; policy->lower_dpas = brw->lower_dpas; + policy->optimistic_simd_heuristic = brw->optimistic_simd_heuristic; policy->spilling_rate = brw->spilling_rate; + policy->register_file_size = brw->register_file_size; policy->register_pressure_threshold = brw->register_pressure_threshold; + policy->lowered_format_count = brw->num_lowered_storage_formats; policy->lowered_formats = brw->lowered_storage_formats; + owner->nir_options = brw->nir_options[MESA_SHADER_COMPUTE]; + } else { + policy->precise_trig = elk->precise_trig; policy->spilling_rate = elk->spilling_rate; + policy->scalar_stage = elk->scalar_stage[MESA_SHADER_COMPUTE]; policy->constant_buffer_0_is_relative = elk->constant_buffer_0_is_relative; + policy->supports_shader_constants = elk->supports_shader_constants; policy->has_negative_rhw_bug = elk->has_negative_rhw_bug; + owner->nir_options = *elk->nir_options[MESA_SHADER_COMPUTE]; + } + memcpy(policy->debug, intel_debug, sizeof(policy->debug)); policy->simd = intel_simd; policy->simd_overridden = intel_simd_overridden; + enum stela_intel_air_status status = copy_provenance(owner, manifest, record, selected, error); + if (!status) status = prepare_bindings(owner, error); + if (!status) { + owner->context = ralloc_context(NULL); + if (!owner->context) status = report(error, STELA_INTEL_AIR_ALLOCATION, "Original ralloc context allocation failed"); + } + if (status) { stela_intel_air_destroy(&owner); return status; } + glsl_type_singleton_init_or_ref(); owner->type_reference = true; + struct stela_air_options air = {.workgroup_size = {options->workgroup_size[0], options->workgroup_size[1], options->workgroup_size[2]}, + .max_instructions = options->max_instructions, .fp_profile = options->fp_profile, + .bind_ssbo = owner->binding_count ? bind_ssbo : NULL, .ssbo_count = owner->binding_count, + .binding_data = owner, .bind_threadgroup = threadgroup.count ? bind_threadgroup : NULL, + .max_threadgroup_bytes = intel_device_info_get_max_slm_size(device)}; + struct stela_air_error air_error; + owner->shader = stela_air_to_nir(original.bytes + record->air_offset, (size_t)record->air_bytes, + owner->provenance.name, &owner->nir_options, &air, &air_error); + if (!owner->shader) { + if (error) error->air = air_error; + status = report(error, STELA_INTEL_AIR_FRONTEND, "Shared AIR frontend refused selected body/policy"); + } else { + if (brw) { const struct brw_nir_compiler_opts opts = {0}; brw_preprocess_nir(brw, owner->shader, &opts); } + else { const struct elk_nir_compiler_opts opts = {0}; elk_preprocess_nir(elk, owner->shader, &opts); } + const nir_lower_compute_system_values_options sys = {.has_base_workgroup_id = false}; + NIR_PASS(_, owner->shader, nir_lower_compute_system_values, &sys); + nir_shader_gather_info(owner->shader, nir_shader_get_entrypoint(owner->shader)); + if (stela_intel_fp_controls(device, &owner->shader->info)) + status = report(error, STELA_INTEL_AIR_UNSUPPORTED, "FP controls unsupported by actual hardware contract"); + } + if (!status) { + owner->work_context = ralloc_context(NULL); + if (!owner->work_context) status = report(error, STELA_INTEL_AIR_ALLOCATION, "Original working context allocation failed"); + } + if (!status) { + if (options->subgroup_size) owner->shader->info.min_subgroup_size = owner->shader->info.max_subgroup_size = (uint8_t)options->subgroup_size; + if (brw) { + struct brw_cs_prog_key key = {0}; brw_nir_lower_cs_intrinsics(owner->shader, device, &owner->brw); + if (brw_nir_lower_cs_subgroup_id(owner->shader, device, 0)) { + owner->brw.base.push_sizes[0] = 4; brw_cs_fill_push_const_info(device, &owner->brw, 0); + owner->brw.base.push_sizes[0] = REG_SIZE; + } else brw_cs_fill_push_const_info(device, &owner->brw, -1); + nir_validate_shader(owner->shader, "owned AIR indexed SSBO BRW"); + struct brw_compile_cs_params p = {.base = {.mem_ctx = owner->work_context, .nir = owner->shader, + .key = &key.base, .prog_data = &owner->brw.base, .log_data = log_data}}; + const void *code = brw_compile(brw, &p.base); status = capture(owner, code, p.base.error_str, NULL, error); + } else { + owner->elk.base.param = ralloc_array(owner->context, uint32_t, 0); + if (!owner->elk.base.param) status = report(error, STELA_INTEL_AIR_ALLOCATION, "Original ELK parameter owner allocation failed"); + else { + struct elk_cs_prog_key key = {0}; elk_nir_lower_cs_intrinsics(owner->shader, device, &owner->elk); + if (!gen7_shared_io_supported(device, owner->shader)) + status = report(error, STELA_INTEL_AIR_UNSUPPORTED, "Gen7 shared access qualification excludes byte-scattered paths"); + else { + nir_validate_shader(owner->shader, "owned AIR indexed SSBO ELK"); + struct elk_compile_cs_params p = {.base = {.mem_ctx = owner->work_context, .nir = owner->shader, .log_data = log_data}, .key = &key, .prog_data = &owner->elk}; + const void *code = elk_compile_cs(elk, &p); status = capture(owner, code, p.base.error_str, elk, error); + } + } + } + } + if (status) { stela_intel_air_destroy(&owner); return status; } + ralloc_free(owner->work_context); owner->work_context = NULL; + *output = owner; return report(error, STELA_INTEL_AIR_OK, ""); +} +const struct stela_intel_air_binary *stela_intel_air_binary(const struct stela_intel_air_compilation *owner) { return owner ? &owner->binary : NULL; } +const nir_shader *stela_intel_air_nir(const struct stela_intel_air_compilation *owner) { return owner ? owner->shader : NULL; } +const struct stela_intel_air_provenance *stela_intel_air_provenance(const struct stela_intel_air_compilation *owner) { return owner ? &owner->provenance : NULL; } +const struct stela_intel_air_binding *stela_intel_air_bindings(const struct stela_intel_air_compilation *owner, uint32_t *count) +{ if (count) *count = owner ? owner->binding_count : 0; return owner ? owner->bindings : NULL; } diff --git a/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.h b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.h new file mode 100644 index 0000000000..2c42e8e0cb --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_compile.h @@ -0,0 +1,131 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_AIR_COMPILE_H +#define STELA_INTEL_AIR_COMPILE_H +#include "../../../metal/compiler/library_assembly.h" +#include "stela/air_to_nir.h" +#include "../../../metal/compiler/threadgroup.h" +#include "intel/compiler/brw/brw_compiler.h" +#include "intel/compiler/elk/elk_compiler.h" +#include "intel/dev/intel_debug.h" +#ifdef __cplusplus +extern "C" { +#endif +#define STELA_INTEL_AIR_ABI 1u +enum stela_intel_air_status { + STELA_INTEL_AIR_OK, STELA_INTEL_AIR_INVALID, STELA_INTEL_AIR_UNSUPPORTED, + STELA_INTEL_AIR_DEVICE, STELA_INTEL_AIR_LIMIT, STELA_INTEL_AIR_ALLOCATION, + STELA_INTEL_AIR_FRONTEND, STELA_INTEL_AIR_BACKEND, +}; +enum stela_intel_air_backend { STELA_INTEL_AIR_BRW = 1, STELA_INTEL_AIR_ELK = 2 }; +struct stela_intel_air_options { + uint32_t size, abi, workgroup_size[3], max_instructions, max_code_bytes; + /* Zero retains original compiler SIMD selection; fixed8/16/32 is explicit + * specialization, not inferred from Apple CPU or a test device name. */ + uint32_t subgroup_size; + enum stela_air_fp_profile fp_profile; +}; +struct stela_intel_air_error { + enum stela_intel_air_status status; + struct stela_air_error air; + char detail[256]; +}; +struct stela_intel_air_binding { struct stela_air_buffer buffer; uint32_t slot; }; +/* Actual code-affecting compiler policy, copied without object/RA/callback + * pointers. NIR options remain available through the owned NIR. */ +struct stela_intel_air_policy { + bool precise_trig, lower_dpas, optimistic_simd_heuristic; + bool scalar_stage, constant_buffer_0_is_relative, supports_shader_constants, has_negative_rhw_bug; + int spilling_rate; + uint32_t register_file_size, register_pressure_threshold, lowered_format_count; + const uint32_t *lowered_formats; + BITSET_WORD debug[BITSET_WORDS(INTEL_DEBUG_MAX)]; + uint64_t simd; + uint32_t simd_overridden; +}; +/* Same-process immutable evidence, not serialized IPC or a cache wire format. + * Compiler/source provenance is absent for an archive unless independently + * established by its actual owner. An FP profile authenticates no input. */ +struct stela_intel_air_provenance { + struct stela_metal_input_info input; + struct stela_metal_input_entry entry; + uint32_t selected_entry, entry_flags, library_flags, compiler_profile; + uint32_t request_language, request_fast_math, argument_count; + uint64_t air_offset, air_bytes; + uint8_t air_sha256[32], source_sha256[32]; + struct stela_msl_build_identity build; + const char *name, *target; + const struct stela_air_argument_info *arguments; + struct stela_intel_air_options options; + struct intel_device_info device; + struct stela_intel_air_policy policy; + struct stela_metal_threadgroup_specialization threadgroup; +}; +struct stela_intel_air_binary { + enum stela_intel_air_backend backend; + const void *code; + uint32_t code_bytes, executable_bytes; + const struct brw_cs_prog_data *brw; + const struct elk_cs_prog_data *elk; +}; +struct stela_intel_air_compilation; +/* Hosted same-CPU compiler. Exactly ONE compiler must be the actual initialized + * matching device/ISA/RA context from this retained build, with genuine debug + * and performance callbacks. Borrowed log_data must be valid for those callbacks + * throughout compilation (NULL only if they support it); it is never retained. + * Actual compute NIR options must have NULL cb_data: opaque callback payload + * ownership cannot be copied or inferred. Non-NULL is refused before allocation. + * The retained compiler implementation must remain loaded for owned NIR + * services/function pointers. All borrowed context policy must stay immutable + * during this call. No device discovery/construction occurs here. The output + * slot is uniquely owned and initially NULL; failures preserve it. The result + * retains no compiler/assembly pointer, and owns original code/progdata, + * relocations, constant data, ELK params, NIR/options and GLSL type lifetimes. + * + * Current ABI maps every declared ordinary AS1 argument (including unused + * arguments) to a distinct contiguous SSBO slot in metadata order. Zero such + * arguments is valid. The existing shared frontend's exact32-bit view-size + * query and bounds lowering remain intact. The actual resource owner uses + * stela_intel_raw_buffer_state with the exact Metal view/rights/alignment, + * including ISL's mapped padding, then uploads real surface states/table + * offsets and retains device/VM/mapping/cache/visibility/fence lifetimes. + * No fixed VA, resource allocator or caller flag authenticates that ownership. + * + * Returned resident bytes include original constant data and unpatched + * relocation records; executable_bytes excludes trailing constant data. + * Apply original relocation helpers and real resource values before upload. + * Scratch/push/SLM/barriers/SIMD are genuine requirements, not readiness. + * Existing compute/legacy producers retain their restrictions, including + * Gen35 original compiler/dispatch qualification hold (refused before its + * assert-bearing path). Gen7/7.5 FP32-preserve is explicitly refused. + * DynamicAS3 specialization and incomplete canonical global reflection remain + * unsupported. No Metal PSO, initialization, upload or GPU work is created. + * Wrapper OOM is typed; original compiler fatal/OOM/cancellation remains the + * normal compiler process owner's responsibility. All views are serialized + * against mutation/destruction; no C++/Rust/host pointers cross the native ABI. */ +/* Exact dispatch-size specialization; existing compile() delegates with NULL. + * Request arrays are borrowed only during the call and copied into provenance. + * Backend shared totals include these rows plus static layout, never expose + * them as Metal staticThreadgroupMemoryLength or add dynamic bytes twice. + * stela_metal_threadgroup_matches checks values only, not resource ownership. */ +enum stela_intel_air_status stela_intel_air_compile_specialized(const struct brw_compiler *, + const struct elk_compiler *, void *log_data, const struct stela_metal_assembly *, uint32_t selected_entry, + const struct stela_intel_air_options *, const struct stela_metal_threadgroup_request *, + struct stela_intel_air_compilation **, + struct stela_intel_air_error *); + +enum stela_intel_air_status stela_intel_air_compile(const struct brw_compiler *, + const struct elk_compiler *, void *log_data, const struct stela_metal_assembly *, uint32_t selected_entry, + const struct stela_intel_air_options *, struct stela_intel_air_compilation **, + struct stela_intel_air_error *); +const struct stela_intel_air_binary *stela_intel_air_binary(const struct stela_intel_air_compilation *); +const nir_shader *stela_intel_air_nir(const struct stela_intel_air_compilation *); +const struct stela_intel_air_provenance *stela_intel_air_provenance(const struct stela_intel_air_compilation *); +const struct stela_intel_air_binding *stela_intel_air_bindings(const struct stela_intel_air_compilation *, uint32_t *count); +void stela_intel_air_destroy(struct stela_intel_air_compilation **); +/* Internal separately compiled TU: original EU implementation headers share + * enumerators across BRW/ELK, so retain the original ELK header in isolation. */ +bool stela_intel_air_validate_elk(const struct elk_compiler *, const void *, uint32_t); +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/hosted/air_validate_elk.c b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_validate_elk.c new file mode 100644 index 0000000000..e3b200206e --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/hosted/air_validate_elk.c @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: MIT */ +#include "intel/compiler/elk/elk_eu.h" +#include "intel/compiler/elk/elk_compiler.h" +/* Own helper declaration also in air_compile.h; its BRW declarations cannot + * be co-included with original ELK EU implementation enums. */ +bool stela_intel_air_validate_elk(const struct elk_compiler *, const void *, uint32_t); +bool stela_intel_air_validate_elk(const struct elk_compiler *compiler, const void *code, uint32_t bytes) +{ + return compiler && code && bytes && bytes <= INT32_MAX && + elk_validate_instructions(&compiler->isa, code, 0, (int)bytes, NULL); +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/pat.c b/crates/stela-drivers/src/gpu/intel/stela/pat.c new file mode 100644 index 0000000000..48d42796b8 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/pat.c @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: MIT */ +#include "pat.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_gt_type.h" +#include "../xe/xe_force_wake_domain_types.h" +#include "../xe/regs/xe_reg_defs.h" +#include "pat_compile_defs.h" +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +struct diagnostics { bool warning, missing; }; +#define XE_PAT_SELECT_WARN(context, condition) (((struct diagnostics *)(context))->warning |= !!(condition)) +#define XE_PAT_SELECT_MISSING(context, version) ((void)(version), ((struct diagnostics *)(context))->missing = true) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-field-initializers" +#include "../xe/xe_pat_select.h" +#pragma clang diagnostic pop +struct program { + const struct stela_intel_activation_io *io; + void *context; + struct stela_intel_pat_result *result; +}; +static void write32(void *context, struct xe_reg reg, uint32_t value) +{ + struct program *program = context; + program->io->write32(program->context, reg.addr, value); + program->result->writes++; +} +#define XE_PAT_PROGRAM_WRITE(context, reg, value) write32(context, reg, value) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" +#include "../xe/xe_pat_program.h" +#pragma clang diagnostic pop +int stela_intel_pat_program(const struct stela_intel_activation_io *io, void *context, + const struct stela_intel_activation_facts *facts, struct stela_intel_pat_result *out) +{ + if (!io || !io->write32 || !io->check_context || !facts || !out) return -22; + if (!facts->platform || facts->platform > INT32_MAX) return -22; + if (facts->gt_type != XE_GT_TYPE_MAIN || !facts->graphics_verx100 || + facts->discrete > 1 || facts->has_llc > 1 || + !(facts->initialized & XE_FW_GT) || !(facts->awake & XE_FW_GT)) return -95; + int status = io->check_context(context); + if (status) return status; + struct xe_pat_selection selection = {0}; + struct diagnostics diagnostics = {0}; + if (!xe_pat_select(&selection, (enum xe_platform)facts->platform, + facts->graphics_verx100, facts->discrete != 0, + facts->has_llc != 0, &diagnostics)) return -95; + /* Profile identity is actual original programmer policy, not table equality: + * DG2 uses the same entries but requires its real multicast MCR operations. */ + if (selection.profile != XE_PAT_PROFILE_XELP || diagnostics.warning || diagnostics.missing || + selection.n_entries != 4 || selection.pat_ats || selection.pat_primary_pta || + selection.pat_media_pta) return -95; + for (int i = 0; i < selection.n_entries; i++) { + uint32_t offset = (uint32_t)_PAT_INDEX(i); + if (offset % 4 || offset > SZ_4M - 4) return -34; + } + struct stela_intel_pat_result result = { + .n_entries = (uint32_t)selection.n_entries, + .cache_none = selection.idx[XE_CACHE_NONE], .cache_wt = selection.idx[XE_CACHE_WT], + .cache_wb = selection.idx[XE_CACHE_WB], + .cache_none_compression = selection.idx[XE_CACHE_NONE_COMPRESSION], + .cache_wb_compression = selection.idx[XE_CACHE_WB_COMPRESSION], + }; + for (int i = 0; i < selection.n_entries; i++) result.entries[i] = selection.table[i].value; + struct program program = {io, context, &result}; + /* Whole original direct loop; no fallible operation/allocation after effects. */ + xe_pat_program_direct(&program, selection.table, selection.n_entries, + selection.pat_ats, selection.pat_primary_pta); + *out = result; + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/pat.h b/crates/stela-drivers/src/gpu/intel/stela/pat.h new file mode 100644 index 0000000000..27db6ddc3d --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/pat.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_PAT_H +#define STELA_INTEL_PAT_H +#include "activation.h" +struct stela_intel_pat_result { + uint32_t writes, n_entries; + uint16_t cache_none, cache_wt, cache_wb, cache_none_compression, cache_wb_compression, reserved; + uint32_t entries[4]; +}; +_Static_assert(sizeof(struct stela_intel_pat_result) == 36, "PAT result ABI"); +_Static_assert(offsetof(struct stela_intel_pat_result, entries) == 20, "PAT entries ABI"); +/* Private same-Device adapter: genuine descriptor/GT facts, exclusive root GT + * wake, original WA/MMIO/cache/power/reset prerequisites and same canonical + * UC view are mandatory. No default callbacks, allocator or guest pointers. + * Unsupported methods refuse before I/O; error preserves output. Success only + * records original ordered writes issued, not readback/ACK/READY/cache drain. + * Unexpected access faults fail-stop under the actual retained owner contract. + */ +/* Opaque actual Device-state entry, not caller-constructed policy/facts. */ +int stela_intel_activation_pat(struct stela_intel_activation *, struct stela_intel_pat_result *); +int stela_intel_pat_program(const struct stela_intel_activation_io *, void *, + const struct stela_intel_activation_facts *, struct stela_intel_pat_result *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/activation.c b/crates/stela-drivers/src/gpu/intel/stela/tests/activation.c new file mode 100644 index 0000000000..b71243deb1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/activation.c @@ -0,0 +1,241 @@ +/* SPDX-License-Identifier: MIT */ +/* Offline MMIO model; never a production owner or physical activation. */ +#include +#include +#include +#include +#include +#include +#include "../activation.c" + +struct model { + pthread_mutex_t lock; + uint32_t graphics, media, ack, last_control; + unsigned prepares, reads, writes, reports; + bool wake_timeout, sleep_timeout, all_ones; + int prepare_error; +}; +static int check_context(void *data) +{ + struct model *m = data; + int status = pthread_mutex_trylock(&m->lock); + if (status == EBUSY) return 0; + if (!status) assert(pthread_mutex_unlock(&m->lock) == 0); + return -16; +} +static int prepare(void *data, uint32_t platform, uint32_t revision, bool discrete) +{ + struct model *m = data; + (void)platform; (void)revision; (void)discrete; + /* This records simulated preparation only. It never certifies native PM. */ + ++m->prepares; + return m->prepare_error; +} +static uint32_t read_model(void *data, uint32_t offset) +{ + struct model *m = data; ++m->reads; + if (offset == GMD_ID.addr) return m->graphics; + if (offset == GMD_ID.addr + MEDIA_GT_GSI_OFFSET) return m->media; + if (offset == XEHP_MTCFG_ADDR.addr) return 0; + assert(offset == FORCEWAKE_ACK_GT.addr || offset == FORCEWAKE_ACK_GT_MTL.addr); + return m->all_ones ? UINT32_MAX : m->ack; +} +static void write_model(void *data, uint32_t offset, uint32_t value) +{ + struct model *m = data; ++m->writes; + assert(offset == FORCEWAKE_GT.addr); + m->last_control = value; + assert(value == (FORCEWAKE_MT_MASK(0) | FORCEWAKE_MT(0)) || value == FORCEWAKE_MT_MASK(0)); + if (value & 1) { if (!m->wake_timeout) m->ack = 1; } + else if (!m->sleep_timeout) m->ack = 0; +} +static int64_t now(void *data) +{ + (void)data; struct timespec t; + assert(clock_gettime(CLOCK_MONOTONIC, &t) == 0); + return t.tv_sec * INT64_C(1000000000) + t.tv_nsec; +} +static int64_t invalid_clock(void *data) { (void)data; return -1; } +static void delay(void *data, uint32_t minimum, uint32_t maximum, bool atomic) +{ + assert(minimum <= maximum); + int64_t end = now(data) + (int64_t)minimum * 1000; + if (atomic) while (now(data) < end) __asm__ volatile("pause"); + else { + struct timespec t = {minimum / 1000000, (long)(minimum % 1000000) * 1000}; + while (nanosleep(&t, &t) && errno == EINTR) {} + } +} +static void check(void *data, bool condition) { (void)data; assert(condition); } +static void report(void *data, uint32_t mask, bool wake, int status, uint32_t value) +{ + (void)wake; (void)status; (void)value; assert(mask == XE_FW_GT); ++((struct model *)data)->reports; +} +static const struct stela_intel_activation_io io = {check_context, prepare, read_model, write_model, now, delay, check, report}; + +/* Real host serialization guards both independently compiled policy fragments; + * no spinlock, IRQ, timer or power success is fabricated for a native device. */ +#ifdef STELA_DONOR_CHECK +struct trace { uint32_t words[256]; unsigned used, failures; }; +static void trace_control(void *data, struct xe_force_wake_domain *domain, bool wake) +{ + struct trace *t = data; assert(t->used < ARRAY_SIZE(t->words)); + t->words[t->used++] = domain->id * 4u + (wake ? 1u : 0u); +} +static int trace_wait(void *data, struct xe_force_wake_domain *domain, bool wake) +{ + struct trace *t = data; assert(t->used < ARRAY_SIZE(t->words)); + t->words[t->used++] = domain->id * 4u + (wake ? 3u : 2u); + return t->failures & (1u << domain->id) ? -110 : 0; +} +static const struct xe_force_wake_core_ops trace_ops = {trace_control, trace_wait, check}; + +#include "activation_donor.h" +static unsigned original_traces(void) +{ + pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + unsigned cases = 0; + for (unsigned initialized = 1; initialized < 8; ++initialized) + for (unsigned failures = 0; failures < 8; ++failures) + for (unsigned nested = 0; nested < 3; ++nested) { + struct xe_force_wake_domain a[XE_FW_DOMAIN_ID_COUNT] = {0}; + for (unsigned i = 0; i < 3; ++i) { + a[i].id = (enum xe_force_wake_domain_id)i; a[i].reg_ctl.addr = 4 * (i + 1); + a[i].ref = initialized & (1u << i) ? nested : 0; + } + struct trace ta = {.failures = failures}; + unsigned awake = nested ? initialized : 0; + struct xe_force_wake_core core = {&ta, &trace_ops, initialized, &awake, a}; + unsigned af; + struct stela_intel_policy_result donor; + assert(pthread_mutex_lock(&lock) == 0); + unsigned ar = xe_force_wake_get_locked(&core, XE_FORCEWAKE_ALL, &af); + unsigned put_failed = xe_force_wake_put_locked(&core, ar); + stela_intel_donor_policy(initialized, failures, nested, &donor); + assert(ar == donor.get && af == donor.failed && put_failed == donor.put_failed && + awake == donor.awake && ta.used == donor.used && + !memcmp(ta.words, donor.words, sizeof(ta.words))); + for (unsigned i = 0; i < 3; ++i) assert(a[i].ref == donor.refs[i]); + assert(pthread_mutex_unlock(&lock) == 0); ++cases; + } + assert(pthread_mutex_destroy(&lock) == 0); + return cases; +} +#endif + +int main(void) +{ + static_assert(sizeof(struct xe_reg) == 4); + struct xe_reg r = {.addr = 1}; assert(r.raw == 1); + r = (struct xe_reg){.masked = 1}; assert(r.raw == (1u << 22)); + r = (struct xe_reg){.mcr = 1}; assert(r.raw == (1u << 23)); + r = (struct xe_reg){.vf = 1}; assert(r.raw == (1u << 24)); + struct model m = {.lock = PTHREAD_MUTEX_INITIALIZER, + .graphics = (1270 / 100u << 22) | (1270 % 100u << 14), .media = 1300 / 100u << 22}; + struct stela_intel_activation state, before; memset(&before, 0xa5, sizeof(before)); + /* The all-zero terminator is not a PCI device or a descriptor. */ + assert(stela_intel_activation_match(0, 0, 0, false, true) == -19); + assert(stela_intel_activation_match(0x8086, 0xffff, 0x030000, false, true) == -19); + unsigned matches = 0; + for (size_t i = 0; i + 1 < ARRAY_SIZE(pciidlist); ++i) { + const struct stela_intel_pci_match *p = &pciidlist[i]; + assert(pthread_mutex_lock(&m.lock) == 0); + state = before; + assert(stela_intel_activation_match(p->vendor, p->device, p->class, false, true) == 0); + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + p->vendor, p->device, p->class, 0, UINT64_C(64) << 20, false, true) == 0); + assert(state.facts.platform == (uint32_t)p->driver_data->platform && + state.facts.dma_bits == p->driver_data->dma_mask_size && !state.facts.awake); + assert(stela_intel_activation_wake(&state) == 0 && state.facts.awake == XE_FW_GT); + unsigned writes = m.writes; + assert(stela_intel_activation_wake(&state) == 0 && m.writes == writes); + assert(stela_intel_activation_sleep(&state) == 0 && m.writes == writes); + assert(stela_intel_activation_sleep(&state) == 0 && !state.facts.awake); + assert(stela_intel_activation_sleep(&state) == -22); + assert(pthread_mutex_unlock(&m.lock) == 0); ++matches; + } + const struct stela_intel_pci_match *p = &pciidlist[0]; + state = before; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + p->vendor, p->device, p->class, 0, UINT64_C(64) << 20, false, true) == -16); + assert(!memcmp(&state, &before, sizeof(state))); + assert(pthread_mutex_lock(&m.lock) == 0); + for (unsigned bad = 0; bad < 14; ++bad) { + state = before; struct stela_intel_activation_io missing = io; + if (bad == 0) missing.check_context = NULL; + if (bad == 1) missing.prepare = NULL; + if (bad == 2) missing.read32 = NULL; + if (bad == 3) missing.write32 = NULL; + if (bad == 4) missing.now_ns = NULL; + if (bad == 5) missing.delay_us = NULL; + if (bad == 6) missing.invariant = NULL; + if (bad == 7) missing.report = NULL; + m.prepare_error = bad == 12 ? -5 : 0; + if (bad == 13) missing.now_ns = invalid_clock; + int ret = stela_intel_activation_init(&state, sizeof(state), &missing, &m, + bad == 8 ? 0 : p->vendor, p->device, p->class, 0, + bad == 9 ? 4096 : UINT64_C(64) << 20, bad == 10, bad != 11); + assert(ret && !memcmp(&state, &before, sizeof(state))); + } + m.prepare_error = 0; + const struct stela_intel_pci_match *post = pciidlist; + while (post->driver_data && post->driver_data->pre_gmdid_graphics_ip) ++post; + assert(post->driver_data); + for (unsigned bad = 0; bad < 3; ++bad) { + state = before; + m.graphics = bad == 0 ? UINT32_MAX : bad == 1 ? 63u << 22 : 1270 / 100u << 22 | 1270 % 100u << 14; + m.media = bad == 2 ? 63u << 22 : 1300 / 100u << 22; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + post->vendor, post->device, post->class, 0, UINT64_C(64) << 20, false, true) < 0); + assert(!memcmp(&state, &before, sizeof(state))); + } + /* Hardware GMDID selection is exercised independently of PCI fixtures: + * every original runtime IP entry, actual field layout and revision bits. */ + unsigned runtime_ips = 0; + for (size_t i = 0; i < ARRAY_SIZE(graphics_ips); ++i) { + uint32_t version = graphics_ips[i].verx100; + m.graphics = version / 100u << 22 | version % 100u << 14 | 17; + m.media = 1300 / 100u << 22 | 11; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + post->vendor, post->device, post->class, 0, UINT64_C(64) << 20, false, true) == 0); + assert(state.facts.graphics_verx100 == version && state.facts.graphics_revision == 17 && + state.facts.media_revision == 11 && state.facts.gt_ack == FORCEWAKE_ACK_GT_MTL.addr); + ++runtime_ips; + } + for (size_t i = 0; i < ARRAY_SIZE(media_ips); ++i) { + uint32_t version = media_ips[i].verx100; + m.media = version / 100u << 22 | version % 100u << 14 | 9; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + post->vendor, post->device, post->class, 0, UINT64_C(64) << 20, false, true) == 0); + assert(state.facts.media_verx100 == version && state.facts.media_revision == 9); + ++runtime_ips; + } + for (u8 maximum = 1; maximum < 5; ++maximum) + for (u32 field = 0; field < 4; ++field) { + u8 count = (u8)(field + 1); + assert(xe_pci_runtime_tile_count(maximum, REG_FIELD_PREP(TILE_COUNT, field)) == + (count < maximum ? count : maximum)); + } + m.graphics = 1270 / 100u << 22 | 1270 % 100u << 14; m.media = 0; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + post->vendor, post->device, post->class, 0, UINT64_C(64) << 20, false, true) == 0); + assert(state.facts.media_verx100 == 0); + for (unsigned bad = 0; bad < 3; ++bad) { + m.wake_timeout = bad == 0; m.sleep_timeout = bad == 1; m.all_ones = bad == 2; m.ack = 0; + assert(stela_intel_activation_init(&state, sizeof(state), &io, &m, + p->vendor, p->device, p->class, 0, UINT64_C(64) << 20, false, true) == 0); + int64_t start = now(&m); + int ret = stela_intel_activation_wake(&state); + if (bad == 1) { assert(ret == 0); ret = stela_intel_activation_sleep(&state); } + assert(ret == (bad == 2 ? -5 : -110)); + if (bad < 2) assert(now(&m) - start >= INT64_C(50000000)); + assert(state.poisoned && stela_intel_activation_wake(&state) == -5); + } + assert(pthread_mutex_unlock(&m.lock) == 0 && pthread_mutex_destroy(&m.lock) == 0); + printf("Intel activation model: %u original PCI rows, 18 atomic refusals, 2 pure unmatched/terminator refusals, fused-off media, real-clock ACK timeout/all-ones checks", matches); +#ifdef STELA_DONOR_CHECK + printf(", %u original-object/core traces", original_traces()); +#endif + printf(", %u runtime IP entries and 16 bounded tile cases; no physical hardware activation\n", runtime_ips); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/activation.rs b/crates/stela-drivers/src/gpu/intel/stela/tests/activation.rs new file mode 100644 index 0000000000..fe3b72d654 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/activation.rs @@ -0,0 +1,1073 @@ +//! Explicit RAM/MMIO models; never a production PCI/power/cache provider. +extern crate alloc; +#[path = "firmware.rs"] +mod intel; +use activation::{Device, Error, PciIdentity, ProbeOwner}; +use bus::mmio::owned::*; +#[path = "wopcm.rs"] +mod wopcm_tests; +use std::{ + alloc::{Layout, alloc_zeroed, dealloc}, + ptr::NonNull, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; +pub use stela_drivers::{bus, firmware, gpu::intel::activation}; + +const BYTES: usize = 16 * 1024 * 1024; +const CONTROL: usize = 0xa188; +const ACK: usize = 0x130044; +struct Memory { + pointer: NonNull, + layout: Layout, +} +// SAFETY: model memory is accessed through raw volatile words under the single +// CPU-affine Device; no Rust reference or concurrently driven hardware exists. +unsafe impl Send for Memory {} +// SAFETY: same explicitly serialized RAM-only model access contract. +unsafe impl Sync for Memory {} +impl Drop for Memory { + fn drop(&mut self) { + // SAFETY: exact standard allocation; canonical/resource owners ended. + unsafe { dealloc(self.pointer.as_ptr(), self.layout) }; + } +} +struct Reservation { + base: u64, + memory: Arc, + epoch: Arc, +} +impl Drop for Reservation { + fn drop(&mut self) { + self.epoch + .reservation_dropped + .fetch_add(1, Ordering::SeqCst); + } +} +// SAFETY: a model reservation of its own live host RAM, not a hardware claim. +unsafe impl ResourceBacking for Reservation { + fn physical_span(&self) -> PhysicalSpan { + PhysicalSpan::new(self.base, BYTES as u64).unwrap() + } + fn kind(&self) -> ResourceKind { + ResourceKind::Registers + } +} +#[derive(Default)] +struct Platform { + fail_unmap: AtomicUsize, + fail_map: AtomicUsize, + calls: Mutex>, +} +// SAFETY: test-only page-table model returns actual aligned live RAM and tracks +// exact unique tokens. It does not qualify real PAT/MTRR/device mappings. +unsafe impl MappingPlatform for Platform { + fn check_context(&self, _: AddressSpace) -> Result<(), bus::mmio::owned::Error> { + Ok(()) + } + unsafe fn map( + &self, + resource: &Resource, + request: MapRequest, + ) -> Result { + let backing = resource.backing().downcast_ref::().unwrap(); + assert!(request.physical.start() >= resource.physical_span().start()); + let offset = + usize::try_from(request.physical.start() - resource.physical_span().start()).unwrap(); + let bytes = usize::try_from(request.physical.bytes()).unwrap(); + assert!(offset <= BYTES && bytes <= BYTES - offset); + assert!(matches!( + (offset, bytes), + (0, 4_194_304) | (8_388_608, 2_097_152 | 4_194_304 | 8_388_608) + )); + assert_eq!( + request.protection, + if offset == 0 { + Protection::ReadWrite + } else { + Protection::ReadOnly + } + ); + self.calls.lock().unwrap().push((true, request.id)); + if self.fail_map.swap(0, Ordering::SeqCst) != 0 { + return Err(MapFailure::Uncertain( + bus::mmio::owned::Error::MappingFailed, + )); + } + Ok(InstalledMapping { + token: request.id, + // SAFETY: actual same-allocation subspan proved above; no fabricated + // CPU base for BAR+8MiB. Registers and GSM are distinct real leases. + cpu_base: unsafe { + NonNull::new_unchecked(backing.memory.pointer.as_ptr().add(offset)) + }, + physical: request.physical, + attribute: request.attribute, + protection: request.protection, + }) + } + unsafe fn unmap( + &self, + request: MapRequest, + mapping: InstalledMapping, + ) -> Result<(), bus::mmio::owned::Error> { + assert_eq!(request.id, mapping.token); + self.calls.lock().unwrap().push((false, mapping.token)); + if self.fail_unmap.swap(0, Ordering::SeqCst) != 0 { + Err(bus::mmio::owned::Error::UnmapFailed) + } else { + Ok(()) + } + } +} +#[derive(Default)] +struct Counts { + prepared: AtomicUsize, + fail_prepare: AtomicUsize, + finished: AtomicUsize, + drained: AtomicUsize, + fail_finish: AtomicUsize, + context_checks: AtomicUsize, + dropped: AtomicUsize, + reservation_dropped: AtomicUsize, + wopcm_reads: AtomicUsize, + wopcm_writes: AtomicUsize, + wopcm_fail_at: AtomicUsize, + sleep_writes: AtomicUsize, + pat_writes: AtomicUsize, + pat_trace: [AtomicU64; 4], + config_reads: AtomicUsize, + config_unavailable: AtomicUsize, + gmch: AtomicUsize, + reads64: AtomicUsize, + read64_unavailable: AtomicUsize, + guc_reset_mode: AtomicUsize, + guc_reset_reads: AtomicUsize, + guc_reset_writes: AtomicUsize, +} +struct Owner { + resource: Resource, + memory: Arc, + counts: Arc, + start: Instant, + thread: std::thread::ThreadId, + device: u16, +} +impl Drop for Owner { + fn drop(&mut self) { + self.counts.dropped.fetch_add(1, Ordering::SeqCst); + } +} +impl bus::pci::ConfigSpace for Owner { + fn read32(&self, _: u16) -> u32 { + panic!("read16 must use the actual model width"); + } + fn read16(&self, offset: u16) -> u16 { + assert_eq!(offset, 0x50); + self.counts.config_reads.fetch_add(1, Ordering::SeqCst); + u16::try_from(self.counts.gmch.load(Ordering::SeqCst)).unwrap() + } + fn write32(&mut self, _: u16, _: u32) { + panic!("read-only probe"); + } + fn write16(&mut self, _: u16, _: u16) { + panic!("read-only probe"); + } + fn write8(&mut self, _: u16, _: u8) { + panic!("read-only probe"); + } +} +// SAFETY: this implements only the explicitly simulated single-thread RAM model. +// No test is evidence of PCI power, native cache attributes, IRQ or real MMIO. +unsafe impl ProbeOwner for Owner { + fn check_context(&self) -> Result<(), i32> { + self.counts.context_checks.fetch_add(1, Ordering::SeqCst); + if std::thread::current().id() == self.thread { + Ok(()) + } else { + Err(-16) + } + } + fn identity(&self) -> PciIdentity { + PciIdentity { + vendor: 0x8086, + device: self.device, + class: 0x030000, + revision: 0, + virtual_function: false, + bar0_start: self.resource.physical_span().start(), + bar0_bytes: BYTES as u64, + } + } + fn bar0(&self) -> Resource { + self.resource.clone() + } + fn config_space(&self) -> Result<&dyn bus::pci::ConfigSpace, i32> { + if self.counts.config_unavailable.load(Ordering::SeqCst) != 0 { + Err(-95) + } else { + Ok(self) + } + } + unsafe fn read64(&self, pointer: NonNull) -> Result { + if self.counts.read64_unavailable.load(Ordering::SeqCst) != 0 { + return Err(-95); + } + assert_eq!(self.counts.finished.load(Ordering::SeqCst), 0); + let offset = pointer.as_ptr() as usize - self.memory.pointer.as_ptr() as usize; + assert!((8 * 1024 * 1024..BYTES).contains(&offset)); + assert!(offset.is_multiple_of(8)); + self.counts.reads64.fetch_add(1, Ordering::SeqCst); + // SAFETY: same actual aligned GSM model allocation, no shared references. + Ok(unsafe { pointer.as_ptr().read_volatile() }) + } + fn prepare(&self, registers: &MappingView, _: u32, _: u32, _: bool) -> Result<(), i32> { + assert_eq!(registers.address(0, 4).unwrap(), self.memory.pointer); + self.counts.prepared.fetch_add(1, Ordering::SeqCst); + if self.counts.fail_prepare.load(Ordering::SeqCst) != 0 { + Err(-5) + } else { + Ok(()) + } + } + unsafe fn read32(&self, pointer: NonNull) -> u32 { + assert_eq!( + self.counts.finished.load(Ordering::SeqCst), + 0, + "drain start must permanently exclude device operations" + ); + let offset = pointer.as_ptr() as usize - self.memory.pointer.as_ptr() as usize; + if matches!(offset, 0x941c | 0xc000) { + self.counts.guc_reset_reads.fetch_add(1, Ordering::SeqCst); + let mode = self.counts.guc_reset_mode.load(Ordering::SeqCst); + return if offset == 0x941c { + if mode == 1 { 8 } else { 0 } + } else if mode == 2 { + 0 + } else { + 1 + }; + } + assert!(matches!( + offset, + ACK | 0xdfc | 0xd8c | 0x380d8c | 0xc050 | 0xc340 + )); + if matches!(offset, 0xc050 | 0xc340) { + self.counts.wopcm_reads.fetch_add(1, Ordering::SeqCst); + } + // SAFETY: actual aligned bounded model RAM, no Rust references. + unsafe { pointer.as_ptr().read_volatile() } + } + unsafe fn write32(&self, pointer: NonNull, value: u32) { + assert_eq!( + self.counts.finished.load(Ordering::SeqCst), + 0, + "drain start must permanently exclude device operations" + ); + let offset = pointer.as_ptr() as usize - self.memory.pointer.as_ptr() as usize; + if offset == 0x941c { + assert_eq!(value, 8); + self.counts.guc_reset_writes.fetch_add(1, Ordering::SeqCst); + // SAFETY: this test writes its own aligned bounded RAM mapping. + // The read callback separately models real clear/status outcomes. + unsafe { pointer.as_ptr().write_volatile(value) }; + return; + } + if (0x4800..=0x480c).contains(&offset) { + let index = self.counts.pat_writes.fetch_add(1, Ordering::SeqCst); + assert!(index < 4 && offset == 0x4800 + index * 4); + self.counts.pat_trace[index] + .store(((offset as u64) << 32) | u64::from(value), Ordering::SeqCst); + // SAFETY: same actual aligned bounded model UC mapping; ordered + // register writes only, no fabricated readback or GPU cache state. + unsafe { pointer.as_ptr().write_volatile(value) }; + return; + } + if matches!(offset, 0xc050 | 0xc340) { + let index = self.counts.wopcm_writes.fetch_add(1, Ordering::SeqCst) + 1; + // SAFETY: exact aligned RAM model word; missing ACK still retains + // the exposed write, deliberately modeling uncertain partial state. + unsafe { + let current = pointer.as_ptr().read_volatile(); + if current & 1 == 0 { + pointer.as_ptr().write_volatile( + value + | u32::from(self.counts.wopcm_fail_at.load(Ordering::SeqCst) != index), + ); + } + } + return; + } + assert_eq!(offset, CONTROL); + assert!(value == 0x10001 || value == 0x10000); + if value == 0x10000 { + self.counts.sleep_writes.fetch_add(1, Ordering::SeqCst); + } + // SAFETY: live model mapping. ACK simulates the device effect only. + unsafe { + pointer.as_ptr().write_volatile(value); + self.memory + .pointer + .as_ptr() + .add(if self.device == 0xe202 { 0xdfc } else { ACK }) + .cast::() + .write_volatile(value & 1); + } + } + fn now_ns(&self) -> i64 { + i64::try_from(self.start.elapsed().as_nanos()).unwrap() + } + fn delay_us(&self, min: u32, max: u32, atomic: bool) { + assert!(min <= max); + if atomic { + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(u64::from(min)) { + std::hint::spin_loop(); + } + } else { + std::thread::sleep(Duration::from_micros(u64::from(min))); + } + } + fn report(&self, domains: u32, _: bool, status: i32, _: u32) { + assert_eq!(domains, 1); + assert_eq!(status, 0); + } + fn finish(&self) -> Result<(), i32> { + // Record a genuine model drain side effect BEFORE the possible error. + // The owner/resource survive; a retry completes this same drain. + self.counts.finished.fetch_add(1, Ordering::SeqCst); + if self.counts.fail_finish.swap(0, Ordering::SeqCst) != 0 { + Err(-5) + } else { + self.counts.drained.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + } + fn fatal(&self) -> ! { + std::process::abort() + } +} +fn owner(base: u64, device: u16) -> (Box, Arc) { + owner_with_registers(base, device, 0, 0) +} +fn owner_with_registers( + base: u64, + device: u16, + wopcm_offset: u32, + wopcm_size: u32, +) -> (Box, Arc) { + let layout = Layout::from_size_align(BYTES, 4096).unwrap(); + // SAFETY: nonzero validated layout, actual host RAM test allocation. + let memory = Arc::new(Memory { + pointer: NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap(), + layout, + }); + // SAFETY: test fixture initializes its own real aligned RAM before sharing. + // Runtime GMDID words are explicit simulated inputs, not physical facts. + unsafe { + let bytes = memory.pointer.as_ptr(); + bytes.add(0xc340).cast::().write(wopcm_offset); + bytes.add(0xc050).cast::().write(wopcm_size); + // Independent raw-PTE oracle at prefix, default-WOPCM and last valid + // page indices. No value establishes PTE validity or GPU readiness. + bytes + .add(8 << 20) + .cast::() + .write(0xfedc_ba98_7654_3210); + for offset in [4096, 8192] { + bytes + .add((8 << 20) + offset) + .cast::() + .write(0x0123_4567_89ab_cdef); + } + for end in [2usize << 30, 0xfee0_0000] { + bytes + .add((8 << 20) + (end / 4096 - 1) * 8) + .cast::() + .write(u64::MAX); + } + if device == 0xe202 { + bytes.add(0xd8c).cast::().write((20 << 22) | (1 << 14)); + bytes + .add(0x380d8c) + .cast::() + .write((13 << 22) | (1 << 14)); + } + } + let counts = Arc::new(Counts::default()); + counts.gmch.store(2 << 6, Ordering::SeqCst); + let resource = Resource::new(Box::new(Reservation { + base, + memory: memory.clone(), + epoch: counts.clone(), + })); + ( + Box::new(Owner { + resource, + memory, + counts: counts.clone(), + start: Instant::now(), + thread: std::thread::current().id(), + device, + }), + counts, + ) +} + +#[test] +fn activation_owned_model_lifetime_and_failed_unmap_retry() { + static NEXT: AtomicU64 = AtomicU64::new(0x1000_0000); + let platform = Arc::new(Platform::default()); + // SAFETY: only this test activates the isolated executable's model roots. + let authority = unsafe { + Authority::activate( + platform.clone(), + AddressSpace { + identity: 1, + physical_bits: 48, + virtual_bits: 48, + }, + vec![], + ) + } + .unwrap(); + // Pure source selection rejects unsupported IDs/disabled force-probe before + // any map or power preparation and releases the ordinary unstarted owner. + for (id, force_probe) in [(0xffff, true), (0x9a49, false)] { + let calls = platform.calls.lock().unwrap().len(); + let (input, counts) = owner(NEXT.fetch_add(BYTES as u64, Ordering::SeqCst), id); + assert!(matches!( + Device::open(&authority, input, force_probe), + Err(Error::Native(_)) + )); + assert_eq!(platform.calls.lock().unwrap().len(), calls); + assert_eq!(counts.prepared.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + } + // Canonical uncertain-map quarantine must retain the separate native + // power/reset owner too; no prepare, CPU access or fabricated drain occurs. + let before = authority.status().unwrap().quarantined; + platform.fail_map.store(1, Ordering::SeqCst); + let (input, counts) = owner(NEXT.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + assert!(matches!( + Device::open(&authority, input, true), + Err(Error::Mapping(bus::mmio::owned::Error::MappingFailed)) + )); + assert_eq!(counts.prepared.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + assert_eq!(authority.status().unwrap().quarantined, before + 1); + // A failed real preparation may already have hardware effects. Its mapped + // resource and entire owner must remain quarantined, with no fake finish. + let before = authority.status().unwrap().quarantined; + let (input, counts) = owner(NEXT.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + counts.fail_prepare.store(1, Ordering::SeqCst); + assert!(matches!( + Device::open(&authority, input, true), + Err(Error::Native(-5)) + )); + assert_eq!(counts.prepared.load(Ordering::SeqCst), 1); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + assert_eq!(authority.status().unwrap().quarantined, before + 1); + pat_owned_contract(&authority, &NEXT); + guc_reset_owned_contract(&authority, &NEXT); + gsm_owned_contract(&authority, &platform, &NEXT); + wopcm_tests::owned_wopcm_contract(&authority, &platform, &NEXT); + huc_default_absence_never_looks_up_provider(&authority); + platform.calls.lock().unwrap().clear(); + let (input, counts) = owner(NEXT.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(&authority, input, true).unwrap(); + let facts = device.facts().unwrap(); + assert_eq!(facts.graphics_verx100, 1200); + assert_eq!(facts.gt_ack as usize, ACK); + intel::canonical_catalog_contract(&device); + intel::huc_catalog_contract(&device); + device.wake().unwrap(); + assert_eq!(device.retire(), Err(Error::Awake)); + assert_eq!(device.wake(), Err(Error::Awake)); + assert_eq!(device.facts().unwrap().awake, 1); + device.sleep().unwrap(); + counts.fail_finish.store(1, Ordering::SeqCst); + platform.fail_unmap.store(1, Ordering::SeqCst); + let calls_before = platform.calls.lock().unwrap().len(); + assert_eq!(device.retire(), Err(Error::Native(-5))); + assert_eq!( + platform.calls.lock().unwrap().len(), + calls_before, + "failed drain must not start native unmapping" + ); + assert_eq!(counts.finished.load(Ordering::SeqCst), 1); + assert_eq!(counts.drained.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + let checks = counts.context_checks.load(Ordering::SeqCst); + assert_eq!(device.facts(), Err(Error::Closing)); + assert!(matches!( + device.guc_firmware(), + Err(intel::firmware::Error::Device(Error::Closing)) + )); + assert!(matches!(device.program_pat(), Err(Error::Closing))); + assert_eq!(device.wake(), Err(Error::Closing)); + assert_eq!(device.sleep(), Err(Error::Closing)); + assert_eq!( + counts.context_checks.load(Ordering::SeqCst), + checks, + "closed operations must not enter C or owner callbacks" + ); + assert!(matches!( + device.retire(), + Err(Error::Mapping(bus::mmio::owned::Error::UnmapFailed)) + )); + assert_eq!(counts.finished.load(Ordering::SeqCst), 2); + assert_eq!(counts.drained.load(Ordering::SeqCst), 1); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + assert_eq!(device.facts(), Err(Error::Closing)); + assert!(matches!( + device.guc_firmware(), + Err(intel::firmware::Error::Device(Error::Closing)) + )); + assert!(matches!(device.program_pat(), Err(Error::Closing))); + assert_eq!(device.wake(), Err(Error::Closing)); + assert_eq!(device.sleep(), Err(Error::Closing)); + device.retire().unwrap(); + assert_eq!( + counts.finished.load(Ordering::SeqCst), + 2, + "unmap retry must not repeat the successful drain or access uncertain MMIO" + ); + assert_eq!(counts.drained.load(Ordering::SeqCst), 1); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 1); + let calls = platform.calls.lock().unwrap(); + assert_eq!(calls.len(), 3); + assert_eq!(calls[1].1, calls[2].1); + drop(calls); + + let before = authority.status().unwrap().quarantined; + let (input, counts) = owner(NEXT.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(&authority, input, true).unwrap(); + device.wake().unwrap(); + drop(device); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(authority.status().unwrap().quarantined, before + 1); +} + +// Test-executable-only allocator. Each armed failure runs in a fresh process; +// there is no production fault hook or alternative ownership implementation. +mod allocation_failure { + use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, + ptr, + }; + + #[derive(Clone, Copy)] + pub struct Observation { + remaining: Option, + pub attempts: usize, + pub failed: bool, + pub first: usize, + pub first_freed: bool, + } + const IDLE: Observation = Observation { + remaining: None, + attempts: 0, + failed: false, + first: 0, + first_freed: false, + }; + std::thread_local! { + static OBSERVATION: Cell = const { Cell::new(IDLE) }; + } + fn deny() -> bool { + OBSERVATION + .try_with(|state| { + let mut value = state.get(); + let Some(left) = value.remaining else { + return false; + }; + value.attempts += 1; + let denied = left == 0; + value.remaining = if denied { None } else { Some(left - 1) }; + value.failed = denied; + state.set(value); + denied + }) + .unwrap_or(false) + } + fn allocated(pointer: *mut u8) { + let _ = OBSERVATION.try_with(|state| { + let mut value = state.get(); + if value.remaining.is_some() && value.first == 0 { + value.first = pointer as usize; + state.set(value); + } + }); + } + pub struct Allocator; + // SAFETY: delegates all actual storage operations to System with the exact + // layout. The isolated test can deny an allocation by returning null; it + // never changes successful pointer provenance, layout or deallocation. + unsafe impl GlobalAlloc for Allocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if deny() { + return ptr::null_mut(); + } + // SAFETY: unchanged GlobalAlloc request to the real allocator. + let pointer = unsafe { System.alloc(layout) }; + allocated(pointer); + pointer + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + if deny() { + return ptr::null_mut(); + } + // SAFETY: unchanged GlobalAlloc request to the real allocator. + let pointer = unsafe { System.alloc_zeroed(layout) }; + allocated(pointer); + pointer + } + unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { + let _ = OBSERVATION.try_with(|state| { + let mut value = state.get(); + if value.first == pointer as usize { + value.first_freed = true; + state.set(value); + } + }); + // SAFETY: exact pointer/layout returned by System above. + unsafe { System.dealloc(pointer, layout) }; + } + } + pub fn arm(successes: usize) { + OBSERVATION.with(|state| { + state.set(Observation { + remaining: Some(successes), + ..IDLE + }); + }); + } + pub fn disarm() -> Observation { + OBSERVATION.with(|state| state.replace(IDLE)) + } +} +#[global_allocator] +static ALLOCATOR: allocation_failure::Allocator = allocation_failure::Allocator; + +#[test] +fn activation_allocation_failure_child() { + let Ok(value) = std::env::var("STELA_INTEL_ACTIVATION_ALLOC_FAIL_AT") else { + return; + }; + let index: usize = value.parse().unwrap(); + assert!(index < 2); + let platform = Arc::new(Platform::default()); + // SAFETY: a fresh process owns this test-only RAM mapping authority. + let authority = unsafe { + Authority::activate( + platform.clone(), + AddressSpace { + identity: 1, + physical_bits: 48, + virtual_bits: 48, + }, + vec![], + ) + } + .unwrap(); + let (input, counts) = owner(0x1000_0000, 0x9a49); + allocation_failure::arm(index); + let result = Device::open(&authority, input, true); + let observed = allocation_failure::disarm(); + assert!(matches!(result, Err(Error::OutOfMemory))); + assert!(observed.failed, "must deny a real allocator request"); + assert_eq!(observed.attempts, index + 1); + if index == 1 { + assert_ne!(observed.first, 0, "State allocation must really succeed"); + assert!( + observed.first_freed, + "context OOM must release State storage" + ); + } + assert_eq!(counts.prepared.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 1); + assert!(platform.calls.lock().unwrap().is_empty()); + assert_eq!(authority.status().unwrap().quarantined, 0); +} + +#[test] +fn activation_allocation_failures_are_recoverable() { + for index in 0..2 { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "activation_allocation_failure_child", + "--nocapture", + ]) + .env("STELA_INTEL_ACTIVATION_ALLOC_FAIL_AT", index.to_string()) + .output() + .unwrap(); + assert!( + output.status.success(), + "actual allocation failure {index} must return an error, not abort: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } +} + +fn huc_default_absence_never_looks_up_provider(authority: &Authority) { + struct Never; + impl firmware::Provider for Never { + fn load( + &self, + _: firmware::Requirement<'_>, + ) -> Result, firmware::Error> { + panic!("absent original role/catalog cannot perform provider lookup"); + } + } + use intel::firmware::{Error as FirmwareError, HucDisposition}; + for (index, pci, disposition) in [ + (0u64, 0xe202, HucDisposition::AbsentRole), + (1, 0x56a0, HucDisposition::AbsentCatalog), + (2, 0x46d0, HucDisposition::AbsentCatalog), + ] { + let (owner, counts) = owner(0x1b0000000 + index * BYTES as u64, pci); + let mut device = Device::open(authority, owner, true).unwrap(); + let request = device.huc_firmware().unwrap(); + assert_eq!(request.disposition(), disposition); + assert_eq!(request.name(), None); + assert_eq!(request.wanted(), None); + allocation_failure::arm(0); + let result = request.load(&Never); + let observed = allocation_failure::disarm(); + assert_eq!(observed.attempts, 0); + assert!(matches!(result, Err(FirmwareError::HucAbsent(value)) if value == disposition)); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + device.retire().unwrap(); + } +} + +fn gsm_owned_contract(authority: &Authority, platform: &Platform, next: &AtomicU64) { + for (pci, expected_bytes, expected_start) in + [(0x9a49, 4 << 20, 2 << 20), (0x56a0, 8 << 20, 4 << 20)] + { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), pci); + let mut device = Device::open(authority, input, true).unwrap(); + assert!(matches!(device.probe_gsm(authority), Err(Error::Awake))); + device.wake().unwrap(); + if pci == 0x56a0 { + counts.config_unavailable.store(1, Ordering::SeqCst); + } + let mut probe = device.probe_gsm(authority).unwrap(); + let geometry = probe.geometry(); + assert_eq!(geometry.gsm_offset, 8 << 20); + assert_eq!(geometry.gsm_bytes, expected_bytes); + assert_eq!(geometry.ggtt_start, expected_start); + assert_eq!( + counts.config_reads.load(Ordering::SeqCst), + usize::from(pci == 0x9a49) + ); + // Prefix reads are intentionally admitted by original xe_ggtt_get_pte, + // even below allocator start. Raw PTE bits are never called valid/ready. + assert_eq!(probe.read_pte(0), Ok(0xfedc_ba98_7654_3210)); + assert_eq!( + probe.read_pte(geometry.ggtt_start), + Ok(0x0123_4567_89ab_cdef) + ); + assert_eq!( + probe.read_pte(geometry.ggtt_start + geometry.ggtt_bytes - 4096), + Ok(u64::MAX) + ); + let reads = counts.reads64.load(Ordering::SeqCst); + assert_eq!(probe.read_pte(1), Err(Error::Native(-22))); + assert_eq!( + probe.read_pte(geometry.ggtt_start + geometry.ggtt_bytes), + Err(Error::Native(-22)) + ); + assert_eq!(probe.read_pte(u64::MAX), Err(Error::Native(-22))); + assert_eq!(counts.reads64.load(Ordering::SeqCst), reads); + counts.read64_unavailable.store(1, Ordering::SeqCst); + assert_eq!(probe.read_pte(0), Err(Error::Native(-95))); + assert_eq!(counts.reads64.load(Ordering::SeqCst), reads); + probe.retire().unwrap(); + assert_eq!(probe.read_pte(0), Err(Error::Closing)); + drop(probe); + device.sleep().unwrap(); + device.retire().unwrap(); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 1); + } + // Missing actual PCI access and original zero-GGMS refusal happen before + // mapping effects and do not fabricate geometry or permanently poison GT. + for (unavailable, gmch, error) in [(1, 2 << 6, -95), (0, 0, -12)] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + counts + .config_unavailable + .store(unavailable, Ordering::SeqCst); + counts.gmch.store(gmch, Ordering::SeqCst); + let before = platform.calls.lock().unwrap().len(); + assert!(matches!(device.probe_gsm(authority), Err(Error::Native(value)) if value == error)); + assert_eq!(platform.calls.lock().unwrap().len(), before); + device.sleep().unwrap(); + device.retire().unwrap(); + } + // Real uncertain second-map retirement retries the SAME token, without + // finish/sleep/new reads or release of the actual reset/forcewake owner. + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + let mut probe = device.probe_gsm(authority).unwrap(); + platform.fail_unmap.store(1, Ordering::SeqCst); + let before = platform.calls.lock().unwrap().len(); + assert_eq!( + probe.retire(), + Err(Error::Mapping(bus::mmio::owned::Error::UnmapFailed)) + ); + assert_eq!(probe.read_pte(0), Err(Error::Closing)); + probe.retire().unwrap(); + { + let calls = platform.calls.lock().unwrap(); + assert_eq!(calls[before].1, calls[before + 1].1); + } + drop(probe); + assert_eq!(device.facts(), Err(Error::Closing)); + assert_eq!(device.sleep(), Err(Error::Closing)); + assert_eq!(device.retire(), Err(Error::Awake)); + drop(device); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.sleep_writes.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + // No explicit retirement: both leases quarantine; actual epoch stays pinned. + let before = authority.status().unwrap().quarantined; + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + drop(device.probe_gsm(authority).unwrap()); + assert_eq!(device.sleep(), Err(Error::Closing)); + drop(device); + assert_eq!(authority.status().unwrap().quarantined, before + 2); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + // Ambiguous second-map failure likewise permanently blocks all device IO. + let before = authority.status().unwrap().quarantined; + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + platform.fail_map.store(1, Ordering::SeqCst); + assert!(matches!( + device.probe_gsm(authority), + Err(Error::Mapping(bus::mmio::owned::Error::MappingFailed)) + )); + assert_eq!(device.facts(), Err(Error::Closing)); + drop(device); + assert_eq!(authority.status().unwrap().quarantined, before + 2); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); +} + +#[test] +fn gsm_allocation_failure_child() { + if std::env::var_os("STELA_INTEL_GSM_ALLOC_FAIL").is_none() { + return; + } + let platform = Arc::new(Platform::default()); + // SAFETY: fresh process, isolated RAM-only canonical mapping model. + let authority = unsafe { + Authority::activate( + platform.clone(), + AddressSpace { + identity: 1, + physical_bits: 48, + virtual_bits: 48, + }, + vec![], + ) + } + .unwrap(); + let (input, counts) = owner(0x1000_0000, 0x9a49); + let mut device = Device::open(&authority, input, true).unwrap(); + device.wake().unwrap(); + let before = platform.calls.lock().unwrap().len(); + allocation_failure::arm(0); + let result = device.probe_gsm(&authority); + let observed = allocation_failure::disarm(); + assert!(matches!( + result, + Err(Error::Mapping(bus::mmio::owned::Error::Unavailable)) + )); + drop(result); + assert!(observed.failed); + assert_eq!(observed.attempts, 1); + assert_eq!( + platform.calls.lock().unwrap().len(), + before, + "fallible canonical metadata precedes map effects" + ); + // Canonical map Error does not attest rollback. Conservative poison retains + // the original acknowledged wake and device owner, with no cleanup effects. + assert_eq!(device.sleep(), Err(Error::Closing)); + drop(device); + assert_eq!(counts.sleep_writes.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); +} +#[test] +fn gsm_actual_metadata_allocation_failure_is_recoverable() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "gsm_allocation_failure_child", "--nocapture"]) + .env("STELA_INTEL_GSM_ALLOC_FAIL", "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "actual allocation NULL must not abort: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn pat_owned_contract(authority: &Authority, next: &AtomicU64) { + for (pci, llc, discrete) in [(0x9a49, 1, 0), (0x4905, 0, 1)] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), pci); + let mut device = Device::open(authority, input, true).unwrap(); + let facts = device.facts().unwrap(); + assert_eq!( + (facts.has_llc, facts.gt_type, facts.discrete), + (llc, 1, discrete) + ); + assert!(matches!(device.program_pat(), Err(Error::Awake))); + assert_eq!(counts.pat_writes.load(Ordering::SeqCst), 0); + device.wake().unwrap(); + { + allocation_failure::arm(0); + let result = device.program_pat(); + let observed = allocation_failure::disarm(); + let report = result.unwrap(); + assert_eq!( + observed.attempts, 0, + "no allocation during policy/program effects" + ); + assert!(!observed.failed); + assert_eq!(report.writes_issued(), 4); + assert_eq!(report.entries(), &[3, 1, 2, 0]); + assert_eq!( + (report.cache_none(), report.cache_wt(), report.cache_wb()), + (3, 2, 0) + ); + } + assert_eq!(counts.pat_writes.load(Ordering::SeqCst), 4); + for (index, value) in [3u64, 1, 2, 0].iter().enumerate() { + assert_eq!( + counts.pat_trace[index].load(Ordering::SeqCst), + ((0x4800 + index as u64 * 4) << 32) | value + ); + } + assert!(matches!(device.program_pat(), Err(Error::Native(-114)))); + assert_eq!(counts.pat_writes.load(Ordering::SeqCst), 4); + device.sleep().unwrap(); + device.retire().unwrap(); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 1); + } + // Same actual root device/GT ownership but genuinely unavailable MCR/ + // modern ATS/PTA method; no substituted direct writes or fake ACK. + for pci in [0x56a0, 0xe202] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), pci); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + assert!(matches!(device.program_pat(), Err(Error::Native(-95)))); + assert_eq!(counts.pat_writes.load(Ordering::SeqCst), 0); + device.sleep().unwrap(); + device.retire().unwrap(); + } +} + +fn guc_reset_owned_contract(authority: &Authority, next: &AtomicU64) { + for pci in [0x9a49, 0x4905, 0x46d0] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), pci); + let mut device = Device::open(authority, input, true).unwrap(); + assert!(matches!(device.reset_guc(), Err(Error::Awake))); + assert_eq!(counts.guc_reset_writes.load(Ordering::SeqCst), 0); + device.wake().unwrap(); + { + allocation_failure::arm(0); + let reset = device.reset_guc(); + let observed = allocation_failure::disarm(); + let reset = reset.unwrap(); + assert_eq!(observed.attempts, 0, "no allocation after reset effects"); + assert!(!observed.failed); + assert_eq!(reset.writes_issued(), 1); + assert_eq!(reset.gdrst_observed(), 0); + assert_eq!(reset.guc_status_observed() & 1, 1); + } + assert!(matches!(device.reset_guc(), Err(Error::Native(-114)))); + assert_eq!(counts.guc_reset_writes.load(Ordering::SeqCst), 1); + device.sleep().unwrap(); + device.retire().unwrap(); + assert!(matches!(device.reset_guc(), Err(Error::Closing))); + assert_eq!(counts.finished.load(Ordering::SeqCst), 1); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 1); + } + for mode in [1, 2] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + counts.guc_reset_mode.store(mode, Ordering::SeqCst); + let quarantined = authority.status().unwrap().quarantined; + allocation_failure::arm(0); + let result = device.reset_guc(); + let observed = allocation_failure::disarm(); + assert_eq!( + observed.attempts, 0, + "uncertain reset retention must not allocate" + ); + assert!(!observed.failed); + assert!( + matches!(result, Err(Error::Native(status)) if status == if mode == 1 { -110 } else { -5 }) + ); + assert_eq!(counts.guc_reset_writes.load(Ordering::SeqCst), 1); + assert!(matches!(device.facts(), Err(Error::Closing))); + assert!(matches!(device.wake(), Err(Error::Closing))); + assert!(matches!(device.sleep(), Err(Error::Closing))); + assert!(matches!(device.program_pat(), Err(Error::Closing))); + assert!(matches!(device.reset_guc(), Err(Error::Closing))); + assert!(matches!(device.probe_gsm(authority), Err(Error::Closing))); + assert!(device.guc_firmware().is_err()); + assert!(device.huc_firmware().is_err()); + assert!(matches!(device.retire(), Err(Error::Awake))); + assert_eq!(counts.sleep_writes.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + drop(device); + assert_eq!(authority.status().unwrap().quarantined, quarantined + 1); + assert_eq!(counts.guc_reset_writes.load(Ordering::SeqCst), 1); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + } + for pci in [0x56a0, 0xe202] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), pci); + let mut device = Device::open(authority, input, true).unwrap(); + device.wake().unwrap(); + assert!(matches!(device.reset_guc(), Err(Error::Native(-95)))); + assert_eq!(counts.guc_reset_writes.load(Ordering::SeqCst), 0); + assert_eq!(counts.guc_reset_reads.load(Ordering::SeqCst), 0); + device.sleep().unwrap(); + device.retire().unwrap(); + } +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.c new file mode 100644 index 0000000000..be457b9bc1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.c @@ -0,0 +1,66 @@ +/* SPDX-License-Identifier: MIT */ +/* Original source fragments compile in their own object, without LTO. Hosted + * mutex serialization is real; this supplies no Linux IRQ/power/timer runtime. */ +#include "activation_donor.h" +#include "../../xe/xe_scalar_types.h" +#include "../../xe/regs/xe_reg_defs.h" +#include "../../xe/xe_force_wake_domain_types.h" +#include +#include +#define for_each_if(condition) if (!(condition)) {} else +#define ffs(value) __builtin_ffs((int)(value)) +#include "../../xe/xe_force_wake_core.h" +struct donor_fw { + struct stela_intel_policy_result *gt; + unsigned initialized_domains, awake_domains, failures; + struct xe_force_wake_domain *domains; +}; +static void control(struct stela_intel_policy_result *r, struct xe_force_wake_domain *d, bool wake) +{ + assert(r->used < 256); r->words[r->used++] = d->id * 4u + (wake ? 1u : 0u); +} +static int wait(struct donor_fw *fw, struct xe_force_wake_domain *d, bool wake) +{ + assert(fw->gt->used < 256); fw->gt->words[fw->gt->used++] = d->id * 4u + (wake ? 3u : 2u); + return fw->failures & (1u << d->id) ? -110 : 0; +} +#define domain_wake(gt, domain) control(gt, domain, true) +#define domain_wake_wait(gt, domain) wait(fw, domain, true) +#define domain_sleep(gt, domain) control(gt, domain, false) +#define domain_sleep_wait(gt, domain) wait(fw, domain, false) +#define xe_gt_assert(gt, condition) assert(condition) +static unsigned donor_get(struct donor_fw *fw, unsigned domains, unsigned *failed) +{ + struct stela_intel_policy_result *gt = fw->gt; + struct xe_force_wake_domain *domain; + unsigned ref_incr = 0, awake_rqst = 0, awake_failed = 0, tmp, ref_rqst; +#include "donor-get.inc" + *failed = awake_failed; return ref_incr; +} +static unsigned donor_put(struct donor_fw *fw, unsigned fw_ref) +{ + struct stela_intel_policy_result *gt = fw->gt; + struct xe_force_wake_domain *domain; + unsigned tmp, sleep = 0; int ack_fail = 0; +#include "donor-put.inc" + return (unsigned)ack_fail; +} +void stela_intel_donor_policy(unsigned initialized, unsigned failures, unsigned nested, + struct stela_intel_policy_result *result) +{ + *result = (struct stela_intel_policy_result){0}; + struct xe_force_wake_domain domains[XE_FW_DOMAIN_ID_COUNT] = {0}; + for (unsigned i = 0; i < 3; ++i) { + domains[i].id = (enum xe_force_wake_domain_id)i; + domains[i].reg_ctl.addr = 4 * (i + 1); + domains[i].ref = initialized & (1u << i) ? nested : 0; + } + struct donor_fw fw = {result, initialized, nested ? initialized : 0, failures, domains}; + pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + assert(pthread_mutex_lock(&lock) == 0); + result->get = donor_get(&fw, XE_FORCEWAKE_ALL, &result->failed); + result->put_failed = donor_put(&fw, result->get); + result->awake = fw.awake_domains; + for (unsigned i = 0; i < 3; ++i) result->refs[i] = domains[i].ref; + assert(pthread_mutex_unlock(&lock) == 0 && pthread_mutex_destroy(&lock) == 0); +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.h b/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.h new file mode 100644 index 0000000000..3b8090c17f --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/activation_donor.h @@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_ACTIVATION_DONOR_H +#define STELA_INTEL_ACTIVATION_DONOR_H +struct stela_intel_policy_result { + unsigned get, failed, put_failed, awake, refs[3], words[256], used; +}; +void stela_intel_donor_policy(unsigned initialized, unsigned failures, unsigned nested, + struct stela_intel_policy_result *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/air_compile.c b/crates/stela-drivers/src/gpu/intel/stela/tests/air_compile.c new file mode 100644 index 0000000000..9355f21af4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/air_compile.c @@ -0,0 +1,760 @@ +/* SPDX-License-Identifier: MIT */ +/* Hosted compiler/RAW/table/plan fixtures. Device topologies and placements + * are synthetic models, not initialized hardware or native execution. */ +#include "../hosted/air_compile.h" +#include "compute.h" +#include "legacy_compute.h" +#include "surface.h" +#include "fp_controls.h" +#include "stela/air_test_fixture.h" +#include "intel/compiler/brw/brw_nir.h" +#include "intel/compiler/elk/elk_nir.h" +#include "intel/common/intel_compute_slm.h" +#include "util/ralloc.h" +#include "util/mesa-blake3.h" +#include +#include +#include +#include +#include +#include +#include +#ifdef NDEBUG +#error "Owned Intel tests require assertions" +#endif +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%s:%d: %s\n",__func__,__LINE__,#x); abort(); } } while(0) +static unsigned allocations, fail_allocation, live_allocations; +void *stela_intel_air_test_malloc(size_t); +void *stela_intel_air_test_calloc(size_t, size_t); +void stela_intel_air_test_free(void *); +void *stela_intel_air_test_malloc(size_t bytes) { + if (++allocations == fail_allocation) return NULL; + void *p = malloc(bytes); if (p) live_allocations++; return p; +} +void *stela_intel_air_test_calloc(size_t count, size_t bytes) { + if (++allocations == fail_allocation) return NULL; + void *p = calloc(count, bytes); if (p) live_allocations++; return p; +} +void stela_intel_air_test_free(void *p) { + if (p) { CHECK(live_allocations); live_allocations--; } free(p); +} +/* Inject only direct owner calls. Original backend/LLVM/GLSL allocators retain + * their normal implementation. Context counters follow actual parent disposal. */ +static void *contexts[8]; +static unsigned live_contexts; +void *stela_intel_air_test_ralloc_context(const void *); +void *stela_intel_air_test_ralloc_array_size(const void *,size_t,unsigned); +void stela_intel_air_test_ralloc_free(void *); +void *stela_intel_air_test_ralloc_context(const void *parent) +{ + if(++allocations==fail_allocation)return NULL; + void *p=ralloc_context(parent);if(!p)return NULL; + unsigned i;for(i=0;isize); + bytes->data = realloc(bytes->data, bytes->size + size); + CHECK(bytes->data); + memcpy(bytes->data + bytes->size, data, size); + bytes->size += size; +} +static void little(void *data, uint64_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; i++) ((uint8_t *)data)[i] = (uint8_t)(value >> (8 * i)); +} +static void tag(struct bytes *bytes, const char name[4], const void *data, size_t size) +{ + CHECK(size <= UINT16_MAX); + uint8_t length[2]; little(length, size, 2); + append(bytes, name, 4); append(bytes, length, 2); append(bytes, data, size); +} +static void digest(const void *bytes, size_t size, uint8_t output[32]) +{ + CHECK(size <= AIR_MAX_BITCODE_BYTES); + CC_SHA256(bytes, (CC_LONG)size, output); +} +/* Own one-entry framing fixture, never a second parser. The production Rust + * parser and shared inspector independently validate all original extents. */ +static struct bytes archive(const void *air, size_t size, const char *name, + unsigned air_minor, unsigned major, unsigned minor, + unsigned os_major, unsigned os_minor) +{ + struct bytes record = {0}; uint8_t prefix[4] = {0}, kind = 2, hash[32]; + append(&record, prefix, 4); tag(&record, "NAME", name, strlen(name) + 1); + tag(&record, "TYPE", &kind, 1); digest(air, size, hash); tag(&record, "HASH", hash, 32); + uint8_t length[8], offsets[24] = {0}, versions[8]; little(length, size, 8); + tag(&record, "MDSZ", length, 8); tag(&record, "OFFT", offsets, 24); + little(versions, 2, 2); little(versions + 2, air_minor, 2); + little(versions + 4, major, 2); little(versions + 6, minor, 2); + tag(&record, "VERS", versions, 8); append(&record, "ENDT", 4); little(record.data, record.size, 4); + uint8_t header[88] = {0}; memcpy(header, "MTLB", 4); + little(header + 4, 0x8001, 2); little(header + 6, 2, 2); little(header + 8, 9, 2); + header[11] = 0x81; little(header + 12, os_major, 2); little(header + 14, os_minor, 2); + size_t start = 92 + record.size; + little(header + 16, start + size, 8); little(header + 24, 88, 8); little(header + 32, record.size, 8); + little(header + 40, start, 8); little(header + 56, start, 8); + little(header + 72, start, 8); little(header + 80, size, 8); + struct bytes result = {0}; append(&result, header, sizeof(header)); + little(prefix, 1, 4); append(&result, prefix, 4); append(&result, record.data, record.size); + append(&result, air, size); free(record.data); return result; +} +static struct stela_metal_assembly *assemble(const struct bytes *bytes) +{ + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL; + enum stela_metal_assembly_status status = stela_metal_assemble_archive( + &options, bytes->data, bytes->size, &library, &error); + if (status) fprintf(stderr, "assembly refused: %u %s\n", status, error.detail); + CHECK(status == STELA_METAL_ASSEMBLY_OK && library); + return library; +} +static struct stela_metal_assembly *fixture(LLVMMemoryBufferRef air) +{ + struct bytes bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 8, 4, 0, 26, 7); + struct stela_metal_assembly *library = assemble(&bytes); free(bytes.data); return library; +} +static struct stela_metal_assembly *two_entries(LLVMMemoryBufferRef air) +{ + size_t size = LLVMGetBufferSize(air); + struct bytes a = archive(LLVMGetBufferStart(air), size, "kernel", 8, 4, 0, 26, 7); + struct bytes b = archive(LLVMGetBufferStart(air), size, "other", 8, 4, 0, 26, 7); + size_t a_record = a.size - 92 - size, b_record = b.size - 92 - size; + size_t start = 92 + a_record + b_record; + uint8_t header[88], count[4]; memcpy(header, a.data, sizeof(header)); + little(header + 16, start + size, 8); little(header + 32, a_record + b_record, 8); + little(header + 40, start, 8); little(header + 56, start, 8); little(header + 72, start, 8); + little(count, 2, 4); + struct bytes bytes = {0}; append(&bytes, header, sizeof(header)); append(&bytes, count, 4); + append(&bytes, a.data + 92, a_record); append(&bytes, b.data + 92, b_record); + append(&bytes, LLVMGetBufferStart(air), size); + struct stela_metal_assembly *library = assemble(&bytes); + free(a.data); free(b.data); free(bytes.data); return library; +} +static void text_append(char *text, size_t capacity, const char *format, ...) +{ + size_t length = strlen(text); CHECK(length < capacity); + va_list args; va_start(args, format); int bytes = vsnprintf(text + length, capacity - length, format, args); + va_end(args); CHECK(bytes >= 0 && (size_t)bytes < capacity - length); +} +static LLVMMemoryBufferRef multibuffer(unsigned count) +{ + CHECK(count <= 31); + char prefix[4096] = "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v28-apple-macosx26.7.0\"\ndefine void @kernel(i32 %tid"; + char body[8192] = "%index = zext i32 %tid to i64\n", metadata[16384] = "}\n" + "!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5"; + for (unsigned i = 0; i < count; i++) { + text_append(prefix, sizeof(prefix), ", ptr addrspace(1) %%b%u", i); + text_append(body, sizeof(body), "%%p%u = getelementptr i32, ptr addrspace(1) %%b%u, i64 %%index\n" + "%%v%u = load i32, ptr addrspace(1) %%p%u, align 4\n" + "%%x%u = add i32 %%v%u, %u\nstore i32 %%x%u, ptr addrspace(1) %%p%u, align 4\n", + i, i, i, i, i, i, i + 1, i, i); + text_append(metadata, sizeof(metadata), ",!%u", i + 6); + } + text_append(prefix, sizeof(prefix), ") {\n"); text_append(body, sizeof(body), "ret void\n"); + text_append(metadata, sizeof(metadata), "}\n!5 = !{i32 0, !\"air.thread_position_in_grid\"," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n"); + for (unsigned i = 0; i < count; i++) + text_append(metadata, sizeof(metadata), "!%u = !{i32 %u, !\"air.buffer\", !\"air.location_index\", i32 %u, i32 1," + " !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4," + " !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"buffer%u\"}\n", + i + 6, i + 1, (i * 7 + 3) % 31, i); + return stela_air_test_custom_bitcode(prefix, body, metadata, ""); +} + + +struct context { + struct intel_device_info device; + struct isl_device isl; + void *memory; + struct brw_compiler *brw; + struct elk_compiler *elk; +}; +static void *expected_log_data; +static unsigned callback_count; +static void logger(void *data,unsigned *id,const char *format,...) +{ + if(expected_log_data){CHECK(data==expected_log_data);callback_count++;} + (void)id;va_list args;va_start(args,format);vfprintf(stderr,format,args);va_end(args); +} +static void context(struct context *c,const char *target) +{ + memset(c,0,sizeof(*c));int pci=intel_device_name_to_pci_device_id(target); + CHECK(pci>=0&&intel_get_device_info_for_build(pci,&c->device)); + CHECK(c->device.kmd_type==INTEL_KMD_TYPE_INVALID); + c->memory=ralloc_context(NULL);CHECK(c->memory);isl_device_init(&c->isl,&c->device); + if(c->device.ver<=8) { c->elk=elk_compiler_create(c->memory,&c->device);CHECK(c->elk); + c->elk->shader_debug_log=c->elk->shader_perf_log=logger; + } else { c->brw=brw_compiler_create(c->memory,&c->device);CHECK(c->brw); + c->brw->shader_debug_log=c->brw->shader_perf_log=logger; + } +} +static struct stela_intel_air_options options(void) +{ + return (struct stela_intel_air_options){.size=sizeof(struct stela_intel_air_options),.abi=STELA_INTEL_AIR_ABI, + .workgroup_size={32,1,1},.max_instructions=4096,.max_code_bytes=1024*1024}; +} +static struct stela_intel_air_compilation *compile(struct context *c,struct stela_metal_assembly *library, + unsigned selected,const struct stela_intel_air_options *opts,enum stela_intel_air_status expected) +{ + struct stela_intel_air_compilation *owner=NULL;struct stela_intel_air_error error; +#ifdef STELA_INTEL_AIR_ALLOC_TEST + unsigned baseline=live_allocations; +#endif + enum stela_intel_air_status status=stela_intel_air_compile(c->brw,c->elk,NULL,library,selected,opts,&owner,&error); + if(status!=expected)fprintf(stderr,"status%u expected%u: %s AIR%u %s\n",status,expected,error.detail,error.air.kind,error.air.detail); + CHECK(status==expected&&error.status==status&&!!owner==(status==STELA_INTEL_AIR_OK)); +#ifdef STELA_INTEL_AIR_ALLOC_TEST + if(status)CHECK(live_allocations==baseline&&!live_contexts); +#endif + return owner; +} +static void destroy(struct stela_intel_air_compilation **owner) +{stela_intel_air_destroy(owner);CHECK(!*owner);stela_intel_air_destroy(owner);stela_intel_air_destroy(NULL);} +struct reference {const struct stela_intel_air_provenance *p;}; +static bool reference_threadgroup(const struct stela_air_buffer *buffer, + struct stela_air_threadgroup_view *view,void *data) +{ + const struct reference *ref=data; + for(unsigned i=0;ip->threadgroup.count;i++) { + const struct stela_metal_threadgroup_binding *row=&ref->p->threadgroup.bindings[i]; + if(row->buffer.argument==buffer->argument) { + CHECK(row->buffer.index==buffer->index&&buffer->address_space==3&& + row->buffer.type_size==buffer->type_size&&row->buffer.type_alignment==buffer->type_alignment); + *view=(struct stela_air_threadgroup_view){.size=row->bytes,.alignment=row->alignment, + .available_access=STELA_AIR_READ_WRITE};return true; + } + } + CHECK(false);return false; +} +static bool reference_bind(const struct stela_air_buffer *buffer,unsigned *slot,void *data) +{ + struct reference *ref=data;unsigned row=0; + for(unsigned i=0;ip->argument_count;i++) { + const struct stela_air_argument_info *a=&ref->p->arguments[i]; + if(a->kind!=1||a->buffer.address_space!=1)continue; + if(a->buffer.argument==buffer->argument) { + CHECK(a->buffer.index==buffer->index&&buffer->address_space==1);*slot=row;return true; + } + row++; + } + CHECK(false);return false; +} +static int plan(struct context *c,const struct stela_intel_air_compilation *owner,unsigned count) +{ + const struct stela_intel_air_binary *bin=stela_intel_air_binary(owner); + const struct shader_info *info=&stela_intel_air_nir(owner)->info; + const uint32_t groups[]={3,5,7}; + if(c->device.verx10>=125) { + struct stela_intel_compute_plan p; + struct stela_intel_compute_placement place={.code_offset=4096,.code_span=bin->code_bytes, + .binding_table_offset=8192,.binding_table_entries=count,.binding_table_span=count*4u}; + int status=stela_intel_compute_plan(c->brw,&c->isl,bin->brw,info,&place,groups,0,&p); + if(c->device.ver==35){CHECK(status==-95);return status;} + CHECK(status==0&&p.requirements.binding_table_entries==count&&p.dispatch.groups[1]==5); + CHECK(p.requirements.slm_bytes_per_group==intel_compute_slm_calculate_size((unsigned)c->device.ver,info->shared_size)&& + p.dispatch.slm_encoding==intel_compute_slm_encode_size((unsigned)c->device.ver,info->shared_size)); + uint32_t words[64];memset(words,0xa5,sizeof(words)); + struct stela_intel_commands commands={words,ARRAY_SIZE(words),1,48}; + CHECK(stela_intel_compute_dispatch(&commands,&p.dispatch)==0&&commands.used>1&&words[0]==UINT32_C(0xa5a5a5a5)&&words[commands.used]==UINT32_C(0xa5a5a5a5)); + return 0; + } + struct stela_intel_legacy_plan p; + struct stela_intel_legacy_placement place={.code_offset=4096,.code_span=bin->code_bytes, + .binding_table_offset=8192,.binding_table_entries=count,.binding_table_span=count*4u, + .curbe_offset=16384,.curbe_span=2048,.descriptor_offset=20480,.descriptor_span=32}; + int status=c->brw?stela_intel_legacy_brw_plan(c->brw,&c->isl,bin->brw,info,&place,groups,0,&p): + stela_intel_legacy_elk_plan(c->elk,&c->isl,bin->elk,info,&place,groups,&p); + CHECK(status==0&&p.binding_table_entries==count&&p.dispatch.groups[2]==7); + CHECK(p.slm_bytes_per_group==intel_compute_slm_calculate_size((unsigned)c->device.ver,info->shared_size)); + uint32_t words[64];memset(words,0xa5,sizeof(words)); + struct stela_intel_commands commands={words,ARRAY_SIZE(words),1,48}; + CHECK(stela_intel_gpgpu_dispatch(&commands,&p.dispatch)==0&&commands.used==1+p.walker_words&& + !memcmp(words+1,p.walker,p.walker_words*4)&&words[0]==UINT32_C(0xa5a5a5a5)&&words[commands.used]==UINT32_C(0xa5a5a5a5)); + return 0; +} +static void raw_states(struct context *c,const struct stela_intel_air_compilation *owner) +{ + unsigned count;const struct stela_intel_air_binding *map=stela_intel_air_bindings(owner,&count); + struct stela_intel_raw_limits limits;CHECK(!stela_intel_query_raw_limits(&c->isl,&limits)); + uint32_t states[AIR_MAX_ARGUMENTS][16],table[AIR_MAX_ARGUMENTS];CHECK(limits.state_bytes<=sizeof(states[0])); + for(unsigned i=0;iisl,&view,states[i],sizeof(states[i]))==(int)limits.state_bytes); + table[i]=0x10000+i*limits.gpu_state_alignment; + CHECK(table[i]%limits.gpu_state_alignment==0); + uint32_t before[16];memcpy(before,states[i],sizeof(before)); + view.available_access=0; + CHECK(stela_intel_raw_buffer_state(&c->isl,&view,states[i],sizeof(states[i]))==-22&&!memcmp(before,states[i],sizeof(before))); + view.available_access=STELA_INTEL_BUFFER_READ_WRITE;view.mapped_bytes=4092;view.buffer_bytes=4092; + CHECK(stela_intel_raw_buffer_state(&c->isl,&view,states[i],sizeof(states[i]))==-22&&!memcmp(before,states[i],sizeof(before))); + view.mapped_bytes=view.buffer_bytes=8192;view.offset=1; + CHECK(stela_intel_raw_buffer_state(&c->isl,&view,states[i],sizeof(states[i]))==-22&&!memcmp(before,states[i],sizeof(before))); + } + for(unsigned i=0;icode&&bin->code_bytes&&p&&map&&count==stela_intel_air_nir(owner)->info.num_ssbos); + struct stela_metal_input_view original={.size=sizeof(original),.abi=STELA_METAL_INPUT_ABI}; + CHECK(stela_metal_assembly_original(library,&original,NULL)==STELA_METAL_ASSEMBLY_OK); + struct reference ref={p};struct stela_air_options opts={ + .workgroup_size={p->options.workgroup_size[0],p->options.workgroup_size[1],p->options.workgroup_size[2]}, + .max_instructions=p->options.max_instructions,.fp_profile=p->options.fp_profile, + .bind_ssbo=count?reference_bind:NULL,.ssbo_count=count,.binding_data=&ref, + .bind_threadgroup=p->threadgroup.count?reference_threadgroup:NULL, + .max_threadgroup_bytes=intel_device_info_get_max_slm_size(&c->device)}; + struct stela_air_error error;void *memory=ralloc_context(NULL);CHECK(memory); + nir_shader *nir=stela_air_to_nir(original.bytes+p->air_offset,(size_t)p->air_bytes,p->name, + stela_intel_air_nir(owner)->options,&opts,&error);CHECK(nir); + if(c->brw){const struct brw_nir_compiler_opts o={0};brw_preprocess_nir(c->brw,nir,&o);} + else{const struct elk_nir_compiler_opts o={0};elk_preprocess_nir(c->elk,nir,&o);} + const nir_lower_compute_system_values_options sys={.has_base_workgroup_id=false}; + NIR_PASS(_,nir,nir_lower_compute_system_values,&sys);nir_shader_gather_info(nir,nir_shader_get_entrypoint(nir)); + if(p->options.subgroup_size)nir->info.min_subgroup_size=nir->info.max_subgroup_size=(uint8_t)p->options.subgroup_size; + const void *code;unsigned bytes; + if(c->brw) { + struct brw_cs_prog_data d={0};struct brw_cs_prog_key key={0};brw_nir_lower_cs_intrinsics(nir,&c->device,&d); + if(brw_nir_lower_cs_subgroup_id(nir,&c->device,0)){d.base.push_sizes[0]=4;brw_cs_fill_push_const_info(&c->device,&d,0);d.base.push_sizes[0]=REG_SIZE;} + else brw_cs_fill_push_const_info(&c->device,&d,-1); + struct brw_compile_cs_params args={.base={.mem_ctx=memory,.nir=nir,.key=&key.base,.prog_data=&d.base}}; + code=brw_compile(c->brw,&args.base);CHECK(code&&!args.base.error_str);bytes=d.base.program_size; + struct brw_cs_prog_data expected=*bin->brw; + CHECK(d.base.num_relocs==expected.base.num_relocs); + if(d.base.num_relocs)CHECK(!memcmp(d.base.relocs,expected.base.relocs,d.base.num_relocs*sizeof(*d.base.relocs))); + d.base.relocs=expected.base.relocs=NULL;CHECK(!memcmp(&d,&expected,sizeof(d))); + } else { + struct elk_cs_prog_data d={0};d.base.param=ralloc_array(memory,uint32_t,0);CHECK(d.base.param); + struct elk_cs_prog_key key={0};elk_nir_lower_cs_intrinsics(nir,&c->device,&d); + struct elk_compile_cs_params args={.base={.mem_ctx=memory,.nir=nir},.key=&key,.prog_data=&d}; + code=elk_compile_cs(c->elk,&args);CHECK(code&&!args.base.error_str);bytes=d.base.program_size; + struct elk_cs_prog_data expected=*bin->elk; + CHECK(d.base.nr_params==expected.base.nr_params&&d.base.num_relocs==expected.base.num_relocs); + if(d.base.nr_params)CHECK(!memcmp(d.base.param,expected.base.param,d.base.nr_params*sizeof(*d.base.param))); + if(d.base.num_relocs)CHECK(!memcmp(d.base.relocs,expected.base.relocs,d.base.num_relocs*sizeof(*d.base.relocs))); + d.base.param=expected.base.param=NULL;d.base.relocs=expected.base.relocs=NULL;CHECK(!memcmp(&d,&expected,sizeof(d))); + } + CHECK(bytes==bin->code_bytes&&!memcmp(code,bin->code,bytes));ralloc_free(nir);ralloc_free(memory); + raw_states(c,owner);int plan_status=plan(c,owner,count); + blake3_hash hash;char hex[BLAKE3_HEX_LEN];_mesa_blake3_compute(bin->code,bin->code_bytes,hash);_mesa_blake3_format(hex,hash); + printf("owned-air-intel input=%s pci=%04x ver=%u backend=%u buffers=%u code_bytes=%u executable_bytes=%u code_blake3=%s plan=%d subgroup=%u\n", + label,c->device.pci_device_id,c->device.verx10,bin->backend,count,bin->code_bytes,bin->executable_bytes,hex,plan_status,p->options.subgroup_size); +} +static void targets(struct stela_metal_assembly *library,enum stela_air_fp_profile fp,const char *label,unsigned subgroup) +{ + const char *names[]={"ivb","byt","hsw","bdw","chv","skl","bxt","kbl","glk","icl","ehl","tgl","rkl","dg1","adl","dg2","mtl","arl","lnl","bmg","ptl","nvl-u","nvl"}; + for(unsigned i=0;icode,retained->code_bytes,before); + ralloc_free(c.memory);c.memory=NULL; + _mesa_blake3_compute(retained->code,retained->code_bytes,after);CHECK(!memcmp(before,after,sizeof(before))); + if(retained->elk&&retained->elk->base.nr_params)CHECK(retained->elk->base.param[retained->elk->base.nr_params-1]==ELK_PARAM_BUILTIN_SUBGROUP_ID); + nir_validate_shader((nir_shader *)stela_intel_air_nir(owner),"after compiler destruction");destroy(&owner); + } + ralloc_free(c.memory); + } +} +static struct bytes read_file(const char *path) +{ + FILE *f=fopen(path,"rb");CHECK(f&&!fseek(f,0,SEEK_END));long size=ftell(f); + CHECK(size>0&&size<=AIR_MAX_BITCODE_BYTES&&!fseek(f,0,SEEK_SET)); + struct bytes b={.data=malloc((size_t)size),.size=(size_t)size};CHECK(b.data); + CHECK(fread(b.data,1,b.size,f)==b.size&&fgetc(f)==EOF&&!ferror(f)&&!fclose(f));return b; +} +struct facts{const char *name;unsigned air,major,minor,osmajor,osminor;bool found;}; +static bool inspect(const struct stela_air_inspection *i,const struct stela_air_entry *e,void *data) +{ + struct facts *f=data;if(strlen(f->name)!=e->name_bytes||memcmp(f->name,e->name,e->name_bytes))return true; + f->found=true;f->air=i->air_minor;f->major=i->language_major;f->minor=i->language_minor; + CHECK(sscanf(i->target,"air64_v%*u-apple-macosx%u.%u.",&f->osmajor,&f->osminor)==2);return true; +} +static void selected_tests(void) +{ + struct context c;context(&c,"bdw");struct stela_intel_air_options opts=options(); + const char *metadata="}\n!air.version = !{!0}\n!air.language_version = !{!1}\n" + "!air.kernel = !{!2,!7}\n!0 = !{i32 2, i32 8, i32 0}\n" + "!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!2 = !{ptr @kernel, !3, !4}\n" + "!3 = !{}\n!4 = !{!5,!6}\n!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 13, i32 1, !\"air.write\"," + " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"result\"}\n!7 = !{ptr @other, !3, !4}\n"; + LLVMMemoryBufferRef air=stela_air_test_custom_bitcode(stela_air_test_prefix, + "store i32 11, ptr addrspace(1) %out, align 4\nret void\n",metadata, + "define void @other(i32 %tid, ptr addrspace(1) %out) {\nstore i32 99, ptr addrspace(1) %out, align 4\nret void\n}\n"); + struct stela_metal_assembly *library=two_entries(air); LLVMDisposeMemoryBuffer(air); + struct stela_intel_air_compilation *owner=compile(&c,library,1,&opts,STELA_INTEL_AIR_OK); + const struct stela_intel_air_provenance *p=stela_intel_air_provenance(owner); + CHECK(p->selected_entry==1&&!strcmp(p->name,"other")&&p->input.entry_count==2&& + p->arguments[1].buffer.index==13&&p->arguments[1].buffer.access==STELA_AIR_WRITE); + unsigned stores=0; + nir_foreach_function_impl(impl,(nir_shader *)stela_intel_air_nir(owner))nir_foreach_block(block,impl) + nir_foreach_instr(instr,block) { + if(instr->type!=nir_instr_type_intrinsic)continue; + nir_intrinsic_instr *intr=nir_instr_as_intrinsic(instr); + if(intr->intrinsic==nir_intrinsic_store_ssbo){CHECK(nir_src_is_const(intr->src[0])&&nir_src_as_uint(intr->src[0])==99);stores++;} + } + CHECK(stores==1);validate(&c,library,owner,"selected-second-entry"); + air=multibuffer(3);struct stela_metal_assembly *second_library=fixture(air);LLVMDisposeMemoryBuffer(air); + opts.workgroup_size[0]=4;opts.workgroup_size[1]=2;opts.workgroup_size[2]=2; + struct stela_intel_air_compilation *second=compile(&c,second_library,0,&opts,STELA_INTEL_AIR_OK); + validate(&c,second_library,second,"coexisting-3d");destroy(&second);stela_metal_assembly_destroy(&second_library); + validate(&c,library,owner,"after-other-owner-destroy"); + stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + CHECK(!strcmp(p->name,"other")&&!strcmp(p->arguments[1].name,"result"));destroy(&owner); +} +#ifdef STELA_INTEL_AIR_CAPTURE_TEST +/* Failure-only malformed output records after a real original compile. No + * fabricated successful program or rewritten vendor algorithm is published. */ +static unsigned bad_capture; +const unsigned *stela_intel_air_test_brw_compile(const struct brw_compiler *,struct brw_compile_params *); +const unsigned *stela_intel_air_test_elk_compile(const struct elk_compiler *,struct elk_compile_cs_params *); +static struct intel_shader_reloc invalid_relocation; +#define CORRUPT(d,error,code) do { \ + switch(bad_capture) { \ + case 0:(code)=NULL;break; \ + case 1:(error)="failure-only original-output fixture";break; \ + case 2:(d)->base.program_size=0;break; \ + case 3:(d)->base.stage=MESA_SHADER_VERTEX;break; \ + case 4:(d)->prog_mask=0;break; \ + case 5:(d)->local_size[0]++;break; \ + case 6:(d)->prog_offset[0]=UINT32_MAX;(d)->prog_mask|=1;break; \ + case 7:(d)->base.const_data_size=16;(d)->base.const_data_offset=(d)->base.program_size;break; \ + case 8:(d)->base.num_relocs=1;(d)->base.relocs=NULL;break; \ + case 9:case 10:case 11: \ + invalid_relocation=(struct intel_shader_reloc){.type=bad_capture==9?(enum intel_shader_reloc_type)99:INTEL_SHADER_RELOC_TYPE_MOV_IMM, \ + .offset=bad_capture==11?1:(d)->base.program_size-8}; \ + (d)->base.num_relocs=1;(d)->base.relocs=&invalid_relocation;break; \ + default:CHECK(false); \ + } \ +} while(0) +const unsigned *stela_intel_air_test_brw_compile(const struct brw_compiler *compiler,struct brw_compile_params *p) +{ + const unsigned *code=brw_compile(compiler,p);CHECK(code&&!p->error_str); + struct brw_cs_prog_data *d=(struct brw_cs_prog_data *)p->prog_data;CORRUPT(d,p->error_str,code);return code; +} +const unsigned *stela_intel_air_test_elk_compile(const struct elk_compiler *compiler,struct elk_compile_cs_params *p) +{ + const unsigned *code=elk_compile_cs(compiler,p);CHECK(code&&!p->base.error_str); + CORRUPT(p->prog_data,p->base.error_str,code);return code; +} +static void invalid_capture_tests(void) +{ + for(unsigned backend=0;backend<2;backend++) { + struct context c;context(&c,backend?"bdw":"skl");struct stela_intel_air_options opts=options(); + LLVMMemoryBufferRef air=stela_air_test_bitcode(stela_air_test_store_body,"");struct stela_metal_assembly *library=fixture(air);LLVMDisposeMemoryBuffer(air); + for(bad_capture=0;bad_capture<12;bad_capture++)CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_BACKEND)); + stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + } + puts("24 malformed original compiler outputs refused atomically; no successful fake program"); +} +#endif +static void original_tests(void) +{ + selected_tests(); + LLVMMemoryBufferRef air=stela_air_test_bitcode(stela_air_test_store_body,"");struct stela_metal_assembly *library=fixture(air);LLVMDisposeMemoryBuffer(air); + targets(library,STELA_AIR_FP_IEEE_DEFAULT,"original-integer",0);stela_metal_assembly_destroy(&library); + for(unsigned count=0;count<=31;count++) { + air=multibuffer(count);library=fixture(air);LLVMDisposeMemoryBuffer(air); + targets(library,STELA_AIR_FP_IEEE_DEFAULT,"generic-buffer-indices",0);stela_metal_assembly_destroy(&library); + } + air=stela_air_test_bitcode("ret void\n","");library=fixture(air);LLVMDisposeMemoryBuffer(air); + targets(library,STELA_AIR_FP_IEEE_DEFAULT,"unused-buffer-no-effects",0);stela_metal_assembly_destroy(&library); + air=stela_air_test_bitcode(stela_air_test_store_body,"");library=fixture(air);LLVMDisposeMemoryBuffer(air); + struct context c;context(&c,"skl");struct stela_intel_air_options opts=options(); + struct stela_intel_air_compilation *owner=compile(&c,library,0,&opts,STELA_INTEL_AIR_OK); + const struct stela_intel_air_provenance *p=stela_intel_air_provenance(owner); + const struct stela_metal_library_manifest *m=stela_metal_assembly_manifest(library); + CHECK(!memcmp(&p->input,&m->input,sizeof(p->input))&&!memcmp(&p->entry,&m->entries[0].entry,sizeof(p->entry))&& + !memcmp(p->air_sha256,m->entries[0].air_sha256,32)&&p->arguments[1].name!=m->entries[0].arguments[1].name); + stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + CHECK(!strcmp(p->name,"kernel")&&!strcmp(p->arguments[1].type_name,"uint")); + nir_validate_shader((nir_shader *)stela_intel_air_nir(owner),"after all inputs destroyed");destroy(&owner); + for(unsigned backend=0;backend<2;backend++) { + context(&c,backend?"bdw":"skl");air=stela_air_test_bitcode(stela_air_test_store_body,"");library=fixture(air);LLVMDisposeMemoryBuffer(air); + opts=options();struct stela_intel_air_options bad=opts; + bad.max_code_bytes=4;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_LIMIT)); + bad=opts;bad.max_instructions=1;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_FRONTEND)); + bad=opts;bad.subgroup_size=3;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_UNSUPPORTED)); + bad=opts;bad.workgroup_size[0]=0;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_UNSUPPORTED)); + bad=opts;bad.workgroup_size[0]=1024;bad.workgroup_size[1]=2;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_UNSUPPORTED)); + bad=opts;bad.fp_profile=(enum stela_air_fp_profile)99;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_UNSUPPORTED)); + bad=opts;bad.abi++;CHECK(!compile(&c,library,0,&bad,STELA_INTEL_AIR_INVALID)); + CHECK(!compile(&c,library,1,&opts,STELA_INTEL_AIR_INVALID)); + if(c.brw){c.brw->shader_perf_log=NULL;CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_DEVICE));c.brw->shader_perf_log=logger;} + else{c.elk->shader_perf_log=NULL;CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_DEVICE));c.elk->shader_perf_log=logger;} + if(c.brw) { + const struct intel_device_info *saved=c.brw->isa.devinfo;c.brw->isa.devinfo=NULL; + CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_DEVICE));c.brw->isa.devinfo=saved; + } else { + const struct intel_device_info *saved=c.elk->isa.devinfo;c.elk->isa.devinfo=NULL; + CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_DEVICE));c.elk->isa.devinfo=saved; + } + nir_shader_compiler_options *actual_options=c.brw?&c.brw->nir_options[MESA_SHADER_COMPUTE]:c.elk->nir_options[MESA_SHADER_COMPUTE]; + CHECK(!actual_options->cb_data);unsigned before_callback_refusal=allocations; + actual_options->cb_data=&c; + CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_UNSUPPORTED)&&allocations==before_callback_refusal); + actual_options->cb_data=NULL; + for(unsigned width=8;width<=32;width*=2) { + opts.subgroup_size=width;owner=compile(&c,library,0,&opts,STELA_INTEL_AIR_OK); + validate(&c,library,owner,"explicit-subgroup");destroy(&owner); + } + opts=options();owner=compile(&c,library,0,&opts,STELA_INTEL_AIR_OK); + struct stela_intel_air_compilation *preserved=owner;struct stela_intel_air_error error; + CHECK(stela_intel_air_compile(c.brw,c.elk,NULL,library,0,&opts,&owner,&error)==STELA_INTEL_AIR_INVALID&&owner==preserved);destroy(&owner); + expected_log_data=&c;callback_count=0; + CHECK(stela_intel_air_compile(c.brw,c.elk,expected_log_data,library,0,&opts,&owner,&error)==STELA_INTEL_AIR_OK&&owner&&callback_count); + expected_log_data=NULL;destroy(&owner); +#ifdef STELA_INTEL_AIR_ALLOC_TEST + allocations=0;owner=compile(&c,library,0,&opts,STELA_INTEL_AIR_OK);unsigned total=allocations;CHECK(total==(backend?5u:4u));destroy(&owner);CHECK(!live_contexts); + for(unsigned fail=1;fail<=total;fail++){allocations=0;fail_allocation=fail;CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_ALLOCATION)&&!live_allocations&&!live_contexts);} + fail_allocation=0; +#endif + stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + } + context(&c,"skl");opts=options(); + air=stela_air_test_bitcode("call void @unsupported()\nret void\n","declare void @unsupported()\n"); + library=fixture(air);LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_FRONTEND));stela_metal_assembly_destroy(&library); + /* Complete dynamic AS3 reflection reaches this owner's explicit missing + * dispatch-specialization refusal, rather than the canonical inspector's + * separate refusal for incomplete module-global reflection. */ + air=stela_air_test_custom_bitcode( + "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v29-apple-macosx27.2.0\"\n" + "define void @kernel(i32 %tid, ptr addrspace(3) %scratch) {\n", + "store i32 %tid, ptr addrspace(3) %scratch, align 4\nret void\n", + "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 9, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 1, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5,!6}\n" + "!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 7, i32 1, !\"air.read_write\"," + " !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"scratch\"}\n",""); + struct bytes shared=archive(LLVMGetBufferStart(air),LLVMGetBufferSize(air),"kernel",9,4,1,27,2); + library=assemble(&shared);free(shared.data);LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&c,library,0,&opts,STELA_INTEL_AIR_UNSUPPORTED)); + stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + puts("owned Intel compiler/RAW/table/plan/lifetime fixtures passed; no hardware execution"); +} +static void source_input(int argc,char **argv) +{ + CHECK(argc==5); /* --source ORIGINAL_MSL ORIGINAL_ADAPTER_AIR INDEPENDENT_IDENTITY_208_BYTES */ + struct bytes source=read_file(argv[2]),air=read_file(argv[3]),identity=read_file(argv[4]);CHECK(identity.size==208); + struct stela_msl_output compiled={.air=air.data,.air_bytes=air.size}; + memcpy(compiled.source_sha256,identity.data,32);memcpy(compiled.air_sha256,identity.data+32,32); + memcpy(&compiled.build,identity.data+64,sizeof(compiled.build)); + struct stela_msl_apple_config config=stela_msl_apple_default_config(); + struct stela_msl_request request={.source=source.data,.source_bytes=source.size,.language_version=0x40001, + .fast_math=true,.target_triple="air64_v29-apple-macosx27.2.0"}; + struct stela_metal_assembly_options assembly_options=stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error;struct stela_metal_assembly *library=NULL; + CHECK(stela_metal_assemble_source(&assembly_options,&config,&request,&compiled,&library,&error)==STELA_METAL_ASSEMBLY_OK); + struct context c;context(&c,"skl"); + struct stela_intel_air_options opts=options();opts.fp_profile=STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41; + struct stela_intel_air_compilation *owner=compile(&c,library,0,&opts,STELA_INTEL_AIR_OK); + validate(&c,library,owner,"original-source-owner"); + free(air.data);free(source.data);stela_metal_assembly_destroy(&library);ralloc_free(c.memory); + const struct stela_intel_air_provenance *p=stela_intel_air_provenance(owner); + CHECK(p->library_flags==STELA_METAL_LIBRARY_SOURCE_COMPILED&&p->compiler_profile==config.profile&& + p->request_language==0x40001&&p->request_fast_math==1&& + !memcmp(p->source_sha256,identity.data,32)&&!memcmp(p->input.original_sha256,identity.data+32,32)&& + !memcmp(&p->build,identity.data+64,sizeof(p->build))); + free(identity.data);nir_validate_shader((nir_shader *)stela_intel_air_nir(owner),"source owner after input/compiler destruction");destroy(&owner); +} +static void requested_threadgroups(int argc,char **argv,struct stela_metal_threadgroup_request_row *rows) +{ + CHECK(argc>=6&&argc-5<=(int)AIR_MAX_ARGUMENTS); + for(int i=5;i='0'&&argv[i][0]<='9'); + unsigned long long index=strtoull(argv[i],&end,10);CHECK(!errno&&index<=UINT32_MAX&&*end==':'); + const char *start=end+1;CHECK(*start>='0'&&*start<='9');errno=0; + unsigned long long bytes=strtoull(start,&end,10);CHECK(!errno&&!*end); + rows[i-5]=(struct stela_metal_threadgroup_request_row){.index=(uint32_t)index,.bytes=(uint64_t)bytes}; + } +} +static void threadgroup_input(int argc,char **argv) +{ + struct stela_metal_threadgroup_request_row rows[AIR_MAX_ARGUMENTS]={0};requested_threadgroups(argc,argv,rows); + char *end;errno=0;unsigned long workgroup=strtoul(argv[4],&end,10);CHECK(!errno&&!*end&&workgroup&&workgroup<=1024); + struct stela_metal_threadgroup_request request={.size=sizeof(request),.abi=STELA_METAL_THREADGROUP_ABI, + .count=(uint32_t)(argc-5),.rows=rows}; + struct bytes air=read_file(argv[2]);struct facts f={.name=argv[3]};struct stela_air_error air_error; + CHECK(stela_air_inspect(air.data,air.size,256,inspect,&f,&air_error)&&f.found); + struct bytes bytes=archive(air.data,air.size,f.name,f.air,f.major,f.minor,f.osmajor,f.osminor); + struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data); + const char *names[]={"ivb","byt","hsw","bdw","chv","skl","bxt","kbl","glk","icl","ehl","tgl","rkl","dg1","adl","dg2","mtl","arl","lnl","bmg","ptl","nvl-u","nvl"}; + for(unsigned i=0;ithreadgroup.count==request.count&&stela_metal_threadgroup_matches(&p->threadgroup,&request)); + struct stela_metal_threadgroup_request_row saved[AIR_MAX_ARGUMENTS];memcpy(saved,rows,sizeof(rows)); + rows[0].bytes+=16;CHECK(!stela_metal_threadgroup_matches(&p->threadgroup,&request)); + memset(rows,0,sizeof(rows)); + CHECK(p->threadgroup.bindings[0].bytes&&p->threadgroup.bindings[0].alignment>=16); + memcpy(rows,saved,sizeof(rows));CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request)); + validate(&c,library,owner,"dispatch-threadgroup-specialization"); + printf("owned-threadgroup-intel pci=%04x count=%u total_shared=%u",c.device.pci_device_id,p->threadgroup.count, + stela_intel_air_nir(owner)->info.shared_size); + for(unsigned r=0;rthreadgroup.count;r++)printf(" row=%u:%u:%llu:%u",p->threadgroup.bindings[r].buffer.argument, + p->threadgroup.bindings[r].buffer.index,(unsigned long long)p->threadgroup.bindings[r].bytes,p->threadgroup.bindings[r].alignment); + puts(""); + ralloc_free(c.memory);nir_validate_shader((nir_shader *)stela_intel_air_nir(owner),"dynamic result after compiler destruction"); + CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request));destroy(&owner); + } + stela_metal_assembly_destroy(&library); +} +static void shared_refusal(int argc,char **argv) +{ + CHECK(argc==4); + struct bytes air=read_file(argv[2]);struct facts f={.name=argv[3]};struct stela_air_error inspect_error; + CHECK(stela_air_inspect(air.data,air.size,256,inspect,&f,&inspect_error)&&f.found); + struct bytes bytes=archive(air.data,air.size,f.name,f.air,f.major,f.minor,f.osmajor,f.osminor); + struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data); + const char *names[]={"ivb","byt","hsw","bdw","chv","skl","bxt","kbl","glk","icl","ehl","tgl","rkl","dg1","adl","dg2","mtl","arl","lnl","bmg","ptl","nvl-u","nvl"}; + for(unsigned i=0;i +#include +#include +#include "../firmware.c" +#include "firmware_donor.h" + +static void same_version(struct xe_uc_fw_version a, struct xe_uc_fw_version b) +{ + assert(a.major == b.major && a.minor == b.minor && a.patch == b.patch && + a.branch == b.branch && a.build == b.build); +} +static void same_fw(const struct xe_uc_fw *a, const struct xe_uc_fw *b) +{ + assert((a->path != NULL) == (b->path != NULL)); + if (a->path) assert(!strcmp(a->path, b->path)); + assert(a->type == b->type && a->full_ver_required == b->full_ver_required && + a->versions.wanted_type == b->versions.wanted_type); + same_version(a->versions.wanted, b->versions.wanted); + for (unsigned i = 0; i < XE_UC_FW_VER_TYPE_COUNT; ++i) same_version(a->versions.found[i], b->versions.found[i]); + assert(a->ucode_size == b->ucode_size && a->rsa_size == b->rsa_size && + a->private_data_size == b->private_data_size && a->build_type == b->build_type); + assert(!a->bo && !b->bo && a->status == XE_UC_FIRMWARE_UNINITIALIZED && + b->status == XE_UC_FIRMWARE_UNINITIALIZED); +} +static struct uc_css_header header(uint32_t release) +{ + return (struct uc_css_header){.header_size_dw = 32 + 64 + 64 + 1, + .size_dw = 32 + 64 + 64 + 1 + 4, + .rsa_info = {.key_size_dw = 64, .modulus_size_dw = 64, .exponent_size_dw = 1}, + .guc_info = {.sw_version = release, .submission_version = MAKE_GUC_VER(1, 26, 2), + .private_data_size = 4096, .ukernel_info = 1u << 2}}; +} +int main(void) +{ + static_assert(sizeof(struct uc_css_header) == 128); + static_assert(_Alignof(struct uc_css_header) == 1); + static_assert(sizeof(struct stela_intel_guc_selection) == 80); + static_assert(sizeof(struct stela_intel_guc_metadata) == 48); + unsigned selectors = 0, guc_entries = 0, parsers = 0, versions = 0; + for (unsigned platform = 0; platform <= XE_NOVALAKE_P; ++platform) + for (unsigned gt = XE_GT_TYPE_MAIN; gt <= XE_GT_TYPE_MEDIA; ++gt) + for (unsigned type = 0; type < XE_UC_FW_NUM_TYPES; ++type) { + struct xe_uc_fw a = {.type = (enum xe_uc_fw_type)type}, b = {0}; + xe_uc_fw_select_default((enum xe_platform)platform, (enum xe_gt_type)gt, &a); + stela_intel_fw_donor_select(platform, gt, type, &b); + same_fw(&a, &b); ++selectors; + if (type == XE_UC_FW_TYPE_GUC && gt == XE_GT_TYPE_MAIN && a.path) { + struct stela_intel_guc_selection output; + assert(stela_intel_guc_select(platform, &output) == 0); + assert(!strcmp((const char *)output.name, a.path) && + output.wanted[0] == a.versions.wanted.major && + output.wanted[1] == a.versions.wanted.minor && + output.wanted[2] == a.versions.wanted.patch); + ++guc_entries; + } + } + assert(guc_entries == 11); + /* Default selection/status classification uses actual frozen source for + * every original platform/type/GT. No test/source marks AVAILABLE. */ + unsigned defaults = 0, huc_defaults = 0; + const unsigned gfx[] = {1200, 1255, 1256, 3500}; + for (unsigned platform = 1; platform <= XE_NOVALAKE_P; ++platform) + for (unsigned gt = XE_GT_TYPE_MAIN; gt <= XE_GT_TYPE_MEDIA; ++gt) + for (unsigned type = 0; type < XE_UC_FW_NUM_TYPES; ++type) { + struct xe_uc_fw original = {0}; + stela_intel_fw_donor_select(platform, gt, type, &original); + bool selected = original.path != NULL; + int status = stela_intel_fw_donor_default_status(&original); + assert(status == (!selected && type == XE_UC_FW_TYPE_GUC ? -2 : 0)); + assert(original.status == (selected ? XE_UC_FIRMWARE_SELECTED : XE_UC_FIRMWARE_NOT_SUPPORTED)); + assert(!original.bo); ++defaults; + if (type != XE_UC_FW_TYPE_HUC) continue; + for (unsigned i = 0; i < ARRAY_SIZE(gfx); ++i) { + struct stela_intel_huc_default out; + assert(!stela_intel_huc_select_default(platform, gfx[i], gt == XE_GT_TYPE_MEDIA, &out)); + bool role = gt != XE_GT_TYPE_MEDIA && gfx[i] > 1255; + uint32_t disposition = role ? STELA_INTEL_HUC_ABSENT_ROLE : + selected ? STELA_INTEL_HUC_SELECTED : STELA_INTEL_HUC_ABSENT_CATALOG; + assert(out.disposition == disposition); + if (disposition == STELA_INTEL_HUC_SELECTED) { + assert(!strcmp((const char *)out.name, original.path)); + assert(out.wanted[0] == original.versions.wanted.major && + out.wanted[1] == original.versions.wanted.minor && + out.wanted[2] == original.versions.wanted.patch && + out.full_version == original.full_ver_required); + } else { + struct stela_intel_huc_default absent = {.disposition = disposition}; + assert(!memcmp(&out, &absent, sizeof(out))); + } + ++huc_defaults; + } + } + for (unsigned invalid = 0; invalid < 3; ++invalid) { + struct stela_intel_huc_default out, before; memset(&before, 0xa5, sizeof(before)); out = before; + assert(stela_intel_huc_select_default(invalid == 0 ? 0 : invalid == 1 ? UINT32_MAX : XE_DG2, + invalid == 2 ? 0 : 1255, false, &out) == -EINVAL && !memcmp(&out, &before, sizeof(out))); + } + assert(stela_intel_huc_select_default(XE_DG2, 1255, false, NULL) == -EINVAL); + /* Unaligned CPU view and genuinely absent optional modulus/exponent bytes. */ + uint8_t storage[401] = {0}, *bytes = storage + 1; + struct uc_css_header css = header(MAKE_GUC_VER(70, 44, 1)); + memcpy(bytes, &css, sizeof(css)); + for (size_t size = 0; size <= 400; ++size) { + struct xe_uc_fw a = {.type = XE_UC_FW_TYPE_GUC}, b = {0}; + xe_uc_fw_select_default(XE_TIGERLAKE, XE_GT_TYPE_MAIN, &a); + stela_intel_fw_donor_select(XE_TIGERLAKE, XE_GT_TYPE_MAIN, XE_UC_FW_TYPE_GUC, &b); + uint32_t ad = 0, bd = 0, nd = 0; + const struct xe_uc_fw_css_ops ops = {&ad, diagnostic, invariant}; + int ar = xe_uc_fw_css_parse(&a, bytes, size, &ops); + if (!ar) ar = xe_uc_fw_css_check_version(&a, &ops); + int br = stela_intel_fw_donor_parse(&b, bytes, size, &bd); + assert(ar == br && ad == bd); same_fw(&a, &b); + struct stela_intel_guc_metadata out, before; memset(&before, 0xa5, sizeof(before)); out = before; + assert(stela_intel_guc_parse(XE_TIGERLAKE, bytes, size, &out, &nd) == ar && nd == ad); + if (ar) assert(!memcmp(&out, &before, sizeof(out))); + else assert(out.ucode_bytes == 16 && out.rsa_bytes == 256 && out.upload_bytes == 144 && + out.submission[0] == 1 && out.submission[1] == 26 && out.submission[2] == 2 && + out.private_bytes == 4096 && out.build_type == 1); + ++parsers; + } + const uint32_t releases[] = {MAKE_GUC_VER(69, 255, 255), MAKE_GUC_VER(70, 29, 1), + MAKE_GUC_VER(70, 29, 2), MAKE_GUC_VER(70, 30, 0), MAKE_GUC_VER(70, 44, 0), + MAKE_GUC_VER(70, 44, 1), MAKE_GUC_VER(70, 53, 0), MAKE_GUC_VER(70, 54, 0), + MAKE_GUC_VER(70, 255, 255), MAKE_GUC_VER(71, 0, 0)}; + for (unsigned platform = XE_TIGERLAKE; platform <= XE_NOVALAKE_P; ++platform) + for (size_t i = 0; i < ARRAY_SIZE(releases); ++i) { + struct xe_uc_fw b = {0}; + stela_intel_fw_donor_select(platform, XE_GT_TYPE_MAIN, XE_UC_FW_TYPE_GUC, &b); + if (!b.path) continue; + css = header(releases[i]); memcpy(bytes, &css, sizeof(css)); + uint32_t expected = 0, actual = 0; + int status = stela_intel_fw_donor_parse(&b, bytes, 400, &expected); + struct stela_intel_guc_metadata out, before; memset(&before, 0xa5, sizeof(before)); out = before; + assert(stela_intel_guc_parse(platform, bytes, 400, &out, &actual) == status && actual == expected); + if (status) assert(!memcmp(&out, &before, sizeof(out))); + ++parsers; + } + for (unsigned full = 0; full < 2; ++full) + for (unsigned overridden = 0; overridden < 2; ++overridden) + for (unsigned wanted_major = 0; wanted_major < 2; ++wanted_major) + for (size_t i = 0; i < ARRAY_SIZE(releases); ++i) { + struct xe_uc_fw a = {.type = XE_UC_FW_TYPE_GUC, + .full_ver_required = full != 0, .user_overridden = overridden != 0, + .versions.wanted = {.major = wanted_major ? 70 : 0, .minor = 44, .patch = 1}}; + a.versions.found[0] = (struct xe_uc_fw_version){ + .major = (u16)(releases[i] >> 16), .minor = (u16)((releases[i] >> 8) & 255), + .patch = (u16)(releases[i] & 255)}; + struct xe_uc_fw b = a; uint32_t ad = 0, bd = 0; + const struct xe_uc_fw_css_ops ops = {&ad, diagnostic, invariant}; + int ar = xe_uc_fw_css_check_version(&a, &ops); + int br = stela_intel_fw_donor_version(&b, &bd); + assert(ar == br && ad == bd); same_fw(&a, &b); ++versions; + } + for (unsigned bad = 0; bad < 6; ++bad) { + css = header(MAKE_GUC_VER(70, 44, 1)); + if (bad == 0) css.header_size_dw = 0; + if (bad == 1) css.size_dw = css.header_size_dw - 1; + if (bad == 2) { css.rsa_info.key_size_dw = UINT32_C(0x40000000); css.header_size_dw = css.rsa_info.key_size_dw + 32 + 64 + 1; css.size_dw = css.header_size_dw; } + if (bad == 3) css.size_dw = css.header_size_dw + UINT32_C(0x40000000); + if (bad == 4) css.rsa_info.modulus_size_dw = UINT32_MAX; + if (bad == 5) css.size_dw = css.header_size_dw + (UINT32_MAX - 128) / 4 + 1; + memcpy(bytes, &css, sizeof(css)); + struct stela_intel_guc_metadata out, before; memset(&before, 0xa5, sizeof(before)); out = before; + uint32_t d = 0; + assert(stela_intel_guc_parse(XE_TIGERLAKE, bytes, 400, &out, &d) == -75 && + d == STELA_INTEL_GUC_UNREPRESENTABLE && !memcmp(&out, &before, sizeof(out))); + } + css = header(MAKE_GUC_VER(70, 44, 1)); + ++css.header_size_dw; ++css.size_dw; memcpy(bytes, &css, sizeof(css)); + struct stela_intel_guc_metadata malformed, before; + memset(&before, 0xa5, sizeof(before)); malformed = before; uint32_t diag = 0; + assert(stela_intel_guc_parse(XE_TIGERLAKE, bytes, 400, &malformed, &diag) == -EPROTO && + diag == STELA_INTEL_GUC_HEADER_SIZE && !memcmp(&malformed, &before, sizeof(malformed))); + struct stela_intel_guc_selection unavailable; + assert(stela_intel_guc_select(XE_PVC, &unavailable) == -ENOENT); + for (unsigned platform = XE_NOVALAKE_S; platform <= XE_NOVALAKE_P; ++platform) { + struct stela_intel_guc_selection out, before; memset(&before, 0xa5, sizeof(before)); out = before; + assert(stela_intel_guc_select(platform, &out) == -ENOENT && !memcmp(&out, &before, sizeof(out))); + } + printf("Intel GuC metadata: %u selector donor/core cases, %u original GuC entries, %u parser cases, %u version/override cases, 6 overflow refusals; %u frozen default-status and %u HuC role/catalog cases; no firmware authentication/upload\n", selectors, guc_entries, parsers, versions, defaults, huc_defaults); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/firmware.rs b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware.rs new file mode 100644 index 0000000000..07781b92bb --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware.rs @@ -0,0 +1,453 @@ +//! Exercise the public native modules and their actual linked C library. +pub use stela_drivers::gpu::intel::{activation, firmware, wopcm}; + +use crate::firmware::{Catalog, ErrorKind, Provenance, Provider, Requirement, Resource}; +use firmware::{Diagnostics, Error, Version}; +use sha2::{Digest, Sha256}; + +pub(super) fn bytes(release: Version) -> Vec { + // Original packed CSS128, uCode16 and RSA256; modulus/exponent lengths + // remain declared while those optional bytes are genuinely absent. + let mut bytes = vec![0; 400]; + for (word, value) in [ + (1, 32 + 64 + 64 + 1), + (6, 32 + 64 + 64 + 1 + 4), + (7, 64), + (8, 64), + (9, 1), + (16, release.major << 16 | release.minor << 8 | release.patch), + (17, 1 << 16 | 26 << 8 | 2), + (30, 4096), + (31, 1 << 2), + ] { + bytes[word * 4..word * 4 + 4].copy_from_slice(&value.to_le_bytes()); + } + bytes +} +pub(super) fn catalog_for(request: &firmware::Request<'_>, bytes: Vec) -> Catalog { + let digest = Sha256::digest(&bytes).into(); + Catalog::from_handoff(vec![Resource { + name: request.name(), + target: request.target(), + provenance: Provenance { + source: "synthetic-css-offline-fixture", + revision: "xe-source-3f08a3b54062842f268da77f913aab57c3c09fb4", + member: "synthetic/css-test.bin", + license: "MIT test data", + }, + expected_length: bytes.len(), + expected_sha256: digest, + bytes, + }]) + .unwrap() +} + +pub fn canonical_catalog_contract(device: &activation::Device) { + let request = device.guc_firmware().unwrap(); + assert_eq!(request.name(), "i915/tgl_guc_70.bin"); + assert_eq!(request.target().driver, "intel-xe-guc"); + assert_eq!(request.target().hardware, "pci-8086-9a49"); + assert_eq!( + request.target().revision, + "pci-00;gfx-1200.0;media-1200.0;gt-main;tile-0" + ); + assert_eq!(request.target().board, None); + assert_eq!( + request.wanted(), + Version { + major: 70, + minor: 44, + patch: 1 + } + ); + assert!(!request.full_version_required()); + let input = bytes(request.wanted()); + let pointer = input.as_ptr(); + let digest: [u8; 32] = Sha256::digest(&input).into(); + let catalog = catalog_for(&request, input); + let image = request.load(&catalog).unwrap(); + assert_eq!( + image.image().bytes().as_ptr(), + pointer, + "provider image must stay borrowed, not copied" + ); + assert_eq!(image.image().sha256(), digest); + assert_eq!( + image.image().provenance().source, + "synthetic-css-offline-fixture" + ); + assert_eq!(image.image().provenance().member, "synthetic/css-test.bin"); + assert_eq!(image.identity().device, 0x9a49); + assert_eq!(image.facts(), device.facts().unwrap()); + assert_eq!(image.wanted(), request.wanted()); + let metadata = image.metadata(); + assert_eq!(metadata.release, request.wanted()); + assert_eq!( + metadata.submission, + Version { + major: 1, + minor: 26, + patch: 2 + } + ); + assert_eq!( + ( + metadata.ucode_bytes, + metadata.rsa_bytes, + metadata.upload_bytes + ), + (16, 256, 144) + ); + assert_eq!( + ( + metadata.private_bytes, + metadata.build_type, + metadata.diagnostics.bits() + ), + (4096, 1, 0) + ); + let empty = Catalog::from_handoff(vec![]).unwrap(); + assert!(matches!( + request.load(&empty), + Err(Error::Provider(crate::firmware::Error { + kind: ErrorKind::Missing, + .. + })) + )); + let short = catalog_for(&request, vec![0; 127]); + assert!(matches!( + request.load(&short), + Err(Error::Provider(crate::firmware::Error { + kind: ErrorKind::Truncated { + expected: 128, + actual: 127 + }, + .. + })) + )); + // A safe Provider can ignore a requested lower bound while returning a + // genuine Image. The native parser must still enforce its readable span. + struct BelowMinimum<'a>(&'a Catalog); + impl Provider for BelowMinimum<'_> { + fn load( + &self, + requirement: Requirement<'_>, + ) -> Result, crate::firmware::Error> { + self.0.load(Requirement { + minimum_bytes: 1, + ..requirement + }) + } + } + assert!(matches!(request.load(&BelowMinimum(&short)), + Err(Error::Parse { status: -61, diagnostics }) if diagnostics.bits() == Diagnostics::SHORT_HEADER)); + for (header_dw, size_dw, expected) in [ + (162u32, 166u32, Diagnostics::HEADER_SIZE), + (161, 166, Diagnostics::SHORT_IMAGE), + ] { + let mut malformed = bytes(request.wanted()); + malformed[4..8].copy_from_slice(&header_dw.to_le_bytes()); + malformed[24..28].copy_from_slice(&size_dw.to_le_bytes()); + let malformed = catalog_for(&request, malformed); + assert!( + matches!(request.load(&malformed), Err(Error::Parse { diagnostics, .. }) if diagnostics.bits() == expected) + ); + } + let wrong = Catalog::from_handoff(vec![Resource { + name: request.name(), + target: crate::firmware::Target { + revision: "wrong-silicon", + ..request.target() + }, + provenance: image.image().provenance(), + expected_length: 400, + expected_sha256: digest, + bytes: bytes(request.wanted()), + }]) + .unwrap(); + assert!(matches!( + request.load(&wrong), + Err(Error::Provider(crate::firmware::Error { + kind: ErrorKind::WrongTarget, + .. + })) + )); + assert!(matches!( + Catalog::from_handoff(vec![Resource { + name: request.name(), + target: request.target(), + provenance: image.image().provenance(), + expected_length: 400, + expected_sha256: [0; 32], + bytes: bytes(request.wanted()), + }]), + Err(crate::firmware::Error { + kind: ErrorKind::DigestMismatch { .. }, + .. + }) + )); + for (release, expected) in [ + ( + Version { + major: 69, + minor: 255, + patch: 255, + }, + Diagnostics::GUC_TOO_OLD, + ), + ( + Version { + major: 70, + minor: 29, + patch: 1, + }, + Diagnostics::GUC_TOO_OLD, + ), + ( + Version { + major: 71, + minor: 0, + patch: 0, + }, + Diagnostics::VERSION_MISMATCH, + ), + ] { + let candidate = catalog_for(&request, bytes(release)); + assert!( + matches!(request.load(&candidate), Err(Error::Parse { diagnostics, .. }) if diagnostics.bits() == expected) + ); + } + let older = catalog_for( + &request, + bytes(Version { + major: 70, + minor: 30, + patch: 0, + }), + ); + assert_eq!( + request.load(&older).unwrap().metadata().diagnostics.bits(), + Diagnostics::RECOMMENDED_NEWER + ); + let mut overflow = bytes(request.wanted()); + overflow[24..28].copy_from_slice(&0u32.to_le_bytes()); + let overflow = catalog_for(&request, overflow); + assert!( + matches!(request.load(&overflow), Err(Error::Parse { status: -75, diagnostics }) if diagnostics.bits() == Diagnostics::UNREPRESENTABLE) + ); + struct Misdirected<'a>(&'a Catalog); + impl Provider for Misdirected<'_> { + fn load( + &self, + requirement: Requirement<'_>, + ) -> Result, crate::firmware::Error> { + self.0.load(Requirement { + target: crate::firmware::Target { + revision: "wrong-silicon", + ..requirement.target + }, + ..requirement + }) + } + } + assert!(matches!( + request.load(&Misdirected(&wrong)), + Err(Error::WrongImage) + )); +} + +fn huc_catalog(request: &firmware::HucRequest<'_>, input: Vec) -> Catalog { + let requirement = request.requirement().unwrap(); + Catalog::from_handoff(vec![Resource { + name: requirement.name, + target: requirement.target, + provenance: Provenance { + source: "synthetic-huc-offline-fixture", + revision: "xe-source-3f08a3b54062842f268da77f913aab57c3c09fb4", + member: "synthetic/huc-test.bin", + license: "MIT test data", + }, + expected_length: input.len(), + expected_sha256: Sha256::digest(&input).into(), + bytes: input, + }]) + .unwrap() +} + +pub fn huc_catalog_contract(device: &activation::Device) { + use firmware::HucDisposition; + let request = device.huc_firmware().unwrap(); + assert_eq!(request.disposition(), HucDisposition::Selected); + assert_eq!(request.name(), Some("i915/tgl_huc.bin")); + assert_eq!(request.target().driver, "intel-xe-huc"); + assert_eq!(request.target().hardware, "pci-8086-9a49"); + assert_eq!( + request.target().revision, + device.guc_firmware().unwrap().target().revision + ); + assert_eq!(request.wanted(), Some(Version::default())); + assert!(!request.full_version_required()); + let release = Version { + major: 1, + minor: 2, + patch: 3, + }; + let input = bytes(release); + let pointer = input.as_ptr(); + let digest: [u8; 32] = Sha256::digest(&input).into(); + let catalog = huc_catalog(&request, input); + crate::allocation_failure::arm(0); + let loaded = request.load(&catalog); + let observed = crate::allocation_failure::disarm(); + let loaded = loaded.unwrap(); + assert_eq!( + observed.attempts, 0, + "actual positive load/parser must allocate nothing" + ); + assert_eq!(loaded.image().bytes().as_ptr(), pointer); + assert_eq!(loaded.image().sha256(), digest); + assert_eq!( + loaded.image().provenance().source, + "synthetic-huc-offline-fixture" + ); + assert_eq!(loaded.identity().device, 0x9a49); + assert_eq!(loaded.facts(), device.facts().unwrap()); + assert_eq!(loaded.wanted(), Version::default()); + let metadata = loaded.metadata(); + assert_eq!( + metadata.release, release, + "GuC-only minimum version must never leak into HuC" + ); + assert_eq!( + ( + metadata.ucode_bytes, + metadata.rsa_bytes, + metadata.upload_bytes, + metadata.css_offset + ), + (16, 256, 144, 0) + ); + assert!(!metadata.has_gsc_headers()); + assert_eq!(metadata.diagnostics.bits(), 0); + + let empty = Catalog::from_handoff(vec![]).unwrap(); + crate::allocation_failure::arm(0); + let missing = request.load(&empty); + let observed = crate::allocation_failure::disarm(); + assert_eq!(observed.attempts, 1); + assert!(observed.failed); + match missing { + Err(Error::Provider(crate::firmware::Error { + kind: ErrorKind::Missing, + name: + crate::firmware::ErrorName::AllocationFailed { + original_bytes, + sha256, + }, + })) => { + assert_eq!(original_bytes, request.name().unwrap().len()); + assert_eq!( + sha256, + <[u8; 32]>::from(Sha256::digest(request.name().unwrap().as_bytes())) + ); + } + _ => panic!("selected HuC failure must retain its actual diagnostic identity under OOM"), + } + let short = huc_catalog(&request, vec![0; 127]); + crate::allocation_failure::arm(0); + let truncated = request.load(&short); + let observed = crate::allocation_failure::disarm(); + assert_eq!(observed.attempts, 1); + assert!(observed.failed); + assert!(matches!( + truncated, + Err(Error::Provider(crate::firmware::Error { + kind: ErrorKind::Truncated { + expected: 128, + actual: 127 + }, + name: crate::firmware::ErrorName::AllocationFailed { .. }, + })) + )); + struct BelowMinimum<'a>(&'a Catalog); + impl Provider for BelowMinimum<'_> { + fn load( + &self, + requirement: Requirement<'_>, + ) -> Result, crate::firmware::Error> { + self.0.load(Requirement { + minimum_bytes: 1, + ..requirement + }) + } + } + assert!(matches!(request.load(&BelowMinimum(&short)), + Err(Error::Parse { status: -61, diagnostics }) if diagnostics.bits() == Diagnostics::SHORT_HEADER)); + let mut cpd = vec![0; 784]; + cpd[0..4].copy_from_slice(&0x44504324u32.to_le_bytes()); + cpd[4..8].copy_from_slice(&2u32.to_le_bytes()); + cpd[10] = 20; + cpd[20..29].copy_from_slice(b"HUCP.man\0"); + cpd[32..36].copy_from_slice(&160u32.to_le_bytes()); + cpd[44..51].copy_from_slice(b"huc_fw\0"); + cpd[56..60].copy_from_slice(&384u32.to_le_bytes()); + cpd[384..].copy_from_slice(&bytes(release)); + let cpd = huc_catalog(&request, cpd); + let loaded = request.load(&cpd).unwrap(); + assert!(loaded.metadata().has_gsc_headers()); + assert_eq!(loaded.metadata().css_offset, 384); + assert_eq!(loaded.metadata().upload_bytes, 144); + assert_eq!(loaded.metadata().release, release); + for (change, expected_status, expected_diagnostic) in [ + (0, -22, Diagnostics::CPD_HEADER_LENGTH), + (1, -61, Diagnostics::CPD_SHORT_IMAGE), + (2, -61, Diagnostics::CPD_MISSING_MANIFEST), + ] { + let mut bad = cpd + .load(request.requirement().unwrap()) + .unwrap() + .bytes() + .to_vec(); + match change { + 0 => bad[10] = 19, + 1 => bad[4..8].copy_from_slice(&1000u32.to_le_bytes()), + _ => bad[20] = b'x', + } + let bad = huc_catalog(&request, bad); + crate::allocation_failure::arm(0); + let refused = request.load(&bad); + let observed = crate::allocation_failure::disarm(); + assert_eq!(observed.attempts, 0); + assert!(matches!(refused, Err(Error::Parse { status, diagnostics }) + if status == expected_status && diagnostics.bits() == expected_diagnostic)); + } + + // Safe Provider can return another genuine image; exact filename/target + // are rechecked at the native consumer, even after catalog validation. + let requirement = request.requirement().unwrap(); + let wrong = Catalog::from_handoff(vec![Resource { + name: "i915/wrong_huc.bin", + target: requirement.target, + provenance: loaded.image().provenance(), + expected_length: 400, + expected_sha256: digest, + bytes: bytes(release), + }]) + .unwrap(); + struct Misdirected<'a>(&'a Catalog); + impl Provider for Misdirected<'_> { + fn load( + &self, + requirement: Requirement<'_>, + ) -> Result, crate::firmware::Error> { + self.0.load(Requirement { + name: "i915/wrong_huc.bin", + ..requirement + }) + } + } + assert!(matches!( + request.load(&Misdirected(&wrong)), + Err(Error::WrongImage) + )); +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.c new file mode 100644 index 0000000000..98711c556b --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.c @@ -0,0 +1,101 @@ +/* SPDX-License-Identifier: MIT */ +/* Separately compiled frozen source policies; no Linux device/GT/BO objects or + * services are fabricated. Only scalar spellings and diagnostics are bound. */ +#include "../../xe/xe_scalar_types.h" +#include "../../xe/xe_platform_types.h" +#include "../../xe/xe_gt_type.h" +#include "../../xe/xe_uc_fw_types.h" +#include "../../xe/abi/uc_fw_abi.h" +#include "../../xe/xe_uc_fw_version.h" +#include "../firmware.h" +#include "firmware_donor.h" +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define __stringify_1(x) #x +#define __stringify(x) __stringify_1(x) +#define FIELD_GET(mask, value) REG_FIELD_GET(mask, value) +#define unlikely(value) __builtin_expect(!!(value), 0) +#define EINVAL 22 +#define ENOENT 2 +#define ENOEXEC 8 +#define ENODATA 61 +#define EPROTO 71 +#define xe_gt_assert(gt, condition) assert(condition) +#define xe_uc_fw_is_overridden(fw) ((fw)->user_overridden) +static _Thread_local uint32_t *active_diagnostics; +static void donor_warn(const char *format, size_t actual, size_t needed) +{ + if (strstr(format, "unexpected header size")) *active_diagnostics |= STELA_INTEL_GUC_HEADER_SIZE; + else { + assert(strstr(format, "invalid size")); + *active_diagnostics |= actual < 128 && needed == 128 ? STELA_INTEL_GUC_SHORT_HEADER : STELA_INTEL_GUC_SHORT_IMAGE; + } +} +static void donor_notice(const char *format) +{ + if (strstr(format, "unexpected version")) *active_diagnostics |= STELA_INTEL_GUC_VERSION_MISMATCH; + else { assert(strstr(format, "recommended")); *active_diagnostics |= STELA_INTEL_GUC_RECOMMENDED_NEWER; } +} +static void donor_info(const char *format) +{ + assert(strstr(format, "linux-firmware")); + *active_diagnostics |= STELA_INTEL_GUC_RECOMMENDED_NEWER; +} +#define drm_warn(device, format, type, path, actual, needed) donor_warn(format, actual, needed) +#define drm_notice(device, format, ...) donor_notice(format) +#define drm_info(device, format, ...) donor_info(format) +#define xe_gt_err(gt, format, ...) ((void)(format), *active_diagnostics |= STELA_INTEL_GUC_TOO_OLD) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wmissing-field-initializers" +#pragma clang diagnostic ignored "-Wshorten-64-to-32" +#include "donor-fw-defs.inc" +void stela_intel_fw_donor_select(unsigned platform, unsigned gt, unsigned type, struct xe_uc_fw *uc_fw) +{ + enum xe_platform p = (enum xe_platform)platform; + enum xe_gt_type gt_type = (enum xe_gt_type)gt; + uc_fw->type = (enum xe_uc_fw_type)type; +#include "donor-fw-select.inc" +} +#define guc_read_css_info donor_guc_read_css_info +#define xe_uc_fw_check_version_requirements donor_check_version +#define parse_css_header donor_parse_css_header +#include "donor-fw-css.inc" +#pragma clang diagnostic pop +int stela_intel_fw_donor_parse(struct xe_uc_fw *fw, const void *bytes, size_t size, uint32_t *diagnostics) +{ + *diagnostics = 0; active_diagnostics = diagnostics; + int result = donor_parse_css_header(fw, bytes, size); + if (!result) result = donor_check_version(fw); + active_diagnostics = NULL; + return result; +} +int stela_intel_fw_donor_css(struct xe_uc_fw *fw, const void *bytes, size_t size, uint32_t *diagnostics) +{ + *diagnostics = 0; active_diagnostics = diagnostics; + int result = donor_parse_css_header(fw, bytes, size); + active_diagnostics = NULL; + return result; +} + +int stela_intel_fw_donor_version(struct xe_uc_fw *fw, uint32_t *diagnostics) +{ + *diagnostics = 0; active_diagnostics = diagnostics; + int result = donor_check_version(fw); + active_diagnostics = NULL; + return result; +} + +/* Original default-path status policy, test object only. This does not make + * a native BO/firmware AVAILABLE and is not the Linux request/load lifecycle. */ +#define XE_WARN_ON(condition) assert(!(condition)) +#include "donor-fw-supported.inc" +#define xe_uc_fw_change_status(uc_fw, value) ((uc_fw)->__status = (value)) +#undef xe_gt_err +#define xe_gt_err(gt, format, ...) ((void)(format)) +int stela_intel_fw_donor_default_status(struct xe_uc_fw *uc_fw) +{ +#include "donor-fw-default-status.inc" + return 0; /* Stage boundary: selected path, not firmware request success. */ +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.h b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.h new file mode 100644 index 0000000000..c9e8a24594 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/firmware_donor.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_FIRMWARE_DONOR_H +#define STELA_INTEL_FIRMWARE_DONOR_H +struct xe_uc_fw; +void stela_intel_fw_donor_select(unsigned platform, unsigned gt_type, unsigned type, + struct xe_uc_fw *); +int stela_intel_fw_donor_parse(struct xe_uc_fw *, const void *, size_t, uint32_t *); +int stela_intel_fw_donor_version(struct xe_uc_fw *, uint32_t *); +int stela_intel_fw_donor_default_status(struct xe_uc_fw *); +int stela_intel_fw_donor_css(struct xe_uc_fw *, const void *, size_t, uint32_t *); +int stela_intel_fw_donor_cpd(struct xe_uc_fw *, unsigned platform, const void *, size_t, + const char *manifest, const char *css, uint32_t *security, + uint32_t *diagnostics); +int stela_intel_fw_donor_huc(struct xe_uc_fw *, unsigned platform, const void *, size_t, + uint32_t *diagnostics); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe.c b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe.c new file mode 100644 index 0000000000..9ed88ff014 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe.c @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT */ +#include "ggtt_probe_donor.h" +#include "../../xe/xe_scalar_types.h" +#include "../../xe/xe_platform_types.h" +#include "ggtt_probe_defs.h" +#include "../../xe/regs/xe_gtt_defs.h" +#include "../../xe/xe_wopcm_size.h" +#include +#include +#include +int main(void) +{ + const struct stela_intel_gsm_geometry sentinel = {1, 2, 3, 4}; + struct stela_intel_gsm_geometry out = sentinel; + uint16_t config = UINT16_MAX; + assert(stela_intel_gsm_config(1200, &config) == 0 && config == 0x50); + config = UINT16_MAX; + assert(stela_intel_gsm_config(1250, &config) == 1 && config == UINT16_MAX); + assert(stela_intel_gsm_config(0, &config) == -22 && config == UINT16_MAX); + assert(stela_intel_gsm_config(1200, NULL) == -22); + unsigned comparisons = 0; + for (unsigned word = 0; word <= UINT16_MAX; ++word) { + unsigned gsm = stela_gsm_donor_decode((u16)word); + for (unsigned p = XE_TIGERLAKE; p <= XE_NOVALAKE_P; ++p) { + for (unsigned d = 0; d <= 1; ++d) { + out = sentinel; + int status = stela_intel_gsm_geometry(p, 1200, d != 0, 16 << 20, true, (u16)word, &out); + if (!gsm) { assert(status == -12 && !memcmp(&out, &sentinel, sizeof(out))); continue; } + assert(!status && out.gsm_offset == 8 << 20 && out.gsm_bytes == gsm); + u64 start, size; + stela_gsm_donor_range(gsm, xe_wopcm_default_size((enum xe_platform)p, d != 0), &start, &size); + assert(out.ggtt_start == start && out.ggtt_bytes == size); + // Independent hardware field/range oracle, not just donor comparison. + assert(gsm == (2u << ((word >> 6 & 3) - 1)) * 1024 * 1024); + assert(start == (p >= XE_LUNARLAKE ? 8u : d || p == XE_METEORLAKE ? 4u : 2u) * 1024 * 1024); + assert(start + size == (gsm == 8 << 20 ? 0xfee00000u : (u64)gsm * 512)); + const u64 addresses[] = {0, start - 4096, start, start + size - 4096}; + for (unsigned a = 0; a < sizeof(addresses)/sizeof(*addresses); ++a) { + size_t offset = SIZE_MAX; + assert(!stela_intel_gsm_pte_offset(&out, addresses[a], &offset)); + assert(offset == stela_gsm_donor_index(start, size, addresses[a]) * 8); + assert(offset == addresses[a] / 4096 * 8 && offset + 8 <= out.gsm_bytes); + } + ++comparisons; + } + } + } + // Fixed-8MiB policy ignores absent/zero configuration; full BAR span still + // mandatory, and geometry does not get fabricated from a short mapping. + assert(!stela_intel_gsm_geometry(XE_DG2, 1250, true, 16 << 20, false, 0, &out)); + assert(out.gsm_bytes == 8 << 20 && out.ggtt_start == 4 << 20); + assert(out.ggtt_bytes + out.ggtt_start == GUC_GGTT_TOP); + size_t offset = 123; + assert(stela_intel_gsm_pte_offset(&out, out.ggtt_start + out.ggtt_bytes, &offset) == -22 && offset == 123); + assert(stela_intel_gsm_pte_offset(&out, 1, &offset) == -22 && offset == 123); + assert(stela_intel_gsm_pte_offset(&out, UINT64_MAX, &offset) == -22 && offset == 123); + assert(stela_intel_gsm_pte_offset(NULL, 0, &offset) == -22 && offset == 123); + struct stela_intel_gsm_geometry bad = out; + bad.gsm_bytes = 8; + assert(stela_intel_gsm_pte_offset(&bad, 4096, &offset) == -34 && offset == 123); + bad = out; bad.ggtt_bytes = UINT64_MAX; + assert(stela_intel_gsm_pte_offset(&bad, 0, &offset) == -22 && offset == 123); + bad = out; bad.ggtt_start = UINT64_MAX; + assert(stela_intel_gsm_pte_offset(&bad, 0, &offset) == -22 && offset == 123); + for (unsigned which = 0; which < 5; ++which) { + out = sentinel; + int status; + switch(which) { + case 0: status = stela_intel_gsm_geometry(XE_TIGERLAKE, 1200, false, 16 << 20, false, 0, &out); assert(status == -95); break; + case 1: status = stela_intel_gsm_geometry(XE_DG2, 1250, true, (16 << 20) - 1, false, 0, &out); assert(status == -34); break; + case 2: status = stela_intel_gsm_geometry(XE_DG2, 1250, true, 0, false, 0, &out); assert(status == -34); break; + case 3: status = stela_intel_gsm_geometry(0, 1250, true, 16 << 20, false, 0, &out); assert(status == -22); break; + default: status = stela_intel_gsm_geometry(UINT32_MAX, 1250, true, 16 << 20, false, 0, &out); assert(status == -22); break; + } + assert(!memcmp(&out, &sentinel, sizeof(out))); + } + printf("Intel GSM: %u original geometry comparisons, independent field/span/index and output-preserving refusals; CPU-only\n", comparisons); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.c new file mode 100644 index 0000000000..71b03eee73 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.c @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: MIT */ +/* Frozen original arithmetic/assertions, separate original-source object. + * Scalar test context only, not a fake Linux GGTT/device/MMIO implementation. */ +#include "ggtt_probe_donor.h" +#include "../../xe/xe_scalar_types.h" +#include "../../xe/regs/xe_gtt_defs.h" +#include "ggtt_probe_defs.h" +#include +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" +unsigned int stela_gsm_donor_decode(uint16_t gmch_ctl) +{ + u16 ggms; +#include "donor-gsm-decode.inc" +} +#pragma clang diagnostic pop +void stela_gsm_donor_range(unsigned int gsm_size, uint64_t wopcm, uint64_t *out_start, uint64_t *out_size) +{ + u64 ggtt_start, ggtt_size; +#include "donor-pf-range.inc" +#include "donor-range-clamp.inc" + *out_start = ggtt_start; *out_size = ggtt_size; +} +uint64_t stela_gsm_donor_index(uint64_t start, uint64_t size, uint64_t addr) +{ +#include "donor-pte-index.inc" +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.h b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.h new file mode 100644 index 0000000000..0659cae203 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/ggtt_probe_donor.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_GGTT_PROBE_DONOR_H +#define STELA_INTEL_GGTT_PROBE_DONOR_H +#include "../ggtt_probe.h" +unsigned int stela_gsm_donor_decode(uint16_t); +void stela_gsm_donor_range(unsigned int, uint64_t, uint64_t *, uint64_t *); +uint64_t stela_gsm_donor_index(uint64_t, uint64_t, uint64_t); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset.c b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset.c new file mode 100644 index 0000000000..089866b3aa --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset.c @@ -0,0 +1,272 @@ +/* SPDX-License-Identifier: MIT */ +/* Complete original/reset Linux-caller trace model, not physical hardware. */ +#include "guc_reset_model.h" +#include "../guc_reset.h" +#include +#include +#include +#include +#define ETIMEDOUT 110 +static void event(struct reset_test_model *m, u32 kind, u32 reg, u32 a, u32 b, u32 c) +{ + assert(m->events < 256); + m->trace[m->events++] = (struct reset_test_event){kind, reg, a, b, c, m->ns}; +} +u32 reset_test_read(struct reset_test_mmio *mmio, struct xe_reg reg) +{ + struct reset_test_model *m = mmio->owner; + u32 value; + switch (reg.addr) { + case 0xc000: /* Actual GUC_STATUS */ + if (m->reset_written) value = m->mia_reset ? GS_MIA_IN_RESET : 0; + else if (m->initial_reset) value = GS_MIA_IN_RESET; + else if (m->idle_written && (uint64_t)(m->ns - m->idle_at) / 1000 >= m->ready_us) + value = REG_FIELD_PREP(GS_UKERNEL_MASK, XE_GUC_LOAD_STATUS_READY); + else value = 0; + break; + case 0xc010: value = m->boot_valid ? GUC_BOOT_UKERNEL_VALID : 0; break; + case 0xc3e4: value = m->idle; break; + case 0xc398: + if (!m->sram_started) { m->sram_started = true; m->sram_at = m->ns; } + value = (uint64_t)(m->ns - m->sram_at) / 1000 >= m->sram_us ? 0 : GUC_SRAM_HANDLING_MASK; + break; + case 0x941c: + assert(m->reset_written); + m->gdrst_reads++; + value = ((uint64_t)(m->ns - m->reset_at) / 1000 >= m->clear_us || + (m->gdrst_clear_read && m->gdrst_reads >= m->gdrst_clear_read)) ? 0 : GRDOM_GUC; + break; + default: abort(); + } + event(m, 'R', reg.addr, value, 0, 0); + return value; +} +void reset_test_write(struct reset_test_mmio *mmio, struct xe_reg reg, u32 value) +{ + struct reset_test_model *m = mmio->owner; + event(m, 'W', reg.addr, value, 0, 0); + if (reg.addr == GDRST.addr) { + assert(value == GRDOM_GUC); m->reset_written = true; m->reset_at = m->ns; + } else { + assert(reg.addr == GUC_MAX_IDLE_COUNT.addr); + assert(value == (m->idle | GUC_IDLE_FLOW_DISABLE)); + m->idle = value; m->idle_written = true; m->idle_at = m->ns; + } +} +u32 reset_test_rmw(struct reset_test_mmio *mmio, struct xe_reg reg, u32 clear, u32 set) +{ + u32 value = reset_test_read(mmio, reg); + value &= ~clear; value |= set; + reset_test_write(mmio, reg, value); + return value; +} +static int64_t model_add_us(int64_t time, int64_t us) { return time + us * 1000; } +static int64_t model_now(struct reset_test_mmio *mmio) { return mmio->owner->ns; } +static void model_delay(struct reset_test_mmio *mmio, int64_t wait, bool atomic) +{ + assert(!atomic); assert(wait >= 0 && wait <= 100000); + event(mmio->owner, 'D', 0, (u32)wait, (u32)wait * 2, (u32)atomic); + mmio->owner->ns += wait * 1000; +} +#define XE_MMIO_POLL_NAME model_poll +#define XE_MMIO_POLL_CONTEXT struct reset_test_mmio +#define XE_MMIO_POLL_TIME int64_t +#define XE_MMIO_POLL_NOW model_now +#define XE_MMIO_POLL_ADD_US model_add_us +#define XE_MMIO_POLL_READ reset_test_read +#define XE_MMIO_POLL_BEFORE(a, b) ((a) < (b)) +#define XE_MMIO_POLL_AFTER(a, b) ((a) > (b)) +#define XE_MMIO_POLL_DELTA_US(a, b) (((a) - (b)) / 1000) +#define XE_MMIO_POLL_DELAY model_delay +#include "../../xe/xe_mmio_poll.h" +int reset_test_wait(struct reset_test_mmio *mmio, struct xe_reg reg, u32 mask, u32 value, + u32 timeout, u32 *out, bool atomic) +{ + event(mmio->owner, 'P', reg.addr, mask, value, timeout); + return model_poll(mmio, reg, mask, value, timeout, out, atomic, true); +} +void reset_test_assert(struct reset_test_model *m, unsigned domains) +{ + assert(m->held && domains == 1); event(m, 'A', 0, domains, 0, 0); +} +bool reset_test_wa(struct reset_test_model *m, uint64_t id) +{ + assert(id == UINT64_C(14025883347)); event(m, 'Q', 0, (u32)m->wa, 0, 0); return m->wa; +} +int reset_test_bootstrap(struct reset_test_model *m) +{ + event(m, 'V', 0, (u32)m->bootstrap_status, 0, 0); return m->bootstrap_status; +} +void reset_test_diagnostic(struct reset_test_model *m, const char *format, u32 value) +{ + u32 kind; + if (!strcmp(format, "GuC not ready after disabling idle flow (GUC_STATUS: 0x%x)\n")) { + kind = 1; m->warnings |= 1; + } else if (!strcmp(format, "SRAM handling not complete (GUC_SRAM_STATUS: 0x%x)\n")) { + kind = 2; m->warnings |= 2; + } else if (!strcmp(format, "GuC reset timed out, GDRST=%#x\n")) { + kind = 3; m->errors |= 1; + } else { + assert(!strcmp(format, "GuC status: %#x, MIA core expected to be in reset\n")); + kind = 4; m->errors |= 2; + } + event(m, 'L', 0, kind, value, 0); +} +static void reset_trace_test(void) +{ + size_t count = 0; + const uint64_t ready[] = {0, 10, 100000, UINT64_MAX}; + const uint64_t sram[] = {0, 5000, UINT64_MAX}; + const uint64_t clear[] = {0, 10, 5000, 5001, UINT64_MAX}; + for (unsigned flags = 0; flags < 64; flags++) + for (size_t r = 0; r < 4; r++) for (size_t s = 0; s < 3; s++) + for (size_t g = 0; g < 5; g++) { + struct reset_test_model a = {.held = true, .vf = !!(flags & 1), .wa = !!(flags & 2), + .boot_valid = !!(flags & 4), .initial_reset = !!(flags & 8), + .mia_reset = !!(flags & 16), .bootstrap_status = flags & 32 ? -95 : 0, + .idle = 0x123456, .ready_us = ready[r], .sram_us = sram[s], .clear_us = clear[g]}; + struct reset_test_model b = a; a.mmio.owner = &a; b.mmio.owner = &b; + int actual = reset_linux(&a), original = reset_donor(&b); + assert(actual == original && a.events == b.events && a.ns == b.ns); + assert(!memcmp(a.trace, b.trace, a.events * sizeof(a.trace[0]))); + if (a.vf) { + assert(actual == a.bootstrap_status && a.events == 2 && !a.reset_written); + } else { + assert(a.reset_written); + assert(actual == (clear[g] > 5000 ? -110 : a.mia_reset ? 0 : -5)); + unsigned expected = a.wa && !a.initial_reset && a.boot_valid ? + (ready[r] > 100000 ? 1u : 0u) | (sram[s] > 5000 ? 2u : 0u) : 0; + assert(a.warnings == expected); + assert(a.idle_written == (a.wa && !a.initial_reset && a.boot_valid)); + assert(a.errors == (clear[g] > 5000 ? 1u : a.mia_reset ? 0u : 2u)); + } + count++; + } + /* Independent final-reread oracle: stuck until the last reread at the real + * 5000us deadline; succeeds without changing timeout or omitting effects. */ + struct reset_test_model m = {.held = true, .mia_reset = true, .clear_us = UINT64_MAX}; + m.mmio.owner = &m; assert(reset_linux(&m) == -110); + u32 reads = m.gdrst_reads; + m = (struct reset_test_model){.held = true, .mia_reset = true, + .clear_us = UINT64_MAX, .gdrst_clear_read = reads}; + m.mmio.owner = &m; assert(reset_linux(&m) == 0 && m.ns == 5000000 && m.gdrst_reads == reads); + printf("GuC reset original/Linux core: %zu complete traces + final-reread deadline oracle\n", count); +} + +/* Native actual-State tests below use the real C activation entry and RAM-only + * mandatory owner callbacks. They do not qualify a physical device/provider. */ +struct native_model { bool timeout, missing_mia; size_t writes, reads; int64_t ns; u32 ack; }; +static int context(void *p) { assert(p); return 0; } +static int prepare(void *p, u32 platform, u32 revision, bool discrete) +{ (void)p; (void)platform; (void)revision; (void)discrete; return 0; } +static u32 native_read(void *p, u32 reg) +{ + struct native_model *m = p; m->reads++; + if (reg == 0x130044 || reg == 0xdfc) return m->ack; + if (reg == 0xd8c) return (20u << 22) | (1u << 14); + if (reg == 0x380d8c) return (13u << 22) | (1u << 14); + if (reg == GDRST.addr) return m->timeout ? GRDOM_GUC : 0; + assert(reg == GUC_STATUS.addr); return m->missing_mia ? 0 : GS_MIA_IN_RESET; +} +static void native_write(void *p, u32 reg, u32 value) +{ + struct native_model *m = p; + if (reg == 0xa188) { m->ack = value & 1; return; } + assert(reg == GDRST.addr && value == GRDOM_GUC); m->writes++; +} +static int64_t now(void *p) { return ((struct native_model *)p)->ns; } +static void delay(void *p, u32 min, u32 max, bool atomic) +{ assert(!atomic && max == min * 2); ((struct native_model *)p)->ns += (int64_t)min * 1000; } +static void invariant(void *p, bool condition) { (void)p; assert(condition); } +static void report(void *p, u32 mask, bool wake, int status, u32 value) +{ (void)p; (void)wake; (void)value; assert(mask == 1 && status == 0); } +static const struct stela_intel_activation_io io = {context, prepare, native_read, native_write, + now, delay, invariant, report}; +static void native_test(void) +{ + size_t cases = 0; + for (unsigned mode = 0; mode < 4; mode++) { + struct native_model m = {.timeout = mode == 1, .missing_mia = mode == 2}; + void *state = calloc(1, stela_intel_activation_size()); assert(state); + assert(!stela_intel_activation_init(state, stela_intel_activation_size(), &io, &m, + 0x8086, mode == 3 ? 0xe202 : 0x9a49, 0x030000, 0, UINT64_C(16) << 20, false, true)); + struct stela_intel_guc_reset_result result, before; + memset(&result, 0xa5, sizeof(result)); before = result; + assert(stela_intel_activation_guc_reset(state, &result) == -22); + assert(!m.writes && !memcmp(&before, &result, sizeof(result))); + assert(!stela_intel_activation_wake(state)); + int ret = stela_intel_activation_guc_reset(state, &result); + if (mode == 3) { + assert(ret == -95 && !m.writes && !memcmp(&before, &result, sizeof(result))); + assert(!stela_intel_activation_sleep(state)); + } else { + assert(ret == (mode == 1 ? -110 : mode == 2 ? -5 : 0)); + assert(m.writes == 1 && result.writes == 1 && !result.warnings); + assert(result.gdrst == (mode == 1 ? GRDOM_GUC : 0)); + if (mode) { + struct stela_intel_activation_facts facts; + assert(stela_intel_activation_facts(state, &facts) == -5); + assert(stela_intel_activation_wake(state) == -5); + assert(stela_intel_activation_sleep(state) == -5); + assert(stela_intel_activation_guc_reset(state, &result) == -5); + } else { + assert(result.guc_status & GS_MIA_IN_RESET); + assert(stela_intel_activation_guc_reset(state, &result) == -114); + assert(!stela_intel_activation_sleep(state)); + } + assert(m.writes == 1); + } + free(state); cases++; + } + /* Private adapter preflight uses an actual initialized State for the held + * assertion; mutated scalar snapshots only exercise negative admission. + * Sentinel output and effect counters must survive each error unchanged. */ + struct native_model m = {0}; + void *state = calloc(1, stela_intel_activation_size()); assert(state); + assert(!stela_intel_activation_init(state, stela_intel_activation_size(), &io, &m, + 0x8086, 0x9a49, 0x030000, 0, UINT64_C(16) << 20, false, true)); + assert(!stela_intel_activation_wake(state)); + struct stela_intel_activation_facts actual; + assert(!stela_intel_activation_facts(state, &actual)); + size_t refusals = 0; + for (unsigned field = 0; field < 10; field++) { + struct stela_intel_activation_facts facts = actual; + switch (field) { + case 0: facts.gt_type = 2; break; + case 1: facts.tile_count = 2; break; + case 2: facts.max_gt_per_tile = 2; break; + case 3: facts.graphics_verx100 = 1199; break; + case 4: facts.graphics_verx100 = 1211; break; + case 5: facts.media_verx100 = 1211; break; + case 6: facts.initialized = 0; break; + case 7: facts.awake = 0; break; + case 8: m.ns = -1; break; + case 9: m.ns = INT64_MAX - INT64_C(99999999); break; + default: abort(); + } + struct stela_intel_guc_reset_result result, before; + memset(&result, 0xa5, sizeof(result)); before = result; + size_t reads = m.reads, writes = m.writes; + int ret = stela_intel_guc_reset(&io, &m, state, &facts, &result); + assert(ret == (field >= 8 ? -22 : -95)); + assert(reads == m.reads && writes == m.writes && !memcmp(&before, &result, sizeof(result))); + m.ns = 0; refusals++; + } + /* Missing mandatory services cannot reach effects or poison the actual + * State because of stale nonzero caller output. */ + struct stela_intel_activation_io missing = io; missing.now_ns = NULL; + struct stela_intel_guc_reset_result result, before; + memset(&result, 0xa5, sizeof(result)); before = result; + size_t reads = m.reads, writes = m.writes; + assert(stela_intel_guc_reset(&missing, &m, state, &actual, &result) == -22); + assert(reads == m.reads && writes == m.writes && !memcmp(&before, &result, sizeof(result))); + m.ns = INT64_MAX - INT64_C(99999999); + assert(stela_intel_activation_guc_reset(state, &result) == -22); + m.ns = 0; + assert(!stela_intel_activation_guc_reset(state, &result)); + assert(!stela_intel_activation_sleep(state)); + free(state); + printf("GuC reset native preflight: %zu zero-I/O refusals + missing service/stale-output safety\n", refusals + 1); + printf("GuC reset actual C State: %zu success/failure/refusal cases; no hardware claim\n", cases); +} +int main(void) { reset_trace_test(); native_test(); return 0; } diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_bind.h b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_bind.h new file mode 100644 index 0000000000..24e5715901 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_bind.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: MIT */ +/* Scalar RAM bindings only for compiling the actual donor/Linux caller; never + * shipping Linux device objects, OS stubs or hardware capability providers. */ +#include "guc_reset_model.h" +#define EIO 5 +#define FIELD_PREP(mask, value) REG_FIELD_PREP(mask, value) +#define xe_guc reset_test_model +#define xe_gt reset_test_model +#define xe_mmio reset_test_mmio +#define guc_to_gt(guc) (guc) +#define gt_to_xe(gt) (gt) +#define gt_to_fw(gt) (gt) +#define XE_FW_GT 1u +#define IS_SRIOV_VF(gt) ((gt)->vf) +#define XE_GT_WA(gt, id) reset_test_wa(gt, id) +#define xe_gt_sriov_vf_bootstrap reset_test_bootstrap +#define xe_force_wake_assert_held reset_test_assert +#define xe_mmio_read32 reset_test_read +#define xe_mmio_write32 reset_test_write +#define xe_mmio_rmw32 reset_test_rmw +#define xe_mmio_wait32 reset_test_wait +#define xe_gt_warn reset_test_diagnostic +#define xe_gt_err reset_test_diagnostic diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_donor.c new file mode 100644 index 0000000000..02a349a29f --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_donor.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: MIT */ +#include "guc_reset_bind.h" +#define xe_guc_reset reset_donor +#include "guc-reset-donor.inc" diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_linux.c b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_linux.c new file mode 100644 index 0000000000..96913525d7 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_linux.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: MIT */ +#include "guc_reset_bind.h" +#define xe_guc_reset reset_linux +#include "guc-reset-linux.inc" diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_model.h b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_model.h new file mode 100644 index 0000000000..fa0af55291 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/guc_reset_model.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_GUC_RESET_MODEL_H +#define STELA_GUC_RESET_MODEL_H +#include "../../xe/xe_scalar_types.h" +#include "../../xe/regs/xe_gt_regs.h" +#include "../../xe/regs/xe_guc_regs.h" +#include "../../xe/abi/guc_errors_abi.h" +struct reset_test_model; +struct reset_test_mmio { struct reset_test_model *owner; }; +struct reset_test_event { uint32_t kind, reg, a, b, c; int64_t ns; }; +struct reset_test_model { + struct reset_test_mmio mmio; + bool held, vf, wa, boot_valid, initial_reset, mia_reset, reset_written, idle_written; + bool sram_started; + int bootstrap_status; + uint32_t warnings, errors, idle, gdrst_reads, gdrst_clear_read, events; + uint64_t clear_us, ready_us, sram_us; + int64_t ns, reset_at, idle_at, sram_at; + struct reset_test_event trace[256]; +}; +u32 reset_test_read(struct reset_test_mmio *, struct xe_reg); +void reset_test_write(struct reset_test_mmio *, struct xe_reg, u32); +u32 reset_test_rmw(struct reset_test_mmio *, struct xe_reg, u32, u32); +int reset_test_wait(struct reset_test_mmio *, struct xe_reg, u32, u32, u32, u32 *, bool); +void reset_test_assert(struct reset_test_model *, unsigned); +void reset_test_diagnostic(struct reset_test_model *, const char *, u32); +int reset_test_bootstrap(struct reset_test_model *); +bool reset_test_wa(struct reset_test_model *, uint64_t); +int reset_donor(struct reset_test_model *); +int reset_linux(struct reset_test_model *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware.c b/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware.c new file mode 100644 index 0000000000..05b4ff0318 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware.c @@ -0,0 +1,181 @@ +/* SPDX-License-Identifier: MIT */ +/* Original-object metadata tests only. Inputs are synthetic unsigned data. */ +#include +#include +#include +#include "../firmware.c" +#include "firmware_donor.h" + +#define CSS_OFFSET 384u +#define MANIFEST_OFFSET 160u +#define IMAGE_BYTES (CSS_OFFSET + 400u) +static unsigned cases, checked_arithmetic; +static void css(uint8_t *bytes, uint32_t release) +{ + const struct uc_css_header header = { + .header_size_dw = 32 + 64 + 64 + 1, .size_dw = 32 + 64 + 64 + 1 + 4, + .rsa_info = {64, 64, 1}, .guc_info.sw_version = release, + }; + memset(bytes, 0, 400); memcpy(bytes, &header, sizeof(header)); +} +static void cpd(uint8_t bytes[IMAGE_BYTES]) +{ + memset(bytes, 0, IMAGE_BYTES); + struct gsc_cpd_header_v2 *h = (void *)bytes; + h->header_marker = GSC_CPD_HEADER_MARKER; + h->header_length = sizeof(*h); h->num_of_entries = 2; + struct gsc_cpd_entry *entry = (void *)(bytes + h->header_length); + memcpy(entry[0].name, "HUCP.man", sizeof("HUCP.man")); entry[0].offset = MANIFEST_OFFSET; + memcpy(entry[1].name, "huc_fw", sizeof("huc_fw")); entry[1].offset = CSS_OFFSET; + struct gsc_manifest_header *manifest = (void *)(bytes + MANIFEST_OFFSET); + manifest->fw_version.major = 9; manifest->fw_version.minor = 8; + manifest->fw_version.hotfix = 7; manifest->fw_version.build = 6; + manifest->security_version = 42; + css(bytes + CSS_OFFSET, MAKE_GUC_VER(1, 2, 3)); +} +static void compare(unsigned platform, bool media_gt, const uint8_t *bytes, size_t size) +{ + assert(size <= IMAGE_BYTES); + /* Frozen original's is_cpd_header dereferences u32*. Give that donor its + * actual alignment; native parser must also work on real offset1 spans. */ + _Alignas(uint32_t) uint8_t aligned[IMAGE_BYTES]; + memcpy(aligned, bytes, size); + struct xe_uc_fw fw = {0}; + stela_intel_fw_donor_select(platform, media_gt ? XE_GT_TYPE_MEDIA : XE_GT_TYPE_MAIN, + XE_UC_FW_TYPE_HUC, &fw); + assert(fw.path); + uint32_t expected_diagnostics, diagnostics; + int expected = stela_intel_fw_donor_huc(&fw, platform, aligned, size, &expected_diagnostics); + struct stela_intel_huc_metadata output, before; + memset(&before, 0xa5, sizeof(before)); output = before; + int status = stela_intel_huc_parse(platform, 1200, media_gt, bytes, size, &output, &diagnostics); + if (status == -75 && expected == -EPROTO && expected_diagnostics == STELA_INTEL_GUC_HEADER_SIZE) { + /* Deliberate wide-arithmetic preflight before original unsigned CSS + * subtraction: rejected invalid directory-as-CSS, never success. */ + assert(diagnostics == STELA_INTEL_GUC_UNREPRESENTABLE && !memcmp(&output, &before, sizeof(output))); + ++checked_arithmetic; + return; + } + if (status != expected || diagnostics != expected_diagnostics) + fprintf(stderr, "HuC case%u platform%u size%zu native%d/%x donor%d/%x\n", cases, platform, size, status, diagnostics, expected, expected_diagnostics); + assert(status == expected && diagnostics == expected_diagnostics); + if (status) assert(!memcmp(&before, &output, sizeof(output))); + else { + assert(output.release[0] == fw.versions.found[XE_UC_FW_VER_RELEASE].major && + output.release[1] == fw.versions.found[XE_UC_FW_VER_RELEASE].minor && + output.release[2] == fw.versions.found[XE_UC_FW_VER_RELEASE].patch); + assert(output.ucode_bytes == fw.ucode_size && output.rsa_bytes == fw.rsa_size && + output.upload_bytes == sizeof(struct uc_css_header) + fw.ucode_size && + output.css_offset == fw.css_offset && + output.format == (fw.has_gsc_headers ? STELA_INTEL_HUC_CPD_CSS : STELA_INTEL_HUC_CSS)); + } + assert(!fw.bo && fw.status == XE_UC_FIRMWARE_UNINITIALIZED); + ++cases; +} +struct manifest_result { uint32_t diagnostics, security; }; +static void test_gsc_manifest(void *context, struct xe_uc_fw *fw, + const struct gsc_manifest_header *manifest) +{ + struct manifest_result *result = context; + fw->versions.found[XE_UC_FW_VER_RELEASE].build = manifest->fw_version.build; + result->security = manifest->security_version; +} +int main(void) +{ + uint8_t storage[IMAGE_BYTES + 1], *bytes = storage + 1; + _Static_assert(sizeof("HUCP.man") <= sizeof(((struct gsc_cpd_entry *)0)->name), "HuC literal"); + _Static_assert(sizeof("huc_fw") <= sizeof(((struct gsc_cpd_entry *)0)->name), "CSS literal"); + _Static_assert(sizeof("RBEP.man") <= sizeof(((struct gsc_cpd_entry *)0)->name), "GSC literal"); + for (unsigned platform = 1; platform <= XE_NOVALAKE_P; ++platform) { + struct xe_uc_fw fw = {0}; + stela_intel_fw_donor_select(platform, XE_GT_TYPE_MAIN, XE_UC_FW_TYPE_HUC, &fw); + if (!fw.path) continue; + css(bytes, MAKE_GUC_VER(1, 2, 3)); + compare(platform, false, bytes, 400); /* No GuC minimum version leakage. */ + cpd(bytes); compare(platform, true, bytes, IMAGE_BYTES); + } + cpd(bytes); + for (size_t size = 0; size <= IMAGE_BYTES; ++size) compare(XE_TIGERLAKE, false, bytes, size); + css(bytes, MAKE_GUC_VER(1, 2, 3)); + for (size_t size = 0; size <= 400; ++size) compare(XE_TIGERLAKE, false, bytes, size); + for (unsigned change = 0; change < 20; ++change) { + cpd(bytes); + struct gsc_cpd_header_v2 *h = (void *)bytes; + struct gsc_cpd_entry *entry = (void *)(bytes + sizeof(*h)); + switch (change) { + case 0: h->header_marker ^= 1; break; + case 1: h->header_length = sizeof(*h) - 1; break; + case 2: h->num_of_entries = UINT32_MAX; break; + case 3: h->header_length = UINT8_MAX; break; + case 4: h->num_of_entries = 0; break; + case 5: memset(entry[0].name, 0xff, sizeof(entry[0].name)); break; + case 6: entry[0].name[sizeof("HUCP.man") - 1] = 'x'; break; + case 7: entry[0].name[1] = 0; break; + case 8: entry[0].offset = 0; break; + case 9: entry[0].offset = GSC_CPD_ENTRY_OFFSET_MASK; break; + case 10: entry[0].offset |= GSC_CPD_ENTRY_HUFFMAN_COMP; break; /* Original mask, not decompression. */ + case 11: entry[1].offset = IMAGE_BYTES + 1; break; + case 12: entry[1].offset = IMAGE_BYTES; break; + case 13: entry[1].offset = 0; break; + case 14: memset(entry[1].name, 0xff, sizeof(entry[1].name)); break; + case 15: entry[1].name[sizeof("huc_fw") - 1] = 'x'; break; + case 16: h->num_of_entries = 3; entry[2] = entry[0]; entry[2].offset = IMAGE_BYTES; break; + case 17: entry[0].name[11] = 0xff; entry[1].name[11] = 0xff; break; /* trailing bytes after NUL */ + case 18: memmove(bytes + CSS_OFFSET - 1, bytes + CSS_OFFSET, 400); entry[1].offset = CSS_OFFSET - 1; break; + case 19: memmove(bytes + sizeof(*h) + 1, entry, 2 * sizeof(*entry)); ++h->header_length; break; + } + compare(XE_TIGERLAKE, false, bytes, IMAGE_BYTES); + } + /* Independent success fields: embedded CSS version wins over manifest; + * source subview offset is retained but not counted in WOPCM transfer. */ + cpd(bytes); struct stela_intel_huc_metadata output; uint32_t d; + assert(!stela_intel_huc_parse(XE_TIGERLAKE, 1200, false, bytes, IMAGE_BYTES, &output, &d)); + assert(output.release[0] == 1 && output.release[1] == 2 && output.release[2] == 3 && + output.css_offset == CSS_OFFSET && output.upload_bytes == 144 && output.rsa_bytes == 256 && !d); + /* GSC original parser caller still sees manifest release/build/security + * through the mandatory real adapter. No fake GSC object is constructed. */ + unsigned gsc_cases = 0; + for (unsigned change = 0; change < 7; ++change) { + _Alignas(uint32_t) uint8_t aligned[IMAGE_BYTES]; cpd(aligned); + struct gsc_cpd_header_v2 *h = (void *)aligned; + struct gsc_cpd_entry *entry = (void *)(aligned + sizeof(*h)); + memcpy(entry[0].name, "RBEP.man", sizeof("RBEP.man")); + if (change == 1) memset(entry[0].name, 0xff, sizeof(entry[0].name)); + if (change == 2) entry[0].name[sizeof("RBEP.man") - 1] = 'x'; + if (change == 3) entry[0].name[2] = 0; + if (change == 4) { h->num_of_entries = 3; entry[2] = entry[0]; entry[2].offset = IMAGE_BYTES; } + if (change == 5) entry[0].name[11] = 0xff; + if (change == 6) entry[0].offset |= GSC_CPD_ENTRY_HUFFMAN_COMP; + struct xe_uc_fw a = {.type = XE_UC_FW_TYPE_GSC}, b = a; + struct manifest_result result = {0}; uint32_t expected_security = 0, expected_diagnostics; + const struct xe_uc_fw_cpd_ops ops = {&result, cpd_diagnostic, invariant, huc_css, test_gsc_manifest}; + int status = xe_uc_fw_cpd_parse(&a, aligned, sizeof(aligned), "RBEP.man", sizeof("RBEP.man"), + NULL, 0, XE_METEORLAKE, &ops); + int expected = stela_intel_fw_donor_cpd(&b, XE_METEORLAKE, aligned, sizeof(aligned), "RBEP.man", NULL, + &expected_security, &expected_diagnostics); + assert(status == expected && result.diagnostics == expected_diagnostics && + a.has_gsc_headers == b.has_gsc_headers && + !memcmp(&a.versions.found[0], &b.versions.found[0], sizeof(a.versions.found[0])) && + result.security == expected_security); + if (!status) assert(a.versions.found[0].major == 9 && a.versions.found[0].minor == 8 && + a.versions.found[0].patch == 7 && a.versions.found[0].build == 6 && result.security == 42); + ++gsc_cases; + } + /* Invalid/absent/default role and malformed arithmetic preserve output. */ + for (unsigned bad = 0; bad < 7; ++bad) { + cpd(bytes); struct stela_intel_huc_metadata before; + memset(&before, 0xa5, sizeof(before)); output = before; + if (bad >= 4) { + struct uc_css_header *h = (void *)(bytes + CSS_OFFSET); + if (bad == 4) h->size_dw = 0; + if (bad == 5) h->rsa_info.key_size_dw = UINT32_MAX; + if (bad == 6) h->size_dw = h->header_size_dw + UINT32_C(0x40000000); + } + int status = stela_intel_huc_parse(bad == 0 ? 0 : bad == 1 ? XE_DG2 : XE_TIGERLAKE, + bad == 2 ? 1256 : bad == 3 ? 0 : 1200, false, bytes, IMAGE_BYTES, &output, &d); + assert(status == (bad == 0 || bad == 3 ? -EINVAL : bad < 4 ? -95 : -75)); + assert(!memcmp(&output, &before, sizeof(output))); + } + printf("Intel HuC: %u frozen CPD/CSS donor comparisons, offset1 native slices,20 directory cases, %u original GSC build/security/name cases,%u strict wide-arithmetic refusals,7 refusal/overflow cases; host images only, no authentication/BO/WOPCM readiness\n", cases, gsc_cases, checked_arithmetic); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware_donor.c new file mode 100644 index 0000000000..457f4ee5da --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/huc_firmware_donor.c @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: MIT */ +/* Frozen original CPD policy object, scalar diagnostics/platform adapters only. + * No fake Linux GSC/GT/BO object or status/transport implementation. */ +#include "../../xe/xe_scalar_types.h" +#include "../../xe/xe_platform_types.h" +#include "../../xe/xe_uc_fw_types.h" +#include "../../xe/abi/uc_fw_abi.h" +#include "../firmware.h" +#include "firmware_donor.h" +#include +#include +#define EINVAL 22 +#define ENOENT 2 +#define ENODATA 61 +static _Thread_local unsigned active_platform; +static _Thread_local uint32_t *active_diagnostics; +static _Thread_local uint32_t *active_security; +#define xe_assert(xe, condition) assert(condition) +static void report(const char *format) +{ + if (strstr(format, "invalid CPD")) *active_diagnostics |= STELA_INTEL_HUC_CPD_HEADER_LENGTH; + else if (strstr(format, "Failed to find")) *active_diagnostics |= STELA_INTEL_HUC_CPD_MISSING_MANIFEST; + else { assert(strstr(format, "FW too small")); *active_diagnostics |= STELA_INTEL_HUC_CPD_SHORT_IMAGE; } +} +#define xe_gt_err(gt, format, ...) report(format) +static int parse_css_header(struct xe_uc_fw *fw, const void *data, size_t size) +{ + return stela_intel_fw_donor_css(fw, data, size, active_diagnostics); +} +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-compare" +#pragma clang diagnostic ignored "-Wpointer-sign" +#include "donor-fw-cpd.inc" +#pragma clang diagnostic pop +int stela_intel_fw_donor_cpd(struct xe_uc_fw *fw, unsigned platform, const void *data, + size_t size, const char *manifest, const char *css, + uint32_t *security, uint32_t *diagnostics) +{ + *diagnostics = 0; active_platform = platform; + active_diagnostics = diagnostics; active_security = security; + int status = parse_cpd_header(fw, data, size, manifest, css); + active_diagnostics = NULL; active_security = NULL; + return status; +} +int stela_intel_fw_donor_huc(struct xe_uc_fw *fw, unsigned platform, + const void *data, size_t size, uint32_t *diagnostics) +{ + int status = stela_intel_fw_donor_cpd(fw, platform, data, size, "HUCP.man", "huc_fw", NULL, diagnostics); + if (status == -ENOENT) status = stela_intel_fw_donor_css(fw, data, size, diagnostics); + if (!status) { + uint32_t version_diagnostics = 0; + status = stela_intel_fw_donor_version(fw, &version_diagnostics); + *diagnostics |= version_diagnostics; + } + return status; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/pat.c b/crates/stela-drivers/src/gpu/intel/stela/tests/pat.c new file mode 100644 index 0000000000..fb60ec4625 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/pat.c @@ -0,0 +1,111 @@ +/* SPDX-License-Identifier: MIT */ +#include "pat_donor.h" +#include "../pat.h" +#include "../../xe/regs/xe_reg_defs.h" +#include "pat_compile_defs.h" +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) +struct diagnostics {bool warning,missing;}; +#define XE_PAT_SELECT_WARN(context, condition) (((struct diagnostics *)(context))->warning |= !!(condition)) +#define XE_PAT_SELECT_MISSING(context, version) ((void)(version), ((struct diagnostics *)(context))->missing=true) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-field-initializers" +#include "../../xe/xe_pat_select.h" +#pragma clang diagnostic pop +static void record(void *context,struct xe_reg reg,u32 value) +{ + struct stela_pat_trace *out=context;assert(out->count<34); + out->offset[out->count]=reg.addr;out->value[out->count++]=value; +} +#define XE_PAT_PROGRAM_WRITE(context,reg,value) record(context,reg,value) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" +#include "../../xe/xe_pat_program.h" +#pragma clang diagnostic pop +static void selected(enum xe_platform platform,uint32_t graphics,bool discrete,bool llc, + struct stela_pat_test_policy *out,struct xe_pat_selection *selection) +{ + struct diagnostics d={0}; + *selection=(struct xe_pat_selection){.profile=XE_PAT_PROFILE_XE2}; + bool known=xe_pat_select(selection,platform,graphics,discrete,llc,&d); + assert(known!=d.missing); + *out=(struct stela_pat_test_policy){.profile=selection->profile,.count=(uint32_t)selection->n_entries, + .warning=d.warning,.missing=d.missing}; + memcpy(out->indices,selection->idx,sizeof(out->indices)); + if(selection->n_entries)memcpy(out->entries,selection->table,(size_t)selection->n_entries*sizeof(*selection->table)); + if(selection->pat_ats){out->special|=1;out->ats=*selection->pat_ats;} + if(selection->pat_primary_pta){out->special|=2;out->primary=*selection->pat_primary_pta;} + if(selection->pat_media_pta){out->special|=4;out->media=*selection->pat_media_pta;} +} +static int check(void *context){return *(int*)context;} +static struct stela_pat_trace native; +static void native_write(void *context,uint32_t offset,uint32_t value) +{(void)context;assert(native.count<34);native.offset[native.count]=offset;native.value[native.count++]=value;} +int main(void) +{ + const uint32_t versions[]={0,1100,1200,1210,1211,1250,1255,1260,1270,1271,1274, + 1999,2000,2001,2002,2004,2099,3000,3001,3003,3004,3005,3099,3500,3510,3511,3512,3599,3600,4000}; + _Static_assert(_PAT_INDEX(7)==0x481c, "original first range end"); + _Static_assert(_PAT_INDEX(8)==0x4848, "original second range start"); + _Static_assert(_PAT_INDEX(31)==0x48a4, "original 32-entry span"); + unsigned cases=0,traces=0,held=0; + for(unsigned p=0;p<=XE_NOVALAKE_P;p++)for(unsigned v=0;ventry_dump debug postcondition. Keep them + // explicit holds, not a successful policy/hardware qualification. + unsigned generation=versions[v]/100; + if(generation>=20 && generation!=20 && generation!=30 && generation!=35 && + (p==XE_METEORLAKE || p==XE_PVC || p==XE_DG2)) {++held;continue;} + struct stela_pat_test_policy expected,actual; + struct xe_pat_selection selection; + stela_pat_donor_policy((enum xe_platform)p,versions[v],d!=0,llc!=0,&expected); + selected((enum xe_platform)p,versions[v],d!=0,llc!=0,&actual,&selection); + assert(!memcmp(&actual,&expected,sizeof(actual)));++cases; + if(actual.missing)continue; + struct stela_pat_trace a,b={0}; + stela_pat_donor_program(&expected,&a); + xe_pat_program_direct(&b,selection.table,selection.n_entries,selection.pat_ats,selection.pat_primary_pta); + assert(!memcmp(&a,&b,sizeof(a)));++traces; + if(versions[v]==2001)assert(actual.count==28); + if(versions[v]/100==20 || versions[v]/100==30) { + for(unsigned i=16;i<20;i++) { + if(i==16 && versions[v]/100==30)assert(actual.entries[i].valid==1); + else assert(actual.entries[i].value==0 && actual.entries[i].valid==0 && actual.entries[i].coh_mode==0); + } + } // Original CLOS3 workaround. + if(versions[v]==3511)assert(actual.count==32 && actual.indices[XE_CACHE_WT]==3 && actual.special==7); + if(versions[v]<=1210 && p!=XE_METEORLAKE && p!=XE_PVC && p!=XE_DG2) { + assert(actual.count==4 && !actual.special && actual.indices[XE_CACHE_WB]==0); + assert(actual.indices[XE_CACHE_NONE_COMPRESSION]==UINT16_MAX && actual.indices[XE_CACHE_WB_COMPRESSION]==UINT16_MAX); + assert(actual.entries[0].value==3 && actual.entries[1].value==1 && actual.entries[2].value==2 && actual.entries[3].value==0); + for(unsigned i=0;i<4;i++)assert(a.offset[i]==0x4800+4*i); + } + } + int context=0;struct stela_intel_activation_io io={.check_context=check,.write32=native_write}; + struct stela_intel_activation_facts facts={.platform=XE_TIGERLAKE,.graphics_verx100=1200, + .has_llc=1,.gt_type=1,.initialized=1,.awake=1}; + struct stela_intel_pat_result out,before;memset(&before,0xa5,sizeof(before)); + unsigned refusals=0; + for(unsigned variant=0;variant<10;variant++) { + struct stela_intel_activation_facts f=facts;out=before;native=(struct stela_pat_trace){0};int expected=-95; + switch(variant){case 0:f.gt_type=2;break;case 1:f.has_llc=0;break;case 2:f.awake=0;break; + case 3:f.platform=XE_DG2;f.graphics_verx100=1255;f.discrete=1;break; + case 4:f.platform=XE_METEORLAKE;f.graphics_verx100=1270;break; + case 5:f.graphics_verx100=4000;break;case 6:context=-16;expected=-16;break; + case 7:f.awake=2;break;case 8:f.has_llc=2;break;case 9:f.platform=XE_METEORLAKE;f.graphics_verx100=4000;break;} + assert(stela_intel_pat_program(&io,&context,&f,&out)==expected); + assert(!native.count && !memcmp(&out,&before,sizeof(out)));context=0;++refusals; + } + out=before;native=(struct stela_pat_trace){0}; + assert(!stela_intel_pat_program(&io,&context,&facts,&out)); + assert(native.count==4 && out.writes==4 && out.n_entries==4 && out.cache_none==3 && out.cache_wt==2 && out.cache_wb==0); + assert(out.cache_none_compression==UINT16_MAX && out.cache_wb_compression==UINT16_MAX); + const uint32_t values[]={3,1,2,0}; + for(unsigned i=0;i<4;i++)assert(native.offset[i]==0x4800+4*i && native.value[i]==values[i] && out.entries[i]==values[i]); + printf("Intel PAT: %u whole original policies, %u full direct/ATS/PTA traces, %u zero-I/O refusals; %u impossible platform/version holds; independent XeLP values/order/cache and modern limits; CPU only\n",cases,traces,refusals,held); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.c new file mode 100644 index 0000000000..5208e0c62e --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.c @@ -0,0 +1,99 @@ +/* SPDX-License-Identifier: MIT */ +/* Original source in separate object, no LTO. Test-only scalar metadata and + * write trace context; no Linux/device/IRQ provider or fake hardware ACK. */ +#include "pat_donor.h" +#include "../../xe/regs/xe_reg_defs.h" +#include "pat_compile_defs.h" +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wmissing-field-initializers" +#include "donor-pat-tables.inc" +#pragma clang diagnostic pop +struct test_ops { bool dump, program_graphics, program_media, entry_dump; uint32_t id; }; +/* Only identity/capability shape, not a callable successful fake programmer. + * Original source assignments are checked separately against retained ops. */ +static const struct test_ops xelp_pat_ops={true,true,false,false,1}, + xehp_pat_ops={true,true,false,false,2},xehpc_pat_ops={true,true,false,false,3}, + xelpg_pat_ops={true,true,true,false,4},xe2_pat_ops={true,true,true,true,5}, + xe3p_xpc_pat_ops={true,true,true,true,6}; +struct stela_pat_model { + struct {enum xe_platform platform;bool has_llc;} info; + struct { const struct test_ops *ops; const struct xe_pat_table_entry *table, + *pat_ats,*pat_primary_pta,*pat_media_pta;int n_entries;u16 idx[__XE_CACHE_LEVEL_COUNT]; } pat; + uint32_t graphics, media, drm;bool discrete,warning,missing; +}; +static struct stela_pat_model *active; +#define xe_device stela_pat_model +#define GRAPHICS_VERx100(xe) ((xe)->graphics) +#define GRAPHICS_VER(xe) ((xe)->graphics/100) +#define MEDIA_VER(xe) ((xe)->media/100) +#define IS_DGFX(xe) ((xe)->discrete) +#define WARN_ON_ONCE(condition) (active->warning |= !!(condition)) +#define drm_err(printer, ...) ((void)(printer), active->missing=true) +#define xe_assert(xe, condition) ((void)(xe),assert(condition)) +#define xe_pat_init_early donor_init +#include "donor-pat-select.inc" +#undef xe_pat_init_early +#undef xe_device +/* Compile the actual retained Linux caller adaptation too, in this scalar + * context. Its shared tables are byte-identical to the frozen tables above. */ +#define XE_PAT_TABLES_H +#define xe_device stela_pat_model +#define xe_pat_init_early current_init +#include "current-pat-wrapper.inc" +#undef xe_pat_init_early +#undef xe_device +void stela_pat_donor_policy(enum xe_platform platform, uint32_t graphics, bool discrete, + bool llc, struct stela_pat_test_policy *out) +{ + struct stela_pat_model xe={.info={platform,llc},.graphics=graphics, + .media=1200,.discrete=discrete}; + /* Existing ops are retained in original missing-policy path. No table or + * programmer is claimed available there; n_entries remains zero. */ + xe.pat.ops=&xe2_pat_ops; + struct stela_pat_model current=xe; + active=&xe;donor_init(&xe); + active=¤t;current_init(¤t); + assert(xe.pat.ops==current.pat.ops && xe.pat.table==current.pat.table && + xe.pat.n_entries==current.pat.n_entries && xe.pat.pat_ats==current.pat.pat_ats && + xe.pat.pat_primary_pta==current.pat.pat_primary_pta && + xe.pat.pat_media_pta==current.pat.pat_media_pta && + !memcmp(xe.pat.idx,current.pat.idx,sizeof(xe.pat.idx)) && + xe.warning==current.warning && xe.missing==current.missing); + *out=(struct stela_pat_test_policy){.profile=xe.pat.ops->id, + .count=(uint32_t)xe.pat.n_entries,.warning=xe.warning,.missing=xe.missing}; + memcpy(out->indices,xe.pat.idx,sizeof(out->indices)); + if(xe.pat.n_entries)memcpy(out->entries,xe.pat.table,(size_t)xe.pat.n_entries*sizeof(*xe.pat.table)); + if(xe.pat.pat_ats){out->special|=1;out->ats=*xe.pat.pat_ats;} + if(xe.pat.pat_primary_pta){out->special|=2;out->primary=*xe.pat.pat_primary_pta;} + if(xe.pat.pat_media_pta){out->special|=4;out->media=*xe.pat.pat_media_pta;} +} +struct stela_pat_gt_model { + struct stela_pat_model *device; + struct stela_pat_trace *mmio; + const struct xe_pat_table_entry *pta; +}; +#define xe_gt stela_pat_gt_model +#define xe_device stela_pat_model +#define gt_to_xe(gt) ((gt)->device) +#define gt_pta_entry(gt) ((gt)->pta) +static void xe_mmio_write32(struct stela_pat_trace **trace,struct xe_reg reg,u32 value) +{ + struct stela_pat_trace *out=*trace;assert(out->count<34); + out->offset[out->count]=reg.addr;out->value[out->count++]=value; +} +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" +#include "donor-pat-program.inc" +#pragma clang diagnostic pop +void stela_pat_donor_program(const struct stela_pat_test_policy *policy, struct stela_pat_trace *out) +{ + *out=(struct stela_pat_trace){0}; + struct stela_pat_model xe={0}; + if(policy->special&1)xe.pat.pat_ats=&policy->ats; + struct stela_pat_gt_model gt={&xe,out,policy->special&2?&policy->primary:NULL}; + program_pat(>,policy->entries,(int)policy->count); +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.h b/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.h new file mode 100644 index 0000000000..b4a305e2d0 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/pat_donor.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_PAT_DONOR_H +#define STELA_INTEL_PAT_DONOR_H +#include "../../xe/xe_pat.h" +#include "../../xe/xe_cache_level.h" +#include "../../xe/xe_platform_types.h" +struct stela_pat_test_policy { + uint32_t profile, count, warning, missing, special; + uint16_t indices[__XE_CACHE_LEVEL_COUNT]; + struct xe_pat_table_entry entries[32], ats, primary, media; +}; +struct stela_pat_trace { uint32_t count, offset[34], value[34]; }; +void stela_pat_donor_policy(enum xe_platform, uint32_t graphics, bool discrete, + bool llc, struct stela_pat_test_policy *); +void stela_pat_donor_program(const struct stela_pat_test_policy *, struct stela_pat_trace *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.c b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.c new file mode 100644 index 0000000000..889a717c5b --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.c @@ -0,0 +1,155 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include +#include +#include +#include +#include "rbtree_bind.h" +#include "rbtree-body.inc" + +#define COUNT 257 +struct item { unsigned key, maximum; struct rb_node node; }; +static unsigned value(struct item *item) { return item->key; } +RB_DECLARE_CALLBACKS_MAX(static, maxima, struct item, node, unsigned, maximum, value) +static uint64_t checksum = UINT64_C(1469598103934665603); +static size_t checks; +static void record(unsigned v) { checksum = (checksum ^ v) * UINT64_C(1099511628211); } +static unsigned verify_node(struct rb_node *node, struct rb_node *parent, int lo, int hi, + bool augmented, unsigned *count, unsigned *maximum) +{ + if (!node) { *maximum = 0; return 1; } + struct item *item = rb_entry(node, struct item, node); + assert(rb_parent(node) == parent); + assert((int)item->key > lo && (int)item->key < hi); + assert(!(node->__rb_parent_color & 2)); + if (rb_is_red(node)) { + assert(!node->rb_left || rb_is_black(node->rb_left)); + assert(!node->rb_right || rb_is_black(node->rb_right)); + } + unsigned left, right; + unsigned lb = verify_node(node->rb_left, node, lo, (int)item->key, augmented, count, &left); + unsigned rb = verify_node(node->rb_right, node, (int)item->key, hi, augmented, count, &right); + assert(lb == rb); + *maximum = item->key; + if (left > *maximum) *maximum = left; + if (right > *maximum) *maximum = right; + if (augmented) assert(item->maximum == *maximum); + ++*count; + record(item->key * 2 + (unsigned)rb_color(node)); + return lb + (unsigned)rb_is_black(node); +} +static void verify(struct rb_root *root, const bool *present, unsigned expected, bool augmented) +{ + unsigned count = 0, maximum; + if (root->rb_node) assert(rb_is_black(root->rb_node)); + verify_node(root->rb_node, NULL, -1, COUNT, augmented, &count, &maximum); + assert(count == expected); + struct rb_node *n = rb_first(root), *prev = NULL; + for (unsigned i = 0; i < COUNT; ++i) { + if (!present[i]) continue; + assert(n && rb_entry(n, struct item, node)->key == i); + assert(rb_prev(n) == prev); + prev = n; + n = rb_next(n); + } + assert(!n && prev == rb_last(root)); + unsigned post = 0; + bool visited[COUNT] = {false}; + for (n = rb_first_postorder(root); n; n = rb_next_postorder(n)) { + assert(++post <= expected); + unsigned key = rb_entry(n, struct item, node)->key; + assert(present[key] && !visited[key]); + if (n->rb_left) assert(visited[rb_entry(n->rb_left, struct item, node)->key]); + if (n->rb_right) assert(visited[rb_entry(n->rb_right, struct item, node)->key]); + visited[key] = true; + struct rb_node *p = rb_parent(n); + if (p) assert(p->rb_left == n || p->rb_right == n); + } + assert(post == expected); + ++checks; +} +static void insert(struct rb_root *root, struct item *item, bool augmented) +{ + struct rb_node **link = &root->rb_node, *parent = NULL; + while (*link) { + parent = *link; + struct item *other = rb_entry(parent, struct item, node); + assert(item->key != other->key); + link = item->key < other->key ? &parent->rb_left : &parent->rb_right; + } + item->maximum = item->key; + rb_link_node(&item->node, parent, link); + if (augmented) { + maxima.propagate(parent, NULL); + rb_insert_augmented(&item->node, root, &maxima); + } else rb_insert_color(&item->node, root); +} +static uint32_t random_word(uint32_t *s) { *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5; return *s; } +static void shuffle(unsigned *order, uint32_t *seed) +{ + for (unsigned i = 0; i < COUNT; ++i) order[i] = i; + for (unsigned i = COUNT - 1; i; --i) { + unsigned j = random_word(seed) % (i + 1), t = order[i]; order[i] = order[j]; order[j] = t; + } +} +int main(void) +{ + struct item *items = calloc(COUNT + 1, sizeof(*items)); + assert(items && (__UINTPTR_TYPE__)items > UINT32_MAX); + fprintf(stderr, "actual owned allocation=%p last_node=%p parent_word_bytes=%zu\n", + (void *)items, (void *)&items[COUNT].node, sizeof(items[0].node.__rb_parent_color)); + struct rb_node *p = &items[0].node, *n = &items[1].node, *link = NULL; + for (unsigned tag = 0; tag < 4; ++tag) { + n->__rb_parent_color = (__UINTPTR_TYPE__)p | tag; + assert(rb_parent(n) == p && __rb_parent(n->__rb_parent_color) == p); + } + for (unsigned color = 0; color < 2; ++color) { + rb_set_parent_color(n, p, (int)color); + assert(rb_parent(n) == p && rb_color(n) == color); + rb_set_parent(n, &items[2].node); + assert(rb_parent(n) == &items[2].node && rb_color(n) == color); + } + RB_CLEAR_NODE(n); assert(RB_EMPTY_NODE(n) && !rb_next(n) && !rb_prev(n)); + rb_link_node(n, p, &link); + assert(link == n && rb_parent(n) == p && !n->rb_left && !n->rb_right); + for (unsigned mode = 0; mode < 2; ++mode) { + for (unsigned round = 1; round <= 32; ++round) { + struct rb_root root = RB_ROOT; + bool present[COUNT] = {false}; + unsigned order[COUNT], count = 0; + uint32_t seed = round; + shuffle(order, &seed); + for (unsigned i = 0; i < COUNT; ++i) { + items[i].key = i; + RB_CLEAR_NODE(&items[i].node); + } + for (unsigned i = 0; i < COUNT; ++i) { + unsigned k = order[i]; + insert(&root, &items[k], mode != 0); + present[k] = true; + verify(&root, present, ++count, mode != 0); + } + /* Replace a real high-address node with a distinct owned node. */ + unsigned k = round % COUNT; + struct item *replacement = &items[COUNT]; + replacement->key = k; + replacement->maximum = items[k].maximum; + rb_replace_node(&items[k].node, &replacement->node, &root); + verify(&root, present, count, mode != 0); + rb_replace_node(&replacement->node, &items[k].node, &root); + verify(&root, present, count, mode != 0); + shuffle(order, &seed); + for (unsigned i = 0; i < COUNT; ++i) { + k = order[i]; + if (mode) rb_erase_augmented(&items[k].node, &root, &maxima); + else rb_erase(&items[k].node, &root); + RB_CLEAR_NODE(&items[k].node); + assert(RB_EMPTY_NODE(&items[k].node)); + present[k] = false; + verify(&root, present, --count, mode != 0); + } + assert(RB_EMPTY_ROOT(&root)); + } + } + printf("STELA_RBTREE checks=%zu checksum=%016llx actual_owned_pointers_above_4GiB=1\n", checks, (unsigned long long)checksum); + free(items); +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.mk b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.mk new file mode 100644 index 0000000000..30fbd49d32 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree.mk @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# Explicit external official input: never fetch an unpinned source during builds. +RBTREE_DONOR_SOURCE ?= +RBTREE_SOURCE_SHA := 3bc417b068cba5aff0c9b6a4400ee5b217bc366fe7b6daa66fab8948d16829c3 +RBTREE_LINUX := $(SOURCE)/../../common/linux/include/linux +RBTREE_HEADERS := $(addprefix $(RBTREE_LINUX)/,rbtree_types.h rbtree.h rbtree_augmented.h container_of.h) +RBTREE_FLAGS := -std=gnu11 -O2 -Wall -Wextra -Werror -Wno-unused-parameter -I$(SOURCE)/tests +RBTREE_NATIVE_FLAGS := -ffreestanding -fno-stack-protector -mno-red-zone -mgeneral-regs-only +RBTREE_TYPES_BLOB := 3c7ae53e813976bd340e3c91c8833910ed1fda56 +RBTREE_BLOB := 48acdc3889dd4e76a2313d822407a570c1b0fe90 +RBTREE_AUGMENTED_BLOB := 6dbc5a1bf6a8ce04042df4c07167cc226d53a466 +RBTREE_CONTAINER_BLOB := 1f6ebf27d962ff01831989cd7744d3cb12c3d37c +.PHONY: rbtree-source-check +rbtree-source-check: + test -n "$(RBTREE_DONOR_SOURCE)" && test -f "$(RBTREE_DONOR_SOURCE)" + test "$$(shasum -a 256 "$(RBTREE_DONOR_SOURCE)" | cut -d ' ' -f 1)" = "$(RBTREE_SOURCE_SHA)" +$(BUILD)/rbtree/donor/fixture.stamp: $(RBTREE_DONOR_SOURCE) $(SOURCE)/tests/rbtree.mk | rbtree-source-check + mkdir -p "$(BUILD)/rbtree/donor" + git -C "$(SOURCE)" show $(RBTREE_TYPES_BLOB) | sed '/^#include /d' > "$(BUILD)/rbtree/donor/rbtree_types.inc" + git -C "$(SOURCE)" show $(RBTREE_BLOB) | sed '/^#include /d' > "$(BUILD)/rbtree/donor/rbtree.inc" + git -C "$(SOURCE)" show $(RBTREE_AUGMENTED_BLOB) | sed '/^#include /d' > "$(BUILD)/rbtree/donor/rbtree_augmented.inc" + git -C "$(SOURCE)" show $(RBTREE_CONTAINER_BLOB) | sed '/^#include /d' > "$(BUILD)/rbtree/donor/container_of.inc" + sed '/^#include /d; /^EXPORT_SYMBOL/d' "$(RBTREE_DONOR_SOURCE)" > "$(BUILD)/rbtree/donor/rbtree-body.inc" + touch "$@" +$(BUILD)/rbtree/current/fixture.stamp: $(BUILD)/rbtree/donor/fixture.stamp $(RBTREE_HEADERS) + mkdir -p "$(BUILD)/rbtree/current" + for h in rbtree_types rbtree rbtree_augmented container_of; do sed '/^#include /d' "$(RBTREE_LINUX)/$$h.h" > "$(BUILD)/rbtree/current/$$h.inc"; done + cp "$(BUILD)/rbtree/donor/rbtree-body.inc" "$(BUILD)/rbtree/current/rbtree-body.inc" + touch "$@" +RBTREE_TEST_INPUTS := $(SOURCE)/tests/rbtree.c $(SOURCE)/tests/rbtree_bind.h +$(BUILD)/rbtree/donor-test: $(RBTREE_TEST_INPUTS) $(BUILD)/rbtree/donor/fixture.stamp + $(HOST_CC) $(RBTREE_FLAGS) $(SANITIZE) -I$(BUILD)/rbtree/donor "$<" -o "$@" +$(BUILD)/rbtree/linux-test: $(RBTREE_TEST_INPUTS) $(BUILD)/rbtree/current/fixture.stamp + $(HOST_CC) $(RBTREE_FLAGS) $(SANITIZE) -I$(BUILD)/rbtree/current "$<" -o "$@" +$(BUILD)/rbtree/native-host-test: $(RBTREE_TEST_INPUTS) $(BUILD)/rbtree/current/fixture.stamp + $(HOST_CC) $(RBTREE_FLAGS) $(SANITIZE) -DSTELA_NATIVE -I$(BUILD)/rbtree/current "$<" -o "$@" +.PHONY: test-rbtree rbtree-abi +# Compare shape/color checksums as well as independent invariants after each op. +test-rbtree: $(BUILD)/rbtree/donor-test $(BUILD)/rbtree/linux-test $(BUILD)/rbtree/native-host-test + $(BUILD)/rbtree/donor-test > "$(BUILD)/rbtree/donor-test.log" 2> "$(BUILD)/rbtree/donor-addresses.log" + $(BUILD)/rbtree/linux-test > "$(BUILD)/rbtree/linux-test.log" 2> "$(BUILD)/rbtree/linux-addresses.log" + $(BUILD)/rbtree/native-host-test > "$(BUILD)/rbtree/native-host-test.log" 2> "$(BUILD)/rbtree/native-host-addresses.log" + cmp "$(BUILD)/rbtree/donor-test.log" "$(BUILD)/rbtree/linux-test.log" + cmp "$(BUILD)/rbtree/donor-test.log" "$(BUILD)/rbtree/native-host-test.log" + cat "$(BUILD)/rbtree/native-host-test.log" +# Compile native COFF/ELF/Mach-O; this target does not execute COFF or ELF. +rbtree-abi: $(BUILD)/rbtree/current/fixture.stamp $(SOURCE)/tests/rbtree_abi.c $(SOURCE)/tests/rbtree_algorithm.c + set -e; for t in x86_64-unknown-windows x86_64-unknown-linux-gnu x86_64-apple-darwin; do \ + for unit in rbtree_abi rbtree_algorithm; do \ + $(CC) --target=$$t $(RBTREE_FLAGS) $(RBTREE_NATIVE_FLAGS) -DSTELA_NATIVE -I$(BUILD)/rbtree/current -c "$(SOURCE)/tests/$$unit.c" -o "$(BUILD)/rbtree/$$t-$$unit.o"; \ + $(CC) --target=$$t $(RBTREE_FLAGS) $(RBTREE_NATIVE_FLAGS) -DSTELA_NATIVE -I$(BUILD)/rbtree/current -S -emit-llvm "$(SOURCE)/tests/$$unit.c" -o "$(BUILD)/rbtree/$$t-$$unit.ll"; \ + done; \ + done + @if $(CC) --target=x86_64-unknown-windows $(RBTREE_FLAGS) $(RBTREE_NATIVE_FLAGS) -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast -I$(BUILD)/rbtree/donor -c "$(SOURCE)/tests/rbtree_abi.c" -o "$(BUILD)/rbtree/broken-donor.o" > "$(BUILD)/rbtree/broken-donor.log" 2>&1; then echo "original LLP64 parent unexpectedly retained pointer width"; exit 1; fi + rg 'parent must retain all pointer bits' "$(BUILD)/rbtree/broken-donor.log" >/dev/null + set -e; for t in x86_64-unknown-linux-gnu x86_64-apple-darwin; do \ + for unit in rbtree_abi rbtree_algorithm; do \ + $(CC) --target=$$t $(RBTREE_FLAGS) $(RBTREE_NATIVE_FLAGS) -I$(BUILD)/rbtree/donor -S -emit-llvm "$(SOURCE)/tests/$$unit.c" -o "$(BUILD)/rbtree/$$t-$$unit-donor.ll"; \ + $(CC) --target=$$t $(RBTREE_FLAGS) $(RBTREE_NATIVE_FLAGS) -I$(BUILD)/rbtree/current -S -emit-llvm "$(SOURCE)/tests/$$unit.c" -o "$(BUILD)/rbtree/$$t-$$unit-linux.ll"; \ + cmp "$(BUILD)/rbtree/$$t-$$unit-donor.ll" "$(BUILD)/rbtree/$$t-$$unit-linux.ll"; \ + cmp "$(BUILD)/rbtree/$$t-$$unit-donor.ll" "$(BUILD)/rbtree/$$t-$$unit.ll"; \ + done; \ + done diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_abi.c b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_abi.c new file mode 100644 index 0000000000..6d643fe7ea --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_abi.c @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "rbtree_bind.h" +_Static_assert(sizeof(((struct rb_node *)0)->__rb_parent_color) == sizeof(void *), "parent must retain all pointer bits"); +_Static_assert(sizeof(struct rb_node) == 3 * sizeof(void *), "node size"); +_Static_assert(_Alignof(struct rb_node) == sizeof(void *), "node alignment"); +_Static_assert(offsetof(struct rb_node, rb_right) == sizeof(void *), "right offset"); +_Static_assert(offsetof(struct rb_node, rb_left) == 2 * sizeof(void *), "left offset"); +const unsigned int stela_rb_layout[] = { + sizeof(void *), sizeof(long), sizeof(((struct rb_node *)0)->__rb_parent_color), + sizeof(struct rb_node), _Alignof(struct rb_node), + offsetof(struct rb_node, rb_right), offsetof(struct rb_node, rb_left) +}; +struct rb_node *stela_rb_parent(const struct rb_node *node) { return rb_parent(node); } +struct rb_node *stela_rb_parent_internal(const struct rb_node *node) { return __rb_parent(node->__rb_parent_color); } +void stela_rb_parent_store(struct rb_node *node, struct rb_node *parent) { rb_set_parent(node, parent); } +void stela_rb_parent_color_store(struct rb_node *node, struct rb_node *parent, int color) { rb_set_parent_color(node, parent, color); } +void stela_rb_clear(struct rb_node *node) { RB_CLEAR_NODE(node); } +bool stela_rb_empty(const struct rb_node *node) { return RB_EMPTY_NODE(node); } +void stela_rb_link(struct rb_node *node, struct rb_node *parent, struct rb_node **link) { rb_link_node(node, parent, link); } diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_algorithm.c b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_algorithm.c new file mode 100644 index 0000000000..60bf7f8f99 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_algorithm.c @@ -0,0 +1,4 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* Whole pinned original algorithm; only include/export annotations are bound. */ +#include "rbtree_bind.h" +#include "rbtree-body.inc" diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_bind.h b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_bind.h new file mode 100644 index 0000000000..7ce44bf40b --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/rbtree_bind.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* Test-only primitive bindings; no concurrent/RCU execution is admitted. */ +#ifndef STELA_RBTREE_TEST_BIND_H +#define STELA_RBTREE_TEST_BIND_H +#ifndef bool +#define bool _Bool +#define true 1 +#define false 0 +#endif +#ifndef NULL +#define NULL ((void *)0) +#endif +#ifndef offsetof +#define offsetof(t, m) __builtin_offsetof(t, m) +#endif +#ifndef static_assert +#define static_assert _Static_assert +#endif +#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) +#ifndef __always_inline +#define __always_inline inline __attribute__((always_inline)) +#endif +#define unlikely(x) __builtin_expect(!!(x), 0) +#define READ_ONCE(x) (*(volatile typeof(x) *)&(x)) +#define WRITE_ONCE(x, v) (*(volatile typeof(x) *)&(x) = (v)) +/* Refuse RCU calls: single-owner tests supply no grace-period service. */ +#define rcu_assign_pointer(p, v) do { (void)sizeof(p); (void)sizeof(v); __builtin_trap(); } while (0) +#define rcu_dereference_raw(p) ({ __builtin_trap(); (typeof(p))0; }) +#include "rbtree_types.inc" +#include "container_of.inc" +#include "rbtree.inc" +#include "rbtree_augmented.inc" +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.c b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.c new file mode 100644 index 0000000000..7566892ef4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.c @@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: MIT */ +/* Original-object trace qualification, never physical register/firmware proof. */ +#include "wopcm_donor.h" +#include "../../xe/xe_huc_role.h" +#include +#include +#include +#include +#include +#define SZ_1K 0x00000400 +#define SZ_4K 0x00001000 +#define SZ_8K 0x00002000 +#define SZ_16K 0x00004000 +#define SZ_32K 0x00008000 +#define SZ_2M 0x00200000 +#define SZ_8M 0x00800000 +#define SZ_16M 0x01000000 +#define min(x, y) __builtin_elementwise_min((x), (y)) +#define unlikely(value) __builtin_expect(!!(value), 0) +static void warn_core(void *, unsigned, bool); +#define XE_WOPCM_WARN(core, id, condition) warn_core((core)->context, (id), !!(condition)) +#include "../../xe/xe_wopcm_core.h" +void stela_wopcm_record(struct stela_wopcm_model *m, uint32_t kind, uint32_t a, uint32_t b, uint32_t c) +{ + assert(m->used < 64); m->records[m->used++] = (struct stela_wopcm_record){kind, a, b, c}; +} +u32 stela_wopcm_read(struct stela_wopcm_model *m, struct xe_reg reg) +{ + assert(reg.addr == GUC_WOPCM_SIZE.addr || reg.addr == DMA_GUC_WOPCM_OFFSET.addr); + uint32_t value = reg.addr == GUC_WOPCM_SIZE.addr ? m->reg_size : m->reg_offset; + stela_wopcm_record(m, 1, reg.addr, value, 0); return value; +} +void stela_wopcm_write(struct stela_wopcm_model *m, struct xe_reg reg, u32 value) +{ + assert(reg.addr == GUC_WOPCM_SIZE.addr || reg.addr == DMA_GUC_WOPCM_OFFSET.addr); + stela_wopcm_record(m, 2, reg.addr, value, 0); ++m->writes; + uint32_t *target = reg.addr == GUC_WOPCM_SIZE.addr ? &m->reg_size : &m->reg_offset; + /* Model real write-once state and deliberately absent ACK on selected write. + * Even failure retains written size/base bytes: it is not rollback. */ + if (!(*target & 1)) *target = value | (m->fail_write == m->writes ? 0u : 1u); +} +void stela_wopcm_assert(struct stela_wopcm_model *m) +{ + int result = pthread_mutex_trylock(m->lock); + assert(result == EBUSY); stela_wopcm_record(m, 3, 0, 0, 0); +} +bool stela_wopcm_huc(struct stela_wopcm_model *m) +{ + stela_wopcm_record(m, 4, m->huc_available, 0, 0); return m->huc_available; +} +#define XE_MMIO_VERIFY_NAME checked_verify +#define XE_MMIO_VERIFY_CONTEXT struct stela_wopcm_model +#define XE_MMIO_VERIFY_WRITE stela_wopcm_write +#define XE_MMIO_VERIFY_READ stela_wopcm_read +#include "../../xe/xe_mmio_verify.h" +static u32 read_core(void *m, struct xe_reg reg) { return stela_wopcm_read(m, reg); } +static int verify_core(void *m, struct xe_reg reg, u32 val, u32 mask, u32 eval) +{ + return checked_verify(m, reg, val, mask, eval); +} +static bool huc_core(void *m) { return stela_wopcm_huc(m); } +static void assert_core(void *m) { stela_wopcm_assert(m); } +static void warn_core(void *m, unsigned id, bool condition) +{ + assert(id < 9); if (condition) stela_wopcm_record(m, 200 + id, 0, 0, 0); +} +static void report_core(void *m, enum xe_wopcm_event event, u32 a, u32 b, u32 c) +{ + if (event == XE_WOPCM_INVALID_LAYOUT) { a /= SZ_1K; b /= SZ_1K; c /= SZ_1K; } + if (event == XE_WOPCM_GUC_SPACE || event == XE_WOPCM_HUC_SPACE || + event == XE_WOPCM_LOCKED || event == XE_WOPCM_CALCULATED) { a /= SZ_1K; b /= SZ_1K; } + if (event == XE_WOPCM_TOTAL) a /= SZ_1K; + stela_wopcm_record(m, 100 + (unsigned)event, a, b, c); +} +static const struct xe_wopcm_core_ops ops = {read_core, verify_core, huc_core, assert_core, report_core}; +static int pair(struct stela_wopcm_model initial, struct xe_wopcm *result) +{ + struct stela_wopcm_model a = initial, b = initial; + struct xe_wopcm wa = {0}, wb = {0}; + const struct xe_wopcm_core core = {&a, &ops}; + int ar = xe_wopcm_core_init(&wa, a.platform, a.discrete, a.guc_fw_size, a.huc_fw_size, &core); + int br = stela_wopcm_donor(&b, &wb); + assert(ar == br && !memcmp(&wa, &wb, sizeof(wa))); + assert(a.writes == b.writes && a.reg_size == b.reg_size && a.reg_offset == b.reg_offset); + assert(a.used == b.used && !memcmp(a.records, b.records, a.used * sizeof(a.records[0]))); + *result = wa; return ar; +} +int main(void) +{ + pthread_mutex_t mutex; assert(pthread_mutex_init(&mutex, NULL) == 0); + assert(pthread_mutex_lock(&mutex) == 0); + unsigned traces = 0, roles = 0; + const u32 sizes[] = {0, 1, 128, 4095, 4096, 16383, 16384, 16385, 65536, 2*1024*1024, 8*1024*1024}; + for (unsigned platform = 1; platform <= XE_NOVALAKE_P; ++platform) + for (unsigned dgfx = 0; dgfx < 2; ++dgfx) + for (unsigned huc = 0; huc < 2; ++huc) + for (unsigned lock = 0; lock < 4; ++lock) + for (unsigned fail = 0; fail < 3; ++fail) + for (unsigned i = 0; i < sizeof(sizes)/sizeof(sizes[0]); ++i) { + struct stela_wopcm_model input = {.platform = (enum xe_platform)platform, + .discrete = dgfx != 0, .huc_available = huc != 0, + .guc_fw_size = sizes[i], .huc_fw_size = huc ? sizes[(i+4)%11] : 0, + .reg_offset = 0x10000 | (lock & 1), + .reg_size = 0x100000 | (lock >> 1), .fail_write = fail, .lock = &mutex}; + struct xe_wopcm result; (void)pair(input, &result); ++traces; + } + /* Independent expected boundaries/fields supplement source equivalence. */ + struct stela_wopcm_model input = {.platform = XE_METEORLAKE, .guc_fw_size = 128, .lock = &mutex}; + struct xe_wopcm result; + assert(pair(input, &result) == 0); + assert(result.size == 0x400000 && result.guc.base == 0x4000 && result.guc.size == 0x3f3000); + assert(!(result.guc.base & 0x3fff) && !(result.guc.size & 0xfff)); + input.platform = XE_BATTLEMAGE; assert(pair(input, &result) == 0 && result.size == 0x800000); + input.platform = XE_TIGERLAKE; assert(pair(input, &result) == 0 && result.size == 0x200000); + input.discrete = true; assert(pair(input, &result) == 0 && result.size == 0x400000); + input.reg_offset = 0x4001; input.reg_size = 0x10001; + input.guc_fw_size = 0x10000 - 0x6000; + assert(pair(input, &result) == 0 && result.guc.size == 0x10000); + ++input.guc_fw_size; assert(pair(input, &result) == -E2BIG); + input.guc_fw_size = 128; input.huc_fw_size = 1; + assert(pair(input, &result) == -E2BIG); /* exact16KiB HuC reserve no longer fits */ + input.huc_fw_size = 0; input.reg_offset = 0x800001; input.reg_size = 0x1001; + assert(pair(input, &result) == -E2BIG); + input.platform = XE_NOVALAKE_P; + input.reg_size = 0x10001; + assert(pair(input, &result) == 0 && result.size == 0x1000000); /* source retained, not native admission */ + const unsigned versions[] = {0, 700, 1200, 1255, 1256, 1270, 2001, 3000, 3500, UINT32_MAX}; + for (unsigned media = 0; media < 2; ++media) + for (unsigned i = 0; i < sizeof(versions)/sizeof(versions[0]); ++i) { + assert(xe_huc_role_unsupported(media != 0, versions[i]) == stela_wopcm_donor_role(media != 0, versions[i])); + ++roles; + } + assert(pthread_mutex_unlock(&mutex) == 0); assert(pthread_mutex_destroy(&mutex) == 0); + printf("Intel WOPCM: %u frozen-object/core traces, %u original role cases, independent reserve/layout/generation bounds; no hardware readback/upload\n", traces, roles); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.rs b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.rs new file mode 100644 index 0000000000..8eca0c83b4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm.rs @@ -0,0 +1,153 @@ +//! Actual Provider + canonical Mapping + original native WOPCM RAM model only. +use super::*; +use intel::{firmware, wopcm}; + +fn catalog_for_device(device: &Device) -> crate::firmware::Catalog { + let request = device.guc_firmware().unwrap(); + intel::catalog_for(&request, intel::bytes(request.wanted())) +} +pub(super) fn owned_wopcm_contract(authority: &Authority, platform: &Platform, next: &AtomicU64) { + // Known missing older HuC prerequisites must not become zero-byte success. + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), 0x9a49); + let mut device = Device::open(authority, input, true).unwrap(); + let catalog = catalog_for_device(&device); + assert!(matches!( + device.prepare_wopcm(&catalog), + Err(wopcm::Error::Device(Error::Awake)) + )); + device.wake().unwrap(); + assert!(matches!( + device.prepare_wopcm(&catalog), + Err(wopcm::Error::Native { + status: -95, + writes: 0, + .. + }) + )); + assert_eq!(counts.wopcm_reads.load(Ordering::SeqCst), 0); + assert_eq!(counts.wopcm_writes.load(Ordering::SeqCst), 0); + device.sleep().unwrap(); + device.retire().unwrap(); + + // Actual owned BMG row with explicit synthetic runtime GMDID input; exact + // real Provider target and original GuC image, not a production fact guess. + for (device_id, graphics, name, total, guc_size) in [ + (0xe202, 2001, "xe/bmg_guc_70.bin", 0x800000, 0x7f3000), + (0x56a0, 1255, "i915/dg2_guc_70.bin", 0x400000, 0x3f3000), + (0x46d0, 1200, "i915/tgl_guc_70.bin", 0x200000, 0x1f3000), + ] { + for locked in [false, true] { + let (offset, size) = if locked { (0x4001, 0x100001) } else { (0, 0) }; + let (input, counts) = owner_with_registers( + next.fetch_add(BYTES as u64, Ordering::SeqCst), + device_id, + offset, + size, + ); + let mut device = Device::open(authority, input, true).unwrap(); + let catalog = catalog_for_device(&device); + device.wake().unwrap(); + let empty = crate::firmware::Catalog::from_handoff(vec![]).unwrap(); + assert!(matches!( + device.prepare_wopcm(&empty), + Err(wopcm::Error::Firmware(firmware::Error::Provider(_))) + )); + assert_eq!(counts.wopcm_reads.load(Ordering::SeqCst), 0); + // All real source/image/owner storage is ready BEFORE register effects. + // An unexpected allocation fails for real; no production fault hook. + allocation_failure::arm(0); + { + let prepared = device.prepare_wopcm(&catalog).unwrap(); + let no_allocation = allocation_failure::disarm(); + assert_eq!(no_allocation.attempts, 0); + assert_eq!(prepared.image().name(), name); + assert_eq!(prepared.identity().device, device_id); + assert_eq!(prepared.facts().graphics_verx100, graphics); + assert_eq!(prepared.metadata().upload_bytes, 144); + assert_eq!( + prepared.layout().total_bytes, + if locked { 0x800000 } else { total } + ); + assert_eq!(prepared.layout().guc_base, 0x4000); + assert_eq!( + prepared.layout().guc_bytes, + if locked { 0x100000 } else { guc_size } + ); + assert_eq!(prepared.writes(), if locked { 0 } else { 2 }); + assert_eq!( + prepared.observed_registers(), + if locked { + (offset, size) + } else { + (0x4001, guc_size | 1) + } + ); + assert_ne!(prepared.diagnostics(), 0); + } // no implicit sleep/reset/drain or lock rollback + assert_eq!(counts.sleep_writes.load(Ordering::SeqCst), 0); + let reads = counts.wopcm_reads.load(Ordering::SeqCst); + assert!(matches!( + device.prepare_wopcm(&catalog), + Err(wopcm::Error::Native { + status: -114, + writes: 0, + .. + }) + )); + assert_eq!(counts.wopcm_reads.load(Ordering::SeqCst), reads); + device.sleep().unwrap(); + device.retire().unwrap(); + assert_eq!(counts.finished.load(Ordering::SeqCst), 1); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 1); + } + } + for device_id in [0xe202, 0x56a0, 0x46d0] { + for fail_at in [1, 2] { + let (input, counts) = owner(next.fetch_add(BYTES as u64, Ordering::SeqCst), device_id); + let mut device = Device::open(authority, input, true).unwrap(); + let catalog = catalog_for_device(&device); + device.wake().unwrap(); + counts.wopcm_fail_at.store(fail_at, Ordering::SeqCst); + let quarantined = authority.status().unwrap().quarantined; + let calls = platform.calls.lock().unwrap().len(); + allocation_failure::arm(0); + let result = device.prepare_wopcm(&catalog); + assert!( + matches!(result, Err(wopcm::Error::Native { status: -22, writes, .. }) if writes == fail_at as u32) + ); + let checks = counts.context_checks.load(Ordering::SeqCst); + let reads = counts.wopcm_reads.load(Ordering::SeqCst); + assert_eq!(device.facts(), Err(Error::Closing)); + assert!(matches!( + device.guc_firmware(), + Err(firmware::Error::Device(Error::Closing)) + )); + assert!(matches!( + device.prepare_wopcm(&catalog), + Err(wopcm::Error::Device(Error::Closing)) + )); + assert_eq!(device.wake(), Err(Error::Closing)); + assert_eq!(device.sleep(), Err(Error::Closing)); + assert_eq!(device.retire(), Err(Error::Awake)); + drop(device); // canonical quarantine + retained exact context/state + assert_eq!(counts.context_checks.load(Ordering::SeqCst), checks); + assert_eq!(counts.wopcm_reads.load(Ordering::SeqCst), reads); + assert_eq!(counts.sleep_writes.load(Ordering::SeqCst), 0); + assert_eq!(counts.finished.load(Ordering::SeqCst), 0); + assert_eq!(counts.dropped.load(Ordering::SeqCst), 0); + assert_eq!(counts.reservation_dropped.load(Ordering::SeqCst), 0); + // Prove the actual allocator was still armed across failure+Drop. + let layout = Layout::from_size_align(8, 8).unwrap(); + // SAFETY: intentional allocation-null probe, null is never dereferenced. + let pointer = unsafe { std::alloc::alloc(layout) }; + let observed = allocation_failure::disarm(); + assert!(pointer.is_null() && observed.failed && observed.attempts == 1); + assert_eq!( + platform.calls.lock().unwrap().len(), + calls, + "no uncertain unmap attempt" + ); + assert_eq!(authority.status().unwrap().quarantined, quarantined + 1); + } + } +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.c b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.c new file mode 100644 index 0000000000..99d2130030 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.c @@ -0,0 +1,83 @@ +/* SPDX-License-Identifier: MIT */ +/* Frozen original algorithms, separate object without LTO. Test scalar/MMIO + * context and real pthread serialization only, no fabricated Linux objects. */ +#include "wopcm_donor.h" +#include "../../xe/xe_uc_fw_types.h" +#include +#include +#include +#include +#define SZ_1K 0x00000400 +#define SZ_4K 0x00001000 +#define SZ_8K 0x00002000 +#define SZ_16K 0x00004000 +#define SZ_32K 0x00008000 +#define SZ_2M 0x00200000 +#define SZ_8M 0x00800000 +#define SZ_16M 0x01000000 +#define min(x, y) __builtin_elementwise_min((x), (y)) +#define unlikely(value) __builtin_expect(!!(value), 0) +#define EINVAL 22 +#define E2BIG 7 +static _Thread_local struct stela_wopcm_model *active_model; +static void donor_log(struct stela_wopcm_model *model, const char *format, ...) +{ + va_list args; va_start(args, format); + uint32_t event = 0, a = 0, b = 0, c = 0; + if (strstr(format, "invalid GuC region")) { + event = 0; a = va_arg(args, unsigned); b = va_arg(args, unsigned); c = va_arg(args, unsigned); + } else if (strstr(format, "no space for")) { + const char *type = va_arg(args, const char *); + assert(!strcmp(type, "GuC") || !strcmp(type, "HuC")); + event = !strcmp(type, "GuC") ? 1 : 2; + a = va_arg(args, unsigned); b = va_arg(args, unsigned); + } else if (strstr(format, "Failed to init")) event = 3; + else if (strstr(format, "%s(%#x)")) { + const char *name = va_arg(args, const char *); + assert(!strcmp(name, "DMA_GUC_WOPCM_OFFSET") || !strcmp(name, "GUC_WOPCM_SIZE")); + event = !strcmp(name, "DMA_GUC_WOPCM_OFFSET") ? 4 : 5; + a = va_arg(args, unsigned); b = va_arg(args, unsigned); + } else if (!strcmp(format, "WOPCM: %uK\n")) { event = 6; a = va_arg(args, unsigned); } + else if (strstr(format, "already locked")) { event = 7; a = va_arg(args, unsigned); b = va_arg(args, unsigned); } + else if (strstr(format, "Calculated")) { event = 8; a = va_arg(args, unsigned); b = va_arg(args, unsigned); } + else { assert(strstr(format, "Unsuccessful")); event = 9; } + va_end(args); stela_wopcm_record(model, 100 + event, a, b, c); +} +static void donor_warn(struct stela_wopcm_model *model, const char *expression, bool condition) +{ + const char *expressions[] = {"!(base & GUC_WOPCM_OFFSET_MASK)", "base & ~GUC_WOPCM_OFFSET_MASK", + "!(size & GUC_WOPCM_SIZE_MASK)", "size & ~GUC_WOPCM_SIZE_MASK", + "guc_fw_size >= wopcm->size", "huc_fw_size >= wopcm->size", + "ctx_rsvd + WOPCM_RESERVED_SIZE >= wopcm->size", "!wopcm->guc.base", "!wopcm->guc.size"}; + unsigned i = 0; + while (i < sizeof(expressions) / sizeof(expressions[0]) && strcmp(expression, expressions[i])) ++i; + assert(i < sizeof(expressions) / sizeof(expressions[0])); + if (condition) stela_wopcm_record(model, 200 + i, 0, 0, 0); +} +#define drm_err(device, ...) donor_log(xe, __VA_ARGS__) +#define drm_dbg(device, ...) donor_log(xe, __VA_ARGS__) +#define drm_notice(device, ...) donor_log(xe, __VA_ARGS__) +#define XE_WARN_ON(condition) donor_warn(xe, #condition, !!(condition)) +#define IS_DGFX(xe) ((xe)->discrete) +#define xe_uc_fw_type_repr(type) ((type) == XE_UC_FW_TYPE_GUC ? "GuC" : "HuC") +#define xe_force_wake_assert_held(fw, domain) stela_wopcm_assert(gt) +#define wopcm_to_xe(wopcm) active_model +#define wopcm_to_gt(wopcm) active_model +#define xe_mmio_write32 stela_wopcm_write +#define xe_mmio_read32 stela_wopcm_read +#define xe_mmio_write32_and_verify donor_verify +#include "donor-verify.inc" +#include "donor-wopcm-constants.inc" +#define xe_wopcm_init donor_wopcm_init +#include "donor-wopcm-body.inc" +int stela_wopcm_donor(struct stela_wopcm_model *model, struct xe_wopcm *output) +{ + active_model = model; + int status = donor_wopcm_init(output); + active_model = NULL; + return status; +} +bool stela_wopcm_donor_role(bool media_gt, unsigned graphics_verx100) +{ +#include "donor-huc-role.inc" +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.h b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.h new file mode 100644 index 0000000000..d7551de2fd --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_donor.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_WOPCM_DONOR_H +#define STELA_INTEL_WOPCM_DONOR_H +#include "../../xe/xe_scalar_types.h" +#include "../../xe/xe_platform_types.h" +#include "../../xe/xe_wopcm_types.h" +#include "../../xe/regs/xe_guc_regs.h" +#include +struct stela_wopcm_record { uint32_t kind, a, b, c; }; +struct stela_wopcm_model { + enum xe_platform platform; + bool discrete, huc_available; + uint32_t guc_fw_size, huc_fw_size, reg_offset, reg_size; + unsigned fail_write, writes, used; + pthread_mutex_t *lock; + struct stela_wopcm_record records[64]; +}; +void stela_wopcm_record(struct stela_wopcm_model *, uint32_t, uint32_t, uint32_t, uint32_t); +u32 stela_wopcm_read(struct stela_wopcm_model *, struct xe_reg); +void stela_wopcm_write(struct stela_wopcm_model *, struct xe_reg, u32); +void stela_wopcm_assert(struct stela_wopcm_model *); +bool stela_wopcm_huc(struct stela_wopcm_model *); +int stela_wopcm_donor(struct stela_wopcm_model *, struct xe_wopcm *); +bool stela_wopcm_donor_role(bool media_gt, unsigned graphics_verx100); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_owned.c b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_owned.c new file mode 100644 index 0000000000..d4e2286d42 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/tests/wopcm_owned.c @@ -0,0 +1,162 @@ +/* SPDX-License-Identifier: MIT */ +/* Explicit pthread/RAM model of actual owned C entry; no native PCI/provider. */ +#include +#include +#include +#include +#include +#include "../activation.c" +#include "../firmware.h" +#include "../../xe/abi/uc_fw_abi.h" +#include "../../xe/xe_uc_fw_version.h" +struct model { + pthread_mutex_t lock; + u32 ack, offset, size; + unsigned reads, writes, wopcm_reads, wopcm_writes, fail_at; +}; +static int check(void *context) +{ + struct model *m = context; + int status = pthread_mutex_trylock(&m->lock); + if (status == EBUSY) return 0; + if (!status) assert(!pthread_mutex_unlock(&m->lock)); + return -16; +} +static int prepare_model(void *c, u32 p, u32 r, bool d) +{ + (void)p; (void)r; (void)d; return check(c); +} +static u32 read_model(void *context, u32 reg) +{ + struct model *m = context; ++m->reads; + assert(!check(m)); + if (reg == 0xd8c) return (20u << 22) | (1u << 14); + if (reg == 0x380d8c) return (13u << 22) | (1u << 14); + if (reg == 0xdfc || reg == 0x130044) return m->ack; + assert(reg == 0xc050 || reg == 0xc340); ++m->wopcm_reads; + return reg == 0xc050 ? m->size : m->offset; +} +static void write_model(void *context, u32 reg, u32 value) +{ + struct model *m = context; ++m->writes; assert(!check(m)); + if (reg == 0xa188) { assert(value == 0x10001 || value == 0x10000); m->ack = value & 1; return; } + assert(reg == 0xc050 || reg == 0xc340); ++m->wopcm_writes; + u32 *target = reg == 0xc050 ? &m->size : &m->offset; + if (!(*target & 1)) *target = value | (m->fail_at == m->wopcm_writes ? 0u : 1u); +} +static int64_t now(void *context) { assert(!check(context)); return 0; } +static void delay(void *context, u32 a, u32 b, bool atomic) +{ + (void)a; (void)b; (void)atomic; assert(!check(context)); + assert(0 && "immediate simulated ACK must not enter poll delay"); +} +static void invariant_model(void *context, bool condition) { assert(!check(context) && condition); } +static void report_model(void *context, u32 domains, bool wake, int status, u32 value) +{ + (void)wake; (void)value; assert(!check(context) && domains == 1 && !status); +} +static const struct stela_intel_activation_io io = {check, prepare_model, read_model, write_model, now, delay, invariant_model, report_model}; +static void initialize_id(struct model *m, struct stela_intel_activation *s, u32 device) +{ + assert(!pthread_mutex_init(&m->lock, NULL)); assert(!pthread_mutex_lock(&m->lock)); + assert(!stela_intel_activation_init(s, sizeof(*s), &io, m, 0x8086, + device, 0x030000, 0, 16*1024*1024, false, true)); +} +static void finish(struct model *m) +{ + assert(!pthread_mutex_unlock(&m->lock)); assert(!pthread_mutex_destroy(&m->lock)); +} +int main(void) +{ + struct uc_css_header css = {.header_size_dw = 32+64+64+1, .size_dw = 32+64+64+1+4, + .rsa_info = {.key_size_dw = 64, .modulus_size_dw = 64, .exponent_size_dw = 1}, + .guc_info = {.sw_version = MAKE_GUC_VER(70,54,0)}}; + uint8_t bytes[400] = {0}; memcpy(bytes, &css, sizeof(css)); + unsigned cases = 0; + for (unsigned mode = 0; mode < 8; ++mode) { + struct model m = {0}; struct stela_intel_activation s; struct stela_intel_wopcm_result out; + initialize_id(&m, &s, mode == 0 ? 0x9a49 : 0xe202); + unsigned reads = m.reads, writes = m.writes; + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -22); + assert(m.reads == reads && m.writes == writes); /* no actual GT ref */ + assert(!stela_intel_activation_wake(&s)); + if (mode == 0) { + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -95); + assert(!out.writes && !m.wopcm_reads && !m.wopcm_writes); + assert(!stela_intel_activation_sleep(&s)); + } else if (mode == 1 || mode == 2) { + m.fail_at = mode; + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -22 && out.writes == mode); + assert(s.poisoned && s.wopcm_uncertain && s.facts.awake && s.domains[XE_FW_DOMAIN_ID_GT].ref); + reads = m.reads; writes = m.writes; + struct stela_intel_activation_facts facts; + assert(stela_intel_activation_facts(&s, &facts) == -5); + assert(stela_intel_activation_wake(&s) == -5); + assert(stela_intel_activation_sleep(&s) == -5); + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -5); + assert(m.reads == reads && m.writes == writes && m.ack == 1); + /* End only this RAM test mutex. No production reset/release exists. */ + } else if (mode == 3) { + m.offset = 0x4001; m.size = 0x100001; + assert(!stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out)); + assert(!out.writes && !m.wopcm_writes && out.guc_base == 0x4000 && out.guc_bytes == 0x100000); + assert(m.wopcm_reads == 2 && out.total_bytes == 0x800000); + assert(!stela_intel_activation_sleep(&s)); + } else if (mode == 4) { + assert(stela_intel_activation_wopcm(&s, bytes, 127, &out) == -61); + assert(!out.writes && !m.wopcm_reads); + assert(!stela_intel_activation_sleep(&s)); + } else if (mode == 5) { + assert(!pthread_mutex_unlock(&m.lock)); + reads = m.reads; writes = m.writes; + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -16); + assert(m.reads == reads && m.writes == writes); + assert(!pthread_mutex_lock(&m.lock)); + assert(!stela_intel_activation_sleep(&s)); + } else if (mode == 6) { + unsigned ref = s.domains[XE_FW_DOMAIN_ID_GT].ref; + s.domains[XE_FW_DOMAIN_ID_GT].ref = 0; + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -22); + assert(!m.wopcm_reads && !out.writes); /* awake bit alone cannot grant access */ + s.domains[XE_FW_DOMAIN_ID_GT].ref = ref; assert(!stela_intel_activation_sleep(&s)); + } else { + assert(!stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out)); + assert(out.writes == 2 && out.raw_offset == 0x4001 && out.raw_size == 0x7f3001); + assert(out.guc_base == 0x4000 && out.guc_bytes == 0x7f3000); + reads = m.reads; writes = m.writes; + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -114); + assert(m.reads == reads && m.writes == writes); + assert(!stela_intel_activation_sleep(&s)); + } + finish(&m); ++cases; + } + const u32 no_huc_ids[] = {0x56a0, 0x46d0}; + unsigned catalog_admitted = 0, selected_refused = 0; + for (unsigned i = 0; i < sizeof(no_huc_ids)/sizeof(no_huc_ids[0]); ++i) { + struct model m = {0}; struct stela_intel_activation s; struct stela_intel_wopcm_result out; + initialize_id(&m, &s, no_huc_ids[i]); assert(!stela_intel_activation_wake(&s)); + assert(!stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out)); + assert(out.writes == 2 && out.guc_base == 0x4000); + assert(out.total_bytes == (i == 0 ? 0x400000 : 0x200000)); + assert(out.guc_bytes == (i == 0 ? 0x3f3000 : 0x1f3000)); + assert(!stela_intel_activation_sleep(&s)); finish(&m); ++catalog_admitted; + } + /* Every actual retained PCI row whose original main-GT default SELECTS + * HuC must retain that prerequisite, regardless of GuC image validity. */ + for (unsigned i = 0; pciidlist[i].driver_data; ++i) { + const struct stela_intel_pci_match *row = &pciidlist[i]; + const struct xe_device_desc *desc = row->driver_data; + if (!desc->pre_gmdid_graphics_ip) continue; + struct stela_intel_huc_default huc; + assert(!stela_intel_huc_select_default((u32)desc->platform, + desc->pre_gmdid_graphics_ip->verx100, false, &huc)); + if (huc.disposition != STELA_INTEL_HUC_SELECTED) continue; + struct model m = {0}; struct stela_intel_activation s; struct stela_intel_wopcm_result out; + initialize_id(&m, &s, row->device); assert(!stela_intel_activation_wake(&s)); + assert(stela_intel_activation_wopcm(&s, bytes, sizeof(bytes), &out) == -95); + assert(!out.writes && !m.wopcm_reads && !m.wopcm_writes); + assert(!stela_intel_activation_sleep(&s)); finish(&m); ++selected_refused; + } + printf("Intel owned WOPCM: %u actual-state/role/context/length/ref/write-failure/poison RAM cases; %u DG2/ADL-N admitted, %u selected-HuC PCI rows refused; no hardware/authentication\n", cases, catalog_admitted, selected_refused); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/wopcm.c b/crates/stela-drivers/src/gpu/intel/stela/wopcm.c new file mode 100644 index 0000000000..f53808ddc6 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/wopcm.c @@ -0,0 +1,126 @@ +/* SPDX-License-Identifier: MIT */ +#include "wopcm.h" +#include "firmware.h" +#include "../xe/xe_scalar_types.h" +#include "../xe/xe_platform_types.h" +#include "../xe/xe_wopcm_types.h" +#include "../xe/regs/xe_guc_regs.h" +_Static_assert(sizeof(struct xe_wopcm) == 12, "original WOPCM metadata ABI"); +_Static_assert(sizeof(struct guc_doorbell_info) == 64, "original packed doorbell ABI"); +_Static_assert(_Alignof(struct guc_doorbell_info) == 1, "original packed alignment"); +#include +/* Fixed scalar spellings from retained linux/sizes.h; no Linux services. + * Original Linux core caller uses its existing size/ALIGN/min definitions. */ +#define SZ_1K 0x00000400 +#define SZ_4K 0x00001000 +#define SZ_8K 0x00002000 +#define SZ_16K 0x00004000 +#define SZ_32K 0x00008000 +#define SZ_2M 0x00200000 +#define SZ_8M 0x00800000 +#define SZ_16M 0x01000000 +#define min(x, y) __builtin_elementwise_min((x), (y)) +#define unlikely(value) __builtin_expect(!!(value), 0) +#define EINVAL 22 +#define E2BIG 7 +static void core_warn(void *, unsigned, bool); +#define XE_WOPCM_WARN(core, id, condition) core_warn((core)->context, (id), !!(condition)) +#include "../xe/xe_wopcm_core.h" + +struct native_wopcm { + const struct stela_intel_activation_io *io; + void *context; + struct stela_intel_wopcm_result *result; + struct stela_intel_activation *activation; + uint32_t huc_disposition; +}; +static u32 native_read(struct native_wopcm *native, struct xe_reg reg) +{ + native->io->invariant(native->context, !(reg.addr & 3) && reg.addr + 4 <= SZ_4M); + u32 value = native->io->read32(native->context, reg.addr); + if (reg.addr == DMA_GUC_WOPCM_OFFSET.addr) native->result->raw_offset = value; + if (reg.addr == GUC_WOPCM_SIZE.addr) native->result->raw_size = value; + return value; +} +static void native_write(struct native_wopcm *native, struct xe_reg reg, u32 value) +{ + native->io->invariant(native->context, !(reg.addr & 3) && reg.addr + 4 <= SZ_4M); + ++native->result->writes; /* Exposure begins BEFORE real owner callback. */ + native->io->write32(native->context, reg.addr, value); +} +#define XE_MMIO_VERIFY_NAME native_verify +#define XE_MMIO_VERIFY_CONTEXT struct native_wopcm +#define XE_MMIO_VERIFY_WRITE native_write +#define XE_MMIO_VERIFY_READ native_read +#include "../xe/xe_mmio_verify.h" +static u32 core_read(void *context, struct xe_reg reg) { return native_read(context, reg); } +static int core_verify(void *context, struct xe_reg reg, u32 val, u32 mask, u32 eval) +{ + return native_verify(context, reg, val, mask, eval); +} +static bool default_huc_available(void *context) +{ + struct native_wopcm *native = context; + native->io->invariant(native->context, + native->huc_disposition == STELA_INTEL_HUC_ABSENT_ROLE || + native->huc_disposition == STELA_INTEL_HUC_ABSENT_CATALOG); + /* Admission proved original unsupported role or missing default path. + * Selected-but-unfetched/failed HuC can NEVER take this branch. */ + return false; +} +static void core_assert_held(void *context) +{ + struct native_wopcm *native = context; + stela_intel_activation_assert_gt(native->activation); +} +static void core_warn(void *context, unsigned id, bool condition) +{ + struct native_wopcm *native = context; + native->io->invariant(native->context, id < 9); + if (condition) native->result->diagnostics |= UINT32_C(1) << (16 + id); +} +static void core_report(void *context, enum xe_wopcm_event event, u32 a, u32 b, u32 c) +{ + struct native_wopcm *native = context; + (void)a; (void)b; (void)c; + native->io->invariant(native->context, (unsigned)event < 10); + native->result->diagnostics |= UINT32_C(1) << (unsigned)event; +} +int stela_intel_wopcm_prepare(const struct stela_intel_activation_io *io, void *context, + struct stela_intel_activation *activation, uint32_t platform, uint32_t graphics_verx100, bool discrete, + const uint8_t *guc_bytes, size_t guc_size, struct stela_intel_wopcm_result *out) +{ + if (!out) return -EINVAL; + *out = (struct stela_intel_wopcm_result){0}; + if (!io || !io->read32 || !io->write32 || !io->invariant || !guc_bytes || !activation) return -EINVAL; + struct stela_intel_huc_default huc; + int status = stela_intel_huc_select_default(platform, graphics_verx100, false, &huc); + if (status) return status; + switch (huc.disposition) { + case STELA_INTEL_HUC_ABSENT_ROLE: + case STELA_INTEL_HUC_ABSENT_CATALOG: + break; + case STELA_INTEL_HUC_SELECTED: + return -95; /* Genuine HuC input/availability still required. */ + default: + return -EINVAL; + } + struct stela_intel_guc_metadata metadata; + status = stela_intel_guc_parse(platform, guc_bytes, guc_size, + &metadata, &out->firmware_diagnostics); + if (status) return status; + if (metadata.upload_bytes > UINT32_MAX - GUC_WOPCM_RESERVED - GUC_WOPCM_STACK_RESERVED) + return -75; + struct native_wopcm native = {io, context, out, activation, huc.disposition}; + static const struct xe_wopcm_core_ops ops = { + core_read, core_verify, default_huc_available, core_assert_held, core_report, + }; + const struct xe_wopcm_core core = {&native, &ops}; + struct xe_wopcm wopcm = {0}; + status = xe_wopcm_core_init(&wopcm, (enum xe_platform)platform, discrete, + metadata.upload_bytes, 0, &core); + out->total_bytes = wopcm.size; + out->guc_base = wopcm.guc.base; + out->guc_bytes = wopcm.guc.size; + return status; +} diff --git a/crates/stela-drivers/src/gpu/intel/stela/wopcm.h b/crates/stela-drivers/src/gpu/intel/stela/wopcm.h new file mode 100644 index 0000000000..b050f4f4e1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/stela/wopcm.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_INTEL_WOPCM_H +#define STELA_INTEL_WOPCM_H +#include "activation.h" + +/* Evidence from one serialized attempt, never firmware READY/auth/upload. + * Layout fields are only usable on success. Raw register fields are the latest + * actual reads. writes is marked BEFORE each owner write; no post-write heap + * reservation or cleanup callback is permitted. Diagnostics bits0..9 are the + * original events; bits16..24 are the original true warning conditions. */ +struct stela_intel_wopcm_result { + uint32_t total_bytes, guc_base, guc_bytes; + uint32_t diagnostics, writes, raw_offset, raw_size, firmware_diagnostics; +}; +_Static_assert(sizeof(struct stela_intel_wopcm_result) == 32, "WOPCM result ABI"); +_Static_assert(offsetof(struct stela_intel_wopcm_result, writes) == 16, "exposure ABI"); +/* Private bounded adapter: activation.c supplies its SAME actual owned context, + * actual immutable facts and already acknowledged exclusive root GT. No new + * provider, mapping, allocation or firmware status exists here. All callbacks + * are mandatory and non-unwinding. The original initializer still gets real + * HuC inputs in its Linux caller; this native path refuses selected HuC, + * admitting only original unsupported-role or missing-default-path cases. */ +int stela_intel_wopcm_prepare(const struct stela_intel_activation_io *, void *, + struct stela_intel_activation *, uint32_t platform, uint32_t graphics_verx100, bool discrete, + const uint8_t *guc_bytes, size_t guc_size, struct stela_intel_wopcm_result *); +/* Actual existing-state assertion; no supplied boolean/fallback proves GT. */ +void stela_intel_activation_assert_gt(struct stela_intel_activation *); +/* Actual owned-state entry. Failed exposed writes poison the native epoch; + * caller MUST retain/quarantine owner/view/forcewake rather than retire it. */ +int stela_intel_activation_wopcm(struct stela_intel_activation *, + const uint8_t *, size_t, struct stela_intel_wopcm_result *); +#endif diff --git a/crates/stela-drivers/src/gpu/intel/wopcm.rs b/crates/stela-drivers/src/gpu/intel/wopcm.rs new file mode 100644 index 0000000000..3d090e59a1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/wopcm.rs @@ -0,0 +1,117 @@ +//! Original root-main-GT WOPCM partition/readback, not GuC upload/authentication. +use super::{activation, firmware}; +use crate::firmware::Image; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(C)] +pub struct Layout { + pub total_bytes: u32, + pub guc_base: u32, + pub guc_bytes: u32, +} +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[repr(C)] +pub(super) struct NativeResult { + pub layout: Layout, + pub diagnostics: u32, + pub writes: u32, + pub raw_offset: u32, + pub raw_size: u32, + pub firmware_diagnostics: u32, +} +const _: () = assert!(core::mem::size_of::() == 32); +const _: () = assert!(core::mem::offset_of!(NativeResult, writes) == 16); +const _: () = assert!(core::mem::offset_of!(NativeResult, firmware_diagnostics) == 28); + +#[derive(Debug, Eq, PartialEq)] +pub enum Error { + Device(activation::Error), + Firmware(firmware::Error), + Native { + status: i32, + diagnostics: u32, + writes: u32, + raw_offset: u32, + raw_size: u32, + firmware_diagnostics: u32, + }, +} +impl From for Error { + fn from(value: activation::Error) -> Self { + Self::Device(value) + } +} +impl From for Error { + fn from(value: firmware::Error) -> Self { + Self::Firmware(value) + } +} +impl NativeResult { + pub(super) fn error(self, status: i32) -> Error { + Error::Native { + status, + diagnostics: self.diagnostics, + writes: self.writes, + raw_offset: self.raw_offset, + raw_size: self.raw_size, + firmware_diagnostics: self.firmware_diagnostics, + } + } +} + +/// One original verified WOPCM partition in the actual retained native epoch. +/// Both real mutable device ownership and original provider Image stay borrowed. +/// Drop performs no sleep/reset/drain/unmap and never invents rollback of locks. +/// There is no READY, BO, GGTT, authentication, upload or submission capability. +/// A successor bootstrap stage must consume this same preparation/owner. +pub struct Preparation<'device, 'provider> { + _device: &'device mut activation::Device, + image: Image<'provider>, + metadata: firmware::Metadata, + identity: activation::PciIdentity, + facts: activation::Facts, + result: NativeResult, +} +impl<'device, 'provider> Preparation<'device, 'provider> { + pub(super) fn from_native( + device: &'device mut activation::Device, + image: Image<'provider>, + metadata: firmware::Metadata, + identity: activation::PciIdentity, + facts: activation::Facts, + result: NativeResult, + ) -> Self { + Self { + _device: device, + image, + metadata, + identity, + facts, + result, + } + } + pub fn image(&self) -> Image<'provider> { + self.image + } + pub fn metadata(&self) -> firmware::Metadata { + self.metadata + } + pub fn identity(&self) -> activation::PciIdentity { + self.identity + } + pub fn facts(&self) -> activation::Facts { + self.facts + } + pub fn layout(&self) -> Layout { + self.result.layout + } + pub fn diagnostics(&self) -> u32 { + self.result.diagnostics + } + pub fn writes(&self) -> u32 { + self.result.writes + } + pub fn observed_registers(&self) -> (u32, u32) { + (self.result.raw_offset, self.result.raw_size) + } +} diff --git a/crates/stela-drivers/src/gpu/intel/xe/abi/uc_fw_abi.h b/crates/stela-drivers/src/gpu/intel/xe/abi/uc_fw_abi.h index 198e949660..c29f124d87 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/abi/uc_fw_abi.h +++ b/crates/stela-drivers/src/gpu/intel/xe/abi/uc_fw_abi.h @@ -6,8 +6,13 @@ #ifndef _ABI_UC_FW_ABI_H #define _ABI_UC_FW_ABI_H +#ifdef STELA_NATIVE +#include "../xe_scalar_types.h" +#define __packed __attribute__((packed)) +#else #include #include +#endif /** * DOC: CSS-based Firmware Layout diff --git a/crates/stela-drivers/src/gpu/intel/xe/regs/xe_guc_regs.h b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_guc_regs.h index fe37a4d9e5..7d9c9e0316 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/regs/xe_guc_regs.h +++ b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_guc_regs.h @@ -6,8 +6,15 @@ #ifndef _XE_GUC_REGS_H_ #define _XE_GUC_REGS_H_ +#ifdef STELA_NATIVE +#include "../xe_scalar_types.h" +#ifndef __packed +#define __packed __attribute__((packed)) +#endif +#else #include #include +#endif #include "regs/xe_reg_defs.h" #include "regs/xe_guc_ct_regs.h" diff --git a/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_defs.h b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_defs.h index 27ac0bf1f6..25e5d0077c 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_defs.h +++ b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_defs.h @@ -6,6 +6,9 @@ #ifndef _XE_REG_DEFS_H_ #define _XE_REG_DEFS_H_ +#ifdef STELA_NATIVE +#include "../xe_scalar_types.h" +#else #include #include @@ -13,53 +16,9 @@ #include #include -/** - * XE_REG_ADDR_MAX - The upper limit on MMIO register address - * - * This macro specifies the upper limit (not inclusive) on MMIO register offset - * supported by struct xe_reg and functions based on struct xe_mmio. - * - * Currently this is defined as 4 MiB. - */ -#define XE_REG_ADDR_MAX SZ_4M +#endif -/** - * struct xe_reg - Register definition - * - * Register definition to be used by the individual register. Although the same - * definition is used for xe_reg and xe_reg_mcr, they use different internal - * APIs for accesses. - */ -struct xe_reg { - union { - struct { - /** @addr: address */ - u32 addr:const_ilog2(XE_REG_ADDR_MAX); - /** - * @masked: register is "masked", with upper 16bits used - * to identify the bits that are updated on the lower - * bits - */ - u32 masked:1; - /** - * @mcr: register is multicast/replicated in the - * hardware and needs special handling. Any register - * with this set should also use a type of xe_reg_mcr_t. - * It's only here so the few places that deal with MCR - * registers specially (xe_sr.c) and tests using the raw - * value can inspect it. - */ - u32 mcr:1; - /** - * @vf: register is accessible from the Virtual Function. - */ - u32 vf:1; - }; - /** @raw: Raw value with both address and options */ - u32 raw; - }; -}; -static_assert(sizeof(struct xe_reg) == sizeof(u32)); +#include "xe_reg_type.h" /** * struct xe_reg_mcr - MCR register definition diff --git a/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_type.h b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_type.h new file mode 100644 index 0000000000..861a9bd06d --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/regs/xe_reg_type.h @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2023 Intel Corporation + */ +#ifndef XE_REG_TYPE_H +#define XE_REG_TYPE_H +/** + * XE_REG_ADDR_MAX - The upper limit on MMIO register address + * + * This macro specifies the upper limit (not inclusive) on MMIO register offset + * supported by struct xe_reg and functions based on struct xe_mmio. + * + * Currently this is defined as 4 MiB. + */ +#define XE_REG_ADDR_MAX SZ_4M + +/** + * struct xe_reg - Register definition + * + * Register definition to be used by the individual register. Although the same + * definition is used for xe_reg and xe_reg_mcr, they use different internal + * APIs for accesses. + */ +struct xe_reg { + union { + struct { + /** @addr: address */ + u32 addr:const_ilog2(XE_REG_ADDR_MAX); + /** + * @masked: register is "masked", with upper 16bits used + * to identify the bits that are updated on the lower + * bits + */ + u32 masked:1; + /** + * @mcr: register is multicast/replicated in the + * hardware and needs special handling. Any register + * with this set should also use a type of xe_reg_mcr_t. + * It's only here so the few places that deal with MCR + * registers specially (xe_sr.c) and tests using the raw + * value can inspect it. + */ + u32 mcr:1; + /** + * @vf: register is accessible from the Virtual Function. + */ + u32 vf:1; + }; + /** @raw: Raw value with both address and options */ + u32 raw; + }; +}; +static_assert(sizeof(struct xe_reg) == sizeof(u32)); + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_cache_level.h b/crates/stela-drivers/src/gpu/intel/xe/xe_cache_level.h new file mode 100644 index 0000000000..52afe229c9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_cache_level.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_CACHE_LEVEL_H +#define XE_CACHE_LEVEL_H +enum xe_cache_level { + XE_CACHE_NONE, + XE_CACHE_WT, + XE_CACHE_WB, + XE_CACHE_NONE_COMPRESSION, /*UC + COH_NONE + COMPRESSION */ + XE_CACHE_WB_COMPRESSION, + __XE_CACHE_LEVEL_COUNT, +}; +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_device_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_device_types.h index aad10899d9..7a76236044 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_device_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_device_types.h @@ -19,6 +19,7 @@ #include "xe_oa_types.h" #include "xe_pagefault_types.h" #include "xe_platform_types.h" +#include "xe_pci_types.h" #include "xe_pmu_types.h" #include "xe_pt_types.h" #include "xe_sriov_pf_types.h" @@ -69,7 +70,6 @@ enum xe_wedged_mode { #define MEDIA_VERx100(xe) ((xe)->info.media_verx100) #define IS_DGFX(xe) ((xe)->info.is_dgfx) -#define XE_VRAM_FLAGS_NEED64K BIT(0) #define XE_GT0 0 #define XE_GT1 1 diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_engine_ids.h b/crates/stela-drivers/src/gpu/intel/xe/xe_engine_ids.h new file mode 100644 index 0000000000..740d4540ae --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_engine_ids.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_ENGINE_IDS_H +#define XE_ENGINE_IDS_H +enum xe_engine_class { + XE_ENGINE_CLASS_RENDER = 0, + XE_ENGINE_CLASS_VIDEO_DECODE = 1, + XE_ENGINE_CLASS_VIDEO_ENHANCE = 2, + XE_ENGINE_CLASS_COPY = 3, + XE_ENGINE_CLASS_OTHER = 4, + XE_ENGINE_CLASS_COMPUTE = 5, + XE_ENGINE_CLASS_MAX = 6, +}; + +enum xe_hw_engine_id { + XE_HW_ENGINE_RCS0, +#define XE_HW_ENGINE_RCS_MASK GENMASK_ULL(XE_HW_ENGINE_RCS0, XE_HW_ENGINE_RCS0) + XE_HW_ENGINE_BCS0, + XE_HW_ENGINE_BCS1, + XE_HW_ENGINE_BCS2, + XE_HW_ENGINE_BCS3, + XE_HW_ENGINE_BCS4, + XE_HW_ENGINE_BCS5, + XE_HW_ENGINE_BCS6, + XE_HW_ENGINE_BCS7, + XE_HW_ENGINE_BCS8, +#define XE_HW_ENGINE_BCS_MASK GENMASK_ULL(XE_HW_ENGINE_BCS8, XE_HW_ENGINE_BCS0) + XE_HW_ENGINE_VCS0, + XE_HW_ENGINE_VCS1, + XE_HW_ENGINE_VCS2, + XE_HW_ENGINE_VCS3, + XE_HW_ENGINE_VCS4, + XE_HW_ENGINE_VCS5, + XE_HW_ENGINE_VCS6, + XE_HW_ENGINE_VCS7, +#define XE_HW_ENGINE_VCS_MASK GENMASK_ULL(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) + XE_HW_ENGINE_VECS0, + XE_HW_ENGINE_VECS1, + XE_HW_ENGINE_VECS2, + XE_HW_ENGINE_VECS3, +#define XE_HW_ENGINE_VECS_MASK GENMASK_ULL(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0) + XE_HW_ENGINE_CCS0, + XE_HW_ENGINE_CCS1, + XE_HW_ENGINE_CCS2, + XE_HW_ENGINE_CCS3, +#define XE_HW_ENGINE_CCS_MASK GENMASK_ULL(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0) + XE_HW_ENGINE_GSCCS0, +#define XE_HW_ENGINE_GSCCS_MASK GENMASK_ULL(XE_HW_ENGINE_GSCCS0, XE_HW_ENGINE_GSCCS0) + XE_NUM_HW_ENGINES, +}; + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.c b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.c index 197e2197bd..875b0c281b 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.c @@ -13,8 +13,7 @@ #include "xe_gt_printk.h" #include "xe_mmio.h" #include "xe_sriov.h" - -#define XE_FORCE_WAKE_ACK_TIMEOUT_MS 50 +#include "xe_force_wake_gt.h" static const char *str_wake_sleep(bool wake) { @@ -33,11 +32,7 @@ static void init_domain(struct xe_force_wake *fw, { struct xe_force_wake_domain *domain = &fw->domains[id]; - domain->id = id; - domain->reg_ctl = reg; - domain->reg_ack = ack; - domain->val = FORCEWAKE_MT(FORCEWAKE_KERNEL); - domain->mask = FORCEWAKE_MT_MASK(FORCEWAKE_KERNEL); + xe_force_wake_domain_init(domain, id, reg, ack); mark_domain_initialized(fw, id); } @@ -49,15 +44,8 @@ void xe_force_wake_init_gt(struct xe_gt *gt, struct xe_force_wake *fw) fw->gt = gt; spin_lock_init(&fw->lock); - if (xe->info.graphics_verx100 >= 1270) { - init_domain(fw, XE_FW_DOMAIN_ID_GT, - FORCEWAKE_GT, - FORCEWAKE_ACK_GT_MTL); - } else { - init_domain(fw, XE_FW_DOMAIN_ID_GT, - FORCEWAKE_GT, - FORCEWAKE_ACK_GT); - } + init_domain(fw, XE_FW_DOMAIN_ID_GT, FORCEWAKE_GT, + xe_force_wake_gt_ack(xe->info.graphics_verx100)); } void xe_force_wake_init_engines(struct xe_gt *gt, struct xe_force_wake *fw) @@ -98,7 +86,7 @@ static void __domain_ctl(struct xe_gt *gt, struct xe_force_wake_domain *domain, if (IS_SRIOV_VF(gt_to_xe(gt))) return; - xe_mmio_write32(>->mmio, domain->reg_ctl, domain->mask | (wake ? domain->val : 0)); + xe_mmio_write32(>->mmio, domain->reg_ctl, xe_force_wake_control(domain, wake)); } static int __domain_wait(struct xe_gt *gt, struct xe_force_wake_domain *domain, bool wake) @@ -120,32 +108,30 @@ static int __domain_wait(struct xe_gt *gt, struct xe_force_wake_domain *domain, xe_gt_err(gt, "Force wake domain %d: %s. MMIO unreliable (forcewake register returns 0xFFFFFFFF)!\n", domain->id, str_wake_sleep(wake)); - ret = -EIO; } - return ret; + return xe_force_wake_wait_status(ret, value); } -static void domain_wake(struct xe_gt *gt, struct xe_force_wake_domain *domain) +static void core_control(void *context, struct xe_force_wake_domain *domain, bool wake) { - __domain_ctl(gt, domain, true); + __domain_ctl(context, domain, wake); } - -static int domain_wake_wait(struct xe_gt *gt, - struct xe_force_wake_domain *domain) +static int core_wait(void *context, struct xe_force_wake_domain *domain, bool wake) { - return __domain_wait(gt, domain, true); + return __domain_wait(context, domain, wake); } - -static void domain_sleep(struct xe_gt *gt, struct xe_force_wake_domain *domain) +static void core_invariant(void *context, bool condition) { - __domain_ctl(gt, domain, false); + xe_gt_assert((struct xe_gt *)context, condition); } - -static int domain_sleep_wait(struct xe_gt *gt, - struct xe_force_wake_domain *domain) +static struct xe_force_wake_core xe_fw_core(struct xe_force_wake *fw) { - return __domain_wait(gt, domain, false); + static const struct xe_force_wake_core_ops ops = { + .control = core_control, .wait = core_wait, .invariant = core_invariant, + }; + return (struct xe_force_wake_core){fw->gt, &ops, fw->initialized_domains, + &fw->awake_domains, fw->domains}; } /** @@ -174,33 +160,16 @@ unsigned int __must_check xe_force_wake_get(struct xe_force_wake *fw, enum xe_force_wake_domains domains) { struct xe_gt *gt = fw->gt; - struct xe_force_wake_domain *domain; - unsigned int ref_incr = 0, awake_rqst = 0, awake_failed = 0; - unsigned int tmp, ref_rqst; + unsigned int ref_incr, awake_failed; unsigned long flags; xe_gt_assert(gt, is_power_of_2(domains)); xe_gt_assert(gt, domains <= XE_FORCEWAKE_ALL); xe_gt_assert(gt, domains == XE_FORCEWAKE_ALL || fw->initialized_domains & domains); - ref_rqst = (domains == XE_FORCEWAKE_ALL) ? fw->initialized_domains : domains; spin_lock_irqsave(&fw->lock, flags); - for_each_fw_domain_masked(domain, ref_rqst, fw, tmp) { - if (!domain->ref++) { - awake_rqst |= BIT(domain->id); - domain_wake(gt, domain); - } - ref_incr |= BIT(domain->id); - } - for_each_fw_domain_masked(domain, awake_rqst, fw, tmp) { - if (domain_wake_wait(gt, domain) == 0) { - fw->awake_domains |= BIT(domain->id); - } else { - awake_failed |= BIT(domain->id); - --domain->ref; - } - } - ref_incr &= ~awake_failed; + struct xe_force_wake_core core = xe_fw_core(fw); + ref_incr = xe_force_wake_get_locked(&core, domains, &awake_failed); spin_unlock_irqrestore(&fw->lock, flags); xe_gt_WARN(gt, awake_failed, "Forcewake domain%s %#x failed to acknowledge awake request\n", @@ -225,8 +194,6 @@ unsigned int __must_check xe_force_wake_get(struct xe_force_wake *fw, void xe_force_wake_put(struct xe_force_wake *fw, unsigned int fw_ref) { struct xe_gt *gt = fw->gt; - struct xe_force_wake_domain *domain; - unsigned int tmp, sleep = 0; unsigned long flags; int ack_fail = 0; @@ -241,20 +208,8 @@ void xe_force_wake_put(struct xe_force_wake *fw, unsigned int fw_ref) fw_ref = fw->initialized_domains; spin_lock_irqsave(&fw->lock, flags); - for_each_fw_domain_masked(domain, fw_ref, fw, tmp) { - xe_gt_assert(gt, domain->ref); - - if (!--domain->ref) { - sleep |= BIT(domain->id); - domain_sleep(gt, domain); - } - } - for_each_fw_domain_masked(domain, sleep, fw, tmp) { - if (domain_sleep_wait(gt, domain) == 0) - fw->awake_domains &= ~BIT(domain->id); - else - ack_fail |= BIT(domain->id); - } + struct xe_force_wake_core core = xe_fw_core(fw); + ack_fail = (int)xe_force_wake_put_locked(&core, fw_ref); spin_unlock_irqrestore(&fw->lock, flags); xe_gt_WARN(gt, ack_fail, "Forcewake domain%s %#x failed to acknowledge sleep request\n", diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.h b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.h index e2721f205d..e8a1b31ae8 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake.h @@ -21,11 +21,7 @@ void xe_force_wake_put(struct xe_force_wake *fw, unsigned int fw_ref); const char *xe_force_wake_domain_to_str(enum xe_force_wake_domain_id id); -#define for_each_fw_domain_masked(domain__, mask__, fw__, tmp__) \ - for (tmp__ = (mask__); tmp__; tmp__ &= ~BIT(ffs(tmp__) - 1)) \ - for_each_if(((domain__) = ((fw__)->domains + \ - (ffs(tmp__) - 1))) && \ - (domain__)->reg_ctl.addr) +#include "xe_force_wake_core.h" #define for_each_fw_domain(domain__, fw__, tmp__) \ for_each_fw_domain_masked((domain__), (fw__)->initialized_domains, (fw__), (tmp__)) diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_core.h b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_core.h new file mode 100644 index 0000000000..c74ebce9c9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_core.h @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_FORCE_WAKE_CORE_H +#define XE_FORCE_WAKE_CORE_H +#define XE_FORCE_WAKE_ACK_TIMEOUT_MS 50 +#define for_each_fw_domain_masked(domain__, mask__, fw__, tmp__) \ + for (tmp__ = (mask__); tmp__; tmp__ &= ~BIT(ffs(tmp__) - 1)) \ + for_each_if(((domain__) = ((fw__)->domains + \ + (ffs(tmp__) - 1))) && \ + (domain__)->reg_ctl.addr) + + +struct xe_force_wake_core_ops { + void (*control)(void *, struct xe_force_wake_domain *, bool); + int (*wait)(void *, struct xe_force_wake_domain *, bool); + void (*invariant)(void *, bool); +}; +struct xe_force_wake_core { + void *context; + const struct xe_force_wake_core_ops *ops; + unsigned int initialized_domains; + unsigned int *awake_domains; + struct xe_force_wake_domain *domains; +}; +/* Caller holds real exclusive serialization across the entire operation. + * Required operations have no defaults. Live domain records are borrowed. + * Public-call validation, ALL-flag normalization, IRQsave locking and diagnostic + * reporting remain in the original Xe wrapper; this is only its locked core. */ +static inline unsigned int xe_force_wake_get_locked(struct xe_force_wake_core *fw, + unsigned int domains, unsigned int *failed) +{ + struct xe_force_wake_domain *domain; + unsigned int ref_incr = 0, awake_rqst = 0, awake_failed = 0; + unsigned int tmp, ref_rqst; + ref_rqst = (domains == XE_FORCEWAKE_ALL) ? fw->initialized_domains : domains; + for_each_fw_domain_masked(domain, ref_rqst, fw, tmp) { + if (!domain->ref++) { + awake_rqst |= BIT(domain->id); + fw->ops->control(fw->context, domain, true); + } + ref_incr |= BIT(domain->id); + } + for_each_fw_domain_masked(domain, awake_rqst, fw, tmp) { + if (fw->ops->wait(fw->context, domain, true) == 0) { + *fw->awake_domains |= BIT(domain->id); + } else { + awake_failed |= BIT(domain->id); + --domain->ref; + } + } + ref_incr &= ~awake_failed; + *failed = awake_failed; + return ref_incr; +} +static inline unsigned int xe_force_wake_put_locked(struct xe_force_wake_core *fw, + unsigned int fw_ref) +{ + struct xe_force_wake_domain *domain; + unsigned int tmp, sleep = 0, ack_fail = 0; + for_each_fw_domain_masked(domain, fw_ref, fw, tmp) { + fw->ops->invariant(fw->context, domain->ref != 0); + + if (!--domain->ref) { + sleep |= BIT(domain->id); + fw->ops->control(fw->context, domain, false); + } + } + for_each_fw_domain_masked(domain, sleep, fw, tmp) { + if (fw->ops->wait(fw->context, domain, false) == 0) + *fw->awake_domains &= ~BIT(domain->id); + else + ack_fail |= BIT(domain->id); + } + return ack_fail; +} +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_domain_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_domain_types.h new file mode 100644 index 0000000000..d3bc8fb0f1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_domain_types.h @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_FORCE_WAKE_DOMAIN_TYPES_H +#define XE_FORCE_WAKE_DOMAIN_TYPES_H +#include "regs/xe_reg_type.h" +enum xe_force_wake_domain_id { + XE_FW_DOMAIN_ID_GT = 0, + XE_FW_DOMAIN_ID_RENDER, + XE_FW_DOMAIN_ID_MEDIA, + XE_FW_DOMAIN_ID_MEDIA_VDBOX0, + XE_FW_DOMAIN_ID_MEDIA_VDBOX1, + XE_FW_DOMAIN_ID_MEDIA_VDBOX2, + XE_FW_DOMAIN_ID_MEDIA_VDBOX3, + XE_FW_DOMAIN_ID_MEDIA_VDBOX4, + XE_FW_DOMAIN_ID_MEDIA_VDBOX5, + XE_FW_DOMAIN_ID_MEDIA_VDBOX6, + XE_FW_DOMAIN_ID_MEDIA_VDBOX7, + XE_FW_DOMAIN_ID_MEDIA_VEBOX0, + XE_FW_DOMAIN_ID_MEDIA_VEBOX1, + XE_FW_DOMAIN_ID_MEDIA_VEBOX2, + XE_FW_DOMAIN_ID_MEDIA_VEBOX3, + XE_FW_DOMAIN_ID_GSC, + XE_FW_DOMAIN_ID_COUNT +}; + +enum xe_force_wake_domains { + XE_FW_GT = BIT(XE_FW_DOMAIN_ID_GT), + XE_FW_RENDER = BIT(XE_FW_DOMAIN_ID_RENDER), + XE_FW_MEDIA = BIT(XE_FW_DOMAIN_ID_MEDIA), + XE_FW_MEDIA_VDBOX0 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX0), + XE_FW_MEDIA_VDBOX1 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX1), + XE_FW_MEDIA_VDBOX2 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX2), + XE_FW_MEDIA_VDBOX3 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX3), + XE_FW_MEDIA_VDBOX4 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX4), + XE_FW_MEDIA_VDBOX5 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX5), + XE_FW_MEDIA_VDBOX6 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX6), + XE_FW_MEDIA_VDBOX7 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX7), + XE_FW_MEDIA_VEBOX0 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX0), + XE_FW_MEDIA_VEBOX1 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX1), + XE_FW_MEDIA_VEBOX2 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX2), + XE_FW_MEDIA_VEBOX3 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX3), + XE_FW_GSC = BIT(XE_FW_DOMAIN_ID_GSC), + XE_FORCEWAKE_ALL = BIT(XE_FW_DOMAIN_ID_COUNT) +}; + +/** + * struct xe_force_wake_domain - Xe force wake power domain + * + * Represents an individual device-internal power domain. The driver must + * ensure the power domain is awake before accessing registers or other + * hardware functionality that is part of the power domain. Since different + * driver threads may access hardware units simultaneously, a reference count + * is used to ensure that the domain remains awake as long as any software + * is using the part of the hardware covered by the power domain. + * + * Hardware provides a register interface to allow the driver to request + * wake/sleep of power domains, although in most cases the actual action of + * powering the hardware up/down is handled by firmware (and may be subject to + * requirements and constraints outside of the driver's visibility) so the + * driver needs to wait for an acknowledgment that a wake request has been + * acted upon before accessing the parts of the hardware that reside within the + * power domain. + */ +struct xe_force_wake_domain { + /** @id: domain force wake id */ + enum xe_force_wake_domain_id id; + /** @reg_ctl: domain wake control register address */ + struct xe_reg reg_ctl; + /** @reg_ack: domain ack register address */ + struct xe_reg reg_ack; + /** @val: domain wake write value */ + u32 val; + /** @mask: domain mask */ + u32 mask; + /** @ref: domain reference */ + u32 ref; +}; + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_gt.h b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_gt.h new file mode 100644 index 0000000000..bb76250fbf --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_gt.h @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_FORCE_WAKE_GT_H +#define XE_FORCE_WAKE_GT_H +static inline struct xe_reg xe_force_wake_gt_ack(u32 graphics_verx100) +{ + if (graphics_verx100 >= 1270) + return FORCEWAKE_ACK_GT_MTL; + return FORCEWAKE_ACK_GT; +} +static inline void xe_force_wake_domain_init(struct xe_force_wake_domain *domain, + enum xe_force_wake_domain_id id, struct xe_reg reg, struct xe_reg ack) +{ + domain->id = id; + domain->reg_ctl = reg; + domain->reg_ack = ack; + domain->val = FORCEWAKE_MT(FORCEWAKE_KERNEL); + domain->mask = FORCEWAKE_MT_MASK(FORCEWAKE_KERNEL); +} +static inline int xe_force_wake_wait_status(int ret, u32 value) +{ + return value == ~((u32)0) ? -EIO : ret; +} +static inline u32 xe_force_wake_control(const struct xe_force_wake_domain *domain, bool wake) +{ + return domain->mask | (wake ? domain->val : 0); +} +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_types.h index 14b7b86e80..4e889e500a 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_force_wake_types.h @@ -11,78 +11,7 @@ #include "regs/xe_reg_defs.h" -enum xe_force_wake_domain_id { - XE_FW_DOMAIN_ID_GT = 0, - XE_FW_DOMAIN_ID_RENDER, - XE_FW_DOMAIN_ID_MEDIA, - XE_FW_DOMAIN_ID_MEDIA_VDBOX0, - XE_FW_DOMAIN_ID_MEDIA_VDBOX1, - XE_FW_DOMAIN_ID_MEDIA_VDBOX2, - XE_FW_DOMAIN_ID_MEDIA_VDBOX3, - XE_FW_DOMAIN_ID_MEDIA_VDBOX4, - XE_FW_DOMAIN_ID_MEDIA_VDBOX5, - XE_FW_DOMAIN_ID_MEDIA_VDBOX6, - XE_FW_DOMAIN_ID_MEDIA_VDBOX7, - XE_FW_DOMAIN_ID_MEDIA_VEBOX0, - XE_FW_DOMAIN_ID_MEDIA_VEBOX1, - XE_FW_DOMAIN_ID_MEDIA_VEBOX2, - XE_FW_DOMAIN_ID_MEDIA_VEBOX3, - XE_FW_DOMAIN_ID_GSC, - XE_FW_DOMAIN_ID_COUNT -}; - -enum xe_force_wake_domains { - XE_FW_GT = BIT(XE_FW_DOMAIN_ID_GT), - XE_FW_RENDER = BIT(XE_FW_DOMAIN_ID_RENDER), - XE_FW_MEDIA = BIT(XE_FW_DOMAIN_ID_MEDIA), - XE_FW_MEDIA_VDBOX0 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX0), - XE_FW_MEDIA_VDBOX1 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX1), - XE_FW_MEDIA_VDBOX2 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX2), - XE_FW_MEDIA_VDBOX3 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX3), - XE_FW_MEDIA_VDBOX4 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX4), - XE_FW_MEDIA_VDBOX5 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX5), - XE_FW_MEDIA_VDBOX6 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX6), - XE_FW_MEDIA_VDBOX7 = BIT(XE_FW_DOMAIN_ID_MEDIA_VDBOX7), - XE_FW_MEDIA_VEBOX0 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX0), - XE_FW_MEDIA_VEBOX1 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX1), - XE_FW_MEDIA_VEBOX2 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX2), - XE_FW_MEDIA_VEBOX3 = BIT(XE_FW_DOMAIN_ID_MEDIA_VEBOX3), - XE_FW_GSC = BIT(XE_FW_DOMAIN_ID_GSC), - XE_FORCEWAKE_ALL = BIT(XE_FW_DOMAIN_ID_COUNT) -}; - -/** - * struct xe_force_wake_domain - Xe force wake power domain - * - * Represents an individual device-internal power domain. The driver must - * ensure the power domain is awake before accessing registers or other - * hardware functionality that is part of the power domain. Since different - * driver threads may access hardware units simultaneously, a reference count - * is used to ensure that the domain remains awake as long as any software - * is using the part of the hardware covered by the power domain. - * - * Hardware provides a register interface to allow the driver to request - * wake/sleep of power domains, although in most cases the actual action of - * powering the hardware up/down is handled by firmware (and may be subject to - * requirements and constraints outside of the driver's visibility) so the - * driver needs to wait for an acknowledgment that a wake request has been - * acted upon before accessing the parts of the hardware that reside within the - * power domain. - */ -struct xe_force_wake_domain { - /** @id: domain force wake id */ - enum xe_force_wake_domain_id id; - /** @reg_ctl: domain wake control register address */ - struct xe_reg reg_ctl; - /** @reg_ack: domain ack register address */ - struct xe_reg reg_ack; - /** @val: domain wake write value */ - u32 val; - /** @mask: domain mask */ - u32 mask; - /** @ref: domain reference */ - u32 ref; -}; +#include "xe_force_wake_domain_types.h" /** * struct xe_force_wake - Xe force wake collection diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt.c b/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt.c index a351c578b1..fee6f588e4 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt.c @@ -171,13 +171,16 @@ static u64 xelpg_ggtt_pte_flags(struct xe_bo *bo, u16 pat_index) return pte; } +#define XE_GGTT_PROBE_ASSERT(context, condition) \ + xe_tile_assert(((struct xe_ggtt *)(context))->tile, condition) +#include "xe_ggtt_probe_core.h" + static unsigned int probe_gsm_size(struct pci_dev *pdev) { - u16 gmch_ctl, ggms; + u16 gmch_ctl; pci_read_config_word(pdev, SNB_GMCH_CTRL, &gmch_ctl); - ggms = (gmch_ctl >> BDW_GMCH_GGMS_SHIFT) & BDW_GMCH_GGMS_MASK; - return ggms ? SZ_1M << ggms : 0; + return xe_ggtt_probe_gsm_decode(gmch_ctl); } static void ggtt_update_access_counter(struct xe_ggtt *ggtt) @@ -251,10 +254,7 @@ static void xe_ggtt_set_pte_and_flush(struct xe_ggtt *ggtt, u64 addr, u64 pte) static u64 xe_ggtt_get_pte(struct xe_ggtt *ggtt, u64 addr) { - xe_tile_assert(ggtt->tile, !(addr & XE_PTE_MASK)); - xe_tile_assert(ggtt->tile, addr < ggtt->start + ggtt->size); - - return readq(&ggtt->gsm[addr >> XE_PTE_SHIFT]); + return readq(&ggtt->gsm[xe_ggtt_probe_pte_index(ggtt, ggtt->start, ggtt->size, addr)]); } static void xe_ggtt_clear(struct xe_ggtt *ggtt, u64 start, u64 size) @@ -397,7 +397,7 @@ int xe_ggtt_init_early(struct xe_ggtt *ggtt) int err; if (!IS_SRIOV_VF(xe)) { - if (GRAPHICS_VERx100(xe) >= 1250) + if (xe_ggtt_probe_fixed_gsm(GRAPHICS_VERx100(xe))) gsm_size = SZ_8M; /* GGTT is expected to be 4GiB */ else gsm_size = probe_gsm_size(pdev); @@ -405,8 +405,7 @@ int xe_ggtt_init_early(struct xe_ggtt *ggtt) xe_tile_err(ggtt->tile, "Hardware reported no preallocated GSM\n"); return -ENOMEM; } - ggtt_start = wopcm; - ggtt_size = (gsm_size / 8) * (u64)XE_PAGE_SIZE - ggtt_start; + xe_ggtt_probe_pf_range(gsm_size, wopcm, &ggtt_start, &ggtt_size); } else { ggtt_start = xe_tile_sriov_vf_ggtt_base(ggtt->tile); ggtt_size = xe_tile_sriov_vf_ggtt(ggtt->tile); @@ -419,12 +418,11 @@ int xe_ggtt_init_early(struct xe_ggtt *ggtt) } } - ggtt->gsm = ggtt->tile->mmio.regs + SZ_8M; + ggtt->gsm = ggtt->tile->mmio.regs + xe_ggtt_probe_gsm_offset(); if (IS_DGFX(xe) && xe->info.vram_flags & XE_VRAM_FLAGS_NEED64K) ggtt->flags |= XE_GGTT_FLAGS_64K; - if (ggtt_size + ggtt_start > GUC_GGTT_TOP) - ggtt_size = GUC_GGTT_TOP - ggtt_start; + xe_ggtt_probe_clamp_range(ggtt_start, &ggtt_size); if (GRAPHICS_VERx100(xe) >= 1270) ggtt->pt_ops = diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt_probe_core.h b/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt_probe_core.h new file mode 100644 index 0000000000..56ee1f3119 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_ggtt_probe_core.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2021 Intel Corporation */ +#ifndef XE_GGTT_PROBE_CORE_H +#define XE_GGTT_PROBE_CORE_H +#ifndef XE_GGTT_PROBE_ASSERT +#error "GGTT probe requires the real caller's invariant binding" +#endif +/* Original PF geometry and PTE index policies. No allocation, ONLINE state, + * mappings, write, scratch, invalidation, PAT or firmware readiness exists. */ +static unsigned int xe_ggtt_probe_gsm_decode(u16 gmch_ctl) +{ + u16 ggms; + + ggms = (gmch_ctl >> BDW_GMCH_GGMS_SHIFT) & BDW_GMCH_GGMS_MASK; + return ggms ? SZ_1M << ggms : 0; +} +static bool xe_ggtt_probe_fixed_gsm(u32 graphics_verx100) +{ + return graphics_verx100 >= 1250; +} +static u64 xe_ggtt_probe_gsm_offset(void) +{ + return SZ_8M; +} +static void xe_ggtt_probe_pf_range(unsigned int gsm_size, u64 wopcm, + u64 *ggtt_start, u64 *ggtt_size) +{ + *ggtt_start = wopcm; + *ggtt_size = (gsm_size / 8) * (u64)XE_PAGE_SIZE - *ggtt_start; +} +static void xe_ggtt_probe_clamp_range(u64 ggtt_start, u64 *ggtt_size) +{ + if (*ggtt_size + ggtt_start > GUC_GGTT_TOP) + *ggtt_size = GUC_GGTT_TOP - ggtt_start; +} +static u64 xe_ggtt_probe_pte_index(void *context, u64 start, u64 size, u64 addr) +{ + XE_GGTT_PROBE_ASSERT(context, !(addr & XE_PTE_MASK)); + XE_GGTT_PROBE_ASSERT(context, addr < start + size); + + return addr >> XE_PTE_SHIFT; +} +#undef XE_GGTT_PROBE_ASSERT +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_gt_type.h b/crates/stela-drivers/src/gpu/intel/xe/xe_gt_type.h new file mode 100644 index 0000000000..3cd1f6919d --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_gt_type.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2022-2023 Intel Corporation + */ +#ifndef XE_GT_TYPE_H +#define XE_GT_TYPE_H +enum xe_gt_type { + XE_GT_TYPE_UNINITIALIZED, + XE_GT_TYPE_MAIN, + XE_GT_TYPE_MEDIA, +}; +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_gt_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_gt_types.h index e5588c8880..f9c0ab5235 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_gt_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_gt_types.h @@ -24,11 +24,7 @@ struct xe_exec_queue_ops; struct xe_migrate; struct xe_ring_ops; -enum xe_gt_type { - XE_GT_TYPE_UNINITIALIZED, - XE_GT_TYPE_MAIN, - XE_GT_TYPE_MEDIA, -}; +#include "xe_gt_type.h" enum xe_gt_eu_type { XE_GT_EU_TYPE_SIMD8, diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_guc.c b/crates/stela-drivers/src/gpu/intel/xe/xe_guc.c index 4023700ff2..33e5778cbe 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_guc.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_guc.c @@ -925,77 +925,29 @@ int xe_guc_post_load_init(struct xe_guc *guc) return xe_guc_submit_enable(guc); } -/* - * Wa_14025883347: Prevent GuC firmware DMA failures during GuC-only reset by ensuring - * SRAM save/restore operations are complete before reset. - */ -static void guc_prevent_fw_dma_failure_on_reset(struct xe_guc *guc) -{ - struct xe_gt *gt = guc_to_gt(guc); - u32 boot_hash_chk, guc_status, sram_status; - int ret; - - guc_status = xe_mmio_read32(>->mmio, GUC_STATUS); - if (guc_status & GS_MIA_IN_RESET) - return; - - boot_hash_chk = xe_mmio_read32(>->mmio, BOOT_HASH_CHK); - if (!(boot_hash_chk & GUC_BOOT_UKERNEL_VALID)) - return; - - /* Disable idle flow during reset (GuC reset re-enables it automatically) */ - xe_mmio_rmw32(>->mmio, GUC_MAX_IDLE_COUNT, 0, GUC_IDLE_FLOW_DISABLE); - - ret = xe_mmio_wait32(>->mmio, GUC_STATUS, GS_UKERNEL_MASK, - FIELD_PREP(GS_UKERNEL_MASK, XE_GUC_LOAD_STATUS_READY), - 100000, &guc_status, false); - if (ret) - xe_gt_warn(gt, "GuC not ready after disabling idle flow (GUC_STATUS: 0x%x)\n", - guc_status); - - ret = xe_mmio_wait32(>->mmio, GUC_SRAM_STATUS, GUC_SRAM_HANDLING_MASK, - 0, 5000, &sram_status, false); - if (ret) - xe_gt_warn(gt, "SRAM handling not complete (GUC_SRAM_STATUS: 0x%x)\n", - sram_status); -} +#define XE_GUC_RESET_CONTEXT struct xe_guc +#define XE_GUC_RESET_READ(guc, reg) xe_mmio_read32(&guc_to_gt(guc)->mmio, reg) +#define XE_GUC_RESET_RMW(guc, reg, clear, set) xe_mmio_rmw32(&guc_to_gt(guc)->mmio, reg, clear, set) +#define XE_GUC_RESET_WRITE(guc, reg, value) xe_mmio_write32(&guc_to_gt(guc)->mmio, reg, value) +#define XE_GUC_RESET_WAIT(guc, reg, mask, value, timeout, out, atomic) \ + xe_mmio_wait32(&guc_to_gt(guc)->mmio, reg, mask, value, timeout, out, atomic) +#define XE_GUC_RESET_ASSERT_HELD(guc) xe_force_wake_assert_held(gt_to_fw(guc_to_gt(guc)), XE_FW_GT) +#define XE_GUC_RESET_IS_VF(guc) IS_SRIOV_VF(gt_to_xe(guc_to_gt(guc))) +#define XE_GUC_RESET_VF_BOOTSTRAP(guc) xe_gt_sriov_vf_bootstrap(guc_to_gt(guc)) +#define XE_GUC_RESET_WA_14025883347(guc) XE_GT_WA(guc_to_gt(guc), 14025883347) +#define XE_GUC_RESET_WARN_READY(guc, value) \ + xe_gt_warn(guc_to_gt(guc), "GuC not ready after disabling idle flow (GUC_STATUS: 0x%x)\n", value) +#define XE_GUC_RESET_WARN_SRAM(guc, value) \ + xe_gt_warn(guc_to_gt(guc), "SRAM handling not complete (GUC_SRAM_STATUS: 0x%x)\n", value) +#define XE_GUC_RESET_ERROR_TIMEOUT(guc, value) \ + xe_gt_err(guc_to_gt(guc), "GuC reset timed out, GDRST=%#x\n", value) +#define XE_GUC_RESET_ERROR_STATUS(guc, value) \ + xe_gt_err(guc_to_gt(guc), "GuC status: %#x, MIA core expected to be in reset\n", value) +#include "xe_guc_reset_core.h" int xe_guc_reset(struct xe_guc *guc) { - struct xe_gt *gt = guc_to_gt(guc); - struct xe_mmio *mmio = >->mmio; - u32 guc_status, gdrst; - int ret; - - xe_force_wake_assert_held(gt_to_fw(gt), XE_FW_GT); - - if (IS_SRIOV_VF(gt_to_xe(gt))) - return xe_gt_sriov_vf_bootstrap(gt); - - if (XE_GT_WA(gt, 14025883347)) - guc_prevent_fw_dma_failure_on_reset(guc); - - xe_mmio_write32(mmio, GDRST, GRDOM_GUC); - - ret = xe_mmio_wait32(mmio, GDRST, GRDOM_GUC, 0, 5000, &gdrst, false); - if (ret) { - xe_gt_err(gt, "GuC reset timed out, GDRST=%#x\n", gdrst); - goto err_out; - } - - guc_status = xe_mmio_read32(mmio, GUC_STATUS); - if (!(guc_status & GS_MIA_IN_RESET)) { - xe_gt_err(gt, "GuC status: %#x, MIA core expected to be in reset\n", - guc_status); - ret = -EIO; - goto err_out; - } - - return 0; - -err_out: - - return ret; + return xe_guc_reset_core(guc); } static void guc_prepare_xfer(struct xe_guc *guc) diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_guc.h b/crates/stela-drivers/src/gpu/intel/xe/xe_guc.h index 02514914f4..d4f42cf548 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_guc.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_guc.h @@ -11,13 +11,7 @@ #include "xe_hw_engine_types.h" #include "xe_macros.h" -/* - * GuC version number components are defined to be only 8-bit size, - * so converting to a 32bit 8.8.8 integer allows simple (and safe) - * numerical comparisons. - */ -#define MAKE_GUC_VER(maj, min, pat) (((maj) << 16) | ((min) << 8) | (pat)) -#define MAKE_GUC_VER_STRUCT(ver) MAKE_GUC_VER((ver).major, (ver).minor, (ver).patch) +#include "xe_uc_fw_version.h" #define MAKE_GUC_VER_ARGS(ver...) \ (BUILD_BUG_ON_ZERO(COUNT_ARGS(ver) < 2 || COUNT_ARGS(ver) > 3) + \ MAKE_GUC_VER(PICK_ARG1(ver), PICK_ARG2(ver), IF_ARGS(PICK_ARG3(ver), 0, PICK_ARG3(ver)))) diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_guc_reset_core.h b/crates/stela-drivers/src/gpu/intel/xe/xe_guc_reset_core.h new file mode 100644 index 0000000000..e01f24224f --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_guc_reset_core.h @@ -0,0 +1,129 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_GUC_RESET_CORE_H +#define XE_GUC_RESET_CORE_H +/* Whole original GuC reset/SRAM policy. Every binding is mandatory; includers + * retain the actual forcewake, VF/WA selection, ordered I/O, poll and diagnostics. + * This does not sanitize software state or establish whole-device quiescence. */ +#ifndef XE_GUC_RESET_CONTEXT +#error "GuC reset requires XE_GUC_RESET_CONTEXT" +#endif +#ifndef XE_GUC_RESET_READ +#error "GuC reset requires XE_GUC_RESET_READ" +#endif +#ifndef XE_GUC_RESET_RMW +#error "GuC reset requires XE_GUC_RESET_RMW" +#endif +#ifndef XE_GUC_RESET_WRITE +#error "GuC reset requires XE_GUC_RESET_WRITE" +#endif +#ifndef XE_GUC_RESET_WAIT +#error "GuC reset requires XE_GUC_RESET_WAIT" +#endif +#ifndef XE_GUC_RESET_ASSERT_HELD +#error "GuC reset requires XE_GUC_RESET_ASSERT_HELD" +#endif +#ifndef XE_GUC_RESET_IS_VF +#error "GuC reset requires XE_GUC_RESET_IS_VF" +#endif +#ifndef XE_GUC_RESET_VF_BOOTSTRAP +#error "GuC reset requires XE_GUC_RESET_VF_BOOTSTRAP" +#endif +#ifndef XE_GUC_RESET_WA_14025883347 +#error "GuC reset requires XE_GUC_RESET_WA_14025883347" +#endif +#ifndef XE_GUC_RESET_WARN_READY +#error "GuC reset requires XE_GUC_RESET_WARN_READY" +#endif +#ifndef XE_GUC_RESET_WARN_SRAM +#error "GuC reset requires XE_GUC_RESET_WARN_SRAM" +#endif +#ifndef XE_GUC_RESET_ERROR_TIMEOUT +#error "GuC reset requires XE_GUC_RESET_ERROR_TIMEOUT" +#endif +#ifndef XE_GUC_RESET_ERROR_STATUS +#error "GuC reset requires XE_GUC_RESET_ERROR_STATUS" +#endif +/* + * Wa_14025883347: Prevent GuC firmware DMA failures during GuC-only reset by ensuring + * SRAM save/restore operations are complete before reset. + */ +static inline void xe_guc_reset_prevent_fw_dma_failure(XE_GUC_RESET_CONTEXT *context) +{ + u32 boot_hash_chk, guc_status, sram_status; + int ret; + + guc_status = XE_GUC_RESET_READ(context, GUC_STATUS); + if (guc_status & GS_MIA_IN_RESET) + return; + + boot_hash_chk = XE_GUC_RESET_READ(context, BOOT_HASH_CHK); + if (!(boot_hash_chk & GUC_BOOT_UKERNEL_VALID)) + return; + + /* Disable idle flow during reset (GuC reset re-enables it automatically) */ + XE_GUC_RESET_RMW(context, GUC_MAX_IDLE_COUNT, 0, GUC_IDLE_FLOW_DISABLE); + + ret = XE_GUC_RESET_WAIT(context, GUC_STATUS, GS_UKERNEL_MASK, + FIELD_PREP(GS_UKERNEL_MASK, XE_GUC_LOAD_STATUS_READY), + 100000, &guc_status, false); + if (ret) + XE_GUC_RESET_WARN_READY(context, guc_status); + + ret = XE_GUC_RESET_WAIT(context, GUC_SRAM_STATUS, GUC_SRAM_HANDLING_MASK, + 0, 5000, &sram_status, false); + if (ret) + XE_GUC_RESET_WARN_SRAM(context, sram_status); +} + +static inline int xe_guc_reset_core(XE_GUC_RESET_CONTEXT *context) +{ + u32 guc_status, gdrst; + int ret; + + XE_GUC_RESET_ASSERT_HELD(context); + + if (XE_GUC_RESET_IS_VF(context)) + return XE_GUC_RESET_VF_BOOTSTRAP(context); + + if (XE_GUC_RESET_WA_14025883347(context)) + xe_guc_reset_prevent_fw_dma_failure(context); + + XE_GUC_RESET_WRITE(context, GDRST, GRDOM_GUC); + + ret = XE_GUC_RESET_WAIT(context, GDRST, GRDOM_GUC, 0, 5000, &gdrst, false); + if (ret) { + XE_GUC_RESET_ERROR_TIMEOUT(context, gdrst); + goto err_out; + } + + guc_status = XE_GUC_RESET_READ(context, GUC_STATUS); + if (!(guc_status & GS_MIA_IN_RESET)) { + XE_GUC_RESET_ERROR_STATUS(context, guc_status); + ret = -EIO; + goto err_out; + } + + return 0; + +err_out: + + return ret; +} + +#undef XE_GUC_RESET_CONTEXT +#undef XE_GUC_RESET_READ +#undef XE_GUC_RESET_RMW +#undef XE_GUC_RESET_WRITE +#undef XE_GUC_RESET_WAIT +#undef XE_GUC_RESET_ASSERT_HELD +#undef XE_GUC_RESET_IS_VF +#undef XE_GUC_RESET_VF_BOOTSTRAP +#undef XE_GUC_RESET_WA_14025883347 +#undef XE_GUC_RESET_WARN_READY +#undef XE_GUC_RESET_WARN_SRAM +#undef XE_GUC_RESET_ERROR_TIMEOUT +#undef XE_GUC_RESET_ERROR_STATUS +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_huc.c b/crates/stela-drivers/src/gpu/intel/xe/xe_huc.c index 57afe21444..f7a2eeb054 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_huc.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_huc.c @@ -4,6 +4,7 @@ */ #include "xe_huc.h" +#include "xe_huc_role.h" #include @@ -76,7 +77,7 @@ int xe_huc_init(struct xe_huc *huc) * no separate GT for media IP, so the HuC was part of the primary * GT. Such platforms have graphics versions 12.55 and earlier. */ - if (!xe_gt_is_media_type(gt) && GRAPHICS_VERx100(xe) > 1255) { + if (xe_huc_role_unsupported(xe_gt_is_media_type(gt), GRAPHICS_VERx100(xe))) { xe_uc_fw_change_status(&huc->fw, XE_UC_FIRMWARE_NOT_SUPPORTED); return 0; } diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_huc_role.h b/crates/stela-drivers/src/gpu/intel/xe/xe_huc_role.h new file mode 100644 index 0000000000..4c2bc05e09 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_huc_role.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_HUC_ROLE_H +#define XE_HUC_ROLE_H +/* Original xe_huc_init no-main-GT-HuC rule, not missing-firmware policy. */ +static inline bool xe_huc_role_unsupported(bool media_gt, unsigned graphics_verx100) +{ + return !media_gt && graphics_verx100 > 1255; +} +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_hw_engine_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_hw_engine_types.h index 84c097da9b..a5e692a011 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_hw_engine_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_hw_engine_types.h @@ -11,52 +11,7 @@ #include "xe_reg_sr_types.h" /* See "Engine ID Definition" struct in the Icelake PRM */ -enum xe_engine_class { - XE_ENGINE_CLASS_RENDER = 0, - XE_ENGINE_CLASS_VIDEO_DECODE = 1, - XE_ENGINE_CLASS_VIDEO_ENHANCE = 2, - XE_ENGINE_CLASS_COPY = 3, - XE_ENGINE_CLASS_OTHER = 4, - XE_ENGINE_CLASS_COMPUTE = 5, - XE_ENGINE_CLASS_MAX = 6, -}; - -enum xe_hw_engine_id { - XE_HW_ENGINE_RCS0, -#define XE_HW_ENGINE_RCS_MASK GENMASK_ULL(XE_HW_ENGINE_RCS0, XE_HW_ENGINE_RCS0) - XE_HW_ENGINE_BCS0, - XE_HW_ENGINE_BCS1, - XE_HW_ENGINE_BCS2, - XE_HW_ENGINE_BCS3, - XE_HW_ENGINE_BCS4, - XE_HW_ENGINE_BCS5, - XE_HW_ENGINE_BCS6, - XE_HW_ENGINE_BCS7, - XE_HW_ENGINE_BCS8, -#define XE_HW_ENGINE_BCS_MASK GENMASK_ULL(XE_HW_ENGINE_BCS8, XE_HW_ENGINE_BCS0) - XE_HW_ENGINE_VCS0, - XE_HW_ENGINE_VCS1, - XE_HW_ENGINE_VCS2, - XE_HW_ENGINE_VCS3, - XE_HW_ENGINE_VCS4, - XE_HW_ENGINE_VCS5, - XE_HW_ENGINE_VCS6, - XE_HW_ENGINE_VCS7, -#define XE_HW_ENGINE_VCS_MASK GENMASK_ULL(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) - XE_HW_ENGINE_VECS0, - XE_HW_ENGINE_VECS1, - XE_HW_ENGINE_VECS2, - XE_HW_ENGINE_VECS3, -#define XE_HW_ENGINE_VECS_MASK GENMASK_ULL(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0) - XE_HW_ENGINE_CCS0, - XE_HW_ENGINE_CCS1, - XE_HW_ENGINE_CCS2, - XE_HW_ENGINE_CCS3, -#define XE_HW_ENGINE_CCS_MASK GENMASK_ULL(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0) - XE_HW_ENGINE_GSCCS0, -#define XE_HW_ENGINE_GSCCS_MASK GENMASK_ULL(XE_HW_ENGINE_GSCCS0, XE_HW_ENGINE_GSCCS0) - XE_NUM_HW_ENGINES, -}; +#include "xe_engine_ids.h" /* FIXME: s/XE_HW_ENGINE_MAX_INSTANCE/XE_HW_ENGINE_MAX_COUNT */ #define XE_HW_ENGINE_MAX_INSTANCE 9 diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_mmio.c b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio.c index 78adb303b6..d64970bcac 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_mmio.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio.c @@ -218,15 +218,16 @@ u32 xe_mmio_rmw32(struct xe_mmio *mmio, struct xe_reg reg, u32 clr, u32 set) return old; } +#define XE_MMIO_VERIFY_NAME xe_mmio_verify_core +#define XE_MMIO_VERIFY_CONTEXT struct xe_mmio +#define XE_MMIO_VERIFY_WRITE xe_mmio_write32 +#define XE_MMIO_VERIFY_READ xe_mmio_read32 +#include "xe_mmio_verify.h" + int xe_mmio_write32_and_verify(struct xe_mmio *mmio, struct xe_reg reg, u32 val, u32 mask, u32 eval) { - u32 reg_val; - - xe_mmio_write32(mmio, reg, val); - reg_val = xe_mmio_read32(mmio, reg); - - return (reg_val & mask) != eval ? -EINVAL : 0; + return xe_mmio_verify_core(mmio, reg, val, mask, eval); } bool xe_mmio_in_range(const struct xe_mmio *mmio, @@ -288,58 +289,27 @@ u64 xe_mmio_read64_2x32(struct xe_mmio *mmio, struct xe_reg reg) return (u64)udw << 32 | ldw; } -static int __xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u32 val, - u32 timeout_us, u32 *out_val, bool atomic, bool expect_match) -{ - ktime_t cur = ktime_get_raw(); - const ktime_t end = ktime_add_us(cur, timeout_us); - int ret = -ETIMEDOUT; - s64 wait = 10; - u32 read; - bool check; - - for (;;) { - read = xe_mmio_read32(mmio, reg); - - check = (read & mask) == val; - if (!expect_match) - check = !check; - - if (check) { - ret = 0; - break; - } - - cur = ktime_get_raw(); - if (!ktime_before(cur, end)) - break; - - if (ktime_after(ktime_add_us(cur, wait), end)) - wait = ktime_us_delta(end, cur); - - if (atomic) - udelay(wait); - else - usleep_range(wait, wait << 1); - wait <<= 1; - } - - if (ret != 0) { - read = xe_mmio_read32(mmio, reg); - - check = (read & mask) == val; - if (!expect_match) - check = !check; - - if (check) - ret = 0; - } - - if (out_val) - *out_val = read; - - return ret; -} +#define XE_MMIO_POLL_NAME __xe_mmio_wait32 +#define XE_MMIO_POLL_CONTEXT struct xe_mmio +#define XE_MMIO_POLL_TIME ktime_t +#define XE_MMIO_POLL_NOW(mmio) ktime_get_raw() +#define XE_MMIO_POLL_ADD_US ktime_add_us +#define XE_MMIO_POLL_READ xe_mmio_read32 +#define XE_MMIO_POLL_BEFORE ktime_before +#define XE_MMIO_POLL_AFTER ktime_after +#define XE_MMIO_POLL_DELTA_US ktime_us_delta +#define XE_MMIO_POLL_DELAY(mmio, wait, atomic) do { if (atomic) udelay(wait); else usleep_range(wait, (wait) << 1); } while (0) +#include "xe_mmio_poll.h" +#undef XE_MMIO_POLL_NAME +#undef XE_MMIO_POLL_CONTEXT +#undef XE_MMIO_POLL_TIME +#undef XE_MMIO_POLL_NOW +#undef XE_MMIO_POLL_ADD_US +#undef XE_MMIO_POLL_READ +#undef XE_MMIO_POLL_BEFORE +#undef XE_MMIO_POLL_AFTER +#undef XE_MMIO_POLL_DELTA_US +#undef XE_MMIO_POLL_DELAY /** * xe_mmio_wait32() - Wait for a register to match the desired masked value diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_poll.h b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_poll.h new file mode 100644 index 0000000000..3cf1c9c588 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_poll.h @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2021-2023 Intel Corporation + */ +/* Original masked/deadline/final-reread algorithm; includer binds actual I/O/time. */ +static int XE_MMIO_POLL_NAME(XE_MMIO_POLL_CONTEXT *mmio, struct xe_reg reg, u32 mask, u32 val, + u32 timeout_us, u32 *out_val, bool atomic, bool expect_match) +{ + XE_MMIO_POLL_TIME cur = XE_MMIO_POLL_NOW(mmio); + const XE_MMIO_POLL_TIME end = XE_MMIO_POLL_ADD_US(cur, timeout_us); + int ret = -ETIMEDOUT; + s64 wait = 10; + u32 read; + bool check; + + for (;;) { + read = XE_MMIO_POLL_READ(mmio, reg); + + check = (read & mask) == val; + if (!expect_match) + check = !check; + + if (check) { + ret = 0; + break; + } + + cur = XE_MMIO_POLL_NOW(mmio); + if (!XE_MMIO_POLL_BEFORE(cur, end)) + break; + + if (XE_MMIO_POLL_AFTER(XE_MMIO_POLL_ADD_US(cur, wait), end)) + wait = XE_MMIO_POLL_DELTA_US(end, cur); + + if (atomic) + XE_MMIO_POLL_DELAY(mmio, wait, true); + else + XE_MMIO_POLL_DELAY(mmio, wait, false); + wait <<= 1; + } + + if (ret != 0) { + read = XE_MMIO_POLL_READ(mmio, reg); + + check = (read & mask) == val; + if (!expect_match) + check = !check; + + if (check) + ret = 0; + } + + if (out_val) + *out_val = read; + + return ret; +} diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_verify.h b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_verify.h new file mode 100644 index 0000000000..9717b93a4b --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_mmio_verify.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2021-2023 Intel Corporation */ +/* Required compile-time bindings, no fallback access operations. */ +#if !defined(XE_MMIO_VERIFY_NAME) || !defined(XE_MMIO_VERIFY_CONTEXT) || \ + !defined(XE_MMIO_VERIFY_WRITE) || !defined(XE_MMIO_VERIFY_READ) +#error "MMIO verification requires actual read/write context bindings" +#endif +static int XE_MMIO_VERIFY_NAME(XE_MMIO_VERIFY_CONTEXT *mmio, + struct xe_reg reg, u32 val, u32 mask, u32 eval) +{ + u32 reg_val; + + XE_MMIO_VERIFY_WRITE(mmio, reg, val); + reg_val = XE_MMIO_VERIFY_READ(mmio, reg); + + return (reg_val & mask) != eval ? -EINVAL : 0; +} +#undef XE_MMIO_VERIFY_NAME +#undef XE_MMIO_VERIFY_CONTEXT +#undef XE_MMIO_VERIFY_WRITE +#undef XE_MMIO_VERIFY_READ diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pat.c b/crates/stela-drivers/src/gpu/intel/xe/xe_pat.c index fad5b5a5ed..21265643b7 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_pat.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pat.c @@ -20,36 +20,7 @@ #include "xe_sriov.h" #include "xe_wa.h" -#define _PAT_ATS 0x47fc -#define _PAT_INDEX(index) _PICK_EVEN_2RANGES(index, 8, \ - 0x4800, 0x4804, \ - 0x4848, 0x484c) -#define _PAT_PTA 0x4820 - -#define XE2_NO_PROMOTE REG_BIT(10) -#define XE2_COMP_EN REG_BIT(9) -#define XE2_L3_CLOS REG_GENMASK(7, 6) -#define XE2_L3_POLICY REG_GENMASK(5, 4) -#define XE2_L4_POLICY REG_GENMASK(3, 2) -#define XE2_COH_MODE REG_GENMASK(1, 0) - -#define XELPG_L4_POLICY_MASK REG_GENMASK(3, 2) -#define XELPG_PAT_3_UC REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 3) -#define XELPG_PAT_1_WT REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 1) -#define XELPG_PAT_0_WB REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 0) -#define XELPG_INDEX_COH_MODE_MASK REG_GENMASK(1, 0) -#define XELPG_3_COH_2W REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 3) -#define XELPG_2_COH_1W REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 2) -#define XELPG_0_COH_NON REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 0) - -#define XEHPC_CLOS_LEVEL_MASK REG_GENMASK(3, 2) -#define XEHPC_PAT_CLOS(x) REG_FIELD_PREP(XEHPC_CLOS_LEVEL_MASK, x) - -#define XELP_MEM_TYPE_MASK REG_GENMASK(1, 0) -#define XELP_PAT_WB REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 3) -#define XELP_PAT_WT REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 2) -#define XELP_PAT_WC REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 1) -#define XELP_PAT_UC REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 0) +#include "xe_pat_tables.h" #define PAT_LABEL_LEN 20 @@ -91,206 +62,6 @@ struct xe_pat_ops { void (*entry_dump)(struct drm_printer *p, const char *label, u32 pat, bool rsvd); }; -static const struct xe_pat_table_entry xelp_pat_table[] = { - [0] = { XELP_PAT_WB, XE_COH_1WAY }, - [1] = { XELP_PAT_WC, XE_COH_NONE }, - [2] = { XELP_PAT_WT, XE_COH_NONE }, - [3] = { XELP_PAT_UC, XE_COH_NONE }, -}; - -static const struct xe_pat_table_entry xehpc_pat_table[] = { - [0] = { XELP_PAT_UC, XE_COH_NONE }, - [1] = { XELP_PAT_WC, XE_COH_NONE }, - [2] = { XELP_PAT_WT, XE_COH_NONE }, - [3] = { XELP_PAT_WB, XE_COH_1WAY }, - [4] = { XEHPC_PAT_CLOS(1) | XELP_PAT_WT, XE_COH_NONE }, - [5] = { XEHPC_PAT_CLOS(1) | XELP_PAT_WB, XE_COH_1WAY }, - [6] = { XEHPC_PAT_CLOS(2) | XELP_PAT_WT, XE_COH_NONE }, - [7] = { XEHPC_PAT_CLOS(2) | XELP_PAT_WB, XE_COH_1WAY }, -}; - -static const struct xe_pat_table_entry xelpg_pat_table[] = { - [0] = { XELPG_PAT_0_WB, XE_COH_NONE }, - [1] = { XELPG_PAT_1_WT, XE_COH_NONE }, - [2] = { XELPG_PAT_3_UC, XE_COH_NONE }, - [3] = { XELPG_PAT_0_WB | XELPG_2_COH_1W, XE_COH_1WAY }, - [4] = { XELPG_PAT_0_WB | XELPG_3_COH_2W, XE_COH_2WAY }, -}; - -/* - * The Xe2 table is getting large/complicated so it's easier to review if - * provided in a form that exactly matches the bspec's formatting. The meaning - * of the fields here are: - * - no_promote: 0=promotable, 1=no promote - * - comp_en: 0=disable, 1=enable - * - l3clos: L3 class of service (0-3) - * - l3_policy: 0=WB, 1=XD ("WB - Transient Display"), - * 2=XA ("WB - Transient App" for Xe3p), 3=UC - * - l4_policy: 0=WB, 1=WT, 3=UC - * - coh_mode: 0=no snoop, 2=1-way coherent, 3=2-way coherent - * - * Reserved entries should be programmed with the maximum caching, minimum - * coherency (which matches an all-0's encoding), so we can just omit them - * in the table. - * - * Note: There is an implicit assumption in the driver that compression and - * coh_1way+ are mutually exclusive for platforms prior to Xe3. Starting - * with Xe3, compression can be combined with coherency. If using compression - * with coherency, userptr and imported dma-buf from external device will - * have uncleared ccs state. See also xe_bo_needs_ccs_pages(). - */ -#define XE2_PAT(no_promote, comp_en, l3clos, l3_policy, l4_policy, __coh_mode) \ - { \ - .value = (no_promote ? XE2_NO_PROMOTE : 0) | \ - (comp_en ? XE2_COMP_EN : 0) | \ - REG_FIELD_PREP(XE2_L3_CLOS, l3clos) | \ - REG_FIELD_PREP(XE2_L3_POLICY, l3_policy) | \ - REG_FIELD_PREP(XE2_L4_POLICY, l4_policy) | \ - REG_FIELD_PREP(XE2_COH_MODE, __coh_mode), \ - .coh_mode = __coh_mode ? __coh_mode : XE_COH_NONE, \ - .valid = 1 \ - } - -static const struct xe_pat_table_entry xe2_pat_table[] = { - [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), - [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), - [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), - [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), - [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), - [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), - [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), - [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), - [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), - [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), - [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), - [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), - [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), - [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), - [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), - [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), - /* 16..19 are reserved; leave set to all 0's */ - [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), - [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), - [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), - [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), - [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), - [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), - [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), - [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), - [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), - [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), - [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), - [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), -}; - -static const struct xe_pat_table_entry xe3_lpg_pat_table[] = { - [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), - [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), - [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), - [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), - [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), - [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), - [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), - [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), - [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), - [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), - [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), - [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), - [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), - [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), - [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), - [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), - [16] = XE2_PAT( 0, 1, 0, 0, 3, 2 ), - /* 17..19 are reserved; leave set to all 0's */ - [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), - [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), - [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), - [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), - [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), - [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), - [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), - [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), - [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), - [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), - [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), - [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), -}; -/* Special PAT values programmed outside the main table */ -static const struct xe_pat_table_entry xe2_pat_ats = XE2_PAT( 0, 0, 0, 0, 3, 3 ); -static const struct xe_pat_table_entry xe2_pat_pta = XE2_PAT( 0, 0, 0, 0, 3, 0 ); - -/* - * Xe3p_XPC PAT table uses the same layout as Xe2/Xe3, except that there's no - * option for compression. Also note that the "L3" and "L4" register fields - * actually control L2 and L3 cache respectively on this platform. - */ -#define XE3P_XPC_PAT(no_promote, l3clos, l3_policy, l4_policy, __coh_mode) \ - XE2_PAT(no_promote, 0, l3clos, l3_policy, l4_policy, __coh_mode) - -static const struct xe_pat_table_entry xe3p_xpc_pat_ats = XE3P_XPC_PAT( 0, 0, 0, 0, 3 ); -static const struct xe_pat_table_entry xe3p_xpc_pat_pta = XE3P_XPC_PAT( 0, 0, 0, 0, 0 ); - -static const struct xe_pat_table_entry xe3p_xpc_pat_table[] = { - [ 0] = XE3P_XPC_PAT( 0, 0, 0, 0, 0 ), - [ 1] = XE3P_XPC_PAT( 0, 0, 0, 0, 2 ), - [ 2] = XE3P_XPC_PAT( 0, 0, 0, 0, 3 ), - [ 3] = XE3P_XPC_PAT( 0, 0, 3, 3, 0 ), - [ 4] = XE3P_XPC_PAT( 0, 0, 3, 3, 2 ), - [ 5] = XE3P_XPC_PAT( 0, 0, 3, 0, 0 ), - [ 6] = XE3P_XPC_PAT( 0, 0, 3, 0, 2 ), - [ 7] = XE3P_XPC_PAT( 0, 0, 3, 0, 3 ), - [ 8] = XE3P_XPC_PAT( 0, 0, 0, 3, 0 ), - [ 9] = XE3P_XPC_PAT( 0, 0, 0, 3, 2 ), - [10] = XE3P_XPC_PAT( 0, 0, 0, 3, 3 ), - /* 11..22 are reserved; leave set to all 0's */ - [23] = XE3P_XPC_PAT( 0, 1, 0, 0, 0 ), - [24] = XE3P_XPC_PAT( 0, 1, 0, 0, 2 ), - [25] = XE3P_XPC_PAT( 0, 1, 0, 0, 3 ), - [26] = XE3P_XPC_PAT( 0, 2, 0, 0, 0 ), - [27] = XE3P_XPC_PAT( 0, 2, 0, 0, 2 ), - [28] = XE3P_XPC_PAT( 0, 2, 0, 0, 3 ), - [29] = XE3P_XPC_PAT( 0, 3, 0, 0, 0 ), - [30] = XE3P_XPC_PAT( 0, 3, 0, 0, 2 ), - [31] = XE3P_XPC_PAT( 0, 3, 0, 0, 3 ), -}; - -static const struct xe_pat_table_entry xe3p_primary_pat_pta = XE2_PAT(0, 0, 0, 0, 0, 3); -static const struct xe_pat_table_entry xe3p_media_pat_pta = XE2_PAT(0, 0, 0, 0, 0, 2); - -static const struct xe_pat_table_entry xe3p_lpg_pat_table[] = { - [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), - [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), - [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), - [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), - [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), - [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), - [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), - [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), - [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), - [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), - [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), - [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), - [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), - [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), - [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), - [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), - [16] = XE2_PAT( 0, 1, 0, 0, 3, 2 ), - /* 17 is reserved; leave set to all 0's */ - [18] = XE2_PAT( 1, 0, 0, 2, 3, 0 ), - [19] = XE2_PAT( 1, 0, 0, 2, 3, 2 ), - [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), - [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), - [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), - [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), - [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), - [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), - [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), - [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), - [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), - [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), - [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), - [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), -}; u16 xe_pat_index_get_coh_mode(struct xe_device *xe, u16 pat_index) { @@ -325,23 +96,17 @@ static const struct xe_pat_table_entry *gt_pta_entry(struct xe_gt *gt) return NULL; } +#define XE_PAT_PROGRAM_WRITE(context, reg, value) \ + xe_mmio_write32(&((struct xe_gt *)(context))->mmio, reg, value) +#include "xe_pat_program.h" + static void program_pat(struct xe_gt *gt, const struct xe_pat_table_entry table[], int n_entries) { struct xe_device *xe = gt_to_xe(gt); const struct xe_pat_table_entry *pta_entry = gt_pta_entry(gt); - for (int i = 0; i < n_entries; i++) { - struct xe_reg reg = XE_REG(_PAT_INDEX(i)); - - xe_mmio_write32(>->mmio, reg, table[i].value); - } - - if (xe->pat.pat_ats) - xe_mmio_write32(>->mmio, XE_REG(_PAT_ATS), xe->pat.pat_ats->value); - - if (pta_entry) - xe_mmio_write32(>->mmio, XE_REG(_PAT_PTA), pta_entry->value); + xe_pat_program_direct(gt, table, n_entries, xe->pat.pat_ats, pta_entry); } static void program_pat_mcr(struct xe_gt *gt, const struct xe_pat_table_entry table[], @@ -556,103 +321,37 @@ static const struct xe_pat_ops xe3p_xpc_pat_ops = { .entry_dump = xe3p_xpc_pat_entry_dump, }; +#define XE_PAT_SELECT_WARN(context, condition) ((void)(context), WARN_ON_ONCE(condition)) +#define XE_PAT_SELECT_MISSING(context, version) \ + drm_err(&((struct xe_device *)(context))->drm, \ + "Missing PAT table for platform with graphics version %d.%02d!\n", \ + (int)((version) / 100), (int)((version) % 100)) +#include "xe_pat_select.h" + void xe_pat_init_early(struct xe_device *xe) { - xe->pat.idx[XE_CACHE_WB_COMPRESSION] = XE_PAT_INVALID_IDX; - xe->pat.idx[XE_CACHE_NONE_COMPRESSION] = XE_PAT_INVALID_IDX; - if (GRAPHICS_VERx100(xe) == 3511) { - xe->pat.ops = &xe3p_xpc_pat_ops; - xe->pat.table = xe3p_xpc_pat_table; - xe->pat.pat_ats = &xe3p_xpc_pat_ats; - xe->pat.pat_primary_pta = &xe3p_xpc_pat_pta; - xe->pat.pat_media_pta = &xe3p_xpc_pat_pta; - xe->pat.n_entries = ARRAY_SIZE(xe3p_xpc_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 3; - xe->pat.idx[XE_CACHE_WT] = 3; /* N/A (no display); use UC */ - xe->pat.idx[XE_CACHE_WB] = 2; - } else if (GRAPHICS_VER(xe) == 35) { - xe->pat.ops = &xe2_pat_ops; - xe->pat.table = xe3p_lpg_pat_table; - xe->pat.pat_ats = &xe2_pat_ats; - if (!IS_DGFX(xe)) { - xe->pat.pat_primary_pta = &xe3p_primary_pat_pta; - xe->pat.pat_media_pta = &xe3p_media_pat_pta; - } - xe->pat.n_entries = ARRAY_SIZE(xe3p_lpg_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 3; - xe->pat.idx[XE_CACHE_WT] = 15; - xe->pat.idx[XE_CACHE_WB] = 2; - xe->pat.idx[XE_CACHE_NONE_COMPRESSION] = 12; - xe->pat.idx[XE_CACHE_WB_COMPRESSION] = 16; - } else if (GRAPHICS_VER(xe) == 30 || GRAPHICS_VER(xe) == 20) { - xe->pat.ops = &xe2_pat_ops; - if (GRAPHICS_VER(xe) == 30) { - xe->pat.table = xe3_lpg_pat_table; - xe->pat.idx[XE_CACHE_WB_COMPRESSION] = 16; - } else { - xe->pat.table = xe2_pat_table; - } - xe->pat.pat_ats = &xe2_pat_ats; - if (IS_DGFX(xe)) { - xe->pat.pat_primary_pta = &xe2_pat_pta; - xe->pat.pat_media_pta = &xe2_pat_pta; - } - - /* Wa_16023588340. XXX: Should use XE_WA */ - if (GRAPHICS_VERx100(xe) == 2001) - xe->pat.n_entries = 28; /* Disable CLOS3 */ - else - xe->pat.n_entries = ARRAY_SIZE(xe2_pat_table); - - xe->pat.idx[XE_CACHE_NONE] = 3; - xe->pat.idx[XE_CACHE_WT] = 15; - xe->pat.idx[XE_CACHE_WB] = 2; - xe->pat.idx[XE_CACHE_NONE_COMPRESSION] = 12; /*Applicable on xe2 and beyond */ - } else if (xe->info.platform == XE_METEORLAKE) { - xe->pat.ops = &xelpg_pat_ops; - xe->pat.table = xelpg_pat_table; - xe->pat.n_entries = ARRAY_SIZE(xelpg_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 2; - xe->pat.idx[XE_CACHE_WT] = 1; - xe->pat.idx[XE_CACHE_WB] = 3; - } else if (xe->info.platform == XE_PVC) { - xe->pat.ops = &xehpc_pat_ops; - xe->pat.table = xehpc_pat_table; - xe->pat.n_entries = ARRAY_SIZE(xehpc_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 0; - xe->pat.idx[XE_CACHE_WT] = 2; - xe->pat.idx[XE_CACHE_WB] = 3; - } else if (xe->info.platform == XE_DG2) { - /* - * Table is the same as previous platforms, but programming - * method has changed. - */ - xe->pat.ops = &xehp_pat_ops; - xe->pat.table = xelp_pat_table; - xe->pat.n_entries = ARRAY_SIZE(xelp_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 3; - xe->pat.idx[XE_CACHE_WT] = 2; - xe->pat.idx[XE_CACHE_WB] = 0; - } else if (GRAPHICS_VERx100(xe) <= 1210) { - WARN_ON_ONCE(!IS_DGFX(xe) && !xe->info.has_llc); - xe->pat.ops = &xelp_pat_ops; - xe->pat.table = xelp_pat_table; - xe->pat.n_entries = ARRAY_SIZE(xelp_pat_table); - xe->pat.idx[XE_CACHE_NONE] = 3; - xe->pat.idx[XE_CACHE_WT] = 2; - xe->pat.idx[XE_CACHE_WB] = 0; - } else { - /* - * Going forward we expect to need new PAT settings for most - * new platforms; failure to provide a new table can easily - * lead to subtle, hard-to-debug problems. If none of the - * conditions above match the platform we're running on we'll - * raise an error rather than trying to silently inherit the - * most recent platform's behavior. - */ - drm_err(&xe->drm, "Missing PAT table for platform with graphics version %d.%02d!\n", - GRAPHICS_VER(xe), GRAPHICS_VERx100(xe) % 100); - } + struct xe_pat_selection selection = { + .table = xe->pat.table, .pat_ats = xe->pat.pat_ats, + .pat_primary_pta = xe->pat.pat_primary_pta, .pat_media_pta = xe->pat.pat_media_pta, + .n_entries = xe->pat.n_entries, + }; + for (int i = 0; i < __XE_CACHE_LEVEL_COUNT; i++) selection.idx[i] = xe->pat.idx[i]; + (void)xe_pat_select(&selection, xe->info.platform, GRAPHICS_VERx100(xe), + IS_DGFX(xe), xe->info.has_llc, xe); + switch (selection.profile) { + case XE_PAT_PROFILE_XELP: xe->pat.ops = &xelp_pat_ops; break; + case XE_PAT_PROFILE_XEHP: xe->pat.ops = &xehp_pat_ops; break; + case XE_PAT_PROFILE_XEHPC: xe->pat.ops = &xehpc_pat_ops; break; + case XE_PAT_PROFILE_XELPG: xe->pat.ops = &xelpg_pat_ops; break; + case XE_PAT_PROFILE_XE2: xe->pat.ops = &xe2_pat_ops; break; + case XE_PAT_PROFILE_XE3P_XPC: xe->pat.ops = &xe3p_xpc_pat_ops; break; + default: break; /* Original missing-policy path preserves existing ops. */ + } + xe->pat.table = selection.table; xe->pat.n_entries = selection.n_entries; + xe->pat.pat_ats = selection.pat_ats; + xe->pat.pat_primary_pta = selection.pat_primary_pta; + xe->pat.pat_media_pta = selection.pat_media_pta; + for (int i = 0; i < __XE_CACHE_LEVEL_COUNT; i++) xe->pat.idx[i] = selection.idx[i]; xe_assert(xe, xe->pat.ops->dump); xe_assert(xe, xe->pat.ops->program_graphics); diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pat.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pat.h index 7060f66e1d..9b800b9abb 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_pat.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pat.h @@ -6,13 +6,21 @@ #ifndef _XE_PAT_H_ #define _XE_PAT_H_ +#ifdef STELA_NATIVE +#include "xe_scalar_types.h" +#else #include +#endif struct drm_printer; struct xe_device; struct xe_gt; +#ifdef STELA_NATIVE +#define XE_PAT_INVALID_IDX UINT16_MAX +#else #define XE_PAT_INVALID_IDX U16_MAX +#endif /** * struct xe_pat_table_entry - The pat_index encoding and other meta information. diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pat_program.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_program.h new file mode 100644 index 0000000000..677560e577 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_program.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2023 Intel Corporation */ +#ifndef XE_PAT_PROGRAM_H +#define XE_PAT_PROGRAM_H +#ifndef XE_PAT_PROGRAM_WRITE +#error "PAT programming requires actual ordered MMIO binding" +#endif +static inline void xe_pat_program_direct(void *context, + const struct xe_pat_table_entry table[], int n_entries, + const struct xe_pat_table_entry *pat_ats, const struct xe_pat_table_entry *pta_entry) +{ + for (int i = 0; i < n_entries; i++) { + struct xe_reg reg = XE_REG(_PAT_INDEX(i)); + + XE_PAT_PROGRAM_WRITE(context, reg, table[i].value); + } + + if (pat_ats) + XE_PAT_PROGRAM_WRITE(context, XE_REG(_PAT_ATS), pat_ats->value); + + if (pta_entry) + XE_PAT_PROGRAM_WRITE(context, XE_REG(_PAT_PTA), pta_entry->value); +} +#undef XE_PAT_PROGRAM_WRITE +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pat_select.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_select.h new file mode 100644 index 0000000000..833fe20b83 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_select.h @@ -0,0 +1,132 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2023 Intel Corporation */ +#ifndef XE_PAT_SELECT_H +#define XE_PAT_SELECT_H +#include "xe_cache_level.h" +#include "xe_platform_types.h" +#include "xe_pat_tables.h" +#ifndef XE_PAT_SELECT_WARN +#error "PAT selector needs actual warning binding" +#endif +#ifndef XE_PAT_SELECT_MISSING +#error "PAT selector needs actual missing-policy diagnostic binding" +#endif +enum xe_pat_profile { XE_PAT_PROFILE_NONE, + XE_PAT_PROFILE_XELP, + XE_PAT_PROFILE_XEHP, + XE_PAT_PROFILE_XEHPC, + XE_PAT_PROFILE_XELPG, + XE_PAT_PROFILE_XE2, + XE_PAT_PROFILE_XE3P_XPC, +}; +struct xe_pat_selection { + enum xe_pat_profile profile; + const struct xe_pat_table_entry *table, *pat_ats, *pat_primary_pta, *pat_media_pta; + int n_entries; + u16 idx[__XE_CACHE_LEVEL_COUNT]; +}; +static inline bool xe_pat_select(struct xe_pat_selection *selection, + enum xe_platform platform, u32 graphics_verx100, bool discrete, bool has_llc, + void *context) +{ + selection->idx[XE_CACHE_WB_COMPRESSION] = XE_PAT_INVALID_IDX; + selection->idx[XE_CACHE_NONE_COMPRESSION] = XE_PAT_INVALID_IDX; + if (graphics_verx100 == 3511) { + selection->profile = XE_PAT_PROFILE_XE3P_XPC; + selection->table = xe3p_xpc_pat_table; + selection->pat_ats = &xe3p_xpc_pat_ats; + selection->pat_primary_pta = &xe3p_xpc_pat_pta; + selection->pat_media_pta = &xe3p_xpc_pat_pta; + selection->n_entries = ARRAY_SIZE(xe3p_xpc_pat_table); + selection->idx[XE_CACHE_NONE] = 3; + selection->idx[XE_CACHE_WT] = 3; /* N/A (no display); use UC */ + selection->idx[XE_CACHE_WB] = 2; + } else if ((graphics_verx100 / 100) == 35) { + selection->profile = XE_PAT_PROFILE_XE2; + selection->table = xe3p_lpg_pat_table; + selection->pat_ats = &xe2_pat_ats; + if (!discrete) { + selection->pat_primary_pta = &xe3p_primary_pat_pta; + selection->pat_media_pta = &xe3p_media_pat_pta; + } + selection->n_entries = ARRAY_SIZE(xe3p_lpg_pat_table); + selection->idx[XE_CACHE_NONE] = 3; + selection->idx[XE_CACHE_WT] = 15; + selection->idx[XE_CACHE_WB] = 2; + selection->idx[XE_CACHE_NONE_COMPRESSION] = 12; + selection->idx[XE_CACHE_WB_COMPRESSION] = 16; + } else if ((graphics_verx100 / 100) == 30 || (graphics_verx100 / 100) == 20) { + selection->profile = XE_PAT_PROFILE_XE2; + if ((graphics_verx100 / 100) == 30) { + selection->table = xe3_lpg_pat_table; + selection->idx[XE_CACHE_WB_COMPRESSION] = 16; + } else { + selection->table = xe2_pat_table; + } + selection->pat_ats = &xe2_pat_ats; + if (discrete) { + selection->pat_primary_pta = &xe2_pat_pta; + selection->pat_media_pta = &xe2_pat_pta; + } + + /* Wa_16023588340. XXX: Should use XE_WA */ + if (graphics_verx100 == 2001) + selection->n_entries = 28; /* Disable CLOS3 */ + else + selection->n_entries = ARRAY_SIZE(xe2_pat_table); + + selection->idx[XE_CACHE_NONE] = 3; + selection->idx[XE_CACHE_WT] = 15; + selection->idx[XE_CACHE_WB] = 2; + selection->idx[XE_CACHE_NONE_COMPRESSION] = 12; /*Applicable on xe2 and beyond */ + } else if (platform == XE_METEORLAKE) { + selection->profile = XE_PAT_PROFILE_XELPG; + selection->table = xelpg_pat_table; + selection->n_entries = ARRAY_SIZE(xelpg_pat_table); + selection->idx[XE_CACHE_NONE] = 2; + selection->idx[XE_CACHE_WT] = 1; + selection->idx[XE_CACHE_WB] = 3; + } else if (platform == XE_PVC) { + selection->profile = XE_PAT_PROFILE_XEHPC; + selection->table = xehpc_pat_table; + selection->n_entries = ARRAY_SIZE(xehpc_pat_table); + selection->idx[XE_CACHE_NONE] = 0; + selection->idx[XE_CACHE_WT] = 2; + selection->idx[XE_CACHE_WB] = 3; + } else if (platform == XE_DG2) { + /* + * Table is the same as previous platforms, but programming + * method has changed. + */ + selection->profile = XE_PAT_PROFILE_XEHP; + selection->table = xelp_pat_table; + selection->n_entries = ARRAY_SIZE(xelp_pat_table); + selection->idx[XE_CACHE_NONE] = 3; + selection->idx[XE_CACHE_WT] = 2; + selection->idx[XE_CACHE_WB] = 0; + } else if (graphics_verx100 <= 1210) { + XE_PAT_SELECT_WARN(context, !discrete && !has_llc); + selection->profile = XE_PAT_PROFILE_XELP; + selection->table = xelp_pat_table; + selection->n_entries = ARRAY_SIZE(xelp_pat_table); + selection->idx[XE_CACHE_NONE] = 3; + selection->idx[XE_CACHE_WT] = 2; + selection->idx[XE_CACHE_WB] = 0; + } else { + /* + * Going forward we expect to need new PAT settings for most + * new platforms; failure to provide a new table can easily + * lead to subtle, hard-to-debug problems. If none of the + * conditions above match the platform we're running on we'll + * raise an error rather than trying to silently inherit the + * most recent platform's behavior. + */ + XE_PAT_SELECT_MISSING(context, graphics_verx100); + return false; + } + + return true; +} +#undef XE_PAT_SELECT_WARN +#undef XE_PAT_SELECT_MISSING +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pat_tables.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_tables.h new file mode 100644 index 0000000000..a3f9a44f61 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pat_tables.h @@ -0,0 +1,238 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2023 Intel Corporation */ +#ifndef XE_PAT_TABLES_H +#define XE_PAT_TABLES_H +#include "xe_pat.h" +#define _PAT_ATS 0x47fc +#define _PAT_INDEX(index) _PICK_EVEN_2RANGES(index, 8, \ + 0x4800, 0x4804, \ + 0x4848, 0x484c) +#define _PAT_PTA 0x4820 + +#define XE2_NO_PROMOTE REG_BIT(10) +#define XE2_COMP_EN REG_BIT(9) +#define XE2_L3_CLOS REG_GENMASK(7, 6) +#define XE2_L3_POLICY REG_GENMASK(5, 4) +#define XE2_L4_POLICY REG_GENMASK(3, 2) +#define XE2_COH_MODE REG_GENMASK(1, 0) + +#define XELPG_L4_POLICY_MASK REG_GENMASK(3, 2) +#define XELPG_PAT_3_UC REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 3) +#define XELPG_PAT_1_WT REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 1) +#define XELPG_PAT_0_WB REG_FIELD_PREP(XELPG_L4_POLICY_MASK, 0) +#define XELPG_INDEX_COH_MODE_MASK REG_GENMASK(1, 0) +#define XELPG_3_COH_2W REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 3) +#define XELPG_2_COH_1W REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 2) +#define XELPG_0_COH_NON REG_FIELD_PREP(XELPG_INDEX_COH_MODE_MASK, 0) + +#define XEHPC_CLOS_LEVEL_MASK REG_GENMASK(3, 2) +#define XEHPC_PAT_CLOS(x) REG_FIELD_PREP(XEHPC_CLOS_LEVEL_MASK, x) + +#define XELP_MEM_TYPE_MASK REG_GENMASK(1, 0) +#define XELP_PAT_WB REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 3) +#define XELP_PAT_WT REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 2) +#define XELP_PAT_WC REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 1) +#define XELP_PAT_UC REG_FIELD_PREP(XELP_MEM_TYPE_MASK, 0) + +static const struct xe_pat_table_entry xelp_pat_table[] = { + [0] = { XELP_PAT_WB, XE_COH_1WAY }, + [1] = { XELP_PAT_WC, XE_COH_NONE }, + [2] = { XELP_PAT_WT, XE_COH_NONE }, + [3] = { XELP_PAT_UC, XE_COH_NONE }, +}; + +static const struct xe_pat_table_entry xehpc_pat_table[] = { + [0] = { XELP_PAT_UC, XE_COH_NONE }, + [1] = { XELP_PAT_WC, XE_COH_NONE }, + [2] = { XELP_PAT_WT, XE_COH_NONE }, + [3] = { XELP_PAT_WB, XE_COH_1WAY }, + [4] = { XEHPC_PAT_CLOS(1) | XELP_PAT_WT, XE_COH_NONE }, + [5] = { XEHPC_PAT_CLOS(1) | XELP_PAT_WB, XE_COH_1WAY }, + [6] = { XEHPC_PAT_CLOS(2) | XELP_PAT_WT, XE_COH_NONE }, + [7] = { XEHPC_PAT_CLOS(2) | XELP_PAT_WB, XE_COH_1WAY }, +}; + +static const struct xe_pat_table_entry xelpg_pat_table[] = { + [0] = { XELPG_PAT_0_WB, XE_COH_NONE }, + [1] = { XELPG_PAT_1_WT, XE_COH_NONE }, + [2] = { XELPG_PAT_3_UC, XE_COH_NONE }, + [3] = { XELPG_PAT_0_WB | XELPG_2_COH_1W, XE_COH_1WAY }, + [4] = { XELPG_PAT_0_WB | XELPG_3_COH_2W, XE_COH_2WAY }, +}; + +/* + * The Xe2 table is getting large/complicated so it's easier to review if + * provided in a form that exactly matches the bspec's formatting. The meaning + * of the fields here are: + * - no_promote: 0=promotable, 1=no promote + * - comp_en: 0=disable, 1=enable + * - l3clos: L3 class of service (0-3) + * - l3_policy: 0=WB, 1=XD ("WB - Transient Display"), + * 2=XA ("WB - Transient App" for Xe3p), 3=UC + * - l4_policy: 0=WB, 1=WT, 3=UC + * - coh_mode: 0=no snoop, 2=1-way coherent, 3=2-way coherent + * + * Reserved entries should be programmed with the maximum caching, minimum + * coherency (which matches an all-0's encoding), so we can just omit them + * in the table. + * + * Note: There is an implicit assumption in the driver that compression and + * coh_1way+ are mutually exclusive for platforms prior to Xe3. Starting + * with Xe3, compression can be combined with coherency. If using compression + * with coherency, userptr and imported dma-buf from external device will + * have uncleared ccs state. See also xe_bo_needs_ccs_pages(). + */ +#define XE2_PAT(no_promote, comp_en, l3clos, l3_policy, l4_policy, __coh_mode) \ + { \ + .value = (no_promote ? XE2_NO_PROMOTE : 0) | \ + (comp_en ? XE2_COMP_EN : 0) | \ + REG_FIELD_PREP(XE2_L3_CLOS, l3clos) | \ + REG_FIELD_PREP(XE2_L3_POLICY, l3_policy) | \ + REG_FIELD_PREP(XE2_L4_POLICY, l4_policy) | \ + REG_FIELD_PREP(XE2_COH_MODE, __coh_mode), \ + .coh_mode = __coh_mode ? __coh_mode : XE_COH_NONE, \ + .valid = 1 \ + } + +static const struct xe_pat_table_entry xe2_pat_table[] = { + [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), + [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), + [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), + [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), + [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), + [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), + [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), + [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), + [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), + [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), + [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), + [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), + [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), + [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), + [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), + [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), + /* 16..19 are reserved; leave set to all 0's */ + [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), + [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), + [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), + [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), + [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), + [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), + [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), + [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), + [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), + [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), + [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), + [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), +}; + +static const struct xe_pat_table_entry xe3_lpg_pat_table[] = { + [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), + [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), + [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), + [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), + [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), + [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), + [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), + [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), + [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), + [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), + [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), + [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), + [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), + [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), + [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), + [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), + [16] = XE2_PAT( 0, 1, 0, 0, 3, 2 ), + /* 17..19 are reserved; leave set to all 0's */ + [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), + [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), + [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), + [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), + [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), + [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), + [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), + [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), + [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), + [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), + [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), + [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), +}; +/* Special PAT values programmed outside the main table */ +static const struct xe_pat_table_entry xe2_pat_ats = XE2_PAT( 0, 0, 0, 0, 3, 3 ); +static const struct xe_pat_table_entry xe2_pat_pta = XE2_PAT( 0, 0, 0, 0, 3, 0 ); + +/* + * Xe3p_XPC PAT table uses the same layout as Xe2/Xe3, except that there's no + * option for compression. Also note that the "L3" and "L4" register fields + * actually control L2 and L3 cache respectively on this platform. + */ +#define XE3P_XPC_PAT(no_promote, l3clos, l3_policy, l4_policy, __coh_mode) \ + XE2_PAT(no_promote, 0, l3clos, l3_policy, l4_policy, __coh_mode) + +static const struct xe_pat_table_entry xe3p_xpc_pat_ats = XE3P_XPC_PAT( 0, 0, 0, 0, 3 ); +static const struct xe_pat_table_entry xe3p_xpc_pat_pta = XE3P_XPC_PAT( 0, 0, 0, 0, 0 ); + +static const struct xe_pat_table_entry xe3p_xpc_pat_table[] = { + [ 0] = XE3P_XPC_PAT( 0, 0, 0, 0, 0 ), + [ 1] = XE3P_XPC_PAT( 0, 0, 0, 0, 2 ), + [ 2] = XE3P_XPC_PAT( 0, 0, 0, 0, 3 ), + [ 3] = XE3P_XPC_PAT( 0, 0, 3, 3, 0 ), + [ 4] = XE3P_XPC_PAT( 0, 0, 3, 3, 2 ), + [ 5] = XE3P_XPC_PAT( 0, 0, 3, 0, 0 ), + [ 6] = XE3P_XPC_PAT( 0, 0, 3, 0, 2 ), + [ 7] = XE3P_XPC_PAT( 0, 0, 3, 0, 3 ), + [ 8] = XE3P_XPC_PAT( 0, 0, 0, 3, 0 ), + [ 9] = XE3P_XPC_PAT( 0, 0, 0, 3, 2 ), + [10] = XE3P_XPC_PAT( 0, 0, 0, 3, 3 ), + /* 11..22 are reserved; leave set to all 0's */ + [23] = XE3P_XPC_PAT( 0, 1, 0, 0, 0 ), + [24] = XE3P_XPC_PAT( 0, 1, 0, 0, 2 ), + [25] = XE3P_XPC_PAT( 0, 1, 0, 0, 3 ), + [26] = XE3P_XPC_PAT( 0, 2, 0, 0, 0 ), + [27] = XE3P_XPC_PAT( 0, 2, 0, 0, 2 ), + [28] = XE3P_XPC_PAT( 0, 2, 0, 0, 3 ), + [29] = XE3P_XPC_PAT( 0, 3, 0, 0, 0 ), + [30] = XE3P_XPC_PAT( 0, 3, 0, 0, 2 ), + [31] = XE3P_XPC_PAT( 0, 3, 0, 0, 3 ), +}; + +static const struct xe_pat_table_entry xe3p_primary_pat_pta = XE2_PAT(0, 0, 0, 0, 0, 3); +static const struct xe_pat_table_entry xe3p_media_pat_pta = XE2_PAT(0, 0, 0, 0, 0, 2); + +static const struct xe_pat_table_entry xe3p_lpg_pat_table[] = { + [ 0] = XE2_PAT( 0, 0, 0, 0, 3, 0 ), + [ 1] = XE2_PAT( 0, 0, 0, 0, 3, 2 ), + [ 2] = XE2_PAT( 0, 0, 0, 0, 3, 3 ), + [ 3] = XE2_PAT( 0, 0, 0, 3, 3, 0 ), + [ 4] = XE2_PAT( 0, 0, 0, 3, 0, 2 ), + [ 5] = XE2_PAT( 0, 0, 0, 3, 3, 2 ), + [ 6] = XE2_PAT( 1, 0, 0, 1, 3, 0 ), + [ 7] = XE2_PAT( 0, 0, 0, 3, 0, 3 ), + [ 8] = XE2_PAT( 0, 0, 0, 3, 0, 0 ), + [ 9] = XE2_PAT( 0, 1, 0, 0, 3, 0 ), + [10] = XE2_PAT( 0, 1, 0, 3, 0, 0 ), + [11] = XE2_PAT( 1, 1, 0, 1, 3, 0 ), + [12] = XE2_PAT( 0, 1, 0, 3, 3, 0 ), + [13] = XE2_PAT( 0, 0, 0, 0, 0, 0 ), + [14] = XE2_PAT( 0, 1, 0, 0, 0, 0 ), + [15] = XE2_PAT( 1, 1, 0, 1, 1, 0 ), + [16] = XE2_PAT( 0, 1, 0, 0, 3, 2 ), + /* 17 is reserved; leave set to all 0's */ + [18] = XE2_PAT( 1, 0, 0, 2, 3, 0 ), + [19] = XE2_PAT( 1, 0, 0, 2, 3, 2 ), + [20] = XE2_PAT( 0, 0, 1, 0, 3, 0 ), + [21] = XE2_PAT( 0, 1, 1, 0, 3, 0 ), + [22] = XE2_PAT( 0, 0, 1, 0, 3, 2 ), + [23] = XE2_PAT( 0, 0, 1, 0, 3, 3 ), + [24] = XE2_PAT( 0, 0, 2, 0, 3, 0 ), + [25] = XE2_PAT( 0, 1, 2, 0, 3, 0 ), + [26] = XE2_PAT( 0, 0, 2, 0, 3, 2 ), + [27] = XE2_PAT( 0, 0, 2, 0, 3, 3 ), + [28] = XE2_PAT( 0, 0, 3, 0, 3, 0 ), + [29] = XE2_PAT( 0, 1, 3, 0, 3, 0 ), + [30] = XE2_PAT( 0, 0, 3, 0, 3, 2 ), + [31] = XE2_PAT( 0, 0, 3, 0, 3, 3 ), +}; + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pci.c b/crates/stela-drivers/src/gpu/intel/xe/xe_pci.c index 9cd8737081..a6a5da0b8b 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_pci.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pci.c @@ -41,488 +41,7 @@ enum toggle_d3cold { D3COLD_ENABLE, }; -__diag_push(); -__diag_ignore_all("-Woverride-init", "Allow field overrides in table"); - -#define PLATFORM(x) \ - .platform = XE_##x, \ - .platform_name = #x - -#define NOP(x) x - -static const struct xe_graphics_desc graphics_xelp = { - .hw_engine_mask = BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0), - .num_geometry_xecore_fuse_regs = 1, -}; - -#define XE_HP_FEATURES \ - .has_range_tlb_inval = true - -static const struct xe_graphics_desc graphics_xehpg = { - .hw_engine_mask = - BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0) | - BIT(XE_HW_ENGINE_CCS0) | BIT(XE_HW_ENGINE_CCS1) | - BIT(XE_HW_ENGINE_CCS2) | BIT(XE_HW_ENGINE_CCS3), - .num_geometry_xecore_fuse_regs = 1, - .num_compute_xecore_fuse_regs = 1, - - XE_HP_FEATURES, -}; - -static const struct xe_graphics_desc graphics_xehpc = { - .hw_engine_mask = - BIT(XE_HW_ENGINE_BCS0) | BIT(XE_HW_ENGINE_BCS1) | - BIT(XE_HW_ENGINE_BCS2) | BIT(XE_HW_ENGINE_BCS3) | - BIT(XE_HW_ENGINE_BCS4) | BIT(XE_HW_ENGINE_BCS5) | - BIT(XE_HW_ENGINE_BCS6) | BIT(XE_HW_ENGINE_BCS7) | - BIT(XE_HW_ENGINE_BCS8) | - BIT(XE_HW_ENGINE_CCS0) | BIT(XE_HW_ENGINE_CCS1) | - BIT(XE_HW_ENGINE_CCS2) | BIT(XE_HW_ENGINE_CCS3), - - XE_HP_FEATURES, - - .has_access_counter = 1, - .has_asid = 1, - .has_atomic_enable_pte_bit = 1, - .has_usm = 1, - .num_compute_xecore_fuse_regs = 2, -}; - -static const struct xe_graphics_desc graphics_xelpg = { - .hw_engine_mask = - BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0) | - BIT(XE_HW_ENGINE_CCS0), - .num_geometry_xecore_fuse_regs = 1, - .num_compute_xecore_fuse_regs = 1, - - XE_HP_FEATURES, -}; - -#define XE2_GFX_FEATURES \ - .has_access_counter = 1, \ - .has_asid = 1, \ - .has_atomic_enable_pte_bit = 1, \ - .has_range_tlb_inval = 1, \ - .has_usm = 1, \ - .has_64bit_timestamp = 1, \ - .hw_engine_mask = \ - BIT(XE_HW_ENGINE_RCS0) | \ - BIT(XE_HW_ENGINE_BCS8) | BIT(XE_HW_ENGINE_BCS0) | \ - GENMASK(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0) - -static const struct xe_graphics_desc graphics_xe2 = { - XE2_GFX_FEATURES, - .num_geometry_xecore_fuse_regs = 3, - .num_compute_xecore_fuse_regs = 3, -}; - -static const struct xe_graphics_desc graphics_xe3p_lpg = { - XE2_GFX_FEATURES, - .has_indirect_ring_state = 1, - .multi_queue_engine_class_mask = BIT(XE_ENGINE_CLASS_COPY) | BIT(XE_ENGINE_CLASS_COMPUTE), - .num_geometry_xecore_fuse_regs = 3, - .num_compute_xecore_fuse_regs = 3, -}; - -static const struct xe_graphics_desc graphics_xe3p_xpc = { - XE2_GFX_FEATURES, - .has_access_counter = 0, - .has_indirect_ring_state = 1, - .hw_engine_mask = - GENMASK(XE_HW_ENGINE_BCS8, XE_HW_ENGINE_BCS1) | - GENMASK(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0), - .multi_queue_engine_class_mask = BIT(XE_ENGINE_CLASS_COPY) | - BIT(XE_ENGINE_CLASS_COMPUTE), - .num_geometry_xecore_fuse_regs = 4, - .num_compute_xecore_fuse_regs = 4, -}; - -static const struct xe_media_desc media_xem = { - .hw_engine_mask = - GENMASK(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) | - GENMASK(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0), -}; - -static const struct xe_media_desc media_xelpmp = { - .hw_engine_mask = - GENMASK(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) | - GENMASK(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0) | - BIT(XE_HW_ENGINE_GSCCS0) -}; - -/* Pre-GMDID Graphics IPs */ -static const struct xe_ip graphics_ip_xelp = { 1200, "Xe_LP", &graphics_xelp }; -static const struct xe_ip graphics_ip_xelpp = { 1210, "Xe_LP+", &graphics_xelp }; -static const struct xe_ip graphics_ip_xehpg = { 1255, "Xe_HPG", &graphics_xehpg }; -static const struct xe_ip graphics_ip_xehpc = { 1260, "Xe_HPC", &graphics_xehpc }; - -/* GMDID-based Graphics IPs */ -static const struct xe_ip graphics_ips[] = { - { 1270, "Xe_LPG", &graphics_xelpg }, - { 1271, "Xe_LPG", &graphics_xelpg }, - { 1274, "Xe_LPG+", &graphics_xelpg }, - { 2001, "Xe2_HPG", &graphics_xe2 }, - { 2002, "Xe2_HPG", &graphics_xe2 }, - { 2004, "Xe2_LPG", &graphics_xe2 }, - { 3000, "Xe3_LPG", &graphics_xe2 }, - { 3001, "Xe3_LPG", &graphics_xe2 }, - { 3003, "Xe3_LPG", &graphics_xe2 }, - { 3004, "Xe3_LPG", &graphics_xe2 }, - { 3005, "Xe3_LPG", &graphics_xe2 }, - { 3510, "Xe3p_LPG", &graphics_xe3p_lpg }, - { 3511, "Xe3p_XPC", &graphics_xe3p_xpc }, -}; - -/* Pre-GMDID Media IPs */ -static const struct xe_ip media_ip_xem = { 1200, "Xe_M", &media_xem }; -static const struct xe_ip media_ip_xehpm = { 1255, "Xe_HPM", &media_xem }; - -/* GMDID-based Media IPs */ -static const struct xe_ip media_ips[] = { - { 1300, "Xe_LPM+", &media_xelpmp }, - { 1301, "Xe2_HPM", &media_xelpmp }, - { 2000, "Xe2_LPM", &media_xelpmp }, - { 3000, "Xe3_LPM", &media_xelpmp }, - { 3002, "Xe3_LPM", &media_xelpmp }, - { 3500, "Xe3p_LPM", &media_xelpmp }, - { 3503, "Xe3p_HPM", &media_xelpmp }, -}; - -#define MULTI_LRC_MASK \ - .multi_lrc_mask = BIT(XE_ENGINE_CLASS_VIDEO_DECODE) | \ - BIT(XE_ENGINE_CLASS_VIDEO_ENHANCE) - -static const struct xe_device_desc tgl_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelp, - .pre_gmdid_media_ip = &media_ip_xem, - PLATFORM(TIGERLAKE), - .dma_mask_size = 39, - .has_cached_pt = true, - .has_display = true, - .has_llc = true, - .has_sriov = true, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const struct xe_device_desc rkl_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelp, - .pre_gmdid_media_ip = &media_ip_xem, - PLATFORM(ROCKETLAKE), - .dma_mask_size = 39, - .has_cached_pt = true, - .has_display = true, - .has_llc = true, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const u16 adls_rpls_ids[] = { INTEL_RPLS_IDS(NOP), 0 }; - -static const struct xe_device_desc adl_s_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelp, - .pre_gmdid_media_ip = &media_ip_xem, - PLATFORM(ALDERLAKE_S), - .dma_mask_size = 39, - .has_cached_pt = true, - .has_display = true, - .has_llc = true, - .has_sriov = true, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .subplatforms = (const struct xe_subplatform_desc[]) { - { XE_SUBPLATFORM_ALDERLAKE_S_RPLS, "RPLS", adls_rpls_ids }, - {}, - }, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const u16 adlp_rplu_ids[] = { INTEL_RPLU_IDS(NOP), 0 }; - -static const struct xe_device_desc adl_p_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelp, - .pre_gmdid_media_ip = &media_ip_xem, - PLATFORM(ALDERLAKE_P), - .dma_mask_size = 39, - .has_cached_pt = true, - .has_display = true, - .has_llc = true, - .has_sriov = true, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .subplatforms = (const struct xe_subplatform_desc[]) { - { XE_SUBPLATFORM_ALDERLAKE_P_RPLU, "RPLU", adlp_rplu_ids }, - {}, - }, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const struct xe_device_desc adl_n_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelp, - .pre_gmdid_media_ip = &media_ip_xem, - PLATFORM(ALDERLAKE_N), - .dma_mask_size = 39, - .has_cached_pt = true, - .has_display = true, - .has_llc = true, - .has_sriov = true, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 3, -}; - -#define DGFX_FEATURES \ - .is_dgfx = 1 - -static const struct xe_device_desc dg1_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xelpp, - .pre_gmdid_media_ip = &media_ip_xem, - DGFX_FEATURES, - PLATFORM(DG1), - .dma_mask_size = 39, - .has_display = true, - .has_gsc_nvm = 1, - .has_heci_gscfi = 1, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const u16 dg2_g10_ids[] = { INTEL_DG2_G10_IDS(NOP), INTEL_ATS_M150_IDS(NOP), 0 }; -static const u16 dg2_g11_ids[] = { INTEL_DG2_G11_IDS(NOP), INTEL_ATS_M75_IDS(NOP), 0 }; -static const u16 dg2_g12_ids[] = { INTEL_DG2_G12_IDS(NOP), 0 }; - -#define DG2_FEATURES \ - DGFX_FEATURES, \ - PLATFORM(DG2), \ - .has_flat_ccs = 1, \ - .has_gsc_nvm = 1, \ - .has_heci_gscfi = 1, \ - .subplatforms = (const struct xe_subplatform_desc[]) { \ - { XE_SUBPLATFORM_DG2_G10, "G10", dg2_g10_ids }, \ - { XE_SUBPLATFORM_DG2_G11, "G11", dg2_g11_ids }, \ - { XE_SUBPLATFORM_DG2_G12, "G12", dg2_g12_ids }, \ - { } \ - }, \ - .va_bits = 48, \ - .vm_max_level = 3, \ - .vram_flags = XE_VRAM_FLAGS_NEED64K - -static const struct xe_device_desc ats_m_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xehpg, - .pre_gmdid_media_ip = &media_ip_xehpm, - .dma_mask_size = 46, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - - DG2_FEATURES, - .has_display = false, - .has_sriov = true, -}; - -static const struct xe_device_desc dg2_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xehpg, - .pre_gmdid_media_ip = &media_ip_xehpm, - .dma_mask_size = 46, - .max_gt_per_tile = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - - DG2_FEATURES, - .has_display = true, - .has_fan_control = true, - .has_mbx_power_limits = false, -}; - -static const __maybe_unused struct xe_device_desc pvc_desc = { - .pre_gmdid_graphics_ip = &graphics_ip_xehpc, - DGFX_FEATURES, - PLATFORM(PVC), - .dma_mask_size = 52, - .has_display = false, - .has_gsc_nvm = 1, - .has_heci_gscfi = 1, - .max_gt_per_tile = 1, - .max_remote_tiles = 1, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 57, - .vm_max_level = 4, - .vram_flags = XE_VRAM_FLAGS_NEED64K, - .has_mbx_power_limits = false, -}; - -static const struct xe_device_desc mtl_desc = { - /* .graphics and .media determined via GMD_ID */ - .require_force_probe = true, - PLATFORM(METEORLAKE), - .dma_mask_size = 46, - .has_display = true, - .has_pxp = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .va_bits = 48, - .vm_max_level = 3, -}; - -static const struct xe_device_desc lnl_desc = { - PLATFORM(LUNARLAKE), - .dma_mask_size = 46, - .has_display = true, - .has_flat_ccs = 1, - .has_pxp = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .needs_scratch = true, - .va_bits = 48, - .vm_max_level = 4, -}; - -static const u16 bmg_g21_ids[] = { INTEL_BMG_G21_IDS(NOP), 0 }; - -static const struct xe_device_desc bmg_desc = { - DGFX_FEATURES, - PLATFORM(BATTLEMAGE), - .dma_mask_size = 46, - .has_display = true, - .has_fan_control = true, - .has_flat_ccs = 1, - .has_mbx_power_limits = true, - .has_mbx_thermal_info = true, - .has_gsc_nvm = 1, - .has_heci_cscfi = 1, - .has_i2c = true, - .has_late_bind = true, - .has_pre_prod_wa = 1, - .has_soc_remapper_telem = true, - .has_sriov = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .needs_scratch = true, - .subplatforms = (const struct xe_subplatform_desc[]) { - { XE_SUBPLATFORM_BATTLEMAGE_G21, "G21", bmg_g21_ids }, - { } - }, - .va_bits = 48, - .vm_max_level = 4, -}; - -static const struct xe_device_desc ptl_desc = { - PLATFORM(PANTHERLAKE), - .dma_mask_size = 46, - .has_display = true, - .has_flat_ccs = 1, - .has_sriov = true, - .has_pre_prod_wa = 1, - .has_pxp = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .needs_scratch = true, - .needs_shared_vf_gt_wq = true, - .va_bits = 48, - .vm_max_level = 4, -}; - -static const struct xe_device_desc nvls_desc = { - PLATFORM(NOVALAKE_S), - .dma_mask_size = 46, - .has_display = true, - .has_flat_ccs = 1, - .has_pre_prod_wa = 1, - .has_sriov = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 4, -}; - -static const struct xe_device_desc cri_desc = { - DGFX_FEATURES, - PLATFORM(CRESCENTISLAND), - .dma_mask_size = 52, - .has_display = false, - .has_flat_ccs = false, - .has_gsc_nvm = 1, - .has_i2c = true, - .has_mbx_power_limits = true, - .has_mbx_thermal_info = true, - .has_mert = true, - .has_pre_prod_wa = 1, - .has_soc_remapper_sysctrl = true, - .has_soc_remapper_telem = true, - .has_sriov = true, - .has_sysctrl = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 57, - .vm_max_level = 4, -}; - -static const struct xe_device_desc nvlp_desc = { - PLATFORM(NOVALAKE_P), - .dma_mask_size = 46, - .has_cached_pt = true, - .has_display = true, - .has_flat_ccs = 1, - .has_page_reclaim_hw_assist = true, - .has_pre_prod_wa = true, - .has_sriov = true, - .max_gt_per_tile = 2, - MULTI_LRC_MASK, - .require_force_probe = true, - .va_bits = 48, - .vm_max_level = 4, -}; - -#undef PLATFORM -__diag_pop(); - -/* - * Make sure any device matches here are from most specific to most - * general. For example, since the Quanta match is based on the subsystem - * and subvendor IDs, we need it to come before the more general IVB - * PCI ID matches, otherwise we'll use the wrong info struct above. - */ -static const struct pci_device_id pciidlist[] = { - INTEL_TGL_IDS(INTEL_VGA_DEVICE, &tgl_desc), - INTEL_RKL_IDS(INTEL_VGA_DEVICE, &rkl_desc), - INTEL_ADLS_IDS(INTEL_VGA_DEVICE, &adl_s_desc), - INTEL_ADLP_IDS(INTEL_VGA_DEVICE, &adl_p_desc), - INTEL_ADLN_IDS(INTEL_VGA_DEVICE, &adl_n_desc), - INTEL_RPLU_IDS(INTEL_VGA_DEVICE, &adl_p_desc), - INTEL_RPLP_IDS(INTEL_VGA_DEVICE, &adl_p_desc), - INTEL_RPLS_IDS(INTEL_VGA_DEVICE, &adl_s_desc), - INTEL_DG1_IDS(INTEL_VGA_DEVICE, &dg1_desc), - INTEL_ATS_M_IDS(INTEL_VGA_DEVICE, &ats_m_desc), - INTEL_ARL_IDS(INTEL_VGA_DEVICE, &mtl_desc), - INTEL_DG2_IDS(INTEL_VGA_DEVICE, &dg2_desc), - INTEL_MTL_IDS(INTEL_VGA_DEVICE, &mtl_desc), - INTEL_LNL_IDS(INTEL_VGA_DEVICE, &lnl_desc), - INTEL_BMG_IDS(INTEL_VGA_DEVICE, &bmg_desc), - INTEL_PTL_IDS(INTEL_VGA_DEVICE, &ptl_desc), - INTEL_WCL_IDS(INTEL_VGA_DEVICE, &ptl_desc), - INTEL_NVLS_IDS(INTEL_VGA_DEVICE, &nvls_desc), - INTEL_CRI_IDS(INTEL_PCI_DEVICE, &cri_desc), - INTEL_NVLP_IDS(INTEL_VGA_DEVICE, &nvlp_desc), - { } -}; +#include "xe_pci_device_info.h" MODULE_DEVICE_TABLE(pci, pciidlist); /* is device_id present in comma separated list of ids */ @@ -574,19 +93,7 @@ static bool id_blocked(u16 device_id) return device_id_in_list(device_id, xe_modparam.force_probe, true); } -static const struct xe_subplatform_desc * -find_subplatform(const struct xe_device_desc *desc, u16 devid) -{ - const struct xe_subplatform_desc *sp; - const u16 *id; - - for (sp = desc->subplatforms; sp && sp->subplatform; sp++) - for (id = sp->pciidlist; *id; id++) - if (*id == devid) - return sp; - - return NULL; -} +#include "xe_pci_runtime.h" enum xe_gmdid_type { GMDID_GRAPHICS, @@ -596,7 +103,7 @@ enum xe_gmdid_type { static int read_gmdid(struct xe_device *xe, enum xe_gmdid_type type, u32 *ver, u32 *revid) { struct xe_mmio *mmio = xe_root_tile_mmio(xe); - struct xe_reg gmdid_reg = GMD_ID; + struct xe_reg gmdid_reg = xe_pci_gmdid_register(type == GMDID_MEDIA); u32 val; KUNIT_STATIC_STUB_REDIRECT(read_gmdid, xe, type, ver, revid); @@ -651,38 +158,14 @@ static int read_gmdid(struct xe_device *xe, enum xe_gmdid_type type, u32 *ver, u * automatically added as it would if we were using a GT mmio * accessor. */ - if (type == GMDID_MEDIA) - gmdid_reg.addr += MEDIA_GT_GSI_OFFSET; - val = xe_mmio_read32(mmio, gmdid_reg); } - *ver = REG_FIELD_GET(GMD_ID_ARCH_MASK, val) * 100 + REG_FIELD_GET(GMD_ID_RELEASE_MASK, val); - *revid = REG_FIELD_GET(GMD_ID_REVID, val); + xe_pci_decode_gmdid(val, ver, revid); return 0; } -static const struct xe_ip *find_graphics_ip(unsigned int verx100) -{ - KUNIT_STATIC_STUB_REDIRECT(find_graphics_ip, verx100); - - for (int i = 0; i < ARRAY_SIZE(graphics_ips); i++) - if (graphics_ips[i].verx100 == verx100) - return &graphics_ips[i]; - return NULL; -} - -static const struct xe_ip *find_media_ip(unsigned int verx100) -{ - KUNIT_STATIC_STUB_REDIRECT(find_media_ip, verx100); - - for (int i = 0; i < ARRAY_SIZE(media_ips); i++) - if (media_ips[i].verx100 == verx100) - return &media_ips[i]; - return NULL; -} - /* * Read IP version from hardware and select graphics/media IP descriptors * based on the result. @@ -832,7 +315,7 @@ static void xe_info_probe_tile_count(struct xe_device *xe) * guaranteed to be initialized earlier in xe_mmio_probe_early() */ mtcfg = xe_mmio_read32(mmio, XEHP_MTCFG_ADDR); - tile_count = REG_FIELD_GET(TILE_COUNT, mtcfg) + 1; + tile_count = xe_pci_runtime_tile_count(xe->info.tile_count, mtcfg); if (tile_count < xe->info.tile_count) { drm_info(&xe->drm, "tile_count: %d, reduced_tile_count %d\n", diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pci_device_info.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_device_info.h new file mode 100644 index 0000000000..0483678e7e --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_device_info.h @@ -0,0 +1,492 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2021 Intel Corporation + */ +#ifndef XE_PCI_DEVICE_INFO_H +#define XE_PCI_DEVICE_INFO_H +#ifndef XE_PCI_ID_TYPE +#define XE_PCI_ID_TYPE struct pci_device_id +#endif +__diag_push(); +__diag_ignore_all("-Woverride-init", "Allow field overrides in table"); + +#define PLATFORM(x) \ + .platform = XE_##x, \ + .platform_name = #x + +#define NOP(x) x + +static const struct xe_graphics_desc graphics_xelp = { + .hw_engine_mask = BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0), + .num_geometry_xecore_fuse_regs = 1, +}; + +#define XE_HP_FEATURES \ + .has_range_tlb_inval = true + +static const struct xe_graphics_desc graphics_xehpg = { + .hw_engine_mask = + BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0) | + BIT(XE_HW_ENGINE_CCS0) | BIT(XE_HW_ENGINE_CCS1) | + BIT(XE_HW_ENGINE_CCS2) | BIT(XE_HW_ENGINE_CCS3), + .num_geometry_xecore_fuse_regs = 1, + .num_compute_xecore_fuse_regs = 1, + + XE_HP_FEATURES, +}; + +static const struct xe_graphics_desc graphics_xehpc = { + .hw_engine_mask = + BIT(XE_HW_ENGINE_BCS0) | BIT(XE_HW_ENGINE_BCS1) | + BIT(XE_HW_ENGINE_BCS2) | BIT(XE_HW_ENGINE_BCS3) | + BIT(XE_HW_ENGINE_BCS4) | BIT(XE_HW_ENGINE_BCS5) | + BIT(XE_HW_ENGINE_BCS6) | BIT(XE_HW_ENGINE_BCS7) | + BIT(XE_HW_ENGINE_BCS8) | + BIT(XE_HW_ENGINE_CCS0) | BIT(XE_HW_ENGINE_CCS1) | + BIT(XE_HW_ENGINE_CCS2) | BIT(XE_HW_ENGINE_CCS3), + + XE_HP_FEATURES, + + .has_access_counter = 1, + .has_asid = 1, + .has_atomic_enable_pte_bit = 1, + .has_usm = 1, + .num_compute_xecore_fuse_regs = 2, +}; + +static const struct xe_graphics_desc graphics_xelpg = { + .hw_engine_mask = + BIT(XE_HW_ENGINE_RCS0) | BIT(XE_HW_ENGINE_BCS0) | + BIT(XE_HW_ENGINE_CCS0), + .num_geometry_xecore_fuse_regs = 1, + .num_compute_xecore_fuse_regs = 1, + + XE_HP_FEATURES, +}; + +#define XE2_GFX_FEATURES \ + .has_access_counter = 1, \ + .has_asid = 1, \ + .has_atomic_enable_pte_bit = 1, \ + .has_range_tlb_inval = 1, \ + .has_usm = 1, \ + .has_64bit_timestamp = 1, \ + .hw_engine_mask = \ + BIT(XE_HW_ENGINE_RCS0) | \ + BIT(XE_HW_ENGINE_BCS8) | BIT(XE_HW_ENGINE_BCS0) | \ + GENMASK(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0) + +static const struct xe_graphics_desc graphics_xe2 = { + XE2_GFX_FEATURES, + .num_geometry_xecore_fuse_regs = 3, + .num_compute_xecore_fuse_regs = 3, +}; + +static const struct xe_graphics_desc graphics_xe3p_lpg = { + XE2_GFX_FEATURES, + .has_indirect_ring_state = 1, + .multi_queue_engine_class_mask = BIT(XE_ENGINE_CLASS_COPY) | BIT(XE_ENGINE_CLASS_COMPUTE), + .num_geometry_xecore_fuse_regs = 3, + .num_compute_xecore_fuse_regs = 3, +}; + +static const struct xe_graphics_desc graphics_xe3p_xpc = { + XE2_GFX_FEATURES, + .has_access_counter = 0, + .has_indirect_ring_state = 1, + .hw_engine_mask = + GENMASK(XE_HW_ENGINE_BCS8, XE_HW_ENGINE_BCS1) | + GENMASK(XE_HW_ENGINE_CCS3, XE_HW_ENGINE_CCS0), + .multi_queue_engine_class_mask = BIT(XE_ENGINE_CLASS_COPY) | + BIT(XE_ENGINE_CLASS_COMPUTE), + .num_geometry_xecore_fuse_regs = 4, + .num_compute_xecore_fuse_regs = 4, +}; + +static const struct xe_media_desc media_xem = { + .hw_engine_mask = + GENMASK(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) | + GENMASK(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0), +}; + +static const struct xe_media_desc media_xelpmp = { + .hw_engine_mask = + GENMASK(XE_HW_ENGINE_VCS7, XE_HW_ENGINE_VCS0) | + GENMASK(XE_HW_ENGINE_VECS3, XE_HW_ENGINE_VECS0) | + BIT(XE_HW_ENGINE_GSCCS0) +}; + +/* Pre-GMDID Graphics IPs */ +static const struct xe_ip graphics_ip_xelp = { 1200, "Xe_LP", &graphics_xelp }; +static const struct xe_ip graphics_ip_xelpp = { 1210, "Xe_LP+", &graphics_xelp }; +static const struct xe_ip graphics_ip_xehpg = { 1255, "Xe_HPG", &graphics_xehpg }; +static const struct xe_ip graphics_ip_xehpc = { 1260, "Xe_HPC", &graphics_xehpc }; + +/* GMDID-based Graphics IPs */ +static const struct xe_ip graphics_ips[] = { + { 1270, "Xe_LPG", &graphics_xelpg }, + { 1271, "Xe_LPG", &graphics_xelpg }, + { 1274, "Xe_LPG+", &graphics_xelpg }, + { 2001, "Xe2_HPG", &graphics_xe2 }, + { 2002, "Xe2_HPG", &graphics_xe2 }, + { 2004, "Xe2_LPG", &graphics_xe2 }, + { 3000, "Xe3_LPG", &graphics_xe2 }, + { 3001, "Xe3_LPG", &graphics_xe2 }, + { 3003, "Xe3_LPG", &graphics_xe2 }, + { 3004, "Xe3_LPG", &graphics_xe2 }, + { 3005, "Xe3_LPG", &graphics_xe2 }, + { 3510, "Xe3p_LPG", &graphics_xe3p_lpg }, + { 3511, "Xe3p_XPC", &graphics_xe3p_xpc }, +}; + +/* Pre-GMDID Media IPs */ +static const struct xe_ip media_ip_xem = { 1200, "Xe_M", &media_xem }; +static const struct xe_ip media_ip_xehpm = { 1255, "Xe_HPM", &media_xem }; + +/* GMDID-based Media IPs */ +static const struct xe_ip media_ips[] = { + { 1300, "Xe_LPM+", &media_xelpmp }, + { 1301, "Xe2_HPM", &media_xelpmp }, + { 2000, "Xe2_LPM", &media_xelpmp }, + { 3000, "Xe3_LPM", &media_xelpmp }, + { 3002, "Xe3_LPM", &media_xelpmp }, + { 3500, "Xe3p_LPM", &media_xelpmp }, + { 3503, "Xe3p_HPM", &media_xelpmp }, +}; + +#define MULTI_LRC_MASK \ + .multi_lrc_mask = BIT(XE_ENGINE_CLASS_VIDEO_DECODE) | \ + BIT(XE_ENGINE_CLASS_VIDEO_ENHANCE) + +static const struct xe_device_desc tgl_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelp, + .pre_gmdid_media_ip = &media_ip_xem, + PLATFORM(TIGERLAKE), + .dma_mask_size = 39, + .has_cached_pt = true, + .has_display = true, + .has_llc = true, + .has_sriov = true, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const struct xe_device_desc rkl_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelp, + .pre_gmdid_media_ip = &media_ip_xem, + PLATFORM(ROCKETLAKE), + .dma_mask_size = 39, + .has_cached_pt = true, + .has_display = true, + .has_llc = true, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const u16 adls_rpls_ids[] = { INTEL_RPLS_IDS(NOP), 0 }; + +static const struct xe_device_desc adl_s_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelp, + .pre_gmdid_media_ip = &media_ip_xem, + PLATFORM(ALDERLAKE_S), + .dma_mask_size = 39, + .has_cached_pt = true, + .has_display = true, + .has_llc = true, + .has_sriov = true, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .subplatforms = (const struct xe_subplatform_desc[]) { + { XE_SUBPLATFORM_ALDERLAKE_S_RPLS, "RPLS", adls_rpls_ids }, + {}, + }, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const u16 adlp_rplu_ids[] = { INTEL_RPLU_IDS(NOP), 0 }; + +static const struct xe_device_desc adl_p_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelp, + .pre_gmdid_media_ip = &media_ip_xem, + PLATFORM(ALDERLAKE_P), + .dma_mask_size = 39, + .has_cached_pt = true, + .has_display = true, + .has_llc = true, + .has_sriov = true, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .subplatforms = (const struct xe_subplatform_desc[]) { + { XE_SUBPLATFORM_ALDERLAKE_P_RPLU, "RPLU", adlp_rplu_ids }, + {}, + }, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const struct xe_device_desc adl_n_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelp, + .pre_gmdid_media_ip = &media_ip_xem, + PLATFORM(ALDERLAKE_N), + .dma_mask_size = 39, + .has_cached_pt = true, + .has_display = true, + .has_llc = true, + .has_sriov = true, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 3, +}; + +#define DGFX_FEATURES \ + .is_dgfx = 1 + +static const struct xe_device_desc dg1_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xelpp, + .pre_gmdid_media_ip = &media_ip_xem, + DGFX_FEATURES, + PLATFORM(DG1), + .dma_mask_size = 39, + .has_display = true, + .has_gsc_nvm = 1, + .has_heci_gscfi = 1, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const u16 dg2_g10_ids[] = { INTEL_DG2_G10_IDS(NOP), INTEL_ATS_M150_IDS(NOP), 0 }; +static const u16 dg2_g11_ids[] = { INTEL_DG2_G11_IDS(NOP), INTEL_ATS_M75_IDS(NOP), 0 }; +static const u16 dg2_g12_ids[] = { INTEL_DG2_G12_IDS(NOP), 0 }; + +#define DG2_FEATURES \ + DGFX_FEATURES, \ + PLATFORM(DG2), \ + .has_flat_ccs = 1, \ + .has_gsc_nvm = 1, \ + .has_heci_gscfi = 1, \ + .subplatforms = (const struct xe_subplatform_desc[]) { \ + { XE_SUBPLATFORM_DG2_G10, "G10", dg2_g10_ids }, \ + { XE_SUBPLATFORM_DG2_G11, "G11", dg2_g11_ids }, \ + { XE_SUBPLATFORM_DG2_G12, "G12", dg2_g12_ids }, \ + { } \ + }, \ + .va_bits = 48, \ + .vm_max_level = 3, \ + .vram_flags = XE_VRAM_FLAGS_NEED64K + +static const struct xe_device_desc ats_m_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xehpg, + .pre_gmdid_media_ip = &media_ip_xehpm, + .dma_mask_size = 46, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + + DG2_FEATURES, + .has_display = false, + .has_sriov = true, +}; + +static const struct xe_device_desc dg2_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xehpg, + .pre_gmdid_media_ip = &media_ip_xehpm, + .dma_mask_size = 46, + .max_gt_per_tile = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + + DG2_FEATURES, + .has_display = true, + .has_fan_control = true, + .has_mbx_power_limits = false, +}; + +static const __maybe_unused struct xe_device_desc pvc_desc = { + .pre_gmdid_graphics_ip = &graphics_ip_xehpc, + DGFX_FEATURES, + PLATFORM(PVC), + .dma_mask_size = 52, + .has_display = false, + .has_gsc_nvm = 1, + .has_heci_gscfi = 1, + .max_gt_per_tile = 1, + .max_remote_tiles = 1, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 57, + .vm_max_level = 4, + .vram_flags = XE_VRAM_FLAGS_NEED64K, + .has_mbx_power_limits = false, +}; + +static const struct xe_device_desc mtl_desc = { + /* .graphics and .media determined via GMD_ID */ + .require_force_probe = true, + PLATFORM(METEORLAKE), + .dma_mask_size = 46, + .has_display = true, + .has_pxp = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .va_bits = 48, + .vm_max_level = 3, +}; + +static const struct xe_device_desc lnl_desc = { + PLATFORM(LUNARLAKE), + .dma_mask_size = 46, + .has_display = true, + .has_flat_ccs = 1, + .has_pxp = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .needs_scratch = true, + .va_bits = 48, + .vm_max_level = 4, +}; + +static const u16 bmg_g21_ids[] = { INTEL_BMG_G21_IDS(NOP), 0 }; + +static const struct xe_device_desc bmg_desc = { + DGFX_FEATURES, + PLATFORM(BATTLEMAGE), + .dma_mask_size = 46, + .has_display = true, + .has_fan_control = true, + .has_flat_ccs = 1, + .has_mbx_power_limits = true, + .has_mbx_thermal_info = true, + .has_gsc_nvm = 1, + .has_heci_cscfi = 1, + .has_i2c = true, + .has_late_bind = true, + .has_pre_prod_wa = 1, + .has_soc_remapper_telem = true, + .has_sriov = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .needs_scratch = true, + .subplatforms = (const struct xe_subplatform_desc[]) { + { XE_SUBPLATFORM_BATTLEMAGE_G21, "G21", bmg_g21_ids }, + { } + }, + .va_bits = 48, + .vm_max_level = 4, +}; + +static const struct xe_device_desc ptl_desc = { + PLATFORM(PANTHERLAKE), + .dma_mask_size = 46, + .has_display = true, + .has_flat_ccs = 1, + .has_sriov = true, + .has_pre_prod_wa = 1, + .has_pxp = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .needs_scratch = true, + .needs_shared_vf_gt_wq = true, + .va_bits = 48, + .vm_max_level = 4, +}; + +static const struct xe_device_desc nvls_desc = { + PLATFORM(NOVALAKE_S), + .dma_mask_size = 46, + .has_display = true, + .has_flat_ccs = 1, + .has_pre_prod_wa = 1, + .has_sriov = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 4, +}; + +static const struct xe_device_desc cri_desc = { + DGFX_FEATURES, + PLATFORM(CRESCENTISLAND), + .dma_mask_size = 52, + .has_display = false, + .has_flat_ccs = false, + .has_gsc_nvm = 1, + .has_i2c = true, + .has_mbx_power_limits = true, + .has_mbx_thermal_info = true, + .has_mert = true, + .has_pre_prod_wa = 1, + .has_soc_remapper_sysctrl = true, + .has_soc_remapper_telem = true, + .has_sriov = true, + .has_sysctrl = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 57, + .vm_max_level = 4, +}; + +static const struct xe_device_desc nvlp_desc = { + PLATFORM(NOVALAKE_P), + .dma_mask_size = 46, + .has_cached_pt = true, + .has_display = true, + .has_flat_ccs = 1, + .has_page_reclaim_hw_assist = true, + .has_pre_prod_wa = true, + .has_sriov = true, + .max_gt_per_tile = 2, + MULTI_LRC_MASK, + .require_force_probe = true, + .va_bits = 48, + .vm_max_level = 4, +}; + +#undef PLATFORM +__diag_pop(); + +/* + * Make sure any device matches here are from most specific to most + * general. For example, since the Quanta match is based on the subsystem + * and subvendor IDs, we need it to come before the more general IVB + * PCI ID matches, otherwise we'll use the wrong info struct above. + */ +static const XE_PCI_ID_TYPE pciidlist[] = { + INTEL_TGL_IDS(INTEL_VGA_DEVICE, &tgl_desc), + INTEL_RKL_IDS(INTEL_VGA_DEVICE, &rkl_desc), + INTEL_ADLS_IDS(INTEL_VGA_DEVICE, &adl_s_desc), + INTEL_ADLP_IDS(INTEL_VGA_DEVICE, &adl_p_desc), + INTEL_ADLN_IDS(INTEL_VGA_DEVICE, &adl_n_desc), + INTEL_RPLU_IDS(INTEL_VGA_DEVICE, &adl_p_desc), + INTEL_RPLP_IDS(INTEL_VGA_DEVICE, &adl_p_desc), + INTEL_RPLS_IDS(INTEL_VGA_DEVICE, &adl_s_desc), + INTEL_DG1_IDS(INTEL_VGA_DEVICE, &dg1_desc), + INTEL_ATS_M_IDS(INTEL_VGA_DEVICE, &ats_m_desc), + INTEL_ARL_IDS(INTEL_VGA_DEVICE, &mtl_desc), + INTEL_DG2_IDS(INTEL_VGA_DEVICE, &dg2_desc), + INTEL_MTL_IDS(INTEL_VGA_DEVICE, &mtl_desc), + INTEL_LNL_IDS(INTEL_VGA_DEVICE, &lnl_desc), + INTEL_BMG_IDS(INTEL_VGA_DEVICE, &bmg_desc), + INTEL_PTL_IDS(INTEL_VGA_DEVICE, &ptl_desc), + INTEL_WCL_IDS(INTEL_VGA_DEVICE, &ptl_desc), + INTEL_NVLS_IDS(INTEL_VGA_DEVICE, &nvls_desc), + INTEL_CRI_IDS(INTEL_PCI_DEVICE, &cri_desc), + INTEL_NVLP_IDS(INTEL_VGA_DEVICE, &nvlp_desc), + { } +}; +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pci_runtime.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_runtime.h new file mode 100644 index 0000000000..d44ff5f065 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_runtime.h @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2021 Intel Corporation + */ +#ifndef XE_PCI_RUNTIME_H +#define XE_PCI_RUNTIME_H +static const struct xe_subplatform_desc * +find_subplatform(const struct xe_device_desc *desc, u16 devid) +{ + const struct xe_subplatform_desc *sp; + const u16 *id; + + for (sp = desc->subplatforms; sp && sp->subplatform; sp++) + for (id = sp->pciidlist; *id; id++) + if (*id == devid) + return sp; + + return NULL; +} + +static inline struct xe_reg xe_pci_gmdid_register(bool media) +{ + struct xe_reg reg = GMD_ID; + if (media) + reg.addr += MEDIA_GT_GSI_OFFSET; + return reg; +} + +static inline void xe_pci_decode_gmdid(u32 val, u32 *ver, u32 *revid) +{ + *ver = REG_FIELD_GET(GMD_ID_ARCH_MASK, val) * 100 + REG_FIELD_GET(GMD_ID_RELEASE_MASK, val); + *revid = REG_FIELD_GET(GMD_ID_REVID, val); +} + +static inline u8 xe_pci_runtime_tile_count(u8 maximum, u32 mtcfg) +{ + u8 tile_count = REG_FIELD_GET(TILE_COUNT, mtcfg) + 1; + return tile_count < maximum ? tile_count : maximum; +} + +static const struct xe_ip *find_graphics_ip(unsigned int verx100) +{ +#ifndef STELA_NATIVE + KUNIT_STATIC_STUB_REDIRECT(find_graphics_ip, verx100); +#endif + + for (int i = 0; i < ARRAY_SIZE(graphics_ips); i++) + if (graphics_ips[i].verx100 == verx100) + return &graphics_ips[i]; + return NULL; +} + +static const struct xe_ip *find_media_ip(unsigned int verx100) +{ +#ifndef STELA_NATIVE + KUNIT_STATIC_STUB_REDIRECT(find_media_ip, verx100); +#endif + + for (int i = 0; i < ARRAY_SIZE(media_ips); i++) + if (media_ips[i].verx100 == verx100) + return &media_ips[i]; + return NULL; +} + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pci_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_types.h index 5b85e2c24b..16d61c8fdb 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_pci_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pci_types.h @@ -6,10 +6,16 @@ #ifndef _XE_PCI_TYPES_H_ #define _XE_PCI_TYPES_H_ +#ifdef STELA_NATIVE +#include "xe_scalar_types.h" +#else #include +#endif #include "xe_platform_types.h" +#define XE_VRAM_FLAGS_NEED64K BIT(0) + struct xe_subplatform_desc { enum xe_subplatform subplatform; const char *name; diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_pt_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_pt_types.h index a7d1bb708b..dc9e839f68 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_pt_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_pt_types.h @@ -15,14 +15,7 @@ struct xe_bo; struct xe_device; struct xe_vma; -enum xe_cache_level { - XE_CACHE_NONE, - XE_CACHE_WT, - XE_CACHE_WB, - XE_CACHE_NONE_COMPRESSION, /*UC + COH_NONE + COMPRESSION */ - XE_CACHE_WB_COMPRESSION, - __XE_CACHE_LEVEL_COUNT, -}; +#include "xe_cache_level.h" #define XE_VM_MAX_LEVEL 4 diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_scalar_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_scalar_types.h new file mode 100644 index 0000000000..ef40859bbd --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_scalar_types.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef XE_SCALAR_TYPES_H +#define XE_SCALAR_TYPES_H +/* Fixed-width native definitions for retained pure types. No Linux services. */ +#include +#include +#include +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; +typedef int64_t s64; +#define BIT(n) (UINT64_C(1) << (n)) +#define GENMASK(h, l) ((UINT64_MAX << (l)) & (UINT64_MAX >> (63 - (h)))) +#define GENMASK_ULL(h, l) GENMASK(h, l) +#define SZ_4M (UINT32_C(4) * 1024 * 1024) +#define const_ilog2(n) (31 - __builtin_clz((unsigned)(n))) +#ifdef static_assert +#undef static_assert +#endif +#define static_assert(c) _Static_assert((c), #c) +#define REG_BIT(n) (UINT32_C(1) << (n)) +#define REG_GENMASK(h, l) ((UINT32_MAX << (l)) & (UINT32_MAX >> (31 - (h)))) +#define REG_FIELD_GET(mask, value) (((u32)(value) & (u32)(mask)) >> __builtin_ctz((u32)(mask))) +#define REG_FIELD_PREP(mask, value) (((u32)(value) << __builtin_ctz((u32)(mask))) & (u32)(mask)) +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw.c b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw.c index 3f08a3b540..0c59ecd46e 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw.c @@ -91,94 +91,7 @@ * This needs to be fixed when the major version of GuC is updated. */ -struct uc_fw_entry { - enum xe_platform platform; - enum xe_gt_type gt_type; - - struct { - const char *path; - u16 major; - u16 minor; - u16 patch; - bool full_ver_required; - }; -}; - -struct fw_blobs_by_type { - const struct uc_fw_entry *entries; - u32 count; -}; - -/* - * Add an "ANY" define just to convey the meaning it's given here. - */ -#define XE_GT_TYPE_ANY XE_GT_TYPE_UNINITIALIZED - -#define XE_GUC_FIRMWARE_DEFS(fw_def, mmp_ver, major_ver) \ - fw_def(PANTHERLAKE, GT_TYPE_ANY, major_ver(xe, guc, ptl, 70, 54, 0)) \ - fw_def(BATTLEMAGE, GT_TYPE_ANY, major_ver(xe, guc, bmg, 70, 54, 0)) \ - fw_def(LUNARLAKE, GT_TYPE_ANY, major_ver(xe, guc, lnl, 70, 53, 0)) \ - fw_def(METEORLAKE, GT_TYPE_ANY, major_ver(i915, guc, mtl, 70, 53, 0)) \ - fw_def(DG2, GT_TYPE_ANY, major_ver(i915, guc, dg2, 70, 53, 0)) \ - fw_def(DG1, GT_TYPE_ANY, major_ver(i915, guc, dg1, 70, 44, 1)) \ - fw_def(ALDERLAKE_N, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ - fw_def(ALDERLAKE_P, GT_TYPE_ANY, major_ver(i915, guc, adlp, 70, 44, 1)) \ - fw_def(ALDERLAKE_S, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ - fw_def(ROCKETLAKE, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ - fw_def(TIGERLAKE, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) - -#define XE_HUC_FIRMWARE_DEFS(fw_def, mmp_ver, no_ver) \ - fw_def(PANTHERLAKE, GT_TYPE_ANY, no_ver(xe, huc, ptl)) \ - fw_def(BATTLEMAGE, GT_TYPE_ANY, no_ver(xe, huc, bmg)) \ - fw_def(LUNARLAKE, GT_TYPE_ANY, no_ver(xe, huc, lnl)) \ - fw_def(METEORLAKE, GT_TYPE_ANY, no_ver(i915, huc_gsc, mtl)) \ - fw_def(DG1, GT_TYPE_ANY, no_ver(i915, huc, dg1)) \ - fw_def(ALDERLAKE_P, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ - fw_def(ALDERLAKE_S, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ - fw_def(ROCKETLAKE, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ - fw_def(TIGERLAKE, GT_TYPE_ANY, no_ver(i915, huc, tgl)) - -/* for the GSC FW we match the compatibility version and not the release one */ -#define XE_GSC_FIRMWARE_DEFS(fw_def, major_ver) \ - fw_def(PANTHERLAKE, GT_TYPE_ANY, major_ver(xe, gsc, ptl, 105, 1, 0)) \ - fw_def(LUNARLAKE, GT_TYPE_ANY, major_ver(xe, gsc, lnl, 104, 1, 0)) \ - fw_def(METEORLAKE, GT_TYPE_ANY, major_ver(i915, gsc, mtl, 102, 1, 0)) - -#define MAKE_FW_PATH(dir__, uc__, shortname__, version__) \ - __stringify(dir__) "/" __stringify(shortname__) "_" __stringify(uc__) version__ ".bin" - -#define fw_filename_mmp_ver(dir_, uc_, shortname_, a, b, c) \ - MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(a ## . ## b ## . ## c)) -#define fw_filename_major_ver(dir_, uc_, shortname_, a, b, c) \ - MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(a)) -#define fw_filename_no_ver(dir_, uc_, shortname_) \ - MAKE_FW_PATH(dir_, uc_, shortname_, "") -#define fw_filename_gsc(dir_, uc_, shortname_, a, b, c) \ - MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(b)) - -#define uc_fw_entry_mmp_ver(dir_, uc_, shortname_, a, b, c) \ - { fw_filename_mmp_ver(dir_, uc_, shortname_, a, b, c), \ - a, b, c, true } -#define uc_fw_entry_major_ver(dir_, uc_, shortname_, a, b, c) \ - { fw_filename_major_ver(dir_, uc_, shortname_, a, b, c), \ - a, b, c } -#define uc_fw_entry_no_ver(dir_, uc_, shortname_) \ - { fw_filename_no_ver(dir_, uc_, shortname_), \ - 0, 0 } -#define uc_fw_entry_gsc(dir_, uc_, shortname_, a, b, c) \ - { fw_filename_gsc(dir_, uc_, shortname_, a, b, c), \ - a, b, c } - -/* All blobs need to be declared via MODULE_FIRMWARE() */ -#define XE_UC_MODULE_FIRMWARE(platform__, gt_type__, fw_filename) \ - MODULE_FIRMWARE(fw_filename); - -#define XE_UC_FW_ENTRY(platform__, gt_type__, entry__) \ - { \ - .platform = XE_ ## platform__, \ - .gt_type = XE_ ## gt_type__, \ - entry__, \ - }, +#include "xe_uc_fw_catalog.h" XE_GUC_FIRMWARE_DEFS(XE_UC_MODULE_FIRMWARE, fw_filename_mmp_ver, fw_filename_major_ver) @@ -227,57 +140,11 @@ void xe_uc_fw_change_status(struct xe_uc_fw *uc_fw, enum xe_uc_fw_status status) static void uc_fw_auto_select(struct xe_device *xe, struct xe_uc_fw *uc_fw) { - static const struct uc_fw_entry entries_guc[] = { - XE_GUC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, - uc_fw_entry_mmp_ver, - uc_fw_entry_major_ver) - }; - static const struct uc_fw_entry entries_huc[] = { - XE_HUC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, - uc_fw_entry_mmp_ver, - uc_fw_entry_no_ver) - }; - static const struct uc_fw_entry entries_gsc[] = { - XE_GSC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, uc_fw_entry_gsc) - }; - static const struct fw_blobs_by_type blobs_all[XE_UC_FW_NUM_TYPES] = { - [XE_UC_FW_TYPE_GUC] = { entries_guc, ARRAY_SIZE(entries_guc) }, - [XE_UC_FW_TYPE_HUC] = { entries_huc, ARRAY_SIZE(entries_huc) }, - [XE_UC_FW_TYPE_GSC] = { entries_gsc, ARRAY_SIZE(entries_gsc) }, - }; struct xe_gt *gt = uc_fw_to_gt(uc_fw); - enum xe_platform p = xe->info.platform; - const struct uc_fw_entry *entries; - u32 count; - int i; - xe_gt_assert(gt, uc_fw->type < ARRAY_SIZE(blobs_all)); + xe_gt_assert(gt, uc_fw->type < XE_UC_FW_NUM_TYPES); xe_gt_assert(gt, gt->info.type != XE_GT_TYPE_UNINITIALIZED); - - entries = blobs_all[uc_fw->type].entries; - count = blobs_all[uc_fw->type].count; - - for (i = 0; i < count && p <= entries[i].platform; i++) { - if (p != entries[i].platform) - continue; - - if (entries[i].gt_type != XE_GT_TYPE_ANY && - entries[i].gt_type != gt->info.type) - continue; - - uc_fw->path = entries[i].path; - uc_fw->versions.wanted.major = entries[i].major; - uc_fw->versions.wanted.minor = entries[i].minor; - uc_fw->versions.wanted.patch = entries[i].patch; - uc_fw->full_ver_required = entries[i].full_ver_required; - - if (uc_fw->type == XE_UC_FW_TYPE_GSC) - uc_fw->versions.wanted_type = XE_UC_FW_VER_COMPATIBILITY; - else - uc_fw->versions.wanted_type = XE_UC_FW_VER_RELEASE; - - break; - } + xe_uc_fw_select_default(xe->info.platform, gt->info.type, uc_fw); } static void @@ -340,58 +207,29 @@ static void uc_fw_fini(struct drm_device *drm, void *arg) xe_uc_fw_change_status(uc_fw, XE_UC_FIRMWARE_SELECTED); } -static int guc_read_css_info(struct xe_uc_fw *uc_fw, struct uc_css_guc_info *guc_info) +#include "xe_uc_fw_css.h" + +static void css_report(void *context, enum xe_uc_fw_css_diagnostic reason, + const struct xe_uc_fw *uc_fw, size_t actual, size_t needed) { - struct xe_gt *gt = uc_fw_to_gt(uc_fw); - struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; - struct xe_uc_fw_version *compatibility = &uc_fw->versions.found[XE_UC_FW_VER_COMPATIBILITY]; + struct xe_device *xe = uc_fw_to_xe(context); + const struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; + const struct xe_uc_fw_version *wanted = &uc_fw->versions.wanted; + const struct xe_uc_fw_version *found = &uc_fw->versions.found[uc_fw->versions.wanted_type]; - xe_gt_assert(gt, uc_fw->type == XE_UC_FW_TYPE_GUC); - - /* We don't support GuC releases older than 70.29.2 */ - if (MAKE_GUC_VER_STRUCT(*release) < MAKE_GUC_VER(70, 29, 2)) { - xe_gt_err(gt, "Unsupported GuC v%u.%u.%u! v70.29.2 or newer is required\n", + switch (reason) { + case XE_UC_FW_CSS_GUC_TOO_OLD: + xe_gt_err(uc_fw_to_gt(context), + "Unsupported GuC v%u.%u.%u! v70.29.2 or newer is required\n", release->major, release->minor, release->patch); - return -EINVAL; - } - - compatibility->major = FIELD_GET(CSS_SW_VERSION_UC_MAJOR, guc_info->submission_version); - compatibility->minor = FIELD_GET(CSS_SW_VERSION_UC_MINOR, guc_info->submission_version); - compatibility->patch = FIELD_GET(CSS_SW_VERSION_UC_PATCH, guc_info->submission_version); - - uc_fw->build_type = FIELD_GET(CSS_UKERNEL_INFO_BUILDTYPE, guc_info->ukernel_info); - uc_fw->private_data_size = guc_info->private_data_size; - - return 0; -} - -int xe_uc_fw_check_version_requirements(struct xe_uc_fw *uc_fw) -{ - struct xe_device *xe = uc_fw_to_xe(uc_fw); - struct xe_uc_fw_version *wanted = &uc_fw->versions.wanted; - struct xe_uc_fw_version *found = &uc_fw->versions.found[uc_fw->versions.wanted_type]; - - /* Driver has no requirement on any version, any is good. */ - if (!wanted->major) - return 0; - - /* - * If full version is required, both major and minor should match. - * Otherwise, at least the major version. - */ - if (wanted->major != found->major || - (uc_fw->full_ver_required && - ((wanted->minor != found->minor) || - (wanted->patch != found->patch)))) { + break; + case XE_UC_FW_CSS_VERSION_MISMATCH: drm_notice(&xe->drm, "%s firmware %s: unexpected version: %u.%u.%u != %u.%u.%u\n", xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, found->major, found->minor, found->patch, wanted->major, wanted->minor, wanted->patch); - goto fail; - } - - if (wanted->minor > found->minor || - (wanted->minor == found->minor && wanted->patch > found->patch)) { + break; + case XE_UC_FW_CSS_RECOMMENDED_NEWER: drm_notice(&xe->drm, "%s firmware (%u.%u.%u) is recommended, but only (%u.%u.%u) was found in %s\n", xe_uc_fw_type_repr(uc_fw->type), wanted->major, wanted->minor, wanted->patch, @@ -399,179 +237,97 @@ int xe_uc_fw_check_version_requirements(struct xe_uc_fw *uc_fw) uc_fw->path); drm_info(&xe->drm, "Consider updating your linux-firmware pkg or downloading from %s\n", XE_UC_FIRMWARE_URL); + break; + case XE_UC_FW_CSS_HEADER_SIZE: + drm_warn(&xe->drm, + "%s firmware %s: unexpected header size: %zu != %zu\n", + xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, actual, needed); + break; + case XE_UC_FW_CSS_SHORT_HEADER: + case XE_UC_FW_CSS_SHORT_IMAGE: + drm_warn(&xe->drm, "%s firmware %s: invalid size: %zu < %zu\n", + xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, actual, needed); + break; } +} - return 0; +static void css_invariant(void *context, bool condition) +{ + xe_gt_assert(uc_fw_to_gt(context), condition); +} -fail: - if (xe_uc_fw_is_overridden(uc_fw)) - return 0; +static struct xe_uc_fw_css_ops css_ops(struct xe_uc_fw *uc_fw) +{ + return (struct xe_uc_fw_css_ops){uc_fw, css_report, css_invariant}; +} - return -ENOEXEC; +int xe_uc_fw_check_version_requirements(struct xe_uc_fw *uc_fw) +{ + struct xe_uc_fw_css_ops ops = css_ops(uc_fw); + + return xe_uc_fw_css_check_version(uc_fw, &ops); } /* Refer to the "CSS-based Firmware Layout" documentation entry for details */ static int parse_css_header(struct xe_uc_fw *uc_fw, const void *fw_data, size_t fw_size) { - struct xe_device *xe = uc_fw_to_xe(uc_fw); + struct xe_uc_fw_css_ops ops = css_ops(uc_fw); + + return xe_uc_fw_css_parse(uc_fw, fw_data, fw_size, &ops); +} + +#define XE_UC_FW_CPD_ENTRY_EQUAL(entry, name, bytes) ((void)(bytes), strcmp((const char *)(entry), (name)) == 0) +#include "xe_uc_fw_cpd.h" + +static void cpd_report(void *context, enum xe_uc_fw_cpd_diagnostic event, + const struct xe_uc_fw *uc_fw, size_t actual, size_t needed) +{ + struct xe_gt *gt = uc_fw_to_gt(context); + + switch (event) { + case XE_UC_FW_CPD_HEADER_LENGTH: + xe_gt_err(gt, "invalid CPD header length %u!\n", (unsigned int)actual); + break; + case XE_UC_FW_CPD_SHORT_IMAGE: + xe_gt_err(gt, "FW too small! %zu < %zu\n", actual, needed); + break; + case XE_UC_FW_CPD_MISSING_MANIFEST: + xe_gt_err(gt, "Failed to find %s manifest!\n", xe_uc_fw_type_repr(uc_fw->type)); + break; + } +} + +static int cpd_parse_css(void *context, struct xe_uc_fw *uc_fw, + const void *data, size_t size) +{ + xe_gt_assert(uc_fw_to_gt(context), context == uc_fw); + return parse_css_header(uc_fw, data, size); +} + +static void cpd_gsc_manifest(void *context, struct xe_uc_fw *uc_fw, + const struct gsc_manifest_header *manifest) +{ + struct xe_gsc *gsc = container_of(uc_fw, struct xe_gsc, fw); struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; - struct uc_css_header *css; - size_t size; - /* Check the size of the blob before examining buffer contents */ - if (unlikely(fw_size < sizeof(struct uc_css_header))) { - drm_warn(&xe->drm, "%s firmware %s: invalid size: %zu < %zu\n", - xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, - fw_size, sizeof(struct uc_css_header)); - return -ENODATA; - } - - css = (struct uc_css_header *)fw_data; - - /* Check integrity of size values inside CSS header */ - size = (css->header_size_dw - css->rsa_info.key_size_dw - css->rsa_info.modulus_size_dw - - css->rsa_info.exponent_size_dw) * sizeof(u32); - if (unlikely(size != sizeof(struct uc_css_header))) { - drm_warn(&xe->drm, - "%s firmware %s: unexpected header size: %zu != %zu\n", - xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, - fw_size, sizeof(struct uc_css_header)); - return -EPROTO; - } - - /* uCode size must calculated from other sizes */ - uc_fw->ucode_size = (css->size_dw - css->header_size_dw) * sizeof(u32); - - /* now RSA */ - uc_fw->rsa_size = css->rsa_info.key_size_dw * sizeof(u32); - - /* At least, it should have header, uCode and RSA. Size of all three. */ - size = sizeof(struct uc_css_header) + uc_fw->ucode_size + - uc_fw->rsa_size; - if (unlikely(fw_size < size)) { - drm_warn(&xe->drm, "%s firmware %s: invalid size: %zu < %zu\n", - xe_uc_fw_type_repr(uc_fw->type), uc_fw->path, - fw_size, size); - return -ENOEXEC; - } - - /* Get version numbers from the CSS header */ - release->major = FIELD_GET(CSS_SW_VERSION_UC_MAJOR, css->guc_info.sw_version); - release->minor = FIELD_GET(CSS_SW_VERSION_UC_MINOR, css->guc_info.sw_version); - release->patch = FIELD_GET(CSS_SW_VERSION_UC_PATCH, css->guc_info.sw_version); - - if (uc_fw->type == XE_UC_FW_TYPE_GUC) - return guc_read_css_info(uc_fw, &css->guc_info); - - return 0; -} - -static bool is_cpd_header(const void *data) -{ - const u32 *marker = data; - - return *marker == GSC_CPD_HEADER_MARKER; -} - -static u32 entry_offset(const struct gsc_cpd_header_v2 *header, const char *name) -{ - const struct gsc_cpd_entry *entry; - int i; - - entry = (void *)header + header->header_length; - - for (i = 0; i < header->num_of_entries; i++, entry++) - if (strcmp(entry->name, name) == 0) - return entry->offset & GSC_CPD_ENTRY_OFFSET_MASK; - - return 0; + xe_gt_assert(uc_fw_to_gt(context), context == uc_fw); + release->build = manifest->fw_version.build; + gsc->security_version = manifest->security_version; } /* Refer to the "GSC-based Firmware Layout" documentation entry for details */ static int parse_cpd_header(struct xe_uc_fw *uc_fw, const void *data, size_t size, const char *manifest_entry, const char *css_entry) { - struct xe_gt *gt = uc_fw_to_gt(uc_fw); - struct xe_device *xe = gt_to_xe(gt); - const struct gsc_cpd_header_v2 *header = data; - struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; - const struct gsc_manifest_header *manifest; - size_t min_size = sizeof(*header); - u32 offset; + const struct xe_uc_fw_cpd_ops ops = { + uc_fw, cpd_report, css_invariant, cpd_parse_css, cpd_gsc_manifest, + }; - /* manifest_entry is mandatory, css_entry is optional */ - xe_assert(xe, manifest_entry); - - if (size < min_size || !is_cpd_header(header)) - return -ENOENT; - - if (header->header_length < sizeof(struct gsc_cpd_header_v2)) { - xe_gt_err(gt, "invalid CPD header length %u!\n", header->header_length); - return -EINVAL; - } - - min_size = header->header_length + sizeof(struct gsc_cpd_entry) * header->num_of_entries; - if (size < min_size) { - xe_gt_err(gt, "FW too small! %zu < %zu\n", size, min_size); - return -ENODATA; - } - - /* Look for the manifest first */ - offset = entry_offset(header, manifest_entry); - if (!offset) { - xe_gt_err(gt, "Failed to find %s manifest!\n", - xe_uc_fw_type_repr(uc_fw->type)); - return -ENODATA; - } - - min_size = offset + sizeof(struct gsc_manifest_header); - if (size < min_size) { - xe_gt_err(gt, "FW too small! %zu < %zu\n", size, min_size); - return -ENODATA; - } - - manifest = data + offset; - - release->major = manifest->fw_version.major; - release->minor = manifest->fw_version.minor; - release->patch = manifest->fw_version.hotfix; - - if (uc_fw->type == XE_UC_FW_TYPE_GSC) { - struct xe_gsc *gsc = container_of(uc_fw, struct xe_gsc, fw); - - release->build = manifest->fw_version.build; - gsc->security_version = manifest->security_version; - } - - /* then optionally look for the css header */ - if (css_entry) { - int ret; - - /* - * This section does not contain a CSS entry on DG2. We - * don't support DG2 HuC right now, so no need to handle - * it, just add a reminder in case that changes. - */ - xe_assert(xe, xe->info.platform != XE_DG2); - - offset = entry_offset(header, css_entry); - - /* the CSS header parser will check that the CSS header fits */ - if (offset > size) { - xe_gt_err(gt, "FW too small! %zu < %u\n", size, offset); - return -ENODATA; - } - - ret = parse_css_header(uc_fw, data + offset, size - offset); - if (ret) - return ret; - - uc_fw->css_offset = offset; - } - - uc_fw->has_gsc_headers = true; - - return 0; + xe_assert(uc_fw_to_xe(uc_fw), manifest_entry); + return xe_uc_fw_cpd_parse(uc_fw, data, size, + manifest_entry, strlen(manifest_entry) + 1, + css_entry, css_entry ? strlen(css_entry) + 1 : 0, + uc_fw_to_xe(uc_fw)->info.platform, &ops); } static int parse_gsc_layout(struct xe_uc_fw *uc_fw, const void *data, size_t size) @@ -643,7 +399,9 @@ static int parse_gsc_layout(struct xe_uc_fw *uc_fw, const void *data, size_t siz static int parse_headers(struct xe_uc_fw *uc_fw, const struct firmware *fw) { - int ret; + const struct xe_uc_fw_cpd_ops ops = { + uc_fw, cpd_report, css_invariant, cpd_parse_css, cpd_gsc_manifest, + }; /* * All GuC releases and older HuC ones use CSS headers, while newer HuC @@ -653,10 +411,8 @@ static int parse_headers(struct xe_uc_fw *uc_fw, const struct firmware *fw) case XE_UC_FW_TYPE_GSC: return parse_gsc_layout(uc_fw, fw->data, fw->size); case XE_UC_FW_TYPE_HUC: - ret = parse_cpd_header(uc_fw, fw->data, fw->size, "HUCP.man", "huc_fw"); - if (!ret || ret != -ENOENT) - return ret; - fallthrough; + return xe_uc_fw_huc_parse(uc_fw, fw->data, fw->size, + uc_fw_to_xe(uc_fw)->info.platform, &ops); case XE_UC_FW_TYPE_GUC: return parse_css_header(uc_fw, fw->data, fw->size); default: diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_catalog.h b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_catalog.h new file mode 100644 index 0000000000..60323b01c9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_catalog.h @@ -0,0 +1,145 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_UC_FW_CATALOG_H +#define XE_UC_FW_CATALOG_H +struct uc_fw_entry { + enum xe_platform platform; + enum xe_gt_type gt_type; + + struct { + const char *path; + u16 major; + u16 minor; + u16 patch; + bool full_ver_required; + }; +}; + +struct fw_blobs_by_type { + const struct uc_fw_entry *entries; + u32 count; +}; + +/* + * Add an "ANY" define just to convey the meaning it's given here. + */ +#define XE_GT_TYPE_ANY XE_GT_TYPE_UNINITIALIZED + +#define XE_GUC_FIRMWARE_DEFS(fw_def, mmp_ver, major_ver) \ + fw_def(PANTHERLAKE, GT_TYPE_ANY, major_ver(xe, guc, ptl, 70, 54, 0)) \ + fw_def(BATTLEMAGE, GT_TYPE_ANY, major_ver(xe, guc, bmg, 70, 54, 0)) \ + fw_def(LUNARLAKE, GT_TYPE_ANY, major_ver(xe, guc, lnl, 70, 53, 0)) \ + fw_def(METEORLAKE, GT_TYPE_ANY, major_ver(i915, guc, mtl, 70, 53, 0)) \ + fw_def(DG2, GT_TYPE_ANY, major_ver(i915, guc, dg2, 70, 53, 0)) \ + fw_def(DG1, GT_TYPE_ANY, major_ver(i915, guc, dg1, 70, 44, 1)) \ + fw_def(ALDERLAKE_N, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ + fw_def(ALDERLAKE_P, GT_TYPE_ANY, major_ver(i915, guc, adlp, 70, 44, 1)) \ + fw_def(ALDERLAKE_S, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ + fw_def(ROCKETLAKE, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) \ + fw_def(TIGERLAKE, GT_TYPE_ANY, major_ver(i915, guc, tgl, 70, 44, 1)) + +#define XE_HUC_FIRMWARE_DEFS(fw_def, mmp_ver, no_ver) \ + fw_def(PANTHERLAKE, GT_TYPE_ANY, no_ver(xe, huc, ptl)) \ + fw_def(BATTLEMAGE, GT_TYPE_ANY, no_ver(xe, huc, bmg)) \ + fw_def(LUNARLAKE, GT_TYPE_ANY, no_ver(xe, huc, lnl)) \ + fw_def(METEORLAKE, GT_TYPE_ANY, no_ver(i915, huc_gsc, mtl)) \ + fw_def(DG1, GT_TYPE_ANY, no_ver(i915, huc, dg1)) \ + fw_def(ALDERLAKE_P, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ + fw_def(ALDERLAKE_S, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ + fw_def(ROCKETLAKE, GT_TYPE_ANY, no_ver(i915, huc, tgl)) \ + fw_def(TIGERLAKE, GT_TYPE_ANY, no_ver(i915, huc, tgl)) + +/* for the GSC FW we match the compatibility version and not the release one */ +#define XE_GSC_FIRMWARE_DEFS(fw_def, major_ver) \ + fw_def(PANTHERLAKE, GT_TYPE_ANY, major_ver(xe, gsc, ptl, 105, 1, 0)) \ + fw_def(LUNARLAKE, GT_TYPE_ANY, major_ver(xe, gsc, lnl, 104, 1, 0)) \ + fw_def(METEORLAKE, GT_TYPE_ANY, major_ver(i915, gsc, mtl, 102, 1, 0)) + +#define MAKE_FW_PATH(dir__, uc__, shortname__, version__) \ + __stringify(dir__) "/" __stringify(shortname__) "_" __stringify(uc__) version__ ".bin" + +#define fw_filename_mmp_ver(dir_, uc_, shortname_, a, b, c) \ + MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(a ## . ## b ## . ## c)) +#define fw_filename_major_ver(dir_, uc_, shortname_, a, b, c) \ + MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(a)) +#define fw_filename_no_ver(dir_, uc_, shortname_) \ + MAKE_FW_PATH(dir_, uc_, shortname_, "") +#define fw_filename_gsc(dir_, uc_, shortname_, a, b, c) \ + MAKE_FW_PATH(dir_, uc_, shortname_, "_" __stringify(b)) + +#define uc_fw_entry_mmp_ver(dir_, uc_, shortname_, a, b, c) \ + { fw_filename_mmp_ver(dir_, uc_, shortname_, a, b, c), \ + a, b, c, true } +#define uc_fw_entry_major_ver(dir_, uc_, shortname_, a, b, c) \ + { fw_filename_major_ver(dir_, uc_, shortname_, a, b, c), \ + a, b, c } +#define uc_fw_entry_no_ver(dir_, uc_, shortname_) \ + { fw_filename_no_ver(dir_, uc_, shortname_), \ + 0, 0 } +#define uc_fw_entry_gsc(dir_, uc_, shortname_, a, b, c) \ + { fw_filename_gsc(dir_, uc_, shortname_, a, b, c), \ + a, b, c } + +/* All blobs need to be declared via MODULE_FIRMWARE() */ +#define XE_UC_MODULE_FIRMWARE(platform__, gt_type__, fw_filename) \ + MODULE_FIRMWARE(fw_filename); + +#define XE_UC_FW_ENTRY(platform__, gt_type__, entry__) \ + { \ + .platform = XE_ ## platform__, \ + .gt_type = XE_ ## gt_type__, \ + entry__, \ + }, + +/* Caller retains original type/GT assertions or validates native inputs. */ +static inline void xe_uc_fw_select_default(enum xe_platform p, + enum xe_gt_type gt_type, struct xe_uc_fw *uc_fw) +{ + static const struct uc_fw_entry entries_guc[] = { + XE_GUC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, + uc_fw_entry_mmp_ver, + uc_fw_entry_major_ver) + }; + static const struct uc_fw_entry entries_huc[] = { + XE_HUC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, + uc_fw_entry_mmp_ver, + uc_fw_entry_no_ver) + }; + static const struct uc_fw_entry entries_gsc[] = { + XE_GSC_FIRMWARE_DEFS(XE_UC_FW_ENTRY, uc_fw_entry_gsc) + }; + static const struct fw_blobs_by_type blobs_all[XE_UC_FW_NUM_TYPES] = { + [XE_UC_FW_TYPE_GUC] = { entries_guc, ARRAY_SIZE(entries_guc) }, + [XE_UC_FW_TYPE_HUC] = { entries_huc, ARRAY_SIZE(entries_huc) }, + [XE_UC_FW_TYPE_GSC] = { entries_gsc, ARRAY_SIZE(entries_gsc) }, + }; + const struct uc_fw_entry *entries; + u32 count; + int i; + + entries = blobs_all[uc_fw->type].entries; + count = blobs_all[uc_fw->type].count; + + for (i = 0; i < count && p <= entries[i].platform; i++) { + if (p != entries[i].platform) + continue; + + if (entries[i].gt_type != XE_GT_TYPE_ANY && + entries[i].gt_type != gt_type) + continue; + + uc_fw->path = entries[i].path; + uc_fw->versions.wanted.major = entries[i].major; + uc_fw->versions.wanted.minor = entries[i].minor; + uc_fw->versions.wanted.patch = entries[i].patch; + uc_fw->full_ver_required = entries[i].full_ver_required; + + if (uc_fw->type == XE_UC_FW_TYPE_GSC) + uc_fw->versions.wanted_type = XE_UC_FW_VER_COMPATIBILITY; + else + uc_fw->versions.wanted_type = XE_UC_FW_VER_RELEASE; + + break; + } +} +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_cpd.h b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_cpd.h new file mode 100644 index 0000000000..812703cd27 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_cpd.h @@ -0,0 +1,144 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_UC_FW_CPD_H +#define XE_UC_FW_CPD_H +#ifndef XE_UC_FW_CPD_ENTRY_EQUAL +#error "CPD requires the actual caller's bounded name equality binding" +#endif +/* Original parser policy. No BO, load state, signature or device service. + * The original Linux caller retains real logging, assertions and GSC writes. + * Native callers must preflight input arithmetic/iteration before this core. */ +enum xe_uc_fw_cpd_diagnostic { + XE_UC_FW_CPD_HEADER_LENGTH, + XE_UC_FW_CPD_SHORT_IMAGE, + XE_UC_FW_CPD_MISSING_MANIFEST, +}; +struct xe_uc_fw_cpd_ops { + void *context; + void (*report)(void *, enum xe_uc_fw_cpd_diagnostic, const struct xe_uc_fw *, size_t, size_t); + void (*invariant)(void *, bool); + int (*parse_css)(void *, struct xe_uc_fw *, const void *, size_t); + void (*gsc_manifest)(void *, struct xe_uc_fw *, const struct gsc_manifest_header *); +}; +static bool is_cpd_header(const void *data) +{ + const struct gsc_cpd_header_v2 *header = data; + + return header->header_marker == GSC_CPD_HEADER_MARKER; +} + +static u32 entry_offset(const struct gsc_cpd_header_v2 *header, const char *name, size_t name_bytes) +{ + const struct gsc_cpd_entry *entry; + int i; + + entry = (void *)header + header->header_length; + + for (i = 0; i < header->num_of_entries; i++, entry++) + if (XE_UC_FW_CPD_ENTRY_EQUAL(entry->name, name, name_bytes)) + return entry->offset & GSC_CPD_ENTRY_OFFSET_MASK; + + return 0; +} + +/* Refer to the "GSC-based Firmware Layout" documentation entry for details */ +static int xe_uc_fw_cpd_parse(struct xe_uc_fw *uc_fw, const void *data, size_t size, + const char *manifest_entry, size_t manifest_bytes, + const char *css_entry, size_t css_bytes, enum xe_platform platform, + const struct xe_uc_fw_cpd_ops *ops) +{ + const struct gsc_cpd_header_v2 *header = data; + struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; + const struct gsc_manifest_header *manifest; + size_t min_size = sizeof(*header); + u32 offset; + + /* manifest_entry is mandatory, css_entry is optional */ + ops->invariant(ops->context, manifest_entry && manifest_bytes && manifest_bytes <= 12); + ops->invariant(ops->context, !css_entry || (css_bytes && css_bytes <= 12)); + + if (size < min_size || !is_cpd_header(header)) + return -ENOENT; + + if (header->header_length < sizeof(struct gsc_cpd_header_v2)) { + ops->report(ops->context, XE_UC_FW_CPD_HEADER_LENGTH, uc_fw, header->header_length, sizeof(*header)); + return -EINVAL; + } + + min_size = header->header_length + sizeof(struct gsc_cpd_entry) * header->num_of_entries; + if (size < min_size) { + ops->report(ops->context, XE_UC_FW_CPD_SHORT_IMAGE, uc_fw, size, min_size); + return -ENODATA; + } + + /* Look for the manifest first */ + offset = entry_offset(header, manifest_entry, manifest_bytes); + if (!offset) { + ops->report(ops->context, XE_UC_FW_CPD_MISSING_MANIFEST, uc_fw, 0, 0); + return -ENODATA; + } + + min_size = offset + sizeof(struct gsc_manifest_header); + if (size < min_size) { + ops->report(ops->context, XE_UC_FW_CPD_SHORT_IMAGE, uc_fw, size, min_size); + return -ENODATA; + } + + manifest = data + offset; + + release->major = manifest->fw_version.major; + release->minor = manifest->fw_version.minor; + release->patch = manifest->fw_version.hotfix; + + if (uc_fw->type == XE_UC_FW_TYPE_GSC) { + ops->invariant(ops->context, ops->gsc_manifest); + ops->gsc_manifest(ops->context, uc_fw, manifest); + } + + /* then optionally look for the css header */ + if (css_entry) { + int ret; + + /* + * This section does not contain a CSS entry on DG2. We + * don't support DG2 HuC right now, so no need to handle + * it, just add a reminder in case that changes. + */ + ops->invariant(ops->context, platform != XE_DG2); + + offset = entry_offset(header, css_entry, css_bytes); + + /* the CSS header parser will check that the CSS header fits */ + if (offset > size) { + ops->report(ops->context, XE_UC_FW_CPD_SHORT_IMAGE, uc_fw, size, offset); + return -ENODATA; + } + + ret = ops->parse_css(ops->context, uc_fw, data + offset, size - offset); + if (ret) + return ret; + + uc_fw->css_offset = offset; + } + + uc_fw->has_gsc_headers = true; + + return 0; +} + +/* Original HuC CPD-first dispatch. Only absent CPD falls through to CSS. */ +static int xe_uc_fw_huc_parse(struct xe_uc_fw *uc_fw, const void *data, size_t size, + enum xe_platform platform, const struct xe_uc_fw_cpd_ops *ops) +{ + int ret; + + ret = xe_uc_fw_cpd_parse(uc_fw, data, size, "HUCP.man", sizeof("HUCP.man"), + "huc_fw", sizeof("huc_fw"), platform, ops); + if (!ret || ret != -ENOENT) + return ret; + + return ops->parse_css(ops->context, uc_fw, data, size); +} + +#undef XE_UC_FW_CPD_ENTRY_EQUAL +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_css.h b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_css.h new file mode 100644 index 0000000000..76a76b0b3a --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_css.h @@ -0,0 +1,132 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2022 Intel Corporation + */ +#ifndef XE_UC_FW_CSS_H +#define XE_UC_FW_CSS_H +/* Required diagnostic/invariant adapters; the original caller retains real + * logging and GT assertions. No device, BO, status or OS service is emulated. */ +enum xe_uc_fw_css_diagnostic { + XE_UC_FW_CSS_GUC_TOO_OLD, + XE_UC_FW_CSS_VERSION_MISMATCH, + XE_UC_FW_CSS_RECOMMENDED_NEWER, + XE_UC_FW_CSS_SHORT_HEADER, + XE_UC_FW_CSS_HEADER_SIZE, + XE_UC_FW_CSS_SHORT_IMAGE, +}; +struct xe_uc_fw_css_ops { + void *context; + void (*report)(void *, enum xe_uc_fw_css_diagnostic, + const struct xe_uc_fw *, size_t, size_t); + void (*invariant)(void *, bool); +}; +static int xe_uc_fw_css_read_guc_info(struct xe_uc_fw *uc_fw, struct uc_css_guc_info *guc_info, + const struct xe_uc_fw_css_ops *ops) +{ + struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; + struct xe_uc_fw_version *compatibility = &uc_fw->versions.found[XE_UC_FW_VER_COMPATIBILITY]; + + ops->invariant(ops->context, uc_fw->type == XE_UC_FW_TYPE_GUC); + + /* We don't support GuC releases older than 70.29.2 */ + if (MAKE_GUC_VER_STRUCT(*release) < MAKE_GUC_VER(70, 29, 2)) { + ops->report(ops->context, XE_UC_FW_CSS_GUC_TOO_OLD, uc_fw, 0, 0); + return -EINVAL; + } + + compatibility->major = FIELD_GET(CSS_SW_VERSION_UC_MAJOR, guc_info->submission_version); + compatibility->minor = FIELD_GET(CSS_SW_VERSION_UC_MINOR, guc_info->submission_version); + compatibility->patch = FIELD_GET(CSS_SW_VERSION_UC_PATCH, guc_info->submission_version); + + uc_fw->build_type = FIELD_GET(CSS_UKERNEL_INFO_BUILDTYPE, guc_info->ukernel_info); + uc_fw->private_data_size = guc_info->private_data_size; + + return 0; +} + +static int xe_uc_fw_css_check_version(struct xe_uc_fw *uc_fw, + const struct xe_uc_fw_css_ops *ops) +{ + struct xe_uc_fw_version *wanted = &uc_fw->versions.wanted; + struct xe_uc_fw_version *found = &uc_fw->versions.found[uc_fw->versions.wanted_type]; + + /* Driver has no requirement on any version, any is good. */ + if (!wanted->major) + return 0; + + /* + * If full version is required, both major and minor should match. + * Otherwise, at least the major version. + */ + if (wanted->major != found->major || + (uc_fw->full_ver_required && + ((wanted->minor != found->minor) || + (wanted->patch != found->patch)))) { + ops->report(ops->context, XE_UC_FW_CSS_VERSION_MISMATCH, uc_fw, 0, 0); + goto fail; + } + + if (wanted->minor > found->minor || + (wanted->minor == found->minor && wanted->patch > found->patch)) { + ops->report(ops->context, XE_UC_FW_CSS_RECOMMENDED_NEWER, uc_fw, 0, 0); + } + + return 0; + +fail: + if (uc_fw->user_overridden) + return 0; + + return -ENOEXEC; +} + +static int xe_uc_fw_css_parse(struct xe_uc_fw *uc_fw, const void *fw_data, size_t fw_size, + const struct xe_uc_fw_css_ops *ops) +{ + struct xe_uc_fw_version *release = &uc_fw->versions.found[XE_UC_FW_VER_RELEASE]; + struct uc_css_header *css; + size_t size; + + /* Check the size of the blob before examining buffer contents */ + if (unlikely(fw_size < sizeof(struct uc_css_header))) { + ops->report(ops->context, XE_UC_FW_CSS_SHORT_HEADER, uc_fw, + fw_size, sizeof(struct uc_css_header)); + return -ENODATA; + } + + css = (struct uc_css_header *)fw_data; + + /* Check integrity of size values inside CSS header */ + size = (css->header_size_dw - css->rsa_info.key_size_dw - css->rsa_info.modulus_size_dw - + css->rsa_info.exponent_size_dw) * sizeof(u32); + if (unlikely(size != sizeof(struct uc_css_header))) { + ops->report(ops->context, XE_UC_FW_CSS_HEADER_SIZE, uc_fw, + fw_size, sizeof(struct uc_css_header)); + return -EPROTO; + } + + /* uCode size must calculated from other sizes */ + uc_fw->ucode_size = (css->size_dw - css->header_size_dw) * sizeof(u32); + + /* now RSA */ + uc_fw->rsa_size = css->rsa_info.key_size_dw * sizeof(u32); + + /* At least, it should have header, uCode and RSA. Size of all three. */ + size = sizeof(struct uc_css_header) + uc_fw->ucode_size + + uc_fw->rsa_size; + if (unlikely(fw_size < size)) { + ops->report(ops->context, XE_UC_FW_CSS_SHORT_IMAGE, uc_fw, fw_size, size); + return -ENOEXEC; + } + + /* Get version numbers from the CSS header */ + release->major = FIELD_GET(CSS_SW_VERSION_UC_MAJOR, css->guc_info.sw_version); + release->minor = FIELD_GET(CSS_SW_VERSION_UC_MINOR, css->guc_info.sw_version); + release->patch = FIELD_GET(CSS_SW_VERSION_UC_PATCH, css->guc_info.sw_version); + + if (uc_fw->type == XE_UC_FW_TYPE_GUC) + return xe_uc_fw_css_read_guc_info(uc_fw, &css->guc_info, ops); + + return 0; +} +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_types.h index 2ebe8c9db6..7f0f1691c7 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_types.h @@ -6,7 +6,11 @@ #ifndef _XE_UC_FW_TYPES_H_ #define _XE_UC_FW_TYPES_H_ +#ifdef STELA_NATIVE +#include "xe_scalar_types.h" +#else #include +#endif struct xe_bo; diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_version.h b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_version.h new file mode 100644 index 0000000000..bc8e37e534 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_uc_fw_version.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_UC_FW_VERSION_H +#define XE_UC_FW_VERSION_H +/* + * GuC version number components are defined to be only 8-bit size, + * so converting to a 32bit 8.8.8 integer allows simple (and safe) + * numerical comparisons. + */ +#define MAKE_GUC_VER(maj, min, pat) (((maj) << 16) | ((min) << 8) | (pat)) +#define MAKE_GUC_VER_STRUCT(ver) MAKE_GUC_VER((ver).major, (ver).minor, (ver).patch) +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm.c b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm.c index fe65ed2467..1ca94cf8eb 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm.c +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm.c @@ -48,27 +48,6 @@ * context). */ -/* Default WOPCM size is 2MB from Gen11, 1MB on previous platforms */ -/* FIXME: Larger size require for some platforms, do a proper probe sooner or later */ -#define DGFX_WOPCM_SIZE SZ_4M -#define LNL_WOPCM_SIZE SZ_8M -#define MTL_WOPCM_SIZE SZ_4M -#define WOPCM_SIZE SZ_2M - -/* 16KB WOPCM (RSVD WOPCM) is reserved from HuC firmware top. */ -#define WOPCM_RESERVED_SIZE SZ_16K - -/* 16KB reserved at the beginning of GuC WOPCM. */ -#define GUC_WOPCM_RESERVED SZ_16K -/* 8KB from GUC_WOPCM_RESERVED is reserved for GuC stack. */ -#define GUC_WOPCM_STACK_RESERVED SZ_8K - -/* GuC WOPCM Offset value needs to be aligned to 16KB. */ -#define GUC_WOPCM_OFFSET_ALIGNMENT (1UL << GUC_WOPCM_OFFSET_SHIFT) - -/* 36KB WOPCM reserved at the end of WOPCM */ -#define WOPCM_HW_CTX_RESERVED (SZ_32K + SZ_4K) - static inline struct xe_gt *wopcm_to_gt(struct xe_wopcm *wopcm) { return container_of(wopcm, struct xe_gt, uc.wopcm); @@ -79,209 +58,89 @@ static inline struct xe_device *wopcm_to_xe(struct xe_wopcm *wopcm) return gt_to_xe(wopcm_to_gt(wopcm)); } -static u32 context_reserved_size(void) +#define XE_WOPCM_WARN(core, id, condition) XE_WARN_ON(condition) +#include "xe_wopcm_core.h" + +static u32 wopcm_read32(void *context, struct xe_reg reg) { - return WOPCM_HW_CTX_RESERVED; + return xe_mmio_read32(&wopcm_to_gt(context)->mmio, reg); } -static bool __check_layout(struct xe_device *xe, u32 wopcm_size, - u32 guc_wopcm_base, u32 guc_wopcm_size, - u32 guc_fw_size, u32 huc_fw_size) +static int wopcm_write32_and_verify(void *context, struct xe_reg reg, + u32 val, u32 mask, u32 eval) { - const u32 ctx_rsvd = context_reserved_size(); - u32 size; + return xe_mmio_write32_and_verify(&wopcm_to_gt(context)->mmio, reg, val, mask, eval); +} - size = wopcm_size - ctx_rsvd; - if (unlikely(guc_wopcm_base >= size || - guc_wopcm_size > size - guc_wopcm_base)) { - drm_err(&xe->drm, - "WOPCM: invalid GuC region layout: %uK + %uK > %uK\n", - guc_wopcm_base / SZ_1K, guc_wopcm_size / SZ_1K, - size / SZ_1K); - return false; - } +static bool wopcm_huc_available(void *context) +{ + return xe_uc_fw_is_available(&wopcm_to_gt(context)->uc.huc.fw); +} - size = guc_fw_size + GUC_WOPCM_RESERVED + GUC_WOPCM_STACK_RESERVED; - if (unlikely(guc_wopcm_size < size)) { +static void wopcm_assert_held(void *context) +{ + xe_force_wake_assert_held(gt_to_fw(wopcm_to_gt(context)), XE_FW_GT); +} + +static void wopcm_report(void *context, enum xe_wopcm_event event, u32 a, u32 b, u32 c) +{ + struct xe_device *xe = wopcm_to_xe(context); + + switch (event) { + case XE_WOPCM_INVALID_LAYOUT: + drm_err(&xe->drm, "WOPCM: invalid GuC region layout: %uK + %uK > %uK\n", + a / SZ_1K, b / SZ_1K, c / SZ_1K); + break; + case XE_WOPCM_GUC_SPACE: drm_err(&xe->drm, "WOPCM: no space for %s: %uK < %uK\n", - xe_uc_fw_type_repr(XE_UC_FW_TYPE_GUC), - guc_wopcm_size / SZ_1K, size / SZ_1K); - return false; - } - - size = huc_fw_size + WOPCM_RESERVED_SIZE; - if (unlikely(guc_wopcm_base < size)) { + xe_uc_fw_type_repr(XE_UC_FW_TYPE_GUC), a / SZ_1K, b / SZ_1K); + break; + case XE_WOPCM_HUC_SPACE: drm_err(&xe->drm, "WOPCM: no space for %s: %uK < %uK\n", - xe_uc_fw_type_repr(XE_UC_FW_TYPE_HUC), - guc_wopcm_base / SZ_1K, size / SZ_1K); - return false; + xe_uc_fw_type_repr(XE_UC_FW_TYPE_HUC), a / SZ_1K, b / SZ_1K); + break; + case XE_WOPCM_INIT_FAILED: + drm_notice(&xe->drm, "Failed to init uC WOPCM registers!\n"); + break; + case XE_WOPCM_OFFSET_READBACK: + drm_notice(&xe->drm, "%s(%#x)=%#x\n", "DMA_GUC_WOPCM_OFFSET", a, b); + break; + case XE_WOPCM_SIZE_READBACK: + drm_notice(&xe->drm, "%s(%#x)=%#x\n", "GUC_WOPCM_SIZE", a, b); + break; + case XE_WOPCM_TOTAL: + drm_dbg(&xe->drm, "WOPCM: %uK\n", a / SZ_1K); + break; + case XE_WOPCM_LOCKED: + drm_dbg(&xe->drm, "GuC WOPCM is already locked [%uK, %uK)\n", a / SZ_1K, b / SZ_1K); + break; + case XE_WOPCM_CALCULATED: + drm_dbg(&xe->drm, "Calculated GuC WOPCM [%uK, %uK)\n", a / SZ_1K, b / SZ_1K); + break; + case XE_WOPCM_PARTITION_FAILED: + drm_notice(&xe->drm, "Unsuccessful WOPCM partitioning\n"); + break; } - - return true; -} - -static bool __wopcm_regs_locked(struct xe_gt *gt, - u32 *guc_wopcm_base, u32 *guc_wopcm_size) -{ - u32 reg_base = xe_mmio_read32(>->mmio, DMA_GUC_WOPCM_OFFSET); - u32 reg_size = xe_mmio_read32(>->mmio, GUC_WOPCM_SIZE); - - if (!(reg_size & GUC_WOPCM_SIZE_LOCKED) || - !(reg_base & GUC_WOPCM_OFFSET_VALID)) - return false; - - *guc_wopcm_base = reg_base & GUC_WOPCM_OFFSET_MASK; - *guc_wopcm_size = reg_size & GUC_WOPCM_SIZE_MASK; - return true; -} - -static int __wopcm_init_regs(struct xe_device *xe, struct xe_gt *gt, - struct xe_wopcm *wopcm) -{ - u32 base = wopcm->guc.base; - u32 size = wopcm->guc.size; - u32 huc_agent = xe_uc_fw_is_available(>->uc.huc.fw) ? HUC_LOADING_AGENT_GUC : 0; - u32 mask; - int err; - - XE_WARN_ON(!(base & GUC_WOPCM_OFFSET_MASK)); - XE_WARN_ON(base & ~GUC_WOPCM_OFFSET_MASK); - XE_WARN_ON(!(size & GUC_WOPCM_SIZE_MASK)); - XE_WARN_ON(size & ~GUC_WOPCM_SIZE_MASK); - - mask = GUC_WOPCM_SIZE_MASK | GUC_WOPCM_SIZE_LOCKED; - err = xe_mmio_write32_and_verify(>->mmio, GUC_WOPCM_SIZE, size, mask, - size | GUC_WOPCM_SIZE_LOCKED); - if (err) - goto err_out; - - mask = GUC_WOPCM_OFFSET_MASK | GUC_WOPCM_OFFSET_VALID | huc_agent; - err = xe_mmio_write32_and_verify(>->mmio, DMA_GUC_WOPCM_OFFSET, - base | huc_agent, mask, - base | huc_agent | - GUC_WOPCM_OFFSET_VALID); - if (err) - goto err_out; - - return 0; - -err_out: - drm_notice(&xe->drm, "Failed to init uC WOPCM registers!\n"); - drm_notice(&xe->drm, "%s(%#x)=%#x\n", "DMA_GUC_WOPCM_OFFSET", - DMA_GUC_WOPCM_OFFSET.addr, - xe_mmio_read32(>->mmio, DMA_GUC_WOPCM_OFFSET)); - drm_notice(&xe->drm, "%s(%#x)=%#x\n", "GUC_WOPCM_SIZE", - GUC_WOPCM_SIZE.addr, - xe_mmio_read32(>->mmio, GUC_WOPCM_SIZE)); - - return err; } u32 xe_wopcm_size(struct xe_device *xe) { - if (xe->info.platform >= XE_LUNARLAKE) - return LNL_WOPCM_SIZE; - else if (IS_DGFX(xe)) - return DGFX_WOPCM_SIZE; - else if (xe->info.platform == XE_METEORLAKE) - return MTL_WOPCM_SIZE; - else - return WOPCM_SIZE; + return xe_wopcm_default_size(xe->info.platform, IS_DGFX(xe)); } -static u32 max_wopcm_size(struct xe_device *xe) -{ - if (xe->info.platform == XE_NOVALAKE_P) - return SZ_16M; - else - return SZ_8M; -} - -/** - * xe_wopcm_init() - Initialize the WOPCM structure. - * @wopcm: pointer to xe_wopcm. - * - * This function will partition WOPCM space based on GuC and HuC firmware sizes - * and will allocate max remaining for use by GuC. This function will also - * enforce platform dependent hardware restrictions on GuC WOPCM offset and - * size. It will fail the WOPCM init if any of these checks fail, so that the - * following WOPCM registers setup and GuC firmware uploading would be aborted. - */ int xe_wopcm_init(struct xe_wopcm *wopcm) { struct xe_device *xe = wopcm_to_xe(wopcm); struct xe_gt *gt = wopcm_to_gt(wopcm); u32 guc_fw_size = xe_uc_fw_get_upload_size(>->uc.guc.fw); u32 huc_fw_size = xe_uc_fw_get_upload_size(>->uc.huc.fw); - u32 ctx_rsvd = context_reserved_size(); - u32 guc_wopcm_base; - u32 guc_wopcm_size; - bool locked; - int ret = 0; + static const struct xe_wopcm_core_ops ops = { + wopcm_read32, wopcm_write32_and_verify, wopcm_huc_available, + wopcm_assert_held, wopcm_report, + }; + const struct xe_wopcm_core core = {wopcm, &ops}; - if (!guc_fw_size) - return -EINVAL; - - wopcm->size = xe_wopcm_size(xe); - drm_dbg(&xe->drm, "WOPCM: %uK\n", wopcm->size / SZ_1K); - - xe_force_wake_assert_held(gt_to_fw(gt), XE_FW_GT); - XE_WARN_ON(guc_fw_size >= wopcm->size); - XE_WARN_ON(huc_fw_size >= wopcm->size); - XE_WARN_ON(ctx_rsvd + WOPCM_RESERVED_SIZE >= wopcm->size); - - locked = __wopcm_regs_locked(gt, &guc_wopcm_base, &guc_wopcm_size); - if (locked) { - drm_dbg(&xe->drm, "GuC WOPCM is already locked [%uK, %uK)\n", - guc_wopcm_base / SZ_1K, guc_wopcm_size / SZ_1K); - /* - * When the GuC wopcm base and size are preprogrammed by - * BIOS/IFWI, check against the max allowed wopcm size to - * validate if the programmed values align to the wopcm layout. - * - * FIXME: This is giving the maximum overall WOPCM size and not - * the size relative to each GT. - */ - wopcm->size = max_wopcm_size(xe); - - goto check; - } - - /* - * Aligned value of guc_wopcm_base will determine available WOPCM space - * for HuC firmware and mandatory reserved area. - */ - guc_wopcm_base = huc_fw_size + WOPCM_RESERVED_SIZE; - guc_wopcm_base = ALIGN(guc_wopcm_base, GUC_WOPCM_OFFSET_ALIGNMENT); - - /* - * Need to clamp guc_wopcm_base now to make sure the following math is - * correct. Formal check of whole WOPCM layout will be done below. - */ - guc_wopcm_base = min(guc_wopcm_base, wopcm->size - ctx_rsvd); - - /* Aligned remainings of usable WOPCM space can be assigned to GuC. */ - guc_wopcm_size = wopcm->size - ctx_rsvd - guc_wopcm_base; - guc_wopcm_size &= GUC_WOPCM_SIZE_MASK; - - drm_dbg(&xe->drm, "Calculated GuC WOPCM [%uK, %uK)\n", - guc_wopcm_base / SZ_1K, guc_wopcm_size / SZ_1K); - -check: - if (__check_layout(xe, wopcm->size, guc_wopcm_base, guc_wopcm_size, - guc_fw_size, huc_fw_size)) { - wopcm->guc.base = guc_wopcm_base; - wopcm->guc.size = guc_wopcm_size; - XE_WARN_ON(!wopcm->guc.base); - XE_WARN_ON(!wopcm->guc.size); - } else { - drm_notice(&xe->drm, "Unsuccessful WOPCM partitioning\n"); - return -E2BIG; - } - - if (!locked) - ret = __wopcm_init_regs(xe, gt, wopcm); - - return ret; + return xe_wopcm_core_init(wopcm, xe->info.platform, IS_DGFX(xe), + guc_fw_size, huc_fw_size, &core); } ALLOW_ERROR_INJECTION(xe_wopcm_init, ERRNO); /* See xe_pci_probe() */ diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_core.h b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_core.h new file mode 100644 index 0000000000..e42b7b1d7f --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_core.h @@ -0,0 +1,230 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_WOPCM_CORE_H +#define XE_WOPCM_CORE_H +#ifndef XE_WOPCM_WARN +#error "WOPCM requires the real caller warning binding" +#endif +/* Original WOPCM policy, with mandatory real context/diagnostic operations. + * The caller retains exclusive serialization and acknowledged GT forcewake. + * No default operations or firmware availability state are supplied here. */ +enum xe_wopcm_event { + XE_WOPCM_INVALID_LAYOUT, XE_WOPCM_GUC_SPACE, XE_WOPCM_HUC_SPACE, + XE_WOPCM_INIT_FAILED, XE_WOPCM_OFFSET_READBACK, XE_WOPCM_SIZE_READBACK, + XE_WOPCM_TOTAL, XE_WOPCM_LOCKED, XE_WOPCM_CALCULATED, XE_WOPCM_PARTITION_FAILED, +}; +struct xe_wopcm_core_ops { + u32 (*read32)(void *, struct xe_reg); + int (*write32_and_verify)(void *, struct xe_reg, u32, u32, u32); + bool (*huc_available)(void *); + void (*assert_held)(void *); + void (*report)(void *, enum xe_wopcm_event, u32, u32, u32); +}; +struct xe_wopcm_core { + void *context; + const struct xe_wopcm_core_ops *ops; +}; +static inline void xe_wopcm_core_report(const struct xe_wopcm_core *core, + enum xe_wopcm_event event, u32 a, u32 b, u32 c) +{ + core->ops->report(core->context, event, a, b, c); +} +#include "xe_wopcm_size.h" + +/* 16KB WOPCM (RSVD WOPCM) is reserved from HuC firmware top. */ +#define WOPCM_RESERVED_SIZE SZ_16K + +/* 16KB reserved at the beginning of GuC WOPCM. */ +#define GUC_WOPCM_RESERVED SZ_16K +/* 8KB from GUC_WOPCM_RESERVED is reserved for GuC stack. */ +#define GUC_WOPCM_STACK_RESERVED SZ_8K + +/* GuC WOPCM Offset value needs to be aligned to 16KB. */ +#define GUC_WOPCM_OFFSET_ALIGNMENT (1UL << GUC_WOPCM_OFFSET_SHIFT) + +/* 36KB WOPCM reserved at the end of WOPCM */ +#define WOPCM_HW_CTX_RESERVED (SZ_32K + SZ_4K) + +static u32 context_reserved_size(void) +{ + return WOPCM_HW_CTX_RESERVED; +} + +static bool __check_layout(const struct xe_wopcm_core *core, u32 wopcm_size, + u32 guc_wopcm_base, u32 guc_wopcm_size, + u32 guc_fw_size, u32 huc_fw_size) +{ + const u32 ctx_rsvd = context_reserved_size(); + u32 size; + + size = wopcm_size - ctx_rsvd; + if (unlikely(guc_wopcm_base >= size || + guc_wopcm_size > size - guc_wopcm_base)) { + xe_wopcm_core_report(core, XE_WOPCM_INVALID_LAYOUT, guc_wopcm_base, guc_wopcm_size, size); + return false; + } + + size = guc_fw_size + GUC_WOPCM_RESERVED + GUC_WOPCM_STACK_RESERVED; + if (unlikely(guc_wopcm_size < size)) { + xe_wopcm_core_report(core, XE_WOPCM_GUC_SPACE, guc_wopcm_size, size, 0); + return false; + } + + size = huc_fw_size + WOPCM_RESERVED_SIZE; + if (unlikely(guc_wopcm_base < size)) { + xe_wopcm_core_report(core, XE_WOPCM_HUC_SPACE, guc_wopcm_base, size, 0); + return false; + } + + return true; +} + +static bool __wopcm_regs_locked(const struct xe_wopcm_core *core, + u32 *guc_wopcm_base, u32 *guc_wopcm_size) +{ + u32 reg_base = core->ops->read32(core->context, DMA_GUC_WOPCM_OFFSET); + u32 reg_size = core->ops->read32(core->context, GUC_WOPCM_SIZE); + + if (!(reg_size & GUC_WOPCM_SIZE_LOCKED) || + !(reg_base & GUC_WOPCM_OFFSET_VALID)) + return false; + + *guc_wopcm_base = reg_base & GUC_WOPCM_OFFSET_MASK; + *guc_wopcm_size = reg_size & GUC_WOPCM_SIZE_MASK; + return true; +} + +static int __wopcm_init_regs(const struct xe_wopcm_core *core, + struct xe_wopcm *wopcm) +{ + u32 base = wopcm->guc.base; + u32 size = wopcm->guc.size; + u32 huc_agent = core->ops->huc_available(core->context) ? HUC_LOADING_AGENT_GUC : 0; + u32 mask; + int err; + + XE_WOPCM_WARN(core, 0, !(base & GUC_WOPCM_OFFSET_MASK)); + XE_WOPCM_WARN(core, 1, base & ~GUC_WOPCM_OFFSET_MASK); + XE_WOPCM_WARN(core, 2, !(size & GUC_WOPCM_SIZE_MASK)); + XE_WOPCM_WARN(core, 3, size & ~GUC_WOPCM_SIZE_MASK); + + mask = GUC_WOPCM_SIZE_MASK | GUC_WOPCM_SIZE_LOCKED; + err = core->ops->write32_and_verify(core->context, GUC_WOPCM_SIZE, size, mask, + size | GUC_WOPCM_SIZE_LOCKED); + if (err) + goto err_out; + + mask = GUC_WOPCM_OFFSET_MASK | GUC_WOPCM_OFFSET_VALID | huc_agent; + err = core->ops->write32_and_verify(core->context, DMA_GUC_WOPCM_OFFSET, + base | huc_agent, mask, + base | huc_agent | + GUC_WOPCM_OFFSET_VALID); + if (err) + goto err_out; + + return 0; + +err_out: + xe_wopcm_core_report(core, XE_WOPCM_INIT_FAILED, 0, 0, 0); + xe_wopcm_core_report(core, XE_WOPCM_OFFSET_READBACK, DMA_GUC_WOPCM_OFFSET.addr, + core->ops->read32(core->context, DMA_GUC_WOPCM_OFFSET), 0); + xe_wopcm_core_report(core, XE_WOPCM_SIZE_READBACK, GUC_WOPCM_SIZE.addr, + core->ops->read32(core->context, GUC_WOPCM_SIZE), 0); + + return err; +} + + +static u32 max_wopcm_size(enum xe_platform platform) +{ + if (platform == XE_NOVALAKE_P) + return SZ_16M; + else + return SZ_8M; +} + +/** + * xe_wopcm_init() - Initialize the WOPCM structure. + * @wopcm: pointer to xe_wopcm. + * + * This function will partition WOPCM space based on GuC and HuC firmware sizes + * and will allocate max remaining for use by GuC. This function will also + * enforce platform dependent hardware restrictions on GuC WOPCM offset and + * size. It will fail the WOPCM init if any of these checks fail, so that the + * following WOPCM registers setup and GuC firmware uploading would be aborted. + */ +static int xe_wopcm_core_init(struct xe_wopcm *wopcm, enum xe_platform platform, + bool discrete, u32 guc_fw_size, u32 huc_fw_size, + const struct xe_wopcm_core *core) +{ + u32 ctx_rsvd = context_reserved_size(); + u32 guc_wopcm_base; + u32 guc_wopcm_size; + bool locked; + int ret = 0; + + if (!guc_fw_size) + return -EINVAL; + + wopcm->size = xe_wopcm_default_size(platform, discrete); + xe_wopcm_core_report(core, XE_WOPCM_TOTAL, wopcm->size, 0, 0); + + core->ops->assert_held(core->context); + XE_WOPCM_WARN(core, 4, guc_fw_size >= wopcm->size); + XE_WOPCM_WARN(core, 5, huc_fw_size >= wopcm->size); + XE_WOPCM_WARN(core, 6, ctx_rsvd + WOPCM_RESERVED_SIZE >= wopcm->size); + + locked = __wopcm_regs_locked(core, &guc_wopcm_base, &guc_wopcm_size); + if (locked) { + xe_wopcm_core_report(core, XE_WOPCM_LOCKED, guc_wopcm_base, guc_wopcm_size, 0); + /* + * When the GuC wopcm base and size are preprogrammed by + * BIOS/IFWI, check against the max allowed wopcm size to + * validate if the programmed values align to the wopcm layout. + * + * FIXME: This is giving the maximum overall WOPCM size and not + * the size relative to each GT. + */ + wopcm->size = max_wopcm_size(platform); + + goto check; + } + + /* + * Aligned value of guc_wopcm_base will determine available WOPCM space + * for HuC firmware and mandatory reserved area. + */ + guc_wopcm_base = huc_fw_size + WOPCM_RESERVED_SIZE; + guc_wopcm_base = ALIGN(guc_wopcm_base, GUC_WOPCM_OFFSET_ALIGNMENT); + + /* + * Need to clamp guc_wopcm_base now to make sure the following math is + * correct. Formal check of whole WOPCM layout will be done below. + */ + guc_wopcm_base = min(guc_wopcm_base, wopcm->size - ctx_rsvd); + + /* Aligned remainings of usable WOPCM space can be assigned to GuC. */ + guc_wopcm_size = wopcm->size - ctx_rsvd - guc_wopcm_base; + guc_wopcm_size &= GUC_WOPCM_SIZE_MASK; + + xe_wopcm_core_report(core, XE_WOPCM_CALCULATED, guc_wopcm_base, guc_wopcm_size, 0); + +check: + if (__check_layout(core, wopcm->size, guc_wopcm_base, guc_wopcm_size, + guc_fw_size, huc_fw_size)) { + wopcm->guc.base = guc_wopcm_base; + wopcm->guc.size = guc_wopcm_size; + XE_WOPCM_WARN(core, 7, !wopcm->guc.base); + XE_WOPCM_WARN(core, 8, !wopcm->guc.size); + } else { + xe_wopcm_core_report(core, XE_WOPCM_PARTITION_FAILED, 0, 0, 0); + return -E2BIG; + } + + if (!locked) + ret = __wopcm_init_regs(core, wopcm); + + return ret; +} +#undef XE_WOPCM_WARN +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_size.h b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_size.h new file mode 100644 index 0000000000..ddff1a56d0 --- /dev/null +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_size.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: MIT */ +/* Copyright © 2022 Intel Corporation */ +#ifndef XE_WOPCM_SIZE_H +#define XE_WOPCM_SIZE_H +/* Default WOPCM size is 2MB from Gen11, 1MB on previous platforms */ +/* FIXME: Larger size require for some platforms, do a proper probe sooner or later */ +#define DGFX_WOPCM_SIZE SZ_4M +#define LNL_WOPCM_SIZE SZ_8M +#define MTL_WOPCM_SIZE SZ_4M +#define WOPCM_SIZE SZ_2M + +static inline u32 xe_wopcm_default_size(enum xe_platform platform, bool discrete) +{ + if (platform >= XE_LUNARLAKE) + return LNL_WOPCM_SIZE; + else if (discrete) + return DGFX_WOPCM_SIZE; + else if (platform == XE_METEORLAKE) + return MTL_WOPCM_SIZE; + else + return WOPCM_SIZE; +} + +#endif diff --git a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_types.h b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_types.h index 99d34837c4..38de3af321 100644 --- a/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_types.h +++ b/crates/stela-drivers/src/gpu/intel/xe/xe_wopcm_types.h @@ -6,7 +6,11 @@ #ifndef _XE_WOPCM_TYPES_H_ #define _XE_WOPCM_TYPES_H_ +#ifdef STELA_NATIVE +#include "xe_scalar_types.h" +#else #include +#endif /** * struct xe_wopcm - Overall WOPCM info and WOPCM regions. diff --git a/crates/stela-drivers/src/gpu/macos/Makefile b/crates/stela-drivers/src/gpu/macos/Makefile index 11411f8cee..13f92d8fc6 100644 --- a/crates/stela-drivers/src/gpu/macos/Makefile +++ b/crates/stela-drivers/src/gpu/macos/Makefile @@ -23,20 +23,29 @@ else $(error unsupported kernel architecture $(ARCH)) endif -OBJECTS := $(BUILD)/memory.o -DEPENDS := $(OBJECTS:.o=.d) +OBJECTS := $(BUILD)/memory.o $(BUILD)/task_memory.o +DEPENDS := $(OBJECTS:.o=.d) $(BUILD)/task-memory-contract.d -.PHONY: all -all: $(BUILD)/gpu-memory.o +.PHONY: all contract-tests +all: $(BUILD)/gpu-memory.o $(BUILD)/task_memory.o $(BUILD): mkdir -p "$@" -$(BUILD)/memory.o: $(SOURCE)/memory.cpp | $(BUILD) +$(BUILD)/%.o: $(SOURCE)/%.cpp | $(BUILD) "$(CXX)" $(COMMON) -fapple-kext -fno-exceptions -fno-rtti \ -std=gnu++17 -MD -MP -c "$<" -o "$@" -$(BUILD)/gpu-memory.o: $(OBJECTS) - "$(LD)" -r -arch $(ARCH) -o "$@" $(OBJECTS) +$(BUILD)/gpu-memory.o: $(BUILD)/memory.o + "$(LD)" -r -arch $(ARCH) -o "$@" "$<" + +# Host-only ownership/error tests. No mocks enter the kernel component. +contract-tests: $(BUILD)/task-memory-contract + "$<" + +$(BUILD)/task-memory-contract: $(SOURCE)/tests/task_memory_contract.cpp $(SOURCE)/task_memory.cpp $(SOURCE)/task_memory.h | $(BUILD) + "$(CXX)" -std=gnu++17 -isysroot "$(SDKROOT)" -idirafter "$(HEADERS)" \ + -O2 -g -Wall -Wextra -Werror -Wconversion -fsanitize=address,undefined \ + -fno-omit-frame-pointer -MD -MP "$<" -o "$@" -include $(DEPENDS) diff --git a/crates/stela-drivers/src/gpu/macos/task_memory.cpp b/crates/stela-drivers/src/gpu/macos/task_memory.cpp new file mode 100644 index 0000000000..3f562e864e --- /dev/null +++ b/crates/stela-drivers/src/gpu/macos/task_memory.cpp @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: MIT */ +#include "task_memory.h" +#include +#include +#include +#include + +namespace stela::gpu { + +TaskMemory::~TaskMemory() +{ + /* Automatically completing here could unwire pages still used by hardware. + * Even releasing the last descriptor reference can complete it inside XNU. + * A still-prepared owner is a kernel caller lifetime bug, never permission + * to manufacture quiescence. Keep this check active in release builds. + */ + if (memory_ || task_) + panic("Stela GPU task memory destroyed before quiescent completion"); +} + +IOReturn TaskMemory::prepare(task_t owning_task, mach_vm_address_t address, + mach_vm_size_t length, IODirection direction) +{ + if (memory_) + return kIOReturnBusy; + if (!owning_task || owning_task == kernel_task || !length || + address > UINT64_MAX - length || + (direction != kIODirectionIn && direction != kIODirectionOut && + direction != kIODirectionOutIn)) + return kIOReturnBadArgument; + + task_reference(owning_task); + OSSharedPtr memory( + IOMemoryDescriptor::withAddressRange(address, length, + direction | kIOMemoryMapperNone, owning_task), OSNoRetain); + if (!memory) { + task_deallocate(owning_task); + return kIOReturnNoMemory; + } + IOReturn status = memory->prepare(); + if (status != kIOReturnSuccess) { + memory.reset(); + task_deallocate(owning_task); + return status; + } + task_ = owning_task; + memory_.reset(memory.detach(), OSNoRetain); + return kIOReturnSuccess; +} + +IOReturn TaskMemory::finish_after_quiescence(bool transfer_failed) +{ + if (!memory_) + return kIOReturnNotReady; + IOReturn status = memory_->complete(transfer_failed ? + kIODirectionCompleteWithError : kIODirectionNone); + if (status != kIOReturnSuccess) + return status; + memory_.reset(); + task_deallocate(task_); + task_ = nullptr; + return kIOReturnSuccess; +} + +} // namespace stela::gpu diff --git a/crates/stela-drivers/src/gpu/macos/task_memory.h b/crates/stela-drivers/src/gpu/macos/task_memory.h new file mode 100644 index 0000000000..b0623f7eaf --- /dev/null +++ b/crates/stela-drivers/src/gpu/macos/task_memory.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: MIT */ +#pragma once +#include +#include + +namespace stela::gpu { + +/* ARM macOS kernel ownership only; never an IPC/native-backend representation. + * Embed in the real task-owned frontend resource. Calls and destruction must be + * serialized by that resource's existing IOKit lifecycle. The caller supplies + * the actual IOUserClient owning task, never a task/address received on the wire. + * + * The frontend MUST retain this owner until every backend mapping/lease is + * genuinely quiescent, including task death, failure and service removal. + * Prepared memory is not a native DMA grant, residency, coherency or permission + * to submit work. No physical/DMA/GPU address is produced here. + */ +class TaskMemory final { +public: + TaskMemory() = default; + ~TaskMemory(); + TaskMemory(const TaskMemory &) = delete; + TaskMemory &operator=(const TaskMemory &) = delete; + TaskMemory(TaskMemory &&) = delete; + TaskMemory &operator=(TaskMemory &&) = delete; + + /* May sleep. Only In, Out and OutIn are accepted; direction is relative to + * described memory, following IOKit. No arbitrary IOMemory option bits. + * Invalid input/busy ownership causes no task/descriptor mutation. Allocation + * or prepare failure releases the original references, without complete(). + */ + IOReturn prepare(task_t owning_task, mach_vm_address_t address, + mach_vm_size_t length, IODirection direction); + + /* Borrowed ARM-kernel object, valid only while this owner remains prepared. + * Do not release, re-prepare, complete, reinitialize or export this pointer. + * Mapping/grant validation and its asynchronous lifetime belong to the real + * transport owner; they must end before finish_after_quiescence(). + */ + IOMemoryDescriptor *prepared_descriptor() const { return memory_.get(); } + + /* Call ONLY after actual backend access/mappings are quiescent and required + * cache/reservation/code visibility is complete. transfer_failed selects the + * original IOKit completion-error flag, not a synthetic GPU completion. + * Failure retains both references unchanged for the caller's quarantine and + * recovery; it must not destroy this owner or report completed teardown. + * Success releases the descriptor before the task. Empty => NotReady. + */ + IOReturn finish_after_quiescence(bool transfer_failed = false); + +private: + OSSharedPtr memory_; + task_t task_ = nullptr; +}; + +} // namespace stela::gpu diff --git a/crates/stela-drivers/src/gpu/macos/tests/task_memory_contract.cpp b/crates/stela-drivers/src/gpu/macos/tests/task_memory_contract.cpp new file mode 100644 index 0000000000..df96d73286 --- /dev/null +++ b/crates/stela-drivers/src/gpu/macos/tests/task_memory_contract.cpp @@ -0,0 +1,233 @@ +/* SPDX-License-Identifier: MIT */ +/* Compile the real owner below against deliberately narrow service mocks. + * These check caller ownership/error handling, not IOKit implementation, kernel + * class layout, ABI, page wiring, task death or hardware quiescence. The normal + * Makefile targets separately compile against the unmodified Apple SDK. + * No mock is compiled into a driver component. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +// Suppress SDK declarations only in this test translation unit. +#define _IOMEMORYDESCRIPTOR_H +#define XNU_LIBKERN_LIBKERN_CXX_OS_SHARED_PTR_H +#define __IOKIT_IOLIB_H +#define _KERN_TASK_H_ +#define _KERN_TASK_REF_H_ + +using IOReturn = int32_t; +using IODirection = uint32_t; +using IOOptionBits = uint32_t; +using mach_vm_address_t = uint64_t; +using mach_vm_size_t = uint64_t; +constexpr IOReturn kIOReturnSuccess = 0; +constexpr IOReturn kIOReturnNoMemory = static_cast(0xe00002bdu); +constexpr IOReturn kIOReturnBadArgument = static_cast(0xe00002c2u); +constexpr IOReturn kIOReturnBusy = static_cast(0xe00002d5u); +constexpr IOReturn kIOReturnNotReady = static_cast(0xe00002d8u); +constexpr IOReturn injected_error = -12345; +constexpr IODirection kIODirectionNone = 0; +constexpr IODirection kIODirectionIn = 1; +constexpr IODirection kIODirectionOut = 2; +constexpr IODirection kIODirectionOutIn = 3; +constexpr IODirection kIODirectionCompleteWithError = 0x40; +constexpr IOOptionBits kIOMemoryMapperNone = 0x800; +struct task { unsigned references = 1; } user, kernel; +using task_t = task *; +task_t kernel_task = &kernel; + +enum Event { ReferenceTask, Factory, Prepare, Complete, ReleaseMemory, ReleaseTask }; +static Event events[32]; +static unsigned event_count, complete_calls, releases; +static IOReturn prepare_status, complete_status; +static bool factory_failure; +static IODirection last_complete_direction; +static void record(Event event) +{ + assert(event_count < 32); + events[event_count++] = event; +} +static void task_reference(task_t owner) +{ + assert(owner == &user && owner->references == 1); + ++owner->references; + record(ReferenceTask); +} +static void task_deallocate(task_t owner) +{ + assert(owner == &user && owner->references == 2); + --owner->references; + record(ReleaseTask); +} +struct IOMemoryDescriptor { + unsigned references = 0; + bool prepared = false; + static IOMemoryDescriptor *withAddressRange(mach_vm_address_t, + mach_vm_size_t, IOOptionBits, task_t); + IOReturn prepare(IODirection direction = kIODirectionNone) + { + assert(references == 1 && !prepared && direction == kIODirectionNone); + assert(user.references == 2); + record(Prepare); + prepared = prepare_status == kIOReturnSuccess; + return prepare_status; + } + IOReturn complete(IODirection direction = kIODirectionNone) + { + assert(references == 1 && prepared && user.references == 2); + ++complete_calls; + last_complete_direction = direction; + record(Complete); + if (complete_status == kIOReturnSuccess) + prepared = false; + return complete_status; + } + void release() + { + // A release while prepared could unwire pages inside original XNU. + assert(references == 1 && !prepared && user.references == 2); + --references; + ++releases; + record(ReleaseMemory); + } +} descriptor; +IOMemoryDescriptor *IOMemoryDescriptor::withAddressRange(mach_vm_address_t, + mach_vm_size_t length, IOOptionBits options, task_t owner) +{ + assert(owner == &user && owner->references == 2 && length != 0); + assert((options & ~kIODirectionOutIn) == kIOMemoryMapperNone); + assert(descriptor.references == 0); + record(Factory); + if (factory_failure) + return nullptr; + descriptor.references = 1; + return &descriptor; +} +struct NoRetain {}; +constexpr NoRetain OSNoRetain{}; +template class OSSharedPtr { +public: + OSSharedPtr() = default; + OSSharedPtr(T *pointer, NoRetain) : pointer_(pointer) {} + ~OSSharedPtr() { reset(); } + OSSharedPtr(const OSSharedPtr &) = delete; + OSSharedPtr &operator=(const OSSharedPtr &) = delete; + explicit operator bool() const { return pointer_ != nullptr; } + T *get() const { return pointer_; } + T *operator->() const { return pointer_; } + T *detach() { T *result = pointer_; pointer_ = nullptr; return result; } + void reset() + { + if (pointer_) + pointer_->release(); + pointer_ = nullptr; + } + void reset(T *pointer, NoRetain) { reset(); pointer_ = pointer; } +private: + T *pointer_ = nullptr; +}; +[[noreturn]] static void panic(const char *, ...) +{ + // The child must refuse destruction before either completion or release. + _Exit(complete_calls == 0 && releases == 0 && user.references == 2 ? 86 : 87); +} + +#include "../task_memory.cpp" +using stela::gpu::TaskMemory; +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_move_constructible_v); +static void reset() +{ + assert(user.references == 1 && kernel.references == 1); + assert(descriptor.references == 0 && !descriptor.prepared); + event_count = complete_calls = releases = 0; + factory_failure = false; + prepare_status = complete_status = kIOReturnSuccess; + last_complete_direction = 0; +} +template static void expect(const Event (&expected)[N]) +{ + assert(event_count == N); + for (unsigned i = 0; i < N; ++i) + assert(events[i] == expected[i]); +} +int main() +{ + reset(); + { + TaskMemory owner; + assert(!owner.prepared_descriptor()); + assert(owner.finish_after_quiescence() == kIOReturnNotReady); + assert(owner.prepare(nullptr, 0x1000, 4096, kIODirectionIn) == kIOReturnBadArgument); + assert(owner.prepare(kernel_task, 0x1000, 4096, kIODirectionIn) == kIOReturnBadArgument); + assert(owner.prepare(&user, 0x1000, 0, kIODirectionIn) == kIOReturnBadArgument); + assert(owner.prepare(&user, UINT64_MAX, 1, kIODirectionIn) == kIOReturnBadArgument); + assert(owner.prepare(&user, 1, UINT64_MAX, kIODirectionIn) == kIOReturnBadArgument); + for (IODirection direction : {0u, 4u, 0x40u, 0x800u, UINT32_MAX}) + assert(owner.prepare(&user, 0x1000, 4096, direction) == kIOReturnBadArgument); + assert(event_count == 0); + } + for (IODirection direction : {kIODirectionIn, kIODirectionOut, kIODirectionOutIn}) { + reset(); + TaskMemory owner; + assert(owner.prepare(&user, UINT64_MAX - 1, 1, direction) == kIOReturnSuccess); + assert(owner.prepared_descriptor() == &descriptor); + assert(owner.prepare(nullptr, 0, 0, 0) == kIOReturnBusy); + assert(event_count == 3 && user.references == 2); + assert(owner.finish_after_quiescence() == kIOReturnSuccess); + assert(!owner.prepared_descriptor() && last_complete_direction == kIODirectionNone); + assert(owner.finish_after_quiescence() == kIOReturnNotReady); + expect({ReferenceTask, Factory, Prepare, Complete, ReleaseMemory, ReleaseTask}); + } + reset(); + { + factory_failure = true; + TaskMemory owner; + assert(owner.prepare(&user, 0x1000, 4096, kIODirectionOut) == kIOReturnNoMemory); + assert(!owner.prepared_descriptor()); + expect({ReferenceTask, Factory, ReleaseTask}); + } + reset(); + { + prepare_status = injected_error; + TaskMemory owner; + assert(owner.prepare(&user, 0x1000, 4096, kIODirectionOut) == injected_error); + assert(!owner.prepared_descriptor() && complete_calls == 0); + expect({ReferenceTask, Factory, Prepare, ReleaseMemory, ReleaseTask}); + } + reset(); + { + TaskMemory owner; + assert(owner.prepare(&user, 0, 4096, kIODirectionIn) == kIOReturnSuccess); + complete_status = injected_error; + assert(owner.finish_after_quiescence() == injected_error); + assert(owner.prepared_descriptor() == &descriptor && descriptor.prepared); + assert(user.references == 2 && releases == 0); + assert(owner.prepare(&user, 0x1000, 4096, kIODirectionOut) == kIOReturnBusy); + complete_status = kIOReturnSuccess; + assert(owner.finish_after_quiescence(true) == kIOReturnSuccess); + assert(last_complete_direction == kIODirectionCompleteWithError); + expect({ReferenceTask, Factory, Prepare, Complete, Complete, ReleaseMemory, ReleaseTask}); + // A finished embedded owner can be reused without retaining stale refs. + assert(owner.prepare(&user, 0x1000, 4096, kIODirectionOut) == kIOReturnSuccess); + assert(owner.finish_after_quiescence() == kIOReturnSuccess); + } + reset(); + pid_t child = fork(); + assert(child >= 0); + if (!child) { + { TaskMemory owner; + assert(owner.prepare(&user, 0x1000, 4096, kIODirectionOut) == kIOReturnSuccess); } + _Exit(88); + } + int status = 0; + assert(waitpid(child, &status, 0) == child); + assert(WIFEXITED(status) && WEXITSTATUS(status) == 86); + std::puts("task memory ownership/error contracts passed (service mocks; no kernel/device execution)"); +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.c b/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.c new file mode 100644 index 0000000000..b60ab2b25a --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.c @@ -0,0 +1,503 @@ +/* SPDX-License-Identifier: MIT */ +#include "library_assembly.h" +#include +#include +#include +#include +#include +#include + +#define INPUT_LIMIT (64u * 1024u * 1024u) +#define ENTRY_LIMIT 256u +#define STRING_LIMIT 4096u +#define TARGET_LIMIT 1024u +#define ENTRY_FLAGS (STELA_METAL_ENTRY_NO_CONSTANTS | STELA_METAL_ENTRY_PLAIN_BUFFERS | \ + STELA_METAL_ENTRY_COMPLETE_REFLECTION) +struct stela_metal_assembly { + struct stela_metal_input *input; + struct stela_metal_input_view original; + struct stela_metal_library_manifest manifest; + struct stela_metal_function_record *records; + void **blocks; + char *target; + unsigned capacity, inspection_entries; + uint64_t metadata_bytes, metadata_limit; +}; +struct visit_context { + struct stela_metal_assembly *owner; + struct stela_metal_assembly_error *error; + const struct stela_msl_request *request; /* Borrowed for this call only. */ + const struct stela_metal_function_record *group; /* Archive module group. */ + struct stela_metal_input_view raw; + uint8_t raw_sha256[32]; +}; +static void reset_error(struct stela_metal_assembly_error *error) +{ + *error = (struct stela_metal_assembly_error) { + .size=sizeof(*error),.abi=STELA_METAL_ASSEMBLY_ABI, + }; +} +static enum stela_metal_assembly_status +report(struct stela_metal_assembly_error *error, enum stela_metal_assembly_status status, + const char *format, ...) +{ + if (error->status == STELA_METAL_ASSEMBLY_OK) { + error->status = status; + va_list args; va_start(args,format); + vsnprintf(error->detail,sizeof(error->detail),format,args); + va_end(args); + } + return status; +} +static enum stela_metal_assembly_status +input_error(struct stela_metal_assembly_error *error, const struct stela_metal_input_error *input) +{ + error->input_status = input->status; error->input_offset = input->offset; + enum stela_metal_assembly_status status = + input->status == STELA_METAL_INPUT_LIMIT ? STELA_METAL_ASSEMBLY_LIMIT : + input->status == STELA_METAL_INPUT_ALLOCATION ? STELA_METAL_ASSEMBLY_ALLOCATION : + input->status == STELA_METAL_INPUT_ABI_MISMATCH ? STELA_METAL_ASSEMBLY_ABI_MISMATCH : + input->status == STELA_METAL_INPUT_INVALID ? STELA_METAL_ASSEMBLY_INPUT : STELA_METAL_ASSEMBLY_CONTAINER; + return report(error,status, + "Canonical input refused (status %u, parser %u, original offset %llu)", + input->status,input->parser_kind,(unsigned long long)input->offset); +} +static bool nonzero(const uint8_t *bytes, size_t count) +{ + uint8_t result = 0; + for (size_t i = 0; i < count; i++) result |= bytes[i]; + return result != 0; +} +static void hash(const void *bytes, size_t size, uint8_t digest[32]) +{ + /* All source/input/raw ranges are independently bounded to 64MiB. */ + CC_SHA256(bytes,(CC_LONG)size,digest); +} +static bool charge(struct stela_metal_assembly *owner, size_t bytes, + struct stela_metal_assembly_error *error) +{ + if (bytes > owner->metadata_limit-owner->metadata_bytes) { + report(error,STELA_METAL_ASSEMBLY_LIMIT,"Retained metadata budget exceeded"); return false; + } + owner->metadata_bytes += bytes; + return true; +} +static bool text(const char *bytes, size_t size) +{ + if (!bytes) return !size; + if (size > STRING_LIMIT || memchr(bytes,0,size)) return false; + /* Use the real hosted string implementation; do not normalize/rewrite bytes. */ + CFStringRef string = CFStringCreateWithBytes(kCFAllocatorDefault,(const UInt8 *)bytes, + (CFIndex)size,kCFStringEncodingUTF8,false); + if (!string) return false; + CFRelease(string); + return true; +} +static bool span(uint64_t offset, uint64_t size, uint64_t limit) +{ + return size && offset <= limit && size <= limit-offset; +} +/* Only the observed AIR macOS triple syntax is admitted. Header version fields + * represent major/minor only: preserve the actual patch, do not invent one or + * infer Metal feature support/deployment compatibility from this consistency. */ +static bool target_version(const struct stela_air_inspection *info, unsigned version[3]) +{ + char prefix[40]; + snprintf(prefix,sizeof(prefix),"air64_v2%u-apple-macosx",info->air_minor); + size_t at = strlen(prefix); + if (info->target_bytes <= at || memcmp(info->target,prefix,at)) return false; + for (unsigned part = 0; part < 3; part++) { + unsigned value = 0, digits = 0; + while (at < info->target_bytes && info->target[at] >= '0' && info->target[at] <= '9') { + unsigned digit = (unsigned)(info->target[at++]-'0'); + if (value > (UINT16_MAX-digit)/10) return false; + value = value*10+digit; digits++; + } + if (!digits) return false; + version[part] = value; + if (part < 2 && (at == info->target_bytes || info->target[at++] != '.')) return false; + } + return at == info->target_bytes && version[0]; +} +static bool same_wrapped_module(const struct stela_metal_function_record *a, + const struct stela_metal_function_record *b) +{ + return a->entry.module_offset == b->entry.module_offset && + a->entry.module_bytes == b->entry.module_bytes && + !memcmp(a->entry.module_sha256,b->entry.module_sha256,32); +} +static bool same_module(const struct stela_metal_function_record *a, + const struct stela_metal_function_record *b) +{ + return same_wrapped_module(a,b) && a->air_offset == b->air_offset && a->air_bytes == b->air_bytes; +} +static bool module_identity(struct visit_context *context, const struct stela_air_inspection *info) +{ + struct stela_metal_assembly *owner = context->owner; + unsigned version[3]; + if (info->target_bytes > TARGET_LIMIT || !target_version(info,version)) { + report(context->error,STELA_METAL_ASSEMBLY_IDENTITY,"Unsupported AIR target encoding"); return false; + } + if (context->request) { + const struct stela_msl_request *request = context->request; + if (info->air_minor != 9 || info->language_major != request->language_version >> 16 || + info->language_minor != (request->language_version & 0xffff) || + !info->fast_math || !info->denorms_disable || + strlen(request->target_triple) != info->target_bytes || + memcmp(request->target_triple,info->target,info->target_bytes)) { + report(context->error,STELA_METAL_ASSEMBLY_SOURCE,"AIR facts differ from the qualified source request"); return false; + } + } else if (version[0] != owner->manifest.input.minimum_os_major || + version[1] != owner->manifest.input.minimum_os_minor) { + report(context->error,STELA_METAL_ASSEMBLY_IDENTITY,"MTLB and AIR target OS version fields disagree"); return false; + } + if (owner->target) { + if (owner->manifest.target_bytes != info->target_bytes || + memcmp(owner->target,info->target,info->target_bytes)) { + report(context->error,STELA_METAL_ASSEMBLY_IDENTITY,"Selected AIR modules have different targets"); return false; + } + } else { + if (!charge(owner,info->target_bytes+1,context->error)) return false; + owner->target = malloc(info->target_bytes+1); + if (!owner->target) { + report(context->error,STELA_METAL_ASSEMBLY_ALLOCATION,"Target copy allocation failed"); return false; + } + memcpy(owner->target,info->target,info->target_bytes); owner->target[info->target_bytes] = 0; + owner->manifest.target = (const uint8_t *)owner->target; + owner->manifest.target_bytes = info->target_bytes; + } + return true; +} +static char *copy_text(char **cursor, const char *bytes, size_t count) +{ + if (!bytes) return NULL; + char *result = *cursor; + memcpy(result,bytes,count); result[count] = 0; *cursor += count+1; + return result; +} +static bool copy_entry(struct visit_context *context, const struct stela_air_entry *entry, + unsigned index) +{ + struct stela_metal_assembly *owner = context->owner; + if (index >= owner->capacity || entry->argument_count > AIR_MAX_ARGUMENTS) { + report(context->error,STELA_METAL_ASSEMBLY_LIMIT,"Entry/argument budget exceeded"); return false; + } + if (!entry->reflection_complete || !entry->name_bytes || + !text(entry->name,entry->name_bytes)) { + report(context->error,STELA_METAL_ASSEMBLY_REFLECTION,"Incomplete/unrepresentable function reflection"); return false; + } + size_t size = entry->argument_count*sizeof(struct stela_air_argument_info)+entry->name_bytes+1; + for (unsigned i = 0; i < entry->argument_count; i++) { + const struct stela_air_argument_info *arg = &entry->arguments[i]; + if (!text(arg->name,arg->name_bytes) || !text(arg->type_name,arg->type_name_bytes)) { + report(context->error,STELA_METAL_ASSEMBLY_REFLECTION,"Unrepresentable argument reflection strings"); return false; + } + /* Bounded above by 128 arguments and 4096 bytes/string before addition. */ + size += arg->name ? arg->name_bytes+1 : 0; + size += arg->type_name ? arg->type_name_bytes+1 : 0; + } + if (!charge(owner,size,context->error)) return false; + void *block = malloc(size); + if (!block) { + report(context->error,STELA_METAL_ASSEMBLY_ALLOCATION,"Reflection copy allocation failed"); return false; + } + owner->blocks[index] = block; + struct stela_air_argument_info *args = block; + char *cursor = (char *)(args+entry->argument_count); + struct stela_metal_function_record *record = &owner->records[index]; + record->size = sizeof(*record); record->abi = STELA_METAL_LIBRARY_ABI; + record->flags = ENTRY_FLAGS; + record->name = (const uint8_t *)copy_text(&cursor,entry->name,entry->name_bytes); + record->name_bytes = entry->name_bytes; record->argument_count = entry->argument_count; + record->arguments = args; + for (unsigned i = 0; i < entry->argument_count; i++) { + args[i] = entry->arguments[i]; + args[i].name = copy_text(&cursor,args[i].name,args[i].name_bytes); + args[i].type_name = copy_text(&cursor,args[i].type_name,args[i].type_name_bytes); + } + return true; +} +static bool visit_entry(const struct stela_air_inspection *info, + const struct stela_air_entry *entry, void *data) +{ + struct visit_context *context = data; + struct stela_metal_assembly *owner = context->owner; + if (!context->group) { + unsigned index = owner->manifest.entry_count; + if (!module_identity(context,info)) return false; + if (index >= owner->capacity) { + report(context->error,STELA_METAL_ASSEMBLY_LIMIT,"Source entry budget exceeded"); return false; + } + struct stela_metal_function_record *record = &owner->records[index]; + record->entry = (struct stela_metal_input_entry) { + .size=sizeof(record->entry),.abi=STELA_METAL_INPUT_ABI,.kind=2, + .air_major=2,.air_minor=info->air_minor, + .language_major=info->language_major,.language_minor=info->language_minor, + .module_offset=0,.module_bytes=owner->original.length, + }; + memcpy(record->entry.module_sha256,owner->manifest.input.original_sha256,32); + record->air_offset = context->raw.original_offset; record->air_bytes = context->raw.length; + memcpy(record->air_sha256,context->raw_sha256,32); + if (!copy_entry(context,entry,index)) return false; + owner->manifest.entry_count++; + return true; + } + for (unsigned i = 0; i < owner->manifest.entry_count; i++) { + struct stela_metal_function_record *record = &owner->records[i]; + if (!same_module(context->group,record) || record->name_bytes != entry->name_bytes || + memcmp(record->name,entry->name,entry->name_bytes)) continue; + if (record->flags || record->entry.air_major != 2 || record->entry.air_minor != info->air_minor || + record->entry.language_major != info->language_major || + record->entry.language_minor != info->language_minor) { + report(context->error,STELA_METAL_ASSEMBLY_IDENTITY,"MTLB NAME/TYPE/VERS differ from selected AIR entry"); return false; + } + return module_identity(context,info) && copy_entry(context,entry,i); + } + return true; /* Extra nonexported AIR entries are not fabricated as exports. */ +} +static bool inspect(struct visit_context *context, uint64_t offset, uint64_t size) +{ + struct stela_metal_assembly *owner = context->owner; + if (!span(offset,size,owner->original.length)) { + report(context->error,STELA_METAL_ASSEMBLY_IDENTITY,"Selected AIR is outside the original input"); return false; + } + struct stela_air_error error; + if (!stela_air_inspect(owner->original.bytes+offset,(size_t)size,owner->inspection_entries, + visit_entry,context,&error)) { + if (!context->error->status) { + context->error->air_kind = error.kind; context->error->air_instruction = error.instruction; + report(context->error,STELA_METAL_ASSEMBLY_AIR,"%s",error.detail); + } + return false; + } + return true; +} +static struct stela_metal_assembly *open_input(const struct stela_metal_assembly_options *options, + uint32_t kind, const void *bytes, size_t count, struct stela_metal_assembly_error *error) +{ + struct stela_metal_input *input = NULL; + struct stela_metal_input_limits limits = {.size=sizeof(limits),.abi=STELA_METAL_INPUT_ABI, + .kind=kind,.max_entries=options->max_entries,.max_bytes=options->max_input_bytes}; + struct stela_metal_input_error input_status; + if (stela_metal_input_open(&limits,bytes,count,&input,&input_status)) { + input_error(error,&input_status); return NULL; + } + struct stela_metal_input_info info = {.size=sizeof(info),.abi=STELA_METAL_INPUT_ABI}; + if (stela_metal_input_info(input,&info,&input_status)) { + input_error(error,&input_status); stela_metal_input_destroy(&input); return NULL; + } + unsigned capacity = kind == STELA_METAL_INPUT_MTLB ? info.entry_count : options->max_entries; + size_t base = sizeof(struct stela_metal_assembly)+capacity*(sizeof(struct stela_metal_function_record)+sizeof(void *)); + if (!capacity || base > options->max_metadata_bytes) { + report(error,STELA_METAL_ASSEMBLY_LIMIT,"No compute entries or retained owner budget exceeded"); + stela_metal_input_destroy(&input); return NULL; + } + struct stela_metal_assembly *owner = calloc(1,sizeof(*owner)); + if (!owner) { + report(error,STELA_METAL_ASSEMBLY_ALLOCATION,"Owner allocation failed"); + stela_metal_input_destroy(&input); return NULL; + } + owner->input = input; owner->capacity = capacity; owner->inspection_entries = options->max_entries; + owner->metadata_bytes = base; owner->metadata_limit = options->max_metadata_bytes; + owner->manifest = (struct stela_metal_library_manifest) { + .size=sizeof(owner->manifest),.abi=STELA_METAL_LIBRARY_ABI,.input=info, + }; + owner->records = calloc(capacity,sizeof(*owner->records)); + owner->blocks = calloc(capacity,sizeof(*owner->blocks)); + if (!owner->records || !owner->blocks) { + report(error,STELA_METAL_ASSEMBLY_ALLOCATION,"Entry table allocation failed"); goto fail; + } + owner->manifest.entries = owner->records; + owner->original = (struct stela_metal_input_view){.size=sizeof(owner->original),.abi=STELA_METAL_INPUT_ABI}; + if (stela_metal_input_original(input,&owner->original,&input_status)) { + input_error(error,&input_status); goto fail; + } + if (!owner->original.bytes || owner->original.original_offset || + owner->original.length != info.original_bytes) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"Canonical original view and input info disagree"); goto fail; + } + return owner; +fail: + stela_metal_assembly_destroy(&owner); return NULL; +} +static bool valid_options(const struct stela_metal_assembly_options *options, + struct stela_metal_assembly **output, + struct stela_metal_assembly_error *error) +{ + if (!options || !output || *output) { + report(error,STELA_METAL_ASSEMBLY_INPUT,"Options and empty owning output slot are required"); return false; + } + if (options->size != sizeof(*options) || options->abi != STELA_METAL_ASSEMBLY_ABI || options->reserved) { + report(error,STELA_METAL_ASSEMBLY_ABI_MISMATCH,"Invalid assembly options ABI/reserved fields"); return false; + } + if (!options->max_entries || options->max_entries > ENTRY_LIMIT || + options->max_input_bytes < 4 || options->max_input_bytes > INPUT_LIMIT || + !options->max_metadata_bytes || options->max_metadata_bytes > INPUT_LIMIT) { + report(error,STELA_METAL_ASSEMBLY_LIMIT,"Invalid assembly entry/input/metadata bounds"); return false; + } + return true; +} +struct stela_metal_assembly_options stela_metal_assembly_default_options(void) +{ + return (struct stela_metal_assembly_options) { + .size=sizeof(struct stela_metal_assembly_options),.abi=STELA_METAL_ASSEMBLY_ABI, + .max_entries=ENTRY_LIMIT,.max_input_bytes=INPUT_LIMIT,.max_metadata_bytes=16u*1024u*1024u, + }; +} +enum stela_metal_assembly_status stela_metal_assemble_archive( + const struct stela_metal_assembly_options *options, const void *bytes, size_t count, + struct stela_metal_assembly **output, struct stela_metal_assembly_error *error) +{ + struct stela_metal_assembly_error local; + if (!error) error = &local; + reset_error(error); + if (!valid_options(options,output,error)) return error->status; + struct stela_metal_assembly *owner = open_input(options,STELA_METAL_INPUT_MTLB,bytes,count,error); + if (!owner) return error->status; + const struct stela_metal_input_info *info = &owner->manifest.input; + if (info->platform != 0x8001 || info->target_os != 0x81 || info->format_major != 2 || info->library_kind) { + report(error,STELA_METAL_ASSEMBLY_CONTAINER,"Requires an observed macOS MTLB2 executable header"); goto fail; + } + owner->manifest.entry_count = info->entry_count; + for (unsigned i = 0; i < info->entry_count; i++) { + struct stela_metal_function_record *record = &owner->records[i]; + record->entry = (struct stela_metal_input_entry){.size=sizeof(record->entry),.abi=STELA_METAL_INPUT_ABI}; + struct stela_metal_input_view name = {.size=sizeof(name),.abi=STELA_METAL_INPUT_ABI}; + struct stela_metal_input_view raw = {.size=sizeof(raw),.abi=STELA_METAL_INPUT_ABI}; + struct stela_metal_input_error input_status; + if (stela_metal_input_entry(owner->input,i,&record->entry,&input_status) || + stela_metal_input_name(owner->input,i,&name,&input_status)) { + input_error(error,&input_status); goto fail; + } + struct stela_metal_input_entry_metadata metadata = {.size=sizeof(metadata),.abi=STELA_METAL_INPUT_ABI}; + if (stela_metal_input_entry_metadata(owner->input,i,&metadata,&input_status)) { + input_error(error,&input_status); goto fail; + } + /* Canonical parsing already requires exactly one each of NAME, TYPE, + * HASH, MDSZ, OFFT, VERS. Only those six function tags and absent/ENDT-only + * metadata streams are qualified here. AIR reflection cannot prove an + * archive has no CNST/ARGR/RETR or unknown extension requirements. */ + if (metadata.function_tags != 6 || metadata.public_tags || metadata.private_tags || metadata.header_tags) { + report(error,STELA_METAL_ASSEMBLY_REFLECTION,"Unqualified MTLB function/public/private/header metadata"); goto fail; + } + if (record->entry.kind != 2) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"Selected MTLB entry is not a compute kernel"); goto fail; + } + record->name = name.bytes; record->name_bytes = name.length; + unsigned cached; + for (cached = 0; cached < i; cached++) { + if (same_wrapped_module(record,&owner->records[cached])) break; + } + if (cached < i) { + /* Immutable original range plus exact expected HASH equality reuses + * the earlier canonical selected-module hash/framing proof. */ + record->air_offset = owner->records[cached].air_offset; + record->air_bytes = owner->records[cached].air_bytes; + memcpy(record->air_sha256,owner->records[cached].air_sha256,32); + continue; + } + if (stela_metal_input_air(owner->input,i,&raw,&input_status)) { + input_error(error,&input_status); goto fail; + } + if (!span(raw.original_offset,raw.length,owner->original.length) || + raw.original_offset < record->entry.module_offset || raw.length > record->entry.module_bytes || + raw.original_offset-record->entry.module_offset > record->entry.module_bytes-raw.length) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"Canonical AIR range is outside its selected module"); goto fail; + } + if (raw.bytes != owner->original.bytes+raw.original_offset) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"Canonical raw view does not retain original storage"); goto fail; + } + record->air_offset = raw.original_offset; record->air_bytes = raw.length; + hash(raw.bytes,(size_t)raw.length,record->air_sha256); + } + /* One LLVM inspection per shared original module, not one per export. + * Every selected entry has a canonical or identical cached HASH proof. */ + for (unsigned i = 0; i < info->entry_count; i++) { + if (owner->records[i].flags) continue; + struct visit_context context = {.owner=owner,.error=error,.group=&owner->records[i]}; + if (!inspect(&context,context.group->air_offset,context.group->air_bytes)) goto fail; + for (unsigned j = 0; j < info->entry_count; j++) { + if (same_module(context.group,&owner->records[j]) && !owner->records[j].flags) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"MTLB NAME is absent from selected AIR kernel entries"); goto fail; + } + } + } + *output = owner; + return STELA_METAL_ASSEMBLY_OK; +fail: + stela_metal_assembly_destroy(&owner); return error->status; +} +enum stela_metal_assembly_status stela_metal_assemble_source( + const struct stela_metal_assembly_options *options, const struct stela_msl_apple_config *config, + const struct stela_msl_request *request, const struct stela_msl_output *compiled, + struct stela_metal_assembly **output, struct stela_metal_assembly_error *error) +{ + struct stela_metal_assembly_error local; + if (!error) error = &local; + reset_error(error); + if (!valid_options(options,output,error)) return error->status; + struct stela_msl_error source_error; + if (stela_msl_apple_validate_request(config,request,&source_error) != STELA_MSL_OK) + return report(error,STELA_METAL_ASSEMBLY_SOURCE,"%s",source_error.detail); + if (!compiled || !compiled->air || compiled->air_bytes < 4 || compiled->air_bytes > config->max_air_bytes || + !nonzero(compiled->build.gpucompiler_uuid,16) || !nonzero(compiled->build.implementation_uuid,16) || + !nonzero(compiled->build.llvm_uuid,16) || !nonzero(compiled->build.lazy_library_sha256,32) || + !nonzero(compiled->build.metal_stdlib_sha256,32) || !nonzero(compiled->build.metal_types_sha256,32)) + return report(error,STELA_METAL_ASSEMBLY_SOURCE,"Successful trusted compiler output/build identity required"); + uint8_t source_hash[32]; hash(request->source,request->source_bytes,source_hash); + if (memcmp(source_hash,compiled->source_sha256,32)) + return report(error,STELA_METAL_ASSEMBLY_SOURCE,"Source request/output digest mismatch"); + struct stela_metal_assembly *owner = open_input(options,STELA_METAL_INPUT_RAW_AIR,compiled->air,compiled->air_bytes,error); + if (!owner) return error->status; + if (memcmp(owner->manifest.input.original_sha256,compiled->air_sha256,32)) { + report(error,STELA_METAL_ASSEMBLY_SOURCE,"Original compiler output digest mismatch"); goto fail; + } + owner->manifest.flags = STELA_METAL_LIBRARY_SOURCE_COMPILED; + owner->manifest.compiler_profile = config->profile; + owner->manifest.request_language = request->language_version; + owner->manifest.request_fast_math = request->fast_math; + memcpy(owner->manifest.source_sha256,source_hash,32); owner->manifest.build = compiled->build; + struct stela_metal_input_view raw = {.size=sizeof(raw),.abi=STELA_METAL_INPUT_ABI}; + struct stela_metal_input_error input_status; + if (stela_metal_input_air(owner->input,0,&raw,&input_status)) { + input_error(error,&input_status); goto fail; + } + if (!span(raw.original_offset,raw.length,owner->original.length) || + raw.bytes != owner->original.bytes+raw.original_offset) { + report(error,STELA_METAL_ASSEMBLY_IDENTITY,"Canonical source AIR view does not retain original storage"); goto fail; + } + struct visit_context context = {.owner=owner,.error=error,.request=request,.raw=raw}; + hash(raw.bytes,(size_t)raw.length,context.raw_sha256); + if (!inspect(&context,raw.original_offset,raw.length)) goto fail; + *output = owner; + return STELA_METAL_ASSEMBLY_OK; +fail: + stela_metal_assembly_destroy(&owner); return error->status; +} +const struct stela_metal_library_manifest *stela_metal_assembly_manifest(const struct stela_metal_assembly *owner) +{ + return owner ? &owner->manifest : NULL; +} +enum stela_metal_assembly_status stela_metal_assembly_original( + const struct stela_metal_assembly *owner, struct stela_metal_input_view *view, + struct stela_metal_assembly_error *error) +{ + struct stela_metal_assembly_error local; + if (!error) error = &local; + reset_error(error); + if (!owner || !view) return report(error,STELA_METAL_ASSEMBLY_INPUT,"Owner and complete writable view required"); + if (view->size != sizeof(*view) || view->abi != STELA_METAL_INPUT_ABI) + return report(error,STELA_METAL_ASSEMBLY_ABI_MISMATCH,"Invalid original view ABI"); + *view = owner->original; + return STELA_METAL_ASSEMBLY_OK; +} +void stela_metal_assembly_destroy(struct stela_metal_assembly **slot) +{ + if (!slot || !*slot) return; + struct stela_metal_assembly *owner = *slot; *slot = NULL; + if (owner->blocks) + for (unsigned i = 0; i < owner->capacity; i++) free(owner->blocks[i]); + free(owner->blocks); free(owner->records); free(owner->target); + stela_metal_input_destroy(&owner->input); + free(owner); +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.h b/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.h new file mode 100644 index 0000000000..b890505491 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/library_assembly.h @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_METAL_LIBRARY_ASSEMBLY_H +#define STELA_METAL_LIBRARY_ASSEMBLY_H +#include "../macos/library_manifest.h" +#ifdef __cplusplus +extern "C" { +#endif +#define STELA_METAL_ASSEMBLY_ABI 1u +struct stela_metal_assembly_options { + uint32_t size, abi, max_entries, reserved; + uint64_t max_input_bytes, max_metadata_bytes; +}; +enum stela_metal_assembly_status { + STELA_METAL_ASSEMBLY_OK, + STELA_METAL_ASSEMBLY_INPUT, + STELA_METAL_ASSEMBLY_ABI_MISMATCH, + STELA_METAL_ASSEMBLY_LIMIT, + STELA_METAL_ASSEMBLY_ALLOCATION, + STELA_METAL_ASSEMBLY_CONTAINER, + STELA_METAL_ASSEMBLY_AIR, + STELA_METAL_ASSEMBLY_IDENTITY, + STELA_METAL_ASSEMBLY_REFLECTION, + STELA_METAL_ASSEMBLY_SOURCE, +}; +struct stela_metal_assembly_error { + uint32_t size, abi, status, input_status, air_kind, air_instruction; + uint64_t input_offset; + char detail[256]; +}; +struct stela_metal_assembly; + +/* Hosted local owner only, never a pointer IPC format. Standard libc owns the + * copied metadata; the canonical Rust input handle owns original bytes. LLVM + * callback views are copied before callback return. No LLVM or request/output + * pointer, device, connection, pipeline or GPU object escapes this assembly. + * + * Options require exact size/ABI1 and nonzero explicit bounds. Metadata budget + * covers all retained C owner/records/pointers/strings, excluding the separately + * bounded Rust input and normal transient LLVM/Foundation allocations. Defaults + * are 64MiB input, 16MiB retained metadata, 256 entries. No partial owner is + * published: failure preserves the empty output slot; error is optional complete + * writable storage. Input/output/error/owner storage must be disjoint, readable + * or writable as indicated and not concurrently mutated/destroyed. */ +/* Archive admission additionally requires exactly the canonical six required + * function tags and absent/ENDT-only public/private/header metadata. Nonempty + * unqualified extensions refuse before any reflection flags are published. */ +struct stela_metal_assembly_options stela_metal_assembly_default_options(void); +enum stela_metal_assembly_status stela_metal_assemble_archive( + const struct stela_metal_assembly_options *options, + const void *bytes, size_t byte_count, struct stela_metal_assembly **output, + struct stela_metal_assembly_error *error); + +/* Source request/output MUST come from a successful invocation of the existing + * qualified adapter by the trusted compiler owner. This is an integrity and + * consistency boundary, not authentication of caller-created C structs. It + * reuses validate_request and checks source/AIR hashes and exact metadata facts; + * llvm.ident is never used to manufacture compiler provenance. The caller may + * dispose source/request/output storage after success. No compiler invocation, + * dylib loading, source option mapping or hardware call is made here. */ +enum stela_metal_assembly_status stela_metal_assemble_source( + const struct stela_metal_assembly_options *options, + const struct stela_msl_apple_config *config, + const struct stela_msl_request *request, const struct stela_msl_output *compiled, + struct stela_metal_assembly **output, struct stela_metal_assembly_error *error); + +/* Views are immutable and valid only while this unique owner is retained. They + * can be passed to the real same-CPU library constructor, which makes its own + * owned snapshot. Serialize destruction with ALL borrowed accesses. No pointer + * in these views may be serialized into IPC. NULL owner yields NULL manifest. */ +const struct stela_metal_library_manifest *stela_metal_assembly_manifest( + const struct stela_metal_assembly *owner); +enum stela_metal_assembly_status stela_metal_assembly_original( + const struct stela_metal_assembly *owner, struct stela_metal_input_view *view, + struct stela_metal_assembly_error *error); +void stela_metal_assembly_destroy(struct stela_metal_assembly **owner); +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/metal/compiler/tests/library_assembly.c b/crates/stela-drivers/src/gpu/metal/compiler/tests/library_assembly.c new file mode 100644 index 0000000000..b23b46e726 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/tests/library_assembly.c @@ -0,0 +1,486 @@ +/* SPDX-License-Identifier: MIT */ +/* Same-source C -> canonical Rust -> real LLVM -> owned manifest tests. + * Original LLVM/MTLB fixtures are not Apple compiler output or a GPU reference. + * Optional source mode consumes the retained genuine adapter result unchanged. */ +#include "../library_assembly.h" +#include "../../../common/mesa/src/stela/air_test_fixture.h" +#include +#include +#include +#ifdef NDEBUG +#error "Assembly ownership tests require active assertions" +#endif +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%s:%d: %s\n",__FILE__,__LINE__,#x); abort(); } } while (0) +_Static_assert(sizeof(struct stela_msl_build_identity) == 144,"fixed-byte build identity fixture"); +_Static_assert(sizeof(struct stela_metal_assembly_options) == 32,"assembly options ABI"); +_Static_assert(sizeof(struct stela_metal_assembly_error) == 288,"assembly error ABI"); + +/* Optional test-object-only macro renaming in library_assembly.c replaces its + * direct libc allocation calls with these. Rust/LLVM/CF keep their real normal + * allocators. This is NOT a shipping allocator or public fault-injection API. */ +static size_t allocation_attempts, fail_allocation, live_allocations; +void *stela_assembly_test_malloc(size_t size); +void *stela_assembly_test_calloc(size_t count, size_t size); +void stela_assembly_test_free(void *pointer); +void *stela_assembly_test_malloc(size_t size) +{ + allocation_attempts++; + if (fail_allocation && allocation_attempts == fail_allocation) return NULL; + void *pointer = malloc(size); if (pointer) live_allocations++; + return pointer; +} +void *stela_assembly_test_calloc(size_t count, size_t size) +{ + allocation_attempts++; + if (fail_allocation && allocation_attempts == fail_allocation) return NULL; + void *pointer = calloc(count,size); if (pointer) live_allocations++; + return pointer; +} +void stela_assembly_test_free(void *pointer) +{ + if (pointer) { CHECK(live_allocations); live_allocations--; } + free(pointer); +} +struct bytes { uint8_t *data; size_t count; }; +static void append(struct bytes *b, const void *data, size_t count) +{ + CHECK(count <= SIZE_MAX-b->count); + b->data = realloc(b->data,b->count+count); CHECK(b->data); + memcpy(b->data+b->count,data,count); b->count += count; +} +static void put16(void *data, uint16_t value) +{ + uint8_t *p = data; p[0] = (uint8_t)value; p[1] = (uint8_t)(value >> 8); +} +static void put32(void *data, uint32_t value) +{ + uint8_t *p = data; for (unsigned i = 0; i < 4; i++) p[i] = (uint8_t)(value >> (8*i)); +} +static void put64(void *data, uint64_t value) +{ + uint8_t *p = data; for (unsigned i = 0; i < 8; i++) p[i] = (uint8_t)(value >> (8*i)); +} +static void tag(struct bytes *b, const char name[4], const void *data, size_t count) +{ + CHECK(count <= UINT16_MAX); + uint8_t size[2]; put16(size,(uint16_t)count); + append(b,name,4); append(b,size,2); append(b,data,count); +} +static void digest(const void *data, size_t size, uint8_t output[32]) +{ + CHECK(size <= 64u*1024u*1024u); CC_SHA256(data,(CC_LONG)size,output); +} +struct specification { + const char *name; + uint8_t kind; + uint16_t air_minor, language_major, language_minor; + const void *module; size_t module_bytes; + bool wrong_hash; + const char *function_tag, *public_tag, *private_tag, *header_tag; +}; +static struct bytes archive(const struct specification *entries, unsigned count, + uint16_t major, uint16_t minor) +{ + CHECK(count && count <= 256); + struct bytes records = {0}, code = {0}; + uint64_t offsets[256]; + for (unsigned i = 0; i < count; i++) { + unsigned same; + for (same = 0; same < i; same++) + if (entries[same].module == entries[i].module && entries[same].module_bytes == entries[i].module_bytes) break; + offsets[i] = same < i ? offsets[same] : code.count; + if (same == i) append(&code,entries[i].module,entries[i].module_bytes); + struct bytes record = {0}; uint8_t zero[4] = {0}; append(&record,zero,4); + tag(&record,"NAME",entries[i].name,strlen(entries[i].name)+1); + tag(&record,"TYPE",&entries[i].kind,1); + uint8_t hash[32]; digest(entries[i].module,entries[i].module_bytes,hash); + if (entries[i].wrong_hash) hash[0] ^= 1; + tag(&record,"HASH",hash,32); + uint8_t size[8]; put64(size,entries[i].module_bytes); tag(&record,"MDSZ",size,8); + uint8_t positions[24] = {0}; put64(positions+16,offsets[i]); tag(&record,"OFFT",positions,24); + uint8_t versions[8]; put16(versions,2); put16(versions+2,entries[i].air_minor); + put16(versions+4,entries[i].language_major); put16(versions+6,entries[i].language_minor); + tag(&record,"VERS",versions,8); + if (entries[i].function_tag) tag(&record,entries[i].function_tag,"retained",8); + append(&record,"ENDT",4); + CHECK(record.count <= UINT32_MAX); put32(record.data,(uint32_t)record.count); + append(&records,record.data,record.count); free(record.data); + } + struct bytes result = {0}; uint8_t header[88] = {0}; memcpy(header,"MTLB",4); + put16(header+4,0x8001); put16(header+6,2); put16(header+8,9); + header[11] = 0x81; put16(header+12,major); put16(header+14,minor); + put64(header+24,88); put64(header+32,records.count); + struct bytes extension = {0}, public = {0}, private = {0}; + /* Own fixture writer only; parser/admission facts come from canonical Rust. */ + if (entries[0].header_tag) { + if (strcmp(entries[0].header_tag,"NONE")) tag(&extension,entries[0].header_tag,"identity",8); + append(&extension,"ENDT",4); + } + struct bytes *groups[] = {&public,&private}; + const char *keys[] = {entries[0].public_tag,entries[0].private_tag}; + for (unsigned i = 0; i < 2; i++) if (keys[i]) { + uint8_t zero[4] = {0}; append(groups[i],zero,4); + if (strcmp(keys[i],"NONE")) tag(groups[i],keys[i],"unimplemented",13); + append(groups[i],"ENDT",4); put32(groups[i]->data,(uint32_t)groups[i]->count); + } + size_t start = 88+4+records.count+extension.count; + put64(header+40,start); put64(header+48,public.count); + put64(header+56,start+public.count); put64(header+64,private.count); + put64(header+72,start+public.count+private.count); put64(header+80,code.count); + put64(header+16,start+public.count+private.count+code.count); append(&result,header,sizeof(header)); + uint8_t n[4]; put32(n,count); append(&result,n,4); + append(&result,records.data,records.count); + if (extension.count) append(&result,extension.data,extension.count); + if (public.count) append(&result,public.data,public.count); + if (private.count) append(&result,private.data,private.count); + append(&result,code.data,code.count); + free(extension.data); free(public.data); free(private.data); + free(records.data); free(code.data); return result; +} +static char *replace(const char *text, const char *from, const char *to) +{ + const char *at = strstr(text,from); CHECK(at); + size_t prefix = (size_t)(at-text), tail = strlen(at+strlen(from)); + char *result = malloc(prefix+strlen(to)+tail+1); CHECK(result); + memcpy(result,text,prefix); memcpy(result+prefix,to,strlen(to)); + memcpy(result+prefix+strlen(to),at+strlen(from),tail+1); return result; +} +static struct specification specification(LLVMMemoryBufferRef module, const char *name) +{ + return (struct specification) {.name=name,.kind=2,.air_minor=8,.language_major=4,.language_minor=0, + .module=LLVMGetBufferStart(module),.module_bytes=LLVMGetBufferSize(module)}; +} +static struct stela_metal_assembly *create(const struct bytes *input, enum stela_metal_assembly_status expected) +{ + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; + struct stela_metal_assembly *owner = NULL; + enum stela_metal_assembly_status status = stela_metal_assemble_archive(&options,input->data,input->count,&owner,&error); + if (status != expected) fprintf(stderr,"Assembly status %u expected %u: %s\n",status,expected,error.detail); + CHECK(status == expected && error.status == status && error.abi == 1 && error.size == sizeof(error)); + CHECK((owner != NULL) == (status == STELA_METAL_ASSEMBLY_OK)); + return owner; +} +static void destroy(struct stela_metal_assembly **owner) +{ + stela_metal_assembly_destroy(owner); CHECK(!*owner); + stela_metal_assembly_destroy(owner); stela_metal_assembly_destroy(NULL); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(live_allocations == 0); +#endif +} +static void check_manifest(const struct stela_metal_library_manifest *m, unsigned count) +{ + CHECK(m && m->size == sizeof(*m) && m->abi == 1 && !m->reserved && m->entry_count == count); + CHECK(m->target && m->target_bytes && m->entries); + for (unsigned i = 0; i < count; i++) { + const struct stela_metal_function_record *r = &m->entries[i]; + CHECK(r->size == sizeof(*r) && r->abi == 1 && r->flags == 7 && !r->reserved && !r->reserved_arguments); + CHECK(r->entry.size == sizeof(r->entry) && r->entry.abi == 1 && r->entry.kind == 2 && !r->entry.reserved); + CHECK(r->name && r->name_bytes && strlen((const char *)r->name) == r->name_bytes); + CHECK(r->air_bytes >= 4 && r->air_offset < m->input.original_bytes && + r->air_bytes <= m->input.original_bytes-r->air_offset); + CHECK(r->argument_count <= AIR_MAX_ARGUMENTS); + for (unsigned a = 0; a < r->argument_count; a++) { + const struct stela_air_argument_info *arg = &r->arguments[a]; + CHECK(arg->buffer.argument < r->argument_count); + if (arg->name) CHECK(strlen(arg->name) == arg->name_bytes); + if (arg->type_name) CHECK(strlen(arg->type_name) == arg->type_name_bytes); + if (arg->kind == 1) CHECK(arg->plain_buffer_type && arg->buffer.type_size && arg->buffer.type_alignment); + } + } +} +static void unit_tests(void) +{ + LLVMMemoryBufferRef module = stela_air_test_bitcode(stela_air_test_store_body,""); + struct specification s = specification(module,"kernel"); + struct bytes input = archive(&s,1,26,7); uint8_t original_hash[32]; digest(input.data,input.count,original_hash); + struct stela_metal_assembly *owner = create(&input,STELA_METAL_ASSEMBLY_OK); + memset(input.data,0,input.count); free(input.data); LLVMDisposeMemoryBuffer(module); + /* Destroyed caller bytes AND LLVM buffers/contexts must not own any view. */ + const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(owner); check_manifest(m,1); + CHECK(!m->flags && !m->compiler_profile && !m->request_language && !m->request_fast_math); + CHECK(!memcmp(m->input.original_sha256,original_hash,32)); + CHECK(m->target_bytes == strlen("air64_v28-apple-macosx26.7.0") && + !memcmp(m->target,"air64_v28-apple-macosx26.7.0",m->target_bytes)); + const struct stela_air_argument_info *arg = &m->entries[0].arguments[1]; + CHECK(arg->buffer.argument == 1 && arg->buffer.index == 7 && arg->buffer.address_space == 1 && + arg->buffer.access == STELA_AIR_READ_WRITE && arg->buffer.type_size == 4 && arg->buffer.type_alignment == 4); + CHECK(arg->primitive == STELA_AIR_UINT && arg->type_components == 1 && arg->used && + !strcmp(arg->name,"output") && !strcmp(arg->type_name,"uint")); + struct stela_metal_input_view view = {.size=sizeof(view),.abi=1}; struct stela_metal_assembly_error error; + CHECK(!stela_metal_assembly_original(owner,&view,&error) && !view.original_offset && view.length == m->input.original_bytes); + uint8_t actual_hash[32]; digest(view.bytes,(size_t)view.length,actual_hash); CHECK(!memcmp(actual_hash,original_hash,32)); + digest(view.bytes+m->entries[0].entry.module_offset,(size_t)m->entries[0].entry.module_bytes,actual_hash); + CHECK(!memcmp(actual_hash,m->entries[0].entry.module_sha256,32)); + digest(view.bytes+m->entries[0].air_offset,(size_t)m->entries[0].air_bytes,actual_hash); + CHECK(!memcmp(actual_hash,m->entries[0].air_sha256,32)); + view.abi = 2; view.length = 123; + CHECK(stela_metal_assembly_original(owner,&view,&error) == STELA_METAL_ASSEMBLY_ABI_MISMATCH && view.length == 123); + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + CHECK(stela_metal_assemble_archive(&options,NULL,0,&owner,&error) == STELA_METAL_ASSEMBLY_INPUT && + stela_metal_assembly_manifest(owner) == m); destroy(&owner); CHECK(!stela_metal_assembly_manifest(NULL)); + + module = stela_air_test_bitcode(stela_air_test_store_body,""); s = specification(module,"kernel"); + for (unsigned wrong = 0; wrong < 5; wrong++) { + struct specification bad = s; + if (wrong == 0) bad.name = "absent"; + if (wrong == 1) bad.kind = 0; + if (wrong == 2) bad.air_minor = 9; + if (wrong == 3) bad.language_minor = 1; + if (wrong == 4) bad.wrong_hash = true; + input = archive(&bad,1,26,7); + owner = create(&input,wrong == 4 ? STELA_METAL_ASSEMBLY_CONTAINER : STELA_METAL_ASSEMBLY_IDENTITY); + CHECK(!owner); free(input.data); + } + for (unsigned wrong = 0; wrong < 4; wrong++) { + input = archive(&s,1,26,7); + if (wrong == 0) input.data[4] = 0; + if (wrong == 1) input.data[11] = 0x82; + if (wrong == 2) put16(input.data+12,25); + if (wrong == 3) put16(input.data+14,0); + owner = create(&input,wrong < 2 ? STELA_METAL_ASSEMBLY_CONTAINER : STELA_METAL_ASSEMBLY_IDENTITY); + CHECK(!owner); free(input.data); + } + /* Unknown tags are retained by the parser, never treated as no constants or + * complete reflection by the assembler, even when AIR reflection is plain. */ + for (unsigned unknown = 0; unknown < 8; unknown++) { + struct specification bad = s; + if (unknown == 0) bad.function_tag = "FUTR"; + if (unknown == 1) bad.function_tag = "CNST"; + if (unknown == 2) bad.public_tag = "CNST"; + if (unknown == 3) bad.public_tag = "ARGR"; + if (unknown == 4) bad.public_tag = "RETR"; + if (unknown == 5) bad.private_tag = "DEBI"; + if (unknown == 6) bad.header_tag = "UUID"; + if (unknown == 7) bad.header_tag = "FUTR"; + input = archive(&bad,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_REFLECTION); CHECK(!owner); free(input.data); + } + struct specification empty = s; empty.public_tag = "NONE"; empty.private_tag = "NONE"; empty.header_tag = "NONE"; + input = archive(&empty,1,26,7); owner = create(&input,STELA_METAL_ASSEMBLY_OK); + check_manifest(stela_metal_assembly_manifest(owner),1); destroy(&owner); free(input.data); + input = archive(&s,1,26,7); + for (unsigned bad = 0; bad < 5; bad++) { + options = stela_metal_assembly_default_options(); + if (bad == 0) options.abi++; + if (bad == 1) options.reserved = 1; + if (bad == 2) options.max_entries = 0; + if (bad == 3) options.max_input_bytes = 3; + if (bad == 4) options.max_metadata_bytes = 1; + allocation_attempts = 0; + CHECK(stela_metal_assemble_archive(&options,input.data,input.count,&owner,&error) == + (bad < 2 ? STELA_METAL_ASSEMBLY_ABI_MISMATCH : STELA_METAL_ASSEMBLY_LIMIT) && !owner); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(!allocation_attempts && !live_allocations); +#endif + } + free(input.data); LLVMDisposeMemoryBuffer(module); + + char *metadata = replace(stela_air_test_metadata,"!\"uint\", !\"air.arg_name\", !\"output\"", + "!\"UnknownStructure\", !\"air.arg_name\", !\"output\""); + module = stela_air_test_custom_bitcode(stela_air_test_prefix,stela_air_test_store_body,metadata,""); free(metadata); + s = specification(module,"kernel"); input = archive(&s,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_REFLECTION); CHECK(!owner); free(input.data); LLVMDisposeMemoryBuffer(module); + metadata = replace(stela_air_test_metadata,"!\"output\"","!\"out\\00put\""); + module = stela_air_test_custom_bitcode(stela_air_test_prefix,stela_air_test_store_body,metadata,""); free(metadata); + s = specification(module,"kernel"); input = archive(&s,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_REFLECTION); CHECK(!owner); free(input.data); LLVMDisposeMemoryBuffer(module); + metadata = replace(stela_air_test_metadata,"!\"output\"","!\"out\\FF\""); + module = stela_air_test_custom_bitcode(stela_air_test_prefix,stela_air_test_store_body,metadata,""); free(metadata); + s = specification(module,"kernel"); input = archive(&s,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_REFLECTION); CHECK(!owner); free(input.data); LLVMDisposeMemoryBuffer(module); + metadata = replace(stela_air_test_metadata,"i32 2, i32 8, i32 0","i32 2, i32 7, i32 0"); + module = stela_air_test_custom_bitcode(stela_air_test_prefix,stela_air_test_store_body,metadata,""); free(metadata); + s = specification(module,"kernel"); input = archive(&s,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_AIR); CHECK(!owner); free(input.data); LLVMDisposeMemoryBuffer(module); + module = stela_air_test_bitcode(stela_air_test_store_body,"@unimplemented = constant i32 1\n"); + s = specification(module,"kernel"); input = archive(&s,1,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_REFLECTION); CHECK(!owner); free(input.data); LLVMDisposeMemoryBuffer(module); + + char *prefix = replace(stela_air_test_prefix,"macosx26.7.0","macosx26.7.3"); + module = stela_air_test_custom_bitcode(prefix,stela_air_test_store_body,stela_air_test_metadata,""); free(prefix); + s = specification(module,"kernel"); input = archive(&s,1,26,7); owner = create(&input,STELA_METAL_ASSEMBLY_OK); + CHECK(strstr((const char *)stela_metal_assembly_manifest(owner)->target,"26.7.3")); + destroy(&owner); free(input.data); LLVMDisposeMemoryBuffer(module); + + /* Reversed archive export order, both names in ONE shared original module. */ + metadata = replace(stela_air_test_metadata,"!air.kernel = !{!2}","!air.kernel = !{!2,!11}"); + module = stela_air_test_custom_bitcode(stela_air_test_prefix,stela_air_test_store_body,metadata, + "define void @second(i32 %tid, ptr addrspace(1) %out) { ret void }\n!11 = !{ptr @second,!3,!4}\n"); free(metadata); + struct specification two[] = {specification(module,"second"),specification(module,"kernel")}; + /* Shared AIR can contain more kernels than the archive exports. Check the + * complete module within the explicit inspection budget; export only NAME. */ + input = archive(&two[1],1,26,7); owner = create(&input,STELA_METAL_ASSEMBLY_OK); + check_manifest(stela_metal_assembly_manifest(owner),1); destroy(&owner); free(input.data); + input = archive(two,2,26,7); allocation_attempts = 0; + owner = create(&input,STELA_METAL_ASSEMBLY_OK); size_t successful_allocations = allocation_attempts; + m = stela_metal_assembly_manifest(owner); check_manifest(m,2); + CHECK(!strcmp((const char *)m->entries[0].name,"second") && !strcmp((const char *)m->entries[1].name,"kernel")); + CHECK(m->entries[0].air_offset == m->entries[1].air_offset && + m->entries[0].entry.module_offset == m->entries[1].entry.module_offset && + !memcmp(m->entries[0].air_sha256,m->entries[1].air_sha256,32)); + CHECK(!m->entries[0].arguments[1].used && m->entries[1].arguments[1].used); destroy(&owner); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(successful_allocations >= 6); + for (size_t fail = 1; fail <= successful_allocations; fail++) { + allocation_attempts = 0; fail_allocation = fail; + owner = create(&input,STELA_METAL_ASSEMBLY_ALLOCATION); CHECK(!owner && !live_allocations); + } + fail_allocation = 0; +#else + (void)successful_allocations; +#endif + /* Exhaust the metadata budget only after copying the first shared-module + * export; no partial manifest or live owned C allocation may escape. */ + options = stela_metal_assembly_default_options(); options.max_metadata_bytes = 1200; allocation_attempts = 0; + CHECK(stela_metal_assemble_archive(&options,input.data,input.count,&owner,&error) == STELA_METAL_ASSEMBLY_LIMIT && !owner); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(allocation_attempts == 5 && !live_allocations); +#endif + /* A second record sharing a range cannot bypass a different expected HASH. */ + two[1].wrong_hash = true; struct bytes bad_hash = archive(two,2,26,7); + owner = create(&bad_hash,STELA_METAL_ASSEMBLY_CONTAINER); CHECK(!owner); free(bad_hash.data); + free(input.data); LLVMDisposeMemoryBuffer(module); + + /* Different original modules must agree on the full target, including patch. */ + module = stela_air_test_bitcode(stela_air_test_store_body,""); + prefix = replace(stela_air_test_prefix,"@kernel","@second"); char *target = replace(prefix,"26.7.0","26.7.3"); free(prefix); + metadata = replace(stela_air_test_metadata,"@kernel","@second"); + LLVMMemoryBufferRef second = stela_air_test_custom_bitcode(target,stela_air_test_store_body,metadata,""); free(target); free(metadata); + two[0] = specification(module,"kernel"); two[1] = specification(second,"second"); input = archive(two,2,26,7); + owner = create(&input,STELA_METAL_ASSEMBLY_IDENTITY); CHECK(!owner); + free(input.data); LLVMDisposeMemoryBuffer(module); LLVMDisposeMemoryBuffer(second); + puts("assembly original LLVM/MTLB ownership, identity, reflection, target and failure tests passed"); +} +static struct bytes read_file(const char *path, size_t maximum) +{ + FILE *f = fopen(path,"rb"); CHECK(f && !fseek(f,0,SEEK_END)); long n = ftell(f); + CHECK(n > 0 && (uint64_t)n <= maximum && !fseek(f,0,SEEK_SET)); + struct bytes bytes = {.data=malloc((size_t)n),.count=(size_t)n}; CHECK(bytes.data); + CHECK(fread(bytes.data,1,bytes.count,f) == bytes.count && !fclose(f)); return bytes; +} +static unsigned number(const char *text) +{ + char *end; errno = 0; unsigned long n = strtoul(text,&end,10); + CHECK(!errno && *text && !*end && n <= UINT16_MAX); return (unsigned)n; +} +static void original_archive(int argc, char **argv) +{ + CHECK(argc == 10); /* --archive AIR NAME AIRminor MSLmajor MSLminor OSmajor OSminor expected-refusal */ + struct bytes module = read_file(argv[2],64u*1024u*1024u); + struct specification s = {.name=argv[3],.kind=2,.air_minor=(uint16_t)number(argv[4]), + .language_major=(uint16_t)number(argv[5]),.language_minor=(uint16_t)number(argv[6]), + .module=module.data,.module_bytes=module.count}; + struct bytes input = archive(&s,1,(uint16_t)number(argv[7]),(uint16_t)number(argv[8])); + bool refusal = !strcmp(argv[9],"refuse-reflection"); CHECK(refusal || !strcmp(argv[9],"complete")); + struct stela_metal_assembly *owner = create(&input,refusal ? STELA_METAL_ASSEMBLY_REFLECTION : STELA_METAL_ASSEMBLY_OK); + if (owner) { + const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(owner); check_manifest(m,1); + uint8_t expected[32]; digest(module.data,module.count,expected); + CHECK(!memcmp(expected,m->entries[0].entry.module_sha256,32)); + printf("original-air-manifest entry=%s bytes=%zu air=2.%u language=%u.%u target=%s original_module_sha256=", + argv[3],module.count,s.air_minor,s.language_major,s.language_minor,m->target); + for (unsigned i = 0; i < 32; i++) printf("%02x",expected[i]); puts(""); destroy(&owner); + } else puts("original-air-manifest explicit incomplete-reflection refusal"); + free(input.data); free(module.data); +} +static void original_archive_pair(int argc, char **argv) +{ + CHECK(argc == 11); /* --archive-pair AIR NAME1 NAME2 AIRminor MSLmajor MSLminor OSmajor OSminor complete */ + CHECK(!strcmp(argv[10],"complete")); + struct bytes module = read_file(argv[2],64u*1024u*1024u); + struct specification specs[2]; + for (unsigned i = 0; i < 2; i++) specs[i] = (struct specification){ + .name=argv[3+i],.kind=2,.air_minor=(uint16_t)number(argv[5]), + .language_major=(uint16_t)number(argv[6]),.language_minor=(uint16_t)number(argv[7]), + .module=module.data,.module_bytes=module.count}; + struct bytes input = archive(specs,2,(uint16_t)number(argv[8]),(uint16_t)number(argv[9])); + struct stela_metal_assembly *owner = create(&input,STELA_METAL_ASSEMBLY_OK); + const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(owner);check_manifest(m,2); + uint8_t expected[32];digest(module.data,module.count,expected); + CHECK(m->entries[0].entry.module_offset==m->entries[1].entry.module_offset && + m->entries[0].air_offset==m->entries[1].air_offset); + for(unsigned i=0;i<2;i++) CHECK(!memcmp(expected,m->entries[i].entry.module_sha256,32)&& + m->entries[i].name_bytes==strlen(specs[i].name)&&!memcmp(m->entries[i].name,specs[i].name,m->entries[i].name_bytes)); + memset(module.data,0,module.count);free(module.data);memset(input.data,0,input.count);free(input.data); + check_manifest(stela_metal_assembly_manifest(owner),2); + printf("original-air-manifest-pair entries=%s,%s module_bytes=%zu original_module_sha256=",specs[0].name,specs[1].name,module.count); + for(unsigned i=0;i<32;i++)printf("%02x",expected[i]);puts("");destroy(&owner); +} +static void original_source(int argc, char **argv) +{ + CHECK(argc == 5); /* --source ORIGINAL_MSL ORIGINAL_ADAPTER_AIR RESULT_IDENTITY_208_BYTES */ + struct bytes source = read_file(argv[2],64u*1024u*1024u), air = read_file(argv[3],64u*1024u*1024u); + struct bytes build = read_file(argv[4],208); CHECK(build.count == 208); + struct stela_msl_output compiled = {.air=air.data,.air_bytes=air.count}; + /* Independent original producer receipt: no rehash-to-bless edited files. */ + memcpy(compiled.source_sha256,build.data,32); memcpy(compiled.air_sha256,build.data+32,32); + memcpy(&compiled.build,build.data+64,144); free(build.data); + const struct stela_msl_build_identity expected_build = compiled.build; + uint8_t expected_source_hash[32], expected_air_hash[32]; + memcpy(expected_source_hash,compiled.source_sha256,32); memcpy(expected_air_hash,compiled.air_sha256,32); + struct stela_msl_apple_config config = stela_msl_apple_default_config(); + struct stela_msl_request request = {.source=source.data,.source_bytes=source.count, + .language_version=0x40001,.fast_math=true,.target_triple="air64_v29-apple-macosx27.2.0"}; + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *owner = NULL; + for (unsigned bad = 0; bad < 7; bad++) { + struct stela_msl_output wrong = compiled; struct stela_msl_request wrong_request = request; + struct stela_msl_apple_config wrong_config = config; + if (bad == 0) wrong.air_sha256[0] ^= 1; + if (bad == 1) wrong.source_sha256[0] ^= 1; + if (bad == 2) memset(wrong.build.gpucompiler_uuid,0,16); + if (bad == 3) wrong_request.fast_math = false; + if (bad == 4) wrong_request.target_triple = "air64_v29-apple-macosx27.3.0"; + if (bad == 5) wrong_request.language_version = 0x30001; + if (bad == 6) wrong_config.profile = 0; + CHECK(stela_metal_assemble_source(&options,&wrong_config,&wrong_request,&wrong,&owner,&error) == STELA_METAL_ASSEMBLY_SOURCE && !owner); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(!live_allocations); +#endif + } + allocation_attempts = 0; + enum stela_metal_assembly_status status = stela_metal_assemble_source(&options,&config,&request,&compiled,&owner,&error); + if (status) fprintf(stderr,"Source assembly refused: %s\n",error.detail); + CHECK(!status && owner); size_t successful_allocations = allocation_attempts; + const struct stela_metal_library_manifest *m = stela_metal_assembly_manifest(owner); + unsigned entries = m->entry_count; check_manifest(m,entries); + CHECK(m->flags == STELA_METAL_LIBRARY_SOURCE_COMPILED && m->compiler_profile == 1 && + m->request_language == request.language_version && m->request_fast_math == 1 && + !memcmp(&m->build,&compiled.build,sizeof(m->build)) && !memcmp(m->source_sha256,compiled.source_sha256,32) && + !memcmp(m->input.original_sha256,compiled.air_sha256,32)); + for (unsigned i = 0; i < entries; i++) CHECK(m->entries[i].entry.module_offset == 0 && + m->entries[i].entry.module_bytes == air.count && !memcmp(m->entries[i].entry.module_sha256,compiled.air_sha256,32)); + destroy(&owner); +#ifdef STELA_ASSEMBLY_ALLOC_TEST + CHECK(successful_allocations >= 5); + for (size_t fail = 1; fail <= successful_allocations; fail++) { + allocation_attempts = 0; fail_allocation = fail; + CHECK(stela_metal_assemble_source(&options,&config,&request,&compiled,&owner,&error) == STELA_METAL_ASSEMBLY_ALLOCATION && + !owner && !live_allocations); + } + fail_allocation = 0; +#else + (void)successful_allocations; +#endif + CHECK(!stela_metal_assemble_source(&options,&config,&request,&compiled,&owner,&error)); + memset(source.data,0,source.count); free(source.data); memset(air.data,0,air.count); free(air.data); + memset(&compiled,0,sizeof(compiled)); memset(&request,0,sizeof(request)); + m = stela_metal_assembly_manifest(owner); check_manifest(m,entries); + CHECK(!memcmp(&m->build,&expected_build,sizeof(expected_build)) && + !memcmp(m->source_sha256,expected_source_hash,32) && !memcmp(m->input.original_sha256,expected_air_hash,32)); + CHECK(m->target_bytes == strlen("air64_v29-apple-macosx27.2.0") && !memcmp(m->target,"air64_v29-apple-macosx27.2.0",m->target_bytes)); + printf("original-source-manifest entries=%u profile=%u original_bytes=%llu original_sha256=", + m->entry_count,m->compiler_profile,(unsigned long long)m->input.original_bytes); + for (unsigned i = 0; i < 32; i++) printf("%02x",m->input.original_sha256[i]); puts(""); destroy(&owner); +} +int main(int argc, char **argv) +{ + unit_tests(); + if (argc > 1 && !strcmp(argv[1],"--archive")) original_archive(argc,argv); + else if (argc > 1 && !strcmp(argv[1],"--source")) original_source(argc,argv); + else if (argc > 1 && !strcmp(argv[1],"--archive-pair")) original_archive_pair(argc,argv); + else CHECK(argc == 1); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup.c b/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup.c new file mode 100644 index 0000000000..01e651f446 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup.c @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: MIT */ +#include "../threadgroup.h" +#include +#include +#include +#ifdef NDEBUG +#error "Threadgroup value tests require active assertions" +#endif +static struct stela_air_argument_info argument(unsigned ordinal, unsigned index, unsigned alignment) +{ + return (struct stela_air_argument_info){.kind = 1, .plain_buffer_type = true, + .buffer = {.argument = ordinal, .index = index, .address_space = 3, + .access = STELA_AIR_READ_WRITE, .type_size = 4, .type_alignment = alignment}}; +} +static void refusal(const struct stela_air_argument_info *args, unsigned count, + const struct stela_metal_threadgroup_request *request, unsigned max_bytes, + enum stela_metal_threadgroup_status expected) +{ + struct stela_metal_threadgroup_specialization result, original; + memset(&result, 0xa5, sizeof(result)); original = result; + assert(stela_metal_threadgroup_normalize(args, count, request, max_bytes, &result) == expected); + assert(!memcmp(&result, &original, sizeof(result))); +} +int main(void) +{ + struct stela_air_argument_info args[] = {argument(4, 7, 4), argument(1, 3, 16), argument(2, 7, 4)}; + args[2].buffer.address_space = 1; /* Same numeric AS1/AS3 index is legal. */ + struct stela_metal_threadgroup_request_row rows[] = {{.index = 3, .bytes = 256}, {.index = 7, .bytes = 128}}; + struct stela_metal_threadgroup_request request = {.size = sizeof(request), + .abi = STELA_METAL_THREADGROUP_ABI, .count = 2, .rows = rows}; + struct stela_metal_threadgroup_specialization result; + assert(stela_metal_threadgroup_normalize(args, 3, &request, 384, &result) == STELA_METAL_THREADGROUP_OK); + assert(result.count == 2 && result.bindings[0].buffer.argument == 4 && result.bindings[0].buffer.index == 7 && + result.bindings[0].bytes == 128 && result.bindings[0].alignment == 16 && + result.bindings[1].buffer.argument == 1 && result.bindings[1].bytes == 256); + assert(stela_metal_threadgroup_matches(&result, &request)); + args[0].buffer.type_size = 16; assert(result.bindings[0].buffer.type_size == 4); args[0].buffer.type_size = 4; + struct stela_metal_threadgroup_request_row saved = rows[0]; rows[0] = rows[1]; rows[1] = saved; + assert(stela_metal_threadgroup_matches(&result, &request)); + rows[0].bytes = 144; assert(!stela_metal_threadgroup_matches(&result, &request)); rows[0].bytes = 128; + assert(!stela_metal_threadgroup_matches(&result, NULL)); + refusal(args, 3, NULL, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); + refusal(args, 3, &request, 383, STELA_METAL_THREADGROUP_LIMIT); + for (unsigned i = 0; i < 5; i++) { + const uint64_t invalid[] = {0, 3, 15, 17, UINT64_MAX}; + rows[0].bytes = invalid[i]; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); + } + rows[0].bytes = UINT64_C(0x100000000); + refusal(args, 3, &request, UINT32_MAX, STELA_METAL_THREADGROUP_LIMIT); rows[0].bytes = 128; + rows[0].reserved = 1; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); rows[0].reserved = 0; + rows[0].index = 3; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); rows[0].index = 7; + rows[0].index = 9; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); rows[0].index = 7; + request.count = 1; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); request.count = 2; + request.size--; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); request.size++; + request.abi++; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); request.abi--; + request.reserved = 1; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); request.reserved = 0; + request.count = AIR_MAX_ARGUMENTS + 1; request.rows = (const void *)(uintptr_t)1; + refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); + request.count = 2; request.rows = NULL; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_INVALID); + request.rows = rows; + refusal((const void *)(uintptr_t)1, AIR_MAX_ARGUMENTS + 1, &request, 384, STELA_METAL_THREADGROUP_INVALID); + args[0].plain_buffer_type = false; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); + args[0].plain_buffer_type = true; args[0].buffer.type_alignment = 3; + refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); args[0].buffer.type_alignment = 4; + args[0].buffer.type_size = 256; refusal(args, 3, &request, 384, STELA_METAL_THREADGROUP_UNSUPPORTED); + args[0].buffer.type_size = 4; + assert(stela_metal_threadgroup_normalize(NULL, 0, NULL, 0, &result) == STELA_METAL_THREADGROUP_OK && !result.count); + assert(stela_metal_threadgroup_matches(&result, NULL)); + refusal(NULL, 0, &request, 384, STELA_METAL_THREADGROUP_INVALID); + puts("threadgroup exact-index/length/alignment ownership, equality, budgets and atomic refusals passed"); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup_nir.c b/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup_nir.c new file mode 100644 index 0000000000..f0ad03b367 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/tests/threadgroup_nir.c @@ -0,0 +1,123 @@ +/* SPDX-License-Identifier: MIT */ +/* Original LLVM fixtures and existing NIR optimization; no GPU interpreter. */ +#include "../threadgroup.h" +#include "stela/air_to_nir.h" +#include "stela/air_test_fixture.h" +#include "util/ralloc.h" +#include +#include +#include +#ifdef NDEBUG +#error "Threadgroup semantics require active assertions" +#endif +static const nir_shader_compiler_options nir_options = {.max_unroll_iterations = 32}; +static LLVMMemoryBufferRef fixture(void) +{ + const char *prefix = "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v29-apple-macosx27.2.0\"\n" + "@used = internal addrspace(3) global [3 x i8] undef, align 1\n" + "@unused = internal addrspace(3) global [4096 x i8] undef, align 256\n" + "declare void @air.wg.barrier(i32,i32,i32) convergent nounwind\n" + "define void @kernel(i32 %tid,ptr addrspace(1) %out,ptr addrspace(3) %first,ptr addrspace(3) %second,ptr addrspace(3) %dead) {\n"; + const char *body = "store i32 11,ptr addrspace(3) %first,align 4\n" + "store i32 22,ptr addrspace(3) %second,align 4\n" + "%p = getelementptr i32,ptr addrspace(3) %first,i64 31\nstore i32 33,ptr addrspace(3) %p,align 4\n" + "%bit = and i32 %tid,1\n%zero = icmp eq i32 %bit,0\n%index = select i1 %zero,i64 63,i64 64\n" + "%q = getelementptr i32,ptr addrspace(3) %second,i64 %index\nstore i32 44,ptr addrspace(3) %q,align 4\n" + "store i8 55,ptr addrspace(3) @used,align 1\n" + "call void @air.wg.barrier(i32 2,i32 5,i32 1) convergent\n" + "%a = load i32,ptr addrspace(3) %first,align 4\n%b = load i32,ptr addrspace(3) %second,align 4\n" + "%sum = add i32 %a,%b\nstore i32 %sum,ptr addrspace(1) %out,align 4\nret void\n"; + const char *metadata = "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!llvm.ident = !{!10}\n!llvm.module.flags = !{!11}\n" + "!0 = !{i32 2,i32 9,i32 0}\n!1 = !{!\"Metal\",i32 4,i32 1,i32 0}\n" + "!2 = !{ptr @kernel,!3,!4}\n!3 = !{}\n!4 = !{!5,!6,!7,!8,!9}\n" + "!5 = !{i32 0,!\"air.thread_position_in_grid\",!\"air.arg_type_name\",!\"uint\",!\"air.arg_name\",!\"tid\"}\n" + "!6 = !{i32 1,!\"air.buffer\",!\"air.location_index\",i32 7,i32 1,!\"air.read_write\",!\"air.address_space\",i32 1,!\"air.arg_type_size\",i32 4,!\"air.arg_type_align_size\",i32 4,!\"air.arg_type_name\",!\"uint\",!\"air.arg_name\",!\"output\"}\n" + "!7 = !{i32 2,!\"air.buffer\",!\"air.location_index\",i32 7,i32 1,!\"air.read_write\",!\"air.address_space\",i32 3,!\"air.arg_type_size\",i32 4,!\"air.arg_type_align_size\",i32 4,!\"air.arg_type_name\",!\"uint\",!\"air.arg_name\",!\"first\"}\n" + "!8 = !{i32 3,!\"air.buffer\",!\"air.location_index\",i32 3,i32 1,!\"air.read_write\",!\"air.address_space\",i32 3,!\"air.arg_type_size\",i32 4,!\"air.arg_type_align_size\",i32 4,!\"air.arg_type_name\",!\"uint\",!\"air.arg_name\",!\"second\"}\n" + "!9 = !{i32 4,!\"air.buffer\",!\"air.location_index\",i32 11,i32 1,!\"air.read_write\",!\"air.address_space\",i32 3,!\"air.arg_type_size\",i32 4,!\"air.arg_type_align_size\",i32 4,!\"air.arg_type_name\",!\"uint\",!\"air.arg_name\",!\"dead\"}\n" + "!10 = !{!\"Apple metal version 32023.922 (metalfe-32023.922.4)\"}\n" + "!11 = !{i32 7,!\"air.max_threadgroup_buffers\",i32 31}\n"; + return stela_air_test_custom_bitcode(prefix,body,metadata,""); +} +struct bindings {struct stela_metal_threadgroup_specialization shared; unsigned callbacks;}; +static bool inspect(const struct stela_air_inspection *module,const struct stela_air_entry *entry,void *data) +{ + (void)module;struct bindings *b=data;assert(entry->reflection_complete); + const struct stela_metal_threadgroup_request_row rows[]={{.index=3,.bytes=256},{.index=11,.bytes=16},{.index=7,.bytes=128}}; + const struct stela_metal_threadgroup_request request={.size=sizeof(request),.abi=STELA_METAL_THREADGROUP_ABI,.count=3,.rows=rows}; + assert(stela_metal_threadgroup_normalize(entry->arguments,entry->argument_count,&request,512,&b->shared)==STELA_METAL_THREADGROUP_OK); + assert(b->shared.count==3&&!entry->arguments[4].used);return true; +} +static bool bind_shared(const struct stela_air_buffer *buffer,struct stela_air_threadgroup_view *view,void *data) +{ + struct bindings *b=data; + for(unsigned i=0;ishared.count;i++) { + const struct stela_metal_threadgroup_binding *row=&b->shared.bindings[i]; + if(row->buffer.argument==buffer->argument){assert(row->buffer.index==buffer->index);b->callbacks++; + *view=(struct stela_air_threadgroup_view){.size=row->bytes,.alignment=row->alignment,.available_access=STELA_AIR_READ_WRITE};return true;} + } + return false; +} +static nir_def *bind_buffer(nir_builder *b,const struct stela_air_buffer *buffer,void *data) +{ + (void)data;assert(buffer->argument==1&&buffer->index==7&&buffer->address_space==1); + return nir_imm_int64(b,0x100000); /* Semantic fixture only, never production ABI. */ +} +static void specialize(nir_shader *nir,unsigned tid) +{ + nir_builder b=nir_builder_at(nir_after_impl(nir_shader_get_entrypoint(nir))); + nir_foreach_function_impl(impl,nir) { + nir_foreach_block(block,impl) { + nir_foreach_instr_safe(instr,block) { + if(instr->type!=nir_instr_type_intrinsic)continue; + nir_intrinsic_instr *in=nir_instr_as_intrinsic(instr); + if(in->intrinsic==nir_intrinsic_load_local_invocation_id||in->intrinsic==nir_intrinsic_load_workgroup_id){ + b.cursor=nir_before_instr(instr);nir_def *v=nir_imm_ivec3(&b,in->intrinsic==nir_intrinsic_load_local_invocation_id?(int32_t)tid:0,0,0); + nir_def_rewrite_uses(&in->def,v);nir_instr_remove(instr); + } + } + } + } + bool progress; + do{progress=nir_opt_constant_folding(nir);progress|=nir_opt_copy_prop(nir);progress|=nir_opt_dce(nir);progress|=nir_opt_dead_cf(nir);}while(progress); + nir_validate_shader(nir,"independent dynamic view boundaries"); +} +static void effects(nir_shader *nir,unsigned tid) +{ + specialize(nir,tid);unsigned stores=0,loads=0,barriers=0; + const unsigned offsets[]={0,128,124,380,400},values[]={11,22,33,44,55}; + nir_foreach_function_impl(impl,nir)nir_foreach_block(block,impl)nir_foreach_instr(instr,block) { + if(instr->type!=nir_instr_type_intrinsic)continue; + nir_intrinsic_instr *in=nir_instr_as_intrinsic(instr); + if(in->intrinsic==nir_intrinsic_store_shared){unsigned expected=stores;if(tid&&stores==3)expected++; + assert(!barriers&&nir_src_is_const(in->src[0])&&nir_src_is_const(in->src[1])&&expected<5); + assert(nir_src_as_uint(in->src[0])==values[expected]&&nir_src_as_uint(in->src[1])+(uint32_t)nir_intrinsic_base(in)==offsets[expected]);stores++; + }else if(in->intrinsic==nir_intrinsic_barrier){assert(stores==(tid?4u:5u)); + assert(nir_intrinsic_execution_scope(in)==SCOPE_WORKGROUP&&nir_intrinsic_memory_scope(in)==SCOPE_WORKGROUP&& + nir_intrinsic_memory_semantics(in)==NIR_MEMORY_ACQ_REL&&nir_intrinsic_memory_modes(in)==nir_var_mem_shared);barriers++; + }else if(in->intrinsic==nir_intrinsic_load_shared){assert(barriers==1);loads++;} + } + assert(stores==(tid?4u:5u)&&loads==2&&barriers==1); +} +int main(int argc,char **argv) +{ + assert(argc==1||(argc==3&&!strcmp(argv[1],"--export"))); + LLVMMemoryBufferRef input=fixture();struct bindings b={0};struct stela_air_error error; + assert(stela_air_inspect(LLVMGetBufferStart(input),LLVMGetBufferSize(input),8,inspect,&b,&error)); + glsl_type_singleton_init_or_ref(); + for(unsigned tid=0;tid<2;tid++) { + struct stela_air_options options={.workgroup_size={64,1,1},.max_instructions=4096,.bind_buffer=bind_buffer, + .bind_threadgroup=bind_shared,.binding_data=&b,.max_threadgroup_bytes=512};b.callbacks=0; + nir_shader *nir=stela_air_to_nir(LLVMGetBufferStart(input),LLVMGetBufferSize(input),"kernel",&nir_options,&options,&error); + if(!nir)fprintf(stderr,"AIR%u %s\n",error.kind,error.detail); + assert(nir&&b.callbacks==3&&nir->info.shared_size==403);effects(nir,tid);ralloc_free(nir); + options.max_threadgroup_bytes=400; + assert(!stela_air_to_nir(LLVMGetBufferStart(input),LLVMGetBufferSize(input),"kernel",&nir_options,&options,&error)&&error.kind==STELA_AIR_LIMIT); + } + if(argc==3){FILE *f=fopen(argv[2],"wx");assert(f);assert(LLVMGetBufferSize(input)<65536); + assert(fwrite(LLVMGetBufferStart(input),1,LLVMGetBufferSize(input),f)==LLVMGetBufferSize(input)&&!fclose(f));} + glsl_type_singleton_decref();LLVMDisposeMemoryBuffer(input); + puts("original LLVM dynamic views: distinct regions, last-valid/OOB path effects, barrier ordering, unused global and combined limit passed");return 0; +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.c b/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.c new file mode 100644 index 0000000000..6528e13287 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.c @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: MIT */ +#include "threadgroup.h" +#include + +static bool request_valid(const struct stela_metal_threadgroup_request *request) +{ + if (!request) return true; + if (request->size != sizeof(*request) || request->abi != STELA_METAL_THREADGROUP_ABI || + request->reserved || request->count > AIR_MAX_ARGUMENTS || (request->count && !request->rows)) return false; + for (unsigned i = 0; i < request->count; i++) { + if (request->rows[i].reserved) return false; + for (unsigned j = 0; j < i; j++) + if (request->rows[j].index == request->rows[i].index) return false; + } + return true; +} +static const struct stela_metal_threadgroup_request_row *find( + const struct stela_metal_threadgroup_request *request, unsigned index) +{ + if (request) { + for (unsigned i = 0; i < request->count; i++) + if (request->rows[i].index == index) return &request->rows[i]; + } + return NULL; +} +enum stela_metal_threadgroup_status stela_metal_threadgroup_normalize( + const struct stela_air_argument_info *arguments, uint32_t argument_count, + const struct stela_metal_threadgroup_request *request, uint32_t max_bytes, + struct stela_metal_threadgroup_specialization *output) +{ + if (!output || argument_count > AIR_MAX_ARGUMENTS || (argument_count && !arguments) || !request_valid(request)) + return STELA_METAL_THREADGROUP_INVALID; + struct stela_metal_threadgroup_specialization result = {0}; + uint64_t total = 0; + for (unsigned i = 0; i < argument_count; i++) { + const struct stela_air_argument_info *arg = &arguments[i]; + if (arg->kind != 1 || arg->buffer.address_space != 3) continue; + const struct stela_air_buffer *b = &arg->buffer; + if (!arg->plain_buffer_type || !b->type_size || !b->type_alignment || + (b->type_alignment & (b->type_alignment - 1)) || b->access < STELA_AIR_READ || b->access > STELA_AIR_READ_WRITE) + return STELA_METAL_THREADGROUP_UNSUPPORTED; + for (unsigned j = 0; j < result.count; j++) + if (result.bindings[j].buffer.index == b->index || result.bindings[j].buffer.argument == b->argument) + return STELA_METAL_THREADGROUP_INVALID; + const struct stela_metal_threadgroup_request_row *row = find(request, b->index); + if (!row || !row->bytes || row->bytes < b->type_size || row->bytes % STELA_METAL_THREADGROUP_ALIGNMENT) + return STELA_METAL_THREADGROUP_UNSUPPORTED; + unsigned alignment = b->type_alignment < STELA_METAL_THREADGROUP_ALIGNMENT ? + STELA_METAL_THREADGROUP_ALIGNMENT : b->type_alignment; + if (!max_bytes || row->bytes > max_bytes || total > max_bytes - row->bytes || alignment > max_bytes) + return STELA_METAL_THREADGROUP_LIMIT; + total += row->bytes; + result.bindings[result.count++] = (struct stela_metal_threadgroup_binding) { + .buffer = *b, .bytes = row->bytes, .alignment = alignment, + }; + } + if (request && result.count != request->count) return STELA_METAL_THREADGROUP_INVALID; + *output = result; + return STELA_METAL_THREADGROUP_OK; +} +bool stela_metal_threadgroup_matches(const struct stela_metal_threadgroup_specialization *compiled, + const struct stela_metal_threadgroup_request *request) +{ + if (!compiled || compiled->count > AIR_MAX_ARGUMENTS || !request_valid(request) || + compiled->count != (request ? request->count : 0)) return false; + for (unsigned i = 0; i < compiled->count; i++) { + const struct stela_metal_threadgroup_request_row *row = find(request, compiled->bindings[i].buffer.index); + if (!row || row->bytes != compiled->bindings[i].bytes) return false; + } + return true; +} diff --git a/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.h b/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.h new file mode 100644 index 0000000000..8ca55567b1 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/compiler/threadgroup.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_METAL_THREADGROUP_H +#define STELA_METAL_THREADGROUP_H +#include "../../common/mesa/src/stela/air_metadata.h" +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +#define STELA_METAL_THREADGROUP_ABI 1u +#define STELA_METAL_THREADGROUP_ALIGNMENT 16u + +/* Same-process borrowed values, never an IPC wire format or resource authority. + * The real encoder supplies its selected entry's requested byte lengths from + * setThreadgroupMemoryLength:atIndex:. Unrelated encoder bindings are omitted. + * Zero/unknown lengths remain unsupported by the current nonempty-view frontend. + * All reserved fields must be zero. Storage is valid/disjoint/serialized. */ +struct stela_metal_threadgroup_request_row { + uint32_t index, reserved; + uint64_t bytes; +}; +struct stela_metal_threadgroup_request { + uint32_t size, abi, count, reserved; + const struct stela_metal_threadgroup_request_row *rows; +}; +struct stela_metal_threadgroup_binding { + struct stela_air_buffer buffer; + uint64_t bytes; + uint32_t alignment; +}; +/* Copied fixed-size normalized identity in AIR metadata order, including unused + * declared AS3 arguments. Backend total shared memory includes this dynamic + * specialization and layout padding: it is NOT staticThreadgroupMemoryLength. + * Neither total-minus-requested-lengths nor a hardware capability is inferred. + * Source/static accounting and a public Metal PSO remain separate contracts. */ +struct stela_metal_threadgroup_specialization { + uint32_t count; + struct stela_metal_threadgroup_binding bindings[AIR_MAX_ARGUMENTS]; +}; +enum stela_metal_threadgroup_status { + STELA_METAL_THREADGROUP_OK, + STELA_METAL_THREADGROUP_INVALID, + STELA_METAL_THREADGROUP_UNSUPPORTED, + STELA_METAL_THREADGROUP_LIMIT, +}; +/* No allocation or lowering. The explicit limit is the actual backend's shared + * byte representation/capacity; original NIR additionally checks combined static + * and dynamic aligned layout. Failure leaves output unchanged. NULL request + * means no supplied lengths, and succeeds only when there are no declared AS3 + * arguments. Successful storage owns no input pointers. */ +enum stela_metal_threadgroup_status stela_metal_threadgroup_normalize( + const struct stela_air_argument_info *, uint32_t argument_count, + const struct stela_metal_threadgroup_request *, uint32_t max_bytes, + struct stela_metal_threadgroup_specialization *output); + +/* Exact selected dispatch value comparison only, independent of row ordering. + * Target/compiler/options/workgroup/profile and all input identities remain + * separate required cache keys. This establishes no device/VM ownership, + * reservation, memory visibility, lifetime, submission or completion. */ +bool stela_metal_threadgroup_matches(const struct stela_metal_threadgroup_specialization *, + const struct stela_metal_threadgroup_request *); +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/metal/input/Cargo.toml b/crates/stela-drivers/src/gpu/metal/input/Cargo.toml new file mode 100644 index 0000000000..7d5836c772 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "stela-metal-input" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[lib] +path = "lib.rs" +crate-type = ["rlib", "staticlib"] + +[dependencies] +sha2 = { version = "0.10", default-features = false } diff --git a/crates/stela-drivers/src/gpu/metal/input/input.h b/crates/stela-drivers/src/gpu/metal/input/input.h new file mode 100644 index 0000000000..4fe92351c9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/input.h @@ -0,0 +1,101 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_METAL_INPUT_H +#define STELA_METAL_INPUT_H +#include +#ifdef __cplusplus +extern "C" { +#endif +#define STELA_METAL_INPUT_ABI 1u +#define STELA_METAL_INPUT_MTLB 1u +#define STELA_METAL_INPUT_RAW_AIR 2u +#define STELA_METAL_INIT(type) {sizeof(type), STELA_METAL_INPUT_ABI} +enum stela_metal_input_status { + STELA_METAL_INPUT_OK = 0, + STELA_METAL_INPUT_INVALID = 1, + STELA_METAL_INPUT_ABI_MISMATCH = 2, + STELA_METAL_INPUT_LIMIT = 3, + STELA_METAL_INPUT_PARSE = 4, + STELA_METAL_INPUT_ALLOCATION = 5, + STELA_METAL_INPUT_INDEX = 6, + STELA_METAL_INPUT_NOT_ARCHIVE = 7, +}; +struct stela_metal_input_limits { + uint32_t size, abi, kind, max_entries; + uint64_t max_bytes; +}; +struct stela_metal_input_error { + uint32_t size, abi, status, parser_kind; + uint64_t offset; +}; +struct stela_metal_input_info { + uint32_t size, abi, kind, entry_count; + uint64_t original_bytes; + uint8_t original_sha256[32]; + uint32_t platform, format_major, format_minor, library_kind, target_os; + uint32_t minimum_os_major, minimum_os_minor; +}; +struct stela_metal_input_entry { + uint32_t size, abi, kind, air_major, air_minor, language_major, language_minor; + uint32_t reserved; + uint64_t module_offset, module_bytes; + uint8_t module_sha256[32]; +}; +/* Counts exclude ENDT. Ranges include it and use original snapshot offsets. + * Absent streams are (count,offset,bytes)=(0,0,0); an ENDT-only stream has + * count0/bytes4. These are structural facts, NOT reflection/no-constants proof. */ +struct stela_metal_input_entry_metadata { + uint32_t size, abi, function_tags, public_tags, private_tags, header_tags; + uint64_t function_offset, function_bytes, public_offset, public_bytes; + uint64_t private_offset, private_bytes, header_offset, header_bytes; +}; +struct stela_metal_input_view { + uint32_t size, abi; + const uint8_t *bytes; + uint64_t length; + uint64_t original_offset; /* UINT64_MAX for copied names. */ +}; +struct stela_metal_input; +/* Local, same-process/CPU C ABI only. NEVER serialize pointers/handles in IPC. + * The helper uses normal hosted Rust/macOS allocation; no hardware crate, + * custom allocator, LLVM implementation or Metal device is linked by this package. + * + * Open owns a byte snapshot and validates container/framing, NOT LLVM semantics, + * compiler provenance, target/GPU support or an executable pipeline. Raw AIR has + * no archive entries: pass its raw view to the real shared LLVM inspector. + * MTLB entry AIR queries verify the selected digest using the canonical parser. + * The helper must run that same inspector and cross-check names/stages/versions + * before publishing any Metal function manifest. Unknown fields stay visible. + * + * Limits bound the function-table reserve before allocation. parser_kind 17 is + * ResourceLimit and returns the existing LIMIT status; codes 1..16 are unchanged. + * Limits/output records must carry exact sizeof(record)/ABI1. Error is optional + * and, when supplied, points to a complete error record. Failures preserve every + * output except error. Bytes are immutable borrowed views until destroy; caller + * must serialize destruction with all accesses. Close the one owning slot once; + * destroy(NULL or an empty slot) is harmless. Do not copy owning raw handles. */ +uint32_t stela_metal_input_open(const struct stela_metal_input_limits *, + const uint8_t *, uint64_t, struct stela_metal_input **, + struct stela_metal_input_error *); +uint32_t stela_metal_input_info(const struct stela_metal_input *, + struct stela_metal_input_info *, struct stela_metal_input_error *); +uint32_t stela_metal_input_entry(const struct stela_metal_input *, uint32_t, + struct stela_metal_input_entry *, struct stela_metal_input_error *); +/* Additive ABI1 query. RAW_AIR returns NOT_ARCHIVE, preserving output. */ +uint32_t stela_metal_input_entry_metadata(const struct stela_metal_input *, uint32_t, + struct stela_metal_input_entry_metadata *, struct stela_metal_input_error *); +uint32_t stela_metal_input_name(const struct stela_metal_input *, uint32_t, + struct stela_metal_input_view *, struct stela_metal_input_error *); +/* index must be zero for RAW_AIR. Archive AIR is the selected original module's + * raw LLVM bitcode. The original wrapped bytes remain retained and hashed. */ +uint32_t stela_metal_input_air(const struct stela_metal_input *, uint32_t, + struct stela_metal_input_view *, struct stela_metal_input_error *); +/* Entire original retained bytes, including container metadata/unknown fields + * and wrapper. Use this immutable view for authenticated helper output; do not + * re-read a caller buffer after parsing and assume it is still the same input. */ +uint32_t stela_metal_input_original(const struct stela_metal_input *, + struct stela_metal_input_view *, struct stela_metal_input_error *); +void stela_metal_input_destroy(struct stela_metal_input **); +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/metal/input/lib.rs b/crates/stela-drivers/src/gpu/metal/input/lib.rs new file mode 100644 index 0000000000..7c87688e1e --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/lib.rs @@ -0,0 +1,530 @@ +//! Hosted, local C ownership boundary around the one canonical Metal parser. +//! This is input validation, never LLVM verification or a Metal device facade. +extern crate alloc; +#[path = "../library.rs"] +pub mod library; + +use core::{mem, ptr, slice}; +use library::{Air, Library}; +use sha2::{Digest, Sha256}; + +const ABI: u32 = 1; +const MTLB: u32 = 1; +const RAW: u32 = 2; +const MAX_BYTES: u64 = 64 * 1024 * 1024; +const MAX_ENTRIES: u32 = 256; +const OK: u32 = 0; +const INVALID: u32 = 1; +const ABI_MISMATCH: u32 = 2; +const LIMIT: u32 = 3; +const PARSE: u32 = 4; +const ALLOCATION: u32 = 5; +const INDEX: u32 = 6; +const NOT_ARCHIVE: u32 = 7; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Limits { + pub size: u32, + pub abi: u32, + pub kind: u32, + pub max_entries: u32, + pub max_bytes: u64, +} +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Error { + pub size: u32, + pub abi: u32, + pub status: u32, + pub parser_kind: u32, + pub offset: u64, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Info { + pub size: u32, + pub abi: u32, + pub kind: u32, + pub entry_count: u32, + pub original_bytes: u64, + pub original_sha256: [u8; 32], + pub platform: u32, + pub format_major: u32, + pub format_minor: u32, + pub library_kind: u32, + pub target_os: u32, + pub minimum_os_major: u32, + pub minimum_os_minor: u32, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Entry { + pub size: u32, + pub abi: u32, + pub kind: u32, + pub air_major: u32, + pub air_minor: u32, + pub language_major: u32, + pub language_minor: u32, + pub reserved: u32, + pub module_offset: u64, + pub module_bytes: u64, + pub module_sha256: [u8; 32], +} +/// Canonical tag counts/ranges; absence is (0,0,0), ENDT-only groups have +/// zero tags and four original bytes. This does not assert tag semantics. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EntryMetadata { + pub size: u32, + pub abi: u32, + pub function_tags: u32, + pub public_tags: u32, + pub private_tags: u32, + pub header_tags: u32, + pub function_offset: u64, + pub function_bytes: u64, + pub public_offset: u64, + pub public_bytes: u64, + pub private_offset: u64, + pub private_bytes: u64, + pub header_offset: u64, + pub header_bytes: u64, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct View { + pub size: u32, + pub abi: u32, + pub bytes: *const u8, + pub length: u64, + pub original_offset: u64, +} +struct OwnedEntry { + name: String, + info: Entry, + metadata: EntryMetadata, +} +pub struct Input { + bytes: Vec, + info: Info, + entries: Vec, +} + +fn parser_kind(kind: library::ErrorKind) -> u32 { + use library::ErrorKind as K; + match kind { + K::Truncated => 1, + K::Overflow => 2, + K::Magic => 3, + K::Version => 4, + K::FileSize => 5, + K::SectionOverlap => 6, + K::FunctionCount => 7, + K::TagSize => 8, + K::DuplicateTag(_) => 9, + K::MissingTag(_) => 10, + K::Terminator => 11, + K::Name => 12, + K::Metadata => 13, + K::Hash => 14, + K::Bitcode => 15, + K::Allocation => 16, + K::ResourceLimit => 17, + } +} +#[derive(Clone, Copy, Debug)] +struct Failure { + status: u32, + kind: u32, + offset: u64, +} +impl From for Failure { + fn from(e: library::Error) -> Self { + Self { + status: match e.kind { + library::ErrorKind::Allocation => ALLOCATION, + library::ErrorKind::ResourceLimit => LIMIT, + _ => PARSE, + }, + kind: parser_kind(e.kind), + offset: e.offset as u64, + } + } +} +fn failure(status: u32) -> Failure { + Failure { + status, + kind: 0, + offset: 0, + } +} +fn header(size: u32, abi: u32) -> Result<(), Failure> { + if size as usize != mem::size_of::() || abi != ABI { + Err(failure(ABI_MISMATCH)) + } else { + Ok(()) + } +} +fn tag_facts(tags: Option>) -> Result<(u32, u64, u64), Failure> { + let Some(tags) = tags else { + return Ok((0, 0, 0)); + }; + let range = tags.range(); + let mut count = 0u32; + for tag in tags { + tag?; + count = count.checked_add(1).ok_or_else(|| failure(LIMIT))?; + } + Ok((count, range.start as u64, range.len() as u64)) +} +fn snapshot(data: &[u8], limits: Limits) -> Result { + if limits.max_bytes == 0 + || limits.max_bytes > MAX_BYTES + || limits.max_entries == 0 + || limits.max_entries > MAX_ENTRIES + || !matches!(limits.kind, MTLB | RAW) + { + return Err(failure(INVALID)); + } + if data.is_empty() || data.len() as u64 > limits.max_bytes { + return Err(failure(LIMIT)); + } + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(data.len()) + .map_err(|_| failure(ALLOCATION))?; + bytes.extend_from_slice(data); + let mut info = Info { + size: mem::size_of::() as u32, + abi: ABI, + kind: limits.kind, + entry_count: 0, + original_bytes: bytes.len() as u64, + original_sha256: Sha256::digest(&bytes).into(), + platform: 0, + format_major: 0, + format_minor: 0, + library_kind: 0, + target_os: 0, + minimum_os_major: 0, + minimum_os_minor: 0, + }; + let mut entries = Vec::new(); + if limits.kind == MTLB { + let archive = Library::parse_bounded(&bytes, limits.max_entries as usize)?; + let header = tag_facts(archive.header_extensions)?; + let h = archive.header; + info.platform = h.platform.into(); + info.format_major = h.format.major.into(); + info.format_minor = h.format.minor.into(); + info.library_kind = h.kind.into(); + info.target_os = h.target_os.into(); + info.minimum_os_major = h.minimum_os.major.into(); + info.minimum_os_minor = h.minimum_os.minor.into(); + entries + .try_reserve_exact(archive.functions().len()) + .map_err(|_| failure(ALLOCATION))?; + for entry in archive.functions() { + if entry.name.len() > 4096 || entries.iter().any(|e: &OwnedEntry| e.name == entry.name) + { + return Err(failure(INVALID)); + } + let mut name = String::new(); + name.try_reserve_exact(entry.name.len()) + .map_err(|_| failure(ALLOCATION))?; + name.push_str(entry.name); + let range = entry.module_range(); + let function = tag_facts(Some(entry.tags))?; + let public = tag_facts(entry.public_metadata)?; + let private = tag_facts(entry.private_metadata)?; + entries.push(OwnedEntry { + name, + metadata: EntryMetadata { + size: mem::size_of::() as u32, + abi: ABI, + function_tags: function.0, + public_tags: public.0, + private_tags: private.0, + header_tags: header.0, + function_offset: function.1, + function_bytes: function.2, + public_offset: public.1, + public_bytes: public.2, + private_offset: private.1, + private_bytes: private.2, + header_offset: header.1, + header_bytes: header.2, + }, + info: Entry { + size: mem::size_of::() as u32, + abi: ABI, + kind: entry.kind.into(), + air_major: entry.air_version.major.into(), + air_minor: entry.air_version.minor.into(), + language_major: entry.language_version.major.into(), + language_minor: entry.language_version.minor.into(), + reserved: 0, + module_offset: range.start as u64, + module_bytes: range.len() as u64, + module_sha256: *entry.digest, + }, + }); + } + info.entry_count = entries.len() as u32; + } else { + Air::parse(&bytes)?; + } + Ok(Input { + bytes, + info, + entries, + }) +} +impl Input { + fn entry(&self, index: u32) -> Result<&OwnedEntry, Failure> { + if self.info.kind != MTLB { + return Err(failure(NOT_ARCHIVE)); + } + self.entries + .get(index as usize) + .ok_or_else(|| failure(INDEX)) + } + fn air(&self, index: u32) -> Result<&[u8], Failure> { + if self.info.kind == RAW { + if index != 0 { + return Err(failure(INDEX)); + } + return Ok(Air::parse(&self.bytes)?.bitcode); + } + let entry = self.entry(index)?; + // Use the canonical selected-entry hash/framing check, not a second parser. + let archive = Library::parse(&self.bytes)?; + let function = &archive.functions()[index as usize]; + debug_assert_eq!(function.name, entry.name); + Ok(function.air()?.bitcode) + } +} +fn finish(error: *mut Error, result: Result<(), Failure>) -> u32 { + let f = result.err().unwrap_or(failure(OK)); + if !error.is_null() { + // SAFETY: each exported caller guarantees complete writable error storage. + unsafe { + error.write(Error { + size: mem::size_of::() as u32, + abi: ABI, + status: f.status, + parser_kind: f.kind, + offset: f.offset, + }) + }; + } + f.status +} + +/// # Safety +/// Valid readable limits/input and writable empty owning output/error slots; +/// disjoint storage, exact indicated bounds, no concurrent mutation/destruction. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_open( + limits: *const Limits, + data: *const u8, + length: u64, + output: *mut *mut Input, + error: *mut Error, +) -> u32 { + finish( + error, + (|| { + if limits.is_null() || output.is_null() || data.is_null() { + return Err(failure(INVALID)); + } + // SAFETY: caller supplies complete limits/output records. + let limits = unsafe { *limits }; + header::(limits.size, limits.abi)?; + if length == 0 + || length > limits.max_bytes + || length > MAX_BYTES + || length > isize::MAX as u64 + { + return Err(failure(LIMIT)); + } + if !unsafe { *output }.is_null() { + return Err(failure(INVALID)); + } + // SAFETY: bounded caller-owned immutable input for this call only. + let input = snapshot( + unsafe { slice::from_raw_parts(data, length as usize) }, + limits, + )?; + // A process OOM/panic never unwinds through C: the isolated helper fails. + unsafe { output.write(Box::into_raw(Box::new(input))) }; + Ok(()) + })(), + ) +} + +/// # Safety +/// Live retained input and disjoint complete initialized output/error records; +/// no destruction may race this call or subsequent borrowed-view use. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_info( + input: *const Input, + out: *mut Info, + error: *mut Error, +) -> u32 { + finish( + error, + (|| { + if input.is_null() || out.is_null() { + return Err(failure(INVALID)); + } + // SAFETY: complete caller-owned output header, retained immutable input. + let (i, o) = unsafe { (&*input, &*out) }; + header::(o.size, o.abi)?; + unsafe { out.write(i.info) }; + Ok(()) + })(), + ) +} +/// # Safety +/// Same storage/lifetime contract as stela_metal_input_info. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_entry( + input: *const Input, + index: u32, + out: *mut Entry, + error: *mut Error, +) -> u32 { + finish( + error, + (|| { + if input.is_null() || out.is_null() { + return Err(failure(INVALID)); + } + let (i, o) = unsafe { (&*input, &*out) }; + header::(o.size, o.abi)?; + let value = i.entry(index)?.info; + unsafe { out.write(value) }; + Ok(()) + })(), + ) +} +/// # Safety +/// Same storage/lifetime contract as stela_metal_input_info. Facts are from the +/// canonical parser, not reflection qualification; raw AIR has no archive facts. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_entry_metadata( + input: *const Input, + index: u32, + out: *mut EntryMetadata, + error: *mut Error, +) -> u32 { + finish( + error, + (|| { + if input.is_null() || out.is_null() { + return Err(failure(INVALID)); + } + let (i, o) = unsafe { (&*input, &*out) }; + header::(o.size, o.abi)?; + let value = i.entry(index)?.metadata; + unsafe { out.write(value) }; + Ok(()) + })(), + ) +} +#[derive(Clone, Copy, PartialEq, Eq)] +enum ViewKind { + Name, + Air, + Original, +} +unsafe fn view( + input: *const Input, + index: u32, + out: *mut View, + error: *mut Error, + kind: ViewKind, +) -> u32 { + finish( + error, + (|| { + if input.is_null() || out.is_null() { + return Err(failure(INVALID)); + } + let (i, o) = unsafe { (&*input, &*out) }; + header::(o.size, o.abi)?; + let bytes = match kind { + ViewKind::Name => i.entry(index)?.name.as_bytes(), + ViewKind::Air => i.air(index)?, + ViewKind::Original => &i.bytes, + }; + unsafe { + out.write(View { + size: mem::size_of::() as u32, + abi: ABI, + bytes: bytes.as_ptr(), + length: bytes.len() as u64, + original_offset: if kind == ViewKind::Name { + u64::MAX + } else { + (bytes.as_ptr().addr() - i.bytes.as_ptr().addr()) as u64 + }, + }) + }; + Ok(()) + })(), + ) +} +/// # Safety +/// Same storage/lifetime contract as stela_metal_input_info; returned name is +/// borrowed UTF-8 (not NUL terminated), immutable until input destruction. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_name( + input: *const Input, + index: u32, + out: *mut View, + error: *mut Error, +) -> u32 { + unsafe { view(input, index, out, error, ViewKind::Name) } +} +/// # Safety +/// Same storage/lifetime contract as stela_metal_input_info. Raw byte framing is +/// not LLVM semantic verification; use the real shared inspector before objects. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_air( + input: *const Input, + index: u32, + out: *mut View, + error: *mut Error, +) -> u32 { + unsafe { view(input, index, out, error, ViewKind::Air) } +} +/// # Safety +/// Same storage/lifetime contract as stela_metal_input_info. The entire original +/// container/wrapper is borrowed without stripping unknown fields or framing. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_original( + input: *const Input, + out: *mut View, + error: *mut Error, +) -> u32 { + unsafe { view(input, 0, out, error, ViewKind::Original) } +} +/// # Safety +/// Slot is null or writable and uniquely owns its live handle. All borrowed +/// views/accesses have ended; no concurrent call, copied owner or foreign handle. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn stela_metal_input_destroy(slot: *mut *mut Input) { + if !slot.is_null() { + let input = unsafe { slot.replace(ptr::null_mut()) }; + if !input.is_null() { + unsafe { drop(Box::from_raw(input)) }; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-drivers/src/gpu/metal/input/tests.rs b/crates/stela-drivers/src/gpu/metal/input/tests.rs new file mode 100644 index 0000000000..1c681744ff --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/tests.rs @@ -0,0 +1,427 @@ +use super::*; +fn limits(kind: u32) -> Limits { + Limits { + size: mem::size_of::() as u32, + abi: ABI, + kind, + max_entries: 8, + max_bytes: 4096, + } +} +fn tag(out: &mut Vec, key: &[u8; 4], value: &[u8]) { + out.extend_from_slice(key); + out.extend_from_slice(&(value.len() as u16).to_le_bytes()); + out.extend_from_slice(value); +} +// Original synthetic MTLB framing; its bytes are deliberately not LLVM IR. +fn archive(duplicate: bool) -> Vec { + archive_metadata(duplicate, None, None, None, None) +} +fn archive_metadata( + duplicate: bool, + function: Option<&[u8; 4]>, + public: Option<&[u8; 4]>, + private: Option<&[u8; 4]>, + header: Option<&[u8; 4]>, +) -> Vec { + let module = b"BC\xc0\xde0123"; + let mut records = Vec::new(); + for _ in 0..if duplicate { 2 } else { 1 } { + let mut r = vec![0; 4]; + for (key, value) in [ + (b"NAME", b"kernel\0".as_slice()), + (b"TYPE", &[2]), + (b"HASH", Sha256::digest(module).as_slice()), + (b"MDSZ", &8u64.to_le_bytes()), + (b"OFFT", &[0; 24]), + (b"VERS", &[2, 0, 9, 0, 4, 0, 1, 0]), + ] { + tag(&mut r, key, value); + } + if let Some(key) = function { + tag(&mut r, key, b"fact"); + } + r.extend_from_slice(b"ENDT"); + let size = r.len() as u32; + r[..4].copy_from_slice(&size.to_le_bytes()); + records.extend_from_slice(&r); + } + let mut data = vec![0; 88]; + data[..4].copy_from_slice(b"MTLB"); + data[6] = 2; + data[8] = 9; + data[24..32].copy_from_slice(&88u64.to_le_bytes()); + data[32..40].copy_from_slice(&(records.len() as u64).to_le_bytes()); + data.extend_from_slice(&(if duplicate { 2u32 } else { 1u32 }).to_le_bytes()); + data.extend_from_slice(&records); + if let Some(key) = header { + tag(&mut data, key, b"identity"); + data.extend_from_slice(b"ENDT"); + } + for (field, key) in [(40, public), (56, private)] { + let start = data.len() as u64; + data[field..field + 8].copy_from_slice(&start.to_le_bytes()); + if let Some(key) = key { + let mut group = vec![0; 4]; + if key != b"NONE" { + tag(&mut group, key, b"fact"); + } + group.extend_from_slice(b"ENDT"); + let size = group.len() as u32; + group[..4].copy_from_slice(&size.to_le_bytes()); + data[field + 8..field + 16].copy_from_slice(&(group.len() as u64).to_le_bytes()); + data.extend_from_slice(&group); + } + } + let code = data.len() as u64; + data[72..80].copy_from_slice(&code.to_le_bytes()); + data[80..88].copy_from_slice(&8u64.to_le_bytes()); + data.extend_from_slice(module); + let size = data.len() as u64; + data[16..24].copy_from_slice(&size.to_le_bytes()); + data +} +fn empty_view() -> View { + View { + size: mem::size_of::() as u32, + abi: ABI, + bytes: ptr::null(), + length: 0, + original_offset: 0, + } +} +#[test] +fn owned_snapshot_and_local_c_abi_keep_bytes_after_source_mutation() { + let mut source = b"BC\xc0\xde0123".to_vec(); + let mut input = ptr::null_mut(); + let mut view = empty_view(); + // SAFETY: exact readable input and disjoint initialized owning outputs. + unsafe { + assert_eq!( + stela_metal_input_open( + &limits(RAW), + source.as_ptr(), + source.len() as u64, + &mut input, + ptr::null_mut() + ), + OK + ); + source.fill(0); + assert_eq!( + stela_metal_input_air(input, 0, &mut view, ptr::null_mut()), + OK + ); + assert_eq!( + slice::from_raw_parts(view.bytes, view.length as usize), + b"BC\xc0\xde0123" + ); + assert_eq!( + stela_metal_input_name(input, 0, &mut view, ptr::null_mut()), + NOT_ARCHIVE + ); + assert_eq!( + slice::from_raw_parts(view.bytes, view.length as usize), + b"BC\xc0\xde0123" + ); + stela_metal_input_destroy(&mut input); + assert!(input.is_null()); + stela_metal_input_destroy(&mut input); + stela_metal_input_destroy(ptr::null_mut()); + } +} +#[test] +fn archive_entries_use_original_ranges_and_selected_digest() { + let bytes = archive(false); + let input = snapshot(&bytes, limits(MTLB)).unwrap(); + assert_eq!(input.entries[0].name, "kernel"); + assert_eq!(input.entries[0].info.kind, 2); + assert_eq!(input.entries[0].info.language_minor, 1); + assert_eq!(input.air(0).unwrap(), b"BC\xc0\xde0123"); + let start = input.entries[0].info.module_offset as usize; + assert_eq!(&input.bytes[start..], input.air(0).unwrap()); + let mut view = empty_view(); + // SAFETY: live immutable owner and disjoint complete output record. + unsafe { + assert_eq!( + stela_metal_input_original(&input, &mut view, ptr::null_mut()), + OK + ); + assert_eq!(view.original_offset, 0); + assert_eq!( + slice::from_raw_parts(view.bytes, view.length as usize), + bytes + ); + } + let mut corrupt = bytes.clone(); + *corrupt.last_mut().unwrap() ^= 1; + let input = snapshot(&corrupt, limits(MTLB)).unwrap(); + assert_eq!(input.air(0).unwrap_err().kind, 14); + assert_eq!( + snapshot(&archive(true), limits(MTLB)).err().unwrap().status, + INVALID + ); +} +#[test] +fn limits_abi_and_failures_never_publish_handles_or_overwrite_views() { + let data = b"BC\xc0\xde0123"; + let mut input = ptr::null_mut(); + let mut bad = limits(RAW); + bad.abi = ABI + 1; + let mut error = Error { + size: 0, + abi: 0, + status: 0, + parser_kind: 0, + offset: 0, + }; + // SAFETY: complete local initialized slots and bounded source. + unsafe { + assert_eq!( + stela_metal_input_open(&bad, data.as_ptr(), 8, &mut input, &mut error), + ABI_MISMATCH + ); + assert!(input.is_null()); + assert_eq!(error.status, ABI_MISMATCH); + bad = limits(RAW); + bad.max_bytes = 7; + assert_eq!( + stela_metal_input_open(&bad, data.as_ptr(), 8, &mut input, &mut error), + LIMIT + ); + assert!(input.is_null()); + bad = limits(RAW); + assert_eq!( + stela_metal_input_open(&bad, data.as_ptr(), u64::MAX, &mut input, &mut error), + LIMIT + ); + assert_eq!( + stela_metal_input_open(&bad, ptr::null(), 8, &mut input, &mut error), + INVALID + ); + assert_eq!( + stela_metal_input_open(&bad, data.as_ptr(), 8, &mut input, &mut error), + OK + ); + let original = input; + assert_eq!( + stela_metal_input_open(&bad, data.as_ptr(), 8, &mut input, &mut error), + INVALID + ); + assert_eq!(input, original); + let mut view = empty_view(); + view.abi = 99; + view.length = 123; + assert_eq!( + stela_metal_input_air(input, 0, &mut view, &mut error), + ABI_MISMATCH + ); + assert_eq!(view.length, 123); + view.abi = ABI; + assert_eq!( + stela_metal_input_air(input, 1, &mut view, &mut error), + INDEX + ); + assert_eq!(view.length, 123); + stela_metal_input_destroy(&mut input); + } + for end in 0..archive(false).len() { + assert!(snapshot(&archive(false)[..end], limits(MTLB)).is_err()); + } +} + +fn empty_metadata() -> EntryMetadata { + EntryMetadata { + size: mem::size_of::() as u32, + abi: ABI, + function_tags: 0, + public_tags: 0, + private_tags: 0, + header_tags: 0, + function_offset: 0, + function_bytes: 0, + public_offset: 0, + public_bytes: 0, + private_offset: 0, + private_bytes: 0, + header_offset: 0, + header_bytes: 0, + } +} +#[test] +fn metadata_facts_keep_unknown_tags_original_ranges_and_absence() { + let bytes = archive_metadata( + false, + Some(b"FUTR"), + Some(b"CNST"), + Some(b"DEBI"), + Some(b"UUID"), + ); + let parsed = Library::parse(&bytes).unwrap(); + let input = snapshot(&bytes, limits(MTLB)).unwrap(); + let mut facts = empty_metadata(); + unsafe { + assert_eq!( + stela_metal_input_entry_metadata(&input, 0, &mut facts, ptr::null_mut()), + OK + ); + } + assert_eq!( + ( + facts.function_tags, + facts.public_tags, + facts.private_tags, + facts.header_tags + ), + (7, 1, 1, 1) + ); + for (offset, len, tags) in [ + ( + facts.function_offset, + facts.function_bytes, + Some(parsed.functions()[0].tags), + ), + ( + facts.public_offset, + facts.public_bytes, + parsed.functions()[0].public_metadata, + ), + ( + facts.private_offset, + facts.private_bytes, + parsed.functions()[0].private_metadata, + ), + ( + facts.header_offset, + facts.header_bytes, + parsed.header_extensions, + ), + ] { + let range = tags.unwrap().range(); + assert_eq!((offset as usize, len as usize), (range.start, range.len())); + assert_eq!(&input.bytes[range.end - 4..range.end], b"ENDT"); + } + let prior = facts; + unsafe { + assert_eq!( + stela_metal_input_entry_metadata(&input, 1, &mut facts, ptr::null_mut()), + INDEX + ); + assert_eq!(facts, prior); + facts.abi = 99; + assert_eq!( + stela_metal_input_entry_metadata(&input, 0, &mut facts, ptr::null_mut()), + ABI_MISMATCH + ); + assert_eq!(facts.function_tags, 7); + facts.abi = ABI; + let raw = snapshot(b"BC\xc0\xde0123", limits(RAW)).unwrap(); + assert_eq!( + stela_metal_input_entry_metadata(&raw, 0, &mut facts, ptr::null_mut()), + NOT_ARCHIVE + ); + assert_eq!(facts, prior); + } + let absent = snapshot(&archive(false), limits(MTLB)).unwrap().entries[0].metadata; + assert_eq!( + ( + absent.function_tags, + absent.public_bytes, + absent.private_bytes, + absent.header_bytes + ), + (6, 0, 0, 0) + ); + let empty = snapshot( + &archive_metadata(false, None, Some(b"NONE"), Some(b"NONE"), None), + limits(MTLB), + ) + .unwrap() + .entries[0] + .metadata; + assert_eq!( + ( + empty.public_tags, + empty.private_tags, + empty.public_bytes, + empty.private_bytes + ), + (0, 0, 4, 4) + ); + assert!(empty.public_offset > 0 && empty.private_offset > empty.public_offset); +} + +// Deny/count large allocations in THIS test thread only; production allocation +// remains normal hosted Rust. No allocation may reach even this denial point +// for an otherwise framed large-count table exceeding the caller's entry cap. +struct TestAllocator; +std::thread_local! { + static DENY_LARGE: core::cell::Cell = const { core::cell::Cell::new(false) }; + static DENIED: core::cell::Cell = const { core::cell::Cell::new(0) }; +} +#[global_allocator] +static ALLOCATOR: TestAllocator = TestAllocator; +unsafe impl std::alloc::GlobalAlloc for TestAllocator { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + if layout.size() >= 1024 * 1024 && DENY_LARGE.try_with(|v| v.get()).unwrap_or(false) { + let _ = DENIED.try_with(|v| v.set(v.get() + 1)); + return ptr::null_mut(); + } + unsafe { std::alloc::System.alloc(layout) } + } + unsafe fn dealloc(&self, pointer: *mut u8, layout: std::alloc::Layout) { + unsafe { + std::alloc::System.dealloc(pointer, layout); + } + } + unsafe fn realloc(&self, pointer: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + if size >= 1024 * 1024 && DENY_LARGE.try_with(|v| v.get()).unwrap_or(false) { + let _ = DENIED.try_with(|v| v.set(v.get() + 1)); + return ptr::null_mut(); + } + unsafe { std::alloc::System.realloc(pointer, layout, size) } + } +} +#[test] +fn function_budget_precedes_table_allocation_and_keeps_c_limit_status() { + // A million minimal framed slots would request >100MiB of Function storage. + // They need not parse: resource refusal must precede both reserve and tags. + let count = 1_000_000usize; + let mut bytes = vec![0; 88 + 4 + count * 8]; + bytes[..4].copy_from_slice(b"MTLB"); + bytes[6] = 2; + let size = bytes.len() as u64; + bytes[16..24].copy_from_slice(&size.to_le_bytes()); + bytes[24..32].copy_from_slice(&88u64.to_le_bytes()); + bytes[32..40].copy_from_slice(&((count * 8) as u64).to_le_bytes()); + for field in [40, 56, 72] { + bytes[field..field + 8].copy_from_slice(&size.to_le_bytes()); + } + bytes[88..92].copy_from_slice(&(count as u32).to_le_bytes()); + DENIED.set(0); + DENY_LARGE.set(true); + let result = Library::parse_bounded(&bytes, 256); + DENY_LARGE.set(false); + assert_eq!( + DENIED.get(), + 0, + "function table reserve was attempted before the limit" + ); + let error = result.unwrap_err(); + assert_eq!( + error, + library::Error { + offset: 88, + kind: library::ErrorKind::ResourceLimit + } + ); + let failure = Failure::from(error); + assert_eq!( + (failure.status, failure.kind, failure.offset), + (LIMIT, 17, 88) + ); + let mut low = limits(MTLB); + low.max_entries = 1; + assert_eq!(snapshot(&archive(true), low).err().unwrap().status, LIMIT); + assert!(Library::parse(&archive(false)).is_ok()); +} diff --git a/crates/stela-drivers/src/gpu/metal/input/tests/abi.c b/crates/stela-drivers/src/gpu/metal/input/tests/abi.c new file mode 100644 index 0000000000..78c67880ff --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/tests/abi.c @@ -0,0 +1,47 @@ +/* SPDX-License-Identifier: MIT */ +#ifdef NDEBUG +#error "This ownership test requires active assertions" +#endif +#include "../input.h" +#include +#include +#include +_Static_assert(sizeof(struct stela_metal_input_limits) == 24, "limits ABI"); +_Static_assert(sizeof(struct stela_metal_input_error) == 24, "error ABI"); +_Static_assert(sizeof(struct stela_metal_input_info) == 88, "input info ABI"); +_Static_assert(sizeof(struct stela_metal_input_entry) == 80, "entry ABI"); +_Static_assert(sizeof(struct stela_metal_input_entry_metadata) == 88, "metadata facts ABI"); +_Static_assert(offsetof(struct stela_metal_input_entry_metadata,function_offset) == 24, "metadata range ABI"); +_Static_assert(sizeof(struct stela_metal_input_view) == 32, "view ABI"); +_Static_assert(offsetof(struct stela_metal_input_view,original_offset) == 24, "view offset ABI"); +int main(void) +{ + uint8_t original[] = {'B','C',0xc0,0xde,1,2,3,4}; + struct stela_metal_input_limits limits = { + .size=sizeof(limits),.abi=1,.kind=STELA_METAL_INPUT_RAW_AIR,.max_entries=4,.max_bytes=64, + }; + struct stela_metal_input *input = NULL; + struct stela_metal_input_error error = {0}; + assert(stela_metal_input_open(&limits,original,sizeof(original),&input,&error)==0 && input); + memset(original,0,sizeof(original)); + struct stela_metal_input_info info = {.size=sizeof(info),.abi=1}; + assert(stela_metal_input_info(input,&info,&error)==0 && info.kind==STELA_METAL_INPUT_RAW_AIR && info.original_bytes==8); + struct stela_metal_input_view view = {.size=sizeof(view),.abi=1}; + assert(stela_metal_input_air(input,0,&view,&error)==0 && view.length==8 && view.original_offset==0); + const uint8_t expected[] = {'B','C',0xc0,0xde,1,2,3,4}; + assert(!memcmp(view.bytes,expected,8)); + assert(stela_metal_input_original(input,&view,&error)==0 && view.length==8 && view.original_offset==0); + assert(!memcmp(view.bytes,expected,8)); + assert(stela_metal_input_name(input,0,&view,&error)==STELA_METAL_INPUT_NOT_ARCHIVE && view.length==8); + struct stela_metal_input_entry_metadata facts = {.size=sizeof(facts),.abi=1,.function_tags=99}; + assert(stela_metal_input_entry_metadata(input,0,&facts,&error)==STELA_METAL_INPUT_NOT_ARCHIVE && facts.function_tags==99); + facts.abi=2; + assert(stela_metal_input_entry_metadata(input,0,&facts,&error)==STELA_METAL_INPUT_ABI_MISMATCH && facts.function_tags==99); + view.abi=2; + assert(stela_metal_input_air(input,0,&view,&error)==STELA_METAL_INPUT_ABI_MISMATCH && view.length==8); + stela_metal_input_destroy(&input); assert(!input); + stela_metal_input_destroy(&input); stela_metal_input_destroy(NULL); + limits.abi=2; + assert(stela_metal_input_open(&limits,original,sizeof(original),&input,&error)==STELA_METAL_INPUT_ABI_MISMATCH && !input); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/metal/input/tests/inspect.c b/crates/stela-drivers/src/gpu/metal/input/tests/inspect.c new file mode 100644 index 0000000000..735e94aa6a --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/input/tests/inspect.c @@ -0,0 +1,76 @@ +/* SPDX-License-Identifier: MIT */ +/* Actual local C -> owned Rust input -> shared LLVM metadata integration. + * No Objective-C, device, framework compiler, GPU or transport is invoked. */ +#ifdef NDEBUG +#error "This ownership test requires active assertions" +#endif +#include "../input.h" +#include "../../../common/mesa/src/stela/air_metadata.h" +#include +#include +#include +#include +struct inspection { + unsigned entries; + bool expect_complete; +}; +static bool visit(const struct stela_air_inspection *module, + const struct stela_air_entry *entry, void *data) +{ + struct inspection *state = data; + assert(module->target && module->target_bytes && entry->name && entry->name_bytes); + assert(entry->reflection_complete == state->expect_complete); + assert(entry->argument_count <= AIR_MAX_ARGUMENTS); + printf("entry=%u air=2.%u msl=%u.%u complete=%u arguments=%u\n", state->entries, + module->air_minor,module->language_major,module->language_minor, + entry->reflection_complete,entry->argument_count); + for (unsigned i = 0; i < entry->argument_count; i++) { + const struct stela_air_argument_info *arg = &entry->arguments[i]; + if (arg->kind != 1) continue; + assert(arg->buffer.argument < entry->argument_count); + if (state->expect_complete) + assert(arg->name && arg->name_bytes && arg->plain_buffer_type && + arg->type_components && arg->type_components <= 4 && + arg->primitive >= STELA_AIR_CHAR && arg->primitive <= STELA_AIR_FLOAT); + printf("argument=%u binding=%u space=%u access=%u size=%u align=%u primitive=%u lanes=%u used=%u\n", + arg->buffer.argument,arg->buffer.index,arg->buffer.address_space,arg->buffer.access, + arg->buffer.type_size,arg->buffer.type_alignment,arg->primitive,arg->type_components,arg->used); + } + state->entries++; + return true; +} +int main(int argc, char **argv) +{ + assert(argc == 3 && (!strcmp(argv[2],"complete") || !strcmp(argv[2],"incomplete"))); + FILE *file = fopen(argv[1],"rb"); + assert(file && !fseek(file,0,SEEK_END)); + long length = ftell(file); + assert(length >= 4 && length <= 64*1024*1024 && !fseek(file,0,SEEK_SET)); + uint8_t *bytes = malloc((size_t)length); + assert(bytes && fread(bytes,1,(size_t)length,file) == (size_t)length && !fclose(file)); + struct stela_metal_input_limits limits = { + .size=sizeof(limits),.abi=1,.kind=STELA_METAL_INPUT_RAW_AIR,.max_entries=256,.max_bytes=64*1024*1024, + }; + struct stela_metal_input *input = NULL; + struct stela_metal_input_error error = {0}; + assert(!stela_metal_input_open(&limits,bytes,(uint64_t)length,&input,&error)); + memset(bytes,0,(size_t)length); free(bytes); /* Retained view must remain original. */ + struct stela_metal_input_info info = {.size=sizeof(info),.abi=1}; + struct stela_metal_input_view view = {.size=sizeof(view),.abi=1}; + assert(!stela_metal_input_info(input,&info,&error)); + assert(!stela_metal_input_original(input,&view,&error) && view.original_offset == 0 && + view.length == (uint64_t)length); + assert(!stela_metal_input_air(input,0,&view,&error) && view.length >= 4); + printf("original_bytes=%llu original_sha256=",(unsigned long long)info.original_bytes); + for (unsigned i = 0; i < 32; i++) printf("%02x",info.original_sha256[i]); + puts(""); + struct inspection state = {.expect_complete=!strcmp(argv[2],"complete")}; + struct stela_air_error metadata_error; + if (!stela_air_inspect(view.bytes,(size_t)view.length,256,visit,&state,&metadata_error)) { + fprintf(stderr,"AIR inspection refused (%u): %s\n",metadata_error.kind,metadata_error.detail); + abort(); + } + assert(state.entries); + stela_metal_input_destroy(&input); assert(!input); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/metal/library.rs b/crates/stela-drivers/src/gpu/metal/library.rs index d937e38148..cc3ce945f6 100644 --- a/crates/stela-drivers/src/gpu/metal/library.rs +++ b/crates/stela-drivers/src/gpu/metal/library.rs @@ -30,6 +30,7 @@ pub enum ErrorKind { Hash, Bitcode, Allocation, + ResourceLimit, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -153,6 +154,11 @@ impl<'a> Iterator for Tags<'a> { } impl<'a> Tags<'a> { + /// Remaining original tag-stream range, including its ENDT terminator. + pub fn range(&self) -> Range { + self.offset..self.offset + self.bytes.len() + } + fn checked(data: &'a [u8], offset: usize) -> Result { if !data.ends_with(b"ENDT") { return Err(error(offset + data.len(), ErrorKind::Terminator)); @@ -196,6 +202,11 @@ pub struct Library<'a> { impl<'a> Library<'a> { pub fn parse(data: &'a [u8]) -> Result { + Self::parse_bounded(data, usize::MAX) + } + + /// Apply the caller's entry budget before allocating the function table. + pub fn parse_bounded(data: &'a [u8], max_functions: usize) -> Result { bytes(data, 0, HEADER_BYTES)?; if &data[..4] != b"MTLB" { return Err(error(0, ErrorKind::Magic)); @@ -238,6 +249,9 @@ impl<'a> Library<'a> { if count > functions_range.len().saturating_sub(4) / 8 { return Err(error(functions_range.start, ErrorKind::FunctionCount)); } + if count > max_functions { + return Err(error(functions_range.start, ErrorKind::ResourceLimit)); + } let mut functions = Vec::new(); functions .try_reserve_exact(count) @@ -377,6 +391,11 @@ impl<'a> Function<'a> { }) } + /// Original wrapped/raw module extent; no payload copy or semantic rewrite. + pub fn module_range(&self) -> Range { + self.module_offset..self.module_offset + self.module.len() + } + /// Verify the archive's digest before returning the LLVM reader's input. pub fn air(&self) -> Result> { if Sha256::digest(self.module).as_slice() != self.digest { @@ -452,4 +471,5 @@ impl<'a> Air<'a> { } #[cfg(test)] +#[path = "library/tests.rs"] mod tests; diff --git a/crates/stela-drivers/src/gpu/metal/macos/Makefile b/crates/stela-drivers/src/gpu/metal/macos/Makefile new file mode 100644 index 0000000000..f943125f62 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/macos/Makefile @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: MIT +# User-space Metal library objects. No device/plugin registration or kernel code. +SOURCE := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))) +ARCH ?= arm64 +BUILD ?= $(abspath $(SOURCE)/../../../../../..)/.stela/gpu/build/metal/$(ARCH) +SDKROOT ?= $(shell xcrun --sdk macosx --show-sdk-path) +CC := $(shell xcrun --sdk macosx --find clang) + +ifeq ($(filter $(ARCH),arm64 arm64e x86_64),) +$(error unsupported Metal object architecture $(ARCH)) +endif +COMMON := -target $(ARCH)-apple-macos26.0 -isysroot $(SDKROOT) -O2 \ + -fobjc-arc -fblocks -Wall -Wextra -Werror + +.PHONY: all +all: $(BUILD)/libstela-metal-library.dylib + +$(BUILD): + mkdir -p "$@" + +$(BUILD)/library.o: $(SOURCE)/library.m | $(BUILD) + "$(CC)" $(COMMON) -MD -MP -c "$<" -o "$@" + +$(BUILD)/libstela-metal-library.dylib: $(BUILD)/library.o + "$(CC)" $(COMMON) -dynamiclib "$<" -framework Foundation -framework Metal \ + -Wl,-install_name,@rpath/libstela-metal-library.dylib -o "$@" + +-include $(BUILD)/library.d diff --git a/crates/stela-drivers/src/gpu/metal/macos/library.m b/crates/stela-drivers/src/gpu/metal/macos/library.m new file mode 100644 index 0000000000..d44a3cc0d9 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/macos/library.m @@ -0,0 +1,463 @@ +/* SPDX-License-Identifier: MIT */ +#import "library_internal.h" +#import +#import +#include + +#define INPUT_LIMIT (64u * 1024u * 1024u) +#define ENTRY_LIMIT 256u + +static void LibraryError(NSError **error, MTLLibraryError code, NSString *detail) +{ + if (error) + *error = [NSError errorWithDomain:MTLLibraryErrorDomain code:(NSInteger)code + userInfo:@{NSLocalizedDescriptionKey:detail}]; +} +static NSData *Digest(NSData *bytes, NSRange range) +{ + uint8_t result[32]; + CC_SHA256((const uint8_t *)bytes.bytes + range.location, (CC_LONG)range.length, result); + return [NSData dataWithBytes:result length:sizeof(result)]; +} +static BOOL Span(uint64_t offset, uint64_t length, NSUInteger limit) +{ + return length && offset <= limit && length <= limit - offset; +} +static BOOL Nonzero(const uint8_t *bytes, size_t length) +{ + uint8_t result = 0; + for (size_t i = 0; i < length; i++) result |= bytes[i]; + return result != 0; +} +static BOOL SameDigest(NSData *actual, const uint8_t expected[32]) +{ + return [actual isEqualToData:[NSData dataWithBytes:expected length:32]]; +} +static NSData *RangeDigest(NSData *bytes, NSRange range, NSMutableDictionary *cache) +{ + NSString *key = [NSString stringWithFormat:@"%llu:%llu", + (unsigned long long)range.location, (unsigned long long)range.length]; + NSData *digest = cache[key]; + if (!digest) { digest = Digest(bytes,range); cache[key] = digest; } + return digest; +} + +/* Genuine public reflection implementations. No Apple private reflection + * containers, ivars, initializers or C++ data are used. Each object owns its + * strings/children and contains only already validated AIR reflection facts. */ +static MTLDataType PrimitiveDataType(enum stela_air_primitive primitive, unsigned components) +{ + static const MTLDataType types[][4] = { + {MTLDataTypeChar,MTLDataTypeChar2,MTLDataTypeChar3,MTLDataTypeChar4}, + {MTLDataTypeUChar,MTLDataTypeUChar2,MTLDataTypeUChar3,MTLDataTypeUChar4}, + {MTLDataTypeShort,MTLDataTypeShort2,MTLDataTypeShort3,MTLDataTypeShort4}, + {MTLDataTypeUShort,MTLDataTypeUShort2,MTLDataTypeUShort3,MTLDataTypeUShort4}, + {MTLDataTypeInt,MTLDataTypeInt2,MTLDataTypeInt3,MTLDataTypeInt4}, + {MTLDataTypeUInt,MTLDataTypeUInt2,MTLDataTypeUInt3,MTLDataTypeUInt4}, + {MTLDataTypeLong,MTLDataTypeLong2,MTLDataTypeLong3,MTLDataTypeLong4}, + {MTLDataTypeULong,MTLDataTypeULong2,MTLDataTypeULong3,MTLDataTypeULong4}, + {MTLDataTypeFloat,MTLDataTypeFloat2,MTLDataTypeFloat3,MTLDataTypeFloat4}, + }; + if (primitive < STELA_AIR_CHAR || primitive > STELA_AIR_FLOAT || !components || components > 4) + return MTLDataTypeNone; + return types[primitive-STELA_AIR_CHAR][components-1]; +} +static MTLBindingAccess BindingAccess(enum stela_air_buffer_access access) +{ + switch (access) { + case STELA_AIR_READ: return MTLBindingAccessReadOnly; + case STELA_AIR_WRITE: return MTLBindingAccessWriteOnly; + case STELA_AIR_READ_WRITE: return MTLBindingAccessReadWrite; + } + __builtin_unreachable(); /* Validated before construction. */ +} +@interface STELAMetalPointerType : MTLPointerType +- (instancetype)initWithArgument:(const struct stela_air_argument_info *)argument; +@end +@implementation STELAMetalPointerType { + MTLDataType _element; + MTLBindingAccess _access; + NSUInteger _alignment, _dataSize; +} +- (instancetype)initWithArgument:(const struct stela_air_argument_info *)arg +{ + self = [super init]; + if (self) { + _element = PrimitiveDataType(arg->primitive,arg->type_components); + _access = BindingAccess(arg->buffer.access); + _alignment = arg->buffer.type_alignment; _dataSize = arg->buffer.type_size; + } + return self; +} +- (MTLDataType)dataType { return MTLDataTypePointer; } +- (MTLDataType)elementType { return _element; } +- (MTLBindingAccess)access { return _access; } +- (NSUInteger)alignment { return _alignment; } +- (NSUInteger)dataSize { return _dataSize; } +- (BOOL)elementIsArgumentBuffer { return NO; } +- (MTLStructType *)elementStructType { return nil; } /* Validated primitive. */ +- (MTLArrayType *)elementArrayType { return nil; } +@end + +@interface STELAMetalBinding : NSObject +@property (readonly) NSString *name; +@property (readonly) MTLBindingType type; +@property (readonly) MTLBindingAccess access; +@property (readonly) NSUInteger index; +@property (readonly, getter=isUsed) BOOL used; +@property (readonly, getter=isArgument) BOOL argument; +@property (readonly) NSUInteger alignment, dataSize; +@property (readonly) MTLDataType dataType; +- (instancetype)initWithArgument:(const struct stela_air_argument_info *)argument; +@end +@implementation STELAMetalBinding +- (instancetype)initWithArgument:(const struct stela_air_argument_info *)arg +{ + self = [super init]; + if (self) { + _name = [[NSString alloc] initWithBytes:arg->name length:arg->name_bytes encoding:NSUTF8StringEncoding]; + _type = arg->buffer.address_space == 1 ? MTLBindingTypeBuffer : MTLBindingTypeThreadgroupMemory; + _access = BindingAccess(arg->buffer.access); _index = arg->buffer.index; + _used = arg->used; _argument = YES; + _alignment = arg->buffer.type_alignment; _dataSize = arg->buffer.type_size; + _dataType = PrimitiveDataType(arg->primitive,arg->type_components); + } + return self; +} +@end +@interface STELAMetalBufferBinding : STELAMetalBinding +@end +@implementation STELAMetalBufferBinding { + MTLPointerType *_pointer; +} +- (instancetype)initWithArgument:(const struct stela_air_argument_info *)arg +{ + self = [super initWithArgument:arg]; + if (self) _pointer = [[STELAMetalPointerType alloc] initWithArgument:arg]; + return self; +} +- (NSUInteger)bufferAlignment { return self.alignment; } +- (NSUInteger)bufferDataSize { return self.dataSize; } +- (MTLDataType)bufferDataType { return self.dataType; } +- (MTLStructType *)bufferStructType { return nil; } +- (MTLPointerType *)bufferPointerType { return _pointer; } +@end +@interface STELAMetalThreadgroupBinding : STELAMetalBinding +@end +@implementation STELAMetalThreadgroupBinding +- (NSUInteger)threadgroupMemoryAlignment { return self.alignment; } +- (NSUInteger)threadgroupMemoryDataSize { return self.dataSize; } +@end +@interface STELAMetalReflection : MTLFunctionReflection +- (instancetype)initWithBindings:(NSArray> *)bindings; +@end +@implementation STELAMetalReflection { + NSArray> *_bindings; +} +- (instancetype)initWithBindings:(NSArray> *)bindings +{ + self = [super init]; + if (self) _bindings = [bindings copy]; + return self; +} +- (NSArray> *)bindings { return _bindings; } +- (NSString *)userAnnotation { return nil; } /* Admission proves absence. */ +@end + +static MTLFunctionReflection *CreateReflection(const struct stela_metal_function_record *record) +{ + if (record->reserved_arguments || record->argument_count > AIR_MAX_ARGUMENTS || + (record->argument_count && !record->arguments)) return nil; + BOOL ordinals[AIR_MAX_ARGUMENTS] = {0}; + BOOL indices[2][AIR_MAX_ARGUMENTS] = {{0}}; + NSMutableArray> *bindings = [NSMutableArray array]; + for (uint32_t i = 0; i < record->argument_count; i++) { + const struct stela_air_argument_info *arg = &record->arguments[i]; + if (arg->buffer.argument >= record->argument_count || ordinals[arg->buffer.argument]) return nil; + ordinals[arg->buffer.argument] = YES; + if (arg->kind == 2) { /* Invocation builtins are not bound resources. */ + if (arg->components != 1 && arg->components != 3) return nil; + continue; + } + if (arg->kind != 1 || !arg->plain_buffer_type || + PrimitiveDataType(arg->primitive,arg->type_components) == MTLDataTypeNone || + !arg->name || !arg->name_bytes || arg->name_bytes > 4096 || + memchr(arg->name,0,arg->name_bytes) || + (arg->buffer.address_space != 1 && arg->buffer.address_space != 3) || + arg->buffer.index >= AIR_MAX_ARGUMENTS || arg->buffer.access < STELA_AIR_READ || + arg->buffer.access > STELA_AIR_READ_WRITE) return nil; + unsigned space = arg->buffer.address_space == 1 ? 0 : 1; + if (indices[space][arg->buffer.index]) return nil; + indices[space][arg->buffer.index] = YES; + unsigned scalar = arg->primitive <= STELA_AIR_UCHAR ? 1 : arg->primitive <= STELA_AIR_USHORT ? 2 : + arg->primitive == STELA_AIR_LONG || arg->primitive == STELA_AIR_ULONG ? 8 : 4; + unsigned extent = scalar * (arg->type_components == 3 ? 4 : arg->type_components); + if (arg->buffer.type_size != extent || arg->buffer.type_alignment != extent || + ![[NSString alloc] initWithBytes:arg->name length:arg->name_bytes encoding:NSUTF8StringEncoding]) return nil; + STELAMetalBinding *binding = space == 0 ? [[STELAMetalBufferBinding alloc] initWithArgument:arg] : + [[STELAMetalThreadgroupBinding alloc] initWithArgument:arg]; + [bindings addObject:binding]; + } + return [[STELAMetalReflection alloc] initWithBindings:bindings]; +} + +@interface STELAMetalFunctionSnapshot () +- (instancetype)initWithInput:(NSData *)input record:(const struct stela_metal_function_record *)record + manifest:(const struct stela_metal_library_manifest *)manifest target:(NSString *)target + reflection:(MTLFunctionReflection *)reflection; +@end +@implementation STELAMetalFunctionSnapshot +- (instancetype)initWithInput:(NSData *)input record:(const struct stela_metal_function_record *)r + manifest:(const struct stela_metal_library_manifest *)m target:(NSString *)target + reflection:(MTLFunctionReflection *)reflection +{ + self = [super init]; + if (self) { + _originalInput = input; + _rawAIRRange = NSMakeRange((NSUInteger)r->air_offset,(NSUInteger)r->air_bytes); + _entryName = [[NSString alloc] initWithBytes:r->name length:(NSUInteger)r->name_bytes encoding:NSUTF8StringEncoding]; + _targetTriple = [target copy]; _reflection = reflection; + _originalSHA256 = [NSData dataWithBytes:m->input.original_sha256 length:32]; + _moduleSHA256 = [NSData dataWithBytes:r->entry.module_sha256 length:32]; + _rawAIRSHA256 = [NSData dataWithBytes:r->air_sha256 length:32]; + _sourceSHA256 = [NSData dataWithBytes:m->source_sha256 length:32]; + _compilerBuildIdentity = [NSData dataWithBytes:&m->build length:sizeof(m->build)]; + _compilerProfile = m->compiler_profile; _requestLanguage = m->request_language; + _requestFastMath = m->request_fast_math != 0; + _airMajor = r->entry.air_major; _airMinor = r->entry.air_minor; + _languageMajor = r->entry.language_major; _languageMinor = r->entry.language_minor; + } + return self; +} +@end + +@interface STELAMetalLibrary : NSObject +@property (nullable, copy, atomic) NSString *label; +@property (readonly) id device; +@property (readonly) NSArray *functionNames; +@property (readonly) MTLLibraryType type; +@property (readonly, nullable) NSString *installName; +- (instancetype)initWithDevice:(id)device entries:(NSDictionary *)entries + reflectionAvailable:(BOOL)reflectionAvailable; +- (id)function:(NSString *)name error:(NSError **)error; +@end +@interface STELAMetalFunction : NSObject +@property (nullable, copy, atomic) NSString *label; +@property (readonly) STELAMetalFunctionSnapshot *snapshot; +- (instancetype)initWithLibrary:(STELAMetalLibrary *)library snapshot:(STELAMetalFunctionSnapshot *)snapshot; +@end + +@implementation STELAMetalFunction { + STELAMetalLibrary *_library; +} +- (instancetype)initWithLibrary:(STELAMetalLibrary *)library snapshot:(STELAMetalFunctionSnapshot *)snapshot +{ + self = [super init]; + if (self) { _library = library; _snapshot = snapshot; } + return self; +} +- (id)device { return _library.device; } +- (NSString *)name { return _snapshot.entryName; } +- (MTLFunctionType)functionType { return MTLFunctionTypeKernel; } +- (MTLPatchType)patchType { return MTLPatchTypeNone; } +- (NSInteger)patchControlPointCount { return -1; } +- (NSArray *)vertexAttributes { return nil; } /* Compute. */ +- (NSArray *)stageInputAttributes { return nil; } /* Compute. */ +- (NSDictionary *)functionConstantsDictionary { return @{}; } +- (MTLFunctionOptions)options { return MTLFunctionOptionNone; } +- (id)newArgumentEncoderWithBufferIndex:(NSUInteger)index +{ + /* Only manifest-proven primitive-buffer functions are constructed. There is + * no declared argument-buffer structure at ANY index for this function. + * Do not return nil from this nonnull API or construct a fake encoder. */ + [NSException raise:NSInvalidArgumentException format:@"Function %@ declares no argument buffer at index %llu", + self.name,(unsigned long long)index]; + __builtin_unreachable(); +} +/* Implement the original public deprecated selector with its exact ARC type. */ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +- (id)newArgumentEncoderWithBufferIndex:(NSUInteger)index + reflection:(MTLAutoreleasedArgument *)reflection +{ + (void)reflection; + return [self newArgumentEncoderWithBufferIndex:index]; +} +#pragma clang diagnostic pop +@end + +@implementation STELAMetalLibrary { + NSDictionary *_entries; + BOOL _reflectionAvailable; +} +- (instancetype)initWithDevice:(id)device entries:(NSDictionary *)entries + reflectionAvailable:(BOOL)reflectionAvailable +{ + self = [super init]; + if (self) { _device = device; _entries = [entries copy]; + _reflectionAvailable = reflectionAvailable; + _functionNames = [[_entries allKeys] sortedArrayUsingSelector:@selector(compare:)]; } + return self; +} +- (MTLLibraryType)type { return MTLLibraryTypeExecutable; } +- (NSString *)installName { return nil; } /* Executable libraries have none. */ +- (id)function:(NSString *)name error:(NSError **)error +{ + if (error) *error = nil; + STELAMetalFunctionSnapshot *snapshot = [name isKindOfClass:NSString.class] ? _entries[name] : nil; + if (!snapshot) { LibraryError(error,MTLLibraryErrorFunctionNotFound,@"Function not found in this library"); return nil; } + return [[STELAMetalFunction alloc] initWithLibrary:self snapshot:snapshot]; +} +- (id)newFunctionWithName:(NSString *)name { return [self function:name error:NULL]; } +- (id)newFunctionWithName:(NSString *)name constantValues:(MTLFunctionConstantValues *)values error:(NSError **)error +{ + if (values) { LibraryError(error,MTLLibraryErrorUnsupported,@"Function constant specialization is not implemented"); return nil; } + return [self function:name error:error]; +} +- (void)newFunctionWithName:(NSString *)name constantValues:(MTLFunctionConstantValues *)values + completionHandler:(void (^)(id,NSError *))handler +{ + if (!handler) [NSException raise:NSInvalidArgumentException format:@"A completion handler is required"]; + NSString *saved = [name copy]; MTLFunctionConstantValues *constants = [values copy]; + void (^completion)(id,NSError *) = [handler copy]; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{ + NSError *error = nil; + id function = [self newFunctionWithName:saved constantValues:constants error:&error]; + completion(function,error); + }); +} +- (id)newFunctionWithDescriptor:(MTLFunctionDescriptor *)descriptor error:(NSError **)error +{ + if (![descriptor isKindOfClass:MTLFunctionDescriptor.class] || + [descriptor isKindOfClass:MTLIntersectionFunctionDescriptor.class] || + descriptor.options != MTLFunctionOptionNone || descriptor.specializedName || descriptor.binaryArchives.count) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Unsupported function descriptor, options or archive lookup"); + return nil; + } + return [self newFunctionWithName:descriptor.name constantValues:descriptor.constantValues error:error]; +} +- (void)newFunctionWithDescriptor:(MTLFunctionDescriptor *)descriptor + completionHandler:(void (^)(id,NSError *))handler +{ + if (!handler) [NSException raise:NSInvalidArgumentException format:@"A completion handler is required"]; + MTLFunctionDescriptor *saved = [descriptor copy]; + void (^completion)(id,NSError *) = [handler copy]; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{ + NSError *error = nil; id function = [self newFunctionWithDescriptor:saved error:&error]; + completion(function,error); + }); +} +- (id)newIntersectionFunctionWithDescriptor:(MTLIntersectionFunctionDescriptor *)descriptor error:(NSError **)error +{ + (void)descriptor; LibraryError(error,MTLLibraryErrorUnsupported,@"Intersection functions are not implemented"); return nil; +} +- (void)newIntersectionFunctionWithDescriptor:(MTLIntersectionFunctionDescriptor *)descriptor + completionHandler:(void (^)(id,NSError *))handler +{ + (void)descriptor; + if (!handler) [NSException raise:NSInvalidArgumentException format:@"A completion handler is required"]; + void (^completion)(id,NSError *) = [handler copy]; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{ + NSError *error = nil; LibraryError(&error,MTLLibraryErrorUnsupported,@"Intersection functions are not implemented"); + completion(nil,error); + }); +} +- (MTLFunctionReflection *)reflectionForFunctionWithName:(NSString *)name +{ + /* The public contract also requires a deployment target of macOS13+. */ + if (!_reflectionAvailable || ![name isKindOfClass:NSString.class] || !_entries[name]) return nil; + return _entries[name].reflection; +} +@end + +id STELAMetalCreateLibrary(id device, NSData *original, + const struct stela_metal_library_manifest *m, NSError **error) +{ + if (error) *error = nil; + if (!device || ![device conformsToProtocol:@protocol(MTLDevice)] || + ![original isKindOfClass:NSData.class] || !m || m->size != sizeof(*m) || + m->abi != STELA_METAL_LIBRARY_ABI || m->reserved || m->flags & ~STELA_METAL_LIBRARY_SOURCE_COMPILED || + !m->entry_count || m->entry_count > ENTRY_LIMIT || !m->entries || + m->input.size != sizeof(m->input) || m->input.abi != STELA_METAL_INPUT_ABI || + !original.length || original.length > INPUT_LIMIT || m->input.original_bytes != original.length || + !m->target || !m->target_bytes || m->target_bytes > 1024 || memchr(m->target,0,(size_t)m->target_bytes) || + m->request_fast_math > 1 || m->compiler_profile > STELA_MSL_APPLE_32023_MACOS_27_2_ARM64) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Invalid/unqualified library manifest, device or input bounds"); return nil; + } + if ((m->input.kind != STELA_METAL_INPUT_MTLB && m->input.kind != STELA_METAL_INPUT_RAW_AIR) || + (m->input.kind == STELA_METAL_INPUT_MTLB && (m->input.format_major != 2 || + m->input.library_kind != 0 || m->input.entry_count != m->entry_count)) || + (m->input.kind == STELA_METAL_INPUT_RAW_AIR && !(m->flags & STELA_METAL_LIBRARY_SOURCE_COMPILED))) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Unsupported library kind or raw-input provenance"); return nil; + } + NSString *target = [[NSString alloc] initWithBytes:m->target length:(NSUInteger)m->target_bytes encoding:NSUTF8StringEncoding]; + if (!target) { LibraryError(error,MTLLibraryErrorUnsupported,@"Invalid target encoding"); return nil; } + if (m->flags & STELA_METAL_LIBRARY_SOURCE_COMPILED) { + if (m->compiler_profile != STELA_MSL_APPLE_32023_MACOS_27_2_ARM64 || m->request_language != 0x40001 || + !m->request_fast_math || ![target isEqualToString:@"air64_v29-apple-macosx27.2.0"] || + !Nonzero(m->source_sha256,32) || !Nonzero(m->build.gpucompiler_uuid,16) || + !Nonzero(m->build.implementation_uuid,16) || !Nonzero(m->build.llvm_uuid,16) || + !Nonzero(m->build.lazy_library_sha256,32) || !Nonzero(m->build.metal_stdlib_sha256,32) || + !Nonzero(m->build.metal_types_sha256,32)) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Source result lacks the qualified compiler/request identity"); return nil; + } + } else if (m->compiler_profile || m->request_language || m->request_fast_math || + Nonzero(m->source_sha256,32) || Nonzero((const uint8_t *)&m->build,sizeof(m->build))) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Precompiled input cannot imply source/compiler authentication"); return nil; + } + /* -copy may return an immutable NSData unchanged, including externally + * borrowed no-copy storage. Take an actual owned byte snapshot before the + * caller/helper lease can end; no manifest or external byte pointer escapes. */ + NSData *input = [[NSData alloc] initWithBytes:original.bytes length:original.length]; + NSMutableDictionary *digests = [NSMutableDictionary dictionary]; + if (!SameDigest(RangeDigest(input,NSMakeRange(0,input.length),digests),m->input.original_sha256)) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Original input digest mismatch"); return nil; + } + NSMutableDictionary *entries = [NSMutableDictionary dictionary]; + for (uint32_t i = 0; i < m->entry_count; i++) { + const struct stela_metal_function_record *r = &m->entries[i]; + if (r->size != sizeof(*r) || r->abi != STELA_METAL_LIBRARY_ABI || r->reserved || + r->flags != (STELA_METAL_ENTRY_NO_CONSTANTS | STELA_METAL_ENTRY_PLAIN_BUFFERS | + STELA_METAL_ENTRY_COMPLETE_REFLECTION) || + r->entry.size != sizeof(r->entry) || r->entry.abi != STELA_METAL_INPUT_ABI || r->entry.reserved || + r->entry.kind != 2 || !r->name || !r->name_bytes || r->name_bytes > 4096 || + memchr(r->name,0,(size_t)r->name_bytes) || + !Span(r->entry.module_offset,r->entry.module_bytes,input.length) || + !Span(r->air_offset,r->air_bytes,input.length) || r->air_bytes < 4 || + r->air_offset < r->entry.module_offset || r->air_bytes > r->entry.module_bytes || + r->air_offset-r->entry.module_offset > r->entry.module_bytes-r->air_bytes || + memcmp((const uint8_t *)input.bytes+r->air_offset,"BC\xc0\xde",4)) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Invalid function manifest/ranges or noncompute entry"); return nil; + } + if ((m->flags & STELA_METAL_LIBRARY_SOURCE_COMPILED) && + (r->entry.air_major != 2 || r->entry.air_minor != 9 || + r->entry.language_major != 4 || r->entry.language_minor != 1)) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Source metadata differs from qualified profile"); return nil; + } + NSString *name = [[NSString alloc] initWithBytes:r->name length:(NSUInteger)r->name_bytes encoding:NSUTF8StringEncoding]; + if (!name || entries[name] || + !SameDigest(RangeDigest(input,NSMakeRange((NSUInteger)r->entry.module_offset,(NSUInteger)r->entry.module_bytes),digests),r->entry.module_sha256) || + !SameDigest(RangeDigest(input,NSMakeRange((NSUInteger)r->air_offset,(NSUInteger)r->air_bytes),digests),r->air_sha256)) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Duplicate/invalid entry name or module digest mismatch"); return nil; + } + MTLFunctionReflection *reflection = CreateReflection(r); + if (!reflection) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Incomplete/unsupported function reflection"); return nil; + } + STELAMetalFunctionSnapshot *snapshot = [[STELAMetalFunctionSnapshot alloc] + initWithInput:input record:r manifest:m target:target reflection:reflection]; + entries[name] = snapshot; + } + return [[STELAMetalLibrary alloc] initWithDevice:device entries:entries + reflectionAvailable:m->input.kind == STELA_METAL_INPUT_RAW_AIR || m->input.minimum_os_major >= 13]; +} + +STELAMetalFunctionSnapshot *STELAMetalCopyFunctionSnapshot(id function, + id expected, NSError **error) +{ + if (error) *error = nil; + if (![function isKindOfClass:STELAMetalFunction.class] || !expected || function.device != expected) { + LibraryError(error,MTLLibraryErrorUnsupported,@"Function implementation or creating device mismatch"); return nil; + } + return ((STELAMetalFunction *)function).snapshot; +} diff --git a/crates/stela-drivers/src/gpu/metal/macos/library_internal.h b/crates/stela-drivers/src/gpu/metal/macos/library_internal.h new file mode 100644 index 0000000000..c2d7b6c395 --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/macos/library_internal.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_METAL_LIBRARY_INTERNAL_H +#define STELA_METAL_LIBRARY_INTERNAL_H +#import +#import +#include "library_manifest.h" + +NS_ASSUME_NONNULL_BEGIN + +/* Immutable first-party pipeline input, never Apple libraryData/functionData. + * The complete downstream device pipeline override must validate actual device + * support, request/specialization/bindings and invoke the real compiler/backend. + * This object cannot itself produce a successful Metal pipeline. */ +@interface STELAMetalFunctionSnapshot : NSObject +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; +@property (nonatomic, readonly) NSData *originalInput; +@property (nonatomic, readonly) NSRange rawAIRRange; +@property (nonatomic, readonly) NSString *entryName; +@property (nonatomic, readonly) NSString *targetTriple; +@property (nonatomic, readonly) MTLFunctionReflection *reflection; +@property (nonatomic, readonly) NSData *originalSHA256; +@property (nonatomic, readonly) NSData *moduleSHA256; +@property (nonatomic, readonly) NSData *rawAIRSHA256; +@property (nonatomic, readonly) NSData *sourceSHA256; +@property (nonatomic, readonly) NSData *compilerBuildIdentity; +@property (nonatomic, readonly) uint32_t compilerProfile; +@property (nonatomic, readonly) uint32_t requestLanguage; +@property (nonatomic, readonly) BOOL requestFastMath; +@property (nonatomic, readonly) uint32_t airMajor; +@property (nonatomic, readonly) uint32_t airMinor; +@property (nonatomic, readonly) uint32_t languageMajor; +@property (nonatomic, readonly) uint32_t languageMinor; +@end + +/* Requires a real creating device supplied by the registered device owner; + * creates no device, connection, service or backend. Failure returns nil and a + * public MTLLibraryErrorDomain error. Source compiler invocation/option mapping + * is deliberately outside this object boundary and stays profile-qualified. + * Original bytes are copied to immutable Foundation storage before publication. + * All manifest/header fields and original/module/raw hashes are checked first. + */ +FOUNDATION_EXPORT id _Nullable STELAMetalCreateLibrary(id device, + NSData *original, const struct stela_metal_library_manifest *manifest, + NSError * _Nullable __autoreleasing * _Nullable error); + +/* Returns nil on device/implementation mismatch, never invokes inherited Apple + * libraryData/compiler methods. The returned immutable object retains bytes. */ +FOUNDATION_EXPORT STELAMetalFunctionSnapshot * _Nullable STELAMetalCopyFunctionSnapshot( + id function, id expectedDevice, + NSError * _Nullable __autoreleasing * _Nullable error); +NS_ASSUME_NONNULL_END +#endif diff --git a/crates/stela-drivers/src/gpu/metal/macos/library_manifest.h b/crates/stela-drivers/src/gpu/metal/macos/library_manifest.h new file mode 100644 index 0000000000..35f633e01f --- /dev/null +++ b/crates/stela-drivers/src/gpu/metal/macos/library_manifest.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_METAL_LIBRARY_MANIFEST_H +#define STELA_METAL_LIBRARY_MANIFEST_H +#include "../input/input.h" +#include "../compiler/apple_source.h" +#include "../../common/mesa/src/stela/air_metadata.h" + +#define STELA_METAL_LIBRARY_ABI 1u +#define STELA_METAL_ENTRY_NO_CONSTANTS 1u +#define STELA_METAL_ENTRY_PLAIN_BUFFERS 2u +#define STELA_METAL_ENTRY_COMPLETE_REFLECTION 4u +#define STELA_METAL_LIBRARY_SOURCE_COMPILED 1u + +/* Same-process, same-CPU helper-result assembly only. These pointers are NOT an + * IPC wire representation. The actual authenticated helper/transport owner must + * produce this manifest with the canonical Rust input parser and shared LLVM23 + * inspector, cross-checking MTLB NAME/TYPE/VERS against the selected actual AIR + * entry. Metadata flags are evidence, never inferred from app/source identity. + * NO_CONSTANTS requires validated absence of function constants in both archive + * metadata (when present) and AIR. PLAIN_BUFFERS + * requires every buffer's reflected MSL type to be a supported builtin scalar/ + * vector; unknown/struct resources cannot claim absence of argument buffers. + * COMPLETE_REFLECTION requires the shared inspector's reflection_complete, + * including absent unsupported constants/annotations/globals (qualified internal + * undef AS3 static storage is understood) and exact primitive + * names/layout. The assembler must copy all borrowed inspector arrays/strings + * during each callback. Manifest pointers must refer to live immutable owner + * storage through constructor return; the constructor retains no such pointers. + * used describes uses in the accepted AIR, not backend liveness. + * LLVM/body/codegen support, device caps and runtime binding are pipeline work. + */ +struct stela_metal_function_record { + uint32_t size, abi, flags, reserved; + struct stela_metal_input_entry entry; + const uint8_t *name; + uint64_t name_bytes; + uint64_t air_offset, air_bytes; + uint8_t air_sha256[32]; + uint32_t argument_count, reserved_arguments; + const struct stela_air_argument_info *arguments; +}; +struct stela_metal_library_manifest { + uint32_t size, abi, flags, compiler_profile; + struct stela_metal_input_info input; + uint32_t request_language, request_fast_math, entry_count, reserved; + const uint8_t *target; + uint64_t target_bytes; + uint8_t source_sha256[32]; + struct stela_msl_build_identity build; + const struct stela_metal_function_record *entries; +}; + +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia.rs b/crates/stela-drivers/src/gpu/nvidia.rs index 641786f86e..bbfd5ce94f 100644 --- a/crates/stela-drivers/src/gpu/nvidia.rs +++ b/crates/stela-drivers/src/gpu/nvidia.rs @@ -5,7 +5,10 @@ use core::{ffi::c_void, marker::PhantomData, marker::PhantomPinned, pin::Pin}; pub mod allocation; mod dma; +pub mod firmware; mod memory; +pub mod mmio; +pub mod page_geometry; pub mod services; const PCI_CONFIG_BYTES: u32 = 4096; diff --git a/crates/stela-drivers/src/gpu/nvidia/firmware.rs b/crates/stela-drivers/src/gpu/nvidia/firmware.rs new file mode 100644 index 0000000000..ff80701674 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/firmware.rs @@ -0,0 +1,178 @@ +//! Original RM firmware lookup over Stela's immutable firmware catalog. +//! +//! This supplies CPU image bytes only. Manifest length/SHA-256 integrity is not +//! vendor authentication. Original RM ELF/version/signature checks, upload, +//! reset, IRQ/context services and actual device initialization remain required. +use super::{memory, services::MemoryServices, services::ServiceError}; +use crate::firmware::{Image, Provider, Requirement, Target}; +use core::{ffi::CStr, ffi::c_char, ffi::c_void, ptr, ptr::NonNull}; + +unsafe extern "C" { + fn stela_nvidia_firmware_family(architecture: u32, implementation: u32) -> u32; + fn stela_nvidia_firmware_alignment() -> u64; +} + +/// A provider bound to one native device's observed NVIDIA chip family. The +/// original vendor helper selects the family; no parallel architecture table. +/// Attach before pinning/binding [`MemoryServices::with_firmware`]. +pub struct FirmwareBinding<'a> { + provider: &'a dyn Provider, + family: u32, +} + +impl<'a> FirmwareBinding<'a> { + /// # Safety + /// `architecture` and `implementation` are the actual device's observed + /// original NV_ARCH facts (not PCI IDs or a guest's assertions). This binding + /// and its MemoryServices requester describe the same device/reset epoch. + /// Keep provider/catalog immutable, CPU-readable and live until all firmware + /// tokens are returned and the pinned service/state successfully unbinds. + /// Serialize every lookup/release with the other service operations; exclude + /// interrupt, allocator and provider reentry. The global heap must be live. + pub unsafe fn new( + provider: &'a dyn Provider, + architecture: u32, + implementation: u32, + ) -> Result { + // SAFETY: pure original C selector, same native integer ABI. + let family = unsafe { stela_nvidia_firmware_family(architecture, implementation) }; + if family == 0 { + return Err(ServiceError::InvalidConfiguration); + } + Ok(Self { provider, family }) + } +} + +struct Token<'a> { + image: Image<'a>, + owner: *const MemoryServices<'a>, +} +const _: () = assert!(align_of::>() <= memory::ALIGNMENT); + +fn native_length(length: usize, address: usize, alignment: usize) -> Option { + if length == 0 || alignment == 0 || !address.is_multiple_of(alignment) { + return None; + } + u32::try_from(length).ok() +} + +/// All fallible preparation precedes publication/counting. The internal bounded +/// allocator seam exercises real metadata OOM without exhausting the host heap. +fn prepare<'a>( + owner: &'a MemoryServices<'a>, + state: *mut c_void, + family: u32, + requirement: Requirement<'_>, + allocate: impl FnOnce() -> Option>, +) -> Option<(NonNull>, *const c_void, u32)> { + if !owner.bound_to(state) { + return None; + } + let binding = owner.firmware.as_ref()?; + if binding.family != family { + return None; + } + let count = owner.firmware_tokens.get().checked_add(1)?; + let image = binding.provider.load(requirement).ok()?; + // A delegating Provider can accidentally return a different valid catalog + // image. Exact name/target still must match the original vendor request. + if image.name() != requirement.name || image.target() != requirement.target { + return None; + } + // SAFETY: a pure layout query on the original vendor ELF types. + let alignment = unsafe { stela_nvidia_firmware_alignment() } as usize; + let bytes = native_length( + image.bytes().len(), + image.bytes().as_ptr() as usize, + alignment, + )?; + let buffer = image.bytes().as_ptr().cast(); + let storage = allocate()?.cast::>(); + // SAFETY: the common heap returned sufficient/aligned exclusively owned + // metadata. The token keeps its Image/provider borrow until the unique put. + unsafe { storage.as_ptr().write(Token { image, owner }) }; + owner.firmware_tokens.set(count); + Some((storage, buffer, bytes)) +} + +/// # Safety +/// Only the native C shim supplies this bound state/service and static original +/// selector strings. Output slots are writable, aligned and disjoint. The pinned +/// owner, catalog and original state remain live through every published token; +/// all operations obey the serialized nonreentrant process/heap contract above. +#[unsafe(no_mangle)] +unsafe extern "C" fn stela_nvidia_get_firmware( + services: *mut c_void, + state: *mut c_void, + family: u32, + name: *const c_char, + hardware: *const c_char, + revision: *const c_char, + buffer: *mut *const c_void, + bytes: *mut u32, +) -> *const c_void { + // SAFETY: C only forwards the handle installed in this live original state. + let owner = unsafe { &*services.cast::>() }; + // SAFETY: these are static, terminated ASCII strings from original helpers. + let labels = unsafe { + ( + CStr::from_ptr(name).to_str(), + CStr::from_ptr(hardware).to_str(), + CStr::from_ptr(revision).to_str(), + ) + }; + let (Ok(name), Ok(hardware), Ok(revision)) = labels else { + return ptr::null(); + }; + let result = prepare( + owner, + state, + family, + Requirement { + name, + target: Target { + driver: "nvidia-rm", + hardware, + revision, + board: None, + }, + minimum_bytes: 1, + }, + || memory::allocate(size_of::>() as u64).ok(), + ); + let Some((token, data, size)) = result else { + return ptr::null(); + }; + // SAFETY: caller-owned checked native output slots. No fallible operation + // follows; publish the one unique token only after both outputs are ready. + unsafe { + bytes.write(size); + buffer.write(data); + } + token.as_ptr().cast() +} + +/// # Safety +/// Return only a live firmware token from this adapter, once, after all CPU +/// readers stop. Provider/service/state/global heap remain live and operations +/// are serialized, noninterrupt and nonreentrant. No fabricated completion. +#[unsafe(no_mangle)] +unsafe extern "C" fn stela_nvidia_put_firmware(token: *const c_void) { + // SAFETY: original nv_put_firmware filters NULL; unique actual token kind. + let token = token.cast_mut().cast::>(); + // SAFETY: the raw ownership contract retains token and pinned service. + let value = unsafe { &*token }; + let owner = unsafe { &*value.owner }; + debug_assert!(owner.firmware_tokens.get() > 0); + // Read the image borrow before release; no image copy or ownership escape. + let _ = value.image.bytes(); + owner.firmware_tokens.set(owner.firmware_tokens.get() - 1); + // SAFETY: unique put after all token users stop; exact common-heap free. + unsafe { + token.drop_in_place(); + memory::free(token.cast()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-drivers/src/gpu/nvidia/firmware/tests.rs b/crates/stela-drivers/src/gpu/nvidia/firmware/tests.rs new file mode 100644 index 0000000000..e2b957d87f --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/firmware/tests.rs @@ -0,0 +1,359 @@ +use super::*; +use crate::{ + bus::{ + dma::{ + mapping::{Direction, DmaDomain, DmaError, DomainMapping}, + memory::{CacheAttribute, MemoryError, PageSource, PinnedPages}, + }, + pci::Address, + }, + firmware::{Catalog, Provenance, Resource}, +}; +use alloc::{alloc::alloc_zeroed, alloc::dealloc, boxed::Box, format, sync::Arc, vec}; +use core::{alloc::Layout, cell::Cell, ops::Range, pin::Pin}; +use sha2::{Digest, Sha256}; + +unsafe extern "C" { + fn stela_nvidia_state_layout(bytes: *mut u64, alignment: *mut u64); + fn stela_nvidia_firmware_version() -> *const c_char; + fn nv_get_firmware( + state: *mut c_void, + kind: u32, + family: u32, + buffer: *mut *const c_void, + bytes: *mut u32, + ) -> *const c_void; + fn nv_put_firmware(token: *const c_void); +} + +// The explicit CPU model attests only its 4KiB geometry. It never exercises +// RAM or DMA: unsupported operations are genuine +// failures so an accidental dependency cannot masquerade as native success. +struct Unavailable; +impl PageSource for Unavailable { + fn page_geometry(&self) -> Result { + crate::bus::dma::memory::PageGeometry::base_only(12) + } + fn allocate(&self, _: usize, _: usize, _: CacheAttribute) -> Result { + panic!("firmware lookup must not allocate RAM pins") + } +} +// SAFETY: this model can never publish any device mapping or successful sync. +unsafe impl DmaDomain for Unavailable { + unsafe fn map(&self, _: &PinnedPages, _: Direction, _: u64) -> Result { + panic!("firmware bytes must not become DMA addresses") + } + unsafe fn unmap(&self, _: DomainMapping) -> Result<(), DmaError> { + panic!("no DMA mapping exists") + } + unsafe fn sync_for_device( + &self, + _: DomainMapping, + _: Range, + _: Direction, + ) -> Result<(), DmaError> { + panic!("no DMA mapping exists") + } + unsafe fn sync_for_cpu( + &self, + _: DomainMapping, + _: Range, + _: Direction, + ) -> Result<(), DmaError> { + panic!("no DMA mapping exists") + } +} + +struct State(NonNull, Layout); +impl State { + fn new() -> Self { + let (mut bytes, mut alignment) = (0, 0); + // SAFETY: writable native integer slots for original type layout. + unsafe { stela_nvidia_state_layout(&mut bytes, &mut alignment) }; + let layout = Layout::from_size_align(bytes as usize, alignment as usize).unwrap(); + // SAFETY: original type layout; zero PCI fixture, never GPU init. + Self( + NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap(), + layout, + ) + } + fn raw(&self) -> *mut c_void { + self.0.as_ptr().cast() + } +} +impl Drop for State { + fn drop(&mut self) { + // SAFETY: fixture callers and bindings ended before final release. + unsafe { dealloc(self.0.as_ptr(), self.1) }; + } +} + +#[repr(align(16))] +struct Aligned([u8; 32]); +static DATA: Aligned = Aligned([0x5a; 32]); +fn version() -> &'static str { + // SAFETY: C returns the static version generated from vendor version.mk. + unsafe { CStr::from_ptr(stela_nvidia_firmware_version()) } + .to_str() + .unwrap() +} +fn target(hardware: &str) -> Target<'_> { + Target { + driver: "nvidia-rm", + hardware, + revision: version(), + board: None, + } +} +fn make_catalog(name: &str, hardware: &str, bytes: &'static [u8]) -> Catalog { + Catalog::from_persistent_handoff(vec![Resource { + name, + target: target(hardware), + provenance: Provenance { + source: "synthetic CPU fixture", + revision: "1", + member: name, + license: "MIT", + }, + expected_length: bytes.len(), + expected_sha256: Sha256::digest(bytes).into(), + bytes, + }]) + .unwrap() +} +fn bind<'a>( + provider: Option<&'a dyn Provider>, + architecture: u32, + implementation: u32, + state: &State, +) -> Pin>> { + static SOURCE: Unavailable = Unavailable; + crate::gpu::nvidia::page_geometry::tests::initialize_model(12); + // SAFETY: CPU model only, same zero PCI requester; no hardware operations. + let mut service = unsafe { + MemoryServices::new( + &SOURCE, + Arc::new(Unavailable), + Address { + segment: 0, + bus: 0, + device: 0, + function: 0, + }, + 12, + u64::MAX, + ) + } + .unwrap(); + if let Some(provider) = provider { + // SAFETY: test attests this synthetic observed architecture to this model. + service = service.with_firmware( + unsafe { FirmwareBinding::new(provider, architecture, implementation) }.unwrap(), + ); + } + let mut service = Box::pin(service); + // SAFETY: live original fixture state, no concurrent callers, pinned owner. + unsafe { service.as_mut().bind(state.raw()) }.unwrap(); + service +} +fn request(state: *mut c_void, kind: u32, family: u32) -> (*const c_void, *const c_void, u32) { + let mut buffer = ptr::dangling::(); + let mut bytes = 0xabcd; + // SAFETY: either NULL or exact live fixture state; distinct writable outputs. + let token = unsafe { nv_get_firmware(state, kind, family, &mut buffer, &mut bytes) }; + (token, buffer, bytes) +} +fn failed(state: *mut c_void, kind: u32, family: u32) { + let (token, buffer, bytes) = request(state, kind, family); + assert!(token.is_null()); + assert_eq!(buffer, ptr::dangling()); + assert_eq!(bytes, 0xabcd); +} + +#[test] +fn original_selectors_cover_architecture_splits_and_all_package_kinds() { + // Frozen independent expectations from the original nv-firmware*.h switch + // bodies at the retained vendor pin. No production enum/selector mirror. + for (arch, implementation, family, hardware, suffix) in [ + (0x160, 6, 1, "tu10x", "tu10x"), + (0x160, 7, 2, "tu11x", "tu10x"), + (0x170, 0, 3, "ga100", "tu10x"), + (0x170, 2, 4, "ga10x", "ga10x"), + (0x190, 2, 5, "ad10x", "ga10x"), + (0x180, 0, 6, "gh100", "ga10x"), + (0x1a0, 0, 8, "gb10x", "ga10x"), + (0x1b0, 0, 9, "gb20x", "ga10x"), + (0x1c0, 0, 10, "gr10x", "ga10x"), + (0x1a0, 11, 11, "gb10y", "ga10x"), + (0x1b0, 11, 12, "gb20y", "ga10x"), + (0x1b0, 12, 12, "gb20y", "ga10x"), + ] { + // SAFETY: pure selector on scalar fixture values. + assert_eq!( + unsafe { stela_nvidia_firmware_family(arch, implementation) }, + family + ); + for (kind, prefix) in [(0, "gsp"), (1, "gsp_log"), (2, "ucodes")] { + let name = format!("nvidia/{}/{}_{}.bin", version(), prefix, suffix); + let catalog = make_catalog(&name, hardware, &DATA.0); + let state = State::new(); + let mut owner = bind(Some(&catalog), arch, implementation, &state); + let (token, buffer, bytes) = request(state.raw(), kind, family); + assert!(!token.is_null()); + assert_eq!(buffer, DATA.0.as_ptr().cast()); + assert_eq!(bytes, 32); + assert_eq!(owner.firmware_tokens.get(), 1); + // SAFETY: a token is still live, so refusal preserves installed slots. + assert_eq!( + unsafe { owner.as_mut().unbind() }, + Err(ServiceError::Native(0x40)) + ); + // SAFETY: no more byte readers, actual unique token, supported context. + unsafe { nv_put_firmware(token) }; + assert_eq!(owner.firmware_tokens.get(), 0); + // SAFETY: every token/caller ended, no hardware was activated. + unsafe { owner.as_mut().unbind() }.unwrap(); + } + } +} + +#[test] +fn original_abi_rejects_invalid_inputs_and_preserves_outputs() { + let name = format!("nvidia/{}/gsp_ga10x.bin", version()); + let catalog = make_catalog(&name, "ga10x", &DATA.0); + let state = State::new(); + failed(ptr::null_mut(), 0, 4); + failed(state.raw(), 0, 4); + let mut owner = bind(Some(&catalog), 0x170, 2, &state); + for (kind, family) in [ + (3, 4), + (u32::MAX, 4), + (0, 0), + (0, 7), + (0, 13), + (0, u32::MAX), + (0, 5), + (1, 4), + ] { + failed(state.raw(), kind, family); + } + let mut bytes = 73; + let mut buffer = ptr::dangling::(); + // SAFETY: invalid NULL output slots are rejected before lookup/publication. + unsafe { + assert!(nv_get_firmware(state.raw(), 0, 4, ptr::null_mut(), &mut bytes).is_null()); + assert!(nv_get_firmware(state.raw(), 0, 4, &mut buffer, ptr::null_mut()).is_null()); + nv_put_firmware(ptr::null()); + } + assert_eq!(bytes, 73); + assert_eq!(buffer, ptr::dangling()); + assert_eq!(owner.firmware_tokens.get(), 0); + // SAFETY: no tokens or callers remain. + unsafe { owner.as_mut().unbind() }.unwrap(); + let state = State::new(); + let mut owner = bind(None, 0x170, 2, &state); + failed(state.raw(), 0, 4); + // SAFETY: no tokens or callers remain. + unsafe { owner.as_mut().unbind() }.unwrap(); + // SAFETY: pure invalid architecture fixture, must refuse binding. + assert!(unsafe { FirmwareBinding::new(&catalog, 0, 0) }.is_err()); +} + +#[test] +fn multiple_real_tokens_prevent_unbind_until_last_put_and_keep_same_bytes() { + let name = format!("nvidia/{}/gsp_ga10x.bin", version()); + let catalog = make_catalog(&name, "ga10x", &DATA.0); + let state = State::new(); + let mut owner = bind(Some(&catalog), 0x170, 2, &state); + let (first, data, _) = request(state.raw(), 0, 4); + let (second, again, _) = request(state.raw(), 0, 4); + assert!(!first.is_null() && !second.is_null()); + assert_ne!(first, second); + assert_eq!(data, again); + // SAFETY: first token retired, second still owned/readable; unbind refuses. + unsafe { + nv_put_firmware(first); + assert_eq!(owner.as_mut().unbind(), Err(ServiceError::Native(0x40))); + } + // SAFETY: second immutable CPU view remains retained by its real token. + assert_eq!( + unsafe { core::slice::from_raw_parts(again.cast::(), 32) }, + &DATA.0 + ); + // SAFETY: last readers stopped, return token then unbind exact owner. + unsafe { + nv_put_firmware(second); + owner.as_mut().unbind().unwrap(); + } + failed(state.raw(), 0, 4); +} + +#[test] +fn metadata_oom_count_overflow_and_invalid_image_never_publish_tokens() { + let name = format!("nvidia/{}/gsp_ga10x.bin", version()); + let catalog = make_catalog(&name, "ga10x", &DATA.0); + let state = State::new(); + let mut owner = bind(Some(&catalog), 0x170, 2, &state); + let requirement = Requirement { + name: &name, + target: target("ga10x"), + minimum_bytes: 1, + }; + assert!(prepare(&owner, state.raw(), 4, requirement, || None).is_none()); + assert_eq!(owner.firmware_tokens.get(), 0); + owner.firmware_tokens.set(usize::MAX); + assert!( + prepare(&owner, state.raw(), 4, requirement, || panic!( + "overflow must fail before metadata allocation" + )) + .is_none() + ); + assert_eq!(owner.firmware_tokens.get(), usize::MAX); + owner.firmware_tokens.set(0); + // SAFETY: tests' exact resource count reset; no published token ever existed. + unsafe { owner.as_mut().unbind() }.unwrap(); + for (hardware, bytes) in [ + ("ad10x", &DATA.0[..]), + ("ga10x", &DATA.0[1..]), + ("ga10x", &DATA.0[0..0]), + ] { + let catalog = make_catalog(&name, hardware, bytes); + let state = State::new(); + let mut owner = bind(Some(&catalog), 0x170, 2, &state); + failed(state.raw(), 0, 4); + assert_eq!(owner.firmware_tokens.get(), 0); + // SAFETY: failure published no token. + unsafe { owner.as_mut().unbind() }.unwrap(); + } + assert_eq!(native_length(u32::MAX as usize, 0x1000, 8), Some(u32::MAX)); + assert_eq!(native_length(u32::MAX as usize + 1, 0x1000, 8), None); + assert_eq!(native_length(1, 0x1001, 8), None); + assert_eq!(native_length(0, 0x1000, 8), None); +} + +#[test] +fn delegating_provider_cannot_substitute_another_valid_catalog_image() { + struct Wrong<'a>(&'a Catalog, &'a str, &'a str, Cell); + impl Provider for Wrong<'_> { + fn load(&self, _: Requirement<'_>) -> Result, crate::firmware::Error> { + self.3.set(self.3.get() + 1); + self.0.load(Requirement { + name: self.1, + target: target(self.2), + minimum_bytes: 1, + }) + } + } + let wanted = format!("nvidia/{}/gsp_ga10x.bin", version()); + for (name, hardware) in [("other.bin", "ga10x"), (&wanted, "ad10x")] { + let catalog = make_catalog(name, hardware, &DATA.0); + let provider = Wrong(&catalog, name, hardware, Cell::new(0)); + let state = State::new(); + let mut owner = bind(Some(&provider), 0x170, 2, &state); + failed(state.raw(), 0, 4); + assert_eq!(provider.3.get(), 1); + assert_eq!(owner.firmware_tokens.get(), 0); + // SAFETY: failed lookup published nothing and all callers stopped. + unsafe { owner.as_mut().unbind() }.unwrap(); + } +} diff --git a/crates/stela-drivers/src/gpu/nvidia/mmio.rs b/crates/stela-drivers/src/gpu/nvidia/mmio.rs new file mode 100644 index 0000000000..b491595042 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/mmio.rs @@ -0,0 +1,422 @@ +//! Original tokenless RM physical mapping ABI over the canonical MMIO authority. +//! +//! This module owns only returned-VA/size -> Mapping lease bookkeeping. Actual +//! resource registration, aliases, effective cache policy, native roots and TLB +//! acknowledgement belong to `bus::mmio::owned` and the real platform adapter. +//! No platform adapter or GPU activation is supplied here. Cached RAM/firmware +//! mapping remains a separate unsupported integration requirement. +use crate::bus::mmio::owned::{ + Authority, CacheAttribute, Error as MappingError, Mapping, PhysicalSpan, Protection, + Status as AuthorityStatus, +}; +use alloc::vec::Vec; +use core::{ + ffi::c_void, + marker::{PhantomData, PhantomPinned}, + pin::Pin, + ptr, + sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering}, +}; + +static INSTALLED: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +// Fail reentry before constructing any Rust reference to the installed object. +// This guard is ownership serialization, never an ISR/context predicate. +static ENTERED: AtomicBool = AtomicBool::new(false); +static REFUSED_CALLS: AtomicU64 = AtomicU64::new(0); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + AlreadyInstalled, + NotInstalled, + Busy, + LiveMappings, + UnknownMapping, + Mapping(MappingError), +} +impl From for Error { + fn from(error: MappingError) -> Self { + Self::Mapping(error) + } +} + +/// Historical failures remain visible because the original unmap ABI is void. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Status { + pub live: usize, + pub pending: usize, + pub busy_retirements: u64, + pub failed_maps: u64, + pub failed_unmaps: u64, + pub unmap_quarantines: u64, + pub last_failure: Option, + /// Boot-global entry refusals before any service reference is constructed. + pub refused_calls: u64, +} + +struct Lease { + address: *mut c_void, + bytes: u64, + mapping: Mapping, + pending: bool, +} + +/// Pinned native installation for the original global, tokenless mapping hooks. +/// It retains a clone of the one canonical Authority, not a BAR/resource table. +/// No resources are registered here. This handle is neither Send nor Sync. +pub struct MmioServices { + authority: Authority, + leases: Vec, + busy_retirements: u64, + failed_maps: u64, + failed_unmaps: u64, + unmap_quarantines: u64, + last_failure: Option, + _owner: PhantomData<*mut ()>, + _pin: PhantomPinned, +} + +struct Entry; +impl Entry { + fn acquire() -> Result { + ENTERED + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .map_err(|_| Error::Busy)?; + Ok(Self) + } +} +impl Drop for Entry { + fn drop(&mut self) { + ENTERED.store(false, Ordering::Release); + } +} + +impl MmioServices { + pub fn new(authority: Authority) -> Self { + Self { + authority, + leases: Vec::new(), + busy_retirements: 0, + failed_maps: 0, + failed_unmaps: 0, + unmap_quarantines: 0, + last_failure: None, + _owner: PhantomData, + _pin: PhantomPinned, + } + } + + /// Publish only after the real global heap, registered resources and native + /// mapping platform are ready. This performs no mapping or initialization. + /// + /// # Safety + /// Keep this pinned object alive until successful uninstall, with the same + /// native CPU ABI/address space. Serialize all native callers and Rust + /// service access; exclude interrupts, callback/allocator reentry and final + /// release outside the providers' process/deferred context. Do not create + /// Rust references to this object while any C callback can access it. + /// Stop/drain all callers and retire live/pending leases before uninstall; + /// they may not outlive installation. The guard rejects reentry but cannot make an + /// invalid lifetime/context or an interrupted allocator safe. + pub unsafe fn install(self: Pin<&mut Self>) -> Result<(), Error> { + let _entry = Entry::acquire()?; + // SAFETY: pin remains in place through all callbacks and uninstall. + let pointer = unsafe { self.get_unchecked_mut() as *mut Self }; + INSTALLED + .compare_exchange( + ptr::null_mut(), + pointer, + Ordering::AcqRel, + Ordering::Acquire, + ) + .map_err(|_| Error::AlreadyInstalled)?; + Ok(()) + } + + /// # Safety + /// All native callers have stopped/drained and cannot restart, including + /// callbacks/workers with raw addresses. The install lifetime/context and + /// serialization contract still applies. Failure leaves the slot installed. + /// Canonically quarantined leases retain actual platform/resources without + /// this object; their failure remains a real teardown error in diagnostics. + /// Live AND pending leases refuse uninstall. Drain pending retirements at + /// real quiescent points, and before attempting final uninstall. + pub unsafe fn uninstall(self: Pin<&mut Self>) -> Result<(), Error> { + let _entry = Entry::acquire()?; + // SAFETY: caller excludes callbacks and keeps the object pinned. + let services = unsafe { self.get_unchecked_mut() }; + let pointer = services as *mut Self; + if INSTALLED.load(Ordering::Acquire) != pointer { + return Err(Error::NotInstalled); + } + if !services.leases.is_empty() { + return Err(Error::LiveMappings); + } + INSTALLED.store(ptr::null_mut(), Ordering::Release); + Ok(()) + } + + /// Inspect only between serialized callbacks, as required by install. + pub fn status(&self) -> Status { + let pending = self.leases.iter().filter(|lease| lease.pending).count(); + Status { + live: self.leases.len() - pending, + pending, + busy_retirements: self.busy_retirements, + failed_maps: self.failed_maps, + failed_unmaps: self.failed_unmaps, + unmap_quarantines: self.unmap_quarantines, + last_failure: self.last_failure, + refused_calls: REFUSED_CALLS.load(Ordering::Relaxed), + } + } + + /// Actual shared-authority state, including uncertain maps that never + /// returned a VA and quarantine from every native authority consumer. + pub fn authority_status(&self) -> Result { + self.authority.status() + } + + /// Retry pending exact canonical tokens, using their existing ledger slots. + /// No adapter allocation, queue or worker is created. Returns the number + /// retired if all attempts succeed; an error may follow earlier progress, + /// which remains visible in status. Busy retains the pending Mapping even + /// if the platform was called and canonical state is already uncertain. + /// + /// # Safety + /// Call only on the installed pinned native owner, serialized with all C + /// hooks in the real platform/global heap's process/deferred context. Every + /// pending lease's initial unmap has already proved complete raw CPU/device/ + /// callback/worker and posted/WC drain; no future access may restart. Retry + /// at actual quiescent points and before uninstall. Never infer that Busy + /// means a platform callback was not entered or a raw VA is usable again. + pub unsafe fn drain_pending_retirements(self: Pin<&mut Self>) -> Result { + let _entry = Entry::acquire()?; + // SAFETY: caller excludes native callbacks and preserves pin/lifetime. + let services = unsafe { self.get_unchecked_mut() }; + if !ptr::eq(INSTALLED.load(Ordering::Acquire), services) { + return Err(Error::NotInstalled); + } + let mut at = 0; + let mut retired = 0; + let mut failure = None; + while at < services.leases.len() { + if !services.leases[at].pending { + at += 1; + continue; + } + // SAFETY: initial unmap permanently ended raw access; retry the + // same retained canonical token in owner-established context. + match unsafe { services.retire(at) } { + Ok(()) => retired += 1, + Err(error) => { + services.record_unmap_failure(error); + failure.get_or_insert(error); + if error == Error::Mapping(MappingError::Busy) { + at += 1; // retained in this same slot + } + // Other failures consumed this slot into quarantine; its + // swapped-in neighbor still needs inspection at this index. + } + } + } + failure.map_or(Ok(retired), Err) + } + + fn map(&mut self, physical: u64, bytes: u64, mode: u32) -> Result<*mut c_void, Error> { + let attribute = match mode { + 1 | 6 => CacheAttribute::Uncached, + 2 => CacheAttribute::WriteCombining, + _ => return Err(MappingError::UnsupportedCache.into()), + }; + if physical == 0 { + return Err(MappingError::InvalidRange.into()); + } + let span = PhysicalSpan::new(physical, bytes)?; + let size = usize::try_from(bytes).map_err(|_| MappingError::InvalidRange)?; + // Validate genuine context and complete rounded ownership BEFORE any + // allocator operation. map_physical repeats lookup and atomically + // reserves the resource/cache range; no GPU BAR metadata is trusted. + drop(self.authority.resolve_resource(span)?); + let authority = &self.authority; + publish( + &mut self.leases, + |leases| { + leases + .try_reserve(1) + .map_err(|_| MappingError::Unavailable.into()) + }, + || { + let mapping = authority.map_physical(span, attribute, Protection::ReadWrite)?; + // A canonical address failure (e.g. concurrent identity + // quarantine) drops into canonical quarantine, never unmaps a + // token or publishes an invalid/partially valid raw pointer. + let address = mapping.address(0, size)?.as_ptr().cast(); + Ok(( + Lease { + address, + bytes, + mapping, + pending: false, + }, + address, + )) + }, + ) + } + + /// # Safety + /// Original caller has stopped/drained every raw consumer and posted/WC + /// effect of precisely this mapping. No future access may begin. + unsafe fn unmap(&mut self, address: *mut c_void, bytes: u64) -> Result<(), Error> { + let at = self + .leases + .iter() + .position(|lease| !lease.pending && lease.address == address && lease.bytes == bytes) + .ok_or(Error::UnknownMapping)?; + // The void ABI ended the caller's raw access regardless of whether + // canonical retirement can finish now. Never hand this lease out again. + self.leases[at].pending = true; + // SAFETY: initial caller proves permanent raw-user/post-write drain. + unsafe { self.retire(at) } + } + + /// # Safety + /// This pending slot has permanently stopped/drained all raw users/effects. + unsafe fn retire(&mut self, at: usize) -> Result<(), Error> { + // SAFETY: caller proves complete raw-user drain; Mapping retains the + // genuine platform/resource and validates exact canonical identity. + match unsafe { self.leases[at].mapping.retire() } { + Ok(()) => { + self.leases.swap_remove(at); + Ok(()) + } + Err(MappingError::Busy) => Err(MappingError::Busy.into()), + Err(error) => { + self.unmap_quarantines = self.unmap_quarantines.saturating_add(1); + // Fatal/ambiguous failures consume into canonical permanent + // quarantine, retaining actual owners and uncertain aliases. + // Busy instead retains the exact token without guessing if + // native unmap ran, for explicit native-owner retry above. + self.leases.swap_remove(at); + Err(error.into()) + } + } + } + + fn record_unmap_failure(&mut self, error: Error) { + if error == Error::Mapping(MappingError::Busy) { + self.busy_retirements = self.busy_retirements.saturating_add(1); + } else { + self.failed_unmaps = self.failed_unmaps.saturating_add(1); + } + self.last_failure = Some(error); + } +} + +// All fallible bookkeeping precedes the real mapping. This internal seam lets +// tests model bounded metadata OOM without exhausting the Rust test harness. +fn publish( + leases: &mut Vec, + reserve: impl FnOnce(&mut Vec) -> Result<(), Error>, + map: impl FnOnce() -> Result<(T, R), Error>, +) -> Result { + reserve(leases)?; + if leases.len() == leases.capacity() { + return Err(MappingError::Unavailable.into()); + } + let (lease, result) = map()?; + leases.push(lease); + Ok(result) +} + +fn refuse() { + let _ = REFUSED_CALLS.try_update(Ordering::Relaxed, Ordering::Relaxed, |count| { + Some(count.saturating_add(1)) + }); +} + +fn with_installed(fallback: R, call: impl FnOnce(&mut MmioServices) -> R) -> R { + let Ok(_entry) = Entry::acquire() else { + refuse(); + return fallback; + }; + let pointer = INSTALLED.load(Ordering::Acquire); + if pointer.is_null() { + refuse(); + return fallback; + } + // SAFETY: unsafe install retains this pinned native object; global entry + // ownership excludes all other callbacks before constructing this borrow. + call(unsafe { &mut *pointer }) +} + +#[unsafe(no_mangle)] +extern "C" fn stela_nvidia_map_mmio(physical: u64, bytes: u64, mode: u32) -> *mut c_void { + with_installed(ptr::null_mut(), |services| { + match services.map(physical, bytes, mode) { + Ok(address) => address, + Err(error) => { + services.failed_maps = services.failed_maps.saturating_add(1); + services.last_failure = Some(error); + ptr::null_mut() + } + } + }) +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn stela_nvidia_unmap_mmio(address: *mut c_void, bytes: u64) { + with_installed((), |services| { + // SAFETY: original C caller satisfies the installed unmap contract. + if let Err(error) = unsafe { services.unmap(address, bytes) } { + services.record_unmap_failure(error); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use core::cell::Cell; + + #[test] + fn failed_metadata_reservation_never_maps_or_publishes() { + let mut leases = Vec::::new(); + let calls = Cell::new(0); + let result = publish( + &mut leases, + |_| Err(MappingError::Unavailable.into()), + || { + calls.set(calls.get() + 1); + Ok((1, ())) + }, + ); + assert_eq!(result, Err(Error::Mapping(MappingError::Unavailable))); + assert!(leases.is_empty()); + assert_eq!(calls.get(), 0); + assert_eq!( + publish( + &mut leases, + |_| Ok(()), + || { + calls.set(1); + Ok((1, ())) + } + ), + Err(Error::Mapping(MappingError::Unavailable)) + ); + assert_eq!(calls.get(), 0); + leases.try_reserve(1).unwrap(); + assert_eq!( + publish( + &mut leases, + |_| Ok(()), + || Err::<(u8, ()), _>(MappingError::MappingFailed.into()) + ), + Err(Error::Mapping(MappingError::MappingFailed)) + ); + assert!(leases.is_empty()); + assert_eq!(publish(&mut leases, |_| Ok(()), || Ok((7, 3))), Ok(3)); + assert_eq!(leases, [7]); + } +} diff --git a/crates/stela-drivers/src/gpu/nvidia/page_geometry.rs b/crates/stela-drivers/src/gpu/nvidia/page_geometry.rs new file mode 100644 index 0000000000..2767ad99f0 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/page_geometry.rs @@ -0,0 +1,132 @@ +//! Original RM global page facts from an actual canonical RAM provider. +//! This publishes metadata only, never RAM, cache policy or RM readiness. +use crate::bus::dma::memory::{MemoryError, PageGeometry, PageSource}; +use core::sync::atomic::{AtomicU32, Ordering}; + +const EMPTY: u32 = 0; +const INSTALLING: u32 = 1; +const READY: u32 = 2; +const BASE_SHIFT_FIELD: u32 = 8; +const MAX_SHIFT_FIELD: u32 = 16; +static PROFILE: AtomicU32 = AtomicU32::new(EMPTY); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Source(MemoryError), + InvalidGeometry, + UnsupportedGeometry, + Unbound, + Busy, + Conflict, + Native(u32), +} + +unsafe extern "C" { + fn stela_nvidia_set_page_geometry(base: u64, max: u64, mask: u64, shift: u8) -> u32; +} + +fn encoded(geometry: PageGeometry) -> u32 { + READY + | u32::from(geometry.base_shift()) << BASE_SHIFT_FIELD + | u32::from(geometry.max_shift()) << MAX_SHIFT_FIELD +} + +fn decode(value: u32) -> Result { + match value { + EMPTY => Err(Error::Unbound), + INSTALLING => Err(Error::Busy), + _ => PageGeometry::contiguous( + (value >> BASE_SHIFT_FIELD) as u8, + (value >> MAX_SHIFT_FIELD) as u8, + ) + .map_err(|_| Error::InvalidGeometry), + } +} + +fn values(geometry: PageGeometry) -> Result<(u64, u64, u64, u8), Error> { + // The current native allocation hook accepts only the configured base + // granule. Never publish a broader original allocation capability mask. + if geometry.max_shift() != geometry.base_shift() { + return Err(Error::UnsupportedGeometry); + } + let base = u64::try_from(geometry.base_bytes()).map_err(|_| Error::InvalidGeometry)?; + let max = u64::try_from(geometry.max_bytes()).map_err(|_| Error::InvalidGeometry)?; + // The original supported-mask accessor doubles max before subtracting1. + // Keep that arithmetic representable as well as the canonical usize extent. + max.checked_mul(2).ok_or(Error::InvalidGeometry)?; + let low = base.checked_sub(1).ok_or(Error::InvalidGeometry)?; + Ok((base, max, !low, geometry.base_shift())) +} + +fn install_with( + state: &AtomicU32, + source: &dyn PageSource, + publish: impl FnOnce(PageGeometry, (u64, u64, u64, u8)) -> Result<(), u32>, +) -> Result { + let geometry = source.page_geometry().map_err(Error::Source)?; + let native_values = values(geometry)?; + let expected = encoded(geometry); + match state.compare_exchange(EMPTY, INSTALLING, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => {} + Err(INSTALLING) => return Err(Error::Busy), + Err(value) if value == expected => return Ok(geometry), + Err(_) => return Err(Error::Conflict), + } + if let Err(status) = publish(geometry, native_values) { + state.store(EMPTY, Ordering::Release); + return Err(Error::Native(status)); + } + state.store(expected, Ordering::Release); + Ok(geometry) +} + +/// Query the original global ABI's successfully published immutable profile. +/// This is metadata, not permission to activate RM or access a device. +pub fn installed() -> Result { + decode(PROFILE.load(Ordering::Acquire)) +} + +/// Publish once before any original RM/native page-fact consumer runs. Matching +/// repeats query the actual source but do not write the C data again. Unknown +/// providers, concurrent installation and conflicting profiles explicitly fail. +/// Multi-granule profiles are unsupported by the current native page producer +/// and fail before publication; the actual source profile is never narrowed. +/// No reset/uninstall is provided: all native callers share these original globals. +/// +/// # Safety +/// `source` must be the actual native RAM provider, with truthful immutable +/// geometry for every RM device using these facts. Exclude all original C/RM +/// callers throughout the initial installation; plain original global reads +/// must never race these writes. Keep the native profile stable for the entire +/// RM lifetime, including every allocation/mapping/retained quarantine. Calls +/// obey the provider's real process/context rules and cannot unwind or reenter +/// native RM. This does not establish a heap, physical mapping, cache policy, +/// DMA domain, IRQ context or complete RM initialization. +pub unsafe fn install(source: &dyn PageSource) -> Result { + install_with(&PROFILE, source, |_, (base, max, mask, shift)| { + // SAFETY: install's caller excludes all original readers. The single + // publisher owns this initial write; helper errors mutate no C data. + let status = unsafe { stela_nvidia_set_page_geometry(base, max, mask, shift) }; + if status == 0 { Ok(()) } else { Err(status) } + }) +} + +fn check_with( + state: &AtomicU32, + source: &dyn PageSource, + shift: u8, +) -> Result { + let geometry = source.page_geometry().map_err(Error::Source)?; + values(geometry)?; + if geometry != decode(state.load(Ordering::Acquire))? || shift != geometry.base_shift() { + return Err(Error::Conflict); + } + Ok(geometry) +} + +pub(super) fn check_source(source: &dyn PageSource, shift: u8) -> Result { + check_with(&PROFILE, source, shift) +} + +#[cfg(test)] +pub(super) mod tests; diff --git a/crates/stela-drivers/src/gpu/nvidia/page_geometry/tests.rs b/crates/stela-drivers/src/gpu/nvidia/page_geometry/tests.rs new file mode 100644 index 0000000000..3148a98496 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/page_geometry/tests.rs @@ -0,0 +1,137 @@ +use super::*; +use crate::bus::dma::memory::{CacheAttribute, PinnedPages}; +use alloc::string::ToString; +use core::cell::Cell; +extern crate std; + +struct Source(Result, Cell); +impl PageSource for Source { + fn page_geometry(&self) -> Result { + self.1.set(self.1.get() + 1); + self.0 + } + fn allocate(&self, _: usize, _: usize, _: CacheAttribute) -> Result { + panic!("geometry queries must not allocate pages"); + } +} + +/// One explicit CPU-model source profile per test process. No production +/// default is supplied, and tests cannot reset already published original data. +pub(crate) fn initialize_model(shift: u8) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let source = Source(PageGeometry::base_only(shift), Cell::new(0)); + // SAFETY: this fresh hosted test process has no original RM callers; + // only explicit RAM models use the immutable test source profile. + unsafe { install(&source).unwrap() }; + }); + assert_eq!( + installed().unwrap(), + PageGeometry::base_only(shift).unwrap() + ); +} + +/// Original 16KiB-native RAM models run unchanged in fresh processes instead of +/// changing global native geometry while other 4KiB models retain allocations. +pub(crate) fn separate_model_process(test: &str, shift: u8) -> bool { + const VARIABLE: &str = "STELA_NVIDIA_PAGE_GEOMETRY_MODEL"; + if let Ok(value) = std::env::var(VARIABLE) { + assert_eq!(value, shift.to_string()); + return false; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test, "--nocapture"]) + .env(VARIABLE, shift.to_string()) + .output() + .unwrap(); + assert!( + output.status.success() + && std::string::String::from_utf8_lossy(&output.stdout).contains("1 passed; 0 failed;"), + "{}{}", + std::string::String::from_utf8_lossy(&output.stdout), + std::string::String::from_utf8_lossy(&output.stderr) + ); + true +} + +#[test] +fn actual_queries_precede_publication_and_unknown_sources_never_install_defaults() { + let state = AtomicU32::new(EMPTY); + let unknown = Source(Err(MemoryError::Unavailable), Cell::new(0)); + assert_eq!( + install_with(&state, &unknown, |_, _| panic!("unknown provider")), + Err(Error::Source(MemoryError::Unavailable)) + ); + assert_eq!(decode(state.load(Ordering::Acquire)), Err(Error::Unbound)); + let broad = Source(PageGeometry::contiguous(12, 14), Cell::new(0)); + assert_eq!( + install_with(&state, &broad, |_, _| panic!("unsupported publisher")), + Err(Error::UnsupportedGeometry) + ); + assert_eq!(state.load(Ordering::Acquire), EMPTY); + let source = Source(PageGeometry::base_only(12), Cell::new(0)); + assert_eq!(check_with(&state, &source, 12), Err(Error::Unbound)); + assert_eq!( + install_with(&state, &source, |_, native| { + assert_eq!(native, (4096, 4096, !4095, 12)); + assert_eq!(decode(state.load(Ordering::Acquire)), Err(Error::Busy)); + assert_eq!( + install_with(&state, &source, |_, _| panic!("reentrant publisher")), + Err(Error::Busy) + ); + Ok(()) + }), + PageGeometry::base_only(12).map_err(Error::Source) + ); + assert_eq!(source.1.get(), 3); + assert_eq!(check_with(&state, &source, 14), Err(Error::Conflict)); + assert_eq!(check_with(&state, &source, 12).unwrap(), source.0.unwrap()); + assert_eq!( + install_with(&state, &source, |_, _| panic!("duplicate publication")), + PageGeometry::base_only(12).map_err(Error::Source) + ); + assert_eq!( + install_with(&state, &unknown, |_, _| panic!("unknown repeat")), + Err(Error::Source(MemoryError::Unavailable)) + ); + let conflict = Source(PageGeometry::contiguous(12, 14), Cell::new(0)); + assert_eq!( + install_with(&state, &conflict, |_, _| panic!("conflicting publisher")), + Err(Error::UnsupportedGeometry) + ); + assert_eq!( + check_with(&state, &conflict, 12), + Err(Error::UnsupportedGeometry) + ); + assert_eq!( + decode(state.load(Ordering::Acquire)).unwrap(), + source.0.unwrap() + ); +} + +#[test] +fn failed_native_publication_is_retryable_and_range_values_preserve_original_mask_arithmetic() { + let state = AtomicU32::new(EMPTY); + let source = Source(PageGeometry::base_only(14), Cell::new(0)); + assert_eq!( + install_with(&state, &source, |_, _| Err(0x40)), + Err(Error::Native(0x40)) + ); + assert_eq!(state.load(Ordering::Acquire), EMPTY); + assert_eq!( + install_with(&state, &source, |geometry, (base, max, mask, shift)| { + assert_eq!((base, max, mask, shift), (16384, 16384, !16383, 14)); + let supported = ((max << 1) - 1) & !(base - 1); + for candidate in 0..64 { + assert_eq!( + supported & (1u64 << candidate) != 0, + geometry.supports(candidate) + ); + } + Ok(()) + }), + source.0.map_err(Error::Source) + ); + let largest = PageGeometry::base_only((usize::BITS - 2) as u8).unwrap(); + assert!(values(largest).unwrap().1.checked_mul(2).is_some()); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/services.rs b/crates/stela-drivers/src/gpu/nvidia/services.rs index 198cfc7d04..6c919b8ba9 100644 --- a/crates/stela-drivers/src/gpu/nvidia/services.rs +++ b/crates/stela-drivers/src/gpu/nvidia/services.rs @@ -3,11 +3,11 @@ //! No global registry, fallback allocator, IRQ-context predicate or DMA identity //! conversion is introduced. RM activation still requires its remaining native //! services, including its original interrupt-allocation/context contract. -use super::{allocation::Allocation, memory}; +use super::{allocation::Allocation, firmware::FirmwareBinding, memory, page_geometry}; use crate::bus::{ dma::{ mapping::DmaDomain, - memory::{CacheAttribute, MemoryError, PageSource}, + memory::{CacheAttribute, MemoryError, PageGeometry, PageSource}, }, pci::Address, }; @@ -32,6 +32,7 @@ pub enum ServiceError { InvalidConfiguration, AlreadyBound, Native(u32), + PageGeometry(page_geometry::Error), } /// Retained allocation provenance. DMA uses this actual attached domain and @@ -51,8 +52,9 @@ pub(super) struct Origin { /// process/deferred context. This handle is neither Send nor Sync. /// /// Keep the source, state and handle alive through all native callers and all -/// producer allocations/published DMA tokens. Unbind refuses until every such -/// allocation is freed and every DMA token is retired or quarantined. Therefore +/// producer allocations/published DMA tokens and firmware tokens. Unbind refuses +/// until every allocation is freed, every DMA token is retired or quarantined, +/// and every firmware token is returned. Therefore /// no map-capable old handle can legitimately survive a rebind/address reuse. /// CPU-only views and consumed quarantine independently retain actual pins/domain /// and may survive. Final releases still obey backing/domain/heap context rules. @@ -61,10 +63,13 @@ pub struct MemoryServices<'a> { domain: Arc, requester: Address, page_shift: u8, + geometry: PageGeometry, address_limit: u64, state: *mut c_void, allocations: Cell, mappings: Cell, + pub(super) firmware: Option>, + pub(super) firmware_tokens: Cell, _owner: PhantomData<*mut ()>, _pin: PhantomPinned, } @@ -87,6 +92,8 @@ impl<'a> MemoryServices<'a> { /// `requester`, with `address_limit` from that device's actual DMA policy. /// `page_shift` is the real native granule, matching the backend's global /// os_page_shift facts before RM runs; it is never a guest granule. The + /// actual source must attest the exact installed PageGeometry; an unknown + /// source, conflicting maximum or non-base configured shift is refused. The /// provider must establish the requested CPU cache policy or refuse it, /// without introducing incompatible aliases. pub unsafe fn new( @@ -103,20 +110,32 @@ impl<'a> MemoryServices<'a> { { return Err(ServiceError::InvalidConfiguration); } + let geometry = + page_geometry::check_source(source, page_shift).map_err(ServiceError::PageGeometry)?; Ok(Self { source, domain, requester, page_shift, + geometry, address_limit, state: ptr::null_mut(), allocations: Cell::new(0), mappings: Cell::new(0), + firmware: None, + firmware_tokens: Cell::new(0), _owner: PhantomData, _pin: PhantomPinned, }) } + /// Attach an immutable firmware provider before pinning/binding. Its actual + /// device-family attestation shares this service's requester/reset epoch. + pub fn with_firmware(mut self, firmware: FirmwareBinding<'a>) -> Self { + self.firmware = Some(firmware); + self + } + /// Bind an initialized native nv_state_t's empty OS/DMA slots. C checks /// its actual PCI identity against the retained requester. This neither /// enables hardware nor creates a channel, IRQ route or GPU VA mapping. @@ -154,7 +173,8 @@ impl<'a> MemoryServices<'a> { /// # Safety /// Hardware is quiescent, all native allocation/mapping/IRQ workers are /// stopped and drained, all producer handles freed, every published DMA - /// token retired or consumed into canonical quarantine, and no new native + /// token retired or consumed into canonical quarantine, all firmware tokens + /// returned after their CPU readers stop, and no new native /// call can start. Keep this pinned service/state live until this succeeds; /// dropping/reusing them while resources remain violates the bind contract. /// CPU-only views and consumed quarantine may remain. The real domain @@ -167,7 +187,10 @@ impl<'a> MemoryServices<'a> { if this.state.is_null() { return Err(ServiceError::Native(Status::InvalidState as u32)); } - if this.allocations.get() != 0 || this.mappings.get() != 0 { + if this.allocations.get() != 0 + || this.mappings.get() != 0 + || this.firmware_tokens.get() != 0 + { return Err(ServiceError::Native(Status::InvalidState as u32)); } // SAFETY: the owner excludes callers; C compares exact installed slots. @@ -263,6 +286,7 @@ unsafe fn allocate_pages( if pages.logical_bytes() != bytes || pages.bytes() != bytes || pages.page_shift() != services.page_shift + || !services.geometry.supports(pages.page_shift()) || pages.cache_attribute() != attribute { return Err(Status::OperatingSystem); diff --git a/crates/stela-drivers/src/gpu/nvidia/services/tests.rs b/crates/stela-drivers/src/gpu/nvidia/services/tests.rs index 551243ce61..1cc68a8ea3 100644 --- a/crates/stela-drivers/src/gpu/nvidia/services/tests.rs +++ b/crates/stela-drivers/src/gpu/nvidia/services/tests.rs @@ -136,6 +136,7 @@ impl Drop for Backing { struct Source { shift: Cell, + geometry: PageGeometry, base: Cell, stride: Cell, cache_override: Cell>, @@ -145,8 +146,10 @@ struct Source { } impl Source { fn new(shift: u8) -> Self { + page_geometry::tests::initialize_model(shift); Self { shift: Cell::new(shift), + geometry: PageGeometry::base_only(shift).unwrap(), base: Cell::new(0x8000_0000), stride: Cell::new(2), cache_override: Cell::new(None), @@ -157,6 +160,9 @@ impl Source { } } impl PageSource for Source { + fn page_geometry(&self) -> Result { + Ok(self.geometry) + } fn allocate( &self, bytes: usize, @@ -522,6 +528,12 @@ fn failed_policies_and_provider_results_do_not_publish_ptes() { #[test] fn native_granule_cache_contiguity_and_force32_are_real_checks() { + if page_geometry::tests::separate_model_process( + "gpu::nvidia::services::tests::native_granule_cache_contiguity_and_force32_are_real_checks", + 14, + ) { + return; + } let source = Source::new(14); source.stride.set(1); let domain = Domain::new(); @@ -872,6 +884,12 @@ fn binding_checks_original_pci_identity_and_existing_slot_ownership() { #[test] fn native_iova_alignment_and_address_limit_fail_before_publication() { + if page_geometry::tests::separate_model_process( + "gpu::nvidia::services::tests::native_iova_alignment_and_address_limit_fail_before_publication", + 14, + ) { + return; + } for base in [0x4000_1000, 0x1_0000_0000] { let source = Source::new(14); let domain = Domain::new(); @@ -1079,3 +1097,49 @@ fn unbound_and_null_original_requests_cannot_reach_a_provider() { ); } } + +#[test] +fn source_geometry_and_configured_native_base_must_match_the_installed_profile() { + struct Unknown; + impl PageSource for Unknown { + fn allocate( + &self, + _: usize, + _: usize, + _: CacheAttribute, + ) -> Result { + panic!("unknown geometry must fail before allocation"); + } + } + let mut source = Source::new(12); + let domain = Domain::new(); + let requester = Address { + segment: 0, + bus: 0, + device: 0, + function: 0, + }; + // SAFETY: isolated CPU-model domain/requester. Each mismatched or unknown + // provider must fail before publishing any native state or allocation. + unsafe { + assert!(matches!( + MemoryServices::new(&Unknown, domain.clone(), requester, 12, u64::MAX), + Err(ServiceError::PageGeometry(page_geometry::Error::Source( + MemoryError::Unavailable + ))) + )); + assert!(matches!( + MemoryServices::new(&source, domain.clone(), requester, 14, u64::MAX), + Err(ServiceError::PageGeometry(page_geometry::Error::Conflict)) + )); + source.geometry = PageGeometry::contiguous(12, 14).unwrap(); + assert!(matches!( + MemoryServices::new(&source, domain.clone(), requester, 12, u64::MAX), + Err(ServiceError::PageGeometry( + page_geometry::Error::UnsupportedGeometry + )) + )); + } + assert_eq!(source.calls.get(), 0); + assert!(domain.events().is_empty()); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/Makefile b/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/Makefile index 83e1f18f25..bff0098024 100644 --- a/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/Makefile +++ b/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/Makefile @@ -33,6 +33,10 @@ LD_HAS_FORCE_GROUP_ALLOCATION = \ # srcs.mk, and the NVIDIA ID string ALL_SRCS = $(SRCS) $(SRCS_CXX) ALL_SRCS += $(NVIDSTRING) +ifeq ($(TARGET_OS),Stela) +ALL_SRCS += ../../stela/stela_nvkms_primitives.c +ALL_SRCS += ../../stela/stela_nvkms_memory.c +endif SRC_COMMON = ../common diff --git a/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/include/nvkms-types.h b/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/include/nvkms-types.h index f0e917d3bf..614a58f56c 100644 --- a/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/include/nvkms-types.h +++ b/crates/stela-drivers/src/gpu/nvidia/src/nvidia-modeset/include/nvkms-types.h @@ -897,13 +897,37 @@ typedef struct { NvU16 Unused; } NVEvoLutEntryRec; +/* + * The device addresses LUT slots at 256-byte offsets. Express that serialized + * layout independently of CPU alignment: nvInternalAlloc's ordinary metadata + * prefix does not promise an over-aligned CPU base. The real LUT surface has + * its own RM allocation/mapping and alignment; the temporary CPU shadow is + * copied to it by nvUploadDataToLutSurfaceEvo's dword loop. + */ +#define NV_EVO_LUT_SLOT_ALIGNMENT 0x100 +#define NV_EVO_LUT_SLOT_BYTES \ + NV_ALIGN_UP((NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES) * \ + sizeof(NVEvoLutEntryRec), NV_EVO_LUT_SLOT_ALIGNMENT) + typedef struct { - NVEvoLutEntryRec base[NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES]; - // The output LUT requires 8-bit alignment. - NVEvoLutEntryRec output[NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES] - __attribute__((aligned(0x100))); + union { + NVEvoLutEntryRec base[NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES]; + NvU8 baseSlotStorage[NV_EVO_LUT_SLOT_BYTES]; + }; + union { + NVEvoLutEntryRec output[NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES]; + NvU8 outputSlotStorage[NV_EVO_LUT_SLOT_BYTES]; + }; } NVEvoLutDataRec; +ct_assert(sizeof(NVEvoLutEntryRec) == 8); +ct_assert(offsetof(NVEvoLutDataRec, base) == 0); +ct_assert(offsetof(NVEvoLutDataRec, output) == NV_EVO_LUT_SLOT_BYTES); +ct_assert((offsetof(NVEvoLutDataRec, output) % NV_EVO_LUT_SLOT_ALIGNMENT) == 0); +ct_assert(sizeof(NVEvoLutDataRec) == 2 * NV_EVO_LUT_SLOT_BYTES); +ct_assert(NV_ALIGNOF(NVEvoLutDataRec) <= NV_ALIGNOF(NvU64)); +ct_assert((sizeof(NVEvoLutDataRec) % sizeof(NvU32)) == 0); + typedef struct { NvBool rasterLockAcrossProtocolsAllowed :1; NvBool adaptiveSyncSdpSupported :1; diff --git a/crates/stela-drivers/src/gpu/nvidia/src/nvidia/Makefile b/crates/stela-drivers/src/gpu/nvidia/src/nvidia/Makefile index 8abfc86690..8fe736df15 100644 --- a/crates/stela-drivers/src/gpu/nvidia/src/nvidia/Makefile +++ b/crates/stela-drivers/src/gpu/nvidia/src/nvidia/Makefile @@ -22,9 +22,18 @@ GET_COMPILER_TYPE = \ ALL_SRCS = $(SRCS) $(SRCS_CXX) ALL_SRCS += $(NVIDSTRING) ifeq ($(TARGET_OS),Stela) +# Stela's shared compiler_builtins owns standard memory symbols. The original +# gcc_helper aliases reverse them to os_mem_* (and narrow lengths to NvU32), +# which would recurse when the actual native OS hooks call the shared runtime. +ALL_SRCS := $(filter-out arch/nvalloc/unix/src/gcc_helper.c,$(ALL_SRCS)) ALL_SRCS += ../../stela/pci.c ../../stela/memory.c ../../stela/stela_ram_mapping.c -ALL_SRCS += ../../stela/stela_pages.c -CFLAGS += -I ../../stela +ALL_SRCS += ../../stela/stela_pages.c ../../stela/stela_page_geometry.c +ALL_SRCS += ../../stela/stela_ordering.c +ALL_SRCS += ../../stela/stela_mmio.c ../../stela/stela_firmware.c +ALL_SRCS += ../../stela/stela_primitives.c ../../stela/stela_nvlink_primitives.c +ALL_SRCS += ../../stela/stela_nvswitch_primitives.c +ALL_SRCS += ../../stela/stela_nvlink_memory.c +CFLAGS += -I ../../stela -I $(OUTPUTDIR) endif SRC_COMMON = ../common diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/firmware.h b/crates/stela-drivers/src/gpu/nvidia/stela/firmware.h new file mode 100644 index 0000000000..d1bd7b9264 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/firmware.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_NVIDIA_FIRMWARE_H +#define STELA_NVIDIA_FIRMWARE_H + +#include "services.h" + +/* Native same-CPU ABI, borrowing immutable canonical catalog bytes. The pinned + * MemoryServices owner supplies the actual device's observed architecture and + * implementation before binding. All calls/releases are serialized, nonreentrant + * process/deferred operations with a live global heap, never ISR callbacks. + * Every non-NULL token is returned once after CPU readers stop. The catalog, + * provider, state and service remain alive until all tokens are put and unbind + * succeeds. NULL put is valid. Failure preserves both caller output slots. + * Bytes are CPU-only: not physical/IOVA addresses, pinned DMA storage or GPU VA. + * Catalog manifest integrity does not authenticate NVIDIA firmware. Original RM + * version/ELF/signature validation, upload and device initialization still apply. + */ +NvU32 stela_nvidia_firmware_family(NvU32 architecture, NvU32 implementation); +NvU64 stela_nvidia_firmware_alignment(void); +const char *stela_nvidia_firmware_version(void); +const void *stela_nvidia_get_firmware(void *services, void *state, NvU32 family, + const char *name, const char *hardware, + const char *revision, const void **buffer, + NvU32 *bytes); +void stela_nvidia_put_firmware(const void *token); + +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.c b/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.c new file mode 100644 index 0000000000..4d8962cbb4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.c @@ -0,0 +1,336 @@ +/* SPDX-License-Identifier: MIT */ +#include "air_compile.h" +#include "nouveau/compiler/nak_private.h" +#include "util/ralloc.h" +#include +#include +#include + +#define MAX_TEXT 4096u +#define MAX_CODE (64u * 1024u * 1024u) +#define CBUF_COUNT 8u +#define CBUF_BYTES 65536u +/* Existing NVK/native compute limits, also checked by nvidia_compute.c. */ +#define MAX_LOCAL_XY 1024u +#define MAX_LOCAL_Z 64u +#define MAX_THREADS 1024u + +struct stela_nv_air_compilation { + struct stela_nv_air_provenance provenance; + nir_shader_compiler_options nir_options; + nir_shader *shader; + struct nak_shader_bin *bin; + struct stela_nv_air_binding bindings[AIR_MAX_ARGUMENTS]; + uint32_t binding_count, table_bytes; + void *metadata; + bool type_reference; +}; +static enum stela_nv_air_status report(struct stela_nv_air_error *error, + enum stela_nv_air_status status, const char *detail) +{ + if (error) { + error->status = status; + snprintf(error->detail, sizeof(error->detail), "%s", detail); + } + return status; +} +void stela_nv_air_destroy(struct stela_nv_air_compilation **slot) +{ + if (!slot || !*slot) return; + struct stela_nv_air_compilation *owner = *slot; *slot = NULL; + if (owner->bin) nak_shader_bin_destroy(owner->bin); + ralloc_free(owner->shader); + if (owner->type_reference) glsl_type_singleton_decref(); + free(owner->metadata); free(owner); +} +static bool text_valid(const char *text, size_t bytes) +{ + return bytes <= MAX_TEXT && (!bytes || (text && !memchr(text, 0, bytes))); +} +static char *copy_text(char **cursor, const void *text, size_t bytes) +{ + if (!text) return NULL; + char *result = *cursor; + memcpy(result, text, bytes); result[bytes] = 0; *cursor += bytes + 1; return result; +} +static enum stela_nv_air_status copy_provenance(struct stela_nv_air_compilation *owner, + const struct stela_metal_library_manifest *manifest, + const struct stela_metal_function_record *record, unsigned selected, + struct stela_nv_air_error *error) +{ + if (!text_valid((const char *)record->name, record->name_bytes) || !record->name_bytes || + !text_valid((const char *)manifest->target, manifest->target_bytes) || !manifest->target_bytes || + record->argument_count > AIR_MAX_ARGUMENTS || (record->argument_count && !record->arguments)) + return report(error, STELA_NV_AIR_INVALID, "Unrepresentable selected entry metadata"); + size_t bytes = record->argument_count * sizeof(struct stela_air_argument_info) + + (size_t)record->name_bytes + (size_t)manifest->target_bytes + 2; + for (unsigned i = 0; i < record->argument_count; i++) { + const struct stela_air_argument_info *arg = &record->arguments[i]; + if (!text_valid(arg->name, arg->name_bytes) || !text_valid(arg->type_name, arg->type_name_bytes)) + return report(error, STELA_NV_AIR_INVALID, "Unrepresentable argument strings"); + bytes += arg->name_bytes + arg->type_name_bytes + 2; + } + /* Bounded before allocation by128 arguments and4096 bytes/string. */ + owner->metadata = malloc(bytes); + if (!owner->metadata) return report(error, STELA_NV_AIR_ALLOCATION, "Selected metadata allocation failed"); + struct stela_air_argument_info *args = owner->metadata; + char *cursor = (char *)(args + record->argument_count); + struct stela_nv_air_provenance *p = &owner->provenance; + p->input = manifest->input; p->entry = record->entry; p->selected_entry = selected; + p->entry_flags = record->flags; p->library_flags = manifest->flags; p->compiler_profile = manifest->compiler_profile; + p->request_language = manifest->request_language; p->request_fast_math = manifest->request_fast_math; + p->build = manifest->build; p->air_offset = record->air_offset; p->air_bytes = record->air_bytes; + memcpy(p->air_sha256, record->air_sha256, 32); memcpy(p->source_sha256, manifest->source_sha256, 32); + p->name = copy_text(&cursor, record->name, (size_t)record->name_bytes); + p->target = copy_text(&cursor, manifest->target, (size_t)manifest->target_bytes); + p->argument_count = record->argument_count; p->arguments = args; + for (unsigned i = 0; i < record->argument_count; i++) { + args[i] = record->arguments[i]; + args[i].name = copy_text(&cursor, args[i].name, args[i].name_bytes); + args[i].type_name = copy_text(&cursor, args[i].type_name, args[i].type_name_bytes); + } + return STELA_NV_AIR_OK; +} +static bool same_buffer(const struct stela_air_buffer *a, const struct stela_air_buffer *b) +{ + return a->argument == b->argument && a->index == b->index && a->address_space == b->address_space && + a->access == b->access && a->type_size == b->type_size && a->type_alignment == b->type_alignment; +} +static enum stela_nv_air_status prepare_bindings(struct stela_nv_air_compilation *owner, + struct stela_nv_air_error *error) +{ + for (unsigned i = 0; i < owner->provenance.argument_count; i++) { + const struct stela_air_argument_info *arg = &owner->provenance.arguments[i]; + if (arg->kind == 2) continue; + if (arg->kind == 1 && arg->buffer.address_space == 3 && arg->plain_buffer_type) continue; + if (arg->kind != 1 || arg->buffer.address_space != 1 || !arg->plain_buffer_type) + return report(error, STELA_NV_AIR_UNSUPPORTED, "Resource requires an unsupported binding specialization"); + if (!arg->used) continue; + unsigned offset = owner->binding_count * STELA_NV_AIR_ROW_BYTES; + if (owner->binding_count >= AIR_MAX_ARGUMENTS || offset > UINT16_MAX - STELA_NV_AIR_ROW_BYTES + 1) + return report(error, STELA_NV_AIR_LIMIT, "Argument table exceeds original cbuf offset representation"); + owner->bindings[owner->binding_count++] = (struct stela_nv_air_binding) { + .buffer = arg->buffer, .cbuf_offset = offset, + }; + } + unsigned bytes = owner->binding_count * STELA_NV_AIR_ROW_BYTES; + owner->table_bytes = (bytes + STELA_NV_AIR_CBUF_ALIGNMENT - 1) & ~(STELA_NV_AIR_CBUF_ALIGNMENT - 1); + if (owner->table_bytes > CBUF_BYTES) + return report(error, STELA_NV_AIR_LIMIT, "Argument table exceeds QMD constant-buffer extent"); + return STELA_NV_AIR_OK; +} +static nir_def *bind_buffer(nir_builder *b, const struct stela_air_buffer *buffer, void *data) +{ + const struct stela_nv_air_compilation *owner = data; + for (unsigned i = 0; i < owner->binding_count; i++) { + const struct stela_nv_air_binding *binding = &owner->bindings[i]; + if (same_buffer(&binding->buffer, buffer)) + return nir_ldc_nv(b, 1, 64, nir_imm_int(b, (int)owner->provenance.options.argument_cbuf), + nir_imm_int(b, 0), .base = binding->cbuf_offset, .align_mul = 8, .align_offset = 0); + } + /* LLVM proves there are no uses of this original parameter. No resource + * is fabricated for a dead argument; ordinary NIR DCE removes its undef. */ + for (unsigned i = 0; i < owner->provenance.argument_count; i++) { + const struct stela_air_argument_info *arg = &owner->provenance.arguments[i]; + if (arg->kind == 1 && !arg->used && same_buffer(&arg->buffer, buffer)) return nir_undef(b, 1, 64); + } + return NULL; +} +static bool device_valid(const struct nv_device_info *device) +{ + if (device->sm < 20 || !device->max_warps_per_mp || device->max_warps_per_mp > 64 || + !device->max_smem_per_wg_kB || !device->sm_smem_size_count || + device->sm_smem_size_count > ARRAY_SIZE(device->sm_smem_sizes_kB)) return false; + for (unsigned i = 0; i < device->sm_smem_size_count; i++) { + unsigned size = device->sm_smem_sizes_kB[i]; + if (size % 4 || (i && size <= device->sm_smem_sizes_kB[i - 1])) return false; + } + return device->max_smem_per_wg_kB <= device->sm_smem_sizes_kB[device->sm_smem_size_count - 1]; +} +static bool bind_threadgroup(const struct stela_air_buffer *buffer, + struct stela_air_threadgroup_view *view, void *data) +{ + const struct stela_nv_air_compilation *owner = data; + const struct stela_metal_threadgroup_specialization *shared = &owner->provenance.threadgroup; + for (unsigned i = 0; i < shared->count; i++) { + const struct stela_metal_threadgroup_binding *binding = &shared->bindings[i]; + const struct stela_air_buffer *b = &binding->buffer; + if (b->argument == buffer->argument && b->index == buffer->index && + b->address_space == buffer->address_space && b->access == buffer->access && + b->type_size == buffer->type_size && b->type_alignment == buffer->type_alignment) { + *view = (struct stela_air_threadgroup_view){.size = binding->bytes, + .alignment = binding->alignment, .available_access = STELA_AIR_READ_WRITE}; + return true; + } + } + return false; +} +enum stela_nv_air_status stela_nv_air_compile(const struct nv_device_info *device, + const struct nak_compiler *compiler, const struct stela_metal_assembly *library, + uint32_t selected, const struct stela_nv_air_options *options, + struct stela_nv_air_compilation **output, struct stela_nv_air_error *error) +{ + return stela_nv_air_compile_specialized(device, compiler, library, selected, options, NULL, output, error); +} +enum stela_nv_air_status stela_nv_air_compile_specialized(const struct nv_device_info *device, + const struct nak_compiler *compiler, const struct stela_metal_assembly *library, + uint32_t selected, const struct stela_nv_air_options *options, + const struct stela_metal_threadgroup_request *request, + struct stela_nv_air_compilation **output, struct stela_nv_air_error *error) +{ + if (error) memset(error, 0, sizeof(*error)); + if (!device || !compiler || !library || !options || !output || *output || + options->size != sizeof(*options) || options->abi != STELA_NV_AIR_ABI) + return report(error, STELA_NV_AIR_INVALID, "Invalid local compiler ownership/ABI"); + if (!options->max_instructions || !options->max_code_bytes || options->max_code_bytes > MAX_CODE) + return report(error, STELA_NV_AIR_LIMIT, "Explicit bounded instruction/code budgets required"); + if (options->argument_cbuf >= CBUF_COUNT || options->record_assembly > 1 || + (options->fp_profile != STELA_AIR_FP_IEEE_DEFAULT && + options->fp_profile != STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41)) + return report(error, STELA_NV_AIR_UNSUPPORTED, "Unsupported cbuf/diagnostic/FP policy"); + if (!device_valid(device) || compiler->sm != device->sm || compiler->warps_per_sm != device->max_warps_per_mp) + return report(error, STELA_NV_AIR_DEVICE, "Actual matching initialized NAK/device facts required"); + uint64_t threads = 1; + for (unsigned axis = 0; axis < 3; axis++) { + unsigned count = options->workgroup_size[axis]; + if (!count || count > (axis == 2 ? MAX_LOCAL_Z : MAX_LOCAL_XY) || threads > MAX_THREADS / count) + return report(error, STELA_NV_AIR_UNSUPPORTED, "Invalid/unsupported workgroup specialization"); + threads *= count; + } + const struct stela_metal_library_manifest *manifest = stela_metal_assembly_manifest(library); + if (!manifest || manifest->size != sizeof(*manifest) || manifest->abi != STELA_METAL_LIBRARY_ABI || + selected >= manifest->entry_count) return report(error, STELA_NV_AIR_INVALID, "Invalid selected canonical entry"); + const struct stela_metal_function_record *record = &manifest->entries[selected]; + if (record->size != sizeof(*record) || record->abi != STELA_METAL_LIBRARY_ABI || + !(record->flags & STELA_METAL_ENTRY_NO_CONSTANTS)) + return report(error, STELA_NV_AIR_UNSUPPORTED, "Unsupported entry ABI/function constants"); + struct stela_metal_input_view original = {.size = sizeof(original), .abi = STELA_METAL_INPUT_ABI}; + if (stela_metal_assembly_original(library, &original, NULL) != STELA_METAL_ASSEMBLY_OK || + record->air_offset > original.length || record->air_bytes > original.length - record->air_offset || + !record->air_bytes || record->air_bytes > AIR_MAX_BITCODE_BYTES) + return report(error, STELA_NV_AIR_INVALID, "Invalid retained raw AIR span"); + struct stela_metal_threadgroup_specialization threadgroup; + enum stela_metal_threadgroup_status shared_status = stela_metal_threadgroup_normalize( + record->arguments, record->argument_count, request, MIN2((unsigned)device->max_smem_per_wg_kB * 1024, UINT16_MAX), &threadgroup); + if (shared_status != STELA_METAL_THREADGROUP_OK) + return report(error, shared_status == STELA_METAL_THREADGROUP_INVALID ? STELA_NV_AIR_INVALID : + shared_status == STELA_METAL_THREADGROUP_LIMIT ? STELA_NV_AIR_LIMIT : STELA_NV_AIR_UNSUPPORTED, + "Resource requires a supported threadgroup binding specialization"); + struct stela_nv_air_compilation *owner = calloc(1, sizeof(*owner)); + if (!owner) return report(error, STELA_NV_AIR_ALLOCATION, "Compilation owner allocation failed"); + owner->provenance.options = *options; owner->provenance.threadgroup = threadgroup; owner->provenance.device = *device; + owner->provenance.base_layout = compiler->const_offsets_base; + owner->provenance.graphics_layout = compiler->const_offsets_turing_graphics; + owner->nir_options = *nak_nir_options(compiler); + enum stela_nv_air_status status = copy_provenance(owner, manifest, record, selected, error); + if (!status) status = prepare_bindings(owner, error); + if (status) { stela_nv_air_destroy(&owner); return status; } + glsl_type_singleton_init_or_ref(); owner->type_reference = true; + struct stela_air_options air = { + .workgroup_size = {options->workgroup_size[0], options->workgroup_size[1], options->workgroup_size[2]}, + .max_instructions = options->max_instructions, .bind_buffer = bind_buffer, .binding_data = owner, + .fp_profile = options->fp_profile, + /* Original nak_shader_info.cs.smem_size is u16. Never allow an + * unrepresentable size to reach the original Rust narrowing. */ + .bind_threadgroup = threadgroup.count ? bind_threadgroup : NULL, + .max_threadgroup_bytes = MIN2((unsigned)device->max_smem_per_wg_kB * 1024, UINT16_MAX), + }; + struct stela_air_error air_error; + owner->shader = stela_air_to_nir(original.bytes + record->air_offset, (size_t)record->air_bytes, + owner->provenance.name, &owner->nir_options, &air, &air_error); + if (!owner->shader) { + if (error) error->air = air_error; + stela_nv_air_destroy(&owner); + return report(error, STELA_NV_AIR_FRONTEND, "Shared AIR frontend refused selected body/policy"); + } + nir_validate_shader(owner->shader, "owned AIR argument-table ABI"); + nak_preprocess_nir(owner->shader, compiler); + /* The original compile function owns its single postprocessing pass. */ + owner->bin = nak_compile_shader(owner->shader, options->record_assembly != 0, compiler, 0, NULL, false); + owner->provenance.nak_debug_flags = nak_debug_flags(compiler); + if (!owner->bin || !owner->bin->code || !owner->bin->code_size || + owner->bin->info.stage != MESA_SHADER_COMPUTE || owner->bin->info.sm != device->sm || + owner->bin->info.cs.smem_size != owner->shader->info.shared_size) { + stela_nv_air_destroy(&owner); + return report(error, STELA_NV_AIR_BACKEND, "Original NAK output unavailable/inconsistent"); + } + if (owner->bin->code_size > options->max_code_bytes) { + stela_nv_air_destroy(&owner); + return report(error, STELA_NV_AIR_LIMIT, "Compiled code exceeds caller budget"); + } + for (unsigned axis = 0; axis < 3; axis++) { + if (owner->bin->info.cs.local_size[axis] != options->workgroup_size[axis]) { + stela_nv_air_destroy(&owner); + return report(error, STELA_NV_AIR_BACKEND, "NAK workgroup specialization differs"); + } + } + *output = owner; return report(error, STELA_NV_AIR_OK, ""); +} + +static bool within_vm(uint64_t address, uint64_t bytes, unsigned bits) +{ + if (!address || !bytes || !bits || bits > 63) return false; + uint64_t last = (UINT64_C(1) << bits) - 1; + return address <= last && bytes - 1 <= last - address; +} +enum stela_nv_air_status stela_nv_air_pack_arguments(const struct stela_nv_air_compilation *owner, + const struct nv_device_info *device, unsigned va_bits, const struct stela_nv_air_buffer_view *views, + uint32_t count, void *output, size_t bytes) +{ + if (!owner || !device || !device_valid(device) || !va_bits || va_bits > 63) + return STELA_NV_AIR_INVALID; + const struct nv_device_info *compiled = &owner->provenance.device; + if (device->sm != compiled->sm || device->max_warps_per_mp != compiled->max_warps_per_mp || + device->cls_compute != compiled->cls_compute) return STELA_NV_AIR_DEVICE; + if (count != owner->binding_count || (count && (!views || !output)) || bytes < owner->table_bytes) + return STELA_NV_AIR_BINDING; + uint64_t addresses[AIR_MAX_ARGUMENTS]; + bool seen[AIR_MAX_ARGUMENTS] = {false}; + for (unsigned i = 0; i < count; i++) { + const struct stela_nv_air_buffer_view *view = &views[i]; + unsigned slot; + for (slot = 0; slot < owner->binding_count; slot++) { + const struct stela_air_buffer *buffer = &owner->bindings[slot].buffer; + if (view->index == buffer->index && view->argument == buffer->argument) break; + } + if (slot == owner->binding_count || seen[slot]) return STELA_NV_AIR_BINDING; + seen[slot] = true; + const struct stela_air_buffer *buffer = &owner->bindings[slot].buffer; + if (view->device != device || !view->owner || !view->bytes || + (view->available_access & ~(uint32_t)STELA_AIR_READ_WRITE) || + (view->available_access & (unsigned)buffer->access) != (unsigned)buffer->access || + view->offset > view->allocation_bytes || view->bytes > view->allocation_bytes - view->offset || + !within_vm(view->allocation_va, view->allocation_bytes, va_bits) || + view->offset > UINT64_MAX - view->allocation_va || view->bytes < buffer->type_size || + !buffer->type_alignment || (view->allocation_va + view->offset) % buffer->type_alignment) + return STELA_NV_AIR_BINDING; + addresses[slot] = view->allocation_va + view->offset; + } + /* Every check precedes writes. Slots/count form a bijection; only this + * dedicated table image (including initialized alignment padding) changes. */ + if (owner->table_bytes) memset(output, 0, owner->table_bytes); + for (unsigned i = 0; i < count; i++) { + uint8_t *row = (uint8_t *)output + owner->bindings[i].cbuf_offset; + for (unsigned byte = 0; byte < STELA_NV_AIR_ROW_BYTES; byte++) row[byte] = (uint8_t)(addresses[i] >> (8 * byte)); + } + return STELA_NV_AIR_OK; +} +const struct nak_shader_bin *stela_nv_air_binary(const struct stela_nv_air_compilation *owner) +{ + return owner ? owner->bin : NULL; +} +const nir_shader *stela_nv_air_nir(const struct stela_nv_air_compilation *owner) +{ + return owner ? owner->shader : NULL; +} +const struct stela_nv_air_provenance *stela_nv_air_provenance(const struct stela_nv_air_compilation *owner) +{ + return owner ? &owner->provenance : NULL; +} +const struct stela_nv_air_binding *stela_nv_air_bindings(const struct stela_nv_air_compilation *owner, + uint32_t *count, uint32_t *table_bytes) +{ + if (count) *count = owner ? owner->binding_count : 0; + if (table_bytes) *table_bytes = owner ? owner->table_bytes : 0; + return owner ? owner->bindings : NULL; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.h b/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.h new file mode 100644 index 0000000000..6405742e3c --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/hosted/air_compile.h @@ -0,0 +1,140 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_NVIDIA_AIR_COMPILE_H +#define STELA_NVIDIA_AIR_COMPILE_H +#include "../../../metal/compiler/library_assembly.h" +#include "stela/air_to_nir.h" +#include "../../../metal/compiler/threadgroup.h" +#include "stela/nvidia_compute.h" +#ifdef __cplusplus +extern "C" { +#endif + +#define STELA_NV_AIR_ABI 1u +#define STELA_NV_AIR_ROW_BYTES 8u +#define STELA_NV_AIR_CBUF_ALIGNMENT 64u + +enum stela_nv_air_status { + STELA_NV_AIR_OK, + STELA_NV_AIR_INVALID, + STELA_NV_AIR_UNSUPPORTED, + STELA_NV_AIR_DEVICE, + STELA_NV_AIR_LIMIT, + STELA_NV_AIR_ALLOCATION, + STELA_NV_AIR_FRONTEND, + STELA_NV_AIR_BACKEND, + STELA_NV_AIR_BINDING, +}; +struct stela_nv_air_options { + uint32_t size, abi, workgroup_size[3], max_instructions, max_code_bytes; + uint32_t argument_cbuf, record_assembly; + enum stela_air_fp_profile fp_profile; +}; +struct stela_nv_air_error { + enum stela_nv_air_status status; + struct stela_air_error air; + char detail[256]; +}; +struct stela_nv_air_binding { + /* Only original LLVM-used AS1 parameters require rows; every parameter's + * complete reflection still appears in provenance.arguments. */ + struct stela_air_buffer buffer; + uint32_t cbuf_offset; +}; +/* Immutable same-process views, never pointer IPC or a cache wire format. + * Source/compiler provenance remains absent for an archive unless independently + * established by its real input owner; selecting an FP policy authenticates + * nothing. The nondefault FP profile needs air_to_nir.h's independent build + * qualification. The actual NAK options, layouts, device facts and debug flags + * join source/workgroup/profile/bindings in the compiled specialization key. */ +struct stela_nv_air_provenance { + struct stela_metal_input_info input; + struct stela_metal_input_entry entry; + uint32_t selected_entry, entry_flags, library_flags, compiler_profile; + uint32_t request_language, request_fast_math, argument_count; + uint64_t air_offset, air_bytes; + uint8_t air_sha256[32], source_sha256[32]; + struct stela_msl_build_identity build; + const char *name, *target; + const struct stela_air_argument_info *arguments; + struct stela_nv_air_options options; + struct nv_device_info device; + struct nak_constant_offset_info base_layout, graphics_layout; + uint64_t nak_debug_flags; + struct stela_metal_threadgroup_specialization threadgroup; +}; +struct stela_nv_air_compilation; + +/* Hosted same-CPU compiler only. Device and compiler MUST be the matching real + * initialized context from the retained Mesa build, not test topology or an + * Apple CPU profile. We use the original nak_compiler declaration to check SM + * and warp consistency; no C++/Rust object ABI is reconstructed. All inputs are + * borrowed through this call only. Success retains no assembly/compiler/device + * pointers. NIR/options/GLSL types and the original nak_shader_bin have owned + * lifetimes. Failure preserves the empty sole-owning output slot. + * + * This first-party compute ABI dedicates one selected QMD cbuf slot (0..7) to + * eight-byte LE GPU addresses in metadata argument order, with an explicit + * Metal-index/LLVM-ordinal map. The complete extent is rounded to64B, <=64KiB. + * The dispatch owner reserves that slot for this table, uploads/publishes it + * and retains every resource through actual completion. No VA is in shader + * code. No other cbuf reads/printf/images/samplers are admitted in this subset; + * expanding it requires an explicit compatible layout contract. + * + * Dynamic AS3 requires compile_specialized with exact requested byte lengths. Static shared + * lowering is retained if admitted by the canonical owner. Scratch/stack/barrier + * requirements are real compiler facts and may outlive current plan support. + * No GPU allocation, initialization, upload, submission or Metal PSO is created. + * Wrapper allocation failures are typed. Original LLVM/Mesa/Rust fatal/OOM and + * cancellation remain the normal compiler process owner's responsibility. */ +/* Exact dispatch-size specialization; existing compile() delegates with NULL. + * Request arrays are borrowed only during the call and copied into provenance. + * Backend shared totals include these rows plus static layout, never expose + * them as Metal staticThreadgroupMemoryLength or add dynamic bytes twice. + * stela_metal_threadgroup_matches checks values only, not resource ownership. */ +enum stela_nv_air_status stela_nv_air_compile_specialized(const struct nv_device_info *, + const struct nak_compiler *, const struct stela_metal_assembly *, uint32_t selected_entry, + const struct stela_nv_air_options *, const struct stela_metal_threadgroup_request *, + struct stela_nv_air_compilation **, + struct stela_nv_air_error *); + +enum stela_nv_air_status stela_nv_air_compile(const struct nv_device_info *, + const struct nak_compiler *, const struct stela_metal_assembly *, uint32_t selected_entry, + const struct stela_nv_air_options *, struct stela_nv_air_compilation **, + struct stela_nv_air_error *); + +/* Actual live GPU view, not an allocator or proof created by these fields. + * Match the live device pointer supplied to pack_arguments and retain a real + * unique mapping/resource owner through dispatch completion. No caller boolean, + * owner cookie or PCI tuple authenticates permissions, residency or device/VM + * epoch. The actual dispatch service establishes those preconditions. Views may + * alias when permitted by their genuine source/runtime contract. */ +struct stela_nv_air_buffer_view { + const struct nv_device_info *device; + const void *owner; + uint32_t argument, index, available_access; + uint64_t allocation_va, allocation_bytes, offset, bytes; +}; +/* Atomic bounded CPU table formation only: exact map/count, view spans, rights, + * type alignment and declared unsigned VM-width arithmetic are checked before + * writes. Device compiler facts must match the compiled target. Output is a + * separate writable normal CPU span, never a cast GPU VA/MMIO mapping; retain + * actual CPU ownership/cache coherency. A successful image must be uploaded to + * a real64B-aligned cbuf allocation of table_bytes, bound at argument_cbuf via + * the existing stela_nv_compute_encode. It neither pins views nor supplies + * visibility/order/fences. No allocations occur in this function. Zero-buffer + * code has table_bytes0 and needs no cbuf/view/output. All storage is disjoint + * and serialized against mutation/destruction; errors preserve output bytes. */ +enum stela_nv_air_status stela_nv_air_pack_arguments(const struct stela_nv_air_compilation *, + const struct nv_device_info *, unsigned va_bits, const struct stela_nv_air_buffer_view *, + uint32_t view_count, void *output, size_t output_bytes); + +const struct nak_shader_bin *stela_nv_air_binary(const struct stela_nv_air_compilation *); +const nir_shader *stela_nv_air_nir(const struct stela_nv_air_compilation *); +const struct stela_nv_air_provenance *stela_nv_air_provenance(const struct stela_nv_air_compilation *); +const struct stela_nv_air_binding *stela_nv_air_bindings(const struct stela_nv_air_compilation *, + uint32_t *count, uint32_t *table_bytes); +void stela_nv_air_destroy(struct stela_nv_air_compilation **); +#ifdef __cplusplus +} +#endif +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/mmio.h b/crates/stela-drivers/src/gpu/nvidia/stela/mmio.h new file mode 100644 index 0000000000..540843a612 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/mmio.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_NVIDIA_MMIO_H +#define STELA_NVIDIA_MMIO_H +#include "nvtypes.h" +#include "os/nv_memory_type.h" + +#if !NVOS_IS_STELA || !NVOS_IS_UNIX || NVOS_IS_LINUX || NVOS_IS_MACINTOSH +#error "native physical mappings must select Stela's OS interface" +#endif + +_Static_assert(NV_MEMORY_CACHED == 0 && NV_MEMORY_UNCACHED == 1 && + NV_MEMORY_WRITECOMBINED == 2 && NV_MEMORY_WRITEBACK == 5 && + NV_MEMORY_DEFAULT == 6 && NV_MEMORY_UNCACHED_WEAK == 7, + "preserve original NVIDIA cache-mode values"); + +/* Native same-CPU ABI. A pinned installed Rust MmioServices retains the single + * canonical native Authority and every published Mapping. It resolves the + * complete physical/page span to an actual registered ResourceBacking; there + * is no PA=VA conversion, BAR ownership inference or cached-RAM mapping here. + * UC/default request genuine UC; WC requests genuine WC or fails. Other modes + * fail. The real platform must enforce context/cache/root/TLB requirements. + * + * The native owner serializes all callbacks/install/uninstall in permitted + * process/deferred context and keeps the installed services/global heap alive. + * Unmap returns the exact pointer and requested byte count once, after ALL raw + * CPU/device/callback/worker uses and posted/WC writes stop and drain. It cannot + * report failure through the original void ABI: owner-visible Rust diagnostics + * retain failures. Busy keeps the exact Mapping pending for explicit native- + * owner quiescent drain; other failures retain uncertain owners through + * canonical quarantine. Pending leases block uninstall and never resume raw + * use after the initial unmap. + * These pointers authorize raw access only, never safe Rust references. + */ +void *stela_nvidia_map_mmio(NvU64 physical, NvU64 bytes, NvU32 mode); +void stela_nvidia_unmap_mmio(void *address, NvU64 bytes); +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/page_geometry.h b/crates/stela-drivers/src/gpu/nvidia/stela/page_geometry.h new file mode 100644 index 0000000000..cc9ea7b3f4 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/page_geometry.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_NVIDIA_PAGE_GEOMETRY_H +#define STELA_NVIDIA_PAGE_GEOMETRY_H +#include "os-interface.h" + +/* Private publisher of the Rust actual-PageSource owner. Original RM data + * symbols remain unavailable/zero until that owner queries and binds genuine + * native geometry before all C callers. Never call this instead of install(). + * Initial publication excludes every original reader; values never change. + * All validation precedes writes; repeats match exactly or preserve old facts. + */ +/* Current native producer admits base-only profiles; broader valid geometry + * returns NV_ERR_NOT_SUPPORTED without changing any original data symbol. */ +NV_STATUS stela_nvidia_set_page_geometry(NvU64, NvU64, NvU64, NvU8); +_Static_assert(sizeof(os_page_size) == 8 && sizeof(os_max_page_size) == 8 && + sizeof(os_page_mask) == 8 && sizeof(os_page_shift) == 1, + "original native RM page globals ABI"); +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/services.h b/crates/stela-drivers/src/gpu/nvidia/stela/services.h index 0f993f0de2..1211ad585d 100644 --- a/crates/stela-drivers/src/gpu/nvidia/stela/services.h +++ b/crates/stela-drivers/src/gpu/nvidia/stela/services.h @@ -26,8 +26,8 @@ _Static_assert(NV_MEMORY_CACHED == 0 && NV_MEMORY_UNCACHED == 1 && * handles. Calls and final releases are serialized process/deferred operations, * never ISR allocation or completion. Stop callers and prove real hardware * quiescence before unbind/removal. MemoryServices refuses unbind while any - * producer allocation or published DMA token remains; keep service/state live - * until all those handles are freed/retired/quarantined and unbind succeeds. + * producer allocation, published DMA token or firmware token remains; keep service/state live + * until all those handles are freed/retired/quarantined/put and unbind succeeds. * Only CPU views and consumed quarantine may survive. Remaining RM/IRQ services * are prerequisites. Bind/unbind below are private helpers of the Rust owner; * use MemoryServices methods so their live-resource checks cannot be bypassed. diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_firmware.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_firmware.c new file mode 100644 index 0000000000..80e234556a --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_firmware.c @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: MIT */ +#include "version.h" +/* Same original package-name policy as kernel-open/nvidia/nv.c at the retained + * NVIDIA pin. version.h is generated from the existing vendor version.mk. */ +#define NV_FIRMWARE_FOR_NAME(name) "nvidia/" NVIDIA_VERSION "/" name ".bin" +#include "firmware.h" +/* Original optional log tables use intentional zero-filled partial initializers. */ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#include "nv-firmware-chip-family-select.h" +#pragma GCC diagnostic pop +#include "libelf.h" + +_Static_assert(sizeof(nv_firmware_type_t) == sizeof(NvU32) && + sizeof(nv_firmware_chip_family_t) == sizeof(NvU32), + "native firmware enum ABI"); + +NvU32 stela_nvidia_firmware_family(NvU32 architecture, NvU32 implementation) +{ + return nv_firmware_get_chip_family(architecture, implementation); +} + +NvU64 stela_nvidia_firmware_alignment(void) +{ + return _Alignof(LibosElf64Header) > _Alignof(LibosElf64SectionHeader) ? + _Alignof(LibosElf64Header) : _Alignof(LibosElf64SectionHeader); +} + +const char *stela_nvidia_firmware_version(void) +{ + return NVIDIA_VERSION; +} + +const void *NV_API_CALL nv_get_firmware(nv_state_t *nv, + nv_firmware_type_t type, + nv_firmware_chip_family_t family, + const void **buffer, NvU32 *bytes) +{ + if (nv == NULL || nv->os_state == NULL || buffer == NULL || bytes == NULL) + return NULL; + const char *name = nv_firmware_for_chip_family(type, family); + const char *hardware = nv_firmware_chip_family_to_string(family); + if (name[0] == '\0' || hardware[0] == '\0') + return NULL; + return stela_nvidia_get_firmware(nv->os_state, nv, family, name, hardware, + NVIDIA_VERSION, buffer, bytes); +} + +void NV_API_CALL nv_put_firmware(const void *token) +{ + if (token != NULL) + stela_nvidia_put_firmware(token); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_mmio.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_mmio.c new file mode 100644 index 0000000000..4c84141cdf --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_mmio.c @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT */ +#include "os-interface.h" +#include "mmio.h" + +/* Original vendor declarations stay unchanged. Only the native Stela build + * selects these hooks; Linux's reference implementation remains separate. */ +void *NV_API_CALL os_map_kernel_space(NvU64 physical, NvU64 bytes, NvU32 mode) +{ + return stela_nvidia_map_mmio(physical, bytes, mode); +} + +void NV_API_CALL os_unmap_kernel_space(void *address, NvU64 bytes) +{ + stela_nvidia_unmap_mmio(address, bytes); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_memory.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_memory.c new file mode 100644 index 0000000000..7fe9cfcf77 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_memory.c @@ -0,0 +1,53 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2015-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +/* + * Original nvkms_alloc/free CPU metadata boundary at official NVIDIA pin + * 1a82fbfda8f321b056eb3568850f9316c5e465c5. Replace only the Linux + * kmalloc(GFP_KERNEL)/vmalloc/kfree/vfree backend with the existing checked + * common heap. No atomic request, context detection or timer service exists + * here. The original nonzero-zero flag and sized-free caller contract remain. + */ +#include "nvidia-modeset-os-interface.h" +#include "memory.h" + +void *nvkms_alloc(size_t size, NvBool zero) +{ + void *pointer = NULL; + if (stela_nvidia_alloc(size, &pointer) != STELA_NVIDIA_ALLOC_SUCCESS) + return NULL; + if (zero && (pointer != NULL)) + nvkms_memset(pointer, 0, size); + return pointer; +} + +void nvkms_free(void *pointer, size_t size) +{ + /* The original caller supplies the exact allocation size. The common + * backend retains its own exact Layout; it needs no page-size dispatch. + */ + (void)size; + stela_nvidia_free(pointer); +} + +_Static_assert(sizeof(size_t) == sizeof(NvU64), "native allocation length"); +_Static_assert(sizeof(NvBool) == 1, "original zero flag width"); diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_primitives.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_primitives.c new file mode 100644 index 0000000000..4cfab6426d --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvkms_primitives.c @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2015-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +/* + * Unchanged CPU primitive bodies from official kernel-open/nvidia-modeset/ + * nvidia-modeset-linux.c at 1a82fbfda8f321b056eb3568850f9316c5e465c5. + * Original size_t spans/return lengths stay native pointer-sized throughout. + */ +#include "stela_primitives.h" +#include "nvidia-modeset-os-interface.h" + +void* nvkms_memset(void *ptr, NvU8 c, size_t size) +{ + return memset(ptr, c, size); +} + +void* nvkms_memcpy(void *dest, const void *src, size_t n) +{ + return memcpy(dest, src, n); +} + +void* nvkms_memmove(void *dest, const void *src, size_t n) +{ + return memmove(dest, src, n); +} + +int nvkms_memcmp(const void *s1, const void *s2, size_t n) +{ + return memcmp(s1, s2, n); +} + +size_t nvkms_strlen(const char *s) +{ + return strlen(s); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_memory.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_memory.c new file mode 100644 index 0000000000..cd9cbbcf05 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_memory.c @@ -0,0 +1,47 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2015-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +/* + * Native CPU metadata boundary for original nvlink_malloc/nvlink_free at + * official pin 1a82fbfda8f321b056eb3568850f9316c5e465c5. The original Linux + * backend is kmalloc(size, GFP_KERNEL)/kfree(ptr). Only that backend changes: + * Stela's existing checked common-heap adapter owns both allocation and free. + * These functions have no atomic-request mode. See NVLINK_MEMORY.md. + */ +#include +#include "nvlink_os.h" +#include "memory.h" + +void *nvlink_malloc(NvLength size) +{ + void *pointer = NULL; + if (stela_nvidia_alloc(size, &pointer) != STELA_NVIDIA_ALLOC_SUCCESS) + return NULL; + return pointer; +} + +void nvlink_free(void *pointer) +{ + stela_nvidia_free(pointer); +} + +_Static_assert(sizeof(NvLength) == sizeof(NvU64), "native allocation length"); diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_primitives.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_primitives.c new file mode 100644 index 0000000000..14c9319cce --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvlink_primitives.c @@ -0,0 +1,44 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2015-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +/* + * Unchanged CPU primitive bodies from official kernel-open/nvidia/nvlink_linux.c + * at 1a82fbfda8f321b056eb3568850f9316c5e465c5. Scalar/pointer ABI only; + * original NvLength stays pointer-sized, without a NvU32 intermediate. + */ +#include "stela_primitives.h" +#include "nvlink_os.h" + +NvLength nvlink_strlen(const char *s) +{ + return strlen(s); +} + +void * nvlink_memset(void *dest, int value, NvLength size) +{ + return memset(dest, value, size); +} + +void * nvlink_memcpy(void *dest, const void *src, NvLength size) +{ + return memcpy(dest, src, size); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvswitch_primitives.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvswitch_primitives.c new file mode 100644 index 0000000000..9f13a72ddd --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_nvswitch_primitives.c @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2016-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/* Unchanged ordinary CPU primitive signatures/bodies from official + * kernel-open/nvidia/linux_nvswitch.c at + * 1a82fbfda8f321b056eb3568850f9316c5e465c5. The shared native runtime + * owns these standard functions; no NvU32 length intermediate is introduced. + */ +#include "stela_primitives.h" +#include "../src/common/nvswitch/interface/export_nvswitch.h" + +NvLength +nvswitch_os_strlen +( + const char *str +) +{ + return strlen(str); +} + +void * +nvswitch_os_memset +( + void *dest, + int value, + NvLength size +) +{ + return memset(dest, value, size); +} + +void * +nvswitch_os_memcpy +( + void *dest, + const void *src, + NvLength size +) +{ + return memcpy(dest, src, size); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_ordering.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_ordering.c new file mode 100644 index 0000000000..83da87001c --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_ordering.c @@ -0,0 +1,40 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 1999-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + + +/* Unchanged official kernel-open/nvidia/os-interface.c body at + * 1a82fbfda8f321b056eb3568850f9316c5e465c5. cpuopsys.h, included through + * the original interface, selects the actual native-x86 implementation. + */ +#include "os-interface.h" + +void NV_API_CALL os_flush_cpu_write_combine_buffer(void) +{ +#if defined(NVCPU_X86_64) + asm volatile("sfence" ::: "memory"); +#elif defined(NVCPU_AARCH64) + asm volatile("dsb st" : : : "memory"); +#else + mb(); +#endif +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_page_geometry.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_page_geometry.c new file mode 100644 index 0000000000..11c098ec13 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_page_geometry.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: MIT */ +#include "page_geometry.h" + +/* Actual original os-interface.h data types. No guessed platform defaults; + * native owner publication is a prerequisite for every original RM accessor. + */ +NvU64 os_page_size; +NvU64 os_max_page_size; +NvU64 os_page_mask; +NvU8 os_page_shift; + +NV_STATUS stela_nvidia_set_page_geometry(NvU64 base, NvU64 max, NvU64 mask, NvU8 shift) +{ + if (shift < 12 || shift >= 63 || base != (1ULL << shift) || + max < base || max > (1ULL << 62) || (max & (max - 1)) || + mask != ~(base - 1)) + return NV_ERR_INVALID_ARGUMENT; + /* nv_alloc_pages currently accepts only the configured base granule. */ + if (max != base) + return NV_ERR_NOT_SUPPORTED; + if (os_page_size || os_max_page_size || os_page_mask || os_page_shift) + return os_page_size == base && os_max_page_size == max && + os_page_mask == mask && os_page_shift == shift ? NV_OK : NV_ERR_INVALID_STATE; + os_max_page_size = max; + os_page_mask = mask; + os_page_shift = shift; + os_page_size = base; + return NV_OK; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.c b/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.c new file mode 100644 index 0000000000..b73c3dc0ae --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.c @@ -0,0 +1,46 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 1999-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: MIT + * + * Original native-x86/default primitive bodies from kernel-open/nvidia/ + * os-interface.c at 1a82fbfda8f321b056eb3568850f9316c5e465c5. + * Architecture-specific Linux/device-memory and size-optimized fallback branches + * are not selected by this native x86-64 Stela build. The shared runtime owns + * the actual algorithms; no new libc, address inference or provider shim. + */ +#include "os-interface.h" +#include "stela_primitives.h" + +NvU32 NV_API_CALL os_string_length( + const char* str +) +{ + return strlen(str); +} + +void *NV_API_CALL os_mem_copy( + void *dst, + const void *src, + NvU32 length +) +{ + return memcpy(dst, src, length); +} + +void* NV_API_CALL os_mem_set( + void *dst, + NvU8 c, + NvU32 length +) +{ + return memset(dst, (int)c, length); +} + +NvS32 NV_API_CALL os_mem_cmp( + const NvU8 *buf0, + const NvU8* buf1, + NvU32 length +) +{ + return memcmp(buf0, buf1, length); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.h b/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.h new file mode 100644 index 0000000000..e300d92b71 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/stela_primitives.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_NVIDIA_PRIMITIVES_H +#define STELA_NVIDIA_PRIMITIVES_H +#include +#include "nvtypes.h" + +#if !NVOS_IS_STELA || !NVCPU_IS_X86_64 +#error "these original RM primitives select native x86-64 Stela" +#endif + +/* Declarations of the existing shared C runtime, not a private implementation. + * Native UEFI resolves these to Rust's compiler_builtins; hosted tests use the + * host C runtime. Calls require ordinary valid CPU buffers, nonoverlapping copy + * ranges and terminated readable strings. They do not perform usercopy, MMIO + * ordering, cache maintenance, pinning or allocation and establish no ISR state. + */ +void *memcpy(void *, const void *, size_t); +void *memmove(void *, const void *, size_t); +void *memset(void *, int, size_t); +int memcmp(const void *, const void *, size_t); +size_t strlen(const char *); + +_Static_assert(sizeof(size_t) == sizeof(NvLength) && sizeof(NvLength) == 8, + "native shared C runtime uses pointer-sized lengths"); +_Static_assert(sizeof(NvU32) == 4 && sizeof(NvU8) == 1 && sizeof(NvS32) == sizeof(int), + "preserve original RM primitive scalar ABI"); +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/air_compile.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/air_compile.c new file mode 100644 index 0000000000..bd69c7ba81 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/air_compile.c @@ -0,0 +1,727 @@ +/* SPDX-License-Identifier: MIT */ +/* Hosted CPU compilation/table/QMD fixtures only. Device topology, GPU VAs and + * resource owners are synthetic test models, never hardware qualification. */ +#include "../hosted/air_compile.h" +#include "stela/air_test_fixture.h" +#include "nouveau/compiler/nak_private.h" +#include "nouveau/headers/drf.h" +#include "clc5c0.h" +#include "clc6c0.h" +#include "clc7c0.h" +#include "clc9c0.h" +#include "clcbc0.h" +#include "clcdc0.h" +#include "clcec0.h" +#include "clc3c0qmd.h" +#include "clc6c0qmd.h" +#include "clcbc0qmd.h" +#include "clcdc0qmd.h" +#include "util/ralloc.h" +#include "util/u_math.h" +#include "util/mesa-blake3.h" +#include +#include +#include +#include +#include +#include +#include +#ifdef NDEBUG +#error "Owned NAK tests require assertions" +#endif +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%s:%d: %s\n", __func__, __LINE__, #x); abort(); } } while (0) +static unsigned allocations, fail_allocation, live_allocations; +void *stela_nv_air_test_malloc(size_t); +void *stela_nv_air_test_calloc(size_t, size_t); +void stela_nv_air_test_free(void *); +void *stela_nv_air_test_malloc(size_t bytes) { + if (++allocations == fail_allocation) return NULL; + void *p = malloc(bytes); if (p) live_allocations++; return p; +} +void *stela_nv_air_test_calloc(size_t count, size_t bytes) { + if (++allocations == fail_allocation) return NULL; + void *p = calloc(count, bytes); if (p) live_allocations++; return p; +} +void stela_nv_air_test_free(void *p) { + if (p) { CHECK(live_allocations); live_allocations--; } free(p); +} +struct bytes { uint8_t *data; size_t size; }; +static void append(struct bytes *bytes, const void *data, size_t size) +{ + CHECK(size <= SIZE_MAX - bytes->size); + bytes->data = realloc(bytes->data, bytes->size + size); + CHECK(bytes->data); + memcpy(bytes->data + bytes->size, data, size); + bytes->size += size; +} +static void little(void *data, uint64_t value, unsigned bytes) +{ + for (unsigned i = 0; i < bytes; i++) ((uint8_t *)data)[i] = (uint8_t)(value >> (8 * i)); +} +static void tag(struct bytes *bytes, const char name[4], const void *data, size_t size) +{ + CHECK(size <= UINT16_MAX); + uint8_t length[2]; little(length, size, 2); + append(bytes, name, 4); append(bytes, length, 2); append(bytes, data, size); +} +static void digest(const void *bytes, size_t size, uint8_t output[32]) +{ + CHECK(size <= AIR_MAX_BITCODE_BYTES); + CC_SHA256(bytes, (CC_LONG)size, output); +} +/* Own one-entry framing fixture, never a second parser. The production Rust + * parser and shared inspector independently validate all original extents. */ +static struct bytes archive(const void *air, size_t size, const char *name, + unsigned air_minor, unsigned major, unsigned minor, + unsigned os_major, unsigned os_minor) +{ + struct bytes record = {0}; uint8_t prefix[4] = {0}, kind = 2, hash[32]; + append(&record, prefix, 4); tag(&record, "NAME", name, strlen(name) + 1); + tag(&record, "TYPE", &kind, 1); digest(air, size, hash); tag(&record, "HASH", hash, 32); + uint8_t length[8], offsets[24] = {0}, versions[8]; little(length, size, 8); + tag(&record, "MDSZ", length, 8); tag(&record, "OFFT", offsets, 24); + little(versions, 2, 2); little(versions + 2, air_minor, 2); + little(versions + 4, major, 2); little(versions + 6, minor, 2); + tag(&record, "VERS", versions, 8); append(&record, "ENDT", 4); little(record.data, record.size, 4); + uint8_t header[88] = {0}; memcpy(header, "MTLB", 4); + little(header + 4, 0x8001, 2); little(header + 6, 2, 2); little(header + 8, 9, 2); + header[11] = 0x81; little(header + 12, os_major, 2); little(header + 14, os_minor, 2); + size_t start = 92 + record.size; + little(header + 16, start + size, 8); little(header + 24, 88, 8); little(header + 32, record.size, 8); + little(header + 40, start, 8); little(header + 56, start, 8); + little(header + 72, start, 8); little(header + 80, size, 8); + struct bytes result = {0}; append(&result, header, sizeof(header)); + little(prefix, 1, 4); append(&result, prefix, 4); append(&result, record.data, record.size); + append(&result, air, size); free(record.data); return result; +} +static struct stela_metal_assembly *assemble(const struct bytes *bytes) +{ + struct stela_metal_assembly_options options = stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error; struct stela_metal_assembly *library = NULL; + enum stela_metal_assembly_status status = stela_metal_assemble_archive( + &options, bytes->data, bytes->size, &library, &error); + if (status) fprintf(stderr, "assembly refused: %u %s\n", status, error.detail); + CHECK(status == STELA_METAL_ASSEMBLY_OK && library); + return library; +} +static struct stela_metal_assembly *fixture(LLVMMemoryBufferRef air) +{ + struct bytes bytes = archive(LLVMGetBufferStart(air), LLVMGetBufferSize(air), "kernel", 8, 4, 0, 26, 7); + struct stela_metal_assembly *library = assemble(&bytes); free(bytes.data); return library; +} +static struct stela_metal_assembly *two_entries(LLVMMemoryBufferRef air) +{ + size_t size = LLVMGetBufferSize(air); + struct bytes a = archive(LLVMGetBufferStart(air), size, "kernel", 8, 4, 0, 26, 7); + struct bytes b = archive(LLVMGetBufferStart(air), size, "other", 8, 4, 0, 26, 7); + size_t a_record = a.size - 92 - size, b_record = b.size - 92 - size; + size_t start = 92 + a_record + b_record; + uint8_t header[88], count[4]; memcpy(header, a.data, sizeof(header)); + little(header + 16, start + size, 8); little(header + 32, a_record + b_record, 8); + little(header + 40, start, 8); little(header + 56, start, 8); little(header + 72, start, 8); + little(count, 2, 4); + struct bytes bytes = {0}; append(&bytes, header, sizeof(header)); append(&bytes, count, 4); + append(&bytes, a.data + 92, a_record); append(&bytes, b.data + 92, b_record); + append(&bytes, LLVMGetBufferStart(air), size); + struct stela_metal_assembly *library = assemble(&bytes); + free(a.data); free(b.data); free(bytes.data); return library; +} +static void text_append(char *text, size_t capacity, const char *format, ...) +{ + size_t length = strlen(text); CHECK(length < capacity); + va_list args; va_start(args, format); int bytes = vsnprintf(text + length, capacity - length, format, args); + va_end(args); CHECK(bytes >= 0 && (size_t)bytes < capacity - length); +} +static LLVMMemoryBufferRef multibuffer(unsigned count) +{ + CHECK(count <= 31); + char prefix[4096] = "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v28-apple-macosx26.7.0\"\ndefine void @kernel(i32 %tid"; + char body[8192] = "%index = zext i32 %tid to i64\n", metadata[16384] = "}\n" + "!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 8, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5"; + for (unsigned i = 0; i < count; i++) { + text_append(prefix, sizeof(prefix), ", ptr addrspace(1) %%b%u", i); + text_append(body, sizeof(body), "%%p%u = getelementptr i32, ptr addrspace(1) %%b%u, i64 %%index\n" + "%%v%u = load i32, ptr addrspace(1) %%p%u, align 4\n" + "%%x%u = add i32 %%v%u, %u\nstore i32 %%x%u, ptr addrspace(1) %%p%u, align 4\n", + i, i, i, i, i, i, i + 1, i, i); + text_append(metadata, sizeof(metadata), ",!%u", i + 6); + } + text_append(prefix, sizeof(prefix), ") {\n"); text_append(body, sizeof(body), "ret void\n"); + text_append(metadata, sizeof(metadata), "}\n!5 = !{i32 0, !\"air.thread_position_in_grid\"," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n"); + for (unsigned i = 0; i < count; i++) + text_append(metadata, sizeof(metadata), "!%u = !{i32 %u, !\"air.buffer\", !\"air.location_index\", i32 %u, i32 1," + " !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4," + " !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"buffer%u\"}\n", + i + 6, i + 1, (i * 7 + 3) % 31, i); + return stela_air_test_custom_bitcode(prefix, body, metadata, ""); +} + +static struct nv_device_info model(unsigned sm, unsigned cls) +{ + struct nv_device_info device = {.sm = (uint8_t)sm, .cls_compute = (uint16_t)cls}; + const uint16_t sizes[] = {0, 8, 16, 32, 64, 100, 132, 164, 196, 228}; + if (sm == 75) { + device.max_warps_per_mp = 32; device.sm_smem_size_count = 2; + device.sm_smem_sizes_kB[0] = 32; device.sm_smem_sizes_kB[1] = 64; + } else { + device.max_warps_per_mp = sm == 86 || sm == 87 || sm == 89 || sm == 120 ? 48 : 64; + device.sm_smem_size_count = sm == 80 || sm == 87 ? 8 : sm >= 90 && sm < 120 ? 10 : 6; + memcpy(device.sm_smem_sizes_kB, sizes, device.sm_smem_size_count * sizeof(sizes[0])); + } + device.max_smem_per_wg_kB = device.sm_smem_sizes_kB[device.sm_smem_size_count - 1]; + return device; +} +static struct nak_compiler *compiler(const struct nv_device_info *device) +{ + const struct nak_constant_offset_info layout = {.sample_info_cb = 0, + .sample_locations_offset = 0, .sample_masks_offset = 256, .printf_cb = 0, .printf_buffer_offset = 512}; + struct nak_compiler *nak = nak_compiler_create(device, &layout, &layout); CHECK(nak); return nak; +} +static struct stela_nv_air_options options(void) +{ + return (struct stela_nv_air_options) {.size = sizeof(struct stela_nv_air_options), .abi = STELA_NV_AIR_ABI, + .workgroup_size = {32, 1, 1}, .max_instructions = 4096, .max_code_bytes = 1024 * 1024, + .argument_cbuf = 1, .record_assembly = 1}; +} +static struct stela_nv_air_compilation *compile(const struct nv_device_info *device, + const struct nak_compiler *nak, struct stela_metal_assembly *library, uint32_t selected, + const struct stela_nv_air_options *opts, enum stela_nv_air_status expected) +{ + struct stela_nv_air_compilation *owner = NULL; struct stela_nv_air_error error; +#ifdef STELA_NV_AIR_ALLOC_TEST + unsigned baseline = live_allocations; +#endif + enum stela_nv_air_status status = stela_nv_air_compile(device, nak, library, selected, opts, &owner, &error); + if (status != expected) fprintf(stderr, "SM%u status%u expected%u: %s (AIR%u %s)\n", + device->sm, status, expected, error.detail, error.air.kind, error.air.detail); + CHECK(status == expected && error.status == status && (owner != NULL) == (status == STELA_NV_AIR_OK)); +#ifdef STELA_NV_AIR_ALLOC_TEST + if (status != STELA_NV_AIR_OK) CHECK(live_allocations == baseline); +#endif + return owner; +} +static void destroy(struct stela_nv_air_compilation **owner) +{ + stela_nv_air_destroy(owner); CHECK(!*owner); stela_nv_air_destroy(owner); stela_nv_air_destroy(NULL); +} +struct reference {const struct stela_nv_air_provenance *p;}; +static bool reference_threadgroup(const struct stela_air_buffer *buffer, + struct stela_air_threadgroup_view *view,void *data) +{ + const struct reference *ref=data; + for(unsigned i=0;ip->threadgroup.count;i++) { + const struct stela_metal_threadgroup_binding *row=&ref->p->threadgroup.bindings[i]; + if(row->buffer.argument==buffer->argument) { + CHECK(row->buffer.index==buffer->index&&buffer->address_space==3&& + row->buffer.type_size==buffer->type_size&&row->buffer.type_alignment==buffer->type_alignment); + *view=(struct stela_air_threadgroup_view){.size=row->bytes,.alignment=row->alignment, + .available_access=STELA_AIR_READ_WRITE};return true; + } + } + CHECK(false);return false; +} +static nir_def *reference_bind(nir_builder *b, const struct stela_air_buffer *buffer, void *data) +{ + struct reference *ref = data; unsigned row = 0; + for (unsigned i = 0; i < ref->p->argument_count; i++) { + const struct stela_air_argument_info *arg = &ref->p->arguments[i]; + if (arg->kind != 1 || arg->buffer.address_space != 1) continue; + if (arg->buffer.argument == buffer->argument) { + CHECK(arg->buffer.index == buffer->index && buffer->address_space == 1); + if (!arg->used) return nir_undef(b, 1, 64); + return nir_ldc_nv(b, 1, 64, nir_imm_int(b, (int)ref->p->options.argument_cbuf), + nir_imm_int(b, 0), .base = row * 8, .align_mul = 8, .align_offset = 0); + } + if (arg->used) row++; + } + CHECK(false); return NULL; +} +static uint64_t get64(const uint8_t *bytes) +{ + uint64_t value = 0; for (unsigned i = 0; i < 8; i++) value |= (uint64_t)bytes[i] << (8 * i); return value; +} +static uint64_t bits(const uint32_t *words, unsigned start, unsigned end) +{ + CHECK(end >= start && end - start <= 64 && end <= NAK_MAX_QMD_SIZE_B * 8); + uint64_t value = 0; + for (unsigned i = start; i < end; i++) value |= (uint64_t)((words[i / 32] >> (i % 32)) & 1) << (i - start); + return value; +} +static void qmd(const struct nv_device_info *device, const struct stela_nv_air_compilation *owner, + uint32_t count, uint32_t table_bytes) +{ + const struct nak_shader_bin *bin = stela_nv_air_binary(owner); + const struct stela_nv_air_provenance *p = stela_nv_air_provenance(owner); + struct stela_nv_compute_dispatch dispatch = {.qmd = {.addr = 0x800000, .smem_size = bin->info.cs.smem_size, + .global_size = {1, 2, 3}, .num_cbufs = count ? 1 : 0}, .qmd_addr = 0x900000, .va_bits = 40}; + if (count) dispatch.qmd.cbufs[0] = (struct nak_qmd_cbuf) {.index = p->options.argument_cbuf, + .size = table_bytes, .addr = 0x400000}; + struct stela_nv_compute_encoded encoded; enum stela_nv_compute_error error; + bool valid = stela_nv_compute_encode(device, bin, &dispatch, &encoded, &error); + if (bin->info.slm_size || bin->info.crs_size) { CHECK(!valid && error == STELA_NV_COMPUTE_SCRATCH_UNSUPPORTED); return; } + CHECK(valid && error == STELA_NV_COMPUTE_OK && encoded.push_dw == 3); + uint32_t original[NAK_MAX_QMD_DWORDS] = {0}; nak_fill_qmd(device, &bin->info, &dispatch.qmd, original, encoded.qmd_size_B); + CHECK(!memcmp(original, encoded.qmd, encoded.qmd_size_B)); + uint32_t shared, barriers; + if (device->cls_compute >= BLACKWELL_COMPUTE_A) { + shared = NVVAL_MW_GET(encoded.qmd, NVCDC0, QMDV05_00, SHARED_MEMORY_SIZE_SHIFTED7) << 7; + barriers = NVVAL_MW_GET(encoded.qmd, NVCDC0, QMDV05_00, BARRIER_COUNT); + } else if (device->cls_compute >= HOPPER_COMPUTE_A) { + shared = NVVAL_MW_GET(encoded.qmd, NVCBC0, QMDV04_00, SHARED_MEMORY_SIZE); + barriers = NVVAL_MW_GET(encoded.qmd, NVCBC0, QMDV04_00, BARRIER_COUNT); + } else if (device->cls_compute >= AMPERE_COMPUTE_A) { + shared = NVVAL_MW_GET(encoded.qmd, NVC6C0, QMDV03_00, SHARED_MEMORY_SIZE); + barriers = NVVAL_MW_GET(encoded.qmd, NVC6C0, QMDV03_00, BARRIER_COUNT); + } else { + shared = NVVAL_MW_GET(encoded.qmd, NVC3C0, QMDV02_02, SHARED_MEMORY_SIZE); + barriers = NVVAL_MW_GET(encoded.qmd, NVC3C0, QMDV02_02, BARRIER_COUNT); + } + CHECK(shared == ALIGN_POT((unsigned)bin->info.cs.smem_size, 256) && barriers == bin->info.num_control_barriers); + if (!count) return; + unsigned slot = p->options.argument_cbuf; + struct nak_qmd_cbuf_desc_layout layout = nak_get_qmd_cbuf_desc_layout(device, (uint8_t)slot); + uint64_t address = bits(encoded.qmd, layout.addr_lo_start, layout.addr_lo_end) | + (bits(encoded.qmd, layout.addr_hi_start, layout.addr_hi_end) << (layout.addr_lo_end - layout.addr_lo_start)); + CHECK((address << layout.addr_shift) == dispatch.qmd.cbufs[0].addr); + uint64_t size; + if (device->cls_compute >= BLACKWELL_COMPUTE_A) + size = NVVAL_MW_GET(encoded.qmd, NVCDC0, QMDV05_00, CONSTANT_BUFFER_SIZE_SHIFTED4, slot) << 4; + else if (device->cls_compute >= HOPPER_COMPUTE_A) + size = NVVAL_MW_GET(encoded.qmd, NVCBC0, QMDV04_00, CONSTANT_BUFFER_SIZE_SHIFTED4, slot) << 4; + else if (device->cls_compute >= AMPERE_COMPUTE_A) + size = NVVAL_MW_GET(encoded.qmd, NVC6C0, QMDV03_00, CONSTANT_BUFFER_SIZE_SHIFTED4, slot) << 4; + else size = NVVAL_MW_GET(encoded.qmd, NVC3C0, QMDV02_02, CONSTANT_BUFFER_SIZE_SHIFTED4, slot) << 4; + CHECK(size == table_bytes); +} +static void specialize(nir_shader *shader, const uint8_t *table, unsigned count, + const uint64_t *addresses) +{ + nir_foreach_function_impl(impl, shader) { + nir_builder b = nir_builder_create(impl); + nir_foreach_block(block, impl) { + nir_foreach_instr_safe(instr, block) { + if (instr->type != nir_instr_type_intrinsic) continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); nir_def *value = NULL; + b.cursor = nir_before_instr(instr); + if (intr->intrinsic == nir_intrinsic_ldc_nv) { + CHECK(nir_intrinsic_base(intr) >= 0); + unsigned offset = (unsigned)nir_intrinsic_base(intr); CHECK(offset % 8 == 0 && offset / 8 < count); + value = nir_imm_int64(&b, (int64_t)get64(table + offset)); + } else if (intr->intrinsic == nir_intrinsic_load_global_invocation_id || + intr->intrinsic == nir_intrinsic_load_workgroup_id || intr->intrinsic == nir_intrinsic_load_local_invocation_id) + value = nir_imm_ivec3(&b, 0, 0, 0); + if (value) { nir_def_rewrite_uses(&intr->def, value); nir_instr_remove(instr); } + } + } + } + bool progress; + do { progress = nir_opt_constant_folding(shader); progress |= nir_opt_copy_prop(shader); + progress |= nir_opt_algebraic(shader); progress |= nir_opt_dce(shader); } while (progress); + unsigned loads[AIR_MAX_ARGUMENTS] = {0}, stores[AIR_MAX_ARGUMENTS] = {0}; + nir_foreach_function_impl(impl, shader) { + nir_foreach_block(block, impl) { + nir_foreach_instr(instr, block) { + if (instr->type != nir_instr_type_intrinsic) continue; + nir_intrinsic_instr *intr = nir_instr_as_intrinsic(instr); nir_src *address; unsigned *seen; + if (intr->intrinsic == nir_intrinsic_load_global) { address = &intr->src[0]; seen = loads; } + else if (intr->intrinsic == nir_intrinsic_store_global) { address = &intr->src[1]; seen = stores; } + else continue; + CHECK(nir_src_is_const(*address)); unsigned row; + for (row = 0; row < count; row++) if (nir_src_as_uint(*address) == addresses[row]) break; + CHECK(row < count); seen[row]++; + } + } + } + for (unsigned i = 0; i < count; i++) CHECK(loads[i] == 1 && stores[i] == 1); +} +static void validate(const struct nv_device_info *device, const struct nak_compiler *nak, + const struct stela_metal_assembly *library, struct stela_nv_air_compilation *owner, + const char *label, bool semantic) +{ + const struct nak_shader_bin *bin = stela_nv_air_binary(owner); + const struct stela_nv_air_provenance *p = stela_nv_air_provenance(owner); + uint32_t count, table_bytes; const struct stela_nv_air_binding *map = stela_nv_air_bindings(owner, &count, &table_bytes); + CHECK(bin && p && map && bin->code && bin->code_size && stela_nv_air_nir(owner)->options); + CHECK(table_bytes == ((count * 8 + 63) & ~63u)); + struct stela_nv_air_buffer_view views[AIR_MAX_ARGUMENTS]; uint64_t addresses[AIR_MAX_ARGUMENTS]; + for (unsigned i = 0; i < count; i++) { + unsigned reverse = count - 1 - i; + CHECK(map[i].cbuf_offset == i * 8); + views[reverse] = (struct stela_nv_air_buffer_view) {.device = device, .owner = &views[reverse], + .argument = map[i].buffer.argument, .index = map[i].buffer.index, .available_access = STELA_AIR_READ_WRITE, + .allocation_va = UINT64_C(0x100000) + i * 4096u, .allocation_bytes = 4096, .offset = 256, .bytes = 2048}; + addresses[i] = views[reverse].allocation_va + views[reverse].offset; + } + uint8_t table[2 * AIR_MAX_ARGUMENTS * 8], second[sizeof(table)]; memset(table, 0xa5, sizeof(table)); + CHECK(stela_nv_air_pack_arguments(owner, device, 40, views, count, table, sizeof(table)) == STELA_NV_AIR_OK); + for (unsigned i = 0; i < count; i++) CHECK(get64(table + i * 8) == addresses[i]); + for (unsigned i = count * 8; i < table_bytes; i++) CHECK(table[i] == 0); + for (unsigned i = table_bytes; i < sizeof(table); i++) CHECK(table[i] == 0xa5); + blake3_hash hash, after; _mesa_blake3_compute(bin->code, bin->code_size, hash); + for (unsigned i = 0; i < count; i++) views[i].allocation_va += 0x1000000; + CHECK(stela_nv_air_pack_arguments(owner, device, 40, views, count, second, sizeof(second)) == STELA_NV_AIR_OK); + for (unsigned i = 0; i < count; i++) CHECK(get64(second + i * 8) == addresses[i] + 0x1000000); + _mesa_blake3_compute(bin->code, bin->code_size, after); CHECK(!memcmp(hash, after, sizeof(hash))); + struct stela_metal_input_view original = {.size = sizeof(original), .abi = STELA_METAL_INPUT_ABI}; + CHECK(stela_metal_assembly_original(library, &original, NULL) == STELA_METAL_ASSEMBLY_OK); + struct reference ref = {.p = p}; const struct stela_air_options opts = { + .workgroup_size = {p->options.workgroup_size[0], p->options.workgroup_size[1], p->options.workgroup_size[2]}, + .max_instructions = p->options.max_instructions, .fp_profile = p->options.fp_profile, + .bind_buffer = reference_bind, .binding_data = &ref, + .bind_threadgroup=p->threadgroup.count?reference_threadgroup:NULL, + .max_threadgroup_bytes = MIN2((unsigned)device->max_smem_per_wg_kB * 1024, UINT16_MAX)}; + struct stela_air_error error; + nir_shader *nir = stela_air_to_nir(original.bytes + p->air_offset, (size_t)p->air_bytes, p->name, + stela_nv_air_nir(owner)->options, &opts, &error); CHECK(nir); + if (semantic) { nir_shader *copy = nir_shader_clone(NULL, nir); CHECK(copy); specialize(copy, table, count, addresses); ralloc_free(copy); } + nak_preprocess_nir(nir, nak); + struct nak_shader_bin *original_bin = nak_compile_shader(nir, true, nak, 0, NULL, false); + CHECK(original_bin && original_bin->code_size == bin->code_size && !memcmp(original_bin->code, bin->code, bin->code_size) && + !memcmp(&original_bin->info, &bin->info, sizeof(bin->info))); + nak_shader_bin_destroy(original_bin); ralloc_free(nir); + qmd(device, owner, count, table_bytes); + char digest[BLAKE3_HEX_LEN]; _mesa_blake3_format(digest, hash); + printf("owned-air-nak input=%s sm=%u buffers=%u cbuf=%u table_bytes=%u code_bytes=%u code_blake3=%s gprs=%u shared=%u barriers=%u scratch=%u stack=%u\n", + label, device->sm, count, p->options.argument_cbuf, table_bytes, bin->code_size, digest, bin->info.num_gprs, + bin->info.cs.smem_size, bin->info.num_control_barriers, bin->info.slm_size, bin->info.crs_size); +} +static void targets(struct stela_metal_assembly *library, enum stela_air_fp_profile fp, const char *label, bool semantic) +{ + const struct {unsigned sm, cls;} targets[] = {{75,TURING_COMPUTE_A},{80,AMPERE_COMPUTE_A},{86,AMPERE_COMPUTE_B}, + {87,AMPERE_COMPUTE_B},{89,ADA_COMPUTE_A},{90,HOPPER_COMPUTE_A},{100,BLACKWELL_COMPUTE_A}, + {104,BLACKWELL_COMPUTE_A},{120,BLACKWELL_COMPUTE_B}}; + for (unsigned i = 0; i < ARRAY_SIZE(targets); i++) { + struct nv_device_info device = model(targets[i].sm, targets[i].cls); struct nak_compiler *nak = compiler(&device); + struct stela_nv_air_options opts = options(); opts.fp_profile = fp; + struct stela_nv_air_compilation *owner = compile(&device, nak, library, 0, &opts, STELA_NV_AIR_OK); + validate(&device, nak, library, owner, label, semantic); nak_compiler_destroy(nak); + nir_validate_shader((nir_shader *)stela_nv_air_nir(owner), "owned options after compiler destruction"); destroy(&owner); + } +} +static void pack_failures(struct stela_nv_air_compilation *owner, const struct nv_device_info *device) +{ + uint32_t count, table_bytes; const struct stela_nv_air_binding *map = stela_nv_air_bindings(owner, &count, &table_bytes); + CHECK(count == 1); + struct stela_nv_air_buffer_view good = {.device=device,.owner=&good,.argument=map[0].buffer.argument,.index=map[0].buffer.index, + .available_access=STELA_AIR_READ_WRITE,.allocation_va=0x100000,.allocation_bytes=4096,.offset=256,.bytes=2048}; + uint8_t output[2048], expected[sizeof(output)]; memset(expected, 0xa5, sizeof(expected)); + for (unsigned i = 0; i < 14; i++) { + struct stela_nv_air_buffer_view bad = good; + switch(i) { + case 0: bad.argument++; break; case 1: bad.index++; break; case 2: bad.device=NULL; break; + case 3: bad.owner=NULL; break; case 4: bad.available_access=STELA_AIR_READ; break; + case 5: bad.available_access=7; break; case 6: bad.bytes=0; break; case 7: bad.bytes=4097; break; + case 8: bad.offset=4097; break; case 9: bad.allocation_va=UINT64_MAX; break; + case 10: bad.allocation_bytes=UINT64_MAX; break; case 11: bad.offset=1; break; + case 12: bad.allocation_va=(UINT64_C(1)<<40)-2048; break; case 13: bad.bytes=1; break; + } + memcpy(output, expected, sizeof(output)); + CHECK(stela_nv_air_pack_arguments(owner, device, 40, &bad, 1, output, sizeof(output)) == STELA_NV_AIR_BINDING && + !memcmp(output, expected, sizeof(output))); + } + memcpy(output, expected, sizeof(output)); + CHECK(stela_nv_air_pack_arguments(owner, device, 40, &good, 1, output, table_bytes-1) == STELA_NV_AIR_BINDING && + !memcmp(output, expected, sizeof(output))); + CHECK(stela_nv_air_pack_arguments(owner, device, 40, &good, 0, output, sizeof(output)) == STELA_NV_AIR_BINDING); + CHECK(stela_nv_air_pack_arguments(owner, device, 0, &good, 1, output, sizeof(output)) == STELA_NV_AIR_INVALID); + CHECK(stela_nv_air_pack_arguments(owner, device, 64, &good, 1, output, sizeof(output)) == STELA_NV_AIR_INVALID); +} +static void selected_and_binding_tests(void) +{ + struct nv_device_info device=model(89,ADA_COMPUTE_A); struct nak_compiler *nak=compiler(&device); + struct stela_nv_air_options opts=options(); + const char *metadata="}\n!air.version = !{!0}\n!air.language_version = !{!1}\n" + "!air.kernel = !{!2,!7}\n!0 = !{i32 2, i32 8, i32 0}\n" + "!1 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!2 = !{ptr @kernel, !3, !4}\n" + "!3 = !{}\n!4 = !{!5,!6}\n!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 13, i32 1, !\"air.write\"," + " !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"result\"}\n!7 = !{ptr @other, !3, !4}\n"; + LLVMMemoryBufferRef air=stela_air_test_custom_bitcode(stela_air_test_prefix, + "store i32 11, ptr addrspace(1) %out, align 4\nret void\n",metadata, + "define void @other(i32 %tid, ptr addrspace(1) %out) {\nstore i32 99, ptr addrspace(1) %out, align 4\nret void\n}\n"); + struct stela_metal_assembly *library=two_entries(air); LLVMDisposeMemoryBuffer(air); + struct stela_nv_air_compilation *owner=compile(&device,nak,library,1,&opts,STELA_NV_AIR_OK); + const struct stela_nv_air_provenance *p=stela_nv_air_provenance(owner); + CHECK(p->selected_entry==1&&!strcmp(p->name,"other")&&p->input.entry_count==2&& + p->arguments[1].buffer.index==13&&p->arguments[1].buffer.access==STELA_AIR_WRITE&& + !p->arguments[0].name&&!p->arguments[0].name_bytes); + validate(&device,nak,library,owner,"selected-second-entry",false); + unsigned stores=0; + nir_foreach_function_impl(impl,(nir_shader *)stela_nv_air_nir(owner)) { + nir_foreach_block(block,impl) { + nir_foreach_instr(instr,block) { + if(instr->type!=nir_instr_type_intrinsic)continue; + nir_intrinsic_instr *intr=nir_instr_as_intrinsic(instr); + if(intr->intrinsic==nir_intrinsic_store_global||intr->intrinsic==nir_intrinsic_store_global_nv) { + CHECK(nir_src_is_const(intr->src[0])&&nir_src_as_uint(intr->src[0])==99);stores++; + } + } + } + } + CHECK(stores==1); + stela_metal_assembly_destroy(&library); + CHECK(!strcmp(p->name,"other")&&!strcmp(p->arguments[1].name,"result")); + destroy(&owner); + air=multibuffer(2); library=fixture(air); LLVMDisposeMemoryBuffer(air); + /* Distinct compiled owners coexist, with independently stable NIR options. + * Both extreme legal cbuf slots and genuine3D specialization reach QMD. */ + opts.argument_cbuf=0; opts.workgroup_size[0]=4;opts.workgroup_size[1]=2;opts.workgroup_size[2]=2; + owner=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); + opts.argument_cbuf=7; + struct stela_nv_air_compilation *other=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); + validate(&device,nak,library,other,"slot-seven-3d",true); destroy(&other); + validate(&device,nak,library,owner,"slot-zero-after-other-owner-destroy",true); + uint32_t count,extent;const struct stela_nv_air_binding *map=stela_nv_air_bindings(owner,&count,&extent);CHECK(count==2); + struct stela_nv_air_buffer_view views[2]; + for(unsigned i=0;i<2;i++) views[i]=(struct stela_nv_air_buffer_view){.device=&device,.owner=&views[i], + .argument=map[i].buffer.argument,.index=map[i].buffer.index,.available_access=STELA_AIR_READ_WRITE, + .allocation_va=0x100000,.allocation_bytes=4096,.bytes=4096}; + uint8_t table[64],expected[64];memset(expected,0xa5,sizeof(expected));memcpy(table,expected,sizeof(table)); + views[1].argument=views[0].argument;views[1].index=views[0].index; + CHECK(stela_nv_air_pack_arguments(owner,&device,40,views,2,table,sizeof(table))==STELA_NV_AIR_BINDING&&!memcmp(table,expected,sizeof(table))); + views[1].argument=map[1].buffer.argument;views[1].index=map[1].buffer.index; + /* Resource aliasing is permitted by this plain-buffer ABI; it is not + * interpreted as a duplicate metadata key or a new ownership guarantee. */ + CHECK(stela_nv_air_pack_arguments(owner,&device,40,views,2,table,sizeof(table))==STELA_NV_AIR_OK&&get64(table)==get64(table+8)); + struct nv_device_info mismatch=device;mismatch.cls_compute=AMPERE_COMPUTE_B; + memcpy(table,expected,sizeof(table)); + CHECK(stela_nv_air_pack_arguments(owner,&mismatch,40,views,2,table,sizeof(table))==STELA_NV_AIR_DEVICE&&!memcmp(table,expected,sizeof(table))); + destroy(&owner);stela_metal_assembly_destroy(&library);nak_compiler_destroy(nak); +} +static void original_tests(void) +{ + selected_and_binding_tests(); + LLVMMemoryBufferRef air = stela_air_test_bitcode(stela_air_test_store_body, ""); + struct stela_metal_assembly *library = fixture(air); LLVMDisposeMemoryBuffer(air); + targets(library, STELA_AIR_FP_IEEE_DEFAULT, "original-integer", false); + struct nv_device_info device = model(89, ADA_COMPUTE_A); struct nak_compiler *nak = compiler(&device); + struct stela_nv_air_options opts=options(); struct stela_nv_air_compilation *owner=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); + pack_failures(owner,&device); + const struct stela_nv_air_provenance *p=stela_nv_air_provenance(owner); + const struct stela_metal_library_manifest *m=stela_metal_assembly_manifest(library); + CHECK(!memcmp(&p->input,&m->input,sizeof(p->input)) && !memcmp(&p->entry,&m->entries[0].entry,sizeof(p->entry)) && + !memcmp(p->air_sha256,m->entries[0].air_sha256,32) && p->air_offset==m->entries[0].air_offset && + p->arguments[1].name!=m->entries[0].arguments[1].name && !strcmp(p->arguments[1].name,m->entries[0].arguments[1].name)); + stela_metal_assembly_destroy(&library); nak_compiler_destroy(nak); + CHECK(!strcmp(p->name,"kernel") && !strcmp(p->arguments[1].type_name,"uint")); + nir_validate_shader((nir_shader *)stela_nv_air_nir(owner),"after all input/compiler storage destruction"); + destroy(&owner); + for(unsigned buffers=0;buffers<=31;buffers++) { + air=multibuffer(buffers); library=fixture(air); LLVMDisposeMemoryBuffer(air); + targets(library,STELA_AIR_FP_IEEE_DEFAULT,"generic-buffer-indices",true); stela_metal_assembly_destroy(&library); + } + air=stela_air_test_bitcode("ret void\n", ""); library=fixture(air); LLVMDisposeMemoryBuffer(air); + targets(library,STELA_AIR_FP_IEEE_DEFAULT,"unused-buffer-no-effects",true); stela_metal_assembly_destroy(&library); + air=stela_air_test_bitcode(stela_air_test_store_body, ""); library=fixture(air); LLVMDisposeMemoryBuffer(air); nak=compiler(&device); + struct stela_nv_air_options bad=opts; bad.max_code_bytes=4; CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_LIMIT)); + bad=opts; bad.max_instructions=1; CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_FRONTEND)); + bad=opts; bad.argument_cbuf=8; CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + bad=opts; bad.workgroup_size[2]=65; CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + bad=opts; bad.fp_profile=(enum stela_air_fp_profile)99; CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + struct nv_device_info mismatch=device; mismatch.sm=86; CHECK(!compile(&mismatch,nak,library,0,&opts,STELA_NV_AIR_DEVICE)); + mismatch=device; mismatch.max_warps_per_mp--; CHECK(!compile(&mismatch,nak,library,0,&opts,STELA_NV_AIR_DEVICE)); + CHECK(!compile(&device,nak,library,1,&opts,STELA_NV_AIR_INVALID)); + bad=opts;bad.size--;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_INVALID)); + bad=opts;bad.abi++;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_INVALID)); + bad=opts;bad.max_code_bytes=0;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_LIMIT)); + bad=opts;bad.max_code_bytes=UINT32_MAX;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_LIMIT)); + bad=opts;bad.record_assembly=2;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + bad=opts;bad.workgroup_size[0]=0;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + bad=opts;bad.workgroup_size[0]=1024;bad.workgroup_size[1]=2;CHECK(!compile(&device,nak,library,0,&bad,STELA_NV_AIR_UNSUPPORTED)); + mismatch=device;mismatch.sm_smem_size_count=0;CHECK(!compile(&mismatch,nak,library,0,&opts,STELA_NV_AIR_DEVICE)); + mismatch=device;mismatch.sm_smem_sizes_kB[1]++;CHECK(!compile(&mismatch,nak,library,0,&opts,STELA_NV_AIR_DEVICE)); + mismatch=device;mismatch.sm_smem_sizes_kB[1]=mismatch.sm_smem_sizes_kB[0];CHECK(!compile(&mismatch,nak,library,0,&opts,STELA_NV_AIR_DEVICE)); + owner=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); + struct stela_nv_air_compilation *retained=owner;struct stela_nv_air_error error; + CHECK(stela_nv_air_compile(&device,nak,library,0,&opts,&owner,&error)==STELA_NV_AIR_INVALID&&owner==retained); + CHECK(stela_nv_air_compile(NULL,nak,library,0,&opts,&owner,&error)==STELA_NV_AIR_INVALID&&owner==retained); + destroy(&owner); + bad=opts;bad.record_assembly=0;owner=compile(&device,nak,library,0,&bad,STELA_NV_AIR_OK); + CHECK(!stela_nv_air_binary(owner)->asm_str);validate(&device,nak,library,owner,"without-assembly-text",false);destroy(&owner); +#ifdef STELA_NV_AIR_ALLOC_TEST + allocations=0; owner=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); CHECK(allocations==2); destroy(&owner); + for(unsigned fail=1;fail<=2;fail++) { allocations=0;fail_allocation=fail;CHECK(!compile(&device,nak,library,0,&opts,STELA_NV_AIR_ALLOCATION)&&!live_allocations); } + fail_allocation=0; +#endif + stela_metal_assembly_destroy(&library); + air=stela_air_test_bitcode("call void @unsupported()\nret void\n","declare void @unsupported()\n"); + library=fixture(air);LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&device,nak,library,0,&opts,STELA_NV_AIR_FRONTEND)); + stela_metal_assembly_destroy(&library); + /* Complete dynamic AS3 reflection reaches this owner's explicit missing + * dispatch-specialization refusal, rather than the canonical inspector's + * separate refusal for incomplete module-global reflection. */ + air=stela_air_test_custom_bitcode( + "target datalayout = \"e-p:64:64-i64:64-n8:16:32\"\n" + "target triple = \"air64_v29-apple-macosx27.2.0\"\n" + "define void @kernel(i32 %tid, ptr addrspace(3) %scratch) {\n", + "store i32 %tid, ptr addrspace(3) %scratch, align 4\nret void\n", + "}\n!air.version = !{!0}\n!air.language_version = !{!1}\n!air.kernel = !{!2}\n" + "!0 = !{i32 2, i32 9, i32 0}\n!1 = !{!\"Metal\", i32 4, i32 1, i32 0}\n" + "!2 = !{ptr @kernel, !3, !4}\n!3 = !{}\n!4 = !{!5,!6}\n" + "!5 = !{i32 0, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"tid\"}\n" + "!6 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 7, i32 1, !\"air.read_write\"," + " !\"air.address_space\", i32 3, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4," + " !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"scratch\"}\n",""); + struct bytes shared=archive(LLVMGetBufferStart(air),LLVMGetBufferSize(air),"kernel",9,4,1,27,2); + library=assemble(&shared);free(shared.data);LLVMDisposeMemoryBuffer(air); + CHECK(!compile(&device,nak,library,0,&opts,STELA_NV_AIR_UNSUPPORTED)); + nak_compiler_destroy(nak); stela_metal_assembly_destroy(&library); + CHECK(!stela_nv_air_binary(NULL)&&!stela_nv_air_nir(NULL)&&!stela_nv_air_provenance(NULL)); + puts("owned NAK compiler/table/QMD/lifetime/failure fixtures passed; no hardware execution"); +} +static struct bytes read_file(const char *path) +{ + FILE *f=fopen(path,"rb");CHECK(f&&!fseek(f,0,SEEK_END));long size=ftell(f); + CHECK(size>0&&size<=AIR_MAX_BITCODE_BYTES&&!fseek(f,0,SEEK_SET)); + struct bytes b={.data=malloc((size_t)size),.size=(size_t)size};CHECK(b.data); + CHECK(fread(b.data,1,b.size,f)==b.size&&fgetc(f)==EOF&&!ferror(f)&&!fclose(f));return b; +} +struct facts {const char *name;unsigned air,major,minor,osmajor,osminor;bool found;}; +static bool inspect(const struct stela_air_inspection *i,const struct stela_air_entry *e,void *data) +{ + struct facts *f=data;if(strlen(f->name)!=e->name_bytes||memcmp(f->name,e->name,e->name_bytes))return true; + f->found=true;f->air=i->air_minor;f->major=i->language_major;f->minor=i->language_minor; + CHECK(sscanf(i->target,"air64_v%*u-apple-macosx%u.%u.",&f->osmajor,&f->osminor)==2);return true; +} +static void source_input(int argc,char **argv) +{ + CHECK(argc==5); /* --source ORIGINAL_MSL ORIGINAL_ADAPTER_AIR INDEPENDENT_IDENTITY_208_BYTES */ + struct bytes source=read_file(argv[2]),air=read_file(argv[3]),identity=read_file(argv[4]);CHECK(identity.size==208); + struct stela_msl_output compiled={.air=air.data,.air_bytes=air.size}; + memcpy(compiled.source_sha256,identity.data,32);memcpy(compiled.air_sha256,identity.data+32,32); + memcpy(&compiled.build,identity.data+64,sizeof(compiled.build)); + struct stela_msl_apple_config config=stela_msl_apple_default_config(); + struct stela_msl_request request={.source=source.data,.source_bytes=source.size,.language_version=0x40001, + .fast_math=true,.target_triple="air64_v29-apple-macosx27.2.0"}; + struct stela_metal_assembly_options assembly_options=stela_metal_assembly_default_options(); + struct stela_metal_assembly_error error;struct stela_metal_assembly *library=NULL; + CHECK(stela_metal_assemble_source(&assembly_options,&config,&request,&compiled,&library,&error)==STELA_METAL_ASSEMBLY_OK); + struct nv_device_info device=model(89,ADA_COMPUTE_A);struct nak_compiler *nak=compiler(&device); + struct stela_nv_air_options opts=options();opts.fp_profile=STELA_AIR_FP_APPLE_32023_922_AIR29_MSL41; + struct stela_nv_air_compilation *owner=compile(&device,nak,library,0,&opts,STELA_NV_AIR_OK); + validate(&device,nak,library,owner,"original-source-owner",false); + free(air.data);free(source.data);stela_metal_assembly_destroy(&library);nak_compiler_destroy(nak); + const struct stela_nv_air_provenance *p=stela_nv_air_provenance(owner); + CHECK(p->library_flags==STELA_METAL_LIBRARY_SOURCE_COMPILED&&p->compiler_profile==config.profile&& + p->request_language==0x40001&&p->request_fast_math==1&& + !memcmp(p->source_sha256,identity.data,32)&&!memcmp(p->input.original_sha256,identity.data+32,32)&& + !memcmp(&p->build,identity.data+64,sizeof(p->build))); + free(identity.data);nir_validate_shader((nir_shader *)stela_nv_air_nir(owner),"source owner after input/compiler destruction");destroy(&owner); +} +static void requested_threadgroups(int argc,char **argv,struct stela_metal_threadgroup_request_row *rows) +{ + CHECK(argc>=6&&argc-5<=(int)AIR_MAX_ARGUMENTS); + for(int i=5;i='0'&&argv[i][0]<='9'); + unsigned long long index=strtoull(argv[i],&end,10);CHECK(!errno&&index<=UINT32_MAX&&*end==':'); + const char *start=end+1;CHECK(*start>='0'&&*start<='9');errno=0; + unsigned long long bytes=strtoull(start,&end,10);CHECK(!errno&&!*end); + rows[i-5]=(struct stela_metal_threadgroup_request_row){.index=(uint32_t)index,.bytes=(uint64_t)bytes}; + } +} +static void threadgroup_input(int argc,char **argv) +{ + struct stela_metal_threadgroup_request_row rows[AIR_MAX_ARGUMENTS]={0};requested_threadgroups(argc,argv,rows); + char *end;errno=0;unsigned long workgroup=strtoul(argv[4],&end,10);CHECK(!errno&&!*end&&workgroup&&workgroup<=1024); + struct stela_metal_threadgroup_request request={.size=sizeof(request),.abi=STELA_METAL_THREADGROUP_ABI, + .count=(uint32_t)(argc-5),.rows=rows}; + struct bytes air=read_file(argv[2]);struct facts f={.name=argv[3]};struct stela_air_error air_error; + CHECK(stela_air_inspect(air.data,air.size,256,inspect,&f,&air_error)&&f.found); + struct bytes bytes=archive(air.data,air.size,f.name,f.air,f.major,f.minor,f.osmajor,f.osminor); + struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data); + const struct {unsigned sm,cls;} targets[]={{75,TURING_COMPUTE_A},{80,AMPERE_COMPUTE_A},{86,AMPERE_COMPUTE_B}, + {87,AMPERE_COMPUTE_B},{89,ADA_COMPUTE_A},{90,HOPPER_COMPUTE_A},{100,BLACKWELL_COMPUTE_A}, + {104,BLACKWELL_COMPUTE_A},{120,BLACKWELL_COMPUTE_B}}; + for(unsigned i=0;ithreadgroup.count==request.count&&stela_metal_threadgroup_matches(&p->threadgroup,&request)); + struct stela_metal_threadgroup_request_row saved[AIR_MAX_ARGUMENTS];memcpy(saved,rows,sizeof(rows)); + rows[0].bytes+=16;CHECK(!stela_metal_threadgroup_matches(&p->threadgroup,&request)); + memset(rows,0,sizeof(rows)); + CHECK(p->threadgroup.bindings[0].bytes&&p->threadgroup.bindings[0].alignment>=16); + memcpy(rows,saved,sizeof(rows));CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request)); + validate(&device,nak,library,owner,"dispatch-threadgroup-specialization",false); + printf("owned-threadgroup-nak sm=%u count=%u total_shared=%u",device.sm,p->threadgroup.count,stela_nv_air_binary(owner)->info.cs.smem_size); + for(unsigned r=0;rthreadgroup.count;r++)printf(" row=%u:%u:%llu:%u",p->threadgroup.bindings[r].buffer.argument, + p->threadgroup.bindings[r].buffer.index,(unsigned long long)p->threadgroup.bindings[r].bytes,p->threadgroup.bindings[r].alignment); + puts(""); + nak_compiler_destroy(nak);nir_validate_shader((nir_shader *)stela_nv_air_nir(owner),"dynamic options after compiler destruction"); + CHECK(stela_metal_threadgroup_matches(&p->threadgroup,&request));destroy(&owner); + } + stela_metal_assembly_destroy(&library); +} +static void shared_refusal(int argc,char **argv) +{ + CHECK(argc==4); + struct bytes air=read_file(argv[2]);struct facts f={.name=argv[3]};struct stela_air_error inspect_error; + CHECK(stela_air_inspect(air.data,air.size,256,inspect,&f,&inspect_error)&&f.found); + struct bytes bytes=archive(air.data,air.size,f.name,f.air,f.major,f.minor,f.osmajor,f.osminor); + struct stela_metal_assembly *library=assemble(&bytes);free(bytes.data);free(air.data); + const struct {unsigned sm,cls;} targets[]={{75,TURING_COMPUTE_A},{80,AMPERE_COMPUTE_A},{86,AMPERE_COMPUTE_B}, + {87,AMPERE_COMPUTE_B},{89,ADA_COMPUTE_A},{90,HOPPER_COMPUTE_A},{100,BLACKWELL_COMPUTE_A}, + {104,BLACKWELL_COMPUTE_A},{120,BLACKWELL_COMPUTE_B}}; + for(unsigned i=0;i= 8448; + const size_t local = output ? byte - 8448 : byte; + NvU16 value; + if (local >= array_bytes) + return 0; + value = value_at(output, local / 8, (local % 8) / 2); + return (NvU8)(value >> ((local % 2) * 8)); +} + +int main(void) +{ + static _Alignas(16) NvU8 destination[16896 + 32]; + NVSurfaceEvoRec surface = {0}; + NVDispEvoRec display = {0}; + NVEvoLutDataRec *p; + size_t i; + const size_t entries = NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES; + + stela_nvkms_test_heap_initialize(); + if (stela_nvkms_test_heap_live() != 0) + return 1; + p = nvInternalAlloc(sizeof(*p), TRUE); + if (p == NULL || sizeof(nvkms_memory_info_t) != 8 || + offsetof(nvkms_memory_info_t, data) != 8 || + (NvU8 *)p - (NvU8 *)allocation != 8 || + allocation_bytes != sizeof(*p) + 8 || + ((NvUPtr)p & 15) != 8 || ((NvUPtr)p & 255) == 0 || + ((NvUPtr)p & 3) != 0) + return 2; + for (i = 0; i < sizeof(*p); i++) { + if (((const NvU8 *)p)[i] != 0) + return 3; + } + for (i = 0; i < entries; i++) { + p->base[i].Red = value_at(0, i, 0); + p->base[i].Green = value_at(0, i, 1); + p->base[i].Blue = value_at(0, i, 2); + p->base[i].Unused = value_at(0, i, 3); + p->output[i].Red = value_at(1, i, 0); + p->output[i].Green = value_at(1, i, 1); + p->output[i].Blue = value_at(1, i, 2); + p->output[i].Unused = value_at(1, i, 3); + } + nvkms_memset(destination, 0xa5, sizeof(destination)); + surface.cpuAddress[0] = destination + 16; + surface.planes[0].rmObjectSizeInBytes = sizeof(*p); + display.displayOwner = 0; + nvUploadDataToLutSurfaceEvo(&surface, p, &display); + for (i = 0; i < sizeof(*p); i++) { + if (((const NvU8 *)p)[i] != expected_at(i) || + destination[16 + i] != expected_at(i)) + return 4; + } + for (i = 0; i < 16; i++) { + if (destination[i] != 0xa5 || destination[16 + sizeof(*p) + i] != 0xa5) + return 5; + } + nvInternalFree(p); + if (allocated != 1 || freed != 1 || invalid_free != 0 || + stela_nvkms_test_heap_live() != 0) + return 6; + return 0; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_heap.rs b/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_heap.rs new file mode 100644 index 0000000000..c191e8fd45 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_heap.rs @@ -0,0 +1,41 @@ +//! CPU fixture only: the actual common heap and metadata adapter, with a +//! process-owned host buffer. This is never linked into the production driver. +#![no_std] +#![allow(dead_code)] +extern crate alloc; + +#[path = "../../../../../../stela-boot/src/heap.rs"] +mod common_heap; +#[path = "../../memory.rs"] +mod nvidia_memory; + +#[global_allocator] +static HEAP: common_heap::Heap = common_heap::Heap::new(); + +#[repr(align(4096))] +struct Buffer([u8; 128 * 1024]); +static mut BUFFER: Buffer = Buffer([0; 128 * 1024]); + +/// # Safety +/// The separate single-thread CPU fixture calls once before any allocation; +/// no aliases, interrupts, migration or concurrent users reach its buffer. +#[unsafe(no_mangle)] +unsafe extern "C" fn stela_nvkms_test_heap_initialize() { + // SAFETY: the fixture owns the full aligned static buffer for its lifetime. + unsafe { HEAP.initialize(core::ptr::addr_of_mut!(BUFFER).cast(), size_of::()) }; +} + +#[unsafe(no_mangle)] +extern "C" fn stela_nvkms_test_heap_live() -> usize { + HEAP.usage().live +} + +#[panic_handler] +fn fixture_panic(_: &core::panic::PanicInfo) -> ! { + unsafe extern "C" { + fn abort() -> !; + } + // SAFETY: actual host C runtime termination for this separate CPU fixture. + // No NVIDIA fatal, purecall, thunk or production runtime hook is supplied. + unsafe { abort() } +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_layout.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_layout.c new file mode 100644 index 0000000000..ebb7d7ae8d --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/lut_layout.c @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: MIT */ +/* Compile as C11 and C++11 with the real NVKMS header for each native/host + * ABI. These constants freeze the retained GPU byte layout independently of + * the ordinary CPU alignment. This fixture supplies no platform services. + */ +#include "nvkms-types.h" + +#ifdef __cplusplus +extern "C" { +extern const NvU64 stela_nvkms_lut_layout[]; +extern const char *const stela_nvkms_lut_layout_labels[]; +extern const NvU64 stela_nvkms_lut_layout_count; +#endif + +#define STELA_LUT_LAYOUT(M) \ + M("sizeof(NVEvoLutEntryRec)", sizeof(NVEvoLutEntryRec)) \ + M("alignof(NVEvoLutEntryRec)", NV_ALIGNOF(NVEvoLutEntryRec)) \ + M("sizeof(NVEvoLutDataRec)", sizeof(NVEvoLutDataRec)) \ + M("alignof(NVEvoLutDataRec)", NV_ALIGNOF(NVEvoLutDataRec)) \ + M("offsetof(base)", offsetof(NVEvoLutDataRec, base)) \ + M("offsetof(output)", offsetof(NVEvoLutDataRec, output)) \ + M("sizeof(base)", sizeof(((NVEvoLutDataRec *)0)->base)) \ + M("sizeof(output)", sizeof(((NVEvoLutDataRec *)0)->output)) \ + M("sizeof(baseSlotStorage)", sizeof(((NVEvoLutDataRec *)0)->baseSlotStorage)) \ + M("sizeof(outputSlotStorage)", sizeof(((NVEvoLutDataRec *)0)->outputSlotStorage)) + +#define STELA_LUT_VALUE(label, value) (NvU64)(value), +const NvU64 stela_nvkms_lut_layout[] = { STELA_LUT_LAYOUT(STELA_LUT_VALUE) }; +#undef STELA_LUT_VALUE +#define STELA_LUT_LABEL(label, value) label, +const char *const stela_nvkms_lut_layout_labels[] = { STELA_LUT_LAYOUT(STELA_LUT_LABEL) }; +#undef STELA_LUT_LABEL +const NvU64 stela_nvkms_lut_layout_count = + sizeof(stela_nvkms_lut_layout) / sizeof(stela_nvkms_lut_layout[0]); + +ct_assert(sizeof(NVEvoLutDataRec) == 16896); +ct_assert(offsetof(NVEvoLutDataRec, base) == 0); +ct_assert(offsetof(NVEvoLutDataRec, output) == 8448); +ct_assert(sizeof(((NVEvoLutDataRec *)0)->base) == 8232); +ct_assert(sizeof(((NVEvoLutDataRec *)0)->output) == 8232); +ct_assert(NV_ALIGNOF(NVEvoLutDataRec) == 2); + +void stela_nvkms_lut_first_entry_store(NVEvoLutDataRec *p, NvU16 value); +void stela_nvkms_lut_first_entry_store(NVEvoLutDataRec *p, NvU16 value) +{ + p->output[0].Red = value; +} + +#ifdef __cplusplus +} +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/mmio.rs b/crates/stela-drivers/src/gpu/nvidia/stela/tests/mmio.rs new file mode 100644 index 0000000000..64d611040f --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/mmio.rs @@ -0,0 +1,732 @@ +//! CPU-only original-C-ABI integration model; never maps hardware or a PA cast. +use std::{ + cell::UnsafeCell, + ffi::c_void, + pin::Pin, + ptr::{self, NonNull}, + sync::{ + Arc, Barrier, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; +use stela_drivers::{ + bus::mmio::owned::{ + AddressSpace, Authority, CacheAttribute, Error as MappingError, ExistingAlias, + InstalledMapping, MapFailure, MapRequest, MappingPlatform, PhysicalSpan, Protection, + Resource, ResourceBacking, ResourceKind, + }, + gpu::nvidia::mmio::{Error, MmioServices}, +}; + +const PAGE: u64 = 4096; +const BASE: u64 = 0x800000; +const PREFETCH: u64 = 0x900000; +const PARTIAL: u64 = 0xa00000; +const SPACE: AddressSpace = AddressSpace { + identity: 31, + physical_bits: 48, + virtual_bits: 48, +}; + +unsafe extern "C" { + fn os_map_kernel_space(physical: u64, bytes: u64, mode: u32) -> *mut c_void; + fn os_unmap_kernel_space(address: *mut c_void, bytes: u64); +} + +#[repr(align(4096))] +struct Pages([u8; 65536]); +struct Window(UnsafeCell); +// SAFETY: model memory is accessed only as raw bytes while an exclusive mapping +// lease is live. Mutex-protected model bookkeeping does not create references +// to mapped bytes. The test drains all uses before acknowledged unmap. +unsafe impl Send for Window {} +unsafe impl Sync for Window {} +struct Backing { + span: PhysicalSpan, + kind: ResourceKind, + window: Arc, + dropped: Arc, +} +// SAFETY: each immutable model reservation owns a distinct aligned allocation +// and isolated physical interval. There is no firmware, physical map or device. +unsafe impl ResourceBacking for Backing { + fn physical_span(&self) -> PhysicalSpan { + self.span + } + fn kind(&self) -> ResourceKind { + self.kind + } +} +impl Drop for Backing { + fn drop(&mut self) { + self.dropped.fetch_add(1, Ordering::Relaxed); + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Mode { + Normal, + Unchanged, + Uncertain, + WrongCache, + RefuseWc, +} +struct Installed { + request: MapRequest, + cpu: usize, + window: Arc, +} +struct State { + installed: Vec, + mode: Mode, + calls: usize, + unmaps: usize, + ack: bool, + busy_unmap: bool, + reenter: Option<(u64, usize, u64)>, + map_gates: Option<(Arc, Arc)>, +} +struct Model { + state: Mutex, + allowed: AtomicBool, +} +impl Model { + fn new() -> Arc { + Arc::new(Self { + state: Mutex::new(State { + installed: Vec::new(), + mode: Mode::Normal, + calls: 0, + unmaps: 0, + ack: true, + busy_unmap: false, + reenter: None, + map_gates: None, + }), + allowed: AtomicBool::new(true), + }) + } + fn calls(&self) -> (usize, usize, usize) { + let state = self.state.lock().unwrap(); + (state.calls, state.unmaps, state.installed.len()) + } + fn mode(&self, mode: Mode) { + self.state.lock().unwrap().mode = mode; + } + fn reenter(&self) { + let reenter = self.state.lock().unwrap().reenter.take(); + if let Some((physical, address, bytes)) = reenter { + // SAFETY: deliberately model native callback reentry while the + // adapter's entry guard is held; neither nested call may act. + unsafe { + assert!(os_map_kernel_space(physical, bytes, 1).is_null()); + os_unmap_kernel_space(address as *mut c_void, bytes); + } + } + } +} +// SAFETY: model maps genuine retained allocations, never physical addresses as +// pointers. It preserves the request and exact aligned CPU range through ack. +// Fault modes intentionally return malformed/uncertain replies for refusal tests. +unsafe impl MappingPlatform for Model { + fn check_context(&self, space: AddressSpace) -> Result<(), MappingError> { + if space == SPACE && self.allowed.load(Ordering::Acquire) { + Ok(()) + } else { + Err(MappingError::Unavailable) + } + } + unsafe fn map( + &self, + resource: &Resource, + request: MapRequest, + ) -> Result { + let backing = resource.backing().downcast_ref::().unwrap(); + assert_eq!(request.address_space, SPACE); + assert_eq!(request.physical.start() % PAGE, 0); + assert_eq!(request.physical.bytes() % PAGE, 0); + assert!(request.physical.start() >= backing.span.start()); + assert!(request.physical.end() <= backing.span.end()); + assert_eq!(request.protection, Protection::ReadWrite); + let (mode, gates) = { + let mut state = self.state.lock().unwrap(); + state.calls += 1; + (state.mode, state.map_gates.take()) + }; + self.reenter(); + if mode == Mode::Unchanged { + return Err(MapFailure::Unchanged(MappingError::MappingFailed)); + } + if mode == Mode::RefuseWc && request.attribute == CacheAttribute::WriteCombining { + return Err(MapFailure::Unchanged(MappingError::UnsupportedCache)); + } + let offset = (request.physical.start() - backing.span.start()) as usize; + // SAFETY: actual pinned model allocation, full request bounds checked + // against its immutable physical reservation; never derive VA from PA. + let cpu = unsafe { + ptr::addr_of_mut!((*backing.window.0.get()).0) + .cast::() + .add(offset) + }; + let reply = InstalledMapping { + token: request.id, + cpu_base: NonNull::new(cpu).unwrap(), + physical: request.physical, + attribute: if mode == Mode::WrongCache { + CacheAttribute::WriteBack + } else { + request.attribute + }, + protection: request.protection, + }; + self.state.lock().unwrap().installed.push(Installed { + request, + cpu: cpu as usize, + window: Arc::clone(&backing.window), + }); + if let Some((ready, release)) = gates { + ready.wait(); + release.wait(); + } + if mode == Mode::Uncertain { + return Err(MapFailure::Uncertain(MappingError::MappingFailed)); + } + Ok(reply) + } + unsafe fn unmap( + &self, + request: MapRequest, + mapping: InstalledMapping, + ) -> Result<(), MappingError> { + { + let mut state = self.state.lock().unwrap(); + state.unmaps += 1; + let live = state + .installed + .iter() + .find(|live| live.request == request) + .unwrap(); + assert_eq!(mapping.token, request.id); + assert_eq!(mapping.cpu_base.as_ptr() as usize, live.cpu); + assert_eq!(mapping.physical, request.physical); + assert_eq!(mapping.attribute, request.attribute); + assert_eq!(mapping.protection, request.protection); + assert!(Arc::strong_count(&live.window) >= 2); + } + self.reenter(); + let mut state = self.state.lock().unwrap(); + if state.busy_unmap { + return Err(MappingError::Busy); + } + if !state.ack { + return Err(MappingError::UnmapFailed); + } + let at = state + .installed + .iter() + .position(|live| live.request == request) + .unwrap(); + state.installed.swap_remove(at); + Ok(()) // model all-root TLB/write drain acknowledgement + } +} + +fn resource(start: u64, bytes: u64, kind: ResourceKind) -> (Resource, Arc) { + let dropped = Arc::new(AtomicUsize::new(0)); + ( + Resource::new(Box::new(Backing { + span: PhysicalSpan::new(start, bytes).unwrap(), + kind, + window: Arc::new(Window(UnsafeCell::new(Pages([0; 65536])))), + dropped: Arc::clone(&dropped), + })), + dropped, + ) +} + +fn rejected( + services: &Pin>, + model: &Model, + physical: u64, + bytes: u64, + mode: u32, + expected: MappingError, + provider_called: bool, +) { + let before = services.status(); + let calls = model.calls(); + // SAFETY: retained installed service/model, serialized process-context call. + assert!(unsafe { os_map_kernel_space(physical, bytes, mode) }.is_null()); + assert_eq!(services.status().live, before.live); + assert_eq!(services.status().failed_maps, before.failed_maps + 1); + assert_eq!( + services.status().last_failure, + Some(Error::Mapping(expected)) + ); + assert_eq!(model.calls().0, calls.0 + usize::from(provider_called)); +} + +#[test] +fn original_global_abi_retains_real_canonical_leases_and_quarantines_failures() { + // Separate integration process preserves canonical production singleton. + // SAFETY: no installed services; hooks must refuse without a provider call. + unsafe { + assert!(os_map_kernel_space(BASE, PAGE, 1).is_null()); + os_unmap_kernel_space(ptr::null_mut(), PAGE); + } + let model = Model::new(); + // SAFETY: isolated CPU model machine, complete alias inventory, genuine + // retained backing and explicit all-root/cache/context acknowledgements. + let authority = unsafe { + Authority::activate( + model.clone(), + SPACE, + vec![ + ExistingAlias { + physical: PhysicalSpan::new(BASE + 4 * PAGE, PAGE).unwrap(), + attribute: Some(CacheAttribute::WriteBack), + }, + ExistingAlias { + physical: PhysicalSpan::new(BASE + 5 * PAGE, PAGE).unwrap(), + attribute: None, + }, + ExistingAlias { + physical: PhysicalSpan::new(BASE + 6 * PAGE, PAGE).unwrap(), + attribute: Some(CacheAttribute::Uncached), + }, + ], + ) + } + .unwrap(); + let (registers, register_drop) = resource(BASE, 16 * PAGE, ResourceKind::Registers); + let register_id = authority.register_resource(registers.clone()).unwrap(); + let (prefetch, prefetch_drop) = resource(PREFETCH, 16 * PAGE, ResourceKind::PrefetchableMemory); + let prefetch_id = authority.register_resource(prefetch).unwrap(); + let (partial, partial_drop) = resource(PARTIAL + 1, PAGE - 2, ResourceKind::Registers); + let partial_id = authority.register_resource(partial).unwrap(); + let mut services = Box::pin(MmioServices::new(authority.clone())); + let mut second = Box::pin(MmioServices::new(authority.clone())); + // SAFETY: pinned services remain alive, serial callbacks in this one test; + // all raw consumers stop before exact unmap and successful uninstall. + unsafe { + services.as_mut().install().unwrap(); + assert_eq!(second.as_mut().install(), Err(Error::AlreadyInstalled)); + assert_eq!(second.as_mut().uninstall(), Err(Error::NotInstalled)); + } + for (physical, bytes) in [(0, PAGE), (BASE, 0), (u64::MAX - 1, 4), (BASE, u64::MAX)] { + rejected( + &services, + &model, + physical, + bytes, + 1, + MappingError::InvalidRange, + false, + ); + } + for mode in [0, 3, 4, 5, 7, u32::MAX] { + rejected( + &services, + &model, + BASE, + PAGE, + mode, + MappingError::UnsupportedCache, + false, + ); + } + for (physical, bytes) in [ + (PARTIAL + 1, 1), + (BASE - 1, 2), + (BASE + 16 * PAGE - 1, 2), + (0xb00000, PAGE), + (BASE, (1u64 << 32) + PAGE), + ] { + rejected( + &services, + &model, + physical, + bytes, + 1, + MappingError::OutsideResource, + false, + ); + } + for page in [4, 5] { + rejected( + &services, + &model, + BASE + page * PAGE + 1, + 1, + 1, + MappingError::CacheConflict, + false, + ); + } + rejected( + &services, + &model, + BASE, + PAGE, + 2, + MappingError::UnsupportedCache, + false, + ); + model.allowed.store(false, Ordering::Release); + rejected( + &services, + &model, + BASE, + PAGE, + 1, + MappingError::Unavailable, + false, + ); + model.allowed.store(true, Ordering::Release); + + // Unaligned logical bytes map only owned rounded pages, preserving offset. + // SAFETY: model storage remains mapped and exclusively raw-accessed. + let address = unsafe { os_map_kernel_space(BASE + 17, 100, 1) }; + assert!(!address.is_null()); + let actual = registers.backing().downcast_ref::().unwrap(); + assert_eq!( + address.cast::(), + actual.window.0.get().cast::().wrapping_add(17) + ); + unsafe { + address.cast::().write_volatile(0x19); + address.cast::().add(99).write_volatile(0xe7); + assert_eq!(address.cast::().read_volatile(), 0x19); + assert_eq!(address.cast::().add(99).read_volatile(), 0xe7); + } + assert_eq!( + model.state.lock().unwrap().installed[0].request.physical, + PhysicalSpan::new(BASE, PAGE).unwrap() + ); + assert_eq!(services.status().live, 1); + assert_eq!( + unsafe { services.as_mut().uninstall() }, + Err(Error::LiveMappings) + ); + rejected( + &services, + &model, + BASE + 1, + 1, + 1, + MappingError::ResourceConflict, + false, + ); + let calls = model.calls(); + for (pointer, bytes) in [ + (address, 99), + (address.wrapping_byte_add(1), 100), + (ptr::null_mut(), 0), + ] { + // SAFETY: invalid keys are never dereferenced or allowed to retire. + unsafe { os_unmap_kernel_space(pointer, bytes) }; + assert_eq!(services.status().live, 1); + assert_eq!(services.status().last_failure, Some(Error::UnknownMapping)); + assert_eq!(model.calls(), calls); + } + // Default is original UC, including a compatible imported raw UC alias. + let default = unsafe { os_map_kernel_space(BASE + 6 * PAGE, PAGE, 6) }; + assert!(!default.is_null()); + assert_eq!( + model.state.lock().unwrap().installed[1].request.attribute, + CacheAttribute::Uncached + ); + model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, address as usize, 100)); + let refused = services.status().refused_calls; + let third = unsafe { os_map_kernel_space(BASE + PAGE, PAGE, 1) }; + assert!(!third.is_null()); + assert_eq!(services.status().refused_calls, refused + 2); + assert_eq!(services.status().live, 3); + model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, address as usize, 100)); + unsafe { os_unmap_kernel_space(third, PAGE) }; + assert_eq!(services.status().refused_calls, refused + 4); + assert_eq!(services.status().live, 2); + unsafe { + os_unmap_kernel_space(default, PAGE); + os_unmap_kernel_space(address, 100); + } + assert_eq!(model.calls().2, 0); + assert_eq!(services.status().live, 0); + let calls = model.calls(); + unsafe { os_unmap_kernel_space(address, 100) }; + assert_eq!(services.status().last_failure, Some(Error::UnknownMapping)); + assert_eq!(model.calls(), calls); + + model.mode(Mode::RefuseWc); + rejected( + &services, + &model, + PREFETCH, + PAGE, + 2, + MappingError::UnsupportedCache, + true, + ); + model.mode(Mode::Normal); + let wc = unsafe { os_map_kernel_space(PREFETCH, PAGE, 2) }; + assert!(!wc.is_null()); + assert_eq!( + model.state.lock().unwrap().installed[0].request.attribute, + CacheAttribute::WriteCombining + ); + unsafe { os_unmap_kernel_space(wc, PAGE) }; + model.mode(Mode::Unchanged); + rejected( + &services, + &model, + BASE + 7 * PAGE, + PAGE, + 1, + MappingError::MappingFailed, + true, + ); + assert_eq!(services.authority_status().unwrap().uncertain, 0); + model.mode(Mode::Normal); + let restored = unsafe { os_map_kernel_space(BASE + 7 * PAGE, PAGE, 1) }; + assert!(!restored.is_null()); + unsafe { os_unmap_kernel_space(restored, PAGE) }; + + // A canonical independent view keeps its actual backing alive; NVIDIA gets + // no alternate authority, widened pointer or safe Rust reference to it. + let mut parent = authority + .map_physical( + PhysicalSpan::new(BASE + 8 * PAGE, PAGE).unwrap(), + CacheAttribute::Uncached, + Protection::ReadWrite, + ) + .unwrap(); + let view = parent.view(17..117).unwrap(); + assert_eq!(view.bytes(), 100); + assert_eq!(unsafe { parent.retire() }, Err(MappingError::Busy)); + drop(view); + unsafe { parent.retire() }.unwrap(); + + // Another real canonical consumer may have a platform map in flight. + // Original void unmap ends raw access now, retaining the same ledger slot + // and Mapping until the native owner reaches a true quiescent retry point. + let busy = unsafe { os_map_kernel_space(BASE + 12 * PAGE, PAGE, 1) }; + assert!(!busy.is_null()); + let ready = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + model.state.lock().unwrap().map_gates = Some((ready.clone(), release.clone())); + let other_authority = authority.clone(); + let other = std::thread::spawn(move || { + other_authority + .map_physical( + PhysicalSpan::new(PREFETCH + PAGE, PAGE).unwrap(), + CacheAttribute::Uncached, + Protection::ReadWrite, + ) + .unwrap() + }); + ready.wait(); + let before = services.status(); + let calls = model.calls(); + unsafe { os_unmap_kernel_space(busy, PAGE) }; + assert_eq!(services.status().live, 0); + assert_eq!(services.status().pending, 1); + assert_eq!( + services.status().busy_retirements, + before.busy_retirements + 1 + ); + assert_eq!(services.status().failed_unmaps, before.failed_unmaps); + assert_eq!( + services.status().unmap_quarantines, + before.unmap_quarantines + ); + assert_eq!(services.authority_status().unwrap().quarantined, 0); + assert_eq!( + unsafe { services.as_mut().uninstall() }, + Err(Error::LiveMappings) + ); + for _ in 0..3 { + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Err(Error::Mapping(MappingError::Busy)) + ); + assert_eq!(services.status().pending, 1); + assert_eq!(model.calls(), calls); // no native unmap or new mapping + } + unsafe { os_unmap_kernel_space(busy, PAGE - 1) }; + assert_eq!(services.status().last_failure, Some(Error::UnknownMapping)); + assert_eq!(services.status().pending, 1); + assert_eq!(model.calls(), calls); + let before_duplicate = services.status(); + unsafe { os_unmap_kernel_space(busy, PAGE) }; + assert_eq!(services.status().last_failure, Some(Error::UnknownMapping)); + assert_eq!(services.status().pending, 1); + assert_eq!( + services.status().busy_retirements, + before_duplicate.busy_retirements + ); + assert_eq!( + services.status().unmap_quarantines, + before_duplicate.unmap_quarantines + ); + assert_eq!(model.calls(), calls); // consumed raw-use key cannot retry + release.wait(); + let mut other = other.join().unwrap(); + model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, busy as usize, PAGE)); + let refused = services.status().refused_calls; + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Ok(1) + ); + assert_eq!(services.status().refused_calls, refused + 2); + assert_eq!(services.status().pending, 0); + assert_eq!(services.authority_status().unwrap().quarantined, 0); + assert_eq!(model.calls().1, calls.1 + 1); // one actual acknowledged retire + unsafe { other.retire() }.unwrap(); + + // Busy returned AFTER entering native unmap makes canonical state uncertain. + // Do not infer that Busy means unchanged: retain/block access and retry the + // exact token. The model verifies the same token/request on every attempt. + let busy = unsafe { os_map_kernel_space(BASE + 13 * PAGE, PAGE, 1) }; + assert!(!busy.is_null()); + let before = services.status(); + let calls = model.calls(); + model.state.lock().unwrap().busy_unmap = true; + unsafe { os_unmap_kernel_space(busy, PAGE) }; + assert_eq!(services.status().pending, 1); + assert_eq!(services.status().live, 0); + assert_eq!(services.authority_status().unwrap().uncertain, 1); + assert_eq!(services.authority_status().unwrap().quarantined, 0); + assert_eq!(model.calls().1, calls.1 + 1); + let duplicate_calls = model.calls(); + unsafe { os_unmap_kernel_space(busy, PAGE) }; + assert_eq!(services.status().last_failure, Some(Error::UnknownMapping)); + assert_eq!(services.status().pending, 1); + assert_eq!(services.authority_status().unwrap().uncertain, 1); + assert_eq!(model.calls(), duplicate_calls); // owner drain is sole retry seam + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Err(Error::Mapping(MappingError::Busy)) + ); + assert_eq!(model.calls().1, calls.1 + 2); + assert_eq!(services.authority_status().unwrap().uncertain, 1); + rejected( + &services, + &model, + BASE + 13 * PAGE, + PAGE, + 1, + MappingError::ResourceConflict, + false, + ); + model.state.lock().unwrap().busy_unmap = false; + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Ok(1) + ); + assert_eq!( + services.status().busy_retirements, + before.busy_retirements + 2 + ); + assert_eq!(services.status().failed_unmaps, before.failed_unmaps + 1); // duplicate key only + assert_eq!( + services.status().unmap_quarantines, + before.unmap_quarantines + ); + assert_eq!(services.status().pending, 0); + assert_eq!(services.authority_status().unwrap().uncertain, 0); + assert_eq!(model.calls().1, calls.1 + 3); + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Ok(0) + ); + + // Failed retirement consumes the void native ABI into actual canonical + // quarantine. The provider's allocation/token and resource stay retained. + let failed = unsafe { os_map_kernel_space(BASE + 9 * PAGE, PAGE, 1) }; + assert!(!failed.is_null()); + model.state.lock().unwrap().ack = false; + let before = services.status(); + unsafe { os_unmap_kernel_space(failed, PAGE) }; + assert_eq!(services.status().live, 0); + assert_eq!(services.status().failed_unmaps, before.failed_unmaps + 1); + assert_eq!( + services.status().unmap_quarantines, + before.unmap_quarantines + 1 + ); + assert_eq!( + services.status().last_failure, + Some(Error::Mapping(MappingError::UnmapFailed)) + ); + assert_eq!(services.authority_status().unwrap().quarantined, 1); + assert_eq!(model.calls().2, 1); + assert_eq!( + authority.unregister_resource(register_id), + Err(MappingError::Busy) + ); + let calls = model.calls(); + unsafe { os_unmap_kernel_space(failed, PAGE) }; + assert_eq!(model.calls(), calls); // no guessed retry/double unmap + model.state.lock().unwrap().ack = true; + rejected( + &services, + &model, + BASE + 9 * PAGE, + PAGE, + 1, + MappingError::ResourceConflict, + false, + ); + + model.mode(Mode::Uncertain); + rejected( + &services, + &model, + BASE + 10 * PAGE, + PAGE, + 1, + MappingError::MappingFailed, + true, + ); + assert_eq!(services.authority_status().unwrap().quarantined, 2); + model.mode(Mode::WrongCache); + rejected( + &services, + &model, + BASE + 11 * PAGE, + PAGE, + 1, + MappingError::InvalidPlatformReply, + true, + ); + assert_eq!(services.authority_status().unwrap().quarantined, 3); + assert_eq!(model.calls().2, 3); + + unsafe { services.as_mut().uninstall() }.unwrap(); + assert_eq!( + unsafe { services.as_mut().drain_pending_retirements() }, + Err(Error::NotInstalled) + ); + assert_eq!( + unsafe { services.as_mut().uninstall() }, + Err(Error::NotInstalled) + ); + let calls = model.calls(); + unsafe { + assert!(os_map_kernel_space(PREFETCH, PAGE, 1).is_null()); + os_unmap_kernel_space(failed, PAGE); + } + assert_eq!(model.calls(), calls); + drop(services); + drop(registers); + assert_eq!(register_drop.load(Ordering::Relaxed), 0); + assert_eq!( + authority.unregister_resource(register_id), + Err(MappingError::Busy) + ); + authority.unregister_resource(prefetch_id).unwrap(); + authority.unregister_resource(partial_id).unwrap(); + assert_eq!(prefetch_drop.load(Ordering::Relaxed), 1); + assert_eq!(partial_drop.load(Ordering::Relaxed), 1); + assert_eq!(authority.status().unwrap().quarantined, 3); + assert_eq!(model.calls().2, 3); +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvkms_memory.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvkms_memory.c new file mode 100644 index 0000000000..649a02dfbe --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvkms_memory.c @@ -0,0 +1,223 @@ +/* SPDX-License-Identifier: MIT */ +/* Separate CPU process. Keep the original private prefix/realloc algorithm, + * observing only its sized free call. The production backend is a separately + * compiled real stela_nvkms_memory.c; only its common-heap/zero callees are + * renamed to the bounded observation/denial seams below. These definitions + * never enter a production archive. The existing lut_heap.rs supplies the + * actual shared Heap and metadata adapter, with no alternate heap algorithm. + */ +#include "nvidia-modeset-os-interface.h" +void stela_nvkms_observed_free(void *pointer, size_t size); +#define nvkms_free stela_nvkms_observed_free +#include "../../src/nvidia-modeset/src/nvkms-utils.c" +#undef nvkms_free +#include "memory.h" + +void stela_nvkms_test_heap_initialize(void); +size_t stela_nvkms_test_heap_live(void); +NvU32 stela_nvkms_model_alloc(NvU64 bytes, void **out); +void stela_nvkms_model_free(void *pointer); +void *stela_nvkms_model_zero(void *pointer, NvU8 value, size_t bytes); + +/* Two simultaneously live allocations cover the original realloc transition. + * This is fixture ownership accounting, never a production allocation registry. + */ +static struct { + void *pointer; + NvU64 bytes; +} live[2]; +static NvU32 deny_status; +static NvU64 last_request; +static unsigned int allocation_calls, free_calls, zero_calls; +static unsigned int sized_frees, null_frees, errors; + +static int live_index(void *pointer) +{ + unsigned int i; + for (i = 0; i < 2; i++) { + if (live[i].pointer == pointer) + return (int)i; + } + return -1; +} + +NvU32 stela_nvkms_model_alloc(NvU64 bytes, void **out) +{ + NvU32 status; + unsigned int i; + allocation_calls++; + last_request = bytes; + *out = NULL; + if (deny_status != 0) + return deny_status; + status = stela_nvidia_alloc(bytes, out); + if (status != STELA_NVIDIA_ALLOC_SUCCESS) + return status; + for (i = 0; i < 2; i++) { + if (live[i].pointer == NULL) { + live[i].pointer = *out; + live[i].bytes = bytes; + return status; + } + } + errors++; + stela_nvidia_free(*out); + *out = NULL; + return STELA_NVIDIA_ALLOC_OUT_OF_MEMORY; +} + +void stela_nvkms_model_free(void *pointer) +{ + int i; + if (pointer == NULL) { + null_frees++; + stela_nvidia_free(NULL); + return; + } + i = live_index(pointer); + if (i < 0) { + errors++; + return; + } + live[i].pointer = NULL; + live[i].bytes = 0; + free_calls++; + stela_nvidia_free(pointer); +} + +void *stela_nvkms_model_zero(void *pointer, NvU8 value, size_t bytes) +{ + int i = live_index(pointer); + if (i < 0 || value != 0 || live[i].bytes != bytes) { + errors++; + return pointer; + } + zero_calls++; + return nvkms_memset(pointer, value, bytes); +} + +void stela_nvkms_observed_free(void *pointer, size_t size) +{ + int i = live_index(pointer); + if (i < 0 || live[i].bytes != size) + errors++; + sized_frees++; + nvkms_free(pointer, size); +} + +static NvU8 pattern(size_t index) +{ + return (NvU8)(0x63 ^ (index * 13)); +} + +static int bytes_match(const NvU8 *pointer, size_t bytes) +{ + size_t i; + for (i = 0; i < bytes; i++) { + if (pointer[i] != pattern(i)) + return 0; + } + return 1; +} + +int main(void) +{ + const size_t sizes[] = {0, 1, 15, 16, 17, 4096, 4097, 65537}; + const NvBool zero_flags[] = {0, 1, 2, 255}; + const NvU32 statuses[] = { + STELA_NVIDIA_ALLOC_INVALID_SIZE, STELA_NVIDIA_ALLOC_OUT_OF_MEMORY, + }; + unsigned int i, j, before_alloc, before_free, before_zero; + size_t k, before_live; + NvU8 *p, *q; + + stela_nvkms_test_heap_initialize(); + if (stela_nvkms_test_heap_live() != 0) + return 1; + for (i = 0; i < sizeof(zero_flags) / sizeof(zero_flags[0]); i++) { + for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) { + before_zero = zero_calls; + p = nvkms_alloc(sizes[j], zero_flags[i]); + if (p == NULL || ((NvUPtr)p & 15) != 0 || + zero_calls != before_zero + (zero_flags[i] != 0) || + last_request != sizes[j]) + return 2; + for (k = 0; k < sizes[j]; k++) { + if (zero_flags[i] != 0 && p[k] != 0) + return 3; + p[k] = pattern(k); + } + if (!bytes_match(p, sizes[j])) + return 4; + nvkms_free(p, sizes[j]); + } + } + for (i = 0; i < sizeof(statuses) / sizeof(statuses[0]); i++) { + deny_status = statuses[i]; + for (j = 0; j < sizeof(zero_flags) / sizeof(zero_flags[0]); j++) { + before_zero = zero_calls; + before_free = free_calls; + before_alloc = allocation_calls; + p = nvkms_alloc(((NvU64)1 << 32) + 17, zero_flags[j]); + if (p != NULL || last_request != ((NvU64)1 << 32) + 17 || + zero_calls != before_zero || free_calls != before_free || + allocation_calls != before_alloc + 1) + return 5; + } + } + deny_status = 0; + before_zero = zero_calls; + p = nvInternalAlloc(63, TRUE); + if (p == NULL || sizeof(nvkms_memory_info_t) != 8 || + offsetof(nvkms_memory_info_t, data) != 8 || + ((NvUPtr)p & 15) != 8 || last_request != 71 || + zero_calls != before_zero + 1) + return 6; + for (k = 0; k < 63; k++) { + if (p[k] != 0) + return 7; + p[k] = pattern(k); + } + before_live = stela_nvkms_test_heap_live(); + before_free = free_calls; + before_zero = zero_calls; + deny_status = STELA_NVIDIA_ALLOC_OUT_OF_MEMORY; + q = nvInternalRealloc(p, 101); + if (q != NULL || !bytes_match(p, 63) || free_calls != before_free || + zero_calls != before_zero || last_request != 109 || + stela_nvkms_test_heap_live() != before_live) + return 8; + deny_status = 0; + before_alloc = allocation_calls; + q = nvInternalRealloc(p, ~(size_t)0); + if (q != NULL || allocation_calls != before_alloc || + free_calls != before_free || !bytes_match(p, 63)) + return 9; + q = nvInternalRealloc(p, ((NvU64)1 << 63) - 1); + if (q != NULL || free_calls != before_free || !bytes_match(p, 63) || + stela_nvkms_test_heap_live() != before_live) + return 10; + q = nvInternalRealloc(p, 101); + if (q == NULL || !bytes_match(q, 63) || free_calls != before_free + 1 || + zero_calls != before_zero) + return 11; + for (k = 63; k < 101; k++) + q[k] = pattern(k); + p = nvInternalRealloc(q, 17); + if (p == NULL || !bytes_match(p, 17) || free_calls != before_free + 2) + return 12; + q = nvInternalRealloc(p, 0); + if (q != NULL || free_calls != before_free + 3) + return 13; + p = nvInternalRealloc(NULL, 0); + if (p == NULL || last_request != 8) + return 14; + nvInternalFree(p); + nvInternalFree(NULL); + nvkms_free(NULL, ~(size_t)0); + if (errors != 0 || live[0].pointer != NULL || live[1].pointer != NULL || + null_frees != 1 || sized_frees != 4 || + stela_nvkms_test_heap_live() != 0) + return 15; + return 0; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvlink_memory.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvlink_memory.c new file mode 100644 index 0000000000..5c9db4d06d --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvlink_memory.c @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: MIT */ +/* Separate CPU-only process: link the actual production stela_nvlink_memory.c + * against this bounded denial provider, never into the driver. Real-success + * heap ownership is exercised by the Rust tests through the actual C hooks. + */ +#include +#include "nvlink_os.h" +#include "memory.h" + +static NvU64 observed_size; +static NvU32 allocations; +static NvU32 frees; +static NvU32 denied_status; +static void *observed_free; + +NvU32 stela_nvidia_alloc(NvU64 size, void **out) +{ + allocations++; + observed_size = size; + *out = NULL; + return denied_status; +} + +void stela_nvidia_free(void *pointer) +{ + frees++; + observed_free = pointer; +} + +int main(void) +{ + const NvU64 sizes[] = {0, 1, 4096, ((NvU64)1 << 32) + 17, ~(NvU64)0}; + const NvU32 statuses[] = { + STELA_NVIDIA_ALLOC_INVALID_SIZE, + STELA_NVIDIA_ALLOC_OUT_OF_MEMORY, + }; + NvU32 i, j; + for (i = 0; i < sizeof(statuses) / sizeof(statuses[0]); i++) { + denied_status = statuses[i]; + for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) { + NvU32 before = allocations; + if (nvlink_malloc(sizes[j]) != NULL || + allocations != before + 1 || observed_size != sizes[j] || + frees != 0) + return 1; + } + } + nvlink_free(NULL); + if (frees != 1 || observed_free != NULL || allocations != 10) + return 2; + return 0; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvswitch_primitives.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvswitch_primitives.c new file mode 100644 index 0000000000..fe6331b25f --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/nvswitch_primitives.c @@ -0,0 +1,109 @@ +/* SPDX-License-Identifier: MIT */ +/* CPU-only original-hook fixture. The optional renamed-provider object observes + * ABI forwarding without pretending a short buffer covers a huge byte range. */ +#include "../../src/common/nvswitch/interface/export_nvswitch.h" +#include +#include +#include + +#ifdef NDEBUG +#error "NVSwitch primitive tests require active assertions" +#endif +_Static_assert(sizeof(NvLength) == 8, "native NVSwitch lengths remain 64-bit"); + +#ifdef STELA_NVSWITCH_FORWARD_TEST +static void *destination; +static const void *source; +static NvLength count; +static int byte_value; +static unsigned copy_calls, set_calls, length_calls; + +void *stela_nvswitch_test_memcpy(void *dest, const void *src, size_t size); +void *stela_nvswitch_test_memset(void *dest, int value, size_t size); +size_t stela_nvswitch_test_strlen(const char *str); + +void *stela_nvswitch_test_memcpy(void *dest, const void *src, size_t size) +{ + assert(dest == destination && src == source && size == count); + copy_calls++; + return dest; +} + +void *stela_nvswitch_test_memset(void *dest, int value, size_t size) +{ + assert(dest == destination && value == byte_value && size == count); + set_calls++; + return dest; +} + +size_t stela_nvswitch_test_strlen(const char *str) +{ + assert(str == source); + length_calls++; + return count; +} + +int main(void) +{ + unsigned char actual_destination = 0xa5; + const unsigned char actual_source = 0x81; + destination = &actual_destination; + source = &actual_source; + const NvLength sizes[] = {0, 1, UINT64_C(0x100000001), UINT64_MAX}; + const int values[] = {-1, 0, 0x180, INT32_MIN, INT32_MAX}; + for (unsigned i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) + { + count = sizes[i]; + assert(nvswitch_os_memcpy(destination, source, count) == destination); + assert(nvswitch_os_strlen(source) == count); + for (unsigned v = 0; v < sizeof(values) / sizeof(values[0]); v++) + { + byte_value = values[v]; + assert(nvswitch_os_memset(destination, byte_value, count) == destination); + } + } + assert(copy_calls == 4 && length_calls == 4 && set_calls == 20); + assert(actual_destination == 0xa5 && actual_source == 0x81); + puts("original NVSwitch wrappers preserve full-width scalar/provider forwarding"); + return 0; +} +#else +int main(void) +{ + unsigned char source[4096 + 32], destination[4096 + 32]; + const NvLength sizes[] = {0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096}; + const int values[] = {-1, 0, 0x80, 0x180, INT32_MIN, INT32_MAX}; + for (unsigned i = 0; i < sizeof(source); i++) + source[i] = (unsigned char)(i * 37 + 0x81); + for (unsigned s = 0; s < sizeof(sizes) / sizeof(sizes[0]); s++) + { + NvLength size = sizes[s]; + for (unsigned offset = 0; offset < 16; offset++) + { + for (unsigned i = 0; i < sizeof(destination); i++) + destination[i] = 0xa5; + assert(nvswitch_os_memcpy(destination + offset, source + 15 - offset, size) + == destination + offset); + for (unsigned i = 0; i < sizeof(destination); i++) + assert(destination[i] == ((i >= offset && i - offset < size) + ? (unsigned char)((i - offset + 15 - offset) * 37 + 0x81) : 0xa5)); + for (unsigned v = 0; v < sizeof(values) / sizeof(values[0]); v++) + { + for (unsigned i = 0; i < sizeof(destination); i++) + destination[i] = 0xa5; + assert(nvswitch_os_memset(destination + offset, values[v], size) + == destination + offset); + for (unsigned i = 0; i < sizeof(destination); i++) + assert(destination[i] == ((i >= offset && i - offset < size) + ? (unsigned char)values[v] : 0xa5)); + } + for (unsigned i = 0; i < sizeof(destination); i++) + destination[i] = 0x80; + destination[offset + size] = 0; + assert(nvswitch_os_strlen((const char *)destination + offset) == size); + } + } + puts("original NVSwitch CPU primitives preserve bytes, returns and untouched spans"); + return 0; +} +#endif diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/ordering.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/ordering.c new file mode 100644 index 0000000000..dfab9a884b --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/ordering.c @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: MIT + * Compile/disassembly fixture only. This is not a CPU/GPU ordering litmus test. + * Include the actual adapter so the emitted probe exposes its compiler clobber + * and instruction between ordinary CPU stores, without calling hardware. + */ +#include "../stela_ordering.c" + +void stela_nvidia_ordering_compile_probe(NvU32 *before, NvU32 *after); + +void stela_nvidia_ordering_compile_probe(NvU32 *before, NvU32 *after) +{ + *before = 0x12345678; + os_flush_cpu_write_combine_buffer(); + *after = 0x76543210; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/page_geometry.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/page_geometry.c new file mode 100644 index 0000000000..c1888aff69 --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/page_geometry.c @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: MIT */ +/* Original global-data ABI plus unchanged original accessor bodies, linked in + * a fresh hosted process. No actual RAM/cache/physical support is attested. */ +#include "../page_geometry.h" +#include "page_geometry_accessors.h" +#include +#include +#include + +#ifdef NDEBUG +#error "page geometry tests require assertions" +#endif +static void unchanged(NvU64 base, NvU64 max, NvU64 mask, NvU8 shift) +{ + assert(os_page_size == base && os_max_page_size == max && + os_page_mask == mask && os_page_shift == shift); +} +int main(int argc, char **argv) +{ + assert(argc == 3); + unsigned base_shift = (unsigned)strtoul(argv[1], NULL, 10); + unsigned max_shift = (unsigned)strtoul(argv[2], NULL, 10); + assert(base_shift >= 12 && base_shift <= max_shift && max_shift <= 62); + NvU64 base = 1ULL << base_shift, max = 1ULL << max_shift, mask = ~(base - 1); + unchanged(0, 0, 0, 0); + const struct { NvU64 base, max, mask; NvU8 shift; } bad[] = { + {0, 0, 0, 0}, {4096, 4096, ~4095ULL, 11}, + {4096, 4096, ~4095ULL, 63}, {4096, 4096, ~4095ULL, 255}, + {8192, 8192, ~8191ULL, 12}, {4096, 0, ~4095ULL, 12}, + {8192, 4096, ~8191ULL, 13}, {4096, 6144, ~4095ULL, 12}, + {4096, 1ULL << 63, ~4095ULL, 12}, {4096, ~0ULL, ~4095ULL, 12}, + {4096, 4096, 0, 12}, + }; + for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + assert(stela_nvidia_set_page_geometry(bad[i].base, bad[i].max, bad[i].mask, bad[i].shift) + == NV_ERR_INVALID_ARGUMENT); + unchanged(0, 0, 0, 0); + } + if (base_shift != max_shift) { + assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift) + == NV_ERR_NOT_SUPPORTED); + unchanged(0, 0, 0, 0); + printf("original RM broad page profile refused before publication: base%u max%u; CPU-only\n", + base_shift, max_shift); + return 0; + } + assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift) == NV_OK); + unchanged(base, max, mask, (NvU8)base_shift); + assert(osGetPageSize() == base && osGetPageShift() == base_shift); + NvU64 supported = osGetSupportedSysmemPageSizeMask(); + for (unsigned i = 0; i < 64; i++) + assert(!!(supported & (1ULL << i)) == (i >= base_shift && i <= max_shift)); + assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift) == NV_OK); + assert(stela_nvidia_set_page_geometry(4096, 16384, ~4095ULL, 12) == NV_ERR_NOT_SUPPORTED); + unchanged(base, max, mask, (NvU8)base_shift); + NvU64 other_base = base_shift == 12 ? 16384 : 4096; + NvU8 other_shift = base_shift == 12 ? 14 : 12; + assert(stela_nvidia_set_page_geometry(other_base, other_base, ~(other_base - 1), other_shift) + == NV_ERR_INVALID_STATE); + unchanged(base, max, mask, (NvU8)base_shift); + for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + assert(stela_nvidia_set_page_geometry(bad[i].base, bad[i].max, bad[i].mask, bad[i].shift) + == NV_ERR_INVALID_ARGUMENT); + unchanged(base, max, mask, (NvU8)base_shift); + } + printf("original RM page globals/accessors: base%u max%u, exact mask and atomic refusals; CPU-only\n", + base_shift, max_shift); + return 0; +} diff --git a/crates/stela-drivers/src/gpu/nvidia/stela/tests/record_layout.c b/crates/stela-drivers/src/gpu/nvidia/stela/tests/record_layout.c new file mode 100644 index 0000000000..1aa8a10a9e --- /dev/null +++ b/crates/stela-drivers/src/gpu/nvidia/stela/tests/record_layout.c @@ -0,0 +1,182 @@ +/* SPDX-License-Identifier: MIT */ +/* Compile the actual vendor declarations under both the full-core target and + * Cargo's OS-hook target. Every active record/scalar measurement must match; + * ordinary long is reported separately and never relaxes a record comparison. + * Core builds use their genuine NvPort atomic/module defines; OS-hook builds + * also define NV_KERNEL_INTERFACE_LAYER, as the real adapter headers do. + * This fixture supplies constants only, no fake records or platform provider. + */ +#include +#include "nv.h" +#include "pci.h" +#include "libelf.h" + +#define STELA_NVIDIA_RECORD_LAYOUT(M) \ + M("sizeof(nv_state_t)", sizeof(nv_state_t)) \ + M("alignof(nv_state_t)", _Alignof(nv_state_t)) \ + M("sizeof(nv_pci_info_t)", sizeof(nv_pci_info_t)) \ + M("alignof(nv_pci_info_t)", _Alignof(nv_pci_info_t)) \ + M("sizeof(nv_aperture_t)", sizeof(nv_aperture_t)) \ + M("alignof(nv_aperture_t)", _Alignof(nv_aperture_t)) \ + M("sizeof(nv_cached_gpu_info_t)", sizeof(nv_cached_gpu_info_t)) \ + M("alignof(nv_cached_gpu_info_t)", _Alignof(nv_cached_gpu_info_t)) \ + M("sizeof(nv_phys_addr_range_t)", sizeof(nv_phys_addr_range_t)) \ + M("alignof(nv_phys_addr_range_t)", _Alignof(nv_phys_addr_range_t)) \ + M("sizeof(nv_soc_irq_info_t)", sizeof(nv_soc_irq_info_t)) \ + M("alignof(nv_soc_irq_info_t)", _Alignof(nv_soc_irq_info_t)) \ + M("sizeof(nv_event_t)", sizeof(nv_event_t)) \ + M("alignof(nv_event_t)", _Alignof(nv_event_t)) \ + M("sizeof(nv_kern_mapping_t)", sizeof(nv_kern_mapping_t)) \ + M("alignof(nv_kern_mapping_t)", _Alignof(nv_kern_mapping_t)) \ + M("sizeof(nv_usermap_access_params_t)", sizeof(nv_usermap_access_params_t)) \ + M("alignof(nv_usermap_access_params_t)", _Alignof(nv_usermap_access_params_t)) \ + M("sizeof(nv_alloc_mapping_context_t)", sizeof(nv_alloc_mapping_context_t)) \ + M("alignof(nv_alloc_mapping_context_t)", _Alignof(nv_alloc_mapping_context_t)) \ + M("sizeof(nv_alloc_mapping_list_node_t)", sizeof(nv_alloc_mapping_list_node_t)) \ + M("alignof(nv_alloc_mapping_list_node_t)", _Alignof(nv_alloc_mapping_list_node_t)) \ + M("sizeof(nvidia_stack_t)", sizeof(nvidia_stack_t)) \ + M("alignof(nvidia_stack_t)", _Alignof(nvidia_stack_t)) \ + M("sizeof(LibosElf64Header)", sizeof(LibosElf64Header)) \ + M("alignof(LibosElf64Header)", _Alignof(LibosElf64Header)) \ + M("sizeof(LibosElf64SectionHeader)", sizeof(LibosElf64SectionHeader)) \ + M("alignof(LibosElf64SectionHeader)", _Alignof(LibosElf64SectionHeader)) \ + M("sizeof(struct stela_nvidia_pci)", sizeof(struct stela_nvidia_pci)) \ + M("alignof(struct stela_nvidia_pci)", _Alignof(struct stela_nvidia_pci)) \ + M("sizeof(nv_firmware_type_t)", sizeof(nv_firmware_type_t)) \ + M("alignof(nv_firmware_type_t)", _Alignof(nv_firmware_type_t)) \ + M("sizeof(nv_firmware_chip_family_t)", sizeof(nv_firmware_chip_family_t)) \ + M("alignof(nv_firmware_chip_family_t)", _Alignof(nv_firmware_chip_family_t)) \ + M("sizeof(NvBool)", sizeof(NvBool)) \ + M("alignof(NvBool)", _Alignof(NvBool)) \ + M("sizeof(NvLength)", sizeof(NvLength)) \ + M("alignof(NvLength)", _Alignof(NvLength)) \ + M("sizeof(NvUPtr)", sizeof(NvUPtr)) \ + M("alignof(NvUPtr)", _Alignof(NvUPtr)) \ + M("sizeof(NV_STATUS)", sizeof(NV_STATUS)) \ + M("alignof(NV_STATUS)", _Alignof(NV_STATUS)) \ + M("sizeof(void *)", sizeof(void *)) \ + M("alignof(void *)", _Alignof(void *)) \ + M("offsetof(nv_state_t,priv)", offsetof(nv_state_t,priv)) \ + M("offsetof(nv_state_t,os_state)", offsetof(nv_state_t,os_state)) \ + M("offsetof(nv_state_t,flags)", offsetof(nv_state_t,flags)) \ + M("offsetof(nv_state_t,pci_info)", offsetof(nv_state_t,pci_info)) \ + M("offsetof(nv_state_t,subsystem_id)", offsetof(nv_state_t,subsystem_id)) \ + M("offsetof(nv_state_t,subsystem_vendor)", offsetof(nv_state_t,subsystem_vendor)) \ + M("offsetof(nv_state_t,gpu_id)", offsetof(nv_state_t,gpu_id)) \ + M("offsetof(nv_state_t,iovaspace_id)", offsetof(nv_state_t,iovaspace_id)) \ + M("offsetof(nv_state_t,nv_uuid_cache)", offsetof(nv_state_t,nv_uuid_cache)) \ + M("offsetof(nv_state_t,handle)", offsetof(nv_state_t,handle)) \ + M("offsetof(nv_state_t,pci_cfg_space)", offsetof(nv_state_t,pci_cfg_space)) \ + M("offsetof(nv_state_t,bars)", offsetof(nv_state_t,bars)) \ + M("offsetof(nv_state_t,regs)", offsetof(nv_state_t,regs)) \ + M("offsetof(nv_state_t,dpaux)", offsetof(nv_state_t,dpaux)) \ + M("offsetof(nv_state_t,hdacodec_regs)", offsetof(nv_state_t,hdacodec_regs)) \ + M("offsetof(nv_state_t,mipical_regs)", offsetof(nv_state_t,mipical_regs)) \ + M("offsetof(nv_state_t,fb)", offsetof(nv_state_t,fb)) \ + M("offsetof(nv_state_t,ud)", offsetof(nv_state_t,ud)) \ + M("offsetof(nv_state_t,simregs)", offsetof(nv_state_t,simregs)) \ + M("offsetof(nv_state_t,num_dpaux_instance)", offsetof(nv_state_t,num_dpaux_instance)) \ + M("offsetof(nv_state_t,interrupt_line)", offsetof(nv_state_t,interrupt_line)) \ + M("offsetof(nv_state_t,dpaux_irqs)", offsetof(nv_state_t,dpaux_irqs)) \ + M("offsetof(nv_state_t,dpaux_devname)", offsetof(nv_state_t,dpaux_devname)) \ + M("offsetof(nv_state_t,soc_irq_info)", offsetof(nv_state_t,soc_irq_info)) \ + M("offsetof(nv_state_t,current_soc_irq)", offsetof(nv_state_t,current_soc_irq)) \ + M("offsetof(nv_state_t,num_soc_irqs)", offsetof(nv_state_t,num_soc_irqs)) \ + M("offsetof(nv_state_t,hdacodec_irq)", offsetof(nv_state_t,hdacodec_irq)) \ + M("offsetof(nv_state_t,tcpc2disp_irq)", offsetof(nv_state_t,tcpc2disp_irq)) \ + M("offsetof(nv_state_t,soc_dcb_blob)", offsetof(nv_state_t,soc_dcb_blob)) \ + M("offsetof(nv_state_t,soc_dcb_size)", offsetof(nv_state_t,soc_dcb_size)) \ + M("offsetof(nv_state_t,disp_sw_soc_chip_id)", offsetof(nv_state_t,disp_sw_soc_chip_id)) \ + M("offsetof(nv_state_t,soc_is_dpalt_mode_supported)", offsetof(nv_state_t,soc_is_dpalt_mode_supported)) \ + M("offsetof(nv_state_t,soc_is_hfrp_supported)", offsetof(nv_state_t,soc_is_hfrp_supported)) \ + M("offsetof(nv_state_t,soc_is_external_phy_supported)", offsetof(nv_state_t,soc_is_external_phy_supported)) \ + M("offsetof(nv_state_t,dma_mask)", offsetof(nv_state_t,dma_mask)) \ + M("offsetof(nv_state_t,is_tegra_pci_igpu)", offsetof(nv_state_t,is_tegra_pci_igpu)) \ + M("offsetof(nv_state_t,supports_tegra_igpu_rg)", offsetof(nv_state_t,supports_tegra_igpu_rg)) \ + M("offsetof(nv_state_t,is_tegra_pci_igpu_rg_enabled)", offsetof(nv_state_t,is_tegra_pci_igpu_rg_enabled)) \ + M("offsetof(nv_state_t,tegra_pci_igpu_pg_mask)", offsetof(nv_state_t,tegra_pci_igpu_pg_mask)) \ + M("offsetof(nv_state_t,gpc_fuse_status_offset)", offsetof(nv_state_t,gpc_fuse_status_offset)) \ + M("offsetof(nv_state_t,primary_vga)", offsetof(nv_state_t,primary_vga)) \ + M("offsetof(nv_state_t,sim_env)", offsetof(nv_state_t,sim_env)) \ + M("offsetof(nv_state_t,rc_timer_enabled)", offsetof(nv_state_t,rc_timer_enabled)) \ + M("offsetof(nv_state_t,event_list)", offsetof(nv_state_t,event_list)) \ + M("offsetof(nv_state_t,event_spinlock)", offsetof(nv_state_t,event_spinlock)) \ + M("offsetof(nv_state_t,kern_mappings)", offsetof(nv_state_t,kern_mappings)) \ + M("offsetof(nv_state_t,dma_dev)", offsetof(nv_state_t,dma_dev)) \ + M("offsetof(nv_state_t,niso_dma_dev)", offsetof(nv_state_t,niso_dma_dev)) \ + M("offsetof(nv_state_t,queue)", offsetof(nv_state_t,queue)) \ + M("offsetof(nv_state_t,request_firmware)", offsetof(nv_state_t,request_firmware)) \ + M("offsetof(nv_state_t,request_fw_client_rm)", offsetof(nv_state_t,request_fw_client_rm)) \ + M("offsetof(nv_state_t,allow_fallback_to_monolithic_rm)", offsetof(nv_state_t,allow_fallback_to_monolithic_rm)) \ + M("offsetof(nv_state_t,enable_firmware_logs)", offsetof(nv_state_t,enable_firmware_logs)) \ + M("offsetof(nv_state_t,removed)", offsetof(nv_state_t,removed)) \ + M("offsetof(nv_state_t,console_device)", offsetof(nv_state_t,console_device)) \ + M("offsetof(nv_state_t,is_external_gpu)", offsetof(nv_state_t,is_external_gpu)) \ + M("offsetof(nv_state_t,preserve_vidmem_allocations)", offsetof(nv_state_t,preserve_vidmem_allocations)) \ + M("offsetof(nv_state_t,force_dma32_alloc)", offsetof(nv_state_t,force_dma32_alloc)) \ + M("offsetof(nv_state_t,d0_state_in_suspend)", offsetof(nv_state_t,d0_state_in_suspend)) \ + M("offsetof(nv_state_t,profiler_owner)", offsetof(nv_state_t,profiler_owner)) \ + M("offsetof(nv_state_t,profiler_context)", offsetof(nv_state_t,profiler_context)) \ + M("offsetof(nv_state_t,rmapi)", offsetof(nv_state_t,rmapi)) \ + M("offsetof(nv_state_t,dma_buf_supported)", offsetof(nv_state_t,dma_buf_supported)) \ + M("offsetof(nv_state_t,is_shutdown)", offsetof(nv_state_t,is_shutdown)) \ + M("offsetof(nv_state_t,coherent)", offsetof(nv_state_t,coherent)) \ + M("offsetof(nv_state_t,mem_has_struct_page)", offsetof(nv_state_t,mem_has_struct_page)) \ + M("offsetof(nv_state_t,coherent_gpu_mem_mode)", offsetof(nv_state_t,coherent_gpu_mem_mode)) \ + M("offsetof(nv_state_t,ats_support)", offsetof(nv_state_t,ats_support)) \ + M("offsetof(nv_state_t,cpu_numa_node_id)", offsetof(nv_state_t,cpu_numa_node_id)) \ + M("offsetof(nv_state_t,iommus)", offsetof(nv_state_t,iommus)) \ + M("offsetof(nv_state_t,clocks)", offsetof(nv_state_t,clocks)) \ + M("offsetof(nv_state_t,client_managed_console)", offsetof(nv_state_t,client_managed_console)) \ + M("offsetof(nv_state_t,sysmem_mapped_console)", offsetof(nv_state_t,sysmem_mapped_console)) \ + M("offsetof(nv_state_t,cached_gpu_info)", offsetof(nv_state_t,cached_gpu_info)) \ + M("offsetof(nv_state_t,is_pm_unsupported)", offsetof(nv_state_t,is_pm_unsupported)) \ + M("offsetof(nv_state_t,is_cxl_dev)", offsetof(nv_state_t,is_cxl_dev)) \ + M("offsetof(nv_state_t,cached_persistence_mode)", offsetof(nv_state_t,cached_persistence_mode)) \ + M("offsetof(nv_state_t,nv_uuid_cache.valid)", offsetof(nv_state_t,nv_uuid_cache.valid)) \ + M("offsetof(nv_state_t,nv_uuid_cache.uuid)", offsetof(nv_state_t,nv_uuid_cache.uuid)) \ + M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_read_attempted)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_read_attempted)) \ + M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_from_dvsec_pdi)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_from_dvsec_pdi)) \ + M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_status)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_status)) \ + M("offsetof(nv_state_t,pci_info.domain)", offsetof(nv_state_t,pci_info.domain)) \ + M("offsetof(nv_state_t,pci_info.bus)", offsetof(nv_state_t,pci_info.bus)) \ + M("offsetof(nv_state_t,pci_info.slot)", offsetof(nv_state_t,pci_info.slot)) \ + M("offsetof(nv_state_t,pci_info.function)", offsetof(nv_state_t,pci_info.function)) \ + M("offsetof(nv_state_t,rmapi.hClient)", offsetof(nv_state_t,rmapi.hClient)) \ + M("offsetof(nv_state_t,iommus.iso_iommu_present)", offsetof(nv_state_t,iommus.iso_iommu_present)) \ + M("offsetof(nv_state_t,iommus.dispIsoStreamId)", offsetof(nv_state_t,iommus.dispIsoStreamId)) \ + M("offsetof(nv_state_t,clocks.max_dispclk_rate_using_disppllkhz)", offsetof(nv_state_t,clocks.max_dispclk_rate_using_disppllkhz)) \ + M("offsetof(nv_pci_info_t,domain)", offsetof(nv_pci_info_t,domain)) \ + M("offsetof(nv_pci_info_t,bus)", offsetof(nv_pci_info_t,bus)) \ + M("offsetof(nv_pci_info_t,slot)", offsetof(nv_pci_info_t,slot)) \ + M("offsetof(nv_pci_info_t,function)", offsetof(nv_pci_info_t,function)) \ + M("offsetof(nv_pci_info_t,vendor_id)", offsetof(nv_pci_info_t,vendor_id)) \ + M("offsetof(nv_pci_info_t,device_id)", offsetof(nv_pci_info_t,device_id)) \ + M("offsetof(nv_aperture_t,cpu_address)", offsetof(nv_aperture_t,cpu_address)) \ + M("offsetof(nv_aperture_t,size)", offsetof(nv_aperture_t,size)) \ + M("offsetof(nv_aperture_t,offset)", offsetof(nv_aperture_t,offset)) \ + M("offsetof(nv_aperture_t,map)", offsetof(nv_aperture_t,map)) \ + M("offsetof(nv_aperture_t,map_u)", offsetof(nv_aperture_t,map_u)) \ + M("offsetof(struct stela_nvidia_pci,context)", offsetof(struct stela_nvidia_pci,context)) \ + M("offsetof(struct stela_nvidia_pci,read)", offsetof(struct stela_nvidia_pci,read)) \ + M("offsetof(struct stela_nvidia_pci,write)", offsetof(struct stela_nvidia_pci,write)) + +#define STELA_LAYOUT_VALUE(label, expression) (expression), +const unsigned long long stela_nvidia_record_layout_values[] = { + STELA_NVIDIA_RECORD_LAYOUT(STELA_LAYOUT_VALUE) +}; +#undef STELA_LAYOUT_VALUE + +#define STELA_LAYOUT_LABEL(label, expression) (label), +const char *const stela_nvidia_record_layout_labels[] = { + STELA_NVIDIA_RECORD_LAYOUT(STELA_LAYOUT_LABEL) +}; +#undef STELA_LAYOUT_LABEL + +const unsigned long long stela_nvidia_record_layout_count = + sizeof(stela_nvidia_record_layout_values) / sizeof(stela_nvidia_record_layout_values[0]); + +/* LP64 hosted tests do not exchange pointers/callers with the Win64 core. + * These two platform facts are deliberately outside the active-record vector. + */ +const unsigned long long stela_nvidia_platform_long[] = {sizeof(long), _Alignof(long)}; diff --git a/crates/stela-drivers/src/gpu/nvidia/tests.rs b/crates/stela-drivers/src/gpu/nvidia/tests.rs index bc9f3eabf9..b043955f3a 100644 --- a/crates/stela-drivers/src/gpu/nvidia/tests.rs +++ b/crates/stela-drivers/src/gpu/nvidia/tests.rs @@ -184,3 +184,365 @@ fn the_end_of_config_space_accepts_each_natural_width() { } assert_eq!(config.accesses.borrow().len(), 6); } + +unsafe extern "C" { + fn os_mem_copy(destination: *mut c_void, source: *const c_void, bytes: u32) -> *mut c_void; + fn os_mem_set(destination: *mut c_void, value: u8, bytes: u32) -> *mut c_void; + fn os_mem_cmp(left: *const u8, right: *const u8, bytes: u32) -> i32; + fn os_string_length(string: *const core::ffi::c_char) -> u32; +} + +#[test] +fn original_memory_primitives_preserve_returns_bytes_and_untouched_spans() { + let mut source = [0u8; 4096 + 32]; + for (index, byte) in source.iter_mut().enumerate() { + *byte = (index.wrapping_mul(37) + 0x80) as u8; + } + for size in [ + 0, 1, 2, 3, 7, 8, 15, 16, 31, 32, 127, 128, 129, 255, 256, 4096, + ] { + for source_offset in 0..16 { + for destination_offset in 0..16 { + let mut destination = [0xa5u8; 4096 + 32]; + // SAFETY: real nonoverlapping CPU arrays cover the complete + // ranges; zero-byte calls also use valid array pointers. + let pointer = unsafe { destination.as_mut_ptr().add(destination_offset) }; + let input = unsafe { source.as_ptr().add(source_offset) }; + assert_eq!( + unsafe { os_mem_copy(pointer.cast(), input.cast(), size as u32) }, + pointer.cast() + ); + for (index, &byte) in destination.iter().enumerate() { + let expected = if (destination_offset..destination_offset + size) + .contains(&index) + { + ((source_offset + index - destination_offset).wrapping_mul(37) + 0x80) as u8 + } else { + 0xa5 + }; + assert_eq!( + byte, expected, + "copy span: {size}/{source_offset}/{destination_offset}/{index}" + ); + } + // SAFETY: the same full CPU ranges remain readable. + assert_eq!(unsafe { os_mem_cmp(pointer, input, size as u32) }, 0); + } + } + for offset in 0..16 { + for value in [0, 0x80, 0xff] { + let mut destination = [0xa5u8; 4096 + 32]; + // SAFETY: actual writable CPU array covers this complete span. + let pointer = unsafe { destination.as_mut_ptr().add(offset) }; + assert_eq!( + unsafe { os_mem_set(pointer.cast(), value, size as u32) }, + pointer.cast() + ); + for (index, &byte) in destination.iter().enumerate() { + assert_eq!( + byte, + if (offset..offset + size).contains(&index) { + value + } else { + 0xa5 + } + ); + } + } + } + } +} + +#[test] +fn original_compare_uses_unsigned_first_difference_and_exact_requested_length() { + for size in [1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 256] { + for mismatch in 0..size { + for (left_byte, right_byte) in [(0, 0xff), (0x80, 0x7f), (0xff, 1)] { + let mut left = [0x6du8; 288]; + let mut right = left; + left[mismatch] = left_byte; + right[mismatch] = right_byte; + // Differences outside the requested span cannot affect results. + left[size] = 0xff; + right[size] = 0; + let expected = (i32::from(left_byte) - i32::from(right_byte)).signum(); + // SAFETY: both arrays cover the exact requested CPU byte range. + assert_eq!( + unsafe { os_mem_cmp(left.as_ptr(), right.as_ptr(), size as u32) }.signum(), + expected + ); + assert_eq!( + unsafe { os_mem_cmp(right.as_ptr(), left.as_ptr(), size as u32) }.signum(), + -expected + ); + assert_eq!( + unsafe { os_mem_cmp(left.as_ptr(), right.as_ptr(), mismatch as u32) }, + 0 + ); + } + } + } +} + +#[test] +fn original_string_length_counts_bytes_until_first_nul() { + let mut string = [0x80u8; 4096 + 32]; + for offset in 0..16 { + for length in [0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096] { + string.fill(0x80); + string[offset + length] = 0; + // SAFETY: readable real CPU array, bounded terminated C string. + let pointer = unsafe { string.as_ptr().add(offset) }; + assert_eq!(unsafe { os_string_length(pointer.cast()) }, length as u32); + } + } +} + +unsafe extern "C" { + fn nvkms_memcpy(destination: *mut c_void, source: *const c_void, bytes: usize) -> *mut c_void; + fn nvkms_memmove(destination: *mut c_void, source: *const c_void, bytes: usize) -> *mut c_void; + fn nvkms_memset(destination: *mut c_void, value: u8, bytes: usize) -> *mut c_void; + fn nvkms_memcmp(left: *const c_void, right: *const c_void, bytes: usize) -> i32; + fn nvkms_strlen(string: *const core::ffi::c_char) -> usize; + fn nvlink_memcpy(destination: *mut c_void, source: *const c_void, bytes: u64) -> *mut c_void; + fn nvlink_memset(destination: *mut c_void, value: i32, bytes: u64) -> *mut c_void; + fn nvlink_strlen(string: *const core::ffi::c_char) -> u64; + fn nvswitch_os_memcpy( + destination: *mut c_void, + source: *const c_void, + bytes: u64, + ) -> *mut c_void; + fn nvswitch_os_memset(destination: *mut c_void, value: i32, bytes: u64) -> *mut c_void; + fn nvswitch_os_strlen(string: *const core::ffi::c_char) -> u64; +} + +#[test] +fn original_display_link_and_switch_copy_set_preserve_bytes_returns_and_native_lengths() { + let mut source = [0u8; 4096 + 32]; + for (index, byte) in source.iter_mut().enumerate() { + *byte = (index.wrapping_mul(53) + 0x81) as u8; + } + for size in [0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096] { + for source_offset in 0..8 { + for destination_offset in 0..16 { + for variant in 0..3 { + let mut destination = [0xa5u8; 4096 + 32]; + // SAFETY: real nonoverlapping CPU arrays cover both spans. + let pointer = unsafe { destination.as_mut_ptr().add(destination_offset) }; + let input = unsafe { source.as_ptr().add(source_offset) }; + let returned = unsafe { + match variant { + 0 => nvkms_memcpy(pointer.cast(), input.cast(), size), + 1 => nvlink_memcpy(pointer.cast(), input.cast(), size as u64), + _ => nvswitch_os_memcpy(pointer.cast(), input.cast(), size as u64), + } + }; + assert_eq!(returned, pointer.cast()); + for (index, &byte) in destination.iter().enumerate() { + let expected = + if (destination_offset..destination_offset + size).contains(&index) { + ((source_offset + index - destination_offset).wrapping_mul(53) + + 0x81) as u8 + } else { + 0xa5 + }; + assert_eq!(byte, expected); + } + } + } + } + for offset in 0..16 { + for value in [-1i32, 0, 0x80, 0x180, 0x1ff] { + for variant in 0..3 { + let mut destination = [0xa5u8; 4096 + 32]; + // SAFETY: actual CPU storage covers the complete span. + let pointer = unsafe { destination.as_mut_ptr().add(offset) }; + let returned = unsafe { + match variant { + 0 => nvkms_memset(pointer.cast(), value as u8, size), + 1 => nvlink_memset(pointer.cast(), value, size as u64), + _ => nvswitch_os_memset(pointer.cast(), value, size as u64), + } + }; + assert_eq!(returned, pointer.cast()); + for (index, &byte) in destination.iter().enumerate() { + assert_eq!( + byte, + if (offset..offset + size).contains(&index) { + value as u8 + } else { + 0xa5 + } + ); + } + } + } + } + } +} + +#[test] +fn original_display_memmove_handles_both_overlap_directions_and_same_range() { + for size in [0, 1, 2, 7, 8, 15, 16, 31, 127, 128, 129, 256, 4096] { + for (source_offset, destination_offset) in [(0, 1), (1, 0), (7, 14), (14, 7), (8, 8)] { + let mut bytes = [0u8; 4096 + 32]; + for (index, byte) in bytes.iter_mut().enumerate() { + *byte = (index.wrapping_mul(19) + 0x83) as u8; + } + // SAFETY: one real CPU allocation covers both full possibly + // overlapping ranges, which original memmove explicitly permits. + let source = unsafe { bytes.as_ptr().add(source_offset) }; + let destination = unsafe { bytes.as_mut_ptr().add(destination_offset) }; + assert_eq!( + unsafe { nvkms_memmove(destination.cast(), source.cast(), size) }, + destination.cast() + ); + for (index, &byte) in bytes.iter().enumerate() { + let original_index = + if (destination_offset..destination_offset + size).contains(&index) { + source_offset + index - destination_offset + } else { + index + }; + assert_eq!(byte, (original_index.wrapping_mul(19) + 0x83) as u8); + } + } + } +} + +#[test] +fn original_display_compare_and_native_length_returns_use_raw_unsigned_bytes() { + for size in [1, 2, 7, 8, 15, 16, 31, 127, 128, 129, 256] { + for mismatch in 0..size { + let mut left = [0x55u8; 288]; + let mut right = left; + left[mismatch] = 0x80; + right[mismatch] = 0x7f; + left[size] = 0; + right[size] = 0xff; + // SAFETY: readable actual CPU arrays cover the exact requested spans. + unsafe { + assert_eq!( + nvkms_memcmp(left.as_ptr().cast(), right.as_ptr().cast(), size).signum(), + 1 + ); + assert_eq!( + nvkms_memcmp(right.as_ptr().cast(), left.as_ptr().cast(), size).signum(), + -1 + ); + assert_eq!( + nvkms_memcmp(left.as_ptr().cast(), right.as_ptr().cast(), mismatch), + 0 + ); + } + } + } + let mut string = [0x80u8; 4096 + 32]; + for offset in 0..16 { + for length in [0, 1, 7, 8, 15, 16, 31, 127, 128, 129, 4096] { + string.fill(0x80); + string[offset + length] = 0; + // SAFETY: actual readable CPU bytes include their terminating NUL. + let pointer = unsafe { string.as_ptr().add(offset) }; + unsafe { + assert_eq!(nvkms_strlen(pointer.cast()), length); + assert_eq!(nvlink_strlen(pointer.cast()), length as u64); + assert_eq!(nvswitch_os_strlen(pointer.cast()), length as u64); + } + } + } +} + +#[test] +fn nvlink_c_metadata_retains_full_payload_and_zero_size_ownership() { + unsafe extern "C" { + fn nvlink_malloc(bytes: u64) -> *mut c_void; + fn nvlink_free(pointer: *mut c_void); + } + let sizes = [0, 1, 7, 8, 15, 16, 17, 4095, 4096, 4097, 65537]; + let mut pointers = [ptr::null_mut::(); 11]; + for (index, (&bytes, pointer)) in sizes.iter().zip(&mut pointers).enumerate() { + // SAFETY: this hosted process has a live common heap and no reentry. + *pointer = unsafe { nvlink_malloc(bytes) }; + assert!(!pointer.is_null()); + assert_eq!(*pointer as usize % 16, 0); + // SAFETY: the checked allocation owns the complete requested payload. + unsafe { + pointer + .cast::() + .write_bytes(index as u8, bytes as usize) + }; + } + for (index, (&bytes, &pointer)) in sizes.iter().zip(&pointers).enumerate().rev() { + assert!(!pointers[..index].contains(&pointer)); + // SAFETY: all allocations are still live and held only by this test. + let payload = unsafe { core::slice::from_raw_parts(pointer.cast::(), bytes as usize) }; + assert!(payload.iter().all(|&byte| byte == index as u8)); + // SAFETY: free exactly this allocator's original live pointer once. + unsafe { nvlink_free(pointer) }; + } + // SAFETY: the original null-free contract is preserved by the common heap. + unsafe { nvlink_free(ptr::null_mut()) }; +} + +#[test] +fn nvlink_c_invalid_native_layouts_return_null_before_allocating() { + unsafe extern "C" { + fn nvlink_malloc(bytes: u64) -> *mut c_void; + } + for bytes in [u64::MAX, isize::MAX as u64, isize::MAX as u64 - 16] { + // SAFETY: a scalar request; checked layouts refuse this before the heap. + assert!(unsafe { nvlink_malloc(bytes) }.is_null()); + } +} + +#[test] +fn nvkms_c_metadata_zero_flags_and_native_sizes_use_the_real_common_heap() { + unsafe extern "C" { + fn nvkms_alloc(bytes: u64, zero: u8) -> *mut c_void; + fn nvkms_free(pointer: *mut c_void, bytes: u64); + } + let cases = [(0, 255), (1, 1), (15, 2), (16, 255), (17, 0), (4097, 1)]; + let mut pointers = [ptr::null_mut::(); 6]; + for (index, (&(bytes, zero), pointer)) in cases.iter().zip(&mut pointers).enumerate() { + // SAFETY: ordinary hosted process context, live shared heap, no reentry. + *pointer = unsafe { nvkms_alloc(bytes, zero) }; + assert!(!pointer.is_null()); + assert_eq!(*pointer as usize % 16, 0); + if zero != 0 { + // SAFETY: successful allocation initialized the full requested span. + let payload = + unsafe { core::slice::from_raw_parts(pointer.cast::(), bytes as usize) }; + assert!(payload.iter().all(|&byte| byte == 0)); + } + // SAFETY: uniquely owned complete payload, initialized before reading. + unsafe { + pointer + .cast::() + .write_bytes(0x70 + index as u8, bytes as usize) + }; + } + for (index, (&(bytes, _), &pointer)) in cases.iter().zip(&pointers).enumerate().rev() { + assert!(!pointers[..index].contains(&pointer)); + // SAFETY: all allocations are still live and exclusively held here. + let payload = unsafe { core::slice::from_raw_parts(pointer.cast::(), bytes as usize) }; + assert!(payload.iter().all(|&byte| byte == 0x70 + index as u8)); + // SAFETY: original pointer and exact size, once, after all access stops. + unsafe { nvkms_free(pointer, bytes) }; + } + // SAFETY: original NULL-free contract is valid independently of the size. + unsafe { nvkms_free(ptr::null_mut(), u64::MAX) }; +} + +#[test] +fn nvkms_c_invalid_layouts_fail_for_every_original_zero_flag_value() { + unsafe extern "C" { + fn nvkms_alloc(bytes: u64, zero: u8) -> *mut c_void; + } + for zero in [0, 1, 2, 255] { + for bytes in [u64::MAX, isize::MAX as u64, isize::MAX as u64 - 16] { + // SAFETY: invalid scalar layouts are rejected before heap access. + assert!(unsafe { nvkms_alloc(bytes, zero) }.is_null()); + } + } +} diff --git a/crates/stela-drivers/src/net/igc.rs b/crates/stela-drivers/src/net/igc.rs index c581825a0c..64509831ba 100644 --- a/crates/stela-drivers/src/net/igc.rs +++ b/crates/stela-drivers/src/net/igc.rs @@ -219,7 +219,7 @@ impl Igc { unsafe { pci::disable_aspm_l1_2_link(function, handoff) } })?; let device = registers(handoff, function.bars()[0], 0, REGISTER_BYTES)?; - function.enable(); + function.enable_polled(); let clock = handoff.clock; let mut hardware = hardware::Hardware::new(&device, &clock)?; let phy_identity = hardware.initialize()?; diff --git a/crates/stela-drivers/src/net/realtek.rs b/crates/stela-drivers/src/net/realtek.rs index 7cf5455d2c..d8da2ef194 100644 --- a/crates/stela-drivers/src/net/realtek.rs +++ b/crates/stela-drivers/src/net/realtek.rs @@ -256,7 +256,7 @@ impl Realtek { .flatten() .find(|b| matches!(b, pci::Bar::Memory { .. })); let device = map_registers(handoff, bar, 0, 256)?; - function.enable(); + function.enable_polled(); let txconfig = device.read32(TX_CONFIG); let revision = detect_revision(&device, txconfig, |bytes| { map_registers(handoff, bar, 0, bytes).map(|_| ()) diff --git a/crates/stela-drivers/src/usb/xhci.rs b/crates/stela-drivers/src/usb/xhci.rs index 248cd1c949..86d21d0180 100644 --- a/crates/stela-drivers/src/usb/xhci.rs +++ b/crates/stela-drivers/src/usb/xhci.rs @@ -2018,7 +2018,7 @@ pub fn attach_with_provider( .and_then(|bar| bar.memory()) .map_or(0, |range| range.end - range.start); let registers = registers(handoff, bars[0], 0, bytes)?; - function.enable(); + function.enable_polled(); let address = function.address; let location = format!( "xhci {:04x}:{:02x}:{:02x}.{}", diff --git a/xtask/src/boot.rs b/xtask/src/boot.rs index a5b637f228..0db8f1ca48 100644 --- a/xtask/src/boot.rs +++ b/xtask/src/boot.rs @@ -724,8 +724,7 @@ fn launch(arguments: Run) -> Result { let cpu = qemu_cpu( arguments.cpu.as_deref(), arguments.no_la57, - usb - || system + usb || system || arguments.native_dma_check || arguments.native_dma_isolation_check || arguments.native_work_check diff --git a/xtask/src/gpu.rs b/xtask/src/gpu.rs index 7aea4aa9d7..6d8d89bb3f 100644 --- a/xtask/src/gpu.rs +++ b/xtask/src/gpu.rs @@ -4,6 +4,10 @@ use anyhow::Result; use clap::{Subcommand, ValueEnum}; use std::path::PathBuf; +#[cfg(test)] +mod amd; +#[cfg(test)] +mod intel; mod macos; mod mesa; mod nvidia; @@ -36,8 +40,8 @@ impl AirFpProfile { #[derive(Subcommand)] pub enum Command { - /// Compile the macOS-facing IOKit helper against kernel headers for - /// arm64e, arm64 and x86-64; inspect its remaining IOKit service imports. + /// Build the IOKit kernel helper and separate user-space Metal library + /// objects for arm64e, arm64 and x86-64. No driver is installed or loaded. Macos, /// Build NVIDIA, AMD and Intel shader compiler libraries for this host /// without Vulkan/OpenGL frontends, and run the native codegen probes. diff --git a/xtask/src/gpu/amd.rs b/xtask/src/gpu/amd.rs new file mode 100644 index 0000000000..968744cf80 --- /dev/null +++ b/xtask/src/gpu/amd.rs @@ -0,0 +1,50 @@ +//! CPU acquisition checks compile the actual retained AMD refresh function. +use super::support::capture; +use crate::tools; +use std::process::Command; + +#[test] +fn discovery_refresh_bounds_actual_driver_reads_and_preserves_failed_output() { + run("discovery-refresh-test"); +} + +#[test] +fn mm_index_reads_preserve_original_order_and_refuse_before_access() { + run("vram-mm-test"); +} + +#[test] +fn tmr_query_preserves_original_selection_order_and_failures() { + run("tmr-test"); +} + +#[test] +fn pci_admission_and_sources_preserve_original_matching_and_callers() { + run("pci-test"); +} + +#[test] +fn hardware_ip_walk_preserves_original_packed_data_and_atomic_refusals() { + run("ip-test"); +} + +#[test] +fn selected_discovery_file_preserves_original_validation_and_release_order() { + run("file-test"); +} + +fn run(target: &str) { + let directory = tempfile::tempdir().unwrap(); + let source = tools::root().join("crates/stela-drivers/src/gpu/amd/stela/Makefile"); + let compiler = tools::which("clang").unwrap(); + let mut command = Command::new(tools::which("make").unwrap()); + command + .current_dir(tools::root()) + .env_remove("MAKEFLAGS") + .arg("-f") + .arg(source) + .arg(format!("OUT_DIR={}", directory.path().display())) + .arg(format!("CC={}", compiler.display())) + .arg(target); + capture(&mut command).unwrap(); +} diff --git a/xtask/src/gpu/intel.rs b/xtask/src/gpu/intel.rs new file mode 100644 index 0000000000..f97a689bd7 --- /dev/null +++ b/xtask/src/gpu/intel.rs @@ -0,0 +1,32 @@ +//! Compare native firmware preparation with the frozen original Xe helpers. +use super::support::capture; +use crate::tools; +use std::process::Command; + +#[test] +fn firmware_wopcm_gsm_pat_and_guc_reset_match_original_policy_and_register_traces() { + let directory = tempfile::tempdir().unwrap(); + let source = tools::root().join("crates/stela-drivers/src/gpu/intel/stela/Makefile"); + let mut command = Command::new(tools::which("make").unwrap()); + command + .current_dir(tools::root()) + .env_remove("MAKEFLAGS") + .arg("-f") + .arg(source) + .arg(format!("BUILD={}", directory.path().display())) + .arg(format!( + "HOST_CC={}", + tools::which("clang").unwrap().display() + )) + .args([ + "SANITIZE=", + "test-firmware", + "test-huc-firmware", + "test-wopcm", + "test-wopcm-owned", + "test-ggtt-probe", + "test-pat", + "test-guc-reset", + ]); + capture(&mut command).unwrap(); +} diff --git a/xtask/src/gpu/macos.rs b/xtask/src/gpu/macos.rs index 76902b8cab..0b62ca7b2a 100644 --- a/xtask/src/gpu/macos.rs +++ b/xtask/src/gpu/macos.rs @@ -1,4 +1,5 @@ -//! Kernel-ABI compilation, without installing or loading a driver. +//! Kernel and user-space ABI compilation, without installing or loading a driver. +mod library; use super::support::{capture, evidence_directory, source_binding}; use crate::tools; use anyhow::{Context, Result, ensure}; @@ -21,9 +22,9 @@ fn sdk(arguments: &[&str]) -> Result { // Make's dependency files include the headers actually read by each target, // including SDK headers. Hash these inputs rather than just an SDK label. -fn dependencies(directory: &Path) -> Result> { +fn dependencies(directory: &Path, filename: &str) -> Result> { let mut paths = BTreeSet::new(); - let text = fs::read_to_string(directory.join("memory.d"))?; + let text = fs::read_to_string(directory.join(filename))?; let text = text.replace("\\\n", " "); let (_, inputs) = text .lines() @@ -36,6 +37,76 @@ fn dependencies(directory: &Path) -> Result> { Ok(paths) } +fn inspect_component( + path: &Path, + arch: &str, + architecture: Architecture, + subarchitecture: u32, + expected: &[&str], + required: &[&str], +) -> Result { + let bytes = fs::read(path)?; + let object = object::File::parse(bytes.as_slice())?; + // object 0.37's sub_architecture() compares the entire subtype word; + // arm64e kernel ABI capability bits must be separated before comparing. + let subtype = match &object { + object::File::MachO64(file) => { + use object::read::macho::MachHeader; + file.macho_header().cpusubtype(file.endian()) + } + _ => anyhow::bail!("expected a 64-bit Mach-O kernel object"), + }; + ensure!( + object.format() == BinaryFormat::MachO + && object.kind() == ObjectKind::Relocatable + && object.architecture() == architecture + && subtype & !object::macho::CPU_SUBTYPE_MASK == subarchitecture, + "incorrect kernel object ABI for {arch}" + ); + let imports: BTreeSet<_> = object + .symbols() + .filter(|symbol| symbol.is_undefined()) + .map(|symbol| symbol.name().map(str::to_owned)) + .collect::>()?; + ensure!( + imports == expected.iter().map(|s| (*s).to_owned()).collect(), + "unexpected kernel imports for {arch}: {imports:?}" + ); + for required in required { + ensure!( + object + .symbols() + .any(|symbol| { symbol.is_definition() && symbol.name() == Ok(*required) }), + "missing {required} for {arch}" + ); + } + Ok( + json!({"architecture":arch,"cpu_subtype_and_capabilities":subtype, + "format":"Mach-O relocatable kernel component", "artifact":tools::binding(path)?, + "kernel_imports":imports}), + ) +} + +fn contract(source: &Path, sdk_root: &Path, output: &Path) -> Result { + fs::create_dir_all(output)?; + let mut command = Command::new(tools::which("make").context("install make")?); + command + .current_dir(tools::root()) + .arg("-f") + .arg(source.join("Makefile")) + .arg(format!("BUILD={}", output.display())) + .arg(format!("SDKROOT={}", sdk_root.display())) + .arg("contract-tests"); + let log = output.join("contract.log"); + fs::write(&log, capture(&mut command)?)?; + Ok( + json!({"scope":"Actual owner C++ with test-only original-service mocks under ASan/UBSan; no kernel page wiring or hardware", + "command":format!("{command:?}"),"binary":tools::binding(&output.join("task-memory-contract"))?, + "output":tools::binding(&log)?,"dependencies":dependencies(output,"task-memory-contract.d")? + .iter().map(|p|tools::binding(p)).collect::>>()?}), + ) +} + pub fn build() -> Result<()> { ensure!( cfg!(target_os = "macos"), @@ -93,60 +164,44 @@ pub fn build() -> Result<()> { log_path.display() ); let path = directory.join("gpu-memory.o"); - let bytes = fs::read(&path)?; - let object = object::File::parse(bytes.as_slice())?; - // object 0.37's sub_architecture() compares the entire subtype word; - // arm64e kernel ABI capability bits must be separated before comparing. - let subtype = match &object { - object::File::MachO64(file) => { - use object::read::macho::MachHeader; - file.macho_header().cpusubtype(file.endian()) - } - _ => anyhow::bail!("expected a 64-bit Mach-O kernel object"), - }; - ensure!( - object.format() == BinaryFormat::MachO - && object.kind() == ObjectKind::Relocatable - && object.architecture() == architecture - && subtype & !object::macho::CPU_SUBTYPE_MASK == subarchitecture, - "incorrect kernel object ABI for {arch}" - ); - let imports: BTreeSet<_> = object - .symbols() - .filter(|symbol| symbol.is_undefined()) - .map(|symbol| symbol.name().map(str::to_owned)) - .collect::>()?; // Apple's x86 kernel headers redirect bzero to __bzero. let zero = if arch == "x86_64" { "___bzero" } else { "_bzero" }; - let expected = ["_IOFreeAligned", "_IOMallocAligned", zero] - .map(str::to_owned) - .into_iter() - .collect(); - ensure!( - imports == expected, - "unexpected kernel imports for {arch}: {imports:?}" - ); - for required in ["_stela_gpu_iokit_allocate_zeroed", "_stela_gpu_iokit_free"] { - ensure!( - object - .symbols() - .any(|symbol| { symbol.is_definition() && symbol.name() == Ok(required) }), - "missing {required} for {arch}" - ); - } - inputs.extend(dependencies(&directory)?); - artifacts.push(json!({ - "architecture": arch, - "cpu_subtype_and_capabilities": subtype, - "format": "Mach-O relocatable kernel component", - "artifact": tools::binding(&path)?, - "kernel_imports": imports, - })); + artifacts.push(inspect_component( + &path, + arch, + architecture, + subarchitecture, + &["_IOFreeAligned", "_IOMallocAligned", zero], + &["_stela_gpu_iokit_allocate_zeroed", "_stela_gpu_iokit_free"], + )?); + let task = directory.join("task_memory.o"); + artifacts.push(inspect_component( + &task, + arch, + architecture, + subarchitecture, + &[ + "__ZN18IOMemoryDescriptor16withAddressRangeEyyjP4task", + "_kernel_task", + "_panic", + "_task_reference", + "_task_deallocate", + ], + &[ + "__ZN5stela3gpu10TaskMemory7prepareEP4taskyyj", + "__ZN5stela3gpu10TaskMemory23finish_after_quiescenceEb", + "__ZN5stela3gpu10TaskMemoryD1Ev", + "__ZN5stela3gpu10TaskMemoryD2Ev", + ], + )?); + inputs.extend(dependencies(&directory, "memory.d")?); + inputs.extend(dependencies(&directory, "task_memory.d")?); } + let task_contract = contract(&source, &sdk_root, &evidence.join("task-contract"))?; let inputs = inputs .iter() .map(|path| tools::binding(path)) @@ -156,7 +211,8 @@ pub fn build() -> Result<()> { &receipt, serde_json::to_vec_pretty(&json!({ "schema": 1, - "scope": "IOKit CPU allocation helper for the macOS-facing frontend", + "scope": "Original IOKit CPU allocation and task-owned prepared memory for the macOS frontend", + "task_memory_contract":task_contract, "limits": "Compilation and relocatable linking only; not a loadable kext or macOS 27 ABI qualification, device initialization, DMA or Metal execution.", "sdk": { "path": sdk_root, "version": sdk_version.trim() }, "compiler": compiler, @@ -170,5 +226,18 @@ pub fn build() -> Result<()> { "macOS GPU memory components built for three ABIs: {}", receipt.display() ); - Ok(()) + library::build(&gpu, &sdk_root, sdk_version.trim(), &compiler, &evidence) +} + +#[cfg(all(test, target_os = "macos"))] +#[test] +fn task_memory_preserves_original_service_ownership_and_failure_contracts() { + let sdk_root = PathBuf::from(sdk(&["--show-sdk-path"]).unwrap().trim()); + let output = tempfile::tempdir().unwrap(); + contract( + &tools::root().join("crates/stela-drivers/src/gpu/macos"), + &sdk_root, + output.path(), + ) + .unwrap(); } diff --git a/xtask/src/gpu/macos/library.rs b/xtask/src/gpu/macos/library.rs new file mode 100644 index 0000000000..946ec3d660 --- /dev/null +++ b/xtask/src/gpu/macos/library.rs @@ -0,0 +1,137 @@ +//! Link the actual user-space objects against the SDK's public frameworks. +use super::{dependencies, tools}; +use crate::gpu::support::source_binding; +use anyhow::{Context, Result, ensure}; +use object::{Architecture, BinaryFormat, Object, ObjectKind, ObjectSymbol}; +use serde_json::json; +use std::{ + collections::BTreeSet, + fs::{self, File}, + path::Path, + process::{Command, Stdio}, +}; + +pub(super) fn build( + gpu: &Path, + sdk_root: &Path, + sdk_version: &str, + compiler: &str, + evidence: &Path, +) -> Result<()> { + let source = gpu.join("metal/macos"); + let mut artifacts = Vec::new(); + let mut inputs = BTreeSet::new(); + for (arch, architecture, expected_subtype) in [ + ( + "arm64", + Architecture::Aarch64, + object::macho::CPU_SUBTYPE_ARM64_ALL, + ), + ( + "arm64e", + Architecture::Aarch64, + object::macho::CPU_SUBTYPE_ARM64E, + ), + ( + "x86_64", + Architecture::X86_64, + object::macho::CPU_SUBTYPE_X86_64_ALL, + ), + ] { + let directory = evidence.join("metal").join(arch); + let log_path = evidence.join(format!("metal-library-{arch}.log")); + let log = File::create(&log_path)?; + let status = Command::new(tools::which("make").context("install make")?) + .current_dir(tools::root()) + .arg("-f") + .arg(source.join("Makefile")) + .arg(format!("ARCH={arch}")) + .arg(format!("BUILD={}", directory.display())) + .arg(format!("SDKROOT={}", sdk_root.display())) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log)) + .status()?; + ensure!( + status.success(), + "Metal library build failed: {}", + log_path.display() + ); + let path = directory.join("libstela-metal-library.dylib"); + let bytes = fs::read(&path)?; + let binary = object::File::parse(bytes.as_slice())?; + let subtype = match &binary { + object::File::MachO64(file) => { + use object::read::macho::MachHeader; + file.macho_header().cpusubtype(file.endian()) + } + _ => anyhow::bail!("expected a 64-bit Mach-O Metal component"), + }; + ensure!( + binary.format() == BinaryFormat::MachO + && binary.kind() == ObjectKind::Dynamic + && binary.architecture() == architecture + && subtype & !object::macho::CPU_SUBTYPE_MASK == expected_subtype, + "incorrect Metal component ABI for {arch}" + ); + for required in [ + "_STELAMetalCreateLibrary", + "_STELAMetalCopyFunctionSnapshot", + ] { + ensure!( + binary + .symbols() + .any(|s| s.is_definition() && s.name() == Ok(required)), + "missing {required} for {arch}" + ); + } + // The SDK link resolves these to real frameworks. No private driver, + // foreign-CPU Rust archive, LLVM or native hardware library is linked. + let imports = binary + .imports()? + .into_iter() + .map(|import| { + Ok(json!({ + "name": std::str::from_utf8(import.name())?, + "library": std::str::from_utf8(import.library())?, + })) + }) + .collect::>>()?; + let forbidden = [ + "_IOServiceOpen", + "_IOConnectCallMethod", + "_stela_metal_input_open", + ]; + ensure!( + !binary + .symbols() + .any(|s| s.is_undefined() && s.name().is_ok_and(|name| forbidden.contains(&name))), + "unexpected device or helper binding in Metal object" + ); + inputs.extend(dependencies(&directory, "library.d")?); + artifacts.push( + json!({"architecture":arch,"cpu_subtype_and_capabilities":subtype, + "artifact":tools::binding(&path)?,"framework_imports":imports}), + ); + } + let inputs = inputs + .iter() + .map(|path| tools::binding(path)) + .collect::>>()?; + let receipt = evidence.join("metal-library.json"); + fs::write( + &receipt, + serde_json::to_vec_pretty(&json!({ + "schema":1, + "scope":"Owned Metal library/function/reflection user-space components", + "limits":"Compile and SDK link only. No Objective-C execution, registered MTLDevice, authenticated helper transport, pipeline, macOS27 runtime ABI or GPU qualification.", + "sdk":{"path":sdk_root,"version":sdk_version},"compiler":compiler, + "source_sha256":source_binding(&source)?,"task":tools::binding(&tools::root().join(file!()))?, + "inputs":inputs,"artifacts":artifacts + }))?, + )?; + println!( + "Metal library components linked for three ABIs: {}", + receipt.display() + ); + Ok(()) +} diff --git a/xtask/src/gpu/mesa.rs b/xtask/src/gpu/mesa.rs index 73250b088c..cec30fe17c 100644 --- a/xtask/src/gpu/mesa.rs +++ b/xtask/src/gpu/mesa.rs @@ -13,6 +13,7 @@ use std::{ process::{Command, Stdio}, }; +mod library; mod threadgroup; const LIBRARIES: &[&str] = &[ @@ -120,6 +121,9 @@ fn inspect_archive(path: &Path) -> Result { path.file_name().and_then(|name| name.to_str()), Some( "libamd_compiler_support.a" + | "libstela_amd_air.a" + | "libstela_nv_air.a" + | "libstela_intel_air.a" | "libintel_dev.a" | "libstela_amd_surface.a" | "libstela_amd_image.a" @@ -410,6 +414,17 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { "metal/compiler/apple_source.c", "metal/compiler/apple_source.h", "metal/compiler/apple_source_test.c", + "metal/compiler/threadgroup.c", + "metal/compiler/threadgroup.h", + "metal/compiler/tests/threadgroup.c", + "metal/compiler/tests/threadgroup_nir.c", + "nvidia/stela/hosted/air_compile.c", + "nvidia/stela/hosted/air_compile.h", + "nvidia/stela/tests/air_compile.c", + "intel/stela/hosted/air_compile.c", + "intel/stela/hosted/air_compile.h", + "intel/stela/hosted/air_validate_elk.c", + "intel/stela/tests/air_compile.c", "nvidia/stela/hosted/image.c", "nvidia/stela/hosted/image.h", "nvidia/stela/tests/image.c", @@ -439,6 +454,9 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { "amd/stela/image_copy.h", "amd/tests/image_copy_test.c", "amd/tests/image_fixture.h", + "amd/stela/air_compile.c", + "amd/stela/air_compile.h", + "amd/tests/air_compile.c", "amd/stela/compute.c", "amd/stela/compute.h", "amd/stela/compute_policy.c", @@ -555,10 +573,37 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { }; let build = tools::root().join(".stela/gpu/build").join(cache); let evidence = evidence_directory()?; + let metal_input = if cfg!(target_os = "macos") && llvm_library.is_some() { + Some(library::build_input(&evidence)?) + } else { + None + }; let input_snapshots = snapshot_air_inputs(air_inputs, &evidence, "air-input")?; let threadgroup_snapshots = snapshot_air_inputs(threadgroup_inputs, &evidence, "threadgroup-input")?; let hash = source_binding(&source)?; + // Meson 1.9 validates supplied options against its old cached inventory + // before rereading meson.options. Refresh once when upgrading this cache. + let cached_options = build.join("meson-info/intro-buildoptions.json"); + if cached_options.is_file() { + let cached: Vec = serde_json::from_slice(&fs::read(cached_options)?)?; + if !cached + .iter() + .any(|option| option["name"] == "stela-metal-input-library") + { + run( + Command::new(&meson) + .env("PATH", &path) + .env("PYTHONDONTWRITEBYTECODE", "1") + .envs(llvm_config.iter().map(|config| ("LLVM_CONFIG", config))) + .args(["setup", "--reconfigure", "--wrap-mode=nodownload"]) + .arg(&build) + .arg(&source), + &evidence, + "refresh-options", + )?; + } + } let mut setup = Command::new(&meson); setup .current_dir(tools::root()) @@ -607,12 +652,25 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { .as_ref() .map_or_else(String::new, |path| path.display().to_string()) )); + setup.arg(format!( + "-Dstela-metal-input-library={}", + metal_input + .as_ref() + .map_or_else(String::new, |p| p.display().to_string()) + )); if build.join("meson-private/coredata.dat").is_file() { setup.arg("--reconfigure"); } run(&mut setup, &evidence, "setup")?; let mut compile = Command::new(&ninja); let mut library_paths = LIBRARIES.to_vec(); + if metal_input.is_some() { + library_paths.push("src/stela/libstela_metal_threadgroup.a"); + library_paths.push("src/stela/libstela_metal_assembly.a"); + library_paths.push("src/stela/libstela_amd_air.a"); + library_paths.push("src/stela/libstela_nv_air.a"); + library_paths.push("src/stela/libstela_intel_air.a"); + } if llvm_sdk.is_some() { library_paths.push("src/amd/llvm/libamd_common_llvm.a"); library_paths.push("src/stela/libstela_amd_llvm_float.a"); @@ -671,7 +729,46 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { compile.arg("src/stela/stela_amd_air_threadgroup_probe"); } } + if metal_input.is_some() { + compile.args([ + "src/stela/stela_metal_threadgroup_test", + "src/stela/stela_metal_threadgroup_nir_test", + "src/stela/stela_metal_assembly_test", + "src/stela/stela_amd_air_compile_test", + "src/stela/stela_nv_air_compile_test", + "src/stela/stela_intel_air_compile_test", + ]); + } run(&mut compile, &evidence, "compile")?; + let amd_air_owned = metal_input + .as_ref() + .map(|_| { + library::verify_owned( + &build, + &evidence, + "amd", + "aco", + 164, + "owned AMD AIR compiler lifetime, multi-buffer, producer and failure tests passed", + ) + }) + .transpose()?; + let nv_air_owned = metal_input.as_ref().map(|_| library::verify_owned(&build, &evidence, "nv", "nak", 310, + "owned NAK compiler/table/QMD/lifetime/failure fixtures passed; no hardware execution")).transpose()?; + let metal_assembly = metal_input + .as_ref() + .map(|input| library::verify(&build, &evidence, input, &gpu)) + .transpose()?; + let intel_air_owned = metal_input.as_ref().map(|_| library::verify_owned(&build, &evidence, "intel", "intel", 757, + "owned Intel compiler/RAW/table/plan/lifetime fixtures passed; no hardware execution")).transpose()?; + let intel_gen7_shared = metal_input + .as_ref() + .map(|_| library::verify_gen7_shared(&build, &evidence)) + .transpose()?; + let metal_threadgroup_values = metal_input + .as_ref() + .map(|_| library::verify_threadgroup_values(&build, &evidence)) + .transpose()?; run( &mut Command::new(build.join("src/stela/stela_amd_commands_probe")), &evidence, @@ -940,6 +1037,12 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { "stela_platform_port": false, "hardware_executed": false, "metal_frontend": false, "source_compiler_boundary": source_compiler_boundary, + "metal_library_assembly": metal_assembly, + "amd_owned_air_compilation": amd_air_owned, + "nvidia_owned_air_compilation": nv_air_owned, + "intel_owned_air_compilation": intel_air_owned, + "intel_gen7_shared_admission": intel_gen7_shared, + "metal_threadgroup_values": metal_threadgroup_values, "air_compute_compiler_subset": llvm_library.is_some(), "amd_llvm_development_files": llvm_sdk, "optional_clrx_disassembler": clrx_disassembler, diff --git a/xtask/src/gpu/mesa/library.rs b/xtask/src/gpu/mesa/library.rs new file mode 100644 index 0000000000..8720b7a5c5 --- /dev/null +++ b/xtask/src/gpu/mesa/library.rs @@ -0,0 +1,363 @@ +//! Hosted library ownership uses the canonical parser and shared AIR inspector. +use super::{run, tools}; +use anyhow::{Result, ensure}; +use object::{Architecture, Object, ObjectSymbol}; +use serde_json::{Value, json}; +use std::{ + env, + path::{Path, PathBuf}, + process::Command, +}; + +pub(super) fn build_input(evidence: &Path) -> Result { + let target = tools::root().join(".stela/gpu/build/metal-input"); + run( + Command::new(env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .current_dir(tools::root()) + .env("CARGO_TARGET_DIR", &target) + .env("CARGO_INCREMENTAL", "0") + .args(["build", "--release", "--locked", "-p", "stela-metal-input"]), + evidence, + "metal-input", + )?; + let path = target.join("release/libstela_metal_input.a"); + ensure!(path.is_file(), "missing hosted Metal input archive"); + Ok(path) +} + +pub(super) fn verify(build: &Path, evidence: &Path, input: &Path, gpu: &Path) -> Result { + let path = build.join("src/stela/stela_metal_assembly_test"); + let bytes = std::fs::read(&path)?; + let binary = object::File::parse(bytes.as_slice())?; + let host_arch = match env::consts::ARCH { + "x86_64" => Architecture::X86_64, + "aarch64" => Architecture::Aarch64, + _ => anyhow::bail!("unsupported hosted Metal assembler architecture"), + }; + ensure!( + binary.architecture() == host_arch, + "wrong Metal assembler CPU ABI" + ); + let symbols = binary + .symbols() + .filter_map(|s| s.name().ok().map(str::to_owned)) + .collect::>(); + for required in [ + "_stela_metal_input_entry_metadata", + "_stela_metal_assemble_archive", + "_stela_air_inspect", + ] { + ensure!( + symbols.iter().any(|s| s == required), + "missing integrated {required}" + ); + } + ensure!( + !symbols + .iter() + .any(|s| s == "_stela_air_to_nir" || s.starts_with("_nir_")), + "local Metal library owner unexpectedly links NIR", + ); + run(&mut Command::new(&path), evidence, "metal-library-assembly")?; + Ok(json!({ + "scope":"Executed local C/Rust/LLVM ownership fixture; no private compiler invocation, Objective-C or GPU execution", + "input_library":tools::binding(input)?,"binary":tools::binding(&path)?, + "output":tools::binding(&evidence.join("metal-library-assembly.log"))?, + "input_sources_sha256":super::source_binding(&gpu.join("metal/input"))?, + "assembly_sources_sha256":super::source_binding(&gpu.join("metal/compiler"))?, + "manifest":tools::binding(&gpu.join("metal/macos/library_manifest.h"))?, + })) +} + +/// Exercise the retained compiler result after its canonical input is destroyed. +/// The fixture independently recompiles NIR with the original backend and compares the +/// complete code and configuration; it never executes GPU machine code. +pub(super) fn verify_owned( + build: &Path, + evidence: &Path, + vendor: &str, + backend: &str, + expected: usize, + completion: &str, +) -> Result { + let path = build.join(format!("src/stela/stela_{vendor}_air_compile_test")); + let bytes = std::fs::read(&path)?; + let binary = object::File::parse(bytes.as_slice())?; + let symbols = binary + .symbols() + .filter_map(|s| s.name().ok()) + .collect::>(); + for symbol in [ + format!("_stela_{vendor}_air_compile"), + format!("_stela_{vendor}_air_destroy"), + "_stela_air_to_nir".to_owned(), + "_stela_metal_assemble_archive".to_owned(), + ] { + ensure!( + symbols.contains(&symbol.as_str()), + "missing actual owned-compiler provider {symbol}" + ); + } + let stage = format!("{vendor}-air-owned"); + run(&mut Command::new(&path), evidence, &stage)?; + let log = evidence.join(format!("{stage}.log")); + let output = std::fs::read_to_string(&log)?; + let prefix = format!("owned-air-{backend} "); + let records = output + .lines() + .filter(|l| l.starts_with(&prefix) && !l.contains(" hold=")) + .count(); + let holds = output + .lines() + .filter(|l| l.starts_with(&prefix) && l.contains(" hold=")) + .count(); + ensure!( + records == expected && output.lines().last() == Some(completion), + "incomplete owned {vendor} compiler fixture" + ); + Ok(json!({ + "scope":"Executed hosted owned-compilation fixture: LLVM-generated inputs, original backend whole code/metadata oracle, lifetime and existing command-producer checks; no GPU execution or Metal pipeline object", + "binary":tools::binding(&path)?,"output":tools::binding(&log)?, + "owned_compiler_results":records,"unsupported_owned_fixture_results":holds,"hardware_executed":false, + })) +} + +/// The unchanged original two-entry AIR module passes through canonical +/// assembly and each owned compiler, with and without dynamic lengths. +pub(super) fn verify_shared(build: &Path, evidence: &Path, input: &Path) -> Result { + let assembly = build.join("src/stela/stela_metal_assembly_test"); + run( + Command::new(&assembly) + .arg("--archive-pair") + .arg(input) + .args([ + "stela_threadgroup_static", + "stela_threadgroup_dynamic", + "9", + "4", + "1", + "27", + "2", + "complete", + ]), + evidence, + "metal-shared-assembly", + )?; + let mut compilers = Vec::new(); + for (vendor, backend, expected, refusals) in [ + ("amd", "aco", 16, 1), + ("nv", "nak", 9, 9), + ("intel", "intel", 22, 23), + ] { + let binary = build.join(format!("src/stela/stela_{vendor}_air_compile_test")); + let static_stage = format!("{vendor}-air-owned-static"); + run( + Command::new(&binary) + .arg("--input") + .arg(input) + .arg("stela_threadgroup_static"), + evidence, + &static_stage, + )?; + let static_log = evidence.join(format!("{static_stage}.log")); + let output = std::fs::read_to_string(&static_log)?; + let prefix = format!("owned-air-{backend} "); + ensure!( + output + .lines() + .filter(|l| l.starts_with(&prefix) && !l.contains(" hold=")) + .count() + == expected, + "incomplete owned {vendor} static threadgroup matrix" + ); + let dynamic_stage = format!("{vendor}-air-owned-dynamic-refusal"); + run( + Command::new(&binary) + .arg("--shared-refusal") + .arg(input) + .arg("stela_threadgroup_dynamic"), + evidence, + &dynamic_stage, + )?; + let dynamic_log = evidence.join(format!("{dynamic_stage}.log")); + let output = std::fs::read_to_string(&dynamic_log)?; + let observed = output.lines().filter(|l| { + if vendor == "amd" { + *l == "shared input explicitly refused: dynamic AS3 dispatch specialization unavailable" + } else { + l.starts_with(&prefix) && l.contains(" shared_refusal=") + } + }).count(); + ensure!( + observed == refusals, + "incomplete owned {vendor} missing dynamic specialization refusals" + ); + compilers.push( + json!({"vendor":vendor,"compiled":expected,"dynamic_refusals":refusals, + "binary":tools::binding(&binary)?,"static_output":tools::binding(&static_log)?, + "dynamic_output":tools::binding(&dynamic_log)?}), + ); + } + let dynamic = verify_dynamic_shared(build, evidence, input)?; + Ok( + json!({"backend":"owned-static-threadgroup","scope":"Canonical two-entry assembly, retained original compiler code/metadata and command-plan oracles; no hardware execution", + "input":tools::binding(input)?,"assembly_binary":tools::binding(&assembly)?, + "assembly_output":tools::binding(&evidence.join("metal-shared-assembly.log"))?, + "compilers":compilers,"dynamic_specializations":dynamic,"hardware_executed":false}), + ) +} + +pub(super) fn verify_threadgroup_values(build: &Path, evidence: &Path) -> Result { + let binary = build.join("src/stela/stela_metal_threadgroup_test"); + let bytes = std::fs::read(&binary)?; + let object = object::File::parse(bytes.as_slice())?; + let symbols = object + .symbols() + .filter_map(|s| s.name().ok()) + .collect::>(); + ensure!( + symbols.contains(&"_stela_metal_threadgroup_normalize"), + "missing value normalizer" + ); + ensure!( + !symbols + .iter() + .any(|s| s.starts_with("_LLVM") || s.starts_with("_nir_")), + "threadgroup value owner unexpectedly depends on LLVM/NIR" + ); + run( + &mut Command::new(&binary), + evidence, + "metal-threadgroup-values", + )?; + let nir_binary = build.join("src/stela/stela_metal_threadgroup_nir_test"); + run( + &mut Command::new(&nir_binary), + evidence, + "metal-threadgroup-nir", + )?; + Ok( + json!({"scope":"Allocation-free value normalization plus actual LLVM/NIR regions, bounds and barrier semantics; synthetic input, no hardware execution", + "binary":tools::binding(&binary)?,"output":tools::binding(&evidence.join("metal-threadgroup-values.log"))?, + "nir_binary":tools::binding(&nir_binary)?,"nir_output":tools::binding(&evidence.join("metal-threadgroup-nir.log"))?}), + ) +} + +fn verify_dynamic_shared(build: &Path, evidence: &Path, original: &Path) -> Result> { + // Export the semantic fixture through its actual LLVM producer, rather than + // maintaining a second bitcode fixture or interpreting the source ourselves. + let mixed = evidence.join("multiple-threadgroups.bc"); + run( + Command::new(build.join("src/stela/stela_metal_threadgroup_nir_test")) + .arg("--export") + .arg(&mixed), + evidence, + "metal-threadgroup-export", + )?; + let mut records = Vec::new(); + for (vendor, backend, expected) in + [("amd", "aco", 16), ("nv", "nak", 9), ("intel", "intel", 22)] + { + let binary = build.join(format!("src/stela/stela_{vendor}_air_compile_test")); + for (name, input, entry, workgroup, rows, compiled, holds, total) in [ + ( + "128", + original, + "stela_threadgroup_dynamic", + "32", + vec!["3:128"], + expected, + 0, + 128, + ), + ( + "256", + original, + "stela_threadgroup_dynamic", + "32", + vec!["3:256"], + expected, + 0, + 256, + ), + ( + "512", + original, + "stela_threadgroup_dynamic", + "32", + vec!["3:512"], + expected, + 0, + 512, + ), + ( + "mixed", + mixed.as_path(), + "kernel", + "64", + vec!["3:256", "11:16", "7:128"], + if vendor == "intel" { 20 } else { expected }, + if vendor == "intel" { 2 } else { 0 }, + 403, + ), + ] { + let stage = format!("{vendor}-air-owned-threadgroup-{name}"); + run( + Command::new(&binary) + .arg("--threadgroup") + .arg(input) + .arg(entry) + .arg(workgroup) + .args(&rows), + evidence, + &stage, + )?; + let log = evidence.join(format!("{stage}.log")); + let text = std::fs::read_to_string(&log)?; + let prefix = format!("owned-threadgroup-{backend} "); + let output = text + .lines() + .filter(|l| l.starts_with(&prefix)) + .collect::>(); + ensure!( + output.iter().filter(|l| !l.contains(" hold=")).count() == compiled + && output.iter().filter(|l| l.contains(" hold=")).count() == holds + && output.iter().filter(|l| !l.contains(" hold=")).all(|l| l + .split_whitespace() + .any(|field| field == format!("total_shared={total}"))), + "incomplete {vendor} threadgroup specialization {name}" + ); + records.push(json!({"vendor":vendor,"fixture":name,"compiled":compiled,"typed_holds":holds, + "total_shared_bytes":total,"input":tools::binding(input)?,"binary":tools::binding(&binary)?, + "output":tools::binding(&log)?,"hardware_executed":false})); + } + } + Ok(records) +} + +pub(super) fn verify_gen7_shared(build: &Path, evidence: &Path) -> Result { + let binary = build.join("src/stela/stela_intel_air_compile_test"); + run( + Command::new(&binary).arg("--gen7-shared"), + evidence, + "intel-gen7-shared", + )?; + let log = evidence.join("intel-gen7-shared.log"); + let text = std::fs::read_to_string(&log)?; + ensure!( + text.lines() + .filter(|l| l.starts_with("guard ") && l.contains("typed_refusal_before_elk_compile=1")) + .count() + == 4 + && text + .lines() + .filter(|l| l.starts_with("owned-air-intel input=root-static-shared-guard ")) + .count() + == 11, + "incomplete Gen7 shared admission/original compiler fixture" + ); + Ok( + json!({"scope":"Synthetic static LLVM through actual canonical owned compiler; four Gen70 typed refusals and eleven aligned32/Gen75+ original code/progdata/ISA/command comparisons; no hardware execution", + "binary":tools::binding(&binary)?,"output":tools::binding(&log)?}), + ) +} diff --git a/xtask/src/gpu/mesa/threadgroup.rs b/xtask/src/gpu/mesa/threadgroup.rs index ead52d0488..56c030ae26 100644 --- a/xtask/src/gpu/mesa/threadgroup.rs +++ b/xtask/src/gpu/mesa/threadgroup.rs @@ -32,6 +32,11 @@ pub(super) fn run( .context("missing threadgroup snapshot") }) .collect::>>()?; + result.probes.push(super::library::verify_shared( + build, + evidence, + Path::new(paths[0]), + )?); let binary = build.join("src/stela/stela_nv_air_threadgroup_probe"); let artifacts = evidence.join("nv-threadgroup-artifacts"); fs::create_dir(&artifacts)?; diff --git a/xtask/src/gpu/nvidia.rs b/xtask/src/gpu/nvidia.rs index 680db5570e..c7b89dbfad 100644 --- a/xtask/src/gpu/nvidia.rs +++ b/xtask/src/gpu/nvidia.rs @@ -20,6 +20,12 @@ use xz2::{ }; mod archive; +mod layout; +mod lut; +mod memory; +mod ordering; +mod page_geometry; +mod primitives; #[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)] pub enum Target { @@ -160,6 +166,14 @@ pub fn build(jobs: u16, target: Target) -> Result<()> { ); } let evidence = evidence_directory()?; + if target == Target::Stela { + layout::verify(&toolchain.clang, &source, &evidence.join("record-layout"))?; + lut::verify(&toolchain.clang, &source, &evidence.join("lut-layout"))?; + memory::verify(&toolchain.clang, &source, &evidence.join("nvkms-memory"))?; + primitives::verify(&toolchain.clang, &source, &evidence.join("cpu-primitives"))?; + page_geometry::verify(&toolchain.clang, &source, &evidence.join("page-geometry"))?; + ordering::verify(&toolchain.clang, &source, &evidence.join("ordering"))?; + } for (component, subdirectory, reference_artifact) in [ ("core", "src/nvidia", "nv-kernel.o"), ("modeset", "src/nvidia-modeset", "nv-modeset-kernel.o"), diff --git a/xtask/src/gpu/nvidia/layout.rs b/xtask/src/gpu/nvidia/layout.rs new file mode 100644 index 0000000000..b957f305a4 --- /dev/null +++ b/xtask/src/gpu/nvidia/layout.rs @@ -0,0 +1,158 @@ +//! Compare actual compiled vendor records across the core and OS-hook ABIs. +use super::{capture, tools}; +use anyhow::{Context, Result, ensure}; +use object::{Architecture, Object, ObjectSection, ObjectSymbol}; +use serde_json::json; +use std::{fs, path::Path, process::Command}; + +pub(super) fn constants(object: &object::File<'_>, name: &str, count: usize) -> Result> { + let symbol = object + .symbols() + .find(|s| { + s.name() + .is_ok_and(|n| n == name || n.strip_prefix('_') == Some(name)) + }) + .with_context(|| format!("missing compiled layout symbol {name}"))?; + let section = + object.section_by_index(symbol.section_index().context("layout has no section")?)?; + let bytes = section + .data_range( + symbol.address(), + u64::try_from(count.checked_mul(8).context("layout size overflow")?)?, + )? + .context("truncated compiled layout array")?; + Ok(bytes + .as_chunks::<8>() + .0 + .iter() + .map(|bytes| u64::from_le_bytes(*bytes)) + .collect()) +} + +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let fixture = source.join("stela/tests/record_layout.c"); + let text = fs::read_to_string(&fixture)?; + let labels: Vec<_> = text + .lines() + .filter_map(|line| { + line.trim() + .strip_prefix("M(\"") + .and_then(|rest| rest.split_once('"')) + .map(|(label, _)| label) + }) + .collect(); + ensure!(!labels.is_empty(), "empty NVIDIA record fixture"); + let makefile = fs::read_to_string(source.join("src/nvidia/Makefile"))?; + let core_defines: Vec<_> = makefile + .lines() + .filter_map(|line| line.strip_prefix("CFLAGS += -DPORT_")) + .map(|suffix| format!("-DPORT_{suffix}")) + .collect(); + ensure!( + !core_defines.is_empty() + && core_defines + .iter() + .all(|s| !s.chars().any(char::is_whitespace)), + "unrecognized core NvPort definitions" + ); + let mut baseline = None; + let mut profiles = Vec::new(); + for (profile, target, kernel_interface) in [ + ("core-ms", "x86_64-unknown-windows", false), + ("shim-ms", "x86_64-unknown-windows", true), + ("shim-uefi-gnu", "x86_64-unknown-windows-gnu", true), + ("shim-host-darwin", "x86_64-apple-macosx", true), + ] { + let artifact = output.join(format!("{profile}.o")); + let mut command = Command::new(clang); + command.args([ + "-target", + target, + "-DNV_STELA", + "-DNVRM", + "-ffreestanding", + "-fno-stack-protector", + "-mno-red-zone", + "-mgeneral-regs-only", + "-std=gnu11", + "-Werror", + // Original nv.h deliberately forward-declares this opaque enum. + "-Wno-microsoft-enum-forward-reference", + ]); + if kernel_interface { + command.arg("-DNV_KERNEL_INTERFACE_LAYER"); + } else { + command.args(&core_defines); + } + for include in [ + "stela", + "src/common/sdk/nvidia/inc", + "src/nvidia/arch/nvalloc/unix/include", + "src/nvidia/arch/nvalloc/common/inc", + "src/nvidia/inc/kernel", + "src/nvidia/inc/libraries", + "src/common/inc", + "src/common/uproc/os/common/include", + ] { + command.arg("-I").arg(source.join(include)); + } + command.arg("-c").arg(&fixture).arg("-o").arg(&artifact); + capture(&mut command)?; + let bytes = fs::read(&artifact)?; + let object = object::File::parse(bytes.as_slice())?; + ensure!( + object.architecture() == Architecture::X86_64 && object.is_little_endian(), + "wrong layout target" + ); + let count = constants(&object, "stela_nvidia_record_layout_count", 1)?[0]; + ensure!(count == labels.len() as u64, "layout label/count mismatch"); + let values = constants(&object, "stela_nvidia_record_layout_values", labels.len())?; + if let Some(base) = &baseline { + for ((label, expected), actual) in labels.iter().zip(base).zip(&values) { + ensure!( + expected == actual, + "{profile}: {label}: core={expected}, actual={actual}" + ); + } + } else { + baseline = Some(values.clone()); + } + let platform_long = constants(&object, "stela_nvidia_platform_long", 2)?; + let expected_long = if profile == "shim-host-darwin" { + [8, 8] + } else { + [4, 4] + }; + ensure!( + platform_long == expected_long, + "unexpected ordinary long ABI for {profile}" + ); + profiles.push( + json!({"profile":profile,"target":target,"command":format!("{command:?}"), + "artifact":tools::binding(&artifact)?,"values":values,"platform_long":platform_long}), + ); + } + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "schema":1,"scope":"Exact compiled record compatibility; no execution or full driver link", + "fixture":tools::binding(&fixture)?,"makefile":tools::binding(&source.join("src/nvidia/Makefile"))?, + "task":tools::binding(&tools::root().join(file!()))?, + "labels":labels,"core_defines":core_defines,"profiles":profiles + }))?, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn actual_core_and_os_hook_records_match_on_all_build_abis() { + let compiler = tools::which("clang").unwrap(); + let source = tools::root().join("crates/stela-drivers/src/gpu/nvidia"); + let directory = tempfile::tempdir().unwrap(); + verify(&compiler, &source, directory.path()).unwrap(); + } +} diff --git a/xtask/src/gpu/nvidia/lut.rs b/xtask/src/gpu/nvidia/lut.rs new file mode 100644 index 0000000000..34f1c7195e --- /dev/null +++ b/xtask/src/gpu/nvidia/lut.rs @@ -0,0 +1,238 @@ +//! Actual NVKMS types and original CPU upload over the maintained common heap. +use super::{capture, layout, tools}; +use anyhow::{Context, Result, ensure}; +use object::{Architecture, Object}; +use serde_json::json; +use std::{fs, path::Path, process::Command}; + +pub(super) struct Flags { + pub(super) common: Vec, + pub(super) c: Vec, + cxx: Vec, +} + +pub(super) fn flags(clang: &Path, source: &Path, output: &Path) -> Result { + let makefile = output.join("flags.mk"); + // Let the retained Makefile and its ordinary shell expand each argument. + // No second flag parser or copied vendor build configuration is needed. + fs::write( + &makefile, + ".PHONY: stela-lut-flags\nstela-lut-flags:\n\t@printf '%s\\n' STELA_COMMON $(CFLAGS) STELA_C $(CC_ONLY_CFLAGS) STELA_CXX $(CXX_ONLY_CFLAGS)\n", + )?; + let mut make = Command::new(tools::which("make").context("install make")?); + make.current_dir(source.join("src/nvidia-modeset")) + .args(["-s", "-f", "Makefile", "-f"]) + .arg(makefile) + .args(["stela-lut-flags", "TARGET_OS=Stela", "TARGET_ARCH=x86_64"]) + .arg(format!("CC={}", clang.display())) + .arg(format!("OUTPUTDIR={}", output.join("flags").display())) + .arg(format!( + "OUTPUTDIR_ABSOLUTE={}", + output.join("flags").display() + )); + for name in ["CFLAGS", "CXXFLAGS", "CPPFLAGS", "LDFLAGS", "MAKEFLAGS"] { + make.env_remove(name); + } + let text = capture(&mut make)?; + let mut sections: [Vec; 3] = Default::default(); + let mut section = None; + for line in text.lines() { + match line { + "STELA_COMMON" => section = Some(0), + "STELA_C" => section = Some(1), + "STELA_CXX" => section = Some(2), + _ => sections[section.context("unexpected Make flag output")?].push(line.to_owned()), + } + } + let [mut common, c, cxx] = sections; + ensure!( + section == Some(2) && !common.is_empty() && !c.is_empty() && !cxx.is_empty(), + "incomplete NVKMS flags" + ); + // Only the probe's object format changes. Full production builds retain + // their original machine-model and external return-thunk options. + common.retain(|flag| { + !flag.starts_with("--target=") && flag != "-mno-incremental-linker-compatible" + }); + Ok(Flags { common, c, cxx }) +} + +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let flags = flags(clang, source, output)?; + let fixture = source.join("stela/tests/lut_layout.c"); + let mut profiles = Vec::new(); + for (profile, target, linux) in [ + ("core-ms", "x86_64-unknown-windows", false), + ("uefi-gnu", "x86_64-unknown-windows-gnu", false), + ("host-darwin", "x86_64-apple-macosx", false), + ("linux", "x86_64-unknown-linux-gnu", true), + ] { + for (language, suffix) in [("c", &flags.c), ("c++", &flags.cxx)] { + let artifact = output.join(format!("{profile}-{language}.o")); + let mut command = Command::new(clang); + command.current_dir(source.join("src/nvidia-modeset")); + for flag in &flags.common { + command.arg(if linux && flag == "-DNV_STELA" { + "-DNV_LINUX" + } else { + flag + }); + } + command + .args(suffix) + .arg(format!("--target={target}")) + .args(["-x", language, "-c"]) + .arg(&fixture) + .arg("-o") + .arg(&artifact); + capture(&mut command)?; + let bytes = fs::read(&artifact)?; + let object = object::File::parse(bytes.as_slice())?; + ensure!( + object.architecture() == Architecture::X86_64 && object.is_little_endian(), + "wrong LUT object ABI" + ); + let count = layout::constants(&object, "stela_nvkms_lut_layout_count", 1)?; + ensure!(count == [10], "changed LUT fixture inventory"); + let values = layout::constants(&object, "stela_nvkms_lut_layout", 10)?; + ensure!( + values == [8, 2, 16896, 2, 0, 8448, 8232, 8232, 8448, 8448], + "changed LUT byte layout or CPU alignment" + ); + profiles.push(json!({"profile":profile,"target":target,"language":language, + "command":format!("{command:?}"),"artifact":tools::binding(&artifact)?,"values":values})); + } + } + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + let cpu = Some(cpu_model( + clang, + source, + output, + &flags, + &[ + ("stela/tests/lut_access.c", &[]), + ("src/nvidia-modeset/src/nvkms-lut.c", &[]), + ("stela/stela_nvkms_primitives.c", &[]), + ], + )?); + #[cfg(not(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux"))))] + let cpu: Option = None; + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "scope":"Actual C/C++ object layouts and separate hosted common-heap/original-upload fixture; no production context qualification or GPU execution", + "task":tools::binding(&tools::root().join(file!()))?,"fixture":tools::binding(&fixture)?, + "header":tools::binding(&source.join("src/nvidia-modeset/include/nvkms-types.h"))?, + "makefile":tools::binding(&source.join("src/nvidia-modeset/Makefile"))?, + "common_flags":flags.common,"c_flags":flags.c,"cxx_flags":flags.cxx, + "profiles":profiles,"hosted_CPU_access":cpu, + }))?, + )?; + Ok(()) +} + +#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] +pub(super) fn cpu_model( + clang: &Path, + source: &Path, + output: &Path, + flags: &Flags, + sources: &[(&str, &[&str])], +) -> Result { + // This executable models ordinary host OS-hook calls. These full-core + // options belong to the separately built kernel archives, not this process. + let excluded = [ + "-mfunction-return=thunk-extern", + "-mcmodel=kernel", + "-fno-pic", + "-msoft-float", + "-mno-mmx", + "-mno-sse", + "-mno-sse2", + "-mno-3dnow", + ]; + let mut objects = Vec::new(); + let mut commands = Vec::new(); + for (index, (file, extra)) in sources.iter().enumerate() { + let artifact = output.join(format!("cpu-{index}.o")); + let mut command = Command::new(clang); + command + .current_dir(source.join("src/nvidia-modeset")) + .args( + flags + .common + .iter() + .filter(|f| !excluded.contains(&f.as_str())), + ) + .args(&flags.c) + .args([ + "-mgeneral-regs-only", + "-ffunction-sections", + "-fdata-sections", + "-fno-inline", + "-I", + ]) + .arg(source.join("stela")) + .args(*extra) + .arg("-c") + .arg(source.join(file)) + .arg("-o") + .arg(&artifact); + capture(&mut command)?; + commands.push(format!("{command:?}")); + objects.push(artifact); + } + let heap = output.join("libactual-heap.a"); + let mut rust = Command::new(tools::which("rustc").context("install rustc")?); + rust.args([ + "--edition=2024", + "--crate-name=stela_nvkms_lut_heap", + "--crate-type=staticlib", + "-C", + "panic=abort", + "-C", + "opt-level=2", + ]) + .arg(source.join("stela/tests/lut_heap.rs")) + .arg("-o") + .arg(&heap); + capture(&mut rust)?; + commands.push(format!("{rust:?}")); + let binary = output.join("cpu-model"); + let mut link = Command::new(clang); + link.args(&objects) + .arg(&heap) + .arg(if cfg!(target_os = "macos") { + "-Wl,-dead_strip" + } else { + "-Wl,--gc-sections" + }) + .arg("-o") + .arg(&binary); + capture(&mut link)?; + commands.push(format!("{link:?}")); + capture(&mut Command::new(&binary))?; + Ok( + json!({"binary":tools::binding(&binary)?,"heap":tools::binding(&heap)?, + "shared_heap_source":tools::binding(&tools::root().join("crates/stela-boot/src/heap.rs"))?, + "metadata_adapter":tools::binding(&source.join("memory.rs"))?, + "fixture_sources":sources.iter().map(|(file,_)| tools::binding(&source.join(file))).collect::>>()?, + "excluded_only_for_host_CPU_fixture":excluded,"commands":commands,"executed":true}), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn original_lut_upload_uses_actual_header_prefix_and_common_heap() { + let output = tempfile::tempdir().unwrap(); + verify( + &tools::which("clang").unwrap(), + &tools::root().join("crates/stela-drivers/src/gpu/nvidia"), + output.path(), + ) + .unwrap(); + } +} diff --git a/xtask/src/gpu/nvidia/memory.rs b/xtask/src/gpu/nvidia/memory.rs new file mode 100644 index 0000000000..149dce82f9 --- /dev/null +++ b/xtask/src/gpu/nvidia/memory.rs @@ -0,0 +1,86 @@ +//! Exercise the actual C adapter's allocator-refusal ABI in a separate process. +#[cfg(test)] +use super::capture; +use super::{lut, tools}; +use anyhow::Result; +use serde_json::json; +#[cfg(test)] +use std::process::Command; +use std::{fs, path::Path}; + +#[cfg(test)] +#[test] +fn nvlink_preserves_full_lengths_and_refuses_common_heap_failures() { + let output = tempfile::tempdir().unwrap(); + let source = tools::root().join("crates/stela-drivers/src/gpu/nvidia"); + let binary = output.path().join("nvlink-memory"); + let mut compiler = Command::new(tools::which("clang").unwrap()); + compiler.args(["-std=gnu11", "-DNV_STELA", "-Wall", "-Wextra", "-Werror"]); + for include in [ + "stela", + "src/common/nvlink/interface", + "src/common/sdk/nvidia/inc", + "src/common/inc", + ] { + compiler.arg("-I").arg(source.join(include)); + } + compiler + .arg(source.join("stela/stela_nvlink_memory.c")) + .arg(source.join("stela/tests/nvlink_memory.c")) + .arg("-o") + .arg(&binary); + capture(&mut compiler).unwrap(); + capture(&mut Command::new(binary)).unwrap(); +} + +/// Replay the original realloc and real common-heap failure boundary separately +/// from the test runner's allocator. No fixture provider enters native archives. +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let flags = lut::flags(clang, source, output)?; + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + let cpu = Some(lut::cpu_model( + clang, + source, + output, + &flags, + &[ + ("stela/tests/nvkms_memory.c", &[]), + ( + "stela/stela_nvkms_memory.c", + &[ + "-Dstela_nvidia_alloc=stela_nvkms_model_alloc", + "-Dstela_nvidia_free=stela_nvkms_model_free", + "-Dnvkms_memset=stela_nvkms_model_zero", + ], + ), + ("stela/stela_nvkms_primitives.c", &[]), + ], + )?); + #[cfg(not(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux"))))] + let cpu: Option = None; + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "scope":"Actual metadata backend, original sized-prefix/realloc and common heap in a separate CPU process; no production context, final driver link or GPU execution", + "task":tools::binding(&tools::root().join(file!()))?, + "original_utils":tools::binding(&source.join("src/nvidia-modeset/src/nvkms-utils.c"))?, + "makefile":tools::binding(&source.join("src/nvidia-modeset/Makefile"))?, + "common_flags":flags.common,"c_flags":flags.c, + "hosted_CPU_access":cpu, + }))?, + )?; + Ok(()) +} + +#[cfg(test)] +#[test] +fn nvkms_original_realloc_preserves_ownership_on_heap_denial() { + let output = tempfile::tempdir().unwrap(); + verify( + &tools::which("clang").unwrap(), + &tools::root().join("crates/stela-drivers/src/gpu/nvidia"), + output.path(), + ) + .unwrap(); +} diff --git a/xtask/src/gpu/nvidia/ordering.rs b/xtask/src/gpu/nvidia/ordering.rs new file mode 100644 index 0000000000..e6f6d9e14e --- /dev/null +++ b/xtask/src/gpu/nvidia/ordering.rs @@ -0,0 +1,129 @@ +//! Inspect the actual original ordering hook; this never executes a fence. +use super::{capture, tools}; +use anyhow::{Context, Result, ensure}; +use object::{Architecture, Object, ObjectSection, ObjectSymbol}; +use serde_json::json; +use std::{fs, path::Path, process::Command}; + +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let objdump = tools::which("llvm-objdump") + .or_else(crate::dit::toolchain_objdump) + .context("original ordering inspection requires llvm-objdump")?; + let fixture = source.join("stela/tests/ordering.c"); + let mut profiles = Vec::new(); + for target in [ + "x86_64-unknown-windows", + "x86_64-unknown-windows-gnu", + "x86_64-apple-macosx", + ] { + let artifact = output.join(format!("{target}.o")); + let mut command = Command::new(clang); + command.args([ + "-target", + target, + "-DNV_STELA", + "-DNV_KERNEL_INTERFACE_LAYER", + "-ffreestanding", + "-fno-stack-protector", + "-fomit-frame-pointer", + "-mno-red-zone", + "-mgeneral-regs-only", + "-std=gnu11", + "-O2", + "-Werror", + ]); + for include in [ + "stela", + "src/common/sdk/nvidia/inc", + "src/nvidia/arch/nvalloc/unix/include", + "src/common/inc", + "src/nvidia/inc/kernel", + "src/common/unix/common/inc", + ] { + command.arg("-I").arg(source.join(include)); + } + let ir = output.join(format!("{target}.ll")); + let mut ir_command = Command::new(clang); + ir_command + .args(command.get_args()) + .arg(&fixture) + .args(["-S", "-emit-llvm", "-o"]) + .arg(&ir); + command.arg(&fixture).arg("-c").arg("-o").arg(&artifact); + capture(&mut command)?; + let bytes = fs::read(&artifact)?; + let object = object::File::parse(bytes.as_slice())?; + ensure!( + object.architecture() == Architecture::X86_64, + "wrong ordering ABI" + ); + ensure!( + !object + .symbols() + .any(|s| s.is_undefined() && s.name().is_ok_and(|n| !n.is_empty())), + "ordering hook has unresolved imports" + ); + let hook = object + .symbols() + .find(|s| { + s.name() + .is_ok_and(|n| n.trim_start_matches('_') == "os_flush_cpu_write_combine_buffer") + }) + .context("missing actual ordering hook")?; + let text = + object.section_by_index(hook.section_index().context("ordering hook section")?)?; + ensure!( + text.data_range(hook.address(), 4)? == Some(&[0x0f, 0xae, 0xf8, 0xc3]), + "ordering hook is not exactly SFENCE and return" + ); + let disassembly = capture(Command::new(&objdump).arg("-d").arg(&artifact))?; + ensure!( + disassembly + .lines() + .filter(|l| l.contains("\tsfence")) + .count() + == 2, + "hook/probe must each contain one SFENCE" + ); + ensure!( + !disassembly + .split_whitespace() + .any(|t| ["%xmm", "%ymm", "%zmm"].iter().any(|r| t.starts_with(r))), + "ordering hook/probe uses SIMD registers" + ); + let dump = output.join(format!("{target}.disassembly")); + fs::write(&dump, disassembly)?; + capture(&mut ir_command)?; + let text = fs::read_to_string(&ir)?; + ensure!( + text.lines() + .filter(|l| l.contains("asm sideeffect \"sfence\"") && l.contains("~{memory}")) + .count() + == 2, + "original volatile SFENCE memory clobber was lost" + ); + profiles.push(json!({"target":target,"command":format!("{command:?}"),"ir_command":format!("{ir_command:?}"), + "object":tools::binding(&artifact)?,"disassembly":tools::binding(&dump)?,"ir":tools::binding(&ir)?})); + } + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "scope":"Three ABI compile/IR/actual emitted-binary inspection only; no hardware or fence execution", + "adapter":tools::binding(&source.join("stela/stela_ordering.c"))?, + "fixture":tools::binding(&fixture)?,"objdump":tools::binding(&objdump)?,"profiles":profiles, + }))?, + )?; + Ok(()) +} + +#[test] +fn original_ordering_hook_keeps_sfence_and_memory_clobber_across_native_abis() { + let output = tempfile::tempdir().unwrap(); + verify( + &tools::which("clang").unwrap(), + &tools::root().join("crates/stela-drivers/src/gpu/nvidia"), + output.path(), + ) + .unwrap(); +} diff --git a/xtask/src/gpu/nvidia/page_geometry.rs b/xtask/src/gpu/nvidia/page_geometry.rs new file mode 100644 index 0000000000..b1026d2798 --- /dev/null +++ b/xtask/src/gpu/nvidia/page_geometry.rs @@ -0,0 +1,119 @@ +//! Original RM page accessors over the actual one-time native publisher. +use super::{capture, tools}; +use anyhow::{Context, Result, ensure}; +use serde_json::json; +use std::{fs, path::Path, process::Command}; + +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let original = source.join("src/nvidia/arch/nvalloc/unix/src/os.c"); + let text = fs::read_to_string(&original)?; + let declarations = source.join("src/nvidia/generated/g_os_nvoc.h"); + let declarations_text = fs::read_to_string(&declarations)?; + let mut accessors = text + .split_once("#include") + .context("missing original OS source notices")? + .0 + .to_owned(); + for (result, name) in [ + ("NvU64", "osGetPageSize"), + ("NvU64", "osGetSupportedSysmemPageSizeMask"), + ("NvU8", "osGetPageShift"), + ] { + let signature = format!("{name}(void);"); + let prototypes: Vec<_> = declarations_text + .lines() + .filter(|line| line.split_whitespace().eq([result, signature.as_str()])) + .collect(); + ensure!(prototypes.len() == 1, "changed original {name} declaration"); + accessors.push_str(prototypes[0]); + accessors.push('\n'); + let marker = format!("{result}\n{name}(void)\n{{\n"); + ensure!( + text.matches(&marker).count() == 1, + "changed original {name}" + ); + let start = text.find(&marker).unwrap(); + let end = text[start..] + .find("\n}\n") + .context("missing original accessor body")?; + accessors.push_str(&text[start..start + end + 3]); + accessors.push('\n'); + } + let header = output.join("page_geometry_accessors.h"); + fs::write(&header, accessors)?; + let adapter = source.join("stela/stela_page_geometry.c"); + let fixture = source.join("stela/tests/page_geometry.c"); + let mut processes = Vec::new(); + for sanitized in [false, true] { + let binary = output.join(if sanitized { "sanitized" } else { "normal" }); + let mut compiler = Command::new(clang); + compiler.args([ + "-DNV_STELA", + "-std=c11", + "-ffreestanding", + "-fno-builtin", + "-Wall", + "-Wextra", + "-Werror", + "-Wmissing-prototypes", + "-O2", + ]); + for include in [ + "stela", + "src/common/sdk/nvidia/inc", + "src/nvidia/arch/nvalloc/unix/include", + "src/nvidia/inc/kernel", + "src/common/inc", + "src/common/unix/common/inc", + ] { + compiler.arg("-I").arg(source.join(include)); + } + if sanitized { + compiler.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]); + } + compiler + .arg("-I") + .arg(output) + .arg(&adapter) + .arg(&fixture) + .arg("-o") + .arg(&binary); + capture(&mut compiler)?; + for (base, max) in [(12, 12), (14, 14), (12, 14), (12, 21), (62, 62)] { + let mut command = Command::new(&binary); + command.args([base.to_string(), max.to_string()]); + let log = output.join(format!("{sanitized}-{base}-{max}.log")); + fs::write(&log, capture(&mut command)?)?; + processes.push(json!({ + "sanitized":sanitized,"base_shift":base,"max_shift":max, + "compiler":format!("{compiler:?}"),"command":format!("{command:?}"), + "binary":tools::binding(&binary)?,"output":tools::binding(&log)?, + })); + } + } + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "scope":"Ten hosted original accessor/publisher processes; broad granules refused before publication; no physical RAM support or RM activation", + "task":tools::binding(&tools::root().join(file!()))?, + "original":tools::binding(&original)?,"accessors":tools::binding(&header)?, + "original_declarations":tools::binding(&declarations)?, + "adapter":tools::binding(&adapter)?,"fixture":tools::binding(&fixture)?, + "processes":processes, + }))?, + )?; + Ok(()) +} + +#[cfg(test)] +#[test] +fn original_page_accessors_publish_only_supported_native_geometry() { + let output = tempfile::tempdir().unwrap(); + verify( + &tools::which("clang").unwrap(), + &tools::root().join("crates/stela-drivers/src/gpu/nvidia"), + output.path(), + ) + .unwrap(); +} diff --git a/xtask/src/gpu/nvidia/primitives.rs b/xtask/src/gpu/nvidia/primitives.rs new file mode 100644 index 0000000000..32626e61ef --- /dev/null +++ b/xtask/src/gpu/nvidia/primitives.rs @@ -0,0 +1,104 @@ +//! Original CPU wrappers and separate full-width observation providers. +use super::{capture, tools}; +use anyhow::Result; +use serde_json::json; +use std::{fs, path::Path, process::Command}; + +pub(super) fn verify(clang: &Path, source: &Path, output: &Path) -> Result<()> { + fs::create_dir_all(output)?; + let adapter = source.join("stela/stela_nvswitch_primitives.c"); + let fixture = source.join("stela/tests/nvswitch_primitives.c"); + let mut models = Vec::new(); + for sanitize in [false, true] { + for forward in [false, true] { + let name = format!( + "{}-{}", + if sanitize { "sanitized" } else { "normal" }, + if forward { "forward" } else { "bytes" } + ); + let mut objects = Vec::new(); + let mut commands = Vec::new(); + for (index, input) in [&adapter, &fixture].iter().enumerate() { + let artifact = output.join(format!("{name}-{index}.o")); + let mut command = Command::new(clang); + command.args([ + "-DNV_STELA", + "-ffreestanding", + "-fno-builtin", + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-Wmissing-prototypes", + "-O2", + ]); + for include in [ + "stela", + "src/common/sdk/nvidia/inc", + "src/nvidia/arch/nvalloc/unix/include", + "src/nvidia/inc/kernel", + "src/common/inc", + "src/common/nvlink/interface", + "src/common/unix/common/inc", + ] { + command.arg("-I").arg(source.join(include)); + } + if sanitize { + command.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]); + } + if forward { + if index == 0 { + // Only the adapter object observes providers; these + // symbols never enter any production archive. + command.args([ + "-Dmemcpy=stela_nvswitch_test_memcpy", + "-Dmemset=stela_nvswitch_test_memset", + "-Dstrlen=stela_nvswitch_test_strlen", + ]); + } else { + command.arg("-DSTELA_NVSWITCH_FORWARD_TEST"); + } + } + command.arg("-c").arg(input).arg("-o").arg(&artifact); + capture(&mut command)?; + commands.push(format!("{command:?}")); + objects.push(artifact); + } + let binary = output.join(&name); + let mut link = Command::new(clang); + link.args(&objects).arg("-o").arg(&binary); + if sanitize { + link.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]); + } + capture(&mut link)?; + commands.push(format!("{link:?}")); + let log = output.join(format!("{name}.log")); + fs::write(&log, capture(&mut Command::new(&binary))?)?; + models.push(json!({"sanitized":sanitize,"forwarding_only":forward,"commands":commands,"binary":tools::binding(&binary)?,"output":tools::binding(&log)?})); + } + } + fs::write( + output.join("receipt.json"), + serde_json::to_vec_pretty(&json!({ + "scope":"Actual original wrappers in four hosted CPU byte/forwarding processes; no native EFI/GPU execution or production observer provider", + "task":tools::binding(&tools::root().join(file!()))?,"adapter":tools::binding(&adapter)?,"fixture":tools::binding(&fixture)?, + "original_header":tools::binding(&source.join("src/common/nvswitch/interface/export_nvswitch.h"))?,"models":models, + }))?, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn original_nvswitch_wrappers_keep_bytes_and_full_native_lengths() { + let output = tempfile::tempdir().unwrap(); + verify( + &tools::which("clang").unwrap(), + &tools::root().join("crates/stela-drivers/src/gpu/nvidia"), + output.path(), + ) + .unwrap(); + } +}