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