reorg: move device data modules into library/device/<domain>/

First step of the device-code reorganization (plan: group device code by
domain, split each domain into a shareable data module + a logic module).
This moves the pure-data modules — the enums, wire types, and taxonomies
that any layer including the kernel can import cheaply — out of
system/devices/ and into their domain home:

  device-abi  -> library/device/model/device-abi.zig
  pci-class   -> library/device/pci/pci-class.zig
  usb-abi     -> library/device/usb/usb-abi.zig
  usb-ids     -> library/device/usb/usb-ids.zig
  acpi-ids    -> library/device/acpi/acpi-ids.zig
  aml/        -> library/device/acpi/aml/

Module names are unchanged, so this is a pure file move: only the
b.addModule paths and the host-test file list in build.zig change; no
importer is touched. system/devices/ now holds only the kernel-internal
device model (device-model, platform, acpi, device-tree, power).

The device *logic* (the pci Function helper, the usb transfer client) and
the kernel's cosmetic taxonomy dependency are handled in following commits.

zig build + zig build test green.
This commit is contained in:
Daniel Samson
2026-07-22 20:36:24 +01:00
parent ea470afe84
commit 794a8b5782
11 changed files with 12 additions and 12 deletions
-138
View File
@@ -1,138 +0,0 @@
//! ACPI / PnP hardware-ID (`_HID`) names: the flat analog of pci-class.zig for
//! `acpi_device` nodes. Unlike PCI, ACPI has no class/subclass/prog-IF taxonomy — a
//! device's identity *is* its `_HID` string (`PNP0303` simply means "PS/2 keyboard"),
//! so this is a plain id <-> name registry rather than a hierarchical decoder.
//! The well-known PnP/ACPI IDs; vendor-specific ids (e.g. `QEMU0002`, `INTC1234`) have
//! no standard name and decode to nothing. Pure reference data, so it is shared by
//! kernel discovery (the device-tree dump) and any user-space driver or tool.
//!
//! Code that means a specific device names the `HardwareId` variant instead of its
//! `_HID` string — `HardwareId.ps2_keyboard.hid()` reads without a registry lookup,
//! where a bare `"PNP0303"` does not.
const std = @import("std");
/// The common standard PnP/ACPI hardware IDs, as named values. Prefix ranges hint at
/// the grouping (PNP03xx keyboards, PNP0Fxx pointing devices, PNP0Cxx ACPI
/// power/thermal, PNP0Axx buses), but there is no formal hierarchy — hence a flat
/// enum over a flat registry.
pub const HardwareId = enum {
programmable_interrupt_controller,
system_timer,
high_precision_event_timer,
dma_controller,
ps2_keyboard,
parallel_port,
ecp_parallel_port,
serial_port,
floppy_disk_controller,
system_speaker,
pci_bus,
generic_container,
/// The second id the ACPI spec assigns the same "Generic Container Device" name.
generic_container_extended,
pci_express_root_bridge,
real_time_clock,
system_board,
motherboard_reserved_resources,
math_coprocessor,
acpi_system_board,
embedded_controller,
control_method_battery,
fan,
power_button,
lid,
sleep_button,
pci_interrupt_link,
microsoft_ps2_mouse,
ps2_mouse,
ac_adapter,
processor_device,
processor_aggregator,
processor_container,
const Entry = struct { hid: []const u8, name: []const u8 };
/// The registry row for this id: its `_HID` string and human-readable name.
fn entry(self: HardwareId) Entry {
return switch (self) {
.programmable_interrupt_controller => .{ .hid = "PNP0000", .name = "Programmable Interrupt Controller (PIC)" },
.system_timer => .{ .hid = "PNP0100", .name = "System Timer (PIT)" },
.high_precision_event_timer => .{ .hid = "PNP0103", .name = "High Precision Event Timer (HPET)" },
.dma_controller => .{ .hid = "PNP0200", .name = "DMA Controller" },
.ps2_keyboard => .{ .hid = "PNP0303", .name = "PS/2 Keyboard" },
.parallel_port => .{ .hid = "PNP0400", .name = "Standard LPT Parallel Port" },
.ecp_parallel_port => .{ .hid = "PNP0401", .name = "ECP Parallel Port" },
.serial_port => .{ .hid = "PNP0501", .name = "16550A-compatible Serial Port" },
.floppy_disk_controller => .{ .hid = "PNP0700", .name = "PC Floppy Disk Controller" },
.system_speaker => .{ .hid = "PNP0800", .name = "System Speaker" },
.pci_bus => .{ .hid = "PNP0A03", .name = "PCI Bus" },
.generic_container => .{ .hid = "PNP0A05", .name = "Generic Container Device" },
.generic_container_extended => .{ .hid = "PNP0A06", .name = "Generic Container Device" },
.pci_express_root_bridge => .{ .hid = "PNP0A08", .name = "PCI Express Root Bridge" },
.real_time_clock => .{ .hid = "PNP0B00", .name = "Real-Time Clock (RTC)" },
.system_board => .{ .hid = "PNP0C01", .name = "System Board" },
.motherboard_reserved_resources => .{ .hid = "PNP0C02", .name = "Motherboard Reserved Resources" },
.math_coprocessor => .{ .hid = "PNP0C04", .name = "Math Coprocessor" },
.acpi_system_board => .{ .hid = "PNP0C08", .name = "ACPI System Board" },
.embedded_controller => .{ .hid = "PNP0C09", .name = "ACPI Embedded Controller" },
.control_method_battery => .{ .hid = "PNP0C0A", .name = "ACPI Control Method Battery" },
.fan => .{ .hid = "PNP0C0B", .name = "ACPI Fan" },
.power_button => .{ .hid = "PNP0C0C", .name = "ACPI Power Button" },
.lid => .{ .hid = "PNP0C0D", .name = "ACPI Lid" },
.sleep_button => .{ .hid = "PNP0C0E", .name = "ACPI Sleep Button" },
.pci_interrupt_link => .{ .hid = "PNP0C0F", .name = "PCI Interrupt Link Device" },
.microsoft_ps2_mouse => .{ .hid = "PNP0F03", .name = "Microsoft PS/2 Mouse" },
.ps2_mouse => .{ .hid = "PNP0F13", .name = "PS/2 Mouse" },
.ac_adapter => .{ .hid = "ACPI0003", .name = "AC Adapter" },
.processor_device => .{ .hid = "ACPI0007", .name = "Processor Device" },
.processor_aggregator => .{ .hid = "ACPI000C", .name = "Processor Aggregator" },
.processor_container => .{ .hid = "ACPI0010", .name = "Processor Container" },
};
}
/// This id's `_HID` string (e.g. `.ps2_keyboard` -> "PNP0303").
pub fn hid(self: HardwareId) []const u8 {
return self.entry().hid;
}
/// This id's human-readable name (e.g. `.ps2_keyboard` -> "PS/2 Keyboard").
pub fn description(self: HardwareId) []const u8 {
return self.entry().name;
}
/// The named value for a `_HID` string, or null if it is not a known standard
/// id (vendor-specific ids are not in the registry).
pub fn fromHid(hid_string: []const u8) ?HardwareId {
for (std.enums.values(HardwareId)) |id| {
if (std.mem.eql(u8, id.hid(), hid_string)) return id;
}
return null;
}
};
/// The human-readable name for a `_HID` string, or "" if it is not a known standard
/// id (vendor-specific ids have no registry name — callers just print the raw HID).
pub fn description(hid: []const u8) []const u8 {
return (HardwareId.fromHid(hid) orelse return "").description();
}
test "decodes standard PnP/ACPI ids and leaves the rest alone" {
const eq = std.testing.expectEqualStrings;
try eq("PS/2 Keyboard", description("PNP0303"));
try eq("PS/2 Mouse", description("PNP0F13"));
try eq("PCI Express Root Bridge", description("PNP0A08"));
try eq("Real-Time Clock (RTC)", description("PNP0B00"));
try eq("", description("QEMU0002")); // vendor-specific: no standard name
try eq("", description("")); // no HID at all
}
test "named values round-trip through their _HID strings" {
const testing = std.testing;
try testing.expectEqualStrings("PNP0303", HardwareId.ps2_keyboard.hid());
try testing.expectEqual(@as(?HardwareId, .ps2_mouse), HardwareId.fromHid("PNP0F13"));
try testing.expectEqual(@as(?HardwareId, null), HardwareId.fromHid("QEMU0002"));
for (std.enums.values(HardwareId)) |id| {
try testing.expectEqual(@as(?HardwareId, id), HardwareId.fromHid(id.hid()));
}
}
-260
View File
@@ -1,260 +0,0 @@
//! AML (ACPI Machine Language) — the bytecode in the DSDT and SSDTs that describes
//! the parts of the machine the static tables don't.
//!
//! This module has two stages. `parser.zig` walks the entire byte stream and
//! records every named object into a namespace tree (`namespace.zig`), capturing
//! method bodies and field/region layout. `interpreter.zig` then *evaluates* control
//! methods on demand — running operators, control flow, and OperationRegion field
//! access — so callers can resolve device status (`_STA`), current resource
//! settings (`_CRS`), sleep states (`_Sx`), and the like against the live namespace.
const std = @import("std");
const opcode = @import("opcodes.zig");
const parser = @import("parser.zig");
/// The named AML opcode/prefix bytes (`zero_opcode`, `byte_prefix`, …). Re-exported so
/// callers that decode raw AML bytes — e.g. the acpi service reading a `_HID` integer —
/// name the opcodes instead of writing bare 0x0A/0x0B/… literals (docs/coding-standards.md).
pub const opcodes = @import("opcodes.zig");
pub const Namespace = @import("namespace.zig").Namespace;
pub const Node = @import("namespace.zig").Node;
pub const NodeKind = @import("namespace.zig").NodeKind;
/// The AML evaluator: interprets control methods (and reads Names/Fields) far
/// enough for device discovery. See `interpreter.zig`.
pub const Interpreter = @import("interpreter.zig").Interpreter;
pub const Object = @import("interpreter.zig").Object;
pub const EvaluateHal = @import("interpreter.zig").Hal;
/// The SLP_TYP values written to PM1a/PM1b control to enter a sleep state.
pub const SleepType = struct {
slp_typ_a: u8,
slp_typ_b: u8,
};
pub const ParseResult = struct {
namespace: Namespace,
/// Bytes the parser consumed across all blocks...
consumed: usize,
/// ...out of this many. A clean full traversal has `consumed == total`.
total: usize,
};
/// Parse the given AML blocks (DSDT first, then SSDTs) into one namespace. Later
/// blocks extend the namespace built by earlier ones, exactly as ACPI intends.
pub fn parse(allocator: std.mem.Allocator, blocks: []const []const u8) !ParseResult {
var namespace = try Namespace.init(allocator);
var consumed: usize = 0;
var total: usize = 0;
for (blocks) |block| {
var p = parser.Parser.init(block, &namespace);
consumed += p.parseAll();
total += block.len;
}
return .{ .namespace = namespace, .consumed = consumed, .total = total };
}
/// Count the Device objects in a parsed namespace — what the acpi service
/// (docs/discovery.md) reports, and what the kernel's own parse counts
/// so the two can be checked equal across the ring-3 move.
pub fn deviceCount(namespace: *const Namespace) usize {
return countKind(namespace.root, .device);
}
fn countKind(node: *const Node, kind: NodeKind) usize {
var n: usize = if (node.kind == kind) 1 else 0;
var c = node.first_child;
while (c) |child| : (c = child.next_sibling) n += countKind(child, kind);
return n;
}
/// Look up the `\_S{state}` sleep package in a parsed namespace and return its
/// first two integer elements (SLP_TYP for PM1a / PM1b), or null if absent.
pub fn sleepState(namespace: *Namespace, state: u8) ?SleepType {
const segment = [4]u8{ '_', 'S', '0' + state, '_' };
const node = namespace.resolve(namespace.root, false, 0, &.{segment}) orelse return null;
if (node.kind != .name) return null;
return parseSleepPackage(node.value);
}
/// Decode a `Package(){ SLP_TYPa, SLP_TYPb, ... }` from the raw AML of a Name's
/// value. Returns the first two elements as bytes (missing elements default to 0).
fn parseSleepPackage(value: []const u8) ?SleepType {
if (value.len == 0 or value[0] != opcode.package_opcode) return null;
var p: usize = 1;
p += packageLengthSize(value, p) orelse return null;
if (p >= value.len) return null;
const number_elements = value[p];
p += 1;
const a: u8 = if (number_elements >= 1) @truncate(readInteger(value, &p) orelse 0) else 0;
const b: u8 = if (number_elements >= 2) @truncate(readInteger(value, &p) orelse 0) else 0;
return .{ .slp_typ_a = a, .slp_typ_b = b };
}
/// Bytes a PkgLength field occupies at `p` (we only need to step over it here).
fn packageLengthSize(bytes: []const u8, p: usize) ?usize {
if (p >= bytes.len) return null;
const follow: usize = bytes[p] >> 6;
if (p + 1 + follow > bytes.len) return null;
return 1 + follow;
}
/// Read one AML integer data object at `p`, advancing `p`.
fn readInteger(bytes: []const u8, p: *usize) ?u64 {
if (p.* >= bytes.len) return null;
const opcode_byte = bytes[p.*];
p.* += 1;
return switch (opcode_byte) {
opcode.zero_opcode => 0,
opcode.one_opcode => 1,
opcode.ones_opcode => 0xFF,
opcode.byte_prefix => readLittle(bytes, p, 1),
opcode.word_prefix => readLittle(bytes, p, 2),
opcode.dword_prefix => readLittle(bytes, p, 4),
opcode.qword_prefix => readLittle(bytes, p, 8),
else => null,
};
}
fn readLittle(bytes: []const u8, p: *usize, n: usize) ?u64 {
if (p.* + n > bytes.len) return null;
var v: u64 = 0;
var k: usize = 0;
while (k < n) : (k += 1) v |= @as(u64, bytes[p.* + k]) << @intCast(k * 8);
p.* += n;
return v;
}
// --- tests ------------------------------------------------------------------
test "parses a nested namespace and finds the sleep package" {
// A hand-assembled AML blob (all PkgLengths computed to be single-byte):
// Name(_S5, Package(2){0x05, 0x00})
// Scope(\_SB) { Device(PCI0) {
// Name(_HID, 0x11)
// Method(MTHD, 1) {}
// Method(CALL, 0) { MTHD(Zero) } // invocation of a 1-arg method
// } }
// OperationRegion(DBG0, SystemIO, 0x0402, 1)
// Field(DBG0, ...) { DBGB, 8 }
const blob = [_]u8{
// Name(_S5, Package(2){Byte 0x05, Byte 0x00})
0x08, 0x5F, 0x53, 0x35, 0x5F, 0x12, 0x06, 0x02, 0x0A, 0x05, 0x0A, 0x00,
// Scope(\_SB) packagelen=0x27
0x10, 0x27, 0x5C, 0x5F, 0x53, 0x42, 0x5F,
// Device(PCI0) packagelen=0x1F
0x5B, 0x82, 0x1F, 0x50, 0x43,
0x49, 0x30,
// Name(_HID, 0x11)
0x08, 0x5F, 0x48, 0x49, 0x44, 0x0A, 0x11,
// Method(MTHD, flags=1) empty, packagelen=0x06
0x14, 0x06, 0x4D,
0x54, 0x48, 0x44, 0x01,
// Method(CALL, flags=0) { MTHD(Zero) }, packagelen=0x0B
0x14, 0x0B, 0x43, 0x41, 0x4C, 0x4C, 0x00, 0x4D,
0x54, 0x48, 0x44, 0x00,
// OperationRegion(DBG0, SystemIO, Word 0x0402, Byte 1)
0x5B, 0x80, 0x44, 0x42, 0x47, 0x30, 0x01, 0x0B,
0x02, 0x04, 0x0A, 0x01,
// Field(DBG0, flags=1) { DBGB, 8 }, packagelen=0x0B
0x5B, 0x81, 0x0B, 0x44, 0x42, 0x47, 0x30, 0x01,
0x44, 0x42, 0x47, 0x42, 0x08,
};
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var result = try parse(arena.allocator(), &.{&blob});
// Integrity: the parser consumed exactly the whole blob (no desync).
try std.testing.expectEqual(blob.len, result.consumed);
try std.testing.expectEqual(blob.len, result.total);
const namespace = &result.namespace;
// Expected top-level nodes.
const sb = namespace.resolve(namespace.root, false, 0, &.{.{ '_', 'S', 'B', '_' }}) orelse return error.NoSB;
try std.testing.expectEqual(NodeKind.scope, sb.kind);
const pci0 = namespace.resolve(sb, false, 0, &.{.{ 'P', 'C', 'I', '0' }}) orelse return error.NoPCI0;
try std.testing.expectEqual(NodeKind.device, pci0.kind);
_ = namespace.resolve(pci0, false, 0, &.{.{ '_', 'H', 'I', 'D' }}) orelse return error.NoHID;
// The 1-arg method's arg count was parsed from its flags byte.
const mthd = namespace.resolve(pci0, false, 0, &.{.{ 'M', 'T', 'H', 'D' }}) orelse return error.NoMTHD;
try std.testing.expectEqual(NodeKind.method, mthd.kind);
try std.testing.expectEqual(@as(u8, 1), mthd.arg_count);
// OperationRegion and the Field unit made it into the namespace.
_ = namespace.resolve(namespace.root, false, 0, &.{.{ 'D', 'B', 'G', '0' }}) orelse return error.NoRegion;
_ = namespace.resolve(namespace.root, false, 0, &.{.{ 'D', 'B', 'G', 'B' }}) orelse return error.NoField;
// The sleep package decoded.
const s5 = sleepState(namespace, 5) orelse return error.NoS5;
try std.testing.expectEqual(@as(u8, 5), s5.slp_typ_a);
try std.testing.expectEqual(@as(u8, 0), s5.slp_typ_b);
}
fn noMap(physical: u64, _: u64, _: bool) u64 {
return physical;
}
fn noRead(_: u8, _: u16) u32 {
return 0;
}
fn noWrite(_: u8, _: u16, _: u32) void {}
test "interpreter runs a method with args, arithmetic, and control flow" {
// Method(TST_, 1) {
// Store(Arg0, Local0); Add(Local0, 5, Local0)
// If (LGreater(Local0, 10)) { Return(One) }
// Return(Zero)
// }
const blob = [_]u8{
0x14, 0x18, 0x54, 0x53, 0x54, 0x5F, 0x01, // Method TST_, 1 arg
0x70, 0x68, 0x60, // Store(Arg0, Local0)
0x72, 0x60, 0x0A, 0x05, 0x60, // Add(Local0, 5, Local0)
0xA0, 0x07, 0x94, 0x60, 0x0A, 0x0A, 0xA4, 0x01, // If(LGreater(Local0,10)) { Return(One) }
0xA4, 0x00, // Return(Zero)
};
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var result = try parse(arena.allocator(), &.{&blob});
const namespace = &result.namespace;
const tst = namespace.resolve(namespace.root, false, 0, &.{.{ 'T', 'S', 'T', '_' }}) orelse return error.NoMethod;
var interpreter = Interpreter.init(namespace, .{ .mapMmio = noMap, .pioRead = noRead, .pioWrite = noWrite }, arena.allocator());
const hi = try interpreter.evaluate(tst, &.{.{ .integer = 7 }}); // 7+5=12 > 10 -> 1
try std.testing.expectEqual(@as(u64, 1), try hi.asInteger());
const lo = try interpreter.evaluate(tst, &.{.{ .integer = 2 }}); // 2+5=7 !> 10 -> 0
try std.testing.expectEqual(@as(u64, 0), try lo.asInteger());
}
test "interpreter records Notify(device, code)" {
// Device(DEV_) { Name(_HID, 0x030AD041) } // PNP0A03-ish placeholder
// Method(TST_, 0) { Notify(DEV_, 0x80); Return(Zero) }
// Encoded: a Device holding a Name, then a Method issuing Notify on it.
const blob = [_]u8{
0x5B, 0x82, 0x0F, 0x44, 0x45, 0x56, 0x5F, // Device(DEV_) len=0x0F (pkglen + DEV_ + Name)
0x08, 0x5F, 0x48, 0x49, 0x44, 0x0C, 0x41, 0xD0, 0x0A, 0x03, // Name(_HID, DWord 0x030AD041)
0x14, 0x0F, 0x54, 0x53, 0x54, 0x5F, 0x00, // Method(TST_, 0) len=0x0F (pkglen + TST_ + flags + body)
0x86, 0x44, 0x45, 0x56, 0x5F, 0x0A, 0x80, // Notify(DEV_, 0x80)
0xA4, 0x00, // Return(Zero)
};
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var result = try parse(arena.allocator(), &.{&blob});
const namespace = &result.namespace;
const tst = namespace.resolve(namespace.root, false, 0, &.{.{ 'T', 'S', 'T', '_' }}) orelse return error.NoMethod;
const dev = namespace.resolve(namespace.root, false, 0, &.{.{ 'D', 'E', 'V', '_' }}) orelse return error.NoDevice;
var interpreter = Interpreter.init(namespace, .{ .mapMmio = noMap, .pioRead = noRead, .pioWrite = noWrite }, arena.allocator());
_ = try interpreter.evaluate(tst, &.{});
const events = interpreter.takeNotifications();
try std.testing.expectEqual(@as(usize, 1), events.len);
try std.testing.expectEqual(dev, events[0].node);
try std.testing.expectEqual(@as(u64, 0x80), events[0].code);
}
-777
View File
@@ -1,777 +0,0 @@
//! A tree-walking AML interpreter — the evaluation stage on top of the parser's
//! structural namespace. It executes control methods (their bodies captured by
//! the parser) far enough to serve device discovery: device status (`_STA`, is a
//! device present), current resource settings (`_CRS`), and the operators, control
//! flow, locals/args, and
//! OperationRegion field access those methods reach for.
//!
//! Scope: integers, buffers, strings, packages, and references; If/Else/While/
//! Return; the arithmetic/logic operators; method invocation; Name/Local/Arg
//! access; CreateField buffer patching (the common current-resource-settings
//! (`_CRS`) idiom); and field
//! reads/writes against SystemMemory and SystemIO regions. Opcodes outside this
//! set return `error.Unsupported`, which callers treat as "couldn't evaluate" and
//! fall back — never a hard failure.
const std = @import("std");
const opcode = @import("opcodes.zig");
const Node = @import("namespace.zig").Node;
const Namespace = @import("namespace.zig").Namespace;
/// Injected hardware access for OperationRegion reads/writes (the architecture VMM + pio).
pub const Hal = struct {
mapMmio: *const fn (physical: u64, len: u64, writable: bool) u64,
pioRead: *const fn (width: u8, port: u16) u32,
pioWrite: *const fn (width: u8, port: u16, value: u32) void,
};
pub const Error = error{ Unsupported, Truncated, DivByZero } || std.mem.Allocator.Error;
/// A runtime AML value.
pub const Object = union(enum) {
uninitialized,
integer: u64,
buffer: []u8,
string: []u8,
package: []Object,
reference: *Node,
pub fn asInteger(self: Object) Error!u64 {
return switch (self) {
.integer => |v| v,
.buffer => |b| blk: {
var v: u64 = 0;
for (b, 0..) |byte, i| {
if (i >= 8) break;
v |= @as(u64, byte) << @intCast(i * 8);
}
break :blk v;
},
else => error.Unsupported,
};
}
};
const maximum_segments = 16;
const NamePath = struct {
rooted: bool = false,
parents: u8 = 0,
segments: [maximum_segments][4]u8 = undefined,
count: usize = 0,
fn slice(self: *const NamePath) []const [4]u8 {
return self.segments[0..self.count];
}
};
const Cursor = struct {
b: []const u8,
i: usize = 0,
fn eof(self: *Cursor) bool {
return self.i >= self.b.len;
}
fn peek(self: *Cursor) ?u8 {
return if (self.eof()) null else self.b[self.i];
}
fn byte(self: *Cursor) Error!u8 {
if (self.eof()) return error.Truncated;
const v = self.b[self.i];
self.i += 1;
return v;
}
fn take(self: *Cursor, n: usize) Error![]const u8 {
if (self.i + n > self.b.len) return error.Truncated;
const s = self.b[self.i .. self.i + n];
self.i += n;
return s;
}
fn packageLength(self: *Cursor) Error!usize {
const lead = try self.byte();
const follow: usize = lead >> 6;
if (follow == 0) return lead & 0x3F;
var value: usize = lead & 0x0F;
var k: usize = 0;
while (k < follow) : (k += 1) value |= @as(usize, try self.byte()) << @intCast(4 + k * 8);
return value;
}
fn nameString(self: *Cursor) Error!NamePath {
var name_path = NamePath{};
if (self.peek() == opcode.root_char) {
name_path.rooted = true;
self.i += 1;
} else {
while (self.peek() == opcode.parent_prefix_char) : (self.i += 1) name_path.parents += 1;
}
const lead = self.peek() orelse return name_path;
switch (lead) {
0x00 => self.i += 1,
opcode.dual_name_prefix => {
self.i += 1;
try self.segment(&name_path);
try self.segment(&name_path);
},
opcode.multi_name_prefix => {
self.i += 1;
const count = try self.byte();
var k: usize = 0;
while (k < count) : (k += 1) try self.segment(&name_path);
},
else => try self.segment(&name_path),
}
return name_path;
}
fn segment(self: *Cursor, name_path: *NamePath) Error!void {
const s = try self.take(4);
if (name_path.count < maximum_segments) {
name_path.segments[name_path.count] = s[0..4].*;
name_path.count += 1;
}
}
};
const Frame = struct {
args: [7]Object = .{.uninitialized} ** 7,
locals: [8]Object = .{.uninitialized} ** 8,
scope: *Node,
ret: Object = .uninitialized,
returned: bool = false,
broke: bool = false,
};
/// A CreateField binding: a name that indexes into a buffer object.
const BufferField = struct { buffer: *Node, byte_off: usize, bit_width: u32 };
/// One Notify(device, code) the interpreter executed.
pub const NotifyEvent = struct { node: *Node, code: u64 };
pub const Interpreter = struct {
namespace: *Namespace,
hal: Hal,
arena: std.mem.Allocator,
/// Runtime object overrides for Name nodes (Store targets, patched buffers).
dynamic_overrides: std.AutoHashMapUnmanaged(*Node, Object) = .{},
/// CreateField bindings active for the current evaluation.
fields: std.AutoHashMapUnmanaged(*Node, BufferField) = .{},
/// Notify(device, code) operations the last evaluation executed — a GPE or
/// EC handler tells the OS "look at this device" this way. Bounded; the
/// caller drains it with `takeNotifications` after `evaluate` (M21).
notify_queue: [16]NotifyEvent = undefined,
notify_count: usize = 0,
pub fn init(namespace: *Namespace, hal: Hal, arena: std.mem.Allocator) Interpreter {
return .{ .namespace = namespace, .hal = hal, .arena = arena };
}
/// Evaluate a namespace object: invoke a Method, read a Name's value, or read a
/// Field. Resets per-evaluation runtime state first.
pub fn evaluate(self: *Interpreter, node: *Node, args: []const Object) Error!Object {
self.notify_count = 0;
self.dynamic_overrides.clearRetainingCapacity();
self.fields.clearRetainingCapacity();
return self.invoke(node, args);
}
fn invoke(self: *Interpreter, node: *Node, args: []const Object) Error!Object {
switch (node.kind) {
.method => {
var frame = Frame{ .scope = node };
for (args, 0..) |a, i| {
if (i < frame.args.len) frame.args[i] = a;
}
var current = Cursor{ .b = node.value };
try self.executeList(&current, &frame);
return frame.ret;
},
.name => {
if (self.dynamic_overrides.get(node)) |o| return o;
var current = Cursor{ .b = node.value };
var frame = Frame{ .scope = node.parent orelse self.namespace.root };
return self.term(&current, &frame);
},
.field => return .{ .integer = try self.readField(node) },
else => return .{ .reference = node },
}
}
/// Execute a TermList until it ends or the frame returns/breaks.
fn executeList(self: *Interpreter, current: *Cursor, frame: *Frame) Error!void {
while (!current.eof() and !frame.returned and !frame.broke) {
_ = try self.term(current, frame);
}
}
/// Evaluate/execute one term, returning its value (`.uninitialized` for pure
/// statements).
fn term(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const lead = current.peek() orelse return error.Truncated;
if (isNameStart(lead)) return self.nameReference(current, frame);
_ = try current.byte();
return switch (lead) {
opcode.zero_opcode => Object{ .integer = 0 },
opcode.one_opcode => Object{ .integer = 1 },
opcode.ones_opcode => Object{ .integer = ~@as(u64, 0) },
opcode.byte_prefix => Object{ .integer = try self.readConstant(current, 1) },
opcode.word_prefix => Object{ .integer = try self.readConstant(current, 2) },
opcode.dword_prefix => Object{ .integer = try self.readConstant(current, 4) },
opcode.qword_prefix => Object{ .integer = try self.readConstant(current, 8) },
opcode.string_prefix => try self.readString(current),
opcode.buffer_opcode => try self.buffer(current, frame),
opcode.package_opcode, opcode.var_package_opcode => try self.package(current, frame, lead == opcode.var_package_opcode),
opcode.local0_opcode...opcode.local7_opcode => frame.locals[lead - opcode.local0_opcode],
opcode.arg0_opcode...opcode.arg6_opcode => frame.args[lead - opcode.arg0_opcode],
opcode.return_opcode => blk: {
frame.ret = try self.term(current, frame);
frame.returned = true;
break :blk .uninitialized;
},
opcode.break_opcode => blk: {
frame.broke = true;
break :blk .uninitialized;
},
opcode.continue_opcode, opcode.noop_opcode => .uninitialized,
opcode.if_opcode => try self.ifElse(current, frame),
opcode.while_opcode => try self.whileLoop(current, frame),
opcode.store_opcode => try self.store(current, frame),
opcode.increment_opcode => try self.incDec(current, frame, 1),
opcode.decrement_opcode => try self.incDec(current, frame, -1),
opcode.add_opcode => try self.binary(current, frame, .add),
opcode.subtract_opcode => try self.binary(current, frame, .sub),
opcode.multiply_opcode => try self.binary(current, frame, .mul),
opcode.mod_opcode => try self.binary(current, frame, .mod),
opcode.and_opcode => try self.binary(current, frame, .band),
opcode.or_opcode => try self.binary(current, frame, .bor),
opcode.xor_opcode => try self.binary(current, frame, .bxor),
opcode.nand_opcode => try self.binary(current, frame, .nand),
opcode.nor_opcode => try self.binary(current, frame, .nor),
opcode.shift_left_opcode => try self.binary(current, frame, .shl),
opcode.shift_right_opcode => try self.binary(current, frame, .shr),
opcode.divide_opcode => try self.divide(current, frame),
opcode.land_opcode => try self.logic2(current, frame, .land),
opcode.lor_opcode => try self.logic2(current, frame, .lor),
opcode.lequal_opcode => try self.logic2(current, frame, .eq),
opcode.lgreater_opcode => try self.logic2(current, frame, .gt),
opcode.lless_opcode => try self.logic2(current, frame, .lt),
opcode.lnot_opcode => try self.lnot(current, frame),
opcode.not_opcode => blk: {
const v = try self.evaluateInteger(current, frame);
const r = ~v;
try self.storeTarget(current, frame, .{ .integer = r });
break :blk .{ .integer = r };
},
opcode.size_of_opcode => try self.sizeOf(current, frame),
opcode.index_opcode => try self.index(current, frame),
opcode.dereference_of_opcode => try self.dereferenceOf(current, frame),
opcode.to_integer_opcode => blk: {
const v = try self.evaluateInteger(current, frame);
try self.storeTarget(current, frame, .{ .integer = v });
break :blk .{ .integer = v };
},
opcode.to_buffer_opcode => try self.passThroughUnary(current, frame),
opcode.notify_opcode => try self.notify(current, frame),
opcode.extended_opcode_prefix => try self.ext(current, frame),
// CreateXField: source, index, name (bit widths differ by op)
opcode.create_bit_field_opcode => try self.createField(current, frame, 1),
opcode.create_byte_field_opcode => try self.createField(current, frame, 8),
opcode.create_word_field_opcode => try self.createField(current, frame, 16),
opcode.create_dword_field_opcode => try self.createField(current, frame, 32),
opcode.create_qword_field_opcode => try self.createField(current, frame, 64),
else => error.Unsupported,
};
}
// --- name references ----------------------------------------------------
fn nameReference(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const name_path = try current.nameString();
const node = self.namespace.resolve(frame.scope, name_path.rooted, name_path.parents, name_path.slice()) orelse
return .uninitialized; // unknown name -> treat as uninitialised
switch (node.kind) {
.method => {
var argbuf: [7]Object = undefined;
var i: usize = 0;
while (i < node.arg_count and i < argbuf.len) : (i += 1) argbuf[i] = try self.term(current, frame);
return self.invoke(node, argbuf[0..@min(node.arg_count, argbuf.len)]);
},
.field => return .{ .integer = try self.readField(node) },
.name => return self.invoke(node, &.{}),
else => return .{ .reference = node },
}
}
// --- data objects -------------------------------------------------------
fn readConstant(self: *Interpreter, current: *Cursor, n: usize) Error!u64 {
_ = self;
const bytes = try current.take(n);
var v: u64 = 0;
for (bytes, 0..) |b, i| v |= @as(u64, b) << @intCast(i * 8);
return v;
}
fn readString(self: *Interpreter, current: *Cursor) Error!Object {
const start = current.i;
while (current.peek()) |c| {
current.i += 1;
if (c == 0) break;
}
const raw = current.b[start .. current.i - 1];
const s = try self.arena.dupe(u8, raw);
return .{ .string = s };
}
fn buffer(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const start = current.i;
const len = try current.packageLength();
const end = @min(start + len, current.b.len);
const size = try self.evaluateInteger(current, frame);
const data = current.b[@min(current.i, end)..end];
const bytes = try self.arena.alloc(u8, @intCast(size));
@memset(bytes, 0);
@memcpy(bytes[0..@min(bytes.len, data.len)], data[0..@min(bytes.len, data.len)]);
current.i = end;
return .{ .buffer = bytes };
}
fn package(self: *Interpreter, current: *Cursor, frame: *Frame, variable: bool) Error!Object {
const start = current.i;
const len = try current.packageLength();
const end = @min(start + len, current.b.len);
const count: usize = if (variable) @intCast(try self.evaluateInteger(current, frame)) else try current.byte();
const elems = try self.arena.alloc(Object, count);
var i: usize = 0;
while (i < count and current.i < end) : (i += 1) elems[i] = try self.term(current, frame);
while (i < count) : (i += 1) elems[i] = .uninitialized;
current.i = end;
return .{ .package = elems };
}
// --- operators ----------------------------------------------------------
const BinaryOperation = enum { add, sub, mul, mod, band, bor, bxor, nand, nor, shl, shr };
fn binary(self: *Interpreter, current: *Cursor, frame: *Frame, kind: BinaryOperation) Error!Object {
const a = try self.evaluateInteger(current, frame);
const b = try self.evaluateInteger(current, frame);
const r: u64 = switch (kind) {
.add => a +% b,
.sub => a -% b,
.mul => a *% b,
.mod => if (b == 0) return error.DivByZero else a % b,
.band => a & b,
.bor => a | b,
.bxor => a ^ b,
.nand => ~(a & b),
.nor => ~(a | b),
.shl => if (b >= 64) 0 else a << @intCast(b),
.shr => if (b >= 64) 0 else a >> @intCast(b),
};
try self.storeTarget(current, frame, .{ .integer = r });
return .{ .integer = r };
}
fn divide(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const a = try self.evaluateInteger(current, frame);
const b = try self.evaluateInteger(current, frame);
if (b == 0) return error.DivByZero;
try self.storeTarget(current, frame, .{ .integer = a % b }); // remainder target
try self.storeTarget(current, frame, .{ .integer = a / b }); // quotient target
return .{ .integer = a / b };
}
const LogicOperation = enum { land, lor, eq, gt, lt };
fn logic2(self: *Interpreter, current: *Cursor, frame: *Frame, kind: LogicOperation) Error!Object {
const a = try self.evaluateInteger(current, frame);
const b = try self.evaluateInteger(current, frame);
const r = switch (kind) {
.land => a != 0 and b != 0,
.lor => a != 0 or b != 0,
.eq => a == b,
.gt => a > b,
.lt => a < b,
};
return .{ .integer = if (r) ~@as(u64, 0) else 0 };
}
fn lnot(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
// 0x92 0x93/94/95 are the compound comparisons.
const b = current.peek() orelse return error.Truncated;
switch (b) {
opcode.lnot.not_equal => {
current.i += 1;
const x = try self.evaluateInteger(current, frame);
const y = try self.evaluateInteger(current, frame);
return .{ .integer = if (x != y) ~@as(u64, 0) else 0 };
},
opcode.lnot.less_equal => {
current.i += 1;
const x = try self.evaluateInteger(current, frame);
const y = try self.evaluateInteger(current, frame);
return .{ .integer = if (x <= y) ~@as(u64, 0) else 0 };
},
opcode.lnot.greater_equal => {
current.i += 1;
const x = try self.evaluateInteger(current, frame);
const y = try self.evaluateInteger(current, frame);
return .{ .integer = if (x >= y) ~@as(u64, 0) else 0 };
},
else => {
const x = try self.evaluateInteger(current, frame);
return .{ .integer = if (x == 0) ~@as(u64, 0) else 0 };
},
}
}
fn incDec(self: *Interpreter, current: *Cursor, frame: *Frame, delta: i64) Error!Object {
// Operand is a SuperName that is both read and written.
const save = current.i;
const current_value = try self.term(current, frame);
const v = try current_value.asInteger();
const r = if (delta > 0) v +% 1 else v -% 1;
var tcur = Cursor{ .b = current.b, .i = save };
try self.storeInto(&tcur, frame, .{ .integer = r });
return .{ .integer = r };
}
fn sizeOf(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const o = try self.term(current, frame);
return .{ .integer = switch (o) {
.buffer => |b| b.len,
.string => |s| s.len,
.package => |p| p.len,
else => 0,
} };
}
fn passThroughUnary(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const o = try self.term(current, frame);
try self.storeTarget(current, frame, o);
return o;
}
fn index(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const source = try self.term(current, frame);
const element_index: usize = @intCast(try self.evaluateInteger(current, frame));
// Optional target (a reference); we don't materialise references, so store
// the indexed value if a target is present.
const value: Object = switch (source) {
.buffer => |b| .{ .integer = if (element_index < b.len) b[element_index] else 0 },
.package => |p| if (element_index < p.len) p[element_index] else .uninitialized,
.string => |s| .{ .integer = if (element_index < s.len) s[element_index] else 0 },
else => .uninitialized,
};
try self.storeTarget(current, frame, value);
return value;
}
fn dereferenceOf(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const o = try self.term(current, frame);
return switch (o) {
.reference => |n| self.invoke(n, &.{}),
else => o,
};
}
// --- control flow -------------------------------------------------------
fn ifElse(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const start = current.i;
const end = @min(start + try current.packageLength(), current.b.len);
const cond = try self.evaluateInteger(current, frame);
if (cond != 0) {
var body = Cursor{ .b = current.b[0..end], .i = current.i };
try self.executeList(&body, frame);
current.i = end;
// Skip a trailing Else.
if (current.peek() == opcode.else_opcode) {
current.i += 1;
const es = current.i;
const ee = @min(es + try current.packageLength(), current.b.len);
current.i = ee;
}
} else {
current.i = end;
if (current.peek() == opcode.else_opcode) {
current.i += 1;
const es = current.i;
const ee = @min(es + try current.packageLength(), current.b.len);
var body = Cursor{ .b = current.b[0..ee], .i = current.i };
try self.executeList(&body, frame);
current.i = ee;
}
}
return .uninitialized;
}
fn whileLoop(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const start = current.i;
const end = @min(start + try current.packageLength(), current.b.len);
const pred_at = current.i;
var guard: usize = 0;
while (guard < 100_000) : (guard += 1) {
var pc = Cursor{ .b = current.b[0..end], .i = pred_at };
const cond = try self.evaluateInteger(&pc, frame);
if (cond == 0) break;
var body = Cursor{ .b = current.b[0..end], .i = pc.i };
try self.executeList(&body, frame);
if (frame.returned) break;
if (frame.broke) {
frame.broke = false;
break;
}
}
current.i = end;
return .uninitialized;
}
// --- store --------------------------------------------------------------
fn store(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const value = try self.term(current, frame);
try self.storeInto(current, frame, value);
return value;
}
/// A Store *target* that may be NullName (no store).
fn storeTarget(self: *Interpreter, current: *Cursor, frame: *Frame, value: Object) Error!void {
if (current.peek() == 0x00) {
current.i += 1; // NullName
return;
}
try self.storeInto(current, frame, value);
}
/// Notify(SuperName, NotifyValue): resolve the named device, evaluate the
/// code, and record the pair for the caller to dispatch. AML control flow
/// continues (Notify returns nothing).
fn notify(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const lead = current.peek() orelse return error.Truncated;
var target: ?*Node = null;
if (isNameStart(lead)) {
const name_path = try current.nameString();
target = self.namespace.resolve(frame.scope, name_path.rooted, name_path.parents, name_path.slice());
} else {
// A non-name SuperName (Local/Arg holding a reference).
const obj = try self.term(current, frame);
if (obj == .reference) target = obj.reference;
}
const code = try self.evaluateInteger(current, frame);
if (target) |node| {
if (self.notify_count < self.notify_queue.len) {
self.notify_queue[self.notify_count] = .{ .node = node, .code = code };
self.notify_count += 1;
}
}
return .uninitialized;
}
/// The Notify events the last `evaluate` produced. Valid until the next
/// `evaluate` clears the queue.
pub fn takeNotifications(self: *Interpreter) []const NotifyEvent {
return self.notify_queue[0..self.notify_count];
}
fn storeInto(self: *Interpreter, current: *Cursor, frame: *Frame, value: Object) Error!void {
const lead = current.peek() orelse return error.Truncated;
if (isNameStart(lead)) {
const name_path = try current.nameString();
const node = self.namespace.resolve(frame.scope, name_path.rooted, name_path.parents, name_path.slice()) orelse return;
if (self.fields.get(node)) |buffer_field| {
try self.writeBufferField(buffer_field, try value.asInteger());
} else if (node.kind == .field) {
try self.writeField(node, try value.asInteger());
} else {
try self.dynamic_overrides.put(self.arena, node, value);
}
return;
}
_ = try current.byte();
switch (lead) {
0x00 => {}, // NullName
opcode.local0_opcode...opcode.local7_opcode => frame.locals[lead - opcode.local0_opcode] = value,
opcode.arg0_opcode...opcode.arg6_opcode => frame.args[lead - opcode.arg0_opcode] = value,
opcode.index_opcode => {
const source = try self.term(current, frame);
const element_index: usize = @intCast(try self.evaluateInteger(current, frame));
switch (source) {
.buffer => |b| if (element_index < b.len) {
b[element_index] = @truncate(try value.asInteger());
},
.package => |p| if (element_index < p.len) {
p[element_index] = value;
},
else => {},
}
},
else => return error.Unsupported,
}
}
// --- CreateField (buffer patching) --------------------------------------
fn createField(self: *Interpreter, current: *Cursor, frame: *Frame, bit_width: u32) Error!Object {
const source = try self.term(current, frame); // source buffer (as a reference or value)
const bit_index = try self.evaluateInteger(current, frame);
const name_path = try current.nameString();
const node = self.namespace.resolve(frame.scope, name_path.rooted, name_path.parents, name_path.slice()) orelse return .uninitialized;
// Bind the new name to the source buffer's node so stores land in it.
const buffer_node: *Node = switch (source) {
.reference => |n| n,
else => return .uninitialized,
};
// Materialise the buffer into `dynamic_overrides` so patches persist and are returned.
if (self.dynamic_overrides.get(buffer_node) == null) {
const value = try self.invoke(buffer_node, &.{});
try self.dynamic_overrides.put(self.arena, buffer_node, value);
}
const byte_off: usize = @intCast(bit_index / 8);
try self.fields.put(self.arena, node, .{ .buffer = buffer_node, .byte_off = byte_off, .bit_width = bit_width });
return .uninitialized;
}
fn writeBufferField(self: *Interpreter, buffer_field: BufferField, value: u64) Error!void {
const obj = self.dynamic_overrides.get(buffer_field.buffer) orelse return;
const bytes = switch (obj) {
.buffer => |b| b,
else => return,
};
const byte_count = (buffer_field.bit_width + 7) / 8;
var k: usize = 0;
while (k < byte_count and buffer_field.byte_off + k < bytes.len) : (k += 1) {
bytes[buffer_field.byte_off + k] = @truncate(value >> @intCast(k * 8));
}
}
// --- OperationRegion field access ---------------------------------------
fn readField(self: *Interpreter, field: *Node) Error!u64 {
const region = field.region orelse return error.Unsupported;
if (field.bit_width == 0 or field.bit_width > 64) return error.Unsupported;
const base = try self.regionBase(region);
const start_byte = base + field.bit_offset / 8;
const shift: u7 = @intCast(field.bit_offset % 8);
const total = @as(usize, shift) + field.bit_width;
const byte_count = (total + 7) / 8;
var raw: u128 = 0;
var k: usize = 0;
while (k < byte_count) : (k += 1) {
raw |= @as(u128, try self.readRegionByte(region.region_space, start_byte + k)) << @intCast(k * 8);
}
const masked = (raw >> shift) & bitMask(field.bit_width);
return @truncate(masked);
}
fn writeField(self: *Interpreter, field: *Node, value: u64) Error!void {
const region = field.region orelse return error.Unsupported;
if (field.bit_width == 0 or field.bit_width > 64) return error.Unsupported;
const base = try self.regionBase(region);
const start_byte = base + field.bit_offset / 8;
const shift: u7 = @intCast(field.bit_offset % 8);
const total = @as(usize, shift) + field.bit_width;
const byte_count = (total + 7) / 8;
// Read-modify-write byte by byte.
var raw: u128 = 0;
var k: usize = 0;
while (k < byte_count) : (k += 1) {
raw |= @as(u128, try self.readRegionByte(region.region_space, start_byte + k)) << @intCast(k * 8);
}
const mask = bitMask(field.bit_width) << shift;
raw = (raw & ~mask) | ((@as(u128, value) << shift) & mask);
k = 0;
while (k < byte_count) : (k += 1) {
try self.writeRegionByte(region.region_space, start_byte + k, @truncate(raw >> @intCast(k * 8)));
}
}
fn regionBase(self: *Interpreter, region: *Node) Error!u64 {
var current = Cursor{ .b = region.region_offset_aml };
var frame = Frame{ .scope = region.parent orelse self.namespace.root };
return (try self.term(&current, &frame)).asInteger();
}
fn readRegionByte(self: *Interpreter, space: u8, address: u64) Error!u8 {
switch (space) {
0 => { // SystemMemory
const virtual = self.hal.mapMmio(address & ~@as(u64, 0xFFF), 0x1000, true);
const p: *align(1) const volatile u8 = @ptrFromInt(virtual + (address & 0xFFF));
return p.*;
},
1 => return @truncate(self.hal.pioRead(1, @intCast(address & 0xFFFF))), // SystemIO
else => return error.Unsupported,
}
}
fn writeRegionByte(self: *Interpreter, space: u8, address: u64, value: u8) Error!void {
switch (space) {
0 => {
const virtual = self.hal.mapMmio(address & ~@as(u64, 0xFFF), 0x1000, true);
const p: *align(1) volatile u8 = @ptrFromInt(virtual + (address & 0xFFF));
p.* = value;
},
1 => self.hal.pioWrite(1, @intCast(address & 0xFFFF), value),
else => return error.Unsupported,
}
}
// --- extended opcodes ---------------------------------------------------
fn ext(self: *Interpreter, current: *Cursor, frame: *Frame) Error!Object {
const e = try current.byte();
switch (e) {
opcode.extended.debug => return .uninitialized,
opcode.extended.revision => return .{ .integer = 2 },
opcode.extended.timer => return .{ .integer = 0 },
// Mutex/Event ops are no-ops in this single-threaded evaluator.
opcode.extended.acquire => {
_ = try self.term(current, frame); // mutex SuperName
_ = try current.take(2); // timeout
return .{ .integer = 0 }; // acquired
},
opcode.extended.release, opcode.extended.reset, opcode.extended.signal => {
_ = try self.term(current, frame);
return .uninitialized;
},
opcode.extended.wait => {
_ = try self.term(current, frame);
_ = try self.term(current, frame);
return .{ .integer = 0 };
},
opcode.extended.sleep, opcode.extended.stall => {
_ = try self.term(current, frame);
return .uninitialized;
},
else => return error.Unsupported,
}
}
fn evaluateInteger(self: *Interpreter, current: *Cursor, frame: *Frame) Error!u64 {
return (try self.term(current, frame)).asInteger();
}
};
fn bitMask(width: u32) u128 {
if (width >= 128) return ~@as(u128, 0);
return (@as(u128, 1) << @intCast(width)) - 1;
}
fn isNameStart(b: u8) bool {
return (b >= opcode.name_char_start and b <= opcode.name_char_end) or
b == opcode.name_char_underscore or
b == opcode.root_char or
b == opcode.parent_prefix_char or
b == opcode.dual_name_prefix or
b == opcode.multi_name_prefix;
}
-181
View File
@@ -1,181 +0,0 @@
//! The ACPI namespace the AML parser builds: a tree of named nodes, plus the name
//! resolution rules the parser needs while it walks (so a method invocation can be
//! resolved to its declaration to learn its argument count).
//!
//! Nodes are individually allocated and linked intrusively (first-child /
//! next-sibling), the same shape as the device tree in `device.zig`.
const std = @import("std");
pub const NodeKind = enum {
root,
scope,
device,
method,
name,
region, // OperationRegion
field, // a Field unit
mutex,
event,
processor,
power_resource,
thermal_zone,
alias,
external,
other,
};
pub const Node = struct {
/// The 4-byte NameSeg identifying this node within its parent. The root uses
/// all-zero.
segment: [4]u8 = .{ 0, 0, 0, 0 },
kind: NodeKind = .other,
/// For Method / External: the declared argument count (0..7). Used to resolve
/// how many TermArgs a method invocation consumes.
arg_count: u8 = 0,
/// For Name: the AML bytes of its DataReferenceObject (so a value like a sleep
/// state's (`_Sx`) Package can be parsed on demand). For Method: the AML bytes of the body,
/// interpreted on demand by the evaluator. Empty otherwise.
value: []const u8 = &.{},
// OperationRegion metadata (kind == .region): the address space, plus the AML
// of the offset/length expressions (evaluated lazily, usually constants).
region_space: u8 = 0,
region_offset_aml: []const u8 = &.{},
region_len_aml: []const u8 = &.{},
// Field-unit metadata (kind == .field): which region it lives in and its bit
// position/width/access, so the evaluator can read/write it.
region: ?*Node = null,
bit_offset: u32 = 0,
bit_width: u32 = 0,
access_type: u8 = 0,
parent: ?*Node = null,
first_child: ?*Node = null,
next_sibling: ?*Node = null,
/// Depth-first count of this node and everything under it.
pub fn subtreeCount(self: *const Node) usize {
var n: usize = 1;
var c = self.first_child;
while (c) |child| : (c = child.next_sibling) n += child.subtreeCount();
return n;
}
};
pub const Namespace = struct {
allocator: std.mem.Allocator,
root: *Node,
pub fn init(allocator: std.mem.Allocator) !Namespace {
const root = try allocator.create(Node);
root.* = .{ .kind = .root };
return .{ .allocator = allocator, .root = root };
}
pub fn nodeCount(self: *const Namespace) usize {
return self.root.subtreeCount();
}
fn findChild(parent: *Node, segment: [4]u8) ?*Node {
var c = parent.first_child;
while (c) |child| : (c = child.next_sibling) {
if (std.mem.eql(u8, &child.segment, &segment)) return child;
}
return null;
}
/// The direct child of `node` named `segment`, or null. Unlike `resolve`, this does
/// not apply the search-rule walk-up — it looks only at immediate children (for
/// reading a device's own hardware ID (`_HID`) / current resource settings (`_CRS`)).
pub fn childOf(node: *Node, segment: [4]u8) ?*Node {
return findChild(node, segment);
}
fn newChild(self: *Namespace, parent: *Node, segment: [4]u8, kind: NodeKind) !*Node {
const n = try self.allocator.create(Node);
n.* = .{ .segment = segment, .kind = kind, .parent = parent };
// Append at the tail so a dump reads in declaration order.
if (parent.first_child == null) {
parent.first_child = n;
} else {
var current = parent.first_child.?;
while (current.next_sibling) |sib| current = sib;
current.next_sibling = n;
}
return n;
}
/// Create a Field unit node directly under `scope` (field units live in the
/// scope of the Field/IndexField/BankField, not under the region).
pub fn newFieldUnit(self: *Namespace, scope: *Node, segment: [4]u8) !*Node {
return self.findOrCreate(scope, segment, .field);
}
fn findOrCreate(self: *Namespace, parent: *Node, segment: [4]u8, kind: NodeKind) !*Node {
if (findChild(parent, segment)) |existing| {
// Reopening a scope (e.g. Scope(\_SB) after Device \_SB) keeps the more
// specific kind rather than downgrading to a plain scope.
if (existing.kind == .scope and kind != .scope) existing.kind = kind;
return existing;
}
return self.newChild(parent, segment, kind);
}
/// The node a definition's NameString names, creating any intermediate scopes.
/// The final segment is created (or found) with `kind`; intermediates are
/// scopes. Returns the namespace root for a NullName (empty path).
pub fn place(
self: *Namespace,
current: *Node,
rooted: bool,
parents: u8,
segments: []const [4]u8,
kind: NodeKind,
) !*Node {
var base = startNode(self, current, rooted, parents);
if (segments.len == 0) return base;
var i: usize = 0;
while (i + 1 < segments.len) : (i += 1) {
base = try self.findOrCreate(base, segments[i], .scope);
}
return self.findOrCreate(base, segments[segments.len - 1], kind);
}
/// Resolve a NameString *reference* to an existing node, or null. A single
/// relative segment uses the ACPI search rule (walk up the ancestors); any
/// rooted, parented, or multi-segment path is resolved exactly.
pub fn resolve(
self: *Namespace,
current: *Node,
rooted: bool,
parents: u8,
segments: []const [4]u8,
) ?*Node {
if (segments.len == 0) return null;
if (!rooted and parents == 0 and segments.len == 1) {
// Search rule: this scope, then each ancestor up to the root.
var scope: ?*Node = current;
while (scope) |s| : (scope = s.parent) {
if (findChild(s, segments[0])) |n| return n;
}
return null;
}
var base = startNode(self, current, rooted, parents);
for (segments) |segment| {
base = findChild(base, segment) orelse return null;
}
return base;
}
fn startNode(self: *Namespace, current: *Node, rooted: bool, parents: u8) *Node {
if (rooted) return self.root;
var base = current;
var up = parents;
while (up > 0) : (up -= 1) base = base.parent orelse self.root;
return base;
}
};
-137
View File
@@ -1,137 +0,0 @@
//! AML opcode constants — the full ACPI Machine Language opcode table.
//!
//! Single-byte opcodes are plain values. Extended opcodes are a two-byte sequence
//! `ext_prefix` (0x5B) followed by a byte listed under `ext`. A few comparison
//! opcodes are `lnot_opcode` (0x92) followed by a second byte (see `lnot`).
// --- name / path characters -------------------------------------------------
pub const zero_opcode = 0x00;
pub const one_opcode = 0x01;
pub const alias_opcode = 0x06;
pub const name_opcode = 0x08;
pub const byte_prefix = 0x0A;
pub const word_prefix = 0x0B;
pub const dword_prefix = 0x0C;
pub const string_prefix = 0x0D;
pub const qword_prefix = 0x0E;
pub const scope_opcode = 0x10;
pub const buffer_opcode = 0x11;
pub const package_opcode = 0x12;
pub const var_package_opcode = 0x13;
pub const method_opcode = 0x14;
pub const external_opcode = 0x15;
pub const dual_name_prefix = 0x2E;
pub const multi_name_prefix = 0x2F;
pub const extended_opcode_prefix = 0x5B;
pub const root_char = 0x5C;
pub const parent_prefix_char = 0x5E;
pub const name_char_underscore = 0x5F;
pub const digit_char_start = 0x30;
pub const digit_char_end = 0x39;
pub const name_char_start = 0x41; // 'A'
pub const name_char_end = 0x5A; // 'Z'
// --- locals / args ----------------------------------------------------------
pub const local0_opcode = 0x60;
pub const local7_opcode = 0x67;
pub const arg0_opcode = 0x68;
pub const arg6_opcode = 0x6E;
// --- store / references / arithmetic ---------------------------------------
pub const store_opcode = 0x70;
pub const ref_of_opcode = 0x71;
pub const add_opcode = 0x72;
pub const concat_opcode = 0x73;
pub const subtract_opcode = 0x74;
pub const increment_opcode = 0x75;
pub const decrement_opcode = 0x76;
pub const multiply_opcode = 0x77;
pub const divide_opcode = 0x78;
pub const shift_left_opcode = 0x79;
pub const shift_right_opcode = 0x7A;
pub const and_opcode = 0x7B;
pub const nand_opcode = 0x7C;
pub const or_opcode = 0x7D;
pub const nor_opcode = 0x7E;
pub const xor_opcode = 0x7F;
pub const not_opcode = 0x80;
pub const find_set_left_bit_opcode = 0x81;
pub const find_set_right_bit_opcode = 0x82;
pub const dereference_of_opcode = 0x83;
pub const concat_resource_opcode = 0x84;
pub const mod_opcode = 0x85;
pub const notify_opcode = 0x86;
pub const size_of_opcode = 0x87;
pub const index_opcode = 0x88;
pub const match_opcode = 0x89;
pub const create_dword_field_opcode = 0x8A;
pub const create_word_field_opcode = 0x8B;
pub const create_byte_field_opcode = 0x8C;
pub const create_bit_field_opcode = 0x8D;
pub const object_type_opcode = 0x8E;
pub const create_qword_field_opcode = 0x8F;
pub const land_opcode = 0x90;
pub const lor_opcode = 0x91;
pub const lnot_opcode = 0x92; // may be followed by a second byte (see `lnot`)
pub const lequal_opcode = 0x93;
pub const lgreater_opcode = 0x94;
pub const lless_opcode = 0x95;
pub const to_buffer_opcode = 0x96;
pub const to_decimal_string_opcode = 0x97;
pub const to_hex_string_opcode = 0x98;
pub const to_integer_opcode = 0x99;
pub const to_string_opcode = 0x9C;
pub const copy_object_opcode = 0x9D;
pub const mid_opcode = 0x9E;
pub const continue_opcode = 0x9F;
pub const if_opcode = 0xA0;
pub const else_opcode = 0xA1;
pub const while_opcode = 0xA2;
pub const noop_opcode = 0xA3;
pub const return_opcode = 0xA4;
pub const break_opcode = 0xA5;
pub const break_point_opcode = 0xCC;
pub const ones_opcode = 0xFF;
/// Second bytes of the `lnot_opcode` (0x92) compound comparison opcodes.
pub const lnot = struct {
pub const not_equal = 0x93; // LNotEqualOp: 0x92 0x93
pub const less_equal = 0x94; // LLessEqualOp: 0x92 0x94
pub const greater_equal = 0x95; // LGreaterEqualOp: 0x92 0x95
};
/// Second bytes of extended opcodes (prefixed by `extended_opcode_prefix`, 0x5B).
pub const extended = struct {
pub const mutex = 0x01;
pub const event = 0x02;
pub const conditional_reference_of = 0x12;
pub const create_field = 0x13;
pub const load_table = 0x1F;
pub const load = 0x20;
pub const stall = 0x21;
pub const sleep = 0x22;
pub const acquire = 0x23;
pub const signal = 0x24;
pub const wait = 0x25;
pub const reset = 0x26;
pub const release = 0x27;
pub const from_bcd = 0x28;
pub const to_bcd = 0x29;
pub const unload = 0x2A;
pub const revision = 0x30;
pub const debug = 0x31;
pub const fatal = 0x32;
pub const timer = 0x33;
pub const operation_region = 0x80;
pub const field = 0x81;
pub const device = 0x82;
pub const processor = 0x83;
pub const power_resource = 0x84;
pub const thermal_zone = 0x85;
pub const index_field = 0x86;
pub const bank_field = 0x87;
pub const data_region = 0x88;
};
-517
View File
@@ -1,517 +0,0 @@
//! Recursive-descent AML parser. Walks the entire byte stream — including method
//! bodies — building the ACPI namespace as it goes. It does not *evaluate*
//! anything (no OperationRegion reads, no arithmetic); it parses structure so the
//! cursor stays aligned and every named object is recorded.
//!
//! The one genuine ambiguity in AML is method invocation: a bare NameString in an
//! operand position is a call whose argument count is only known from the method's
//! (earlier) declaration. Because we build the namespace in the same in-order pass,
//! `resolve` finds that declaration and tells us how many operands to consume.
//!
//! Safety net: every object delimited by a PkgLength (Scope/Device/Method/If/While/
//! Field/Buffer/Package/…) is parsed within its known extent, and the cursor is
//! snapped to that extent afterwards. So a mis-resolved invocation can only desync
//! *within* one such object; the enclosing walk realigns at the boundary.
const std = @import("std");
const opcode = @import("opcodes.zig");
const Namespace = @import("namespace.zig").Namespace;
const Node = @import("namespace.zig").Node;
const NodeKind = @import("namespace.zig").NodeKind;
pub const Error = error{ Truncated, Malformed } || std.mem.Allocator.Error;
const maximum_segments = 64;
/// A parsed NameString: an optional root anchor or some parent hops, then a list
/// of 4-byte segments.
const NamePath = struct {
rooted: bool = false,
parents: u8 = 0,
segments: [maximum_segments][4]u8 = undefined,
count: usize = 0,
fn slice(self: *const NamePath) []const [4]u8 {
return self.segments[0..self.count];
}
};
pub const Parser = struct {
aml: []const u8,
position: usize = 0,
namespace: *Namespace,
pub fn init(aml: []const u8, namespace: *Namespace) Parser {
return .{ .aml = aml, .namespace = namespace };
}
/// Parse the whole block as a TermList under the namespace root. Returns the
/// number of bytes consumed — equal to `aml.len` for a clean full traversal.
pub fn parseAll(self: *Parser) usize {
self.termList(self.aml.len, self.namespace.root);
return self.position;
}
// --- cursor primitives --------------------------------------------------
fn eof(self: *Parser) bool {
return self.position >= self.aml.len;
}
fn peek(self: *Parser) ?u8 {
return if (self.eof()) null else self.aml[self.position];
}
fn readByte(self: *Parser) Error!u8 {
if (self.eof()) return error.Truncated;
const b = self.aml[self.position];
self.position += 1;
return b;
}
fn skip(self: *Parser, n: usize) Error!void {
if (self.position + n > self.aml.len) return error.Truncated;
self.position += n;
}
fn skipCString(self: *Parser) Error!void {
while (true) {
const b = try self.readByte();
if (b == 0) return;
}
}
/// AML PkgLength: the lead byte's top two bits give how many extra bytes
/// follow; the value counts from the start of the PkgLength field.
fn readPackageLength(self: *Parser) Error!usize {
const lead = try self.readByte();
const follow: usize = lead >> 6;
if (follow == 0) return lead & 0x3F;
var value: usize = lead & 0x0F;
var i: usize = 0;
while (i < follow) : (i += 1) {
const b = try self.readByte();
value |= @as(usize, b) << @intCast(4 + i * 8);
}
return value;
}
fn readNameSegment(self: *Parser) Error![4]u8 {
if (self.position + 4 > self.aml.len) return error.Truncated;
const segment = self.aml[self.position..][0..4].*;
self.position += 4;
return segment;
}
fn readNameString(self: *Parser) Error!NamePath {
var name_path = NamePath{};
// A NameString is either root-anchored or parent-relative, not both.
if (self.peek() == opcode.root_char) {
name_path.rooted = true;
self.position += 1;
} else {
while (self.peek() == opcode.parent_prefix_char) : (self.position += 1) name_path.parents += 1;
}
const lead = self.peek() orelse return name_path;
switch (lead) {
0x00 => self.position += 1, // NullName
opcode.dual_name_prefix => {
self.position += 1;
try self.appendSegment(&name_path);
try self.appendSegment(&name_path);
},
opcode.multi_name_prefix => {
self.position += 1;
const count = try self.readByte();
var i: usize = 0;
while (i < count) : (i += 1) try self.appendSegment(&name_path);
},
else => {
if (isNameStart(lead)) try self.appendSegment(&name_path);
},
}
return name_path;
}
fn appendSegment(self: *Parser, name_path: *NamePath) Error!void {
const segment = try self.readNameSegment();
if (name_path.count < maximum_segments) {
name_path.segments[name_path.count] = segment;
name_path.count += 1;
}
}
// --- term list / object -------------------------------------------------
/// Parse objects until `end`, then snap to `end`. Any parse error resyncs to
/// the boundary rather than propagating — containment for the rare desync.
fn termList(self: *Parser, end: usize, scope: *Node) void {
while (self.position < end) {
self.object(scope) catch break;
}
self.position = end;
}
/// Parse exactly one object/term at the cursor. Used for both TermObjs and
/// operands (TermArg / SuperName / Target all reduce to "one object" for the
/// purpose of advancing the cursor).
fn object(self: *Parser, scope: *Node) Error!void {
const lead = self.peek() orelse return error.Truncated;
if (isNameStart(lead)) return self.nameInvocation(scope);
_ = try self.readByte();
switch (lead) {
// constants and no-operand statements
opcode.zero_opcode, opcode.one_opcode, opcode.ones_opcode => {},
opcode.noop_opcode, opcode.continue_opcode, opcode.break_opcode, opcode.break_point_opcode => {},
opcode.local0_opcode...opcode.local7_opcode => {},
opcode.arg0_opcode...opcode.arg6_opcode => {},
// literal data
opcode.byte_prefix => try self.skip(1),
opcode.word_prefix => try self.skip(2),
opcode.dword_prefix => try self.skip(4),
opcode.qword_prefix => try self.skip(8),
opcode.string_prefix => try self.skipCString(),
// data containers (contents skipped via their PkgLength)
opcode.buffer_opcode, opcode.package_opcode, opcode.var_package_opcode => try self.skipPackage(),
// namespace modifiers / named objects
opcode.name_opcode => try self.parseName(scope),
opcode.alias_opcode => try self.parseAlias(scope),
opcode.scope_opcode => try self.parseScopeLike(scope, .scope),
opcode.method_opcode => try self.parseMethod(scope),
opcode.external_opcode => try self.parseExternal(scope),
opcode.extended_opcode_prefix => try self.parseExtended(scope),
// control flow
opcode.if_opcode => try self.parseIf(scope),
opcode.else_opcode => try self.parseElse(scope),
opcode.while_opcode => try self.parseWhile(scope),
opcode.return_opcode => try self.object(scope),
opcode.notify_opcode => try self.args(scope, 2),
// stores / references / unary+target
opcode.store_opcode => try self.args(scope, 2),
opcode.ref_of_opcode, opcode.dereference_of_opcode, opcode.size_of_opcode, opcode.object_type_opcode => try self.args(scope, 1),
opcode.increment_opcode, opcode.decrement_opcode => try self.args(scope, 1),
opcode.not_opcode, opcode.find_set_left_bit_opcode, opcode.find_set_right_bit_opcode => try self.args(scope, 2),
opcode.to_buffer_opcode, opcode.to_decimal_string_opcode, opcode.to_hex_string_opcode, opcode.to_integer_opcode => try self.args(scope, 2),
opcode.copy_object_opcode => try self.args(scope, 2),
// binary + target
opcode.add_opcode, opcode.subtract_opcode, opcode.multiply_opcode, opcode.mod_opcode => try self.args(scope, 3),
opcode.and_opcode, opcode.nand_opcode, opcode.or_opcode, opcode.nor_opcode, opcode.xor_opcode => try self.args(scope, 3),
opcode.shift_left_opcode, opcode.shift_right_opcode, opcode.concat_opcode, opcode.concat_resource_opcode, opcode.index_opcode => try self.args(scope, 3),
opcode.divide_opcode => try self.args(scope, 4),
opcode.to_string_opcode => try self.args(scope, 3),
opcode.mid_opcode => try self.args(scope, 4),
// logical
opcode.land_opcode, opcode.lor_opcode => try self.args(scope, 2),
opcode.lequal_opcode, opcode.lgreater_opcode, opcode.lless_opcode => try self.args(scope, 2),
opcode.lnot_opcode => try self.parseLnot(scope),
opcode.match_opcode => try self.parseMatch(scope),
// CreateXField: <source> <index> NameString
opcode.create_dword_field_opcode,
opcode.create_word_field_opcode,
opcode.create_byte_field_opcode,
opcode.create_bit_field_opcode,
opcode.create_qword_field_opcode,
=> try self.parseCreateField(scope, 2),
else => return error.Malformed,
}
}
/// Parse `n` operands.
fn args(self: *Parser, scope: *Node, n: usize) Error!void {
var i: usize = 0;
while (i < n) : (i += 1) try self.object(scope);
}
/// A NameString in operand/statement position: a method invocation (consuming
/// the callee's declared argument count) or a plain name reference.
fn nameInvocation(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
if (self.namespace.resolve(scope, name_path.rooted, name_path.parents, name_path.slice())) |node| {
if ((node.kind == .method or node.kind == .external) and node.arg_count > 0) {
try self.args(scope, node.arg_count);
}
}
}
/// Skip a PkgLength-delimited body wholesale (Buffer / Package / VarPackage):
/// the contents are pure data, never namespace declarations.
fn skipPackage(self: *Parser) Error!void {
const start = self.position;
const len = try self.readPackageLength();
const end = start + len;
if (end > self.aml.len) return error.Truncated;
self.position = end;
}
// --- namespace objects --------------------------------------------------
fn parseName(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
const value_start = self.position;
try self.object(scope); // the DataReferenceObject value
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .name);
node.value = self.aml[value_start..self.position];
}
fn parseAlias(self: *Parser, scope: *Node) Error!void {
_ = try self.readNameString(); // source
const name_path = try self.readNameString(); // the alias name
_ = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .alias);
}
fn parseMethod(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
const name_path = try self.readNameString();
const flags = try self.readByte();
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .method);
node.arg_count = flags & 0x7;
// Capture the body for on-demand evaluation and skip it — objects declared
// inside a method are created at *runtime*, not at load, so they must not
// become permanent namespace nodes.
node.value = self.aml[self.position..@min(end, self.aml.len)];
self.position = end;
}
fn parseExternal(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
_ = try self.readByte(); // object type
const arg_count = try self.readByte();
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .external);
node.arg_count = arg_count;
}
/// Scope / Device / ThermalZone: PkgLength, NameString, then a nested TermList.
fn parseScopeLike(self: *Parser, scope: *Node, kind: NodeKind) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
const name_path = try self.readNameString();
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), kind);
self.termList(end, node);
}
fn parseProcessor(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
const name_path = try self.readNameString();
try self.skip(6); // ProcID(byte) + PblkAddress(dword) + PblkLen(byte)
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .processor);
self.termList(end, node);
}
fn parsePowerResource(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
const name_path = try self.readNameString();
try self.skip(3); // SystemLevel(byte) + ResourceOrder(word)
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .power_resource);
self.termList(end, node);
}
/// OperationRegion: NameString, RegionSpace(byte), Offset(TermArg), Len(TermArg).
/// The offset/length expressions are kept as AML for lazy evaluation.
fn parseRegion(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
const space = try self.readByte();
const off_start = self.position;
try self.object(scope);
const off_end = self.position;
try self.object(scope);
const len_end = self.position;
const node = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .region);
node.region_space = space;
node.region_offset_aml = self.aml[off_start..off_end];
node.region_len_aml = self.aml[off_end..len_end];
}
fn parseDataRegion(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
try self.args(scope, 3); // signature, oem id, oem table id (TermArgs)
_ = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .region);
}
fn parseMutex(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
try self.skip(1); // sync flags
_ = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .mutex);
}
fn parseEvent(self: *Parser, scope: *Node) Error!void {
const name_path = try self.readNameString();
_ = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .event);
}
/// CreateXField: `count` TermArgs then the new field's NameString.
fn parseCreateField(self: *Parser, scope: *Node, count: usize) Error!void {
try self.args(scope, count);
const name_path = try self.readNameString();
_ = try self.namespace.place(scope, name_path.rooted, name_path.parents, name_path.slice(), .name);
}
/// Field / IndexField / BankField: a region/bank reference, flags, then a
/// FieldList whose NamedFields become nodes in the current scope. For a plain
/// Field, the first NameString is the backing region — captured so field units
/// carry a region + bit position the evaluator can read/write.
fn parseField(self: *Parser, scope: *Node, name_strings: u8, bank: bool) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
var region: ?*Node = null;
var i: u8 = 0;
while (i < name_strings) : (i += 1) {
const name_path = try self.readNameString();
// Only a plain Field's single NameString denotes an OperationRegion.
if (name_strings == 1) region = self.namespace.resolve(scope, name_path.rooted, name_path.parents, name_path.slice());
}
if (bank) try self.object(scope); // bank value TermArg
const flags = try self.readByte();
self.fieldList(end, scope, region, flags & 0x0F);
}
fn fieldList(self: *Parser, end: usize, scope: *Node, region: ?*Node, initial_access: u8) void {
var bit_offset: u32 = 0;
var access = initial_access;
while (self.position < end) {
const lead = self.peek() orelse break;
switch (lead) {
0x00 => { // ReservedField: advances the bit position
self.position += 1;
const width = self.readPackageLength() catch break;
bit_offset += @intCast(width);
},
0x01 => { // AccessField: AccessType (low nibble) + AccessAttrib
self.position += 1;
const at = self.readByte() catch break;
self.skip(1) catch break;
access = at & 0x0F;
},
0x02 => { // ConnectField: NameString | BufferData
self.position += 1;
self.object(scope) catch break;
},
0x03 => { // ExtendedAccessField: type + attrib + length
self.position += 1;
self.skip(3) catch break;
},
else => { // NamedField: NameSegment + PkgLength (bit width)
const segment = self.readNameSegment() catch break;
const width = self.readPackageLength() catch break;
const unit = self.namespace.newFieldUnit(scope, segment) catch break;
unit.region = region;
unit.bit_offset = bit_offset;
unit.bit_width = @intCast(width);
unit.access_type = access;
bit_offset += @intCast(width);
},
}
}
self.position = end;
}
// --- control flow -------------------------------------------------------
fn parseIf(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
try self.object(scope); // predicate
self.termList(end, scope);
if (self.peek() == opcode.else_opcode) {
self.position += 1;
try self.parseElse(scope);
}
}
fn parseElse(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
self.termList(end, scope);
}
fn parseWhile(self: *Parser, scope: *Node) Error!void {
const start = self.position;
const end = start + try self.readPackageLength();
try self.object(scope); // predicate
self.termList(end, scope);
}
fn parseLnot(self: *Parser, scope: *Node) Error!void {
// 0x92 followed by 0x93/94/95 is a compound comparison (two operands);
// otherwise it is a plain LNot of one operand.
const b = self.peek() orelse return error.Truncated;
switch (b) {
opcode.lnot.not_equal, opcode.lnot.less_equal, opcode.lnot.greater_equal => {
self.position += 1;
try self.args(scope, 2);
},
else => try self.object(scope),
}
}
fn parseMatch(self: *Parser, scope: *Node) Error!void {
try self.object(scope); // search package
try self.skip(1); // match opcode 1
try self.object(scope); // operand 1
try self.skip(1); // match opcode 2
try self.object(scope); // operand 2
try self.object(scope); // start index
}
// --- extended opcodes (0x5B xx) -----------------------------------------
fn parseExtended(self: *Parser, scope: *Node) Error!void {
const e = try self.readByte();
switch (e) {
opcode.extended.mutex => try self.parseMutex(scope),
opcode.extended.event => try self.parseEvent(scope),
opcode.extended.operation_region => try self.parseRegion(scope),
opcode.extended.data_region => try self.parseDataRegion(scope),
opcode.extended.field => try self.parseField(scope, 1, false),
opcode.extended.index_field => try self.parseField(scope, 2, false),
opcode.extended.bank_field => try self.parseField(scope, 2, true),
opcode.extended.device => try self.parseScopeLike(scope, .device),
opcode.extended.thermal_zone => try self.parseScopeLike(scope, .thermal_zone),
opcode.extended.processor => try self.parseProcessor(scope),
opcode.extended.power_resource => try self.parsePowerResource(scope),
opcode.extended.conditional_reference_of => try self.args(scope, 2), // SuperName, Target
opcode.extended.create_field => try self.parseCreateField(scope, 3),
opcode.extended.load_table => try self.args(scope, 6),
opcode.extended.load => try self.args(scope, 2), // NameString, Target
opcode.extended.stall, opcode.extended.sleep => try self.args(scope, 1),
opcode.extended.acquire => {
try self.object(scope); // mutex SuperName
try self.skip(2); // timeout WordData
},
opcode.extended.signal, opcode.extended.reset, opcode.extended.release, opcode.extended.unload => try self.args(scope, 1),
opcode.extended.wait => try self.args(scope, 2),
opcode.extended.from_bcd, opcode.extended.to_bcd => try self.args(scope, 2),
opcode.extended.fatal => {
try self.skip(5); // Type(byte) + Code(dword)
try self.object(scope); // Arg TermArg
},
opcode.extended.revision, opcode.extended.debug, opcode.extended.timer => {},
else => return error.Malformed,
}
}
};
fn isNameStart(b: u8) bool {
return (b >= opcode.name_char_start and b <= opcode.name_char_end) or
b == opcode.name_char_underscore or
b == opcode.root_char or
b == opcode.parent_prefix_char or
b == opcode.dual_name_prefix or
b == opcode.multi_name_prefix;
}
-137
View File
@@ -1,137 +0,0 @@
//! The **device ABI**: the flat, `extern` device types that cross the system_call
//! boundary — what `device_enumerate` hands a user-space driver, what
//! `device_register` takes back. This is the devices sub-project's *public
//! interface*, exposed as its own `device-abi` module the same way the VFS server
//! exposes `vfs-protocol` — so both the kernel and user space depend on the contract
//! by name, and neither reaches into the other's files.
//!
//! It is also the **single source of truth** for `DeviceClass` and `ResourceKind`:
//! the kernel's rich, pointer-based device tree (system/devices/device-model.zig,
//! which user space must never import) re-exports these, so the enum that a driver
//! matches on and the enum the kernel classifies with are the *same* type — no
//! hand-kept "mirror in order" to drift. The core kernel↔user ABI is [[abi]]; the
//! loader↔kernel handoff is [[boot-handoff]].
/// A coarse classification of a device, independent of the describing firmware.
/// Kept small on purpose; refine as real drivers arrive. `enum(u32)` because the
/// `@intFromEnum` value crosses the system_call boundary in `DeviceDescriptor.class`.
pub const DeviceClass = enum(u32) {
/// The synthetic root every discovered device hangs beneath.
root,
processor,
interrupt_controller,
timer,
/// A PCI(e) host bridge — the root of a PCI segment (owns an ECAM window).
pci_host_bridge,
/// A single PCI function.
pci_device,
/// A device named in the ACPI namespace (from the DSDT/SSDT), carrying a
/// hardware ID (`_HID`) and, where static, current resource settings (`_CRS`).
acpi_device,
/// The ACPI tables themselves, published as one node for the user-space acpi
/// service (docs/discovery.md): memory resources over the AML blobs,
/// a broad io_port grant for OperationRegion access, and the SCI interrupt.
/// The one node whose claimant is trusted to run firmware bytecode.
acpi_tables,
/// One interface of a USB device, registered by the xHCI bus driver. It owns
/// no MMIO — it is reached through its controller — so it carries no
/// resources; the (class, subclass, protocol) triple that says what it is
/// travels in the bus report's identity, not here.
usb_device,
/// A scanout framebuffer: a linear region of pixel memory the display service
/// claims and maps. Unlike the other classes this one is not firmware-discovered
/// — the kernel seeds it from the loader's [[boot-handoff]] framebuffer
/// (`devices_broker.seedDisplay`). Its one `memory` resource is the framebuffer,
/// flagged write-combining; the geometry to interpret it travels in
/// `DeviceDescriptor.display`.
display,
unknown,
};
/// The kind of hardware resource a device occupies. `enum(u32)` for the same
/// boundary-crossing reason as `DeviceClass` (see `ResourceDescriptor.kind`).
pub const ResourceKind = enum(u32) {
/// A memory-mapped I/O window: `start` is the physical base, `len` its size.
memory,
/// A legacy I/O-port range: `start` is the first port, `len` the count.
io_port,
/// An interrupt: `start` is the global system interrupt (GSI), `len` is 1.
irq,
/// A range of bus numbers owned by a bridge: `start`..`start+len`.
bus_range,
};
/// One device resource, as handed to a user-space driver (flat, extern).
pub const ResourceDescriptor = extern struct {
kind: u64, // a ResourceKind value
start: u64,
len: u64,
/// A bitmask of `resource_flag_*` hints. Zero for a plain register/RAM window;
/// the kernel reads it when it maps the resource. Defaulted so every existing
/// literal (which never set flags) keeps compiling and lays out identically.
flags: u64 = 0,
};
/// `ResourceDescriptor.flags`: map this `memory` resource **write-combining** rather
/// than strong-uncacheable — for a framebuffer, where batched bursts to pixel memory
/// are the whole point (an uncacheable framebuffer blit is glacial). See
/// `mmio_map` (system/kernel/process.zig) and `setupPat` (…/x86_64/paging.zig).
pub const resource_flag_write_combining: u64 = 1 << 0;
pub const maximum_device_resources = 8;
/// The byte order of a display's pixels — mirrors the loader's `PixelFormat`
/// ([[boot-handoff]]) with the same numeric values, but lives here so user space
/// (which must never import the loader↔kernel handoff) can name it. Only the two
/// linear 32-bpp layouts a console can paint into exist; see docs/gop.md.
pub const DisplayFormat = enum(u32) {
rgbx = 0, // byte 0 = Red, 1 = Green, 2 = Blue, 3 = reserved
bgrx = 1, // byte 0 = Blue, 1 = Green, 2 = Red, 3 = reserved
};
/// The geometry of a `display` device's framebuffer, carried in its descriptor so a
/// claiming driver knows how to interpret the pixel bytes its `memory` resource maps.
/// `pitch` is bytes per row (may exceed `width * 4`; see docs/framebuffer.md).
pub const DisplayInfo = extern struct {
width: u32 = 0, // visible pixels per row
height: u32 = 0, // visible rows
pitch: u32 = 0, // bytes from one row's start to the next
format: u32 = 0, // a DisplayFormat value
refresh_hz: u32 = 0, // panel refresh rate from EDID (0 = unknown); see boot-handoff
};
/// `DeviceDescriptor.parent` for a device with no parent — a root of the device tree.
pub const no_parent: u64 = ~@as(u64, 0);
/// `DeviceDescriptor.pci_class` for a device that is not a PCI function. (Zero would be
/// ambiguous: 0x000000 is a real class code, "unclassified device".)
pub const no_pci_class: u64 = ~@as(u64, 0);
/// A device, as snapshotted for user space by `device_enumerate`. A driver scans
/// these to find the hardware it owns, claims it, and maps its MMIO.
///
/// `parent` makes the table a tree rather than a list, which is what a **bus driver**
/// needs: it claims the bus, finds the devices below it, and publishes any it
/// discovers itself with `device_register`. A registered child's resources must lie
/// within its parent's (the kernel enforces this) — that containment is what makes
/// delegation safe, since a device descriptor is otherwise a licence to map physical
/// memory.
pub const DeviceDescriptor = extern struct {
id: u64,
parent: u64, // a device id, or `no_parent`
class: u64, // a DeviceClass value
// The PCI class/subclass/prog-IF triple packed as 0xCCSSPP when this device is a PCI
// function, or `no_pci_class` otherwise. This is how a manager tells *what* a
// `pci_device` is (an xHCI controller, an AHCI controller) — decode the triple into
// names with the pci-class module.
pci_class: u64,
hid_len: u64,
resource_count: u64,
hid: [8]u8,
resources: [maximum_device_resources]ResourceDescriptor,
// Framebuffer geometry, meaningful only when `class` is `DeviceClass.display`
// (zeroed otherwise). Kept here — a class-specific field on the shared descriptor —
// the same way `pci_class` is meaningful only for `pci_device` and `hid` only for
// `acpi_device`.
display: DisplayInfo = .{},
};
-568
View File
@@ -1,568 +0,0 @@
//! PCI class-code decoding: turn the (class, subclass, prog-IF) triple a PCI function
//! reports in its configuration header into human-readable names. Every PCI function
//! carries a 24-bit class code — base class (config byte 0x0B), subclass (0x0A), and
//! programming interface (0x09) — that says *what it is* far more precisely than
//! danos's coarse `DeviceClass`: an ISA bridge, a SATA/AHCI controller, and an xHCI USB
//! controller are all just `pci_device` by class, and only this triple tells them
//! apart. Pure reference data (from the PCI spec; see https://wiki.osdev.org/PCI) — no
//! hardware access — so it is shared by kernel discovery (the device-tree dump) and any
//! user-space tool (a future lspci, driver matching).
//!
//! The taxonomy is named, not numbered (docs/coding-standards.md, "Named values"): the
//! base class is a `BaseClass` enum, and each class with defined subclasses gets a
//! namespace holding its `SubClass` enum (and, where the spec defines them, per-subclass
//! `ProgIf` enums) — the same shape as `usb-ids.zig`. Code that *means* a specific class
//! names it (`BaseClass.serial_bus`, `serial_bus.usb.ProgIf.xhci`) rather than writing a
//! bare 0x0C/0x03/0x30. The `className`/`subclassName`/`progIfName` functions still take
//! the raw bytes a function reports in its header, because that is what hardware hands us.
const std = @import("std");
/// The three bytes of a PCI class code, unpacked from the `0xCCSSPP` value discovery
/// records in `Device.ids.pci_class` (CC = base class, SS = subclass, PP = prog-IF).
pub const ClassCode = struct {
base: u8, // class code (config offset 0x0B)
subclass: u8, // subclass (0x0A)
prog_if: u8, // programming interface (0x09)
pub fn unpack(packed_code: u24) ClassCode {
return .{
.base = @intCast((packed_code >> 16) & 0xFF),
.subclass = @intCast((packed_code >> 8) & 0xFF),
.prog_if = @intCast(packed_code & 0xFF),
};
}
/// Re-pack the triple into the `0xCCSSPP` form. Lets code name a whole class code
/// from its parts — `pack(.{ .base = @intFromEnum(BaseClass.serial_bus), … })` —
/// instead of writing the literal 0x0C0330.
pub fn pack(self: ClassCode) u24 {
return (@as(u24, self.base) << 16) | (@as(u24, self.subclass) << 8) | self.prog_if;
}
};
/// Base class (config byte 0x0B). Non-exhaustive: an unlisted code is a real but
/// unnamed class, decoded as "Unknown" rather than rejected.
pub const BaseClass = enum(u8) {
unclassified = 0x00,
mass_storage = 0x01,
network = 0x02,
display = 0x03,
multimedia = 0x04,
memory = 0x05,
bridge = 0x06,
simple_communication = 0x07,
base_system_peripheral = 0x08,
input_device = 0x09,
docking_station = 0x0A,
processor = 0x0B,
serial_bus = 0x0C,
wireless = 0x0D,
intelligent = 0x0E,
satellite_communication = 0x0F,
encryption = 0x10,
signal_processing = 0x11,
processing_accelerator = 0x12,
non_essential_instrumentation = 0x13,
co_processor = 0x40,
unassigned = 0xFF,
_,
pub fn name(self: BaseClass) []const u8 {
return switch (self) {
.unclassified => "Unclassified",
.mass_storage => "Mass Storage Controller",
.network => "Network Controller",
.display => "Display Controller",
.multimedia => "Multimedia Controller",
.memory => "Memory Controller",
.bridge => "Bridge",
.simple_communication => "Simple Communication Controller",
.base_system_peripheral => "Base System Peripheral",
.input_device => "Input Device Controller",
.docking_station => "Docking Station",
.processor => "Processor",
.serial_bus => "Serial Bus Controller",
.wireless => "Wireless Controller",
.intelligent => "Intelligent Controller",
.satellite_communication => "Satellite Communication Controller",
.encryption => "Encryption Controller",
.signal_processing => "Signal Processing Controller",
.processing_accelerator => "Processing Accelerator",
.non_essential_instrumentation => "Non-Essential Instrumentation",
.co_processor => "Co-Processor",
.unassigned => "Unassigned Class (Vendor specific)",
_ => "Unknown",
};
}
};
// --- Per-class subclass (and prog-IF) taxonomies --------------------------------------
// One namespace per base class that has defined subclasses, named after the class. Each
// holds an exhaustive `SubClass` enum (so an unlisted code decodes to the class default,
// not a wrong name), and, where the spec assigns them, per-subclass `ProgIf` enums.
pub const mass_storage = struct {
pub const SubClass = enum(u8) {
scsi_bus = 0x00,
ide = 0x01,
floppy = 0x02,
ipi_bus = 0x03,
raid = 0x04,
ata = 0x05,
serial_ata = 0x06,
serial_attached_scsi = 0x07,
non_volatile_memory = 0x08,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.scsi_bus => "SCSI Bus Controller",
.ide => "IDE Controller",
.floppy => "Floppy Disk Controller",
.ipi_bus => "IPI Bus Controller",
.raid => "RAID Controller",
.ata => "ATA Controller",
.serial_ata => "Serial ATA Controller",
.serial_attached_scsi => "Serial Attached SCSI Controller",
.non_volatile_memory => "Non-Volatile Memory Controller",
};
}
};
pub const serial_ata = struct {
pub const ProgIf = enum(u8) {
vendor_specific = 0x00,
ahci = 0x01,
serial_storage_bus = 0x02,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.vendor_specific => "Vendor Specific Interface",
.ahci => "AHCI 1.0",
.serial_storage_bus => "Serial Storage Bus",
};
}
};
};
pub const non_volatile_memory = struct {
pub const ProgIf = enum(u8) {
nvmhci = 0x01,
nvm_express = 0x02,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.nvmhci => "NVMHCI",
.nvm_express => "NVM Express",
};
}
};
};
};
pub const network = struct {
pub const SubClass = enum(u8) {
ethernet = 0x00,
token_ring = 0x01,
fddi = 0x02,
atm = 0x03,
isdn = 0x04,
picmg_multi_computing = 0x06,
infiniband = 0x07,
fabric = 0x08,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.ethernet => "Ethernet Controller",
.token_ring => "Token Ring Controller",
.fddi => "FDDI Controller",
.atm => "ATM Controller",
.isdn => "ISDN Controller",
.picmg_multi_computing => "PICMG 2.14 Multi Computing Controller",
.infiniband => "Infiniband Controller",
.fabric => "Fabric Controller",
};
}
};
};
pub const display = struct {
pub const SubClass = enum(u8) {
vga_compatible = 0x00,
xga = 0x01,
three_dimensional = 0x02,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.vga_compatible => "VGA Compatible Controller",
.xga => "XGA Controller",
.three_dimensional => "3D Controller (Not VGA-Compatible)",
};
}
};
pub const vga_compatible = struct {
pub const ProgIf = enum(u8) {
vga = 0x00,
compatible_8514 = 0x01,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.vga => "VGA Controller",
.compatible_8514 => "8514-Compatible Controller",
};
}
};
};
};
pub const multimedia = struct {
pub const SubClass = enum(u8) {
video = 0x00,
audio = 0x01,
telephony = 0x02,
audio_device = 0x03,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.video => "Multimedia Video Controller",
.audio => "Multimedia Audio Controller",
.telephony => "Computer Telephony Device",
.audio_device => "Audio Device",
};
}
};
};
pub const memory = struct {
pub const SubClass = enum(u8) {
ram = 0x00,
flash = 0x01,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.ram => "RAM Controller",
.flash => "Flash Controller",
};
}
};
};
pub const bridge = struct {
pub const SubClass = enum(u8) {
host = 0x00,
isa = 0x01,
eisa = 0x02,
mca = 0x03,
pci_to_pci = 0x04,
pcmcia = 0x05,
nubus = 0x06,
cardbus = 0x07,
raceway = 0x08,
pci_to_pci_semi_transparent = 0x09,
infiniband_to_pci = 0x0A,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.host => "Host Bridge",
.isa => "ISA Bridge",
.eisa => "EISA Bridge",
.mca => "MCA Bridge",
.pci_to_pci => "PCI-to-PCI Bridge",
.pcmcia => "PCMCIA Bridge",
.nubus => "NuBus Bridge",
.cardbus => "CardBus Bridge",
.raceway => "RACEway Bridge",
.pci_to_pci_semi_transparent => "PCI-to-PCI Bridge (Semi-Transparent)",
.infiniband_to_pci => "InfiniBand-to-PCI Host Bridge",
};
}
};
pub const pci_to_pci = struct {
pub const ProgIf = enum(u8) {
normal_decode = 0x00,
subtractive_decode = 0x01,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.normal_decode => "Normal Decode",
.subtractive_decode => "Subtractive Decode",
};
}
};
};
};
pub const simple_communication = struct {
pub const SubClass = enum(u8) {
serial = 0x00,
parallel = 0x01,
multiport_serial = 0x02,
modem = 0x03,
gpib = 0x04,
smart_card = 0x05,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.serial => "Serial Controller",
.parallel => "Parallel Controller",
.multiport_serial => "Multiport Serial Controller",
.modem => "Modem",
.gpib => "IEEE 488.1/2 (GPIB) Controller",
.smart_card => "Smart Card Controller",
};
}
};
pub const serial = struct {
pub const ProgIf = enum(u8) {
compatible_8250 = 0x00,
compatible_16450 = 0x01,
compatible_16550 = 0x02,
compatible_16650 = 0x03,
compatible_16750 = 0x04,
compatible_16850 = 0x05,
compatible_16950 = 0x06,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.compatible_8250 => "8250-Compatible (Generic XT)",
.compatible_16450 => "16450-Compatible",
.compatible_16550 => "16550-Compatible",
.compatible_16650 => "16650-Compatible",
.compatible_16750 => "16750-Compatible",
.compatible_16850 => "16850-Compatible",
.compatible_16950 => "16950-Compatible",
};
}
};
};
};
pub const base_system_peripheral = struct {
pub const SubClass = enum(u8) {
pic = 0x00,
dma = 0x01,
timer = 0x02,
rtc = 0x03,
pci_hot_plug = 0x04,
sd_host = 0x05,
iommu = 0x06,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.pic => "PIC",
.dma => "DMA Controller",
.timer => "Timer",
.rtc => "RTC Controller",
.pci_hot_plug => "PCI Hot-Plug Controller",
.sd_host => "SD Host Controller",
.iommu => "IOMMU",
};
}
};
};
pub const input_device = struct {
pub const SubClass = enum(u8) {
keyboard = 0x00,
digitizer_pen = 0x01,
mouse = 0x02,
scanner = 0x03,
gameport = 0x04,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.keyboard => "Keyboard Controller",
.digitizer_pen => "Digitizer Pen",
.mouse => "Mouse Controller",
.scanner => "Scanner Controller",
.gameport => "Gameport Controller",
};
}
};
};
pub const serial_bus = struct {
pub const SubClass = enum(u8) {
firewire = 0x00,
access_bus = 0x01,
ssa = 0x02,
usb = 0x03,
fibre_channel = 0x04,
smbus = 0x05,
infiniband = 0x06,
ipmi = 0x07,
sercos = 0x08,
canbus = 0x09,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.firewire => "FireWire (IEEE 1394) Controller",
.access_bus => "ACCESS Bus Controller",
.ssa => "SSA",
.usb => "USB Controller",
.fibre_channel => "Fibre Channel",
.smbus => "SMBus Controller",
.infiniband => "InfiniBand Controller",
.ipmi => "IPMI Interface",
.sercos => "SERCOS Interface (IEC 61491)",
.canbus => "CANbus Controller",
};
}
};
pub const usb = struct {
pub const ProgIf = enum(u8) {
uhci = 0x00,
ohci = 0x10,
ehci = 0x20,
xhci = 0x30,
unspecified = 0x80,
device = 0xFE,
pub fn name(self: ProgIf) []const u8 {
return switch (self) {
.uhci => "UHCI Controller",
.ohci => "OHCI Controller",
.ehci => "EHCI (USB2) Controller",
.xhci => "XHCI (USB3) Controller",
.unspecified => "Unspecified",
.device => "USB Device (not a host controller)",
};
}
};
};
};
pub const wireless = struct {
pub const SubClass = enum(u8) {
irda = 0x00,
consumer_ir = 0x01,
rf = 0x10,
bluetooth = 0x11,
broadband = 0x12,
ethernet_802_1a = 0x20,
ethernet_802_1b = 0x21,
pub fn name(self: SubClass) []const u8 {
return switch (self) {
.irda => "iRDA Compatible Controller",
.consumer_ir => "Consumer IR Controller",
.rf => "RF Controller",
.bluetooth => "Bluetooth Controller",
.broadband => "Broadband Controller",
.ethernet_802_1a => "Ethernet Controller (802.1a)",
.ethernet_802_1b => "Ethernet Controller (802.1b)",
};
}
};
};
// --- Raw-byte decoding (what a function reports in its header) -------------------------
/// The name of an exhaustive class-code enum member, or null if `value` is not one — the
/// bridge from a raw config byte to a named taxonomy above.
fn enumName(comptime Enum: type, value: u8) ?[]const u8 {
return (std.enums.fromInt(Enum, value) orelse return null).name();
}
/// Name of the base class (byte 0x0B), e.g. `0x06` -> "Bridge".
pub fn className(base: u8) []const u8 {
return @as(BaseClass, @enumFromInt(base)).name();
}
/// Name of the subclass within its base class, e.g. `(0x06, 0x01)` -> "ISA Bridge".
/// Subclass `0x80` is "Other" by PCI convention; anything unlisted is "Unknown".
pub fn subclassName(base: u8, subclass: u8) []const u8 {
const named: ?[]const u8 = switch (@as(BaseClass, @enumFromInt(base))) {
.mass_storage => enumName(mass_storage.SubClass, subclass),
.network => enumName(network.SubClass, subclass),
.display => enumName(display.SubClass, subclass),
.multimedia => enumName(multimedia.SubClass, subclass),
.memory => enumName(memory.SubClass, subclass),
.bridge => enumName(bridge.SubClass, subclass),
.simple_communication => enumName(simple_communication.SubClass, subclass),
.base_system_peripheral => enumName(base_system_peripheral.SubClass, subclass),
.input_device => enumName(input_device.SubClass, subclass),
.serial_bus => enumName(serial_bus.SubClass, subclass),
.wireless => enumName(wireless.SubClass, subclass),
else => null,
};
return named orelse defaultSubclass(subclass);
}
fn defaultSubclass(subclass: u8) []const u8 {
return if (subclass == 0x80) "Other" else "Unknown";
}
/// Name of the programming interface, for the subclasses that define standard ones
/// (IDE modes, SATA/AHCI, NVMe, PCI-bridge decode, UART generation, USB host type).
/// Returns "" when the prog-IF carries no standard meaning for this class/subclass —
/// callers just print the hex byte in that case.
pub fn progIfName(base: u8, subclass: u8, prog_if: u8) []const u8 {
const named: ?[]const u8 = switch (@as(BaseClass, @enumFromInt(base))) {
.mass_storage => switch (std.enums.fromInt(mass_storage.SubClass, subclass) orelse return "") {
.serial_ata => enumName(mass_storage.serial_ata.ProgIf, prog_if),
.non_volatile_memory => enumName(mass_storage.non_volatile_memory.ProgIf, prog_if),
else => null,
},
.display => switch (std.enums.fromInt(display.SubClass, subclass) orelse return "") {
.vga_compatible => enumName(display.vga_compatible.ProgIf, prog_if),
else => null,
},
.bridge => switch (std.enums.fromInt(bridge.SubClass, subclass) orelse return "") {
.pci_to_pci => enumName(bridge.pci_to_pci.ProgIf, prog_if),
else => null,
},
.simple_communication => switch (std.enums.fromInt(simple_communication.SubClass, subclass) orelse return "") {
.serial => enumName(simple_communication.serial.ProgIf, prog_if),
else => null,
},
.serial_bus => switch (std.enums.fromInt(serial_bus.SubClass, subclass) orelse return "") {
.usb => enumName(serial_bus.usb.ProgIf, prog_if),
else => null,
},
else => null,
};
return named orelse "";
}
test "decodes the common class codes" {
const eq = std.testing.expectEqualStrings;
const isa = ClassCode.unpack(0x06_01_00);
try std.testing.expectEqual(@as(u8, 0x06), isa.base);
try std.testing.expectEqual(@as(u8, 0x01), isa.subclass);
try eq("Bridge", className(isa.base));
try eq("ISA Bridge", subclassName(isa.base, isa.subclass));
const ahci = ClassCode.unpack(0x01_06_01);
try eq("Mass Storage Controller", className(ahci.base));
try eq("Serial ATA Controller", subclassName(ahci.base, ahci.subclass));
try eq("AHCI 1.0", progIfName(ahci.base, ahci.subclass, ahci.prog_if));
const xhci = ClassCode.unpack(0x0C_03_30);
try eq("Serial Bus Controller", className(xhci.base));
try eq("USB Controller", subclassName(xhci.base, xhci.subclass));
try eq("XHCI (USB3) Controller", progIfName(xhci.base, xhci.subclass, xhci.prog_if));
}
test "unlisted codes fall back without a wrong name" {
const eq = std.testing.expectEqualStrings;
try eq("Unknown", className(0x77)); // no such base class
try eq("Other", subclassName(0x01, 0x80)); // 0x80 is the PCI "Other" convention
try eq("Unknown", subclassName(0x01, 0x7A)); // unlisted mass-storage subclass
try eq("", progIfName(0x01, 0x06, 0x7F)); // no standard SATA prog-IF for 0x7F
try eq("", progIfName(0x02, 0x00, 0x00)); // class with no prog-IF taxonomy at all
}
test "named parts pack to the raw triple" {
const xhci = ClassCode{
.base = @intFromEnum(BaseClass.serial_bus),
.subclass = @intFromEnum(serial_bus.SubClass.usb),
.prog_if = @intFromEnum(serial_bus.usb.ProgIf.xhci),
};
try std.testing.expectEqual(@as(u24, 0x0C_03_30), xhci.pack());
}
-945
View File
@@ -1,945 +0,0 @@
//! USB device-framework wire ABI: the set-up packets, standard requests, and standard
//! descriptors every USB device speaks over its default control pipe, as defined by chapter 9
//! of the USB 2.0 specification (see https://wiki.osdev.org/Universal_Serial_Bus). Pure data
//! definitions — no hardware access — shared by the host-controller bus drivers (which build
//! the requests) and anything that parses what devices return (device naming, driver
//! matching, configuration). The structs mirror the wire byte-for-byte: multi-byte fields are
//! little-endian and align(1), so a descriptor can be bit-cast straight out of a transfer
//! buffer at any offset, and bitmap bytes are packed structs so no caller ever needs a magic
//! mask. Class, subclass, and protocol code tables live in usb-ids.zig.
pub const DeviceState = enum(u8) {
// Immediately after the USB device is attached to the USB system, it is in this state.
// The USB specifications do not define the state of a USB device that is detached from
// a USB system.
attached,
// A device is in this state after it has both been attached to the bus, and the VBUS line is
// applied to the device (the host controller drives the VBUS at +5V, however this is only
// particularly important for hardware developers). In this state, the device must not respond
// to any bus transactions. The USB specification recognizes three potential scenarios with
// respect to how a device draws power:
// - Self-Powered Devices draw power from an external power source (e.g, a USB printer plugs
// into the wall as well as a USB port). Although the device may be considered
// technically "powered" even before attachment to the USB, it is still only considered
// powered after the VBUS line is applied to the device.
// - Bus-Powered Devices draw power solely from the USB up to 100mA.
// - Self- or Bus-Powered Devices may draw power from either the bus or an external power
// source, depending on the configuration. These devices may change power source at any
// time. If a device is currently self-powered and requires more than 100mA of power, but
// switches to being bus-powered, then the device must return to the Address state.
powered,
// A device in the powered state enters the default state after receiving a bus reset. In this
// state, the device is addressable at the default, reserved address of 0. At this point, the
// device is operating at the correct speed. The host is expected to allow 10 milliseconds
// before expecting the device to respond to data transfers after reset.
default,
// A device enters this state after the host assigns it an address via the default control pipe,
// which is always accessible whether the device's address has been set or not.
address,
// A device is in this state after the host examines its possible configurations and selects
// one. All endpoint's data toggle bits are initialized to zero when a device enters this state.
configured,
// When no traffic is observed on the bus for a period of 1 millisecond, a USB device enters
// this state, characterized by its low power consumption. The device's address and
// configuration settings are maintained while suspended. A device exits the suspended state as
// soon as it begins seeing bus activity again. The host is expected to allow 10 milliseconds
// before expecting the device to respond to data transfers after resume.
suspended,
};
pub const RequestCode = enum(u8) {
get_status = 0,
clear_feature = 1,
set_feature = 3,
set_address = 5,
get_descriptor = 6,
set_descriptor = 7,
get_configuration = 8,
set_configuration = 9,
get_interface = 10,
set_interface = 11,
sync_frame = 12,
// Non-exhaustive: class-specific requests (HID, mass storage) reuse this byte
// field with codes from their own class's namespace — see the class-request
// constructors below. Some class codes numerically coincide with a standard
// one; the wire byte is what matters, and the constructors set it explicitly.
_,
};
// Direction of an endpoint, from the host's point of view
pub const EndpointDirection = enum(u1) {
out = 0,
in = 1,
};
// Identifier newtypes: distinct wire-sized types for values that identify something on the
// device rather than count something. Each is a non-exhaustive enum whose values originate
// in the descriptors below and flow, still typed, into the standard request constructors —
// so an interface number can never be passed where a configuration value is expected.
// The bus address of a device, assigned by the host with SET_ADDRESS. Addresses are 7 bits
// wide.
pub const DeviceAddress = enum(u7) {
// The default address every device answers at after a reset, until SET_ADDRESS
// completes
default = 0,
_,
};
// Identifies a configuration; from ConfigurationDescriptor.configuration_value.
pub const ConfigurationValue = enum(u8) {
// Not configured: returned by GET_CONFIGURATION while the device is in the address
// state, and passed to SET_CONFIGURATION to return a configured device to the address
// state
none = 0,
_,
};
// Identifies an interface within a configuration; from
// InterfaceDescriptor.interface_number.
pub const InterfaceNumber = enum(u8) { _ };
// Selects between the alternate settings of one interface; from
// InterfaceDescriptor.alternate_setting.
pub const AlternateSetting = enum(u8) {
// The default setting of an interface
default = 0,
_,
};
// The number of an endpoint within a device, 4 bits wide. The direction bit carried
// alongside it tells the two endpoints sharing a number apart.
pub const EndpointNumber = enum(u4) {
// Endpoint zero: the default control pipe every device provides
default_control = 0,
_,
};
// Index of a STRING descriptor, stored in descriptors that reference a string and passed to
// GET_DESCRIPTOR to read it.
pub const StringIndex = enum(u8) {
// The device has no string descriptor for this field
none = 0,
_,
};
// Characteristics of a device request (the bmRequestType field of a set-up packet). Fields are
// declared least-significant first: recipient occupies bits 4...0, kind bits 6...5, and
// direction bit 7.
pub const RequestType = packed struct(u8) {
// The recipient of the request (values 4...31 are reserved)
recipient: Recipient,
// The type of the request
kind: Kind,
// Data transfer direction. The value of this bit is ignored when length is zero.
direction: Direction,
pub const Recipient = enum(u5) {
device = 0,
interface = 1,
endpoint = 2,
other = 3,
};
pub const Kind = enum(u2) {
standard = 0,
class = 1,
vendor = 2,
reserved = 3,
};
pub const Direction = enum(u1) {
host_to_device = 0,
device_to_host = 1,
};
};
pub const Request = extern struct {
// Characteristics of the request
request_type: RequestType,
// Specific request
request_code: RequestCode,
// Word-sized field that may (or may not) serve as a parameter to the request, depending
// on the specific request. For GET_DESCRIPTOR and SET_DESCRIPTOR, bit-cast a
// DescriptorValue into this field.
value: u16 align(1),
// Word-sized field that may (or may not) serve as a parameter to the request, depending
// on the specific request. Typically this field holds an index or an offset value. When
// request_type specifies an endpoint or an interface as the recipient, bit-cast an
// EndpointIndex or an InterfaceIndex into this field.
index: u16 align(1),
// Number of bytes to transfer if there is a DATA stage.
// - If this field is non-zero, and request_type indicates a transfer from
// device-to-host, then the device must never return more than length bytes of data.
// However, a device may return less.
// - If this field is non-zero, and request_type indicates a transfer from
// host-to-device, then the host must send exactly length bytes of data. If the host
// sends more than length bytes, the behavior of the device is undefined.
length: u16 align(1),
// The format of the index field when request_type specifies an endpoint as the
// recipient. The host should always set the direction bit to zero (but the device
// should accept either value) when the endpoint is part of a control pipe.
pub const EndpointIndex = packed struct(u16) {
// Endpoint number
number: EndpointNumber,
// Reserved (reset to zero)
reserved: u3 = 0,
// Selects the OUT or the IN endpoint with the specified endpoint number
direction: EndpointDirection,
// Reserved (reset to zero)
reserved_high: u8 = 0,
};
// The format of the index field when request_type specifies an interface as the
// recipient.
pub const InterfaceIndex = packed struct(u16) {
// Interface number
number: u8,
// Reserved (reset to zero)
reserved: u8 = 0,
};
// The format of the value field of GET_DESCRIPTOR and SET_DESCRIPTOR requests: the
// descriptor type in the high byte, and the descriptor index in the low byte. The index
// is used to select a specific descriptor (only for CONFIGURATION and STRING
// descriptors) when several descriptors of that type are implemented by a device.
pub const DescriptorValue = packed struct(u16) {
// Descriptor index
index: u8 = 0,
// Descriptor type
kind: DescriptorType,
};
};
// Feature selectors, used as the value field of CLEAR_FEATURE and SET_FEATURE requests. The
// comment on each value notes the recipient the selector applies to.
pub const FeatureSelector = enum(u16) {
// Halts an endpoint (recipient: endpoint)
endpoint_halt = 0,
// Enables or disables the device's remote wakeup capability (recipient: device)
device_remote_wakeup = 1,
// Puts a hi-speed device into a test mode, selected by a TestMode value in the high
// byte of the index field (recipient: device)
test_mode = 2,
};
// Test mode selectors, passed in the high byte of the index field of a SET_FEATURE request
// with the test_mode feature selector. Values 06h...3Fh are reserved for standard test
// selectors and C0h...FFh for vendor-specific test modes; all other unlisted values are
// reserved.
pub const TestMode = enum(u8) {
test_j = 0x01,
test_k = 0x02,
test_se0_nak = 0x03,
test_packet = 0x04,
test_force_enable = 0x05,
_,
};
// The two bytes returned by a GET_STATUS request directed at a device. Fields are declared
// least-significant first.
pub const DeviceStatus = packed struct(u16) {
// Whether the device is currently self-powered (as opposed to bus-powered). This bit
// cannot be changed with the SET_FEATURE or CLEAR_FEATURE requests.
self_powered: bool,
// Whether the device is currently enabled to request remote wakeup. Changed with the
// SET_FEATURE and CLEAR_FEATURE requests using the device_remote_wakeup feature
// selector.
remote_wakeup: bool,
// Reserved (reset to zero)
reserved: u14,
};
// The two bytes returned by a GET_STATUS request directed at an endpoint. (A GET_STATUS
// request directed at an interface returns two bytes that are entirely reserved.)
pub const EndpointStatus = packed struct(u16) {
// Whether the endpoint is currently halted. Set with the SET_FEATURE request using the
// endpoint_halt feature selector, and cleared with CLEAR_FEATURE.
halted: bool,
// Reserved (reset to zero)
reserved: u15,
};
// A target for the standard requests that may be directed at the device, an interface, or
// an endpoint.
pub const Target = union(enum) {
device,
interface: InterfaceNumber,
endpoint: Request.EndpointIndex,
fn recipient(target: Target) RequestType.Recipient {
return switch (target) {
.device => .device,
.interface => .interface,
.endpoint => .endpoint,
};
}
fn index(target: Target) u16 {
return switch (target) {
.device => 0,
.interface => |number| @intFromEnum(number),
.endpoint => |endpoint| @bitCast(endpoint),
};
}
};
// Constructors for the standard device requests, one per RequestCode. Each returns a
// ready-to-send set-up packet with the request_type, value, index, and length fields the
// specification prescribes for that request.
// Reads the status of the given target: bit-cast the two bytes the device returns into a
// DeviceStatus or an EndpointStatus. (The two bytes returned for an interface are entirely
// reserved.)
pub fn getStatus(target: Target) Request {
return .{
.request_type = .{
.recipient = target.recipient(),
.kind = .standard,
.direction = .device_to_host,
},
.request_code = .get_status,
.value = 0,
.index = target.index(),
.length = 2,
};
}
// Clears or disables the given feature. A device cannot be taken out of a test mode with
// this request; test_mode is only cleared by cycling power.
pub fn clearFeature(feature: FeatureSelector, target: Target) Request {
return .{
.request_type = .{
.recipient = target.recipient(),
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .clear_feature,
.value = @intFromEnum(feature),
.index = target.index(),
.length = 0,
};
}
// Sets or enables the given feature. For the test_mode feature selector, use setTestMode
// instead: the test selector rides in the high byte of the index field.
pub fn setFeature(feature: FeatureSelector, target: Target) Request {
return .{
.request_type = .{
.recipient = target.recipient(),
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_feature,
.value = @intFromEnum(feature),
.index = target.index(),
.length = 0,
};
}
// Puts a hi-speed device into the given test mode: a SET_FEATURE request with the test_mode
// feature selector and the test selector in the high byte of the index field.
pub fn setTestMode(mode: TestMode) Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_feature,
.value = @intFromEnum(FeatureSelector.test_mode),
.index = @as(u16, @intFromEnum(mode)) << 8,
.length = 0,
};
}
// Assigns the device its bus address, moving it from the default state to the address
// state. The device does not answer at the new address until the status stage of this
// request completes.
pub fn setAddress(address: DeviceAddress) Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_address,
.value = @intFromEnum(address),
.index = 0,
.length = 0,
};
}
// Reads a descriptor from the device.
// - descriptor_index selects among descriptors of the same type, and is only used for
// configuration and string descriptors.
// - language_id selects the language of a string descriptor, and is zero otherwise.
// - length is the number of bytes to read; a device never returns more than length bytes,
// but may return less if the descriptor is shorter.
pub fn getDescriptor(kind: DescriptorType, descriptor_index: u8, language_id: u16, length: u16) Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .device_to_host,
},
.request_code = .get_descriptor,
.value = @bitCast(Request.DescriptorValue{ .index = descriptor_index, .kind = kind }),
.index = language_id,
.length = length,
};
}
// Updates an existing descriptor or adds a new one (optional; many devices do not support
// this request). The parameters mirror getDescriptor; the descriptor itself is sent in the
// DATA stage.
pub fn setDescriptor(kind: DescriptorType, descriptor_index: u8, language_id: u16, length: u16) Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_descriptor,
.value = @bitCast(Request.DescriptorValue{ .index = descriptor_index, .kind = kind }),
.index = language_id,
.length = length,
};
}
// Reads the currently active configuration: @enumFromInt the byte the device returns into a
// ConfigurationValue, which is none while the device is not configured.
pub fn getConfiguration() Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .device_to_host,
},
.request_code = .get_configuration,
.value = 0,
.index = 0,
.length = 1,
};
}
// Selects the configuration with the given configuration_value (from
// ConfigurationDescriptor.configuration_value), moving the device from the address state to
// the configured state. Selecting none returns the device to the address state.
pub fn setConfiguration(configuration_value: ConfigurationValue) Request {
return .{
.request_type = .{
.recipient = .device,
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_configuration,
.value = @intFromEnum(configuration_value),
.index = 0,
.length = 0,
};
}
// Reads the alternate setting currently selected for the given interface: @enumFromInt the
// byte the device returns into an AlternateSetting.
pub fn getInterface(interface: InterfaceNumber) Request {
return .{
.request_type = .{
.recipient = .interface,
.kind = .standard,
.direction = .device_to_host,
},
.request_code = .get_interface,
.value = 0,
.index = @intFromEnum(interface),
.length = 1,
};
}
// Selects an alternate setting (from InterfaceDescriptor.alternate_setting) for the given
// interface.
pub fn setInterface(interface: InterfaceNumber, alternate_setting: AlternateSetting) Request {
return .{
.request_type = .{
.recipient = .interface,
.kind = .standard,
.direction = .host_to_device,
},
.request_code = .set_interface,
.value = @intFromEnum(alternate_setting),
.index = @intFromEnum(interface),
.length = 0,
};
}
// Reads the two-byte number of the frame in which the given isochronous endpoint's
// repeating pattern of transfers begins.
pub fn syncFrame(endpoint: Request.EndpointIndex) Request {
return .{
.request_type = .{
.recipient = .endpoint,
.kind = .standard,
.direction = .device_to_host,
},
.request_code = .sync_frame,
.value = 0,
.index = @bitCast(endpoint),
.length = 2,
};
}
// Class-specific requests. These carry a `kind = .class` request_type and a
// request_code from the interface's class namespace (not the standard
// RequestCode set above); the code is written into the same byte field, which
// is why RequestCode is non-exhaustive. Each is directed at an interface, whose
// number rides in the index field.
// The HID class request codes (USB HID 1.11 §7.2). Only the ones danos issues
// are named; the field on the wire is the raw byte.
pub const HidRequestCode = enum(u8) {
get_report = 0x01,
get_idle = 0x02,
get_protocol = 0x03,
set_report = 0x09,
set_idle = 0x0A,
set_protocol = 0x0B,
};
// The two protocols a boot-capable HID device can run (USB HID 1.11 §7.2.5).
// A driver selects `boot` for the simplified fixed-format boot report, usable
// before a full report-descriptor parser exists.
pub const HidProtocol = enum(u8) {
boot = 0,
report = 1,
};
// SET_PROTOCOL: choose the boot or report protocol on a HID interface.
pub fn setProtocol(interface: InterfaceNumber, protocol: HidProtocol) Request {
return .{
.request_type = .{ .recipient = .interface, .kind = .class, .direction = .host_to_device },
.request_code = @enumFromInt(@intFromEnum(HidRequestCode.set_protocol)),
.value = @intFromEnum(protocol),
.index = @intFromEnum(interface),
.length = 0,
};
}
// SET_IDLE: bound a HID interface's report rate. `duration` is in 4 ms units
// (0 means report only on change); `report_id` selects a report (0 = all).
pub fn setIdle(interface: InterfaceNumber, duration: u8, report_id: u8) Request {
return .{
.request_type = .{ .recipient = .interface, .kind = .class, .direction = .host_to_device },
.request_code = @enumFromInt(@intFromEnum(HidRequestCode.set_idle)),
.value = (@as(u16, duration) << 8) | report_id,
.index = @intFromEnum(interface),
.length = 0,
};
}
// Bulk-Only Mass Storage Reset (USB MSC BOT §3.1): ready a mass-storage
// interface for the next Command Block Wrapper after a protocol error.
pub fn bulkOnlyMassStorageReset(interface: InterfaceNumber) Request {
return .{
.request_type = .{ .recipient = .interface, .kind = .class, .direction = .host_to_device },
.request_code = @enumFromInt(0xFF),
.value = 0,
.index = @intFromEnum(interface),
.length = 0,
};
}
// Get Max LUN (USB MSC BOT §3.2): read the highest logical unit number the
// device supports (0 for a single-LUN flash drive). One byte is returned.
pub fn getMaxLun(interface: InterfaceNumber) Request {
return .{
.request_type = .{ .recipient = .interface, .kind = .class, .direction = .device_to_host },
.request_code = @enumFromInt(0xFE),
.value = 0,
.index = @intFromEnum(interface),
.length = 1,
};
}
pub const DescriptorType = enum(u8) {
device = 1,
configuration = 2,
string = 3,
interface = 4,
endpoint = 5,
device_qualifier = 6,
other_speed_configuration = 7,
interface_power = 8,
_,
};
pub const DeviceDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// DEVICE Descriptor Type
descriptor_type: DescriptorType,
// USB Specification Release Number in Binary-Coded Decimal (i.e, 2.10 is expressed as 210h).
// Identifies the release of the USB Specification with with the device and its
// descriptors are compliant.
bcd_usb: u16 align(1),
// Class code (assigned by the USB-IF)
// - This field is reset to zero if each interface within a configuration specifies its own
// class information and the various interfaces operate independently.
// - A value of FFh in this field indicates the device class is vendor-specific.
device_class: u8,
// Subclass Code (assigned by the USB-IF)
// - The subclass code of a device is qualified by the class code of that device.
// - If device_class is reset to zero, then this field must also be reset to zero.
// - When device_class is not set to FFh, then all values for this field are reserved for
// assignment by the USB-IF.
device_subclass: u8,
// Protocol code (assigned by the USB-IF)
// - The protocol code of a device is qualified by both the class and subclass codes of
// that device.
// - A value of 00h in this field means that the device may specify class-specific
// protocols on an interface basis, though this is not a requirement.
// - If this field is set to FFh, then the device uses a vendor-specific protocol.
device_protocol: u8,
// Maximum packet size for endpoint zero (8, 16, 32, or 64 are the only valid options)
max_packet_size_0: u8,
// Vendor ID (assigned by the USB-IF)
vendor_id: u16 align(1),
// Product ID (assigned by the USB-IF)
product_id: u16 align(1),
// Device release number in binary-coded decimal
bcd_device: u16 align(1),
// Index of STRING descriptor describing manufacturer
manufacturer_index: StringIndex,
// Index of STRING descriptor describing product
product_index: StringIndex,
// Index of STRING descriptor describing the device's serial number
serial_number_index: StringIndex,
// Number of possible configurations
configuration_count: u8,
};
pub const DeviceQualifierDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// DEVICE_QUALIFIER Descriptor Type
descriptor_type: DescriptorType,
// USB Specification Release Number in Binary-Coded Decimal (i.e, 2.00 is expressed as 200h).
// Identifies the release of the USB Specification with with the device and its
// descriptors are compliant. This field must be at least 0200h.
bcd_usb: u16 align(1),
// Class code (assigned by the USB-IF)
device_class: u8,
// Subclass Code (assigned by the USB-IF)
device_subclass: u8,
// Protocol code (assigned by the USB-IF)
device_protocol: u8,
// Maximum packet size for endpoint zero (8, 16, 32, or 64 are the only valid options)
max_packet_size_0: u8,
// Number of possible configurations
configuration_count: u8,
// Reserved for future uses, must be zero.
reserved: u8,
};
pub const ConfigurationDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// CONFIGURATION Descriptor Type
descriptor_type: DescriptorType,
// The total combined length in bytes of all the descriptors returned with the request for
// this CONFIGURATION descriptor (including CONFIGURATION, INTERFACE, ENDPOINT, class- and
// vendor-specific descriptors).
total_length: u16 align(1),
// Number of interfaces supported by this configuration
interface_count: u8,
// Value which when used as an argument in the SET_CONFIGURATION request, causes the device
// to assume the configuration described by this descriptor.
configuration_value: ConfigurationValue,
// Index of STRING descriptor describing this configuration.
configuration_index: StringIndex,
// Configuration Characteristics
attributes: Attributes,
// Maximum power consumption of this device from the bus when fully operational and using
// this configuration. Expressed in units of 2mA (i.e., a value of 50 in this field
// indicates 100mA).
// - A device reports with the attributes field whether the configuration is bus- or
// self-powered, but the device status (retrieved with a GET_STATUS request) reports
// whether the device is currently self-powered.
// - If a device is disconnected from an external power source, it may not draw more
// power from the bus than specified in this field.
max_power: u8,
// Configuration characteristics. Fields are declared least-significant first.
pub const Attributes = packed struct(u8) {
// Reserved, reset to zero (D4...0)
reserved: u5,
// Whether Remote Wakeup is supported by this configuration (D5)
remote_wakeup: bool,
// Self-Powered (D6)
// - false: Device runs on power supplied by the bus
// - true: Device provides a local power source; if max_power is non-zero, the
// device also may use bus power.
self_powered: bool,
// Reserved, must be set to one for historical reasons (D7)
reserved_one: u1,
};
};
// This descriptor describes the configuration of a high-speed device if it were operating at
// its alternative speed. The structure of the OTHER_SPEED_CONFIGURATION is identical to that
// of the CONFIGURATION descriptor; the only difference is that the descriptor_type field
// reflects that the descriptor is an OTHER_SPEED_CONFIGURATION descriptor.
pub const OtherSpeedConfigurationDescriptor = ConfigurationDescriptor;
pub const InterfaceDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// INTERFACE Descriptor Type
descriptor_type: DescriptorType,
// Number of this interface. Zero-based value which identifies the index of this interface
// in the array of interfaces supported within a configuration.
interface_number: InterfaceNumber,
// Value used to select the alternate settings described by this INTERFACE descriptor for
// the interface with the interface_number in the previous field. This value is zero if
// this descriptor describes the default settings for a particular interface.
alternate_setting: AlternateSetting,
// Number of endpoints used by this interface, not including endpoint zero.
endpoint_count: u8,
// Class code (assigned by the USB-IF)
// - A value of zero here is reserved for future standardization.
// - If this value is FFh, the interface class is vendor-specific.
// - All other values are reserved for assignment by the USB-IF.
interface_class: u8,
// Subclass code (assigned by the USB-IF)
// - The subclass code in this field is qualified by the value of the interface_class
// field.
// - If interface_class is reset to zero, then this field must also be reset to zero.
// - If interface_class is not set to the value of FFh, then all values of this field are
// reserved for assignment by the USB-IF.
interface_subclass: u8,
// Protocol code (assigned by the USB-IF)
// - The protocol code in this field is qualified by the values of the interface_class
// and interface_subclass fields.
// - If an interface supports class-specific requests, then this field identifies the
// protocols that the device uses as defined by the specifications of the device class.
// - If this field is reset to zero, then the device does not use a class-specific
// protocol on this interface.
// - If this field is set to FFh, then the device uses a vendor-specific protocol on
// this interface.
interface_protocol: u8,
// Index of STRING descriptor describing this interface
interface_index: StringIndex,
};
pub const EndpointDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// ENDPOINT Descriptor Type
descriptor_type: DescriptorType,
// The address of the endpoint on the USB device described by this descriptor
endpoint_address: Address,
// The endpoint's attributes
attributes: Attributes,
// Maximum packet size that this endpoint is capable of sending or receiving. For
// isochronous endpoints, this value is used to reserve bus time; the pipe, however, may
// not always use all of the reserved bus time.
max_packet_size: MaxPacketSize align(1),
// Interval for polling a device during a data transfer, expressed in units of microframes
// for high-speed devices, and frames for low- and full-speed devices. The exact meaning of
// the value in this field depends on the endpoint type and the operating speed of the
// device:
// - Full- and High-speed isochronous endpoints, and high-speed interrupt endpoints:
// This field must be in the range from 1 to 16, and is used to calculate the period
// as 2^(interval - 1). That is, a value of 4 calculates to 2^(4 - 1) = 2^3 = 8.
// - Full- and Low-speed interrupt endpoints: This field must be in the range from
// 1 to 255.
// - High-speed bulk and control OUT endpoints: This field must be in the range from
// 0 to 255, and specifies the maximum NAK rate of the endpoint. A value of zero
// indicates that the endpoint never NAKs; other values indicate at most 1 NAK each
// interval number of microframes.
interval: u8,
// The address of an endpoint. Fields are declared least-significant first.
pub const Address = packed struct(u8) {
// Endpoint Number (D3...0)
number: EndpointNumber,
// Reserved, reset to zero (D6...4)
reserved: u3,
// Direction, ignored for control endpoints (D7)
direction: EndpointDirection,
};
// An endpoint's attributes. Fields are declared least-significant first.
pub const Attributes = packed struct(u8) {
// Transfer Type (D1...0)
transfer_type: TransferType,
// Synchronization Type; isochronous endpoints only, reserved and reset to zero for
// other endpoint types (D3...2)
synchronization: Synchronization,
// Usage Type; isochronous endpoints only, reserved and reset to zero for other
// endpoints (D5...4)
usage: Usage,
// Reserved, reset to zero (D7...6)
reserved: u2,
};
pub const TransferType = enum(u2) {
control = 0,
isochronous = 1,
bulk = 2,
interrupt = 3,
};
pub const Synchronization = enum(u2) {
none = 0,
asynchronous = 1,
adaptive = 2,
synchronous = 3,
};
pub const Usage = enum(u2) {
data = 0,
feedback = 1,
implicit_feedback_data = 2,
_,
};
// The maximum packet size of an endpoint. Fields are declared least-significant first.
pub const MaxPacketSize = packed struct(u16) {
// Maximum packet size in bytes (bits 10...0)
size: u11,
// Number of additional transaction opportunities per microframe, for high-speed
// isochronous and interrupt endpoints; reserved and reset to zero for other
// endpoints (bits 12...11)
additional_transactions: AdditionalTransactions,
// Reserved, must be reset to zero (bits 15...13)
reserved: u3,
};
pub const AdditionalTransactions = enum(u2) {
// None (1 transaction per microframe)
none = 0,
// 1 additional (2 transactions per microframe)
one = 1,
// 2 additional (3 transactions per microframe)
two = 2,
_,
};
};
// A STRING descriptor at index zero returns the list of LANGID codes supported by the
// device; all other indices return a Unicode string. Both forms start with this two-byte
// header, followed by the variable-length payload:
// - index 0: an array of two-byte LANGID codes (wLangID[0] through wLangID[x])
// - other indices: a Unicode string of N bytes
pub const StringDescriptor = extern struct {
// Size of this descriptor in bytes
length: u8,
// STRING Descriptor Type
descriptor_type: DescriptorType,
};
const std = @import("std");
test "wire sizes and offsets match the specification" {
const expectEqual = std.testing.expectEqual;
try expectEqual(8, @sizeOf(Request));
try expectEqual(18, @sizeOf(DeviceDescriptor));
try expectEqual(10, @sizeOf(DeviceQualifierDescriptor));
try expectEqual(9, @sizeOf(ConfigurationDescriptor));
try expectEqual(9, @sizeOf(InterfaceDescriptor));
try expectEqual(7, @sizeOf(EndpointDescriptor));
try expectEqual(2, @sizeOf(StringDescriptor));
try expectEqual(2, @offsetOf(DeviceDescriptor, "bcd_usb"));
try expectEqual(8, @offsetOf(DeviceDescriptor, "vendor_id"));
try expectEqual(17, @offsetOf(DeviceDescriptor, "configuration_count"));
try expectEqual(2, @offsetOf(ConfigurationDescriptor, "total_length"));
try expectEqual(4, @offsetOf(EndpointDescriptor, "max_packet_size"));
}
test "bitmap packings match the specification" {
const expectEqual = std.testing.expectEqual;
const expect = std.testing.expect;
// bmRequestType for GET_DESCRIPTOR: device-to-host | standard | device = 80h
const request_type = RequestType{
.recipient = .device,
.kind = .standard,
.direction = .device_to_host,
};
try expectEqual(0x80, @as(u8, @bitCast(request_type)));
// wValue for GET_DESCRIPTOR(CONFIGURATION, index 0) = 0200h
const descriptor_value = Request.DescriptorValue{ .kind = .configuration };
try expectEqual(0x0200, @as(u16, @bitCast(descriptor_value)));
// wIndex for the IN endpoint 1 = 0081h
const endpoint_index = Request.EndpointIndex{ .number = @enumFromInt(1), .direction = .in };
try expectEqual(0x0081, @as(u16, @bitCast(endpoint_index)));
// Endpoint address 81h = IN endpoint 1
const address: EndpointDescriptor.Address = @bitCast(@as(u8, 0x81));
try expectEqual(1, @intFromEnum(address.number));
try expectEqual(.in, address.direction);
// Endpoint attributes 03h = interrupt transfer
const attributes: EndpointDescriptor.Attributes = @bitCast(@as(u8, 0x03));
try expectEqual(.interrupt, attributes.transfer_type);
// wMaxPacketSize 0008h = 8 bytes, no additional transactions
const max_packet_size: EndpointDescriptor.MaxPacketSize = @bitCast(@as(u16, 0x0008));
try expectEqual(8, max_packet_size.size);
try expectEqual(.none, max_packet_size.additional_transactions);
// Configuration attributes C0h = self-powered, with the historical D7 bit set
const configuration_attributes: ConfigurationDescriptor.Attributes = @bitCast(@as(u8, 0xC0));
try expect(configuration_attributes.self_powered);
try expect(!configuration_attributes.remote_wakeup);
try expectEqual(1, configuration_attributes.reserved_one);
// GET_STATUS words: device 0001h = self-powered; endpoint 0001h = halted
const device_status: DeviceStatus = @bitCast(@as(u16, 0x0001));
try expect(device_status.self_powered and !device_status.remote_wakeup);
const endpoint_status: EndpointStatus = @bitCast(@as(u16, 0x0001));
try expect(endpoint_status.halted);
// DescriptorType is non-exhaustive: class-specific values (HID = 21h) pass through
const hid_type: DescriptorType = @enumFromInt(0x21);
try expectEqual(0x21, @intFromEnum(hid_type));
try expect(hid_type != .device);
}
pub fn expectRequestBytes(request: Request, expected: [8]u8) !void {
try std.testing.expectEqualSlices(u8, &expected, std.mem.asBytes(&request));
}
test "standard request constructors encode the specification's set-up packets" {
try expectRequestBytes(getStatus(.device), .{ 0x80, 0, 0, 0, 0, 0, 2, 0 });
try expectRequestBytes(getStatus(.{ .interface = @enumFromInt(3) }), .{ 0x81, 0, 0, 0, 3, 0, 2, 0 });
try expectRequestBytes(getStatus(.{ .endpoint = .{ .number = @enumFromInt(2), .direction = .in } }), .{ 0x82, 0, 0, 0, 0x82, 0, 2, 0 });
try expectRequestBytes(clearFeature(.endpoint_halt, .{ .endpoint = .{ .number = @enumFromInt(1), .direction = .out } }), .{ 0x02, 1, 0, 0, 0x01, 0, 0, 0 });
try expectRequestBytes(setFeature(.device_remote_wakeup, .device), .{ 0x00, 3, 1, 0, 0, 0, 0, 0 });
try expectRequestBytes(setTestMode(.test_packet), .{ 0x00, 3, 2, 0, 0, 0x04, 0, 0 });
try expectRequestBytes(setAddress(@enumFromInt(5)), .{ 0x00, 5, 5, 0, 0, 0, 0, 0 });
try expectRequestBytes(getDescriptor(.device, 0, 0, 18), .{ 0x80, 6, 0, 1, 0, 0, 18, 0 });
try expectRequestBytes(getDescriptor(.string, 2, 0x0409, 255), .{ 0x80, 6, 2, 3, 0x09, 0x04, 255, 0 });
try expectRequestBytes(setDescriptor(.string, 2, 0x0409, 16), .{ 0x00, 7, 2, 3, 0x09, 0x04, 16, 0 });
try expectRequestBytes(getConfiguration(), .{ 0x80, 8, 0, 0, 0, 0, 1, 0 });
try expectRequestBytes(setConfiguration(@enumFromInt(1)), .{ 0x00, 9, 1, 0, 0, 0, 0, 0 });
try expectRequestBytes(getInterface(@enumFromInt(2)), .{ 0x81, 10, 0, 0, 2, 0, 1, 0 });
try expectRequestBytes(setInterface(@enumFromInt(2), @enumFromInt(1)), .{ 0x01, 11, 1, 0, 2, 0, 0, 0 });
try expectRequestBytes(syncFrame(.{ .number = @enumFromInt(3), .direction = .in }), .{ 0x82, 12, 0, 0, 0x83, 0, 2, 0 });
}
test "class request constructors encode the specification's set-up packets" {
// bmRequestType for a host-to-device class request to an interface = 0x21;
// device-to-host = 0xA1. The request_code byte is the class code, not a
// standard one — SET_PROTOCOL 0x0B, SET_IDLE 0x0A, BOT reset 0xFF, Max LUN 0xFE.
try expectRequestBytes(setProtocol(@enumFromInt(0), .boot), .{ 0x21, 0x0B, 0, 0, 0, 0, 0, 0 });
try expectRequestBytes(setProtocol(@enumFromInt(1), .report), .{ 0x21, 0x0B, 1, 0, 1, 0, 0, 0 });
try expectRequestBytes(setIdle(@enumFromInt(1), 0, 0), .{ 0x21, 0x0A, 0, 0, 1, 0, 0, 0 });
try expectRequestBytes(bulkOnlyMassStorageReset(@enumFromInt(0)), .{ 0x21, 0xFF, 0, 0, 0, 0, 0, 0 });
try expectRequestBytes(getMaxLun(@enumFromInt(0)), .{ 0xA1, 0xFE, 0, 0, 0, 0, 1, 0 });
}
-542
View File
@@ -1,542 +0,0 @@
//! USB class-code decoding: turn the (class, subclass, protocol) triple a USB device or
//! interface reports in its descriptors into typed values. The device descriptor carries one
//! triple for the whole device, and each interface descriptor carries its own; a class code
//! of zero at the device level defers entirely to the interfaces. Subclass and protocol
//! codes are qualified by the class code — the same value means different things under
//! different classes — so there is no single SubClass or Protocol enum: each class with
//! spec-defined codes gets its own namespace below. Pure reference data (from the USB-IF
//! defined class codes; see https://www.usb.org/defined-class-codes) — no hardware access —
//! so it is shared by kernel discovery and any user-space tool (device naming, driver
//! matching).
// Base class codes (assigned by the USB-IF). The comment on each value notes where the code
// may legally appear: in the device descriptor, in interface descriptors, or both.
pub const Class = enum(u8) {
// Use class information in the interface descriptors (device descriptor only). Each
// interface within a configuration specifies its own class information and the various
// interfaces operate independently.
per_interface = 0x00,
// Audio: speakers, microphones, sound cards (interface)
audio = 0x01,
// Communications and CDC control: modems, network adapters (both)
communications = 0x02,
// Human Interface Device: keyboards, mice, game controllers (interface)
hid = 0x03,
// Physical: force-feedback devices (interface)
physical = 0x05,
// Image: still-imaging cameras, scanners (interface)
image = 0x06,
// Printer (interface)
printer = 0x07,
// Mass storage: flash drives, external disks, card readers (interface)
mass_storage = 0x08,
// Hub (device descriptor only)
hub = 0x09,
// CDC-Data: the data interfaces paired with a communications control interface
// (interface)
cdc_data = 0x0A,
// Smart card readers (interface)
smart_card = 0x0B,
// Content security (interface)
content_security = 0x0D,
// Video: webcams (interface)
video = 0x0E,
// Personal healthcare devices (interface)
personal_healthcare = 0x0F,
// Audio/Video devices (interface)
audio_video = 0x10,
// Billboard: describes alternate modes a USB Type-C device supports (device descriptor
// only)
billboard = 0x11,
// USB Type-C bridge (interface)
type_c_bridge = 0x12,
// USB Bulk Display Protocol devices (interface)
bulk_display = 0x13,
// MCTP over USB protocol endpoint devices (interface)
mctp = 0x14,
// I3C devices (interface)
i3c = 0x3C,
// Diagnostic devices (both)
diagnostic = 0xDC,
// Wireless controllers: Bluetooth adapters (interface)
wireless_controller = 0xE0,
// Miscellaneous (both)
miscellaneous = 0xEF,
// Application-specific: firmware upgrade, IrDA bridges, test and measurement
// (interface)
application_specific = 0xFE,
// Vendor-specific (both)
vendor_specific = 0xFF,
_,
};
/// A human-readable name for a device/interface class code, for logs. Unknown
/// codes fall through to "class 0xNN".
pub fn className(class: u8) []const u8 {
return switch (@as(Class, @enumFromInt(class))) {
.per_interface => "per-interface",
.audio => "Audio",
.communications => "Communications",
.hid => "HID",
.physical => "Physical",
.image => "Image",
.printer => "Printer",
.mass_storage => "Mass Storage",
.hub => "Hub",
.cdc_data => "CDC Data",
.smart_card => "Smart Card",
.content_security => "Content Security",
.video => "Video",
.personal_healthcare => "Personal Healthcare",
.audio_video => "Audio/Video",
.billboard => "Billboard",
.type_c_bridge => "Type-C Bridge",
.bulk_display => "Bulk Display",
.mctp => "MCTP",
.i3c => "I3C",
.diagnostic => "Diagnostic",
.wireless_controller => "Wireless Controller",
.miscellaneous => "Miscellaneous",
.application_specific => "Application-specific",
.vendor_specific => "Vendor-specific",
_ => "Unknown",
};
}
/// The USB speed class (as xHCI reports it in PORTSC/slot contexts) named.
pub fn speedName(speed: u32) []const u8 {
return switch (speed) {
1 => "Full-speed",
2 => "Low-speed",
3 => "High-speed",
4 => "SuperSpeed",
5 => "SuperSpeedPlus",
else => "unknown-speed",
};
}
/// A USB3 Port Link State (xHCI PORTSC PLS field) named.
pub fn linkStateName(pls: u32) []const u8 {
return switch (pls) {
0 => "U0",
1 => "U1",
2 => "U2",
3 => "U3-suspended",
4 => "Disabled",
5 => "RxDetect",
6 => "Inactive",
7 => "Polling",
8 => "Recovery",
9 => "HotReset",
10 => "Compliance",
11 => "Test",
15 => "Resume",
else => "reserved",
};
}
/// The most useful readable name for an interface's (class, subclass, protocol)
/// triple, decoding the well-known combinations recognizable in a log — e.g.
/// "HID boot keyboard", "Mass Storage SCSI Bulk-Only", "Bluetooth". Falls back
/// to the class name (and then "Unknown") for codes without a spelled-out combo.
pub fn interfaceName(class: u8, subclass: u8, protocol: u8) []const u8 {
return switch (@as(Class, @enumFromInt(class))) {
.hid => if (subclass == @intFromEnum(hid.SubClass.boot)) switch (@as(hid.Protocol, @enumFromInt(protocol))) {
.keyboard => "HID boot keyboard",
.mouse => "HID boot mouse",
else => "HID boot device",
} else "HID",
.mass_storage => switch (@as(mass_storage.Protocol, @enumFromInt(protocol))) {
.bulk_only => "Mass Storage (Bulk-Only)",
.uas => "Mass Storage (UAS)",
else => "Mass Storage",
},
.hub => switch (@as(hub.Protocol, @enumFromInt(protocol))) {
.super_speed => "Hub (SuperSpeed)",
.hi_speed_multi_tt => "Hub (Hi-Speed multi-TT)",
.hi_speed_single_tt => "Hub (Hi-Speed single-TT)",
else => "Hub",
},
.wireless_controller => if (subclass == @intFromEnum(wireless_controller.SubClass.radio_frequency))
wireless_controller.protocolName(protocol)
else
"Wireless Controller",
.communications => communications.subclassName(subclass),
.application_specific => application_specific.subclassName(subclass),
.miscellaneous => "Miscellaneous",
else => className(class),
};
}
// Subclass and protocol codes qualified by Class.hub. Hubs have no subclass codes; the
// protocol distinguishes the hub's transaction-translator arrangement.
pub const hub = struct {
pub const Protocol = enum(u8) {
// Full-speed hub
full_speed = 0x00,
// Hi-speed hub with a single transaction translator
hi_speed_single_tt = 0x01,
// Hi-speed hub with multiple transaction translators
hi_speed_multi_tt = 0x02,
// SuperSpeed hub (USB 3)
super_speed = 0x03,
_,
};
pub fn protocolName(protocol: u8) []const u8 {
return switch (@as(Protocol, @enumFromInt(protocol))) {
.full_speed => "full-speed",
.hi_speed_single_tt => "Hi-Speed single-TT",
.hi_speed_multi_tt => "Hi-Speed multi-TT",
.super_speed => "SuperSpeed",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.hid.
pub const hid = struct {
pub const SubClass = enum(u8) {
// No subclass
none = 0x00,
// Boot interface: the device also supports the simplified boot protocol, usable by
// firmware before a full HID report-descriptor parser is available
boot = 0x01,
_,
};
// Only meaningful when the subclass is boot
pub const Protocol = enum(u8) {
none = 0x00,
keyboard = 0x01,
mouse = 0x02,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.none => "none",
.boot => "boot",
_ => "unknown",
};
}
pub fn protocolName(protocol: u8) []const u8 {
return switch (@as(Protocol, @enumFromInt(protocol))) {
.none => "none",
.keyboard => "keyboard",
.mouse => "mouse",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.mass_storage. The subclass identifies the
// command set the device understands; the protocol identifies the transport used to carry
// commands, data, and status over the bus.
pub const mass_storage = struct {
pub const SubClass = enum(u8) {
// SCSI command set not reported; de facto, treat as scsi
not_reported = 0x00,
// Reduced Block Commands: typically flash devices
rbc = 0x01,
// MMC-5 (ATAPI): CD and DVD drives
atapi = 0x02,
// QIC-157 tape drives (obsolete)
qic_157 = 0x03,
// UFI: floppy disk drives
ufi = 0x04,
// SFF-8070i (obsolete)
sff_8070i = 0x05,
// Transparent SCSI command set: the common case for flash drives and disks
scsi = 0x06,
// LSD FS: negotiated access to large storage devices
lsd_fs = 0x07,
// IEEE 1667
ieee_1667 = 0x08,
// Vendor-specific
vendor_specific = 0xFF,
_,
};
pub const Protocol = enum(u8) {
// Control/Bulk/Interrupt with command completion interrupt
cbi_completion_interrupt = 0x00,
// Control/Bulk/Interrupt without command completion interrupt
cbi = 0x01,
// Bulk-only transport: the common case for flash drives and disks
bulk_only = 0x50,
// USB attached SCSI
uas = 0x62,
// Vendor-specific
vendor_specific = 0xFF,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.not_reported => "SCSI (not reported)",
.rbc => "RBC",
.atapi => "ATAPI",
.qic_157 => "QIC-157",
.ufi => "UFI",
.sff_8070i => "SFF-8070i",
.scsi => "SCSI",
.lsd_fs => "LSD FS",
.ieee_1667 => "IEEE 1667",
.vendor_specific => "vendor-specific",
_ => "unknown",
};
}
pub fn protocolName(protocol: u8) []const u8 {
return switch (@as(Protocol, @enumFromInt(protocol))) {
.cbi_completion_interrupt => "CBI",
.cbi => "CBI (no completion IRQ)",
.bulk_only => "Bulk-Only",
.uas => "UAS",
.vendor_specific => "vendor-specific",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.communications (CDC). The protocol codes
// are model-specific; the useful invariant is the subclass, which selects the control model
// the interface implements.
pub const communications = struct {
pub const SubClass = enum(u8) {
// Direct line control model
direct_line = 0x01,
// Abstract control model: USB modems and serial adapters
abstract_control = 0x02,
// Telephone control model
telephone = 0x03,
// Multi-channel control model
multi_channel = 0x04,
// CAPI control model
capi = 0x05,
// Ethernet networking control model
ethernet = 0x06,
// ATM networking control model
atm = 0x07,
// Wireless handset control model
wireless_handset = 0x08,
// Device management
device_management = 0x09,
// Mobile direct line model
mobile_direct_line = 0x0A,
// OBEX
obex = 0x0B,
// Ethernet emulation model
ethernet_emulation = 0x0C,
// Network control model
network_control = 0x0D,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.direct_line => "Direct Line",
.abstract_control => "Abstract Control (modem/serial)",
.telephone => "Telephone",
.multi_channel => "Multi-Channel",
.capi => "CAPI",
.ethernet => "Ethernet",
.atm => "ATM",
.wireless_handset => "Wireless Handset",
.device_management => "Device Management",
.mobile_direct_line => "Mobile Direct Line",
.obex => "OBEX",
.ethernet_emulation => "Ethernet Emulation",
.network_control => "Network Control",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.wireless_controller.
pub const wireless_controller = struct {
pub const SubClass = enum(u8) {
// Radio frequency controllers
radio_frequency = 0x01,
_,
};
// Only meaningful when the subclass is radio_frequency
pub const Protocol = enum(u8) {
// Bluetooth programming interface
bluetooth = 0x01,
// Ultra-wideband radio control
ultra_wideband = 0x02,
// Remote NDIS
remote_ndis = 0x03,
// Bluetooth AMP controller
bluetooth_amp = 0x04,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.radio_frequency => "RF",
_ => "unknown",
};
}
pub fn protocolName(protocol: u8) []const u8 {
return switch (@as(Protocol, @enumFromInt(protocol))) {
.bluetooth => "Bluetooth",
.ultra_wideband => "Ultra-Wideband",
.remote_ndis => "Remote NDIS",
.bluetooth_amp => "Bluetooth AMP",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.miscellaneous.
pub const miscellaneous = struct {
pub const SubClass = enum(u8) {
// Common class
common = 0x02,
_,
};
// Only meaningful when the subclass is common
pub const Protocol = enum(u8) {
// Interface association descriptor: at the device level, announces that the
// configuration groups interfaces into functions with IADs
interface_association = 0x01,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.common => "common",
_ => "unknown",
};
}
pub fn protocolName(protocol: u8) []const u8 {
return switch (@as(Protocol, @enumFromInt(protocol))) {
.interface_association => "Interface Association",
_ => "unknown",
};
}
};
// Subclass and protocol codes qualified by Class.application_specific.
pub const application_specific = struct {
pub const SubClass = enum(u8) {
// Device firmware upgrade
firmware_upgrade = 0x01,
// IrDA bridge
irda_bridge = 0x02,
// Test and measurement
test_and_measurement = 0x03,
_,
};
pub fn subclassName(subclass: u8) []const u8 {
return switch (@as(SubClass, @enumFromInt(subclass))) {
.firmware_upgrade => "Device Firmware Upgrade",
.irda_bridge => "IrDA Bridge",
.test_and_measurement => "Test & Measurement",
_ => "unknown",
};
}
};
/// Pack a (class, subclass, protocol) triple into one 0xCCSSPP value — the
/// bus-native identity a USB bus driver reports in `ChildAdded.identity` and the
/// device manager matches on (the USB analog of a packed PCI class code). Mirrors
/// `pci_class.ClassCode.pack`, so both sides build/decode the identical u64.
pub fn packTriple(class: u8, subclass: u8, protocol: u8) u64 {
return (@as(u64, class) << 16) | (@as(u64, subclass) << 8) | protocol;
}
/// The inverse of `packTriple`.
pub fn unpackTriple(triple: u64) struct { class: u8, subclass: u8, protocol: u8 } {
return .{
.class = @truncate(triple >> 16),
.subclass = @truncate(triple >> 8),
.protocol = @truncate(triple),
};
}
test "class codes match the USB-IF assignments" {
const std = @import("std");
const expectEqual = std.testing.expectEqual;
try expectEqual(0x03, @intFromEnum(Class.hid));
try expectEqual(0x09, @intFromEnum(Class.hub));
try expectEqual(0xFF, @intFromEnum(Class.vendor_specific));
// A typical flash drive: mass storage, transparent SCSI, bulk-only transport.
try expectEqual(0x06, @intFromEnum(mass_storage.SubClass.scsi));
try expectEqual(0x50, @intFromEnum(mass_storage.Protocol.bulk_only));
// A boot keyboard: HID, boot subclass, keyboard protocol.
try expectEqual(0x01, @intFromEnum(hid.SubClass.boot));
try expectEqual(0x01, @intFromEnum(hid.Protocol.keyboard));
// Class codes are non-exhaustive: unlisted values pass through undamaged.
const unknown: Class = @enumFromInt(0x42);
try expectEqual(0x42, @intFromEnum(unknown));
_ = hub.Protocol.hi_speed_multi_tt;
_ = communications.SubClass.abstract_control;
_ = wireless_controller.Protocol.bluetooth;
_ = miscellaneous.Protocol.interface_association;
_ = application_specific.SubClass.firmware_upgrade;
}
test "readable names decode the well-known triples" {
const std = @import("std");
const eql = std.testing.expectEqualStrings;
try eql("Hub", className(0x09));
try eql("Unknown", className(0x42));
// interfaceName decodes the combos we log.
try eql("HID boot keyboard", interfaceName(0x03, 0x01, 0x01));
try eql("HID boot mouse", interfaceName(0x03, 0x01, 0x02));
try eql("Mass Storage (Bulk-Only)", interfaceName(0x08, 0x06, 0x50));
try eql("Hub (SuperSpeed)", interfaceName(0x09, 0x00, 0x03));
try eql("Bluetooth", interfaceName(0xE0, 0x01, 0x01));
// The per-enum name functions.
try eql("Bulk-Only", mass_storage.protocolName(0x50));
try eql("SCSI", mass_storage.subclassName(0x06));
try eql("Bluetooth", wireless_controller.protocolName(0x01));
try eql("SuperSpeed", hub.protocolName(0x03));
try eql("keyboard", hid.protocolName(0x01));
try eql("SuperSpeed", speedName(4));
try eql("Polling", linkStateName(7));
}
test "packTriple / unpackTriple round-trip the identity a bus driver reports" {
const std = @import("std");
const expectEqual = std.testing.expectEqual;
// A boot keyboard interface: HID / boot / keyboard.
const keyboard = packTriple(
@intFromEnum(Class.hid),
@intFromEnum(hid.SubClass.boot),
@intFromEnum(hid.Protocol.keyboard),
);
try expectEqual(@as(u64, 0x03_01_01), keyboard);
// A flash drive interface: mass storage / SCSI / bulk-only.
const storage = packTriple(
@intFromEnum(Class.mass_storage),
@intFromEnum(mass_storage.SubClass.scsi),
@intFromEnum(mass_storage.Protocol.bulk_only),
);
try expectEqual(@as(u64, 0x08_06_50), storage);
const parts = unpackTriple(storage);
try expectEqual(@as(u8, 0x08), parts.class);
try expectEqual(@as(u8, 0x06), parts.subclass);
try expectEqual(@as(u8, 0x50), parts.protocol);
}