I think we can't get rid of ep0_pending, otherwise we need to add ep0_xferred_bytes which ends up the same thing, just one counting up another counting down.
#tinyusb
1 messages · Page 10 of 1
I think it should be safe, which scenario you are thinking about ?
You are right, I just feel a bit un-easy when both handle_epin_slave() and edpt_schedule_packets() can write to difof. Especially handle_epin_slave() also called edpt_schedule_packets() in case of ep0. But it is probably safe enough, actually we can refactor this and try to write as many packet as we could before enable the TX empty if there is remaining packet ?
dwc2_ep_tsize_t tsiz = {.value = epin->tsiz};
...
I agree, ep0_xferred_bytes is better since it will only increased when xfer is complete, and we can also use that in case of error for xferred so far. Maybe i will do that in follow-up PR later.
I have update PR to only increase stack size when debug is enabled.
Gates Failed
Enforce advisory code health rules
(1 file with Large Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| family.c | 1 advisory rule | 9.58 →... |
❌ Getting worse: Large Method
board_init increases from 75 to 98 lines of code, threshold = 70
<sub>Suppress</sub>
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3294&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| family.c | 1 advisory rule | 9.58... |
❌ New issue: Complex Method
board_init has a cyclomatic complexity of 9, threshold = 9
<sub>Suppress</sub>
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3294&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
@HiFiPhile retrying iso with flush and re-write packet seems a bit heavy, with high enough bInterval we may end up doing it mostly every frame. Since dwc2 requires
For Periodic IN endpoints, the data must always be prefetched 1 microframe ahead for transmission
in the next microframe. This can be done, by enabling the Periodic IN endpoint 1 (micro)frame ahead
of the (micro)frame in which the data transfer is scheduled
I think in the future we have to improve how we manage IS...
@Ryzee119 all weak callback is now migrated to use default empty implementation to better support keil/armcc. I guess we can safely close this now ?
On smaller devices, there isn’t enough RAM to store an entire high-resolution frame. I haven’t found a way to use the video device without such a buffer, so I added a callback mechanism that allows the code to request payload data on the fly. This makes it possible to generate or forward data without storing a whole frame at once.
- The code has been tested on a NanoCH32V305 board.
- I added demo code to the video device example.
- I tried to stay consistent with the existing code and us...
Gates Failed
Enforce advisory code health rules
(1 file with Excess Number of Function Arguments)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| main.c | 1 a... |
❌ New issue: Excess Number of Function Arguments
tud_video_prepare_payload_cb has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3322&biomarker=Excess+Number+of+Function+Arguments&file...
Related area
OTG
Hardware specification
STM32H7 controller
Is your feature request related to a problem?
Yes, While I was working i could notice that, Dual OTG Mode is not working. On H7 board
Describe the solution you'd like
Dedicated Dynamic switch of Host and Device on H7
I have checked existing issues, dicussion and documentation
- [x] I confirm I have checked existing issues, dicussion and documentation.
I've refactored the fifo writing routine and added a tunable CFG_TUD_DWC2_IN_DOUBLE_BUFFER to set GAHBCFG_TX_FIFO_EPMTY_LVL and fifo allocation, in order to allow writing 2 packets to fifo.
By default we allocate fifo size=packet size, the writing loop will likely stop after one packet is written.
For OUT transfer it's easy to get ep0_xferred_bytes, but for IN transfer it can't be read from register, we have to add something like last_xfer_bytes and set it in edpt_schedule_packets. I don't know if it's worth the change.
- iso transfer --> compute target frame_num = last xferred frame_num + bInterval
- enable sof interrupt, loop for iso in check target frame, if there is transfer next --> write data, set odd/even bit.
- iso incomplete still requires, but I guess host will mostly respect the iso bInterval so the number of rety would be much less often.
- sof interrupt can be disabled when there is no active iso transfer.
That's what should be done ideally (kernel does something similar), but in r...
Thanks @HiFiPhile for the detail info, I think we should follow the bInterval, I don't understand UAC1, but I think bInterval is the hard limit between the ISO transfer, while bRefresh is probably more flexible maybe bRefresh = n*bInterval. Mabye the class driver can have both with the same value to make every OS happy. For dwc2 driver, I think sticking with bInterval is easier and cleaner.
@hathach I remembered why we can't do scheduling with bInterval, due to Nak interrupt is unavailable on some devices (OTG_FS). Nak interrupt is needed in order to align the frame number with the host.
For example when bInterval=4 kernel does this:
- Enable global Nak interrupt on transfer start
- Nak interrupt will fire since no packet is written
- In Nak interrupt, check if it's ISO IN EP, then get the frame number (ex. 10), calculate the next frame of ISO transfer (14)
- In SOF inte...
Have you tried tud_deinit then tuh_rhport_init ?
Gates Failed
Prevent hotspot decline
(2 hotspots with Complex Method, Complex Conditional, Bumpy Road Ahead, Deep, Nested Complexity)
Enforce critical code health rules
(2 files with Bumpy Road Ahead, Deep, Nested Complexity)
Enforce advisory code health rules `(5 files with Complex Method, Overall Code Complexity, Code...
❌ New issue: Complex Method
audio10_set_req_entity has a cyclomatic complexity of 9, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Complex+Method&filename=examples%2Fdevice%2Faudio_test_multi_rate%2Fsrc%2...
❌ New issue: Overall Code Complexity
This module has a mean cyclomatic complexity of 4.42 across 19 functions. The mean complexity threshold is 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Overall+Code+Complexity&filename=exampl...
❌ New issue: Complex Method
audio20_get_req_entity has a cyclomatic complexity of 19, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Complex+Method&filename=examples%2Fdevice%2Faudio_test_multi_rate%2Fsrc%...
❌ New issue: Complex Method
audio10_get_req_entity has a cyclomatic complexity of 10, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Complex+Method&filename=examples%2Fdevice%2Faudio_test_multi_rate%2Fsrc%...
❌ Getting worse: Code Duplication
introduced similar code in: audio20_get_req_entity,audio20_set_req_entity,tud_audio_get_req_ep_cb
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Code+Duplication&filename=examples%2Fdevice%2Fuac2_headset%2Fsrc%2Fma...
❌ Getting worse: Deep, Nested Complexity
process_set_config increases in nested complexity depth from 6 to 8, threshold = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3270&biomarker=Deep%2C+Nested+Complexity&filename=src%2Fdevice%2Fusbd.c&method=process_set_...
@hathach that's great. That should fix any outstanding issues I had.
We may just need the defined(clang) check on GNUC so clang compiler will use those definitions which should all be compatible now
I will confirm this soon
❌ Getting worse: Complex Method
dcd_int_handler increases in cyclomatic complexity from 13 to 19, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3275&biomarker=Complex+Method&filename=src%2Fportable%2Fsynopsys%2Fdwc2%2Fdcd_dwc2.c&method=d...
❌ New issue: Deep, Nested Complexity
dcd_int_handler has a nested complexity depth of 5, threshold = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3275&biomarker=Deep%2C+Nested+Complexity&filename=src%2Fportable%2Fsynopsys%2Fdwc2%2Fdcd_dw...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method, Complex Conditional)
Enforce advisory code health rules
(1 file with Complex Method, Complex Conditional)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reaso...
❌ New issue: Complex Conditional
dcd_int_handler has 1 complex conditionals with 2 branches, threshold = 2
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3275&biomarker=Complex+Conditional&filename=src%2Fportable%2Fsynopsys%2Fdwc2%2Fdcd_dwc2.c&met...
❌ Getting worse: Complex Method
dcd_int_handler increases in cyclomatic complexity from 13 to 20, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3275&biomarker=Complex+Method&filename=src%2Fportable%2Fsynopsys%2Fdwc2%2Fdcd_dwc2.c&method=d...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method, Complex Conditional)
Enforce advisory code health rules
(1 file with Complex Method, Complex Conditional)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reaso...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method, Complex Conditional)
Enforce advisory code health rules
(1 file with Complex Method, Complex Conditional)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reaso...
@HiFiPhile does it need to use global NAK, I see there is DIEPINTi bit 13 that is available in stm32f4.
<img width="1091" height="364" alt="image" src="https://github.com/user-attachments/assets/9af113dd-57c2-4ad5-b3f3-38f055edb7a7" />
I think we should not introduce this option. I always think the fine-tune fifo should be dictated by application per endpoint basic. E.g MSC + CDC, we would want a massive endpoint size for msc and smaller for cdc. I am think we should do that via a tud_configure() (which allo to pass an option id + pointer to struct) that fine tune the behavior of dcd or stack. similar to tuh_configure() https://github.com/hathach/tinyusb/blob/master/src/host/usbh.h#L145 . dwc2 option may include grxsize and...
you are right, sorry, I forgot some of these thing.
we have a possibility to call epin_write_tx_fifo() 2nd time with ep0. although it would not write any bytes, I think we should skip this for ep0.
perfect !! Thank you very much, I didn't test but go through code changes. It looks great, audio is by far the most complicated driver. I think its descriptor is too complicated to have template descirptor as macro. I will try to improve it later on with typedef struct like video example. Thank you very much for putting lots of effort into the driver.
@hathach It's only available for OTG_HS, OTG_FS doesn't have it .
<img width="1450" height="262" alt="image" src="https://github.com/user-attachments/assets/6138a3c8-cc02-4824-b2e2-fc8e2862d8c3" />
Yeah a configurable parameter is better, didn't notice there is a tuh_configure().
@HiFiPhile which mcu in your screenshot, mine is otg fs stm32f405/407
<img width="1522" height="1652" alt="image" src="https://github.com/user-attachments/assets/038ffbfe-9c35-4e28-b887-1f527241cfa8" />
@hathach
Just realized my RM0090 is too old !
DIEPMSK->NAKM will enable the interrupt for all endpoints, many interrupts will be generated especially if there are any bulk EP.
Incomplete transfer interrupt only fires once each frame, by default when 80% time of the frame is elapsed. So the CPU load is similar to SOF interrupt.
<img width="861" height="390" alt="image" src="https://github.com/user-attachments/assets/4279e43e-b50d-4162-b218-93c35de843e7" />
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
@HiFiPhile yeah, I think using incomplete iso interrupt is much better than NAK. I guess maybe this interrupt is probably introduced in later version of dwc2 where NAK is already implemented. Also I think we only need to do this once per ISO activate for syncing the first, however we cannot trust host to keep the bInterval right, so yeah sync target/last frame numb everytime ISO is transfer complete or incomplete is great idea.
Thank you, tested on STM32U5, please fix pre-commit whitespace issue as I can't push to your branch (got permission denied).
@kkitayam @lijunru-hub what do you think ?
C-STAT found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fbridgete...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fchipidea%...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fchipidea%...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fmentor%2Fmusb...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer_fifo has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fmen...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fmicroc...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer_fifo has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fsunxi%2Fdcd_sun...
❌ New issue: Excess Number of Function Arguments
dcd_edpt_xfer has 5 arguments, max arguments = 4
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3313&biomarker=Excess+Number+of+Function+Arguments&filename=src%2Fportable%2Fwch%2Fdcd_ch32_us...
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3313&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Sorry for the whitespaces, should have looked a bit deeper into the logs. Did some experiments with a new Editor and didn't had my settings right.
@ArcaneNibble is probably busy with other works. I think this PR is good to merge now. Should there be any issues, we can fix it with follow up PR. Thank you very much for the PR
Describe the PR
Added the USB device for the STM32U3 using stm32_fsdev.
Additional context
- Essentially the same as the STM32U0 and STM32U5 (stm32_fsdev) and others.
- I am not sure if this addition also handles USB host, but it is possible on this MCU. I left the column empty in the README.
- This was tested on a custom PCB so I did not add any
hw/bsp - I have only tested it wit...
[hathach/tinyusb] New branch created: fix-code-alerts
The operands j' and 4' have essential type categories unsigned 32-bit int and signed 8-bit int, which do not match
The operand `0xf' is essentially signed, but should be essentially unsigned
The operands (uid[i]>>(j*4))' and 0xf' have essential type categories unsigned 8-bit int and signed 8-bit int, which do not match
The operands addr' and (~0x80)' have essential type categories unsigned 8-bit int and anonymous enum, which do not match
The operand `btn' has essential type unsigned 32-bit int, but should be Essentially Boolean
In a ternary operator, the type anonymous enum' of the second operand 0x80' is different from the type signed 8-bit int' of the third operand 0'
The operands btn_prev' and 0' have essential type categories unsigned 32-bit int and signed 8-bit int, which do not match
Pull Request Overview
This PR performs code cleanup and standardization across the TinyUSB codebase. The changes remove deprecated macros, improve code consistency, and fix minor issues related to header includes and code style.
Key changes:
- Removes deprecated
TU_BIN8()macro usage and replaces with hex literals - Renames internal macros to be public (
_TU_CHECK_MCU→TU_MCU_IS_EQUAL,_OSAL_Q_NAME→OSAL_Q_NAME,_TU_ARGS_APPLY_*→TU_ARGS_APPLY_*) - Reorganizes `` includes...
Binary representation comment is missing '0b' prefix for the last value. Should be '0b01000100' for consistency with the other binary comments on this line and line 922.
(interval == 2) ? 0xaa /* 0b10101010 */ : 0x44 /* 0b01000100 */;
Grammatical error: 'with a selected' should be 'with a separator' to match the actual functionality. The macro uses a separator/delimiter parameter, not a 'selected' one.
// Apply a macro X to each of the arguments with a separator/delimiter
@HiFiPhile , Yes I did.
Use of `stdio.h' is not compliant
💡 Codex Review
https://github.com/hathach/tinyusb/blob/a01bf9b3306c8aa093ebdef46d1c9175bae17b9a/src/common/tusb_common.h#L74-L79
<sub><sub></sub></sub> Keep stdio available for modules using printf
Dropping #include <stdio.h> from the common header means all translation units that relied on tusb_common.h for the printf prototype now compile without it. Many BSP sources still call printf directly (for example `hw...
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| video_device.c | 1 advisory rule ... |
❌ Getting worse: Complex Method
_update_streaming_parameters already has high cyclomatic complexity, and now it increases in Lines of Code from 79 to 81
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3326&biomarker=Complex+Method&filename=src%2Fcla...
❌ Getting worse: Complex Method
handle_video_stm_cs_req already has high cyclomatic complexity, and now it increases in Lines of Code from 126 to 128
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3326&biomarker=Complex+Method&filename=src%2Fclass%2Fvid...
Expression '0 == ofs_ep' is always false.
The operands 0' and tu_fifo_depth(&s->ff)' have essential type categories signed 8-bit int and unsigned 16-bit int, which do not match
The operands 0' and tu_fifo_depth(&s->ff)' have essential type categories signed 8-bit int and unsigned 16-bit int, which do not match
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| video_device.c | [1 advisory rule... |
@hathach I don't like adding a redundant 0 != into the condition, can we change the static analyzer behavior ?
yeah, It is rather annoying, maybe we can suppress that rule. let me check
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| video_device.c | [1 advisory rule... |
❌ Getting worse: Complex Method
_update_streaming_parameters already has high cyclomatic complexity, and now it increases in Lines of Code from 79 to 83
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3326&biomarker=Complex+Method&filename=src%2Fcla...
Some make sense to change to != 0 though like checking on number. For flag with and/or it is indeed unneccessary.
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| video_device.c | [1 advisory rule... |
[hathach/tinyusb] New branch created: me-no-dev-patch-1
When both host and device are enabled at the same time, this function is compiled twice, once for host and once for device, but the device dcd_int_handler is not declared when compiling host and the opposite for when compiling device. This PR only adds the declarations so that the function can compile in both cases.
dwc2_esp32.h is included by dwc2_common.h, which is included by dwc2_common.c, dwc2_common.c also includes the prototype headers, so it should be fine:
dwc2_common.c
|--device/dcd.h -> void dcd_int_handler(uint8_t rhport);
|--host/hcd.h -> void hcd_int_handler(uint8_t rhport, bool in_isr);
|--dwc2_common.h
|--dwc2_esp32.h
I think the real issue is prevent dwc2_int_handler_wrap to be compiled 2 times ?
@HiFiPhile it was hard to track this down, but in Arduino we now have both Host and Device enabled at the same time and that produced build errors for undefined dcd_int_handler when host is compiled and hcd_int_handler when Device is compiled. I guess my colleagues at Espressif never tested both options enabled at the same time.
@HiFiPhile
device/usbd.cincludesdcd.hwhich definesdcd_int_handlerand also pulldwc2_esp32.hhost/usbh.cincludeshcd.hwhich defineshcd_int_handlerand also pulldwc2_esp32.h
So they both compile the function dwc2_int_handler_wrap in dwc2_esp32.h and see that both Host and Device are enabled, but depending on which usbh or usbd is compiled, it only sees hcd_int_handler or dcd_int_handler declared, but never both. Compilation fails
@me-no-dev
device/usbd.c includes dcd.h which defines dcd_int_handler and also pull dwc2_esp32.h
host/usbh.c includes hcd.h which defines hcd_int_handler and also pull dwc2_esp32.h
I can't find how dwc2_esp32.h get pulled by usbd.c or usbh.c, the only dependency chain I found are:
ddc_dwc2.c -> dwc2_common.h ->dwc2_esp32.h
ddc_common.c -> dwc2_common.h ->dwc2_esp32.h
hdc_dwc2.c -> dwc2_common.h ->dwc2_esp32.h
@HiFiPhile let me try to compile and give you the exact errors
@HiFiPhile
Device dcd_dwc2.c
/Users/ficeto/Desktop/ESP32/ESP-IDF-5/esp32-arduino-lib-builder/components/arduino_tinyusb/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c
In file included from /Users/ficeto/Desktop/ESP32/ESP-IDF-5/esp32-arduino-lib-builder/components/arduino_tinyusb/tinyusb/src/portable/synopsys/dwc2/dwc2_common.h:43,
from /Users/ficeto/Desktop/ESP32/ESP-IDF-5/esp32-arduino-lib-builder/components/arduino_tinyusb/tinyusb/src/portable/synopsys/dwc2/dcd_d...
@HiFiPhile @hathach CI failures are unrelated to this PR
@me-no-dev Thank you for the log.
Adding a declaration could resulting error dcd_dwc2.c:1040:6: error: redundant redeclaration of 'dcd_int_handler' [-Werror=redundant-decls], even though for esp-idf this check is not enabled ATM.
Another way is to fix once for all (future) ports, but it will leak dcd api into hcd or vice versa:
diff --git a/src/portable/synopsys/dwc2/dwc2_common.c b/src/portable/synopsys/dwc2/dwc2_common.c
index 5ff18ab94..ee79ddc46 100644
--- a/src/portabl...
@HiFiPhile I'm OK with whatever you guys decide, as long as it's working 😄
@HiFiPhile maybe the includes can be added to dwc2_esp32.h, so that APIs would be mixed only for ESP32? Could this problem exist for other targets?
❌ Getting worse: Complex Method
process_set_config already has high cyclomatic complexity, and now it increases in Lines of Code from 81 to 82
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3326&biomarker=Complex+Method&filename=src%2Fdevice%2Fusbd.c&method=process_set_con...
❌ Getting worse: Complex Method
tud_task_ext already has high cyclomatic complexity, and now it increases in Lines of Code from 95 to 98
<sub>Suppress...
C-STAT found more than 20 potential problems in the proposed changes. Check the Files changed tab for more details.
Code Health Improved
(2 files improve in Code Health)
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code he...
@HiFiPhile maybe the includes can be added to
dwc2_esp32.h, so that APIs would be mixed only for ESP32? Could this problem exist for other targets?
I'm good with it, other port headers are simpler and doesn't need dcd/hcd api for now.
Code Health Improved
(2 files improve in Code Health)
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code he...
Code Health Improved
(2 files improve in Code Health)
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code he...
Code Health Improved
(2 files improve in Code Health)
Gates Failed
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
3 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce advisory code he...
@me-no-dev let me check, I think my esp32p4 I got is the old version that does not wire the usbfs to usbc connector. And I didn't test with dual examples.
@hathach yes. P4 EV board has the USB-OTG port only for host, but there are other boards and there are also S2 and S3 boards that we tested with. Both host and device are working fine with the changes (only one is initialize at a time), but since Arduino uses pre-built TinyUSB, we need it to be compiled for both at the same time.
Operating System
Others
Commit SHA
5.5.1
Board
ESP32P4
Firmware
ESP IDF 5.5.1
espressif/esp_tinyusb: "~2.0.1"
espressif/tinyusb: ">=0.17.0"
What happened ?
I created a USB OTG MIDI device using the ESP32-P4 board and based it on an example template. I have code in place to read MIDI packets, and everything seemed to be working fine until I began testing SysEx data.
When my app (running on a Mac) sends a burst of SysEx messages (each less than 12 bytes, with 16–24...
since you are using espressif fork, you should open an issue there.
Quality Gate passed
Issues
[2 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3333&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
@HiFiPhile suggestion is better, I have made an PR for it, also update example to compile/test with https://github.com/hathach/tinyusb/pull/3333, but haven't tested dual mode on 2 otg (fs & hs) just yet as I don't have time to wiring up the board atm, will test it out later.
Pull Request Overview
This PR refactors the CMake build system to improve modularity and adds FreeRTOS support for the ESP32P4 platform. The main changes extract TinyUSB source file lists into a reusable function and enable the host_info_to_device_cdc dual-role example to work with FreeRTOS-based systems like ESP32P4.
Key changes:
- Extracted TinyUSB source listing into
tinyusb_sources_get()function for better reusability - Added FreeRTOS task management to host_info_to_device_cdc exa...
Corrected spelling of 'USBH_STACK_SZE' to 'USBH_STACK_SIZE'.
xTaskCreate(usb_host_task, "usbh", USBH_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL);
Corrected spelling of 'MAIN_STACK_SZIE' to 'MAIN_STACK_SIZE'.
xTaskCreate(main_task, "main", MAIN_STACK_SIZE, NULL, configMAX_PRIORITIES - 2, NULL);
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Fix typoed stack size macros in FreeRTOS path
When configSUPPORT_STATIC_ALLOCATION is disabled the FreeRTOS setup uses xTaskCreate with USBH_STACK_SZE and MAIN_STACK_SZIE. Both identifiers are misspelled and undefined, so any build that relies on dynamic task allocation will fail to compile. These lines should use the existing USBH_STACK_SIZE and MAIN_STACK_SIZE macros.
Useful? React with 👍...
Quality Gate passed
Issues
[2 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3333&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
[hathach/tinyusb] New branch created: fix-alerts-3
Pull Request Overview
This PR adds support for the STM32U3 microcontroller family to TinyUSB. The STM32U3 uses the FSDEV (Full-Speed Device) USB peripheral similar to other STM32 U-series microcontrollers.
Key Changes
- Added STM32U3 MCU option definition (OPT_MCU_STM32U3 = 321)
- Configured STM32U3 to use the stm32_fsdev driver with 2KB PMA buffer, 32-bit bus, and 8 endpoints
- Added STM32U3 USB interrupt configuration (USB_FS_IRQn)
Reviewed Changes
Copilot reviewed 4 out of 4...
The Host column is empty (no symbol) for STM32U3, which is inconsistent with other entries in the table. Looking at similar entries (U0 line 213, G4 line 205), untested/unknown host support is indicated with '✖'. Consider using '✖' instead of leaving it blank, or if host support status is truly unknown, consider using a '?' or similar indicator for consistency.
| | U3 | ✔ | ✖ | ✖ | stm32_fsdev | |...
The comment indicates SBUF_ISO support is untested. This is inconsistent with STM32U0 (line 206) which explicitly disables SBUF_ISO due to performance issues. Consider either: (1) disabling SBUF_ISO for STM32U3 until tested, similar to U0, or (2) updating the comment to explain why U3 is expected to work better than U0, given their architectural similarities (both use USB_DRD_FS, FSDEV_BUS_32BIT).
// Disable SBUF_ISO on U3 for now due to lack of testing and possible performanc...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
❌ Getting worse: Complex Method
proc_builtin_scsi already has high cyclomatic complexity, and now it increases in Lines of Code from 125 to 127
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3334&biomarker=Complex+Method&filename=src%2Fclass%2Fmsc%2Fmsc_device.c&...
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub>
osal_semaphore_post now returns a void expression
osal_semaphore_post() now returns the result of sem_release(sem_hdl). On the RP2040 SDK sem_release returns void, so this change produces a compile-time error (“void value not ignored as it ought to be”) and breaks all Pico builds. The previous implementation returned true after calling sem_release. Restore the explicit `sem_release(); return ...
<sub><sub></sub></sub> Restore default TX FIFO overwrite behaviour
The default configuration macro now sets tx_overwritabe_if_not_connected to false, whereas previously it was 1 and the driver still documents “Default: is overwritable”. This silently changes the public API’s behaviour so that CDC writes while the terminal is disconnected will stop once the FIFO fills rather than overwriting old data. Existing applicatio...
Pull Request Overview
This PR focuses on code quality improvements through static analysis fixes, formatting standardization, and MISRA C compliance. The changes include PVS-Studio warning suppressions, explicit comparisons for clarity, proper type usage (bool instead of uint8_t for flags), void casts for unused return values, and clang-format configuration updates for consistent code style.
Key Changes
- Added PVS-Studio static analysis suppressions and configuration improvements
- ...
thank you LGTM as well
The default value for tx_overwritabe_if_not_connected was changed from 1 (true) to false, which appears to be an unintended behavior change. The original code set this to 1 (true), indicating that this was the intended default behavior. If this change is intentional, it should be documented as a breaking change.
.tx_overwritabe_if_not_connected = true, \
Changing TU_LOG1 from tu_printf to (void) tu_printf breaks the macro's functionality. When used as TU_LOG1("format", args...), it will expand to (void) tu_printf("format", args...) which attempts to cast a function pointer rather than calling the function and casting its return value. The correct form should be #define TU_LOG1(...) (void) tu_printf(__VA_ARGS__) to properly suppress the return value warning while maintaining functionality.
#define TU_LOG1(...) ...
The cast (uint8_t*) is unnecessary here. _mscd_epbuf.buf is already defined as uint8_t[] via the TUD_EPBUF_DEF macro, and &p_msc->csw is of type msc_csw_t* which is compatible with const void* (memcpy's second parameter). The standard memcpy signature is void* memcpy(void*, const void*, size_t), so no cast is needed for either parameter.
memcpy(_mscd_epbuf.buf, &p_msc->csw, sizeof(msc_csw_t)); //-V1086
A call of the 'memcpy' function will lead to overflow of the buffer 'cbw.command'.
A call of the 'memcpy' function will lead to overflow of the buffer 'cbw.command'.
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
Pull Request Overview
This PR adds nested locking support to the bare-metal spinlock implementation in osal_none.h. The enhancement allows the same execution context to acquire a spinlock multiple times without deadlocking, which is crucial for single-core bare-metal systems where nested critical sections are common.
Key changes:
- Added
nested_countfield to track lock depth and prevent premature interrupt re-enabling - Modified lock/unlock logic to only disable/enable interrupts on...
[hathach/tinyusb] New review comment on pull request #3151: osal/none: add nested count to spin lock
Re-enabling interrupts in the underflow error path is problematic. If nested_count is 0, it means either: (1) unlock was called without a matching lock, or (2) the lock was acquired in an ISR. In case (1), the interrupt state is unknown - interrupts may have been disabled by other code or may already be enabled. Unconditionally enabling them could break the caller's interrupt state assumptions. Consider removing lines 66-69 and just asserting, or only re-enable if you can confirm they were di...
[hathach/tinyusb] New review comment on pull request #3151: osal/none: add nested count to spin lock
The comment on line 56 claims the nested_count increment is atomic, but it's not. There's a race condition: an interrupt could fire between checking ctx->nested_count == 0 (line 57) and disabling interrupts (line 58), potentially causing the same interrupt handler to see nested_count == 0 and also disable interrupts. While this may not break the current implementation's correctness, the comment is misleading. Consider revising the comment to: `// Disable interrupts on first lock to protect ...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
❌ Getting worse: Complex Method
audiod_fb_params_prepare increases in cyclomatic complexity from 14 to 15, threshold = 9
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3321&biomarker=Complex+Method&filename=src%2Fclass%2Faudio%2Faudio_device.c&method=a...
❌ Getting worse: Complex Method
audiod_set_interface already has high cyclomatic complexity, and now it increases in Lines of Code from 145 to 146
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3321&biomarker=Complex+Method&filename=src%2Fclass%2Faudio%2Fa...
Pull Request Overview
This PR adds FIFO threshold configuration support for USB audio devices, enabling fine-tuned control over both EP IN (transmit) and EP OUT (receive via feedback) FIFO buffer management for better latency control.
- Adds getter/setter API functions for EP IN FIFO threshold configuration
- Extends
audio_feedback_params_tstruct withfifo_count.fifo_thresholdfield for EP OUT feedback control - Updates flow control logic to use configurable thresholds instead of ha...
Missing NULL descriptor check. The setter function should verify that _audiod_fct[func_id].p_desc != NULL before accessing ep_in_ff.depth and setting ep_in_fifo_threshold, consistent with other API functions like tud_audio_n_clear_ep_in_ff() at line 538. Without this check, there's a risk of accessing uninitialized data.
if (func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL && threshold < _audiod_fct[func_id].ep_in_ff.depth) {
Missing NULL descriptor check. The getter function should verify that _audiod_fct[func_id].p_desc != NULL before accessing ep_in_fifo_threshold, consistent with tud_audio_n_get_ep_in_ff() at line 543. Without this check, there's a risk of accessing uninitialized data.
if (func_id < CFG_TUD_AUDIO && _audiod_fct[func_id].p_desc != NULL) {
return _audiod_fct[func_id].ep_in_fifo_threshold;
}
Typo in parameter name: 'norminal_size' should be 'nominal_size'.
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
I've done the fixup and also added RX FIFO threshold adjustment.
You wrote slot_size 2 times, should be data_count < (target_fifo_size - slot_size)
Should be data_count > (target_fifo_size + slot_size)
IMO tud_audio_n_set_ep_in_fifo_threahold(uint8_t func_id, uint16_t fifo_threshold); is a better naming
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
Describe the PR
The endpoint number is 4 bits wide. The original code extracts 7 bits.
~TUSB_DIR_IN_MASK is 0x7F but we need to use 0x0F.
It is safer not to assume that bits 4..6 of bEndpointAddress are zero.
Additional context
See the bEndpointAddress description in the following link.
Describe the PR
The endpoint number is used to index arrays of size CFG_TUD_ENDPPOINT_MAX. This PR adds a bounds check before the index is used.
Additional context
Maybe #3281 will be fixed
Gates Failed
Prevent hotspot decline
(1 hotspot with Complex Method)
Enforce advisory code health rules
(1 file with Complex Method)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Prevent hotspot decline |...
❌ Getting worse: Complex Method
process_set_config already has high cyclomatic complexity, and now it increases in Lines of Code from 82 to 83
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3336&biomarker=Complex+Method&filename=src%2Fdevice%2Fusbd.c&method=process_set_con...
❌ Getting worse: Complex Method
audiod_open already has high cyclomatic complexity, and now it increases in Lines of Code from 151 to 153
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3334&biomarker=Complex+Method&filename=src%2Fclass%2Faudio%2Faudio_device.c&meth...
Quality Gate failed
Failed conditions
E Reliability Rating on New Code (required ≥ A)
...
currently pvs-studion, Sonarqube and codescene IAR C-stat (disabled for now) are alreay in use. This can be closed
Hi,
I just want to let you know that your original code (current version) works correctly in ESP-IDF + ESP32 P4 for SysEx MIDI (the problem I tested).
I tried to make an identical project with esp-tinyUSB fork again, but I was not able to read all incoming data (SysEx burst),
and I tried almost everything I think could be related.
I will push this to Espressif, of course.
Thank you.
J.
On 6 Nov 2025, at 12:43, Ha Thach @.***> wrote:
hathach
left a commen...
thank you very much for putting efforts to improve the documentation, which is much needed. I make some changes to also add make instruction which is still very popular, and move things around. This will surely help lots of new users
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3313&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Just for reference, it looks like this commit db7670a3bcd502193d138041c20d401bc3f59001 was responsible for this issue (it seems that ZLP was correctly handled prior to that commit).
[hathach/tinyusb] New branch created: midi-edpt-stream
- migrate midi_device to use edpt stream API
- also add tud_midi_n_packet_write/read_n()
Code Health Improved
(1 files improve in Code Health)
Gates Failed
Enforce critical code health rules
(1 file with Bumpy Road Ahead)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce critical code ...
❌ Getting worse: Bumpy Road Ahead
tud_midi_n_stream_write increases from 4 to 5 logical blocks with deeply nested code, threshold is 2 blocks per function
<sub>[Suppress](https://codescene.io/projects/37161/delta?repo-id=115424&review-id=3337&biomarker=Bumpy+Road+Ahead&filename=src%2Fclas...
Code Health Improved
(1 files improve in Code Health)
Gates Failed
Enforce critical code health rules
(1 file with Bumpy Road Ahead)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce critical code ...
Pull Request Overview
This PR migrates the MIDI device class driver from using direct FIFO management to using the new endpoint stream API. This simplifies the code by leveraging the shared stream infrastructure and adds new functions for reading/writing multiple MIDI packets at once.
- Replaced manual FIFO and endpoint management with
tu_edpt_stream_tAPI - Added
tud_midi_n_packet_read_n()andtud_midi_n_packet_write_n()functions for bulk packet operations - Updated style convent...
Corrected spelling of 'writtent' to 'written'.
// Write multiple event packets, return number of written packets
The function tud_midi_n_packet_write_n should return the number of packets written (as stated in the API documentation), not the number of bytes. Since each MIDI packet is 4 bytes, this should return n_write / 4 or n_write >> 2.
return n_write >> 2;
The return type is bool but the function returns the result of tud_midi_n_packet_write_n() which returns uint32_t (number of packets). The return type should be uint32_t to match the underlying function's return type.
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_midi_packet_write_n(const uint8_t packets[], uint32_t n_packets) {
💡 Codex Review
https://github.com/hathach/tinyusb/blob/0b6d5080e1bd45d6ad334e8b0148628c27b60431/src/class/midi/midi_device.c#L298-L309
<sub><sub></sub></sub> Return packet count from tud_midi_n_packet_write_n
The new bulk send API advertises that it returns the number of packets written, mirroring tud_midi_n_packet_read_n. However the implementation returns the raw byte count from tu_edpt_stream_write. Callers that ...
The 'stream->index' variable was assigned the same value.
Code Health Improved
(1 files improve in Code Health)
Gates Failed
Enforce critical code health rules
(1 file with Bumpy Road Ahead)
Gates Passed
2 Quality Gates Passed
See analysis details in CodeScene
Reason for failure
| Enforce critical code ...
Pull Request Overview
Copilot reviewed 7 out of 8 changed files in this pull request and generated 1 comment.
The order of operations is inconsistent with the pattern used in the host code. While functionally correct (since n_packets << 2u is always a multiple of 4), the host code pattern (see tuh_midi_packet_read_n in midi_host.c lines 425-426) is clearer:
n_bytes = tu_min32(n_bytes, n_packets << 2u);
n_bytes = tu_align4(n_bytes);
or equivalently:
n_bytes = tu_align4(tu_min32(n_bytes, n_packets << 2u));
This makes the intent clearer: take the minimum of available and requested ...
[hathach/tinyusb] New branch created: cdc-edpt-stream
💡 Codex Review
https://github.com/hathach/tinyusb/blob/0871c7d619d96953d6a87bdc37a447217a836fc2/src/class/cdc/cdc_device.c#L372-L379
<sub><sub></sub></sub> Avoid asserting when persistent CDC RX FIFO is full
The new cdcd_open always asserts that tu_edpt_stream_read_xfer() succeeds after opening the OUT endpoint. When RX persistence is enabled (_cdcd_cfg.rx_persistent == true) the FIFO contents are intentionally pr...
Pull Request Overview
This PR migrates the CDC device class to use the unified endpoint stream API, consolidating FIFO management and endpoint transfer logic into reusable stream abstractions. The changes simplify CDC device/host implementations while maintaining backward compatibility.
Key Changes:
- Refactored CDC device to use
tu_edpt_stream_tinstead of direct FIFO management, removing ~150 lines of code - Updated MIDI and vendor device classes to use stream clear operations fo...
Missing error handling for tu_edpt_stream_init(). This function can fail (returns bool), but the return value is not checked. Consider adding error checking similar to how it's done in cdc_host.c with TU_ASSERT().
Inconsistent spacing in for loop. Should be for (uint8_t i = 0; i < CFG_TUD_CDC; i++) with spaces around operators to match the project style (see line 272).
for (uint8_t i = 0; i < CFG_TUD_CDC; i++) {
Missing error handling for tu_edpt_stream_deinit(). The function returns bool but the return values are not checked. If deinitialization fails, the function should propagate the error instead of always returning true.
Clearing stream state before closing streams. The tu_memclr on line 309 clears ITF_MEM_RESET_SIZE bytes which includes the stream state (ep_addr, is_mps512), but then tu_edpt_stream_close is called on lines 312-313 which sets ep_addr = 0. The close calls are redundant since the streams are already cleared. Consider either: 1) calling tu_edpt_stream_close before tu_memclr, or 2) removing the close calls since memclr already zeros the ep_addr.
[nitpick] Extra blank line. Consider removing one of the empty lines to maintain consistent spacing in the file.
Double forward slash in comment. Should be a single "//" not "// //".
tu_fifo_set_overwritable(&p_cdc->stream.tx.ff, _cdcd_cfg.tx_overwritabe_if_not_connected); // back to default
Pull Request Overview
Copilot reviewed 9 out of 10 changed files in this pull request and generated 8 comments.
The return value of tu_edpt_stream_init() is not checked. If initialization fails, the interface will be in an inconsistent state. Consider adding TU_ASSERT() to validate the initialization succeeded, similar to how cdch_init() in cdc_host.c checks these return values.
While the return values of tu_edpt_stream_deinit() are explicitly cast to void, consider checking the return values and returning false if any deinit operation fails, to properly propagate errors to callers.
if (!tu_edpt_stream_deinit(&p_cdc->stream.tx)) {
return false;
}
if (!tu_edpt_stream_deinit(&p_cdc->stream.rx)) {
return false;
}
The return value of tu_edpt_stream_read_xfer() is not explicitly cast to void. For consistency with cdc_host.c (line 521) and to clearly indicate the intentional ignoring of the return value, consider adding (void) cast.
(void)tu_edpt_stream_read_xfer(dev_addr, ep_str_rx); // prepare for next transfer
The return value of tu_edpt_stream_write_zlp_if_needed() is not explicitly cast to void. For consistency with cdch_xfer_cb() in cdc_host.c (line 698) and to clearly indicate the intentional ignoring of the return value, consider adding (void) cast.
(void)tu_edpt_stream_write_zlp_if_needed(rhport, stream_tx, xferred_bytes);
The return value of tu_edpt_stream_read_xfer() is not explicitly cast to void. For consistency with cdch_xfer_cb() in cdc_host.c (line 718) and to clearly indicate the intentional ignoring of the return value, consider adding (void) cast.
(void)tu_edpt_stream_read_xfer(rhport, stream_rx); // prepare for more data
Thank you but I don't think it's necessary.
CFG_TUD_ENDPPOINT_MAX is already checked in usbd_edpt_open and usbd_edpt_iso_alloc, #3281 is due to erroneous test adapter sending invalid event which can only happens in stack overflow or RAM corruption.
Maybe @kkitayam @lijunru-hub are busy, if anything goes wrong we can fix it afterwards.
[hathach/tinyusb] New branch created: update-iso-alloc
@HiFiPhile oops, I thought there is still more changes to the PR. Didn't know that it is all implemented, give me a bit of time to do some basic testing.
Describe the PR
Remove assumption that HID Report descriptor is before HID Endpoint.
Additional context
I have been using tinyusb's HID Host stack in my project and came across a game controller that has an...odd configuration.
Most HID Devices have the HID Report Descriptor preceding the endpoint, however I came across a device that has it following the endpoint.
you can see it in this lsusb call where it tails the endpoint with DEVICE CLASS which is actually the Rep...
Operating System
Others
Commit SHA
latest master
Board
Adafruit Feather nrf52832 + USB Host Featherwing (max3421)
Firmware
custom firmware based on based on examples/host/cdc_msc_hid (only enabled CDC), compiled with nrfsdk 2.9.2 based on Zephyr.
What happened ?
I'm working on a small device (USB Host) to connect my Rowing machine (CDC Device) to translate received data to be tracked by my sports watch.
What I've stumbled accross is, that after a couple of unplug...
added logfile that shows the full connection process, incl. the partially happening 0D error on disconnect (which does prevent hanging on connecting the device again, since the busy_lock is reset)
I've applied these changes to a current version of tinyusb. Feel free to grab it from https://github.com/SmittyHalibut/tinyusb/commit/667ae4972cf0a8d11a0219da149e2994ecde6519 if you want to update the pull request.
@dpgeorge it seems to be fixed by #3293, let me know if that works for you.
@hathach yes, that PR fixes the issue. We have needed to update our TinyUSB submodule to include that patch which is not yet in a release (see https://github.com/micropython/micropython/pull/18406) and also fork the Espressif fork of TinyUSB to patch that as well (see https://github.com/micropython/micropython/pull/18407).
@dpgeorge I will make an minor release for this soon enough (in a day or two)
I will make an minor release for this soon enough (in a day or two)
That would be great, thank you!
make TUP_DCD_EDPT_ISO_ALLOC i.e dcd_edpt_iso_alloc()/dcd_edpt_iso_activate() as default driver implementation. dcd_edpt_close() is deprecated and will be removed from all driver in the future.
Pull Request Overview
This PR transitions TinyUSB to use dcd_edpt_iso_alloc()/dcd_edpt_iso_activate() as the default driver API for ISO endpoints, deprecating dcd_edpt_close(). The changes include:
- Inverting the conditional compilation logic in
dcd.hto make ISO APIs the default - Defining
TUP_DCD_EDPT_CLOSE_APIfor drivers that still implement the old API - Updating multiple DCD drivers to either stub out or implement the new ISO APIs
- Updating MCX board configuration files...
Adding -w to suppress all warnings for board targets is concerning. This silences all compiler warnings which could hide real issues. If specific warnings need to be suppressed for auto-generated code, use targeted warning suppressions (e.g., -Wno-specific-warning) instead of disabling all warnings.
These commented-out lines in dcd_edpt_iso_activate() should either be removed if unnecessary or uncommented with an explanation if they're needed. Leaving ambiguous commented code reduces maintainability.
#if CFG_TUD_MEM_DCACHE_ENABLE
// Ensure data cache coherency for DMA: clean and invalidate dcd_data_t before hardware access
dcd_dcache_clean_invalidate(&_dcd_data, sizeof(dcd_data_t));
#endif
[nitpick] The macro definition for ENDPTCTRL_RESET_MASK should be placed with other related masks in the enum block below (lines 71-76) rather than separately. This would improve code organization and make it easier to find related constants.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3345&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Operating System
Windows 11
Commit SHA
esp-idf v5.5.0
Board
esp32p4
Firmware
bool msc_complete_cb(uint8_t dev_addr, tuh_msc_complete_data_t const *cb_data)
{
if (cb_data->csw != NULL)
{
if (cb_data->csw->status == 0)
{
if (xSemaphoreGive(msc_completion_sem) != pdTRUE)
{
ESP_LOGE("MSC", "Failed to give msc_completion_sem");
}
}
els...
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Default ISO API leaves many MCUs without a working handler
Making TUP_DCD_EDPT_ISO_ALLOC the default in src/common/tusb_mcu.h (lines 692‑699) now routes every isochronous endpoint through dcd_edpt_iso_alloc()/dcd_edpt_iso_activate(), but several drivers added in the same commit still leave those functions as return false stubs – for example src/portable/microchip/samd/dcd_samd.c 248‑258, `src/...
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3345&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3345&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3345&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3345&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
@HiFiPhile PR stil haven't implemented the target frame yet. So the application need to call the edpt_xfer() 1 frame before the bInterval, otherwise we will miss that IN token and send data in the next bInterval (late timing) ?
I think in the future we have to improve how we manage ISO transfer e.g
- iso transfer --> compute target frame_num = last xferred frame_num + bInterval
- enable sof interrupt, loop for iso in check target frame, if there is transfer next --> write data, set...
is there any chances that 2 ISO is schedule at the same uframe, and 1 is complete and 1 is incomplete and we detect the wrong endpoint ?
thanks for the issue, I will check this out the next time I work with max3421e port (currently busy with other things)>
Pull Request Overview
This PR fixes an issue where queued transfers from a failed USB device enumeration interfere with subsequent enumeration attempts by implementing a cleanup mechanism for pending transfers when a device is closed.
Key Changes:
- Added a
closingflag to thehcd_xfer_tstructure to mark transfers being cleaned up - Modified
hcd_device_close()to mark associated transfers as closing and disable their channels - Updated all four channel interrupt handlers (IN/O...
For non-split periodic channels, the closing flag is set (line 470) but channel_disable() is not called (line 472-474). The closing flag is only checked within if (hcint & HCINT_HALTED) blocks in the interrupt handlers (lines 962-966, 1027-1031, 1149-1154, 1216-1221). If a non-split periodic channel doesn't naturally halt after the device is removed, it may never be properly cleaned up.
Consider whether non-split periodic channels need additional handling to ensure they eventually halt a...
In slave mode, the closing flag check uses else if (lines 962-966), which means it won't execute if the transfer has a valid result (line 957-958) or reached max errors (line 959-961). This could cause events to be sent for closing transfers.
In contrast, the DMA mode handlers (lines 1149-1154, 1216-1221) use a separate if statement that correctly overrides is_done to false regardless of the transfer result.
The slave mode handlers should use a separate if statement (not else if) ...
The endpoint is cleared before marking associated channels as closing, which creates a race condition. If a channel interrupt occurs after the endpoint is cleared (line 464) but before the transfer is marked as closing (line 470), the interrupt handler will access the cleared endpoint data via edpt = &_hcd_data.edpt[xfer->ep_id] (used in all channel handlers).
Recommendation: Move the tu_memclr(edpt, sizeof(hcd_endpoint_t)) call to after the channel cleanup loop, or disable interrupts fo...
Similar to the issue in handle_channel_in_slave, the closing flag check uses else if (lines 1027-1031), which means it won't execute if the transfer has a valid result (line 1022-1023) or reached max errors (line 1024-1026). This could cause events to be sent for closing transfers.
The DMA mode handlers (lines 1149-1154, 1216-1221) correctly use a separate if statement that overrides is_done to false.
Change this to a separate if statement (not else if) to match the DMA handler ...
is there any chances that 2 ISO is schedule at the same uframe, and 1 is complete and 1 is incomplete and we detect the wrong endpoint ?
The interrupt is fired at the end of periodic frame interval (80% of the frame by default), it's unlikely any transfer is still pending.
<img width="832" height="79" alt="image" src="https://github.com/user-attachments/assets/7bad7c0d-f749-42fc-97d0-8b6038f6bb60" />
PR stil haven't implemented the target frame yet. So the application need to call the edpt_xfer() 1 frame before the bInterval, otherwise we will miss that IN token and send data in the next bInterval (late timing) ?
@hathach Both audio and video are real-time streaming data it's ok to return transfer failed if the host didn't read the data in the specified interval. edpt_xfer() needs to be called not earlier than bInterval*frames before the IN token:
- If bInterval = 1 the packet is s...
Copilot sounds reasonable, I need to bring up the memory ...
I tried to update the tinyUSB stack (from the master branch), but the MSC transfer no longer works at all (even without HID connected).
There was a broken link in the readme.
I making some changes to PR as well, will take this chance to implement the hcd_edpt_close() as well
this is only true for DMA mode, for slave mode, we still need to disable it I guess
<img width="982" height="192" alt="Image" src="https://github.com/user-attachments/assets/167b4f64-7f23-4075-989a-458ec7ae0e6c" />
@HiFiPhile I make more changes to PR, also add closing flag for endpoint to de-alloc() it when chanel is halted with closing flags. Also put the check into chanel_disable(). Let me know if these make sense to you.
@hathach It looks good but I don't remember some details. Tried plugging in/out a bad contact USB stick on H7RS and no assert is hit.
@HiFiPhile why skipping these examples for h7rs, I see it compile just fine with minsize.
@HiFiPhile thanks for the explanation, I know ISO data can be missed. Let's say bInterval = 10, and we recevie setInterface at frame=100, assume host send the 1st IN token as well. So we will have
- frame 100: 1st IN token
- frame 110: 2nd In token and so on
So ideally video/audio must prepare the next iso data within the bInterval and call edpt_xfer() it as soon as the data is ready. let's say at frame 105th, the stack would then ideally only fetch data to fifo at frame 109. with the c...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
@hathach With LOG=2 IAR debug builds needs > 70k for these examples, cdc_msc_hid_freertos needs 66k even on MinRel build.
So ideally video/audio must prepare the next iso data within the bInterval and call edpt_xfer() it as soon as the data is ready. let's say at frame 105th, the stack would then ideally only fetch data to fifo at frame 109. with the current implementation, what would happen at frame 106,107 ?
@hathach If edpt_xfer is called at 105th data will be pushed into fifo and the transfer will be scheduled for 106th. At 106th incomplete interrupt fires and rearm the endpoint for 107th. At 107th same...
@hathach I'm think about when CFG_TUD_ENDPOINT0_BUFSIZE >= CFG_TUD_DFU_XFER_BUFSIZE we can skip dfu transfer buffer.
@hathach With LOG=2 IAR debug builds needs > 70k for these examples, cdc_msc_hid_freertos needs 66k even on MinRel build.
as long as minsize with LOG=0 compile, we can leave it enabled since that is what ci build, also user can test with those example as well.
I've just dropped that commit, maybe later we can enhance skip/only mechanism for debug variant.
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3295&issueStatuses=OP...
@hathach I'm think about when
CFG_TUD_ENDPOINT0_BUFSIZE >= CFG_TUD_DFU_XFER_BUFSIZEwe can skip dfu transfer buffer.
yeah, though I think we can do it in follow up Pr.
So ideally video/audio must prepare the next iso data within the bInterval and call edpt_xfer() it as soon as the data is ready. let's say at frame 105th, the stack would then ideally only fetch data to fifo at frame 109. with the current implementation, what would happen at frame 106,107 ?
@hathach If edpt_xfer is called at 105th data will be pushed into fifo and the transfer will be scheduled for 106th. At 106th incomplete interrupt fires and rearm the endpoint for 107th. At 107t...
excelllent PR as always. Thank you very much, I extract the function into its own handle_() to make it easier to read.
seems like lsusb also got confused by the device as well, this device is clearly out of specs. I am ok to add support for it. But the change seems to be more complicated than it should be. Let only change to allow the hid descriptor to either before (as current) or after endpoint descriptor
[hathach/tinyusb] New review comment on pull request #3151: osal/none: add nested count to spin lock
let make it simpler, in case of 0, we just return since the spin is not locked to begin with
perfect, thank you very much
[hathach/tinyusb] New branch created: fix-more-warnings
Pull Request Overview
This PR addresses static analysis alerts from PVS-Studio across the DWC2 USB host controller driver, focusing on improving code clarity and addressing MISRA-C compliance warnings.
Key changes:
- Added explicit unsigned literal suffixes (0x01u, 0x02u) to prevent type promotion issues
- Converted implicit boolean checks to explicit comparisons for 1-bit bitfields
- Refactored if-else chains into switch statements for transfer type handling
- Introduced named constants...
The file is named copilot-instructions.md (plural), not copilot-instruction.md (singular) as shown in the comment. Also, the path should be .github/copilot-instructions.md not ./github/copilot-instruction.md (the leading period should not be included in the path reference).
## Copilot Agent Notes (`.github/copilot-instructions.md`)
The comparison > 0 is unnecessary and changes the semantics. The post-decrement operator count-- returns the value before decrementing, so when count is 0, it returns 0 (which is falsy) and the loop terminates correctly. The original while (count--) idiom is the standard C pattern for countdown loops and is used consistently in similar files (e.g., dwc2_at32.h line 98). The added comparison doesn't fix any issue and makes the code less idiomatic.
while (count--) {
So are you imagining changing the original assert into a check TU_ASSERT(HID_DESC_TYPE_HID == desc_hid->bDescriptorType);
if it fails, attempt to flip the order and parse it that way?
Then assert if that fails?
[hathach/tinyusb] New branch created: update-agents
Pull Request Overview
This PR bumps the TinyUSB version from 0.19.0 to 0.20.0 in preparation for a new release. The changes update version numbers across configuration files, consolidate agent documentation, add new board presets, and document all changes in the release changelog.
- Version number updated from 0.19.0 to 0.20.0 across all configuration files
- Documentation consolidated from
.github/copilot-instructions.mdintoAGENTS.mdwith enhanced release instructions - New board ...
Malformed comment contains extraneous characters '(ver#'. Should be '##########' to match the comment style used elsewhere in the file.
###################
@hathach I think it's nice to have this one in 0.20, which fixes a spin lock issue when dcd_edpt_xfer() called by xfer_isr.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3313&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
[hathach/tinyusb] New tag created: 0.20.0
0.20.0 is release, please give it a try to see if there is any other new issues.
@HiFiPhile ooops, I didn't see your mention. Though this PR change driver signature, let have this in the next release.
Very good, thank you! I will test it.
@dinsfire64 I push the update, please try to see if that works for you.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3313&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
this may be fixed by #3007, if @RobertDaleSmith or anyone you have time to try it out.
@hathach I can't thank you enough for all the awesome work you do. I finally got around to revamping my USB controller project and updated to latest TinyUSB. Every controller I was having this issue with, is now working! 🙌
Just a minor typo as I think. Should be port 1 in the second interrupt request handler.
This pull request improves how control transfer buffers are managed for both the Audio and DFU device classes. The main enhancement is to allow the use of the endpoint 0 buffer for control transfers when it is large enough, falling back to a dedicated buffer only when necessary.
Pull Request Overview
This PR optimizes control transfer buffer management in TinyUSB by allowing device classes to use the EP0 buffer directly when it's large enough, avoiding unnecessary dedicated buffer allocations and memory copies. This improves memory efficiency on resource-constrained devices while maintaining the same functional behavior.
Key Changes
- Added
usbd_control_get_buffer()API to expose the EP0 buffer to device class implementations - Optimized control transfer p...
The get_ctrl_buffer() function is defined here but first used at line 1329 (before the definition). Since this is a static inline function, it needs to be defined before its first use or have a forward declaration.
Suggested fix: Move this function definition to an earlier location in the file, ideally near the other forward declarations (around line 450), or add a forward declaration.
I tested TinyUSB 0.20.0 and found an issue with samd21, see https://github.com/micropython/micropython/pull/18406#issuecomment-3561498377
Operating System
Others
Commit SHA
3af1bec
Board
STM32C071
Firmware
CDC Sample
What happened ?
HI,
Im trying now for days to make a very simple tinyUSB USB CDC sample with a STM32 Nucelo C071 board. I have searched the whole internet but found no explanation to my problem. Im failing to integrate the tinyUSB lib into my project. Can someone explain a minimal cmake example how to implement the tinyUSB lib?
BR
Matthias
How to reproduce ?
My cmake so far:
cm...
I'm not quite sure if it's actually wrong. I found that in five example codes the size of tusb_desc_device_t is taken for the tusb_desc_device_qualifier_t length field. In multiple other example codes the size of the actual struct tusb_desc_device_qualifier_t is taken instead.
But as I said, I'm not sure if it has some other background.
Thank you, device qualifer's length is indeed 10 bytes. Although this descriptor does nothing actually
Describe the PR
Add dcd_configure to configure dwc2 IN EP double buffer.
Although the gain is minimal as bandwidth limit is close (29MB/s vs 31MB/s). My PC's host controller only does 8 transfer per msof which yields a maximum throughput of 32MB/s.
I think there is no need to set FIFO level to complete empty in any case ?
Pull request overview
This PR adds a new configuration API (dcd_configure) to dynamically configure DWC2 device controller behavior, specifically enabling double buffering for IN endpoints to improve throughput. The implementation replaces the previous hardcoded TX FIFO empty level configuration with a configurable double buffering approach.
Key changes:
- New public API
tud_configure()to configure device stack behavior before initialization - DWC2-specific configuration structure t...
The documentation references 'tud_init()' which is deprecated (as shown in line 65). Consider updating to reference 'tud_rhport_init()' instead, or use the more generic 'initialization' to avoid referencing a specific deprecated function.
// Should be called before initialization of the device stack
Corrected function name reference from 'tuh_configure()' to 'tud_configure()'. This is a device-side API (tud_), not host-side (tuh_).
// ConfigID for tud_configure()
The '(TBD)' placeholder should be removed or updated to reflect actual usage. The parameter description should mention the TUD_CFGID_* enum values, e.g., 'configure ID from TUD_CFGID_* enum values'.
// - cfg_id : configure ID from TUD_CFGID_* enum values
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Dedicated hwfifo now breaks DWC2 DMA transfers
The new block unconditionally sets CFG_TUD_EDPT_DEDICATED_HWFIFO whenever TUP_USBIP_DWC2 and slave mode are enabled. When DMA is also enabled (CFG_TUD_DWC2_DMA_ENABLE=1), CDC/device streams now use usbd_edpt_xfer_fifo, which clears xfer->buffer (dcd_dwc2.c:687-692). The DMA path in edpt_schedule_packets() still programs diepdma from `xfer->buffe...
Pull request overview
This pull request removes intermediate endpoint buffers for USB endpoints with dedicated hardware FIFOs, optimizing memory usage and data transfer efficiency for certain USB controllers like DWC2.
- Introduces
CFG_TUD_EDPT_DEDICATED_HWFIFOconfiguration to enable direct hardware FIFO access without intermediate buffering - Refactors FIFO API to use
tu_fifo_access_mode_tenum withTU_FIFO_FIXED_ADDR_RW32mode for hardware FIFO operations - Updates CDC device cl...
Typo in comment: "even multiple wanted chars are present" should be "even if multiple wanted chars are present".
break; // only invoke once per transfer, even if multiple wanted chars are present
[nitpick] Missing space after // in comment. Should be // based on actual crash tests detected by fuzzing for consistency with comment formatting style.
Indentation is incorrect. These lines should be indented by 2 spaces to match the function body indentation.
Indentation is incorrect. This line should be indented by 2 spaces to match the function body indentation.
tu_fifo_set_overwritable(ff, true);
This line uses undefined functions _ff_count and _ff_remaining. These functions were removed in this PR and replaced with tu_ff_overflow_count and tu_ff_remaining_local. This will cause a compilation error.
tu_ff_overflow_count(f->depth, wr_idx, rd_idx), tu_ff_remaining_local(f->depth, wr_idx, rd_idx), n);
Operating System
Windows 11
Commit SHA
86a4990b96eafb5904f946fa061b310f155a7d51
Board
stm32n6
Firmware
examples/device/cdc_msc
What happened ?
Build fails with the following errors:
cdc_msc - Debug
system_stm32n6xx_fsbl.o
SAU->RNR = 0;
^
Error[Pe020]: identifier "SAU" is undefined D:\projects\SC3\test\BB\tinyusb\hw\mcu\st\cmsis_device_n6\Source\Templates\system_stm32n6xx_fsbl.c 192
SCB_NS->CPACR |= ((3UL << 20U)|(3UL << 22U)); /* set CP1...
[hathach/tinyusb] New branch created: hcd_fsdev
I think you can try to build a template project from STM32Cube, if the error persist it could be a ST's HAL bug. It's generally not a good idea to override internal symbol with double underscore.
I am able to create custom IAR project and make tinyusb work with stm32n6 but wanted to see how Cmake and documented how to works, and decided to build project from the examples folder. And this causes issue described above.
I am able to create custom IAR project with cubemx and make tinyusb work with stm32n6 but wanted to see how Cmake and documented "how to" works, and decided to build project from the examples folder. And this causes issue described above.
Normally internal symbols like __ARM_FEATURE_CMSE are defined automatically by IAR. Maybe the processor define in https://github.com/hathach/tinyusb/blob/master/examples/build_system/cmake/cpu/cortex-m55.cmake is incorrect, you can compare with your cu...
Describe the PR
Add stm32_fsdev HCD mode support, host mode works pretty like device mode with 8 bidirectional channels.
- Static buffer allocation, 64 bytes per channel (no ISO support)
- Dynamic channel allocation like dwc2
- No interrupt transfer scheduler, transfer will be retried on each frame if NAKed
- Hub is untested
Tested on Nucleo-C071RB (put on both STLINK and USB power jumper):
| Example | Result | Note |
|---|---|---|
| device_info | OK | Keyboard/Disk... |
Pull request overview
This PR adds USB Host Controller Driver (HCD) support for STM32 FSDEV peripheral, enabling host mode functionality on STM32 C0, G0, H5, and U5 MCU families. The implementation refactors common code from the existing device controller driver (DCD) into shared files to support both device and host modes.
Key changes:
- Implements a new HCD driver with static buffer allocation (64 bytes per channel), dynamic channel allocation, and NAK retry mechanism
- Refactors packe...
The comment incorrectly states 'External oscillator' but HSE_VALUE of 48MHz suggests this is configured for the Nucleo board's ST-LINK MCO output (which provides 48MHz from ST-LINK's HSE). The comment should clarify this is the ST-LINK MCO frequency, not a typical external crystal oscillator.
#define HSE_VALUE (48000000U) /*!< Value of the ST-LINK MCO output in Hz (Nucleo boards), not a typical external crystal oscillator */
hcd_edpt_close() should return true on success, not false. Other HCD implementations (dwc2, max3421) return true after successfully closing an endpoint. This function successfully closes the endpoint but incorrectly signals failure.
Thanks for your efforts!
tried to add extra param to
<img width="742" height="691" alt="Image" src="https://github.com/user-attachments/assets/674e1309-430f-42e9-98b1-f434ffd5a5cf" />
but same error for now.
<img width="2488" height="540" alt="Image" src="https://github.com/user-attachments/assets/3d61653a-f974-4092-b9da-b64c3656b730" />
Might be worth for me to rise issue with IAR on Cmake support.
Operating System
Windows 11
Commit SHA
the latest HEAD
Board
any board can reproduce this issue per my test, I tried stm32f103_bluepill and stm32f072disco
Firmware
examples/device/webusb_serial with attached patch to remove the cdc so that only CFG_TUD_VENDOR is enabled.
What happened ?
Windows can't initialize the usb device properly, and UsbTreeView show "28" for the device. so wi...
brilliant as usual, unfortunately, I got an sore throat and running nose. I will test this out later on when getting better.
[hathach/tinyusb] New branch created: n6_build
Update linker and compiler flag
-DTOOLCHAIN=iar is no longer needed.
you can compare with your cubemx project's build output (set Filter level to All in Build log window)
After compare the output myself I found --cmse flag is missing:
<img width="785" height="82" alt="Image" src="https://github.com/user-attachments/assets/d92dcf0d-abee-4826-bedd-4fcf606a0086" />
Should be fixed my #3367
[hathach/tinyusb] New branch created: disable_isr
Describe the PR
Some BSP have either:
- Enabled SysTick without
OPT_OS_NONEcheck - Forget to disable SysTick ISR with FreeRTOS
Fix them.
Pull request overview
This PR fixes SysTick timer configuration issues across multiple BSP (Board Support Package) implementations to ensure proper behavior when FreeRTOS is enabled. The changes prevent SysTick ISR from running before the FreeRTOS scheduler starts, which could cause timing issues and undefined behavior.
Key changes:
- Added explicit SysTick disable (
SysTick->CTRL &= ~1U;) for FreeRTOS configurations - Wrapped
SysTick_Configcalls withOPT_OS_NONEchecks where they ...
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
// Explicitly disable systick to prevent its ISR from running before scheduler start
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
Grammar issue in comment: "its ISR runs" should be "its ISR from running". The correct comment should read: "Explicitly disable systick to prevent its ISR from running before scheduler start"
[hathach/tinyusb] New branch created: misc_fix
Pull request overview
This PR includes miscellaneous fixes across the codebase, addressing performance settings, concurrency issues, and developer tooling improvements.
Key Changes:
- Enables FSDEV_HAS_SBUF_ISO for STM32U0, resolving previous audio performance issues
- Fixes potential race condition in FIFO empty check by reading volatile indices to local variables
- Improves Python audio debug script with better signal handling, error codes, and matplotlib best practices
Review...
Import pollutes the enclosing namespace, as the imported module ctypes does not define 'all'.
from ctypes import Structure, c_uint32, c_uint8, c_int8, c_int16, c_uint16 # type: ignore
Hey Espressif guys =)
If possible: PLEASE add dual tinyUSB stack support, so both USB2.0 Hosts can run at the same time.
I want to give you a valid important usecase:
You are already providing usb audio support & usb_hid support. Both device types -and that is the point - are mostly FS (!) ones.
Currently you cannot use them together with devices like mass storage and others with these others running at HS.
There are boards available already, that have "hubs" for HS (3 ports) and a single FS ...
I think they made a typo, N6 has 2 HS phy.
<img width="736" height="306" alt="image" src="https://github.com/user-attachments/assets/dc695afd-b633-4025-a985-790e12c81970" />
[hathach/tinyusb] New branch created: enum_catch
Description
During the recent update (https://github.com/hathach/tinyusb/pull/3326)
dcd_deinit(rhport); -> TU_VERIFY(dcd_deinit(rhport));
the assertion fails for the ports, where dcd_deinit() isn't implemented yet.
Changes
This PR introduces a quick fix by changing the default return value from false to true in the WEAK function, allowing the assert to pass.
The same way, as we have it for:
TU_ATTR_WEAK bool dcd_dcache_clean(const void* addr, uint32...
Describe the PR
I've made 2 hub enumeration reliability improvements, they works will here but not sure if there are any edge case.
-
Stop enumeration gracefully if EP0 can't be open
WhenCFG_TUH_FSDEV_ENDPOINT_MAXis not enough,usbh_edpt_control_open()fails and the hub become stuck.With quick plug/unplug sometimes old endpoint release happens after new endpoint open. Normally my config only needs 15 EPs (3 for hub + 4 for keyboard + 4 for USB key + 4 for FTDI) but I hit ...
I think we can take the chance to add dcd_deinit to dwc2, disable interrupt and disconnect may be enough ?
Related area
class driver
Hardware specification
Pico W or other boards with bluetooth support
Is your feature request related to a problem?
Hi, I see there is not an example for Bluetooth device class, I'm would like to get some example how it's the correct use of this driver.
I'm trying to use this driver with rp2040, but I'm having a hard time with an error about the setting the device configuration. I'm getting this error:
USBD Setup Received 00 09 01 00 00 00 00 00...
Hi @HiFiPhile,
I think we can take the chance to add dcd_deinit to dwc2
Sure, that is my next step.
This PR is about another thing: the dcd_deinit() might be optional, as the dcd_init() could have all the necessary code to start from two states: was init done or wasn't init done.
So in this case, if we have an TU_ASSERT() for the optional call, we need to make it pass even if the function isn't implemented.
My concern is maybe other port require additional tweak to proper deinit, returning true will hide the issue. I prefer to make TU_ASSERT(dcd_deinit(rhport)); in usbd.c to be safe and in dwc2:
dcd_deinit(uint8_t rhport) {
(void) rhport;
// to be filled later
return true;
}
@hathach What do you think ?
[hathach/tinyusb] New branch created: vendor-dedicated-hwfifo
- update vendor device to omit ep buf when dedicated hwfifo is supported
- change tud_vendor_rx_cb() behavior, buffer and bufsize only available when CFG_TUD_VENDOR_RX_BUFSIZE = 0
- add tud_vendor_n_read_discard(), refactor vendor device. Update webusb example for more robust
- add tu_fifo_discard_n() and tu_edpt_stream_discard()
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3373&issueStatuses=OP...
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Restore non-FIFO stream reads
In tu_edpt_stream_read the non-FIFO path now immediately returns 0 without copying from s->ep_buf. For configurations that deliberately disable the RX FIFO (e.g., CFG_TUD_VENDOR_RX_BUFSIZE == 0 or any stream with tu_fifo_depth(&s->ff) == 0), host transfers complete and tud_vendor_n_read() is invoked but always reports no data because the endpoint buffer is never...
Pull request overview
This PR updates the vendor device implementation to support hardware endpoints with dedicated FIFO buffers, eliminating the need for local endpoint buffers in such configurations. This optimization reduces memory usage on hardware platforms with built-in FIFO support.
Key Changes:
- Modified stream read/write functions to handle both buffered and unbuffered (dedicated HWFIFO) modes
- Changed
tud_vendor_rx_cb()API behavior: buffer/bufsize parameters are only v...
Typo in comment: "rad" should be "read". The comment reads "Read one item without removing it from the FIFO, correct rad index if overflowed" but should say "correct read index if overflowed".
// Read one item without removing it from the FIFO, correct read index if overflowed
The newly added tusb_buffer_t struct is defined but never used anywhere in the codebase. Consider removing it unless it's intended for future use in subsequent commits.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3373&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
I think it's useful to add a config whether next transfer is scheduled automatically or manually later in read_finished().
To give processing time for some commands.
Related area
I am trying to make a CCID reader device
Hardware specification
ESP32S3
Is your feature request related to a problem?
Firstly, please, let me know if there is any way to make a "generic" device with simple bulk in and out.
If so, that would suit me for now. But so far I have not found one - perhaps this could itself be a feature to allow for a variety of classes of devices that are not yet covered by TinyUSB. I tried VENDOR, but had not realised that it specific...
You can slightly modify the vendor class and register it as a custom driver. check https://github.com/kkitayam/akiprobe as example.
Just declare the interface then use usbd_app_driver_get_cb()
usbd_class_driver_t const cmsis_dap = {
#if CFG_TUSB_DEBUG >= 2
.name = "CMSIS-DAP",
#endif
.init = cmsis_dapd_init,
.reset = cmsis_dapd_reset,
.open = cmsis_dapd_open,
.control_xfer_cb = tud_vendor_control_xfer_cb,
.xfer_cb = cmsis_dapd_xf...
I had not found "app" driver, thanks. Is that essentially a generic driver (does not check class) that has bulk in and out?
Is that essentially a generic driver (does not check class) that has bulk in and out?
Yep, just modify the class code check to meet your need.
Perhaps the VENDOR class could avoid checking the class is 0xFF and add bulk in and out?
This check is needed for each class to avoid messing around with other class drivers, on device init the configuration descriptor passes into all classes, the class driver should process only the one it concerns.
what CFG_TUD_ do I define?
Do what ever y...
OK, a generic class could have a #define for what class code to check even. And even #defines to say which interfaces to expect with a simple BULK IN/OUT default perhaps.
But it seems I will have to change some tinyusb code to make anything work for me, bodging VENDOR or some such. I can do that, but makes it a maintenance headache as I can never update the managed components from ESP IDF without zapping my changes.
A feature request (apart from smart card specific) would be a way to allow,...
I can do that, but makes it a maintenance headache as I can never update the managed components from ESP IDF without zapping my changes.
You don't need to poke around managed components, I wasn't clear that I means was copy vendor class driver and modify it in your project, not in-place modification.
OK, a generic class could have a #define for what class code to check even. And even #defines to say which interfaces to expect with a simple BULK IN/OUT default perhaps.
Vendor class cod...
OK, can I just copy vendor class and change. Literally copy the C code to my main and that will work?
I am a make person and never got to grips with cmake, so sorry if that is a dumb question.
If so, that will be a good way forward, thank you.
If I have missed the point, some clues would be appreciated.
OK, can I just copy vendor class and change. Literally copy the C code to my main and that will work?
Yep, copy the code and modify the name to avoid collision, to something like ccid_open, ccid_reset, ccid_xfer_cb etc.
Then add driver registration:
usbd_class_driver_t const ccid_driver = {
#if CFG_TUSB_DEBUG >= 2
.name = "CCID driver",
#endif
.init = ccid_init,
.reset = ccid_reset,
.open = ccid_open,
.control_xfer_cb = ccid_control...
I'll try that - thanks for you help.
yeah, we can have tud_vendor_configure() for manual read transfer including the intial xfer() when driver is open()
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3373&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
I add CFG_TUD_VENDOR_RX_MANUAL_XFER (default to 0) instead of dynamic configure, since I think this is only helpful with no-fifo RX.
Nice, but I think the logic is inversed in vendord_open and vendord_xfer_cb ?
ah right, sorry. It is late here already.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3373&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
[hathach/tinyusb] New branch created: fix-zephyr-build
Pull request overview
This PR fixes build compatibility with Zephyr RTOS when using the latest nrfx v4 by adding proper version detection and conditional compilation for Zephyr-specific configurations.
Key changes:
- Extended nrfx version detection to support v3 and v4 based on MDK version ranges
- Updated clock API calls to use the new nrf_clock_is_running() function for nrfx v2+
- Added Zephyr-specific conditional compilation to exclude UART initialization that conflicts with Zephyr's ...
The variable active_clk_src is declared but its value is never used after the function call. Consider using NULL as the third parameter if the API supports it, or add a comment explaining why the output parameter is intentionally unused.
// Output parameter unused; pass NULL
return nrf_clock_is_running(NRF_CLOCK, NRF_CLOCK_DOMAIN_HFCLK, NULL);
[nitpick] The macro was renamed from _MDK_VERSION to MDK_VERSION, removing the leading underscore. This could potentially conflict with a macro defined by the MDK headers themselves. Consider using a project-specific prefix like TUSB_MDK_VERSION to avoid potential naming collisions with external libraries.
The void cast should include both unused parameters. Add (void) len; on the next line to explicitly mark both parameters as intentionally unused in the Zephyr build.
(void) buf;
(void) len;
<sub><sub></sub></sub> Preserve clock API for nrfx v2/v3 builds
When CFG_TUD_NRF_NRFX_VERSION resolves to 2 or 3 (MDK 8.44–8.53 per the version table), hfclk_running now calls nrf_clock_is_running(NRF_CLOCK, NRF_CLOCK_DOMAIN_HFCLK, …) for all versions greater than 1. That helper only exists in nrfx v4, while the v2/v3 HALs still expose nrf_clock_hf_is_running, so building against the common nrfx v2/v3 SDKs will fail t...
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
[hathach/tinyusb] New branch created: armgcc-toolchain
Pull request overview
This PR refactors the ARM GCC toolchain setup in CI/CD workflows from using a third-party GitHub action to manual download and installation. The change enables cross-platform support by allowing OS-specific toolchain downloads for Windows and macOS builds.
Key changes:
- Removes dependency on
carlosperate/arm-none-eabi-gcc-actionfor ARM GCC installation - Adds OS-specific ARM GCC toolchain URLs to support macOS and Windows runners
- Updates Nordic board reference...
The macOS toolchain URL specifies darwin-arm64, which only supports Apple Silicon Macs. Intel-based macOS runners (if any are used) would fail with this toolchain. Consider using darwin-x64 for broader compatibility or documenting that macOS builds require ARM64 runners.
"arm-gcc-macos-latest": "https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v14.2.1-1.1/xpack-arm-none-eabi-gcc-14.2.1-1.1-darwin-x64.tar.gz",
BTH is too complicated, you need an bluetooth stack to get it running like ecm need lwip. Check out the mynewt blehci example with pca10056. It works the last time I tried. https://github.com/hathach/mynewt-tinyusb-example
[hathach/tinyusb] New branch created: dwc2_deinit
@roma-jam Hi, I've added deinit support to dwc2, tested on STM32H7S3:
static uint32_t btn_prev = 0;
const uint32_t btn = board_button_read();
static bool onoff = false;
if (!btn_prev && btn) {
onoff = !onoff;
if(onoff) {
tud_deinit(BOARD_TUD_RHPORT);
printf("Host Stopped\r\n");
} else {
tusb_rhport_init_t dev_init = {
.role = TUSB_ROLE_DEVICE,
.speed = TUSB_SPEED_AUTO
...
Pull request overview
This PR adds deinitialization support for the Synopsys DWC2 USB controller, enabling dynamic start/stop of USB host and device modes. The implementation mirrors the initialization sequence in reverse, disabling interrupts, disconnecting from the bus, and resetting the core. This was tested on STM32H7S3 with device mode toggling via button press.
Key Changes
- Implements
hcd_deinit()anddcd_deinit()functions for DWC2 host and device controllers - Adds commo...
The host deinit function should turn off VBUS power before shutdown, similar to how hcd_init() turns it on with dwc2->hprt = HPRT_POWER; at line 435.
Add before calling dwc2_core_deinit():
dwc2->hprt = HPRT_W1_MASK; // clear write-1-clear bits
dwc2->hprt = 0; // turn off VBUS
// Turn off VBUS power before shutdown
dwc2->hprt = HPRT_W1_MASK; // clear write-1-clear bits
dwc2->hprt = 0; // turn off VBUS
The deinit function already calls dcd_disconnect() at line 511, which sets dwc2->dctl |= DCTL_SDIS (soft disconnect). Then dwc2_core_deinit() sets the same bit again at dwc2_common.c:258. This is redundant, though not harmful. Consider whether the soft disconnect in dwc2_core_deinit should be removed to avoid duplicate operations.
dwc2_core_deinit(rhport); // Note: Remove redundant soft disconnect in dwc2_core_deinit implementation.
The DCTL register is device-specific and should not be accessed unconditionally in a common deinit function that is called by both host and device modes. When in host mode, this writes to a device-only register which may cause undefined behavior.
Consider removing this line or making it conditional based on the role (host vs device), similar to how the init sequence uses TUSB_ROLE_HOST vs TUSB_ROLE_DEVICE. The device-specific disconnect should be handled in dcd_deinit() (which already...
@copilot fix ci build issue with make-os: matrix: os = "windows-latest", arm-none-abi-gcc is added to GITHUB_PATH but not found when running build.py with make. Possibly the GITHUB_PATH is not the same as cmd.exe
Thanks for the feedback on #3377. I've created this new PR, which merges into #3377, to address your comment. I will work on the changes and keep this PR's description up to date as I make progress.
Original PR: #3377
Triggering comment (https://github.com/hathach/tinyusb/pull/3377#issuecomment-3589933143):
@copilot fix ci build issue with make-os: matrix: os = "windows-latest", arm-none-abi-gcc is added to GITHUB_PATH but not found when running build.py with make. Possibly the GITHUB_PATH...
@hathach I've opened a new pull request, #3379, to work on those changes. Once the pull request is ready, I'll request review from you.
@copilot the target branch is update, rebase
@copilot the target branch is update, rebase
I'm unable to perform a rebase as I don't have access to force push or pull from GitHub. Could you please rebase this branch on your end, or let me know if you'd like me to recreate the changes on a fresh branch?
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3378&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3378&issueStatuses=OP...
Unreachable code detected. It is possible that an error is present.
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3378&issueStatuses=OP...
A OTG example has been added in #3378, I haven't tested on H7 hope it works.
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3378&issueStatuses=OP...
Unreachable code detected. It is possible that an error is present.
Pull request overview
Copilot reviewed 22 out of 22 changed files in this pull request and generated 9 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Incorrect register field used. The code is clearing bits from USB_OTG_HS->GOTGCTL but using USB_OTG_GCCFG_VBVALEXTOEN and USB_OTG_GCCFG_VBVALOVAL which are GCCFG register bits, not GOTGCTL register bits. This should likely be:
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL;
Incorrect pin reference in comment. For STM32U5, the comment should not reference "PM9" as this appears to be copied from STM32H7RS code. The pin reference should be updated to match the actual hardware configuration for STM32U5.
// Enable VBUS sense (B device) via pin PA9
Spelling error: "Disaable" should be "Disable".
// Disable session valid override
Incorrect register field used. The code is clearing bits from USB_OTG_HS->GOTGCTL but using USB_OTG_GCCFG_VBVALEXTOEN and USB_OTG_GCCFG_VBVALOVAL which are GCCFG register bits, not GOTGCTL register bits. This should likely be:
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALEXTOEN;
USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBVALOVAL;
The documentation is misleading. The example supports both FreeRTOS and non-RTOS modes (as evidenced by the code at lines 120-172 in main.c), not just "polling mode without RTOS". Consider updating this to: "The example supports both FreeRTOS and polling mode (no RTOS)".
- The example supports both **FreeRTOS** and **polling mode** (no RTOS)
Thanks @HiFiPhile , I will try it on H7 and get back
[hathach/tinyusb] New branch created: audio_open
This pull request improves the robustness of the audio device interface validation logic in audio_device.c by adding extra checks to differentiate between Audio and MIDI interfaces.
- Added logic to verify that the second interface descriptor is specifically Audio Streaming (subclass 2) and not MIDI Streaming (subclass 3), preventing misidentification between audio and MIDI devices.
Pull request overview
This PR enhances the audiod_open function in audio_device.c to properly differentiate between Audio and MIDI device interfaces, preventing the audio driver from incorrectly accepting MIDI devices. The fix adds validation logic to verify that the interface following an Audio Control interface is Audio Streaming (subclass 2) rather than MIDI Streaming (subclass 3).
Key changes:
- Added explicit return value
0to all TU_VERIFY and TU_ASSERT macro calls for co...
The loop condition p_desc_end - p_desc > 0 doesn't validate that there's enough space to safely call tu_desc_next(p_desc) and tu_desc_type(p_desc). If a malformed descriptor has a length field of 0, this could cause an infinite loop. Consider using tu_desc_in_bounds(p_desc, p_desc_end) helper function (similar to line 870 in midi_device.c) which properly validates descriptor boundaries before advancing.
while (tu_desc_in_bounds(p_desc, p_desc_end) && tu_desc_type(p_d...
The bounds check p_desc_end - p_desc > 0 only verifies at least 1 byte is available, but then the code accesses next_itf->bInterfaceClass and next_itf->bInterfaceSubClass which requires a full tusb_desc_interface_t structure (9 bytes). This could read beyond the buffer boundary if there are fewer than 9 bytes remaining. The check should be p_desc_end - p_desc >= sizeof(tusb_desc_interface_t) to ensure safe access to the structure fields.
if (p_desc_end - p_desc >= ...
This fix tested and worked for my problem in discussion: https://github.com/hathach/tinyusb/discussions/3382
[hathach/tinyusb] New branch created: pr-size-diff
Describe the PR
A clear and concise description of what this PR solve.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Metrics target lacks Python interpreter
The new tinyusb_examples_metrics target is invoked by the updated build script, but the command relies on ${Python3_EXECUTABLE} even though this CMake project never calls find_package(Python3). As a result, the first argument of the custom command expands to an empty string and attempts to execute tools/metrics.py directly, which is not marked executable. ...
Pull request overview
This PR introduces automated code size metrics collection and reporting for TinyUSB by integrating the linkermap tool. The changes include adding a new metrics aggregation script, refactoring the build system to use safer subprocess calls, and configuring CMake to generate linker map files and compute average code sizes across multiple builds.
- Added
tools/metrics.pyto calculate and aggregate average sizes from multiple linker map files - Refactored `tools/build...
Potential KeyError if the JSON data doesn't contain the expected 'files' key. Consider adding validation or using .get("files", []) to handle missing keys gracefully, especially since this processes external data from linker map files that might have varying formats.
f for f in json_data.get("files", [])
[nitpick] Commented-out debug code should be removed before merging. If this debug output is needed for troubleshooting, consider using a debug/verbose flag instead.
Potential KeyError if json_data doesn't contain the expected keys ('sections', 'files'). Consider adding validation or error handling to ensure the loaded JSON has the required structure, especially since line 68 has a generic exception handler that might mask structural issues.
The metrics module is imported but never used in this file. Consider removing this unused import.
The glob module is imported but never used in this file. Consider removing this unused import.
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=OP...
Quality Gate failed
Failed conditions
[1 Security Hotspot](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=OP...
Linker Map Summary
| File | .text | .rodata | .data | .bss | Total |
|---|---|---|---|---|---|
| ehci.c | 2651 | 0 | 0 | 5970 | 8622 |
| cdc_host.c | 6655 | 487 | 15 | 1612 | 8450 |
| ncm_device.c | 1496 | 28 | 1408 | 5964 | 7475 |
| hcd_dwc2.c | 4885 | 29 | 0 | 512 | 5426 |
| usbh.c | ... |
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Linker Map Summary
| File | .text | .rodata | .data | .bss | Total |
|---|---|---|---|---|---|
| ehci.c | 2652 | 0 | 0 | 6056 | 8709 |
| cdc_host.c | 6643 | 487 | 15 | 1612 | 8438 |
| ncm_device.c | 1503 | 28 | 1408 | 5961 | 7478 |
| hcd_dwc2.c | 4885 | 29 | 0 | 512 | 5426 |
| usbh.c | ... |
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
Quality Gate failed
Failed conditions
[2 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=hathach_tinyusb&pullRequest=3384&issueStatuses=O...
TinyUSB Code Size Different Report
Base: base-metrics/metrics.json
New: metrics.json
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 0 | 2804 ➡ 2809 (+5, +0.2%) | 1228 ➡ 1228 | 1754 ➡ 1749 (-5, -0.3%) | 4553 ➡ 4553 |
| cdc_device.c | 16 ➡ 16 | 1431 ➡ 1436 (+5, +0.3%) | 22 ➡ 22 | 664 ➡ 684 (+20, +3.0%) | 2094 ➡ 2119 (+25, +1.2%) |
| cdc_host.c | 487 ➡ 487 | 6653 ➡ 6655 (+2, +0.0%) | 15 ➡ 15 | 1444 ➡ 1612 (+168, +... |
[hathach/tinyusb] New branch created: fine-tune-ci
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
[hathach/tinyusb] New review comment on pull request #3386: fine tune ci to build more with circleci
<sub><sub></sub></sub> Avoid unbounded parallelism when PR builds switch to make
Setting BUILD_SYSTEM="make" for pull requests means CircleCI PR jobs now go through the make path in tools/build.py, but that path ignores the -j 4 cap you pass in config and instead spins up a multiprocessing pool sized to os.cpu_count() while also disabling -j in make_one_example when CIRCLECI is set (see tools/build.py lines 14...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 0 | 2804 ➡ 2806 (+2, +0.1%) | 1228 ➡ 1228 | 1754 ➡ 1754 | 4553 ➡ 4555 (+2, +0.0%) |
| cdc_device.c | 16 ➡ 16 | 1431 ➡ 1433 (+2, +0.1%) | 22 ➡ 22 | 664 ➡ 653 (-11, -1.7%) | 2094 ➡ 2085 (-9, -0.4%) |
| cdc_host.c | 487 ➡ 48... |
Sorry for the delay. I have been onleave from work and this account is tied to my work email which I haven't been checking while I am out. I'm catching up with the engineer who was working on USB while I was out. Give me a little bit to get back up to speed and I can test this out.
@fcooperti Hi, any update ?
Operating System
Linux
Commit SHA
1
Board
Any board using STM32F103xB
Firmware
TinyUSB asserts when trying to open a USB endpoint with address 08.
What happened ?
In STM32 USB endpoint values are 4 bit, with values 0 - 15.
tusb_mcu.h defines TUP_DCD_ENDPOINT_MAX as 8 which is incorrect. It should be 16.
How to reproduce ?
Try and open an endpoint address >= 0x08, e.g. 0x88 and usbd.c will assert at approx line 1360.
for example
#define EPNUM_CDC_3_NOTIF...
Please check reference manual first.
<img width="817" height="211" alt="Image" src="https://github.com/user-attachments/assets/7b3d2dfd-eca2-4107-98c8-3748e3ecdac9" />
<img width="879" height="178" alt="Image" src="https://github.com/user-attachments/assets/eb0a0862-4cf5-4e02-96c7-784ce3febe61" />
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.
Original prompt
Fix #3387, stm32_fsdev support 4 bit (0-15) EP address, but hte endpoint count is 8
💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.
Quality Gate passed
Issues
[0 New issues](https://sonarcloud.io/project/issues?id=hathach_tinyusb&pullRequest=3388&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod...
TinyUSB Code Size Different Report
Base: base-metrics/metrics.json
New: metrics.json
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 0 | 2804 ➡ 2809 (+5, +0.2%) | 1228 ➡ 1228 | 1754 ➡ 1738 (-16, -0.9%) | 4553 ➡ 4541 (-12, -0.3%) |
| cdc_device.c | 16 ➡ 16 | 1431 ➡ 1438 (+7, +0.5%) | 22 ➡ 22 | 664 ➡ 714 (+50, +7.5%) | 2094 ➡ 2150 (+56, +2.7%) |
| cdc_host.c | 487 ➡ 487 | 6653 ➡ 6619 (-34, -0.5%) | 15 ➡ 15 | 1444 ... |
it not how it should be changed. TUP_DCD_ENDPOINT_MAX increase memory footprint, if we want to support these numbering, we should use these as index in the fsdev driver instead
hw only support up to 8 endpoints, can you use the number 1-7 instead ?
it not how it should be changed. TUP_DCD_ENDPOINT_MAX increase memory footprint, if we want to support these numbering, we should use these as index in the usbd and fsdev driver instead.
Yeah, forgot about that.
[hathach/tinyusb] New branch created: more-ci-build-for-size
run cmake ci build on github with a fixed set of board to keep the metrics size stable
Pull request overview
This PR refactors the CI build configuration to use a fixed set of boards, migrating from file-based skip lists to Python-based configuration dictionaries. The change introduces two new command-line options (--one-first and --one-random) to replace the previous --one-per-family flag, providing more explicit control over board selection in CI builds.
Key Changes:
- Migrated CI board control from
skip_ci.txtfiles to Python dictionaries (ci_skip_boardsa...
The logic when both one_first and one_random are True is potentially confusing. If both flags are set, one_first always takes precedence over one_random (line 245-246 will execute before reaching 247-248). Consider adding mutual exclusivity validation or documenting the precedence order explicitly. For example:
if one_first and one_random:
raise ValueError("Cannot specify both --one-first and --one-random")
Or at minimum, document in the function docstring which fl...
The select_list (from ci_preferred_boards) is returned without validation. This could return boards that:
- Don't exist in the family
- Were filtered out by
skip_list(fromci_skip_boards) - Result in an empty list if all preferred boards are skipped
Consider validating that at least one board from select_list exists in all_boards:
if select_list:
valid_boards = [b for b in select_list if b in all_boards]
if valid_boards:
return valid_boards
# Fa...
[nitpick] The previous implementation checked if a board was already specified via the -b flag and would skip selecting a board from that family. This check has been removed, which means if a user specifies both a family and a specific board from that family (e.g., python tools/build.py stm32h7 -b stm32h743eval --one-first), the board may be built twice (once from the -b flag and once from the family selection).
If this behavior change is intentional for simplification, consider docume...
The comment states "only one random board per family" but the actual build option used is --one-first (line 81), which selects the first board alphabetically, not a random one. Update the comment to reflect the actual behavior:
# CMake build: only one board per family (first alphabetically). Full build is done by CircleCI in PR
# CMake build: only one board per family (first alphabetically). Full build is done by CircleCI in PR
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
| File | .text | .rodata | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 2811 ➙ 2809 (-2, -0.1%) | 0 | 1228 | 1751 ➙ 1739 (-12, -0.7%) | 4557 ➙ 4542 (-15, -0.3%) |
| cdc_device.c | 1436 ➙ 1437 (+1, +0.1%) | 16 | 22 | 680 ➙ 698 (+18, +2.6%) ... |
FYI this change increased the CircuitPython arduino_zero build by 532 bytes. I can't easily update to 0.20.0 due to this because some languages now overflow (ru in this case).
It now includes tu_edpt_stream_write_xfer and tu_edpt_stream_read_xfer which are 280 bytes. midid_ init, open, reset and xfer_cb all grow in size as well.
@tannewt do you have a branch that have wip 0.20.0 (else I will just bump tinyusb submodule in cpy to test with). I will try to see if could reduce the size by dropping features that some smaller ports does not need. This refactor all common edpt stream code so it should reduce code size if e.g cdc and midi both enabled, but I haven't check.
PS: I am trying to optimize the code size for tinyusb, new PR now will have a comment on code size change.
[hathach/tinyusb] New branch created: more-diff-size-report
Describe the PR
A clear and concise description of what this PR solve.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
I've compared HEAD and 2f0a35f21af4c09154d6b4b5b118325af8990e51 with IAR debug build midi_test:
| Header | HEAD | 2f0a35f21 |
|---|---|---|
| midi_device.o | 1578 | 1490 |
| tusb.o | 1964 | 448 |
| Total | 23298 | 21706 |
We can reduce size by remove some inline comparing tud_midi_n_available()
Master:
<img height="900" alt="image" src="https://github.com/user-attachments/assets/dd168d5c-9bc1-4550-93ec-a201e895d320" />
2f0a35f21af4c09154d6b4b5b118325af8990...
[hathach/tinyusb] New branch created: size_tweak
I did some test in https://github.com/hathach/tinyusb/tree/size_tweak by:
- un-inline common used functions
- unpack 2 packed bitfield, cortex-m is inefficient doing bit-ops
While it's still larger but half-way done ;)
Debug:
| Header | HEAD | 2f0a35f21 | Test |
|---|---|---|---|
| midi_device.o | 1578 | 1490 | 1430 |
| tusb.o | 1964 | 448 | 1404 |
| Total | 23298 | 21706 | 22278 |
Release:
| Header | HEAD | 2f0a35f21| Test |
|--------|--------|--------|----...
is due to extra log in edpt stream that cover all cases such as non-buffered (non-fifo) and xfer_fifo. I will try also to optimize further
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in any section
No entries.
Changes <1% in all sections
No entries.
No changes
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 0 | 2809 | 1228 | 1739 | 4542 |
| cdc_device.c | 16 | 1437 | 22 | ... |
[hathach/tinyusb] New branch created: hide-unchange-size
Describe the PR
A clear and concise description of what this PR solve.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
@tannewt do you have a branch that have wip 0.20.0 (else I will just bump tinyusb submodule in cpy to test with).
I was testing with https://github.com/adafruit/circuitpython/pull/10736 but didn't end up needing to update TinyUSB. I had done it to the 0.20.0 tag. The tip of master yesterday had even less remaining space.
I was doing the arduino_zero TRANSLATION=ru build in testing. It has CDC and MIDI so it should share the stream code. It is LTOd too. That may make a difference.
Apologies for the delay, the holidays have eaten up my time to test.
Your suggested commit works correctly with the quirky device and I am happy with the solution if you are.
[hathach/tinyusb] New branch created: ci_deinit
Describe the PR
Tested on LPC4322 with new dynamic_switch example.
Rebase after #3378
Pull request overview
This PR adds comprehensive deinitialization support to TinyUSB, enabling dynamic switching between USB device and host modes at runtime. The changes introduce new pre-init and post-deinit callback hooks, implement deinit functions across multiple USB controller drivers, and include a new example demonstrating the dual-role switching capability.
Key Changes:
- Added
tusb_pre_init_cb()andtusb_post_deinit_cb()callback hooks with weak default implementations ...
The comment "// Switch to the other mode" appears misplaced. It should be on its own line after the #endif, as it describes the code block starting at line 244, not the #endif directive itself.
#endif
// Switch to the other mode
The comment states "via pin PA14" but the VBUS sense pin for OTG_FS is configured on PA9 (see line 181 in board_init()). This should read "via pin PA9" instead.
// Enable VBUS sense (B device) via pin PA9
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in any section
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| dcd_ci_hs.c | 0 | 1725 ➙ 1726 (+1, +0.1%) | 0 | 1152 ➙ 1280 (+128, +11.1%) | 2493 ➙ 2512 (+19, +0.8%) |
| ehci.c | 0 | 2651 ➙ 2655 (+4, +0.2%) | 0 | 5970 ... |
I would like to point out that the number of hw endpoint registers has nothing to do with the values of an endpoint address.
They are two separate things, e.g. a single hw endpoint register can hold any endpoint address in the range 0 - 15.
we know, but atm we don't have plan/motivation to implement that since user can simply use the number 1-7 instead.
Operating System
Linux
Commit SHA
1
Board
WeActv-STM32F103CBT6-BluePillv1.1
Firmware
A triple CD, triple UART application on a AliExpress Bluepill board (fitted with a non fake STM processor).
TinyUSB source code was taken from the github Releases area in .zip form, for 0.19.0 and 0.20.0.
App code was initially written using 0.18.0.
I just updated it to using to 0.20.0 and it stopped working.
I've just stepped back and tried 0.19.0 instead which works, i.e. updating fro...
From your log I saw a transfer was queued before the device is fully initialized:
USBD Setup Received 80 06 00 02 00 00 CF 00
Get Descriptor Configuration[0]
Queue EP 80 with 32 bytes ...
Queue EP 00 with 8 bytes ... <-------EP not init yet
USBD Xfer Complete on EP 80 with 32 bytes
Queue EP 80 with 32 bytes ...
USBD Xfer Complete on EP 80 with 32 bytes
Queue EP 80 with 32 bytes ...
USBD Xfer Complete on EP 80 with 32 bytes
Queue EP 80 with 32 b...
[hathach/tinyusb] New branch created: hwfifo_post
Describe the PR
- Add
CFG_TUD_EDPT_DEDICATED_HWFIFOflag to other supported families. - There is a weak
dcd_edpt_xfer_fifo()implementation in usbd.c so no need to guardusbd_edpt_xfer_fifo()withCFG_TUD_EDPT_DEDICATED_HWFIFOflag, remove the ifdef guard makes the log more verbose when failed (was debugging why audio no longer work) - In audio_device.c, replace local test by
CFG_TUD_EDPT_DEDICATED_HWFIFO
Pull request overview
This PR standardizes the handling of hardware FIFO support across different USB IP families by introducing and utilizing the CFG_TUD_EDPT_DEDICATED_HWFIFO configuration flag.
Key Changes:
- Fixed a typo in DWC2 host configuration (CFG_TUD → CFG_TUH on line 312)
- Added
CFG_TUD_EDPT_DEDICATED_HWFIFOsupport for ChipIdea HS, FSDEV, MUSB, and RUSB2 USB IP families - Removed
CFG_TUD_EDPT_DEDICATED_HWFIFOguards fromusbd_edpt_xfer_fifo()to enable better log...
The condition !defined(CFG_TUD_MEM_DCACHE_ENABLE) should be !CFG_TUD_MEM_DCACHE_ENABLE. According to the comment on line 327, FIFO transfer should be enabled when "DCACHE is disabled" (i.e., when the value is 0), not when it's undefined. This matches the pattern used for DWC2 on line 308 (!CFG_TUD_DWC2_DMA_ENABLE) and the actual usage in dcd_ci_hs.c:526 (#if !CFG_TUD_MEM_DCACHE_ENABLE). The current condition would incorrectly enable FIFO when DCACHE is undefined, which could lead to...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in any section
| File | .rodata | .text | .data | .bss | Total |
|---|---|---|---|---|---|
| audio_device.c | 0 | 2809 ➙ 2802 (-7, -0.2%) | 1228 | 1739 ➙ 1677 (-62, -3.6%) | 4542 ➙ 4474 (-68, -1.5%) |
| cdc_device.c | 16 | 1437 ➙ 1430 (-7, -0.5%) ... |
Thanks for the quick look at that. I've gone thru my code and added in tud_cdc_n_ready() calls prior to any CDC accesses.
Also chopped out most of the other app functionality, e.g. buttons, uarts etc... to reduce what I'm looking thru.
The app now asserts at cdcd_open 376, (cdc_device.c which is where it was initially asserting on my 1st attempt at using 0.20.0).
TU_ASSERT(tu_edpt_stream_read_xfer(rhport, stream_rx) > 0, 0); // prepare for incoming data
My app basically boils down to
m...
UPDATE - I have found what it is in my code that is causing the failure in 0.20.0 --> setting CFG_TUD_CDC_RX_BUFSIZE=32.
(I have CFG_TUD_ENDPOINT0_SIZE=64, CFG_TUD_CDC_TX_BUFSIZE=64 and CFG_TUD_CDC_EP_BUFSIZE=64).
(My original app code which worked for 0.18.0 and 0.19.0 set all four values to 32).
Attached are two logs for CFG_TUD_CDC_RX_BUFSIZE=32 and CFG_TUD_CDC_RX_BUFSIZE=64.
(In both logs, the other three settings are 64, so the only change is that for CFG_TUD_CDC_RX_BUFSIZE).
[cutecom...
UPDATE - I have found what it is in my code that is causing the failure in 0.20.0 --> setting CFG_TUD_CDC_RX_BUFSIZE=32.
(I have CFG_TUD_ENDPOINT0_SIZE=64, CFG_TUD_CDC_TX_BUFSIZE=64 and CFG_TUD_CDC_EP_BUFSIZE=64).
Yeah I took a look at new stream transfer functions and found that it assumes FS bulk endpoint size (MPS) is 64 bytes, it refuse to launch transfer if the FIFO is smaller than MPS.
Should be fixed by #3396
Woohoo another bug squashed. Glad to be of service :o)
If you are tidying up code, to help reduce noise in the source code the following line could be removed from "cdc_device.c" ~line 46 as it doesn't seem to be explicitly used, and is in effect duplicated by settings in "tusb_config.h."
#define BULK_PACKET_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
Hi, think you, I think HP Micro use Chipidea HS controller, could you add the port to /src/portable/chipidea/ci_hs instead of creating a new ?
[hathach/tinyusb] New branch created: size-reduce
Describe the PR
A clear and concise description of what this PR solve.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Merge metrics using truncated filenames
Bloaty compile units are recorded with file set to os.path.basename(unit_path), but compute_avg later groups entries solely by f["file"]. When two different objects share the same basename (e.g., usb.c in multiple port directories), their sizes and symbols are merged and averaged together, yielding incorrect totals and hiding regressions for any duplicat...
Pull request overview
This PR refactors the code metrics system to use Google's bloaty tool instead of the linkermap library for analyzing code size. It also introduces optimizations for reducing code size through conditional compilation of FIFO-related code when vendor class buffers are zero-sized, and consolidates compiler attribute definitions.
Key Changes
- Replace linkermap-based metrics with bloaty CSV parsing in tools/metrics.py
- Add CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED to co...
[nitpick] Changing from include guards to #pragma once is generally fine, but #pragma once is not part of the C standard (though widely supported). The original include guards were more portable. If this codebase needs to support very old or non-standard compilers, this could be problematic. Consider verifying that all target compilers support #pragma once.
The condition CFG_TUD_VENDOR_TX_BUFSIZE == 0 || CFG_TUD_VENDOR_RX_BUFSIZE == 0 will enable CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED if either buffer size is zero. However, this might not be the intended behavior - if only TX is zero but RX is non-zero, should no-FIFO mode be enabled for both? Consider whether this should be && instead of ||, or whether separate TX/RX flags are needed.
#if CFG_TUD_ENABLED && CFG_TUD_VENDOR && (CFG_TUD_VENDOR_TX_BUFSIZE == 0 && CFG_TUD_VENDO...
Potential division by zero when totals_list is empty. If all data entries lack a valid TOTAL, the fallback calculation sum(f["size"] for f in files_average) or 1 uses or 1 to avoid division by zero, but this creates a misleading total of 1 when all files have zero size. Consider raising an error or returning a more meaningful value instead.
if totals_list:
total_size = round(sum(totals_list) / len(totals_list))
else:
sum_sizes = sum(f["size"] for f ...
[nitpick] The (void)hwid; statement on line 505 is only needed when CFG_TUSB_EDPT_STREAM_NO_FIFO_ENABLED is 0. When it's 1, the non-fifo branch uses hwid. Consider moving this to the beginning of the function with a proper guard or restructuring the conditional compilation to avoid the unused parameter warning more cleanly.
{
// In FIFO mode, hwid is unused
[nitpick] The commented-out post-build command (lines 247-250) suggests there was an intention to generate CSV output automatically but this was disabled. Consider either removing the commented code if it's not needed, or documenting why it's disabled if future enablement is planned.
[nitpick] The refactored overflow count calculation using int32_t intermediate cast is clearer and avoids potential unsigned underflow issues. However, ensure that wr_idx and rd_idx are always within the valid range for int32_t conversion. If these can exceed INT32_MAX, the cast could cause undefined behavior. Given they're uint16_t, this should be safe, but consider adding a comment explaining this constraint.
The fallback calculation on line 339 recomputes the total from files when json_data.get("TOTAL") is missing, but this differs from the averaging logic in compute_avg. In compute_avg, when totals_list is empty, it also falls back to summing file sizes. However, the or 1 on line 207 could cause total_size to be 1 instead of the actual sum, leading to incorrect percentage calculations. Consider ensuring consistency between these two code paths.
total_size = json_dat...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| tusb.c | 616 ➙ 532 (-84) | 524 ➙ 453 (-71) | 3 | 617 ➙ 533 (-84) | -13.6% |
| TOTAL | 616... |
If one sends data of exactly the length of bulk_mps, is_complete is errorneously not set. Therefore, the referenced line
https://github.com/hathach/tinyusb/blob/e9cd4d823fe4cd7de03587c57fc8288ad5711b15/src/class/mtp/mtp_device.c#L428
should be:
p_mtp->xferred_len >= p_mtp->total_len) // total length reached
{
This happens, e.g. when replying to a GetHandles request with 12 elements (and low speed). This gives exactly 64 bytes, they are sent, but is_complete is ne...
Thanks for assigning this issue to me. I'm starting to work on it and will keep this PR's description up to date as I form a plan and make progress.
Original prompt
This section details on the original issue you should resolve
MTP bug in mtp_device.c : mtpd_xfer_cb (including fix!)
If one sends data of exactly the length of bulk_mps, is_complete is errorneously not set. Therefore, the referenced line
https://github.com/hathach/tinyusb/blob/e9cd4d823fe4cd7de03...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| mtp_device.c | 1621 ➙ 1622 (+1) | 2... |
[hathach/tinyusb] New branch created: more-size-reduce-edpt-stream
Describe the PR
A clear and concise description of what this PR solve.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| vendor_device.c | 697 ➙ 674 (-23) | 590 ➙ 566 (-24) | 477 | 1173 ➙ 115... |
Hi, think you, I think HP Micro use Chipidea HS controller, could you add the port to
/src/portable/chipidea/ci_hsinstead of creating a new ?
Yes, I update my port files by using Chipidea HS controller to support HPMicro chips. Thank you!
Describe the PR
When CFG_TUD_VENDOR_TX_BUFSIZE set to 0. User should write ZLP by themselves. But there is no way to write ZLP. This check point not supports ZLP. I think expose tu_edpt_stream_write_zlp_if_needed is a good way.
Additional context
If applicable, add any other context about the PR and/or screenshots here.
The users can write ZLP like this:
void tud_vendor_tx_cb(uint8_t itf, uint32_t sent_bytes) {
// other logic...
if(sendFinished){
tud_vendor_write_zlp_if_needed(sent_bytes);
}
}
perfect, thank you. Though I revert the changes with ifdef guard for usbd_xfer_fifo() since it save a bit of flash. Why would it cause the audio issue with logging though, without the CFG_TUD_EDPT_DEDICATED_HWFIFO, the function would return false anyway ?
Hmm, seems like we have cdc echo issue with musb and rusb2 which just set the CFG_TUD_EDPT_DEDICATED_HWFIFO. @HiFiPhile did you test with these port, I guess we may miss a thing or two for them to work properly ?
Though I revert the changes with ifdef guard for usbd_xfer_fifo() since it save a bit of flash. Why would it cause the audio issue with logging though, without the CFG_TUD_EDPT_DEDICATED_HWFIFO, the function would return false anyway ?
It's fine to revert now, audio_device used different test condition for FIFO transfer, resulting usbd_edpt_xfer_fifo is called when CFG_TUD_EDPT_DEDICATED_HWFIFO=0 but failed silently without assert or breakpoint.
seems like we have cdc echo issu...
It's fine to revert now, audio_device used different test condition for FIFO transfer, resulting
usbd_edpt_xfer_fifois called whenCFG_TUD_EDPT_DEDICATED_HWFIFO=0but failed silently without assert or breakpoint.
ok, I will refactor usbd_xfer and usbd xfer_fifo later. Let revert this for now.
seems like we have cdc echo issue with musb and rusb2
msub needs #3017, maybe rusb2 has the same access limitation ? I don't have board to test with.
right, I guess we need mor...
Thank you, could you remove extra spaces ?
maybe we should update the write() to allow zlp instead, let me check that option first.
@hathach Thank you very much for the quick merge! 👍 ❤️
Describe the PR
This PR adds support for the NXP RW61x wireless MCU family.
The RW612 utilizes the ChipIdea High-Speed USB IP, which is architecturally compatible with the NXP MCX N9 series.
Additional context
This is related to discussion #3392.
It seems that the host instance should be initialized with role TUSB_ROLE_HOST.
I have not, however, tested this and might be wrong about that. Feel free to just close this PR if this is incorrect.
I think we need to verify if stream is opened before operation, the check is removed after cdc & vendor refactor. Fix #3395
diff --git a/src/class/cdc/cdc_device.c b/src/class/cdc/cdc_device.c
index d7792afe4..d8e636f38 100644
--- a/src/class/cdc/cdc_device.c
+++ b/src/class/cdc/cdc_device.c
@@ -43,7 +43,6 @@
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//----------------------------------------------------------------...
@HiFiPhile thank right, the idea to drop the check for cdc is to allow it to write/read from fifo even if device is not connected. Eg. some device print out boot message before enumerated. I think we should add the check to _xfer() only. Not sure if midi need this "feature", currently it skip if not connected.
@HiFiPhile thank right, the idea to drop the check for cdc is to allow it to write/read from fifo even if device is not connected. Eg. some device print out boot message before enumerated. I think we should add the check to _xfer() only. Not sure if midi need this "feature", currently it skip if not connected.
In fact it's enough to put the check in fewer places while allowing fifo access. I think skip midi write is good, for midi read is less needed.
diff --git a/src/class/cdc...
@HiFiPhile perfect, I apply your suggetion fix in the push as well.
i will look into it
many apologies, meant to open a PR against our forked repo, not the main repo :disappointed:
Although, I've found it useful to have the write method return the number of bytes physically flushed, not just written to the internal CDC buffer. If anyone thinks it's worthwhile, I can try adding this feature as a new method and try opening another PR
[hathach/tinyusb] New branch created: rusb2_fifo_fix
Found a RA4M2-EK from no where, turns out compatible with ra4m3_ek...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .bss | size | % diff |
|---|---|---|---|---|
| dcd_rusb2.c | 2966 ➙ 3076 (+110) | 156 | 3122 ➙ 3232 (+110) | +3.5% |
| TOTAL | 2966 ➙ 3076 (+110) ... |
Remove this line should be OK?
https://github.com/hathach/tinyusb/blob/64820791516b4001cb169f095588ccb52eb35ea8/src/tusb.c#L453
Will this affect other logic?
I tried this method. It works fine.
void tud_vendor_tx_cb(uint8_t itf, uint32_t sent_bytes) {
// other logic...
if(sendFinished){
if(sent_bytes&&(sent_bytes%MAX_PACKET_SIZE)==0){
tud_vendor_write(NULL,0);
}
}
}
Or we can only check buffer length when FIFO enabled.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Correct MCU list name to match HPM family
FAMILY_MCUS is set to HPMIRCO instead of the actual HPM identifier, so CMake’s family_filter logic will iterate over the wrong MCU name. Any mcu:HPM entries in skip/only.txt (or other MCU-specific handling) will be ignored, causing unsupported HPM builds to be attempted rather than filtered out. Please rename the entry to the real HPM MCU token so filtering ...
@hathach could you pick this before 0.20.1 tag?
[hathach/tinyusb] New branch created: cdch_typo
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
[hathach/tinyusb] New branch created: hcd_ip3516
@tannewt https://github.com/hathach/tinyusb/pull/3402 fine tune to reduce the tinyusb foot print. I also add the code metrics which basically sum average all boards/examples for each .c file. The metrics make it easier to follow the code size and make fine tuning later on.
make BOARD=arduino_zero V=1 TRANSLATION=ru all
QSTR not updated
Module registrations not updated
Root pointer registrations not updated
Memory region Used Size Region Size %age Used
FLASH_BOOTLOADER...
There's a video here of me using this fix, along with MIDI And Vendor connections.
https://youtu.be/GtFvweOVEOg
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| audio_device.c | 2803 ➙ 2859 (+56) | 1228 ➙ 1250 (+22) | 1689 | 4... |
great, I kind of guess why we have issue with fifo read, that force us to do byte read previously and skip 32-bit access for highspeed Though I don't really remember it, will test it out later on.
No I don't think that would be a good idea, application usually check if (count == write(count) and if the flushed bytes are less than what is written e.g write(128) and only flush 64, it will cause user confusion thinking that fifo is full.
[hathach/tinyusb] New branch created: metrics-on-release
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Pin checkout to a published major version
build.yml now uses actions/checkout@v6, but the checkout action only publishes up to v4 today. GitHub will abort the workflow with “Unable to resolve action ‘actions/checkout@v6’” before any steps run, and the same change in the other workflows in this commit will similarly block those jobs until the checkout version is pinned to an existing release.
Useful...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
Pull request overview
This PR enhances the build workflow to automatically upload code metrics and comparison reports to GitHub releases. It adds a release event trigger, downloads metrics from the previous release for comparison, and uploads both metrics.json and a comparison markdown file to the current release page. Additionally, it updates all actions/checkout references from v4 to v6 across multiple workflow files.
Key Changes
- Adds release event trigger and upload functi...
The fetch-tags parameter may not be supported in actions/checkout v4. This parameter name appears to be non-standard. The standard parameter name is 'fetch-depth' to control cloning depth. If you need to fetch tags, you typically set fetch-depth to 0 or use a separate git command to fetch tags. Please verify this parameter name is correct for the version of actions/checkout being used.
fetch-depth: ${{ github.event_name == 'release' && '0' || '1' }}
The variable expansion here is missing curly braces. It should be ${{ github.event.release.tag_name }} (with the ${{ }} wrapper around it). Without the proper GitHub Actions expression syntax, this will be treated as a literal string rather than a variable substitution.
The git tag command may fail if there are fewer than 2 tags in the repository, or if tags have not been fetched. Consider adding error handling to check if PREV_TAG is empty before using it in subsequent commands, especially since the checkout step only fetches tags conditionally.
if [ -z "$PREV_TAG" ]; then
echo "No previous tag found. Skipping previous release asset download."
echo "PREV_TAG=" >> $GITHUB_ENV
else
echo "Pr...
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.
Original prompt
udpate build.yml to and metrics-comment.yml so that it ccould post PR comment on forked PR. Currently it does works
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](ht...
TinyUSB Average Code Size Metrics
| File | .text | .rodata | .data | .bss | size | % |
|---|---|---|---|---|---|---|
| ehci.c | 2651 | 0 | 0 | 5970 | 8622 | 72.3% |
| cdc_host.c | 6614 | 487 | 15 | 1624 | 8422 | 70.6% |
| ncm_device.c | 1503 | 28 | 1408 | 5961 | 7478 | 62.7% |
| hcd_dwc2.c | 4898 | 32 | 0 | 512 | 5442 | 45.6% |
| usbh.c ... |
@copilot the metrics.md (wihtout compare posted on the comment) has the % column incorrect, try to fix that metrics.py percent should be re-computed after input file is combined. # TinyUSB Average Code Size Metrics
| File | .text | .rodata | .data | .bss | size | % |
|---|---|---|---|---|---|---|
| ehci.c | 2651 | 0 | 0 | 5970 | 8622 | 72.3% |
| cdc_host.c | 6614 | 487 | 15 | 1624 | 8... |
@copilot the metrics.md (wihtout compare posted on the comment) has the % column incorrect, try to fix that metrics.py percent should be re-computed after input file is combined. # TinyUSB Average Cod...
Recomputed metrics totals after combining inputs so the percent column is derived from the merged data (9efa15b).
@copilot TOTAL'size column is still incorrect TOTAL 109863 1154 16524 46006 11926, the .text column alone is larger than the size 109863 > 11926
@copilot TOTAL'size column is still incorrect TOTAL 109863 1154 16524 46006 11926, the .text column alone is larger than the size 109863 > 11926
Total size now derives from summed section totals, so the TOTAL row aligns with the .text/.rodata/.data/.bss columns (281a787).
@copilot revert changes to metrics.py, and rebase from base
@copilot revert changes to metrics.py, and rebase from base
Reverted metrics.py back to the base version as requested (708c4ae).
I think we use this to write more data to the tx fifo when doing multiple packets ?
PS: sorry, I forgot, set means complete empty, while default is half-empty. What if we have 2 endpoint 1 is doubles, 1 is single. And half-empty is trigger on the single while we cannot write a full packet to its fifo. I forgot that if the interrupt trigger again when it is fully empty ? or it keeps interrupting until data is written (until transfer complete)
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| cdc_host.... |
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| tusb.c | 416 ➙ 422 (+6) | 361 ➙ 363 (+2) | 3 | 418 ➙ 423 (+5) | +1.2% |
| TOTAL | 416 ➙ 422 (+... |
And half-empty is trigger on the single while we cannot write a full packet to its fifo.
I think it can't happen. The controller will read one whole packet each time so the fifo level will drop from 64 directly to 0. STM32Cube leave it by default.
perfect, thank you very much
@hathach looking from HIL test the fix is good. musb has another zlp stuck transfer issue https://github.com/hathach/tinyusb/discussions/3362
[hathach/tinyusb] New branch created: stream_write
Thank you! I will test it on my board on Monday.
Move TU_VERIFY(bufsize > 0); to fifo mode to allow sending ZLP.
TU_VERIFY(s->ep_buf != NULL, 0); is needed like as we don't know if the data is on stack or not.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
Decided to do the bsp aswell.
The host examples seem to work as far as i can tell, only the msc_file_explorer one failed to mount on the devices i had here and im not really sure if its a device or host problem.
For the device side the cdc_msc and cdc_msc_freertos also seemed to work fine.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| dfu_device.c | 741 ➙ 766 (+25... |
tested on my h563 nucleo and it works perfectly. Thank you very much for this brilliant work
yeah, probably a typo in the AN
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| usbh.c | 4286 ➙ 4329 (+43) | 60 | 60 | ... |
prefect, thank you, every changes make sense.
do we really need this, both init() and de-init() is called by application, they should call them before/after those accordingly ?
It's for host/device specific init, like STM32's GCCFG and GOTGCTL register, which need to be set to different value on host/device. Their meaning is also different across families, I haven't found a easy way to include them in the driver.
For anyone wanting to build the example cdc_dualports out of the box for an stm32f103 bluepill board, this is what I had to do.
unzip your copy of tinyusb "tinyusb.zip" into a folder... I used "/whatever"
cd /whatever/tinyusb-0.20.0/examples/device/cdc_dual_ports
make -C . BOARD=stm32f103_bluepill get-deps
make -C . BOARD=stm32f103_bluepill all
The resulting .bin or .hex files are then in the subfolder "_build/stm32f103_bluepill/"
Operating System
Windows 10
Commit SHA
1
Board
STM32F103 Bluepill
Firmware
I'm not having much luck in getting my custom CDC_ACM device to be recognised by Win10 Pro 2009 Build 19045.5737.
Device manager generally says Get Device Descriptor failed, status 0xC000009C, Problem 0xA.
So I tried the CDC ACMM dual port example and it too won't load under Win 10.
What happened ?
The device works perfectly in Ubuntu 25.10, but Win10 refuses to load it.
Just in case it ...
Well that's weird, I mostly work on Windows 10 22H2 and never met this issue with daily cdc_dual_ports build on different MCUs.
I have resloved the doc conflicts, please review again, thank you!
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
@hathach It's for host/device specific init, like STM32's GCCFG and GOTGCTL register, which need to be set to different value on host/device. Their meaning is also different across families, I haven't found a easy way to include them in the driver.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| cdc_device.c | 1332 ➙ 1330 (-2) | ... |
Operating System
Linux
Commit SHA
3a0
Board
MSPM0G5187
Firmware
NA
What happened ?
While using DFU via TinyUSB on an MUSB-based controller, DFU_UPLOAD intermittently fails after one successful upload. The failure occurs specifically when the host issues a DFU_GETSTATUS request immediately after a DFU_UPLOAD transfer.
This results in:
• Device no longer responding to GETSTATUS
• DFU state machine getting stuck
• Subsequent DFU operations failing until reset
H...
Hi, I'm a little confused about the cause. Both DFU Upload and GetStatus are control IN transfers just like get descriptors, unless there is a racing condition which makes one work but not another.
• _dcd.status_out is still set
• A new valid SETUP packet is already present
• The driver incorrectly interprets the new SETUP as STATUS handling and drops it
Setup packet is received in dcd_int_handler() -> process_ep0() -> process_setup_packet, the device is always ready to receive Setu...
I don't have MSPM0G5187 and it is not one supported MCUs. Can you confirm the issue also occur with tm4c123. For the issue detail: please update 1st post with
- complete commit hash
- firmware: we will need an example that run on mcu, I guess you are runing dfu examples, if you have modification, please provide the minial example that could cause the issue.
- "how to reproduce": which specific command or testing to trigger the issue
there is no such commit hash "esp-idf v5.5.0", also please provide which examples you are testing with.
Hi, sorry for the delay getting back. I couldn't remember which device I was having trouble connecting to. I think my idea was to make a mini dumb terminal to connect to one of my vintage computer replicas. They're currently in storage, so I'll grab them next time I go there and test it out.
[hathach/tinyusb] New branch created: remove-sprintf
Pull request overview
This PR removes the usage of snprintf in the tu_lookup_find function by replacing dynamic hex formatting of unknown keys with a static "NotFound" string. This change simplifies the code and eliminates a thread-safety issue caused by returning a pointer to a static buffer.
Key changes:
- Removes
snprintfcall that formatted unknown keys as hex strings (e.g., "0x00000005") - Returns a constant "NotFound" string instead of a dynamically formatted value
- Eliminat...
Replacing the hex-formatted key value with "NotFound" results in loss of important debugging information. When a lookup fails, developers previously could see the actual key value (e.g., "0x00000005") to help debug why the lookup failed. Now they will only see "NotFound" which provides no information about what key was being looked for. Consider passing the key value to the logging caller so the diagnostic value can be preserved, or provide an alternative mechanism to log unknown keys.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
[hathach/tinyusb] New branch created: fix-imxrt-1011-bsp
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@code...
<sub><sub></sub></sub> Preserve XIP boot header symbols during link
The -Wl,-uimage_vector_table and -Wl,-ug_boot_data link options were removed here, but the imxrt toolchain uses --gc-sections (see examples/build_system/cmake/toolchain/common.cmake:35), and fsl_flexspi_nor_boot.c defines those boot header symbols without any references. Without the -u keeps, the linker can garbage-collect the boot header, so XIP ...
Pull request overview
This PR adds DCache enablement support for i.MX RT boards, particularly the RT1011, and refactors the build configuration to use __START=main instead of a custom _start() implementation.
- Enables DCache early in board initialization for boards that don't configure it via MPU setup
- Replaces custom
_start()function with standard__START=maincompiler define - Moves
fsl_flexspi_nor_boot.cfrom board library to example targets in CMake build
Reviewed ...
The comment should start with a capital letter and end with a period for consistency with the codebase style. Additionally, consider being more specific about why DCache enablement is needed.
// Ensure the data cache is enabled before board initialization for consistent performance.
The DCache is being enabled before BOARD_ConfigMPU() is called. This ordering may cause issues:
-
Some boards (like mimxrt1170_evkb) disable DCache at the start of BOARD_ConfigMPU(), reconfigure the MPU, then re-enable DCache. For these boards, the early enablement here is redundant.
-
For boards with empty BOARD_ConfigMPU(), enabling DCache before proper MPU configuration might work but goes against the recommended initialization sequence shown in boards like mimxrt1170_evkb.
Consider m...
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
Describe the PR
I have run into an edge cast where the host application abruptly stops while there is data still within the vendor output buffer. I need to be able to manually clear this buffer after the application is restarted. This doesn't seem to be a perfect solution as there is still data in the endpoint buffer when the application starts reading. Please let me know if there is any way to fully solve this problem.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| vendor_device.c | 609 ➙ 633 (+24) | 514 ➙ 534 (+20) | 476 | 1083 ➙ 110... |
Hi, why did you modify tusb_fifo and tusb_private which are unnecessary?
I was unsure if it was possible for the fifo to be changed after the count was retrieved, so I had the count retrieval inside the ff_lock() block. I removed that and use tu_edpt_stream_read_available() instead.
Could you just replicate cdc ? Since the data will be cleared the count won't worth much ? Anyway there are could be some data already been loaded into endpoint buffer.
Describe the PR
This PR introduces an OSAL header implementation for ThreadX (https://threadx.io/) and includes corresponding documentation updates.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
tud_cdc_wait_for_zlp(bool)
Any plans on this? On Windows C# App it is not possible to send ZLP packet.
Help needed on the TinyUSB side.
Any plans on this? On Windows C# App it is not possible to send ZLP packet. Help needed on the TinyUSB side.
tud_cdc_wait_for_zlp(bool)
Just set CFG_TUD_CDC_EP_BUFSIZE=64
Hi, could you either fill missing implementations or adding a note about why are they missing ?
[hathach/tinyusb] New branch created: fifo_read_epsize
Describe the PR
I've added if (s->ep_buf != NULL) { during the fixup but it will break receiving behavior when the host can't send ZLP. With this if added settingCFG_TUD_CDC_EP_BUFSIZE will no longer have effect on devices using HWFIFO.
Related to #2287
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
| file | .text | .data | .bss | size | % diff |
|---|---|---|---|---|---|
| tusb.c | 420 ➙ 418 (-2) | 361 ➙ 360 (-1) | 3 | 421 ➙ 420 (-... |
Operating System
Windows 11
Commit SHA
from eed294f to master
Board
ch32v307v_r1_1v0
Firmware
Test code examples/device/audio_test
Caused commit https://github.com/hathach/tinyusb/commit/eed294fbb58257f56b0fb59284624e50f43fa8a4
What happened ?
The audio was intermittently set to near 0.
This wasn't just limited to the mic test; the same applied to the speaker.
This issue persists e...
I'm not familiar with ch32, if you can find the issue please let me know.
Good point. I will do.
Operating System
Linux
Commit SHA
ALL
Board
STM32N6
Firmware
tinyusb/src/portable/synopsys/dwc2/dwc2_stm32.h
What happened ?
When I tried to open DMA, this error occurred. The specific code is:
static mem_region_t uncached_regions[] = {
// DTCM (although USB DMA can't transfer to/from DTCM)
#if CFG_TUSB_MCU == OPT_MCU_STM32H7
{.start = 0x20000000, .end = 0x2001FFFF},
#elif CFG_TUSB_MCU == OPT_MCU_STM32H7RS
// DTCM (although USB DMA can't transfer to/f...
I don't have stm32n6 board, you are welcomed to open a PR.
Operating System
Others
Commit SHA
f6a77b87f04386ea27effb7c1faf8e1a33da0fa1
Board
RP2040
Firmware
based on examples/device/mtp/ , nothing special in fact
What happened ?
Some two weeks or so ago, I posted #3400 including a fix which was based on my lack of understanding how USB transfers work. The problem I was observing, that the condition setting is_complete=true in mtpd_xfer_cb() would never be met a case where I sent 64 bytes of mtp payload, leading to a...
Describe the PR
A couple of very simple fixes for compilation errors/warnings I got after upgrading my project to tinyusb 0.20.0 release
It's on purpose that stdio.h is only included when there is no custom printer defined.
Not all H7 devices are dual-core, in which case CORE_CM4/CORE_CM7 are not defined
Oh I see, the miscompiling code has been removed after v0.20.0 in 7f4a761 - I will drop this commit.
Hmm. ok.
So would it be ok to just write:
#ifndef CORE_CM4
// Enable dcache if DMA is enabled
#define CFG_TUD_MEM_DCACHE_ENABLE_DEFAULT CFG_TUD_DWC2_DMA_ENABLE
#define CFG_TUH_MEM_DCACHE_ENABLE_DEFAULT CFG_TUH_DWC2_DMA_ENABLE
#define CFG_TUSB_MEM_DCACHE_LINE_SIZE_DEFAULT 32
#endif
I think #ifndef CORE_CM4 is ok.
These new function variants allows the main application loop to limit how much time is spend on these functions, to ensure that other critical code can run fast enough.
Describe the PR
An application main loop (without os) that usually tinyusb host and device stack look like:
while(1) { // the mainloop
application_code();
tud_task(); // tinyusb device task
tuh_task(); // tinyusb host task
}
Unfortunately, without patching, tud_t...
I will close this PR and create a new one, I'm no GIT expert...
I think this is just a poor man's solution, the number of events per cycle is not directly proportional to how long tud_task will run.
For your MSC case the long latency is due to disk IO in blocked callback functions. The right way is using RTOS + non-blocking asynconous IO like cdc_msc_freertos example.
I think this is just a poor man's solution, the number of events per cycle is not directly proportional to how long tud_task will run.
It might be a poor man's solution, but it still is a solution to a real problem.
For your MSC case the long latency is due to disk IO in blocked callback functions. The right way is using RTOS + non-blocking asynconous IO like cdc_msc_freertos example.
Well, in my c...
Describe the PR
A couple of very simple fixes for compilation errors/warnings I got after upgrading my project to tinyusb 0.20.0 release
This replaces PR #3431 and adresses HiFiPhile comments.
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
No entries.
<details><summary>No changes</summary>
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| audio_device.c... |
Size Difference Report
Because TinyUSB code size varies by port and configuration, the metrics below represent the averaged totals across all example builds.
Note: If there is no change, only one value is shown.
Changes >1% in size
No entries.
Changes <1% in size
| file | .text | .rodata | .data | .bss | size | % diff |
|---|---|---|---|---|---|---|
| usbd.c | 3155 ➙ 3187 (+32) | ... |
Operating System
MacOS
Commit SHA
3af1bec
Board
Custom STM32H747 board
Firmware
Custom firmware
What happened ?
When debugging my firmware (which uses tinyusb) by stopping on breakpoints on doing step-by-step, I will very quickly end up in the TU_LOG_USBD("FAILED\r\n"); TU_BREAKPOINT(); code at the end of usbd_edpt_xfer() and it's impossible to continue/recover.
What I believe is happening is that:
- the host detects that the device is "stuck" (because of d...
What you mean it's can't be continued ? You just need to step over the breakpoint https://github.com/hathach/tinyusb/blob/3eafddb02a3347873dc1816f53b428518eb97c61/src/common/tusb_verify.h#L79
What you mean it's can't be continued ? You just need to step over the breakpoint
Well, I'm using the STM32CubeIDE and if I just stay on this line (step over, step into, continue) nothing work.
I might be doing something wrong, but no idea what.
Is it safe to just remove the TU_BREAKPOINT(); line or will the stack run into other issues in this scenario?
What you mean it's can't be continued ? You just need to step over the breakpoint
Well, I'm using the STM32CubeIDE and I just stay on this line (step over, step into, continue) nothing work. I might be doing something wrong, but no idea what.
Well that's strange, what about changing breakpoint number in the assembly macro?
What you mean it's can't be continued ? You just need to step over the breakpoint
Well, I'm using the STM32CubeIDE and I just stay on this line (step over, step into, continue) nothing work. I might be doing something wrong, but no idea what.
Well that's strange, what about changing breakpoint number in the assembly macro?
I tried with { __asm("BKPT #1\n"); } no difference. Once I reach this opcode, I cannot go further.
You can remove TU_BREAKPOINT();
Ok, I wil...
I was curious enough to launch STM32CubeIDE....
Turns out once again a ST's issue, you have to either use J-Link or OpenOCD:
<img width="446" height="147" alt="Image" src="https://github.com/user-attachments/assets/c03b6eff-9510-4d43-a1d4-4dd0e60b65ef" />
You may contact me by mail.
Operating System
Linux
Commit SHA
Release V0.20
Board
STM32N647
Firmware
tinyusb/src/portable/synopsys/dwc2/dwc2_common.c
tinyusb/src/portable/synopsys/dwc2/dwc2_stm32.h
What happened ?
I attempted to use the STM32N647 development board to implement the Device mode USB-CDC. However, when I used the following macros, the USB-OTG peripheral of the STM32N647 could not function properly.
#ifndef TUSB_CONFIG_H_
#define TUSB_CONFIG_H_
#ifdef __cplusplus
extern "C...
Please test with stock example, N657 is supported : https://github.com/hathach/tinyusb/pull/3226
Also you have speed wrong:
#ifndef BOARD_TUD_MAX_SPEED
#define BOARD_TUD_MAX_SPEED OPT_MODE_FULL_SPEED
#endif
Operating System
Linux
Commit SHA
3af1bec
Board
Custom stm32h747 board
Firmware
Custom stm32h747 board, but the problematic code is very similar to net_lwip_webserver with NCM config.
Alpine Linux 3.23 on the host side.
What happened ?
When the system run for the first time, everything is fine.
Configuration:
#define CFG_TUD_NCM_IN_NTB_N 2
#define CFG_TUD_NCM_IN_NTB_MAX_SIZE 2048
#define CFG_TUD_NCM_OUT_NTB_N 2
#define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 2048
...
[hathach/tinyusb] New branch created: mtp_zlp
I've took a look and it's more complicated, both IN & OUT need zlp handling.
You can try: https://github.com/hathach/tinyusb/tree/mtp_zlp
I am using HS USB and set CFG_TUD_CDC_EP_BUFSIZE to 512. And it solves my problem. Will discuss your PR #3424 with my colleague.
Any plans on this? On Windows C# App it is not possible to send ZLP packet. Help needed on the TinyUSB side.
tud_cdc_wait_for_zlp(bool)
Just set CFG_TUD_CDC_EP_BUFSIZE=64
Since I am using HS USB, i set CFG_TUD_CDC_EP_BUFSIZE to 512. And it solves my problem. Will discuss your PR #3424 with my colleague later on.