diff --git a/core/src/allocator.zig b/core/src/allocator.zig index a9a915a9a..33d4522e1 100644 --- a/core/src/allocator.zig +++ b/core/src/allocator.zig @@ -418,7 +418,7 @@ pub const Chunk = extern struct { }); // Otherwise, just go for it. - return @as(*Chunk, @ptrCast(@alignCast(data_slice.ptr - header_size))); + return @ptrCast(@alignCast(data_slice.ptr - header_size)); } /// Return a data slice that maps the chunk's memory the user can use. diff --git a/core/src/core/arm_semihosting.zig b/core/src/core/arm_semihosting.zig index 73e121e65..52a840757 100644 --- a/core/src/core/arm_semihosting.zig +++ b/core/src/core/arm_semihosting.zig @@ -216,7 +216,7 @@ pub const Time = struct { ///return the host time in epoch pub fn system_time() usize { - return @as(usize, @bitCast(sys_time())); + return @bitCast(sys_time()); } ///return the corrent tick counter value in centiseconds pub fn absolute() TimeError!usize { diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index a21e9e554..9adbe5178 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -1,31 +1,36 @@ const std = @import("std"); +const configuration = @import("usb/configuration.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_ctrl); +pub const Configuration = configuration.Configuration; +pub const ConfigurationOptions = configuration.Options; pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { pub const CDC = @import("usb/drivers/CDC.zig"); pub const EchoExample = @import("usb/drivers/EchoExample.zig"); - pub const hid = @import("usb/drivers/hid.zig"); + pub const HID_Interrupt = @import("usb/drivers/HID.zig"); }; +pub const HID_report = @import("usb/HID_report.zig"); pub const types = @import("usb/types.zig"); pub const ack: []const u8 = ""; pub const nak: ?[]const u8 = null; -// What does this do? It lets you iterate through interfaces and endpoints? +/// Helper struct for endpoint allocation for drivers. +/// Also deduplicates static strings. pub const DescriptorAllocator = struct { next_ep_num: [2]u8, next_itf_num: u8, unique_endpoints: bool, strings: []const []const u8, - pub fn init(unique_endpoints: bool) @This() { + pub fn init(unique_endpoints: bool, strings: []const []const u8) @This() { return .{ .next_ep_num = @splat(1), .next_itf_num = 0, .unique_endpoints = unique_endpoints, - .strings = &.{}, + .strings = strings, }; } @@ -44,21 +49,7 @@ pub const DescriptorAllocator = struct { } pub fn string(self: *@This(), str: []const u8) u8 { - if (str.len == 0) return 0; - // deduplicate - for (self.strings, 1..) |s, i| { - if (std.mem.eql(u8, s, str)) - return i; - } - - self.strings = self.strings ++ .{str}; - return @intCast(self.strings.len); - } - - pub fn string_descriptors(self: @This(), lang: descriptor.String.Language) []const descriptor.String { - var ret: []const descriptor.String = &.{.from_lang(lang)}; - for (self.strings) |s| - ret = ret ++ [1]descriptor.String{.from_str(s)}; + self.strings, const ret = dedup_string(self.strings, str); return ret; } @@ -68,33 +59,55 @@ pub const DescriptorAllocator = struct { } }; +/// Device-specific information +pub const DeviceCapabilities = struct { + max_supported_bcd_usb: types.Version = .v1_00, + /// Maximum packet size on ep0 + max_packet_size0: types.PacketLength, + /// Maximum packet size on other endpoints + max_packet_size: types.PacketLength, + default_vendor: ?Options.IdStringPair = null, + default_product: ?Options.IdStringPair = null, + /// Ports that enable this must also provide the `signal_resume` vtable function. + supports_remote_wakeup: bool = false, +}; + /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. -pub fn DescriptorCreateResult(Descriptor: type) type { +pub fn DriverInfo(Descriptor: type) type { return struct { + /// If not void, a pointer to a value of this type + /// will be passed to driver's init function. + Alloc: type = void, + /// Field attributes of `Alloc` + alloc_attrs: std.builtin.Type.Struct.FieldAttributes = .{}, + Runtime: type, descriptor: Descriptor, - /// If not null, a slice of this length will be passed - /// to driver's init function. - alloc_bytes: ?usize = null, - /// Null means natural alignment - alloc_align: ?usize = null, }; } +pub const RemoteWakeupError = error{ + NotSupported, + NotEnabledByHost, + NotConfigured, + NotSuspended, +}; + /// USB Device interface /// Any device implementation used with DeviceController must implement these functions pub const DeviceInterface = struct { pub const VTable = struct { - ep_writev: *const fn (*DeviceInterface, types.Endpoint.Num, []const []const u8) types.Len, - ep_readv: *const fn (*DeviceInterface, types.Endpoint.Num, []const []u8) types.Len, - ep_listen: *const fn (*DeviceInterface, types.Endpoint.Num, types.Len) void, + ep_writev: *const fn (*DeviceInterface, types.Endpoint.Num, []const []const u8) types.PacketLength, + ep_readv: *const fn (*DeviceInterface, types.Endpoint.Num, []const []u8) types.PacketLength, + ep_listen: *const fn (*DeviceInterface, types.Endpoint.Num, types.PacketLength) void, ep_open: *const fn (*DeviceInterface, *const descriptor.Endpoint) void, set_address: *const fn (*DeviceInterface, u7) void, + signal_resume: ?*const fn (*DeviceInterface) RemoteWakeupError!void = null, }; vtable: *const VTable, /// Called by drivers to send a packet. - pub fn ep_writev(self: *@This(), ep_num: types.Endpoint.Num, data: []const []const u8) types.Len { + pub fn ep_writev(self: *@This(), ep_num: types.Endpoint.Num, data: []const []const u8) types.PacketLength { return self.vtable.ep_writev(self, ep_num, data); } @@ -106,13 +119,13 @@ pub const DeviceInterface = struct { /// Called by drivers to retrieve a received packet. /// Must be called exactly once for each packet. /// Buffers in `data` must collectively be long enough to fit the whole packet. - pub fn ep_readv(self: *@This(), ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + pub fn ep_readv(self: *@This(), ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { return self.vtable.ep_readv(self, ep_num, data); } /// Called by drivers to report readiness to receive up to `len` bytes. /// After being called it may not be called again until a packet is received. - pub fn ep_listen(self: *@This(), ep_num: types.Endpoint.Num, len: types.Len) void { + pub fn ep_listen(self: *@This(), ep_num: types.Endpoint.Num, len: types.PacketLength) void { return self.vtable.ep_listen(self, ep_num, len); } @@ -128,69 +141,44 @@ pub const DeviceInterface = struct { pub fn set_address(self: *@This(), addr: u7) void { return self.vtable.set_address(self, addr); } + + /// Drive resume signaling on the bus to wake the host + pub fn signal_resume(self: *@This()) RemoteWakeupError!void { + const f = self.vtable.signal_resume orelse return error.NotSupported; + return f(self); + } }; pub fn EndpointHandler(Driver: type) type { return fn (*Driver, types.Endpoint.Num) void; } -pub fn DriverHandlers(Driver: type) type { +pub fn DriverHandlers(Descriptor: type, Runtime: type) type { var field_names: []const [:0]const u8 = &.{}; - const info = @typeInfo(Driver.Descriptor).@"struct"; + const info = @typeInfo(Descriptor).@"struct"; for (info.field_names, info.field_types) |field_name, field_type| switch (field_type) { descriptor.Endpoint => field_names = field_names ++ .{field_name}, else => {}, }; - return @Struct(.auto, null, field_names, &@splat(EndpointHandler(Driver)), &@splat(.{})); + return @Struct(.auto, null, field_names, &@splat(EndpointHandler(Runtime)), &@splat(.{})); } -pub const Config = struct { +pub const Options = struct { pub const IdStringPair = struct { id: u16, str: []const u8, }; - pub const Configuration = struct { - name: []const u8 = "", - attributes: descriptor.Configuration.Attributes, - max_current_ma: u9, - Drivers: type, - - /// Generate A struct with a field for each field in Drivers, where the type is the third - /// arg of the Drivers' Descriptor's 'create' method. - pub fn Args(self: @This()) type { - const info = @typeInfo(self.Drivers).@"struct"; - const count = info.field_names.len; - var field_names: [count][:0]const u8 = undefined; - var field_types: [count]type = undefined; - for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // Collect field names - field_names[i] = field_name; - // Collect the type info for the Descriptor.create function parameter - const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // Ensure it takes 3 parameters - assert(param_types.len == 3); - // The first must be a DescriptorAllocator - assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.Len - assert(param_types[1] == types.Len); - // And save the type of the third - field_types[i] = param_types[2].?; - } - return @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); - } - }; - - /// Usb specification version. - bcd_usb: types.Version, + /// Usb specification version. `null` means highest supported by device. + bcd_usb: ?types.Version = null, /// Class, subclass and protocol of this device. device_triple: types.ClassSubclassProtocol, - /// Vendor id and string - vendor: IdStringPair, - /// Product id and string. - product: IdStringPair, + /// Vendor id and string. `null` means default provided by device + vendor: ?IdStringPair = null, + /// Product id and string. `null` means default provided by device + product: ?IdStringPair = null, /// Device version. bcd_device: types.Version, /// String descriptor 0. @@ -198,20 +186,11 @@ pub const Config = struct { /// Serial number string. serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. - max_supported_packet_size: types.Len, - /// Currently only a single configuration is supported. - configurations: []const Configuration, - /// Only use either IN or OUT on each endpoint. Useful for debugging. - /// Realistically, it should only be turned off if you are exhausting - /// the 15 endpoint limit. - unique_endpoints: bool = true, - - pub fn DriverArgs(self: @This()) type { - var field_types: [self.configurations.len]type = undefined; - for (self.configurations, &field_types) |cfg, *dst| - dst.* = cfg.Args(); - return @Tuple(&field_types); - } + device_capabilities: DeviceCapabilities, + /// Only called when the bus actually enters suspend. + on_suspend: ?*const fn () void = null, + /// Only called when the bus actually leaves suspend. + on_resume: ?*const fn () void = null, }; pub fn validate_controller(T: type) void { @@ -225,191 +204,81 @@ pub fn validate_controller(T: type) void { } } +pub fn validate_device(Device: type) void { + if (!@hasDecl(Device, "device_capabilities")) + @compileError("USB device " ++ @typeName(Device) ++ " is missing a device_capabilities declaration."); + if (@TypeOf(Device.device_capabilities) != DeviceCapabilities) + @compileError("USB device " ++ @typeName(Device) ++ ".device_capabilities has incorrect type.\n" ++ + "Got: " ++ @typeName(@TypeOf(DeviceCapabilities)) ++ ", expected usb.DeviceCapabilities"); +} + /// USB device controller /// /// 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 { - std.debug.assert(config.configurations.len == 1); +/// provided options. +pub fn DeviceController(options: Options, Configurations: []const type) type { + // Currently only a single configuration is supported. + std.debug.assert(Configurations.len == 1); return struct { - // We only support one configuration - const config0 = config.configurations[0]; - const driver_info = @typeInfo(config0.Drivers).@"struct"; - const DriverEnum = std.meta.FieldEnum(config0.Drivers); - /// This parses the drivers' descriptors and creates: - /// * the configuration descriptor (currently only one configuration is supported) + /// * the configuration descriptor /// * table of handlers for endpoints /// * table of handlers for interfaces const descriptor_parse_result = blk: { - const max_psize = config.max_supported_packet_size; - assert(max_psize >= 8); - assert(std.math.isPowerOfTwo(max_psize)); + const max_psize0 = options.device_capabilities.max_packet_size0; + const max_psize = options.device_capabilities.max_packet_size; + if (max_psize0 < 8 or !std.math.isPowerOfTwo(max_psize0) or max_psize < 8 or !std.math.isPowerOfTwo(max_psize)) + @compileError("Maximum packet size must be a power of two and at least 8"); + + const vendor = options.vendor orelse + (options.device_capabilities.default_vendor orelse + @compileError("Vendor ID not provided and device does not specify a default.")); + + const product = options.product orelse + (options.device_capabilities.default_product orelse + @compileError("Product ID not provided and device does not specify a default.")); - var alloc: DescriptorAllocator = .init(config.unique_endpoints); - const manufacturer_s = alloc.string(config.vendor.str); - const product_s = alloc.string(config.product.str); - const serial_s = alloc.string(config.serial); + var strings: []const []const u8 = &.{}; + strings, const manufacturer_s = dedup_string(strings, vendor.str); + strings, const product_s = dedup_string(strings, product.str); + strings, const serial_s = dedup_string(strings, options.serial); const desc_device: descriptor.Device = .{ - .bcd_usb = config.bcd_usb, - .device_triple = config.device_triple, - .max_packet_size0 = @min(config.max_supported_packet_size, 64), - .vendor = .from(config.vendor.id), - .product = .from(config.product.id), - .bcd_device = config.bcd_device, + .bcd_usb = options.bcd_usb orelse options.device_capabilities.max_supported_bcd_usb, + .device_triple = options.device_triple, + .max_packet_size0 = max_psize0, + .vendor = .from(vendor.id), + .product = .from(product.id), + .bcd_device = options.bcd_device, .manufacturer_s = manufacturer_s, .product_s = product_s, .serial_s = serial_s, - .num_configurations = config.configurations.len, + .num_configurations = Configurations.len, }; - const configuration_s = alloc.string(config0.name); - - var size = @sizeOf(descriptor.Configuration); - var field_names: [driver_info.field_names.len][:0]const u8 = undefined; - var field_types: [driver_info.field_names.len]type = undefined; - var field_attrs: [driver_info.field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; - var ep_handler_types: [2][16]type = @splat(@splat(void)); - var ep_handler_names: [2][16][:0]const u8 = undefined; - var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); - var itf_handlers: []const DriverEnum = &.{}; - var driver_alloc_names: []const [:0]const u8 = &.{}; - var driver_alloc_types: []const type = &.{}; - var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; - - for (driver_info.field_names, driver_info.field_types, 0..) |driver_field_name, driver_field_type, drv_id| { - // 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)); - // Get the descriptor instance from the result. - const descriptors = result.descriptor; - - // If the driver requests memory, then collect the names, types, and attrs - if (result.alloc_bytes) |len| { - driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; - driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; - driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = result.alloc_align }}; - } else { - assert(result.alloc_align == null); - } - - assert(@alignOf(Descriptors) == 1); - size += @sizeOf(Descriptors); - - // Collect handler types, names, and drivers, to later be bound to the appropriate - // endpoints - const info = @typeInfo(Descriptors).@"struct"; - for (info.field_names, info.field_types, 0..) |field_name, field_type, desc_num| { - const desc = @field(descriptors, field_name); - - // Determine which interface numbers this driver owns. If it is an - // InterfaceAssociation, then use the interface count. If it is an Interface, - // then the driver owns just that one interface. - if (desc_num == 0) { - const itf_start, const itf_count = switch (field_type) { - descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, - descriptor.Interface => .{ desc.interface_number, 1 }, - else => |T| @compileError( - "Expected first descriptor of driver " ++ - @typeName(driver_field_type) ++ - " to be of type Interface or InterfaceAssociation descriptor, got: " ++ - @typeName(T), - ), - }; - if (itf_start != itf_handlers.len) - @compileError("interface numbering mismatch"); - - itf_handlers = itf_handlers ++ @as([itf_count]DriverEnum, @splat(@field(DriverEnum, driver_field_name))); - } - switch (field_type) { - // Register handler for endpoints - descriptor.Endpoint => { - const ep_dir = @backingInt(desc.endpoint.dir); - const ep_num = @backingInt(desc.endpoint.num); - - if (ep_handler_types[ep_dir][ep_num] != void) - @compileError(std.fmt.comptimePrint( - "ep{} {t}: multiple handlers: {s} and {s}", - .{ ep_num, desc.endpoint.dir, ep_handler_drivers[ep_dir][ep_num], driver_field_name }, - )); - - ep_handler_types[ep_dir][ep_num] = EndpointHandler(driver_field_type); - ep_handler_drivers[ep_dir][ep_num] = drv_id; - ep_handler_names[ep_dir][ep_num] = field_name; - }, - // Interface association must be first - descriptor.InterfaceAssociation => assert(desc_num == 0), - else => {}, - } - } - field_names[drv_id] = driver_field_name; - field_types[drv_id] = Descriptors; - field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; - } + var configs: @Tuple(Configurations) = undefined; + for (0..Configurations.len) |i| + configs[i], strings = Configurations[i].create(options.device_capabilities, strings); - // Finally, bind the handler functions based on the data collected above. - // Create a tuple with the appropriate types - const ep_handlers_types: [2]type = .{ @Tuple(&ep_handler_types[0]), @Tuple(&ep_handler_types[1]) }; - var ep_handlers: @Tuple(&ep_handlers_types) = undefined; - // Iterate over all IN and OUT endpoints and bind the handler for any that are set. - for (&ep_handler_types, &ep_handler_names, &ep_handler_drivers, 0..) |htypes, hnames, hdrivers, dir| { - for (&htypes, &hnames, &hdrivers, 0..) |T, name, drv_id, ep| { - if (T != void) - ep_handlers[dir][ep] = @field(driver_info.field_types[drv_id.?].handlers, name); - } - } + var desc_string: []const descriptor.String = &.{.from_lang(options.language)}; + for (strings) |s| + desc_string = desc_string ++ [1]descriptor.String{.from_str(s)}; - // alloc is invalidated after this point. It will cause a compile - // error if mutated. - const const_alloc = alloc.to_const(); - const const_ep_handlers = ep_handlers; - - const DriverConfig = @Struct(.@"extern", null, &field_names, &field_types, &field_attrs); - const idx_in = @backingInt(types.Dir.in); - const idx_out = @backingInt(types.Dir.out); break :blk .{ .device_descriptor = desc_device, - .config_descriptor = extern struct { - first: descriptor.Configuration = .{ - .total_length = .from(size), - .num_interfaces = const_alloc.next_itf_num, - .configuration_value = 1, - .configuration_s = configuration_s, - .attributes = config0.attributes, - .max_current = .from_ma(config0.max_current_ma), - }, - drv: DriverConfig = .{}, - }{}, - .string_descriptors = const_alloc.string_descriptors(config.language), - .handlers_itf = itf_handlers, - .handlers_ep = struct { - in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], - out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], - }{}, - .drivers_ep = ep_handler_drivers, - .DriverAlloc = @Struct( - .auto, - null, - driver_alloc_names, - driver_alloc_types[0..driver_alloc_attrs.len], - driver_alloc_attrs[0..driver_alloc_attrs.len], - ), + .string_descriptors = desc_string, + .configurations = configs, }; }; - const config_descriptor = descriptor_parse_result.config_descriptor; const device_descriptor = descriptor_parse_result.device_descriptor; const string_descriptors = descriptor_parse_result.string_descriptors; - const handlers_itf = descriptor_parse_result.handlers_itf; - const handlers_ep = .{ - .han = descriptor_parse_result.handlers_ep, - .drv = descriptor_parse_result.drivers_ep, - }; - const DriverAlloc = descriptor_parse_result.DriverAlloc; + const configurations = descriptor_parse_result.configurations; + + const config_descriptor = configurations[0].Descriptor{}; + const endpoint2handler = configurations[0].EndpointHandlers{}; /// If not zero, change the device address at the next opportunity. /// Necessary because when the host sets the device address, @@ -420,9 +289,13 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { /// Ep0 data waiting to be sent tx_slice: ?[]const u8, /// Driver state - driver_data: ?config0.Drivers, - /// - driver_alloc: DriverAlloc, + driver_data: ?configurations[0].RuntimeData, + /// Additional driver allocations (size is comptime-known) + driver_alloc: configurations[0].DriverAlloc, + /// Whether the host has enabled the remote wakeup feature + remote_wakeup_enabled: bool, + /// Whether the bus is currently suspended. + is_suspended: bool, /// Initial values pub const init: @This() = .{ @@ -431,11 +304,13 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { .tx_slice = null, .driver_data = null, .driver_alloc = undefined, + .remote_wakeup_enabled = false, + .is_suspended = false, }; /// Returns a pointer to the drivers /// or null in case host has not yet configured the device. - pub fn drivers(self: *@This()) ?*config0.Drivers { + pub fn drivers(self: *@This()) ?*configurations[0].RuntimeData { return if (self.driver_data) |*ret| ret else null; } @@ -464,8 +339,8 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { pub fn on_buffer(self: *@This(), device_itf: *DeviceInterface, comptime ep: types.Endpoint) void { log.debug("on_buffer {t} {t}", .{ ep.num, ep.dir }); - const driver_opt = comptime handlers_ep.drv[@backingInt(ep.dir)][@backingInt(ep.num)]; - const handler = comptime @field(handlers_ep.han, @tagName(ep.dir))[@backingInt(ep.num)]; + const driver = comptime configurations[0].endpoint2driver[@backingInt(ep.dir)][@backingInt(ep.num)]; + const handler = comptime @field(endpoint2handler, @tagName(ep.dir))[@backingInt(ep.num)]; if (comptime ep == types.Endpoint.in(.ep0)) { // We use this opportunity to finish the delayed @@ -493,9 +368,8 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { } else if (comptime ep == types.Endpoint.out(.ep0)) log.warn("Unhandled packet on ep0 Out", .{}); - if (comptime driver_opt) |driver| { - handler(&@field(self.driver_data.?, driver_info.field_names[driver]), ep.num); - } + if (comptime driver.len != 0) + handler(&@field(self.driver_data.?, driver), ep.num); } /// Called by the device implementation on bus reset. @@ -508,6 +382,56 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { self.* = .init; } + /// Called by the device implementation when the bus has been suspended. + pub fn on_suspend(self: *@This(), device_itf: *DeviceInterface) void { + _ = device_itf; + log.debug("on_suspend", .{}); + + if (!self.is_suspended) { + self.is_suspended = true; + if (options.on_suspend) |cb| cb(); + } + } + + /// Called by the device implementation when the bus has resumed, + /// either by the host or by the device itself via remote wakeupe. + pub fn on_resume(self: *@This(), device_itf: *DeviceInterface) void { + _ = device_itf; + log.debug("on_resume", .{}); + + if (self.is_suspended) { + self.is_suspended = false; + if (options.on_resume) |cb| cb(); + } + } + + /// Returns whether the bus is currently suspended. + pub fn suspended(self: *@This()) bool { + return self.is_suspended; + } + + /// Attempt to wake up the host with a device-initiated remote wakeup. + pub fn remote_wakeup(self: *@This(), device_itf: *DeviceInterface) RemoteWakeupError!void { + if (!self.remote_wakeup_enabled) { + log.debug("remote wakeup requested, but not enabled by host", .{}); + return error.NotEnabledByHost; + } + if (self.cfg_num == 0) { + log.debug("remote wakeup requested, but device is not configured", .{}); + return error.NotConfigured; + } + if (!self.is_suspended) { + log.debug("remote wakeup requested, but bus is not suspended", .{}); + return error.NotSuspended; + } + device_itf.signal_resume() catch |err| { + log.debug("remote wakeup requested, but device implementation refused: {s}", .{@errorName(err)}); + return err; + }; + // In the case of self-initiated resume we call the callback directly + self.on_resume(device_itf); + } + // Utility functions fn process_device_setup(self: *@This(), device_itf: *DeviceInterface, setup: *const types.SetupPacket) ?[]const u8 { @@ -518,21 +442,53 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { switch (request) { .get_status => { const attr = config_descriptor.first.attributes; - const status: types.DeviceStatus = comptime .create(attr.self_powered, false); - return std.mem.asBytes(&status); + const S = struct { + const responses = [2]types.DeviceStatus{ + .create(attr.self_powered, false), + .create(attr.self_powered, true), + }; + }; + return std.mem.asBytes(&S.responses[@intFromBool(self.remote_wakeup_enabled)]); }, .set_address => self.new_address = @truncate(setup.value.native()), .set_configuration => self.process_set_config(device_itf, setup.value.native()), .get_descriptor => return get_descriptor(setup.value.native()), .set_feature => { - const feature: types.FeatureSelector = @fromBackingInt(@intCast(setup.value.native() >> 8)); + const feature: types.FeatureSelector = @fromBackingInt(@truncate(setup.value.native())); switch (feature) { - .DeviceRemoteWakeup, .EndpointHalt => {}, + .DeviceRemoteWakeup => { + if (comptime !config_descriptor.first.attributes.can_remote_wakeup) { + log.warn("Host set DEVICE_REMOTE_WAKEUP, but we do not advertise it", .{}); + return nak; + } + log.debug("Host enabled remote wakeup", .{}); + self.remote_wakeup_enabled = true; + }, + .EndpointHalt => { + // TODO: Implement endpoint halting. + }, // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/453 .TestMode => return nak, else => return nak, } }, + .clear_feature => { + const feature: types.FeatureSelector = @fromBackingInt(@truncate(setup.value.native())); + switch (feature) { + .DeviceRemoteWakeup => { + if (comptime !config_descriptor.first.attributes.can_remote_wakeup) { + log.warn("Host cleared DEVICE_REMOTE_WAKEUP, but we do not advertise it", .{}); + return nak; + } + log.debug("Host disabled remote wakeup", .{}); + self.remote_wakeup_enabled = false; + }, + .EndpointHalt => { + // TODO: Implement endpoint halting. + }, + else => return nak, + } + }, else => { log.warn("Unsupported standard request: {}", .{setup.request}); return nak; @@ -549,12 +505,15 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { fn process_interface_setup(self: *@This(), setup: *const types.SetupPacket) ?[]const u8 { const itf_num: u8 = @truncate(setup.index.native()); + const num_interfaces = configurations[0].interface2driver.len; switch (itf_num) { - inline else => |itf| if (comptime itf < handlers_itf.len) { - const drv = handlers_itf[itf]; - return @field(self.driver_data.?, @tagName(drv)).class_request(setup); + inline else => |itf| if (comptime itf < num_interfaces) { + const driver = &@field(self.driver_data.?, configurations[0].interface2driver[itf]); + if (!@hasDecl(@TypeOf(driver.*), "class_request")) + @compileError(@typeName(@TypeOf(driver.*)) ++ ".class_request() missing"); + return driver.class_request(setup); } else { - log.warn("Interface index ({}) out of range ({})", .{ itf_num, handlers_itf.len }); + log.warn("Interface index ({}) out of range ({})", .{ itf_num, num_interfaces }); return nak; }, } @@ -586,44 +545,35 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { fn process_set_config(self: *@This(), device_itf: *DeviceInterface, cfg_num: u16) void { if (cfg_num == self.cfg_num) return; - if (self.driver_data) |data_old| { - _ = data_old; - // deinitialize drivers - } - - self.cfg_num = cfg_num; - if (cfg_num == 0) { - self.driver_data = null; - return; - } + if (self.driver_data) |*data_old| + configurations[0].deinit(device_itf, data_old); - // We support just one config for now so ignore config index - self.driver_data = @as(config0.Drivers, undefined); - inline for (driver_info.field_names) |driver_field_name| { - const cfg = @field(config_descriptor.drv, driver_field_name); - const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; - - // Open OUT endpoint first so that the driver can call ep_listen in init - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) - device_itf.ep_open(desc); - } + // (Re)configuration disables the remote wakeup feature. + self.remote_wakeup_enabled = false; - const drv = &@field(self.driver_data.?, driver_field_name); - // Don't pass empty slices around - if (@hasField(@TypeOf(self.driver_alloc), driver_field_name)) - drv.init(&cfg, device_itf, &@field(self.driver_alloc, driver_field_name)) - else - drv.init(&cfg, device_itf); - - // Open IN endpoint last so that callbacks can happen - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) - device_itf.ep_open(desc); - } + self.cfg_num = cfg_num; + if (cfg_num == 0) + self.driver_data = null + else { + // We support just one config for now so ignore config index + self.driver_data = @as(configurations[0].RuntimeData, undefined); + configurations[0].init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); } } }; } + +fn dedup_string( + comptime strings: []const []const u8, + comptime new: []const u8, +) struct { []const []const u8, u8 } { + if (new.len == 0) + return .{ strings, 0 }; + // deduplicate + for (strings, 1..) |s, i| { + if (std.mem.eql(u8, s, new)) + return .{ strings, i }; + } + const new_strings = strings ++ .{new}; + return .{ new_strings, @intCast(new_strings.len) }; +} diff --git a/core/src/core/usb/HID_report.zig b/core/src/core/usb/HID_report.zig new file mode 100644 index 000000000..23eb295fd --- /dev/null +++ b/core/src/core/usb/HID_report.zig @@ -0,0 +1,470 @@ +const std = @import("std"); +const usb = @import("../usb.zig"); +const SFAttributes = std.builtin.Type.Struct.FieldAttributes; + +pub const Keycode = enum(u8) { + // Codes taken from: + // https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 + // https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2 + + // zig fmt: off + reserved = 0x00, error_roll_over, post_fail, error_undefined, + a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, + top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, + enter, escape, delete, tab, space, + @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", + caps_lock, + f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, + + print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, + right_arrow, left_arrow, down_arrow, up_arrow, num_lock, + + kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, + kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, + kpad_delete, @"non_us_\\", application, power, @"kpad_=", + + f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, + + execute, help, menu, select, stop, again, undo, cut, copy, paste, find, + mute, volumeup, volumedown, + locking_caps_lock, locking_num_lock, locking_scroll_lock, + + @"kpad_,", @"kpad_alternate_=", + + international1, international2, international3, international4, international5, + international6, international7, international8, international9, + lang1, lang2, lang3, lang4, lang5, lang6, lang7, lang8, lang9, + + alternate_erase, sysreq_attention, cancel, clear, prior, @"return", + separator, out, oper, clear_again, crsel_props, exsel, + + kpad_00 = 0xb0, kpad_000, kpad_thousands_separator, kpad_decimal_separator, + kpad_currency_unit, kpad_currency_subunit, + @"kpad_(", @"kpad_)", @"kpad_{", @"kpad_}", kpad_tab, kpad_backspace, + kpad_a, kpad_b, kpad_c, kpad_d, kpad_e, kpad_f, + kpad_xor, @"kpad_^", @"kpad_%", @"kpad_<", @"kpad_>", @"kpad_&", @"kpad_&&", + @"kpad_|", @"kpad_||", @"kpad_:", @"kpad_#", kpad_space, @"kpad_@", @"kpad_!", + kpad_memory_store, kpad_memory_recall, kpad_memory_clear, kpad_memory_add, + kpad_memory_subtract, kpad_memory_multiply, kpad_memory_divide, @"kpad_+/-", + kpad_clear, kpad_clear_entry, kpad_binary, kpad_octal, kpad_decimal, kpad_hexadecimal, + + lctrl = 0xe0, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, + + media_playpause, media_stopcd, media_previoussong, media_nextsong, + media_ejectcd, media_volumeup, media_volumedown, media_mute, + media_www, media_back, media_forward, media_stop, media_find, + media_scrollup, media_scrolldown, media_edit, media_sleep, + media_coffee, media_refresh, media_calc, + // zig fmt: on + _, + + // Aliases + const open: @This() = .execute; + const props: @This() = .menu; + const front: @This() = .select; + const ro: @This() = .international1; + const katakanahiragana: @This() = .international2; + const yen: @This() = .international3; + const henkan: @This() = .international4; + const muhenkan: @This() = .international5; + const kpjpcomma: @This() = .international6; + const hangeul: @This() = .lang1; + const hanja: @This() = .lang2; + const katakana: @This() = .lang3; + const hiragana: @This() = .lang4; + const zenkakuhankaku: @This() = .lang5; +}; + +pub const Ledcode = enum(u3) { + num_lock = 1, + caps_lock = 2, + scroll_lock = 3, + compose = 4, + kana = 5, +}; + +/// Reports are a list of tagged ?i32 values. Encoding is variable-length. +pub const Item = union(enum) { + pub const Header = packed struct(u8) { + pub const Payload = enum(u2) { + null = 0, + i8 = 1, + i16 = 2, + i32 = 3, + }; + pub const Type = enum(u2) { main = 0, global = 1, local = 2, _ }; + + len: Payload, + type: Type, + tag: u4, + }; + + pub const Collection = enum(i32) { + Physical = 0, + Application, + Logical, + Report, + NamedArray, + UsageSwitch, + UsageModifier, + _, + }; + + pub const UsagePage = enum(i32) { + generic_desktop = 0x01, + keyboard = 0x07, + led = 0x08, + fido = @as(i16, @bitCast(@as(u16, 0xF1D0))), + vendor = 0xFF, + _, + + pub fn Type(self: @This()) type { + return switch (self) { + .keyboard => Keycode, + .led => Ledcode, + inline else => @compileError("Not supported for: " ++ @tagName(self)), + }; + } + }; + + pub const Usage = union(UsagePage) { + pub const GenericDesktop = enum(i32) { + keyboard = 0x06, + _, + }; + + pub const Keyboard = enum(i32) { _ }; + pub const Led = enum(i32) { _ }; + pub const Button = enum(i32) { _ }; + + pub const Fido = enum(i32) { + u2fhid = 0x01, + data_in = 0x20, + data_out = 0x21, + _, + }; + + generic_desktop: GenericDesktop, + keyboard: Keyboard, + led: Led, + fido: Fido, + vendor: i32, + + pub fn local(self: @This()) i32 { + return switch (self) { + inline else => |x| @backingInt(x), + .vendor => |x| x, + }; + } + }; + + pub const InputOutput = packed struct(i8) { + constant: bool = false, // HID_DATA/HID_CONSTANT + variable: bool = false, // HID_ARRAY/HID_VARIABLE + relative: bool = false, // HID_ABSOLUTE/HID_RELATIVE + wrap: bool = false, // HID_WRAP_NO/HID_WRAP + nonlinear: bool = false, // HID_LINEAR/HID_NONLINEAR + not_preferred: bool = false, // HID_PREFERRED_STATE/HID_PREFERRED_NO + null_state: bool = false, // HID_NO_NULL_POSITION/HID_NULL_STATE + @"volatile": bool = false, // HID_NON_VOLATILE/HID_VOLATILE + + pub const dynamic: @This() = .{ .variable = true }; + pub const selector: @This() = .{}; + pub const static: @This() = .{ .constant = true }; + }; + + // main items + main_input: InputOutput, + main_output: InputOutput, + main_collection: Collection, + main_feature: ?i32, + main_collection_end, + + // global items + global_usage_page: UsagePage, + global_logical_min: i32, + global_logical_max: i32, + global_physical_min: ?i32, + global_physical_max: ?i32, + global_unit_exponent: ?i32, + global_unit: ?i32, + global_report_size: u31, + global_report_id: u31, + global_report_count: u31, + global_push: ?i32, + global_pop: ?i32, + + // local items + local_usage: i32, + local_usage_min: i32, + local_usage_max: i32, + local_designator_index: ?i32, + local_designator_min: ?i32, + local_designator_max: ?i32, + local_string_index: ?i32, + local_string_min: ?i32, + local_string_max: ?i32, + local_delimiter, + + pub fn main_io(dir: usb.types.Dir, payload: InputOutput) @This() { + return switch (dir) { + .in => .{ .main_input = payload }, + .out => .{ .main_output = payload }, + }; + } + + pub fn local_usage_enum(usage: Usage) @This() { + return .{ .local_usage = usage.local() }; + } + + pub fn encode_int(int_opt: ?i32) []const u8 { + const asBytes = std.mem.asBytes; + const toLittle = std.mem.nativeToLittle; + const int = int_opt orelse return ""; + return if (std.math.cast(i8, int)) |result| + &.{@bitCast(result)} + else if (std.math.cast(i16, int)) |result| + asBytes(&toLittle(i16, result)) + else + asBytes(&toLittle(i32, int)); + } + + pub fn header(self: @This(), length: usize) Header { + const len: Header.Payload = switch (length) { + 0 => .null, + 1 => .i8, + 2 => .i16, + 4 => .i32, + else => unreachable, + }; + const typ: Header.Type, const tag: u4 = switch (self) { + .main_input => .{ .main, 8 }, + .main_output => .{ .main, 9 }, + .main_collection => .{ .main, 10 }, + .main_feature => .{ .main, 11 }, + .main_collection_end => .{ .main, 12 }, + .global_usage_page => .{ .global, 0 }, + .global_logical_min => .{ .global, 1 }, + .global_logical_max => .{ .global, 2 }, + .global_physical_min => .{ .global, 3 }, + .global_physical_max => .{ .global, 4 }, + .global_unit_exponent => .{ .global, 5 }, + .global_unit => .{ .global, 6 }, + .global_report_size => .{ .global, 7 }, + .global_report_id => .{ .global, 8 }, + .global_report_count => .{ .global, 9 }, + .global_push => .{ .global, 10 }, + .global_pop => .{ .global, 11 }, + .local_usage => .{ .local, 0 }, + .local_usage_min => .{ .local, 1 }, + .local_usage_max => .{ .local, 2 }, + .local_designator_index => .{ .local, 3 }, + .local_designator_min => .{ .local, 4 }, + .local_designator_max => .{ .local, 5 }, + .local_string_index => .{ .local, 7 }, + .local_string_min => .{ .local, 8 }, + .local_string_max => .{ .local, 9 }, + .local_delimiter => .{ .local, 10 }, + }; + return .{ .len = len, .type = typ, .tag = tag }; + } + + pub fn create_report(items: []const @This()) []const u8 { + var ret: []const u8 = ""; + + for (items) |it| { + ret = ret ++ switch (it) { + inline else => |payload| blk: { + const data: []const u8 = switch (@TypeOf(payload)) { + void => "", + Collection, UsagePage => encode_int(@backingInt(payload)), + u31, i32, ?i32 => encode_int(payload), + InputOutput => &.{@backingInt(payload)}, + else => |T| @compileError(@typeName(T) ++ " cannot be turned into a HID report"), + }; + const h = it.header(data.len); + break :blk &[1]u8{@backingInt(h)} ++ data; + }, + }; + } + + return ret; + } +}; + +pub const Finalized = struct { + descriptor: []const u8, + in: type, + out: type, + + pub const boot_keyboard = blk: { + var ret: Report = .generic_desktop; + ret.add_raw(.local_usage_enum(.{ .generic_desktop = .keyboard })); + ret.add_raw(.{ .main_collection = .Application }); + // Input: modifier key bitmap + ret.add_data_dynamic("modifiers", u8, .keyboard, .lctrl, 8, .in); + // Reserved 8 bits + ret.add_data_static(8, .in); + // Output: indicator LEDs + ret.add_data_dynamic("led", u8, .led, .num_lock, 5, .out); + // Input: up to 6 pressed key codes + ret.add_data_selector("keys", .keyboard, 6, .in); + break :blk ret.finalize(); + }; +}; + +const Report = @This(); + +reserved: u16 = 0, +items: []const Item, +names: [2][]const [:0]const u8, +types: [2][]const type, +attrs: [2][]const SFAttributes, + +pub fn finalize(self: Report) Finalized { + var ret = Finalized{ + .descriptor = Item.create_report(self.items ++ [_]Item{.main_collection_end}), + .in = undefined, + .out = undefined, + }; + for (&.{ usb.types.Dir.in, usb.types.Dir.out }) |dir| + @field(ret, @tagName(dir)) = @Struct( + .@"extern", + null, + self.names[@backingInt(dir)], + self.types[@backingInt(dir)], + self.attrs[@backingInt(dir)], + ); + return ret; +} + +pub fn add_raw(self: *Report, item: Item) void { + self.items = self.items ++ [_]Item{item}; +} + +pub fn add_data_static( + self: *Report, + num_bits: u16, + dir: usb.types.Dir, +) void { + self.add_data_static_no_field(num_bits, dir); + self.add_field(dir, "", @Int(.unsigned, num_bits)); +} + +pub fn add_data_dynamic( + self: *Report, + name: [:0]const u8, + BackingInt: type, + usage_page: Item.UsagePage, + first: usage_page.Type(), + count: u16, + dir: usb.types.Dir, +) void { + const T = usage_page.Type(); + self.add_data_non_static_no_field( + usage_page, + @backingInt(first), + @backingInt(first) + (count - 1), + count, + 1, + dir, + .dynamic, + ); + var names: [count + @intFromBool(count < @bitSizeOf(BackingInt))][:0]const u8 = undefined; + var types: [names.len]type = @splat(bool); + var attrs: [names.len]SFAttributes = @splat(.{}); + for (0..count) |i| + names[i] = @tagName(@as(T, @fromBackingInt(@backingInt(first) + i))); + + if (count < @bitSizeOf(BackingInt)) { + const Padding = @Int(.unsigned, @bitSizeOf(BackingInt) - count); + self.add_data_static_no_field(@bitSizeOf(Padding), dir); + names[count] = self.get_reserved_name(); + types[count] = Padding; + attrs[count].default_value_ptr = &@as(Padding, 0); + } + self.add_field(dir, name, @Struct(.@"packed", BackingInt, &names, &types, &attrs)); +} + +pub fn add_data_selector( + self: *Report, + name: [:0]const u8, + usage_page: Item.UsagePage, + count: u16, + dir: usb.types.Dir, +) void { + const T = usage_page.Type(); + self.add_data_non_static_no_field( + usage_page, + 0, + (1 << @bitSizeOf(T)) - 1, + count, + @bitSizeOf(T), + dir, + .selector, + ); + self.add_field(dir, name, [count]T); +} + +pub fn with_first_item(item: Item) Report { + return .{ + .reserved = 0, + .items = &.{item}, + .names = @splat(&.{}), + .types = @splat(&.{}), + .attrs = @splat(&.{}), + }; +} + +pub const generic_desktop = with_first_item(.{ .global_usage_page = .generic_desktop }); + +fn add_field(self: *Report, dir: usb.types.Dir, name: [:0]const u8, Type: type) void { + var attr = SFAttributes{ .@"align" = 1 }; + if (name.len > 0) + self.names[@backingInt(dir)] = self.names[@backingInt(dir)] ++ [_][:0]const u8{name} + else { + self.names[@backingInt(dir)] = self.names[@backingInt(dir)] ++ [_][:0]const u8{self.get_reserved_name()}; + attr.default_value_ptr = &@as(Type, 0); + } + self.types[@backingInt(dir)] = self.types[@backingInt(dir)] ++ [_]type{Type}; + self.attrs[@backingInt(dir)] = self.attrs[@backingInt(dir)] ++ [_]SFAttributes{attr}; +} + +fn get_reserved_name(self: *Report) [:0]const u8 { + defer self.reserved += 1; + return std.fmt.comptimePrint("reserved{}", .{self.reserved}); +} + +fn add_data_static_no_field( + self: *Report, + bitsize: u16, + dir: usb.types.Dir, +) void { + self.items = self.items ++ [_]Item{ + .{ .global_report_count = 1 }, + .{ .global_report_size = bitsize }, + .main_io(dir, .static), + }; +} + +fn add_data_non_static_no_field( + self: *Report, + usage_page: Item.UsagePage, + range_min: i32, + range_max: i32, + count: u16, + bitsize: u16, + dir: usb.types.Dir, + data_type: Item.InputOutput, +) void { + self.items = self.items ++ [_]Item{ + .{ .global_usage_page = usage_page }, + .{ .local_usage_min = range_min }, + .{ .local_usage_max = range_max }, + .{ .global_logical_min = 0 }, + .{ .global_logical_max = (1 << bitsize) - 1 }, + .{ .global_report_count = count }, + .{ .global_report_size = bitsize }, + .main_io(dir, data_type), + }; +} diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig new file mode 100644 index 000000000..e00067256 --- /dev/null +++ b/core/src/core/usb/configuration.zig @@ -0,0 +1,255 @@ +const std = @import("std"); +const usb = @import("../usb.zig"); + +const assert = std.debug.assert; +const descriptor = usb.descriptor; +const SFAttributes = std.builtin.Type.Struct.FieldAttributes; + +pub const Options = struct { + attributes: descriptor.Configuration.Attributes, + max_current_ma: u9, + name: []const u8 = "", + /// Only use either IN or OUT on each endpoint. Useful for debugging. + /// Realistically, it should only be turned off if you are exhausting + /// the 15 endpoint limit. + unique_endpoints: bool = true, +}; + +pub fn Configuration( + options: Options, + driver_config: anytype, +) type { + // Descriptor and EndpointHandlers are passed the default value of a struct, + // because zig does not support `anytype` in structs. + return struct { + const DriverName = []const u8; + + Descriptor: type, + DriverAlloc: type, + RuntimeData: type, + + endpoint2driver: [2][16]DriverName, + EndpointHandlers: type, + interface2driver: []const DriverName, + + pub fn create( + device_capabilities: usb.DeviceCapabilities, + strings: []const []const u8, + ) struct { @This(), []const []const u8 } { + var alloc = usb.DescriptorAllocator.init(options.unique_endpoints, strings); + const configuration_s = alloc.string(options.name); + const driver_names = @typeInfo(@TypeOf(driver_config)).@"struct".field_names; + + var endpoint2driver: [2][16]DriverName = @splat(@splat("")); + var interface2driver: []const DriverName = &.{}; + + // RuntimeData + var runtime_field_types: [driver_names.len]type = undefined; + + // Descriptor + var desc_field_types: [driver_names.len]type = undefined; + var desc_field_attrs: [driver_names.len]SFAttributes = undefined; + + // EndpointHandlers + var ep_handler_types: [2][16]type = @splat(@splat(void)); + var ep_handler_names: [2][16][:0]const u8 = undefined; + + // DriverAlloc + var driver_alloc_types: [driver_names.len]type = undefined; + var driver_alloc_attrs: [driver_names.len]SFAttributes = undefined; + + for ( + driver_names, + &runtime_field_types, + &desc_field_types, + &desc_field_attrs, + &driver_alloc_types, + &driver_alloc_attrs, + ) | + driver_field_name, + *Runtime, + *Descriptor, + *desc_attr, + *driver_alloc_type, + *driver_alloc_attr, + | { + // Get type information for the current driver + const driver = @field(driver_config, driver_field_name); + const Driver = @TypeOf(driver); + if (!@hasDecl(Driver, "driver_info")) + @compileError(@typeName(Driver) ++ ".driver_info() missing"); + const driver_data = driver.driver_info(device_capabilities, &alloc); + Descriptor.* = @TypeOf(driver_data.descriptor); + assert(@alignOf(Descriptor.*) == 1); + Runtime.* = driver_data.Runtime; + desc_attr.* = .{ .default_value_ptr = &driver_data.descriptor }; + driver_alloc_type.* = driver_data.Alloc; + driver_alloc_attr.* = driver_data.alloc_attrs; + + // Collect handler types, names, and drivers, to later be bound to the appropriate + // endpoints + const desc_info = @typeInfo(Descriptor.*).@"struct"; + for (desc_info.field_names, desc_info.field_types, 0..) |desc_field_name, DescriptorField, desc_num| { + const desc = @field(driver_data.descriptor, desc_field_name); + + // Determine which interface numbers this driver owns. If it is an + // InterfaceAssociation, then use the interface count. If it is an Interface, + // then the driver owns just that one interface. + if (desc_num == 0) { + const itf_start, const itf_count = switch (DescriptorField) { + descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, + descriptor.Interface => .{ desc.interface_number, 1 }, + else => |T| @compileError( + "Expected first descriptor of driver " ++ @typeName(Driver) ++ + " to be of type Interface or InterfaceAssociation descriptor, got: " ++ @typeName(T), + ), + }; + if (itf_start != interface2driver.len) + @compileError("interface numbering mismatch"); + + interface2driver = interface2driver ++ @as([itf_count]DriverName, @splat(driver_field_name)); + } + + switch (DescriptorField) { + // Register handler for endpoints + descriptor.Endpoint => { + const ep_dir = @backingInt(desc.endpoint.dir); + const ep_num = @backingInt(desc.endpoint.num); + + if (endpoint2driver[ep_dir][ep_num].len != 0) + @compileError(std.fmt.comptimePrint( + "ep{} {t}: multiple handlers: {s} and {s}", + .{ ep_num, desc.endpoint.dir, endpoint2driver[ep_dir][ep_num], driver_field_name }, + )); + + endpoint2driver[ep_dir][ep_num] = driver_field_name; + ep_handler_names[ep_dir][ep_num] = desc_field_name; + ep_handler_types[ep_dir][ep_num] = usb.EndpointHandler(Runtime.*); + }, + // Interface association must be first + descriptor.InterfaceAssociation => assert(desc_num == 0), + else => {}, + } + } + } + + const RuntimeData = @Struct( + .auto, + null, + driver_names, + &runtime_field_types, + &@splat(.{}), + ); + + // Finally, bind the handler functions based on the data collected above. + // Create a tuple with the appropriate types + const ep_handlers_types: [2]type = .{ @Tuple(&ep_handler_types[0]), @Tuple(&ep_handler_types[1]) }; + var ep_handlers: @Tuple(&ep_handlers_types) = undefined; + // Iterate over all IN and OUT endpoints and bind the handler for any that are set. + for (&ep_handlers, &ep_handler_names, &ep_handler_types, &endpoint2driver) |*handlers, *names, *types, *drivers| { + for (handlers, names, types, drivers) |*handler, name, Type, driver| { + if (Type != void) + handler.* = @field(@FieldType(RuntimeData, driver).handlers, name); + } + } + + // alloc is invalidated after this point. It will cause a compile error if accessed. + const const_alloc = alloc.to_const(); + const const_ep_handlers = ep_handlers; + + const DriverConfig = @Struct( + .@"extern", + null, + driver_names, + &desc_field_types, + &desc_field_attrs, + ); + + const Descriptor = extern struct { + first: descriptor.Configuration = .{ + .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), + .num_interfaces = const_alloc.next_itf_num, + .configuration_value = 1, + .configuration_s = configuration_s, + .attributes = options.attributes, + .max_current = .from_ma(options.max_current_ma), + }, + drv: DriverConfig = .{}, + }; + + std.testing.expectEqual( + (Descriptor{}).first.total_length.native(), + @sizeOf(Descriptor), + ) catch unreachable; + + const idx_in = @backingInt(usb.types.Dir.in); + const idx_out = @backingInt(usb.types.Dir.out); + return .{ + .{ + .Descriptor = Descriptor, + .DriverAlloc = @Struct( + .auto, + null, + driver_names, + &driver_alloc_types, + &driver_alloc_attrs, + ), + .endpoint2driver = endpoint2driver, + .EndpointHandlers = struct { + in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], + out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], + }, + .interface2driver = interface2driver, + .RuntimeData = RuntimeData, + }, + const_alloc.strings, + }; + } + + pub fn init( + comptime self: @This(), + device_itf: *usb.DeviceInterface, + driver_data: *self.RuntimeData, + driver_alloc: anytype, + comptime config_descriptor: anytype, + ) void { + inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { + const cfg = @field(config_descriptor.drv, driver_field_name); + const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; + + // Open OUT endpoint first so that the driver can call ep_listen in init + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) + device_itf.ep_open(desc); + } + + const driver = @field(driver_config, driver_field_name); + const runtime = &@field(driver_data, driver_field_name); + const alloc = &@field(driver_alloc, driver_field_name); + + if (!@hasDecl(@TypeOf(runtime.*), "init")) + @compileError(@typeName(@TypeOf(runtime.*)) ++ ".init() missing"); + + // Don't pass *void around + if (@TypeOf(alloc) != *void) + runtime.init(driver, &cfg, device_itf, alloc) + else + runtime.init(driver, &cfg, device_itf); + + // Open IN endpoint last so that callbacks can happen + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) + device_itf.ep_open(desc); + } + } + } + + pub fn deinit(comptime self: @This(), device_itf: *usb.DeviceInterface, driver_data: *self.RuntimeData) void { + _ = device_itf; + _ = driver_data; + // deinitialize drivers + } + }; +} diff --git a/core/src/core/usb/descriptor.zig b/core/src/core/usb/descriptor.zig index 581e68a70..4c9b296df 100644 --- a/core/src/core/usb/descriptor.zig +++ b/core/src/core/usb/descriptor.zig @@ -1,7 +1,5 @@ const std = @import("std"); -const EndianInt = @import("../mem.zig").EndianInt; - const types = @import("types.zig"); const assert = std.debug.assert; @@ -69,9 +67,9 @@ pub const Device = extern struct { /// Maximum length of data this device can move. max_packet_size0: u8, /// ID of product vendor. - vendor: EndianInt(u16, .little) align(1), + vendor: types.LeInt(u16) align(1), /// ID of product. - product: EndianInt(u16, .little) align(1), + product: types.LeInt(u16) align(1), /// Device version number as Binary Coded Decimal. bcd_device: types.Version, /// Index of manufacturer name in string descriptor table. @@ -130,7 +128,7 @@ pub const Configuration = extern struct { /// Total length of all descriptors in this configuration, concatenated. /// This will include this descriptor, plus at least one interface /// descriptor, plus each interface descriptor's endpoint descriptors. - total_length: EndianInt(u16, .little) align(1), + total_length: types.LeInt(u16) align(1), /// Number of interface descriptors in this configuration. num_interfaces: u8, /// Number to use when requesting this configuration via a @@ -157,7 +155,7 @@ pub const String = struct { const ret: *const extern struct { length: u8 = @sizeOf(@This()), descriptor_type: Type = .string, - lang: EndianInt(u16, .little) align(1), + lang: types.LeInt(u16) align(1), } = comptime &.{ .lang = .from(@backingInt(lang)) }; return .{ .data = std.mem.asBytes(ret) }; } @@ -207,12 +205,12 @@ pub const Endpoint = extern struct { /// control the transfer type using the values from `TransferType`. attributes: Attributes, /// Maximum packet size this endpoint can accept/produce. - max_packet_size: EndianInt(u16, .little) align(1), + max_packet_size: types.LeInt(u16) align(1), /// Interval for polling interrupt/isochronous endpoints (which we don't /// currently support) in milliseconds. interval: u8, - pub fn control(ep: types.Endpoint, max_packet_size: types.Len) @This() { + pub fn control(ep: types.Endpoint, max_packet_size: types.PacketLength) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Control, .usage = .data }, @@ -221,7 +219,7 @@ pub const Endpoint = extern struct { }; } - pub fn bulk(ep: types.Endpoint, max_packet_size: types.Len) @This() { + pub fn bulk(ep: types.Endpoint, max_packet_size: types.PacketLength) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Bulk, .usage = .data }, @@ -230,7 +228,7 @@ pub const Endpoint = extern struct { }; } - pub fn interrupt(ep: types.Endpoint, max_packet_size: types.Len, poll_interval: u8) @This() { + pub fn interrupt(ep: types.Endpoint, max_packet_size: types.PacketLength, poll_interval: u8) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Interrupt, .usage = .data }, @@ -300,7 +298,7 @@ pub const BOS = struct { const header: []const u8 = std.mem.asBytes(&extern struct { length: u8 = @sizeOf(@This()), descriptor_type: Type = .bos, - total_length: EndianInt(u16, .little) align(1) = .from(@sizeOf(@This()) + data.len), + total_length: types.LeInt(u16) align(1) = .from(@sizeOf(@This()) + data.len), num_descriptors: u8 = @intCast(objects.len), }{}); return .{ .data = header ++ data }; @@ -378,5 +376,5 @@ pub const HID = extern struct { /// Type of HID class report report_type: CsType = .Report, /// The total size of the Report descriptor - report_length: EndianInt(u16, .little) align(1), + report_length: types.LeInt(u16) align(1), }; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index f6ab55abb..1b3724df5 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -2,12 +2,11 @@ const std = @import("std"); const microzig = @import("../../../microzig.zig"); const assert = microzig.assert; -const mem = @import("../../mem.zig"); -const EndianInt = mem.EndianInt; - const usb = @import("../../usb.zig"); const log = std.log.scoped(.usb_cdc); +const Driver = @This(); + /// CDC PSTN Subclass Management Element Requests pub const ManagementRequestType = enum(u8) { SetCommFeature = 0x02, @@ -45,7 +44,7 @@ pub const LineCoding = extern struct { _, }; - bit_rate: EndianInt(u32, .little), + bit_rate: usb.types.LeInt(u32), stop_bits: StopBits, parity: Parity, data_bits: u8, @@ -72,212 +71,221 @@ pub const Descriptor = extern struct { itf_data: desc.Interface, ep_out: desc.Endpoint, ep_in: desc.Endpoint, - - 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, - }, - }, - .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, - }; - } }; -// 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, -}; +pub const Runtime = struct { + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + line_coding: LineCoding align(4), + notifi_ready: std.atomic.Value(bool), -device: *usb.DeviceInterface, -descriptor: *const Descriptor, -line_coding: LineCoding align(4), -notifi_ready: std.atomic.Value(bool), + rx_data: []u8, + rx_seek: usb.types.PacketLength, + rx_end: usb.types.PacketLength, + rx_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.PacketLength, + tx_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.PacketLength { + return self.rx_end - self.rx_seek; + } -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; -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; - 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)); + } - // 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; } - return len; -} + pub fn write(self: *@This(), data: []const u8) usize { + const len = @min(self.tx_data.len - self.tx_end, data.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); - @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(); - if (self.tx_end == self.tx_data.len) - _ = self.flush(); + return len; + } - 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; -/// 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); - 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; + } - 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; -} + // *** USB driver interface below *** + + // Called when the host selects a configuration. + pub fn init( + self: *Runtime, + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + data: []u8, + ) void { + const len_half = @divExact(data.len, 2); + assert(len_half == descriptor.ep_in.max_packet_size.native(), .{}); + assert(len_half == descriptor.ep_out.max_packet_size.native(), .{}); + self.* = .{ + .device = device, + .descriptor = descriptor, + .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(descriptor.ep_out.endpoint.num, @intCast(self.rx_data.len)); + } -// 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), + // 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(Descriptor, @This()) = .{ + .ep_notifi = on_notifi_ready, + .ep_out = on_rx, + .ep_in = on_tx_ready, }; - 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, - }; -} + /// 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_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_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_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); + } +}; + +itf_notifi_str: []const u8 = "", +itf_data_str: []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 driver_info( + self: Driver, + comptime device_capabilities: usb.DeviceCapabilities, + alloc: *usb.DescriptorAllocator, +) usb.DriverInfo(Descriptor) { + // 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 .{ + .Runtime = Runtime, + .Alloc = [2 * device_capabilities.max_packet_size]u8, + .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(self.itf_notifi_str), + }, + .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 (device_capabilities.max_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(self.itf_data_str), + }, + .ep_out = .bulk(alloc.next_ep(.out), device_capabilities.max_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), device_capabilities.max_packet_size), + }, + }; } diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index f78a4bc6f..0e2d8914d 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -1,113 +1,148 @@ //! This is an example driver that sends any data received on ep2 to ep1. +//! Also acts as the specification of the USB driver interface. + const std = @import("std"); const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_echo); -/// The descriptors need to have the same memory layout as the sent data. +const Driver = @This(); + +/// Binary representation of the device descriptor as sent to the host. +/// Make sure to use `extern` layout and endian-aware field types, +/// such as `usb.types.LeInt(uXX/iXX)`. pub const Descriptor = extern struct { const desc = usb.descriptor; itf: desc.Interface, + /// Endpoint descriptor names are special. + /// Later, they are matched to endpoint handler functions 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 preffered to making the whole driver generic. - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, - itf_string: []const u8, - ) usb.DescriptorCreateResult(@This()) { - return .{ - .descriptor = .{ - .itf = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .vendor_specific, - .interface_s = alloc.string(itf_string), - }, - .ep_out = .bulk(alloc.next_ep(.Out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.In), max_supported_packet_size), - }, - // Buffers whose length is only known after creating the - // descriptor can be allocated at this stage. - .alloc_bytes = max_supported_packet_size, +/// Runtime data and code associated with an instance of the driver. +/// Avoid using global variables here, so that multiple driver instances +/// can be used at the same time. +pub const Runtime = struct { + /// This is a mapping from endpoint descriptor field names to handler function names. + /// 'in' and 'out' are from the perspective of the host. + /// USB devices send data on 'in' endpoints and receive on 'out' endpoints. + pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ + .ep_in = on_tx_ready, + .ep_out = on_rx, + }; + + /// Fields in this struct have no special meaning to MicroZig + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + packet_buffer: []u8, + tx_ready: std.atomic.Value(bool), + + /// This function is called when the host chooses a configuration that contains this driver. `self` + /// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. + pub fn init( + self: *@This(), + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + data: []u8, + ) void { + assert(data.len == descriptor.ep_in.max_packet_size.native()); + self.* = .{ + .device = device, + .descriptor = descriptor, + .packet_buffer = data, + .tx_ready = .init(false), }; + device.ep_listen( + descriptor.ep_out.endpoint.num, + @intCast(descriptor.ep_out.max_packet_size.native()), + ); } -}; -/// This is a mapping from endpoint descriptor field names to handler function names. -/// 'in' and 'out' are from the perspective of the host, so, usb devices send data on 'in' endpoints -/// and receive on 'out' endpoints. -pub const handlers: usb.DriverHandlers(@This()) = .{ - .ep_in = on_tx_ready, - .ep_out = on_rx, -}; + /// Used for interface configuration through endpoint 0. + /// Data returned by this function is sent on endpoint 0. + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + _ = self; + log.debug("setup: {x}, {}, {}", .{ setup.request, setup.length.native(), setup.value.native() }); + return usb.ack; + } -device: *usb.DeviceInterface, -descriptor: *const Descriptor, -packet_buffer: []u8, -tx_ready: std.atomic.Value(bool), + /// Transmit handler callback. + /// Each endpoint (as defined in the descriptor) has its own handler. + /// Endpoint number is passed as an argument so that it does not need to be stored in the driver. + pub fn on_tx_ready(self: *@This(), ep_tx: usb.types.Endpoint.Num) void { + log.info("tx ready ({t})", .{ep_tx}); + // Mark transmission as available + self.tx_ready.store(true, .seq_cst); + } -/// This function is called when the host chooses a configuration that contains this driver. `self` -/// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. -pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - assert(data.len == desc.ep_in.max_packet_size.native()); - self.* = .{ - .device = device, - .descriptor = desc, - .packet_buffer = data, - .tx_ready = .init(false), - }; - device.ep_listen( - desc.ep_out.endpoint.num, - @intCast(desc.ep_out.max_packet_size.native()), - ); -} + /// Receive handler callback. + /// Endpoint number is passed as an argument so that it does not need to be stored in the driver. + pub fn on_rx(self: *@This(), ep_rx: usb.types.Endpoint.Num) void { + var buf: [64]u8 = undefined; + // Read incoming packet into a local buffer + const len_rx = self.device.ep_readv(ep_rx, &.{&buf}); + log.info("Received on {t}: {s}", .{ ep_rx, buf[0..len_rx] }); -/// Used for interface configuration through endpoint 0. -/// Data returned by this function is sent on endpoint 0. -pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - _ = self; - log.debug("setup: {x}, {}, {}", .{ setup.request, setup.length.native(), setup.value.native() }); - return usb.ack; -} + // Check if we can transmit + if (self.tx_ready.load(.seq_cst)) { + // Mark transmission as not available + self.tx_ready.store(false, .seq_cst); + // Send received packet + log.info("Sending {} bytes", .{len_rx}); + const len_tx = self.device.ep_writev( + self.descriptor.ep_in.endpoint.num, + &.{buf[0..len_rx]}, + ); + if (len_tx != len_rx) + log.err("Only sent {} bytes", .{len_tx}); + } + // Listen for next packet + self.device.ep_listen(ep_rx, 64); + } +}; -/// Transmit handler callback. -/// Each endpoint (as defined in the descriptor) has its own handler. -/// Endpoint number is passed as an argument so that it does not need to be stored in the driver. -pub fn on_tx_ready(self: *@This(), ep_tx: usb.types.Endpoint.Num) void { - log.info("tx ready ({t})", .{ep_tx}); - // Mark transmission as available - self.tx_ready.store(true, .seq_cst); -} +/// `Runtime` type can be generic, in which case the driver type +/// is the only parameter passed. It may be a good idea to make this function +/// a wrapper around another, that only takes a subset of the parameters. +/// This way the generic types are much more readable in zig error output +/// and potentially less code is duplicated when using multiple driver instances +/// with different options. See HID.zig for an example. -/// Receive handler callback. -/// Endpoint number is passed as an argument so that it does not need to be stored in the driver. -pub fn on_rx(self: *@This(), ep_rx: usb.types.Endpoint.Num) void { - var buf: [64]u8 = undefined; - // Read incoming packet into a local buffer - const len_rx = self.device.ep_readv(ep_rx, &.{&buf}); - log.info("Received on {t}: {s}", .{ ep_rx, buf[0..len_rx] }); +// Each field represents a configuration option of the driver. +// The values are declared by user code and available during initialization. +// May not have any fields if the driver does not require configuration. +// Common use case for this type of configuration is for descriptor data +// that is not used by the driver at runtime, like descriptor strings. +itf_string: []const u8 = "", - // Check if we can transmit - if (self.tx_ready.load(.seq_cst)) { - // Mark transmission as not available - self.tx_ready.store(false, .seq_cst); - // Send received packet - log.info("Sending {} bytes", .{len_rx}); - const len_tx = self.device.ep_writev( - self.descriptor.ep_in.endpoint.num, - &.{buf[0..len_rx]}, - ); - if (len_tx != len_rx) - log.err("Only sent {} bytes", .{len_tx}); - } - // Listen for next packet - self.device.ep_listen(ep_rx, 64); +/// This function is used during descriptor creation. Endpoint and interface numbers are +/// allocated through the `alloc` parameter. Third argument contains the maximum supported +/// packet length, which varies by implementation. If multiple instances of a driver are used, +/// this function is called for each, with different arguments. +/// Aside from the descriptor, this function can return a type that is later used +pub fn driver_info( + self: Driver, + comptime device_capabilities: usb.DeviceCapabilities, + alloc: *usb.DescriptorAllocator, +) usb.DriverInfo(Descriptor) { + return .{ + // Buffers whose length is only known after creating the + // descriptor can be allocated at this stage. + .Alloc = [device_capabilities.max_packet_size]u8, + .Runtime = Runtime, + .descriptor = .{ + .itf = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .vendor_specific, + .interface_s = alloc.string(self.itf_string), + }, + .ep_out = .bulk(alloc.next_ep(.out), device_capabilities.max_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), device_capabilities.max_packet_size), + }, + }; } diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig new file mode 100644 index 000000000..fad1d08eb --- /dev/null +++ b/core/src/core/usb/drivers/HID.zig @@ -0,0 +1,202 @@ +const std = @import("std"); +const usb = @import("../../usb.zig"); +const assert = std.debug.assert; +const log = std.log.scoped(.usb_hid_int_driver); + +const Driver = @This(); + +pub const Descriptor = extern struct { + const desc = usb.descriptor; + + interface: desc.Interface, + hid: desc.HID, + ep_out: desc.Endpoint, + ep_in: desc.Endpoint, +}; + +/// HID Driver with an IN and OUT endpoint +pub fn Runtime(report: usb.HID_report.Finalized) type { + return struct { + pub const ReportIn = report.in; + pub const ReportOut = report.out; + + pub const RequestType = enum(u8) { + GetReport = 0x01, + GetIdle = 0x02, + GetProtocol = 0x03, + SetReport = 0x09, + SetIdle = 0x0a, + SetProtocol = 0x0b, + _, + }; + + pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ + .ep_in = on_tx_ready, + .ep_out = on_rx, + }; + + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + tx_ready: std.atomic.Value(bool), + rx_ready: std.atomic.Value(bool), + + pub fn init( + self: *@This(), + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + ) void { + log.debug("init", .{}); + self.* = .{ + .device = device, + .descriptor = descriptor, + .tx_ready = .init(true), + .rx_ready = .init(false), + }; + device.ep_listen( + descriptor.ep_out.endpoint.num, + @intCast(descriptor.ep_out.max_packet_size.native()), + ); + } + + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + log.debug("class_request {any}", .{setup}); + switch (setup.request_type.type) { + .standard => { + const hid_desc_type: usb.descriptor.HID.CsType = @fromBackingInt(@intCast(setup.value.native() >> 8)); + const request_code: usb.types.SetupRequest = @fromBackingInt(setup.request); + + if (request_code == .get_descriptor and hid_desc_type == .HID) + return std.mem.asBytes(&self.descriptor.hid) + else if (request_code == .get_descriptor and hid_desc_type == .Report) + return report.descriptor; + }, + .class => { + const hid_request_type: RequestType = @fromBackingInt(setup.request); + switch (hid_request_type) { + .SetIdle => { + // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 + // The host is attempting to limit bandwidth by requesting that + // the device only return report data when its values actually change, + // or when the specified duration elapses. In practice, the device can + // still send reports as often as it wants, but for completeness this + // should be implemented eventually. + // + return usb.ack; + }, + .SetProtocol => { + // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 + // The device should switch the format of its reports from the boot + // keyboard/mouse protocol to the format described in its report descriptor, + // or vice versa. + // + // For now, this request is ACKed without doing anything; in practice, + // the OS will request the report protocol anyway, so usually only one format is needed. + // Unless the report format matches the boot protocol exactly (see ReportDescriptorKeyboard), + // our device might not work in a limited BIOS environment. + // + return usb.ack; + }, + .SetReport => { + // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 + // This request sends a feature or output report to the device, + // e.g. turning on the caps lock LED. This must be handled in an + // application-specific way, so notify the application code of the event. + // + return usb.ack; + }, + else => {}, + } + }, + else => {}, + } + return usb.nak; + } + + pub fn on_tx_ready(self: *@This(), ep: usb.types.Endpoint.Num) void { + log.debug("tx ready ({t})", .{ep}); + self.tx_ready.store(true, .seq_cst); + } + + pub fn on_rx(self: *@This(), ep: usb.types.Endpoint.Num) void { + log.debug("rx ({t})", .{ep}); + self.rx_ready.store(true, .seq_cst); + } + + pub fn send_report(self: *@This(), rep: *const ReportIn) bool { + if (!self.tx_ready.load(.seq_cst)) return false; + + self.tx_ready.store(false, .seq_cst); + + const len = self.device.ep_writev( + self.descriptor.ep_in.endpoint.num, + &.{std.mem.asBytes(rep)}, + ); + + log.debug("sent report {} {any}", .{ len, rep }); + + return true; + } + + pub fn receive_report(self: *@This()) ?ReportOut { + if (!self.rx_ready.load(.seq_cst)) return null; + + self.rx_ready.store(false, .seq_cst); + + var rep: ReportOut = undefined; + const ep_num = self.descriptor.ep_out.endpoint.num; + const len = self.device.ep_readv(ep_num, &.{std.mem.asBytes(&rep)}); + self.device.ep_listen(ep_num, @intCast(self.descriptor.ep_out.max_packet_size.native())); + + log.debug("received report {} {any}", .{ len, rep }); + + return rep; + } + }; +} + +const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; + +subclass: ClassCode.Subclass(), +protocol: ClassCode.Protocol(), + +itf_string: []const u8 = "", +poll_interval: u8, +country_code: usb.descriptor.HID.CountryCode = .NotSupported, +report: usb.HID_report.Finalized, + +pub fn driver_info( + comptime self: Driver, + comptime device_capabilities: usb.DeviceCapabilities, + alloc: *usb.DescriptorAllocator, +) usb.DriverInfo(Descriptor) { + assert(@sizeOf(self.report.in) <= device_capabilities.max_packet_size); + assert(@sizeOf(self.report.out) <= device_capabilities.max_packet_size); + return .{ + .Runtime = Runtime(self.report), + .descriptor = .{ + .interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.HID, self.subclass, self.protocol), + .interface_s = alloc.string(self.itf_string), + }, + .hid = .{ + .country_code = self.country_code, + .num_descriptors = 1, + .report_length = .from(self.report.descriptor.len), + }, + .ep_out = .interrupt( + alloc.next_ep(.out), + @sizeOf(self.report.out), + self.poll_interval, + ), + .ep_in = .interrupt( + alloc.next_ep(.in), + @sizeOf(self.report.in), + self.poll_interval, + ), + }, + }; +} diff --git a/core/src/core/usb/drivers/hid.zig b/core/src/core/usb/drivers/hid.zig deleted file mode 100644 index 49205c845..000000000 --- a/core/src/core/usb/drivers/hid.zig +++ /dev/null @@ -1,490 +0,0 @@ -const std = @import("std"); -const usb = @import("../../usb.zig"); -const assert = std.debug.assert; - -/// Reports are a list of tagged ?i32 values. Encoding is variable-length. -pub const ReportItem = union(enum) { - pub const Header = packed struct(u8) { - pub const Payload = enum(u2) { - null = 0, - i8 = 1, - i16 = 2, - i32 = 3, - }; - pub const Type = enum(u2) { main = 0, global = 1, local = 2, _ }; - - len: Payload, - type: Type, - tag: u4, - }; - - pub const Collection = enum(i32) { - Physical = 0, - Application, - Logical, - Report, - NamedArray, - UsageSwitch, - UsageModifier, - _, - }; - - pub const UsagePage = enum(i32) { - generic_desktop = 0x01, - keyboard = 0x07, - led = 0x08, - fido = @as(i16, @bitCast(@as(u16, 0xF1D0))), - vendor = 0xFF, - _, - }; - - pub const Usage = union(UsagePage) { - pub const GenericDesktop = enum(i32) { - keyboard = 0x06, - _, - }; - - pub const Keyboard = enum(i32) { _ }; - pub const Led = enum(i32) { _ }; - pub const Button = enum(i32) { _ }; - - pub const Fido = enum(i32) { - u2fhid = 0x01, - data_in = 0x20, - data_out = 0x21, - _, - }; - - generic_desktop: GenericDesktop, - keyboard: Keyboard, - led: Led, - fido: Fido, - vendor: i32, - - pub fn local(self: @This()) i32 { - return switch (self) { - inline else => |x| @backingInt(x), - .vendor => |x| x, - }; - } - }; - - pub const InputOutput = packed struct(i8) { - constant: bool = false, // HID_DATA/HID_CONSTANT - variable: bool = false, // HID_ARRAY/HID_VARIABLE - relative: bool = false, // HID_ABSOLUTE/HID_RELATIVE - wrap: bool = false, // HID_WRAP_NO/HID_WRAP - nonlinear: bool = false, // HID_LINEAR/HID_NONLINEAR - not_preferred: bool = false, // HID_PREFERRED_STATE/HID_PREFERRED_NO - null_state: bool = false, // HID_NO_NULL_POSITION/HID_NULL_STATE - @"volatile": bool = false, // HID_NON_VOLATILE/HID_VOLATILE - - pub const dynamic: @This() = .{ .variable = true }; - pub const selector: @This() = .{}; - pub const static: @This() = .{ .constant = true }; - }; - - pub const Data = struct { - pub const Type = enum { dynamic, selector }; - - usage: union(enum) { - global_page: UsagePage, - local: Usage, - local_raw: i32, - - pub fn report(self: @This()) ReportItem { - return switch (self) { - .global_page => |page| .{ .global_usage_page = page }, - .local => |usage| .local_usage_enum(usage), - .local_raw => |val| .{ .local_usage = val }, - }; - } - }, - usage_range: ?[2]i32 = null, - logical_range: ?[2]i32 = null, - count: u31, - Child: type, - dir: usb.types.Dir, - type: Type, - }; - - // main items - main_input: InputOutput, - main_output: InputOutput, - main_collection: Collection, - main_feature: ?i32, - main_collection_end, - - // global items - global_usage_page: UsagePage, - global_logical_min: i32, - global_logical_max: i32, - global_physical_min: ?i32, - global_physical_max: ?i32, - global_unit_exponent: ?i32, - global_unit: ?i32, - global_report_size: u31, - global_report_id: u31, - global_report_count: u31, - global_push: ?i32, - global_pop: ?i32, - - // local items - local_usage: i32, - local_usage_min: i32, - local_usage_max: i32, - local_designator_index: ?i32, - local_designator_min: ?i32, - local_designator_max: ?i32, - local_string_index: ?i32, - local_string_min: ?i32, - local_string_max: ?i32, - local_delimiter, - - // helpers - usage_page_and_local: Usage, - global_logical_range: [2]i32, - global_report_type: type, - local_usage_range: [2]i32, - data: Data, - data_static: struct { usb.types.Dir, type }, - - pub fn main_io(dir: usb.types.Dir, payload: InputOutput) @This() { - return switch (dir) { - .in => .{ .main_input = payload }, - .out => .{ .main_output = payload }, - }; - } - - pub fn local_usage_enum(usage: Usage) @This() { - return .{ .local_usage = usage.local() }; - } - - pub fn encode_int(int_opt: ?i32) []const u8 { - const asBytes = std.mem.asBytes; - const toLittle = std.mem.nativeToLittle; - const int = int_opt orelse return ""; - return if (std.math.cast(i8, int)) |result| - &.{@bitCast(result)} - else if (std.math.cast(i16, int)) |result| - asBytes(&toLittle(i16, result)) - else - asBytes(&toLittle(i32, int)); - } - - pub fn header(self: @This(), length: usize) ?Header { - const len: Header.Payload = switch (length) { - 0 => .null, - 1 => .i8, - 2 => .i16, - 4 => .i32, - else => unreachable, - }; - const typ: Header.Type, const tag: u4 = switch (self) { - .main_input => .{ .main, 8 }, - .main_output => .{ .main, 9 }, - .main_collection => .{ .main, 10 }, - .main_feature => .{ .main, 11 }, - .main_collection_end => .{ .main, 12 }, - .global_usage_page => .{ .global, 0 }, - .global_logical_min => .{ .global, 1 }, - .global_logical_max => .{ .global, 2 }, - .global_physical_min => .{ .global, 3 }, - .global_physical_max => .{ .global, 4 }, - .global_unit_exponent => .{ .global, 5 }, - .global_unit => .{ .global, 6 }, - .global_report_size => .{ .global, 7 }, - .global_report_id => .{ .global, 8 }, - .global_report_count => .{ .global, 9 }, - .global_push => .{ .global, 10 }, - .global_pop => .{ .global, 11 }, - .local_usage => .{ .local, 0 }, - .local_usage_min => .{ .local, 1 }, - .local_usage_max => .{ .local, 2 }, - .local_designator_index => .{ .local, 3 }, - .local_designator_min => .{ .local, 4 }, - .local_designator_max => .{ .local, 5 }, - .local_string_index => .{ .local, 7 }, - .local_string_min => .{ .local, 8 }, - .local_string_max => .{ .local, 9 }, - .local_delimiter => .{ .local, 10 }, - else => return null, - }; - return .{ .len = len, .type = typ, .tag = tag }; - } - - pub fn type_size(T: type) comptime_int { - return switch (@typeInfo(T)) { - .int, .bool => @bitSizeOf(T), - else => @compileError(@typeName(T) ++ " cannot be sent in a HID report"), - }; - } - - pub fn create_report(items: []const ?@This()) []const u8 { - var ret: []const u8 = ""; - - for (items) |it_opt| if (it_opt) |it| { - ret = ret ++ switch (it) { - .global_report_type => |T| blk: { - const count, const Child = switch (@typeInfo(T)) { - .array => |info| .{ info.len, info.child }, - else => .{ 1, T }, - }; - break :blk create_report(&.{ - .{ .global_report_count = count }, - .{ .global_report_size = type_size(Child) }, - }); - }, - .global_logical_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .global_logical_min = range[0] }, - .{ .global_logical_max = range[1] }, - }); - }, - .local_usage_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .local_usage_min = range[0] }, - .{ .local_usage_max = range[1] }, - }); - }, - .data => |info| create_report(&.{ - info.usage.report(), - if (info.usage_range) |ur| .{ .local_usage_range = ur } else null, - .{ .global_logical_range = info.logical_range orelse - switch (@typeInfo(info.Child)) { - .bool => .{ 0, 1 }, - .int => .{ std.math.minInt(info.Child), std.math.maxInt(info.Child) }, - else => unreachable, - } }, - .{ .global_report_type = [info.count]info.Child }, - .main_io(info.dir, switch (info.type) { - .dynamic => .dynamic, - .selector => .selector, - }), - }), - .data_static => |info| create_report(&.{ - .{ .global_report_type = info[1] }, - .main_io(info[0], .static), - }), - .usage_page_and_local => |usage| create_report(&.{ - .{ .global_usage_page = usage }, - .{ .local_usage = usage.local() }, - }), - inline else => |payload| blk: { - const data: []const u8 = switch (@TypeOf(payload)) { - void => "", - Collection, UsagePage => encode_int(@backingInt(payload)), - u31, i32, ?i32 => encode_int(payload), - InputOutput => &.{@bitCast(payload)}, - else => |T| @compileError(@typeName(T) ++ " cannot be turned into a HID report"), - }; - const h = it.header(data.len) orelse - @compileError(@tagName(it) ++ " is not a report"); - break :blk &[1]u8{@bitCast(h)} ++ data; - }, - }; - }; - - return ret; - } -}; - -const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; - -pub const InterruptDriverOptions = struct { - subclass: ClassCode.Subclass(), - protocol: ClassCode.Protocol(), - InReport: type, - OutReport: type, - report_descriptor: []const ?ReportItem, -}; - -/// HID Driver with an IN and OUT endpoint -pub fn InterruptDriver(options: InterruptDriverOptions) type { - const log = std.log.scoped(.usb_hid_int_driver); - - return struct { - pub const RequestType = enum(u8) { - GetReport = 0x01, - GetIdle = 0x02, - GetProtocol = 0x03, - SetReport = 0x09, - SetIdle = 0x0a, - SetProtocol = 0x0b, - _, - }; - - pub const report_descriptor = ReportItem.create_report(options.report_descriptor); - - const OutReport = options.OutReport; - const InReport = options.InReport; - - pub const Descriptor = extern struct { - const desc = usb.descriptor; - - interface: desc.Interface, - hid: desc.HID, - ep_out: desc.Endpoint, - ep_in: desc.Endpoint, - - pub const Options = struct { - itf_string: []const u8 = "", - poll_interval: u8, - country_code: desc.HID.CountryCode = .NotSupported, - }; - - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, - desc_options: Options, - ) usb.DescriptorCreateResult(@This()) { - assert(@sizeOf(InReport) <= max_supported_packet_size); - assert(@sizeOf(OutReport) <= max_supported_packet_size); - return .{ .descriptor = .{ - .interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.HID, options.subclass, options.protocol), - .interface_s = alloc.string(desc_options.itf_string), - }, - .hid = .{ - .country_code = desc_options.country_code, - .num_descriptors = 1, - .report_length = .from(report_descriptor.len), - }, - .ep_out = .interrupt( - alloc.next_ep(.out), - @sizeOf(OutReport), - desc_options.poll_interval, - ), - .ep_in = .interrupt( - alloc.next_ep(.in), - @sizeOf(InReport), - desc_options.poll_interval, - ), - } }; - } - }; - - pub const handlers: usb.DriverHandlers(@This()) = .{ - .ep_in = on_tx_ready, - .ep_out = on_rx, - }; - - device: *usb.DeviceInterface, - descriptor: *const Descriptor, - tx_ready: std.atomic.Value(bool), - rx_ready: std.atomic.Value(bool), - - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { - log.debug("init", .{}); - self.* = .{ - .device = device, - .descriptor = desc, - .tx_ready = .init(true), - .rx_ready = .init(false), - }; - self.device.ep_listen( - self.descriptor.ep_out.endpoint.num, - @intCast(self.descriptor.ep_out.max_packet_size.native()), - ); - } - - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - log.debug("class_request {any}", .{setup}); - switch (setup.request_type.type) { - .standard => { - const hid_desc_type: usb.descriptor.HID.CsType = @fromBackingInt(@intCast(setup.value.native() >> 8)); - const request_code: usb.types.SetupRequest = @fromBackingInt(setup.request); - - if (request_code == .get_descriptor and hid_desc_type == .HID) - return std.mem.asBytes(&self.descriptor.hid) - else if (request_code == .get_descriptor and hid_desc_type == .Report) - return report_descriptor; - }, - .class => { - const hid_request_type: RequestType = @fromBackingInt(setup.request); - switch (hid_request_type) { - .SetIdle => { - // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 - // The host is attempting to limit bandwidth by requesting that - // the device only return report data when its values actually change, - // or when the specified duration elapses. In practice, the device can - // still send reports as often as it wants, but for completeness this - // should be implemented eventually. - // - return usb.ack; - }, - .SetProtocol => { - // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 - // The device should switch the format of its reports from the boot - // keyboard/mouse protocol to the format described in its report descriptor, - // or vice versa. - // - // For now, this request is ACKed without doing anything; in practice, - // the OS will reuqest the report protocol anyway, so usually only one format is needed. - // Unless the report format matches the boot protocol exactly (see ReportDescriptorKeyboard), - // our device might not work in a limited BIOS environment. - // - return usb.ack; - }, - .SetReport => { - // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/454 - // This request sends a feature or output report to the device, - // e.g. turning on the caps lock LED. This must be handled in an - // application-specific way, so notify the application code of the event. - // - return usb.ack; - }, - else => {}, - } - }, - else => {}, - } - return usb.nak; - } - - pub fn on_tx_ready(self: *@This(), ep: usb.types.Endpoint.Num) void { - log.debug("tx ready ({t})", .{ep}); - self.tx_ready.store(true, .seq_cst); - } - - pub fn on_rx(self: *@This(), ep: usb.types.Endpoint.Num) void { - log.debug("rx ({t})", .{ep}); - self.rx_ready.store(true, .seq_cst); - } - - pub fn send_report(self: *@This(), report: *const InReport) bool { - if (!self.tx_ready.load(.seq_cst)) return false; - - self.tx_ready.store(false, .seq_cst); - - const len = self.device.ep_writev( - self.descriptor.ep_in.endpoint.num, - &.{std.mem.asBytes(report)}, - ); - - log.debug("sent report {} {any}", .{ len, report }); - - return true; - } - - pub fn receive_report(self: *@This()) ?OutReport { - if (!self.rx_ready.load(.seq_cst)) return null; - - self.rx_ready.store(false, .seq_cst); - - var report: OutReport = undefined; - const ep_num = self.descriptor.ep_out.endpoint.num; - const len = self.device.ep_readv(ep_num, &.{std.mem.asBytes(&report)}); - self.device.ep_listen(ep_num, @intCast(self.descriptor.ep_out.max_packet_size.native())); - - log.debug("received report {} {any}", .{ len, report }); - - return report; - } - }; -} diff --git a/core/src/core/usb/types.zig b/core/src/core/usb/types.zig index 658b3f706..d8e0bf151 100644 --- a/core/src/core/usb/types.zig +++ b/core/src/core/usb/types.zig @@ -1,5 +1,11 @@ const std = @import("std"); -const EndianInt = @import("../mem.zig").EndianInt; +const mem = @import("../mem.zig"); + +/// Little endian integer, unaffected by host endianness. +/// Commonly used in USB descriptors +pub fn LeInt(T: type) type { + return mem.EndianInt(T, .little); +} pub const ClassSubclassProtocol = extern struct { /// Class of device, giving a broad functional area. @@ -402,12 +408,12 @@ pub const SetupPacket = packed struct(u64) { /// conflict. request: u8, /// A simple argument of up to 16 bits, specific to the request. - value: EndianInt(u16, .little), - index: EndianInt(u16, .little), + value: LeInt(u16), + index: LeInt(u16), /// If data will be transferred after this request (in the direction given /// by `request_type`), this gives the number of bytes (OUT) or maximum /// number of bytes (IN). - length: EndianInt(u16, .little), + length: LeInt(u16), pub fn format(self: SetupPacket, writer: *std.Io.Writer) !void { try writer.print("request_type={} request={} value={} index={} length={}", .{ @@ -480,5 +486,8 @@ pub const Version = extern struct { } }; -/// Represents packet length. -pub const Len = u11; +/// Represents physical packet length. +pub const PacketLength = u11; + +/// Deprecated; use `PacketLength`. +pub const Len = PacketLength; diff --git a/drivers/src/base/Digital_IO.zig b/drivers/src/base/Digital_IO.zig index ffda44901..eea8218a9 100644 --- a/drivers/src/base/Digital_IO.zig +++ b/drivers/src/base/Digital_IO.zig @@ -29,7 +29,7 @@ pub const State = enum(u1) { high = 1, pub inline fn invert(state: State) State { - return @as(State, @fromBackingInt(~@backingInt(state))); + return @fromBackingInt(~@backingInt(state)); } pub inline fn value(state: State) u1 { diff --git a/drivers/src/root.zig b/drivers/src/root.zig index b5ec2b2f3..67c19aaf8 100644 --- a/drivers/src/root.zig +++ b/drivers/src/root.zig @@ -106,7 +106,7 @@ pub const time = struct { _, pub fn from_us(us: u64) Absolute { - return @as(Absolute, @fromBackingInt(us)); + return @fromBackingInt(us); } pub fn to_us(abs: Absolute) u64 { @@ -136,7 +136,7 @@ pub const time = struct { _, pub fn from_us(us: u64) Duration { - return @as(Duration, @fromBackingInt(us)); + return @fromBackingInt(us); } pub fn from_ms(ms: u64) Duration { @@ -210,11 +210,11 @@ pub const time = struct { }; pub fn make_timeout(since: Absolute, timeout: Duration) Absolute { - return @as(Absolute, @fromBackingInt(since.to_us() + timeout.to_us())); + return @fromBackingInt(since.to_us() + timeout.to_us()); } pub fn make_timeout_us(since: Absolute, timeout_us: u64) Absolute { - return @as(Absolute, @fromBackingInt(since.to_us() + timeout_us)); + return @fromBackingInt(since.to_us() + timeout_us); } }; diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 0a5cbc99e..1f90d951d 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -11,8 +11,6 @@ const USBD = nrf.usbd.USBD; const clocks = nrf.clocks; const uart = nrf.uart.num(0); -const USB_Serial = usb.drivers.CDC; - pub const panic = microzig.panic; pub const std_options = microzig.std_options(.{ @@ -31,23 +29,16 @@ comptime { var usb_device: USBD = undefined; -// Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) +// Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) var usb_controller: usb.DeviceController(.{ - .bcd_usb = USBD.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USBD.default_vendor_id, - .product = USBD.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USBD.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, - }}, -}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, -}}) = .init; + .device_capabilities = USBD.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, +)}) = .init; pub fn main() !void { board.init(); @@ -97,7 +88,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *usb.drivers.CDC.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -114,7 +105,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial) []const u8 { +pub fn usb_cdc_read(serial: *usb.drivers.CDC.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 717850901..0ab0ebf7c 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -27,122 +27,25 @@ comptime { _ = microzig.export_startup(); } -pub const Modifiers = packed struct(u8) { - lctrl: bool, - lshift: bool, - lalt: bool, - lgui: bool, - rctrl: bool, - rshift: bool, - ralt: bool, - rgui: bool, - - pub const none: @This() = @bitCast(@as(u8, 0)); -}; - -pub const Code = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 - // zig fmt: off - reserved = 0x00, error_roll_over, post_fail, error_undefined, - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, - top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, - enter, escape, delete, tab, space, - @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", - caps_lock, - f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, - print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, - right_arrow, left_arrow, down_arrow, up_arrow, num_lock, - kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, - kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, - kpad_delete, @"non_us_\\", application, power, @"kpad_=", - f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, - // zig fmt: on - _, -}; - -pub const KeyboardInReport = extern struct { - modifiers: Modifiers, - reserved: u8 = 0, - keys: [6]Code, - - comptime { - std.debug.assert(@sizeOf(@This()) == 8); - } - - pub const empty: @This() = .{ .modifiers = .none, .keys = @splat(.reserved) }; -}; - -pub const KeyboardOutReport = packed struct(u8) { - num_lock: bool, - caps_lock: bool, - scroll_lock: bool, - padding: u5 = 0, -}; - -const Keyboard = usb.drivers.hid.InterruptDriver(.{ +const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, -}); + .itf_string = "Boot Keyboard", + .poll_interval = 1, + .report = .boot_keyboard, +}; var usb_device: USBD = undefined; var usb_controller: usb.DeviceController(.{ - .bcd_usb = USBD.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USBD.default_vendor_id, - .product = USBD.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USBD.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { keyboard: Keyboard }, - }}, -}, .{.{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, -}}) = .init; + .device_capabilities = USBD.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ .keyboard = hid_driver_options }, +)}) = .init; pub fn main() !void { board.init(); @@ -159,7 +62,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Code = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const usb.HID_report.Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -173,16 +76,14 @@ pub fn main() !void { idx = 0; } else { std.log.info("report {}", .{idx}); - idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) - drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Code, @splat(.reserved)) }, - ) - else - drivers.keyboard.send_report(&.empty)); + var report = std.mem.zeroes(@TypeOf(drivers.keyboard).ReportIn); + if (idx & 1 == 0 and idx < 2 * message.len) + report.keys[0] = message[@intCast(idx / 2)]; + idx += @intFromBool(drivers.keyboard.send_report(&report)); } if (drivers.keyboard.receive_report()) |report| - board.led1.put(@intFromBool(report.caps_lock)); + board.led1.put(@intFromBool(report.led.caps_lock)); } } } diff --git a/examples/raspberrypi/rp2xxx/build.zig b/examples/raspberrypi/rp2xxx/build.zig index a16987076..08747e494 100644 --- a/examples/raspberrypi/rp2xxx/build.zig +++ b/examples/raspberrypi/rp2xxx/build.zig @@ -86,6 +86,7 @@ pub fn build(b: *std.Build) void { .{ .name = "stepper_driver_dumb", .file = "src/stepper_driver_dumb.zig" }, .{ .name = "usb-hid", .file = "src/usb_hid.zig" }, .{ .name = "usb-cdc", .file = "src/usb_cdc.zig" }, + .{ .name = "usb-raw-echo", .file = "src/usb_raw_echo.zig" }, .{ .name = "dma", .file = "src/dma.zig" }, .{ .name = "cyw43", .file = "src/cyw43.zig" }, .{ .name = "cyw43-blinky", .file = "src/cyw43/blinky.zig" }, diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index edb307f0b..a099b9cc2 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -8,29 +8,23 @@ 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; var usb_device: USB_Device = undefined; -// Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) and +// Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) 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; + .device_capabilities = USB_Device.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ + .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" }, + .reset = rp2xxx.usb.ResetDriver(null, 0){}, + }, +)}) = .init; pub const std_options = microzig.std_options(.{ .log_level = .debug, @@ -105,7 +99,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *usb.drivers.CDC.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -122,7 +116,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial) []const u8 { +pub fn usb_cdc_read(serial: *usb.drivers.CDC.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 90bc4d18e..4c07c3cca 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -20,123 +20,28 @@ comptime { _ = microzig.export_startup(); } -pub const Modifiers = packed struct(u8) { - lctrl: bool, - lshift: bool, - lalt: bool, - lgui: bool, - rctrl: bool, - rshift: bool, - ralt: bool, - rgui: bool, - - pub const none: @This() = @bitCast(@as(u8, 0)); -}; - -pub const Code = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 - // zig fmt: off - reserved = 0x00, error_roll_over, post_fail, error_undefined, - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, - top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, - enter, escape, delete, tab, space, - @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", - caps_lock, - f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, - print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, - right_arrow, left_arrow, down_arrow, up_arrow, num_lock, - kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, - kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, - kpad_delete, @"non_us_\\", application, power, @"kpad_=", - f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, - // zig fmt: on - _, -}; - -pub const KeyboardInReport = extern struct { - modifiers: Modifiers, - reserved: u8 = 0, - keys: [6]Code, - - comptime { - std.debug.assert(@sizeOf(@This()) == 8); - } - - pub const empty: @This() = .{ .modifiers = .none, .keys = @splat(.reserved) }; -}; - -pub const KeyboardOutReport = packed struct(u8) { - num_lock: bool, - caps_lock: bool, - scroll_lock: bool, - padding: u5 = 0, -}; - -const Keyboard = usb.drivers.hid.InterruptDriver(.{ +const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, -}); + .itf_string = "Boot Keyboard", + .poll_interval = 1, + .report = .boot_keyboard, +}; var usb_device: USB_Device = undefined; 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 { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, - }}, -}, .{.{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, - .reset = "", -}}) = .init; + .device_capabilities = USB_Device.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ + .keyboard = hid_driver_options, + .reset = rp2xxx.usb.ResetDriver(null, 0){}, + }, +)}) = .init; pub fn panic(message: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn { std.log.err("panic: {s}", .{message}); @@ -165,7 +70,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Code = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const usb.HID_report.Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -178,16 +83,14 @@ pub fn main() !void { old = new; idx = 0; } else { - idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) - drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Code, @splat(.reserved)) }, - ) - else - drivers.keyboard.send_report(&.empty)); + var report = std.mem.zeroes(@TypeOf(drivers.keyboard).ReportIn); + if (idx & 1 == 0 and idx < 2 * message.len) + report.keys[0] = message[@intCast(idx / 2)]; + idx += @intFromBool(drivers.keyboard.send_report(&report)); } if (drivers.keyboard.receive_report()) |report| - pins.led.put(@intFromBool(report.caps_lock)); + pins.led.put(@intFromBool(report.led.caps_lock)); } } } diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig new file mode 100644 index 000000000..baa00ed2b --- /dev/null +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -0,0 +1,82 @@ +const std = @import("std"); +const microzig = @import("microzig"); + +const rp2xxx = microzig.hal; +const time = rp2xxx.time; +const usb = microzig.core.usb; +// Port-specific type which implements the DeviceInterface interface, used by the USB core to +// read from/write to the peripheral. +const USB_Device = rp2xxx.usb.Polled(.{}); + +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(.{ + .device_triple = .unspecified, + .bcd_device = .v1_00, + .serial = "someserial", + .device_capabilities = USB_Device.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ + .echo = usb.drivers.EchoExample{}, + .reset = rp2xxx.usb.ResetDriver(null, 0){}, + }, +)}) = .init; + +pub const std_options = microzig.std_options(.{ + .log_level = .debug, + .log_scope_levels = &.{ + .{ .scope = .usb_dev, .level = .warn }, + .{ .scope = .usb_ctrl, .level = .warn }, + .{ .scope = .usb_echo, .level = .warn }, + }, + .logFn = rp2xxx.uart.log, +}); + +comptime { + _ = microzig.export_startup(); +} + +pub fn panic(message: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn { + std.log.err("panic: {s}", .{message}); + @breakpoint(); + while (true) {} +} + +const pin_config: rp2xxx.pins.GlobalConfiguration = .{ + .GPIO25 = .{ .name = "led", .direction = .out }, +}; + +pub fn main() !void { + const pins = pin_config.apply(); + + const uart = rp2xxx.uart.instance.num(0); + uart.apply(.{ + .clock_config = rp2xxx.clock_config, + }); + rp2xxx.uart.init_logger(uart); + + pins.led.put(1); + + // Then initialize the USB device using the configuration defined above + usb_device = .init(); + + var old: u64 = time.get_time_since_boot().to_us(); + var new: u64 = 0; + + while (true) { + // You can now poll for USB events + usb_device.poll(&usb_controller); + + // Ensure that the host as finished enumerating our USB device + if (usb_controller.drivers()) |_| { + new = time.get_time_since_boot().to_us(); + if (new - old > 500_000) { + old = new; + pins.led.toggle(); + } + } + } +} diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 0854fdef2..5e27663cf 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -23,6 +23,8 @@ comptime { _ = microzig.export_startup(); } +const USB_Device = hal.usb.Polled(board.usb_setup, .{}); + const USB_Controller = usb.DeviceController(.{ .bcd_usb = .v2_00, .device_triple = .unspecified, @@ -30,17 +32,13 @@ const USB_Controller = usb.DeviceController(.{ .product = .{ .id = 0x0001, .str = board.product_string }, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = hal.usb.max_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, - }}, -}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, -}}); - -pub var usb_dev: hal.usb.Polled(board.usb_setup, .{}) = undefined; + .device_capabilities = USB_Device.device_capabilities, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, +)}); + +pub var usb_dev: USB_Device = undefined; var usb_controller: USB_Controller = .init; @@ -90,7 +88,7 @@ var usb_tx_buff: [1024]u8 = undefined; // Transfer data to host // NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { const text = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; var write_buff = text; while (write_buff.len > 0) { @@ -106,7 +104,7 @@ var usb_rx_buff: [1024]u8 = undefined; // Receive data from host // NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every read operation pub fn usb_cdc_read( - serial: *USB_Serial, + serial: *USB_Serial.Runtime, ) []const u8 { var total_read: usize = 0; var read_buff: []u8 = usb_rx_buff[0..]; diff --git a/port/espressif/esp/src/hal/gpio.zig b/port/espressif/esp/src/hal/gpio.zig index cb6a643fa..889ae753a 100644 --- a/port/espressif/esp/src/hal/gpio.zig +++ b/port/espressif/esp/src/hal/gpio.zig @@ -218,7 +218,7 @@ pub const Mask = enum(u22) { pub fn num(n: u5) Pin { std.debug.assert(n < 22); - return @as(Pin, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const Pin = enum(u5) { diff --git a/port/nordic/nrf5x/src/hal/i2c.zig b/port/nordic/nrf5x/src/hal/i2c.zig index 44c8d9edb..d5f2b2aee 100644 --- a/port/nordic/nrf5x/src/hal/i2c.zig +++ b/port/nordic/nrf5x/src/hal/i2c.zig @@ -38,7 +38,7 @@ pub const AddressError = drivers.I2C_Device.Address.Error; pub const Error = drivers.I2C_Device.Error || error{Overrun}; pub fn num(n: u1) I2C { - return @as(I2C, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const I2C = enum(u1) { diff --git a/port/nordic/nrf5x/src/hal/i2cdma.zig b/port/nordic/nrf5x/src/hal/i2cdma.zig index 0045ef7c6..4af21ba96 100644 --- a/port/nordic/nrf5x/src/hal/i2cdma.zig +++ b/port/nordic/nrf5x/src/hal/i2cdma.zig @@ -46,7 +46,7 @@ pub const Error = drivers.I2C_Device.Error || error{ /// Create an I2C instance from a peripheral number (0 or 1). pub fn num(n: u1) I2C { - return @as(I2C, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const I2C = enum(u1) { diff --git a/port/nordic/nrf5x/src/hal/spim.zig b/port/nordic/nrf5x/src/hal/spim.zig index f5553537e..51a81b6ce 100644 --- a/port/nordic/nrf5x/src/hal/spim.zig +++ b/port/nordic/nrf5x/src/hal/spim.zig @@ -59,7 +59,7 @@ pub const TransactionError = error{ }; pub fn num(n: u2) SPIM { - return @as(SPIM, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const SPIM = enum(u1) { diff --git a/port/nordic/nrf5x/src/hal/usbd.zig b/port/nordic/nrf5x/src/hal/usbd.zig index fa6583410..85d57e92b 100644 --- a/port/nordic/nrf5x/src/hal/usbd.zig +++ b/port/nordic/nrf5x/src/hal/usbd.zig @@ -40,6 +40,8 @@ const EP_Config = struct { }; pub const USBD = struct { + const Self = @This(); + power: PowerState = .detached, bufs_in: [NUM_EP][MAX_PACKET_SIZE]u8 align(4) = @splat(@splat(0)), @@ -50,10 +52,17 @@ pub const USBD = struct { interface: usb.DeviceInterface, - pub const max_supported_packet_size = MAX_PACKET_SIZE; - pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Config.IdStringPair = .{ .id = 0x1209, .str = "pid.codes" }; - pub const default_product_id: usb.Config.IdStringPair = .{ .id = 0x0001, .str = "nRF5x test device" }; + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v1_10, + .max_packet_size0 = MAX_PACKET_SIZE, + .max_packet_size = MAX_PACKET_SIZE, + .default_vendor = .{ .id = 0x1209, .str = "pid.codes" }, + .default_product = .{ .id = 0x0001, .str = "nRF5x test device" }, + }; + + comptime { + usb.validate_device(Self); + } const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, @@ -63,8 +72,6 @@ pub const USBD = struct { .set_address = set_address, }; - const Self = @This(); - pub fn init() Self { peripherals.USBD.USBPULLUP.write_raw(0); peripherals.USBD.ENABLE.write_raw(0); @@ -263,7 +270,7 @@ pub const USBD = struct { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []const u8, - ) usb.types.Len { + ) usb.types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); log.debug("ep_writev {t}: ({} bytes) {X} ({s})", .{ ep_num, data[0].len, data[0], data[0] }); @@ -283,7 +290,7 @@ pub const USBD = struct { scratch_slice = scratch_slice[len..]; } - const len: usb.types.Len = @intCast(scratch_cap - scratch_slice.len); + const len: usb.types.PacketLength = @intCast(scratch_cap - scratch_slice.len); // Prepare DMA transfer peripherals.USBD.EPIN[i].PTR.write_raw(@intFromPtr(scratch)); @@ -323,7 +330,7 @@ pub const USBD = struct { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []u8, - ) usb.types.Len { + ) usb.types.PacketLength { var total_len: usize = data[0].len; for (data[1..]) |d| total_len += d.len; log.debug("ep_readv {t}: ({} bytes)", .{ ep_num, total_len }); @@ -362,7 +369,7 @@ pub const USBD = struct { fn ep_listen( _: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, - len: usb.types.Len, + len: usb.types.PacketLength, ) void { log.debug("ep_listen {t}: ({} bytes)", .{ ep_num, len }); diff --git a/port/raspberrypi/rp2xxx/src/hal/adc.zig b/port/raspberrypi/rp2xxx/src/hal/adc.zig index 19e3b5754..a091dcca6 100644 --- a/port/raspberrypi/rp2xxx/src/hal/adc.zig +++ b/port/raspberrypi/rp2xxx/src/hal/adc.zig @@ -19,7 +19,7 @@ pub const Error = error{ /// temp_sensor is not valid because you can refer to it by name. pub fn input(n: u2) Input { - return @as(Input, @fromBackingInt(n)); + return @fromBackingInt(n); } /// Enable the ADC controller. @@ -81,7 +81,7 @@ pub fn select_input(in: Input) void { /// Get the currently selected analog input. pub fn get_selected_input() Input { const cs = ADC.SC.read(); - return @as(Input, @fromBackingInt(cs.AINSEL)); + return @fromBackingInt(cs.AINSEL); } /// For RP2040 and RP2350A, the values are: diff --git a/port/raspberrypi/rp2xxx/src/hal/i2c.zig b/port/raspberrypi/rp2xxx/src/hal/i2c.zig index 97314ebd9..aad0c0a11 100644 --- a/port/raspberrypi/rp2xxx/src/hal/i2c.zig +++ b/port/raspberrypi/rp2xxx/src/hal/i2c.zig @@ -158,11 +158,12 @@ test "i2c.translate_baudrate" { } pub const instance = struct { - pub const I2C0: I2C = @as(I2C, @fromBackingInt(0)); - pub const I2C1: I2C = @as(I2C, @fromBackingInt(1)); pub fn num(instance_number: u1) I2C { - return @as(I2C, @fromBackingInt(instance_number)); + return @fromBackingInt(instance_number); } + + pub const I2C0 = num(0); + pub const I2C1 = num(1); }; /// An API for interacting with the RP2040's I2C driver. diff --git a/port/raspberrypi/rp2xxx/src/hal/pio.zig b/port/raspberrypi/rp2xxx/src/hal/pio.zig index 3287ad962..bd511d2d3 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pio.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pio.zig @@ -37,7 +37,7 @@ pub fn num(n: u2) Pio { }, } - return @as(Pio, @fromBackingInt(@intCast(n))); + return @fromBackingInt(@intCast(n)); } pub const Pio = chip_specific.Pio; diff --git a/port/raspberrypi/rp2xxx/src/hal/pio/common.zig b/port/raspberrypi/rp2xxx/src/hal/pio/common.zig index dfa5a0102..34dee469a 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pio/common.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pio/common.zig @@ -122,7 +122,7 @@ pub fn PioImpl(EnumType: type, chip: Chip) type { return struct { pub fn get_instruction_memory(self: EnumType) *volatile [32]u32 { const regs = self.get_regs(); - return @as(*volatile [32]u32, @ptrCast(®s.INSTR_MEM0)); + return @ptrCast(®s.INSTR_MEM0); } pub fn can_add_program_at_offset(self: EnumType, program: Program, offset: u5) bool { diff --git a/port/raspberrypi/rp2xxx/src/hal/pwm.zig b/port/raspberrypi/rp2xxx/src/hal/pwm.zig index 169d2e7fe..3c6ceb341 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pwm.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pwm.zig @@ -12,7 +12,7 @@ fn get_regs(slice: u32) *volatile Regs { @import("std").debug.assert(slice < if (has_rp2350b) 12 else 8); const PwmType = microzig.chip.types.peripherals.PWM; const reg_diff = comptime @offsetOf(PwmType, "CH1_CSR") - @offsetOf(PwmType, "CH0_CSR"); - return @as(*volatile Regs, @ptrFromInt(@intFromPtr(PWM) + reg_diff * slice)); + return @ptrFromInt(@intFromPtr(PWM) + reg_diff * slice); } pub const Channel = enum(u1) { a, b }; diff --git a/port/raspberrypi/rp2xxx/src/hal/spi.zig b/port/raspberrypi/rp2xxx/src/hal/spi.zig index 916beb452..6ac9c2cf4 100644 --- a/port/raspberrypi/rp2xxx/src/hal/spi.zig +++ b/port/raspberrypi/rp2xxx/src/hal/spi.zig @@ -58,11 +58,12 @@ pub const Config = struct { }; pub const instance = struct { - pub const SPI0: SPI = @as(SPI, @fromBackingInt(0)); - pub const SPI1: SPI = @as(SPI, @fromBackingInt(1)); pub fn num(instance_number: u1) SPI { - return @as(SPI, @fromBackingInt(instance_number)); + return @fromBackingInt(instance_number); } + + pub const SPI0 = num(0); + pub const SPI1 = num(1); }; pub const ConfigError = error{ diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 517cfe23a..609cb0cb4 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -46,7 +46,7 @@ const rp2xxx_buffers = struct { fn data_offset(ep_data_buffer: []u8) u16 { const buf_base = @intFromPtr(&ep_data_buffer[0]); const dpram_base = @intFromPtr(peripherals.USB_DPRAM); - return @as(u16, @intCast(buf_base - dpram_base)); + return @intCast(buf_base - dpram_base); } }; @@ -84,20 +84,29 @@ pub fn Polled(config: Config) type { } return struct { - pub const max_supported_packet_size = 64; - pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Config.IdStringPair = .{ .id = 0x2E8A, .str = "Raspberry Pi" }; - pub const default_product_id: usb.Config.IdStringPair = switch (chip) { - .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, - .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v1_10, + .max_packet_size0 = 64, + .max_packet_size = 64, + .default_vendor = .{ .id = 0x2E8A, .str = "Raspberry Pi" }, + .default_product = switch (chip) { + .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, + .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, + }, + .supports_remote_wakeup = true, }; + comptime { + usb.validate_device(@This()); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, .ep_listen = ep_listen, .ep_open = ep_open, .set_address = set_address, + .signal_resume = signal_resume, }; endpoints: [config.max_endpoints_count][2]HardwareEndpointData, @@ -173,6 +182,30 @@ pub fn Polled(config: Config) type { set_address(&self.interface, 0); controller.on_bus_reset(&self.interface); } + + // Has the suspend state changed? + if (ints.DEV_SUSPEND != 0) { + const suspended = peripherals.USB.SIE_STATUS.read().SUSPENDED != 0; + + peripherals.USB.SIE_STATUS.write(.{ .SUSPENDED = 1 }); + + if (suspended) { + log.debug("-- bus suspended --", .{}); + controller.on_suspend(&self.interface); + } else { + log.debug("-- bus resumed --", .{}); + controller.on_resume(&self.interface); + } + } + + // Has the host signaled a resume? + if (ints.DEV_RESUME_FROM_HOST != 0) { + log.debug("-- resume signaled by host --", .{}); + + peripherals.USB.SIE_STATUS.write(.{ .RESUME = 1 }); + + controller.on_resume(&self.interface); + } } pub fn init() @This() { @@ -235,6 +268,10 @@ pub fn Polled(config: Config) type { .BUS_RESET = 1, // We've gotten a setup request on EP0 .SETUP_REQ = 1, + // The suspend state has changed (entering or leaving suspend) + .DEV_SUSPEND = 1, + // The host has signaled a resume + .DEV_RESUME_FROM_HOST = 1, }); var self: @This() = .{ @@ -246,15 +283,15 @@ pub fn Polled(config: Config) type { @memset(std.mem.asBytes(&self.endpoints), 0); // Set up endpoints. - self.interface.ep_open(&.control(.in(.ep0), max_supported_packet_size)); - self.interface.ep_open(&.control(.out(.ep0), max_supported_packet_size)); + self.interface.ep_open(&.control(.in(.ep0), device_capabilities.max_packet_size)); + self.interface.ep_open(&.control(.out(.ep0), device_capabilities.max_packet_size)); // Present full-speed device by enabling pullup on DP. This is the point // where the host will notice our presence. peripherals.USB.SIE_CTRL.modify(.{ .PULLUP_EN = 1 }); // Listen for ACKs - self.interface.ep_listen(.ep0, max_supported_packet_size); + self.interface.ep_listen(.ep0, device_capabilities.max_packet_size); return self; } @@ -268,7 +305,7 @@ pub fn Polled(config: Config) type { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []const u8, - ) usb.types.Len { + ) usb.types.PacketLength { log.debug("writev {t} {}: {any}", .{ ep_num, data[0].len, data[0] }); const self: *@This() = @fieldParentPtr("interface", itf); @@ -283,7 +320,7 @@ pub fn Polled(config: Config) type { hw_buf = hw_buf[len..]; } - const len: usb.types.Len = @intCast(ep.data_buffer.len - hw_buf.len); + const len: usb.types.PacketLength = @intCast(ep.data_buffer.len - hw_buf.len); var bufctrl = bufctrl_ptr.read(); assert(bufctrl.AVAILABLE_0 == 0); @@ -314,7 +351,7 @@ pub fn Polled(config: Config) type { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []u8, - ) usb.types.Len { + ) usb.types.PacketLength { var total_len: usize = data[0].len; for (data[1..]) |d| total_len += d.len; log.debug("readv {t} {}", .{ ep_num, total_len }); @@ -340,7 +377,7 @@ pub fn Polled(config: Config) type { fn ep_listen( itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, - len: usb.types.Len, + len: usb.types.PacketLength, ) void { log.debug("listen {t} {}", .{ ep_num, len }); @@ -375,6 +412,17 @@ pub fn Polled(config: Config) type { peripherals.USB.ADDR_ENDP.write(.{ .ADDRESS = addr }); } + /// Device-initiated remote wakeup: signal a resume to the host by + /// driving the bus into K state. + fn signal_resume(_: *usb.DeviceInterface) usb.RemoteWakeupError!void { + comptime assert(device_capabilities.supports_remote_wakeup); + + if (peripherals.USB.SIE_STATUS.read().SUSPENDED == 0) + return error.NotSuspended; + + peripherals.USB.SIE_CTRL.modify(.{ .RESUME = 1 }); + } + /// On the RP2350 @memcpy uses unaligned accesses, /// which only work on SRAM and fault on peripheral memory. fn dpram_memcpy(dst: []u8, src: []const u8) void { @@ -411,7 +459,7 @@ pub fn Polled(config: Config) type { const ep_hard = self.hardware_endpoint_get_by_address(ep); - assert(desc.max_packet_size.native() <= max_supported_packet_size); + assert(desc.max_packet_size.native() <= device_capabilities.max_packet_size); buffer_control[@backingInt(ep.num)].get(ep.dir).modify(.{ .PID_0 = 1 }); @@ -446,39 +494,16 @@ pub fn Polled(config: Config) type { } pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type { - return struct { - const log_drv = std.log.scoped(.pico_reset); + const log_drv = std.log.scoped(.pico_reset); - pub const Descriptor = extern struct { - reset_interface: usb.descriptor.Interface, - - pub fn create( - alloc: *usb.DescriptorAllocator, - _: usb.types.Len, - interface_str: []const u8, - ) usb.DescriptorCreateResult(@This()) { - return .{ .descriptor = .{ .reset_interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 0, - .interface_triple = .from( - .VendorSpecific, - @fromBackingInt(0x00), - @fromBackingInt(0x01), - ), - .interface_s = alloc.string(interface_str), - } } }; - } - }; + const Descriptor = extern struct { + reset_interface: usb.descriptor.Interface, + }; - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { - _ = desc; - _ = device; - self.* = .{}; - } + const Runtime = struct { + pub fn init(_: *@This(), _: anytype, _: *const Descriptor, _: *usb.DeviceInterface) void {} - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - _ = self; + pub fn class_request(_: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { switch (setup.request) { 0x01 => { const value = setup.value.native(); @@ -500,4 +525,29 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type return usb.ack; } }; + + return struct { + itf_string: []const u8 = "", + + pub fn driver_info( + self: @This(), + comptime _: usb.DeviceCapabilities, + alloc: *usb.DescriptorAllocator, + ) usb.DriverInfo(Descriptor) { + return .{ + .Runtime = Runtime, + .descriptor = .{ .reset_interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 0, + .interface_triple = .from( + .VendorSpecific, + @fromBackingInt(0x00), + @fromBackingInt(0x01), + ), + .interface_s = alloc.string(self.itf_string), + } }, + }; + } + }; } diff --git a/port/stmicro/stm32/src/hals/STM32F407.zig b/port/stmicro/stm32/src/hals/STM32F407.zig index b1b802cf7..93dd5643c 100644 --- a/port/stmicro/stm32/src/hals/STM32F407.zig +++ b/port/stmicro/stm32/src/hals/STM32F407.zig @@ -120,7 +120,7 @@ pub const gpio = struct { pub fn read(comptime pin: type) microzig.gpio.State { const idr_reg = pin.gpio_port.IDR; const reg_value = @field(idr_reg.read(), "IDR" ++ pin.suffix); // TODO extract to getRegField()? - return @as(microzig.gpio.State, @fromBackingInt(reg_value)); + return @fromBackingInt(reg_value); } pub fn write(comptime pin: type, state: microzig.gpio.State) void { @@ -355,7 +355,7 @@ pub fn Uart(comptime index: usize, comptime pins: microzig.uart.Pins) type { pub fn rx(self: Self) u8 { while (!self.can_read()) {} // Wait till the data is received const data_with_parity_bit: u9 = @field(peripherals, usart_name).DR.read(); - return @as(u8, @intCast(data_with_parity_bit & self.parity_read_mask)); + return @intCast(data_with_parity_bit & self.parity_read_mask); } }; } diff --git a/port/stmicro/stm32/src/hals/common/uart_v3.zig b/port/stmicro/stm32/src/hals/common/uart_v3.zig index b1ff8050a..aa4a77e72 100644 --- a/port/stmicro/stm32/src/hals/common/uart_v3.zig +++ b/port/stmicro/stm32/src/hals/common/uart_v3.zig @@ -165,7 +165,7 @@ pub fn Uart(comptime index: UART_Type) type { pub fn rx(self: Self) u8 { while (!self.can_read()) {} // Wait till the data is received const data_with_parity_bit: u9 = regs.RDR.read().RDR; - return @as(u8, @intCast(data_with_parity_bit & self.read_mask())); + return @intCast(data_with_parity_bit & self.read_mask()); } fn writer_fn(self: *Self, buffer: []const u8) error{}!usize { diff --git a/port/wch/ch32v/src/hals/usbd.zig b/port/wch/ch32v/src/hals/usbd.zig index 910d433ad..fde747a00 100644 --- a/port/wch/ch32v/src/hals/usbd.zig +++ b/port/wch/ch32v/src/hals/usbd.zig @@ -327,6 +327,16 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, // Is this correct? + .max_packet_size0 = 64, + .max_packet_size = 64, + }; + + comptime { + usb.validate_device(Self); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -666,7 +676,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { } } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.debug("ep_listen ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -696,7 +706,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { Epr.set_stat_rx(ep_i, .valid); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const ep_i: u4 = epn(ep_num); const st_out = self.st(ep_num, .out); @@ -727,7 +737,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { log.debug("ep_writev called for ep{} with {} chunks", .{ ep_num, vec.len }); const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); diff --git a/port/wch/ch32v/src/hals/usbfs.zig b/port/wch/ch32v/src/hals/usbfs.zig index 9ebf31670..fdb7d3f77 100644 --- a/port/wch/ch32v/src/hals/usbfs.zig +++ b/port/wch/ch32v/src/hals/usbfs.zig @@ -10,9 +10,6 @@ const peripherals = microzig.chip.peripherals; const usb = microzig.core.usb; const types = usb.types; const descriptor = usb.descriptor; - -pub const max_packet_size: u11 = 64; - pub const USB_MAX_ENDPOINTS_COUNT = 8; const max_buffer_pool_size = USB_MAX_ENDPOINTS_COUNT * 2 * 64 + 64; @@ -156,6 +153,16 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, // Is this correct? + .max_packet_size0 = 64, + .max_packet_size = 64, + }; + + comptime { + usb.validate_device(Self); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -186,13 +193,13 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { // EP0 is required; open OUT then IN (or vice versa), we will share buffer. self.interface.ep_open(&.{ .endpoint = .out(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); self.interface.ep_open(&.{ .endpoint = .in(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); @@ -457,7 +464,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.debug("ep_listen ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -489,7 +496,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_rx_ctrl(ep_i, RES_ACK, current_rx_tog(ep_i), false); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const st_out = self.st(ep_num, .out); @@ -514,10 +521,10 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } // Driver is responsible for re-arming via ep_listen(). - return @as(types.Len, @intCast(copied)); + return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { log.debug("ep_writev called for ep{} with {} chunks", .{ ep_num, vec.len }); const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); @@ -549,7 +556,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_tx_ctrl(ep_i, RES_ACK, current_tx_tog(ep_i), false); // For ZLP ACK, usb.DeviceInterface.ep_ack() expects ep_writev() returns 0. - return @as(types.Len, @intCast(w)); + return @intCast(w); } // ---- HW init --------------------------------------------------------- diff --git a/port/wch/ch32v/src/hals/usbhs.zig b/port/wch/ch32v/src/hals/usbhs.zig index a1ef04ccc..c6c1077e4 100644 --- a/port/wch/ch32v/src/hals/usbhs.zig +++ b/port/wch/ch32v/src/hals/usbhs.zig @@ -11,8 +11,6 @@ const usb = microzig.core.usb; const types = usb.types; const descriptor = usb.descriptor; -pub const max_packet_size: u11 = 512; - pub const USBHD_MAX_ENDPOINTS_COUNT = 16; const max_buffer_pool_size = USBHD_MAX_ENDPOINTS_COUNT * 2 * 512 + 64; @@ -141,6 +139,16 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, + .max_packet_size0 = 64, + .max_packet_size = 512, + }; + + comptime { + usb.validate_device(Self); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -171,13 +179,13 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { // EP0 is required; open OUT then IN (or vice versa), we will share buffer. self.interface.ep_open(&.{ .endpoint = .out(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); self.interface.ep_open(&.{ .endpoint = .in(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); @@ -522,7 +530,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { log.debug("ep_open completed for ep{}", .{ep_i}); } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.info("ep_listen called for ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -558,7 +566,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_rx_ctrl(ep_i, RES_ACK, current_rx_tog(ep_i), false); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const st_out = self.st(ep_num, .out); @@ -583,10 +591,10 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } // Driver is responsible for re-arming via ep_listen(). - return @as(types.Len, @intCast(copied)); + return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); @@ -619,7 +627,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_tx_ctrl(ep_i, RES_ACK, current_tx_tog(ep_i), false); // For ZLP ACK, usb.DeviceInterface.ep_ack() expects ep_writev() returns 0. - return @as(types.Len, @intCast(w)); + return @intCast(w); } // ---- HW init ---------------------------------------------------------