From 4bc05353dfb9b5681a499ccbe93292de3422a567 Mon Sep 17 00:00:00 2001 From: Vesim Date: Wed, 11 Nov 2026 01:46:09 +0100 Subject: [PATCH] feat(usb): better DeviceController configuration --- core/src/core/usb.zig | 6 +- core/src/core/usb/drivers/CDC.zig | 435 ++++++++++---------- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 38 +- 3 files changed, 242 insertions(+), 237 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index a21e9e554..62c668539 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -4,7 +4,7 @@ const log = std.log.scoped(.usb_ctrl); pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { - pub const CDC = @import("usb/drivers/CDC.zig"); + pub const CDC = @import("usb/drivers/CDC.zig").CDC; pub const EchoExample = @import("usb/drivers/EchoExample.zig"); pub const hid = @import("usb/drivers/hid.zig"); }; @@ -230,7 +230,7 @@ pub fn validate_controller(T: type) void { /// Responds to host requests and dispatches to the appropriate drivers. /// When this type is build (at comptime), it builds descriptor and handler tables based on the /// provided config. -pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { +pub fn DeviceController(config: Config) type { std.debug.assert(config.configurations.len == 1); return struct { @@ -283,7 +283,7 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { // Get descriptor type for the current driver const Descriptors = driver_field_type.Descriptor; // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = Descriptors.create(&alloc, max_psize, @field(driver_args[0], driver_field_name)); + const result = Descriptors.create(&alloc, max_psize); // Get the descriptor instance from the result. const descriptors = result.descriptor; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index f6ab55abb..007e032e7 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -58,226 +58,229 @@ pub const LineCoding = extern struct { }; }; -// This struct bundles all the descriptors CDC needs into one Configuration. -pub const Descriptor = extern struct { - const desc = usb.descriptor; - - itf_assoc: desc.InterfaceAssociation, - itf_notifi: desc.Interface, - cdc_header: desc.cdc.Header, - cdc_call_mgmt: desc.cdc.CallManagement, - cdc_acm: desc.cdc.AbstractControlModel, - cdc_union: desc.cdc.Union, - ep_notifi: desc.Endpoint, - itf_data: desc.Interface, - ep_out: desc.Endpoint, - ep_in: desc.Endpoint, - - const Strings = struct { - itf_notifi: []const u8 = "", - itf_data: []const u8 = "", - }; +const Strings = struct { + itf_notifi: []const u8 = "", + itf_data: []const u8 = "", +}; - /// This function is used during descriptor creation. Endpoint and interface numbers are - /// allocated through the `alloc` parameter. Third argument can be of any type, it's passed - /// by the user when creating the device controller type. If multiple instances of a driver - /// are used, this function is called for each, with different arguments. Passing arguments - /// through this function is preferred to making the whole driver generic. - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, - strings: Strings, - ) usb.DescriptorCreateResult(@This()) { - // Endpoint and interface numbers are allocated through the `alloc` parameter, - // so that multiple instances of this driver can coexist. - const itf_notifi = alloc.next_itf(); - const itf_data = alloc.next_itf(); - return .{ - .descriptor = .{ - .itf_assoc = .{ - .first_interface = itf_notifi, - .interface_count = 2, - .function_class = 2, - .function_subclass = 2, - .function_protocol = 0, - .function = 0, - }, - .itf_notifi = .{ - .interface_number = itf_notifi, - .alternate_setting = 0, - .num_endpoints = 1, - .interface_triple = .from(.CDC, .Abstract, .NoneRequired), - .interface_s = alloc.string(strings.itf_notifi), - }, - .cdc_header = .{ .bcd_cdc = .from(1, 20) }, - .cdc_call_mgmt = .{ - .capabilities = .none, - .data_interface = itf_data, - }, - .cdc_acm = .{ - .capabilities = .{ - .comm_feature = false, - .send_break = false, - // Line coding requests get sent regardless of this bit - .line_coding = true, - .network_connection = false, +// This struct bundles all the descriptors CDC needs into one Configuration. +pub fn CDC(strings: Strings) type { + return struct { + pub const Descriptor = extern struct { + const desc = usb.descriptor; + + itf_assoc: desc.InterfaceAssociation, + itf_notifi: desc.Interface, + cdc_header: desc.cdc.Header, + cdc_call_mgmt: desc.cdc.CallManagement, + cdc_acm: desc.cdc.AbstractControlModel, + cdc_union: desc.cdc.Union, + ep_notifi: desc.Endpoint, + itf_data: desc.Interface, + ep_out: desc.Endpoint, + ep_in: desc.Endpoint, + + /// This function is used during descriptor creation. Endpoint and interface numbers are + /// allocated through the `alloc` parameter. Third argument can be of any type, it's passed + /// by the user when creating the device controller type. If multiple instances of a driver + /// are used, this function is called for each, with different arguments. Passing arguments + /// through this function is preferred to making the whole driver generic. + pub fn create( + alloc: *usb.DescriptorAllocator, + max_supported_packet_size: usb.types.Len, + ) usb.DescriptorCreateResult(@This()) { + // Endpoint and interface numbers are allocated through the `alloc` parameter, + // so that multiple instances of this driver can coexist. + const itf_notifi = alloc.next_itf(); + const itf_data = alloc.next_itf(); + return .{ + .descriptor = .{ + .itf_assoc = .{ + .first_interface = itf_notifi, + .interface_count = 2, + .function_class = 2, + .function_subclass = 2, + .function_protocol = 0, + .function = 0, + }, + .itf_notifi = .{ + .interface_number = itf_notifi, + .alternate_setting = 0, + .num_endpoints = 1, + .interface_triple = .from(.CDC, .Abstract, .NoneRequired), + .interface_s = alloc.string(strings.itf_notifi), + }, + .cdc_header = .{ .bcd_cdc = .from(1, 20) }, + .cdc_call_mgmt = .{ + .capabilities = .none, + .data_interface = itf_data, + }, + .cdc_acm = .{ + .capabilities = .{ + .comm_feature = false, + .send_break = false, + // Line coding requests get sent regardless of this bit + .line_coding = true, + .network_connection = false, + }, + }, + .cdc_union = .{ + .master_interface = itf_notifi, + .slave_interface_0 = itf_data, + }, + // High-speed interrupt intervals are encoded as + // 2^(bInterval - 1) microframes, while full-speed intervals + // are expressed directly in milliseconds. Keep the intended + // polling period at 16 ms for both speeds. + .ep_notifi = .interrupt( + alloc.next_ep(.in), + 8, + if (max_supported_packet_size > 64) 8 else 16, + ), + .itf_data = .{ + .interface_number = itf_data, + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), + .interface_s = alloc.string(strings.itf_data), + }, + .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), }, - }, - .cdc_union = .{ - .master_interface = itf_notifi, - .slave_interface_0 = itf_data, - }, - // High-speed interrupt intervals are encoded as - // 2^(bInterval - 1) microframes, while full-speed intervals - // are expressed directly in milliseconds. Keep the intended - // polling period at 16 ms for both speeds. - .ep_notifi = .interrupt( - alloc.next_ep(.in), - 8, - if (max_supported_packet_size > 64) 8 else 16, - ), - .itf_data = .{ - .interface_number = itf_data, - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), - .interface_s = alloc.string(strings.itf_data), - }, - .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), - }, - .alloc_bytes = 2 * max_supported_packet_size, + .alloc_bytes = 2 * max_supported_packet_size, + }; + } }; - } -}; - -// These field names are matched (at comptime) to the field names in the descriptor returned from -// `create` when binding the endpoints. -pub const handlers: usb.DriverHandlers(@This()) = .{ - .ep_notifi = on_notifi_ready, - .ep_out = on_rx, - .ep_in = on_tx_ready, -}; - -device: *usb.DeviceInterface, -descriptor: *const Descriptor, -line_coding: LineCoding align(4), -notifi_ready: std.atomic.Value(bool), - -rx_data: []u8, -rx_seek: usb.types.Len, -rx_end: usb.types.Len, -rx_ready: std.atomic.Value(bool), - -tx_data: []u8, -tx_end: usb.types.Len, -tx_ready: std.atomic.Value(bool), - -pub fn available(self: *@This()) usb.types.Len { - return self.rx_end - self.rx_seek; -} - -pub fn read(self: *@This(), dst: []u8) usize { - const len = @min(dst.len, self.rx_end - self.rx_seek); - @memcpy(dst[0..len], self.rx_data[self.rx_seek..][0..len]); - self.rx_seek += len; - - if (self.available() > 0) return len; - - // request more data - if (self.rx_ready.load(.seq_cst)) { - const ep_out = self.descriptor.ep_out.endpoint.num; - self.rx_ready.store(false, .seq_cst); - self.rx_end = self.device.ep_readv(ep_out, &.{self.rx_data}); - self.rx_seek = 0; - self.device.ep_listen(ep_out, @intCast(self.rx_data.len)); - } - - return len; -} -pub fn write(self: *@This(), data: []const u8) usize { - const len = @min(self.tx_data.len - self.tx_end, data.len); - - @memcpy(self.tx_data[self.tx_end..][0..len], data[0..len]); - self.tx_end += @intCast(len); - - if (self.tx_end == self.tx_data.len) - _ = self.flush(); - - return len; -} - -/// Flushes tx buffer. Returns true if there is no more buffered data. -pub fn flush(self: *@This()) bool { - if (self.tx_end == 0) - return true; - - if (!self.tx_ready.load(.seq_cst)) - return false; - self.tx_ready.store(false, .seq_cst); - - assert(self.tx_end == self.device.ep_writev( - self.descriptor.ep_in.endpoint.num, - &.{self.tx_data[0..self.tx_end]}, - ), .{}); - self.tx_end = 0; - return true; -} - -// Called when the host selects a configuration. -pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - const len_half = @divExact(data.len, 2); - assert(len_half == desc.ep_in.max_packet_size.native(), .{}); - assert(len_half == desc.ep_out.max_packet_size.native(), .{}); - self.* = .{ - .device = device, - .descriptor = desc, - .line_coding = .init, - .notifi_ready = .init(true), - - // `init` provides a data buffer, which we split in half for rx and tx data. - .rx_data = data[0..len_half], - .rx_seek = 0, - .rx_end = 0, - .rx_ready = .init(false), - - .tx_data = data[len_half..], - .tx_end = 0, - .tx_ready = .init(true), - }; - device.ep_listen(desc.ep_out.endpoint.num, @intCast(self.rx_data.len)); -} + // These field names are matched (at comptime) to the field names in the descriptor returned from + // `create` when binding the endpoints. + pub const handlers: usb.DriverHandlers(@This()) = .{ + .ep_notifi = on_notifi_ready, + .ep_out = on_rx, + .ep_in = on_tx_ready, + }; -/// Handle class-specific SETUP requests where recipient=Interface -/// Called by DeviceController when the interface number matches this driver. -pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - const mgmt_request: ManagementRequestType = @fromBackingInt(setup.request); - log.debug("cdc setup: {any} {} {}", .{ mgmt_request, setup.length.native(), setup.value.native() }); - - return switch (mgmt_request) { - .SetLineCoding => usb.ack, // we should handle data phase somehow to read sent line_coding - .GetLineCoding => std.mem.asBytes(&self.line_coding), - .SetControlLineState => usb.ack, - .SendBreak => usb.ack, - else => usb.nak, + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + line_coding: LineCoding align(4), + notifi_ready: std.atomic.Value(bool), + + rx_data: []u8, + rx_seek: usb.types.Len, + rx_end: usb.types.Len, + rx_ready: std.atomic.Value(bool), + + tx_data: []u8, + tx_end: usb.types.Len, + tx_ready: std.atomic.Value(bool), + + pub fn available(self: *@This()) usb.types.Len { + return self.rx_end - self.rx_seek; + } + + pub fn read(self: *@This(), dst: []u8) usize { + const len = @min(dst.len, self.rx_end - self.rx_seek); + @memcpy(dst[0..len], self.rx_data[self.rx_seek..][0..len]); + self.rx_seek += len; + + if (self.available() > 0) return len; + + // request more data + if (self.rx_ready.load(.seq_cst)) { + const ep_out = self.descriptor.ep_out.endpoint.num; + self.rx_ready.store(false, .seq_cst); + self.rx_end = self.device.ep_readv(ep_out, &.{self.rx_data}); + self.rx_seek = 0; + self.device.ep_listen(ep_out, @intCast(self.rx_data.len)); + } + + return len; + } + + pub fn write(self: *@This(), data: []const u8) usize { + const len = @min(self.tx_data.len - self.tx_end, data.len); + + @memcpy(self.tx_data[self.tx_end..][0..len], data[0..len]); + self.tx_end += @intCast(len); + + if (self.tx_end == self.tx_data.len) + _ = self.flush(); + + return len; + } + + /// Flushes tx buffer. Returns true if there is no more buffered data. + pub fn flush(self: *@This()) bool { + if (self.tx_end == 0) + return true; + + if (!self.tx_ready.load(.seq_cst)) + return false; + self.tx_ready.store(false, .seq_cst); + + assert(self.tx_end == self.device.ep_writev( + self.descriptor.ep_in.endpoint.num, + &.{self.tx_data[0..self.tx_end]}, + ), .{}); + self.tx_end = 0; + return true; + } + + // Called when the host selects a configuration. + pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { + const len_half = @divExact(data.len, 2); + assert(len_half == desc.ep_in.max_packet_size.native(), .{}); + assert(len_half == desc.ep_out.max_packet_size.native(), .{}); + self.* = .{ + .device = device, + .descriptor = desc, + .line_coding = .init, + .notifi_ready = .init(true), + + // `init` provides a data buffer, which we split in half for rx and tx data. + .rx_data = data[0..len_half], + .rx_seek = 0, + .rx_end = 0, + .rx_ready = .init(false), + + .tx_data = data[len_half..], + .tx_end = 0, + .tx_ready = .init(true), + }; + device.ep_listen(desc.ep_out.endpoint.num, @intCast(self.rx_data.len)); + } + + /// Handle class-specific SETUP requests where recipient=Interface + /// Called by DeviceController when the interface number matches this driver. + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + const mgmt_request: ManagementRequestType = @fromBackingInt(setup.request); + log.debug("cdc setup: {any} {} {}", .{ mgmt_request, setup.length.native(), setup.value.native() }); + + return switch (mgmt_request) { + .SetLineCoding => usb.ack, // we should handle data phase somehow to read sent line_coding + .GetLineCoding => std.mem.asBytes(&self.line_coding), + .SetControlLineState => usb.ack, + .SendBreak => usb.ack, + else => usb.nak, + }; + } + + pub fn on_rx(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.rx_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_rx", ep_num }); + self.rx_ready.store(true, .seq_cst); + } + + pub fn on_tx_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.tx_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_tx_ready", ep_num }); + self.tx_ready.store(true, .seq_cst); + } + + pub fn on_notifi_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.notifi_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_notifi_ready", ep_num }); + self.notifi_ready.store(true, .seq_cst); + } }; } - -pub fn on_rx(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.rx_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_rx", ep_num }); - self.rx_ready.store(true, .seq_cst); -} - -pub fn on_tx_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.tx_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_tx_ready", ep_num }); - self.tx_ready.store(true, .seq_cst); -} - -pub fn on_notifi_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.notifi_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_notifi_ready", ep_num }); - self.notifi_ready.store(true, .seq_cst); -} diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index edb307f0b..4ff06ffeb 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -8,29 +8,31 @@ const usb = microzig.core.usb; // read from/write to the peripheral. const USB_Device = rp2xxx.usb.Polled(.{}); // USB class driver -const USB_Serial = usb.drivers.CDC; +const USB_Serial = usb.drivers.CDC(.{.itf_notifi = "Board CDC", .itf_data = "Board CDC Data"}); var usb_device: USB_Device = undefined; // Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) and // picotool-controlled reset (ResetDriver). -var usb_controller: usb.DeviceController(.{ - .bcd_usb = USB_Device.max_supported_bcd_usb, - .device_triple = .unspecified, - .vendor = USB_Device.default_vendor_id, - .product = USB_Device.default_product_id, - .bcd_device = .v1_00, - .serial = "someserial", - .max_supported_packet_size = USB_Device.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, - }}, -}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, - .reset = "", -}}) = .init; +var usb_controller: usb.DeviceController( + .{ + .bcd_usb = USB_Device.max_supported_bcd_usb, + .device_triple = .unspecified, + .vendor = USB_Device.default_vendor_id, + .product = USB_Device.default_product_id, + .bcd_device = .v1_00, + .serial = "someserial", + .max_supported_packet_size = USB_Device.max_supported_packet_size, + .configurations = &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { + serial: USB_Serial, + // reset: rp2xxx.usb.ResetDriver(null, 0), + }, + }}, + }, +) = .init; pub const std_options = microzig.std_options(.{ .log_level = .debug,