library: the last three protocols speak the envelope

These were the awkward ones. Each began with an operation packed into a
single byte — two of them with a version wedged in beside it — so there was
no wrapping them: the layouts had to be rebuilt. The device manager's own
enumerate and subscribe become the reserved verbs that mean the same thing
everywhere, its replies lose three status structs the envelope already
carries, and a device id becomes the packet's target. Power drops the
version it repeated on every request, because describe is the handshake,
and stops claiming a 64-byte ceiling it never needed for calls. USB moves a
control transfer's data to the packet tail in both directions, which makes
the status length the transferred length and retires a field that had been
saying the same thing twice.

The danger in this one was not the protocols but their readers. Init
recognised a power button by two bytes at the head of a message, the ACPI
service dispatched on the first byte, the xHCI driver read its operation
with a raw integer load, and the HID drivers reinterpreted a report
wholesale — none of which would have failed to compile once the layouts
moved. They would simply have stopped: no shutdown on the power button, no
reports from the keyboard. Every one of them now reads through the
generated types, and the shutdown gate that answers only a subscriber is
the same code it was.

Two sizes were decided by measuring rather than assuming. The child-added
message is both a request and the event broadcast to subscribers, and
alignment rounds it to 48 bytes, which puts its packet exactly on the
64-byte push floor — a test pins that, because a field added carelessly
would now overflow it. The interrupt report gives up eight bytes of inline
room to make space for the header; the two drivers that produce reports
send eight and four.

Suite 110/110.
This commit is contained in:
Daniel Samson
2026-08-01 07:20:37 +01:00
parent d2dfbcabf8
commit 2719b93530
27 changed files with 1058 additions and 685 deletions
+81 -46
View File
@@ -22,6 +22,7 @@ const logging = @import("logging");
const aml = @import("aml");
const acpi_ids = @import("acpi-ids");
const device_manager_protocol = @import("device-manager-protocol");
const envelope = @import("envelope");
const power_protocol = @import("power-protocol");
/// AML opcode/prefix bytes by name (`zero_opcode`, `byte_prefix`, …) — so the `_HID`
/// integer decode names the opcodes instead of bare 0x0A/0x0B/… (docs/coding-standards.md).
@@ -241,10 +242,20 @@ fn onInit(endpoint: ipc.Handle) bool {
else
std.log.info("device {d} bus=acpi hid={s} ({d} resources)", .{ entry.device_id, hid, entry.resource_count });
if (manager) |h| {
var report = device_manager_protocol.ChildAdded{ .bus = @intFromEnum(device_manager_protocol.BusKind.acpi), .parent = node_id, .bus_address = entry.device_id, .identity = 0, .device_id = entry.device_id };
// The registered device id is the packet's target, so the body only
// says where on the firmware tree the node sits and what it is.
var report = device_manager_protocol.ChildAdded{
.bus = @intFromEnum(device_manager_protocol.BusKind.acpi),
.parent = node_id,
.bus_address = entry.device_id,
.identity = 0,
};
@memcpy(report.hid[0..entry.hid_len], entry.hid[0..entry.hid_len]);
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, std.mem.asBytes(&report), &reply) catch {};
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
if (device_manager_protocol.Protocol.encodeRequest(.child_added, entry.device_id, report, &.{}, &packet)) |framed| {
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, framed, &reply) catch {};
}
}
}
std.log.info("reported {d} device(s) to the manager", .{registered_count});
@@ -389,13 +400,21 @@ fn dispatchGpe(n: u32) void {
fn publishNotify(node: *aml.Node, code: u64) void {
// Map the notified device's _HID to a domain event where we recognize it.
// The kind IS the packet's verb, so the mapping picks which event to frame
// rather than which tag to put in a payload.
var hid: [8]u8 = .{0} ** 8;
if (readHid(node, &global_interpreter)) |h| hid = h;
const which: power_protocol.Event = if (std.mem.eql(u8, hid[0..7], "PNP0C0A")) .battery else if (std.mem.eql(u8, hid[0..7], "ACPI0003")) .ac else if (std.mem.eql(u8, hid[0..7], "PNP0C0D")) .lid else .notify;
var event = power_protocol.EventMessage{ .event = @intFromEnum(which), .code = @truncate(code) };
event.hid = hid;
const notice = power_protocol.Notice{ .code = @truncate(code), .hid = hid };
std.log.info("power: notify {s} code {d}", .{ hid[0..7], code });
publishEvent(std.mem.asBytes(&event));
if (std.mem.eql(u8, hid[0..7], "PNP0C0A")) {
publish(.battery, notice);
} else if (std.mem.eql(u8, hid[0..7], "ACPI0003")) {
publish(.ac, notice);
} else if (std.mem.eql(u8, hid[0..7], "PNP0C0D")) {
publish(.lid, notice);
} else {
publish(.notify, notice);
}
}
/// Two lowercase hex digits of `n` into `out[0..2]`.
@@ -406,14 +425,19 @@ fn writeHex2(out: []u8, n: u32) void {
}
fn publishButton() void {
const event = power_protocol.EventMessage{ .event = @intFromEnum(power_protocol.Event.power_button) };
publishEvent(std.mem.asBytes(&event));
publish(.power_button, .{});
}
fn publishEvent(bytes: []const u8) void {
/// Push one event to every subscriber. The kind is the packet's operation, so
/// this is framed once, outside the loop — every subscriber gets identical
/// bytes. A subscriber whose endpoint stops accepting (it died) is dropped on
/// the failed send, so a dead one can never stall the rest.
fn publish(comptime kind: power_protocol.Event, notice: power_protocol.Notice) void {
var packet: [envelope.post_maximum]u8 = undefined;
const framed = power_protocol.Protocol.encodeEvent(kind, 0, notice, &packet) orelse return;
for (&subscribers) |*slot| {
if (slot.*) |handle| {
if (!ipc.send(handle, bytes)) slot.* = null;
if (!ipc.send(handle, framed)) slot.* = null;
}
}
}
@@ -449,43 +473,54 @@ fn onNotification(badge: u64) void {
onSci();
}
/// The `.power` protocol: subscribe (endpoint as the call's capability),
/// shutdown (PID 1 only). Device discovery uses a different endpoint (the
/// device manager's), so nothing here handles ChildAdded.
/// The generated power dispatch. One provider per system, so the handler context
/// is empty and the subscriber table stays in this file's globals.
const Serve = power_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// Set by `onSubscribe` when the subscriber table has taken the capability the
/// call carried, and read by `onMessage`, where the turn's `Arrival` lives.
var capability_claimed = false;
/// The power contract: the reserved `subscribe` (the subscriber's endpoint as
/// the call's capability) and `shutdown` (subscribers only). Device discovery
/// uses a different endpoint — the device manager's — so nothing here handles a
/// tree report.
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
if (message.len < 1) return 0;
switch (message[0]) {
@intFromEnum(power_protocol.Operation.subscribe) => {
// The subscriber's endpoint is claimed only when a slot takes it;
// a full table refuses and the turn closes what arrived.
var status: i32 = -1;
if (arrived.peek() != null) {
for (&subscribers, 0..) |*slot, si| {
if (slot.* == null) {
slot.* = arrived.take();
subscriber_tasks[si] = sender;
status = 0;
break;
}
}
}
const r = power_protocol.Reply{ .status = status };
@memcpy(reply[0..@sizeOf(power_protocol.Reply)], std.mem.asBytes(&r));
return @sizeOf(power_protocol.Reply);
},
@intFromEnum(power_protocol.Operation.shutdown) => {
// Honored only from a power subscriber — init, which has already run
// the stop sequence over everything else. The power service is
// mechanism (write S5); deciding *when* to shut down and stopping
// the rest of the system first is init's policy.
const allowed = isSubscriber(sender);
const r = power_protocol.Reply{ .status = if (allowed) 0 else -1 };
@memcpy(reply[0..@sizeOf(power_protocol.Reply)], std.mem.asBytes(&r));
if (allowed) enterS5();
return @sizeOf(power_protocol.Reply);
},
else => return 0,
capability_claimed = false;
const written = Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
if (capability_claimed) _ = arrived.take();
return written;
}
const handlers = Serve.Handlers{ .shutdown = onShutdown, .subscribe = onSubscribe };
/// The subscriber's endpoint is claimed only when a slot takes it; a full table
/// refuses and the turn closes what arrived.
fn onSubscribe(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const endpoint = invocation.capability orelse return -envelope.EPROTO;
for (&subscribers, 0..) |*slot, index| {
if (slot.* == null) {
slot.* = endpoint;
subscriber_tasks[index] = invocation.sender;
capability_claimed = true;
return 0;
}
}
return -envelope.ENOSPC;
}
/// Honored only from a power subscriber — init, which has already run the stop
/// sequence over everything else. The power service is mechanism (write S5);
/// deciding *when* to shut down and stopping the rest of the system first is
/// init's policy. The badge is the whole gate: it is kernel-stamped, so nothing
/// in the packet can claim to be init.
fn onShutdown(_: void, invocation: Invocation(void), _: Answer(void)) isize {
if (!isSubscriber(invocation.sender)) return -envelope.EPERM;
enterS5();
return 0;
}
/// Depth-first walk: register + report each present device with a _HID, then
+2 -2
View File
@@ -14,8 +14,8 @@ pub fn build(b: *std.Build) void {
.name = "discovery",
.root_source_file = b.path("acpi.zig"),
.imports = &.{
"acpi-ids", "aml", "channel", "device-manager-protocol", "driver", "ipc", "logging",
"memory", "power-protocol", "process", "service", "time",
"acpi-ids", "aml", "channel", "device-manager-protocol", "driver", "envelope",
"ipc", "logging", "memory", "power-protocol", "process", "service", "time",
},
});
b.installArtifact(exe);