diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index edd7d701e665cd..b3e5cb4c43862f 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -251,7 +251,10 @@ impl EventManager { }); for wq in owners { - wq.fail_all(error); + if wq.fail_all(error) { + // The pinned commands still point at this queue's ring; keep it until reboot. + core::mem::forget(wq); + } } } } diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 0c4c6048408262..24938d2ea7e5ac 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -70,7 +70,6 @@ struct Vm { vm: mmu::Vm, user_range: Range, kernel_range: Range, - _dummy_mapping: mmu::KernelMapping, gpu: Arc, } @@ -83,41 +82,15 @@ impl Drop for Vm { // object must not outlive the client's VM handle. status.release_mirror(); } - if self.vm.status().is_some() { - // Tracked jobs can outlive their file's VM handle. Their last guard performs - // these unmaps once no accepted work can still dereference the mappings. - if let Err(error) = self - .vm - .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) - { - pr_err!("Vm::Drop: deferred user unmap failed: {:?}\n", error); - } - self.vm.bo_deferred_cleanup(); - self.gpu.vm_closed(&self.vm); - return; - } - // When the user Vm is dropped, verify that no user mappings exists. - let left_range = self.user_range.start..self.kernel_range.start; - let right_range = self.kernel_range.end..self.user_range.end; - - if !left_range.is_empty() - && self - .vm - .unmap_range(None, left_range.start, left_range.range()) - .is_err() - { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); - } - if !right_range.is_empty() - && self - .vm - .unmap_range(None, right_range.start, right_range.range()) - .is_err() + // Accepted jobs retain mappings until firmware completion or GPU stop. + if let Err(error) = self + .vm + .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); + pr_err!("Vm::Drop: deferred user unmap failed: {:?}\n", error); } - self.vm.bo_deferred_cleanup(); + self.gpu.vm_closed(&self.vm); } } @@ -555,13 +528,15 @@ impl File { let gpu = ®_data.gpu; let file_id = file.inner().id; - let vm = gpu.new_vm_for_file(kernel_range.clone(), file_id)?; + let vm = gpu + .new_vm_for_file(kernel_range.clone(), file_id)? + .with_job_lifetime()?; // G16 registers a retained backend owner before returning this VM. Any later // allocation can fail before file::Vm exists to run its normal close path. let failed_vm = ScopeGuard::new_with_data( (vm.clone(), user_range.clone(), kernel_range.clone()), |(vm, user_range, kernel_range)| { - if gpu.tracked_submission() && vm.status().is_some() && !vm.is_closed() { + if !vm.is_closed() { vm.close_idle_reclaim(); if let Err(error) = vm.unmap_user_ranges(user_range, kernel_range) { pr_err!("VM create: closing unpublished VM failed: {:?}\n", error); @@ -631,6 +606,7 @@ impl File { mmu::PROT_GPU_SHARED_RW, true, )?; + vm.retain_mapping(dummy_mapping)?; mod_dev_dbg!(device, "[File {} VM {}]: VM created\n", file_id, id); resv.fill(KBox::new( @@ -645,7 +621,6 @@ impl File { vm, user_range, kernel_range, - _dummy_mapping: dummy_mapping, gpu: gpu.clone(), }, GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 66d507c2d76949..5b67984e62bed3 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -74,6 +74,8 @@ pub(super) struct VmLifetime { changed: CondVar, #[pin] driver: Mutex>, + #[pin] + retained: Mutex>, } impl VmLifetime { @@ -97,6 +99,7 @@ impl VmLifetime { unmaps:KVec::new(), objects:KVec::new() }, "VM job lifetime"), changed <- new_condvar!("VM mapping admission"), driver <- new_mutex!(None, "VM driver mappings"), + retained <- new_mutex!(KVec::new(), "VM retained mappings"), }), GFP_KERNEL, ) @@ -111,7 +114,9 @@ pub(crate) struct VmJobGuard { } impl VmJobGuard { - /// Blocks mapping commits before the error fence can become visible to userspace. + /// Blocks mapping commits until existing commits drain, before the error fence becomes visible. + /// May sleep; callers must run in sleepable context. This runs in the crash callback with no + /// timeout, so the mapping-commit window must never wait on the firmware. pub(crate) fn quarantine(&self) { if let Some(lifetime) = self.vm.lifetime.as_ref() { let mut state = lifetime.state.lock(); @@ -169,6 +174,11 @@ impl Vm { } Ok(()) } + /// Keeps fixed kernel aliases alive while accepted work can still reference them. + pub(crate) fn retain_mapping(&self, mapping: KernelMapping) -> Result { + let lifetime = self.lifetime.as_ref().ok_or(EINVAL)?; + Ok(lifetime.retained.lock().push(mapping, GFP_KERNEL)?) + } pub(crate) fn render_pool_tvb_blocks(&self, slot: u8, id: u64) -> Option { if id == 0 { @@ -351,6 +361,15 @@ impl Vm { .is_some_and(|lifetime| lifetime.state.lock().closed) } + /// Track accepted work on the legacy submission path. Called for every backend; a no-op where + /// tracking already exists (G15 and later attach it when they create the VM). + pub(crate) fn with_job_lifetime(mut self) -> Result { + if self.lifetime.is_none() { + self.lifetime = Some(VmLifetime::new()?); + } + Ok(self) + } + /// Tests mappings and reservations which userspace must never replace. pub(crate) fn driver_range_overlaps(&self, range: Range) -> bool { let Some(lifetime) = self.lifetime.as_ref() else { diff --git a/drivers/gpu/drm/asahi/queue/compute.rs b/drivers/gpu/drm/asahi/queue/compute.rs index c9f205708e3131..c2c348b83118f4 100644 --- a/drivers/gpu/drm/asahi/queue/compute.rs +++ b/drivers/gpu/drm/asahi/queue/compute.rs @@ -62,7 +62,7 @@ impl super::QueueInner::ver { // but it's unclear *which* slot... let slot_client_seq: u8 = (self.id & 0xff) as u8; - let vm_bind = job.vm_bind.clone(); + let vm_bind = job.vm_bind.as_ref().clone(); mod_dev_dbg!( self.dev, diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 4abdd3e485f726..c9b38c852abfba 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -89,9 +89,16 @@ struct SubQueue { #[versions(AGX)] impl SubQueue::ver { - fn new_job(&mut self, fence: dma_fence::Fence) -> SubQueueJob::ver { + fn new_job( + &mut self, + fence: dma_fence::Fence, + vm_job: Arc, + vm_bind: Arc, + ) -> SubQueueJob::ver { SubQueueJob::ver { wq: self.wq.clone(), + vm_job, + vm_bind, fence: Some(fence), job: None, } @@ -101,6 +108,8 @@ impl SubQueue::ver { #[versions(AGX)] struct SubQueueJob { wq: Arc, + vm_job: Arc, + vm_bind: Arc, job: Option, fence: Option, } @@ -110,8 +119,13 @@ impl SubQueueJob::ver { fn get(&mut self) -> Result<&mut workqueue::Job::ver> { if self.job.is_none() { mod_pr_debug!("SubQueueJob: Creating {:?} job\n", self.wq.pipe_type()); - self.job - .replace(self.wq.new_job(self.fence.take().unwrap())?); + self.job.replace( + self.wq.new_job( + self.fence.take().unwrap(), + self.vm_job.clone(), + self.vm_bind.clone(), + )?, + ); } Ok(self.job.as_mut().expect("expected a Job")) } @@ -201,7 +215,9 @@ impl dma_fence::FenceOps for JobFence::ver { #[versions(AGX)] pub(crate) struct QueueJob { dev: AsahiDevRef, - vm_bind: mmu::VmBind, + vm_bind: Arc, + // Retain the VM when no sub-queue job exists; otherwise child jobs hold clones. + _vm_job: Arc, op_guard: Option, sj_vtx: Option, sj_frag: Option, @@ -715,7 +731,8 @@ impl Queue for Queue::ver { GFP_KERNEL, )?; - let vm_bind = gpu.bind_vm(&self.vm)?; + let vm_job = Arc::new(self.vm.retain_first_job()?, GFP_KERNEL)?; + let vm_bind = Arc::new(gpu.bind_vm(&self.vm)?, GFP_KERNEL)?; let vm_slot = vm_bind.slot(); mod_dev_dbg!(self.dev, "[Submission {}] Creating job\n", id); @@ -790,20 +807,21 @@ impl Queue for Queue::ver { 1, QueueJob::ver { dev: self.dev.clone(), - vm_bind, + vm_bind: vm_bind.clone(), + _vm_job: vm_job.clone(), op_guard, sj_vtx: self .q_vtx .as_mut() - .map(|a| a.new_job(Fence::from_fence(&fence))), + .map(|a| a.new_job(Fence::from_fence(&fence), vm_job.clone(), vm_bind.clone())), sj_frag: self .q_frag .as_mut() - .map(|a| a.new_job(Fence::from_fence(&fence))), + .map(|a| a.new_job(Fence::from_fence(&fence), vm_job.clone(), vm_bind.clone())), sj_comp: self .q_comp .as_mut() - .map(|a| a.new_job(Fence::from_fence(&fence))), + .map(|a| a.new_job(Fence::from_fence(&fence), vm_job.clone(), vm_bind.clone())), fence, notifier: self.inner.notifier.clone(), diff --git a/drivers/gpu/drm/asahi/queue/render.rs b/drivers/gpu/drm/asahi/queue/render.rs index 68c4856ca4200c..f87ec4a3452d44 100644 --- a/drivers/gpu/drm/asahi/queue/render.rs +++ b/drivers/gpu/drm/asahi/queue/render.rs @@ -294,7 +294,7 @@ impl super::QueueInner::ver { let scene = Arc::new(buffer.new_scene(kalloc, &tile_info)?, GFP_KERNEL)?; - let vm_bind = job.vm_bind.clone(); + let vm_bind = job.vm_bind.as_ref().clone(); mod_dev_dbg!( self.dev, diff --git a/drivers/gpu/drm/asahi/workqueue.rs b/drivers/gpu/drm/asahi/workqueue.rs index 315396ef716ce1..8989485143324d 100644 --- a/drivers/gpu/drm/asahi/workqueue.rs +++ b/drivers/gpu/drm/asahi/workqueue.rs @@ -29,6 +29,7 @@ use crate::{ event, fw, gpu, + mmu, regs, // }; use core::any::Any; @@ -156,6 +157,8 @@ where vm_slot: u32, callback: Option, fence: dma_fence::Fence, + _vm_job: Arc, + _vm_bind: Arc, } pub(crate) trait GenSubmittedWork: Send + Sync { @@ -163,6 +166,7 @@ pub(crate) trait GenSubmittedWork: Send + Sync { fn value(&self) -> event::EventValue; fn wptr(&self) -> u32; fn set_wptr(&mut self, wptr: u32); + fn quarantine_vm(&self); fn mark_error(&mut self, error: WorkError); fn complete(&mut self); fn get_fence(&self) -> dma_fence::Fence; @@ -213,6 +217,10 @@ impl) + Send + Sync> GenSubm self.wptr = wptr; } + fn quarantine_vm(&self) { + self._vm_job.quarantine(); + } + fn complete(&mut self) { if let Some(cb) = self.callback.take() { cb(self.error); @@ -296,6 +304,8 @@ pub(crate) struct Job { submitted: bool, event_count: usize, fence: dma_fence::Fence, + vm_job: Arc, + vm_bind: Arc, } #[versions(AGX)] @@ -342,7 +352,8 @@ impl Job::ver { let fence = self.fence.clone(); let value = self.event_info.value.next(); - + let vm_job = self.vm_job.clone(); + let vm_bind = self.vm_bind.clone(); self.pending.push( KBox::try_pin_init( try_pin_init!(SubmittedWorkContainer { @@ -355,6 +366,8 @@ impl Job::ver { wptr: 0, vm_slot, fence, + _vm_job: vm_job, + _vm_bind: vm_bind, }, GFP_KERNEL)? }), GFP_KERNEL, @@ -596,6 +609,7 @@ impl<'a> Drop for JobSubmission::ver<'a> { mod_pr_debug!("WorkQueue({:?}): Dropping JobSubmission\n", inner.pipe_type); let new_len = inner.pending.len() - self.command_count; + // Job retains its guard until this submission drops the queue lock. inner.pending.truncate(new_len); let pipe_type = inner.pipe_type; @@ -780,7 +794,12 @@ impl WorkQueue::ver { }) } - pub(crate) fn new_job(self: &Arc, fence: dma_fence::Fence) -> Result { + pub(crate) fn new_job( + self: &Arc, + fence: dma_fence::Fence, + vm_job: Arc, + vm_bind: Arc, + ) -> Result { let mut inner = self.inner.lock(); if inner.event.is_none() { @@ -826,6 +845,8 @@ impl WorkQueue::ver { committed: false, submitted: false, fence, + vm_job, + vm_bind, }) } @@ -863,7 +884,9 @@ pub(crate) trait WorkQueue { fn signal(&self) -> bool; fn mark_error(&self, value: event::EventValue, error: WorkError); - fn fail_all(&self, error: WorkError); + /// Fails all pending commands. Returns true when commands were left pinned: the caller + /// must then keep its reference to this queue, whose ring they still point at. + fn fail_all(&self, error: WorkError) -> bool; } #[versions(AGX)] @@ -1001,7 +1024,7 @@ impl WorkQueue for WorkQueue::ver { } /// Mark all of this queue's work as having failed, and complete it. - fn fail_all(&self, error: WorkError) { + fn fail_all(&self, error: WorkError) -> bool { // If anything is marked completed, we can consider it successful // at this point, even if we didn't get the signal event yet. self.signal(); @@ -1014,7 +1037,7 @@ impl WorkQueue for WorkQueue::ver { if inner.pending_jobs > 0 || !inner.pending.is_empty() { pr_crit!("WorkQueue: fail_all() called with no event and pending jobs.\n"); } - return; + return false; } mod_pr_debug!( @@ -1033,9 +1056,14 @@ impl WorkQueue for WorkQueue::ver { core::mem::drop(inner); + let pinned = !cmds.is_empty(); for mut cmd in cmds { + cmd.as_mut().inner_mut().quarantine_vm(); cmd.as_mut().inner_mut().mark_error(error); cmd.as_mut().inner_mut().complete(); + // No confirmed GPU stop exists after a firmware crash; retain command resources until reboot. + core::mem::forget(cmd); } + pinned } } diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile index 84011ba695884d..a81397902f82e0 100644 --- a/tools/testing/selftests/Makefile +++ b/tools/testing/selftests/Makefile @@ -21,6 +21,7 @@ TARGETS += drivers/apple TARGETS += drivers/dma-buf TARGETS += drivers/gpu/apple-afkv2 TARGETS += drivers/gpu/apple-dcp +TARGETS += drivers/gpu/asahi-sigkill TARGETS += drivers/ntsync TARGETS += drivers/s390x/uvdevice TARGETS += drivers/net diff --git a/tools/testing/selftests/drivers/gpu/asahi-sigkill/Makefile b/tools/testing/selftests/drivers/gpu/asahi-sigkill/Makefile new file mode 100644 index 00000000000000..23d199cde15e64 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-sigkill/Makefile @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +TEST_PROGS := run.sh +TEST_FILES := comp.comp vkrepro.c +include ../../../lib.mk diff --git a/tools/testing/selftests/drivers/gpu/asahi-sigkill/comp.comp b/tools/testing/selftests/drivers/gpu/asahi-sigkill/comp.comp new file mode 100644 index 00000000000000..d78c02ee26ce70 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-sigkill/comp.comp @@ -0,0 +1,10 @@ +#version 450 +layout(local_size_x = 256) in; +layout(std430, binding = 0) buffer B { float d[]; }; +void main() { + uint i = gl_GlobalInvocationID.x; + float x = d[i]; + for (int k = 0; k < 3000; k++) + x = fma(x, 1.0001, 0.5); + d[i] = x; +} diff --git a/tools/testing/selftests/drivers/gpu/asahi-sigkill/run.sh b/tools/testing/selftests/drivers/gpu/asahi-sigkill/run.sh new file mode 100755 index 00000000000000..936318ccc82135 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-sigkill/run.sh @@ -0,0 +1,138 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0-only OR MIT +set -eu +# This checks compute work through file close, but does not observe GPU execution or test render or VM_BIND. + +ksft_skip=4 +if [ "${ASAHI_SIGKILL_RUN:-}" != 1 ]; then + echo "SKIP: set ASAHI_SIGKILL_RUN=1 to run destructive GPU tests" + exit "$ksft_skip" +fi + +count=${ASAHI_SIGKILL_COUNT:-20} +case "$count" in + ''|*[!0-9]*) echo "FAIL: ASAHI_SIGKILL_COUNT must be an integer" >&2; exit 1 ;; +esac +if [ "$count" -lt 20 ]; then + echo "FAIL: the regression test requires at least 20 kills" >&2 + exit 1 +fi + +command -v cc >/dev/null || { echo "FAIL: cc is required" >&2; exit 1; } +command -v journalctl >/dev/null || { echo "FAIL: journalctl is required" >&2; exit 1; } +if command -v glslangValidator >/dev/null; then + shader_compiler=glslangValidator +elif command -v glslc >/dev/null; then + shader_compiler=glslc +else + echo "FAIL: glslangValidator or glslc is required" >&2 + exit 1 +fi + +VK_DRIVER_FILES=${VK_DRIVER_FILES:-/usr/share/vulkan/icd.d/asahi_icd.json} +if [ ! -r "$VK_DRIVER_FILES" ]; then + echo "FAIL: Vulkan driver manifest is not readable: $VK_DRIVER_FILES" >&2 + exit 1 +fi +export VK_DRIVER_FILES +echo "Vulkan driver manifest: $VK_DRIVER_FILES" + +root=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +tmp=$(mktemp -d "${TMPDIR:-/tmp}/asahi-sigkill.XXXXXX") +child='' +cleanup() { + if [ -n "$child" ]; then + kill -KILL "$child" 2>/dev/null || true + wait "$child" 2>/dev/null || true + fi + rm -rf -- "$tmp" +} +trap cleanup EXIT +trap 'exit 1' HUP INT TERM + +cc -O1 "$root/vkrepro.c" -lvulkan -o "$tmp/vkrepro" +shader="$tmp/comp.spv" +if [ "$shader_compiler" = glslangValidator ]; then + glslangValidator -V -S comp "$root/comp.comp" -o "$shader" +else + glslc -fshader-stage=compute "$root/comp.comp" -o "$shader" +fi + +kernel_journal_snapshot() { + journalctl -k -b --no-pager -o cat > "$tmp/kernel.log" || { + echo "FAIL: cannot read current-boot kernel journal" >&2 + return 1 + } + if [ ! -s "$tmp/kernel.log" ]; then + echo "FAIL: current-boot kernel journal is empty" >&2 + return 1 + fi +} + +gpu_fault_count() { + kernel_journal_snapshot || return 1 + awk '/GPU fault nya|Unmapped address/ { count++ } END { print count + 0 }' "$tmp/kernel.log" +} + +gpu_timeout_count() { + kernel_journal_snapshot || return 1 + awk '/GPU timeout nya/ { count++ } END { print count + 0 }' "$tmp/kernel.log" +} + +kernel_error_count() { + kernel_journal_snapshot || return 1 + awk ' + /MMU: deferred VM close failed/ || + /deferred user unmap failed/ || + /deferred object unmap failed/ || + /WARNING:/ || /BUG:/ { count++ } + END { print count + 0 } + ' "$tmp/kernel.log" +} + +before_faults=$(gpu_fault_count) +before_timeouts=$(gpu_timeout_count) +before_kernel_errors=$(kernel_error_count) +iteration=1 +while [ "$iteration" -le "$count" ]; do + log="$tmp/run.log" + "$tmp/vkrepro" "$shader" > "$log" 2>&1 & + child=$! + deadline=$(( $(date +%s) + 30 )) + while ! grep -q '^ready$' "$log" 2>/dev/null; do + if ! kill -0 "$child" 2>/dev/null; then + cat "$log" >&2 + echo "FAIL: repro exited before readiness at iteration $iteration" >&2 + exit 1 + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + cat "$log" >&2 + echo "FAIL: readiness timed out at iteration $iteration" >&2 + exit 1 + fi + sleep 0.1 + done + kill -KILL "$child" + wait "$child" 2>/dev/null || true + child= + sleep 1 + echo "SIGKILL $iteration/$count" + iteration=$((iteration + 1)) +done + +sleep 3 + +after_faults=$(gpu_fault_count) +after_timeouts=$(gpu_timeout_count) +after_kernel_errors=$(kernel_error_count) +new_faults=$((after_faults - before_faults)) +new_timeouts=$((after_timeouts - before_timeouts)) +new_kernel_errors=$((after_kernel_errors - before_kernel_errors)) +echo "GPU faults before=$before_faults after=$after_faults delta=$new_faults" +echo "GPU timeouts before=$before_timeouts after=$after_timeouts delta=$new_timeouts" +echo "Kernel error lines before=$before_kernel_errors after=$after_kernel_errors delta=$new_kernel_errors" +if [ "$new_faults" -ne 0 ] || [ "$new_timeouts" -ne 0 ] || [ "$new_kernel_errors" -ne 0 ]; then + echo "FAIL: GPU faults, timeouts, or kernel errors increased" >&2 + exit 1 +fi +echo "PASS: $count SIGKILL runs after two compute submissions had no GPU faults, timeouts, or kernel errors" diff --git a/tools/testing/selftests/drivers/gpu/asahi-sigkill/vkrepro.c b/tools/testing/selftests/drivers/gpu/asahi-sigkill/vkrepro.c new file mode 100644 index 00000000000000..1adb90b587020d --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-sigkill/vkrepro.c @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include + +#define GROUPS 65536u +#define CHECK(call) do { \ + VkResult result = (call); \ + if (result != VK_SUCCESS) { \ + fprintf(stderr, "%s failed: %d\n", #call, result); \ + return 1; \ + } \ +} while (0) + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "usage: %s shader.spv\n", argv[0]); + return 1; + } + VkApplicationInfo app = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .apiVersion = VK_API_VERSION_1_1, + }; + VkInstanceCreateInfo instance_info = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + }; + VkInstance instance; + CHECK(vkCreateInstance(&instance_info, NULL, &instance)); + + uint32_t device_count = 0; + CHECK(vkEnumeratePhysicalDevices(instance, &device_count, NULL)); + if (!device_count) { + fprintf(stderr, "no Vulkan device\n"); + return 1; + } + VkPhysicalDevice *devices = calloc(device_count, sizeof(*devices)); + if (!devices) + return 1; + CHECK(vkEnumeratePhysicalDevices(instance, &device_count, devices)); + VkPhysicalDevice physical = VK_NULL_HANDLE; + for (uint32_t i = 0; i < device_count; i++) { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(devices[i], &properties); + if (strstr(properties.deviceName, "Apple")) { + physical = devices[i]; + printf("device %s\n", properties.deviceName); + break; + } + } + free(devices); + if (physical == VK_NULL_HANDLE) { + fprintf(stderr, "no Apple Vulkan device\n"); + return 1; + } + + uint32_t family_count = 0; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, NULL); + VkQueueFamilyProperties *families = calloc(family_count, sizeof(*families)); + if (!families) + return 1; + vkGetPhysicalDeviceQueueFamilyProperties(physical, &family_count, families); + uint32_t family = family_count; + for (uint32_t i = 0; i < family_count; i++) { + if (families[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { + family = i; + break; + } + } + free(families); + if (family == family_count) { + fprintf(stderr, "no Vulkan compute queue\n"); + return 1; + } + + float priority = 1.0f; + VkDeviceQueueCreateInfo queue_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueFamilyIndex = family, + .queueCount = 1, + .pQueuePriorities = &priority, + }; + VkDeviceCreateInfo device_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + }; + VkDevice device; + CHECK(vkCreateDevice(physical, &device_info, NULL, &device)); + VkQueue queue; + vkGetDeviceQueue(device, family, 0, &queue); + + VkBufferCreateInfo buffer_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .size = (VkDeviceSize)GROUPS * 256 * sizeof(float), + .usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; + VkBuffer buffer; + CHECK(vkCreateBuffer(device, &buffer_info, NULL, &buffer)); + VkMemoryRequirements requirements; + vkGetBufferMemoryRequirements(device, buffer, &requirements); + VkPhysicalDeviceMemoryProperties memory_properties; + vkGetPhysicalDeviceMemoryProperties(physical, &memory_properties); + uint32_t memory_type = memory_properties.memoryTypeCount; + for (uint32_t i = 0; i < memory_properties.memoryTypeCount; i++) { + if ((requirements.memoryTypeBits & (1u << i)) && + (memory_properties.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) { + memory_type = i; + break; + } + } + if (memory_type == memory_properties.memoryTypeCount) { + fprintf(stderr, "no host-visible memory type\n"); + return 1; + } + VkMemoryAllocateInfo allocation = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = requirements.size, + .memoryTypeIndex = memory_type, + }; + VkDeviceMemory memory; + CHECK(vkAllocateMemory(device, &allocation, NULL, &memory)); + CHECK(vkBindBufferMemory(device, buffer, memory, 0)); + + FILE *shader_file = fopen(argv[1], "rb"); + if (!shader_file) { + perror("shader"); + return 1; + } + if (fseek(shader_file, 0, SEEK_END)) + return 1; + long shader_size = ftell(shader_file); + if (shader_size <= 0 || fseek(shader_file, 0, SEEK_SET)) + return 1; + uint32_t *shader_code = malloc((size_t)shader_size); + if (!shader_code) + return 1; + if (fread(shader_code, 1, (size_t)shader_size, shader_file) != (size_t)shader_size) + return 1; + fclose(shader_file); + VkShaderModuleCreateInfo shader_info = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = (size_t)shader_size, + .pCode = shader_code, + }; + VkShaderModule shader; + CHECK(vkCreateShaderModule(device, &shader_info, NULL, &shader)); + free(shader_code); + + VkDescriptorSetLayoutBinding binding = { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + }; + VkDescriptorSetLayoutCreateInfo set_layout_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 1, + .pBindings = &binding, + }; + VkDescriptorSetLayout set_layout; + CHECK(vkCreateDescriptorSetLayout(device, &set_layout_info, NULL, &set_layout)); + VkPipelineLayoutCreateInfo pipeline_layout_info = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = 1, + .pSetLayouts = &set_layout, + }; + VkPipelineLayout pipeline_layout; + CHECK(vkCreatePipelineLayout(device, &pipeline_layout_info, NULL, &pipeline_layout)); + VkComputePipelineCreateInfo pipeline_info = { + .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .layout = pipeline_layout, + .stage = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, + .module = shader, + .pName = "main", + }, + }; + VkPipeline pipeline; + CHECK(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, NULL, &pipeline)); + + VkDescriptorPoolSize pool_size = { + .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, + }; + VkDescriptorPoolCreateInfo pool_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, + .maxSets = 1, + .poolSizeCount = 1, + .pPoolSizes = &pool_size, + }; + VkDescriptorPool pool; + CHECK(vkCreateDescriptorPool(device, &pool_info, NULL, &pool)); + VkDescriptorSetAllocateInfo set_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .descriptorPool = pool, + .descriptorSetCount = 1, + .pSetLayouts = &set_layout, + }; + VkDescriptorSet set; + CHECK(vkAllocateDescriptorSets(device, &set_info, &set)); + VkDescriptorBufferInfo descriptor_buffer = { + .buffer = buffer, + .range = VK_WHOLE_SIZE, + }; + VkWriteDescriptorSet write = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .dstSet = set, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .pBufferInfo = &descriptor_buffer, + }; + vkUpdateDescriptorSets(device, 1, &write, 0, NULL); + + VkCommandPoolCreateInfo command_pool_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .queueFamilyIndex = family, + }; + VkCommandPool command_pool; + CHECK(vkCreateCommandPool(device, &command_pool_info, NULL, &command_pool)); + VkCommandBufferAllocateInfo command_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = command_pool, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 2, + }; + VkCommandBuffer commands[2]; + CHECK(vkAllocateCommandBuffers(device, &command_info, commands)); + VkFence fences[2]; + VkFenceCreateInfo fence_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO }; + for (int i = 0; i < 2; i++) { + VkCommandBufferBeginInfo begin = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; + CHECK(vkBeginCommandBuffer(commands[i], &begin)); + vkCmdBindPipeline(commands[i], VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); + vkCmdBindDescriptorSets(commands[i], VK_PIPELINE_BIND_POINT_COMPUTE, + pipeline_layout, 0, 1, &set, 0, NULL); + vkCmdDispatch(commands[i], GROUPS, 1, 1); + CHECK(vkEndCommandBuffer(commands[i])); + CHECK(vkCreateFence(device, &fence_info, NULL, &fences[i])); + } + + VkSubmitInfo submits[2] = {0}; + for (int i = 0; i < 2; i++) { + submits[i].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submits[i].commandBufferCount = 1; + submits[i].pCommandBuffers = &commands[i]; + } + CHECK(vkQueueSubmit(queue, 1, &submits[0], fences[0])); + CHECK(vkQueueSubmit(queue, 1, &submits[1], fences[1])); + puts("ready"); + fflush(stdout); + + int current = 0; + for (;;) { + CHECK(vkWaitForFences(device, 1, &fences[current], VK_TRUE, UINT64_MAX)); + CHECK(vkResetFences(device, 1, &fences[current])); + CHECK(vkQueueSubmit(queue, 1, &submits[current], fences[current])); + current ^= 1; + } +}