From f37847557d1825ed34ad9d8f3418c62a34131e39 Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 29 Nov 2026 03:34:22 -0500 Subject: [PATCH 1/2] test(dmabuf): enforce sync_file fence ordering stress test across 1000+ handoffs (#15) --- src/fs_dmabuf.cpp | 42 +++++++- tests/test_freesched.cpp | 200 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 238 insertions(+), 4 deletions(-) diff --git a/src/fs_dmabuf.cpp b/src/fs_dmabuf.cpp index 8ffdf0c..c8dafa4 100644 --- a/src/fs_dmabuf.cpp +++ b/src/fs_dmabuf.cpp @@ -595,6 +595,10 @@ fs_status_t fs_fence_signal(fs_fence_t* fence, int sync_file_fd) { if (fence->state == FS_FENCE_ERROR) { return FS_ERR_FENCE; } + if (fence->state == FS_FENCE_SIGNALED) { + /* Duplicate signal: reject cleanly without overwriting the original sync_file. */ + return FS_ERR_FENCE; + } fence->sync_file_fd = sync_file_fd; fence->state = FS_FENCE_SIGNALED; fence->signaled_at_us = fs_now_us(); @@ -894,6 +898,12 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, const uint64_t t0 = fs_now_us(); + /* Snapshot for atomic rollback if target mapping fails after the transfer. */ + fs_dev_t prev_owner = from_dev; + uint64_t prev_gen = 1u; + fs_fence_t prev_fence = fs_fence_init(from_dev); + bool have_prev = false; + { std::lock_guard lock(ctx->mu); fs_dmabuf_record* rec = fs_record_from_pub(buf); @@ -954,6 +964,20 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, static_cast(rec->pub.buf_id)); return FS_ERR_FENCE; } + /* Strict monotonic sync_file ordering: a pre-sequenced fence that is not + * strictly newer than the buffer's last fence is duplicate/stale and is + * rejected without touching ownership or generation. seq == 0 means the + * caller signaled without allocating a sequence (fs_fence_signal leaves + * seq untouched); such fences are upgraded to a fresh sequence below so + * they stay compatible with backend-produced signal fences. */ + if (io_fence->state == FS_FENCE_SIGNALED && io_fence->seq != 0u && + io_fence->seq <= rec->last_fence.seq) { + fs_set_error(ctx, "stale/duplicate fence on buf %llu: seq %llu <= last %llu", + static_cast(rec->pub.buf_id), + static_cast(io_fence->seq), + static_cast(rec->last_fence.seq)); + return FS_ERR_FENCE; + } if (io_fence->sync_file_fd >= 0) { fs_status_t wst = fs_fence_wait(io_fence, 5000u); if (wst != FS_OK) { @@ -962,11 +986,13 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, return wst; } } - if (io_fence->state == FS_FENCE_UNSIGNALED) { + if (io_fence->state == FS_FENCE_UNSIGNALED || io_fence->seq == 0u) { io_fence->producer_dev = from_dev; io_fence->seq = ++ctx->next_fence_seq; io_fence->state = FS_FENCE_SIGNALED; io_fence->signaled_at_us = fs_now_us(); + } else if (io_fence->seq > ctx->next_fence_seq) { + ctx->next_fence_seq = io_fence->seq; } rec->last_fence = *io_fence; rec->pub.sync_file_fd = io_fence->sync_file_fd; @@ -1047,6 +1073,10 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, ctx->telemetry.zero_copy_handoffs++; } + prev_owner = rec->pub.owner_dev; + prev_gen = rec->pub.generation; + prev_fence = rec->last_fence; + have_prev = true; rec->pub.owner_dev = to_dev; rec->pub.generation += 1u; rec->pub.last_handoff_us = fs_now_us(); @@ -1058,11 +1088,15 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, /* Ensure target device has zero-copy mapping (EDGETPU_MAP_DMABUF / VK_KHR_external_memory_fd) */ fs_status_t map_st = fs_dmabuf_ensure_mapped(ctx, buf, to_dev); if (map_st != FS_OK) { - /* Roll back ownership atomically if backend import rejects the buffer */ + /* Roll back ownership, generation, and fence atomically if backend import + * rejects the buffer, so a failed handoff leaves no state change behind. */ std::lock_guard lock(ctx->mu); fs_dmabuf_record* rec = fs_record_from_pub(buf); - if (rec && rec->owner_ctx == ctx) { - rec->pub.owner_dev = from_dev; + if (have_prev && rec && rec->owner_ctx == ctx) { + rec->pub.owner_dev = prev_owner; + rec->pub.generation = prev_gen; + rec->last_fence = prev_fence; + rec->pub.sync_file_fd = prev_fence.sync_file_fd; } } return map_st; diff --git a/tests/test_freesched.cpp b/tests/test_freesched.cpp index 8cf207a..de3a268 100644 --- a/tests/test_freesched.cpp +++ b/tests/test_freesched.cpp @@ -7,10 +7,12 @@ #include "freesched.h" #include "ggml_freesilicon.h" +#include #include #include #include #include +#include #include #define CHECK(cond) \ @@ -1136,6 +1138,203 @@ static bool test_real_backend_adapters_and_dmabuf_sync() { return true; } +/* ========================================================================= + * Test 8: DMA-BUF sync_file Fence Ordering Stress (Issue #15) + * + * Deterministic multi-handoff stress across GPU <-> TPU <-> CPU: + * - 1,000+ sequential handoffs cycling GPU_VK -> TPU -> CPU_NEON, + * - strict FS_ERR_OWNERSHIP on stale writer handoffs and stale consumer + * accesses after ownership moved on, + * - monotonic fence ordering: duplicate/out-of-order/stale fence signals + * rejected with FS_ERR_FENCE and no ownership corruption, + * - concurrent multi-threaded handoffs (one buffer per worker thread + * sharing a single context mutex) under TSan. + * Verifies fallback_copies == 0 across every transition. + * ========================================================================= */ +static bool test_dmabuf_fence_ordering_stress() { + fs_config_t cfg = fs_config_default(); + cfg.mock_mode = 1; + cfg.profile = FS_PROFILE_PIXEL11_MALIBU; + + fs_context_t* ctx = nullptr; + CHECK(fs_context_create(&cfg, &ctx) == FS_OK); + + /* Reconciled linear non-coherent attrs: zero-copy eligible on all 3 devices. */ + fs_buf_attr_t cycle_attrs[3] = { + fs_buf_attr_default(FS_DEV_GPU_VK), + fs_buf_attr_default(FS_DEV_TPU), + fs_buf_attr_default(FS_DEV_CPU_NEON), + }; + const fs_dev_t cyc[3] = {FS_DEV_GPU_VK, FS_DEV_TPU, FS_DEV_CPU_NEON}; + + fs_dmabuf_t* buf = nullptr; + CHECK(fs_buffer_alloc_reconciled(ctx, 4096u, cycle_attrs, 3u, FS_DEV_GPU_VK, FS_BUF_ZERO_INIT, + &buf, nullptr) == FS_OK); + CHECK(buf->zero_copy_compatible == 1); + CHECK(buf->generation == 1u); + + /* Phase A: 1,000 deterministic sequential handoffs GPU -> TPU -> CPU_NEON -> ... */ + constexpr int kSeqHandoffs = 1000; + for (int i = 0; i < kSeqHandoffs; ++i) { + const fs_dev_t from = cyc[i % 3]; + const fs_dev_t to = cyc[(i + 1) % 3]; + CHECK(buf->owner_dev == from); + fs_fence_t fence = fs_fence_init(from); + CHECK(fs_buffer_handoff(ctx, buf, from, to, &fence) == FS_OK); + CHECK(fence.state == FS_FENCE_SIGNALED); + CHECK(buf->owner_dev == to); + CHECK(buf->generation == static_cast(i) + 2u); + } + fs_telemetry_t tel; + CHECK(fs_context_get_telemetry(ctx, &tel) == FS_OK); + CHECK(tel.zero_copy_handoffs == static_cast(kSeqHandoffs)); + CHECK(tel.fallback_copies == 0u); + + /* Phase B: stale generation / stale writer traps (ownership moved on). */ + const uint64_t cur_gen = buf->generation; + const fs_dev_t cur_owner = buf->owner_dev; + const fs_dev_t old_owner = cyc[(kSeqHandoffs - 1) % 3]; /* owner before last handoff */ + CHECK(cur_owner != old_owner); + /* Stale writer: previously-owning device attempts handoff. */ + CHECK(fs_buffer_handoff(ctx, buf, old_owner, FS_DEV_CPU_NEON == cur_owner ? FS_DEV_GPU_VK + : FS_DEV_CPU_NEON, + nullptr) == FS_ERR_OWNERSHIP); + CHECK(buf->owner_dev == cur_owner); + CHECK(buf->generation == cur_gen); + /* Stale consumer: previous device and stale generation both trapped. */ + CHECK(fs_buffer_acquire_access(ctx, buf, old_owner, cur_gen) == FS_ERR_OWNERSHIP); + CHECK(fs_buffer_acquire_access(ctx, buf, cur_owner, cur_gen - 1u) == FS_ERR_OWNERSHIP); + CHECK(buf->owner_dev == cur_owner); + CHECK(buf->generation == cur_gen); + /* Current owner + current generation still succeeds. */ + CHECK(fs_buffer_acquire_access(ctx, buf, cur_owner, cur_gen) == FS_OK); + CHECK(fs_buffer_release_access(ctx, buf, cur_owner) == FS_OK); + + /* Phase C: monotonic fence ordering. Export a real sequenced fence. */ + fs_fence_t exp = fs_fence_init(cur_owner); + CHECK(fs_buffer_export_sync_file(ctx, buf, FS_DMA_SYNC_RW, &exp) == FS_OK); + CHECK(exp.state == FS_FENCE_SIGNALED); + CHECK(exp.seq > 0u); + const uint64_t exp_seq = exp.seq; + const fs_dev_t nxt = (cur_owner == FS_DEV_GPU_VK) ? FS_DEV_TPU : FS_DEV_GPU_VK; + /* Fresh exported fence is strictly newer: handoff succeeds. */ + fs_fence_t exp_copy = exp; + CHECK(fs_buffer_handoff(ctx, buf, cur_owner, nxt, &exp_copy) == FS_OK); + CHECK(buf->owner_dev == nxt); + CHECK(buf->generation == cur_gen + 1u); + fs_fence_close(&exp); + fs_fence_close(&exp_copy); + /* Replaying the exact same fence (duplicate) is rejected, state intact. */ + fs_fence_t dup = fs_fence_init(cur_owner); + dup.state = FS_FENCE_SIGNALED; + dup.seq = exp_seq; + CHECK(fs_buffer_handoff(ctx, buf, nxt, cur_owner, &dup) == FS_ERR_FENCE); + CHECK(buf->owner_dev == nxt); + CHECK(buf->generation == cur_gen + 1u); + /* Out-of-order ancient seq also rejected. */ + fs_fence_t stale = fs_fence_init(cur_owner); + stale.state = FS_FENCE_SIGNALED; + stale.seq = 1u; + CHECK(fs_buffer_handoff(ctx, buf, nxt, cur_owner, &stale) == FS_ERR_FENCE); + CHECK(buf->owner_dev == nxt); + CHECK(buf->generation == cur_gen + 1u); + /* Errored fence rejected. */ + fs_fence_t bad = fs_fence_init(cur_owner); + bad.state = FS_FENCE_ERROR; + CHECK(fs_buffer_handoff(ctx, buf, nxt, cur_owner, &bad) == FS_ERR_FENCE); + CHECK(buf->owner_dev == nxt); + CHECK(buf->generation == cur_gen + 1u); + /* Unsignaled fence gets a fresh monotonic seq and succeeds. */ + fs_fence_t fresh = fs_fence_init(nxt); + CHECK(fs_buffer_handoff(ctx, buf, nxt, cur_owner, &fresh) == FS_OK); + CHECK(fresh.seq > exp_seq); + CHECK(buf->owner_dev == cur_owner); + CHECK(buf->generation == cur_gen + 2u); + /* Manually signaled seq==0 fence (backend-style) is upgraded and accepted. */ + fs_fence_t manual = fs_fence_init(cur_owner); + CHECK(fs_fence_signal(&manual, -1) == FS_OK); + CHECK(fs_buffer_handoff(ctx, buf, cur_owner, nxt, &manual) == FS_OK); + CHECK(manual.seq > fresh.seq); + CHECK(buf->owner_dev == nxt); + /* Duplicate fs_fence_signal is rejected without overwriting. */ + fs_fence_t once = fs_fence_init(nxt); + CHECK(fs_fence_signal(&once, -1) == FS_OK); + CHECK(fs_fence_signal(&once, -1) == FS_ERR_FENCE); + CHECK(once.state == FS_FENCE_SIGNALED); + CHECK(fs_context_get_telemetry(ctx, &tel) == FS_OK); + CHECK(tel.fallback_copies == 0u); + fs_buffer_release(ctx, buf); + + /* Phase D: concurrent handoffs, one buffer per thread on a shared context. */ + constexpr int kThreads = 4; + constexpr int kPerThread = 250; /* 4 * 250 = 1,000 more transitions */ + fs_dmabuf_t* cbufs[kThreads] = {nullptr, nullptr, nullptr, nullptr}; + for (int t = 0; t < kThreads; ++t) { + CHECK(fs_buffer_alloc_reconciled(ctx, 4096u, cycle_attrs, 3u, FS_DEV_GPU_VK, FS_BUF_ZERO_INIT, + &cbufs[t], nullptr) == FS_OK); + } + std::atomic err_count{0}; + auto worker = [&](int w) { + fs_dmabuf_t* wb = cbufs[w]; + fs_dev_t wcur = FS_DEV_GPU_VK; + for (int i = 0; i < kPerThread; ++i) { + const fs_dev_t wfrom = cyc[i % 3]; + const fs_dev_t wto = cyc[(i + 1) % 3]; + if (wfrom != wcur) { err_count.fetch_add(1); return; } + fs_fence_t wf = fs_fence_init(wfrom); + if (fs_buffer_handoff(ctx, wb, wfrom, wto, &wf) != FS_OK) { + err_count.fetch_add(1); + return; + } + if (wb->owner_dev != wto) { err_count.fetch_add(1); return; } + if (wb->generation != static_cast(i) + 2u) { err_count.fetch_add(1); return; } + wcur = wto; + } + }; + std::vector pool; + for (int t = 0; t < kThreads; ++t) pool.emplace_back(worker, t); + for (auto& th : pool) th.join(); + CHECK(err_count.load() == 0); + for (int t = 0; t < kThreads; ++t) { + CHECK(cbufs[t]->generation == static_cast(kPerThread) + 1u); + fs_buffer_release(ctx, cbufs[t]); + } + CHECK(fs_context_get_telemetry(ctx, &tel) == FS_OK); + CHECK(tel.fallback_copies == 0u); + CHECK(tel.zero_copy_handoffs == + static_cast(kSeqHandoffs + 3 + kThreads * kPerThread)); + + /* Phase E: exclusive-access contention on one shared buffer. */ + fs_dmabuf_t* sbuf = nullptr; + CHECK(fs_buffer_alloc_reconciled(ctx, 4096u, cycle_attrs, 3u, FS_DEV_GPU_VK, FS_BUF_ZERO_INIT, + &sbuf, nullptr) == FS_OK); + CHECK(fs_buffer_acquire_access(ctx, sbuf, FS_DEV_GPU_VK, sbuf->generation) == FS_OK); + std::atomic locked{1}; + std::atomic contend_ok{0}; + std::thread other([&]() { + while (!locked.load(std::memory_order_acquire)) { /* spin until holder is locked */ } + /* Exclusive lock held by GPU: TPU attempt must be trapped. */ + if (fs_buffer_acquire_access(ctx, sbuf, FS_DEV_TPU, 0u) == FS_ERR_OWNERSHIP) { + contend_ok.fetch_add(1); + } + while (locked.load(std::memory_order_acquire) != 2) { /* spin until holder releases */ } + /* After release, same accessor with pinned generation succeeds. */ + const uint64_t g2 = sbuf->generation; + if (fs_buffer_acquire_access(ctx, sbuf, FS_DEV_GPU_VK, g2) == FS_OK) { + fs_buffer_release_access(ctx, sbuf, FS_DEV_GPU_VK); + contend_ok.fetch_add(1); + } + }); + CHECK(fs_buffer_release_access(ctx, sbuf, FS_DEV_GPU_VK) == FS_OK); + locked.store(2, std::memory_order_release); + other.join(); + CHECK(contend_ok.load() == 2); + fs_buffer_release(ctx, sbuf); + + fs_context_destroy(ctx); + return true; +} + int main() { struct { const char* name; @@ -1148,6 +1347,7 @@ int main() { {"custom_vtable_and_ggml_seam", test_custom_vtable_and_ggml_seam}, {"dmabuf_reconcile_and_router_pricing", test_dmabuf_reconcile_and_router_pricing}, {"real_backend_adapters_and_dmabuf_sync", test_real_backend_adapters_and_dmabuf_sync}, + {"dmabuf_fence_ordering_stress", test_dmabuf_fence_ordering_stress}, }; int passed = 0; From 293dfdefe2d7fc2efe5e365b81a6cd324ce1bba7 Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 29 Nov 2026 08:25:25 -0500 Subject: [PATCH 2/2] harden(freesched-31): fence fd validation, seq wrap, alloc overflow, refcount and rollback clamp --- src/fs_dmabuf.cpp | 90 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 73 insertions(+), 17 deletions(-) diff --git a/src/fs_dmabuf.cpp b/src/fs_dmabuf.cpp index c8dafa4..8f5ac9d 100644 --- a/src/fs_dmabuf.cpp +++ b/src/fs_dmabuf.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -68,6 +69,14 @@ static fs_dmabuf_record* fs_record_from_pub(fs_dmabuf_t* buf) { return rec; } +static uint64_t fs_next_fence_seq(fs_context_t* ctx) { + uint64_t next = ++ctx->next_fence_seq; + if (next == 0u) { + next = ++ctx->next_fence_seq; + } + return next; +} + static size_t fs_page_size(void) { long pg = sysconf(_SC_PAGESIZE); return (pg > 0) ? static_cast(pg) : 4096u; @@ -102,8 +111,14 @@ static void fs_free_record_backing(fs_context_t* ctx, fs_dmabuf_record* rec) { close(rec->pub.dmabuf_fd); } } + if (rec->last_fence.sync_file_fd >= 0 && + rec->last_fence.sync_file_fd != rec->pub.dmabuf_fd) { + close(rec->last_fence.sync_file_fd); + rec->last_fence.sync_file_fd = -1; + } rec->pub.host_ptr = nullptr; rec->pub.dmabuf_fd = -1; + rec->pub.sync_file_fd = -1; rec->pub.owner_dev = FS_DEV_NONE; rec->magic = 0u; std::free(rec); @@ -571,7 +586,7 @@ fs_status_t fs_buffer_export_sync_file(fs_context_t* ctx, #endif *out_fence = fs_fence_init(rec->pub.owner_dev); - out_fence->seq = ++ctx->next_fence_seq; + out_fence->seq = fs_next_fence_seq(ctx); out_fence->sync_file_fd = sync_fd; out_fence->state = FS_FENCE_SIGNALED; out_fence->signaled_at_us = fs_now_us(); @@ -592,6 +607,9 @@ fs_status_t fs_fence_signal(fs_fence_t* fence, int sync_file_fd) { if (!fence) { return FS_ERR_INVALID_ARG; } + if (sync_file_fd < -1) { + return FS_ERR_INVALID_ARG; + } if (fence->state == FS_FENCE_ERROR) { return FS_ERR_FENCE; } @@ -609,6 +627,9 @@ fs_status_t fs_fence_wait(const fs_fence_t* fence, uint32_t timeout_ms) { if (!fence) { return FS_OK; } + if (fence->sync_file_fd < -1) { + return FS_ERR_INVALID_ARG; + } if (fence->state == FS_FENCE_ERROR) { return FS_ERR_FENCE; } @@ -619,8 +640,11 @@ fs_status_t fs_fence_wait(const fs_fence_t* fence, uint32_t timeout_ms) { pfd.events = POLLIN; pfd.revents = 0; int rc = 0; + const int poll_timeout = timeout_ms > static_cast(INT_MAX) + ? INT_MAX + : static_cast(timeout_ms); do { - rc = poll(&pfd, 1, static_cast(timeout_ms)); + rc = poll(&pfd, 1, poll_timeout); } while (rc < 0 && errno == EINTR); if (rc < 0) { return FS_ERR_IO; @@ -663,6 +687,9 @@ fs_status_t fs_buffer_alloc(fs_context_t* ctx, const size_t pg = fs_page_size(); const size_t alloc_size = fs_align_up(size_bytes, pg); + if (alloc_size < size_bytes || alloc_size == 0u) { + return FS_ERR_OVERFLOW; + } std::lock_guard lock(ctx->mu); @@ -670,7 +697,10 @@ fs_status_t fs_buffer_alloc(fs_context_t* ctx, if ((flags & FS_BUF_NO_POOL) == 0u) { for (auto it = ctx->pooled_buffers.begin(); it != ctx->pooled_buffers.end(); ++it) { fs_dmabuf_record* rec = *it; - if (rec->alloc_size >= alloc_size && rec->alloc_size <= alloc_size * 2u) { + const size_t alloc_limit = (alloc_size > static_cast(-1) / 2u) + ? static_cast(-1) + : alloc_size * 2u; + if (rec->alloc_size >= alloc_size && rec->alloc_size <= alloc_limit) { ctx->pooled_buffers.erase(it); ctx->pooled_bytes -= rec->alloc_size; ctx->pool_hits++; @@ -848,6 +878,9 @@ fs_status_t fs_buffer_retain(fs_context_t* ctx, fs_dmabuf_t* buf) { if (!rec || rec->owner_ctx != ctx || rec->in_pool) { return FS_ERR_INVALID_ARG; } + if (rec->pub.refcount == UINT32_MAX) { + return FS_ERR_OVERFLOW; + } rec->pub.refcount++; return FS_OK; } @@ -898,11 +931,12 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, const uint64_t t0 = fs_now_us(); - /* Snapshot for atomic rollback if target mapping fails after the transfer. */ - fs_dev_t prev_owner = from_dev; - uint64_t prev_gen = 1u; - fs_fence_t prev_fence = fs_fence_init(from_dev); - bool have_prev = false; + /* Snapshot taken under lock before any mutation so rollback can restore + * the pre-handoff fence, not the overwritten one. */ + fs_dev_t prev_owner = from_dev; + uint64_t prev_gen = 1u; + fs_fence_t prev_fence = fs_fence_init(from_dev); + bool have_prev = false; { std::lock_guard lock(ctx->mu); @@ -911,6 +945,10 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, fs_set_error(ctx, "handoff called on invalid or released buffer"); return FS_ERR_INVALID_ARG; } + prev_owner = rec->pub.owner_dev; + prev_gen = rec->pub.generation; + prev_fence = rec->last_fence; + have_prev = true; /* Strict single-owner invariant: catches use-after-handoff and wrong owner */ if (rec->pub.owner_dev != from_dev) { @@ -959,6 +997,10 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, /* Validate / advance explicit sync_file fence */ if (io_fence) { + if (io_fence->sync_file_fd < -1) { + fs_set_error(ctx, "invalid fence fd on buf %llu", static_cast(rec->pub.buf_id)); + return FS_ERR_INVALID_ARG; + } if (io_fence->state == FS_FENCE_ERROR) { fs_set_error(ctx, "cannot handoff buf %llu with errored fence", static_cast(rec->pub.buf_id)); @@ -988,17 +1030,30 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, } if (io_fence->state == FS_FENCE_UNSIGNALED || io_fence->seq == 0u) { io_fence->producer_dev = from_dev; - io_fence->seq = ++ctx->next_fence_seq; + io_fence->seq = fs_next_fence_seq(ctx); io_fence->state = FS_FENCE_SIGNALED; io_fence->signaled_at_us = fs_now_us(); } else if (io_fence->seq > ctx->next_fence_seq) { ctx->next_fence_seq = io_fence->seq; } + if (rec->last_fence.sync_file_fd >= 0 && + rec->last_fence.sync_file_fd != io_fence->sync_file_fd) { + close(rec->last_fence.sync_file_fd); + } rec->last_fence = *io_fence; - rec->pub.sync_file_fd = io_fence->sync_file_fd; + if (io_fence->sync_file_fd >= 0) { + int dup_fd = dup(io_fence->sync_file_fd); + if (dup_fd >= 0) { + rec->last_fence.sync_file_fd = dup_fd; + } + } + rec->pub.sync_file_fd = rec->last_fence.sync_file_fd; } else { + if (rec->last_fence.sync_file_fd >= 0) { + close(rec->last_fence.sync_file_fd); + } rec->last_fence = fs_fence_init(from_dev); - rec->last_fence.seq = ++ctx->next_fence_seq; + rec->last_fence.seq = fs_next_fence_seq(ctx); rec->last_fence.state = FS_FENCE_SIGNALED; rec->last_fence.signaled_at_us = fs_now_us(); rec->pub.sync_file_fd = -1; @@ -1073,10 +1128,6 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, ctx->telemetry.zero_copy_handoffs++; } - prev_owner = rec->pub.owner_dev; - prev_gen = rec->pub.generation; - prev_fence = rec->last_fence; - have_prev = true; rec->pub.owner_dev = to_dev; rec->pub.generation += 1u; rec->pub.last_handoff_us = fs_now_us(); @@ -1089,10 +1140,15 @@ fs_status_t fs_buffer_handoff(fs_context_t* ctx, fs_status_t map_st = fs_dmabuf_ensure_mapped(ctx, buf, to_dev); if (map_st != FS_OK) { /* Roll back ownership, generation, and fence atomically if backend import - * rejects the buffer, so a failed handoff leaves no state change behind. */ + * rejects the buffer. Use current-state guard so a concurrent successful + * handoff in the map window is not clobbered. */ std::lock_guard lock(ctx->mu); fs_dmabuf_record* rec = fs_record_from_pub(buf); - if (have_prev && rec && rec->owner_ctx == ctx) { + if (have_prev && rec && rec->owner_ctx == ctx && rec->pub.owner_dev == to_dev && + rec->pub.generation == prev_gen + 1u) { + if (rec->last_fence.sync_file_fd >= 0) { + close(rec->last_fence.sync_file_fd); + } rec->pub.owner_dev = prev_owner; rec->pub.generation = prev_gen; rec->last_fence = prev_fence;