Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
137 commits
Select commit Hold shift + click to select a range
3688f3c
CUDA keyed graph cache and device arena, both off until a family inst…
jayleaton Oct 10, 2026
b7be793
A failed CUDA kernel launch names its kernel and launch configuration…
jayleaton Oct 10, 2026
faf5901
fix(cuda): correct RDMA VMM capability attribute
jrb-ai Oct 10, 2026
3cc0397
Graph cache: a capture is freed until the map holds it, the keep floo…
jayleaton Oct 11, 2026
c58d83c
CUDA arena: the address maps are rehashed before tombstones fill them
jayleaton Oct 11, 2026
25c02d3
Tensor parallelism across CUDA processes: bootstrap, NCCL, mailbox an…
jayleaton Oct 10, 2026
6b5404d
TP tests: a drain on rank 0 then its clean stop ends rank 1's loop at…
jayleaton Oct 10, 2026
06c4e75
TP RoCE: with no TF_TP_ROCE_HCA, each rank picks the ports on an IPv4…
jayleaton Oct 11, 2026
062af8b
TP README: when -Dtp-nvcc, TF_TP_ROCE_HCA, NCCL_IB_HCA, NCCL_SOCKET_I…
jayleaton Oct 11, 2026
d7510ef
TP test runner: a binary built without the mailbox kernel refuses the…
jayleaton Oct 11, 2026
e16e331
TP RoCE: every RDMA post is bounds-checked before the verb, and peers…
jayleaton Oct 11, 2026
649e788
TP RoCE: no RDMA write past 1 MiB, and boot refuses any setting that …
jayleaton Oct 11, 2026
664a8e2
TP RoCE: TF_TP_ROCE_CHUNKED_KB gathers strides past the slot in slot-…
jayleaton Oct 11, 2026
4ad5029
TP RoCE: a failed transport halts its QPs, drains them and keeps its …
jayleaton Oct 11, 2026
9bbc21a
TP RoCE: tf-tp-test failfast V transport checks the failed-transport …
jayleaton Oct 11, 2026
cf19042
Fix RoCE test smaps lookup for merged mappings
jayleaton Oct 11, 2026
0ba7d30
Sessions: the page map is rehashed before tombstones fill it
jayleaton Oct 11, 2026
0918809
Let a family's round planner drive the lane host with prompt pieces
jayleaton Oct 10, 2026
361f063
Lane host halt: a stop's drain deadline ends the rounds at the next b…
jayleaton Oct 10, 2026
e9f9210
Round planner test: both prompts queue before the host starts, and it…
jayleaton Oct 10, 2026
96ae865
Server hooks for a model family's own chat rules.
jayleaton Oct 10, 2026
df480e0
Server: a stop logs its signal and the open connections when the acce…
jayleaton Oct 10, 2026
2c4d837
Server: SIGTERM / SIGINT drains before stopping.
jayleaton Oct 10, 2026
55bf0a7
Server tests: a stop that lands between a request's count and its dra…
jayleaton Oct 10, 2026
9fbc2b3
Server: a stream that has not sent its first token gets keepalives ev…
jayleaton Oct 10, 2026
bb53ff4
Server tests: the drain test's reply in progress is held until its dr…
jayleaton Oct 10, 2026
9eb765d
DeepSeek-V4.1 host side: release config, EXL3 pack headers, a rank's …
jayleaton Oct 11, 2026
865335e
DeepSeek-V4.1 weight forms built at load, and prepared weight folders…
jayleaton Oct 11, 2026
7ccfc5c
DeepSeek-V4.1 Engram host side: table layout, n-gram hashes of a wind…
jayleaton Oct 11, 2026
b775815
DeepSeek-V4.1 phase timers: where a serving round's time goes, by nam…
jayleaton Oct 11, 2026
def4859
DeepSeek-V4.1 Engram rows from packed per-rank shards on local NVMe, …
jayleaton Oct 11, 2026
c7d29ea
DeepSeek-V4.1 CUDA kernel sources: CSA2 attention and top-k, mHC, rou…
jayleaton Oct 11, 2026
b17df97
DeepSeek-V4.1 kernel tooling: nvcc in a container for any checkout la…
jayleaton Oct 11, 2026
73be75f
DeepSeek-V4.1 kernel launch bindings and their loader: each kernel's …
jayleaton Oct 11, 2026
e687ad5
DeepSeek-V4.1 device kernel tests: tf-dsv41-test, bit-exact against t…
jayleaton Oct 11, 2026
a7674d2
DeepSeek-V4.1 kernel prototypes: attention merge and phase timing, x3…
jayleaton Oct 11, 2026
c0605f0
DeepSeek-V4.1 device-side load: named weights in device buffers, run-…
jayleaton Oct 11, 2026
46bff5e
DeepSeek-V4.1 block emitter: a decode window as calls (attention, the…
jayleaton Oct 11, 2026
6d44dab
CUDA runtime: prioritized streams, external event records, 2D async c…
jayleaton Oct 11, 2026
63e708f
CUDA AOT sets: aot.json specs parsed and matched without cubins, and …
jayleaton Oct 11, 2026
2eeabf7
CUDA memory: a driver allocation count, the arena's first failed chun…
jayleaton Oct 11, 2026
a89bd4f
Graph cache: named caches publish their counts, the floor's state is …
jayleaton Oct 11, 2026
05977fa
Session store: historyOf returns an entry's ids from RAM or from the …
jayleaton Oct 11, 2026
063e855
Graph cache registry: slots claimed, published, released and read und…
jayleaton Oct 11, 2026
d800c62
DeepSeek-V4.1 KV memory: the family's pages, split KV's exchange, the…
jayleaton Oct 11, 2026
bf5a8e8
DeepSeek-V4.1 forward: decode windows over the block emitter, split K…
jayleaton Oct 11, 2026
989ca7e
TP RoCE: run_hosts.sh gives NCCL the RoCE picker's ports when neither…
jayleaton Oct 11, 2026
05c5213
Session memory for paged-KV families: page pool, prefix trie, RAM res…
jayleaton Oct 10, 2026
a3303c7
CUDA keyed graph cache and device arena, both off until a family inst…
jayleaton Oct 10, 2026
69e8a65
A failed CUDA kernel launch names its kernel and launch configuration…
jayleaton Oct 10, 2026
d7e89df
fix(cuda): correct RDMA VMM capability attribute
jrb-ai Oct 10, 2026
5826f89
Graph cache: a capture is freed until the map holds it, the keep floo…
jayleaton Oct 11, 2026
5806e55
CUDA arena: the address maps are rehashed before tombstones fill them
jayleaton Oct 11, 2026
d335520
Graph cache: TF_GRAPH_CACHE=0 or off runs every step eagerly in any f…
jayleaton Oct 14, 2026
7ff83d8
Tensor parallelism across CUDA processes: bootstrap, NCCL, mailbox an…
jayleaton Oct 10, 2026
9af2ea2
TP tests: a drain on rank 0 then its clean stop ends rank 1's loop at…
jayleaton Oct 10, 2026
7c9a26e
TP RoCE: with no TF_TP_ROCE_HCA, each rank picks the ports on an IPv4…
jayleaton Oct 11, 2026
8ebb0be
TP README: when -Dtp-nvcc, TF_TP_ROCE_HCA, NCCL_IB_HCA, NCCL_SOCKET_I…
jayleaton Oct 11, 2026
e9e0056
TP test runner: a binary built without the mailbox kernel refuses the…
jayleaton Oct 11, 2026
0472cbf
TP RoCE: every RDMA post is bounds-checked before the verb, and peers…
jayleaton Oct 11, 2026
9688398
TP RoCE: no RDMA write past 1 MiB, and boot refuses any setting that …
jayleaton Oct 11, 2026
72132f0
TP RoCE: TF_TP_ROCE_CHUNKED_KB gathers strides past the slot in slot-…
jayleaton Oct 11, 2026
e65583c
Server hooks for a model family's own chat rules.
jayleaton Oct 10, 2026
bf19238
TP RoCE: a failed transport halts its QPs, drains them and keeps its …
jayleaton Oct 11, 2026
9a486bb
Server: a stop logs its signal and the open connections when the acce…
jayleaton Oct 10, 2026
beae7e8
TP RoCE: tf-tp-test failfast V transport checks the failed-transport …
jayleaton Oct 11, 2026
467504a
Server: SIGTERM / SIGINT drains before stopping.
jayleaton Oct 10, 2026
602aad5
Fix RoCE test smaps lookup for merged mappings
jayleaton Oct 11, 2026
23bf7d8
Server tests: a stop that lands between a request's count and its dra…
jayleaton Oct 10, 2026
890dfc6
TP RoCE: run_hosts.sh gives NCCL the RoCE picker's ports when neither…
jayleaton Oct 11, 2026
5410eac
Session memory for paged-KV families: page pool, prefix trie, RAM res…
jayleaton Oct 10, 2026
a5b8b35
Server: a stream that has not sent its first token gets keepalives ev…
jayleaton Oct 10, 2026
a3e2fb1
TP NCCL: all_reduce's doc says NCCL adds in its ring's order, so its …
jayleaton Oct 14, 2026
0d0bdb2
Sessions: the page map is rehashed before tombstones fill it
jayleaton Oct 11, 2026
2b3cccf
Server tests: the drain test's reply in progress is held until its dr…
jayleaton Oct 10, 2026
62a75ae
TP: keep Linux-only transport host tests off macOS builds
jayleaton Oct 15, 2026
2cf61d3
Sessions: honor zero residency budgets and reserve uncapped requests
jayleaton Oct 15, 2026
9367784
server: keep shared halt and drain on the existing template path
jayleaton Oct 15, 2026
864fe25
Graph cache: effective settings have one digest for ranks to compare …
jayleaton Oct 16, 2026
e2504f6
TP: bootstrap compares the graph cache's effective settings, so a ran…
jayleaton Oct 16, 2026
dcdc30c
Keep the Linux NVMe lane test out of portable host tests
cwschroeder Oct 16, 2026
368a0d3
Keep the Linux NVMe lane test out of portable host tests
cwschroeder Oct 16, 2026
7a6b32f
server: main's drain stop closes the engine without the closed lane-h…
jayleaton Oct 16, 2026
abcad7d
Merge ashhart/main into stack/02-graph-cache-arena
jayleaton Oct 16, 2026
02d455e
Merge stack/02-graph-cache-arena (with ashhart/main) into stack/03-tp…
jayleaton Oct 16, 2026
9266f3f
Merge stack/03-tp-fabric (with ashhart/main) into stack/04-sessions
jayleaton Oct 16, 2026
001ac2e
Merge stack/04-sessions (with ashhart/main) into stack/07-server
jayleaton Oct 16, 2026
33c0ef6
Merge stack/07-server (sessions, TP, graph cache, current main) into …
jayleaton Oct 16, 2026
af0bc53
Server tests: the drain test imports the named json module
jayleaton Oct 16, 2026
7051a3c
Merge stack/07-server's drain-test json import fix into stack/08a-config
jayleaton Oct 16, 2026
e6df8ad
merge origin/main: the round planner and halt on main's split lane host
jayleaton Oct 16, 2026
4da2618
Merge shared/lane-host-core (#861, on current main) into stack/08a-co…
jayleaton Oct 16, 2026
6b9bede
Merge stack/08a-config (current main, shared layers, #861) into stack…
jayleaton Oct 16, 2026
f17db02
Merge stack/08b-engram (current main, shared layers, #861) into stack…
jayleaton Oct 16, 2026
0137ac2
Merge stack/08c-kernels (current main, shared layers, #861) into stac…
jayleaton Oct 16, 2026
cf649ff
Merge stack/08e-block (current main, shared layers, #861) into stack/…
jayleaton Oct 16, 2026
4a02606
Merge stack/08r-runtime (current main, shared layers, #861) into stac…
jayleaton Oct 16, 2026
968a4f2
Merge stack/09a-kv (current main, shared layers, #861) into stack/09b…
jayleaton Oct 16, 2026
8900c7c
Sessions: a failed prefix insert leaves the index as it was
jayleaton Oct 17, 2026
3aeebb9
CUDA arena: a reuse whose address-map insertion fails keeps its range…
jayleaton Oct 17, 2026
46161ac
Merge stack/02-graph-cache-arena (the #635 arena fix) into stack/03-t…
jayleaton Oct 17, 2026
78ce706
Merge stack/03-tp-fabric (the #635 arena and #637 prefix fixes) into …
jayleaton Oct 17, 2026
9c5bd60
Merge stack/04-sessions (the #635 arena and #637 prefix fixes) into s…
jayleaton Oct 17, 2026
eaa7953
Merge stack/07-server (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
4370f91
Merge stack/08a-config (the #635 arena and #637 prefix fixes) into st…
jayleaton Oct 17, 2026
a0f9598
Merge stack/08b-engram (the #635 arena and #637 prefix fixes) into st…
jayleaton Oct 17, 2026
98a1695
Merge stack/08c-kernels (the #635 arena and #637 prefix fixes) into s…
jayleaton Oct 17, 2026
28e33cc
Merge stack/08e-block (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
f5a0b8b
Merge the layer below (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
3b7681f
Merge the layer below (the #635 arena and #637 prefix fixes) into sta…
jayleaton Oct 17, 2026
88418d8
test(tp): reject malformed runner commands before configuration
cwschroeder Oct 17, 2026
4c69b0d
fix(tp): parse runner commands before opening sessions
cwschroeder Oct 17, 2026
4df28ce
test(tp): retain verbs load failures in HCA diagnostics
cwschroeder Oct 17, 2026
0a80da0
fix(tp): distinguish verbs load errors from absent HCA ports
cwschroeder Oct 17, 2026
999cb03
Merge stack/03-tp-fabric (adopted #636 runner CLI validation and HCA …
jayleaton Oct 18, 2026
5f14a64
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
749240a
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
7122563
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
6390cf1
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
829c4c9
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
b81382d
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
2be028e
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
e47ed0e
Merge the layer below (adopted #636 runner CLI validation and HCA ver…
jayleaton Oct 18, 2026
cdde1a4
Merge ashhart/main (1.1.0, 76aafcf2) into stack/02-graph-cache-arena
jayleaton Oct 18, 2026
adbdb8a
CUDA launches: a not-ready launch returns NotReady unlogged, as Drive…
jayleaton Oct 18, 2026
3bd6a6a
Merge stack/02-graph-cache-arena (adbdb8ab, main 76aafcf2) into stack…
jayleaton Oct 18, 2026
54141a1
Merge stack/03-tp-fabric (3bd6a6ab, main 76aafcf2) into stack/04-sess…
jayleaton Oct 18, 2026
80d4ed5
Merge stack/04-sessions (54141a1e, main 76aafcf2) into stack/07-server
jayleaton Oct 18, 2026
aebceae
Merge stack/07-server (80d4ed5c, main 76aafcf2) into stack/08a-config
jayleaton Oct 18, 2026
1003f08
Build: DeepSeek-V4.1's host tests on hosts other than Windows, whose …
jayleaton Oct 18, 2026
aa96782
Merge stack/08a-config (1003f08f, main 76aafcf2) into stack/08b-engram
jayleaton Oct 18, 2026
3f758dc
Merge stack/08b-engram (aa967828, main 76aafcf2) into stack/08c-kernels
jayleaton Oct 18, 2026
ea54d42
Merge stack/08c-kernels (3f758dcf, main 76aafcf2) into stack/08e-block
jayleaton Oct 18, 2026
d6190dc
Merge stack/08e-block (ea54d42d, main 76aafcf2) into stack/08r-runtime
jayleaton Oct 18, 2026
6742872
Merge stack/08r-runtime (d6190dcf, main 76aafcf2) into stack/09a-kv
jayleaton Oct 18, 2026
a88da5d
Build: DeepSeek-V4.1's KV host tests also skip Windows, like the fami…
jayleaton Oct 18, 2026
696e58a
Merge stack/09a-kv (a88da5de, main 76aafcf2) into stack/09b-forward
jayleaton Oct 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
TP RoCE: a failed transport halts its QPs, drains them and keeps its …
…region; the region is DONTFORK and NOHUGEPAGE

A local protection error can arrive while the IOMMU invalidates its mappings lazily. On such an error the old path
left the other HCA's QP ready to send (still taking the peer's writes), hung up the fate channel without telling
the peer to stop, and freed the region at once: unregistered from CUDA with no GPU sync, then QP destroy, MR
deregistration and munmap. A device write after the unmap could then reach a reused page through a stale IOTLB entry.

- Roce.fail and Roce.abort (the fail-fast hook) move every QP to the error state: no send goes out and no peer write
  lands.
- Roce.deinit quiesces first: QPs to error, every posted request reaped (flushed or not), cuCtxSynchronize. A failed
  transport, or one that does not quiesce, keeps its region registered and mapped; the process exit tears it down.
- Session.close on a failed transport goes fail-fast before closing, so the peer aborts and halts its HCAs first.
- The region is MADV_DONTFORK and MADV_NOHUGEPAGE before ibv_reg_mr; a refusal fails the start.
- A QP whose actual max_inline_data is under 4 B is refused (the flag post uses lkey 0 on a stack word).
- One log line a rank: region base and length, each HCA's lkey and rkey, the peer's region and rkeys.

Tests: on fake verbs Roce.abort halts both QPs; quiesce halts both before the first flush and reaps every posted write;
an aborted transport reports itself failed, and over the shm wire the aborted rank keeps its region while the other
frees it; smaps shows dc and nh on a prepared region; the inline bound refuses 3 B and takes 4.
  • Loading branch information
jayleaton committed Oct 16, 2026
commit bf19238c00a700755fe5c99702465f9dfe146ce5
42 changes: 42 additions & 0 deletions zig/src/fabric/tp/roce.zig
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ pub const Roce = struct {
r.mapping = try posix.mmap(null, len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .PRIVATE, .ANONYMOUS = true }, -1, 0);
r.region = r.mapping;
errdefer posix.munmap(r.mapping);
try rv.prepareRegion(r.mapping);
r.wire = .{ .verbs = try rv.VerbsWire.open(o.hcas, r.region, .{ .send = send_off, .recv = send_off + 2 * r.slot_bytes, .flags = flag_off, .slot = r.slot_bytes }, o.traffic_class) };
},
.shm => {
Expand All @@ -222,6 +223,8 @@ pub const Roce = struct {
if (all[1 - r.me].len != @sizeOf(rv.Record)) return error.BadRecord;
@memcpy(std.mem.asBytes(&peer), all[1 - r.me]);
try v.connect(peer);
var line: [512]u8 = undefined;
log.info("[tensorfold] tp roce: rank {d} registered {s}", .{ r.me, v.describe(&line) });
return true;
},
}
Expand Down Expand Up @@ -261,14 +264,37 @@ pub const Roce = struct {
posix.munmap(r.mapping);
}

/// Regions a failed transport left registered and mapped (the process exit is their only teardown).
pub var kept: std.atomic.Value(u32) = .init(0);

/// HCAs and GPU quiet, then unregister and unmap; a failed transport's region is kept until exit.
pub fn deinit(r: *Roce) void {
const was_failed = r.failed();
r.word(w_abort).store(1, .release);
r.running.store(false, .release);
if (r.thread) |t| t.join();
const quiet = r.quiesce();
if (was_failed or !quiet) {
const why = if (was_failed) "failed" else "did not quiesce";
log.warn("[tensorfold] tp roce: rank {d}: the transport {s}; region 0x{x} ({d} B) kept registered until exit", .{ r.me, why, @intFromPtr(r.region.ptr), r.region.len });
_ = kept.fetchAdd(1, .monotonic);
return;
}
r.closeDevice();
r.closeWire();
std.heap.page_allocator.destroy(r);
}

/// The QPs to error with every posted request reaped, and the GPU's work on the region done.
fn quiesce(r: *Roce) bool {
const wire = switch (r.wire) {
.verbs => |*v| v.quiesce(rv.quiesce_ns),
.shm => true,
};
const gpu = if (r.d) |d| d.api.cuCtxSynchronize() == cuda.abi.success else true;
return wire and gpu;
}

fn word(r: *const Roce, i: usize) *std.atomic.Value(u32) {
return @ptrCast(@alignCast(r.region[ctrl_off + 4 * i ..].ptr));
}
Expand All @@ -279,6 +305,21 @@ pub const Roce = struct {
log.err("[tensorfold] tp roce proxy: {s}", .{s});
r.word(w_proxy_failed).store(1, .release);
r.word(w_abort).store(1, .release); // waits on this rank end now instead of at the timeout
r.halt();
}

/// The HCAs stop: nothing of this rank's goes out and none of the peer's writes lands while the ranks go down.
fn halt(r: *Roce) void {
switch (r.wire) {
.verbs => |*v| _ = v.halt(),
.shm => {},
}
}

/// The transport failed or was aborted: a device may still write to its region.
pub fn failed(r: *const Roce) bool {
if (r.aborted.load(.acquire) or r.word(w_abort).load(.acquire) != 0) return true;
return r.word(w_proxy_failed).load(.acquire) != 0 or r.word(w_failed).load(.acquire) != 0;
}

/// The proxy loop: spin on the doorbell, post each new sequence (at most two pending), reap while idle, then nap.
Expand Down Expand Up @@ -382,6 +423,7 @@ pub const Roce = struct {
pub fn abort(r: *Roce) void {
r.aborted.store(true, .release);
r.word(w_abort).store(1, .release);
r.halt();
}

pub fn check(r: *Roce) Error!void {
Expand Down
37 changes: 37 additions & 0 deletions zig/src/fabric/tp/roce_fake.zig
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,43 @@ pub const Fake = struct {
}
};

/// QPs that complete nothing on their own: a QP moved to error flushes what it holds, as an HCA reports it.
pub const Halts = struct {
pub var halted: [2]bool = .{ false, false };
pub var flushed_before_halt: u32 = 0;
pub var flushes: u32 = 0;

pub fn reset() void {
halted = .{ false, false };
flushed_before_halt = 0;
flushes = 0;
}

pub fn modifyQp(qp: *abi.Qp, attr: *abi.QpAttr, mask: c_int) callconv(.c) c_int {
if (attr.qp_state == abi.qps_err and mask == abi.mask.state) halted[qp.qp_num] = true;
return 0;
}

pub fn pollCq(cq: *abi.Cq, _: c_int, wc: [*]abi.Wc) callconv(.c) c_int {
const q = cq.handle;
if (Fake.len[q] == 0 or !halted[q]) return 0;
if (!halted[0] or !halted[1]) flushed_before_halt += 1;
Fake.inflight -= Fake.queue[q][Fake.head[q]];
Fake.head[q] = (Fake.head[q] + 1) % 512;
Fake.len[q] -= 1;
flushes += 1;
wc[0] = std.mem.zeroes(abi.Wc);
wc[0].status = 5; // IBV_WC_WR_FLUSH_ERR
return 1;
}

/// Points a wire's QPs at these handlers.
pub fn install(hw: *Hw, w: *rv.VerbsWire) void {
w.v.api.ibv_modify_qp = modifyQp;
for (&hw.ctx) |*c| c.ops.poll_cq = pollCq;
}
};

/// Two fake HCAs behind one VerbsWire, connected to a peer whose region has this rank's layout.
pub const Hw = struct {
ctx: [2]abi.Context = undefined,
Expand Down
74 changes: 74 additions & 0 deletions zig/src/fabric/tp/roce_inflight_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const rv = @import("roce_verbs.zig");
const fake = @import("roce_fake.zig");
const Roce = @import("roce.zig").Roce;
const Fake = fake.Fake;
const Halts = fake.Halts;
const slot = fake.slot;

test "chunked posts: the wire's own in-flight count and peak match the HCAs', and reach the 2 MiB cap" {
Expand All @@ -24,3 +25,76 @@ test "chunked posts: the wire's own in-flight count and peak match the HCAs', an
try std.testing.expectEqual(Fake.max_inflight, w.peak.load(.monotonic));
try std.testing.expectEqual(@as(u64, 2 << 20), w.peak.load(.monotonic));
}

test "a failed transport: both QPs go to error before the first flush and every posted write is reaped" {
const region = try std.testing.allocator.alignedAlloc(u8, .fromByteUnits(4096), Roce.regionBytes(slot));
defer std.testing.allocator.free(region);
@memset(region, 0);
Fake.region = region;
Fake.slot_bytes = slot;
Fake.reset(1);
Halts.reset();
var hw: fake.Hw = .{};
var w = hw.wire(region);
Halts.install(&hw, &w);
// two 1 MiB ops posted, neither completed: 2 MiB in flight at the HCAs
try w.post(1, 1, slot);
try w.post(0, 2, slot);
try std.testing.expectEqual(@as(u64, 2 * slot), w.inflight());
try std.testing.expect(w.quiesce(std.time.ns_per_s));
try std.testing.expect(Halts.halted[0] and Halts.halted[1]);
try std.testing.expectEqual(@as(u32, 0), Halts.flushed_before_halt);
try std.testing.expectEqual(@as(u32, 4), Halts.flushes);
try std.testing.expectEqual(@as(u64, 0), w.inflight());
try std.testing.expectEqual(@as(u64, 0), Fake.inflight);
// an aborted transport reports itself failed: its deinit keeps the region
Halts.reset();
var r: Roce = .{ .me = 0, .slot_bytes = slot, .timeout_ns = 1, .region = region, .mapping = region, .wire = .{ .verbs = w }, .cpu = null };
try std.testing.expect(!r.failed());
r.abort();
try std.testing.expect(Halts.halted[0] and Halts.halted[1]);
try std.testing.expect(r.failed());
}

test "a QP whose inline capacity cannot take the 4-byte flag post is refused" {
try std.testing.expect(!rv.inlineFits(.{ .max_send_wr = 1, .max_recv_wr = 1, .max_send_sge = 1, .max_recv_sge = 1, .max_inline_data = 3 }));
try std.testing.expect(rv.inlineFits(.{ .max_send_wr = 1, .max_recv_wr = 1, .max_send_sge = 1, .max_recv_sge = 1, .max_inline_data = 4 }));
}

/// /proc/self/smaps' VmFlags of the mapping that starts at `at`.
fn vmFlags(at: usize, buf: []u8) ![]const u8 {
const fd = std.c.open("/proc/self/smaps", .{});
if (fd < 0) return error.NoSmaps;
defer _ = std.c.close(fd);
var n: usize = 0;
while (n < buf.len) {
const got = std.c.read(fd, buf[n..].ptr, buf.len - n);
if (got <= 0) break;
n += @intCast(got);
}
var head: [32]u8 = undefined;
const want = try std.fmt.bufPrint(&head, "{x}-", .{at});
var lines = std.mem.splitScalar(u8, buf[0..n], '\n');
var inside = false;
while (lines.next()) |l| {
if (std.mem.startsWith(u8, l, want)) inside = true;
if (inside and std.mem.startsWith(u8, l, "VmFlags:")) return l;
}
return error.NotFound;
}

test "the region is DONTFORK and NOHUGEPAGE before registration" {
if (@import("builtin").os.tag != .linux) return error.SkipZigTest;
const len = Roce.regionBytes(slot);
const m = try std.posix.mmap(null, len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .PRIVATE, .ANONYMOUS = true }, -1, 0);
defer std.posix.munmap(m);
const buf = try std.testing.allocator.alloc(u8, 4 << 20);
defer std.testing.allocator.free(buf);
// smaps: dc = MADV_DONTFORK, nh = MADV_NOHUGEPAGE
const before = try vmFlags(@intFromPtr(m.ptr), buf);
try std.testing.expect(std.mem.indexOf(u8, before, " dc") == null and std.mem.indexOf(u8, before, " nh") == null);
try rv.prepareRegion(m);
const flags = try vmFlags(@intFromPtr(m.ptr), buf);
try std.testing.expect(std.mem.indexOf(u8, flags, " dc") != null);
try std.testing.expect(std.mem.indexOf(u8, flags, " nh") != null);
}
16 changes: 16 additions & 0 deletions zig/src/fabric/tp/roce_post_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,19 @@ test "chunked strides posted back to back: at most 2 MiB in flight over both HCA
try std.testing.expect(Fake.max_inflight > 1 << 20);
}
}

test "Roce.abort (the fail-fast hook) moves both QPs to error: no send goes out and no peer write lands" {
const region = try std.testing.allocator.alignedAlloc(u8, .fromByteUnits(4096), Roce.regionBytes(fake.slot));
defer std.testing.allocator.free(region);
@memset(region, 0);
Fake.region = region;
Fake.slot_bytes = fake.slot;
Fake.reset(1);
fake.Halts.reset();
var hw: fake.Hw = .{};
var w = hw.wire(region);
fake.Halts.install(&hw, &w);
var r: Roce = .{ .me = 0, .slot_bytes = fake.slot, .timeout_ns = 1, .region = region, .mapping = region, .wire = .{ .verbs = w }, .cpu = null };
r.abort();
try std.testing.expect(fake.Halts.halted[0] and fake.Halts.halted[1]);
}
3 changes: 3 additions & 0 deletions zig/src/fabric/tp/roce_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,10 @@ test "a peer that stops makes the waiting rank time out, and abort ends a wait a
try std.testing.expectEqual(@as(?anyerror, error.Timeout), run.errs[0]);
try std.testing.expectEqual(@as(u32, 20), run.done[0]);
var run2: Run = .{ .port = 0, .wire = .shm, .ops = 50, .stop_after = 20, .abort_after_ms = 50 };
const kept = roce.Roce.kept.load(.monotonic);
try twoRanks(&run2);
// the aborted rank keeps its region until exit, the other frees it
try std.testing.expectEqual(kept + 1, roce.Roce.kept.load(.monotonic));
try std.testing.expectEqual(@as(?anyerror, error.Aborted), run2.errs[0]);
try std.testing.expectEqual(@as(?anyerror, null), run2.errs[1]);
}
Expand Down
66 changes: 63 additions & 3 deletions zig/src/fabric/tp/roce_verbs.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ pub const max_inflight: u64 = 2 * @as(u64, guard.max_write);
/// A post that waits on completions this long fails the proxy (a peer or HCA that stopped answering).
const inflight_wait_ns: u64 = 10 * std.time.ns_per_s;
const ring_len = send_depth / 4;
/// The flag post's bytes: a u32 on the stack under lkey 0, legal only while the QP sends it inline.
pub const flag_bytes: u32 = @sizeOf(u32);
/// The longest `quiesce` waits for the HCAs to flush what was posted.
pub const quiesce_ns: u64 = 5 * std.time.ns_per_s;

/// Before ibv_reg_mr: no fork shares or copies the region (DONTFORK), its pages stay 4 KiB (NOHUGEPAGE); else no start.
pub fn prepareRegion(region: []align(std.heap.page_size_min) u8) Error!void {
if (comptime @import("builtin").os.tag != .linux) return; // the verbs wire runs on Linux only
const advice = [_]u32{ std.os.linux.MADV.DONTFORK, std.os.linux.MADV.NOHUGEPAGE };
for (advice) |a| std.posix.madvise(region.ptr, region.len, a) catch |e| {
log.warn("tp roce: madvise({d}) on the {d} B region failed: {t}; refusing to start", .{ a, region.len, e });
return error.VerbsFailed;
};
}

/// Whether a QP's actual inline capacity takes the flag post.
pub fn inlineFits(cap: abi.QpCap) bool {
return cap.max_inline_data >= flag_bytes;
}

/// One HCA as configured: its device name and RoCE v2 GID index (null: detected).
pub const HcaSpec = struct { name: [64]u8 = @splat(0), name_len: u8 = 0, gid: ?u8 = null };
Expand Down Expand Up @@ -190,6 +209,10 @@ pub const VerbsWire = struct {
var init: abi.QpInitAttr = .{ .send_cq = cq, .recv_cq = cq, .cap = .{ .max_send_wr = send_depth, .max_recv_wr = 1, .max_send_sge = 1, .max_recv_sge = 1, .max_inline_data = 16 }, .qp_type = abi.qpt_rc };
const qp = api.ibv_create_qp(pd, &init) orelse return error.VerbsFailed;
errdefer _ = api.ibv_destroy_qp(qp);
if (!inlineFits(init.cap)) {
log.warn("tp roce: {s}'s QP sends {d} B inline, the flag post needs {d}; refusing to start", .{ name, init.cap.max_inline_data, flag_bytes });
return error.VerbsFailed;
}
var a: abi.QpAttr = .{ .qp_state = abi.qps_init, .port_num = 1, .qp_access_flags = abi.access_remote_write };
if (api.ibv_modify_qp(qp, &a, abi.mask.state | abi.mask.pkey_index | abi.mask.port | abi.mask.access_flags) != 0) return error.VerbsFailed;
w.hcas[w.n_hca] = .{ .ctx = ctx, .pd = pd, .mr = mr, .cq = cq, .qp = qp, .gid_index = gi, .gid = gid.raw, .mtu = @intCast(port.active_mtu), .lid = port.lid };
Expand All @@ -210,6 +233,39 @@ pub const VerbsWire = struct {
w.v.close();
}

/// The region and each HCA's keys, this side's and the peer's (a protection error is checked against them).
pub fn describe(w: *const VerbsWire, buf: []u8) []const u8 {
var out: std.Io.Writer = .fixed(buf);
out.print("region 0x{x} len {d}", .{ @intFromPtr(w.region.ptr), w.region.len }) catch return out.buffered();
for (w.hcas[0..w.n_hca], 0..) |h, i| {
out.print("; HCA {d} lkey 0x{x} rkey 0x{x}, peer region 0x{x} rkey 0x{x}", .{ i, h.mr.lkey, h.mr.rkey, w.peer_region, w.peer_rkey[i] }) catch break;
}
return out.buffered();
}

/// The QPs to error: the HCAs stop sending and refuse the peer's writes, and what was posted completes as flushed.
pub fn halt(w: *VerbsWire) bool {
var ok = true;
for (w.hcas[0..w.n_hca]) |h| {
var a: abi.QpAttr = .{ .qp_state = abi.qps_err };
if (w.v.api.ibv_modify_qp(h.qp, &a, abi.mask.state) != 0) ok = false;
}
return ok;
}

/// `halt`, then every posted request's completion reaped, flushed or not: no request of the region left at an HCA.
pub fn quiesce(w: *VerbsWire, timeout_ns: u64) bool {
if (!w.halt()) return false;
const t0 = sock.nowNs();
for (w.hcas[0..w.n_hca]) |*h| while (h.outstanding > 0) {
var wc: [32]abi.Wc = undefined;
const n = h.ctx.ops.poll_cq(h.cq, 32, &wc);
if (n < 0) return false;
if (n > 0) w.popped(h, @intCast(n)) else if (sock.nowNs() - t0 > timeout_ns) return false;
};
return true;
}

pub fn record(w: *const VerbsWire) Record {
var r: Record = .{ .n_hca = w.n_hca, .region = @intFromPtr(w.region.ptr), .slot_bytes = w.slot_bytes, .region_len = w.region.len };
for (w.hcas[0..w.n_hca], 0..) |h, i| {
Expand Down Expand Up @@ -292,12 +348,16 @@ pub const VerbsWire = struct {
log.err("tp roce: RDMA write of seq {d} failed: {s} (vendor 0x{x})", .{ c.wr_id, w.v.statusText(c.status), c.vendor_err });
return error.Completion;
};
for (0..@intCast(n)) |_| {
w.popped(h, @intCast(n));
}

fn popped(w: *VerbsWire, h: *Hca, n: u32) void {
for (0..n) |_| {
h.inflight -= h.ring[h.head];
h.head = (h.head + 1) % ring_len;
}
h.outstanding -= @intCast(n);
w.completed += @intCast(n);
h.outstanding -= n;
w.completed += n;
}

/// Bytes posted and not yet completed over every HCA.
Expand Down
2 changes: 2 additions & 0 deletions zig/src/fabric/tp/tp.zig
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ pub const Session = struct {

/// A normal stop: every rank calls it (rank 0 first marks the stop as expected with `fate.expectStop`).
pub fn close(s: *Session) void {
// a failed transport: every rank goes down (the peers stop posting) before this one lets go of anything
if (s.roce) |r| if (r.failed()) if (s.fate) |*f| f.fatal("transport", error.BackendFailed);
if (s.fate) |*f| f.close();
s.plan.close();
if (s.roce) |r| r.deinit();
Expand Down