Skip to content

mt76x0u: receive-only MT7610U / MT7630U / MT7650U backend (DEVOURER_MT76X0U) - #611

Open
MichealShoemaker wants to merge 4 commits into
OpenIPC:masterfrom
MichealShoemaker:mt76x0u-upstream
Open

MichealShoemaker wants to merge 4 commits into
OpenIPC:masterfrom
MichealShoemaker:mt76x0u-upstream

Conversation

@MichealShoemaker

Copy link
Copy Markdown

MT7610U / MT7630U / MT7650U: receive-only MediaTek backend (DEVOURER_MT76X0U, default OFF)

A port of the kernel's mt76x0u (reference/mt76 @ be5ce79) as a self-contained subtree, src/mt76x0u/, behind IRadio as Mt76x0uRadio. It is built for monitor capture and is receive-only by design: send_packet is refused, and there is no TX power/TSSI and no beacons. Same shape as the MT7612U backend (#412): opt-in, own transport, firmware found at runtime (mt7610e.bin, then mt7610u.bin). Like DEVOURER_MT7612U, the option counts as chip support, so an MT76x0U-only build configures.

Commits

  1. mt76x0u: the backend, factory/USB hooks, CMake, selftests and tools
  2. docs: docs/mt76x0u.md (measured record) and the README Supported hardware row
  3. ci: DEVOURER_MT76X0U=ON in the platform, mingw and sanitizer jobs, plus an mt76x0u-only build-configs cell
  4. cmake: the selftests aggregate also builds mt76x0u_wire_harness, so the mingw selftests-only build can run mt76x0u_wire

Measured on hardware

MT7610U 0e8d:7610, two units, on a native Linux host and on WSL2 + usbipd. The reference is the kernel mt76x0u on the same adapter, run sequentially. Full record, with each result's counterpart, in docs/mt76x0u.md:

  • cold and warm bring-up on both hosts; warm restarts 5/5; recovery after kill -9
  • beacon ratio 0.96–0.99 on strong APs; RSSI within 0.0–0.8 dB of the kernel; injected HT20 MCS 0/3/7 received 100/100, as with the kernel
  • HT40 RX; a full WPA3 4-way handshake on 5/5 reconnects; a 24 h soak (8.0 M frames, 0 errors); recovery from unplug/replug
  • channel set ~105 ms with two passes (the default), ~51 ms with one; no FastRetune, no 80 MHz
  • not shown: VHT RX (no 1-stream 802.11ac source was available), DFS RX with traffic, and MT7630U/MT7650U units

Build and test

  • Fork CI (run): 27 of 29 jobs pass. That covers Linux GCC/Clang, Windows MSVC, mingw, the sanitizers and every build-configs cell, including mt76x0u-only. Both macOS cells were cancelled three times with "job was not acquired by Runner … capacity constraints". macOS GCC passed in an earlier run of the same code (f3d9004; only the CMake fix differs). macOS Clang has not run yet, so I'm relying on this PR's CI for it.
  • Local: Linux GCC: all-on 103/103, backend OFF 95/95, mt76x0u-only 89/89. Windows MSVC 19.51 (vcpkg libusb/OpenSSL): 106/106 including mt76x0u_wire, with 0 warnings in the new code.

Please look at

  • Licensing: the files derived from mt76x0/ (chan, eeprom, init, initvals, mac, phy) are GPL-2.0-only; the ones derived from mt76x02 are BSD-3-Clause-Clear. Each file is marked. The repo licence is GPLv2, but the rest of src/ is BSD-3-Clause-Clear, so I'm flagging it explicitly.
  • 7392:b711 is listed by both mt76x0u and mt76x2u. The factory now reads MT_ASIC_VERSION to route it (src/MediatekProbe.h), which touches an id the MT7612U backend already claims.
  • USB transport duplication: usb.cpp and async.cpp are adapted from src/mt7612u (prefix mt0_, RX-only ring). I'm happy to factor out a shared MediaTek transport in a follow-up if you prefer.
  • USB/IP: the chip drops the first EP0 read after the firmware start command. Over usbipd that wedges EP0 until a write goes through, so mt0_fw_wait_running writes MT_FCE_PSE_CTRL after an unanswered read. Details in the doc.
  • The USB reset at open is skipped for this chip's exclusive ids, because it desyncs the running firmware's command ring.

🤖 Generated with Claude Code

MichealShoemaker and others added 4 commits November 25, 2026 11:14
A port of the kernel's mt76x0u (reference/mt76 @ be5ce79) as a self-
contained subtree, src/mt76x0u, behind IRadio as Mt76x0uRadio and the
opt-in DEVOURER_MT76X0U (default OFF). Built for monitor capture:
send_packet is refused, no TX power/TSSI, no beacons.

- transport, EP 0x84 RX ring, in-band MCU, firmware (mt7610e.bin then
  mt7610u.bin, found at runtime), EFUSE, power-on and init, 20/40 MHz
  channel set with calibration, RXWI parse and RSSI correction;
- warm start keeps running firmware (a forced re-upload is refused), and
  drains EP 0x84 and pulses the DMA|PBF reset; no USB reset at open for
  the chip's exclusive ids (it desyncs the running firmware's command ring);
- the RX loop returns on NO_DEVICE or a dry ring so the caller can reclaim;
- after the firmware start command, a read with no answer is followed by a
  MT_FCE_PSE_CTRL write before the next read: over USB/IP (usbipd) the
  dropped first read otherwise wedges EP0;
- 7392:b711 is listed by both mt76x0u and mt76x2u, so the factory routes it
  by MT_ASIC_VERSION (MediatekProbe.h);
- counts as chip support in the no-chip-selected check, like MT7612U.

mt76x0/ sources are GPL-2.0-only and the shared mt76x02 code
BSD-3-Clause-Clear; each file carries the licence of what it derives from.

Selftests: USB ids vs the kernel's table, channel math over a real 43-entry
hop list, EEPROM, firmware parse/framing and the firmware-start wait, RX
ring, RXWI mapping, and mt76x0u_wire (the library against a scripted
MT7610U). Tools: the initvals extractor (--check), a recovery CLI, and a
transfer-level comparison against wifit3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/mt76x0u.md: bring-up (cold/warm, native and WSL2 + usbipd), RX against
the kernel mt76x0u on the same adapter, channel-set cost, a 24 h soak and
loss handling, each with its counterpart, and the open list (VHT RX not yet
demonstrated, DFS RX untested, MT7630U/MT7650U untested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Turn the option on beside DEVOURER_MT7612U in the platform, mingw and
sanitizer jobs, and add an mt76x0u-only build-configs cell (every Realtek
chip off) so the subtree cannot quietly depend on a Realtek chip's sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mt76x0u_wire runs the wire model against this binary, but the aggregate only
collects *Selftest targets, so a selftests-only build (the mingw job) left
the registered test without its harness and it failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Add opt-in, receive-only MT76x0U monitor backend

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add opt-in monitor capture for MT7610U, MT7630U, and MT7650U without packet transmission.
• Route shared MediaTek USB IDs by chip identity and preserve firmware across warm starts.
• Add offline tests, CI builds, and MT7610U hardware measurements to validate the backend.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: MediaTek USB monitor-capture integration.
  • The VID:PID gate, firmware/EEPROM/PHY initialization, channel tuning, RX ring and packet callback together implement one end-to-end monitor-capture behavior.
  • They are separate technical hops in one bounded MediaTek USB integration, not independent capabilities.
  • RX descriptor decoding, USB completion handling, queue hand-off and the packet callback are successive hops of the same monitor-capture behavior.
  • They do not constitute separate end-to-end capabilities.
  • Tuning and calibration change where and how the same monitor-capture capability receives frames; they are not independent user outcomes from the parser or bring-up path.
  • The utility is an operational recovery surface for the same bounded MT76x0U integration.
  • Its outcome is restoring or diagnosing the adapter used by monitor capture; it does not introduce an independent product domain.
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before, no MT76x0U RX descriptor path existed.
  • After, raw USB buffers are transformed through DMA-header/RXWI parsing, PHY-rate decoding, MPDU-length clamping, optional L2-pad movement, RSSI correction and packet-attribute mapping.
  • The new correctness conditions are that parser bounds agree with the device's MPDU and pad semantics, the header move preserves every 802.11 header variant, and the callback never observes a buffer after the event-thread transfer is reused.
  • The ring also requires the new ordering invariant of starting the ring before MAC RX and quiescing MAC RX before joining/stopping the ring.
  • These are newly interacting transformation and concurrency conditions, not complexity inherited from the existing queue type.
Potential damage 🟡 Medium 🩹 Temporary loss

  • The directly affected behavior is monitor capture on the MT76x0U adapter.
  • A bring-up, dispatch, or USB sequencing fault prevents the session from starting.
  • Recovery normally requires correcting the build/configuration or restarting/reopening the adapter; if firmware or device state is left inconsistent, a power cycle or manual recovery may be required.
  • A source-level revert restores the prior code but does not automatically repair a device already left in a bad runtime state.
  • The shared-ID path can also temporarily deny an MT7612U open when family classification fails, but does not establish a broader unrelated consumer impact.
  • Usually recoverable by restarting the process, reopening or power-cycling the USB adapter, and using the correct firmware/configuration.
  • No automatic state-repair worker or external compensation path was established.
Assessed commit 35436cb
Diagram

graph TD
  IDs["USB ID table"] --> Factory["Radio factory"] --> Radio["Mt76x0uRadio"] --> HAL["MT76x0U HAL"] --> Transport["libusb transport"] --> Device["MT76x0U adapter"]
  Firmware["Runtime firmware"] --> HAL
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Share the MT7612U MediaTek transport
  • ➕ Removes duplicated USB and RX-ring machinery.
  • ➕ Centralizes fixes to common transfer and teardown behavior.
  • ➖ Couples the new port to an established backend during initial validation.
  • ➖ Chip-specific endpoint, firmware, and recovery behavior complicates the abstraction.

Recommendation: Keep the separate, opt-in transport for this first hardware-validated port. Consider a shared MediaTek transport in a follow-up once both backends' differing lifecycle and recovery requirements are captured by tests.

Files changed (43) +9423 / -6

Enhancement (24) +6505 / -1
env_config.cppExpose MT76x0U environment settings +13/-0

Expose MT76x0U environment settings

• Parses firmware directory, calibration tick, forced-upload request, control-frame filtering, and double-tune settings into DeviceConfig.

examples/common/env_config.cpp

AdapterCaps.hIdentify MT76x0U capabilities +11/-1

Identify MT76x0U capabilities

• Adds an MT76x0U chip generation and advertises only the ported 20/40 MHz bandwidths.

src/AdapterCaps.h

DeviceConfig.hDefine MT76x0U runtime configuration +30/-0

Define MT76x0U runtime configuration

• Adds firmware lookup and monitor, calibration, and tuning controls. Retains a forced-upload setting while documenting that uploads onto running firmware are refused.

src/DeviceConfig.h

MediatekProbe.hResolve shared MediaTek USB IDs by ASIC +88/-0

Resolve shared MediaTek USB IDs by ASIC

• Provides an early MT_ASIC_VERSION read and chip-family mapping so the shared 7392:b711 ID routes to MT76x0U or MT7612U.

src/MediatekProbe.h

WiFiDriver.cppConstruct the MT76x0U radio safely +50/-0

Construct the MT76x0U radio safely

• Adds USB-ID dispatch ahead of MT7612U and Realtek detection, probes the ASIC for shared IDs, and refuses MT76x0U devices when support is disabled.

src/WiFiDriver.cpp

Mt76x0uMapping.hTranslate MT76x0U receive metadata +103/-0

Translate MT76x0U receive metadata

• Maps RX rates, bandwidth, RSSI, QoS, and aggregation into devourer packet attributes without reporting an absent FCS or extra receive chains.

src/mt76x0u/Mt76x0uMapping.h

Mt76x0uRadio.cppImplement receive-only IRadio behavior +414/-0

Implement receive-only IRadio behavior

• Coordinates bring-up, channel tuning, periodic calibration, RX hand-off, and teardown. Refuses packet transmission and reports adapter capabilities.

src/mt76x0u/Mt76x0uRadio.cpp

Mt76x0uRadio.hDeclare the MT76x0U radio lifecycle +108/-0

Declare the MT76x0U radio lifecycle

• Defines the IRadio adapter, RX queue and thread state, device ownership, and calibration synchronization.

src/mt76x0u/Mt76x0uRadio.h

Mt76x0uUsbIds.hList MT76x0U USB identities and quirks +110/-0

List MT76x0U USB identities and quirks

• Adds the pinned upstream VID:PID set, including the shared MT7612U ID and Archer T1U 2.4 GHz restriction.

src/mt76x0u/Mt76x0uUsbIds.h

async.cppAdd the asynchronous RX ring +268/-0

Add the asynchronous RX ring

• Adapts the MT7612U ring for receive-only EP 0x84 operation, including completion accounting, device-loss detection, and safe stranded-transfer teardown.

src/mt76x0u/async.cpp

chan.cppPort 20/40 MHz tuning and RX calibration +666/-0

Port 20/40 MHz tuning and RX calibration

• Implements channel validation, RF/BBP programming, gain tracking, periodic calibration, and monitor filtering. Runs each channel set twice by default and refuses unsupported widths.

src/mt76x0u/chan.cpp

eeprom.cppRead and interpret MT76x0U EFUSE data +237/-0

Read and interpret MT76x0U EFUSE data

• Reads the on-chip EFUSE and derives MAC address, available bands, frequency offset, LNA gain, RSSI offsets, and temperature calibration values.

src/mt76x0u/eeprom.cpp

fw.cppLoad firmware while preserving warm starts +446/-0

Load firmware while preserving warm starts

• Parses and uploads mt7610e.bin or mt7610u.bin, retaining running firmware. After an unanswered post-start EP0 read, issues a write to recover USB/IP control transfers.

src/mt76x0u/fw.cpp

mt76x0u.hExpose the MT76x0U HAL interface +215/-0

Expose the MT76x0U HAL interface

• Defines the C ABI for adopted USB handles, firmware, bring-up, channel selection, receive callbacks, lifecycle operations, and statistics.

src/mt76x0u/include/mt76x0u/mt76x0u.h

init.cppPort MT76x0U hardware initialization +328/-0

Port MT76x0U hardware initialization

• Sequences power-on, firmware, DMA, MAC, BBP, EFUSE, and PHY setup. Drains and resets receive DMA on warm starts without resetting the MCU.

src/mt76x0u/init.cpp

initvals.hAdd generated MT76x0U initialization tables +814/-0

Add generated MT76x0U initialization tables

• Contains pinned, generated MAC, BBP, RF, and frequency-plan values used during initialization and channel changes.

src/mt76x0u/initvals.h

internal.hDefine private HAL state and interfaces +354/-0

Define private HAL state and interfaces

• Declares device, USB-transfer, RX-ring, channel, MCU, and calibration state alongside internal functions and the transfer-test hook.

src/mt76x0u/internal.h

mac.cppControl monitor MAC reception +140/-0

Control monitor MAC reception

• Starts MAC reception only after an RX ring exists, applies the monitor filter, and disables reception before ring teardown.

src/mt76x0u/mac.cpp

mcu.cppAdd in-band MCU commands and RF access +394/-0

Add in-band MCU commands and RF access

• Sends sequenced commands over bulk USB, validates register-pair replies, and drains stale responses after failures. Requires firmware and Q_SELECT before MCU RF access.

src/mt76x0u/mcu.cpp

phy.cppInitialize MT76x0U antenna and RF paths +197/-0

Initialize MT76x0U antenna and RF paths

• Ports antenna selection, RF table programming and patches, frequency trim, receive-path selection, and PHY initialization.

src/mt76x0u/phy.cpp

phy.hDefine RF tables and channel constants +73/-0

Define RF tables and channel constants

• Adds upstream-derived band and width flags plus the table entry types used by generated initialization values.

src/mt76x0u/phy.h

regs.hDefine MT76x0U register and wire constants +572/-0

Define MT76x0U register and wire constants

• Provides USB requests, endpoints, register maps, descriptor fields, EEPROM offsets, and MT76x0U-specific MCU and calibration identifiers.

src/mt76x0u/regs.h

rx.cppParse MT76x0U receive descriptors +135/-0

Parse MT76x0U receive descriptors

• Extracts RXWI rates, sequence numbers, and corrected RSSI, removes L2 padding, and rejects invalid or short receive records.

src/mt76x0u/rx.cpp

usb.cppAdd independent libusb register transport +739/-0

Add independent libusb register transport

• Adapts the MT7612U USB transport with separate symbols, synchronized transfer completion, register I/O, chip identification, and handle adoption.

src/mt76x0u/usb.cpp

Bug fix (1) +21 / -0
UsbOpen.cppAvoid disruptive resets for exclusive MT76x0U IDs +21/-0

Avoid disruptive resets for exclusive MT76x0U IDs

• Skips the open-time USB reset for exclusive MT76x0U identities to preserve a running firmware command ring. Shared IDs retain the existing reset behavior.

src/UsbOpen.cpp

Tests (10) +1718 / -0
adapter_caps_selftest.cppCheck MT76x0U capability reporting +7/-0

Check MT76x0U capability reporting

• Asserts the new generation name and 20/40 MHz bandwidth mask.

tests/adapter_caps_selftest.cpp

mt76x0u_chan_selftest.cppTest channel math and monitor filtering +106/-0

Test channel math and monitor filtering

• Checks hop-list coverage, HT40 center selection, invalid channels, radar flags, and control-frame filter values.

tests/mt76x0u_chan_selftest.cpp

mt76x0u_eeprom_selftest.cppTest EFUSE decoding and RF values +160/-0

Test EFUSE decoding and RF values

• Checks calibration decoding, band restrictions, RF patch overrides, and representative generated-table values.

tests/mt76x0u_eeprom_selftest.cpp

mt76x0u_fw_selftest.cppTest firmware framing and boot waits +341/-0

Test firmware framing and boot waits

• Covers image validation, IVB and chunk layout, MCU register pairs, preconditions, and post-start EP0 recovery. Optionally checks supplied firmware images.

tests/mt76x0u_fw_selftest.cpp

mt76x0u_mapping_selftest.cppTest receive-attribute translation +80/-0

Test receive-attribute translation

• Checks rate bounds, RSSI bias, one-chain reporting, FCS absence, and four-address QoS TID extraction.

tests/mt76x0u_mapping_selftest.cpp

mt76x0u_rx_ring_selftest.cppTest RX parsing and completion bookkeeping +200/-0

Test RX parsing and completion bookkeeping

• Checks padding removal, RSSI correction, malformed-frame accounting, callback lock behavior, cancellation, and detached slots.

tests/mt76x0u_rx_ring_selftest.cpp

mt76x0u_usb_ids_selftest.cppGuard USB routing against collisions +158/-0

Guard USB routing against collisions

• Checks MT76x0U identities against Realtek and MT7612U sets, shared-ID flags, no-2GHz quirks, and ASIC family classification.

tests/mt76x0u_usb_ids_selftest.cpp

mt76x0u_usb_ids_vs_mt76.pyCompare USB IDs with pinned upstream +118/-0

Compare USB IDs with pinned upstream

• Checks the upstream ID set, interface-class entries, and no-2GHz quirk against a pinned mt76 source; skips when the submodule is absent.

tests/mt76x0u_usb_ids_vs_mt76.py

mt76x0u_wire_harness.cppDrive HAL transfers through a test pipe +151/-0

Drive HAL transfers through a test pipe

• Provides a hook-backed device harness for logging bring-up and channel-setting transfers against a scripted chip.

tests/mt76x0u_wire_harness.cpp

mt76x0u_wire_model.pyModel MT7610U transfer sequences +397/-0

Model MT7610U transfer sequences

• Simulates registers, EFUSE, firmware, and MCU replies to test cold, warm, and forced-upload behavior without hardware.

tests/mt76x0u_wire_model.py

Documentation (3) +240 / -2
README.mdDocument MT7610U support and limits +15/-2

Document MT7610U support and limits

• Adds the receive-only hardware row, firmware configuration, measured capture behavior, and unsupported or unverified capabilities.

README.md

mt76x0u.mdRecord MT7610U hardware validation +128/-0

Record MT7610U hardware validation

• Documents native Linux and WSL2/usbipd bring-up, kernel-driver RX comparisons, channel timing, soak and recovery results, and outstanding validation gaps.

docs/mt76x0u.md

README.mdExplain the port and its departures +97/-0

Explain the port and its departures

• Maps subtree responsibilities, identifies upstream sources and licenses, and explains receive-only behavior, recovery choices, and transfer-level comparisons.

src/mt76x0u/README.md

Other (5) +939 / -3
cmake-multi-platform.ymlExercise MT76x0U across CI builds +7/-1

Exercise MT76x0U across CI builds

• Enables the backend in platform, mingw, and sanitizer jobs and adds an MT76x0U-only configuration cell.

.github/workflows/cmake-multi-platform.yml

CMakeLists.txtGate and test the new backend +152/-2

Gate and test the new backend

• Adds the default-off DEVOURER_MT76X0U option, HAL sources, public definition, and standalone chip-support configuration. Registers offline tests and makes the selftests aggregate build the wire harness.

CMakeLists.txt

extract_mt76x0u_tables.pyGenerate pinned MT76x0U hardware tables +354/-0

Generate pinned MT76x0U hardware tables

• Evaluates upstream register expressions into initvals.h and verifies source hashes, row counts, and checked-in output.

tools/extract_mt76x0u_tables.py

mt76x0u_recover.cppAdd standalone MT7610U recovery probe +290/-0

Add standalone MT7610U recovery probe

• Provides explicit register inspection, reset, firmware, drain, and RX steps for diagnosing a running but unresponsive adapter.

tools/mt76x0u_recover.cpp

mt76x0u_wire_vs_wifit3.pyCompare transfer logs with wifit3 +136/-0

Compare transfer logs with wifit3

• Runs wifit3 against the scripted chip through a USB stub and emits comparable bring-up and channel-setting logs.

tools/mt76x0u_wire_vs_wifit3.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (8) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. CCA mode requests are silently discarded 📘 Rule violation ≡ Correctness
Description
Mt76x0uRadio::SetCcaMode has an empty body, so a caller's disabled request is accepted and
dropped while the header declares it an override. A monitor application that toggles CCA gets no
error or feedback, and a later reader will assume the backend honours the call.
Code

src/mt76x0u/Mt76x0uRadio.cpp[R358-360]

+void Mt76x0uRadio::SetCcaMode(bool /*disabled*/) {
+  /* CCA gates transmission; this backend does not transmit. */
+}
Evidence
Rule 17 requires that SetCcaMode remain implemented by each backend rather than silently no-oping.
The new SetCcaMode in src/mt76x0u/Mt76x0uRadio.cpp (lines 358-360) has an empty body, and the
header declares it as an override (void SetCcaMode(bool disabled) override;), which matches the
rule's failure criterion of a backend silently ignoring a CCA mode request.

src/mt76x0u/Mt76x0uRadio.h
CLAUDE.md: Do not silently disable carrier-sense APIs or RX decoding

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The mt76x0u backend's `Mt76x0uRadio::SetCcaMode(bool disabled)` is an empty function. It silently accepts and ignores the caller's CCA request, which violates the requirement that every backend implement `SetCcaMode` rather than silently no-oping it.

## Fix Focus Areas
- src/mt76x0u/Mt76x0uRadio.cpp[358-360]
- src/mt76x0u/Mt76x0uRadio.h[62-62]

## Recommended Fix
Replace the empty body with one of these, following the convention used by the other backends:
1. Preferred: refuse the call explicitly, for example by logging a warning and returning, or by throwing `std::runtime_error` when the device is not initialized, so the caller knows the mode did not change.
2. If the chip does have a usable CCA control, implement it under `_mu` and only after bring-up, and refuse calls made before bring-up.
Update the comment so it no longer claims the backend is exempt. Add a selftest or a doc note that states the chosen behaviour.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. A late USB callback can access freed memory 🐞 Bug ☼ Reliability
Description
submit_and_wait() abandons a transfer whose cancellation never completes, but its eventual
callback calls sync_xfer_free() through a pointer to the device that mt76x0u_close() deletes. If
the callback arrives after close, it locks a destroyed device mutex and accesses the freed transfer
pool.
Code

src/mt76x0u/usb.cpp[R262-265]

+			if (x->state.exchange(XFER_ABANDONED,
+			                      std::memory_order_acq_rel) == XFER_DONE)
+				sync_xfer_free(x);
+			return LIBUSB_ERROR_OTHER;
Evidence
The abandonment path leaves cleanup to sync_done(), whose cleanup routine dereferences x->d;
close subsequently deletes that device without waiting for the callback.

src/mt76x0u/usb.cpp[154-180]
src/mt76x0u/usb.cpp[252-265]
src/mt76x0u/usb.cpp[726-734]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An abandoned synchronous transfer retains a device pointer after close deletes the device; its late callback accesses freed device state.
## Fix Focus Areas
- src/mt76x0u/usb.cpp[154-180]
- src/mt76x0u/usb.cpp[252-265]
- src/mt76x0u/usb.cpp[726-734]
## Recommended Fix
Make abandoned-transfer callback cleanup independent of the device and its pool, or retain the device state until all such callbacks have completed. Ensure close cannot destroy state that a pending callback will access.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Concurrent shutdown can free the RX ring 🐞 Bug ☼ Reliability
Description
start_rx_loop() releases its teardown lock after a MAC-start failure, then calls
mt76x0u_rx_stop() using the saved device pointer while _rx_active is still false. A concurrent
Stop() can pass the inactive-ring check and close that device before the failure path uses it.
Code

src/mt76x0u/Mt76x0uRadio.cpp[R248-250]

+  if (mac_failed) {
+    /* Rule 4: the ring teardown joins the event thread - not under _mu. */
+    mt76x0u_rx_stop(mac_failed);
Evidence
The failed-start path retains a raw device pointer outside the lock, while Stop treats `_rx_active
== false` as permission to skip ring teardown and close the device.

src/mt76x0u/Mt76x0uRadio.cpp[238-252]
src/mt76x0u/Mt76x0uRadio.cpp[298-314]
src/mt76x0u/Mt76x0uRadio.cpp[362-380]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A failed MAC start leaves an RX ring to tear down, but concurrent Stop can free its device before that teardown runs.
## Fix Focus Areas
- src/mt76x0u/Mt76x0uRadio.cpp[238-252]
- src/mt76x0u/Mt76x0uRadio.cpp[298-314]
- src/mt76x0u/Mt76x0uRadio.cpp[362-380]
## Recommended Fix
Represent the started ring independently of successful MAC activation and serialize its teardown with Stop. Keep the device alive through `mt76x0u_rx_stop()` without holding a lock whose acquisition requires the event thread to finish.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View action required (1)
4. Failed key clears can pass bring-up 🐞 Bug ≡ Correctness
Description
mt0_wr_copy() returns on a failed block-write request without recording an I/O error, and its
callers in wcid_and_key_clear() do not inspect a result. When a key or device-table clear fails,
the final bring-up check can still report successful initialization.
Code

src/mt76x0u/usb.cpp[R667-669]

+		if (mt0_vendor_req(d, MT_VEND_MULTI_WRITE, REQ_OUT, 0,
+		                   (uint16_t)(offset + i), buf, (size_t)xfer) < 0)
+			return;
Evidence
The vendor request only returns its error, the copy helper discards it, and the bring-up boundary
checks the separate io_err accumulator.

src/mt76x0u/usb.cpp[331-358]
src/mt76x0u/usb.cpp[653-671]
src/mt76x0u/init.cpp[183-203]
src/mt76x0u/init.cpp[302-311]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Failed block writes during key and device-table initialization are neither returned to the caller nor counted by bring-up's I/O-error check.
## Fix Focus Areas
- src/mt76x0u/usb.cpp[653-671]
- src/mt76x0u/init.cpp[186-203]
- src/mt76x0u/init.cpp[302-311]
## Recommended Fix
Have `mt0_wr_copy()` report failed or short writes, propagate that result from initialization, and fail bring-up if a required clear did not complete.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. Unburned calibration data passes checks 🐞 Bug ≡ Correctness
Description
efuse_physical_size_check() leaves start and end at zero when the usage map contains no zero
entries, making cnt_free equal one rather than identifying an unburned map. When EFUSE supplies
all 0xff bytes, initialization accepts the image and proceeds to parse it as EEPROM data.
Code

src/mt76x0u/eeprom.cpp[R201-205]

+	const uint32_t cnt_free = end - start + 1;
+	if (MT_EFUSE_USAGE_MAP_SIZE - cnt_free < 5) {
+		ERR("driver does not support default EEPROM (EFUSE usage map "
+		    "nearly empty: the card's calibration was never burned)");
+		return -1;
Evidence
Unburned blocks become 0xff, whereas the scan changes its bounds only for zero bytes; the
unchecked zero bounds then pass the threshold before EEPROM parsing.

src/mt76x0u/eeprom.cpp[137-162]
src/mt76x0u/eeprom.cpp[185-223]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An all-`0xff` EFUSE usage map has no zero entry, but the initialized scan bounds make it pass the physical-size check.
## Fix Focus Areas
- src/mt76x0u/eeprom.cpp[185-208]
- src/mt76x0u/eeprom.cpp[210-223]
## Recommended Fix
Track whether the scan found an allocated usage-map entry and reject a map with none before computing the free span. Add a test for an all-`0xff` map.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Late replies can derail channel tuning 🐞 Bug ☼ Reliability
Description
mt0_mcu_send() clears mcu_stale_pending after one five-millisecond timeout, although the
preceding timed-out command may still produce a reply later. If that reply arrives during the next
command, its sequence is handled as a mismatch instead of being excluded from the new transaction,
consuming that command's response-wait budget.
Code

src/mt76x0u/mcu.cpp[166]

+			if (brc == LIBUSB_ERROR_TIMEOUT) { drained_clean = 1; break; }
Evidence
The timeout path explicitly marks a reply as outstanding, but the pre-send drain clears that marker
on its first five-millisecond timeout; the subsequent wait logs mismatched sequences.

src/mt76x0u/mcu.cpp[74-109]
src/mt76x0u/mcu.cpp[130-180]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An empty queue for five milliseconds does not establish that a timed-out MCU reply will never arrive, yet it disables stale-reply handling before the next command.
## Fix Focus Areas
- src/mt76x0u/mcu.cpp[74-109]
- src/mt76x0u/mcu.cpp[130-180]
## Recommended Fix
Preserve enough outstanding-command sequence state to discard late predecessor replies while waiting for the current sequence. Do not treat a short empty-queue interval alone as proof that an outstanding reply has been resolved.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Stopping reception in its callback crashes 🐞 Bug ☼ Reliability
Description
rx_done() invokes the supplied callback on the event thread, but mt0_async_stop() waits for that
callback's transfer and then unconditionally joins the same event thread. If a callback calls the
public RX-stop or close API, the transfer cannot finish while the callback waits, and the self-join
throws across the C callback boundary.
Code

src/mt76x0u/async.cpp[R218-219]

+	if (a->evt_started)
+		a->evt.join();
Evidence
The callback runs before rx_inflight is decremented; stop waits on that count and then joins its
event thread, while public close also enters stop.

src/mt76x0u/async.cpp[39-99]
src/mt76x0u/async.cpp[193-238]
src/mt76x0u/usb.cpp[726-733]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Calling RX-stop or close from an RX callback makes the event thread wait for its own completion and then attempt to join itself.
## Fix Focus Areas
- src/mt76x0u/async.cpp[39-99]
- src/mt76x0u/async.cpp[193-238]
- src/mt76x0u/usb.cpp[726-733]
## Recommended Fix
Make callback-initiated stop request quiescence without waiting or joining on the event thread, and perform final cancellation, join, and cleanup from another thread. Keep close from freeing callback-owned state before that cleanup finishes.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (1)
8. Recovery can reset the wrong adapter 🐞 Bug ≡ Correctness
Description
mt76x0u_recover opens the first device matching its hard-coded vendor and product IDs without
letting the operator identify a particular unit. With multiple matching adapters attached, its reset
and chip-power commands act on whichever matching device libusb opens first.
Code

tools/mt76x0u_recover.cpp[176]

+  libusb_device_handle *h = libusb_open_device_with_vid_pid(ctx, MT76X0U_VID, MT76X0U_PID);
Evidence
Selection uses only VID:PID, while the command loop exposes firmware, DMA, MCU, chip, and USB reset
operations on the opened handle.

tools/mt76x0u_recover.cpp[164-190]
tools/mt76x0u_recover.cpp[197-227]
tools/mt76x0u_recover.cpp[267-273]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The recovery utility selects an unspecified matching USB device before offering commands that reset or power-cycle it.
## Fix Focus Areas
- tools/mt76x0u_recover.cpp[164-190]
- tools/mt76x0u_recover.cpp[197-227]
## Recommended Fix
Enumerate matching devices and require a bus/address or serial selection when more than one is present; display the selected device before executing recovery steps.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

9. Edimax b711 MT7612U adapters can now be refused at open 🐞 Bug ☼ Reliability
Description
Before this change, 7392:b711 went straight to Mt7612uRadio. Now CreateRadio first calls
read_asic_version, and if that read fails three times it returns nullptr, even in builds where
DEVOURER_MT76X0U is OFF and MT7612U is the only backend that could take the id. A failed or
timed-out EP0 read on that adapter now refuses it at open, while previously the MT7612U backend
would have run its own identify step and retry handling.
Code

src/WiFiDriver.cpp[R224-229]

+    if (!rev) {
+      _logger->error("MediaTek {:04x}:{:04x}: MT_ASIC_VERSION read failed; "
+                     "cannot tell MT76x0U from MT7612U - refusing",
+                     vid, pid);
+      return nullptr;
+    }
Evidence
The new routing block runs for every id mt76x0u::is_usb_id accepts that is not exclusive, which
today is only b711. It sits ahead of the existing mt7612u::is_usb_id gate and refuses outright
when the read returns nullopt. The read helper gives up after 3 attempts with a 300 ms timeout.
Nothing in the block checks whether the MT76x0U backend is compiled in.

src/WiFiDriver.cpp[220-243]
src/MediatekProbe.h[60-83]
src/mt76x0u/Mt76x0uUsbIds.h[58-84]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
For the shared id 7392:b711, `WiFiDriver::CreateRadio` refuses the device if the MT_ASIC_VERSION probe fails. That happens even when DEVOURER_MT76X0U is OFF, so MT7612U is the only possible backend. This is a regression for MT7612U-only builds.

## Fix Focus Areas
- src/WiFiDriver.cpp[220-243]

## Recommended Fix
Wrap the probe in `#if defined(DEVOURER_HAVE_MT76X0U)`. When the MT76x0U backend is not compiled in, skip the read and let the id fall through to the existing MT7612U gate. That backend validates the chip itself. Optionally, when both backends are built and the read fails, fall through to MT7612U too (its own identify step stays authoritative) instead of returning nullptr.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Context preparation
  Commit messages: summarized; full text retained for this review
Review mode: Auto: 🧠 Deep: Large hardware backend spans USB, firmware, probing, radio, and many independent paths.

Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@josephnef josephnef left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this — it is a careful port, and the offline test coverage (wire model, generated-table --check, id table vs the kernel) is exactly the right shape.

What I checked

  • All-on build (DEVOURER_MT7612U=ON, DEVOURER_MT76X0U=ON), GCC 16: clean, no warnings in the new files; ctest 107/107. extract_mt76x0u_tables.py --check (770 entries, 15 tables) and mt76x0u_usb_ids_vs_mt76.py (25 ids) reproduce against reference/mt76 @ be5ce79.
  • Realtek dispatch is unaffected: the PR's rxdemo on an RTL8733BU still routes and receives.
  • Read against the kernel function by function: RF channel programming, HT40 centre/ext-CCA, RSSI/LNA correction, EFUSE decode and size check, the calibration tick and table coverage all match.
  • Not checked: the backend on hardware. I have no MT7610U on the bench, so every on-air figure here is yours.

Requesting changes for (details inline):

  1. RX parser clamps and delivers frames the kernel drops; no FCS on this part to catch it.
  2. MT_TX_PIN_CFG (LNA / T-R switch pins) is never written.
  3. mt0_poll waits ~1 ms where the kernel does ~101 reads; the WPDMA wait is a hard failure.
  4. 7392:b711 regresses for the MT7612U backend when the ASIC read fails, and still takes the USB reset.
  5. tune_twice defaults on without support from the kernel source or your own measurement.
  6. force_fw_upload is a dead knob; a warm start still demands a firmware file.
  7. SetCcaMode silently no-ops.
  8. Three lifecycle races (abandoned sync transfer after close, start_rx_loop failure path, stop from the RX callback).

Also, not tied to a line

  • Please add src/mt76x0u/CLAUDE.md (the subtree convention; src/mt7612u/ has one) and the backend's entry in the root CLAUDE.md. The dated bench narratives in code comments belong in docs/mt76x0u.md; comments should describe the code as it is.
  • mt76x0u_get_stats reads d->io_err from the RX-loop thread while the calibration tick writes it; make it atomic.
  • Smaller decode differences from mt76x02_mac_process_rate: CCK indices 4–7 and OFDM ≥ 8 are masked rather than rejected, and SGI/LDPC/STBC are reported for legacy rates.
  • Licensing: GPL-2.0-only files inside a GPLv2 repository are compatible, and marking each file is the right call. No change needed.

Given the size, I am happy to take the fixes as additional commits rather than a rewrite.

Comment thread src/mt76x0u/rx.cpp
/* MPDU_LEN excludes the L2 pad: the buffer holds hdr + pad + body. */
const int pad = (rxinfo & MT_RXINFO_L2PAD) ? 2 : 0;
int len = (int)info->mpdu_len;
if (len > n - MT_DMA_HDR_LEN - MT_RXWI_LEN - pad)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The parser delivers what the kernel drops. The DMA header length word is never read, and an oversize MPDU_LEN is clamped here instead of rejected. The kernel drops in both places: mt76u_get_rx_entry_len (usb.c: data_len < min_len, !dma_len, dma_len + MT_DMA_HDR_LEN > data_len, dma_len & 3) and mt76x02_mac_process_rx (len > skb->len). The clamp bound also still includes the 4-byte FCE trailer, so a clamped frame carries trailer bytes as payload. This part delivers no FCS, so nothing downstream can tell a truncated or garbage completion from a real frame. Please validate the DMA length against actual_length and return MT_RX_PARSE_INVALID rather than clamp, with a selftest case for each drop condition.

Comment thread src/mt76x0u/chan.cpp
/* mt76x02_edcca_init with ed_monitor off (mac80211's default outside ETSI
* DFS operation), minus mt76x02_edcca_tx_enable. */
static void edcca_init(struct mt76x0u_dev *d)
{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

MT_TX_PIN_CFG is never written anywhere in the subtree. mt76x02_edcca_tx_enable(dev, true) runs on every kernel channel set and ORs TXANT | RXANT | RFTR_EN | TRSW_EN into it ("enable pa-lna"). Dropping ENABLE_TX and AUTO_RSP_EN is right for a receive-only backend, but RXANT and TRSW_EN are receive-path pins, so this is not a TX-only omission. On a board with an external LNA or T/R switch it could cost sensitivity. Please either port the pin write, or show the register's value after bring-up and an RSSI A/B with the four bits set, and record the result in docs/mt76x0u.md.

Comment thread src/mt76x0u/usb.cpp
* access can itself cost up to VEND_RETRIES * CTRL_TIMEOUT_MS, so counting
* iterations would let a caller asking for 200 ms block for seconds.
*/
int mt0_poll(struct mt76x0u_dev *d, uint32_t addr, uint32_t mask,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This poll is far shorter than the kernel's for the same argument. __mt76_poll(…, timeout) does timeout/10 + 1 reads regardless of how long each read takes; mt0_poll treats the argument as a wall-clock deadline in µs. For 1000 that is 101 reads in the kernel and one or two here. The call sites were ported with the kernel's numbers, so each one now waits about 1 ms.

Comment thread src/mt76x0u/init.cpp
/* mt76x0_init_hardware */
static int init_hardware(struct mt76x0u_dev *d)
{
if (!mt0_poll(d, MT_WPDMA_GLO_CFG,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is the call site where the shorter poll matters: mt76x02_wait_for_wpdma(…, 1000) is 101 reads, this is ~1 ms, and a miss is a hard bring-up failure. Please give it the kernel's read budget.

Comment thread src/WiFiDriver.cpp
if (!route_mt76x0u && mt76x0u::is_usb_id(vid, pid)) {
const std::optional<uint32_t> rev =
devourer::mediatek::read_asic_version(dev_handle);
if (!rev) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Regression for an id the MT7612U backend already serves. Before this PR 7392:b711 went straight to Mt7612uRadio, which has its own identify step and retries. Now a failed MT_ASIC_VERSION read refuses the adapter, including in builds with DEVOURER_MT76X0U=OFF where MT7612U is the only backend that could take it. Please fall through to the MT7612U gate when the read fails (and skip the probe entirely when MT76x0U is not compiled in).

Also, the comment in MediatekProbe.h says the synchronous libusb_control_transfer is safe because no backend has an event thread on the context yet. That holds for a single-adapter process only: a caller with a second radio already running on the same libusb_context hits exactly the race the comment describes.

*
* The complete mt76x0_device_table, transcribed from the pinned reference tree
* reference/mt76 @ be5ce79, mt76x0/usb.c:14-44, and held to it by
* tests/mt76x0u_usb_ids_vs_mt76.py. No entry is hardware-verified yet; the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Stale for 0e8d:7610, which the measured record covers. Please state which ids are verified and which are routed only.

Comment thread src/mt76x0u/usb.cpp
* here (it would invalidate the caller's handle) and no kernel-driver detach
* (the caller dealt with it).
*
* Deliberately NOT here yet: the kernel's probe-time sequence

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This paragraph and the other "(phase 3)" references describe a development plan, not the code as it stands (the warm path is in init.cpp/fw.cpp). Please reword to current state.

Comment thread src/mt76x0u/usb.cpp
@@ -0,0 +1,739 @@
/* SPDX-License-Identifier: BSD-3-Clause-Clear */
/*
* libusb transport for the MT76x0U. Copied from src/mt7612u/usb.cpp (the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

usb.cpp and async.cpp are near-copies of the MT7612U transport, so every fix now has to land twice (the abandoned-transfer and status-bit comments in this review are both examples). I would rather see a shared MediaTek transport before this merges than as an open-ended follow-up. If you would prefer to keep this PR scoped, say so and we can agree a tracked issue for it instead.

Comment thread tools/mt76x0u_recover.cpp
* (exits if the device re-enumerated)
* sleep MS
*
* Build (no CMake target; standalone against the backend sources):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

With no CMake target, CI never compiles this against internal.h, so it will rot. Please add a target under DEVOURER_MT76X0U (UNIX-gated if needed, like mt7612uprobe). It should also take a bus/port selector rather than opening the first matching id: with two adapters attached the reset and chip-power steps hit whichever libusb returns first.

dev = _dev;
_dev = nullptr;
if (dev)
mt76x0u_stop(dev);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The kernel powers the chip off on teardown (mt76x0u_cleanup → mt76x0_chip_onoff(dev, false, false)); here the chip stays powered and the firmware running after Stop(). If that is deliberate (it is what makes the next start warm), please say so here and in the doc, since the other backends power down on Stop().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants