summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/fs.zig133
-rw-r--r--src/serve.zig175
2 files changed, 288 insertions, 20 deletions
diff --git a/src/fs.zig b/src/fs.zig
index 2ab619a..9e7a25a 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -178,6 +178,13 @@ fn noPayload(comptime Payload: type) Payload {
/// or readdir travel beside it as the `bytes` argument of `reply()`.
pub const Reply = ReplyWith(void);
+/// A request the backend answered `.again`, kept to be answered later, the
+/// way lib9p lets a server keep a Req and respond() when it has something:
+/// the slot it parked in and that park's sequence number, which nothing
+/// parked there later will carry. Good on the connection that issued it,
+/// until that connection hangs up.
+pub const Ticket = struct { slot: u16, seq: u64 };
+
/// The errno values a backend may answer with; `errString` names each.
pub const E = struct {
pub const PERM: u16 = 1;
@@ -474,7 +481,10 @@ pub fn Server(comptime Backend: type, comptime opts: Options) type {
/// bump-allocated and nothing reads a slot at or past `high_water`,
/// so those slots are left unwritten: a large `fid_capacity` then
/// costs memory only for the fids a client actually holds, where
- /// `init` writes the whole table on every connection.
+ /// `init` writes the whole table on every connection. `seq` carries
+ /// over, so an engine set up again for its next connection never
+ /// repeats a backend tag or a `Ticket` of the last one: set it once
+ /// (to 0) before the first `initIn`, as `init` does.
pub fn initIn(s: *Self, o: InitOptions) void {
assert(o.in.len >= msize_min);
assert(o.out.len >= 2 * msize_min);
@@ -486,7 +496,6 @@ pub fn Server(comptime Backend: type, comptime opts: Options) type {
if (!opts.fid_index) s.fids = @splat(.{});
s.slots = @splat(.{});
s.job = .{};
- s.seq = 0;
s.nfids = 0;
s.norphans = 0;
s.index = @splat(no_slot);
@@ -728,17 +737,9 @@ pub fn Server(comptime Backend: type, comptime opts: Options) type {
return null;
}
const sl = &s.slots[i];
- if (sl.holdsJob()) {
- // Its fid may have been clunked while it waited: then there
- // is nobody to answer, and asking the backend would make it
- // do the work -- open a handle, make an object -- for no one.
- if (s.findFid(sl.fid) == null) {
- s.fail(sl.tag, e_unknown_fid);
- sl.* = .{};
- return s.retry();
- }
- return s.resumeJob(i);
- }
+ // A clunk of its fid while it waited took it out (`clunk`), so
+ // nothing here is asked again for no one.
+ if (sl.holdsJob()) return s.resumeJob(i);
sl.retried = true;
sl.parked = false;
return sl.req;
@@ -787,6 +788,34 @@ pub fn Server(comptime Backend: type, comptime opts: Options) type {
if (s.findSlot(r.tag)) |i| return s.slotReply(i, r, bytes);
}
+ /// The ticket of the request `req_tag` while it waits parked: right
+ /// after the backend answered it `.again`.
+ pub fn ticket(s: *const Self, req_tag: u64) ?Ticket {
+ for (&s.slots, 0..) |*sl, i| {
+ if (sl.used and sl.parked and sl.req.tag == req_tag) return .{ .slot = @intCast(i), .seq = sl.seq };
+ }
+ return null;
+ }
+
+ /// Whether the request `t` names still waits parked: not flushed,
+ /// its fid not clunked, the connection not hung up, and not out
+ /// being asked again by `retry()` (whose asking answers it instead).
+ pub fn waiting(s: *const Self, t: Ticket) bool {
+ if (t.slot >= s.slots.len) return false;
+ const sl = &s.slots[t.slot];
+ return sl.used and sl.parked and sl.seq == t.seq;
+ }
+
+ /// Answers the request `t` names, as `reply()` would; false, with
+ /// nothing sent, once it no longer waits. A backend whose answer
+ /// costs something to make (a record taken off a queue) asks
+ /// `waiting()` first, in the same hold of the engine.
+ pub fn answer(s: *Self, t: Ticket, r: *const Backend.Reply, bytes: []const u8) bool {
+ if (!s.waiting(t)) return false;
+ s.slotReply(t.slot, r, bytes);
+ return true;
+ }
+
fn orphan(s: *Self) ?Backend.Req {
if (s.norphans == 0) return null;
for (s.touched(), 0..) |*f, i| {
@@ -964,6 +993,14 @@ pub fn Server(comptime Backend: type, comptime opts: Options) type {
fn clunk(s: *Self, tag: u16, fid: u32, kind: Kind) void {
assert(kind == .clunk or kind == .remove);
const i = s.findFid(fid) orelse return s.fail(tag, e_unknown_fid);
+ // What is parked on the fid has nobody left to answer for: it is
+ // interrupted now, so that no slot outlives its fid, to be
+ // retried with a handle the backend has let go of or answered
+ // after a fid of the same number is walked anew.
+ for (&s.slots) |*sl| if (sl.used and sl.fid == fid) {
+ s.fail(sl.tag, e_interrupted);
+ sl.* = .{};
+ };
if (s.fids[i].open or refs or (kind == .remove and features.remove)) {
s.job = .{ .kind = kind, .tag = tag, .fid = fid };
return;
@@ -2266,22 +2303,23 @@ test "fs server: a parked open, truncate and clunk complete on retry, and a walk
try testing.expectEqualStrings(e_again, got.msg.rerror.ename);
h.fsys.park_lookups = false;
- // A parked open whose fid is clunked meanwhile is answered for the
- // clunk's sake and never asked again: the backend would otherwise open
- // a handle for nobody.
+ // A parked open whose fid is clunked meanwhile is interrupted by the
+ // clunk and never asked again: the backend would otherwise open a
+ // handle for nobody.
_ = try h.walkTo(16, 5, &.{ "1", "tag" });
h.fsys.park_opens = true;
try h.send(17, .{ .topen = .{ .fid = 5, .mode = oread } });
try h.quiet();
try h.send(18, .{ .tclunk = .{ .fid = 5 } });
got = try h.reap();
+ try testing.expectEqual(@as(u16, 17), got.tag);
+ try testing.expectEqualStrings(e_interrupted, got.msg.rerror.ename);
+ got = try h.reap();
try testing.expect(got.msg == .rclunk);
h.fsys.park_opens = false;
const asked = h.fsys.calls;
h.pump();
- got = try h.reap();
- try testing.expectEqual(@as(u16, 17), got.tag);
- try testing.expectEqualStrings(e_unknown_fid, got.msg.rerror.ename);
+ try h.quiet();
try testing.expectEqual(asked, h.fsys.calls);
// A flush reaches a parked job the way it reaches a parked read.
@@ -2354,6 +2392,62 @@ test "fs server: Tflush answers the original first and the Rflush second" {
try h.quiet();
}
+test "fs server: a ticket answers only the park it was given for" {
+ var h: Harness = .{};
+ try h.handshake(4096);
+ _ = try h.walkTo(5, 1, &.{ "1", "event" });
+ try h.send(6, .{ .topen = .{ .fid = 1, .mode = oread } });
+ _ = try h.reap();
+ const parked = struct {
+ /// The ticket of the one read parked now, taken by its backend tag.
+ fn ticket(hh: *Harness) !Ticket {
+ for (hh.srv.slots) |sl| if (sl.used and sl.parked) return hh.srv.ticket(sl.req.tag).?;
+ return error.NothingParked;
+ }
+ };
+
+ // Parked, the read can be answered later through its ticket, once.
+ try h.send(7, .{ .tread = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ try h.quiet();
+ const t = try parked.ticket(&h);
+ try testing.expect(h.srv.waiting(t));
+ try testing.expect(h.srv.answer(t, &.{ .tag = 0 }, "held\n"));
+ var got = try h.reap();
+ try testing.expectEqual(@as(u16, 7), got.tag);
+ try testing.expectEqualStrings("held\n", got.msg.rread.data);
+ try testing.expect(!h.srv.answer(t, &.{ .tag = 0 }, "twice\n"));
+ try h.quiet();
+
+ // Flushed, and the tag used again for a read of another fid parked in
+ // the same slot: the old ticket answers neither.
+ try h.send(7, .{ .tread = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ const old = try parked.ticket(&h);
+ try h.send(8, .{ .tflush = .{ .oldtag = 7 } });
+ _ = try h.reap();
+ _ = try h.reap();
+ _ = try h.walkTo(9, 2, &.{ "1", "event" });
+ try h.send(10, .{ .topen = .{ .fid = 2, .mode = oread } });
+ _ = try h.reap();
+ try h.send(7, .{ .tread = .{ .fid = 2, .offset = 0, .count = 4096 } });
+ const new = try parked.ticket(&h);
+ try testing.expectEqual(old.slot, new.slot);
+ try testing.expect(!h.srv.waiting(old));
+ try testing.expect(!h.srv.answer(old, &.{ .tag = 0 }, "misrouted\n"));
+ try h.quiet();
+
+ // Clunking a fid interrupts what is parked on it, and its ticket dies.
+ try h.send(11, .{ .tclunk = .{ .fid = 2 } });
+ got = try h.reap();
+ try testing.expectEqual(@as(u16, 7), got.tag);
+ try testing.expectEqualStrings(e_interrupted, got.msg.rerror.ename);
+ got = try h.reap();
+ try testing.expectEqual(@as(u16, 11), got.tag);
+ try testing.expect(got.msg == .rclunk);
+ try testing.expect(!h.srv.waiting(new));
+ for (h.srv.slots) |sl| try testing.expect(!sl.used);
+ try h.quiet();
+}
+
test "fs server: the fid and permission refusals, each in a string Linux knows" {
var h: Harness = .{};
try h.handshake(4096);
@@ -3400,6 +3494,7 @@ test "fs server: an engine set up in place never writes the fid slots it has not
defer testing.allocator.destroy(r);
r.* = .{ .fsys = .{} };
@memset(std.mem.asBytes(&r.srv), 0xA5);
+ r.srv.seq = 0; // the one field a runner writes when it is made
r.srv.initIn(.{ .in = &r.in, .out = &r.out, .root = 1, .seed = 0x4242 });
_ = try r.call(notag, .{ .tversion = .{ .msize = 4096, .version = "9P2000" } });
_ = try r.call(0, .{ .tattach = .{ .fid = 0, .afid = nofid, .uname = "goblin", .aname = "" } });
diff --git a/src/serve.zig b/src/serve.zig
index 0311f3d..d70ebcf 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -32,7 +32,9 @@ pub const Limits = struct {
/// `Conn.reply()`, at once or later from any task or thread. A backend that
/// answers `Status.again` is asked again when someone calls `Conn.wake()`
/// (or `wakeAll()`), which is the runner's only spontaneous retry; new
-/// input, replies and closing do not retry parked requests.
+/// input, replies and closing do not retry parked requests. Or it answers
+/// `.again` through `Conn.hold()` and keeps the ticket, and answers that
+/// request itself through `Conn.answerWith()` when it has something.
pub fn Runner(comptime Backend: type, comptime opts: fs.Options, comptime limits: Limits) type {
if (limits.msize < fs.msize_min) @compileError("9P runner msize must hold one full Rwalk");
if (limits.connections == 0 or limits.connections > 255) @compileError("9P runner needs 1..255 connection slots");
@@ -147,6 +149,55 @@ pub fn Runner(comptime Backend: type, comptime opts: fs.Options, comptime limits
c.raise(output);
}
+ /// Answers a read or write `.again` and hands back the ticket
+ /// of the park, to answer it through `answerWith()` when the backend
+ /// has something (lib9p's kept Req); null when it could not
+ /// park, the engine having refused it instead.
+ pub fn hold(c: *Conn, r: *const Backend.Reply) ?fs.Ticket {
+ std.debug.assert(r.status == .again);
+ c.lock();
+ c.engine.reply(r, "");
+ const t = c.engine.ticket(r.tag);
+ c.unlock();
+ c.raise(output);
+ return t;
+ }
+
+ /// Whether the request a ticket names still waits: not flushed,
+ /// its fid not clunked, the connection not hung up, and not out
+ /// being asked again by a retry (whose asking answers it).
+ pub fn waiting(c: *Conn, t: fs.Ticket) bool {
+ c.lock();
+ defer c.unlock();
+ return c.engine.waiting(t);
+ }
+
+ /// A reply and the bytes that travel beside it.
+ pub const Answer = struct { reply: Backend.Reply, bytes: []const u8 = "" };
+
+ /// Answers the request a ticket names, from any task or thread,
+ /// with what `produce(ctx)` makes, which is asked only while
+ /// that request still waits and under the same hold of the
+ /// engine: an answer that costs something to make (a record
+ /// taken off a queue) is never spent on a request flushed
+ /// meanwhile. `produce` answers null when it has nothing yet.
+ /// Answers whether the request still waits afterwards.
+ pub fn answerWith(c: *Conn, t: fs.Ticket, ctx: anytype, comptime produce: fn (@TypeOf(ctx)) ?Answer) bool {
+ c.lock();
+ if (!c.engine.waiting(t)) {
+ c.unlock();
+ return false;
+ }
+ const made = produce(ctx) orelse {
+ c.unlock();
+ return true;
+ };
+ _ = c.engine.answer(t, &made.reply, made.bytes);
+ c.unlock();
+ c.raise(output);
+ return false;
+ }
+
/// Sends whatever the engine has produced; for a caller that
/// drove the engine itself under `lock()`.
pub fn flush(c: *Conn) void {
@@ -320,6 +371,9 @@ pub fn Runner(comptime Backend: type, comptime opts: fs.Options, comptime limits
c.signal = .unset;
c.room = .unset;
c.used = .init(false);
+ // Counts on across the slot's connections (`Engine.initIn`),
+ // so a ticket of one never names a park of the next.
+ c.engine.seq = 0;
}
}
@@ -752,6 +806,125 @@ test "serve: a parked read completes when another task posts and wakes" {
_ = try tc.one(.{ .clunk = .{ .fid = 1 } });
}
+/// Answers at once, but holds a read that parks, keeping its ticket.
+const Holder = struct {
+ stub: *Stub,
+ conn: ?*TestRunner.Conn = null,
+ ticket: ?fs.Ticket = null,
+
+ fn serve(ctx: ?*anyopaque, conn: *TestRunner.Conn, req: fs.Req) void {
+ const hd: *Holder = @ptrCast(@alignCast(ctx.?));
+ const a = hd.stub.handle(req);
+ if (a.reply.status != .again) return conn.reply(&a.reply, a.bytes);
+ const t = conn.hold(&a.reply);
+ hd.stub.mutex.lockUncancelable(testing.io);
+ defer hd.stub.mutex.unlock(testing.io);
+ hd.conn = conn;
+ hd.ticket = t;
+ }
+
+ fn held(hd: *Holder) !struct { *TestRunner.Conn, fs.Ticket } {
+ var tries: usize = 0;
+ while (tries < 2000) : (tries += 1) {
+ hd.stub.mutex.lockUncancelable(testing.io);
+ const got = if (hd.ticket) |t| .{ hd.conn.?, t } else null;
+ hd.ticket = null;
+ hd.stub.mutex.unlock(testing.io);
+ if (got) |g| return g;
+ try testing.io.sleep(.fromMilliseconds(1), .awake);
+ }
+ return error.Timeout;
+ }
+};
+
+/// Makes an answer, counting the times it was asked to.
+const Producer = struct {
+ text: []const u8,
+ made: u32 = 0,
+
+ fn make(pr: *Producer) ?TestRunner.Conn.Answer {
+ pr.made += 1;
+ return .{ .reply = .{ .tag = 0 }, .bytes = pr.text };
+ }
+};
+
+test "serve: a held read is answered through its ticket, and a flushed one is not" {
+ var rig: Rig = .{ .dir = undefined };
+ var holder: Holder = .{ .stub = &rig.stub };
+ try rig.start(.{ .serve = Holder.serve }, 0);
+ defer rig.end();
+ rig.runner.handler.ctx = &holder;
+ var tc: TestClient = .{ .io = undefined, .stream = undefined };
+ try tc.open(testing.io, .{ .unix = rig.unix });
+ defer tc.close();
+ try tc.handshake();
+ _ = try tc.one(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"event"} } });
+ _ = try tc.one(.{ .open = .{ .fid = 1, .mode = c9.oread } });
+
+ // Flushed, the ticket answers nothing and its answer is never made, and
+ // the tag's next read is not answered with what was meant for the old.
+ const flushed = try tc.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 64 } });
+ const old_conn, const old = try holder.held();
+ _ = try tc.submit(.{ .flush = .{ .oldtag = flushed } });
+ try testing.expectEqualStrings(fs.e_interrupted, (try tc.reap()).result.fail);
+ try testing.expectEqual(Client.Op.flush, (try tc.reap()).op);
+ const again = try tc.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 64 } });
+ try testing.expectEqual(flushed, again);
+ const conn, const t = try holder.held();
+ var misrouted: Producer = .{ .text = "misrouted\n" };
+ try testing.expect(!old_conn.waiting(old));
+ try testing.expect(!old_conn.answerWith(old, &misrouted, Producer.make));
+ try testing.expectEqual(@as(u32, 0), misrouted.made);
+
+ // Held, the read is answered from here, with no retry asked for.
+ try testing.expect(conn.waiting(t));
+ var record: Producer = .{ .text = "record 1\n" };
+ try testing.expect(!conn.answerWith(t, &record, Producer.make));
+ const done = try tc.reap();
+ try testing.expectEqual(again, done.tag);
+ try testing.expectEqualStrings("record 1\n", done.result.read);
+ try testing.expect(!conn.answerWith(t, &record, Producer.make));
+ try testing.expectEqual(@as(u32, 1), record.made);
+ _ = try tc.one(.{ .clunk = .{ .fid = 1 } });
+}
+
+test "serve: a ticket of a hung-up client never names a park of the next one in its slot" {
+ var rig: Rig = .{ .dir = undefined };
+ var holder: Holder = .{ .stub = &rig.stub };
+ try rig.start(.{ .serve = Holder.serve }, 0);
+ defer rig.end();
+ rig.runner.handler.ctx = &holder;
+ var stale: struct { *TestRunner.Conn, fs.Ticket } = undefined;
+ for (0..2) |round| {
+ var tc: TestClient = .{ .io = undefined, .stream = undefined };
+ try tc.open(testing.io, .{ .unix = rig.unix });
+ defer tc.close();
+ try tc.handshake();
+ _ = try tc.one(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"event"} } });
+ _ = try tc.one(.{ .open = .{ .fid = 1, .mode = c9.oread } });
+ _ = try tc.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 64 } });
+ const held = try holder.held();
+ if (round == 0) {
+ stale = held;
+ continue; // hangs up with the read held
+ }
+ // The same slot and, request for request, the same park: only the
+ // sequence number, which counts on across connections, tells them
+ // apart.
+ try testing.expectEqual(stale[0], held[0]);
+ try testing.expectEqual(stale[1].slot, held[1].slot);
+ var wrong: Producer = .{ .text = "for the last client\n" };
+ try testing.expect(!held[0].answerWith(stale[1], &wrong, Producer.make));
+ try testing.expectEqual(@as(u32, 0), wrong.made);
+ try testing.expect(held[0].waiting(held[1]));
+ // Clunked, the held read is interrupted first.
+ _ = try tc.submit(.{ .clunk = .{ .fid = 1 } });
+ try testing.expectEqualStrings(fs.e_interrupted, (try tc.reap()).result.fail);
+ try testing.expectEqual(Client.Op.clunk, (try tc.reap()).op);
+ try testing.expect(!held[0].waiting(held[1]));
+ }
+}
+
test "serve: two clients at once, a third is refused, and stop() hangs up" {
var rig: Rig = .{ .dir = undefined };
try rig.start(.{ .serve = serveNow, .closed = countClosed }, 0);