rp2040/
usb.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Universal Serial Bus Device for Raspberry Pi Pico
6
7//! Authors: Cosmin Radu <cosmin.radu@wyliodrin.com>
8//!          Teodora Miu <teodora.miu01@gmail.com>
9
10use crate::gpio::RPGpioPin;
11use core::cell::Cell;
12use kernel::hil;
13use kernel::hil::usb::TransferType;
14use kernel::utilities::cells::{OptionalCell, VolatileCell};
15use kernel::utilities::registers::interfaces::{ReadWriteable, Readable, Writeable};
16use kernel::utilities::registers::{register_bitfields, register_structs, ReadWrite};
17use kernel::utilities::StaticRef;
18
19macro_rules! internal_err {
20    [ $( $arg:expr ),+ ] => {
21        panic!($( $arg ),+)
22    };
23}
24
25register_structs! {
26    Ep_ctrl {
27        (0x00 => ep_in_ctrl: ReadWrite<u32, EP_CONTROL::Register>),
28        (0x04 => ep_out_ctrl: ReadWrite<u32, EP_CONTROL::Register>),
29        (0x08 => @END),
30    }
31}
32
33register_structs! {
34    Ep_buf_ctrl {
35        (0x00 => ep_in_buf_ctrl: ReadWrite<u32, EP_BUFFER_CONTROL::Register>),
36        (0x04 => ep_out_buf_ctrl: ReadWrite<u32, EP_BUFFER_CONTROL::Register>),
37        (0x08 => @END),
38    }
39}
40
41register_structs! {
42    /// USB FS/LS controller device registers
43    Usbctrl_DPSRAM {
44        /// Device address and endpoint control
45        (0x00 => setup_h: ReadWrite<u32, SETUP_H::Register>),
46        (0x04 => setup_l: ReadWrite<u32, SETUP_L::Register>),
47        (0x08 => ep_ctrl: [Ep_ctrl; 15]),
48        (0x80 => ep_buf_ctrl: [Ep_buf_ctrl; 16]),
49        (0x100 => ep0_buffer0: [VolatileCell<u8>; 0x40]),
50        (0x140 => optional_ep0_buffer0: [VolatileCell<u8>; 0x40]),
51        (0x180 => buffers: [VolatileCell<u8>; 4096-0x180]),
52        (0x1000 => @END),
53    }
54}
55
56register_structs! {
57    /// USB FS/LS controller device registers
58    Usbctrl_RegsRegisters {
59        /// Device address and endpoint control
60        (0x000 => addr_endp: ReadWrite<u32, ADDR_ENDP::Register>),
61        /// Interrupt endpoint 1. Only valid for HOST mode.
62        (0x004 => addr_endp1: ReadWrite<u32, ADDR_ENDP1::Register>),
63        /// Interrupt endpoint 2. Only valid for HOST mode.
64        (0x008 => addr_endp2: ReadWrite<u32, ADDR_ENDP2::Register>),
65        /// Interrupt endpoint 3. Only valid for HOST mode.
66        (0x00C => addr_endp3: ReadWrite<u32, ADDR_ENDP3::Register>),
67        /// Interrupt endpoint 4. Only valid for HOST mode.
68        (0x010 => addr_endp4: ReadWrite<u32, ADDR_ENDP4::Register>),
69        /// Interrupt endpoint 5. Only valid for HOST mode.
70        (0x014 => addr_endp5: ReadWrite<u32, ADDR_ENDP5::Register>),
71        /// Interrupt endpoint 6. Only valid for HOST mode.
72        (0x018 => addr_endp6: ReadWrite<u32, ADDR_ENDP6::Register>),
73        /// Interrupt endpoint 7. Only valid for HOST mode.
74        (0x01C => addr_endp7: ReadWrite<u32, ADDR_ENDP7::Register>),
75        /// Interrupt endpoint 8. Only valid for HOST mode.
76        (0x020 => addr_endp8: ReadWrite<u32, ADDR_ENDP8::Register>),
77        /// Interrupt endpoint 9. Only valid for HOST mode.
78        (0x024 => addr_endp9: ReadWrite<u32, ADDR_ENDP9::Register>),
79        /// Interrupt endpoint 10. Only valid for HOST mode.
80        (0x028 => addr_endp10: ReadWrite<u32, ADDR_ENDP10::Register>),
81        /// Interrupt endpoint 11. Only valid for HOST mode.
82        (0x02C => addr_endp11: ReadWrite<u32, ADDR_ENDP11::Register>),
83        /// Interrupt endpoint 12. Only valid for HOST mode.
84        (0x030 => addr_endp12: ReadWrite<u32, ADDR_ENDP12::Register>),
85        /// Interrupt endpoint 13. Only valid for HOST mode.
86        (0x034 => addr_endp13: ReadWrite<u32, ADDR_ENDP13::Register>),
87        /// Interrupt endpoint 14. Only valid for HOST mode.
88        (0x038 => addr_endp14: ReadWrite<u32, ADDR_ENDP14::Register>),
89        /// Interrupt endpoint 15. Only valid for HOST mode.
90        (0x03C => addr_endp15: ReadWrite<u32, ADDR_ENDP15::Register>),
91        /// Main control register
92        (0x040 => main_ctrl: ReadWrite<u32, MAIN_CTRL::Register>),
93        /// Set the SOF (Start of Frame) frame number in the host controller.
94        /// The SOF packet is sent every 1ms and the host will increment the
95        /// frame number by 1 each time.
96        (0x044 => sof_wr: ReadWrite<u32, SOF_WR::Register>),
97        /// Read the last SOF (Start of Frame) frame number seen. In device
98        /// mode the last SOF received from the host. In host mode the last
99        /// SOF sent by the host.
100        (0x048 => sof_rd: ReadWrite<u32, SOF_RD::Register>),
101        /// SIE control register
102        (0x04C => sie_ctrl: ReadWrite<u32, SIE_CTRL::Register>),
103        /// SIE status register
104        (0x050 => sie_status: ReadWrite<u32, SIE_STATUS::Register>),
105        /// interrupt endpoint control register
106        (0x054 => int_ep_ctrl: ReadWrite<u32, INT_EP_CTRL::Register>),
107        /// Buffer status register. A bit set here indicates that a buffer has
108        /// completed on the endpoint (if the buffer interrupt is enabled). It
109        /// is possible for 2 buffers to be completed, so clearing the buffer
110        /// status bit may instantly re set it on the next clock cycle.
111        (0x058 => buff_status: ReadWrite<u32, BUFF_STATUS::Register>),
112        /// Which of the double buffers should be handled. Only valid if
113        /// using an interrupt per buffer (i.e. not per 2 buffers). Not valid for
114        /// host interrupt endpoint polling because they are only single
115        /// buffered.
116        (0x05C => buff_cpu_should_handle: ReadWrite<u32, BUFF_CPU_SHOULD_HANDLE::Register>),
117        /// Device only: Can be set to ignore the buffer control register for
118        /// this endpoint in case you would like to revoke a buffer. A NAK
119        /// will be sent for every access to the endpoint until this bit is
120        /// cleared. A corresponding bit in EP_ABORT_DONE is set when it is safe
121        /// to modify the buffer control register.
122        (0x060 => ep_abort: ReadWrite<u32, EP_ABORT::Register>),
123        /// Device only: Used in conjunction with EP_ABORT. Set once an
124        /// endpoint is idle so the programmer knows it is safe to modify the
125        /// buffer control register.
126        (0x064 => ep_abort_done: ReadWrite<u32, EP_ABORT_DONE::Register>),
127        /// Device: this bit must be set in conjunction with the STALL bit in the
128        /// buffer control register to send a STALL on EP0. The device
129        /// controller clears these bits when a SETUP packet is received
130        /// because the USB spec requires that a STALL condition is cleared
131        /// when a SETUP packet is received.
132        (0x068 => ep_stall_arm: ReadWrite<u32, EP_STALL_ARM::Register>),
133        /// Used by the host controller. Sets the wait time in microseconds
134        /// before trying again if the device replies with a NAK.
135        (0x06C => nak_poll: ReadWrite<u32, NAK_POLL::Register>),
136        /// Device: bits are set when the IRQ_ON_NAK or IRQ_ON_STALL bits are
137        /// set. For EP0 this comes from SIE_CTRL. For all other endpoints it
138        /// comes from the endpoint control register.
139        (0x070 => ep_status_stall_nak: ReadWrite<u32, EP_STATUS_STALL_NAK::Register>),
140        /// Where to connect the USB controller. Should be to_phy by default.
141        (0x074 => usb_muxing: ReadWrite<u32, USB_MUXING::Register>),
142        /// Overrides for the power signals in the event that the VBUS
143        /// signals are not hooked up to GPIO. Set the value of the override
144        /// and then the override enable to switch over to the override value.
145        (0x078 => usb_pwr: ReadWrite<u32, USB_PWR::Register>),
146        /// This register allows for direct control of the USB phy. Use in
147        /// conjunction with usbphy_direct_override register to enable each
148        /// override bit.
149        (0x07C => usbphy_direct: ReadWrite<u32, USBPHY_DIRECT::Register>),
150        /// Override enable for each control in usbphy_direct
151        (0x080 => usbphy_direct_override: ReadWrite<u32, USBPHY_DIRECT_OVERRIDE::Register>),
152        /// Used to adjust trim values of USB phy pull down resistors.
153        (0x084 => usbphy_trim: ReadWrite<u32, USBPHY_TRIM::Register>),
154        (0x088 => _reserved0),
155        /// Raw Interrupts
156        (0x08C => intr: ReadWrite<u32, INTR::Register>),
157        /// Interrupt Enable
158        (0x090 => inte: ReadWrite<u32, INTE::Register>),
159        /// Interrupt Force
160        (0x094 => intf: ReadWrite<u32, INTF::Register>),
161        /// Interrupt status after masking & forcing
162        (0x098 => ints: ReadWrite<u32, INTS::Register>),
163        (0x09C => @END),
164    }
165}
166register_bitfields![u32,
167ADDR_ENDP [
168    /// Device endpoint to send data to. Only valid for HOST mode.
169    ENDPOINT OFFSET(16) NUMBITS(4) [],
170    /// In device mode, the address that the device should
171    /// respond to. Set in response to a SET_ADDR setup packet
172    /// from the host. In host mode set to the address of the
173    /// device to communicate with.
174    ADDRESS OFFSET(0) NUMBITS(7) []
175],
176ADDR_ENDP1 [
177    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
178    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
179    /// Direction of the interrupt endpoint. In=0, Out=1
180    INTEP_DIR OFFSET(25) NUMBITS(1) [],
181    /// Endpoint number of the interrupt endpoint
182    ENDPOINT OFFSET(16) NUMBITS(4) [],
183    /// Device address
184    ADDRESS OFFSET(0) NUMBITS(7) []
185],
186ADDR_ENDP2 [
187    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
188    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
189    /// Direction of the interrupt endpoint. In=0, Out=1
190    INTEP_DIR OFFSET(25) NUMBITS(1) [],
191    /// Endpoint number of the interrupt endpoint
192    ENDPOINT OFFSET(16) NUMBITS(4) [],
193    /// Device address
194    ADDRESS OFFSET(0) NUMBITS(7) []
195],
196ADDR_ENDP3 [
197    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
198    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
199    /// Direction of the interrupt endpoint. In=0, Out=1
200    INTEP_DIR OFFSET(25) NUMBITS(1) [],
201    /// Endpoint number of the interrupt endpoint
202    ENDPOINT OFFSET(16) NUMBITS(4) [],
203    /// Device address
204    ADDRESS OFFSET(0) NUMBITS(7) []
205],
206ADDR_ENDP4 [
207    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
208    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
209    /// Direction of the interrupt endpoint. In=0, Out=1
210    INTEP_DIR OFFSET(25) NUMBITS(1) [],
211    /// Endpoint number of the interrupt endpoint
212    ENDPOINT OFFSET(16) NUMBITS(4) [],
213    /// Device address
214    ADDRESS OFFSET(0) NUMBITS(7) []
215],
216ADDR_ENDP5 [
217    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
218    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
219    /// Direction of the interrupt endpoint. In=0, Out=1
220    INTEP_DIR OFFSET(25) NUMBITS(1) [],
221    /// Endpoint number of the interrupt endpoint
222    ENDPOINT OFFSET(16) NUMBITS(4) [],
223    /// Device address
224    ADDRESS OFFSET(0) NUMBITS(7) []
225],
226ADDR_ENDP6 [
227    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
228    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
229    /// Direction of the interrupt endpoint. In=0, Out=1
230    INTEP_DIR OFFSET(25) NUMBITS(1) [],
231    /// Endpoint number of the interrupt endpoint
232    ENDPOINT OFFSET(16) NUMBITS(4) [],
233    /// Device address
234    ADDRESS OFFSET(0) NUMBITS(7) []
235],
236ADDR_ENDP7 [
237    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
238    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
239    /// Direction of the interrupt endpoint. In=0, Out=1
240    INTEP_DIR OFFSET(25) NUMBITS(1) [],
241    /// Endpoint number of the interrupt endpoint
242    ENDPOINT OFFSET(16) NUMBITS(4) [],
243    /// Device address
244    ADDRESS OFFSET(0) NUMBITS(7) []
245],
246ADDR_ENDP8 [
247    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
248    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
249    /// Direction of the interrupt endpoint. In=0, Out=1
250    INTEP_DIR OFFSET(25) NUMBITS(1) [],
251    /// Endpoint number of the interrupt endpoint
252    ENDPOINT OFFSET(16) NUMBITS(4) [],
253    /// Device address
254    ADDRESS OFFSET(0) NUMBITS(7) []
255],
256ADDR_ENDP9 [
257    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
258    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
259    /// Direction of the interrupt endpoint. In=0, Out=1
260    INTEP_DIR OFFSET(25) NUMBITS(1) [],
261    /// Endpoint number of the interrupt endpoint
262    ENDPOINT OFFSET(16) NUMBITS(4) [],
263    /// Device address
264    ADDRESS OFFSET(0) NUMBITS(7) []
265],
266ADDR_ENDP10 [
267    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
268    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
269    /// Direction of the interrupt endpoint. In=0, Out=1
270    INTEP_DIR OFFSET(25) NUMBITS(1) [],
271    /// Endpoint number of the interrupt endpoint
272    ENDPOINT OFFSET(16) NUMBITS(4) [],
273    /// Device address
274    ADDRESS OFFSET(0) NUMBITS(7) []
275],
276ADDR_ENDP11 [
277    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
278    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
279    /// Direction of the interrupt endpoint. In=0, Out=1
280    INTEP_DIR OFFSET(25) NUMBITS(1) [],
281    /// Endpoint number of the interrupt endpoint
282    ENDPOINT OFFSET(16) NUMBITS(4) [],
283    /// Device address
284    ADDRESS OFFSET(0) NUMBITS(7) []
285],
286ADDR_ENDP12 [
287    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
288    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
289    /// Direction of the interrupt endpoint. In=0, Out=1
290    INTEP_DIR OFFSET(25) NUMBITS(1) [],
291    /// Endpoint number of the interrupt endpoint
292    ENDPOINT OFFSET(16) NUMBITS(4) [],
293    /// Device address
294    ADDRESS OFFSET(0) NUMBITS(7) []
295],
296ADDR_ENDP13 [
297    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
298    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
299    /// Direction of the interrupt endpoint. In=0, Out=1
300    INTEP_DIR OFFSET(25) NUMBITS(1) [],
301    /// Endpoint number of the interrupt endpoint
302    ENDPOINT OFFSET(16) NUMBITS(4) [],
303    /// Device address
304    ADDRESS OFFSET(0) NUMBITS(7) []
305],
306ADDR_ENDP14 [
307    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
308    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
309    /// Direction of the interrupt endpoint. In=0, Out=1
310    INTEP_DIR OFFSET(25) NUMBITS(1) [],
311    /// Endpoint number of the interrupt endpoint
312    ENDPOINT OFFSET(16) NUMBITS(4) [],
313    /// Device address
314    ADDRESS OFFSET(0) NUMBITS(7) []
315],
316ADDR_ENDP15 [
317    /// Interrupt EP requires preamble (is a low speed device on a full speed hub)
318    INTEP_PREAMBLE OFFSET(26) NUMBITS(1) [],
319    /// Direction of the interrupt endpoint. In=0, Out=1
320    INTEP_DIR OFFSET(25) NUMBITS(1) [],
321    /// Endpoint number of the interrupt endpoint
322    ENDPOINT OFFSET(16) NUMBITS(4) [],
323    /// Device address
324    ADDRESS OFFSET(0) NUMBITS(7) []
325],
326MAIN_CTRL [
327    /// Reduced timings for simulation
328    SIM_TIMING OFFSET(31) NUMBITS(1) [],
329    /// Device mode = 0, Host mode = 1
330    HOST_NDEVICE OFFSET(1) NUMBITS(1) [],
331    /// Enable controller
332    CONTROLLER_EN OFFSET(0) NUMBITS(1) []
333],
334SOF_WR [
335
336    COUNT OFFSET(0) NUMBITS(11) []
337],
338SOF_RD [
339
340    COUNT OFFSET(0) NUMBITS(11) []
341],
342SIE_CTRL [
343    /// Device: Set bit in EP_STATUS_STALL_NAK when EP0 sends a STALL
344    EP0_INT_STALL OFFSET(31) NUMBITS(1) [],
345    /// Device: EP0 single buffered = 0, double buffered = 1
346    EP0_DOUBLE_BUF OFFSET(30) NUMBITS(1) [],
347    /// Device: Set bit in BUFF_STATUS for every buffer completed on EP0
348    EP0_INT_1BUF OFFSET(29) NUMBITS(1) [],
349    /// Device: Set bit in BUFF_STATUS for every 2 buffers completed on EP0
350    EP0_INT_2BUF OFFSET(28) NUMBITS(1) [],
351    /// Device: Set bit in EP_STATUS_STALL_NAK when EP0 sends a NAK
352    EP0_INT_NAK OFFSET(27) NUMBITS(1) [],
353    /// Direct bus drive enable
354    DIRECT_EN OFFSET(26) NUMBITS(1) [],
355    /// Direct control of DP
356    DIRECT_DP OFFSET(25) NUMBITS(1) [],
357    /// Direct control of DM
358    DIRECT_DM OFFSET(24) NUMBITS(1) [],
359    /// Power down bus transceiver
360    TRANSCEIVER_PD OFFSET(18) NUMBITS(1) [],
361    /// Device: Pull-up strength (0=1K2, 1=2k3)
362    RPU_OPT OFFSET(17) NUMBITS(1) [],
363    /// Device: Enable pull up resistor
364    PULLUP_EN OFFSET(16) NUMBITS(1) [],
365    /// Host: Enable pull down resistors
366    PULLDOWN_EN OFFSET(15) NUMBITS(1) [],
367    /// Host: Reset bus
368    RESET_BUS OFFSET(13) NUMBITS(1) [],
369    /// Device: Remote wakeup. Device can initiate its own resume after suspend.
370    RESUME OFFSET(12) NUMBITS(1) [],
371    /// Host: Enable VBUS
372    VBUS_EN OFFSET(11) NUMBITS(1) [],
373    /// Host: Enable keep alive packet (for low speed bus)
374    KEEP_ALIVE_EN OFFSET(10) NUMBITS(1) [],
375    /// Host: Enable SOF generation (for full speed bus)
376    SOF_EN OFFSET(9) NUMBITS(1) [],
377    /// Host: Delay packet(s) until after SOF
378    SOF_SYNC OFFSET(8) NUMBITS(1) [],
379    /// Host: Preable enable for LS device on FS hub
380    PREAMBLE_EN OFFSET(6) NUMBITS(1) [],
381    /// Host: Stop transaction
382    STOP_TRANS OFFSET(4) NUMBITS(1) [],
383    /// Host: Receive transaction (IN to host)
384    RECEIVE_DATA OFFSET(3) NUMBITS(1) [],
385    /// Host: Send transaction (OUT from host)
386    SEND_DATA OFFSET(2) NUMBITS(1) [],
387    /// Host: Send Setup packet
388    SEND_SETUP OFFSET(1) NUMBITS(1) [],
389    /// Host: Start transaction
390    START_TRANS OFFSET(0) NUMBITS(1) []
391],
392SIE_STATUS [
393    /// Data Sequence Error.
394    /// The device can raise a sequence error in the following conditions:
395    /// * A SETUP packet is received followed by a DATA1 packet (data phase
396    /// should always be DATA0) * An OUT packet is received from the host but
397    /// doesn't match the data pid in the buffer control register read from DPSRAM
398    /// The host can raise a data sequence error in the following conditions:
399    /// * An IN packet from the device has the wrong data PID
400    DATA_SEQ_ERROR OFFSET(31) NUMBITS(1) [],
401    /// ACK received. Raised by both host and device.
402    ACK_REC OFFSET(30) NUMBITS(1) [],
403    /// Host: STALL received
404    STALL_REC OFFSET(29) NUMBITS(1) [],
405    /// Host: NAK received
406    NAK_REC OFFSET(28) NUMBITS(1) [],
407    /// RX timeout is raised by both the host and device if an ACK
408    /// is not received in the maximum time specified by the USB
409    /// spec.
410    RX_TIMEOUT OFFSET(27) NUMBITS(1) [],
411    /// RX overflow is raised by the Serial RX engine if the incoming data is too fast.
412    RX_OVERFLOW OFFSET(26) NUMBITS(1) [],
413    /// Bit Stuff Error. Raised by the Serial RX engine.
414    BIT_STUFF_ERROR OFFSET(25) NUMBITS(1) [],
415    /// CRC Error. Raised by the Serial RX engine.
416    CRC_ERROR OFFSET(24) NUMBITS(1) [],
417    /// Device: bus reset received
418    BUS_RESET OFFSET(19) NUMBITS(1) [],
419    /// Transaction complete.
420    /// Raised by device if:
421    /// * An IN or OUT packet is sent with the LAST_BUFF bit set in
422    /// the buffer control register
423    /// Raised by host if:
424    /// * A setup packet is sent when no data in or data out
425    /// transaction follows * An IN packet is received and the
426    /// LAST_BUFF bit is set in the buffer control register * An IN
427    /// packet is received with zero length * An OUT packet is
428    /// sent and the LAST_BUFF bit is set
429    TRANS_COMPLETE OFFSET(18) NUMBITS(1) [],
430    /// Device: Setup packet received
431    SETUP_REC OFFSET(17) NUMBITS(1) [],
432    /// Device: connected
433    CONNECTED OFFSET(16) NUMBITS(1) [],
434    /// Host: Device has initiated a remote resume. Device: host has initiated a resume.
435    RESUME OFFSET(11) NUMBITS(1) [],
436    /// VBUS over current detected
437    VBUS_OVER_CURR OFFSET(10) NUMBITS(1) [],
438    /// Host: device speed. Disconnected = 00, LS = 01, FS = 10
439    SPEED OFFSET(8) NUMBITS(2) [],
440    /// Bus in suspended state. Valid for device and host. Host
441    /// and device will go into suspend if neither Keep Alive / SOF
442    /// frames are enabled.
443    SUSPENDED OFFSET(4) NUMBITS(1) [],
444    /// USB bus line state
445    LINE_STATE OFFSET(2) NUMBITS(2) [],
446    /// Device: VBUS Detected
447    VBUS_DETECTED OFFSET(0) NUMBITS(1) []
448],
449INT_EP_CTRL [
450    /// Host: Enable interrupt endpoint 1 -> 15
451    INT_EP_ACTIVE OFFSET(1) NUMBITS(15) []
452],
453BUFF_STATUS [
454
455    EP15_OUT OFFSET(31) NUMBITS(1) [],
456
457    EP15_IN OFFSET(30) NUMBITS(1) [],
458
459    EP14_OUT OFFSET(29) NUMBITS(1) [],
460
461    EP14_IN OFFSET(28) NUMBITS(1) [],
462
463    EP13_OUT OFFSET(27) NUMBITS(1) [],
464
465    EP13_IN OFFSET(26) NUMBITS(1) [],
466
467    EP12_OUT OFFSET(25) NUMBITS(1) [],
468
469    EP12_IN OFFSET(24) NUMBITS(1) [],
470
471    EP11_OUT OFFSET(23) NUMBITS(1) [],
472
473    EP11_IN OFFSET(22) NUMBITS(1) [],
474
475    EP10_OUT OFFSET(21) NUMBITS(1) [],
476
477    EP10_IN OFFSET(20) NUMBITS(1) [],
478
479    EP9_OUT OFFSET(19) NUMBITS(1) [],
480
481    EP9_IN OFFSET(18) NUMBITS(1) [],
482
483    EP8_OUT OFFSET(17) NUMBITS(1) [],
484
485    EP8_IN OFFSET(16) NUMBITS(1) [],
486
487    EP7_OUT OFFSET(15) NUMBITS(1) [],
488
489    EP7_IN OFFSET(14) NUMBITS(1) [],
490
491    EP6_OUT OFFSET(13) NUMBITS(1) [],
492
493    EP6_IN OFFSET(12) NUMBITS(1) [],
494
495    EP5_OUT OFFSET(11) NUMBITS(1) [],
496
497    EP5_IN OFFSET(10) NUMBITS(1) [],
498
499    EP4_OUT OFFSET(9) NUMBITS(1) [],
500
501    EP4_IN OFFSET(8) NUMBITS(1) [],
502
503    EP3_OUT OFFSET(7) NUMBITS(1) [],
504
505    EP3_IN OFFSET(6) NUMBITS(1) [],
506
507    EP2_OUT OFFSET(5) NUMBITS(1) [],
508
509    EP2_IN OFFSET(4) NUMBITS(1) [],
510
511    EP1_OUT OFFSET(3) NUMBITS(1) [],
512
513    EP1_IN OFFSET(2) NUMBITS(1) [],
514
515    EP0_OUT OFFSET(1) NUMBITS(1) [],
516
517    EP0_IN OFFSET(0) NUMBITS(1) []
518],
519BUFF_CPU_SHOULD_HANDLE [
520
521    EP15_OUT OFFSET(31) NUMBITS(1) [],
522
523    EP15_IN OFFSET(30) NUMBITS(1) [],
524
525    EP14_OUT OFFSET(29) NUMBITS(1) [],
526
527    EP14_IN OFFSET(28) NUMBITS(1) [],
528
529    EP13_OUT OFFSET(27) NUMBITS(1) [],
530
531    EP13_IN OFFSET(26) NUMBITS(1) [],
532
533    EP12_OUT OFFSET(25) NUMBITS(1) [],
534
535    EP12_IN OFFSET(24) NUMBITS(1) [],
536
537    EP11_OUT OFFSET(23) NUMBITS(1) [],
538
539    EP11_IN OFFSET(22) NUMBITS(1) [],
540
541    EP10_OUT OFFSET(21) NUMBITS(1) [],
542
543    EP10_IN OFFSET(20) NUMBITS(1) [],
544
545    EP9_OUT OFFSET(19) NUMBITS(1) [],
546
547    EP9_IN OFFSET(18) NUMBITS(1) [],
548
549    EP8_OUT OFFSET(17) NUMBITS(1) [],
550
551    EP8_IN OFFSET(16) NUMBITS(1) [],
552
553    EP7_OUT OFFSET(15) NUMBITS(1) [],
554
555    EP7_IN OFFSET(14) NUMBITS(1) [],
556
557    EP6_OUT OFFSET(13) NUMBITS(1) [],
558
559    EP6_IN OFFSET(12) NUMBITS(1) [],
560
561    EP5_OUT OFFSET(11) NUMBITS(1) [],
562
563    EP5_IN OFFSET(10) NUMBITS(1) [],
564
565    EP4_OUT OFFSET(9) NUMBITS(1) [],
566
567    EP4_IN OFFSET(8) NUMBITS(1) [],
568
569    EP3_OUT OFFSET(7) NUMBITS(1) [],
570
571    EP3_IN OFFSET(6) NUMBITS(1) [],
572
573    EP2_OUT OFFSET(5) NUMBITS(1) [],
574
575    EP2_IN OFFSET(4) NUMBITS(1) [],
576
577    EP1_OUT OFFSET(3) NUMBITS(1) [],
578
579    EP1_IN OFFSET(2) NUMBITS(1) [],
580
581    EP0_OUT OFFSET(1) NUMBITS(1) [],
582
583    EP0_IN OFFSET(0) NUMBITS(1) []
584],
585EP_ABORT [
586
587    EP15_OUT OFFSET(31) NUMBITS(1) [],
588
589    EP15_IN OFFSET(30) NUMBITS(1) [],
590
591    EP14_OUT OFFSET(29) NUMBITS(1) [],
592
593    EP14_IN OFFSET(28) NUMBITS(1) [],
594
595    EP13_OUT OFFSET(27) NUMBITS(1) [],
596
597    EP13_IN OFFSET(26) NUMBITS(1) [],
598
599    EP12_OUT OFFSET(25) NUMBITS(1) [],
600
601    EP12_IN OFFSET(24) NUMBITS(1) [],
602
603    EP11_OUT OFFSET(23) NUMBITS(1) [],
604
605    EP11_IN OFFSET(22) NUMBITS(1) [],
606
607    EP10_OUT OFFSET(21) NUMBITS(1) [],
608
609    EP10_IN OFFSET(20) NUMBITS(1) [],
610
611    EP9_OUT OFFSET(19) NUMBITS(1) [],
612
613    EP9_IN OFFSET(18) NUMBITS(1) [],
614
615    EP8_OUT OFFSET(17) NUMBITS(1) [],
616
617    EP8_IN OFFSET(16) NUMBITS(1) [],
618
619    EP7_OUT OFFSET(15) NUMBITS(1) [],
620
621    EP7_IN OFFSET(14) NUMBITS(1) [],
622
623    EP6_OUT OFFSET(13) NUMBITS(1) [],
624
625    EP6_IN OFFSET(12) NUMBITS(1) [],
626
627    EP5_OUT OFFSET(11) NUMBITS(1) [],
628
629    EP5_IN OFFSET(10) NUMBITS(1) [],
630
631    EP4_OUT OFFSET(9) NUMBITS(1) [],
632
633    EP4_IN OFFSET(8) NUMBITS(1) [],
634
635    EP3_OUT OFFSET(7) NUMBITS(1) [],
636
637    EP3_IN OFFSET(6) NUMBITS(1) [],
638
639    EP2_OUT OFFSET(5) NUMBITS(1) [],
640
641    EP2_IN OFFSET(4) NUMBITS(1) [],
642
643    EP1_OUT OFFSET(3) NUMBITS(1) [],
644
645    EP1_IN OFFSET(2) NUMBITS(1) [],
646
647    EP0_OUT OFFSET(1) NUMBITS(1) [],
648
649    EP0_IN OFFSET(0) NUMBITS(1) []
650],
651EP_ABORT_DONE [
652
653    EP15_OUT OFFSET(31) NUMBITS(1) [],
654
655    EP15_IN OFFSET(30) NUMBITS(1) [],
656
657    EP14_OUT OFFSET(29) NUMBITS(1) [],
658
659    EP14_IN OFFSET(28) NUMBITS(1) [],
660
661    EP13_OUT OFFSET(27) NUMBITS(1) [],
662
663    EP13_IN OFFSET(26) NUMBITS(1) [],
664
665    EP12_OUT OFFSET(25) NUMBITS(1) [],
666
667    EP12_IN OFFSET(24) NUMBITS(1) [],
668
669    EP11_OUT OFFSET(23) NUMBITS(1) [],
670
671    EP11_IN OFFSET(22) NUMBITS(1) [],
672
673    EP10_OUT OFFSET(21) NUMBITS(1) [],
674
675    EP10_IN OFFSET(20) NUMBITS(1) [],
676
677    EP9_OUT OFFSET(19) NUMBITS(1) [],
678
679    EP9_IN OFFSET(18) NUMBITS(1) [],
680
681    EP8_OUT OFFSET(17) NUMBITS(1) [],
682
683    EP8_IN OFFSET(16) NUMBITS(1) [],
684
685    EP7_OUT OFFSET(15) NUMBITS(1) [],
686
687    EP7_IN OFFSET(14) NUMBITS(1) [],
688
689    EP6_OUT OFFSET(13) NUMBITS(1) [],
690
691    EP6_IN OFFSET(12) NUMBITS(1) [],
692
693    EP5_OUT OFFSET(11) NUMBITS(1) [],
694
695    EP5_IN OFFSET(10) NUMBITS(1) [],
696
697    EP4_OUT OFFSET(9) NUMBITS(1) [],
698
699    EP4_IN OFFSET(8) NUMBITS(1) [],
700
701    EP3_OUT OFFSET(7) NUMBITS(1) [],
702
703    EP3_IN OFFSET(6) NUMBITS(1) [],
704
705    EP2_OUT OFFSET(5) NUMBITS(1) [],
706
707    EP2_IN OFFSET(4) NUMBITS(1) [],
708
709    EP1_OUT OFFSET(3) NUMBITS(1) [],
710
711    EP1_IN OFFSET(2) NUMBITS(1) [],
712
713    EP0_OUT OFFSET(1) NUMBITS(1) [],
714
715    EP0_IN OFFSET(0) NUMBITS(1) []
716],
717EP_STALL_ARM [
718
719    EP0_OUT OFFSET(1) NUMBITS(1) [],
720
721    EP0_IN OFFSET(0) NUMBITS(1) []
722],
723NAK_POLL [
724    /// NAK polling interval for a full speed device
725    DELAY_FS OFFSET(16) NUMBITS(10) [],
726    /// NAK polling interval for a low speed device
727    DELAY_LS OFFSET(0) NUMBITS(10) []
728],
729EP_STATUS_STALL_NAK [
730
731    EP15_OUT OFFSET(31) NUMBITS(1) [],
732
733    EP15_IN OFFSET(30) NUMBITS(1) [],
734
735    EP14_OUT OFFSET(29) NUMBITS(1) [],
736
737    EP14_IN OFFSET(28) NUMBITS(1) [],
738
739    EP13_OUT OFFSET(27) NUMBITS(1) [],
740
741    EP13_IN OFFSET(26) NUMBITS(1) [],
742
743    EP12_OUT OFFSET(25) NUMBITS(1) [],
744
745    EP12_IN OFFSET(24) NUMBITS(1) [],
746
747    EP11_OUT OFFSET(23) NUMBITS(1) [],
748
749    EP11_IN OFFSET(22) NUMBITS(1) [],
750
751    EP10_OUT OFFSET(21) NUMBITS(1) [],
752
753    EP10_IN OFFSET(20) NUMBITS(1) [],
754
755    EP9_OUT OFFSET(19) NUMBITS(1) [],
756
757    EP9_IN OFFSET(18) NUMBITS(1) [],
758
759    EP8_OUT OFFSET(17) NUMBITS(1) [],
760
761    EP8_IN OFFSET(16) NUMBITS(1) [],
762
763    EP7_OUT OFFSET(15) NUMBITS(1) [],
764
765    EP7_IN OFFSET(14) NUMBITS(1) [],
766
767    EP6_OUT OFFSET(13) NUMBITS(1) [],
768
769    EP6_IN OFFSET(12) NUMBITS(1) [],
770
771    EP5_OUT OFFSET(11) NUMBITS(1) [],
772
773    EP5_IN OFFSET(10) NUMBITS(1) [],
774
775    EP4_OUT OFFSET(9) NUMBITS(1) [],
776
777    EP4_IN OFFSET(8) NUMBITS(1) [],
778
779    EP3_OUT OFFSET(7) NUMBITS(1) [],
780
781    EP3_IN OFFSET(6) NUMBITS(1) [],
782
783    EP2_OUT OFFSET(5) NUMBITS(1) [],
784
785    EP2_IN OFFSET(4) NUMBITS(1) [],
786
787    EP1_OUT OFFSET(3) NUMBITS(1) [],
788
789    EP1_IN OFFSET(2) NUMBITS(1) [],
790
791    EP0_OUT OFFSET(1) NUMBITS(1) [],
792
793    EP0_IN OFFSET(0) NUMBITS(1) []
794],
795USB_MUXING [
796
797    SOFTCON OFFSET(3) NUMBITS(1) [],
798
799    TO_DIGITAL_PAD OFFSET(2) NUMBITS(1) [],
800
801    TO_EXTPHY OFFSET(1) NUMBITS(1) [],
802
803    TO_PHY OFFSET(0) NUMBITS(1) []
804],
805USB_PWR [
806
807    OVERCURR_DETECT_EN OFFSET(5) NUMBITS(1) [],
808
809    OVERCURR_DETECT OFFSET(4) NUMBITS(1) [],
810
811    VBUS_DETECT_OVERRIDE_EN OFFSET(3) NUMBITS(1) [],
812
813    VBUS_DETECT OFFSET(2) NUMBITS(1) [],
814
815    VBUS_EN_OVERRIDE_EN OFFSET(1) NUMBITS(1) [],
816
817    VBUS_EN OFFSET(0) NUMBITS(1) []
818],
819USBPHY_DIRECT [
820    /// DM over voltage
821    DM_OVV OFFSET(22) NUMBITS(1) [],
822    /// DP over voltage
823    DP_OVV OFFSET(21) NUMBITS(1) [],
824    /// DM overcurrent
825    DM_OVCN OFFSET(20) NUMBITS(1) [],
826    /// DP overcurrent
827    DP_OVCN OFFSET(19) NUMBITS(1) [],
828    /// DPM pin state
829    RX_DM OFFSET(18) NUMBITS(1) [],
830    /// DPP pin state
831    RX_DP OFFSET(17) NUMBITS(1) [],
832    /// Differential RX
833    RX_DD OFFSET(16) NUMBITS(1) [],
834    /// TX_DIFFMODE=0: Single ended mode
835    /// TX_DIFFMODE=1: Differential drive mode (TX_DM, TX_DM_OE ignored)
836    TX_DIFFMODE OFFSET(15) NUMBITS(1) [],
837    /// TX_FSSLEW=0: Low speed slew rate
838    /// TX_FSSLEW=1: Full speed slew rate
839    TX_FSSLEW OFFSET(14) NUMBITS(1) [],
840    /// TX power down override (if override enable is set). 1 = powered down.
841    TX_PD OFFSET(13) NUMBITS(1) [],
842    /// RX power down override (if override enable is set). 1 = powered down.
843    RX_PD OFFSET(12) NUMBITS(1) [],
844    /// Output data. TX_DIFFMODE=1, Ignored
845    /// TX_DIFFMODE=0, Drives DPM only. TX_DM_OE=1 to
846    /// enable drive. DPM=TX_DM
847    TX_DM OFFSET(11) NUMBITS(1) [],
848    /// Output data. If TX_DIFFMODE=1, Drives DPP/DPM diff
849    /// pair. TX_DP_OE=1 to enable drive. DPP=TX_DP,
850    /// DPM=~TX_DP
851    /// If TX_DIFFMODE=0, Drives DPP only. TX_DP_OE=1 to
852    /// enable drive. DPP=TX_DP
853    TX_DP OFFSET(10) NUMBITS(1) [],
854    /// Output enable. If TX_DIFFMODE=1, Ignored.
855    /// If TX_DIFFMODE=0, OE for DPM only. 0 - DPM in Hi-Z
856    /// state; 1 - DPM driving
857    TX_DM_OE OFFSET(9) NUMBITS(1) [],
858    /// Output enable. If TX_DIFFMODE=1, Ignored.
859    /// If TX_DIFFMODE=0, OE for DPM only. 0 - DPM in Hi-Z
860    /// state; 1 - DPM driving
861    TX_DP_OE OFFSET(8) NUMBITS(1) [],
862    /// DM pull down enable
863    DM_PULLDN_EN OFFSET(6) NUMBITS(1) [],
864    /// DM pull up enable
865    DM_PULLUP_EN OFFSET(5) NUMBITS(1) [],
866    /// Enable the second DM pull up resistor. 0 - Pull = Rpu2; 1 - Pull = Rpu1 + Rpu2
867    DM_PULLUP_HISEL OFFSET(4) NUMBITS(1) [],
868    /// DP pull down enable
869    DP_PULLDN_EN OFFSET(2) NUMBITS(1) [],
870    /// DP pull up enable
871    DP_PULLUP_EN OFFSET(1) NUMBITS(1) [],
872    /// Enable the second DP pull up resistor. 0 - Pull = Rpu2; 1 - Pull = Rpu1 + Rpu2
873    DP_PULLUP_HISEL OFFSET(0) NUMBITS(1) []
874],
875USBPHY_DIRECT_OVERRIDE [
876
877    TX_DIFFMODE_OVERRIDE_EN OFFSET(15) NUMBITS(1) [],
878
879    DM_PULLUP_OVERRIDE_EN OFFSET(12) NUMBITS(1) [],
880
881    TX_FSSLEW_OVERRIDE_EN OFFSET(11) NUMBITS(1) [],
882
883    TX_PD_OVERRIDE_EN OFFSET(10) NUMBITS(1) [],
884
885    RX_PD_OVERRIDE_EN OFFSET(9) NUMBITS(1) [],
886
887    TX_DM_OVERRIDE_EN OFFSET(8) NUMBITS(1) [],
888
889    TX_DP_OVERRIDE_EN OFFSET(7) NUMBITS(1) [],
890
891    TX_DM_OE_OVERRIDE_EN OFFSET(6) NUMBITS(1) [],
892
893    TX_DP_OE_OVERRIDE_EN OFFSET(5) NUMBITS(1) [],
894
895    DM_PULLDN_EN_OVERRIDE_EN OFFSET(4) NUMBITS(1) [],
896
897    DP_PULLDN_EN_OVERRIDE_EN OFFSET(3) NUMBITS(1) [],
898
899    DP_PULLUP_EN_OVERRIDE_EN OFFSET(2) NUMBITS(1) [],
900
901    DM_PULLUP_HISEL_OVERRIDE_EN OFFSET(1) NUMBITS(1) [],
902
903    DP_PULLUP_HISEL_OVERRIDE_EN OFFSET(0) NUMBITS(1) []
904],
905USBPHY_TRIM [
906    /// Value to drive to USB PHY
907    /// DM pulldown resistor trim control
908    // Experimental data suggests that the reset value will work,
909    // but this register allows adjustment if required
910    DM_PULLDN_TRIM OFFSET(8) NUMBITS(5) [],
911    /// Value to drive to USB PHY
912    /// DP pulldown resistor trim control
913    /// Experimental data suggests that the reset value will work,
914    /// but this register allows adjustment if required
915    DP_PULLDN_TRIM OFFSET(0) NUMBITS(5) []
916],
917INTR [
918    /// Raised when any bit in EP_STATUS_STALL_NAK is set.
919    /// Clear by clearing all bits in EP_STATUS_STALL_NAK.
920    EP_STALL_NAK OFFSET(19) NUMBITS(1) [],
921    /// Raised when any bit in ABORT_DONE is set. Clear by
922    /// clearing all bits in ABORT_DONE.
923    ABORT_DONE OFFSET(18) NUMBITS(1) [],
924    /// Set every time the device receives a SOF (Start of Frame)
925    /// packet. Cleared by reading SOF_RD
926    DEV_SOF OFFSET(17) NUMBITS(1) [],
927    /// Device. Source: SIE_STATUS.SETUP_REC
928    SETUP_REQ OFFSET(16) NUMBITS(1) [],
929    /// Set when the device receives a resume from the host.
930    /// Cleared by writing to SIE_STATUS.RESUME
931    DEV_RESUME_FROM_HOST OFFSET(15) NUMBITS(1) [],
932    /// Set when the device suspend state changes. Cleared by
933    /// writing to SIE_STATUS.SUSPENDED
934    DEV_SUSPEND OFFSET(14) NUMBITS(1) [],
935    /// Set when the device connection state changes. Cleared by
936    /// writing to SIE_STATUS.CONNECTED
937    DEV_CONN_DIS OFFSET(13) NUMBITS(1) [],
938    /// Source: SIE_STATUS.BUS_RESET
939    BUS_RESET OFFSET(12) NUMBITS(1) [],
940    /// Source: SIE_STATUS.VBUS_DETECT
941    VBUS_DETECT OFFSET(11) NUMBITS(1) [],
942    /// Source: SIE_STATUS.STALL_REC
943    STALL OFFSET(10) NUMBITS(1) [],
944    /// Source: SIE_STATUS.CRC_ERROR
945    ERROR_CRC OFFSET(9) NUMBITS(1) [],
946    /// Source: SIE_STATUS.BIT_STUFF_ERROR
947    ERROR_BIT_STUFF OFFSET(8) NUMBITS(1) [],
948    /// Source: SIE_STATUS.RX_OVERFLOW
949    ERROR_RX_OVERFLOW OFFSET(7) NUMBITS(1) [],
950    /// Source: SIE_STATUS.RX_TIMEOUT
951    ERROR_RX_TIMEOUT OFFSET(6) NUMBITS(1) [],
952    /// Source: SIE_STATUS.DATA_SEQ_ERROR
953    ERROR_DATA_SEQ OFFSET(5) NUMBITS(1) [],
954    /// Raised when any bit in BUFF_STATUS is set. Clear by
955    /// clearing all bits in BUFF_STATUS.
956    BUFF_STATUS OFFSET(4) NUMBITS(1) [],
957    /// Raised every time SIE_STATUS.TRANS_COMPLETE is set.
958    /// Clear by writing to this bit.
959    TRANS_COMPLETE OFFSET(3) NUMBITS(1) [],
960    /// Host: raised every time the host sends a SOF (Start of
961    /// Frame). Cleared by reading SOF_RD
962    HOST_SOF OFFSET(2) NUMBITS(1) [],
963    /// Host: raised when a device wakes up the host. Cleared by
964    /// writing to SIE_STATUS.RESUME
965    HOST_RESUME OFFSET(1) NUMBITS(1) [],
966    /// Host: raised when a device is connected or disconnected
967    /// (i.e. when SIE_STATUS.SPEED changes). Cleared by
968    /// writing to SIE_STATUS.SPEED
969    HOST_CONN_DIS OFFSET(0) NUMBITS(1) []
970],
971INTE [
972    /// Raised when any bit in EP_STATUS_STALL_NAK is set.
973    /// Clear by clearing all bits in EP_STATUS_STALL_NAK.
974    EP_STALL_NAK OFFSET(19) NUMBITS(1) [],
975    /// Raised when any bit in ABORT_DONE is set. Clear by
976    /// clearing all bits in ABORT_DONE.
977    ABORT_DONE OFFSET(18) NUMBITS(1) [],
978    /// Set every time the device receives a SOF (Start of Frame)
979    /// packet. Cleared by reading SOF_RD
980    DEV_SOF OFFSET(17) NUMBITS(1) [],
981    /// Device. Source: SIE_STATUS.SETUP_REC
982    SETUP_REQ OFFSET(16) NUMBITS(1) [],
983    /// Set when the device receives a resume from the host.
984    /// Cleared by writing to SIE_STATUS.RESUME
985    DEV_RESUME_FROM_HOST OFFSET(15) NUMBITS(1) [],
986    /// Set when the device suspend state changes. Cleared by
987    /// writing to SIE_STATUS.SUSPENDED
988    DEV_SUSPEND OFFSET(14) NUMBITS(1) [],
989    /// Set when the device connection state changes. Cleared by
990    /// writing to SIE_STATUS.CONNECTED
991    DEV_CONN_DIS OFFSET(13) NUMBITS(1) [],
992    /// Source: SIE_STATUS.BUS_RESET
993    BUS_RESET OFFSET(12) NUMBITS(1) [],
994    /// Source: SIE_STATUS.VBUS_DETECT
995    VBUS_DETECT OFFSET(11) NUMBITS(1) [],
996    /// Source: SIE_STATUS.STALL_REC
997    STALL OFFSET(10) NUMBITS(1) [],
998    /// Source: SIE_STATUS.CRC_ERROR
999    ERROR_CRC OFFSET(9) NUMBITS(1) [],
1000    /// Source: SIE_STATUS.BIT_STUFF_ERROR
1001    ERROR_BIT_STUFF OFFSET(8) NUMBITS(1) [],
1002    /// Source: SIE_STATUS.RX_OVERFLOW
1003    ERROR_RX_OVERFLOW OFFSET(7) NUMBITS(1) [],
1004    /// Source: SIE_STATUS.RX_TIMEOUT
1005    ERROR_RX_TIMEOUT OFFSET(6) NUMBITS(1) [],
1006    /// Source: SIE_STATUS.DATA_SEQ_ERROR
1007    ERROR_DATA_SEQ OFFSET(5) NUMBITS(1) [],
1008    /// Raised when any bit in BUFF_STATUS is set. Clear by
1009    /// clearing all bits in BUFF_STATUS.
1010    BUFF_STATUS OFFSET(4) NUMBITS(1) [],
1011    /// Raised every time SIE_STATUS.TRANS_COMPLETE is set.
1012    /// Clear by writing to this bit.
1013    TRANS_COMPLETE OFFSET(3) NUMBITS(1) [],
1014    /// Host: raised every time the host sends a SOF (Start of
1015    /// Frame). Cleared by reading SOF_RD
1016    HOST_SOF OFFSET(2) NUMBITS(1) [],
1017    /// Host: raised when a device wakes up the host. Cleared by
1018    /// writing to SIE_STATUS.RESUME
1019    HOST_RESUME OFFSET(1) NUMBITS(1) [],
1020    /// Host: raised when a device is connected or disconnected
1021    /// (i.e. when SIE_STATUS.SPEED changes). Cleared by
1022    /// writing to SIE_STATUS.SPEED
1023    HOST_CONN_DIS OFFSET(0) NUMBITS(1) []
1024],
1025INTF [
1026    /// Raised when any bit in EP_STATUS_STALL_NAK is set.
1027    /// Clear by clearing all bits in EP_STATUS_STALL_NAK.
1028    EP_STALL_NAK OFFSET(19) NUMBITS(1) [],
1029    /// Raised when any bit in ABORT_DONE is set. Clear by
1030    /// clearing all bits in ABORT_DONE.
1031    ABORT_DONE OFFSET(18) NUMBITS(1) [],
1032    /// Set every time the device receives a SOF (Start of Frame)
1033    /// packet. Cleared by reading SOF_RD
1034    DEV_SOF OFFSET(17) NUMBITS(1) [],
1035    /// Device. Source: SIE_STATUS.SETUP_REC
1036    SETUP_REQ OFFSET(16) NUMBITS(1) [],
1037    /// Set when the device receives a resume from the host.
1038    /// Cleared by writing to SIE_STATUS.RESUME
1039    DEV_RESUME_FROM_HOST OFFSET(15) NUMBITS(1) [],
1040    /// Set when the device suspend state changes. Cleared by
1041    /// writing to SIE_STATUS.SUSPENDED
1042    DEV_SUSPEND OFFSET(14) NUMBITS(1) [],
1043    /// Set when the device connection state changes. Cleared by
1044    /// writing to SIE_STATUS.CONNECTED
1045    DEV_CONN_DIS OFFSET(13) NUMBITS(1) [],
1046    /// Source: SIE_STATUS.BUS_RESET
1047    BUS_RESET OFFSET(12) NUMBITS(1) [],
1048    /// Source: SIE_STATUS.VBUS_DETECT
1049    VBUS_DETECT OFFSET(11) NUMBITS(1) [],
1050    /// Source: SIE_STATUS.STALL_REC
1051    STALL OFFSET(10) NUMBITS(1) [],
1052    /// Source: SIE_STATUS.CRC_ERROR
1053    ERROR_CRC OFFSET(9) NUMBITS(1) [],
1054    /// Source: SIE_STATUS.BIT_STUFF_ERROR
1055    ERROR_BIT_STUFF OFFSET(8) NUMBITS(1) [],
1056    /// Source: SIE_STATUS.RX_OVERFLOW
1057    ERROR_RX_OVERFLOW OFFSET(7) NUMBITS(1) [],
1058    /// Source: SIE_STATUS.RX_TIMEOUT
1059    ERROR_RX_TIMEOUT OFFSET(6) NUMBITS(1) [],
1060    /// Source: SIE_STATUS.DATA_SEQ_ERROR
1061    ERROR_DATA_SEQ OFFSET(5) NUMBITS(1) [],
1062    /// Raised when any bit in BUFF_STATUS is set. Clear by
1063    /// clearing all bits in BUFF_STATUS.
1064    BUFF_STATUS OFFSET(4) NUMBITS(1) [],
1065    /// Raised every time SIE_STATUS.TRANS_COMPLETE is set.
1066    /// Clear by writing to this bit.
1067    TRANS_COMPLETE OFFSET(3) NUMBITS(1) [],
1068    /// Host: raised every time the host sends a SOF (Start of
1069    /// Frame). Cleared by reading SOF_RD
1070    HOST_SOF OFFSET(2) NUMBITS(1) [],
1071    /// Host: raised when a device wakes up the host. Cleared by
1072    /// writing to SIE_STATUS.RESUME
1073    HOST_RESUME OFFSET(1) NUMBITS(1) [],
1074    /// Host: raised when a device is connected or disconnected
1075    /// (i.e. when SIE_STATUS.SPEED changes). Cleared by
1076    /// writing to SIE_STATUS.SPEED
1077    HOST_CONN_DIS OFFSET(0) NUMBITS(1) []
1078],
1079INTS [
1080    /// Raised when any bit in EP_STATUS_STALL_NAK is set.
1081    /// Clear by clearing all bits in EP_STATUS_STALL_NAK.
1082    EP_STALL_NAK OFFSET(19) NUMBITS(1) [],
1083    /// Raised when any bit in ABORT_DONE is set. Clear by
1084    /// clearing all bits in ABORT_DONE.
1085    ABORT_DONE OFFSET(18) NUMBITS(1) [],
1086    /// Set every time the device receives a SOF (Start of Frame)
1087    /// packet. Cleared by reading SOF_RD
1088    DEV_SOF OFFSET(17) NUMBITS(1) [],
1089    /// Device. Source: SIE_STATUS.SETUP_REC
1090    SETUP_REQ OFFSET(16) NUMBITS(1) [],
1091    /// Set when the device receives a resume from the host.
1092    /// Cleared by writing to SIE_STATUS.RESUME
1093    DEV_RESUME_FROM_HOST OFFSET(15) NUMBITS(1) [],
1094    /// Set when the device suspend state changes. Cleared by
1095    /// writing to SIE_STATUS.SUSPENDED
1096    DEV_SUSPEND OFFSET(14) NUMBITS(1) [],
1097    /// Set when the device connection state changes. Cleared by
1098    /// writing to SIE_STATUS.CONNECTED
1099    DEV_CONN_DIS OFFSET(13) NUMBITS(1) [],
1100    /// Source: SIE_STATUS.BUS_RESET
1101    BUS_RESET OFFSET(12) NUMBITS(1) [],
1102    /// Source: SIE_STATUS.VBUS_DETECT
1103    VBUS_DETECT OFFSET(11) NUMBITS(1) [],
1104    /// Source: SIE_STATUS.STALL_REC
1105    STALL OFFSET(10) NUMBITS(1) [],
1106    /// Source: SIE_STATUS.CRC_ERROR
1107    ERROR_CRC OFFSET(9) NUMBITS(1) [],
1108    /// Source: SIE_STATUS.BIT_STUFF_ERROR
1109    ERROR_BIT_STUFF OFFSET(8) NUMBITS(1) [],
1110    /// Source: SIE_STATUS.RX_OVERFLOW
1111    ERROR_RX_OVERFLOW OFFSET(7) NUMBITS(1) [],
1112    /// Source: SIE_STATUS.RX_TIMEOUT
1113    ERROR_RX_TIMEOUT OFFSET(6) NUMBITS(1) [],
1114    /// Source: SIE_STATUS.DATA_SEQ_ERROR
1115    ERROR_DATA_SEQ OFFSET(5) NUMBITS(1) [],
1116    /// Raised when any bit in BUFF_STATUS is set. Clear by
1117    /// clearing all bits in BUFF_STATUS.
1118    BUFF_STATUS OFFSET(4) NUMBITS(1) [],
1119    /// Raised every time SIE_STATUS.TRANS_COMPLETE is set.
1120    /// Clear by writing to this bit.
1121    TRANS_COMPLETE OFFSET(3) NUMBITS(1) [],
1122    /// Host: raised every time the host sends a SOF (Start of
1123    /// Frame). Cleared by reading SOF_RD
1124    HOST_SOF OFFSET(2) NUMBITS(1) [],
1125    /// Host: raised when a device wakes up the host. Cleared by
1126    /// writing to SIE_STATUS.RESUME
1127    HOST_RESUME OFFSET(1) NUMBITS(1) [],
1128    /// Host: raised when a device is connected or disconnected
1129    /// (i.e. when SIE_STATUS.SPEED changes). Cleared by
1130    /// writing to SIE_STATUS.SPEED
1131    HOST_CONN_DIS OFFSET(0) NUMBITS(1) []
1132]
1133];
1134
1135register_bitfields![u32,
1136    RequestType [
1137        RECIPIENT OFFSET(0) NUMBITS(5) [
1138            Device = 0,
1139            Interface = 1,
1140            Endpoint = 2,
1141            Other = 3
1142        ],
1143        TYPE OFFSET(5) NUMBITS(2) [
1144            Standard = 0,
1145            Class = 1,
1146            Vendor = 2
1147        ],
1148        DIRECTION OFFSET(7) NUMBITS(1) [
1149            HostToDevice = 0,
1150            DeviceToHost = 1
1151        ]
1152    ],
1153    SETUP_H [
1154        BM_REQUEST_TYPE OFFSET(0) NUMBITS(8) [],
1155        B_REQUEST OFFSET(8) NUMBITS(8) [
1156            GET_ADDRESS = 0x05,
1157            GET_DESCRIPTOR = 0x07,
1158            GET_CONFIGURATION = 0x09,
1159        ],
1160        W_VALUE_L OFFSET(16) NUMBITS(8) [],
1161        W_VALUE_H OFFSET(24) NUMBITS(8) [],
1162    ],
1163    SETUP_L [
1164        W_INDEX_L OFFSET(0) NUMBITS(8) [],
1165        W_INDEX_H OFFSET(8) NUMBITS(8) [],
1166        W_LENGTH_L OFFSET(16) NUMBITS(8) [],
1167        W_LENGTH_H OFFSET(24) NUMBITS(8) [],
1168    ],
1169    EP_CONTROL [
1170        ENDPOINT_ENABLE OFFSET(31) NUMBITS(1) [],
1171        DOUBLE_BUFFERED OFFSET(30) NUMBITS(1) [],
1172        INTERRUPT_SINGLE_BIT OFFSET(29) NUMBITS(1) [],
1173        INTERRUPT_DOUBLE_BIT OFFSET(28) NUMBITS(1) [],
1174        ENDPOINT_TYPE OFFSET(26) NUMBITS(2) [
1175            CONTROL = 0,
1176            ISO = 1,
1177            BULK = 2,
1178            INT = 3
1179        ],
1180        INT_STALL OFFSET(17) NUMBITS(1) [],
1181        INT_NAK OFFSET(16) NUMBITS(1) [],
1182        ADDR_BASE OFFSET(0) NUMBITS(16) [],
1183    ],
1184    EP_BUFFER_CONTROL [
1185        BUFFER1_FULL OFFSET(31) NUMBITS(1) [],
1186        LAST_BUFFER1 OFFSET(30) NUMBITS(1) [],
1187        DATA_PID1 OFFSET(29) NUMBITS(1) [],
1188        DOUBLE_BUFFERED_OFFSET_ISO OFFSET(27) NUMBITS(2) [
1189            OFFSET_128 = 0,
1190            OFFSET_256 = 1,
1191            OFFSET_512 = 2,
1192            OFFSET_1024 = 3,
1193        ],
1194        AVAILABLE1 OFFSET(26) NUMBITS(1) [],
1195        TRANSFER_LENGTH1 OFFSET(16) NUMBITS(10) [],
1196        BUFFER0_FULL OFFSET(15) NUMBITS(1) [],
1197        LAST_BUFFER0 OFFSET(14) NUMBITS(1) [],
1198        DATA_PID0 OFFSET(13) NUMBITS(1) [],
1199        RESET_BUFFER OFFSET(12) NUMBITS(1) [],
1200        STALL OFFSET(11) NUMBITS(1) [],
1201        AVAILABLE0 OFFSET(10) NUMBITS(1) [],
1202        TRANSFER_LENGTH0 OFFSET(0) NUMBITS(10) [],
1203    ]
1204];
1205
1206#[derive(Copy, Clone, Debug, PartialEq)]
1207pub enum UsbState {
1208    Disabled,
1209    Started,
1210    Initialized,
1211    PoweredOn,
1212    Attached,
1213    Configured,
1214}
1215
1216#[derive(Copy, Clone, Debug)]
1217pub enum EndpointState {
1218    Disabled,
1219    Ctrl(CtrlState),
1220    Bulk(TransferType, Option<BulkInState>, Option<BulkOutState>),
1221}
1222
1223impl EndpointState {
1224    fn ctrl_state(self) -> CtrlState {
1225        match self {
1226            EndpointState::Ctrl(state) => state,
1227            _ => panic!("Expected EndpointState::Ctrl"),
1228        }
1229    }
1230
1231    fn bulk_state(self) -> (TransferType, Option<BulkInState>, Option<BulkOutState>) {
1232        match self {
1233            EndpointState::Bulk(transfer_type, in_state, out_state) => {
1234                (transfer_type, in_state, out_state)
1235            }
1236            _ => panic!("Expected EndpointState::Bulk"),
1237        }
1238    }
1239}
1240
1241/// State of the control endpoint (endpoint 0).
1242#[derive(Copy, Clone, PartialEq, Debug)]
1243pub enum CtrlState {
1244    /// Control endpoint is idle, and waiting for a command from the host.
1245    Init,
1246    /// Control endpoint has started an IN transfer.
1247    ReadIn,
1248    /// Control endpoint has moved to the status phase.
1249    ReadStatus,
1250    /// Control endpoint is handling a control write (OUT) transfer.
1251    WriteOut,
1252}
1253
1254#[derive(Copy, Clone, PartialEq, Debug)]
1255pub enum BulkInState {
1256    // The endpoint is ready to perform transactions.
1257    Init,
1258    // There is a pending IN packet transfer on this endpoint.
1259    InData,
1260}
1261
1262#[derive(Copy, Clone, PartialEq, Debug)]
1263pub enum BulkOutState {
1264    // The endpoint is ready to perform transactions.
1265    Init,
1266    // There is a pending OUT packet in this endpoint's buffer, to be read by
1267    // the client application.
1268    OutDelay,
1269    // There is a pending EPDATA to reply to. Store the size right after the
1270    // EPDATA event.
1271    OutData { size: u32 },
1272}
1273
1274#[derive(Copy, Clone, PartialEq, Debug)]
1275pub enum EndpointType {
1276    NONE,
1277    IN,
1278    OUT,
1279}
1280
1281pub struct Endpoint<'a> {
1282    slice_in: OptionalCell<&'a [VolatileCell<u8>]>,
1283    slice_out: OptionalCell<&'a [VolatileCell<u8>]>,
1284    state: Cell<EndpointState>,
1285    // Whether a transfer is requested on this IN endpoint.
1286    request_transmit_in: Cell<bool>,
1287    // Whether a transfer is requested on this OUT endpoint.
1288    request_transmit_out: Cell<bool>,
1289    direction: Cell<EndpointType>,
1290}
1291
1292impl Endpoint<'_> {
1293    const fn new() -> Self {
1294        Endpoint {
1295            slice_in: OptionalCell::empty(),
1296            slice_out: OptionalCell::empty(),
1297            state: Cell::new(EndpointState::Disabled),
1298            request_transmit_in: Cell::new(false),
1299            request_transmit_out: Cell::new(false),
1300            direction: Cell::new(EndpointType::NONE),
1301        }
1302    }
1303}
1304
1305const USBCTRL_DPSRAM: StaticRef<Usbctrl_DPSRAM> =
1306    unsafe { StaticRef::new(0x50100000 as *const Usbctrl_DPSRAM) };
1307
1308const USBCTRL_REGS_BASE: StaticRef<Usbctrl_RegsRegisters> =
1309    unsafe { StaticRef::new(0x50110000 as *const Usbctrl_RegsRegisters) };
1310
1311pub const N_ENDPOINTS: usize = 16;
1312
1313pub struct UsbCtrl<'a> {
1314    dpsram: StaticRef<Usbctrl_DPSRAM>,
1315    registers: StaticRef<Usbctrl_RegsRegisters>,
1316    state: OptionalCell<UsbState>,
1317    client: OptionalCell<&'a dyn hil::usb::Client<'a>>,
1318    descriptors: [Endpoint<'a>; N_ENDPOINTS],
1319    should_set_address: VolatileCell<bool>,
1320    address: VolatileCell<u32>,
1321    next_pid_in: [VolatileCell<u8>; 16],
1322    next_pid_out: [VolatileCell<u8>; 16],
1323    errata_pin: OptionalCell<&'a RPGpioPin<'a>>,
1324    counter: VolatileCell<u32>,
1325}
1326
1327impl<'a> UsbCtrl<'a> {
1328    pub const fn new() -> Self {
1329        Self {
1330            dpsram: USBCTRL_DPSRAM,
1331            registers: USBCTRL_REGS_BASE,
1332            client: OptionalCell::empty(),
1333            state: OptionalCell::new(UsbState::Disabled),
1334            descriptors: [
1335                Endpoint::new(),
1336                Endpoint::new(),
1337                Endpoint::new(),
1338                Endpoint::new(),
1339                Endpoint::new(),
1340                Endpoint::new(),
1341                Endpoint::new(),
1342                Endpoint::new(),
1343                Endpoint::new(),
1344                Endpoint::new(),
1345                Endpoint::new(),
1346                Endpoint::new(),
1347                Endpoint::new(),
1348                Endpoint::new(),
1349                Endpoint::new(),
1350                Endpoint::new(),
1351            ],
1352            should_set_address: VolatileCell::new(false),
1353            address: VolatileCell::new(0),
1354            next_pid_in: [
1355                VolatileCell::new(0),
1356                VolatileCell::new(0),
1357                VolatileCell::new(0),
1358                VolatileCell::new(0),
1359                VolatileCell::new(0),
1360                VolatileCell::new(0),
1361                VolatileCell::new(0),
1362                VolatileCell::new(0),
1363                VolatileCell::new(0),
1364                VolatileCell::new(0),
1365                VolatileCell::new(0),
1366                VolatileCell::new(0),
1367                VolatileCell::new(0),
1368                VolatileCell::new(0),
1369                VolatileCell::new(0),
1370                VolatileCell::new(0),
1371            ],
1372            next_pid_out: [
1373                VolatileCell::new(0),
1374                VolatileCell::new(0),
1375                VolatileCell::new(0),
1376                VolatileCell::new(0),
1377                VolatileCell::new(0),
1378                VolatileCell::new(0),
1379                VolatileCell::new(0),
1380                VolatileCell::new(0),
1381                VolatileCell::new(0),
1382                VolatileCell::new(0),
1383                VolatileCell::new(0),
1384                VolatileCell::new(0),
1385                VolatileCell::new(0),
1386                VolatileCell::new(0),
1387                VolatileCell::new(0),
1388                VolatileCell::new(0),
1389            ],
1390            errata_pin: OptionalCell::empty(),
1391            counter: VolatileCell::new(0),
1392        }
1393    }
1394
1395    fn nop_wait(&self) {
1396        for _i in 0..100 {
1397            cortexm0p::support::nop()
1398        }
1399    }
1400
1401    // This is errata RP2040-E5 https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf#RP2040-E5
1402    pub fn set_gpio(&self, gpio_pin: &'a RPGpioPin<'a>) {
1403        self.errata_pin.set(gpio_pin);
1404    }
1405
1406    pub fn enable(&self) {
1407        self.registers
1408            .usb_muxing
1409            .modify(USB_MUXING::TO_PHY::SET + USB_MUXING::SOFTCON::SET);
1410        self.registers
1411            .usb_pwr
1412            .modify(USB_PWR::VBUS_DETECT::SET + USB_PWR::VBUS_DETECT_OVERRIDE_EN::SET);
1413        self.registers.main_ctrl.modify(
1414            MAIN_CTRL::CONTROLLER_EN::SET
1415                + MAIN_CTRL::HOST_NDEVICE::CLEAR
1416                + MAIN_CTRL::SIM_TIMING::CLEAR,
1417        );
1418
1419        self.apply_errata_e5();
1420        self.state.set(UsbState::Started);
1421    }
1422
1423    pub fn get_state(&self) -> UsbState {
1424        self.state.unwrap_or_panic()
1425    }
1426
1427    // Allows the peripheral to be enumerated by the USB master
1428    fn start(&self) {
1429        if self.get_state() == UsbState::Disabled {
1430            self.enable();
1431            self.registers
1432                .inte
1433                .modify(INTE::SETUP_REQ::SET + INTE::BUFF_STATUS::SET + INTE::BUS_RESET::SET);
1434            self.registers
1435                .sie_ctrl
1436                .modify(SIE_CTRL::EP0_DOUBLE_BUF::CLEAR + SIE_CTRL::EP0_INT_1BUF::SET);
1437        }
1438    }
1439
1440    pub fn enable_pullup(&self) {
1441        if self.get_state() == UsbState::Started {
1442            self.registers.sie_ctrl.modify(SIE_CTRL::PULLUP_EN::SET);
1443        }
1444        self.state.set(UsbState::Attached);
1445    }
1446
1447    pub fn disable_pullup(&self) {
1448        self.state.set(UsbState::Started);
1449        self.registers.sie_ctrl.modify(SIE_CTRL::PULLUP_EN::CLEAR);
1450    }
1451
1452    fn enable_in_endpoint_(&self, transfer_type: TransferType, endpoint: usize) {
1453        self.descriptors[endpoint].state.set(match endpoint {
1454            0 => {
1455                self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.set(0);
1456                self.dpsram.ep_buf_ctrl[endpoint]
1457                    .ep_in_buf_ctrl
1458                    .modify(EP_BUFFER_CONTROL::DATA_PID0::SET + EP_BUFFER_CONTROL::AVAILABLE0::SET);
1459                EndpointState::Ctrl(CtrlState::Init)
1460            }
1461            1..=N_ENDPOINTS => {
1462                self.dpsram.ep_ctrl[endpoint - 1].ep_in_ctrl.write(
1463                    EP_CONTROL::ENDPOINT_ENABLE::SET
1464                        + EP_CONTROL::DOUBLE_BUFFERED::CLEAR
1465                        + EP_CONTROL::ENDPOINT_TYPE::BULK
1466                        + EP_CONTROL::INTERRUPT_SINGLE_BIT::SET
1467                        + EP_CONTROL::INTERRUPT_DOUBLE_BIT::CLEAR
1468                        + EP_CONTROL::ADDR_BASE.val((0x180 + 64 * (endpoint - 1)) as u32),
1469                );
1470                self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.set(0);
1471                self.descriptors[endpoint].direction.set(EndpointType::IN);
1472                EndpointState::Bulk(transfer_type, Some(BulkInState::Init), None)
1473            }
1474            _ => unreachable!("unexisting endpoint"),
1475        });
1476    }
1477
1478    fn enable_out_endpoint_(&self, transfer_type: TransferType, endpoint: usize) {
1479        self.descriptors[endpoint].state.set(match endpoint {
1480            0 => {
1481                self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.set(0);
1482                self.dpsram.ep_buf_ctrl[endpoint]
1483                    .ep_out_buf_ctrl
1484                    .modify(EP_BUFFER_CONTROL::DATA_PID0::SET);
1485                EndpointState::Ctrl(CtrlState::Init)
1486            }
1487            1..=N_ENDPOINTS => {
1488                self.dpsram.ep_ctrl[endpoint].ep_out_ctrl.set(0);
1489                self.dpsram.ep_ctrl[endpoint - 1].ep_out_ctrl.modify(
1490                    EP_CONTROL::ENDPOINT_ENABLE::SET
1491                        + EP_CONTROL::DOUBLE_BUFFERED::CLEAR
1492                        + EP_CONTROL::ENDPOINT_TYPE::BULK
1493                        + EP_CONTROL::INTERRUPT_SINGLE_BIT::SET
1494                        + EP_CONTROL::INTERRUPT_DOUBLE_BIT::CLEAR
1495                        + EP_CONTROL::ADDR_BASE.val((0x180 + 64 * (endpoint - 1)) as u32),
1496                );
1497                self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.set(0);
1498                self.descriptors[endpoint].direction.set(EndpointType::OUT);
1499                EndpointState::Bulk(transfer_type, None, Some(BulkOutState::Init))
1500            }
1501            _ => unreachable!("unexisting endpoint"),
1502        });
1503    }
1504
1505    fn apply_errata_e5(&self) {
1506        self.errata_pin.map(|p| {
1507            let (prev_ctrl, prev_pad) = p.start_usb_errata();
1508            self.registers.usb_muxing.set(0);
1509            self.registers
1510                .usb_muxing
1511                .modify(USB_MUXING::TO_DIGITAL_PAD::SET + USB_MUXING::SOFTCON::SET);
1512            for _i in 0..106400 {
1513                cortexm0p::support::nop()
1514            }
1515            self.registers.usb_muxing.set(0);
1516            self.registers
1517                .usb_muxing
1518                .modify(USB_MUXING::TO_PHY::SET + USB_MUXING::SOFTCON::SET);
1519            p.finish_usb_errata(prev_ctrl, prev_pad);
1520        });
1521    }
1522
1523    fn handle_bus_reset(&self) {
1524        for (ep, desc) in self.descriptors.iter().enumerate() {
1525            match desc.state.get() {
1526                EndpointState::Disabled => {}
1527                EndpointState::Ctrl(_) => desc.state.set(EndpointState::Ctrl(CtrlState::Init)),
1528                EndpointState::Bulk(transfer_type, in_state, out_state) => {
1529                    desc.state.set(EndpointState::Bulk(
1530                        transfer_type,
1531                        in_state.map(|_| BulkInState::Init),
1532                        out_state.map(|_| BulkOutState::Init),
1533                    ));
1534                    if out_state.is_some() {
1535                        self.dpsram.ep_buf_ctrl[ep].ep_out_buf_ctrl.set(0);
1536                        self.dpsram.ep_buf_ctrl[ep].ep_out_buf_ctrl.modify(
1537                            EP_BUFFER_CONTROL::AVAILABLE0::SET
1538                                + EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(64_u32),
1539                        );
1540                    }
1541                }
1542            }
1543            self.next_pid_in[ep].set(0);
1544            self.next_pid_out[ep].set(0);
1545            desc.request_transmit_in.set(false);
1546            desc.request_transmit_out.set(false);
1547        }
1548        self.dpsram.ep_buf_ctrl[0]
1549            .ep_out_buf_ctrl
1550            .modify(EP_BUFFER_CONTROL::DATA_PID0::SET);
1551
1552        self.dpsram.ep_buf_ctrl[0].ep_in_buf_ctrl.modify(
1553            EP_BUFFER_CONTROL::AVAILABLE0::SET
1554                + EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(64)
1555                + EP_BUFFER_CONTROL::DATA_PID0::CLEAR,
1556        );
1557        self.registers.buff_status.set(0);
1558        self.registers.addr_endp.modify(ADDR_ENDP::ADDRESS.val(0));
1559
1560        self.address.set(0);
1561        self.client.map(|client| {
1562            client.bus_reset();
1563        });
1564        self.registers.sie_status.modify(SIE_STATUS::BUS_RESET::SET);
1565    }
1566
1567    pub fn handle_interrupt(&self) {
1568        if self.registers.ints.is_set(INTS::BUS_RESET) {
1569            self.handle_bus_reset();
1570        }
1571
1572        if self.registers.buff_status.get() != 0 {
1573            self.handle_buff_status();
1574        }
1575
1576        self.process_requests();
1577
1578        if self.registers.ints.is_set(INTS::SETUP_REQ) {
1579            self.registers.sie_status.modify(SIE_STATUS::SETUP_REC::SET);
1580            self.usb_handle_setup_packet();
1581        }
1582    }
1583
1584    fn handle_buff_status(&self) {
1585        // Endpoint 0
1586        if self.registers.buff_status.is_set(BUFF_STATUS::EP0_IN) {
1587            self.handle_ep0datadone();
1588        }
1589        if self.registers.buff_status.is_set(BUFF_STATUS::EP0_OUT) {
1590            self.handle_endepout(0);
1591        }
1592        // Endpoint 1
1593        if self.registers.buff_status.is_set(BUFF_STATUS::EP1_IN) {
1594            self.handle_endepin(1);
1595        }
1596        if self.registers.buff_status.is_set(BUFF_STATUS::EP1_OUT) {
1597            self.handle_epdata_out(1);
1598        }
1599        // Endpoint 2
1600        if self.registers.buff_status.is_set(BUFF_STATUS::EP2_IN) {
1601            self.handle_epdata_in(2);
1602        }
1603        if self.registers.buff_status.is_set(BUFF_STATUS::EP2_OUT) {
1604            self.handle_epdata_out(2);
1605        }
1606        // Endpoint 3
1607        if self.registers.buff_status.is_set(BUFF_STATUS::EP3_IN) {
1608            self.handle_endepin(3);
1609        }
1610        if self.registers.buff_status.is_set(BUFF_STATUS::EP3_OUT) {
1611            self.handle_epdata_out(3);
1612        }
1613        // Endpoint 4
1614        if self.registers.buff_status.is_set(BUFF_STATUS::EP4_IN) {
1615            self.handle_epdata_in(4);
1616        }
1617        if self.registers.buff_status.is_set(BUFF_STATUS::EP4_OUT) {
1618            self.handle_epdata_out(4);
1619        }
1620        // Endpoint 5
1621        if self.registers.buff_status.is_set(BUFF_STATUS::EP5_IN) {
1622            self.handle_epdata_in(5);
1623        }
1624        if self.registers.buff_status.is_set(BUFF_STATUS::EP5_OUT) {
1625            self.registers
1626                .buff_status
1627                .modify(BUFF_STATUS::EP5_OUT::CLEAR);
1628            self.handle_epdata_out(5);
1629        }
1630        // Endpoint 6
1631        if self.registers.buff_status.is_set(BUFF_STATUS::EP6_IN) {
1632            self.registers
1633                .buff_status
1634                .modify(BUFF_STATUS::EP6_IN::CLEAR);
1635            self.handle_epdata_in(6);
1636        }
1637        if self.registers.buff_status.is_set(BUFF_STATUS::EP6_OUT) {
1638            self.registers
1639                .buff_status
1640                .modify(BUFF_STATUS::EP6_OUT::CLEAR);
1641            self.handle_epdata_out(6);
1642        }
1643        // Endpoint 7
1644        if self.registers.buff_status.is_set(BUFF_STATUS::EP7_IN) {
1645            self.registers
1646                .buff_status
1647                .modify(BUFF_STATUS::EP7_IN::CLEAR);
1648            self.handle_epdata_in(7);
1649        }
1650        if self.registers.buff_status.is_set(BUFF_STATUS::EP7_OUT) {
1651            self.registers
1652                .buff_status
1653                .modify(BUFF_STATUS::EP7_OUT::CLEAR);
1654            self.handle_epdata_out(7);
1655        }
1656        // Endpoint 8
1657        if self.registers.buff_status.is_set(BUFF_STATUS::EP8_IN) {
1658            self.registers
1659                .buff_status
1660                .modify(BUFF_STATUS::EP8_IN::CLEAR);
1661            self.handle_epdata_in(8);
1662        }
1663        if self.registers.buff_status.is_set(BUFF_STATUS::EP8_OUT) {
1664            self.registers
1665                .buff_status
1666                .modify(BUFF_STATUS::EP8_OUT::CLEAR);
1667            self.handle_epdata_out(8);
1668        }
1669        // Endpoint 9
1670        if self.registers.buff_status.is_set(BUFF_STATUS::EP9_IN) {
1671            self.registers
1672                .buff_status
1673                .modify(BUFF_STATUS::EP9_IN::CLEAR);
1674            self.handle_epdata_in(9);
1675        }
1676        if self.registers.buff_status.is_set(BUFF_STATUS::EP9_OUT) {
1677            self.registers
1678                .buff_status
1679                .modify(BUFF_STATUS::EP9_OUT::CLEAR);
1680            self.handle_epdata_out(9);
1681        }
1682        // Endpoint 10
1683        if self.registers.buff_status.is_set(BUFF_STATUS::EP10_IN) {
1684            self.registers
1685                .buff_status
1686                .modify(BUFF_STATUS::EP10_IN::CLEAR);
1687            self.handle_epdata_in(10);
1688        }
1689        if self.registers.buff_status.is_set(BUFF_STATUS::EP10_OUT) {
1690            self.registers
1691                .buff_status
1692                .modify(BUFF_STATUS::EP10_OUT::CLEAR);
1693            self.handle_epdata_out(10);
1694        }
1695        // Endpoint 11
1696        if self.registers.buff_status.is_set(BUFF_STATUS::EP11_IN) {
1697            self.registers
1698                .buff_status
1699                .modify(BUFF_STATUS::EP11_IN::CLEAR);
1700            self.handle_epdata_in(11);
1701        }
1702        if self.registers.buff_status.is_set(BUFF_STATUS::EP11_OUT) {
1703            self.registers
1704                .buff_status
1705                .modify(BUFF_STATUS::EP11_OUT::CLEAR);
1706            self.handle_epdata_out(11);
1707        }
1708        // Endpoint 12
1709        if self.registers.buff_status.is_set(BUFF_STATUS::EP12_IN) {
1710            self.registers
1711                .buff_status
1712                .modify(BUFF_STATUS::EP12_IN::CLEAR);
1713            self.handle_epdata_in(12);
1714        }
1715        if self.registers.buff_status.is_set(BUFF_STATUS::EP12_OUT) {
1716            self.registers
1717                .buff_status
1718                .modify(BUFF_STATUS::EP12_OUT::CLEAR);
1719            self.handle_epdata_out(12);
1720        }
1721        // Endpoint 13
1722        if self.registers.buff_status.is_set(BUFF_STATUS::EP13_IN) {
1723            self.registers
1724                .buff_status
1725                .modify(BUFF_STATUS::EP13_IN::CLEAR);
1726            self.handle_epdata_in(13);
1727        }
1728        if self.registers.buff_status.is_set(BUFF_STATUS::EP13_OUT) {
1729            self.registers
1730                .buff_status
1731                .modify(BUFF_STATUS::EP13_OUT::CLEAR);
1732            self.handle_epdata_out(13);
1733        }
1734        // Endpoint 14
1735        if self.registers.buff_status.is_set(BUFF_STATUS::EP14_IN) {
1736            self.handle_epdata_in(14);
1737            self.registers
1738                .buff_status
1739                .modify(BUFF_STATUS::EP14_IN::CLEAR);
1740        }
1741        if self.registers.buff_status.is_set(BUFF_STATUS::EP14_OUT) {
1742            self.handle_epdata_out(14);
1743            self.registers
1744                .buff_status
1745                .modify(BUFF_STATUS::EP14_OUT::CLEAR);
1746        }
1747        // Endpoint 15
1748        if self.registers.buff_status.is_set(BUFF_STATUS::EP15_IN) {
1749            self.handle_epdata_in(15);
1750        }
1751        self.registers
1752            .buff_status
1753            .modify(BUFF_STATUS::EP15_IN::CLEAR);
1754
1755        if self.registers.buff_status.is_set(BUFF_STATUS::EP15_OUT) {
1756            self.handle_epdata_out(15);
1757        }
1758        self.registers
1759            .buff_status
1760            .modify(BUFF_STATUS::EP15_OUT::CLEAR);
1761
1762        self.registers.buff_status.set(0);
1763    }
1764
1765    fn process_requests(&self) {
1766        for (endpoint, desc) in self.descriptors.iter().enumerate() {
1767            if desc.request_transmit_in.take() {
1768                if endpoint == 0 {
1769                    self.transmit_in_ep0();
1770                } else {
1771                    self.transmit_in(endpoint);
1772                }
1773            }
1774            if desc.request_transmit_out.take() {
1775                if endpoint == 0 {
1776                    self.transmit_out_ep0();
1777                } else {
1778                    self.transmit_out(endpoint);
1779                }
1780            }
1781        }
1782    }
1783
1784    fn handle_epdata_out(&self, ep: usize) {
1785        let (transfer_type, in_state, out_state) = self.descriptors[ep].state.get().bulk_state();
1786        assert!(out_state.is_some());
1787
1788        // We need to read the size at this point in the process. At this point
1789        // the USB hardware has received the data, but we need to
1790        // copy the data to memory. Later on the EPOUT.SIZE register can
1791        // be overwritten, particularly if the host is sending OUT
1792        // transactions quickly.
1793        let ep_size = self.dpsram.ep_buf_ctrl[ep]
1794            .ep_out_buf_ctrl
1795            .read(EP_BUFFER_CONTROL::TRANSFER_LENGTH0);
1796
1797        match out_state.unwrap() {
1798            BulkOutState::Init => {
1799                // The endpoint is ready to receive data. Request a transmit_out.
1800                self.descriptors[ep].request_transmit_out.set(true);
1801            }
1802            BulkOutState::OutDelay => {
1803                // The endpoint will be resumed later by the client application with transmit_out().
1804            }
1805            BulkOutState::OutData { size: _ } => {
1806                self.descriptors[ep].request_transmit_out.set(true);
1807            }
1808        }
1809        // Indicate that the endpoint now has data available.
1810        self.descriptors[ep].state.set(EndpointState::Bulk(
1811            transfer_type,
1812            in_state,
1813            Some(BulkOutState::OutData { size: ep_size }),
1814        ));
1815    }
1816
1817    fn handle_epdata_in(&self, endpoint: usize) {
1818        let (transfer_type, in_state, out_state) =
1819            self.descriptors[endpoint].state.get().bulk_state();
1820        assert!(in_state.is_some());
1821        match in_state.unwrap() {
1822            BulkInState::InData => {
1823                // Totally expected state. Nothing to do.
1824                self.client
1825                    .map(|client| client.packet_transmitted(endpoint));
1826                self.descriptors[endpoint].state.set(EndpointState::Bulk(
1827                    transfer_type,
1828                    Some(BulkInState::Init),
1829                    out_state,
1830                ));
1831            }
1832            BulkInState::Init => {}
1833        }
1834    }
1835
1836    fn usb_handle_setup_packet(&self) {
1837        let endpoint = 0;
1838
1839        // We are idle, and ready for any control transfer.
1840        let state = self.descriptors[endpoint].state.get().ctrl_state();
1841        match state {
1842            CtrlState::Init => {
1843                let ep_buf = &self.descriptors[endpoint].slice_out;
1844                let ep_buf = ep_buf.unwrap_or_panic();
1845                if ep_buf.len() < 8 {
1846                    panic!("EP0 DMA buffer length < 8");
1847                }
1848
1849                // Re-construct the SETUP packet from various registers. The
1850                // client's ctrl_setup() will parse it as a SetupData
1851                // descriptor.
1852                ep_buf[0].set(self.dpsram.setup_h.read(SETUP_H::BM_REQUEST_TYPE) as u8);
1853                ep_buf[1].set(self.dpsram.setup_h.read(SETUP_H::B_REQUEST) as u8);
1854                ep_buf[2].set(self.dpsram.setup_h.read(SETUP_H::W_VALUE_L) as u8);
1855                ep_buf[3].set(self.dpsram.setup_h.read(SETUP_H::W_VALUE_H) as u8);
1856                ep_buf[4].set(self.dpsram.setup_l.read(SETUP_L::W_INDEX_L) as u8);
1857                ep_buf[5].set(self.dpsram.setup_l.read(SETUP_L::W_INDEX_H) as u8);
1858                ep_buf[6].set(self.dpsram.setup_l.read(SETUP_L::W_LENGTH_L) as u8);
1859                ep_buf[7].set(self.dpsram.setup_l.read(SETUP_L::W_LENGTH_H) as u8);
1860
1861                let size = self.dpsram.setup_l.read(SETUP_L::W_LENGTH_L)
1862                    + (self.dpsram.setup_l.read(SETUP_L::W_LENGTH_H) << 8);
1863                self.client.map(|client| {
1864                    // Notify the client that the ctrl setup event has occurred.
1865                    // Allow it to configure any data we need to send back.
1866                    match client.ctrl_setup(endpoint) {
1867                        hil::usb::CtrlSetupResult::OkSetAddress => {
1868                            self.should_set_address.set(true);
1869                            self.send_empty_in(endpoint);
1870                            self.descriptors[0]
1871                                .state
1872                                .set(EndpointState::Ctrl(CtrlState::ReadStatus));
1873                        }
1874                        hil::usb::CtrlSetupResult::Ok => {
1875                            // Setup request is successful.
1876                            if size == 0 {
1877                                // Directly handle a 0 length setup request.
1878                                self.send_empty_in(endpoint);
1879                            } else {
1880                                match self.dpsram.setup_h.read(SETUP_H::BM_REQUEST_TYPE) >> 7 {
1881                                    0 => {
1882                                        self.send_empty_in(endpoint);
1883
1884                                        self.transmit_out_ep0();
1885                                    }
1886                                    1 => {
1887                                        self.descriptors[endpoint]
1888                                            .state
1889                                            .set(EndpointState::Ctrl(CtrlState::ReadIn));
1890                                        // Transmit first packet.
1891                                        self.next_pid_in[endpoint].set(1);
1892                                        self.transmit_in_ep0();
1893                                    }
1894                                    _ => {
1895                                        unreachable!()
1896                                    }
1897                                }
1898                            }
1899                        }
1900                        _err => {
1901                            // An error occurred, we stall the endpoint.
1902                            self.registers
1903                                .ep_stall_arm
1904                                .modify(EP_STALL_ARM::EP0_IN::SET);
1905                            self.dpsram.ep_buf_ctrl[0]
1906                                .ep_in_buf_ctrl
1907                                .modify(EP_BUFFER_CONTROL::STALL::SET);
1908                        }
1909                    }
1910                });
1911            }
1912
1913            CtrlState::ReadIn | CtrlState::ReadStatus | CtrlState::WriteOut => {
1914                // Unexpected state to receive a SETUP packet. Let's STALL the endpoint.
1915                self.registers.sie_ctrl.write(SIE_CTRL::EP0_INT_STALL::SET);
1916            }
1917        }
1918    }
1919
1920    fn handle_ep0datadone(&self) {
1921        let endpoint = 0;
1922        let state = self.descriptors[endpoint].state.get().ctrl_state();
1923
1924        match state {
1925            CtrlState::ReadIn => {
1926                self.transmit_in_ep0();
1927            }
1928
1929            CtrlState::ReadStatus => {
1930                self.complete_ctrl_status();
1931            }
1932
1933            CtrlState::WriteOut => {
1934                // We just completed the Setup stage for a CTRL WRITE transfer.
1935                self.transmit_out_ep0();
1936            }
1937
1938            CtrlState::Init => {
1939                self.send_empty_in(0);
1940                self.complete_ctrl_status();
1941            }
1942        }
1943
1944        self.nop_wait();
1945
1946        self.dpsram.ep_buf_ctrl[0]
1947            .ep_in_buf_ctrl
1948            .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
1949    }
1950
1951    fn handle_endepin(&self, endpoint: usize) {
1952        match endpoint {
1953            0 => {}
1954            1..=N_ENDPOINTS => {
1955                let (transfer_type, _in_state, out_state) =
1956                    self.descriptors[endpoint].state.get().bulk_state();
1957                self.descriptors[endpoint].state.set(EndpointState::Bulk(
1958                    transfer_type,
1959                    Some(BulkInState::InData),
1960                    out_state,
1961                ));
1962            }
1963            _ => panic!("unexisting endpoint"),
1964        }
1965
1966        // Nothing else to do. Wait for the EPDATA event.
1967    }
1968
1969    fn handle_endepout(&self, endpoint: usize) {
1970        match endpoint {
1971            0 => {
1972                // We got data on the control endpoint during a CTRL WRITE
1973                // transfer. Let the client handle the data, and then finish up
1974                // the control write by moving to the status stage.
1975
1976                // Now we can handle it and pass it to the client to see
1977                // what the client returns.
1978
1979                if self.dpsram.ep0_buffer0[0].get() == 128
1980                    && self.dpsram.ep0_buffer0[1].get() == 37
1981                    && self.dpsram.ep0_buffer0[2].get() == 0
1982                {
1983                    self.dpsram.ep0_buffer0[0].set(0);
1984                    self.dpsram.ep0_buffer0[1].set(194);
1985                    self.dpsram.ep0_buffer0[2].set(1);
1986                }
1987
1988                self.transmit_out_ep0();
1989                self.client.map(|client| {
1990                    match client.ctrl_out(
1991                        endpoint,
1992                        self.dpsram.ep_buf_ctrl[endpoint]
1993                            .ep_out_buf_ctrl
1994                            .read(EP_BUFFER_CONTROL::TRANSFER_LENGTH0),
1995                    ) {
1996                        hil::usb::CtrlOutResult::Ok => {
1997                            // We only handle the simple case where we have
1998                            // received all of the data we need to.
1999                            self.complete_ctrl_status();
2000                        }
2001                        hil::usb::CtrlOutResult::Delay => {}
2002                        _ => {
2003                            // Respond with STALL to any following transactions
2004                            // in this request
2005                            self.registers
2006                                .ep_stall_arm
2007                                .modify(EP_STALL_ARM::EP0_OUT::SET);
2008                            self.dpsram.ep_buf_ctrl[0]
2009                                .ep_in_buf_ctrl
2010                                .modify(EP_BUFFER_CONTROL::STALL::SET);
2011                        }
2012                    }
2013                });
2014            }
2015            1..=N_ENDPOINTS => {
2016                // Notify the client about the new packet.
2017                let (transfer_type, in_state, out_state) =
2018                    self.descriptors[endpoint].state.get().bulk_state();
2019
2020                let packet_bytes = if let Some(BulkOutState::OutData { size }) = out_state {
2021                    size
2022                } else {
2023                    0
2024                };
2025
2026                self.client.map(|client| {
2027                    let result = client.packet_out(transfer_type, endpoint, packet_bytes);
2028                    let new_out_state = match result {
2029                        hil::usb::OutResult::Ok => {
2030                            if self.dpsram.ep_buf_ctrl[endpoint]
2031                                .ep_out_buf_ctrl
2032                                .read(EP_BUFFER_CONTROL::DATA_PID0)
2033                                == 0
2034                            {
2035                                self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.modify(
2036                                    EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(packet_bytes)
2037                                        + EP_BUFFER_CONTROL::DATA_PID0::SET
2038                                        + EP_BUFFER_CONTROL::BUFFER0_FULL::CLEAR,
2039                                );
2040                                self.next_pid_out[endpoint].set(0);
2041                            } else {
2042                                self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.modify(
2043                                    EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(packet_bytes)
2044                                        + EP_BUFFER_CONTROL::DATA_PID0::CLEAR
2045                                        + EP_BUFFER_CONTROL::BUFFER0_FULL::CLEAR,
2046                                );
2047                                self.next_pid_out[endpoint].set(1);
2048                            }
2049                            self.nop_wait();
2050                            self.dpsram.ep_buf_ctrl[endpoint]
2051                                .ep_out_buf_ctrl
2052                                .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2053                            BulkOutState::Init
2054                        }
2055
2056                        hil::usb::OutResult::Delay => {
2057                            // We can't send the packet now. Wait for a resume_out call from the client.
2058                            BulkOutState::OutDelay
2059                        }
2060
2061                        hil::usb::OutResult::Error => {
2062                            self.registers
2063                                .ep_stall_arm
2064                                .modify(EP_STALL_ARM::EP0_OUT::SET);
2065                            self.dpsram.ep_buf_ctrl[endpoint]
2066                                .ep_out_buf_ctrl
2067                                .modify(EP_BUFFER_CONTROL::STALL::SET);
2068                            BulkOutState::Init
2069                        }
2070                    };
2071                    self.descriptors[endpoint].state.set(EndpointState::Bulk(
2072                        transfer_type,
2073                        in_state,
2074                        Some(new_out_state),
2075                    ));
2076                });
2077            }
2078            _ => unreachable!("unexisting endpoint"),
2079        }
2080    }
2081
2082    fn transmit_in_ep0(&self) {
2083        let endpoint = 0;
2084        self.client.map(|client| {
2085            match client.ctrl_in(endpoint) {
2086                hil::usb::CtrlInResult::Packet(size, last) => {
2087                    if size == 0 {
2088                        internal_err!("Empty ctrl packet?");
2089                    }
2090                    let slice = self.descriptors[endpoint].slice_in.unwrap_or_panic();
2091
2092                    for idx in 0..size {
2093                        self.dpsram.ep0_buffer0[idx].set(slice[idx].get());
2094                    }
2095
2096                    if self.next_pid_in[endpoint].get() == 1 {
2097                        self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2098                            EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(size as u32)
2099                                + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2100                                + EP_BUFFER_CONTROL::DATA_PID0::SET,
2101                        );
2102                        self.next_pid_in[endpoint].set(0);
2103                    } else {
2104                        self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2105                            EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(size as u32)
2106                                + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2107                                + EP_BUFFER_CONTROL::DATA_PID0::CLEAR,
2108                        );
2109                        self.next_pid_in[endpoint].set(1);
2110                    }
2111                    self.nop_wait();
2112                    self.dpsram.ep_buf_ctrl[endpoint]
2113                        .ep_in_buf_ctrl
2114                        .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2115                    if last {
2116                        self.transmit_out_ep0();
2117                        self.complete_ctrl_status();
2118                    }
2119                }
2120
2121                hil::usb::CtrlInResult::Delay => {
2122                    self.registers.sie_ctrl.write(SIE_CTRL::EP0_INT_NAK::SET);
2123                }
2124
2125                hil::usb::CtrlInResult::Error => {
2126                    // An error occurred, we STALL
2127                    self.registers
2128                        .ep_stall_arm
2129                        .modify(EP_STALL_ARM::EP0_IN::SET);
2130                    self.registers.sie_ctrl.write(SIE_CTRL::EP0_INT_STALL::SET);
2131                    self.descriptors[endpoint]
2132                        .state
2133                        .set(EndpointState::Ctrl(CtrlState::Init));
2134                }
2135            }
2136        });
2137    }
2138
2139    fn transmit_out_ep0(&self) {
2140        let endpoint = 0;
2141
2142        let slice = self.descriptors[endpoint].slice_out.unwrap_or_panic();
2143
2144        for idx in 0..self.dpsram.ep_buf_ctrl[endpoint]
2145            .ep_out_buf_ctrl
2146            .read(EP_BUFFER_CONTROL::TRANSFER_LENGTH0) as usize
2147        {
2148            slice[idx].set(self.dpsram.ep0_buffer0[idx].get());
2149        }
2150
2151        if self.dpsram.ep_buf_ctrl[endpoint]
2152            .ep_out_buf_ctrl
2153            .read(EP_BUFFER_CONTROL::DATA_PID0)
2154            == 0
2155        {
2156            self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.modify(
2157                EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(slice.len() as u32)
2158                    + EP_BUFFER_CONTROL::DATA_PID0::SET
2159                    + EP_BUFFER_CONTROL::BUFFER0_FULL::CLEAR,
2160            );
2161            self.next_pid_out[endpoint].set(0);
2162            self.nop_wait();
2163            self.dpsram.ep_buf_ctrl[endpoint]
2164                .ep_out_buf_ctrl
2165                .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2166        } else {
2167            self.dpsram.ep_buf_ctrl[endpoint].ep_out_buf_ctrl.modify(
2168                EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(slice.len() as u32)
2169                    + EP_BUFFER_CONTROL::DATA_PID0::CLEAR
2170                    + EP_BUFFER_CONTROL::BUFFER0_FULL::CLEAR,
2171            );
2172            self.next_pid_out[endpoint].set(1);
2173            self.nop_wait();
2174            self.dpsram.ep_buf_ctrl[endpoint]
2175                .ep_out_buf_ctrl
2176                .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2177        }
2178    }
2179
2180    fn complete_ctrl_status(&self) {
2181        let endpoint = 0;
2182        self.client.map(|client| {
2183            client.ctrl_status(endpoint);
2184            if self.should_set_address.get() {
2185                self.should_set_address.set(false);
2186            }
2187            client.ctrl_status_complete(endpoint);
2188            self.descriptors[endpoint]
2189                .state
2190                .set(EndpointState::Ctrl(CtrlState::Init));
2191        });
2192    }
2193
2194    fn transmit_in(&self, endpoint: usize) {
2195        self.client.map(|client| {
2196            let (transfer_type, in_state, out_state) =
2197                self.descriptors[endpoint].state.get().bulk_state();
2198            assert_eq!(in_state, Some(BulkInState::Init));
2199
2200            let result = client.packet_in(transfer_type, endpoint);
2201
2202            let new_in_state = match result {
2203                hil::usb::InResult::Packet(size) => {
2204                    let slice = self.descriptors[endpoint].slice_in.unwrap_or_panic();
2205
2206                    self.counter.set(self.counter.get() + 1);
2207                    for idx in 0..size {
2208                        self.dpsram.buffers[(64 * (endpoint - 1)) + idx].set(slice[idx].get());
2209                    }
2210                    if self.next_pid_in[endpoint].get() == 1 {
2211                        self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2212                            EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(size as u32)
2213                                + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2214                                + EP_BUFFER_CONTROL::DATA_PID0::SET,
2215                        );
2216                        self.next_pid_in[endpoint].set(0);
2217                    } else {
2218                        self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2219                            EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(size as u32)
2220                                + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2221                                + EP_BUFFER_CONTROL::DATA_PID0::CLEAR,
2222                        );
2223                        self.next_pid_in[endpoint].set(1);
2224                    }
2225                    self.nop_wait();
2226                    self.dpsram.ep_buf_ctrl[endpoint]
2227                        .ep_in_buf_ctrl
2228                        .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2229                    self.descriptors[endpoint].request_transmit_in.set(false);
2230                    BulkInState::InData
2231                }
2232
2233                hil::usb::InResult::Delay => {
2234                    // No packet to send now. Wait for a resume call from the client.
2235                    BulkInState::Init
2236                }
2237
2238                hil::usb::InResult::Error => {
2239                    self.dpsram.ep_buf_ctrl[endpoint]
2240                        .ep_in_buf_ctrl
2241                        .modify(EP_BUFFER_CONTROL::STALL::SET);
2242                    BulkInState::Init
2243                }
2244            };
2245            self.descriptors[endpoint].state.set(EndpointState::Bulk(
2246                transfer_type,
2247                Some(new_in_state),
2248                out_state,
2249            ));
2250        });
2251    }
2252
2253    fn send_empty_in(&self, endpoint: usize) {
2254        match endpoint {
2255            0 => {
2256                self.dpsram.ep_buf_ctrl[0].ep_in_buf_ctrl.modify(
2257                    EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(0)
2258                        + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2259                        + EP_BUFFER_CONTROL::DATA_PID0::SET,
2260                );
2261                self.next_pid_in[endpoint].set(1);
2262                self.nop_wait();
2263                self.dpsram.ep_buf_ctrl[0]
2264                    .ep_in_buf_ctrl
2265                    .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2266            }
2267            1..=N_ENDPOINTS => {
2268                if self.dpsram.ep_buf_ctrl[endpoint]
2269                    .ep_in_buf_ctrl
2270                    .read(EP_BUFFER_CONTROL::DATA_PID0)
2271                    == 0
2272                {
2273                    self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2274                        EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(0)
2275                            + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2276                            + EP_BUFFER_CONTROL::DATA_PID0::SET,
2277                    );
2278                } else {
2279                    self.dpsram.ep_buf_ctrl[endpoint].ep_in_buf_ctrl.modify(
2280                        EP_BUFFER_CONTROL::TRANSFER_LENGTH0.val(0)
2281                            + EP_BUFFER_CONTROL::BUFFER0_FULL::SET
2282                            + EP_BUFFER_CONTROL::DATA_PID0::SET,
2283                    );
2284                }
2285                self.nop_wait();
2286                self.dpsram.ep_buf_ctrl[endpoint]
2287                    .ep_in_buf_ctrl
2288                    .modify(EP_BUFFER_CONTROL::AVAILABLE0::SET);
2289            }
2290            _ => unreachable!("unexisting endpoint"),
2291        }
2292    }
2293
2294    fn transmit_out(&self, endpoint: usize) {
2295        let size = self.dpsram.ep_buf_ctrl[endpoint]
2296            .ep_out_buf_ctrl
2297            .read(EP_BUFFER_CONTROL::TRANSFER_LENGTH0);
2298
2299        let slice = self.descriptors[endpoint].slice_out.unwrap_or_panic();
2300
2301        for idx in 0..size as usize {
2302            slice[idx].set(self.dpsram.buffers[(64 * (endpoint - 1)) + idx].get());
2303        }
2304        let (transfer_type, in_state, out_state) =
2305            self.descriptors[endpoint].state.get().bulk_state();
2306        // Starting the receiving can only happen in the OutData state, i.e. after an EPDATA event.
2307        assert!(matches!(out_state, Some(BulkOutState::OutData { .. })));
2308        self.descriptors[endpoint].request_transmit_out.set(false);
2309        let size = if let Some(BulkOutState::OutData { size }) = out_state {
2310            size
2311        } else {
2312            0
2313        };
2314
2315        self.descriptors[endpoint].state.set(EndpointState::Bulk(
2316            transfer_type,
2317            in_state,
2318            Some(BulkOutState::OutData { size }),
2319        ));
2320
2321        self.handle_endepout(endpoint);
2322    }
2323}
2324
2325impl<'a> hil::usb::UsbController<'a> for UsbCtrl<'a> {
2326    fn set_client(&self, client: &'a dyn hil::usb::Client<'a>) {
2327        self.client.set(client);
2328    }
2329
2330    fn endpoint_set_ctrl_buffer(&self, buf: &'a [VolatileCell<u8>]) {
2331        if buf.len() < 8 {
2332            panic!("Endpoint buffer must be at least 8 bytes");
2333        }
2334        if !buf.len().is_power_of_two() {
2335            panic!("Buffer size must be a power of 2");
2336        }
2337        self.descriptors[0].slice_in.set(buf);
2338        self.descriptors[0].slice_out.set(buf);
2339    }
2340
2341    fn endpoint_set_in_buffer(&self, endpoint: usize, buf: &'a [VolatileCell<u8>]) {
2342        if buf.len() < 8 {
2343            panic!("Endpoint buffer must be at least 8 bytes");
2344        }
2345        if !buf.len().is_power_of_two() {
2346            panic!("Buffer size must be a power of 2");
2347        }
2348        if endpoint == 0 || endpoint >= N_ENDPOINTS {
2349            panic!("Endpoint number is invalid");
2350        }
2351        self.descriptors[endpoint].slice_in.set(buf);
2352    }
2353
2354    fn endpoint_set_out_buffer(&self, endpoint: usize, buf: &'a [VolatileCell<u8>]) {
2355        if buf.len() < 8 {
2356            panic!("Endpoint buffer must be at least 8 bytes");
2357        }
2358        if !buf.len().is_power_of_two() {
2359            panic!("Buffer size must be a power of 2");
2360        }
2361        if endpoint == 0 || endpoint >= N_ENDPOINTS {
2362            panic!("Endpoint number is invalid");
2363        }
2364        self.descriptors[endpoint].slice_out.set(buf);
2365    }
2366
2367    fn enable_as_device(&self, speed: hil::usb::DeviceSpeed) {
2368        match speed {
2369            hil::usb::DeviceSpeed::Low => internal_err!("Low speed is not supported"),
2370            hil::usb::DeviceSpeed::Full => {}
2371        }
2372        self.start();
2373    }
2374
2375    fn attach(&self) {
2376        self.enable_pullup();
2377    }
2378
2379    fn detach(&self) {
2380        self.disable_pullup();
2381    }
2382
2383    fn set_address(&self, addr: u16) {
2384        self.address.set(addr as u32);
2385    }
2386
2387    fn enable_address(&self) {
2388        self.registers
2389            .addr_endp
2390            .modify(ADDR_ENDP::ADDRESS.val(self.address.get()));
2391    }
2392
2393    fn endpoint_in_enable(&self, transfer_type: TransferType, endpoint: usize) {
2394        match transfer_type {
2395            TransferType::Control => {
2396                panic!("There is no IN control endpoint");
2397            }
2398            TransferType::Bulk | TransferType::Interrupt => {
2399                if endpoint == 0 || endpoint >= N_ENDPOINTS {
2400                    panic!("Bulk/Interrupt endpoints are endpoints 1 to 7");
2401                }
2402                self.enable_in_endpoint_(transfer_type, endpoint);
2403            }
2404            TransferType::Isochronous => unimplemented!("isochronous endpoint"),
2405        }
2406    }
2407
2408    fn endpoint_out_enable(&self, transfer_type: TransferType, endpoint: usize) {
2409        match transfer_type {
2410            TransferType::Control => {
2411                if endpoint != 0 {
2412                    panic!("Only endpoint 0 can be a control endpoint");
2413                }
2414                self.enable_out_endpoint_(transfer_type, endpoint);
2415            }
2416            TransferType::Bulk | TransferType::Interrupt => {
2417                if endpoint == 0 || endpoint >= N_ENDPOINTS {
2418                    panic!("Bulk/Interrupt endpoints are endpoints 1 to 7");
2419                }
2420                self.enable_out_endpoint_(transfer_type, endpoint);
2421            }
2422            TransferType::Isochronous => unimplemented!("isochronous endpoint"),
2423        }
2424    }
2425
2426    fn endpoint_in_out_enable(&self, transfer_type: TransferType, endpoint: usize) {
2427        match transfer_type {
2428            TransferType::Control => {
2429                panic!("There is no IN control endpoint");
2430            }
2431            TransferType::Bulk | TransferType::Interrupt => {
2432                if endpoint == 0 || endpoint >= N_ENDPOINTS {
2433                    panic!("Bulk/Interrupt endpoints are endpoints 1 to 7");
2434                }
2435            }
2436            TransferType::Isochronous => unimplemented!("isochronous endpoint"),
2437        }
2438    }
2439
2440    fn endpoint_resume_in(&self, endpoint: usize) {
2441        // Get the state of the endpoint that the upper layer requested to start
2442        // an IN transfer with for our state machine.
2443        let (_, in_state, _) = self.descriptors[endpoint].state.get().bulk_state();
2444        // If the state is `None`, this endpoint is not configured and should
2445        // not have been used to call `endpoint_resume_in()`.
2446        assert!(in_state.is_some());
2447
2448        // If there is an active request, or we are waiting on finishing up
2449        // a previous IN transfer, we queue this request and it will be serviced
2450        // after those complete.
2451        if in_state == Some(BulkInState::Init) {
2452            // If we aren't waiting on anything, trigger the transaction now.
2453            self.transmit_in(endpoint);
2454        } else {
2455            self.descriptors[endpoint].request_transmit_in.set(true);
2456        }
2457    }
2458
2459    fn endpoint_resume_out(&self, endpoint: usize) {
2460        let (transfer_type, in_state, out_state) =
2461            self.descriptors[endpoint].state.get().bulk_state();
2462        assert!(out_state.is_some());
2463
2464        match out_state.unwrap() {
2465            BulkOutState::OutDelay => {
2466                // The endpoint has now finished processing the last ENDEPOUT. No EPDATA event
2467                // happened in the meantime, so the state is now back to Init.
2468                self.descriptors[endpoint].state.set(EndpointState::Bulk(
2469                    transfer_type,
2470                    in_state,
2471                    Some(BulkOutState::Init),
2472                ));
2473            }
2474            BulkOutState::OutData { size: _ } => {
2475                // Although the client reported a delay before, an EPDATA event has
2476                // happened in the meantime. This pending transaction will now
2477                // continue in transmit_out().
2478                self.transmit_out(endpoint);
2479            }
2480            BulkOutState::Init => {
2481                internal_err!("Unexpected state: {:?}", out_state);
2482            }
2483        }
2484    }
2485}