Skip to content

fix(third_party/bluetooth): fix bugs in USB host BT HCI drivers#411

Merged
sakumisu merged 1 commit intocherry-embedded:masterfrom
shchen-Lab:master
Apr 21, 2026
Merged

fix(third_party/bluetooth): fix bugs in USB host BT HCI drivers#411
sakumisu merged 1 commit intocherry-embedded:masterfrom
shchen-Lab:master

Conversation

@shchen-Lab
Copy link
Copy Markdown
Contributor

@shchen-Lab shchen-Lab commented Apr 17, 2026

NimBLE (nimble-1.6.0/ble_hci_usbh.c):

  • fix hci_read_callback: pass full buffer to hci_h4_sm_rx in one call instead of splitting type byte and payload into two calls
  • fix ble_transport_to_ll_cmd_impl: use struct ble_hci_cmd for type-safe length calculation instead of raw byte indexing
  • fix ble_transport_to_ll_acl_impl: gather mbuf with os_mbuf_copydata and issue single usbh_bluetooth_hci_write; the old per-segment loop violated USB Bluetooth class bulk transfer requirements
  • fix unused-parameter warnings in run/stop callbacks

Zephyr (zephyr_bluetooth-2.7.5/ble_hci_usbh.c):

  • remove unreachable fallthrough comment after return statement
  • restore ISO payload length check (was commented out); use inline mask (& 0x3FFF) per BT Core Spec v5.x Vol 4 Part E Section 5.4.5
  • fix bt_usbh_send error code: 255 -> -EIO
  • guard bt_hci_driver_register with static bool to prevent duplicate registration on USB reconnect
  • fix unused-parameter warnings in run/stop callbacks

Summary by CodeRabbit

  • Bug Fixes

    • Restored strict ISO payload-length validation and improved error reporting for malformed packets.
    • Standardized error return values and normalized error handling to avoid misleading statuses.
    • Prevented duplicate driver registration and ensured safe start/stop behavior for USB Bluetooth.
  • Performance

    • Reduced runtime copying and streamlined packet processing to improve USB Bluetooth throughput and efficiency.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 17, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d56a658a-6167-4188-9418-a8f7b1f527c6

📥 Commits

Reviewing files that changed from the base of the PR and between c3203ee and 29e1f21.

📒 Files selected for processing (2)
  • third_party/nimble-1.6.0/ble_hci_usbh.c
  • third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c
🚧 Files skipped from review as they are similar to previous changes (2)
  • third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c
  • third_party/nimble-1.6.0/ble_hci_usbh.c

📝 Walkthrough

Walkthrough

Adjusted USB-host Bluetooth HCI transport code in NimBLE and Zephyr trees: forwarding raw HCI buffers to H4 state machine, refactoring command/ACL handling to typed structures and consolidated buffers, re-enabled ISO payload-length validation, improved error returns, and added guards/casts to avoid warnings.

Changes

Cohort / File(s) Summary
NimBLE HCI Transport
third_party/nimble-1.6.0/ble_hci_usbh.c
Added nimble/hci_common.h include. RX callback now forwards the received buffer directly to hci_h4_sm_rx() (casts len to uint16_t). Command packets use struct ble_hci_cmd * to compute pkt_len. ACL handling copies full mbuf contents into a single stack buffer sized from BLE_HCI_DATA_HDR_SZ + BLE_TRANSPORT_ACL_SIZE, frees on oversize, normalizes negative write results to BLE_ERR_MEM_CAPACITY, and returns 0 on success. Explicit (void)bluetooth_class casts added.
Zephyr Bluetooth ISO and HCI
third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c
Re-enabled ISO payload-length validation comparing remaining to sys_le16_to_cpu(hdr.len) & 0x3FFF, returning NULL on mismatch. On write failure, bt_usbh_send() returns -EIO instead of 255. Added static bool s_registered guard to ensure single bt_hci_driver_register() and RX thread creation; explicit (void)bluetooth_class casts. Removed a standalone /* fallthrough */ comment.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 Hopping through packets, tidy and bright,
I stitch raw buffers into HCI light.
ISO checks guard the rhythmic beat,
Typed structs and fewer bytes to treat.
A joyful nibble — code neat and light.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(third_party/bluetooth): fix bugs in USB host BT HCI drivers' directly and clearly summarizes the main change—fixing bugs in USB Bluetooth HCI drivers across two third-party libraries (NimBLE and Zephyr).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@shchen-Lab
Copy link
Copy Markdown
Contributor Author

@sakumisu This CI failure is not related to my PR (c3203ee). It's a pre-existing issue in port/hpmicro/usb_dc_hpm.c:

#error "Please use SDK version 1.12.0 or later because of USB api modification"

The HPM SDK version used in the CI environment is older than 1.12.0, so usb_dcd_set_sutw() and usb_dcd_get_sutw() are unavailable.
This file was already on master before my changes. Could someone update the HPM SDK version in the CI workflow, or skip this build
target until the SDK is updated?

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c (1)

314-332: ⚠️ Potential issue | 🟠 Major

Thread creation is still unguarded on reconnect.

s_registered guards only bt_hci_driver_register, but the usb_osal_thread_create calls below run every time usbh_bluetooth_run is invoked. On a USB reconnect you'll spawn additional ble_rx / ble_evt / ble_acl threads — a resource leak that will cause duplicate RX dispatch.

The threads do have exit paths (they detect USB_ERR_SHUTDOWN from the USB core and call usb_osal_thread_delete), so they won't accumulate indefinitely. However, there is still a window where multiple thread instances coexist, particularly if the device reconnects faster than the old threads exit.

Extend the s_registered guard to cover thread creation:

🛡️ Minimal fix: extend the one-shot guard to cover thread creation
 void usbh_bluetooth_run(struct usbh_bluetooth *bluetooth_class)
 {
     static bool s_registered;

     (void)bluetooth_class;

     if (!s_registered) {
         bt_hci_driver_register(&usbh_drv);
-        s_registered = true;
-    }

 `#ifdef` CONFIG_USBHOST_BLUETOOTH_HCI_H4
-    usb_osal_thread_create("ble_rx", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_rx_thread, NULL);
+        usb_osal_thread_create("ble_rx", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_rx_thread, NULL);
 `#else`
-    usb_osal_thread_create("ble_evt", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_evt_rx_thread, NULL);
-    usb_osal_thread_create("ble_acl", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_acl_rx_thread, NULL);
+        usb_osal_thread_create("ble_evt", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_evt_rx_thread, NULL);
+        usb_osal_thread_create("ble_acl", 2048, CONFIG_USBHOST_PSC_PRIO + 1, usbh_bluetooth_hci_acl_rx_thread, NULL);
 `#endif`
+        s_registered = true;
+    }
     usbh_bluetooth_run_callback();
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c` around lines 314 - 332,
usbh_bluetooth_run currently only guards bt_hci_driver_register with the static
s_registered flag, but still calls usb_osal_thread_create unconditionally;
move/extend the s_registered check to also surround the usb_osal_thread_create
calls so threads (usb_osal_thread_create for usbh_bluetooth_hci_rx_thread,
usbh_bluetooth_hci_evt_rx_thread and usbh_bluetooth_hci_acl_rx_thread) are
created only once per driver registration, leaving usbh_bluetooth_run_callback()
outside if you need it always called.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@third_party/nimble-1.6.0/ble_hci_usbh.c`:
- Around line 58-68: The function ble_transport_to_ll_acl_impl currently copies
pkt_len bytes into a stack buffer without validating pkt_len; add a bounds check
that pkt_len <= sizeof(buf) before calling os_mbuf_copydata and return a
suitable error (e.g., BLE_ERR_MEM_CAPACITY) if it is too large; additionally,
replace the large stack allocation with a heap or static buffer (or a fixed
bounded buffer) when MYNEWT_VAL(BLE_TRANSPORT_ACL_SIZE) can be large to avoid
stack overflow—update references in ble_transport_to_ll_acl_impl and ensure
os_mbuf_free_chain(om) still runs on error paths.

---

Outside diff comments:
In `@third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c`:
- Around line 314-332: usbh_bluetooth_run currently only guards
bt_hci_driver_register with the static s_registered flag, but still calls
usb_osal_thread_create unconditionally; move/extend the s_registered check to
also surround the usb_osal_thread_create calls so threads
(usb_osal_thread_create for usbh_bluetooth_hci_rx_thread,
usbh_bluetooth_hci_evt_rx_thread and usbh_bluetooth_hci_acl_rx_thread) are
created only once per driver registration, leaving usbh_bluetooth_run_callback()
outside if you need it always called.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9602e4a5-4f16-4f1a-91f0-a9dcbfbe8f6a

📥 Commits

Reviewing files that changed from the base of the PR and between 3bd79e2 and c3203ee.

📒 Files selected for processing (2)
  • third_party/nimble-1.6.0/ble_hci_usbh.c
  • third_party/zephyr_bluetooth-2.7.5/ble_hci_usbh.c

Comment thread third_party/nimble-1.6.0/ble_hci_usbh.c
NimBLE (nimble-1.6.0/ble_hci_usbh.c):
- fix hci_read_callback: pass full buffer to hci_h4_sm_rx in one call
  instead of splitting type byte and payload into two calls
- fix ble_transport_to_ll_cmd_impl: use struct ble_hci_cmd for
  type-safe length calculation instead of raw byte indexing
- fix ble_transport_to_ll_acl_impl: gather mbuf with os_mbuf_copydata
  and issue single usbh_bluetooth_hci_write; the old per-segment loop
  violated USB Bluetooth class bulk transfer requirements
- fix unused-parameter warnings in run/stop callbacks

Zephyr (zephyr_bluetooth-2.7.5/ble_hci_usbh.c):
- remove unreachable fallthrough comment after return statement
- restore ISO payload length check (was commented out); use inline
  mask (& 0x3FFF) per BT Core Spec v5.x Vol 4 Part E Section 5.4.5
- fix bt_usbh_send error code: 255 -> -EIO
- guard bt_hci_driver_register with static bool to prevent duplicate
  registration on USB reconnect
- fix unused-parameter warnings in run/stop callbacks
@sakumisu sakumisu merged commit febe71b into cherry-embedded:master Apr 21, 2026
5 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants