usb_stack/device/class/gs_usb.rs
1//! USB GS_USB class — CAN bus adapter protocol.
2//!
3//! Implements the Geschwister Schneider / candleLight USB-CAN protocol used by
4//! the Linux `gs_usb` driver (`drivers/net/can/usb/gs_usb.c`).
5//!
6//! # Protocol overview
7//!
8//! - Interface class: vendor-specific (0xFF).
9//! - Bulk IN / OUT endpoints carry [`GsHostFrame`] packets.
10//! - Vendor control transfers handle configuration (bit timing, mode, etc.).
11//!
12//! # Example
13//!
14//! ```ignore
15//! use my_hal_usb::{UsbBusAllocator, UsbDeviceBuilder};
16//! use my_hal_usb::class::gs_usb::GsUsbClass;
17//! use my_hal_usb::MyBus;
18//!
19//! let alloc = UsbBusAllocator::new(MyBus::new(/* peripheral */));
20//! let mut gs_usb = GsUsbClass::new(&alloc);
21//! let mut dev = UsbDeviceBuilder::new(&alloc, 0x1D50, 0x606F)
22//! .product("candleLight RP2350")
23//! .build();
24//!
25//! loop {
26//! if dev.poll(&mut [&mut gs_usb]) {
27//! // Handle CAN frames via gs_usb.try_recv() / gs_usb.try_send()
28//! }
29//! }
30//! ```
31
32use crate::device::bus::{InterfaceNumber, UsbBus, UsbBusAllocator};
33use crate::device::class::UsbClass;
34use crate::device::control::{ControlIn, ControlOut};
35use crate::device::descriptor::DescriptorWriter;
36use crate::device::endpoint::{EndpointIn, EndpointOut};
37use crate::device::error::{UsbError, UsbResult};
38use crate::request::{Recipient, RequestType};
39
40// ─── Vendor-specific control requests ─────────────────────────────────────────
41
42/// GS_USB vendor control request codes (`bRequest`).
43///
44/// Mirrors the constants used by the Linux `gs_usb` driver and `gs_usb_rs` host library.
45pub mod gs_usb_breq {
46 /// Host frame format version (device→host: 1 byte; host→device: 4 bytes LE).
47 pub const HOST_FORMAT: u8 = 0;
48 /// Set CAN bit timing (host→device, writes `GsDeviceBitTiming`, 20 bytes).
49 pub const BITTIMING: u8 = 1;
50 /// Set CAN controller mode + flags (host→device, writes 8 bytes: u32 mode + u32 flags).
51 pub const MODE: u8 = 2;
52 /// Bus error reporting state (host→device, writes `u32`).
53 pub const BERR: u8 = 3;
54 /// Get bit-timing constraints (device→host, reads `GsDeviceBtConst`, 40 bytes).
55 pub const BT_CONST: u8 = 4;
56 /// Get device configuration (device→host, reads `GsDeviceConfig`, 12 bytes).
57 pub const DEVICE_CONFIG: u8 = 5;
58 /// Get/set timestamp value (device→host reads, host→device writes).
59 pub const TIMESTAMP: u8 = 6;
60 /// Identify device (e.g. blink LED).
61 pub const IDENTIFY: u8 = 7;
62 /// Get user ID (device→host).
63 pub const GET_USER_ID: u8 = 8;
64 /// Set user ID (host→device).
65 pub const SET_USER_ID: u8 = 9;
66 /// Set CAN FD data-phase bit timing (host→device, writes `GsDeviceBitTiming`, 20 bytes).
67 pub const DATA_BITTIMING: u8 = 10;
68 /// Get extended bit-timing constraints incl. CAN FD (device→host, 72 bytes).
69 pub const BT_CONST_EXT: u8 = 11;
70 /// Set termination resistor value (host→device).
71 pub const SET_TERMINATION: u8 = 12;
72 /// Get termination resistor value (device→host).
73 pub const GET_TERMINATION: u8 = 13;
74 /// Get CAN controller state + error counters (device→host, 12 bytes).
75 pub const GET_STATE: u8 = 14;
76}
77
78// ─── CAN controller mode constants ────────────────────────────────────────────
79
80/// CAN controller operational mode (`GS_USB_BREQ_MODE` first word).
81pub mod gs_can_mode {
82 /// Reset the CAN controller (no-op if already reset).
83 pub const RESET: u32 = 0;
84 /// Put the CAN controller into operational mode.
85 pub const START: u32 = 1;
86}
87
88// ─── CAN mode flags (used in the second u32 of MODE control OUT) ──────────────
89
90/// Mode flags for the second word of a `GS_USB_BREQ_MODE` request.
91pub mod gs_can_mode_flags {
92 /// Listen-only mode (no ACKs).
93 pub const LISTEN_ONLY: u32 = 1 << 0;
94 /// Loopback mode (for testing).
95 pub const LOOP_BACK: u32 = 1 << 1;
96 /// Triple sampling mode.
97 pub const TRIPLE_SAMPLE: u32 = 1 << 2;
98 /// One-shot mode (no retransmission).
99 pub const ONE_SHOT: u32 = 1 << 3;
100 /// Hardware timestamp mode.
101 pub const HW_TIMESTAMP: u32 = 1 << 4;
102 /// Identify / blink LED.
103 pub const IDENTIFY: u32 = 1 << 5;
104 /// User-ID mode.
105 pub const USER_ID: u32 = 1 << 6;
106 /// Pad packets to max packet size.
107 pub const PAD_PKTS: u32 = 1 << 7;
108 /// CAN-FD mode.
109 pub const FD: u32 = 1 << 8;
110}
111
112// ─── CAN frame flags ──────────────────────────────────────────────────────────
113
114/// Per-frame flags in [`GsCanFrame`](struct.GsCanFrame.html) (same bits as `canfd_frame.flags`).
115pub mod gs_can_flag {
116 /// RX overflow (data lost).
117 pub const OVERFLOW: u8 = 1 << 0;
118 /// CAN-FD frame.
119 pub const FD: u8 = 1 << 1;
120 /// Bit Rate Switch (FD frame transmitted at data bitrate).
121 pub const BRS: u8 = 1 << 2;
122 /// Error State Indicator.
123 pub const ESI: u8 = 1 << 3;
124}
125
126// ─── Wire-format structures (packed C-compatible layout) ──────────────────────
127
128/// A CAN frame as transmitted over USB bulk endpoints.
129///
130/// Wire format used by both the Linux `gs_usb` driver and candleLight firmware.
131/// Must be `#[repr(C, packed)]` for correct binary compatibility.
132#[repr(C, packed)]
133#[derive(Clone, Copy, Debug, Default)]
134pub struct GsHostFrame {
135 /// Echo ID: host→device frames carry a sequence number echoed back in
136 /// device→host TX-complete frames.
137 pub echo_id: u32,
138 /// CAN identifier (11-bit or 29-bit depending on flags).
139 pub can_id: u32,
140 /// Data Length Code (0–8 for classic CAN, 0–64 for CAN-FD).
141 pub can_dlc: u8,
142 /// Channel number (0 for single-channel devices).
143 pub channel: u8,
144 /// Flags (see [`gs_can_flag`]).
145 pub flags: u8,
146 /// Reserved, must be 0.
147 pub reserved: u8,
148 /// CAN data payload (classic CAN uses only first 8 bytes).
149 pub data: [u8; 8],
150}
151
152impl GsHostFrame {
153 /// Size of this struct on the wire.
154 pub const SIZE: usize = core::mem::size_of::<Self>(); // 20 bytes
155
156 /// Create a new frame from its raw bytes.
157 ///
158 /// # Safety
159 ///
160 /// `bytes` must be at least 20 bytes and contain a valid `GsHostFrame`
161 /// wire encoding.
162 pub fn from_bytes(bytes: &[u8]) -> Self {
163 assert!(bytes.len() >= Self::SIZE);
164 // Safety: GsHostFrame is repr(C, packed), plain-old-data.
165 unsafe { core::ptr::read_unaligned(bytes.as_ptr() as *const Self) }
166 }
167
168 /// Serialise this frame into a byte slice.
169 pub fn to_bytes(&self) -> [u8; Self::SIZE] {
170 // Safety: GsHostFrame is repr(C, packed), plain-old-data.
171 unsafe { core::ptr::read_unaligned(self as *const Self as *const [u8; Self::SIZE]) }
172 }
173}
174
175/// View a `repr(C, packed)` struct as a byte slice.
176///
177/// # Safety
178///
179/// `T` must be `repr(C, packed)` with no interior padding.
180/// The returned slice is valid only as long as `t` is alive.
181unsafe fn as_bytes<T: Sized>(t: &T) -> &[u8] {
182 // Safety: caller guarantees T is repr(C, packed) POD.
183 // The slice is constructed from a valid reference.
184 unsafe { core::slice::from_raw_parts((t as *const T).cast::<u8>(), core::mem::size_of::<T>()) }
185}
186
187/// Read a `repr(C, packed)` struct from a byte slice (safe copy version).
188///
189/// Unlike the unsafe reference-based approach, this copies bytes into a
190/// stack-local and returns by value, avoiding alignment UB.
191fn read_packed<T: Copy>(bytes: &[u8]) -> T {
192 assert!(bytes.len() >= core::mem::size_of::<T>());
193 // Safety: we copy size_of::<T>() bytes from a valid slice into a
194 // stack-local that is properly aligned for T (repr(C, packed) has
195 // alignment 1).
196 unsafe { core::ptr::read_unaligned(bytes.as_ptr() as *const T) }
197}
198
199// ─── Device configuration structs ─────────────────────────────────────────────
200
201/// Response to `GS_USB_BREQ_DEVICE_CONFIG`.
202#[repr(C, packed)]
203#[derive(Clone, Copy, Debug, Default)]
204pub struct GsDeviceConfig {
205 /// Reserved (was `icount` in older protocol versions).
206 pub reserved1: u8,
207 /// Reserved.
208 pub reserved2: u8,
209 /// Reserved.
210 pub reserved3: u8,
211 /// Interface count (typically 1).
212 pub icount: u8,
213 /// Firmware version (user-defined).
214 pub sw_version: u32,
215 /// Hardware version (user-defined).
216 pub hw_version: u32,
217}
218
219impl GsDeviceConfig {
220 /// Size of the wire structure in bytes.
221 pub const SIZE: usize = core::mem::size_of::<Self>(); // 12 bytes
222}
223
224/// Response to `GS_USB_BREQ_BT_CONST` — CAN bit-timing constraints.
225#[repr(C, packed)]
226#[derive(Clone, Copy, Debug, Default)]
227pub struct GsDeviceBtConst {
228 /// Feature flags (reserved).
229 pub feature: u32,
230 /// CAN peripheral clock frequency in Hz.
231 pub fclk_can: u32,
232 /// Minimum time segment 1 (in time quanta).
233 pub tseg1_min: u32,
234 /// Maximum time segment 1.
235 pub tseg1_max: u32,
236 /// Minimum time segment 2.
237 pub tseg2_min: u32,
238 /// Maximum time segment 2.
239 pub tseg2_max: u32,
240 /// Maximum Synchronisation Jump Width.
241 pub sjw_max: u32,
242 /// Minimum Baud Rate Prescaler.
243 pub brp_min: u32,
244 /// Maximum Baud Rate Prescaler.
245 pub brp_max: u32,
246 /// BRP increment (usually 1).
247 pub brp_inc: u32,
248}
249
250impl GsDeviceBtConst {
251 /// Size of the wire structure in bytes.
252 pub const SIZE: usize = core::mem::size_of::<Self>(); // 40 bytes
253}
254
255/// Host→device request to set CAN bit timing.
256#[repr(C, packed)]
257#[derive(Clone, Copy, Debug, Default)]
258pub struct GsDeviceBitTiming {
259 /// Propagation segment (time quanta).
260 pub prop_seg: u32,
261 /// Phase segment 1 (time quanta).
262 pub phase_seg1: u32,
263 /// Phase segment 2 (time quanta).
264 pub phase_seg2: u32,
265 /// Synchronisation Jump Width.
266 pub sjw: u32,
267 /// Baud Rate Prescaler.
268 pub brp: u32,
269}
270
271impl GsDeviceBitTiming {
272 /// Size of the wire structure in bytes.
273 pub const SIZE: usize = core::mem::size_of::<Self>(); // 20 bytes
274}
275
276// ─── GsUsbClass ──────────────────────────────────────────────────────────────
277
278/// USB GS_USB class implementing the candleLight / Linux `gs_usb` protocol.
279///
280/// Provides a bidirectional CAN channel via USB bulk endpoints plus
281/// vendor-specific control requests for configuration.
282pub struct GsUsbClass<'a, B: UsbBus> {
283 interface: InterfaceNumber,
284 bulk_in: EndpointIn<'a, B>,
285 bulk_out: EndpointOut<'a, B>,
286 device_config: GsDeviceConfig,
287 bt_const: GsDeviceBtConst,
288 /// Currently requested bit timing.
289 bit_timing: GsDeviceBitTiming,
290 /// CAN controller mode (0 = reset, 1 = start).
291 mode: u32,
292 /// Mode flags (GS_CAN_MODE_FLAGS_*).
293 mode_flags: u32,
294 configured: bool,
295}
296
297impl<'a, B: UsbBus> GsUsbClass<'a, B> {
298 /// Create a new GS_USB class with default device configuration.
299 ///
300 /// Call [`set_device_config`](Self::set_device_config) and
301 /// [`set_bt_const`](Self::set_bt_const) before connecting to set
302 /// device-specific parameters.
303 pub fn new(alloc: &'a UsbBusAllocator<B>) -> Self {
304 let interface = alloc.interface();
305 let bulk_in = alloc.bulk(64);
306 let bulk_out = alloc.bulk::<crate::endpoint::Out>(64);
307
308 Self {
309 interface,
310 bulk_in,
311 bulk_out,
312 device_config: GsDeviceConfig {
313 icount: 1,
314 sw_version: 0x0001_0000,
315 hw_version: 0x0001_0000,
316 ..Default::default()
317 },
318 bt_const: GsDeviceBtConst {
319 // Feature flags: report capabilities the firmware supports.
320 feature: gs_can_mode_flags::LISTEN_ONLY
321 | gs_can_mode_flags::LOOP_BACK
322 | gs_can_mode_flags::ONE_SHOT
323 | gs_can_mode_flags::IDENTIFY,
324 fclk_can: 40_000_000, // 40 MHz – compatible with candleLight / gs_usb_rs
325 tseg1_min: 1,
326 tseg1_max: 256,
327 tseg2_min: 1,
328 tseg2_max: 128,
329 sjw_max: 128,
330 brp_min: 1,
331 brp_max: 1024,
332 brp_inc: 1,
333 },
334 bit_timing: GsDeviceBitTiming::default(),
335 mode: gs_can_mode::RESET,
336 mode_flags: 0,
337 configured: false,
338 }
339 }
340
341 // ── Configuration setters (call before USB enumeration) ──────────────────
342
343 /// Set the device configuration reported to the host.
344 pub fn set_device_config(&mut self, cfg: GsDeviceConfig) {
345 self.device_config = cfg;
346 }
347
348 /// Set the bit-timing constraints reported to the host.
349 pub fn set_bt_const(&mut self, c: GsDeviceBtConst) {
350 self.bt_const = c;
351 }
352
353 // ── Public API ────────────────────────────────────────────────────────────
354
355 /// `true` when the device is configured by the host.
356 pub fn is_configured(&self) -> bool {
357 self.configured
358 }
359
360 /// Current CAN controller mode.
361 pub fn mode(&self) -> u32 {
362 self.mode
363 }
364
365 /// Current mode flags.
366 pub fn mode_flags(&self) -> u32 {
367 self.mode_flags
368 }
369
370 /// Current bit timing parameters.
371 pub fn bit_timing(&self) -> &GsDeviceBitTiming {
372 &self.bit_timing
373 }
374
375 /// Attempt to read a CAN frame from the host (bulk OUT).
376 ///
377 /// Returns `Ok(Some(frame))` when a frame is available,
378 /// `Ok(None)` when no data is waiting, or an error.
379 pub fn try_recv(&self) -> UsbResult<Option<GsHostFrame>> {
380 if !self.configured {
381 return Err(UsbError::InvalidState);
382 }
383 let mut buf = [0u8; GsHostFrame::SIZE];
384 match self.bulk_out.read(&mut buf) {
385 Ok(n) if n == GsHostFrame::SIZE => {
386 let frame = GsHostFrame::from_bytes(&buf);
387 Ok(Some(frame))
388 }
389 Ok(_) => Ok(None), // Short packet — ignore
390 Err(UsbError::WouldBlock) => Ok(None),
391 Err(e) => Err(e),
392 }
393 }
394
395 /// Send a CAN frame to the host (bulk IN).
396 ///
397 /// Returns `Ok(())` on success, or an error (e.g. `WouldBlock` if the
398 /// previous packet hasn't been sent yet).
399 pub fn try_send(&self, frame: &GsHostFrame) -> UsbResult<()> {
400 if !self.configured {
401 return Err(UsbError::InvalidState);
402 }
403 let bytes = frame.to_bytes();
404 self.bulk_in.write(&bytes)?;
405 Ok(())
406 }
407}
408
409// ─── UsbClass<B> implementation ───────────────────────────────────────────────
410
411impl<B: UsbBus> UsbClass<B> for GsUsbClass<'_, B> {
412 fn configuration_descriptors(&self, w: &mut DescriptorWriter) -> UsbResult<()> {
413 // Vendor-specific interface with two bulk endpoints.
414 w.interface(
415 self.interface,
416 2, // IN + OUT bulk
417 0xFF, // bInterfaceClass: vendor-specific
418 0x00, // bInterfaceSubClass
419 0x00, // bInterfaceProtocol
420 )?;
421
422 // Bulk IN endpoint (device→host CAN frames).
423 w.endpoint(
424 self.bulk_in.address(),
425 self.bulk_in.ep_type(),
426 self.bulk_in.max_packet_size(),
427 0, // interval (ignored for bulk)
428 )?;
429
430 // Bulk OUT endpoint (host→device CAN frames).
431 w.endpoint(
432 self.bulk_out.address(),
433 self.bulk_out.ep_type(),
434 self.bulk_out.max_packet_size(),
435 0,
436 )?;
437
438 Ok(())
439 }
440
441 fn control_in(&mut self, xfer: ControlIn<'_, B>) {
442 let req = xfer.request();
443
444 // Only handle vendor requests to this interface.
445 if req.request_type != RequestType::Vendor {
446 return;
447 }
448 // Accept both Interface and Device recipients (candleLight uses both).
449 if req.recipient != Recipient::Interface && req.recipient != Recipient::Device {
450 return;
451 }
452
453 match req.request {
454 gs_usb_breq::HOST_FORMAT => {
455 // Linux driver expects at least version 1.
456 let _ = xfer.accept_with(&[1u8]);
457 }
458 gs_usb_breq::DEVICE_CONFIG => {
459 let raw = unsafe { as_bytes(&self.device_config) };
460 let len = core::cmp::min(raw.len(), req.length as usize);
461 let _ = xfer.accept_with(&raw[..len]);
462 }
463 gs_usb_breq::BT_CONST => {
464 let raw = unsafe { as_bytes(&self.bt_const) };
465 let len = core::cmp::min(raw.len(), req.length as usize);
466 let _ = xfer.accept_with(&raw[..len]);
467 }
468 gs_usb_breq::TIMESTAMP => {
469 // Return zero timestamp (device doesn't provide HW timestamps).
470 let ts: u32 = 0;
471 let raw = unsafe { as_bytes(&ts) };
472 let _ = xfer.accept_with(raw);
473 }
474 gs_usb_breq::GET_USER_ID => {
475 // Return zero (no user ID set).
476 let uid: u32 = 0;
477 let raw = unsafe { as_bytes(&uid) };
478 let _ = xfer.accept_with(raw);
479 }
480 gs_usb_breq::BT_CONST_EXT => {
481 // Device doesn't support CAN-FD; reject gracefully.
482 let _ = xfer.reject();
483 }
484 gs_usb_breq::GET_TERMINATION => {
485 // Return zero (no termination control).
486 let term: u32 = 0;
487 let raw = unsafe { as_bytes(&term) };
488 let _ = xfer.accept_with(raw);
489 }
490 gs_usb_breq::GET_STATE => {
491 // Return CAN state + error counters as 3 × u32.
492 // [state(u32), rx_err_cnt(u32), tx_err_cnt(u32)]
493 let state: [u32; 3] = [
494 match self.mode {
495 gs_can_mode::START => 0, // ERROR_ACTIVE (simplified)
496 _ => 4, // STOPPED
497 },
498 0, // rx error count
499 0, // tx error count
500 ];
501 let raw = unsafe { as_bytes(&state) };
502 let len = core::cmp::min(raw.len(), req.length as usize);
503 let _ = xfer.accept_with(&raw[..len]);
504 }
505 _ => {
506 let _ = xfer.reject();
507 }
508 }
509 }
510
511 fn control_out(&mut self, xfer: ControlOut<'_, B>) {
512 let req = xfer.request();
513
514 if req.request_type != RequestType::Vendor {
515 return;
516 }
517 if req.recipient != Recipient::Interface && req.recipient != Recipient::Device {
518 return;
519 }
520
521 let data = xfer.data();
522
523 match req.request {
524 gs_usb_breq::HOST_FORMAT => {
525 // Host sends byte-order hint (0x0000BEEF LE). Accept silently.
526 let _ = xfer.accept();
527 }
528 gs_usb_breq::BITTIMING => {
529 if data.len() >= GsDeviceBitTiming::SIZE {
530 self.bit_timing = read_packed(&data[..GsDeviceBitTiming::SIZE]);
531 }
532 let _ = xfer.accept();
533 }
534 gs_usb_breq::MODE => {
535 // gs_usb_rs sends DeviceMode: [mode(u32 LE), flags(u32 LE)] = 8 bytes.
536 // Linux kernel sends just mode (u32 LE) = 4 bytes.
537 if data.len() >= 4 {
538 self.mode = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
539 }
540 if data.len() >= 8 {
541 self.mode_flags = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
542 } else {
543 self.mode_flags = 0;
544 }
545 let _ = xfer.accept();
546 }
547 gs_usb_breq::BERR => {
548 // Bus-error reporting: accept the value but implementation
549 // is hardware-specific.
550 let _ = xfer.accept();
551 }
552 gs_usb_breq::TIMESTAMP => {
553 // Host sets timestamp — accept silently.
554 let _ = xfer.accept();
555 }
556 gs_usb_breq::IDENTIFY => {
557 // Blink LED / identify: hardware-specific, accept for now.
558 let _ = xfer.accept();
559 }
560 gs_usb_breq::SET_USER_ID => {
561 // Accept silently (no persistent storage).
562 let _ = xfer.accept();
563 }
564 gs_usb_breq::DATA_BITTIMING => {
565 // CAN-FD data-phase timing: accept but ignore (no FD support).
566 let _ = xfer.accept();
567 }
568 gs_usb_breq::SET_TERMINATION => {
569 // Accept silently (no termination control).
570 let _ = xfer.accept();
571 }
572 _ => {
573 let _ = xfer.reject();
574 }
575 }
576 }
577
578 fn configure(&mut self) {
579 self.configured = true;
580 self.mode = gs_can_mode::RESET;
581 }
582
583 fn deconfigure(&mut self) {
584 self.configured = false;
585 self.mode = gs_can_mode::RESET;
586 }
587
588 fn reset(&mut self) {
589 self.configured = false;
590 self.mode = gs_can_mode::RESET;
591 }
592}