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:
@@ -229,18 +229,21 @@ fn registerAndReport(bus: u64, dev: u64, function: u64, class_triple: u32) void
|
||||
std.log.info("register refused for {d}:{d}.{d}", .{ bus, dev, function });
|
||||
return;
|
||||
};
|
||||
const report = device_manager_protocol.ChildAdded{
|
||||
// The registered device id is the packet's target — the manager's object
|
||||
// addressing — so the report body carries only where on the bus it sits and
|
||||
// what it is.
|
||||
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
const framed = device_manager_protocol.Protocol.encodeRequest(.child_added, registered, .{
|
||||
.bus = @intFromEnum(device_manager_protocol.BusKind.pci),
|
||||
.parent = bridge_id,
|
||||
.bus_address = (bus << 8) | (dev << 3) | function,
|
||||
.identity = class_triple,
|
||||
.device_id = registered,
|
||||
.vendor = descriptor.vendor,
|
||||
.device = descriptor.device,
|
||||
.subsystem = descriptor.subsystem,
|
||||
};
|
||||
}, &.{}, &packet) orelse return;
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(manager_handle, std.mem.asBytes(&report), &reply) catch {
|
||||
_ = ipc.call(manager_handle, framed, &reply) catch {
|
||||
std.log.info("child report for {d}:{d}.{d} failed", .{ bus, dev, function });
|
||||
};
|
||||
}
|
||||
|
||||
@@ -112,9 +112,10 @@ pub fn main(init: process.Init) void {
|
||||
if (signals.has(.terminate)) return;
|
||||
continue;
|
||||
}
|
||||
if (!got.isMessage() or got.len < @sizeOf(usb.InterruptReport)) continue;
|
||||
|
||||
const message = std.mem.bytesToValue(usb.InterruptReport, receive[0..@sizeOf(usb.InterruptReport)]);
|
||||
if (!got.isMessage()) continue;
|
||||
// An `interrupt_report` event packet: the verb in its folded header, the
|
||||
// report after it. Anything else on this endpoint is not ours.
|
||||
const message = usb.reportOf(receive[0..got.len]) orelse continue;
|
||||
if (message.length < @sizeOf(hid.KeyboardReport)) continue;
|
||||
const report = std.mem.bytesToValue(hid.KeyboardReport, message.data[0..@sizeOf(hid.KeyboardReport)]);
|
||||
const transitions = decoder.feed(report);
|
||||
|
||||
@@ -74,9 +74,10 @@ pub fn main(init: process.Init) void {
|
||||
if (signals.has(.terminate)) return;
|
||||
continue;
|
||||
}
|
||||
if (!got.isMessage() or got.len < @sizeOf(usb.InterruptReport)) continue;
|
||||
|
||||
const message = std.mem.bytesToValue(usb.InterruptReport, receive[0..@sizeOf(usb.InterruptReport)]);
|
||||
if (!got.isMessage()) continue;
|
||||
// An `interrupt_report` event packet: the verb in its folded header, the
|
||||
// report after it. Anything else on this endpoint is not ours.
|
||||
const message = usb.reportOf(receive[0..got.len]) orelse continue;
|
||||
const length = @min(message.length, message.data.len);
|
||||
const report = hid.parseMouse(message.data[0..length]) orelse continue;
|
||||
const mask = buttonMask(report.buttons);
|
||||
|
||||
@@ -10,10 +10,10 @@ pub fn build(b: *std.Build) void {
|
||||
.name = "usb-xhci-bus",
|
||||
.root_source_file = b.path("usb-xhci-bus.zig"),
|
||||
.imports = &.{
|
||||
"channel", "device-manager-protocol", "driver", "input-client",
|
||||
"ipc", "logging", "memory", "mmio",
|
||||
"pci", "process", "service", "time",
|
||||
"usb-abi", "usb-ids", "usb-transfer-protocol",
|
||||
"channel", "device-manager-protocol", "driver", "envelope",
|
||||
"input-client", "ipc", "logging", "memory",
|
||||
"mmio", "pci", "process", "service",
|
||||
"time", "usb-abi", "usb-ids", "usb-transfer-protocol",
|
||||
},
|
||||
});
|
||||
b.installArtifact(exe);
|
||||
|
||||
@@ -25,6 +25,7 @@ const device_manager = @import("driver");
|
||||
const memory = @import("memory");
|
||||
const logging = @import("logging");
|
||||
const device_manager_protocol = @import("device-manager-protocol");
|
||||
const envelope = @import("envelope");
|
||||
const usb_ids = @import("usb-ids");
|
||||
const usb_abi = @import("usb-abi");
|
||||
const usb_transfer_protocol = @import("usb-transfer-protocol");
|
||||
@@ -386,6 +387,23 @@ fn bringUpBehindHub(manager: ipc.Handle, engine: *library.Controller, hub: *libr
|
||||
if (deviceIsHub(usb_device)) _ = engine.setupHub(usb_device);
|
||||
}
|
||||
|
||||
/// Report one interface gone. A removal is addressed by the composite (parent,
|
||||
/// bus address) — a pair no single `Header.target` can carry — so that stays the
|
||||
/// packet's body and the target addresses the manager itself. `where` names the
|
||||
/// port and interface for the log line, or null where the caller stays quiet
|
||||
/// (a hub subtree collapsing reports a great many at once).
|
||||
fn reportRemoved(manager: ipc.Handle, bus_address: u64, where: ?struct { port: u32, interface: u8 }) void {
|
||||
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
const framed = device_manager_protocol.Protocol.encodeRequest(.child_removed, 0, .{
|
||||
.parent = controller_id,
|
||||
.bus_address = bus_address,
|
||||
}, &.{}, &packet) orelse return;
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(manager, framed, &reply) catch {
|
||||
if (where) |place| std.log.info("child-removed report for port {d} interface {d} failed", .{ place.port, place.interface });
|
||||
};
|
||||
}
|
||||
|
||||
/// Tear down a device that disconnected from a hub: recursively tear down its
|
||||
/// own downstream devices first if it is a hub, report each interface removed,
|
||||
/// then Disable Slot. Mirrors tearDownPort for a hub-attached device.
|
||||
@@ -398,12 +416,7 @@ fn tearDownHubDevice(manager: ipc.Handle, engine: *library.Controller, dev: *lib
|
||||
const key = hubPortKey(dev.parent_slot, dev.parent_port);
|
||||
for (dev.interfaces[0..dev.interface_count]) |*interface| {
|
||||
if (interface.registered_device_id == 0) continue;
|
||||
const event = device_manager_protocol.ChildRemoved{
|
||||
.parent = controller_id,
|
||||
.bus_address = (@as(u64, key) << 8) | interface.number,
|
||||
};
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(manager, std.mem.asBytes(&event), &reply) catch {};
|
||||
reportRemoved(manager, (@as(u64, key) << 8) | interface.number, null);
|
||||
interface.registered_device_id = 0;
|
||||
}
|
||||
engine.tearDownDevice(dev);
|
||||
@@ -428,14 +441,7 @@ fn tearDownPort(manager: ipc.Handle, engine: *library.Controller, port: u32) voi
|
||||
std.log.info("port {d} disconnected", .{port});
|
||||
for (usb_device.interfaces[0..usb_device.interface_count]) |*interface| {
|
||||
if (interface.registered_device_id == 0) continue;
|
||||
const event = device_manager_protocol.ChildRemoved{
|
||||
.parent = controller_id,
|
||||
.bus_address = (@as(u64, port) << 8) | interface.number,
|
||||
};
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(manager, std.mem.asBytes(&event), &reply) catch {
|
||||
std.log.info("child-removed report for port {d} interface {d} failed", .{ port, interface.number });
|
||||
};
|
||||
reportRemoved(manager, (@as(u64, port) << 8) | interface.number, .{ .port = port, .interface = interface.number });
|
||||
interface.registered_device_id = 0;
|
||||
}
|
||||
engine.tearDownDevice(usb_device);
|
||||
@@ -469,15 +475,17 @@ fn reportInterface(manager: ipc.Handle, port: u32, interface: library.InterfaceI
|
||||
return null;
|
||||
};
|
||||
|
||||
const report = device_manager_protocol.ChildAdded{
|
||||
// The registered device id is the packet's target — the manager's object
|
||||
// addressing — so the report body carries only where on the bus it sits.
|
||||
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
const framed = device_manager_protocol.Protocol.encodeRequest(.child_added, registered, .{
|
||||
.bus = @intFromEnum(device_manager_protocol.BusKind.usb),
|
||||
.parent = controller_id,
|
||||
.bus_address = (@as(u64, port) << 8) | interface.number,
|
||||
.identity = identity,
|
||||
.device_id = registered,
|
||||
};
|
||||
}, &.{}, &packet) orelse return null;
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(manager, std.mem.asBytes(&report), &reply) catch {
|
||||
_ = ipc.call(manager, framed, &reply) catch {
|
||||
std.log.info("child report for port {d} interface {d} failed", .{ port, interface.number });
|
||||
return null;
|
||||
};
|
||||
@@ -496,59 +504,55 @@ fn reportInterface(manager: ipc.Handle, port: u32, interface: library.InterfaceI
|
||||
return registered;
|
||||
}
|
||||
|
||||
/// Serve the USB transfer protocol: a class driver opens its device, then issues
|
||||
/// control / interrupt-subscribe / bulk requests against it.
|
||||
/// The generated transfer dispatch. One controller per process, so the handler
|
||||
/// context is empty and the open table stays in this file's globals.
|
||||
const Serve = usb_transfer_protocol.Protocol.Provider(void);
|
||||
|
||||
const Invocation = envelope.Invocation;
|
||||
const Answer = envelope.Answer;
|
||||
|
||||
/// Every refusal here is the same one — this controller does not (or no longer)
|
||||
/// serve the device the packet addressed — so there is one errno for all of them.
|
||||
const refused: isize = -envelope.ENOENT;
|
||||
|
||||
/// Set by `onOpen` when the open table has taken ownership of the endpoint the
|
||||
/// call carried, and read by `onMessage`, where the turn's `Arrival` lives. The
|
||||
/// generated dispatch hands a handler the raw handle rather than the `Arrival`,
|
||||
/// so the *claim* travels back out this way. One turn, one handler, one thread.
|
||||
var capability_claimed = false;
|
||||
|
||||
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
|
||||
_ = sender;
|
||||
if (message.len < 4) return 0;
|
||||
const operation = std.mem.readInt(u32, message[0..4], .little);
|
||||
return switch (operation) {
|
||||
@intFromEnum(usb_transfer_protocol.Operation.open) => handleOpen(message, reply, arrived),
|
||||
@intFromEnum(usb_transfer_protocol.Operation.control) => handleControl(message, reply),
|
||||
@intFromEnum(usb_transfer_protocol.Operation.interrupt_subscribe) => handleSubscribe(message, reply),
|
||||
@intFromEnum(usb_transfer_protocol.Operation.bulk) => handleBulk(message, reply),
|
||||
@intFromEnum(usb_transfer_protocol.Operation.dma_attach) => handleDmaAttach(message, reply, arrived),
|
||||
else => 0,
|
||||
};
|
||||
capability_claimed = false;
|
||||
const written = Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
|
||||
if (capability_claimed) _ = arrived.take();
|
||||
return written;
|
||||
}
|
||||
|
||||
/// dma_attach: bind the class driver's DMA-region capability into the controller's IOMMU
|
||||
/// domain, so the controller may DMA to the physical addresses inside that buffer. The
|
||||
/// binding holds its own kernel reference, so this never claims the arriving handle —
|
||||
/// the turn's `defer` in the harness is the close, on the failure paths as well as this
|
||||
/// one.
|
||||
fn handleDmaAttach(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
|
||||
if (message.len < @sizeOf(usb_transfer_protocol.DmaAttachRequest)) return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = -1 });
|
||||
const handle = arrived.peek() orelse return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = -1 });
|
||||
const ok = device.dmaBind(controller_id, handle);
|
||||
return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = if (ok) 0 else -1 });
|
||||
}
|
||||
const handlers = Serve.Handlers{
|
||||
.open = onOpen,
|
||||
.control = onControl,
|
||||
.interrupt_subscribe = onInterruptSubscribe,
|
||||
.bulk = onBulk,
|
||||
.dma_attach = onDmaAttach,
|
||||
};
|
||||
|
||||
fn writeReply(reply: []u8, value: anytype) usize {
|
||||
const bytes = std.mem.asBytes(&value);
|
||||
@memcpy(reply[0..bytes.len], bytes);
|
||||
return bytes.len;
|
||||
}
|
||||
|
||||
/// open: resolve the assigned device id to an interface, remember the caller's
|
||||
/// endpoint (for interrupt reports), and answer with a device token + the
|
||||
/// interface's endpoints so the class driver need not re-read the config.
|
||||
fn handleOpen(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
|
||||
if (message.len < @sizeOf(usb_transfer_protocol.OpenRequest)) return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
|
||||
const request = std.mem.bytesToValue(usb_transfer_protocol.OpenRequest, message[0..@sizeOf(usb_transfer_protocol.OpenRequest)]);
|
||||
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
|
||||
const found = engine.findInterface(request.device_id) orelse return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
|
||||
/// open: the target is the class driver's assigned device id. Resolve it to an
|
||||
/// interface, remember the caller's endpoint (for interrupt reports), and answer
|
||||
/// with a device token — the target of every later packet — plus the interface's
|
||||
/// endpoints, so the class driver need not re-read the configuration descriptor.
|
||||
fn onOpen(_: void, invocation: Invocation(void), answer: Answer(usb_transfer_protocol.Opened)) isize {
|
||||
const engine = if (controller) |*c| c else return refused;
|
||||
const found = engine.findInterface(invocation.target) orelse return refused;
|
||||
|
||||
// The report endpoint is claimed only if the open table actually keeps it;
|
||||
// a full table leaves it to the turn to close.
|
||||
if (arrived.peek()) |endpoint| {
|
||||
if (recordOpen(request.device_id, endpoint)) _ = arrived.take();
|
||||
if (invocation.capability) |endpoint| {
|
||||
if (recordOpen(invocation.target, endpoint)) capability_claimed = true;
|
||||
}
|
||||
|
||||
var open_reply = usb_transfer_protocol.OpenReply{
|
||||
.status = 0,
|
||||
var opened = usb_transfer_protocol.Opened{
|
||||
.device_token = invocation.target,
|
||||
.endpoint_count = found.interface.endpoint_count,
|
||||
.device_token = request.device_id,
|
||||
.interface_class = found.interface.class,
|
||||
.interface_subclass = found.interface.subclass,
|
||||
.interface_protocol = found.interface.protocol,
|
||||
@@ -556,57 +560,71 @@ fn handleOpen(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
|
||||
};
|
||||
const count = @min(found.interface.endpoint_count, usb_transfer_protocol.max_reported_endpoints);
|
||||
for (found.interface.endpoints[0..count], 0..) |endpoint, index| {
|
||||
open_reply.endpoints[index] = .{
|
||||
opened.endpoints[index] = .{
|
||||
.address = endpoint.address,
|
||||
.transfer_type = endpoint.transfer_type,
|
||||
.max_packet_size = endpoint.max_packet_size,
|
||||
.interval = endpoint.interval,
|
||||
};
|
||||
}
|
||||
return writeReply(reply, open_reply);
|
||||
answer.set(opened);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// control: one EP0 control transfer, small data inline both ways.
|
||||
fn handleControl(message: []const u8, reply: []u8) usize {
|
||||
if (message.len < @sizeOf(usb_transfer_protocol.ControlRequest)) return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
|
||||
const request = std.mem.bytesToValue(usb_transfer_protocol.ControlRequest, message[0..@sizeOf(usb_transfer_protocol.ControlRequest)]);
|
||||
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
|
||||
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
|
||||
/// control: one EP0 control transfer. The data stage rides the tail in both
|
||||
/// directions, so an IN transfer's answer is simply however many bytes were
|
||||
/// written into `answer.tail()` — which is what `Status.len` then reports.
|
||||
fn onControl(_: void, invocation: Invocation(usb_transfer_protocol.Control), answer: Answer(void)) isize {
|
||||
const engine = if (controller) |*c| c else return refused;
|
||||
const found = engine.findInterface(invocation.target) orelse return refused;
|
||||
|
||||
const setup = std.mem.bytesToValue(usb_abi.Request, &invocation.request.setup);
|
||||
const direction_in = invocation.request.direction_in != 0;
|
||||
const room = @min(usb_transfer_protocol.max_inline_data, answer.tail().len);
|
||||
const data_length = @min(@as(usize, invocation.request.data_length), room);
|
||||
|
||||
const setup = std.mem.bytesToValue(usb_abi.Request, &request.setup);
|
||||
const direction_in = request.direction_in != 0;
|
||||
const data_length = @min(request.data_length, usb_transfer_protocol.max_inline_data);
|
||||
var data: [usb_transfer_protocol.max_inline_data]u8 = undefined;
|
||||
if (!direction_in) @memcpy(data[0..data_length], request.data[0..data_length]);
|
||||
if (!direction_in) {
|
||||
const supplied = @min(data_length, invocation.tail.len);
|
||||
@memcpy(data[0..supplied], invocation.tail[0..supplied]);
|
||||
if (supplied < data_length) @memset(data[supplied..data_length], 0);
|
||||
}
|
||||
|
||||
const ok = engine.controlTransfer(found.device, setup, data[0..data_length], direction_in);
|
||||
var control_reply = usb_transfer_protocol.ControlReply{ .status = if (ok) 0 else -1, .actual_length = if (ok) data_length else 0 };
|
||||
if (ok and direction_in) @memcpy(control_reply.data[0..data_length], data[0..data_length]);
|
||||
return writeReply(reply, control_reply);
|
||||
if (!engine.controlTransfer(found.device, setup, data[0..data_length], direction_in)) return refused;
|
||||
if (!direction_in) return 0; // nothing follows an OUT: the status is the whole answer
|
||||
@memcpy(answer.tail()[0..data_length], data[0..data_length]);
|
||||
return @intCast(data_length);
|
||||
}
|
||||
|
||||
/// interrupt_subscribe: arm periodic IN polling; reports flow back asynchronously.
|
||||
fn handleSubscribe(message: []const u8, reply: []u8) usize {
|
||||
if (message.len < @sizeOf(usb_transfer_protocol.InterruptSubscribeRequest)) return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
|
||||
const request = std.mem.bytesToValue(usb_transfer_protocol.InterruptSubscribeRequest, message[0..@sizeOf(usb_transfer_protocol.InterruptSubscribeRequest)]);
|
||||
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
|
||||
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
|
||||
const endpoint = library.Controller.endpointForAddress(found.interface, request.endpoint_address) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
|
||||
const report_endpoint = reportEndpointFor(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
|
||||
const ok = engine.subscribeInterrupt(found.device, endpoint, request.device_token, report_endpoint);
|
||||
return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = if (ok) 0 else -1 });
|
||||
/// interrupt_subscribe: arm periodic IN polling; reports flow back asynchronously
|
||||
/// to the endpoint this device's `open` handed over.
|
||||
fn onInterruptSubscribe(_: void, invocation: Invocation(usb_transfer_protocol.InterruptSubscribe), _: Answer(void)) isize {
|
||||
const engine = if (controller) |*c| c else return refused;
|
||||
const found = engine.findInterface(invocation.target) orelse return refused;
|
||||
const endpoint = library.Controller.endpointForAddress(found.interface, invocation.request.endpoint_address) orelse return refused;
|
||||
const report_endpoint = reportEndpointFor(invocation.target) orelse return refused;
|
||||
return if (engine.subscribeInterrupt(found.device, endpoint, invocation.target, report_endpoint)) 0 else refused;
|
||||
}
|
||||
|
||||
/// bulk: one bulk transfer to/from the class driver's own DMA buffer (by physical
|
||||
/// address), so sector-sized data never crosses IPC.
|
||||
fn handleBulk(message: []const u8, reply: []u8) usize {
|
||||
if (message.len < @sizeOf(usb_transfer_protocol.BulkRequest)) return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
|
||||
const request = std.mem.bytesToValue(usb_transfer_protocol.BulkRequest, message[0..@sizeOf(usb_transfer_protocol.BulkRequest)]);
|
||||
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
|
||||
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
|
||||
const endpoint = library.Controller.endpointForAddress(found.interface, request.endpoint_address) orelse return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
|
||||
const transferred = engine.bulkTransfer(found.device, endpoint, request.physical_address, request.length);
|
||||
return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = if (transferred != null) 0 else -1, .actual_length = transferred orelse 0 });
|
||||
fn onBulk(_: void, invocation: Invocation(usb_transfer_protocol.Bulk), answer: Answer(usb_transfer_protocol.Transferred)) isize {
|
||||
const engine = if (controller) |*c| c else return refused;
|
||||
const found = engine.findInterface(invocation.target) orelse return refused;
|
||||
const endpoint = library.Controller.endpointForAddress(found.interface, invocation.request.endpoint_address) orelse return refused;
|
||||
const transferred = engine.bulkTransfer(found.device, endpoint, invocation.request.physical_address, invocation.request.length) orelse return refused;
|
||||
answer.set(.{ .actual_length = transferred });
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// dma_attach: bind the class driver's DMA-region capability into the controller's IOMMU
|
||||
/// domain, so the controller may DMA to the physical addresses inside that buffer. The
|
||||
/// binding holds its own kernel reference, so this never claims the arriving handle —
|
||||
/// the turn's `defer` in the harness is the close, on the failure paths as well as this
|
||||
/// one.
|
||||
fn onDmaAttach(_: void, invocation: Invocation(void), _: Answer(void)) isize {
|
||||
const handle = invocation.capability orelse return -envelope.EPROTO;
|
||||
return if (device.dmaBind(controller_id, handle)) 0 else refused;
|
||||
}
|
||||
|
||||
/// A timer tick or an MSI landed: drain the event ring, reconcile ports, and fan out.
|
||||
@@ -679,14 +697,18 @@ fn serviceController() void {
|
||||
if (serviced >= 32) break;
|
||||
}
|
||||
while (engine.takeReport()) |report| {
|
||||
var message = usb_transfer_protocol.InterruptReport{
|
||||
.device_token = report.device_token,
|
||||
.endpoint_address = report.endpoint_address,
|
||||
.length = @intCast(@min(report.length, usb_transfer_protocol.max_report_data)),
|
||||
};
|
||||
// One `interrupt_report` event packet: the device token in the folded
|
||||
// header, the report after it. A device that produced more than the
|
||||
// push floor admits has its report truncated here, never split.
|
||||
const n = @min(report.length, usb_transfer_protocol.max_report_data);
|
||||
@memcpy(message.data[0..n], report.data[0..n]);
|
||||
_ = ipc.send(report.report_endpoint, std.mem.asBytes(&message));
|
||||
var payload = usb_transfer_protocol.InterruptReport{
|
||||
.endpoint_address = report.endpoint_address,
|
||||
.length = @intCast(n),
|
||||
};
|
||||
@memcpy(payload.data[0..n], report.data[0..n]);
|
||||
var packet: [envelope.post_maximum]u8 = undefined;
|
||||
const framed = usb_transfer_protocol.Protocol.encodeEvent(.interrupt_report, report.device_token, payload, &packet) orelse continue;
|
||||
_ = ipc.send(report.report_endpoint, framed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -10,8 +10,8 @@ pub fn build(b: *std.Build) void {
|
||||
.name = "device-manager",
|
||||
.root_source_file = b.path("device-manager.zig"),
|
||||
.imports = &.{
|
||||
"device-manager-protocol", "device-registry", "driver", "file-system", "ipc",
|
||||
"logging", "memory", "process", "service", "time",
|
||||
"device-manager-protocol", "device-registry", "driver", "envelope", "file-system",
|
||||
"ipc", "logging", "memory", "process", "service", "time",
|
||||
},
|
||||
});
|
||||
b.installArtifact(exe);
|
||||
|
||||
@@ -24,7 +24,15 @@ const time = @import("time");
|
||||
const memory = @import("memory");
|
||||
const logging = @import("logging");
|
||||
const device_manager_protocol = @import("device-manager-protocol");
|
||||
const envelope = @import("envelope");
|
||||
const registry = @import("device-registry");
|
||||
|
||||
/// The generated device-manager dispatch. One manager per system, so the handler
|
||||
/// context is empty and the tables stay in this file's globals.
|
||||
const Serve = device_manager_protocol.Protocol.Provider(void);
|
||||
|
||||
const Invocation = envelope.Invocation;
|
||||
const Answer = envelope.Answer;
|
||||
const fs = @import("file-system");
|
||||
|
||||
// --- the device registry ------------------------------------------------------
|
||||
@@ -155,12 +163,20 @@ var test_kill_due_ns: u64 = 0;
|
||||
const maximum_subscribers = 8;
|
||||
var subscribers: [maximum_subscribers]?ipc.Handle = .{null} ** maximum_subscribers;
|
||||
|
||||
/// Publish one event (a ChildAdded or ChildRemoved struct, the same encoding
|
||||
/// the bus drivers send) to every subscriber.
|
||||
fn publishEvent(event: []const u8) void {
|
||||
/// Push one event to every subscriber: the same struct a bus driver *called*
|
||||
/// with, framed as an event instead — one encoding, both directions, told apart
|
||||
/// by the packet's verb rather than by anything inside it. A subscriber whose
|
||||
/// endpoint stops accepting (it died) is dropped on the failed send.
|
||||
fn publish(
|
||||
comptime event: device_manager_protocol.Event,
|
||||
target: u64,
|
||||
payload: device_manager_protocol.Protocol.PayloadOf(event),
|
||||
) void {
|
||||
var packet: [envelope.post_maximum]u8 = undefined;
|
||||
const framed = device_manager_protocol.Protocol.encodeEvent(event, target, payload, &packet) orelse return;
|
||||
for (&subscribers) |*slot| {
|
||||
if (slot.*) |handle| {
|
||||
if (!ipc.send(handle, event)) slot.* = null; // dead subscriber
|
||||
if (!ipc.send(handle, framed)) slot.* = null; // dead subscriber
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -209,8 +225,7 @@ fn pruneChildrenOf(reporter: u32) void {
|
||||
if (child.used and child.reporter == reporter) {
|
||||
std.log.info("child removed (device {d} port {d})", .{ child.parent, child.bus_address });
|
||||
child.used = false;
|
||||
const event = device_manager_protocol.ChildRemoved{ .parent = child.parent, .bus_address = child.bus_address };
|
||||
publishEvent(std.mem.asBytes(&event));
|
||||
publish(.child_removed, 0, .{ .parent = child.parent, .bus_address = child.bus_address });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -395,59 +410,72 @@ fn initialise(endpoint: ipc.Handle) bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
|
||||
if (message.len < 1) return 0;
|
||||
switch (message[0]) {
|
||||
@intFromEnum(device_manager_protocol.Operation.child_added) => return onChildAdded(message, reply, sender),
|
||||
@intFromEnum(device_manager_protocol.Operation.child_removed) => return onChildRemoved(message, reply, sender),
|
||||
@intFromEnum(device_manager_protocol.Operation.enumerate) => return onEnumerate(reply),
|
||||
@intFromEnum(device_manager_protocol.Operation.subscribe) => return onSubscribe(reply, arrived),
|
||||
@intFromEnum(device_manager_protocol.Operation.hello) => {},
|
||||
else => return 0,
|
||||
}
|
||||
if (message.len < device_manager_protocol.hello_size) return 0;
|
||||
const hello = std.mem.bytesToValue(device_manager_protocol.Hello, message[0..device_manager_protocol.hello_size]);
|
||||
/// Set by `onSubscribe` when the subscriber table has taken ownership of the
|
||||
/// capability the call carried, and read by `onMessage`, where the turn's
|
||||
/// `Arrival` lives. The generated dispatch hands a handler the raw handle rather
|
||||
/// than the `Arrival` — deliberately, since a handler has no business closing the
|
||||
/// turn's property — so the *claim* travels back out this way. One turn, one
|
||||
/// handler, one thread: there is nothing here to race.
|
||||
var capability_claimed = false;
|
||||
|
||||
var status: i32 = 0;
|
||||
if (hello.version != device_manager_protocol.version) {
|
||||
status = -1;
|
||||
std.log.info("refused hello (version {d}) from process {d}", .{ hello.version, sender });
|
||||
} else if (driverByProcess(sender)) |driver| {
|
||||
driver.state = .running;
|
||||
std.log.info("hello from {s} (device {d})", .{ driver.name(), hello.device_id });
|
||||
// Resilience drill (V6): once, kill the virtio-gpu driver a moment after it hellos, so
|
||||
// the normal restart policy respawns it — the compositor must survive and re-attach.
|
||||
if (test_scanout_restart_mode and !test_scanout_killed and std.mem.eql(u8, driver.name(), "/system/drivers/virtio-gpu")) {
|
||||
test_scanout_killed = true;
|
||||
test_kill_pid = sender;
|
||||
test_kill_due_ns = time.clock() + 1_500_000_000;
|
||||
_ = time.timerOnce(manager_endpoint, 1600);
|
||||
}
|
||||
} else {
|
||||
status = -1;
|
||||
std.log.info("hello from unknown process {d}", .{sender});
|
||||
}
|
||||
const hello_reply = device_manager_protocol.HelloReply{ .status = status };
|
||||
@memcpy(reply[0..device_manager_protocol.reply_size], std.mem.asBytes(&hello_reply));
|
||||
return device_manager_protocol.reply_size;
|
||||
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
|
||||
capability_claimed = false;
|
||||
const written = Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
|
||||
if (capability_claimed) _ = arrived.take();
|
||||
return written;
|
||||
}
|
||||
|
||||
/// A bus driver reported a discovered device: mirror it, and in
|
||||
/// test-usb-restart mode kill the reporter once after its second child — the
|
||||
const handlers = Serve.Handlers{
|
||||
.hello = onHello,
|
||||
.child_added = onChildAdded,
|
||||
.child_removed = onChildRemoved,
|
||||
.enumerate = onEnumerate,
|
||||
.subscribe = onSubscribe,
|
||||
};
|
||||
|
||||
/// The handshake. The device this driver was assigned is the packet's target.
|
||||
fn onHello(_: void, invocation: Invocation(device_manager_protocol.Hello), _: Answer(void)) isize {
|
||||
if (invocation.request.version != device_manager_protocol.version) {
|
||||
std.log.info("refused hello (version {d}) from process {d}", .{ invocation.request.version, invocation.sender });
|
||||
return -envelope.EPROTO;
|
||||
}
|
||||
const driver = driverByProcess(invocation.sender) orelse {
|
||||
std.log.info("hello from unknown process {d}", .{invocation.sender});
|
||||
return -envelope.EPERM;
|
||||
};
|
||||
driver.state = .running;
|
||||
std.log.info("hello from {s} (device {d})", .{ driver.name(), invocation.target });
|
||||
// Resilience drill (V6): once, kill the virtio-gpu driver a moment after it hellos, so
|
||||
// the normal restart policy respawns it — the compositor must survive and re-attach.
|
||||
if (test_scanout_restart_mode and !test_scanout_killed and std.mem.eql(u8, driver.name(), "/system/drivers/virtio-gpu")) {
|
||||
test_scanout_killed = true;
|
||||
test_kill_pid = invocation.sender;
|
||||
test_kill_due_ns = time.clock() + 1_500_000_000;
|
||||
_ = time.timerOnce(manager_endpoint, 1600);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// A bus driver reported a discovered device: mirror it, publish it, match a
|
||||
/// driver for it — and in the restart drills kill the reporter once, the
|
||||
/// deterministic trigger for prune -> backoff -> respawn -> re-report.
|
||||
fn onChildAdded(message: []const u8, reply: []u8, sender: u32) usize {
|
||||
if (message.len < device_manager_protocol.child_added_size) return 0;
|
||||
const report = std.mem.bytesToValue(device_manager_protocol.ChildAdded, message[0..device_manager_protocol.child_added_size]);
|
||||
var status: i32 = 0;
|
||||
fn onChildAdded(_: void, invocation: Invocation(device_manager_protocol.ChildAdded), _: Answer(void)) isize {
|
||||
const report = invocation.request;
|
||||
const sender = invocation.sender;
|
||||
// The registered kernel device id is the packet's target, not a field: what
|
||||
// the manager hands a matched driver as its argv assignment.
|
||||
const device_id = invocation.target;
|
||||
|
||||
var status: isize = 0;
|
||||
if (driverByProcess(sender)) |driver| {
|
||||
if (!addChild(report.parent, report.bus_address, report.identity, report.device_id, sender)) status = -1;
|
||||
if (!addChild(report.parent, report.bus_address, report.identity, device_id, sender)) status = -envelope.ENOSPC;
|
||||
std.log.info("child added (device {d} port {d}, identity {d}) by {s}", .{ report.parent, report.bus_address, report.identity, driver.name() });
|
||||
if (status == 0) publishEvent(message[0..device_manager_protocol.child_added_size]);
|
||||
if (status == 0) publish(.child_added, device_id, report);
|
||||
// Matching from reports (M19.3), now data-driven via the /system/configuration/devices.csv
|
||||
// registry: a registered child gets the most-specific driver its identity
|
||||
// matches, once — re-reports after a bus restart dedupe on the registered
|
||||
// id, exactly like the registrations do.
|
||||
if (status == 0 and report.device_id != device_manager_protocol.no_device) {
|
||||
if (status == 0 and device_id != device_manager_protocol.no_device) {
|
||||
const id = identityFromReport(report);
|
||||
if (registry.matchDriver(registry_rules[0..registry_count], id)) |match| {
|
||||
if (match.ambiguous)
|
||||
@@ -458,15 +486,13 @@ fn onChildAdded(message: []const u8, reply: []u8, sender: u32) usize {
|
||||
if (!alreadySupervised(match.driver)) addDriver(match.driver, device_manager_protocol.no_device, false);
|
||||
} else {
|
||||
// A per-device driver: one instance, the registered id as argv[1].
|
||||
if (!driverForDevice(report.device_id)) addDriver(match.driver, report.device_id, true);
|
||||
if (!driverForDevice(device_id)) addDriver(match.driver, device_id, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
status = -1;
|
||||
status = -envelope.EPERM;
|
||||
}
|
||||
const report_reply = device_manager_protocol.ReportReply{ .status = status };
|
||||
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
|
||||
if (test_pci_restart_mode and !test_usb_killed) {
|
||||
if (driverByProcess(sender)) |driver| {
|
||||
if (std.mem.eql(u8, driver.name(), "pci-bus") and childCountOf(sender) >= 3) {
|
||||
@@ -494,61 +520,55 @@ fn onChildAdded(message: []const u8, reply: []u8, sender: u32) usize {
|
||||
}
|
||||
}
|
||||
}
|
||||
return @sizeOf(device_manager_protocol.ReportReply);
|
||||
return status;
|
||||
}
|
||||
|
||||
/// A bus driver reported a device gone (hot-unplug; no sender exists yet, but
|
||||
/// the handler is protocol-complete — death-pruning covers removal until then).
|
||||
fn onChildRemoved(message: []const u8, reply: []u8, sender: u32) usize {
|
||||
if (message.len < device_manager_protocol.child_removed_size) return 0;
|
||||
const report = std.mem.bytesToValue(device_manager_protocol.ChildRemoved, message[0..device_manager_protocol.child_removed_size]);
|
||||
var status: i32 = -1;
|
||||
/// A bus driver reported a device gone (hot-unplug). Addressed by the composite
|
||||
/// (parent, bus address) the reporter knows, which is why that pair is the
|
||||
/// packet's body rather than its target.
|
||||
fn onChildRemoved(_: void, invocation: Invocation(device_manager_protocol.ChildRemoved), _: Answer(void)) isize {
|
||||
const report = invocation.request;
|
||||
var status: isize = -envelope.ENOENT;
|
||||
for (&children) |*child| {
|
||||
if (child.used and child.parent == report.parent and child.bus_address == report.bus_address and child.reporter == sender) {
|
||||
if (child.used and child.parent == report.parent and child.bus_address == report.bus_address and child.reporter == invocation.sender) {
|
||||
std.log.info("child removed (device {d} port {d})", .{ child.parent, child.bus_address });
|
||||
child.used = false;
|
||||
status = 0;
|
||||
}
|
||||
}
|
||||
const report_reply = device_manager_protocol.ReportReply{ .status = status };
|
||||
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
|
||||
return @sizeOf(device_manager_protocol.ReportReply);
|
||||
return status;
|
||||
}
|
||||
|
||||
/// An application asked for the tree: the mirror, as a header plus entries.
|
||||
fn onEnumerate(reply: []u8) usize {
|
||||
var count: u32 = 0;
|
||||
var offset: usize = @sizeOf(device_manager_protocol.EnumerateReply);
|
||||
/// The reserved `enumerate` verb: the mirror, one `ChildEntry` per known child,
|
||||
/// packed into the reply's tail. How many arrived is the reply's own length —
|
||||
/// `Status.len` — so no count header is spent saying it twice.
|
||||
fn onEnumerate(_: void, _: Invocation(void), answer: Answer(void)) isize {
|
||||
const entry_size = @sizeOf(device_manager_protocol.ChildEntry);
|
||||
const tail = answer.tail();
|
||||
var written: usize = 0;
|
||||
for (&children) |*child| {
|
||||
if (!child.used) continue;
|
||||
if (offset + @sizeOf(device_manager_protocol.ChildEntry) > reply.len) break;
|
||||
if (written + entry_size > tail.len) break;
|
||||
const entry = device_manager_protocol.ChildEntry{ .parent = child.parent, .bus_address = child.bus_address, .identity = child.identity };
|
||||
@memcpy(reply[offset..][0..@sizeOf(device_manager_protocol.ChildEntry)], std.mem.asBytes(&entry));
|
||||
offset += @sizeOf(device_manager_protocol.ChildEntry);
|
||||
count += 1;
|
||||
@memcpy(tail[written..][0..entry_size], std.mem.asBytes(&entry));
|
||||
written += entry_size;
|
||||
}
|
||||
const header = device_manager_protocol.EnumerateReply{ .status = 0, .count = count };
|
||||
@memcpy(reply[0..@sizeOf(device_manager_protocol.EnumerateReply)], std.mem.asBytes(&header));
|
||||
return offset;
|
||||
return @intCast(written);
|
||||
}
|
||||
|
||||
/// An application subscribed: its endpoint arrived as the call's capability. The
|
||||
/// table taking a slot is what claims it (`take`); a full table refuses and lets
|
||||
/// the turn close it, so a subscribe storm cannot spend the handle table too.
|
||||
fn onSubscribe(reply: []u8, arrived: *ipc.Arrival) usize {
|
||||
var status: i32 = -1;
|
||||
if (arrived.peek() != null) {
|
||||
for (&subscribers) |*slot| {
|
||||
if (slot.* == null) {
|
||||
slot.* = arrived.take(); // claimed: the table holds it from here
|
||||
status = 0;
|
||||
break;
|
||||
}
|
||||
/// The reserved `subscribe` verb: an application's endpoint arrived as the call's
|
||||
/// capability. The table taking a slot is what claims it; a full table refuses
|
||||
/// and lets the turn close it, so a subscribe storm cannot spend the handle table.
|
||||
fn onSubscribe(_: void, invocation: Invocation(void), _: Answer(void)) isize {
|
||||
const endpoint = invocation.capability orelse return -envelope.EPROTO;
|
||||
for (&subscribers) |*slot| {
|
||||
if (slot.* == null) {
|
||||
slot.* = endpoint;
|
||||
capability_claimed = true; // the table holds it from here
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
const report_reply = device_manager_protocol.ReportReply{ .status = status };
|
||||
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
|
||||
return @sizeOf(device_manager_protocol.ReportReply);
|
||||
return -envelope.ENOSPC;
|
||||
}
|
||||
|
||||
fn onNotification(badge: u64) void {
|
||||
|
||||
@@ -902,9 +902,12 @@ fn onPowerEvent(sender: u32, payload: []const u8) void {
|
||||
std.log.info("ignored a power event from pid {d}: /protocol/power is pid {d}", .{ sender, authorized });
|
||||
return;
|
||||
}
|
||||
if (payload.len < 2) return;
|
||||
if (payload[0] != @intFromEnum(power_protocol.Operation.event)) return;
|
||||
if (payload[1] == @intFromEnum(power_protocol.Event.power_button)) shutDown();
|
||||
// Read as an envelope packet, never by byte offset: the kind IS the packet's
|
||||
// verb, so a power event is decoded exactly the way every other event in the
|
||||
// system is. A packet whose operation is not one of this protocol's events —
|
||||
// anything else that lands in this mailbox — decodes to null and is dropped.
|
||||
const kind = power_protocol.Protocol.eventOf(payload) orelse return;
|
||||
if (kind == .power_button) shutDown();
|
||||
}
|
||||
|
||||
/// A supervised boot service died. Find which one and restart it — unless it exited
|
||||
@@ -955,9 +958,11 @@ fn restartChild(id: u32) void {
|
||||
/// init calls owes the same discipline.
|
||||
fn subscribePower() void {
|
||||
const handle = power_endpoint orelse return;
|
||||
const request = power_protocol.Subscribe{};
|
||||
// The reserved `subscribe` verb: nothing but the header, with our own
|
||||
// endpoint riding as the call's capability.
|
||||
const header = envelope.Header{ .operation = envelope.operation_subscribe };
|
||||
var reply: [power_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.callCap(handle, std.mem.asBytes(&request), &reply, supervision_endpoint) catch {};
|
||||
_ = ipc.callCap(handle, std.mem.asBytes(&header), &reply, supervision_endpoint) catch {};
|
||||
}
|
||||
|
||||
/// The stop sequence: persist the log while storage is still up, then terminate
|
||||
@@ -976,9 +981,11 @@ fn shutDown() void {
|
||||
if (child_ids[i] != 0) process.stop(child_ids[i], 2000, supervision_endpoint);
|
||||
}
|
||||
if (power_endpoint) |h| {
|
||||
const request = power_protocol.Shutdown{};
|
||||
var reply: [power_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(h, std.mem.asBytes(&request), &reply) catch {};
|
||||
var packet: [power_protocol.message_maximum]u8 = undefined;
|
||||
if (power_protocol.Protocol.encodeRequest(.shutdown, 0, {}, &.{}, &packet)) |framed| {
|
||||
var reply: [power_protocol.message_maximum]u8 = undefined;
|
||||
_ = ipc.call(h, framed, &reply) catch {};
|
||||
}
|
||||
}
|
||||
// If S5 did not take, init has nothing left to do but idle.
|
||||
while (true) time.sleepMillis(1000);
|
||||
|
||||
Reference in New Issue
Block a user