From 6f7f7ddd6cd536cb2b37d59b0f1377b0dc812b40 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 9 Sep 2026 11:58:16 +0100 Subject: [PATCH] Bluetooth mic startup: honest Listening indicator, startup-time investigation The bar turned green after 2 s on a timer even when the microphone delivered nothing. It now turns green only on real audio: RMS above 0.0005, or three consecutive chunks that are not digital silence (the virtual mic emits one stray nonzero chunk right after start, and a Bluetooth headset's floor ramps in from a few LSB). Measured 1.2-1.4 s after the key, within 0.14 s of the first real samples. diagnostics/bluetooth/ records how startup went from ~1.6 s (or never) to ~1.1-1.4 s: a btusb driver bug, two PipeWire bluez5 bugs, a 500 ms WirePlumber switch timeout and an over-broad auto-connect rule. Those fixes are machine level and live outside this repo; the patches, tools and measurements are here. STARTUP-TIME.md is the summary and explains the ~0.9 s hardware floor. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Xoc9DJCViR7dg9eKzzAcfQ --- .gitignore | 5 + daemon/sttd.py | 12 +- ...0001-bluez5-mark-sco-acquire-pending.patch | 13 + ...isoc-alt-setting-on-every-sco-enable.patch | 72 + ...-hangup-after-audio-is-not-a-failure.patch | 51 + diagnostics/bluetooth/HANDOFF.md | 405 ++ diagnostics/bluetooth/README.md | 113 + diagnostics/bluetooth/STARTUP-TIME.md | 55 + diagnostics/bluetooth/test_sco_acquire.py | 114 + diagnostics/bluetooth/tools/btusb.c | 4739 +++++++++++++++++ diagnostics/bluetooth/tools/kernel-probes.sh | 38 + diagnostics/bluetooth/tools/repro-loop.sh | 12 + diagnostics/bluetooth/tools/trial.sh | 22 + diagnostics/bluetooth/tools/trial2.py | 94 + 14 files changed, 5742 insertions(+), 3 deletions(-) create mode 100644 diagnostics/bluetooth/0001-bluez5-mark-sco-acquire-pending.patch create mode 100644 diagnostics/bluetooth/0002-btusb-program-isoc-alt-setting-on-every-sco-enable.patch create mode 100644 diagnostics/bluetooth/0003-media-sink-hfp-hangup-after-audio-is-not-a-failure.patch create mode 100644 diagnostics/bluetooth/HANDOFF.md create mode 100644 diagnostics/bluetooth/README.md create mode 100644 diagnostics/bluetooth/STARTUP-TIME.md create mode 100644 diagnostics/bluetooth/test_sco_acquire.py create mode 100644 diagnostics/bluetooth/tools/btusb.c create mode 100755 diagnostics/bluetooth/tools/kernel-probes.sh create mode 100755 diagnostics/bluetooth/tools/repro-loop.sh create mode 100755 diagnostics/bluetooth/tools/trial.sh create mode 100755 diagnostics/bluetooth/tools/trial2.py diff --git a/.gitignore b/.gitignore index 7a60b85..7b73c53 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,7 @@ __pycache__/ *.pyc +diagnostics/**/*.ko +diagnostics/**/*.so +diagnostics/**/*.log +diagnostics/**/*.btsnoop +__pycache__/ diff --git a/daemon/sttd.py b/daemon/sttd.py index b9b8680..0a60aae 100755 --- a/daemon/sttd.py +++ b/daemon/sttd.py @@ -528,6 +528,7 @@ class Recorder: self.error = "" self.listening = False # real audio is arriving (a Bluetooth mic sends silence while it switches profile) self.chunks = 0 + self.nonzero_run = 0 # consecutive chunks that were not digital silence self.standby = False # warm mode: the stream runs but only the last second is kept def start(self): @@ -558,9 +559,14 @@ class Recorder: rms = math.sqrt(sum(s * s for s in samples) / max(1, n)) / 32768.0 level = min(1.0, math.sqrt(rms * 12.0)) # perceptual-ish: speech at normal level fills most of the bar self.chunks += 1 - # Green means "your voice is getting through": any real signal (room noise counts), - # or 2 s of chunks for a microphone that is digitally silent. - if rms > 0.0005 or self.chunks >= 40: + # Green means "your voice is getting through". Clear input (speech, room noise on most + # mics) turns it on at once. Otherwise wait for three consecutive chunks that are not + # digital silence: a Bluetooth headset delivers exact zeros until its microphone link + # is up, the virtual mic emits one stray nonzero chunk right after start (processing + # residue), and the headset's own floor then ramps in from a few LSB with the odd + # all-zero chunk. No time-based fallback: a mic that only sends zeros is not listening. + self.nonzero_run = self.nonzero_run + 1 if rms > 0 else 0 + if rms > 0.0005 or self.nonzero_run >= 3: self.listening = True with self.lock: self.buf += data diff --git a/diagnostics/bluetooth/0001-bluez5-mark-sco-acquire-pending.patch b/diagnostics/bluetooth/0001-bluez5-mark-sco-acquire-pending.patch new file mode 100644 index 0000000..0979cb8 --- /dev/null +++ b/diagnostics/bluetooth/0001-bluez5-mark-sco-acquire-pending.patch @@ -0,0 +1,13 @@ +--- a/spa/plugins/bluez5/backend-native.c ++++ b/spa/plugins/bluez5/backend-native.c +@@ -2835,6 +2835,11 @@ + + if (td->err != -EINPROGRESS) + sco_ready(t); ++ else ++ /* A second node can acquire the same transport while connect() is ++ * pending. Do not let it re-emit an error from the previous attempt. ++ */ ++ spa_bt_transport_set_state(t, SPA_BT_TRANSPORT_STATE_PENDING); + + return 0; diff --git a/diagnostics/bluetooth/0002-btusb-program-isoc-alt-setting-on-every-sco-enable.patch b/diagnostics/bluetooth/0002-btusb-program-isoc-alt-setting-on-every-sco-enable.patch new file mode 100644 index 0000000..7a6cb76 --- /dev/null +++ b/diagnostics/bluetooth/0002-btusb-program-isoc-alt-setting-on-every-sco-enable.patch @@ -0,0 +1,72 @@ +From: Alan Silva +Subject: [PATCH] Bluetooth: btusb: switch the isoc interface on every SCO enable notification + +hci_conn_num(hdev, SCO_LINK) also counts (e)SCO links that are still being +set up, since hci_connect_sco() adds them to the connection hash before the +Synchronous Connection Complete event arrives. btusb_notify() only compares +that count with data->sco_num and stores whatever event it was called with +as the air mode. Two things go wrong when an unrelated connection event +arrives while an (e)SCO link is pending: + + 1. The unrelated event (e.g. HCI_NOTIFY_CONN_DEL from a failed ACL page to + another device) changes the count from 0 to 1, so btusb_work() runs + with air_mode = HCI_NOTIFY_CONN_DEL, computes new_alts = 0 and submits + isochronous URBs on the alternate setting 0 endpoints, whose + wMaxPacketSize is 0. usb_submit_urb() fails with -EMSGSIZE: + Bluetooth: hci0: urb 00000000d42f828b submission failed (90) + and BTUSB_ISOC_RUNNING is cleared again. + + 2. When HCI_NOTIFY_ENABLE_SCO_TRANSP finally arrives for that link, the + count already equals data->sco_num, so nothing is scheduled. The + interface stays on alternate setting 0, no isochronous URBs are + submitted, and the SCO link carries no audio in either direction for + its whole lifetime. The user sees a working headset with a dead + microphone. + +Reproduced on an Intel AX210 (8087:0032) with a Sony WH-1000XM5 and +PipeWire 1.6.8: PipeWire re-tries ConnectProfile() on absent paired devices +when it starts, bluetoothd pages them, the page times out (status 0x04) +while dictation opens the headset microphone, and the mSBC link comes up +silent. Traced with kprobes on btusb_notify/btusb_work/btusb_submit_isoc_urb. + +Program the alternate setting on every ENABLE_SCO_* notification, and on +other events only react when links went away. +--- +--- a/drivers/bluetooth/btusb.c 2026-09-09 02:54:49.664029766 +0100 ++++ b/drivers/bluetooth/btusb.c 2026-09-09 02:55:52.408391149 +0100 +@@ -2289,13 +2289,33 @@ + static void btusb_notify(struct hci_dev *hdev, unsigned int evt) + { + struct btusb_data *data = hci_get_drvdata(hdev); ++ int sco_num = hci_conn_num(hdev, SCO_LINK); + + BT_DBG("%s evt %d", hdev->name, evt); + +- if (hci_conn_num(hdev, SCO_LINK) != data->sco_num) { +- data->sco_num = hci_conn_num(hdev, SCO_LINK); ++ switch (evt) { ++ case HCI_NOTIFY_ENABLE_SCO_CVSD: ++ case HCI_NOTIFY_ENABLE_SCO_TRANSP: ++ /* A (e)SCO link just came up: program the isochronous ++ * alternate setting for its air mode, even if the link was ++ * already counted while it was still being set up. ++ */ ++ data->sco_num = sco_num; + data->air_mode = evt; + schedule_work(&data->work); ++ break; ++ default: ++ /* hci_conn_num() also counts (e)SCO links that are still ++ * being set up, and only the ENABLE_SCO_* notifications ++ * carry an air mode. Any other event may only tear the ++ * isochronous interface down or adjust it for fewer links; ++ * a pending link is handled once it is enabled. ++ */ ++ if (sco_num < data->sco_num) { ++ data->sco_num = sco_num; ++ schedule_work(&data->work); ++ } ++ break; + } + } + diff --git a/diagnostics/bluetooth/0003-media-sink-hfp-hangup-after-audio-is-not-a-failure.patch b/diagnostics/bluetooth/0003-media-sink-hfp-hangup-after-audio-is-not-a-failure.patch new file mode 100644 index 0000000..3690dd7 --- /dev/null +++ b/diagnostics/bluetooth/0003-media-sink-hfp-hangup-after-audio-is-not-a-failure.patch @@ -0,0 +1,51 @@ +--- a/spa/plugins/bluez5/media-sink.c ++++ b/spa/plugins/bluez5/media-sink.c +@@ -152,6 +152,7 @@ + unsigned int start_ready:1; + unsigned int transport_started:1; + unsigned int following:1; ++ bool transport_wrote; /* data left for the remote since transport start (HFP: only after RX was seen) */ + unsigned int is_output:1; + unsigned int flush_pending:1; + unsigned int iso_pending:1; +@@ -748,6 +749,8 @@ + written = spa_bt_send(this->flush_source.fd, this->buffer, this->buffer_used, + &this->tx_latency, SPA_TIMESPEC_TO_NSEC(&ts_pre)); + } ++ if (written > 0) ++ this->transport_wrote = true; + + if (SPA_UNLIKELY(spa_log_level_topic_enabled(this->log, SPA_LOG_TOPIC_DEFAULT, SPA_LOG_LEVEL_TRACE))) { + struct timespec ts; +@@ -1517,6 +1520,7 @@ + struct impl *this = user_data; + + this->transport_started = true; ++ this->transport_wrote = false; + if (this->transport->iso_io) + spa_bt_iso_io_set_cb(this->transport->iso_io, media_iso_pull, this); + return 0; +@@ -2466,7 +2470,8 @@ + else + transport_stop(this); + +- if (state < SPA_BT_TRANSPORT_STATE_ACTIVE && was_started && !this->is_duplex && this->is_output) { ++ if (state < SPA_BT_TRANSPORT_STATE_ACTIVE && was_started && !this->is_duplex && this->is_output && ++ !(this->codec->kind == MEDIA_CODEC_HFP && this->transport_wrote)) { + /* + * If establishing connection fails due to remote end not activating + * the transport, we won't get a write error, but instead see a transport +@@ -2474,6 +2479,13 @@ + * + * Treat this as a transport error, so that upper levels don't try to + * retry too often. ++ * ++ * An HFP link that already carried audio both ways (sco-io only writes ++ * after the first packet came in) and then hangs up is not a failed ++ * activation: headsets drop the SCO link when the profile switches back ++ * to A2DP after every call. Counting that as an error made ++ * spa_bt_transport_acquire() refuse the next acquire once three such ++ * hangups landed within its error window. + */ + + spa_log_debug(this->log, "%p: transport %p becomes inactive: stop and indicate error", diff --git a/diagnostics/bluetooth/HANDOFF.md b/diagnostics/bluetooth/HANDOFF.md new file mode 100644 index 0000000..95720ec --- /dev/null +++ b/diagnostics/bluetooth/HANDOFF.md @@ -0,0 +1,405 @@ +# XM5 dictation startup: investigation handoff + +Date: 2026-09-09. Status: **fixed and installed** (see the resolution section +below). The older sections are kept as the investigation record. + +## Resolution, 2026-09-09 afternoon session + +Three independent faults were reproduced, fixed and re-measured with +`tools/trial2.py` (kernel kprobes with the `mono` trace clock, the daemon's own +level stream, the card profile before/during/after each take). Everything below +is installed on this machine; nothing was submitted upstream. + +### 1. Silent first start: btusb alternate-setting bug (patch `0002`) + +Reproduced on the first stock attempt (`tools/stock-repro-1.log`): eSCO +`connect()` at 0.76 s stuck behind two pages, `btusb_switch_alt_setting(0)` and +the isochronous submit failure at 0.95 s, link up at 6.19 s with **zero** SCO +URBs for its whole life. With the patched module the exact same race +(`tools/patched-repro-3.log`: eSCO request stalled 3 s behind a page timeout, +`HCI_NOTIFY_CONN_DEL` ignored, alt setting 6 programmed on +`ENABLE_SCO_TRANSP`) delivered audio. + +Installed: `/usr/lib/modules/7.2.3-arch1-3/updates/btusb.ko` (+ `depmod`); +`modinfo -n btusb` resolves there. btusb is not in the UKI, so no initramfs +rebuild was needed. A kernel upgrade replaces the whole modules directory and +silently returns to the stock driver; rebuild `tools/btusb.c` against the new +kernel and reinstall. `/etc/modprobe.d` needs nothing. + +The trigger was `~/.config/wireplumber/wireplumber.conf.d/bluetooth-a2dp-autoconnect.conf` +matching every card. It is now narrowed to `bluez_card.88_C9_E8_A7_EC_7E`. +Disabling it entirely was tried first and is wrong: after a WirePlumber restart +the XM5's A2DP profile does not come back on its own (the card offered only +`headset-head-unit`), so the XM5 needs the rule. Absent devices are no longer +paged (`journalctl -u bluetooth` shows no "Host is down" after a restart). + +### 2. Autoswitch delay: 50 ms script now in effect + +`~/.local/share/wireplumber/scripts/device/autoswitch-bluetooth-profile.lua` +(the packaged script with `PROFILE_SWITCH_TIMEOUT_MSEC = 50`). eSCO connect +moved from 0.65–0.85 s to 0.26–0.49 s after the start command. The +ineffective copy under `~/.config/wireplumber/scripts/device/` is still there +(this session could not delete it); it is harmless. + +### 3. PipeWire: stale error replay and a hangup counted as failure (patches `0001`, `0003`) + +With 1 and 2 in place, 1 take in 3 still came up silent with the stock plugin: +`bluez_input ... running -> error` right at acquire, the `0001` replay +(`tools/normal-5.log`, journal 11:26:46). `0001` is a real, independent bug, +not a symptom of the paging. + +With `0001` alone, the 4th of 4 quick takes failed with +`spa.audioadapter: can't send command 2: Input/output error` and no eSCO +request at all (`tools/pw-4.log`). Cause: every take ends with +`Failure in Bluetooth audio transport .../fd60` because `media-sink.c` +converts the SCO hangup (the headset drops SCO when the profile goes back to +A2DP) into `SPA_BT_TRANSPORT_STATE_ERROR`, and `spa_bt_transport_acquire()` +returns `-EIO` once `error_count >= 3` within a 6 s window +(`TRANSPORT_ERROR_TIMEOUT = 2 * BLUEZ_ACTION_RATE_MSEC`). Four takes each +started within ~8 s of the previous one ending is enough. Patch `0003` skips +that escalation for an HFP sink that already wrote data (sco-io only writes +after the first packet came in, so this implies the link was really up). + +Installed: `~/.local/lib/spa-0.2/bluez5/libspa-bluez5.so` (PipeWire 1.6.8 + +`0001` + `0003`, built with `--prefix=/usr` so `bluez-hardware.conf` resolves +to `/usr/share`), selected by +`~/.config/systemd/user/{pipewire,wireplumber}.service.d/spa-plugin-dir.conf` +(`SPA_PLUGIN_DIR=/home/tank/.local/lib/spa-0.2:/usr/lib/spa-0.2`). Codec +plugins still come from `/usr/lib/spa-0.2/bluez5`. WirePlumber is the process +that maps the plugin. After a PipeWire upgrade rebuild against the new source +(the build needs `gdbus-codegen`, extracted from `glib2-devel` without +installing it, and a `gio-2.0.pc` copy pointing at it) or delete the two +drop-ins to fall back to the packaged plugin. A copy of the built plugin is in +`tools/libspa-bluez5.so`. + +Result: 8 of 8 rapid takes (`tools/pw2-*.log`) and 6 more after that with no +transport failure, no start error, A2DP restored 2 s after every take. + +### 4. Honest "Listening" indicator (`daemon/sttd.py`) + +The 40-chunk fallback lit the indicator at 2.1 s on a dead microphone. The +level stream showed why a plain "first nonzero chunk" test is wrong too: the +virtual mic emits one stray nonzero chunk at ~0.15 s (level 0.02, processing +residue), then exact zeros until the headset floor ramps in from a few LSB +with the odd all-zero chunk (`tools/win-*.log`). The daemon now turns +`listening` on at RMS > 0.0005 or after three consecutive nonzero chunks, and +never on a timer. Measured: 1.19–1.43 s after the start command, 0–0.14 s +after the first nonzero chunk (`tools/ind2-*.log`). + +### Timeline now (normal path, quiet room) + +| after F13 | event | +|---|---| +| 0.26–0.49 s | eSCO link up | +| 1.06–1.43 s | first nonzero PCM at the daemon | +| 1.19–1.43 s | UI "Listening" | + +The 0.7–0.9 s between link-up and first PCM is the headset's own silence plus +the Camera Effects path; see the earlier analysis. The remaining Linux-side +gain would be requesting the headset profile from the daemon at capture start +(~0.25 s), not done: the autoswitch script only restores a profile it switched +itself, so a daemon-side switch would leave the headset in mono after the take. + +### Not fixable + +Stereo playback while the headset microphone is in use: A2DP is one-way and +the WH-1000XM5 has no LE Audio. Every OS drops to mono HFP for its mic. + +### Files added this session + +`0003-media-sink-hfp-hangup-after-audio-is-not-a-failure.patch`, +`tools/trial2.py` (trial driver, replaces `trial.sh`, which needed a `/tmp` +script that is gone), `tools/libspa-bluez5.so`, `tools/*.log`. +`tools/kernel-probes.sh` now disables the events before rewriting them, so it +can be re-run after a module reload. + +--- + +## Earlier record (superseded where the resolution above says so) + +## Update, 2026-09-09 later session: silent first start root-caused + +Status: **the "first microphone start gets no audio at all" failure is fully +explained and reproduced under kernel tracing; a kernel driver patch is written and +built but not loaded. The remaining startup delay is measured and its floor is set +by the headset, not by Linux.** + +### The silent start is a btusb driver bug, triggered by paging absent devices + +Reproduced twice out of two attempts by restarting WirePlumber and starting +dictation about 10 s later. Kernel event order (kprobes, see `tools/`): + +1. PipeWire `connect()`s the mSBC SCO socket: `hci_conn_add_unset(ESCO)` puts the + pending link in the connection hash (counted by `hci_conn_num(SCO_LINK)`), and + the Enhanced Setup Synchronous Connection command is queued. +2. The command does **not** go out for 2.3 s: bluetoothd is paging another paired + device at that moment, and the kernel's synchronous Create Connection request + holds the HCI command queue until its Connect Complete arrives (page timeout, + ~5.1 s). Any dictation start that overlaps such a page stalls the same way. +3. Connect Complete arrives with status 0x04 (Page Timeout) for that other device; + its `hci_conn_del()` notifies btusb with `HCI_NOTIFY_CONN_DEL`. +4. `btusb_notify()` only compares `hci_conn_num(SCO_LINK)` (now 1, the pending + link) with its `data->sco_num` (0), stores CONN_DEL as the "air mode" and runs + `btusb_work()`, which computes `new_alts = 0` and submits isochronous URBs on the + alternate-setting-0 endpoints (wMaxPacketSize 0). `usb_submit_urb()` returns + -EMSGSIZE: that is the `urb ... submission failed (90)` line. The `len 0 mtu 0` + debug print from `__fill_isoc_descriptor` confirms it. +5. 0.14 s later the eSCO link comes up (Synchronous Connect Complete, air mode + transparent) and `HCI_NOTIFY_ENABLE_SCO_TRANSP` is sent, but the count already + matches `data->sco_num`, so nothing is scheduled. The interface stays on + alternate setting 0 for the life of the link: no SCO URBs, no audio either way. + PipeWire waits for the first incoming packet (USB adapters) forever, the daemon + sees silence, and "Listening" appears only from the 40-chunk fallback. + +All four historical `submission failed (90)` entries (00:49, 00:53, 01:39, 02:17) +sit 2–5 s after a WirePlumber restart, and the "physical HFP nodes enter error" +failures in the stock trials are the same event seen from PipeWire (the pending +SCO connect fails with the paging device's status). The `0001` PipeWire patch +therefore addresses a symptom of this, not an independent bug. + +Why a page was in flight: the user's own +`~/.config/wireplumber/wireplumber.conf.d/bluetooth-a2dp-autoconnect.conf` sets +`bluez5.auto-connect = [ a2dp_sink a2dp_source ]`. On every WirePlumber start +PipeWire calls `ConnectProfile()` on every paired A2DP device that is not connected +("Nothing Ear (3)" and "RB Meta 042Q" here), bluetoothd pages each for 5.1 s, and +the whole HCI command queue is blocked while it does. In normal use that is the +first ~11 s after login or after any WirePlumber restart; every absent paired +device extends it by ~5 s. Dropping that rule, or narrowing its match to the +devices it was written for, removes the trigger. The btusb bug itself fires on +any non-SCO connection add/remove that lands while an eSCO link is pending (an +LE device connecting, another ACL dropping), so it stays worth fixing. + +Fix: `0002-btusb-program-isoc-alt-setting-on-every-sco-enable.patch` changes +`btusb_notify()` to program the interface on every `ENABLE_SCO_*` notification and +to ignore count increases from other events. `tools/btusb.ko` is that patch built +against the exact stable 7.2.3 source (identical to the local driver source) with +the installed headers, vermagic `7.2.3-arch1-3 SMP preempt mod_unload`. It is +**not loaded**; test with `sudo rmmod btusb && sudo insmod tools/btusb.ko` +(headset reconnects), revert with `sudo rmmod btusb && sudo modprobe btusb`. +Not submitted upstream. + +### Normal-path timing, stock, ACL in sniff mode (trace of 02:49:34.93) + +| after F13 | event | +|---|---| +| 0.01 s | daemon recording, pw-record running | +| 0.28 s | Camera Effects helper stream running, autoswitch script triggered | +| 0.79 s | autoswitch 500 ms timer fires, profile set to headset-head-unit | +| 0.82 s | SCO `connect()`; Exit Sniff Mode, Mode Change 65 ms later | +| 1.01 s | eSCO up (Enhanced Setup Sync took 117 ms); first SCO packet 19 ms later | +| ~1.2 s | first decoded PCM, all zeros (earlier instrumented runs) | +| 1.61 s | first nonzero input at Camera Effects; 1.72 s first nonzero daemon level | +| 2.07 s | UI "Listening" (40-chunk fallback; room noise is below the RMS threshold) | + +The 0.5–0.6 s between eSCO link-up and the first nonzero sample is the headset: +it sends encoded digital silence for roughly 300 ms after the link opens, plus +mSBC sync. Linux cannot shorten it. What Linux can shorten: + +- The 500 ms autoswitch timer (`PROFILE_SWITCH_TIMEOUT_MSEC` in + `/usr/share/wireplumber/scripts/device/autoswitch-bluetooth-profile.lua`): + ~0.45 s. A copy with 50 ms placed at + `~/.config/wireplumber/scripts/device/autoswitch-bluetooth-profile.lua` was + **not** picked up (measured: still 500 ms). It is still there; remove it, or move + it to `~/.local/share/wireplumber/scripts/device/` (where the user's other + script lives) and re-measure the gap between `Triggering profile switch` and + `Switching profile` in the WirePlumber journal at info level. +- The ~0.27 s before the profile switch is even requested (Camera Effects 250 ms + maintenance poll opening the helper stream, then WirePlumber noticing it). + Requesting the headset profile directly when capture starts would remove most + of it. + +With both, eSCO link-up lands near 0.3–0.35 s and first real audio near 0.9 s. +That is the floor with this headset. Words spoken before ~0.9 s are lost unless +the microphone is already in HFP, which the user has rejected; the honest +alternative is an indicator that turns on only when nonzero physical input +arrives, which the current 0.0005 RMS threshold and 40-chunk fallback do not give +(quiet-room noise measured RMS ~1e-4, Camera Effects residue ~4e-5). + +### Stereo playback while the microphone is used + +Not possible with this headset on any OS. A2DP is one-way; the microphone +needs an HFP SCO link, and the WH-1000XM5 has no LE Audio. Windows and macOS drop +to the same mono hands-free profile when its microphone is used. + +### State after this session + +Stock btusb loaded (srcversion matches the packaged module), all kprobes and +dynamic-debug prints removed, no btmon running, WirePlumber restarted with default +logging and `WIREPLUMBER_DEBUG` unset, dictation idle, warm mic off. The only +persistent change is the ineffective script copy under +`~/.config/wireplumber/scripts/device/`. `tools/` holds the probe installer +(`kernel-probes.sh`, `off` to remove), the trial driver (`trial.sh`, needs +`/tmp/stt-startup-trace.py`), the restart-and-retry reproducer (`repro-loop.sh`), +and the patched driver source and module. + +## Required outcome + +F13 dictation must use the Sony WH-1000XM5's own microphone, start immediately +without losing opening words, and preserve headphone playback quality. The user +rejects substituting the webcam microphone and keeping HFP/mic capture permanently +open. Do not compare this with Deadlock. Mac/Windows microphone selection was not +verified; do not assume that comparison establishes an identical Bluetooth path. + +## Verified state at handoff + +- Stock WirePlumber is active/running, with no service drop-ins and no test SPA or + data-directory environment overrides. +- Camera Effects explicitly selects `bluez_input.88:C9:E8:A7:EC:7E` (WH-1000XM5). +- Speech-to-text is idle, warm capture is false, Camera Effects is not capturing. +- No btmon, pkexec, startup trace, or patched-test process remains running. +- The earlier unwanted webcam-microphone substitution was reverted. +- No kernel/module replacement, system package installation, permanent candidate + PipeWire installation, or upstream submission was done. +- Repository status is only untracked `diagnostics/`; STT runtime source was not + changed by this investigation. + +## Actual application path + +`F13 -> speech-to-text/bin/stt -> daemon/sttd.py -> pw-record -> camera-effects-mic` + +VoxType is the transcription engine here, not the ordinary VoxType microphone +daemon. Testing its separate CLI does not reproduce the F13 startup path. + +Camera Effects creates `camera-effects-mic-input`, which links through the +WirePlumber Bluetooth loopback to the physical HFP source. A helper capture named +`camera-effects-mic-headset` triggers automatic profile switching. The user's +Camera Effects permission rule hides raw microphones from unrelated clients; +do not bypass that rule by impersonating an allowed client. + +STT requests raw S16, 16 kHz, mono audio in 50 ms chunks. Its `listening` flag +becomes true when RMS exceeds 0.0005, or after 40 chunks (two seconds of PCM). +This flag controls UI readiness, not recording commencement: preceding chunks +are already collected. Therefore quiet input can show a two-second delay, and +silence from a disconnected microphone can falsely become "Listening." + +Camera Effects maintenance polls every 250 ms. Its virtual stream supplies +silence before the physical mic is ready and may initially contain residual +buffered audio. First virtual buffers or early virtual nonzero samples are not +reliable proof that current headset speech is being captured. Read-only input +metering and instrumentation at the Bluetooth decoder are more meaningful. + +## Measurements + +Tests invoked the same daemon start command used by F13, without keyboard +dispatch. Six-second takes were cancelled, not pasted or saved as completed +history. Live transcription may nevertheless have processed data during them. + +Stock observations: + +- Daemon recording state begins in roughly 12–20 ms; virtual PCM around 160 ms. +- WirePlumber intentionally waits 500 ms before a headset-profile switch and + restarts that timer on further relevant graph events. Restoration waits 2 s. +- Profile change generally starts around 0.6–0.9 s. +- HCI synchronous connection completion was around 0.87–1.02 s. That is not + equivalent to microphone audio being ready. +- Some trials fail entirely: physical HFP nodes enter error, or usable audio + never arrives. A stock failing trial stopped accumulating PCM at 0.8 s. +- Kernel logs sometimes contain `Bluetooth: hci0: urb ... submission failed (90)`. + Error 90 is EMSGSIZE. Which USB submission path causes it is not yet proven. + +With the candidate PipeWire fix and temporary decoder instrumentation, two +successful trials measured: incoming encoded packets at 0.97–0.99 s; first decoded +PCM at 1.16–1.19 s; first nonzero decoded PCM at 1.48–1.50 s; nonzero PCM sent to +the graph at 1.53–1.55 s; Camera Effects input signal around 1.62 s; UI readiness +around 2.14 s. This narrows the delay but does not establish speech intelligibility. +Initial zero packets versus codec synchronization versus headset startup remains +unresolved. The H2 reader itself parses a 60-byte frame without an explicit timer. + +The first trial after the instrumented WirePlumber restart received no encoded +audio within six seconds, with a USB submission error around 4.46 s. + +## Candidate actual PipeWire bug + +An HFP transport can retain ERROR from an earlier use. `sco_acquire_cb()` starts +an asynchronous connection without changing that stale state. A second node +acquiring the same transport takes the reference-count branch in +`spa_bt_transport_acquire()` and re-emits the old ERROR, even though the new +connection subsequently succeeds. + +Observed debug sequence: 01:32:25.430 acquire, .447 second acquire/error replay, +.538 successful connection (BST). The candidate sets PENDING while the asynchronous +acquire is in progress. It does not signal readiness early or suppress real errors. + +Files in this directory: + +- `0001-bluez5-mark-sco-acquire-pending.patch` +- `test_sco_acquire.py`: extracts the actual acquire functions and compiles them + with mocked I/O. Original source fails; patched source passes cold/retry + concurrent acquire, delayed readiness, synchronous success, and real failures. + +The Bluetooth component builds. No stale-error replay was observed in the three +initial patched trials, but silent startup remained. This is a partial candidate, +not proof of an end-to-end fix. The relevant upstream master acquire function +inspected during the investigation matched 1.6.8; nothing was submitted upstream. + +## Important integration-test confounds + +The local Meson build used its default `/usr/local` prefix. A later log showed +that the test plugin could not load the installed Bluetooth hardware-quirks file: +it searched `/usr/local/share/spa-0.2/bluez5/bluez-hardware.conf`, while the file is +at `/usr/share/spa-0.2/bluez5/bluez-hardware.conf`. Correct build prefix/data paths +before attributing any patched-versus-stock behavior to the candidate patch. + +A separate 50 ms WirePlumber-delay experiment previously removed roughly 450 ms +but did not eliminate failures. The latest attempted combined test did not run: +`WIREPLUMBER_DATA_DIR` pointed to a copied system data directory without the user's +required `camera-effects-hide-mics.lua`. WirePlumber hit its restart limit. The +override was removed and stock service restored/reset successfully. Do not count +this attempt as latency data. Preserve user scripts when building another overlay. + +## Machine and relevant paths + +- PipeWire 1.6.8, WirePlumber 0.5.17, BlueZ 5.87, kernel 7.2.3-arch1-3. +- Intel AX210 Bluetooth USB 8087:0032; device `/sys/bus/usb/devices/1-9`, + isochronous interface `1-9:1.1`, full-speed USB. +- Sony WH-1000XM5 address 88:C9:E8:A7:EC:7E. +- Observed profiles: A2DP AAC/SBC/SBC-XQ and HFP CVSD/mSBC. No LE Audio profile + observed. Idle playback is AAC stereo; mic use selects mSBC mono HFP. +- Those observations do not establish that a Linux-only update can provide the + headset mic plus unchanged stereo playback. That part of the requirement is + unresolved; do not promise it as a consequence of reducing switching delay. +- Camera Effects running binary: `/usr/local/lib/camera-effects/camera-effects-server`. +- Camera Effects sources: `/home/tank/.config/omarchy/plugins/alanfortlink.camera-effects/daemon/src/`. +- STT config: `/home/tank/.config/speech-to-text/config.json`. +- Camera Effects config: `/home/tank/.config/camera-effects/config.json`. +- WirePlumber user scripts include both `~/.config/wireplumber/scripts/` and + `~/.local/share/wireplumber/scripts/camera-effects-hide-mics.lua`. + +## Temporary working materials (may disappear after reboot) + +Root: `/tmp/stt-bluetooth-switch.uZDCcW/` + +- `pipewire-1.6.8/`: official source plus candidate backend patch and temporary + `media-source.c` timing instrumentation. `build-test/` holds its Meson build. +- `backend-native.c`, `bluez5-dbus.c`, `media-source.c`: original source copies. +- `patched-spa/bluez5/libspa-bluez5.so`: experimental component; **not suitable + for permanent installation** given the caveat above. +- `build-tools.ini`, `build-tools/`: extracted matching glib2 development tool + used for gdbus-codegen, without installing system packages. +- `run-patched-test.sh`: temporary service override, three cancelled captures, + automatic restoration. Correct its environment setup before reuse. +- `autoswitch-bluetooth-profile.lua`: packaged script with 500 changed to 50 ms. +- `filter-hci.py`: btmon metadata-only filter, drops audio/keys/addresses. Fixed + SCO parser recognizes actual `> BR-ESCO:` RX and `< BR-ESCO:` TX headers. + Earlier zero RX/TX counts from the incorrect parser were invalid evidence. +- `btusb.c`: upstream v7.2 driver reference, not yet checked against all 7.2.3 + changes; `bluez-packet.c`: BlueZ 5.87 monitor formatting reference. +- `/tmp/stt-startup-trace.py`: daemon start/cancel, graph and input-meter timing. + +## Most useful remaining work + +1. Correct the test build paths and repeat controlled stock/patched measurements. +2. Trace the first-start USB failure. `sudo -n true` succeeded at the end of this + investigation, so passwordless scoped tracing may now be available. Earlier + pending pkexec/btmon authentication was cancelled; it is not running. +3. Tracefs exists at `/sys/kernel/tracing`, accessible with sudo. No probes were + installed. No perf/bpftrace/bpftool is installed; kernel headers and BTF exist. +4. Determine which `usb_submit_urb` returns EMSGSIZE and the associated endpoint, + alternate setting, and packet lengths. USB alt6 permits 63 bytes; SCO frames + observed were 60 bytes. Kernel SCO_OPTIONS reports 96, which PipeWire already + knows is unreliable for USB and avoids by waiting for incoming packet size. +5. Investigate before changing that wait: native SCO waits for readable data on + USB before declaring transport ready; sco-io also waits for RX before TX. + No-RX startup could involve this interaction, the driver, or the headset. +6. Treat quality preservation as a separate capability question, not a side + effect of a latency patch. Do not restore webcam or warm-mic workarounds. diff --git a/diagnostics/bluetooth/README.md b/diagnostics/bluetooth/README.md new file mode 100644 index 0000000..5f2433c --- /dev/null +++ b/diagnostics/bluetooth/README.md @@ -0,0 +1,113 @@ +# F13 Bluetooth startup investigation + +Status: **fixed and installed on 2026-09-09** — three faults (btusb +alternate-setting bug, PipeWire stale-error replay, PipeWire counting the +end-of-take SCO hangup as a failure), the 500 ms autoswitch delay, and the +daemon's false "Listening" indicator. Stereo playback with the headset +microphone is not possible with this headset. Full account in the resolution +section at the top of [HANDOFF.md](HANDOFF.md). + +## Reproduction + +Environment: PipeWire 1.6.8, WirePlumber 0.5.17, BlueZ 5.87, +Linux 7.2.3-arch1-3, Intel AX210 USB Bluetooth, Sony WH-1000XM5. +Measurements taken on 2026-09-09, with the dictation microphone initially idle. + +The F13 extension uses its Python daemon and `pw-record`, targeting +`camera-effects-mic`. VoxType performs transcription, not microphone startup. +Tests invoked the same daemon start command, omitting keyboard dispatch, and +cancelled the take without pasting or adding completed recordings to history. + +Observed on the stock system: + +- Recording state starts in roughly 12–20 ms. +- The virtual microphone supplies buffers before the Bluetooth mic connects; + even an early nonzero level can be buffered data, not current microphone input. +- Successful HCI synchronous-connection completion was measured around + 0.87–1.02 seconds after the start command. This does not establish when usable + speech first arrives. +- A failing trial accumulated 0.8 seconds of PCM, then stayed at that duration + through cancellation at six seconds. Both physical HFP nodes entered error. +- The UI also has a separate signal threshold / two-seconds-of-PCM fallback. + Its “Listening” indication is not proof of physical microphone readiness. + +## Candidate PipeWire fix + +An HFP transport can retain `SPA_BT_TRANSPORT_STATE_ERROR` from an earlier use. +`sco_acquire_cb()` starts an asynchronous connection but does not change that +state while waiting. A second node acquiring the same transport executes +`spa_bt_transport_acquire()`'s reference-count path, which re-emits the retained +error to both nodes. This can happen even though the new connection succeeds +shortly afterward. + +The debug trace reproduced that sequence: acquire at 01:32:25.430, +second acquire and error re-emission at .447, successful completion at .538 BST. + +`0001-bluez5-mark-sco-acquire-pending.patch` sets the state to `PENDING` during +the asynchronous acquire. It does not report readiness early, disable genuine +errors, change the Bluetooth codec, keep the microphone open, or shorten +WirePlumber's profile-switch delay. It applies to PipeWire 1.6.8; the corresponding +acquire function in the upstream master source inspected that day was unchanged. + +## Validation and limits + +`test_sco_acquire.py` compiles the actual two acquire functions with mocked I/O. +It fails against the unmodified source and passes with the patch. It covers +concurrent cold/retry acquisition, delayed readiness, synchronous success, and +real connection failures. It is a focused reproduction harness, not the full +PipeWire integration suite. + +Run it against a PipeWire source checkout: + +```sh +python3 diagnostics/bluetooth/test_sco_acquire.py \ + /path/to/pipewire/spa/plugins/bluez5/backend-native.c \ + /path/to/pipewire/spa/plugins/bluez5/bluez5-dbus.c +``` + +The patched Bluetooth component compiled and was loaded in WirePlumber using +a temporary, process-specific SPA plugin path. Across three cancelled startup +trials, the HFP error-state replay was not observed, but the first trial still +produced only silence. The kernel logged `urb ... submission failed (90)` during +that trial. The other trials produced signal but indicated readiness at about +2.2 seconds. Similar USB errors had also occurred in earlier unpatched tests; +their cause and relation to ordinary cold-start delay remain unproven. + +The temporary service override was removed and the stock service restored. +No system packages, permanent microphone settings, or speech-to-text behavior +were changed. Nothing has been submitted upstream. + +Further work must distinguish the USB/SCO first-start failure from the +error-state replay and measure current microphone input, not virtual-buffer +arrival or the UI indicator. This patch alone does not meet the requested +instant-start / full-quality experience. + +## Later measurements and test-environment caveat + +Temporary instrumentation in `media-source.c` measured two successful starts +with the candidate patch and the stock WirePlumber 500 ms switch delay: + +- First encoded SCO data: 0.97–0.99 s after the start request. +- First decoded PCM: 1.16–1.19 s. +- First nonzero decoded PCM: 1.48–1.50 s. +- First nonzero PCM delivered to the graph: 1.53–1.55 s. +- Camera Effects input meter first nonzero: about 1.62 s. +- UI listening indication: about 2.14 s. + +Nonzero samples establish signal, not intelligibility or preservation of opening +words. The first trial after restarting WirePlumber had no encoded data during +the six-second capture and logged a USB submission error at about 4.46 s. + +A later combined test with a 50 ms WirePlumber delay did **not run**: the temporary +data-directory override omitted the user's required `camera-effects-hide-mics.lua` +script, so WirePlumber failed to start. The override was removed, the service's +restart limit reset, and the stock service successfully started again. + +That startup log also exposed a build-environment confound: the locally built +PipeWire plugin searched `/usr/local/share/spa-0.2/bluez5/bluez-hardware.conf`, +whereas the installed quirks file is under `/usr/share/spa-0.2/bluez5/`. +Correct the build prefix/data paths before relying on patched-versus-stock +integration comparisons. The focused acquire-function regression test is +independent of this configuration problem. + +See [HANDOFF.md](HANDOFF.md) for the complete investigation handoff. diff --git a/diagnostics/bluetooth/STARTUP-TIME.md b/diagnostics/bluetooth/STARTUP-TIME.md new file mode 100644 index 0000000..557c649 --- /dev/null +++ b/diagnostics/bluetooth/STARTUP-TIME.md @@ -0,0 +1,55 @@ +# How we cut Bluetooth microphone startup time + +Measured on a Sony WH-1000XM5 over an Intel AX210, PipeWire 1.6.8, WirePlumber +0.5.17, kernel 7.2.3. Times are after the dictation key press. + +| | before | after | +|---|---|---| +| mic link (eSCO) up | 0.7–1.0 s, sometimes never | 0.26–0.49 s | +| first real audio at the daemon | 1.5–1.7 s, or never | 1.06–1.43 s | +| "Listening" in the bar | 2.1 s on a timer, even with no audio | 1.19–1.43 s, only on real audio | + +## What changed + +| Change | Where it lives | Gain | +|---|---|---| +| Daemon indicator: green on real audio only (RMS > 0.0005 or three consecutive non-silent chunks), no timer | `daemon/sttd.py` | the bar cannot claim to listen to a dead mic | +| WirePlumber profile-switch timeout 500 ms → 50 ms | `~/.local/share/wireplumber/scripts/device/autoswitch-bluetooth-profile.lua` | link up ~0.45 s sooner | +| A2DP auto-connect rule narrowed to the XM5 | `~/.config/wireplumber/wireplumber.conf.d/bluetooth-a2dp-autoconnect.conf` | no 5 s pages of absent devices at login | +| btusb driver patch `0002` | `/usr/lib/modules//updates/btusb.ko` | mic link no longer comes up silent when a page overlaps it | +| PipeWire bluez5 patches `0001` + `0003` | `~/.local/lib/spa-0.2/bluez5/` via `SPA_PLUGIN_DIR` drop-ins | no stale-error dead takes; back-to-back takes work | + +Only the first row is part of this repo. The rest are machine-level and are +described, with patches and measurements, in [HANDOFF.md](HANDOFF.md). + +## Why ~0.9 s is the floor + +``` +key press +0.00 s ─┬─ daemon starts pw-record on camera-effects-mic + │ + │ Camera Effects notices the client (250 ms poll), + │ opens its helper stream, WirePlumber waits 50 ms, + │ then asks BlueZ for the headset profile + │ +0.30 s ─┼─ eSCO link up (the headset must leave sniff mode, + │ then the radio sets up the synchronous link: ~0.1 s) + │ + │ headset sends encoded digital silence while its own + │ mic path starts and mSBC syncs: ~0.5–0.6 s + │ (measured at the decoder; Linux cannot shorten it) + │ +0.85 s ─┼─ first non-zero samples leave the headset + │ Camera Effects processing + 50 ms chunking +0.90 s ─┴─ first real audio reaches the daemon +``` + +What is left on the Linux side is the ~0.25 s before the profile switch is +even requested. The daemon could ask for the headset profile itself when +capture starts, but the WirePlumber autoswitch script only restores a profile +it switched, so the daemon would have to restore A2DP too. Not done. + +The headset's silence after link-up and the eSCO setup are hardware. Words +spoken in the first ~0.9 s are lost unless the microphone is already in +hands-free mode, which drops playback to mono, so it is off by default +(`warmMic`). diff --git a/diagnostics/bluetooth/test_sco_acquire.py b/diagnostics/bluetooth/test_sco_acquire.py new file mode 100644 index 0000000..f4c0295 --- /dev/null +++ b/diagnostics/bluetooth/test_sco_acquire.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Compile the actual acquire functions with mocked I/O; no Bluetooth access. + +This is a focused reproduction harness, not PipeWire's full integration suite. +Usage: test-sco-acquire.py +""" +import pathlib +import subprocess +import sys +import tempfile + + +def function(path, signature): + source = pathlib.Path(path).read_text() + start = source.index(signature + "\n{") + end = source.index("\n}", start) + 2 + return source[start:end] + + +stub = r''' +#include +#include +#include +#include +#include +enum { SPA_BT_TRANSPORT_STATE_ERROR = -1, SPA_BT_TRANSPORT_STATE_IDLE, + SPA_BT_TRANSPORT_STATE_PENDING, SPA_BT_TRANSPORT_STATE_ACTIVE }; +struct impl { void *log; } backend; +struct spa_bt_monitor { void *log; } monitor; +struct transport_data { int err; bool requesting; } td; +struct spa_bt_transport { + void *backend, *user_data; + struct spa_bt_monitor *monitor; + int fd, state, acquire_refcount, error_count; + bool acquired; + uint64_t last_error_time; +}; +#define SPA_CONTAINER_OF(p, type, member) ((type *)(p)) +#define spa_log_debug(...) ((void)0) +#define spa_assert assert +#define TRANSPORT_ERROR_TIMEOUT 6000000000ULL +#define TRANSPORT_ERROR_MAX_RETRY 3 +#define spa_bt_transport_impl(t, op, version, optional) sco_acquire_cb(t, optional) +static int error_events, connect_result, connect_error; +static uint64_t get_time_now(struct spa_bt_monitor *m) { return 10000000000ULL; } +static void spa_bt_transport_emit_state_changed(struct spa_bt_transport *t, int old, int state) { + if (state == SPA_BT_TRANSPORT_STATE_ERROR) ++error_events; +} +static void spa_bt_transport_set_state(struct spa_bt_transport *t, int state) { + int old = t->state; + if (old != state) { + t->state = state; + spa_bt_transport_emit_state_changed(t, old, state); + } +} +static int sco_do_connect(struct spa_bt_transport *t) { + td.err = connect_error; + return connect_result; +} +static void sco_start_source(struct spa_bt_transport *t) {} +static void sco_ready(struct spa_bt_transport *t) { + td.requesting = false; + spa_bt_transport_set_state(t, td.err ? SPA_BT_TRANSPORT_STATE_ERROR : SPA_BT_TRANSPORT_STATE_ACTIVE); +} +''' +tests = r''' +static struct spa_bt_transport fresh(int state) { + td = (struct transport_data){0}; + error_events = 0; + connect_result = 42; + connect_error = -EINPROGRESS; + return (struct spa_bt_transport){ .backend=&backend, .user_data=&td, + .monitor=&monitor, .fd=-1, .state=state }; +} +int main(void) { + for (int initial = SPA_BT_TRANSPORT_STATE_ERROR; initial <= SPA_BT_TRANSPORT_STATE_IDLE; ++initial) { + struct spa_bt_transport t = fresh(initial); + assert(spa_bt_transport_acquire(&t, false) == 0); + if (t.state != SPA_BT_TRANSPORT_STATE_PENDING) { + fprintf(stderr, "FAIL: asynchronous acquire retained state %d (initial %d)\n", t.state, initial); + return 1; + } + assert(td.requesting && t.acquire_refcount == 1 && t.acquired); + assert(spa_bt_transport_acquire(&t, false) == 0); + assert(t.acquire_refcount == 2 && !error_events); + assert(t.state != SPA_BT_TRANSPORT_STATE_ACTIVE); + td.err = 0; + sco_ready(&t); + assert(t.state == SPA_BT_TRANSPORT_STATE_ACTIVE); + } + struct spa_bt_transport t = fresh(SPA_BT_TRANSPORT_STATE_IDLE); + connect_result = -1; + assert(spa_bt_transport_acquire(&t, false) < 0); + assert(t.state == SPA_BT_TRANSPORT_STATE_ERROR && !t.acquired && error_events == 1); + t = fresh(SPA_BT_TRANSPORT_STATE_IDLE); + t.fd = 42; + assert(spa_bt_transport_acquire(&t, true) == 0); + assert(t.state == SPA_BT_TRANSPORT_STATE_ACTIVE && !error_events); + t = fresh(SPA_BT_TRANSPORT_STATE_ERROR); + assert(spa_bt_transport_acquire(&t, false) == 0); + td.err = -ECONNREFUSED; + sco_ready(&t); + assert(t.state == SPA_BT_TRANSPORT_STATE_ERROR && error_events == 1); + puts("PASS: cold/retry concurrent acquire, delayed readiness, synchronous success, real failures"); +} +''' +source = stub + function(sys.argv[1], 'static int sco_acquire_cb(void *data, bool optional)') +source += function(sys.argv[2], 'int spa_bt_transport_acquire(struct spa_bt_transport *transport, bool optional)') +source += tests +with tempfile.TemporaryDirectory(prefix='stt-sco-unit-') as tmp: + binary = str(pathlib.Path(tmp) / 'test') + subprocess.run(['cc', '-std=c11', '-Wall', '-Wno-unused-variable', '-Wno-unused-parameter', + '-x', 'c', '-', '-o', binary], input=source, text=True, check=True) + sys.exit(subprocess.run([binary]).returncode) diff --git a/diagnostics/bluetooth/tools/btusb.c b/diagnostics/bluetooth/tools/btusb.c new file mode 100644 index 0000000..80e5401 --- /dev/null +++ b/diagnostics/bluetooth/tools/btusb.c @@ -0,0 +1,4739 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * + * Generic Bluetooth USB driver + * + * Copyright (C) 2005-2008 Marcel Holtmann + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "btintel.h" +#include "btbcm.h" +#include "btrtl.h" +#include "btmtk.h" + +#define VERSION "0.8" + +static bool disable_scofix; +static bool force_scofix; +static bool enable_autosuspend = IS_ENABLED(CONFIG_BT_HCIBTUSB_AUTOSUSPEND); +static bool enable_poll_sync = IS_ENABLED(CONFIG_BT_HCIBTUSB_POLL_SYNC); +static bool reset = true; + +static struct usb_driver btusb_driver; + +#define BTUSB_IGNORE BIT(0) +#define BTUSB_DIGIANSWER BIT(1) +#define BTUSB_CSR BIT(2) +#define BTUSB_SNIFFER BIT(3) +#define BTUSB_BCM92035 BIT(4) +#define BTUSB_BROKEN_ISOC BIT(5) +#define BTUSB_WRONG_SCO_MTU BIT(6) +#define BTUSB_ATH3012 BIT(7) +#define BTUSB_INTEL_COMBINED BIT(8) +#define BTUSB_INTEL_BOOT BIT(9) +#define BTUSB_BCM_PATCHRAM BIT(10) +#define BTUSB_MARVELL BIT(11) +#define BTUSB_SWAVE BIT(12) +#define BTUSB_AMP BIT(13) +#define BTUSB_QCA_ROME BIT(14) +#define BTUSB_BCM_APPLE BIT(15) +#define BTUSB_REALTEK BIT(16) +#define BTUSB_BCM2045 BIT(17) +#define BTUSB_IFNUM_2 BIT(18) +#define BTUSB_CW6622 BIT(19) +#define BTUSB_MEDIATEK BIT(20) +#define BTUSB_WIDEBAND_SPEECH BIT(21) +#define BTUSB_INVALID_LE_STATES BIT(22) +#define BTUSB_QCA_WCN6855 BIT(23) +#define BTUSB_INTEL_BROKEN_SHUTDOWN_LED BIT(24) +#define BTUSB_INTEL_BROKEN_INITIAL_NCMD BIT(25) +#define BTUSB_INTEL_NO_WBS_SUPPORT BIT(26) +#define BTUSB_ACTIONS_SEMI BIT(27) +#define BTUSB_BARROT BIT(28) + +static const struct usb_device_id btusb_table[] = { + /* Generic Bluetooth USB device */ + { USB_DEVICE_INFO(0xe0, 0x01, 0x01) }, + + /* Generic Bluetooth AMP device */ + { USB_DEVICE_INFO(0xe0, 0x01, 0x04), .driver_info = BTUSB_AMP }, + + /* Generic Bluetooth USB interface */ + { USB_INTERFACE_INFO(0xe0, 0x01, 0x01) }, + + /* Apple-specific (Broadcom) devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x05ac, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_APPLE | BTUSB_IFNUM_2 }, + + /* MediaTek MT76x0E */ + { USB_DEVICE(0x0e8d, 0x763f) }, + + /* Broadcom SoftSailing reporting vendor specific */ + { USB_DEVICE(0x0a5c, 0x21e1) }, + + /* Apple MacBookPro 7,1 */ + { USB_DEVICE(0x05ac, 0x8213) }, + + /* Apple iMac11,1 */ + { USB_DEVICE(0x05ac, 0x8215) }, + + /* Apple MacBookPro6,2 */ + { USB_DEVICE(0x05ac, 0x8218) }, + + /* Apple MacBookAir3,1, MacBookAir3,2 */ + { USB_DEVICE(0x05ac, 0x821b) }, + + /* Apple MacBookAir4,1 */ + { USB_DEVICE(0x05ac, 0x821f) }, + + /* Apple MacBookPro8,2 */ + { USB_DEVICE(0x05ac, 0x821a) }, + + /* Apple MacMini5,1 */ + { USB_DEVICE(0x05ac, 0x8281) }, + + /* AVM BlueFRITZ! USB v2.0 */ + { USB_DEVICE(0x057c, 0x3800), .driver_info = BTUSB_SWAVE }, + + /* Bluetooth Ultraport Module from IBM */ + { USB_DEVICE(0x04bf, 0x030a) }, + + /* ALPS Modules with non-standard id */ + { USB_DEVICE(0x044e, 0x3001) }, + { USB_DEVICE(0x044e, 0x3002) }, + + /* Ericsson with non-standard id */ + { USB_DEVICE(0x0bdb, 0x1002) }, + + /* Canyon CN-BTU1 with HID interfaces */ + { USB_DEVICE(0x0c10, 0x0000) }, + + /* Broadcom BCM20702B0 (Dynex/Insignia) */ + { USB_DEVICE(0x19ff, 0x0239), .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom BCM43142A0 (Foxconn/Lenovo) */ + { USB_VENDOR_AND_INTERFACE_INFO(0x105b, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom BCM920703 (HTC Vive) */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0bb4, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Foxconn - Hon Hai */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0489, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Lite-On Technology - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x04ca, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom devices with vendor specific id */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0a5c, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* ASUSTek Computer - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0b05, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Belkin F8065bf - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x050d, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* IMC Networks - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x13d3, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Dell Computer - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x413c, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Toshiba Corp - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0930, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Intel Bluetooth USB Bootloader (RAM module) */ + { USB_DEVICE(0x8087, 0x0a5a), + .driver_info = BTUSB_INTEL_BOOT | BTUSB_BROKEN_ISOC }, + + { } /* Terminating entry */ +}; + +MODULE_DEVICE_TABLE(usb, btusb_table); + +static const struct usb_device_id quirks_table[] = { + /* CSR BlueCore devices */ + { USB_DEVICE(0x0a12, 0x0001), .driver_info = BTUSB_CSR }, + + /* Broadcom BCM2033 without firmware */ + { USB_DEVICE(0x0a5c, 0x2033), .driver_info = BTUSB_IGNORE }, + + /* Broadcom BCM2045 devices */ + { USB_DEVICE(0x0a5c, 0x2045), .driver_info = BTUSB_BCM2045 }, + + /* Atheros 3011 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x04f2, 0xaff1), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0cf3, 0x3002), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0cf3, 0xe019), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE }, + + /* Atheros AR9285 Malbec with sflash firmware */ + { USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE }, + + /* Atheros 3012 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe04d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe04e), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe056), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe057), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe05f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe076), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe078), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe095), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04c5, 0x1330), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3005), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3006), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3007), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3008), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300b), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3010), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3014), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3018), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0219), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x021c), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0220), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0227), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0b05, 0x17d0), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x0036), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3008), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311e), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3121), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x817a), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x817b), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe003), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe005), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe006), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3362), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3375), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3393), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3395), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3402), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3408), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3423), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3432), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3472), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3474), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3487), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3490), .driver_info = BTUSB_ATH3012 }, + + /* Atheros AR5BBU12 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe02c), .driver_info = BTUSB_IGNORE }, + + /* Atheros AR5BBU12 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe036), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe03c), .driver_info = BTUSB_ATH3012 }, + + /* QCA ROME chipset */ + { USB_DEVICE(0x0cf3, 0x535b), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe007), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe009), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe010), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe300), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe301), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe360), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe500), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe092), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe09f), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0a2), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3011), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3015), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3016), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x301a), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3021), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3491), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3496), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3501), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + + /* QCA WCN6855 chipset */ + { USB_DEVICE(0x0489, 0xe0c7), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0c9), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ca), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cb), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cc), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ce), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d0), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d6), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0de), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0df), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e1), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e3), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ea), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ec), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3022), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3023), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3024), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a22), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a24), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a26), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a27), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe600), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9108), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9109), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9208), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9209), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9308), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9309), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9408), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9409), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9508), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9509), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9608), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9609), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9f09), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x28de, 0x1401), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + + /* QCA WCN785x chipset */ + { USB_DEVICE(0x0cf3, 0xe700), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0fc), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f3), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe100), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe103), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10a), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10d), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11b), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11c), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11f), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe141), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14a), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14b), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14d), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3623), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3624), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0130), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0131), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0132), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + + /* Broadcom BCM2035 */ + { USB_DEVICE(0x0a5c, 0x2009), .driver_info = BTUSB_BCM92035 }, + { USB_DEVICE(0x0a5c, 0x200a), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2035), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Broadcom BCM2045 */ + { USB_DEVICE(0x0a5c, 0x2039), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2101), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* IBM/Lenovo ThinkPad with Broadcom chip */ + { USB_DEVICE(0x0a5c, 0x201e), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2110), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* HP laptop with Broadcom chip */ + { USB_DEVICE(0x03f0, 0x171d), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Dell laptop with Broadcom chip */ + { USB_DEVICE(0x413c, 0x8126), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Dell Wireless 370 and 410 devices */ + { USB_DEVICE(0x413c, 0x8152), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x413c, 0x8156), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Belkin F8T012 and F8T013 devices */ + { USB_DEVICE(0x050d, 0x0012), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x050d, 0x0013), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Asus WL-BTD202 device */ + { USB_DEVICE(0x0b05, 0x1715), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Kensington Bluetooth USB adapter */ + { USB_DEVICE(0x047d, 0x105e), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* RTX Telecom based adapters with buggy SCO support */ + { USB_DEVICE(0x0400, 0x0807), .driver_info = BTUSB_BROKEN_ISOC }, + { USB_DEVICE(0x0400, 0x080a), .driver_info = BTUSB_BROKEN_ISOC }, + + /* CONWISE Technology based adapters with buggy SCO support */ + { USB_DEVICE(0x0e5e, 0x6622), + .driver_info = BTUSB_BROKEN_ISOC | BTUSB_CW6622}, + + /* Roper Class 1 Bluetooth Dongle (Silicon Wave based) */ + { USB_DEVICE(0x1310, 0x0001), .driver_info = BTUSB_SWAVE }, + + /* Digianswer devices */ + { USB_DEVICE(0x08fd, 0x0001), .driver_info = BTUSB_DIGIANSWER }, + { USB_DEVICE(0x08fd, 0x0002), .driver_info = BTUSB_IGNORE }, + + /* CSR BlueCore Bluetooth Sniffer */ + { USB_DEVICE(0x0a12, 0x0002), + .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, + + /* Frontline ComProbe Bluetooth Sniffer */ + { USB_DEVICE(0x16d3, 0x0002), + .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, + + /* Marvell Bluetooth devices */ + { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL }, + + /* Intel Bluetooth devices */ + { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0026), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0029), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0032), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0033), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0035), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0036), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0037), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0038), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0039), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0040), .driver_info = BTUSB_INTEL_COMBINED }, /* Lizard Peak 2 */ + { USB_DEVICE(0x8087, 0x07da), .driver_info = BTUSB_CSR }, + { USB_DEVICE(0x8087, 0x07dc), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_NO_WBS_SUPPORT | + BTUSB_INTEL_BROKEN_INITIAL_NCMD | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0a2a), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_NO_WBS_SUPPORT | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0a2b), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0aa7), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0aaa), .driver_info = BTUSB_INTEL_COMBINED }, + + /* Other Intel Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x8087, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_IGNORE }, + + /* Realtek 8821CE Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3529), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3533), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8822CE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb00c), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc822), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8822CU Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8851BE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb850), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3600), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3601), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0489, 0xe112), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8851BU Bluetooth devices */ + { USB_DEVICE(0x3625, 0x010b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2001, 0x332a), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x7392, 0xe611), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c4e, 0x0128), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852AE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x2852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x385a), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x4852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x165c), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x4006), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb8, 0xc549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852CE Bluetooth devices */ + { USB_DEVICE(0x04ca, 0x4007), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x1675), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb8, 0xc558), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3587), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3586), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3592), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3612), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe122), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852BE Bluetooth devices */ + { USB_DEVICE(0x0cb8, 0xc559), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x4853), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x887b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xb85b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3570), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3571), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3572), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3591), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe125), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852BT/8852BE-VT Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x8520), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe12f), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3618), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3619), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8922AE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x8922), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xd922), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xd923), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3617), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3616), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe130), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0bda, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_REALTEK }, + + /* MediaTek Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0e8d, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7615E Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3560), .driver_info = BTUSB_MEDIATEK}, + + /* Additional MediaTek MT7663 Bluetooth devices */ + { USB_DEVICE(0x043e, 0x310c), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3801), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7668 Bluetooth devices */ + { USB_DEVICE(0x043e, 0x3109), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7920 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe134), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe135), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3620), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3621), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3622), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe158), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7921 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe0c8), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cd), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e0), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3802), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x0608), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3563), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3564), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3567), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3576), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3578), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3583), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3606), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + /* MediaTek MT7902 Bluetooth devices */ + { USB_DEVICE(0x0e8d, 0x1ede), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3579), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3580), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3594), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3596), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + /* MediaTek MT7922 Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3585), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3610), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* MediaTek MT7922A Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe0d8), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d9), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e4), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f1), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f5), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f6), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe102), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11d), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe152), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe153), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe170), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe174), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3804), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3807), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x38e4), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x223c), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3568), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3584), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3605), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3607), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3614), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3615), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3633), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x35f5, 0x7922), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7925 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe111), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe113), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe118), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11e), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe124), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe139), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe13a), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0fa), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10f), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe110), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe116), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3588), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14e), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14f), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe150), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe151), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x8c38), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3602), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3603), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3604), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3608), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3609), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3613), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3627), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3628), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3630), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x7009), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional Realtek 8723AE Bluetooth devices */ + { USB_DEVICE(0x0930, 0x021d), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3394), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723BE Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe085), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0489, 0xe08b), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x04f2, 0xb49f), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3410), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3416), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3459), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3494), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723BU Bluetooth devices */ + { USB_DEVICE(0x7392, 0xa611), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x2c0a, 0x8761), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723DE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb009), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x2ff8, 0xb011), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8761BUV Bluetooth devices */ + { USB_DEVICE(0x2c4e, 0x0115), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2357, 0x0604), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2357, 0x0607), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0b05, 0x190e), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2550, 0x8761), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x8771), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x6655, 0x8771), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x7392, 0xc611), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2b89, 0x8761), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2b89, 0x6275), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x37ad, 0x0600), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional Realtek 8821AE Bluetooth devices */ + { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3414), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3458), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3461), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3462), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8822BE Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3526), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0b05, 0x185c), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8822CE Bluetooth devices */ + { USB_DEVICE(0x04ca, 0x4005), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x161f), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0b05, 0x18ef), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3548), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3553), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3555), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2ff8, 0x3051), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x1358, 0xc123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb5, 0xc547), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Barrot Technology Bluetooth devices */ + { USB_DEVICE(0x33fa, 0x0010), .driver_info = BTUSB_BARROT }, + { USB_DEVICE(0x33fa, 0x0012), .driver_info = BTUSB_BARROT }, + + /* Actions Semiconductor ATS2851 based devices */ + { USB_DEVICE(0x10d7, 0xb012), .driver_info = BTUSB_ACTIONS_SEMI }, + + /* Silicon Wave based devices */ + { USB_DEVICE(0x0c10, 0x0000), .driver_info = BTUSB_SWAVE }, + + { } /* Terminating entry */ +}; + +/* The Bluetooth USB module build into some devices needs to be reset on resume, + * this is a problem with the platform (likely shutting off all power) not with + * the module itself. So we use a DMI list to match known broken platforms. + */ +static const struct dmi_system_id btusb_needs_reset_resume_table[] = { + { + /* Dell OptiPlex 3060 (QCA ROME device 0cf3:e007) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 3060"), + }, + }, + { + /* Dell XPS 9360 (QCA ROME device 0cf3:e300) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "XPS 13 9360"), + }, + }, + { + /* Dell Inspiron 5565 (QCA ROME device 0cf3:e009) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "Inspiron 5565"), + }, + }, + {} +}; + +struct qca_dump_info { + /* fields for dump collection */ + u16 id_vendor; + u16 id_product; + u32 fw_version; + u32 controller_id; + u32 ram_dump_size; + u16 ram_dump_seqno; +}; + +#define BTUSB_MAX_ISOC_FRAMES 10 + +#define BTUSB_INTR_RUNNING 0 +#define BTUSB_BULK_RUNNING 1 +#define BTUSB_ISOC_RUNNING 2 +#define BTUSB_SUSPENDING 3 +#define BTUSB_DID_ISO_RESUME 4 +#define BTUSB_BOOTLOADER 5 +#define BTUSB_DOWNLOADING 6 +#define BTUSB_FIRMWARE_LOADED 7 +#define BTUSB_FIRMWARE_FAILED 8 +#define BTUSB_BOOTING 9 +#define BTUSB_DIAG_RUNNING 10 +#define BTUSB_OOB_WAKE_ENABLED 11 +#define BTUSB_HW_RESET_ACTIVE 12 +#define BTUSB_TX_WAIT_VND_EVT 13 +#define BTUSB_WAKEUP_AUTOSUSPEND 14 +#define BTUSB_USE_ALT3_FOR_WBS 15 +#define BTUSB_ALT6_CONTINUOUS_TX 16 +#define BTUSB_HW_SSR_ACTIVE 17 + +struct btusb_data { + struct hci_dev *hdev; + struct usb_device *udev; + struct usb_interface *intf; + struct usb_interface *isoc; + struct usb_interface *diag; + unsigned isoc_ifnum; + + unsigned long flags; + + bool poll_sync; + int intr_interval; + struct work_struct work; + struct work_struct waker; + struct delayed_work rx_work; + + struct sk_buff_head acl_q; + + struct usb_anchor deferred; + struct usb_anchor tx_anchor; + int tx_in_flight; + spinlock_t txlock; + + struct usb_anchor intr_anchor; + struct usb_anchor bulk_anchor; + struct usb_anchor isoc_anchor; + struct usb_anchor diag_anchor; + struct usb_anchor ctrl_anchor; + spinlock_t rxlock; + + struct sk_buff *evt_skb; + struct sk_buff *acl_skb; + struct sk_buff *sco_skb; + + struct usb_endpoint_descriptor *intr_ep; + struct usb_endpoint_descriptor *bulk_tx_ep; + struct usb_endpoint_descriptor *bulk_rx_ep; + struct usb_endpoint_descriptor *isoc_tx_ep; + struct usb_endpoint_descriptor *isoc_rx_ep; + struct usb_endpoint_descriptor *diag_tx_ep; + struct usb_endpoint_descriptor *diag_rx_ep; + + struct gpio_desc *reset_gpio; + + __u8 cmdreq_type; + __u8 cmdreq; + + unsigned int sco_num; + unsigned int air_mode; + bool usb_alt6_packet_flow; + int isoc_altsetting; + int suspend_count; + + int (*recv_event)(struct hci_dev *hdev, struct sk_buff *skb); + int (*recv_acl)(struct hci_dev *hdev, struct sk_buff *skb); + int (*recv_bulk)(struct btusb_data *data, void *buffer, int count); + + int (*setup_on_usb)(struct hci_dev *hdev); + + int (*suspend)(struct hci_dev *hdev); + int (*resume)(struct hci_dev *hdev); + int (*disconnect)(struct hci_dev *hdev); + + int oob_wake_irq; /* irq for out-of-band wake-on-bt */ + + struct qca_dump_info qca_dump; +}; + +static void btusb_reset(struct hci_dev *hdev) +{ + struct btusb_data *data; + int err; + + data = hci_get_drvdata(hdev); + /* This is not an unbalanced PM reference since the device will reset */ + err = usb_autopm_get_interface(data->intf); + if (err) { + bt_dev_err(hdev, "Failed usb_autopm_get_interface: %d", err); + return; + } + + bt_dev_err(hdev, "Resetting usb device."); + usb_queue_reset_device(data->intf); +} + +static void btusb_intel_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + struct btintel_data *intel_data = hci_get_priv(hdev); + + if (intel_data->acpi_reset_method) { + if (test_and_set_bit(INTEL_ACPI_RESET_ACTIVE, intel_data->flags)) { + bt_dev_err(hdev, "acpi: last reset failed ? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Initiating acpi reset method"); + /* If ACPI reset method fails, lets try with legacy GPIO + * toggling + */ + if (!intel_data->acpi_reset_method(hdev)) { + return; + } + } + + if (!reset_gpio) { + btusb_reset(hdev); + return; + } + + /* + * Toggle the hard reset line if the platform provides one. The reset + * is going to yank the device off the USB and then replug. So doing + * once is enough. The cleanup is handled correctly on the way out + * (standard USB disconnect), and the new device is detected cleanly + * and bound to the driver again like it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Initiating HW reset via gpio"); + gpiod_set_value_cansleep(reset_gpio, 1); + msleep(100); + gpiod_set_value_cansleep(reset_gpio, 0); +} + +#define RTK_DEVCOREDUMP_CODE_MEMDUMP 0x01 +#define RTK_DEVCOREDUMP_CODE_HW_ERR 0x02 +#define RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT 0x03 + +#define RTK_SUB_EVENT_CODE_COREDUMP 0x34 + +struct rtk_dev_coredump_hdr { + u8 type; + u8 code; + u8 reserved[2]; +} __packed; + +static inline void btusb_rtl_alloc_devcoredump(struct hci_dev *hdev, + struct rtk_dev_coredump_hdr *hdr, u8 *buf, u32 len) +{ + struct sk_buff *skb; + + skb = alloc_skb(len + sizeof(*hdr), GFP_ATOMIC); + if (!skb) + return; + + skb_put_data(skb, hdr, sizeof(*hdr)); + if (len) + skb_put_data(skb, buf, len); + + if (!hci_devcd_init(hdev, skb->len)) { + hci_devcd_append(hdev, skb); + hci_devcd_complete(hdev); + } else { + bt_dev_err(hdev, "RTL: Failed to generate devcoredump"); + kfree_skb(skb); + } +} + +static void btusb_rtl_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + struct rtk_dev_coredump_hdr hdr = { + .type = RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT, + }; + + btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); + + if (!reset_gpio) { + btusb_reset(hdev); + return; + } + + /* Toggle the hard reset line. The Realtek device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Reset Realtek device via gpio"); + gpiod_set_value_cansleep(reset_gpio, 1); + msleep(200); + gpiod_set_value_cansleep(reset_gpio, 0); +} + +static void btusb_rtl_hw_error(struct hci_dev *hdev, u8 code) +{ + struct rtk_dev_coredump_hdr hdr = { + .type = RTK_DEVCOREDUMP_CODE_HW_ERR, + .code = code, + }; + + bt_dev_err(hdev, "RTL: hw err, trigger devcoredump (%d)", code); + + btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); +} + +static void btusb_qca_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + + if (test_bit(BTUSB_HW_SSR_ACTIVE, &data->flags)) { + bt_dev_info(hdev, "Ramdump in progress, defer reset"); + return; + } + + if (reset_gpio) { + bt_dev_err(hdev, "Reset qca device via bt_en gpio"); + + /* Toggle the hard reset line. The qca bt device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + gpiod_set_value_cansleep(reset_gpio, 0); + msleep(200); + gpiod_set_value_cansleep(reset_gpio, 1); + + return; + } + + btusb_reset(hdev); +} + +static u8 btusb_classify_qca_pkt_type(struct hci_dev *hdev, struct sk_buff *skb) +{ + /* Some Qualcomm controllers, e.g., QCNFA765 with WCN6855 chip, send debug + * packets as ACL frames with connection handle 0x2EDC. These are not real + * ACL packets and should be reclassified as HCI_DIAG_PKT to prevent + * "ACL packet for unknown connection handle 3804" errors. + */ + if (skb->len >= 2) { + u16 handle = get_unaligned_le16(skb->data); + + if (handle == 0x2EDC) + return HCI_DIAG_PKT; + } + + /* Use default packet type for other packets */ + return hci_skb_pkt_type(skb); +} + +static inline void btusb_free_frags(struct btusb_data *data) +{ + unsigned long flags; + + spin_lock_irqsave(&data->rxlock, flags); + + dev_kfree_skb_irq(data->evt_skb); + data->evt_skb = NULL; + + dev_kfree_skb_irq(data->acl_skb); + data->acl_skb = NULL; + + dev_kfree_skb_irq(data->sco_skb); + data->sco_skb = NULL; + + spin_unlock_irqrestore(&data->rxlock, flags); +} + +static int btusb_recv_event(struct btusb_data *data, struct sk_buff *skb) +{ + if (data->intr_interval) { + /* Trigger dequeue immediately if an event is received */ + schedule_delayed_work(&data->rx_work, 0); + } + + return data->recv_event(data->hdev, skb); +} + +static int btusb_recv_intr(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->evt_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_EVENT_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_EVENT_PKT; + hci_skb_expect(skb) = HCI_EVENT_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_EVENT_HDR_SIZE) { + /* Complete event header */ + hci_skb_expect(skb) = hci_event_hdr(skb)->plen; + + if (skb_tailroom(skb) < hci_skb_expect(skb)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Each chunk should correspond to at least 1 or more + * events so if there are still bytes left that doesn't + * constitute a new event this is likely a bug in the + * controller. + */ + if (count && count < HCI_EVENT_HDR_SIZE) { + bt_dev_warn(data->hdev, + "Unexpected continuation: %d bytes", + count); + count = 0; + } + + /* Complete frame */ + btusb_recv_event(data, skb); + skb = NULL; + } + } + + data->evt_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static int btusb_recv_acl(struct btusb_data *data, struct sk_buff *skb) +{ + /* Only queue ACL packet if intr_interval is set as it means + * force_poll_sync has been enabled. + */ + if (!data->intr_interval) + return data->recv_acl(data->hdev, skb); + + skb_queue_tail(&data->acl_q, skb); + schedule_delayed_work(&data->rx_work, data->intr_interval); + + return 0; +} + +static int btusb_recv_bulk(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->acl_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_FRAME_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT; + hci_skb_expect(skb) = HCI_ACL_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_ACL_HDR_SIZE) { + __le16 dlen = hci_acl_hdr(skb)->dlen; + + /* Complete ACL header */ + hci_skb_expect(skb) = __le16_to_cpu(dlen); + + if (skb_tailroom(skb) < hci_skb_expect(skb)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Complete frame */ + btusb_recv_acl(data, skb); + skb = NULL; + } + } + + data->acl_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static bool btusb_validate_sco_handle(struct hci_dev *hdev, + struct hci_sco_hdr *hdr) +{ + __u16 handle; + + if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) + // Can't validate, userspace controls everything. + return true; + + /* + * USB isochronous transfers are not designed to be reliable and may + * lose fragments. When this happens, the next first fragment + * encountered might actually be a continuation fragment. + * Validate the handle to detect it and drop it, or else the upper + * layer will get garbage for a while. + */ + + handle = hci_handle(__le16_to_cpu(hdr->handle)); + + switch (hci_conn_lookup_type(hdev, handle)) { + case SCO_LINK: + case ESCO_LINK: + return true; + default: + return false; + } +} + +static int btusb_recv_isoc(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->sco_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_SCO_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_SCODATA_PKT; + hci_skb_expect(skb) = HCI_SCO_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_SCO_HDR_SIZE) { + /* Complete SCO header */ + struct hci_sco_hdr *hdr = hci_sco_hdr(skb); + + hci_skb_expect(skb) = hdr->dlen; + + if (skb_tailroom(skb) < hci_skb_expect(skb) || + !btusb_validate_sco_handle(data->hdev, hdr)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Complete frame */ + hci_recv_frame(data->hdev, skb); + skb = NULL; + } + } + + data->sco_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static void btusb_intr_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + hdev->stat.byte_rx += urb->actual_length; + + if (btusb_recv_intr(data, urb->transfer_buffer, + urb->actual_length) < 0) { + bt_dev_err(hdev, "corrupted event packet"); + hdev->stat.err_rx++; + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_INTR_RUNNING, &data->flags)) + return; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->intr_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + if (err != -EPERM) + hci_cmd_sync_cancel(hdev, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size; + + BT_DBG("%s", hdev->name); + + if (!data->intr_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + if (le16_to_cpu(data->udev->descriptor.idVendor) == 0x0a12 && + le16_to_cpu(data->udev->descriptor.idProduct) == 0x0001) + /* Fake CSR devices don't seem to support sort-transter */ + size = le16_to_cpu(data->intr_ep->wMaxPacketSize); + else + /* Use maximum HCI Event size so the USB stack handles + * ZPL/short-transfer automatically. + */ + size = HCI_MAX_EVENT_SIZE; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvintpipe(data->udev, data->intr_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, buf, size, + btusb_intr_complete, hdev, data->intr_ep->bInterval); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_anchor_urb(urb, &data->intr_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + if (err != -EPERM) + hci_cmd_sync_cancel(hdev, -err); + usb_unanchor_urb(urb); + } + + /* Only initialize intr_interval if URB poll sync is enabled */ + if (!data->poll_sync) + goto done; + + /* The units are frames (milliseconds) for full and low speed devices, + * and microframes (1/8 millisecond) for highspeed and SuperSpeed + * devices. + * + * This is done once on open/resume so it shouldn't change even if + * force_poll_sync changes. + */ + switch (urb->dev->speed) { + case USB_SPEED_SUPER_PLUS: + case USB_SPEED_SUPER: /* units are 125us */ + data->intr_interval = usecs_to_jiffies(urb->interval * 125); + break; + default: + data->intr_interval = msecs_to_jiffies(urb->interval); + break; + } + +done: + usb_free_urb(urb); + + return err; +} + +static void btusb_bulk_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + hdev->stat.byte_rx += urb->actual_length; + + if (data->recv_bulk(data, urb->transfer_buffer, + urb->actual_length) < 0) { + bt_dev_err(hdev, "corrupted ACL packet"); + hdev->stat.err_rx++; + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_BULK_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->bulk_anchor); + usb_mark_last_busy(data->udev); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_bulk_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size = HCI_MAX_FRAME_SIZE; + + BT_DBG("%s", hdev->name); + + if (!data->bulk_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvbulkpipe(data->udev, data->bulk_rx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, + btusb_bulk_complete, hdev); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->bulk_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_isoc_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int i, err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + for (i = 0; i < urb->number_of_packets; i++) { + unsigned int offset = urb->iso_frame_desc[i].offset; + unsigned int length = urb->iso_frame_desc[i].actual_length; + + if (urb->iso_frame_desc[i].status) + continue; + + hdev->stat.byte_rx += length; + + if (btusb_recv_isoc(data, urb->transfer_buffer + offset, + length) < 0) { + bt_dev_err(hdev, "corrupted SCO packet"); + hdev->stat.err_rx++; + } + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_ISOC_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->isoc_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static inline void __fill_isoc_descriptor_msbc(struct urb *urb, int len, + int mtu, struct btusb_data *data) +{ + int i = 0, offset = 0; + unsigned int interval; + + BT_DBG("len %d mtu %d", len, mtu); + + /* For mSBC ALT 6 settings some chips need to transmit the data + * continuously without the zero length of USB packets. + */ + if (test_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags)) + goto ignore_usb_alt6_packet_flow; + + /* For mSBC ALT 6 setting the host will send the packet at continuous + * flow. As per core spec 5, vol 4, part B, table 2.1. For ALT setting + * 6 the HCI PACKET INTERVAL should be 7.5ms for every usb packets. + * To maintain the rate we send 63bytes of usb packets alternatively for + * 7ms and 8ms to maintain the rate as 7.5ms. + */ + if (data->usb_alt6_packet_flow) { + interval = 7; + data->usb_alt6_packet_flow = false; + } else { + interval = 6; + data->usb_alt6_packet_flow = true; + } + + for (i = 0; i < interval; i++) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = offset; + } + +ignore_usb_alt6_packet_flow: + if (len && i < BTUSB_MAX_ISOC_FRAMES) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = len; + i++; + } + + urb->number_of_packets = i; +} + +static inline void __fill_isoc_descriptor(struct urb *urb, int len, int mtu) +{ + int i, offset = 0; + + BT_DBG("len %d mtu %d", len, mtu); + + for (i = 0; i < BTUSB_MAX_ISOC_FRAMES && len >= mtu; + i++, offset += mtu, len -= mtu) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = mtu; + } + + if (len && i < BTUSB_MAX_ISOC_FRAMES) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = len; + i++; + } + + urb->number_of_packets = i; +} + +static int btusb_submit_isoc_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size; + + BT_DBG("%s", hdev->name); + + if (!data->isoc_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, mem_flags); + if (!urb) + return -ENOMEM; + + size = le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize) * + BTUSB_MAX_ISOC_FRAMES; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvisocpipe(data->udev, data->isoc_rx_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, buf, size, btusb_isoc_complete, + hdev, data->isoc_rx_ep->bInterval); + + urb->transfer_flags = URB_FREE_BUFFER | URB_ISO_ASAP; + + __fill_isoc_descriptor(urb, size, + le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize)); + + usb_anchor_urb(urb, &data->isoc_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_diag_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (urb->status == 0) { + struct sk_buff *skb; + + skb = bt_skb_alloc(urb->actual_length, GFP_ATOMIC); + if (skb) { + skb_put_data(skb, urb->transfer_buffer, + urb->actual_length); + hci_recv_diag(hdev, skb); + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_DIAG_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->diag_anchor); + usb_mark_last_busy(data->udev); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_diag_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size = HCI_MAX_FRAME_SIZE; + + BT_DBG("%s", hdev->name); + + if (!data->diag_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvbulkpipe(data->udev, data->diag_rx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, + btusb_diag_complete, hdev); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->diag_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_tx_complete(struct urb *urb) +{ + struct sk_buff *skb = urb->context; + struct hci_dev *hdev = (struct hci_dev *)skb->dev; + struct btusb_data *data = hci_get_drvdata(hdev); + unsigned long flags; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (!urb->status) { + hdev->stat.byte_tx += urb->transfer_buffer_length; + } else { + if (hci_skb_pkt_type(skb) == HCI_COMMAND_PKT) + hci_cmd_sync_cancel(hdev, -urb->status); + hdev->stat.err_tx++; + } + +done: + spin_lock_irqsave(&data->txlock, flags); + data->tx_in_flight--; + spin_unlock_irqrestore(&data->txlock, flags); + + kfree(urb->setup_packet); + + kfree_skb(skb); +} + +static void btusb_isoc_tx_complete(struct urb *urb) +{ + struct sk_buff *skb = urb->context; + struct hci_dev *hdev = (struct hci_dev *)skb->dev; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (!urb->status) + hdev->stat.byte_tx += urb->transfer_buffer_length; + else + hdev->stat.err_tx++; + +done: + kfree(urb->setup_packet); + + kfree_skb(skb); +} + +static int btusb_open(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s", hdev->name); + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + return err; + + /* Patching USB firmware files prior to starting any URBs of HCI path + * It is more safe to use USB bulk channel for downloading USB patch + */ + if (data->setup_on_usb) { + err = data->setup_on_usb(hdev); + if (err < 0) + goto setup_fail; + } + + data->intf->needs_remote_wakeup = 1; + + if (test_and_set_bit(BTUSB_INTR_RUNNING, &data->flags)) + goto done; + + err = btusb_submit_intr_urb(hdev, GFP_KERNEL); + if (err < 0) + goto failed; + + err = btusb_submit_bulk_urb(hdev, GFP_KERNEL); + if (err < 0) { + usb_kill_anchored_urbs(&data->intr_anchor); + goto failed; + } + + set_bit(BTUSB_BULK_RUNNING, &data->flags); + btusb_submit_bulk_urb(hdev, GFP_KERNEL); + + if (data->diag) { + if (!btusb_submit_diag_urb(hdev, GFP_KERNEL)) + set_bit(BTUSB_DIAG_RUNNING, &data->flags); + } + +done: + usb_autopm_put_interface(data->intf); + return 0; + +failed: + clear_bit(BTUSB_INTR_RUNNING, &data->flags); +setup_fail: + usb_autopm_put_interface(data->intf); + return err; +} + +static void btusb_stop_traffic(struct btusb_data *data) +{ + usb_kill_anchored_urbs(&data->intr_anchor); + usb_kill_anchored_urbs(&data->bulk_anchor); + usb_kill_anchored_urbs(&data->isoc_anchor); + usb_kill_anchored_urbs(&data->diag_anchor); + usb_kill_anchored_urbs(&data->ctrl_anchor); +} + +static int btusb_close(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s", hdev->name); + + cancel_delayed_work(&data->rx_work); + cancel_work_sync(&data->work); + cancel_work_sync(&data->waker); + + skb_queue_purge(&data->acl_q); + + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + clear_bit(BTUSB_BULK_RUNNING, &data->flags); + clear_bit(BTUSB_INTR_RUNNING, &data->flags); + clear_bit(BTUSB_DIAG_RUNNING, &data->flags); + + btusb_stop_traffic(data); + btusb_free_frags(data); + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + goto failed; + + data->intf->needs_remote_wakeup = 0; + + /* Enable remote wake up for auto-suspend */ + if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) + data->intf->needs_remote_wakeup = 1; + + usb_autopm_put_interface(data->intf); + +failed: + usb_scuttle_anchored_urbs(&data->deferred); + return 0; +} + +static int btusb_flush(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + BT_DBG("%s", hdev->name); + + cancel_delayed_work(&data->rx_work); + + skb_queue_purge(&data->acl_q); + + usb_kill_anchored_urbs(&data->tx_anchor); + btusb_free_frags(data); + + return 0; +} + +static struct urb *alloc_ctrl_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_ctrlrequest *dr; + struct urb *urb; + unsigned int pipe; + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + dr = kmalloc_obj(*dr); + if (!dr) { + usb_free_urb(urb); + return ERR_PTR(-ENOMEM); + } + + dr->bRequestType = data->cmdreq_type; + dr->bRequest = data->cmdreq; + dr->wIndex = 0; + dr->wValue = 0; + dr->wLength = __cpu_to_le16(skb->len); + + pipe = usb_sndctrlpipe(data->udev, 0x00); + + usb_fill_control_urb(urb, data->udev, pipe, (void *)dr, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static struct urb *alloc_bulk_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned int pipe; + + if (!data->bulk_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + pipe = usb_sndbulkpipe(data->udev, data->bulk_tx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static struct urb *alloc_isoc_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned int pipe; + + if (!data->isoc_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + pipe = usb_sndisocpipe(data->udev, data->isoc_tx_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_isoc_tx_complete, + skb, data->isoc_tx_ep->bInterval); + + urb->transfer_flags = URB_ISO_ASAP; + + if (data->isoc_altsetting == 6) + __fill_isoc_descriptor_msbc(urb, skb->len, + le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize), + data); + else + __fill_isoc_descriptor(urb, skb->len, + le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize)); + skb->dev = (void *)hdev; + + return urb; +} + +static int submit_tx_urb(struct hci_dev *hdev, struct urb *urb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + usb_anchor_urb(urb, &data->tx_anchor); + + err = usb_submit_urb(urb, GFP_KERNEL); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + kfree(urb->setup_packet); + usb_unanchor_urb(urb); + } else { + usb_mark_last_busy(data->udev); + } + + usb_free_urb(urb); + return err; +} + +static int submit_or_queue_tx_urb(struct hci_dev *hdev, struct urb *urb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + unsigned long flags; + bool suspending; + + spin_lock_irqsave(&data->txlock, flags); + suspending = test_bit(BTUSB_SUSPENDING, &data->flags); + if (!suspending) + data->tx_in_flight++; + spin_unlock_irqrestore(&data->txlock, flags); + + if (!suspending) + return submit_tx_urb(hdev, urb); + + usb_anchor_urb(urb, &data->deferred); + schedule_work(&data->waker); + + usb_free_urb(urb); + return 0; +} + +static int btusb_send_frame(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + switch (hci_skb_pkt_type(skb)) { + case HCI_COMMAND_PKT: + urb = alloc_ctrl_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.cmd_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_ACLDATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.acl_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_SCODATA_PKT: + if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && + hci_conn_num(hdev, SCO_LINK) < 1) + return -ENODEV; + + urb = alloc_isoc_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.sco_tx++; + return submit_tx_urb(hdev, urb); + + case HCI_ISODATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } + + return -EILSEQ; +} + +static void btusb_notify(struct hci_dev *hdev, unsigned int evt) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int sco_num = hci_conn_num(hdev, SCO_LINK); + + BT_DBG("%s evt %d", hdev->name, evt); + + switch (evt) { + case HCI_NOTIFY_ENABLE_SCO_CVSD: + case HCI_NOTIFY_ENABLE_SCO_TRANSP: + /* A (e)SCO link just came up: program the isochronous + * alternate setting for its air mode, even if the link was + * already counted while it was still being set up. + */ + data->sco_num = sco_num; + data->air_mode = evt; + schedule_work(&data->work); + break; + default: + /* hci_conn_num() also counts (e)SCO links that are still + * being set up, and only the ENABLE_SCO_* notifications + * carry an air mode. Any other event may only tear the + * isochronous interface down or adjust it for fewer links; + * a pending link is handled once it is enabled. + */ + if (sco_num < data->sco_num) { + data->sco_num = sco_num; + schedule_work(&data->work); + } + break; + } +} + +static inline int __set_isoc_interface(struct hci_dev *hdev, int altsetting) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_interface *intf = data->isoc; + struct usb_endpoint_descriptor *ep_desc; + int i, err; + + if (!data->isoc) + return -ENODEV; + + err = usb_set_interface(data->udev, data->isoc_ifnum, altsetting); + if (err < 0) { + bt_dev_err(hdev, "setting interface failed (%d)", -err); + return err; + } + + data->isoc_altsetting = altsetting; + + data->isoc_tx_ep = NULL; + data->isoc_rx_ep = NULL; + + for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) { + ep_desc = &intf->cur_altsetting->endpoint[i].desc; + + if (!data->isoc_tx_ep && usb_endpoint_is_isoc_out(ep_desc)) { + data->isoc_tx_ep = ep_desc; + continue; + } + + if (!data->isoc_rx_ep && usb_endpoint_is_isoc_in(ep_desc)) { + data->isoc_rx_ep = ep_desc; + continue; + } + } + + if (!data->isoc_tx_ep || !data->isoc_rx_ep) { + bt_dev_err(hdev, "invalid SCO descriptors"); + return -ENODEV; + } + + return 0; +} + +static int btusb_switch_alt_setting(struct hci_dev *hdev, int new_alts) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + if (data->isoc_altsetting != new_alts) { + unsigned long flags; + + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + usb_kill_anchored_urbs(&data->isoc_anchor); + + /* When isochronous alternate setting needs to be + * changed, because SCO connection has been added + * or removed, a packet fragment may be left in the + * reassembling state. This could lead to wrongly + * assembled fragments. + * + * Clear outstanding fragment when selecting a new + * alternate setting. + */ + spin_lock_irqsave(&data->rxlock, flags); + dev_kfree_skb_irq(data->sco_skb); + data->sco_skb = NULL; + spin_unlock_irqrestore(&data->rxlock, flags); + + err = __set_isoc_interface(hdev, new_alts); + if (err < 0) + return err; + } + + if (!test_and_set_bit(BTUSB_ISOC_RUNNING, &data->flags)) { + if (btusb_submit_isoc_urb(hdev, GFP_KERNEL) < 0) + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + else + btusb_submit_isoc_urb(hdev, GFP_KERNEL); + } + + return 0; +} + +static struct usb_host_interface *btusb_find_altsetting(struct btusb_data *data, + int alt) +{ + struct usb_interface *intf = data->isoc; + int i; + + BT_DBG("Looking for Alt no :%d", alt); + + if (!intf) + return NULL; + + for (i = 0; i < intf->num_altsetting; i++) { + if (intf->altsetting[i].desc.bAlternateSetting == alt) + return &intf->altsetting[i]; + } + + return NULL; +} + +static void btusb_work(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, work); + struct hci_dev *hdev = data->hdev; + int new_alts = 0; + int err; + + if (data->sco_num > 0) { + if (!test_bit(BTUSB_DID_ISO_RESUME, &data->flags)) { + err = usb_autopm_get_interface(data->isoc ? data->isoc : data->intf); + if (err < 0) { + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + usb_kill_anchored_urbs(&data->isoc_anchor); + return; + } + + set_bit(BTUSB_DID_ISO_RESUME, &data->flags); + } + + if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_CVSD) { + if (hdev->voice_setting & 0x0020) { + static const int alts[3] = { 2, 4, 5 }; + unsigned int sco_idx; + + sco_idx = min_t(unsigned int, data->sco_num - 1, + ARRAY_SIZE(alts) - 1); + new_alts = alts[sco_idx]; + } else { + new_alts = data->sco_num; + } + } else if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_TRANSP) { + /* Bluetooth USB spec recommends alt 6 (63 bytes), but + * many adapters do not support it. Alt 1 appears to + * work for all adapters that do not have alt 6, and + * which work with WBS at all. Some devices prefer + * alt 3 (HCI payload >= 60 Bytes let air packet + * data satisfy 60 bytes), requiring + * MTU >= 3 (packets) * 25 (size) - 3 (headers) = 72 + * see also Core spec 5, vol 4, B 2.1.1 & Table 2.1. + */ + if (btusb_find_altsetting(data, 6)) + new_alts = 6; + else if (btusb_find_altsetting(data, 3) && + hdev->sco_mtu >= 72 && + test_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags)) + new_alts = 3; + else + new_alts = 1; + } + + if (btusb_switch_alt_setting(hdev, new_alts) < 0) + bt_dev_err(hdev, "set USB alt:(%d) failed!", new_alts); + } else { + usb_kill_anchored_urbs(&data->isoc_anchor); + + if (test_and_clear_bit(BTUSB_ISOC_RUNNING, &data->flags)) + __set_isoc_interface(hdev, 0); + + if (test_and_clear_bit(BTUSB_DID_ISO_RESUME, &data->flags)) + usb_autopm_put_interface(data->isoc ? data->isoc : data->intf); + } +} + +static void btusb_waker(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, waker); + int err; + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + return; + + usb_autopm_put_interface(data->intf); +} + +static void btusb_rx_work(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, + rx_work.work); + struct sk_buff *skb; + + /* Dequeue ACL data received during the interval */ + while ((skb = skb_dequeue(&data->acl_q))) + data->recv_acl(data->hdev, skb); +} + +static int btusb_setup_bcm92035(struct hci_dev *hdev) +{ + struct sk_buff *skb; + u8 val = 0x00; + + BT_DBG("%s", hdev->name); + + skb = __hci_cmd_sync(hdev, 0xfc3b, 1, &val, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) + bt_dev_err(hdev, "BCM92035 command failed (%ld)", PTR_ERR(skb)); + else + kfree_skb(skb); + + return 0; +} + +static int btusb_setup_csr(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + u16 bcdDevice = le16_to_cpu(data->udev->descriptor.bcdDevice); + struct hci_rp_read_local_version *rp; + struct sk_buff *skb; + bool is_fake = false; + int ret; + + BT_DBG("%s", hdev->name); + + skb = __hci_cmd_sync(hdev, HCI_OP_READ_LOCAL_VERSION, 0, NULL, + HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + int err = PTR_ERR(skb); + + bt_dev_err(hdev, "CSR: Local version failed (%d)", err); + return err; + } + + rp = skb_pull_data(skb, sizeof(*rp)); + if (!rp) { + bt_dev_err(hdev, "CSR: Local version length mismatch"); + kfree_skb(skb); + return -EIO; + } + + bt_dev_info(hdev, "CSR: Setting up dongle with HCI ver=%u rev=%04x", + rp->hci_ver, le16_to_cpu(rp->hci_rev)); + + bt_dev_info(hdev, "LMP ver=%u subver=%04x; manufacturer=%u", + rp->lmp_ver, le16_to_cpu(rp->lmp_subver), + le16_to_cpu(rp->manufacturer)); + + /* Detect a wide host of Chinese controllers that aren't CSR. + * + * Known fake bcdDevices: 0x0100, 0x0134, 0x1915, 0x2520, 0x7558, 0x8891 + * + * The main thing they have in common is that these are really popular low-cost + * options that support newer Bluetooth versions but rely on heavy VID/PID + * squatting of this poor old Bluetooth 1.1 device. Even sold as such. + * + * We detect actual CSR devices by checking that the HCI manufacturer code + * is Cambridge Silicon Radio (10) and ensuring that LMP sub-version and + * HCI rev values always match. As they both store the firmware number. + */ + if (le16_to_cpu(rp->manufacturer) != 10 || + le16_to_cpu(rp->hci_rev) != le16_to_cpu(rp->lmp_subver)) + is_fake = true; + + /* Known legit CSR firmware build numbers and their supported BT versions: + * - 1.1 (0x1) -> 0x0073, 0x020d, 0x033c, 0x034e + * - 1.2 (0x2) -> 0x04d9, 0x0529 + * - 2.0 (0x3) -> 0x07a6, 0x07ad, 0x0c5c + * - 2.1 (0x4) -> 0x149c, 0x1735, 0x1899 (0x1899 is a BlueCore4-External) + * - 4.0 (0x6) -> 0x1d86, 0x2031, 0x22bb + * + * e.g. Real CSR dongles with LMP subversion 0x73 are old enough that + * support BT 1.1 only; so it's a dead giveaway when some + * third-party BT 4.0 dongle reuses it. + */ + else if (le16_to_cpu(rp->lmp_subver) <= 0x034e && + rp->hci_ver > BLUETOOTH_VER_1_1) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x0529 && + rp->hci_ver > BLUETOOTH_VER_1_2) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x0c5c && + rp->hci_ver > BLUETOOTH_VER_2_0) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x1899 && + rp->hci_ver > BLUETOOTH_VER_2_1) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x22bb && + rp->hci_ver > BLUETOOTH_VER_4_0) + is_fake = true; + + /* Other clones which beat all the above checks */ + else if (bcdDevice == 0x0134 && + le16_to_cpu(rp->lmp_subver) == 0x0c5c && + rp->hci_ver == BLUETOOTH_VER_2_0) + is_fake = true; + + if (is_fake) { + bt_dev_warn(hdev, "CSR: Unbranded CSR clone detected; adding workarounds and force-suspending once..."); + + /* Generally these clones have big discrepancies between + * advertised features and what's actually supported. + * Probably will need to be expanded in the future; + * without these the controller will lock up. + */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL); + hci_set_quirk(hdev, HCI_QUIRK_NO_SUSPEND_NOTIFIER); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_VOICE_SETTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_PAGE_SCAN_TYPE); + + /* Clear the reset quirk since this is not an actual + * early Bluetooth 1.1 device from CSR. + */ + hci_clear_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + hci_clear_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + + /* + * Special workaround for these BT 4.0 chip clones, and potentially more: + * + * - 0x0134: a Barrot 8041a02 (HCI rev: 0x0810 sub: 0x1012) + * - 0x7558: IC markings FR3191AHAL 749H15143 (HCI rev/sub-version: 0x0709) + * + * These controllers are really messed-up. + * + * 1. Their bulk RX endpoint will never report any data unless + * the device was suspended at least once (yes, really). + * 2. They will not wakeup when autosuspended and receiving data + * on their bulk RX endpoint from e.g. a keyboard or mouse + * (IOW remote-wakeup support is broken for the bulk endpoint). + * + * To fix 1. enable runtime-suspend, force-suspend the + * HCI and then wake-it up by disabling runtime-suspend. + * + * To fix 2. clear the HCI's can_wake flag, this way the HCI + * will still be autosuspended when it is not open. + * + * -- + * + * Because these are widespread problems we prefer generic solutions; so + * apply this initialization quirk to every controller that gets here, + * it should be harmless. The alternative is to not work at all. + */ + pm_runtime_allow(&data->udev->dev); + + ret = pm_runtime_suspend(&data->udev->dev); + if (ret >= 0) + msleep(200); + else + bt_dev_warn(hdev, "CSR: Couldn't suspend the device for our Barrot 8041a02 receive-issue workaround"); + + pm_runtime_forbid(&data->udev->dev); + + device_set_wakeup_capable(&data->udev->dev, false); + + /* Re-enable autosuspend if this was requested */ + if (enable_autosuspend) + usb_enable_autosuspend(data->udev); + } + + kfree_skb(skb); + + return 0; +} + +static int inject_cmd_complete(struct hci_dev *hdev, __u16 opcode) +{ + struct sk_buff *skb; + struct hci_event_hdr *hdr; + struct hci_ev_cmd_complete *evt; + + skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL); + if (!skb) + return -ENOMEM; + + hdr = skb_put(skb, sizeof(*hdr)); + hdr->evt = HCI_EV_CMD_COMPLETE; + hdr->plen = sizeof(*evt) + 1; + + evt = skb_put(skb, sizeof(*evt)); + evt->ncmd = 0x01; + evt->opcode = cpu_to_le16(opcode); + + skb_put_u8(skb, 0x00); + + hci_skb_pkt_type(skb) = HCI_EVENT_PKT; + + return hci_recv_frame(hdev, skb); +} + +static int btusb_recv_bulk_intel(struct btusb_data *data, void *buffer, + int count) +{ + struct hci_dev *hdev = data->hdev; + + /* When the device is in bootloader mode, then it can send + * events via the bulk endpoint. These events are treated the + * same way as the ones received from the interrupt endpoint. + */ + if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) + return btusb_recv_intr(data, buffer, count); + + return btusb_recv_bulk(data, buffer, count); +} + +static int btusb_send_frame_intel(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + switch (hci_skb_pkt_type(skb)) { + case HCI_COMMAND_PKT: + if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) { + struct hci_command_hdr *cmd = (void *)skb->data; + __u16 opcode = le16_to_cpu(cmd->opcode); + + /* When in bootloader mode and the command 0xfc09 + * is received, it needs to be send down the + * bulk endpoint. So allocate a bulk URB instead. + */ + if (opcode == 0xfc09) + urb = alloc_bulk_urb(hdev, skb); + else + urb = alloc_ctrl_urb(hdev, skb); + + /* When the BTINTEL_HCI_OP_RESET command is issued to + * boot into the operational firmware, it will actually + * not send a command complete event. To keep the flow + * control working inject that event here. + */ + if (opcode == BTINTEL_HCI_OP_RESET) + inject_cmd_complete(hdev, opcode); + } else { + urb = alloc_ctrl_urb(hdev, skb); + } + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.cmd_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_ACLDATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.acl_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_SCODATA_PKT: + if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && + hci_conn_num(hdev, SCO_LINK) < 1) + return -ENODEV; + + urb = alloc_isoc_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.sco_tx++; + return submit_tx_urb(hdev, urb); + + case HCI_ISODATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } + + return -EILSEQ; +} + +static int btusb_setup_realtek(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int ret; + + ret = btrtl_setup_realtek(hdev); + + if (btrealtek_test_flag(data->hdev, REALTEK_ALT6_CONTINUOUS_TX_CHIP)) + set_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags); + + return ret; +} + +static int btusb_recv_event_realtek(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (skb->len >= HCI_EVENT_HDR_SIZE + 1 && + skb->data[0] == HCI_VENDOR_PKT && + skb->data[2] == RTK_SUB_EVENT_CODE_COREDUMP) { + struct rtk_dev_coredump_hdr hdr = { + .code = RTK_DEVCOREDUMP_CODE_MEMDUMP, + }; + + bt_dev_dbg(hdev, "RTL: received coredump vendor evt, len %u", + skb->len); + + btusb_rtl_alloc_devcoredump(hdev, &hdr, skb->data, skb->len); + kfree_skb(skb); + + return 0; + } + + return hci_recv_frame(hdev, skb); +} + +static void btusb_mtk_claim_iso_intf(struct btusb_data *data) +{ + struct btmtk_data *btmtk_data; + int err; + + if (!data->hdev) + return; + + btmtk_data = hci_get_priv(data->hdev); + if (!btmtk_data) + return; + + if (!btmtk_data->isopkt_intf) { + bt_dev_err(data->hdev, "Can't claim NULL iso interface"); + return; + } + + /* + * The function usb_driver_claim_interface() is documented to need + * locks held if it's not called from a probe routine. The code here + * is called from the hci_power_on workqueue, so grab the lock. + */ + device_lock(&btmtk_data->isopkt_intf->dev); + err = usb_driver_claim_interface(&btusb_driver, + btmtk_data->isopkt_intf, data); + device_unlock(&btmtk_data->isopkt_intf->dev); + if (err < 0) { + btmtk_data->isopkt_intf = NULL; + bt_dev_err(data->hdev, "Failed to claim iso interface: %d", err); + return; + } + + set_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); + init_usb_anchor(&btmtk_data->isopkt_anchor); +} + +static void btusb_mtk_release_iso_intf(struct hci_dev *hdev) +{ + struct btmtk_data *btmtk_data; + + if (!hdev) + return; + + btmtk_data = hci_get_priv(hdev); + if (!btmtk_data) + return; + + if (test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { + usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor); + clear_bit(BTMTK_ISOPKT_RUNNING, &btmtk_data->flags); + + if (btmtk_data->isopkt_skb) { + dev_kfree_skb_irq(btmtk_data->isopkt_skb); + btmtk_data->isopkt_skb = NULL; + } + + if (btmtk_data->isopkt_intf) { + usb_set_intfdata(btmtk_data->isopkt_intf, NULL); + usb_driver_release_interface(&btusb_driver, + btmtk_data->isopkt_intf); + btmtk_data->isopkt_intf = NULL; + } + } + + clear_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); +} + +static int btusb_mtk_disconnect(struct hci_dev *hdev) +{ + /* This function describes the specific additional steps taken by MediaTek + * when Bluetooth usb driver's resume function is called. + */ + btusb_mtk_release_iso_intf(hdev); + + return 0; +} + +static int btusb_mtk_reset(struct hci_dev *hdev, void *rst_data) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct btmtk_data *btmtk_data = hci_get_priv(hdev); + int err; + + /* It's MediaTek specific bluetooth reset mechanism via USB */ + if (test_and_set_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return -EBUSY; + } + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + return err; + + /* Release MediaTek ISO data interface */ + btusb_mtk_release_iso_intf(hdev); + + btusb_stop_traffic(data); + usb_kill_anchored_urbs(&data->tx_anchor); + + /* Toggle the hard reset line. The MediaTek device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (data->reset_gpio) { + gpiod_set_value_cansleep(data->reset_gpio, 1); + msleep(200); + gpiod_set_value_cansleep(data->reset_gpio, 0); + return 0; + } + + err = btmtk_usb_subsys_reset(hdev, btmtk_data->dev_id); + + usb_queue_reset_device(data->intf); + clear_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags); + + return err; +} + +static int btusb_send_frame_mtk(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + if (hci_skb_pkt_type(skb) == HCI_ISODATA_PKT) { + urb = alloc_mtk_intr_urb(hdev, skb, btusb_tx_complete); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } else { + return btusb_send_frame(hdev, skb); + } +} + +static int btusb_mtk_setup(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct btmtk_data *btmtk_data = hci_get_priv(hdev); + + /* MediaTek WMT vendor cmd requiring below USB resources to + * complete the handshake. + */ + btmtk_data->drv_name = btusb_driver.name; + btmtk_data->intf = data->intf; + btmtk_data->udev = data->udev; + btmtk_data->ctrl_anchor = &data->ctrl_anchor; + btmtk_data->reset_sync = btusb_mtk_reset; + + /* Claim ISO data interface and endpoint */ + if (!test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { + btmtk_data->isopkt_intf = usb_ifnum_to_if(data->udev, MTK_ISO_IFNUM); + btusb_mtk_claim_iso_intf(data); + } + + return btmtk_usb_setup(hdev); +} + +static int btusb_mtk_shutdown(struct hci_dev *hdev) +{ + int ret; + + ret = btmtk_usb_shutdown(hdev); + + /* Release MediaTek iso interface after shutdown */ + btusb_mtk_release_iso_intf(hdev); + + return ret; +} + +#ifdef CONFIG_PM +/* Configure an out-of-band gpio as wake-up pin, if specified in device tree */ +static int marvell_config_oob_wake(struct hci_dev *hdev) +{ + struct sk_buff *skb; + struct btusb_data *data = hci_get_drvdata(hdev); + struct device *dev = &data->udev->dev; + u16 pin, gap, opcode; + int ret; + u8 cmd[5]; + + /* Move on if no wakeup pin specified */ + if (of_property_read_u16(dev->of_node, "marvell,wakeup-pin", &pin) || + of_property_read_u16(dev->of_node, "marvell,wakeup-gap-ms", &gap)) + return 0; + + /* Vendor specific command to configure a GPIO as wake-up pin */ + opcode = hci_opcode_pack(0x3F, 0x59); + cmd[0] = opcode & 0xFF; + cmd[1] = opcode >> 8; + cmd[2] = 2; /* length of parameters that follow */ + cmd[3] = pin; + cmd[4] = gap; /* time in ms, for which wakeup pin should be asserted */ + + skb = bt_skb_alloc(sizeof(cmd), GFP_KERNEL); + if (!skb) { + bt_dev_err(hdev, "%s: No memory", __func__); + return -ENOMEM; + } + + skb_put_data(skb, cmd, sizeof(cmd)); + hci_skb_pkt_type(skb) = HCI_COMMAND_PKT; + + ret = btusb_send_frame(hdev, skb); + if (ret) { + bt_dev_err(hdev, "%s: configuration failed", __func__); + kfree_skb(skb); + return ret; + } + + return 0; +} +#else +static inline int marvell_config_oob_wake(struct hci_dev *hdev) +{ + return 0; +} +#endif + +static int btusb_set_bdaddr_marvell(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + struct sk_buff *skb; + u8 buf[8]; + long ret; + + buf[0] = 0xfe; + buf[1] = sizeof(bdaddr_t); + memcpy(buf + 2, bdaddr, sizeof(bdaddr_t)); + + skb = __hci_cmd_sync(hdev, 0xfc22, sizeof(buf), buf, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "changing Marvell device address failed (%ld)", + ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +static int btusb_set_bdaddr_ath3012(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + struct sk_buff *skb; + u8 buf[10]; + long ret; + + buf[0] = 0x01; + buf[1] = 0x01; + buf[2] = 0x00; + buf[3] = sizeof(bdaddr_t); + memcpy(buf + 4, bdaddr, sizeof(bdaddr_t)); + + skb = __hci_cmd_sync(hdev, 0xfc0b, sizeof(buf), buf, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "Change address command failed (%ld)", ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +static int btusb_set_bdaddr_wcn6855(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + struct sk_buff *skb; + u8 buf[6]; + long ret; + + memcpy(buf, bdaddr, sizeof(bdaddr_t)); + + skb = __hci_cmd_sync_ev(hdev, 0xfc14, sizeof(buf), buf, + HCI_EV_CMD_COMPLETE, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "Change address command failed (%ld)", ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +#define QCA_MEMDUMP_ACL_HANDLE 0x2EDD +#define QCA_MEMDUMP_SIZE_MAX 0x100000 +#define QCA_MEMDUMP_VSE_CLASS 0x01 +#define QCA_MEMDUMP_MSG_TYPE 0x08 +#define QCA_MEMDUMP_PKT_SIZE 248 +#define QCA_LAST_SEQUENCE_NUM 0xffff + +struct qca_dump_hdr { + u8 vse_class; + u8 msg_type; + __le16 seqno; + u8 reserved; + union { + u8 data[0]; + struct { + __le32 ram_dump_size; + u8 data0[0]; + } __packed; + }; +} __packed; + + +static void btusb_dump_hdr_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + char buf[128]; + struct btusb_data *btdata = hci_get_drvdata(hdev); + + snprintf(buf, sizeof(buf), "Controller Name: 0x%x\n", + btdata->qca_dump.controller_id); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Firmware Version: 0x%x\n", + btdata->qca_dump.fw_version); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Driver: %s\nVendor: qca\n", + btusb_driver.name); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "VID: 0x%x\nPID:0x%x\n", + btdata->qca_dump.id_vendor, btdata->qca_dump.id_product); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Lmp Subversion: 0x%x\n", + hdev->lmp_subver); + skb_put_data(skb, buf, strlen(buf)); +} + +static void btusb_coredump_qca(struct hci_dev *hdev) +{ + int err; + static const u8 param[] = { 0x26 }; + + err = __hci_cmd_send(hdev, 0xfc0c, 1, param); + if (err < 0) + bt_dev_err(hdev, "%s: triggle crash failed (%d)", __func__, err); +} + +/* Return: 0 on success, negative errno on failure. */ +static int handle_dump_pkt_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + int ret = 0; + unsigned int skip = 0; + u8 pkt_type; + u16 seqno; + u32 dump_size; + + struct qca_dump_hdr *dump_hdr; + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct usb_device *udev = btdata->udev; + + pkt_type = hci_skb_pkt_type(skb); + skip = sizeof(struct hci_event_hdr); + if (pkt_type == HCI_ACLDATA_PKT) + skip += sizeof(struct hci_acl_hdr); + + skb_pull(skb, skip); + dump_hdr = (struct qca_dump_hdr *)skb->data; + + seqno = le16_to_cpu(dump_hdr->seqno); + if (seqno == 0) { + set_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); + dump_size = le32_to_cpu(dump_hdr->ram_dump_size); + if (!dump_size || (dump_size > QCA_MEMDUMP_SIZE_MAX)) { + ret = -EILSEQ; + bt_dev_err(hdev, "Invalid memdump size(%u)", + dump_size); + goto out; + } + + ret = hci_devcd_init(hdev, dump_size); + if (ret < 0) { + bt_dev_err(hdev, "memdump init error(%d)", ret); + goto out; + } + + btdata->qca_dump.ram_dump_size = dump_size; + btdata->qca_dump.ram_dump_seqno = 0; + + skb_pull(skb, offsetof(struct qca_dump_hdr, data0)); + + usb_disable_autosuspend(udev); + bt_dev_info(hdev, "%s memdump size(%u)\n", + (pkt_type == HCI_ACLDATA_PKT) ? "ACL" : "event", + dump_size); + } else { + skb_pull(skb, offsetof(struct qca_dump_hdr, data)); + } + + if (!btdata->qca_dump.ram_dump_size) { + ret = -EINVAL; + bt_dev_err(hdev, "memdump is not active"); + goto out; + } + + if ((seqno > btdata->qca_dump.ram_dump_seqno + 1) && (seqno != QCA_LAST_SEQUENCE_NUM)) { + dump_size = QCA_MEMDUMP_PKT_SIZE * (seqno - btdata->qca_dump.ram_dump_seqno - 1); + hci_devcd_append_pattern(hdev, 0x0, dump_size); + bt_dev_err(hdev, + "expected memdump seqno(%u) is not received(%u)\n", + btdata->qca_dump.ram_dump_seqno, seqno); + btdata->qca_dump.ram_dump_seqno = seqno; + kfree_skb(skb); + return ret; + } + + hci_devcd_append(hdev, skb); + btdata->qca_dump.ram_dump_seqno++; + if (seqno == QCA_LAST_SEQUENCE_NUM) { + bt_dev_info(hdev, + "memdump done: pkts(%u), total(%u)\n", + btdata->qca_dump.ram_dump_seqno, btdata->qca_dump.ram_dump_size); + + hci_devcd_complete(hdev); + goto out; + } + return ret; + +out: + if (btdata->qca_dump.ram_dump_size) + usb_enable_autosuspend(udev); + btdata->qca_dump.ram_dump_size = 0; + btdata->qca_dump.ram_dump_seqno = 0; + clear_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); + + if (ret < 0) + kfree_skb(skb); + return ret; +} + +/* Return: true if the ACL packet is a dump packet, false otherwise. */ +static bool acl_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct hci_event_hdr *event_hdr; + struct hci_acl_hdr *acl_hdr; + struct qca_dump_hdr *dump_hdr; + struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + bool is_dump = false; + + if (!clone) + return false; + + acl_hdr = skb_pull_data(clone, sizeof(*acl_hdr)); + if (!acl_hdr || (le16_to_cpu(acl_hdr->handle) != QCA_MEMDUMP_ACL_HANDLE)) + goto out; + + event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); + if (!event_hdr || (event_hdr->evt != HCI_VENDOR_PKT)) + goto out; + + dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); + if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || + (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) + goto out; + + is_dump = true; +out: + consume_skb(clone); + return is_dump; +} + +/* Return: true if the event packet is a dump packet, false otherwise. */ +static bool evt_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct hci_event_hdr *event_hdr; + struct qca_dump_hdr *dump_hdr; + struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + bool is_dump = false; + + if (!clone) + return false; + + event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); + if (!event_hdr || (event_hdr->evt != HCI_VENDOR_PKT)) + goto out; + + dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); + if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || + (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) + goto out; + + is_dump = true; +out: + consume_skb(clone); + return is_dump; +} + +static int btusb_recv_acl_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (acl_pkt_is_dump_qca(hdev, skb)) + return handle_dump_pkt_qca(hdev, skb); + return hci_recv_frame(hdev, skb); +} + +static int btusb_recv_evt_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (evt_pkt_is_dump_qca(hdev, skb)) + return handle_dump_pkt_qca(hdev, skb); + return hci_recv_frame(hdev, skb); +} + + +#define QCA_DFU_PACKET_LEN 4096 + +#define QCA_GET_TARGET_VERSION 0x09 +#define QCA_CHECK_STATUS 0x05 +#define QCA_DFU_DOWNLOAD 0x01 + +#define QCA_SYSCFG_UPDATED 0x40 +#define QCA_PATCH_UPDATED 0x80 +#define QCA_DFU_TIMEOUT 3000 +#define QCA_FLAG_MULTI_NVM 0x80 +#define QCA_BT_RESET_WAIT_MS 100 + +#define WCN6855_2_0_RAM_VERSION_GF 0x400c1200 +#define WCN6855_2_1_RAM_VERSION_GF 0x400c1211 + +struct qca_version { + __le32 rom_version; + __le32 patch_version; + __le32 ram_version; + __u8 chip_id; + __u8 platform_id; + __le16 flag; + __u8 reserved[4]; +} __packed; + +struct qca_rampatch_version { + __le16 rom_version_high; + __le16 rom_version_low; + __le16 patch_version; +} __packed; + +struct qca_device_info { + u32 rom_version; + u8 rampatch_hdr; /* length of header in rampatch */ + u8 nvm_hdr; /* length of header in NVM */ + u8 ver_offset; /* offset of version structure in rampatch */ +}; + +struct qca_custom_firmware { + u32 rom_version; + u16 board_id; + const char *subdirectory; +}; + +static const struct qca_device_info qca_devices_table[] = { + { 0x00000100, 20, 4, 8 }, /* Rome 1.0 */ + { 0x00000101, 20, 4, 8 }, /* Rome 1.1 */ + { 0x00000200, 28, 4, 16 }, /* Rome 2.0 */ + { 0x00000201, 28, 4, 16 }, /* Rome 2.1 */ + { 0x00000300, 28, 4, 16 }, /* Rome 3.0 */ + { 0x00000302, 28, 4, 16 }, /* Rome 3.2 */ + { 0x00130100, 40, 4, 16 }, /* WCN6855 1.0 */ + { 0x00130200, 40, 4, 16 }, /* WCN6855 2.0 */ + { 0x00130201, 40, 4, 16 }, /* WCN6855 2.1 */ + { 0x00190200, 40, 4, 16 }, /* WCN785x 2.0 */ +}; + +static const struct qca_custom_firmware qca_custom_btfws[] = { + { 0x00130201, 0x030A, "QCA2066" }, + { 0x00130201, 0x030B, "QCA2066" }, + { }, +}; + +static u16 qca_extract_board_id(const struct qca_version *ver) +{ + u16 flag = le16_to_cpu(ver->flag); + u16 board_id = 0; + + if (((flag >> 8) & 0xff) == QCA_FLAG_MULTI_NVM) { + /* The board_id should be split into two bytes + * The 1st byte is chip ID, and the 2nd byte is platform ID + * For example, board ID 0x010A, 0x01 is platform ID. 0x0A is chip ID + * we have several platforms, and platform IDs are continuously added + * Platform ID: + * 0x00 is for Mobile + * 0x01 is for X86 + * 0x02 is for Automotive + * 0x03 is for Consumer electronic + */ + board_id = (ver->chip_id << 8) + ver->platform_id; + } + + /* Take 0xffff as invalid board ID */ + if (board_id == 0xffff) + board_id = 0; + + return board_id; +} + +static const char *qca_get_fw_subdirectory(const struct qca_version *ver) +{ + const struct qca_custom_firmware *ptr; + u32 rom_ver; + u16 board_id; + + rom_ver = le32_to_cpu(ver->rom_version); + board_id = qca_extract_board_id(ver); + if (!board_id) + return NULL; + + for (ptr = qca_custom_btfws; ptr->rom_version; ptr++) { + if (ptr->rom_version == rom_ver && + ptr->board_id == board_id) + return ptr->subdirectory; + } + + return NULL; +} + +static int btusb_qca_send_vendor_req(struct usb_device *udev, u8 request, + void *data, u16 size) +{ + int err; + + /* Found some of USB hosts have IOT issues with ours so that we should + * not wait until HCI layer is ready. + */ + err = usb_control_msg_recv(udev, 0, request, USB_TYPE_VENDOR | USB_DIR_IN, + 0, 0, data, size, USB_CTRL_GET_TIMEOUT, + GFP_KERNEL); + if (err) + dev_err(&udev->dev, "Failed to access otp area (%d)", err); + + return err; +} + +static int btusb_setup_qca_download_fw(struct hci_dev *hdev, + const struct firmware *firmware, + size_t hdr_size) +{ + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct usb_device *udev = btdata->udev; + size_t count, size, sent = 0; + int pipe, len, err; + u8 *buf; + + buf = kmalloc(QCA_DFU_PACKET_LEN, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + count = firmware->size; + + size = min_t(size_t, count, hdr_size); + memcpy(buf, firmware->data, size); + + /* USB patches should go down to controller through USB path + * because binary format fits to go down through USB channel. + * USB control path is for patching headers and USB bulk is for + * patch body. + */ + pipe = usb_sndctrlpipe(udev, 0); + err = usb_control_msg(udev, pipe, QCA_DFU_DOWNLOAD, USB_TYPE_VENDOR, + 0, 0, buf, size, USB_CTRL_SET_TIMEOUT); + if (err < 0) { + bt_dev_err(hdev, "Failed to send headers (%d)", err); + goto done; + } + + sent += size; + count -= size; + + /* ep2 need time to switch from function acl to function dfu, + * so we add 20ms delay here. + */ + msleep(20); + + while (count) { + size = min_t(size_t, count, QCA_DFU_PACKET_LEN); + + memcpy(buf, firmware->data + sent, size); + + pipe = usb_sndbulkpipe(udev, 0x02); + err = usb_bulk_msg(udev, pipe, buf, size, &len, + QCA_DFU_TIMEOUT); + if (err < 0) { + bt_dev_err(hdev, "Failed to send body at %zd of %zd (%d)", + sent, firmware->size, err); + break; + } + + if (size != len) { + bt_dev_err(hdev, "Failed to get bulk buffer"); + err = -EILSEQ; + break; + } + + sent += size; + count -= size; + } + +done: + kfree(buf); + return err; +} + +static int btusb_setup_qca_load_rampatch(struct hci_dev *hdev, + struct qca_version *ver, + const struct qca_device_info *info) +{ + struct qca_rampatch_version *rver; + const struct firmware *fw; + const char *fw_subdir; + u32 ver_rom, ver_patch, rver_rom; + u16 rver_rom_low, rver_rom_high, rver_patch; + char fwname[80]; + int err; + + ver_rom = le32_to_cpu(ver->rom_version); + ver_patch = le32_to_cpu(ver->patch_version); + + fw_subdir = qca_get_fw_subdirectory(ver); + if (fw_subdir) + snprintf(fwname, sizeof(fwname), "qca/%s/rampatch_usb_%08x.bin", + fw_subdir, ver_rom); + else + snprintf(fwname, sizeof(fwname), "qca/rampatch_usb_%08x.bin", + ver_rom); + + err = request_firmware(&fw, fwname, &hdev->dev); + if (err) { + bt_dev_err(hdev, "failed to request rampatch file: %s (%d)", + fwname, err); + return err; + } + + bt_dev_info(hdev, "using rampatch file: %s", fwname); + + rver = (struct qca_rampatch_version *)(fw->data + info->ver_offset); + rver_rom_low = le16_to_cpu(rver->rom_version_low); + rver_patch = le16_to_cpu(rver->patch_version); + + if (ver_rom & ~0xffffU) { + rver_rom_high = le16_to_cpu(rver->rom_version_high); + rver_rom = rver_rom_high << 16 | rver_rom_low; + } else { + rver_rom = rver_rom_low; + } + + bt_dev_info(hdev, "QCA: patch rome 0x%x build 0x%x, " + "firmware rome 0x%x build 0x%x", + rver_rom, rver_patch, ver_rom, ver_patch); + + /* Allow rampatch when the patch version equals the firmware version. + * A firmware download may be aborted by a transient USB error (e.g. + * disconnect) after the controller updates version info but before + * completion. + * Allowing equal versions enables re-flashing during recovery. + */ + if (rver_rom != ver_rom || rver_patch < ver_patch) { + bt_dev_err(hdev, "rampatch file version did not match with firmware"); + err = -EINVAL; + goto done; + } + + err = btusb_setup_qca_download_fw(hdev, fw, info->rampatch_hdr); + +done: + release_firmware(fw); + + return err; +} + +static void btusb_generate_qca_nvm_name(char *fwname, size_t max_size, + const struct qca_version *ver) +{ + u32 rom_version = le32_to_cpu(ver->rom_version); + const char *variant, *fw_subdir; + int len; + u16 board_id; + + fw_subdir = qca_get_fw_subdirectory(ver); + board_id = qca_extract_board_id(ver); + + switch (le32_to_cpu(ver->ram_version)) { + case WCN6855_2_0_RAM_VERSION_GF: + case WCN6855_2_1_RAM_VERSION_GF: + variant = "_gf"; + break; + default: + variant = NULL; + break; + } + + if (fw_subdir) + len = snprintf(fwname, max_size, "qca/%s/nvm_usb_%08x", + fw_subdir, rom_version); + else + len = snprintf(fwname, max_size, "qca/nvm_usb_%08x", + rom_version); + if (variant) + len += snprintf(fwname + len, max_size - len, "%s", variant); + if (board_id) + len += snprintf(fwname + len, max_size - len, "_%04x", board_id); + len += snprintf(fwname + len, max_size - len, ".bin"); +} + +static int btusb_setup_qca_load_nvm(struct hci_dev *hdev, + struct qca_version *ver, + const struct qca_device_info *info) +{ + const struct firmware *fw; + char fwname[80]; + int err; + + btusb_generate_qca_nvm_name(fwname, sizeof(fwname), ver); + + err = request_firmware(&fw, fwname, &hdev->dev); + if (err) { + bt_dev_err(hdev, "failed to request NVM file: %s (%d)", + fwname, err); + return err; + } + + bt_dev_info(hdev, "using NVM file: %s", fwname); + + err = btusb_setup_qca_download_fw(hdev, fw, info->nvm_hdr); + + release_firmware(fw); + + return err; +} + +/* identify the ROM version and check whether patches are needed */ +static bool btusb_qca_need_patch(struct usb_device *udev) +{ + struct qca_version ver; + + if (btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver))) + return false; + /* only low ROM versions need patches */ + return !(le32_to_cpu(ver.rom_version) & ~0xffffU); +} + +static int btusb_setup_qca(struct hci_dev *hdev) +{ + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct usb_device *udev = btdata->udev; + const struct qca_device_info *info = NULL; + struct qca_version ver; + u32 ver_rom; + u8 status; + int i, err; + + err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver)); + if (err) + return err; + + ver_rom = le32_to_cpu(ver.rom_version); + + for (i = 0; i < ARRAY_SIZE(qca_devices_table); i++) { + if (ver_rom == qca_devices_table[i].rom_version) + info = &qca_devices_table[i]; + } + if (!info) { + /* If the rom_version is not matched in the qca_devices_table + * and the high ROM version is not zero, we assume this chip no + * need to load the rampatch and nvm. + */ + if (ver_rom & ~0xffffU) + return 0; + + bt_dev_err(hdev, "don't support firmware rome 0x%x", ver_rom); + return -ENODEV; + } + + err = btusb_qca_send_vendor_req(udev, QCA_CHECK_STATUS, &status, + sizeof(status)); + if (err) + return err; + + if (!(status & QCA_PATCH_UPDATED)) { + err = btusb_setup_qca_load_rampatch(hdev, &ver, info); + if (err < 0) + return err; + } + + err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver)); + if (err) + return err; + + btdata->qca_dump.fw_version = le32_to_cpu(ver.patch_version); + btdata->qca_dump.controller_id = le32_to_cpu(ver.rom_version); + + if (!(status & QCA_SYSCFG_UPDATED)) { + err = btusb_setup_qca_load_nvm(hdev, &ver, info); + if (err < 0) + return err; + + /* WCN6855 2.1 and later will reset to apply firmware downloaded here, so + * wait ~100ms for reset Done then go ahead, otherwise, it maybe + * cause potential enable failure. + */ + if (info->rom_version >= 0x00130201) + msleep(QCA_BT_RESET_WAIT_MS); + } + + /* Mark HCI_OP_ENHANCED_SETUP_SYNC_CONN as broken as it doesn't seem to + * work with the likes of HSP/HFP mSBC. + */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); + + return 0; +} + +static inline int __set_diag_interface(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_interface *intf = data->diag; + int ret; + + if (!data->diag) + return -ENODEV; + + ret = usb_find_common_endpoints(intf->cur_altsetting, &data->diag_rx_ep, + &data->diag_tx_ep, NULL, NULL); + if (ret) { + bt_dev_err(hdev, "invalid diagnostic descriptors"); + return -ENODEV; + } + + return 0; +} + +static struct urb *alloc_diag_urb(struct hci_dev *hdev, bool enable) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct sk_buff *skb; + struct urb *urb; + unsigned int pipe; + + if (!data->diag_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + skb = bt_skb_alloc(2, GFP_KERNEL); + if (!skb) { + usb_free_urb(urb); + return ERR_PTR(-ENOMEM); + } + + skb_put_u8(skb, 0xf0); + skb_put_u8(skb, enable); + + pipe = usb_sndbulkpipe(data->udev, data->diag_tx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static int btusb_bcm_set_diag(struct hci_dev *hdev, bool enable) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + + if (!data->diag) + return -ENODEV; + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return -ENETDOWN; + + urb = alloc_diag_urb(hdev, enable); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); +} + +#ifdef CONFIG_PM +static irqreturn_t btusb_oob_wake_handler(int irq, void *priv) +{ + struct btusb_data *data = priv; + + pm_wakeup_event(&data->udev->dev, 0); + pm_system_wakeup(); + + /* Disable only if not already disabled (keep it balanced) */ + if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { + disable_irq_nosync(irq); + disable_irq_wake(irq); + } + return IRQ_HANDLED; +} + +static const struct of_device_id btusb_match_table[] = { + { .compatible = "usb1286,204e" }, + { .compatible = "usbcf3,e300" }, /* QCA6174A */ + { .compatible = "usb4ca,301a" }, /* QCA6174A (Lite-On) */ + { } +}; +MODULE_DEVICE_TABLE(of, btusb_match_table); + +/* Use an oob wakeup pin? */ +static int btusb_config_oob_wake(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct device *dev = &data->udev->dev; + int irq, ret; + + clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); + + if (!of_match_device(btusb_match_table, dev)) + return 0; + + /* Move on if no IRQ specified */ + irq = of_irq_get_byname(dev->of_node, "wakeup"); + if (irq <= 0) { + bt_dev_dbg(hdev, "%s: no OOB Wakeup IRQ in DT", __func__); + return 0; + } + + irq_set_status_flags(irq, IRQ_NOAUTOEN); + ret = request_irq(irq, btusb_oob_wake_handler, 0, "OOB Wake-on-BT", data); + if (ret) { + bt_dev_err(hdev, "%s: IRQ request failed", __func__); + return ret; + } + + ret = device_init_wakeup(dev, true); + if (ret) { + bt_dev_err(hdev, "%s: failed to init_wakeup", __func__); + goto err_free_irq; + } + + data->oob_wake_irq = irq; + bt_dev_info(hdev, "OOB Wake-on-BT configured at IRQ %u", irq); + + return 0; + +err_free_irq: + free_irq(irq, data); + + return ret; +} +#else +static inline int btusb_config_oob_wake(struct hci_dev *hdev) +{ + return 0; +} +#endif + +static void btusb_check_needs_reset_resume(struct usb_interface *intf) +{ + if (dmi_check_system(btusb_needs_reset_resume_table)) + interface_to_usbdev(intf)->quirks |= USB_QUIRK_RESET_RESUME; +} + +static bool btusb_wakeup(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + return device_may_wakeup(&data->udev->dev); +} + +static int btusb_shutdown_qca(struct hci_dev *hdev) +{ + struct sk_buff *skb; + + skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + bt_dev_err(hdev, "HCI reset during shutdown failed"); + return PTR_ERR(skb); + } + kfree_skb(skb); + + return 0; +} + +static ssize_t force_poll_sync_read(struct file *file, char __user *user_buf, + size_t count, loff_t *ppos) +{ + struct btusb_data *data = file->private_data; + char buf[3]; + + buf[0] = data->poll_sync ? 'Y' : 'N'; + buf[1] = '\n'; + buf[2] = '\0'; + return simple_read_from_buffer(user_buf, count, ppos, buf, 2); +} + +static ssize_t force_poll_sync_write(struct file *file, + const char __user *user_buf, + size_t count, loff_t *ppos) +{ + struct btusb_data *data = file->private_data; + bool enable; + int err; + + err = kstrtobool_from_user(user_buf, count, &enable); + if (err) + return err; + + /* Only allow changes while the adapter is down */ + if (test_bit(HCI_UP, &data->hdev->flags)) + return -EPERM; + + if (data->poll_sync == enable) + return -EALREADY; + + data->poll_sync = enable; + + return count; +} + +static const struct file_operations force_poll_sync_fops = { + .owner = THIS_MODULE, + .open = simple_open, + .read = force_poll_sync_read, + .write = force_poll_sync_write, + .llseek = default_llseek, +}; + +#define BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS \ + hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0000) +#define BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE 0 +struct btusb_hci_drv_rp_supported_altsettings { + __u8 num; + __u8 altsettings[]; +} __packed; + +#define BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING \ + hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0001) +#define BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE 1 +struct btusb_hci_drv_cmd_switch_altsetting { + __u8 altsetting; +} __packed; + +static const struct { + u16 opcode; + const char *desc; +} btusb_hci_drv_supported_commands[] = { + /* Common commands */ + { HCI_DRV_OP_READ_INFO, "Read Info" }, + + /* Driver specific commands */ + { BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, "Supported Altsettings" }, + { BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, "Switch Altsetting" }, +}; +static int btusb_hci_drv_read_info(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct hci_drv_rp_read_info *rp; + size_t rp_size; + int err, i; + u16 opcode, num_supported_commands = + ARRAY_SIZE(btusb_hci_drv_supported_commands); + + rp_size = sizeof(*rp) + num_supported_commands * 2; + + rp = kmalloc(rp_size, GFP_KERNEL); + if (!rp) + return -ENOMEM; + + strscpy_pad(rp->driver_name, btusb_driver.name); + + rp->num_supported_commands = cpu_to_le16(num_supported_commands); + for (i = 0; i < num_supported_commands; i++) { + opcode = btusb_hci_drv_supported_commands[i].opcode; + bt_dev_info(hdev, + "Supported HCI Drv command (0x%02x|0x%04x): %s", + hci_opcode_ogf(opcode), + hci_opcode_ocf(opcode), + btusb_hci_drv_supported_commands[i].desc); + rp->supported_commands[i] = cpu_to_le16(opcode); + } + + err = hci_drv_cmd_complete(hdev, HCI_DRV_OP_READ_INFO, + HCI_DRV_STATUS_SUCCESS, rp, rp_size); + + kfree(rp); + return err; +} + +static int btusb_hci_drv_supported_altsettings(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct btusb_data *drvdata = hci_get_drvdata(hdev); + struct btusb_hci_drv_rp_supported_altsettings *rp; + size_t rp_size; + int err; + u8 i; + + /* There are at most 7 alt (0 - 6) */ + rp = kmalloc(sizeof(*rp) + 7, GFP_KERNEL); + if (!rp) + return -ENOMEM; + + rp->num = 0; + if (!drvdata->isoc) + goto done; + + for (i = 0; i <= 6; i++) { + if (btusb_find_altsetting(drvdata, i)) + rp->altsettings[rp->num++] = i; + } + +done: + rp_size = sizeof(*rp) + rp->num; + + err = hci_drv_cmd_complete(hdev, BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, + HCI_DRV_STATUS_SUCCESS, rp, rp_size); + kfree(rp); + return err; +} + +static int btusb_hci_drv_switch_altsetting(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct btusb_hci_drv_cmd_switch_altsetting *cmd = data; + u8 status; + + if (cmd->altsetting > 6) { + status = HCI_DRV_STATUS_INVALID_PARAMETERS; + } else { + if (btusb_switch_alt_setting(hdev, cmd->altsetting)) + status = HCI_DRV_STATUS_UNSPECIFIED_ERROR; + else + status = HCI_DRV_STATUS_SUCCESS; + } + + return hci_drv_cmd_status(hdev, BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, + status); +} + +static const struct hci_drv_handler btusb_hci_drv_common_handlers[] = { + { btusb_hci_drv_read_info, HCI_DRV_READ_INFO_SIZE }, +}; + +static const struct hci_drv_handler btusb_hci_drv_specific_handlers[] = { + { btusb_hci_drv_supported_altsettings, + BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE }, + { btusb_hci_drv_switch_altsetting, + BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE }, +}; + +static struct hci_drv btusb_hci_drv = { + .common_handler_count = ARRAY_SIZE(btusb_hci_drv_common_handlers), + .common_handlers = btusb_hci_drv_common_handlers, + .specific_handler_count = ARRAY_SIZE(btusb_hci_drv_specific_handlers), + .specific_handlers = btusb_hci_drv_specific_handlers, +}; + +static int btusb_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + struct gpio_desc *reset_gpio; + struct btusb_data *data; + struct hci_dev *hdev; + unsigned ifnum_base; + int err, priv_size; + + BT_DBG("intf %p id %p", intf, id); + + if ((id->driver_info & BTUSB_IFNUM_2) && + (intf->cur_altsetting->desc.bInterfaceNumber != 0) && + (intf->cur_altsetting->desc.bInterfaceNumber != 2)) + return -ENODEV; + + ifnum_base = intf->cur_altsetting->desc.bInterfaceNumber; + + if (!id->driver_info) { + const struct usb_device_id *match; + + match = usb_match_id(intf, quirks_table); + if (match) + id = match; + } + + if (id->driver_info == BTUSB_IGNORE) + return -ENODEV; + + if (id->driver_info & BTUSB_ATH3012) { + struct usb_device *udev = interface_to_usbdev(intf); + + /* Old firmware would otherwise let ath3k driver load + * patch and sysconfig files + */ + if (le16_to_cpu(udev->descriptor.bcdDevice) <= 0x0001 && + !btusb_qca_need_patch(udev)) + return -ENODEV; + } + + data = kzalloc_obj(*data); + if (!data) + return -ENOMEM; + + err = usb_find_common_endpoints(intf->cur_altsetting, &data->bulk_rx_ep, + &data->bulk_tx_ep, &data->intr_ep, NULL); + if (err) + goto err_free_data; + + if (id->driver_info & BTUSB_AMP) { + data->cmdreq_type = USB_TYPE_CLASS | 0x01; + data->cmdreq = 0x2b; + } else { + data->cmdreq_type = USB_TYPE_CLASS; + data->cmdreq = 0x00; + } + + data->udev = interface_to_usbdev(intf); + data->intf = intf; + + INIT_WORK(&data->work, btusb_work); + INIT_WORK(&data->waker, btusb_waker); + INIT_DELAYED_WORK(&data->rx_work, btusb_rx_work); + + skb_queue_head_init(&data->acl_q); + + init_usb_anchor(&data->deferred); + init_usb_anchor(&data->tx_anchor); + spin_lock_init(&data->txlock); + + init_usb_anchor(&data->intr_anchor); + init_usb_anchor(&data->bulk_anchor); + init_usb_anchor(&data->isoc_anchor); + init_usb_anchor(&data->diag_anchor); + init_usb_anchor(&data->ctrl_anchor); + spin_lock_init(&data->rxlock); + + priv_size = 0; + + data->recv_event = hci_recv_frame; + data->recv_bulk = btusb_recv_bulk; + + if (id->driver_info & BTUSB_INTEL_COMBINED) { + /* Allocate extra space for Intel device */ + priv_size += sizeof(struct btintel_data); + + /* Override the rx handlers */ + data->recv_event = btintel_recv_event; + data->recv_bulk = btusb_recv_bulk_intel; + } else if (id->driver_info & BTUSB_REALTEK) { + /* Allocate extra space for Realtek device */ + priv_size += sizeof(struct btrealtek_data); + + data->recv_event = btusb_recv_event_realtek; + } else if (id->driver_info & BTUSB_MEDIATEK) { + /* Allocate extra space for Mediatek device */ + priv_size += sizeof(struct btmtk_data); + } + + data->recv_acl = hci_recv_frame; + + hdev = hci_alloc_dev_priv(priv_size); + if (!hdev) { + err = -ENOMEM; + goto err_free_data; + } + + hdev->bus = HCI_USB; + hci_set_drvdata(hdev, data); + + data->hdev = hdev; + + SET_HCIDEV_DEV(hdev, &intf->dev); + + reset_gpio = gpiod_get_optional(&data->udev->dev, "reset", + GPIOD_OUT_LOW); + if (IS_ERR(reset_gpio)) { + err = PTR_ERR(reset_gpio); + goto err_free_hdev; + } else if (reset_gpio) { + data->reset_gpio = reset_gpio; + } + + hdev->open = btusb_open; + hdev->close = btusb_close; + hdev->flush = btusb_flush; + hdev->send = btusb_send_frame; + hdev->notify = btusb_notify; + hdev->wakeup = btusb_wakeup; + hdev->hci_drv = &btusb_hci_drv; + + err = btusb_config_oob_wake(hdev); + if (err) + goto err_put_reset; + + /* Marvell devices may need a specific chip configuration */ + if (id->driver_info & BTUSB_MARVELL && data->oob_wake_irq) { + err = marvell_config_oob_wake(hdev); + if (err) + goto err_disable_wakeup; + } + + if (id->driver_info & BTUSB_CW6622) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + + if (id->driver_info & BTUSB_BCM2045) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + + if (id->driver_info & BTUSB_BCM92035) + hdev->setup = btusb_setup_bcm92035; + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && + (id->driver_info & BTUSB_BCM_PATCHRAM)) { + hdev->manufacturer = 15; + hdev->setup = btbcm_setup_patchram; + hdev->set_diag = btusb_bcm_set_diag; + hdev->set_bdaddr = btbcm_set_bdaddr; + + /* Broadcom LM_DIAG Interface numbers are hardcoded */ + data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && + (id->driver_info & BTUSB_BCM_APPLE)) { + hdev->manufacturer = 15; + hdev->setup = btbcm_setup_apple; + hdev->set_diag = btusb_bcm_set_diag; + + /* Broadcom LM_DIAG Interface numbers are hardcoded */ + data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); + } + + /* Combined Intel Device setup to support multiple setup routine */ + if (id->driver_info & BTUSB_INTEL_COMBINED) { + err = btintel_configure_setup(hdev, btusb_driver.name); + if (err) + goto err_kill_tx_urbs; + + /* Transport specific configuration */ + hdev->send = btusb_send_frame_intel; + hdev->reset = btusb_intel_reset; + + if (id->driver_info & BTUSB_INTEL_NO_WBS_SUPPORT) + btintel_set_flag(hdev, INTEL_ROM_LEGACY_NO_WBS_SUPPORT); + + if (id->driver_info & BTUSB_INTEL_BROKEN_INITIAL_NCMD) + btintel_set_flag(hdev, INTEL_BROKEN_INITIAL_NCMD); + + if (id->driver_info & BTUSB_INTEL_BROKEN_SHUTDOWN_LED) + btintel_set_flag(hdev, INTEL_BROKEN_SHUTDOWN_LED); + } + + if (id->driver_info & BTUSB_MARVELL) + hdev->set_bdaddr = btusb_set_bdaddr_marvell; + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) && + (id->driver_info & BTUSB_MEDIATEK)) { + hdev->setup = btusb_mtk_setup; + hdev->shutdown = btusb_mtk_shutdown; + hdev->manufacturer = 70; + hdev->reset = btmtk_reset_sync; + hdev->set_bdaddr = btmtk_set_bdaddr; + hdev->send = btusb_send_frame_mtk; + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); + hci_set_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_SETUP); + data->recv_acl = btmtk_usb_recv_acl; + data->recv_event = btmtk_recv_event; + data->suspend = btmtk_usb_suspend; + data->resume = btmtk_usb_resume; + data->disconnect = btusb_mtk_disconnect; + } + + if (id->driver_info & BTUSB_SWAVE) { + hci_set_quirk(hdev, HCI_QUIRK_FIXUP_INQUIRY_MODE); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LOCAL_COMMANDS); + } + + if (id->driver_info & BTUSB_INTEL_BOOT) { + hdev->manufacturer = 2; + hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); + } + + if (id->driver_info & BTUSB_ATH3012) { + data->setup_on_usb = btusb_setup_qca; + hdev->set_bdaddr = btusb_set_bdaddr_ath3012; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + hci_set_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER); + } + + if (id->driver_info & BTUSB_QCA_ROME) { + data->setup_on_usb = btusb_setup_qca; + hdev->shutdown = btusb_shutdown_qca; + hdev->set_bdaddr = btusb_set_bdaddr_ath3012; + hdev->reset = btusb_qca_reset; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + btusb_check_needs_reset_resume(intf); + } + + if (id->driver_info & BTUSB_QCA_WCN6855) { + data->qca_dump.id_vendor = id->idVendor; + data->qca_dump.id_product = id->idProduct; + data->recv_event = btusb_recv_evt_qca; + data->recv_acl = btusb_recv_acl_qca; + hci_devcd_register(hdev, btusb_coredump_qca, btusb_dump_hdr_qca, NULL); + data->setup_on_usb = btusb_setup_qca; + hdev->classify_pkt_type = btusb_classify_qca_pkt_type; + hdev->shutdown = btusb_shutdown_qca; + hdev->set_bdaddr = btusb_set_bdaddr_wcn6855; + hdev->reset = btusb_qca_reset; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + hci_set_msft_opcode(hdev, 0xFD70); + } + + if (id->driver_info & BTUSB_AMP) { + /* AMP controllers do not support SCO packets */ + data->isoc = NULL; + } else { + /* Interface orders are hardcoded in the specification */ + data->isoc = usb_ifnum_to_if(data->udev, ifnum_base + 1); + data->isoc_ifnum = ifnum_base + 1; + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_RTL) && + (id->driver_info & BTUSB_REALTEK)) { + btrtl_set_driver_name(hdev, btusb_driver.name); + hdev->setup = btusb_setup_realtek; + hdev->shutdown = btrtl_shutdown_realtek; + hdev->reset = btusb_rtl_reset; + hdev->hw_error = btusb_rtl_hw_error; + + /* Realtek devices need to set remote wakeup on auto-suspend */ + set_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags); + set_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags); + } + + if (id->driver_info & BTUSB_ACTIONS_SEMI) { + /* Support is advertised, but not implemented */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_TRANSMIT_POWER); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_SET_RPA_TIMEOUT); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_SCAN); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_ENC_KEY_SIZE); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_CREATE_CONN); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_WRITE_AUTH_PAYLOAD_TIMEOUT); + } + + if (!reset) + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + + if (force_scofix || id->driver_info & BTUSB_WRONG_SCO_MTU) { + if (!disable_scofix) + hci_set_quirk(hdev, HCI_QUIRK_FIXUP_BUFFER_SIZE); + } + + if (id->driver_info & BTUSB_BROKEN_ISOC) + data->isoc = NULL; + + if (id->driver_info & BTUSB_WIDEBAND_SPEECH) + hci_set_quirk(hdev, HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED); + + if (id->driver_info & BTUSB_INVALID_LE_STATES) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LE_STATES); + + if (id->driver_info & BTUSB_DIGIANSWER) { + data->cmdreq_type = USB_TYPE_VENDOR; + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + } + + if (id->driver_info & BTUSB_CSR) { + struct usb_device *udev = data->udev; + u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice); + + /* Old firmware would otherwise execute USB reset */ + if (bcdDevice < 0x117) + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + + /* This must be set first in case we disable it for fakes */ + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + + /* Fake CSR devices with broken commands */ + if (le16_to_cpu(udev->descriptor.idVendor) == 0x0a12 && + le16_to_cpu(udev->descriptor.idProduct) == 0x0001) + hdev->setup = btusb_setup_csr; + } + + if (id->driver_info & BTUSB_SNIFFER) { + struct usb_device *udev = data->udev; + + /* New sniffer firmware has crippled HCI interface */ + if (le16_to_cpu(udev->descriptor.bcdDevice) > 0x997) + hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); + } + + if (id->driver_info & BTUSB_INTEL_BOOT) { + /* A bug in the bootloader causes that interrupt interface is + * only enabled after receiving SetInterface(0, AltSetting=0). + */ + err = usb_set_interface(data->udev, 0, 0); + if (err < 0) { + BT_ERR("failed to set interface 0, alt 0 %d", err); + goto err_kill_tx_urbs; + } + } + + if (data->isoc) { + err = usb_driver_claim_interface(&btusb_driver, + data->isoc, data); + if (err < 0) + goto err_kill_tx_urbs; + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && data->diag) { + if (!usb_driver_claim_interface(&btusb_driver, + data->diag, data)) + __set_diag_interface(hdev); + else + data->diag = NULL; + } + + if (enable_autosuspend) + usb_enable_autosuspend(data->udev); + + data->poll_sync = enable_poll_sync; + + err = hci_register_dev(hdev); + if (err < 0) + goto err_release_siblings; + + usb_set_intfdata(intf, data); + + debugfs_create_file("force_poll_sync", 0644, hdev->debugfs, data, + &force_poll_sync_fops); + + return 0; + +err_release_siblings: + if (data->diag) { + usb_set_intfdata(data->diag, NULL); + usb_driver_release_interface(&btusb_driver, data->diag); + } + if (data->isoc) { + usb_set_intfdata(data->isoc, NULL); + usb_driver_release_interface(&btusb_driver, data->isoc); + } +err_kill_tx_urbs: + usb_kill_anchored_urbs(&data->tx_anchor); +err_disable_wakeup: + if (data->oob_wake_irq) { + device_init_wakeup(&data->udev->dev, false); + free_irq(data->oob_wake_irq, data); + } +err_put_reset: + if (data->reset_gpio) + gpiod_put(data->reset_gpio); +err_free_hdev: + hci_free_dev(hdev); +err_free_data: + kfree(data); + + return err; +} + +static void btusb_disconnect(struct usb_interface *intf) +{ + struct btusb_data *data = usb_get_intfdata(intf); + struct hci_dev *hdev; + + BT_DBG("intf %p", intf); + + if (!data) + return; + + hdev = data->hdev; + usb_set_intfdata(data->intf, NULL); + + if (data->isoc) + usb_set_intfdata(data->isoc, NULL); + + if (data->diag) + usb_set_intfdata(data->diag, NULL); + + if (data->disconnect) + data->disconnect(hdev); + + hci_unregister_dev(hdev); + + if (data->oob_wake_irq) { + device_init_wakeup(&data->udev->dev, false); + free_irq(data->oob_wake_irq, data); + } + + if (data->reset_gpio) + gpiod_put(data->reset_gpio); + + if (intf == data->intf) { + if (data->isoc) + usb_driver_release_interface(&btusb_driver, data->isoc); + if (data->diag) + usb_driver_release_interface(&btusb_driver, data->diag); + } else if (intf == data->isoc) { + if (data->diag) + usb_driver_release_interface(&btusb_driver, data->diag); + usb_driver_release_interface(&btusb_driver, data->intf); + } else if (intf == data->diag) { + if (data->isoc) + usb_driver_release_interface(&btusb_driver, data->isoc); + usb_driver_release_interface(&btusb_driver, data->intf); + } + + hci_free_dev(hdev); + kfree(data); +} + +static int btusb_suspend(struct usb_interface *intf, pm_message_t message) +{ + struct btusb_data *data = usb_get_intfdata(intf); + + BT_DBG("intf %p", intf); + + /* Don't auto-suspend if there are connections or discovery in + * progress; external suspend calls shall never fail. + */ + if (PMSG_IS_AUTO(message) && + (hci_conn_count(data->hdev) || hci_discovery_active(data->hdev))) + return -EBUSY; + + if (data->suspend_count++) + return 0; + + spin_lock_irq(&data->txlock); + if (!(PMSG_IS_AUTO(message) && data->tx_in_flight)) { + set_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + } else { + spin_unlock_irq(&data->txlock); + data->suspend_count--; + return -EBUSY; + } + + cancel_work_sync(&data->work); + + if (data->suspend) + data->suspend(data->hdev); + + btusb_stop_traffic(data); + usb_kill_anchored_urbs(&data->tx_anchor); + + if (data->oob_wake_irq && device_may_wakeup(&data->udev->dev)) { + set_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); + enable_irq_wake(data->oob_wake_irq); + enable_irq(data->oob_wake_irq); + } + + /* For global suspend, Realtek devices lose the loaded fw + * in them. But for autosuspend, firmware should remain. + * Actually, it depends on whether the usb host sends + * set feature (enable wakeup) or not. + */ + if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) { + if (PMSG_IS_AUTO(message) && + device_can_wakeup(&data->udev->dev)) + data->udev->do_remote_wakeup = 1; + else if (!PMSG_IS_AUTO(message) && + !device_may_wakeup(&data->udev->dev)) { + data->udev->do_remote_wakeup = 0; + data->udev->reset_resume = 1; + } + } + + return 0; +} + +static void play_deferred(struct btusb_data *data) +{ + struct urb *urb; + int err; + + while ((urb = usb_get_from_anchor(&data->deferred))) { + usb_anchor_urb(urb, &data->tx_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + BT_ERR("%s urb %p submission failed (%d)", + data->hdev->name, urb, -err); + kfree(urb->setup_packet); + usb_unanchor_urb(urb); + usb_free_urb(urb); + break; + } + + data->tx_in_flight++; + usb_free_urb(urb); + } + + /* Cleanup the rest deferred urbs. */ + while ((urb = usb_get_from_anchor(&data->deferred))) { + kfree(urb->setup_packet); + usb_free_urb(urb); + } +} + +static int btusb_resume(struct usb_interface *intf) +{ + struct btusb_data *data = usb_get_intfdata(intf); + struct hci_dev *hdev = data->hdev; + int err = 0; + + BT_DBG("intf %p", intf); + + if (--data->suspend_count) + return 0; + + /* Disable only if not already disabled (keep it balanced) */ + if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { + disable_irq(data->oob_wake_irq); + disable_irq_wake(data->oob_wake_irq); + } + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (test_bit(BTUSB_INTR_RUNNING, &data->flags)) { + err = btusb_submit_intr_urb(hdev, GFP_NOIO); + if (err < 0) { + clear_bit(BTUSB_INTR_RUNNING, &data->flags); + goto failed; + } + } + + if (test_bit(BTUSB_BULK_RUNNING, &data->flags)) { + err = btusb_submit_bulk_urb(hdev, GFP_NOIO); + if (err < 0) { + clear_bit(BTUSB_BULK_RUNNING, &data->flags); + goto failed; + } + + btusb_submit_bulk_urb(hdev, GFP_NOIO); + } + + if (test_bit(BTUSB_ISOC_RUNNING, &data->flags)) { + if (btusb_submit_isoc_urb(hdev, GFP_NOIO) < 0) + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + else + btusb_submit_isoc_urb(hdev, GFP_NOIO); + } + + if (data->resume) + data->resume(hdev); + + spin_lock_irq(&data->txlock); + play_deferred(data); + clear_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + schedule_work(&data->work); + + return 0; + +failed: + usb_scuttle_anchored_urbs(&data->deferred); +done: + spin_lock_irq(&data->txlock); + clear_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + + return err; +} + +#ifdef CONFIG_DEV_COREDUMP +static void btusb_coredump(struct device *dev) +{ + struct btusb_data *data = dev_get_drvdata(dev); + struct hci_dev *hdev = data->hdev; + + if (hdev->dump.coredump) + hdev->dump.coredump(hdev); +} +#endif + +static struct usb_driver btusb_driver = { + .name = "btusb", + .probe = btusb_probe, + .disconnect = btusb_disconnect, + .suspend = pm_ptr(btusb_suspend), + .resume = pm_ptr(btusb_resume), + .id_table = btusb_table, + .supports_autosuspend = 1, + .disable_hub_initiated_lpm = 1, + +#ifdef CONFIG_DEV_COREDUMP + .driver = { + .coredump = btusb_coredump, + }, +#endif +}; + +module_usb_driver(btusb_driver); + +module_param(disable_scofix, bool, 0644); +MODULE_PARM_DESC(disable_scofix, "Disable fixup of wrong SCO buffer size"); + +module_param(force_scofix, bool, 0644); +MODULE_PARM_DESC(force_scofix, "Force fixup of wrong SCO buffers size"); + +module_param(enable_autosuspend, bool, 0644); +MODULE_PARM_DESC(enable_autosuspend, "Enable USB autosuspend by default"); + +module_param(reset, bool, 0644); +MODULE_PARM_DESC(reset, "Send HCI reset command on initialization"); + +MODULE_AUTHOR("Marcel Holtmann "); +MODULE_DESCRIPTION("Generic Bluetooth USB driver ver " VERSION); +MODULE_VERSION(VERSION); +MODULE_LICENSE("GPL"); diff --git a/diagnostics/bluetooth/tools/kernel-probes.sh b/diagnostics/bluetooth/tools/kernel-probes.sh new file mode 100755 index 0000000..80eac3c --- /dev/null +++ b/diagnostics/bluetooth/tools/kernel-probes.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Install (or with "off": remove) the tracefs kprobes and dynamic-debug prints used to trace +# Bluetooth SCO setup through the kernel and btusb. Needs passwordless sudo. +S=/sys/kernel/tracing +if [ "${1:-}" = off ]; then + sudo -n sh -c "echo 0 > $S/events/bt/enable; echo > $S/kprobe_events; echo > $S/trace + echo 'module btusb -p' > /sys/kernel/debug/dynamic_debug/control + echo 'func hci_sync_conn_complete_evt -p' > /sys/kernel/debug/dynamic_debug/control" + exit +fi +sudo -n sh -c " +echo 0 > $S/events/bt/enable 2>/dev/null +echo > $S/kprobe_events +echo 'p:bt/notify btusb_notify evt=\$arg2:u32' >> $S/kprobe_events +echo 'p:bt/work btusb_work' >> $S/kprobe_events +echo 'p:bt/switch_alt btusb_switch_alt_setting new_alts=\$arg2:s32' >> $S/kprobe_events +echo 'r:bt/switch_alt_ret btusb_switch_alt_setting ret=\$retval:s32' >> $S/kprobe_events +echo 'p:bt/set_intf usb_set_interface ifnum=\$arg2:s32 alt=\$arg3:s32' >> $S/kprobe_events +echo 'r:bt/set_intf_ret usb_set_interface ret=\$retval:s32' >> $S/kprobe_events +echo 'r:bt/submit_isoc_ret btusb_submit_isoc_urb ret=\$retval:s32' >> $S/kprobe_events +echo 'r:bt/autopm_ret usb_autopm_get_interface ret=\$retval:s32' >> $S/kprobe_events +echo 'p:bt/conn_add hci_conn_add_unset type=\$arg2:s32' >> $S/kprobe_events +echo 'p:bt/conn_del hci_conn_del' >> $S/kprobe_events +echo 'p:bt/conn_failed hci_conn_failed status=\$arg2:u8' >> $S/kprobe_events +echo 'p:bt/conn_complete hci_conn_complete_evt status=+0(\$arg2):u8 link_type=+9(\$arg2):u8' >> $S/kprobe_events +echo 'p:bt/disconn_complete hci_disconn_complete_evt status=+0(\$arg2):u8 handle=+1(\$arg2):u16 reason=+3(\$arg2):u8' >> $S/kprobe_events +echo 'p:bt/mode_change hci_mode_change_evt status=+0(\$arg2):u8' >> $S/kprobe_events +echo 'p:bt/sco_setup hci_sco_setup status=\$arg2:u8' >> $S/kprobe_events +echo 'p:bt/cs_enh_setup_sync hci_cs_enhanced_setup_sync_conn status=\$arg2:u8' >> $S/kprobe_events +echo 'p:bt/sync_complete hci_sync_conn_complete_evt' >> $S/kprobe_events +echo 'p:bt/connect_cfm sco_connect_cfm status=\$arg2:u8' >> $S/kprobe_events +echo 'p:bt/sco_tx hci_send_sco' >> $S/kprobe_events +echo 'p:bt/sco_rx_urb btusb_isoc_complete' >> $S/kprobe_events +echo 1 > $S/events/bt/enable +echo 'module btusb +pf' > /sys/kernel/debug/dynamic_debug/control +echo 'func hci_sync_conn_complete_evt +pf' > /sys/kernel/debug/dynamic_debug/control +echo > $S/trace +echo 1 > $S/tracing_on" diff --git a/diagnostics/bluetooth/tools/repro-loop.sh b/diagnostics/bluetooth/tools/repro-loop.sh new file mode 100755 index 0000000..f9bac44 --- /dev/null +++ b/diagnostics/bluetooth/tools/repro-loop.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# Restart WirePlumber, run a traced trial, stop when the kernel logs submission failed (90). +SC=$(dirname "$0") +for i in 1 2 3 4 5 6; do + systemctl --user restart wireplumber; sleep 9 + /home/tank/repos/speech-to-text/bin/stt status --json | grep -q '"state": *"idle"' || { echo "stt busy"; break; } + T0=$(date +%s) + "$SC/trial.sh" "repro-$i" > "$SC/repro-$i.log" 2>&1 + if sudo -n journalctl -k --since "@$T0" --no-pager | grep -q 'submission failed (90)'; then echo "REPRODUCED on attempt $i"; exit 0; fi + echo "attempt $i: no failure"; sleep 3 +done +echo "not reproduced" diff --git a/diagnostics/bluetooth/tools/trial.sh b/diagnostics/bluetooth/tools/trial.sh new file mode 100755 index 0000000..e8e04bf --- /dev/null +++ b/diagnostics/bluetooth/tools/trial.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# One dictation startup trial: kernel probes + btmon + userspace timing. $1 = label +set -u +SC=$(dirname "$0"); L=${1:-trial}; S=/sys/kernel/tracing +sudo -n sh -c "echo > $S/trace" +sudo -n btmon -w "$SC/$L.btsnoop" >/dev/null 2>&1 & +BTMON=$! +sleep 0.5 +T0=$(date +%s.%N) +echo "T0 unix $T0 monotonic $(python3 -c 'import time;print(round(time.monotonic(),3))')" +python3 /tmp/stt-startup-trace.py 2>&1 | grep -vE '"graph"|audio-progress' +sleep 0.5 +sudo -n kill $BTMON; wait $BTMON 2>/dev/null +echo "--- ftrace" +sudo -n cat $S/trace | grep -v '^#' | grep -vE 'sco_tx|sco_rx_urb' | sed -E 's/^ +//; s/ \[[0-9]+\] [^ ]+ / /; s/\([^)]*\)//' | cut -c1-120 +echo "--- sco tx/rx-urb per second" +sudo -n cat $S/trace | grep -E 'sco_tx|sco_rx_urb' | sed -E 's/.* ([0-9]+)\.[0-9]+: (sco_tx|sco_rx_urb).*/\1 \2/' | sort | uniq -c | tr '\n' ';'; echo +echo "--- dmesg" +sudo -n journalctl -k -o short-precise --since "@${T0%.*}" --no-pager | grep -E 'Bluetooth:|hci_sync_conn|hci_conn_request|btusb_notify|__set_isoc|btusb_submit_isoc|__fill_isoc' | cut -c1-160 +echo "--- btmon (commands/events only)" +sudo -n chown $USER "$SC/$L.btsnoop" +btmon -r "$SC/$L.btsnoop" -t 2>/dev/null | grep -E '^[<>] HCI (Command|Event)|^\s+(Status|Handle|Link type|Air mode|Reason|Opcode|Voice setting|Transmit coding|Receive coding|RX packet length|TX packet length|Mode|Interval|Packet type|Retransmission|Max latency|Transmit bandwidth|Receive bandwidth):' | grep -vE 'HCI Event: Number of Completed|HCI Event: Command Complete.*(Read RSSI|Read Clock)|Vendor' | sed -E 's/\{[^}]*\}//' | cut -c1-140 diff --git a/diagnostics/bluetooth/tools/trial2.py b/diagnostics/bluetooth/tools/trial2.py new file mode 100755 index 0000000..eac9fd1 --- /dev/null +++ b/diagnostics/bluetooth/tools/trial2.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""One F13-path dictation startup trial, timed against the kernel. + +usage: trial2.py LABEL [--wp-restart SECS] (--wp-restart: restart WirePlumber, wait SECS, then start) +Needs tools/kernel-probes.sh installed and `echo mono > /sys/kernel/tracing/trace_clock` (passwordless sudo). +Starts dictation the way F13 does (`stt start`), polls the daemon for 6 s, cancels the take (nothing is +pasted or kept), then prints a timeline relative to the start command. +""" +import json, os, re, socket, subprocess, sys, time + +STT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "bin", "stt") +SOCK = os.path.join(os.environ.get("XDG_RUNTIME_DIR", "/tmp"), "speech-to-text", "ctl.sock") +TR = "/sys/kernel/tracing" + +def sudo(cmd): + return subprocess.run(["sudo", "-n", "sh", "-c", cmd], capture_output=True, text=True).stdout + +def profile(): + out = subprocess.run(["pactl", "list", "cards"], capture_output=True, text=True).stdout + card = out.split("Name: bluez_card.88_C9_E8_A7_EC_7E", 1) + if len(card) < 2: return "no-card" + m = re.search(r"Active Profile: (\S+)", card[1].split("Card #")[0]) + return m.group(1) if m else "?" + +def status(): + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); s.connect(SOCK); s.settimeout(2) + buf = b"" + while b"\n" not in buf: + buf += s.recv(65536) + s.close() + return json.loads(buf.split(b"\n", 1)[0]) + +label = sys.argv[1] +if "--wp-restart" in sys.argv: + wait = float(sys.argv[sys.argv.index("--wp-restart") + 1]) + subprocess.run(["systemctl", "--user", "restart", "wireplumber"], check=True) + time.sleep(wait) +assert status()["state"] == "idle", "stt busy" +p0 = profile() +assert p0.startswith("a2dp"), f"headset not in A2DP before start: {p0}" +sudo(f"echo > {TR}/trace") +t0m, t0w = time.monotonic(), time.time() +subprocess.Popen([STT, "start"], stdout=subprocess.DEVNULL) +first_nz = first_sig = listening = None +levels = []; window = None +while time.monotonic() - t0m < 6.0: + st = status(); t = time.monotonic() - t0m + if st["state"] == "recording" and st["levels"]: + lv = st["levels"][-1] + levels.append((round(t, 2), lv)) + if lv > 0 and first_nz is None: first_nz = t + if lv >= 0.05 and first_sig is None: first_sig = t # rms >= 2e-4 + if st["listening"] and listening is None: listening = t + if window is None and t >= 2.3: window = (round(t, 2), st["levels"]) + elif st["state"] != "recording" and st["state"] != "idle" and st["state"] != "opening": + pass + time.sleep(0.02) +subprocess.run([STT, "cancel"], stdout=subprocess.DEVNULL) +time.sleep(0.3) +p_rec = profile() + +# kernel timeline (trace clock must be "mono") +ev = {} +trace = sudo(f"cat {TR}/trace") +rx = tx = 0 +for line in trace.splitlines(): + m = re.match(r"\s*\S+\s+\[\d+\]\s+\S+\s+([\d.]+):\s+(\S+):\s*(.*)", line) + if not m: continue + t = float(m.group(1)) - t0m; name = m.group(2); rest = m.group(3) + if name == "sco_rx_urb": rx += 1; ev.setdefault("first_sco_rx_urb", t); continue + if name == "sco_tx": tx += 1; ev.setdefault("first_sco_tx", t); continue + if name == "conn_add" and "type=2" in rest: ev.setdefault("esco_connect", t) + elif name == "cs_enh_setup_sync": ev.setdefault("enh_setup_cmd_status", t) + elif name == "sync_complete": ev.setdefault("esco_up", t) + elif name == "submit_isoc_ret" and "ret=-" in rest: ev.setdefault("isoc_submit_fail", t) + elif name == "notify": ev.setdefault("notify", []).append((round(t, 3), rest)) + elif name == "switch_alt": ev.setdefault("switch_alt", []).append((round(t, 3), rest)) + elif name == "conn_complete": ev.setdefault("conn_complete", []).append((round(t, 3), rest)) +dmesg = sudo(f"journalctl -k --since @{int(t0w)-1} --no-pager -o short-precise | grep -E 'submission failed|Bluetooth' | cut -c1-140") + +print(f"== {label}") +for k in ("esco_connect", "enh_setup_cmd_status", "esco_up", "first_sco_rx_urb", "first_sco_tx", "isoc_submit_fail"): + print(f"{k:22s} {ev[k]:.3f}" if k in ev else f"{k:22s} -") +print(f"sco rx urbs {rx} sco tx {tx}") +print(f"{'first nonzero level':22s} {first_nz:.3f}" if first_nz else f"{'first nonzero level':22s} -") +print(f"{'first level>=0.05':22s} {first_sig:.3f}" if first_sig else f"{'first level>=0.05':22s} -") +print(f"{'UI listening':22s} {listening:.3f}" if listening else f"{'UI listening':22s} -") +print("notify:", ev.get("notify")); print("switch_alt:", ev.get("switch_alt")); print("conn_complete:", ev.get("conn_complete")) +print("levels:", [l for l in levels if l[1] > 0][:12]) +if window: print(f"level window at {window[0]} s (oldest first, 50 ms each):", window[1]) +print("dmesg:", dmesg.strip() or "-") +print("ERROR90" if "submission failed (90)" in dmesg else "no error 90") +time.sleep(3.5) +print(f"profile: before {p0}, during {p_rec}, 3.5 s after cancel {profile()}")