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:
@@ -61,6 +61,7 @@ pub fn build(b: *std.Build) void {
|
||||
.{ .name = "abi", .module = abi },
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "device-abi", .module = device_abi },
|
||||
.{ .name = "envelope", .module = protocol.module("envelope") },
|
||||
.{ .name = "system-call", .module = system_call },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
@@ -87,6 +88,7 @@ pub fn build(b: *std.Build) void {
|
||||
.root_source_file = b.path("usb/usb.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "envelope", .module = protocol.module("envelope") },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "usb-transfer-protocol", .module = protocol.module("usb-transfer-protocol") },
|
||||
|
||||
@@ -8,6 +8,7 @@ const abi = @import("abi");
|
||||
const device_abi = @import("device-abi");
|
||||
const sc = @import("system-call");
|
||||
const channel = @import("channel");
|
||||
const envelope = @import("envelope");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const device_manager_protocol = @import("device-manager-protocol");
|
||||
@@ -168,6 +169,9 @@ const lookup_pause_ms: u64 = 20;
|
||||
/// (best-effort standalone bring-up) or it refused the handshake. Bus drivers keep the handle
|
||||
/// to report children through; a driver that runs fine unsupervised discards it with `_ =`,
|
||||
/// and one that requires supervision bails on null. Logs the outcome itself.
|
||||
///
|
||||
/// The device this driver was assigned is the packet's `Header.target` — the manager's
|
||||
/// object addressing, so `no_device` here is a driver that serves none.
|
||||
pub fn hello(role: Role, device_id: u64) ?ipc.Handle {
|
||||
var attempts: u32 = 0;
|
||||
const manager = while (attempts < lookup_attempts) : (attempts += 1) {
|
||||
@@ -178,15 +182,25 @@ pub fn hello(role: Role, device_id: u64) ?ipc.Handle {
|
||||
return null;
|
||||
};
|
||||
|
||||
const message = device_manager_protocol.Hello{ .role = @intFromEnum(role), .device_id = device_id };
|
||||
var reply: [device_manager_protocol.reply_size]u8 = undefined;
|
||||
const length = ipc.call(manager, std.mem.asBytes(&message), &reply) catch {
|
||||
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
const framed = device_manager_protocol.Protocol.encodeRequest(
|
||||
.hello,
|
||||
device_id,
|
||||
.{ .role = @intFromEnum(role) },
|
||||
&.{},
|
||||
&packet,
|
||||
) orelse return null;
|
||||
|
||||
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
|
||||
const length = ipc.call(manager, framed, &reply) catch {
|
||||
std.log.info("hello call failed", .{});
|
||||
return null;
|
||||
};
|
||||
if (length < device_manager_protocol.reply_size or
|
||||
std.mem.bytesToValue(device_manager_protocol.HelloReply, reply[0..device_manager_protocol.reply_size]).status != 0)
|
||||
{
|
||||
const status = envelope.statusOf(reply[0..length]) orelse {
|
||||
std.log.info("hello answered nothing readable", .{});
|
||||
return null;
|
||||
};
|
||||
if (status.status != 0) {
|
||||
std.log.info("hello refused", .{});
|
||||
return null;
|
||||
}
|
||||
|
||||
+72
-41
@@ -11,16 +11,24 @@
|
||||
//! _ = device.subscribeInterrupt(address, length); // reports arrive asynchronously
|
||||
//! while (true) { ... ipc.replyWait(device.endpoint, ...) ... } // its own loop
|
||||
//!
|
||||
//! Reports are delivered to `device.endpoint` as asynchronous `InterruptReport`
|
||||
//! messages (the class driver runs a bare `replyWait` loop to read them, because
|
||||
//! the service harness drops buffered-message payloads — see service.zig).
|
||||
//! Reports are delivered to `device.endpoint` as asynchronous `interrupt_report`
|
||||
//! event packets, decoded with `reportOf` (the class driver runs a bare `replyWait`
|
||||
//! loop to read them, because the service harness drops buffered-message payloads
|
||||
//! — see service.zig).
|
||||
//!
|
||||
//! Every packet this file lays down is an envelope packet: the verb and the
|
||||
//! device token in the folded `Header`, the transfer's own fields after it, and
|
||||
//! a control transfer's data stage in the tail.
|
||||
|
||||
const std = @import("std");
|
||||
const channel = @import("channel");
|
||||
const envelope = @import("envelope");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const usb_transfer_protocol = @import("usb-transfer-protocol");
|
||||
|
||||
const Protocol = usb_transfer_protocol.Protocol;
|
||||
|
||||
/// The USB chapter-9 wire ABI and the class taxonomy, re-exported so a class driver reaches
|
||||
/// the whole USB domain through its one `usb` import (`usb.abi.getDescriptor`, `usb.ids.Class`).
|
||||
pub const abi = @import("usb-abi");
|
||||
@@ -57,21 +65,41 @@ pub const Device = struct {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// One request at the bus driver, addressing this device by its token — the
|
||||
/// packet's `Header.target`, so no request body ever names the device again.
|
||||
/// Null covers both a failed transport and a refusal: a class driver has the
|
||||
/// same recourse either way.
|
||||
fn call(
|
||||
self: *Device,
|
||||
comptime operation: Protocol.Operation,
|
||||
request: Protocol.RequestOf(operation),
|
||||
tail: []const u8,
|
||||
capability: ?ipc.Handle,
|
||||
reply: []u8,
|
||||
) ?[]u8 {
|
||||
var packet: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
const framed = Protocol.encodeRequest(operation, self.token, request, tail, &packet) orelse return null;
|
||||
const answer = ipc.callCap(self.bus, framed, reply, capability) catch return null;
|
||||
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
|
||||
if (status.status != 0) return null;
|
||||
return reply[0..answer.len];
|
||||
}
|
||||
|
||||
/// The data stage rides the tail in both directions, so the answer's length
|
||||
/// *is* the transferred length — `Status.len`, which the envelope stamps.
|
||||
fn controlTransfer(self: *Device, setup: [8]u8, direction_in: bool, data: []u8) ?usize {
|
||||
var request = usb_transfer_protocol.ControlRequest{
|
||||
.device_token = self.token,
|
||||
if (data.len > usb_transfer_protocol.max_inline_data) return null;
|
||||
const outgoing: []const u8 = if (direction_in) &.{} else data;
|
||||
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
const answered = self.call(.control, .{
|
||||
.setup = setup,
|
||||
.direction_in = @intFromBool(direction_in),
|
||||
.data_length = @intCast(data.len),
|
||||
};
|
||||
if (!direction_in and data.len > 0) @memcpy(request.data[0..data.len], data);
|
||||
var reply: [@sizeOf(usb_transfer_protocol.ControlReply)]u8 = undefined;
|
||||
const length = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return null;
|
||||
if (length < @sizeOf(usb_transfer_protocol.ControlReply)) return null;
|
||||
const control_reply = std.mem.bytesToValue(usb_transfer_protocol.ControlReply, reply[0..@sizeOf(usb_transfer_protocol.ControlReply)]);
|
||||
if (control_reply.status != 0) return null;
|
||||
const actual = @min(control_reply.actual_length, data.len);
|
||||
if (direction_in and actual > 0) @memcpy(data[0..actual], control_reply.data[0..actual]);
|
||||
}, outgoing, null, &reply) orelse return null;
|
||||
|
||||
const returned = Protocol.replyTail(.control, answered);
|
||||
const actual = @min(returned.len, data.len);
|
||||
if (direction_in and actual > 0) @memcpy(data[0..actual], returned[0..actual]);
|
||||
return actual;
|
||||
}
|
||||
|
||||
@@ -89,15 +117,11 @@ pub const Device = struct {
|
||||
/// Begin periodic IN polling of an interrupt endpoint; reports flow back to
|
||||
/// `self.endpoint` as asynchronous `InterruptReport` messages.
|
||||
pub fn subscribeInterrupt(self: *Device, endpoint_address: u8, max_length: u16) bool {
|
||||
var request = usb_transfer_protocol.InterruptSubscribeRequest{
|
||||
.device_token = self.token,
|
||||
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
return self.call(.interrupt_subscribe, .{
|
||||
.endpoint_address = endpoint_address,
|
||||
.max_length = max_length,
|
||||
};
|
||||
var reply: [@sizeOf(usb_transfer_protocol.InterruptSubscribeReply)]u8 = undefined;
|
||||
const length = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return false;
|
||||
if (length < @sizeOf(usb_transfer_protocol.InterruptSubscribeReply)) return false;
|
||||
return std.mem.bytesToValue(usb_transfer_protocol.InterruptSubscribeReply, reply[0..@sizeOf(usb_transfer_protocol.InterruptSubscribeReply)]).status == 0;
|
||||
}, &.{}, null, &reply) != null;
|
||||
}
|
||||
|
||||
/// Hand the controller a DMA-region capability (`handle` — from a `shareable`
|
||||
@@ -106,31 +130,33 @@ pub const Device = struct {
|
||||
/// will name in a `bulk` transfer, before the transfer. Harmless (and a no-op
|
||||
/// success) when no IOMMU is enforcing. Returns false on failure.
|
||||
pub fn attachDma(self: *Device, handle: ipc.Handle) bool {
|
||||
var request = usb_transfer_protocol.DmaAttachRequest{ .device_token = self.token };
|
||||
var reply: [@sizeOf(usb_transfer_protocol.DmaAttachReply)]u8 = undefined;
|
||||
const result = ipc.callCap(self.bus, std.mem.asBytes(&request), &reply, handle) catch return false;
|
||||
if (result.len < @sizeOf(usb_transfer_protocol.DmaAttachReply)) return false;
|
||||
return std.mem.bytesToValue(usb_transfer_protocol.DmaAttachReply, reply[0..@sizeOf(usb_transfer_protocol.DmaAttachReply)]).status == 0;
|
||||
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
return self.call(.dma_attach, {}, &.{}, handle, &reply) != null;
|
||||
}
|
||||
|
||||
/// One bulk transfer (IN or OUT per `endpoint_address`'s direction bit) to or
|
||||
/// from the caller's own DMA buffer at `physical`. Returns the bytes moved.
|
||||
pub fn bulk(self: *Device, endpoint_address: u8, physical: u64, length: u32) ?u32 {
|
||||
var request = usb_transfer_protocol.BulkRequest{
|
||||
.device_token = self.token,
|
||||
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
const answered = self.call(.bulk, .{
|
||||
.physical_address = physical,
|
||||
.length = length,
|
||||
.endpoint_address = endpoint_address,
|
||||
};
|
||||
var reply: [@sizeOf(usb_transfer_protocol.BulkReply)]u8 = undefined;
|
||||
const replied = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return null;
|
||||
if (replied < @sizeOf(usb_transfer_protocol.BulkReply)) return null;
|
||||
const bulk_reply = std.mem.bytesToValue(usb_transfer_protocol.BulkReply, reply[0..@sizeOf(usb_transfer_protocol.BulkReply)]);
|
||||
if (bulk_reply.status != 0) return null;
|
||||
return bulk_reply.actual_length;
|
||||
}, &.{}, null, &reply) orelse return null;
|
||||
return (Protocol.decodeReply(.bulk, answered) orelse return null).actual_length;
|
||||
}
|
||||
};
|
||||
|
||||
/// Decode one asynchronous interrupt report out of a packet that arrived on the
|
||||
/// class driver's own endpoint. Null when it is not one — a stray message, or a
|
||||
/// packet too short to carry the report it names. The device it came from is the
|
||||
/// packet's `Header.target`, which a single-device class driver never has to read.
|
||||
pub fn reportOf(packet: []const u8) ?InterruptReport {
|
||||
const event = Protocol.eventOf(packet) orelse return null;
|
||||
if (event != .interrupt_report) return null;
|
||||
return Protocol.decodeEvent(.interrupt_report, packet);
|
||||
}
|
||||
|
||||
/// Open `/protocol/usb-transfer` and, on that channel, open the device with the
|
||||
/// assigned id, handing over a freshly created endpoint for asynchronous interrupt
|
||||
/// reports. Retries while the bus is still coming up (a class driver races the bus
|
||||
@@ -144,12 +170,17 @@ pub fn open(device_id: u64) ?Device {
|
||||
} else return null;
|
||||
|
||||
const endpoint = ipc.createIpcEndpoint() orelse return null;
|
||||
var request = usb_transfer_protocol.OpenRequest{ .device_id = device_id };
|
||||
var reply: [@sizeOf(usb_transfer_protocol.OpenReply)]u8 = undefined;
|
||||
const result = ipc.callCap(bus, std.mem.asBytes(&request), &reply, endpoint) catch return null;
|
||||
if (result.len < @sizeOf(usb_transfer_protocol.OpenReply)) return null;
|
||||
const open_reply = std.mem.bytesToValue(usb_transfer_protocol.OpenReply, reply[0..@sizeOf(usb_transfer_protocol.OpenReply)]);
|
||||
if (open_reply.status != 0) return null;
|
||||
// The assigned device id is the target: it is what the caller has before a
|
||||
// token exists, and the token the reply hands back addresses every packet
|
||||
// after this one.
|
||||
var packet: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
const framed = Protocol.encodeRequest(.open, device_id, {}, &.{}, &packet) orelse return null;
|
||||
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
|
||||
const result = ipc.callCap(bus, framed, &reply, endpoint) catch return null;
|
||||
const answered = reply[0..result.len];
|
||||
const status = envelope.statusOf(answered) orelse return null;
|
||||
if (status.status != 0) return null;
|
||||
const open_reply = Protocol.decodeReply(.open, answered) orelse return null;
|
||||
|
||||
var device = Device{
|
||||
.bus = bus,
|
||||
|
||||
@@ -58,6 +58,9 @@ pub fn build(b: *std.Build) void {
|
||||
"vfs/vfs-protocol.zig", // NodeKind / DirectoryEntry sizes + op values
|
||||
"input/input-protocol.zig", // event numbering + the push-floor budget
|
||||
"display/display-protocol.zig", // pack(): native pixel encoding per format
|
||||
"device-manager/device-manager-protocol.zig", // the dual-use report, exactly on the push floor
|
||||
"power/power-protocol.zig", // the event kind as the packet's verb
|
||||
"usb-transfer/usb-transfer-protocol.zig", // the tail-carried control stage + the trimmed report
|
||||
}) |root| {
|
||||
const protocol_tests = b.addTest(.{
|
||||
.root_module = b.createModule(.{
|
||||
|
||||
@@ -1,15 +1,48 @@
|
||||
//! The device-manager protocol (docs/device-manager.md): what drivers and
|
||||
//! applications say to the device manager over its well-known endpoint. The
|
||||
//! vfs-protocol pattern — extern-struct messages, a version in the handshake,
|
||||
//! reserved fields — so both sides depend on the contract by name. Deliberately
|
||||
//! contains nothing lifecycle-shaped: stopping, liveness (the zero-length ping),
|
||||
//! and exit reasons are the universal vocabulary of
|
||||
//! The device-manager protocol (docs/device-driver-development/device-manager.md):
|
||||
//! what drivers and applications say to the device manager over
|
||||
//! `/protocol/device-manager`. Defined through the envelope
|
||||
//! (docs/os-development/protocol-namespace.md), so every packet — request, reply,
|
||||
//! and pushed event alike — begins with the folded `Header`.
|
||||
//!
|
||||
//! **`Header.target` is the device id.** It was the `device_id` field of three
|
||||
//! different messages; folding it into the header is what made the packed
|
||||
//! leading operation byte disappear along with it. `no_device` addresses a
|
||||
//! driver that serves no enumerated device.
|
||||
//!
|
||||
//! Two of the manager's four old operations were the reserved verbs under
|
||||
//! another name and are gone from this protocol's own numbering: `enumerate`
|
||||
//! (the tree, one `ChildEntry` per record in the reply tail) and `subscribe`
|
||||
//! (the watcher's endpoint rides as the call's capability). What is left is the
|
||||
//! driver-facing half — the handshake and the two tree reports.
|
||||
//!
|
||||
//! **`ChildAdded` travels in both directions, and says so twice.** A bus driver
|
||||
//! *calls* `child_added` to report a device; the manager then *pushes* the same
|
||||
//! struct to every subscriber as the `child_added` event. Operations and events
|
||||
//! are numbered in separate spaces, so one struct under two numbers is exactly
|
||||
//! how the envelope spells "one encoding, both directions" — and the direction
|
||||
//! (call vs. send) already tells them apart.
|
||||
//!
|
||||
//! Deliberately contains nothing lifecycle-shaped: stopping, liveness (the
|
||||
//! zero-length ping), and exit reasons are the universal vocabulary of
|
||||
//! docs/process-lifecycle.md, not this protocol.
|
||||
|
||||
/// The protocol version a driver states in its hello. A manager that cannot
|
||||
/// serve a driver's version refuses the hello, and the mismatch is loud at
|
||||
/// startup instead of quiet corruption later.
|
||||
pub const version: u16 = 1;
|
||||
const std = @import("std");
|
||||
const envelope = @import("envelope");
|
||||
|
||||
/// The protocol version a driver states in its hello, and the version this
|
||||
/// contract answers `describe` with. A manager that cannot serve a driver's
|
||||
/// version refuses the hello, and the mismatch is loud at startup instead of
|
||||
/// quiet corruption later.
|
||||
///
|
||||
/// `describe` publishes the same number, but it cannot replace this: it tells a
|
||||
/// *client* what the provider is, and here it is the **provider** that has to
|
||||
/// learn what the client was built against in order to refuse it.
|
||||
pub const version = 1;
|
||||
|
||||
/// `Header.target` for a driver that serves no enumerated device (a test
|
||||
/// fixture, a synthetic source), and `ChildAdded`'s answer for a leaf that was
|
||||
/// never `device_register`ed.
|
||||
pub const no_device: u64 = ~@as(u64, 0);
|
||||
|
||||
/// Which bus a `child_added` came from — stated by the reporting bus driver so
|
||||
/// the manager's /system/configuration/devices.csv matcher knows how to read the report's identity
|
||||
@@ -24,7 +57,7 @@ pub const BusKind = enum(u8) {
|
||||
acpi = 3,
|
||||
};
|
||||
|
||||
/// What kind of driver is talking (docs/driver-model.md's shapes).
|
||||
/// What kind of driver is talking (docs/device-driver-development/driver-model.md's shapes).
|
||||
pub const Role = enum(u8) {
|
||||
/// Owns a controller and reports the devices behind it (`child_added`).
|
||||
bus = 1,
|
||||
@@ -32,58 +65,45 @@ pub const Role = enum(u8) {
|
||||
device = 2,
|
||||
};
|
||||
|
||||
/// The message kinds.
|
||||
pub const Operation = enum(u8) {
|
||||
hello = 1,
|
||||
child_added = 2,
|
||||
child_removed = 3,
|
||||
enumerate = 4,
|
||||
subscribe = 5,
|
||||
};
|
||||
|
||||
/// `Hello.device_id` for a driver that serves no enumerated device (a test
|
||||
/// fixture, a synthetic source).
|
||||
pub const no_device: u64 = ~@as(u64, 0);
|
||||
// --- the per-operation request parts ----------------------------------------
|
||||
//
|
||||
// Each names the bytes AFTER the prefix. Nothing here carries an operation or a
|
||||
// device id: those are the packet header's, folded in once. No reply part
|
||||
// carries a status either — that is the `Status` every reply already begins
|
||||
// with, so the manager's old three `{status, reserved}` reply structs are gone.
|
||||
|
||||
/// The handshake, sent once by every driver the manager spawns — the manager's
|
||||
/// one self-enforced deadline: spawned and silent past it means wrong binary,
|
||||
/// wrong version, or wedged before main, and the stop sequence follows.
|
||||
/// wrong version, or wedged before main, and the stop sequence follows. The
|
||||
/// device this driver was assigned (its argv[1]) is `Header.target`.
|
||||
pub const Hello = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.hello),
|
||||
/// A Role value.
|
||||
/// A `Role` value.
|
||||
role: u8,
|
||||
_padding: u8 = 0,
|
||||
/// The protocol version this driver was built against (`version`).
|
||||
version: u16 = version,
|
||||
reserved: u32 = 0,
|
||||
/// The device this driver was assigned (its argv[1]), or `no_device`.
|
||||
device_id: u64,
|
||||
};
|
||||
|
||||
pub const hello_size = @sizeOf(Hello);
|
||||
|
||||
/// The manager's answer to a hello. Nonzero status = refused (version mismatch,
|
||||
/// unknown sender); a refused driver should exit cleanly.
|
||||
pub const HelloReply = extern struct {
|
||||
status: i32,
|
||||
reserved: u32 = 0,
|
||||
};
|
||||
|
||||
pub const reply_size = @sizeOf(HelloReply);
|
||||
|
||||
/// A bus driver reporting one device it discovered behind its controller
|
||||
/// (docs/device-manager.md "the tree"). Identity is the bus's native language —
|
||||
/// for USB a port-speed class; the (class, subclass, protocol) triple joins it
|
||||
/// once control transfers exist (the USB track). The manager mirrors the child
|
||||
/// into its tree; when the reporting driver dies, the manager prunes everything
|
||||
/// it reported (the children describe protocol state that died with it) and the
|
||||
/// restarted instance rediscovers and re-reports.
|
||||
/// (docs/device-driver-development/device-manager.md "the tree"), and the payload
|
||||
/// the manager pushes to its subscribers for the same event. Identity is the
|
||||
/// bus's native language — for USB a port-speed class, for PCI the class triple.
|
||||
/// The manager mirrors the child into its tree; when the reporting driver dies,
|
||||
/// the manager prunes everything it reported (the children describe protocol
|
||||
/// state that died with it) and the restarted instance rediscovers and
|
||||
/// re-reports.
|
||||
///
|
||||
/// `Header.target` is the kernel device id this child was `device_register`ed
|
||||
/// as — what the manager hands a matched driver as its argv assignment — or
|
||||
/// `no_device` for an unregistered leaf (a USB port before the descriptor
|
||||
/// track). That is the field that used to sit at the end of this struct.
|
||||
///
|
||||
/// **The field order is the size budget.** An event packet is the header plus
|
||||
/// this, within 64 bytes, and three `u64`s round the whole struct up to a
|
||||
/// multiple of eight whatever order they sit in — so the small fields are
|
||||
/// packed tail-first into the space the rounding pays for anyway. `Define`
|
||||
/// checks the result; this comment is why there is no slack in it.
|
||||
pub const ChildAdded = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.child_added),
|
||||
/// A `BusKind` value: which bus reported this child, so the manager reads the
|
||||
/// identity in the right namespace and matches against the right `bus` column.
|
||||
bus: u8 = @intFromEnum(BusKind.unknown),
|
||||
reserved1: u16 = 0,
|
||||
reserved2: u32 = 0,
|
||||
/// The reporting driver's own device (the controller) — the child's parent.
|
||||
parent: u64,
|
||||
/// Where on the bus (for USB: the root port number, 1-based).
|
||||
@@ -91,10 +111,10 @@ pub const ChildAdded = extern struct {
|
||||
/// Bus-specific identity (for USB: the PORTSC port-speed class; for PCI:
|
||||
/// the class triple; for ACPI devices, 0 — identity is the hid below).
|
||||
identity: u64,
|
||||
/// The kernel device id this child was `device_register`ed as — what the
|
||||
/// manager hands a matched driver as its argv assignment — or `no_device`
|
||||
/// for an unregistered leaf (a USB port before the descriptor track).
|
||||
device_id: u64 = no_device,
|
||||
/// The PCI subsystem id, packed `(subsystem_vendor << 16) | subsystem_device`
|
||||
/// (so it reads vendor-first, matching the CSV's `ssvid:ssid`), or 0 when the
|
||||
/// device has no subsystem id (a bridge, or a non-PCI bus).
|
||||
subsystem: u32 = 0,
|
||||
/// The vendor id (PCI vendor / USB idVendor), or 0 when the bus has no such
|
||||
/// concept (ACPI). Carried so the manager's /system/configuration/devices.csv matcher can bind
|
||||
/// on vendor — a level the bus-native `identity` (a class triple) cannot express.
|
||||
@@ -103,73 +123,118 @@ pub const ChildAdded = extern struct {
|
||||
/// level: this is what lets one virtio-gpu (1AF4:1050) be told from any other
|
||||
/// virtio display function without the driver re-confirming after it is spawned.
|
||||
device: u16 = 0,
|
||||
/// The PCI subsystem id, packed `(subsystem_vendor << 16) | subsystem_device`
|
||||
/// (so it reads vendor-first, matching the CSV's `ssvid:ssid`), or 0 when the
|
||||
/// device has no subsystem id (a bridge, or a non-PCI bus).
|
||||
subsystem: u32 = 0,
|
||||
/// The ACPI hardware id (`_HID`), EISA-decoded (e.g. "PNP0303"), for devices
|
||||
/// discovered by firmware string rather than a numeric bus identity. Empty
|
||||
/// (all zero) otherwise. Widens for FDT `compatible` strings later.
|
||||
hid: [8]u8 = .{0} ** 8,
|
||||
/// A `BusKind` value: which bus reported this child, so the manager reads the
|
||||
/// identity in the right namespace and matches against the right `bus` column.
|
||||
bus: u8 = @intFromEnum(BusKind.unknown),
|
||||
_padding: [7]u8 = .{0} ** 7,
|
||||
};
|
||||
|
||||
pub const child_added_size = @sizeOf(ChildAdded);
|
||||
|
||||
/// A bus driver reporting a device gone (hot-unplug). Not yet sent by any
|
||||
/// driver — the port scan has no unplug interrupt — but the manager handles it;
|
||||
/// death-pruning covers removal until hotplug lands.
|
||||
/// A bus driver reporting a device gone (hot-unplug), and the payload pushed to
|
||||
/// subscribers for it.
|
||||
///
|
||||
/// **This is the one message whose target stays 0.** A removal is addressed by
|
||||
/// the composite (parent, bus address) — the reporter knows where the device
|
||||
/// *was*, not necessarily what id it had been registered under — and a single
|
||||
/// `u64` cannot carry a pair. So the address stays in the payload, where it
|
||||
/// always was, and the header addresses the provider itself.
|
||||
pub const ChildRemoved = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.child_removed),
|
||||
reserved0: u8 = 0,
|
||||
reserved1: u16 = 0,
|
||||
reserved2: u32 = 0,
|
||||
parent: u64,
|
||||
bus_address: u64,
|
||||
};
|
||||
|
||||
pub const child_removed_size = @sizeOf(ChildRemoved);
|
||||
|
||||
/// The manager's answer to a tree report.
|
||||
pub const ReportReply = extern struct {
|
||||
status: i32,
|
||||
reserved: u32 = 0,
|
||||
};
|
||||
|
||||
/// An application asking for the tree (M18.3): the reply is an EnumerateReply
|
||||
/// header followed by `count` ChildEntry records.
|
||||
pub const Enumerate = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.enumerate),
|
||||
reserved0: u8 = 0,
|
||||
reserved1: u16 = 0,
|
||||
reserved2: u32 = 0,
|
||||
};
|
||||
|
||||
pub const EnumerateReply = extern struct {
|
||||
status: i32,
|
||||
/// ChildEntry records following this header.
|
||||
count: u32,
|
||||
};
|
||||
|
||||
/// One record of the reserved `enumerate` reply: the manager's mirror, one
|
||||
/// entry per known child, packed into the reply tail. The count is
|
||||
/// `Status.len / @sizeOf(ChildEntry)` — the envelope's reply length says how
|
||||
/// many arrived, so no count header is spent on saying it twice.
|
||||
pub const ChildEntry = extern struct {
|
||||
parent: u64,
|
||||
bus_address: u64,
|
||||
identity: u64,
|
||||
};
|
||||
|
||||
/// An application subscribing to published add/remove events (the input-service
|
||||
/// pattern): the subscriber's endpoint rides as the call's **capability**, and
|
||||
/// events arrive on it as buffered messages whose payload is the same
|
||||
/// ChildAdded / ChildRemoved struct the bus drivers send — one encoding, both
|
||||
/// directions.
|
||||
pub const Subscribe = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.subscribe),
|
||||
reserved0: u8 = 0,
|
||||
reserved1: u16 = 0,
|
||||
reserved2: u32 = 0,
|
||||
};
|
||||
/// How many `ChildEntry` records one `enumerate` reply can carry. Paging joins
|
||||
/// the protocol if a tree ever outgrows one packet.
|
||||
pub const entries_per_reply: usize = (envelope.packet_maximum - envelope.prefix_size) / @sizeOf(ChildEntry);
|
||||
|
||||
/// Upper bound on any message in this protocol — sizes the endpoint buffers.
|
||||
/// Capped by the kernel's IPC MESSAGE_MAXIMUM (256): an EnumerateReply carries
|
||||
/// up to ten ChildEntry records per call, plenty for the mirror's current
|
||||
/// bounds; paging joins the protocol if a tree ever outgrows one message.
|
||||
pub const message_maximum = 256;
|
||||
pub const Protocol = envelope.Define(.{
|
||||
.name = "device-manager",
|
||||
.version = version,
|
||||
.operations = &.{
|
||||
// The driver-facing half. `enumerate` and `subscribe` are not here: they
|
||||
// are the reserved verbs, which mean the same thing at every provider.
|
||||
.{ .name = "hello", .request = Hello },
|
||||
.{ .name = "child_added", .request = ChildAdded },
|
||||
.{ .name = "child_removed", .request = ChildRemoved },
|
||||
},
|
||||
.events = &.{
|
||||
// The watcher-facing half — the same two structs, pushed rather than
|
||||
// called, in the events' own numbering space.
|
||||
.{ .name = "child_added", .payload = ChildAdded },
|
||||
.{ .name = "child_removed", .payload = ChildRemoved },
|
||||
},
|
||||
});
|
||||
|
||||
pub const Operation = Protocol.Operation;
|
||||
pub const Event = Protocol.Event;
|
||||
|
||||
/// What the manager sizes its buffers to — the call floor, as every protocol does.
|
||||
pub const message_maximum: usize = Protocol.message_maximum;
|
||||
|
||||
test "a tree report fits the push floor with the header folded in" {
|
||||
// The dual-use struct is the tight one: `child_added` is both a call and an
|
||||
// event, and the event floor is 64 bytes *including* the header. Forty-one
|
||||
// bytes of content, rounded to 48 by the three u64s' alignment, plus the
|
||||
// 16-byte header — exactly on the floor, which is what folding the operation
|
||||
// byte and the device id out of the payload bought.
|
||||
try std.testing.expectEqual(@as(usize, 48), @sizeOf(ChildAdded));
|
||||
try std.testing.expectEqual(envelope.post_maximum, Protocol.event_maximum);
|
||||
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
|
||||
// Ten records per enumerate reply — what the old count-header layout carried.
|
||||
try std.testing.expectEqual(@as(usize, 10), entries_per_reply);
|
||||
}
|
||||
|
||||
test "the verb and event numbering, and the device id in the header" {
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.hello));
|
||||
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Operation.child_added));
|
||||
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Operation.child_removed));
|
||||
// Events number in their own space, so the same two reports start at 16 too.
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.child_added));
|
||||
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Event.child_removed));
|
||||
// The manager's own enumerate/subscribe became the RESERVED verbs, below the
|
||||
// protocol range entirely.
|
||||
try std.testing.expectEqual(@as(u32, 1), envelope.operation_enumerate);
|
||||
try std.testing.expectEqual(@as(u32, 2), envelope.operation_subscribe);
|
||||
|
||||
var buffer: [message_maximum]u8 = undefined;
|
||||
const hello = Protocol.encodeRequest(.hello, 7, .{ .role = @intFromEnum(Role.bus) }, &.{}, &buffer).?;
|
||||
try std.testing.expectEqual(@as(u64, 7), envelope.headerOf(hello).?.target);
|
||||
try std.testing.expectEqual(@as(u16, 1), Protocol.decodeRequest(.hello, hello).?.version);
|
||||
}
|
||||
|
||||
test "one struct, two numbers: the report a bus calls and the event a watcher is pushed" {
|
||||
const report = ChildAdded{
|
||||
.parent = 3,
|
||||
.bus_address = 1,
|
||||
.identity = 0x030000,
|
||||
.bus = @intFromEnum(BusKind.pci),
|
||||
.vendor = 0x1AF4,
|
||||
};
|
||||
|
||||
var call: [message_maximum]u8 = undefined;
|
||||
const called = Protocol.encodeRequest(.child_added, 42, report, &.{}, &call).?;
|
||||
try std.testing.expectEqual(Operation.child_added, Protocol.operationOf(called).?);
|
||||
try std.testing.expectEqual(@as(u64, 42), envelope.headerOf(called).?.target);
|
||||
|
||||
var push: [envelope.post_maximum]u8 = undefined;
|
||||
const pushed = Protocol.encodeEvent(.child_added, 42, report, &push).?;
|
||||
try std.testing.expectEqual(envelope.post_maximum, pushed.len);
|
||||
try std.testing.expectEqual(Event.child_added, Protocol.eventOf(pushed).?);
|
||||
try std.testing.expectEqual(@as(u16, 0x1AF4), Protocol.decodeEvent(.child_added, pushed).?.vendor);
|
||||
// Same bytes after the prefix, different verb in it — the direction is what
|
||||
// tells a call from a push, and the numbering spaces never collide.
|
||||
try std.testing.expectEqualSlices(u8, called[envelope.prefix_size..], pushed[envelope.prefix_size..]);
|
||||
}
|
||||
|
||||
@@ -1,70 +1,104 @@
|
||||
//! The power protocol (docs/power.md): system power's domain-named surface,
|
||||
//! bound at `/protocol/power`. On x86 the acpi service provides it; on ARM a
|
||||
//! PSCI/mailbox service will bind the same name — subscribers never learn which
|
||||
//! firmware they are on (docs/discovery.md — firmware neutrality), which is the
|
||||
//! whole point of naming the contract rather than the provider
|
||||
//! (docs/os-development/protocol-namespace.md).
|
||||
//! The vfs-protocol pattern: extern-struct messages, a version, reserved fields.
|
||||
//! The power protocol (docs/os-development/power.md): system power's
|
||||
//! domain-named surface, bound at `/protocol/power`. On x86 the acpi service
|
||||
//! provides it; on ARM a PSCI/mailbox service will bind the same name —
|
||||
//! subscribers never learn which firmware they are on (docs/discovery.md —
|
||||
//! firmware neutrality), which is the whole point of naming the contract rather
|
||||
//! than the provider (docs/os-development/protocol-namespace.md).
|
||||
//!
|
||||
//! Defined through the envelope, so every packet begins with the folded
|
||||
//! `Header`. Three shapes ride the channel, and the envelope names all three:
|
||||
//!
|
||||
//! - **subscribe** is the *reserved* verb, not one of this protocol's own: a
|
||||
//! synchronous call whose attached capability is the subscriber's endpoint is
|
||||
//! exactly what `envelope.operation_subscribe` means everywhere.
|
||||
//! - **shutdown** is this protocol's one verb — the only operation that *does*
|
||||
//! something irreversible, and the reason the provider gates it by badge.
|
||||
//! - **the events** are pushes: the service `ipc_send`s each one to every
|
||||
//! subscriber, no reply owed, so a slow or dead subscriber can never wedge the
|
||||
//! source. **The kind is the packet's operation** — one declared event per
|
||||
//! named kind, exactly as the input protocol delivers one per device class —
|
||||
//! so a subscriber reads *what happened* out of the header instead of a tag
|
||||
//! inside the payload. That is what the old `EventMessage`'s two leading bytes
|
||||
//! (an operation byte saying "this is an event", then the kind) fold into.
|
||||
//!
|
||||
//! `Header.target` is unused (0) in both directions: the provider is the only
|
||||
//! object either side addresses. And no packet carries a version any more — the
|
||||
//! reserved `describe` verb is the version handshake, asked once at connect time
|
||||
//! rather than re-carried out of every packet's budget.
|
||||
|
||||
/// The protocol version a client states nowhere yet — reserved for the day a
|
||||
/// handshake needs it; requests carry it so a mismatch can be refused loudly.
|
||||
pub const version: u16 = 1;
|
||||
const std = @import("std");
|
||||
const envelope = @import("envelope");
|
||||
|
||||
pub const Operation = enum(u8) {
|
||||
/// Subscribe to power events: the subscriber's endpoint rides as the
|
||||
/// call's capability (the input/device-manager pattern); events arrive on
|
||||
/// it as buffered messages carrying an `EventMessage`.
|
||||
subscribe = 1,
|
||||
/// Orderly shutdown's last step: enter S5. Accepted only from PID 1
|
||||
/// (init) — the process that has already run the stop sequence over
|
||||
/// everything else.
|
||||
shutdown = 2,
|
||||
/// The published event payload (never sent *to* the service).
|
||||
event = 3,
|
||||
};
|
||||
|
||||
/// What happened. The vocabulary is hardware-neutral: a lid is a lid whether
|
||||
/// ACPI or a PSCI mailbox reported it.
|
||||
pub const Event = enum(u8) {
|
||||
power_button = 1,
|
||||
lid = 2,
|
||||
ac = 3,
|
||||
battery = 4,
|
||||
/// A device notification that maps to none of the named events — the
|
||||
/// `code` and `hid` fields say which device and what code.
|
||||
notify = 5,
|
||||
};
|
||||
|
||||
pub const Subscribe = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.subscribe),
|
||||
reserved0: u8 = 0,
|
||||
version: u16 = version,
|
||||
reserved1: u32 = 0,
|
||||
};
|
||||
|
||||
pub const Shutdown = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.shutdown),
|
||||
reserved0: u8 = 0,
|
||||
version: u16 = version,
|
||||
reserved1: u32 = 0,
|
||||
};
|
||||
|
||||
/// A published event, as the buffered-message payload subscribers receive.
|
||||
pub const EventMessage = extern struct {
|
||||
operation: u8 = @intFromEnum(Operation.event),
|
||||
/// An Event value.
|
||||
event: u8,
|
||||
reserved0: u16 = 0,
|
||||
/// The device notification code (Notify's second argument), or 0.
|
||||
/// What a published event carries beyond its kind. The kind is the packet's
|
||||
/// operation, so nothing here repeats it; `power_button`, `lid`, `ac` and
|
||||
/// `battery` leave both fields zero and are fully described by the verb alone.
|
||||
pub const Notice = extern struct {
|
||||
/// The device notification code (ACPI `Notify`'s second argument), or 0.
|
||||
code: u32 = 0,
|
||||
/// The notifying device's hardware id (EISA-decoded), or all zero.
|
||||
hid: [8]u8 = .{0} ** 8,
|
||||
};
|
||||
|
||||
pub const Reply = extern struct {
|
||||
status: i32,
|
||||
reserved: u32 = 0,
|
||||
};
|
||||
pub const Protocol = envelope.Define(.{
|
||||
.name = "power",
|
||||
.version = 1,
|
||||
.operations = &.{
|
||||
// Orderly shutdown's last step: enter S5. Honored only from a
|
||||
// subscriber — init, the process that has already run the stop sequence
|
||||
// over everything else (docs/os-development/power.md, "authority, not
|
||||
// information"). Nothing to say and nothing to answer, so the verb and
|
||||
// the reply's `Status` are the whole exchange.
|
||||
.{ .name = "shutdown" },
|
||||
},
|
||||
.events = &.{
|
||||
// The vocabulary is hardware-neutral: a lid is a lid whether ACPI or a
|
||||
// PSCI mailbox reported it. One event per kind, each carrying the same
|
||||
// `Notice`, because what differs between them is which thing happened —
|
||||
// and that is the header's job now.
|
||||
.{ .name = "power_button", .payload = Notice },
|
||||
.{ .name = "lid", .payload = Notice },
|
||||
.{ .name = "ac", .payload = Notice },
|
||||
.{ .name = "battery", .payload = Notice },
|
||||
// A device notification that maps to none of the named events — the
|
||||
// `code` and `hid` say which device and what happened.
|
||||
.{ .name = "notify", .payload = Notice },
|
||||
},
|
||||
});
|
||||
|
||||
/// Upper bound on any message in this protocol — sizes endpoint buffers.
|
||||
pub const message_maximum = 64;
|
||||
pub const Operation = Protocol.Operation;
|
||||
|
||||
/// What happened. The event *is* the kind: this is the generated event
|
||||
/// enumeration, re-exported under the name this protocol has always called its
|
||||
/// vocabulary, with the same members it has always had.
|
||||
pub const Event = Protocol.Event;
|
||||
|
||||
/// What a provider and a subscriber size their buffers to. This module used to
|
||||
/// declare 64 — the *push* floor — which was simply wrong for a protocol whose
|
||||
/// requests ride `ipc_call`: a provider sizing its receive buffer to 64 refuses
|
||||
/// any caller that sends up to the floor it is entitled to.
|
||||
pub const message_maximum: usize = Protocol.message_maximum;
|
||||
|
||||
test "the kind is the verb, and an event fits the push floor" {
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.shutdown));
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.power_button));
|
||||
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Event.lid));
|
||||
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Event.ac));
|
||||
try std.testing.expectEqual(@as(u32, 19), @intFromEnum(Event.battery));
|
||||
try std.testing.expectEqual(@as(u32, 20), @intFromEnum(Event.notify));
|
||||
// subscribe is the RESERVED verb, below the protocol range entirely.
|
||||
try std.testing.expectEqual(@as(u32, 2), envelope.operation_subscribe);
|
||||
try std.testing.expectEqual(envelope.prefix_size + @sizeOf(Notice), Protocol.event_maximum);
|
||||
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
|
||||
// The call floor, not the push floor: `shutdown` is a synchronous call.
|
||||
try std.testing.expectEqual(envelope.packet_maximum, message_maximum);
|
||||
}
|
||||
|
||||
test "a pushed event names its kind in the header" {
|
||||
var buffer: [envelope.post_maximum]u8 = undefined;
|
||||
const packet = Protocol.encodeEvent(.power_button, 0, .{}, &buffer).?;
|
||||
try std.testing.expectEqual(Event.power_button, Protocol.eventOf(packet).?);
|
||||
|
||||
const notified = Protocol.encodeEvent(.notify, 0, .{ .code = 0x80, .hid = "PNP0C0A\x00".* }, &buffer).?;
|
||||
try std.testing.expectEqual(Event.notify, Protocol.eventOf(notified).?);
|
||||
try std.testing.expectEqual(@as(u32, 0x80), Protocol.decodeEvent(.notify, notified).?.code);
|
||||
}
|
||||
|
||||
@@ -1,57 +1,66 @@
|
||||
//! The USB transfer protocol: what a USB class driver (a keyboard, mouse, or
|
||||
//! mass-storage driver) says to the xHCI bus driver over its well-known
|
||||
//! `.usb_bus` endpoint to drive its device. The class driver owns no hardware —
|
||||
//! it reaches its device entirely through these messages, the way a PS/2 keyboard
|
||||
//! driver reaches the 8042 through the ps2-bus. Extern-struct messages tagged by
|
||||
//! `Operation`, the vfs-protocol / device-manager-protocol pattern.
|
||||
//! mass-storage driver) says to the xHCI bus driver over `/protocol/usb-transfer`
|
||||
//! to drive its device. The class driver owns no hardware — it reaches its device
|
||||
//! entirely through these packets, the way a PS/2 keyboard driver reaches the
|
||||
//! 8042 through the ps2-bus.
|
||||
//!
|
||||
//! Defined through the envelope (docs/os-development/protocol-namespace.md), so
|
||||
//! every packet begins with the folded `Header`. **`Header.target` is the device
|
||||
//! token** — the per-open handle the bus driver hands back, which every request
|
||||
//! but `open` addressed through a `device_token` field of its own before the
|
||||
//! rebase. `open` itself addresses the *assigned device id*, because that is what
|
||||
//! the caller has before there is a token.
|
||||
//!
|
||||
//! The shape:
|
||||
//! - **open** (a capability-passing `ipc.callCap`): the class driver hands over
|
||||
//! its own endpoint (for asynchronous interrupt reports) and its assigned
|
||||
//! device id, and receives a `device_token` plus its interface's endpoints.
|
||||
//! - **control / bulk** (synchronous `ipc.call`): one transfer, answered when
|
||||
//! it completes. Control data travels inline (descriptors, HID/MSC class
|
||||
//! requests are all small); bulk data travels by **physical address** — the
|
||||
//! class driver's own `dma_alloc`'d buffer — so a 512-byte sector never has
|
||||
//! to cross the 256-byte IPC boundary.
|
||||
//! - **open** (a capability-passing call): the class driver hands over its own
|
||||
//! endpoint (for asynchronous interrupt reports); the target is its assigned
|
||||
//! device id, and the reply carries a `device_token` plus its interface's
|
||||
//! endpoints.
|
||||
//! - **control / bulk** (synchronous calls): one transfer, answered when it
|
||||
//! completes. Control data travels **in the packet's tail** in both
|
||||
//! directions (descriptors, HID/MSC class requests are all small), so the
|
||||
//! fixed parts stay tiny and `Status.len` is the transferred length — the
|
||||
//! envelope's own field for "how many bytes follow", which is precisely what
|
||||
//! the old `actual_length` said. Bulk data travels by **physical address** —
|
||||
//! the class driver's own `dma_alloc`'d buffer — so a 512-byte sector never
|
||||
//! has to cross the packet floor.
|
||||
//! - **interrupt_subscribe** (synchronous): arm periodic IN polling of an
|
||||
//! interrupt endpoint; each report the device produces is then pushed to the
|
||||
//! class driver's endpoint as an asynchronous `InterruptReport` (`ipc.send`),
|
||||
//! exactly how the input service delivers events.
|
||||
//! class driver's endpoint as an asynchronous `interrupt_report` event.
|
||||
//! It stays one of **this protocol's own verbs**, not the reserved
|
||||
//! `subscribe`: the reserved verb means "push me this provider's events" and
|
||||
//! carries the subscriber's endpoint, while this names one endpoint address
|
||||
//! on one device and a poll length, and the endpoint it pushes to was handed
|
||||
//! over at `open`. Same word, different contract.
|
||||
//! - **dma_attach**: a class driver hands the controller a DMA-region
|
||||
//! capability (riding the call's cap slot) so the controller binds that
|
||||
//! buffer into its IOMMU domain and may then DMA to the physical addresses
|
||||
//! inside it. Needed once per buffer the class driver will name in a `bulk`
|
||||
//! transfer (its own, or one forwarded to it).
|
||||
//!
|
||||
//! Single controller assumption: one `.usb_bus` singleton serves QEMU's one xHCI.
|
||||
//! A multi-controller machine would need a per-controller endpoint (the device
|
||||
//! manager handing each class driver the right one); noted, not built.
|
||||
//! Single controller assumption: one provider serves QEMU's one xHCI. A
|
||||
//! multi-controller machine would need the controller in the target (or the
|
||||
//! spawner wiring each class driver its own channel); noted, not built.
|
||||
|
||||
/// Fits one synchronous IPC message (kernel MESSAGE_MAXIMUM).
|
||||
pub const message_maximum: usize = 256;
|
||||
const std = @import("std");
|
||||
const envelope = @import("envelope");
|
||||
|
||||
/// The largest inline control-transfer payload. Sized so a whole message
|
||||
/// (header + data) stays under `message_maximum`: descriptors and HID/MSC class
|
||||
/// requests are all far smaller.
|
||||
pub const max_inline_data: usize = 200;
|
||||
/// The largest control-transfer data stage. It rides the packet's tail, so the
|
||||
/// bound is the call floor less the header and the fixed request part — derived
|
||||
/// rather than declared, which is what keeps it honest when a field moves.
|
||||
pub const max_inline_data: usize = envelope.packet_maximum - envelope.prefix_size - @sizeOf(Control);
|
||||
|
||||
/// The largest interrupt report pushed asynchronously. Sized so `InterruptReport`
|
||||
/// fits an `ipc_send` payload slot (POST_MAXIMUM = 64): boot keyboard reports are
|
||||
/// 8 bytes, boot mouse reports 3–4.
|
||||
pub const max_report_data: usize = 48;
|
||||
/// The largest interrupt report pushed asynchronously. An event packet is the
|
||||
/// header plus the payload within 64 bytes, so this is what is left after the
|
||||
/// report's own four bytes of framing: boot keyboard reports are 8 bytes, boot
|
||||
/// mouse reports 3–4, and the whole HID boot vocabulary fits many times over.
|
||||
/// A device that produces more has its report truncated, never split.
|
||||
pub const max_report_data: usize = 40;
|
||||
|
||||
/// Endpoints per interface reported back in an open reply (a boot HID interface
|
||||
/// has one interrupt endpoint, a mass-storage interface two bulk endpoints).
|
||||
pub const max_reported_endpoints: usize = 4;
|
||||
|
||||
pub const Operation = enum(u32) {
|
||||
open = 0,
|
||||
control = 1,
|
||||
interrupt_subscribe = 2,
|
||||
bulk = 3,
|
||||
/// dma_attach: a class driver hands the controller a DMA-region capability (riding
|
||||
/// the call's cap slot) so the controller binds that buffer into its IOMMU domain
|
||||
/// and may then DMA to the physical addresses inside it. Needed once per buffer the
|
||||
/// class driver will name in a `bulk` transfer (its own, or one forwarded to it).
|
||||
dma_attach = 4,
|
||||
};
|
||||
|
||||
/// The endpoint facts a class driver needs, lifted from the endpoint descriptor
|
||||
/// the bus driver already parsed during enumeration.
|
||||
pub const Endpoint = extern struct {
|
||||
@@ -64,114 +73,146 @@ pub const Endpoint = extern struct {
|
||||
reserved: [3]u8 = .{ 0, 0, 0 },
|
||||
};
|
||||
|
||||
/// open: the class driver's receive endpoint rides as the call's capability, and
|
||||
/// `device_id` is the interface's assigned id (its argv[1]).
|
||||
pub const OpenRequest = extern struct {
|
||||
operation: u32 = @intFromEnum(Operation.open),
|
||||
reserved: u32 = 0,
|
||||
device_id: u64,
|
||||
};
|
||||
// --- the per-operation request and reply parts ------------------------------
|
||||
//
|
||||
// Each names the bytes AFTER the prefix. Nothing here carries an operation or a
|
||||
// device token: those are the packet header's, folded in once. No reply carries
|
||||
// a status either — that is the `Status` every reply begins with.
|
||||
|
||||
/// The answer to open: a token scoping every later request to this device, the
|
||||
/// interface's class triple (a sanity check), and its endpoints.
|
||||
pub const OpenReply = extern struct {
|
||||
status: i32,
|
||||
endpoint_count: u32,
|
||||
/// The answer to `open`: the token every later packet puts in `Header.target`,
|
||||
/// the interface's class triple (a sanity check), and its endpoints.
|
||||
pub const Opened = extern struct {
|
||||
device_token: u64,
|
||||
endpoint_count: u32,
|
||||
interface_class: u8,
|
||||
interface_subclass: u8,
|
||||
interface_protocol: u8,
|
||||
interface_number: u8,
|
||||
reserved2: u32 = 0,
|
||||
endpoints: [max_reported_endpoints]Endpoint = [_]Endpoint{.{ .address = 0, .transfer_type = 0, .max_packet_size = 0, .interval = 0 }} ** max_reported_endpoints,
|
||||
};
|
||||
|
||||
/// control: one EP0 control transfer. `setup` is a bit-cast `usb_abi.Request`.
|
||||
/// For an OUT transfer `data[0..data_length]` is sent; for an IN transfer the
|
||||
/// reply carries up to `data_length` bytes back.
|
||||
pub const ControlRequest = extern struct {
|
||||
operation: u32 = @intFromEnum(Operation.control),
|
||||
reserved: u32 = 0,
|
||||
device_token: u64,
|
||||
/// `control`: one EP0 control transfer on `Header.target`. `setup` is a bit-cast
|
||||
/// `usb_abi.Request`. For an OUT transfer the data stage is the request's tail;
|
||||
/// for an IN transfer it comes back as the reply's tail, and `Status.len` is how
|
||||
/// much of it arrived.
|
||||
pub const Control = extern struct {
|
||||
setup: [8]u8,
|
||||
direction_in: u8, // 1 = device-to-host (IN), 0 = host-to-device (OUT)
|
||||
reserved2: u8 = 0,
|
||||
/// 1 = device-to-host (IN), 0 = host-to-device (OUT).
|
||||
direction_in: u8,
|
||||
_padding: u8 = 0,
|
||||
/// Bytes of data stage: what an IN transfer asks for, and what an OUT
|
||||
/// transfer's tail carries.
|
||||
data_length: u16,
|
||||
reserved3: u32 = 0,
|
||||
data: [max_inline_data]u8 = [_]u8{0} ** max_inline_data,
|
||||
_padding2: u32 = 0,
|
||||
};
|
||||
|
||||
pub const ControlReply = extern struct {
|
||||
status: i32, // 0 success, negative on failure/stall
|
||||
actual_length: u32,
|
||||
data: [max_inline_data]u8 = [_]u8{0} ** max_inline_data,
|
||||
};
|
||||
|
||||
/// interrupt_subscribe: begin periodic IN polling of an interrupt endpoint. Each
|
||||
/// report the device returns is pushed to the caller's endpoint (handed over at
|
||||
/// open) as an asynchronous `InterruptReport`.
|
||||
pub const InterruptSubscribeRequest = extern struct {
|
||||
operation: u32 = @intFromEnum(Operation.interrupt_subscribe),
|
||||
reserved: u32 = 0,
|
||||
device_token: u64,
|
||||
/// `interrupt_subscribe`: begin periodic IN polling of an interrupt endpoint of
|
||||
/// `Header.target`. Each report the device returns is pushed to the endpoint the
|
||||
/// caller handed over at `open`, as an `interrupt_report` event.
|
||||
pub const InterruptSubscribe = extern struct {
|
||||
endpoint_address: u8,
|
||||
reserved2: u8 = 0,
|
||||
max_length: u16, // bytes to request per poll (the endpoint's max packet size)
|
||||
_padding: u8 = 0,
|
||||
/// Bytes to request per poll (the endpoint's max packet size).
|
||||
max_length: u16,
|
||||
};
|
||||
|
||||
pub const InterruptSubscribeReply = extern struct {
|
||||
status: i32,
|
||||
reserved: u32 = 0,
|
||||
};
|
||||
|
||||
/// bulk: one bulk IN or OUT transfer. `physical_address` is the class driver's own
|
||||
/// `dma_alloc`'d buffer — the controller DMAs straight to/from it, so the bulk
|
||||
/// data never crosses IPC. `endpoint_address`'s bit 7 selects IN vs OUT.
|
||||
pub const BulkRequest = extern struct {
|
||||
operation: u32 = @intFromEnum(Operation.bulk),
|
||||
reserved: u32 = 0,
|
||||
device_token: u64,
|
||||
/// `bulk`: one bulk IN or OUT transfer on `Header.target`. `physical_address` is
|
||||
/// the class driver's own `dma_alloc`'d buffer — the controller DMAs straight
|
||||
/// to/from it, so the bulk data never crosses IPC. `endpoint_address`'s bit 7
|
||||
/// selects IN vs OUT.
|
||||
pub const Bulk = extern struct {
|
||||
physical_address: u64,
|
||||
length: u32,
|
||||
endpoint_address: u8,
|
||||
reserved2: u8 = 0,
|
||||
reserved3: u16 = 0,
|
||||
_padding: u8 = 0,
|
||||
_padding2: u16 = 0,
|
||||
};
|
||||
|
||||
pub const BulkReply = extern struct {
|
||||
status: i32,
|
||||
actual_length: u32,
|
||||
};
|
||||
/// How many bytes a bulk transfer actually moved. It cannot ride `Status.len`
|
||||
/// the way a control transfer's does: nothing follows a bulk reply, because the
|
||||
/// data went to the caller's DMA buffer rather than into the packet.
|
||||
pub const Transferred = extern struct { actual_length: u32 };
|
||||
|
||||
/// dma_attach: the region capability rides the call's cap slot; the body only carries
|
||||
/// the device token (scoping) so the controller knows which caller is attaching.
|
||||
pub const DmaAttachRequest = extern struct {
|
||||
operation: u32 = @intFromEnum(Operation.dma_attach),
|
||||
reserved: u32 = 0,
|
||||
device_token: u64,
|
||||
};
|
||||
|
||||
pub const DmaAttachReply = extern struct {
|
||||
status: i32,
|
||||
reserved: u32 = 0,
|
||||
};
|
||||
|
||||
/// An asynchronous interrupt report, pushed with `ipc.send` to a subscriber's
|
||||
/// endpoint. `Received.isMessage()` is set; there is no reply owed.
|
||||
/// One asynchronous interrupt report, pushed to the endpoint the class driver
|
||||
/// handed over at `open`. The device it came from is `Header.target`.
|
||||
pub const InterruptReport = extern struct {
|
||||
device_token: u64,
|
||||
endpoint_address: u8,
|
||||
length: u8,
|
||||
reserved: u16 = 0,
|
||||
_padding: u16 = 0,
|
||||
data: [max_report_data]u8 = [_]u8{0} ** max_report_data,
|
||||
};
|
||||
|
||||
comptime {
|
||||
const std = @import("std");
|
||||
// Every synchronous message must fit one IPC message; the async report must
|
||||
// fit an ipc_send payload slot.
|
||||
std.debug.assert(@sizeOf(ControlRequest) <= message_maximum);
|
||||
std.debug.assert(@sizeOf(ControlReply) <= message_maximum);
|
||||
std.debug.assert(@sizeOf(OpenReply) <= message_maximum);
|
||||
std.debug.assert(@sizeOf(InterruptReport) <= 64);
|
||||
pub const Protocol = envelope.Define(.{
|
||||
.name = "usb-transfer",
|
||||
.version = 1,
|
||||
.operations = &.{
|
||||
// open: the target is the interface's assigned device id (its argv[1]),
|
||||
// and the class driver's receive endpoint rides as the capability.
|
||||
.{ .name = "open", .reply = Opened },
|
||||
.{ .name = "control", .request = Control },
|
||||
.{ .name = "interrupt_subscribe", .request = InterruptSubscribe },
|
||||
.{ .name = "bulk", .request = Bulk, .reply = Transferred },
|
||||
// dma_attach: the region capability rides the call's cap slot; the
|
||||
// target says which caller's device is attaching, so there is nothing
|
||||
// left for a body to carry.
|
||||
.{ .name = "dma_attach" },
|
||||
},
|
||||
.events = &.{
|
||||
.{ .name = "interrupt_report", .payload = InterruptReport },
|
||||
},
|
||||
});
|
||||
|
||||
pub const Operation = Protocol.Operation;
|
||||
pub const Event = Protocol.Event;
|
||||
|
||||
/// What both sides size their buffers to — the call floor, as every protocol does.
|
||||
pub const message_maximum: usize = Protocol.message_maximum;
|
||||
|
||||
test "the budgets, re-verified by Define rather than by hand" {
|
||||
// What the hand-rolled comptime asserts used to say, now said by `Define`
|
||||
// — and counting the header, which the old checks did not.
|
||||
try std.testing.expectEqual(@as(usize, 224), max_inline_data);
|
||||
try std.testing.expect(Protocol.request_maximum <= envelope.packet_maximum);
|
||||
try std.testing.expect(Protocol.reply_maximum <= envelope.packet_maximum);
|
||||
// The report was 48 bytes of data in a 64-byte struct that had no room left
|
||||
// for a header. Folding the device token into the target and trimming the
|
||||
// data to 40 leaves the whole packet at 60 of the 64-byte push floor.
|
||||
try std.testing.expectEqual(@as(usize, 44), @sizeOf(InterruptReport));
|
||||
try std.testing.expectEqual(@as(usize, 60), Protocol.event_maximum);
|
||||
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
|
||||
}
|
||||
|
||||
test "the verb numbering, and the device token in the header" {
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.open));
|
||||
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Operation.control));
|
||||
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Operation.interrupt_subscribe));
|
||||
try std.testing.expectEqual(@as(u32, 19), @intFromEnum(Operation.bulk));
|
||||
try std.testing.expectEqual(@as(u32, 20), @intFromEnum(Operation.dma_attach));
|
||||
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.interrupt_report));
|
||||
|
||||
var buffer: [message_maximum]u8 = undefined;
|
||||
const packet = Protocol.encodeRequest(.control, 9, .{
|
||||
.setup = .{ 0, 6, 0, 1, 0, 0, 18, 0 },
|
||||
.direction_in = 1,
|
||||
.data_length = 18,
|
||||
}, &.{}, &buffer).?;
|
||||
try std.testing.expectEqual(@as(u64, 9), envelope.headerOf(packet).?.target);
|
||||
try std.testing.expectEqual(@as(u16, 18), Protocol.decodeRequest(.control, packet).?.data_length);
|
||||
}
|
||||
|
||||
test "a control OUT carries its data stage as the packet's tail" {
|
||||
var buffer: [message_maximum]u8 = undefined;
|
||||
const payload = [_]u8{ 1, 2, 3, 4 };
|
||||
const packet = Protocol.encodeRequest(.control, 5, .{
|
||||
.setup = .{ 0x21, 11, 0, 0, 0, 0, 4, 0 },
|
||||
.direction_in = 0,
|
||||
.data_length = payload.len,
|
||||
}, &payload, &buffer).?;
|
||||
try std.testing.expectEqualSlices(u8, &payload, Protocol.requestTail(.control, packet));
|
||||
|
||||
// And the answer to an IN: the bytes follow the (empty) fixed reply part,
|
||||
// with `Status.len` counting exactly them.
|
||||
const answered = Protocol.encodeReply(.control, 0, {}, &payload, &buffer).?;
|
||||
try std.testing.expectEqual(@as(u32, payload.len), envelope.statusOf(answered).?.len);
|
||||
try std.testing.expectEqualSlices(u8, &payload, Protocol.replyTail(.control, answered));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user