From c7bfd100979266d03191c8677d6a5c0dad527b1b Mon Sep 17 00:00:00 2001 From: Vesim Date: Mon, 16 Nov 2026 12:32:08 +0100 Subject: [PATCH] feat(usb): Add suspend and resume support Also adds example for rp2xxx. --- core/src/core/usb.zig | 118 +++++++++++++++++- examples/raspberrypi/rp2xxx/build.zig | 1 + .../raspberrypi/rp2xxx/src/usb_suspend.zig | 116 +++++++++++++++++ port/raspberrypi/rp2xxx/src/hal/usb.zig | 41 ++++++ 4 files changed, 272 insertions(+), 4 deletions(-) create mode 100644 examples/raspberrypi/rp2xxx/src/usb_suspend.zig diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 3c4c34704..8db8ebd3c 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -68,6 +68,8 @@ pub const DeviceCapabilities = struct { 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. @@ -83,6 +85,13 @@ pub fn DriverInfo(Descriptor: type) type { }; } +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 { @@ -92,6 +101,7 @@ pub const DeviceInterface = struct { 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, @@ -131,6 +141,11 @@ 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 { + return if (self.vtable.signal_resume) |f| f(self) else error.NotSupported; + } }; pub fn EndpointHandler(Driver: type) type { @@ -171,6 +186,10 @@ pub const Options = struct { serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. 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 { @@ -272,6 +291,10 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { 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() = .{ @@ -280,6 +303,8 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { .tx_slice = null, .driver_data = null, .driver_alloc = undefined, + .remote_wakeup_enabled = false, + .is_suspended = false, }; /// Returns a pointer to the drivers @@ -356,6 +381,56 @@ pub fn DeviceController(options: Options, Configurations: []const type) 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 { @@ -366,21 +441,53 @@ pub fn DeviceController(options: Options, Configurations: []const type) 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: https://github.com/ZigEmbeddedGroup/microzig/issues/1144 + }, // 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: https://github.com/ZigEmbeddedGroup/microzig/issues/1144 + }, + else => return nak, + } + }, else => { log.warn("Unsupported standard request: {}", .{setup.request}); return nak; @@ -440,6 +547,9 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { if (self.driver_data) |*data_old| configurations[0].deinit(device_itf, data_old); + // (Re)configuration disables the remote wakeup feature. + self.remote_wakeup_enabled = false; + self.cfg_num = cfg_num; if (cfg_num == 0) self.driver_data = null diff --git a/examples/raspberrypi/rp2xxx/build.zig b/examples/raspberrypi/rp2xxx/build.zig index 08747e494..c0bf648f4 100644 --- a/examples/raspberrypi/rp2xxx/build.zig +++ b/examples/raspberrypi/rp2xxx/build.zig @@ -87,6 +87,7 @@ pub fn build(b: *std.Build) void { .{ .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 = "usb-suspend", .file = "src/usb_suspend.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_suspend.zig b/examples/raspberrypi/rp2xxx/src/usb_suspend.zig new file mode 100644 index 000000000..e3017a823 --- /dev/null +++ b/examples/raspberrypi/rp2xxx/src/usb_suspend.zig @@ -0,0 +1,116 @@ +const std = @import("std"); +const microzig = @import("microzig"); + +const rp2xxx = microzig.hal; +const time = rp2xxx.time; +const usb = microzig.core.usb; + +const Deadline = microzig.drivers.time.Deadline; + +// 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 handler sfor the picotool-controlled reset (ResetDriver). +var usb_controller: usb.DeviceController(.{ + .device_triple = .unspecified, + .bcd_device = .v1_00, + .serial = "someserial", + .device_capabilities = USB_Device.device_capabilities, + .on_suspend = on_suspend, + .on_resume = on_resume, +}, &.{usb.Configuration( + .{ + .attributes = .{ + .self_powered = false, + // this is required so the usb stack responds to DeviceRemoteWakeup set/clear feature + // from the host + .can_remote_wakeup = true, + }, + .max_current_ma = 50, + }, + .{ + .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, +}); + +pub const panic = microzig.panic; + +comptime { + _ = microzig.export_startup(); +} + +const pin_config = microzig.board.pin_config; + +var wakeup_deadline: ?Deadline = null; +fn on_suspend() void { + // try to wake up the host after 5 seconds. + wakeup_deadline = rp2xxx.time.deadline_in_ms(5 * std.time.ms_per_s); +} + +fn on_resume() void { + wakeup_deadline = null; +} + +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 led_deadline: Deadline = time.deadline_in_ms(500); + + while (true) { + // You can now poll for USB events + usb_device.poll(&usb_controller); + + if (wakeup_deadline) |deadline| { + if (deadline.is_reached_by(rp2xxx.time.get_time_since_boot())) { + // try to wake up the host + usb_controller.remote_wakeup(&usb_device.interface) catch |err| switch (err) { + error.NotSupported => unreachable, + error.NotEnabledByHost => { + std.log.warn("Host didn't enabled remote wakeup", .{}); + // on succesfull remote_wakeup it is guranteed that on_resume will be called + // but in the case of error.NotEnabledByHost let's disable it manually, so we don't spam the host + wakeup_deadline = null; + }, + error.NotConfigured => unreachable, // on_suspend guarantee that the controller is already configured + error.NotSuspended => unreachable, // the deadline is disabled in on_resume, so we whould never hit this + }; + } + } + + if (usb_controller.suspended()) { + // do something when the device is suspended + } + + // Ensure that the host has finished enumerating our USB device + if (usb_controller.drivers()) |_| { + if (led_deadline.is_reached_by(time.get_time_since_boot())) { + led_deadline = time.deadline_in_ms(500); + pins.led.toggle(); + } + } + } +} diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 66c27dd5e..eca973268 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -95,6 +95,7 @@ pub fn Polled(config: Config) type { .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, }, + .supports_remote_wakeup = true, }; comptime { @@ -107,6 +108,7 @@ pub fn Polled(config: Config) type { .ep_listen = ep_listen, .ep_open = ep_open, .set_address = set_address, + .signal_resume = signal_resume, }; endpoints: [config.max_endpoints_count][2]HardwareEndpointData, @@ -182,6 +184,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() { @@ -265,6 +291,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() = .{ @@ -405,6 +435,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 {