Phase 5: atomics through every layer (RFC 0015)
AIR: linear atomic<T> (AtomicScalar), atomic.new/take/load/store/RMW/ cmpxchg (two results)/fence with explicit orderings; feature atomics published. Verifier: ordering tables (E4201), ordinary access (E4202), effects [atomic] / [atomic, atomic.weak], linearity, take while lent (E4101, also for mutex.take). Interpreter: timestamped message machine (src/interp/weak.zig); views travel through spawn/join, channels, mutexes, close and cancel; seq_cst reads the latest message and programs without weak reads make no extra draw (existing records unchanged). aji explore: exhaustive exploration that branches only before visible operations. Litmus: 20/20 tests give exactly the oracle's sets; differential test (1500 random programs) found no unsound outcome. .aji layer 10, Quick Reference atomics, source coverage 67/67, audit report atomic_operations. AIR bundle +5.9 %, QUICK.md +0.5k.
This commit is contained in:
1 parent
ce9ef03bc0
commit
4242132b2a
70 files changed
+2630
-80
No files matched your search
+312
-34
@@ -27,6 +27,7 @@ const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
const host_mod = @import("host.zig");
|
||||
const budget = @import("../verifier/budget.zig");
|
||||
const weak = @import("weak.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
@@ -72,10 +73,17 @@ pub const Value = union(enum) {
|
||||
graph: *Graph,
|
||||
/// `iref<T>`: graph identity and slot; opaque to programs.
|
||||
iref: struct { id: u64, slot: u32 },
|
||||
/// `atomic<T>`: index into the machine's atomic cells (spec 04 §42).
|
||||
atomic: u32,
|
||||
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
pub const MutexCell = struct { locked: bool, cell: *Cell };
|
||||
pub const MutexCell = struct {
|
||||
locked: bool,
|
||||
cell: *Cell,
|
||||
/// The view of the last unlock (spec 04 §20.3: unlock → next lock).
|
||||
view: weak.View = .{},
|
||||
};
|
||||
|
||||
/// A graph: object cells addressed by slot, an identity never reused in
|
||||
/// the execution, the authority it charges and the bytes it holds.
|
||||
@@ -197,6 +205,9 @@ pub const Options = struct {
|
||||
quantum: u64 = 1000,
|
||||
task_limit: u64 = 1024,
|
||||
schedule_seed: ?u64 = null,
|
||||
/// Exhaustive exploration: choices come from `Explore` instead of the
|
||||
/// schedule generator (spec 04 §20.5).
|
||||
explore: ?*Explore = null,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
@@ -262,6 +273,8 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
m.arc_events = options.arc_events;
|
||||
m.explore = options.explore;
|
||||
m.mem.weak_reads = hasWeakReads(module);
|
||||
if (options.collect_threshold) |t| {
|
||||
m.exec_heap.floor = t;
|
||||
m.exec_heap.threshold = t;
|
||||
@@ -282,6 +295,31 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Operations whose order between tasks can change an outcome: atomic
|
||||
/// memory operations and the synchronization of channels, mutexes and
|
||||
/// cancellation. `task.spawn` and `task.join` commute with them.
|
||||
fn isVisibleOp(op: air.Op) bool {
|
||||
return switch (op) {
|
||||
.atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => true,
|
||||
.channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => true,
|
||||
.mutex_lock, .mutex_unlock => true,
|
||||
.task_cancel, .task_cancelled, .task_check_cancel, .task_join_cancel => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether a read may read an older message: a non-`seq_cst` load or
|
||||
/// compare-exchange failure (spec 04 §42). Without one, cells keep only their
|
||||
/// latest message.
|
||||
fn hasWeakReads(module: air.Module) bool {
|
||||
for (module.functions) |f| for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
|
||||
.atomic_load => |x| if (x.ord != .seq_cst) return true,
|
||||
.atomic_cmpxchg => |x| if (x.failure != .seq_cst) return true,
|
||||
else => {},
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Copies values into another heap, preserving sharing: a cell, a mutex or
|
||||
/// a payload reached twice is copied once.
|
||||
const Copier = struct {
|
||||
@@ -303,7 +341,7 @@ const Copier = struct {
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
.guard => |mc| .{ .guard = try c.mutex(mc) },
|
||||
.graph => |g| .{ .graph = try c.graph(g) },
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref, .atomic => v,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -332,7 +370,7 @@ const Copier = struct {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
try c.mutexes.put(c.tmp, old, n);
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell) };
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell), .view = try old.view.copy(c.to) };
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -403,13 +441,18 @@ pub const Wait = union(enum) {
|
||||
|
||||
/// A rendezvous offer: a task waiting to send or receive on a capacity-0
|
||||
/// channel, in arm `arm` of its instruction (0 outside `select`).
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void };
|
||||
const Offer = struct { task: u32, arm: u32, value: Value = .void, view: weak.View = .{} };
|
||||
|
||||
/// A channel (spec 04 §38.3).
|
||||
const Channel = struct {
|
||||
capacity: u64,
|
||||
buf: std.ArrayList(Value) = .empty,
|
||||
/// The sender's view of each buffered value (spec 04 §20.3: send → the
|
||||
/// receive that obtains the value). Parallel to `buf`.
|
||||
views: std.ArrayList(weak.View) = .empty,
|
||||
head: usize = 0,
|
||||
/// Joined views of the senders' closes (close → the `closed` outcome).
|
||||
close_view: weak.View = .{},
|
||||
senders: u64 = 1,
|
||||
receiver: enum { open, closing, closed } = .open,
|
||||
authority: u32,
|
||||
@@ -445,7 +488,21 @@ const Task = struct {
|
||||
/// Shield depth (spec 04 §37.3).
|
||||
shield: u32 = 0,
|
||||
/// Set by a peer that completed a rendezvous against this waiting task.
|
||||
delivered: ?struct { arm: u32, value: Value } = null,
|
||||
delivered: ?struct { arm: u32, value: Value, view: weak.View = .{} } = null,
|
||||
/// Weak-memory views (spec 04 §42).
|
||||
views: weak.TaskViews = .{},
|
||||
/// Joined views of the cancellers (cancel → the `cancelled` outcome).
|
||||
cancel_view: weak.View = .{},
|
||||
/// Exploration: the scheduler already chose this task to perform the
|
||||
/// atomic operation it is at.
|
||||
chosen: bool = false,
|
||||
};
|
||||
|
||||
/// Exhaustive exploration (spec 04 §20.5): replays a prefix of choices,
|
||||
/// then takes choice 0, and records the number of options at every choice.
|
||||
pub const Explore = struct {
|
||||
prefix: []const u32 = &.{},
|
||||
widths: std.ArrayList(u32) = .empty,
|
||||
};
|
||||
|
||||
/// Execution heap: collected between instructions (see the file comment).
|
||||
@@ -490,6 +547,9 @@ const Machine = struct {
|
||||
drew: bool = false,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
/// Atomic cells and the `seq_cst` view (spec 04 §42).
|
||||
mem: weak.Memory = .{},
|
||||
explore: ?*Explore = null,
|
||||
|
||||
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
|
||||
|
||||
@@ -511,6 +571,16 @@ const Machine = struct {
|
||||
const b = f.blocks[frame.block];
|
||||
const inst = b.insts[frame.inst];
|
||||
const here: Location = .{ .function = f.name, .block = b.name, .inst = frame.inst };
|
||||
// Exploration branches only before visible operations: what a
|
||||
// task does between two of them is local to it and commutes with
|
||||
// every other task (spec 04 §20.5). The task parks there; the
|
||||
// scheduler chooses once every runnable task is parked.
|
||||
if (m.explore != null and isVisibleOp(inst.op) and !t.chosen) {
|
||||
t.chosen = true;
|
||||
if (try m.schedule()) |o| return o;
|
||||
continue;
|
||||
}
|
||||
t.chosen = false;
|
||||
// Fuel is consumed when an instruction begins (spec 11 §7.1); a
|
||||
// blocked instruction paid when it first began (spec 04 §36.3).
|
||||
if (!t.fuel_paid) {
|
||||
@@ -588,20 +658,40 @@ const Machine = struct {
|
||||
for (m.tasks.items) |*t| {
|
||||
for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals);
|
||||
t.result = try c.value(t.result);
|
||||
if (t.delivered) |*d| d.value = try c.value(d.value);
|
||||
if (t.delivered) |*d| {
|
||||
d.value = try c.value(d.value);
|
||||
d.view = try d.view.copy(c.to);
|
||||
}
|
||||
t.views = try t.views.copy(c.to);
|
||||
t.cancel_view = try t.cancel_view.copy(c.to);
|
||||
}
|
||||
for (m.channels.items) |*ch| {
|
||||
var buf: std.ArrayList(Value) = .empty;
|
||||
try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head);
|
||||
for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v));
|
||||
var views: std.ArrayList(weak.View) = .empty;
|
||||
try views.ensureTotalCapacity(c.to, ch.views.items.len - ch.head);
|
||||
for (ch.views.items[ch.head..]) |v| views.appendAssumeCapacity(try v.copy(c.to));
|
||||
ch.buf = buf;
|
||||
ch.views = views;
|
||||
ch.head = 0;
|
||||
ch.close_view = try ch.close_view.copy(c.to);
|
||||
var offers: std.ArrayList(Offer) = .empty;
|
||||
try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len);
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value) });
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value), .view = try o.view.copy(c.to) });
|
||||
ch.send_offers = offers;
|
||||
if (ch.recv_offer) |*o| o.value = try c.value(o.value);
|
||||
if (ch.recv_offer) |*o| {
|
||||
o.value = try c.value(o.value);
|
||||
o.view = try o.view.copy(c.to);
|
||||
}
|
||||
}
|
||||
// Atomic messages no live task can read any more are dropped.
|
||||
const floor = try tmp.allocator().alloc(u64, m.mem.cells.items.len);
|
||||
@memset(floor, std.math.maxInt(u64));
|
||||
for (m.tasks.items) |t| if (t.state != .done) for (floor, 0..) |*fl, i| {
|
||||
fl.* = @min(fl.*, t.views.cur.get(@intCast(i)));
|
||||
};
|
||||
try m.mem.compact(c.to, floor);
|
||||
var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty;
|
||||
try owners.ensureTotalCapacity(c.to, m.owners.count());
|
||||
var it = m.owners.iterator();
|
||||
@@ -660,12 +750,35 @@ const Machine = struct {
|
||||
m.current = runnable.items[0]; // no choice to make: no draw
|
||||
return null;
|
||||
}
|
||||
const x = m.sched.next();
|
||||
m.choices += 1;
|
||||
m.current = runnable.items[x % runnable.items.len];
|
||||
// Exploration: tasks with local work run first, without a choice.
|
||||
if (m.explore != null) for (runnable.items) |id| if (!m.tasks.items[id].chosen) {
|
||||
m.current = id;
|
||||
return null;
|
||||
};
|
||||
m.current = runnable.items[try m.choose(runnable.items.len)];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Exhaustive exploration does not branch after `task.spawn` and a
|
||||
/// completed `task.join`: they commute with every operation of every
|
||||
/// other task, so branching there would only repeat outcomes. Ordinary
|
||||
/// runs keep them as scheduling points (spec 04 §36.1).
|
||||
fn yieldUnlessExploring(m: *Machine) Step {
|
||||
return if (m.explore != null) .next else .yield;
|
||||
}
|
||||
|
||||
/// One choice among `n > 1` options (spec 04 §36.2): a draw from the
|
||||
/// schedule generator, or the next choice of an exhaustive exploration.
|
||||
fn choose(m: *Machine, n: usize) !usize {
|
||||
m.choices += 1;
|
||||
if (m.explore) |e| {
|
||||
const i = e.widths.items.len;
|
||||
try e.widths.append(m.arena, @intCast(n));
|
||||
return if (i < e.prefix.len) e.prefix[i] else 0;
|
||||
}
|
||||
return m.sched.next() % n;
|
||||
}
|
||||
|
||||
const Step = union(enum) {
|
||||
next,
|
||||
jump: u32,
|
||||
@@ -769,25 +882,33 @@ const Machine = struct {
|
||||
m.live_tasks += 1;
|
||||
m.spawned = true;
|
||||
const id: u32 = @intCast(m.tasks.items.len);
|
||||
try m.tasks.append(m.arena, .{});
|
||||
// spawn → the child's first event (spec 04 §20.3).
|
||||
const parent = m.tasks.items[m.current].views.cur;
|
||||
try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } });
|
||||
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
|
||||
vals[inst.result.?] = .{ .task = id };
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_join => |v| {
|
||||
const id = vals[v].task;
|
||||
const t = m.tasks.items[id];
|
||||
if (t.state != .done) return .{ .wait = .{ .join = id } };
|
||||
m.live_tasks -= 1;
|
||||
// The child's last event → join (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(t.views.cur, m.heap());
|
||||
if (inst.result) |r| vals[r] = t.result;
|
||||
return .yield;
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.task_cancel => |v| {
|
||||
m.tasks.items[vals[v].task].cancel = true;
|
||||
const target = &m.tasks.items[vals[v].task];
|
||||
target.cancel = true;
|
||||
target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap());
|
||||
return .yield;
|
||||
},
|
||||
.task_cancelled => {
|
||||
vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel };
|
||||
const cancelled = m.tasks.items[m.current].cancel;
|
||||
if (cancelled) try m.observeCancel();
|
||||
vals[inst.result.?] = .{ .boolean = cancelled };
|
||||
return .yield;
|
||||
},
|
||||
.task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst),
|
||||
@@ -795,6 +916,7 @@ const Machine = struct {
|
||||
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
|
||||
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
|
||||
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst),
|
||||
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
|
||||
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
|
||||
.trap => return .{ .trap = .explicit },
|
||||
@@ -869,33 +991,52 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
/// Completes the peer of a rendezvous: it resumes on arm `arm`.
|
||||
fn deliver(m: *Machine, o: Offer, value: Value) void {
|
||||
fn deliver(m: *Machine, o: Offer, value: Value, view: weak.View) void {
|
||||
m.removeOffers(o.task);
|
||||
const t = &m.tasks.items[o.task];
|
||||
t.delivered = .{ .arm = o.arm, .value = value };
|
||||
t.delivered = .{ .arm = o.arm, .value = value, .view = view };
|
||||
if (t.state == .waiting) t.state = .runnable;
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready send.
|
||||
/// The sender's view travels with the value (spec 04 §20.3).
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
const view = m.tasks.items[m.current].views.cur;
|
||||
if (c.capacity > 0) {
|
||||
try c.views.append(m.heap(), view);
|
||||
return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
}
|
||||
const o = c.recv_offer.?;
|
||||
m.deliver(o, try m.deepCopy(v));
|
||||
m.deliver(o, try m.deepCopy(v), view);
|
||||
}
|
||||
|
||||
/// Performs an `ok`-ready receive.
|
||||
fn doRecv(m: *Machine, id: u32) Value {
|
||||
fn doRecv(m: *Machine, id: u32) !Value {
|
||||
const c = &m.channels.items[id];
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
if (c.buffered() > 0) {
|
||||
c.head += 1;
|
||||
try views.acquire(c.views.items[c.head - 1], m.heap());
|
||||
return c.buf.items[c.head - 1];
|
||||
}
|
||||
const o = c.send_offers.orderedRemove(0);
|
||||
m.deliver(o, .void);
|
||||
m.deliver(o, .void, .{});
|
||||
try views.acquire(o.view, m.heap());
|
||||
return o.value;
|
||||
}
|
||||
|
||||
/// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3).
|
||||
fn observeCancel(m: *Machine) !void {
|
||||
const t = &m.tasks.items[m.current];
|
||||
try t.views.acquire(t.cancel_view, m.heap());
|
||||
}
|
||||
|
||||
/// The `closed` outcome of a receive synchronizes with the closes.
|
||||
fn observeClose(m: *Machine, id: u32) !void {
|
||||
try m.tasks.items[m.current].views.acquire(m.channels.items[id].close_view, m.heap());
|
||||
}
|
||||
|
||||
/// Returns the channel's bytes once it is `CLOSED` with no sender.
|
||||
fn maybeRelease(m: *Machine, id: u32) void {
|
||||
const c = &m.channels.items[id];
|
||||
@@ -911,15 +1052,21 @@ const Machine = struct {
|
||||
fn execCancellation(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
const t = &m.tasks.items[m.current];
|
||||
switch (inst.op) {
|
||||
.task_check_cancel => |x| return .{ .jump_yield = if (cancelObservable(t)) x.cancelled else x.ok },
|
||||
.task_check_cancel => |x| {
|
||||
if (!cancelObservable(t)) return .{ .jump_yield = x.ok };
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
},
|
||||
.task_join_cancel => |x| {
|
||||
const child = vals[x.task].task;
|
||||
if (m.tasks.items[child].state == .done) {
|
||||
m.live_tasks -= 1;
|
||||
try t.views.acquire(m.tasks.items[child].views.cur, m.heap());
|
||||
setParams(f, vals, x.ok, &.{m.tasks.items[child].result});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{vals[x.task]});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -958,7 +1105,9 @@ const Machine = struct {
|
||||
},
|
||||
.channel_close_sender => |v| {
|
||||
const id = vals[v].sender;
|
||||
m.channels.items[id].senders -= 1;
|
||||
const ch = &m.channels.items[id];
|
||||
ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap());
|
||||
ch.senders -= 1;
|
||||
m.maybeRelease(id);
|
||||
return .yield;
|
||||
},
|
||||
@@ -994,11 +1143,12 @@ const Machine = struct {
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, &.{v});
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v });
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v, .view = t.views.cur });
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
}
|
||||
@@ -1007,6 +1157,7 @@ const Machine = struct {
|
||||
const t = &m.tasks.items[self];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{d.value});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
@@ -1014,12 +1165,18 @@ const Machine = struct {
|
||||
const id = endpointOf(vals[x.receiver]);
|
||||
switch (m.recvState(id)) {
|
||||
.ok => {
|
||||
setParams(f, vals, x.ok, &.{m.doRecv(id)});
|
||||
setParams(f, vals, x.ok, &.{try m.doRecv(id)});
|
||||
return .{ .jump_yield = x.ok };
|
||||
},
|
||||
.closed => return .{ .jump_yield = x.closed },
|
||||
.closed => {
|
||||
try m.observeClose(id);
|
||||
return .{ .jump_yield = x.closed };
|
||||
},
|
||||
.none => {
|
||||
if (cancelObservable(t)) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) c.recv_offer = .{ .task = self, .arm = 0 };
|
||||
return .{ .wait = .op };
|
||||
@@ -1041,6 +1198,7 @@ const Machine = struct {
|
||||
for (vs, v_vals) |v, *o| o.* = vals[v];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
try t.views.acquire(d.view, m.heap());
|
||||
return m.selectOk(f, vals, x, d.arm, d.value, vs, v_vals);
|
||||
}
|
||||
m.removeOffers(self);
|
||||
@@ -1052,6 +1210,7 @@ const Machine = struct {
|
||||
}
|
||||
if (ready_arms.items.len == 0) {
|
||||
if (cancelObservable(t)) {
|
||||
try m.observeCancel();
|
||||
setParams(f, vals, x.cancelled, v_vals);
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
@@ -1059,21 +1218,21 @@ const Machine = struct {
|
||||
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
|
||||
if (c.capacity != 0) continue;
|
||||
if (arm.value) |v| {
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v], .view = t.views.cur });
|
||||
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
}
|
||||
var pick: usize = 0;
|
||||
if (ready_arms.items.len > 1) {
|
||||
pick = m.sched.next() % ready_arms.items.len;
|
||||
m.choices += 1;
|
||||
pick = try m.choose(ready_arms.items.len);
|
||||
m.drew = true;
|
||||
}
|
||||
const arm_i, const st = ready_arms.items[pick];
|
||||
const arm = x.arms[arm_i];
|
||||
const ch = endpointOf(vals[arm.endpoint]);
|
||||
if (st == .closed) {
|
||||
if (arm.value == null) try m.observeClose(ch);
|
||||
setParams(f, vals, arm.closed, v_vals);
|
||||
return .{ .jump_yield = arm.closed };
|
||||
}
|
||||
@@ -1081,7 +1240,7 @@ const Machine = struct {
|
||||
try m.doSend(ch, vals[v]);
|
||||
return m.selectOk(f, vals, x, arm_i, .void, vs, v_vals);
|
||||
}
|
||||
return m.selectOk(f, vals, x, arm_i, m.doRecv(ch), vs, v_vals);
|
||||
return m.selectOk(f, vals, x, arm_i, try m.doRecv(ch), vs, v_vals);
|
||||
}
|
||||
|
||||
/// Continues at the `ok` target of arm `i`: the received value (for a
|
||||
@@ -1109,21 +1268,140 @@ const Machine = struct {
|
||||
const mc = mutexOf(vals[x.mutex]);
|
||||
if (!mc.locked) {
|
||||
mc.locked = true;
|
||||
// unlock → the next lock (spec 04 §20.3).
|
||||
try m.tasks.items[m.current].views.acquire(mc.view, m.heap());
|
||||
setParams(f, vals, x.ok, &.{.{ .guard = mc }});
|
||||
return .{ .jump_yield = x.ok };
|
||||
}
|
||||
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
|
||||
if (cancelObservable(&m.tasks.items[m.current])) {
|
||||
try m.observeCancel();
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
vals[g].guard.view = m.tasks.items[m.current].views.cur;
|
||||
return .yield;
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ atomics (spec 04 §20–§30, §42)
|
||||
|
||||
fn cellOf(v: Value) u32 {
|
||||
return switch (v) {
|
||||
.atomic => |id| id,
|
||||
.place => |p| cellOf(placePtr(p).*),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarBits(v: Value) u128 {
|
||||
return switch (v) {
|
||||
.int => |x| x.bits,
|
||||
.boolean => |b| @intFromBool(b),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn scalarValue(ty: air.Type, bits: u128) Value {
|
||||
return switch (ty) {
|
||||
.int => |it| .{ .int = .{ .ty = it, .bits = bits } },
|
||||
.bool => .{ .boolean = bits != 0 },
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
/// A weak-memory choice among `n` readable messages (spec 04 §42).
|
||||
fn weakChoice(m: *Machine, n: u64) !u64 {
|
||||
if (n == 1) return 0;
|
||||
m.drew = true;
|
||||
return try m.choose(@intCast(n));
|
||||
}
|
||||
|
||||
fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step {
|
||||
const gpa = m.heap();
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
switch (inst.op) {
|
||||
.atomic_new => |v| {
|
||||
const ty: air.Type = switch (vals[v]) {
|
||||
.int => |x| .{ .int = x.ty },
|
||||
else => .bool,
|
||||
};
|
||||
return bind(vals, inst.result, .{ .atomic = try m.mem.create(gpa, m.arena, ty, scalarBits(vals[v])) });
|
||||
},
|
||||
.atomic_take => |v| {
|
||||
const c = &m.mem.cells.items[vals[v].atomic];
|
||||
const value = scalarValue(c.ty, c.at(c.latest()).bits);
|
||||
c.taken = true;
|
||||
return bind(vals, inst.result, value);
|
||||
},
|
||||
.atomic_load => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const first, const last = m.mem.readRange(views, id, x.ord);
|
||||
const ts = first + try m.weakChoice(last - first + 1);
|
||||
const bits = try m.mem.read(gpa, views, id, ts, x.ord);
|
||||
vals[inst.result.?] = scalarValue(m.mem.cells.items[id].ty, bits);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_store => |x| {
|
||||
try m.mem.write(gpa, views, cellOf(vals[x.cell]), scalarBits(vals[x.value]), x.ord, .{});
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_rmw => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const ty = m.mem.cells.items[id].ty;
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.ord);
|
||||
const operand = scalarBits(vals[x.value]);
|
||||
const new: u128 = switch (x.op) {
|
||||
.xchg => operand,
|
||||
.add_wrap => arith(.add, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.sub_wrap => arith(.sub, .wrap, ty.int, old, operand) catch unreachable,
|
||||
.@"and" => old & operand,
|
||||
.@"or" => old | operand,
|
||||
.xor => old ^ operand,
|
||||
};
|
||||
try m.mem.write(gpa, views, id, new, x.ord, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_cmpxchg => |x| {
|
||||
const id = cellOf(vals[x.cell]);
|
||||
const c = &m.mem.cells.items[id];
|
||||
const expected = scalarBits(vals[x.expected]);
|
||||
// Readable messages: the latest (a success when it equals
|
||||
// the expected value), and older ones that differ from it
|
||||
// (failures; a strong CAS cannot fail on an equal value).
|
||||
const first, const last = m.mem.readRange(views, id, x.failure);
|
||||
var options: std.ArrayList(u64) = .empty;
|
||||
var ts = first;
|
||||
while (ts < last) : (ts += 1) if (c.at(ts).bits != expected) try options.append(gpa, ts);
|
||||
try options.append(gpa, c.latest());
|
||||
const pick = options.items[@intCast(try m.weakChoice(options.items.len))];
|
||||
const ty = c.ty;
|
||||
if (pick == c.latest() and c.at(pick).bits == expected) {
|
||||
const old, const carried = try m.mem.rmwRead(gpa, views, id, x.success);
|
||||
try m.mem.write(gpa, views, id, scalarBits(vals[x.desired]), x.success, carried);
|
||||
vals[inst.result.?] = scalarValue(ty, old);
|
||||
vals[inst.result2.?] = .{ .boolean = true };
|
||||
} else {
|
||||
const bits = try m.mem.read(gpa, views, id, pick, x.failure);
|
||||
vals[inst.result.?] = scalarValue(ty, bits);
|
||||
vals[inst.result2.?] = .{ .boolean = false };
|
||||
}
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
.atomic_fence => |o| {
|
||||
try m.mem.fence(gpa, views, o);
|
||||
return m.yieldUnlessExploring();
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
fn mutexOf(v: Value) *Value.MutexCell {
|
||||
return switch (v) {
|
||||
.mutex => |mc| mc,
|
||||
@@ -1857,7 +2135,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
},
|
||||
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
|
||||
.local, .place, .slice => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
|
||||
Reference in new issue
Block a user