//! Whose turn it is with the core. The core is single-threaded: the editor's //! thread has it, and lets go of it in two kinds of gap -- while it waits for //! input (`rest`, `wake`), and while it is out in the host filesystem in the //! middle of a step (`yield`, `back`). A 9P connection task takes the turn //! in those gaps to answer a request (`take`, `give`), which is what lets the //! editor read its own tree through a mount: the syscall goes out, another //! thread answers it, the syscall comes back. A step of a connection task's //! own -- a Look written to `look` -- goes out the same way. //! //! `out` counts the steps that are out. While one is, the core reads //! consistently but that step still holds pointers into it, so nothing may //! change it: a request that would is parked in the engine (runtime/9p_io.zig) //! and retried when the turn is next given up with nothing out, which //! `parked` remembers to arrange; and the editor's own wake waits for the //! count to reach zero, since a step of the editor's may change anything. //! It is never a write of its own that a step waits on out there -- writes //! come from a shell performing a save between steps -- so a parked request //! is never the syscall's own. const std = @import("std"); const Turn = @This(); mutex: std.Io.Mutex = .init, /// Set by `start`; a process that never starts the turn has none. io: ?std.Io = null, /// Steps out in a host syscall, from any thread. out: u32 = 0, /// A request that changes a pane was parked for want of quiet. parked: bool = false, wake_parked: ?*const fn (?*anyopaque) void = null, /// Answers the reads the core holds, with the turn, as it is given up. answer_held: ?*const fn (?*anyopaque) void = null, wake_ctx: ?*anyopaque = null, /// Bumped each time the editor has performed what the core asked of it, /// so a request that asked for something -- a save, a shell -- can be /// answered once it is done rather than merely queued, the way writing /// `put` to acme's ctl returns after the file is written. epoch: u64 = 0, /// Bumped each time a shell has attempted the Restore the core asked for /// (`takeRestore`), which lives after `pump` because it swaps the core /// out from under it; a request that asked for one waits for this. restores: u64 = 0, /// Bumped each time a language server's answer (or its lack) is taken /// in (`lspResponse`): a write that asked one waits for this. lsp_answers: u64 = 0, /// Reads out of the ptys (a pane's reader, as it reads) and those applied /// or dropped since (`outputApplied`): a write waits for the output read /// before it (`awaitOutput`). reads: std.atomic.Value(u64) = .init(0), applied: std.atomic.Value(u64) = .init(0), /// The editor gave the turn up to wait for input (`listen`), not for a /// call of its own (`rest`, `yield`: a save through its own mount, whose /// write it would never answer applying output meanwhile). listening: bool = false, /// All of the above, and `out` reaching zero. settled: std.Io.Condition = .init, /// Every `yield`, ever: a replica's step makes none (each syscall of its /// core is a tape site), which its tape checks by this count across a /// speculation and a replayed input (core/tape.zig `stray`). yields: u64 = 0, /// The editor's thread takes the turn for good; it has it until `stop`. pub fn start(t: *Turn, io: std.Io) void { t.io = io; t.mutex.lockUncancelable(io); } pub fn stop(t: *Turn) void { const io = t.io orelse return; t.io = null; t.parked = false; t.mutex.unlock(io); } /// The editor is about to wait for input: anyone may have the core. pub fn rest(t: *Turn) void { if (t.io == null) return; t.release(); } /// The editor is about to wait for input, the output its readers read /// among it (its loop's wait): `rest`, and a write may wait for that /// output meanwhile (`awaitOutput`). pub fn listen(t: *Turn) void { if (t.io == null) return; t.listening = true; t.release(); } /// The editor takes the turn back -- once every step that is out in a /// syscall has returned, since a step of the editor's may change what /// those still point into. pub fn wake(t: *Turn) void { const io = t.io orelse return; t.mutex.lockUncancelable(io); t.listening = false; while (t.out != 0) t.settled.waitUncancelable(io, &t.mutex); } /// Whoever has the turn is about to block in the host in the middle of /// a step. Nests: a directory listing that resolves each entry yields /// inside a yield, and only the outermost one lets go. pub fn yield(t: *Turn) void { t.yields +%= 1; const io = t.io orelse return; yield_depth += 1; if (yield_depth != 1) return; t.out += 1; t.mutex.unlock(io); } pub fn back(t: *Turn) void { const io = t.io orelse return; yield_depth -= 1; if (yield_depth != 0) return; t.mutex.lockUncancelable(io); t.out -= 1; if (t.out == 0) t.settled.broadcast(io); } /// How many yields this thread is inside of. threadlocal var yield_depth: u32 = 0; /// A connection task takes the turn; answers whether nothing is out /// mid-step, which is what a request that changes a pane needs. pub fn take(t: *Turn) bool { t.mutex.lockUncancelable(t.io.?); return t.out == 0; } pub fn give(t: *Turn) void { t.release(); } /// One of `epoch`, `restores` or `lsp_answers` moved on: the editor /// performed the core's effects, a shell attempted a Restore (at the /// top of each loop step, when the previous step's attempt is over), /// or a language server's answer was taken in. pub fn bump(t: *Turn, counter: *u64) void { const io = t.io orelse return; counter.* +%= 1; t.settled.broadcast(io); } /// A pty's read applied, or dropped: a write waiting on it told. pub fn outputApplied(t: *Turn) void { _ = t.applied.fetchAdd(1, .acq_rel); if (t.io) |io| t.settled.broadcast(io); } /// With the turn: waits, turn given up meanwhile, until every read out of /// a pty before now is applied, as a terminal shows a program's output /// before what it led to: `cmd | pardes -` typed in a pane writes its /// pager after the shell echoed the line and started the command, and /// the editor, a read a step, could still hold that echo (a client's keys /// come a step each, so a shell's echo comes a key a read): the pager's /// layout then saw the shell's line not yet ended, and its emulator's /// resize cleared that line as a prompt the shell would draw again /// (ghostty's Screen.clearPromptForRedraw). Only while the editor waits /// in its loop (`listening`): resting in a call of its own it applies /// nothing, and the request goes first, as before. A read its reader /// drops off the turn wakes nobody: seen at the next recheck. pub fn awaitOutput(t: *Turn) void { const mark = t.reads.load(.acquire); while (t.listening and t.applied.load(.acquire) < mark) t.settled.waitTimeout(t.io.?, &t.mutex, .{ .duration = .{ .raw = .fromMilliseconds(25), .clock = .awake } }) catch |err| switch (err) { error.Timeout => {}, error.Canceled => return, }; } /// With the turn: waits, turn given up meanwhile, until `counter` has /// moved past `seen`; stopping ends the wait early. pub fn awaitPast(t: *Turn, counter: *const u64, seen: u64) void { while (counter.* == seen) t.settled.wait(t.io.?, &t.mutex) catch return; } fn release(t: *Turn) void { // Whatever the holder just did may be what a held read waits for, // and answering it takes the core, so before letting go. Even with // a step out in a syscall: a read is served then, as in onServe. if (t.answer_held) |f| f(t.wake_ctx); const woken = t.out == 0 and t.parked; if (woken) t.parked = false; t.mutex.unlock(t.io.?); if (woken) if (t.wake_parked) |f| f(t.wake_ctx); } test "a write waits for the output read before it while the editor listens, not while it rests in a call of its own" { const io = std.testing.io; var t: Turn = .{}; t.start(io); _ = t.reads.fetchAdd(2, .acq_rel); // A save through its own mount: the editor rests in it, applies // nothing, and the write it waits on is served at once. t.rest(); _ = t.take(); t.awaitOutput(); try std.testing.expectEqual(@as(u64, 0), t.applied.load(.acquire)); t.give(); // Its loop's wait: the write waits for both reads, applied meanwhile. t.wake(); t.listen(); const editor = try std.Thread.spawn(.{}, struct { fn apply(turn: *Turn) void { for (0..2) |_| { turn.wake(); turn.outputApplied(); turn.listen(); } } }.apply, .{&t}); _ = t.take(); t.awaitOutput(); try std.testing.expectEqual(@as(u64, 2), t.applied.load(.acquire)); t.give(); editor.join(); t.wake(); t.stop(); }