summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHiFiPhile <[email protected]>2026-06-23 23:12:51 +0200
committerHiFiPhile <[email protected]>2026-06-23 23:12:51 +0200
commit033dc6bb77e8a9e1c1172d74d47707848b5c5bf5 (patch)
treee7672f9bda54aa1a243b2a1c0f74a48055569c63
parentb5e63ca44c846813ece9ad9df684cae0d1d5b542 (diff)
parentcd3561bf158afd5a5718904b8139a338d1e3b67c (diff)
Merge remote-tracking branch 'tinyusb/master' into fix-stm32-usbc
-rw-r--r--.claude/commands/hil.md58
-rw-r--r--.claude/skills/code-size/SKILL.md76
-rw-r--r--.claude/skills/hil/SKILL.md64
-rw-r--r--.claude/skills/pvs/SKILL.md36
-rwxr-xr-x.claude/skills/pvs/run_pvs.sh85
-rw-r--r--.gitattributes3
-rw-r--r--.github/FUNDING.yml1
-rw-r--r--.github/labeler.yml77
-rw-r--r--.github/workflows/build.yml105
-rw-r--r--.github/workflows/build_util.yml2
-rwxr-xr-x.github/workflows/ci_set_matrix.py2
-rw-r--r--.github/workflows/claude-code-review.yml40
-rw-r--r--.github/workflows/claude.yml47
-rw-r--r--.github/workflows/labeler.yml159
-rw-r--r--.github/workflows/metrics_comment.yml39
-rw-r--r--.github/workflows/pr_comment.yml131
-rw-r--r--.gitignore35
-rw-r--r--AGENTS.md480
-rw-r--r--README.rst216
-rw-r--r--docs/assets/adafruit_logo.svg6
-rw-r--r--docs/assets/stack.svg2
-rwxr-xr-xdocs/conf.py19
-rw-r--r--docs/reference/boards.rst2
-rw-r--r--docs/reference/class_drivers.rst316
-rw-r--r--docs/reference/dependencies.rst4
-rw-r--r--docs/reference/device_issues.rst35
-rw-r--r--docs/reference/index.rst2
-rw-r--r--docs/troubleshooting.rst2
-rw-r--r--examples/device/CMakeLists.txt2
-rw-r--r--examples/device/audio_4_channel_mic/skip.txt1
-rwxr-xr-xexamples/device/audio_4_channel_mic/src/plot_audio_samples.py49
-rw-r--r--examples/device/audio_4_channel_mic/src/usb_descriptors.c8
-rw-r--r--examples/device/audio_4_channel_mic_freertos/CMakeLists.txt5
-rw-r--r--examples/device/audio_4_channel_mic_freertos/skip.txt1
-rwxr-xr-xexamples/device/audio_4_channel_mic_freertos/src/plot_audio_samples.py50
-rw-r--r--examples/device/audio_4_channel_mic_freertos/src/usb_descriptors.c4
-rw-r--r--examples/device/audio_test/skip.txt1
-rwxr-xr-xexamples/device/audio_test/src/plot_audio_samples.py50
-rw-r--r--examples/device/audio_test/src/usb_descriptors.c8
-rw-r--r--examples/device/audio_test_freertos/CMakeLists.txt5
-rw-r--r--examples/device/audio_test_freertos/sdkconfig.defaults3
-rw-r--r--examples/device/audio_test_freertos/skip.txt1
-rwxr-xr-xexamples/device/audio_test_freertos/src/plot_audio_samples.py50
-rw-r--r--examples/device/audio_test_freertos/src/usb_descriptors.c4
-rw-r--r--examples/device/audio_test_multi_rate/skip.txt1
-rw-r--r--examples/device/audio_test_multi_rate/src/main.c2
-rwxr-xr-xexamples/device/audio_test_multi_rate/src/plot_audio_samples.py50
-rw-r--r--examples/device/audio_test_multi_rate/src/usb_descriptors.c8
-rw-r--r--examples/device/board_test/CMakeLists.txt5
-rw-r--r--examples/device/board_test/src/main.c26
-rw-r--r--examples/device/cdc_dual_ports/src/usb_descriptors.c25
-rw-r--r--examples/device/cdc_msc/src/usb_descriptors.c22
-rw-r--r--examples/device/cdc_msc_freertos/CMakeLists.txt5
-rw-r--r--examples/device/cdc_msc_freertos/skip.txt1
-rw-r--r--examples/device/cdc_msc_freertos/src/main.c6
-rw-r--r--examples/device/cdc_msc_freertos/src/usb_descriptors.c22
-rw-r--r--examples/device/cdc_msc_throughput/CMakeLists.txt35
-rw-r--r--examples/device/cdc_msc_throughput/CMakePresets.json6
-rw-r--r--examples/device/cdc_msc_throughput/Makefile11
-rw-r--r--examples/device/cdc_msc_throughput/src/main.c151
-rw-r--r--examples/device/cdc_msc_throughput/src/tusb_config.h103
-rw-r--r--examples/device/cdc_msc_throughput/src/usb_descriptors.c186
-rw-r--r--examples/device/cdc_uac2/skip.txt1
-rw-r--r--examples/device/cdc_uac2/src/uac2_app.c132
-rw-r--r--examples/device/cdc_uac2/src/usb_descriptors.c22
-rw-r--r--examples/device/dfu/skip.txt1
-rw-r--r--examples/device/dfu_runtime/skip.txt1
-rw-r--r--examples/device/dynamic_configuration/src/usb_descriptors.c2
-rw-r--r--examples/device/hid_boot_interface/skip.txt1
-rw-r--r--examples/device/hid_composite/skip.txt1
-rw-r--r--examples/device/hid_composite_freertos/CMakeLists.txt5
-rw-r--r--examples/device/hid_composite_freertos/skip.txt1
-rw-r--r--examples/device/hid_generic_inout/skip.txt1
-rw-r--r--examples/device/hid_generic_inout/src/usb_descriptors.c2
-rw-r--r--examples/device/hid_multiple_interface/skip.txt1
-rw-r--r--examples/device/midi2_device/CMakeLists.txt35
-rw-r--r--examples/device/midi2_device/CMakePresets.json6
-rw-r--r--examples/device/midi2_device/Makefile16
-rw-r--r--examples/device/midi2_device/README.md59
-rw-r--r--examples/device/midi2_device/skip.txt1
-rw-r--r--examples/device/midi2_device/src/main.c718
-rw-r--r--examples/device/midi2_device/src/tusb_config.h88
-rw-r--r--examples/device/midi2_device/src/usb_descriptors.c146
-rw-r--r--examples/device/midi_test/skip.txt1
-rw-r--r--examples/device/midi_test/src/usb_descriptors.c2
-rw-r--r--examples/device/midi_test_freertos/skip.txt1
-rw-r--r--examples/device/midi_test_freertos/src/usb_descriptors.c2
-rw-r--r--examples/device/msc_dual_lun/src/main.c2
-rw-r--r--examples/device/msc_dual_lun/src/usb_descriptors.c12
-rw-r--r--examples/device/mtp/src/mtp_fs_example.c44
-rw-r--r--examples/device/mtp/src/tusb_config.h1
-rw-r--r--examples/device/mtp/src/usb_descriptors.c2
-rw-r--r--examples/device/net_lwip_webserver/skip.txt2
-rw-r--r--examples/device/net_lwip_webserver/src/lwipopts.h20
-rw-r--r--examples/device/net_lwip_webserver/src/tusb_config.h40
-rw-r--r--examples/device/net_lwip_webserver/src/usb_descriptors.c181
-rw-r--r--examples/device/printer_to_cdc/CMakePresets.json6
-rw-r--r--examples/device/printer_to_cdc/src/usb_descriptors.c21
-rw-r--r--examples/device/uac2_headset/skip.txt1
-rw-r--r--examples/device/uac2_headset/src/main.c132
-rw-r--r--examples/device/uac2_headset/src/usb_descriptors.c15
-rw-r--r--examples/device/uac2_speaker_fb/skip.txt1
-rw-r--r--examples/device/uac2_speaker_fb/src/main.c132
-rw-r--r--examples/device/uac2_speaker_fb/src/usb_descriptors.c15
-rw-r--r--examples/device/usbtmc/src/usb_descriptors.c14
-rw-r--r--examples/device/video_capture/skip.txt1
-rw-r--r--examples/device/video_capture_2ch/skip.txt1
-rw-r--r--examples/device/webusb_serial/skip.txt1
-rw-r--r--examples/device/webusb_serial/src/usb_descriptors.c22
-rw-r--r--examples/dual/dynamic_switch/only.txt1
-rw-r--r--examples/dual/dynamic_switch/src/main.c159
-rw-r--r--examples/dual/dynamic_switch/src/usb_descriptors.c2
-rw-r--r--examples/dual/host_info_to_device_cdc/src/main.c6
-rw-r--r--examples/host/CMakeLists.txt2
-rw-r--r--examples/host/bare_api/only.txt1
-rw-r--r--examples/host/bare_api/src/main.c43
-rw-r--r--examples/host/cdc_msc_hid/only.txt1
-rw-r--r--examples/host/cdc_msc_hid/src/cdc_app.c6
-rw-r--r--examples/host/cdc_msc_hid_freertos/only.txt1
-rw-r--r--examples/host/cdc_msc_hid_freertos/src/cdc_app.c10
-rw-r--r--examples/host/device_info/only.txt1
-rw-r--r--examples/host/device_info/src/main.c71
-rw-r--r--examples/host/midi2_host/CMakeLists.txt29
-rw-r--r--examples/host/midi2_host/CMakePresets.json6
-rw-r--r--examples/host/midi2_host/Makefile13
-rw-r--r--examples/host/midi2_host/only.txt34
-rw-r--r--examples/host/midi2_host/skip.txt1
-rw-r--r--examples/host/midi2_host/src/main.c163
-rw-r--r--examples/host/midi2_host/src/tusb_config.h106
-rw-r--r--examples/host/midi_rx/only.txt1
-rw-r--r--examples/host/msc_file_explorer/only.txt1
-rw-r--r--examples/host/msc_file_explorer_freertos/CMakeLists.txt42
-rw-r--r--examples/host/msc_file_explorer_freertos/CMakePresets.json6
-rw-r--r--examples/host/msc_file_explorer_freertos/Makefile27
-rw-r--r--examples/host/msc_file_explorer_freertos/README.md105
-rw-r--r--examples/host/msc_file_explorer_freertos/only.txt28
-rw-r--r--examples/host/msc_file_explorer_freertos/skip.txt4
-rw-r--r--examples/host/msc_file_explorer_freertos/src/CMakeLists.txt13
-rw-r--r--examples/host/msc_file_explorer_freertos/src/ffconf.h313
-rw-r--r--examples/host/msc_file_explorer_freertos/src/main.c158
-rw-r--r--examples/host/msc_file_explorer_freertos/src/msc_app.c709
-rw-r--r--examples/host/msc_file_explorer_freertos/src/msc_app.h34
-rw-r--r--examples/host/msc_file_explorer_freertos/src/tusb_config.h126
-rw-r--r--hw/bsp/BoardPresets.json48
-rw-r--r--hw/bsp/at32f402_405/family.c2
-rw-r--r--hw/bsp/at32f403a_407/family.c2
-rw-r--r--hw/bsp/at32f413/family.c2
-rw-r--r--hw/bsp/at32f415/family.c2
-rw-r--r--hw/bsp/at32f423/family.c2
-rw-r--r--hw/bsp/at32f425/family.c2
-rw-r--r--hw/bsp/at32f435_437/family.c2
-rw-r--r--hw/bsp/at32f45x/family.c2
-rw-r--r--hw/bsp/board.c6
-rw-r--r--hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.cmake8
-rw-r--r--hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.h27
-rw-r--r--hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.mk5
-rw-r--r--hw/bsp/ch32v10x/family.c22
-rw-r--r--hw/bsp/ch32v10x/linker/ch32v10x.ld23
-rw-r--r--hw/bsp/ch32v20x/family.c2
-rw-r--r--hw/bsp/ch32v20x/family.cmake3
-rw-r--r--hw/bsp/ch32v20x/linker/ch32v20x.ld23
-rw-r--r--hw/bsp/ch32v30x/linker/ch32v30x.ld24
-rw-r--r--hw/bsp/ch583/boards/ch582m_evt/board.cmake5
-rw-r--r--hw/bsp/ch583/boards/ch582m_evt/board.h61
-rw-r--r--hw/bsp/ch583/boards/ch582m_evt/board.mk3
-rw-r--r--hw/bsp/ch583/boards/yd-ch582m/board.cmake5
-rw-r--r--hw/bsp/ch583/boards/yd-ch582m/board.h61
-rw-r--r--hw/bsp/ch583/boards/yd-ch582m/board.mk3
-rw-r--r--hw/bsp/ch583/ch583_it.c37
-rw-r--r--hw/bsp/ch583/ch583_it.h46
-rw-r--r--hw/bsp/ch583/debug_uart.c86
-rw-r--r--hw/bsp/ch583/debug_uart.h44
-rw-r--r--hw/bsp/ch583/family.c194
-rw-r--r--hw/bsp/ch583/family.cmake108
-rw-r--r--hw/bsp/ch583/family.mk59
-rw-r--r--hw/bsp/ch583/linker/ch582.ld167
-rw-r--r--hw/bsp/ch583/system_ch583.c39
-rw-r--r--hw/bsp/ch583/system_ch583.h43
-rw-r--r--hw/bsp/ch583/wch-riscv.cfg17
-rw-r--r--hw/bsp/espressif/boards/family.c8
-rw-r--r--hw/bsp/espressif/family.cmake24
-rw-r--r--hw/bsp/family_support.cmake68
-rw-r--r--hw/bsp/ft9xx/family.c5
-rw-r--r--hw/bsp/gd32vf103/family.c2
-rw-r--r--hw/bsp/imxrt/boards/metro_m7_1011/board.cmake1
-rw-r--r--hw/bsp/imxrt/boards/metro_m7_1011/board.mk2
-rw-r--r--hw/bsp/imxrt/boards/mimxrt1010_evk/board.cmake1
-rw-r--r--hw/bsp/imxrt/boards/mimxrt1010_evk/board.mk2
-rw-r--r--hw/bsp/imxrt/boards/mimxrt1015_evk/board.cmake1
-rw-r--r--hw/bsp/imxrt/boards/mimxrt1015_evk/board.mk2
-rw-r--r--hw/bsp/kinetis_k/family.c2
-rw-r--r--hw/bsp/lpc55/boards/lpcxpresso55s69/board.cmake1
-rw-r--r--hw/bsp/mm32/family.c8
-rw-r--r--hw/bsp/nrf/boards/nrf54h20dk/board.cmake3
-rw-r--r--hw/bsp/nrf/boards/nrf54h20dk/board.mk5
-rw-r--r--hw/bsp/nrf/boards/nrf54lm20dk/board.cmake5
-rw-r--r--hw/bsp/pic32mz/family.c4
-rw-r--r--hw/bsp/rp2040/family.c2
-rw-r--r--hw/bsp/rp2040/family.cmake3
-rw-r--r--hw/bsp/samd11/family.c4
-rw-r--r--hw/bsp/samd2x_l2x/family.c2
-rw-r--r--hw/bsp/samg/family.c4
-rw-r--r--hw/bsp/stm32c0/family.c2
-rw-r--r--hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h165
-rw-r--r--hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake13
-rw-r--r--hw/bsp/stm32c5/boards/stm32c542nucleo/board.h83
-rw-r--r--hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk13
-rw-r--r--hw/bsp/stm32c5/family.c250
-rw-r--r--hw/bsp/stm32c5/family.cmake111
-rw-r--r--hw/bsp/stm32c5/family.mk52
-rw-r--r--hw/bsp/stm32c5/linker/stm32c542xc_flash.icf46
-rw-r--r--hw/bsp/stm32c5/linker/stm32c542xc_flash.ld185
-rw-r--r--hw/bsp/stm32c5/stm32c5xx_hal_conf.h684
-rw-r--r--hw/bsp/stm32f0/family.c2
-rw-r--r--hw/bsp/stm32f1/family.c12
-rw-r--r--hw/bsp/stm32f2/family.c2
-rw-r--r--hw/bsp/stm32f3/family.c9
-rw-r--r--hw/bsp/stm32f4/family.c7
-rw-r--r--hw/bsp/stm32f7/boards/stm32f746disco/board.cmake2
-rw-r--r--hw/bsp/stm32f7/boards/stm32f769disco/board.cmake1
-rw-r--r--hw/bsp/stm32f7/family.c23
-rw-r--r--hw/bsp/stm32g0/family.c2
-rw-r--r--hw/bsp/stm32g4/family.c12
-rw-r--r--hw/bsp/stm32h5/boards/stm32h573i_dk/board.h5
-rw-r--r--hw/bsp/stm32h5/family.c2
-rw-r--r--hw/bsp/stm32h7/family.c2
-rw-r--r--hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h5
-rw-r--r--hw/bsp/stm32h7rs/family.c2
-rw-r--r--hw/bsp/stm32l0/family.c2
-rw-r--r--hw/bsp/stm32l4/family.c2
-rw-r--r--hw/bsp/stm32n6/boards/stm32n6570dk/board.h5
-rw-r--r--hw/bsp/stm32n6/boards/stm32n657nucleo/board.h5
-rw-r--r--hw/bsp/stm32n6/family.c2
-rw-r--r--hw/bsp/stm32u0/family.c15
-rw-r--r--hw/bsp/stm32u5/family.c2
-rw-r--r--hw/bsp/stm32wb/family.c2
-rw-r--r--hw/bsp/tm4c/family.c10
-rw-r--r--hw/bsp/tm4c/family.cmake4
-rw-r--r--hw/bsp/xmc4000/family.c2
-rw-r--r--lib/networking/rndis_reports.c8
-rw-r--r--src/CMakeLists.txt3
-rw-r--r--src/class/audio/audio.h32
-rw-r--r--src/class/cdc/cdc_host.c92
-rw-r--r--src/class/hid/hid_host.c33
-rw-r--r--src/class/hid/hid_host.h2
-rw-r--r--src/class/midi/midi.h18
-rw-r--r--src/class/midi/midi2_device.c769
-rw-r--r--src/class/midi/midi2_device.h193
-rw-r--r--src/class/midi/midi2_host.c635
-rw-r--r--src/class/midi/midi2_host.h107
-rw-r--r--src/class/midi/midi_host.h7
-rw-r--r--src/class/mtp/mtp_device.c15
-rw-r--r--src/class/net/ecm_rndis_device.c22
-rw-r--r--src/class/net/ncm.h14
-rw-r--r--src/class/net/ncm_device.c117
-rw-r--r--src/class/net/net_device.h20
-rw-r--r--src/class/printer/printer_device.c1
-rw-r--r--src/class/video/video_device.c2
-rw-r--r--src/common/tusb_compiler.h9
-rw-r--r--src/common/tusb_fifo.c8
-rw-r--r--src/common/tusb_mcu.h74
-rw-r--r--src/common/tusb_private.h19
-rw-r--r--src/common/tusb_types.h34
-rw-r--r--src/device/dcd.h5
-rw-r--r--src/device/usbd.c519
-rw-r--r--src/device/usbd.h53
-rw-r--r--src/device/usbd_control.c217
-rw-r--r--src/device/usbd_pvt.h4
-rw-r--r--src/host/usbh.c369
-rw-r--r--src/osal/osal.h39
-rw-r--r--src/osal/osal_freertos.h13
-rw-r--r--src/osal/osal_mynewt.h6
-rw-r--r--src/osal/osal_none.h16
-rw-r--r--src/osal/osal_pico.h7
-rw-r--r--src/osal/osal_rtthread.h6
-rw-r--r--src/osal/osal_rtx4.h6
-rw-r--r--src/osal/osal_threadx.h5
-rw-r--r--src/osal/osal_zephyr.h6
-rw-r--r--src/portable/chipidea/ci_fs/dcd_ci_fs.c14
-rw-r--r--src/portable/dialog/da146xx/dcd_da146xx.c42
-rw-r--r--src/portable/mentor/musb/dcd_musb.c801
-rw-r--r--src/portable/mentor/musb/musb_max32.h2
-rw-r--r--src/portable/mentor/musb/musb_ti.h2
-rw-r--r--src/portable/mentor/musb/musb_type.h14
-rw-r--r--src/portable/microchip/samg/dcd_samg.c4
-rw-r--r--src/portable/nordic/nrf5x/dcd_nrf5x.c10
-rw-r--r--src/portable/nuvoton/nuc120/dcd_nuc120.c8
-rw-r--r--src/portable/nuvoton/nuc121/dcd_nuc121.c8
-rw-r--r--src/portable/nuvoton/nuc505/dcd_nuc505.c6
-rw-r--r--src/portable/nxp/lpc17_40/dcd_lpc17_40.c4
-rw-r--r--src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c10
-rw-r--r--src/portable/raspberrypi/rp2040/hcd_rp2040.c12
-rw-r--r--src/portable/renesas/rusb2/dcd_rusb2.c34
-rw-r--r--src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c43
-rw-r--r--src/portable/st/stm32_fsdev/fsdev_common.c4
-rw-r--r--src/portable/st/stm32_fsdev/fsdev_common.h4
-rw-r--r--src/portable/st/stm32_fsdev/fsdev_stm32.h86
-rw-r--r--src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c50
-rw-r--r--src/portable/synopsys/dwc2/dcd_dwc2.c154
-rw-r--r--src/portable/synopsys/dwc2/dwc2_esp32.h12
-rw-r--r--src/portable/synopsys/dwc2/hcd_dwc2.c56
-rw-r--r--src/portable/wch/ch32_usbfs_reg.h211
-rw-r--r--src/portable/wch/dcd_ch32_usbfs.c457
-rw-r--r--src/portable/wch/dcd_ch32_usbhs.c434
-rw-r--r--src/tinyusb.mk3
-rw-r--r--src/tusb.c17
-rw-r--r--src/tusb.h8
-rw-r--r--src/tusb_option.h36
-rw-r--r--test/fuzz/rules.mk1
-rw-r--r--test/hil/hfp.json4
-rw-r--r--test/hil/hil_ci.sh114
-rw-r--r--test/hil/hil_ci_set_matrix.py83
-rwxr-xr-xtest/hil/hil_test.py964
-rw-r--r--test/hil/requirements.txt11
-rw-r--r--test/hil/tinyusb.json343
-rw-r--r--test/unit-test/CMakeLists.txt4
-rw-r--r--test/unit-test/test/device/midi2/test_midi2_device.c266
-rw-r--r--test/unit-test/test/device/usbd/test_usbd.c52
-rw-r--r--test/unit-test/test/host/midi2/test_midi2_host.c101
-rwxr-xr-xtools/build.py30
-rw-r--r--tools/codespell/ignore-words.txt1
-rwxr-xr-xtools/gen_presets.py4
-rwxr-xr-xtools/get_deps.py13
-rw-r--r--tools/metrics.py10
-rw-r--r--tools/metrics_compare_base.py350
325 files changed, 15477 insertions, 3098 deletions
diff --git a/.claude/commands/hil.md b/.claude/commands/hil.md
deleted file mode 100644
index 07e1a865b..000000000
--- a/.claude/commands/hil.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# hil
-
-Run Hardware-in-the-Loop (HIL) tests on physical boards.
-
-## Arguments
-- $ARGUMENTS: Optional flags (e.g. board name, extra args). If empty, runs all boards with default config.
-
-## Instructions
-
-1. Parse $ARGUMENTS:
- - If $ARGUMENTS contains `-b BOARD_NAME`, run for that specific board only.
- - If $ARGUMENTS is empty or has no `-b`, run for all boards in the config.
- - Pass through any other flags (e.g. `-v` for verbose, `-r N` for retry count) directly to the command.
-
-2. Determine whether to run **locally** or **remotely via SSH**:
- - **Local**: boards are attached to this machine (default when `local.json` is used)
- - **Remote (`ssh ci.lan`)**: boards are attached to the CI machine (when `tinyusb.json` is used)
-
-3. **Local execution** (boards attached to this machine):
- ```bash
- python test/hil/hil_test.py -b BOARD_NAME -B examples $HIL_CONFIG $EXTRA_ARGS
- ```
-
-4. **Remote execution** (boards attached to `ci.lan`):
- Only copy the minimal files needed (firmware binaries + test script + config), then run remotely.
-
- ```bash
- REMOTE=ci.lan
- REMOTE_DIR=/tmp/tinyusb-hil
-
- # Create remote working directory
- ssh $REMOTE "rm -rf $REMOTE_DIR && mkdir -p $REMOTE_DIR/test/hil"
-
- # Copy HIL test script and its dependency
- scp test/hil/hil_test.py test/hil/pymtp.py test/hil/tinyusb.json $REMOTE:$REMOTE_DIR/test/hil/
-
- # Copy only the firmware binaries for the target board(s)
- # For a specific board:
- scp -r examples/cmake-build-$BOARD_NAME $REMOTE:$REMOTE_DIR/examples/
-
- # Or for all boards that have been built:
- # for dir in examples/cmake-build-*/; do scp -r "$dir" $REMOTE:$REMOTE_DIR/examples/; done
-
- # Run the test remotely
- ssh $REMOTE "cd $REMOTE_DIR && python3 test/hil/hil_test.py -b $BOARD_NAME -B examples tinyusb.json $EXTRA_ARGS"
- ```
-
- Note: The remote machine (`ci.lan`) must have:
- - Python 3 with `pyserial` installed (`pip install pyserial`)
- - Flasher tools: `JLinkExe`, `openocd`, etc. as needed by the board
- - USB access to the boards (udev rules configured)
-
-5. Use a timeout of at least 20 minutes (600000ms). HIL tests take 2-5 minutes. NEVER cancel early.
-
-6. After the test completes:
- - Show the test output to the user.
- - Summarize pass/fail results per board.
- - If there are failures, suggest re-running with `-v` flag for verbose output to help debug.
diff --git a/.claude/skills/code-size/SKILL.md b/.claude/skills/code-size/SKILL.md
new file mode 100644
index 000000000..f3c51ccfa
--- /dev/null
+++ b/.claude/skills/code-size/SKILL.md
@@ -0,0 +1,76 @@
+---
+name: code-size
+description: Use when comparing TinyUSB code size between a base ref (master by default) and the current branch to evaluate the size impact of changes. Three granularities — single example on one board (with optional bloaty), all examples on one board, or all examples across CI families combined.
+---
+
+# Code Size Comparison
+
+Compare TinyUSB code size between a base ref (default `master`) and the current branch using `tools/metrics_compare_base.py`. Three granularities — pick the narrowest one that exercises your change:
+
+| Granularity | When to use | Command |
+|---|---|---|
+| **single example, one board** | Focused change touching one feature | `-b BOARD -e device/cdc_msc` |
+| **all examples, one board** | Per-board regression sweep | `-b BOARD` |
+| **all examples, all CI families (combined)** | Pre-merge full check | `--ci` |
+
+The script handles the full base-vs-branch dance:
+1. Creates a temporary git worktree of the base ref under `cmake-metrics/_worktree/`.
+2. Builds the base in `cmake-metrics/<board>/base/`.
+3. Builds the current tree in `cmake-metrics/<board>/build/`.
+4. Runs `tools/metrics.py compare` and writes `cmake-metrics/<board>/metrics_compare.md`.
+5. Removes the worktree on exit.
+
+`--combined` (auto-set by `--ci`) also produces `cmake-metrics/_combined/metrics_compare.md` aggregating across all boards.
+
+## Choosing arguments
+
+Infer from the user's request:
+
+- **Board(s):** named board → `-b BOARD` (repeatable). "All boards" / "CI" / "full sweep" → `--ci` (first board of each arm-gcc family). Default to a fast board (`raspberry_pi_pico`) if unspecified for an iterative check.
+- **Example:** named example → `-e <group>/<name>` (e.g. `-e device/cdc_msc`). "All examples" → omit `-e`.
+- **Bloaty:** only with `-e`. Use when the user wants a section/symbol-level breakdown for a single binary.
+- **Base ref:** default `master`. Override with `--base-branch <ref>` (tag or commit also works).
+- **Filter:** default is the absolute path of each side's `<checkout>/src/` directory, which uniquely identifies TinyUSB stack code without matching vendored deps that also have a `src/` (e.g. `pico-sdk/src/`). Override with one or more `-f SUBSTRING` flags to use repo-relative substrings instead. Change only if asked.
+
+## Common invocations
+
+```bash
+# Single example, one board (linkermap, fastest):
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico -e device/cdc_msc
+
+# Same with bloaty for section/symbol breakdown:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico -e device/cdc_msc --bloaty
+
+# All examples for one board:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico
+
+# Multiple boards, one combined report:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico -b raspberry_pi_pico2 --combined
+
+# Full CI sweep (first board per arm-gcc family, combined):
+python3 tools/metrics_compare_base.py --ci
+
+# Compare against a tag/commit instead of master:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico --base-branch v0.18.0
+```
+
+## Outputs
+
+- **Per-board:** `cmake-metrics/<board>/metrics_compare.md` (and `_<example>.md` when `-e` is set)
+- **Combined (with `--combined`/`--ci`):** `cmake-metrics/_combined/metrics_compare.md`
+- **Bloaty:** printed to stdout as section + symbol diffs
+
+## Timing
+
+- Single example, single board: ~30 s
+- All examples, single board: ~60-90 s
+- `--ci` (all arm-gcc families, first board each): 4-8 minutes — sequential sweep across boards (Ninja parallelizes within each board, not across)
+
+Use timeouts ≥ 10 minutes (600000 ms) for `--ci`.
+
+## Reporting results
+
+After running:
+- Show the markdown report's summary table to the user.
+- Highlight any rows with non-zero `% diff` — under the default filter every row is a TinyUSB stack source file (e.g. `usbd.c`, `cdc_device.c`, `dcd_<port>.c`), so any non-zero delta is a real stack-size impact.
+- If the diff is unexpected, follow up with a single-example `--bloaty` run to localize.
diff --git a/.claude/skills/hil/SKILL.md b/.claude/skills/hil/SKILL.md
new file mode 100644
index 000000000..a7a916907
--- /dev/null
+++ b/.claude/skills/hil/SKILL.md
@@ -0,0 +1,64 @@
+---
+name: hil
+description: Use when running TinyUSB Hardware-in-the-Loop (HIL) tests on physical boards, debugging HIL failures, or copying firmware to the ci.lan test rig. Covers per-host config selection (htpc uses local.json, ci uses tinyusb.json), local execution on either htpc or ci, remote execution over SSH from htpc, and debugging tips.
+---
+
+# Hardware-in-the-Loop (HIL) Testing
+
+Run TinyUSB HIL tests on real boards. **Run `hostname` first** — it tells you which host you are on, which determines the default config and whether remote mode is possible.
+
+| Host | Local config | Remote (SSH → ci.lan)? |
+|------|--------------|------------------------|
+| `htpc` (dev PC) | `test/hil/local.json` | yes (large pool, `test/hil/tinyusb.json`) |
+| `ci` (the rig) | `test/hil/tinyusb.json` (large pool) | no — can't SSH to htpc, and boards are already local |
+
+Default to **local**. Use **remote** only when on `htpc` and the user says `remote`/`ci.lan`. Never attempt remote on `ci`.
+
+## Prerequisites
+
+Examples must be built for the target board(s) — see AGENTS.md "Build" → "All examples for a board" (produces `examples/cmake-build-<board>/`). `-B examples` points `hil_test.py` at that parent folder.
+
+## Arguments
+
+- **Board:** `-b BOARD_NAME` for one board; omit to run all boards in the config.
+- **Pass-through:** `-v`, `-r N`, etc. forwarded unchanged.
+
+If `local.json` is missing on `htpc`, ask the user to supply one (only fall back to `tinyusb.json` if told to).
+
+## Local execution
+
+Set `CONFIG` from `hostname` first (`test/hil/local.json` on htpc, `test/hil/tinyusb.json` on ci):
+
+```bash
+CONFIG=test/hil/local.json # on ci use: CONFIG=test/hil/tinyusb.json
+
+# All boards in the config:
+python3 test/hil/hil_test.py -B examples "$CONFIG"
+
+# A single board (replace stm32f723disco):
+python3 test/hil/hil_test.py -b stm32f723disco -B examples "$CONFIG"
+```
+
+Append pass-through flags (`-v`, `-r 1`, …) to either command as needed.
+
+## Remote execution (htpc → ci.lan only)
+
+`test/hil/hil_ci.sh` handles dir setup, scp of test scripts, rsync of firmware (`.elf`/`.bin`/`.hex`), and runs `hil_test.py` on `ci.lan` with `tinyusb.json`:
+
+```bash
+# All boards:
+bash test/hil/hil_ci.sh
+
+# A single board, with pass-through flags:
+bash test/hil/hil_ci.sh -b raspberry_pi_pico2 -t host/cdc_msc_hid -r 1
+```
+
+Env overrides: `REMOTE`, `REMOTE_DIR`, `CONFIG`. Fails fast if the build dir/repo layout is missing.
+
+## Timing
+
+Runs take 2-5 min. Use a timeout ≥ 20 min (1200000 ms). NEVER cancel early.
+
+## Reporting
+
+Show the output, summarize pass/fail per board. On failure, retry with `-v`; if that's not enough, add temporary debug prints to `hil_test.py`.
diff --git a/.claude/skills/pvs/SKILL.md b/.claude/skills/pvs/SKILL.md
new file mode 100644
index 000000000..bc4bf01bd
--- /dev/null
+++ b/.claude/skills/pvs/SKILL.md
@@ -0,0 +1,36 @@
+---
+name: pvs
+description: Use when running PVS-Studio static analysis (SAST + MISRA C:2023 / C++:2008) on TinyUSB for a given board. Builds the examples with an exported compile_commands.json, runs pvs-studio-analyzer against .PVS-Studio/.pvsconfig, and emits readable + SARIF output.
+---
+
+# PVS-Studio Static Analysis
+
+`run_pvs.sh <BOARD>` builds all examples for the board (with
+`compile_commands.json` exported), runs `pvs-studio-analyzer` against
+`.PVS-Studio/.pvsconfig`, then writes `pvs-<board>.log` and `pvs-<board>.sarif`
+plus printed errorfile findings. Needs a license file or `$PVS_STUDIO_CREDENTIALS`.
+
+```bash
+.claude/skills/pvs/run_pvs.sh raspberry_pi_pico # whole project for a board
+
+# Scope to specific files — -S takes a plaintext list (one path per line),
+# NOT a source file directly. Extra args pass through to the analyzer.
+printf 'src/tusb.c\nsrc/class/cdc/cdc_device.c\n' > /tmp/files.txt
+.claude/skills/pvs/run_pvs.sh stm32f407disco -S /tmp/files.txt
+```
+
+## Notes
+
+- **Board:** `raspberry_pi_pico` mirrors CI (needs Pico SDK deps);
+ `stm32f407disco` is fastest (no external SDK). Any board works once its deps
+ are fetched (`python3 tools/get_deps.py -b <board>`).
+- `.pvsconfig` already excludes vendored code and suppresses accepted MISRA
+ deviations — don't re-add those on the command line. Surviving `src/` findings
+ are genuinely new.
+- Timing is dominated by the build (deps may push it past a minute); the analysis
+ pass is ~10-30 s. Use a timeout ≥ 10 min when deps must be fetched first.
+- `--dump-files` is intentionally omitted — it scatters `.PVS-Studio.i/.cfg`
+ dumps across the tree (FP-debugging only); add it back via the passthrough args.
+
+After a run, summarize findings by rule/severity from the errorfile output and
+point the user at `pvs-<board>.sarif`.
diff --git a/.claude/skills/pvs/run_pvs.sh b/.claude/skills/pvs/run_pvs.sh
new file mode 100755
index 000000000..7406a3b4f
--- /dev/null
+++ b/.claude/skills/pvs/run_pvs.sh
@@ -0,0 +1,85 @@
+#!/usr/bin/env bash
+# Run PVS-Studio static analysis on TinyUSB for a given BOARD.
+#
+# Mirrors the "Static Analysis (PVS-Studio)" section in AGENTS.md / CLAUDE.md:
+# - build all examples for BOARD with compile_commands.json exported
+# - run pvs-studio-analyzer against that compile DB using .PVS-Studio/.pvsconfig
+# - convert the log to human-readable (errorfile) and SARIF output
+#
+# Usage:
+# .claude/skills/pvs/run_pvs.sh <BOARD> [extra pvs-studio-analyzer args...]
+#
+# Examples:
+# .claude/skills/pvs/run_pvs.sh raspberry_pi_pico
+# # Scope to specific files via a plaintext list (one path per line):
+# printf 'src/tusb.c\nsrc/class/cdc/cdc_device.c\n' > /tmp/files.txt
+# .claude/skills/pvs/run_pvs.sh stm32f407disco -S /tmp/files.txt
+set -euo pipefail
+
+BOARD="${1:-}"
+if [ -z "$BOARD" ]; then
+ echo "Usage: $0 <BOARD> [extra pvs-studio-analyzer args...]" >&2
+ echo "Example: $0 raspberry_pi_pico" >&2
+ exit 2
+fi
+shift
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
+cd "$REPO_ROOT"
+
+BUILD_DIR="examples/cmake-build-${BOARD}"
+COMPILE_DB="${BUILD_DIR}/compile_commands.json"
+REPORT_LOG="pvs-${BOARD}.log"
+SARIF_OUT="pvs-${BOARD}.sarif"
+JOBS="$(nproc 2>/dev/null || echo 4)"
+
+# --- License ---------------------------------------------------------------
+# Use an existing license file, else materialize one from PVS_STUDIO_CREDENTIALS
+# (format: "<name> <key>", as supplied by the CI secret of the same name).
+if ! pvs-studio-analyzer lic-info >/dev/null 2>&1; then
+ if [ -n "${PVS_STUDIO_CREDENTIALS:-}" ]; then
+ echo ">>> Registering PVS-Studio license from PVS_STUDIO_CREDENTIALS"
+ # Split "<name> <key>" into exactly two fields, quoted, so a key containing
+ # glob chars or extra spaces can't be word-split/expanded.
+ read -r _pvs_name _pvs_key <<< "$PVS_STUDIO_CREDENTIALS"
+ pvs-studio-analyzer credentials "$_pvs_name" "$_pvs_key"
+ else
+ echo "ERROR: no PVS-Studio license found and PVS_STUDIO_CREDENTIALS is unset." >&2
+ exit 1
+ fi
+fi
+
+# --- Build (exports compile_commands.json) ---------------------------------
+echo ">>> Building all examples for ${BOARD} (this also fetches the compile DB)"
+cmake examples -B "${BUILD_DIR}" -G Ninja \
+ -DBOARD="${BOARD}" \
+ -DCMAKE_BUILD_TYPE=MinSizeRel \
+ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
+cmake --build "${BUILD_DIR}"
+
+if [ ! -f "${COMPILE_DB}" ]; then
+ echo "ERROR: ${COMPILE_DB} was not produced by the build." >&2
+ exit 1
+fi
+
+# --- Analyze ---------------------------------------------------------------
+echo ">>> Running PVS-Studio analyzer (-j${JOBS})"
+# Note: AGENTS.md shows --dump-files, but that scatters .PVS-Studio.i/.cfg dump
+# files across the source tree (only useful for debugging false positives). It is
+# omitted here to keep the working tree clean; add it back via "$@" if needed.
+pvs-studio-analyzer analyze \
+ -f "${COMPILE_DB}" \
+ -R .PVS-Studio/.pvsconfig \
+ -o "${REPORT_LOG}" -j"${JOBS}" \
+ --security-related-issues \
+ --misra-c-version 2023 --misra-cpp-version 2008 --use-old-parser \
+ "$@"
+
+# --- Report ----------------------------------------------------------------
+echo ">>> General-analysis + MISRA findings (errorfile):"
+plog-converter -a GA:1,2 -t errorfile "${REPORT_LOG}" || true
+plog-converter -t sarif -o "${SARIF_OUT}" "${REPORT_LOG}" >/dev/null
+
+echo ">>> Done."
+echo " Raw log : ${REPORT_LOG}"
+echo " SARIF : ${SARIF_OUT}"
diff --git a/.gitattributes b/.gitattributes
index 140ae8929..723f48277 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -19,6 +19,9 @@
Makefile text
+# Shell scripts must stay LF even when core.autocrlf=true (CRLF breaks bash)
+*.sh text eol=lf
+
# Windows-only Visual Studio things
*.sln text eol=crlf
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 000000000..e9930a25a
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: hathach
diff --git a/.github/labeler.yml b/.github/labeler.yml
new file mode 100644
index 000000000..6c7aa7e7d
--- /dev/null
+++ b/.github/labeler.yml
@@ -0,0 +1,77 @@
+# Path-based auto-labeling for USB IP / port drivers.
+# Maps changed dcd/hcd files under src/portable/ to their "Port <ip>" label.
+# Consumed by actions/labeler (see .github/workflows/labeler.yml -> label-port job).
+
+"Port DWC2":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/synopsys/dwc2/**'
+
+"Port EHCI":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/ehci/**'
+
+"Port OHCI":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/ohci/**'
+
+"Port FSDev":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/st/stm32_fsdev/**'
+
+"Port ChipIdea":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/chipidea/**'
+
+"Port NXP IP3511":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/nxp/lpc_ip3511/**'
+
+"Port NXP IP3516":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/nxp/lpc_ip3516/**'
+
+"Port MUSB":
+ - changed-files:
+ - any-glob-to-any-file:
+ - 'src/portable/mentor/musb/**'
+ - 'src/portable/sunxi/**'
+
+"Port RUSB2":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/renesas/rusb2/**'
+
+"Port WCH USBFS":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/wch/*usbfs*'
+
+"Port WCH USBHS":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/wch/*usbhs*'
+
+"Port MAX3421":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/analog/max3421/**'
+
+"Port SAMD":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/microchip/samd/**'
+
+"Port SAMG":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/microchip/samg/**'
+
+"Port nRF":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/nordic/nrf5x/**'
+
+"Port Nuvoton":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/nuvoton/**'
+
+"Port RP2":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/raspberrypi/**'
+
+"Port MSP430":
+ - changed-files:
+ - any-glob-to-any-file: 'src/portable/ti/msp430x5xx/**'
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 60f4c7ca1..c8c597e50 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -9,12 +9,9 @@ on:
types: [ published ]
concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
+ group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}
-env:
- HIL_JSON: test/hil/tinyusb.json
-
jobs:
# Check if the code changes and we need to run ci build
# Cannot use paths filter in the on-event since we want this workflow to run even when there are no code changes, to register the commit chain
@@ -59,11 +56,12 @@ jobs:
id: set-matrix-json
run: |
# build matrix
- MATRIX_JSON=$(python .github/workflows/ci_set_matrix.py)/
+ MATRIX_JSON=$(python .github/workflows/ci_set_matrix.py)
echo "matrix=$MATRIX_JSON"
echo "matrix=$MATRIX_JSON" >> $GITHUB_OUTPUT
- # hil matrix
- HIL_MATRIX_JSON=$(python test/hil/hil_ci_set_matrix.py ${{ env.HIL_JSON }})
+
+ # HIL matrix (merged from tinyusb + hifiphile configs)
+ HIL_MATRIX_JSON=$(python test/hil/hil_ci_set_matrix.py test/hil/tinyusb.json test/hil/hfp.json)
echo "hil_matrix=$HIL_MATRIX_JSON"
echo "hil_matrix=$HIL_MATRIX_JSON" >> $GITHUB_OUTPUT
@@ -173,10 +171,6 @@ jobs:
mv metrics_compare.md $COMPARE_FILE
gh release upload $CURR_TAG metrics.json $COMPARE_FILE
- - name: Save PR number
- if: github.event_name == 'pull_request'
- run: echo ${{ github.event.number }} > pr_number.txt
-
- name: Upload Metrics Comment Artifact
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v7
@@ -185,7 +179,6 @@ jobs:
path: |
metrics_compare.md
metrics.json
- pr_number.txt
- name: Post Code Metrics as PR Comment
if: (github.event_name == 'workflow_dispatch') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false)
@@ -195,6 +188,36 @@ jobs:
path: metrics_compare.md
# ---------------------------------------
+ # Keep the metrics baseline available on no-code-change pushes
+ # The code-metrics job only runs (and uploads metrics-tinyusb) when code changed, so a
+ # workflow/docs-only push to master would leave the latest run without a baseline for PRs
+ # to compare against. Carry the previous artifact forward so the baseline is never missing.
+ # ---------------------------------------
+ metrics-carry-forward:
+ needs: [ check-paths ]
+ if: github.event_name == 'push' && needs.check-paths.outputs.code_changed != 'true'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Download previous metrics baseline from this branch
+ uses: dawidd6/action-download-artifact@v11
+ with:
+ workflow: build.yml
+ workflow_conclusion: '' # any conclusion, matching the PR-side baseline download
+ search_artifacts: true # scan back past runs that lack the artifact (e.g. earlier no-code pushes)
+ branch: ${{ github.ref_name }}
+ name: metrics-tinyusb
+ path: .
+ if_no_artifact_found: warn
+ continue-on-error: true # best-effort: never make a no-code push red
+
+ - name: Re-publish baseline so the latest run keeps it
+ if: hashFiles('metrics.json') != ''
+ uses: actions/upload-artifact@v7
+ with:
+ name: metrics-tinyusb
+ path: metrics.json
+
+ # ---------------------------------------
# Build Make/CMake on Windows/MacOS
# ---------------------------------------
build-os:
@@ -239,7 +262,7 @@ jobs:
# ---------------------------------------
# Hardware in the loop (HIL)
- # Run on PR only (hil-tinyusb), hil-hfp only run on non-forked PR
+ # Run on PR only (hil-tinyusb), hil-hfp-iar only run on non-forked PR
# ---------------------------------------
hil-build:
needs: [ check-paths, set-matrix ]
@@ -250,6 +273,7 @@ jobs:
matrix:
toolchain:
- 'arm-gcc'
+ - 'riscv-gcc'
- 'esp-idf'
with:
build-system: 'cmake'
@@ -263,8 +287,24 @@ jobs:
# ---------------------------------------
hil-tinyusb:
needs: hil-build
- runs-on: [ self-hosted, X64, hathach, hardware-in-the-loop ]
+ name: hil-tinyusb (${{ matrix.display }})
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - display: tinyusb.json
+ runner: [ self-hosted, X64, hathach, hardware-in-the-loop ]
+ hil_json: test/hil/tinyusb.json
+ - display: hfp.json
+ runner: [ self-hosted, Linux, X64, hifiphile ]
+ hil_json: test/hil/hfp.json
+ runs-on: ${{ matrix.runner }}
+ env:
+ HIL_JSON: ${{ matrix.hil_json }}
steps:
+ - name: Set HIL report dir (sibling of workspace; persists across run attempts)
+ run: echo "HIL_REPORT_DIR=$(dirname "$GITHUB_WORKSPACE")/hil-report" >> "$GITHUB_ENV"
+
- name: Get Skip Boards from previous run
if: github.run_attempt != '1'
run: |
@@ -303,25 +343,36 @@ jobs:
exit 1
fi)
+ - name: Upload HIL report
+ if: always() && github.event_name == 'pull_request'
+ uses: actions/upload-artifact@v7
+ with:
+ name: hil-report-${{ matrix.display }}
+ path: ${{ env.HIL_REPORT_DIR }}/hil_report.md
+ if-no-files-found: ignore
+ overwrite: true
+
# ---------------------------------------
# Hardware in the loop (HIL)
# self-hosted by HFP, build with IAR toolchain, for attached hardware checkout test/hil/hfp.json
# Since IAR Token secret is not passed to forked PR, only build non-forked PR
# ---------------------------------------
- hil-hfp:
+ hil-hfp-iar:
needs: [ check-paths ]
if: |
needs.check-paths.outputs.code_changed == 'true' &&
github.repository_owner == 'hathach' &&
!(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true)
runs-on: [ self-hosted, Linux, X64, hifiphile ]
+ timeout-minutes: 30
env:
IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }}
+ PYTHONUNBUFFERED: '1'
steps:
- name: Clean workspace
run: |
echo "Cleaning up previous run"
- rm -rf "${{ github.workspace }}"3
+ rm -rf "${{ github.workspace }}"
mkdir -p "${{ github.workspace }}"
- name: Toolchain version
@@ -342,7 +393,25 @@ jobs:
run: python3 tools/get_deps.py $BUILD_ARGS
- name: Build
- run: python3 tools/build.py --toolchain iar $BUILD_ARGS
+ run: |
+ # Each variant carries its own --build-name/--cflag, which are global to a
+ # single build.py invocation — so build one matrix entry at a time rather
+ # than joining them (joining would leak a variant's flags onto every board).
+ readarray -t ENTRIES < <(python test/hil/hil_ci_set_matrix.py test/hil/hfp.json | jq -r '.["arm-gcc"][]')
+ for entry in "${ENTRIES[@]}"; do
+ echo "+ tools/build.py --toolchain iar $entry"
+ python3 tools/build.py --toolchain iar $entry
+ done
- name: Test on actual hardware (hardware in the loop)
- run: python3 test/hil/hil_test.py hfp.json
+ run: |
+ python3 test/hil/hil_test.py hfp.json
+
+ - name: Upload HIL report
+ if: always() && github.event_name == 'pull_request'
+ uses: actions/upload-artifact@v7
+ with:
+ name: hil-report-hfp-iar
+ path: hil_report.md
+ if-no-files-found: ignore
+ overwrite: true
diff --git a/.github/workflows/build_util.yml b/.github/workflows/build_util.yml
index 69b6f28d5..2532caebe 100644
--- a/.github/workflows/build_util.yml
+++ b/.github/workflows/build_util.yml
@@ -67,7 +67,7 @@ jobs:
IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }}
run: |
if [ "${{ inputs.toolchain }}" == "esp-idf" ]; then
- docker run --rm -e MEMBROWSE_API_KEY="$MEMBROWSE_API_KEY" -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py --target all ${{ matrix.arg }}
+ docker run --rm -e MEMBROWSE_API_KEY="$MEMBROWSE_API_KEY" -e CI="$CI" -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py --target all ${{ matrix.arg }}
else
BUILD_PY_ARGS="-s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} --target all"
if [ "${{ inputs.upload-metrics }}" = "true" ]; then
diff --git a/.github/workflows/ci_set_matrix.py b/.github/workflows/ci_set_matrix.py
index 1d35f15dd..dc0d3871f 100755
--- a/.github/workflows/ci_set_matrix.py
+++ b/.github/workflows/ci_set_matrix.py
@@ -30,6 +30,7 @@ family_list = {
"ch32v10x": ["riscv-gcc"],
"ch32v20x": ["riscv-gcc"],
"ch32v30x": ["riscv-gcc"],
+ "ch583": ["riscv-gcc"],
"da1469x": ["arm-gcc"],
"fomu": ["riscv-gcc"],
"ft9xx": ["ft9xx-gcc"],
@@ -68,6 +69,7 @@ family_list = {
"samd5x_e5x": ["arm-gcc", "arm-clang"],
"samg": ["arm-gcc", "arm-clang"],
"stm32c0": ["arm-gcc", "arm-clang", "arm-iar"],
+ "stm32c5": ["arm-gcc", "arm-clang", "arm-iar"],
"stm32f0": ["arm-gcc", "arm-clang", "arm-iar"],
"stm32f1": ["arm-gcc", "arm-clang", "arm-iar"],
"stm32f2": ["arm-gcc", "arm-clang", "arm-iar"],
diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml
index 43144bb5e..59019616f 100644
--- a/.github/workflows/claude-code-review.yml
+++ b/.github/workflows/claude-code-review.yml
@@ -1,18 +1,29 @@
name: Claude Code Review
on:
- pull_request_target:
- types: [opened, synchronize, ready_for_review, reopened]
+ pull_request:
+ # opened/reopened/ready_for_review -> first auto review
+ # synchronize -> auto re-review on new pushes
+ #
+ # NOTE: pull_request (not _target) means fork PRs get a read-only GITHUB_TOKEN
+ # and NO repository secrets (CLAUDE_CODE_OAUTH_TOKEN), so they cannot be
+ # auto-reviewed. The job condition below skips them cleanly -> use @claude on
+ # those. Same-repo branches (yours or write-access contributors) auto-review.
+ types: [opened, synchronize, reopened, ready_for_review]
jobs:
claude-review:
- if: false
+ # Skip drafts, and skip fork PRs (no secrets -> would only fail noisily)
+ if: >
+ github.event.pull_request.draft == false &&
+ github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
- issues: read
+ issues: write # Claude posts the review comment via the issues API
id-token: write
+ actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
@@ -25,8 +36,25 @@ jobs:
uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
+ # Allow claude[bot]'s own pushes to be handled gracefully (skip) instead
+ # of erroring out the workflow
+ allowed_bots: 'claude'
+ # Pairs with the actions: read permission so Claude can read CI results
+ additional_permissions: |
+ actions: read
plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
plugins: 'code-review@claude-code-plugins'
- prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'
+ # Post/update a single summary comment every run, so a clean review
+ # ("no issues found") is still visible instead of posting nothing.
+ use_sticky_comment: true
+ # --comment makes the code-review command post its findings to the PR.
+ # Without it the command only prints the review to the Actions log.
+ prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }} --comment'
+ # TEMPORARY: expose the full Claude transcript in the Actions log for
+ # debugging. Revert to remove once done.
+ show_full_output: true
+ claude_args: |
+ --max-turns 50
+ --model claude-opus-4-8
+ --effort max
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
- # or https://code.claude.com/docs/en/cli-reference for available options
diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml
index 50f449949..66e36897c 100644
--- a/.github/workflows/claude.yml
+++ b/.github/workflows/claude.yml
@@ -6,22 +6,32 @@ on:
pull_request_review_comment:
types: [created]
issues:
- types: [opened, assigned]
+ # only "opened" — an issue's author_association gates the summon below;
+ # "assigned" would gate on the issue author, not the assigner, so a
+ # maintainer assigning an outsider's issue would be wrongly skipped.
+ types: [opened]
pull_request_review:
types: [submitted]
jobs:
claude:
+ # Only trusted actors (repo owner/member/collaborator) may summon @claude, so the
+ # write-scoped token and OAuth secret are never issued for an outside contributor's
+ # comment on this public repo. Defense-in-depth on top of the action's own check.
if: |
- (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
- (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
- (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
- (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
+ (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude') &&
+ contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) ||
+ (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude') &&
+ contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) ||
+ (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude') &&
+ contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.review.author_association)) ||
+ (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')) &&
+ contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.issue.author_association))
runs-on: ubuntu-latest
permissions:
- contents: read
- pull-requests: read
- issues: read
+ contents: write # allow Claude to push commits/branches when asked
+ pull-requests: write # allow Claude to comment on / update PRs
+ issues: write # allow Claude to comment on / update issues
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
@@ -40,10 +50,19 @@ jobs:
additional_permissions: |
actions: read
- # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
- # prompt: 'Update the pull request description to include a summary of changes.'
+ # Sign the bot's commits so they show as "Verified". The action commits
+ # automatically — on a PR comment it pushes to that PR's branch; on an
+ # issue comment it opens a new claude/* branch + PR with the fix.
+ use_commit_signing: true
- # Optional: Add claude_args to customize behavior and configuration
- # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
- # or https://code.claude.com/docs/en/cli-reference for available options
- # claude_args: '--allowed-tools Bash(gh pr:*)'
+ # No custom prompt: Claude performs the instructions in the @claude comment.
+
+ # Deliberately NO Bash in the tool allowlist. @claude can be summoned on a
+ # fork PR (claude-code-review.yml even directs fork PRs here), and this job
+ # holds the OAuth secret + a write token. Any build/interpreter command
+ # (python -c, cmake/make custom targets, etc.) run against attacker-
+ # controlled PR content is arbitrary code + network execution, so no
+ # command allowlist can safely contain it. Claude still edits files and
+ # the action commits/opens the PR; the resulting commit is verified by the
+ # repo's CircleCI matrix. --max-turns gives room to investigate + fix.
+ claude_args: '--max-turns 30'
diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml
index c3cc59d0d..fe09413f1 100644
--- a/.github/workflows/labeler.yml
+++ b/.github/workflows/labeler.yml
@@ -4,23 +4,29 @@ on:
issues:
types: [opened]
pull_request_target:
- types: [opened]
+ types: [opened, synchronize, reopened]
+ discussion:
+ types: [created]
jobs:
label-priority:
+ # Author-based priority labels: only on issue/PR/discussion creation, not on PR updates.
+ if: github.event_name != 'pull_request_target' || github.event.action == 'opened'
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
+ discussions: write
steps:
- - name: Label New Issue or PR
- uses: actions/github-script@v7
+ - name: Label New Issue, PR or Discussion
+ uses: actions/github-script@v8
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
- let label = '';
+ let labels = [];
let username = '';
let issueOrPrNumber = 0;
+ let discussionNodeId = '';
if (context.eventName === 'issues') {
username = context.payload.issue.user.login;
@@ -28,25 +34,85 @@ jobs:
} else if (context.eventName === 'pull_request_target') {
username = context.payload.pull_request.user.login;
issueOrPrNumber = context.payload.pull_request.number;
+ } else if (context.eventName === 'discussion') {
+ username = context.payload.discussion.user.login;
+ discussionNodeId = context.payload.discussion.node_id;
}
- // Check if an Adafruit member
- try {
- const adafruitResponse = await github.rest.orgs.checkMembershipForUser({
- org: 'adafruit',
- username: username
- });
+ // Maintainer is an Adafruit member; skip the Adafruit perks for their own
+ // issues/PRs and treat them as a plain contributor (Prio only).
+ const isOwner = username.toLowerCase() === 'hathach';
- if (adafruitResponse.status === 204) {
- console.log('Adafruit Member');
- label = 'Prio Urgent';
+ // Check if an Adafruit member: Adafruit + Sponsor + top priority
+ if (!isOwner) {
+ try {
+ const adafruitResponse = await github.rest.orgs.checkMembershipForUser({
+ org: 'adafruit',
+ username: username
+ });
+
+ if (adafruitResponse.status === 204) {
+ console.log('Adafruit Member');
+ labels = ['Adafruit 🌸', 'Sponsor 💖', 'Prio Top 🚨'];
+ }
+ } catch (error) {
+ console.log('Not an Adafruit member');
}
- } catch (error) {
- console.log('Not an Adafruit member');
}
- // Check if a contributor
- if (label == '') {
+ // Check if a public GitHub Sponsor of the repo owner.
+ // Word ($32) tier and up get triage priority; DWORD/QWORD ($128+) go to the top.
+ // Private sponsorships are not visible to GITHUB_TOKEN, so only public sponsors are detected.
+ if (labels.length === 0) {
+ try {
+ const result = await github.graphql(`
+ query($sponsorable: String!, $sponsor: String!) {
+ user(login: $sponsorable) {
+ isSponsoredBy(accountLogin: $sponsor)
+ sponsorshipsAsMaintainer(includePrivate: false, first: 100) {
+ nodes {
+ sponsorEntity {
+ ... on User { login }
+ ... on Organization { login }
+ }
+ tier { monthlyPriceInDollars }
+ }
+ }
+ }
+ }`, { sponsorable: context.repo.owner, sponsor: username });
+
+ const owner = result.user;
+ if (owner && owner.isSponsoredBy) {
+ let monthly = 0;
+ const nodes = (owner.sponsorshipsAsMaintainer && owner.sponsorshipsAsMaintainer.nodes) || [];
+ for (const node of nodes) {
+ const login = node.sponsorEntity && node.sponsorEntity.login;
+ if (login && login.toLowerCase() === username.toLowerCase()) {
+ monthly = (node.tier && node.tier.monthlyPriceInDollars) || 0;
+ break;
+ }
+ }
+
+ if (monthly >= 128) {
+ console.log('Sponsor (DWORD/QWORD tier)');
+ labels = ['Sponsor 💖', 'Prio Top 🚨'];
+ } else if (monthly >= 32) {
+ console.log('Sponsor (Word tier)');
+ labels = ['Sponsor 💖', 'Prio 📌'];
+ } else {
+ console.log('Sponsor (below Word tier or tier not visible)');
+ labels = ['Sponsor 💖'];
+ }
+ } else {
+ console.log('Not a public sponsor');
+ }
+ } catch (error) {
+ console.log('Sponsor lookup failed: ' + error.message);
+ }
+ }
+
+ // Check if a contributor: prioritized in triage queue
+ if (labels.length === 0) {
try {
const collaboratorResponse = await github.rest.repos.checkCollaborator({
owner: context.repo.owner,
@@ -56,18 +122,61 @@ jobs:
if (collaboratorResponse.status === 204) {
console.log('Contributor');
- label = 'Prio Higher';
+ labels = ['Prio 📌'];
}
} catch (error) {
console.log('Not a contributor');
}
}
- if (label !== '') {
- await github.rest.issues.addLabels({
- owner: context.repo.owner,
- repo: context.repo.repo,
- issue_number: issueOrPrNumber,
- labels: [label]
- });
+ if (labels.length !== 0) {
+ if (context.eventName === 'discussion') {
+ // Discussions are not covered by the REST issues API; resolve the label
+ // names to node IDs and attach them with the GraphQL labelable mutation.
+ const labelIds = [];
+ for (const name of labels) {
+ const res = await github.graphql(`
+ query($owner: String!, $repo: String!, $name: String!) {
+ repository(owner: $owner, name: $repo) {
+ label(name: $name) { id }
+ }
+ }`, { owner: context.repo.owner, repo: context.repo.repo, name: name });
+ if (res.repository.label) {
+ labelIds.push(res.repository.label.id);
+ }
+ }
+ if (labelIds.length !== 0) {
+ await github.graphql(`
+ mutation($labelableId: ID!, $labelIds: [ID!]!) {
+ addLabelsToLabelable(input: { labelableId: $labelableId, labelIds: $labelIds }) {
+ clientMutationId
+ }
+ }`, { labelableId: discussionNodeId, labelIds: labelIds });
+ }
+ } else {
+ await github.rest.issues.addLabels({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issueOrPrNumber,
+ labels: labels
+ });
+ }
}
+
+ # Path-based Port labels: attach "Port <ip>" when a PR touches the matching
+ # dcd/hcd driver under src/portable/. Mapping lives in .github/labeler.yml.
+ label-port:
+ if: github.event_name == 'pull_request_target'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: write
+ issues: write # allow auto-creating a Port label that doesn't exist yet
+ steps:
+ - uses: actions/labeler@v5
+ with:
+ configuration-path: .github/labeler.yml
+ # sync-labels so a Port label is removed once a PR no longer touches
+ # that driver (job reruns on synchronize). Only labels listed in
+ # labeler.yml are managed, so author-based Prio/Sponsor labels are untouched.
+ sync-labels: true
diff --git a/.github/workflows/metrics_comment.yml b/.github/workflows/metrics_comment.yml
deleted file mode 100644
index 5d250211f..000000000
--- a/.github/workflows/metrics_comment.yml
+++ /dev/null
@@ -1,39 +0,0 @@
-name: Metrics Comment
-
-on:
- workflow_run:
- workflows: ["Build"]
- types:
- - completed
-
-jobs:
- post-comment:
- runs-on: ubuntu-latest
- if: >
- github.event.workflow_run.event == 'pull_request' &&
- github.event.workflow_run.conclusion == 'success'
- permissions:
- actions: read
- pull-requests: write
- steps:
- - name: Download Artifacts
- uses: actions/download-artifact@v5
- with:
- run-id: ${{ github.event.workflow_run.id }}
- github-token: ${{ secrets.GITHUB_TOKEN }}
- name: metrics-comment
-
- - name: Read PR Number
- id: pr_number
- run: |
- if [ -f pr_number.txt ]; then
- echo "number=$(cat pr_number.txt)" >> $GITHUB_OUTPUT
- fi
-
- - name: Post Code Metrics as PR Comment
- if: steps.pr_number.outputs.number != ''
- uses: marocchino/sticky-pull-request-comment@v2
- with:
- header: code-metrics
- path: metrics_compare.md
- number: ${{ steps.pr_number.outputs.number }}
diff --git a/.github/workflows/pr_comment.yml b/.github/workflows/pr_comment.yml
new file mode 100644
index 000000000..4d50817b4
--- /dev/null
+++ b/.github/workflows/pr_comment.yml
@@ -0,0 +1,131 @@
+name: PR Comment
+
+on:
+ workflow_run:
+ workflows: ["Build"]
+ types:
+ - completed
+
+jobs:
+ # Resolve the PR number from trusted workflow_run metadata, NOT from build artifacts: a forked PR
+ # controls its own Build run and could plant any number, which the privileged jobs below would
+ # then post to. Same-repo PRs populate workflow_run.pull_requests; for forks it is empty, so look
+ # the PR up by the trusted head SHA.
+ pr_number:
+ if: github.event.workflow_run.event == 'pull_request'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ number: ${{ steps.resolve.outputs.number }}
+ steps:
+ - name: Resolve PR number
+ id: resolve
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ REPO: ${{ github.repository }}
+ HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
+ HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
+ PRS_JSON: ${{ toJSON(github.event.workflow_run.pull_requests) }}
+ run: |
+ # Every lookup is best-effort: on any miss the number stays empty and the comment jobs
+ # below simply skip (never a failed check).
+ # Same-repo PRs: workflow_run.pull_requests is populated.
+ num=$(printf '%s' "$PRS_JSON" | jq -r '.[0].number // empty')
+ # Fork PRs: pull_requests is empty. Find the open PR by its trusted head ref and confirm
+ # its head SHA matches the built commit.
+ if [ -z "$num" ] && [ -n "$HEAD_BRANCH" ] && [ -n "$HEAD_REPO" ]; then
+ num=$(gh api --method GET "repos/$REPO/pulls" \
+ -f state=open -f head="${HEAD_REPO%%/*}:$HEAD_BRANCH" \
+ --jq '[.[] | select(.head.sha == env.HEAD_SHA)][0].number // empty' 2>/dev/null || true)
+ fi
+ echo "number=$num" >> "$GITHUB_OUTPUT"
+
+ metrics-comment:
+ needs: pr_number
+ if: >
+ github.event.workflow_run.conclusion == 'success' &&
+ needs.pr_number.outputs.number != ''
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ pull-requests: write
+ steps:
+ - name: Download Artifacts
+ uses: actions/download-artifact@v5
+ with:
+ run-id: ${{ github.event.workflow_run.id }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ name: metrics-comment
+ # Best-effort: docs-only PRs skip code-metrics, so the artifact may be absent.
+ continue-on-error: true
+
+ - name: Post Code Metrics as PR Comment
+ if: hashFiles('metrics_compare.md') != ''
+ uses: marocchino/sticky-pull-request-comment@v2
+ with:
+ header: code-metrics
+ path: metrics_compare.md
+ number: ${{ needs.pr_number.outputs.number }}
+
+ # ---------------------------------------
+ # Combine the rigs' HIL reports into one sticky PR comment (one table per rig).
+ # Runs here (workflow_run / base-repo context) rather than in build.yml so it also works on
+ # forked PRs, whose build-side GITHUB_TOKEN is read-only and cannot post comments. Posts even
+ # on build/HIL failure (when the report matters most); skips only on cancellation.
+ # ---------------------------------------
+ hil-comment:
+ needs: pr_number
+ if: >
+ github.event.workflow_run.conclusion != 'cancelled' &&
+ needs.pr_number.outputs.number != ''
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ pull-requests: write
+ steps:
+ - name: Download HIL reports
+ uses: actions/download-artifact@v5
+ with:
+ run-id: ${{ github.event.workflow_run.id }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ pattern: hil-report-*
+ path: hil-reports
+ continue-on-error: true
+
+ - name: Combine rig reports (one table per rig)
+ id: combine
+ run: |
+ shopt -s nullglob
+ dirs=(hil-reports/hil-report-*)
+ if [ ${#dirs[@]} -eq 0 ]; then
+ echo "No HIL reports found"
+ exit 0
+ fi
+ {
+ echo "## Hardware-in-the-loop (HIL) Test Report"
+ echo
+ for d in "${dirs[@]}"; do
+ [ -d "$d" ] || continue
+ echo "### ${d#hil-reports/hil-report-}"
+ echo
+ cat "$d/hil_report.md" 2>/dev/null || echo "_no report produced_"
+ echo
+ done
+ } > hil_combined.md
+ # Fork PRs can influence report content and this job posts in base-repo context, so
+ # neutralize @-mentions (insert a zero-width space) to prevent notification abuse.
+ zwsp=$(printf '\342\200\213')
+ sed -i -E "s/@([A-Za-z0-9_-])/@${zwsp}\1/g" hil_combined.md
+ cat hil_combined.md
+ echo "found=true" >> "$GITHUB_OUTPUT"
+
+ - name: Post HIL report as sticky PR comment
+ if: steps.combine.outputs.found == 'true'
+ uses: marocchino/sticky-pull-request-comment@v2
+ with:
+ header: hil-report
+ path: hil_combined.md
+ number: ${{ needs.pr_number.outputs.number }}
diff --git a/.gitignore b/.gitignore
index 162f9a019..8fe09e65f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
html
latex
+hil_report.md
+hil_report.json
*.a
*.d
*.o
@@ -10,6 +12,7 @@ latex
*.env
*.ind
*.log
+*.sarif
*.map
*.obj
*.jlink
@@ -55,3 +58,35 @@ Release
BrowseInfo
.cmake_build
README_processed.rst
+.worktrees
+cmake-metrics/
+# Directories fetched by tools/get_deps.py - not to be committed
+lib/CMSIS_5/
+lib/CMSIS_6/
+lib/FreeRTOS-Kernel/
+lib/fatfs/
+lib/lwip/
+lib/sct_neopixel/
+lib/threadx/
+tools/linkermap/
+tools/uf2/
+hw/mcu/allwinner/
+hw/mcu/analog/
+hw/mcu/artery/
+hw/mcu/broadcom/
+hw/mcu/bridgetek/ft9xx/ft90x-sdk/
+hw/mcu/gd/
+hw/mcu/hpmicro/
+hw/mcu/infineon/
+hw/mcu/microchip/
+hw/mcu/mindmotion/
+hw/mcu/nordic/nrfx/
+hw/mcu/nuvoton/
+hw/mcu/nxp/
+hw/mcu/raspberry_pi/
+hw/mcu/renesas/
+hw/mcu/silabs/
+hw/mcu/sony/cxd56/spresense-exported-sdk/
+hw/mcu/st/
+hw/mcu/ti/
+hw/mcu/wch/
diff --git a/AGENTS.md b/AGENTS.md
index eb6b737c3..25dcdd618 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,428 +1,224 @@
# TinyUSB Agent Instructions
-TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems, designed to be memory-safe with no
-dynamic allocation and thread-safe with all interrupt events deferred to non-ISR task functions.
+TinyUSB is a cross-platform USB Host/Device stack for embedded systems: memory-safe (no dynamic allocation) and thread-safe (ISR events deferred to task context).
-Always reference these instructions first and fallback to search or bash commands only when you encounter unexpected
-information that does not match the info here.
+Reference these instructions first; fall back to search/bash only when reality diverges.
-## Shared Ground Rules
-- Keep TinyUSB memory-safe: avoid dynamic allocation, defer ISR work to task context, and follow C99 with two-space indentation/no tabs.
-- Match file organization: core stack under `src`, MCU/BSP support in `hw/{mcu,bsp}`, examples under `examples/{device,host,dual}`, docs in `docs`, tests under `test/{unit-test,fuzz,hil}`.
-- Use descriptive snake_case for helpers, reserve `tud_`/`tuh_` for public APIs, `TU_` for macros, and keep headers self-contained with `#if CFG_TUSB_MCU` guards where needed.
-- Prefer `.clang-format` for C/C++ formatting, run `pre-commit run --all-files` before submitting, and document board/HIL coverage when applicable.
-- Commit in imperative mood, keep changes scoped, and supply PRs with linked issues plus test/build evidence.
+## Behavioral Guidelines
+Bias toward caution over speed. For trivial tasks, use judgment.
-## Bootstrap and Build Setup
+- **Think first** — state assumptions; ask if unclear; present alternatives instead of picking silently.
+- **Simplicity** — no features, abstractions, flexibility, or error handling beyond what was asked. If 200 lines could be 50, rewrite.
+- **Surgical changes** — touch only what the task requires; match existing style; don't refactor working code; mention unrelated dead code rather than deleting it. Remove only orphans *your* changes created.
+- **Goal-driven** — turn tasks into verifiable goals ("write failing test, make it pass"). For multi-step work, state a brief `step → verify` plan.
-- Install ARM GCC toolchain: `sudo apt-get update && sudo apt-get install -y gcc-arm-none-eabi`
-- Fetch core dependencies: `python3 tools/get_deps.py` -- takes <1 second. NEVER CANCEL.
-- For specific board families: `python3 tools/get_deps.py FAMILY_NAME` (e.g., rp2040, stm32f4), or
- `python3 tools/get_deps.py -b BOARD_NAME`
-- Dependencies are cached in `lib/` and `hw/mcu/` directories
-- For **Espressif** boards, initialize the ESP-IDF environment before any build/flash/monitor command:
- `. $HOME/code/esp-idf/export.sh`
+## Ground Rules
-## Build Examples
+- **Language/style:** C99, 2-space indent (no tabs), snake_case helpers, `UPPER_CASE` macros. Public APIs use `tud_`/`tuh_`; macros use `TU_`. Headers self-contained with `#if CFG_TUSB_MCU` guards.
+- **Safety:** no dynamic allocation; defer ISR work to task context; use `TU_ASSERT()` for error checks; always check return values; include order: C stdlib → tusb common → drivers → classes.
+- **Layout:** `src/` core, `hw/{mcu,bsp}/` MCU+BSP, `examples/{device,host,dual}/`, `test/{unit-test,fuzz,hil}/`, `docs/`, `tools/`.
+- **Commits/PRs:** imperative mood, scoped changes, link issues, include test/build evidence. After opening a PR, monitor it and drive it to green: address automated review comments (Copilot/Codex/Claude) and fix any failing CI builds, pushing follow-up commits until checks pass and review threads are resolved. Useful: `gh pr checks <num> --watch`, `gh pr view <num> --comments`.
+- **Formatting/lint:** `clang-format` (`.clang-format`), `codespell` (`.codespellrc`), run `pre-commit run --all-files` before submitting.
-Choose ONE of these approaches:
-**Option 1: Individual Example with CMake and Ninja (RECOMMENDED)**
+## Bootstrap
```bash
-cd examples/device/cdc_msc
-mkdir -p build && cd build
-cmake -DBOARD=raspberry_pi_pico -G Ninja -DCMAKE_BUILD_TYPE=MinSizeRel ..
-cmake --build .
+sudo apt-get install -y gcc-arm-none-eabi # ARM toolchain (2-5 min, one-time)
+python3 tools/get_deps.py [FAMILY|-b BOARD] # fetch deps into lib/, hw/mcu/ (<1 s)
+. $HOME/code/esp-idf/export.sh # Espressif only: before any build/flash/monitor
```
--- takes 1-2 seconds. NEVER CANCEL. Set timeout to 5+ minutes.
-
-**Option 2: All Examples for a Board**
-
-different folder than Option 1
+## Build
+Single example (CMake+Ninja, recommended, 1-3 s):
```bash
-cd examples/
-mkdir -p build && cd build
+cd examples/device/cdc_msc && mkdir -p build && cd build
cmake -DBOARD=raspberry_pi_pico -G Ninja -DCMAKE_BUILD_TYPE=MinSizeRel ..
cmake --build .
```
--- takes 15-20 seconds, may have some objcopy failures that are non-critical. NEVER CANCEL. Set timeout to 30+ minutes.
-
-**Option 3: Individual Example with Make**
-
+All examples for a board (15-20 s; some objcopy failures are non-critical). Use `cmake-build-<board>` as the build dir — HIL tests expect that exact name:
```bash
-cd examples/device/cdc_msc
-make BOARD=raspberry_pi_pico all
+cd examples
+cmake -B cmake-build-raspberry_pi_pico -DBOARD=raspberry_pi_pico -G Ninja -DCMAKE_BUILD_TYPE=MinSizeRel .
+cmake --build cmake-build-raspberry_pi_pico
```
--- takes 2-3 seconds. NEVER CANCEL. Set timeout to 5+ minutes.
-
-**Option 4: Espressif Example with ESP-IDF**
-
-Only ESP-IDF-enabled examples are supported for Espressif boards. Use FreeRTOS examples such as `examples/device/cdc_msc_freertos`
-that contain `idf_component_register()` support.
+Single example with Make:
+```bash
+cd examples/device/cdc_msc && make BOARD=raspberry_pi_pico all
+```
+Espressif (only ESP-IDF examples like `cdc_msc_freertos`):
```bash
. $HOME/code/esp-idf/export.sh
cd examples/device/cdc_msc_freertos
idf.py -DBOARD=espressif_s3_devkitc build
```
-Use `-DBOARD=...` with any supported board under `hw/bsp/espressif/boards/`. NEVER CANCEL. Set timeout to 10+ minutes.
-
-
-## Build Options
+**Build options** (CMake `-D…` / Make `…=…`):
+- Debug: `CMAKE_BUILD_TYPE=Debug` / `DEBUG=1`
+- Logging: `LOG=2` (add `LOGGER=rtt` for RTT)
+- Root hub port: `RHPORT_DEVICE=1`
+- Speed: `RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED`
-- **Debug build**:
- - CMake: `-DCMAKE_BUILD_TYPE=Debug`
- - Make: `DEBUG=1`
-- **With logging**:
- - CMake: `-DLOG=2`
- - Make: `LOG=2`
-- **With RTT logger**:
- - CMake: `-DLOG=2 -DLOGGER=rtt`
- - Make: `LOG=2 LOGGER=rtt`
-- **RootHub port selection**:
- - CMake: `-DRHPORT_DEVICE=1`
- - Make: `RHPORT_DEVICE=1`
-- **Port speed**:
- - CMake: `-DRHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED`
- - Make: `RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED`
+## Flash
-## Flashing and Deployment
-
-- **Flash with JLink**:
- - CMake: `ninja cdc_msc-jlink`
- - Make: `make BOARD=raspberry_pi_pico flash-jlink`
-- **Flash with OpenOCD**:
- - CMake: `ninja cdc_msc-openocd`
- - Make: `make BOARD=raspberry_pi_pico flash-openocd`
-- **Generate UF2**:
- - CMake: `ninja cdc_msc-uf2`
- - Make: `make BOARD=raspberry_pi_pico all uf2`
-- **List all targets** (CMake/Ninja): `ninja -t targets`
-- **Espressif flash**:
- - Run `. $HOME/code/esp-idf/export.sh`
- - `cd examples/device/cdc_msc_freertos`
- - `idf.py -DBOARD=espressif_s3_devkitc flash`
-- **Espressif serial monitor / chip log output**:
- - Run `. $HOME/code/esp-idf/export.sh`
- - `cd examples/device/cdc_msc_freertos`
- - `idf.py -DBOARD=espressif_s3_devkitc monitor`
+```bash
+# JLink
+ninja cdc_msc-jlink # CMake
+make BOARD=<board> flash-jlink # Make
-## GDB Debugging
+# OpenOCD
+ninja cdc_msc-openocd # CMake
+make BOARD=<board> flash-openocd # Make
-Look up the board's `JLINK_DEVICE` and `OPENOCD_OPTION` from `hw/bsp/*/boards/*/board.cmake` (or `board.mk`).
+# UF2
+ninja cdc_msc-uf2 # CMake
+make BOARD=<board> all uf2 # Make
-### JLinkGDBServer
+ninja -t targets # list CMake targets
-**Terminal 1 – start the GDB server:**
-```bash
-JLinkGDBServer -device stm32h743xi -if SWD -speed 4000 \
- -port 2331 -swoport 2332 -telnetport 2333 -nogui
+# Espressif (after . $HOME/code/esp-idf/export.sh)
+idf.py -DBOARD=<board> flash
+idf.py -DBOARD=<board> monitor
```
-**Terminal 2 – connect GDB:**
-```bash
-arm-none-eabi-gdb /tmp/build/firmware.elf
-(gdb) target remote :2331
-(gdb) monitor reset halt
-(gdb) load
-(gdb) continue
-```
+## GDB Debugging
+
+Look up `JLINK_DEVICE` / `OPENOCD_OPTION` in `hw/bsp/*/boards/*/board.cmake` (CMake builds) or `board.mk` (Make builds).
-To break on entry instead of running immediately:
+**JLink — Terminal 1:**
```bash
-(gdb) monitor reset halt
-(gdb) load
-(gdb) break main
-(gdb) continue
+JLinkGDBServer -device stm32h743xi -if SWD -speed 4000 -port 2331 -swoport 2332 -telnetport 2333 -nogui
```
-### OpenOCD
-
-**Terminal 1 – start the GDB server:**
+**OpenOCD — Terminal 1:**
```bash
openocd -f interface/stlink.cfg -f target/stm32h7x.cfg
-# or with J-Link probe:
+# or with a J-Link interface:
openocd -f interface/jlink.cfg -f target/stm32h7x.cfg
-```
-
-For **rp2040/rp2350** with a CMSIS-DAP probe (e.g. Picoprobe, debugprobe):
-```bash
+# rp2040/rp2350 via CMSIS-DAP:
openocd -f interface/cmsis-dap.cfg -f target/rp2040.cfg -c "adapter speed 5000"
-# or for rp2350:
-openocd -f interface/cmsis-dap.cfg -f target/rp2350.cfg -c "adapter speed 5000"
```
-For boards that define `OPENOCD_OPTION` in `board.cmake`, use those options directly:
-```bash
-openocd $(cat hw/bsp/FAMILY/boards/BOARD/board.cmake | grep OPENOCD_OPTION | ...)
-```
-
-**Terminal 2 – connect GDB (OpenOCD default port is 3333):**
+**Terminal 2 — connect GDB** (replace `<port>` with `2331` for JLinkGDBServer or `3333` for OpenOCD):
```bash
arm-none-eabi-gdb /tmp/build/firmware.elf
-(gdb) target remote :3333
+(gdb) target remote :<port>
(gdb) monitor reset halt
(gdb) load
+(gdb) break main # optional, to stop at entry
(gdb) continue
```
-### RTT Logging with JLinkGDBServer
-
-- Build with RTT logging enabled (example):
- `cd examples/device/cdc_msc && make BOARD=stm32h743eval LOG=2 LOGGER=rtt all`
-- Flash with J-Link:
- `cd examples/device/cdc_msc && make BOARD=stm32h743eval LOG=2 LOGGER=rtt flash-jlink`
-- Launch GDB server with RTT port (keep this running in terminal 1):
- `JLinkGDBServer -device stm32h743xi -if SWD -speed 4000 -port 2331 -swoport 2332 -telnetport 2333 -RTTTelnetPort 19021 -nogui`
-- Read RTT output (terminal 2):
- `JLinkRTTClient`
-- Capture RTT to file (optional):
- `JLinkRTTClient | tee rtt.log`
-- For non-interactive capture:
- `timeout 20s JLinkRTTClient > rtt.log`
-
-## Unit Testing
-
-- Install Ceedling: `sudo gem install ceedling`
-- Run all unit tests: `cd test/unit-test && ceedling` or `cd test/unit-test && ceedling test:all` -- takes 4 seconds.
- NEVER CANCEL. Set timeout to 10+ minutes.
-- Run specific test: `cd test/unit-test && ceedling test:test_fifo`
-- Tests use Unity framework with CMock for mocking
-
-## Hardware-in-the-Loop (HIL) Testing
-
-- `-B examples` means `examples` is the parent folder that contains multi-board build outputs such as `examples/cmake-build-BOARD_NAME/...`
-- Select config file before running HIL tests:
- - if GitHub Actions self-hosted runner service is running, use `tinyusb.json`
- - otherwise use `local.json`
- - example:
- `HIL_CONFIG=$( (systemctl list-units --type=service --state=running 2>/dev/null; systemctl --user list-units --type=service --state=running 2>/dev/null) | grep -q 'actions\.runner' && echo tinyusb.json || echo local.json )`
-- Run tests on actual hardware, one of following ways:
- - test a specific board `python test/hil/hil_test.py -b BOARD_NAME -B examples $HIL_CONFIG`
- - test all boards in config `python test/hil/hil_test.py -B examples $HIL_CONFIG`
-- In case of error, enabled verbose mode with `-v` flag for detailed logs. Also try to observe script output, and try to
- modify hil_test.py (temporarily) to add more debug prints to pinpoint the issue.
-- Requires pre-built (all) examples for target boards (see Build Examples section 2)
-
-take 2-5 minutes. NEVER CANCEL. Set timeout to 20+ minutes.
-
-## Documentation
-
-- Install requirements: `pip install -r docs/requirements.txt`
-- Build docs: `cd docs && sphinx-build -b html . _build` -- takes 2-3 seconds. NEVER CANCEL. Set timeout to 10+ minutes.
+**RTT logging:** build with `LOG=2 LOGGER=rtt`, flash, then run JLinkGDBServer with `-RTTTelnetPort 19021`, and in another terminal `JLinkRTTClient` (pipe to `tee rtt.log` or use `timeout 20s JLinkRTTClient > rtt.log` for non-interactive capture).
-## Code Size Metrics
-
-Generate and compare code size metrics to evaluate the impact of changes. This is the most common workflow
-when making code changes — use it to verify size impact before committing.
-
-**Quick single-board metrics (preferred for iterative development):**
+## Testing
+**Unit (Ceedling, Unity+CMock, ~4 s):**
```bash
-rm -rf cmake-build
-python3 tools/build.py -b raspberry_pi_pico --target all --target tinyusb_metrics
-python3 tools/metrics.py combine -j -m -f tinyusb/src cmake-build/cmake-build-*/metrics.json
+sudo gem install ceedling
+cd test/unit-test && ceedling test:all # or ceedling test:test_fifo
```
-This builds all examples for one board and produces `metrics.json` + `metrics.md`. Takes ~30 seconds.
-NEVER CANCEL. Set timeout to 10+ minutes.
-
-**Comparing with master (before/after workflow):**
+**HIL (2-5 min):** invoke the `hil` skill (`.claude/skills/hil/SKILL.md`) for the full procedure (local vs remote mode, config selection, SSH copy steps, debugging tips). Requires pre-built examples — see Build → "All examples for a board".
-1. On master: build and save baseline
- ```bash
- rm -rf cmake-build
- python3 tools/build.py -b raspberry_pi_pico --target all --target tinyusb_metrics
- python3 tools/metrics.py combine -j -m -f tinyusb/src cmake-build/cmake-build-*/metrics.json
- mv metrics.json metrics_master.json
- ```
-2. Switch to your branch: rebuild
- ```bash
- rm -rf cmake-build
- python3 tools/build.py -b raspberry_pi_pico --target all --target tinyusb_metrics
- python3 tools/metrics.py combine -j -m -f tinyusb/src cmake-build/cmake-build-*/metrics.json
- ```
-3. Compare: `python3 tools/metrics.py compare -m -f tinyusb/src metrics_master.json metrics.json`
- Produces `metrics_compare.md` showing size differences.
-
-**Full CI metrics (all arm-gcc families, for thorough validation):**
+## Documentation
```bash
-rm -rf cmake-build
-FAMILIES=$(python3 .github/workflows/ci_set_matrix.py | python3 -c "import sys,json; d=json.load(sys.stdin); print(' '.join(d.get('arm-gcc',[])))")
-python3 tools/build.py --one-first --target all --target tinyusb_metrics $FAMILIES
-python3 tools/metrics.py combine -j -m -f tinyusb/src cmake-build/cmake-build-*/metrics.json
+pip install -r docs/requirements.txt
+cd docs && sphinx-build -b html . _build # ~2.5 s
```
-Builds the first board of each family. Takes 2-4 minutes. NEVER CANCEL. Set timeout to 10+ minutes.
-
-## Code Quality and Validation
+## Code Size Metrics
-- Format code: `clang-format -i path/to/file.c` (uses `.clang-format` config)
-- Check spelling: `pip install codespell && codespell` (uses `.codespellrc` config)
-- Pre-commit hooks validate unit tests and code quality automatically
+Verify size impact before committing. Invoke the `code-size` skill (`.claude/skills/code-size/SKILL.md`) — it wraps `tools/metrics_compare_base.py` to handle the base-vs-branch worktree + build + compare flow.
-## Static Analysis with PVS-Studio
+Quick reference:
+```bash
+# Single example, one board:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico -e device/cdc_msc
+# Add --bloaty for section/symbol breakdown.
-- **Analyze whole project**:
- ```bash
- pvs-studio-analyzer analyze -f examples/cmake-build-raspberry_pi_pico/compile_commands.json -R .PVS-Studio/.pvsconfig -o pvs-report.log -j12 --dump-files --misra-cpp-version 2008 --misra-c-version 2023 --use-old-parser
- ```
-- **Analyze specific source files**:
- ```bash
- pvs-studio-analyzer analyze -f examples/cmake-build-raspberry_pi_pico/compile_commands.json -R .PVS-Studio/.pvsconfig -S path/to/file.c -o pvs-report.log -j12 --dump-files --misra-cpp-version 2008 --misra-c-version 2023 --use-old-parser
- ```
-- **Multiple specific files**:
- ```bash
- pvs-studio-analyzer analyze -f examples/cmake-build-raspberry_pi_pico/compile_commands.json -R .PVS-Studio/.pvsconfig -S src/file1.c -S src/file2.c -o pvs-report.log -j12 --dump-files --misra-cpp-version 2008 --misra-c-version 2023 --use-old-parser
- ```
-- Requires `compile_commands.json` in the build directory (generated by CMake with `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`)
-- Use `-f` option to specify path to `compile_commands.json`
-- Use `-R .PVS-Studio/.pvsconfig` to specify rule configuration file
-- Use `-j12` for parallel analysis with 12 threads
-- `--dump-files` saves preprocessed files for debugging
-- `--misra-c-version 2023` enables MISRA C:2023 checks
-- `--misra-cpp-version 2008` enables MISRA C++:2008 checks
-- `--use-old-parser` uses legacy parser for compatibility
-- Analysis takes ~10-30 seconds depending on project size. Set timeout to 5+ minutes.
-- View results: `plog-converter -a GA:1,2 -t errorfile pvs-report.log` or open in PVS-Studio GUI
+# All examples, one board:
+python3 tools/metrics_compare_base.py -b raspberry_pi_pico
-## Validation Checklist
+# All arm-gcc CI families combined (pre-merge sweep, 4-8 min):
+python3 tools/metrics_compare_base.py --ci
+```
-### ALWAYS Run These After Making Changes
+Reports land in `cmake-metrics/<board>/metrics_compare.md` (per-board) and `cmake-metrics/_combined/metrics_compare.md` (with `--combined`/`--ci`).
-1. **Pre-commit validation** (RECOMMENDED): `pre-commit run --all-files`
- - Install pre-commit: `pip install pre-commit && pre-commit install`
- - Runs all quality checks, unit tests, spell checking, and formatting
- - Takes 10-15 seconds. NEVER CANCEL. Set timeout to 15+ minutes.
-2. **Build validation**: Build at least one board with all example that exercises your changes, see Build Examples
- section (option 2)
-3. Run unit tests relevant to touched modules; add fuzz/HIL coverage when modifying parsers or protocol state machines.
+## Static Analysis (PVS-Studio)
-### Manual Testing Scenarios
-- **Device examples**: Cannot be fully tested without real hardware, but must build successfully
-- **Unit tests**: Exercise core stack functionality - ALL tests must pass
-- **Build system**: Must be able to build examples for multiple board families
+Requires `compile_commands.json`, which the examples build exports by default
+(`hw/bsp/family_support.cmake` sets `CMAKE_EXPORT_COMPILE_COMMANDS ON`). The
+`pvs` skill (`.claude/skills/pvs/SKILL.md`) wraps the build + analyze flow for a
+board; the commands below are the underlying steps.
-### Board Selection for Testing
-- **STM32F4**: `stm32f407disco` - no external SDK required, good for testing
-- **RP2040**: `raspberry_pi_pico` - requires Pico SDK, commonly used
-- **Other families**: Check `hw/bsp/FAMILY/boards/` for available boards
+```bash
+# Whole project:
+pvs-studio-analyzer analyze \
+ -f examples/cmake-build-raspberry_pi_pico/compile_commands.json \
+ -R .PVS-Studio/.pvsconfig \
+ -o pvs-report.log -j12 \
+ --security-related-issues \
+ --misra-c-version 2023 --misra-cpp-version 2008 --use-old-parser
-## Release Instructions
+# Specific files: -S takes a plaintext list (one path per line), not paths directly:
+printf 'src/foo.c\nsrc/bar.c\n' > files.txt
+pvs-studio-analyzer analyze \
+ -f examples/cmake-build-raspberry_pi_pico/compile_commands.json \
+ -R .PVS-Studio/.pvsconfig \
+ -S files.txt \
+ -o pvs-report.log -j12 \
+ --security-related-issues \
+ --misra-c-version 2023 --misra-cpp-version 2008 --use-old-parser
-**DO NOT commit files automatically - only modify files and let the maintainer review before committing.**
+plog-converter -a GA:1,2 -t errorfile pvs-report.log # view results
+```
-1. Bump the release version variable at the top of `tools/make_release.py`.
-2. Execute `python3 tools/make_release.py` to refresh:
- - `src/tusb_option.h` (version defines)
- - `repository.yml` (version mapping)
- - `library.json` (PlatformIO version)
- - `sonar-project.properties` (SonarQube version)
- - `docs/reference/boards.rst` (generated board documentation)
- - `hw/bsp/BoardPresets.json` (CMake presets)
-3. Generate release notes for `docs/info/changelog.rst`:
- - Get commit list: `git log <last-release-tag>..HEAD --oneline`
- - **Visit GitHub PRs** for merged pull requests to understand context and gather details
- - Use GitHub tools to search/read PRs: `github-mcp-server-list_pull_requests`, `github-mcp-server-pull_request_read`
- - Extract key changes, API modifications, bug fixes, and new features from PR descriptions
- - Add new changelog entry following the existing format:
- - Version heading with equals underline (e.g., `0.20.0` followed by `======`)
- - Release date in italics (e.g., `*November 19, 2024*`)
- - Major sections: General, API Changes, Controller Driver (DCD & HCD), Device Stack, Host Stack, Testing
- - Use bullet lists with descriptive categorization
- - Reference function names, config macros, and file paths using RST inline code (double backticks)
- - Include meaningful descriptions, not just commit messages
-4. **Validation before commit**:
- - Run unit tests: `cd test/unit-test && ceedling test:all`
- - Build at least one example: `cd examples/device/cdc_msc && make BOARD=stm32f407disco all`
- - Verify changed files look correct: `git diff --stat`
-5. **Leave files unstaged** for maintainer to review, modify if needed, and commit with message: `Bump version to X.Y.Z`
-6. **After maintainer commits**: Create annotated tag with `git tag -a vX.Y.Z -m "Release X.Y.Z"`
-7. Push commit and tag: `git push origin <branch> && git push origin vX.Y.Z`
-8. Create GitHub release from the tag with changelog content
+Takes ~10-30 s. (`--dump-files` adds preprocessed `.PVS-Studio.i/.cfg` dumps next
+to every source for false-positive debugging — omit it for normal runs.)
-## Repository Structure Quick Reference
-```
-├── src/ # Core TinyUSB stack
-│ ├── class/ # USB device classes (CDC, HID, MSC, Audio, etc.)
-│ ├── portable/ # MCU-specific drivers (organized by vendor)
-│ ├── device/ # USB device stack core
-│ ├── host/ # USB host stack core
-│ └── common/ # Shared utilities (FIFO, etc.)
-├── examples/ # Example applications
-│ ├── device/ # Device examples (cdc_msc, hid_generic, etc.)
-│ ├── host/ # Host examples
-│ └── dual/ # Dual-role examples
-├── hw/bsp/ # Board Support Packages
-│ └── FAMILY/boards/ # Board-specific configurations
-├── test/unit-test/ # Unit tests using Ceedling
-├── tools/ # Build and utility scripts
-└── docs/ # Sphinx documentation
-```
+## Validation After Changes
-#### Build Time Reference
-- **Dependency fetch**: <1 second
-- **Single example build**: 1-3 seconds
-- **Unit tests**: ~4 seconds
-- **Documentation build**: ~2.5 seconds
-- **Full board examples**: 15-20 seconds
-- **Toolchain installation**: 2-5 minutes (one-time)
+1. `pre-commit run --all-files` — format, spell, unit tests (10-15 s).
+2. Build at least one board's full example set (Build → "All examples for a board") for modules you touched.
+3. Run relevant unit tests; add fuzz/HIL coverage for parsers or protocol state machines.
-#### Key Files to Know
-- `tools/get_deps.py`: Manages dependencies for MCU families
-- `tools/build.py`: Builds multiple examples, supports make/cmake
-- `src/tusb.h`: Main TinyUSB header file
-- `src/tusb_config.h`: Configuration template
-- `examples/device/cdc_msc/`: Most commonly used example for testing
-- `test/unit-test/project.yml`: Ceedling test configuration
+**Boards good for local testing:**
+- `stm32f407disco` — no external SDK
+- `raspberry_pi_pico` — Pico SDK required
+- Others: see `hw/bsp/FAMILY/boards/`
-#### MCU Reference Manuals and Datasheets
-- Look in `$HOME/Documents/Calibre Library` for all MCU reference manuals, datasheets and board schematics.
+Device examples need real hardware to validate runtime behavior; must at least build.
-#### Debugging Build Issues
-- **Missing compiler**: Install `gcc-arm-none-eabi` package
-- **Missing dependencies**: Run `python3 tools/get_deps.py FAMILY`
-- **Board not found**: Check `hw/bsp/FAMILY/boards/` for valid board names
-- **objcopy errors**: Often non-critical in full builds, try individual example builds
+## Release
-#### Working with USB Device Classes
-- **CDC (Serial)**: `src/class/cdc/` - Virtual serial port
-- **HID**: `src/class/hid/` - Human Interface Device (keyboard, mouse, etc.)
-- **MSC**: `src/class/msc/` - Mass Storage Class (USB drive)
-- **Audio**: `src/class/audio/` - USB Audio Class
-- Each class has device (`*_device.c`) and host (`*_host.c`) implementations
+**Do not commit automatically — leave changes for maintainer review.**
-#### MCU Family Support
-- **STM32**: Largest support (F0, F1, F2, F3, F4, F7, G0, G4, H7, L4, U5, etc.)
-- **Raspberry Pi**: RP2040, RP2350 with PIO-USB host support
-- **NXP**: iMXRT, Kinetis, LPC families
-- **Microchip**: SAM D/E/G/L families
-- Check `hw/bsp/` for complete list and `docs/reference/boards.rst` for details
+1. Bump version at top of `tools/make_release.py`.
+2. Run `python3 tools/make_release.py` to refresh: `src/tusb_option.h`, `repository.yml`, `library.json`, `sonar-project.properties`, `docs/reference/boards.rst`, `hw/bsp/BoardPresets.json`.
+3. Changelog `docs/info/changelog.rst`:
+ - `git log <last-tag>..HEAD --oneline` for commit list.
+ - Read merged PRs for context (`gh pr view`, or github MCP tools).
+ - Follow existing format: version + `======` underline, italic date, sections (General, API Changes, DCD & HCD, Device Stack, Host Stack, Testing), RST inline code for symbols.
+4. Validate: `ceedling test:all`, build `cdc_msc` for `stm32f407disco`, review `git diff --stat`.
+5. Leave unstaged. Maintainer commits `Bump version to X.Y.Z`, then: `git tag -a vX.Y.Z -m "Release X.Y.Z" && git push origin <branch> vX.Y.Z`. Create GitHub release from tag.
-### Code Style Guidelines
+## References
-#### General Coding Standards
-- Use C99 standard
-- Memory-safe: no dynamic allocation
-- Thread-safe: defer all interrupt events to non-ISR task functions
-- 2-space indentation, no tabs
-- Use snake_case for variables/functions
-- Use UPPER_CASE for macros and constants
-- Follow existing variable naming patterns in files you're modifying
-- Include proper header comments with MIT license
-- Add descriptive comments for non-obvious functions
+- MCU reference manuals, datasheets, schematics: `$HOME/Documents/calibre-library`.
+- Supported MCUs/boards: `hw/bsp/` and `docs/reference/boards.rst`.
+- USB classes: `src/class/{cdc,hid,msc,audio,…}/` — each has `*_device.c` and `*_host.c`.
+- Key files: `src/tusb.h`, `src/tusb_config.h`, `tools/get_deps.py`, `tools/build.py`, `test/unit-test/project.yml`.
-#### Best Practices
-- When including headers, group in order: C stdlib, tusb common, drivers, classes
-- Always check return values from functions that can fail
-- Use TU_ASSERT() for error checking with return statements
-- Follow the existing code patterns in the files you're modifying
+## Common Build Issues
-Remember: TinyUSB is designed for embedded systems - builds are fast, tests are focused, and the codebase is optimized for resource-constrained environments.
+- Missing compiler → install `gcc-arm-none-eabi`.
+- Missing deps → `python3 tools/get_deps.py FAMILY`.
+- Unknown board → check `hw/bsp/FAMILY/boards/`.
+- `objcopy` errors in full builds are often non-critical; retry the single example.
diff --git a/README.rst b/README.rst
index 6be9d4873..ea71e1adc 100644
--- a/README.rst
+++ b/README.rst
@@ -1,12 +1,32 @@
TinyUSB
=======
-|Build Status| |CircleCI Status| |Documentation Status| |Static Analysis| |Fuzzing Status| |Membrowse| |License|
+|Sponsor| |Build Status| |CircleCI Status| |Documentation Status| |Static Analysis| |Fuzzing Status| |Membrowse| |License|
+
+Overview
+--------
+
+.. figure:: docs/assets/logo.svg
+ :alt: TinyUSB
+ :align: left
+
+.. raw:: html
+
+ <div class="clear-both"></div>
+
+TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems. It’s designed for memory safety
+(no dynamic allocation) and thread safety (all interrupts deferred to non-ISR task functions). The stack emphasizes portability,
+small footprint, and real-time performance across 50+ MCU families.
Sponsors
--------
-TinyUSB is funded by: Adafruit. Purchasing products from them helps to support this project.
+TinyUSB's continued development is made possible by its sponsors. If TinyUSB helps your products or projects, consider funding its development on `GitHub Sponsors`_.
+
+Platinum
+^^^^^^^^
+
+`Adafruit`_ has backed TinyUSB since day one as its founding and sole Platinum sponsor. Buying their products directly funds the project's development.
.. figure:: docs/assets/adafruit_logo.svg
:alt: Adafruit Logo
@@ -17,20 +37,44 @@ TinyUSB is funded by: Adafruit. Purchasing products from them helps to support t
<div class="clear-both"></div>
-Overview
---------
+Sponsors (QWORD)
+^^^^^^^^^^^^^^^^
-.. figure:: docs/assets/logo.svg
- :alt: TinyUSB
- :align: left
+.. QWORD-SPONSORS-START
-.. raw:: html
+*No QWORD sponsors yet — be the first!*
- <div class="clear-both"></div>
+.. QWORD-SPONSORS-END
-TinyUSB is an open-source cross-platform USB Host/Device stack for embedded systems. It’s designed for memory safety
-(no dynamic allocation) and thread safety (all interrupts deferred to non-ISR task functions). The stack emphasizes portability,
-small footprint, and real-time performance across 50+ MCU families.
+Backers (DWORD)
+^^^^^^^^^^^^^^^
+
+.. DWORD-BACKERS-START
+
+*No backers yet — be the first!*
+
+.. DWORD-BACKERS-END
+
+Supporters (Word)
+^^^^^^^^^^^^^^^^^
+
+.. WORD-SUPPORTERS-START
+
+*No supporters yet — be the first!*
+
+.. WORD-SUPPORTERS-END
+
+Thanks (Byte)
+^^^^^^^^^^^^^
+
+.. BYTE-THANKS-START
+
+*No names listed yet — be the first!*
+
+.. BYTE-THANKS-END
+
+.. _GitHub Sponsors: https://github.com/sponsors/hathach
+.. _Adafruit: https://www.adafruit.com
Key Features
------------
@@ -130,153 +174,161 @@ TinyUSB is completely thread-safe by pushing all Interrupt Service Request (ISR)
Supported CPUs
--------------
-
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
| Manufacturer | Family | Device | Host | Highspeed | Driver | Note |
+==============+=============================+========+======+===========+========================+====================+
-| Allwinner | F1C100s/F1C200s | ✔ | | ✔ | sunxi | musb variant |
+| Allwinner | F1C100s/F1C200s | ✅ | | ✅ | sunxi | musb variant |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Analog | MAX3421E | | ✔ | ✖ | max3421 | via SPI |
+| Analog | MAX3421E | | ✅ | ❌ | max3421 | via SPI |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | MAX32 650, 666, 690, | ✔ | | ✔ | musb | 1-dir ep |
+| | MAX32 650, 666, 690, | ✅ | | ✅ | musb | 1-dir ep |
| | MAX78002 | | | | | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Artery AT32 | F403a_407, F413 | ✔ | | | fsdev | 512 USB RAM |
+| Artery AT32 | F403a_407, F413 | ✅ | | | fsdev | 512 USB RAM |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | F415, F435_437, F423, | ✔ | ✔ | | dwc2 | |
+| | F415, F435_437, F423, | ✅ | ✅ | | dwc2 | |
| | F425, F45x | | | | | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | F402_F405 | ✔ | ✔ | ✔ | dwc2 | F405 is HS |
+| | F402_F405 | ✅ | ✅ | ✅ | dwc2 | F405 is HS |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Bridgetek | FT90x | ✔ | | ✔ | ft9xx | 1-dir ep |
+| Bridgetek | FT90x | ✅ | | ✅ | ft9xx | 1-dir ep |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Broadcom | BCM2711, BCM2837 | ✔ | | ✔ | dwc2 | |
+| Broadcom | BCM2711, BCM2837 | ✅ | | ✅ | dwc2 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Dialog | DA1469x | ✔ | ✖ | ✖ | da146xx | |
+| Dialog | DA1469x | ✅ | ❌ | ❌ | da146xx | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Espressif | S2, S3, H4 | ✔ | ✔ | ✖ | dwc2 | |
+| Espressif | S2, S3, H4 | ✅ | ✅ | ❌ | dwc2 | |
| ESP32 +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | P4 | ✔ | ✔ | ✔ | dwc2 | |
+| | P4 | ✅ | ✅ | ✅ | dwc2 | |
+| +-----------------------------+--------+------+-----------+------------------------+--------------------+
+| | S31 | ✅ | ✅ | ✅ | dwc2 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| GigaDevice | GD32VF103 | ✔ | | ✖ | dwc2 | |
+| GigaDevice | GD32VF103 | ✅ | | ❌ | dwc2 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| HPMicro | HPM6750 | ✔ | ✔ | ✔ | ci_hs, ehci | |
+| HPMicro | HPM6750 | ✅ | ✅ | ✅ | ci_hs, ehci | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Infineon | XMC4500 | ✔ | ✔ | ✖ | dwc2 | |
+| Infineon | XMC4500 | ✅ | ✅ | ❌ | dwc2 | |
+--------------+-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| MicroChip | SAM | D11, D21, L21, L22 | ✔ | | ✖ | samd | |
+| MicroChip | SAM | D11, D21, L21, L22 | ✅ | | ❌ | samd | |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | D51, E5x | ✔ | | ✖ | samd | |
+| | | D51, E5x | ✅ | | ❌ | samd | |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | G55 | ✔ | | ✖ | samg | 1-dir ep |
+| | | G55 | ✅ | | ❌ | samg | 1-dir ep |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | E70,S70,V70,V71 | ✔ | | ✔ | samx7x | 1-dir ep |
+| | | E70,S70,V70,V71 | ✅ | | ✅ | samx7x | 1-dir ep |
| +-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| | PIC | 24 | ✔ | | | pic | ci_fs variant |
+| | PIC | 24 | ✅ | | | pic | ci_fs variant |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | 32 mm, mk, mx | ✔ | | | pic | ci_fs variant |
+| | | 32 mm, mk, mx | ✅ | | | pic | ci_fs variant |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | dsPIC33 | ✔ | | | pic | ci_fs variant |
+| | | dsPIC33 | ✅ | | | pic | ci_fs variant |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | 32mz | ✔ | | | pic32mz | musb variant |
+| | | 32mz | ✅ | | | pic32mz | musb variant |
+--------------+-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| MindMotion | mm32 | ✔ | | ✖ | mm32f327x_otg | ci_fs variant |
+| MindMotion | mm32 | ✅ | | ❌ | mm32f327x_otg | ci_fs variant |
+--------------+-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| NordicSemi | nRF52, nRF53 | ✔ | ✖ | ✖ | nrf5x | only ep8 is ISO |
+| NordicSemi | nRF52, nRF53 | ✅ | ❌ | ❌ | nrf5x | only ep8 is ISO |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | nRF54 | ✔ | ✖ | ✔ | dwc2 | |
+| | nRF54 | ✅ | ❌ | ✅ | dwc2 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Nuvoton | NUC120 | ✔ | ✖ | ✖ | nuc120 | |
+| Nuvoton | NUC120 | ✅ | ❌ | ❌ | nuc120 | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | NUC121/NUC125, NUC126 | ✔ | ✖ | ✖ | nuc121 | |
+| | NUC121/NUC125, NUC126 | ✅ | ❌ | ❌ | nuc121 | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | NUC505 | ✔ | | ✔ | nuc505 | |
+| | NUC505 | ✅ | | ✅ | nuc505 | |
+--------------+---------+-------------------+--------+------+-----------+------------------------+--------------------+
-| NXP | iMXRT | RT 10xx, 11xx | ✔ | ✔ | ✔ | ci_hs, ehci | |
+| NXP | iMXRT | RT 10xx, 11xx | ✅ | ✅ | ✅ | ci_hs, ehci | |
| +---------+-------------------+--------+------+-----------+------------------------+--------------------+
-| | Kinetis | KL | ✔ | ⚠ | ✖ | ci_fs, khci | |
+| | Kinetis | KL | ✅ | 🟡 | ❌ | ci_fs, khci | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | K32L2 | ✔ | | ✖ | khci | ci_fs variant |
+| | | K32L2 | ✅ | | ❌ | khci | ci_fs variant |
| +---------+-------------------+--------+------+-----------+------------------------+--------------------+
-| | LPC | 11u, 13, 15 | ✔ | ✖ | ✖ | lpc_ip3511 | |
+| | LPC | 11u, 13, 15 | ✅ | ❌ | ❌ | lpc_ip3511 | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | 17, 40 | ✔ | ⚠ | ✖ | lpc17_40, ohci | |
+| | | 17, 40 | ✅ | 🟡 | ❌ | lpc17_40, ohci | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | 18, 43 | ✔ | ✔ | ✔ | ci_hs, ehci | |
+| | | 18, 43 | ✅ | ✅ | ✅ | ci_hs, ehci | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | 51u | ✔ | ✖ | ✖ | lpc_ip3511 | |
+| | | 51u | ✅ | ❌ | ❌ | lpc_ip3511 | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | 54 | ⚠ | ⚠ | ✔ | lpc_ip3511, lpc_ip3516 | NRND, read errata |
+| | | 54 | 🟡 | 🟡 | ✅ | lpc_ip3511, lpc_ip3516 | NRND [1]_ |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | 55 | ✔ | ✔ | ✔ | lpc_ip3511, lpc_ip3516 | |
+| | | 55 | ✅ | ✅ | ✅ | lpc_ip3511, lpc_ip3516 | |
| +---------+-------------------+--------+------+-----------+------------------------+--------------------+
-| | MCX | N9 | ✔ | | ✔ | ci_fs, ci_hs, ehci | |
+| | MCX | N9 | ✅ | | ✅ | ci_fs, ci_hs, ehci | |
| | +-------------------+--------+------+-----------+------------------------+--------------------+
-| | | A15 | ✔ | | | ci_fs | |
+| | | A15 | ✅ | | | ci_fs | |
| +---------+-------------------+--------+------+-----------+------------------------+--------------------+
-| | RW61x | ✔ | ✔ | ✔ | ci_hs, ehci | |
+| | RW61x | ✅ | ✅ | ✅ | ci_hs, ehci | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Raspberry Pi | RP2040, RP2350 | ✔ | ✔ | ✖ | rp2040, pio_usb | |
+| Raspberry Pi | RP2040, RP2350 | ✅ | ✅ | ❌ | rp2040, pio_usb | |
+--------------+-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| Renesas | RX | 63N, 65N, 72N | ✔ | ✔ | ✖ | rusb2 | |
+| Renesas | RX | 63N, 65N, 72N | ✅ | ✅ | ❌ | rusb2 | |
| +-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| | RA | 4M1, 4M3, 6M1 | ✔ | ✔ | ✖ | rusb2 | |
+| | RA | 4M1, 4M3, 6M1 | ✅ | ✅ | ❌ | rusb2 | |
| | +-----------------------+--------+------+-----------+------------------------+--------------------+
-| | | 6M5 | ✔ | ✔ | ✔ | rusb2 | |
+| | | 6M5 | ✅ | ✅ | ✅ | rusb2 | |
+--------------+-----+-----------------------+--------+------+-----------+------------------------+--------------------+
-| Silabs | EFM32GG12 | ✔ | | ✖ | dwc2 | |
+| Silabs | EFM32GG12 | ✅ | | ❌ | dwc2 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| Sony | CXD56 | ✔ | ✖ | ✔ | cxd56 | |
+| Sony | CXD56 | ✅ | ❌ | ✅ | cxd56 | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| ST STM32 | F0, F3, L0, L1, L5, WBx5 | ✔ | ✖ | ✖ | stm32_fsdev | |
+| ST STM32 | F0, F3, L0, L1, L5, WBx5 | ✅ | ❌ | ❌ | stm32_fsdev | |
| +----+------------------------+--------+------+-----------+------------------------+--------------------+
-| | F1 | 102, 103 | ✔ | ✖ | ✖ | stm32_fsdev | 512 USB RAM |
+| | F1 | 102, 103 | ✅ | ❌ | ❌ | stm32_fsdev | 512 USB RAM |
| | +------------------------+--------+------+-----------+------------------------+--------------------+
-| | | 105, 107 | ✔ | ✔ | ✖ | dwc2 | |
+| | | 105, 107 | ✅ | ✅ | ❌ | dwc2 | |
| +----+------------------------+--------+------+-----------+------------------------+--------------------+
-| | F2, F4, F7, H7, H7RS | ✔ | ✔ | ✔ | dwc2 | |
+| | F2, F4, F7, H7, H7RS | ✅ | ✅ | ✅ | dwc2 | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | C0, G0, H5, U3 | ✔ | ✔ | ✖ | stm32_fsdev | 2KB USB RAM |
+| | C0, C5, G0, H5, U3 | ✅ | ✅ | ❌ | stm32_fsdev | 2KB USB RAM |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | G4 | ✔ | ✖ | ✖ | stm32_fsdev | 1KB USB RAM |
+| | G4 | ✅ | ❌ | ❌ | stm32_fsdev | 1KB USB RAM |
| +----+------------------------+--------+------+-----------+------------------------+--------------------+
-| | L4 | 4x2, 4x3 | ✔ | ✖ | ✖ | stm32_fsdev | 1KB USB RAM |
+| | L4 | 4x2, 4x3 | ✅ | ❌ | ❌ | stm32_fsdev | 1KB USB RAM |
| | +------------------------+--------+------+-----------+------------------------+--------------------+
-| | | 4x5, 4x6, 4+ | ✔ | ✔ | ✖ | dwc2 | |
+| | | 4x5, 4x6, 4+ | ✅ | ✅ | ❌ | dwc2 | |
| +----+------------------------+--------+------+-----------+------------------------+--------------------+
-| | N6 | ✔ | ✔ | ✔ | dwc2 | |
+| | N6 | ✅ | ✅ | ✅ | dwc2 | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | U0 | ✔ | ✖ | ✖ | stm32_fsdev | 1KB USB RAM |
+| | U0 | ✅ | ❌ | ❌ | stm32_fsdev | 1KB USB RAM |
| +----+------------------------+--------+------+-----------+------------------------+--------------------+
-| | U5 | 535, 545 | ✔ | ✔ | ✖ | stm32_fsdev | 2KB USB RAM |
+| | U5 | 535, 545 | ✅ | ✅ | ❌ | stm32_fsdev | 2KB USB RAM |
| | +------------------------+--------+------+-----------+------------------------+--------------------+
-| | | 575, 585 | ✔ | ✔ | ✖ | dwc2 | |
+| | | 575, 585 | ✅ | ✅ | ❌ | dwc2 | |
| | +------------------------+--------+------+-----------+------------------------+--------------------+
-| | | 59x,5Ax,5Fx,5Gx | ✔ | ✔ | ✔ | dwc2 | |
+| | | 59x,5Ax,5Fx,5Gx | ✅ | ✅ | ✅ | dwc2 | |
+--------------+----+------------------------+--------+------+-----------+------------------------+--------------------+
-| TI | MSP430 | ✔ | ✖ | ✖ | msp430x5xx | |
+| TI | MSP430 | ✅ | ❌ | ❌ | msp430x5xx | |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | MSP432E4, TM4C123 | ✔ | | ✖ | musb | |
+| | MSP432E4, TM4C123 | ✅ | | ❌ | musb | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| ValentyUSB | eptri | ✔ | ✖ | ✖ | eptri | |
+| ValentyUSB | eptri | ✅ | ❌ | ❌ | eptri | |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
-| WCH | CH32F20x | ✔ | | ✔ | ch32_usbhs | |
+| WCH | CH32F20x | 🟡 | | ✅ | ch32_usbhs | ISO data loss [2]_ |
+| +-----------------------------+--------+------+-----------+------------------------+--------------------+
+| | CH32V20x | 🟡 | | ❌ | stm32_fsdev/ch32_usbfs | ISO data loss [2]_ |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | CH32V20x | ✔ | | ✖ | stm32_fsdev/ch32_usbfs | |
+| | CH32V305, CH32V307 | 🟡 | | ✅ | ch32_usbfs/hs | ISO data loss [2]_ |
| +-----------------------------+--------+------+-----------+------------------------+--------------------+
-| | CH32V305, CH32V307 | ✔ | | ✔ | ch32_usbfs/hs | |
+| | CH32V103 | 🟡 | | ❌ | ch32_usbfs | ISO data loss [2]_ |
+| +-----------------------------+--------+------+-----------+------------------------+--------------------+
+| | CH583, CH582 | 🟡 | | ❌ | ch32_usbfs | Device only |
+--------------+-----------------------------+--------+------+-----------+------------------------+--------------------+
Table Legend
^^^^^^^^^^^^
========= =========================
-✔ Supported
-⚠ Partial support
-✖ Not supported by hardware
+✅ Supported
+🟡 Partial support
+❌ Not supported by hardware
\[empty\] Unknown
========= =========================
+.. [1] NRND (Not Recommended for New Design), see `NXP LPC54600 issues <docs/reference/device_issues.rst#nxp-lpc54600>`_
+.. [2] ISO data loss, see `WCH CH32F20x/CH32V20x/CH32V30x issues <docs/reference/device_issues.rst#wch-ch32f20x-ch32v20x-ch32v30x>`_
+
Development Tools
-----------------
@@ -301,6 +353,8 @@ The following tools are provided freely to support the development of the TinyUS
:target: https://membrowse.com/public/hathach/tinyusb
.. |License| image:: https://img.shields.io/badge/license-MIT-brightgreen.svg
:target: https://opensource.org/licenses/MIT
+.. |Sponsor| image:: https://img.shields.io/badge/sponsor-%E2%9D%A4-ec6cb9.svg
+ :target: https://github.com/sponsors/hathach
.. _Changelog: docs/info/changelog.rst
diff --git a/docs/assets/adafruit_logo.svg b/docs/assets/adafruit_logo.svg
index cafd5a10e..e978f2c6e 100644
--- a/docs/assets/adafruit_logo.svg
+++ b/docs/assets/adafruit_logo.svg
@@ -1,8 +1,8 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" style="enable-background:new 0 0 1382 768;" xml:space="preserve" width="144" height="80" viewBox="14 12.81 1350 455.81">
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" style="enable-background:new 0 0 1382 768;" xml:space="preserve" width="224" height="89.6" viewBox="-56 -57.19 1490 595.81">
<style type="text/css">
- .st0{fill:#0;}
+ .st0{fill:#000;}
</style>
-<rect x="0" y="0" width="1382" height="768" fill="#fff"/>
+<rect x="-56" y="-57.19" width="1490" height="595.81" rx="60" ry="60" fill="#fff"/>
<g>
<g>
<g>
diff --git a/docs/assets/stack.svg b/docs/assets/stack.svg
index ed46c8649..113c92b60 100644
--- a/docs/assets/stack.svg
+++ b/docs/assets/stack.svg
@@ -1 +1 @@
-<svg version="1.1" viewBox="0.0 0.0 510.73490813648294 310.08923884514434" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="p.0"><path d="m0 0l510.7349 0l0 310.08923l-510.7349 0l0 -310.08923z" clip-rule="nonzero"/></clipPath><g clip-path="url(#p.0)"><path fill="#ffffff" d="m0 0l510.7349 0l0 310.08923l-510.7349 0z" fill-rule="evenodd"/><path fill="#cfe2f3" d="m28.509478 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m55.37576 252.31943l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.8967705 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm12.972076 -2.515625l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.4592743 -0.125q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307358 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm10.963608 -1.15625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2438507 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.4118958 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.3906326 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.5937576 0 -2.5781326 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.6093826 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.9687576 0 -1.6093826 0.71875q-0.625 0.71875 -0.625 2.1875zm7.2761154 3.796875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2561493 0l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.490524 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166733 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.124496 0l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021759 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.3655396 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.1667175 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m109.94667 270.31943l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm18.021774 -3.671875l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm3.0998993 3.671875l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m240.27715 252.31943l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.240524 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm18.894958 0.859375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.459259 -0.125q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307373 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm10.963593 -1.15625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.243866 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.4118958 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.2760925 3.796875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2561646 0l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.490509 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.124481 0l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.02179 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.365509 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m302.17975 270.31943l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm16.67804 -2.4375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm3.099884 3.671875l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m263.86716 149.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2249146 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm12.503815 1.234375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.24054 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm11.4105835 4.53125l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021759 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.365509 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m304.5869 167.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2249146 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm8.431854 1.234375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#cfe2f3" d="m28.509478 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m78.9189 149.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2248993 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm12.550705 1.234375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.896774 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm5.4877014 1.15625l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021774 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.3655243 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166733 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m112.30695 167.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2248993 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375076 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0000076 0zm1.390625 -6.078125l2.2656326 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.0937576 0l0 3.171875zm0 4.84375l2.6093826 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.4218826 0l0 3.609375zm8.478737 1.234375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0z" fill-rule="nonzero"/><path fill="#d9d9d9" d="m28.509478 27.969963l384.56693 0l0 48.62992l-384.56693 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 27.969963l384.56693 0l0 48.62992l-384.56693 0z" fill-rule="evenodd"/><path fill="#000000" d="m184.92747 57.36492l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.7443542 7.21875l0 -10.5l1.171875 0l0 0.984375q0.421875 -0.578125 0.9375 -0.859375q0.515625 -0.296875 1.265625 -0.296875q0.96875 0 1.71875 0.5q0.75 0.5 1.125 1.421875q0.375 0.90625 0.375 1.984375q0 1.171875 -0.421875 2.109375q-0.40625 0.921875 -1.21875 1.421875q-0.796875 0.5 -1.671875 0.5q-0.640625 0 -1.15625 -0.265625q-0.515625 -0.28125 -0.84375 -0.6875l0 3.6875l-1.28125 0zm1.15625 -6.65625q0 1.453125 0.59375 2.15625q0.609375 0.703125 1.453125 0.703125q0.859375 0 1.46875 -0.71875q0.609375 -0.734375 0.609375 -2.25q0 -1.453125 -0.609375 -2.171875q-0.59375 -0.734375 -1.421875 -0.734375q-0.8125 0 -1.453125 0.78125q-0.640625 0.765625 -0.640625 2.234375zm6.994858 6.65625l0 -10.5l1.171875 0l0 0.984375q0.421875 -0.578125 0.9375 -0.859375q0.515625 -0.296875 1.265625 -0.296875q0.96875 0 1.71875 0.5q0.75 0.5 1.125 1.421875q0.375 0.90625 0.375 1.984375q0 1.171875 -0.421875 2.109375q-0.40625 0.921875 -1.21875 1.421875q-0.796875 0.5 -1.671875 0.5q-0.640625 0 -1.15625 -0.265625q-0.515625 -0.28125 -0.84375 -0.6875l0 3.6875l-1.28125 0zm1.15625 -6.65625q0 1.453125 0.59375 2.15625q0.609375 0.703125 1.453125 0.703125q0.859375 0 1.46875 -0.71875q0.609375 -0.734375 0.609375 -2.25q0 -1.453125 -0.609375 -2.171875q-0.59375 -0.734375 -1.421875 -0.734375q-0.8125 0 -1.453125 0.78125q-0.640625 0.765625 -0.640625 2.234375zm6.963608 3.75l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2873993 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.209274 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.328125 1.84375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm6.119858 2.65625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2594757 -7.859375l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm2.7717743 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307358 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0z" fill-rule="nonzero"/><path fill="#d9d2e9" d="m28.509478 195.19305l384.56693 0l0 29.606308l-384.56693 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 195.19305l384.56693 0l0 29.606308l-384.56693 0z" fill-rule="evenodd"/><path fill="#000000" d="m125.783455 209.96683q0 -2.609375 1.40625 -4.078125q1.4062576 -1.484375 3.6250076 -1.484375q1.453125 0 2.609375 0.703125q1.171875 0.6875 1.78125 1.921875q0.609375 1.234375 0.609375 2.8125q0 1.59375 -0.640625 2.859375q-0.640625 1.265625 -1.828125 1.90625q-1.171875 0.640625 -2.546875 0.640625q-1.46875 0 -2.640625 -0.703125q-1.1718826 -0.71875 -1.7812576 -1.953125q-0.59375 -1.25 -0.59375 -2.625zm1.4375 0.015625q0 1.90625 1.0156326 3.0q1.015625 1.078125 2.5625 1.078125q1.5625 0 2.578125 -1.09375q1.015625 -1.109375 1.015625 -3.125q0 -1.28125 -0.4375 -2.234375q-0.4375 -0.96875 -1.265625 -1.484375q-0.828125 -0.53125 -1.875 -0.53125q-1.46875 0 -2.53125 1.015625q-1.0625076 1.015625 -1.0625076 3.375zm9.915733 1.71875l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm12.366455 3.375l4.015625 -10.484375l1.5 0l4.2968597 10.484375l-1.578125 0l-1.2343597 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm8.931839 4.3125l-1.203125 0l0 -10.484375l1.296875 0l0 3.734375q0.8125 -1.015625 2.078125 -1.015625q0.703125 0 1.328125 0.28125q0.625 0.28125 1.03125 0.796875q0.40625 0.5 0.625 1.234375q0.234375 0.71875 0.234375 1.53125q0 1.96875 -0.96875 3.03125q-0.953125 1.0625 -2.3125 1.0625q-1.34375 0 -2.109375 -1.125l0 0.953125zm-0.015625 -3.859375q0 1.375 0.375 1.984375q0.609375 0.984375 1.640625 0.984375q0.84375 0 1.453125 -0.734375q0.625 -0.734375 0.625 -2.1875q0 -1.484375 -0.59375 -2.1875q-0.59375 -0.71875 -1.421875 -0.71875q-0.84375 0 -1.46875 0.734375q-0.609375 0.734375 -0.609375 2.125zm6.463623 1.59375l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2438354 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.849396 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm8.260498 1.03125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm5.1875 1.625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2594604 -7.859375l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm2.7717896 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.3073425 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm12.3324585 0l0 -10.484375l1.390625 0l0 9.25l5.15625 0l0 1.234375l-6.546875 0zm12.994873 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm3.2448425 6.734375l-0.140625 -1.203125q0.421875 0.109375 0.734375 0.109375q0.4375 0 0.6875 -0.140625q0.265625 -0.140625 0.421875 -0.40625q0.125 -0.1875 0.390625 -0.953125q0.046875 -0.109375 0.125 -0.3125l-2.890625 -7.609375l1.390625 0l1.578125 4.390625q0.3125 0.84375 0.546875 1.765625q0.234375 -0.890625 0.53125 -1.734375l1.625 -4.421875l1.296875 0l-2.890625 7.71875q-0.46875 1.25 -0.734375 1.734375q-0.34375 0.625 -0.78125 0.921875q-0.4375 0.296875 -1.0625 0.296875q-0.375 0 -0.828125 -0.15625zm12.593765 -5.375l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.1718903 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.5156403 0 2.4843903 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.6562653 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.50001526 -0.375 0.79689026 -1.203125zm-4.2343903 -2.078125l4.2500153 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.62501526 -0.75 -1.6093903 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.1667633 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm11.421356 3.078125q-1.0625 -1.34375 -1.796875 -3.140625q-0.734375 -1.8125 -0.734375 -3.734375q0 -1.703125 0.546875 -3.265625q0.640625 -1.8125 1.984375 -3.609375l0.921875 0q-0.859375 1.484375 -1.140625 2.125q-0.4375 0.984375 -0.6875 2.0625q-0.296875 1.34375 -0.296875 2.6875q0 3.453125 2.125 6.875l-0.921875 0zm2.1618958 -8.1875q0 -2.609375 1.40625 -4.078125q1.40625 -1.484375 3.625 -1.484375q1.453125 0 2.609375 0.703125q1.171875 0.6875 1.78125 1.921875q0.609375 1.234375 0.609375 2.8125q0 1.59375 -0.640625 2.859375q-0.640625 1.265625 -1.828125 1.90625q-1.171875 0.640625 -2.546875 0.640625q-1.46875 0 -2.640625 -0.703125q-1.171875 -0.71875 -1.78125 -1.953125q-0.59375 -1.25 -0.59375 -2.625zm1.4375 0.015625q0 1.90625 1.015625 3.0q1.015625 1.078125 2.5625 1.078125q1.5625 0 2.578125 -1.09375q1.015625 -1.109375 1.015625 -3.125q0 -1.28125 -0.4375 -2.234375q-0.4375 -0.96875 -1.265625 -1.484375q-0.828125 -0.53125 -1.875 -0.53125q-1.46875 0 -2.53125 1.015625q-1.0625 1.015625 -1.0625 3.375zm9.915741 1.71875l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm9.103729 3.375l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.8537292 4.3125l0 -10.484375l1.390625 0l0 9.25l5.15625 0l0 1.234375l-6.546875 0zm8.885468 3.078125l-0.921875 0q2.140625 -3.421875 2.140625 -6.875q0 -1.34375 -0.3125 -2.671875q-0.25 -1.0625 -0.671875 -2.046875q-0.28125 -0.65625 -1.15625 -2.15625l0.921875 0q1.34375 1.796875 1.984375 3.609375q0.546875 1.5625 0.546875 3.265625q0 1.921875 -0.734375 3.734375q-0.734375 1.796875 -1.796875 3.140625z" fill-rule="nonzero"/><path fill="#cfe2f3" d="m28.509478 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m76.95251 104.10596l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.896774 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm12.972076 -2.515625l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.9123993 3.671875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.240532 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.6562576 0.25 -1.4218826 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625076 -0.1875 2.2968826 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.4531326 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.7187576 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.0937576 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.7343826 0 1.3125076 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm2.7917328 1.546875l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm7.328125 0l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.122101 2.265625l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.9006042 4.3125l0 -10.484375l3.96875 0q1.046875 0 1.59375 0.09375q0.765625 0.125 1.28125 0.484375q0.53125 0.359375 0.84375 1.015625q0.328125 0.65625 0.328125 1.4375q0 1.328125 -0.859375 2.265625q-0.84375 0.921875 -3.078125 0.921875l-2.6875 0l0 4.265625l-1.390625 0zm1.390625 -5.5l2.71875 0q1.34375 0 1.90625 -0.5q0.5625 -0.5 0.5625 -1.40625q0 -0.671875 -0.328125 -1.140625q-0.328125 -0.46875 -0.875 -0.609375q-0.359375 -0.09375 -1.296875 -0.09375l-2.6875 0l0 3.75zm8.619354 5.5l0 -10.484375l1.390625 0l0 10.484375l-1.390625 0z" fill-rule="nonzero"/><path fill="#000000" d="m113.3875 122.10595l0 -9.25l-3.453125 0l0 -1.234375l8.3125 0l0 1.234375l-3.46875 0l0 9.25l-1.390625 0zm13.171371 -10.484375l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.7405243 10.484375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m261.85388 104.10596l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.24054 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm18.894958 0.859375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.912384 3.671875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.24054 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm2.7917175 1.546875l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm7.328125 0l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.122101 2.265625l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.9006042 4.3125l0 -10.484375l3.96875 0q1.046875 0 1.59375 0.09375q0.765625 0.125 1.28125 0.484375q0.53125 0.359375 0.84375 1.015625q0.328125 0.65625 0.328125 1.4375q0 1.328125 -0.859375 2.265625q-0.84375 0.921875 -3.078125 0.921875l-2.6875 0l0 4.265625l-1.390625 0zm1.390625 -5.5l2.71875 0q1.34375 0 1.90625 -0.5q0.5625 -0.5 0.5625 -1.40625q0 -0.671875 -0.328125 -1.140625q-0.328125 -0.46875 -0.875 -0.609375q-0.359375 -0.09375 -1.296875 -0.09375l-2.6875 0l0 3.75zm8.619354 5.5l0 -10.484375l1.390625 0l0 10.484375l-1.390625 0z" fill-rule="nonzero"/><path fill="#000000" d="m305.66745 122.10595l0 -9.25l-3.453125 0l0 -1.234375l8.3125 0l0 1.234375l-3.46875 0l0 9.25l-1.390625 0zm13.171387 -10.484375l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.693634 10.484375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#000000" fill-opacity="0.0" d="m414.7422 230.80695l0 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m414.7422 230.80695l0 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m416.97958 84.35958l69.102356 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" stroke-dasharray="8.0,3.0" d="m416.97958 84.35958l69.102356 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m430.57208 84.35958l69.10239 0l0 37.5748l-69.10239 0z" fill-rule="evenodd"/><path fill="#000000" d="m441.68146 103.87958l0 -7.578125l-2.828125 0l0 -1.015625l6.8125 0l0 1.015625l-2.84375 0l0 7.578125l-1.140625 0zm4.5722656 -7.375l0 -1.21875l1.0625 0l0 1.21875l-1.0625 0zm0 7.375l0 -6.21875l1.0625 0l0 6.21875l-1.0625 0zm2.6660156 0l0 -6.21875l0.9375 0l0 0.875q0.6875 -1.015625 1.984375 -1.015625q0.5625 0 1.03125 0.203125q0.484375 0.203125 0.71875 0.53125q0.234375 0.328125 0.328125 0.765625q0.046875 0.296875 0.046875 1.03125l0 3.828125l-1.046875 0l0 -3.78125q0 -0.65625 -0.125 -0.96875q-0.125 -0.3125 -0.4375 -0.5q-0.3125 -0.203125 -0.734375 -0.203125q-0.671875 0 -1.171875 0.4375q-0.484375 0.421875 -0.484375 1.609375l0 3.40625l-1.046875 0zm6.626953 2.390625l-0.125 -0.984375q0.34375 0.09375 0.609375 0.09375q0.34375 0 0.546875 -0.125q0.21875 -0.109375 0.359375 -0.3125q0.09375 -0.171875 0.328125 -0.796875q0.015625 -0.078125 0.09375 -0.25l-2.375 -6.234375l1.140625 0l1.296875 3.59375q0.25 0.6875 0.453125 1.453125q0.1875 -0.734375 0.4375 -1.421875l1.328125 -3.625l1.046875 0l-2.359375 6.328125q-0.390625 1.015625 -0.59375 1.40625q-0.28125 0.53125 -0.65625 0.765625q-0.359375 0.25 -0.859375 0.25q-0.296875 0 -0.671875 -0.140625zm11.8125 -10.984375l1.140625 0l0 4.96875q0 1.296875 -0.296875 2.0625q-0.296875 0.75 -1.0625 1.234375q-0.765625 0.46875 -2.0 0.46875q-1.203125 0 -1.984375 -0.40625q-0.765625 -0.421875 -1.09375 -1.203125q-0.328125 -0.796875 -0.328125 -2.15625l0 -4.96875l1.140625 0l0 4.953125q0 1.125 0.203125 1.65625q0.21875 0.53125 0.71875 0.828125q0.515625 0.28125 1.25 0.28125q1.25 0 1.78125 -0.5625q0.53125 -0.578125 0.53125 -2.203125l0 -4.953125zm2.6503906 5.828125l1.0625 -0.09375q0.078125 0.65625 0.359375 1.0625q0.28125 0.40625 0.859375 0.671875q0.59375 0.25 1.328125 0.25q0.640625 0 1.140625 -0.1875q0.5 -0.203125 0.734375 -0.53125q0.25 -0.34375 0.25 -0.734375q0 -0.40625 -0.234375 -0.703125q-0.234375 -0.3125 -0.765625 -0.515625q-0.359375 -0.140625 -1.546875 -0.421875q-1.171875 -0.28125 -1.640625 -0.53125q-0.625 -0.328125 -0.921875 -0.796875q-0.296875 -0.484375 -0.296875 -1.078125q0 -0.640625 0.359375 -1.203125q0.375 -0.578125 1.078125 -0.859375q0.71875 -0.296875 1.578125 -0.296875q0.953125 0 1.6875 0.3125q0.734375 0.296875 1.125 0.90625q0.390625 0.59375 0.421875 1.34375l-1.09375 0.078125q-0.09375 -0.8125 -0.609375 -1.21875q-0.5 -0.421875 -1.484375 -0.421875q-1.03125 0 -1.5 0.375q-0.46875 0.375 -0.46875 0.90625q0 0.46875 0.328125 0.765625q0.328125 0.296875 1.703125 0.609375q1.390625 0.3125 1.90625 0.546875q0.75 0.359375 1.109375 0.890625q0.359375 0.515625 0.359375 1.21875q0 0.6875 -0.390625 1.296875q-0.390625 0.59375 -1.125 0.9375q-0.734375 0.328125 -1.65625 0.328125q-1.171875 0 -1.96875 -0.328125q-0.78125 -0.34375 -1.234375 -1.03125q-0.4375 -0.6875 -0.453125 -1.546875zm8.332031 2.765625l0 -8.59375l3.234375 0q0.984375 0 1.578125 0.265625q0.59375 0.265625 0.921875 0.8125q0.34375 0.53125 0.34375 1.125q0 0.546875 -0.296875 1.03125q-0.296875 0.484375 -0.90625 0.78125q0.78125 0.234375 1.1875 0.796875q0.421875 0.546875 0.421875 1.296875q0 0.59375 -0.25 1.125q-0.25 0.515625 -0.625 0.796875q-0.375 0.28125 -0.953125 0.421875q-0.5625 0.140625 -1.375 0.140625l-3.28125 0zm1.140625 -4.984375l1.859375 0q0.75 0 1.078125 -0.09375q0.4375 -0.125 0.65625 -0.421875q0.21875 -0.3125 0.21875 -0.765625q0 -0.421875 -0.203125 -0.75q-0.203125 -0.328125 -0.59375 -0.4375q-0.375 -0.125 -1.296875 -0.125l-1.71875 0l0 2.59375zm0 3.96875l2.140625 0q0.546875 0 0.765625 -0.046875q0.40625 -0.0625 0.65625 -0.21875q0.265625 -0.171875 0.4375 -0.484375q0.171875 -0.3125 0.171875 -0.71875q0 -0.484375 -0.25 -0.84375q-0.234375 -0.359375 -0.671875 -0.5q-0.4375 -0.140625 -1.265625 -0.140625l-1.984375 0l0 2.953125z" fill-rule="nonzero"/><path fill="#000000" fill-opacity="0.0" d="m416.97958 231.92447l69.102356 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" stroke-dasharray="8.0,3.0" d="m416.97958 231.92447l69.102356 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m429.0601 231.92447l72.12598 0l0 37.5748l-72.12598 0z" fill-rule="evenodd"/><path fill="#000000" d="m437.9507 251.44447l0 -8.59375l1.71875 0l2.03125 6.078125q0.28125 0.859375 0.40625 1.28125q0.140625 -0.46875 0.453125 -1.375l2.0625 -5.984375l1.53125 0l0 8.59375l-1.09375 0l0 -7.1875l-2.5 7.1875l-1.03125 0l-2.484375 -7.3125l0 7.3125l-1.09375 0zm16.167969 -3.015625l1.125 0.296875q-0.359375 1.390625 -1.28125 2.125q-0.921875 0.734375 -2.265625 0.734375q-1.390625 0 -2.265625 -0.5625q-0.875 -0.5625 -1.328125 -1.625q-0.453125 -1.078125 -0.453125 -2.3125q0 -1.34375 0.515625 -2.34375q0.515625 -1.0 1.453125 -1.515625q0.953125 -0.515625 2.09375 -0.515625q1.28125 0 2.15625 0.65625q0.890625 0.65625 1.234375 1.84375l-1.125 0.265625q-0.296875 -0.9375 -0.875 -1.359375q-0.5625 -0.4375 -1.421875 -0.4375q-0.984375 0 -1.65625 0.484375q-0.65625 0.46875 -0.9375 1.265625q-0.265625 0.796875 -0.265625 1.65625q0 1.09375 0.3125 1.90625q0.328125 0.8125 1.0 1.21875q0.671875 0.40625 1.46875 0.40625q0.953125 0 1.609375 -0.546875q0.671875 -0.546875 0.90625 -1.640625zm8.166016 -5.578125l1.140625 0l0 4.96875q0 1.296875 -0.296875 2.0625q-0.296875 0.75 -1.0625 1.234375q-0.765625 0.46875 -2.0 0.46875q-1.203125 0 -1.984375 -0.40625q-0.765625 -0.421875 -1.09375 -1.203125q-0.328125 -0.796875 -0.328125 -2.15625l0 -4.96875l1.140625 0l0 4.953125q0 1.125 0.203125 1.65625q0.21875 0.53125 0.71875 0.828125q0.515625 0.28125 1.25 0.28125q1.25 0 1.78125 -0.5625q0.53125 -0.578125 0.53125 -2.203125l0 -4.953125zm6.359375 8.59375l0 -8.59375l3.25 0q0.84375 0 1.296875 0.078125q0.640625 0.109375 1.0625 0.40625q0.4375 0.296875 0.6875 0.828125q0.265625 0.53125 0.265625 1.171875q0 1.09375 -0.703125 1.859375q-0.6875 0.75 -2.515625 0.75l-2.203125 0l0 3.5l-1.140625 0zm1.140625 -4.5l2.21875 0q1.109375 0 1.5625 -0.40625q0.46875 -0.421875 0.46875 -1.171875q0 -0.53125 -0.28125 -0.90625q-0.265625 -0.390625 -0.703125 -0.515625q-0.296875 -0.078125 -1.0625 -0.078125l-2.203125 0l0 3.078125zm6.3476562 1.390625q0 -1.734375 0.953125 -2.5625q0.796875 -0.6875 1.953125 -0.6875q1.28125 0 2.09375 0.84375q0.828125 0.828125 0.828125 2.3125q0 1.203125 -0.359375 1.890625q-0.359375 0.6875 -1.0625 1.078125q-0.6875 0.375 -1.5 0.375q-1.296875 0 -2.109375 -0.828125q-0.796875 -0.84375 -0.796875 -2.421875zm1.078125 0q0 1.1875 0.515625 1.78125q0.53125 0.59375 1.3125 0.59375q0.796875 0 1.3125 -0.59375q0.515625 -0.59375 0.515625 -1.8125q0 -1.15625 -0.53125 -1.75q-0.515625 -0.59375 -1.296875 -0.59375q-0.78125 0 -1.3125 0.59375q-0.515625 0.578125 -0.515625 1.78125zm5.970703 3.109375l0 -6.21875l0.953125 0l0 0.9375q0.359375 -0.65625 0.65625 -0.859375q0.3125 -0.21875 0.6875 -0.21875q0.53125 0 1.078125 0.328125l-0.359375 0.984375q-0.390625 -0.234375 -0.765625 -0.234375q-0.359375 0 -0.640625 0.21875q-0.265625 0.203125 -0.375 0.578125q-0.1875 0.5625 -0.1875 1.21875l0 3.265625l-1.046875 0zm6.3085938 -0.9375l0.15625 0.921875q-0.453125 0.09375 -0.796875 0.09375q-0.578125 0 -0.890625 -0.171875q-0.3125 -0.1875 -0.453125 -0.484375q-0.125 -0.296875 -0.125 -1.25l0 -3.578125l-0.765625 0l0 -0.8125l0.765625 0l0 -1.546875l1.046875 -0.625l0 2.171875l1.0625 0l0 0.8125l-1.0625 0l0 3.640625q0 0.453125 0.046875 0.578125q0.0625 0.125 0.1875 0.203125q0.125 0.078125 0.359375 0.078125q0.1875 0 0.46875 -0.03125z" fill-rule="nonzero"/></g></svg>
+<svg version="1.1" viewBox="0.0 0.0 510.73490813648294 310.08923884514434" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="p.0"><rect x="0" y="0" width="510.73490813648294" height="310.08923884514434" rx="20" ry="20"/></clipPath><g clip-path="url(#p.0)"><rect fill="#ffffff" x="0" y="0" width="510.73490813648294" height="310.08923884514434" rx="20" ry="20"/><path fill="#cfe2f3" d="m28.509478 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m55.37576 252.31943l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.8967705 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm12.972076 -2.515625l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.4592743 -0.125q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307358 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm10.963608 -1.15625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2438507 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.4118958 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.3906326 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.5937576 0 -2.5781326 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.6093826 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.9687576 0 -1.6093826 0.71875q-0.625 0.71875 -0.625 2.1875zm7.2761154 3.796875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2561493 0l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.490524 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166733 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.124496 0l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021759 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.3655396 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.1667175 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m109.94667 270.31943l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm18.021774 -3.671875l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm3.0998993 3.671875l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 231.92447l192.28346 0l0 48.629913l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m240.27715 252.31943l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.240524 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm18.894958 0.859375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.459259 -0.125q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307373 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm10.963593 -1.15625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.243866 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.4118958 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.2760925 3.796875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2561646 0l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.490509 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.124481 0l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.02179 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.365509 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m302.17975 270.31943l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm16.67804 -2.4375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm3.099884 3.671875l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m263.86716 149.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2249146 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm12.503815 1.234375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.24054 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm11.4105835 4.53125l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021759 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.365509 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166748 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m304.5869 167.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2249146 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm8.431854 1.234375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#cfe2f3" d="m28.509478 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 139.45203l192.28346 0l0 48.62993l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m78.9189 149.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2248993 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0 0zm1.390625 -6.078125l2.265625 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.09375 0l0 3.171875zm0 4.84375l2.609375 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.421875 0l0 3.609375zm12.550705 1.234375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.896774 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm5.4877014 1.15625l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm9.021774 1.234375l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm4.8962708 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm5.3655243 0l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm10.421875 -2.453125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.166733 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0z" fill-rule="nonzero"/><path fill="#000000" d="m112.30695 167.36261l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.2248993 7.109375l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm10.197479 3.375l0 -10.484375l3.9375076 0q1.203125 0 1.921875 0.3125q0.734375 0.3125 1.140625 0.984375q0.40625 0.65625 0.40625 1.375q0 0.671875 -0.375 1.265625q-0.359375 0.59375 -1.09375 0.96875q0.953125 0.28125 1.46875 0.953125q0.515625 0.671875 0.515625 1.578125q0 0.75 -0.3125 1.390625q-0.3125 0.625 -0.78125 0.96875q-0.453125 0.34375 -1.140625 0.515625q-0.6875 0.171875 -1.6875 0.171875l-4.0000076 0zm1.390625 -6.078125l2.2656326 0q0.921875 0 1.3125 -0.125q0.53125 -0.15625 0.796875 -0.515625q0.28125 -0.375 0.28125 -0.921875q0 -0.53125 -0.25 -0.921875q-0.25 -0.390625 -0.71875 -0.53125q-0.46875 -0.15625 -1.59375 -0.15625l-2.0937576 0l0 3.171875zm0 4.84375l2.6093826 0q0.671875 0 0.9375 -0.046875q0.484375 -0.09375 0.796875 -0.296875q0.328125 -0.203125 0.53125 -0.578125q0.21875 -0.390625 0.21875 -0.890625q0 -0.578125 -0.3125 -1.015625q-0.296875 -0.4375 -0.828125 -0.609375q-0.53125 -0.171875 -1.53125 -0.171875l-2.4218826 0l0 3.609375zm8.478737 1.234375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0z" fill-rule="nonzero"/><path fill="#d9d9d9" d="m28.509478 27.969963l384.56693 0l0 48.62992l-384.56693 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 27.969963l384.56693 0l0 48.62992l-384.56693 0z" fill-rule="evenodd"/><path fill="#000000" d="m184.92747 57.36492l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.7443542 7.21875l0 -10.5l1.171875 0l0 0.984375q0.421875 -0.578125 0.9375 -0.859375q0.515625 -0.296875 1.265625 -0.296875q0.96875 0 1.71875 0.5q0.75 0.5 1.125 1.421875q0.375 0.90625 0.375 1.984375q0 1.171875 -0.421875 2.109375q-0.40625 0.921875 -1.21875 1.421875q-0.796875 0.5 -1.671875 0.5q-0.640625 0 -1.15625 -0.265625q-0.515625 -0.28125 -0.84375 -0.6875l0 3.6875l-1.28125 0zm1.15625 -6.65625q0 1.453125 0.59375 2.15625q0.609375 0.703125 1.453125 0.703125q0.859375 0 1.46875 -0.71875q0.609375 -0.734375 0.609375 -2.25q0 -1.453125 -0.609375 -2.171875q-0.59375 -0.734375 -1.421875 -0.734375q-0.8125 0 -1.453125 0.78125q-0.640625 0.765625 -0.640625 2.234375zm6.994858 6.65625l0 -10.5l1.171875 0l0 0.984375q0.421875 -0.578125 0.9375 -0.859375q0.515625 -0.296875 1.265625 -0.296875q0.96875 0 1.71875 0.5q0.75 0.5 1.125 1.421875q0.375 0.90625 0.375 1.984375q0 1.171875 -0.421875 2.109375q-0.40625 0.921875 -1.21875 1.421875q-0.796875 0.5 -1.671875 0.5q-0.640625 0 -1.15625 -0.265625q-0.515625 -0.28125 -0.84375 -0.6875l0 3.6875l-1.28125 0zm1.15625 -6.65625q0 1.453125 0.59375 2.15625q0.609375 0.703125 1.453125 0.703125q0.859375 0 1.46875 -0.71875q0.609375 -0.734375 0.609375 -2.25q0 -1.453125 -0.609375 -2.171875q-0.59375 -0.734375 -1.421875 -0.734375q-0.8125 0 -1.453125 0.78125q-0.640625 0.765625 -0.640625 2.234375zm6.963608 3.75l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm3.2873993 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.209274 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.328125 1.84375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm6.119858 2.65625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2594757 -7.859375l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm2.7717743 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.307358 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0z" fill-rule="nonzero"/><path fill="#d9d2e9" d="m28.509478 195.19305l384.56693 0l0 29.606308l-384.56693 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 195.19305l384.56693 0l0 29.606308l-384.56693 0z" fill-rule="evenodd"/><path fill="#000000" d="m125.783455 209.96683q0 -2.609375 1.40625 -4.078125q1.4062576 -1.484375 3.6250076 -1.484375q1.453125 0 2.609375 0.703125q1.171875 0.6875 1.78125 1.921875q0.609375 1.234375 0.609375 2.8125q0 1.59375 -0.640625 2.859375q-0.640625 1.265625 -1.828125 1.90625q-1.171875 0.640625 -2.546875 0.640625q-1.46875 0 -2.640625 -0.703125q-1.1718826 -0.71875 -1.7812576 -1.953125q-0.59375 -1.25 -0.59375 -2.625zm1.4375 0.015625q0 1.90625 1.0156326 3.0q1.015625 1.078125 2.5625 1.078125q1.5625 0 2.578125 -1.09375q1.015625 -1.109375 1.015625 -3.125q0 -1.28125 -0.4375 -2.234375q-0.4375 -0.96875 -1.265625 -1.484375q-0.828125 -0.53125 -1.875 -0.53125q-1.46875 0 -2.53125 1.015625q-1.0625076 1.015625 -1.0625076 3.375zm9.915733 1.71875l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm12.366455 3.375l4.015625 -10.484375l1.5 0l4.2968597 10.484375l-1.578125 0l-1.2343597 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm8.931839 4.3125l-1.203125 0l0 -10.484375l1.296875 0l0 3.734375q0.8125 -1.015625 2.078125 -1.015625q0.703125 0 1.328125 0.28125q0.625 0.28125 1.03125 0.796875q0.40625 0.5 0.625 1.234375q0.234375 0.71875 0.234375 1.53125q0 1.96875 -0.96875 3.03125q-0.953125 1.0625 -2.3125 1.0625q-1.34375 0 -2.109375 -1.125l0 0.953125zm-0.015625 -3.859375q0 1.375 0.375 1.984375q0.609375 0.984375 1.640625 0.984375q0.84375 0 1.453125 -0.734375q0.625 -0.734375 0.625 -2.1875q0 -1.484375 -0.59375 -2.1875q-0.59375 -0.71875 -1.421875 -0.71875q-0.84375 0 -1.46875 0.734375q-0.609375 0.734375 -0.609375 2.125zm6.463623 1.59375l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2438354 1.15625l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm9.849396 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm8.260498 1.03125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm5.1875 1.625l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm1.2594604 -7.859375l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm2.7717896 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm7.3073425 3.796875l0 -7.59375l1.15625 0l0 1.078125q0.84375 -1.25 2.421875 -1.25q0.6875 0 1.265625 0.25q0.578125 0.234375 0.859375 0.640625q0.28125 0.40625 0.40625 0.953125q0.0625 0.359375 0.0625 1.25l0 4.671875l-1.28125 0l0 -4.625q0 -0.78125 -0.15625 -1.171875q-0.15625 -0.390625 -0.546875 -0.625q-0.375 -0.234375 -0.890625 -0.234375q-0.8125 0 -1.421875 0.53125q-0.59375 0.515625 -0.59375 1.96875l0 4.15625l-1.28125 0zm12.3324585 0l0 -10.484375l1.390625 0l0 9.25l5.15625 0l0 1.234375l-6.546875 0zm12.994873 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm3.2448425 6.734375l-0.140625 -1.203125q0.421875 0.109375 0.734375 0.109375q0.4375 0 0.6875 -0.140625q0.265625 -0.140625 0.421875 -0.40625q0.125 -0.1875 0.390625 -0.953125q0.046875 -0.109375 0.125 -0.3125l-2.890625 -7.609375l1.390625 0l1.578125 4.390625q0.3125 0.84375 0.546875 1.765625q0.234375 -0.890625 0.53125 -1.734375l1.625 -4.421875l1.296875 0l-2.890625 7.71875q-0.46875 1.25 -0.734375 1.734375q-0.34375 0.625 -0.78125 0.921875q-0.4375 0.296875 -1.0625 0.296875q-0.375 0 -0.828125 -0.15625zm12.593765 -5.375l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.1718903 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.5156403 0 2.4843903 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.6562653 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.50001526 -0.375 0.79689026 -1.203125zm-4.2343903 -2.078125l4.2500153 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.62501526 -0.75 -1.6093903 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm7.1667633 4.53125l0 -7.59375l1.15625 0l0 1.140625q0.453125 -0.796875 0.828125 -1.046875q0.375 -0.265625 0.8125 -0.265625q0.65625 0 1.328125 0.40625l-0.4375 1.203125q-0.46875 -0.28125 -0.953125 -0.28125q-0.421875 0 -0.765625 0.25q-0.328125 0.25 -0.46875 0.703125q-0.21875 0.6875 -0.21875 1.5l0 3.984375l-1.28125 0zm11.421356 3.078125q-1.0625 -1.34375 -1.796875 -3.140625q-0.734375 -1.8125 -0.734375 -3.734375q0 -1.703125 0.546875 -3.265625q0.640625 -1.8125 1.984375 -3.609375l0.921875 0q-0.859375 1.484375 -1.140625 2.125q-0.4375 0.984375 -0.6875 2.0625q-0.296875 1.34375 -0.296875 2.6875q0 3.453125 2.125 6.875l-0.921875 0zm2.1618958 -8.1875q0 -2.609375 1.40625 -4.078125q1.40625 -1.484375 3.625 -1.484375q1.453125 0 2.609375 0.703125q1.171875 0.6875 1.78125 1.921875q0.609375 1.234375 0.609375 2.8125q0 1.59375 -0.640625 2.859375q-0.640625 1.265625 -1.828125 1.90625q-1.171875 0.640625 -2.546875 0.640625q-1.46875 0 -2.640625 -0.703125q-1.171875 -0.71875 -1.78125 -1.953125q-0.59375 -1.25 -0.59375 -2.625zm1.4375 0.015625q0 1.90625 1.015625 3.0q1.015625 1.078125 2.5625 1.078125q1.5625 0 2.578125 -1.09375q1.015625 -1.109375 1.015625 -3.125q0 -1.28125 -0.4375 -2.234375q-0.4375 -0.96875 -1.265625 -1.484375q-0.828125 -0.53125 -1.875 -0.53125q-1.46875 0 -2.53125 1.015625q-1.0625 1.015625 -1.0625 3.375zm9.915741 1.71875l1.3125 -0.109375q0.09375 0.78125 0.421875 1.296875q0.34375 0.5 1.0625 0.8125q0.71875 0.3125 1.609375 0.3125q0.796875 0 1.40625 -0.234375q0.609375 -0.234375 0.90625 -0.640625q0.296875 -0.421875 0.296875 -0.90625q0 -0.5 -0.296875 -0.859375q-0.28125 -0.375 -0.9375 -0.625q-0.421875 -0.171875 -1.875 -0.515625q-1.4375 -0.34375 -2.015625 -0.65625q-0.75 -0.390625 -1.125 -0.96875q-0.359375 -0.59375 -0.359375 -1.3125q0 -0.796875 0.4375 -1.484375q0.453125 -0.6875 1.3125 -1.046875q0.875 -0.359375 1.9375 -0.359375q1.171875 0 2.0625 0.375q0.890625 0.375 1.359375 1.109375q0.484375 0.734375 0.515625 1.65625l-1.328125 0.09375q-0.109375 -1.0 -0.734375 -1.5q-0.609375 -0.515625 -1.8125 -0.515625q-1.265625 0 -1.84375 0.46875q-0.578125 0.46875 -0.578125 1.109375q0 0.5625 0.421875 0.9375q0.390625 0.359375 2.078125 0.75q1.703125 0.375 2.328125 0.65625q0.921875 0.421875 1.359375 1.078125q0.4375 0.640625 0.4375 1.484375q0 0.84375 -0.484375 1.59375q-0.484375 0.734375 -1.390625 1.140625q-0.890625 0.40625 -2.015625 0.40625q-1.421875 0 -2.390625 -0.40625q-0.953125 -0.421875 -1.5 -1.25q-0.546875 -0.828125 -0.578125 -1.890625zm9.103729 3.375l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.8537292 4.3125l0 -10.484375l1.390625 0l0 9.25l5.15625 0l0 1.234375l-6.546875 0zm8.885468 3.078125l-0.921875 0q2.140625 -3.421875 2.140625 -6.875q0 -1.34375 -0.3125 -2.671875q-0.25 -1.0625 -0.671875 -2.046875q-0.28125 -0.65625 -1.15625 -2.15625l0.921875 0q1.34375 1.796875 1.984375 3.609375q0.546875 1.5625 0.546875 3.265625q0 1.921875 -0.734375 3.734375q-0.734375 1.796875 -1.796875 3.140625z" fill-rule="nonzero"/><path fill="#cfe2f3" d="m28.509478 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m28.509478 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m76.95251 104.10596l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0zm9.896774 -3.796875q0 -2.109375 1.171875 -3.125q0.984375 -0.84375 2.390625 -0.84375q1.578125 0 2.5625 1.03125q1.0 1.015625 1.0 2.828125q0 1.46875 -0.4375 2.3125q-0.4375 0.828125 -1.28125 1.296875q-0.84375 0.46875 -1.84375 0.46875q-1.59375 0 -2.578125 -1.015625q-0.984375 -1.03125 -0.984375 -2.953125zm1.328125 0q0 1.453125 0.625 2.1875q0.640625 0.71875 1.609375 0.71875q0.96875 0 1.59375 -0.71875q0.640625 -0.734375 0.640625 -2.234375q0 -1.40625 -0.640625 -2.125q-0.640625 -0.734375 -1.59375 -0.734375q-0.96875 0 -1.609375 0.71875q-0.625 0.71875 -0.625 2.1875zm6.791733 1.53125l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.65625 1.109375l0.1875 1.140625q-0.546875 0.109375 -0.984375 0.109375q-0.6875 0 -1.078125 -0.21875q-0.390625 -0.21875 -0.546875 -0.578125q-0.15625 -0.359375 -0.15625 -1.515625l0 -4.375l-0.953125 0l0 -1.0l0.953125 0l0 -1.890625l1.28125 -0.765625l0 2.65625l1.296875 0l0 1.0l-1.296875 0l0 4.4375q0 0.546875 0.0625 0.71875q0.078125 0.15625 0.21875 0.25q0.15625 0.078125 0.453125 0.078125q0.203125 0 0.5625 -0.046875zm12.972076 -2.515625l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.9123993 3.671875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.240532 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.6562576 0.25 -1.4218826 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625076 -0.1875 2.2968826 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.4531326 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.7187576 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.0937576 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.7343826 0 1.3125076 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm2.7917328 1.546875l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm7.328125 0l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.122101 2.265625l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.9006042 4.3125l0 -10.484375l3.96875 0q1.046875 0 1.59375 0.09375q0.765625 0.125 1.28125 0.484375q0.53125 0.359375 0.84375 1.015625q0.328125 0.65625 0.328125 1.4375q0 1.328125 -0.859375 2.265625q-0.84375 0.921875 -3.078125 0.921875l-2.6875 0l0 4.265625l-1.390625 0zm1.390625 -5.5l2.71875 0q1.34375 0 1.90625 -0.5q0.5625 -0.5 0.5625 -1.40625q0 -0.671875 -0.328125 -1.140625q-0.328125 -0.46875 -0.875 -0.609375q-0.359375 -0.09375 -1.296875 -0.09375l-2.6875 0l0 3.75zm8.619354 5.5l0 -10.484375l1.390625 0l0 10.484375l-1.390625 0z" fill-rule="nonzero"/><path fill="#000000" d="m113.3875 122.10595l0 -9.25l-3.453125 0l0 -1.234375l8.3125 0l0 1.234375l-3.46875 0l0 9.25l-1.390625 0zm13.171371 -10.484375l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.7405243 10.484375l0 -10.484375l1.390625 0l0 4.296875l5.453125 0l0 -4.296875l1.390625 0l0 10.484375l-1.390625 0l0 -4.9375l-5.453125 0l0 4.9375l-1.390625 0z" fill-rule="nonzero"/><path fill="#d9ead3" d="m220.78944 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m220.78944 83.71099l192.28346 0l0 48.62992l-192.28346 0z" fill-rule="evenodd"/><path fill="#000000" d="m261.85388 104.10596l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625zm14.24054 -1.21875l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm9.291718 4.53125l-2.890625 -7.59375l1.359375 0l1.625 4.546875q0.265625 0.734375 0.5 1.53125q0.15625 -0.609375 0.46875 -1.453125l1.6875 -4.625l1.328125 0l-2.875 7.59375l-1.203125 0zm5.21875 -9.015625l0 -1.46875l1.296875 0l0 1.46875l-1.296875 0zm0 9.015625l0 -7.59375l1.296875 0l0 7.59375l-1.296875 0zm8.20929 -2.78125l1.265625 0.15625q-0.203125 1.3125 -1.0625 2.0625q-0.84375 0.734375 -2.09375 0.734375q-1.5625 0 -2.515625 -1.015625q-0.9375 -1.03125 -0.9375 -2.921875q0 -1.234375 0.40625 -2.15625q0.40625 -0.921875 1.234375 -1.375q0.84375 -0.46875 1.8125 -0.46875q1.25 0 2.03125 0.625q0.78125 0.625 1.015625 1.765625l-1.265625 0.203125q-0.171875 -0.765625 -0.625 -1.15625q-0.453125 -0.390625 -1.09375 -0.390625q-0.984375 0 -1.59375 0.703125q-0.609375 0.703125 -0.609375 2.203125q0 1.53125 0.578125 2.234375q0.59375 0.6875 1.546875 0.6875q0.75 0 1.265625 -0.453125q0.515625 -0.46875 0.640625 -1.4375zm7.578125 0.328125l1.328125 0.171875q-0.3125 1.171875 -1.171875 1.8125q-0.84375 0.640625 -2.171875 0.640625q-1.671875 0 -2.65625 -1.015625q-0.96875 -1.03125 -0.96875 -2.890625q0 -1.921875 0.984375 -2.96875q1.0 -1.0625 2.578125 -1.0625q1.515625 0 2.484375 1.03125q0.96875 1.03125 0.96875 2.921875q0 0.109375 -0.015625 0.34375l-5.65625 0q0.0625 1.25 0.703125 1.921875q0.640625 0.65625 1.59375 0.65625q0.703125 0 1.203125 -0.359375q0.5 -0.375 0.796875 -1.203125zm-4.234375 -2.078125l4.25 0q-0.09375 -0.953125 -0.484375 -1.4375q-0.625 -0.75 -1.609375 -0.75q-0.875 0 -1.484375 0.59375q-0.609375 0.59375 -0.671875 1.59375zm18.894958 0.859375l1.390625 0.34375q-0.4375 1.703125 -1.578125 2.609375q-1.125 0.890625 -2.765625 0.890625q-1.6875 0 -2.75 -0.6875q-1.0625 -0.6875 -1.625 -2.0q-0.546875 -1.3125 -0.546875 -2.8125q0 -1.640625 0.625 -2.859375q0.625 -1.21875 1.78125 -1.84375q1.15625 -0.640625 2.546875 -0.640625q1.5625 0 2.640625 0.8125q1.078125 0.796875 1.5 2.25l-1.375 0.3125q-0.359375 -1.140625 -1.0625 -1.65625q-0.6875 -0.53125 -1.734375 -0.53125q-1.21875 0 -2.03125 0.578125q-0.8125 0.578125 -1.140625 1.5625q-0.328125 0.96875 -0.328125 2.015625q0 1.328125 0.390625 2.328125q0.390625 1.0 1.21875 1.5q0.828125 0.484375 1.78125 0.484375q1.171875 0 1.96875 -0.671875q0.8125 -0.671875 1.09375 -1.984375zm2.912384 3.671875l0 -10.484375l1.28125 0l0 10.484375l-1.28125 0zm8.24054 -0.9375q-0.71875 0.609375 -1.375 0.859375q-0.65625 0.25 -1.421875 0.25q-1.25 0 -1.921875 -0.609375q-0.671875 -0.609375 -0.671875 -1.5625q0 -0.5625 0.25 -1.015625q0.25 -0.46875 0.65625 -0.75q0.421875 -0.28125 0.9375 -0.421875q0.375 -0.09375 1.140625 -0.1875q1.5625 -0.1875 2.296875 -0.453125q0.015625 -0.265625 0.015625 -0.328125q0 -0.796875 -0.375 -1.109375q-0.484375 -0.4375 -1.453125 -0.4375q-0.921875 0 -1.359375 0.328125q-0.421875 0.3125 -0.625 1.109375l-1.265625 -0.171875q0.171875 -0.796875 0.5625 -1.296875q0.390625 -0.5 1.140625 -0.765625q0.75 -0.265625 1.71875 -0.265625q0.984375 0 1.59375 0.234375q0.609375 0.21875 0.890625 0.5625q0.28125 0.34375 0.40625 0.875q0.0625 0.328125 0.0625 1.1875l0 1.71875q0 1.796875 0.078125 2.28125q0.078125 0.46875 0.328125 0.90625l-1.34375 0q-0.203125 -0.40625 -0.265625 -0.9375zm-0.109375 -2.875q-0.703125 0.28125 -2.09375 0.484375q-0.796875 0.109375 -1.125 0.265625q-0.328125 0.140625 -0.515625 0.421875q-0.171875 0.265625 -0.171875 0.59375q0 0.515625 0.390625 0.859375q0.390625 0.34375 1.140625 0.34375q0.734375 0 1.3125 -0.3125q0.59375 -0.328125 0.859375 -0.890625q0.203125 -0.4375 0.203125 -1.296875l0 -0.46875zm2.7917175 1.546875l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm7.328125 0l1.265625 -0.203125q0.109375 0.765625 0.59375 1.171875q0.5 0.40625 1.375 0.40625q0.890625 0 1.3125 -0.359375q0.4375 -0.359375 0.4375 -0.84375q0 -0.4375 -0.375 -0.6875q-0.265625 -0.171875 -1.3125 -0.4375q-1.421875 -0.359375 -1.96875 -0.609375q-0.546875 -0.265625 -0.828125 -0.734375q-0.28125 -0.46875 -0.28125 -1.015625q0 -0.515625 0.21875 -0.9375q0.234375 -0.4375 0.640625 -0.734375q0.296875 -0.21875 0.8125 -0.359375q0.53125 -0.15625 1.125 -0.15625q0.890625 0 1.5625 0.265625q0.671875 0.25 1.0 0.6875q0.328125 0.4375 0.4375 1.171875l-1.25 0.171875q-0.09375 -0.578125 -0.5 -0.90625q-0.40625 -0.34375 -1.15625 -0.34375q-0.890625 0 -1.28125 0.296875q-0.375 0.296875 -0.375 0.6875q0 0.25 0.15625 0.453125q0.15625 0.203125 0.5 0.34375q0.1875 0.078125 1.140625 0.328125q1.359375 0.359375 1.890625 0.59375q0.546875 0.234375 0.859375 0.6875q0.3125 0.4375 0.3125 1.09375q0 0.640625 -0.375 1.21875q-0.375 0.5625 -1.09375 0.875q-0.703125 0.3125 -1.59375 0.3125q-1.484375 0 -2.265625 -0.609375q-0.765625 -0.625 -0.984375 -1.828125zm10.122101 2.265625l4.015625 -10.484375l1.5 0l4.296875 10.484375l-1.578125 0l-1.234375 -3.171875l-4.375 0l-1.15625 3.171875l-1.46875 0zm3.015625 -4.3125l3.5625 0l-1.09375 -2.90625q-0.5 -1.3125 -0.75 -2.171875q-0.203125 1.015625 -0.5625 2.0l-1.15625 3.078125zm7.9006042 4.3125l0 -10.484375l3.96875 0q1.046875 0 1.59375 0.09375q0.765625 0.125 1.28125 0.484375q0.53125 0.359375 0.84375 1.015625q0.328125 0.65625 0.328125 1.4375q0 1.328125 -0.859375 2.265625q-0.84375 0.921875 -3.078125 0.921875l-2.6875 0l0 4.265625l-1.390625 0zm1.390625 -5.5l2.71875 0q1.34375 0 1.90625 -0.5q0.5625 -0.5 0.5625 -1.40625q0 -0.671875 -0.328125 -1.140625q-0.328125 -0.46875 -0.875 -0.609375q-0.359375 -0.09375 -1.296875 -0.09375l-2.6875 0l0 3.75zm8.619354 5.5l0 -10.484375l1.390625 0l0 10.484375l-1.390625 0z" fill-rule="nonzero"/><path fill="#000000" d="m305.66745 122.10595l0 -9.25l-3.453125 0l0 -1.234375l8.3125 0l0 1.234375l-3.46875 0l0 9.25l-1.390625 0zm13.171387 -10.484375l1.390625 0l0 6.046875q0 1.59375 -0.359375 2.53125q-0.359375 0.921875 -1.296875 1.5q-0.9375 0.578125 -2.453125 0.578125q-1.46875 0 -2.40625 -0.5q-0.9375 -0.515625 -1.34375 -1.46875q-0.390625 -0.96875 -0.390625 -2.640625l0 -6.046875l1.390625 0l0 6.046875q0 1.375 0.25 2.015625q0.25 0.640625 0.859375 1.0q0.625 0.34375 1.53125 0.34375q1.53125 0 2.171875 -0.6875q0.65625 -0.703125 0.65625 -2.671875l0 -6.046875zm3.693634 10.484375l0 -10.484375l3.625 0q1.21875 0 1.859375 0.140625q0.90625 0.203125 1.546875 0.75q0.828125 0.703125 1.234375 1.796875q0.40625 1.09375 0.40625 2.5q0 1.1875 -0.28125 2.109375q-0.265625 0.921875 -0.703125 1.53125q-0.4375 0.609375 -0.96875 0.953125q-0.515625 0.34375 -1.25 0.53125q-0.71875 0.171875 -1.671875 0.171875l-3.796875 0zm1.390625 -1.234375l2.25 0q1.03125 0 1.625 -0.1875q0.59375 -0.203125 0.9375 -0.546875q0.5 -0.5 0.765625 -1.328125q0.28125 -0.84375 0.28125 -2.03125q0 -1.640625 -0.546875 -2.515625q-0.53125 -0.890625 -1.3125 -1.1875q-0.546875 -0.21875 -1.796875 -0.21875l-2.203125 0l0 8.015625z" fill-rule="nonzero"/><path fill="#000000" fill-opacity="0.0" d="m414.7422 230.80695l0 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m414.7422 230.80695l0 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m416.97958 84.35958l69.102356 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" stroke-dasharray="8.0,3.0" d="m416.97958 84.35958l69.102356 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m430.57208 84.35958l69.10239 0l0 37.5748l-69.10239 0z" fill-rule="evenodd"/><path fill="#000000" d="m441.68146 103.87958l0 -7.578125l-2.828125 0l0 -1.015625l6.8125 0l0 1.015625l-2.84375 0l0 7.578125l-1.140625 0zm4.5722656 -7.375l0 -1.21875l1.0625 0l0 1.21875l-1.0625 0zm0 7.375l0 -6.21875l1.0625 0l0 6.21875l-1.0625 0zm2.6660156 0l0 -6.21875l0.9375 0l0 0.875q0.6875 -1.015625 1.984375 -1.015625q0.5625 0 1.03125 0.203125q0.484375 0.203125 0.71875 0.53125q0.234375 0.328125 0.328125 0.765625q0.046875 0.296875 0.046875 1.03125l0 3.828125l-1.046875 0l0 -3.78125q0 -0.65625 -0.125 -0.96875q-0.125 -0.3125 -0.4375 -0.5q-0.3125 -0.203125 -0.734375 -0.203125q-0.671875 0 -1.171875 0.4375q-0.484375 0.421875 -0.484375 1.609375l0 3.40625l-1.046875 0zm6.626953 2.390625l-0.125 -0.984375q0.34375 0.09375 0.609375 0.09375q0.34375 0 0.546875 -0.125q0.21875 -0.109375 0.359375 -0.3125q0.09375 -0.171875 0.328125 -0.796875q0.015625 -0.078125 0.09375 -0.25l-2.375 -6.234375l1.140625 0l1.296875 3.59375q0.25 0.6875 0.453125 1.453125q0.1875 -0.734375 0.4375 -1.421875l1.328125 -3.625l1.046875 0l-2.359375 6.328125q-0.390625 1.015625 -0.59375 1.40625q-0.28125 0.53125 -0.65625 0.765625q-0.359375 0.25 -0.859375 0.25q-0.296875 0 -0.671875 -0.140625zm11.8125 -10.984375l1.140625 0l0 4.96875q0 1.296875 -0.296875 2.0625q-0.296875 0.75 -1.0625 1.234375q-0.765625 0.46875 -2.0 0.46875q-1.203125 0 -1.984375 -0.40625q-0.765625 -0.421875 -1.09375 -1.203125q-0.328125 -0.796875 -0.328125 -2.15625l0 -4.96875l1.140625 0l0 4.953125q0 1.125 0.203125 1.65625q0.21875 0.53125 0.71875 0.828125q0.515625 0.28125 1.25 0.28125q1.25 0 1.78125 -0.5625q0.53125 -0.578125 0.53125 -2.203125l0 -4.953125zm2.6503906 5.828125l1.0625 -0.09375q0.078125 0.65625 0.359375 1.0625q0.28125 0.40625 0.859375 0.671875q0.59375 0.25 1.328125 0.25q0.640625 0 1.140625 -0.1875q0.5 -0.203125 0.734375 -0.53125q0.25 -0.34375 0.25 -0.734375q0 -0.40625 -0.234375 -0.703125q-0.234375 -0.3125 -0.765625 -0.515625q-0.359375 -0.140625 -1.546875 -0.421875q-1.171875 -0.28125 -1.640625 -0.53125q-0.625 -0.328125 -0.921875 -0.796875q-0.296875 -0.484375 -0.296875 -1.078125q0 -0.640625 0.359375 -1.203125q0.375 -0.578125 1.078125 -0.859375q0.71875 -0.296875 1.578125 -0.296875q0.953125 0 1.6875 0.3125q0.734375 0.296875 1.125 0.90625q0.390625 0.59375 0.421875 1.34375l-1.09375 0.078125q-0.09375 -0.8125 -0.609375 -1.21875q-0.5 -0.421875 -1.484375 -0.421875q-1.03125 0 -1.5 0.375q-0.46875 0.375 -0.46875 0.90625q0 0.46875 0.328125 0.765625q0.328125 0.296875 1.703125 0.609375q1.390625 0.3125 1.90625 0.546875q0.75 0.359375 1.109375 0.890625q0.359375 0.515625 0.359375 1.21875q0 0.6875 -0.390625 1.296875q-0.390625 0.59375 -1.125 0.9375q-0.734375 0.328125 -1.65625 0.328125q-1.171875 0 -1.96875 -0.328125q-0.78125 -0.34375 -1.234375 -1.03125q-0.4375 -0.6875 -0.453125 -1.546875zm8.332031 2.765625l0 -8.59375l3.234375 0q0.984375 0 1.578125 0.265625q0.59375 0.265625 0.921875 0.8125q0.34375 0.53125 0.34375 1.125q0 0.546875 -0.296875 1.03125q-0.296875 0.484375 -0.90625 0.78125q0.78125 0.234375 1.1875 0.796875q0.421875 0.546875 0.421875 1.296875q0 0.59375 -0.25 1.125q-0.25 0.515625 -0.625 0.796875q-0.375 0.28125 -0.953125 0.421875q-0.5625 0.140625 -1.375 0.140625l-3.28125 0zm1.140625 -4.984375l1.859375 0q0.75 0 1.078125 -0.09375q0.4375 -0.125 0.65625 -0.421875q0.21875 -0.3125 0.21875 -0.765625q0 -0.421875 -0.203125 -0.75q-0.203125 -0.328125 -0.59375 -0.4375q-0.375 -0.125 -1.296875 -0.125l-1.71875 0l0 2.59375zm0 3.96875l2.140625 0q0.546875 0 0.765625 -0.046875q0.40625 -0.0625 0.65625 -0.21875q0.265625 -0.171875 0.4375 -0.484375q0.171875 -0.3125 0.171875 -0.71875q0 -0.484375 -0.25 -0.84375q-0.234375 -0.359375 -0.671875 -0.5q-0.4375 -0.140625 -1.265625 -0.140625l-1.984375 0l0 2.953125z" fill-rule="nonzero"/><path fill="#000000" fill-opacity="0.0" d="m416.97958 231.92447l69.102356 0" fill-rule="evenodd"/><path stroke="#000000" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" stroke-dasharray="8.0,3.0" d="m416.97958 231.92447l69.102356 0" fill-rule="evenodd"/><path fill="#000000" fill-opacity="0.0" d="m429.0601 231.92447l72.12598 0l0 37.5748l-72.12598 0z" fill-rule="evenodd"/><path fill="#000000" d="m437.9507 251.44447l0 -8.59375l1.71875 0l2.03125 6.078125q0.28125 0.859375 0.40625 1.28125q0.140625 -0.46875 0.453125 -1.375l2.0625 -5.984375l1.53125 0l0 8.59375l-1.09375 0l0 -7.1875l-2.5 7.1875l-1.03125 0l-2.484375 -7.3125l0 7.3125l-1.09375 0zm16.167969 -3.015625l1.125 0.296875q-0.359375 1.390625 -1.28125 2.125q-0.921875 0.734375 -2.265625 0.734375q-1.390625 0 -2.265625 -0.5625q-0.875 -0.5625 -1.328125 -1.625q-0.453125 -1.078125 -0.453125 -2.3125q0 -1.34375 0.515625 -2.34375q0.515625 -1.0 1.453125 -1.515625q0.953125 -0.515625 2.09375 -0.515625q1.28125 0 2.15625 0.65625q0.890625 0.65625 1.234375 1.84375l-1.125 0.265625q-0.296875 -0.9375 -0.875 -1.359375q-0.5625 -0.4375 -1.421875 -0.4375q-0.984375 0 -1.65625 0.484375q-0.65625 0.46875 -0.9375 1.265625q-0.265625 0.796875 -0.265625 1.65625q0 1.09375 0.3125 1.90625q0.328125 0.8125 1.0 1.21875q0.671875 0.40625 1.46875 0.40625q0.953125 0 1.609375 -0.546875q0.671875 -0.546875 0.90625 -1.640625zm8.166016 -5.578125l1.140625 0l0 4.96875q0 1.296875 -0.296875 2.0625q-0.296875 0.75 -1.0625 1.234375q-0.765625 0.46875 -2.0 0.46875q-1.203125 0 -1.984375 -0.40625q-0.765625 -0.421875 -1.09375 -1.203125q-0.328125 -0.796875 -0.328125 -2.15625l0 -4.96875l1.140625 0l0 4.953125q0 1.125 0.203125 1.65625q0.21875 0.53125 0.71875 0.828125q0.515625 0.28125 1.25 0.28125q1.25 0 1.78125 -0.5625q0.53125 -0.578125 0.53125 -2.203125l0 -4.953125zm6.359375 8.59375l0 -8.59375l3.25 0q0.84375 0 1.296875 0.078125q0.640625 0.109375 1.0625 0.40625q0.4375 0.296875 0.6875 0.828125q0.265625 0.53125 0.265625 1.171875q0 1.09375 -0.703125 1.859375q-0.6875 0.75 -2.515625 0.75l-2.203125 0l0 3.5l-1.140625 0zm1.140625 -4.5l2.21875 0q1.109375 0 1.5625 -0.40625q0.46875 -0.421875 0.46875 -1.171875q0 -0.53125 -0.28125 -0.90625q-0.265625 -0.390625 -0.703125 -0.515625q-0.296875 -0.078125 -1.0625 -0.078125l-2.203125 0l0 3.078125zm6.3476562 1.390625q0 -1.734375 0.953125 -2.5625q0.796875 -0.6875 1.953125 -0.6875q1.28125 0 2.09375 0.84375q0.828125 0.828125 0.828125 2.3125q0 1.203125 -0.359375 1.890625q-0.359375 0.6875 -1.0625 1.078125q-0.6875 0.375 -1.5 0.375q-1.296875 0 -2.109375 -0.828125q-0.796875 -0.84375 -0.796875 -2.421875zm1.078125 0q0 1.1875 0.515625 1.78125q0.53125 0.59375 1.3125 0.59375q0.796875 0 1.3125 -0.59375q0.515625 -0.59375 0.515625 -1.8125q0 -1.15625 -0.53125 -1.75q-0.515625 -0.59375 -1.296875 -0.59375q-0.78125 0 -1.3125 0.59375q-0.515625 0.578125 -0.515625 1.78125zm5.970703 3.109375l0 -6.21875l0.953125 0l0 0.9375q0.359375 -0.65625 0.65625 -0.859375q0.3125 -0.21875 0.6875 -0.21875q0.53125 0 1.078125 0.328125l-0.359375 0.984375q-0.390625 -0.234375 -0.765625 -0.234375q-0.359375 0 -0.640625 0.21875q-0.265625 0.203125 -0.375 0.578125q-0.1875 0.5625 -0.1875 1.21875l0 3.265625l-1.046875 0zm6.3085938 -0.9375l0.15625 0.921875q-0.453125 0.09375 -0.796875 0.09375q-0.578125 0 -0.890625 -0.171875q-0.3125 -0.1875 -0.453125 -0.484375q-0.125 -0.296875 -0.125 -1.25l0 -3.578125l-0.765625 0l0 -0.8125l0.765625 0l0 -1.546875l1.046875 -0.625l0 2.171875l1.0625 0l0 0.8125l-1.0625 0l0 3.640625q0 0.453125 0.046875 0.578125q0.0625 0.125 0.1875 0.203125q0.125 0.078125 0.359375 0.078125q0.1875 0 0.46875 -0.03125z" fill-rule="nonzero"/></g></svg>
diff --git a/docs/conf.py b/docs/conf.py
index 9e9784fb7..86ddcf672 100755
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -53,6 +53,25 @@ def preprocess_readme():
tgt = Path(__file__).parent.parent / "README_processed.rst"
if src.exists():
content = src.read_text(encoding='utf-8')
+ # if the matching is inside a table, keep the table cell width by adding the same number of spaces in the end of the line
+ # match pattern: | ... `... <docs/...>`_ ... |
+ # change into: | ... `... <...>`_ ... |
+ def _rewrite_table_line(line):
+ if not (line.startswith('|') and line.rstrip().endswith('|')):
+ return line
+
+ rewritten = re.sub(r"<docs/([^>]+)>", r"<\1>", line)
+ delta = len(line) - len(rewritten) - 1 # -1 for rst->html
+
+ if delta > 0:
+ last_pipe = rewritten.rfind('|')
+ if last_pipe >= 0:
+ rewritten = rewritten[:last_pipe] + (' ' * delta) + rewritten[last_pipe:]
+
+ return rewritten
+
+ content = ''.join(_rewrite_table_line(line) for line in content.splitlines(keepends=True))
+
content = re.sub(r"docs/", r"", content)
content = re.sub(r"\.rst\b", r".html", content)
if not content.endswith("\n"):
diff --git a/docs/reference/boards.rst b/docs/reference/boards.rst
index e61c4f98b..8a83496a4 100644
--- a/docs/reference/boards.rst
+++ b/docs/reference/boards.rst
@@ -266,6 +266,7 @@ STMicroelectronics
Board Name Family URL Note
=================== ================================= ========= ================================================================= ======
stm32c071nucleo STM32C071 Nucleo stm32c0 https://www.st.com/en/evaluation-tools/nucleo-c071rb.html
+stm32c542nucleo STM32C542 Nucleo stm32c5 https://www.st.com/en/evaluation-tools/nucleo-c542rc.html
stm32f070rbnucleo STM32 F070 Nucleo stm32f0 https://www.st.com/en/evaluation-tools/nucleo-f070rb.html
stm32f072disco STM32 F072 Discovery stm32f0 https://www.st.com/en/evaluation-tools/32f072bdiscovery.html
stm32f072eval STM32 F072 Eval stm32f0 https://www.st.com/en/evaluation-tools/stm32072b-eval.html
@@ -369,4 +370,5 @@ ch32v203g_r0_1v0 CH32V203G-R0-1v0 ch32v20x https://github.com/openwch/ch32v20
nanoch32v203 nanoCH32V203 ch32v20x https://github.com/wuxx/nanoCH32V203
ch32v307v_r1_1v0 CH32V307V-R1-1v0 ch32v30x https://github.com/openwch/ch32v307/tree/main/SCHPCB/CH32V307V-R1-1v0
nanoch32v305 nanoCH32V305 ch32v30x https://github.com/wuxx/nanoCH32V305
+yd-ch582m yd-ch582m ch583 http://vcc-gnd.com
================ ================ ======== ===================================================================== ======
diff --git a/docs/reference/class_drivers.rst b/docs/reference/class_drivers.rst
new file mode 100644
index 000000000..4a101fabc
--- /dev/null
+++ b/docs/reference/class_drivers.rst
@@ -0,0 +1,316 @@
+***************
+Class Drivers
+***************
+
+USB Class Drivers implement specific USB device classes (CDC, HID, MSC, MIDI, Audio, etc.) and are the main interface between the USB core and application code.
+
+MIDI 2.0 Device Driver
+=======================
+
+Overview
+--------
+
+The MIDI 2.0 Device driver enables TinyUSB to act as a USB MIDI 2.0 device. It implements both Alt Setting 0 (MIDI 1.0 fallback) and Alt Setting 1 (native UMP) as required by the USB-MIDI 2.0 specification.
+
+**Key Features:**
+
+- **Dual Alt Settings**: Alt 0 (MIDI 1.0) and Alt 1 (UMP native) per USB-MIDI 2.0 spec
+- **Protocol Negotiation**: Endpoint Discovery, Config Request/Notify, Function Block Discovery
+- **Group Terminal Block**: Served via GET_DESCRIPTOR automatically
+- **Atomic UMP Framing**: Read/write with correct message boundaries
+- **Memory Safe**: No dynamic allocation, static instances
+
+Configuration
+-------------
+
+Enable MIDI 2.0 Device support in ``tusb_config.h``:
+
+.. code-block:: c
+
+ #define CFG_TUD_ENABLED 1
+ #define CFG_TUD_MIDI2 1
+
+Optional configuration:
+
+.. code-block:: c
+
+ #define CFG_TUD_MIDI2_TX_BUFSIZE 256
+ #define CFG_TUD_MIDI2_RX_BUFSIZE 256
+ #define CFG_TUD_MIDI2_TX_EPSIZE 64
+ #define CFG_TUD_MIDI2_RX_EPSIZE 64
+ #define CFG_TUD_MIDI2_NUM_GROUPS 1 // 1..16
+ #define CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS 1 // 1..32
+ #define CFG_TUD_MIDI2_EP_NAME "TinyUSB MIDI 2.0"
+ #define CFG_TUD_MIDI2_PRODUCT_ID "TinyUSB-MIDI2"
+
+Public API
+----------
+
+Query Functions
+^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ bool tud_midi2_mounted(void);
+ uint32_t tud_midi2_available(void);
+ uint8_t tud_midi2_alt_setting(void);
+ bool tud_midi2_negotiated(void);
+ uint8_t tud_midi2_protocol(void);
+
+I/O Functions
+^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ uint32_t tud_midi2_ump_read(uint32_t* words, uint32_t max_words);
+ uint32_t tud_midi2_ump_write(const uint32_t* words, uint32_t count);
+ uint32_t tud_midi2_packet_read(uint8_t packets[], uint32_t max_packets);
+ uint32_t tud_midi2_packet_write(const uint8_t packets[], uint32_t count);
+
+Callbacks
+^^^^^^^^^
+
+.. code-block:: c
+
+ void tud_midi2_rx_cb(uint8_t itf);
+ void tud_midi2_set_itf_cb(uint8_t itf, uint8_t alt);
+ bool tud_midi2_get_req_itf_cb(uint8_t rhport, const tusb_control_request_t* request);
+
+MIDI 2.0 Host Driver
+=====================
+
+Overview
+--------
+
+The MIDI 2.0 Host driver enables TinyUSB to enumerate and communicate with USB MIDI 2.0 devices. It implements the USB MIDI 2.0 specification, supporting both MIDI 1.0 legacy devices and modern MIDI 2.0 devices with UMP (Universal MIDI Packet) protocol.
+
+**Key Features:**
+
+- **Reactive Architecture**: Auto-detects Alt Setting 1 (MIDI 2.0) capability during enumeration
+- **Auto-Selection**: Automatically selects the highest available protocol and issues SET_INTERFACE to activate Alt Setting 1 when MIDI 2.0 is detected
+- **Transparent Stream Messages**: All data (UMP packets + Stream Messages) flow through callbacks
+- **Memory Safe**: No dynamic allocation, fixed-size instances per device
+
+Configuration
+-------------
+
+Enable MIDI 2.0 Host support in ``tusb_config.h``:
+
+.. code-block:: c
+
+ #define CFG_TUH_ENABLED 1
+ #define CFG_TUH_MIDI2 4 // Number of MIDI 2.0 devices to support
+
+Optional buffer configuration:
+
+.. code-block:: c
+
+ #define CFG_TUH_MIDI2_RX_BUFSIZE (4 * TUH_EPSIZE_BULK_MAX)
+ #define CFG_TUH_MIDI2_TX_BUFSIZE (4 * TUH_EPSIZE_BULK_MAX)
+
+Enumeration Lifecycle
+---------------------
+
+When a MIDI 2.0 device is connected, the host stack invokes callbacks in this order:
+
+.. code-block:: none
+
+ Device Connected
+ |
+ [Host detects Alt 0 and Alt 1 descriptors]
+ |
+ tuh_midi2_descriptor_cb() <- Device detected, NOT yet ready
+ |
+ [Auto-select highest protocol]
+ |
+ tuh_midi2_mount_cb() <- Device ready to use
+ |
+ [Application can read/write data]
+ |
+ tuh_midi2_rx_cb() <- Data arrived
+ tuh_midi2_tx_cb() <- TX buffer space available
+ |
+ [Device disconnects]
+ |
+ tuh_midi2_umount_cb() <- Device removed
+
+Public API
+----------
+
+Query Functions
+^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ bool tuh_midi2_mounted(uint8_t idx);
+ uint8_t tuh_midi2_get_protocol_version(uint8_t idx); // 0=MIDI 1.0, 1=MIDI 2.0
+ uint8_t tuh_midi2_get_alt_setting_active(uint8_t idx); // 0 or 1
+ uint8_t tuh_midi2_get_cable_count(uint8_t idx);
+
+I/O Functions
+^^^^^^^^^^^^^
+
+Read and write UMP (Universal MIDI Packet) data:
+
+.. code-block:: c
+
+ uint32_t tuh_midi2_ump_read(uint8_t idx, uint32_t* words, uint32_t max_words);
+ uint32_t tuh_midi2_ump_write(uint8_t idx, const uint32_t* words, uint32_t count);
+ uint32_t tuh_midi2_write_flush(uint8_t idx);
+
+Callbacks
+---------
+
+Application can define weak callback implementations to respond to device events.
+
+Descriptor Callback
+^^^^^^^^^^^^^^^^^^^
+
+Invoked when device is detected but not yet ready for I/O:
+
+.. code-block:: c
+
+ void tuh_midi2_descriptor_cb(uint8_t idx, const tuh_midi2_descriptor_cb_t *desc_cb_data) {
+ printf("MIDI %s device detected\r\n",
+ desc_cb_data->protocol_version == 0 ? "1.0" : "2.0");
+ }
+
+Mount Callback
+^^^^^^^^^^^^^^
+
+Invoked when device is ready for I/O:
+
+.. code-block:: c
+
+ void tuh_midi2_mount_cb(uint8_t idx, const tuh_midi2_mount_cb_t *mount_cb_data) {
+ printf("Device mounted at idx=%u, protocol=%u, alt_setting=%u\r\n",
+ idx, mount_cb_data->protocol_version, mount_cb_data->alt_setting_active);
+ }
+
+RX Callback
+^^^^^^^^^^^
+
+Invoked when data arrives from device (both UMP packets and Stream Messages):
+
+.. code-block:: c
+
+ void tuh_midi2_rx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ uint32_t words[4];
+ uint32_t n = tuh_midi2_ump_read(idx, words, 4);
+
+ for (uint32_t i = 0; i < n; i++) {
+ uint8_t mt = (words[i] >> 28) & 0x0F;
+ if (mt == 0x0F) {
+ // Stream Message - app handles discovery, negotiation, etc.
+ } else {
+ // Regular MIDI UMP packet
+ }
+ }
+ }
+
+TX Callback
+^^^^^^^^^^^
+
+Invoked when TX buffer space becomes available:
+
+.. code-block:: c
+
+ void tuh_midi2_tx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ // Buffer space available for writing
+ }
+
+Unmount Callback
+^^^^^^^^^^^^^^^^
+
+Invoked when device is disconnected:
+
+.. code-block:: c
+
+ void tuh_midi2_umount_cb(uint8_t idx) {
+ printf("Device at idx=%u disconnected\r\n", idx);
+ }
+
+Complete Example
+----------------
+
+.. code-block:: c
+
+ #include "tusb.h"
+
+ void tuh_midi2_mount_cb(uint8_t idx, const tuh_midi2_mount_cb_t *mount_cb_data) {
+ printf("MIDI 2.0 device mounted\r\n");
+ }
+
+ void tuh_midi2_rx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ uint32_t words[4];
+ uint32_t n = tuh_midi2_ump_read(idx, words, 4);
+
+ for (uint32_t i = 0; i < n; i++) {
+ printf("RX: 0x%08lx\r\n", words[i]);
+ }
+ }
+
+ void tuh_midi2_umount_cb(uint8_t idx) {
+ printf("MIDI 2.0 device disconnected\r\n");
+ }
+
+ int main(void) {
+ board_init();
+
+ tusb_rhport_init_t host_init = {.role = TUSB_ROLE_HOST, .speed = TUSB_SPEED_AUTO};
+ tusb_init(BOARD_TUH_RHPORT, &host_init);
+
+ while (1) {
+ tuh_task();
+ }
+ }
+
+Architecture
+------------
+
+The MIDI 2.0 Host driver uses a **reactive, callback-driven architecture** that mirrors the proven patterns in TinyUSB's existing device drivers (CDC, HID, etc.):
+
+- **Auto-Detection**: Host automatically detects Alt Setting 1 capability
+- **Auto-Selection**: Selects highest protocol available and issues SET_INTERFACE
+- **Transparent I/O**: Stream Messages and UMP packets flow through callbacks
+- **Callback-Driven**: App receives events via callbacks (descriptor, mount, rx, tx, unmount)
+
+Differences from MIDI 1.0 Host
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. list-table::
+ :header-rows: 1
+
+ * - Aspect
+ - MIDI 1.0 Host
+ - MIDI 2.0 Host
+ * - Alt Settings
+ - Parses only Alt 0
+ - Parses Alt 0 + Alt 1
+ * - Data Format
+ - 4-byte MIDI packets
+ - UMP (32/64/128-bit)
+ * - Version Detection
+ - None
+ - bcdMSC from descriptor
+ * - GTB
+ - N/A
+ - Presence detection
+ * - Stream Messages
+ - N/A
+ - Transparent passthrough
+ * - Callbacks
+ - descriptor_cb, mount_cb, rx_cb, umount_cb
+ - descriptor_cb, mount_cb, rx_cb, tx_cb, umount_cb
+ * - Public API
+ - tuh_midi_*
+ - tuh_midi2_*
+
+Implementation Notes
+--------------------
+
+- All internal state is statically allocated (no dynamic allocation)
+- Endpoint streams use TinyUSB's tu_edpt_stream_t for buffered I/O
+- Protocol version detection via bcdMSC field
+- Alt Setting is automatically selected during mount
+- Compatible with all TinyUSB-supported MCU families
diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst
index c5b755577..d281e912a 100644
--- a/docs/reference/dependencies.rst
+++ b/docs/reference/dependencies.rst
@@ -59,6 +59,7 @@ hw/mcu/st/cmsis_device_l5 https://github.com/STMicroelectronics/
hw/mcu/st/cmsis_device_n6 https://github.com/STMicroelectronics/cmsis-device-n6.git 7bcdc944fbf7cf5928d3c1d14054ca13261d33ec stm32n6
hw/mcu/st/cmsis_device_u5 https://github.com/STMicroelectronics/cmsis_device_u5.git 6e67187dec98035893692ab2923914cb5f4e0117 stm32u5
hw/mcu/st/cmsis_device_wb https://github.com/STMicroelectronics/cmsis_device_wb.git cda2cb9fc4a5232ab18efece0bb06b0b60910083 stm32wb
+hw/mcu/st/stm32c5xx-dfp https://github.com/STMicroelectronics/stm32c5xx-dfp.git 6d0940882511d9430f83af9bd3da6bcb77f79239 stm32c5
hw/mcu/st/stm32-mfxstm32l152 https://github.com/STMicroelectronics/stm32-mfxstm32l152.git 7f4389efee9c6a655b55e5df3fceef5586b35f9b stm32h7
hw/mcu/st/stm32-tcpp0203 https://github.com/STMicroelectronics/stm32-tcpp0203.git 9918655bff176ac3046ccf378b5c7bbbc6a38d15 stm32h5 stm32h7rs stm32n6
hw/mcu/st/stm32c0xx_hal_driver https://github.com/STMicroelectronics/stm32c0xx_hal_driver.git c283b143bef6bdaacf64240ee6f15eb61dad6125 stm32c0
@@ -82,13 +83,14 @@ hw/mcu/st/stm32u0xx_hal_driver https://github.com/STMicroelectronics/
hw/mcu/st/stm32u5xx_hal_driver https://github.com/STMicroelectronics/stm32u5xx_hal_driver.git 2c5e2568fbdb1900a13ca3b2901fdd302cac3444 stm32u5
hw/mcu/st/stm32wbaxx_hal_driver https://github.com/STMicroelectronics/stm32wbaxx_hal_driver.git 9442fbb71f855ff2e64fbf662b7726beba511a24 stm32wba
hw/mcu/st/stm32wbxx_hal_driver https://github.com/STMicroelectronics/stm32wbxx_hal_driver.git d60dd46996876506f1d2e9abd6b1cc110c8004cd stm32wb
+hw/mcu/st/stm32c5xx-drivers https://github.com/STMicroelectronics/stm32c5xx-drivers.git 79b901285a7efeaf87c4c25db81d24cb5d8c9465 stm32c5
hw/mcu/ti https://github.com/hathach/ti_driver.git 083944907e7d08fcb1f614b47598ce45935b8da1 msp430 msp432e4 tm4c
hw/mcu/wch/ch32f20x https://github.com/openwch/ch32f20x.git 77c4095087e5ed2c548ec9058e655d0b8757663b ch32f20x
hw/mcu/wch/ch32v103 https://github.com/openwch/ch32v103.git 7578cae0b21f86dd053a1f781b2fc6ab99d0ec17 ch32v10x
hw/mcu/wch/ch32v20x https://github.com/openwch/ch32v20x.git c4c38f507e258a4e69b059ccc2dc27dde33cea1b ch32v20x
hw/mcu/wch/ch32v307 https://github.com/openwch/ch32v307.git 184f21b852cb95eed58e86e901837bc9fff68775 ch32v30x
lib/CMSIS_5 https://github.com/ARM-software/CMSIS_5.git 2b7495b8535bdcb306dac29b9ded4cfb679d7e5c kinetis_k kinetis_kl lpc54 rw61x mm32 msp432e4 nrf samd2x_l2x lpc11 lpc13 lpc15 lpc17 lpc18 lpc40 lpc43 stm32c0 stm32f0 stm32f1 stm32f2 stm32f3 stm32f4 stm32f7 stm32g0 stm32g4 stm32h5 stm32h7 stm32h7rs stm32l0 stm32l1 stm32l4 stm32l5 stm32u0 stm32u5 stm32wb stm32wba sam3x samd11 samd21 samd51 samd5x_e5x same5x same7x samg tm4c
-lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git 6f0a58d01aa9bd2feba212097f9afe7acd991d52 imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx
+lib/CMSIS_6 https://github.com/ARM-software/CMSIS_6.git 6f0a58d01aa9bd2feba212097f9afe7acd991d52 imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx stm32c5
lib/FreeRTOS-Kernel https://github.com/FreeRTOS/FreeRTOS-Kernel.git cc0e0707c0c748713485b870bb980852b210877f all
lib/lwip https://github.com/lwip-tcpip/lwip.git 159e31b689577dbf69cf0683bbaffbd71fa5ee10 all
lib/sct_neopixel https://github.com/gsteiert/sct_neopixel.git e73e04ca63495672d955f9268e003cffe168fcd8 lpc55
diff --git a/docs/reference/device_issues.rst b/docs/reference/device_issues.rst
new file mode 100644
index 000000000..ae9cd55f1
--- /dev/null
+++ b/docs/reference/device_issues.rst
@@ -0,0 +1,35 @@
+Device specific known issues and workarounds
+===============================================
+This page lists known issues and workarounds for specific devices.
+
+NXP LPC54600
+----------------
+**Severity: High**
+
+**Not recommended for USB device applications (except high-speed host controller)**
+
+Reference: `LPC54600 Errata Sheet`_
+
+.. _LPC54600 Errata Sheet: https://www.nxp.com/docs/en/errata/ES_LPC546XX.pdf
+
+The LPC54600 series have a very buggy USB controller, with 17 issues listed in the errata which is more than half of the total issues.
+
+Most severe issues are:
+
+- USB.2: In USB high-speed device mode, the NBytes field is not correct after BULK IN transfer
+- USB.5: In USB full-speed host mode, linked list on done queue is broken.
+- USB.15: USB high-speed device in endpoint TX data corruption
+
+WCH CH32F20x/CH32V20x/CH32V30x
+---------------------------------
+**Severity: Medium**
+
+**Not recommended for USB audio applications**
+
+Reference: `CH32V30X Reference Manual`_ USBFS/USBHS controller chapter
+
+.. _CH32V30X Reference Manual: https://www.wch-ic.com/downloads/CH32FV2x_V3xRM_PDF.html
+
+Data corruption may occur on isochronous endpoints. Due to the lacking of FIFO for interrupt status registers, later completed transfer will overwrite `INT_ST` and `RX_LEN` register if previous transfer processing is not completed.
+
+Other types of transfers are not affected.
diff --git a/docs/reference/index.rst b/docs/reference/index.rst
index d3c96eeee..c66ce618f 100644
--- a/docs/reference/index.rst
+++ b/docs/reference/index.rst
@@ -9,7 +9,9 @@ Complete reference documentation for TinyUSB APIs, configuration, and supported
architecture
usb_concepts
+ class_drivers
boards
dependencies
concurrency
+ device_issues
glossary
diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst
index bb9f15166..613c7fcef 100644
--- a/docs/troubleshooting.rst
+++ b/docs/troubleshooting.rst
@@ -76,6 +76,8 @@ Invalid board name in build command.
Runtime Issues
==============
+Check :doc:`reference/device_issues` for known hardware-specific issues that may affect USB functionality on your device.
+
Device Mode Problems
--------------------
diff --git a/examples/device/CMakeLists.txt b/examples/device/CMakeLists.txt
index 7173f455e..1432b36bb 100644
--- a/examples/device/CMakeLists.txt
+++ b/examples/device/CMakeLists.txt
@@ -16,6 +16,7 @@ set(EXAMPLE_LIST
cdc_dual_ports
cdc_msc
cdc_msc_freertos
+ cdc_msc_throughput
cdc_uac2
dfu
dfu_runtime
@@ -27,6 +28,7 @@ set(EXAMPLE_LIST
hid_multiple_interface
midi_test
midi_test_freertos
+ midi2_device
msc_dual_lun
mtp
net_lwip_webserver
diff --git a/examples/device/audio_4_channel_mic/skip.txt b/examples/device/audio_4_channel_mic/skip.txt
index 157605df1..3ca433c08 100644
--- a/examples/device/audio_4_channel_mic/skip.txt
+++ b/examples/device/audio_4_channel_mic/skip.txt
@@ -3,3 +3,4 @@ mcu:SAME5X
mcu:SAMG
family:broadcom_64bit
family:espressif
+mcu:CH583
diff --git a/examples/device/audio_4_channel_mic/src/plot_audio_samples.py b/examples/device/audio_4_channel_mic/src/plot_audio_samples.py
index 4d61e7f5e..618745934 100755
--- a/examples/device/audio_4_channel_mic/src/plot_audio_samples.py
+++ b/examples/device/audio_4_channel_mic/src/plot_audio_samples.py
@@ -4,6 +4,51 @@ import matplotlib.pyplot as plt
import numpy as np
import platform
+
+def find_windows_input_device(name_hint, channels, preferred_apis=None):
+ """Pick a Windows input device index from query_devices() output."""
+ preferred_apis = preferred_apis or []
+ name_hint = name_hint.lower()
+ candidates = []
+
+ for index in range(len(sd.query_devices())):
+ device_info = sd.query_devices(index)
+ max_input_channels = int(device_info.get('max_input_channels', 0))
+
+ if max_input_channels < channels:
+ continue
+
+ device_name = str(device_info.get('name', '')).lower()
+ if name_hint not in device_name:
+ continue
+
+ score = 0
+
+ # Prefer exact channel matches to avoid selecting a different stream layout.
+ if max_input_channels == channels:
+ score += 100
+ else:
+ score += 10
+
+ hostapi_index = int(device_info.get('hostapi', -1))
+ api_name = ''
+ if hostapi_index >= 0:
+ api_name = str(sd.query_hostapis(hostapi_index)).lower()
+
+ for priority, api_hint in enumerate(preferred_apis):
+ if api_hint in api_name:
+ score += 50 - priority
+ break
+
+ candidates.append((score, index))
+
+ if not candidates:
+ raise ValueError(
+ 'No input device matching hint="{}" with at least {} channels'.format(name_hint, channels)
+ )
+
+ return max(candidates, key=lambda item: item[0])[1]
+
if __name__ == '__main__':
# If you got "ValueError: No input device matching", that is because your PC name example device
@@ -14,8 +59,8 @@ if __name__ == '__main__':
duration = 1 # Duration of recording
if platform.system() == 'Windows':
- # WDM-KS is needed since there are more than one MicNode device APIs (at least in Windows)
- device = 'Microphone (MicNode_4_Ch), Windows WASAPI'
+ # Match by substring to support names like "Microphone (2- MicNode_4_Ch)".
+ device = find_windows_input_device('micnode_4_ch', channels=4, preferred_apis=['wasapi', 'wdm-ks', 'mme'])
elif platform.system() == 'Darwin':
device = 'MicNode_4_Ch'
else:
diff --git a/examples/device/audio_4_channel_mic/src/usb_descriptors.c b/examples/device/audio_4_channel_mic/src/usb_descriptors.c
index 00337eee7..6b9a9bbae 100644
--- a/examples/device/audio_4_channel_mic/src/usb_descriptors.c
+++ b/examples/device/audio_4_channel_mic/src/usb_descriptors.c
@@ -91,6 +91,14 @@ enum
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
+#elif TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+
+#elif TU_CHECK_MCU(OPT_MCU_CH32V20X, OPT_MCU_CH32V307)
+ // Only EP3 is available for ISO
+ #define EPNUM_AUDIO 0x03
+
#else
#define EPNUM_AUDIO 0x01
#endif
diff --git a/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt b/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt
index d43a72e58..66ef19fbc 100644
--- a/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt
+++ b/examples/device/audio_4_channel_mic_freertos/CMakeLists.txt
@@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+# Need to set Espressif defaults before project() is called
+if(FAMILY STREQUAL "espressif")
+ list(APPEND SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
+endif()
+
project(audio_4_channel_mic_freertos C CXX ASM)
# Checks this example is valid for the family and initializes the project
diff --git a/examples/device/audio_4_channel_mic_freertos/skip.txt b/examples/device/audio_4_channel_mic_freertos/skip.txt
index 61a7b0605..1fd6b4b8a 100644
--- a/examples/device/audio_4_channel_mic_freertos/skip.txt
+++ b/examples/device/audio_4_channel_mic_freertos/skip.txt
@@ -2,6 +2,7 @@ mcu:CH32F20X
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:CXD56
mcu:F1C100S
mcu:GD32VF103
diff --git a/examples/device/audio_4_channel_mic_freertos/src/plot_audio_samples.py b/examples/device/audio_4_channel_mic_freertos/src/plot_audio_samples.py
index 4d5ca28d6..3b3cd0d83 100755
--- a/examples/device/audio_4_channel_mic_freertos/src/plot_audio_samples.py
+++ b/examples/device/audio_4_channel_mic_freertos/src/plot_audio_samples.py
@@ -4,6 +4,52 @@ import matplotlib.pyplot as plt
import numpy as np
import platform
+
+def find_windows_input_device(name_hint, channels, preferred_apis=None):
+ """Pick a Windows input device index from query_devices() output."""
+ preferred_apis = preferred_apis or []
+ name_hint = name_hint.lower()
+ candidates = []
+
+ for index in range(len(sd.query_devices())):
+ device_info = sd.query_devices(index)
+ max_input_channels = int(device_info.get('max_input_channels', 0))
+
+ if max_input_channels < channels:
+ continue
+
+ device_name = str(device_info.get('name', '')).lower()
+ if name_hint not in device_name:
+ continue
+
+ score = 0
+
+ # Prefer exact channel matches to avoid selecting a different stream layout.
+ if max_input_channels == channels:
+ score += 100
+ else:
+ score += 10
+
+ hostapi_index = int(device_info.get('hostapi', -1))
+ api_name = ''
+ if hostapi_index >= 0:
+ hostapi_info = sd.query_hostapis(hostapi_index)
+ api_name = str(hostapi_info.get('name', '')).lower()
+
+ for priority, api_hint in enumerate(preferred_apis):
+ if api_hint in api_name:
+ score += 50 - priority
+ break
+
+ candidates.append((score, index))
+
+ if not candidates:
+ raise ValueError(
+ 'No input device matching hint="{}" with at least {} channels'.format(name_hint, channels)
+ )
+
+ return max(candidates, key=lambda item: item[0])[1]
+
if __name__ == '__main__':
# If you got "ValueError: No input device matching", that is because your PC name example device
@@ -14,8 +60,8 @@ if __name__ == '__main__':
duration = 100e-3 # Duration of recording
if platform.system() == 'Windows':
- # WDM-KS is needed since there are more than one MicNode device APIs (at least in Windows)
- device = 'Microphone (MicNode_4_Ch), Windows WDM-KS'
+ # Match by substring to support names like "Microphone (2- MicNode_4_Ch)".
+ device = find_windows_input_device('micnode_4_ch', channels=4, preferred_apis=['wdm-ks', 'wasapi', 'mme'])
elif platform.system() == 'Darwin':
device = 'MicNode_4_Ch'
else:
diff --git a/examples/device/audio_4_channel_mic_freertos/src/usb_descriptors.c b/examples/device/audio_4_channel_mic_freertos/src/usb_descriptors.c
index 3bb93f67d..216cd062a 100644
--- a/examples/device/audio_4_channel_mic_freertos/src/usb_descriptors.c
+++ b/examples/device/audio_4_channel_mic_freertos/src/usb_descriptors.c
@@ -91,6 +91,10 @@ enum
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
+#elif TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+
#else
#define EPNUM_AUDIO 0x01
#endif
diff --git a/examples/device/audio_test/skip.txt b/examples/device/audio_test/skip.txt
index 65b137814..42394bb11 100644
--- a/examples/device/audio_test/skip.txt
+++ b/examples/device/audio_test/skip.txt
@@ -2,3 +2,4 @@ mcu:SAMD11
mcu:SAME5X
mcu:SAMG
family:espressif
+mcu:CH583
diff --git a/examples/device/audio_test/src/plot_audio_samples.py b/examples/device/audio_test/src/plot_audio_samples.py
index 2be8948ea..af01b7b3e 100755
--- a/examples/device/audio_test/src/plot_audio_samples.py
+++ b/examples/device/audio_test/src/plot_audio_samples.py
@@ -5,6 +5,52 @@ import numpy as np
import platform
import csv
+
+def find_windows_input_device(name_hint, channels, preferred_apis=None):
+ """Pick a Windows input device index from query_devices() output."""
+ preferred_apis = preferred_apis or []
+ name_hint = name_hint.lower()
+ candidates = []
+
+ for index in range(len(sd.query_devices())):
+ device_info = sd.query_devices(index)
+ max_input_channels = int(device_info.get('max_input_channels', 0))
+
+ if max_input_channels < channels:
+ continue
+
+ device_name = str(device_info.get('name', '')).lower()
+ if name_hint not in device_name:
+ continue
+
+ score = 0
+
+ # Prefer exact channel matches (for example 1ch source over a 4ch source).
+ if max_input_channels == channels:
+ score += 100
+ else:
+ score += 10
+
+ hostapi_index = int(device_info.get('hostapi', -1))
+ api_name = ''
+ if hostapi_index >= 0:
+ hostapi_info = sd.query_hostapis(hostapi_index)
+ api_name = str(hostapi_info.get('name', '')).lower()
+
+ for priority, api_hint in enumerate(preferred_apis):
+ if api_hint in api_name:
+ score += 50 - priority
+ break
+
+ candidates.append((score, index))
+
+ if not candidates:
+ raise ValueError(
+ 'No input device matching hint="{}" with at least {} channels'.format(name_hint, channels)
+ )
+
+ return max(candidates, key=lambda item: item[0])[1]
+
if __name__ == '__main__':
# If you got "ValueError: No input device matching", that is because your PC name example device
@@ -15,8 +61,8 @@ if __name__ == '__main__':
duration = 3 # Duration of recording
if platform.system() == 'Windows':
- # MME is needed since there are more than one MicNode device APIs (at least in Windows)
- device = 'Microphone (MicNode), Windows WASAPI'
+ # Match by substring to support names like "Microphone (2- MicNode)".
+ device = find_windows_input_device('micnode', channels=1, preferred_apis=['wasapi', 'mme', 'wdm-ks'])
elif platform.system() == 'Darwin':
device = 'MicNode'
else:
diff --git a/examples/device/audio_test/src/usb_descriptors.c b/examples/device/audio_test/src/usb_descriptors.c
index ad161939e..cea4eb8d1 100644
--- a/examples/device/audio_test/src/usb_descriptors.c
+++ b/examples/device/audio_test/src/usb_descriptors.c
@@ -91,6 +91,14 @@ enum
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
+#elif TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+
+#elif TU_CHECK_MCU(OPT_MCU_CH32V20X, OPT_MCU_CH32V307)
+ // Only EP3 is available for ISO
+ #define EPNUM_AUDIO 0x03
+
#else
#define EPNUM_AUDIO 0x01
#endif
diff --git a/examples/device/audio_test_freertos/CMakeLists.txt b/examples/device/audio_test_freertos/CMakeLists.txt
index 71d65eccc..a39e56822 100644
--- a/examples/device/audio_test_freertos/CMakeLists.txt
+++ b/examples/device/audio_test_freertos/CMakeLists.txt
@@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+# Need to set Espressif defaults before project() is called
+if(FAMILY STREQUAL "espressif")
+ list(APPEND SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
+endif()
+
project(audio_test_freertos C CXX ASM)
# Checks this example is valid for the family and initializes the project
diff --git a/examples/device/audio_test_freertos/sdkconfig.defaults b/examples/device/audio_test_freertos/sdkconfig.defaults
index 83871619e..6e7a1cf52 100644
--- a/examples/device/audio_test_freertos/sdkconfig.defaults
+++ b/examples/device/audio_test_freertos/sdkconfig.defaults
@@ -1,3 +1,6 @@
CONFIG_IDF_CMAKE=y
+# 1000 Hz tick: the UAC iso IN endpoint must be serviced every 1 ms frame;
+# ESP-IDF's default 100 Hz starves the audio task -> host capture fails (arecord EIO).
+CONFIG_FREERTOS_HZ=1000
CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK=y
CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
diff --git a/examples/device/audio_test_freertos/skip.txt b/examples/device/audio_test_freertos/skip.txt
index 386a0cdfb..660bacd25 100644
--- a/examples/device/audio_test_freertos/skip.txt
+++ b/examples/device/audio_test_freertos/skip.txt
@@ -2,6 +2,7 @@ mcu:CH32F20X
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:CXD56
mcu:F1C100S
mcu:GD32VF103
diff --git a/examples/device/audio_test_freertos/src/plot_audio_samples.py b/examples/device/audio_test_freertos/src/plot_audio_samples.py
index b6d8e824b..b6a916be4 100755
--- a/examples/device/audio_test_freertos/src/plot_audio_samples.py
+++ b/examples/device/audio_test_freertos/src/plot_audio_samples.py
@@ -4,6 +4,52 @@ import matplotlib.pyplot as plt
import numpy as np
import platform
+
+def find_windows_input_device(name_hint, channels, preferred_apis=None):
+ """Pick a Windows input device index from query_devices() output."""
+ preferred_apis = preferred_apis or []
+ name_hint = name_hint.lower()
+ candidates = []
+
+ for index in range(len(sd.query_devices())):
+ device_info = sd.query_devices(index)
+ max_input_channels = int(device_info.get('max_input_channels', 0))
+
+ if max_input_channels < channels:
+ continue
+
+ device_name = str(device_info.get('name', '')).lower()
+ if name_hint not in device_name:
+ continue
+
+ score = 0
+
+ # Prefer exact channel matches (for example 1ch source over a 4ch source).
+ if max_input_channels == channels:
+ score += 100
+ else:
+ score += 10
+
+ hostapi_index = int(device_info.get('hostapi', -1))
+ api_name = ''
+ if hostapi_index >= 0:
+ hostapi_info = sd.query_hostapis(hostapi_index)
+ api_name = str(hostapi_info.get('name', '')).lower()
+
+ for priority, api_hint in enumerate(preferred_apis):
+ if api_hint in api_name:
+ score += 50 - priority
+ break
+
+ candidates.append((score, index))
+
+ if not candidates:
+ raise ValueError(
+ 'No input device matching hint="{}" with at least {} channels'.format(name_hint, channels)
+ )
+
+ return max(candidates, key=lambda item: item[0])[1]
+
if __name__ == '__main__':
# If you got "ValueError: No input device matching", that is because your PC name example device
@@ -14,8 +60,8 @@ if __name__ == '__main__':
duration = 3 # Duration of recording
if platform.system() == 'Windows':
- # MME is needed since there are more than one MicNode device APIs (at least in Windows)
- device = 'Microphone (MicNode), Windows WASAPI'
+ # Match by substring to support names like "Microphone (2- MicNode)".
+ device = find_windows_input_device('micnode', channels=1, preferred_apis=['wasapi', 'mme', 'wdm-ks'])
elif platform.system() == 'Darwin':
device = 'MicNode'
else:
diff --git a/examples/device/audio_test_freertos/src/usb_descriptors.c b/examples/device/audio_test_freertos/src/usb_descriptors.c
index ad161939e..37ebf84d3 100644
--- a/examples/device/audio_test_freertos/src/usb_descriptors.c
+++ b/examples/device/audio_test_freertos/src/usb_descriptors.c
@@ -91,6 +91,10 @@ enum
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
+#elif TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+
#else
#define EPNUM_AUDIO 0x01
#endif
diff --git a/examples/device/audio_test_multi_rate/skip.txt b/examples/device/audio_test_multi_rate/skip.txt
index 65b137814..42394bb11 100644
--- a/examples/device/audio_test_multi_rate/skip.txt
+++ b/examples/device/audio_test_multi_rate/skip.txt
@@ -2,3 +2,4 @@ mcu:SAMD11
mcu:SAME5X
mcu:SAMG
family:espressif
+mcu:CH583
diff --git a/examples/device/audio_test_multi_rate/src/main.c b/examples/device/audio_test_multi_rate/src/main.c
index 952176997..a86beb415 100644
--- a/examples/device/audio_test_multi_rate/src/main.c
+++ b/examples/device/audio_test_multi_rate/src/main.c
@@ -532,7 +532,7 @@ static bool audio20_get_req_entity(uint8_t rhport, tusb_control_request_t const
bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
//uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const alt = tu_u16_low(p_request->wValue);
// Clear buffer when streaming format is changed
if (alt != 0) {
diff --git a/examples/device/audio_test_multi_rate/src/plot_audio_samples.py b/examples/device/audio_test_multi_rate/src/plot_audio_samples.py
index 1f33a003e..f35cfa311 100755
--- a/examples/device/audio_test_multi_rate/src/plot_audio_samples.py
+++ b/examples/device/audio_test_multi_rate/src/plot_audio_samples.py
@@ -5,6 +5,52 @@ import numpy as np
import platform
import csv
+
+def find_windows_input_device(name_hint, channels, preferred_apis=None):
+ """Pick a Windows input device index from query_devices() output."""
+ preferred_apis = preferred_apis or []
+ name_hint = name_hint.lower()
+ candidates = []
+
+ for index in range(len(sd.query_devices())):
+ device_info = sd.query_devices(index)
+ max_input_channels = int(device_info.get('max_input_channels', 0))
+
+ if max_input_channels < channels:
+ continue
+
+ device_name = str(device_info.get('name', '')).lower()
+ if name_hint not in device_name:
+ continue
+
+ score = 0
+
+ # Prefer exact channel matches (for example 1ch source over a 4ch source).
+ if max_input_channels == channels:
+ score += 100
+ else:
+ score += 10
+
+ hostapi_index = int(device_info.get('hostapi', -1))
+ api_name = ''
+ if hostapi_index >= 0:
+ hostapi_info = sd.query_hostapis(hostapi_index)
+ api_name = str(hostapi_info.get('name', '')).lower()
+
+ for priority, api_hint in enumerate(preferred_apis):
+ if api_hint in api_name:
+ score += 50 - priority
+ break
+
+ candidates.append((score, index))
+
+ if not candidates:
+ raise ValueError(
+ 'No input device matching hint="{}" with at least {} channels'.format(name_hint, channels)
+ )
+
+ return max(candidates, key=lambda item: item[0])[1]
+
if __name__ == '__main__':
# If you got "ValueError: No input device matching", that is because your PC name example device
@@ -15,8 +61,8 @@ if __name__ == '__main__':
duration = 100e-3 # Duration of recording
if platform.system() == 'Windows':
- # MME is needed since there are more than one MicNode device APIs (at least in Windows)
- device = 'Microphone (MicNode) MME'
+ # Match by substring to support names like "Microphone (2- MicNode)".
+ device = find_windows_input_device('micnode', channels=1, preferred_apis=['mme', 'wasapi', 'wdm-ks'])
elif platform.system() == 'Darwin':
device = 'MicNode'
else:
diff --git a/examples/device/audio_test_multi_rate/src/usb_descriptors.c b/examples/device/audio_test_multi_rate/src/usb_descriptors.c
index 505936fdb..b1f60dd10 100644
--- a/examples/device/audio_test_multi_rate/src/usb_descriptors.c
+++ b/examples/device/audio_test_multi_rate/src/usb_descriptors.c
@@ -88,6 +88,14 @@ enum {
// nRF5x ISO can only be endpoint 8
#define EPNUM_AUDIO 0x08
+#elif TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+
+#elif TU_CHECK_MCU(OPT_MCU_CH32V20X, OPT_MCU_CH32V307)
+ // Only EP3 is available for ISO
+ #define EPNUM_AUDIO 0x03
+
#else
#define EPNUM_AUDIO 0x01
#endif
diff --git a/examples/device/board_test/CMakeLists.txt b/examples/device/board_test/CMakeLists.txt
index bd7b8e0ca..f14d72c08 100644
--- a/examples/device/board_test/CMakeLists.txt
+++ b/examples/device/board_test/CMakeLists.txt
@@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+# Need to set Espressif defaults before project() is called
+if(FAMILY STREQUAL "espressif")
+ list(APPEND SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
+endif()
+
project(board_test C CXX ASM)
# Checks this example is valid for the family and initializes the project
diff --git a/examples/device/board_test/src/main.c b/examples/device/board_test/src/main.c
index 71e7e1da7..96dc1bd30 100644
--- a/examples/device/board_test/src/main.c
+++ b/examples/device/board_test/src/main.c
@@ -54,6 +54,19 @@ void tusb_time_delay_ms_api(uint32_t ms) {
//
//--------------------------------------------------------------------+
+// CI_BUILD (defined for all CI builds, see hw/bsp/family_support.cmake) skips the
+// blink/echo loop below: after HIL tests, this firmware is flashed to park the
+// board in a quiet, low-power idle state (no USB, LED, or UART activity).
+#ifdef CI_BUILD
+int main(void) {
+ while (1) {
+ #if defined(ESP_PLATFORM)
+ vTaskDelay(portMAX_DELAY);
+ #endif
+ }
+}
+
+#else
// Task parameter type: ULONG for ThreadX, void* for FreeRTOS and noos
#if CFG_TUSB_OS == OPT_OS_THREADX
#define RTOS_PARAM ULONG
@@ -122,12 +135,6 @@ int main(void) {
return 0;
}
-#ifdef ESP_PLATFORM
-void app_main(void) {
- main();
-}
-#endif
-
//--------------------------------------------------------------------+
// FreeRTOS
//--------------------------------------------------------------------+
@@ -173,3 +180,10 @@ void tx_application_define(void *first_unused_memory) {
1, 1, TX_NO_TIME_SLICE, TX_AUTO_START);
}
#endif
+#endif // CI_BUILD
+
+#ifdef ESP_PLATFORM
+void app_main(void) {
+ main();
+}
+#endif
diff --git a/examples/device/cdc_dual_ports/src/usb_descriptors.c b/examples/device/cdc_dual_ports/src/usb_descriptors.c
index e6011c35a..adfd8cf9d 100644
--- a/examples/device/cdc_dual_ports/src/usb_descriptors.c
+++ b/examples/device/cdc_dual_ports/src/usb_descriptors.c
@@ -106,16 +106,27 @@ enum {
#define EPNUM_CDC_1_OUT 0x05
#define EPNUM_CDC_1_IN 0x84
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_CDC_0_NOTIF 0x81
- #define EPNUM_CDC_0_OUT 0x02
- #define EPNUM_CDC_0_IN 0x83
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_0_NOTIF 0x81
+ #define EPNUM_CDC_0_OUT 0x08
+ #define EPNUM_CDC_0_IN 0x89
- #define EPNUM_CDC_1_NOTIF 0x84
- #define EPNUM_CDC_1_OUT 0x05
- #define EPNUM_CDC_1_IN 0x86
+ #define EPNUM_CDC_1_NOTIF 0x82
+ #define EPNUM_CDC_1_OUT 0x0A
+ #define EPNUM_CDC_1_IN 0x8B
+ #else
+ #define EPNUM_CDC_0_NOTIF 0x81
+ #define EPNUM_CDC_0_OUT 0x02
+ #define EPNUM_CDC_0_IN 0x83
+
+ #define EPNUM_CDC_1_NOTIF 0x84
+ #define EPNUM_CDC_1_OUT 0x05
+ #define EPNUM_CDC_1_IN 0x86
+ #endif
#else
#define EPNUM_CDC_0_NOTIF 0x81
diff --git a/examples/device/cdc_msc/src/usb_descriptors.c b/examples/device/cdc_msc/src/usb_descriptors.c
index c668ea3a7..5dc80dee3 100644
--- a/examples/device/cdc_msc/src/usb_descriptors.c
+++ b/examples/device/cdc_msc/src/usb_descriptors.c
@@ -102,15 +102,25 @@ enum {
#define EPNUM_MSC_OUT 0x05
#define EPNUM_MSC_IN 0x84
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_CDC_NOTIF 0x81
- #define EPNUM_CDC_OUT 0x02
- #define EPNUM_CDC_IN 0x83
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
- #define EPNUM_MSC_OUT 0x04
- #define EPNUM_MSC_IN 0x85
+ #define EPNUM_MSC_OUT 0x0A
+ #define EPNUM_MSC_IN 0x8B
+ #else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x83
+
+ #define EPNUM_MSC_OUT 0x04
+ #define EPNUM_MSC_IN 0x85
+ #endif
#else
#define EPNUM_CDC_NOTIF 0x81
diff --git a/examples/device/cdc_msc_freertos/CMakeLists.txt b/examples/device/cdc_msc_freertos/CMakeLists.txt
index 429000427..1eafd529a 100644
--- a/examples/device/cdc_msc_freertos/CMakeLists.txt
+++ b/examples/device/cdc_msc_freertos/CMakeLists.txt
@@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+# Need to set Espressif defaults before project() is called
+if(FAMILY STREQUAL "espressif")
+ list(APPEND SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
+endif()
+
project(cdc_msc_freertos C CXX ASM)
# Checks this example is valid for the family and initializes the project
diff --git a/examples/device/cdc_msc_freertos/skip.txt b/examples/device/cdc_msc_freertos/skip.txt
index 429c62d93..48781de84 100644
--- a/examples/device/cdc_msc_freertos/skip.txt
+++ b/examples/device/cdc_msc_freertos/skip.txt
@@ -2,6 +2,7 @@ mcu:CH32F20X
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:CXD56
mcu:F1C100S
mcu:GD32VF103
diff --git a/examples/device/cdc_msc_freertos/src/main.c b/examples/device/cdc_msc_freertos/src/main.c
index 4fb209fd0..4a920c90b 100644
--- a/examples/device/cdc_msc_freertos/src/main.c
+++ b/examples/device/cdc_msc_freertos/src/main.c
@@ -34,10 +34,10 @@
#define USBD_STACK_SIZE 4096
#else
// Increase stack size when debug log is enabled
- #define USBD_STACK_SIZE (3*configMINIMAL_STACK_SIZE/2) * (CFG_TUSB_DEBUG ? 2 : 1)
+ #define USBD_STACK_SIZE (configMINIMAL_STACK_SIZE * (CFG_TUSB_DEBUG ? 4 : 2))
#endif
-#define CDC_STACK_SIZE (configMINIMAL_STACK_SIZE * (CFG_TUSB_DEBUG ? 2 : 1))
+#define CDC_STACK_SIZE (configMINIMAL_STACK_SIZE * (CFG_TUSB_DEBUG ? 3 : 2))
#define BLINKY_STACK_SIZE configMINIMAL_STACK_SIZE
//--------------------------------------------------------------------+
@@ -88,7 +88,7 @@ int main(void) {
#else
xTaskCreate(led_blinking_task, "blinky", BLINKY_STACK_SIZE, NULL, 1, NULL);
xTaskCreate(usb_device_task, "usbd", USBD_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL);
- xTaskCreate(cdc_task, "cdc", CDC_STACK_SZIE, NULL, configMAX_PRIORITIES - 2, NULL);
+ xTaskCreate(cdc_task, "cdc", CDC_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL);
#endif
#ifndef ESP_PLATFORM
diff --git a/examples/device/cdc_msc_freertos/src/usb_descriptors.c b/examples/device/cdc_msc_freertos/src/usb_descriptors.c
index 4950f02e0..f5b015051 100644
--- a/examples/device/cdc_msc_freertos/src/usb_descriptors.c
+++ b/examples/device/cdc_msc_freertos/src/usb_descriptors.c
@@ -102,15 +102,25 @@ enum {
#define EPNUM_MSC_OUT 0x05
#define EPNUM_MSC_IN 0x84
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_CDC_NOTIF 0x81
- #define EPNUM_CDC_OUT 0x02
- #define EPNUM_CDC_IN 0x83
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
- #define EPNUM_MSC_OUT 0x04
- #define EPNUM_MSC_IN 0x85
+ #define EPNUM_MSC_OUT 0x0A
+ #define EPNUM_MSC_IN 0x8B
+ #else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x83
+
+ #define EPNUM_MSC_OUT 0x04
+ #define EPNUM_MSC_IN 0x85
+ #endif
#else
#define EPNUM_CDC_NOTIF 0x81
diff --git a/examples/device/cdc_msc_throughput/CMakeLists.txt b/examples/device/cdc_msc_throughput/CMakeLists.txt
new file mode 100644
index 000000000..69c1caa6a
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/CMakeLists.txt
@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 3.20)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+
+project(cdc_msc_throughput C CXX ASM)
+
+# Checks this example is valid for the family and initializes the project
+family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR})
+
+# Espressif has its own cmake build system
+if(FAMILY STREQUAL "espressif")
+ return()
+endif()
+
+if (RTOS STREQUAL zephyr)
+ set(EXE_NAME app)
+else()
+ set(EXE_NAME ${PROJECT_NAME})
+ add_executable(${EXE_NAME})
+endif()
+
+# Example source
+target_sources(${EXE_NAME} PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c
+ )
+
+# Example include
+target_include_directories(${EXE_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+ )
+
+# Configure compilation flags and libraries for the example without RTOS.
+# See the corresponding function in hw/bsp/FAMILY/family.cmake for details.
+family_configure_device_example(${EXE_NAME} ${RTOS})
diff --git a/examples/device/cdc_msc_throughput/CMakePresets.json b/examples/device/cdc_msc_throughput/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/device/cdc_msc_throughput/Makefile b/examples/device/cdc_msc_throughput/Makefile
new file mode 100644
index 000000000..035e90308
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/Makefile
@@ -0,0 +1,11 @@
+include ../../../hw/bsp/family_support.mk
+
+INC += \
+ src \
+
+
+# Example source
+EXAMPLE_SOURCE += $(wildcard src/*.c)
+SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE))
+
+include ../../../hw/bsp/family_rules.mk
diff --git a/examples/device/cdc_msc_throughput/src/main.c b/examples/device/cdc_msc_throughput/src/main.c
new file mode 100644
index 000000000..116cbe13f
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/src/main.c
@@ -0,0 +1,151 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+
+// cdc_msc_throughput: minimal CDC+MSC device aimed at measuring pure USB bulk throughput.
+// MSC read/write callbacks don't touch any backing storage - write discards the
+// data and read only zero-fills the low LBAs the host scans during enumeration
+// (partition table, GPT header). Higher LBAs return whatever is already in the
+// transfer buffer, so `dd` numbers reflect the USB/driver ceiling, not any
+// simulated storage or per-byte memset cost.
+// CDC path drains RX in tud_cdc_rx_cb and sources TX from a static filler in the
+// main loop so `dd` can target /dev/ttyACMx in either direction.
+
+static void cdc_throughput_task(void);
+
+//--------------------------------------------------------------------+
+// Main
+//--------------------------------------------------------------------+
+int main(void) {
+ board_init();
+
+ tusb_rhport_init_t dev_init = {.role = TUSB_ROLE_DEVICE, .speed = TUSB_SPEED_AUTO};
+ tusb_init(BOARD_TUD_RHPORT, &dev_init);
+
+ board_init_after_tusb();
+
+ while (1) {
+ tud_task();
+ cdc_throughput_task();
+ }
+}
+
+//--------------------------------------------------------------------+
+// CDC callbacks + tasks
+//--------------------------------------------------------------------+
+void tud_cdc_rx_cb(uint8_t itf) {
+ (void) itf;
+ tud_cdc_read_flush(); // Drain RX
+}
+
+static void cdc_throughput_task(void) {
+ if (!tud_cdc_connected()) return;
+
+ // Source TX: fill whatever write room is free.
+ static uint8_t const filler[CFG_TUD_CDC_TX_EPSIZE] = {0};
+ uint32_t room = tud_cdc_write_available();
+ while (room > 0) {
+ uint32_t n = tud_cdc_write(filler, tu_min32(room, sizeof(filler)));
+ if (n == 0) {
+ break;
+ }
+ room -= n;
+ }
+ tud_cdc_write_flush();
+}
+
+//--------------------------------------------------------------------+
+// MSC callbacks
+//--------------------------------------------------------------------+
+
+// 1 GiB logical capacity so `dd` can run long enough for stable numbers.
+// No real backing store - block content is synthesised on read, discarded on write.
+enum {
+ DISK_BLOCK_SIZE = 512,
+ DISK_BLOCK_COUNT = 0x00200000u, // 2 Mi blocks = 1 GiB
+ // Kernel probes partition-table / filesystem-superblock locations near the
+ // start of the disk during enumeration. Zero-fill only this head range so the
+ // block layer sees "no partition, no filesystem" and leaves us alone; higher
+ // LBAs skip the memset so `dd` measures pure USB/driver throughput.
+ DISK_ZEROFILL_LBA = 64, // 32 KiB
+};
+
+void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) {
+ (void) lun;
+ const char vid[] = "TinyUSB";
+ const char pid[] = "Mass Storage";
+ const char rev[] = "1.0";
+ (void) strncpy((char*) vendor_id, vid, 8);
+ (void) strncpy((char*) product_id, pid, 16);
+ (void) strncpy((char*) product_rev, rev, 4);
+}
+
+bool tud_msc_test_unit_ready_cb(uint8_t lun) {
+ (void) lun;
+ return true;
+}
+
+void tud_msc_capacity_cb(uint8_t lun, uint32_t *block_count, uint16_t *block_size) {
+ (void) lun;
+ *block_count = DISK_BLOCK_COUNT;
+ *block_size = DISK_BLOCK_SIZE;
+}
+
+bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject) {
+ (void) lun; (void) power_condition; (void) start; (void) load_eject;
+ return true;
+}
+
+bool tud_msc_is_writable_cb(uint8_t lun) {
+ (void) lun;
+ return true;
+}
+
+// READ10: zero-fill only the head range the kernel inspects, skip memset everywhere
+// else so we measure the USB / driver path rather than memset cost.
+int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) {
+ (void) lun; (void) offset;
+ if (lba < DISK_ZEROFILL_LBA) {
+ memset(buffer, 0, bufsize);
+ } else {
+ (void) buffer;
+ }
+ return (int32_t) bufsize;
+}
+
+// WRITE10: discard the received data entirely - this is the pure USB-speed test.
+int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) {
+ (void) lun; (void) lba; (void) offset; (void) buffer;
+ return (int32_t) bufsize;
+}
+
+// Unknown SCSI commands: stall with Invalid Command sense.
+int32_t tud_msc_scsi_cb(uint8_t lun, uint8_t const scsi_cmd[16], void *buffer, uint16_t bufsize) {
+ (void) scsi_cmd; (void) buffer; (void) bufsize;
+ tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
+ return -1;
+}
diff --git a/examples/device/cdc_msc_throughput/src/tusb_config.h b/examples/device/cdc_msc_throughput/src/tusb_config.h
new file mode 100644
index 000000000..6c8655719
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/src/tusb_config.h
@@ -0,0 +1,103 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#ifndef TUSB_CONFIG_H_
+#define TUSB_CONFIG_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------
+// Board Specific Configuration
+//--------------------------------------------------------------------
+
+#ifndef BOARD_TUD_RHPORT
+ #define BOARD_TUD_RHPORT 0
+#endif
+
+#ifndef BOARD_TUD_MAX_SPEED
+ #define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+#endif
+
+//--------------------------------------------------------------------
+// Common Configuration
+//--------------------------------------------------------------------
+
+#ifndef CFG_TUSB_MCU
+ #error CFG_TUSB_MCU must be defined
+#endif
+
+#ifndef CFG_TUSB_OS
+ #define CFG_TUSB_OS OPT_OS_NONE
+#endif
+
+#ifndef CFG_TUSB_DEBUG
+ #define CFG_TUSB_DEBUG 0
+#endif
+
+// Enable Device stack
+#define CFG_TUD_ENABLED 1
+#define CFG_TUD_MAX_SPEED BOARD_TUD_MAX_SPEED
+
+#ifndef CFG_TUSB_MEM_SECTION
+ #define CFG_TUSB_MEM_SECTION
+#endif
+
+#ifndef CFG_TUSB_MEM_ALIGN
+ #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
+#endif
+
+//--------------------------------------------------------------------
+// DEVICE CONFIGURATION
+//--------------------------------------------------------------------
+
+#ifndef CFG_TUD_ENDPOINT0_SIZE
+ #define CFG_TUD_ENDPOINT0_SIZE 64
+#endif
+
+//------------- CLASS -------------//
+#define CFG_TUD_CDC 1
+#define CFG_TUD_MSC 1
+
+// Large MSC bulk buffer: host transfers big CBW payloads (e.g. dd bs=1M does 64KiB
+// chunks). A 4K per-bulk-IO buffer lets the class driver amortise the per-CBW
+// overhead across many USB packets, approximating the maximum USB bulk throughput.
+#define CFG_TUD_MSC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 4096 : 1024)
+
+// #define CFG_TUD_CDC_TX_PERSISTENT 1
+
+// CDC throughput: size for HS; tinyusb will auto-scale for FS via TUD_OPT_HIGH_SPEED.
+#define CFG_TUD_CDC_RX_EPSIZE (TUD_OPT_HIGH_SPEED ? 2*512 : 2*64)
+#define CFG_TUD_CDC_TX_EPSIZE CFG_TUD_CDC_RX_EPSIZE
+
+#define CFG_TUD_CDC_RX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 2*512 : 2*64)
+#define CFG_TUD_CDC_TX_BUFSIZE CFG_TUD_CDC_RX_BUFSIZE
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* TUSB_CONFIG_H_ */
diff --git a/examples/device/cdc_msc_throughput/src/usb_descriptors.c b/examples/device/cdc_msc_throughput/src/usb_descriptors.c
new file mode 100644
index 000000000..3b0ff6e17
--- /dev/null
+++ b/examples/device/cdc_msc_throughput/src/usb_descriptors.c
@@ -0,0 +1,186 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ */
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+
+#define USB_PID (0x4000 | ((CFG_TUD_CDC) ? (1 << 0) : 0) | ((CFG_TUD_MSC) ? (1 << 1) : 0))
+#define USB_VID 0xCafe
+#define USB_BCD 0x0200
+
+static tusb_desc_device_t const desc_device = {
+ .bLength = sizeof(tusb_desc_device_t),
+ .bDescriptorType = TUSB_DESC_DEVICE,
+ .bcdUSB = USB_BCD,
+
+ // IAD required for composite CDC + MSC
+ .bDeviceClass = TUSB_CLASS_MISC,
+ .bDeviceSubClass = MISC_SUBCLASS_COMMON,
+ .bDeviceProtocol = MISC_PROTOCOL_IAD,
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+
+ .idVendor = USB_VID,
+ .idProduct = USB_PID,
+ .bcdDevice = 0x0100,
+
+ .iManufacturer = 0x01,
+ .iProduct = 0x02,
+ .iSerialNumber = 0x03,
+
+ .bNumConfigurations = 0x01,
+};
+
+uint8_t const *tud_descriptor_device_cb(void) {
+ return (uint8_t const *) &desc_device;
+}
+
+enum {
+ ITF_NUM_CDC = 0,
+ ITF_NUM_CDC_DATA,
+ ITF_NUM_MSC,
+ ITF_NUM_TOTAL,
+};
+
+// Place bulk endpoints on EP>=8 for MAX32690 class parts (bigger FIFO, DPB-capable).
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
+ #define EPNUM_MSC_OUT 0x0A
+ #define EPNUM_MSC_IN 0x8B
+ #else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x83
+ #define EPNUM_MSC_OUT 0x04
+ #define EPNUM_MSC_IN 0x85
+ #endif
+#else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x82
+ #define EPNUM_MSC_OUT 0x03
+ #define EPNUM_MSC_IN 0x83
+#endif
+
+#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN + TUD_MSC_DESC_LEN)
+
+static uint8_t const desc_fs_configuration[] = {
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+ TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 16, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),
+ TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC_OUT, EPNUM_MSC_IN, 64),
+};
+
+#if TUD_OPT_HIGH_SPEED
+static uint8_t const desc_hs_configuration[] = {
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+ TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 16, EPNUM_CDC_OUT, EPNUM_CDC_IN, 512),
+ TUD_MSC_DESCRIPTOR(ITF_NUM_MSC, 5, EPNUM_MSC_OUT, EPNUM_MSC_IN, 512),
+};
+
+static uint8_t desc_other_speed_config[CONFIG_TOTAL_LEN];
+
+static tusb_desc_device_qualifier_t const desc_device_qualifier = {
+ .bLength = sizeof(tusb_desc_device_qualifier_t),
+ .bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER,
+ .bcdUSB = USB_BCD,
+ .bDeviceClass = 0x00,
+ .bDeviceSubClass = 0x00,
+ .bDeviceProtocol = 0x00,
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+ .bNumConfigurations = 0x01,
+ .bReserved = 0x00,
+};
+
+uint8_t const *tud_descriptor_device_qualifier_cb(void) {
+ return (uint8_t const *) &desc_device_qualifier;
+}
+
+uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
+ (void) index;
+ memcpy(desc_other_speed_config,
+ (tud_speed_get() == TUSB_SPEED_HIGH) ? desc_fs_configuration : desc_hs_configuration,
+ CONFIG_TOTAL_LEN);
+ desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
+ return desc_other_speed_config;
+}
+#endif
+
+uint8_t const *tud_descriptor_configuration_cb(uint8_t index) {
+ (void) index;
+#if TUD_OPT_HIGH_SPEED
+ return (tud_speed_get() == TUSB_SPEED_HIGH) ? desc_hs_configuration : desc_fs_configuration;
+#else
+ return desc_fs_configuration;
+#endif
+}
+
+enum {
+ STRID_LANGID = 0,
+ STRID_MANUFACTURER,
+ STRID_PRODUCT,
+ STRID_SERIAL,
+};
+
+static char const *string_desc_arr[] = {
+ (const char[]) { 0x09, 0x04 },
+ "TinyUSB",
+ "Throughput",
+ NULL,
+ "TinyUSB CDC",
+ "TinyUSB MSC",
+};
+
+static uint16_t _desc_str[32 + 1];
+
+uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
+ (void) langid;
+ size_t chr_count;
+
+ switch (index) {
+ case STRID_LANGID:
+ memcpy(&_desc_str[1], string_desc_arr[0], 2);
+ chr_count = 1;
+ break;
+
+ case STRID_SERIAL:
+ chr_count = board_usb_get_serial(_desc_str + 1, 32);
+ break;
+
+ default:
+ if (!(index < sizeof(string_desc_arr) / sizeof(string_desc_arr[0]))) return NULL;
+ const char *str = string_desc_arr[index];
+ chr_count = strlen(str);
+ size_t const max_count = sizeof(_desc_str) / sizeof(_desc_str[0]) - 1;
+ if (chr_count > max_count) chr_count = max_count;
+ for (size_t i = 0; i < chr_count; i++) _desc_str[1 + i] = str[i];
+ break;
+ }
+
+ _desc_str[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * chr_count + 2));
+ return _desc_str;
+}
diff --git a/examples/device/cdc_uac2/skip.txt b/examples/device/cdc_uac2/skip.txt
index a2a76af0e..db1d5b80b 100644
--- a/examples/device/cdc_uac2/skip.txt
+++ b/examples/device/cdc_uac2/skip.txt
@@ -6,3 +6,4 @@ mcu:SAME5X
mcu:SAMG
board:stm32l052dap52
family:espressif
+mcu:CH583
diff --git a/examples/device/cdc_uac2/src/uac2_app.c b/examples/device/cdc_uac2/src/uac2_app.c
index 7760c402b..a504c3b57 100644
--- a/examples/device/cdc_uac2/src/uac2_app.c
+++ b/examples/device/cdc_uac2/src/uac2_app.c
@@ -82,20 +82,20 @@ void audio_task(void) {
}
// Helper for clock get requests
-static bool tud_audio_clock_get_request(uint8_t rhport, audio20_control_request_t const *request)
+static bool tud_audio_clock_get_request(uint8_t rhport, tusb_control_request_t const *p_request)
{
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ)
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ)
{
- if (request->bRequest == AUDIO20_CS_REQ_CUR)
+ if (p_request->bRequest == AUDIO20_CS_REQ_CUR)
{
TU_LOG1("Clock get current freq %" PRIu32 "\r\n", current_sample_rate);
audio20_control_cur_4_t curf = { (int32_t) tu_htole32(current_sample_rate) };
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &curf, sizeof(curf));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &curf, sizeof(curf));
}
- else if (request->bRequest == AUDIO20_CS_REQ_RANGE)
+ else if (p_request->bRequest == AUDIO20_CS_REQ_RANGE)
{
audio20_control_range_4_n_t(N_SAMPLE_RATES) rangef =
{
@@ -110,32 +110,33 @@ static bool tud_audio_clock_get_request(uint8_t rhport, audio20_control_request_
TU_LOG1("Range %d (%d, %d, %d)\r\n", i, (int)rangef.subrange[i].bMin, (int)rangef.subrange[i].bMax, (int)rangef.subrange[i].bRes);
}
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &rangef, sizeof(rangef));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &rangef, sizeof(rangef));
}
}
- else if (request->bControlSelector == AUDIO20_CS_CTRL_CLK_VALID &&
- request->bRequest == AUDIO20_CS_REQ_CUR)
+ else if (ctrl_sel == AUDIO20_CS_CTRL_CLK_VALID &&
+ p_request->bRequest == AUDIO20_CS_REQ_CUR)
{
audio20_control_cur_1_t cur_valid = { .bCur = 1 };
TU_LOG1("Clock get is valid %u\r\n", cur_valid.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &cur_valid, sizeof(cur_valid));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_valid, sizeof(cur_valid));
}
- TU_LOG1("Clock get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
// Helper for clock set requests
-static bool tud_audio_clock_set_request(uint8_t rhport, audio20_control_request_t const *request, uint8_t const *buf)
+static bool tud_audio_clock_set_request(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t const *buf)
{
(void)rhport;
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ)
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
+
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ)
{
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_4_t));
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_4_t));
current_sample_rate = (uint32_t) ((audio20_control_cur_4_t const *)buf)->bCur;
@@ -145,80 +146,83 @@ static bool tud_audio_clock_set_request(uint8_t rhport, audio20_control_request_
}
else
{
- TU_LOG1("Clock set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
// Helper for feature unit get requests
-static bool tud_audio_feature_unit_get_request(uint8_t rhport, audio20_control_request_t const *request)
+static bool tud_audio_feature_unit_get_request(uint8_t rhport, tusb_control_request_t const *p_request)
{
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE && request->bRequest == AUDIO20_CS_REQ_CUR)
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE && p_request->bRequest == AUDIO20_CS_REQ_CUR)
{
- audio20_control_cur_1_t mute1 = { .bCur = mute[request->bChannelNumber] };
- TU_LOG1("Get channel %u mute %d\r\n", request->bChannelNumber, mute1.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &mute1, sizeof(mute1));
+ audio20_control_cur_1_t mute1 = { .bCur = mute[channel_num] };
+ TU_LOG1("Get channel %u mute %d\r\n", channel_num, mute1.bCur);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute1, sizeof(mute1));
}
- else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME)
+ else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME)
{
- if (request->bRequest == AUDIO20_CS_REQ_RANGE)
+ if (p_request->bRequest == AUDIO20_CS_REQ_RANGE)
{
audio20_control_range_2_n_t(1) range_vol = {
.wNumSubRanges = tu_htole16(1),
.subrange[0] = { .bMin = tu_htole16(-VOLUME_CTRL_50_DB), tu_htole16(VOLUME_CTRL_0_DB), tu_htole16(256) }
};
- TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", request->bChannelNumber,
+ TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", channel_num,
range_vol.subrange[0].bMin / 256, range_vol.subrange[0].bMax / 256, range_vol.subrange[0].bRes / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &range_vol, sizeof(range_vol));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &range_vol, sizeof(range_vol));
}
- else if (request->bRequest == AUDIO20_CS_REQ_CUR)
+ else if (p_request->bRequest == AUDIO20_CS_REQ_CUR)
{
- audio20_control_cur_2_t cur_vol = { .bCur = tu_htole16(volume[request->bChannelNumber]) };
- TU_LOG1("Get channel %u volume %d dB\r\n", request->bChannelNumber, cur_vol.bCur / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *)request, &cur_vol, sizeof(cur_vol));
+ audio20_control_cur_2_t cur_vol = { .bCur = tu_htole16(volume[channel_num]) };
+ TU_LOG1("Get channel %u volume %d dB\r\n", channel_num, cur_vol.bCur / 256);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_vol, sizeof(cur_vol));
}
}
- TU_LOG1("Feature unit get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
// Helper for feature unit set requests
-static bool tud_audio_feature_unit_set_request(uint8_t rhport, audio20_control_request_t const *request, uint8_t const *buf)
+static bool tud_audio_feature_unit_set_request(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t const *buf)
{
(void)rhport;
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
+
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE)
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE)
{
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_1_t));
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
- mute[request->bChannelNumber] = ((audio20_control_cur_1_t const *)buf)->bCur;
+ mute[channel_num] = ((audio20_control_cur_1_t const *)buf)->bCur;
- TU_LOG1("Set channel %d Mute: %d\r\n", request->bChannelNumber, mute[request->bChannelNumber]);
+ TU_LOG1("Set channel %d Mute: %d\r\n", channel_num, mute[channel_num]);
return true;
}
- else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME)
+ else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME)
{
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_2_t));
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
- volume[request->bChannelNumber] = ((audio20_control_cur_2_t const *)buf)->bCur;
+ volume[channel_num] = ((audio20_control_cur_2_t const *)buf)->bCur;
- TU_LOG1("Set channel %d volume: %d dB\r\n", request->bChannelNumber, volume[request->bChannelNumber] / 256);
+ TU_LOG1("Set channel %d volume: %d dB\r\n", channel_num, volume[channel_num] / 256);
return true;
}
else
{
- TU_LOG1("Feature unit set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
@@ -229,32 +233,32 @@ static bool tud_audio_feature_unit_set_request(uint8_t rhport, audio20_control_r
// Invoked when audio class specific get request received for an entity
bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
- audio20_control_request_t const *request = (audio20_control_request_t const *)p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_CLOCK) {
- return tud_audio_clock_get_request(rhport, request);
+ if (entity_id == UAC2_ENTITY_CLOCK) {
+ return tud_audio_clock_get_request(rhport, p_request);
}
- if (request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT) {
- return tud_audio_feature_unit_get_request(rhport, request);
+ if (entity_id == UAC2_ENTITY_SPK_FEATURE_UNIT) {
+ return tud_audio_feature_unit_get_request(rhport, p_request);
} else {
TU_LOG1("Get request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
}
return false;
}
// Invoked when audio class specific set request received for an entity
bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *buf) {
- audio20_control_request_t const *request = (audio20_control_request_t const *)p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT) {
- return tud_audio_feature_unit_set_request(rhport, request, buf);
+ if (entity_id == UAC2_ENTITY_SPK_FEATURE_UNIT) {
+ return tud_audio_feature_unit_set_request(rhport, p_request, buf);
}
- if (request->bEntityID == UAC2_ENTITY_CLOCK) {
- return tud_audio_clock_set_request(rhport, request, buf);
+ if (entity_id == UAC2_ENTITY_CLOCK) {
+ return tud_audio_clock_set_request(rhport, p_request, buf);
}
TU_LOG1("Set request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
return false;
}
@@ -263,8 +267,8 @@ bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const
{
(void)rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
if (ITF_NUM_AUDIO_STREAMING_SPK == itf && alt == 0) {
// Audio streaming stop
@@ -277,8 +281,8 @@ bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const
bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request)
{
(void)rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
TU_LOG2("Set interface %d alt %d\r\n", itf, alt);
if (ITF_NUM_AUDIO_STREAMING_SPK == itf && alt != 0) {
diff --git a/examples/device/cdc_uac2/src/usb_descriptors.c b/examples/device/cdc_uac2/src/usb_descriptors.c
index e6caaa971..fdffc761e 100644
--- a/examples/device/cdc_uac2/src/usb_descriptors.c
+++ b/examples/device/cdc_uac2/src/usb_descriptors.c
@@ -97,15 +97,25 @@ uint8_t const * tud_descriptor_device_cb(void)
#define EPNUM_CDC_OUT 0x02
#define EPNUM_CDC_IN 0x82
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_AUDIO_IN 0x01
- #define EPNUM_AUDIO_OUT 0x02
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put CDC bulk on EP>=8 and audio iso on EP10/11 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO_OUT 0x0A
+ #define EPNUM_AUDIO_IN 0x0B
- #define EPNUM_CDC_NOTIF 0x83
- #define EPNUM_CDC_OUT 0x04
- #define EPNUM_CDC_IN 0x85
+ #define EPNUM_CDC_NOTIF 0x83
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
+ #else
+ #define EPNUM_AUDIO_IN 0x01
+ #define EPNUM_AUDIO_OUT 0x02
+
+ #define EPNUM_CDC_NOTIF 0x83
+ #define EPNUM_CDC_OUT 0x04
+ #define EPNUM_CDC_IN 0x85
+ #endif
#else
#define EPNUM_AUDIO_IN 0x01
diff --git a/examples/device/dfu/skip.txt b/examples/device/dfu/skip.txt
index 79d3da9d2..ccff857ac 100644
--- a/examples/device/dfu/skip.txt
+++ b/examples/device/dfu/skip.txt
@@ -1,3 +1,2 @@
-mcu:TM4C
mcu:BCM2835
family:espressif
diff --git a/examples/device/dfu_runtime/skip.txt b/examples/device/dfu_runtime/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/dfu_runtime/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/dynamic_configuration/src/usb_descriptors.c b/examples/device/dynamic_configuration/src/usb_descriptors.c
index 458b7c2a5..c4049414f 100644
--- a/examples/device/dynamic_configuration/src/usb_descriptors.c
+++ b/examples/device/dynamic_configuration/src/usb_descriptors.c
@@ -132,7 +132,7 @@ enum
#define EPNUM_1_MSC_OUT 0x02
#define EPNUM_1_MSC_IN 0x82
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_0_CDC_NOTIF 0x81
diff --git a/examples/device/hid_boot_interface/skip.txt b/examples/device/hid_boot_interface/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/hid_boot_interface/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/hid_composite/skip.txt b/examples/device/hid_composite/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/hid_composite/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/hid_composite_freertos/CMakeLists.txt b/examples/device/hid_composite_freertos/CMakeLists.txt
index b52373011..2081a7782 100644
--- a/examples/device/hid_composite_freertos/CMakeLists.txt
+++ b/examples/device/hid_composite_freertos/CMakeLists.txt
@@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20)
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+# Need to set Espressif defaults before project() is called
+if(FAMILY STREQUAL "espressif")
+ list(APPEND SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
+endif()
+
project(hid_composite_freertos C CXX ASM)
# Checks this example is valid for the family and initializes the project
diff --git a/examples/device/hid_composite_freertos/skip.txt b/examples/device/hid_composite_freertos/skip.txt
index d2ee8d636..97d8e168b 100644
--- a/examples/device/hid_composite_freertos/skip.txt
+++ b/examples/device/hid_composite_freertos/skip.txt
@@ -2,6 +2,7 @@ mcu:CH32F20X
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:CXD56
mcu:F1C100S
mcu:GD32VF103
diff --git a/examples/device/hid_generic_inout/skip.txt b/examples/device/hid_generic_inout/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/hid_generic_inout/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/hid_generic_inout/src/usb_descriptors.c b/examples/device/hid_generic_inout/src/usb_descriptors.c
index 929b2fd3a..93e718461 100644
--- a/examples/device/hid_generic_inout/src/usb_descriptors.c
+++ b/examples/device/hid_generic_inout/src/usb_descriptors.c
@@ -97,7 +97,7 @@ enum
#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_INOUT_DESC_LEN)
-#if defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_HID_OUT 0x01
diff --git a/examples/device/hid_multiple_interface/skip.txt b/examples/device/hid_multiple_interface/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/hid_multiple_interface/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/midi2_device/CMakeLists.txt b/examples/device/midi2_device/CMakeLists.txt
new file mode 100644
index 000000000..f1fe09db2
--- /dev/null
+++ b/examples/device/midi2_device/CMakeLists.txt
@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 3.20)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+
+project(midi2_device C CXX ASM)
+
+# Checks this example is valid for the family and initializes the project
+family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR})
+
+# Espressif has its own cmake build system
+if(FAMILY STREQUAL "espressif")
+ return()
+endif()
+
+add_executable(${PROJECT_NAME})
+
+# Example source
+target_sources(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/usb_descriptors.c
+ )
+
+# Example include
+target_include_directories(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+ )
+
+# Configure compilation flags and libraries for the example without RTOS.
+# See the corresponding function in hw/bsp/FAMILY/family.cmake for details.
+family_configure_device_example(${PROJECT_NAME} noos)
+
+# Suppress pre-existing warning in usbd.c (uint8_t comparison always true/false)
+if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ target_compile_options(${PROJECT_NAME} PRIVATE -Wno-type-limits)
+endif()
diff --git a/examples/device/midi2_device/CMakePresets.json b/examples/device/midi2_device/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/device/midi2_device/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/device/midi2_device/Makefile b/examples/device/midi2_device/Makefile
new file mode 100644
index 000000000..829d9da59
--- /dev/null
+++ b/examples/device/midi2_device/Makefile
@@ -0,0 +1,16 @@
+include ../../../hw/bsp/family_support.mk
+
+INC += \
+ src \
+
+# Example source
+EXAMPLE_SOURCE += \
+ src/main.c \
+ src/usb_descriptors.c \
+
+SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE))
+
+# Suppress pre-existing warning in usbd.c
+CFLAGS_GCC += -Wno-type-limits
+
+include ../../../hw/bsp/family_rules.mk
diff --git a/examples/device/midi2_device/README.md b/examples/device/midi2_device/README.md
new file mode 100644
index 000000000..1731dba57
--- /dev/null
+++ b/examples/device/midi2_device/README.md
@@ -0,0 +1,59 @@
+# MIDI 2.0 Song Sender
+
+USB MIDI 2.0 Device example that plays "Twinkle Twinkle Little Star" using
+native UMP (Universal MIDI Packet) format with full MIDI 2.0 expression.
+
+## MIDI 2.0 Features Demonstrated
+
+- 16-bit Velocity (vs 7-bit MIDI 1.0)
+- 32-bit Control Change values
+- 32-bit Pitch Bend (vs 14-bit MIDI 1.0)
+- 32-bit Channel Pressure (Aftertouch)
+- 32-bit Poly Pressure (Per-Note Aftertouch)
+- Per-Note Management (MIDI 2.0 exclusive)
+- Program Change with Bank Select
+- JR Timestamps
+
+## USB Descriptor
+
+The device exposes both USB-MIDI 1.0 (Alt Setting 0) and USB-MIDI 2.0 (Alt Setting 1)
+as required by the USB-MIDI 2.0 specification. A MIDI 2.0 capable host (e.g. Windows
+MIDI Services) will select Alt Setting 1 for native UMP transport. Legacy hosts use
+Alt Setting 0 with automatic MIDI 1.0 fallback.
+
+## Hardware
+
+- Any RP2040 board with USB (e.g. Raspberry Pi Pico)
+- LED on GPIO 25: steady = playing, slow blink = waiting for host
+
+## Building
+
+```bash
+mkdir build && cd build
+cmake -DBOARD=raspberry_pi_pico -DPICO_SDK_FETCH_FROM_GIT=on -G Ninja ..
+cmake --build .
+```
+
+## Flashing
+
+Hold BOOTSEL, connect USB, drag `midi2_device.uf2` to the RPI-RP2 drive.
+
+## Testing
+
+**Linux:**
+```bash
+aseqdump -p "MIDI 2.0 Device"
+```
+
+**Windows (MIDI 2.0 native):**
+```powershell
+midi endpoint list
+midi endpoint monitor
+```
+
+## Song Data
+
+Twinkle Twinkle Little Star in C major, 120 BPM. Six phrases with dynamic
+shaping (pp to ff crescendo and back), pitch bend vibrato on sustained notes,
+and channel/poly pressure for expression. All values use genuine MIDI 2.0
+resolution with no 7-bit equivalent.
diff --git a/examples/device/midi2_device/skip.txt b/examples/device/midi2_device/skip.txt
new file mode 100644
index 000000000..eadb6e74a
--- /dev/null
+++ b/examples/device/midi2_device/skip.txt
@@ -0,0 +1 @@
+mcu:SAMD11
diff --git a/examples/device/midi2_device/src/main.c b/examples/device/midi2_device/src/main.c
new file mode 100644
index 000000000..ce052a20b
--- /dev/null
+++ b/examples/device/midi2_device/src/main.c
@@ -0,0 +1,718 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include "bsp/board_api.h"
+#include "tusb.h"
+#include "class/midi/midi2_device.h"
+
+//--------------------------------------------------------------------+
+// MIDI 2.0 UMP Message Type Constants (M2-104-UM, Section 4)
+//--------------------------------------------------------------------+
+// Message Type (MT) occupies bits 31-28 of Word 0
+#define UMP_MT_UTILITY 0x00000000 // 32-bit: Utility (NOOP, JR Clock, JR Timestamp)
+#define UMP_MT_SYSTEM 0x10000000 // 32-bit: System Common / Real Time
+#define UMP_MT_MIDI1_CV 0x20000000 // 32-bit: MIDI 1.0 Channel Voice
+#define UMP_MT_DATA64 0x30000000 // 64-bit: Data (SysEx 7-bit)
+#define UMP_MT_MIDI2_CV 0x40000000 // 64-bit: MIDI 2.0 Channel Voice
+#define UMP_MT_DATA128 0x50000000 // 128-bit: Data (SysEx 8-bit)
+
+// MIDI 2.0 Channel Voice status (bits 23-20 of Word 0)
+#define UMP_STATUS_NOTE_OFF 0x00800000
+#define UMP_STATUS_NOTE_ON 0x00900000
+#define UMP_STATUS_POLY_PRESSURE 0x00A00000
+#define UMP_STATUS_CC 0x00B00000
+#define UMP_STATUS_PROGRAM 0x00C00000
+#define UMP_STATUS_CHAN_PRESSURE 0x00D00000
+#define UMP_STATUS_PITCH_BEND 0x00E00000
+#define UMP_STATUS_PN_MGMT 0x00F00000 // Per-Note Management
+
+// Note Attribute Types (MIDI 2.0 spec, Section 4.2.6)
+#define UMP_ATTR_NONE 0x00
+#define UMP_ATTR_MANUFACTURER 0x01
+#define UMP_ATTR_PROFILE 0x02
+#define UMP_ATTR_PITCH_7_9 0x03 // Pitch 7.9 format
+
+//--------------------------------------------------------------------+
+// MIDI 2.0 UMP Builders - Full Spec Coverage
+//--------------------------------------------------------------------+
+
+// Helper: send a 64-bit UMP (2 words)
+static inline void ump_send_64(uint32_t w0, uint32_t w1) {
+ uint32_t words[2] = { w0, w1 };
+ tud_midi2_ump_write(words, 2);
+}
+
+// Helper: send a 32-bit UMP (1 word)
+static inline void ump_send_32(uint32_t w0) {
+ tud_midi2_ump_write(&w0, 1);
+}
+
+// -- Utility Messages (MT=0x0, 32-bit) --
+
+static inline void ump_jr_timestamp(uint16_t timestamp) {
+ // Word 0: [MT(0x0) | Group(0) | Status(0x0020) | Timestamp(16-bit)]
+ ump_send_32(UMP_MT_UTILITY | 0x00200000 | (uint32_t)timestamp);
+}
+
+// -- MIDI 2.0 Channel Voice: Note On (MT=0x4, 64-bit) --
+// Word 0: [MT(4):Group(4):Status(4):Channel(4):NoteNumber(8):AttrType(8)]
+// Word 1: [Velocity(16):Attribute(16)]
+static inline void ump_note_on(uint8_t group, uint8_t channel,
+ uint8_t pitch, uint16_t velocity,
+ uint8_t attr_type, uint16_t attr_val) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_NOTE_ON | ((uint32_t)(channel & 0x0F) << 16)
+ | ((uint32_t)(pitch & 0x7F) << 8)
+ | (uint32_t)(attr_type & 0xFF);
+ uint32_t w1 = ((uint32_t)(velocity & 0xFFFF) << 16)
+ | (uint32_t)(attr_val & 0xFFFF);
+ ump_send_64(w0, w1);
+}
+
+// -- MIDI 2.0 Channel Voice: Note Off (MT=0x4, 64-bit) --
+static inline void ump_note_off(uint8_t group, uint8_t channel,
+ uint8_t pitch, uint16_t velocity,
+ uint8_t attr_type, uint16_t attr_val) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_NOTE_OFF | ((uint32_t)(channel & 0x0F) << 16)
+ | ((uint32_t)(pitch & 0x7F) << 8)
+ | (uint32_t)(attr_type & 0xFF);
+ uint32_t w1 = ((uint32_t)(velocity & 0xFFFF) << 16)
+ | (uint32_t)(attr_val & 0xFFFF);
+ ump_send_64(w0, w1);
+}
+
+// -- MIDI 2.0 Channel Voice: Control Change (MT=0x4, 64-bit) --
+// Word 0: [MT(4):Group(4):Status(0xB):Channel(4):Index(8):Reserved(8)]
+// Word 1: [Data(32)] -- full 32-bit CC resolution (vs 7-bit MIDI 1.0)
+static inline void ump_cc(uint8_t group, uint8_t channel,
+ uint8_t index, uint32_t value) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_CC | ((uint32_t)(channel & 0x0F) << 16)
+ | ((uint32_t)(index & 0x7F) << 8);
+ ump_send_64(w0, value);
+}
+
+// -- MIDI 2.0 Channel Voice: Program Change (MT=0x4, 64-bit) --
+// Word 0: [MT(4):Group(4):Status(0xC):Channel(4):Reserved(8):OptionFlags(8)]
+// Word 1: [Program(8):Reserved(8):BankMSB(8):BankLSB(8)]
+// OptionFlags bit 0 = Bank Valid
+static inline void ump_program_change(uint8_t group, uint8_t channel,
+ uint8_t program,
+ bool bank_valid, uint8_t bank_msb,
+ uint8_t bank_lsb) {
+ uint8_t flags = bank_valid ? 0x01 : 0x00;
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_PROGRAM | ((uint32_t)(channel & 0x0F) << 16)
+ | (uint32_t)flags;
+ uint32_t w1 = ((uint32_t)program << 24)
+ | ((uint32_t)bank_msb << 8)
+ | (uint32_t)bank_lsb;
+ ump_send_64(w0, w1);
+}
+
+// -- MIDI 2.0 Channel Voice: Pitch Bend (MT=0x4, 64-bit) --
+// Word 0: [MT(4):Group(4):Status(0xE):Channel(4):Reserved(16)]
+// Word 1: [PitchBend(32)] -- full 32-bit (vs 14-bit MIDI 1.0!)
+// 0x80000000 = center, 0x00000000 = min, 0xFFFFFFFF = max
+static inline void ump_pitch_bend(uint8_t group, uint8_t channel,
+ uint32_t value) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_PITCH_BEND | ((uint32_t)(channel & 0x0F) << 16);
+ ump_send_64(w0, value);
+}
+
+// -- MIDI 2.0 Channel Voice: Channel Pressure / Aftertouch (MT=0x4, 64-bit) --
+// Word 0: [MT(4):Group(4):Status(0xD):Channel(4):Reserved(16)]
+// Word 1: [Pressure(32)] -- full 32-bit (vs 7-bit MIDI 1.0)
+static inline void ump_channel_pressure(uint8_t group, uint8_t channel,
+ uint32_t pressure) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_CHAN_PRESSURE | ((uint32_t)(channel & 0x0F) << 16);
+ ump_send_64(w0, pressure);
+}
+
+// -- MIDI 2.0 Channel Voice: Poly Pressure / Per-Note Aftertouch --
+// Word 0: [MT(4):Group(4):Status(0xA):Channel(4):NoteNumber(8):Reserved(8)]
+// Word 1: [Pressure(32)]
+static inline void ump_poly_pressure(uint8_t group, uint8_t channel,
+ uint8_t pitch, uint32_t pressure) {
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_POLY_PRESSURE | ((uint32_t)(channel & 0x0F) << 16)
+ | ((uint32_t)(pitch & 0x7F) << 8);
+ ump_send_64(w0, pressure);
+}
+
+// -- MIDI 2.0 Channel Voice: Per-Note Management (MT=0x4, 64-bit) --
+// Exclusive to MIDI 2.0: controls per-note behavior
+// Word 0: [MT(4):Group(4):Status(0xF):Channel(4):NoteNumber(8):Flags(8)]
+// Word 1: Reserved
+// Flags bit 1 = Reset (S), bit 0 = Detach (D)
+static inline void ump_per_note_mgmt(uint8_t group, uint8_t channel,
+ uint8_t pitch, bool detach,
+ bool reset) {
+ uint8_t flags = (reset ? 0x02 : 0x00) | (detach ? 0x01 : 0x00);
+ uint32_t w0 = UMP_MT_MIDI2_CV | ((uint32_t)(group & 0x0F) << 24)
+ | UMP_STATUS_PN_MGMT | ((uint32_t)(channel & 0x0F) << 16)
+ | ((uint32_t)(pitch & 0x7F) << 8)
+ | (uint32_t)flags;
+ ump_send_64(w0, 0x00000000);
+}
+
+//--------------------------------------------------------------------+
+// MIDI 1.0 Channel Voice Builders (UMP MT 0x2, 32-bit)
+//--------------------------------------------------------------------+
+// Used on Alt 1 when negotiated protocol is MIDI 1.0.
+// Word layout: [MT(0x2) | Group(4b) | Status(8b) | Data1(8b) | Data2(8b)]
+// Status nibbles: 0x8=NoteOff, 0x9=NoteOn, 0xA=PolyPress, 0xB=CC,
+// 0xC=ProgChg, 0xD=ChanPress, 0xE=PitchBend.
+
+static inline void ump_midi1_send(uint8_t group, uint8_t status,
+ uint8_t data1, uint8_t data2) {
+ uint32_t w = UMP_MT_MIDI1_CV
+ | ((uint32_t)(group & 0x0F) << 24)
+ | ((uint32_t)status << 16)
+ | ((uint32_t)data1 << 8)
+ | (uint32_t)data2;
+ ump_send_32(w);
+}
+
+static inline void ump_midi1_note_on(uint8_t group, uint8_t channel,
+ uint8_t note, uint8_t vel7) {
+ ump_midi1_send(group, 0x90 | (channel & 0x0F), note & 0x7F, vel7 & 0x7F);
+}
+
+static inline void ump_midi1_note_off(uint8_t group, uint8_t channel,
+ uint8_t note, uint8_t vel7) {
+ ump_midi1_send(group, 0x80 | (channel & 0x0F), note & 0x7F, vel7 & 0x7F);
+}
+
+static inline void ump_midi1_cc(uint8_t group, uint8_t channel,
+ uint8_t cc, uint8_t val7) {
+ ump_midi1_send(group, 0xB0 | (channel & 0x0F), cc & 0x7F, val7 & 0x7F);
+}
+
+static inline void ump_midi1_program(uint8_t group, uint8_t channel,
+ uint8_t program) {
+ ump_midi1_send(group, 0xC0 | (channel & 0x0F), program & 0x7F, 0);
+}
+
+static inline void ump_midi1_pitch_bend(uint8_t group, uint8_t channel,
+ uint16_t value14) {
+ // 14-bit pitch bend: LSB first, then MSB. Center = 0x2000.
+ ump_midi1_send(group, 0xE0 | (channel & 0x0F),
+ (uint8_t)(value14 & 0x7F),
+ (uint8_t)((value14 >> 7) & 0x7F));
+}
+
+static inline void ump_midi1_channel_pressure(uint8_t group, uint8_t channel,
+ uint8_t val7) {
+ ump_midi1_send(group, 0xD0 | (channel & 0x0F), val7 & 0x7F, 0);
+}
+
+static inline void ump_midi1_poly_pressure(uint8_t group, uint8_t channel,
+ uint8_t note, uint8_t val7) {
+ ump_midi1_send(group, 0xA0 | (channel & 0x0F), note & 0x7F, val7 & 0x7F);
+}
+
+//--------------------------------------------------------------------+
+// USB-MIDI 1.0 32-bit Event Packet Builders (Alt 0 transport)
+//--------------------------------------------------------------------+
+// Used on Alt 0 (USB-MIDI 1.0). Each packet is 4 raw bytes:
+// [(Cable << 4) | CIN] [Status] [Data1] [Data2]
+// CIN = Code Index Number. See USB-MIDI 1.0 spec Section 4.
+
+static inline void midi1_pkt_send(uint8_t cable, uint8_t cin,
+ uint8_t status, uint8_t data1,
+ uint8_t data2) {
+ uint8_t packet[4] = {
+ (uint8_t)(((cable & 0x0F) << 4) | (cin & 0x0F)),
+ status, data1, data2
+ };
+ (void) tud_midi2_packet_write(packet, 1);
+}
+
+static inline void midi1_pkt_note_on(uint8_t cable, uint8_t channel,
+ uint8_t note, uint8_t vel7) {
+ midi1_pkt_send(cable, 0x9, 0x90 | (channel & 0x0F),
+ note & 0x7F, vel7 & 0x7F);
+}
+
+static inline void midi1_pkt_note_off(uint8_t cable, uint8_t channel,
+ uint8_t note, uint8_t vel7) {
+ midi1_pkt_send(cable, 0x8, 0x80 | (channel & 0x0F),
+ note & 0x7F, vel7 & 0x7F);
+}
+
+static inline void midi1_pkt_cc(uint8_t cable, uint8_t channel,
+ uint8_t cc, uint8_t val7) {
+ midi1_pkt_send(cable, 0xB, 0xB0 | (channel & 0x0F),
+ cc & 0x7F, val7 & 0x7F);
+}
+
+static inline void midi1_pkt_program(uint8_t cable, uint8_t channel,
+ uint8_t program) {
+ midi1_pkt_send(cable, 0xC, 0xC0 | (channel & 0x0F),
+ program & 0x7F, 0);
+}
+
+static inline void midi1_pkt_pitch_bend(uint8_t cable, uint8_t channel,
+ uint16_t value14) {
+ midi1_pkt_send(cable, 0xE, 0xE0 | (channel & 0x0F),
+ (uint8_t)(value14 & 0x7F),
+ (uint8_t)((value14 >> 7) & 0x7F));
+}
+
+static inline void midi1_pkt_channel_pressure(uint8_t cable, uint8_t channel,
+ uint8_t val7) {
+ midi1_pkt_send(cable, 0xD, 0xD0 | (channel & 0x0F), val7 & 0x7F, 0);
+}
+
+static inline void midi1_pkt_poly_pressure(uint8_t cable, uint8_t channel,
+ uint8_t note, uint8_t val7) {
+ midi1_pkt_send(cable, 0xA, 0xA0 | (channel & 0x0F),
+ note & 0x7F, val7 & 0x7F);
+}
+
+//--------------------------------------------------------------------+
+// Scaling Helpers (MIDI 2.0 ↔ MIDI 1.0)
+//--------------------------------------------------------------------+
+
+static inline uint8_t scale_vel16_to_vel7(uint16_t v16) { return (uint8_t)(v16 >> 9); }
+static inline uint8_t scale_val32_to_val7(uint32_t v32) { return (uint8_t)(v32 >> 25); }
+static inline uint16_t scale_pb32_to_pb14(uint32_t pb32) { return (uint16_t)(pb32 >> 18); }
+
+//--------------------------------------------------------------------+
+// Dispatch Layer - Transport + Protocol Fallback
+//--------------------------------------------------------------------+
+// Follows the same idea as the UAC examples (`tud_descriptor_configuration_cb`
+// returning UAC1 or UAC2 based on bus speed): pick the path that matches the
+// state the host put us in. Here the decision is made per message because
+// MIDI 2.0 advertises both alts in a single config descriptor; the host
+// selects via SetInterface and UMP Stream protocol negotiation.
+
+static void send_note_on(uint8_t grp, uint8_t ch, uint8_t note, uint16_t vel16) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_note_on(grp, ch, note, scale_vel16_to_vel7(vel16));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_note_on(grp, ch, note, scale_vel16_to_vel7(vel16));
+ } else {
+ ump_note_on(grp, ch, note, vel16, UMP_ATTR_NONE, 0);
+ }
+}
+
+static void send_note_off(uint8_t grp, uint8_t ch, uint8_t note, uint16_t vel16) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_note_off(grp, ch, note, scale_vel16_to_vel7(vel16));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_note_off(grp, ch, note, scale_vel16_to_vel7(vel16));
+ } else {
+ ump_note_off(grp, ch, note, vel16, UMP_ATTR_NONE, 0);
+ }
+}
+
+static void send_cc(uint8_t grp, uint8_t ch, uint8_t cc, uint32_t val32) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_cc(grp, ch, cc, scale_val32_to_val7(val32));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_cc(grp, ch, cc, scale_val32_to_val7(val32));
+ } else {
+ ump_cc(grp, ch, cc, val32);
+ }
+}
+
+static void send_program_change(uint8_t grp, uint8_t ch, uint8_t program,
+ bool with_bank, uint8_t bank_msb,
+ uint8_t bank_lsb) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ if (with_bank) {
+ midi1_pkt_cc(grp, ch, 0x00, bank_msb);
+ midi1_pkt_cc(grp, ch, 0x20, bank_lsb);
+ }
+ midi1_pkt_program(grp, ch, program);
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ if (with_bank) {
+ ump_midi1_cc(grp, ch, 0x00, bank_msb);
+ ump_midi1_cc(grp, ch, 0x20, bank_lsb);
+ }
+ ump_midi1_program(grp, ch, program);
+ } else {
+ ump_program_change(grp, ch, program, with_bank, bank_msb, bank_lsb);
+ }
+}
+
+static void send_pitch_bend(uint8_t grp, uint8_t ch, uint32_t pb32) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_pitch_bend(grp, ch, scale_pb32_to_pb14(pb32));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_pitch_bend(grp, ch, scale_pb32_to_pb14(pb32));
+ } else {
+ ump_pitch_bend(grp, ch, pb32);
+ }
+}
+
+static void send_channel_pressure(uint8_t grp, uint8_t ch, uint32_t val32) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_channel_pressure(grp, ch, scale_val32_to_val7(val32));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_channel_pressure(grp, ch, scale_val32_to_val7(val32));
+ } else {
+ ump_channel_pressure(grp, ch, val32);
+ }
+}
+
+static void send_poly_pressure(uint8_t grp, uint8_t ch, uint8_t note,
+ uint32_t val32) {
+ uint8_t alt = tud_midi2_alt_setting();
+ if (alt == 0) {
+ midi1_pkt_poly_pressure(grp, ch, note, scale_val32_to_val7(val32));
+ } else if (tud_midi2_protocol() == MIDI_PROTOCOL_MIDI1) {
+ ump_midi1_poly_pressure(grp, ch, note, scale_val32_to_val7(val32));
+ } else {
+ ump_poly_pressure(grp, ch, note, val32);
+ }
+}
+
+//--------------------------------------------------------------------+
+// Song Data
+//--------------------------------------------------------------------+
+
+// Extended note event with MIDI 2.0 expression data
+typedef struct {
+ uint8_t pitch; // MIDI pitch (0-127, 0=rest)
+ uint16_t duration_ms; // Duration in ms
+ uint16_t velocity; // 16-bit velocity (MIDI 2.0)
+ uint32_t pressure; // 32-bit aftertouch (0 = none)
+ int16_t bend_cents; // Pitch bend in cents (0 = none, for vibrato/ornaments)
+} midi2_note_t;
+
+// 16-bit velocity (MIDI 2.0): values that have NO 7-bit equivalent.
+// MIDI 1.0 can only express 128 levels (0x0000, 0x0200, 0x0400 ... 0xFE00).
+// These use the full 16-bit range to prove genuine MIDI 2.0 resolution.
+#define V_PPP 0x0A3D // 2621 - between MIDI1 vel 5 and 6
+#define V_PP 0x1C71 // 7281 - between MIDI1 vel 14 and 15
+#define V_P 0x3219 // 12825 - between MIDI1 vel 24 and 25
+#define V_MP 0x4F5C // 20316 - between MIDI1 vel 39 and 40
+#define V_MF 0x6E93 // 28307 - between MIDI1 vel 55 and 56
+#define V_F 0x8DA5 // 36261 - between MIDI1 vel 70 and 71
+#define V_FF 0xAC37 // 44087 - between MIDI1 vel 85 and 86
+#define V_FFF 0xDEB8 // 57016 - between MIDI1 vel 111 and 112
+
+// Twinkle Twinkle Little Star - Traditional
+// Tempo: 120 BPM (500ms per quarter note)
+// Key: C major, 4/4
+// Demonstrates all MIDI 2.0 Channel Voice features:
+// 16-bit velocity, 32-bit CC, 32-bit pitch bend,
+// 32-bit channel pressure, per-note poly pressure,
+// per-note management, program change with bank select,
+// JR timestamps
+static const midi2_note_t song_data[] = {
+ // Phrase 1: "Twin-kle twin-kle lit-tle star" (C C G G A A G-)
+ // Crescendo pp -> mp, gentle entry
+ { .pitch = 60, .duration_ms = 500, .velocity = V_PP, .pressure = 0, .bend_cents = 0 }, // C4
+ { .pitch = 60, .duration_ms = 500, .velocity = V_P, .pressure = 0, .bend_cents = 0 }, // C4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 69, .duration_ms = 500, .velocity = V_MF, .pressure = 0x1A3D7E5F, .bend_cents = 0 }, // A4 (32-bit pressure)
+ { .pitch = 69, .duration_ms = 500, .velocity = V_MF, .pressure = 0x2B851EB9, .bend_cents = 0 }, // A4 (pressure swell)
+ { .pitch = 67, .duration_ms = 1000,.velocity = V_MF, .pressure = 0x3C6EF373, .bend_cents = 7 }, // G4 (half, bend 7 cents)
+
+ // Phrase 2: "How I won-der what you are" (F F E E D D C-)
+ // mf, sustained
+ { .pitch = 65, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // F4
+ { .pitch = 65, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // F4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0x1E4C2B7A, .bend_cents = 0 }, // E4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0x2D5A8FC1, .bend_cents = 0 }, // E4 (aftertouch swell)
+ { .pitch = 62, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // D4
+ { .pitch = 62, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // D4
+ { .pitch = 60, .duration_ms = 1000,.velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // C4 (half, resolve)
+
+ // Phrase 3: "Up a-bove the world so high" (G G F F E E D-)
+ // f, building intensity
+ { .pitch = 67, .duration_ms = 500, .velocity = V_F, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_F, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 65, .duration_ms = 500, .velocity = V_F, .pressure = 0x2F8A4E13, .bend_cents = 0 }, // F4
+ { .pitch = 65, .duration_ms = 500, .velocity = V_MF, .pressure = 0x41B2C9D7, .bend_cents = 0 }, // F4 (triggers poly pressure)
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // E4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // E4
+ { .pitch = 62, .duration_ms = 1000,.velocity = V_MF, .pressure = 0x537DC2A6, .bend_cents = 13 }, // D4 (half, vibrato 13 cents)
+
+ // Phrase 4: "Like a dia-mond in the sky" (G G F F E E D-)
+ // ff, expressive peak
+ { .pitch = 67, .duration_ms = 500, .velocity = V_FF, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_FF, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 65, .duration_ms = 500, .velocity = V_F, .pressure = 0x44E7B8D2, .bend_cents = 0 }, // F4 (triggers poly pressure)
+ { .pitch = 65, .duration_ms = 500, .velocity = V_F, .pressure = 0x56A3F14B, .bend_cents = 0 }, // F4 (triggers poly pressure)
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0x2C8E1F5A, .bend_cents = 0 }, // E4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_MF, .pressure = 0x1D73A4E8, .bend_cents = 0 }, // E4
+ { .pitch = 62, .duration_ms = 1000,.velocity = V_MF, .pressure = 0x63F5B17D, .bend_cents = 19 }, // D4 (half, vibrato 19 cents)
+
+ // Phrase 5: "Twin-kle twin-kle lit-tle star" (C C G G A A G-)
+ // Diminuendo mf -> mp
+ { .pitch = 60, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // C4
+ { .pitch = 60, .duration_ms = 500, .velocity = V_MF, .pressure = 0, .bend_cents = 0 }, // C4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 67, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // G4
+ { .pitch = 69, .duration_ms = 500, .velocity = V_MP, .pressure = 0x1B4F6D83, .bend_cents = 0 }, // A4
+ { .pitch = 69, .duration_ms = 500, .velocity = V_P, .pressure = 0x0E29C5A1, .bend_cents = 0 }, // A4
+ { .pitch = 67, .duration_ms = 1000,.velocity = V_P, .pressure = 0x2A6D3B9E, .bend_cents = 5 }, // G4 (half, gentle bend 5 cents)
+
+ // Phrase 6: "How I won-der what you are" (F F E E D D C-)
+ // Dying away mp -> ppp
+ { .pitch = 65, .duration_ms = 500, .velocity = V_MP, .pressure = 0, .bend_cents = 0 }, // F4
+ { .pitch = 65, .duration_ms = 500, .velocity = V_P, .pressure = 0, .bend_cents = 0 }, // F4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_P, .pressure = 0, .bend_cents = 0 }, // E4
+ { .pitch = 64, .duration_ms = 500, .velocity = V_PP, .pressure = 0, .bend_cents = 0 }, // E4
+ { .pitch = 62, .duration_ms = 500, .velocity = V_PP, .pressure = 0, .bend_cents = 0 }, // D4
+ { .pitch = 62, .duration_ms = 500, .velocity = V_PPP, .pressure = 0, .bend_cents = 0 }, // D4
+ { .pitch = 60, .duration_ms = 2000,.velocity = V_PPP, .pressure = 0x07A1E3C9, .bend_cents = 0 }, // C4 (fermata)
+
+ // Silence before loop
+ { .pitch = 0, .duration_ms = 1000,.velocity = 0, .pressure = 0, .bend_cents = 0 },
+
+ // End marker
+ { .pitch = 0, .duration_ms = 0, .velocity = 0, .pressure = 0, .bend_cents = 0 },
+};
+
+#define SONG_LENGTH (sizeof(song_data) / sizeof(midi2_note_t))
+
+//--------------------------------------------------------------------+
+// Song Playback State Machine
+//--------------------------------------------------------------------+
+
+typedef struct {
+ uint32_t current_note_idx;
+ uint32_t note_start_ms;
+ uint8_t active_pitch;
+ bool note_is_active;
+ bool setup_sent; // Initial setup (Program Change, CC) sent?
+ uint32_t loop_count;
+} song_state_t;
+
+static song_state_t song = { 0 };
+
+// Forward declarations
+void update_song_playback(uint32_t now_ms);
+void send_initial_setup(void);
+
+//--------------------------------------------------------------------+
+// MIDI 2.0 Device Callbacks (override weak stubs from middleware)
+//--------------------------------------------------------------------+
+
+void tud_midi2_rx_cb(uint8_t itf) {
+ // Drain the RX FIFO in a loop until empty. Leaving words in the FIFO
+ // across callbacks can prevent subsequent bulk OUT transfers from landing.
+ uint32_t words[8];
+ uint32_t n;
+ while ((n = tud_midi2_n_ump_read(itf, words, TU_ARRAY_SIZE(words))) > 0) {
+ (void) n;
+ }
+}
+
+// Reset playback state and re-send setup when host switches alt setting or
+// renegotiates the UMP Stream protocol.
+void tud_midi2_set_itf_cb(uint8_t itf, uint8_t alt) {
+ (void)itf;
+ song.setup_sent = false;
+ printf("[ALT] Host selected alt=%u\r\n", (unsigned)alt);
+}
+
+//--------------------------------------------------------------------+
+// Initial Setup - Program Change, CC, Per-Note Management
+//--------------------------------------------------------------------+
+
+void send_initial_setup(void) {
+ // JR Timestamp is UMP-only (Utility MT 0x0); skipped on Alt 0 transport.
+ if (tud_midi2_alt_setting() == 1) ump_jr_timestamp(0x0001);
+
+ send_program_change(0, 0, 0, true, 0, 0);
+ send_cc(0, 0, 7, 0xCCCCCCCC); // Volume 80%
+ send_cc(0, 0, 11, 0xFFFFFFFF); // Expression 100%
+ send_cc(0, 0, 64, 0x00000000); // Sustain off
+ send_cc(0, 0, 1, 0x20000000); // Modulation
+ send_cc(0, 0, 10, 0x80000000); // Pan center
+
+ // Per-Note Management is MIDI 2.0 exclusive (MT 0x4 status 0xF).
+ // Skipped when the active path falls back to MIDI 1.0 in any form.
+ if (tud_midi2_alt_setting() == 1 &&
+ tud_midi2_protocol() == MIDI_PROTOCOL_MIDI2) {
+ ump_per_note_mgmt(0, 0, 0, false, true);
+ }
+
+ send_pitch_bend(0, 0, 0x80000000); // Center
+ send_channel_pressure(0, 0, 0x00000000);
+
+ printf("[SETUP] Piano | Vol 80%% | alt=%u proto=%u\r\n",
+ (unsigned)tud_midi2_alt_setting(),
+ (unsigned)tud_midi2_protocol());
+}
+
+//--------------------------------------------------------------------+
+// Pitch Bend Conversion: cents to 32-bit value
+//--------------------------------------------------------------------+
+
+// Convert pitch bend in cents (-200 to +200) to 32-bit UMP value
+// Center = 0x80000000, range = +/- 2 semitones (200 cents)
+static inline uint32_t cents_to_pitch_bend(int16_t cents) {
+ if (cents == 0) return 0x80000000;
+ // Scale: 200 cents = full range (0x7FFFFFFF deviation from center)
+ int32_t offset = (int32_t)(((int64_t)cents * 0x7FFFFFFF) / 200);
+ return (uint32_t)((int32_t)0x80000000 + offset);
+}
+
+//--------------------------------------------------------------------+
+// Song Playback Logic - Full MIDI 2.0 Expression
+//--------------------------------------------------------------------+
+
+void update_song_playback(uint32_t now_ms) {
+ const midi2_note_t *current = &song_data[song.current_note_idx];
+
+ if (!song.setup_sent) {
+ send_initial_setup();
+ song.setup_sent = true;
+ song.note_start_ms = now_ms;
+ }
+
+ // Note duration elapsed: send Note Off, advance
+ if (song.note_is_active && (now_ms - song.note_start_ms) >= current->duration_ms) {
+ if (song.active_pitch > 0) {
+ if (current->bend_cents != 0) send_pitch_bend(0, 0, 0x80000000);
+ if (current->pressure > 0) send_channel_pressure(0, 0, 0x00000000);
+ send_note_off(0, 0, song.active_pitch, V_P);
+ }
+
+ song.note_is_active = false;
+ song.current_note_idx++;
+
+ if (song.current_note_idx >= SONG_LENGTH) {
+ song.current_note_idx = 0;
+ song.setup_sent = false;
+ song.loop_count++;
+ printf("\r\n=== Loop %lu ===\r\n", (unsigned long)song.loop_count);
+ }
+
+ song.note_start_ms = now_ms;
+ }
+
+ // Start next note
+ if (!song.note_is_active && song.current_note_idx < SONG_LENGTH) {
+ const midi2_note_t *next = &song_data[song.current_note_idx];
+
+ if (next->duration_ms == 0) {
+ song.current_note_idx = 0;
+ song.setup_sent = false;
+ song.loop_count++;
+ printf("\r\n=== Loop %lu ===\r\n", (unsigned long)song.loop_count);
+ return;
+ }
+
+ if (next->pitch > 0) {
+ // JR Timestamp is UMP-only; skip on Alt 0 transport.
+ if (tud_midi2_alt_setting() == 1) {
+ ump_jr_timestamp((uint16_t)(now_ms & 0xFFFF));
+ }
+ if (next->bend_cents != 0) {
+ send_pitch_bend(0, 0, cents_to_pitch_bend(next->bend_cents));
+ }
+ send_note_on(0, 0, next->pitch, next->velocity);
+ if (next->pressure > 0) {
+ send_channel_pressure(0, 0, next->pressure);
+ }
+ if (next->pressure > 0x40000000 && next->duration_ms > 500) {
+ send_poly_pressure(0, 0, next->pitch, next->pressure);
+ }
+
+ song.active_pitch = next->pitch;
+ song.note_is_active = true;
+ }
+
+ // Rest: honor duration
+ if (!song.note_is_active) {
+ song.active_pitch = 0;
+ song.note_is_active = true;
+ song.note_start_ms = now_ms;
+ }
+ }
+}
+
+//--------------------------------------------------------------------+
+// Main
+//--------------------------------------------------------------------+
+
+int main(void) {
+ board_init();
+ printf("\r\n");
+ printf("===========================================\r\n");
+ printf(" TinyUSB MIDI 2.0 Device\r\n");
+ printf("===========================================\r\n");
+ printf("Tempo: 120 BPM | Song: %u notes\r\n", (unsigned)SONG_LENGTH);
+ printf("Transport + protocol fallback:\r\n");
+ printf(" Alt 0 -> USB-MIDI 1.0 32-bit Event Packets (packet_write)\r\n");
+ printf(" Alt 1 + MIDI1 -> UMP MT 0x2 MIDI 1.0 Channel Voice (ump_write)\r\n");
+ printf(" Alt 1 + MIDI2 -> UMP MT 0x4 MIDI 2.0 Channel Voice (ump_write)\r\n");
+ printf("Status: Initializing...\r\n");
+
+ tusb_rhport_init_t dev_init = {.role = TUSB_ROLE_DEVICE, .speed = TUSB_SPEED_AUTO};
+ tusb_init(BOARD_TUD_RHPORT, &dev_init);
+
+ board_init_after_tusb();
+ board_led_write(true);
+
+ uint32_t last_report_ms = 0;
+
+ while (1) {
+ tud_task();
+
+ uint32_t now_ms = tusb_time_millis_api();
+
+ if (tud_midi2_mounted()) {
+ update_song_playback(now_ms);
+ board_led_write(song.active_pitch > 0);
+ } else {
+ board_led_write((now_ms / 500) & 1);
+ }
+
+ // Status report every 10 seconds
+ if (now_ms - last_report_ms > 10000) {
+ last_report_ms = now_ms;
+ if (tud_midi2_mounted()) {
+ printf("[%lums] Playing idx %lu/%u loop %lu\r\n",
+ (unsigned long)now_ms,
+ (unsigned long)song.current_note_idx,
+ (unsigned)SONG_LENGTH,
+ (unsigned long)song.loop_count);
+ } else {
+ printf("[%lums] Waiting for host...\r\n", (unsigned long)now_ms);
+ }
+ }
+ }
+}
diff --git a/examples/device/midi2_device/src/tusb_config.h b/examples/device/midi2_device/src/tusb_config.h
new file mode 100644
index 000000000..1ada0015f
--- /dev/null
+++ b/examples/device/midi2_device/src/tusb_config.h
@@ -0,0 +1,88 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef TUSB_CONFIG_H_
+#define TUSB_CONFIG_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Board Specific Configuration
+//--------------------------------------------------------------------+
+
+#ifndef BOARD_TUD_RHPORT
+#define BOARD_TUD_RHPORT 0
+#endif
+
+#ifndef BOARD_TUD_MAX_SPEED
+#define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+#endif
+
+//--------------------------------------------------------------------
+// COMMON CONFIGURATION
+//--------------------------------------------------------------------
+
+#ifndef CFG_TUSB_MCU
+#error CFG_TUSB_MCU must be defined
+#endif
+
+#ifndef CFG_TUSB_OS
+#define CFG_TUSB_OS OPT_OS_NONE
+#endif
+
+#ifndef CFG_TUSB_DEBUG
+#define CFG_TUSB_DEBUG 0
+#endif
+
+// Enable Device stack
+#define CFG_TUD_ENABLED 1
+
+#define CFG_TUD_MAX_SPEED BOARD_TUD_MAX_SPEED
+
+#ifndef CFG_TUSB_MEM_SECTION
+#define CFG_TUSB_MEM_SECTION
+#endif
+
+#ifndef CFG_TUSB_MEM_ALIGN
+#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
+#endif
+
+//--------------------------------------------------------------------
+// DEVICE CONFIGURATION
+//--------------------------------------------------------------------
+
+#ifndef CFG_TUD_ENDPOINT0_SIZE
+#define CFG_TUD_ENDPOINT0_SIZE 64
+#endif
+
+//------------- CLASS -------------//
+#define CFG_TUD_MIDI2 1
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* TUSB_CONFIG_H_ */
diff --git a/examples/device/midi2_device/src/usb_descriptors.c b/examples/device/midi2_device/src/usb_descriptors.c
new file mode 100644
index 000000000..f035f9c48
--- /dev/null
+++ b/examples/device/midi2_device/src/usb_descriptors.c
@@ -0,0 +1,146 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <string.h>
+#include "bsp/board_api.h"
+#include "tusb.h"
+#include "class/audio/audio.h"
+#include "class/midi/midi.h"
+
+//--------------------------------------------------------------------+
+// Device Descriptors
+//--------------------------------------------------------------------+
+
+static tusb_desc_device_t const desc_device = {
+ .bLength = sizeof(tusb_desc_device_t),
+ .bDescriptorType = TUSB_DESC_DEVICE,
+ .bcdUSB = 0x0200,
+ .bDeviceClass = 0x00,
+ .bDeviceSubClass = 0x00,
+ .bDeviceProtocol = 0x00,
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+
+ .idVendor = 0xcafe,
+ .idProduct = 0x4062, // MIDI 2.0 Device
+ .bcdDevice = 0x0100,
+
+ .iManufacturer = 0x01,
+ .iProduct = 0x02,
+ .iSerialNumber = 0x03,
+
+ .bNumConfigurations = 0x01
+};
+
+uint8_t const * tud_descriptor_device_cb(void) {
+ return (uint8_t const *) &desc_device;
+}
+
+//--------------------------------------------------------------------+
+// Configuration Descriptor - MIDI 2.0
+//--------------------------------------------------------------------+
+
+enum {
+ ITF_NUM_MIDI2 = 0, // Audio Control interface
+ ITF_NUM_MIDI2_STREAMING, // MIDI Streaming interface (auto-created by TUD_MIDI2_DESCRIPTOR)
+ ITF_NUM_TOTAL
+};
+
+#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MIDI2_DESC_LEN)
+
+// Endpoint addresses
+#define EPNUM_MIDI2_OUT 0x01
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+#define EPNUM_MIDI2_IN 0x82
+#else
+#define EPNUM_MIDI2_IN 0x81
+#endif
+
+static uint8_t const desc_fs_configuration[] = {
+ // Config number, interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+
+ // MIDI 2.0 Interface
+ TUD_MIDI2_DESCRIPTOR(ITF_NUM_MIDI2, 0, EPNUM_MIDI2_OUT, EPNUM_MIDI2_IN, 64)
+};
+
+uint8_t const * tud_descriptor_configuration_cb(uint8_t index) {
+ (void) index;
+ return desc_fs_configuration;
+}
+
+//--------------------------------------------------------------------+
+// String Descriptors
+//--------------------------------------------------------------------+
+
+enum {
+ STRID_LANGID = 0,
+ STRID_MANUFACTURER = 1,
+ STRID_PRODUCT = 2,
+ STRID_SERIAL = 3,
+};
+
+static char const *string_desc_arr[] = {
+ (const char[]) { 0x09, 0x04 }, // 0: Language
+ "TinyUSB", // 1: Manufacturer
+ "TinyUSB MIDI 2.0", // 2: Product
+ NULL, // 3: Serial
+};
+
+static uint16_t _desc_str[32 + 1];
+
+uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
+ (void) langid;
+ size_t chr_count;
+
+ switch ( index ) {
+ case STRID_LANGID:
+ memcpy(&_desc_str[1], string_desc_arr[0], 2);
+ chr_count = 1;
+ break;
+
+ case STRID_SERIAL:
+ chr_count = board_usb_get_serial(_desc_str + 1, 32);
+ break;
+
+ default:
+ if (!(index < sizeof(string_desc_arr) / sizeof(string_desc_arr[0]))) {
+ return NULL;
+ }
+
+ const char *str = string_desc_arr[index];
+ chr_count = strlen(str);
+ const size_t max_count = sizeof(_desc_str) / sizeof(_desc_str[0]) - 1;
+ if ( chr_count > max_count ) {
+ chr_count = max_count;
+ }
+
+ for ( size_t i = 0; i < chr_count; i++ ) {
+ _desc_str[1 + i] = str[i];
+ }
+ break;
+ }
+
+ _desc_str[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * chr_count + 2));
+ return _desc_str;
+}
diff --git a/examples/device/midi_test/skip.txt b/examples/device/midi_test/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/midi_test/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/midi_test/src/usb_descriptors.c b/examples/device/midi_test/src/usb_descriptors.c
index e969f33a3..99c798ce1 100644
--- a/examples/device/midi_test/src/usb_descriptors.c
+++ b/examples/device/midi_test/src/usb_descriptors.c
@@ -87,7 +87,7 @@ enum {
#define EPNUM_MIDI_OUT 0x02
#define EPNUM_MIDI_IN 0x81
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_MIDI_OUT 0x01
diff --git a/examples/device/midi_test_freertos/skip.txt b/examples/device/midi_test_freertos/skip.txt
index d2ee8d636..97d8e168b 100644
--- a/examples/device/midi_test_freertos/skip.txt
+++ b/examples/device/midi_test_freertos/skip.txt
@@ -2,6 +2,7 @@ mcu:CH32F20X
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:CXD56
mcu:F1C100S
mcu:GD32VF103
diff --git a/examples/device/midi_test_freertos/src/usb_descriptors.c b/examples/device/midi_test_freertos/src/usb_descriptors.c
index e969f33a3..99c798ce1 100644
--- a/examples/device/midi_test_freertos/src/usb_descriptors.c
+++ b/examples/device/midi_test_freertos/src/usb_descriptors.c
@@ -87,7 +87,7 @@ enum {
#define EPNUM_MIDI_OUT 0x02
#define EPNUM_MIDI_IN 0x81
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_MIDI_OUT 0x01
diff --git a/examples/device/msc_dual_lun/src/main.c b/examples/device/msc_dual_lun/src/main.c
index a4ade6f9b..1d764f12c 100644
--- a/examples/device/msc_dual_lun/src/main.c
+++ b/examples/device/msc_dual_lun/src/main.c
@@ -71,7 +71,7 @@ static void usb_device_init(void) {
board_init_after_tusb();
}
-#if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO
+#if CFG_TUSB_OS_HAS_SCHEDULER
static void usb_device_task(RTOS_PARAM param) {
(void) param;
usb_device_init();
diff --git a/examples/device/msc_dual_lun/src/usb_descriptors.c b/examples/device/msc_dual_lun/src/usb_descriptors.c
index f73935ee0..b328cf17f 100644
--- a/examples/device/msc_dual_lun/src/usb_descriptors.c
+++ b/examples/device/msc_dual_lun/src/usb_descriptors.c
@@ -91,11 +91,17 @@ enum
#define EPNUM_MSC_OUT 0x02
#define EPNUM_MSC_IN 0x81
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_MSC_OUT 0x01
- #define EPNUM_MSC_IN 0x82
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_MSC_OUT 0x08
+ #define EPNUM_MSC_IN 0x89
+ #else
+ #define EPNUM_MSC_OUT 0x01
+ #define EPNUM_MSC_IN 0x82
+ #endif
#else
#define EPNUM_MSC_OUT 0x01
diff --git a/examples/device/mtp/src/mtp_fs_example.c b/examples/device/mtp/src/mtp_fs_example.c
index 09697693e..b7d062c64 100644
--- a/examples/device/mtp/src/mtp_fs_example.c
+++ b/examples/device/mtp/src/mtp_fs_example.c
@@ -143,6 +143,7 @@ static int32_t fs_get_device_properties(tud_mtp_cb_data_t* cb_data);
static int32_t fs_get_object_handles(tud_mtp_cb_data_t* cb_data);
static int32_t fs_get_object_info(tud_mtp_cb_data_t* cb_data);
static int32_t fs_get_object(tud_mtp_cb_data_t* cb_data);
+static int32_t fs_get_partial_object(tud_mtp_cb_data_t* cb_data);
static int32_t fs_delete_object(tud_mtp_cb_data_t* cb_data);
static int32_t fs_send_object_info(tud_mtp_cb_data_t* cb_data);
static int32_t fs_send_object(tud_mtp_cb_data_t* cb_data);
@@ -164,6 +165,7 @@ fs_op_handler_dict_t fs_op_handler_dict[] = {
{ MTP_OP_GET_OBJECT_HANDLES, fs_get_object_handles },
{ MTP_OP_GET_OBJECT_INFO, fs_get_object_info },
{ MTP_OP_GET_OBJECT, fs_get_object },
+ { MTP_OP_GET_PARTIAL_OBJECT, fs_get_partial_object },
{ MTP_OP_DELETE_OBJECT, fs_delete_object },
{ MTP_OP_SEND_OBJECT_INFO, fs_send_object_info },
{ MTP_OP_SEND_OBJECT, fs_send_object },
@@ -330,6 +332,14 @@ int32_t tud_mtp_data_complete_cb(tud_mtp_cb_data_t* cb_data) {
break;
}
+ case MTP_OP_GET_PARTIAL_OBJECT: {
+ // response parameter: actual length of data sent excluding container header
+ const uint32_t len = cb_data->total_xferred_bytes - sizeof(mtp_container_header_t);
+ (void) mtp_container_add_uint32(resp, len);
+ resp->header->code = MTP_RESP_OK;
+ break;
+ }
+
default:
resp->header->code = (cb_data->xfer_result == XFER_RESULT_SUCCESS) ? MTP_RESP_OK : MTP_RESP_GENERAL_ERROR;
break;
@@ -535,6 +545,40 @@ static int32_t fs_get_object(tud_mtp_cb_data_t* cb_data) {
return 0;
}
+static int32_t fs_get_partial_object(tud_mtp_cb_data_t* cb_data) {
+ const mtp_container_command_t* command = cb_data->command_container;
+ mtp_container_info_t* io_container = &cb_data->io_container;
+ const uint32_t obj_handle = command->params[0];
+ const uint32_t req_offset = command->params[1];
+ const uint32_t req_max = command->params[2];
+ const fs_file_t* f = fs_get_file(obj_handle);
+ if (f == NULL) {
+ return MTP_RESP_INVALID_OBJECT_HANDLE;
+ }
+
+ const uint32_t avail = (req_offset >= f->size) ? 0u : (f->size - req_offset);
+ const uint32_t to_send = tu_min32(avail, req_max);
+
+ if (cb_data->phase == MTP_PHASE_COMMAND) {
+ // If file contents is larger than CFG_TUD_MTP_EP_BUFSIZE, data may only partially be added here
+ // the rest will be sent in tud_mtp_data_more_cb
+ (void) mtp_container_add_raw(io_container, f->data + req_offset, to_send);
+ tud_mtp_data_send(io_container);
+ } else if (cb_data->phase == MTP_PHASE_DATA) {
+ // continue sending remaining data: file contents offset is xferred byte minus header size
+ const uint32_t offset = cb_data->total_xferred_bytes - sizeof(mtp_container_header_t);
+ const uint32_t xact_len = tu_min32(to_send - offset, io_container->payload_bytes);
+ if (xact_len > 0) {
+ memcpy(io_container->payload, f->data + offset + req_offset, xact_len);
+ tud_mtp_data_send(io_container);
+ }
+ } else {
+ // nothing to do
+ }
+
+ return 0;
+}
+
static int32_t fs_send_object_info(tud_mtp_cb_data_t* cb_data) {
const mtp_container_command_t* command = cb_data->command_container;
mtp_container_info_t* io_container = &cb_data->io_container;
diff --git a/examples/device/mtp/src/tusb_config.h b/examples/device/mtp/src/tusb_config.h
index 95cc048ee..5224cd79b 100644
--- a/examples/device/mtp/src/tusb_config.h
+++ b/examples/device/mtp/src/tusb_config.h
@@ -106,6 +106,7 @@
MTP_OP_GET_OBJECT_HANDLES, \
MTP_OP_GET_OBJECT_INFO, \
MTP_OP_GET_OBJECT, \
+ MTP_OP_GET_PARTIAL_OBJECT, \
MTP_OP_DELETE_OBJECT, \
MTP_OP_SEND_OBJECT_INFO, \
MTP_OP_SEND_OBJECT, \
diff --git a/examples/device/mtp/src/usb_descriptors.c b/examples/device/mtp/src/usb_descriptors.c
index f0aa3de6b..4c840560e 100644
--- a/examples/device/mtp/src/usb_descriptors.c
+++ b/examples/device/mtp/src/usb_descriptors.c
@@ -94,7 +94,7 @@ enum
#define EPNUM_MTP_OUT 0x02
#define EPNUM_MTP_IN 0x81
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_MTP_EVT 0x81
diff --git a/examples/device/net_lwip_webserver/skip.txt b/examples/device/net_lwip_webserver/skip.txt
index ecb9eb7ec..5e5562087 100644
--- a/examples/device/net_lwip_webserver/skip.txt
+++ b/examples/device/net_lwip_webserver/skip.txt
@@ -19,6 +19,6 @@ board:at_start_f425
board:curiosity_nano
board:frdm_kl25z
# lpc55 has weird error 'ncm_interface' causes a section type conflict with 'ntb_parameters'
-family:lpc55
+#family:lpc55
family:nuc126
family:nuc100_120
diff --git a/examples/device/net_lwip_webserver/src/lwipopts.h b/examples/device/net_lwip_webserver/src/lwipopts.h
index 11686ce2a..350120423 100644
--- a/examples/device/net_lwip_webserver/src/lwipopts.h
+++ b/examples/device/net_lwip_webserver/src/lwipopts.h
@@ -32,6 +32,14 @@
#ifndef LWIPOPTS_H__
#define LWIPOPTS_H__
+// Pulls in tusb_option.h → tusb_config.h, which defines LWIP_HIGH_THROUGHPUT
+// based on the target MCU's SRAM tier.
+#include "tusb_option.h"
+
+#ifndef LWIP_HIGH_THROUGHPUT
+ #define LWIP_HIGH_THROUGHPUT 0
+#endif
+
/* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */
#define NO_SYS 1
#define MEM_ALIGNMENT 4
@@ -49,7 +57,15 @@
#define TCP_MSS (1500 /*mtu*/ - 20 /*iphdr*/ - 20 /*tcphhr*/)
#define TCP_SND_BUF (4 * TCP_MSS)
-#define TCP_WND (4 * TCP_MSS)
+#if LWIP_HIGH_THROUGHPUT
+ #define TCP_WND (8 * TCP_MSS)
+ #define PBUF_POOL_SIZE 8
+ // Must grow in step with TCP_SND_BUF (default MEMP_NUM_TCP_SEG=16 caps TCP_SND_BUF at 4*MSS).
+ #define MEMP_NUM_TCP_SEG 16
+#else
+ #define TCP_WND (4 * TCP_MSS)
+ #define PBUF_POOL_SIZE 4
+#endif
#define ETHARP_SUPPORT_STATIC_ENTRIES 1
@@ -60,8 +76,6 @@
#define LWIP_SINGLE_NETIF 1
#define LWIP_NETIF_LINK_CALLBACK 1
-#define PBUF_POOL_SIZE 4
-
#define HTTPD_USE_CUSTOM_FSDATA 0
#define LWIP_MULTICAST_PING 1
diff --git a/examples/device/net_lwip_webserver/src/tusb_config.h b/examples/device/net_lwip_webserver/src/tusb_config.h
index 3285ea52c..d94a87c99 100644
--- a/examples/device/net_lwip_webserver/src/tusb_config.h
+++ b/examples/device/net_lwip_webserver/src/tusb_config.h
@@ -30,8 +30,6 @@
extern "C" {
#endif
-#include "lwipopts.h"
-
//--------------------------------------------------------------------+
// Board Specific Configuration
//--------------------------------------------------------------------+
@@ -92,32 +90,50 @@ extern "C" {
#define USE_ECM 1
#elif TU_CHECK_MCU(OPT_MCU_STM32F0, OPT_MCU_STM32F1)
#define USE_ECM 1
-#elif TU_CHECK_MCU(OPT_MCU_MAX32690, OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX78002)
- #define USE_ECM 1
#else
#define USE_ECM 0
- #define INCLUDE_IPERF
#endif
#endif
+// MCU SRAM tier — drives the bigger lwIP buffers in lwipopts.h, the larger
+// NCM OUT NTB size below, and whether iperf is built. Small-RAM MCUs
+// (stm32c0/f1/wb, lpc11/13, samd11) keep modest defaults to fit.
+#ifndef LWIP_HIGH_THROUGHPUT
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002) || \
+ TU_CHECK_MCU(OPT_MCU_STM32F2, OPT_MCU_STM32F4, OPT_MCU_STM32F7) || \
+ TU_CHECK_MCU(OPT_MCU_STM32H5, OPT_MCU_STM32H7, OPT_MCU_STM32H7RS) || \
+ TU_CHECK_MCU(OPT_MCU_STM32C5, OPT_MCU_STM32U5, OPT_MCU_STM32N6) || \
+ TU_CHECK_MCU(OPT_MCU_RP2040, OPT_MCU_CH32V307) || \
+ TU_CHECK_MCU(OPT_MCU_MIMXRT1XXX) || \
+ TU_CHECK_MCU(OPT_MCU_NRF5X)
+ #define LWIP_HIGH_THROUGHPUT 1
+ #else
+ #define LWIP_HIGH_THROUGHPUT 0
+ #endif
+#endif
+
+#if LWIP_HIGH_THROUGHPUT && !defined(INCLUDE_IPERF)
+ #define INCLUDE_IPERF
+#endif
+
//--------------------------------------------------------------------
// NCM CLASS CONFIGURATION, SEE "ncm.h" FOR PERFORMANCE TUNING
//--------------------------------------------------------------------
-// Must be >> MTU
-// Can be set to 2048 without impact
-#define CFG_TUD_NCM_IN_NTB_MAX_SIZE (2 * TCP_MSS + 100)
+// CDC-NCM 1.0 Table 6-4 defines 2048 as the minimum required NTB size
+#define CFG_TUD_NCM_IN_NTB_MAX_SIZE 2048
-// Must be >> MTU
-// Can be set to smaller values if wNtbOutMaxDatagrams==1
-#define CFG_TUD_NCM_OUT_NTB_MAX_SIZE (2 * TCP_MSS + 100)
+#if LWIP_HIGH_THROUGHPUT
+ #define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 4096
+#else
+ #define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 2048
+#endif
// Number of NCM transfer blocks for reception side
#ifndef CFG_TUD_NCM_OUT_NTB_N
#define CFG_TUD_NCM_OUT_NTB_N 1
#endif
-// Number of NCM transfer blocks for transmission side
#ifndef CFG_TUD_NCM_IN_NTB_N
#define CFG_TUD_NCM_IN_NTB_N 1
#endif
diff --git a/examples/device/net_lwip_webserver/src/usb_descriptors.c b/examples/device/net_lwip_webserver/src/usb_descriptors.c
index c976cb62b..09090bb92 100644
--- a/examples/device/net_lwip_webserver/src/usb_descriptors.c
+++ b/examples/device/net_lwip_webserver/src/usb_descriptors.c
@@ -65,17 +65,19 @@ enum {
CONFIG_ID_COUNT
};
+#if CFG_TUD_NCM
+#define USB_BCD 0x0201
+#else
+#define USB_BCD 0x0200
+#endif
+
//--------------------------------------------------------------------+
// Device Descriptors
//--------------------------------------------------------------------+
static const tusb_desc_device_t desc_device = {
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
-#if CFG_TUD_NCM
- .bcdUSB = 0x0201,
-#else
- .bcdUSB = 0x0200,
-#endif
+ .bcdUSB = USB_BCD,
// Use Interface Association Descriptor (IAD) device class
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
@@ -121,12 +123,20 @@ const uint8_t *tud_descriptor_device_cb(void) {
#define EPNUM_NET_OUT 0x02
#define EPNUM_NET_IN 0x81
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
-// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+// MCUs that don't support the same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
+
+#if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+// endpoint 8,9 has FIFO of 2048 bytes
+#define EPNUM_NET_NOTIF 0x81
+#define EPNUM_NET_OUT 0x08
+#define EPNUM_NET_IN 0x89
+#else
#define EPNUM_NET_NOTIF 0x81
#define EPNUM_NET_OUT 0x02
#define EPNUM_NET_IN 0x83
+#endif
#else
#define EPNUM_NET_NOTIF 0x81
@@ -136,57 +146,184 @@ const uint8_t *tud_descriptor_device_cb(void) {
#if CFG_TUD_ECM_RNDIS
-static uint8_t const rndis_configuration[] = {
+// full speed configuration
+static uint8_t const rndis_fs_configuration[] = {
// Config number (index+1), interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(CONFIG_ID_RNDIS + 1, ITF_NUM_TOTAL, 0, MAIN_CONFIG_TOTAL_LEN, 0, 100),
// Interface number, string index, EP notification address and size, EP data address (out, in) and size.
TUD_RNDIS_DESCRIPTOR(
- ITF_NUM_CDC, STRID_INTERFACE, EPNUM_NET_NOTIF, 8, EPNUM_NET_OUT, EPNUM_NET_IN, CFG_TUD_NET_ENDPOINT_SIZE),
+ ITF_NUM_CDC, STRID_INTERFACE, EPNUM_NET_NOTIF, 8, EPNUM_NET_OUT, EPNUM_NET_IN, 64),
};
-static const uint8_t ecm_configuration[] = {
+static const uint8_t ecm_fs_configuration[] = {
// Config number (index+1), interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(CONFIG_ID_ECM + 1, ITF_NUM_TOTAL, 0, ALT_CONFIG_TOTAL_LEN, 0, 100),
// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size.
TUD_CDC_ECM_DESCRIPTOR(
ITF_NUM_CDC, STRID_INTERFACE, STRID_MAC, EPNUM_NET_NOTIF, 64, EPNUM_NET_OUT, EPNUM_NET_IN,
- CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU),
+ 64, CFG_TUD_NET_MTU),
};
-#else
+#if TUD_OPT_HIGH_SPEED
+// Per USB specs: high speed capable device must report device_qualifier and other_speed_configuration
-static uint8_t const ncm_configuration[] = {
+// high speed configuration
+static uint8_t const rndis_hs_configuration[] = {
// Config number (index+1), interface count, string index, total length, attribute, power in mA
- TUD_CONFIG_DESCRIPTOR(CONFIG_ID_NCM + 1, ITF_NUM_TOTAL, 0, NCM_CONFIG_TOTAL_LEN, 0, 100),
+ TUD_CONFIG_DESCRIPTOR(CONFIG_ID_RNDIS + 1, ITF_NUM_TOTAL, 0, MAIN_CONFIG_TOTAL_LEN, 0, 100),
+
+ // Interface number, string index, EP notification address and size, EP data address (out, in) and size.
+ TUD_RNDIS_DESCRIPTOR(
+ ITF_NUM_CDC, STRID_INTERFACE, EPNUM_NET_NOTIF, 8, EPNUM_NET_OUT, EPNUM_NET_IN, 512),
+};
+
+static const uint8_t ecm_hs_configuration[] = {
+ // Config number (index+1), interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(CONFIG_ID_ECM + 1, ITF_NUM_TOTAL, 0, ALT_CONFIG_TOTAL_LEN, 0, 100),
// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size.
- TUD_CDC_NCM_DESCRIPTOR(
+ TUD_CDC_ECM_DESCRIPTOR(
ITF_NUM_CDC, STRID_INTERFACE, STRID_MAC, EPNUM_NET_NOTIF, 64, EPNUM_NET_OUT, EPNUM_NET_IN,
- CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU),
+ 512, CFG_TUD_NET_MTU),
+};
+#endif // highspeed
+
+#else
+
+// full speed configuration
+static uint8_t const ncm_fs_configuration[] = {
+ // Config number (index+1), interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(CONFIG_ID_NCM + 1, ITF_NUM_TOTAL, 0, NCM_CONFIG_TOTAL_LEN, 0, 100),
+
+ // Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size, EP notification bInterval, NCM capabilities.
+ TUD_CDC_NCM_DESCRIPTOR(ITF_NUM_CDC, STRID_INTERFACE, STRID_MAC, EPNUM_NET_NOTIF, 64, EPNUM_NET_OUT, EPNUM_NET_IN,
+ 64, CFG_TUD_NET_MTU, 50, (uint8_t)((uint8_t)NCM_NETWORK_CAPS_ETH_FILTER | (uint8_t)NCM_NETWORK_CAPS_NTB_INPUT_SIZE)),
+};
+
+#if TUD_OPT_HIGH_SPEED
+// Per USB specs: high speed capable device must report device_qualifier and other_speed_configuration
+
+// high speed configuration
+// bInterval: FS=50 means 50ms; HS encodes as 2^(n-1) * 125us, so 9 = 2^8 * 125us = 32ms
+static uint8_t const ncm_hs_configuration[] = {
+ // Config number (index+1), interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(CONFIG_ID_NCM + 1, ITF_NUM_TOTAL, 0, NCM_CONFIG_TOTAL_LEN, 0, 100),
+
+ // Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size, EP notification bInterval, NCM capabilities.
+ TUD_CDC_NCM_DESCRIPTOR(ITF_NUM_CDC, STRID_INTERFACE, STRID_MAC, EPNUM_NET_NOTIF, 64, EPNUM_NET_OUT, EPNUM_NET_IN,
+ 512, CFG_TUD_NET_MTU, 9, (uint8_t)((uint8_t)NCM_NETWORK_CAPS_ETH_FILTER | (uint8_t)NCM_NETWORK_CAPS_NTB_INPUT_SIZE)),
};
+#endif // highspeed
#endif
-// Configuration array: RNDIS and CDC-ECM
+// NCM work with all latest OS i.e macos 10.10+, windows 10+, and Linux.
+// For older system Configuration array of RNDIS and CDC-ECM may be needed for better compatibility.
// - Windows only works with RNDIS
// - MacOS only works with CDC-ECM
// - Linux will work on both
-static const uint8_t *const configuration_arr[CONFIG_ID_COUNT] = {
#if CFG_TUD_ECM_RNDIS
- [CONFIG_ID_RNDIS] = rndis_configuration,
- [CONFIG_ID_ECM] = ecm_configuration
+
+static const uint8_t *const configuration_fs_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_RNDIS] = rndis_fs_configuration,
+ [CONFIG_ID_ECM] = ecm_fs_configuration
+};
+
+#if TUD_OPT_HIGH_SPEED
+static const uint8_t *const configuration_hs_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_RNDIS] = rndis_hs_configuration,
+ [CONFIG_ID_ECM] = ecm_hs_configuration
+};
+
+// Size array for each configuration
+static const uint16_t configuration_sz_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_RNDIS] = MAIN_CONFIG_TOTAL_LEN,
+ [CONFIG_ID_ECM] = ALT_CONFIG_TOTAL_LEN
+};
+
+// Scratch buffer for other speed configuration (sized to hold the largest config)
+#define MAX_CONFIG_TOTAL_LEN TU_MAX(MAIN_CONFIG_TOTAL_LEN, ALT_CONFIG_TOTAL_LEN)
+#endif
+
#else
- [CONFIG_ID_NCM] = ncm_configuration
+
+static const uint8_t *const configuration_fs_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_NCM] = ncm_fs_configuration
+};
+
+#if TUD_OPT_HIGH_SPEED
+static const uint8_t *const configuration_hs_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_NCM] = ncm_hs_configuration
+};
+
+// Size array for each configuration
+static const uint16_t configuration_sz_arr[CONFIG_ID_COUNT] = {
+ [CONFIG_ID_NCM] = NCM_CONFIG_TOTAL_LEN
+};
+
+// Scratch buffer for other speed configuration (sized to hold the largest config)
+#define MAX_CONFIG_TOTAL_LEN NCM_CONFIG_TOTAL_LEN
#endif
+
+#endif
+
+#if TUD_OPT_HIGH_SPEED
+static uint8_t desc_other_speed_config[MAX_CONFIG_TOTAL_LEN];
+
+// device qualifier: device descriptor fields that differ at other speed
+static tusb_desc_device_qualifier_t const desc_device_qualifier = {
+ .bLength = sizeof(tusb_desc_device_qualifier_t),
+ .bDescriptorType = TUSB_DESC_DEVICE_QUALIFIER,
+ .bcdUSB = USB_BCD,
+
+ .bDeviceClass = TUSB_CLASS_MISC,
+ .bDeviceSubClass = MISC_SUBCLASS_COMMON,
+ .bDeviceProtocol = MISC_PROTOCOL_IAD,
+
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+ .bNumConfigurations = CONFIG_ID_COUNT,
+ .bReserved = 0x00
};
+// Invoked when received GET DEVICE QUALIFIER DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete.
+// device_qualifier descriptor describes information about a high-speed capable device that would
+// change if the device were operating at the other speed. If not highspeed capable stall this request.
+uint8_t const *tud_descriptor_device_qualifier_cb(void) {
+ return (uint8_t const *) &desc_device_qualifier;
+}
+
+// Invoked when received GET OTHER SPEED CONFIGURATION DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
+// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa
+uint8_t const *tud_descriptor_other_speed_configuration_cb(uint8_t index) {
+ if (index >= CONFIG_ID_COUNT) return NULL;
+
+ // if link speed is high return fullspeed config, and vice versa
+ const uint8_t *const *arr = (tud_speed_get() == TUSB_SPEED_HIGH) ? configuration_fs_arr : configuration_hs_arr;
+
+ // Note: the descriptor type is OTHER_SPEED_CONFIG instead of CONFIG
+ memcpy(desc_other_speed_config, arr[index], configuration_sz_arr[index]);
+ desc_other_speed_config[1] = TUSB_DESC_OTHER_SPEED_CONFIG;
+
+ return desc_other_speed_config;
+}
+
+#endif // highspeed
+
// Invoked when received GET CONFIGURATION DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
const uint8_t *tud_descriptor_configuration_cb(uint8_t index) {
- return (index < CONFIG_ID_COUNT) ? configuration_arr[index] : NULL;
+ if (index >= CONFIG_ID_COUNT) return NULL;
+#if TUD_OPT_HIGH_SPEED
+ // Although we are highspeed, host may be fullspeed.
+ return (tud_speed_get() == TUSB_SPEED_HIGH) ? configuration_hs_arr[index] : configuration_fs_arr[index];
+#else
+ return configuration_fs_arr[index];
+#endif
}
#if CFG_TUD_NCM
diff --git a/examples/device/printer_to_cdc/CMakePresets.json b/examples/device/printer_to_cdc/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/device/printer_to_cdc/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/device/printer_to_cdc/src/usb_descriptors.c b/examples/device/printer_to_cdc/src/usb_descriptors.c
index 30d309ed4..db7bfe97a 100644
--- a/examples/device/printer_to_cdc/src/usb_descriptors.c
+++ b/examples/device/printer_to_cdc/src/usb_descriptors.c
@@ -67,12 +67,21 @@ uint8_t const *tud_descriptor_device_cb(void) {
//--------------------------------------------------------------------+
// Endpoint numbers
-#if defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
- #define EPNUM_CDC_NOTIF 0x81
- #define EPNUM_CDC_OUT 0x02
- #define EPNUM_CDC_IN 0x83
- #define EPNUM_PRINTER_OUT 0x04
- #define EPNUM_PRINTER_IN 0x85
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
+ #define EPNUM_PRINTER_OUT 0x0A
+ #define EPNUM_PRINTER_IN 0x8B
+ #else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x83
+ #define EPNUM_PRINTER_OUT 0x04
+ #define EPNUM_PRINTER_IN 0x85
+ #endif
#else
#define EPNUM_CDC_NOTIF 0x81
#define EPNUM_CDC_OUT 0x02
diff --git a/examples/device/uac2_headset/skip.txt b/examples/device/uac2_headset/skip.txt
index a2a76af0e..db1d5b80b 100644
--- a/examples/device/uac2_headset/skip.txt
+++ b/examples/device/uac2_headset/skip.txt
@@ -6,3 +6,4 @@ mcu:SAME5X
mcu:SAMG
board:stm32l052dap52
family:espressif
+mcu:CH583
diff --git a/examples/device/uac2_headset/src/main.c b/examples/device/uac2_headset/src/main.c
index 0ea63d8f7..c30b31f67 100644
--- a/examples/device/uac2_headset/src/main.c
+++ b/examples/device/uac2_headset/src/main.c
@@ -319,16 +319,16 @@ static bool audio10_get_req_entity(uint8_t rhport, tusb_control_request_t const
#if TUD_OPT_HIGH_SPEED
// Helper for clock get requests
-static bool audio20_clock_get_request(uint8_t rhport, audio20_control_request_t const *request) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
+static bool audio20_clock_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ) {
- if (request->bRequest == AUDIO20_CS_REQ_CUR) {
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
+ if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
TU_LOG1("Clock get current freq %" PRIu32 "\r\n", current_sample_rate);
audio20_control_cur_4_t curf = {(int32_t) tu_htole32(current_sample_rate)};
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &curf, sizeof(curf));
- } else if (request->bRequest == AUDIO20_CS_REQ_RANGE) {
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &curf, sizeof(curf));
+ } else if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_4_n_t(N_SAMPLE_RATES) rangef =
{
.wNumSubRanges = tu_htole16(N_SAMPLE_RATES)};
@@ -340,28 +340,29 @@ static bool audio20_clock_get_request(uint8_t rhport, audio20_control_request_t
TU_LOG1("Range %d (%d, %d, %d)\r\n", i, (int) rangef.subrange[i].bMin, (int) rangef.subrange[i].bMax, (int) rangef.subrange[i].bRes);
}
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &rangef, sizeof(rangef));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &rangef, sizeof(rangef));
}
- } else if (request->bControlSelector == AUDIO20_CS_CTRL_CLK_VALID &&
- request->bRequest == AUDIO20_CS_REQ_CUR) {
+ } else if (ctrl_sel == AUDIO20_CS_CTRL_CLK_VALID &&
+ p_request->bRequest == AUDIO20_CS_REQ_CUR) {
audio20_control_cur_1_t cur_valid = {.bCur = 1};
TU_LOG1("Clock get is valid %u\r\n", cur_valid.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &cur_valid, sizeof(cur_valid));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_valid, sizeof(cur_valid));
}
- TU_LOG1("Clock get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
// Helper for clock set requests
-static bool audio20_clock_set_request(uint8_t rhport, audio20_control_request_t const *request, uint8_t const *buf) {
+static bool audio20_clock_set_request(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t const *buf) {
(void) rhport;
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_4_t));
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
+
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_4_t));
current_sample_rate = (uint32_t) ((audio20_control_cur_4_t const *) buf)->bCur;
@@ -369,93 +370,96 @@ static bool audio20_clock_set_request(uint8_t rhport, audio20_control_request_t
return true;
} else {
- TU_LOG1("Clock set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
// Helper for feature unit get requests
-static bool audio20_feature_unit_get_request(uint8_t rhport, audio20_control_request_t const *request) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT);
+static bool audio20_feature_unit_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE && request->bRequest == AUDIO20_CS_REQ_CUR) {
- audio20_control_cur_1_t mute1 = {.bCur = mute[request->bChannelNumber]};
- TU_LOG1("Get channel %u mute %d\r\n", request->bChannelNumber, mute1.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &mute1, sizeof(mute1));
- } else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME) {
- if (request->bRequest == AUDIO20_CS_REQ_RANGE) {
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE && p_request->bRequest == AUDIO20_CS_REQ_CUR) {
+ audio20_control_cur_1_t mute1 = {.bCur = mute[channel_num]};
+ TU_LOG1("Get channel %u mute %d\r\n", channel_num, mute1.bCur);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute1, sizeof(mute1));
+ } else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
+ if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_2_n_t(1) range_vol = {
.wNumSubRanges = tu_htole16(1),
.subrange[0] = {.bMin = tu_htole16(-VOLUME_CTRL_50_DB), tu_htole16(VOLUME_CTRL_0_DB), tu_htole16(256)}};
- TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", request->bChannelNumber,
+ TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", channel_num,
range_vol.subrange[0].bMin / 256, range_vol.subrange[0].bMax / 256, range_vol.subrange[0].bRes / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &range_vol, sizeof(range_vol));
- } else if (request->bRequest == AUDIO20_CS_REQ_CUR) {
- audio20_control_cur_2_t cur_vol = {.bCur = tu_htole16(volume[request->bChannelNumber])};
- TU_LOG1("Get channel %u volume %d dB\r\n", request->bChannelNumber, cur_vol.bCur / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &cur_vol, sizeof(cur_vol));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &range_vol, sizeof(range_vol));
+ } else if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
+ audio20_control_cur_2_t cur_vol = {.bCur = tu_htole16(volume[channel_num])};
+ TU_LOG1("Get channel %u volume %d dB\r\n", channel_num, cur_vol.bCur / 256);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_vol, sizeof(cur_vol));
}
}
- TU_LOG1("Feature unit get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
// Helper for feature unit set requests
-static bool audio20_feature_unit_set_request(uint8_t rhport, audio20_control_request_t const *request, uint8_t const *buf) {
+static bool audio20_feature_unit_set_request(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t const *buf) {
(void) rhport;
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
+
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_1_t));
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
- mute[request->bChannelNumber] = ((audio20_control_cur_1_t const *) buf)->bCur;
+ mute[channel_num] = ((audio20_control_cur_1_t const *) buf)->bCur;
- TU_LOG1("Set channel %d Mute: %d\r\n", request->bChannelNumber, mute[request->bChannelNumber]);
+ TU_LOG1("Set channel %d Mute: %d\r\n", channel_num, mute[channel_num]);
return true;
- } else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_2_t));
+ } else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
- volume[request->bChannelNumber] = ((audio20_control_cur_2_t const *) buf)->bCur;
+ volume[channel_num] = ((audio20_control_cur_2_t const *) buf)->bCur;
- TU_LOG1("Set channel %d volume: %d dB\r\n", request->bChannelNumber, volume[request->bChannelNumber] / 256);
+ TU_LOG1("Set channel %d volume: %d dB\r\n", channel_num, volume[channel_num] / 256);
return true;
} else {
- TU_LOG1("Feature unit set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
static bool audio20_get_req_entity(uint8_t rhport, tusb_control_request_t const *p_request) {
- audio20_control_request_t const *request = (audio20_control_request_t const *) p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_CLOCK)
- return audio20_clock_get_request(rhport, request);
- if (request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT)
- return audio20_feature_unit_get_request(rhport, request);
+ if (entity_id == UAC2_ENTITY_CLOCK)
+ return audio20_clock_get_request(rhport, p_request);
+ if (entity_id == UAC2_ENTITY_SPK_FEATURE_UNIT)
+ return audio20_feature_unit_get_request(rhport, p_request);
else {
TU_LOG1("Get request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
}
return false;
}
static bool audio20_set_req_entity(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *buf) {
- audio20_control_request_t const *request = (audio20_control_request_t const *) p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_SPK_FEATURE_UNIT)
- return audio20_feature_unit_set_request(rhport, request, buf);
- if (request->bEntityID == UAC2_ENTITY_CLOCK)
- return audio20_clock_set_request(rhport, request, buf);
+ if (entity_id == UAC2_ENTITY_SPK_FEATURE_UNIT)
+ return audio20_feature_unit_set_request(rhport, p_request, buf);
+ if (entity_id == UAC2_ENTITY_CLOCK)
+ return audio20_clock_set_request(rhport, p_request, buf);
TU_LOG1("Set request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
return false;
}
@@ -522,8 +526,8 @@ bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p
bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
if (ITF_NUM_AUDIO_STREAMING_SPK == itf && alt == 0) {
blink_interval_ms = BLINK_MOUNTED;
@@ -534,8 +538,8 @@ bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const
bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
TU_LOG2("Set interface %d alt %d\r\n", itf, alt);
if (ITF_NUM_AUDIO_STREAMING_SPK == itf && alt != 0) {
diff --git a/examples/device/uac2_headset/src/usb_descriptors.c b/examples/device/uac2_headset/src/usb_descriptors.c
index e4fbbf8a5..b554e7195 100644
--- a/examples/device/uac2_headset/src/usb_descriptors.c
+++ b/examples/device/uac2_headset/src/usb_descriptors.c
@@ -97,12 +97,19 @@ uint8_t const * tud_descriptor_device_cb(void)
#define EPNUM_AUDIO_OUT 0x08
#define EPNUM_AUDIO_INT 0x01
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_AUDIO_IN 0x01
- #define EPNUM_AUDIO_OUT 0x02
- #define EPNUM_AUDIO_INT 0x03
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP10/11 so the 4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO_OUT 0x0A
+ #define EPNUM_AUDIO_IN 0x0B
+ #define EPNUM_AUDIO_INT 0x01
+ #else
+ #define EPNUM_AUDIO_IN 0x01
+ #define EPNUM_AUDIO_OUT 0x02
+ #define EPNUM_AUDIO_INT 0x03
+ #endif
#else
#define EPNUM_AUDIO_IN 0x01
diff --git a/examples/device/uac2_speaker_fb/skip.txt b/examples/device/uac2_speaker_fb/skip.txt
index 234f1ebed..0c7339c65 100644
--- a/examples/device/uac2_speaker_fb/skip.txt
+++ b/examples/device/uac2_speaker_fb/skip.txt
@@ -6,3 +6,4 @@ mcu:SAME5X
mcu:SAMG
board:stm32l052dap52
family:broadcom_64bit
+mcu:CH583
diff --git a/examples/device/uac2_speaker_fb/src/main.c b/examples/device/uac2_speaker_fb/src/main.c
index c3e97bb28..7e4d27f1c 100644
--- a/examples/device/uac2_speaker_fb/src/main.c
+++ b/examples/device/uac2_speaker_fb/src/main.c
@@ -315,16 +315,16 @@ const uint32_t sample_rates[] = {44100, 48000, 88200, 96000};
#define N_SAMPLE_RATES TU_ARRAY_SIZE(sample_rates)
-static bool audio20_clock_get_request(uint8_t rhport, audio20_control_request_t const *request) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
+static bool audio20_clock_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ) {
- if (request->bRequest == AUDIO20_CS_REQ_CUR) {
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
+ if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
TU_LOG1("Clock get current freq %" PRIu32 "\r\n", current_sample_rate);
audio20_control_cur_4_t curf = {(int32_t) tu_htole32(current_sample_rate)};
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &curf, sizeof(curf));
- } else if (request->bRequest == AUDIO20_CS_REQ_RANGE) {
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &curf, sizeof(curf));
+ } else if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_4_n_t(N_SAMPLE_RATES) rangef =
{
.wNumSubRanges = tu_htole16(N_SAMPLE_RATES)};
@@ -336,25 +336,26 @@ static bool audio20_clock_get_request(uint8_t rhport, audio20_control_request_t
TU_LOG1("Range %d (%d, %d, %d)\r\n", i, (int) rangef.subrange[i].bMin, (int) rangef.subrange[i].bMax, (int) rangef.subrange[i].bRes);
}
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &rangef, sizeof(rangef));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &rangef, sizeof(rangef));
}
- } else if (request->bControlSelector == AUDIO20_CS_CTRL_CLK_VALID &&
- request->bRequest == AUDIO20_CS_REQ_CUR) {
+ } else if (ctrl_sel == AUDIO20_CS_CTRL_CLK_VALID &&
+ p_request->bRequest == AUDIO20_CS_REQ_CUR) {
audio20_control_cur_1_t cur_valid = {.bCur = 1};
TU_LOG1("Clock get is valid %u\r\n", cur_valid.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &cur_valid, sizeof(cur_valid));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_valid, sizeof(cur_valid));
}
- TU_LOG1("Clock get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
-static bool audio20_clock_set_request(audio20_control_request_t const *request, uint8_t const *buf) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_CLOCK);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+static bool audio20_clock_set_request(tusb_control_request_t const *p_request, uint8_t const *buf) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
- if (request->bControlSelector == AUDIO20_CS_CTRL_SAM_FREQ) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_4_t));
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
+
+ if (ctrl_sel == AUDIO20_CS_CTRL_SAM_FREQ) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_4_t));
current_sample_rate = (uint32_t) ((audio20_control_cur_4_t const *) buf)->bCur;
@@ -362,89 +363,92 @@ static bool audio20_clock_set_request(audio20_control_request_t const *request,
return true;
} else {
- TU_LOG1("Clock set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Clock set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
-static bool audio20_feature_unit_get_request(uint8_t rhport, audio20_control_request_t const *request) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_FEATURE_UNIT);
+static bool audio20_feature_unit_get_request(uint8_t rhport, tusb_control_request_t const *p_request) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE && request->bRequest == AUDIO20_CS_REQ_CUR) {
- audio20_control_cur_1_t mute1 = {.bCur = mute[request->bChannelNumber]};
- TU_LOG1("Get channel %u mute %d\r\n", request->bChannelNumber, mute1.bCur);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &mute1, sizeof(mute1));
- } else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME) {
- if (request->bRequest == AUDIO20_CS_REQ_RANGE) {
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE && p_request->bRequest == AUDIO20_CS_REQ_CUR) {
+ audio20_control_cur_1_t mute1 = {.bCur = mute[channel_num]};
+ TU_LOG1("Get channel %u mute %d\r\n", channel_num, mute1.bCur);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &mute1, sizeof(mute1));
+ } else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
+ if (p_request->bRequest == AUDIO20_CS_REQ_RANGE) {
audio20_control_range_2_n_t(1) range_vol = {
.wNumSubRanges = tu_htole16(1),
.subrange[0] = {.bMin = tu_htole16(-VOLUME_CTRL_50_DB), tu_htole16(VOLUME_CTRL_0_DB), tu_htole16(256)}};
- TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", request->bChannelNumber,
+ TU_LOG1("Get channel %u volume range (%d, %d, %u) dB\r\n", channel_num,
range_vol.subrange[0].bMin / 256, range_vol.subrange[0].bMax / 256, range_vol.subrange[0].bRes / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &range_vol, sizeof(range_vol));
- } else if (request->bRequest == AUDIO20_CS_REQ_CUR) {
- audio20_control_cur_2_t cur_vol = {.bCur = tu_htole16(volume[request->bChannelNumber])};
- TU_LOG1("Get channel %u volume %d dB\r\n", request->bChannelNumber, cur_vol.bCur / 256);
- return tud_audio_buffer_and_schedule_control_xfer(rhport, (tusb_control_request_t const *) request, &cur_vol, sizeof(cur_vol));
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &range_vol, sizeof(range_vol));
+ } else if (p_request->bRequest == AUDIO20_CS_REQ_CUR) {
+ audio20_control_cur_2_t cur_vol = {.bCur = tu_htole16(volume[channel_num])};
+ TU_LOG1("Get channel %u volume %d dB\r\n", channel_num, cur_vol.bCur / 256);
+ return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur_vol, sizeof(cur_vol));
}
}
- TU_LOG1("Feature unit get request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit get request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
-static bool audio20_feature_unit_set_request(audio20_control_request_t const *request, uint8_t const *buf) {
- TU_ASSERT(request->bEntityID == UAC2_ENTITY_FEATURE_UNIT);
- TU_VERIFY(request->bRequest == AUDIO20_CS_REQ_CUR);
+static bool audio20_feature_unit_set_request(tusb_control_request_t const *p_request, uint8_t const *buf) {
+ uint8_t const ctrl_sel = TU_U16_HIGH(p_request->wValue);
+ uint8_t const channel_num = TU_U16_LOW(p_request->wValue);
+
+ TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR);
- if (request->bControlSelector == AUDIO20_FU_CTRL_MUTE) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_1_t));
+ if (ctrl_sel == AUDIO20_FU_CTRL_MUTE) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t));
- mute[request->bChannelNumber] = ((audio20_control_cur_1_t const *) buf)->bCur;
+ mute[channel_num] = ((audio20_control_cur_1_t const *) buf)->bCur;
- TU_LOG1("Set channel %d Mute: %d\r\n", request->bChannelNumber, mute[request->bChannelNumber]);
+ TU_LOG1("Set channel %d Mute: %d\r\n", channel_num, mute[channel_num]);
return true;
- } else if (request->bControlSelector == AUDIO20_FU_CTRL_VOLUME) {
- TU_VERIFY(request->wLength == sizeof(audio20_control_cur_2_t));
+ } else if (ctrl_sel == AUDIO20_FU_CTRL_VOLUME) {
+ TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t));
- volume[request->bChannelNumber] = ((audio20_control_cur_2_t const *) buf)->bCur;
+ volume[channel_num] = ((audio20_control_cur_2_t const *) buf)->bCur;
- TU_LOG1("Set channel %d volume: %d dB\r\n", request->bChannelNumber, volume[request->bChannelNumber] / 256);
+ TU_LOG1("Set channel %d volume: %d dB\r\n", channel_num, volume[channel_num] / 256);
return true;
} else {
- TU_LOG1("Feature unit set request not supported, entity = %u, selector = %u, request = %u\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ TU_LOG1("Feature unit set request not supported, selector = %u, request = %u\r\n",
+ ctrl_sel, p_request->bRequest);
return false;
}
}
static bool audio20_get_req_entity(uint8_t rhport, tusb_control_request_t const *p_request) {
- audio20_control_request_t const *request = (audio20_control_request_t const *) p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_CLOCK)
- return audio20_clock_get_request(rhport, request);
- if (request->bEntityID == UAC2_ENTITY_FEATURE_UNIT)
- return audio20_feature_unit_get_request(rhport, request);
+ if (entity_id == UAC2_ENTITY_CLOCK)
+ return audio20_clock_get_request(rhport, p_request);
+ if (entity_id == UAC2_ENTITY_FEATURE_UNIT)
+ return audio20_feature_unit_get_request(rhport, p_request);
else {
TU_LOG1("Get request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
}
return false;
}
static bool audio20_set_req_entity(tusb_control_request_t const *p_request, uint8_t *buf) {
- audio20_control_request_t const *request = (audio20_control_request_t const *) p_request;
+ uint8_t const entity_id = TU_U16_HIGH(p_request->wIndex);
- if (request->bEntityID == UAC2_ENTITY_FEATURE_UNIT)
- return audio20_feature_unit_set_request(request, buf);
- if (request->bEntityID == UAC2_ENTITY_CLOCK)
- return audio20_clock_set_request(request, buf);
+ if (entity_id == UAC2_ENTITY_FEATURE_UNIT)
+ return audio20_feature_unit_set_request(p_request, buf);
+ if (entity_id == UAC2_ENTITY_CLOCK)
+ return audio20_clock_set_request(p_request, buf);
TU_LOG1("Set request not handled, entity = %d, selector = %d, request = %d\r\n",
- request->bEntityID, request->bControlSelector, request->bRequest);
+ entity_id, TU_U16_HIGH(p_request->wValue), p_request->bRequest);
return false;
}
@@ -457,8 +461,8 @@ static bool audio20_set_req_entity(tusb_control_request_t const *p_request, uint
bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
TU_LOG2("Set interface %d alt %d\r\n", itf, alt);
if (ITF_NUM_AUDIO_STREAMING == itf && alt != 0)
@@ -531,8 +535,8 @@ bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p
bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) {
(void) rhport;
- uint8_t const itf = tu_u16_low(tu_le16toh(p_request->wIndex));
- uint8_t const alt = tu_u16_low(tu_le16toh(p_request->wValue));
+ uint8_t const itf = tu_u16_low(p_request->wIndex);
+ uint8_t const alt = tu_u16_low(p_request->wValue);
if (ITF_NUM_AUDIO_STREAMING == itf && alt == 0) {
blink_interval_ms = BLINK_MOUNTED;
diff --git a/examples/device/uac2_speaker_fb/src/usb_descriptors.c b/examples/device/uac2_speaker_fb/src/usb_descriptors.c
index c5a161a1e..f0c780e38 100644
--- a/examples/device/uac2_speaker_fb/src/usb_descriptors.c
+++ b/examples/device/uac2_speaker_fb/src/usb_descriptors.c
@@ -115,12 +115,19 @@ uint8_t const * tud_hid_descriptor_report_cb(uint8_t itf) {
#define EPNUM_AUDIO_FB 0x08
#define EPNUM_DEBUG 0x01
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_AUDIO 0x02
- #define EPNUM_AUDIO_FB 0x01
- #define EPNUM_DEBUG 0x03
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put audio iso on EP10/11 so the 4096-byte FIFOs can back double packet buffering
+ #define EPNUM_AUDIO 0x0A
+ #define EPNUM_AUDIO_FB 0x0B
+ #define EPNUM_DEBUG 0x01
+ #else
+ #define EPNUM_AUDIO 0x02
+ #define EPNUM_AUDIO_FB 0x01
+ #define EPNUM_DEBUG 0x03
+ #endif
#else
#define EPNUM_AUDIO 0x01
diff --git a/examples/device/usbtmc/src/usb_descriptors.c b/examples/device/usbtmc/src/usb_descriptors.c
index 16bd176f8..ecdcef834 100644
--- a/examples/device/usbtmc/src/usb_descriptors.c
+++ b/examples/device/usbtmc/src/usb_descriptors.c
@@ -79,16 +79,26 @@ uint8_t const * tud_descriptor_device_cb(void)
#if defined(CFG_TUD_USBTMC)
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+# define EPNUM_USBTMC_OUT 0x01
+# define EPNUM_USBTMC_IN 0x82
+# define EPNUM_USBTMC_INT 0x83
+#else
+# define EPNUM_USBTMC_OUT 0x01
+# define EPNUM_USBTMC_IN 0x81
+# define EPNUM_USBTMC_INT 0x82
+#endif
+
# define TUD_USBTMC_DESC_MAIN(_itfnum,_bNumEndpoints, _bulkMaxPacketLength) \
TUD_USBTMC_IF_DESCRIPTOR(_itfnum, _bNumEndpoints, /*_stridx = */ 4u, TUD_USBTMC_PROTOCOL_USB488), \
- TUD_USBTMC_BULK_DESCRIPTORS(/* OUT = */0x01, /* IN = */ 0x81, /* packet size = */_bulkMaxPacketLength)
+ TUD_USBTMC_BULK_DESCRIPTORS(EPNUM_USBTMC_OUT, EPNUM_USBTMC_IN, /* packet size = */_bulkMaxPacketLength)
#if CFG_TUD_USBTMC_ENABLE_INT_EP
// USBTMC Interrupt xfer always has length of 2, but we use epMaxSize=8 for
// compatibility with mcus that only allow 8, 16, 32 or 64 for FS endpoints
# define TUD_USBTMC_DESC(_itfnum, _bulkMaxPacketLength) \
TUD_USBTMC_DESC_MAIN(_itfnum, /* _epCount = */ 3, _bulkMaxPacketLength), \
- TUD_USBTMC_INT_DESCRIPTOR(/* INT ep # */ 0x82, /* epMaxSize = */ 8, /* bInterval = */16u )
+ TUD_USBTMC_INT_DESCRIPTOR(EPNUM_USBTMC_INT, /* epMaxSize = */ 8, /* bInterval = */16u )
# define TUD_USBTMC_DESC_LEN (TUD_USBTMC_IF_DESCRIPTOR_LEN + TUD_USBTMC_BULK_DESCRIPTORS_LEN + TUD_USBTMC_INT_DESCRIPTOR_LEN)
#else
diff --git a/examples/device/video_capture/skip.txt b/examples/device/video_capture/skip.txt
index cb0c7d2e6..5a7a1d00e 100644
--- a/examples/device/video_capture/skip.txt
+++ b/examples/device/video_capture/skip.txt
@@ -1,5 +1,6 @@
mcu:CH32V103
mcu:CH32V20X
+mcu:CH583
mcu:MSP430x5xx
mcu:NUC121
mcu:SAMD11
diff --git a/examples/device/video_capture_2ch/skip.txt b/examples/device/video_capture_2ch/skip.txt
index af3b0de04..c37205b8c 100644
--- a/examples/device/video_capture_2ch/skip.txt
+++ b/examples/device/video_capture_2ch/skip.txt
@@ -5,6 +5,7 @@ mcu:GD32VF103
mcu:CH32V103
mcu:CH32V20X
mcu:CH32V307
+mcu:CH583
mcu:STM32L0
family:espressif
board:curiosity_nano
diff --git a/examples/device/webusb_serial/skip.txt b/examples/device/webusb_serial/skip.txt
new file mode 100644
index 000000000..2c6c2a64c
--- /dev/null
+++ b/examples/device/webusb_serial/skip.txt
@@ -0,0 +1 @@
+family:espressif
diff --git a/examples/device/webusb_serial/src/usb_descriptors.c b/examples/device/webusb_serial/src/usb_descriptors.c
index 0ef41a68e..527837161 100644
--- a/examples/device/webusb_serial/src/usb_descriptors.c
+++ b/examples/device/webusb_serial/src/usb_descriptors.c
@@ -104,15 +104,25 @@ enum
#define EPNUM_VENDOR_OUT 0x05
#define EPNUM_VENDOR_IN 0x84
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
- #define EPNUM_CDC_NOTIF 0x81
- #define EPNUM_CDC_OUT 0x02
- #define EPNUM_CDC_IN 0x83
+ #if TU_CHECK_MCU(OPT_MCU_MAX32650, OPT_MCU_MAX32666, OPT_MCU_MAX32690, OPT_MCU_MAX78002)
+ // Put bulk on EP>=8 so the 2048/4096-byte FIFOs can back double packet buffering
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x08
+ #define EPNUM_CDC_IN 0x89
+
+ #define EPNUM_VENDOR_OUT 0x0A
+ #define EPNUM_VENDOR_IN 0x8B
+ #else
+ #define EPNUM_CDC_NOTIF 0x81
+ #define EPNUM_CDC_OUT 0x02
+ #define EPNUM_CDC_IN 0x83
- #define EPNUM_VENDOR_OUT 0x04
- #define EPNUM_VENDOR_IN 0x85
+ #define EPNUM_VENDOR_OUT 0x04
+ #define EPNUM_VENDOR_IN 0x85
+ #endif
#else
#define EPNUM_CDC_NOTIF 0x81
diff --git a/examples/dual/dynamic_switch/only.txt b/examples/dual/dynamic_switch/only.txt
index 70be49b28..e1038f9d4 100644
--- a/examples/dual/dynamic_switch/only.txt
+++ b/examples/dual/dynamic_switch/only.txt
@@ -2,6 +2,7 @@ family:espressif
mcu:LPC43XX
mcu:MIMXRT1XXX
mcu:STM32C0
+mcu:STM32C5
mcu:STM32G0
mcu:STM32H5
mcu:STM32F2
diff --git a/examples/dual/dynamic_switch/src/main.c b/examples/dual/dynamic_switch/src/main.c
index c9ad2a835..f67cd885c 100644
--- a/examples/dual/dynamic_switch/src/main.c
+++ b/examples/dual/dynamic_switch/src/main.c
@@ -79,6 +79,9 @@ StaticTask_t usb_taskdef;
StackType_t cdc_stack[CDC_STACK_SIZE];
StaticTask_t cdc_taskdef;
+
+StackType_t devinfo_stack[USBH_STACK_SIZE];
+StaticTask_t devinfo_taskdef;
#endif
#endif
@@ -87,14 +90,13 @@ static tusb_role_t current_role = TUSB_ROLE_DEVICE;
#if CFG_TUSB_OS == OPT_OS_FREERTOS
static void usb_task(void *param);
-void led_blinking_task(void *param);
-void cdc_task(void *params);
-#else
-void led_blinking_task(void);
-void cdc_task(void);
#endif
+void led_blinking_task(void *param);
+void cdc_task(void *param);
+void print_devinfo_task(void *param);
+
void usb_mode_switch(void);
-static void print_device_info(uint8_t daddr);
+static void print_one_device(uint8_t daddr);
static void print_utf16(uint16_t* temp_buf, size_t buf_len);
// Declare buffer for USB transfer
@@ -124,11 +126,13 @@ int main(void) {
xTaskCreateStatic(usb_task, "usb", USBD_STACK_SIZE > USBH_STACK_SIZE ? USBD_STACK_SIZE : USBH_STACK_SIZE,
NULL, configMAX_PRIORITIES-1, usb_stack, &usb_taskdef);
xTaskCreateStatic(cdc_task, "cdc", CDC_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, cdc_stack, &cdc_taskdef);
+ xTaskCreateStatic(print_devinfo_task, "devinfo", USBH_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, devinfo_stack, &devinfo_taskdef);
#else
xTaskCreate(led_blinking_task, "blinky", BLINKY_STACK_SIZE, NULL, 1, NULL);
xTaskCreate(usb_task, "usb", USBD_STACK_SIZE > USBH_STACK_SIZE ? USBD_STACK_SIZE : USBH_STACK_SIZE,
NULL, configMAX_PRIORITIES - 1, NULL);
xTaskCreate(cdc_task, "cdc", CDC_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL);
+ xTaskCreate(print_devinfo_task, "devinfo", USBH_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL);
#endif
#ifndef ESP_PLATFORM
@@ -162,12 +166,13 @@ int main(void) {
// Process USB tasks based on current mode
if (current_role == TUSB_ROLE_DEVICE) {
tud_task();
- cdc_task();
+ cdc_task(NULL);
} else {
tuh_task();
+ print_devinfo_task(NULL);
}
- led_blinking_task();
+ led_blinking_task(NULL);
}
#endif
}
@@ -227,21 +232,28 @@ static void usb_task(void *param) {
void usb_mode_switch(void) {
printf("\r\n--- Switching USB mode ---\r\n");
- // Deinitialize current mode
- if (current_role == TUSB_ROLE_DEVICE) {
+ // Snapshot then clear current_role BEFORE tusb_deinit() so concurrent
+ // tasks (cdc_task / print_devinfo_task on RTOS) see the role-change
+ // boundary and exit cleanly instead of calling host/device APIs against
+ // a deinitialised stack.
+ const tusb_role_t prev_role = current_role;
+ current_role = TUSB_ROLE_INVALID;
+
+ if (prev_role == TUSB_ROLE_DEVICE) {
printf("Stopping DEVICE mode...\r\n");
- tusb_deinit(BOARD_RHPORT);
} else {
printf("Stopping HOST mode...\r\n");
- tusb_deinit(BOARD_RHPORT);
}
+ tusb_deinit(BOARD_RHPORT);
#if CFG_TUSB_OS == OPT_OS_FREERTOS
vTaskDelay(pdMS_TO_TICKS(100)); // Small delay for clean transition
#else
- tusb_time_delay_ms_api(100); // Small delay for clean transition
-#endif // Switch to the other mode
- if (current_role == TUSB_ROLE_DEVICE) {
+ tusb_time_delay_ms_api(100);
+#endif
+
+ // Switch to the other mode
+ if (prev_role == TUSB_ROLE_DEVICE) {
printf("Starting HOST mode...\r\n");
tusb_rhport_init_t host_init = {
.role = TUSB_ROLE_HOST,
@@ -267,61 +279,29 @@ void usb_mode_switch(void) {
// Device Mode: CDC Task
//--------------------------------------------------------------------+
+void cdc_task(void *param) {
+ (void) param;
#if CFG_TUSB_OS == OPT_OS_FREERTOS
-void cdc_task(void *params) {
- (void) params;
-
- // RTOS forever loop
while (1) {
- // Only process CDC when in device mode
+#endif
+ // Only touch device-CDC APIs while we're in device mode. After
+ // usb_mode_switch() sets current_role to INVALID and tusb_deinit() runs,
+ // calling tud_cdc_write_flush() here would hit a deinit'd device stack.
if (current_role == TUSB_ROLE_DEVICE) {
- // Connected and there are data available
- while (tud_cdc_available()) {
+ if (tud_cdc_available()) {
uint8_t buf[64];
-
- // Read data
- uint32_t count = tud_cdc_read(buf, sizeof(buf));
-
- // Echo back
- tud_cdc_write(buf, count);
-
- // Add newline for carriage return
- for (uint32_t i = 0; i < count; i++) {
- if (buf[i] == '\r') {
- tud_cdc_write_char('\n');
- break;
- }
+ const uint32_t count = tud_cdc_read(buf, sizeof(buf));
+ if (count) {
+ tud_cdc_write(buf, count);
}
}
-
tud_cdc_write_flush();
}
-
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
vTaskDelay(pdMS_TO_TICKS(10));
}
-}
-#else
-void cdc_task(void) {
- // Connected and there are data available
- if (tud_cdc_available()) {
- uint8_t buf[64];
-
- // Read data
- uint32_t count = tud_cdc_read(buf, sizeof(buf));
-
- // Echo back
- for (uint32_t i = 0; i < count; i++) {
- tud_cdc_write_char(buf[i]);
-
- if (buf[i] == '\r') {
- tud_cdc_write_char('\n');
- }
- }
-
- tud_cdc_write_flush();
- }
-}
#endif
+}
//--------------------------------------------------------------------+
// Device Callbacks
@@ -356,24 +336,56 @@ void tud_resume_cb(void) {
// Host Callbacks
//--------------------------------------------------------------------+
-// Invoked when device is mounted (configured)
+// One flag per possible device address — set by tuh_mount_cb (host task) and
+// cleared by print_devinfo_task once the device's descriptors are printed.
+static volatile bool need_devinfo[CFG_TUH_DEVICE_MAX + 1];
+
+// Invoked when device is mounted (configured). Runs in the host task — keep
+// minimal; descriptor fetching happens in print_devinfo_task (different
+// context so sync helpers are safe).
void tuh_mount_cb(uint8_t daddr) {
printf("[HOST] Device attached, address = %d\r\n", daddr);
blink_interval_ms = BLINK_MOUNTED;
- print_device_info(daddr);
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = true;
+ }
}
// Invoked when device is unmounted (unplugged)
void tuh_umount_cb(uint8_t daddr) {
printf("[HOST] Device removed, address = %d\r\n", daddr);
blink_interval_ms = BLINK_NOT_MOUNTED;
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = false;
+ }
}
//--------------------------------------------------------------------+
-// Host Device Info
+// Host Device Info — serialises descriptor fetching across all mounted
+// devices using sync helpers. Safe to call from main loop (OS_NONE) or a
+// dedicated task (FreeRTOS) — but NOT from a host-stack callback.
//--------------------------------------------------------------------+
-static void print_device_info(uint8_t daddr) {
+void print_devinfo_task(void *param) {
+ (void) param;
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
+ while (1) {
+#endif
+ if (current_role == TUSB_ROLE_HOST) {
+ for (uint8_t daddr = 1; daddr < TU_ARRAY_SIZE(need_devinfo); daddr++) {
+ if (need_devinfo[daddr]) {
+ need_devinfo[daddr] = false;
+ print_one_device(daddr);
+ }
+ }
+ }
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
+ vTaskDelay(pdMS_TO_TICKS(10));
+ }
+#endif
+}
+
+static void print_one_device(uint8_t daddr) {
// Get Device Descriptor
uint8_t xfer_result = tuh_descriptor_get_device_sync(daddr, &desc.device, 18);
if (XFER_RESULT_SUCCESS != xfer_result) {
@@ -467,30 +479,23 @@ static void print_utf16(uint16_t* temp_buf, size_t buf_len) {
// Blinking Task
//--------------------------------------------------------------------+
-#if CFG_TUSB_OS == OPT_OS_FREERTOS
void led_blinking_task(void *param) {
(void) param;
+ static uint32_t start_ms = 0;
static bool led_state = false;
-
- // RTOS forever loop
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
while (1) {
- board_led_write(led_state);
- led_state = 1 - led_state; // toggle
vTaskDelay(pdMS_TO_TICKS(blink_interval_ms));
+ start_ms += blink_interval_ms;
+ board_led_write(led_state);
+ led_state = 1 - led_state;
}
-}
#else
-void led_blinking_task(void) {
- static uint32_t start_ms = 0;
- static bool led_state = false;
-
- // Blink every interval ms
if (tusb_time_millis_api() - start_ms < blink_interval_ms) {
return; // not enough time
}
start_ms += blink_interval_ms;
-
board_led_write(led_state);
- led_state = 1 - led_state; // toggle
-}
+ led_state = 1 - led_state;
#endif
+}
diff --git a/examples/dual/dynamic_switch/src/usb_descriptors.c b/examples/dual/dynamic_switch/src/usb_descriptors.c
index 54ffc2c18..ef6d795b7 100644
--- a/examples/dual/dynamic_switch/src/usb_descriptors.c
+++ b/examples/dual/dynamic_switch/src/usb_descriptors.c
@@ -86,7 +86,7 @@ enum {
#define EPNUM_CDC_OUT 0x02
#define EPNUM_CDC_IN 0x82
-#elif defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#elif CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
// MCUs that don't support a same endpoint number with different direction IN and OUT defined in tusb_mcu.h
// e.g EP1 OUT & EP1 IN cannot exist together
#define EPNUM_CDC_NOTIF 0x81
diff --git a/examples/dual/host_info_to_device_cdc/src/main.c b/examples/dual/host_info_to_device_cdc/src/main.c
index cf3430464..5186f91dc 100644
--- a/examples/dual/host_info_to_device_cdc/src/main.c
+++ b/examples/dual/host_info_to_device_cdc/src/main.c
@@ -130,7 +130,7 @@ static void main_task(void* param) {
led_blinking_task();
// preempted RTOS run device/host stack in its own task
-#if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO
+#if CFG_TUSB_OS_HAS_SCHEDULER == 0
tud_task(); // tinyusb device task
tuh_task(); // tinyusb host task
#endif
@@ -140,7 +140,7 @@ static void main_task(void* param) {
int main(void) {
board_init();
-#if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO
+#if CFG_TUSB_OS_HAS_SCHEDULER == 0
printf("TinyUSB Host Information -> Device CDC Example\r\n");
usb_device_init();
@@ -156,7 +156,7 @@ int main(void) {
return 0;
}
-#if CFG_TUSB_OS != OPT_OS_NONE && CFG_TUSB_OS != OPT_OS_PICO
+#if CFG_TUSB_OS_HAS_SCHEDULER
// USB Device Driver task for RTOS
static void usb_device_task(void *param) {
(void) param;
diff --git a/examples/host/CMakeLists.txt b/examples/host/CMakeLists.txt
index f8e0ce692..7c74e3c73 100644
--- a/examples/host/CMakeLists.txt
+++ b/examples/host/CMakeLists.txt
@@ -13,7 +13,9 @@ set(EXAMPLE_LIST
device_info
hid_controller
midi_rx
+ midi2_host
msc_file_explorer
+ msc_file_explorer_freertos
)
foreach (example ${EXAMPLE_LIST})
diff --git a/examples/host/bare_api/only.txt b/examples/host/bare_api/only.txt
index 1ddfc2b5c..a2ff93be5 100644
--- a/examples/host/bare_api/only.txt
+++ b/examples/host/bare_api/only.txt
@@ -20,6 +20,7 @@ mcu:RP2040
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/bare_api/src/main.c b/examples/host/bare_api/src/main.c
index 544f38102..679ce6f43 100644
--- a/examples/host/bare_api/src/main.c
+++ b/examples/host/bare_api/src/main.c
@@ -48,14 +48,19 @@ CFG_TUH_MEM_SECTION uint16_t temp_buf[128]; // temp buffer for string descriptor
// MACRO CONSTANT TYPEDEF PROTYPES
//--------------------------------------------------------------------+
void led_blinking_task(void);
+void print_devinfo_task(void);
static void print_utf16(uint16_t *temp_buf, size_t buf_len);
-void print_device_descriptor(tuh_xfer_t* xfer);
+static void print_one_device(uint8_t daddr);
void parse_config_descriptor(uint8_t dev_addr, tusb_desc_configuration_t const* desc_cfg);
uint8_t* get_hid_buf(uint8_t daddr);
void free_hid_buf(uint8_t daddr);
+// One flag per possible device address — set in tuh_mount_cb (host task) and
+// cleared by print_devinfo_task (main loop) once the descriptors are printed.
+static volatile bool need_devinfo[CFG_TUH_DEVICE_MAX + 1];
+
/*------------- MAIN -------------*/
int main(void) {
board_init();
@@ -74,38 +79,53 @@ int main(void) {
while (1) {
// tinyusb host task
tuh_task();
+ print_devinfo_task();
led_blinking_task();
}
}
/*------------- TinyUSB Callbacks -------------*/
-// Invoked when device is mounted (configured)
+// Invoked when device is mounted (configured). Runs in the host task — keep
+// it minimal. The descriptor fetching/printing happens in print_devinfo_task()
+// below where the sync helpers are safe (different context).
void tuh_mount_cb(uint8_t daddr) {
printf("Device attached, address = %d\r\n", daddr);
-
- // Get Device Descriptor
- // TODO: invoking control transfer now has issue with mounting hub with multiple devices attached, fix later
- tuh_descriptor_get_device(daddr, &desc_device, 18, print_device_descriptor, 0);
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = true;
+ }
}
/// Invoked when device is unmounted (bus reset/unplugged)
void tuh_umount_cb(uint8_t daddr) {
printf("Device removed, address = %d\r\n", daddr);
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = false;
+ }
free_hid_buf(daddr);
}
//--------------------------------------------------------------------+
-// Device Descriptor
+// Print device info task — serialises descriptor fetching across all
+// mounted devices via sync helpers. Sync calls are safe here because this
+// runs in the main loop (outside any host-stack callback context).
//--------------------------------------------------------------------+
-void print_device_descriptor(tuh_xfer_t *xfer) {
- if (XFER_RESULT_SUCCESS != xfer->result) {
+void print_devinfo_task(void) {
+ for (uint8_t daddr = 1; daddr < TU_ARRAY_SIZE(need_devinfo); daddr++) {
+ if (need_devinfo[daddr]) {
+ need_devinfo[daddr] = false;
+ print_one_device(daddr);
+ }
+ }
+}
+
+static void print_one_device(uint8_t daddr) {
+ // Get Device Descriptor
+ if (XFER_RESULT_SUCCESS != tuh_descriptor_get_device_sync(daddr, &desc_device, 18)) {
printf("Failed to get device descriptor\r\n");
return;
}
- uint8_t const daddr = xfer->daddr;
-
printf("Device %u: ID %04x:%04x\r\n", daddr, desc_device.idVendor, desc_device.idProduct);
printf("Device Descriptor:\r\n");
printf(" bLength %u\r\n" , desc_device.bLength);
@@ -119,7 +139,6 @@ void print_device_descriptor(tuh_xfer_t *xfer) {
printf(" idProduct 0x%04x\r\n" , desc_device.idProduct);
printf(" bcdDevice %04x\r\n" , desc_device.bcdDevice);
- // Get String descriptor using Sync API
printf(" iManufacturer %u ", desc_device.iManufacturer);
if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, temp_buf, sizeof(temp_buf))) {
print_utf16(temp_buf, TU_ARRAY_SIZE(temp_buf));
diff --git a/examples/host/cdc_msc_hid/only.txt b/examples/host/cdc_msc_hid/only.txt
index 1ddfc2b5c..a2ff93be5 100644
--- a/examples/host/cdc_msc_hid/only.txt
+++ b/examples/host/cdc_msc_hid/only.txt
@@ -20,6 +20,7 @@ mcu:RP2040
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/cdc_msc_hid/src/cdc_app.c b/examples/host/cdc_msc_hid/src/cdc_app.c
index 20033981e..e6c190715 100644
--- a/examples/host/cdc_msc_hid/src/cdc_app.c
+++ b/examples/host/cdc_msc_hid/src/cdc_app.c
@@ -95,7 +95,6 @@ void tuh_cdc_mount_cb(uint8_t idx) {
printf("CDC Interface is mounted: address = %u, itf_num = %u\r\n", itf_info.daddr,
itf_info.desc.bInterfaceNumber);
-#ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM
// If CFG_TUH_CDC_LINE_CODING_ON_ENUM is defined, line coding will be set by tinyusb stack
// while eneumerating new cdc device
cdc_line_coding_t line_coding = {0};
@@ -103,11 +102,6 @@ void tuh_cdc_mount_cb(uint8_t idx) {
printf(" Baudrate: %" PRIu32 ", Stop Bits : %u\r\n", line_coding.bit_rate, line_coding.stop_bits);
printf(" Parity : %u, Data Width: %u\r\n", line_coding.parity, line_coding.data_bits);
}
-#else
- // Set Line Coding upon mounted
- cdc_line_coding_t new_line_coding = { 115200, CDC_LINE_CODING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 };
- tuh_cdc_set_line_coding(idx, &new_line_coding, NULL, 0);
-#endif
}
// Invoked when a device with CDC interface is unmounted
diff --git a/examples/host/cdc_msc_hid_freertos/only.txt b/examples/host/cdc_msc_hid_freertos/only.txt
index 753fa7cd3..4ab8a906e 100644
--- a/examples/host/cdc_msc_hid_freertos/only.txt
+++ b/examples/host/cdc_msc_hid_freertos/only.txt
@@ -16,6 +16,7 @@ mcu:MSP432E4
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/cdc_msc_hid_freertos/src/cdc_app.c b/examples/host/cdc_msc_hid_freertos/src/cdc_app.c
index 30baacaac..9fad775e9 100644
--- a/examples/host/cdc_msc_hid_freertos/src/cdc_app.c
+++ b/examples/host/cdc_msc_hid_freertos/src/cdc_app.c
@@ -29,16 +29,16 @@
#include "app.h"
#ifdef ESP_PLATFORM
- #define CDC_STACK_SZIE 2048
+ #define CDC_STACK_SIZE 2048
#else
- #define CDC_STACK_SZIE (3*configMINIMAL_STACK_SIZE/2)
+ #define CDC_STACK_SIZE (3*configMINIMAL_STACK_SIZE/2)
#endif
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
#if configSUPPORT_STATIC_ALLOCATION
-StackType_t cdc_stack[CDC_STACK_SZIE];
+StackType_t cdc_stack[CDC_STACK_SIZE];
StaticTask_t cdc_taskdef;
#endif
@@ -46,9 +46,9 @@ static void cdc_app_task(void* param);
void cdc_app_init(void) {
#if configSUPPORT_STATIC_ALLOCATION
- (void) xTaskCreateStatic(cdc_app_task, "cdc", CDC_STACK_SZIE, NULL, configMAX_PRIORITIES-2, cdc_stack, &cdc_taskdef);
+ (void) xTaskCreateStatic(cdc_app_task, "cdc", CDC_STACK_SIZE, NULL, configMAX_PRIORITIES-2, cdc_stack, &cdc_taskdef);
#else
- (void) xTaskCreate(cdc_app_task, "cdc", CDC_STACK_SZIE, NULL, configMAX_PRIORITIES-2, NULL);
+ (void) xTaskCreate(cdc_app_task, "cdc", CDC_STACK_SIZE, NULL, configMAX_PRIORITIES-2, NULL);
#endif
}
diff --git a/examples/host/device_info/only.txt b/examples/host/device_info/only.txt
index 742935dcf..4c2cb0f35 100644
--- a/examples/host/device_info/only.txt
+++ b/examples/host/device_info/only.txt
@@ -21,6 +21,7 @@ mcu:RP2040
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/device_info/src/main.c b/examples/host/device_info/src/main.c
index b0e38dd6b..f32ed1a3e 100644
--- a/examples/host/device_info/src/main.c
+++ b/examples/host/device_info/src/main.c
@@ -72,8 +72,14 @@ CFG_TUH_MEM_SECTION struct {
} desc;
void led_blinking_task(void* param);
+void print_devinfo_task(void* param);
static void print_utf16(uint16_t* temp_buf, size_t buf_len);
+// One flag per possible device address — set by tuh_mount_cb (host task) and
+// cleared by print_devinfo_task (separate task / main loop) once the device's
+// descriptor info has been printed.
+static volatile bool need_devinfo[CFG_TUH_DEVICE_MAX + 1];
+
#if CFG_TUSB_OS == OPT_OS_FREERTOS
void init_freertos_task(void);
#endif
@@ -103,6 +109,7 @@ int main(void) {
init_tinyusb();
while (1) {
tuh_task(); // tinyusb host task
+ print_devinfo_task(NULL);
led_blinking_task(NULL);
}
#endif
@@ -110,10 +117,34 @@ int main(void) {
/*------------- TinyUSB Callbacks -------------*/
-// Invoked when device is mounted (configured)
+// Invoked when device is mounted (configured). Runs in the host task — keep
+// it minimal. The actual descriptor fetching/printing happens in
+// print_devinfo_task() below, which runs in a different context (main loop
+// on OS_NONE / dedicated task on RTOS) where the sync helpers are safe.
void tuh_mount_cb(uint8_t daddr) {
blink_interval_ms = BLINK_MOUNTED;
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = true;
+ }
+}
+// Invoked when device is unmounted (bus reset/unplugged)
+void tuh_umount_cb(uint8_t daddr) {
+ blink_interval_ms = BLINK_NOT_MOUNTED;
+ if (daddr < TU_ARRAY_SIZE(need_devinfo)) {
+ need_devinfo[daddr] = false;
+ }
+ printf("Device removed, address = %d\r\n", daddr);
+}
+
+//--------------------------------------------------------------------+
+// Print device info task — serialises descriptor fetching across all
+// mounted devices using the sync helpers. Sync calls are safe here because
+// this task runs outside the host-task callback context (main loop on
+// OS_NONE / dedicated FreeRTOS task on RTOS).
+//--------------------------------------------------------------------+
+
+static void print_one_device(uint8_t daddr) {
// Get Device Descriptor
uint8_t xfer_result = tuh_descriptor_get_device_sync(daddr, &desc.device, 18);
if (XFER_RESULT_SUCCESS != xfer_result) {
@@ -129,9 +160,8 @@ void tuh_mount_cb(uint8_t daddr) {
}
if (XFER_RESULT_SUCCESS != xfer_result) {
uint16_t* serial = (uint16_t*)(uintptr_t) desc.serial;
-
serial[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * 1 + 2));
- serial[1] = '0'; // simply 0
+ serial[1] = '0';
serial[2] = 0;
}
print_utf16((uint16_t*)(uintptr_t) desc.serial, sizeof(desc.serial)/2);
@@ -149,12 +179,9 @@ void tuh_mount_cb(uint8_t daddr) {
printf(" idProduct 0x%04x\r\n", desc.device.idProduct);
printf(" bcdDevice %04x\r\n", desc.device.bcdDevice);
- // Get String descriptor using Sync API
-
printf(" iManufacturer %u ", desc.device.iManufacturer);
if (desc.device.iManufacturer != 0) {
- xfer_result = tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf));
- if (XFER_RESULT_SUCCESS == xfer_result) {
+ if (XFER_RESULT_SUCCESS == tuh_descriptor_get_manufacturer_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf))) {
print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2);
}
}
@@ -162,22 +189,33 @@ void tuh_mount_cb(uint8_t daddr) {
printf(" iProduct %u ", desc.device.iProduct);
if (desc.device.iProduct != 0) {
- xfer_result = tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf));
- if (XFER_RESULT_SUCCESS == xfer_result) {
+ if (XFER_RESULT_SUCCESS == tuh_descriptor_get_product_string_sync(daddr, LANGUAGE_ID, desc.buf, sizeof(desc.buf))) {
print_utf16((uint16_t*)(uintptr_t) desc.buf, sizeof(desc.buf)/2);
}
}
printf("\r\n");
printf(" iSerialNumber %u ", desc.device.iSerialNumber);
- printf("%s\r\n", (char*)desc.serial); // serial is already to UTF-8
+ printf("%s\r\n", (char*)desc.serial); // serial is already UTF-8
printf(" bNumConfigurations %u\r\n", desc.device.bNumConfigurations);
}
-// Invoked when device is unmounted (bus reset/unplugged)
-void tuh_umount_cb(uint8_t daddr) {
- blink_interval_ms = BLINK_NOT_MOUNTED;
- printf("Device removed, address = %d\r\n", daddr);
+void print_devinfo_task(void* param) {
+ (void) param;
+
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
+ while (1) {
+#endif
+ for (uint8_t daddr = 1; daddr < TU_ARRAY_SIZE(need_devinfo); daddr++) {
+ if (need_devinfo[daddr]) {
+ need_devinfo[daddr] = false;
+ print_one_device(daddr);
+ }
+ }
+#if CFG_TUSB_OS == OPT_OS_FREERTOS
+ vTaskDelay(pdMS_TO_TICKS(10));
+ }
+#endif
}
//--------------------------------------------------------------------+
@@ -278,6 +316,9 @@ StaticTask_t blinky_taskdef;
StackType_t usb_stack[USB_STACK_SIZE];
StaticTask_t usb_taskdef;
+
+StackType_t devinfo_stack[USB_STACK_SIZE];
+StaticTask_t devinfo_taskdef;
#endif
#ifdef ESP_PLATFORM
@@ -299,9 +340,11 @@ void init_freertos_task(void) {
#if configSUPPORT_STATIC_ALLOCATION
xTaskCreateStatic(led_blinking_task, "blinky", BLINKY_STACK_SIZE, NULL, 1, blinky_stack, &blinky_taskdef);
xTaskCreateStatic(usb_host_task, "usbh", USB_STACK_SIZE, NULL, configMAX_PRIORITIES-1, usb_stack, &usb_taskdef);
+ xTaskCreateStatic(print_devinfo_task, "devinfo", USB_STACK_SIZE, NULL, configMAX_PRIORITIES-2, devinfo_stack, &devinfo_taskdef);
#else
xTaskCreate(led_blinking_task, "blinky", BLINKY_STACK_SIZE, NULL, 1, NULL);
xTaskCreate(usb_host_task, "usbh", USB_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL);
+ xTaskCreate(print_devinfo_task, "devinfo", USB_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL);
#endif
// only start scheduler for non-espressif mcu
diff --git a/examples/host/midi2_host/CMakeLists.txt b/examples/host/midi2_host/CMakeLists.txt
new file mode 100644
index 000000000..0ec03bf5f
--- /dev/null
+++ b/examples/host/midi2_host/CMakeLists.txt
@@ -0,0 +1,29 @@
+cmake_minimum_required(VERSION 3.20)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+
+project(midi2_host C CXX ASM)
+
+# Checks this example is valid for the family and initializes the project
+family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR})
+
+# Espressif has its own cmake build system
+if(FAMILY STREQUAL "espressif")
+ return()
+endif()
+
+add_executable(${PROJECT_NAME})
+
+# Example source
+target_sources(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
+ )
+
+# Example include
+target_include_directories(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+ )
+
+# Configure compilation flags and libraries for the example without RTOS.
+# See the corresponding function in hw/bsp/FAMILY/family.cmake for details.
+family_configure_host_example(${PROJECT_NAME} noos)
diff --git a/examples/host/midi2_host/CMakePresets.json b/examples/host/midi2_host/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/host/midi2_host/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/host/midi2_host/Makefile b/examples/host/midi2_host/Makefile
new file mode 100644
index 000000000..f8292385e
--- /dev/null
+++ b/examples/host/midi2_host/Makefile
@@ -0,0 +1,13 @@
+include ../../../hw/bsp/family_support.mk
+
+INC += \
+ src \
+
+
+# Example source
+EXAMPLE_SOURCE += \
+ src/main.c
+
+SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE))
+
+include ../../../hw/bsp/family_rules.mk
diff --git a/examples/host/midi2_host/only.txt b/examples/host/midi2_host/only.txt
new file mode 100644
index 000000000..c71aacd87
--- /dev/null
+++ b/examples/host/midi2_host/only.txt
@@ -0,0 +1,34 @@
+family:hpmicro
+family:samd21
+family:samd5x_e5x
+mcu:CH32V20X
+mcu:ESP32P4
+mcu:ESP32S2
+mcu:ESP32S3
+mcu:KINETIS_KL
+mcu:LPC175X_6X
+mcu:LPC177X_8X
+mcu:LPC18XX
+mcu:LPC40XX
+mcu:LPC43XX
+mcu:LPC54
+mcu:LPC55
+mcu:MAX3421
+mcu:MIMXRT10XX
+mcu:MIMXRT11XX
+mcu:MIMXRT1XXX
+mcu:MSP432E4
+mcu:RAXXX
+mcu:RP2040
+mcu:RW61X
+mcu:RX65X
+mcu:STM32C0
+mcu:STM32F4
+mcu:STM32F7
+mcu:STM32G0
+mcu:STM32H5
+mcu:STM32H7
+mcu:STM32H7RS
+mcu:STM32N6
+mcu:STM32U3
+mcu:STM32U5
diff --git a/examples/host/midi2_host/skip.txt b/examples/host/midi2_host/skip.txt
new file mode 100644
index 000000000..308796869
--- /dev/null
+++ b/examples/host/midi2_host/skip.txt
@@ -0,0 +1 @@
+board:lpcxpresso54114
diff --git a/examples/host/midi2_host/src/main.c b/examples/host/midi2_host/src/main.c
new file mode 100644
index 000000000..d81e77a33
--- /dev/null
+++ b/examples/host/midi2_host/src/main.c
@@ -0,0 +1,163 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+// Minimal USB-MIDI 2.0 host example.
+// Receives UMP from any MIDI 2.0 device, prints each packet to stdout.
+
+#include <stdio.h>
+#include <string.h>
+#include "bsp/board_api.h"
+#include "tusb.h"
+#include "class/midi/midi2_host.h"
+
+//--------------------------------------------------------------------+
+// State
+//--------------------------------------------------------------------+
+
+TU_ATTR_UNUSED static uint8_t midi2_idx = 0xFF;
+
+//--------------------------------------------------------------------+
+// UMP printer - shows MT and word(s) in hex; decodes Channel Voice
+//--------------------------------------------------------------------+
+
+static void print_ump(const uint32_t* words, uint8_t wc) {
+ uint8_t mt = (uint8_t)((words[0] >> 28) & 0x0F);
+ uint8_t group = (uint8_t)((words[0] >> 24) & 0x0F);
+
+ if (mt == 0x4 && wc >= 2) {
+ // MIDI 2.0 Channel Voice
+ uint8_t status = (uint8_t)((words[0] >> 20) & 0x0F);
+ uint8_t channel = (uint8_t)((words[0] >> 16) & 0x0F);
+ uint8_t data1 = (uint8_t)((words[0] >> 8) & 0x7F);
+ switch (status) {
+ case 0x9:
+ printf("[g%u ch%u] M2 NoteOn n=%u vel=%04X attr=%04X\r\n",
+ group, channel, data1,
+ (unsigned)((words[1] >> 16) & 0xFFFF),
+ (unsigned)(words[1] & 0xFFFF));
+ break;
+ case 0x8:
+ printf("[g%u ch%u] M2 NoteOff n=%u vel=%04X\r\n",
+ group, channel, data1,
+ (unsigned)((words[1] >> 16) & 0xFFFF));
+ break;
+ case 0xB:
+ printf("[g%u ch%u] M2 CC#%u = %08lX\r\n",
+ group, channel, data1, (unsigned long)words[1]);
+ break;
+ case 0xC:
+ printf("[g%u ch%u] M2 ProgChg %u\r\n",
+ group, channel, (unsigned)((words[1] >> 24) & 0x7F));
+ break;
+ case 0xD:
+ printf("[g%u ch%u] M2 ChanPress %08lX\r\n",
+ group, channel, (unsigned long)words[1]);
+ break;
+ case 0xE:
+ printf("[g%u ch%u] M2 PitchBend %08lX\r\n",
+ group, channel, (unsigned long)words[1]);
+ break;
+ default:
+ printf("[g%u ch%u] M2 status=0x%X w0=%08lX w1=%08lX\r\n",
+ group, channel, status,
+ (unsigned long)words[0], (unsigned long)words[1]);
+ break;
+ }
+ } else if (mt == 0x2 && wc == 1) {
+ // MIDI 1.0 Channel Voice
+ uint8_t status = (uint8_t)((words[0] >> 16) & 0xFF);
+ uint8_t data1 = (uint8_t)((words[0] >> 8) & 0x7F);
+ uint8_t data2 = (uint8_t)(words[0] & 0x7F);
+ printf("[g%u] M1 %02X %02X %02X\r\n", group, status, data1, data2);
+ } else {
+ printf("UMP MT=0x%X wc=%u w0=%08lX\r\n",
+ mt, wc, (unsigned long)words[0]);
+ }
+}
+
+//--------------------------------------------------------------------+
+// MIDI 2.0 Host Callbacks
+//--------------------------------------------------------------------+
+
+void tuh_midi2_descriptor_cb(uint8_t idx, const tuh_midi2_descriptor_cb_t* d) {
+ (void)idx;
+ printf("MIDI2 descriptor: %s, RX cables=%u TX cables=%u\r\n",
+ d->protocol_version ? "MIDI 2.0" : "MIDI 1.0",
+ d->rx_cable_count, d->tx_cable_count);
+}
+
+void tuh_midi2_mount_cb(uint8_t idx, const tuh_midi2_mount_cb_t* m) {
+ midi2_idx = idx;
+ printf("MIDI2 mounted: idx=%u protocol=%s\r\n",
+ idx, m->protocol_version ? "MIDI 2.0" : "MIDI 1.0");
+}
+
+void tuh_midi2_rx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ (void)xferred_bytes;
+
+ uint32_t words[16];
+ while (1) {
+ uint32_t n = tuh_midi2_ump_read(idx, words, 16);
+ if (n == 0) break;
+
+ uint32_t i = 0;
+ while (i < n) {
+ uint8_t mt = (uint8_t)((words[i] >> 28) & 0x0F);
+ uint8_t wc = midi2_ump_word_count(mt);
+ if (i + wc > n) break;
+ print_ump(&words[i], wc);
+ i += wc;
+ }
+ }
+}
+
+void tuh_midi2_tx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ (void)idx; (void)xferred_bytes;
+}
+
+void tuh_midi2_umount_cb(uint8_t idx) {
+ (void)idx;
+ midi2_idx = 0xFF;
+ printf("MIDI2 unmounted\r\n");
+}
+
+//--------------------------------------------------------------------+
+// Main
+//--------------------------------------------------------------------+
+
+int main(void) {
+ board_init();
+
+ printf("\r\nTinyUSB Host MIDI 2.0 Example\r\n");
+
+ tusb_rhport_init_t host_init = {
+ .role = TUSB_ROLE_HOST,
+ .speed = TUSB_SPEED_AUTO,
+ };
+ tusb_init(BOARD_TUH_RHPORT, &host_init);
+
+ while (1) {
+ tuh_task();
+ }
+}
diff --git a/examples/host/midi2_host/src/tusb_config.h b/examples/host/midi2_host/src/tusb_config.h
new file mode 100644
index 000000000..4bd6ef2ea
--- /dev/null
+++ b/examples/host/midi2_host/src/tusb_config.h
@@ -0,0 +1,106 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef TUSB_CONFIG_H_
+#define TUSB_CONFIG_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Common Configuration
+//--------------------------------------------------------------------+
+
+#ifndef CFG_TUSB_MCU
+#error CFG_TUSB_MCU must be defined
+#endif
+
+#ifdef ESP_PLATFORM
+#define CFG_TUSB_OS_INC_PATH freertos/
+#endif
+
+#ifndef CFG_TUSB_OS
+#define CFG_TUSB_OS OPT_OS_NONE
+#endif
+
+#ifndef CFG_TUSB_DEBUG
+#define CFG_TUSB_DEBUG 0
+#endif
+
+#ifndef CFG_TUH_MEM_SECTION
+#define CFG_TUH_MEM_SECTION
+#endif
+
+#ifndef CFG_TUH_MEM_ALIGN
+#define CFG_TUH_MEM_ALIGN __attribute__ ((aligned(4)))
+#endif
+
+//--------------------------------------------------------------------+
+// Host Configuration
+//--------------------------------------------------------------------+
+
+#define CFG_TUH_ENABLED 1
+
+#if CFG_TUSB_MCU == OPT_MCU_RP2040
+ // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller
+ // #define CFG_TUH_MAX3421 1 // use max3421 as host controller
+
+ // host roothub port is 1 if using either pio-usb or max3421
+ #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421)
+ #define BOARD_TUH_RHPORT 1
+ #endif
+#endif
+
+#define CFG_TUH_MAX_SPEED BOARD_TUH_MAX_SPEED
+
+//------------------------- Board Specific --------------------------+
+
+#ifndef BOARD_TUH_RHPORT
+#define BOARD_TUH_RHPORT 0
+#endif
+
+#ifndef BOARD_TUH_MAX_SPEED
+#define BOARD_TUH_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+#endif
+
+//--------------------------------------------------------------------+
+// Driver Configuration
+//--------------------------------------------------------------------+
+
+#define CFG_TUH_ENUMERATION_BUFSIZE 256
+
+#define CFG_TUH_HUB 1
+#define CFG_TUH_DEVICE_MAX (3*CFG_TUH_HUB + 1)
+
+// USB-MIDI 2.0 Host
+#define CFG_TUH_MIDI2 CFG_TUH_DEVICE_MAX
+#define CFG_TUH_MIDI2_RX_BUFSIZE 512
+#define CFG_TUH_MIDI2_TX_BUFSIZE 512
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/examples/host/midi_rx/only.txt b/examples/host/midi_rx/only.txt
index c71aacd87..65ef8fac9 100644
--- a/examples/host/midi_rx/only.txt
+++ b/examples/host/midi_rx/only.txt
@@ -23,6 +23,7 @@ mcu:RP2040
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/msc_file_explorer/only.txt b/examples/host/msc_file_explorer/only.txt
index 1ddfc2b5c..a2ff93be5 100644
--- a/examples/host/msc_file_explorer/only.txt
+++ b/examples/host/msc_file_explorer/only.txt
@@ -20,6 +20,7 @@ mcu:RP2040
mcu:RW61X
mcu:RX65X
mcu:STM32C0
+mcu:STM32C5
mcu:STM32F4
mcu:STM32F7
mcu:STM32G0
diff --git a/examples/host/msc_file_explorer_freertos/CMakeLists.txt b/examples/host/msc_file_explorer_freertos/CMakeLists.txt
new file mode 100644
index 000000000..4893dd1fb
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/CMakeLists.txt
@@ -0,0 +1,42 @@
+cmake_minimum_required(VERSION 3.20)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/../../../hw/bsp/family_support.cmake)
+
+project(msc_file_explorer_freertos C CXX ASM)
+
+# Checks this example is valid for the family and initializes the project
+family_initialize_project(${PROJECT_NAME} ${CMAKE_CURRENT_LIST_DIR})
+
+# Espressif has its own cmake build system
+if(FAMILY STREQUAL "espressif")
+ return()
+endif()
+
+add_executable(${PROJECT_NAME})
+
+# Example source
+target_sources(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/main.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/msc_app.c
+ ${TOP}/lib/fatfs/source/ff.c
+ ${TOP}/lib/fatfs/source/ffsystem.c
+ ${TOP}/lib/fatfs/source/ffunicode.c
+ )
+
+# Example include
+target_include_directories(${PROJECT_NAME} PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src
+ ${TOP}/lib/fatfs/source
+ ${TOP}/lib/embedded-cli
+ )
+
+# Configure compilation flags and libraries for the example with FreeRTOS.
+# See the corresponding function in hw/bsp/FAMILY/family.cmake for details.
+family_configure_host_example(${PROJECT_NAME} freertos)
+
+# Suppress warnings on fatfs
+if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ set_source_files_properties(${TOP}/lib/fatfs/source/ff.c PROPERTIES
+ COMPILE_OPTIONS "-Wno-conversion;-Wno-cast-qual"
+ )
+endif ()
diff --git a/examples/host/msc_file_explorer_freertos/CMakePresets.json b/examples/host/msc_file_explorer_freertos/CMakePresets.json
new file mode 100644
index 000000000..5cd8971e9
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/CMakePresets.json
@@ -0,0 +1,6 @@
+{
+ "version": 6,
+ "include": [
+ "../../../hw/bsp/BoardPresets.json"
+ ]
+}
diff --git a/examples/host/msc_file_explorer_freertos/Makefile b/examples/host/msc_file_explorer_freertos/Makefile
new file mode 100644
index 000000000..15c7420d4
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/Makefile
@@ -0,0 +1,27 @@
+RTOS = freertos
+include ../../../hw/bsp/family_support.mk
+
+FATFS_PATH = lib/fatfs/source
+
+INC += \
+ src \
+ $(TOP)/$(FATFS_PATH) \
+ $(TOP)/lib/embedded-cli \
+
+# Example source
+EXAMPLE_SOURCE = \
+ src/main.c \
+ src/msc_app.c \
+
+SRC_C += $(addprefix $(EXAMPLE_PATH)/, $(EXAMPLE_SOURCE))
+
+# FatFS source
+SRC_C += \
+ $(FATFS_PATH)/ff.c \
+ $(FATFS_PATH)/ffsystem.c \
+ $(FATFS_PATH)/ffunicode.c \
+
+# suppress warning caused by fatfs
+CFLAGS += -Wno-error=cast-qual
+
+include ../../../hw/bsp/family_rules.mk
diff --git a/examples/host/msc_file_explorer_freertos/README.md b/examples/host/msc_file_explorer_freertos/README.md
new file mode 100644
index 000000000..4ee6b96fa
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/README.md
@@ -0,0 +1,105 @@
+# MSC File Explorer (FreeRTOS)
+
+This host example implements an interactive command-line file browser for USB Mass Storage devices.
+When a USB flash drive is connected, the device is automatically mounted using FatFS and a shell-like
+CLI is presented over the board's serial console.
+
+## Features
+
+- Automatic mount/unmount of USB storage devices
+- FAT12/16/32 filesystem support via FatFS
+- Interactive CLI with command history
+- Read speed benchmarking with `dd`
+- Support for up to 4 simultaneous USB storage devices (via hub)
+
+## Supported Commands
+
+| Command | Usage | Description |
+|---------|--------------------|------------------------------------------------------|
+| help | `help` | Print list of available commands |
+| cat | `cat <file>` | Print file contents to the console |
+| cd | `cd <dir>` | Change current working directory |
+| cp | `cp <src> <dest>` | Copy a file |
+| dd | `dd [count]` | Read sectors and report speed (default 1024 sectors) |
+| ls | `ls [dir]` | List directory contents |
+| pwd | `pwd` | Print current working directory |
+| mkdir | `mkdir <dir>` | Create a directory |
+| mv | `mv <src> <dest>` | Rename/move a file or directory |
+| rm | `rm <file>` | Remove a file |
+
+## Build
+
+Build for a specific board using CMake (see [Getting Started](https://docs.tinyusb.org/en/latest/getting_started.html)):
+
+```bash
+# Example: build for STM32F407 Discovery board
+cmake -B build -DBOARD=stm32f407disco -GNinja examples/host/msc_file_explorer_freertos
+cmake --build build
+```
+
+## Usage
+
+1. Flash the firmware to your board.
+2. Open a serial terminal (e.g. `minicom`, `screen`, `PuTTY`) at 115200 baud.
+3. Plug a USB flash drive into the board's USB host port.
+4. The device is auto-mounted and the prompt appears:
+
+```
+TinyUSB MSC File Explorer Example
+
+Device connected
+ Vendor : Kingston
+ Product : DataTraveler 2.0
+ Rev : 1.0
+ Capacity: 1.9 GB
+
+0:/> _
+```
+
+### Browsing Files
+
+```
+0:/> ls
+----a 1234 readme.txt
+d---- 0 photos
+d---- 0 docs
+
+0:/> cd photos
+0:/photos> ls
+----a 520432 vacation.jpg
+----a 312088 family.png
+
+0:/> cat readme.txt
+Hello from USB drive!
+```
+
+### Copying and Moving Files
+
+```
+0:/> cp readme.txt backup.txt
+0:/> mv backup.txt docs/backup.txt
+```
+
+### Measuring Read Speed
+
+```
+0:/> dd
+Reading 1024 sectors...
+ Data speed: 823 KB/s
+```
+
+### Multiple Devices
+
+When using a USB hub, multiple drives are mounted as `0:`, `1:`, etc. Use the drive prefix to
+navigate between them:
+
+```
+0:/> cd 1:
+1:/> ls
+```
+
+## Testing
+
+Build-time validation follows the standard TinyUSB host example flow. Runtime behavior should be
+verified on hardware by attaching an MSC device and exercising CLI commands such as `ls`, `pwd`,
+and `dd`.
diff --git a/examples/host/msc_file_explorer_freertos/only.txt b/examples/host/msc_file_explorer_freertos/only.txt
new file mode 100644
index 000000000..519ac2ebd
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/only.txt
@@ -0,0 +1,28 @@
+family:espressif
+family:samd21
+family:samd5x_e5x
+mcu:LPC175X_6X
+mcu:LPC177X_8X
+mcu:LPC18XX
+mcu:LPC40XX
+mcu:LPC43XX
+mcu:LPC54
+mcu:LPC55
+mcu:MAX3421
+mcu:MIMXRT10XX
+mcu:MIMXRT11XX
+mcu:MIMXRT1XXX
+mcu:MSP432E4
+mcu:RP2040
+mcu:RW61X
+mcu:RX65X
+mcu:STM32C0
+mcu:STM32F4
+mcu:STM32F7
+mcu:STM32G0
+mcu:STM32H5
+mcu:STM32H7
+mcu:STM32H7RS
+mcu:STM32N6
+mcu:STM32U3
+mcu:STM32U5
diff --git a/examples/host/msc_file_explorer_freertos/skip.txt b/examples/host/msc_file_explorer_freertos/skip.txt
new file mode 100644
index 000000000..a8c9bea2a
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/skip.txt
@@ -0,0 +1,4 @@
+mcu:CH32F20X
+board:lpcxpresso54114
+mcu:FT90X
+board:stm32h7s3nucleo
diff --git a/examples/host/msc_file_explorer_freertos/src/CMakeLists.txt b/examples/host/msc_file_explorer_freertos/src/CMakeLists.txt
new file mode 100644
index 000000000..c3fb35607
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/CMakeLists.txt
@@ -0,0 +1,13 @@
+# This file is for ESP-IDF only
+set(FATFS_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../../lib/fatfs/source)
+set(EMBEDDED_CLI_DIR ${CMAKE_CURRENT_LIST_DIR}/../../../../lib/embedded-cli)
+
+idf_component_register(
+ SRCS "main.c" "msc_app.c"
+ ${FATFS_DIR}/ff.c
+ ${FATFS_DIR}/ffsystem.c
+ ${FATFS_DIR}/ffunicode.c
+ INCLUDE_DIRS "." ${FATFS_DIR} ${EMBEDDED_CLI_DIR}
+ REQUIRES boards tinyusb_src)
+
+target_compile_options(${COMPONENT_LIB} PRIVATE -Wno-error=format)
diff --git a/examples/host/msc_file_explorer_freertos/src/ffconf.h b/examples/host/msc_file_explorer_freertos/src/ffconf.h
new file mode 100644
index 000000000..5c89136fe
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/ffconf.h
@@ -0,0 +1,313 @@
+/*---------------------------------------------------------------------------/
+/ Configurations of FatFs Module
+/---------------------------------------------------------------------------*/
+
+#define FFCONF_DEF 80386 /* Revision ID */
+
+/*---------------------------------------------------------------------------/
+/ Function Configurations
+/---------------------------------------------------------------------------*/
+
+#define FF_FS_READONLY 0
+/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
+/ Read-only configuration removes writing API functions, f_write(), f_sync(),
+/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
+/ and optional writing functions as well. */
+
+
+#define FF_FS_MINIMIZE 0
+/* This option defines minimization level to remove some basic API functions.
+/
+/ 0: Basic functions are fully enabled.
+/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
+/ are removed.
+/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
+/ 3: f_lseek() function is removed in addition to 2. */
+
+
+#define FF_USE_FIND 0
+/* This option switches filtered directory read functions, f_findfirst() and
+/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
+
+
+#define FF_USE_MKFS 0
+/* This option switches f_mkfs(). (0:Disable or 1:Enable) */
+
+
+#define FF_USE_FASTSEEK 0
+/* This option switches fast seek feature. (0:Disable or 1:Enable) */
+
+
+#define FF_USE_EXPAND 0
+/* This option switches f_expand(). (0:Disable or 1:Enable) */
+
+
+#define FF_USE_CHMOD 0
+/* This option switches attribute control API functions, f_chmod() and f_utime().
+/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
+
+
+#define FF_USE_LABEL 0
+/* This option switches volume label API functions, f_getlabel() and f_setlabel().
+/ (0:Disable or 1:Enable) */
+
+
+#define FF_USE_FORWARD 0
+/* This option switches f_forward(). (0:Disable or 1:Enable) */
+
+
+#define FF_USE_STRFUNC 0
+#define FF_PRINT_LLI 0
+#define FF_PRINT_FLOAT 0
+#define FF_STRF_ENCODE 0
+/* FF_USE_STRFUNC switches string API functions, f_gets(), f_putc(), f_puts() and
+/ f_printf().
+/
+/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
+/ 1: Enable without LF-CRLF conversion.
+/ 2: Enable with LF-CRLF conversion.
+/
+/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
+/ makes f_printf() support floating point argument. These features want C99 or later.
+/ When FF_LFN_UNICODE >= 1 with LFN enabled, string API functions convert the character
+/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
+/ to be read/written via those functions.
+/
+/ 0: ANSI/OEM in current CP
+/ 1: Unicode in UTF-16LE
+/ 2: Unicode in UTF-16BE
+/ 3: Unicode in UTF-8
+*/
+
+
+/*---------------------------------------------------------------------------/
+/ Locale and Namespace Configurations
+/---------------------------------------------------------------------------*/
+
+#define FF_CODE_PAGE 437
+/* This option specifies the OEM code page to be used on the target system.
+/ Incorrect code page setting can cause a file open failure.
+/
+/ 437 - U.S.
+/ 720 - Arabic
+/ 737 - Greek
+/ 771 - KBL
+/ 775 - Baltic
+/ 850 - Latin 1
+/ 852 - Latin 2
+/ 855 - Cyrillic
+/ 857 - Turkish
+/ 860 - Portuguese
+/ 861 - Icelandic
+/ 862 - Hebrew
+/ 863 - Canadian French
+/ 864 - Arabic
+/ 865 - Nordic
+/ 866 - Russian
+/ 869 - Greek 2
+/ 932 - Japanese (DBCS)
+/ 936 - Simplified Chinese (DBCS)
+/ 949 - Korean (DBCS)
+/ 950 - Traditional Chinese (DBCS)
+/ 0 - Include all code pages above and configured by f_setcp()
+*/
+
+
+#define FF_USE_LFN 1
+#define FF_MAX_LFN 255
+/* The FF_USE_LFN switches the support for LFN (long file name).
+/
+/ 0: Disable LFN. FF_MAX_LFN has no effect.
+/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
+/ 2: Enable LFN with dynamic working buffer on the STACK.
+/ 3: Enable LFN with dynamic working buffer on the HEAP.
+/
+/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN feature
+/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
+/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
+/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
+/ be in range of 12 to 255. It is recommended to be set 255 to fully support the LFN
+/ specification.
+/ When use stack for the working buffer, take care on stack overflow. When use heap
+/ memory for the working buffer, memory management functions, ff_memalloc() and
+/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
+
+
+#define FF_LFN_UNICODE 0
+/* This option switches the character encoding on the API when LFN is enabled.
+/
+/ 0: ANSI/OEM in current CP (TCHAR = char)
+/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
+/ 2: Unicode in UTF-8 (TCHAR = char)
+/ 3: Unicode in UTF-32 (TCHAR = DWORD)
+/
+/ Also behavior of string I/O functions will be affected by this option.
+/ When LFN is not enabled, this option has no effect. */
+
+
+#define FF_LFN_BUF 255
+#define FF_SFN_BUF 12
+/* This set of options defines size of file name members in the FILINFO structure
+/ which is used to read out directory items. These values should be sufficient for
+/ the file names to read. The maximum possible length of the read file name depends
+/ on character encoding. When LFN is not enabled, these options have no effect. */
+
+
+#define FF_FS_RPATH 2
+/* This option configures support for relative path feature.
+/
+/ 0: Disable relative path and remove related API functions.
+/ 1: Enable relative path and dot names. f_chdir() and f_chdrive() are available.
+/ 2: f_getcwd() is available in addition to 1.
+*/
+
+
+#define FF_PATH_DEPTH 10
+/* This option defines maximum depth of directory in the exFAT volume. It is NOT
+/ relevant to FAT/FAT32 volume.
+/ For example, FF_PATH_DEPTH = 3 will able to follow a path "/dir1/dir2/dir3/file"
+/ but a sub-directory in the dir3 will not able to be followed and set current
+/ directory.
+/ The size of filesystem object (FATFS) increases FF_PATH_DEPTH * 24 bytes.
+/ When FF_FS_EXFAT == 0 or FF_FS_RPATH == 0, this option has no effect.
+*/
+
+
+
+/*---------------------------------------------------------------------------/
+/ Drive/Volume Configurations
+/---------------------------------------------------------------------------*/
+
+#define FF_VOLUMES 4
+/* Number of volumes (logical drives) to be used. (1-10) */
+
+
+#define FF_STR_VOLUME_ID 0
+#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
+/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
+/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
+/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
+/ logical drive. Number of items must not be less than FF_VOLUMES. Valid
+/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
+/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
+/ not defined, a user defined volume string table is needed as:
+/
+/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
+*/
+
+
+#define FF_MULTI_PARTITION 0
+/* This option switches support for multiple volumes on the physical drive.
+/ By default (0), each logical drive number is bound to the same physical drive
+/ number and only an FAT volume found on the physical drive will be mounted.
+/ When this feature is enabled (1), each logical drive number can be bound to
+/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
+/ will be available. */
+
+
+#define FF_MIN_SS 512
+#define FF_MAX_SS 512
+/* This set of options configures the range of sector size to be supported. (512,
+/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
+/ harddisk, but a larger value may be required for on-board flash memory and some
+/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is
+/ configured for variable sector size mode and disk_ioctl() needs to implement
+/ GET_SECTOR_SIZE command. */
+
+
+#define FF_LBA64 0
+/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
+/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
+
+
+#define FF_MIN_GPT 0x10000000
+/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs() and
+/ f_fdisk(). 2^32 sectors maximum. This option has no effect when FF_LBA64 == 0. */
+
+
+#define FF_USE_TRIM 0
+/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
+/ To enable this feature, also CTRL_TRIM command should be implemented to
+/ the disk_ioctl(). */
+
+
+
+/*---------------------------------------------------------------------------/
+/ System Configurations
+/---------------------------------------------------------------------------*/
+
+#define FF_FS_TINY 0
+/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
+/ At the tiny configuration, size of file object (FIL) is reduced FF_MAX_SS bytes.
+/ Instead of private sector buffer eliminated from the file object, common sector
+/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
+
+
+#define FF_FS_EXFAT 0
+/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
+/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
+/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
+
+
+#define FF_FS_NORTC 1
+#define FF_NORTC_MON 1
+#define FF_NORTC_MDAY 1
+#define FF_NORTC_YEAR 2025
+/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
+/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
+/ timestamp feature. Every object modified by FatFs will have a fixed timestamp
+/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
+/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() need to be added
+/ to the project to read current time form real-time clock. FF_NORTC_MON,
+/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
+/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
+
+
+#define FF_FS_CRTIME 0
+/* This option enables(1)/disables(0) the timestamp of the file created. When
+/ set 1, the file created time is available in FILINFO structure. */
+
+
+#define FF_FS_NOFSINFO 0
+/* If you need to know the correct free space on the FAT32 volume, set bit 0 of
+/ this option, and f_getfree() on the first time after volume mount will force
+/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
+/
+/ bit0=0: Use free cluster count in the FSINFO if available.
+/ bit0=1: Do not trust free cluster count in the FSINFO.
+/ bit1=0: Use last allocated cluster number in the FSINFO if available.
+/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
+*/
+
+
+#define FF_FS_LOCK 0
+/* The option FF_FS_LOCK switches file lock function to control duplicated file open
+/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
+/ is 1.
+/
+/ 0: Disable file lock function. To avoid volume corruption, application program
+/ should avoid illegal open, remove and rename to the open objects.
+/ >0: Enable file lock function. The value defines how many files/sub-directories
+/ can be opened simultaneously under file lock control. Note that the file
+/ lock control is independent of re-entrancy. */
+
+
+#define FF_FS_REENTRANT 0
+#define FF_FS_TIMEOUT 1000
+/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
+/ module itself. Note that regardless of this option, file access to different
+/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
+/ and f_fdisk(), are always not re-entrant. Only file/directory access to
+/ the same volume is under control of this featuer.
+/
+/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
+/ 1: Enable re-entrancy. Also user provided synchronization handlers,
+/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give(),
+/ must be added to the project. Samples are available in ffsystem.c.
+/
+/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
+*/
+
+
+
+/*--- End of configuration options ---*/
diff --git a/examples/host/msc_file_explorer_freertos/src/main.c b/examples/host/msc_file_explorer_freertos/src/main.c
new file mode 100644
index 000000000..d1e627f4f
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/main.c
@@ -0,0 +1,158 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#include <string.h>
+
+#include "bsp/board_api.h"
+#include "tusb.h"
+#ifdef ESP_PLATFORM
+ // ESP-IDF need "freertos/" prefix in include path.
+ // CFG_TUSB_OS_INC_PATH should be defined accordingly.
+ #include "freertos/FreeRTOS.h"
+ #include "freertos/task.h"
+ #include "freertos/timers.h"
+#else
+ #include "FreeRTOS.h"
+ #include "task.h"
+ #include "timers.h"
+#endif
+
+#include "msc_app.h"
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF PROTYPES
+//--------------------------------------------------------------------+
+#ifdef ESP_PLATFORM
+ #define USBH_STACK_SIZE 4096
+#else
+ // Increase stack size when debug log is enabled.
+ #define USBH_STACK_SIZE (configMINIMAL_STACK_SIZE * (CFG_TUSB_DEBUG ? 4 : 3))
+#endif
+
+enum {
+ BLINK_MOUNTED = 1000,
+};
+
+#if configSUPPORT_STATIC_ALLOCATION
+StaticTimer_t blinky_tmdef;
+
+StackType_t usb_host_stack[USBH_STACK_SIZE];
+StaticTask_t usb_host_taskdef;
+#endif
+
+TimerHandle_t blinky_tm;
+
+static void led_blinky_cb(TimerHandle_t xTimer);
+static void usb_host_task(void* param);
+
+/*------------- MAIN -------------*/
+int main(void) {
+ board_init();
+
+ printf("TinyUSB Host MassStorage Explorer FreeRTOS Example\r\n");
+
+ // Create soft timer for blinky and task for TinyUSB host stack.
+#if configSUPPORT_STATIC_ALLOCATION
+ blinky_tm = xTimerCreateStatic(NULL, pdMS_TO_TICKS(BLINK_MOUNTED), true, NULL, led_blinky_cb, &blinky_tmdef);
+ xTaskCreateStatic(usb_host_task, "usbh", USBH_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, usb_host_stack,
+ &usb_host_taskdef);
+#else
+ blinky_tm = xTimerCreate(NULL, pdMS_TO_TICKS(BLINK_MOUNTED), true, NULL, led_blinky_cb);
+ xTaskCreate(usb_host_task, "usbh", USBH_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL);
+#endif
+
+ xTimerStart(blinky_tm, 0);
+
+ // only start scheduler for non-espressif mcu
+#ifndef ESP_PLATFORM
+ vTaskStartScheduler();
+#endif
+
+ return 0;
+}
+
+#ifdef ESP_PLATFORM
+void app_main(void) {
+ main();
+}
+#endif
+
+// USB Host task
+// This top-level thread processes all USB events and invokes callbacks.
+static void usb_host_task(void* param) {
+ (void) param;
+
+ // init host stack on configured roothub port
+ tusb_rhport_init_t host_init = {
+ .role = TUSB_ROLE_HOST,
+ .speed = TUSB_SPEED_AUTO
+ };
+
+ if (!tusb_init(BOARD_TUH_RHPORT, &host_init)) {
+ printf("Failed to init USB Host Stack\r\n");
+ vTaskSuspend(NULL);
+ }
+
+ board_init_after_tusb();
+
+#if CFG_TUH_ENABLED && CFG_TUH_MAX3421
+ // FeatherWing MAX3421E uses MAX3421E GPIO0 for VBUS enable.
+ enum { IOPINS1_ADDR = 20u << 3 };
+ tuh_max3421_reg_write(BOARD_TUH_RHPORT, IOPINS1_ADDR, 0x01, false);
+#endif
+
+ if (!msc_app_init()) {
+ printf("Failed to init MSC app\r\n");
+ vTaskSuspend(NULL);
+ }
+
+ while (1) {
+ // TinyUSB host task.
+ tuh_task();
+ }
+}
+
+//--------------------------------------------------------------------+
+// TinyUSB Callbacks
+//--------------------------------------------------------------------+
+
+void tuh_mount_cb(uint8_t dev_addr) {
+ (void) dev_addr;
+}
+
+void tuh_umount_cb(uint8_t dev_addr) {
+ (void) dev_addr;
+}
+
+//--------------------------------------------------------------------+
+// Blinking Task
+//--------------------------------------------------------------------+
+static void led_blinky_cb(TimerHandle_t xTimer) {
+ (void) xTimer;
+ static bool led_state = false;
+
+ board_led_write(led_state);
+ led_state = 1 - led_state; // toggle
+}
diff --git a/examples/host/msc_file_explorer_freertos/src/msc_app.c b/examples/host/msc_file_explorer_freertos/src/msc_app.c
new file mode 100644
index 000000000..c7e00e52a
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/msc_app.c
@@ -0,0 +1,709 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#include <ctype.h>
+#include "tusb.h"
+#include "bsp/board_api.h"
+#ifdef ESP_PLATFORM
+ // ESP-IDF need "freertos/" prefix in include path.
+ // CFG_TUSB_OS_INC_PATH should be defined accordingly.
+ #include "freertos/FreeRTOS.h"
+ #include "freertos/task.h"
+ #include "freertos/timers.h"
+#else
+ #include "FreeRTOS.h"
+ #include "task.h"
+ #include "timers.h"
+#endif
+
+#include "ff.h"
+#include "diskio.h"
+
+// lib/embedded-cli
+#define EMBEDDED_CLI_IMPL
+#include "embedded_cli.h"
+
+#include "msc_app.h"
+
+
+//--------------------------------------------------------------------+
+// MACRO TYPEDEF CONSTANT ENUM DECLARATION
+//--------------------------------------------------------------------+
+
+//------------- embedded-cli -------------//
+#define CLI_BUFFER_SIZE 512
+#define CLI_RX_BUFFER_SIZE 16
+#define CLI_CMD_BUFFER_SIZE 64
+#define CLI_HISTORY_SIZE 32
+#define CLI_BINDING_COUNT 9
+
+#ifdef ESP_PLATFORM
+ #define MSC_APP_STACK_SIZE 4096
+#else
+ #define MSC_APP_STACK_SIZE (configMINIMAL_STACK_SIZE * (CFG_TUSB_DEBUG ? 3 : 2))
+#endif
+
+static EmbeddedCli *_cli;
+static CLI_UINT cli_buffer[BYTES_TO_CLI_UINTS(CLI_BUFFER_SIZE)];
+
+#if configSUPPORT_STATIC_ALLOCATION
+StackType_t msc_app_stack[MSC_APP_STACK_SIZE];
+StaticTask_t msc_app_taskdef;
+#endif
+
+//------------- Elm Chan FatFS -------------//
+static CFG_TUH_MEM_SECTION FATFS fatfs[CFG_TUH_DEVICE_MAX]; // for simplicity only support 1 LUN per device
+static volatile bool _disk_busy[CFG_TUH_DEVICE_MAX];
+static volatile bool _mount_pending[CFG_TUH_DEVICE_MAX];
+
+static CFG_TUH_MEM_SECTION FIL file1, file2;
+
+#ifndef CFG_EXAMPLE_MSC_FILE_EXPLORER_RW_BUFSIZE
+#define CFG_EXAMPLE_MSC_FILE_EXPLORER_RW_BUFSIZE 4096
+#endif
+static CFG_TUH_MEM_SECTION uint8_t rw_buf[CFG_EXAMPLE_MSC_FILE_EXPLORER_RW_BUFSIZE];
+
+// define the buffer to be place in USB/DMA memory with correct alignment/cache line size
+CFG_TUH_MEM_SECTION static struct {
+ TUH_EPBUF_TYPE_DEF(scsi_inquiry_resp_t, inquiry);
+} scsi_resp;
+
+
+//--------------------------------------------------------------------+
+//
+//--------------------------------------------------------------------+
+
+static bool cli_init(void);
+static void msc_app_task(void* param);
+static void process_pending_mount(void);
+
+bool msc_app_init(void) {
+ for (size_t i = 0; i < CFG_TUH_DEVICE_MAX; i++) {
+ _disk_busy[i] = false;
+ _mount_pending[i] = false;
+ }
+
+// disable stdout buffered for echoing typing command
+#ifndef __ICCARM__ // TODO IAR doesn't support stream control ?
+ setbuf(stdout, NULL);
+#endif
+
+ cli_init();
+
+#if configSUPPORT_STATIC_ALLOCATION
+ TaskHandle_t task_hdl = xTaskCreateStatic(msc_app_task, "msc", MSC_APP_STACK_SIZE, NULL,
+ configMAX_PRIORITIES - 2, msc_app_stack, &msc_app_taskdef);
+ TU_ASSERT(task_hdl != NULL);
+#else
+ TU_ASSERT(xTaskCreate(msc_app_task, "msc", MSC_APP_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL) == pdPASS);
+#endif
+
+ return true;
+}
+
+static void msc_app_task(void* param) {
+ (void) param;
+
+ while (1) {
+ process_pending_mount();
+
+ if (!_cli) {
+ vTaskDelay(1);
+ continue;
+ }
+
+ int ch = board_getchar();
+ if (ch > 0) {
+ while (ch > 0) {
+ embeddedCliReceiveChar(_cli, (char) ch);
+ ch = board_getchar();
+ }
+ embeddedCliProcess(_cli);
+ }
+
+ vTaskDelay(1);
+ }
+}
+
+static void process_pending_mount(void) {
+ for (uint8_t drive_num = 0; drive_num < CFG_TUH_DEVICE_MAX; drive_num++) {
+ if (!_mount_pending[drive_num]) {
+ continue;
+ }
+
+ _mount_pending[drive_num] = false;
+
+ const uint8_t dev_addr = drive_num + 1;
+ if (!tuh_msc_mounted(dev_addr)) {
+ continue;
+ }
+
+ char drive_path[3] = "0:";
+ drive_path[0] += drive_num;
+
+ if (f_mount(&fatfs[drive_num], drive_path, 1) != FR_OK) {
+ printf("mount failed\r\n");
+ continue;
+ }
+
+ f_chdrive(drive_path);
+ FRESULT rc = f_chdir("/");
+ if (rc != FR_OK) {
+ printf("chdir failed: %d\r\n", rc);
+ }
+ }
+}
+
+//--------------------------------------------------------------------+
+//
+//--------------------------------------------------------------------+
+
+static bool inquiry_complete_cb(uint8_t dev_addr, const tuh_msc_complete_data_t *cb_data) {
+ const msc_cbw_t *cbw = cb_data->cbw;
+ const msc_csw_t *csw = cb_data->csw;
+
+ if (csw->status != 0) {
+ printf("Inquiry failed\r\n");
+ return false;
+ }
+
+ // Print out Vendor ID, Product ID and Rev
+ printf("%.8s %.16s %.4s\r\n", scsi_resp.inquiry.vendor_id, scsi_resp.inquiry.product_id,
+ scsi_resp.inquiry.product_rev);
+
+ // Get capacity of device
+ const uint32_t block_count = tuh_msc_get_block_count(dev_addr, cbw->lun);
+ const uint32_t block_size = tuh_msc_get_block_size(dev_addr, cbw->lun);
+
+ printf("Disk Size: %" PRIu32 " %" PRIu32 "-byte blocks: %" PRIu32 " MB\r\n",
+ block_count, block_size, block_count / ((1024 * 1024) / block_size));
+
+ // For simplicity: we only mount 1 LUN per device
+ const uint8_t drive_num = dev_addr - 1;
+ _mount_pending[drive_num] = true;
+
+ // print the drive label
+ // char label[34];
+ // if ( FR_OK == f_getlabel(drive_path, label, NULL) )
+ // {
+ // puts(label);
+ // }
+
+ return true;
+}
+
+//------------- IMPLEMENTATION -------------//
+void tuh_msc_mount_cb(uint8_t dev_addr) {
+ printf("A MassStorage device (addr = %u) is mounted\r\n", dev_addr);
+
+ const uint8_t lun = 0;
+ tuh_msc_inquiry(dev_addr, lun, &scsi_resp.inquiry, inquiry_complete_cb, 0);
+}
+
+void tuh_msc_umount_cb(uint8_t dev_addr) {
+ printf("A MassStorage device is unmounted\r\n");
+
+ const uint8_t drive_num = dev_addr - 1;
+ char drive_path[3] = "0:";
+ drive_path[0] += drive_num;
+
+ _mount_pending[drive_num] = false;
+
+ f_unmount(drive_path);
+
+ // if ( phy_disk == f_get_current_drive() )
+ // { // active drive is unplugged --> change to other drive
+ // for(uint8_t i=0; i<CFG_TUH_DEVICE_MAX; i++)
+ // {
+ // if ( disk_is_ready(i) )
+ // {
+ // f_chdrive(i);
+ // cli_init(); // refractor, rename
+ // }
+ // }
+ // }
+}
+
+//--------------------------------------------------------------------+
+// DiskIO
+//--------------------------------------------------------------------+
+
+static void wait_for_disk_io(BYTE pdrv) {
+ while (_disk_busy[pdrv]) {
+ vTaskDelay(1);
+ }
+}
+
+static bool disk_io_complete(uint8_t dev_addr, const tuh_msc_complete_data_t *cb_data) {
+ (void)dev_addr;
+ (void)cb_data;
+ _disk_busy[dev_addr - 1] = false;
+ return true;
+}
+
+DSTATUS disk_status(BYTE pdrv /* Physical drive nmuber to identify the drive */
+) {
+ uint8_t dev_addr = pdrv + 1;
+ return tuh_msc_mounted(dev_addr) ? 0 : STA_NODISK;
+}
+
+DSTATUS disk_initialize(BYTE pdrv /* Physical drive nmuber to identify the drive */
+) {
+ (void)pdrv;
+ return 0; // nothing to do
+}
+
+DRESULT disk_read(BYTE pdrv, /* Physical drive nmuber to identify the drive */
+ BYTE *buff, /* Data buffer to store read data */
+ LBA_t sector, /* Start sector in LBA */
+ UINT count /* Number of sectors to read */
+) {
+ const uint8_t dev_addr = pdrv + 1;
+ const uint8_t lun = 0;
+
+ _disk_busy[pdrv] = true;
+ tuh_msc_read10(dev_addr, lun, buff, sector, (uint16_t)count, disk_io_complete, 0);
+ wait_for_disk_io(pdrv);
+
+ return RES_OK;
+}
+
+#if FF_FS_READONLY == 0
+
+DRESULT disk_write(BYTE pdrv, /* Physical drive nmuber to identify the drive */
+ const BYTE *buff, /* Data to be written */
+ LBA_t sector, /* Start sector in LBA */
+ UINT count /* Number of sectors to write */
+) {
+ const uint8_t dev_addr = pdrv + 1;
+ const uint8_t lun = 0;
+
+ _disk_busy[pdrv] = true;
+ tuh_msc_write10(dev_addr, lun, buff, sector, (uint16_t)count, disk_io_complete, 0);
+ wait_for_disk_io(pdrv);
+
+ return RES_OK;
+}
+
+#endif
+
+DRESULT disk_ioctl(BYTE pdrv, /* Physical drive nmuber (0..) */
+ BYTE cmd, /* Control code */
+ void *buff /* Buffer to send/receive control data */
+) {
+ const uint8_t dev_addr = pdrv + 1;
+ const uint8_t lun = 0;
+ switch (cmd) {
+ case CTRL_SYNC:
+ // nothing to do since we do blocking
+ return RES_OK;
+
+ case GET_SECTOR_COUNT:
+ *((DWORD *)buff) = (DWORD)tuh_msc_get_block_count(dev_addr, lun);
+ return RES_OK;
+
+ case GET_SECTOR_SIZE:
+ *((WORD *)buff) = (WORD)tuh_msc_get_block_size(dev_addr, lun);
+ return RES_OK;
+
+ case GET_BLOCK_SIZE:
+ *((DWORD *)buff) = 1; // erase block size in units of sector size
+ return RES_OK;
+
+ default:
+ return RES_PARERR;
+ }
+}
+
+//--------------------------------------------------------------------+
+// CLI Commands
+//--------------------------------------------------------------------+
+
+void cli_cmd_cat(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_cd(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_cp(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_dd(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_ls(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_pwd(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_mkdir(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_mv(EmbeddedCli *cli, char *args, void *context);
+void cli_cmd_rm(EmbeddedCli *cli, char *args, void *context);
+
+static void cli_write_char(EmbeddedCli *cli, char c) {
+ (void)cli;
+ putchar((int)c);
+}
+
+bool cli_init(void) {
+ EmbeddedCliConfig *config = embeddedCliDefaultConfig();
+ config->cliBuffer = cli_buffer;
+ config->cliBufferSize = CLI_BUFFER_SIZE;
+ config->rxBufferSize = CLI_RX_BUFFER_SIZE;
+ config->cmdBufferSize = CLI_CMD_BUFFER_SIZE;
+ config->historyBufferSize = CLI_HISTORY_SIZE;
+ config->maxBindingCount = CLI_BINDING_COUNT;
+
+ TU_ASSERT(embeddedCliRequiredSize(config) <= CLI_BUFFER_SIZE);
+
+ _cli = embeddedCliNew(config);
+ TU_ASSERT(_cli != NULL);
+
+ _cli->writeChar = cli_write_char;
+
+ embeddedCliAddBinding(_cli,
+ (CliCommandBinding){"cat", "Usage: cat [FILE]...\r\n\tConcatenate FILE(s) to standard output..",
+ true, NULL, cli_cmd_cat});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"cd", "Usage: cd [DIR]...\r\n\tChange the current directory to DIR.",
+ true, NULL, cli_cmd_cd});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"cp", "Usage: cp SOURCE DEST\r\n\tCopy SOURCE to DEST.", true, NULL,
+ cli_cmd_cp});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"dd", "Usage: dd [COUNT]\r\n\t" "Read COUNT sectors (default 1024) and report speed.", true, NULL,
+ cli_cmd_dd});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"ls",
+ "Usage: ls [DIR]...\r\n\tList information about the FILEs (the "
+ "current directory by default).",
+ true, NULL, cli_cmd_ls});
+
+ embeddedCliAddBinding(_cli,
+ (CliCommandBinding){"pwd", "Usage: pwd\r\n\tPrint the name of the current working directory.",
+ true, NULL, cli_cmd_pwd});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"mkdir",
+ "Usage: mkdir DIR...\r\n\tCreate the DIRECTORY(ies), if they do not "
+ "already exist..",
+ true, NULL, cli_cmd_mkdir});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"mv", "Usage: mv SOURCE DEST...\r\n\tRename SOURCE to DEST.", true,
+ NULL, cli_cmd_mv});
+
+ embeddedCliAddBinding(_cli, (CliCommandBinding){"rm", "Usage: rm [FILE]...\r\n\tRemove (unlink) the FILE(s).", true,
+ NULL, cli_cmd_rm});
+
+ return true;
+}
+
+void cli_cmd_dd(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint32_t count = 1024; // default sectors to read
+ if (embeddedCliGetTokenCount(args) >= 1) {
+ count = (uint32_t)atoi(embeddedCliGetToken(args, 1));
+ if (count == 0) {
+ count = 1024;
+ }
+ }
+
+ // find first mounted MSC device
+ uint8_t dev_addr = 0;
+ for (uint8_t i = 1; i <= CFG_TUH_DEVICE_MAX; i++) {
+ if (tuh_msc_mounted(i)) {
+ dev_addr = i;
+ break;
+ }
+ }
+ if (dev_addr == 0) {
+ printf("no MSC device mounted\r\n");
+ return;
+ }
+
+ const uint8_t lun = 0;
+ const uint32_t block_size = tuh_msc_get_block_size(dev_addr, lun);
+ const uint32_t block_count = tuh_msc_get_block_count(dev_addr, lun);
+ if (count > block_count) {
+ count = block_count;
+ }
+
+ const uint16_t sectors_per_xfer = (uint16_t)(sizeof(rw_buf) / block_size);
+ const uint32_t xfer_count = (count + sectors_per_xfer - 1) / sectors_per_xfer;
+
+ printf("dd: reading %" PRIu32 " sectors (%" PRIu32 " bytes), %u sectors/xfer ...\r\n",
+ count, count * block_size, sectors_per_xfer);
+
+ const uint32_t start_ms = tusb_time_millis_api();
+ const uint8_t pdrv = dev_addr - 1;
+ bool submit_failed = false;
+
+ for (uint32_t i = 0; i < count; i += sectors_per_xfer) {
+ const uint16_t n = (uint16_t)((count - i < sectors_per_xfer) ? (count - i) : sectors_per_xfer);
+ _disk_busy[pdrv] = true;
+
+ if (!tuh_msc_read10(dev_addr, lun, rw_buf, i, n, disk_io_complete, 0)) {
+ _disk_busy[pdrv] = false;
+ printf("dd: failed to submit read at sector %" PRIu32 " (%u sectors)\r\n", i, n);
+ submit_failed = true;
+ break;
+ }
+
+ wait_for_disk_io(pdrv);
+ }
+
+ if (submit_failed) {
+ return;
+ }
+
+ const uint32_t elapsed_ms = tusb_time_millis_api() - start_ms;
+ const uint32_t total_data = count * block_size;
+ // each SCSI transaction has 31-byte CBW + data + 13-byte CSW
+ const uint32_t total_bus = total_data + xfer_count * (31 + 13);
+
+ if (elapsed_ms > 0) {
+ const uint32_t data_kbs = total_data / elapsed_ms; // KB/s (bytes/ms = KB/s)
+ const uint32_t bus_kbs = total_bus / elapsed_ms;
+ printf("dd: %" PRIu32 " bytes in %" PRIu32 " ms = %" PRIu32 " KB/s (bus %" PRIu32 " KB/s)\r\n",
+ total_data, elapsed_ms, data_kbs, bus_kbs);
+ } else {
+ printf("dd: %" PRIu32 " bytes in <1 ms\r\n", total_data);
+ }
+}
+
+void cli_cmd_cat(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ // need at least 1 argument
+ if (argc == 0) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ for (uint16_t i = 0; i < argc; i++) {
+ FIL *fi = &file1;
+ const char *fpath = embeddedCliGetToken(args, i + 1); // token count from 1
+
+ if (FR_OK != f_open(fi, fpath, FA_READ)) {
+ printf("%s: No such file or directory\r\n", fpath);
+ } else {
+ UINT count = 0;
+ while ((FR_OK == f_read(fi, rw_buf, sizeof(rw_buf), &count)) && (count > 0)) {
+ for (UINT c = 0; c < count; c++) {
+ const uint8_t ch = rw_buf[c];
+ if (isprint(ch) || iscntrl(ch)) {
+ putchar(ch);
+ } else {
+ putchar('.');
+ }
+ }
+ }
+ }
+
+ f_close(fi);
+ }
+}
+
+void cli_cmd_cd(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ // only support 1 argument
+ if (argc != 1) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ // default is current directory
+ const char *dpath = args;
+
+ if (FR_OK != f_chdir(dpath)) {
+ printf("%s: No such file or directory\r\n", dpath);
+ return;
+ }
+}
+
+void cli_cmd_cp(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+ if (argc != 2) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ // default is current directory
+ const char *src = embeddedCliGetToken(args, 1);
+ const char *dst = embeddedCliGetToken(args, 2);
+
+ FIL *f_src = &file1;
+ FIL *f_dst = &file2;
+
+ if (FR_OK != f_open(f_src, src, FA_READ)) {
+ printf("cannot stat '%s': No such file or directory\r\n", src);
+ return;
+ }
+
+ if (FR_OK != f_open(f_dst, dst, FA_WRITE | FA_CREATE_ALWAYS)) {
+ printf("cannot create '%s'\r\n", dst);
+ f_close(f_src);
+ return;
+ } else {
+ UINT rd_count = 0;
+ while ((FR_OK == f_read(f_src, rw_buf, sizeof(rw_buf), &rd_count)) && (rd_count > 0)) {
+ UINT wr_count = 0;
+
+ if (FR_OK != f_write(f_dst, rw_buf, rd_count, &wr_count)) {
+ printf("cannot write to '%s'\r\n", dst);
+ break;
+ }
+ }
+ }
+
+ f_close(f_src);
+ f_close(f_dst);
+}
+
+void cli_cmd_ls(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ // only support 1 argument
+ if (argc > 1) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ // default is current directory
+ const char *dpath = ".";
+ if (argc) {
+ dpath = args;
+ }
+
+ DIR dir;
+ if (FR_OK != f_opendir(&dir, dpath)) {
+ printf("cannot access '%s': No such file or directory\r\n", dpath);
+ return;
+ }
+
+ FILINFO fno;
+ while ((f_readdir(&dir, &fno) == FR_OK) && (fno.fname[0] != 0)) {
+ if (fno.fname[0] != '.') // ignore . and .. entry
+ {
+ if (fno.fattrib & AM_DIR) {
+ // directory
+ printf("/%s\r\n", fno.fname);
+ } else {
+ printf("%-40s", fno.fname);
+ if (fno.fsize < 1024) {
+ printf("%" PRIu32 " B\r\n", fno.fsize);
+ } else {
+ printf("%" PRIu32 " KB\r\n", fno.fsize / 1024);
+ }
+ }
+ }
+ }
+
+ f_closedir(&dir);
+}
+
+void cli_cmd_pwd(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ if (argc != 0) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ char path[256];
+ if (FR_OK != f_getcwd(path, sizeof(path))) {
+ printf("cannot get current working directory\r\n");
+ return;
+ }
+
+ puts(path);
+}
+
+void cli_cmd_mkdir(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ // only support 1 argument
+ if (argc != 1) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ // default is current directory
+ const char *dpath = args;
+
+ if (FR_OK != f_mkdir(dpath)) {
+ printf("%s: cannot create this directory\r\n", dpath);
+ return;
+ }
+}
+
+void cli_cmd_mv(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+ if (argc != 2) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ // default is current directory
+ const char *src = embeddedCliGetToken(args, 1);
+ const char *dst = embeddedCliGetToken(args, 2);
+
+ if (FR_OK != f_rename(src, dst)) {
+ printf("cannot mv %s to %s\r\n", src, dst);
+ return;
+ }
+}
+
+void cli_cmd_rm(EmbeddedCli *cli, char *args, void *context) {
+ (void)cli;
+ (void)context;
+
+ uint16_t argc = embeddedCliGetTokenCount(args);
+
+ // need at least 1 argument
+ if (argc == 0) {
+ printf("invalid arguments\r\n");
+ return;
+ }
+
+ for (uint16_t i = 0; i < argc; i++) {
+ const char *fpath = embeddedCliGetToken(args, i + 1); // token count from 1
+
+ if (FR_OK != f_unlink(fpath)) {
+ printf("cannot remove '%s': No such file or directory\r\n", fpath);
+ }
+ }
+}
diff --git a/examples/host/msc_file_explorer_freertos/src/msc_app.h b/examples/host/msc_file_explorer_freertos/src/msc_app.h
new file mode 100644
index 000000000..eff195b1a
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/msc_app.h
@@ -0,0 +1,34 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2025 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+#ifndef MSC_APP_H
+#define MSC_APP_H
+
+#include <stdbool.h>
+#include <stdio.h>
+
+bool msc_app_init(void);
+
+#endif
diff --git a/examples/host/msc_file_explorer_freertos/src/tusb_config.h b/examples/host/msc_file_explorer_freertos/src/tusb_config.h
new file mode 100644
index 000000000..c3fc4624f
--- /dev/null
+++ b/examples/host/msc_file_explorer_freertos/src/tusb_config.h
@@ -0,0 +1,126 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+
+#ifndef TUSB_CONFIG_H_
+#define TUSB_CONFIG_H_
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+//--------------------------------------------------------------------
+// Common Configuration
+//--------------------------------------------------------------------
+
+// defined by compiler flags for flexibility
+#ifndef CFG_TUSB_MCU
+#error CFG_TUSB_MCU must be defined
+#endif
+
+#ifndef CFG_TUSB_OS
+#define CFG_TUSB_OS OPT_OS_FREERTOS
+#endif
+
+// Espressif IDF requires "freertos/" prefix in include path
+#ifdef ESP_PLATFORM
+#define CFG_TUSB_OS_INC_PATH freertos/
+#endif
+
+#ifndef CFG_TUSB_DEBUG
+#define CFG_TUSB_DEBUG 0
+#endif
+
+/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
+ * Tinyusb use follows macros to declare transferring memory so that they can be put
+ * into those specific section.
+ * e.g
+ * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
+ * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
+ */
+#ifndef CFG_TUH_MEM_SECTION
+#define CFG_TUH_MEM_SECTION
+#endif
+
+#ifndef CFG_TUH_MEM_ALIGN
+#define CFG_TUH_MEM_ALIGN __attribute__ ((aligned(4)))
+#endif
+
+//--------------------------------------------------------------------
+// Host Configuration
+//--------------------------------------------------------------------
+
+// Enable Host stack
+#define CFG_TUH_ENABLED 1
+
+// #define CFG_TUH_MAX3421 1 // use max3421 as host controller
+
+#if CFG_TUSB_MCU == OPT_MCU_RP2040
+ // #define CFG_TUH_RPI_PIO_USB 1 // use pio-usb as host controller
+
+ // host roothub port is 1 if using either pio-usb or max3421
+ #if (defined(CFG_TUH_RPI_PIO_USB) && CFG_TUH_RPI_PIO_USB) || (defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421)
+ #define BOARD_TUH_RHPORT 1
+ #endif
+#endif
+
+// Default is max speed that hardware controller could support with on-chip PHY
+#define CFG_TUH_MAX_SPEED BOARD_TUH_MAX_SPEED
+
+//------------------------- Board Specific --------------------------
+
+// RHPort number used for host can be defined by board.mk, default to port 0
+#ifndef BOARD_TUH_RHPORT
+#define BOARD_TUH_RHPORT 0
+#endif
+
+// RHPort max operational speed can defined by board.mk
+#ifndef BOARD_TUH_MAX_SPEED
+#define BOARD_TUH_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+#endif
+
+//--------------------------------------------------------------------
+// Driver Configuration
+//--------------------------------------------------------------------
+
+// Size of buffer to hold descriptors and other data used for enumeration
+#define CFG_TUH_ENUMERATION_BUFSIZE 256
+
+#define CFG_TUH_HUB 1 // number of supported hubs
+#define CFG_TUH_MSC 1
+#define CFG_TUH_CDC 0
+#define CFG_TUH_HID 0 // typical keyboard + mouse device can have 3-4 HID interfaces
+#define CFG_TUH_VENDOR 0
+
+// max device support (excluding hub device): 1 hub typically has 4 ports
+#define CFG_TUH_DEVICE_MAX (3*CFG_TUH_HUB + 1)
+
+//------------- MSC -------------//
+#define CFG_TUH_MSC_MAXLUN 4 // typical for most card reader
+
+#ifdef __cplusplus
+ }
+#endif
+
+#endif /* TUSB_CONFIG_H_ */
diff --git a/hw/bsp/BoardPresets.json b/hw/bsp/BoardPresets.json
index 86609d075..2ad940caf 100644
--- a/hw/bsp/BoardPresets.json
+++ b/hw/bsp/BoardPresets.json
@@ -6,7 +6,7 @@
"hidden": true,
"description": "Configure preset for the ${presetName} board",
"generator": "Ninja Multi-Config",
- "binaryDir": "${sourceDir}/build/${presetName}",
+ "binaryDir": "${sourceDir}/cmake-build-${presetName}",
"cacheVariables": {
"CMAKE_DEFAULT_BUILD_TYPE": "RelWithDebInfo",
"BOARD": "${presetName}"
@@ -17,7 +17,7 @@
"hidden": true,
"description": "Configure preset for the ${presetName} board",
"generator": "Ninja",
- "binaryDir": "${sourceDir}/build/${presetName}",
+ "binaryDir": "${sourceDir}/cmake-build-${presetName}",
"cacheVariables": {
"BOARD": "${presetName}"
}
@@ -123,6 +123,10 @@
"inherits": "default"
},
{
+ "name": "ch32v103c_bluepill",
+ "inherits": "default"
+ },
+ {
"name": "ch32v103r_r1_1v0",
"inherits": "default"
},
@@ -627,6 +631,10 @@
"inherits": "default"
},
{
+ "name": "stm32c542nucleo",
+ "inherits": "default"
+ },
+ {
"name": "stm32f070rbnucleo",
"inherits": "default"
},
@@ -1088,6 +1096,11 @@
"configurePreset": "ch32f205r-r0"
},
{
+ "name": "ch32v103c_bluepill",
+ "description": "Build preset for the ch32v103c_bluepill board",
+ "configurePreset": "ch32v103c_bluepill"
+ },
+ {
"name": "ch32v103r_r1_1v0",
"description": "Build preset for the ch32v103r_r1_1v0 board",
"configurePreset": "ch32v103r_r1_1v0"
@@ -1763,6 +1776,11 @@
"configurePreset": "stm32c071nucleo"
},
{
+ "name": "stm32c542nucleo",
+ "description": "Build preset for the stm32c542nucleo board",
+ "configurePreset": "stm32c542nucleo"
+ },
+ {
"name": "stm32f070rbnucleo",
"description": "Build preset for the stm32f070rbnucleo board",
"configurePreset": "stm32f070rbnucleo"
@@ -2473,6 +2491,19 @@
]
},
{
+ "name": "ch32v103c_bluepill",
+ "steps": [
+ {
+ "type": "configure",
+ "name": "ch32v103c_bluepill"
+ },
+ {
+ "type": "build",
+ "name": "ch32v103c_bluepill"
+ }
+ ]
+ },
+ {
"name": "ch32v103r_r1_1v0",
"steps": [
{
@@ -4228,6 +4259,19 @@
]
},
{
+ "name": "stm32c542nucleo",
+ "steps": [
+ {
+ "type": "configure",
+ "name": "stm32c542nucleo"
+ },
+ {
+ "type": "build",
+ "name": "stm32c542nucleo"
+ }
+ ]
+ },
+ {
"name": "stm32f070rbnucleo",
"steps": [
{
diff --git a/hw/bsp/at32f402_405/family.c b/hw/bsp/at32f402_405/family.c
index 56d4a7bea..aa1a5b484 100644
--- a/hw/bsp/at32f402_405/family.c
+++ b/hw/bsp/at32f402_405/family.c
@@ -220,7 +220,7 @@ int board_uart_write(void const *buf, int len)
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f403a_407/family.c b/hw/bsp/at32f403a_407/family.c
index 942e15872..cf15ba83a 100644
--- a/hw/bsp/at32f403a_407/family.c
+++ b/hw/bsp/at32f403a_407/family.c
@@ -238,7 +238,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f413/family.c b/hw/bsp/at32f413/family.c
index d9af0ae4d..69591b2ba 100644
--- a/hw/bsp/at32f413/family.c
+++ b/hw/bsp/at32f413/family.c
@@ -238,7 +238,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f415/family.c b/hw/bsp/at32f415/family.c
index ca205d480..132e0db31 100644
--- a/hw/bsp/at32f415/family.c
+++ b/hw/bsp/at32f415/family.c
@@ -212,7 +212,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f423/family.c b/hw/bsp/at32f423/family.c
index 9f13dba07..79ac3fcca 100644
--- a/hw/bsp/at32f423/family.c
+++ b/hw/bsp/at32f423/family.c
@@ -239,7 +239,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f425/family.c b/hw/bsp/at32f425/family.c
index 1629ad7c0..75e53b1f7 100644
--- a/hw/bsp/at32f425/family.c
+++ b/hw/bsp/at32f425/family.c
@@ -220,7 +220,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f435_437/family.c b/hw/bsp/at32f435_437/family.c
index 59a4fe120..80e200363 100644
--- a/hw/bsp/at32f435_437/family.c
+++ b/hw/bsp/at32f435_437/family.c
@@ -265,7 +265,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/at32f45x/family.c b/hw/bsp/at32f45x/family.c
index 27eae861f..42b688b87 100644
--- a/hw/bsp/at32f45x/family.c
+++ b/hw/bsp/at32f45x/family.c
@@ -216,7 +216,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/board.c b/hw/bsp/board.c
index ae58bb5fc..5093382d9 100644
--- a/hw/bsp/board.c
+++ b/hw/bsp/board.c
@@ -51,12 +51,12 @@ int sys_read(int fhdl, char *buf, size_t count) TU_ATTR_USED;
int sys_write(int fhdl, const char *buf, size_t count) {
(void) fhdl;
- return (int) SEGGER_RTT_Write(0, buf, (int) count);
+ return (int) SEGGER_RTT_Write(0, buf, (unsigned) count);
}
int sys_read(int fhdl, char *buf, size_t count) {
(void) fhdl;
- int rd = (int) SEGGER_RTT_Read(0, buf, count);
+ int rd = (int) SEGGER_RTT_Read(0, buf, (unsigned) count);
return (rd > 0) ? rd : -1;
}
#endif
@@ -171,7 +171,7 @@ int board_getchar(void) {
}
int board_putchar(int c) {
- if (board_uart_write((const char *)&c, 1)) {
+ if (board_uart_write((const char *)&c, 1) > 0) {
return c;
} else {
return -1;
diff --git a/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.cmake b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.cmake
new file mode 100644
index 000000000..f6e47ba30
--- /dev/null
+++ b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.cmake
@@ -0,0 +1,8 @@
+set(LD_FLASH_SIZE 64K)
+set(LD_RAM_SIZE 20K)
+
+function(update_board TARGET)
+ target_compile_definitions(${TARGET} PUBLIC
+ CFG_EXAMPLE_MSC_DUAL_READONLY
+ )
+endfunction()
diff --git a/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.h b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.h
new file mode 100644
index 000000000..3a97b44d6
--- /dev/null
+++ b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.h
@@ -0,0 +1,27 @@
+/* Some Chinese manufacturers use CH32V103C8T6 to make Bluepill boards
+ */
+/* metadata:
+ name: CH32V103C8T6-Bluepill
+ url: https://stm32-base.org/boards/STM32F103C8T6-Blue-Pill
+*/
+
+#ifndef BOARD_H_
+#define BOARD_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define LED_PORT GPIOC
+#define LED_PIN GPIO_Pin_13
+#define LED_STATE_ON 0
+
+#define BUTTON_PORT GPIOA
+#define BUTTON_PIN GPIO_Pin_1
+#define BUTTON_STATE_ACTIVE 1
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.mk b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.mk
new file mode 100644
index 000000000..e594f42a7
--- /dev/null
+++ b/hw/bsp/ch32v10x/boards/ch32v103c_bluepill/board.mk
@@ -0,0 +1,5 @@
+CFLAGS += -DCFG_EXAMPLE_MSC_DUAL_READONLY
+
+LDFLAGS += \
+ -Wl,--defsym=__FLASH_SIZE=64K \
+ -Wl,--defsym=__RAM_SIZE=20K \
diff --git a/hw/bsp/ch32v10x/family.c b/hw/bsp/ch32v10x/family.c
index 72dae7086..aa709b0d8 100644
--- a/hw/bsp/ch32v10x/family.c
+++ b/hw/bsp/ch32v10x/family.c
@@ -67,13 +67,20 @@ uint32_t tusb_time_millis_api(void) {
#endif
void board_init(void) {
- __disable_irq();
+ /* Do NOT toggle the global interrupt enable here.
+ * CH32V103 startup enters U-mode (mret with mstatus.MPP=0), so:
+ * - the SDK __disable_irq()/__enable_irq() write mstatus, which faults in U-mode;
+ * - writing CSR 0x800 (INTSYSCR) corrupts the QingKe V3 interrupt-mode config,
+ * which made the USB interrupt vector to a bad address (PC=0) and hang.
+ * The startup already leaves interrupts correctly configured, and machine-mode
+ * interrupts are globally enabled while running in U-mode regardless of mstatus.MIE. */
#if CFG_TUSB_OS == OPT_OS_NONE
SysTick_Config(SystemCoreClock / 1000);
#endif
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
+ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
EXTEN->EXTEN_CTR |= EXTEN_USBFS_IO_EN;
uint8_t usb_div;
@@ -123,8 +130,6 @@ void board_init(void) {
USART_Init(USART1, &usart);
USART_Cmd(USART1, ENABLE);
- __enable_irq();
-
board_led_write(true);
}
@@ -136,6 +141,17 @@ uint32_t board_button_read(void) {
return BUTTON_STATE_ACTIVE == GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN);
}
+size_t board_get_unique_id(uint8_t id[], size_t max_len) {
+ (void) max_len;
+ volatile uint32_t* ch32_uuid = ((volatile uint32_t*) 0x1FFFF7E8UL);
+ uint32_t* serial_32 = (uint32_t*) (uintptr_t) id;
+ serial_32[0] = ch32_uuid[0];
+ serial_32[1] = ch32_uuid[1];
+ serial_32[2] = ch32_uuid[2];
+
+ return 12;
+}
+
int board_uart_read(uint8_t *buf, int len) {
(void) buf;
(void) len;
diff --git a/hw/bsp/ch32v10x/linker/ch32v10x.ld b/hw/bsp/ch32v10x/linker/ch32v10x.ld
index cd5c8dc17..a2de3c25f 100644
--- a/hw/bsp/ch32v10x/linker/ch32v10x.ld
+++ b/hw/bsp/ch32v10x/linker/ch32v10x.ld
@@ -13,6 +13,7 @@ ENTRY( _start )
__stack_size = 2048;
PROVIDE( _stack_size = __stack_size );
+_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
@@ -150,16 +151,16 @@ SECTIONS
PROVIDE( _ebss = .);
} >RAM AT>FLASH
- PROVIDE( _end = _ebss);
- PROVIDE( end = . );
-
- .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size :
- {
- PROVIDE( _heap_end = . );
- . = ALIGN(4);
- PROVIDE(_susrstack = . );
- . = . + __stack_size;
- PROVIDE( _eusrstack = .);
- } >RAM
+ ._user_heap_stack :
+ {
+ . = ALIGN(8);
+ PROVIDE( end = . );
+ PROVIDE( _end = . );
+ . = . + __stack_size;
+ . = ALIGN(8);
+ } >RAM
+ PROVIDE( _heap_end = ORIGIN(RAM) + LENGTH(RAM) - __stack_size );
+ PROVIDE( _susrstack = _heap_end );
+ PROVIDE( _eusrstack = ORIGIN(RAM) + LENGTH(RAM) );
}
diff --git a/hw/bsp/ch32v20x/family.c b/hw/bsp/ch32v20x/family.c
index 221f62107..76024cfde 100644
--- a/hw/bsp/ch32v20x/family.c
+++ b/hw/bsp/ch32v20x/family.c
@@ -220,6 +220,6 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/ch32v20x/family.cmake b/hw/bsp/ch32v20x/family.cmake
index 59a96f70d..785f5ee35 100644
--- a/hw/bsp/ch32v20x/family.cmake
+++ b/hw/bsp/ch32v20x/family.cmake
@@ -61,8 +61,9 @@ function(family_add_board BOARD_TARGET)
if (RHPORT_DEVICE EQUAL 0)
target_compile_definitions(${BOARD_TARGET} PUBLIC CFG_TUD_WCH_USBIP_FSDEV=1)
+ target_compile_definitions(${BOARD_TARGET} PUBLIC CFG_TUH_WCH_USBIP_FSDEV=1)
elseif (RHPORT_DEVICE EQUAL 1)
- target_compile_definitions(${BOARD_TARGET} PUBLIC CFG_TUH_WCH_USBIP_USBFS=1)
+ target_compile_definitions(${BOARD_TARGET} PUBLIC CFG_TUD_WCH_USBIP_USBFS=1)
else()
message(FATAL_ERROR "Invalid RHPORT_DEVICE ${RHPORT_DEVICE}")
endif()
diff --git a/hw/bsp/ch32v20x/linker/ch32v20x.ld b/hw/bsp/ch32v20x/linker/ch32v20x.ld
index f84808b0d..bfa9a8436 100644
--- a/hw/bsp/ch32v20x/linker/ch32v20x.ld
+++ b/hw/bsp/ch32v20x/linker/ch32v20x.ld
@@ -12,6 +12,7 @@ MEMORY
ENTRY( _start )
PROVIDE( _stack_size = __stack_size );
+_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
@@ -149,16 +150,16 @@ SECTIONS
PROVIDE( _ebss = .);
} >RAM AT>FLASH
- PROVIDE( _end = _ebss);
- PROVIDE( end = . );
-
- .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size :
- {
- PROVIDE( _heap_end = . );
- . = ALIGN(4);
- PROVIDE(_susrstack = . );
- . = . + __stack_size;
- PROVIDE( _eusrstack = .);
- } >RAM
+ ._user_heap_stack :
+ {
+ . = ALIGN(8);
+ PROVIDE( end = . );
+ PROVIDE( _end = . );
+ . = . + __stack_size;
+ . = ALIGN(8);
+ } >RAM
+ PROVIDE( _heap_end = ORIGIN(RAM) + LENGTH(RAM) - __stack_size );
+ PROVIDE( _susrstack = _heap_end );
+ PROVIDE( _eusrstack = ORIGIN(RAM) + LENGTH(RAM) );
}
diff --git a/hw/bsp/ch32v30x/linker/ch32v30x.ld b/hw/bsp/ch32v30x/linker/ch32v30x.ld
index 6dd5d344a..2941c41a0 100644
--- a/hw/bsp/ch32v30x/linker/ch32v30x.ld
+++ b/hw/bsp/ch32v30x/linker/ch32v30x.ld
@@ -12,6 +12,7 @@ MEMORY
ENTRY( _start )
PROVIDE( _stack_size = __stack_size );
+_estack = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
@@ -151,17 +152,16 @@ SECTIONS
PROVIDE( _ebss = .);
} >RAM AT>FLASH
- PROVIDE( _end = _ebss);
- PROVIDE( end = . );
-
- .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size :
- {
- PROVIDE( _heap_end = . );
- . = ALIGN(4);
- PROVIDE(_susrstack = . );
- . = . + __stack_size;
- PROVIDE( _eusrstack = .);
- __freertos_irq_stack_top = .;
- } >RAM
+ ._user_heap_stack :
+ {
+ . = ALIGN(8);
+ PROVIDE( end = . );
+ PROVIDE( _end = . );
+ . = . + __stack_size;
+ . = ALIGN(8);
+ } >RAM
+ PROVIDE( _heap_end = ORIGIN(RAM) + LENGTH(RAM) - __stack_size );
+ PROVIDE( _susrstack = _heap_end );
+ PROVIDE( _eusrstack = ORIGIN(RAM) + LENGTH(RAM) );
}
diff --git a/hw/bsp/ch583/boards/ch582m_evt/board.cmake b/hw/bsp/ch583/boards/ch582m_evt/board.cmake
new file mode 100644
index 000000000..4129c4550
--- /dev/null
+++ b/hw/bsp/ch583/boards/ch582m_evt/board.cmake
@@ -0,0 +1,5 @@
+set(LD_FLASH_SIZE 448K)
+set(LD_RAM_SIZE 32K)
+
+function(update_board TARGET)
+endfunction()
diff --git a/hw/bsp/ch583/boards/ch582m_evt/board.h b/hw/bsp/ch583/boards/ch582m_evt/board.h
new file mode 100644
index 000000000..c3483bf17
--- /dev/null
+++ b/hw/bsp/ch583/boards/ch582m_evt/board.h
@@ -0,0 +1,61 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/* metadata:
+ name: CH582M-EVT evaluation board
+ url: https://www.wch-ic.com/products/CH582.html
+*/
+
+#ifndef BOARD_H_
+#define BOARD_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// LED: PB4 on CH582M-EVT
+#define LED_PIN GPIO_Pin_4
+#define LED_STATE_ON 0
+
+// Directly reuse BOOT pin as user button
+#define BUTTON_PIN GPIO_Pin_22
+#define BUTTON_STATE_ACTIVE 0
+
+// UART: UART1 TX=PA9, RX=PA8
+#define CFG_BOARD_UART_BAUDRATE 115200
+
+// Device only on USB1 (rhport 0). CH58x host / USB2 is not supported by the shared usbfs dcd;
+// BOARD_TUH_RHPORT is kept commented out to ease re-adding host later.
+#ifndef BOARD_TUD_RHPORT
+#define BOARD_TUD_RHPORT 0
+#endif
+// #ifndef BOARD_TUH_RHPORT
+// #define BOARD_TUH_RHPORT 1
+// #endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/hw/bsp/ch583/boards/ch582m_evt/board.mk b/hw/bsp/ch583/boards/ch582m_evt/board.mk
new file mode 100644
index 000000000..a13979799
--- /dev/null
+++ b/hw/bsp/ch583/boards/ch582m_evt/board.mk
@@ -0,0 +1,3 @@
+LDFLAGS += \
+ -Wl,--defsym=__FLASH_SIZE=448K \
+ -Wl,--defsym=__RAM_SIZE=32K \
diff --git a/hw/bsp/ch583/boards/yd-ch582m/board.cmake b/hw/bsp/ch583/boards/yd-ch582m/board.cmake
new file mode 100644
index 000000000..4129c4550
--- /dev/null
+++ b/hw/bsp/ch583/boards/yd-ch582m/board.cmake
@@ -0,0 +1,5 @@
+set(LD_FLASH_SIZE 448K)
+set(LD_RAM_SIZE 32K)
+
+function(update_board TARGET)
+endfunction()
diff --git a/hw/bsp/ch583/boards/yd-ch582m/board.h b/hw/bsp/ch583/boards/yd-ch582m/board.h
new file mode 100644
index 000000000..0da5747bc
--- /dev/null
+++ b/hw/bsp/ch583/boards/yd-ch582m/board.h
@@ -0,0 +1,61 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/* metadata:
+ name: yd-ch582m from vcc-gnd studio
+ url: http://vcc-gnd.com/
+*/
+
+#ifndef BOARD_H_
+#define BOARD_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// LED: PB4 on yd-ch582m board
+#define LED_PIN GPIO_Pin_4
+#define LED_STATE_ON 0
+
+// Directly reuse BOOT pin as user button
+#define BUTTON_PIN GPIO_Pin_22
+#define BUTTON_STATE_ACTIVE 0
+
+// UART: UART1 TX=PA9, RX=PA8
+#define CFG_BOARD_UART_BAUDRATE 115200
+
+// Device only on USB1 (rhport 0). CH58x host / USB2 is not supported by the shared usbfs dcd;
+// BOARD_TUH_RHPORT is kept commented out to ease re-adding host later.
+#ifndef BOARD_TUD_RHPORT
+#define BOARD_TUD_RHPORT 0
+#endif
+// #ifndef BOARD_TUH_RHPORT
+// #define BOARD_TUH_RHPORT 1
+// #endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/hw/bsp/ch583/boards/yd-ch582m/board.mk b/hw/bsp/ch583/boards/yd-ch582m/board.mk
new file mode 100644
index 000000000..a13979799
--- /dev/null
+++ b/hw/bsp/ch583/boards/yd-ch582m/board.mk
@@ -0,0 +1,3 @@
+LDFLAGS += \
+ -Wl,--defsym=__FLASH_SIZE=448K \
+ -Wl,--defsym=__RAM_SIZE=32K \
diff --git a/hw/bsp/ch583/ch583_it.c b/hw/bsp/ch583/ch583_it.c
new file mode 100644
index 000000000..8479c537a
--- /dev/null
+++ b/hw/bsp/ch583/ch583_it.c
@@ -0,0 +1,37 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "ch583_it.h"
+
+// NMI exception handler
+__INTERRUPT __HIGH_CODE void NMI_Handler(void) {
+ while (1) {}
+}
+
+// Hard Fault exception handler
+__INTERRUPT __HIGH_CODE void HardFault_Handler(void) {
+ while (1) {}
+}
diff --git a/hw/bsp/ch583/ch583_it.h b/hw/bsp/ch583/ch583_it.h
new file mode 100644
index 000000000..29d175403
--- /dev/null
+++ b/hw/bsp/ch583/ch583_it.h
@@ -0,0 +1,46 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef CH583_IT_H_
+#define CH583_IT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "CH58x_common.h"
+
+void NMI_Handler(void);
+void HardFault_Handler(void);
+void USB_IRQHandler(void);
+// void USB2_IRQHandler(void); // host on USB2 (rhport 1) — re-add together with the host driver
+void SysTick_Handler(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CH583_IT_H_ */
diff --git a/hw/bsp/ch583/debug_uart.c b/hw/bsp/ch583/debug_uart.c
new file mode 100644
index 000000000..850e40718
--- /dev/null
+++ b/hw/bsp/ch583/debug_uart.c
@@ -0,0 +1,86 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "debug_uart.h"
+#include "CH58x_common.h"
+
+//--------------------------------------------------------------------+
+// Ring buffer based UART TX for non-blocking writes
+//--------------------------------------------------------------------+
+
+#define UART_RINGBUFFER_SIZE_TX 128
+#define UART_RINGBUFFER_MASK_TX (UART_RINGBUFFER_SIZE_TX - 1)
+
+static char tx_buf[UART_RINGBUFFER_SIZE_TX];
+static uint32_t tx_produce;
+static volatile uint32_t tx_consume;
+
+void uart_write(char c) {
+ uint32_t tx_produce_next = (tx_produce + 1) & UART_RINGBUFFER_MASK_TX;
+
+ // If the ring buffer is full, drain it here as the FIFO frees up: nothing else advances
+ // tx_consume between uart_write() calls, so a plain spin would deadlock on a >buffer-size burst.
+ while (tx_produce_next == tx_consume) {
+ if (R8_UART1_LSR & RB_LSR_TX_FIFO_EMP) {
+ R8_UART1_THR = tx_buf[tx_consume];
+ tx_consume = (tx_consume + 1) & UART_RINGBUFFER_MASK_TX;
+ }
+ }
+
+ // If UART TX FIFO is empty and no pending data, send directly
+ if ((tx_consume == tx_produce) && (R8_UART1_LSR & RB_LSR_TX_FIFO_EMP)) {
+ R8_UART1_THR = c;
+ } else {
+ tx_buf[tx_produce] = c;
+ tx_produce = tx_produce_next;
+ }
+}
+
+void uart_sync(void) {
+ // Wait for ring buffer to drain
+ while (tx_consume != tx_produce) {
+ if (R8_UART1_LSR & RB_LSR_TX_FIFO_EMP) {
+ R8_UART1_THR = tx_buf[tx_consume];
+ tx_consume = (tx_consume + 1) & UART_RINGBUFFER_MASK_TX;
+ }
+ }
+ // Wait for last byte to finish transmitting
+ while (!(R8_UART1_LSR & RB_LSR_TX_ALL_EMP)) {}
+}
+
+void usart_printf_init(uint32_t baudrate) {
+ tx_produce = 0;
+ tx_consume = 0;
+
+ // Configure UART1 pins: TX=PA9, RX=PA8
+ GPIOA_SetBits(GPIO_Pin_9);
+ GPIOA_ModeCfg(GPIO_Pin_9, GPIO_ModeOut_PP_5mA);
+ GPIOA_ModeCfg(GPIO_Pin_8, GPIO_ModeIN_PU);
+
+ // Init UART1 with specified baud rate
+ UART1_DefInit();
+ UART1_BaudRateCfg(baudrate);
+}
diff --git a/hw/bsp/ch583/debug_uart.h b/hw/bsp/ch583/debug_uart.h
new file mode 100644
index 000000000..44c3e7948
--- /dev/null
+++ b/hw/bsp/ch583/debug_uart.h
@@ -0,0 +1,44 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef DEBUG_UART_H_
+#define DEBUG_UART_H_
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void uart_write(char c);
+void uart_sync(void);
+void usart_printf_init(uint32_t baudrate);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* DEBUG_UART_H_ */
diff --git a/hw/bsp/ch583/family.c b/hw/bsp/ch583/family.c
new file mode 100644
index 000000000..716e2b76b
--- /dev/null
+++ b/hw/bsp/ch583/family.c
@@ -0,0 +1,194 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+/* metadata:
+ manufacturer: WCH
+*/
+
+// WCH SDK's DEBUG macro enables a _write() that conflicts with TinyUSB's.
+// TinyUSB uses UART1 for printf via debug_uart.c, so DEBUG is not needed.
+// If you need a different UART or want to keep SDK's DEBUG, modify
+// debug_uart.c (TinyUSB side) or CH58x_sys.c (SDK side) to remove one _write().
+// If done, remove this #error to continue.
+#ifdef DEBUG
+ #error "Remove the DEBUG macro from preprocessor defines to avoid " \
+ "duplicate _write() between WCH SDK and TinyUSB. " \
+ "TinyUSB uses UART1 by default (see debug_uart.c)."
+#endif
+
+#include "debug_uart.h"
+#include "CH58x_common.h"
+#include "ch583_it.h"
+
+#include "bsp/board_api.h"
+#include "board.h"
+
+//--------------------------------------------------------------------+
+// Forward USB interrupt events to TinyUSB IRQ Handler
+//--------------------------------------------------------------------+
+
+// Device only: the shared dcd_ch32_usbfs.c drives USB0 (rhport 0). CH58x's second controller
+// (USB2 / rhport 1) was driven by the now-removed ch58x host driver; its handler is kept
+// commented out below to ease re-adding host support.
+__INTERRUPT __HIGH_CODE void USB_IRQHandler(void) {
+ tusb_int_handler(0, true);
+}
+
+// __INTERRUPT __HIGH_CODE void USB2_IRQHandler(void) {
+// tusb_int_handler(1, true);
+// }
+
+//--------------------------------------------------------------------+
+// SysTick
+//--------------------------------------------------------------------+
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+volatile uint32_t system_ticks = 0;
+
+__INTERRUPT __HIGH_CODE void SysTick_Handler(void) {
+ SysTick->SR = 0;
+ system_ticks++;
+}
+
+uint32_t tusb_time_millis_api(void) {
+ return system_ticks;
+}
+#endif
+
+//--------------------------------------------------------------------+
+// Board Init
+//--------------------------------------------------------------------+
+
+void board_init(void) {
+ // Disable interrupts during init
+ PFIC_DisableAllIRQ();
+
+ // Set system clock to PLL 60MHz (default for CH582)
+ SetSysClock(CLK_SOURCE_PLL_60MHz);
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+ SysTick_Config(GetSysClock() / 1000);
+#endif
+
+ // UART1 init for debug output
+#ifdef CFG_BOARD_UART_BAUDRATE
+ usart_printf_init(CFG_BOARD_UART_BAUDRATE);
+#endif
+
+ // LED
+#ifdef LED_PORT_IS_A
+ GPIOA_ModeCfg(LED_PIN, GPIO_ModeOut_PP_5mA);
+#else
+ GPIOB_ModeCfg(LED_PIN, GPIO_ModeOut_PP_5mA);
+#endif
+
+ // Button
+#ifdef BUTTON_PIN
+ #ifdef BUTTON_PORT_IS_A
+ GPIOA_ModeCfg(BUTTON_PIN, GPIO_ModeIN_PU);
+ #else
+ GPIOB_ModeCfg(BUTTON_PIN, GPIO_ModeIN_PU);
+ #endif
+#endif
+
+ // Device only on USB0 (rhport 0): enable analog function for USB1 D+/D- and assert its D+
+ // pull-up. The shared dcd_ch32_usbfs.c drives USB0; CH58x host / USB2 (rhport 1) is unsupported
+ // here — to re-add host, also OR in RB_PIN_USB2_IE below.
+ R16_PIN_ANALOG_IE |= RB_PIN_USB_IE; // | RB_PIN_USB2_IE (re-add for host on USB2)
+#if CFG_TUD_ENABLED
+ R16_PIN_ANALOG_IE |= RB_PIN_USB_DP_PU;
+#endif
+
+ // Keep USB clock active during sleep
+ R8_SLP_CLK_OFF1 &= ~RB_SLP_CLK_USB;
+
+ // Enable interrupts globally
+ PFIC_EnableAllIRQ();
+
+ board_delay(2);
+}
+
+//--------------------------------------------------------------------+
+// Board porting API
+//--------------------------------------------------------------------+
+
+void board_led_write(bool state) {
+#ifdef LED_PORT_IS_A
+ if (state ^ LED_STATE_ON) {
+ GPIOA_ResetBits(LED_PIN);
+ } else {
+ GPIOA_SetBits(LED_PIN);
+ }
+#else
+ if (state ^ LED_STATE_ON) {
+ GPIOB_ResetBits(LED_PIN);
+ } else {
+ GPIOB_SetBits(LED_PIN);
+ }
+#endif
+}
+
+uint32_t board_button_read(void) {
+#ifdef BUTTON_PIN
+ #ifdef BUTTON_PORT_IS_A
+ return BUTTON_STATE_ACTIVE == (GPIOA_ReadPortPin(BUTTON_PIN) ? 1 : 0);
+ #else
+ return BUTTON_STATE_ACTIVE == (GPIOB_ReadPortPin(BUTTON_PIN) ? 1 : 0);
+ #endif
+#else
+ return 0;
+#endif
+}
+
+// CH58x has no memory-mapped unique-ID register (unlike ch32v10x/v20x at 0x1FFFF7E8), but the
+// factory programs a unique 6-byte MAC address into FlashROM (it is a BLE part). GetMACAddress()
+// reads it via the ISP ROM command FLASH_EEPROM_CMD, which is provided by libISP583.a.
+size_t board_get_unique_id(uint8_t id[], size_t max_len) {
+ // FLASH_EEPROM_CMD writes word-granular and requires a 4-byte-aligned buffer (CH58x_flash.c);
+ // size 8 matches the SDK's GET_UNIQUE_ID buffer (6 MAC bytes + 2 it pads), so the read can't
+ // run past the end whether it returns 6 or a full 8.
+ TU_ATTR_ALIGNED(4) uint8_t mac[8];
+ GetMACAddress(mac);
+ size_t len = TU_MIN(max_len, (size_t) 6); // the 6-byte MAC is the unique part
+ memcpy(id, mac, len);
+ return len;
+}
+
+int board_uart_read(uint8_t* buf, int len) {
+ (void) buf;
+ (void) len;
+ return 0;
+}
+
+int board_uart_write(void const* buf, int len) {
+ int txsize = len;
+ const char* bufc = (const char*) buf;
+ while (txsize--) {
+ uart_write(*bufc++);
+ }
+ uart_sync();
+ return len;
+}
diff --git a/hw/bsp/ch583/family.cmake b/hw/bsp/ch583/family.cmake
new file mode 100644
index 000000000..a379298e5
--- /dev/null
+++ b/hw/bsp/ch583/family.cmake
@@ -0,0 +1,108 @@
+include_guard()
+
+set(SDK_DIR ${TOP}/hw/mcu/wch/ch583)
+set(SDK_SRC_DIR ${SDK_DIR}/EVT/EXAM/SRC)
+
+# include board specific
+include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake)
+
+# toolchain set up
+set(CMAKE_SYSTEM_CPU rv32imac-ilp32 CACHE INTERNAL "System Processor")
+set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/riscv_${TOOLCHAIN}.cmake)
+
+set(FAMILY_MCUS CH583 CACHE INTERNAL "")
+set(OPENOCD_OPTION "-f ${CMAKE_CURRENT_LIST_DIR}/wch-riscv.cfg")
+
+#------------------------------------
+# Startup & Linker script
+#------------------------------------
+if (NOT DEFINED LD_FILE_GNU)
+ set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/linker/ch582.ld)
+endif ()
+set(LD_FILE_Clang ${LD_FILE_GNU})
+if (NOT DEFINED STARTUP_FILE_GNU)
+ set(STARTUP_FILE_GNU ${SDK_SRC_DIR}/Startup/startup_CH583.S)
+endif ()
+set(STARTUP_FILE_Clang ${STARTUP_FILE_GNU})
+
+#------------------------------------
+# Board Target
+#------------------------------------
+function(family_add_board BOARD_TARGET)
+ add_library(${BOARD_TARGET} STATIC
+ ${SDK_SRC_DIR}/StdPeriphDriver/CH58x_gpio.c
+ ${SDK_SRC_DIR}/StdPeriphDriver/CH58x_clk.c
+ ${SDK_SRC_DIR}/StdPeriphDriver/CH58x_uart1.c
+ ${SDK_SRC_DIR}/StdPeriphDriver/CH58x_sys.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/ch583_it.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/system_ch583.c
+ )
+ target_include_directories(${BOARD_TARGET} PUBLIC
+ ${SDK_SRC_DIR}/RVMSIS
+ ${SDK_SRC_DIR}/StdPeriphDriver/inc
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}
+ )
+ target_link_libraries(${BOARD_TARGET} PUBLIC
+ ${SDK_SRC_DIR}/StdPeriphDriver/libISP583.a
+ )
+ target_compile_definitions(${BOARD_TARGET} PUBLIC
+ CFG_TUD_WCH_USBIP_USBFS=1
+ FREQ_SYS=60000000
+ DISK_LIB_ENABLE=0
+ INT_SOFT
+ )
+
+ update_board(${BOARD_TARGET})
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
+ target_compile_options(${BOARD_TARGET} PUBLIC
+ -flto
+ -msmall-data-limit=16
+ -mno-save-restore
+ -fmessage-length=0
+ -fsigned-char
+ -Wno-error=strict-prototypes
+ )
+ endif ()
+endfunction()
+
+#------------------------------------
+# Functions
+#------------------------------------
+function(family_configure_example TARGET RTOS)
+ family_configure_common(${TARGET} ${RTOS})
+ family_add_tinyusb(${TARGET} OPT_MCU_CH583)
+
+ target_sources(${TARGET} PUBLIC
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/debug_uart.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c
+ ${TOP}/src/portable/wch/dcd_ch32_usbfs.c
+ ${STARTUP_FILE_${CMAKE_C_COMPILER_ID}}
+ )
+ target_include_directories(${TARGET} PUBLIC
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}
+ )
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
+ target_link_options(${TARGET} PUBLIC
+ -nostartfiles
+ --specs=nosys.specs --specs=nano.specs
+ -Wl,--defsym=__FLASH_SIZE=${LD_FLASH_SIZE}
+ -Wl,--defsym=__RAM_SIZE=${LD_RAM_SIZE}
+ "LINKER:--script=${LD_FILE_GNU}"
+ )
+ elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ message(FATAL_ERROR "Clang is not supported for CH58x")
+ endif ()
+
+ set_source_files_properties(${STARTUP_FILE_${CMAKE_C_COMPILER_ID}} PROPERTIES
+ SKIP_LINTING ON
+ COMPILE_OPTIONS -w)
+
+ # Flashing
+ family_add_bin_hex(${TARGET})
+ family_flash_openocd_wch(${TARGET})
+endfunction()
diff --git a/hw/bsp/ch583/family.mk b/hw/bsp/ch583/family.mk
new file mode 100644
index 000000000..98d0f9337
--- /dev/null
+++ b/hw/bsp/ch583/family.mk
@@ -0,0 +1,59 @@
+# https://www.embecosm.com/resources/tool-chain-downloads/#riscv-stable
+#CROSS_COMPILE ?= riscv32-unknown-elf-
+
+# Toolchain from https://nucleisys.com/download.php
+#CROSS_COMPILE ?= riscv-nuclei-elf-
+
+# Toolchain from https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack
+CROSS_COMPILE ?= riscv-none-elf-
+
+SDK_DIR = hw/mcu/wch/ch583
+SDK_SRC_DIR = $(SDK_DIR)/EVT/EXAM/SRC
+
+include $(TOP)/$(BOARD_PATH)/board.mk
+CPU_CORE ?= rv32imac-ilp32
+
+CFLAGS += \
+ -flto \
+ -msmall-data-limit=16 \
+ -mno-save-restore \
+ -fmessage-length=0 \
+ -fsigned-char \
+ -DCFG_TUSB_MCU=OPT_MCU_CH583 \
+ -DCFG_TUD_WCH_USBIP_USBFS=1 \
+ -DFREQ_SYS=60000000 \
+ -DDISK_LIB_ENABLE=0 \
+ -DINT_SOFT \
+ -Wno-error=strict-prototypes
+
+LDFLAGS += \
+ -nostartfiles \
+ --specs=nosys.specs --specs=nano.specs
+
+LIBS += $(TOP)/$(SDK_SRC_DIR)/StdPeriphDriver/libISP583.a
+
+SRC_C += \
+ src/portable/wch/dcd_ch32_usbfs.c \
+ $(SDK_SRC_DIR)/StdPeriphDriver/CH58x_gpio.c \
+ $(SDK_SRC_DIR)/StdPeriphDriver/CH58x_clk.c \
+ $(SDK_SRC_DIR)/StdPeriphDriver/CH58x_uart1.c \
+ $(SDK_SRC_DIR)/StdPeriphDriver/CH58x_sys.c \
+ $(FAMILY_PATH)/debug_uart.c \
+ $(FAMILY_PATH)/ch583_it.c \
+ $(FAMILY_PATH)/system_ch583.c
+
+SRC_S += \
+ $(SDK_SRC_DIR)/Startup/startup_CH583.S
+
+INC += \
+ $(TOP)/$(BOARD_PATH) \
+ $(TOP)/$(SDK_SRC_DIR)/RVMSIS \
+ $(TOP)/$(SDK_SRC_DIR)/StdPeriphDriver/inc
+
+LD_FILE ?= $(FAMILY_PATH)/linker/ch582.ld
+
+OPENOCD_WCH_OPTION=-f $(TOP)/$(FAMILY_PATH)/wch-riscv.cfg
+flash: flash-openocd-wch
+
+# For freeRTOS port source
+FREERTOS_PORTABLE_SRC = $(FREERTOS_PORTABLE_PATH)/RISC-V
diff --git a/hw/bsp/ch583/linker/ch582.ld b/hw/bsp/ch583/linker/ch582.ld
new file mode 100644
index 000000000..821998a49
--- /dev/null
+++ b/hw/bsp/ch583/linker/ch582.ld
@@ -0,0 +1,167 @@
+/* CH582 Linker Script for TinyUSB
+ * Based on WCH CH583 SDK Link.ld
+ * Supports parameterized flash/ram sizes via --defsym
+ */
+
+/* Default sizes if not provided via --defsym */
+__flash_size = DEFINED(__FLASH_SIZE) ? __FLASH_SIZE : 448K;
+__ram_size = DEFINED(__RAM_SIZE) ? __RAM_SIZE : 32K;
+__stack_size = DEFINED(__STACK_SIZE) ? __STACK_SIZE : 2048;
+
+ENTRY( _start )
+
+PROVIDE( _stack_size = __stack_size );
+
+MEMORY
+{
+ FLASH (rx) : ORIGIN = 0x00000000, LENGTH = __flash_size
+ RAM (xrw) : ORIGIN = 0x20000000, LENGTH = __ram_size
+}
+
+SECTIONS
+{
+ .init :
+ {
+ _sinit = .;
+ . = ALIGN(4);
+ KEEP(*(SORT_NONE(.init)))
+ . = ALIGN(4);
+ _einit = .;
+ } >FLASH AT>FLASH
+
+ .highcodelalign :
+ {
+ . = ALIGN(4);
+ PROVIDE(_highcode_lma = .);
+ } >FLASH AT>FLASH
+
+ .highcode :
+ {
+ . = ALIGN(4);
+ PROVIDE(_highcode_vma_start = .);
+ *(.vector);
+ KEEP(*(SORT_NONE(.vector_handler)))
+ *(.highcode);
+ *(.highcode.*);
+ . = ALIGN(4);
+ PROVIDE(_highcode_vma_end = .);
+ } >RAM AT>FLASH
+
+ .text :
+ {
+ . = ALIGN(4);
+ KEEP(*(SORT_NONE(.handle_reset)))
+ *(.text)
+ *(.text.*)
+ *(.rodata)
+ *(.rodata*)
+ *(.sdata2.*)
+ *(.glue_7)
+ *(.glue_7t)
+ *(.gnu.linkonce.t.*)
+ . = ALIGN(4);
+ } >FLASH AT>FLASH
+
+ .fini :
+ {
+ KEEP(*(SORT_NONE(.fini)))
+ . = ALIGN(4);
+ } >FLASH AT>FLASH
+
+ PROVIDE( _etext = . );
+ PROVIDE( _eitcm = . );
+
+ .preinit_array :
+ {
+ PROVIDE_HIDDEN (__preinit_array_start = .);
+ KEEP (*(.preinit_array))
+ PROVIDE_HIDDEN (__preinit_array_end = .);
+ } >FLASH AT>FLASH
+
+ .init_array :
+ {
+ PROVIDE_HIDDEN (__init_array_start = .);
+ KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*)))
+ KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors))
+ PROVIDE_HIDDEN (__init_array_end = .);
+ } >FLASH AT>FLASH
+
+ .fini_array :
+ {
+ PROVIDE_HIDDEN (__fini_array_start = .);
+ KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*)))
+ KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors))
+ PROVIDE_HIDDEN (__fini_array_end = .);
+ } >FLASH AT>FLASH
+
+ .ctors :
+ {
+ KEEP (*crtbegin.o(.ctors))
+ KEEP (*crtbegin?.o(.ctors))
+ KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors))
+ KEEP (*(SORT(.ctors.*)))
+ KEEP (*(.ctors))
+ } >FLASH AT>FLASH
+
+ .dtors :
+ {
+ KEEP (*crtbegin.o(.dtors))
+ KEEP (*crtbegin?.o(.dtors))
+ KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors))
+ KEEP (*(SORT(.dtors.*)))
+ KEEP (*(.dtors))
+ } >FLASH AT>FLASH
+
+ .dlalign :
+ {
+ . = ALIGN(4);
+ PROVIDE(_data_lma = .);
+ } >FLASH AT>FLASH
+
+ .data :
+ {
+ . = ALIGN(4);
+ PROVIDE(_data_vma = .);
+ *(.gnu.linkonce.r.*)
+ *(.data .data.*)
+ *(.gnu.linkonce.d.*)
+ . = ALIGN(8);
+ PROVIDE( __global_pointer$ = . + 0x800 );
+ *(.sdata .sdata.*)
+ *(.gnu.linkonce.s.*)
+ . = ALIGN(8);
+ *(.srodata.cst16)
+ *(.srodata.cst8)
+ *(.srodata.cst4)
+ *(.srodata.cst2)
+ *(.srodata .srodata.*)
+ . = ALIGN(4);
+ PROVIDE( _edata = .);
+ } >RAM AT>FLASH
+
+ .bss :
+ {
+ . = ALIGN(4);
+ PROVIDE( _sbss = .);
+ *(.sbss*)
+ *(.gnu.linkonce.sb.*)
+ *(.bss*)
+ *(.gnu.linkonce.b.*)
+ *(COMMON*)
+ . = ALIGN(4);
+ PROVIDE( _ebss = .);
+ } >RAM AT>FLASH
+
+ PROVIDE( _end = _ebss);
+ PROVIDE( end = . );
+
+ .stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size :
+ {
+ PROVIDE( _heap_end = . );
+ . = ALIGN(4);
+ PROVIDE(_susrstack = . );
+ . = . + __stack_size;
+ PROVIDE( _eusrstack = .);
+ __freertos_irq_stack_top = .;
+ } >RAM
+}
diff --git a/hw/bsp/ch583/system_ch583.c b/hw/bsp/ch583/system_ch583.c
new file mode 100644
index 000000000..d3724f0ce
--- /dev/null
+++ b/hw/bsp/ch583/system_ch583.c
@@ -0,0 +1,39 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "CH58x_common.h"
+#include "system_ch583.h"
+
+uint32_t SystemCoreClock = FREQ_SYS;
+
+void SystemInit(void) {
+ SetSysClock(CLK_SOURCE_PLL_60MHz);
+ SystemCoreClock = GetSysClock();
+}
+
+void SystemCoreClockUpdate(void) {
+ SystemCoreClock = GetSysClock();
+}
diff --git a/hw/bsp/ch583/system_ch583.h b/hw/bsp/ch583/system_ch583.h
new file mode 100644
index 000000000..c174c9f5e
--- /dev/null
+++ b/hw/bsp/ch583/system_ch583.h
@@ -0,0 +1,43 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2024 TinyUSB contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef SYSTEM_CH583_H_
+#define SYSTEM_CH583_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern uint32_t SystemCoreClock; // System Clock Frequency (Core Clock)
+
+extern void SystemInit(void);
+extern void SystemCoreClockUpdate(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SYSTEM_CH583_H_ */
diff --git a/hw/bsp/ch583/wch-riscv.cfg b/hw/bsp/ch583/wch-riscv.cfg
new file mode 100644
index 000000000..64d595d8e
--- /dev/null
+++ b/hw/bsp/ch583/wch-riscv.cfg
@@ -0,0 +1,17 @@
+adapter driver wlinke
+adapter speed 6000
+transport select sdi
+
+wlink_set_address 0x00000000
+set _CHIPNAME wch_riscv
+sdi newtap $_CHIPNAME cpu -irlen 5 -expected-id 0x00001
+
+set _TARGETNAME $_CHIPNAME.cpu
+
+target create $_TARGETNAME.0 wch_riscv -chain-position $_TARGETNAME
+$_TARGETNAME.0 configure -work-area-phys 0x20000000 -work-area-size 0x8000 -work-area-backup 1
+set _FLASHNAME $_CHIPNAME.flash
+
+flash bank $_FLASHNAME wch_riscv 0x00000000 0 0 0 $_TARGETNAME.0
+
+echo "Ready for Remote Connections"
diff --git a/hw/bsp/espressif/boards/family.c b/hw/bsp/espressif/boards/family.c
index 48b1253b6..4b28cecf2 100644
--- a/hw/bsp/espressif/boards/family.c
+++ b/hw/bsp/espressif/boards/family.c
@@ -49,7 +49,7 @@ static led_strip_handle_t led_strip;
static void max3421_init(void);
#endif
-#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32H4, OPT_MCU_ESP32P4)
+#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32H4, OPT_MCU_ESP32P4, OPT_MCU_ESP32S31)
static bool usb_init(uint8_t rhport, bool is_host);
#endif
@@ -111,10 +111,6 @@ void board_init(void) {
#endif
}
-#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32H4)
-
-#endif
-
//--------------------------------------------------------------------+
// Board porting API
//--------------------------------------------------------------------+
@@ -178,7 +174,7 @@ void board_reset_to_bootloader(void) {
// PHY Init
//--------------------------------------------------------------------
-#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32H4, OPT_MCU_ESP32P4)
+#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3, OPT_MCU_ESP32H4, OPT_MCU_ESP32P4, OPT_MCU_ESP32S31)
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
#include "esp_private/usb_phy.h"
diff --git a/hw/bsp/espressif/family.cmake b/hw/bsp/espressif/family.cmake
index ca9eadaf6..b3bda4ad8 100644
--- a/hw/bsp/espressif/family.cmake
+++ b/hw/bsp/espressif/family.cmake
@@ -2,7 +2,10 @@
include("${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake")
string(TOUPPER ${IDF_TARGET} FAMILY_MCUS)
-# Device port default to Port1 for P4 (highspeed), Port0 for others (fullspeed)
+# Device/host port defaults:
+# - ESP32-P4 uses Port1 (highspeed)
+# - ESP32-S31 uses Port0 (highspeed)
+# - Other targets use Port0 and derive the default speed from RHPORT_SPEED
set(RHPORT_SPEED OPT_MODE_FULL_SPEED OPT_MODE_HIGH_SPEED)
if (NOT DEFINED RHPORT_DEVICE)
@@ -22,10 +25,18 @@ if (NOT DEFINED RHPORT_HOST)
endif()
if (NOT DEFINED RHPORT_DEVICE_SPEED)
- list(GET RHPORT_SPEED ${RHPORT_DEVICE} RHPORT_DEVICE_SPEED)
+ if (IDF_TARGET STREQUAL "esp32s31")
+ set(RHPORT_DEVICE_SPEED OPT_MODE_HIGH_SPEED)
+ else ()
+ list(GET RHPORT_SPEED ${RHPORT_DEVICE} RHPORT_DEVICE_SPEED)
+ endif ()
endif ()
if (NOT DEFINED RHPORT_HOST_SPEED)
- list(GET RHPORT_SPEED ${RHPORT_HOST} RHPORT_HOST_SPEED)
+ if (IDF_TARGET STREQUAL "esp32s31")
+ set(RHPORT_HOST_SPEED OPT_MODE_HIGH_SPEED)
+ else ()
+ list(GET RHPORT_SPEED ${RHPORT_HOST} RHPORT_HOST_SPEED)
+ endif ()
endif ()
# Add example src and bsp directories
@@ -33,3 +44,10 @@ set(EXTRA_COMPONENT_DIRS "src" "${CMAKE_CURRENT_LIST_DIR}/boards" "${CMAKE_CURRE
set(SDKCONFIG ${CMAKE_BINARY_DIR}/sdkconfig)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
+
+# CI_BUILD marks firmware built in CI (GitHub Actions sets CI). Mirrors the
+# non-espressif define added in family_configure_common(); applied build-wide
+# here since espressif examples return before that function runs.
+if(DEFINED ENV{CI})
+ idf_build_set_property(COMPILE_DEFINITIONS "CI_BUILD=1" APPEND)
+endif()
diff --git a/hw/bsp/family_support.cmake b/hw/bsp/family_support.cmake
index cb8ec6cf8..1f3952205 100644
--- a/hw/bsp/family_support.cmake
+++ b/hw/bsp/family_support.cmake
@@ -244,7 +244,7 @@ function(family_add_bloaty TARGET)
COMMAND ${BLOATY_EXE} ${OPTION_LIST} $<TARGET_FILE:${TARGET}>
VERBATIM)
- set_property(TARGET ${TARGET}-bloaty PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-bloaty PROPERTY FOLDER ${TARGET}-group)
# post build
# add_custom_command(TARGET ${TARGET} POST_BUILD
# COMMAND ${BLOATY_EXE} --csv ${OPTION_LIST} $<TARGET_FILE:${TARGET}> > ${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_bloaty.csv
@@ -265,7 +265,7 @@ function(family_add_linkermap TARGET)
VERBATIM
)
- set_property(TARGET ${TARGET}-linkermap PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-linkermap PROPERTY FOLDER ${TARGET}-group)
# post build
add_custom_command(TARGET ${TARGET} POST_BUILD
@@ -326,10 +326,12 @@ ld_defs=\"$(echo \"$ld_defs\" | xargs)\"")
"if [ -f \"${TARGET_ELF_PATH}\" ]; then \
${MEMBROWSE_LD_SCRIPTS_CMD}; \
${MEMBROWSE_LD_DEFS_CMD}; \
+ map_arg=\"\"; \
+ if [ -f \"${TARGET_ELF_PATH}.map\" ]; then map_arg=\"--map-file \\\"${TARGET_ELF_PATH}.map\\\"\"; fi; \
if [ \"$MEMBROWSE_UPLOAD\" = \"1\" ]; then \
- MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs --upload --github --target-name ${BOARD}/${TARGET} --api-key $ENV{MEMBROWSE_API_KEY}\"; \
+ MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs $map_arg --upload --github --target-name ${BOARD}/${TARGET} --api-key $ENV{MEMBROWSE_API_KEY}\"; \
else \
- MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs\"; \
+ MEMBROWSE_CMD=\"${MEMBROWSE_EXE} report ${OPTION} \\\"${TARGET_ELF_PATH}\\\" \\\"$ld_scripts\\\" $ld_defs $map_arg\"; \
fi; \
else \
if [ \"$MEMBROWSE_UPLOAD\" = \"1\" ]; then \
@@ -345,7 +347,7 @@ echo \"$MEMBROWSE_CMD\"")
COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=0 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\""
VERBATIM
)
- set_property(TARGET ${TARGET}-membrowse PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-membrowse PROPERTY FOLDER ${TARGET}-group)
add_custom_target(${TARGET}-membrowse-upload
COMMAND ${CMAKE_COMMAND} -E env MEMBROWSE_UPLOAD=1 bash -lc "${MEMBROWSE_PREPARE_CMD}; eval \"$MEMBROWSE_CMD\""
@@ -357,7 +359,7 @@ echo \"$MEMBROWSE_CMD\"")
endif ()
add_dependencies(examples-membrowse-upload ${TARGET}-membrowse-upload)
- set_property(TARGET ${TARGET}-membrowse-upload PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-membrowse-upload PROPERTY FOLDER ${TARGET}-group)
endif ()
endfunction()
@@ -452,6 +454,12 @@ function(family_configure_common TARGET RTOS)
BOARD_${BOARD_UPPER}
)
+ # CI_BUILD marks firmware built in CI (GitHub Actions sets CI). Examples can use
+ # it to alter behavior under test, e.g. board_test idles to park HIL boards.
+ if(DEFINED ENV{CI})
+ target_compile_definitions(${TARGET} PUBLIC CI_BUILD=1)
+ endif()
+
# compile define from command line
if(DEFINED CFLAGS_CLI)
separate_arguments(CFLAGS_CLI)
@@ -646,7 +654,7 @@ exit"
VERBATIM
)
- set_property(TARGET ${NAME_TARGET}-jlink PROPERTY FOLDER ${TARGET}-group)
+# set_property(TARGET ${NAME_TARGET}-jlink PROPERTY FOLDER ${NAME_TARGET}-group)
endfunction()
@@ -661,7 +669,7 @@ function(family_flash_stlink TARGET)
COMMAND ${STM32_PROGRAMMER_CLI} --connect port=swd --write $<TARGET_FILE:${TARGET}> --go
)
- set_property(TARGET ${TARGET}-stlink PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-stlink PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -676,7 +684,7 @@ function(family_flash_stflash TARGET)
COMMAND ${ST_FLASH} write $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.bin 0x8000000
)
- set_property(TARGET ${TARGET}-stflash PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-stflash PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -704,7 +712,7 @@ function(family_flash_openocd TARGET)
VERBATIM
)
- set_property(TARGET ${TARGET}-openocd PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-openocd PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -767,7 +775,7 @@ function(family_flash_wlink_rs TARGET)
COMMAND ${WLINK_RS} flash $<TARGET_FILE:${TARGET}>
)
- set_property(TARGET ${TARGET}-wlink-rs PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-wlink-rs PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -782,7 +790,7 @@ function(family_flash_pyocd TARGET)
COMMAND ${PYOCD} flash -t ${PYOCD_TARGET} $<TARGET_FILE:${TARGET}>
)
- set_property(TARGET ${TARGET}-pyocd PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-pyocd PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -792,7 +800,7 @@ function(family_flash_uf2 TARGET FAMILY_ID)
DEPENDS ${TARGET}
COMMAND python ${UF2CONV_PY} -f ${FAMILY_ID} --deploy $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.uf2
)
- set_property(TARGET ${TARGET}-uf2 PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-uf2 PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -808,7 +816,7 @@ function(family_flash_teensy TARGET)
COMMAND ${TEENSY_CLI} --mcu=${TEENSY_MCU} -w -s $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex
)
- set_property(TARGET ${TARGET}-teensy PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-teensy PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -828,7 +836,7 @@ function(family_flash_nxplink TARGET)
COMMAND ${LINKSERVER_PATH} flash ${NXPLINK_DEVICE} load $<TARGET_FILE:${TARGET}>
)
- set_property(TARGET ${TARGET}-nxplink PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-nxplink PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -843,7 +851,7 @@ function(family_flash_dfu_util TARGET OPTION)
VERBATIM
)
- set_property(TARGET ${TARGET}-dfu-util PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-dfu-util PROPERTY FOLDER ${TARGET}-group)
endfunction()
function(family_flash_msp430flasher TARGET)
@@ -860,7 +868,7 @@ function(family_flash_msp430flasher TARGET)
${MSP430FLASHER} -w $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.hex -z [VCC]
)
- set_property(TARGET ${TARGET}-msp430flasher PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-msp430flasher PROPERTY FOLDER ${TARGET}-group)
endfunction()
function(family_flash_rfp TARGET)
@@ -878,7 +886,7 @@ function(family_flash_rfp TARGET)
VERBATIM
)
- set_property(TARGET ${TARGET}-rfp PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-rfp PROPERTY FOLDER ${TARGET}-group)
endfunction()
@@ -895,7 +903,27 @@ function(family_flash_uniflash TARGET)
VERBATIM
)
- set_property(TARGET ${TARGET}-uniflash PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-uniflash PROPERTY FOLDER ${TARGET}-group)
+endfunction()
+
+# Add flash lm4flash target (lightweight flasher for TI Tiva-C/Stellaris ICDI boards)
+function(family_flash_lm4flash TARGET)
+ if (NOT DEFINED LM4FLASH)
+ set(LM4FLASH lm4flash)
+ endif ()
+
+ if (NOT DEFINED LM4FLASH_OPTION)
+ set(LM4FLASH_OPTION "")
+ endif ()
+ separate_arguments(OPTION_LIST UNIX_COMMAND ${LM4FLASH_OPTION})
+
+ add_custom_target(${TARGET}-lm4flash
+ DEPENDS ${TARGET}
+ COMMAND ${LM4FLASH} ${OPTION_LIST} $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.bin
+ VERBATIM
+ )
+
+ #set_property(TARGET ${TARGET}-lm4flash PROPERTY FOLDER ${TARGET}-group)
endfunction()
# Add flash ft9xx target need to remove kernal's ftdi_sio and bind D2XX drivers
@@ -910,7 +938,7 @@ function(family_flash_ft9xx TARGET)
COMMAND ${FT9XXPROG} -f $<TARGET_FILE_DIR:${TARGET}>/${TARGET}.bin
)
- set_property(TARGET ${TARGET}-ft9xx PROPERTY FOLDER ${TARGET}-group)
+ #set_property(TARGET ${TARGET}-ft9xx PROPERTY FOLDER ${TARGET}-group)
endfunction()
#----------------------------------
diff --git a/hw/bsp/ft9xx/family.c b/hw/bsp/ft9xx/family.c
index 5ee134eb0..0ca2663ac 100644
--- a/hw/bsp/ft9xx/family.c
+++ b/hw/bsp/ft9xx/family.c
@@ -221,8 +221,8 @@ int board_uart_read(uint8_t *buf, int len)
// Send characters to UART
int board_uart_write(void const *buf, int len)
{
- int count = 0;
#ifdef BOARD_UART
+ int count = 0;
uint8_t const *p = (uint8_t const *) buf;
while (count < len) {
if (BOARD_UART->LSR_ICR_XON2 & MASK_UART_LSR_THRE) {
@@ -232,10 +232,11 @@ int board_uart_write(void const *buf, int len)
break;
}
}
+ return count;
#else
(void) buf; (void) len;
+ return -1;
#endif
- return count;
}
// Get current milliseconds
diff --git a/hw/bsp/gd32vf103/family.c b/hw/bsp/gd32vf103/family.c
index c1dc82bda..8f82b3ada 100644
--- a/hw/bsp/gd32vf103/family.c
+++ b/hw/bsp/gd32vf103/family.c
@@ -174,7 +174,7 @@ int board_uart_write(void const* buf, int len) {
#else
(void)buf;
(void)len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/imxrt/boards/metro_m7_1011/board.cmake b/hw/bsp/imxrt/boards/metro_m7_1011/board.cmake
index 63b2a120a..5edf6cc91 100644
--- a/hw/bsp/imxrt/boards/metro_m7_1011/board.cmake
+++ b/hw/bsp/imxrt/boards/metro_m7_1011/board.cmake
@@ -12,5 +12,6 @@ function(update_board TARGET)
target_compile_definitions(${TARGET} PUBLIC
CPU_MIMXRT1011DAE5A
CFG_EXAMPLE_VIDEO_READONLY
+ LWIP_HIGH_THROUGHPUT=0
)
endfunction()
diff --git a/hw/bsp/imxrt/boards/metro_m7_1011/board.mk b/hw/bsp/imxrt/boards/metro_m7_1011/board.mk
index 229b5c18c..fadb760b3 100644
--- a/hw/bsp/imxrt/boards/metro_m7_1011/board.mk
+++ b/hw/bsp/imxrt/boards/metro_m7_1011/board.mk
@@ -1,4 +1,4 @@
-CFLAGS += -DCPU_MIMXRT1011DAE5A -DCFG_EXAMPLE_VIDEO_READONLY
+CFLAGS += -DCPU_MIMXRT1011DAE5A -DCFG_EXAMPLE_VIDEO_READONLY -DLWIP_HIGH_THROUGHPUT=0
MCU_FAMILY = RT1010
MCU_VARIANT = MIMXRT1011
diff --git a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.cmake b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.cmake
index 63b2a120a..5edf6cc91 100644
--- a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.cmake
+++ b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.cmake
@@ -12,5 +12,6 @@ function(update_board TARGET)
target_compile_definitions(${TARGET} PUBLIC
CPU_MIMXRT1011DAE5A
CFG_EXAMPLE_VIDEO_READONLY
+ LWIP_HIGH_THROUGHPUT=0
)
endfunction()
diff --git a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.mk b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.mk
index c5521faf5..81ec74d70 100644
--- a/hw/bsp/imxrt/boards/mimxrt1010_evk/board.mk
+++ b/hw/bsp/imxrt/boards/mimxrt1010_evk/board.mk
@@ -1,4 +1,4 @@
-CFLAGS += -DCPU_MIMXRT1011DAE5A -DCFG_EXAMPLE_VIDEO_READONLY
+CFLAGS += -DCPU_MIMXRT1011DAE5A -DCFG_EXAMPLE_VIDEO_READONLY -DLWIP_HIGH_THROUGHPUT=0
MCU_FAMILY = RT1010
MCU_VARIANT = MIMXRT1011
diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.cmake b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.cmake
index 5661bb3e6..fe74b8d33 100644
--- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.cmake
+++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.cmake
@@ -12,5 +12,6 @@ function(update_board TARGET)
target_compile_definitions(${TARGET} PUBLIC
CPU_MIMXRT1015DAF5A
CFG_EXAMPLE_VIDEO_READONLY
+ LWIP_HIGH_THROUGHPUT=0
)
endfunction()
diff --git a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.mk b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.mk
index 062929902..a84263a81 100644
--- a/hw/bsp/imxrt/boards/mimxrt1015_evk/board.mk
+++ b/hw/bsp/imxrt/boards/mimxrt1015_evk/board.mk
@@ -1,4 +1,4 @@
-CFLAGS += -DCPU_MIMXRT1015DAF5A -DCFG_EXAMPLE_VIDEO_READONLY
+CFLAGS += -DCPU_MIMXRT1015DAF5A -DCFG_EXAMPLE_VIDEO_READONLY -DLWIP_HIGH_THROUGHPUT=0
MCU_FAMILY = RT1015
MCU_VARIANT = MIMXRT1015
diff --git a/hw/bsp/kinetis_k/family.c b/hw/bsp/kinetis_k/family.c
index 8efab2762..a5af83931 100644
--- a/hw/bsp/kinetis_k/family.c
+++ b/hw/bsp/kinetis_k/family.c
@@ -140,7 +140,7 @@ int board_uart_write(void const *buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/lpc55/boards/lpcxpresso55s69/board.cmake b/hw/bsp/lpc55/boards/lpcxpresso55s69/board.cmake
index 59f7d6329..ef20d7601 100644
--- a/hw/bsp/lpc55/boards/lpcxpresso55s69/board.cmake
+++ b/hw/bsp/lpc55/boards/lpcxpresso55s69/board.cmake
@@ -2,7 +2,6 @@ set(MCU_VARIANT LPC55S69)
set(MCU_CORE LPC55S69_cm33_core0)
set(JLINK_DEVICE LPC55S69_M33_0)
-set(JLINK_OPTION "-USB 000727648789")
set(PYOCD_TARGET LPC55S69)
set(NXPLINK_DEVICE LPC55S69:LPCXpresso55S69)
diff --git a/hw/bsp/mm32/family.c b/hw/bsp/mm32/family.c
index 651c9496e..1538181dc 100644
--- a/hw/bsp/mm32/family.c
+++ b/hw/bsp/mm32/family.c
@@ -59,11 +59,11 @@ void OTG_FS_IRQHandler(void) {
void USB_DeviceClockInit(void) {
/* Select USBCLK source */
// RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_Div1);
- RCC->CFGR &= ~(0x3 << 22);
- RCC->CFGR |= (0x1 << 22);
+ RCC->CFGR &= ~(0x3U << 22);
+ RCC->CFGR |= (0x1U << 22);
/* Enable USB clock */
- RCC->AHB2ENR |= 0x1 << 7;
+ RCC->AHB2ENR |= 0x1U << 7;
}
void board_init(void) {
@@ -167,7 +167,7 @@ int board_uart_write(void const* buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/nrf/boards/nrf54h20dk/board.cmake b/hw/bsp/nrf/boards/nrf54h20dk/board.cmake
index fca7a56d2..8095b59fe 100644
--- a/hw/bsp/nrf/boards/nrf54h20dk/board.cmake
+++ b/hw/bsp/nrf/boards/nrf54h20dk/board.cmake
@@ -1,7 +1,8 @@
set(MCU_VARIANT nrf54h20)
function(update_board TARGET)
- # temporarily, 54h20 has multiple sram sections
+ # 32 KB primary RAM is too tight for memory-heavy examples (e.g. video YUY2
+ # framebuf). TODO: route static .bss to RAM00 (512 KB) and drop this.
target_compile_definitions(${TARGET} PUBLIC
CFG_EXAMPLE_VIDEO_READONLY
)
diff --git a/hw/bsp/nrf/boards/nrf54h20dk/board.mk b/hw/bsp/nrf/boards/nrf54h20dk/board.mk
index c49b605e8..3333a76f1 100644
--- a/hw/bsp/nrf/boards/nrf54h20dk/board.mk
+++ b/hw/bsp/nrf/boards/nrf54h20dk/board.mk
@@ -1,6 +1,11 @@
MCU_VARIANT = nrf54h20
CFLAGS += -DNRF54H20_XXAA
+# 32 KB primary RAM is too tight for memory-heavy examples (e.g. video YUY2
+# framebuf). Match the CMake build (board.cmake) — TODO: route static .bss to
+# RAM00 (512 KB) and drop this.
+CFLAGS += -DCFG_EXAMPLE_VIDEO_READONLY
+
# enable max3421 host driver for this board
MAX3421_HOST = 1
diff --git a/hw/bsp/nrf/boards/nrf54lm20dk/board.cmake b/hw/bsp/nrf/boards/nrf54lm20dk/board.cmake
index 8c2b83346..e97b8822c 100644
--- a/hw/bsp/nrf/boards/nrf54lm20dk/board.cmake
+++ b/hw/bsp/nrf/boards/nrf54lm20dk/board.cmake
@@ -2,7 +2,6 @@ set(MCU_VARIANT nrf54lm20a_enga)
set(JLINK_DEVICE NRF54LM20A_M33)
function(update_board TARGET)
- target_compile_definitions(${TARGET} PUBLIC
- CFG_EXAMPLE_VIDEO_READONLY
- )
+ # No board-specific overrides needed — primary 256 KB RAM is plenty for
+ # memory-heavy examples (video YUY2 framebuf etc.).
endfunction()
diff --git a/hw/bsp/pic32mz/family.c b/hw/bsp/pic32mz/family.c
index 5805e653f..98038b4f7 100644
--- a/hw/bsp/pic32mz/family.c
+++ b/hw/bsp/pic32mz/family.c
@@ -102,7 +102,9 @@ TU_ATTR_WEAK int board_uart_read(uint8_t * buf, int len)
TU_ATTR_WEAK int board_uart_write(void const * buf, int len)
{
(void) buf;
- return len;
+ (void) len;
+
+ return -1;
}
#if CFG_TUSB_OS == OPT_OS_NONE
diff --git a/hw/bsp/rp2040/family.c b/hw/bsp/rp2040/family.c
index a4642face..55feec159 100644
--- a/hw/bsp/rp2040/family.c
+++ b/hw/bsp/rp2040/family.c
@@ -282,7 +282,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/rp2040/family.cmake b/hw/bsp/rp2040/family.cmake
index 6e88b9fa1..aab9a4fae 100644
--- a/hw/bsp/rp2040/family.cmake
+++ b/hw/bsp/rp2040/family.cmake
@@ -93,13 +93,13 @@ target_sources(tinyusb_device_base INTERFACE
${TOP}/src/portable/raspberrypi/rp2040/dcd_rp2040.c
${TOP}/src/portable/raspberrypi/rp2040/rp2040_usb.c
${TOP}/src/device/usbd.c
- ${TOP}/src/device/usbd_control.c
${TOP}/src/class/audio/audio_device.c
${TOP}/src/class/cdc/cdc_device.c
${TOP}/src/class/dfu/dfu_device.c
${TOP}/src/class/dfu/dfu_rt_device.c
${TOP}/src/class/hid/hid_device.c
${TOP}/src/class/midi/midi_device.c
+ ${TOP}/src/class/midi/midi2_device.c
${TOP}/src/class/msc/msc_device.c
${TOP}/src/class/mtp/mtp_device.c
${TOP}/src/class/net/ecm_rndis_device.c
@@ -122,6 +122,7 @@ target_sources(tinyusb_host_base INTERFACE
${TOP}/src/class/cdc/cdc_host.c
${TOP}/src/class/hid/hid_host.c
${TOP}/src/class/midi/midi_host.c
+ ${TOP}/src/class/midi/midi2_host.c
${TOP}/src/class/msc/msc_host.c
${TOP}/src/class/vendor/vendor_host.c
)
diff --git a/hw/bsp/samd11/family.c b/hw/bsp/samd11/family.c
index 0c987b85a..0864aa3dd 100644
--- a/hw/bsp/samd11/family.c
+++ b/hw/bsp/samd11/family.c
@@ -34,6 +34,8 @@
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#include "hal/include/hal_gpio.h"
@@ -66,7 +68,7 @@ void USB_Handler(void)
//--------------------------------------------------------------------+
/* Referenced GCLKs, should be initialized firstly */
-#define _GCLK_INIT_1ST (1 << 0 | 1 << 1)
+#define _GCLK_INIT_1ST (1u << 0 | 1u << 1)
/* Not referenced GCLKs, initialized last */
#define _GCLK_INIT_LAST (~_GCLK_INIT_1ST)
diff --git a/hw/bsp/samd2x_l2x/family.c b/hw/bsp/samd2x_l2x/family.c
index 11b6343cd..306ea2308 100644
--- a/hw/bsp/samd2x_l2x/family.c
+++ b/hw/bsp/samd2x_l2x/family.c
@@ -79,7 +79,7 @@
#ifdef SAMD21_FAMILY
/* Referenced GCLKs, should be initialized firstly */
-#define _GCLK_INIT_1ST (1 << 0 | 1 << 1)
+#define _GCLK_INIT_1ST (1u << 0 | 1u << 1)
/* Not referenced GCLKs, initialized last */
#define _GCLK_INIT_LAST (~_GCLK_INIT_1ST)
#endif
diff --git a/hw/bsp/samg/family.c b/hw/bsp/samg/family.c
index 519068986..9edc43b51 100644
--- a/hw/bsp/samg/family.c
+++ b/hw/bsp/samg/family.c
@@ -27,15 +27,17 @@
manufacturer: Microchip
*/
-#include "sam.h"
// Suppress warning caused by mcu driver
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wredundant-decls"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
+#include "sam.h"
#include "peripheral_clk_config.h"
#include "hal/include/hal_init.h"
#include "hal/include/hpl_usart_sync.h"
diff --git a/hw/bsp/stm32c0/family.c b/hw/bsp/stm32c0/family.c
index 72af3ce7f..ac37045fb 100644
--- a/hw/bsp/stm32c0/family.c
+++ b/hw/bsp/stm32c0/family.c
@@ -193,7 +193,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h b/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h
new file mode 100644
index 000000000..732d9a5cf
--- /dev/null
+++ b/hw/bsp/stm32c5/FreeRTOSConfig/FreeRTOSConfig.h
@@ -0,0 +1,165 @@
+/*
+ * FreeRTOS Kernel V10.0.0
+ * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ * the Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software. If you wish to use our Amazon
+ * FreeRTOS name, please do so in a fair use way that does not cause confusion.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * http://www.FreeRTOS.org
+ * http://aws.amazon.com/freertos
+ *
+ * 1 tab == 4 spaces!
+ */
+
+
+#ifndef FREERTOS_CONFIG_H
+#define FREERTOS_CONFIG_H
+
+/*-----------------------------------------------------------
+ * Application specific definitions.
+ *
+ * These definitions should be adjusted for your particular hardware and
+ * application requirements.
+ *
+ * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
+ * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
+ *
+ * See http://www.freertos.org/a00110.html.
+ *----------------------------------------------------------*/
+
+// skip if included from IAR assembler
+#ifndef __IASMARM__
+ #include "stm32c5xx.h"
+#endif
+
+/* Cortex M23/M33 port configuration. */
+#define configENABLE_MPU 0
+#define configENABLE_FPU 1
+#define configENABLE_TRUSTZONE 0
+#define configMINIMAL_SECURE_STACK_SIZE (1024)
+
+#define configUSE_PREEMPTION 1
+#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
+#define configCPU_CLOCK_HZ SystemCoreClock
+#define configTICK_RATE_HZ ( 1000 )
+#define configMAX_PRIORITIES ( 5 )
+#define configMINIMAL_STACK_SIZE ( 200 )
+#define configTOTAL_HEAP_SIZE ( configSUPPORT_DYNAMIC_ALLOCATION*4*1024 )
+#define configMAX_TASK_NAME_LEN 16
+#define configUSE_16_BIT_TICKS 0
+#define configIDLE_SHOULD_YIELD 1
+#define configUSE_MUTEXES 1
+#define configUSE_RECURSIVE_MUTEXES 1
+#define configUSE_COUNTING_SEMAPHORES 1
+#define configQUEUE_REGISTRY_SIZE 4
+#define configUSE_QUEUE_SETS 0
+#define configUSE_TIME_SLICING 0
+#define configUSE_NEWLIB_REENTRANT 0
+#define configENABLE_BACKWARD_COMPATIBILITY 1
+#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0
+
+#define configSUPPORT_STATIC_ALLOCATION 1
+#define configSUPPORT_DYNAMIC_ALLOCATION 0
+
+/* Hook function related definitions. */
+#define configUSE_IDLE_HOOK 0
+#define configUSE_TICK_HOOK 0
+#define configUSE_MALLOC_FAILED_HOOK 0 // cause nested extern warning
+#define configCHECK_FOR_STACK_OVERFLOW 2
+#define configCHECK_HANDLER_INSTALLATION 0
+
+/* Run time and task stats gathering related definitions. */
+#define configGENERATE_RUN_TIME_STATS 0
+#define configRECORD_STACK_HIGH_ADDRESS 1
+#define configUSE_TRACE_FACILITY 1 // legacy trace
+#define configUSE_STATS_FORMATTING_FUNCTIONS 0
+
+/* Co-routine definitions. */
+#define configUSE_CO_ROUTINES 0
+#define configMAX_CO_ROUTINE_PRIORITIES 2
+
+/* Software timer related definitions. */
+#define configUSE_TIMERS 1
+#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES-2)
+#define configTIMER_QUEUE_LENGTH 32
+#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE
+
+/* Optional functions - most linkers will remove unused functions anyway. */
+#define INCLUDE_vTaskPrioritySet 0
+#define INCLUDE_uxTaskPriorityGet 0
+#define INCLUDE_vTaskDelete 0
+#define INCLUDE_vTaskSuspend 1 // required for queue, semaphore, mutex to be blocked indefinitely with portMAX_DELAY
+#define INCLUDE_xResumeFromISR 0
+#define INCLUDE_vTaskDelayUntil 1
+#define INCLUDE_vTaskDelay 1
+#define INCLUDE_xTaskGetSchedulerState 0
+#define INCLUDE_xTaskGetCurrentTaskHandle 1
+#define INCLUDE_uxTaskGetStackHighWaterMark 0
+#define INCLUDE_xTaskGetIdleTaskHandle 0
+#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0
+#define INCLUDE_pcTaskGetTaskName 0
+#define INCLUDE_eTaskGetState 0
+#define INCLUDE_xEventGroupSetBitFromISR 0
+#define INCLUDE_xTimerPendFunctionCall 0
+
+/* Define to trap errors during development. */
+// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7
+#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__) || defined(__ARM_ARCH_8_1M_MAIN__) || \
+ defined(__ARM7M__) || defined (__ARM7EM__) || defined(__ARM8M_MAINLINE__) || defined(__ARM8EM_MAINLINE__)
+ #define configASSERT(_exp) \
+ do {\
+ if ( !(_exp) ) { \
+ volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \
+ if ( (*ARM_CM_DHCSR) & 1UL ) { /* Only halt mcu if debugger is attached */ \
+ taskDISABLE_INTERRUPTS(); \
+ __asm("BKPT #0\n"); \
+ }\
+ }\
+ } while(0)
+#endif
+
+/* FreeRTOS hooks to NVIC vectors */
+#define xPortPendSVHandler PendSV_Handler
+#define xPortSysTickHandler SysTick_Handler
+#define vPortSVCHandler SVC_Handler
+
+//--------------------------------------------------------------------+
+// Interrupt nesting behavior configuration.
+//--------------------------------------------------------------------+
+
+// For Cortex-M specific: __NVIC_PRIO_BITS is defined in mcu header
+#define configPRIO_BITS 4
+
+/* The lowest interrupt priority that can be used in a call to a "set priority" function. */
+#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1<<configPRIO_BITS) - 1)
+
+/* The highest interrupt priority that can be used by any interrupt service
+routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL
+INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
+PRIORITY THAN THIS! (higher priorities are lower numeric values. */
+#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 2
+
+/* Interrupt priorities used by the kernel port layer itself. These are generic
+to all Cortex-M ports, and do not rely on any particular library functions. */
+#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
+
+/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
+See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
+#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
+
+#endif
diff --git a/hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake
new file mode 100644
index 000000000..563a47ba2
--- /dev/null
+++ b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.cmake
@@ -0,0 +1,13 @@
+set(MCU_VARIANT stm32c542xx)
+set(JLINK_DEVICE stm32c542rc)
+
+set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/../../linker/stm32c542xc_flash.ld)
+set(LD_FILE_IAR ${CMAKE_CURRENT_LIST_DIR}/../../linker/stm32c542xc_flash.icf)
+
+function(update_board TARGET)
+ target_compile_definitions(${TARGET} PUBLIC
+ STM32C542xx
+ HSE_VALUE=24000000
+ HSE_STARTUP_TIMEOUT=100
+ )
+endfunction()
diff --git a/hw/bsp/stm32c5/boards/stm32c542nucleo/board.h b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.h
new file mode 100644
index 000000000..b64fad243
--- /dev/null
+++ b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.h
@@ -0,0 +1,83 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026, HiFiPhile
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+/* metadata:
+ name: STM32C542 Nucleo
+ url: https://www.st.com/en/evaluation-tools/nucleo-c542rc.html
+*/
+
+#ifndef BOARD_H_
+#define BOARD_H_
+
+// LED
+#define LED_PORT HAL_GPIOA
+#define LED_PIN HAL_GPIO_PIN_5
+
+// Button
+#define BUTTON_PORT HAL_GPIOC
+#define BUTTON_PIN HAL_GPIO_PIN_13
+#define BUTTON_STATE_ACTIVE 1
+
+// Enable UART serial communication with the ST-Link
+#define UART_ID 2
+#define UART_GPIO_PORT HAL_GPIOA
+#define UART_GPIO_AF HAL_GPIO_AF_7
+#define UART_TX_PIN HAL_GPIO_PIN_2
+#define UART_RX_PIN HAL_GPIO_PIN_3
+
+static inline void board_clock_init(void) {
+ HAL_RCC_HSE_Enable(HAL_RCC_HSE_ON);
+
+ hal_rcc_psi_config_t config_psi;
+ config_psi.psi_source = HAL_RCC_PSI_SRC_HSE;
+ config_psi.psi_ref = HAL_RCC_PSI_REF_24MHZ;
+ config_psi.psi_out = HAL_RCC_PSI_OUT_144MHZ;
+ HAL_RCC_PSI_SetConfig(&config_psi);
+ HAL_RCC_PSIS_Enable();
+
+ /** Initializes the CPU, AHB and APB busses clocks */
+ hal_rcc_bus_clk_config_t config_bus;
+ config_bus.hclk_prescaler = HAL_RCC_HCLK_PRESCALER1;
+ config_bus.pclk1_prescaler = HAL_RCC_PCLK_PRESCALER1;
+ config_bus.pclk2_prescaler = HAL_RCC_PCLK_PRESCALER1;
+ config_bus.pclk3_prescaler = HAL_RCC_PCLK_PRESCALER1;
+ HAL_RCC_SetBusClockConfig(&config_bus);
+
+ /** Frequency will be increased */
+ HAL_FLASH_ITF_SetLatency(HAL_FLASH, HAL_FLASH_ITF_LATENCY_4);
+
+ HAL_RCC_SetSYSCLKSource(HAL_RCC_SYSCLK_SRC_PSIS);
+
+ HAL_FLASH_ITF_SetProgrammingDelay(HAL_FLASH, HAL_FLASH_ITF_PROGRAM_DELAY_2);
+
+ HAL_UpdateCoreClock();
+
+ HAL_RCC_USART2_SetKernelClkSource(HAL_RCC_USART2_CLK_SRC_PCLK1);
+
+ HAL_RCC_PSIDIV3_Enable();
+ HAL_RCC_CK48_SetKernelClkSource(HAL_RCC_CK48_CLK_SRC_PSIDIV3);
+}
+#endif /* BOARD_H_ */
diff --git a/hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk
new file mode 100644
index 000000000..b3da64713
--- /dev/null
+++ b/hw/bsp/stm32c5/boards/stm32c542nucleo/board.mk
@@ -0,0 +1,13 @@
+MCU_VARIANT = stm32c542xx
+
+CFLAGS += \
+ -DSTM32C542xx \
+ -DHSE_VALUE=24000000 \
+ -DHSE_STARTUP_TIMEOUT=100
+
+# GCC
+LD_FILE = $(FAMILY_PATH)/linker/stm32c542xc_flash.ld
+
+
+# For flash-jlink target
+JLINK_DEVICE = stm32c542rc
diff --git a/hw/bsp/stm32c5/family.c b/hw/bsp/stm32c5/family.c
new file mode 100644
index 000000000..40b86fc55
--- /dev/null
+++ b/hw/bsp/stm32c5/family.c
@@ -0,0 +1,250 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ * Copyright (c) 2023 HiFiPhile
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+/* metadata:
+ manufacturer: STMicroelectronics
+*/
+
+#include "stm32_hal.h"
+#include "bsp/board_api.h"
+#include "board.h"
+
+#ifdef UART_ID
+ #if UART_ID == 1
+ #define UARTn USART1
+ #define UARTn_CLK_ENABLE HAL_RCC_USART1_EnableClock
+ #elif UART_ID == 2
+ #define UARTn USART2
+ #define UARTn_CLK_ENABLE HAL_RCC_USART2_EnableClock
+ #endif
+#endif
+
+//--------------------------------------------------------------------+
+// Forward USB interrupt events to TinyUSB IRQ Handler
+//--------------------------------------------------------------------+
+void USB_DRD_FS_IRQHandler(void) {
+ tusb_int_handler(0, true);
+}
+
+//--------------------------------------------------------------------+
+// MACRO TYPEDEF CONSTANT ENUM
+//--------------------------------------------------------------------+
+static void mpu_init(void);
+
+void board_init(void) {
+ mpu_init();
+ LL_ICACHE_Enable(ICACHE);
+
+ HAL_Init();
+ board_clock_init();
+
+ // Enable peripheral clocks.
+ HAL_RCC_GPIOA_EnableClock();
+ HAL_RCC_GPIOB_EnableClock();
+ HAL_RCC_GPIOC_EnableClock();
+ HAL_RCC_GPIOD_EnableClock();
+ HAL_RCC_USB_EnableClock();
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+ // 1ms tick timer
+ SysTick_Config(SystemCoreClock / 1000);
+#elif CFG_TUSB_OS == OPT_OS_FREERTOS
+ // Explicitly disable systick to prevent its ISR from running before scheduler start
+ SysTick->CTRL &= ~1U;
+
+ // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher )
+ NVIC_SetPriority(USB_DRD_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
+#endif
+
+ // LED
+ {
+ hal_gpio_config_t gpio_config;
+ gpio_config.mode = HAL_GPIO_MODE_OUTPUT;
+ gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW;
+ gpio_config.pull = HAL_GPIO_PULL_NO;
+ gpio_config.output_type = HAL_GPIO_OUTPUT_PUSHPULL;
+ gpio_config.init_state = HAL_GPIO_PIN_RESET;
+
+ HAL_GPIO_Init(LED_PORT, LED_PIN, &gpio_config);
+ }
+
+ // Button
+ {
+ hal_gpio_config_t gpio_config;
+ gpio_config.mode = HAL_GPIO_MODE_INPUT;
+ gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW;
+ gpio_config.pull = BUTTON_STATE_ACTIVE ? HAL_GPIO_PULL_DOWN : HAL_GPIO_PULL_UP;
+ HAL_GPIO_Init(BUTTON_PORT, BUTTON_PIN, &gpio_config);
+ }
+
+#ifdef UART_ID
+ UARTn_CLK_ENABLE();
+ // UART
+ {
+ hal_gpio_config_t gpio_config;
+ gpio_config.mode = HAL_GPIO_MODE_ALTERNATE;
+ gpio_config.output_type = HAL_GPIO_OUTPUT_PUSHPULL;
+ gpio_config.pull = HAL_GPIO_PULL_NO;
+ gpio_config.speed = HAL_GPIO_SPEED_FREQ_LOW;
+ gpio_config.alternate = UART_GPIO_AF;
+ HAL_GPIO_Init(UART_GPIO_PORT, UART_TX_PIN | UART_RX_PIN, &gpio_config);
+ }
+
+ LL_USART_ConfigAsyncMode(UARTn);
+ uint32_t reg_temp = (LL_USART_DATAWIDTH_8_BIT | LL_USART_PARITY_NONE
+ | LL_USART_DIRECTION_TX_RX | LL_USART_OVERSAMPLING_16);
+ LL_USART_ConfigXfer(UARTn, reg_temp, LL_USART_STOP_BIT_1);
+ LL_USART_SetBaudRate(UARTn, SystemCoreClock, LL_USART_PRESCALER_DIV1, LL_USART_OVERSAMPLING_16,
+ 115200);
+ LL_USART_EnableFIFO(UARTn);
+ LL_USART_Enable(UARTn);
+#endif
+}
+
+static void mpu_init(void)
+{
+ /* Disables the MPU */
+ HAL_CORTEX_MPU_Disable();
+
+ /*
+ Initializes and configures the MPU attributes
+ */
+ HAL_CORTEX_MPU_SetCacheMemAttr(HAL_CORTEX_MPU_MEM_ATTR_0, HAL_CORTEX_MPU_NORMAL_MEM_NCACHEABLE);
+
+ /*
+ Initializes and configures the MPU Region
+ */
+ hal_cortex_mpu_region_config_t p_region_config = {0};
+
+ p_region_config.base_addr = 0x8FFE000;
+ p_region_config.limit_addr = 0x8FFFFFF;
+ p_region_config.access_attr = HAL_CORTEX_MPU_REGION_ALL_RO;
+ p_region_config.exec_attr = HAL_CORTEX_MPU_EXECUTION_ATTR_DISABLE;
+ p_region_config.attr_idx = HAL_CORTEX_MPU_MEM_ATTR_0;
+ HAL_CORTEX_MPU_SetConfigRegion(HAL_CORTEX_MPU_REGION_0, &p_region_config);
+
+ HAL_CORTEX_MPU_EnableRegion(HAL_CORTEX_MPU_REGION_0);
+
+ /* Enables the MPU */
+ HAL_CORTEX_MPU_Enable(HAL_CORTEX_MPU_HARDFAULT_NMI_DISABLE, HAL_CORTEX_MPU_ACCESS_FAULT_ONLY_PRIV);
+}
+
+//--------------------------------------------------------------------+
+// Board porting API
+//--------------------------------------------------------------------+
+
+void board_led_write(bool state) {
+ hal_gpio_pin_state_t pin_state = state ? HAL_GPIO_PIN_SET : HAL_GPIO_PIN_RESET;
+ HAL_GPIO_WritePin(LED_PORT, LED_PIN, pin_state);
+}
+
+uint32_t board_button_read(void) {
+ return BUTTON_STATE_ACTIVE == HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN);
+}
+
+size_t board_get_unique_id(uint8_t id[], size_t max_len) {
+ (void) max_len;
+ volatile uint32_t * stm32_uuid = (volatile uint32_t *) UID_BASE;
+ uint32_t* id32 = (uint32_t*) (uintptr_t) id;
+ uint8_t const len = 12;
+
+ id32[0] = stm32_uuid[0];
+ id32[1] = stm32_uuid[1];
+ id32[2] = stm32_uuid[2];
+
+ return len;
+}
+
+int board_uart_read(uint8_t *buf, int len) {
+#ifdef UART_ID
+ int count = 0;
+ while (count < len) {
+ if (LL_USART_IsActiveFlag_RXNE_RXFNE(UARTn)) {
+ buf[count] = LL_USART_ReceiveData8(UARTn);
+ count++;
+ } else {
+ break;
+ }
+ }
+ return count;
+#else
+ (void) buf; (void) len;
+ return -1;
+#endif
+}
+
+int board_uart_write(void const *buf, int len) {
+#ifdef UART_ID
+ const uint8_t *p = (const uint8_t *) buf;
+ int count = 0;
+ while (count < len) {
+ if (LL_USART_IsActiveFlag_TXE_TXFNF(UARTn)) {
+ LL_USART_TransmitData8(UARTn, p[count]);
+ count++;
+ } else {
+ break;
+ }
+ }
+ return count;
+#else
+ (void) buf; (void) len;
+ return 0;
+#endif
+}
+
+#if CFG_TUSB_OS == OPT_OS_NONE
+volatile uint32_t system_ticks = 0;
+
+void SysTick_Handler(void) {
+ system_ticks++;
+ HAL_IncTick();
+}
+
+uint32_t tusb_time_millis_api(void) {
+ return system_ticks;
+}
+#endif
+
+void HardFault_Handler(void) {
+ __asm("BKPT #0\n");
+}
+
+#ifndef __ICCARM__
+// Implement _start() since we use linker flag '-nostartfiles'.
+extern int main(void);
+TU_ATTR_UNUSED void _start(void) {
+ // called by startup code
+ main();
+ while (1) {}
+}
+#endif
+
+// Required by __libc_init_array in startup code if we are compiling using
+// -nostdlib/-nostartfiles.
+void _init(void) {
+
+}
diff --git a/hw/bsp/stm32c5/family.cmake b/hw/bsp/stm32c5/family.cmake
new file mode 100644
index 000000000..5b63b1ce4
--- /dev/null
+++ b/hw/bsp/stm32c5/family.cmake
@@ -0,0 +1,111 @@
+include_guard()
+
+set(ST_FAMILY c5)
+set(ST_PREFIX stm32${ST_FAMILY}xx)
+
+set(ST_DRIVER ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx-drivers)
+set(ST_CMSIS ${TOP}/hw/mcu/st/stm32${ST_FAMILY}xx-dfp)
+set(CMSIS_6 ${TOP}/lib/CMSIS_6)
+
+# include board specific
+include(${CMAKE_CURRENT_LIST_DIR}/boards/${BOARD}/board.cmake)
+
+# toolchain set up
+set(CMAKE_SYSTEM_CPU cortex-m33 CACHE INTERNAL "System Processor")
+set(CMAKE_TOOLCHAIN_FILE ${TOP}/examples/build_system/cmake/toolchain/arm_${TOOLCHAIN}.cmake)
+
+set(FAMILY_MCUS STM32C5 CACHE INTERNAL "")
+set(OPENOCD_OPTION "-f interface/stlink.cfg -f target/stm32c5x.cfg")
+
+#------------------------------------
+# Startup & Linker script
+#------------------------------------
+set(STARTUP_FILE ${ST_CMSIS}/Source/startup_${MCU_VARIANT}.c)
+set(LD_FILE_Clang ${LD_FILE_GNU})
+
+#------------------------------------
+# BOARD_TARGET
+#------------------------------------
+function(family_add_board BOARD_TARGET)
+ add_library(${BOARD_TARGET} STATIC
+ ${ST_CMSIS}/Source/Templates/system_${ST_PREFIX}.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_cortex.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_flash_itf.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_pwr.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_rcc.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_gpio.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_uart.c
+ ${ST_DRIVER}/hal/${ST_PREFIX}_hal_dma.c
+ )
+ target_include_directories(${BOARD_TARGET} PUBLIC
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}
+ ${CMSIS_6}/CMSIS/Core/Include
+ ${ST_CMSIS}/Include
+ ${ST_DRIVER}/hal
+ ${ST_DRIVER}/ll
+ )
+ target_compile_definitions(${BOARD_TARGET} PUBLIC
+ )
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ target_compile_options(${BOARD_TARGET} PUBLIC -Wno-redundant-decls)
+ endif ()
+
+ if(CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ target_compile_definitions(${BOARD_TARGET} PUBLIC
+ __STACK_LIMIT=__StackLimit
+ __INITIAL_SP=__StackTop
+ )
+ endif ()
+
+ update_board(${BOARD_TARGET})
+endfunction()
+
+#------------------------------------
+# Functions
+#------------------------------------
+function(family_configure_example TARGET RTOS)
+ family_configure_common(${TARGET} ${RTOS})
+ family_add_tinyusb(${TARGET} OPT_MCU_STM32C5)
+
+ target_sources(${TARGET} PUBLIC
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../board.c
+ ${TOP}/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c
+ ${TOP}/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c
+ ${TOP}/src/portable/st/stm32_fsdev/fsdev_common.c
+ ${STARTUP_FILE}
+ )
+ target_include_directories(${TARGET} PUBLIC
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/boards/${BOARD}
+ )
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
+ target_link_options(${TARGET} PUBLIC
+ "LINKER:--script=${LD_FILE_GNU}"
+ -nostartfiles
+ --specs=nosys.specs --specs=nano.specs
+ )
+ elseif (CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ target_link_options(${TARGET} PUBLIC
+ "LINKER:--script=${LD_FILE_Clang}"
+ )
+ elseif (CMAKE_C_COMPILER_ID STREQUAL "IAR")
+ target_link_options(${TARGET} PUBLIC
+ "LINKER:--config=${LD_FILE_IAR}"
+ )
+ endif ()
+
+ if (CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang")
+ set_source_files_properties(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/family.c PROPERTIES COMPILE_FLAGS "-Wno-missing-prototypes")
+ endif ()
+
+ # Flashing
+ family_add_bin_hex(${TARGET})
+ family_flash_jlink(${TARGET})
+ family_flash_stlink(${TARGET})
+ #family_flash_openocd(${TARGET})
+endfunction()
diff --git a/hw/bsp/stm32c5/family.mk b/hw/bsp/stm32c5/family.mk
new file mode 100644
index 000000000..165ad4ad5
--- /dev/null
+++ b/hw/bsp/stm32c5/family.mk
@@ -0,0 +1,52 @@
+ST_FAMILY = c5
+ST_CMSIS = hw/mcu/st/stm32$(ST_FAMILY)xx-dfp
+ST_DRIVER = hw/mcu/st/stm32$(ST_FAMILY)xx-drivers
+
+include $(TOP)/$(BOARD_PATH)/board.mk
+CPU_CORE ?= cortex-m33
+
+# --------------
+# Compiler Flags
+# --------------
+CFLAGS += \
+ -DCFG_TUSB_MCU=OPT_MCU_STM32C5 \
+
+# GCC Flags
+CFLAGS += \
+ -flto \
+
+# suppress warnings caused by vendor mcu driver
+CFLAGS += -Wno-error=cast-align -Wno-error=unused-parameter -Wno-error=redundant-decls
+
+LDFLAGS += \
+ -nostdlib -nostartfiles \
+ --specs=nosys.specs --specs=nano.specs
+
+# -----------------
+# Sources & Include
+# -----------------
+
+SRC_C += \
+ src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c \
+ src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c \
+ src/portable/st/stm32_fsdev/fsdev_common.c \
+ $(ST_CMSIS)/Source/Templates/system_stm32$(ST_FAMILY)xx.c \
+ $(ST_CMSIS)/Source/startup_$(MCU_VARIANT).c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_cortex.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_flash_itf.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_pwr.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_rcc.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_gpio.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_uart.c \
+ $(ST_DRIVER)/hal/stm32$(ST_FAMILY)xx_hal_dma.c
+
+INC += \
+ $(TOP)/$(BOARD_PATH) \
+ $(TOP)/lib/CMSIS_6/CMSIS/Core/Include \
+ $(TOP)/$(ST_CMSIS)/Include \
+ $(TOP)/$(ST_DRIVER)/hal \
+ $(TOP)/$(ST_DRIVER)/ll
+
+# flash target using on-board stlink
+flash: flash-stlink
diff --git a/hw/bsp/stm32c5/linker/stm32c542xc_flash.icf b/hw/bsp/stm32c5/linker/stm32c542xc_flash.icf
new file mode 100644
index 000000000..ea826ba8e
--- /dev/null
+++ b/hw/bsp/stm32c5/linker/stm32c542xc_flash.icf
@@ -0,0 +1,46 @@
+/**
+******************************************************************************
+* @file stm32c542xc_flash.icf
+* @brief Linker File
+******************************************************************************
+* @attention
+*
+* Copyright (c) 2026 STMicroelectronics.
+* All rights reserved.
+*
+* This software is licensed under terms that can be found in the LICENSE file
+* in the root directory of this software component.
+* If no LICENSE file comes with this software, it is provided AS-IS.
+*
+******************************************************************************
+*/
+
+define memory mem with size = 4G;
+define region ROM = mem:[from 0x8000000 size 0x40000];
+define region RAM = mem:[from 0x20000000 size 0x10000];
+
+/* define blocks */
+define block HEAP with alignment = 8, size = 0x200 { };
+define block CSTACK with alignment = 8, size = 0x1000 { };
+
+/* setup initialization strategies */
+initialize by copy {
+ readwrite
+};
+
+do not initialize {
+ section .noinit
+};
+
+place at start of ROM { readonly section .intvec } ;
+
+/* sections placements */
+place in ROM {
+ readonly
+};
+
+place in RAM {
+ readwrite,
+ block HEAP,
+ block CSTACK
+};
diff --git a/hw/bsp/stm32c5/linker/stm32c542xc_flash.ld b/hw/bsp/stm32c5/linker/stm32c542xc_flash.ld
new file mode 100644
index 000000000..34e2bf660
--- /dev/null
+++ b/hw/bsp/stm32c5/linker/stm32c542xc_flash.ld
@@ -0,0 +1,185 @@
+/**
+******************************************************************************
+* @file stm32c542xc_flash.ld
+* @brief Linker File
+******************************************************************************
+* @attention
+*
+* Copyright (c) 2026 STMicroelectronics.
+* All rights reserved.
+*
+* This software is licensed under terms that can be found in the LICENSE file
+* in the root directory of this software component.
+* If no LICENSE file comes with this software, it is provided AS-IS.
+*
+******************************************************************************
+*/
+
+/* Entry Point */
+ENTRY(Reset_Handler)
+
+HEAP_SIZE = 0x200;
+STACK_SIZE = 0x1000;
+
+
+MEMORY
+{
+ ROM (rx) : org = 0x8000000, len = 0x40000
+ RAM (xrw) : org = 0x20000000, len = 0x10000
+}
+
+SECTIONS
+{
+ .vectors :
+ {
+ . = ALIGN(8);
+ KEEP(*(.vectors));
+ . = ALIGN(8);
+ } > ROM
+
+ .text :
+ {
+ . = ALIGN(8);
+ *(.text);
+ *(.text*);
+ *(.glue_7);
+ *(.glue_7t);
+ *(.eh_frame);
+ KEEP (*(.init));
+ KEEP (*(.fini));
+ . = ALIGN(8);
+ _etext = .;
+ } > ROM
+
+ .rodata :
+ {
+ . = ALIGN(8);
+ *(.rodata);
+ *(.rodata*);
+ . = ALIGN(8);
+ } > ROM
+
+ .ARM.extab : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ *(.ARM.extab* .gnu.linkonce.armextab.*)
+ . = ALIGN(8);
+ } > ROM
+
+ .ARM : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ __exidx_start = .;
+ *(.ARM.exidx*);
+ __exidx_end = .;
+ . = ALIGN(8);
+ } > ROM
+
+ .preinit_array : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ PROVIDE_HIDDEN (__preinit_array_start = .);
+ KEEP (*(.preinit_array*));
+ PROVIDE_HIDDEN (__preinit_array_end = .);
+ . = ALIGN(8);
+ } > ROM
+
+ .init_array : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ PROVIDE_HIDDEN (__init_array_start = .);
+ KEEP (*(SORT(.init_array.*)));
+ KEEP (*(.init_array*));
+ PROVIDE_HIDDEN (__init_array_end = .);
+ . = ALIGN(8);
+ } > ROM
+
+ .fini_array : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ PROVIDE_HIDDEN (__fini_array_start = .);
+ KEEP (*(SORT(.fini_array.*)));
+ KEEP (*(.fini_array*));
+ PROVIDE_HIDDEN (__fini_array_end = .);
+ . = ALIGN(8);
+ } > ROM
+
+ .copy.table : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ __copy_table_start__ = .;
+ LONG(LOADADDR(.data));
+ LONG (ADDR(.data));
+ LONG (SIZEOF(.data) / 4);
+ __copy_table_end__ = .;
+ } > ROM
+
+ .zero.table : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ . = ALIGN(8);
+ __zero_table_start__ = .;
+ LONG (ADDR(.bss));
+ LONG (SIZEOF(.bss) / 4);
+ __zero_table_end__ = .;
+ } > ROM
+
+ .data :
+ {
+ . = ALIGN(8);
+ _sidata = LOADADDR(.data);
+ __data_start__ = .;
+ _sdata = .;
+ *(.data);
+ *(.data*);
+ . = ALIGN(8);
+ _edata = .;
+ } > RAM AT> ROM
+
+ .bss :
+ {
+ . = ALIGN(8);
+ _sbss = .;
+ __bss_start__ = _sbss;
+ *(.bss);
+ *(.bss*);
+ *(COMMON);
+ . = ALIGN(8);
+ _ebss = .;
+ __bss_end__ = _ebss;
+ } > RAM
+
+ .heap (NOLOAD) :
+ {
+ . = ALIGN(8);
+ __end__ = .;
+ PROVIDE (end = .);
+ _heap_start = .;
+ . += HEAP_SIZE;
+ . = ALIGN(8);
+ _heap_end = .;
+ __HeapLimit = .;
+ } > RAM
+
+ .stack (NOLOAD) :
+ {
+ . = ALIGN(8);
+ __StackLimit = .;
+ . += STACK_SIZE;
+ . = ALIGN(8);
+ __StackTop = .;
+ _estack = .;
+ __stack = .;
+ } > RAM
+
+ /DISCARD/ :
+ {
+ libc.a ( * )
+ libm.a ( * )
+ libgcc.a ( * )
+ }
+
+ .ARM.attributes 0 :
+ {
+ *(.ARM.attributes)
+ }
+}
diff --git a/hw/bsp/stm32c5/stm32c5xx_hal_conf.h b/hw/bsp/stm32c5/stm32c5xx_hal_conf.h
new file mode 100644
index 000000000..0833fa3dd
--- /dev/null
+++ b/hw/bsp/stm32c5/stm32c5xx_hal_conf.h
@@ -0,0 +1,684 @@
+/**
+ ******************************************************************************
+ * @file stm32c5xx_hal_conf.h
+ * @brief HAL configuration file.
+ ******************************************************************************
+ * @attention
+ *
+ * Copyright (c) 2026 STMicroelectronics.
+ * All rights reserved.
+ *
+ * This software is licensed under terms that can be found in the mx_stm32c5xx_hal_drivers_license.md file
+ * in the same directory as the generated code.
+ * If no mx_stm32c5xx_hal_drivers_license.md file comes with this software, it is provided AS-IS.
+ *
+ ******************************************************************************
+ */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef STM32C5XX_HAL_CONF_H
+#define STM32C5XX_HAL_CONF_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+/* Exported types ------------------------------------------------------------*/
+/* Exported constants --------------------------------------------------------*/
+
+/** @defgroup HAL_Conf_How_To_Use HAL Conf How to Use
+ * @{
+ - The STM32 HAL configuration file, stm32tnxx_hal_conf.h, is designed to customize the behaviour of the HAL modules.
+ - The users can utilize the provided file as-is, where all HAL modules are enabled with their default settings.
+ - Alternatively, users have the flexibility to customize the file based on their application's requirements.
+ - For example, they can enable only the necessary HAL modules or modify the predefined settings to achieve
+ the desired functionality.
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup HAL_Conf_Exported_Constants HAL Conf Constants
+ * @{
+ */
+
+/** @defgroup HAL_System_Configuration HAL System Configuration
+ * @{
+ */
+
+/* ########################### System Configuration ############################# */
+/**
+ * @brief This is the HAL system configuration section
+ */
+#define USE_HAL_TICK_INT_PRIORITY 15U /*!< tick interrupt priority */
+#define USE_HAL_FLASH_PREFETCH 1U /*!< Enable FLASH prefetch */
+/**
+ * @}
+ */
+
+/** @defgroup HAL_MUTEX_Usage_Activation HAL MUTEX Usage Activation
+ * @{
+ */
+/* ########################## HAL MUTEX usage activation ####################### */
+/**
+ * @brief Used by the HAL PPP Acquire/Release APIs when the define USE_HAL_MUTEX is set to 1
+ */
+#define USE_HAL_MUTEX 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_API_Parameters_Check HAL API Parameters Check
+ * @{
+ */
+/* ########################## HAL API parameters check ##################### */
+/**
+ * @brief Run time parameter check activation
+ */
+#define USE_HAL_CHECK_PARAM 0U
+#define USE_HAL_SECURE_CHECK_PARAM 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_State_Transition HAL State Transition
+ * @{
+ */
+/* ########################## State transition ################################ */
+/**
+ * @brief Enable protection of state transition in thread safe
+ */
+#define USE_HAL_CHECK_PROCESS_STATE 0U
+/**
+ * @}
+ */
+
+/* ########################## Peripheral configuration ######################### */
+
+/** @defgroup HAL_ADC_Config HAL ADC Configuration
+ * @{
+ */
+/* ########################## HAL_ADC Config #################################### */
+#define USE_HAL_ADC_MODULE 0U
+#define USE_HAL_ADC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_ADC_REGISTER_CALLBACKS 0U
+#define USE_HAL_ADC_USER_DATA 0U
+#define USE_HAL_ADC_GET_LAST_ERRORS 0U
+#define USE_HAL_ADC_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_AES_Config HAL AES Configuration
+ * @{
+ */
+/* ########################## HAL_AES Config #################################### */
+#define USE_HAL_AES_MODULE 0U
+#define USE_HAL_AES_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_AES_REGISTER_CALLBACKS 0U
+#define USE_HAL_AES_USER_DATA 0U
+#define USE_HAL_AES_GET_LAST_ERRORS 0U
+#define USE_HAL_AES_DMA 0U
+#define USE_HAL_AES_ECB_CBC_ALGO 0U
+#define USE_HAL_AES_CTR_ALGO 0U
+#define USE_HAL_AES_GCM_GMAC_ALGO 0U
+#define USE_HAL_AES_CCM_ALGO 0U
+#define USE_HAL_AES_SUSPEND_RESUME 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_CCB_Config HAL CCB Configuration
+ * @{
+ */
+/* ########################## HAL_CCB Config #################################### */
+#define USE_HAL_CCB_MODULE 0U
+#define USE_HAL_CCB_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_CCB_USER_DATA 0U
+#define USE_HAL_CCB_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_COMP_Config HAL COMP Configuration
+ * @{
+ */
+/* ########################## HAL_COMP Config ################################### */
+#define USE_HAL_COMP_MODULE 0U
+#define USE_HAL_COMP_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_COMP_REGISTER_CALLBACKS 0U
+#define USE_HAL_COMP_USER_DATA 0U
+/* Use comparator with EXTI (needed to generate system wake-up event and CPU event) */
+#define USE_HAL_COMP_EXTI 0U
+/* Use comparators window mode feature */
+#define USE_HAL_COMP_WINDOW_MODE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_CORDIC_Config HAL CORDIC Configuration
+ * @{
+ */
+/* ########################## HAL_CORDIC Config ################################# */
+#define USE_HAL_CORDIC_MODULE 0U
+#define USE_HAL_CORDIC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_CORDIC_REGISTER_CALLBACKS 0U
+#define USE_HAL_CORDIC_USER_DATA 0U
+#define USE_HAL_CORDIC_GET_LAST_ERRORS 0U
+#define USE_HAL_CORDIC_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_CORTEX_Config HAL CORTEX Configuration
+ * @{
+ */
+/* ########################## HAL_CORTEX Config ################################# */
+#define USE_HAL_CORTEX_MODULE 1U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_CRC_Config HAL CRC Configuration
+ * @{
+ */
+/* ########################## HAL_CRC Config #################################### */
+#define USE_HAL_CRC_MODULE 0U
+#define USE_HAL_CRC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_CRC_USER_DATA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_CRS_Config HAL CRS Configuration
+ * @{
+ */
+/* ########################## HAL_CRS Config #################################### */
+#define USE_HAL_CRS_MODULE 0U
+#define USE_HAL_CRS_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_CRS_REGISTER_CALLBACKS 0U
+#define USE_HAL_CRS_USER_DATA 0U
+#define USE_HAL_CRS_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_DAC_Config HAL DAC Configuration
+ * @{
+ */
+/* ########################## HAL_DAC Config #################################### */
+#define USE_HAL_DAC_MODULE 0U
+#define USE_HAL_DAC_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_DAC_REGISTER_CALLBACKS 0U
+#define USE_HAL_DAC_USER_DATA 0U
+#define USE_HAL_DAC_GET_LAST_ERRORS 0U
+#define USE_HAL_DAC_DMA 0U
+#define USE_HAL_DAC_DUAL_CHANNEL 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_DBGMCU_Config HAL DBGMCU Configuration
+ * @{
+ */
+/* ########################## HAL_DBGMCU Config ################################# */
+#define USE_HAL_DBGMCU_MODULE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_DMA_Config HAL DMA Configuration
+ * @{
+ */
+/* ########################## HAL_DMA Config #################################### */
+#define USE_HAL_DMA_MODULE 1U
+#define USE_HAL_DMA_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_DMA_USER_DATA 0U
+#define USE_HAL_DMA_GET_LAST_ERRORS 0U
+#define USE_HAL_DMA_LINKEDLIST 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_ETH_Config HAL ETH Configuration
+ * @{
+ */
+/* ########################## HAL_ETH Config #################################### */
+#define USE_HAL_ETH_MODULE 0U
+#define USE_HAL_ETH_REGISTER_CALLBACKS 0U
+#define USE_HAL_ETH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_ETH_USER_DATA 0U
+#define USE_HAL_ETH_GET_LAST_ERRORS 0U
+#define USE_HAL_ETH_ATOMIC_CHANNEL_LOCK 0U
+#define USE_HAL_ETH_MAX_TX_CH_NB 1U
+#define USE_HAL_ETH_MAX_RX_CH_NB 1U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_EXTI_Config HAL EXTI Configuration
+ * @{
+ */
+/* ########################## HAL_EXTI Config ################################### */
+#define USE_HAL_EXTI_MODULE 0U
+#define USE_HAL_EXTI_REGISTER_CALLBACKS 0U
+#define USE_HAL_EXTI_USER_DATA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_FDCAN_Config HAL FDCAN Configuration
+ * @{
+ */
+/* ########################## HAL_FDCAN Config ################################## */
+#define USE_HAL_FDCAN_MODULE 0U
+#define USE_HAL_FDCAN_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0U
+#define USE_HAL_FDCAN_USER_DATA 0U
+#define USE_HAL_FDCAN_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_FLASH_Config HAL FLASH Configuration
+ * @{
+ */
+/* ########################## HAL_FLASH Config ################################## */
+#define USE_HAL_FLASH_MODULE 1U
+#define USE_HAL_FLASH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_FLASH_REGISTER_CALLBACKS 0U
+#define USE_HAL_FLASH_USER_DATA 0U
+#define USE_HAL_FLASH_GET_LAST_ERRORS 0U
+/* Use the FLASH program by address feature */
+#define USE_HAL_FLASH_PROGRAM_BY_ADDR 0U
+/* Use the FLASH erase by address feature */
+#define USE_HAL_FLASH_ERASE_BY_ADDR 0U
+/* Use the FLASH erase by PAGE feature */
+#define USE_HAL_FLASH_ERASE_PAGE 0U
+/* Use the FLASH bank erase feature */
+#define USE_HAL_FLASH_ERASE_BANK 0U
+/* Use the FLASH mass erase feature */
+#define USE_HAL_FLASH_MASS_ERASE 0U
+/* Use ECC errors handling APIs */
+#define USE_HAL_FLASH_ECC 0U
+/* Use FLASH HAL API for EDATA */
+#define USE_HAL_FLASH_OB_EDATA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_GPIO_Config HAL GPIO Configuration
+ * @{
+ */
+/* ########################## HAL_GPIO Config ################################### */
+#define USE_HAL_GPIO_MODULE 1U
+#define USE_HAL_GPIO_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+/**
+ * @}
+ */
+
+/** @defgroup HAL_HASH_Config HAL HASH Configuration
+ * @{
+ */
+/* ########################## HAL_HASH Config ################################### */
+#define USE_HAL_HASH_MODULE 0U
+#define USE_HAL_HASH_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_HASH_REGISTER_CALLBACKS 0U
+#define USE_HAL_HASH_USER_DATA 0U
+#define USE_HAL_HASH_GET_LAST_ERRORS 0U
+#define USE_HAL_HASH_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_HCD_Config HAL HCD Configuration
+ * @{
+ */
+/* ########################## HAL_HCD Config #################################### */
+#define USE_HAL_HCD_MODULE 0U
+#define USE_HAL_HCD_REGISTER_CALLBACKS 0U
+#define USE_HAL_HCD_USER_DATA 0U
+#define USE_HAL_HCD_GET_LAST_ERRORS 0U
+#define USE_HAL_HCD_USB_DOUBLE_BUFFER 0U
+#define USE_HAL_HCD_USB_EP_TYPE_ISOC 0U
+#define USE_HAL_HCD_MAX_CHANNEL_NB 16U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_I2C_Config HAL I2C Configuration
+ * @{
+ */
+/* ########################## HAL_I2C Config #################################### */
+#define USE_HAL_I2C_MODULE 0U
+#define USE_HAL_I2C_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_I2C_REGISTER_CALLBACKS 0U
+#define USE_HAL_I2C_USER_DATA 0U
+#define USE_HAL_I2C_GET_LAST_ERRORS 0U
+#define USE_HAL_I2C_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_I3C_Config HAL I3C Configuration
+ * @{
+ */
+/* ########################## HAL_I3C Config #################################### */
+#define USE_HAL_I3C_MODULE 0U
+#define USE_HAL_I3C_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_I3C_REGISTER_CALLBACKS 0U
+#define USE_HAL_I3C_USER_DATA 0U
+#define USE_HAL_I3C_GET_LAST_ERRORS 0U
+#define USE_HAL_I3C_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_I2S_Config HAL I2S Configuration
+ * @{
+ */
+/* ########################## HAL_I2S Config #################################### */
+#define USE_HAL_I2S_MODULE 0U
+#define USE_HAL_I2S_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_I2S_REGISTER_CALLBACKS 0U
+#define USE_HAL_I2S_USER_DATA 0U
+#define USE_HAL_I2S_GET_LAST_ERRORS 0U
+#define USE_HAL_I2S_OVR_UDR_ERRORS 0U
+#define USE_HAL_I2S_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_ICACHE_Config HAL ICACHE Configuration
+ * @{
+ */
+/* ########################## HAL_ICACHE Config ################################# */
+#define USE_HAL_ICACHE_MODULE 1U
+#define USE_HAL_ICACHE_REGISTER_CALLBACKS 0U
+#define USE_HAL_ICACHE_USER_DATA 0U
+#define USE_HAL_ICACHE_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_IWDG_Config HAL IWDG Configuration
+ * @{
+ */
+/* ########################## HAL_IWDG Config ################################### */
+#define USE_HAL_IWDG_MODULE 0U
+#define USE_HAL_IWDG_REGISTER_CALLBACKS 0U
+#define USE_HAL_IWDG_USER_DATA 0U
+/* IWDG time unit configuration */
+#define USE_HAL_IWDG_TIME_UNIT HAL_IWDG_TIME_UNIT_MS
+/* IWDG hardware start configuration
+ warning: In case of starting IWDG in Hardware mode, make sure that
+ USE_HAL_IWDG_HARDWARE_START is aligned with OB activated set for IWDG */
+#define USE_HAL_IWDG_HARDWARE_START 0U
+/* User can choose the value of the LSI frequency with the USE_HAL_IWDG_LSI_FREQ define:
+ - 0U : Dynamic LSI to be computed and set by the user.
+ - LSI_VALUE : LSI value of 32KHz.
+ - (LSI_VALUE / 128U): LSI value of 250Hz */
+#define USE_HAL_IWDG_LSI_FREQ LSI_VALUE
+/**
+ * @}
+ */
+
+/** @defgroup HAL_LPTIM_Config HAL LPTIM Configuration
+ * @{
+ */
+/* ########################## HAL_LPTIM Config ################################## */
+#define USE_HAL_LPTIM_MODULE 0U
+#define USE_HAL_LPTIM_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U
+#define USE_HAL_LPTIM_USER_DATA 0U
+#define USE_HAL_LPTIM_GET_LAST_ERRORS 0U
+#define USE_HAL_LPTIM_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_OPAMP_Config HAL OPAMP Configuration
+ * @{
+ */
+/* ########################## HAL_OPAMP Config ################################## */
+#define USE_HAL_OPAMP_MODULE 0U
+#define USE_HAL_OPAMP_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_OPAMP_USER_DATA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_PCD_Config HAL PCD Configuration
+ * @{
+ */
+/* ########################## HAL_PCD Config #################################### */
+#define USE_HAL_PCD_MODULE 1U
+#define USE_HAL_PCD_REGISTER_CALLBACKS 0U
+#define USE_HAL_PCD_USER_DATA 0U
+#define USE_HAL_PCD_GET_LAST_ERRORS 0U
+#define USE_HAL_PCD_USB_DOUBLE_BUFFER 0U
+#define USE_HAL_PCD_USB_LPM 0U
+#define USE_HAL_PCD_USB_BCD 0U
+#define USE_HAL_PCD_USB_EP_TYPE_ISOC 0U
+#define USE_HAL_PCD_MAX_ENDPOINT_NB 8U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_PKA_Config HAL PKA Configuration
+ * @{
+ */
+/* ########################## HAL_PKA Config #################################### */
+#define USE_HAL_PKA_MODULE 0U
+#define USE_HAL_PKA_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_PKA_REGISTER_CALLBACKS 0U
+#define USE_HAL_PKA_USER_DATA 0U
+#define USE_HAL_PKA_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_PWR_Config HAL PWR Configuration
+ * @{
+ */
+/* ########################## HAL_PWR Config #################################### */
+#define USE_HAL_PWR_MODULE 1U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_RAMCFG_Config HAL RAMCFG Configuration
+ * @{
+ */
+/* ########################## HAL_RAMCFG Config ################################# */
+#define USE_HAL_RAMCFG_MODULE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_RCC_Config HAL RCC Configuration
+ * @{
+ */
+/* ########################## HAL_RCC Config #################################### */
+#define USE_HAL_RCC_MODULE 1U
+/* Use RCC HAL API for Reset function */
+#define USE_HAL_RCC_RESET_PERIPH_CLOCK_MANAGEMENT 0U
+#define USE_HAL_RCC_RESET_RTC_DOMAIN 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_RNG_Config HAL RNG Configuration
+ * @{
+ */
+/* ########################## HAL_RNG Config #################################### */
+#define USE_HAL_RNG_MODULE 0U
+#define USE_HAL_RNG_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_RNG_REGISTER_CALLBACKS 0U
+#define USE_HAL_RNG_USER_DATA 0U
+#define USE_HAL_RNG_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_RTC_Config HAL RTC Configuration
+ * @{
+ */
+/* ########################## HAL_RTC Config #################################### */
+#define USE_HAL_RTC_MODULE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SBS_Config HAL SBS Configuration
+ * @{
+ */
+/* ########################## HAL_SBS Config #################################### */
+#define USE_HAL_SBS_MODULE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SMARTCARD_Config HAL SMARTCARD Configuration
+ * @{
+ */
+/* ########################## HAL_SMARTCARD Config ############################## */
+#define USE_HAL_SMARTCARD_MODULE 0U
+#define USE_HAL_SMARTCARD_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U
+#define USE_HAL_SMARTCARD_USER_DATA 0U
+#define USE_HAL_SMARTCARD_GET_LAST_ERRORS 0U
+#define USE_HAL_SMARTCARD_DMA 0U
+/* #################### SMARTCARD FIFO configuration ######################## */
+#define USE_HAL_SMARTCARD_FIFO 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SMBUS_Config HAL SMBUS Configuration
+ * @{
+ */
+/* ########################## HAL_SMBUS Config ################################## */
+#define USE_HAL_SMBUS_MODULE 0U
+#define USE_HAL_SMBUS_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U
+#define USE_HAL_SMBUS_USER_DATA 0U
+#define USE_HAL_SMBUS_GET_LAST_ERRORS 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_SPI_Config HAL SPI Configuration
+ * @{
+ */
+/* ########################## HAL_SPI Config #################################### */
+#define USE_HAL_SPI_MODULE 0U
+#define USE_HAL_SPI_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_SPI_REGISTER_CALLBACKS 0U
+#define USE_HAL_SPI_USER_DATA 0U
+#define USE_HAL_SPI_GET_LAST_ERRORS 0U
+#define USE_HAL_SPI_DMA 0U
+/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver
+ * Activated: CRC code is present inside driver
+ * Deactivated: CRC code cleaned from driver
+ */
+#define USE_HAL_SPI_CRC 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_TAMP_Config HAL TAMP Configuration
+ * @{
+ */
+/* ########################## HAL_TAMP Config ################################### */
+#define USE_HAL_TAMP_MODULE 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_TIM_Config HAL TIM Configuration
+ * @{
+ */
+/* ########################## HAL_TIM Config #################################### */
+#define USE_HAL_TIM_MODULE 0U
+#define USE_HAL_TIM_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_TIM_REGISTER_CALLBACKS 0U
+#define USE_HAL_TIM_USER_DATA 0U
+#define USE_HAL_TIM_GET_LAST_ERRORS 0U
+#define USE_HAL_TIM_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_UART_Config HAL UART Configuration
+ * @{
+ */
+/* ########################## HAL_UART Config ################################### */
+#define USE_HAL_UART_MODULE 1U
+#define USE_HAL_UART_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_UART_REGISTER_CALLBACKS 0U
+#define USE_HAL_UART_USER_DATA 0U
+#define USE_HAL_UART_GET_LAST_ERRORS 0U
+#define USE_HAL_UART_DMA 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_USART_Config HAL USART Configuration
+ * @{
+ */
+/* ########################## HAL_USART Config ################################## */
+#define USE_HAL_USART_MODULE 0U
+#define USE_HAL_USART_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_USART_REGISTER_CALLBACKS 0U
+#define USE_HAL_USART_USER_DATA 0U
+#define USE_HAL_USART_GET_LAST_ERRORS 0U
+#define USE_HAL_USART_DMA 0U
+#define USE_HAL_USART_FIFO 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_WWDG_Config HAL WWDG Configuration
+ * @{
+ */
+/* ########################## HAL_WWDG Config ################################### */
+#define USE_HAL_WWDG_MODULE 0U
+#define USE_HAL_WWDG_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U
+#define USE_HAL_WWDG_USER_DATA 0U
+/* WWDG time unit configuration */
+#define USE_HAL_WWDG_TIME_UNIT HAL_WWDG_TIME_UNIT_MS
+/* WWDG hardware start configuration
+ warning: In case of starting WWDG in Hardware mode, make sure that
+ USE_HAL_WWDG_HARDWARE_START is aligned with OB activated set for WWDG */
+#define USE_HAL_WWDG_HARDWARE_START 0U
+/**
+ * @}
+ */
+
+/** @defgroup HAL_XSPI_Config HAL XSPI Configuration
+ * @{
+ */
+/* ########################## HAL_XSPI Config ################################### */
+#define USE_HAL_XSPI_MODULE 0U
+#define USE_HAL_XSPI_CLK_ENABLE_MODEL HAL_CLK_ENABLE_NO
+#define USE_HAL_XSPI_REGISTER_CALLBACKS 0U
+#define USE_HAL_XSPI_USER_DATA 0U
+#define USE_HAL_XSPI_GET_LAST_ERRORS 0U
+#define USE_HAL_XSPI_DMA 0U
+#define USE_HAL_XSPI_HYPERBUS 0U
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* STM32C5XX_HAL_CONF_H */
diff --git a/hw/bsp/stm32f0/family.c b/hw/bsp/stm32f0/family.c
index f413163e5..c77ef4008 100644
--- a/hw/bsp/stm32f0/family.c
+++ b/hw/bsp/stm32f0/family.c
@@ -206,7 +206,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32f1/family.c b/hw/bsp/stm32f1/family.c
index 74e0f53f2..67427da1f 100644
--- a/hw/bsp/stm32f1/family.c
+++ b/hw/bsp/stm32f1/family.c
@@ -63,9 +63,11 @@ void USB_LP_IRQHandler(void) {
tud_int_handler(0);
}
-void USBWakeUp_IRQHandler(void) {
- tud_int_handler(0);
-}
+// USB wakeup EXTI IRQ is not enabled by the fsdev driver (see fsdev_stm32.h);
+// restore when STOP-mode wakeup is implemented.
+//void USBWakeUp_IRQHandler(void) {
+// tud_int_handler(0);
+//}
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM
@@ -128,7 +130,7 @@ void board_init(void) {
// If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher )
NVIC_SetPriority(USB_HP_CAN1_TX_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
- NVIC_SetPriority(USBWakeUp_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
+ //NVIC_SetPriority(USBWakeUp_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
#endif
// LED
@@ -246,7 +248,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32f2/family.c b/hw/bsp/stm32f2/family.c
index 051a026c5..260e5e067 100644
--- a/hw/bsp/stm32f2/family.c
+++ b/hw/bsp/stm32f2/family.c
@@ -210,7 +210,7 @@ int board_uart_write(void const* buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32f3/family.c b/hw/bsp/stm32f3/family.c
index 0864d0fad..bddf224d2 100644
--- a/hw/bsp/stm32f3/family.c
+++ b/hw/bsp/stm32f3/family.c
@@ -76,9 +76,10 @@ void USB_LP_IRQHandler(void) {
// USB wakeup interrupt (Channel 76): Triggered by the wakeup event from the USB
// Suspend mode.
-void USBWakeUp_RMP_IRQHandler(void) {
- tud_int_handler(0);
-}
+// Not enabled by the fsdev driver (see fsdev_stm32.h); restore for STOP-mode wakeup.
+//void USBWakeUp_RMP_IRQHandler(void) {
+// tud_int_handler(0);
+//}
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM
@@ -222,7 +223,7 @@ int board_uart_write(void const* buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32f4/family.c b/hw/bsp/stm32f4/family.c
index f4ef99150..3a323e673 100644
--- a/hw/bsp/stm32f4/family.c
+++ b/hw/bsp/stm32f4/family.c
@@ -109,6 +109,11 @@ void USARTn_IRQHandler(void) {
void board_init(void) {
board_clock_init();
+
+ __HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
+ __HAL_FLASH_DATA_CACHE_ENABLE();
+ __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
+
//SystemCoreClockUpdate();
// Enable All GPIOs clocks
@@ -295,7 +300,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32f7/boards/stm32f746disco/board.cmake b/hw/bsp/stm32f7/boards/stm32f746disco/board.cmake
index bc26c6ef4..5f46365f4 100644
--- a/hw/bsp/stm32f7/boards/stm32f746disco/board.cmake
+++ b/hw/bsp/stm32f7/boards/stm32f746disco/board.cmake
@@ -1,5 +1,5 @@
set(MCU_VARIANT stm32f746xx)
-set(JLINK_DEVICE stm32f746xx)
+set(JLINK_DEVICE stm32f746ng)
set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32F746ZGTx_FLASH.ld)
diff --git a/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake b/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake
index 2335b869e..dbdd07e4d 100644
--- a/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake
+++ b/hw/bsp/stm32f7/boards/stm32f769disco/board.cmake
@@ -1,5 +1,6 @@
set(MCU_VARIANT stm32f769xx)
set(JLINK_DEVICE stm32f769ni)
+#set(JLINK_OPTION "-USB 000778170924")
set(LD_FILE_GNU ${CMAKE_CURRENT_LIST_DIR}/STM32F769ZITx_FLASH.ld)
diff --git a/hw/bsp/stm32f7/family.c b/hw/bsp/stm32f7/family.c
index 078e372d8..9427ac4a6 100644
--- a/hw/bsp/stm32f7/family.c
+++ b/hw/bsp/stm32f7/family.c
@@ -82,8 +82,9 @@ static UART_HandleTypeDef UartHandle = {.Instance = USARTn,
.OverSampling = UART_OVERSAMPLING_16,
}};
-// RX ring buffer via RXNE interrupt — no HAL IT functions used (avoid HAL state conflicts)
-static uint8_t uart_rx_ff_buf[32];
+// RX ring buffer via RXNE interrupt — no HAL IT functions used (avoid HAL state conflicts).
+// Sized to absorb a full host-forwarding burst (>64B) when the main loop briefly stalls.
+static uint8_t uart_rx_ff_buf[256];
static tu_fifo_t uart_rx_ff;
void USARTn_IRQHandler(void) {
@@ -142,13 +143,24 @@ void board_init(void) {
// 1ms tick timer
SysTick_Config(SystemCoreClock / 1000);
+ // Set UART interrupt higher priority than USB OTG since the F7 USART has no hardware RX FIFO, so a host example's
+ // UART RX must not be starved by the frequent USB host interrupts or incoming bytes overrun (ORE) and dropped.
+ NVIC_SetPriority(OTG_FS_IRQn, 1);
+ NVIC_SetPriority(OTG_HS_IRQn, 1);
+ #ifdef UART_ID
+ NVIC_SetPriority(USARTn_IRQn, 0);
+ #endif
+
#elif CFG_TUSB_OS == OPT_OS_FREERTOS
// Explicitly disable systick to prevent its ISR from running before scheduler start
SysTick->CTRL &= ~1U;
// If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher )
- NVIC_SetPriority(OTG_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
- NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
+ NVIC_SetPriority(OTG_FS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
+ NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1);
+ #ifdef UART_ID
+ NVIC_SetPriority(USARTn_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
+ #endif
#endif
#ifdef UART_ID
@@ -156,7 +168,6 @@ void board_init(void) {
HAL_UART_Init(&UartHandle);
tu_fifo_config(&uart_rx_ff, uart_rx_ff_buf, sizeof(uart_rx_ff_buf), false);
USARTn->CR1 |= USART_CR1_RXNEIE;
- NVIC_SetPriority(USARTn_IRQn, (1 << __NVIC_PRIO_BITS) - 1);
NVIC_EnableIRQ(USARTn_IRQn);
#endif
@@ -357,7 +368,7 @@ int board_uart_write(const void *buf, int len) {
#else
(void)buf;
(void)len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32g0/family.c b/hw/bsp/stm32g0/family.c
index d0ff8bac2..cb674ccc9 100644
--- a/hw/bsp/stm32g0/family.c
+++ b/hw/bsp/stm32g0/family.c
@@ -206,7 +206,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32g4/family.c b/hw/bsp/stm32g4/family.c
index 98739ffd5..cf7d4329b 100644
--- a/hw/bsp/stm32g4/family.c
+++ b/hw/bsp/stm32g4/family.c
@@ -61,9 +61,11 @@ void USB_LP_IRQHandler(void) {
tud_int_handler(0);
}
-void USBWakeUp_IRQHandler(void) {
- tud_int_handler(0);
-}
+// USB wakeup EXTI IRQ is not enabled by the fsdev driver (see fsdev_stm32.h);
+// restore when STOP-mode wakeup is implemented.
+//void USBWakeUp_IRQHandler(void) {
+// tud_int_handler(0);
+//}
// USB PD
void UCPD1_IRQHandler(void) {
@@ -99,7 +101,7 @@ void board_init(void) {
// If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher )
NVIC_SetPriority(USB_HP_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
NVIC_SetPriority(USB_LP_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
- NVIC_SetPriority(USBWakeUp_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
+ //NVIC_SetPriority(USBWakeUp_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY);
#endif
GPIO_InitTypeDef GPIO_InitStruct;
@@ -236,7 +238,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h b/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h
index 5788837ab..e9c406486 100644
--- a/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h
+++ b/hw/bsp/stm32h5/boards/stm32h573i_dk/board.h
@@ -204,6 +204,10 @@ int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Le
return 0;
}
+static int32_t i2c_get_tick(void) {
+ return (int32_t) HAL_GetTick();
+}
+
static inline void board_init2(void) {
TCPP0203_IO_t io_ctx;
@@ -212,6 +216,7 @@ static inline void board_init2(void) {
io_ctx.DeInit = board_tcpp0203_deinit;
io_ctx.ReadReg = i2c_readreg;
io_ctx.WriteReg = i2c_writereg;
+ io_ctx.GetTick = i2c_get_tick;
TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, );
diff --git a/hw/bsp/stm32h5/family.c b/hw/bsp/stm32h5/family.c
index 8298dfaab..f52f94f32 100644
--- a/hw/bsp/stm32h5/family.c
+++ b/hw/bsp/stm32h5/family.c
@@ -238,7 +238,7 @@ int board_uart_write(void const* buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32h7/family.c b/hw/bsp/stm32h7/family.c
index b32f73754..5173c5401 100644
--- a/hw/bsp/stm32h7/family.c
+++ b/hw/bsp/stm32h7/family.c
@@ -328,7 +328,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h
index b1446414e..996eb1515 100644
--- a/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h
+++ b/hw/bsp/stm32h7rs/boards/stm32h7s3nucleo/board.h
@@ -223,6 +223,10 @@ int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Le
return 0;
}
+static int32_t i2c_get_tick(void) {
+ return (int32_t) HAL_GetTick();
+}
+
static inline void board_init2(void) {
TCPP0203_IO_t io_ctx;
@@ -231,6 +235,7 @@ static inline void board_init2(void) {
io_ctx.DeInit = board_tcpp0203_deinit;
io_ctx.ReadReg = i2c_readreg;
io_ctx.WriteReg = i2c_writereg;
+ io_ctx.GetTick = i2c_get_tick;
TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, );
diff --git a/hw/bsp/stm32h7rs/family.c b/hw/bsp/stm32h7rs/family.c
index 7ae9e5532..b0841c947 100644
--- a/hw/bsp/stm32h7rs/family.c
+++ b/hw/bsp/stm32h7rs/family.c
@@ -490,7 +490,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32l0/family.c b/hw/bsp/stm32l0/family.c
index 930fa2d66..a4a0ebbfe 100644
--- a/hw/bsp/stm32l0/family.c
+++ b/hw/bsp/stm32l0/family.c
@@ -176,7 +176,7 @@ int board_uart_write(void const* buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32l4/family.c b/hw/bsp/stm32l4/family.c
index 7a8acb3de..96de82bd5 100644
--- a/hw/bsp/stm32l4/family.c
+++ b/hw/bsp/stm32l4/family.c
@@ -264,7 +264,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32n6/boards/stm32n6570dk/board.h b/hw/bsp/stm32n6/boards/stm32n6570dk/board.h
index 4d162bbca..0cba5e1f9 100644
--- a/hw/bsp/stm32n6/boards/stm32n6570dk/board.h
+++ b/hw/bsp/stm32n6/boards/stm32n6570dk/board.h
@@ -244,6 +244,10 @@ static int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint
return 0;
}
+static int32_t i2c_get_tick(void) {
+ return (int32_t) HAL_GetTick();
+}
+
static inline void board_init2(void) {
TCPP0203_IO_t io_ctx;
@@ -252,6 +256,7 @@ static inline void board_init2(void) {
io_ctx.DeInit = board_tcpp0203_deinit;
io_ctx.ReadReg = i2c_readreg;
io_ctx.WriteReg = i2c_writereg;
+ io_ctx.GetTick = i2c_get_tick;
TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, );
diff --git a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h
index c26367af6..be9ea7a31 100644
--- a/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h
+++ b/hw/bsp/stm32n6/boards/stm32n657nucleo/board.h
@@ -239,6 +239,10 @@ int32_t i2c_writereg(uint16_t DevAddr, uint16_t Reg, uint8_t *pData, uint16_t Le
return 0;
}
+static int32_t i2c_get_tick(void) {
+ return (int32_t) HAL_GetTick();
+}
+
static inline void board_init2(void) {
TCPP0203_IO_t io_ctx;
@@ -247,6 +251,7 @@ static inline void board_init2(void) {
io_ctx.DeInit = board_tcpp0203_deinit;
io_ctx.ReadReg = i2c_readreg;
io_ctx.WriteReg = i2c_writereg;
+ io_ctx.GetTick = i2c_get_tick;
TU_ASSERT(TCPP0203_RegisterBusIO(&tcpp0203_obj, &io_ctx) == TCPP0203_OK, );
diff --git a/hw/bsp/stm32n6/family.c b/hw/bsp/stm32n6/family.c
index 95578af04..80de20c6a 100644
--- a/hw/bsp/stm32n6/family.c
+++ b/hw/bsp/stm32n6/family.c
@@ -388,7 +388,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32u0/family.c b/hw/bsp/stm32u0/family.c
index 5cf6e1eb2..0d20ba43f 100644
--- a/hw/bsp/stm32u0/family.c
+++ b/hw/bsp/stm32u0/family.c
@@ -166,6 +166,19 @@ uint32_t board_button_read(void) {
return BUTTON_STATE_ACTIVE == HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN);
}
+size_t board_get_unique_id(uint8_t id[], size_t max_len) {
+ (void) max_len;
+ volatile uint32_t *stm32_uuid = (volatile uint32_t *) UID_BASE;
+ uint32_t *id32 = (uint32_t *) (uintptr_t) id;
+ uint8_t const len = 12;
+
+ id32[0] = stm32_uuid[0];
+ id32[1] = stm32_uuid[1];
+ id32[2] = stm32_uuid[2];
+
+ return len;
+}
+
int board_uart_read(uint8_t* buf, int len) {
#ifdef UART_ID
int count = 0;
@@ -199,7 +212,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32u5/family.c b/hw/bsp/stm32u5/family.c
index 41e354351..7969b1c70 100644
--- a/hw/bsp/stm32u5/family.c
+++ b/hw/bsp/stm32u5/family.c
@@ -304,7 +304,7 @@ int board_uart_write(void const *buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/stm32wb/family.c b/hw/bsp/stm32wb/family.c
index d97be2115..1f1da2271 100644
--- a/hw/bsp/stm32wb/family.c
+++ b/hw/bsp/stm32wb/family.c
@@ -196,7 +196,7 @@ int board_uart_write(void const* buf, int len) {
return count;
#else
(void) buf; (void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/hw/bsp/tm4c/family.c b/hw/bsp/tm4c/family.c
index 6988a264e..4f85be220 100644
--- a/hw/bsp/tm4c/family.c
+++ b/hw/bsp/tm4c/family.c
@@ -36,7 +36,7 @@ static void board_uart_init(void) {
// BAUDRATE = 115200, with SystemCoreClock = 50 Mhz refer manual for calculation
// - BRDI = SystemCoreClock / (16* baud)
// - BRDF = int(fraction*64 + 0.5)
- UART0->CTL &= ~(1 << 0); // Disable UART0 by clearing UARTEN bit in the UARTCTL register
+ UART0->CTL &= ~(1U << 0); // Disable UART0 by clearing UARTEN bit in the UARTCTL register
UART0->IBRD = 27; // Write the integer portion of the BRD to the UARTIRD register
UART0->FBRD = 8; // Write the fractional portion of the BRD to the UARTFBRD registerer
@@ -58,6 +58,14 @@ static void board_button_init(GPIOA_Type* port, uint8_t PinMsk) {
/* Set direction */
port->DIR &= ~PinMsk;
+
+ /* Enable internal pull so the idle state is deterministic. LaunchPad buttons
+ * connect the pin to GND when pressed (active-low) and require a pull-up. */
+#if BUTTON_STATE_ACTIVE == 0
+ port->PUR |= PinMsk;
+#else
+ port->PDR |= PinMsk;
+#endif
}
static void board_led_init(GPIOA_Type* port, uint8_t PinMsk, uint8_t dirmsk) {
diff --git a/hw/bsp/tm4c/family.cmake b/hw/bsp/tm4c/family.cmake
index 41b8a597a..ce7c62409 100644
--- a/hw/bsp/tm4c/family.cmake
+++ b/hw/bsp/tm4c/family.cmake
@@ -79,6 +79,6 @@ function(family_configure_example TARGET RTOS)
# Flashing
family_add_bin_hex(${TARGET})
family_flash_jlink(${TARGET})
- family_flash_openocd(${TARGET})
- family_flash_uniflash(${TARGET})
+ family_flash_lm4flash(${TARGET})
+ # family_flash_uniflash(${TARGET})
endfunction()
diff --git a/hw/bsp/xmc4000/family.c b/hw/bsp/xmc4000/family.c
index 1325b784b..7e224d092 100644
--- a/hw/bsp/xmc4000/family.c
+++ b/hw/bsp/xmc4000/family.c
@@ -150,7 +150,7 @@ int board_uart_write(void const* buf, int len) {
#else
(void) buf;
(void) len;
- return 0;
+ return -1;
#endif
}
diff --git a/lib/networking/rndis_reports.c b/lib/networking/rndis_reports.c
index 5e824d5a5..f06bc5507 100644
--- a/lib/networking/rndis_reports.c
+++ b/lib/networking/rndis_reports.c
@@ -36,9 +36,13 @@
#include "rndis_protocol.h"
#include "netif/ethernet.h"
-#define RNDIS_LINK_SPEED 12000000 /* Link baudrate (12Mbit/s for USB-FS) */
#define RNDIS_VENDOR "TinyUSB" /* NIC vendor name */
+// USB link speed in bits/sec, reflected to host via OID_GEN_LINK_SPEED.
+static inline uint32_t rndis_link_speed_bps(void) {
+ return (tud_speed_get() == TUSB_SPEED_HIGH) ? 480000000U : 12000000U;
+}
+
static const uint8_t *const station_hwaddr = tud_network_mac_address;
static const uint8_t *const permanent_hwaddr = tud_network_mac_address;
@@ -127,7 +131,7 @@ static void rndis_query(void)
case OID_GEN_MEDIA_IN_USE: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIUM_802_3); return;
case OID_GEN_PHYSICAL_MEDIUM: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, NDIS_MEDIUM_802_3); return;
case OID_GEN_HARDWARE_STATUS: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0); return;
- case OID_GEN_LINK_SPEED: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, RNDIS_LINK_SPEED / 100); return;
+ case OID_GEN_LINK_SPEED: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, rndis_link_speed_bps() / 100U); return;
case OID_GEN_VENDOR_ID: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, 0x00FFFFFF); return;
case OID_GEN_VENDOR_DESCRIPTION: rndis_query_cmplt(RNDIS_STATUS_SUCCESS, rndis_vendor, strlen(rndis_vendor) + 1); return;
case OID_GEN_CURRENT_PACKET_FILTER: rndis_query_cmplt32(RNDIS_STATUS_SUCCESS, oid_packet_filter); return;
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 00f466007..b3e05f60f 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -8,13 +8,13 @@ function(tinyusb_sources_get OUTPUT_VAR)
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/common/tusb_fifo.c
# device
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/device/usbd.c
- ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/device/usbd_control.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/audio/audio_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/cdc/cdc_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/dfu/dfu_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/dfu/dfu_rt_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/hid/hid_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi_device.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi2_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/msc/msc_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/mtp/mtp_device.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/net/ecm_rndis_device.c
@@ -29,6 +29,7 @@ function(tinyusb_sources_get OUTPUT_VAR)
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/cdc/cdc_host.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/hid/hid_host.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi_host.c
+ ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/midi/midi2_host.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/msc/msc_host.c
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/class/vendor/vendor_host.c
# typec
diff --git a/src/class/audio/audio.h b/src/class/audio/audio.h
index cff38cc22..428391bb2 100644
--- a/src/class/audio/audio.h
+++ b/src/class/audio/audio.h
@@ -490,10 +490,19 @@ typedef struct TU_ATTR_PACKED {
uint8_t bDescriptorType; ///< Descriptor Type. Value: TUSB_DESC_ENDPOINT.
uint8_t bEndpointAddress;///< The address of the endpoint on the USB device described by this descriptor.
struct TU_ATTR_PACKED {
+#if (TU_BITFIELD_ORDER == TU_BITFIELD_LE)
uint8_t xfer : 2; // Control, ISO, Bulk, Interrupt
uint8_t sync : 2; // None, Asynchronous, Adaptive, Synchronous
uint8_t usage : 2; // Data, Feedback, Implicit feedback
uint8_t : 2;
+#elif (TU_BITFIELD_ORDER == TU_BITFIELD_BE)
+ uint8_t : 2;
+ uint8_t usage : 2; // Data, Feedback, Implicit feedback
+ uint8_t sync : 2; // None, Asynchronous, Adaptive, Synchronous
+ uint8_t xfer : 2; // Control, ISO, Bulk, Interrupt
+#else
+ #error "Please define TU_BITFIELD_ORDER as TU_BITFIELD_LE or TU_BITFIELD_BE"
+#endif
} bmAttributes;
uint16_t wMaxPacketSize; ///< Maximum packet size this endpoint is capable of sending or receiving when this configuration is selected.
uint8_t bInterval; ///< Interval for polling endpoint for data transfers.
@@ -1177,29 +1186,6 @@ typedef struct TU_ATTR_PACKED {
uint16_t wLockDelay; ///< Indicates the time it takes this endpoint to reliably lock its internal clock recovery circuitry. Units used depend on the value of the bLockDelayUnits field.
} audio20_desc_cs_as_iso_data_ep_t;
-// 5.2.2 Control Request Layout
-typedef struct TU_ATTR_PACKED {
- union {
- struct TU_ATTR_PACKED {
- uint8_t recipient : 5;///< Recipient type tusb_request_recipient_t.
- uint8_t type : 2; ///< Request type tusb_request_type_t.
- uint8_t direction : 1;///< Direction type. tusb_dir_t
- } bmRequestType_bit;
-
- uint8_t bmRequestType;
- };
-
- uint8_t bRequest;///< Request type audio_cs_req_t
- uint8_t bChannelNumber;
- uint8_t bControlSelector;
- union {
- uint8_t bInterface;
- uint8_t bEndpoint;
- };
- uint8_t bEntityID;
- uint16_t wLength;
-} audio20_control_request_t;
-
//// 5.2.3 Control Request Parameter Block Layout
// 5.2.3.1 1-byte Control CUR Parameter Block
diff --git a/src/class/cdc/cdc_host.c b/src/class/cdc/cdc_host.c
index 62c313b83..4441222c8 100644
--- a/src/class/cdc/cdc_host.c
+++ b/src/class/cdc/cdc_host.c
@@ -99,6 +99,7 @@ typedef struct {
typedef struct {
TUH_EPBUF_DEF(tx, CFG_TUH_CDC_TX_EPSIZE);
TUH_EPBUF_DEF(rx, CFG_TUH_CDC_RX_EPSIZE);
+ TUH_EPBUF_DEF(ctrl, 8);
} cdch_epbuf_t;
static cdch_interface_t cdch_data[CFG_TUH_CDC];
@@ -1003,15 +1004,16 @@ static bool acm_set_line_coding(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_
.wLength = tu_htole16((uint16_t) sizeof(cdc_line_coding_t))
};
- // use usbh enum buf to hold line coding since user line_coding variable does not live long enough
- uint8_t *enum_buf = usbh_get_enum_buf();
- memcpy(enum_buf, &p_cdc->requested_line.coding, sizeof(cdc_line_coding_t));
+ // use local ctrl buf to hold line coding since user line_coding variable does not live long enough
+ uint8_t const idx = get_idx_by_ptr(p_cdc);
+ uint8_t *ctrl_buf = cdch_epbuf[idx].ctrl;
+ memcpy(ctrl_buf, &p_cdc->requested_line.coding, sizeof(cdc_line_coding_t));
tuh_xfer_t xfer = {
.daddr = p_cdc->daddr,
.ep_addr = 0,
.setup = &request,
- .buffer = enum_buf,
+ .buffer = ctrl_buf,
.complete_cb = complete_cb,
.user_data = user_data
};
@@ -1491,7 +1493,7 @@ static inline uint32_t ftdi_get_divisor(cdch_interface_t *p_cdc) {
//------------- Control Request -------------//
static bool cp210x_set_request(cdch_interface_t * p_cdc, uint8_t command, uint16_t value,
- uint8_t * buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
+ uint8_t const * buffer, uint16_t length, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
@@ -1504,19 +1506,20 @@ static bool cp210x_set_request(cdch_interface_t * p_cdc, uint8_t command, uint16
.wLength = tu_htole16(length)
};
- // use usbh enum buf since application variable does not live long enough
- uint8_t * enum_buf = NULL;
+ // use local ctrl buf since application variable does not live long enough
+ uint8_t * ctrl_buf = NULL;
if (buffer && length > 0) {
- enum_buf = usbh_get_enum_buf();
- tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length);
+ uint8_t const idx = get_idx_by_ptr(p_cdc);
+ ctrl_buf = cdch_epbuf[idx].ctrl;
+ tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length);
}
tuh_xfer_t xfer = {
.daddr = p_cdc->daddr,
.ep_addr = 0,
.setup = &request,
- .buffer = enum_buf,
+ .buffer = ctrl_buf,
.complete_cb = complete_cb,
.user_data = user_data
};
@@ -1563,7 +1566,7 @@ static void cp210x_internal_control_complete(cdch_interface_t *p_cdc, tuh_xfer_t
static bool cp210x_set_baudrate(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
// Not every baud rate is supported. See datasheets and AN205 "CP210x Baud Rate Support"
uint32_t baud_le = tu_htole32(p_cdc->requested_line.coding.bit_rate);
- return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t *) &baud_le, 4, complete_cb, user_data);
+ return cp210x_set_request(p_cdc, CP210X_SET_BAUDRATE, 0, (uint8_t const *) &baud_le, 4, complete_cb, user_data);
}
static bool cp210x_set_data_format(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
@@ -1640,7 +1643,7 @@ static uint16_t ch34x_get_divisor_prescaler(cdch_interface_t *p_cdc);
//------------- Control Request -------------//
static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_t request,
- uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length,
+ uint16_t value, uint16_t index, uint8_t const *buffer, uint16_t length,
tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
tusb_control_request_t const request_setup = {
.bmRequestType_bit = {
@@ -1654,13 +1657,14 @@ static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_
.wLength = tu_htole16(length)
};
- // use usbh enum buf since application variable does not live long enough
- uint8_t *enum_buf = NULL;
+ // use local ctrl buf since application variable does not live long enough
+ uint8_t *ctrl_buf = NULL;
- if (buffer && length > 0) {
- enum_buf = usbh_get_enum_buf();
- if (direction == TUSB_DIR_OUT) {
- tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length);
+ if (length > 0) {
+ uint8_t const idx = get_idx_by_ptr(p_cdc);
+ ctrl_buf = cdch_epbuf[idx].ctrl;
+ if (buffer && direction == TUSB_DIR_OUT) {
+ tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length);
}
}
@@ -1668,7 +1672,7 @@ static bool ch34x_set_request(cdch_interface_t *p_cdc, uint8_t direction, uint8_
.daddr = p_cdc->daddr,
.ep_addr = 0,
.setup = &request_setup,
- .buffer = enum_buf,
+ .buffer = ctrl_buf,
.complete_cb = complete_cb,
.user_data = user_data
};
@@ -1682,8 +1686,8 @@ TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_out(cdch_interface_t *p_c
}
TU_ATTR_ALWAYS_INLINE static inline bool ch34x_control_in(cdch_interface_t *p_cdc, uint8_t request, uint16_t value, uint16_t index,
- uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
- return ch34x_set_request(p_cdc, TUSB_DIR_IN, request, value, index, buffer, buffersize,
+ uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
+ return ch34x_set_request(p_cdc, TUSB_DIR_IN, request, value, index, NULL, buffersize,
complete_cb, user_data);
}
@@ -1692,12 +1696,6 @@ TU_ATTR_ALWAYS_INLINE static inline bool ch34x_write_reg(cdch_interface_t *p_cdc
return ch34x_control_out(p_cdc, CH34X_REQ_WRITE_REG, reg, reg_value, complete_cb, user_data);
}
-//static bool ch34x_read_reg_request ( cdch_interface_t * p_cdc, uint16_t reg,
-// uint8_t *buffer, uint16_t buffersize, tuh_xfer_cb_t complete_cb, uintptr_t user_data )
-//{
-// return ch34x_control_in ( p_cdc, CH34X_REQ_READ_REG, reg, 0, buffer, buffersize, complete_cb, user_data );
-//}
-
//------------- Driver API -------------//
// internal control complete to update state such as line state, encoding
@@ -1794,8 +1792,7 @@ static bool ch34x_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
switch (state) {
case CONFIG_CH34X_READ_VERSION: {
- uint8_t* enum_buf = usbh_get_enum_buf();
- TU_ASSERT(ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, enum_buf, 2,
+ TU_ASSERT(ch34x_control_in(p_cdc, CH34X_REQ_READ_VERSION, 0, 0, 2,
cdch_process_set_config, CONFIG_CH34X_SERIAL_INIT));
break;
}
@@ -1950,7 +1947,7 @@ static bool pl2303_encode_baud_rate(cdch_interface_t *p_cdc, uint8_t buf[PL2303_
//------------- Control Request -------------//
static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t requesttype,
- uint16_t value, uint16_t index, uint8_t *buffer, uint16_t length,
+ uint16_t value, uint16_t index, uint8_t const *buffer, uint16_t length,
tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
tusb_control_request_t const request_setup = {
.bmRequestType = requesttype,
@@ -1960,13 +1957,14 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t
.wLength = tu_htole16(length)
};
- // use usbh enum buf since application variable does not live long enough
- uint8_t *enum_buf = NULL;
+ // use local ctrl buf since application variable does not live long enough
+ uint8_t *ctrl_buf = NULL;
- if (buffer && length > 0) {
- enum_buf = usbh_get_enum_buf();
- if (request_setup.bmRequestType_bit.direction == TUSB_DIR_OUT) {
- tu_memcpy_s(enum_buf, CFG_TUH_ENUMERATION_BUFSIZE, buffer, length);
+ if (length > 0) {
+ uint8_t const idx = get_idx_by_ptr(p_cdc);
+ ctrl_buf = cdch_epbuf[idx].ctrl;
+ if (buffer && request_setup.bmRequestType_bit.direction == TUSB_DIR_OUT) {
+ tu_memcpy_s(ctrl_buf, sizeof(cdch_epbuf[idx].ctrl), buffer, length);
}
}
@@ -1974,7 +1972,7 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t
.daddr = p_cdc->daddr,
.ep_addr = 0,
.setup = &request_setup,
- .buffer = enum_buf,
+ .buffer = ctrl_buf,
.complete_cb = complete_cb,
.user_data = user_data
};
@@ -1982,10 +1980,10 @@ static bool pl2303_set_request(cdch_interface_t *p_cdc, uint8_t request, uint8_t
return tuh_control_xfer(&xfer);
}
-static bool pl2303_vendor_read(cdch_interface_t *p_cdc, uint16_t value, uint8_t *buf,
+static bool pl2303_vendor_read(cdch_interface_t *p_cdc, uint16_t value,
tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
uint8_t request = p_cdc->pl2303.type == PL2303_TYPE_HXN ? PL2303_VENDOR_READ_NREQUEST : PL2303_VENDOR_READ_REQUEST;
- return pl2303_set_request(p_cdc, request, PL2303_VENDOR_READ_REQUEST_TYPE, value, 0, buf, 1, complete_cb, user_data);
+ return pl2303_set_request(p_cdc, request, PL2303_VENDOR_READ_REQUEST_TYPE, value, 0, NULL, 1, complete_cb, user_data);
}
static bool pl2303_vendor_write(cdch_interface_t *p_cdc, uint16_t value, uint16_t index,
@@ -1995,9 +1993,8 @@ static bool pl2303_vendor_write(cdch_interface_t *p_cdc, uint16_t value, uint16_
}
static inline bool pl2303_supports_hx_status(cdch_interface_t *p_cdc, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
- uint8_t buf = 0;
return pl2303_set_request(p_cdc, PL2303_VENDOR_READ_REQUEST, PL2303_VENDOR_READ_REQUEST_TYPE, PL2303_READ_TYPE_HX_STATUS, 0,
- &buf, 1, complete_cb, user_data);
+ NULL, 1, complete_cb, user_data);
}
//static bool pl2303_get_line_request(cdch_interface_t * p_cdc, uint8_t buf[PL2303_LINE_CODING_BUFSIZE]) {
@@ -2131,7 +2128,6 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
// state CONFIG_PL2303_READ1 may have no success due to expected stall by pl2303_supports_hx_status()
const uintptr_t state = xfer->user_data;
TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS || state == CONFIG_PL2303_READ1);
- uint8_t* enum_buf = usbh_get_enum_buf();
pl2303_type_t type;
switch (state) {
@@ -2162,7 +2158,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE1));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_WRITE1));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
@@ -2178,7 +2174,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
case CONFIG_PL2303_READ2:
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ3));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_READ3));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
@@ -2186,7 +2182,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
case CONFIG_PL2303_READ3:
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ4));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, cdch_process_set_config, CONFIG_PL2303_READ4));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
@@ -2194,7 +2190,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
case CONFIG_PL2303_READ4:
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE2));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_WRITE2));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
@@ -2210,7 +2206,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
case CONFIG_PL2303_READ5:
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, enum_buf, cdch_process_set_config, CONFIG_PL2303_READ6));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8484, cdch_process_set_config, CONFIG_PL2303_READ6));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
@@ -2218,7 +2214,7 @@ static bool pl2303_process_set_config(cdch_interface_t *p_cdc, tuh_xfer_t *xfer)
case CONFIG_PL2303_READ6:
// purpose unknown, overtaken from Linux Kernel driver
if (p_cdc->pl2303.type != PL2303_TYPE_HXN) {
- TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, enum_buf, cdch_process_set_config, CONFIG_PL2303_WRITE3));
+ TU_ASSERT(pl2303_vendor_read(p_cdc, 0x8383, cdch_process_set_config, CONFIG_PL2303_WRITE3));
break;
}// else: continue with next step
TU_ATTR_FALLTHROUGH;
diff --git a/src/class/hid/hid_host.c b/src/class/hid/hid_host.c
index 7935b84d3..fc7704258 100644
--- a/src/class/hid/hid_host.c
+++ b/src/class/hid/hid_host.c
@@ -74,44 +74,31 @@ static uint8_t _hidh_default_protocol = HID_PROTOCOL_BOOT;
// Weak stubs: invoked if no strong implementation is available
//--------------------------------------------------------------------+
TU_ATTR_WEAK void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t idx, uint8_t const* report_desc, uint16_t desc_len) {
- (void) dev_addr;
- (void) idx;
- (void) report_desc;
- (void) desc_len;
+ (void) dev_addr; (void) idx; (void) report_desc; (void) desc_len;
}
TU_ATTR_WEAK void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t idx) {
- (void) dev_addr;
- (void) idx;
+ (void) dev_addr; (void) idx;
+}
+
+TU_ATTR_WEAK void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t idx, const uint8_t *report, uint16_t len) {
+ (void) dev_addr; (void) idx; (void) report; (void) len;
}
TU_ATTR_WEAK void tuh_hid_report_sent_cb(uint8_t dev_addr, uint8_t idx, uint8_t const* report, uint16_t len) {
- (void) dev_addr;
- (void) idx;
- (void) report;
- (void) len;
+ (void) dev_addr; (void) idx; (void) report; (void) len;
}
TU_ATTR_WEAK void tuh_hid_get_report_complete_cb(uint8_t dev_addr, uint8_t idx, uint8_t report_id, uint8_t report_type, uint16_t len) {
- (void) dev_addr;
- (void) idx;
- (void) report_id;
- (void) report_type;
- (void) len;
+ (void) dev_addr; (void) idx; (void) report_id; (void) report_type; (void) len;
}
TU_ATTR_WEAK void tuh_hid_set_report_complete_cb(uint8_t dev_addr, uint8_t idx, uint8_t report_id, uint8_t report_type, uint16_t len) {
- (void) dev_addr;
- (void) idx;
- (void) report_id;
- (void) report_type;
- (void) len;
+ (void) dev_addr; (void) idx; (void) report_id; (void) report_type; (void) len;
}
TU_ATTR_WEAK void tuh_hid_set_protocol_complete_cb(uint8_t dev_addr, uint8_t idx, uint8_t protocol) {
- (void) dev_addr;
- (void) idx;
- (void) protocol;
+ (void) dev_addr; (void) idx; (void) protocol;
}
//--------------------------------------------------------------------+
diff --git a/src/class/hid/hid_host.h b/src/class/hid/hid_host.h
index 922848fc2..95ba859ad 100644
--- a/src/class/hid/hid_host.h
+++ b/src/class/hid/hid_host.h
@@ -140,7 +140,7 @@ bool tuh_hid_send_ready(uint8_t dev_addr, uint8_t idx);
bool tuh_hid_send_report(uint8_t dev_addr, uint8_t idx, uint8_t report_id, const void *report, uint16_t len);
//--------------------------------------------------------------------+
-// Callbacks (Weak is optional)
+// Callbacks (optional)
//--------------------------------------------------------------------+
// Invoked when device with hid interface is mounted
diff --git a/src/class/midi/midi.h b/src/class/midi/midi.h
index cd67640e4..8121ec016 100644
--- a/src/class/midi/midi.h
+++ b/src/class/midi/midi.h
@@ -186,6 +186,24 @@ typedef midi_desc_cs_endpoint_n_t(1) midi_desc_cs_endpoint_1jack_t;
TU_VERIFY_STATIC(sizeof(midi_desc_cs_endpoint_1jack_t) == 4+1, "size is not correct");
//--------------------------------------------------------------------+
+// MIDI 2.0 UMP Helpers
+//--------------------------------------------------------------------+
+
+// Return the number of 32-bit words for a UMP message given its Message Type
+static inline uint8_t midi2_ump_word_count(uint8_t mt) {
+ switch (mt) {
+ case 0x0: case 0x1: case 0x2: case 0x6: case 0x7:
+ return 1;
+ case 0x3: case 0x4: case 0x8: case 0x9: case 0xA:
+ return 2;
+ case 0xB: case 0xC:
+ return 3;
+ default: // 0x5, 0xD, 0xE, 0xF
+ return 4;
+ }
+}
+
+//--------------------------------------------------------------------+
// For Internal Driver Use
//--------------------------------------------------------------------+
typedef struct {
diff --git a/src/class/midi/midi2_device.c b/src/class/midi/midi2_device.c
new file mode 100644
index 000000000..b14f439f8
--- /dev/null
+++ b/src/class/midi/midi2_device.c
@@ -0,0 +1,769 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "tusb_option.h"
+
+#if CFG_TUD_ENABLED && CFG_TUD_MIDI2
+
+#include <string.h>
+
+#include "device/usbd.h"
+#include "device/usbd_pvt.h"
+#include "midi2_device.h"
+
+//--------------------------------------------------------------------+
+// Weak stubs
+//--------------------------------------------------------------------+
+TU_ATTR_WEAK void tud_midi2_rx_cb(uint8_t itf) { (void) itf; }
+TU_ATTR_WEAK void tud_midi2_set_itf_cb(uint8_t itf, uint8_t alt) { (void) itf; (void) alt; }
+TU_ATTR_WEAK bool tud_midi2_get_req_itf_cb(uint8_t rhport, const tusb_control_request_t* request) {
+ (void) rhport; (void) request; return false;
+}
+TU_ATTR_WEAK uint8_t tud_midi2_num_groups_cb(uint8_t itf) {
+ (void) itf; return CFG_TUD_MIDI2_NUM_GROUPS;
+}
+TU_ATTR_WEAK uint8_t tud_midi2_num_function_blocks_cb(uint8_t itf) {
+ (void) itf; return CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS;
+}
+TU_ATTR_WEAK const char* tud_midi2_ep_name_cb(uint8_t itf) {
+ (void) itf; return CFG_TUD_MIDI2_EP_NAME;
+}
+TU_ATTR_WEAK const char* tud_midi2_product_id_cb(uint8_t itf) {
+ (void) itf; return CFG_TUD_MIDI2_PRODUCT_ID;
+}
+
+//--------------------------------------------------------------------+
+// Byte order note
+//--------------------------------------------------------------------+
+// Per USB-MIDI 2.0 Section 3.2.2, each 32-bit UMP word is transmitted with the
+// least significant byte first. This driver reads and writes UMP words as
+// native uint32_t through tu_edpt_stream_read/write. All TinyUSB targets are
+// little-endian, so the in-memory layout already matches the wire order and no
+// swap is needed. If a big-endian target is ever supported, wrap access with
+// tu_htole32 / tu_le32toh at the buffer boundary.
+
+//--------------------------------------------------------------------+
+// UMP Stream Message Constants
+//--------------------------------------------------------------------+
+// UMP Message Type for Stream messages (bits 31:28)
+enum {
+ MT_STREAM = 0x0F,
+};
+
+// UMP Stream Status values (10-bit, bits 25:16)
+enum {
+ STREAM_ENDPOINT_DISCOVERY = 0x000,
+ STREAM_ENDPOINT_INFO = 0x001,
+ STREAM_EP_NAME = 0x003,
+ STREAM_PROD_INSTANCE_ID = 0x004,
+ STREAM_CONFIG_REQUEST = 0x005,
+ STREAM_CONFIG_NOTIFY = 0x006,
+ STREAM_FB_DISCOVERY = 0x010,
+ STREAM_FB_INFO = 0x011,
+};
+
+enum {
+ UMP_VER_MAJOR = 1,
+ UMP_VER_MINOR = 1,
+};
+
+// Group Terminal Block descriptor types (USB-MIDI 2.0)
+enum {
+ MIDI2_CS_GRP_TRM_BLOCK = 0x26,
+ MIDI2_GRP_TRM_BLOCK_HEADER = 0x01,
+ MIDI2_GRP_TRM_BLOCK_ENTRY = 0x02,
+};
+
+//--------------------------------------------------------------------+
+// MACRO CONSTANT TYPEDEF
+//--------------------------------------------------------------------+
+typedef struct {
+ uint8_t ep_addr;
+ uint16_t mps;
+ tu_fifo_t ff;
+
+#if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0
+ uint8_t* ep_buf;
+#endif
+} midi2d_tx_t;
+
+typedef struct {
+ uint8_t rhport;
+ uint8_t itf_num;
+ uint8_t alt_setting;
+ uint8_t protocol;
+ bool negotiated;
+
+ /*------------- From this point, data is not cleared by bus reset -------------*/
+ struct {
+ midi2d_tx_t tx;
+ tu_edpt_stream_t rx;
+
+ uint8_t rx_ff_buf[CFG_TUD_MIDI2_RX_BUFSIZE];
+ uint8_t tx_ff_buf[CFG_TUD_MIDI2_TX_BUFSIZE];
+ } ep_stream;
+} midi2d_interface_t;
+
+// Skip local EP buffer if dedicated hw FIFO is supported
+#if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0
+typedef struct {
+ TUD_EPBUF_DEF(epin, CFG_TUD_MIDI2_TX_EPSIZE);
+ TUD_EPBUF_DEF(epout, CFG_TUD_MIDI2_RX_EPSIZE);
+} midi2d_epbuf_t;
+
+CFG_TUD_MEM_SECTION static midi2d_epbuf_t _midi2d_epbuf[CFG_TUD_MIDI2];
+#endif
+
+TU_VERIFY_STATIC(CFG_TUD_MIDI2_NUM_GROUPS >= 1 && CFG_TUD_MIDI2_NUM_GROUPS <= 16,
+ "CFG_TUD_MIDI2_NUM_GROUPS must be 1..16");
+TU_VERIFY_STATIC(CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS >= 1 && CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS <= 32,
+ "CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS must be 1..32");
+
+#define ITF_MEM_RESET_SIZE offsetof(midi2d_interface_t, ep_stream)
+
+static midi2d_interface_t _midi2d_itf[CFG_TUD_MIDI2];
+
+// Default Group Terminal Block descriptor (USB-MIDI 2.0 spec, Table 5-5/5-6)
+static const uint8_t _default_gtb_desc[] = {
+ // GTB Header (5 bytes)
+ 5, // bLength
+ MIDI2_CS_GRP_TRM_BLOCK, // bDescriptorType
+ MIDI2_GRP_TRM_BLOCK_HEADER, // bDescriptorSubtype
+ U16_TO_U8S_LE(18), // wTotalLength (5 + 13 = 18)
+
+ // GTB Entry (13 bytes)
+ 13, // bLength
+ MIDI2_CS_GRP_TRM_BLOCK, // bDescriptorType
+ MIDI2_GRP_TRM_BLOCK_ENTRY, // bDescriptorSubtype
+ 1, // bGrpTrmBlkID
+ 0x00, // bGrpTrmBlkType: bidirectional
+ 0x00, // nGroupTrm: first group (0)
+ CFG_TUD_MIDI2_NUM_GROUPS, // nNumGroupTrm
+ CFG_TUD_MIDI2_BLOCK_STRIDX, // iBlockItem: string descriptor index (0 = none)
+ 0x00, // bMIDIProtocol: unknown/not fixed
+ 0, 0, // wMaxInputBandwidth: unknown
+ 0, 0 // wMaxOutputBandwidth: unknown
+};
+
+//--------------------------------------------------------------------+
+// Common utility functions
+//--------------------------------------------------------------------+
+
+static inline uint8_t _itf_idx(const midi2d_interface_t* p_midi) {
+ return (uint8_t)(p_midi - _midi2d_itf);
+}
+
+static inline bool _tx_opened(const midi2d_interface_t* p_midi) {
+ return p_midi->ep_stream.tx.ep_addr != 0;
+}
+
+static uint8_t _tx_byte_at(const tu_fifo_buffer_info_t* info, uint16_t offset) {
+ if (offset < info->linear.len) {
+ return info->linear.ptr[offset];
+ }
+
+ offset = (uint16_t) (offset - info->linear.len);
+ if (offset < info->wrapped.len) {
+ return info->wrapped.ptr[offset];
+ }
+
+ return 0;
+}
+
+// Calculate the largest byte count that contains only whole UMP packets and
+// fits in one USB transfer (<= mps).
+static uint16_t _tx_nonseg_len_to_mps(midi2d_tx_t* tx) {
+ tu_fifo_buffer_info_t info;
+ tu_fifo_get_read_info(&tx->ff, &info);
+
+ const uint16_t available = (uint16_t) (info.linear.len + info.wrapped.len);
+ uint16_t bytes = 0;
+
+ while (bytes < tx->mps) {
+ if ((uint16_t) (available - bytes) < 4) break;
+
+ uint8_t mt = (uint8_t)((_tx_byte_at(&info, (uint16_t) (bytes + 3)) >> 4) & 0x0F);
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+ uint16_t pkt_bytes = (uint16_t) pkt_words * 4;
+
+ if (pkt_bytes == 0) break;
+ if ((uint16_t) (available - bytes) < pkt_bytes) break;
+ if ((uint16_t) (bytes + pkt_bytes) > tx->mps) break;
+
+ bytes = (uint16_t) (bytes + pkt_bytes);
+ }
+
+ return bytes;
+}
+
+// Start one IN transfer capped at mps, return number of bytes queued to the controller, or 0 if nothing was queued.
+static uint16_t _tx_start_xfer(midi2d_interface_t* p_midi) {
+ midi2d_tx_t* tx = &p_midi->ep_stream.tx;
+ uint16_t ff_count = tu_fifo_count(&tx->ff);
+
+ if (ff_count == 0) return 0;
+
+ if (!usbd_edpt_claim(p_midi->rhport, tx->ep_addr)) return 0;
+
+ uint16_t bytes;
+ if (p_midi->alt_setting == 1) {
+ bytes = _tx_nonseg_len_to_mps(tx);
+ } else {
+ bytes = tu_min16(tu_fifo_count(&tx->ff), tx->mps);
+ }
+ if (bytes == 0) {
+ usbd_edpt_release(p_midi->rhport, tx->ep_addr);
+ return 0;
+ }
+
+#if CFG_TUD_EDPT_DEDICATED_HWFIFO
+ TU_ASSERT(usbd_edpt_xfer_fifo(p_midi->rhport, tx->ep_addr, &tx->ff, bytes, false), 0);
+#else
+ tu_fifo_read_n(&tx->ff, tx->ep_buf, bytes);
+ TU_ASSERT(usbd_edpt_xfer(p_midi->rhport, tx->ep_addr, tx->ep_buf, bytes, false), 0);
+#endif
+
+ return bytes;
+}
+
+static uint32_t _tx_ump_write(midi2d_interface_t* p_midi, const uint32_t* words, uint32_t count) {
+ uint32_t written = 0;
+ while (written < count) {
+ uint8_t mt = (uint8_t)((words[written] >> 28) & 0x0F);
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+ uint16_t pkt_bytes = (uint16_t) pkt_words * 4;
+
+ if (written + pkt_words > count) break;
+ if (tu_fifo_remaining(&p_midi->ep_stream.tx.ff) < pkt_bytes) break;
+
+ if (tu_fifo_write_n(&p_midi->ep_stream.tx.ff, &words[written], pkt_bytes) != pkt_bytes) break;
+ written += pkt_words;
+ }
+
+ (void) _tx_start_xfer(p_midi);
+ return written;
+}
+
+//--------------------------------------------------------------------+
+// Protocol Negotiation
+//--------------------------------------------------------------------+
+static void _nego_send_ump(midi2d_interface_t* p_midi, const uint32_t* words, uint8_t count) {
+ if (!_tx_opened(p_midi)) return;
+ if (tu_fifo_remaining(&p_midi->ep_stream.tx.ff) < (uint32_t) count * 4) return;
+ (void) _tx_ump_write(p_midi, words, count);
+}
+
+static void _nego_send_endpoint_info(midi2d_interface_t* p_midi) {
+ uint32_t msg[4] = {0};
+ msg[0] = ((uint32_t) MT_STREAM << 28)
+ | ((uint32_t) STREAM_ENDPOINT_INFO << 16)
+ | ((uint32_t) UMP_VER_MAJOR << 8)
+ | (uint32_t) UMP_VER_MINOR;
+ msg[1] = (UINT32_C(1) << 31) // Static Function Blocks flag
+ | ((uint32_t)(tud_midi2_num_function_blocks_cb(_itf_idx(p_midi)) & 0x7F) << 24)
+ | (UINT32_C(1) << 9) // MIDI 2.0 Protocol capability
+ | (UINT32_C(1) << 8); // MIDI 1.0 Protocol capability
+ _nego_send_ump(p_midi, msg, 4);
+}
+
+static void _nego_send_stream_text(midi2d_interface_t* p_midi, uint16_t status, const char* str) {
+ if (!str || str[0] == '\0') return;
+
+ uint16_t total_len = (uint16_t) strlen(str);
+ uint16_t offset = 0;
+
+ while (offset < total_len) {
+ uint16_t remaining = total_len - offset;
+ uint8_t n = (uint8_t)((remaining > 14) ? 14 : remaining);
+ bool is_first = (offset == 0);
+ bool is_last = (remaining <= 14);
+
+ uint8_t form;
+ if (is_first && is_last) form = 0;
+ else if (is_first) form = 1;
+ else if (is_last) form = 3;
+ else form = 2;
+
+ uint32_t msg[4] = {0};
+ msg[0] = ((uint32_t) MT_STREAM << 28)
+ | ((uint32_t) form << 26)
+ | ((uint32_t) status << 16);
+
+ const char* p = str + offset;
+ if (n > 0) msg[0] |= ((uint32_t)(uint8_t) p[0] << 8);
+ if (n > 1) msg[0] |= (uint32_t)(uint8_t) p[1];
+ for (uint8_t i = 2; i < n; i++) {
+ uint8_t word_idx = (uint8_t)(1 + (i - 2) / 4);
+ uint8_t shift = (uint8_t)(24 - ((i - 2) % 4) * 8);
+ msg[word_idx] |= ((uint32_t)(uint8_t) p[i] << shift);
+ }
+
+ _nego_send_ump(p_midi, msg, 4);
+ offset += n;
+ }
+}
+
+static void _nego_send_config_notify(midi2d_interface_t* p_midi, uint8_t protocol) {
+ uint32_t msg[4] = {0};
+ msg[0] = ((uint32_t) MT_STREAM << 28)
+ | ((uint32_t) STREAM_CONFIG_NOTIFY << 16)
+ | ((uint32_t) protocol << 8);
+ _nego_send_ump(p_midi, msg, 4);
+}
+
+static void _nego_send_fb_info(midi2d_interface_t* p_midi, uint8_t fb_idx) {
+ uint32_t msg[4] = {0};
+ msg[0] = ((uint32_t) MT_STREAM << 28)
+ | ((uint32_t) STREAM_FB_INFO << 16)
+ | (UINT32_C(1) << 15)
+ | ((uint32_t) fb_idx << 8)
+ | 0x02; // bDirection: bidirectional
+ msg[1] = ((uint32_t) 0 << 24) // bFirstGroup
+ | ((uint32_t) tud_midi2_num_groups_cb(_itf_idx(p_midi)) << 16);
+ _nego_send_ump(p_midi, msg, 4);
+}
+
+static void _nego_handle_stream_msg(midi2d_interface_t* p_midi, const uint32_t* words) {
+ uint16_t status = (words[0] >> 16) & 0x3FF;
+
+ switch (status) {
+ case STREAM_ENDPOINT_DISCOVERY:
+ _nego_send_endpoint_info(p_midi);
+ _nego_send_stream_text(p_midi, STREAM_EP_NAME, tud_midi2_ep_name_cb(_itf_idx(p_midi)));
+ _nego_send_stream_text(p_midi, STREAM_PROD_INSTANCE_ID, tud_midi2_product_id_cb(_itf_idx(p_midi)));
+ break;
+
+ case STREAM_CONFIG_REQUEST: {
+ uint8_t req_proto = (words[0] >> 8) & 0xFF;
+ if (req_proto == MIDI_PROTOCOL_MIDI1 || req_proto == MIDI_PROTOCOL_MIDI2) {
+ p_midi->protocol = req_proto;
+ }
+ _nego_send_config_notify(p_midi, p_midi->protocol);
+ p_midi->negotiated = true;
+ break;
+ }
+
+ case STREAM_FB_DISCOVERY: {
+ uint8_t fb_idx = (words[0] >> 8) & 0xFF;
+ uint8_t fb_count = tud_midi2_num_function_blocks_cb(_itf_idx(p_midi));
+ if (fb_idx == 0xFF) {
+ for (uint8_t f = 0; f < fb_count; f++) {
+ _nego_send_fb_info(p_midi, f);
+ }
+ } else if (fb_idx < fb_count) {
+ _nego_send_fb_info(p_midi, fb_idx);
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+}
+
+static void _nego_process_rx(midi2d_interface_t* p_midi) {
+ tu_edpt_stream_t* ep_rx = &p_midi->ep_stream.rx;
+ uint8_t word_bytes[4];
+
+ while (tu_fifo_peek_n(&ep_rx->ff, word_bytes, 4) == 4) {
+ // UMP words travel LSB-first on the wire and in LE memory, so MT is in
+ // the high nibble of byte 3, not byte 0.
+ uint8_t mt = (word_bytes[3] >> 4) & 0x0F;
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+ uint32_t pkt_bytes = (uint32_t)pkt_words * 4;
+
+ if (mt != MT_STREAM) break;
+ if (tu_edpt_stream_read_available(ep_rx) < pkt_bytes) break;
+
+ uint32_t buf[4] = {0};
+ tu_edpt_stream_read(ep_rx, buf, pkt_bytes);
+ _nego_handle_stream_msg(p_midi, buf);
+ }
+}
+
+//--------------------------------------------------------------------+
+// READ API
+//--------------------------------------------------------------------+
+bool tud_midi2_n_mounted(uint8_t itf) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2, false);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+ return _tx_opened(p_midi) &&
+ tu_edpt_stream_is_opened(&p_midi->ep_stream.rx);
+}
+
+uint32_t tud_midi2_n_available(uint8_t itf) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+ return tu_edpt_stream_read_available(&p_midi->ep_stream.rx) / 4;
+}
+
+uint32_t tud_midi2_n_ump_read(uint8_t itf, uint32_t* words, uint32_t max_words) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2 && words != NULL && max_words > 0, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+
+ // UMP API is only valid on Alt Setting 1 (USB-MIDI 2.0).
+ // Alt 0 carries USB-MIDI 1.0 32-bit Event Packets, not UMP words.
+ if (p_midi->alt_setting != 1) { return 0; }
+
+ tu_edpt_stream_t* ep_rx = &p_midi->ep_stream.rx;
+
+ uint32_t total_read = 0;
+ while (total_read < max_words) {
+ uint8_t word_bytes[4];
+ if (tu_fifo_peek_n(&ep_rx->ff, word_bytes, 4) < 4) break;
+
+ // UMP words travel LSB-first; MT is the high nibble of byte 3, not byte 0.
+ uint8_t mt = (word_bytes[3] >> 4) & 0x0F;
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+
+ if (total_read + pkt_words > max_words) break;
+ if (tu_edpt_stream_read_available(ep_rx) < (uint32_t)pkt_words * 4) break;
+
+ tu_edpt_stream_read(ep_rx, &words[total_read], pkt_words * 4);
+ total_read += pkt_words;
+ }
+
+ return total_read;
+}
+
+uint32_t tud_midi2_n_packet_read(uint8_t itf, uint8_t packets[], uint32_t max_packets) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2 && packets != NULL && max_packets > 0, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+ return tu_edpt_stream_read(&p_midi->ep_stream.rx, packets, max_packets * 4u) >> 2u;
+}
+
+//--------------------------------------------------------------------+
+// WRITE API
+//--------------------------------------------------------------------+
+uint32_t tud_midi2_n_ump_write(uint8_t itf, const uint32_t* words, uint32_t count) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2 && words != NULL && count > 0, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+
+ // UMP API is only valid on Alt Setting 1 (USB-MIDI 2.0).
+ // Alt 0 carries USB-MIDI 1.0 32-bit Event Packets, not UMP words.
+ if (p_midi->alt_setting != 1) { return 0; }
+ TU_VERIFY(_tx_opened(p_midi), 0);
+
+ return _tx_ump_write(p_midi, words, count);
+}
+
+uint32_t tud_midi2_n_packet_write(uint8_t itf, const uint8_t packets[], uint32_t count) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2 && packets != NULL && count > 0, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[itf];
+ midi2d_tx_t* tx = &p_midi->ep_stream.tx;
+
+ // Packet API is for Alt Setting 0 (USB-MIDI 1.0) event packets.
+ TU_VERIFY(p_midi->alt_setting == 0, 0);
+ TU_VERIFY(_tx_opened(p_midi), 0);
+
+ uint32_t written = 0;
+ while (written < count) {
+ if (tu_fifo_remaining(&tx->ff) < 4) break;
+
+ if (tu_fifo_write_n(&tx->ff, packets + written * 4u, 4) != 4) break;
+ written++;
+ }
+
+ (void) _tx_start_xfer(p_midi);
+
+ return written;
+}
+
+//--------------------------------------------------------------------+
+// STATE GETTERS
+//--------------------------------------------------------------------+
+uint8_t tud_midi2_n_alt_setting(uint8_t itf) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2, 0);
+ return _midi2d_itf[itf].alt_setting;
+}
+
+bool tud_midi2_n_negotiated(uint8_t itf) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2, false);
+ return _midi2d_itf[itf].negotiated;
+}
+
+uint8_t tud_midi2_n_protocol(uint8_t itf) {
+ TU_VERIFY(itf < CFG_TUD_MIDI2, 0);
+ return _midi2d_itf[itf].protocol;
+}
+
+//--------------------------------------------------------------------+
+// USBD Driver API
+//--------------------------------------------------------------------+
+void midi2d_init(void) {
+ tu_memclr(_midi2d_itf, sizeof(_midi2d_itf));
+ for (uint8_t i = 0; i < CFG_TUD_MIDI2; i++) {
+ midi2d_interface_t* p_midi = &_midi2d_itf[i];
+ p_midi->protocol = MIDI_PROTOCOL_MIDI2;
+
+ #if CFG_TUD_EDPT_DEDICATED_HWFIFO
+ uint8_t *epout_buf = NULL;
+ uint8_t *epin_buf = NULL;
+ #else
+ uint8_t *epout_buf = _midi2d_epbuf[i].epout;
+ uint8_t *epin_buf = _midi2d_epbuf[i].epin;
+ #endif
+
+ tu_edpt_stream_init(&p_midi->ep_stream.rx, false, false, false,
+ p_midi->ep_stream.rx_ff_buf, CFG_TUD_MIDI2_RX_BUFSIZE, epout_buf);
+
+ midi2d_tx_t* tx = &p_midi->ep_stream.tx;
+ (void) tu_fifo_config(&tx->ff, p_midi->ep_stream.tx_ff_buf, CFG_TUD_MIDI2_TX_BUFSIZE, false);
+#if CFG_TUD_EDPT_DEDICATED_HWFIFO == 0
+ tx->ep_buf = epin_buf;
+#else
+ (void) epin_buf;
+#endif
+ }
+}
+
+bool midi2d_deinit(void) {
+ for (uint8_t i = 0; i < CFG_TUD_MIDI2; i++) {
+ midi2d_interface_t* p_midi = &_midi2d_itf[i];
+ tu_edpt_stream_deinit(&p_midi->ep_stream.rx);
+ }
+ return true;
+}
+
+void midi2d_reset(uint8_t rhport) {
+ (void) rhport;
+ for (uint8_t i = 0; i < CFG_TUD_MIDI2; i++) {
+ midi2d_interface_t* p_midi = &_midi2d_itf[i];
+ tu_memclr(p_midi, ITF_MEM_RESET_SIZE);
+
+ tu_edpt_stream_clear(&p_midi->ep_stream.rx);
+ tu_edpt_stream_close(&p_midi->ep_stream.rx);
+
+ tu_fifo_clear(&p_midi->ep_stream.tx.ff);
+ p_midi->ep_stream.tx.ep_addr = 0;
+ }
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint8_t find_midi2_itf(uint8_t ep_addr) {
+ for (uint8_t idx = 0; idx < CFG_TUD_MIDI2; idx++) {
+ const midi2d_interface_t* p_midi = &_midi2d_itf[idx];
+ if (ep_addr == p_midi->ep_stream.rx.ep_addr || ep_addr == p_midi->ep_stream.tx.ep_addr) {
+ return idx;
+ }
+ }
+ return TUSB_INDEX_INVALID_8;
+}
+
+static uint8_t find_midi2_itf_by_num(uint8_t itf_num) {
+ for (uint8_t idx = 0; idx < CFG_TUD_MIDI2; idx++) {
+ if (_midi2d_itf[idx].itf_num == itf_num) return idx;
+ }
+ return TUSB_INDEX_INVALID_8;
+}
+
+uint16_t midi2d_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len) {
+ const uint8_t* p_desc = (const uint8_t*) desc_itf;
+ const uint8_t* desc_end = p_desc + max_len;
+
+ // 1st Interface: Audio Control v1 (optional)
+ if (TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass &&
+ AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass &&
+ AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol) {
+ p_desc = tu_desc_next(desc_itf);
+ while (tu_desc_in_bounds(p_desc, desc_end) && TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc)) {
+ p_desc = tu_desc_next(p_desc);
+ }
+ }
+
+ // 2nd Interface: MIDI Streaming
+ TU_VERIFY(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0);
+ const tusb_desc_interface_t* desc_midi = (const tusb_desc_interface_t*) p_desc;
+
+ TU_VERIFY(TUSB_CLASS_AUDIO == desc_midi->bInterfaceClass &&
+ AUDIO_SUBCLASS_MIDI_STREAMING == desc_midi->bInterfaceSubClass &&
+ AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_midi->bInterfaceProtocol,
+ 0);
+
+ uint8_t idx = find_midi2_itf(0);
+ TU_ASSERT(idx < CFG_TUD_MIDI2, 0);
+ midi2d_interface_t* p_midi = &_midi2d_itf[idx];
+
+ p_midi->rhport = rhport;
+ p_midi->itf_num = desc_midi->bInterfaceNumber;
+ p_midi->alt_setting = 0;
+ p_midi->protocol = MIDI_PROTOCOL_MIDI2;
+ p_midi->negotiated = false;
+
+ p_desc = tu_desc_next(p_desc);
+
+ // Skip class-specific descriptors
+ while (tu_desc_in_bounds(p_desc, desc_end) && TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc)) {
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ // Find and open endpoint descriptors
+ uint8_t found_ep = 0;
+ while ((found_ep < desc_midi->bNumEndpoints) && tu_desc_in_bounds(p_desc, desc_end)) {
+ if (TUSB_DESC_ENDPOINT == tu_desc_type(p_desc)) {
+ const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc;
+ TU_ASSERT(usbd_edpt_open(rhport, desc_ep), 0);
+ const uint8_t ep_addr = desc_ep->bEndpointAddress;
+
+ if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
+ p_midi->ep_stream.tx.ep_addr = ep_addr;
+ p_midi->ep_stream.tx.mps = tu_edpt_packet_size(desc_ep);
+ tu_fifo_clear(&p_midi->ep_stream.tx.ff);
+ } else {
+ tu_edpt_stream_open(&p_midi->ep_stream.rx, rhport, desc_ep, tu_edpt_packet_size(desc_ep));
+ tu_edpt_stream_clear(&p_midi->ep_stream.rx);
+ TU_ASSERT(tu_edpt_stream_read_xfer(&p_midi->ep_stream.rx) > 0, 0);
+ }
+
+ found_ep++;
+ }
+
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ // Skip remaining descriptors (alt setting 1, CS endpoints, GTB)
+ // Stop at any interface descriptor that is not our MIDI Streaming alt setting
+ while (tu_desc_in_bounds(p_desc, desc_end)) {
+ uint8_t dtype = tu_desc_type(p_desc);
+
+ if (dtype == TUSB_DESC_INTERFACE) {
+ const tusb_desc_interface_t* next_itf = (const tusb_desc_interface_t*) p_desc;
+ // Continue only if this is an alternate setting of our own interface
+ if (next_itf->bInterfaceNumber != desc_midi->bInterfaceNumber) break;
+ } else if (dtype != TUSB_DESC_CS_INTERFACE && dtype != TUSB_DESC_CS_ENDPOINT &&
+ dtype != TUSB_DESC_ENDPOINT) {
+ break;
+ }
+
+ p_desc = tu_desc_next(p_desc);
+ }
+
+ return (uint16_t)(p_desc - (const uint8_t*) desc_itf);
+}
+
+bool midi2d_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
+ TU_LOG2("MIDI2 ctrl: stage=%u bRequest=0x%02X wValue=0x%04X wIndex=0x%04X wLength=%u\r\n",
+ stage, request->bRequest, request->wValue, request->wIndex, request->wLength);
+
+ if (stage != CONTROL_STAGE_SETUP) return true;
+
+ switch (request->bRequest) {
+ case TUSB_REQ_SET_INTERFACE: {
+ uint8_t itf_num = tu_u16_low(request->wIndex);
+ uint8_t alt = tu_u16_low(request->wValue);
+
+ // Only Alt Setting 0 (MIDI 1.0) and 1 (UMP) are valid
+ if (alt > 1) return false;
+
+ uint8_t idx = find_midi2_itf_by_num(itf_num);
+ if (idx >= CFG_TUD_MIDI2) return false;
+
+ midi2d_interface_t* p_midi = &_midi2d_itf[idx];
+ p_midi->alt_setting = alt;
+
+ tu_edpt_stream_clear(&p_midi->ep_stream.rx);
+ tu_fifo_clear(&p_midi->ep_stream.tx.ff);
+
+ if (alt == 1) {
+ p_midi->negotiated = false;
+ p_midi->protocol = MIDI_PROTOCOL_MIDI2;
+ }
+
+ // Re-arm RX endpoint for receiving data after alt setting change
+ tu_edpt_stream_read_xfer(&p_midi->ep_stream.rx);
+
+ tud_midi2_set_itf_cb(idx, alt);
+ tud_control_status(rhport, request);
+ return true;
+ }
+
+ case TUSB_REQ_GET_DESCRIPTOR: {
+ // USB-MIDI 2.0 Section 6: GTB descriptor retrieval
+ // bmRequestType = 0x81 (Device-to-Host, Standard, Interface)
+ // wValue = CS_GR_TRM_BLOCK (0x26) in high byte, alt setting in low byte
+ // wIndex = interface number
+ if (request->bmRequestType_bit.direction != TUSB_DIR_IN) return false;
+ if (request->bmRequestType_bit.type != TUSB_REQ_TYPE_STANDARD) return false;
+ if (request->bmRequestType_bit.recipient != TUSB_REQ_RCPT_INTERFACE) return false;
+ if (tu_u16_high(request->wValue) != MIDI2_CS_GRP_TRM_BLOCK) return false;
+
+ uint8_t itf_num = tu_u16_low(request->wIndex);
+ uint8_t idx = find_midi2_itf_by_num(itf_num);
+ if (idx >= CFG_TUD_MIDI2) return false;
+
+ // Only Alt Setting 1 exposes Group Terminal Block descriptors.
+ if (tu_u16_low(request->wValue) != 0x01) return false;
+
+ if (tud_midi2_get_req_itf_cb(rhport, request)) return true;
+
+ uint16_t len = request->wLength;
+ if (len > sizeof(_default_gtb_desc)) {
+ len = sizeof(_default_gtb_desc);
+ }
+ tud_control_xfer(rhport, request, (void*)(uintptr_t) _default_gtb_desc, len);
+ return true;
+ }
+
+ default:
+ return false;
+ }
+}
+
+bool midi2d_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
+ (void) rhport;
+
+ uint8_t idx = find_midi2_itf(ep_addr);
+ TU_ASSERT(idx < CFG_TUD_MIDI2);
+ midi2d_interface_t* p_midi = &_midi2d_itf[idx];
+
+ tu_edpt_stream_t* ep_rx = &p_midi->ep_stream.rx;
+ midi2d_tx_t* ep_tx = &p_midi->ep_stream.tx;
+
+ if (ep_addr == ep_rx->ep_addr) {
+ if (result == XFER_RESULT_SUCCESS) {
+ tu_edpt_stream_read_xfer_complete(ep_rx, xferred_bytes);
+ if (p_midi->alt_setting == 1) {
+ _nego_process_rx(p_midi);
+ }
+ tud_midi2_rx_cb(idx);
+ }
+ tu_edpt_stream_read_xfer(ep_rx);
+ } else if (ep_addr == ep_tx->ep_addr && result == XFER_RESULT_SUCCESS) {
+ uint16_t queued = _tx_start_xfer(p_midi);
+ // Send ZLP if no more data is queued but the last transfer was exactly mps
+ if (queued == 0 && tu_fifo_count(&ep_tx->ff) == 0 && xferred_bytes > 0 &&
+ (0 == (xferred_bytes & (ep_tx->mps - 1)))) {
+ if (usbd_edpt_claim(rhport, ep_tx->ep_addr)) {
+ usbd_edpt_xfer(rhport, ep_tx->ep_addr, NULL, 0, false);
+ }
+ }
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
+#endif
diff --git a/src/class/midi/midi2_device.h b/src/class/midi/midi2_device.h
new file mode 100644
index 000000000..e53535693
--- /dev/null
+++ b/src/class/midi/midi2_device.h
@@ -0,0 +1,193 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef TUSB_MIDI2_DEVICE_H_
+#define TUSB_MIDI2_DEVICE_H_
+
+#include "class/audio/audio.h"
+#include "midi.h"
+
+//--------------------------------------------------------------------+
+// Class Driver Configuration
+//--------------------------------------------------------------------+
+
+// Config defaults are in tusb_option.h:
+// CFG_TUD_MIDI2_RX_EPSIZE, CFG_TUD_MIDI2_TX_EPSIZE,
+// CFG_TUD_MIDI2_RX_BUFSIZE, CFG_TUD_MIDI2_TX_BUFSIZE,
+// CFG_TUD_MIDI2_NUM_GROUPS, CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS,
+// CFG_TUD_MIDI2_EP_NAME, CFG_TUD_MIDI2_PRODUCT_ID
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Class Driver Configuration
+//--------------------------------------------------------------------+
+
+#ifndef CFG_TUD_MIDI2_TX_EPSIZE
+ #define CFG_TUD_MIDI2_TX_EPSIZE TUD_EPSIZE_BULK_MAX
+#endif
+
+#ifndef CFG_TUD_MIDI2_RX_EPSIZE
+ #define CFG_TUD_MIDI2_RX_EPSIZE TUD_EPSIZE_BULK_MAX
+#endif
+
+#ifndef CFG_TUD_MIDI2_TX_BUFSIZE
+ #define CFG_TUD_MIDI2_TX_BUFSIZE CFG_TUD_MIDI2_TX_EPSIZE
+#endif
+
+#ifndef CFG_TUD_MIDI2_RX_BUFSIZE
+ #define CFG_TUD_MIDI2_RX_BUFSIZE CFG_TUD_MIDI2_RX_EPSIZE
+#endif
+
+#ifndef CFG_TUD_MIDI2_NUM_GROUPS
+ #define CFG_TUD_MIDI2_NUM_GROUPS 1
+#endif
+
+#ifndef CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS
+ #define CFG_TUD_MIDI2_NUM_FUNCTION_BLOCKS 1
+#endif
+
+#ifndef CFG_TUD_MIDI2_EP_NAME
+ #define CFG_TUD_MIDI2_EP_NAME "TinyUSB MIDI 2.0"
+#endif
+
+#ifndef CFG_TUD_MIDI2_PRODUCT_ID
+ #define CFG_TUD_MIDI2_PRODUCT_ID "TinyUSB-MIDI2"
+#endif
+
+// String descriptor index for the Group Terminal Block (iBlockItem, Table 5-6).
+// 0 = no string descriptor (default, spec-allowed).
+#ifndef CFG_TUD_MIDI2_BLOCK_STRIDX
+ #define CFG_TUD_MIDI2_BLOCK_STRIDX 0
+#endif
+
+//--------------------------------------------------------------------+
+// MIDI Protocol Values (returned by tud_midi2_n_protocol)
+//--------------------------------------------------------------------+
+
+// Per USB-MIDI 2.0 spec, UMP Stream Configuration messages.
+enum {
+ MIDI_PROTOCOL_MIDI1 = 0x01,
+ MIDI_PROTOCOL_MIDI2 = 0x02,
+};
+
+//--------------------------------------------------------------------+
+// Application Callback API (weak, optional)
+//--------------------------------------------------------------------+
+void tud_midi2_rx_cb(uint8_t itf);
+void tud_midi2_set_itf_cb(uint8_t itf, uint8_t alt);
+bool tud_midi2_get_req_itf_cb(uint8_t rhport, const tusb_control_request_t* request);
+
+// Per-interface UMP Stream config (override for per-itf values).
+uint8_t tud_midi2_num_groups_cb(uint8_t itf);
+uint8_t tud_midi2_num_function_blocks_cb(uint8_t itf);
+const char* tud_midi2_ep_name_cb(uint8_t itf);
+const char* tud_midi2_product_id_cb(uint8_t itf);
+
+//--------------------------------------------------------------------+
+// Application API (Multiple Interfaces)
+//--------------------------------------------------------------------+
+
+bool tud_midi2_n_mounted(uint8_t itf);
+uint32_t tud_midi2_n_available(uint8_t itf);
+uint8_t tud_midi2_n_alt_setting(uint8_t itf);
+bool tud_midi2_n_negotiated(uint8_t itf);
+uint8_t tud_midi2_n_protocol(uint8_t itf);
+
+// Read up to max_words UMP words from the RX FIFO. Returns the number of
+// words actually read (0 if FIFO is empty).
+//
+// NOTE: this function returns when max_words is reached or when the FIFO is
+// empty, whichever comes first. Applications should invoke it in a loop
+// until it returns 0 to guarantee the RX FIFO is fully drained per
+// tud_midi2_rx_cb callback. Leaving words in the FIFO across callbacks can
+// prevent subsequent bulk OUT transfers from landing.
+uint32_t tud_midi2_n_ump_read(uint8_t itf, uint32_t* words, uint32_t max_words);
+uint32_t tud_midi2_n_ump_write(uint8_t itf, const uint32_t* words, uint32_t count);
+
+uint32_t tud_midi2_n_packet_read(uint8_t itf, uint8_t packets[], uint32_t max_packets);
+uint32_t tud_midi2_n_packet_write(uint8_t itf, const uint8_t packets[], uint32_t count);
+
+//--------------------------------------------------------------------+
+// Application API (Single Interface)
+//--------------------------------------------------------------------+
+TU_ATTR_ALWAYS_INLINE static inline bool tud_midi2_mounted(void) {
+ return tud_midi2_n_mounted(0);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_midi2_available(void) {
+ return tud_midi2_n_available(0);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint8_t tud_midi2_alt_setting(void) {
+ return tud_midi2_n_alt_setting(0);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline bool tud_midi2_negotiated(void) {
+ return tud_midi2_n_negotiated(0);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint8_t tud_midi2_protocol(void) {
+ return tud_midi2_n_protocol(0);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t
+tud_midi2_ump_read(uint32_t* words, uint32_t max_words) {
+ return tud_midi2_n_ump_read(0, words, max_words);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t
+tud_midi2_ump_write(const uint32_t* words, uint32_t count) {
+ return tud_midi2_n_ump_write(0, words, count);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t
+tud_midi2_packet_read(uint8_t packets[], uint32_t max_packets) {
+ return tud_midi2_n_packet_read(0, packets, max_packets);
+}
+
+TU_ATTR_ALWAYS_INLINE static inline uint32_t
+tud_midi2_packet_write(const uint8_t packets[], uint32_t count) {
+ return tud_midi2_n_packet_write(0, packets, count);
+}
+
+//--------------------------------------------------------------------+
+// Internal Class Driver API
+//--------------------------------------------------------------------+
+void midi2d_init(void);
+bool midi2d_deinit(void);
+void midi2d_reset(uint8_t rhport);
+uint16_t midi2d_open(uint8_t rhport, const tusb_desc_interface_t* itf_desc, uint16_t max_len);
+bool midi2d_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request);
+bool midi2d_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/class/midi/midi2_host.c b/src/class/midi/midi2_host.c
new file mode 100644
index 000000000..6d8861f4b
--- /dev/null
+++ b/src/class/midi/midi2_host.c
@@ -0,0 +1,635 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#include "tusb_option.h"
+
+#if (CFG_TUH_ENABLED && CFG_TUH_MIDI2)
+
+#include "host/usbh.h"
+#include "host/usbh_pvt.h"
+#include "midi2_host.h"
+
+#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_MIDI2_LOG_LEVEL, __VA_ARGS__)
+
+//--------------------------------------------------------------------+
+// Weak stubs for application callbacks
+//--------------------------------------------------------------------+
+
+TU_ATTR_WEAK void tuh_midi2_descriptor_cb(uint8_t idx, const tuh_midi2_descriptor_cb_t *desc_cb_data) {
+ (void) idx; (void) desc_cb_data;
+}
+
+TU_ATTR_WEAK void tuh_midi2_mount_cb(uint8_t idx, const tuh_midi2_mount_cb_t *mount_cb_data) {
+ (void) idx; (void) mount_cb_data;
+}
+
+TU_ATTR_WEAK void tuh_midi2_rx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ (void) idx; (void) xferred_bytes;
+}
+
+TU_ATTR_WEAK void tuh_midi2_tx_cb(uint8_t idx, uint32_t xferred_bytes) {
+ (void) idx; (void) xferred_bytes;
+}
+
+TU_ATTR_WEAK void tuh_midi2_umount_cb(uint8_t idx) {
+ (void) idx;
+}
+
+//--------------------------------------------------------------------+
+// Internal structure and state
+//--------------------------------------------------------------------+
+
+typedef struct {
+ uint8_t ep_addr;
+ uint16_t mps;
+ tu_fifo_t ff;
+ uint8_t* ep_buf;
+} midih2_tx_t;
+
+typedef struct {
+ uint8_t daddr;
+ uint8_t bInterfaceNumber;
+
+ uint8_t alt_setting_current;
+
+ uint8_t protocol_version;
+ uint8_t bcdMSC_hi, bcdMSC_lo;
+ uint8_t rx_cable_count_alt0;
+ uint8_t tx_cable_count_alt0;
+ uint8_t rx_cable_count_alt1;
+ uint8_t tx_cable_count_alt1;
+
+ struct {
+ midih2_tx_t tx;
+ tu_edpt_stream_t rx;
+
+ uint8_t rx_ff_buf[CFG_TUH_MIDI2_RX_BUFSIZE];
+ uint8_t tx_ff_buf[CFG_TUH_MIDI2_TX_BUFSIZE];
+ } ep_stream;
+
+ bool mounted;
+} midih2_interface_t;
+
+static midih2_interface_t _midi2_host[CFG_TUH_MIDI2];
+
+typedef struct {
+ TUH_EPBUF_DEF(tx, TUH_EPSIZE_BULK_MAX);
+ TUH_EPBUF_DEF(rx, TUH_EPSIZE_BULK_MAX);
+} midih2_epbuf_t;
+
+CFG_TUH_MEM_SECTION static midih2_epbuf_t _midi2_epbuf[CFG_TUH_MIDI2];
+
+//--------------------------------------------------------------------+
+// Helper functions
+//--------------------------------------------------------------------+
+
+static inline uint8_t find_new_midi2_index(void) {
+ for (uint8_t idx = 0; idx < CFG_TUH_MIDI2; idx++) {
+ if (_midi2_host[idx].daddr == 0) {
+ return idx;
+ }
+ }
+ return TUSB_INDEX_INVALID_8;
+}
+
+static inline uint8_t get_idx_by_ep_addr(uint8_t daddr, uint8_t ep_addr) {
+ for (uint8_t idx = 0; idx < CFG_TUH_MIDI2; idx++) {
+ const midih2_interface_t *p_midi = &_midi2_host[idx];
+ if ((p_midi->daddr == daddr) &&
+ (ep_addr == p_midi->ep_stream.rx.ep_addr || ep_addr == p_midi->ep_stream.tx.ep_addr)) {
+ return idx;
+ }
+ }
+ return TUSB_INDEX_INVALID_8;
+}
+
+static inline bool _tuh_tx_opened(const midih2_interface_t* p_midi) {
+ return p_midi->ep_stream.tx.ep_addr != 0;
+}
+
+static uint8_t _tuh_tx_byte_at(const tu_fifo_buffer_info_t* info, uint16_t offset) {
+ if (offset < info->linear.len) {
+ return info->linear.ptr[offset];
+ }
+ offset = (uint16_t)(offset - info->linear.len);
+ if (offset < info->wrapped.len) {
+ return info->wrapped.ptr[offset];
+ }
+ return 0;
+}
+
+// Largest byte count containing only whole UMP packets and fitting one xfer.
+static uint16_t _tuh_tx_nonseg_len_to_mps(midih2_tx_t* tx) {
+ tu_fifo_buffer_info_t info;
+ tu_fifo_get_read_info(&tx->ff, &info);
+
+ const uint16_t available = (uint16_t)(info.linear.len + info.wrapped.len);
+ uint16_t bytes = 0;
+
+ while (bytes < tx->mps) {
+ if ((uint16_t)(available - bytes) < 4) break;
+
+ uint8_t mt = (uint8_t)((_tuh_tx_byte_at(&info, (uint16_t)(bytes + 3)) >> 4) & 0x0F);
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+ uint16_t pkt_bytes = (uint16_t)(pkt_words * 4);
+
+ if (pkt_bytes == 0) break;
+ if ((uint16_t)(available - bytes) < pkt_bytes) break;
+ if ((uint16_t)(bytes + pkt_bytes) > tx->mps) break;
+
+ bytes = (uint16_t)(bytes + pkt_bytes);
+ }
+
+ return bytes;
+}
+
+// Start one OUT transfer capped at mps. Returns bytes queued, or 0 if nothing.
+static uint16_t _tuh_tx_start_xfer(midih2_interface_t* p_midi) {
+ midih2_tx_t* tx = &p_midi->ep_stream.tx;
+ uint16_t ff_count = tu_fifo_count(&tx->ff);
+ if (ff_count == 0) return 0;
+ if (!usbh_edpt_claim(p_midi->daddr, tx->ep_addr)) return 0;
+
+ uint16_t bytes;
+ if (p_midi->alt_setting_current == 1) {
+ bytes = _tuh_tx_nonseg_len_to_mps(tx);
+ } else {
+ bytes = tu_min16(tu_fifo_count(&tx->ff), tx->mps);
+ }
+ if (bytes == 0) {
+ usbh_edpt_release(p_midi->daddr, tx->ep_addr);
+ return 0;
+ }
+
+ tu_fifo_read_n(&tx->ff, tx->ep_buf, bytes);
+ TU_ASSERT(usbh_edpt_xfer(p_midi->daddr, tx->ep_addr, tx->ep_buf, bytes), 0);
+ return bytes;
+}
+
+static uint32_t _tuh_tx_ump_write(midih2_interface_t* p_midi, const uint32_t* words, uint32_t count) {
+ uint32_t written = 0;
+ while (written < count) {
+ uint8_t mt = (uint8_t)((words[written] >> 28) & 0x0F);
+ uint8_t pkt_words = midi2_ump_word_count(mt);
+ uint16_t pkt_bytes = (uint16_t)(pkt_words * 4);
+
+ if (written + pkt_words > count) break;
+ if (tu_fifo_remaining(&p_midi->ep_stream.tx.ff) < pkt_bytes) break;
+ if (tu_fifo_write_n(&p_midi->ep_stream.tx.ff, &words[written], pkt_bytes) != pkt_bytes) break;
+ written += pkt_words;
+ }
+
+ (void) _tuh_tx_start_xfer(p_midi);
+ return written;
+}
+
+//--------------------------------------------------------------------+
+// Descriptor parsing
+//--------------------------------------------------------------------+
+
+// Parse Alt Setting 0 (MIDI 1.0) descriptors. Returns pointer past last consumed descriptor.
+static const uint8_t* midih2_parse_descriptors_alt0(midih2_interface_t *p_midi,
+ const tusb_desc_interface_t *desc_itf, const uint8_t *desc_end) {
+ TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == desc_itf->bInterfaceSubClass, NULL);
+
+ p_midi->bInterfaceNumber = desc_itf->bInterfaceNumber;
+
+ const uint8_t *p_desc = (const uint8_t *) desc_itf;
+ p_desc = tu_desc_next(p_desc);
+
+ uint8_t rx_cable_count = 0;
+ uint8_t tx_cable_count = 0;
+ bool found_new_interface = false;
+
+ while (tu_desc_in_bounds(p_desc, desc_end) && !found_new_interface) {
+ switch (tu_desc_type(p_desc)) {
+ case TUSB_DESC_INTERFACE:
+ found_new_interface = true;
+ break;
+
+ case TUSB_DESC_ENDPOINT: {
+ const tusb_desc_endpoint_t *p_ep = (const tusb_desc_endpoint_t *) p_desc;
+
+ TU_ASSERT(tuh_edpt_open(p_midi->daddr, p_ep), NULL);
+ if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_IN) {
+ tu_edpt_stream_open(&p_midi->ep_stream.rx, p_midi->daddr, p_ep, tu_edpt_packet_size(p_ep));
+ tu_edpt_stream_clear(&p_midi->ep_stream.rx);
+ } else {
+ p_midi->ep_stream.tx.ep_addr = p_ep->bEndpointAddress;
+ p_midi->ep_stream.tx.mps = tu_edpt_packet_size(p_ep);
+ tu_fifo_clear(&p_midi->ep_stream.tx.ff);
+ }
+
+ p_desc = tu_desc_next(p_desc);
+ if (tu_desc_in_bounds(p_desc, desc_end) && tu_desc_type(p_desc) == TUSB_DESC_CS_ENDPOINT) {
+ const midi_desc_cs_endpoint_t *p_csep = (const midi_desc_cs_endpoint_t *) p_desc;
+ if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) {
+ tx_cable_count = p_csep->bNumEmbMIDIJack;
+ } else {
+ rx_cable_count = p_csep->bNumEmbMIDIJack;
+ }
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+
+ if (!found_new_interface) {
+ p_desc = tu_desc_next(p_desc);
+ }
+ }
+
+ p_midi->rx_cable_count_alt0 = rx_cable_count;
+ p_midi->tx_cable_count_alt0 = tx_cable_count;
+ return p_desc;
+}
+
+// Parse Alt Setting 1 (MIDI 2.0 UMP) descriptors. Returns pointer past last consumed descriptor.
+static const uint8_t* midih2_parse_descriptors_alt1(midih2_interface_t *p_midi,
+ const tusb_desc_interface_t *desc_itf, const uint8_t *desc_end) {
+ TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == desc_itf->bInterfaceSubClass, NULL);
+ TU_VERIFY(desc_itf->bAlternateSetting == 1, NULL);
+
+ const uint8_t *p_desc = (const uint8_t *) desc_itf;
+ p_desc = tu_desc_next(p_desc);
+
+ uint8_t rx_cable_count = 0;
+ uint8_t tx_cable_count = 0;
+ bool found_new_interface = false;
+
+ while (tu_desc_in_bounds(p_desc, desc_end) && !found_new_interface) {
+ switch (tu_desc_type(p_desc)) {
+ case TUSB_DESC_INTERFACE:
+ found_new_interface = true;
+ break;
+
+ case TUSB_DESC_CS_INTERFACE:
+ if (tu_desc_subtype(p_desc) == MIDI_CS_INTERFACE_HEADER) {
+ // bcdMSC at offset 3-4 in CS Interface Header
+ const uint8_t *bcd_ptr = p_desc + 3;
+ p_midi->bcdMSC_lo = bcd_ptr[0];
+ p_midi->bcdMSC_hi = bcd_ptr[1];
+ if (p_midi->bcdMSC_hi == 0x02) { // bcdMSC 0x0200 = USB-MIDI 2.0
+ p_midi->protocol_version = 1;
+ }
+ }
+ break;
+
+ case TUSB_DESC_ENDPOINT: {
+ const tusb_desc_endpoint_t *p_ep = (const tusb_desc_endpoint_t *) p_desc;
+ p_desc = tu_desc_next(p_desc);
+
+ if (tu_desc_in_bounds(p_desc, desc_end) && tu_desc_type(p_desc) == TUSB_DESC_CS_ENDPOINT) {
+ // MIDI 2.0 CS Endpoint General 2.0: bNumGrpTrmBlk at offset 3
+ if (p_desc[0] >= 4 && p_desc[2] == MIDI_CS_ENDPOINT_GENERAL_2_0) {
+ uint8_t num_grp_trm_blk = p_desc[3];
+ if (tu_edpt_dir(p_ep->bEndpointAddress) == TUSB_DIR_OUT) {
+ tx_cable_count = num_grp_trm_blk;
+ } else {
+ rx_cable_count = num_grp_trm_blk;
+ }
+ }
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+
+ if (!found_new_interface) {
+ p_desc = tu_desc_next(p_desc);
+ }
+ }
+
+ p_midi->rx_cable_count_alt1 = rx_cable_count;
+ p_midi->tx_cable_count_alt1 = tx_cable_count;
+ return p_desc;
+}
+
+//--------------------------------------------------------------------+
+// Auto-selection logic
+//--------------------------------------------------------------------+
+
+static void midih2_auto_select_alt_setting(midih2_interface_t *p_midi) {
+ p_midi->alt_setting_current = 0;
+ if (p_midi->protocol_version == 1) {
+ p_midi->alt_setting_current = 1;
+ }
+}
+
+//--------------------------------------------------------------------+
+// Init/Deinit
+//--------------------------------------------------------------------+
+
+bool midih2_init(void) {
+ tu_memclr(&_midi2_host, sizeof(_midi2_host));
+ for (int inst = 0; inst < CFG_TUH_MIDI2; inst++) {
+ midih2_interface_t *p_midi = &_midi2_host[inst];
+
+ tu_edpt_stream_init(&p_midi->ep_stream.rx, true, false, false,
+ p_midi->ep_stream.rx_ff_buf, CFG_TUH_MIDI2_RX_BUFSIZE, _midi2_epbuf[inst].rx);
+
+ // TX uses raw tu_fifo + direct usbh_edpt_xfer (no FIFO wrapper) to preserve
+ // UMP packet boundaries across USB transfers.
+ midih2_tx_t* tx = &p_midi->ep_stream.tx;
+ (void) tu_fifo_config(&tx->ff, p_midi->ep_stream.tx_ff_buf, CFG_TUH_MIDI2_TX_BUFSIZE, false);
+ tx->ep_buf = _midi2_epbuf[inst].tx;
+ }
+ return true;
+}
+
+bool midih2_deinit(void) {
+ for (size_t i = 0; i < CFG_TUH_MIDI2; i++) {
+ midih2_interface_t* p_midi = &_midi2_host[i];
+ tu_edpt_stream_deinit(&p_midi->ep_stream.rx);
+ }
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// Class driver callbacks
+//--------------------------------------------------------------------+
+
+uint16_t midih2_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_interface_t *desc_itf, uint16_t max_len) {
+ (void) rhport;
+
+ TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass, 0);
+
+ // For Alt Setting 1, reuse existing slot for same device+interface
+ uint8_t idx = TUSB_INDEX_INVALID_8;
+ if (desc_itf->bAlternateSetting > 0) {
+ for (uint8_t i = 0; i < CFG_TUH_MIDI2; i++) {
+ if (_midi2_host[i].daddr == dev_addr &&
+ _midi2_host[i].bInterfaceNumber == desc_itf->bInterfaceNumber) {
+ idx = i;
+ break;
+ }
+ }
+ }
+ if (idx == TUSB_INDEX_INVALID_8) {
+ idx = find_new_midi2_index();
+ }
+ TU_VERIFY(idx < CFG_TUH_MIDI2, 0);
+
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+ p_midi->daddr = dev_addr;
+
+ const uint8_t *desc_start = (const uint8_t *) desc_itf;
+ const uint8_t *desc_end = desc_start + max_len;
+
+ // Skip Audio Control interface and any non-MIDI-Streaming descriptors
+ // (following midi_host.c pattern from Ha Thach)
+ if (AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass) {
+ const uint8_t *p_desc = tu_desc_next((const uint8_t *)desc_itf);
+ // Skip CS_INTERFACE header
+ TU_VERIFY(tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE, 0);
+ p_desc = tu_desc_next(p_desc);
+ desc_itf = (const tusb_desc_interface_t *) p_desc;
+ // Skip until we find MIDI Streaming interface
+ while (tu_desc_in_bounds(p_desc, desc_end) &&
+ (desc_itf->bDescriptorType != TUSB_DESC_INTERFACE ||
+ (desc_itf->bInterfaceClass == TUSB_CLASS_AUDIO &&
+ desc_itf->bInterfaceSubClass != AUDIO_SUBCLASS_MIDI_STREAMING))) {
+ p_desc = tu_desc_next(p_desc);
+ desc_itf = (const tusb_desc_interface_t *) p_desc;
+ }
+ TU_VERIFY(tu_desc_in_bounds(p_desc, desc_end), 0);
+ TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass, 0);
+ }
+
+ TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == desc_itf->bInterfaceSubClass, 0);
+
+ TU_LOG_DRV("MIDI2 opening Interface %u Alt %u (addr = %u)\r\n",
+ desc_itf->bInterfaceNumber, desc_itf->bAlternateSetting, dev_addr);
+
+ // Dispatch to appropriate parser based on Alt Setting
+ const uint8_t *p_end = NULL;
+ if (desc_itf->bAlternateSetting == 0) {
+ p_end = midih2_parse_descriptors_alt0(p_midi, desc_itf, desc_end);
+ } else if (desc_itf->bAlternateSetting == 1) {
+ p_end = midih2_parse_descriptors_alt1(p_midi, desc_itf, desc_end);
+ }
+
+ // Return number of bytes consumed (following midi_host.c pattern)
+ uint16_t const parsed_len = (p_end != NULL) ? (uint16_t)(p_end - desc_start) : 0;
+ return parsed_len;
+}
+
+static void midih2_set_config_complete(midih2_interface_t *p_midi, uint8_t idx) {
+ uint8_t dev_addr = p_midi->daddr;
+
+ // Invoke descriptor_cb
+ tuh_midi2_descriptor_cb_t desc_cb = {
+ .protocol_version = p_midi->protocol_version,
+ .bcdMSC_hi = p_midi->bcdMSC_hi,
+ .bcdMSC_lo = p_midi->bcdMSC_lo,
+ .rx_cable_count = (p_midi->alt_setting_current == 0) ?
+ p_midi->rx_cable_count_alt0 : p_midi->rx_cable_count_alt1,
+ .tx_cable_count = (p_midi->alt_setting_current == 0) ?
+ p_midi->tx_cable_count_alt0 : p_midi->tx_cable_count_alt1,
+ };
+ tuh_midi2_descriptor_cb(idx, &desc_cb);
+
+ // Mark as mounted
+ TU_LOG_DRV("MIDI2 mounted addr = %u, alt = %u, protocol = %u\r\n",
+ dev_addr, p_midi->alt_setting_current, p_midi->protocol_version);
+ p_midi->mounted = true;
+
+ // Invoke mount_cb
+ tuh_midi2_mount_cb_t mount_cb = {
+ .daddr = dev_addr,
+ .bInterfaceNumber = p_midi->bInterfaceNumber,
+ .protocol_version = p_midi->protocol_version,
+ .alt_setting_active = p_midi->alt_setting_current,
+ .rx_cable_count = desc_cb.rx_cable_count,
+ .tx_cable_count = desc_cb.tx_cable_count,
+ };
+ tuh_midi2_mount_cb(idx, &mount_cb);
+
+ // Prepare RX transfer
+ tu_edpt_stream_read_xfer(&p_midi->ep_stream.rx);
+
+ // Signal USBH that configuration is complete
+ usbh_driver_set_config_complete(dev_addr, p_midi->bInterfaceNumber);
+}
+
+static void midih2_set_interface_cb(tuh_xfer_t *xfer) {
+ uint8_t const dev_addr = xfer->daddr;
+ uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex);
+
+ // Find our interface
+ for (uint8_t idx = 0; idx < CFG_TUH_MIDI2; idx++) {
+ if (_midi2_host[idx].daddr == dev_addr && _midi2_host[idx].bInterfaceNumber == itf_num) {
+ if (xfer->result == XFER_RESULT_SUCCESS) {
+ midih2_set_config_complete(&_midi2_host[idx], idx);
+ } else {
+ // SET_INTERFACE failed, fall back to alt 0
+ TU_LOG_DRV("MIDI2 SET_INTERFACE failed, falling back to alt 0\r\n");
+ _midi2_host[idx].alt_setting_current = 0;
+ midih2_set_config_complete(&_midi2_host[idx], idx);
+ }
+ return;
+ }
+ }
+}
+
+bool midih2_set_config(uint8_t dev_addr, uint8_t itf_num) {
+ uint8_t idx = 0;
+ for (idx = 0; idx < CFG_TUH_MIDI2; idx++) {
+ if (_midi2_host[idx].daddr == dev_addr && _midi2_host[idx].bInterfaceNumber == itf_num) {
+ break;
+ }
+ }
+
+ if (idx >= CFG_TUH_MIDI2) {
+ // Not our interface (e.g. Audio Control) - pass through to next
+ usbh_driver_set_config_complete(dev_addr, itf_num);
+ return true;
+ }
+
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+
+ // Auto-select alt setting
+ midih2_auto_select_alt_setting(p_midi);
+
+ // If MIDI 2.0 detected, issue SET_INTERFACE to activate Alt Setting 1
+ if (p_midi->alt_setting_current == 1) {
+ TU_LOG_DRV("MIDI2 requesting SET_INTERFACE alt 1 for itf %u\r\n", itf_num);
+ TU_ASSERT(tuh_interface_set(dev_addr, itf_num, 1, midih2_set_interface_cb, 0));
+ } else {
+ // MIDI 1.0 only, complete immediately
+ midih2_set_config_complete(p_midi, idx);
+ }
+
+ return true;
+}
+
+void midih2_close(uint8_t dev_addr) {
+ for (uint8_t idx = 0; idx < CFG_TUH_MIDI2; idx++) {
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+ if (p_midi->daddr == dev_addr) {
+ TU_LOG_DRV(" MIDI2 close addr = %u index = %u\r\n", dev_addr, idx);
+ tu_edpt_stream_close(&p_midi->ep_stream.rx);
+ tu_fifo_clear(&p_midi->ep_stream.tx.ff);
+ p_midi->ep_stream.tx.ep_addr = 0;
+ tuh_midi2_umount_cb(idx);
+ tu_memclr(p_midi, sizeof(midih2_interface_t));
+ }
+ }
+}
+
+bool midih2_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
+ uint8_t idx = get_idx_by_ep_addr(dev_addr, ep_addr);
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+ midih2_tx_t* ep_tx = &p_midi->ep_stream.tx;
+
+ if (ep_addr == p_midi->ep_stream.rx.ep_addr) {
+ if (result == XFER_RESULT_SUCCESS && xferred_bytes > 0) {
+ tu_edpt_stream_read_xfer_complete(&p_midi->ep_stream.rx, xferred_bytes);
+ tuh_midi2_rx_cb(idx, xferred_bytes);
+ }
+ tu_edpt_stream_read_xfer(&p_midi->ep_stream.rx);
+ } else if (ep_addr == ep_tx->ep_addr) {
+ tuh_midi2_tx_cb(idx, xferred_bytes);
+ if (result == XFER_RESULT_SUCCESS) {
+ uint16_t queued = _tuh_tx_start_xfer(p_midi);
+ // Send ZLP if no more data is queued but the last transfer was exactly mps
+ if (queued == 0 && tu_fifo_count(&ep_tx->ff) == 0 && xferred_bytes > 0 &&
+ (0 == (xferred_bytes & (ep_tx->mps - 1)))) {
+ if (usbh_edpt_claim(dev_addr, ep_tx->ep_addr)) {
+ usbh_edpt_xfer(dev_addr, ep_tx->ep_addr, NULL, 0);
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
+// Public API
+//--------------------------------------------------------------------+
+
+bool tuh_midi2_mounted(uint8_t idx) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+ return _midi2_host[idx].mounted;
+}
+
+uint8_t tuh_midi2_get_protocol_version(uint8_t idx) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+ return _midi2_host[idx].protocol_version;
+}
+
+uint8_t tuh_midi2_get_alt_setting_active(uint8_t idx) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+ return _midi2_host[idx].alt_setting_current;
+}
+
+uint8_t tuh_midi2_get_cable_count(uint8_t idx) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+ return (_midi2_host[idx].alt_setting_current == 0) ?
+ _midi2_host[idx].rx_cable_count_alt0 : _midi2_host[idx].rx_cable_count_alt1;
+}
+
+uint32_t tuh_midi2_ump_read(uint8_t idx, uint32_t* words, uint32_t max_words) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2 && words && max_words);
+
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+ tu_edpt_stream_t *ep_rx = &p_midi->ep_stream.rx;
+
+ uint32_t n_words = 0;
+ for (uint32_t i = 0; i < max_words; i++) {
+ if (tu_edpt_stream_read_available(ep_rx) >= 4) {
+ tu_edpt_stream_read(ep_rx, (uint8_t *) &words[i], 4);
+ n_words++;
+ } else {
+ break;
+ }
+ }
+
+ return n_words;
+}
+
+uint32_t tuh_midi2_ump_write(uint8_t idx, const uint32_t* words, uint32_t count) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2 && words && count);
+
+ midih2_interface_t *p_midi = &_midi2_host[idx];
+ TU_VERIFY(_tuh_tx_opened(p_midi), 0);
+
+ return _tuh_tx_ump_write(p_midi, words, count);
+}
+
+uint32_t tuh_midi2_write_flush(uint8_t idx) {
+ TU_VERIFY(idx < CFG_TUH_MIDI2);
+ return _tuh_tx_start_xfer(&_midi2_host[idx]);
+}
+
+#endif // CFG_TUH_ENABLED && CFG_TUH_MIDI2
diff --git a/src/class/midi/midi2_host.h b/src/class/midi/midi2_host.h
new file mode 100644
index 000000000..47039eb85
--- /dev/null
+++ b/src/class/midi/midi2_host.h
@@ -0,0 +1,107 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * This file is part of the TinyUSB stack.
+ */
+
+#ifndef TUSB_MIDI2_HOST_H_
+#define TUSB_MIDI2_HOST_H_
+
+#include "class/audio/audio.h"
+#include "midi.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//--------------------------------------------------------------------+
+// Callback Type Definitions
+//--------------------------------------------------------------------+
+
+typedef struct {
+ uint8_t protocol_version; // 0 = MIDI 1.0 only, 1 = MIDI 2.0
+ uint8_t bcdMSC_hi, bcdMSC_lo; // MIDI version from descriptor
+ uint8_t rx_cable_count; // For both alt settings (same for Alt 0 and Alt 1)
+ uint8_t tx_cable_count;
+} tuh_midi2_descriptor_cb_t;
+
+typedef struct {
+ uint8_t daddr;
+ uint8_t bInterfaceNumber;
+ uint8_t protocol_version; // 0 = MIDI 1.0, 1 = MIDI 2.0
+ uint8_t alt_setting_active; // 0 or 1
+ uint8_t rx_cable_count;
+ uint8_t tx_cable_count;
+} tuh_midi2_mount_cb_t;
+
+//--------------------------------------------------------------------+
+// Application Callback API (weak, optional)
+//--------------------------------------------------------------------+
+
+void tuh_midi2_descriptor_cb(uint8_t idx, const tuh_midi2_descriptor_cb_t *desc_cb_data);
+void tuh_midi2_mount_cb(uint8_t idx, const tuh_midi2_mount_cb_t *mount_cb_data);
+void tuh_midi2_rx_cb(uint8_t idx, uint32_t xferred_bytes);
+void tuh_midi2_tx_cb(uint8_t idx, uint32_t xferred_bytes);
+void tuh_midi2_umount_cb(uint8_t idx);
+
+//--------------------------------------------------------------------+
+// Application API - Query
+//--------------------------------------------------------------------+
+
+bool tuh_midi2_mounted(uint8_t idx);
+uint8_t tuh_midi2_get_protocol_version(uint8_t idx);
+uint8_t tuh_midi2_get_alt_setting_active(uint8_t idx);
+uint8_t tuh_midi2_get_cable_count(uint8_t idx);
+
+//--------------------------------------------------------------------+
+// Application API - I/O
+//--------------------------------------------------------------------+
+
+// Read up to max_words UMP words from the RX FIFO. Returns the number of
+// words actually read (0 if FIFO is empty).
+//
+// NOTE: this function returns when max_words is reached or when the FIFO is
+// empty, whichever comes first. Applications should invoke it in a loop
+// until it returns 0 to guarantee the RX FIFO is fully drained per
+// tuh_midi2_rx_cb callback. Leaving words in the FIFO across callbacks can
+// prevent subsequent bulk IN transfers from landing.
+uint32_t tuh_midi2_ump_read(uint8_t idx, uint32_t* words, uint32_t max_words);
+uint32_t tuh_midi2_ump_write(uint8_t idx, const uint32_t* words, uint32_t count);
+uint32_t tuh_midi2_write_flush(uint8_t idx);
+
+//--------------------------------------------------------------------+
+// Internal Class Driver API
+//--------------------------------------------------------------------+
+
+bool midih2_init(void);
+bool midih2_deinit(void);
+bool midih2_set_config(uint8_t dev_addr, uint8_t itf_num);
+void midih2_close(uint8_t dev_addr);
+uint16_t midih2_open(uint8_t rhport, uint8_t dev_addr, const tusb_desc_interface_t *desc_itf, uint16_t max_len);
+bool midih2_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/class/midi/midi_host.h b/src/class/midi/midi_host.h
index b9ab0130d..8fdfd8966 100644
--- a/src/class/midi/midi_host.h
+++ b/src/class/midi/midi_host.h
@@ -150,6 +150,13 @@ uint32_t tuh_midi_stream_write(uint8_t idx, uint8_t cable_num, const uint8_t *p_
// Note that this function ignores the CIN field of the MIDI packet
// because a number of commercial devices out there do not encode
// it properly.
+//
+// NOTE: this function terminates when it encounters an event whose cable
+// number differs from the one being returned. Applications should invoke
+// it in a loop until it returns 0 (or until tuh_midi_read_available()
+// returns 0) to guarantee the stream FIFO is fully drained per callback.
+// Leaving bytes in the FIFO across callbacks can prevent subsequent bulk
+// IN transfers from landing.
uint32_t tuh_midi_stream_read(uint8_t idx, uint8_t *p_cable_num, uint8_t *p_buffer, uint16_t bufsize);
#endif
diff --git a/src/class/mtp/mtp_device.c b/src/class/mtp/mtp_device.c
index 59096e476..1f76dfcc7 100644
--- a/src/class/mtp/mtp_device.c
+++ b/src/class/mtp/mtp_device.c
@@ -321,7 +321,7 @@ bool mtpd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t
.session_id = p_mtp->session_id,
.request = request,
.buf = p_mtp->control_buf,
- .bufsize = tu_le16toh(request->wLength),
+ .bufsize = request->wLength,
};
switch (request->bRequest) {
@@ -441,9 +441,16 @@ bool mtpd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
threshold = CFG_TUD_MTP_EP_BUFSIZE;
}
- // Check completion: ZLP, short packet, or total length reached
- const bool is_complete =
- (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len);
+ // Check completion for IN and OUT separately
+ bool is_complete;
+ if (is_data_in) {
+ // IN completion: short packet, ZLP, or reaching total_len
+ is_complete = (xferred_bytes == 0 || xferred_bytes < threshold || p_mtp->xferred_len >= p_mtp->total_len);
+ } else {
+ // OUT completion: reaching total_len or ZLP only. A short packet does NOT end the phase
+ // (an early short packet before total_len is the cancel case, not normal completion).
+ is_complete = (p_mtp->xferred_len >= p_mtp->total_len) || ((xferred_bytes == 0 && p_mtp->xferred_len > 0));
+ }
TU_LOG_DRV(" MTP Data %s CB: xferred_bytes=%lu, xferred_len/total_len=%lu/%lu, is_complete=%d\r\n",
is_data_in ? "IN" : "OUT", xferred_bytes, p_mtp->xferred_len, p_mtp->total_len, is_complete ? 1 : 0);
diff --git a/src/class/net/ecm_rndis_device.c b/src/class/net/ecm_rndis_device.c
index eaa82c187..643bcfbcd 100644
--- a/src/class/net/ecm_rndis_device.c
+++ b/src/class/net/ecm_rndis_device.c
@@ -48,9 +48,10 @@ typedef struct {
uint8_t itf_num; // Index number of Management Interface, +1 for Data Interface
uint8_t itf_data_alt; // Alternate setting of Data Interface. 0 : inactive, 1 : active
- uint8_t ep_notif;
uint8_t ep_in;
uint8_t ep_out;
+ uint16_t ep_size; // bulk endpoint max packet size (IN and OUT assumed equal)
+ uint8_t ep_notif;
bool ecm_mode;
@@ -81,6 +82,13 @@ CFG_TUD_MEM_SECTION static netd_epbuf_t _netd_epbuf;
static bool can_xmit;
static bool ecm_link_is_up = true; // Store link state for ECM mode
+//--------------------------------------------------------------------+
+// Weak stubs: invoked if no strong implementation is available
+//--------------------------------------------------------------------+
+TU_ATTR_WEAK void tud_network_set_packet_filter_cb(uint16_t packet_filter) {
+ (void) packet_filter;
+}
+
void tud_network_recv_renew(void) {
usbd_edpt_xfer(0, _netd_itf.ep_out, _netd_epbuf.rx, NETD_PACKET_SIZE, false);
}
@@ -176,6 +184,9 @@ uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint1
// Pair of endpoints
TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc), 0);
+ // Save the actual bulk endpoint size (IN and OUT assumed equal)
+ _netd_itf.ep_size = tu_edpt_packet_size((tusb_desc_endpoint_t const *) p_desc);
+
if (_netd_itf.ecm_mode) {
// ECM by default is in-active, save the endpoint attribute
// to open later when received setInterface
@@ -206,14 +217,15 @@ static void ecm_report(bool nc) {
},
};
+ const uint32_t link_bps = (tud_speed_get() == TUSB_SPEED_HIGH) ? 480000000U : 12000000U;
const ecm_notify_t ecm_notify_csc = {
.header = {
.bmRequestType = 0xA1,
.bRequest = 0x2A, /* CONNECTION_SPEED_CHANGE aka ConnectionSpeedChange */
.wLength = 8,
},
- .downlink = 9728000,
- .uplink = 9728000,
+ .downlink = link_bps,
+ .uplink = link_bps,
};
ecm_notify_t notify = (nc) ? ecm_notify_nc : ecm_notify_csc;
@@ -285,6 +297,7 @@ bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t
if (_netd_itf.ecm_mode) {
/* the only required CDC-ECM Management Element Request is SetEthernetPacketFilter */
if (0x43 /* SET_ETHERNET_PACKET_FILTER */ == request->bRequest) {
+ tud_network_set_packet_filter_cb(request->wValue);
tud_control_xfer(rhport, request, NULL, 0);
// Only send connection notification if link is up
if (ecm_link_is_up) {
@@ -356,8 +369,7 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_
/* data transmission finished */
if (ep_addr == _netd_itf.ep_in) {
/* TinyUSB requires the class driver to implement ZLP (since ZLP usage is class-specific) */
-
- if (xferred_bytes && (0 == (xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE))) {
+ if (xferred_bytes > 0 && 0 == (xferred_bytes & (_netd_itf.ep_size-1))) {
do_in_xfer(NULL, 0); /* a ZLP is needed */
} else {
/* we're finally finished */
diff --git a/src/class/net/ncm.h b/src/class/net/ncm.h
index 8989fe0b4..27ff89b72 100644
--- a/src/class/net/ncm.h
+++ b/src/class/net/ncm.h
@@ -161,4 +161,18 @@ typedef struct {
uint32_t uplink;
} ncm_notify_t;
+typedef struct TU_ATTR_PACKED {
+ uint8_t bFunctionLength;
+ uint8_t bDescriptorType;
+ uint8_t bDescriptorSubType;
+ uint16_t bcdNcmVersion;
+ uint8_t bmCapabilities;
+} tusb_desc_cdc_ncm_func_t;
+
+typedef struct TU_ATTR_PACKED {
+ uint32_t dwNtbInMaxSize;
+ uint16_t wNtbInMaxDatagrams;
+ uint16_t wReserved;
+} ncm_ntb_input_size_t;
+
#endif
diff --git a/src/class/net/ncm_device.c b/src/class/net/ncm_device.c
index 405e4467b..e5f441300 100644
--- a/src/class/net/ncm_device.c
+++ b/src/class/net/ncm_device.c
@@ -83,6 +83,7 @@ typedef struct {
uint8_t itf_num; // interface number
uint8_t itf_data_alt; // ==0 -> no endpoints, i.e. no network traffic, ==1 -> normal operation with two endpoints (spec, chapter 5.3)
uint8_t rhport; // storage of \a rhport because some callbacks are done without it
+ uint16_t ep_size; // bulk endpoint max packet size (IN and OUT assumed equal)
// recv handling
recv_ntb_t *recv_free_ntb[RECV_NTB_N]; // free list of recv NTBs
@@ -118,6 +119,12 @@ typedef struct {
bool notification_xmit_is_running; // notification is currently transmitted
bool link_is_up; // current link state
+ // host-configured transmit limits
+ uint8_t bm_capabilities;
+ uint16_t xmit_max_ntb_size; // maximum NTB size device may send
+ uint16_t xmit_max_datagrams; // maximum datagrams per NTB device may send
+ ncm_ntb_input_size_t ntb_input_size;
+
// misc
bool tud_network_recv_renew_active; // tud_network_recv_renew() is active (avoid recursive invocations)
bool tud_network_recv_renew_process_again; // tud_network_recv_renew() should process again
@@ -138,6 +145,21 @@ typedef struct {
static ncm_interface_t ncm_interface;
CFG_TUD_MEM_SECTION static ncm_epbuf_t ncm_epbuf;
+//--------------------------------------------------------------------+
+// Weak stubs: invoked if no strong implementation is available
+//--------------------------------------------------------------------+
+TU_ATTR_WEAK void tud_network_set_packet_filter_cb(uint16_t packet_filter) {
+ (void) packet_filter;
+}
+
+TU_ATTR_WEAK bool tud_network_default_link_state_cb(void) {
+ #ifdef CFG_TUD_NCM_DEFAULT_LINK_UP
+ return CFG_TUD_NCM_DEFAULT_LINK_UP;
+ #else
+ return true;
+ #endif
+}
+
/**
* This is the NTB parameter structure
*
@@ -340,7 +362,8 @@ static xmit_ntb_t *xmit_get_next_ready_ntb(void) {
static bool xmit_insert_required_zlp(uint8_t rhport, uint32_t xferred_bytes) {
TU_LOG_DRV("xmit_insert_required_zlp(%d,%ld)\n", rhport, xferred_bytes);
- if (xferred_bytes == 0 || xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE != 0) {
+ uint16_t const ep_size = ncm_interface.ep_size;
+ if (xferred_bytes == 0 || (xferred_bytes & (ep_size-1)) != 0) {
return false;
}
@@ -408,10 +431,10 @@ static bool xmit_requested_datagram_fits_into_current_ntb(uint16_t datagram_size
if (ncm_interface.xmit_glue_ntb == NULL) {
return false;
}
- if (ncm_interface.xmit_glue_ntb_datagram_ndx >= CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB) {
+ if (ncm_interface.xmit_glue_ntb_datagram_ndx >= ncm_interface.xmit_max_datagrams) {
return false;
}
- if (ncm_interface.xmit_glue_ntb->nth.wBlockLength + datagram_size + XMIT_ALIGN_OFFSET(datagram_size) > CFG_TUD_NCM_IN_NTB_MAX_SIZE) {
+ if (ncm_interface.xmit_glue_ntb->nth.wBlockLength + datagram_size + (uint32_t)XMIT_ALIGN_OFFSET(datagram_size) > (uint32_t)ncm_interface.xmit_max_ntb_size) {
return false;
}
return true;
@@ -708,7 +731,7 @@ static void recv_transfer_datagram_to_glue_logic(void) {
bool tud_network_can_xmit(uint16_t size) {
TU_LOG_DRV("tud_network_can_xmit(%d)\n", size);
- TU_ASSERT(size <= CFG_TUD_NCM_IN_NTB_MAX_SIZE - (sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)), false);
+ TU_ASSERT(size <= ncm_interface.xmit_max_ntb_size - (sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)), false);
if (xmit_requested_datagram_fits_into_current_ntb(size) || xmit_setup_next_glue_ntb()) {
// -> everything is fine
@@ -828,18 +851,16 @@ void netd_init(void) {
memset(&ncm_interface, 0, sizeof(ncm_interface));
+ ncm_interface.xmit_max_ntb_size = CFG_TUD_NCM_IN_NTB_MAX_SIZE;
+ ncm_interface.xmit_max_datagrams = CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB;
+
for (int i = 0; i < XMIT_NTB_N; ++i) {
ncm_interface.xmit_free_ntb[i] = &ncm_epbuf.xmit[i].ntb;
}
for (int i = 0; i < RECV_NTB_N; ++i) {
ncm_interface.recv_free_ntb[i] = &ncm_epbuf.recv[i].ntb;
}
- // Default link state - can be configured via CFG_TUD_NCM_DEFAULT_LINK_UP
- #ifdef CFG_TUD_NCM_DEFAULT_LINK_UP
- ncm_interface.link_is_up = CFG_TUD_NCM_DEFAULT_LINK_UP;
- #else
- ncm_interface.link_is_up = true; // Default to link up if not set.
- #endif
+ ncm_interface.link_is_up = tud_network_default_link_state_cb();
} // netd_init
/**
@@ -878,10 +899,14 @@ uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16
ncm_interface.itf_num = itf_desc->bInterfaceNumber;// management interface
- // skip the two first entries and the following TUSB_DESC_CS_INTERFACE entries
uint16_t drv_len = sizeof(tusb_desc_interface_t);
uint8_t const *p_desc = tu_desc_next(itf_desc);
while (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && drv_len <= max_len) {
+ if (tu_desc_subtype(p_desc) == CDC_FUNC_DESC_NCM) {
+ TU_ASSERT(tu_desc_len(p_desc) >= sizeof(tusb_desc_cdc_ncm_func_t), 0);
+ tusb_desc_cdc_ncm_func_t const *ncm_func = (tusb_desc_cdc_ncm_func_t const *) p_desc;
+ ncm_interface.bm_capabilities = ncm_func->bmCapabilities;
+ }
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
@@ -905,6 +930,7 @@ uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16
// a TUSB_DESC_ENDPOINT (actually two) must follow, open these endpoints
TU_ASSERT(tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT, 0);
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &ncm_interface.ep_out, &ncm_interface.ep_in));
+ ncm_interface.ep_size = tu_edpt_packet_size((tusb_desc_endpoint_t const *) p_desc);
drv_len += 2 * sizeof(tusb_desc_endpoint_t);
return drv_len;
@@ -954,12 +980,12 @@ bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_
* At startup transmission of notification packets are done here.
*/
bool netd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) {
- if (stage != CONTROL_STAGE_SETUP) {
- return true;
- }
switch (request->bmRequestType_bit.type) {
case TUSB_REQ_TYPE_STANDARD:
+ if (stage != CONTROL_STAGE_SETUP) {
+ return true;
+ }
switch (request->bRequest) {
case TUSB_REQ_GET_INTERFACE: {
@@ -993,16 +1019,75 @@ bool netd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t
TU_VERIFY(ncm_interface.itf_num == request->wIndex, false);
switch (request->bRequest) {
case NCM_GET_NTB_PARAMETERS: {
+ if (stage != CONTROL_STAGE_SETUP) {
+ return true;
+ }
// transfer NTB parameters to host.
tud_control_xfer(rhport, request, (void *) (uintptr_t) &ntb_parameters, sizeof(ntb_parameters));
} break;
- // unsupported request
+ case NCM_SET_ETHERNET_PACKET_FILTER: {
+ if (stage != CONTROL_STAGE_SETUP) {
+ return true;
+ }
+
+ // Some hosts issue this request even if ETH_FILTER is not advertised,
+ // see https://bugzilla.kernel.org/show_bug.cgi?id=217290
+
+ tud_network_set_packet_filter_cb(request->wValue);
+ tud_control_xfer(rhport, request, NULL, 0);
+ } break;
+
+ case NCM_GET_NTB_INPUT_SIZE: {
+ if (stage != CONTROL_STAGE_SETUP) {
+ return true;
+ }
+
+ TU_VERIFY(request->wLength >=4, false);
+
+ uint8_t resp_len = (request->wLength >= 8 && (ncm_interface.bm_capabilities & NCM_NETWORK_CAPS_NTB_INPUT_SIZE)) ? 8 : 4;
+
+ ncm_ntb_input_size_t ntb_input_size = {
+ .dwNtbInMaxSize = ncm_interface.xmit_max_ntb_size,
+ .wNtbInMaxDatagrams = ncm_interface.xmit_max_datagrams
+ };
+ tud_control_xfer(rhport, request, &ntb_input_size, resp_len);
+ } break;
+
+ case NCM_SET_NTB_INPUT_SIZE: {
+ if (stage == CONTROL_STAGE_SETUP) {
+ /* wLength == 8 -> the NTB Input Size Structure (if NCM_NETWORK_CAPS_NTB_INPUT_SIZE is set)
+ wLength == 4 -> dwNtbInMaxSize field of the NTB Input Size Structure. */
+ TU_VERIFY(request->wLength == 4 || request->wLength == 8, false);
+ if (request->wLength == 8) {
+ TU_VERIFY(ncm_interface.bm_capabilities & NCM_NETWORK_CAPS_NTB_INPUT_SIZE, false);
+ }
+
+ tu_memclr(&ncm_interface.ntb_input_size, sizeof(ncm_interface.ntb_input_size));
+ tud_control_xfer(rhport, request, &ncm_interface.ntb_input_size, request->wLength);
+ } else if (stage == CONTROL_STAGE_DATA) {
+ /* CDC-NCM 1.0 Table 6-4, up to NTB16 size */
+ const uint32_t requested_size = ncm_interface.ntb_input_size.dwNtbInMaxSize;
+ if (requested_size < 2048u || requested_size > 65535u) {
+ return false;
+ }
+ ncm_interface.xmit_max_ntb_size = tu_min16(requested_size, CFG_TUD_NCM_IN_NTB_MAX_SIZE);
+
+ if (ncm_interface.ntb_input_size.wNtbInMaxDatagrams == 0 || ncm_interface.ntb_input_size.wNtbInMaxDatagrams > CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB) {
+ ncm_interface.xmit_max_datagrams = CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB;
+ } else {
+ ncm_interface.xmit_max_datagrams = ncm_interface.ntb_input_size.wNtbInMaxDatagrams;
+ }
+ }
+ } break;
+
+ // unsupported request
default:
return false;
}
break;
- // unsupported request
+
+ // unsupported request
default:
return false;
}
diff --git a/src/class/net/net_device.h b/src/class/net/net_device.h
index 96c03fd61..1ad069d92 100644
--- a/src/class/net/net_device.h
+++ b/src/class/net/net_device.h
@@ -35,9 +35,6 @@
#error "Cannot enable both ECM_RNDIS and NCM network drivers"
#endif
-/* declared here, NOT in usb_descriptors.c, so that the driver can intelligently ZLP as needed */
-#define CFG_TUD_NET_ENDPOINT_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
-
/* Maximum Transmission Unit (in bytes) of the network, including Ethernet header */
#ifndef CFG_TUD_NET_MTU
#define CFG_TUD_NET_MTU 1514
@@ -50,6 +47,16 @@ typedef enum
NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK = 0x01
} ncm_data_interface_protocol_code_t;
+// Table 5.2 bmNetworkCapabilities bits
+typedef enum {
+ NCM_NETWORK_CAPS_NONE = 0x00,
+ NCM_NETWORK_CAPS_ETH_FILTER = (1 << 0),
+ NCM_NETWORK_CAPS_NET_ADDRESS = (1 << 1),
+ NCM_NETWORK_CAPS_ENCAP_COMMAND = (1 << 2),
+ NCM_NETWORK_CAPS_MAX_DATAGRAM_SIZE = (1 << 3),
+ NCM_NETWORK_CAPS_CRC_MODE = (1 << 4),
+ NCM_NETWORK_CAPS_NTB_INPUT_SIZE = (1 << 5)
+} ncm_network_capabilities_t;
#ifdef __cplusplus
extern "C" {
@@ -96,6 +103,13 @@ extern uint8_t tud_network_mac_address[6];
//------------- NCM -------------//
+// Optional callback: informs the application about host requested packet filter bits
+void tud_network_set_packet_filter_cb(uint16_t packet_filter);
+
+// Optional callback: called during netd_init() to get the initial link state.
+// Override to return the actual physical link state instead of the compile-time default.
+bool tud_network_default_link_state_cb(void);
+
// Set the network link state (up/down) and notify the host
void tud_network_link_state(uint8_t rhport, bool is_up);
diff --git a/src/class/printer/printer_device.c b/src/class/printer/printer_device.c
index d2dc9b163..158455fc9 100644
--- a/src/class/printer/printer_device.c
+++ b/src/class/printer/printer_device.c
@@ -41,7 +41,6 @@ typedef struct {
uint8_t itf_num;
/*------------- From this point, data is not cleared by bus reset -------------*/
-
tu_edpt_stream_t rx_stream;
tu_edpt_stream_t tx_stream;
diff --git a/src/class/video/video_device.c b/src/class/video/video_device.c
index bbcfe45d5..e31ab4194 100644
--- a/src/class/video/video_device.c
+++ b/src/class/video/video_device.c
@@ -865,7 +865,7 @@ static bool _open_vs_itf(uint8_t rhport, videod_streaming_interface_t *stm, uint
/* FS must be less than or equal to max packet size */
TU_VERIFY (tu_edpt_packet_size(ep) >= max_size);
#ifdef TUP_DCD_EDPT_ISO_ALLOC
- usbd_edpt_iso_activate(rhport, ep);
+ TU_ASSERT(usbd_edpt_iso_activate(rhport, ep));
#else
TU_ASSERT(usbd_edpt_open(rhport, ep));
#endif
diff --git a/src/common/tusb_compiler.h b/src/common/tusb_compiler.h
index f20834cea..a8971c3df 100644
--- a/src/common/tusb_compiler.h
+++ b/src/common/tusb_compiler.h
@@ -66,6 +66,9 @@
#define TU_LITTLE_ENDIAN (0x12u)
#define TU_BIG_ENDIAN (0x21u)
+#define TU_BITFIELD_LE (0x34u)
+#define TU_BITFIELD_BE (0x43u)
+
/*------------------------------------------------------------------*/
/* Count number of arguments of __VA_ARGS__
* - reference www.stackoverflow.com/questions/2124339/c-preprocessor-va-args-number-of-arguments
@@ -167,8 +170,10 @@
// For TI ARM compiler, __BYTE_ORDER__ is not defined for MSP430 but still LE
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ || defined(__MSP430__)
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_LE
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_BE
#endif
// Unfortunately XC16 doesn't provide builtins for 32bit endian conversion
@@ -212,8 +217,10 @@
// Endian conversion use well-known host to network (big endian) naming
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_LE
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_BE
#endif
#define TU_BSWAP16(u16) (__iar_builtin_REV16(u16))
@@ -239,8 +246,10 @@
// Endian conversion use well-known host to network (big endian) naming
#if defined(__LIT)
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_LE
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
+ #define TU_BITFIELD_ORDER TU_BITFIELD_BE
#endif
#define TU_BSWAP16(u16) ((unsigned short)_builtin_revw((unsigned long)u16))
diff --git a/src/common/tusb_fifo.c b/src/common/tusb_fifo.c
index 06d25d131..a8ac99fd2 100644
--- a/src/common/tusb_fifo.c
+++ b/src/common/tusb_fifo.c
@@ -281,14 +281,14 @@ static void hwff_push_n(const tu_fifo_t *f, const void *app_buf, uint16_t n, uin
// Write full words to the linear part of the buffer
const uint8_t data_stride = access_mode->data_stride;
const uint32_t odd_mask = data_stride - 1;
- uint16_t lin_even = lin_bytes & ~odd_mask;
+ uint16_t lin_even = (uint16_t)(lin_bytes & ~odd_mask);
tu_hwfifo_read(hwfifo, ff_buf, lin_even, access_mode);
HWFIFO_ADDR_NEXT_N(hwfifo, const, lin_even * HWFIFO_ADDR_DATA_RATIO);
ff_buf += lin_even;
// There could be an odd 1 byte (16bit) or 1-3 bytes (32bit) before the wrap-around boundary
// combine it with the wrapped part to form a full word for data stride
- const uint8_t lin_odd = lin_bytes & odd_mask;
+ const uint8_t lin_odd = (uint8_t)(lin_bytes & odd_mask);
if (lin_odd > 0) {
const uint8_t wrap_odd = (uint8_t)tu_min16(wrap_bytes, data_stride - lin_odd);
uint8_t buf_temp[4];
@@ -338,13 +338,13 @@ static void hwff_pull_n(const tu_fifo_t *f, void *app_buf, uint16_t n, uint16_t
// Read full words from linear part
const uint8_t data_stride = access_mode->data_stride;
const uint32_t odd_mask = data_stride - 1;
- uint16_t lin_even = lin_bytes & ~odd_mask;
+ uint16_t lin_even = (uint16_t)(lin_bytes & ~odd_mask);
tu_hwfifo_write(hwfifo, ff_buf, lin_even, access_mode);
HWFIFO_ADDR_NEXT_N(hwfifo, , lin_even * HWFIFO_ADDR_DATA_RATIO);
ff_buf += lin_even;
// There could be odd 1 byte (16bit) or 1-3 bytes (32bit) before the wrap-around boundary
- const uint8_t lin_odd = lin_bytes & odd_mask;
+ const uint8_t lin_odd = (uint8_t)(lin_bytes & odd_mask);
if (lin_odd > 0) {
const uint8_t wrap_odd = (uint8_t)tu_min16(wrap_bytes, data_stride - lin_odd);
diff --git a/src/common/tusb_mcu.h b/src/common/tusb_mcu.h
index 77a0bbf1d..b5390a59d 100644
--- a/src/common/tusb_mcu.h
+++ b/src/common/tusb_mcu.h
@@ -177,12 +177,12 @@
#elif TU_CHECK_MCU(OPT_MCU_SAMG)
#define TUP_DCD_ENDPOINT_MAX 6
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
#elif TU_CHECK_MCU(OPT_MCU_SAMX7X)
#define TUP_DCD_ENDPOINT_MAX 10
#define TUP_RHPORT_HIGHSPEED 1
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
// Enable dcache if DMA is enabled
#define CFG_TUD_MEM_DCACHE_ENABLE_DEFAULT CFG_TUD_SAMX7X_DMA_ENABLE
@@ -190,11 +190,11 @@
#elif TU_CHECK_MCU(OPT_MCU_PIC32MZ)
#define TUP_DCD_ENDPOINT_MAX 8
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
#elif TU_CHECK_MCU(OPT_MCU_PIC32MX, OPT_MCU_PIC32MM, OPT_MCU_PIC32MK) || TU_CHECK_MCU(OPT_MCU_PIC24, OPT_MCU_DSPIC33)
#define TUP_DCD_ENDPOINT_MAX 16
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
#define TUP_DCD_EDPT_CLOSE_API
//--------------------------------------------------------------------+
@@ -206,6 +206,12 @@
#define TUP_USBIP_FSDEV_DRD
#define CFG_TUSB_FSDEV_PMA_SIZE 2048u
+#elif TU_CHECK_MCU(OPT_MCU_STM32C5)
+ #define TUP_USBIP_FSDEV
+ #define TUP_USBIP_FSDEV_STM32
+ #define TUP_USBIP_FSDEV_DRD
+ #define CFG_TUSB_FSDEV_PMA_SIZE 2048u
+
#elif TU_CHECK_MCU(OPT_MCU_STM32F0)
#define TUP_USBIP_FSDEV
#define TUP_USBIP_FSDEV_STM32
@@ -411,7 +417,7 @@
#elif TU_CHECK_MCU(OPT_MCU_CXD56)
#define TUP_DCD_ENDPOINT_MAX 7
#define TUP_RHPORT_HIGHSPEED 1
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
//--------------------------------------------------------------------+
// TI
@@ -455,7 +461,7 @@
#define CFG_TUSB_OS_INC_PATH_DEFAULT freertos/
// clang-format on
- #if CFG_TUSB_MCU == OPT_MCU_ESP32S3
+ #if CFG_TUSB_MCU == OPT_MCU_ESP32S3 || CFG_TUSB_MCU == OPT_MCU_ESP32H4
#define TUP_MCU_MULTIPLE_CORE 1
#endif
@@ -476,6 +482,22 @@
#define CFG_TUH_MEM_DCACHE_ENABLE_DEFAULT CFG_TUH_DWC2_DMA_ENABLE
#define CFG_TUSB_MEM_DCACHE_LINE_SIZE_DEFAULT 64
+#elif TU_CHECK_MCU(OPT_MCU_ESP32S31)
+ #define TUP_USBIP_DWC2
+ #define TUP_USBIP_DWC2_ESP32
+ #define TUP_RHPORT_HIGHSPEED 1
+ #define TUP_DCD_ENDPOINT_MAX 16
+
+ // clang-format off
+ #define CFG_TUSB_OS_INC_PATH_DEFAULT freertos/
+ // clang-format on
+
+ #define TUP_MCU_MULTIPLE_CORE 1
+
+ // Disable slave if DMA is enabled
+ #define CFG_TUD_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUD_DWC2_DMA_ENABLE
+ #define CFG_TUH_DWC2_SLAVE_ENABLE_DEFAULT !CFG_TUH_DWC2_DMA_ENABLE
+
#elif TU_CHECK_MCU(OPT_MCU_ESP32, OPT_MCU_ESP32C2, OPT_MCU_ESP32C3, OPT_MCU_ESP32C5, OPT_MCU_ESP32C6, \
OPT_MCU_ESP32C61, OPT_MCU_ESP32H2)
#if (CFG_TUD_ENABLED || !(defined(CFG_TUH_MAX3421) && CFG_TUH_MAX3421))
@@ -547,12 +569,12 @@
#elif TU_CHECK_MCU(OPT_MCU_FT90X)
#define TUP_DCD_ENDPOINT_MAX 8
#define TUP_RHPORT_HIGHSPEED 1
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
#elif TU_CHECK_MCU(OPT_MCU_FT93X)
#define TUP_DCD_ENDPOINT_MAX 16
#define TUP_RHPORT_HIGHSPEED 1
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
//--------------------------------------------------------------------+
// Allwinner
@@ -600,10 +622,6 @@
#define CFG_TUH_WCH_USBIP_USBFS 1
#endif
- #define TUP_USBIP_FSDEV
- #define TUP_USBIP_FSDEV_CH32
- #define CFG_TUSB_FSDEV_PMA_SIZE 512u
-
// default to FSDEV for device
#if !defined(CFG_TUD_WCH_USBIP_USBFS)
#define CFG_TUD_WCH_USBIP_USBFS 0
@@ -613,6 +631,12 @@
#define CFG_TUD_WCH_USBIP_FSDEV (CFG_TUD_WCH_USBIP_USBFS ? 0 : 1)
#endif
+ #if CFG_TUD_WCH_USBIP_FSDEV
+ #define TUP_USBIP_FSDEV
+ #define TUP_USBIP_FSDEV_CH32
+ #define CFG_TUSB_FSDEV_PMA_SIZE 512u
+ #endif
+
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_CH32V307)
@@ -635,6 +659,19 @@
#define TUP_DCD_EDPT_CLOSE_API
#endif
+#elif TU_CHECK_MCU(OPT_MCU_CH583)
+ // CH582/583 USBFS: older WCH USBFS IP with a single combined per-endpoint control register
+ // (like CH32V103), driven by the shared dcd_ch32_usbfs.c on USB0 (rhport 0). Device only:
+ // the shared hcd_ch32_usbfs.c is CH32V20x-specific and does not support CH58x, so host /
+ // USB2 (rhport 1) is not provided here.
+ #define TUP_USBIP_WCH_USBFS
+
+ #ifndef CFG_TUD_WCH_USBIP_USBFS
+ #define CFG_TUD_WCH_USBIP_USBFS 1
+ #endif
+
+ #define TUP_DCD_ENDPOINT_MAX 8
+
//--------------------------------------------------------------------+
// Analog Devices
//--------------------------------------------------------------------+
@@ -643,7 +680,7 @@
#define TUP_USBIP_MUSB_ADI
#define TUP_DCD_ENDPOINT_MAX 12
#define TUP_RHPORT_HIGHSPEED 1
- #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 1
//--------------------------------------------------------------------+
// ArteryTek
@@ -727,3 +764,14 @@
#ifndef TUP_DCD_EDPT_CLOSE_API
#define TUP_DCD_EDPT_ISO_ALLOC
#endif
+
+// Some USBIPs (SAMG, SAMX7X, PIC32, MAX3266x/MAX78002) cannot assign the same endpoint
+// number to both IN and OUT. Default to 0 (same endpoint number may be used for IN and OUT).
+#ifndef CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY 0
+#endif
+
+// Backward-compatible alias: legacy code only tests defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY && !defined(TUD_ENDPOINT_ONE_DIRECTION_ONLY)
+ #define TUD_ENDPOINT_ONE_DIRECTION_ONLY
+#endif
diff --git a/src/common/tusb_private.h b/src/common/tusb_private.h
index 91d213755..a31bf7b03 100644
--- a/src/common/tusb_private.h
+++ b/src/common/tusb_private.h
@@ -46,17 +46,10 @@ extern tusb_role_t _tusb_rhport_role[TUP_USBIP_CONTROLLER_NUM];
// Endpoint
//--------------------------------------------------------------------+
-enum {
- TU_EDPT_STATE_BUSY = 0x01,
- TU_EDPT_STATE_STALLED = 0x02,
- TU_EDPT_STATE_CLAIMED = 0x04,
-};
-
-typedef struct TU_ATTR_PACKED {
- volatile uint8_t busy : 1;
- volatile uint8_t stalled : 1;
- volatile uint8_t claimed : 1;
-} tu_edpt_state_t;
+// Endpoint state bits — manipulate the bare uint8_t with these masks.
+#define TU_EDPT_STATE_BUSY 0x01u
+#define TU_EDPT_STATE_STALLED 0x02u
+#define TU_EDPT_STATE_CLAIMED 0x04u
typedef struct {
uint8_t hwid; // device: rhport, host: daddr
@@ -92,10 +85,10 @@ bool tu_bind_driver_to_ep_itf(uint8_t driver_id, uint8_t ep2drv[][2], uint8_t it
const uint8_t *p_desc, uint16_t desc_len);
// Claim an endpoint with provided mutex
-bool tu_edpt_claim(tu_edpt_state_t* ep_state, osal_mutex_t mutex);
+bool tu_edpt_claim(volatile uint8_t* ep_state, osal_mutex_t mutex);
// Release an endpoint with provided mutex
-bool tu_edpt_release(tu_edpt_state_t* ep_state, osal_mutex_t mutex);
+bool tu_edpt_release(volatile uint8_t* ep_state, osal_mutex_t mutex);
//--------------------------------------------------------------------+
// Endpoint Stream
diff --git a/src/common/tusb_types.h b/src/common/tusb_types.h
index a18f9feb7..cb06b89bb 100644
--- a/src/common/tusb_types.h
+++ b/src/common/tusb_types.h
@@ -100,12 +100,14 @@ typedef enum {
} tusb_xfer_type_t;
typedef enum {
- TUSB_DIR_OUT = 0,
- TUSB_DIR_IN = 1,
+ TUSB_DIR_OUT = 0u,
+ TUSB_DIR_IN = 1u,
+} tusb_dir_t;
- TUSB_EPNUM_MASK = 0x0F,
+enum {
+ TUSB_EPNUM_MASK = 0x0F,
TUSB_DIR_IN_MASK = 0x80
-} tusb_dir_t;
+};
enum {
TUSB_EPSIZE_BULK_FS = 64,
@@ -280,6 +282,7 @@ typedef enum {
XFER_RESULT_FAILED,
XFER_RESULT_STALLED,
XFER_RESULT_TIMEOUT,
+ XFER_RESULT_ABORTED,
XFER_RESULT_INVALID
} xfer_result_t;
@@ -319,6 +322,12 @@ enum {
TUSB_INDEX_INVALID_8 = 0xFF
};
+enum {
+ TU_EP0_OUT = 0x00,
+ TU_EP0_IN = 0x80
+};
+
+
//--------------------------------------------------------------------+
//
//--------------------------------------------------------------------+
@@ -409,10 +418,19 @@ typedef struct TU_ATTR_PACKED {
uint8_t bEndpointAddress ; // The address of the endpoint
struct TU_ATTR_PACKED {
+#if (TU_BITFIELD_ORDER == TU_BITFIELD_LE)
uint8_t xfer : 2; // Control, ISO, Bulk, Interrupt
uint8_t sync : 2; // None, Asynchronous, Adaptive, Synchronous
uint8_t usage : 2; // Data, Feedback, Implicit feedback
uint8_t : 2;
+#elif (TU_BITFIELD_ORDER == TU_BITFIELD_BE)
+ uint8_t : 2;
+ uint8_t usage : 2;
+ uint8_t sync : 2;
+ uint8_t xfer : 2;
+#else
+ #error "Please define TU_BITFIELD_ORDER as TU_BITFIELD_LE or TU_BITFIELD_BE"
+#endif
} bmAttributes;
uint16_t wMaxPacketSize ; // Bit 10..0 : max packet size, bit 12..11 additional transaction per highspeed micro-frame
@@ -522,9 +540,17 @@ typedef struct TU_ATTR_PACKED {
typedef struct TU_ATTR_PACKED {
union {
struct TU_ATTR_PACKED {
+#if (TU_BITFIELD_ORDER == TU_BITFIELD_LE)
uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
uint8_t type : 2; ///< Request type tusb_request_type_t.
uint8_t direction : 1; ///< Direction type. tusb_dir_t
+#elif (TU_BITFIELD_ORDER == TU_BITFIELD_BE)
+ uint8_t direction : 1; ///< Direction type. tusb_dir_t
+ uint8_t type : 2; ///< Request type tusb_request_type_t.
+ uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
+#else
+ #error "Please define TU_BITFIELD_ORDER as TU_BITFIELD_LE or TU_BITFIELD_BE"
+#endif
} bmRequestType_bit;
uint8_t bmRequestType;
diff --git a/src/device/dcd.h b/src/device/dcd.h
index 850c37bc2..f861eb258 100644
--- a/src/device/dcd.h
+++ b/src/device/dcd.h
@@ -219,6 +219,11 @@ TU_ATTR_ALWAYS_INLINE static inline void dcd_event_setup_received(uint8_t rhport
event.rhport = rhport;
event.event_id = DCD_EVENT_SETUP_RECEIVED;
(void) memcpy(&event.setup_received, setup, sizeof(tusb_control_request_t));
+ // USB wire format is little-endian. Convert multi-byte fields to host byte order
+ // so the stack always sees correct values regardless of CPU endianness.
+ event.setup_received.wValue = tu_le16toh(event.setup_received.wValue);
+ event.setup_received.wIndex = tu_le16toh(event.setup_received.wIndex);
+ event.setup_received.wLength = tu_le16toh(event.setup_received.wLength);
dcd_event_handler(&event, in_isr);
}
diff --git a/src/device/usbd.c b/src/device/usbd.c
index 3c14175f6..f87b63111 100644
--- a/src/device/usbd.c
+++ b/src/device/usbd.c
@@ -115,7 +115,20 @@ TU_ATTR_WEAK bool dcd_dcache_clean_invalidate(const void* addr, uint32_t data_si
//--------------------------------------------------------------------+
// Device Data
//--------------------------------------------------------------------+
+
+// Per-control-transfer state: populated at process_setup_received() entry,
+// consumed asynchronously by usbd_control_xfer_cb() when the EP0 transfer completes.
+typedef struct {
+ tusb_control_request_t request;
+ uint8_t* buffer;
+ uint16_t data_len;
+ uint16_t total_xferred;
+ usbd_control_xfer_cb_t complete_cb;
+} usbd_control_xfer_t;
+
typedef struct {
+ usbd_control_xfer_t ctrl_xfer;
+
// Note: these may share an enum state
volatile uint8_t connected;
volatile uint8_t addressed;
@@ -136,12 +149,16 @@ typedef struct {
uint8_t itf2drv[CFG_TUD_INTERFACE_MAX]; // map interface number to driver (0xff is invalid)
uint8_t ep2drv[CFG_TUD_ENDPPOINT_MAX][2]; // map endpoint to driver ( 0xff is invalid ), can use only 4-bit each
- tu_edpt_state_t ep_status[CFG_TUD_ENDPPOINT_MAX][2];
+ volatile uint8_t ep_status[CFG_TUD_ENDPPOINT_MAX][2];
} usbd_device_t;
static usbd_device_t _usbd_dev;
static volatile uint8_t _usbd_queued_setup;
+CFG_TUD_MEM_SECTION static struct {
+ TUD_EPBUF_DEF(buf, CFG_TUD_ENDPOINT0_BUFSIZE);
+} _ctrl_epbuf;
+
//--------------------------------------------------------------------+
// Class Driver
//--------------------------------------------------------------------+
@@ -237,6 +254,20 @@ static const usbd_class_driver_t _usbd_driver[] = {
},
#endif
+ #if CFG_TUD_MIDI2
+ {
+ .name = DRIVER_NAME("MIDI2"),
+ .init = midi2d_init,
+ .deinit = midi2d_deinit,
+ .open = midi2d_open,
+ .reset = midi2d_reset,
+ .control_xfer_cb = midi2d_control_xfer_cb,
+ .xfer_cb = midi2d_xfer_cb,
+ .xfer_isr = NULL,
+ .sof = NULL
+ },
+ #endif
+
#if CFG_TUD_VENDOR
{
.name = DRIVER_NAME("VENDOR"),
@@ -405,7 +436,8 @@ TU_ATTR_ALWAYS_INLINE static inline bool queue_event(dcd_event_t const * event,
//--------------------------------------------------------------------+
// Prototypes
//--------------------------------------------------------------------+
-static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
+static bool usbd_control_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
+static bool process_setup_received(uint8_t rhport, tusb_control_request_t const * p_request);
static bool process_set_config(uint8_t rhport, uint8_t cfg_num);
static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request);
@@ -419,12 +451,6 @@ static bool process_test_mode_cb(uint8_t rhport, uint8_t stage, tusb_control_req
}
#endif
-// from usbd_control.c
-void usbd_control_reset(void);
-void usbd_control_set_request(tusb_control_request_t const *request);
-void usbd_control_set_complete_callback( usbd_control_xfer_cb_t fp );
-bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
-
//--------------------------------------------------------------------+
// Weak stubs: invoked if no strong implementation is available
//--------------------------------------------------------------------+
@@ -459,17 +485,6 @@ static char const *const _usbd_event_str[DCD_EVENT_COUNT] = {
"Func Call"
};
-// for usbd_control to print the name of control complete driver
-void usbd_driver_print_control_complete_name(usbd_control_xfer_cb_t callback) {
- for (uint8_t i = 0; i < TOTAL_DRIVER_COUNT; i++) {
- usbd_class_driver_t const* driver = get_driver(i);
- if (driver && driver->control_xfer_cb == callback) {
- TU_LOG_USBD("%s control complete\r\n", driver->name);
- return;
- }
- }
-}
-
#endif
//--------------------------------------------------------------------+
@@ -609,9 +624,7 @@ bool tud_deinit(uint8_t rhport) {
}
}
- // Clear device data
- tu_varclr(&_usbd_dev);
- usbd_control_reset();
+ tu_varclr(&_usbd_dev); // Clear device data
// Deinit device queue & task
osal_queue_delete(_usbd_q);
@@ -646,7 +659,6 @@ static void configuration_reset(uint8_t rhport) {
static void usbd_reset(uint8_t rhport) {
configuration_reset(rhport);
- usbd_control_reset();
}
bool tud_task_event_ready(void) {
@@ -713,7 +725,9 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) {
break;
case DCD_EVENT_SETUP_RECEIVED:
- TU_ASSERT(_usbd_queued_setup > 0,);
+ if (_usbd_queued_setup == 0) {
+ break;
+ }
_usbd_queued_setup--;
TU_LOG_BUF(CFG_TUD_LOG_LEVEL, &event.setup_received, 8);
if (_usbd_queued_setup != 0) {
@@ -725,18 +739,16 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) {
// But it is easier to set it every time instead of wasting time to check then set
_usbd_dev.connected = 1;
- // mark both in & out control as free
- _usbd_dev.ep_status[0][TUSB_DIR_OUT].busy = 0;
- _usbd_dev.ep_status[0][TUSB_DIR_OUT].claimed = 0;
- _usbd_dev.ep_status[0][TUSB_DIR_IN].busy = 0;
- _usbd_dev.ep_status[0][TUSB_DIR_IN].claimed = 0;
+ // reset ep state
+ _usbd_dev.ep_status[0][TUSB_DIR_OUT] = 0;
+ _usbd_dev.ep_status[0][TUSB_DIR_IN] = 0;
// Process control request
- if (!process_control_request(event.rhport, &event.setup_received)) {
+ if (!process_setup_received(event.rhport, &event.setup_received)) {
TU_LOG_USBD(" Stall EP0\r\n");
// Failed -> stall both control endpoint IN and OUT
- dcd_edpt_stall(event.rhport, 0);
- dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK);
+ dcd_edpt_stall(event.rhport, TU_EP0_OUT);
+ dcd_edpt_stall(event.rhport, TU_EP0_IN);
}
break;
@@ -748,8 +760,8 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) {
TU_LOG_USBD("on EP %02X with %u bytes\r\n", ep_addr, (unsigned int) event.xfer_complete.len);
- _usbd_dev.ep_status[epnum][ep_dir].busy = 0;
- _usbd_dev.ep_status[epnum][ep_dir].claimed = 0;
+ // Clear busy + claimed
+ _usbd_dev.ep_status[epnum][ep_dir] &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
if (0 == epnum) {
usbd_control_xfer_cb(event.rhport, ep_addr, (xfer_result_t) event.xfer_complete.result, event.xfer_complete.len);
@@ -809,25 +821,275 @@ void tud_task_ext(uint32_t timeout_ms, bool in_isr) {
}
//--------------------------------------------------------------------+
+// Control Endpoint
+//--------------------------------------------------------------------+
+
+// Weak hook: invoked when the control transfer's status stage completes
+TU_ATTR_WEAK void dcd_edpt0_status_complete(uint8_t rhport, const tusb_control_request_t* request) {
+ (void) rhport;
+ (void) request;
+}
+
+uint8_t* usbd_get_ctrl_buf(void) {
+ return _ctrl_epbuf.buf;
+}
+
+// Endpoint used for the Status stage of a control transfer.
+// Per USB 2.0 §9.3.1, when wLength == 0 the Direction bit is ignored and the Status
+// stage is always IN. Otherwise the Status stage is opposite of the Data stage direction.
+TU_ATTR_ALWAYS_INLINE static inline uint8_t status_stage_ep(const tusb_control_request_t* request) {
+ return (request->wLength != 0 && request->bmRequestType_bit.direction) ? TU_EP0_OUT : TU_EP0_IN;
+}
+
+// Queue ZLP status transaction
+TU_ATTR_ALWAYS_INLINE static inline bool status_stage_xact(uint8_t rhport, uint8_t ep_status) {
+ return usbd_edpt_xfer(rhport, ep_status, NULL, 0, false);
+}
+
+// Queue a transaction in Data Stage. Each transaction has up to Endpoint0's max
+// packet size. This function can also transfer a zero-length packet.
+static bool data_stage_xact(uint8_t rhport) {
+ usbd_control_xfer_t* const ctrl_xfer = &_usbd_dev.ctrl_xfer;
+ const uint16_t xact_len = tu_min16(ctrl_xfer->data_len - ctrl_xfer->total_xferred, CFG_TUD_ENDPOINT0_BUFSIZE);
+ uint8_t ep_addr = TU_EP0_OUT;
+
+ if (ctrl_xfer->request.bmRequestType_bit.direction == TUSB_DIR_IN) {
+ ep_addr = TU_EP0_IN;
+ if (0u != xact_len && ctrl_xfer->buffer != _ctrl_epbuf.buf) {
+ TU_VERIFY(0 == tu_memcpy_s(_ctrl_epbuf.buf, CFG_TUD_ENDPOINT0_BUFSIZE, ctrl_xfer->buffer, xact_len));
+ }
+ }
+
+ return usbd_edpt_xfer(rhport, ep_addr, xact_len ? _ctrl_epbuf.buf : NULL, xact_len, false);
+}
+
+// Status phase
+bool tud_control_status(uint8_t rhport, const tusb_control_request_t* request) {
+ // _usbd_dev.ctrl_xfer fields are pre-initialized at process_setup_received entry
+ (void) request;
+ return status_stage_xact(rhport, status_stage_ep(&_usbd_dev.ctrl_xfer.request));
+}
+
+// Transmit data to/from the control endpoint. If wLength is zero, a status packet is sent instead.
+bool tud_control_xfer(uint8_t rhport, const tusb_control_request_t* request, void* buffer, uint16_t len) {
+ // _usbd_dev.ctrl_xfer.request and reset fields are pre-initialized at process_setup_received entry
+ (void) request;
+ usbd_control_xfer_t* const ctrl_xfer = &_usbd_dev.ctrl_xfer;
+ ctrl_xfer->buffer = (uint8_t*) buffer;
+ ctrl_xfer->data_len = tu_min16(len, ctrl_xfer->request.wLength);
+
+ if (ctrl_xfer->request.wLength > 0U) {
+ if (ctrl_xfer->data_len > 0U) {
+ TU_ASSERT(buffer);
+ }
+ TU_ASSERT(data_stage_xact(rhport));
+ } else {
+ // wLength == 0: Status stage is always IN per USB 2.0 §9.3.1
+ TU_ASSERT(status_stage_xact(rhport, TU_EP0_IN));
+ }
+
+ return true;
+}
+
+// Callback when a transaction completes on the DATA stage or Status stage of EP0
+static bool usbd_control_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
+ (void) result;
+ usbd_control_xfer_t* const ctrl_xfer = &_usbd_dev.ctrl_xfer;
+
+ // Status Stage complete: ep_addr matches the resolved Status stage endpoint
+ uint8_t const ep_status = status_stage_ep(&ctrl_xfer->request);
+ if (ep_addr == ep_status) {
+ TU_ASSERT(0 == xferred_bytes);
+
+ // invoke optional dcd hook if available
+ dcd_edpt0_status_complete(rhport, &ctrl_xfer->request);
+
+ if (NULL != ctrl_xfer->complete_cb) {
+ ctrl_xfer->complete_cb(rhport, CONTROL_STAGE_ACK, &ctrl_xfer->request);
+ }
+
+ return true;
+ }
+
+ // Data stage progress
+ if (ctrl_xfer->request.bmRequestType_bit.direction == TUSB_DIR_OUT) {
+ TU_VERIFY(ctrl_xfer->buffer);
+ // Clamp host overrun to remaining capacity (data_len) so memcpy can't overflow the caller buffer
+ xferred_bytes = tu_min32(xferred_bytes, ctrl_xfer->data_len - ctrl_xfer->total_xferred);
+ if (ctrl_xfer->buffer != _ctrl_epbuf.buf) {
+ memcpy(ctrl_xfer->buffer, _ctrl_epbuf.buf, xferred_bytes);
+ }
+ TU_LOG_MEM(CFG_TUD_LOG_LEVEL, ctrl_xfer->buffer, xferred_bytes, 2);
+ }
+
+ ctrl_xfer->total_xferred += (uint16_t) xferred_bytes;
+ ctrl_xfer->buffer += xferred_bytes;
+
+ // Data Stage complete when wLength reached or short packet (incl. ZLP) seen
+ if ((ctrl_xfer->request.wLength == ctrl_xfer->total_xferred) ||
+ (xferred_bytes < CFG_TUD_ENDPOINT0_BUFSIZE)) {
+ bool is_ok = true;
+
+ if (NULL != ctrl_xfer->complete_cb) {
+ // Callback can still stall control in status phase, e.g. OUT data doesn't make sense
+ is_ok = ctrl_xfer->complete_cb(rhport, CONTROL_STAGE_DATA, &ctrl_xfer->request);
+ }
+
+ if (is_ok) {
+ TU_ASSERT(status_stage_xact(rhport, ep_status));
+ } else {
+ // Stall both IN and OUT control endpoint
+ dcd_edpt_stall(rhport, TU_EP0_OUT);
+ dcd_edpt_stall(rhport, TU_EP0_IN);
+ }
+ } else {
+ // More data to transfer
+ TU_ASSERT(data_stage_xact(rhport));
+ }
+
+ return true;
+}
+
+//--------------------------------------------------------------------+
// Control Request Parser & Handling
//--------------------------------------------------------------------+
// Helper to invoke class driver control request handler
static bool invoke_class_control(uint8_t rhport, usbd_class_driver_t const * driver, tusb_control_request_t const * request) {
- usbd_control_set_complete_callback(driver->control_xfer_cb);
+ _usbd_dev.ctrl_xfer.complete_cb = driver->control_xfer_cb;
TU_LOG_USBD(" %s control request\r\n", driver->name);
return driver->control_xfer_cb(rhport, CONTROL_STAGE_SETUP, request);
}
+// Process a standard request to the device recipient.
+static bool process_std_device_request(uint8_t rhport, tusb_control_request_t const * p_request) {
+ switch (p_request->bRequest) { //-V2520
+ case TUSB_REQ_SET_ADDRESS:
+ // Depending on mcu, status phase could be sent either before or after changing device address,
+ // or even require stack to not response with status at all
+ // Therefore DCD must take full responsibility to response and include zlp status packet if needed.
+ dcd_set_address(rhport, (uint8_t) p_request->wValue);
+ _usbd_dev.addressed = 1;
+ return true;
+
+ case TUSB_REQ_GET_CONFIGURATION: {
+ uint8_t cfg_num = _usbd_dev.cfg_num;
+ tud_control_xfer(rhport, p_request, &cfg_num, 1);
+ return true;
+ }
+
+ case TUSB_REQ_SET_CONFIGURATION: {
+ uint8_t const cfg_num = (uint8_t) p_request->wValue;
+
+ // Only process if new configure is different
+ if (_usbd_dev.cfg_num != cfg_num) {
+ if (_usbd_dev.cfg_num != 0) {
+ // already configured: need to clear all endpoints and driver first
+ TU_LOG_USBD(" Clear current Configuration (%u) before switching\r\n", _usbd_dev.cfg_num);
+
+ dcd_sof_enable(rhport, false);
+ dcd_edpt_close_all(rhport);
+
+ // close all drivers and current configured state except bus speed
+ const uint8_t speed = _usbd_dev.speed;
+ configuration_reset(rhport);
+
+ _usbd_dev.speed = speed; // restore speed
+ }
+
+ _usbd_dev.cfg_num = cfg_num;
+
+ // Handle the new configuration
+ if (cfg_num == 0) {
+ tud_umount_cb();
+ } else {
+ if (!process_set_config(rhport, cfg_num)) {
+ _usbd_dev.cfg_num = 0;
+ TU_ASSERT(false);
+ }
+ tud_mount_cb();
+ }
+ }
+
+ tud_control_status(rhport, p_request);
+ return true;
+ }
+
+ case TUSB_REQ_GET_DESCRIPTOR:
+ return process_get_descriptor(rhport, p_request);
+
+ case TUSB_REQ_SET_FEATURE:
+ switch (p_request->wValue) { //-V2520
+ case TUSB_REQ_FEATURE_REMOTE_WAKEUP:
+ TU_LOG_USBD(" Enable Remote Wakeup\r\n");
+ // Host may enable remote wake up before suspending especially HID device
+ _usbd_dev.remote_wakeup_en = 1;
+ tud_control_status(rhport, p_request);
+ return true;
+
+ #if CFG_TUD_TEST_MODE
+ case TUSB_REQ_FEATURE_TEST_MODE: {
+ // Only handle the test mode if supported and valid
+ TU_VERIFY(0 == tu_u16_low(p_request->wIndex));
+
+ uint8_t const selector = tu_u16_high(p_request->wIndex);
+ TU_VERIFY(TUSB_FEATURE_TEST_J <= selector && selector <= TUSB_FEATURE_TEST_FORCE_ENABLE);
+
+ _usbd_dev.ctrl_xfer.complete_cb = process_test_mode_cb;
+ tud_control_status(rhport, p_request);
+ return true;
+ }
+ #endif
+
+ // Stall unsupported feature selector
+ default: return false;
+ }
+
+ case TUSB_REQ_CLEAR_FEATURE:
+ // Only support remote wakeup for device feature
+ TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
+ TU_LOG_USBD(" Disable Remote Wakeup\r\n");
+
+ // Host may disable remote wake up after resuming
+ _usbd_dev.remote_wakeup_en = 0;
+ tud_control_status(rhport, p_request);
+ return true;
+
+ case TUSB_REQ_GET_STATUS: {
+ // Device status bit mask
+ // - Bit 0: Self Powered TODO must invoke callback to get actual status
+ // - Bit 1: Remote Wakeup enabled
+ uint16_t status = (uint16_t) _usbd_dev.dev_state_bm;
+ tud_control_xfer(rhport, p_request, &status, 2);
+ return true;
+ }
+
+ default:
+ TU_BREAKPOINT();
+ return false;
+ }
+}
+
+
// This handles the actual request and its response.
// Returns false if unable to complete the request, causing caller to stall control endpoints.
-static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) {
- usbd_control_set_complete_callback(NULL);
+static bool process_setup_received(uint8_t rhport, tusb_control_request_t const * p_request) {
+ // Initialize control transfer state for this request. The request copy must be
+ // visible to usbd_control_xfer_cb when the (asynchronous) status ZLP completes,
+ // since the SETUP packet event has already gone out of scope by then.
+ usbd_control_xfer_t* const ctrl_xfer = &_usbd_dev.ctrl_xfer;
+ ctrl_xfer->request = *p_request;
+ ctrl_xfer->buffer = NULL;
+ ctrl_xfer->total_xferred = 0;
+ ctrl_xfer->data_len = 0;
+ ctrl_xfer->complete_cb = NULL;
+
+ p_request = &ctrl_xfer->request; // re-direct request pointer to internal copy (modifiable for hacking)
TU_ASSERT(p_request->bmRequestType_bit.type < TUSB_REQ_TYPE_INVALID);
// Vendor request
if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR ) {
- usbd_control_set_complete_callback(tud_vendor_control_xfer_cb);
+ ctrl_xfer->complete_cb = tud_vendor_control_xfer_cb;
return tud_vendor_control_xfer_cb(rhport, CONTROL_STAGE_SETUP, p_request);
}
@@ -860,115 +1122,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
return false;
}
- switch (p_request->bRequest) { //-V2520
- case TUSB_REQ_SET_ADDRESS:
- // Depending on mcu, status phase could be sent either before or after changing device address,
- // or even require stack to not response with status at all
- // Therefore DCD must take full responsibility to response and include zlp status packet if needed.
- usbd_control_set_request(p_request); // set request since DCD has no access to tud_control_status() API
- dcd_set_address(rhport, (uint8_t) p_request->wValue);
- // skip tud_control_status()
- _usbd_dev.addressed = 1;
- break;
-
- case TUSB_REQ_GET_CONFIGURATION: {
- uint8_t cfg_num = _usbd_dev.cfg_num;
- tud_control_xfer(rhport, p_request, &cfg_num, 1);
- }
- break;
-
- case TUSB_REQ_SET_CONFIGURATION: {
- uint8_t const cfg_num = (uint8_t) p_request->wValue;
-
- // Only process if new configure is different
- if (_usbd_dev.cfg_num != cfg_num) {
- if (_usbd_dev.cfg_num != 0) {
- // already configured: need to clear all endpoints and driver first
- TU_LOG_USBD(" Clear current Configuration (%u) before switching\r\n", _usbd_dev.cfg_num);
-
- dcd_sof_enable(rhport, false);
- dcd_edpt_close_all(rhport);
-
- // close all drivers and current configured state except bus speed
- const uint8_t speed = _usbd_dev.speed;
- configuration_reset(rhport);
-
- _usbd_dev.speed = speed; // restore speed
- }
-
- _usbd_dev.cfg_num = cfg_num;
-
- // Handle the new configuration
- if (cfg_num == 0) {
- tud_umount_cb();
- } else {
- if (!process_set_config(rhport, cfg_num)) {
- _usbd_dev.cfg_num = 0;
- TU_ASSERT(false);
- }
- tud_mount_cb();
- }
- }
-
- tud_control_status(rhport, p_request);
- }
- break;
-
- case TUSB_REQ_GET_DESCRIPTOR:
- TU_VERIFY(process_get_descriptor(rhport, p_request));
- break;
-
- case TUSB_REQ_SET_FEATURE:
- switch(p_request->wValue) { //-V2520
- case TUSB_REQ_FEATURE_REMOTE_WAKEUP:
- TU_LOG_USBD(" Enable Remote Wakeup\r\n");
- // Host may enable remote wake up before suspending especially HID device
- _usbd_dev.remote_wakeup_en = 1;
- tud_control_status(rhport, p_request);
- break;
-
- #if CFG_TUD_TEST_MODE
- case TUSB_REQ_FEATURE_TEST_MODE: {
- // Only handle the test mode if supported and valid
- TU_VERIFY(0 == tu_u16_low(p_request->wIndex));
-
- uint8_t const selector = tu_u16_high(p_request->wIndex);
- TU_VERIFY(TUSB_FEATURE_TEST_J <= selector && selector <= TUSB_FEATURE_TEST_FORCE_ENABLE);
-
- usbd_control_set_complete_callback(process_test_mode_cb);
- tud_control_status(rhport, p_request);
- break;
- }
- #endif
-
- // Stall unsupported feature selector
- default: return false;
- }
- break;
-
- case TUSB_REQ_CLEAR_FEATURE:
- // Only support remote wakeup for device feature
- TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
- TU_LOG_USBD(" Disable Remote Wakeup\r\n");
-
- // Host may disable remote wake up after resuming
- _usbd_dev.remote_wakeup_en = 0;
- tud_control_status(rhport, p_request);
- break;
-
- case TUSB_REQ_GET_STATUS: {
- // Device status bit mask
- // - Bit 0: Self Powered TODO must invoke callback to get actual status
- // - Bit 1: Remote Wakeup enabled
- uint16_t status = (uint16_t)_usbd_dev.dev_state_bm;
- tud_control_xfer(rhport, p_request, &status, 2);
- break;
- }
-
- // Unknown/Unsupported request
- default: TU_BREAKPOINT(); return false;
- }
- break;
+ return process_std_device_request(rhport, p_request);
//------------- Class/Interface Specific Request -------------//
case TUSB_REQ_RCPT_INTERFACE: {
@@ -1004,7 +1158,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
TU_VERIFY(TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type);
// Clear complete callback if driver set since it can also stall the request.
- usbd_control_set_complete_callback(NULL);
+ ctrl_xfer->complete_cb = NULL;
switch (p_request->bRequest) { //-V2520
case TUSB_REQ_GET_INTERFACE: {
@@ -1062,10 +1216,10 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// STD request must always be ACKed regardless of driver returned value
// Also clear complete callback if driver set since it can also stall the request.
(void) invoke_class_control(rhport, driver, p_request);
- usbd_control_set_complete_callback(NULL);
+ ctrl_xfer->complete_cb = NULL;
// skip ZLP status if driver already did that
- if (!_usbd_dev.ep_status[0][TUSB_DIR_IN].busy) {
+ if (!(_usbd_dev.ep_status[0][TUSB_DIR_IN] & TU_EDPT_STATE_BUSY)) {
tud_control_status(rhport, p_request);
}
}
@@ -1144,8 +1298,7 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num) {
}
// return descriptor's buffer and update desc_len
-static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request)
-{
+static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request) {
tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue);
uint8_t const desc_index = tu_u16_low( p_request->wValue );
@@ -1153,20 +1306,18 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
case TUSB_DESC_DEVICE: {
TU_LOG_USBD(" Device\r\n");
- void* desc_device = (void*) (uintptr_t) tud_descriptor_device_cb();
+ void *desc_device = (void *)(uintptr_t)tud_descriptor_device_cb();
TU_ASSERT(desc_device);
// Only response with exactly 1 Packet if: not addressed and host requested more data than device descriptor has.
// This only happens with the very first get device descriptor and EP0 size = 8 or 16.
if ((CFG_TUD_ENDPOINT0_SIZE < sizeof(tusb_desc_device_t)) && !_usbd_dev.addressed &&
- ((tusb_control_request_t const*) p_request)->wLength > sizeof(tusb_desc_device_t)) {
+ p_request->wLength > sizeof(tusb_desc_device_t)) {
// Hack here: we modify the request length to prevent usbd_control response with zlp
// since we are responding with 1 packet & less data than wLength.
- tusb_control_request_t mod_request = *p_request;
- mod_request.wLength = CFG_TUD_ENDPOINT0_SIZE;
-
- return tud_control_xfer(rhport, &mod_request, desc_device, CFG_TUD_ENDPOINT0_SIZE);
- }else {
+ ((tusb_control_request_t *)(uintptr_t)p_request)->wLength = CFG_TUD_ENDPOINT0_SIZE;
+ return tud_control_xfer(rhport, p_request, desc_device, CFG_TUD_ENDPOINT0_SIZE);
+ } else {
return tud_control_xfer(rhport, p_request, desc_device, sizeof(tusb_desc_device_t));
}
}
@@ -1212,7 +1363,7 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
TU_LOG_USBD(" String[%u]\r\n", desc_index);
// String Descriptor always uses the desc set from user
- uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, tu_le16toh(p_request->wIndex));
+ uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, p_request->wIndex);
TU_VERIFY(desc_str);
// first byte of descriptor is its size
@@ -1305,15 +1456,15 @@ TU_ATTR_FAST_FUNC void dcd_event_handler(dcd_event_t const* event, bool in_isr)
usbd_class_driver_t const* driver = get_driver(_usbd_dev.ep2drv[epnum][ep_dir]);
if (driver && driver->xfer_isr) {
- _usbd_dev.ep_status[epnum][ep_dir].busy = 0;
- _usbd_dev.ep_status[epnum][ep_dir].claimed = 0;
+ // Clear busy + claimed
+ _usbd_dev.ep_status[epnum][ep_dir] &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
send = !driver->xfer_isr(event->rhport, ep_addr, (xfer_result_t) event->xfer_complete.result, event->xfer_complete.len);
// xfer_isr() is deferred to xfer_cb(), revert busy/claimed status
if (send) {
- _usbd_dev.ep_status[epnum][ep_dir].busy = 1;
- _usbd_dev.ep_status[epnum][ep_dir].claimed = 1;
+ // set busy + claimed
+ _usbd_dev.ep_status[epnum][ep_dir] |= (TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
}
}
}
@@ -1403,9 +1554,7 @@ bool usbd_edpt_claim(uint8_t rhport, uint8_t ep_addr) {
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- tu_edpt_state_t* ep_state = &_usbd_dev.ep_status[epnum][dir];
-
- return tu_edpt_claim(ep_state, _usbd_mutex);
+ return tu_edpt_claim(&_usbd_dev.ep_status[epnum][dir], _usbd_mutex);
}
bool usbd_edpt_release(uint8_t rhport, uint8_t ep_addr) {
@@ -1413,9 +1562,7 @@ bool usbd_edpt_release(uint8_t rhport, uint8_t ep_addr) {
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- tu_edpt_state_t* ep_state = &_usbd_dev.ep_status[epnum][dir];
-
- return tu_edpt_release(ep_state, _usbd_mutex);
+ return tu_edpt_release(&_usbd_dev.ep_status[epnum][dir], _usbd_mutex);
}
bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t total_bytes, bool is_isr) {
@@ -1435,18 +1582,17 @@ bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t t
#endif
// Attempt to transfer on a busy endpoint, sound like an race condition !
- TU_ASSERT(_usbd_dev.ep_status[epnum][dir].busy == 0);
+ TU_ASSERT((_usbd_dev.ep_status[epnum][dir] & TU_EDPT_STATE_BUSY) == 0);
// Set busy first since the actual transfer can be complete before dcd_edpt_xfer()
// could return and USBD task can preempt and clear the busy
- _usbd_dev.ep_status[epnum][dir].busy = 1;
+ _usbd_dev.ep_status[epnum][dir] |= TU_EDPT_STATE_BUSY;
if (dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes, is_isr)) {
return true;
} else {
// DCD error, mark endpoint as ready to allow next transfer
- _usbd_dev.ep_status[epnum][dir].busy = 0;
- _usbd_dev.ep_status[epnum][dir].claimed = 0;
+ _usbd_dev.ep_status[epnum][dir] &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
TU_LOG_USBD("FAILED\r\n");
TU_BREAKPOINT();
return false;
@@ -1467,19 +1613,18 @@ bool usbd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t* ff, uint16_
TU_LOG_USBD(" Queue FIFO EP %02X with %u bytes ... ", ep_addr, total_bytes);
// Attempt to transfer on a busy endpoint, sound like a race condition !
- TU_ASSERT(_usbd_dev.ep_status[epnum][dir].busy == 0);
+ TU_ASSERT((_usbd_dev.ep_status[epnum][dir] & TU_EDPT_STATE_BUSY) == 0);
// Set busy first since the actual transfer can be complete before dcd_edpt_xfer() could return
// and usbd task can preempt and clear the busy
- _usbd_dev.ep_status[epnum][dir].busy = 1;
+ _usbd_dev.ep_status[epnum][dir] |= TU_EDPT_STATE_BUSY;
if (dcd_edpt_xfer_fifo(rhport, ep_addr, ff, total_bytes, is_isr)) {
TU_LOG_USBD("OK\r\n");
return true;
} else {
// DCD error, mark endpoint as ready to allow next transfer
- _usbd_dev.ep_status[epnum][dir].busy = 0;
- _usbd_dev.ep_status[epnum][dir].claimed = 0;
+ _usbd_dev.ep_status[epnum][dir] &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
TU_LOG_USBD("failed\r\n");
TU_BREAKPOINT();
return false;
@@ -1500,7 +1645,7 @@ bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr) {
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- return _usbd_dev.ep_status[epnum][dir].busy;
+ return (_usbd_dev.ep_status[epnum][dir] & TU_EDPT_STATE_BUSY) != 0;
}
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr) {
@@ -1512,8 +1657,7 @@ void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr) {
// only stalled if currently cleared
TU_LOG_USBD(" Stall EP %02X\r\n", ep_addr);
dcd_edpt_stall(rhport, ep_addr);
- _usbd_dev.ep_status[epnum][dir].stalled = 1;
- _usbd_dev.ep_status[epnum][dir].busy = 1;
+ _usbd_dev.ep_status[epnum][dir] |= (TU_EDPT_STATE_STALLED | TU_EDPT_STATE_BUSY);
}
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) {
@@ -1525,8 +1669,7 @@ void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) {
// only clear if currently stalled
TU_LOG_USBD(" Clear Stall EP %02X\r\n", ep_addr);
dcd_edpt_clear_stall(rhport, ep_addr);
- _usbd_dev.ep_status[epnum][dir].stalled = 0;
- _usbd_dev.ep_status[epnum][dir].busy = 0;
+ _usbd_dev.ep_status[epnum][dir] &= (uint8_t) ~(TU_EDPT_STATE_STALLED | TU_EDPT_STATE_BUSY);
}
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) {
@@ -1535,7 +1678,7 @@ bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) {
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- return _usbd_dev.ep_status[epnum][dir].stalled;
+ return (_usbd_dev.ep_status[epnum][dir] & TU_EDPT_STATE_STALLED) != 0;
}
/**
@@ -1555,9 +1698,7 @@ void usbd_edpt_close(uint8_t rhport, uint8_t ep_addr) {
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_close(rhport, ep_addr);
- _usbd_dev.ep_status[epnum][dir].stalled = 0;
- _usbd_dev.ep_status[epnum][dir].busy = 0;
- _usbd_dev.ep_status[epnum][dir].claimed = 0;
+ _usbd_dev.ep_status[epnum][dir] = 0;
#endif
return;
@@ -1602,9 +1743,7 @@ bool usbd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep)
TU_ASSERT(epnum < CFG_TUD_ENDPPOINT_MAX);
TU_ASSERT(tu_edpt_validate(desc_ep, (tusb_speed_t)_usbd_dev.speed));
- _usbd_dev.ep_status[epnum][dir].stalled = 0;
- _usbd_dev.ep_status[epnum][dir].busy = 0;
- _usbd_dev.ep_status[epnum][dir].claimed = 0;
+ _usbd_dev.ep_status[epnum][dir] = 0;
return dcd_edpt_iso_activate(rhport, desc_ep);
#else
(void) rhport; (void) desc_ep;
diff --git a/src/device/usbd.h b/src/device/usbd.h
index d3a6dccbb..abce5a887 100644
--- a/src/device/usbd.h
+++ b/src/device/usbd.h
@@ -425,6 +425,43 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ
TUD_MIDI_JACKID_OUT_EMB(1)
//--------------------------------------------------------------------+
+// MIDI 2.0 Descriptor Templates (USB-MIDI 2.0)
+//--------------------------------------------------------------------+
+
+// Alt Setting 1: MS Interface + MS Header (bcdMSC=0x0200)
+// Per USB-MIDI 2.0 Table 5-2: wTotalLength in the MS Header is not used in 2.0
+// and shall be set to match bLength (= 0x0007) for conformity with USB-MIDI 1.0.
+#define TUD_MIDI2_DESC_ALT1_HEAD_LEN (9 + 7)
+#define TUD_MIDI2_DESC_ALT1_HEAD(_itfnum, _stridx) \
+ /* MIDI Streaming Interface, Alt Setting 1 */\
+ 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum) + 1), 1, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_FUNC_PROTOCOL_CODE_UNDEF, 0,\
+ /* MS Header (MIDI 2.0): wTotalLength = bLength per spec */\
+ 7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0200), U16_TO_U8S_LE(0x0007)
+
+// Alt Setting 1: Standard USB Endpoint (7 bytes) + CS Endpoint General 2.0
+#define TUD_MIDI2_DESC_ALT1_EP_LEN(_numgtbs) (7 + 4 + (_numgtbs))
+#define TUD_MIDI2_DESC_ALT1_EP(_ep, _epsize, _numgtbs, ...) \
+ 7, TUSB_DESC_ENDPOINT, _ep, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0, \
+ (uint8_t)(4 + (_numgtbs)), TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL_2_0, _numgtbs, ## __VA_ARGS__
+
+// Total length: Alt 0 (MIDI 1.0) + Alt 1 (UMP)
+#define TUD_MIDI2_DESC_LEN (TUD_MIDI_DESC_LEN + TUD_MIDI2_DESC_ALT1_HEAD_LEN + TUD_MIDI2_DESC_ALT1_EP_LEN(1) * 2)
+
+// Complete MIDI 2.0 descriptor with both alternate settings (single cable/GTB)
+#define TUD_MIDI2_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
+ /* Alt Setting 0 (MIDI 1.0) */\
+ TUD_MIDI_DESC_HEAD(_itfnum, _stridx, 1),\
+ TUD_MIDI_DESC_JACK_DESC(1, 0),\
+ TUD_MIDI_DESC_EP(_epout, _epsize, 1),\
+ TUD_MIDI_JACKID_IN_EMB(1),\
+ TUD_MIDI_DESC_EP(_epin, _epsize, 1),\
+ TUD_MIDI_JACKID_OUT_EMB(1),\
+ /* Alt Setting 1 (UMP) */\
+ TUD_MIDI2_DESC_ALT1_HEAD(_itfnum, _stridx),\
+ TUD_MIDI2_DESC_ALT1_EP(_epout, _epsize, 1, 1 /* bAssoGrpTrmBlkID */),\
+ TUD_MIDI2_DESC_ALT1_EP(_epin, _epsize, 1, 1 /* bAssoGrpTrmBlkID */)
+
+//--------------------------------------------------------------------+
// Audio Descriptor Templates
//--------------------------------------------------------------------+
@@ -1026,23 +1063,23 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ
// Length of template descriptor
#define TUD_CDC_NCM_DESC_LEN (8+9+5+5+13+6+7+9+9+7+7)
-// CDC-ECM Descriptor Template
-// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size.
-#define TUD_CDC_NCM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize) \
+// CDC-NCM Descriptor Template
+// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size, EP notification bInterval, capability.
+#define TUD_CDC_NCM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize, _ep_notif_interval, _capability) \
/* Interface Association */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, _desc_stridx,\
- /* CDC-NCM Header */\
+ /* CDC Header */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0110),\
- /* CDC-NCM Union */\
+ /* CDC Union */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\
- /* CDC-NCM Functional Descriptor */\
+ /* CDC Ethernet Networking Descriptor */\
13, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ETHERNET_NETWORKING, _mac_stridx, 0, 0, 0, 0, U16_TO_U8S_LE(_maxsegmentsize), U16_TO_U8S_LE(0), 0, \
/* CDC-NCM Functional Descriptor */\
- 6, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_NCM, U16_TO_U8S_LE(0x0100), 0, \
+ 6, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_NCM, U16_TO_U8S_LE(0x0100), _capability, \
/* Endpoint Notification */\
- 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 50,\
+ 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), _ep_notif_interval,\
/* CDC Data Interface (default inactive) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 0, TUSB_CLASS_CDC_DATA, 0, NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK, 0,\
/* CDC Data Interface (alternative active) */\
diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c
deleted file mode 100644
index 87593d4a7..000000000
--- a/src/device/usbd_control.c
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2019 Ha Thach (tinyusb.org)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * This file is part of the TinyUSB stack.
- */
-
-#include "tusb_option.h"
-
-#if CFG_TUD_ENABLED
-
-#include "dcd.h"
-#include "tusb.h"
-#include "device/usbd_pvt.h"
-
-//--------------------------------------------------------------------+
-// Callback weak stubs (called if application does not provide)
-//--------------------------------------------------------------------+
-TU_ATTR_WEAK void dcd_edpt0_status_complete(uint8_t rhport, const tusb_control_request_t* request) {
- (void) rhport;
- (void) request;
-}
-
-//--------------------------------------------------------------------+
-// MACRO CONSTANT TYPEDEF
-//--------------------------------------------------------------------+
-
-enum {
- EDPT_CTRL_OUT = 0x00,
- EDPT_CTRL_IN = 0x80
-};
-
-typedef struct {
- tusb_control_request_t request;
- uint8_t* buffer;
- uint16_t data_len;
- uint16_t total_xferred;
- usbd_control_xfer_cb_t complete_cb;
-} usbd_control_xfer_t;
-
-static usbd_control_xfer_t _ctrl_xfer;
-
-CFG_TUD_MEM_SECTION static struct {
- TUD_EPBUF_DEF(buf, CFG_TUD_ENDPOINT0_BUFSIZE);
-} _ctrl_epbuf;
-
-uint8_t* usbd_get_ctrl_buf(void) {
- return _ctrl_epbuf.buf;
-}
-
-//--------------------------------------------------------------------+
-// Application API
-//--------------------------------------------------------------------+
-
-// Queue ZLP status transaction
-static inline bool status_stage_xact(uint8_t rhport, const tusb_control_request_t* request) {
- // Opposite to endpoint in Data Phase
- const uint8_t ep_addr = request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN;
- return usbd_edpt_xfer(rhport, ep_addr, NULL, 0, false);
-}
-
-// Status phase
-bool tud_control_status(uint8_t rhport, const tusb_control_request_t* request) {
- _ctrl_xfer.request = (*request);
- _ctrl_xfer.buffer = NULL;
- _ctrl_xfer.total_xferred = 0;
- _ctrl_xfer.data_len = 0;
-
- return status_stage_xact(rhport, request);
-}
-
-// Queue a transaction in Data Stage
-// Each transaction has up to Endpoint0's max packet size.
-// This function can also transfer an zero-length packet
-static bool data_stage_xact(uint8_t rhport) {
- const uint16_t xact_len = tu_min16(_ctrl_xfer.data_len - _ctrl_xfer.total_xferred, CFG_TUD_ENDPOINT0_BUFSIZE);
- uint8_t ep_addr = EDPT_CTRL_OUT;
-
- if (_ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_IN) {
- ep_addr = EDPT_CTRL_IN;
- if (0u != xact_len && _ctrl_xfer.buffer != _ctrl_epbuf.buf) {
- TU_VERIFY(0 == tu_memcpy_s(_ctrl_epbuf.buf, CFG_TUD_ENDPOINT0_BUFSIZE, _ctrl_xfer.buffer, xact_len));
- }
- }
-
- return usbd_edpt_xfer(rhport, ep_addr, xact_len ? _ctrl_epbuf.buf : NULL, xact_len, false);
-}
-
-// Transmit data to/from the control endpoint.
-// If the request's wLength is zero, a status packet is sent instead.
-bool tud_control_xfer(uint8_t rhport, const tusb_control_request_t* request, void* buffer, uint16_t len) {
- _ctrl_xfer.request = (*request);
- _ctrl_xfer.buffer = (uint8_t*) buffer;
- _ctrl_xfer.total_xferred = 0U;
- _ctrl_xfer.data_len = tu_min16(len, request->wLength);
-
- if (request->wLength > 0U) {
- if (_ctrl_xfer.data_len > 0U) {
- TU_ASSERT(buffer);
- }
- TU_ASSERT(data_stage_xact(rhport));
- } else {
- TU_ASSERT(status_stage_xact(rhport, request));
- }
-
- return true;
-}
-
-//--------------------------------------------------------------------+
-// USBD API
-//--------------------------------------------------------------------+
-void usbd_control_reset(void);
-void usbd_control_set_request(const tusb_control_request_t* request);
-void usbd_control_set_complete_callback(usbd_control_xfer_cb_t fp);
-bool usbd_control_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
-
-void usbd_control_reset(void) {
- tu_varclr(&_ctrl_xfer);
-}
-
-// Set complete callback
-void usbd_control_set_complete_callback(usbd_control_xfer_cb_t fp) {
- _ctrl_xfer.complete_cb = fp;
-}
-
-// for dcd_set_address where DCD is responsible for status response
-void usbd_control_set_request(const tusb_control_request_t* request) {
- _ctrl_xfer.request = (*request);
- _ctrl_xfer.buffer = NULL;
- _ctrl_xfer.total_xferred = 0;
- _ctrl_xfer.data_len = 0;
-}
-
-// callback when a transaction complete on
-// - DATA stage of control endpoint or
-// - Status stage
-bool usbd_control_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
- (void) result;
-
- // Endpoint Address is opposite to direction bit, this is Status Stage complete event
- if (tu_edpt_dir(ep_addr) != _ctrl_xfer.request.bmRequestType_bit.direction) {
- TU_ASSERT(0 == xferred_bytes);
-
- // invoke optional dcd hook if available
- dcd_edpt0_status_complete(rhport, &_ctrl_xfer.request);
-
- if (NULL != _ctrl_xfer.complete_cb) {
- // TODO refactor with usbd_driver_print_control_complete_name
- _ctrl_xfer.complete_cb(rhport, CONTROL_STAGE_ACK, &_ctrl_xfer.request);
- }
-
- return true;
- }
-
- if (_ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_OUT) {
- TU_VERIFY(_ctrl_xfer.buffer);
- if (_ctrl_xfer.buffer != _ctrl_epbuf.buf) {
- memcpy(_ctrl_xfer.buffer, _ctrl_epbuf.buf, xferred_bytes);
- }
- TU_LOG_MEM(CFG_TUD_LOG_LEVEL, _ctrl_xfer.buffer, xferred_bytes, 2);
- }
-
- _ctrl_xfer.total_xferred += (uint16_t) xferred_bytes;
- _ctrl_xfer.buffer += xferred_bytes;
-
- // Data Stage is complete when all request's length are transferred or
- // a short packet is sent including zero-length packet.
- if ((_ctrl_xfer.request.wLength == _ctrl_xfer.total_xferred) ||
- (xferred_bytes < CFG_TUD_ENDPOINT0_BUFSIZE)) {
- // DATA stage is complete
- bool is_ok = true;
-
- // invoke complete callback if set
- // callback can still stall control in status phase e.g out data does not make sense
- if (NULL != _ctrl_xfer.complete_cb) {
- #if CFG_TUSB_DEBUG >= CFG_TUD_LOG_LEVEL
- usbd_driver_print_control_complete_name(_ctrl_xfer.complete_cb);
- #endif
-
- is_ok = _ctrl_xfer.complete_cb(rhport, CONTROL_STAGE_DATA, &_ctrl_xfer.request);
- }
-
- if (is_ok) {
- TU_ASSERT(status_stage_xact(rhport, &_ctrl_xfer.request));
- } else {
- // Stall both IN and OUT control endpoint
- dcd_edpt_stall(rhport, EDPT_CTRL_OUT);
- dcd_edpt_stall(rhport, EDPT_CTRL_IN);
- }
- } else {
- // More data to transfer
- TU_ASSERT(data_stage_xact(rhport));
- }
-
- return true;
-}
-
-#endif
diff --git a/src/device/usbd_pvt.h b/src/device/usbd_pvt.h
index 5f11ea481..be778f9af 100644
--- a/src/device/usbd_pvt.h
+++ b/src/device/usbd_pvt.h
@@ -130,10 +130,6 @@ void usbd_sof_enable(uint8_t rhport, sof_consumer_t consumer, bool en);
bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in);
void usbd_defer_func(osal_task_func_t func, void *param, bool in_isr);
-#if CFG_TUSB_DEBUG >= CFG_TUD_LOG_LEVEL
-void usbd_driver_print_control_complete_name(usbd_control_xfer_cb_t callback);
-#endif
-
#ifdef __cplusplus
}
#endif
diff --git a/src/host/usbh.c b/src/host/usbh.c
index 8f80800e9..9d159985e 100644
--- a/src/host/usbh.c
+++ b/src/host/usbh.c
@@ -40,6 +40,14 @@
#define CFG_TUH_TASK_QUEUE_SZ 16
#endif
+#ifndef CFG_TUH_CONTROL_PENDING_QUEUE_SZ
+ #if CFG_TUH_HUB
+ #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 4
+ #else
+ #define CFG_TUH_CONTROL_PENDING_QUEUE_SZ 2
+ #endif
+#endif
+
#ifndef CFG_TUH_INTERFACE_MAX
#define CFG_TUH_INTERFACE_MAX 8
#endif
@@ -140,7 +148,7 @@ typedef struct {
uint8_t itf2drv[CFG_TUH_INTERFACE_MAX]; // map interface number to driver (0xff is invalid)
uint8_t ep2drv[CFG_TUH_ENDPOINT_MAX][2]; // map endpoint to driver ( 0xff is invalid ), can use only 4-bit each
- tu_edpt_state_t ep_status[CFG_TUH_ENDPOINT_MAX][2];
+ volatile uint8_t ep_status[CFG_TUH_ENDPOINT_MAX][2];
#if CFG_TUH_API_EDPT_XFER
// TODO array can be CFG_TUH_ENDPOINT_MAX-1
@@ -175,11 +183,11 @@ static OSAL_SPINLOCK_DEF(_usbh_spin, usbh_int_set);
OSAL_QUEUE_DEF(usbh_int_set, _usbh_qdef, CFG_TUH_TASK_QUEUE_SZ, hcd_event_t);
static osal_queue_t _usbh_q;
- #if CFG_TUH_HUB
+#if CFG_TUH_HUB
// Deferred attachment queue, only needed when using hub
OSAL_QUEUE_DEF(usbh_int_set, _usbh_daqdef, CFG_TUH_HUB, hcd_event_t);
static osal_queue_t _usbh_daq;
- #endif
+#endif
// Control transfers: since most controllers do not support multiple control transfers
// on multiple devices concurrently and control transfers are not used much except for
@@ -189,9 +197,9 @@ typedef struct {
tuh_xfer_cb_t complete_cb;
uintptr_t user_data;
+ volatile uint16_t actual_len;
volatile uint8_t stage;
uint8_t daddr;
- volatile uint16_t actual_len;
uint8_t failed_count;
} usbh_ctrl_xfer_info_t;
@@ -202,17 +210,32 @@ typedef struct {
} usbh_call_after_t;
typedef struct {
- uint8_t controller_id; // controller ID
+ tusb_control_request_t setup;
+ uint8_t* buffer;
+ tuh_xfer_cb_t complete_cb;
+ uintptr_t user_data;
+ uint8_t daddr;
+ uint8_t daddr_gen;
+} usbh_pending_ctrl_t;
+
+// FIFO for pending async control transfers since we only execute 1 control transfer at a time
+TU_FIFO_DEF(_usbh_pending_ctrl_q, CFG_TUH_CONTROL_PENDING_QUEUE_SZ * sizeof(usbh_pending_ctrl_t), false);
+
+typedef struct {
uint8_t enumerating_daddr; // device address of the device being enumerated
uint8_t attach_debouncing_bm; // bitmask for roothub port attach debouncing
tuh_bus_info_t dev0_bus; // bus info for dev0 in enumeration
usbh_ctrl_xfer_info_t ctrl_xfer_info; // control transfer
usbh_call_after_t call_after;
+ // Per-daddr generation counter — bumped on usbh_device_close() to identify stale pending control transfer
+ uint8_t daddr_gen[TOTAL_DEVICES + 1];
+#if CFG_TUSB_OS_HAS_SCHEDULER
+ osal_task_handle_t task_hdl; // host task handle, lazy-captured on first tuh_task_ext()
+#endif
} usbh_data_t;
-static usbh_data_t _usbh_data = {
- .controller_id = TUSB_INDEX_INVALID_8,
-};
+static uint8_t _usbh_controller_id = TUSB_INDEX_INVALID_8;
+static usbh_data_t _usbh_data;
typedef struct {
TUH_EPBUF_TYPE_DEF(tusb_control_request_t, request);
@@ -278,6 +301,18 @@ static usbh_class_driver_t const usbh_class_drivers[] = {
},
#endif
+ #if CFG_TUH_MIDI2
+ {
+ .name = DRIVER_NAME("MIDI2"),
+ .init = midih2_init,
+ .deinit = midih2_deinit,
+ .open = midih2_open,
+ .set_config = midih2_set_config,
+ .xfer_cb = midih2_xfer_cb,
+ .close = midih2_close
+ },
+ #endif
+
#if CFG_TUH_HUB
{
.name = DRIVER_NAME("HUB"),
@@ -334,8 +369,11 @@ static void enum_new_device(hcd_event_t* event);
static void enum_delay_async(uintptr_t state);
static void process_remove_event(hcd_event_t *event);
static void remove_device_tree(uint8_t rhport, uint8_t hub_addr, uint8_t hub_port);
+
static bool usbh_edpt_control_open(uint8_t dev_addr, uint8_t max_packet_size);
static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
+static void control_xfer_dispatch_pending(void);
+static void control_xfer_complete(uint8_t daddr, xfer_result_t result);
TU_ATTR_ALWAYS_INLINE static inline usbh_device_t* get_device(uint8_t dev_addr) {
TU_VERIFY(dev_addr > 0 && dev_addr <= TOTAL_DEVICES, NULL);
@@ -352,7 +390,7 @@ TU_ATTR_ALWAYS_INLINE static inline bool queue_event(hcd_event_t const * event,
return true;
}
-TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage) {
+TU_ATTR_ALWAYS_INLINE static inline void control_xfer_set_stage(uint8_t stage) {
if (_usbh_data.ctrl_xfer_info.stage != stage) {
(void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
_usbh_data.ctrl_xfer_info.stage = stage;
@@ -360,15 +398,6 @@ TU_ATTR_ALWAYS_INLINE static inline void _control_set_xfer_stage(uint8_t stage)
}
}
-TU_ATTR_ALWAYS_INLINE static inline bool usbh_setup_send(uint8_t daddr, const uint8_t setup_packet[8]) {
- const uint8_t rhport = usbh_get_rhport(daddr);
- const bool ret = hcd_setup_send(rhport, daddr, setup_packet);
- if (!ret) {
- _control_set_xfer_stage(CONTROL_STAGE_IDLE);
- }
- return ret;
-}
-
bool usbh_defer_func_ms_async(uint32_t ms, tusb_defer_func_t func, uintptr_t param) {
TU_ASSERT(_usbh_data.call_after.func == NULL);
TU_LOG_USBH("USBH schedule function after %u ms\r\n", (unsigned int)ms);
@@ -382,9 +411,16 @@ bool usbh_defer_func_ms_async(uint32_t ms, tusb_defer_func_t func, uintptr_t par
TU_ATTR_ALWAYS_INLINE static inline void usbh_device_close(uint8_t rhport, uint8_t daddr) {
hcd_device_close(rhport, daddr);
- // abort any ongoing control transfer
- if (daddr == _usbh_data.ctrl_xfer_info.daddr) {
- _control_set_xfer_stage(CONTROL_STAGE_IDLE);
+ // Bump the generation under the mutex so a concurrent producer in
+ // tuh_control_xfer stamps a value that is strictly monotonic w.r.t. close.
+ (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
+ _usbh_data.daddr_gen[daddr]++;
+ (void) osal_mutex_unlock(_usbh_mutex);
+
+ // If this device has in-flight control xfer, complete as FAILED
+ usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
+ if (daddr == ctrl_info->daddr && ctrl_info->stage != CONTROL_STAGE_IDLE) {
+ control_xfer_complete(daddr, XFER_RESULT_FAILED);
}
// invalidate if enumerating
@@ -446,7 +482,7 @@ tusb_speed_t tuh_speed_get(uint8_t daddr) {
}
bool tuh_rhport_is_active(uint8_t rhport) {
- return _usbh_data.controller_id == rhport;
+ return _usbh_controller_id == rhport;
}
bool tuh_rhport_reset_bus(uint8_t rhport, bool active) {
@@ -473,7 +509,7 @@ static void clear_device(usbh_device_t* dev) {
}
bool tuh_inited(void) {
- return _usbh_data.controller_id != TUSB_INDEX_INVALID_8;
+ return _usbh_controller_id != TUSB_INDEX_INVALID_8;
}
bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
@@ -535,7 +571,7 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
tu_memclr(_usbh_devices, sizeof(_usbh_devices));
tu_memclr(&_usbh_data, sizeof(_usbh_data));
- _usbh_data.controller_id = TUSB_INDEX_INVALID_8;
+ _usbh_controller_id = TUSB_INDEX_INVALID_8;
_usbh_data.enumerating_daddr = TUSB_INDEX_INVALID_8;
for (uint8_t i = 0; i < TOTAL_DEVICES; i++) {
@@ -553,7 +589,7 @@ bool tuh_rhport_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
}
// Init host controller
- _usbh_data.controller_id = rhport;
+ _usbh_controller_id = rhport;
TU_ASSERT(hcd_init(rhport, rh_init));
hcd_int_enable(rhport);
@@ -568,7 +604,7 @@ bool tuh_deinit(uint8_t rhport) {
// deinit host controller
hcd_int_disable(rhport);
TU_ASSERT(hcd_deinit(rhport));
- _usbh_data.controller_id = TUSB_INDEX_INVALID_8;
+ _usbh_controller_id = TUSB_INDEX_INVALID_8;
// remove all devices on this rhport (hub_addr = 0, hub_port = 0)
remove_device_tree(rhport, 0, 0);
@@ -592,6 +628,25 @@ bool tuh_deinit(uint8_t rhport) {
_usbh_daq = NULL;
#endif
+ // Fire FAILED cb for any queued async control xfer so callers aren't stranded.
+ usbh_pending_ctrl_t pending;
+ while (tu_fifo_read_n(&_usbh_pending_ctrl_q, &pending, sizeof(pending)) == sizeof(pending)) {
+ if (pending.complete_cb) {
+ tuh_xfer_t x = {
+ .daddr = pending.daddr,
+ .ep_addr = 0,
+ .result = XFER_RESULT_FAILED,
+ .actual_len = 0,
+ .setup = &pending.setup,
+ .buffer = pending.buffer,
+ .complete_cb = pending.complete_cb,
+ .user_data = pending.user_data,
+ };
+ pending.complete_cb(&x);
+ }
+ }
+ tu_fifo_clear(&_usbh_pending_ctrl_q);
+
#if OSAL_MUTEX_REQUIRED
// TODO make sure there is no task waiting on this mutex
osal_mutex_delete(_usbh_mutex);
@@ -617,6 +672,12 @@ bool tuh_task_event_ready(void) {
}
#endif
+ // Pending control xfer waiting for an idle slot
+ if (_usbh_data.ctrl_xfer_info.stage == CONTROL_STAGE_IDLE &&
+ !tu_fifo_empty(&_usbh_pending_ctrl_q)) {
+ return true;
+ }
+
if (_usbh_data.call_after.func) {
int32_t remain_ms = (int32_t)(_usbh_data.call_after.at_ms - tusb_time_millis_api());
if (remain_ms <= 0) {
@@ -651,6 +712,13 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) {
(void) in_isr; // not implemented yet
+#if CFG_TUSB_OS_HAS_SCHEDULER
+ // Save task handle on 1st run
+ if (_usbh_data.task_hdl == NULL) {
+ _usbh_data.task_hdl = osal_task_get_current_handle();
+ }
+#endif
+
// Loop until there are no more events in the queue or CFG_TUH_TASK_EVENTS_PER_RUN is reached
for (unsigned epr = 0;; epr++) {
#if CFG_TUH_TASK_EVENTS_PER_RUN > 0
@@ -683,6 +751,16 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) {
}
}
+ // Drain pending async control xfers. Slot transitions and dispatch are
+ // decoupled: completion / abort / device_close set stage = IDLE via
+ // control_xfer_set_stage() and the actual FIFO drain happens here in the
+ // event loop. The check is a fast non-mutex sanity gate; the dispatcher
+ // itself re-checks under the mutex.
+ if (_usbh_data.ctrl_xfer_info.stage == CONTROL_STAGE_IDLE &&
+ !tu_fifo_empty(&_usbh_pending_ctrl_q)) {
+ control_xfer_dispatch_pending();
+ }
+
hcd_event_t event;
#if CFG_TUH_HUB
@@ -744,8 +822,8 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) {
usbh_device_t* dev = get_device(event.dev_addr);
TU_VERIFY(dev && dev->connected,);
- dev->ep_status[epnum][ep_dir].busy = 0;
- dev->ep_status[epnum][ep_dir].claimed = 0;
+ // clear busy and claimed
+ dev->ep_status[epnum][ep_dir] &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
if (0 == epnum) {
usbh_control_xfer_cb(event.dev_addr, ep_addr, (xfer_result_t) event.xfer_complete.result, event.xfer_complete.len);
@@ -806,73 +884,179 @@ void tuh_task_ext(uint32_t timeout_ms, bool in_isr) {
// Control transfer
//--------------------------------------------------------------------+
-static void _control_blocking_complete_cb(tuh_xfer_t* xfer) {
- // update result
- *((xfer_result_t*) xfer->user_data) = xfer->result;
+// Carries both fields the sync waiter cares about — capturing from xfer_temp
+// (snapshot taken before release_slot resets ctrl_info for the next pending
+// entry) so the waiter sees this xfer's data, not the next dispatched one's.
+typedef struct {
+ volatile xfer_result_t result;
+ volatile uint32_t actual_len;
+} control_xfer_sync_param_t;
+
+static void control_xfer_sync_complete(tuh_xfer_t* xfer) {
+ control_xfer_sync_param_t* s = (control_xfer_sync_param_t*) xfer->user_data;
+ s->actual_len = xfer->actual_len;
+ s->result = xfer->result;
}
// TODO timeout_ms is not supported yet
bool tuh_control_xfer (tuh_xfer_t* xfer) {
- TU_VERIFY(xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet
const uint8_t daddr = xfer->daddr;
- TU_VERIFY(tuh_connected(daddr));
-
+ TU_VERIFY(daddr <= TOTAL_DEVICES && xfer->ep_addr == 0 && xfer->setup); // EP0 with setup packet
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
- TU_VERIFY(ctrl_info->stage == CONTROL_STAGE_IDLE); // pre-check to help reducing mutex lock
- (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
- bool const is_idle = (ctrl_info->stage == CONTROL_STAGE_IDLE);
- if (is_idle) {
- ctrl_info->stage = CONTROL_STAGE_SETUP;
- ctrl_info->daddr = daddr;
- ctrl_info->actual_len = 0;
- ctrl_info->failed_count = 0;
+#if CFG_TUSB_OS_HAS_SCHEDULER
+ // Sync (complete_cb == NULL) from a host-stack callback is forbidden on
+ // RTOS targets — the event-loop driver can't block on its own pending xfer
+ // (deadlock if other control xfers are queued behind). Use async with a
+ // chained cb instead. OS_NONE / OS_PICO are exempt: they have a single
+ // execution context and the recursive-drive path is the only way to wait.
+ TU_ASSERT(!(xfer->complete_cb == NULL &&
+ osal_task_get_current_handle() == _usbh_data.task_hdl));
+#endif
- ctrl_info->buffer = xfer->buffer;
- ctrl_info->complete_cb = xfer->complete_cb;
- ctrl_info->user_data = xfer->user_data;
- _usbh_epbuf.request = (*xfer->setup);
- }
- (void) osal_mutex_unlock(_usbh_mutex);
+ // Slot is single-threaded — when busy, sync callers block until it frees
+ // (blocking semantics require the result); async callers get queued in the
+ // pending FIFO and submitted by control_xfer_complete() when the slot
+ // drains. The test-and-{claim|enqueue} is one critical section so a slot
+ // that becomes IDLE between the check and the enqueue can't strand an async
+ // request in a queue nothing else drains.
+ const bool is_nonblocking = (xfer->complete_cb != NULL);
+ while (true) {
+ TU_VERIFY(tuh_connected(daddr));
+ bool claimed = false;
+ bool is_queued = false;
+ (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
+ if (ctrl_info->stage == CONTROL_STAGE_IDLE) {
+ ctrl_info->stage = CONTROL_STAGE_SETUP;
+ ctrl_info->daddr = daddr;
+ ctrl_info->actual_len = 0;
+ ctrl_info->failed_count = 0;
+
+ ctrl_info->buffer = xfer->buffer;
+ ctrl_info->complete_cb = xfer->complete_cb;
+ ctrl_info->user_data = xfer->user_data;
+ _usbh_epbuf.request = (*xfer->setup);
+ claimed = true;
+ } else if (is_nonblocking) {
+ // Async + busy: queue the transfer.
+ const usbh_pending_ctrl_t entry = {
+ .setup = *xfer->setup,
+ .buffer = xfer->buffer,
+ .complete_cb = xfer->complete_cb,
+ .user_data = xfer->user_data,
+ .daddr = daddr,
+ .daddr_gen = _usbh_data.daddr_gen[daddr]
+ };
+ is_queued = tu_fifo_write_n(&_usbh_pending_ctrl_q, &entry, sizeof(entry)) == sizeof(entry);
+ }
+
+ (void) osal_mutex_unlock(_usbh_mutex);
+
+ if (claimed) {
+ break;
+ }
- TU_VERIFY(is_idle);
+ if (is_nonblocking) {
+ return is_queued;
+ }
+
+ // - OS_HAS_SCHEDULER: delay 1 ms
+ // - Otherwise: single execution context; drive the loop ourselves to progress the in-flight transfer.
+#if CFG_TUSB_OS_HAS_SCHEDULER
+ osal_task_delay(1);
+#else
+ tuh_task_ext(0, false);
+#endif
+ }
TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(daddr), daddr,
(xfer->setup->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer->setup->bRequest <= TUSB_REQ_SYNCH_FRAME) ?
tu_str_std_request[xfer->setup->bRequest] : "Class Request");
TU_LOG_BUF_USBH(xfer->setup, 8);
- if (xfer->complete_cb != NULL) {
- TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request));
- }else {
- // blocking if complete callback is not provided
- // change callback to internal blocking, and result as user argument
- volatile xfer_result_t result = XFER_RESULT_INVALID;
-
- // use user_data to point to xfer_result_t
- ctrl_info->user_data = (uintptr_t) &result;
- ctrl_info->complete_cb = _control_blocking_complete_cb;
+ // Sync: wire control_xfer_sync_complete BEFORE submit so a fast completion
+ // event has the cb in place. control_xfer_complete() captures both result
+ // and actual_len through this cb before release_slot overwrites ctrl_info.
+ volatile control_xfer_sync_param_t sync_state;
+ if (!is_nonblocking) {
+ sync_state.result = XFER_RESULT_INVALID;
+ sync_state.actual_len = 0;
+ ctrl_info->user_data = (uintptr_t) &sync_state;
+ ctrl_info->complete_cb = control_xfer_sync_complete;
+ }
- TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) &_usbh_epbuf.request));
+ if (!hcd_setup_send(usbh_get_rhport(daddr), daddr, (uint8_t const *) &_usbh_epbuf.request)) {
+ control_xfer_set_stage(CONTROL_STAGE_IDLE);
+ return false;
+ }
- while (result == XFER_RESULT_INVALID) {
- // Note: this can be called within an callback ie. part of tuh_task()
- // therefore even with RTOS tuh_task_ext() still need to be invoked
+ if (!is_nonblocking) {
+ // No tuh_connected() escape needed: usbh_device_close() routes through
+ // control_xfer_complete(daddr, FAILED) on disconnect, which fires
+ // sync_complete and unblocks this poll.
+ while (sync_state.result == XFER_RESULT_INVALID) {
+#if CFG_TUSB_OS_HAS_SCHEDULER
+ osal_task_delay(1);
+#else
tuh_task_ext(0, false);
- // TODO probably some timeout to prevent hanged
+#endif
}
- // update transfer result, user_data is expected to point to xfer_result_t
+ // Forward to caller (xfer->user_data, if set, is a xfer_result_t pointer).
if (xfer->user_data != 0) {
- *((xfer_result_t*) xfer->user_data) = result;
+ *((xfer_result_t*) xfer->user_data) = sync_state.result;
}
- xfer->result = result;
- xfer->actual_len = ctrl_info->actual_len;
+ xfer->result = sync_state.result;
+ xfer->actual_len = sync_state.actual_len;
}
return true;
}
-static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) {
+// Start control transfer from pending fifo
+static void control_xfer_dispatch_pending(void) {
+ usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
+
+ while (true) {
+ usbh_pending_ctrl_t xfer;
+ bool has_xfer = false;
+
+ (void) osal_mutex_lock(_usbh_mutex, OSAL_TIMEOUT_WAIT_FOREVER);
+ if (ctrl_info->stage == CONTROL_STAGE_IDLE &&
+ tu_fifo_read_n(&_usbh_pending_ctrl_q, &xfer, sizeof(xfer)) == sizeof(xfer)) {
+ ctrl_info->stage = CONTROL_STAGE_SETUP;
+ ctrl_info->daddr = xfer.daddr;
+ ctrl_info->actual_len = 0;
+ ctrl_info->failed_count = 0;
+ ctrl_info->buffer = xfer.buffer;
+ ctrl_info->complete_cb = xfer.complete_cb;
+ ctrl_info->user_data = xfer.user_data;
+ _usbh_epbuf.request = xfer.setup;
+ has_xfer = true;
+ }
+ (void) osal_mutex_unlock(_usbh_mutex);
+
+ if (!has_xfer) {
+ return; // nothing to do
+ }
+
+ // mismatched daddr_gen means pending transfer is stale due to the device got disconnected while in the FIFO
+ // Note: the address can be re-allocated to another device at this point.
+ if (xfer.daddr_gen == _usbh_data.daddr_gen[xfer.daddr]) {
+ TU_LOG_USBH("[%u:%u] %s: ", usbh_get_rhport(xfer.daddr), xfer.daddr,
+ (xfer.setup.bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && xfer.setup.bRequest <= TUSB_REQ_SYNCH_FRAME) ?
+ tu_str_std_request[xfer.setup.bRequest] : "Class Request");
+ TU_LOG_BUF_USBH(&xfer.setup, 8);
+ if (hcd_setup_send(usbh_get_rhport(xfer.daddr), xfer.daddr, (uint8_t const *) &_usbh_epbuf.request)) {
+ return; // transfer kicked-off, we are done
+ }
+ }
+
+ // complete callback as FAILED and continue with next pending xfer
+ control_xfer_complete(xfer.daddr, XFER_RESULT_FAILED);
+ }
+}
+
+static void control_xfer_complete(uint8_t daddr, xfer_result_t result) {
TU_LOG_USBH("\r\n");
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
@@ -889,7 +1073,8 @@ static void _control_xfer_complete(uint8_t daddr, xfer_result_t result) {
.user_data = ctrl_info->user_data
};
- _control_set_xfer_stage(CONTROL_STAGE_IDLE);
+ // set to IDLE before callback since cb can invoke another transfer
+ control_xfer_set_stage(CONTROL_STAGE_IDLE);
if (xfer_temp.complete_cb != NULL) {
xfer_temp.complete_cb(&xfer_temp);
@@ -903,11 +1088,17 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t
tusb_control_request_t const * request = &_usbh_epbuf.request;
usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
+ // Drop stale completions: slot already released (abort/close fired its cb)
+ // or now owns a different device's xfer (a pending entry was dispatched).
+ if (ctrl_info->stage == CONTROL_STAGE_IDLE || ctrl_info->daddr != daddr) {
+ return true;
+ }
+
switch (result) {
case XFER_RESULT_STALLED:
TU_LOG_USBH("[%u:%u] Control STALLED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes);
TU_LOG_BUF_USBH(request, 8);
- _control_xfer_complete(daddr, result);
+ control_xfer_complete(daddr, result);
break;
case XFER_RESULT_FAILED:
@@ -919,11 +1110,14 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t
ctrl_info->actual_len = 0; // reset actual_len
(void) osal_mutex_unlock(_usbh_mutex);
- TU_ASSERT(usbh_setup_send(daddr, (uint8_t const *) request));
+ if (!hcd_setup_send(rhport, daddr, (uint8_t const *) request)) {
+ control_xfer_complete(daddr, XFER_RESULT_FAILED);
+ return false;
+ }
} else {
TU_LOG_USBH("[%u:%u] Control FAILED, xferred_bytes = %" PRIu32 "\r\n", rhport, daddr, xferred_bytes);
TU_LOG_BUF_USBH(request, 8);
- _control_xfer_complete(daddr, result);
+ control_xfer_complete(daddr, result);
}
break;
@@ -932,7 +1126,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t
case CONTROL_STAGE_SETUP:
if (request->wLength > 0) {
// DATA stage: initial data toggle is always 1
- _control_set_xfer_stage(CONTROL_STAGE_DATA);
+ control_xfer_set_stage(CONTROL_STAGE_DATA);
const uint8_t ep_data = tu_edpt_addr(0, request->bmRequestType_bit.direction);
TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_data, ctrl_info->buffer, request->wLength));
return true;
@@ -947,7 +1141,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t
ctrl_info->actual_len = (uint16_t) xferred_bytes;
// ACK stage: toggle is always 1
- _control_set_xfer_stage(CONTROL_STAGE_ACK);
+ control_xfer_set_stage(CONTROL_STAGE_ACK);
const uint8_t ep_status = tu_edpt_addr(0, 1 - request->bmRequestType_bit.direction);
TU_ASSERT(hcd_edpt_xfer(rhport, daddr, ep_status, NULL, 0));
break;
@@ -964,7 +1158,7 @@ static bool usbh_control_xfer_cb (uint8_t daddr, uint8_t ep_addr, xfer_result_t
}
}
- _control_xfer_complete(daddr, result);
+ control_xfer_complete(daddr, result);
break;
}
@@ -1011,15 +1205,15 @@ bool tuh_edpt_abort_xfer(uint8_t daddr, uint8_t ep_addr) {
const usbh_ctrl_xfer_info_t* ctrl_info = &_usbh_data.ctrl_xfer_info;
TU_VERIFY(daddr == ctrl_info->daddr && ctrl_info->stage != CONTROL_STAGE_IDLE);
hcd_edpt_abort_xfer(rhport, daddr, ep_addr);
- _control_set_xfer_stage(CONTROL_STAGE_IDLE); // reset control transfer state to idle
+ control_xfer_complete(daddr, XFER_RESULT_ABORTED);
} else {
usbh_device_t* dev = get_device(daddr);
TU_VERIFY(dev);
- TU_VERIFY(dev->ep_status[epnum][dir].busy); // non-control skip if not busy
+ TU_VERIFY(dev->ep_status[epnum][dir] & TU_EDPT_STATE_BUSY); // non-control skip if not busy
// abort then mark as ready and release endpoint
hcd_edpt_abort_xfer(dev->bus_info.rhport, daddr, ep_addr);
- dev->ep_status[epnum][dir].busy = false;
+ dev->ep_status[epnum][dir] &= (uint8_t) ~TU_EDPT_STATE_BUSY; // clear busy
tu_edpt_release(&dev->ep_status[epnum][dir], _usbh_mutex);
}
@@ -1043,9 +1237,9 @@ uint8_t *usbh_get_enum_buf(void) {
void usbh_int_set(bool enabled) {
// TODO all host controller if multiple are used since they shared the same event queue
if (enabled) {
- hcd_int_enable(_usbh_data.controller_id);
+ hcd_int_enable(_usbh_controller_id);
} else {
- hcd_int_disable(_usbh_data.controller_id);
+ hcd_int_disable(_usbh_controller_id);
}
}
@@ -1110,16 +1304,16 @@ bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t* bu
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- tu_edpt_state_t* ep_state = &dev->ep_status[epnum][dir];
+ volatile uint8_t* ep_state = &dev->ep_status[epnum][dir];
TU_LOG_USBH(" Queue EP %02X with %u bytes ... \r\n", ep_addr, total_bytes);
// Attempt to transfer on a busy endpoint, sound like an race condition !
- TU_ASSERT(ep_state->busy == 0);
+ TU_ASSERT((*ep_state & TU_EDPT_STATE_BUSY) == 0);
// Set busy first since the actual transfer can be complete before hcd_edpt_xfer()
// could return and USBH task can preempt and clear the busy
- ep_state->busy = 1;
+ *ep_state |= TU_EDPT_STATE_BUSY;
#if CFG_TUH_API_EDPT_XFER
dev->ep_callback[epnum][dir].complete_cb = complete_cb;
@@ -1130,9 +1324,8 @@ bool usbh_edpt_xfer_with_callback(uint8_t dev_addr, uint8_t ep_addr, uint8_t* bu
TU_LOG_USBH("OK\r\n");
return true;
} else {
- // HCD error, mark endpoint as ready to allow next transfer
- ep_state->busy = 0;
- ep_state->claimed = 0;
+ // HCD error, clear busy and claimed to allow next transfer
+ *ep_state &= (uint8_t) ~(TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED);
TU_LOG1("Failed\r\n");
// TU_BREAKPOINT();
return false;
@@ -1178,7 +1371,7 @@ bool usbh_edpt_busy(uint8_t dev_addr, uint8_t ep_addr) {
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
- return dev->ep_status[epnum][dir].busy;
+ return (dev->ep_status[epnum][dir] & TU_EDPT_STATE_BUSY) != 0;
}
//--------------------------------------------------------------------+
diff --git a/src/osal/osal.h b/src/osal/osal.h
index 4840463f3..69cb356d4 100644
--- a/src/osal/osal.h
+++ b/src/osal/osal.h
@@ -76,28 +76,31 @@ typedef void (*osal_task_func_t)(void* param);
/*--------------------------------------------------------------------
OSAL Porting API
Should be implemented as static inline function in osal_port.h header
- uint32_t osal_time_millis(void);
+ uint32_t osal_time_millis(void);
- void osal_spin_init(osal_spinlock_t *ctx);
- void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr)
- void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr);
+ void osal_task_delay(uint32_t msec);
+ osal_task_handle_t osal_task_get_current_handle(void);
- osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef);
- bool osal_semaphore_delete(osal_semaphore_t semd_hdl);
- bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr);
- bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec);
- void osal_semaphore_reset(osal_semaphore_t sem_hdl);
+ void osal_spin_init(osal_spinlock_t *ctx);
+ void osal_spin_lock(osal_spinlock_t *ctx, bool in_isr)
+ void osal_spin_unlock(osal_spinlock_t *ctx, bool in_isr);
- osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef);
- bool osal_mutex_delete(osal_mutex_t mutex_hdl)
- bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec);
- bool osal_mutex_unlock(osal_mutex_t mutex_hdl);
+ osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef);
+ bool osal_semaphore_delete(osal_semaphore_t semd_hdl);
+ bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr);
+ bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec);
+ void osal_semaphore_reset(osal_semaphore_t sem_hdl);
- osal_queue_t osal_queue_create(osal_queue_def_t* qdef);
- bool osal_queue_delete(osal_queue_t qhdl);
- bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec);
- bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr);
- bool osal_queue_empty(osal_queue_t qhdl);
+ osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef);
+ bool osal_mutex_delete(osal_mutex_t mutex_hdl)
+ bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec);
+ bool osal_mutex_unlock(osal_mutex_t mutex_hdl);
+
+ osal_queue_t osal_queue_create(osal_queue_def_t* qdef);
+ bool osal_queue_delete(osal_queue_t qhdl);
+ bool osal_queue_receive(osal_queue_t qhdl, void* data, uint32_t msec);
+ bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr);
+ bool osal_queue_empty(osal_queue_t qhdl);
--------------------------------------------------------------------------*/
diff --git a/src/osal/osal_freertos.h b/src/osal/osal_freertos.h
index 898edd4ed..2f36aa9e8 100644
--- a/src/osal/osal_freertos.h
+++ b/src/osal/osal_freertos.h
@@ -83,6 +83,19 @@ typedef struct {
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef TaskHandle_t osal_task_handle_t;
+
+// Requires INCLUDE_xTaskGetCurrentTaskHandle == 1 in FreeRTOSConfig.h. FreeRTOS
+// also exposes the symbol when configUSE_MUTEXES == 1, so accept either.
+#if !defined(INCLUDE_xTaskGetCurrentTaskHandle) || (INCLUDE_xTaskGetCurrentTaskHandle == 0)
+ #if !defined(configUSE_MUTEXES) || (configUSE_MUTEXES == 0)
+ #error "TinyUSB host stack requires INCLUDE_xTaskGetCurrentTaskHandle or configUSE_MUTEXES to be enabled in FreeRTOSConfig.h"
+ #endif
+#endif
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return xTaskGetCurrentTaskHandle();
+}
+
TU_ATTR_ALWAYS_INLINE static inline uint32_t _osal_ms2tick(uint32_t msec) {
if (msec == OSAL_TIMEOUT_WAIT_FOREVER) { return portMAX_DELAY; }
if (msec == 0) { return 0; }
diff --git a/src/osal/osal_mynewt.h b/src/osal/osal_mynewt.h
index 335d53491..d1fa77ecb 100644
--- a/src/osal/osal_mynewt.h
+++ b/src/osal/osal_mynewt.h
@@ -36,6 +36,12 @@
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef struct os_task* osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return os_sched_get_current_task();
+}
+
TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
os_time_delay( os_time_ms_to_ticks32(msec) );
}
diff --git a/src/osal/osal_none.h b/src/osal/osal_none.h
index 7bf6029d6..e174d3518 100644
--- a/src/osal/osal_none.h
+++ b/src/osal/osal_none.h
@@ -34,6 +34,22 @@ extern "C" {
// osal_time_millis() is not provided, tusb_time_millis_api() must be implemented by user application
//--------------------------------------------------------------------+
+// TASK API
+//--------------------------------------------------------------------+
+// Bare-metal single context: return a non-NULL sentinel so equality compares true.
+typedef void* osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return (osal_task_handle_t) 1;
+}
+
+// Bare-metal has no scheduler to yield to; this is dead code in practice because
+// callers gate it on running outside the host task, which can't happen here.
+TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
+ (void) msec;
+}
+
+//--------------------------------------------------------------------+
// Spinlock API
//--------------------------------------------------------------------+
// Note: This implementation is designed for bare-metal single-core systems without RTOS.
diff --git a/src/osal/osal_pico.h b/src/osal/osal_pico.h
index 6a0a21bb3..364c38b01 100644
--- a/src/osal/osal_pico.h
+++ b/src/osal/osal_pico.h
@@ -39,6 +39,13 @@ extern "C" {
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+// Bare-metal single context: return a non-NULL sentinel so equality compares true.
+typedef void* osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return (osal_task_handle_t) 1;
+}
+
TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
sleep_ms(msec);
}
diff --git a/src/osal/osal_rtthread.h b/src/osal/osal_rtthread.h
index f560281c5..a151a7d70 100644
--- a/src/osal/osal_rtthread.h
+++ b/src/osal/osal_rtthread.h
@@ -38,6 +38,12 @@ extern "C" {
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef rt_thread_t osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return rt_thread_self();
+}
+
TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
rt_thread_mdelay(msec);
}
diff --git a/src/osal/osal_rtx4.h b/src/osal/osal_rtx4.h
index e1930c96c..e5b708a2c 100644
--- a/src/osal/osal_rtx4.h
+++ b/src/osal/osal_rtx4.h
@@ -37,6 +37,12 @@ extern "C" {
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef OS_TID osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return os_tsk_self();
+}
+
TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
uint16_t hi = msec >> 16;
uint16_t lo = msec;
diff --git a/src/osal/osal_threadx.h b/src/osal/osal_threadx.h
index 6bcf9c5ab..cca4eb487 100644
--- a/src/osal/osal_threadx.h
+++ b/src/osal/osal_threadx.h
@@ -37,6 +37,11 @@ extern "C" {
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef TX_THREAD* osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return tx_thread_identify();
+}
TU_ATTR_ALWAYS_INLINE static inline uint32_t _osal_ms2tick(uint32_t msec) {
if ( msec == TX_WAIT_FOREVER ) {
diff --git a/src/osal/osal_zephyr.h b/src/osal/osal_zephyr.h
index 900ac786c..6ea45131e 100644
--- a/src/osal/osal_zephyr.h
+++ b/src/osal/osal_zephyr.h
@@ -31,6 +31,12 @@
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
+typedef k_tid_t osal_task_handle_t;
+
+TU_ATTR_ALWAYS_INLINE static inline osal_task_handle_t osal_task_get_current_handle(void) {
+ return k_current_get();
+}
+
TU_ATTR_ALWAYS_INLINE static inline void osal_task_delay(uint32_t msec) {
k_msleep(msec);
}
diff --git a/src/portable/chipidea/ci_fs/dcd_ci_fs.c b/src/portable/chipidea/ci_fs/dcd_ci_fs.c
index 312a98299..62df1a6d5 100644
--- a/src/portable/chipidea/ci_fs/dcd_ci_fs.c
+++ b/src/portable/chipidea/ci_fs/dcd_ci_fs.c
@@ -360,7 +360,7 @@ static bool edpt_open(uint8_t rhport, uint8_t ep_addr, uint16_t max_packet_size,
unsigned val = USB_ENDPT_EPCTLDIS_MASK;
val |= (xfer != TUSB_XFER_ISOCHRONOUS) ? USB_ENDPT_EPHSHK_MASK : 0;
val |= dir ? USB_ENDPT_EPTXEN_MASK : USB_ENDPT_EPRXEN_MASK;
- CI_REG->EP[epn].CTL |= val;
+ CI_REG->EP[epn].CTL |= (uint8_t)val;
if (xfer != TUSB_XFER_ISOCHRONOUS) {
bd[odd].dts = 1;
@@ -434,11 +434,11 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t
buffer_descriptor_t *next = ep->odd ? bd - 1: bd + 1;
/* When total_bytes is greater than the max packet size,
* it prepares to the next transfer to avoid NAK in advance. */
- next->bc = total_bytes >= 2 * mps ? mps: total_bytes - mps;
+ next->bc = (total_bytes >= 2 * mps) ? mps : (total_bytes - mps);
next->addr = buffer + mps;
next->own = 1;
}
- bd->bc = total_bytes >= mps ? mps: total_bytes;
+ bd->bc = (total_bytes >= mps ? mps : total_bytes);
bd->addr = buffer;
__DSB();
bd->own = 1; /* This bit must be set last */
@@ -506,16 +506,16 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
//--------------------------------------------------------------------+
void dcd_int_handler(uint8_t rhport)
{
- uint32_t is = CI_REG->INT_STAT;
- uint32_t msk = CI_REG->INT_EN;
+ uint8_t is = CI_REG->INT_STAT;
+ uint8_t msk = CI_REG->INT_EN;
// clear non-enabled interrupts
- CI_REG->INT_STAT = is & ~msk;
+ CI_REG->INT_STAT = (uint8_t)(is & ~msk);
is &= msk;
if (is & USB_ISTAT_ERROR_MASK) {
/* TODO: */
- uint32_t es = CI_REG->ERR_STAT;
+ uint8_t es = CI_REG->ERR_STAT;
CI_REG->ERR_STAT = es;
CI_REG->INT_STAT = is; /* discard any pending events */
}
diff --git a/src/portable/dialog/da146xx/dcd_da146xx.c b/src/portable/dialog/da146xx/dcd_da146xx.c
index a283c8362..7d90b1f94 100644
--- a/src/portable/dialog/da146xx/dcd_da146xx.c
+++ b/src/portable/dialog/da146xx/dcd_da146xx.c
@@ -148,8 +148,8 @@ typedef struct
#ifndef TU_DA146XX_DMA_RX_CHANNEL
#define TU_DA146XX_DMA_RX_CHANNEL 6
#endif
-#define DA146XX_DMA_USB_MUX (0x6 << (TU_DA146XX_DMA_RX_CHANNEL * 2))
-#define DA146XX_DMA_USB_MUX_MASK (0xF << (TU_DA146XX_DMA_RX_CHANNEL * 2))
+#define DA146XX_DMA_USB_MUX (0x6u << (TU_DA146XX_DMA_RX_CHANNEL * 2))
+#define DA146XX_DMA_USB_MUX_MASK (0xFu << (TU_DA146XX_DMA_RX_CHANNEL * 2))
typedef struct
{
@@ -311,12 +311,12 @@ static void fill_tx_fifo(xfer_ctl_t * xfer)
// Max packet size is set to value greater then FIFO. Enable fifo level warning
// to handle larger packets.
regs->txc |= (3 << USB_USB_TXC1_REG_USB_TFWL_Pos);
- USB->USB_FWMSK_REG |= 1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_TXWARN31_Pos);
+ USB->USB_FWMSK_REG |= 1u << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_TXWARN31_Pos);
}
else
{
regs->txc &= ~USB_USB_TXC1_REG_USB_TFWL_Msk;
- USB->USB_FWMSK_REG &= ~(1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_TXWARN31_Pos));
+ USB->USB_FWMSK_REG &= ~(1u << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_TXWARN31_Pos));
// Whole packet already in fifo, no need to refill it later. Mark last.
regs->txc |= USB_USB_TXC1_REG_USB_LAST_Msk;
}
@@ -371,14 +371,14 @@ static void start_rx_packet(xfer_ctl_t *xfer)
// For endpoint size greater than FIFO size enable FIFO level warning interrupt
// when FIFO has less than 17 bytes free.
regs->rxc |= USB_USB_RXC1_REG_USB_RFWL_Msk;
- USB->USB_FWMSK_REG |= 1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos);
+ USB->USB_FWMSK_REG |= 1u << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos);
}
}
else if (epnum != 0)
{
// If max_packet_size would fit in FIFO no need for FIFO level warning interrupt.
regs->rxc &= ~USB_USB_RXC1_REG_USB_RFWL_Msk;
- USB->USB_FWMSK_REG &= ~(1 << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos));
+ USB->USB_FWMSK_REG &= ~(1u << (epnum - 1 + USB_USB_FWMSK_REG_USB_M_RXWARN31_Pos));
}
regs->rxc |= USB_USB_RXC1_REG_USB_RX_EN_Msk;
}
@@ -388,7 +388,7 @@ static void start_tx_dma(void *src, volatile void *dst, uint16_t size)
// Setup SRC and DST registers
TX_DMA_REGS->DMAx_A_START_REG = (uint32_t)src;
TX_DMA_REGS->DMAx_B_START_REG = (uint32_t)dst;
- // Interrupt not needed
+ // Interrupt is not needed
TX_DMA_REGS->DMAx_INT_REG = size;
TX_DMA_REGS->DMAx_LEN_REG = size - 1;
TX_DMA_REGS->DMAx_CTRL_REG = TX_DMA_START;
@@ -430,7 +430,9 @@ static uint16_t read_rx_fifo(xfer_ctl_t *xfer, uint16_t bytes_in_fifo)
uint8_t *buf = xfer->buffer + xfer->transferred + xfer->last_packet_size;
- for (int i = 0; i < receive_this_time; ++i) buf[i] = regs->rxd;
+ for (int i = 0; i < receive_this_time; ++i) {
+ buf[i] = (uint8_t)regs->rxd;
+ }
xfer->last_packet_size += receive_this_time;
@@ -449,7 +451,9 @@ static void handle_ep0_rx(void)
{
xfer_ctl_t *xfer_in = XFER_CTL_BASE(0, TUSB_DIR_IN);
// Setup packet is in
- for (int i = 0; i < fifo_bytes; ++i) _setup_packet[i] = USB->USB_RXD0_REG;
+ for (int i = 0; i < fifo_bytes; ++i) {
+ _setup_packet[i] = (uint8_t)USB->USB_RXD0_REG;
+ }
xfer->stall = 0;
xfer->data1 = 1;
@@ -469,7 +473,7 @@ static void handle_ep0_rx(void)
}
else
{
- read_rx_fifo(xfer, fifo_bytes);
+ read_rx_fifo(xfer, (uint16_t)fifo_bytes);
if (rxs0 & USB_USB_RXS0_REG_USB_RX_LAST_Msk)
{
xfer->transferred += xfer->last_packet_size;
@@ -553,7 +557,7 @@ static void handle_epx_rx_ev(uint8_t ep)
{
// Disable DMA and update last_packet_size with what DMA reported.
RX_DMA_REGS->DMAx_CTRL_REG &= ~DMA_DMA0_CTRL_REG_DMA_ON_Msk;
- xfer->last_packet_size = RX_DMA_REGS->DMAx_IDX_REG;
+ xfer->last_packet_size = (uint16_t)RX_DMA_REGS->DMAx_IDX_REG;
// When DMA did not finished (packet was smaller then MPS), DMAx_IDX_REG holds exact number of bytes transmitted.
// When DMA finished value in DMAx_IDX_REG is one less then actual number of transmitted bytes.
if (xfer->last_packet_size == RX_DMA_REGS->DMAx_LEN_REG) xfer->last_packet_size++;
@@ -564,7 +568,7 @@ static void handle_epx_rx_ev(uint8_t ep)
// FIFO maybe empty if DMA read it before or it's final iteration and function already read all that was to read.
if (fifo_bytes > 0)
{
- fifo_bytes = read_rx_fifo(xfer, fifo_bytes);
+ fifo_bytes = read_rx_fifo(xfer, (uint16_t)fifo_bytes);
}
if (GET_BIT(rxs, USB_USB_RXS1_REG_USB_RX_LAST))
{
@@ -624,7 +628,7 @@ static void handle_epx_tx_ev(xfer_ctl_t *xfer)
{
// Disable DMA and update last_packet_size with what DMA reported.
TX_DMA_REGS->DMAx_CTRL_REG &= ~DMA_DMA1_CTRL_REG_DMA_ON_Msk;
- xfer->last_packet_size = TX_DMA_REGS->DMAx_IDX_REG + 1;
+ xfer->last_packet_size = (uint16_t)(TX_DMA_REGS->DMAx_IDX_REG + 1);
// Release DMA to used by other endpoints.
_dcd.dma_ep[TUSB_DIR_IN] = 0;
}
@@ -954,13 +958,13 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
if (dir == TUSB_DIR_OUT)
{
regs->epc_out = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
- USB->USB_RXMSK_REG |= 0x11 << (epnum - 1);
+ USB->USB_RXMSK_REG |= 0x11u << (epnum - 1);
REG_SET_BIT(USB_MAMSK_REG, USB_M_RX_EV);
}
else
{
regs->epc_in = epnum | USB_USB_EPC1_REG_USB_EP_EN_Msk | iso_mask;
- USB->USB_TXMSK_REG |= 0x11 << (epnum - 1);
+ USB->USB_TXMSK_REG |= 0x11u << (epnum - 1);
REG_SET_BIT(USB_MAMSK_REG, USB_M_TX_EV);
}
}
@@ -974,8 +978,8 @@ void dcd_edpt_close_all (uint8_t rhport)
for (int epnum = 1; epnum < EP_MAX; ++epnum)
{
- dcd_edpt_close(0, epnum | TUSB_DIR_OUT);
- dcd_edpt_close(0, epnum | TUSB_DIR_IN);
+ dcd_edpt_close(0, (uint8_t)(epnum | TUSB_DIR_OUT));
+ dcd_edpt_close(0, (uint8_t)(epnum | TUSB_DIR_IN));
}
}
@@ -1001,7 +1005,7 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
regs->rxc = USB_USB_RXC1_REG_USB_FLUSH_Msk;
regs->epc_out = 0;
- USB->USB_RXMSK_REG &= ~(0x11 << (epnum - 1));
+ USB->USB_RXMSK_REG &= ~(0x11u << (epnum - 1));
// Release DMA if needed
if (_dcd.dma_ep[TUSB_DIR_OUT] == epnum)
{
@@ -1013,7 +1017,7 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
regs->txc = USB_USB_TXC1_REG_USB_FLUSH_Msk;
regs->epc_in = 0;
- USB->USB_TXMSK_REG &= ~(0x11 << (epnum - 1));
+ USB->USB_TXMSK_REG &= ~(0x11u << (epnum - 1));
// Release DMA if needed
if (_dcd.dma_ep[TUSB_DIR_IN] == epnum)
{
diff --git a/src/portable/mentor/musb/dcd_musb.c b/src/portable/mentor/musb/dcd_musb.c
index 64f9ebacf..1d1280bf4 100644
--- a/src/portable/mentor/musb/dcd_musb.c
+++ b/src/portable/mentor/musb/dcd_musb.c
@@ -50,36 +50,133 @@
* MACRO TYPEDEF CONSTANT ENUM DECLARATION
*------------------------------------------------------------------*/
-#define REQUEST_TYPE_INVALID (0xFFu)
-
typedef union {
volatile uint8_t u8;
volatile uint16_t u16;
volatile uint32_t u32;
} hw_fifo_t;
-typedef struct TU_ATTR_PACKED
-{
- void *buf; /* the start address of a transfer data buffer */
+typedef struct {
+ union {
+ uint8_t *buf; /* the start address of a transfer data buffer */
+ tu_fifo_t *fifo;
+ };
uint16_t length; /* the number of bytes in the buffer */
uint16_t remaining; /* the number of bytes remaining in the buffer */
+ bool armed; /* true while a transfer is posted */
+ bool use_fifo; /* true: buf is tu_fifo_t*; false: buf is plain byte pointer. */
} pipe_state_t;
-typedef struct
-{
- union {
- tusb_control_request_t setup_packet;
- uint32_t setup_buffer[2];
- };
- uint16_t remaining_ctrl; /* The number of bytes remaining in data stage of control transfer. */
- int8_t status_out;
- pipe_state_t pipe0;
- pipe_state_t pipe[2][TUP_DCD_ENDPOINT_MAX-1]; /* pipe[direction][endpoint number - 1] */
- uint16_t pipe_buf_is_fifo[2]; /* Bitmap. Each bit means whether 1:TU_FIFO or 0:POD. */
+// Pipe array layout (N = TUP_DCD_ENDPOINT_MAX). EP0 has its own scalars in
+// dcd_data_t and does not occupy a pipe slot.
+// One-direction-only IPs (CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY=1):
+// [0..N-2] : EP1..N-1 (single slot per endpoint)
+// Bidirectional-capable IPs:
+// [0..N-2 ] : EP1..N-1 OUT
+// [N-1..2*N-3 ] : EP1..N-1 IN
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ #define MUSB_PIPE_COUNT (TUP_DCD_ENDPOINT_MAX - 1u)
+#else
+ #define MUSB_PIPE_COUNT (2u * (TUP_DCD_ENDPOINT_MAX - 1u))
+#endif
+
+enum {
+ PIPE0_STATE_IDLE = 0, // no active control transfer
+ PIPE0_STATE_DATA_IN, // DATA IN stage
+ PIPE0_STATE_DATA_OUT, // DATA OUT stage
+ PIPE0_STATE_STATUS_IN, // STATUS IN — device sends IN-ZLP; awaits send-ACK IRQ
+ PIPE0_STATE_STATUS_OUT, // post-DATAEND, neither edpt0_xfer(STATUS OUT) nor confirmation IRQ has happened yet
+ PIPE0_STATE_STATUS_OUT_PENDING_XFER, // edpt0_xfer(STATUS OUT) called first; the confirmation IRQ fires xfer_complete
+ PIPE0_STATE_STATUS_OUT_PENDING_IRQ, // confirmation IRQ seen (or synthesized) first; edpt0_xfer(STATUS OUT) fires xfer_complete
+};
+
+// EP0 control-transfer state (own scalars, not a pipe[] slot).
+typedef struct {
+ uint8_t *buf; // DATA OUT drain target (only valid while EP0 is in DATA OUT stage)
+ uint16_t xact_len; // DATA IN chunk length armed via edpt0_xfer; reported in its xfer_complete (OUT reports count0)
+ uint16_t remain_wlength; // bytes remaining in the control transfer's DATA stage
+ uint8_t state;
+ uint8_t pending_addr; // new USB address latched by dcd_set_address; applied when STATUS IN completes
+ bool rxrdy_consumed; // RxPktRdy left set in hw for an already-consumed packet (NAK flow control);
+ // RXRDY events are stale while set. Cleared when RXRDYC is written.
+ bool deferred_setup_valid;
+ uint32_t deferred_setup[2]; // raw SETUP words, replayed via pipe0_start_setup
+} pipe0_state_t;
+
+typedef struct {
+ pipe0_state_t pipe0;
+ pipe_state_t pipe[MUSB_PIPE_COUNT];
} dcd_data_t;
static dcd_data_t _dcd;
+// Read the 8-byte SETUP packet (2 words) from the EP0 FIFO into setup[]. Does not ack RxPktRdy.
+static bool pipe0_read_setup(musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr, uint32_t setup[2]) {
+ TU_ASSERT(sizeof(tusb_control_request_t) == ep_csr->count0);
+ setup[0] = musb_regs->fifo[0];
+ setup[1] = musb_regs->fifo[0];
+ return true;
+}
+
+static void pipe0_start_setup(uint8_t rhport, musb_ep_csr_t* ep_csr,
+ const uint32_t setup[2], bool is_isr) {
+ tusb_control_request_t const* req = (tusb_control_request_t const*) setup;
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ pipe0->remain_wlength = req->wLength;
+
+ if (req->wLength == 0) {
+ // Leave RXRDY set; edpt0_xfer(STATUS IN) acks it together with DATAEND.
+ pipe0->state = PIPE0_STATE_STATUS_IN;
+ pipe0->rxrdy_consumed = true;
+ } else {
+ if (req->bmRequestType & TUSB_DIR_IN_MASK) {
+ pipe0->state = PIPE0_STATE_DATA_IN;
+ // On a deferred replay the packet's RXRDY stays parked until the edpt0_xfer(DATA IN) arm
+ // acks it — a stale latched EP0 IRQ in between is gated by rxrdy_consumed.
+ if (!pipe0->rxrdy_consumed) {
+ ep_csr->csr0l = MUSB_CSRL0_RXRDYC;
+ }
+ } else {
+ // If OUT (rx) direction, let edpt0_xfer() clear RXRDY when it's ready to receive data.
+ // Deliberate deviation from the databook's canonical flow (ack right after unload),
+ // used as NAK flow control until usbd arms the drain buffer.
+ pipe0->state = PIPE0_STATE_DATA_OUT;
+ pipe0->rxrdy_consumed = true;
+ }
+ }
+
+ dcd_event_setup_received(rhport, (const uint8_t *) setup, is_isr);
+}
+
+// Replay a previously deferred SETUP, if any.
+static void pipe0_try_deferred_setup(uint8_t rhport, musb_ep_csr_t* ep_csr, bool is_isr) {
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ if (!pipe0->deferred_setup_valid) {
+ return;
+ }
+
+ pipe0->deferred_setup_valid = false;
+ pipe0_start_setup(rhport, ep_csr, pipe0->deferred_setup, is_isr);
+}
+
+// Last DATA packet: wLength satisfied, or a short packet (incl. ZLP) ends the stage.
+TU_ATTR_ALWAYS_INLINE static inline bool pipe0_data_stage_done(uint16_t xfer_len) {
+ return _dcd.pipe0.remain_wlength == 0 || xfer_len < CFG_TUD_ENDPOINT0_SIZE;
+}
+
+// EP0 must not call this — it has its own scalars in dcd_data_t.
+TU_ATTR_ALWAYS_INLINE static inline pipe_state_t* pipe_get(uint8_t epnum, tusb_dir_t epdir) {
+ size_t idx = epnum - 1u;
+#if CFG_TUD_ENDPOINT_ONE_DIRECTION_ONLY
+ (void) epdir;
+#else
+ if (epdir == TUSB_DIR_IN) {
+ idx += TUP_DCD_ENDPOINT_MAX - 1u;
+ }
+#endif
+ return &_dcd.pipe[idx];
+}
+
//--------------------------------------------------------------------
// HW FIFO Helper
// Note: Index register is already set by caller
@@ -110,7 +207,6 @@ TU_ATTR_ALWAYS_INLINE static inline void hwfifo_reset(musb_regs_t* musb, unsigne
TU_ATTR_ALWAYS_INLINE static inline bool hwfifo_config(musb_regs_t* musb, unsigned epnum, unsigned is_rx, unsigned mps,
bool double_packet) {
- (void) epnum;
uint8_t ffsize = hwfifo_byte2size(mps);
mps = 8 << ffsize; // round up to the next power of 2
@@ -123,6 +219,13 @@ TU_ATTR_ALWAYS_INLINE static inline bool hwfifo_config(musb_regs_t* musb, unsign
musb->fifo_addr[is_rx] = alloced_fifo_bytes / 8;
musb->fifo_size[is_rx] = ffsize;
+ volatile uint16_t* dp_disable = is_rx ? &musb->rx_doulbe_packet_disable : &musb->tx_double_packet_disable;
+ if (double_packet) {
+ *dp_disable &= ~(1u << epnum);
+ } else {
+ *dp_disable |= (1u << epnum);
+ }
+
alloced_fifo_bytes += mps;
return true;
}
@@ -136,18 +239,29 @@ TU_ATTR_ALWAYS_INLINE static inline void hwfifo_reset(musb_regs_t* musb, unsigne
TU_ATTR_ALWAYS_INLINE static inline bool hwfifo_config(musb_regs_t* musb, unsigned epnum, unsigned is_rx, unsigned mps,
bool double_packet) {
- (void) epnum; (void) mps;
- if (!double_packet) {
- #if defined(TUP_USBIP_MUSB_ADI)
- musb->indexed_csr.maxp_csr[is_rx].csrh |= MUSB_CSRH_DISABLE_DOUBLE_PACKET(is_rx);
- #else
- if (is_rx) {
- musb->rx_doulbe_packet_disable |= 1u << epnum;
- } else {
- musb->tx_double_packet_disable |= 1u << epnum;
- }
- #endif
+ (void) mps;
+
+ #if defined(TUP_USBIP_MUSB_ADI)
+ // AnalogDevice FIFO sizes: EP1..7 = 512 B, EP8..9 = 2048 B, EP10..11 = 4096 B.
+ // DPB requires FIFO >= 2 * MPS. For HS bulk (MPS=512) only EP >= 8 qualifies.
+ // Force single-buffered on EP < 8 even if the caller requested DPB.
+ if (epnum < 8 && (musb->power & MUSB_POWER_HSMODE)) {
+ double_packet = false;
+ }
+ volatile uint8_t* csrh = &musb->indexed_csr.maxp_csr[is_rx].csrh;
+ if (double_packet) {
+ *csrh &= ~MUSB_CSRH_DISABLE_DOUBLE_PACKET;
+ } else {
+ *csrh |= MUSB_CSRH_DISABLE_DOUBLE_PACKET;
}
+ #else
+ volatile uint16_t* dp_disable = is_rx ? &musb->rx_doulbe_packet_disable : &musb->tx_double_packet_disable;
+ if (double_packet) {
+ *dp_disable &= ~(1u << epnum);
+ } else {
+ *dp_disable |= (1u << epnum);
+ }
+ #endif
return true;
}
@@ -167,322 +281,359 @@ TU_ATTR_ALWAYS_INLINE static inline void hwfifo_flush(musb_regs_t* musb, unsigne
}
}
-static void process_setup_packet(uint8_t rhport) {
- musb_regs_t* musb_regs = MUSB_REGS(rhport);
-
- // Read setup packet
- _dcd.setup_buffer[0] = musb_regs->fifo[0];
- _dcd.setup_buffer[1] = musb_regs->fifo[0];
-
- _dcd.pipe0.buf = NULL;
- _dcd.pipe0.length = 0;
- _dcd.pipe0.remaining = 0;
- dcd_event_setup_received(rhport, (const uint8_t*)(uintptr_t)&_dcd.setup_packet, true);
-
- const unsigned len = _dcd.setup_packet.wLength;
- _dcd.remaining_ctrl = len;
- const unsigned dir_in = tu_edpt_dir(_dcd.setup_packet.bmRequestType);
- /* Clear RX FIFO and reverse the transaction direction */
- if (len && dir_in) {
- musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0);
- ep_csr->csr0l = MUSB_CSRL0_RXRDYC;
+// write to txfifo using pipe_state_t info
+static void pipe_write(musb_regs_t* musb_regs, pipe_state_t* pipe, uint8_t epnum) {
+ musb_ep_csr_t* ep_csr = &musb_regs->indexed_csr;
+ const uint16_t mps = ep_csr->tx_maxp & MUSB_TXMAXP_PACKET_SIZE_M;
+ const uint16_t xact_len = tu_min16(mps, pipe->remaining);
+ volatile void *hwfifo = &musb_regs->fifo[epnum];
+ if (xact_len) {
+ if (pipe->use_fifo) {
+ tu_hwfifo_write_from_fifo(hwfifo, pipe->fifo, xact_len, NULL);
+ } else {
+ tu_hwfifo_write(hwfifo, pipe->buf, xact_len, NULL);
+ pipe->buf += xact_len;
+ }
+ pipe->remaining -= xact_len;
}
+ ep_csr->tx_csrl = MUSB_TXCSRL1_TXRDY;
}
-static bool handle_xfer_in(uint8_t rhport, uint_fast8_t ep_addr) {
- unsigned epnum = tu_edpt_number(ep_addr);
- unsigned epnum_minus1 = epnum - 1;
- pipe_state_t *pipe = &_dcd.pipe[tu_edpt_dir(ep_addr)][epnum_minus1];
- const unsigned rem = pipe->remaining;
+// Called from the TX interrupt. If the last queued packet finished the transfer,
+// signal completion; otherwise queue the next packet.
+static void process_epin_isr(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum) {
+ musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum);
+ const uint_fast8_t csrl = ep_csr->tx_csrl;
+ if (csrl & MUSB_TXCSRL1_STALLED) {
+ ep_csr->tx_csrl &= ~(MUSB_TXCSRL1_STALLED | MUSB_TXCSRL1_UNDRN);
+ return; // sent STALL, do nothing
+ }
- if (rem == 0 && pipe->length > 0) {
+ pipe_state_t* pipe = pipe_get(epnum, TUSB_DIR_IN);
+ if (pipe->remaining > 0) {
+ pipe_write(musb_regs, pipe, epnum);
+ } else {
+ // All bytes have been loaded into the FIFO. With double-packet buffering a
+ // second packet may still be waiting in the FIFO when this IRQ fires (the
+ // hardware signals TXRDY clear as soon as a slot frees, not when the wire
+ // transfer finishes). Defer completion until FIFONE == 0 so we don't emit
+ // a duplicate xfer_complete before the final packet has been sent.
+ if (csrl & MUSB_TXCSRL1_FIFONE) {
+ return;
+ }
+ const uint16_t xferred_len = pipe->length;
pipe->buf = NULL;
- return true;
+ pipe->armed = false;
+ dcd_event_xfer_complete(rhport, tu_edpt_addr(epnum, TUSB_DIR_IN), xferred_len, XFER_RESULT_SUCCESS, true);
}
+}
- musb_regs_t* musb_regs = MUSB_REGS(rhport);
- musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum);
- const unsigned mps = ep_csr->tx_maxp;
- const unsigned len = TU_MIN(mps, rem);
- void *buf = pipe->buf;
- volatile void *fifo_ptr = &musb_regs->fifo[epnum];
- // TU_LOG1(" %p mps %d len %d rem %d\r\n", buf, mps, len, rem);
- if (len) {
- if (_dcd.pipe_buf_is_fifo[TUSB_DIR_IN] & TU_BIT(epnum_minus1)) {
- tu_hwfifo_write_from_fifo(fifo_ptr, (tu_fifo_t *)buf, len, NULL);
+// Drain one packet from the Rx FIFO into pipe->buf/fifo, update pipe state, and
+// release the FIFO slot by clearing RXRDY. return true if short packet
+static bool pipe_read(musb_regs_t* musb_regs, pipe_state_t* pipe, uint8_t epnum) {
+ musb_ep_csr_t* ep_csr = &musb_regs->indexed_csr; // index already set in process_epout_isr()
+ const uint16_t mps = ep_csr->rx_maxp & MUSB_RXMAXP_PACKET_SIZE_M;
+ const uint16_t rx_count = ep_csr->rx_count;
+ const uint16_t xact_len = tu_min16(tu_min16(pipe->remaining, mps), rx_count);
+ volatile void *hwfifo = &musb_regs->fifo[epnum];
+ if (xact_len) {
+ if (pipe->use_fifo) {
+ tu_hwfifo_read_to_fifo(hwfifo, pipe->fifo, xact_len, NULL);
} else {
- tu_hwfifo_write(fifo_ptr, buf, len, NULL);
- pipe->buf = (uint8_t*)buf + len;
+ tu_hwfifo_read(hwfifo, pipe->buf, xact_len, NULL);
+ pipe->buf += xact_len;
}
- pipe->remaining = rem - len;
+ pipe->remaining -= xact_len;
}
- ep_csr->tx_csrl = MUSB_TXCSRL1_TXRDY;
- // TU_LOG1(" TXCSRL%d = %x %d\r\n", epnum, ep_csr->tx_csrl, rem - len);
- return false;
+ ep_csr->rx_csrl = 0; /* Clear RXRDY - release this FIFO slot */
+
+ return (xact_len < mps);
}
-static bool handle_xfer_out(uint8_t rhport, uint_fast8_t ep_addr)
-{
- unsigned epnum = tu_edpt_number(ep_addr);
- unsigned epnum_minus1 = epnum - 1;
- pipe_state_t *pipe = &_dcd.pipe[tu_edpt_dir(ep_addr)][epnum_minus1];
- musb_regs_t* musb_regs = MUSB_REGS(rhport);
+static void process_epout_isr(uint8_t rhport, musb_regs_t *musb_regs, uint8_t epnum, bool is_isr) {
musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum);
- // TU_LOG1(" RXCSRL%d = %x\r\n", epnum_minus1 + 1, ep_csr->rx_csrl);
-
- //Fail gracefully. Spurious interrupt.
- if (!(ep_csr->rx_csrl & MUSB_RXCSRL1_RXRDY)) return false;
+ if (ep_csr->rx_csrl & MUSB_RXCSRL1_STALLED) {
+ ep_csr->rx_csrl &= ~(MUSB_RXCSRL1_STALLED | MUSB_RXCSRL1_OVER);
+ return; // sent STALL, do nothing
+ }
- void *buf = pipe->buf;
- if (buf == NULL) {
- ep_csr->rx_csrl = MUSB_RXCSRL1_FLUSH;
- return false;
+ // Fail gracefully. Spurious interrupt.
+ if (!(ep_csr->rx_csrl & MUSB_RXCSRL1_RXRDY)) {
+ return;
}
- const unsigned mps = ep_csr->rx_maxp;
- const unsigned rem = pipe->remaining;
- const unsigned vld = ep_csr->rx_count;
- const unsigned len = TU_MIN(TU_MIN(rem, mps), vld);
- volatile void *fifo_ptr = &musb_regs->fifo[epnum];
- if (len) {
- if (_dcd.pipe_buf_is_fifo[TUSB_DIR_OUT] & TU_BIT(epnum_minus1)) {
- tu_hwfifo_read_to_fifo(fifo_ptr, (tu_fifo_t *)buf, len, NULL);
- } else {
- tu_hwfifo_read(fifo_ptr, buf, len, NULL);
- pipe->buf = (uint8_t*)buf + len;
- }
- pipe->remaining = rem - len;
+ pipe_state_t *pipe = pipe_get(epnum, TUSB_DIR_OUT);
+ if (!pipe->armed) {
+ // Packet is already ACK'd by hardware and sitting in the Rx FIFO, but no transfer is
+ // posted. Do NOT flush (per MUSB spec §3.3.11 FlushFIFO) - that would silently drop
+ // acknowledged data. Mask this endpoint's Rx interrupt so the ISR stops re-firing;
+ // the FIFO stays occupied so hardware NAKs further OUT tokens (natural backpressure).
+ // The next dcd_edpt_xfer() on this endpoint will drain the staged packet.
+ musb_regs->intr_rxen &= (uint16_t) ~TU_BIT(epnum);
+ return;
}
- ep_csr->rx_csrl = 0; /* Always Clear RXRDY bit */
- if ((len < mps) || (rem == len)) {
+ const bool is_short = pipe_read(musb_regs, pipe, epnum);
+
+ // Transfer completes on a short packet or when the rx buffer is filled.
+ if (is_short || pipe->remaining == 0) {
+ const uint16_t xferred_len = pipe->length - pipe->remaining;
pipe->buf = NULL;
- return NULL != buf;
+ pipe->armed = false;
+ dcd_event_xfer_complete(rhport, epnum, xferred_len, XFER_RESULT_SUCCESS, is_isr);
}
- return false;
}
-static bool edpt_n_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
-{
- unsigned epnum = tu_edpt_number(ep_addr);
- unsigned epnum_minus1 = epnum - 1;
- unsigned dir_in = tu_edpt_dir(ep_addr);
+static bool edpt_n_xfer(uint8_t rhport, uint8_t ep_addr, void *buffer, uint16_t total_bytes, bool use_fifo, bool is_isr) {
+ const uint8_t epnum = tu_edpt_number(ep_addr);
+ const tusb_dir_t dir_in = tu_edpt_dir(ep_addr);
+
+ pipe_state_t *pipe = pipe_get(epnum, dir_in);
+ if (use_fifo) {
+ pipe->fifo = (tu_fifo_t *)buffer;
+ } else {
+ pipe->buf = (uint8_t *)buffer;
+ }
+ pipe->length = total_bytes;
+ pipe->remaining = total_bytes;
+ pipe->use_fifo = use_fifo;
+ pipe->armed = true;
- pipe_state_t *pipe = &_dcd.pipe[dir_in][epnum_minus1];
- pipe->buf = buffer;
- pipe->length = total_bytes;
- pipe->remaining = total_bytes;
+ musb_regs_t *musb_regs = MUSB_REGS(rhport);
+ musb_ep_csr_t *ep_csr = get_ep_csr(musb_regs, epnum);
if (dir_in) {
- handle_xfer_in(rhport, ep_addr);
+ pipe_write(musb_regs, pipe, epnum);
} else {
- musb_regs_t* musb_regs = MUSB_REGS(rhport);
- musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epnum);
- if (ep_csr->rx_csrl & MUSB_RXCSRL1_RXRDY) ep_csr->rx_csrl = 0;
+ // Re-enable Rx interrupt (may have been masked by the no-buffer path in process_epout_isr)
+ musb_regs->intr_rxen |= (uint16_t)TU_BIT(epnum);
+
+ // Drain any packet staged in the Rx FIFO from a prior no-buffer interrupt.
+ // process_epout_isr() fires dcd_event_xfer_complete() itself if the drain completes.
+ if (ep_csr->rx_csrl & MUSB_RXCSRL1_RXRDY) {
+ process_epout_isr(rhport, musb_regs, epnum, is_isr);
+ }
}
return true;
}
-static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes)
-{
- (void)rhport;
- TU_ASSERT(total_bytes <= 64); /* Current implementation supports for only up to 64 bytes. */
+static bool edpt0_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes, bool is_isr) {
+ TU_ASSERT(total_bytes <= CFG_TUD_ENDPOINT0_SIZE); /* EP0 only supports 1 packet per dcd_edpt_xfer()*/
musb_regs_t* musb_regs = MUSB_REGS(rhport);
musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0);
- const unsigned req = _dcd.setup_packet.bmRequestType;
- TU_ASSERT(req != REQUEST_TYPE_INVALID || total_bytes == 0);
-
- if (req == REQUEST_TYPE_INVALID || _dcd.status_out) {
- /* STATUS OUT stage.
- * MUSB controller automatically handles STATUS OUT packets without
- * software helps. We do not have to do anything. And STATUS stage
- * may have already finished and received the next setup packet
- * without calling this function, so we have no choice but to
- * invoke the callback function of status packet here. */
- // TU_LOG1(" STATUS OUT ep_csr->csr0l = %x\r\n", ep_csr->csr0l);
- _dcd.status_out = 0;
- if (req == REQUEST_TYPE_INVALID) {
- dcd_event_xfer_complete(rhport, ep_addr, total_bytes, XFER_RESULT_SUCCESS, false);
- } else {
- /* The next setup packet has already been received, it aborts
- * invoking callback function to avoid confusing TUSB stack. */
- TU_LOG1("Drop CONTROL_STAGE_ACK\r\n");
- }
- return true;
- }
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
const unsigned dir_in = tu_edpt_dir(ep_addr);
- if (tu_edpt_dir(req) == dir_in) { /* DATA stage */
- TU_ASSERT(total_bytes <= _dcd.remaining_ctrl);
- const unsigned rem = _dcd.remaining_ctrl;
- const unsigned len = TU_MIN(TU_MIN(rem, 64), total_bytes);
- volatile void *fifo_ptr = &musb_regs->fifo[0];
- if (dir_in) {
- tu_hwfifo_write(fifo_ptr, buffer, len, NULL);
- _dcd.pipe0.buf = buffer + len;
- _dcd.pipe0.length = len;
- _dcd.pipe0.remaining = 0;
-
- _dcd.remaining_ctrl = rem - len;
- if ((len < 64) || (rem == len)) {
- _dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID; /* Change to STATUS/SETUP stage */
- _dcd.status_out = 1;
- /* Flush TX FIFO and reverse the transaction direction. */
+ switch (pipe0->state) {
+ // DATA stage exits on its last packet, so state matches the call direction here.
+ case PIPE0_STATE_DATA_IN:
+ TU_ASSERT(dir_in);
+ pipe0->xact_len = total_bytes;
+ if (pipe0->rxrdy_consumed) { // replayed SETUP: ack its parked RXRDY before loading the FIFO
+ ep_csr->csr0l = MUSB_CSRL0_RXRDYC;
+ pipe0->rxrdy_consumed = false;
+ }
+ tu_hwfifo_write(&musb_regs->fifo[0], buffer, total_bytes, NULL);
+ pipe0->remain_wlength -= total_bytes;
+ // Add DATAEND on the last packet to end the data stage.
+ if (pipe0_data_stage_done(total_bytes)) {
ep_csr->csr0l = MUSB_CSRL0_TXRDY | MUSB_CSRL0_DATAEND;
} else {
- ep_csr->csr0l = MUSB_CSRL0_TXRDY; /* Flush TX FIFO to return ACK. */
+ ep_csr->csr0l = MUSB_CSRL0_TXRDY;
}
- // TU_LOG1(" IN ep_csr->csr0l = %x\r\n", ep_csr->csr0l);
- } else {
- // TU_LOG1(" OUT ep_csr->csr0l = %x\r\n", ep_csr->csr0l);
- _dcd.pipe0.buf = buffer;
- _dcd.pipe0.length = len;
- _dcd.pipe0.remaining = len;
- ep_csr->csr0l = MUSB_CSRL0_RXRDYC; /* Clear RX FIFO to return ACK. */
- }
- } else if (dir_in) {
- // TU_LOG1(" STATUS IN ep_csr->csr0l = %x\r\n", ep_csr->csr0l);
- _dcd.pipe0.buf = NULL;
- _dcd.pipe0.length = 0;
- _dcd.pipe0.remaining = 0;
- /* Clear RX FIFO and reverse the transaction direction */
- ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND;
+ break;
+
+ case PIPE0_STATE_DATA_OUT:
+ TU_ASSERT(!dir_in);
+ pipe0->xact_len = total_bytes;
+ pipe0->buf = buffer; // arm drain target, ack RXRDY so host can send DATA OUT
+ ep_csr->csr0l = MUSB_CSRL0_RXRDYC;
+ pipe0->rxrdy_consumed = false;
+ break;
+
+ case PIPE0_STATE_STATUS_IN:
+ TU_ASSERT(dir_in && total_bytes == 0); // only STATUS IN allowed
+ ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND;
+ pipe0->rxrdy_consumed = false;
+ break;
+
+ case PIPE0_STATE_STATUS_OUT:
+ TU_ASSERT(!dir_in && total_bytes == 0); // only STATUS OUT allowed
+ // First event of the STATUS OUT pair — wait for the IRQ to fire complete.
+ pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_XFER;
+ break;
+
+ case PIPE0_STATE_STATUS_OUT_PENDING_IRQ:
+ // Second event — IRQ already arrived, fire complete now. The old transfer is retired here,
+ // so a deferred SETUP can be replayed safely.
+ pipe0->state = PIPE0_STATE_IDLE;
+ dcd_event_xfer_complete(rhport, ep_addr, 0, XFER_RESULT_SUCCESS, is_isr);
+ pipe0_try_deferred_setup(rhport, ep_csr, is_isr);
+ break;
+
+ default: break;
}
+
return true;
}
-static void process_ep0(uint8_t rhport)
-{
+// Advance EP0's status-stage state machine on a tail event: the csrl==0 confirmation IRQ, or such a
+// confirmation combined with a new SETUP (caller sets deferred_setup_valid first). ISR context only.
+static void pipe0_process_xfer_state_isr(uint8_t rhport, musb_regs_t* musb_regs, musb_ep_csr_t* ep_csr) {
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ switch (pipe0->state) {
+ case PIPE0_STATE_DATA_IN:
+ if (pipe0_data_stage_done(pipe0->xact_len)) {
+ if (pipe0->deferred_setup_valid) {
+ pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ; // status confirm coalesced with deferred SETUP
+ } else {
+ pipe0->state = PIPE0_STATE_STATUS_OUT; // await host's STATUS-OUT ZLP IRQ
+ }
+ }
+ dcd_event_xfer_complete(rhport, TU_EP0_IN, pipe0->xact_len, XFER_RESULT_SUCCESS, true);
+ break;
+
+ case PIPE0_STATE_STATUS_OUT:
+ // Confirmation seen — await edpt0_xfer(STATUS OUT) to fire complete.
+ pipe0->state = PIPE0_STATE_STATUS_OUT_PENDING_IRQ;
+ break;
+
+ case PIPE0_STATE_STATUS_OUT_PENDING_XFER:
+ // edpt0_xfer(STATUS OUT) already called — fire complete and replay now.
+ pipe0->state = PIPE0_STATE_IDLE;
+ dcd_event_xfer_complete(rhport, TU_EP0_OUT, 0, XFER_RESULT_SUCCESS, true);
+ pipe0_try_deferred_setup(rhport, ep_csr, true);
+ break;
+
+ case PIPE0_STATE_STATUS_OUT_PENDING_IRQ:
+ // Confirmation already accounted for — the pairing edpt0_xfer(STATUS OUT) fires complete.
+ break;
+
+ case PIPE0_STATE_STATUS_IN:
+ if (pipe0->pending_addr) {
+ musb_regs->faddr = pipe0->pending_addr;
+ pipe0->pending_addr = 0;
+ }
+ pipe0->state = PIPE0_STATE_IDLE;
+ dcd_event_xfer_complete(rhport, TU_EP0_IN, 0, XFER_RESULT_SUCCESS, true);
+ pipe0_try_deferred_setup(rhport, ep_csr, true);
+ break;
+
+ default: break;
+ }
+}
+
+// 21.1.5: endpoint 0 service routine as peripheral
+static void process_ep0_isr(uint8_t rhport) {
musb_regs_t* musb_regs = MUSB_REGS(rhport);
musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0);
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
uint_fast8_t csrl = ep_csr->csr0l;
- // TU_LOG1(" EP0 ep_csr->csr0l = %x\r\n", csrl);
- // 21.1.5: endpoint 0 service routine as peripheral
-
+ // 21.1.5: SentStall and SetupEnd must be checked before anything else.
if (csrl & MUSB_CSRL0_STALLED) {
- /* Returned STALL packet to HOST. */
- ep_csr->csr0l = 0; /* Clear STALL */
+ ep_csr->csr0l = 0;
+ pipe0->state = PIPE0_STATE_IDLE;
+ pipe0->deferred_setup_valid = false;
+ pipe0->rxrdy_consumed = false;
return;
}
- unsigned req = _dcd.setup_packet.bmRequestType;
if (csrl & MUSB_CSRL0_SETEND) {
- TU_LOG1(" ABORT by the next packets\r\n");
+ // Host aborted the current control transfer (new SETUP or premature STATUS).
+ // do nothing, it is probably another setup packet, usbd will reset its state.
ep_csr->csr0l = MUSB_CSRL0_SETENDC;
- if (req != REQUEST_TYPE_INVALID && _dcd.pipe0.buf) {
- /* DATA stage was aborted by receiving STATUS or SETUP packet. */
- _dcd.pipe0.buf = NULL;
- _dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
- dcd_event_xfer_complete(rhport,
- req & TUSB_DIR_IN_MASK,
- _dcd.pipe0.length - _dcd.pipe0.remaining,
- XFER_RESULT_SUCCESS, true);
+ pipe0->state = PIPE0_STATE_IDLE;
+ pipe0->deferred_setup_valid = false;
+ pipe0->rxrdy_consumed = false;
+ if (!(csrl & MUSB_CSRL0_RXRDY)) {
+ return; /* no SETUP waiting behind it */
}
- req = REQUEST_TYPE_INVALID;
- if (!(csrl & MUSB_CSRL0_RXRDY)) return; /* Received SETUP packet */
}
+ // Receive Data (Setup or OUT)
if (csrl & MUSB_CSRL0_RXRDY) {
- /* Received SETUP or DATA OUT packet */
- if (req == REQUEST_TYPE_INVALID) {
- /* SETUP */
- TU_ASSERT(sizeof(tusb_control_request_t) == ep_csr->count0,);
- process_setup_packet(rhport);
- return;
+ if (pipe0->rxrdy_consumed) {
+ return; // stale latched IRQ: this RXRDY's packet was already drained
}
- if (_dcd.pipe0.buf) {
- /* DATA OUT */
- const unsigned vld = ep_csr->count0;
- const unsigned rem = _dcd.pipe0.remaining;
- const unsigned len = TU_MIN(TU_MIN(rem, 64), vld);
- volatile void *fifo_ptr = &musb_regs->fifo[0];
- tu_hwfifo_read(fifo_ptr, _dcd.pipe0.buf, len, NULL);
+ switch (pipe0->state) {
+ case PIPE0_STATE_IDLE: {
+ uint32_t setup[2];
+ TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, setup), );
+ pipe0_start_setup(rhport, ep_csr, setup, true);
+ break;
+ }
- _dcd.pipe0.remaining = rem - len;
- _dcd.remaining_ctrl -= len;
+ case PIPE0_STATE_DATA_OUT: {
+ // EP0 OUT is single-packet (TU_ASSERT total_bytes <= EP0_SIZE in edpt0_xfer)
+ // so the whole packet drains in one shot.
+ const uint16_t count0 = ep_csr->count0;
+ if (count0) {
+ TU_ASSERT(pipe0->buf, );
+ tu_hwfifo_read(&musb_regs->fifo[0], pipe0->buf, count0, NULL);
+ pipe0->remain_wlength -= tu_min16(count0, pipe0->remain_wlength); // clamp: host may overrun
+ }
+ // RXRDY stays set until the next edpt0_xfer arm acks it (NAK flow control):
+ // edpt0_xfer(DATA OUT) for a mid-stream packet, edpt0_xfer(STATUS IN) for the last.
+ pipe0->rxrdy_consumed = true;
+ if (pipe0_data_stage_done(count0)) {
+ pipe0->state = PIPE0_STATE_STATUS_IN;
+ }
+ dcd_event_xfer_complete(rhport, TU_EP0_OUT, count0, XFER_RESULT_SUCCESS, true);
+ break;
+ }
- _dcd.pipe0.buf = NULL;
- dcd_event_xfer_complete(rhport,
- tu_edpt_addr(0, TUSB_DIR_OUT),
- _dcd.pipe0.length - _dcd.pipe0.remaining,
- XFER_RESULT_SUCCESS, true);
- }
- return;
- }
+ // New SETUP arrived while the old control transfer's tail events are still in flight (IRQs
+ // combined under high CPU load): the old transfer's status confirm and this SETUP land together.
+ case PIPE0_STATE_DATA_IN:
+ case PIPE0_STATE_STATUS_OUT:
+ case PIPE0_STATE_STATUS_OUT_PENDING_XFER:
+ case PIPE0_STATE_STATUS_OUT_PENDING_IRQ:
+ case PIPE0_STATE_STATUS_IN:
+ // Save it, then finish the old transfer's tail event; deferred_setup_valid makes
+ // pipe0_process_xfer_state_isr() synthesize the coalesced status confirm and replay the SETUP
+ // once the old transfer is retired. Its RXRDY stays parked so a stale IRQ can't re-process it.
+ TU_VERIFY(pipe0_read_setup(musb_regs, ep_csr, pipe0->deferred_setup), );
+ pipe0->deferred_setup_valid = true;
+ pipe0->rxrdy_consumed = true;
+ pipe0_process_xfer_state_isr(rhport, musb_regs, ep_csr);
+ break;
- /* When CSRL0 is zero, it means that completion of sending a any length packet
- * or receiving a zero length packet. */
- if (req != REQUEST_TYPE_INVALID && !tu_edpt_dir(req)) {
- /* STATUS IN */
- if (*(const uint16_t*)(uintptr_t)&_dcd.setup_packet == 0x0500) {
- /* The address must be changed on completion of the control transfer. */
- musb_regs->faddr = (uint8_t)_dcd.setup_packet.wValue;
+ default: break;
}
- _dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
- dcd_event_xfer_complete(rhport,
- tu_edpt_addr(0, TUSB_DIR_IN),
- _dcd.pipe0.length - _dcd.pipe0.remaining,
- XFER_RESULT_SUCCESS, true);
+
return;
}
- if (_dcd.pipe0.buf) {
- /* DATA IN */
- _dcd.pipe0.buf = NULL;
- dcd_event_xfer_complete(rhport,
- tu_edpt_addr(0, TUSB_DIR_IN),
- _dcd.pipe0.length - _dcd.pipe0.remaining,
- XFER_RESULT_SUCCESS, true);
- }
-}
-static void process_edpt_n(uint8_t rhport, uint_fast8_t ep_addr)
-{
- bool completed;
- const unsigned dir_in = tu_edpt_dir(ep_addr);
- const unsigned epn = tu_edpt_number(ep_addr);
- const unsigned epn_minus1 = epn - 1;
-
- musb_regs_t* musb_regs = MUSB_REGS(rhport);
- musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epn);
- if (dir_in) {
- // TU_LOG1(" TX CSRL%d = %x\r\n", epn, ep_csr->tx_csrl);
- if (ep_csr->tx_csrl & MUSB_TXCSRL1_STALLED) {
- ep_csr->tx_csrl &= ~(MUSB_TXCSRL1_STALLED | MUSB_TXCSRL1_UNDRN);
- return;
- }
- completed = handle_xfer_in(rhport, ep_addr);
- } else {
- // TU_LOG1(" RX CSRL%d = %x\r\n", epn, ep_csr->rx_csrl);
- if (ep_csr->rx_csrl & MUSB_RXCSRL1_STALLED) {
- ep_csr->rx_csrl &= ~(MUSB_RXCSRL1_STALLED | MUSB_RXCSRL1_OVER);
- return;
- }
- completed = handle_xfer_out(rhport, ep_addr);
+ if (csrl & MUSB_CSRL0_DATAEND) {
+ // Last DATA IN chunk / STATUS IN arm wrote TXRDY|DATAEND and the status stage has not completed
+ // yet — nothing to service. DataEnd is CPU-set-only per the CSR access table; whether it ever
+ // reads back 1 is vendor-dependent (on cores where it reads 0 this guard is dead code).
+ return;
}
- if (completed) {
- pipe_state_t *pipe = &_dcd.pipe[dir_in][epn_minus1];
- dcd_event_xfer_complete(rhport, ep_addr,
- pipe->length - pipe->remaining,
- XFER_RESULT_SUCCESS, true);
- }
+ /* When CSRL0 is zero, it means that either
+ * - completion of sending any length packet TxPktRdy clear
+ * - or status stage is complete (ZLP) after DataEnd is set */
+ pipe0_process_xfer_state_isr(rhport, musb_regs, ep_csr);
}
// Upon BUS RESET is detected, hardware havs already done:
// faddr = 0, index = 0, flushes all ep fifos, clears all ep csr, enabled all ep interrupts
-static void process_bus_reset(uint8_t rhport) {
+static void process_bus_reset_isr(uint8_t rhport) {
musb_regs_t* musb = MUSB_REGS(rhport);
#if MUSB_CFG_DYNAMIC_FIFO
alloced_fifo_bytes = CFG_TUD_ENDPOINT0_SIZE;
#endif
- /* When bmRequestType is REQUEST_TYPE_INVALID(0xFF), a control transfer state is SETUP or STATUS stage. */
- _dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
- _dcd.status_out = 0;
- /* When pipe0.buf has not NULL, DATA stage works in progress. */
- _dcd.pipe0.buf = NULL;
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ pipe0->state = PIPE0_STATE_IDLE;
+ pipe0->buf = NULL;
+ pipe0->xact_len = 0;
+ pipe0->remain_wlength = 0;
+ pipe0->deferred_setup_valid = false;
+ pipe0->rxrdy_consumed = false;
musb->intr_txen = 1; /* Enable only EP0 */
musb->intr_rxen = 0;
@@ -544,18 +695,22 @@ void dcd_int_disable(uint8_t rhport) {
musb_dcd_int_disable(rhport);
}
-// Receive Set Address request, mcu port must also include status IN response
+// Receive Set Address request. Stash the new address here; hardware faddr is
+// latched from pending_addr in process_ep0_isr once the STATUS IN completes (per
+// USB spec, address must only take effect after the status stage).
void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
- (void)dev_addr;
musb_regs_t* musb_regs = MUSB_REGS(rhport);
musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, 0);
- _dcd.pipe0.buf = NULL;
- _dcd.pipe0.length = 0;
- _dcd.pipe0.remaining = 0;
- /* Clear RX FIFO to return ACK. */
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ pipe0->pending_addr = dev_addr;
+ pipe0->buf = NULL;
+ pipe0->xact_len = 0;
+ pipe0->state = PIPE0_STATE_STATUS_IN;
+ /* Send STATUS IN ZLP with DATAEND; host ACK fires the confirmation IRQ. */
ep_csr->csr0l = MUSB_CSRL0_RXRDYC | MUSB_CSRL0_DATAEND;
+ pipe0->rxrdy_consumed = false;
}
// Wake up host
@@ -595,39 +750,36 @@ void dcd_sof_enable(uint8_t rhport, bool en)
//--------------------------------------------------------------------+
// Endpoint API
//--------------------------------------------------------------------+
-// static void edpt_setup(musb_regs_t* musb, uint8_t ep_addr, uint8_t ep_type, uint16_t ep_size){
-// const unsigned epn = tu_edpt_number(ep_addr);
-// const unsigned dir_in = tu_edpt_dir(ep_addr);
-// }
// Configure endpoint's registers according to descriptor
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc) {
const unsigned ep_addr = ep_desc->bEndpointAddress;
const unsigned epn = tu_edpt_number(ep_addr);
- const unsigned dir_in = tu_edpt_dir(ep_addr);
+ const tusb_dir_t epdir = tu_edpt_dir(ep_addr);
const unsigned mps = tu_edpt_packet_size(ep_desc);
- pipe_state_t *pipe = &_dcd.pipe[dir_in][epn - 1];
+ pipe_state_t *pipe = pipe_get(epn, epdir);
pipe->buf = NULL;
pipe->length = 0;
pipe->remaining = 0;
+ pipe->armed = false;
musb_regs_t* musb = MUSB_REGS(rhport);
musb_ep_csr_t* ep_csr = get_ep_csr(musb, epn);
- const uint8_t is_rx = 1 - dir_in;
+ const uint8_t is_rx = (1 - epdir);
musb_ep_maxp_csr_t* maxp_csr = &ep_csr->maxp_csr[is_rx];
maxp_csr->maxp = mps;
maxp_csr->csrh = 0;
#if MUSB_CFG_SHARED_FIFO
- if (dir_in) {
+ if (epdir) {
maxp_csr->csrh |= MUSB_CSRH_TX_MODE;
}
#endif
hwfifo_flush(musb, epn, is_rx, true);
- TU_ASSERT(hwfifo_config(musb, epn, is_rx, mps, false));
+ TU_ASSERT(hwfifo_config(musb, epn, is_rx, mps, ep_desc->bmAttributes.xfer == TUSB_XFER_BULK));
musb->intren_ep[is_rx] |= TU_BIT(epn);
return true;
@@ -646,16 +798,17 @@ bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet
bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const *ep_desc ) {
const unsigned ep_addr = ep_desc->bEndpointAddress;
const unsigned epn = tu_edpt_number(ep_addr);
- const unsigned dir_in = tu_edpt_dir(ep_addr);
+ const tusb_dir_t dir_in = tu_edpt_dir(ep_addr);
const unsigned mps = tu_edpt_packet_size(ep_desc);
unsigned const ie = musb_dcd_get_int_enable(rhport);
musb_dcd_int_disable(rhport);
- pipe_state_t *pipe = &_dcd.pipe[dir_in][epn - 1];
+ pipe_state_t *pipe = pipe_get(epn, dir_in);
pipe->buf = NULL;
pipe->length = 0;
pipe->remaining = 0;
+ pipe->armed = false;
musb_regs_t* musb = MUSB_REGS(rhport);
musb_ep_csr_t* ep_csr = get_ep_csr(musb, epn);
@@ -713,22 +866,22 @@ void dcd_edpt_close_all(uint8_t rhport)
// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes, bool is_isr)
{
- (void) is_isr;
(void)rhport;
bool ret;
- // TU_LOG1("X %x %d\r\n", ep_addr, total_bytes);
unsigned const epnum = tu_edpt_number(ep_addr);
unsigned const ie = musb_dcd_get_int_enable(rhport);
musb_dcd_int_disable(rhport);
if (epnum) {
- _dcd.pipe_buf_is_fifo[tu_edpt_dir(ep_addr)] &= ~TU_BIT(epnum - 1);
- ret = edpt_n_xfer(rhport, ep_addr, buffer, total_bytes);
+ ret = edpt_n_xfer(rhport, ep_addr, buffer, total_bytes, false, is_isr);
} else {
- ret = edpt0_xfer(rhport, ep_addr, buffer, total_bytes);
+ (void) is_isr;
+ ret = edpt0_xfer(rhport, ep_addr, buffer, total_bytes, is_isr);
}
- if (ie) musb_dcd_int_enable(rhport);
+ if (ie) {
+ musb_dcd_int_enable(rhport);
+ }
return ret;
}
@@ -736,16 +889,13 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t t
// - optional, however, must be listed in usbd.c
bool dcd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes, bool is_isr)
{
- (void) is_isr;
(void)rhport;
bool ret;
- // TU_LOG1("X %x %d\r\n", ep_addr, total_bytes);
unsigned const epnum = tu_edpt_number(ep_addr);
TU_ASSERT(epnum);
unsigned const ie = musb_dcd_get_int_enable(rhport);
musb_dcd_int_disable(rhport);
- _dcd.pipe_buf_is_fifo[tu_edpt_dir(ep_addr)] |= TU_BIT(epnum - 1);
- ret = edpt_n_xfer(rhport, ep_addr, (uint8_t*)ff, total_bytes);
+ ret = edpt_n_xfer(rhport, ep_addr, ff, total_bytes, true, is_isr);
if (ie) musb_dcd_int_enable(rhport);
return ret;
}
@@ -760,14 +910,27 @@ void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) {
musb_ep_csr_t* ep_csr = get_ep_csr(musb_regs, epn);
if (0 == epn) {
- if (!ep_addr) { /* Ignore EP80 */
- _dcd.setup_packet.bmRequestType = REQUEST_TYPE_INVALID;
- _dcd.pipe0.buf = NULL;
- ep_csr->csr0l = MUSB_CSRL0_STALL;
+ if (ep_addr == TU_EP0_OUT) { /* Ignore EP0 IN */
+ pipe0_state_t* pipe0 = &_dcd.pipe0;
+ pipe0->state = PIPE0_STATE_IDLE;
+ pipe0->buf = NULL;
+ if (pipe0->deferred_setup_valid) {
+ // A deferred SETUP means the stalled transfer already ended on the wire and the host's next
+ // request was ACKed — SendStall would hit that innocent request. Replay it instead of stalling.
+ pipe0_try_deferred_setup(rhport, ep_csr, false);
+ } else {
+ // Forcing EP0 to IDLE: any RXRDY parked by the aborted transfer's flow control is stale,
+ // clear it so the next SETUP IRQ is not gated off.
+ pipe0->rxrdy_consumed = false;
+ ep_csr->csr0l = MUSB_CSRL0_STALL;
+ }
}
} else {
- const uint8_t is_rx = 1 - tu_edpt_dir(ep_addr);
+ const tusb_dir_t ep_dir = tu_edpt_dir(ep_addr);
+ const uint8_t is_rx = (ep_dir == TUSB_DIR_OUT ? 1u : 0u);
ep_csr->maxp_csr[is_rx].csrl = MUSB_CSRL_SEND_STALL(is_rx);
+ pipe_state_t* pipe = pipe_get(epn, ep_dir);
+ pipe->armed = false;
}
if (ie) musb_dcd_int_enable(rhport);
@@ -812,7 +975,7 @@ void dcd_int_handler(uint8_t rhport) {
dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
}
if (intr_usb & MUSB_IS_RESET) {
- process_bus_reset(rhport);
+ process_bus_reset_isr(rhport);
}
if (intr_usb & MUSB_IS_RESUME) {
dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
@@ -822,21 +985,35 @@ void dcd_int_handler(uint8_t rhport) {
}
intr_tx &= musb_regs->intr_txen; /* Clear disabled interrupts */
- if (intr_tx & TU_BIT(0)) {
- process_ep0(rhport);
- intr_tx &= ~TU_BIT(0);
- }
+
while (intr_tx) {
- unsigned const num = __builtin_ctz(intr_tx);
- process_edpt_n(rhport, tu_edpt_addr(num, TUSB_DIR_IN));
- intr_tx &= ~TU_BIT(num);
+ const unsigned epnum = __builtin_ctz(intr_tx);
+ if (epnum == 0) {
+ process_ep0_isr(rhport); // EP0 has its own state machine (control transfers)
+ } else {
+ process_epin_isr(rhport, musb_regs, epnum);
+ }
+ intr_tx &= ~TU_BIT(epnum);
+
+ // Double packet endpoint: TxPktRdy is clear, and interrupt is generated immediately when 1st packet is written.
+ // Also catches EP0 SETUP arriving during bulk processing.
+ uint_fast8_t new_intr_tx = musb_regs->intr_tx;
+ new_intr_tx &= musb_regs->intr_txen;
+
+ intr_tx |= new_intr_tx;
}
intr_rx &= musb_regs->intr_rxen; /* Clear disabled interrupts */
while (intr_rx) {
- unsigned const num = __builtin_ctz(intr_rx);
- process_edpt_n(rhport, tu_edpt_addr(num, TUSB_DIR_OUT));
- intr_rx &= ~TU_BIT(num);
+ unsigned const epnum = __builtin_ctz(intr_rx);
+ process_epout_isr(rhport, musb_regs, epnum, true);
+ intr_rx &= ~TU_BIT(epnum);
+
+ // Double packet endpoint: RxPktRdy is set and interrupt is generated immediately if 2nd packet is received
+ uint_fast8_t new_intr_rx = musb_regs->intr_rx;
+ new_intr_rx &= musb_regs->intr_rxen;
+
+ intr_rx |= new_intr_rx;
}
musb_regs->index = saved_index; // restore endpoint index
diff --git a/src/portable/mentor/musb/musb_max32.h b/src/portable/mentor/musb/musb_max32.h
index 599de2ca1..134b47122 100644
--- a/src/portable/mentor/musb/musb_max32.h
+++ b/src/portable/mentor/musb/musb_max32.h
@@ -47,7 +47,7 @@ extern "C" {
#define MUSB_CFG_SHARED_FIFO 1 // shared FIFO for TX and RX endpoints
#define MUSB_CFG_DYNAMIC_FIFO 0 // dynamic EP FIFO sizing
-const uintptr_t MUSB_BASES[] = { MXC_BASE_USBHS };
+static const uintptr_t MUSB_BASES[] = { MXC_BASE_USBHS };
#if CFG_TUD_ENABLED
#define USBHS_M31_CLOCK_RECOVERY
diff --git a/src/portable/mentor/musb/musb_ti.h b/src/portable/mentor/musb/musb_ti.h
index 68e89d77d..deaea8017 100644
--- a/src/portable/mentor/musb/musb_ti.h
+++ b/src/portable/mentor/musb/musb_ti.h
@@ -49,7 +49,7 @@
#define MUSB_CFG_DYNAMIC_FIFO 1
#define MUSB_CFG_DYNAMIC_FIFO_SIZE 4096
-const uintptr_t MUSB_BASES[] = { USB0_BASE };
+static const uintptr_t MUSB_BASES[] = { USB0_BASE };
// Header supports both device and host modes. Only include what's necessary
#if CFG_TUD_ENABLED
diff --git a/src/portable/mentor/musb/musb_type.h b/src/portable/mentor/musb/musb_type.h
index b2f6492fa..3d3c3c834 100644
--- a/src/portable/mentor/musb/musb_type.h
+++ b/src/portable/mentor/musb/musb_type.h
@@ -300,7 +300,7 @@ TU_VERIFY_STATIC(sizeof(musb_regs_t) == 0x350, "size is not correct");
// Helper
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline musb_ep_csr_t* get_ep_csr(musb_regs_t* musb_regs, unsigned epnum) {
- musb_regs->index = epnum;
+ musb_regs->index = (uint8_t)epnum;
return &musb_regs->indexed_csr;
}
@@ -336,7 +336,7 @@ TU_ATTR_ALWAYS_INLINE static inline musb_ep_csr_t* get_ep_csr(musb_regs_t* musb_
#define MUSB_CSRL_CLEAR_DATA_TOGGLE(_rx) (1u << ((_rx) ? 7 : 6))
// 0x13, 0x17: TX/RX CSRH
-#define MUSB_CSRH_DISABLE_DOUBLE_PACKET(_rx) (1u << 1)
+#define MUSB_CSRH_DISABLE_DOUBLE_PACKET (1u << 1)
#define MUSB_CSRH_TX_MODE (1u << 5) // 1 = TX, 0 = RX. only relevant for SHARED FIFO
#define MUSB_CSRH_ISO (1u << 6)
@@ -568,6 +568,16 @@ TU_ATTR_ALWAYS_INLINE static inline musb_ep_csr_t* get_ep_csr(musb_regs_t* musb_
//*****************************************************************************
//
+// The following are defines for the bit fields in the MUSB_O_TXMAXP / MUSB_O_RXMAXP
+// registers. Bits [10:0] carry the maximum packet size; bits [15:11] carry
+// numpackminus1 (HB-iso / HS-bulk multiplier - 1).
+//
+//*****************************************************************************
+#define MUSB_TXMAXP_PACKET_SIZE_M 0x07FFu
+#define MUSB_RXMAXP_PACKET_SIZE_M 0x07FFu
+
+//*****************************************************************************
+//
// The following are defines for the bit fields in the MUSB_O_TXCSRL1 register.
//
//*****************************************************************************
diff --git a/src/portable/microchip/samg/dcd_samg.c b/src/portable/microchip/samg/dcd_samg.c
index 4115eecc5..f8980b775 100644
--- a/src/portable/microchip/samg/dcd_samg.c
+++ b/src/portable/microchip/samg/dcd_samg.c
@@ -352,8 +352,8 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
csr_clear(epnum, UDP_CSR_FORCESTALL_Msk);
// must also reset EP to clear data toggle
- UDP->UDP_RST_EP |= (1 << epnum);
- UDP->UDP_RST_EP &= ~(1 << epnum);
+ UDP->UDP_RST_EP |= (1u << epnum);
+ UDP->UDP_RST_EP &= ~(1u << epnum);
}
//--------------------------------------------------------------------+
diff --git a/src/portable/nordic/nrf5x/dcd_nrf5x.c b/src/portable/nordic/nrf5x/dcd_nrf5x.c
index 8a41c4790..befbaa338 100644
--- a/src/portable/nordic/nrf5x/dcd_nrf5x.c
+++ b/src/portable/nordic/nrf5x/dcd_nrf5x.c
@@ -36,6 +36,8 @@
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wcast-align"
#pragma GCC diagnostic ignored "-Wunused-parameter"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#include "nrf.h"
@@ -461,7 +463,7 @@ bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t* buffer, uint16_t to
xfer->actual_len = 0;
// Control endpoint with zero-length packet and opposite direction to 1st request byte --> status stage
- bool const control_status = (epnum == 0 && total_bytes == 0 && dir != tu_edpt_dir(NRF_USBD->BMREQUESTTYPE));
+ bool const control_status = (epnum == 0 && total_bytes == 0 && dir != tu_edpt_dir((uint8_t)NRF_USBD->BMREQUESTTYPE));
if (control_status) {
// The nRF doesn't interrupt on status transmit so we queue up a success response.
@@ -1047,6 +1049,12 @@ void tusb_hal_nrf_power_event(uint32_t event) {
NVIC_EnableIRQ(USBD_IRQn);
}
+ // Ensure HFCLK is requested in the current context. The hfclk_enable() in
+ // USB_EVT_DETECTED may have been pre-SoftDevice. After Softdevice is
+ // enabled, HFXO is physically off again. So any caller that fires
+ // USB_EVT_READY post-SD would hang here.
+ hfclk_enable();
+
// Wait for HFCLK
while (!hfclk_running()) {}
diff --git a/src/portable/nuvoton/nuc120/dcd_nuc120.c b/src/portable/nuvoton/nuc120/dcd_nuc120.c
index d9a0e3fa8..2edb1bc7a 100644
--- a/src/portable/nuvoton/nuc120/dcd_nuc120.c
+++ b/src/portable/nuvoton/nuc120/dcd_nuc120.c
@@ -253,13 +253,13 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
- int const size = tu_edpt_packet_size(p_endpoint_desc);
+ uint16_t const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = (tusb_xfer_type_t) p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
/* allocate buffer from USB RAM */
ep->BUFSEG = bufseg_addr;
- bufseg_addr += size;
+ bufseg_addr += (uint32_t)size;
TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE);
/* construct USB Configuration Register value and then write it */
@@ -435,7 +435,7 @@ void dcd_int_handler(uint8_t rhport)
/* given ACK from host has happened, we can now set the address (if not already done) */
if((USBD->FADDR != assigned_address) && (USBD->FADDR == 0)) USBD->FADDR = assigned_address;
- uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD;
+ uint16_t const available_bytes = (uint16_t)USBD->EP[PERIPH_EP0].MXPLD;
active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size);
@@ -453,7 +453,7 @@ void dcd_int_handler(uint8_t rhport)
{
USBD->INTSTS = mask;
- uint16_t const available_bytes = ep->MXPLD;
+ uint16_t const available_bytes = (uint16_t)ep->MXPLD;
uint8_t const ep_addr = decode_ep_addr(ep);
bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK);
diff --git a/src/portable/nuvoton/nuc121/dcd_nuc121.c b/src/portable/nuvoton/nuc121/dcd_nuc121.c
index 42fb58a0a..008c9df6b 100644
--- a/src/portable/nuvoton/nuc121/dcd_nuc121.c
+++ b/src/portable/nuvoton/nuc121/dcd_nuc121.c
@@ -42,6 +42,8 @@
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#include "NuMicro.h"
@@ -291,7 +293,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
- int const size = tu_edpt_packet_size(p_endpoint_desc);
+ uint16_t const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = (tusb_xfer_type_t) p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
@@ -478,7 +480,7 @@ void dcd_int_handler(uint8_t rhport)
{
if (status & USBD_INTSTS_EPEVT0_Msk) /* PERIPH_EP0 (EP0_IN) event: this is treated separately from the rest */
{
- uint16_t const available_bytes = USBD->EP[PERIPH_EP0].MXPLD;
+ uint16_t const available_bytes = (uint16_t)USBD->EP[PERIPH_EP0].MXPLD;
active_ep0_xfer = (available_bytes == xfer_table[PERIPH_EP0].max_packet_size);
@@ -496,7 +498,7 @@ void dcd_int_handler(uint8_t rhport)
{
USBD->INTSTS = mask;
- uint16_t const available_bytes = ep->MXPLD;
+ uint16_t const available_bytes = (uint16_t)ep->MXPLD;
uint8_t const ep_addr = decode_ep_addr(ep);
bool const out_ep = !(ep_addr & TUSB_DIR_IN_MASK);
diff --git a/src/portable/nuvoton/nuc505/dcd_nuc505.c b/src/portable/nuvoton/nuc505/dcd_nuc505.c
index ca17d6251..a0f3d4c3f 100644
--- a/src/portable/nuvoton/nuc505/dcd_nuc505.c
+++ b/src/portable/nuvoton/nuc505/dcd_nuc505.c
@@ -42,6 +42,8 @@
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#include "NUC505Series.h"
@@ -338,13 +340,13 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc)
/* mine the data for the information we need */
int const dir = tu_edpt_dir(p_endpoint_desc->bEndpointAddress);
- int const size = tu_edpt_packet_size(p_endpoint_desc);
+ uint16_t const size = tu_edpt_packet_size(p_endpoint_desc);
tusb_xfer_type_t const type = p_endpoint_desc->bmAttributes.xfer;
struct xfer_ctl_t *xfer = &xfer_table[ep - USBD->EP];
/* allocate buffer from USB RAM */
ep->EPBUFSTART = bufseg_addr;
- bufseg_addr += size;
+ bufseg_addr += (uint32_t)size;
ep->EPBUFEND = bufseg_addr - 1;
TU_ASSERT(bufseg_addr <= USBD_BUF_SIZE);
diff --git a/src/portable/nxp/lpc17_40/dcd_lpc17_40.c b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c
index 349229c8d..2840c6d5e 100644
--- a/src/portable/nxp/lpc17_40/dcd_lpc17_40.c
+++ b/src/portable/nxp/lpc17_40/dcd_lpc17_40.c
@@ -131,7 +131,7 @@ static uint8_t sie_read (uint8_t cmd_code)
//--------------------------------------------------------------------+
static inline uint8_t ep_addr2idx(uint8_t ep_addr)
{
- return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0);
+ return (uint8_t)(2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0));
}
static void set_ep_size(uint8_t ep_id, uint16_t max_packet_size)
@@ -243,7 +243,7 @@ void dcd_sof_enable(uint8_t rhport, bool en)
//--------------------------------------------------------------------+
static inline uint8_t byte2dword(uint8_t bytes)
{
- return (bytes + 3) / 4; // length in dwords
+ return (uint8_t)((bytes + 3) / 4); // length in dwords
}
static void control_ep_write(void const * buffer, uint8_t len)
diff --git a/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c b/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c
index 5f4a441dc..8adf0f840 100644
--- a/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c
+++ b/src/portable/nxp/lpc_ip3511/dcd_lpc_ip3511.c
@@ -243,7 +243,7 @@ TU_ATTR_ALWAYS_INLINE static inline uint16_t get_buf_offset(void const * buffer)
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t ep_addr2id(uint8_t ep_addr) {
- return 2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0);
+ return (uint8_t)(2*(ep_addr & 0x0F) + ((ep_addr & TUSB_DIR_IN_MASK) ? 1 : 0));
}
TU_ATTR_ALWAYS_INLINE static inline bool ep_is_iso(ep_cmd_sts_t* ep_cs, bool is_highspeed) {
@@ -539,8 +539,8 @@ static void process_xfer_isr(uint8_t rhport, uint32_t int_status) {
uint16_t buf_nbytes;
if ( rhport_is_highspeed(rhport) ) {
- buf_offset = ep_cs->buffer_hs.offset;
- buf_nbytes = ep_cs->buffer_hs.nbytes;
+ buf_offset = (uint16_t)ep_cs->buffer_hs.offset;
+ buf_nbytes = (uint16_t)ep_cs->buffer_hs.nbytes;
#if TU_CHECK_MCU(OPT_MCU_LPC54)
// LPC54 Errata USB.2: In USB high-speed device mode, the NBytes field is not correct after BULK IN transfer
@@ -550,8 +550,8 @@ static void process_xfer_isr(uint8_t rhport, uint32_t int_status) {
}
#endif
} else {
- buf_offset = ep_cs->buffer_fs.offset;
- buf_nbytes = ep_cs->buffer_fs.nbytes;
+ buf_offset = (uint16_t)ep_cs->buffer_fs.offset;
+ buf_nbytes = (uint16_t)ep_cs->buffer_fs.nbytes;
}
xfer_dma->xferred_bytes += xfer_dma->nbytes - buf_nbytes;
diff --git a/src/portable/raspberrypi/rp2040/hcd_rp2040.c b/src/portable/raspberrypi/rp2040/hcd_rp2040.c
index 02a4e055e..064834efb 100644
--- a/src/portable/raspberrypi/rp2040/hcd_rp2040.c
+++ b/src/portable/raspberrypi/rp2040/hcd_rp2040.c
@@ -617,10 +617,16 @@ bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t *b
io_rw_32 *buf_reg = dpram_int_ep_buffer_ctrl(ep->interrupt_num);
rp2usb_xfer_start(ep, ep_reg, buf_reg, buffer, NULL, buflen);
} else {
- // Control endpoint can change direction 0x00 <-> 0x80 when changing stages
- if (ep_addr != ep->ep_addr) {
+ // Control transfer data and status stages always start with DATA1, regardless of
+ // whether the direction changed since the previous stage. SET_REPORT (and any other
+ // host-to-device class request with an OUT data stage) keeps the same direction
+ // across SETUP -> DATA, so we cannot key off "direction changed" -- we must reset
+ // next_pid every time hcd_edpt_xfer is invoked on ep 0. Without this, the data stage
+ // of SET_REPORT goes out as DATA0 because ep->next_pid is still 0 from hcd_edpt_open(),
+ // which strict devices treat as a protocol violation and disconnect.
+ if (tu_edpt_number(ep_addr) == 0) {
ep->ep_addr = ep_addr;
- ep->next_pid = 1; // data and status stage start with DATA1
+ ep->next_pid = 1;
}
// If EPX is busy with another transfer, mark as pending
diff --git a/src/portable/renesas/rusb2/dcd_rusb2.c b/src/portable/renesas/rusb2/dcd_rusb2.c
index e2a51a5ca..adbb53787 100644
--- a/src/portable/renesas/rusb2/dcd_rusb2.c
+++ b/src/portable/renesas/rusb2/dcd_rusb2.c
@@ -93,7 +93,9 @@ static unsigned find_pipe(unsigned xfer_type) {
const uint8_t idx_last = pipe_idx_arr[xfer_type][1];
for (int i = idx_last; i >= idx_first; i--) {
- if (0 == _dcd.pipe[i].ep) return i;
+ if (0 == _dcd.pipe[i].ep) {
+ return (unsigned)i;
+ }
}
return 0;
@@ -117,10 +119,10 @@ static volatile reg_pipetre_t* get_pipetre(rusb2_reg_t *rusb, unsigned num) {
static volatile uint16_t* ep_addr_to_pipectr(uint8_t rhport, unsigned ep_addr) {
rusb2_reg_t *rusb = RUSB2_REG(rhport);
- const unsigned epn = tu_edpt_number(ep_addr);
+ const unsigned epn = tu_edpt_number((uint8_t)ep_addr);
if (epn) {
- const unsigned dir = tu_edpt_dir(ep_addr);
+ const unsigned dir = tu_edpt_dir((uint8_t)ep_addr);
const unsigned num = _dcd.ep[dir][epn];
return get_pipectr(rusb, num);
} else {
@@ -129,11 +131,11 @@ static volatile uint16_t* ep_addr_to_pipectr(uint8_t rhport, unsigned ep_addr) {
}
static uint16_t edpt0_max_packet_size(rusb2_reg_t* rusb) {
- return rusb->DCPMAXP_b.MXPS;
+ return (uint16_t)rusb->DCPMAXP_b.MXPS;
}
static uint16_t edpt_max_packet_size(rusb2_reg_t *rusb, unsigned num) {
- rusb->PIPESEL = num;
+ rusb->PIPESEL = (uint16_t)num;
return rusb->PIPEMAXP;
}
@@ -285,7 +287,7 @@ static bool pipe_xfer_out(rusb2_reg_t* rusb, unsigned num)
const uint16_t mps = edpt_max_packet_size(rusb, num);
pipe_wait_for_ready(rusb, num);
- const uint16_t vld = rusb->D0FIFOCTR_b.DTLN;
+ const uint16_t vld = (uint16_t)rusb->D0FIFOCTR_b.DTLN;
const uint16_t len = tu_min16(tu_min16(rem, mps), vld);
void *buf = pipe->buf;
@@ -498,7 +500,7 @@ static void process_bus_reset(uint8_t rhport)
volatile uint16_t *ctr = (volatile uint16_t*)((uintptr_t) (&rusb->PIPE_CTR[0]));
volatile uint16_t *tre = (volatile uint16_t*)((uintptr_t) (&rusb->PIPE_TR[0].E));
- for (int i = 1; i <= 5; ++i) {
+ for (uint16_t i = 1; i <= 5; ++i) {
rusb->PIPESEL = i;
rusb->PIPECFG = 0;
*ctr = RUSB2_PIPE_CTR_ACLRM_Msk;
@@ -508,7 +510,7 @@ static void process_bus_reset(uint8_t rhport)
tre += 2;
}
- for (int i = 6; i <= 9; ++i) {
+ for (uint16_t i = 6; i <= 9; ++i) {
rusb->PIPESEL = i;
rusb->PIPECFG = 0;
*ctr = RUSB2_PIPE_CTR_ACLRM_Msk;
@@ -542,7 +544,7 @@ static void process_bus_reset(uint8_t rhport)
static void process_set_address(uint8_t rhport)
{
rusb2_reg_t* rusb = RUSB2_REG(rhport);
- const uint16_t addr = rusb->USBADDR_b.USBADDR;
+ const uint16_t addr = (uint16_t)rusb->USBADDR_b.USBADDR;
if (!addr) {
return;
}
@@ -706,7 +708,7 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
(void)rhport;
rusb2_reg_t * rusb = RUSB2_REG(rhport);
- const unsigned ep_addr = ep_desc->bEndpointAddress;
+ const uint8_t ep_addr = ep_desc->bEndpointAddress;
const unsigned epn = tu_edpt_number(ep_addr);
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned xfer = ep_desc->bmAttributes.xfer;
@@ -770,8 +772,10 @@ void dcd_edpt_close_all(uint8_t rhport)
dcd_int_disable(rhport);
while (--i) { /* Close all pipes except 0 */
const unsigned ep_addr = _dcd.pipe[i].ep;
- if (!ep_addr) continue;
- dcd_edpt_close(rhport, ep_addr);
+ if (!ep_addr) {
+ continue;
+ }
+ dcd_edpt_close(rhport, (uint8_t)ep_addr);
}
dcd_int_enable(rhport);
}
@@ -783,10 +787,10 @@ void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
const unsigned dir = tu_edpt_dir(ep_addr);
const unsigned num = _dcd.ep[dir][epn];
- rusb->BRDYENB &= ~TU_BIT(num);
+ rusb->BRDYENB &= (uint16_t)~TU_BIT(num);
volatile uint16_t *ctr = get_pipectr(rusb, num);
*ctr = 0;
- rusb->PIPESEL = num;
+ rusb->PIPESEL = (uint16_t)num;
rusb->PIPECFG = 0;
_dcd.pipe[num].ep = 0;
_dcd.ep[dir][epn] = 0;
@@ -860,7 +864,7 @@ void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
*ctr = RUSB2_PIPE_CTR_PID_BUF;
} else {
const unsigned num = _dcd.ep[0][tu_edpt_number(ep_addr)];
- rusb->PIPESEL = num;
+ rusb->PIPESEL = (uint16_t)num;
if (rusb->PIPECFG_b.TYPE != 1) {
*ctr = RUSB2_PIPE_CTR_PID_BUF;
}
diff --git a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c
index 8b4719b21..6f7f490a8 100644
--- a/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c
+++ b/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c
@@ -41,6 +41,7 @@
* F302xB/C, F303xB/C, F373 512 byte buffer; no internal D+ pull-up
* F302x6/8, F302xD/E2, F303xD/E 1024 byte buffer; no internal D+ pull-up
* C0 2048 byte buffer; 32-bit bus; host mode
+ * C5 2048 byte buffer; 32-bit bus; host mode
* G0 2048 byte buffer; 32-bit bus; host mode
* G4 1024 byte buffer
* H5 2048 byte buffer; 32-bit bus; host mode
@@ -259,7 +260,7 @@ static void handle_ctr_tx(uint32_t ep_id) {
}
if (xfer->total_len != xfer->queued_len) {
- dcd_transmit_packet(xfer, ep_id);
+ dcd_transmit_packet(xfer, (uint16_t)ep_id);
} else {
dcd_event_xfer_complete(0, ep_num | TUSB_DIR_IN_MASK, xfer->queued_len, XFER_RESULT_SUCCESS, true);
}
@@ -267,7 +268,7 @@ static void handle_ctr_tx(uint32_t ep_id) {
static void handle_ctr_setup(uint32_t ep_id) {
uint16_t rx_count = btable_get_count(ep_id, BTABLE_BUF_RX);
- uint16_t rx_addr = btable_get_addr(ep_id, BTABLE_BUF_RX);
+ uint16_t rx_addr = (uint16_t)btable_get_addr(ep_id, BTABLE_BUF_RX);
uint8_t setup_packet[8] TU_ATTR_ALIGNED(4);
tu_hwfifo_read(PMA_BUF_AT(rx_addr), setup_packet, rx_count, NULL);
@@ -342,7 +343,7 @@ void dcd_int_handler(uint8_t rhport) {
uint32_t int_status = FSDEV_REG->ISTR;
/* Put SOF flag at the beginning of ISR in case to get least amount of jitter if it is used for timing purposes */
- if (int_status & U_ISTR_SOF) {
+ if ((int_status & U_ISTR_SOF) && (FSDEV_REG->CNTR & U_CNTR_SOFM)) {
FSDEV_REG->ISTR = (fsdev_bus_t)~U_ISTR_SOF;
dcd_event_sof(0, FSDEV_REG->FNR & U_FNR_FN, true);
}
@@ -393,26 +394,8 @@ void dcd_int_handler(uint8_t rhport) {
const uint32_t ep_reg = ep_read(ep_id);
if (ep_reg & U_EP_CTR_RX) {
- #ifdef CFG_TUSB_FSDEV_32BIT
- /* https://www.st.com/resource/en/errata_sheet/es0561-stm32h503cbebkbrb-device-errata-stmicroelectronics.pdf
- * https://www.st.com/resource/en/errata_sheet/es0587-stm32u535xx-and-stm32u545xx-device-errata-stmicroelectronics.pdf
- * From H503/U535 errata: Buffer description table update completes after CTR interrupt triggers
- * Description:
- * - During OUT transfers, the correct transfer interrupt (CTR) is triggered a little before the last USB SRAM
- * accesses have completed. If the software responds quickly to the interrupt, the full buffer contents may not be
- * correct. Workaround:
- * - Software should ensure that a small delay is included before accessing the SRAM contents. This delay
- * should be 800 ns in Full Speed mode and 6.4 μs in Low Speed mode
- * - Since H5 can run up to 250Mhz -> 1 cycle = 4ns. Per errata, we need to wait 200 cycles. Though executing code
- * also takes time, so we'll wait 60 cycles (count = 20).
- * - Since Low Speed mode is not supported/popular, we will ignore it for now.
- *
- * Note: this errata may also apply to G0, U5, H5 etc.
- */
- volatile uint32_t cycle_count = 20; // defined as PCD_RX_PMA_CNT in stm32 hal_driver
- while (cycle_count > 0U) {
- cycle_count--; // each count take 3 cycles (1 for sub, jump, and compare)
- }
+ #if defined(TUP_USBIP_FSDEV_STM32) && defined(CFG_TUSB_FSDEV_32BIT)
+ fsdev_btable_workaround_delay(false);
#endif
if (ep_reg & U_EP_SETUP) {
@@ -531,8 +514,8 @@ void edpt0_open(uint8_t rhport) {
xfer_status[0][1].max_packet_size = CFG_TUD_ENDPOINT0_SIZE;
xfer_status[0][1].ep_idx = 0;
- uint16_t pma_addr0 = dcd_pma_alloc(CFG_TUD_ENDPOINT0_SIZE, false);
- uint16_t pma_addr1 = dcd_pma_alloc(CFG_TUD_ENDPOINT0_SIZE, false);
+ uint16_t pma_addr0 = (uint16_t)dcd_pma_alloc(CFG_TUD_ENDPOINT0_SIZE, false);
+ uint16_t pma_addr1 = (uint16_t)dcd_pma_alloc(CFG_TUD_ENDPOINT0_SIZE, false);
btable_set_addr(0, BTABLE_BUF_RX, pma_addr0);
btable_set_addr(0, BTABLE_BUF_TX, pma_addr1);
@@ -574,7 +557,7 @@ bool dcd_edpt_open(uint8_t rhport, const tusb_desc_endpoint_t *desc_ep) {
}
/* Create a packet memory buffer area. */
- uint16_t pma_addr = dcd_pma_alloc(packet_size, false);
+ uint16_t pma_addr = (uint16_t)dcd_pma_alloc(packet_size, false);
btable_set_addr(ep_idx, dir == TUSB_DIR_IN ? BTABLE_BUF_TX : BTABLE_BUF_RX, pma_addr);
xfer_ctl_t *xfer = xfer_ctl_ptr(ep_num, dir);
@@ -624,17 +607,17 @@ bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet
#if CFG_TUD_FSDEV_DOUBLE_BUFFERED_ISO_EP != 0
uint32_t pma_addr = dcd_pma_alloc(largest_packet_size, true);
- uint16_t pma_addr2 = pma_addr >> 16;
+ uint16_t pma_addr2 = (uint16_t)(pma_addr >> 16);
#else
uint32_t pma_addr = dcd_pma_alloc(largest_packet_size, false);
- uint16_t pma_addr2 = pma_addr;
+ uint16_t pma_addr2 = (uint16_t)pma_addr;
#endif
#if FSDEV_USE_SBUF_ISO == 0
- btable_set_addr(ep_idx, 0, pma_addr);
+ btable_set_addr(ep_idx, 0, (uint16_t)pma_addr);
btable_set_addr(ep_idx, 1, pma_addr2);
#else
- btable_set_addr(ep_idx, dir == TUSB_DIR_IN ? BTABLE_BUF_TX : BTABLE_BUF_RX, pma_addr);
+ btable_set_addr(ep_idx, dir == TUSB_DIR_IN ? BTABLE_BUF_TX : BTABLE_BUF_RX, (uint16_t)pma_addr);
(void)pma_addr2;
#endif
diff --git a/src/portable/st/stm32_fsdev/fsdev_common.c b/src/portable/st/stm32_fsdev/fsdev_common.c
index 003bcd069..7c4572a1e 100644
--- a/src/portable/st/stm32_fsdev/fsdev_common.c
+++ b/src/portable/st/stm32_fsdev/fsdev_common.c
@@ -81,11 +81,11 @@ uint16_t pma_align_buffer_size(uint16_t size, uint8_t* blsize, uint8_t* num_bloc
if (size > 62) {
block_in_bytes = 32;
*blsize = 1;
- *num_block = tu_div_ceil(size, 32);
+ *num_block = (uint8_t)tu_div_ceil(size, 32);
} else {
block_in_bytes = 2;
*blsize = 0;
- *num_block = tu_div_ceil(size, 2);
+ *num_block = (uint8_t)tu_div_ceil(size, 2);
}
return (*num_block) * block_in_bytes;
diff --git a/src/portable/st/stm32_fsdev/fsdev_common.h b/src/portable/st/stm32_fsdev/fsdev_common.h
index 140ff1d61..af84b8b97 100644
--- a/src/portable/st/stm32_fsdev/fsdev_common.h
+++ b/src/portable/st/stm32_fsdev/fsdev_common.h
@@ -345,7 +345,7 @@ TU_ATTR_ALWAYS_INLINE static inline void ep_write_clear_ctr(uint32_t ep_id, tusb
uint32_t reg = FSDEV_REG->ep[ep_id].reg;
reg |= U_EP_CTR_TX | U_EP_CTR_RX;
reg &= U_EPREG_MASK;
- reg &= ~(1 << (U_EP_CTR_TX_Pos + (dir == TUSB_DIR_IN ? 0 : 8)));
+ reg &= ~(1u << (U_EP_CTR_TX_Pos + (dir == TUSB_DIR_IN ? 0u : 8u)));
ep_write(ep_id, reg, false);
}
@@ -378,7 +378,7 @@ TU_ATTR_ALWAYS_INLINE static inline void ch_write_clear_ctr(uint32_t ch_id, tusb
uint32_t reg = FSDEV_REG->ep[ch_id].reg;
reg |= U_EP_CTR_TX | U_EP_CTR_RX;
reg &= U_EPREG_MASK;
- reg &= ~(1 << (U_EP_CTR_TX_Pos + (dir == TUSB_DIR_IN ? 8 : 0)));
+ reg &= ~(1u << (U_EP_CTR_TX_Pos + (dir == TUSB_DIR_IN ? 8u : 0u)));
ep_write(ch_id, reg, false);
}
diff --git a/src/portable/st/stm32_fsdev/fsdev_stm32.h b/src/portable/st/stm32_fsdev/fsdev_stm32.h
index a63592c5d..93cdac808 100644
--- a/src/portable/st/stm32_fsdev/fsdev_stm32.h
+++ b/src/portable/st/stm32_fsdev/fsdev_stm32.h
@@ -36,6 +36,10 @@
#include "stm32c0xx.h"
#define FSDEV_HAS_SBUF_ISO 1
+#elif CFG_TUSB_MCU == OPT_MCU_STM32C5
+ #include "stm32c5xx.h"
+ #define FSDEV_HAS_SBUF_ISO 1
+
#elif CFG_TUSB_MCU == OPT_MCU_STM32F0
#include "stm32f0xx.h"
#define FSDEV_HAS_SBUF_ISO 0
@@ -164,20 +168,24 @@
#define FSDEV_USE_SBUF_ISO 0
#endif
-//--------------------------------------------------------------------+
-//
-//--------------------------------------------------------------------+
-
+// STM32L1 calls it USB_FS_WKUP_IRQn; alias so the commented USBWakeUp_IRQn below
+// can be uncommented as-is.
#if TU_CHECK_MCU(OPT_MCU_STM32L1) && !defined(USBWakeUp_IRQn)
#define USBWakeUp_IRQn USB_FS_WKUP_IRQn
#endif
+// USB interrupt vectors to enable in NVIC. The EXTI-line USB wakeup interrupt
+// (USBWakeUp_IRQn, and USBWakeUp_RMP_IRQn on F3) is left commented out: resume is
+// handled in-band via ISTR.WKUP in the USB_LP/HP ISR; the EXTI line is only needed to
+// wake the core from STOP mode, which this driver does not implement (it never arms or
+// clears that EXTI line, so enabling its NVIC vector can only spuriously fire/freeze).
+// TODO: uncomment USBWakeUp_IRQn (+ arm/clear its EXTI line) when adding STOP-mode wakeup.
static const IRQn_Type fsdev_irq[] = {
#if TU_CHECK_MCU(OPT_MCU_STM32F0, OPT_MCU_STM32L0, OPT_MCU_STM32L4, OPT_MCU_STM32U5)
USB_IRQn,
#elif TU_CHECK_MCU(OPT_MCU_STM32L5, OPT_MCU_STM32U3)
USB_FS_IRQn,
- #elif TU_CHECK_MCU(OPT_MCU_STM32C0, OPT_MCU_STM32H5, OPT_MCU_STM32U0)
+ #elif TU_CHECK_MCU(OPT_MCU_STM32C0, OPT_MCU_STM32C5, OPT_MCU_STM32H5, OPT_MCU_STM32U0)
USB_DRD_FS_IRQn,
#elif CFG_TUSB_MCU == OPT_MCU_STM32G0
#ifdef STM32G0B0xx
@@ -188,15 +196,15 @@ static const IRQn_Type fsdev_irq[] = {
#elif CFG_TUSB_MCU == OPT_MCU_STM32F1
USB_HP_CAN1_TX_IRQn,
USB_LP_CAN1_RX0_IRQn,
- USBWakeUp_IRQn,
+ //USBWakeUp_IRQn,
#elif CFG_TUSB_MCU == OPT_MCU_STM32F3
USB_HP_CAN_TX_IRQn,
USB_LP_CAN_RX0_IRQn,
- USBWakeUp_IRQn,
+ //USBWakeUp_IRQn,
#elif TU_CHECK_MCU(OPT_MCU_STM32G4, OPT_MCU_STM32L1)
USB_HP_IRQn,
USB_LP_IRQn,
- USBWakeUp_IRQn,
+ //USBWakeUp_IRQn,
#elif CFG_TUSB_MCU == OPT_MCU_STM32WB
USB_HP_IRQn,
USB_LP_IRQn,
@@ -219,7 +227,7 @@ TU_ATTR_ALWAYS_INLINE static inline void fsdev_int_enable(uint8_t rhport) {
if (SYSCFG->CFGR1 & SYSCFG_CFGR1_USB_IT_RMP) {
NVIC_EnableIRQ(USB_HP_IRQn);
NVIC_EnableIRQ(USB_LP_IRQn);
- NVIC_EnableIRQ(USBWakeUp_RMP_IRQn);
+ //NVIC_EnableIRQ(USBWakeUp_RMP_IRQn);
} else
#endif
{
@@ -239,7 +247,7 @@ TU_ATTR_ALWAYS_INLINE static inline void fsdev_int_disable(uint8_t rhport) {
if (SYSCFG->CFGR1 & SYSCFG_CFGR1_USB_IT_RMP) {
NVIC_DisableIRQ(USB_HP_IRQn);
NVIC_DisableIRQ(USB_LP_IRQn);
- NVIC_DisableIRQ(USBWakeUp_RMP_IRQn);
+ //NVIC_DisableIRQ(USBWakeUp_RMP_IRQn);
} else
#endif
{
@@ -252,6 +260,64 @@ TU_ATTR_ALWAYS_INLINE static inline void fsdev_int_disable(uint8_t rhport) {
}
//--------------------------------------------------------------------+
+// STM32 FSDEV PMA Buffer Description Table errata workaround
+//--------------------------------------------------------------------+
+
+#ifdef CFG_TUSB_FSDEV_32BIT
+/* Errata: Buffer description table update completes after CTR interrupt triggers
+ * https://www.st.com/resource/en/errata_sheet/es0561-stm32h503cbebkbrb-device-errata-stmicroelectronics.pdf
+ * https://www.st.com/resource/en/errata_sheet/es0587-stm32u535xx-and-stm32u545xx-device-errata-stmicroelectronics.pdf
+ *
+ * CTR may trigger before final PMA SRAM accesses complete on OUT transfers.
+ * Insert delay before reading PMA count/data.
+ * Max CPU frequency in Hz, used to derive conservative FSDEV PMA delay defaults.
+ */
+#if CFG_TUSB_MCU == OPT_MCU_STM32H5
+ #define FSDEV_STM32_CPU_HZ 250000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32U5
+ #define FSDEV_STM32_CPU_HZ 160000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32U3
+ #define FSDEV_STM32_CPU_HZ 96000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32U0
+ #define FSDEV_STM32_CPU_HZ 56000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32G0
+ #define FSDEV_STM32_CPU_HZ 64000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32C0
+ #define FSDEV_STM32_CPU_HZ 48000000U
+#elif CFG_TUSB_MCU == OPT_MCU_STM32C5
+ #define FSDEV_STM32_CPU_HZ 144000000U
+#endif
+
+// 11 cycles / 800ns = ~13750000 cycles per second, used to derive conservative FSDEV PMA delay defaults
+#ifndef CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT
+ #define CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT (FSDEV_STM32_CPU_HZ / 13750000U)
+#endif
+
+// 11 cycles / 6.4us = ~1718750 cycles per second, used to derive conservative FSDEV PMA delay defaults
+#ifndef CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT
+ #define CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT (FSDEV_STM32_CPU_HZ / 1718750U)
+#endif
+
+/**
+ * LDR from SP-relative: 2 cycles
+ * SUBS: 1 cycle
+ * STR to SP-relative: 2 cycles
+ * LDR from SP-relative: 2 cycles
+ * CMP: 1 cycle
+ * BNE:
+ * taken: 3 cycles total (often shown as 1 + pipeline refill)
+ * not taken: 1 cycle
+ * Total cycles if delay is needed: 11 cycles
+ */
+TU_ATTR_ALWAYS_INLINE static inline void fsdev_btable_workaround_delay(bool low_speed) {
+ volatile uint32_t cycle_count = low_speed ? CFG_TUSB_FSDEV_BTABLE_LS_DELAY_COUNT : CFG_TUSB_FSDEV_BTABLE_FS_DELAY_COUNT;
+ while (cycle_count > 0U) {
+ cycle_count--;
+ }
+}
+#endif
+
+//--------------------------------------------------------------------+
// Connect / Disconnect
//--------------------------------------------------------------------+
diff --git a/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c b/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c
index 18685dbdc..f9201651a 100644
--- a/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c
+++ b/src/portable/st/stm32_fsdev/hcd_stm32_fsdev.c
@@ -58,20 +58,6 @@
TU_VERIFY_STATIC(CFG_TUH_FSDEV_ENDPOINT_MAX <= 255, "currently only use 8-bit for index");
-#if CFG_TUSB_MCU == OPT_MCU_STM32H5
- #define CPU_FREQUENCY_MHZ 250U
-#elif CFG_TUSB_MCU == OPT_MCU_STM32U5
- #define CPU_FREQUENCY_MHZ 160U
-#elif CFG_TUSB_MCU == OPT_MCU_STM32U3
- #define CPU_FREQUENCY_MHZ 96U
-#elif CFG_TUSB_MCU == OPT_MCU_STM32G0
- #define CPU_FREQUENCY_MHZ 64U
-#elif CFG_TUSB_MCU == OPT_MCU_STM32C0
- #define CPU_FREQUENCY_MHZ 48U
-#else
- #error "CPU_FREQUENCY_MHZ not defined for this STM32 MCU"
-#endif
-
enum {
HCD_XFER_ERROR_MAX = 3,
HCD_XFER_NAK_MAX = 15,
@@ -165,35 +151,9 @@ static inline void channel_write_status(uint8_t ch_id, uint32_t ch_reg, tusb_dir
}
static inline uint16_t channel_get_rx_count(uint8_t ch_id) {
- /* https://www.st.com/resource/en/errata_sheet/es0561-stm32h503cbebkbrb-device-errata-stmicroelectronics.pdf
- * https://www.st.com/resource/en/errata_sheet/es0587-stm32u535xx-and-stm32u545xx-device-errata-stmicroelectronics.pdf
- * From H503/U535 errata: Buffer description table update completes after CTR interrupt triggers
- * Description:
- * - During OUT transfers, the correct transfer interrupt (CTR) is triggered a little before the last USB SRAM accesses
- * have completed. If the software responds quickly to the interrupt, the full buffer contents may not be correct.
- * Workaround:
- * - Software should ensure that a small delay is included before accessing the SRAM contents. This delay
- * should be 800 ns in Full Speed mode and 6.4 μs in Low Speed mode
- *
- * Note: this errata may also apply to G0, U5, H5 etc.
- *
- * We choose the delay count based on max CPU frequency (in MHz) to ensure the delay is at least the required time.
- */
-
uint32_t ch_reg = ch_read(ch_id);
- if (FSDEV_REG->ISTR & U_ISTR_LS_DCONN || ch_reg & U_EP_LSEP) {
- // Low speed mode: 6.4 us delay -> about 2 cycles per MHz
- volatile uint32_t cycle_count = CPU_FREQUENCY_MHZ * 2U;
- while (cycle_count > 0U) {
- cycle_count--; // each count take 3 cycles (1 for sub, jump, and compare)
- }
- } else {
- // Full speed mode: 800 ns delay -> about 0.25 cycles per MHz
- volatile uint32_t cycle_count = CPU_FREQUENCY_MHZ / 4U;
- while (cycle_count > 0U) {
- cycle_count--; // each count take 3 cycles (1 for sub, jump, and compare)
- }
- }
+ const bool is_low_speed = (FSDEV_REG->ISTR & U_ISTR_LS_DCONN) || (ch_reg & U_EP_LSEP);
+ fsdev_btable_workaround_delay(is_low_speed);
return btable_get_count(ch_id, BTABLE_BUF_RX);
}
@@ -237,11 +197,7 @@ bool hcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
// If DCON_STAT is already set, the controller sometimes misses the initial connection interrupt
if (FSDEV_REG->ISTR & U_ISTR_DCON_STAT) {
- // Wait DP/DM stabilize time
- volatile uint32_t cycle_count = CPU_FREQUENCY_MHZ / 4U;
- while (cycle_count > 0U) {
- cycle_count--;
- }
+ tusb_time_delay_ms_api(2);
port_status_handler(rhport, false);
}
diff --git a/src/portable/synopsys/dwc2/dcd_dwc2.c b/src/portable/synopsys/dwc2/dcd_dwc2.c
index 9a9c734a0..e1a2f6cf2 100644
--- a/src/portable/synopsys/dwc2/dcd_dwc2.c
+++ b/src/portable/synopsys/dwc2/dcd_dwc2.c
@@ -73,8 +73,15 @@ typedef struct {
static dcd_data_t _dcd_data;
+// DMA receives up to 3 back-to-back SETUP packets (3 x 8 bytes), Slave mode only needs 1 packet (8 bytes)
+#if CFG_TUD_DWC2_DMA_ENABLE
+ #define DWC2_SETUP_BUFFER_SIZE 24
+#else
+ #define DWC2_SETUP_BUFFER_SIZE 8
+#endif
+
CFG_TUD_MEM_SECTION static struct {
- TUD_EPBUF_DEF(setup_packet, 8);
+ TUD_EPBUF_DEF(setup_buffer, DWC2_SETUP_BUFFER_SIZE);
} _dcd_usbbuf;
static tud_configure_dwc2_t _tud_cfg = CFG_TUD_CONFIGURE_DWC2_DEFAULT;
@@ -136,9 +143,9 @@ static void dma_setup_prepare(uint8_t rhport) {
}
}
- // Receive only 1 packet
- dwc2->epout[0].doeptsiz = (1 << DOEPTSIZ_STUPCNT_Pos) | (1 << DOEPTSIZ_PKTCNT_Pos) | (8 << DOEPTSIZ_XFRSIZ_Pos);
- dwc2->epout[0].doepdma = (uintptr_t) _dcd_usbbuf.setup_packet;
+ // Receive back-to-back setup packets
+ dwc2->epout[0].doeptsiz = (3 << DOEPTSIZ_STUPCNT_Pos);
+ dwc2->epout[0].doepdma = (uintptr_t) _dcd_usbbuf.setup_buffer;
dwc2->epout[0].doepctl |= DOEPCTL_EPENA | DOEPCTL_USBAEP;
}
@@ -191,7 +198,7 @@ static void dma_setup_prepare(uint8_t rhport) {
*/
TU_ATTR_ALWAYS_INLINE static inline uint16_t calc_device_grxfsiz(uint16_t largest_ep_size, uint8_t ep_count) {
- return 13 + 1 + 2 * ((largest_ep_size / 4) + 1) + 2 * ep_count;
+ return (uint16_t)(13 + 1 + 2 * ((largest_ep_size / 4) + 1) + 2 * ep_count);
}
static bool dfifo_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t packet_size, bool is_bulk) {
@@ -203,7 +210,7 @@ static bool dfifo_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t packet_size, b
TU_ASSERT(epnum < ep_count);
- uint16_t fifo_size = tu_div_ceil(packet_size, 4);
+ uint16_t fifo_size = (uint16_t)tu_div_ceil(packet_size, 4);
if (dir == TUSB_DIR_OUT) {
// Calculate required size of RX FIFO
const uint16_t new_sz = calc_device_grxfsiz(4 * fifo_size, ep_count);
@@ -371,7 +378,7 @@ static void edpt_schedule_packets(uint8_t rhport, const uint8_t epnum, const uin
num_packets = 1;
} else {
total_bytes = xfer->total_len;
- num_packets = tu_div_ceil(total_bytes, xfer->max_size);
+ num_packets = (uint16_t)tu_div_ceil(total_bytes, xfer->max_size);
if (num_packets == 0) {
num_packets = 1; // zero length packet still count as 1
}
@@ -541,8 +548,9 @@ void dcd_remote_wakeup(uint8_t rhport) {
void dcd_connect(uint8_t rhport) {
dwc2_regs_t* dwc2 = DWC2_REG(rhport);
-#ifdef TUP_USBIP_DWC2_ESP32
- // On ESP32-P4 HS PHY, do not write to USB_WRAP register which belongs to FS PHY
+#if defined(TUP_USBIP_DWC2_ESP32) && !TU_CHECK_MCU(OPT_MCU_ESP32S31)
+ // S31 is excluded at compile time (no USB_WRAP peripheral).
+ // On P4, the HS PHY (port 1) must not touch USB_WRAP which belongs to the FS PHY.
if (rhport == 0) {
usb_wrap_otg_conf_reg_t conf = USB_WRAP.otg_conf;
conf.pad_pull_override = 0;
@@ -560,8 +568,9 @@ void dcd_connect(uint8_t rhport) {
void dcd_disconnect(uint8_t rhport) {
dwc2_regs_t* dwc2 = DWC2_REG(rhport);
-#ifdef TUP_USBIP_DWC2_ESP32
- // On ESP32-P4 HS PHY, do not write to USB_WRAP register which belongs to FS PHY
+#if defined(TUP_USBIP_DWC2_ESP32) && !TU_CHECK_MCU(OPT_MCU_ESP32S31)
+ // S31 is excluded at compile time (no USB_WRAP peripheral).
+ // On P4, the HS PHY (port 1) must not touch USB_WRAP which belongs to the FS PHY.
if (rhport == 0) {
usb_wrap_otg_conf_reg_t conf = USB_WRAP.otg_conf;
conf.pad_pull_override = 1;
@@ -791,13 +800,15 @@ static void handle_bus_reset(uint8_t rhport) {
xfer_status[0][TUSB_DIR_OUT].max_size = CFG_TUD_ENDPOINT0_SIZE;
xfer_status[0][TUSB_DIR_IN].max_size = CFG_TUD_ENDPOINT0_SIZE;
+ uint32_t gintmsk = GINTMSK_OTGINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM;
if(dma_device_enabled(dwc2)) {
+ gintmsk |= GINTMSK_OEPINT;
dma_setup_prepare(rhport);
} else {
dwc2->epout[0].doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos);
}
- dwc2->gintmsk |= GINTMSK_OTGINT | GINTMSK_OEPINT | GINTMSK_IEPINT | GINTMSK_IISOIXFRM;
+ dwc2->gintmsk |= gintmsk;
}
static void handle_enum_done(uint8_t rhport) {
@@ -881,31 +892,47 @@ static void handle_rxflvl_irq(uint8_t rhport) {
dwc2_regs_t* dwc2 = DWC2_REG(rhport);
const volatile uint32_t* rx_fifo = dwc2->fifo[0];
+ // DWC2 v3.10a (e.g. STM32L476) emits an extra EP0 RX_COMPLETE that is NOT a real OUT data transfer completion, in two
+ // situations - each flagged by a DOEPINT bit set on that word:
+ // - DOEPINT.STPKTRX (Setup Packet Received): pushed between SETUP_RX and SETUP_DONE of every control transfer.
+ // - DOEPINT.STSPHSRX (Status Phase Received for control write): pushed after the OUT data stage when the host
+ // starts the IN status phase.
+ // Both are dropped in the RX_COMPLETE case below, clearing the flag (W1C) so a latched STSPHSRX
+ // does not block the core from emitting the next SETUP_DONE. usbd still processes the real OUT data
+ // and queues the IN status ZLP itself - the core does not auto-complete the control-write status.
+ const bool quirk_v310a = (dwc2->gsnpsid == DWC2_CORE_REV_3_10a);
+
// Pop control word off FIFO
const dwc2_grxstsp_t grxstsp = {.value = dwc2->grxstsp};
+ const uint8_t packet_status = grxstsp.packet_status;
const uint8_t epnum = grxstsp.ep_ch_num;
dwc2_dep_t* epout = &dwc2->epout[epnum];
- switch (grxstsp.packet_status) {
+ switch (packet_status) {
case GRXSTS_PKTSTS_GLOBAL_OUT_NAK:
// Global OUT NAK: do nothing
break;
case GRXSTS_PKTSTS_SETUP_RX: {
// Setup packet received
- uint32_t* setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_packet;
+ uint32_t * setup = (uint32_t*)(uintptr_t) _dcd_usbbuf.setup_buffer;
// We can receive up to three setup packets in succession, but only the last one is valid.
setup[0] = (*rx_fifo);
setup[1] = (*rx_fifo);
break;
}
- case GRXSTS_PKTSTS_SETUP_DONE:
- // Setup packet done:
- // After popping this out, dwc2 asserts a DOEPINT_SETUP interrupt which is handled by handle_epout_irq()
+ case GRXSTS_PKTSTS_SETUP_DONE: {
+ // Pop this word causes the Setup interrupt
epout->doeptsiz |= (3 << DOEPTSIZ_STUPCNT_Pos);
+ epout->doepint = DOEPINT_SETUP | DOEPINT_STPKTRX; // Clear SETUP interrupt, required for core to re-write this control word
+ if (edpt_is_enabled(&dwc2->epin[0])) {
+ edpt_disable(rhport, 0x80, false);
+ }
+ dcd_event_setup_received(rhport, _dcd_usbbuf.setup_buffer, true);
break;
+ }
case GRXSTS_PKTSTS_RX_DATA: {
// Out packet received
@@ -933,41 +960,31 @@ static void handle_rxflvl_irq(uint8_t rhport) {
break;
}
- case GRXSTS_PKTSTS_RX_COMPLETE:
- // Out packet done
- // After this entry is popped from the receive FIFO, dwc2 asserts a Transfer Completed interrupt on
- // the specified OUT endpoint which will be handled by handle_epout_irq()
- break;
+ case GRXSTS_PKTSTS_RX_COMPLETE: {
+ // Pop this word causes the xfer complete interrupt
+ const uint32_t doepint = epout->doepint;
+ epout->doepint = DOEPINT_XFRC;
- default: break; // nothing to do
- }
-}
-
-static void handle_epout_slave(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepint_bm) {
- if (doepint_bm.setup_phase_done) {
- // Cleanup previous pending EP0 IN transfer if any
- dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0];
- if (edpt_is_enabled(epin0)) {
- edpt_disable(rhport, 0x80, false);
- }
- dcd_event_setup_received(rhport, _dcd_usbbuf.setup_packet, true);
- return;
- }
+ // v3.10a quirk (see top of function): the extra RX_COMPLETE flagged with Setup Packet Received (STPKTRX) or
+ // Status Phase Received for control write (STSPHSRX) is not a real OUT completion. Drop it
+ if (quirk_v310a) {
+ if (doepint & (DOEPINT_STPKTRX | DOEPINT_STSPHSRX)) {
+ epout->doepint = DOEPINT_STPKTRX | DOEPINT_STSPHSRX;
+ break;
+ }
+ }
- // Normal OUT transfer complete
- if (doepint_bm.xfer_complete) {
- // only handle data skip if it is setup or status related
- // Note: even though (xfer_complete + status_phase_rx) is for buffered DMA only, for STM32L47x (dwc2 v3.00a) they
- // can is set when GRXSTS_PKTSTS_SETUP_RX is popped therefore they can bet set before/together with setup_phase_done
- if (!doepint_bm.status_phase_rx && !doepint_bm.setup_packet_rx) {
xfer_ctl_t* xfer = XFER_CTL_BASE(epnum, TUSB_DIR_OUT);
- if ((epnum == 0) && _dcd_data.ep0_pending[TUSB_DIR_OUT]) {
- // EP0 can only handle one packet, Schedule another packet to be received.
- edpt_schedule_packets(rhport, epnum, TUSB_DIR_OUT);
+ if (epnum == 0 && _dcd_data.ep0_pending[TUSB_DIR_OUT] > 0) {
+ // EP0 can only handle one packet, schedule another packet to be received.
+ edpt_schedule_packets(rhport, 0, TUSB_DIR_OUT);
} else {
dcd_event_xfer_complete(rhport, epnum, xfer->total_len, XFER_RESULT_SUCCESS, true);
}
+ break;
}
+
+ default: break; // nothing to do
}
}
@@ -1006,13 +1023,23 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi
if (doepint_bm.setup_phase_done) {
// Cleanup previous pending EP0 IN transfer if any
- dwc2_dep_t* epin0 = &DWC2_REG(rhport)->epin[0];
+ dwc2_dep_t* epin0 = &dwc2->epin[0];
+ dwc2_dep_t* epout0 = &dwc2->epout[0];
if (edpt_is_enabled(epin0)) {
edpt_disable(rhport, 0x80, false);
}
- dma_setup_prepare(rhport);
- dcd_dcache_invalidate(_dcd_usbbuf.setup_packet, 8);
- dcd_event_setup_received(rhport, _dcd_usbbuf.setup_packet, true);
+
+ dcd_dcache_invalidate(_dcd_usbbuf.setup_buffer, sizeof(_dcd_usbbuf.setup_buffer));
+
+ // DOEPDMA0 has advanced past the last received SETUP packet; back up one packet to the latest valid one
+ // (Programming Guide v4.20a section 9.1.2.1: "DOEPDMAn-8 provides the pointer to the last valid SETUP data")
+ tusb_control_request_t *setup_packet = (tusb_control_request_t *) (uintptr_t) (epout0->doepdma - sizeof(tusb_control_request_t));
+ dcd_event_setup_received(rhport, (uint8_t*)setup_packet, true);
+
+ // Prepare EP0 for next setup if this setup has no data stage
+ if (setup_packet->wLength == 0) {
+ dma_setup_prepare(rhport);
+ }
return;
}
@@ -1033,9 +1060,8 @@ static void handle_epout_dma(uint8_t rhport, uint8_t epnum, dwc2_doepint_t doepi
const uint16_t remain = tsiz.xfer_size;
xfer->total_len -= remain;
- // this is ZLP, so prepare EP0 for next setup
- // TODO use status phase rx
- if(epnum == 0 && xfer->total_len == 0) {
+ // prepare EP0 for next setup
+ if(epnum == 0) {
dma_setup_prepare(rhport);
}
@@ -1054,9 +1080,6 @@ static void handle_epin_dma(uint8_t rhport, uint8_t epnum, dwc2_diepint_t diepin
// EP0 can only handle one packet. Schedule another packet to be transmitted.
edpt_schedule_packets(rhport, epnum, TUSB_DIR_IN);
} else {
- if(epnum == 0) {
- dma_setup_prepare(rhport);
- }
dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, xfer->total_len, XFER_RESULT_SUCCESS, true);
}
}
@@ -1097,7 +1120,7 @@ static void handle_ep_irq(uint8_t rhport, uint8_t dir) {
if (dir == TUSB_DIR_IN) {
handle_epin_slave(rhport, epnum, intr.diepint_bm);
} else {
- handle_epout_slave(rhport, epnum, intr.doepint_bm);
+ // epout is handled in handle_rxflvl_irq
}
#endif
}
@@ -1134,8 +1157,9 @@ static void handle_incomplete_iso_in(uint8_t rhport) {
}
epin->diepctl = depctl.value;
} else {
- // too many retries, give up
+ // too many retries, give up, but keep endpoint activated
edpt_disable(rhport, epnum | TUSB_DIR_IN_MASK, false);
+ epin->diepctl |= DIEPCTL_USBAEP;
dcd_event_xfer_complete(rhport, epnum | TUSB_DIR_IN_MASK, 0, XFER_RESULT_FAILED, true);
}
}
@@ -1204,7 +1228,7 @@ void dcd_int_handler(uint8_t rhport) {
dwc2->gotgint = otg_int;
}
- if(gintsts & GINTSTS_SOF) {
+ if(gintsts & GINTSTS_SOF && dwc2->gintmsk & GINTMSK_SOFM) {
dwc2->gintsts = GINTSTS_SOF;
dwc2->gintmsk |= GINTMSK_USBSUSPM;
const uint32_t frame = (dwc2->dsts & DSTS_FNSOF) >> DSTS_FNSOF_Pos;
@@ -1217,6 +1241,12 @@ void dcd_int_handler(uint8_t rhport) {
dcd_event_sof(rhport, frame, true);
}
+ // IN endpoint interrupt handling.
+ if (gintsts & GINTSTS_IEPINT) {
+ // IEPINT bit read-only, clear using DIEPINTn
+ handle_ep_irq(rhport, TUSB_DIR_IN);
+ }
+
#if CFG_TUD_DWC2_SLAVE_ENABLE
// RxFIFO non-empty interrupt handling.
if (gintsts & GINTSTS_RXFLVL) {
@@ -1231,17 +1261,13 @@ void dcd_int_handler(uint8_t rhport) {
}
#endif
+#if CFG_TUD_DWC2_DMA_ENABLE
// OUT endpoint interrupt handling.
if (gintsts & GINTSTS_OEPINT) {
// OEPINT is read-only, clear using DOEPINTn
handle_ep_irq(rhport, TUSB_DIR_OUT);
}
-
- // IN endpoint interrupt handling.
- if (gintsts & GINTSTS_IEPINT) {
- // IEPINT bit read-only, clear using DIEPINTn
- handle_ep_irq(rhport, TUSB_DIR_IN);
- }
+#endif
// Incomplete isochronous IN transfer interrupt handling.
if (gintsts & GINTSTS_IISOIXFR) {
diff --git a/src/portable/synopsys/dwc2/dwc2_esp32.h b/src/portable/synopsys/dwc2/dwc2_esp32.h
index 6a10dc7f8..436f8dc30 100644
--- a/src/portable/synopsys/dwc2/dwc2_esp32.h
+++ b/src/portable/synopsys/dwc2/dwc2_esp32.h
@@ -37,7 +37,11 @@
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
+
+// ESP32-S31 does not have USB_WRAP peripheral (HS-only with UTMI PHY)
+#if !TU_CHECK_MCU(OPT_MCU_ESP32S31)
#include "soc/usb_wrap_struct.h"
+#endif
#if TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3)
#define DWC2_FS_REG_BASE 0x60080000UL
@@ -75,6 +79,14 @@ static const dwc2_controller_t _dwc2_controller[] = {
{ .reg_base = DWC2_FS_REG_BASE, .irqnum = ETS_USB_OTG11_CH0_INTR_SOURCE, .ep_count = 7, .ep_in_count = 5, .otg_dfifo_depth = 256 },
{ .reg_base = DWC2_HS_REG_BASE, .irqnum = ETS_USB_OTG_INTR_SOURCE, .ep_count = 16, .ep_in_count = 8, .otg_dfifo_depth = 1024 }
};
+
+#elif TU_CHECK_MCU(OPT_MCU_ESP32S31)
+#define DWC2_HS_REG_BASE 0x20300000UL
+#define DWC2_EP_MAX 16
+
+static const dwc2_controller_t _dwc2_controller[] = {
+ { .reg_base = DWC2_HS_REG_BASE, .irqnum = ETS_USB_OTGHS_INTR_SOURCE, .ep_count = 16, .ep_in_count = 8, .otg_dfifo_depth = 1024 }
+};
#endif
//--------------------------------------------------------------------+
diff --git a/src/portable/synopsys/dwc2/hcd_dwc2.c b/src/portable/synopsys/dwc2/hcd_dwc2.c
index 6098d6eaa..84a0c6afd 100644
--- a/src/portable/synopsys/dwc2/hcd_dwc2.c
+++ b/src/portable/synopsys/dwc2/hcd_dwc2.c
@@ -104,6 +104,7 @@ typedef struct {
uint16_t xferred_bytes; // bytes that accumulate transferred though USB bus for the whole hcd_edpt_xfer(), which can
// be composed of multiple channel_xfer_start() (retry with NAK/NYET)
uint16_t fifo_bytes; // bytes written/read from/to FIFO (may not be transferred on USB bus).
+ uint8_t retry_disabled; // 1: channel was disabled to throttle a split retry (NAK in / XactErr out); re-arm on its halt
} hcd_xfer_t;
typedef struct {
@@ -903,9 +904,6 @@ static void handle_rxflvl_irq(uint8_t rhport) {
// return true if there is still pending data and need more ISR
static bool handle_txfifo_empty(dwc2_regs_t* dwc2, bool is_periodic) {
- // Use period txsts for both p/np to get request queue space available (1-bit difference, it is small enough)
- const dwc2_hptxsts_t txsts = {.value = (is_periodic ? dwc2->hptxsts : dwc2->hnptxsts)};
-
const uint8_t max_channel = dwc2_channel_count(dwc2);
for (uint8_t ch_id = 0; ch_id < max_channel; ch_id++) {
dwc2_channel_t* channel = &dwc2->channel[ch_id];
@@ -923,6 +921,8 @@ static bool handle_txfifo_empty(dwc2_regs_t* dwc2, bool is_periodic) {
// skip if there is not enough space in FIFO and RequestQueue.
// Packet's last word written to FIFO will trigger a request queue
+ // Use period txsts for both p/np to get request queue space available (1-bit difference, it is small enough)
+ const dwc2_hptxsts_t txsts = {.value = (is_periodic ? dwc2->hptxsts : dwc2->hnptxsts)};
if ((xact_bytes > (txsts.fifo_available << 2)) || (txsts.req_queue_available == 0)) {
return true;
}
@@ -1138,7 +1138,16 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci
// TU_LOG1("in hcint = %02lX\r\n", hcint);
if (hcint & HCINT_HALTED) {
- if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL | HCINT_BABBLE_ERR)) {
+ if (xfer->retry_disabled) {
+ // Halt from our split-NAK throttle disable (below): re-arm the start-split, or let teardown finish
+ // if the endpoint is closing. Programming Guide 3.5 "Halting a Channel" (p73).
+ xfer->retry_disabled = 0;
+ if (xfer->closing) {
+ is_done = true;
+ } else {
+ channel_send_in_token(dwc2, channel);
+ }
+ } else if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL | HCINT_BABBLE_ERR)) {
const uint16_t remain_bytes = (uint16_t) hctsiz.xfer_size;
const uint16_t remain_packets = hctsiz.packet_count;
const uint16_t actual_len = edpt->buflen - remain_bytes;
@@ -1204,7 +1213,15 @@ static bool handle_channel_in_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hci
channel->hcintmsk &= ~(HCINT_NAK | HCINT_DATATOGGLE_ERR);
hcsplt.split_compl = 0; // restart with start-split
channel->hcsplt = hcsplt.value;
- channel_xfer_in_retry(dwc2, ch_id, hcint);
+ // Persistent split bulk/control IN NAK (e.g. idle polled endpoint): re-enabling immediately storms
+ // the ISR and starves the task. Disable + re-arm on the resulting halt to throttle (like the slave
+ // path); no frame deferral. Programming Guide 3.5 (p73) Note permits disable on NAK/FrmOvrn splits.
+ if ((hcint & HCINT_NAK) && hcsplt.split_en && !channel_is_periodic(channel->hcchar)) {
+ xfer->retry_disabled = 1;
+ channel_disable(dwc2, channel);
+ } else {
+ channel_xfer_in_retry(dwc2, ch_id, hcint);
+ }
} else if (hcint & HCINT_FARME_OVERRUN) {
// retry start-split in next binterval
channel_xfer_in_retry(dwc2, ch_id, hcint);
@@ -1229,7 +1246,16 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc
// TU_LOG1("out hcint = %02lX\r\n", hcint);
if (hcint & HCINT_HALTED) {
- if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL)) {
+ if (xfer->retry_disabled) {
+ // Halt from our split-XactErr throttle disable (below): re-issue the start-split (pointers already
+ // rewound), giving the hub TT a recovery gap. Programming Guide 3.5 "Halting a Channel" (p73).
+ xfer->retry_disabled = 0;
+ if (xfer->closing) {
+ is_done = true;
+ } else {
+ channel_xfer_start(dwc2, ch_id);
+ }
+ } else if (hcint & (HCINT_XFER_COMPLETE | HCINT_STALL)) {
is_done = true;
xfer->err_count = 0;
if (hcint & HCINT_XFER_COMPLETE) {
@@ -1252,9 +1278,17 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc
xfer->result = XFER_RESULT_FAILED;
is_done = true;
} else {
- // clean up transfer so far and start again
+ // Rewind, then retry the start-split. Non-periodic SPLIT throttles via channel_disable + re-arm on
+ // the halt (immediate re-fire exhausts the retry budget; the disable gives the hub TT a recovery
+ // gap, like slave). Periodic split is excluded: channel_disable() is a no-op for it, so the halt
+ // never fires and the channel would wedge. Non-split re-inits immediately (Programming Guide 5.1.2.3).
channel_xfer_out_wrapup(dwc2, ch_id);
- channel_xfer_start(dwc2, ch_id);
+ if (hcsplt.split_en && !channel_is_periodic(channel->hcchar)) {
+ xfer->retry_disabled = 1;
+ channel_disable(dwc2, channel);
+ } else {
+ channel_xfer_start(dwc2, ch_id);
+ }
}
}
} else if (hcint & HCINT_NYET) {
@@ -1272,6 +1306,12 @@ static bool handle_channel_out_dma(dwc2_regs_t* dwc2, uint8_t ch_id, uint32_t hc
channel->hcsplt = hcsplt.value;
channel->hcchar |= HCCHAR_CHENA;
}
+ } else if ((hcint & HCINT_NAK) && hcsplt.split_en) {
+ // Split OUT NAK: rewind + retry the start-split, else the channel stalls (Programming Guide 5.1.4.2).
+ // Non-split OUT NAK is core-handled (5.1.2.2), so this is split-only.
+ xfer->err_count = 0;
+ channel_xfer_out_wrapup(dwc2, ch_id);
+ channel_xfer_start(dwc2, ch_id);
}
if (xfer->closing == 1) {
diff --git a/src/portable/wch/ch32_usbfs_reg.h b/src/portable/wch/ch32_usbfs_reg.h
index 68be64f5e..415a015dc 100644
--- a/src/portable/wch/ch32_usbfs_reg.h
+++ b/src/portable/wch/ch32_usbfs_reg.h
@@ -39,64 +39,163 @@
#include <ch32f20x.h>
#elif CFG_TUSB_MCU == OPT_MCU_CH32V103
#include <ch32v10x.h>
+ // Newer-IP layout (separate UEPn_TX_CTRL/UEPn_RX_CTRL). The older IP (CH32V103) has a single
+ // combined control register at the UEPn_TX_CTRL offset, with UEPn_RX_CTRL reserved; the union
+ // exposes that same byte as UEPn_CTRL. Offsets are byte offsets from the peripheral base.
+ // TODO unify into a single struct shared by all WCH USBFS parts.
typedef struct
{
- __IO uint8_t BASE_CTRL;
- __IO uint8_t UDEV_CTRL;
- __IO uint8_t INT_EN;
- __IO uint8_t DEV_ADDR;
- __IO uint8_t Reserve0;
- __IO uint8_t MIS_ST;
- __IO uint8_t INT_FG;
- __IO uint8_t INT_ST;
- __IO uint32_t RX_LEN;
- __IO uint8_t UEP4_1_MOD;
- __IO uint8_t UEP2_3_MOD;
- __IO uint8_t UEP5_6_MOD;
- __IO uint8_t UEP7_MOD;
- __IO uint32_t UEP0_DMA;
- __IO uint32_t UEP1_DMA;
- __IO uint32_t UEP2_DMA;
- __IO uint32_t UEP3_DMA;
- __IO uint32_t UEP4_DMA;
- __IO uint32_t UEP5_DMA;
- __IO uint32_t UEP6_DMA;
- __IO uint32_t UEP7_DMA;
- __IO uint16_t UEP0_TX_LEN;
- __IO uint8_t UEP0_TX_CTRL;
- __IO uint8_t UEP0_RX_CTRL;
- __IO uint16_t UEP1_TX_LEN;
- __IO uint8_t UEP1_TX_CTRL;
- __IO uint8_t UEP1_RX_CTRL;
- __IO uint16_t UEP2_TX_LEN;
- __IO uint8_t UEP2_TX_CTRL;
- __IO uint8_t UEP2_RX_CTRL;
- __IO uint16_t UEP3_TX_LEN;
- __IO uint8_t UEP3_TX_CTRL;
- __IO uint8_t UEP3_RX_CTRL;
- __IO uint16_t UEP4_TX_LEN;
- __IO uint8_t UEP4_TX_CTRL;
- __IO uint8_t UEP4_RX_CTRL;
- __IO uint16_t UEP5_TX_LEN;
- __IO uint8_t UEP5_TX_CTRL;
- __IO uint8_t UEP5_RX_CTRL;
- __IO uint16_t UEP6_TX_LEN;
- __IO uint8_t UEP6_TX_CTRL;
- __IO uint8_t UEP6_RX_CTRL;
- __IO uint16_t UEP7_TX_LEN;
- __IO uint8_t UEP7_TX_CTRL;
- __IO uint8_t UEP7_RX_CTRL;
- __IO uint32_t Reserve1;
- __IO uint32_t OTG_CR;
- __IO uint32_t OTG_SR;
+ __IO uint8_t BASE_CTRL; // 0x00
+ __IO uint8_t UDEV_CTRL; // 0x01
+ __IO uint8_t INT_EN; // 0x02
+ __IO uint8_t DEV_ADDR; // 0x03
+ __IO uint8_t Reserve0; // 0x04
+ __IO uint8_t MIS_ST; // 0x05
+ __IO uint8_t INT_FG; // 0x06
+ __IO uint8_t INT_ST; // 0x07
+ __IO uint32_t RX_LEN; // 0x08
+ __IO uint8_t UEP4_1_MOD; // 0x0C
+ __IO uint8_t UEP2_3_MOD; // 0x0D
+ __IO uint8_t UEP5_6_MOD; // 0x0E
+ __IO uint8_t UEP7_MOD; // 0x0F
+ __IO uint32_t UEP0_DMA; // 0x10
+ __IO uint32_t UEP1_DMA; // 0x14
+ __IO uint32_t UEP2_DMA; // 0x18
+ __IO uint32_t UEP3_DMA; // 0x1C
+ __IO uint32_t UEP4_DMA; // 0x20
+ __IO uint32_t UEP5_DMA; // 0x24
+ __IO uint32_t UEP6_DMA; // 0x28
+ __IO uint32_t UEP7_DMA; // 0x2C
+ __IO uint16_t UEP0_TX_LEN; // 0x30
+ union {
+ __IO uint8_t UEP0_TX_CTRL;
+ __IO uint8_t UEP0_CTRL;
+ }; // 0x32 (TX_CTRL: IN | CTRL: combined)
+ __IO uint8_t UEP0_RX_CTRL; // 0x33 (OUT ctrl; reserved on combined IP)
+ __IO uint16_t UEP1_TX_LEN; // 0x34
+ union {
+ __IO uint8_t UEP1_TX_CTRL;
+ __IO uint8_t UEP1_CTRL;
+ }; // 0x36
+ __IO uint8_t UEP1_RX_CTRL; // 0x37
+ __IO uint16_t UEP2_TX_LEN; // 0x38
+ union {
+ __IO uint8_t UEP2_TX_CTRL;
+ __IO uint8_t UEP2_CTRL;
+ }; // 0x3A
+ __IO uint8_t UEP2_RX_CTRL; // 0x3B
+ __IO uint16_t UEP3_TX_LEN; // 0x3C
+ union {
+ __IO uint8_t UEP3_TX_CTRL;
+ __IO uint8_t UEP3_CTRL;
+ }; // 0x3E
+ __IO uint8_t UEP3_RX_CTRL; // 0x3F
+ __IO uint16_t UEP4_TX_LEN; // 0x40
+ union {
+ __IO uint8_t UEP4_TX_CTRL;
+ __IO uint8_t UEP4_CTRL;
+ }; // 0x42
+ __IO uint8_t UEP4_RX_CTRL; // 0x43
+ __IO uint16_t UEP5_TX_LEN; // 0x44
+ union {
+ __IO uint8_t UEP5_TX_CTRL;
+ __IO uint8_t UEP5_CTRL;
+ }; // 0x46
+ __IO uint8_t UEP5_RX_CTRL; // 0x47
+ __IO uint16_t UEP6_TX_LEN; // 0x48
+ union {
+ __IO uint8_t UEP6_TX_CTRL;
+ __IO uint8_t UEP6_CTRL;
+ }; // 0x4A
+ __IO uint8_t UEP6_RX_CTRL; // 0x4B
+ __IO uint16_t UEP7_TX_LEN; // 0x4C
+ union {
+ __IO uint8_t UEP7_TX_CTRL;
+ __IO uint8_t UEP7_CTRL;
+ }; // 0x4E
+ __IO uint8_t UEP7_RX_CTRL; // 0x4F
+ __IO uint32_t Reserve1; // 0x50
+ __IO uint32_t OTG_CR; // 0x54
+ __IO uint32_t OTG_SR; // 0x58
} USBOTG_FS_TypeDef;
#define USBOTG_FS ((USBOTG_FS_TypeDef *) 0x40023400)
+
+ // CH32V103 has the older USBFS IP: a single combined control register per endpoint
+ // (UEPn_CTRL) instead of separate TX_CTRL/RX_CTRL bytes. The struct's UEPn_TX_CTRL field
+ // aliases that combined register (same address); UEPn_RX_CTRL maps to unused padding.
+ #define CH32_USBFS_EP_CTRL_COMBINED 1
#elif CFG_TUSB_MCU == OPT_MCU_CH32V20X
#include <ch32v20x.h>
#elif CFG_TUSB_MCU == OPT_MCU_CH32V307
#include <ch32v30x.h>
#define USBHD_IRQn OTG_FS_IRQn
+#elif CFG_TUSB_MCU == OPT_MCU_CH583
+ #include "CH58x_common.h"
+ // CH582/583 USBFS device controller: same combined per-endpoint control register as
+ // CH32V103 (IN response bits[1:0], OUT response bits[3:2]) but a different register map -
+ // the EP control/length block sits lower (EP0_CTRL @ +0x22), EP5-7 are split out, EP4
+ // shares EP0's DMA buffer, and EP5/6/7 mode bits live in one UEP567_MOD. The control/status
+ // block matches CH32. Two FS controllers exist (USB @ 0x40008000, USB2 @ 0x40008400); the
+ // device uses USB0. Full register map per CH583/582 datasheet Table 17-2; the parameterized
+ // EP_* macros below index off these named fields.
+ #define CH58X_USBFS_BASE 0x40008000u
+ // Per-endpoint register slots, 4-byte stride each; the EP_* macros index arrays of these.
+ typedef struct {
+ __IO uint16_t DMA; // R16_UEPn_DMA: endpoint n buffer start address
+ __IO uint16_t reserved;
+ } ch58x_ep_dma_t;
+ typedef struct {
+ __IO uint8_t T_LEN; // R8_UEPn_T_LEN (+0): transmit length
+ __IO uint8_t reserved0;
+ __IO uint8_t CTRL; // R8_UEPn_CTRL (+2): endpoint control
+ __IO uint8_t reserved1;
+ } ch58x_ep_ctrl_t;
+ typedef struct {
+ __IO uint8_t BASE_CTRL; // 0x00 R8_USB_CTRL
+ __IO uint8_t UDEV_CTRL; // 0x01 R8_UDEV_CTRL
+ __IO uint8_t INT_EN; // 0x02 R8_USB_INT_EN
+ __IO uint8_t DEV_ADDR; // 0x03 R8_USB_DEV_AD
+ __IO uint8_t Reserve0; // 0x04
+ __IO uint8_t MIS_ST; // 0x05 R8_USB_MIS_ST
+ __IO uint8_t INT_FG; // 0x06 R8_USB_INT_FG
+ __IO uint8_t INT_ST; // 0x07 R8_USB_INT_ST
+ __IO uint8_t RX_LEN; // 0x08 R8_USB_RX_LEN (8-bit on CH58X)
+ __IO uint8_t Reserve1[3]; // 0x09..0x0B
+ __IO uint8_t UEP4_1_MOD; // 0x0C R8_UEP4_1_MOD
+ __IO uint8_t UEP2_3_MOD; // 0x0D R8_UEP2_3_MOD
+ __IO uint8_t UEP567_MOD; // 0x0E R8_UEP567_MOD
+ __IO uint8_t Reserve2; // 0x0F
+ ch58x_ep_dma_t EP_DMA_0_3[4]; // 0x10 EP0-3 DMA (EP4 has no DMA reg; it shares EP0's, index 0)
+ ch58x_ep_ctrl_t EP_CTRL_0_4[5]; // 0x20 EP0-4 length/control
+ __IO uint8_t Reserve3[0x54u - 0x34u]; // 0x34..0x53
+ ch58x_ep_dma_t EP_DMA_5_7[3]; // 0x54 EP5-7 DMA
+ __IO uint8_t Reserve4[0x64u - 0x60u]; // 0x60..0x63
+ ch58x_ep_ctrl_t EP_CTRL_5_7[3]; // 0x64 EP5-7 length/control
+ } USBOTG_FS_TypeDef;
+ #define USBOTG_FS ((USBOTG_FS_TypeDef *) CH58X_USBFS_BASE)
+
+ // 4-byte slot stride + these block offsets pin every EP register to its datasheet address.
+ TU_VERIFY_STATIC(sizeof(ch58x_ep_dma_t) == 4, "CH58x EP DMA slot must be 4 bytes");
+ TU_VERIFY_STATIC(sizeof(ch58x_ep_ctrl_t) == 4, "CH58x EP ctrl slot must be 4 bytes");
+ TU_VERIFY_STATIC(offsetof(USBOTG_FS_TypeDef, EP_DMA_0_3) == 0x10, "CH58x EP_DMA_0_3 @0x10");
+ TU_VERIFY_STATIC(offsetof(USBOTG_FS_TypeDef, EP_CTRL_0_4) == 0x20, "CH58x EP_CTRL_0_4 @0x20");
+ TU_VERIFY_STATIC(offsetof(USBOTG_FS_TypeDef, EP_DMA_5_7) == 0x54, "CH58x EP_DMA_5_7 @0x54");
+ TU_VERIFY_STATIC(offsetof(USBOTG_FS_TypeDef, EP_CTRL_5_7) == 0x64, "CH58x EP_CTRL_5_7 @0x64");
+
+ #define CH32_USBFS_EP_CTRL_COMBINED 1
+ // CH58x's hardware AUTO_TOG does not stay in sync (notably across clear-stall and multi-packet
+ // bulk transfers), causing data-toggle mismatch and bus resets. Drive the toggle manually in
+ // the ISR instead. CH32V103/V20x/V307 keep AUTO_TOG (this macro is undefined for them).
+ #define CH32_USBFS_EP_MANUAL_TOG 1
+ // CH58x EP4 has no DMA register of its own: it overlays EP0's DMA region as
+ // EP0[0:63] + EP4_OUT[64:127] + EP4_IN[128:191], so EP0 needs a 192-byte buffer.
+ #define CH32_USBFS_EP4_SHARES_EP0 1
+ #define USBHD_IRQn USB_IRQn
+ #ifndef NVIC_EnableIRQ
+ #define NVIC_EnableIRQ(n) PFIC_EnableIRQ(n)
+ #define NVIC_DisableIRQ(n) PFIC_DisableIRQ(n)
+ #endif
#endif
#ifdef __GNUC__
@@ -134,9 +233,14 @@
#define USBFS_INT_FG_TOG_OK (1 << 6)
#define USBFS_INT_FG_IS_NAK (1 << 7)
+// MIS_ST: the SUSPEND interrupt fires on both suspend and resume; this bit (R8_USB_MIS_ST) is 1
+// while the bus is suspended and 0 once it has resumed, so it tells the two apart.
+#define USBFS_MIS_ST_SUSPEND (1 << 2)
+
// INT_ST
#define USBFS_INT_ST_MASK_UIS_ENDP(x) (((x) >> 0) & 0x0F)
#define USBFS_INT_ST_MASK_UIS_TOKEN(x) (((x) >> 4) & 0x03)
+#define USBFS_INT_ST_TOG_OK (1 << 6) // received packet's data toggle matched expectation
// UDEV_CTRL
#define USBFS_UDEV_CTRL_PORT_EN (1 << 0)
@@ -166,6 +270,17 @@
#define USBFS_EP_R_RES_NAK (2 << 0)
#define USBFS_EP_R_RES_STALL (3 << 0)
+#ifdef CH32_USBFS_EP_CTRL_COMBINED
+// Combined per-endpoint control register (older IP, e.g. CH32V103): IN response in
+// bits [1:0], OUT response in bits [3:2], shared auto-toggle, separate IN/OUT toggle.
+#define USBFS_EPC_T_RES_MASK 0x03
+#define USBFS_EPC_R_RES_MASK 0x0C
+#define USBFS_EPC_R_RES_SHIFT 2
+#define USBFS_EPC_AUTO_TOG 0x10
+#define USBFS_EPC_T_TOG 0x40
+#define USBFS_EPC_R_TOG 0x80
+#endif
+
// token PID
#define PID_OUT 0
#define PID_SOF 1
diff --git a/src/portable/wch/dcd_ch32_usbfs.c b/src/portable/wch/dcd_ch32_usbfs.c
index 5cd25e33e..ece9cde07 100644
--- a/src/portable/wch/dcd_ch32_usbfs.c
+++ b/src/portable/wch/dcd_ch32_usbfs.c
@@ -29,84 +29,237 @@
#if CFG_TUD_ENABLED && defined(TUP_USBIP_WCH_USBFS) && CFG_TUD_WCH_USBIP_USBFS
-#include "device/dcd.h"
-#include "ch32_usbfs_reg.h"
+ #include "device/dcd.h"
+ #include "ch32_usbfs_reg.h"
-/* private defines */
-#define EP_MAX (8)
+ /* private defines */
+ #define EP_MAX (8)
-#define EP_DMA(ep) ((&USBOTG_FS->UEP0_DMA)[ep])
-#define EP_TX_LEN(ep) ((&USBOTG_FS->UEP0_TX_LEN)[2 * ep])
-#define EP_TX_CTRL(ep) ((&USBOTG_FS->UEP0_TX_CTRL)[4 * ep])
-#define EP_RX_CTRL(ep) ((&USBOTG_FS->UEP0_RX_CTRL)[4 * ep])
+ // Struct-based EP register access (uniform layout). CH58X has a different register map and
+ // defines EP_DMA/EP_TX_LEN/EP_CTRL itself in ch32_usbfs_reg.h.
+ #if CFG_TUSB_MCU == OPT_MCU_CH583
+ // CH58X EP registers split into a low block (EP0-4) and a high block (EP5-7). Walk from each
+ // block's first slot by the 4-byte slot stride (pointer arithmetic off slot 0, so the unused
+ // ternary branch's index can't trip -Warray-bounds). EP4 has no DMA register of its own (it
+ // shares EP0's, slot 0) and is never written (see ep_shares_ep0_dma()).
+ #define EP_TX_LEN(ep) (*((ep) <= 4u ? &USBOTG_FS->EP_CTRL_0_4[0].T_LEN + (ep) * 4u \
+ : &USBOTG_FS->EP_CTRL_5_7[0].T_LEN + ((ep) - 5u) * 4u))
+ #define EP_CTRL(ep) (*((ep) <= 4u ? &USBOTG_FS->EP_CTRL_0_4[0].CTRL + (ep) * 4u \
+ : &USBOTG_FS->EP_CTRL_5_7[0].CTRL + ((ep) - 5u) * 4u))
+ #define EP_DMA(ep) (*((ep) <= 3u ? &USBOTG_FS->EP_DMA_0_3[0].DMA + (ep) * 2u \
+ : (ep) == 4u ? &USBOTG_FS->EP_DMA_0_3[0].DMA \
+ : &USBOTG_FS->EP_DMA_5_7[0].DMA + ((ep) - 5u) * 2u))
+ #else
+ #define EP_DMA(ep) ((&USBOTG_FS->UEP0_DMA)[ep])
+ #define EP_TX_LEN(ep) ((&USBOTG_FS->UEP0_TX_LEN)[2 * ep])
+ #define EP_TX_CTRL(ep) ((&USBOTG_FS->UEP0_TX_CTRL)[4 * ep])
+ #define EP_RX_CTRL(ep) ((&USBOTG_FS->UEP0_RX_CTRL)[4 * ep])
+ #endif
+
+// Endpoint control register access. The newer USBFS IP (CH32V20x/V307/X035) has separate
+// TX_CTRL and RX_CTRL bytes per endpoint; the older IP (CH32V103) has a single combined
+// UEPn_CTRL register. These helpers hide the difference so the rest of the driver is shared.
+// Values use the newer-IP encoding (USBFS_EP_T_*/USBFS_EP_R_*); the combined path remaps them.
+#ifdef CH32_USBFS_EP_CTRL_COMBINED
+ #ifndef EP_CTRL // parts with a custom register map (CH58X) define EP_CTRL directly in reg.h
+ #define EP_CTRL(ep) EP_TX_CTRL(ep) // UEPn_TX_CTRL field aliases the combined UEPn_CTRL register
+ #endif
+
+ static inline uint8_t ep_tx_to_comb(uint8_t v) {
+ uint8_t c = v & USBFS_EP_T_RES_MASK; // IN response: bits [1:0] in both encodings
+ if (v & USBFS_EP_T_TOG) { c |= USBFS_EPC_T_TOG; }
+ if (v & USBFS_EP_T_AUTO_TOG) { c |= USBFS_EPC_AUTO_TOG; }
+ return c;
+ }
+ static inline uint8_t ep_rx_to_comb(uint8_t v) {
+ uint8_t c = (uint8_t) ((v & USBFS_EP_R_RES_MASK) << USBFS_EPC_R_RES_SHIFT); // OUT response -> bits [3:2]
+ if (v & USBFS_EP_R_TOG) { c |= USBFS_EPC_R_TOG; }
+ if (v & USBFS_EP_R_AUTO_TOG) { c |= USBFS_EPC_AUTO_TOG; }
+ return c;
+ }
+ // Set IN side (response/toggle/auto-tog), preserving the OUT response + OUT toggle.
+ static inline void ep_tx_ctrl_set(uint8_t ep, uint8_t v) {
+ EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & (USBFS_EPC_R_RES_MASK | USBFS_EPC_R_TOG)) | ep_tx_to_comb(v));
+ }
+ // Set OUT side, preserving the IN response + IN toggle.
+ static inline void ep_rx_ctrl_set(uint8_t ep, uint8_t v) {
+ EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & (USBFS_EPC_T_RES_MASK | USBFS_EPC_T_TOG)) | ep_rx_to_comb(v));
+ }
+ static inline void ep_tx_set_response(uint8_t ep, uint8_t res) {
+ EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & ~USBFS_EPC_T_RES_MASK) | (res & USBFS_EP_T_RES_MASK));
+ }
+ static inline void ep_rx_set_response(uint8_t ep, uint8_t res) {
+ EP_CTRL(ep) = (uint8_t) ((EP_CTRL(ep) & ~USBFS_EPC_R_RES_MASK) | ((res & USBFS_EP_R_RES_MASK) << USBFS_EPC_R_RES_SHIFT));
+ }
+ #define EP0_SETUP_RX_TOG USBFS_EP_R_TOG // combined IP: data/status stage after SETUP is DATA1
+#else
+ static inline void ep_tx_ctrl_set(uint8_t ep, uint8_t v) { EP_TX_CTRL(ep) = v; }
+ static inline void ep_rx_ctrl_set(uint8_t ep, uint8_t v) { EP_RX_CTRL(ep) = v; }
+ static inline void ep_tx_set_response(uint8_t ep, uint8_t res) {
+ EP_TX_CTRL(ep) = (uint8_t) ((EP_TX_CTRL(ep) & ~USBFS_EP_T_RES_MASK) | res);
+ }
+ static inline void ep_rx_set_response(uint8_t ep, uint8_t res) {
+ EP_RX_CTRL(ep) = (uint8_t) ((EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | res);
+ }
+ #define EP0_SETUP_RX_TOG 0
+#endif
+
+// Hardware auto data-toggle flag. Parts whose AUTO_TOG is reliable OR it into the EP setup so the
+// controller flips DATA0/DATA1 itself; CH58x (CH32_USBFS_EP_MANUAL_TOG) leaves it clear and the
+// ISR flips the toggle bit after each packet instead.
+#ifdef CH32_USBFS_EP_MANUAL_TOG
+ #define EP_T_AUTO_TOG 0
+ #define EP_R_AUTO_TOG 0
+#else
+ #define EP_T_AUTO_TOG USBFS_EP_T_AUTO_TOG
+ #define EP_R_AUTO_TOG USBFS_EP_R_AUTO_TOG
+#endif
/* private data */
struct usb_xfer {
- bool valid;
- uint8_t* buffer;
- size_t len;
- size_t processed_len;
- size_t max_size;
+ bool valid;
+ uint8_t *buffer;
+ size_t len;
+ size_t processed_len;
+ size_t max_size;
};
static struct {
- bool ep0_tog;
- bool isochronous[EP_MAX];
+ bool ep0_tog;
+ bool isochronous[EP_MAX];
struct usb_xfer xfer[EP_MAX][2];
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+ // CH58X buffers laid out by hand so EP0/EP4 don't burn two unused buffer[] slots. EP0 and EP4
+ // share one contiguous 192-byte DMA region (EP4 has no DMA register of its own):
+ // EP0 [0:63] (half-duplex OUT+IN) + EP4 OUT [64:127] + EP4 IN [128:191]. Every other endpoint
+ // (incl. EP3, which is bulk-only here — CH58X has no isochronous support) gets a plain 128-byte
+ // OUT+IN buffer, so no oversized EP3 buffer is needed.
+ TU_ATTR_ALIGNED(4) uint8_t ep0_ep4_buffer[3 * 64];
+ TU_ATTR_ALIGNED(4) uint8_t ep1_buffer[2][64];
+ TU_ATTR_ALIGNED(4) uint8_t ep2_buffer[2][64];
+ TU_ATTR_ALIGNED(4) uint8_t ep3_buffer[2][64];
+ TU_ATTR_ALIGNED(4) uint8_t ep5_buffer[2][64];
+ TU_ATTR_ALIGNED(4) uint8_t ep6_buffer[2][64];
+ TU_ATTR_ALIGNED(4) uint8_t ep7_buffer[2][64];
+#else
TU_ATTR_ALIGNED(4) uint8_t buffer[EP_MAX][2][64];
+ // EP3 IN gets an enlarged buffer for full-speed isochronous (packets up to 1023 B).
TU_ATTR_ALIGNED(4) struct {
// OUT transfers >64 bytes will overwrite queued IN data!
uint8_t out[64];
uint8_t in[1023];
uint8_t pad;
} ep3_buffer;
+#endif
} data;
+// DMA / copy buffer pointers per endpoint. The WCH USBFS buffer holds OUT (RX) at offset 0 and
+// IN (TX) at +64; EP0 is half-duplex and reuses its OUT chunk for IN; EP3 has an enlarged IN
+// buffer for throughput. On CH58X, EP0/EP4 share ep0_ep4_buffer and the regular endpoints use
+// their own named buffer (see the struct above).
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+// OUT base of the regular CH58X endpoints (EP1/2/3/5/6/7; EP0/EP4 share ep0_ep4_buffer).
+static inline uint8_t* ch58x_ep_buffer(uint8_t ep) {
+ switch (ep) {
+ case 1: return data.ep1_buffer[0];
+ case 2: return data.ep2_buffer[0];
+ case 3: return data.ep3_buffer[0];
+ case 5: return data.ep5_buffer[0];
+ case 6: return data.ep6_buffer[0];
+ default: return data.ep7_buffer[0]; // ep == 7
+ }
+}
+#endif
+
+static inline uint32_t ep_dma_addr(uint8_t ep) {
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+ if (ep == 0 || ep == 4) { return (uint32_t) &data.ep0_ep4_buffer[0]; } // EP4 shares EP0's DMA
+ return (uint32_t) ch58x_ep_buffer(ep);
+#else
+ if (ep == 3) { return (uint32_t) &data.ep3_buffer.out[0]; }
+ return (uint32_t) &data.buffer[ep][0];
+#endif
+}
+
+static inline uint8_t* ep_out_buf(uint8_t ep) {
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+ if (ep == 0) { return &data.ep0_ep4_buffer[0]; }
+ if (ep == 4) { return &data.ep0_ep4_buffer[64]; }
+ return ch58x_ep_buffer(ep);
+#else
+ if (ep == 3) { return data.ep3_buffer.out; }
+ return data.buffer[ep][TUSB_DIR_OUT];
+#endif
+}
+
+static inline uint8_t* ep_in_buf(uint8_t ep) {
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+ if (ep == 0) { return &data.ep0_ep4_buffer[0]; } // EP0 half-duplex: IN reuses OUT chunk
+ if (ep == 4) { return &data.ep0_ep4_buffer[128]; }
+ return ch58x_ep_buffer(ep) + 64; // IN at +64 within the endpoint's 128-byte buffer
+#else
+ if (ep == 0) { return data.buffer[0][TUSB_DIR_OUT]; } // EP0 half-duplex: IN reuses OUT chunk
+ if (ep == 3) { return data.ep3_buffer.in; }
+ return data.buffer[ep][TUSB_DIR_IN];
+#endif
+}
+
+// EP4 on CH58X has no DMA register (shares EP0's); skip its EP_DMA() write.
+static inline bool ep_shares_ep0_dma(uint8_t ep) {
+#ifdef CH32_USBFS_EP4_SHARES_EP0
+ return ep == 4;
+#else
+ (void) ep;
+ return false;
+#endif
+}
+
/* private helpers */
static void update_in(uint8_t rhport, uint8_t ep, bool force) {
- struct usb_xfer* xfer = &data.xfer[ep][TUSB_DIR_IN];
+ struct usb_xfer *xfer = &data.xfer[ep][TUSB_DIR_IN];
if (xfer->valid) {
if (force || xfer->len) {
size_t len = TU_MIN(xfer->max_size, xfer->len);
- if (ep == 0) {
- memcpy(data.buffer[ep][TUSB_DIR_OUT], xfer->buffer, len); // ep0 uses same chunk
- } else if (ep == 3) {
- memcpy(data.ep3_buffer.in, xfer->buffer, len);
- } else {
- memcpy(data.buffer[ep][TUSB_DIR_IN], xfer->buffer, len);
- }
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ // Every CH58x endpoint buffer is 64 bytes. Isochronous (which would push max_size up to 1023)
+ // is refused in dcd_edpt_iso_alloc(), but some classes (e.g. video) ignore that result, so cap
+ // the copy here to guarantee we never write past the buffer into a neighbouring endpoint's.
+ len = TU_MIN(len, 64u);
+#endif
+ memcpy(ep_in_buf(ep), xfer->buffer, len);
xfer->buffer += len;
xfer->len -= len;
xfer->processed_len += len;
EP_TX_LEN(ep) = len;
if (ep == 0) {
- EP_TX_CTRL(0) = USBFS_EP_T_RES_ACK | (data.ep0_tog ? USBFS_EP_T_TOG : 0);
- data.ep0_tog = !data.ep0_tog;
+ ep_tx_ctrl_set(0, USBFS_EP_T_RES_ACK | (data.ep0_tog ? USBFS_EP_T_TOG : 0));
+ data.ep0_tog = !data.ep0_tog;
} else if (data.isochronous[ep]) {
- EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_NYET;
+ ep_tx_set_response(ep, USBFS_EP_T_RES_NYET);
} else {
- EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_ACK;
+ ep_tx_set_response(ep, USBFS_EP_T_RES_ACK);
}
} else {
xfer->valid = false;
- EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK)) | USBFS_EP_T_RES_NAK;
- dcd_event_xfer_complete(
- rhport, ep | TUSB_DIR_IN_MASK, xfer->processed_len,
- XFER_RESULT_SUCCESS, true);
+ if (ep == 0) {
+ ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK | (data.ep0_tog ? USBFS_EP_T_TOG : 0));
+ } else if (!data.isochronous[ep]) {
+ ep_tx_set_response(ep, USBFS_EP_T_RES_NAK);
+ }
+ dcd_event_xfer_complete(rhport, ep | TUSB_DIR_IN_MASK, xfer->processed_len, XFER_RESULT_SUCCESS, true);
}
}
}
static void update_out(uint8_t rhport, uint8_t ep, size_t rx_len) {
- struct usb_xfer* xfer = &data.xfer[ep][TUSB_DIR_OUT];
+ struct usb_xfer *xfer = &data.xfer[ep][TUSB_DIR_OUT];
if (xfer->valid) {
size_t len = TU_MIN(xfer->max_size, TU_MIN(xfer->len, rx_len));
- if (ep == 3) {
- memcpy(xfer->buffer, data.ep3_buffer.out, len);
- } else {
- memcpy(xfer->buffer, data.buffer[ep][TUSB_DIR_OUT], len);
- }
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ len = TU_MIN(len, 64u); // cap to the 64-byte EP buffer (see update_in)
+#endif
+ memcpy(xfer->buffer, ep_out_buf(ep), len);
xfer->buffer += len;
xfer->len -= len;
xfer->processed_len += len;
@@ -117,41 +270,54 @@ static void update_out(uint8_t rhport, uint8_t ep, size_t rx_len) {
}
if (ep == 0) {
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
+ ep_rx_set_response(0, USBFS_EP_R_RES_NAK);
+ } else {
+ uint8_t rx_res =
+ data.isochronous[ep] ? USBFS_EP_R_RES_NYET : (xfer->valid ? USBFS_EP_R_RES_ACK : USBFS_EP_R_RES_NAK);
+ ep_rx_set_response(ep, rx_res);
}
}
}
+static void reset_ep_ctrls(void) {
+ for (uint8_t ep = 1; ep < EP_MAX; ep++) {
+ if (!ep_shares_ep0_dma(ep)) { EP_DMA(ep) = ep_dma_addr(ep); }
+ EP_TX_LEN(ep) = 0;
+ ep_tx_ctrl_set(ep, EP_T_AUTO_TOG | USBFS_EP_T_RES_NYET);
+ ep_rx_ctrl_set(ep, EP_R_AUTO_TOG | USBFS_EP_R_RES_NYET);
+ }
+}
+
/* public functions */
-bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
- (void) rh_init;
+bool dcd_init(uint8_t rhport, const tusb_rhport_init_t *rh_init) {
+ (void)rh_init;
// init registers
USBOTG_FS->BASE_CTRL = USBFS_CTRL_SYS_CTRL | USBFS_CTRL_INT_BUSY | USBFS_CTRL_DMA_EN;
USBOTG_FS->UDEV_CTRL = USBFS_UDEV_CTRL_PD_DIS | USBFS_UDEV_CTRL_PORT_EN;
- USBOTG_FS->DEV_ADDR = 0x00;
+ USBOTG_FS->DEV_ADDR = 0x00;
USBOTG_FS->INT_FG = 0xFF;
USBOTG_FS->INT_EN = USBFS_INT_EN_BUS_RST | USBFS_INT_EN_TRANSFER | USBFS_INT_EN_SUSPEND;
- // setup endpoint 0
- EP_DMA(0) = (uint32_t) &data.buffer[0][0];
- EP_TX_LEN(0) = 0;
- EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK;
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
+ // setup endpoint 0 (also backs EP4's buffer on CH58X via the shared DMA region)
+ EP_DMA(0) = ep_dma_addr(0);
+ EP_TX_LEN(0) = 0;
+ ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK);
+ ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK);
// enable other endpoints but NAK everything
USBOTG_FS->UEP4_1_MOD = 0xCC;
USBOTG_FS->UEP2_3_MOD = 0xCC;
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ // CH58X: a single mode register enables EP5/6/7 RX+TX (different bit layout than CH32).
+ USBOTG_FS->UEP567_MOD = RB_UEP5_RX_EN | RB_UEP5_TX_EN | RB_UEP6_RX_EN | RB_UEP6_TX_EN |
+ RB_UEP7_RX_EN | RB_UEP7_TX_EN;
+#else
USBOTG_FS->UEP5_6_MOD = 0xCC;
- USBOTG_FS->UEP7_MOD = 0x0C;
+ USBOTG_FS->UEP7_MOD = 0x0C;
+#endif
- for (uint8_t ep = 1; ep < EP_MAX; ep++) {
- EP_DMA(ep) = (uint32_t) &data.buffer[ep][0];
- EP_TX_LEN(ep) = 0;
- EP_TX_CTRL(ep) = USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK;
- EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK;
- }
- EP_DMA(3) = (uint32_t) &data.ep3_buffer.out[0];
+ reset_ep_ctrls();
dcd_connect(rhport);
@@ -159,196 +325,251 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
}
void dcd_int_handler(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
uint8_t status = USBOTG_FS->INT_FG;
if (status & USBFS_INT_FG_TRANSFER) {
- uint8_t ep = USBFS_INT_ST_MASK_UIS_ENDP(USBOTG_FS->INT_ST);
- uint8_t token = USBFS_INT_ST_MASK_UIS_TOKEN(USBOTG_FS->INT_ST);
+ uint8_t int_st = USBOTG_FS->INT_ST;
+ uint8_t ep = USBFS_INT_ST_MASK_UIS_ENDP(int_st);
+ uint8_t token = USBFS_INT_ST_MASK_UIS_TOKEN(int_st);
+ uint16_t rx_len = USBOTG_FS->RX_LEN;
switch (token) {
case PID_OUT: {
- uint16_t rx_len = USBOTG_FS->RX_LEN;
+ // Drop an OUT packet whose data toggle doesn't match what we expect -- a host retransmit
+ // after a lost ACK, or a host that doesn't alternate DATA0/DATA1. The hardware auto-toggle
+ // does not reject these on its own, so the check is needed on every variant. EP0 keeps its
+ // own toggle via the SETUP/status flow and is exempt.
+ if (ep != 0 && !(int_st & USBFS_INT_ST_TOG_OK)) { break; }
+#ifdef CH32_USBFS_EP_MANUAL_TOG
+ // CH58x has no hardware auto-toggle: advance the expected RX toggle after each accepted packet
+ // (EP0 included -- it also has no auto-toggle and a control-OUT data stage can span packets).
+ EP_CTRL(ep) ^= USBFS_EPC_R_TOG;
+#endif
update_out(rhport, ep, rx_len);
break;
}
case PID_IN:
+#ifdef CH32_USBFS_EP_MANUAL_TOG
+ // Manual toggle: flip the TX toggle after each ACK'd IN packet (EP0 manages its own).
+ if (ep != 0) { EP_CTRL(ep) ^= USBFS_EPC_T_TOG; }
+#endif
update_in(rhport, ep, false);
break;
case PID_SETUP:
// setup clears stall
- EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK;
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
+ ep_tx_ctrl_set(0, USBFS_EP_T_RES_NAK);
+ data.ep0_tog = true;
+ // A new SETUP supersedes any control transfer still in flight; drop its stale EP0 state so a
+ // spurious EP0 IN/OUT can't run update_in()/update_out() against the previous request.
+ data.xfer[0][TUSB_DIR_OUT].valid = false;
+ data.xfer[0][TUSB_DIR_IN].valid = false;
+
+ uint8_t *ep0_out = ep_out_buf(0);
+ const tusb_control_request_t *setup = (const tusb_control_request_t *)ep0_out;
+ // EP0_SETUP_RX_TOG arms the data/status stage at DATA1 on the combined-control IP
+ ep_rx_ctrl_set(0, ((setup->wLength == 0) ? USBFS_EP_R_RES_ACK : USBFS_EP_R_RES_NAK) | EP0_SETUP_RX_TOG);
- data.ep0_tog = true;
- dcd_event_setup_received(rhport, &data.buffer[0][TUSB_DIR_OUT][0], true);
+ dcd_event_setup_received(rhport, ep0_out, true);
break;
}
USBOTG_FS->INT_FG = USBFS_INT_FG_TRANSFER;
} else if (status & USBFS_INT_FG_BUS_RST) {
- data.ep0_tog = true;
+ data.ep0_tog = true;
data.xfer[0][TUSB_DIR_OUT].max_size = 64;
- data.xfer[0][TUSB_DIR_IN].max_size = 64;
+ data.xfer[0][TUSB_DIR_IN].max_size = 64;
- //dcd_event_bus_reset(rhport, (USBOTG_FS->BASE_CTRL & USBFS_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL, true);
- dcd_event_bus_reset(rhport, (USBOTG_FS->UDEV_CTRL & USBFS_UDEV_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL, true);
+ // dcd_event_bus_reset(rhport, (USBOTG_FS->BASE_CTRL & USBFS_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL,
+ // true);
+ dcd_event_bus_reset(rhport, (USBOTG_FS->UDEV_CTRL & USBFS_UDEV_CTRL_LOW_SPEED) ? TUSB_SPEED_LOW : TUSB_SPEED_FULL,
+ true);
USBOTG_FS->DEV_ADDR = 0x00;
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
+ ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK);
+
+ reset_ep_ctrls();
USBOTG_FS->INT_FG = USBFS_INT_FG_BUS_RST;
} else if (status & USBFS_INT_FG_SUSPEND) {
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ // CH58x raises this single interrupt for both suspend and resume; MIS_ST's suspend bit tells
+ // them apart (set while suspended, clear once resumed) so tud_resume_cb() actually fires.
+ dcd_event_t event = {.rhport = rhport,
+ .event_id = (USBOTG_FS->MIS_ST & USBFS_MIS_ST_SUSPEND) ? DCD_EVENT_SUSPEND : DCD_EVENT_RESUME};
+#else
dcd_event_t event = {.rhport = rhport, .event_id = DCD_EVENT_SUSPEND};
+#endif
dcd_event_handler(&event, true);
USBOTG_FS->INT_FG = USBFS_INT_FG_SUSPEND;
}
}
void dcd_int_enable(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
NVIC_EnableIRQ(USBHD_IRQn);
}
void dcd_int_disable(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
NVIC_DisableIRQ(USBHD_IRQn);
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr) {
- (void) dev_addr;
+ (void)dev_addr;
dcd_edpt_xfer(rhport, 0x80, NULL, 0, false); // zlp status response
}
void dcd_remote_wakeup(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
// TODO optional
}
void dcd_connect(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
USBOTG_FS->BASE_CTRL |= USBFS_CTRL_DEV_PUEN;
}
void dcd_disconnect(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
USBOTG_FS->BASE_CTRL &= ~USBFS_CTRL_DEV_PUEN;
}
void dcd_sof_enable(uint8_t rhport, bool en) {
- (void) rhport;
- (void) en;
+ (void)rhport;
+ (void)en;
// TODO implement later
}
-void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const* request) {
- (void) rhport;
+void dcd_edpt0_status_complete(uint8_t rhport, const tusb_control_request_t *request) {
+ (void)rhport;
if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE &&
- request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD &&
- request->bRequest == TUSB_REQ_SET_ADDRESS) {
- USBOTG_FS->DEV_ADDR = (uint8_t) request->wValue;
+ request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && request->bRequest == TUSB_REQ_SET_ADDRESS) {
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ // On CH58x R8_USB_DEV_AD bit 7 is a user general-purpose flag; only bits [6:0] are the address.
+ USBOTG_FS->DEV_ADDR = (uint8_t)((USBOTG_FS->DEV_ADDR & 0x80u) | (request->wValue & 0x7Fu));
+#else
+ USBOTG_FS->DEV_ADDR = (uint8_t)request->wValue;
+#endif
}
- EP_TX_CTRL(0) = USBFS_EP_T_RES_NAK;
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
}
-bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_ep) {
- (void) rhport;
- uint8_t ep = tu_edpt_number(desc_ep->bEndpointAddress);
+bool dcd_edpt_open(uint8_t rhport, const tusb_desc_endpoint_t *desc_ep) {
+ (void)rhport;
+ uint8_t ep = tu_edpt_number(desc_ep->bEndpointAddress);
uint8_t dir = tu_edpt_dir(desc_ep->bEndpointAddress);
TU_ASSERT(ep < EP_MAX);
- data.isochronous[ep] = desc_ep->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS;
data.xfer[ep][dir].max_size = tu_edpt_packet_size(desc_ep);
if (ep != 0) {
+ // Opening clears the toggle to DATA0 (ep_*_ctrl_set writes the toggle bit clear since v has no
+ // R/T_TOG); with manual toggle EP_*_AUTO_TOG is 0 so the ISR owns subsequent toggling.
if (dir == TUSB_DIR_OUT) {
- if (data.isochronous[ep]) {
- EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_NYET;
- } else {
- EP_RX_CTRL(ep) = USBFS_EP_R_AUTO_TOG | USBFS_EP_R_RES_ACK;
- }
+ ep_rx_ctrl_set(ep, EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK);
} else {
- EP_TX_LEN(ep) = 0;
- EP_TX_CTRL(ep) = USBFS_EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK;
+ ep_tx_ctrl_set(ep, EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK);
}
}
return true;
}
void dcd_edpt_close_all(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
// TODO optional
}
bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet_size) {
- (void) rhport;
- (void) ep_addr;
+ (void)rhport;
+ (void)ep_addr;
(void)largest_packet_size;
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ // No isochronous support on CH58x: its 8-bit T_LEN caps a packet at 255B and the endpoints use
+ // plain 64-byte buffers, so accepting an iso max_size (up to 1023) would let update_in()/
+ // update_out() run off the end of the buffer into neighbouring ones. Refuse it outright.
return false;
+#else
+ uint8_t ep = tu_edpt_number(ep_addr);
+ uint8_t dir = tu_edpt_dir(ep_addr);
+
+ data.isochronous[ep] = true;
+ data.xfer[ep][dir].max_size = largest_packet_size;
+ return true;
+#endif
}
bool dcd_edpt_iso_activate(uint8_t rhport, const tusb_desc_endpoint_t *desc_ep) {
(void)rhport;
(void)desc_ep;
- return false;
+#if CFG_TUSB_MCU == OPT_MCU_CH583
+ return false; // CH58x has no isochronous support (see dcd_edpt_iso_alloc)
+#else
+ return true;
+#endif
}
-bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes, bool is_isr) {
- (void) is_isr;
- (void) rhport;
- uint8_t ep = tu_edpt_number(ep_addr);
+bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes, bool is_isr) {
+ (void)is_isr;
+ (void)rhport;
+ uint8_t ep = tu_edpt_number(ep_addr);
uint8_t dir = tu_edpt_dir(ep_addr);
- struct usb_xfer* xfer = &data.xfer[ep][dir];
+ struct usb_xfer *xfer = &data.xfer[ep][dir];
+ // Keep the IRQ masked across the whole arming sequence: update_in()/ep_rx_set_response() do a
+ // read-modify-write of the (combined) EP control register, which the ISR also RMWs to flip the
+ // manual data toggle; re-enabling before they run lets a transfer IRQ clobber that toggle.
dcd_int_disable(rhport);
- xfer->valid = true;
- xfer->buffer = buffer;
- xfer->len = total_bytes;
+ xfer->valid = true;
+ xfer->buffer = buffer;
+ xfer->len = total_bytes;
xfer->processed_len = 0;
- dcd_int_enable(rhport);
if (dir == TUSB_DIR_IN) {
update_in(rhport, ep, true);
+ } else {
+ uint8_t rx_res = data.isochronous[ep] ? USBFS_EP_R_RES_NYET : USBFS_EP_R_RES_ACK;
+ ep_rx_set_response(ep, rx_res);
}
+ dcd_int_enable(rhport);
return true;
}
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) {
- (void) rhport;
- uint8_t ep = tu_edpt_number(ep_addr);
+ (void)rhport;
+ uint8_t ep = tu_edpt_number(ep_addr);
uint8_t dir = tu_edpt_dir(ep_addr);
if (ep == 0) {
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(0) = USBFS_EP_R_RES_STALL;
+ ep_rx_ctrl_set(0, USBFS_EP_R_RES_STALL);
} else {
- EP_TX_LEN(0) = 0;
- EP_TX_CTRL(0) = USBFS_EP_T_RES_STALL;
+ EP_TX_LEN(0) = 0;
+ ep_tx_ctrl_set(0, USBFS_EP_T_RES_STALL);
}
} else {
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(ep) = (EP_RX_CTRL(ep) & ~USBFS_EP_R_RES_MASK) | USBFS_EP_R_RES_STALL;
+ ep_rx_set_response(ep, USBFS_EP_R_RES_STALL);
} else {
- EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~USBFS_EP_T_RES_MASK) | USBFS_EP_T_RES_STALL;
+ ep_tx_set_response(ep, USBFS_EP_T_RES_STALL);
}
}
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) {
- (void) rhport;
- uint8_t ep = tu_edpt_number(ep_addr);
+ (void)rhport;
+ uint8_t ep = tu_edpt_number(ep_addr);
uint8_t dir = tu_edpt_dir(ep_addr);
if (ep == 0) {
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(0) = USBFS_EP_R_RES_ACK;
+ ep_rx_ctrl_set(0, USBFS_EP_R_RES_ACK);
}
} else {
+ // clear-stall resets the toggle to DATA0 (USB spec); manual-toggle parts then re-sync via ISR
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(ep) = (EP_RX_CTRL(ep) & ~(USBFS_EP_R_RES_MASK | USBFS_EP_R_TOG)) | USBFS_EP_R_RES_ACK;
+ ep_rx_ctrl_set(ep, EP_R_AUTO_TOG | USBFS_EP_R_RES_NAK);
} else {
- EP_TX_CTRL(ep) = (EP_TX_CTRL(ep) & ~(USBFS_EP_T_RES_MASK | USBFS_EP_T_TOG)) | USBFS_EP_T_RES_NAK;
+ ep_tx_ctrl_set(ep, EP_T_AUTO_TOG | USBFS_EP_T_RES_NAK);
}
}
}
diff --git a/src/portable/wch/dcd_ch32_usbhs.c b/src/portable/wch/dcd_ch32_usbhs.c
index 11734de37..ea3b052ad 100644
--- a/src/portable/wch/dcd_ch32_usbhs.c
+++ b/src/portable/wch/dcd_ch32_usbhs.c
@@ -24,7 +24,6 @@
*
* This file is part of the TinyUSB stack.
*/
-
#include "tusb_option.h"
#if CFG_TUD_ENABLED && defined(TUP_USBIP_WCH_USBHS) && defined(CFG_TUD_WCH_USBIP_USBHS) && \
@@ -37,138 +36,182 @@
#define EP_MAX 16
typedef struct {
- uint8_t* buffer;
+ uint8_t *buffer;
uint16_t total_len;
uint16_t queued_len;
uint16_t max_size;
- bool is_last_packet;
- bool is_iso;
+ bool is_iso;
+ bool valid;
} xfer_ctl_t;
-typedef enum {
- EP_RESPONSE_ACK,
- EP_RESPONSE_NAK,
-} ep_response_list_t;
-
-#define XFER_CTL_BASE(_ep, _dir) &xfer_status[_ep][_dir]
+ #define XFER_CTL_BASE(_ep, _dir) &xfer_status[_ep][_dir]
static xfer_ctl_t xfer_status[EP_MAX][2];
-#define EP_TX_LEN(ep) *(volatile uint16_t *)((volatile uint16_t *)&(USBHSD->UEP0_TX_LEN) + (ep) * 2)
-#define EP_TX_CTRL(ep) *(volatile uint8_t *)((volatile uint8_t *)&(USBHSD->UEP0_TX_CTRL) + (ep) * 4)
-#define EP_RX_CTRL(ep) *(volatile uint8_t *)((volatile uint8_t *)&(USBHSD->UEP0_RX_CTRL) + (ep) * 4)
-#define EP_RX_MAX_LEN(ep) *(volatile uint16_t *)((volatile uint16_t *)&(USBHSD->UEP0_MAX_LEN) + (ep) * 2)
+ #define EP_TX_LEN(ep) *(volatile uint16_t *)((volatile uint16_t *)&(USBHSD->UEP0_TX_LEN) + (ep) * 2)
+ #define EP_TX_CTRL(ep) *(volatile uint8_t *)((volatile uint8_t *)&(USBHSD->UEP0_TX_CTRL) + (ep) * 4)
+ #define EP_RX_CTRL(ep) *(volatile uint8_t *)((volatile uint8_t *)&(USBHSD->UEP0_RX_CTRL) + (ep) * 4)
+ #define EP_RX_MAX_LEN(ep) *(volatile uint16_t *)((volatile uint16_t *)&(USBHSD->UEP0_MAX_LEN) + (ep) * 2)
-#define EP_TX_DMA_ADDR(ep) *(volatile uint32_t *)((volatile uint32_t *)&(USBHSD->UEP1_TX_DMA) + (ep - 1))
-#define EP_RX_DMA_ADDR(ep) *(volatile uint32_t *)((volatile uint32_t *)&(USBHSD->UEP1_RX_DMA) + (ep - 1))
+ #define EP_TX_DMA_ADDR(ep) *(volatile uint32_t *)((volatile uint32_t *)&(USBHSD->UEP1_TX_DMA) + (ep - 1))
+ #define EP_RX_DMA_ADDR(ep) *(volatile uint32_t *)((volatile uint32_t *)&(USBHSD->UEP1_RX_DMA) + (ep - 1))
/* Endpoint Buffer */
TU_ATTR_ALIGNED(4) static uint8_t ep0_buffer[CFG_TUD_ENDPOINT0_SIZE];
+static bool ep0_tog;
+static bool ep_data_tog[EP_MAX][2];
-static void ep_set_response_and_toggle(uint8_t ep_num, tusb_dir_t ep_dir, ep_response_list_t response_type) {
+static void set_ep_toggle(uint8_t ep_num, tusb_dir_t ep_dir, bool data1) {
if (ep_dir == TUSB_DIR_IN) {
- uint8_t response = (response_type == EP_RESPONSE_ACK) ? USBHS_EP_T_RES_ACK : USBHS_EP_T_RES_NAK;
- if (ep_num == 0) {
- if (response_type == EP_RESPONSE_ACK) {
- if (EP_TX_LEN(ep_num) == 0) {
- EP_TX_CTRL(ep_num) |= USBHS_EP_T_TOG_1;
- } else {
- EP_TX_CTRL(ep_num) ^= USBHS_EP_T_TOG_1;
- }
- }
- }
- if (xfer_status[ep_num][TUSB_DIR_IN].is_iso == true) {
- EP_TX_CTRL(ep_num) = USBHS_EP_T_AUTOTOG;
- } else {
- EP_TX_CTRL(ep_num) = (EP_TX_CTRL(ep_num) & ~(USBHS_EP_T_RES_MASK)) | response;
- }
+ EP_TX_CTRL(ep_num) = (EP_TX_CTRL(ep_num) & ~(USBHS_EP_T_TOG_MASK)) |
+ (data1 ? USBHS_EP_T_TOG_1 : USBHS_EP_T_TOG_0);
} else {
- uint8_t response = (response_type == EP_RESPONSE_ACK) ? USBHS_EP_R_RES_ACK : USBHS_EP_R_RES_NAK;
- if (ep_num == 0) {
- if (response_type == EP_RESPONSE_ACK) {
- if (xfer_status[ep_num][TUSB_DIR_OUT].queued_len == 0) {
- EP_RX_CTRL(ep_num) |= USBHS_EP_R_TOG_1;
- }
- } else {
- EP_RX_CTRL(ep_num) ^= USBHS_EP_R_TOG_1;
- }
- }
- EP_RX_CTRL(ep_num) = (EP_RX_CTRL(ep_num) & ~(USBHS_EP_R_RES_MASK)) | response;
+ EP_RX_CTRL(ep_num) = (EP_RX_CTRL(ep_num) & ~(USBHS_EP_R_TOG_MASK)) |
+ (data1 ? USBHS_EP_R_TOG_1 : USBHS_EP_R_TOG_0);
}
}
-static void xfer_data_packet(uint8_t ep_num, tusb_dir_t ep_dir, xfer_ctl_t* xfer) {
- if (ep_dir == TUSB_DIR_IN) {
- uint16_t remaining = xfer->total_len - xfer->queued_len;
- uint16_t next_tx_size = TU_MIN(remaining, xfer->max_size);
+static void queue_in_packet(uint8_t ep_num, xfer_ctl_t* xfer) {
+ uint16_t remaining = xfer->total_len - xfer->queued_len;
+ uint16_t tx_len = TU_MIN(remaining, xfer->max_size);
+
+ if (ep_num == 0) {
+ memcpy(ep0_buffer, &xfer->buffer[xfer->queued_len], tx_len);
+ } else {
+ EP_TX_DMA_ADDR(ep_num) = (uint32_t) &xfer->buffer[xfer->queued_len];
+ }
+
+ EP_TX_LEN(ep_num) = tx_len;
+ xfer->queued_len += tx_len;
+
+ if (ep_num == 0) {
+ EP_TX_CTRL(0) = USBHS_EP_T_RES_ACK | (ep0_tog ? USBHS_EP_T_TOG_1 : USBHS_EP_T_TOG_0);
+ ep0_tog = !ep0_tog;
+ } else if (xfer->is_iso) {
+ EP_TX_CTRL(ep_num) = (EP_TX_CTRL(ep_num) & ~(USBHS_EP_T_RES_MASK)) | USBHS_EP_T_RES_NYET;
+ } else {
+ set_ep_toggle(ep_num, TUSB_DIR_IN, ep_data_tog[ep_num][TUSB_DIR_IN]);
+ EP_TX_CTRL(ep_num) = (EP_TX_CTRL(ep_num) & ~(USBHS_EP_T_RES_MASK)) | USBHS_EP_T_RES_ACK;
+ }
+}
+
+static void queue_out_packet(uint8_t ep_num, xfer_ctl_t* xfer) {
+ uint16_t remaining = xfer->total_len - xfer->queued_len;
+ uint16_t rx_len = TU_MIN(remaining, xfer->max_size);
+
+ if (ep_num > 0) {
+ EP_RX_DMA_ADDR(ep_num) = (uint32_t) &xfer->buffer[xfer->queued_len];
+ EP_RX_MAX_LEN(ep_num) = rx_len;
+ }
+
+ if (ep_num == 0) {
+ EP_RX_CTRL(0) = (EP_RX_CTRL(0) & ~(USBHS_EP_R_RES_MASK)) | USBHS_EP_R_RES_ACK;
+ } else if (xfer->is_iso) {
+ EP_RX_CTRL(ep_num) = (EP_RX_CTRL(ep_num) & ~(USBHS_EP_R_RES_MASK)) | USBHS_EP_R_RES_NYET;
+ } else {
+ set_ep_toggle(ep_num, TUSB_DIR_OUT, ep_data_tog[ep_num][TUSB_DIR_OUT]);
+ EP_RX_CTRL(ep_num) = (EP_RX_CTRL(ep_num) & ~(USBHS_EP_R_RES_MASK)) | USBHS_EP_R_RES_ACK;
+ }
+}
+static void update_in(uint8_t rhport, uint8_t ep_num, bool force) {
+ xfer_ctl_t* xfer = XFER_CTL_BASE(ep_num, TUSB_DIR_IN);
+ if (!xfer->valid) {
+ return;
+ }
+
+ if (!force && ep_num != 0 && !xfer->is_iso) {
+ ep_data_tog[ep_num][TUSB_DIR_IN] = !ep_data_tog[ep_num][TUSB_DIR_IN];
+ }
+
+ if (force || (xfer->total_len > xfer->queued_len)) {
+ queue_in_packet(ep_num, xfer);
+ } else {
+ xfer->valid = false;
if (ep_num == 0) {
- memcpy(ep0_buffer, &xfer->buffer[xfer->queued_len], next_tx_size);
+ EP_TX_CTRL(0) = USBHS_EP_T_RES_NAK | (ep0_tog ? USBHS_EP_T_TOG_1 : USBHS_EP_T_TOG_0);
} else {
- EP_TX_DMA_ADDR(ep_num) = (uint32_t) &xfer->buffer[xfer->queued_len];
+ EP_TX_CTRL(ep_num) = (EP_TX_CTRL(ep_num) & ~(USBHS_EP_T_RES_MASK)) | USBHS_EP_T_RES_NAK;
}
+ dcd_event_xfer_complete(rhport, ep_num | TUSB_DIR_IN_MASK, xfer->queued_len, XFER_RESULT_SUCCESS, true);
+ }
+}
- EP_TX_LEN(ep_num) = next_tx_size;
- xfer->queued_len += next_tx_size;
- if (xfer->queued_len == xfer->total_len) {
- xfer->is_last_packet = true;
- }
- if (xfer->is_iso == true) {
- /* Enable EP to generate ISA_ACT interrupt */
- USBHSD->ENDP_CONFIG |= (USBHS_EP0_T_EN << ep_num);
- }
- } else { /* TUSB_DIR_OUT */
- uint16_t left_to_receive = xfer->total_len - xfer->queued_len;
- uint16_t max_possible_rx_size = TU_MIN(xfer->max_size, left_to_receive);
+static void update_out(uint8_t rhport, uint8_t ep_num, uint16_t rx_len) {
+ xfer_ctl_t* xfer = XFER_CTL_BASE(ep_num, TUSB_DIR_OUT);
+ if (!xfer->valid) {
+ return;
+ }
+
+ uint16_t remaining = xfer->total_len - xfer->queued_len;
+ uint16_t len = TU_MIN(rx_len, TU_MIN(remaining, xfer->max_size));
+
+ if (ep_num == 0) {
+ memcpy(&xfer->buffer[xfer->queued_len], ep0_buffer, len);
+ }
- if (max_possible_rx_size == left_to_receive) {
- xfer->is_last_packet = true;
+ xfer->queued_len += len;
+
+ if (ep_num != 0 && !xfer->is_iso) {
+ ep_data_tog[ep_num][TUSB_DIR_OUT] = !ep_data_tog[ep_num][TUSB_DIR_OUT];
+ }
+
+ if ((xfer->queued_len == xfer->total_len) || (len < xfer->max_size)) {
+ xfer->valid = false;
+ if (ep_num == 0) {
+ EP_RX_CTRL(0) = (EP_RX_CTRL(0) & ~(USBHS_EP_R_RES_MASK)) | USBHS_EP_R_RES_NAK;
}
+ dcd_event_xfer_complete(rhport, ep_num, xfer->queued_len, XFER_RESULT_SUCCESS, true);
+ }
- if (ep_num > 0) {
- EP_RX_DMA_ADDR(ep_num) = (uint32_t) &xfer->buffer[xfer->queued_len];
- EP_RX_MAX_LEN(ep_num) = max_possible_rx_size;
+ if (ep_num != 0) {
+ if (xfer->valid) {
+ queue_out_packet(ep_num, xfer);
+ } else {
+ uint8_t rx_res = xfer->is_iso ? USBHS_EP_R_RES_NYET : USBHS_EP_R_RES_NAK;
+ EP_RX_CTRL(ep_num) = (EP_RX_CTRL(ep_num) & ~(USBHS_EP_R_RES_MASK)) | rx_res;
}
}
- ep_set_response_and_toggle(ep_num, ep_dir, USBHS_EP_R_RES_ACK);
}
-bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
- (void) rhport;
- (void) rh_init;
+bool dcd_init(uint8_t rhport, const tusb_rhport_init_t *rh_init) {
+ (void)rhport;
+ (void)rh_init;
memset(&xfer_status, 0, sizeof(xfer_status));
+ memset(ep_data_tog, 0, sizeof(ep_data_tog));
+ ep0_tog = true;
USBHSD->HOST_CTRL = 0x00;
USBHSD->HOST_CTRL = USBHS_PHY_SUSPENDM;
USBHSD->CONTROL = 0;
-#if TUD_OPT_HIGH_SPEED
+ #if TUD_OPT_HIGH_SPEED
USBHSD->CONTROL = USBHS_DMA_EN | USBHS_INT_BUSY_EN | USBHS_HIGH_SPEED;
-#else
- #error OPT_MODE_FULL_SPEED not currently supported on CH32
+ #else
+ #error OPT_MODE_FULL_SPEED not currently supported on CH32
USBHSD->CONTROL = USBHS_DMA_EN | USBHS_INT_BUSY_EN | USBHS_FULL_SPEED;
-#endif
+ #endif
USBHSD->INT_EN = 0;
- USBHSD->INT_EN = USBHS_SETUP_ACT_EN | USBHS_TRANSFER_EN | USBHS_BUS_RST_EN | USBHS_SUSPEND_EN | USBHS_ISO_ACT_EN;
+ USBHSD->INT_EN = USBHS_SETUP_ACT_EN | USBHS_TRANSFER_EN | USBHS_BUS_RST_EN | USBHS_SUSPEND_EN;
USBHSD->ENDP_CONFIG = USBHS_EP0_T_EN | USBHS_EP0_R_EN;
- USBHSD->ENDP_TYPE = 0x00;
- USBHSD->BUF_MODE = 0x00;
+ USBHSD->ENDP_TYPE = 0x00;
+ USBHSD->BUF_MODE = 0x00;
for (int ep = 0; ep < EP_MAX; ep++) {
- EP_TX_LEN(ep) = 0;
- EP_TX_CTRL(ep) = USBHS_EP_T_AUTOTOG | USBHS_EP_T_RES_NAK;
- EP_RX_CTRL(ep) = USBHS_EP_R_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_TX_LEN(ep) = 0;
+ EP_TX_CTRL(ep) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ EP_RX_CTRL(ep) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
EP_RX_MAX_LEN(ep) = 0;
}
- USBHSD->UEP0_DMA = (uint32_t) ep0_buffer;
- USBHSD->UEP0_MAX_LEN = CFG_TUD_ENDPOINT0_SIZE;
+ USBHSD->UEP0_DMA = (uint32_t)ep0_buffer;
+ USBHSD->UEP0_MAX_LEN = CFG_TUD_ENDPOINT0_SIZE;
xfer_status[0][TUSB_DIR_OUT].max_size = CFG_TUD_ENDPOINT0_SIZE;
- xfer_status[0][TUSB_DIR_IN].max_size = CFG_TUD_ENDPOINT0_SIZE;
+ xfer_status[0][TUSB_DIR_IN].max_size = CFG_TUD_ENDPOINT0_SIZE;
USBHSD->DEV_AD = 0;
USBHSD->CONTROL |= USBHS_DEV_PU_EN;
@@ -177,22 +220,24 @@ bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
}
void dcd_int_enable(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
NVIC_EnableIRQ(USBHS_IRQn);
}
void dcd_int_disable(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
NVIC_DisableIRQ(USBHS_IRQn);
}
void dcd_edpt_close_all(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
+
+ memset(ep_data_tog, 0, sizeof(ep_data_tog));
for (size_t ep = 1; ep < EP_MAX; ep++) {
- EP_TX_LEN(ep) = 0;
- EP_TX_CTRL(ep) = USBHS_EP_T_AUTOTOG | USBHS_EP_T_RES_NAK;
- EP_RX_CTRL(ep) = USBHS_EP_R_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_TX_LEN(ep) = 0;
+ EP_TX_CTRL(ep) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ EP_RX_CTRL(ep) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
EP_RX_MAX_LEN(ep) = 0;
}
@@ -201,18 +246,18 @@ void dcd_edpt_close_all(uint8_t rhport) {
}
void dcd_set_address(uint8_t rhport, uint8_t dev_addr) {
- (void) dev_addr;
+ (void)dev_addr;
// Response with zlp status
dcd_edpt_xfer(rhport, 0x80, NULL, 0, false);
}
void dcd_remote_wakeup(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
}
void dcd_sof_enable(uint8_t rhport, bool en) {
- (void) rhport;
+ (void)rhport;
if (en) {
USBHSD->INT_EN |= USBHS_SOF_ACT_EN;
} else {
@@ -220,24 +265,19 @@ void dcd_sof_enable(uint8_t rhport, bool en) {
}
}
-void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const* request) {
- (void) rhport;
-
+void dcd_edpt0_status_complete(uint8_t rhport, const tusb_control_request_t *request) {
+ (void)rhport;
if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE &&
- request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD &&
- request->bRequest == TUSB_REQ_SET_ADDRESS) {
- USBHSD->DEV_AD = (uint8_t) request->wValue;
+ request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD && request->bRequest == TUSB_REQ_SET_ADDRESS) {
+ USBHSD->DEV_AD = (uint8_t)request->wValue;
}
-
- EP_TX_CTRL(0) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
- EP_RX_CTRL(0) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
}
-bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) {
- (void) rhport;
+bool dcd_edpt_open(uint8_t rhport, const tusb_desc_endpoint_t *desc_edpt) {
+ (void)rhport;
- uint8_t const ep_num = tu_edpt_number(desc_edpt->bEndpointAddress);
- tusb_dir_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
+ const uint8_t ep_num = tu_edpt_number(desc_edpt->bEndpointAddress);
+ const tusb_dir_t dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
TU_ASSERT(ep_num < EP_MAX);
@@ -245,13 +285,14 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) {
return true;
}
- xfer_ctl_t* xfer = XFER_CTL_BASE(ep_num, dir);
- xfer->max_size = tu_edpt_packet_size(desc_edpt);
+ xfer_ctl_t *xfer = XFER_CTL_BASE(ep_num, dir);
+ xfer->max_size = tu_edpt_packet_size(desc_edpt);
+ ep_data_tog[ep_num][dir] = false;
xfer->is_iso = (desc_edpt->bmAttributes.xfer == TUSB_XFER_ISOCHRONOUS);
if (dir == TUSB_DIR_OUT) {
USBHSD->ENDP_CONFIG |= (USBHS_EP0_R_EN << ep_num);
- EP_RX_CTRL(ep_num) = USBHS_EP_R_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_RX_CTRL(ep_num) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
if (xfer->is_iso == true) {
USBHSD->ENDP_TYPE |= (USBHS_EP0_R_TYP << ep_num);
}
@@ -259,31 +300,31 @@ bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const* desc_edpt) {
} else {
if (xfer->is_iso == true) {
USBHSD->ENDP_TYPE |= (USBHS_EP0_T_TYP << ep_num);
- } else {
- /* Enable all types except Isochronous to avoid ISO_ACT interrupt generation */
- USBHSD->ENDP_CONFIG |= (USBHS_EP0_T_EN << ep_num);
}
- EP_TX_LEN(ep_num) = 0;
- EP_TX_CTRL(ep_num) = USBHS_EP_T_AUTOTOG | USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ USBHSD->ENDP_CONFIG |= (USBHS_EP0_T_EN << ep_num);
+ EP_TX_LEN(ep_num) = 0;
+ EP_TX_CTRL(ep_num) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
}
return true;
}
void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr) {
- (void) rhport;
+ (void)rhport;
- uint8_t const ep_num = tu_edpt_number(ep_addr);
- tusb_dir_t const dir = tu_edpt_dir(ep_addr);
+ const uint8_t ep_num = tu_edpt_number(ep_addr);
+ const tusb_dir_t dir = tu_edpt_dir(ep_addr);
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(ep_num) = USBHS_EP_R_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_RX_CTRL(ep_num) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
EP_RX_MAX_LEN(ep_num) = 0;
+ ep_data_tog[ep_num][TUSB_DIR_OUT] = false;
USBHSD->ENDP_TYPE &= ~(USBHS_EP0_R_TYP << ep_num);
USBHSD->ENDP_CONFIG &= ~(USBHS_EP0_R_EN << ep_num);
- } else { // TUSB_DIR_IN
- EP_TX_CTRL(ep_num) = USBHS_EP_T_AUTOTOG | USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
- EP_TX_LEN(ep_num) = 0;
+ } else { // TUSB_DIR_IN
+ EP_TX_CTRL(ep_num) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ EP_TX_LEN(ep_num) = 0;
+ ep_data_tog[ep_num][TUSB_DIR_IN] = false;
USBHSD->ENDP_TYPE &= ~(USBHS_EP0_T_TYP << ep_num);
USBHSD->ENDP_CONFIG &= ~(USBHS_EP0_T_EN << ep_num);
}
@@ -305,128 +346,120 @@ bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const * desc_ep)
#endif
void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr) {
- (void) rhport;
+ (void)rhport;
- uint8_t const ep_num = tu_edpt_number(ep_addr);
- tusb_dir_t const dir = tu_edpt_dir(ep_addr);
+ const uint8_t ep_num = tu_edpt_number(ep_addr);
+ const tusb_dir_t dir = tu_edpt_dir(ep_addr);
if (dir == TUSB_DIR_OUT) {
EP_RX_CTRL(ep_num) = USBHS_EP_R_RES_STALL;
} else {
- EP_TX_LEN(0) = 0;
+ EP_TX_LEN(ep_num) = 0;
EP_TX_CTRL(ep_num) = USBHS_EP_T_RES_STALL;
}
}
void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) {
- (void) rhport;
+ (void)rhport;
- uint8_t const ep_num = tu_edpt_number(ep_addr);
- tusb_dir_t const dir = tu_edpt_dir(ep_addr);
+ const uint8_t ep_num = tu_edpt_number(ep_addr);
+ const tusb_dir_t dir = tu_edpt_dir(ep_addr);
if (dir == TUSB_DIR_OUT) {
- EP_RX_CTRL(ep_num) = USBHS_EP_R_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_RX_CTRL(ep_num) = USBHS_EP_R_RES_NAK | USBHS_EP_R_TOG_0;
+ ep_data_tog[ep_num][TUSB_DIR_OUT] = false;
} else {
- EP_TX_CTRL(ep_num) = USBHS_EP_T_AUTOTOG | USBHS_EP_R_RES_NAK;
+ EP_TX_CTRL(ep_num) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ ep_data_tog[ep_num][TUSB_DIR_IN] = false;
}
}
-bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes, bool is_isr) {
- (void) is_isr;
- (void) rhport;
- uint8_t const ep_num = tu_edpt_number(ep_addr);
- tusb_dir_t const dir = tu_edpt_dir(ep_addr);
+bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t *buffer, uint16_t total_bytes, bool is_isr) {
+ (void)is_isr;
+ (void)rhport;
+ const uint8_t ep_num = tu_edpt_number(ep_addr);
+ const tusb_dir_t dir = tu_edpt_dir(ep_addr);
+
+ xfer_ctl_t *xfer = XFER_CTL_BASE(ep_num, dir);
+ xfer->buffer = buffer;
+ xfer->total_len = total_bytes;
+ xfer->queued_len = 0;
+ xfer->valid = true;
- xfer_ctl_t* xfer = XFER_CTL_BASE(ep_num, dir);
- xfer->buffer = buffer;
- xfer->total_len = total_bytes;
- xfer->queued_len = 0;
- xfer->is_last_packet = false;
+ if (ep_num == 0 && dir == TUSB_DIR_OUT) {
+ if (total_bytes == 0) {
+ EP_RX_CTRL(0) = (EP_RX_CTRL(0) & ~(USBHS_EP_R_TOG_MASK)) | USBHS_EP_R_TOG_1;
+ } else {
+ EP_RX_CTRL(0) ^= USBHS_EP_R_TOG_1;
+ }
+ }
- xfer_data_packet(ep_num, dir, xfer);
+ if (dir == TUSB_DIR_IN) {
+ update_in(rhport, ep_num, true);
+ } else {
+ queue_out_packet(ep_num, xfer);
+ }
return true;
}
void dcd_int_handler(uint8_t rhport) {
- (void) rhport;
+ (void)rhport;
- uint8_t int_flag = USBHSD->INT_FG;
+ uint8_t int_flag = USBHSD->INT_FG;
uint8_t int_status = USBHSD->INT_ST;
- if (int_flag & (USBHS_ISO_ACT_FLAG | USBHS_TRANSFER_FLAG)) {
- uint8_t const token = int_status & MASK_UIS_TOKEN;
+ if (int_flag & USBHS_TRANSFER_FLAG) {
+ const uint8_t token = int_status & MASK_UIS_TOKEN;
+ const uint8_t ep_num = int_status & MASK_UIS_ENDP;
+ const uint16_t len = USBHSD->RX_LEN;
if (token == USBHS_TOKEN_PID_SOF) {
uint32_t frame_count = USBHSD->FRAME_NO & USBHS_FRAME_NO_NUM_MASK;
dcd_event_sof(rhport, frame_count, true);
- }else {
- uint8_t const ep_num = int_status & MASK_UIS_ENDP;
- tusb_dir_t const ep_dir = (token == USBHS_TOKEN_PID_IN) ? TUSB_DIR_IN : TUSB_DIR_OUT;
- uint8_t const ep_addr = tu_edpt_addr(ep_num, ep_dir);
- xfer_ctl_t* xfer = XFER_CTL_BASE(ep_num, ep_dir);
-
- if (token == USBHS_TOKEN_PID_OUT) {
- uint16_t rx_len = USBHSD->RX_LEN;
-
- if (ep_num == 0) {
- memcpy(&xfer->buffer[xfer->queued_len], ep0_buffer, rx_len);
- }
-
- xfer->queued_len += rx_len;
- if (rx_len < xfer->max_size) {
- xfer->is_last_packet = true;
- }
- } else if (token == USBHS_TOKEN_PID_IN) {
- if (xfer->is_iso && xfer->is_last_packet) {
- /* Disable EP to avoid ISO_ACT interrupt generation */
- USBHSD->ENDP_CONFIG &= ~(USBHS_EP0_T_EN << ep_num);
- } else {
- // Do nothing, no need to update xfer->is_last_packet, it is already updated in xfer_data_packet
- }
- }
-
- if (xfer->is_last_packet == true) {
- ep_set_response_and_toggle(ep_num, ep_dir, EP_RESPONSE_NAK);
- dcd_event_xfer_complete(0, ep_addr, xfer->queued_len, XFER_RESULT_SUCCESS, true);
- } else {
- /* prepare next part of packet to xref */
- xfer_data_packet(ep_num, ep_dir, xfer);
- }
+ } else if (token == USBHS_TOKEN_PID_OUT) {
+ update_out(rhport, ep_num, len);
+ } else if (token == USBHS_TOKEN_PID_IN) {
+ update_in(rhport, ep_num, false);
}
-
- USBHSD->INT_FG = (int_flag & (USBHS_ISO_ACT_FLAG | USBHS_TRANSFER_FLAG)); /* Clear flag */
+ USBHSD->INT_FG = (int_flag & USBHS_TRANSFER_FLAG); /* Clear flag */
} else if (int_flag & USBHS_SETUP_FLAG) {
- ep_set_response_and_toggle(0, TUSB_DIR_IN, EP_RESPONSE_NAK);
- ep_set_response_and_toggle(0, TUSB_DIR_OUT, EP_RESPONSE_NAK);
+ tusb_control_request_t const* setup =
+ (tusb_control_request_t const*) ep0_buffer;
+ ep0_tog = true;
+ EP_RX_CTRL(0) = (setup->wLength == 0) ? USBHS_EP_R_RES_ACK : USBHS_EP_R_RES_NAK;
+ EP_TX_CTRL(0) = USBHS_EP_T_RES_NAK;
+
dcd_event_setup_received(0, ep0_buffer, true);
USBHSD->INT_FG = USBHS_SETUP_FLAG; /* Clear flag */
} else if (int_flag & USBHS_BUS_RST_FLAG) {
// TODO CH32 does not detect actual speed at this time (should be known at end of reset)
// This interrupt probably triggered at start of bus reset
-// tusb_speed_t actual_speed;
-// switch(USBHSD->SPEED_TYPE & USBHS_SPEED_TYPE_MASK){
-// case USBHS_SPEED_TYPE_HIGH:
-// actual_speed = TUSB_SPEED_HIGH;
-// break;
-// case USBHS_SPEED_TYPE_FULL:
-// actual_speed = TUSB_SPEED_FULL;
-// break;
-// case USBHS_SPEED_TYPE_LOW:
-// actual_speed = TUSB_SPEED_LOW;
-// break;
-// default:
-// TU_ASSERT(0,);
-// break;
-// }
-// dcd_event_bus_reset(0, actual_speed, true);
+ // tusb_speed_t actual_speed;
+ // switch(USBHSD->SPEED_TYPE & USBHS_SPEED_TYPE_MASK){
+ // case USBHS_SPEED_TYPE_HIGH:
+ // actual_speed = TUSB_SPEED_HIGH;
+ // break;
+ // case USBHS_SPEED_TYPE_FULL:
+ // actual_speed = TUSB_SPEED_FULL;
+ // break;
+ // case USBHS_SPEED_TYPE_LOW:
+ // actual_speed = TUSB_SPEED_LOW;
+ // break;
+ // default:
+ // TU_ASSERT(0,);
+ // break;
+ // }
+ // dcd_event_bus_reset(0, actual_speed, true);
dcd_event_bus_reset(0, TUSB_SPEED_HIGH, true);
USBHSD->DEV_AD = 0;
- EP_RX_CTRL(0) = USBHS_EP_R_RES_ACK | USBHS_EP_R_TOG_0;
- EP_TX_CTRL(0) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
+ memset(ep_data_tog, 0, sizeof(ep_data_tog));
+ ep0_tog = true;
+ EP_RX_CTRL(0) = USBHS_EP_R_RES_ACK | USBHS_EP_R_TOG_0;
+ EP_TX_CTRL(0) = USBHS_EP_T_RES_NAK | USBHS_EP_T_TOG_0;
USBHSD->INT_FG = USBHS_BUS_RST_FLAG; /* Clear flag */
} else if (int_flag & USBHS_SUSPEND_FLAG) {
@@ -434,6 +467,9 @@ void dcd_int_handler(uint8_t rhport) {
dcd_event_handler(&event, true);
USBHSD->INT_FG = USBHS_SUSPEND_FLAG; /* Clear flag */
+ } else {
+ // Unhandled interrupt
+ USBHSD->INT_FG = int_flag; /* Clear all flags */
}
}
#endif
diff --git a/src/tinyusb.mk b/src/tinyusb.mk
index 169098016..365043927 100644
--- a/src/tinyusb.mk
+++ b/src/tinyusb.mk
@@ -3,7 +3,6 @@ TINYUSB_SRC_C += \
src/tusb.c \
src/common/tusb_fifo.c \
src/device/usbd.c \
- src/device/usbd_control.c \
src/typec/usbc.c \
src/class/audio/audio_device.c \
src/class/cdc/cdc_device.c \
@@ -11,6 +10,7 @@ TINYUSB_SRC_C += \
src/class/dfu/dfu_rt_device.c \
src/class/hid/hid_device.c \
src/class/midi/midi_device.c \
+ src/class/midi/midi2_device.c \
src/class/msc/msc_device.c \
src/class/mtp/mtp_device.c \
src/class/net/ecm_rndis_device.c \
@@ -24,5 +24,6 @@ TINYUSB_SRC_C += \
src/class/cdc/cdc_host.c \
src/class/hid/hid_host.c \
src/class/midi/midi_host.c \
+ src/class/midi/midi2_host.c \
src/class/msc/msc_host.c \
src/class/vendor/vendor_host.c \
diff --git a/src/tusb.c b/src/tusb.c
index 5e4422e41..634cbc10b 100644
--- a/src/tusb.c
+++ b/src/tusb.c
@@ -224,32 +224,31 @@ uint8_t const* tu_desc_find3(uint8_t const* desc, uint8_t const* end, uint8_t by
// Endpoint Helper for both Host and Device stack
//--------------------------------------------------------------------+
-bool tu_edpt_claim(tu_edpt_state_t* ep_state, osal_mutex_t mutex) {
+bool tu_edpt_claim(volatile uint8_t* ep_state, osal_mutex_t mutex) {
(void) mutex;
// pre-check to help reducing mutex lock
- TU_VERIFY(ep_state->busy == 0);
- TU_VERIFY(ep_state->claimed == 0);
+ TU_VERIFY((*ep_state & (TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED)) == 0);
(void) osal_mutex_lock(mutex, OSAL_TIMEOUT_WAIT_FOREVER);
// can only claim the endpoint if it is not busy and not claimed yet.
- bool const available = (ep_state->busy == 0) && (ep_state->claimed == 0);
+ bool const available = (*ep_state & (TU_EDPT_STATE_BUSY | TU_EDPT_STATE_CLAIMED)) == 0;
if (available) {
- ep_state->claimed = 1;
+ *ep_state |= TU_EDPT_STATE_CLAIMED;
}
(void) osal_mutex_unlock(mutex);
return available;
}
-bool tu_edpt_release(tu_edpt_state_t* ep_state, osal_mutex_t mutex) {
+bool tu_edpt_release(volatile uint8_t* ep_state, osal_mutex_t mutex) {
(void) mutex;
(void) osal_mutex_lock(mutex, OSAL_TIMEOUT_WAIT_FOREVER);
// can only release the endpoint if it is claimed and not busy
- bool const ret = (ep_state->claimed == 1) && (ep_state->busy == 0);
+ bool const ret = (*ep_state & (TU_EDPT_STATE_CLAIMED | TU_EDPT_STATE_BUSY)) == TU_EDPT_STATE_CLAIMED;
if (ret) {
- ep_state->claimed = 0;
+ *ep_state &= (uint8_t) ~TU_EDPT_STATE_CLAIMED;
}
(void) osal_mutex_unlock(mutex);
@@ -498,7 +497,7 @@ char const* const tu_str_std_request[] = {
};
char const* const tu_str_xfer_result[] = {
- "OK", "FAILED", "STALLED", "TIMEOUT"
+ "OK", "FAILED", "STALLED", "TIMEOUT", "ABORTED", "INVALID"
};
#endif
diff --git a/src/tusb.h b/src/tusb.h
index c80c8433c..aa6b461e5 100644
--- a/src/tusb.h
+++ b/src/tusb.h
@@ -63,6 +63,10 @@
#include "class/midi/midi_host.h"
#endif
+ #if CFG_TUH_MIDI2
+ #include "class/midi/midi2_host.h"
+ #endif
+
#if CFG_TUH_VENDOR
#include "class/vendor/vendor_host.h"
#endif
@@ -108,6 +112,10 @@
#include "class/midi/midi_device.h"
#endif
+ #if CFG_TUD_MIDI2
+ #include "class/midi/midi2_device.h"
+ #endif
+
#if CFG_TUD_VENDOR
#include "class/vendor/vendor_device.h"
#endif
diff --git a/src/tusb_option.h b/src/tusb_option.h
index dd7af76f6..b5457fe8a 100644
--- a/src/tusb_option.h
+++ b/src/tusb_option.h
@@ -98,6 +98,7 @@
#define OPT_MCU_STM32N6 319 ///< ST N6
#define OPT_MCU_STM32WBA 320 ///< ST WBA
#define OPT_MCU_STM32U3 321 ///< ST U3
+#define OPT_MCU_STM32C5 322 ///< ST C5
// Sony
#define OPT_MCU_CXD56 400 ///< SONY CXD56
@@ -134,6 +135,7 @@
#define OPT_MCU_ESP32C5 908 ///< Espressif ESP32-C5
#define OPT_MCU_ESP32C61 909 ///< Espressif ESP32-C61
#define OPT_MCU_ESP32H4 910 ///< Espressif ESP32-H4
+#define OPT_MCU_ESP32S31 911 ///< Espressif ESP32-S31
// Dialog
#define OPT_MCU_DA1469X 1000 ///< Dialog Semiconductor DA1469x
@@ -193,6 +195,8 @@
#define OPT_MCU_CH32F20X 2210 ///< WCH CH32F20x
#define OPT_MCU_CH32V20X 2220 ///< WCH CH32V20X
#define OPT_MCU_CH32V103 2230 ///< WCH CH32V103
+#define OPT_MCU_CH583 2240 ///< WCH CH583
+#define OPT_MCU_CH582 OPT_MCU_CH583 ///< WCH CH582 (alias, same USB IP as CH583)
// NXP LPC MCX
#define OPT_MCU_MCXN9 2300 ///< NXP MCX N9 Series
@@ -534,6 +538,18 @@
#define CFG_TUSB_OS OPT_OS_NONE
#endif
+// 1 when CFG_TUSB_OS provides a preemptive scheduler with distinct tasks
+// (FreeRTOS, Zephyr, ThreadX, etc.); 0 when the application is single-context
+// (bare-metal OS_NONE or Pico SDK). Sync host control xfers from the host
+// task are forbidden when this is 1.
+#ifndef CFG_TUSB_OS_HAS_SCHEDULER
+ #if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO
+ #define CFG_TUSB_OS_HAS_SCHEDULER 0
+ #else
+ #define CFG_TUSB_OS_HAS_SCHEDULER 1
+ #endif
+#endif
+
#ifndef CFG_TUSB_OS_INC_PATH
#ifndef CFG_TUSB_OS_INC_PATH_DEFAULT
#define CFG_TUSB_OS_INC_PATH_DEFAULT
@@ -645,6 +661,10 @@
#define CFG_TUD_MIDI 0
#endif
+#ifndef CFG_TUD_MIDI2
+ #define CFG_TUD_MIDI2 0
+#endif
+
#ifndef CFG_TUD_VENDOR
#define CFG_TUD_VENDOR 0
#endif
@@ -814,6 +834,22 @@
#define CFG_TUH_MIDI 0
#endif
+#ifndef CFG_TUH_MIDI2
+ #define CFG_TUH_MIDI2 0
+#endif
+
+#ifndef CFG_TUH_MIDI2_RX_BUFSIZE
+ #define CFG_TUH_MIDI2_RX_BUFSIZE TUH_EPSIZE_BULK_MAX
+#endif
+
+#ifndef CFG_TUH_MIDI2_TX_BUFSIZE
+ #define CFG_TUH_MIDI2_TX_BUFSIZE TUH_EPSIZE_BULK_MAX
+#endif
+
+#ifndef CFG_TUH_MIDI2_LOG_LEVEL
+ #define CFG_TUH_MIDI2_LOG_LEVEL CFG_TUH_LOG_LEVEL
+#endif
+
#ifndef CFG_TUH_MSC
#define CFG_TUH_MSC 0
#endif
diff --git a/test/fuzz/rules.mk b/test/fuzz/rules.mk
index 329dcce11..c14330312 100644
--- a/test/fuzz/rules.mk
+++ b/test/fuzz/rules.mk
@@ -23,7 +23,6 @@ SRC_C += \
src/tusb.c \
src/common/tusb_fifo.c \
src/device/usbd.c \
- src/device/usbd_control.c \
src/class/audio/audio_device.c \
src/class/cdc/cdc_device.c \
src/class/dfu/dfu_device.c \
diff --git a/test/hil/hfp.json b/test/hil/hfp.json
index 8ba7a8f44..bb146d2fc 100644
--- a/test/hil/hfp.json
+++ b/test/hil/hfp.json
@@ -15,6 +15,10 @@
{
"name": "stm32f746disco",
"uid": "210041000C51343237303334",
+ "variant": [
+ { "name": "stm32f746disco", "flags": "" },
+ { "name": "stm32f746disco-DMA", "flags": "-DCFG_TUD_DWC2_DMA_ENABLE=1 -DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
"tests": {
"device": true, "host": false, "dual": false
},
diff --git a/test/hil/hil_ci.sh b/test/hil/hil_ci.sh
index fa8bb0245..3ec907979 100644
--- a/test/hil/hil_ci.sh
+++ b/test/hil/hil_ci.sh
@@ -1,15 +1,24 @@
-#!/bin/bash
+#!/usr/bin/env bash
# Run HIL test remotely on ci.lan
# Usage: test/hil/hil_ci.sh [-b BOARD] [-t TEST] [extra hil_test.py args...]
# Example:
# test/hil/hil_ci.sh -b stm32f723disco
# test/hil/hil_ci.sh -b stm32f723disco -t host/cdc_msc_hid -r 1
+#
+# Env overrides: REMOTE, REMOTE_DIR, CONFIG (path to HIL config json),
+# ROOT_DIR (tinyusb checkout to test; defaults to the script's own checkout).
-set -e
+set -euo pipefail
+
+REMOTE=${REMOTE:-ci.lan}
+REMOTE_DIR=${REMOTE_DIR:-/tmp/tinyusb-hil}
+ROOT_DIR=${ROOT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}
+CONFIG=${CONFIG:-$ROOT_DIR/test/hil/tinyusb.json}
-REMOTE=ci.lan
-REMOTE_DIR=/tmp/tinyusb-hil
-SCRIPT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
+[[ -f "$ROOT_DIR/test/hil/hil_test.py" && -d "$ROOT_DIR/examples" ]] || {
+ echo "error: $ROOT_DIR does not look like a tinyusb checkout" >&2
+ exit 1
+}
# Parse -b BOARD from arguments to know which build to copy
BOARD=""
@@ -17,6 +26,7 @@ ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
-b)
+ [[ $# -ge 2 ]] || { echo "error: -b requires a BOARD argument" >&2; exit 1; }
BOARD="$2"
ARGS+=("$1" "$2")
shift 2
@@ -28,42 +38,98 @@ while [[ $# -gt 0 ]]; do
esac
done
-# Setup remote directory
+# Setup remote directory. Use `bash -s` + heredoc so REMOTE_DIR (user-overridable)
+# is passed as a positional parameter and never reinterpreted by the remote shell.
echo "==> Setting up remote $REMOTE:$REMOTE_DIR"
-ssh "$REMOTE" "rm -rf $REMOTE_DIR && mkdir -p $REMOTE_DIR/test/hil $REMOTE_DIR/examples"
+ssh "$REMOTE" bash -s -- "$REMOTE_DIR" <<'REMOTE'
+set -e
+rm -rf -- "$1"
+mkdir -p -- "$1/test/hil" "$1/examples"
+REMOTE
# Copy HIL test script and config
echo "==> Copying test scripts"
-scp -q "$SCRIPT_DIR/test/hil/hil_test.py" \
- "$SCRIPT_DIR/test/hil/pymtp.py" \
- "$SCRIPT_DIR/test/hil/tinyusb.json" \
+scp -q "$ROOT_DIR/test/hil/hil_test.py" \
+ "$ROOT_DIR/test/hil/pymtp.py" \
+ "$CONFIG" \
"$REMOTE:$REMOTE_DIR/test/hil/"
-# Copy only firmware binaries (elf/bin/hex), preserving directory structure
+# Copy only firmware binaries (elf/bin/hex) plus esptool metadata
+# (config.env + flash_args needed by the esptool flasher), preserving structure
copy_board_binaries() {
local src="$1"
- local board_name
- board_name=$(basename "$src")
- rsync -a --include='*/' --include='*.elf' --include='*.bin' --include='*.hex' --exclude='*' \
+ rsync -a --prune-empty-dirs \
+ --include='*/' --include='*.elf' --include='*.bin' --include='*.hex' \
+ --include='config.env' --include='flash_args' \
+ --exclude='*' \
"$src" "$REMOTE:$REMOTE_DIR/examples/"
}
if [ -n "$BOARD" ]; then
- BUILD_DIR="$SCRIPT_DIR/examples/cmake-build-$BOARD"
- if [ ! -d "$BUILD_DIR" ]; then
- echo "Error: build directory not found: $BUILD_DIR"
- echo "Build first with: cd examples && cmake -DBOARD=$BOARD -G Ninja -B cmake-build-$BOARD .. && cmake --build cmake-build-$BOARD"
+ # Copy the board's build dir plus its variant dirs. Variant names come from
+ # $CONFIG (they are not required to be prefixed with the board name); the
+ # cmake-build-<BOARD>-* glob is kept as a fallback for ad-hoc local builds.
+ # Collect only dirs that actually exist, deduplicated.
+ declare -A SEEN_DIRS=()
+ BUILD_DIRS=()
+ add_build_dir() {
+ [[ -d "$1" && -z "${SEEN_DIRS[$1]:-}" ]] || return 0
+ SEEN_DIRS[$1]=1
+ BUILD_DIRS+=("$1")
+ }
+ shopt -s nullglob
+ for d in "$ROOT_DIR"/examples/cmake-build-"$BOARD" "$ROOT_DIR"/examples/cmake-build-"$BOARD"-*; do
+ add_build_dir "$d"
+ done
+ shopt -u nullglob
+ while IFS= read -r v; do
+ add_build_dir "$ROOT_DIR/examples/cmake-build-$v"
+ done < <(python3 -c '
+import json, sys
+cfg = json.load(open(sys.argv[1]))
+for b in cfg.get("boards", []):
+ if b["name"] == sys.argv[2]:
+ for v in b.get("variant") or []:
+ print(v["name"])
+' "$CONFIG" "$BOARD")
+ if [ ${#BUILD_DIRS[@]} -eq 0 ]; then
+ echo "Error: no build directory found for $BOARD under $ROOT_DIR/examples/"
+ echo "Build first with: cd examples && cmake --preset $BOARD && cmake --build --preset $BOARD"
exit 1
fi
- echo "==> Copying binaries for $BOARD"
- copy_board_binaries "$BUILD_DIR"
+ echo "==> Copying binaries for $BOARD (${#BUILD_DIRS[@]} build dir(s))"
+ for d in "${BUILD_DIRS[@]}"; do
+ copy_board_binaries "$d"
+ done
else
echo "==> Copying all built binaries"
- for dir in "$SCRIPT_DIR"/examples/cmake-build-*/; do
- [ -d "$dir" ] && copy_board_binaries "$dir"
+ # Use `%/` parameter expansion to strip the trailing slash from the glob —
+ # rsync needs the bare dir name so the per-board cmake-build-<BOARD>/ subdir
+ # is preserved on the remote (hil_test.py looks up binaries by that path).
+ for dir in "$ROOT_DIR"/examples/cmake-build-*/; do
+ [ -d "$dir" ] && copy_board_binaries "${dir%/}"
done
fi
-# Run test
+# Run test. Use `bash -s` so REMOTE_DIR + ARGS reach the remote shell as positional
+# parameters; quoting and metacharacters in args are preserved.
+CONFIG_BASENAME="$(basename "$CONFIG")"
echo "==> Running HIL test on $REMOTE"
-ssh -t "$REMOTE" "cd $REMOTE_DIR && python3 -u test/hil/hil_test.py -B examples ${ARGS[*]} tinyusb.json"
+rc=0
+ssh "$REMOTE" bash -s -- "$REMOTE_DIR" "${ARGS[@]}" "test/hil/$CONFIG_BASENAME" <<'REMOTE' || rc=$?
+cd -- "$1"
+shift
+# Flasher CLIs live in the user bin dirs on ci.lan (esptool/idf in ~/.local/bin,
+# STM32CubeProgrammer's STM32_Programmer_CLI in ~/bin); the non-interactive shell
+# subprocess used for flashing doesn't source profile/rc, so add them explicitly.
+export PATH="$HOME/.local/bin:$HOME/bin:$PATH"
+python3 -u test/hil/hil_test.py -B examples "$@"
+REMOTE
+
+# Copy the generated report back to the local checkout (best-effort; the run's
+# exit code is preserved regardless of whether a report was produced).
+scp -q "$REMOTE:$REMOTE_DIR/hil_report.md" "$ROOT_DIR/hil_report.md" \
+ && echo "==> Report copied to $ROOT_DIR/hil_report.md" \
+ || echo "==> warning: no hil_report.md copied back" >&2
+
+exit $rc
diff --git a/test/hil/hil_ci_set_matrix.py b/test/hil/hil_ci_set_matrix.py
index ecd964d87..13f7f1882 100644
--- a/test/hil/hil_ci_set_matrix.py
+++ b/test/hil/hil_ci_set_matrix.py
@@ -3,45 +3,70 @@ import json
import os
+def _resolve_config_path(config_file):
+ if os.path.exists(config_file):
+ return config_file
+
+ script_relative = os.path.join(os.path.dirname(__file__), config_file)
+ if os.path.exists(script_relative):
+ return script_relative
+
+ raise FileNotFoundError(f'Config file not found: {config_file}')
+
+
def main():
parser = argparse.ArgumentParser()
- parser.add_argument('config_file', help='Configuration JSON file')
+ parser.add_argument('config_files', nargs='+', help='Configuration JSON file(s)')
args = parser.parse_args()
- config_file = args.config_file
-
- # if config file is not found, try to find it in the same directory as this script
- if not os.path.exists(config_file):
- config_file = os.path.join(os.path.dirname(__file__), config_file)
- with open(config_file) as f:
- config = json.load(f)
-
+ # Toolchain buckets must match the toolchains instantiated by the hil-build
+ # job in .github/workflows/build.yml. Keep all keys present (even if empty)
+ # so `fromJSON(hil_json)[toolchain]` always resolves to a list.
matrix = {
'arm-gcc': [],
+ 'riscv-gcc': [],
'esp-idf': []
}
- for board in config['boards']:
- name = board['name']
- flasher = board['flasher']
- if flasher['name'] == 'esptool':
- toolchain = 'esp-idf'
- else:
- toolchain = 'arm-gcc'
- build_board = f'-b {name}'
- if 'build' in board:
- if 'args' in board['build']:
- build_board += ' ' + ' '.join(f'-D{a}' for a in board['build']['args'])
- if 'flags_on' in board['build']:
- for f in board['build']['flags_on']:
- if f == '':
- matrix[toolchain].append(build_board)
- else:
- matrix[toolchain].append(f'{build_board} -f1 {f.replace(" ", " -f1 ")}')
+ seen = {toolchain: set() for toolchain in matrix}
+
+ def append_build_arg(toolchain, build_arg):
+ if build_arg not in seen[toolchain]:
+ seen[toolchain].add(build_arg)
+ matrix[toolchain].append(build_arg)
+
+ for config_file in args.config_files:
+ with open(_resolve_config_path(config_file)) as f:
+ config = json.load(f)
+
+ for board in config['boards']:
+ name = board['name']
+ flasher = board['flasher']
+ # esptool boards must build under esp-idf; others default to arm-gcc
+ # but may opt into another bucket via an explicit "toolchain" field
+ # (e.g. RISC-V boards like ch32v20x need "riscv-gcc").
+ if flasher['name'] == 'esptool':
+ toolchain = 'esp-idf'
else:
- matrix[toolchain].append(build_board)
- else:
- matrix[toolchain].append(build_board)
+ toolchain = board.get('toolchain', 'arm-gcc')
+
+ build_board = f'-b {name}'
+ if 'build' in board and 'args' in board['build']:
+ build_board += ' ' + ' '.join(f'-D{a}' for a in board['build']['args'])
+
+ # Each variant builds into cmake-build-<variant.name> with its own cmake
+ # -D defines and raw CFLAGS. No 'variant' -> a single build named after
+ # the board.
+ variants = board.get('variant') or [{'name': name, 'flags': ''}]
+ for v in variants:
+ arg = build_board
+ if v['name'] != name:
+ arg += f' --build-name {v["name"]}'
+ for d in v.get('defines', []):
+ arg += f' -D{d}'
+ for tok in v.get('flags', '').split():
+ arg += f' --cflag={tok}'
+ append_build_arg(toolchain, arg)
print(json.dumps(matrix))
diff --git a/test/hil/hil_test.py b/test/hil/hil_test.py
index d50a60894..07375c1ad 100755
--- a/test/hil/hil_test.py
+++ b/test/hil/hil_test.py
@@ -22,29 +22,37 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
+# Host setup (required: a missing tool fails its test rather than skipping it):
+# - System packages: sudo apt install mtools libmtp9 alsa-utils iperf
+# mtools - read_disk_file (device/cdc_msc, device/msc_dual_lun)
+# libmtp9 - pymtp ctypes load (device/mtp); Debian 13 uses libmtp9t64
+# alsa-utils - arecord (device/audio_test_freertos)
+# iperf - throughput tests (device/net_lwip_*)
+# - Python packages: pip install -r requirements.txt
+#
# udev rules :
# ACTION=="add", SUBSYSTEM=="tty", SUBSYSTEMS=="usb", MODE="0666", PROGRAM="/bin/sh -c 'echo $$ID_SERIAL_SHORT | rev | cut -c -8 | rev'", SYMLINK+="ttyUSB_%c.%s{bInterfaceNumber}"
# ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", ENV{ID_FS_USAGE}=="filesystem", MODE="0666", PROGRAM="/bin/sh -c 'echo $$ID_SERIAL_SHORT | rev | cut -c -8 | rev'", RUN{program}+="/usr/bin/systemd-mount --no-block --automount=yes --collect $devnode /media/blkUSB_%c.%s{bInterfaceNumber}"
import argparse
+import io
import os
import random
import re
+import select
import sys
import time
-import warnings
-
-# Suppress pkg_resources deprecation warning from fs module
-warnings.filterwarnings("ignore", message="pkg_resources is deprecated")
-# Suppress pyfatfs unclean unmount warning
-warnings.filterwarnings("ignore", message="Filesystem was not cleanly unmounted")
+import signal
+from contextlib import redirect_stdout
+from pathlib import Path
+from typing import Any, TypedDict, NotRequired, cast
import serial
import subprocess
import json
import glob
-from multiprocessing import Pool
-import fs
+from multiprocessing import Pool, Lock
+from multiprocessing import TimeoutError as MpTimeoutError
import hashlib
import ctypes
from pymtp import MTP
@@ -56,9 +64,97 @@ STATUS_OK = "\033[32mOK\033[0m"
STATUS_FAILED = "\033[31mFailed\033[0m"
STATUS_SKIPPED = "\033[33mSkipped\033[0m"
+# Plain (non-ANSI) cell symbols for the markdown matrix report (hil_report.md).
+# A missing binary is reported as skipped too.
+REPORT_CELL = {'pass': '✅', 'fail': '❌', 'skip': '⚪'}
+
verbose = False
test_only = []
+board_test = {}
build_dir = 'cmake-build'
+skip_flash = False
+print_lock = None
+
+
+def init_worker(lock):
+ global print_lock
+ print_lock = lock
+
+
+def log_line(msg: str) -> None:
+ out = sys.__stdout__ if sys.__stdout__ is not None else sys.stdout
+ if print_lock is not None:
+ with print_lock:
+ print(msg, file=out, flush=True)
+ else:
+ print(msg, file=out, flush=True)
+
+
+def compact_output(raw: str) -> str:
+ if not raw:
+ return ''
+ lines = [ln.strip() for ln in raw.replace('\r', '\n').split('\n') if ln.strip()]
+ return ' | '.join(lines)
+
+class FlasherCfg(TypedDict):
+ name: str
+ uid: str
+ args: str
+
+
+class AttachedDevCfg(TypedDict, total=False):
+ vid_pid: str
+ serial: str
+ is_cdc: bool
+ is_msc: bool
+ block_count: int
+ block_size: int
+
+
+class TestsCfg(TypedDict, total=False):
+ device: bool
+ dual: bool
+ host: bool
+ only: list[str]
+ skip: list[str]
+ dev_attached: list[AttachedDevCfg]
+
+
+class BuildCfg(TypedDict, total=False):
+ args: list[str]
+
+
+class VariantCfg(TypedDict, total=False):
+ name: str # build dir (cmake-build-<name>) and HIL report row
+ flags: str # raw CFLAGS, e.g. "-DCFG_TUD_DWC2_DMA_ENABLE=1"
+ defines: list[str] # cmake -D defines, e.g. ["RHPORT_DEVICE=1"] (vs flags which are compiler-only)
+
+
+class Board(TypedDict):
+ name: str
+ uid: str
+ tests: TestsCfg
+ flasher: FlasherCfg
+ build: NotRequired[BuildCfg]
+ variant: NotRequired[list[VariantCfg]]
+ toolchain: NotRequired[str] # CI build bucket override, e.g. "riscv-gcc" (consumed by hil_ci_set_matrix.py)
+
+
+class HilConfig(TypedDict):
+ boards: list[Board]
+
+CMD_TIMEOUT = int(os.getenv('HIL_CMD_TIMEOUT', '180'))
+POOL_TIMEOUT = int(os.getenv('HIL_POOL_TIMEOUT', '3000'))
+SERIAL_READ_TIMEOUT = float(os.getenv('HIL_SERIAL_READ_TIMEOUT', '5'))
+SERIAL_WRITE_TIMEOUT = float(os.getenv('HIL_SERIAL_WRITE_TIMEOUT', '10'))
+
+
+def cmd_stdout_text(out: Any) -> str:
+ if out is None:
+ return ''
+ if isinstance(out, bytes):
+ return out.decode('utf-8', errors='ignore')
+ return str(out)
WCH_RISCV_CONTENT = """
adapter driver wlinke
@@ -88,8 +184,8 @@ issue at github.com/hathach/tinyusb"
# -------------------------------------------------------------
# Path
# -------------------------------------------------------------
-OPENCOD_ADI_PATH = f'{os.getenv("HOME")}/app/openocd_adi'
-TINYUSB_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+OPENCOD_ADI_PATH = Path.home() / 'app' / 'openocd_adi'
+TINYUSB_ROOT = Path(__file__).resolve().parents[2]
# get usb serial by id
def get_serial_dev(id, vendor_str, product_str, ifnum):
@@ -116,13 +212,29 @@ def get_hid_dev(id, vendor_str, product_str, event):
return f'/dev/input/by-id/usb-{vendor_str}_{product_str}_{id}-{event}'
-def open_serial_dev(port):
+def get_alsa_capture_dev(id):
+ pattern = f'/dev/snd/by-id/usb-*_{id}-*'
+ for dev in glob.glob(pattern):
+ try:
+ link = os.path.basename(os.path.realpath(dev))
+ except OSError:
+ continue
+ m = re.match(r'controlC(\d+)', link)
+ if m:
+ return f'hw:{m.group(1)},0'
+ return None
+
+
+def open_serial_dev(port: str):
timeout = ENUM_TIMEOUT
ser = None
while timeout > 0:
if os.path.exists(port):
try:
- ser = serial.Serial(port, baudrate=115200, timeout=5)
+ # write_timeout: a wedged device otherwise blocks ser.write() forever,
+ # hanging the worker until the pool/job timeout kills the whole run
+ ser = serial.Serial(port, baudrate=115200, timeout=SERIAL_READ_TIMEOUT,
+ write_timeout=SERIAL_WRITE_TIMEOUT)
break
except serial.SerialException:
print(f'serial {port} not reaady {timeout} sec')
@@ -131,28 +243,39 @@ def open_serial_dev(port):
timeout -= 0.1
assert timeout > 0, f'Cannot open port f{port}' if os.path.exists(port) else f'Port {port} not existed'
+ assert ser is not None
return ser
-def read_disk_file(uid, lun, fname):
- # open_fs("fat://{dev}) require 'pip install pyfatfs'
+def serial_write_all(ser: serial.Serial, data: bytes):
+ # write_timeout is a total deadline for the whole call (pyserial keeps partial progress
+ # internally). A timeout means the device stopped draining — treat it as fatal: pyserial
+ # loses the partial-write count on raise, so retrying would duplicate bytes on the wire.
+ try:
+ ser.write(data)
+ except serial.SerialTimeoutException:
+ raise AssertionError(f'Serial write timeout after {SERIAL_WRITE_TIMEOUT:.1f}s')
+
+
+def read_disk_file(uid: str, lun: int, fname: str) -> bytes:
+ # Reads a file from a FAT volume on a block device without mounting it.
+ # Requires mtools: `apt install mtools` (no pip dependency).
dev = get_disk_dev(uid, 'TinyUSB', lun)
timeout = ENUM_TIMEOUT
+ last_err = None
while timeout > 0:
if os.path.exists(dev):
- fat = fs.open_fs(f'fat://{dev}?read_only=true')
try:
- with fat.open(fname, 'rb') as f:
- data = f.read()
- finally:
- fat.close()
- assert data, f'Cannot read file {fname} from {dev}'
- return data
+ data = subprocess.check_output(
+ ['mtype', '-i', dev, f'::/{fname}'], stderr=subprocess.PIPE)
+ assert data, f'Cannot read file {fname} from {dev}'
+ return data
+ except subprocess.CalledProcessError as e:
+ last_err = e.stderr.decode(errors='replace').strip()
time.sleep(1)
timeout -= 1
- assert timeout > 0, f'Storage {dev} not existed'
- return None
+ raise AssertionError(f'mtype failed on {dev}: {last_err}' if last_err else f'Storage {dev} not existed')
def open_mtp_dev(uid):
@@ -174,7 +297,7 @@ def open_mtp_dev(uid):
return None
-def get_printer_dev(id, vendor_str, product_str, ifnum):
+def get_printer_dev(id: str, vendor_str, product_str, ifnum: int):
"""Find /dev/usb/lpX by matching USB serial, vendor, product, and interface number via sysfs"""
vendor_str = vendor_str.replace(' ', '_') if vendor_str else ''
product_str = product_str.replace(' ', '_') if product_str else ''
@@ -188,7 +311,7 @@ def get_printer_dev(id, vendor_str, product_str, ifnum):
return None
-def open_printer_dev(id, vendor_str, product_str, ifnum):
+def open_printer_dev(id: str, vendor_str, product_str, ifnum: int) -> str:
"""Wait for printer device to enumerate and return its path"""
timeout = ENUM_TIMEOUT
while timeout > 0:
@@ -203,41 +326,77 @@ def open_printer_dev(id, vendor_str, product_str, ifnum):
# -------------------------------------------------------------
# Flashing firmware
# -------------------------------------------------------------
-def run_cmd(cmd, cwd=None):
- r = subprocess.run(cmd, cwd=cwd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+def run_cmd(cmd: str, cwd: str | None = None, timeout: int = CMD_TIMEOUT) -> subprocess.CompletedProcess:
+ popen_kwargs = {
+ 'cwd': cwd,
+ 'shell': True,
+ 'stdout': subprocess.PIPE,
+ 'stderr': subprocess.STDOUT,
+ 'text': True,
+ 'encoding': 'utf-8',
+ 'errors': 'replace',
+ }
+ if os.name != 'nt':
+ popen_kwargs['preexec_fn'] = os.setsid
+
+ p = subprocess.Popen(cmd, **popen_kwargs)
+ try:
+ out, _ = p.communicate(timeout=timeout)
+ r = subprocess.CompletedProcess(args=cmd, returncode=p.returncode, stdout=out)
+ except subprocess.TimeoutExpired as ex:
+ if os.name != 'nt':
+ try:
+ os.killpg(p.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ else:
+ p.kill()
+ out, _ = p.communicate()
+ timeout_out = ex.stdout or out or b''
+ title = f'COMMAND TIMEOUT ({timeout}s): {cmd}'
+ print()
+ if os.getenv('CI'):
+ print(f"::group::{title}")
+ print(cmd_stdout_text(timeout_out))
+ print(f"::endgroup::")
+ else:
+ print(title)
+ print(cmd_stdout_text(timeout_out))
+ return subprocess.CompletedProcess(args=cmd, returncode=124, stdout=timeout_out)
+
if r.returncode != 0:
title = f'COMMAND FAILED: {cmd}'
print()
if os.getenv('CI'):
print(f"::group::{title}")
- print(r.stdout.decode("utf-8"))
+ print(cmd_stdout_text(r.stdout))
print(f"::endgroup::")
else:
print(title)
- print(r.stdout.decode("utf-8"))
+ print(cmd_stdout_text(r.stdout))
elif verbose:
print(cmd)
- print(r.stdout.decode("utf-8"))
+ print(cmd_stdout_text(r.stdout))
return r
-def flash_jlink(board, firmware):
+def flash_jlink(board: Board, firmware: str) -> subprocess.CompletedProcess:
flasher = board['flasher']
script = ['halt', 'r', f'loadfile {firmware}.elf', 'r', 'go', 'exit']
- f_jlink = f'{board["name"]}_{os.path.basename(firmware)}.jlink'
- with open(f_jlink, 'w') as f:
+ f_jlink = Path(f'{board["name"]}_{Path(firmware).name}.jlink')
+ with f_jlink.open('w') as f:
f.writelines(f'{s}\n' for s in script)
ret = run_cmd(f'JLinkExe -USB {flasher["uid"]} {flasher["args"]} -if swd -JTAGConf -1,-1 -speed auto -NoGui 1 -ExitOnError 1 -CommandFile {f_jlink}')
- os.remove(f_jlink)
+ f_jlink.unlink(missing_ok=True)
return ret
-def reset_jlink(board):
+def reset_jlink(board: Board) -> subprocess.CompletedProcess:
flasher = board['flasher']
script = ['halt', 'r', 'go', 'exit']
- f_jlink = f'{board["name"]}_reset.jlink'
- if not os.path.exists(f_jlink):
- with open(f_jlink, 'w') as f:
+ f_jlink = Path(f'{board["name"]}_reset.jlink')
+ if not f_jlink.exists():
+ with f_jlink.open('w') as f:
f.writelines(f'{s}\n' for s in script)
ret = run_cmd(f'JLinkExe -USB {flasher["uid"]} {flasher["args"]} -if swd -JTAGConf -1,-1 -speed auto -NoGui 1 -ExitOnError 1 -CommandFile {f_jlink}')
return ret
@@ -300,16 +459,20 @@ def reset_openocd_wch(board):
return ret
-def flash_openocd_adi(board, firmware):
+def flash_openocd_adi(board: Board, firmware: str) -> subprocess.CompletedProcess:
flasher = board['flasher']
- ret = run_cmd(f'{OPENCOD_ADI_PATH}/src/openocd -c "adapter serial {flasher["uid"]}" -s {OPENCOD_ADI_PATH}/tcl '
+ openocd = OPENCOD_ADI_PATH / 'src' / 'openocd'
+ tcl_dir = OPENCOD_ADI_PATH / 'tcl'
+ ret = run_cmd(f'{openocd} -c "adapter serial {flasher["uid"]}" -s {tcl_dir} '
f'{flasher["args"]} -c "program {firmware}.elf reset exit"')
return ret
-def reset_openocd_adi(board):
+def reset_openocd_adi(board: Board) -> subprocess.CompletedProcess:
flasher = board['flasher']
- ret = run_cmd(f'{OPENCOD_ADI_PATH}/src/openocd -c "adapter serial {flasher["uid"]}" -s {OPENCOD_ADI_PATH}/tcl '
+ openocd = OPENCOD_ADI_PATH / 'src' / 'openocd'
+ tcl_dir = OPENCOD_ADI_PATH / 'tcl'
+ ret = run_cmd(f'{openocd} -c "adapter serial {flasher["uid"]}" -s {tcl_dir} '
f'{flasher["args"]} -c "program reset exit"')
return ret
@@ -328,17 +491,17 @@ def reset_wlink_rs(board):
return ret
-def flash_esptool(board, firmware):
+def flash_esptool(board: Board, firmware: str) -> subprocess.CompletedProcess:
flasher = board['flasher']
port = get_serial_dev(flasher["uid"], None, None, 0)
- fw_dir = os.path.dirname(f'{firmware}.bin')
- with open(f'{fw_dir}/config.env') as f:
+ fw_dir = Path(f'{firmware}.bin').parent
+ with (fw_dir / 'config.env').open() as f:
idf_target = json.load(f)['IDF_TARGET']
- with open(f'{fw_dir}/flash_args') as f:
+ with (fw_dir / 'flash_args').open() as f:
flash_args = f.read().strip().replace('\n', ' ')
command = (f'esptool --chip {idf_target} -p {port} {flasher["args"]} '
f'--before=default_reset --after=hard_reset write_flash {flash_args}')
- ret = run_cmd(command, cwd=fw_dir)
+ ret = run_cmd(command, cwd=str(fw_dir))
return ret
@@ -358,6 +521,19 @@ def reset_uniflash(board):
return subprocess.CompletedProcess(args=['dummy'], returncode=0)
+def flash_lm4flash(board, firmware):
+ # TI Tiva-C / Stellaris ICDI: lightweight lm4flash, resets and runs after write
+ flasher = board['flasher']
+ ret = run_cmd(f'lm4flash -s {flasher["uid"]} {flasher["args"]} {firmware}.bin')
+ return ret
+
+
+def reset_lm4flash(board):
+ # lm4flash has no reset-only mode; it resets+runs on flash, so reset is a no-op
+ flasher = board['flasher']
+ return subprocess.CompletedProcess(args=['dummy'], returncode=0)
+
+
# -------------------------------------------------------------
# Tests: dual
# -------------------------------------------------------------
@@ -562,8 +738,7 @@ def test_host_cdc_msc_hid(board):
offset = 0
while offset < echo_len:
chunk_size = min(random.randint(1, packet_size), echo_len - offset)
- ser.write(echo_data[offset:offset + chunk_size])
- ser.flush()
+ serial_write_all(ser, echo_data[offset:offset + chunk_size])
# wait until this chunk is echoed back
echo = b''
t_end = time.monotonic() + 1.0
@@ -612,8 +787,7 @@ def test_host_msc_file_explorer(board):
time.sleep(1)
ser.reset_input_buffer()
for ch in 'cat README.TXT\r':
- ser.write(ch.encode())
- ser.flush()
+ serial_write_all(ser, ch.encode())
time.sleep(0.002)
resp = b''
@@ -635,8 +809,7 @@ def test_host_msc_file_explorer(board):
time.sleep(0.5)
ser.reset_input_buffer()
for ch in 'dd 1024\r':
- ser.write(ch.encode())
- ser.flush()
+ serial_write_all(ser, ch.encode())
time.sleep(0.002)
# Read dd output until prompt
@@ -652,12 +825,21 @@ def test_host_msc_file_explorer(board):
t -= 0.05
resp_text = resp.decode('utf-8', errors='ignore')
+ speed = None
for line in resp_text.splitlines():
if 'KB/s' in line:
print(f'{line.strip()} ', end='')
+ m = re.search(r'([\d.]+\s*[KMG]B/s)', line) # MSC read speed for the report cell
+ if m:
+ speed = 'rd ' + m.group(1).replace(' ', '')
break
ser.close()
+ return speed
+
+
+def test_host_msc_file_explorer_freertos(board):
+ return test_host_msc_file_explorer(board)
# -------------------------------------------------------------
@@ -681,7 +863,7 @@ def test_device_cdc_dual_ports(board):
sizes = [32, 64, 128, 256, 512, random.randint(2000, 5000)]
- def write_and_check(writer, payload):
+ def write_and_check(writer, payload : bytes):
payload_len = len(payload)
for s in ser:
s.reset_input_buffer()
@@ -691,8 +873,7 @@ def test_device_cdc_dual_ports(board):
# Write in chunks of random 1-64 bytes (device has 64-byte buffer)
while offset < payload_len:
chunk_size = min(random.randint(1, 64), payload_len - offset)
- ser[writer].write(payload[offset:offset + chunk_size])
- ser[writer].flush()
+ serial_write_all(ser[writer], payload[offset:offset + chunk_size])
rd0 += ser[0].read(chunk_size)
rd1 += ser[1].read(chunk_size)
offset += chunk_size
@@ -726,8 +907,7 @@ def test_device_cdc_msc(board):
# Write in chunks of random 1-64 bytes (device has 64-byte buffer)
while offset < size:
chunk_size = min(random.randint(1, 64), size - offset)
- ser.write(test_str[offset:offset + chunk_size])
- ser.flush()
+ serial_write_all(ser, test_str[offset:offset + chunk_size])
rd_str += ser.read(chunk_size)
offset += chunk_size
assert rd_str == test_str, f'CDC wrong data ({size} bytes):\n expected: {test_str}\n received: {rd_str}'
@@ -737,56 +917,84 @@ def test_device_cdc_msc(board):
data = read_disk_file(uid, 0, 'README.TXT')
assert data == MSC_README_TXT, f'MSC wrong data in README.TXT\n expected: {MSC_README_TXT.decode()}\n received: {data.decode()}'
- # MSC dd throughput test: read all sectors then write back same data
+
+def test_device_cdc_msc_freertos(board):
+ test_device_cdc_msc(board)
+
+
+def test_device_cdc_msc_throughput(board):
+ uid = board['uid']
+
+ def parse_speed(dd_output):
+ for line in dd_output.splitlines():
+ m = re.search(r'([\d.]+)\s+([kMG]?B)/s', line)
+ if m:
+ return f'{float(m.group(1)):.1f} {m.group(2)}ps'
+ return '?'
+
+ # Wait for MSC disk enumeration
dev = get_disk_dev(uid, 'TinyUSB', 0)
timeout = ENUM_TIMEOUT
while timeout > 0:
if os.path.exists(dev):
break
- time.sleep(1)
- timeout -= 1
- assert timeout > 0, f'Disk {dev} not found for dd test'
+ time.sleep(0.1); timeout -= 0.1
+ assert timeout > 0, f'Disk {dev} not found'
- block_count = 16
- block_size = 512
- tmp_file = f'/tmp/msc_dd_{uid}.bin'
+ # Wait for CDC tty enumeration
+ tty = get_serial_dev(uid, 'TinyUSB', 'Throughput', 0)
+ timeout = ENUM_TIMEOUT
+ while timeout > 0:
+ if os.path.exists(tty):
+ break
+ time.sleep(0.1); timeout -= 0.1
+ assert timeout > 0, f'CDC tty {tty} not found'
- # dd reports speed based on payload only. Each block also transfers 31-byte CBW + 13-byte CSW on USB.
- scsi_ratio = (block_size + 31 + 13) / block_size
+ # Detect speed (12 Mbps FS / 480 Mbps HS) for payload scaling
+ is_fs = False
+ for f in glob.glob('/sys/bus/usb/devices/*/serial'):
+ try:
+ if open(f).read().strip() == uid:
+ is_fs = (open(os.path.join(os.path.dirname(f), 'speed')).read().strip() == '12')
+ break
+ except (OSError, ValueError):
+ pass
- def parse_dd_speed(dd_output):
- """Parse dd output, return USB-adjusted speed string"""
- for line in dd_output.splitlines():
- m = re.search(r'([\d.]+)\s+([kMG]?B/s)', line)
- if m:
- speed_val = float(m.group(1)) * scsi_ratio
- return f'{speed_val:.1f} {m.group(2)}'
- return ''
+ # Put tty in raw mode so dd sees pure binary throughput.
+ rs = run_cmd(f'timeout 30 stty -F {tty} raw -echo')
+ assert rs.returncode == 0, f'stty failed: {cmd_stdout_text(rs.stdout)}'
- # Read: dd from device to file
- ret = run_cmd(f'dd if={dev} of={tmp_file} bs={block_size} count={block_count} iflag=direct 2>&1')
- assert ret.returncode == 0, f'dd read failed: {ret.stdout.decode()}'
- read_speed = parse_dd_speed(ret.stdout.decode())
+ # Payload aim: ~5 s per direction at FS (~830 kB/s), much less at HS.
+ msc_count = 2 if is_fs else 16 # bs=1M
+ cdc_count = 16 if is_fs else 128 # bs=64K
- # Write back the same data to avoid corrupting the disk (skip if read-only)
- ret = run_cmd(f'dd if={tmp_file} of={dev} bs={block_size} count={block_count} oflag=direct 2>&1')
- if ret.returncode != 0 and 'Read-only' in ret.stdout.decode():
- write_speed = 'skip (read-only)'
- else:
- assert ret.returncode == 0, f'dd write failed: {ret.stdout.decode()}'
- write_speed = parse_dd_speed(ret.stdout.decode())
+ tmp_file = f'/tmp/cdc_msc_tp_{uid}.bin'
+
+ rw = run_cmd(f'timeout 30 dd if=/dev/zero of={tty} bs=64K count={cdc_count} 2>&1')
+ assert rw.returncode == 0, f'CDC dd write failed: {cmd_stdout_text(rw.stdout)}'
+ cdc_w = parse_speed(cmd_stdout_text(rw.stdout))
+
+ rr = run_cmd(f'timeout 30 dd if={tty} of=/dev/null bs=64K count={cdc_count} iflag=fullblock 2>&1')
+ assert rr.returncode == 0, f'CDC dd read failed: {cmd_stdout_text(rr.stdout)}'
+ cdc_r = parse_speed(cmd_stdout_text(rr.stdout))
+
+ rmr = run_cmd(f'dd if={dev} of={tmp_file} bs=1M count={msc_count} iflag=direct 2>&1')
+ assert rmr.returncode == 0, f'MSC dd read failed: {cmd_stdout_text(rmr.stdout)}'
+ msc_r = parse_speed(cmd_stdout_text(rmr.stdout))
+
+ rmw = run_cmd(f'dd if={tmp_file} of={dev} bs=1M count={msc_count} oflag=direct 2>&1')
+ assert rmw.returncode == 0, f'MSC dd write failed: {cmd_stdout_text(rmw.stdout)}'
+ msc_w = parse_speed(cmd_stdout_text(rmw.stdout))
try:
os.remove(tmp_file)
except OSError:
pass
- if read_speed and write_speed:
- print(f' dd read: {read_speed}, write: {write_speed}', end='')
-
-
-def test_device_cdc_msc_freertos(board):
- test_device_cdc_msc(board)
+ print(f' CDC read {cdc_r} write {cdc_w}, MSC read {msc_r} write {msc_w} ', end='')
+ # compact read/write speed for the report cell, e.g. "✅ CDC 652k/422k MSC 1.1M/783k"
+ short = lambda s: (s.split()[0].rstrip('0').rstrip('.') + s.split()[-1][0]) if ' ' in s else s
+ return f'{REPORT_CELL["pass"]} CDC {short(cdc_r)}/{short(cdc_w)} MSC {short(msc_r)}/{short(msc_w)}'
def test_device_dfu(board):
@@ -796,7 +1004,7 @@ def test_device_dfu(board):
timeout = ENUM_TIMEOUT
while timeout > 0:
ret = run_cmd(f'dfu-util -l')
- stdout = ret.stdout.decode()
+ stdout = cmd_stdout_text(ret.stdout)
if f'serial="{uid}"' in stdout and 'Found DFU: [cafe:4000]' in stdout:
break
time.sleep(1)
@@ -836,7 +1044,7 @@ def test_device_dfu_runtime(board):
timeout = ENUM_TIMEOUT
while timeout > 0:
ret = run_cmd(f'dfu-util -l')
- stdout = ret.stdout.decode()
+ stdout = cmd_stdout_text(ret.stdout)
if f'serial="{uid}"' in stdout and 'Found Runtime: [cafe:4000]' in stdout:
break
time.sleep(1)
@@ -896,18 +1104,27 @@ def test_device_printer_to_cdc(board):
ser.reset_input_buffer()
# Test 1: Printer -> CDC with multiple sizes, write in random 1-64 byte chunks
+ LP_WRITE_TIMEOUT = 5.0 # seconds; firmware may stall draining the printer OUT endpoint
for size in sizes:
test_data = rand_ascii(size)
ser.reset_input_buffer()
rd = b''
offset = 0
- with open(lp_dev, 'wb') as lp:
+ lp_fd = os.open(lp_dev, os.O_WRONLY | os.O_NONBLOCK)
+ try:
while offset < size:
chunk_size = min(random.randint(1, 64), size - offset)
- lp.write(test_data[offset:offset + chunk_size])
- lp.flush()
+ buf = test_data[offset:offset + chunk_size]
+ written = 0
+ while written < len(buf):
+ _, wr, _ = select.select([], [lp_fd], [], LP_WRITE_TIMEOUT)
+ assert wr, f'Printer write timeout after {LP_WRITE_TIMEOUT}s (firmware not draining OUT endpoint)'
+ n = os.write(lp_fd, buf[written:])
+ written += n
rd += ser.read(chunk_size)
offset += chunk_size
+ finally:
+ os.close(lp_fd)
# read any remaining bytes (fullspeed devices may need extra time)
while len(rd) < size:
remaining = ser.read(size - len(rd))
@@ -954,8 +1171,7 @@ def test_device_printer_to_cdc(board):
offset = 0
while offset < size:
chunk_size = min(random.randint(1, 64), size - offset)
- ser.write(test_data[offset:offset + chunk_size])
- ser.flush()
+ serial_write_all(ser, test_data[offset:offset + chunk_size])
time.sleep(0.01)
offset += chunk_size
@@ -1028,6 +1244,65 @@ def test_device_mtp(board):
mtp.disconnect()
+def test_device_net_lwip_webserver(board):
+ # MAC hard-coded in examples/device/net_lwip_webserver/src/main.c; Linux names the
+ # USB network interface enx<MAC_lowercase_no_colons>. Device IP is 192.168.7.1 and
+ # the example runs an iperf2 TCP server on port 5001 (INCLUDE_IPERF).
+ import socket
+ mac_no_colons = '0202846a9600'
+ iface = 'enx' + mac_no_colons
+ device_ip = '192.168.7.1'
+ iperf_port = 5001
+
+ # Wait for the host to get an IPv4 address in the device's subnet (DHCP served by the device).
+ # USB enum + DHCP serve can take longer on the CI HIL hardware than on local — give it 30s.
+ iface_timeout = 30
+ deadline = time.time() + iface_timeout
+ host_ip = None
+ while time.time() < deadline:
+ ret = subprocess.run(['ip', '-o', '-4', 'addr', 'show', iface],
+ capture_output=True, text=True, timeout=2)
+ m = re.search(r'inet (192\.168\.7\.\d+)/', ret.stdout) if ret.returncode == 0 else None
+ if m:
+ host_ip = m.group(1)
+ break
+ time.sleep(0.5)
+ assert host_ip, f'USB net iface {iface} did not come up with 192.168.7.x within {iface_timeout}s'
+
+ # Poll the iperf TCP port until the device is accepting. The net stack comes up a bit
+ # after DHCP completes; iperf server binding isn't instantaneous after reflash.
+ deadline = time.time() + ENUM_TIMEOUT
+ last_err = None
+ while time.time() < deadline:
+ try:
+ with socket.create_connection((device_ip, iperf_port), timeout=1):
+ last_err = None
+ break
+ except OSError as e:
+ last_err = e
+ time.sleep(0.3)
+ assert last_err is None, f'iperf TCP {device_ip}:{iperf_port} not accepting within {ENUM_TIMEOUT}s: {last_err}'
+
+ # Throughput: 5-second iperf2 TCP test, CSV output for stable parsing.
+ # iperf2 CSV final summary line: timestamp,src_ip,src_port,dst_ip,dst_port,id,interval,bytes,bps
+ ret = subprocess.run(['iperf', '-c', device_ip, '-t', '5', '-y', 'C'],
+ capture_output=True, text=True, timeout=30)
+ stderr = ret.stderr.strip()
+ stdout = ret.stdout.strip()
+ assert ret.returncode == 0, f'iperf rc={ret.returncode}: stderr={stderr!r} stdout={stdout!r}'
+ lines = [l for l in stdout.splitlines() if l]
+ assert lines, f'iperf produced no output (rc={ret.returncode}, stderr={stderr!r})'
+ try:
+ bps = int(lines[-1].split(',')[-1])
+ except (ValueError, IndexError) as e:
+ raise AssertionError(f'could not parse iperf output: {lines[-1]!r} ({e})')
+ mbps = bps / 1e6
+ print(f' iperf {mbps:5.1f} Mbps', end='')
+
+ # Reject implausibly low throughput - a working USB-net link should clear this easily.
+ assert mbps >= 1.0, f'iperf throughput too low: {mbps:.2f} Mbps'
+
+
def test_device_msc_dual_lun(board):
uid = board['uid']
@@ -1098,9 +1373,78 @@ def test_device_midi_test(board):
assert n in note_sequence, f'Unexpected MIDI note {n}'
+def test_device_audio_test_freertos(board):
+ uid = board['uid']
+
+ if os.name == 'nt':
+ return 'skipped'
+
+ pcm = None
+ timeout = ENUM_TIMEOUT
+ while timeout > 0:
+ pcm = get_alsa_capture_dev(uid)
+ if pcm:
+ break
+ time.sleep(1)
+ timeout -= 1
+
+ assert pcm is not None, f'ALSA capture device not found for {uid}'
+
+ raw_path = f'/tmp/tinyusb_audio_{uid}.raw'
+ cmd = [
+ 'arecord',
+ '-D', pcm,
+ '-q',
+ '-f', 'S16_LE',
+ '-c', '1',
+ '-r', '48000',
+ '-d', '2',
+ '-t', 'raw',
+ raw_path,
+ ]
+
+ ret = subprocess.run(cmd, capture_output=True, text=True, timeout=20)
+ assert ret.returncode == 0, f'arecord failed: {ret.stderr.strip() or ret.stdout.strip()}'
+
+ try:
+ with open(raw_path, 'rb') as f:
+ raw = f.read()
+ finally:
+ try:
+ os.remove(raw_path)
+ except OSError:
+ pass
+
+ assert len(raw) >= 48000, f'Captured too little audio: {len(raw)} bytes'
+ assert (len(raw) % 2) == 0, f'Invalid 16-bit audio length: {len(raw)}'
+
+ sample_count = len(raw) // 2
+ samples = [int.from_bytes(raw[i:i + 2], 'little', signed=False) for i in range(0, len(raw), 2)]
+ assert sample_count > 1024, f'Not enough samples captured: {sample_count}'
+
+ # The firmware sends a continuous uint16 ramp. Using ALSA hw: capture bypasses
+ # PulseAudio processing, so most adjacent samples should differ by exactly 1.
+ total_diffs = sample_count - 1
+ one_step = 0
+ near_step = 0
+ for i in range(total_diffs):
+ d = (samples[i + 1] - samples[i]) & 0xFFFF
+ if d == 1:
+ one_step += 1
+ if d in (0, 1, 2, 47, 48, 49):
+ near_step += 1
+
+ one_ratio = one_step / total_diffs
+ near_ratio = near_step / total_diffs
+ assert one_ratio >= 0.85, f'Unexpected audio pattern (strict ratio={one_ratio:.3f})'
+ assert near_ratio >= 0.98, f'Unexpected audio pattern (relaxed ratio={near_ratio:.3f})'
+
+ print(f' ALSA {pcm} strict={one_ratio:.3f} relaxed={near_ratio:.3f}', end='')
+
+
def test_device_hid_generic_inout(board):
uid = board['uid']
- import hid
+ import hid # cython-hidapi (pip: hidapi, apt: python3-hid)
# Find HID device by UID (VID=0xCafe)
timeout = ENUM_TIMEOUT
@@ -1116,22 +1460,23 @@ def test_device_hid_generic_inout(board):
timeout -= 1
assert dev is not None, f'HID device not found for {uid}'
- h = hid.Device(vid=dev['vendor_id'], pid=dev['product_id'], serial=uid)
-
- # Echo test: send random data and verify echo
- for size in [8, 32, 63]:
- # Report ID (0) + payload, padded to 64 bytes
- payload = bytes([random.randint(1, 255) for _ in range(size)])
- report = bytes([0]) + payload + bytes(64 - size)
- h.write(report)
- echo = h.read(64, timeout=2000)
- assert echo is not None and len(echo) >= size, (
- f'HID echo timeout or short read ({size} bytes)')
- assert bytes(echo[:size]) == payload, (
- f'HID echo wrong data ({size} bytes):\n'
- f' expected: {payload.hex()}\n received: {bytes(echo[:size]).hex()}')
-
- h.close()
+ h = hid.device()
+ h.open(dev['vendor_id'], dev['product_id'], uid)
+ try:
+ # Echo test: send random data and verify echo
+ for size in [8, 32, 63]:
+ # Report ID (0) + payload, padded to 64 bytes
+ payload = bytes([random.randint(1, 255) for _ in range(size)])
+ report = bytes([0]) + payload + bytes(64 - size)
+ h.write(report)
+ echo = h.read(64, 2000)
+ assert echo and len(echo) >= size, (
+ f'HID echo timeout or short read ({size} bytes)')
+ assert bytes(echo[:size]) == payload, (
+ f'HID echo wrong data ({size} bytes):\n'
+ f' expected: {payload.hex()}\n received: {bytes(echo[:size]).hex()}')
+ finally:
+ h.close()
# -------------------------------------------------------------
@@ -1140,9 +1485,15 @@ def test_device_hid_generic_inout(board):
# device tests
# note don't test 2 examples with cdc or 2 msc next to each other
device_tests = [
+ # Order matters: cdc_msc and cdc_msc_throughput share the same VID:PID (cafe:4003), so keep a
+ # differently-PID'd example (dfu, cafe:4000) between them. Boards whose CPU-reset does not drop
+ # D+ (e.g. WCH CH58x via openocd) only re-enumerate when the PID changes; back-to-back same-PID
+ # firmware would otherwise leave the host on the previous example's cached descriptors.
'device/cdc_dual_ports',
- 'device/dfu',
'device/cdc_msc',
+ 'device/dfu',
+ 'device/cdc_msc_throughput',
+ 'device/audio_test_freertos',
'device/dfu_runtime',
'device/cdc_msc_freertos',
'device/hid_boot_interface',
@@ -1150,7 +1501,8 @@ device_tests = [
'device/hid_generic_inout',
'device/printer_to_cdc',
'device/midi_test',
- 'device/mtp'
+ 'device/mtp',
+ # 'device/net_lwip_webserver', # disabled for PR #3605: USB net iface enum is flaky on the CI HIL host
]
dual_tests = [
@@ -1160,85 +1512,179 @@ dual_tests = [
host_test = [
'host/cdc_msc_hid',
'host/msc_file_explorer',
+ 'host/msc_file_explorer_freertos',
'host/device_info',
]
-def test_example(board, f1, example):
+def find_firmware(variant: str, example: str):
+ """Locate a built example's firmware base path (no extension) under
+ cmake-build-<variant>/<example>/. Accepts the single-config layout (firmware
+ directly in the example dir) or Ninja Multi-Config (a per-config subdir like
+ RelWithDebInfo/). Returns the base Path, or None if not built."""
+ fw_dir = TINYUSB_ROOT / build_dir / f'cmake-build-{variant}' / example
+ base = Path(example).name
+ if fw_dir.is_dir():
+ for cand in [fw_dir / base, fw_dir / 'RelWithDebInfo' / base,
+ *(p.with_suffix('') for p in sorted(fw_dir.glob(f'*/{base}.elf')))]:
+ if cand.with_suffix('.elf').exists() or cand.with_suffix('.bin').exists():
+ return cand
+ return None
+
+
+def test_example(board: Board, variant: str, example: str) -> tuple[int, str]:
"""
Test example firmware
:param board: board dict
- :param f1: flags on
+ :param variant: build variant name = build dir (cmake-build-<variant>) and report row
:param example: example name
- :return: 0 if success/skip, 1 if failed
+ :return: (err_count, status, metric) where err_count is 0 on success/skip or
+ 1 on failure, status is one of 'pass'/'fail'/'skip' (a missing binary
+ counts as 'skip'), and metric is an optional string a test returns to
+ show in its report cell instead of the pass symbol (e.g. speed)
"""
- name = board['name']
err_count = 0
+ result_status = 'fail'
+ metric = None
- f1_str = ""
- if f1 != "":
- f1_str = '-f1_' + f1.replace(' ', '_')
+ test_name = f'{variant:40} {example:30} ...'
- fw_dir = f'{TINYUSB_ROOT}/{build_dir}/cmake-build-{name}{f1_str}/{example}'
- fw_name = f'{fw_dir}/{os.path.basename(example)}'
- print(f'{name+f1_str:40} {example:30} ...', end='')
-
- if not os.path.exists(fw_dir) or not (os.path.exists(f'{fw_name}.elf') or os.path.exists(f'{fw_name}.bin')):
- print('Skip (no binary)')
- return 0
+ fw_name = find_firmware(variant, example)
+ if fw_name is None:
+ log_line(f'{test_name} Skip (no binary)')
+ return 0, 'skip', None
if verbose:
- print(f'Flashing {fw_name}.elf')
+ log_line(f'Flashing {fw_name}.elf')
- # flash firmware. It may fail randomly, retry a few times
+ # flash firmware (unless --skip-flash), then run the test. Both may fail randomly,
+ # retry a few times.
start_s = time.time()
+ flash_ok = True
+ last_err = ''
+ last_detail = ''
for i in range(max_retry):
- ret = globals()[f'flash_{board["flasher"]["name"].lower()}'](board, fw_name)
- if ret.returncode == 0:
- try:
- tret = globals()[f'test_{example.replace("/", "_")}'](board)
- if tret == 'skipped':
- print(f' {STATUS_SKIPPED}', end='')
- else:
- print(' OK', end='')
- break
- except Exception as e:
- if i == max_retry - 1:
- err_count += 1
- print(f'{STATUS_FAILED}: {e}')
- else:
- print(f'\n Test failed: {e}, retry {i+2}/{max_retry}', end='')
- time.sleep(0.5)
- else:
- print(f'\n Flash failed, retry {i+2}/{max_retry}', end='')
- time.sleep(0.5)
+ attempt_out = io.StringIO()
+ with redirect_stdout(attempt_out):
+ if not skip_flash:
+ ret = globals()[f'flash_{board["flasher"]["name"].lower()}'](board, str(fw_name))
+ flash_ok = (ret.returncode == 0)
+ if flash_ok:
+ try:
+ tret = globals()[f'test_{example.replace("/", "_")}'](board)
+ last_detail = compact_output(attempt_out.getvalue())
+ if tret == 'skipped':
+ status = STATUS_SKIPPED
+ result_status = 'skip'
+ else:
+ status = STATUS_OK
+ result_status = 'pass'
+ # a test may return a string to show in its report cell (e.g. speed)
+ metric = tret if isinstance(tret, str) else None
+ msg = f'{test_name} {status}'
+ if last_detail:
+ msg += f' {last_detail}'
+ msg += f' in {time.time() - start_s:.1f}s'
+ log_line(msg)
+ break
+ except Exception as e:
+ last_err = str(e)
+ last_detail = compact_output(attempt_out.getvalue())
+ if i == max_retry - 1:
+ err_count += 1
+ msg = f'{test_name} {STATUS_FAILED}: {e}'
+ if last_detail:
+ msg += f' {last_detail}'
+ msg += f' in {time.time() - start_s:.1f}s'
+ log_line(msg)
+ else:
+ msg = f'{test_name} retry {i+2}/{max_retry}: test failed: {e}'
+ if last_detail:
+ msg += f' {last_detail}'
+ log_line(msg)
+ time.sleep(0.5)
+ else:
+ last_err = 'Flash failed'
+ last_detail = compact_output(attempt_out.getvalue())
+ if i < max_retry - 1:
+ msg = f'{test_name} retry {i+2}/{max_retry}: flash failed'
+ if last_detail:
+ msg += f' {last_detail}'
+ log_line(msg)
+ time.sleep(0.5)
- if ret.returncode != 0:
+ if not flash_ok:
err_count += 1
- print(f' Flash {STATUS_FAILED}', end='')
+ msg = f'{test_name} Flash {STATUS_FAILED}'
+ if last_err:
+ msg += f': {last_err}'
+ if last_detail:
+ msg += f' {last_detail}'
+ msg += f' in {time.time() - start_s:.1f}s'
+ log_line(msg)
- print(f' in {time.time() - start_s:.1f}s')
+ return err_count, result_status, metric
- return err_count
+def build_board(board: Board) -> tuple[str, int]:
+ """Build firmware for this board via tools/build.py.
+ Honors board config's variant list and build.args defines.
+ Output goes to cmake-build/cmake-build-<variant>/ (tools/build.py layout)."""
+ name = board['name']
+ bcfg = cast(BuildCfg, board.get('build', {}))
+ extra_defs = bcfg.get('args', [])
+ variants = board.get('variant') or [{'name': name, 'flags': ''}]
-def test_board(board):
+ failed = 0
+ for v in variants:
+ cmd = [sys.executable, str(TINYUSB_ROOT / 'tools' / 'build.py'), '-b', name]
+ for d in extra_defs:
+ cmd += ['-D', d]
+ if v['name'] != name:
+ cmd += ['--build-name', v['name']]
+ for d in v.get('defines', []):
+ cmd += ['-D', d]
+ for tok in v.get('flags', '').split():
+ cmd += [f'--cflag={tok}']
+ if verbose:
+ cmd.append('-v')
+ print(f' + {" ".join(cmd)}')
+ r = subprocess.run(cmd, cwd=TINYUSB_ROOT)
+ if r.returncode != 0:
+ failed += 1
+ return name, failed
+
+
+def test_board(board: Board) -> tuple[str, int, list[str], list]:
name = board['name']
flasher = board['flasher']
# default to all tests
test_list = []
- if len(test_only) > 0:
- test_list = test_only
+ if name in board_test:
+ test_list = board_test[name]
+ elif len(test_only) > 0:
+ # Explicit -t: filter against the board's capabilities so a device-only
+ # board doesn't try to run host/dual tests (the test functions need a
+ # `dev_attached` entry in the board config that won't exist).
+ board_tests = board.get('tests', {})
+ if 'only' in board_tests:
+ allowed = set(board_tests['only'])
+ test_list = [t for t in test_only if t in allowed]
+ else:
+ for t in test_only:
+ category = t.split('/', 1)[0]
+ if board_tests.get(category) is True:
+ test_list.append(t)
else:
if 'tests' in board:
board_tests = board['tests']
- if 'device' in board_tests and board_tests['device'] == True:
+ if board_tests.get('device') is True:
test_list += list(device_tests)
- if 'dual' in board_tests and board_tests['dual'] == True:
+ if board_tests.get('dual') is True:
test_list += dual_tests
- if 'host' in board_tests and board_tests['host'] == True:
+ if board_tests.get('host') is True:
test_list += host_test
if 'only' in board_tests:
test_list = board_tests['only']
@@ -1246,75 +1692,207 @@ def test_board(board):
for skip in board_tests['skip']:
if skip in test_list:
test_list.remove(skip)
- print(f'{name:25} {skip:30} ... Skip')
+ log_line(f'{name:25} {skip:30} ... Skip')
err_count = 0
- flags_on_list = [""]
- if 'build' in board and 'flags_on' in board['build']:
- flags_on_list = board['build']['flags_on']
+ failed_tests = []
+ rows = [] # list of (row_label, {example: status}) — one row per build variant
+ variants = board.get('variant') or [{'name': name, 'flags': ''}]
- for f1 in flags_on_list:
+ for v in variants:
+ vname = v['name']
+ cells = {}
for test in test_list:
- err_count += test_example(board, f1, test)
+ ec, status, metric = test_example(board, vname, test)
+ err_count += ec
+ cells[test] = metric if metric else status
+ if ec > 0:
+ failed_tests.append(test)
+ rows.append((vname, cells))
+
+ # flash board_test last to disable board's usb (skipped when --skip-flash is set);
+ # this is teardown/park, not a test — not recorded in the report
+ if not skip_flash:
+ test_example(board, variants[0]['name'], 'device/board_test')
+
+ return name, err_count, sorted(set(failed_tests)), rows
- # flash board_test last to disable board's usb
- test_example(board, flags_on_list[0], 'device/board_test')
- return name, err_count
+REPORT_MD = 'hil_report.md'
+REPORT_JSON = 'hil_report.json'
-def main():
+def render_matrix(rows_all: list) -> str:
+ """Render rows (list of (row_label, {example: status})) as an aligned markdown
+ matrix: columns = tests (bare names) centered, boards left-aligned."""
+ canonical = device_tests + dual_tests + host_test
+ seen = set()
+ for _, cells in rows_all:
+ seen.update(cells)
+ if not seen:
+ return 'No tests were run.'
+
+ # columns: canonical order first, then any extras (e.g. from -t) alphabetically
+ columns = [t for t in canonical if t in seen]
+ columns += [t for t in sorted(seen) if t not in canonical]
+ headers = [c.rsplit('/', 1)[-1] for c in columns] # bare example name
+
+ def cell(cells, col):
+ v = cells.get(col)
+ if v is None:
+ return ''
+ return REPORT_CELL.get(v, v) # status symbol, or a metric string (e.g. speed) verbatim
+
+ board_hdr = 'Board'
+ board_w = max([len(board_hdr)] + [len(lbl) for lbl, _ in rows_all])
+ col_w = [max([len(h)] + [len(cell(cells, c)) for _, cells in rows_all])
+ for h, c in zip(headers, columns)]
+
+ def line(label, values):
+ padded = [label.ljust(board_w)] + [v.center(w) for v, w in zip(values, col_w)]
+ return '| ' + ' | '.join(padded) + ' |'
+
+ header = line(board_hdr, headers)
+ sep = '| ' + '-' * board_w + ' | ' + ' | '.join(':' + '-' * (w - 2) + ':' for w in col_w) + ' |'
+ body = [line(lbl, [cell(cells, c) for c in columns]) for lbl, cells in rows_all]
+
+ legend = 'Legend: ✅ pass · ❌ fail · ⚪ skipped · blank not run'
+ return '\n'.join([header, sep] + body) + '\n\n' + legend
+
+
+def accumulate_report(mret: list, report_dir: Path, fresh: bool) -> str:
+ """Merge this run's results into hil_report.json in report_dir, then (re)write
+ the markdown matrix to hil_report.md. `fresh` (a full run, no --skip-board/-bt)
+ starts a new report; otherwise a re-run accumulates so boards/tests that
+ already passed are preserved while re-run cells are updated. Returns the md."""
+ acc = {} # ordered {row_label: {example: status}}
+ jpath = report_dir / REPORT_JSON
+ if not fresh and jpath.is_file():
+ try:
+ for entry in json.loads(jpath.read_text()).get('rows', []):
+ acc[entry['board']] = dict(entry['cells'])
+ except (ValueError, KeyError, TypeError):
+ pass # corrupt/old sidecar: start fresh
+
+ # merge this run: current cells override prior for boards/tests that ran
+ for _, _, _, rows in mret:
+ for row_label, cells in rows:
+ acc.setdefault(row_label, {}).update(cells)
+
+ report_dir.mkdir(parents=True, exist_ok=True)
+ jpath.write_text(json.dumps({'rows': [{'board': k, 'cells': v} for k, v in acc.items()]},
+ indent=2) + '\n')
+
+ md = render_matrix(list(acc.items()))
+ (report_dir / REPORT_MD).write_text(md + '\n', encoding='utf-8')
+ return md
+
+
+def main() -> None:
"""
Hardware test on specified boards
"""
global verbose
global test_only
+ global board_test
global build_dir
global max_retry
+ global skip_flash
duration = time.time()
parser = argparse.ArgumentParser()
parser.add_argument('config_file', help='Configuration JSON file')
parser.add_argument('-b', '--board', action='append', default=[], help='Boards to test, all if not specified')
- parser.add_argument('-s', '--skip', action='append', default=[], help='Skip boards from test')
+ parser.add_argument('-s', '--skip-board', action='append', default=[], help='Skip boards from test')
+ parser.add_argument('-sf', '--skip-flash', action='store_true', help='Run tests without flashing firmware (use whatever is already on the board)')
parser.add_argument('-t', '--test-only', action='append', default=[], help='Tests to run, all if not specified')
- parser.add_argument('-B', '--build', default='cmake-build', help='Build folder name (default: cmake-build)')
+ parser.add_argument('-bt', '--board-test', action='append', default=[],
+ help='Per-board test list as BOARD:test1,test2 (overrides -t for that board); repeat for multiple boards')
+ parser.add_argument('-B', '--build-dir', default='cmake-build', help='Build folder name (default: cmake-build)')
+ parser.add_argument('--build', action='store_true', help='Build firmware for selected boards with cmake before running tests')
parser.add_argument('-r', '--retry', type=int, default=3, help='Retry count for failed tests (default: 3)')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
args = parser.parse_args()
- config_file = args.config_file
+ config_file = Path(args.config_file)
boards = args.board
- skip_boards = args.skip
+ skip_boards = args.skip_board
verbose = args.verbose
test_only = args.test_only
- build_dir = args.build
+ for entry in args.board_test:
+ bname, _, tnames = entry.partition(':')
+ if not bname or not tnames:
+ parser.error(f'invalid --board-test value: {entry!r} (expected BOARD:test1,test2)')
+ board_test[bname] = [t for t in tnames.split(',') if t]
+ build_dir = args.build_dir
max_retry = args.retry
+ skip_flash = args.skip_flash
# if config file is not found, try to find it in the same directory as this script
- if not os.path.exists(config_file):
- config_file = os.path.join(os.path.dirname(__file__), config_file)
- with open(config_file) as f:
- config = json.load(f)
+ if not config_file.exists():
+ config_file = Path(__file__).resolve().parent / config_file
+ with config_file.open() as f:
+ config = cast(HilConfig, json.load(f))
if len(boards) == 0:
config_boards = [e for e in config['boards'] if e['name'] not in skip_boards]
else:
config_boards = [e for e in config['boards'] if e['name'] in boards]
- err_count = 0
- with Pool(processes=os.cpu_count()) as pool:
- mret = pool.map(test_board, config_boards)
- err_count = sum(e[1] for e in mret)
- # generate skip list for next re-run if failed
- skip_fname = f'{config_file}.skip'
+ build_err = 0
+ if args.build:
+ if build_dir != 'cmake-build':
+ print(f'warning: --build writes into cmake-build/, but -B is {build_dir!r}; '
+ f'tests will not find the freshly built firmware')
+ print('-' * 30)
+ print(f'Build phase: {len(config_boards)} board(s)')
+ print('-' * 30)
+ for board in config_boards:
+ _, nfail = build_board(board)
+ build_err += nfail
+ print('-' * 30)
+ print(f'Build phase done: {build_err} failed')
+ print('-' * 30)
+
+ # HIL report sidecar (hil_report.json/.md). A full run starts fresh; a re-run
+ # (--skip-board / -bt, i.e. the .skip file) accumulates so already-passed
+ # boards/tests are preserved. Clear any prior report up front on a fresh run so
+ # a crash mid-run can't leave stale results to be merged by a retry or posted.
+ report_dir = Path(os.environ.get('HIL_REPORT_DIR', '.'))
+ fresh = not (args.skip_board or args.board_test)
+ if fresh:
+ report_dir.mkdir(parents=True, exist_ok=True)
+ for f in (REPORT_JSON, REPORT_MD):
+ (report_dir / f).unlink(missing_ok=True)
+
+ with Pool(processes=os.cpu_count() or 1, initializer=init_worker, initargs=(Lock(),)) as pool:
+ async_ret = pool.map_async(test_board, config_boards)
+ try:
+ mret = async_ret.get(timeout=POOL_TIMEOUT)
+ except MpTimeoutError:
+ pool.terminate()
+ pool.join()
+ raise RuntimeError(f'HIL worker pool timed out after {POOL_TIMEOUT}s')
+
+ err_count = build_err + sum(e[1] for e in mret)
+ # generate skip list for next re-run if failed: skip boards that fully passed,
+ # and emit -bt BOARD:t1,t2 so each failed board only re-runs its own failed tests.
+ skip_fname = config_file.with_suffix(config_file.suffix + '.skip')
if err_count > 0:
- skip_boards += [name for name, err in mret if err == 0]
- with open(skip_fname, 'w') as f:
- f.write(' '.join(f'-s {i}' for i in skip_boards))
- elif os.path.exists(skip_fname):
- os.remove(skip_fname)
+ skip_boards += [name for name, err, _, _ in mret if err == 0]
+ parts = [f'--skip-board {i}' for i in skip_boards]
+ parts += [f'-bt {name}:{",".join(fts)}' for name, err, fts, _ in mret if err > 0 and fts]
+ with skip_fname.open('w') as f:
+ f.write(' '.join(parts))
+ elif skip_fname.exists():
+ skip_fname.unlink()
+
+ # board x test result matrix -> hil_report.md (accumulates across re-runs) + stdout
+ report = accumulate_report(mret, report_dir, fresh)
+ print()
+ print(report)
+ print(f'\nReport written to {(report_dir / REPORT_MD).resolve()}')
duration = time.time() - duration
print()
diff --git a/test/hil/requirements.txt b/test/hil/requirements.txt
index ef2fecebe..ef1cf575b 100644
--- a/test/hil/requirements.txt
+++ b/test/hil/requirements.txt
@@ -1,4 +1,9 @@
-fs
-hid
-pyfatfs
+# System packages (install separately):
+# sudo apt install mtools libmtp9 alsa-utils iperf
+# mtools - read_disk_file (device/cdc_msc, device/msc_dual_lun)
+# libmtp9 - pymtp ctypes load (device/mtp); Debian 13 uses libmtp9t64
+# alsa-utils - arecord (device/audio_test_freertos)
+# iperf - throughput tests (device/net_lwip_*)
+hidapi
pyserial
+esptool
diff --git a/test/hil/tinyusb.json b/test/hil/tinyusb.json
index 92b7b21b0..2ea910c4c 100644
--- a/test/hil/tinyusb.json
+++ b/test/hil/tinyusb.json
@@ -1,14 +1,49 @@
{
"boards": [
{
+ "name": "ek_tm4c123gxl",
+ "uid": "010105186C60A110",
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
+ },
+ "flasher": {
+ "name": "lm4flash",
+ "uid": "0E205D19",
+ "args": "-v"
+ }
+ },
+ {
"name": "espressif_p4_function_ev",
"uid": "6055F9F98715",
- "build" : {
- "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE CFG_TUH_DWC2_DMA_ENABLE"]
- },
+ "variant": [
+ { "name": "espressif_p4_function_ev", "flags": "" },
+ { "name": "espressif_p4_function_ev-DMA", "flags": "-DCFG_TUD_DWC2_DMA_ENABLE=1 -DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
"tests": {
- "only": ["device/cdc_msc_freertos", "device/hid_composite_freertos", "host/device_info"],
- "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2002427", "is_cdc": true}]
+ "only": [
+ "device/cdc_msc_freertos",
+ "device/hid_composite_freertos",
+ "device/audio_test_freertos",
+ "host/device_info",
+ "host/msc_file_explorer_freertos"
+ ],
+ "dev_attached": [
+ {
+ "vid_pid": "1a86_55d4",
+ "serial": "52D2002427",
+ "is_cdc": true
+ },
+ {
+ "vid_pid": "21c4_0cc7",
+ "serial": "900058944CB80A53",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 60620800,
+ "msc_inquiry": "Lexar USB Flash Drive PMAP"
+ }
+ ]
},
"flasher": {
"name": "esptool",
@@ -21,12 +56,34 @@
{
"name": "espressif_s3_devkitm",
"uid": "84F703C084E4",
- "build" : {
- "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE CFG_TUH_DWC2_DMA_ENABLE"]
- },
+ "variant": [
+ { "name": "espressif_s3_devkitm", "flags": "" },
+ { "name": "espressif_s3_devkitm-DMA", "flags": "-DCFG_TUD_DWC2_DMA_ENABLE=1 -DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
"tests": {
- "only": ["device/cdc_msc_freertos", "device/hid_composite_freertos", "host/device_info"],
- "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2005402", "is_cdc": true}]
+ "only": [
+ "device/cdc_msc_freertos",
+ "device/hid_composite_freertos",
+ "device/audio_test_freertos",
+ "host/device_info",
+ "host/msc_file_explorer_freertos"
+ ],
+ "dev_attached": [
+ {
+ "vid_pid": "1a86_55d4",
+ "serial": "52D2005402",
+ "is_cdc": true
+ },
+ {
+ "vid_pid": "048d_04d2",
+ "serial": "\u0409",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 30720000,
+ "msc_inquiry": "General UDisk 5.00",
+ "comment": "General UDisk reports iSerialNumber=U+0409"
+ }
+ ]
},
"flasher": {
"name": "esptool",
@@ -39,11 +96,13 @@
"name": "feather_nrf52840_express",
"uid": "1F0479CD0F764471",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "jlink",
- "uid": "000682804350",
+ "uid": "681295394",
"args": "-device nrf52840_xxaa"
}
},
@@ -51,7 +110,9 @@
"name": "max32666fthr",
"uid": "0C81464124010B20FF0A08CC2C",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "openocd_adi",
@@ -71,8 +132,15 @@
"device": true,
"host": false,
"dual": true,
- "dev_attached": [{"vid_pid": "067b_2303", "serial": "0", "is_cdc": true}],
- "comment": "pl23x"
+ "skip": ["device/audio_test_freertos"],
+ "dev_attached": [
+ {
+ "vid_pid": "067b_2303",
+ "serial": "0",
+ "is_cdc": true
+ }
+ ],
+ "comment": "pl23x; audio_test_freertos skipped: samd51 iso-IN capture fails (arecord EIO)"
},
"flasher": {
"name": "jlink",
@@ -84,7 +152,9 @@
"name": "mimxrt1015_evk",
"uid": "DC28F865D2111D228D00B0543A70463C",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "jlink",
@@ -96,9 +166,25 @@
"name": "mimxrt1064_evk",
"uid": "BAE96FB95AFA6DBB8F00005002001200",
"tests": {
- "device": true, "host": true, "dual": true,
- "dev_attached": [{"vid_pid": "10c4_ea60", "serial": "0001", "is_cdc": true}],
- "comment": "cp2102"
+ "device": true,
+ "host": true,
+ "dual": true,
+ "dev_attached": [
+ {
+ "vid_pid": "10c4_ea60",
+ "serial": "0001",
+ "is_cdc": true,
+ "comment": "cp2102"
+ },
+ {
+ "vid_pid": "21c4_0cc7",
+ "serial": "900058874D871F66",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 60620800,
+ "msc_inquiry": "Lexar USB Flash Drive PMAP"
+ }
+ ]
},
"flasher": {
"name": "jlink",
@@ -110,7 +196,9 @@
"name": "lpcxpresso11u37",
"uid": "17121919",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "jlink",
@@ -135,13 +223,30 @@
{
"name": "raspberry_pi_pico",
"uid": "E6614C311B764A37",
- "build" : {
- "flags_on": ["CFG_TUH_RPI_PIO_USB"]
- },
+ "variant": [
+ { "name": "raspberry_pi_pico", "flags": "-DCFG_TUH_RPI_PIO_USB=1" }
+ ],
"tests": {
- "device": true, "host": true, "dual": true,
- "dev_attached": [{"vid_pid": "1a86_7523", "serial": "0", "is_cdc": true}],
- "comment": "ch34x"
+ "device": true,
+ "host": true,
+ "dual": true,
+ "dev_attached": [
+ {
+ "vid_pid": "1a86_7523",
+ "serial": "0",
+ "is_cdc": true,
+ "comment": "ch34x"
+ },
+ {
+ "vid_pid": "048d_04d2",
+ "serial": "\u0409",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 30720000,
+ "msc_inquiry": "General UDisk 5.00",
+ "comment": "General UDisk reports iSerialNumber=U+0409"
+ }
+ ]
},
"flasher": {
"name": "openocd",
@@ -153,11 +258,13 @@
"name": "raspberry_pi_pico_w",
"uid": "E6614864D35DAE36",
"tests": {
- "device": false, "host": true, "dual": false,
+ "device": false,
+ "host": true,
+ "dual": false,
"dev_attached": [
{
"vid_pid": "1a86_55d4",
- "serial": "52D2023934",
+ "serial": "52D2002694",
"is_cdc": true
},
{
@@ -181,20 +288,17 @@
"name": "raspberry_pi_pico2",
"uid": "560AE75E1C7152C9",
"tests": {
- "device": false, "host": true, "dual": false,
+ "device": false,
+ "host": true,
+ "dual": false,
"dev_attached": [
{
- "vid_pid": "1a86_55d4",
- "serial": "52D2002694",
- "is_cdc": true
- },
- {
"vid_pid": "0951_1603",
"serial": "820000000000000045B46338",
"is_msc": true,
"block_size": 512,
"block_count": 3987456,
- "msc_inquiry": "Kingston DataTraveler 2.0 1.0"
+ "msc_inquiry": "Kingston DataTraveler 2.0 1.00"
}
]
},
@@ -212,20 +316,35 @@
"host": true,
"dual": true,
"dev_attached": [
- {"vid_pid": "0403_6001", "serial": "0", "is_cdc": true},
- {"vid_pid": "058f_6387", "serial": "A8BEE062633D", "is_msc": true,
- "block_size": 512, "block_count": 7639040, "msc_inquiry": "Generic Flash Disk 8.07"}
+ {
+ "vid_pid": "0403_6001",
+ "serial": "0",
+ "is_cdc": true
+ },
+ {
+ "vid_pid": "058f_6387",
+ "serial": "A8BEE062633D",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 7639040,
+ "msc_inquiry": "Generic Flash Disk 8.07"
+ }
]
},
"flasher": {
"name": "openocd",
- "uid": "E6614103E78E8324",
+ "uid": "E663AC91D3359B38",
"args": "-f interface/cmsis-dap.cfg -f target/rp2350.cfg -c \"adapter speed 5000\""
}
},
{
"name": "stm32f072disco",
"uid": "3A001A001357364230353532",
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
+ },
"flasher": {
"name": "jlink",
"uid": "779541626",
@@ -234,14 +353,45 @@
"comment": "2x16 access scheme with 1KB USB SRAM"
},
{
+ "name": "stm32f407disco",
+ "uid": "30001A000647313332353735",
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
+ },
+ "flasher": {
+ "name": "jlink",
+ "uid": "000773661813",
+ "args": "-device stm32f407vg"
+ }
+ },
+ {
"name": "stm32f723disco",
"uid": "460029001951373031313335",
- "build" : {
- "flags_on": ["", "CFG_TUH_DWC2_DMA_ENABLE"]
- },
+ "variant": [
+ { "name": "stm32f723disco", "flags": "" },
+ { "name": "stm32f723disco-DMA", "flags": "-DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
"tests": {
- "device": true, "host": true, "dual": false,
- "dev_attached": [{"vid_pid": "1a86_55d4", "serial": "52D2003414", "is_cdc": true}]
+ "device": true,
+ "host": true,
+ "dual": false,
+ "dev_attached": [
+ {
+ "vid_pid": "1a86_55d4",
+ "serial": "52D2003414",
+ "is_cdc": true
+ },
+ {
+ "vid_pid": "21c4_0cc7",
+ "serial": "90005893730A1A63",
+ "is_msc": true,
+ "block_size": 512,
+ "block_count": 60620800,
+ "msc_inquiry": "Lexar USB Flash Drive PMAP"
+ }
+ ]
},
"flasher": {
"name": "jlink",
@@ -253,11 +403,14 @@
{
"name": "stm32h743nucleo",
"uid": "110018000951383432343236",
- "build" : {
- "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE"]
- },
+ "variant": [
+ { "name": "stm32h743nucleo", "flags": "" },
+ { "name": "stm32h743nucleo-DMA", "flags": "-DCFG_TUD_DWC2_DMA_ENABLE=1 -DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "openocd",
@@ -269,7 +422,9 @@
"name": "stm32g0b1nucleo",
"uid": "4D0038000450434E37343120",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "openocd",
@@ -277,29 +432,46 @@
"args": "-f interface/stlink.cfg -f target/stm32g0x.cfg"
},
"comment": "32-bit scheme, 2KB USB SRAM"
- }
- ],
- "boards-skip": [
+ },
{
- "name": "stm32f769disco",
- "uid": "21002F000F51363531383437",
- "build" : {
- "flags_on": ["", "CFG_TUD_DWC2_DMA_ENABLE"]
- },
+ "name": "stm32l476disco",
+ "uid": "3C0050001150334258343920",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "jlink",
- "uid": "000778170924",
- "args": "-device stm32f769ni"
+ "uid": "777632258",
+ "args": "-device STM32L476VG"
+ }
+ },
+ {
+ "name": "stm32u083nucleo",
+ "uid": "300044000D5036394E373620",
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
+ },
+ "flasher": {
+ "name": "stlink",
+ "uid": "0668FF575457657187061314"
}
},
{
"name": "nanoch32v203",
"uid": "CDAB277B0FBC03E339E339E3",
+ "toolchain": "riscv-gcc",
+ "variant": [
+ {"name": "nanoch32v203-fsdev", "defines": ["RHPORT_DEVICE=0"]},
+ {"name": "nanoch32v203-usbfs", "defines": ["RHPORT_DEVICE=1"]}
+ ],
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "openocd_wch",
@@ -308,15 +480,54 @@
}
},
{
- "name": "stm32f407disco",
- "uid": "30001A000647313332353735",
+ "name": "ch32v103r_r1_1v0",
+ "uid": "CDAB3E8749BC54EF0F410025",
+ "toolchain": "riscv-gcc",
"tests": {
- "device": true, "host": false, "dual": false
+ "device": true,
+ "host": false,
+ "dual": false,
+ "skip": ["device/cdc_msc_throughput"]
+ },
+ "flasher": {
+ "name": "openocd_wch",
+ "uid": "BC4954081051",
+ "args": ""
+ }
+ },
+ {
+ "name": "ch582m_evt",
+ "uid": "D443627B5450",
+ "toolchain": "riscv-gcc",
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
+ },
+ "flasher": {
+ "name": "openocd_wch",
+ "uid": "7FD88F0604B5",
+ "args": ""
+ }
+ }
+ ],
+ "boards-skip": [
+ {
+ "name": "stm32f769disco",
+ "uid": "21002F000F51363531383437",
+ "variant": [
+ { "name": "stm32f769disco", "flags": "" },
+ { "name": "stm32f769disco-DMA", "flags": "-DCFG_TUD_DWC2_DMA_ENABLE=1 -DCFG_TUH_DWC2_DMA_ENABLE=1" }
+ ],
+ "tests": {
+ "device": true,
+ "host": false,
+ "dual": false
},
"flasher": {
"name": "jlink",
- "uid": "000773661813",
- "args": "-device stm32f407vg"
+ "uid": "000778170924",
+ "args": "-device stm32f769ni"
}
}
]
diff --git a/test/unit-test/CMakeLists.txt b/test/unit-test/CMakeLists.txt
index b44a91d57..a33af4563 100644
--- a/test/unit-test/CMakeLists.txt
+++ b/test/unit-test/CMakeLists.txt
@@ -117,14 +117,14 @@ add_ceedling_test(
add_ceedling_test(
test_usbd
${CEEDLING_WORKDIR}/test/device/usbd/test_usbd.c
- "${CEEDLING_WORKDIR}/../../src/tusb.c;${CEEDLING_WORKDIR}/../../src/device/usbd.c;${CEEDLING_WORKDIR}/../../src/device/usbd_control.c;${CEEDLING_WORKDIR}/../../src/common/tusb_fifo.c"
+ "${CEEDLING_WORKDIR}/../../src/tusb.c;${CEEDLING_WORKDIR}/../../src/device/usbd.c;${CEEDLING_WORKDIR}/../../src/common/tusb_fifo.c"
"${CEEDLING_BUILD_DIR}/test/mocks/test_usbd/mock_dcd.c;${CEEDLING_BUILD_DIR}/test/mocks/test_usbd/mock_msc_device.c"
)
add_ceedling_test(
test_msc_device
${CEEDLING_WORKDIR}/test/device/msc/test_msc_device.c
- "${CEEDLING_WORKDIR}/../../src/tusb.c;${CEEDLING_WORKDIR}/../../src/device/usbd.c;${CEEDLING_WORKDIR}/../../src/device/usbd_control.c;${CEEDLING_WORKDIR}/../../src/class/msc/msc_device.c;${CEEDLING_WORKDIR}/../../src/common/tusb_fifo.c"
+ "${CEEDLING_WORKDIR}/../../src/tusb.c;${CEEDLING_WORKDIR}/../../src/device/usbd.c;${CEEDLING_WORKDIR}/../../src/class/msc/msc_device.c;${CEEDLING_WORKDIR}/../../src/common/tusb_fifo.c"
"${CEEDLING_BUILD_DIR}/test/mocks/test_msc_device/mock_dcd.c"
)
diff --git a/test/unit-test/test/device/midi2/test_midi2_device.c b/test/unit-test/test/device/midi2/test_midi2_device.c
new file mode 100644
index 000000000..1314c2585
--- /dev/null
+++ b/test/unit-test/test/device/midi2/test_midi2_device.c
@@ -0,0 +1,266 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "unity.h"
+#include "tusb_types.h"
+#include "class/audio/audio.h"
+#include "class/midi/midi.h"
+#include "device/usbd.h"
+
+void setUp(void) {}
+void tearDown(void) {}
+
+//--------------------------------------------------------------------+
+// UMP Word Count: all 16 message types
+//--------------------------------------------------------------------+
+
+void test_ump_word_count_1word_types(void) {
+ uint8_t types[] = {0x0, 0x1, 0x2, 0x6, 0x7};
+ for (int i = 0; i < 5; i++) {
+ TEST_ASSERT_EQUAL(1, midi2_ump_word_count(types[i]));
+ }
+}
+
+void test_ump_word_count_2word_types(void) {
+ uint8_t types[] = {0x3, 0x4, 0x8, 0x9, 0xA};
+ for (int i = 0; i < 5; i++) {
+ TEST_ASSERT_EQUAL(2, midi2_ump_word_count(types[i]));
+ }
+}
+
+void test_ump_word_count_3word_types(void) {
+ TEST_ASSERT_EQUAL(3, midi2_ump_word_count(0xB));
+ TEST_ASSERT_EQUAL(3, midi2_ump_word_count(0xC));
+}
+
+void test_ump_word_count_4word_types(void) {
+ uint8_t types[] = {0x5, 0xD, 0xE, 0xF};
+ for (int i = 0; i < 4; i++) {
+ TEST_ASSERT_EQUAL(4, midi2_ump_word_count(types[i]));
+ }
+}
+
+void test_ump_word_count_covers_all_16(void) {
+ for (uint8_t mt = 0; mt <= 0xF; mt++) {
+ uint8_t wc = midi2_ump_word_count(mt);
+ TEST_ASSERT_TRUE(wc >= 1 && wc <= 4);
+ }
+}
+
+//--------------------------------------------------------------------+
+// CS Endpoint subtypes (defined in midi.h)
+//--------------------------------------------------------------------+
+
+void test_cs_endpoint_subtypes(void) {
+ TEST_ASSERT_EQUAL(0x01, MIDI_CS_ENDPOINT_GENERAL);
+ TEST_ASSERT_EQUAL(0x02, MIDI_CS_ENDPOINT_GENERAL_2_0);
+}
+
+//--------------------------------------------------------------------+
+// Descriptor macro length calculations
+//--------------------------------------------------------------------+
+
+void test_midi1_desc_len(void) {
+ TEST_ASSERT_EQUAL(TUD_MIDI_DESC_HEAD_LEN + TUD_MIDI_DESC_JACK_LEN + TUD_MIDI_DESC_EP_LEN(1) * 2,
+ TUD_MIDI_DESC_LEN);
+}
+
+void test_midi2_alt1_head_len(void) {
+ TEST_ASSERT_EQUAL(16, TUD_MIDI2_DESC_ALT1_HEAD_LEN);
+}
+
+void test_midi2_alt1_ep_len(void) {
+ // EP(7) + CS base(4) + numgtbs
+ TEST_ASSERT_EQUAL(12, TUD_MIDI2_DESC_ALT1_EP_LEN(1));
+ TEST_ASSERT_EQUAL(13, TUD_MIDI2_DESC_ALT1_EP_LEN(2));
+ TEST_ASSERT_EQUAL(18, TUD_MIDI2_DESC_ALT1_EP_LEN(7));
+}
+
+void test_midi2_desc_len(void) {
+ int expected = TUD_MIDI_DESC_LEN + TUD_MIDI2_DESC_ALT1_HEAD_LEN + TUD_MIDI2_DESC_ALT1_EP_LEN(1) * 2;
+ TEST_ASSERT_EQUAL(expected, TUD_MIDI2_DESC_LEN);
+}
+
+void test_midi2_desc_len_greater_than_midi1(void) {
+ TEST_ASSERT_TRUE(TUD_MIDI2_DESC_LEN > TUD_MIDI_DESC_LEN);
+}
+
+//--------------------------------------------------------------------+
+// Descriptor macro byte validation
+//--------------------------------------------------------------------+
+
+void test_midi2_descriptor_bytes(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x01, 0x81, 64) };
+
+ TEST_ASSERT_EQUAL(TUD_MIDI2_DESC_LEN, sizeof(desc));
+
+ // First byte: Audio Control Interface descriptor length = 9
+ TEST_ASSERT_EQUAL(9, desc[0]);
+ TEST_ASSERT_EQUAL(TUSB_DESC_INTERFACE, desc[1]);
+ TEST_ASSERT_EQUAL(0, desc[2]);
+
+ // Find Alt Setting 1 by scanning
+ int alt1_offset = -1;
+ int pos = 0;
+ while (pos < (int)sizeof(desc)) {
+ if (desc[pos + 1] == TUSB_DESC_INTERFACE && desc[pos + 3] == 1) {
+ alt1_offset = pos;
+ break;
+ }
+ pos += desc[pos];
+ }
+
+ TEST_ASSERT_TRUE_MESSAGE(alt1_offset >= 0, "Alt Setting 1 interface not found");
+
+ TEST_ASSERT_EQUAL(9, desc[alt1_offset]);
+ TEST_ASSERT_EQUAL(TUSB_DESC_INTERFACE, desc[alt1_offset + 1]);
+ TEST_ASSERT_EQUAL(1, desc[alt1_offset + 2]); // bInterfaceNumber
+ TEST_ASSERT_EQUAL(1, desc[alt1_offset + 3]); // bAlternateSetting
+ TEST_ASSERT_EQUAL(2, desc[alt1_offset + 4]); // bNumEndpoints
+ TEST_ASSERT_EQUAL(TUSB_CLASS_AUDIO, desc[alt1_offset + 5]);
+
+ // MS Header after Alt Setting 1 interface: bcdMSC = 0x0200
+ int ms2_offset = alt1_offset + 9;
+ TEST_ASSERT_EQUAL(7, desc[ms2_offset]);
+ TEST_ASSERT_EQUAL(TUSB_DESC_CS_INTERFACE, desc[ms2_offset + 1]);
+ TEST_ASSERT_EQUAL(MIDI_CS_INTERFACE_HEADER, desc[ms2_offset + 2]);
+ TEST_ASSERT_EQUAL(0x00, desc[ms2_offset + 3]);
+ TEST_ASSERT_EQUAL(0x02, desc[ms2_offset + 4]);
+ // USB-MIDI 2.0 Table 5-2: wTotalLength shall match bLength (= 0x0007)
+ TEST_ASSERT_EQUAL(0x07, desc[ms2_offset + 5]);
+ TEST_ASSERT_EQUAL(0x00, desc[ms2_offset + 6]);
+}
+
+void test_midi2_descriptor_alt1_cs_endpoint_subtype(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x01, 0x81, 64) };
+
+ int cs_ep_count = 0;
+ int pos = 0;
+ while (pos < (int)sizeof(desc)) {
+ if (desc[pos + 1] == TUSB_DESC_CS_ENDPOINT &&
+ desc[pos + 2] == MIDI_CS_ENDPOINT_GENERAL_2_0) {
+ cs_ep_count++;
+ TEST_ASSERT_EQUAL(1, desc[pos + 3]);
+ }
+ pos += desc[pos];
+ }
+ TEST_ASSERT_EQUAL(2, cs_ep_count);
+}
+
+void test_midi2_descriptor_has_both_alt_settings(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x01, 0x81, 64) };
+
+ int alt0_count = 0;
+ int alt1_count = 0;
+ int pos = 0;
+ while (pos < (int)sizeof(desc)) {
+ if (desc[pos + 1] == TUSB_DESC_INTERFACE) {
+ if (desc[pos + 3] == 0) alt0_count++;
+ if (desc[pos + 3] == 1) alt1_count++;
+ }
+ pos += desc[pos];
+ }
+ TEST_ASSERT_TRUE(alt0_count >= 2);
+ TEST_ASSERT_EQUAL(1, alt1_count);
+}
+
+void test_midi2_descriptor_endpoint_addresses(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x02, 0x82, 64) };
+
+ int ep_out_count = 0;
+ int ep_in_count = 0;
+ int pos = 0;
+ while (pos < (int)sizeof(desc)) {
+ if (desc[pos + 1] == TUSB_DESC_ENDPOINT) {
+ uint8_t ep_addr = desc[pos + 2];
+ if (ep_addr == 0x02) ep_out_count++;
+ if (ep_addr == 0x82) ep_in_count++;
+ TEST_ASSERT_EQUAL(TUSB_XFER_BULK, desc[pos + 3]);
+ TEST_ASSERT_EQUAL(64, desc[pos + 4]);
+ TEST_ASSERT_EQUAL(0, desc[pos + 5]);
+ }
+ pos += desc[pos];
+ }
+ TEST_ASSERT_EQUAL(2, ep_out_count);
+ TEST_ASSERT_EQUAL(2, ep_in_count);
+}
+
+void test_midi2_descriptor_nonzero_itfnum(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(2, 0, 0x03, 0x83, 64) };
+
+ TEST_ASSERT_EQUAL(2, desc[2]);
+
+ int pos = desc[0];
+ while (pos < (int)sizeof(desc)) {
+ if (desc[pos + 1] == TUSB_DESC_INTERFACE) {
+ TEST_ASSERT_EQUAL(3, desc[pos + 2]);
+ break;
+ }
+ pos += desc[pos];
+ }
+}
+
+//--------------------------------------------------------------------+
+// Descriptor traversal integrity
+//--------------------------------------------------------------------+
+
+void test_midi2_descriptor_no_zero_length(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x01, 0x81, 64) };
+
+ int pos = 0;
+ int desc_count = 0;
+ while (pos < (int)sizeof(desc)) {
+ TEST_ASSERT_TRUE_MESSAGE(desc[pos] > 0, "Zero-length descriptor found");
+ TEST_ASSERT_TRUE_MESSAGE(desc[pos] <= (int)sizeof(desc) - pos,
+ "Descriptor length exceeds remaining bytes");
+ pos += desc[pos];
+ desc_count++;
+ }
+ TEST_ASSERT_EQUAL((int)sizeof(desc), pos);
+ TEST_ASSERT_TRUE(desc_count > 5);
+}
+
+void test_midi2_descriptor_valid_types(void) {
+ uint8_t desc[] = { TUD_MIDI2_DESCRIPTOR(0, 0, 0x01, 0x81, 64) };
+
+ int pos = 0;
+ while (pos < (int)sizeof(desc)) {
+ uint8_t dtype = desc[pos + 1];
+ bool valid = (dtype == TUSB_DESC_INTERFACE ||
+ dtype == TUSB_DESC_ENDPOINT ||
+ dtype == TUSB_DESC_CS_INTERFACE ||
+ dtype == TUSB_DESC_CS_ENDPOINT);
+ TEST_ASSERT_TRUE_MESSAGE(valid, "Invalid descriptor type found");
+ pos += desc[pos];
+ }
+}
+
+//--------------------------------------------------------------------+
+// Edge cases
+//--------------------------------------------------------------------+
+
+void test_ump_word_count_with_values_beyond_0xf(void) {
+ TEST_ASSERT_EQUAL(4, midi2_ump_word_count(0x10));
+ TEST_ASSERT_EQUAL(4, midi2_ump_word_count(0xFF));
+}
diff --git a/test/unit-test/test/device/usbd/test_usbd.c b/test/unit-test/test/device/usbd/test_usbd.c
index 3a2cf3217..7f3c3f5b2 100644
--- a/test/unit-test/test/device/usbd/test_usbd.c
+++ b/test/unit-test/test/device/usbd/test_usbd.c
@@ -29,7 +29,7 @@
#include "tusb_fifo.h"
#include "tusb.h"
#include "usbd.h"
-TEST_SOURCE_FILE("usbd_control.c")
+TEST_SOURCE_FILE("usbd.c")
// Mock File
#include "mock_dcd.h"
@@ -100,6 +100,16 @@ tusb_control_request_t const req_get_desc_configuration =
.wLength = 256
};
+// Vendor OUT control request (direction OUT, type Vendor, recipient Device), 8-byte data stage
+tusb_control_request_t const req_vendor_out =
+{
+ .bmRequestType = 0x40,
+ .bRequest = 0x01,
+ .wValue = 0x0000,
+ .wIndex = 0x0000,
+ .wLength = 8
+};
+
uint8_t const* desc_device;
uint8_t const* desc_configuration;
@@ -120,6 +130,19 @@ uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
return NULL;
}
+// Backing buffer for the vendor OUT data stage. Sized to EP0 max packet so an (untested) regression
+// that drops the clamp can't corrupt memory here; the regression is caught by the expectation below.
+static uint8_t vendor_out_buf[CFG_TUD_ENDPOINT0_SIZE];
+
+bool tud_vendor_control_xfer_cb(uint8_t rhport_, uint8_t stage, tusb_control_request_t const* request) {
+ (void) request;
+ if (stage == CONTROL_STAGE_SETUP) {
+ // Offer only an 8-byte capacity even though the data stage may receive a larger packet
+ return tud_control_xfer(rhport_, request, vendor_out_buf, 8);
+ }
+ return true;
+}
+
void setUp(void) {
dcd_int_disable_Ignore();
dcd_int_enable_Ignore();
@@ -246,3 +269,30 @@ void test_usbd_control_in_zlp(void)
tud_task();
}
+
+//--------------------------------------------------------------------+
+// Control OUT data stage host overrun
+//--------------------------------------------------------------------+
+
+// A non-compliant host sends an OUT data packet larger than the buffer the class offered:
+// wLength = 8, but the DCD reports a full CFG_TUD_ENDPOINT0_SIZE packet. usbd must clamp the
+// copy/accounting to the 8-byte capacity so total_xferred reaches wLength, ends the data stage,
+// and queues the IN status stage. Without the clamp total_xferred overshoots wLength and usbd
+// re-arms an OUT data packet (EDPT_CTRL_OUT) instead, failing the EDPT_CTRL_IN expectation below.
+void test_usbd_control_out_overrun_clamp(void)
+{
+ dcd_event_setup_received(rhport, (uint8_t*) &req_vendor_out, false);
+
+ // Data stage: usbd arms an 8-byte OUT into its internal bounce buffer (buffer ptr is internal)
+ dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_OUT, NULL, 8, false, true);
+ dcd_edpt_xfer_IgnoreArg_buffer();
+ // Host overrun: DCD reports a full max packet, larger than the 8-byte capacity
+ dcd_event_xfer_complete(rhport, EDPT_CTRL_OUT, CFG_TUD_ENDPOINT0_SIZE, XFER_RESULT_SUCCESS, false);
+
+ // Clamp -> total_xferred == wLength -> data stage done -> IN status stage queued
+ dcd_edpt_xfer_ExpectAndReturn(rhport, EDPT_CTRL_IN, NULL, 0, false, true);
+ dcd_event_xfer_complete(rhport, EDPT_CTRL_IN, 0, 0, false);
+ dcd_edpt0_status_complete_ExpectWithArray(rhport, &req_vendor_out, 1);
+
+ tud_task();
+}
diff --git a/test/unit-test/test/host/midi2/test_midi2_host.c b/test/unit-test/test/host/midi2/test_midi2_host.c
new file mode 100644
index 000000000..8ad77c14e
--- /dev/null
+++ b/test/unit-test/test/host/midi2/test_midi2_host.c
@@ -0,0 +1,101 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2026 Saulo Verissimo
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "unity.h"
+#include "tusb_option.h"
+#include "class/midi/midi.h"
+#include "class/midi/midi2_host.h"
+
+void setUp(void) {}
+void tearDown(void) {}
+
+//--------------------------------------------------------------------+
+// UMP Word Count (shared helper, defined in midi.h)
+//--------------------------------------------------------------------+
+
+void test_midi2_host_ump_word_count_1word(void) {
+ uint8_t types[] = {0x0, 0x1, 0x2, 0x6, 0x7};
+ for (int i = 0; i < 5; i++) {
+ TEST_ASSERT_EQUAL(1, midi2_ump_word_count(types[i]));
+ }
+}
+
+void test_midi2_host_ump_word_count_2word(void) {
+ uint8_t types[] = {0x3, 0x4, 0x8, 0x9, 0xA};
+ for (int i = 0; i < 5; i++) {
+ TEST_ASSERT_EQUAL(2, midi2_ump_word_count(types[i]));
+ }
+}
+
+void test_midi2_host_ump_word_count_4word(void) {
+ uint8_t types[] = {0x5, 0xD, 0xE, 0xF};
+ for (int i = 0; i < 4; i++) {
+ TEST_ASSERT_EQUAL(4, midi2_ump_word_count(types[i]));
+ }
+}
+
+//--------------------------------------------------------------------+
+// Callback struct field validation
+//--------------------------------------------------------------------+
+
+void test_midi2_descriptor_cb_struct_fields(void) {
+ tuh_midi2_descriptor_cb_t desc = {
+ .protocol_version = 1,
+ .bcdMSC_hi = 0x02,
+ .bcdMSC_lo = 0x00,
+ .rx_cable_count = 1,
+ .tx_cable_count = 1
+ };
+ TEST_ASSERT_EQUAL(1, desc.protocol_version);
+ TEST_ASSERT_EQUAL(0x02, desc.bcdMSC_hi);
+ TEST_ASSERT_EQUAL(0x00, desc.bcdMSC_lo);
+ TEST_ASSERT_EQUAL(1, desc.rx_cable_count);
+ TEST_ASSERT_EQUAL(1, desc.tx_cable_count);
+}
+
+void test_midi2_mount_cb_struct_fields(void) {
+ tuh_midi2_mount_cb_t mount = {
+ .daddr = 1,
+ .bInterfaceNumber = 0,
+ .protocol_version = 1,
+ .alt_setting_active = 1,
+ .rx_cable_count = 2,
+ .tx_cable_count = 2
+ };
+ TEST_ASSERT_EQUAL(1, mount.daddr);
+ TEST_ASSERT_EQUAL(0, mount.bInterfaceNumber);
+ TEST_ASSERT_EQUAL(1, mount.protocol_version);
+ TEST_ASSERT_EQUAL(1, mount.alt_setting_active);
+ TEST_ASSERT_EQUAL(2, mount.rx_cable_count);
+ TEST_ASSERT_EQUAL(2, mount.tx_cable_count);
+}
+
+//--------------------------------------------------------------------+
+// CS Endpoint subtypes
+//--------------------------------------------------------------------+
+
+void test_midi2_host_cs_endpoint_subtypes(void) {
+ TEST_ASSERT_EQUAL(0x01, MIDI_CS_ENDPOINT_GENERAL);
+ TEST_ASSERT_EQUAL(0x02, MIDI_CS_ENDPOINT_GENERAL_2_0);
+}
diff --git a/tools/build.py b/tools/build.py
index 3c5c3c077..86bc30d28 100755
--- a/tools/build.py
+++ b/tools/build.py
@@ -105,16 +105,14 @@ def print_build_result(board, build_target, status, duration):
# -----------------------------
# CMake
# -----------------------------
-def cmake_board(board, build_args, build_flags_on, build_targets):
+def cmake_board(board, build_args, build_name, build_cflags, build_targets):
ret = [0, 0, 0]
start_time = time.monotonic()
- build_dir = f'cmake-build/cmake-build-{board}'
+ build_dir = f'cmake-build/cmake-build-{build_name or board}'
build_flags = []
- if len(build_flags_on) > 0:
- cli_flags = ' '.join(f'-D{flag}=1' for flag in build_flags_on)
- build_flags.append(f'-DCFLAGS_CLI={cli_flags}')
- build_dir += '-f1_' + '_'.join(build_flags_on)
+ if build_cflags:
+ build_flags.append('-DCFLAGS_CLI=' + ' '.join(build_cflags))
family = find_family(board)
if family == 'espressif':
@@ -194,13 +192,13 @@ def make_board(board, build_args, build_targets):
# -----------------------------
# Build Family
# -----------------------------
-def build_boards_list(boards, build_defines, build_system, build_flags_on, build_targets):
+def build_boards_list(boards, build_defines, build_system, build_name, build_cflags, build_targets):
ret = [0, 0, 0]
for b in boards:
r = [0, 0, 0]
if build_system == 'cmake':
build_args = [f'-D{d}' for d in build_defines]
- r = cmake_board(b, build_args, build_flags_on, build_targets)
+ r = cmake_board(b, build_args, build_name, build_cflags, build_targets)
elif build_system == 'make':
build_args = ' '.join(f'{d}' for d in build_defines)
r = make_board(b, build_args, build_targets)
@@ -261,7 +259,10 @@ def main():
parser.add_argument('-t', '--toolchain', default='gcc', help='Toolchain to use, default is gcc')
parser.add_argument('-s', '--build-system', default='cmake', help='Build system to use, default is cmake')
parser.add_argument('-D', '--define-symbol', action='append', default=[], help='Define to pass to build system')
- parser.add_argument('-f1', '--build-flags-on', action='append', default=[], help='Build flag to pass to build system')
+ parser.add_argument('--build-name', default=None,
+ help='Override build dir name (cmake-build-<name>); default is the board name. Used for HIL variants.')
+ parser.add_argument('--cflag', action='append', default=[],
+ help='Raw compiler flag appended to CFLAGS_CLI, e.g. --cflag=-DCFG_TUD_DWC2_DMA_ENABLE=1 (repeatable)')
parser.add_argument('--one-random', action='store_true', default=False,
help='Build only one random board of each specified family')
parser.add_argument('--one-first', action='store_true', default=False,
@@ -277,7 +278,8 @@ def main():
toolchain = args.toolchain
build_system = args.build_system
build_defines = args.define_symbol
- build_flags_on = args.build_flags_on
+ build_name = args.build_name
+ build_cflags = args.cflag
one_random = args.one_random
one_first = args.one_first
build_targets = args.target if args.target else ['all']
@@ -290,6 +292,12 @@ def main():
print("Please specify families or board to build")
return 1
+ # --build-name renames the single shared build dir, so building more than one
+ # board with it would clobber/mix artifacts
+ if build_name and (len(families) > 0 or len(boards) != 1):
+ print("--build-name requires exactly one board (-b) and no families")
+ return 1
+
print(build_separator)
print(build_format.format('Board', 'Target', '\033[39mResult\033[0m', 'Time'))
total_time = time.monotonic()
@@ -310,7 +318,7 @@ def main():
all_boards.extend(get_family_boards(f, one_random, one_first))
# build all boards
- result = build_boards_list(all_boards, build_defines, build_system, build_flags_on, build_targets)
+ result = build_boards_list(all_boards, build_defines, build_system, build_name, build_cflags, build_targets)
total_time = time.monotonic() - total_time
print(build_separator)
diff --git a/tools/codespell/ignore-words.txt b/tools/codespell/ignore-words.txt
index 7ce778fab..0b1aa284a 100644
--- a/tools/codespell/ignore-words.txt
+++ b/tools/codespell/ignore-words.txt
@@ -6,6 +6,7 @@ fro
hsi
inout
mot
+ore
pris
ptd
ser
diff --git a/tools/gen_presets.py b/tools/gen_presets.py
index 94a9361db..6f32976a7 100755
--- a/tools/gen_presets.py
+++ b/tools/gen_presets.py
@@ -32,7 +32,7 @@ def main():
"hidden": True,
"description": r"Configure preset for the ${presetName} board",
"generator": "Ninja Multi-Config",
- "binaryDir": r"${sourceDir}/build/${presetName}",
+ "binaryDir": r"${sourceDir}/cmake-build-${presetName}",
"cacheVariables": {
"CMAKE_DEFAULT_BUILD_TYPE": "RelWithDebInfo",
"BOARD": r"${presetName}"
@@ -41,7 +41,7 @@ def main():
"hidden": True,
"description": r"Configure preset for the ${presetName} board",
"generator": "Ninja",
- "binaryDir": r"${sourceDir}/build/${presetName}",
+ "binaryDir": r"${sourceDir}/cmake-build-${presetName}",
"cacheVariables": {
"BOARD": r"${presetName}"
}}]
diff --git a/tools/get_deps.py b/tools/get_deps.py
index eb87abf6e..ebbf9b871 100755
--- a/tools/get_deps.py
+++ b/tools/get_deps.py
@@ -163,6 +163,9 @@ deps_optional = {
'hw/mcu/st/cmsis-device-wba': ['https://github.com/STMicroelectronics/cmsis-device-wba.git',
'647d8522e5fd15049e9a1cc30ed19d85e5911eaf',
'stm32wba'],
+ 'hw/mcu/st/stm32c5xx-dfp': ['https://github.com/STMicroelectronics/stm32c5xx-dfp.git',
+ '6d0940882511d9430f83af9bd3da6bcb77f79239',
+ 'stm32c5'],
'hw/mcu/st/stm32-mfxstm32l152': ['https://github.com/STMicroelectronics/stm32-mfxstm32l152.git',
'7f4389efee9c6a655b55e5df3fceef5586b35f9b',
'stm32h7'],
@@ -232,6 +235,9 @@ deps_optional = {
'hw/mcu/st/stm32wbaxx_hal_driver': ['https://github.com/STMicroelectronics/stm32wbaxx_hal_driver.git',
'9442fbb71f855ff2e64fbf662b7726beba511a24',
'stm32wba'],
+ 'hw/mcu/st/stm32c5xx-drivers': ['https://github.com/STMicroelectronics/stm32c5xx-drivers.git',
+ '79b901285a7efeaf87c4c25db81d24cb5d8c9465',
+ 'stm32c5'],
'hw/mcu/ti': ['https://github.com/hathach/ti_driver.git',
'083944907e7d08fcb1f614b47598ce45935b8da1',
'msp430 msp432e4 tm4c'],
@@ -247,6 +253,9 @@ deps_optional = {
'hw/mcu/wch/ch32f20x': ['https://github.com/openwch/ch32f20x.git',
'77c4095087e5ed2c548ec9058e655d0b8757663b',
'ch32f20x'],
+ 'hw/mcu/wch/ch583': ['https://github.com/openwch/ch583.git',
+ 'bd508ad7ceed48377619837051412a651952857f',
+ 'ch583'],
'hw/mcu/artery/at32f403a_407': ['https://github.com/ArteryTek/AT32F403A_407_Firmware_Library.git',
'f2cb360c3d28fada76b374308b8c4c61d37a090b',
'at32f403a_407'],
@@ -284,7 +293,7 @@ deps_optional = {
'tm4c '],
'lib/CMSIS_6': ['https://github.com/ARM-software/CMSIS_6.git',
'6f0a58d01aa9bd2feba212097f9afe7acd991d52',
- 'imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx'],
+ 'imxrt kinetis_k32l ra stm32n6 lpc51 lpc55 mcx stm32c5'],
'lib/sct_neopixel': ['https://github.com/gsteiert/sct_neopixel.git',
'e73e04ca63495672d955f9268e003cffe168fcd8',
'lpc55'],
@@ -366,6 +375,8 @@ def main():
parser.add_argument('-b', '--board', action='append', default=[], help='Boards to fetch')
parser.add_argument('-D', '--define', action='append', default=[], help='Have no effect')
parser.add_argument('-f1', '--build-flags-on', action='append', default=[], help='Have no effect')
+ parser.add_argument('--build-name', default=None, help='Have no effect')
+ parser.add_argument('--cflag', action='append', default=[], help='Have no effect')
args = parser.parse_args()
families = args.families
diff --git a/tools/metrics.py b/tools/metrics.py
index f624f382f..0e29fc1ab 100644
--- a/tools/metrics.py
+++ b/tools/metrics.py
@@ -384,9 +384,9 @@ def render_combine_table(json_data, sort_order='name+'):
def write_combine_markdown(json_data, path, sort_order='name+', title="TinyUSB Average Code Size Metrics"):
"""Write averaged size data to a markdown file."""
- md_lines = [f"# {title}", ""]
+ md_lines = [f"## {title}", "", "<details><summary>Size table</summary>", ""]
md_lines.extend(render_combine_table(json_data, sort_order))
- md_lines.append("")
+ md_lines.extend(["", "</details>", ""])
if json_data.get("file_list"):
md_lines.extend(["<details>", "<summary>Input files</summary>", ""])
@@ -400,7 +400,7 @@ def write_combine_markdown(json_data, path, sort_order='name+', title="TinyUSB A
def write_compare_markdown(comparison, path, sort_order='size'):
"""Write comparison data to markdown file."""
md_lines = [
- "# Size Difference Report",
+ "## Size Difference Report",
"",
"Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.",
"",
@@ -415,7 +415,7 @@ def write_compare_markdown(comparison, path, sort_order='size'):
md_lines.append(f"<details><summary>{title}</summary>")
md_lines.append("")
else:
- md_lines.append(f"## {title}")
+ md_lines.append(f"### {title}")
md_lines.extend(render_compare_table(_build_rows(rows, sort_order), include_sum=True))
md_lines.append("")
@@ -425,7 +425,7 @@ def write_compare_markdown(comparison, path, sort_order='size'):
md_lines.append("")
render("Changes >1% in size", significant)
- render("Changes <1% in size", minor)
+ render("Changes <1% in size", minor, collapsed=True)
render("No changes", unchanged, collapsed=True)
with open(path, "w", encoding="utf-8") as f:
diff --git a/tools/metrics_compare_base.py b/tools/metrics_compare_base.py
new file mode 100644
index 000000000..799a96800
--- /dev/null
+++ b/tools/metrics_compare_base.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python3
+"""Build base branch (master) and current tree, then compare code size metrics.
+
+Creates cmake-metrics/<board>/{base,build} directories for each board.
+With --combined, also writes cmake-metrics/_combined/metrics_compare.md aggregating
+all boards into a single comparison.
+
+Usage:
+ python tools/metrics_compare_base.py -b raspberry_pi_pico
+ python tools/metrics_compare_base.py -b raspberry_pi_pico -b raspberry_pi_pico2
+ python tools/metrics_compare_base.py -b raspberry_pi_pico -f portable/raspberrypi
+ python tools/metrics_compare_base.py -b raspberry_pi_pico -e device/cdc_msc
+ python tools/metrics_compare_base.py -b raspberry_pi_pico -e device/cdc_msc --bloaty
+ python tools/metrics_compare_base.py --ci # first board of each arm-gcc family, combined
+ python tools/metrics_compare_base.py -b pico -b pico2 --combined # aggregate listed boards
+"""
+import argparse
+import glob
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+
+TINYUSB_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+METRICS_DIR = os.path.join(TINYUSB_ROOT, 'cmake-metrics')
+
+def tinyusb_src_filter(checkout_dir):
+ """Return a path-substring filter that uniquely matches TinyUSB stack source files
+ in `checkout_dir`. The substring is the absolute path to the checkout's `src/`
+ dir — collision-free with vendored deps (pico-sdk, lwip, FreeRTOS, etc.) which
+ live at unrelated paths."""
+ return os.path.realpath(os.path.join(checkout_dir, 'src')) + os.sep
+
+verbose = False
+
+
+def run(cmd, **kwargs):
+ """Run a command. cmd must be a list (no shell=True). On `timeout=`-induced
+ TimeoutExpired, return a CompletedProcess with rc=124 instead of letting the
+ exception propagate, so the caller can fall through to error reporting and
+ worktree cleanup rather than crashing with a traceback."""
+ if not isinstance(cmd, list):
+ raise TypeError('run() requires a list, got str — fix the caller')
+ if verbose:
+ print(f' $ {" ".join(shlex.quote(str(c)) for c in cmd)}')
+ try:
+ return subprocess.run(cmd, capture_output=True, text=True, **kwargs)
+ except subprocess.TimeoutExpired as e:
+ msg = f'Command timed out after {e.timeout}s: {" ".join(shlex.quote(str(c)) for c in cmd)}'
+ stderr = (e.stderr or '') + ('\n' if e.stderr else '') + msg
+ return subprocess.CompletedProcess(cmd, 124, stdout=(e.stdout or ''), stderr=stderr)
+
+
+def symlink_deps(main_root, worktree_dir):
+ """Symlink dependency directories (fetched by tools/get_deps.py) from the main
+ checkout into the temporary worktree. Without this, the base build fails because
+ the worktree doesn't have the untracked deps."""
+ def link_subdirs(rel_parent):
+ src_parent = os.path.join(main_root, rel_parent)
+ dst_parent = os.path.join(worktree_dir, rel_parent)
+ if not os.path.isdir(src_parent):
+ return
+ os.makedirs(dst_parent, exist_ok=True)
+ for entry in os.listdir(src_parent):
+ src = os.path.join(src_parent, entry)
+ dst = os.path.join(dst_parent, entry)
+ if os.path.isdir(src) and not os.path.exists(dst):
+ os.symlink(src, dst)
+
+ # lib/* and tools/* deps (e.g. lib/lwip, tools/linkermap)
+ link_subdirs('lib')
+ link_subdirs('tools')
+ # hw/mcu/<vendor>/<dep> (e.g. hw/mcu/raspberry_pi/Pico-PIO-USB)
+ hw_mcu = os.path.join(main_root, 'hw', 'mcu')
+ if os.path.isdir(hw_mcu):
+ for vendor in os.listdir(hw_mcu):
+ link_subdirs(os.path.join('hw', 'mcu', vendor))
+
+
+def ci_first_boards():
+ """Return the first board (alphabetical) of each arm-gcc CI family."""
+ matrix_py = os.path.join(TINYUSB_ROOT, '.github', 'workflows', 'ci_set_matrix.py')
+ if not os.path.isfile(matrix_py):
+ return []
+ ret = run([sys.executable, matrix_py])
+ if ret.returncode != 0:
+ return []
+ try:
+ data = json.loads(ret.stdout)
+ except json.JSONDecodeError:
+ return []
+ families = data.get('arm-gcc', [])
+ boards = []
+ bsp_root = os.path.join(TINYUSB_ROOT, 'hw', 'bsp')
+ for family in families:
+ family_boards = sorted(
+ d for d in os.listdir(os.path.join(bsp_root, family, 'boards'))
+ if os.path.isdir(os.path.join(bsp_root, family, 'boards', d))
+ ) if os.path.isdir(os.path.join(bsp_root, family, 'boards')) else []
+ if family_boards:
+ boards.append(family_boards[0])
+ return boards
+
+
+def build_board(src_dir, build_dir, board, example=None):
+ """Configure and build examples for a board. Returns True on success.
+
+ When `example` is given, only that target is built (`cmake --build --target NAME`),
+ keeping single-example workflows fast.
+ """
+ os.makedirs(build_dir, exist_ok=True)
+ ret = run(['cmake', '-B', build_dir, '-G', 'Ninja',
+ f'-DBOARD={board}', '-DCMAKE_BUILD_TYPE=MinSizeRel',
+ os.path.join(src_dir, 'examples')])
+ if ret.returncode != 0:
+ print(f' Error configuring {board}: {ret.stderr}')
+ return False
+ cmd = ['cmake', '--build', build_dir]
+ if example:
+ cmd += ['--target', os.path.basename(example)]
+ ret = run(cmd, timeout=600)
+ if ret.returncode != 0:
+ print(f' Error building {board}: {ret.stderr}')
+ return False
+ return True
+
+
+def generate_metrics(build_dir, out_basename, filters, example=None):
+ """Run metrics.py combine on .map.json files. Returns metrics json path or None.
+
+ `filters` is a list of substrings; metrics.py keeps a compile unit if its path
+ contains any of them.
+ """
+ if example:
+ patterns = glob.glob(f'{build_dir}/{example}/*.map.json')
+ else:
+ patterns = glob.glob(f'{build_dir}/**/*.map.json', recursive=True)
+ if not patterns:
+ print(f' Error: no .map.json files in {build_dir}' + (f' for {example}' if example else ''))
+ return None
+
+ metrics_py = os.path.join(TINYUSB_ROOT, 'tools', 'metrics.py')
+ cmd = [sys.executable, metrics_py, 'combine']
+ for f in filters:
+ cmd += ['-f', f]
+ cmd += ['-j', '-q', '-o', out_basename, *patterns]
+ ret = run(cmd)
+ if ret.returncode != 0:
+ print(f' Error: {ret.stderr}')
+ return None
+ return f'{out_basename}.json'
+
+
+def main():
+ global verbose
+
+ parser = argparse.ArgumentParser(description='Compare code size metrics with base branch')
+ parser.add_argument('-b', '--board', action='append', default=[],
+ help='Board name (repeatable). Required unless --ci is given.')
+ parser.add_argument('-f', '--filter', action='append', default=None,
+ help='Path-substring filter (repeatable). When given, '
+ 'overrides the default and is applied to BOTH base and '
+ 'current builds. Default: each side\'s own absolute '
+ '<checkout>/src/ path, which uniquely matches TinyUSB '
+ 'stack code without colliding with vendored deps.')
+ parser.add_argument('--base-branch', default='master',
+ help='Base branch to compare against (default: master)')
+ parser.add_argument('-e', '--example', action='append', default=None,
+ help='Compare specific example (repeatable, e.g. -e device/cdc_msc -e host/cdc_msc_hid)')
+ parser.add_argument('--bloaty', action='store_true',
+ help='Use bloaty for detailed section/symbol diff (requires -e)')
+ parser.add_argument('--ci', action='store_true',
+ help='Add the first board of every arm-gcc CI family. Implies --combined.')
+ parser.add_argument('--combined', action='store_true',
+ help='Aggregate map.json files across all boards into one comparison '
+ '(in cmake-metrics/_combined/), instead of (or in addition to) per-board.')
+ parser.add_argument('-v', '--verbose', action='store_true',
+ help='Print build commands')
+ args = parser.parse_args()
+ verbose = args.verbose
+
+ if args.bloaty and not args.example:
+ parser.error('--bloaty requires -e/--example')
+
+ if args.ci:
+ args.combined = True
+ ci_boards = ci_first_boards()
+ if not ci_boards:
+ parser.error('--ci: failed to derive boards from .github/workflows/ci_set_matrix.py')
+ # Append, dedup, preserve order
+ seen = set(args.board)
+ for b in ci_boards:
+ if b not in seen:
+ args.board.append(b)
+ seen.add(b)
+
+ if not args.board:
+ parser.error('at least one -b BOARD is required (or pass --ci)')
+
+ metrics_py = os.path.join(TINYUSB_ROOT, 'tools', 'metrics.py')
+ worktree_dir = os.path.join(METRICS_DIR, '_worktree')
+
+ # Per-side filters: when no override is given, each build uses its own
+ # absolute <checkout>/src/ path so we only match TinyUSB stack code from that
+ # checkout (and never vendored-dep `src/` like pico-sdk/src/...).
+ if args.filter:
+ base_filters = cur_filters = list(args.filter)
+ else:
+ base_filters = [tinyusb_src_filter(worktree_dir)]
+ cur_filters = [tinyusb_src_filter(TINYUSB_ROOT)]
+
+ # Step 1: Create worktree for base branch
+ print(f'[1/5] Setting up {args.base_branch} worktree...')
+ if os.path.isdir(worktree_dir):
+ run(['git', '-C', TINYUSB_ROOT, 'worktree', 'remove', '--force', worktree_dir])
+ # --detach: check out the ref at a detached HEAD instead of trying to claim the
+ # branch. Lets us add a worktree of `master` even if master is already checked
+ # out elsewhere (main repo, another worktree).
+ ret = run(['git', '-C', TINYUSB_ROOT, 'worktree', 'add', '--detach',
+ worktree_dir, args.base_branch])
+ if ret.returncode != 0:
+ print(f'Error creating worktree: {ret.stderr}')
+ sys.exit(1)
+
+ # Symlink dependency dirs (lib/*, hw/mcu/*/*, tools/*) so the worktree builds.
+ symlink_deps(TINYUSB_ROOT, worktree_dir)
+
+ try:
+ examples = args.example or [None]
+ # For --combined: track every (base_build, cur_build) pair so we can aggregate at the end.
+ built_pairs = []
+
+ for board in args.board:
+ print(f'\n=== {board} ===')
+ board_dir = os.path.join(METRICS_DIR, board)
+ base_build = os.path.join(board_dir, 'base')
+ cur_build = os.path.join(board_dir, 'build')
+
+ # Build only the requested examples (or all if -e not given). Single-example
+ # mode used to build everything and filter at metric time — that was wasted work.
+ board_failed = False
+ for example in examples:
+ build_label = f' --target {os.path.basename(example)}' if example else ''
+ print(f'[2/5] Building {args.base_branch} for {board}{build_label}...')
+ if not build_board(worktree_dir, base_build, board, example):
+ board_failed = True
+ break
+ print(f'[3/5] Building current for {board}{build_label}...')
+ if not build_board(TINYUSB_ROOT, cur_build, board, example):
+ board_failed = True
+ break
+ if board_failed:
+ continue
+
+ built_pairs.append((board, base_build, cur_build))
+
+ for example in examples:
+ suffix = f'_{example.replace("/", "_")}' if example else ''
+ label = f' ({example})' if example else ''
+
+ # Step 4: Generate metrics
+ print(f'[4/5] Generating metrics for {board}{label}...')
+ base_json = generate_metrics(base_build, os.path.join(board_dir, f'base_metrics{suffix}'),
+ base_filters, example)
+ cur_json = generate_metrics(cur_build, os.path.join(board_dir, f'build_metrics{suffix}'),
+ cur_filters, example)
+ if not base_json or not cur_json:
+ continue
+
+ # Step 5: Compare
+ out_base = os.path.join(board_dir, f'metrics_compare{suffix}')
+ print(f'[5/5] Comparing {board}{label}...')
+ ret = run([sys.executable, metrics_py, 'compare', '-m', '-o', out_base, base_json, cur_json])
+ print(ret.stdout)
+
+ # Optional: bloaty diff
+ if args.bloaty and example:
+ elf_name = os.path.basename(example)
+ base_elf = os.path.join(base_build, example, f'{elf_name}.elf')
+ cur_elf = os.path.join(cur_build, example, f'{elf_name}.elf')
+ if os.path.exists(base_elf) and os.path.exists(cur_elf):
+ # Bloaty expects one regex; OR-join all filters (current side
+ # for the new ELF, base side for the base ELF).
+ bloaty_regex = '(' + '|'.join(
+ re.escape(f) for f in (cur_filters + base_filters)
+ ) + ')'
+ bloaty_common = ['bloaty', '--domain=vm', f'--source-filter={bloaty_regex}']
+ print(f'--- bloaty sections ---')
+ ret = run(bloaty_common + ['-d', 'compileunits,sections', cur_elf, '--', base_elf])
+ print(ret.stdout)
+ print(f'--- bloaty symbols ---')
+ ret = run(bloaty_common + ['-d', 'compileunits,symbols', '-s', 'vm',
+ cur_elf, '--', base_elf])
+ print(ret.stdout)
+ else:
+ print(f' bloaty: ELF not found')
+
+ # Optional combined comparison across all boards.
+ # Aggregates the per-board metrics JSONs (not raw map.json globs) so the argv
+ # stays small even with --ci spanning many boards.
+ if args.combined and built_pairs:
+ combined_dir = os.path.join(METRICS_DIR, '_combined')
+ os.makedirs(combined_dir, exist_ok=True)
+
+ # Use the no-suffix per-board JSONs (whole-board metrics). Combined mode
+ # is meant for board-level sweeps; -e/--example combinations skip combined.
+ base_jsons, cur_jsons = [], []
+ for board, _, _ in built_pairs:
+ bj = os.path.join(METRICS_DIR, board, 'base_metrics.json')
+ cj = os.path.join(METRICS_DIR, board, 'build_metrics.json')
+ if os.path.isfile(bj) and os.path.isfile(cj):
+ base_jsons.append(bj)
+ cur_jsons.append(cj)
+
+ if not base_jsons or not cur_jsons:
+ print(' combined: no per-board metrics found (did you pass -e? skip --combined with -e)')
+ else:
+ print(f'\n=== combined ({len(base_jsons)} boards) ===')
+ base_out = os.path.join(combined_dir, 'base_metrics')
+ cur_out = os.path.join(combined_dir, 'build_metrics')
+
+ # Per-board JSONs are already filtered to TinyUSB-only files; combine
+ # without re-filtering so we don't accidentally drop entries.
+ def _combine(out_basename, inputs):
+ cmd = [sys.executable, metrics_py, 'combine',
+ '-j', '-q', '-o', out_basename, *inputs]
+ return run(cmd)
+
+ ret = _combine(base_out, base_jsons)
+ if ret.returncode != 0:
+ print(f' combined base error: {ret.stderr}')
+ else:
+ ret = _combine(cur_out, cur_jsons)
+ if ret.returncode != 0:
+ print(f' combined current error: {ret.stderr}')
+ else:
+ out_combined = os.path.join(combined_dir, 'metrics_compare')
+ ret = run([sys.executable, metrics_py, 'compare', '-m',
+ '-o', out_combined, f'{base_out}.json', f'{cur_out}.json'])
+ print(ret.stdout)
+ print(f' combined report: {out_combined}.md')
+ finally:
+ print(f'\nCleaning up worktree...')
+ run(['git', '-C', TINYUSB_ROOT, 'worktree', 'remove', '--force', worktree_dir])
+
+
+if __name__ == '__main__':
+ main()