147 Commits
Author SHA1 Message Date
Joel Wirāmu Pauling f0019f7aad Merge pull request 'sv6160: clean-room SDIO driver — association through self-recovering wedge handling' (#2) from pkilar/sv6160-rk915:sdio-rx-hardening into main
Reviewed-on: https://codeberg.org/aenertia/sv6160-rk915/pulls/2
2026-11-08 22:38:06 +01:00
Paul KilarandClaude Opus 5 d02a2d511d docs: the branch is soaked — 472 ifdown/ifup cycles, clean
8 hours on the handheld against 3f0f67e, with the coverage the old harness
could not provide.  soak.sh reloaded the module every trial, so anything .stop
stranded was freed by the unload a second later; this run loaded the module
ONCE and cycled the interface underneath it 472 times.

  472 ifdown/ifup cycles, 472 reconnects, 0 failures
  1,089,645 TX descriptors, completions exactly 1:1 (final gap 0)
  per-AC credit leak (<-- GATED):        0 cycles, final ledger all busy=0
  wedges (gap persisting across re-read): 0
  tx_resyncs / tx_ebusy / rx_nomem / oversize: 0, no growth over 8 h
  recovery ladder never fired: tx_resync_giveup 0, host_rebind 0
  independent 60 s sampler, 469 samples: gap never outside +/-2,
    SoC 45.0-53.3 C, mains throughout, device up the whole run

That settles the class this review was mostly about.  The four lifecycle
criticals -- remove() freeing the softc under a live IRQ thread, .stop/.flush
stranding the per-AC credit and leaking batched companions, the unlocked
per-AC counter, and .start re-entered by restart_hw on the previous session's
state -- all live in paths that only matter on a module that stays loaded.
472 of those cycles with a clean ledger every time is the evidence that was
missing when they were written.

What it does NOT settle, stated because the tempting reading is wrong:

  - Zero wedges is NOT the wedge mode fixed.  Section 1 records it as bursty
    (55 inside 36 minutes of a 480-minute run, 7+ clean hours either side), so
    a clean 8 hours is what the quiet periods look like.  Encouraging, not
    evidence.
  - The two behavioural changes still have no A/B.  This run exercised only
    the new build with no paired arms, so the -EBUSY lock release and the
    IRQF_NO_SUSPEND removal remain untested comparatively.
  - Suspend was never exercised: the soak does not suspend.

One harness artefact worth recording so the next reader does not misread it:
`dmesg | grep -c "mac80211 stopped"` ends at 21, not 472, because the kernel
ring wrapped and holds only the last ~1400 s.  21 stops in that window at
~58 s/cycle is one per cycle -- the rate, not the total, is the evidence.

Docs only; the module is byte-identical (cc98b810599f).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-19 18:03:33 -04:00
Paul KilarandClaude Opus 5 3f0f67e174 sv6160: correct two claims this review got wrong about the kernel
Both were found by fact-checking the review's own output against the 6.18
tree, line by line, rather than against what it remembered writing.

  - The comment above devm_request_threaded_irq() said "the PM core masks the
    line for the suspend and latches a wake".  Backwards.  With the wake
    armed, suspend_device_irq() takes the irqd_is_wakeup_set() branch, sets
    IRQD_WAKEUP_ARMED and returns BEFORE any __disable_irq(): the line stays
    enabled through the suspend.  What disables it, marks it pending and
    aborts the suspend is the first assertion after that point
    (irq_can_handle_pm() -> irq_pm_handle_wakeup()).  The line that really is
    disabled at suspend time is one with neither IRQF_NO_SUSPEND nor a wake
    armed.  The behaviour the change was made for is unaffected; the
    explanation was wrong, and a wrong explanation in a comment is how the
    next reader gets it wrong too.

  - KNOWN-ISSUES said a module-reload harness "never exercises" ifdown/ifup,
    mac_stop, mac_flush or remove().  It does: rmmod -> sv6160_remove ->
    ieee80211_unregister_hw -> ieee80211_remove_interfaces ->
    cfg80211_shutdown_all_interfaces -> dev_close, which both disconnects
    (.flush) and stops (.stop), and backtoours.sh brings the interface up
    again afterwards.  What the harness never does is run any of them on a
    module that then STAYS loaded -- a credit or skb stranded by .stop is
    freed by the unload a second later, so "never returned for the module's
    life" leaves no trace, and the .start after a reload always meets a fresh
    softc.  And only three or four of the findings were of that shape: the
    rest ran on every cycle and survived because their knob defaults off
    (cmd_gate, wt_trace), because the firmware never sent the input that
    trips them (runt RX_SERIAS links, event 32), or because the next unload
    erased the damage.  The harness gap is real, but it is "and then keep the
    module loaded", not "never runs .stop".

Also: the A/B baseline paragraph said two code commits sit between a57846c
and 09fd788.  Four commits touch the driver source there, two of them
docs:-prefixed; only a7dfd19 changes executable code.  Subject prefixes lie
in both directions, which is the reason to read the diffs.

Comment and documentation only; no behavioural change.  Builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-19 07:40:23 -04:00
Paul KilarandClaude Opus 5 b0e34e9617 docs: fix three inaccuracies the review's own docs introduced
Self-audit of everything this review touched, checking claims against the code
rather than against what I remembered writing.

  - README said the debug dumps mean "a shared dmesg cannot carry session keys
    or plaintext".  Half true.  SETKEY is redacted and WBODY/RXDATA stop after
    the header plus IV, but RXTAIL still prints the last 8 bytes of a decrypted
    frame -- which ARE payload whenever the firmware stripped the MIC, and
    telling those two cases apart is the whole reason RXTAIL exists.  Kept the
    dump, documented it honestly, and said to scrub a capture taken with it.

  - KNOWN-ISSUES filed three items under "Recorded, not applied" that had in
    fact been applied: the -EBUSY lock release, the IRQF_NO_SUSPEND removal,
    and .start no longer failing fast on a dead card.  They are consequences
    and caveats of applied changes, not deferred work, and reading them as
    deferred would send the next soak looking for behaviour that is already in
    the tree.  Section 5 is now split by what the reader has to DO: soak it,
    A/B it, know about it, or it is still open.

  - The A/B baseline was wrong.  Section 5 said to measure against a57846c
    because that is the last soaked build, but two code commits sit between
    a57846c and the review's parent, so a difference could not be attributed
    to the change under test.  It is 09fd788, with a note saying why the
    soaked build is not the control.

Also verified and left alone: the parameter count (31), tx_batch's default (8,
SV6160_TX_BATCH_MAX) against the ceiling of 9, the debugfs recover return codes
(added the -ENODEV case the text omitted), that tx_ebusy and tx_bulk_done are
really in debugfs tx_tokens before telling anyone to measure them, and that no
document still references a symbol this review deleted.

One thing found in the code and recorded rather than fixed: bcn_timer re-arms
itself on beacon_enabled && vif, which timer_delete_sync() cannot stop, and
nothing clears beacon_enabled on the way down.  Pre-existing and identical in
mac_stop, harmless today only because the TX worker's is_rpu_ready gate catches
the frames, AP/IBSS only.

No code changes; the module is byte-identical (cc98b810599f).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 19:39:07 -04:00
Paul KilarandClaude Opus 5 92cb22740f docs: record the convergence pass, including what it found wrong
Section 5 now says that three of the review's own fixes did not do what their
comments claimed and were fixed in turn, because "a review fixed this" is worth
less than knowing the fix was checked and what checking it caught.

Five further findings are recorded without being acted on, each with its
mechanism and no measurement behind it:

  - The -EBUSY back-off releasing sc->lock also admits control-command CMD53s
    between a failed TX descriptor attempt and its retry, and the descriptor
    and body are matched by arrival order.  So that change needs measuring
    against frames-never-transmitted, not only against the wedge rate.
  - Dropping IRQF_NO_SUSPEND changes suspend under RX load rather than simply
    fixing it: a pending host-wake now aborts the suspend and it retries,
    where before it drained through.
  - .start on a dead card now blocks for seconds under rtnl rather than
    returning -EIO, because the gate that made it fast also made an exhausted
    bring-up permanent.
  - The local scan abort races the drain's SCAN_COMPLETE for scan_request.
  - Stopping a truncated RX_SERIAS chain still rings the notify doorbell, which
    this file elsewhere records as its own fatal outcome; done_no_ack exists
    for that shape and the choice between them should be deliberate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 17:27:27 -04:00
Paul KilarandClaude Opus 5 ac57ada73d tools: serctl.py signals a timeout as 124, not 2
2 is a real remote exit status -- `ls` on a missing path and `grep` on an error
both use it -- so the contract the previous commit introduced could not
actually tell a hung handheld from either.  124, as timeout(1) uses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 17:27:27 -04:00
Paul KilarandClaude Opus 5 48a253db26 sv6160: fix three fixes from 9de36d7 that did not do what they claimed
A convergence pass over 9de36d7 -- re-reviewing the fixes rather than the code
they fixed -- caught three of them closing nothing, plus three smaller misses.
Two of the three are the same mistake: a guard added on one path while the
sibling path that reaches the same code was left alone.

  - The probe-window fix was inert.  It ADDED sc->is_firmware_loaded = true to
    core_init without removing the one in boot_firmware, and probe runs
    boot_firmware first, so the flag still went up before core_init allocated
    rx_buf and INIT_WORK'd rx_work.  Worse than inert: the old assignment sits
    ABOVE boot_firmware's own "clear the boot GPIO burst" block, whose comment
    says those assertions "are ignored by the handler because
    is_firmware_loaded is still false" -- which that line had already made
    untrue.  A host-wake there drains into a NULL rx_buf.  Removed; the flag is
    now raised only by core_init (probe) and fw_reboot (every later boot).

  - The runt-length guard went on the first RX link only.  The chain walk
    re-enters the loop with pkt_len = rx_next_len, taken either from the
    previous link's upper 16 bits or verbatim from serias_next_len, and
    screened only against the upper cap.  A chain pointer of 1..27 then got
    __dev_alloc_skb(pkt_len) followed by a read and a REWRITE of hdr->length at
    offset 20 of it, i.e. into the skb's shared info.  Same test as the first
    link now applies to the chain pointer.  process_event's own runt check
    cannot help here: rx_drain touches the header before it ever calls it.

  - sv6160_quiesce_for_bringup left the RX side running, which is most of the
    point of it.  Its charter says "every one of these can otherwise put a
    CMD53 on the bus during the upload", and rx_drain gates only on
    gpio_irq_pending, with no is_firmware_loaded test at all -- so an rx_work
    already queued when the wedge hit would read SDIO address 0 between two
    image chunks.  scan_poll's trigger_rx queues one every 500 ms and a wedge
    under scan traffic is the common case, so at quiesce time there is very
    likely one queued.  Added rx_poll, rx_work and bcn_timer.

And three smaller ones from the same pass:

  - remove() cleared is_firmware_loaded AFTER core_exit, whose last statement
    is ieee80211_unregister_hw().  An event drained in that window reaches
    handlers that call into a wiphy being torn down -- SCAN_COMPLETE ->
    ieee80211_scan_completed() after wiphy_unregister()'s final cancel.  The
    flag now goes down first; it costs nothing, because the only command the
    teardown sends (remove_vif) waits for no reply.  The devm_free_irq stays
    where it was, still before ieee80211_free_hw().

  - The rung-2 escalation TEST was left outside the new sdio_wedged guard while
    the counting moved inside it, so recover_count never decayed for a caller
    that does not set sdio_wedged.  At the default host_rebind=3 the escalation
    zeroes the count itself so it can only sit at 0..2 and the path is closed,
    but host_rebind is a documented tunable and at 1 or 2 one stale bus wedge
    would make the next TX-link death spend the one-shot host re-create -- the
    exact conflation the commit claimed to remove.

  - tx_quarantine is named in tx_token_lock's comment as something it guards,
    and the reclaim path wrote it with no lock held while get_token clears the
    same slot under that lock.  A lost stamp hands a still-firmware-owned id
    straight back out.

Cross-compiles clean, zero warnings.  Still not soaked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 17:27:14 -04:00
Paul KilarandClaude Opus 5 f5a42b7818 docs: record what the review changed, and what still needs measuring
README:

  - The recovery-ladder section now says which two details changed and that
    neither has been re-soaked: rung 2 counts only bus faults, and mac_start
    quiesces before the firmware re-upload because restart_hw never calls
    .stop.  The second one is the likely explanation for the "made things
    worse" row in KNOWN-ISSUES, so it is stated where that claim is repeated.
  - The debugfs recover knob's return codes are written down, since they are
    now the difference between exercising the deep rung and silently getting
    the shallow one.
  - The parameter section says fwpoke/fwpoke_when are insmod-only and that
    the dumps no longer carry keys or plaintext.
  - The suspend row is marked as measured BEFORE IRQF_NO_SUSPEND was dropped
    from the host-wake IRQ.  It is the one Current State row this branch
    invalidated.

KNOWN-ISSUES:

  - New section 5 lists what the review applied and what it did not.  The
    correctness fixes want an ordinary soak.  The two behavioural changes --
    the -EBUSY back-off releasing sc->lock, and the suspend gating -- want a
    paired A/B against a57846c, per this file's own measurement rules; the
    first is a candidate mechanism for the wedge mode in section 1 and should
    be measured against tx_ebusy and the wedge rate rather than assumed.
  - Four things are recorded WITHOUT being applied, each with its evidence
    and no measurement: the level-IRQ re-fire during firmware upload, the
    vmalloc/stack buffers handed to sdio_memcpy_toio() that silently force
    PIO, cmd_gate's force-retire path having no soak evidence (it deadlocked
    the drain until this review, so it could not have had any), and the
    event-32 handler now being counted so it is visible if it ever fires.
  - The restart_hw row in section 2b carries the explanation rather than just
    the observation.

SDIO_ARCHITECTURE: a banner under the title saying which sections are still
the reference and which are a historical snapshot; the "Current Blocker: CMD53
Read Timeout (-110)" section is retitled as resolved and points at README.
Nothing was deleted -- the investigation record is the point of the file --
but a reader arriving at it was being told a fixed bug is current.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 13:59:36 -04:00
Paul KilarandClaude Opus 5 0e6129f9c1 tools: make the harness report failures instead of hiding them
From the same review.  Each of these makes a failed run look like a different,
wrong thing, which is worse than failing loudly.

  - reloadp.sh echoed `insmod rc=$?` AFTER a `sleep 6`, so it reported sleep's
    status, not insmod's.  A rejected module parameter -- the entire purpose
    of that script -- always logged rc=0.
  - backtoours.sh never captured insmod's status at all, so a load failure
    and a connect failure were both "NOT CONNECTED after 40s".
  - sdioreset.sh logged the post-bind device count and then exec'd into
    backtoours.sh regardless, so a failed rebind also surfaced as a generic
    connect failure.  It now stops with REBIND-FAILED.
  - serctl.py returned whatever partial bytes it had when the end marker never
    arrived, and exited 0 no matter what happened on the device.  A harness
    step checking only the exit code could not tell a wedged handheld from a
    successful command.  It now exits 2 on timeout and propagates the remote
    command's own status.
  - flightrec.sh collected EVERY connected wlan interface into $IF, so with a
    second vif present it became two words and every `iw dev $IF` below it
    silently produced nothing -- in the one log that survives a reboot.  It
    now filters on driver == sv6160, like backtoours.sh already did, and takes
    one.
  - backtoours.sh sorted `wdev <hex>` lexically to pick the lowest wdev, which
    is the bug it was written to avoid as soon as an id reaches two digits
    (0x10 sorting before 0x2).  Numeric now.

Also: backtoours.sh sourced /storage/sv6160.conf as shell code to read one
variable, as root, from the user-data partition ROCKNIX exports over SMB.  It
parses the SSID= line instead.

Dedup: gen_fw_patch.py and gen_fw_macfix.py had a byte-identical main();
serctl.py and serial_capture.py each hardcoded PORT and BAUD.  Both now share
a module (fw_patch_common.py, tools/serial_common.py), with the serial pair
taking SV6160_SERIAL_PORT / SV6160_SERIAL_BAUD overrides.

Behaviour of the fw-patch scripts is unchanged, including the abort path on a
byte mismatch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 13:59:18 -04:00
Paul KilarandClaude Opus 5 9de36d7731 sv6160: fix the lifecycle and accounting bugs a reload harness never hits
A seven-pass review of this branch (testing, maintainability, security,
performance, simplification, adversarial, red team) found 13 crash-, deadlock-
or leak-class defects.  Every one was verified by reading the code on both
sides of the defect before it was touched.

They share a reason for surviving the 8 h soak: the harness recovers by
rmmod/insmod, so it never exercises ifdown/ifup, mac_stop, mac_flush,
remove(), or the restart path's own state.  Those are exactly where these live.

Use-after-free and ordering:

  - remove() called ieee80211_free_hw() while the threaded host-wake IRQ was
    still registered.  devm frees that IRQ only AFTER remove() returns, i.e.
    after the softc is gone, and rung 2 of the recovery ladder runs remove()
    precisely when the level line is stuck high with the thread mid-drain.
    Free both IRQs and flush rx_work first, the way the probe error path
    already did; the probe path now flushes rx_work too.

  - is_firmware_loaded went true inside boot_firmware, which probe calls
    BEFORE core_init allocates rx_buf and INIT_WORKs rx_work -- with both IRQ
    paths already registered and gating on that flag.  A host-wake in that
    window drained into a NULL rx_buf.  It is now raised in core_init once the
    drain has somewhere to land, and re-raised by fw_reboot on success.

  - The wt_trace WT53 RX line read ((struct rpu_msg_hdr *)skb->data)->id ten
    lines before skb was allocated: uninitialised stack on chain link 0, and
    on later links the previous link's skb, already consumed by
    process_event().  Read the id from sc->rx_buf, which is what was just
    filled.

  - tx_pending[slot] was published before sv6160_sdio_write_tx() read
    bodies[i]->data, and tx_retire_all() took no lock, so the resync could
    claim the descriptor and hand every frame in it to mac80211 while the
    CMD53 was still copying from them.  The worker now marks tx_writing[id]
    before publishing and clears it when the write returns; the reclaim path
    skips a descriptor that is being written.

Deadlock:

  - The CMD53 writers guarded recursion with current_work() != &sc->rx_work.
    current_work() is NULL in a threaded IRQ, which is where the drain runs
    since it moved there, so a write reached from inside the drain (the
    cmd_gate kick on COMMAND_PROC_DONE) re-took the mutex it already held and
    the IRQ thread slept on itself for good.  cmd_gate defaults off, which is
    the only reason this never fired.  sc->lock now records its owner task and
    the guard compares against current.

Accounting that never recovers:

  - mac_stop and mac_flush(drop) zeroed tx_token_bmp but never
    tx_outstanding_ac[], whose only decrement is gated on a bit they had just
    cleared.  Any AC with descriptors in flight at stop time kept its count
    for the module's life: get_token refuses it, the worker stops every queue,
    and tx_resync cannot help because !tx_token_bmp returns early.  They also
    never freed the batched companions in tx_batch[][], and stored NULL over
    tx_pending[] with plain stores that raced the cmpxchg completion path.
    One sv6160_tx_drop_all() now does all of it under the token lock, and
    mac_flush cancels tx_work first like its siblings.

  - tx_outstanding_ac[] is a plain u8 incremented in the TX worker and
    decremented from the IRQ thread and the resync work.  A lost update is
    permanent and is exactly the "<-- GATED" state the debugfs ledger was
    written to diagnose.  Added tx_token_lock around the pool.

  - tx_outstanding was added AFTER the slot was published, so a completion
    claiming it in between decremented what was never added and drifted the
    counter negative for the rest of the session.  Count first, undo on the
    write-failure path.

  - RPU_EVENT_HOST_DATA_TX_DONE (id 32, which the firmware does emit per the
    comment at its own case label) bulk-completed with plain stores, never
    freed the tokens, and ignored tx_batch[][].  If it ever arrived it gated
    every AC for good.  Routed through the same claim path and counted as
    tx_bulk_done in debugfs, because whether this firmware emits it is the
    thing worth knowing next time TX dies.

Firmware-supplied lengths:

  - An RX_SERIAS sub-packet shorter than struct rpu_msg_hdr (28) had its
    hdr->length read AND rewritten past the aggregate's tail, which has 0-63
    bytes of tailroom and skb_shared_info behind it.  Same for a top-level
    RECV_LEN of 1..27.  Both are now rejected, and process_event() drops a
    runt rather than reading an event id out of allocation slack.

  - Any early exit from the sub-packet loop left serias_next_len holding a
    sub-packet's in-aggregate "next", which the drain then read as a chain
    link the firmware never queued: the -110 that wedges the controller.  The
    chain is stopped instead.

  - The OOM path set gpio_irq_pending via trigger_rx and then cleared it at
    clear_and_done, so the rescheduled drain returned at its own gate and the
    aggregate was stranded.

Recovery ladder semantics:

  - ieee80211_restart_hw() re-enters .start WITHOUT calling .stop --
    ieee80211_reconfig() calls drv_start only.  Two comments here claimed the
    opposite, and the consequence was that is_rpu_ready stayed true so the TX
    worker kept writing descriptors to SDIO address 0, the address a WAIT_FW
    MCU takes image bytes at, while fw_reboot re-uploaded the firmware there.
    The resync kept firing, the command gate and fwpeek kept sending.  That is
    very likely the "restart_hw made things worse (4->8 resyncs, 6->13 lost)"
    recorded in KNOWN-ISSUES.  mac_start now quiesces its own state first.

  - The 60 s rung-2 counter counted every trigger_recovery() call, including
    the tx_resync_giveup escalation and a debugfs level-1 write.  Three
    TX-completion link deaths inside a minute -- a mode whose median gap is
    28 s -- therefore re-created the dw_mmc host instead of the restart_hw
    that was measured to fix that failure, conflating the two failure modes
    the rest of this driver's notes insist on keeping apart.  Only sdio_wedged
    faults count now.

  - mac_start refused with -EIO when is_firmware_loaded was false, which is
    the state an exhausted bring-up leaves, so the interface could never come
    back without rmmod.  fw_bringup re-uploads the firmware itself; the gate
    is gone.

  - recover_work aborts a hardware scan before restart_hw (mac80211 WARNs
    otherwise), and hw_scan now fails cleanly instead of scheduling a sweep
    fallback that could not run: rpu_scan() had already dropped scan_request,
    so scan_work bailed without completing anything and mac80211 stayed in
    SCAN_HW_SCANNING until a module reload -- no scan, no roam.

mac80211 contracts:

  - tx_status_skb() was mixed with tx_status_irqsafe() on one hw, which
    mac80211.h forbids.  All completions are irqsafe now.
  - Frames delivered after .stop hit WARN_ON(!local->started) per frame.
  - connection_loss() is STA-only; on an AP/IBSS vif it scribbles the u.mgd
    union.
  - RX BA sessions were programmed against vif->bss_conf.bssid, which is our
    own address in AP/IBSS mode.  Use the STA's.
  - remain_on_channel never called ieee80211_ready_on_channel(), so every ROC
    expired without the off-channel work ever starting.
  - The PMF branch set encrypt=1 with a hardcoded iv_len=8 without consulting
    hw_key, so a frame mac80211 had already encrypted in software would have
    been encrypted again.

Debug surface, before anyone else reads this tree:

  - wiredump and wt_trace>=2 hex-dumped RPU_CMD_SETKEY, i.e. the PTK/GTK, and
    the WBODY/RXDATA/RXTAIL dumps carried plaintext payload.  Keys are
    redacted and the frame dumps stop after the header plus IV.
  - fwpoke/fwpoke_when are 0400: they write firmware memory.  The charp is
    read under kernel_param_lock().
  - fw_peek and fw_addr_ok compared addr + len, which wraps; addr=0xFFFFFFFC
    len=4 passed both.
  - chan_settle and sweep_len are clamped (a negative chan_settle was a 49-day
    msleep under the wiphy lock; a negative sweep_len was ~2^30 iterations of
    msleep(60) that cancel_delayed_work_sync would then wait for).  Negative
    tx_stall_ms, host_rebind and tx_resync_giveup mean off rather than "fire
    on the first event".
  - The debugfs recover knob returns -EINVAL/-EFAULT rather than silently
    running the shallow rung, and -EBUSY when the deep one is a no-op.
  - The TX bounce buffer was 3 bytes short of what write_tx could put in it.
  - The beacon RXCH line is dev_dbg: it was one printk per received beacon.

Behavioural, applied as experiments -- A/B these against a57846c before
trusting either direction (see KNOWN-ISSUES section 5):

  - The -EBUSY back-off now drops sc->lock, not just the host claim.  The
    comment claimed releasing the claim "lets the RX drain interleave", but
    the drain takes sc->lock BEFORE the claim, so for up to 16 x 25 ms the
    chip was held busy by the very frames it was waiting for us to collect,
    and the tries ran out into a declared wedge.  Candidate mechanism for the
    open wedge mode.
  - IRQF_NO_SUSPEND is gone from the host-wake IRQ (it is documented as
    incompatible with the enable_irq_wake() next to it) and the thread refuses
    to drain while is_suspended, where it was issuing CMD53s to a host being
    clock-gated.  Suspend needs re-verifying.

Dead state removed: gpio_irq_disabled and the three enable_irq blocks that
tested it (nothing set it since the IRQ went threaded), rx_queue, need_reinit,
last_drain_jiffies, dwmmc_regs, PS_MODE_*.

Cross-compiles clean for aarch64, zero warnings.  NOT yet soaked: the
lifecycle fixes want an ifdown/ifup cycle in the harness, which is the gap
that hid them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 13:59:03 -04:00
Paul KilarandClaude Opus 5 09fd7881db docs: re-verify the Current State table against the device
Three rows in this table had already been caught as wrong by the user, so the
rest were checked rather than trusted.  Five more were stale or misleading:

  - "mac80211 registration (wlan0)" -- the interface is wlan22 right now.  The
    index increments on every reload and host re-create, so naming wlan0 in the
    table invites a wrong assumption in every script that reads it.
  - "Firmware upload (48KB) + patch (16KB)" -- the blobs are 48056 and 16716
    bytes.  Stated exactly now.
  - "NOP ping (data path verification) | Working" -- sv6160_rpu_fw_priv_nop()
    is compiled in and has NO callers anywhere in the driver.  The row
    described dead code as a working feature; it presumably was a bring-up
    check before real traffic existed.
  - "authenticated ~19ms after the auth frame" -- measured now at 9.7 ms
    (81579.373474 -> 81579.383137).
  - A-MSDU still said mac80211 "never builds one", contradicting the section
    added directly below it in the same file: with SUPPORT_FAST_XMIT it does
    build one (tx_max_frame 3080), and the chip then cannot carry it.

Verified live and correct: m0_ready, RESET_COMPLETE, FW_PRIV_INIT, VIF add,
channel programming, scan finding 12 BSSes, auth/assoc/4-way/DHCP, tx_frames ==
tx_done_events at 3099, 81k RX drains.

Rows resting on a single past measurement rather than anything re-checkable --
the 8h soak, suspend/resume, the roaming walk -- now say "measured" so it is
clear they are historical evidence rather than a live property.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 10:11:18 -04:00
Paul KilarandClaude Opus 5 f64d378b63 docs: record where the MAC comes from; fix a heading I doubled
Two things.

First, the useful half of the MAC story, which the previous commit corrected
but did not explain: the address is the FACTORY MAC and it is PER DEVICE.  It
lives in Rockchip vendor storage (tag 0x524B5644, sector 7296, item id 3), the
same place the BSP read it from via rockchip_wifi_mac_addr().  Vendor U-Boot
reads it, exports ethaddr, and fdt_fixup_ethernet() writes it into whatever
/aliases/ethernet0 resolves to; ROCKNIX points that alias at the wifi node, so
of_get_mac_address() finds local-mac-address there.  The 1e:28:78: prefix is
common to the family and the low three bytes are per unit, so this is not one
unit's address baked into a shared DTS.

Also scopes reading the SV6160's own eFuse, since the old table row implied a
missing feature.  The registers are known (EFUSE_CTRL 0xC0000134, offset in
bits 0-5, busy in bit 7; EFUSE_RDATA 0xC0000138; MAC at eFuse offset 0x10) and
fw_peek's rw=0 is a plain load with no firmware-side address validation, so the
MMIO is reachable -- the SRAM window is our own guard.  It would cost widening
that guard, a write path for EFUSE_CTRL (only rw=0 has ever been exercised),
and busy-polling.  It would very likely buy a blank eFuse: the factory
provisioned vendor storage instead, which is exactly why the BSP reads vendor
storage.  Only a board with neither a vendor-storage MAC nor a DT property
would benefit.

Second, repairs "### Recovery ladder### Recovery ladder" in the A-MSDU commit
(768b42a).  That splice ended with the heading and was pasted onto a slice that
began with it, so the two ran together.  Caught by an assertion refusing to
match the anchor on the next edit, not by rereading the file -- worth the note.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 10:06:23 -04:00
Paul KilarandClaude Opus 5 fc9160b949 docs: the MAC address is stable and comes from the device tree
The Current State table said "eFuse MAC address | Not implemented (random
MAC)".  Both halves are wrong, and it was wrong in the opposite of the useful
direction: it claimed an instability the driver does not have.

On this board the MAC is fixed.  The DT carries local-mac-address on the
wifi@1 node under mmc@ff380000, of_get_mac_address() picks it up, and dmesg
says so on every load:

    sv6160 mmc2:0001:1: MAC 1e:28:78:e8:94:15 from device tree

ethtool -P reports the same value as the permanent address, and it has been
identical across every reload and reboot in this session's logs.

The code comment was stale in the same way -- it described the DT path as "the
right answer if the board ever describes one.  This board currently does not."
It does.  Corrected, with the command to check it and a note that
/proc/device-tree is a symlink, so a plain `find` will not see the property
(that is what made me miss it on the first pass).

What genuinely is not implemented is reading a MAC out of the SV6160's own
eFuse, which is a different thing and not needed while the DT supplies one.
The random fallback exists but is unreachable here; it only runs if both the DT
property and the RK3326 OTP fail.

Reported by the user, who noticed the handheld's MAC does not change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 10:00:14 -04:00
Paul KilarandClaude Opus 5 768b42a0b6 sv6160: root-cause A-MSDU -- we never set SUPPORT_FAST_XMIT, and the chip cannot carry it
Chased down properly instead of guessed at, and every previous explanation in
this repo turned out to be wrong.

WHY IT NEVER ENGAGED.  ieee80211_amsdu_aggregate() has exactly one call site,
inside ieee80211_xmit_fast().  mac80211 only populates sta->fast_tx when the
driver advertises IEEE80211_HW_SUPPORT_FAST_XMIT, and
ieee80211_check_fast_xmit() returns at its very first line without it.  We
never set that flag, so the aggregation code was structurally unreachable.  We
did set TX_AMSDU, which only says we can ACCEPT an aggregated frame -- not that
mac80211 should build one.

Adding the flag works: tx_max_frame went 1542 -> 3080, two MSDUs in one frame,
the first A-MSDU this driver has sent.

AND IT IS UNUSABLE.  Throughput collapsed from 0.77 MB/s to 0.02-0.08 MB/s,
with sdio_write_data() failing -16 and the host-rebind recovery firing.  The
chip will not carry the larger body, which is consistent with the rule already
recorded here that padding a CMD53 to the block size kills the link and that
the vendor found concatenating does too.  So A-MSDU is closed as a throughput
lever -- now for a measured reason rather than a guessed one.

REFUTED ON HARDWARE, recorded so nobody repeats them:
  - "the peer does not advertise a usable max_amsdu_len" -- it does, iw decodes
    the AP's HT capabilities as "Max AMSDU length: 7935 bytes"
  - "the ADDBA Response clears the A-MSDU bit so mac80211 latches
    IEEE80211_TXQ_NO_AMSDU on the TID" -- refusing TX BlockAck outright left
    tx_max_frame at 1542 and cut throughput 5x
  - "blocked on a pull-model TX rewrite" -- that rewrite exists (mod_txq) and
    could never have helped: with fast-xmit off no TX model can aggregate

METHOD NOTE, because it cost three invalid runs: SUPPORT_FAST_XMIT is latched
at probe from mod_amsdu, so it has to be passed to insmod.  Setting amsdu=1 by
sysfs after loading measures the unflagged driver and produces a clean-looking
negative result.  The probe build was made to log its own flag state and the
harness to discard any arm that could not prove it, which is the only reason
the real answer surfaced.

Comment and README only; no behavioural change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 09:39:39 -04:00
Paul KilarandClaude Opus 5 aa908e8c7f docs: correct the A-MSDU status -- the pull-model rewrite exists and is active
The Current State table said A-MSDU was "blocked on a pull-model TX rewrite".
That is wrong twice over, and it was my error: the claim was carried forward
from notes into yesterday's README rewrite without being checked.

The rewrite is implemented.  mod_txq wires .wake_tx_queue to
ieee80211_tx_dequeue, and it works -- txq_pulled climbs into the thousands, so
frames really are being pulled rather than pushed.  It was written precisely to
unblock A-MSDU: the push shim drains the txq on every wake, so mac80211 never
has a queued head for ieee80211_amsdu_aggregate() to append to.

It did not unblock it.  Measured now, on hardware:

    txq=0 amsdu=0   0.92 MB/s   tx_max_frame 1542   txq_pulled 0
    txq=0 amsdu=1   0.95 MB/s   tx_max_frame 1542   txq_pulled 0
    txq=1 amsdu=1   0.79 MB/s   tx_max_frame 1542   txq_pulled 4392

tx_max_frame stays at one MSDU in every combination, so no A-MSDU is ever
built, and the pull model costs throughput -- which is why it defaults off.

The payoff was also overstated, and the code comment still argued for it from a
premise this repo has since refuted: "~500 us of fixed cost per CMD53 almost
regardless of size".  Measured, 326 B costs 318 us and 1530 B costs 1592 us --
intercept about zero.  Cost scales with bytes, so A-MSDU saves per-frame header
and contention overhead only, not a fixed per-command charge.  That comment now
says so instead of the opposite.

What remains genuinely unchecked is the peer's advertised max_amsdu_len:
mac80211 will not aggregate if the AP does not offer one, and that is decided
by the AP rather than by us.  Recorded in both places as the next thing to
look at.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 07:39:15 -04:00
Paul KilarandClaude Opus 5 453e06ba1e tools: fix the flight recorder going blind after any driver reload
The debugfs path was resolved once at start-up and cached for the life of the
script.  The phy number changes on every driver reload and every SDIO host
re-create, so after the first recovery the cached path was stale and every
counter field logged empty -- tx=, done=, resync= -- while the timestamp,
battery, temperature and signal kept recording normally, so the log looked
perfectly healthy.

Caught by reading an actual overnight capture: the counters went blank at entry
29, exactly when the driver was reloaded, and stayed blank for the remaining
2.5 of its 2.8 hours.  The recorder exists to catch the wedge burst, a wedge is
followed by a recovery, and a recovery is precisely what blinded it -- so it
would have been useless for its one job.

Resolve the path every iteration, and log an explicit "nodev" rather than an
empty field when it cannot be found, so this can never fail silently again.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-18 00:25:10 -04:00
Paul KilarandClaude Opus 5 d3d26c3052 docs: bring the README up to date, and ship the on-device harness
The README described a driver from several days ago.  An upstream reader would
have been told the SDIO wedge "is the current blocker", that the link "held 48s"
and that the usable connection was "Blocked -- DHCP does not complete".  All
three are stale: DHCP works and carries the ssh session this is developed over,
an 8 h soak moved 2,149,692 TX descriptors with every one completed, and the
wedge now self-recovers in about ten seconds.

Fixed in the README:
  - status line and Current State table rewritten against measured reality,
    including a self-contradicting duplicate row (WPA key management appeared
    as both "Working" and "Not yet exercised")
  - new Recovery ladder section, since self-recovery is the main behavioural
    change and was documented nowhere
  - Module Parameters listed 5 of 31 and included mac_program, culled two
    sessions ago.  Now lists the ones that change behaviour, points at modinfo
    for the rest, and carries the tx_batch clamp warning -- that trap
    invalidated ~1173 transfers of evidence once already
  - Known Issues listed three problems, all since fixed; now points at
    KNOWN-ISSUES.md and says what resolved them
  - a note that firmware/README.md and VENDOR-DRIVER-FINDINGS.md reference
    parameters that no longer exist.  Those are records of experiments, not
    current knobs, so the history is left intact rather than rewritten

Also adds tools/device/, which until now existed only on the handheld and would
have been lost by a reflash: the reload/reconnect harness, the deep SDIO
unbind/bind recovery, a parameterised reload, and the flight recorder.  They
encode three traps worth keeping: pick the interface by wdev rather than name
(userspace adds a second never-upped vif that can sort first), never unbind
ff370000.mmc because it holds /storage, and verify the load-test listeners
actually bound because a socat that loses the bind race dies silently.

The reconnect script had a hardcoded SSID; it now reads one from
/storage/sv6160.conf with a neutral default.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 23:43:19 -04:00
Paul KilarandClaude Opus 5 a7dfd19029 sv6160: fix the host-rebind guard latching before it could fail
Found in review of 53493a1.  The one-shot guard was set BEFORE the two steps
that can fail:

    sv6160_host_rebound = true;
    rb = kzalloc(sizeof(*rb), GFP_ATOMIC);
    if (!rb)
            return;                 /* latched, nothing queued */
    if (!try_module_get(THIS_MODULE)) {
            kfree(rb);
            return;                 /* latched, nothing queued */
    }

Either failure left the guard latched with no work queued, and the only release
was sv6160_rebind_note_probe_ok() from a SUCCESSFUL probe -- which is precisely
what cannot happen in the state this mechanism exists for, where the bus is
wedged and probe fails -16 before drv->probe is even entered.  So one transient
allocation failure would have silently disabled the escalation for the rest of
the module's life, logging "already re-created once" forever while never
actually re-binding anything.  Now claimed with cmpxchg and released again on
every path that does not queue the work.

Three more from the same review:

  - The guard was a plain bool with a non-atomic test-and-set.  Two callers on
    different CPUs could both see it clear and queue a rebind each; the second
    teardown would then destroy the host the first had just re-created.  It is
    an atomic_t claimed with cmpxchg now.

  - The re-arm from probe() raced the attempt it belonged to.  mmc_rescan runs
    asynchronously, so the new probe can land while device_attach() is still in
    flight and clear the guard from under it.  The release moves into the work
    function, after the attempt finishes, and happens only when the re-bind
    actually succeeded -- a failing one stays latched rather than looping.
    sv6160_rebind_note_probe_ok() is gone.

  - GFP_ATOMIC was both unnecessary and the worst flag for the moment: every
    caller is sleepable (each holds sc->lock, or is a work item or a syscall),
    and atomic reserves are exactly what is scarce when a wifi driver is dying.
    GFP_KERNEL, and the "safe from any context" comment corrected to say
    process context.

Also: the failure path now prints the sysfs bind recipe, since a re-bind that
does not bind leaves the card absent with no automatic way back; the
"not looping" warning is ratelimited (the caller resets its counter every 3 bus
recoveries, so it could stream); and a note records that this pair is what
device_reprobe() does, and that module_put() at the end of a work item leaves a
narrow window where rmmod can free the text the epilogue is still running in.

Verified on hardware: triggered the rebind twice in a row via debugfs.  Both
re-created the host and reported OK, with zero spurious "already tried"
warnings -- i.e. the guard is released after a success, which is what the racy
probe re-arm only achieved by accident.  Link healthy afterwards, counters 1:1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 23:43:05 -04:00
Paul KilarandClaude Opus 5 d79c78015c docs: write up the open bugs, with what has been ruled out
The wedge-prone mode is mitigated but not fixed, and most of what is known
about it is negative results -- expensive to obtain and easy to re-run by
accident.  KNOWN-ISSUES.md records them so nobody repeats a dead hypothesis.

Covers:
  1. the wedge-prone MODE -- a mode, not bad luck: all 55 wedges of an 8h soak
     fell inside 36 minutes of a 480-minute run (random would span ~463), gaps
     median 28 s.  Six hypotheses ruled out with real sample sizes, including
     "a wedge leaves residue" (post-wedge susceptibility 0/48 == baseline
     0/48), so the mode is NOT self-sustaining.
  2. the two distinct failures underneath it -- TX-completion link death
     (resyncs, no bus errors) vs hard SDIO bus wedge (-16, probe failing) --
     with the measured recovery ladder for each, and why recovery cannot be
     hooked into probe().
  3. the unexplained reboot, and the flight recorder now in place to catch the
     next one (no ramoops on this board).
  4. throughput vs the vendor reference and why the levers are exhausted.

Also records the measurement rules this repo keeps relearning: no single-trial
A/Bs, no throughput A/B across a reload, alternate arms every cycle, verify a
module parameter actually took effect (tx_batch clamps silently), and never
infer driver state from a proxy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 23:22:08 -04:00
Paul KilarandClaude Opus 5 a57846cbeb sv6160: enable tx_resync_giveup by default; it was re-measured and it works
tx_resync_giveup has sat at 0 since 2026-09-12 with a comment saying it "was
measured doing harm and never measured doing good", and ending "it must be
re-measured before being trusted".  Re-measured, on a live link death rather
than a synthetic one.

The device entered the classic state during a soak: associated, holding an IP,
and unreachable.  71 descriptors sent and never completed, tx_resyncs climbing
past 40, token_bmp 0x042, signal -46 dBm and the battery charging, so neither
RF nor power.  Nothing escalated, because this was 0 -- exactly the "it never
self-recovers" behaviour on record.  Setting it to 3 logged

    TX engine dead across 3 resyncs - restarting hw

ssh returned immediately, and across the next 971 frames the sent-vs-completed
gap stayed at exactly 77: every new descriptor completed and no new resync
fired.  The 77 were the historical losses from the wedge.

The old objection was specific and is answered.  It used to misfire during
connection teardown, where ieee80211_restart_hw() produced WARNINGs in
ieee80211_reconfig()/ieee80211_del_chanctx().  Across an 8 h soak of 2180
cycles rotating tx/rx/both it fired 16 times, every one of them on a genuine
stall, and not once during teardown or idle.

Soak on this build (da28aab69a16), the same binary this commit rebuilds to:

    2180 cycles, 8 h, tx_frames == tx_done_events at 2,149,692 EXACTLY
    55 wedges, ALL 55 self-recovered, 0 needed intervention
    50 of 55 recovered in 10-11 s; worst 171 s
    16 restart_hw escalations, 1 SDIO host re-create
    7.16 M RX drains, 17.7 M packets, 0 oversize, 0 nomem
    0 oops, 0 reboots, pio 0

Before this, every one of those 55 events was a dead radio needing an
unbind/bind typed in over the serial console.

The two rungs compose, and the soak exercised the join for real: three
fruitless resyncs restart the hw, and when three of those inside a minute
still do not clear it, sv6160_rebind_sdio_host() re-creates the SDIO host.
That second rung fired once, immediately after three failed restarts.

Also records a distinction this session kept collapsing: the TX-completion
link death (descriptors never completed, resyncs climbing) and the hard SDIO
bus wedge (-16/-110 faults, probe failing) are DIFFERENT failures with
different triggers.  The host-rebind escalation added in 53493a1 counts bus
recoveries and does not see resyncs at all, so it could not have rescued the
state above -- which is why that state sat there until this lever was turned
on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 21:18:05 -04:00
Paul KilarandClaude Opus 5 53493a14b3 sv6160: recover a wedged SDIO bus by re-creating the host
A hard SDIO wedge has stranded this device repeatedly, and nothing the driver
could do brought it back -- each time it needed an unbind/bind of
ff380000.mmc typed in over the serial console.  With tx_batch>9 as a reliable
way to provoke one, the recovery ladder could finally be measured on a real
wedge rather than guessed at:

    ieee80211_restart_hw   clears a SOFT wedge well (~11 s, "attempt 1 OK"),
                           but on a hard one it does nothing; watched once
                           taking a wedge from 4 to 8 resyncs and 6 to 13
                           lost descriptors
    mmc_hw_reset           returns SUCCESS and does not help.  With a single
                           function probed it is mmc_power_cycle +
                           mmc_sdio_reinit_card, and dmesg shows the bus
                           dutifully renegotiating 400kHz -> 50MHz while
                           staying wedged
    module reload          probe still fails -16, no netdev
    unbind/bind            CLEARS it every time

The problem is the HOST, not the card: only re-running dw_mci_probe() puts
the controller back in a working state.  A function driver cannot call that,
but it can ask the driver core to re-bind its own grandparent, which is
exactly what the sysfs unbind/bind does.  sv6160_rebind_sdio_host() does so
from a STANDALONE work item, because device_release_driver() on the dw_mmc
platform device tears down the host, the card and this driver -- our
.remove() runs inside that call -- so the work cannot live in the softc it is
about to free.  It holds a reference on the platform device and on the module,
and is one-shot until a probe succeeds.

It escalates on REPEATED RUNTIME WEDGES, not on a single fault: three bus
recoveries inside 60 s (host_rebind, 0 disables) means restart_hw is being
asked to fix something it cannot, and each extra round trip is another ~11 s
of dead radio.  Three is safe to trigger on -- a recovery only fires on a
genuine -16/-110 fault, and a 10 h soak of 4.1 M descriptors produced zero --
against an ~8 s cure.  The bring-up retry path escalates too, once its four
fw_reboot attempts are spent.

VERIFIED on hardware, from a cleared dmesg so every count is provably new:

    hit 0: TimeoutError   escalations=0
    hit 1: TimeoutError   escalations=0
    hit 2: TimeoutError   escalations=1
    "3 bus recoveries in 60 s - restart_hw is not clearing it,
     re-creating the SDIO host"
    -> recovered UNATTENDED

and the mechanism separately: the netdev is renumbered (wlan15 -> wlan16, so
the card really is destroyed and re-enumerated), the bus re-inits from
400kHz, and the link is back with its IP in 8 s -- against the serial-console
rescue it needed before.

NOT hooked into probe, though that looks like the obvious place.  Once the bus
is hard-wedged our probe is never entered at all: sdio_bus_probe() calls
sdio_set_block_size() before drv->probe, that CMD52 fails -EBUSY, and the core
logs "probe failed -16" without ever calling us -- the failing reloads have no
probe entry line in dmesg.  A driver already rmmod'ed on a wedged bus is past
helping itself, and only a test harness reloads a wedged driver.  The comment
there says so, because the hook looks correct and will otherwise be re-added.

debugfs "recover" takes a level now: 1 (or empty) restarts the hw as before,
2 re-creates the host, so the deep path has a deliberate manual trigger.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 10:30:20 -04:00
Paul KilarandClaude Opus 5 d99b1e305b sv6160: restore the tx_batch ceiling; the retraction was a clamped-build error
714280f retracted the 9-frame ceiling on the grounds that it "did not
replicate": ~1173 transfers at tx_batch 10, 12 and 16 with zero stalls.  That
replication was invalid.  tx_batch is clamped by

    min3(mod_tx_batch, SV6160_TX_BATCH_MAX, SV6160_MAX_TX_CMDS)

and by then SV6160_TX_BATCH_MAX was back at 8, so the parameter accepted 16,
read back 16, and ran at 8.  Not one of those transfers ever left batch 8.
The tell was in debugfs all along: param=8 and param=16 both reported 7.0
frames/descriptor while param=2 reported 1.99.

Re-measured on a build where the cap genuinely lifts, six trials each:

    tx_batch= 8   0/6 stalled, 1.87 MB/s
    tx_batch= 9   0/6 stalled, 1.77 MB/s, fills to 7.9 frames/descriptor
    tx_batch=10   6/6 stalled
    tx_batch=12   6/6 stalled
    tx_batch=16   stalled, and wedged the bus hard enough that recovery failed

A sharp cliff between 9 and 10 -- 0/12 below it, 12/12 above -- so the
original reading was right and the "probability dial" idea is dead too.  The
one fair criticism in the retraction stands and is now answered: 10 and 12
had a single trial each before, and have six apiece now.

The far more valuable result is that tx_batch>9 is a RELIABLE REPRODUCER for
the link-death / SDIO wedge, which has otherwise arrived hours apart with no
warning and defeated a day of load-based hunting (batch size, write regime,
reload churn, concurrent TX+RX, suspend-while-unloaded: all eliminated, and
three of those eliminations were themselves run on the clamped build).  It
produces the exact signature -- tx_frames > tx_done_events with tx_resyncs
climbing -- and at 16 escalates to the full bus wedge: TX write -16, dwmmc
"Busy; trying anyway", mmc2 "Timeout sending command", every probe -16.

With a wedge available on demand, the escalation ladder could finally be
measured on a real one instead of an anecdote:

    ieee80211_restart_hw   untestable once probe fails (no debugfs); separately
                           observed NOT clearing a softer wedge, taking it from
                           4 to 8 resyncs and 6 to 13 lost descriptors
    module reload          FAILED -- probe still -16, no interface
    SDIO unbind/bind       CLEARED it -- probes, associates, 1.42 MB/s, 1:1

That is the shape of the fix: recovery must reach the SDIO host, not just the
802.11 stack.  sv6160_trigger_recovery already calls mmc_hw_reset -- dmesg
shows the bus renegotiating 400kHz->50MHz -- and it is NOT enough; only
tearing down and re-creating the dw_mmc host brought the card back.
tx_resync_giveup escalates to exactly the path that does not work, which
explains why it has never helped.

Default stays 8.  9 is worth ~3% (45 paired trials, 34/45 wins) but it is the
last working value and 10 fails 6/6 into a wedge needing an unbind/bind.

Comment only; binary unchanged (md5 7280ff0261eb).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-17 07:21:41 -04:00
Paul KilarandClaude Opus 5 714280f648 sv6160: retract the tx_batch ceiling; the stalls tracked the write regime
The previous commit claimed the firmware refuses num_frames_per_desc above 9,
on the strength of tx_batch=16 stalling TX 4 times out of 4 and 12 and 10
stalling on their first transfer.  That does not replicate.  Six transfers at
each of 8, 10, 12 and 16 stalled ZERO times, at 1.81-1.91 MB/s throughout.

The claim was under-powered where it mattered: 10 and 12 had exactly ONE
trial each, which is the single-trial A/B this driver is known to punish.
Only 16 had repeats, and those all fell inside one bad window.

What actually separates the two passes is the SDIO write regime, not the
batch size.  Every stall observed happened while throughput sat in the
degraded ~1.0 MB/s regime; every clean run, including all 24 trials of the
replication, has been in the healthy ~1.85 MB/s one.  debugfs tx_tokens
`body_avg_us` plus its byte count tells them apart at a glance: ~7-9 B/us
healthy, ~2 B/us degraded.

So batch size above 9 may be a probability dial on the link-death stall while
the chip is already degraded, and harmless while it is not.  That is a
statement about that open bug, not about a descriptor limit -- and it is a
lead worth having, because it is the first thing found that correlates with
a failure that otherwise arrives hours apart with no warning.

The two negative results from that work do hold and are kept: we are not
truncating the descriptor (it sums to exactly SV6160_TX_CMD_SIZE with 16
table slots, all transmitted), and it is not a global firmware frame pool
(descs_per_ac=1 + tx_batch=16 is 16 frames in flight, fewer than the 18 that
descs_per_ac=2 + tx_batch=9 runs happily on, and it stalled anyway).  The
8-vs-9 throughput figure also stands: it came from 45 paired trials with the
arms alternating every cycle, so both arms saw the same regime.

Default stays 8, for the same reason as before but on honest grounds: 9 is
the highest value never yet seen to stall, and +3% does not pay for spending
that margin while the stall itself is not understood.

Comment only; the binary is unchanged (md5 7280ff0261eb).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 12:30:04 -04:00
Paul KilarandClaude Opus 5 1a30deb20c sv6160: measure the TX batch ceiling; the firmware's nominal 16 is not usable
SV6160_TX_BATCH_MAX carried an open invitation to try the firmware's nominal
SV6160_MAX_TX_CMDS(16), on the strength of uplink scaling almost linearly from
tx_batch=1 to 8 with no sign of flattening.  Measured now, on hardware:

  tx_batch=16  stalls TX on the first transfer, 3 tries out of 3
  tx_batch=12  stalls on the first transfer
  tx_batch=10  stalls on the first transfer
  tx_batch=9   clean, and fills to 7.86 frames/descriptor
  tx_batch=8   clean, 9 transfers out of 9

Two explanations ruled out, so the ceiling is properly bounded.  It is not us
truncating the descriptor: the struct sums to exactly SV6160_TX_CMD_SIZE with
SV6160_MAX_TX_CMDS=16, so all 16 table slots really do go on the wire.  And it
is not a global firmware frame pool, which is what a ceiling at the odd value
of 9 first suggested: descs_per_ac=1 with tx_batch=16 puts only 16 frames in
flight -- FEWER than the 18 that descs_per_ac=2 with tx_batch=9 runs happily
on -- and it still stalls on the first transfer.  The limit is per-descriptor;
the firmware does not honour num_frames_per_desc above 9.

9 does work, and is worth about 3%: 45 paired trials alternating 8 and 9 every
cycle with NO reload between the arms -- so both arms see the same RF and the
same throughput regime, the trap that made earlier block-designed A/Bs on this
driver measure the regime instead of the variable -- gave median 1.873 ->
1.937 MB/s, 9 ahead in 34 of 45 pairs, zero stalls on either arm over 135 MB.

Left at 8 regardless.  9 is the LAST working value, 10 fails immediately, and
the failure is not graceful: the descriptors in flight are never completed,
and it once left the SDIO bus at -16 needing an unbind/bind of ff380000.mmc
over the serial console.  3% does not buy that loss of margin on a driver
whose throughput regime already swings 2x on its own.

Also retires the ambiguity the old note left: no reboot occurred in any of
these trials (uptime held throughout), so the historical reboot at 16 was the
separate sustained-uplink bug, exactly as that note suspected it might be.

Comment only -- the constant is unchanged, and the rebuilt module is
byte-identical (md5 7280ff0261eb) to the one this branch already ships.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 11:44:18 -04:00
Paul KilarandClaude Opus 5 8f53002d6f sv6160: drop cmd_rearm; a cancelled RX drain does not lose the wake
cmd_rearm guarded what its comment called a fatal race: __sv6160_rpu_write_cmd
cancels rx_work before writing so no CMD53 read collides with the write, and
for a merely-QUEUED work item that cancel throws the item away.  The comment
claimed this "kills the whole firmware->host pipe for good: no RX, no TX_DONE,
no command replies", and left the hand-back behind a default-off parameter so
it could be A/B'd.  It was never A/B'd.

The premise is wrong.  Dropping the work item does not drop the wake:

  - gpio_irq_pending is a LATCH.  The IRQ handlers set it; only a drain that
    runs to completion clears it (end of sv6160_rx_drain), and rx_drain
    returns early unless it is set.  A dropped work item leaves the wake
    standing for the next trigger to service.
  - The GPIO host-wake is LEVEL_HIGH + IRQF_ONESHOT with a NULL primary
    handler, and its thread calls sv6160_rx_drain INLINE rather than through
    this work item.  While the firmware still holds data the line stays
    asserted, so the kernel re-fires the thread on unmask.

So the wake is deferred, not lost, and no re-queue is needed.

Measurement agrees.  cmd_rx_cancelled was 0 over 2h18m of normal operation
(216k RX packets, ~178 control commands), and stayed 0 under deliberate
provocation: 30 scans during ~150 MB of RX load, ~9800 drains.  The window
between schedule_work and the worker starting is microseconds wide, and
drain_rx is true on three of the four call sites, so the guard does run --
cancel_work_sync simply never returns true.

(The comment is not stale inheritance from an older IRQ model: the threaded
ONESHOT rework 34fa536 is an ancestor of 672fdf5, which added cmd_rearm.)

Keeps the cancel_work_sync itself -- that is the load-bearing bus-collision
guard -- and keeps cmd_rx_cancelled as the tripwire for a window that has
never been observed to open.  Drops the dead rearm path and its counter.

Parameters 31 -> 30.  Verified on hardware: associated first try, scan
returns 12 BSSes, tx_frames == tx_done_events (446), tx_resyncs 0,
pio_body 0, cmd_rx_cancelled 0, zero oops/-110/desc_id lines.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 10:35:54 -04:00
Paul KilarandClaude Opus 5 f19fe8c4e9 sv6160: cull five settled module parameters and the last cull's debris
Each of these carried a question that is now answered, so the knob has no
remaining diagnostic value.  The knowledge moves to the use site, where a
reader would actually ask the question:

  rx_chain   its own premise is refuted.  Firmware RE suggested the chain
             walk stranded the 34 RX buffers; measurement says the chain is
             correct and much faster (4.7M chained drains over an 8h soak,
             no stranded buffers).  The real stall was the 4096-byte
             SV6160_MAX_RX_SIZE cap against the vendor's 33280.
  scan_mode  mode 0 is documented-obsolete: a bare CHANNEL does not re-tune
             the RF at runtime, so the sweep is deaf on every channel but
             the fresh-boot one.  It survives as the RPU_CMD_SCAN fallback.
  mcast      tested "the MCST_ADDR_CFG burst stalls TX".  It does not; the
             stall was our own premature descriptor retire.
  ba_tx      existed to tell "TX BA went operational" apart from "we
             programmed an RX BA session" while chasing the TID-0 TX stall.
             That investigation is closed.
  ps         measured and rejected: ~8 mA of ~365 mA system draw, and PS was
             slightly worse in both rounds.

Every removal is behaviour-preserving: at the shipped defaults each deleted
line was an unreachable branch.  The PS plumbing stays as scaffolding for a
real implementation but is now marked DORMANT, because without SUPPORTS_PS
mac80211 never sets IEEE80211_CONF_PS -- so debugfs ps_pm_frames is
structurally 0, and that zero means "PS is off", not "PS is on and not
stamping".

Also clears debris the 45->34 cull left behind:

  - Four comment blocks stranded at the top of the file with no code under
    them.  vendor_bringup, cmd_gate and fwpeek are re-homed to their real
    definitions; ba_rx's is moved down to its own (it sat ~175 lines away).
    The system_rev one described a parameter that cull REMOVED and told the
    reader to "pass system_rev=0" -- deleted, since the knowledge already
    lives in sv6160.h and at the RESET site.
  - That RESET site carried the same system_rev comment twice, stacked.
  - hw_scan's comment claimed channel-sweep was the DMA-safe path and
    "default sweep", contradicting the initialiser (1 = RPU_CMD_SCAN) and
    the hardware.  Believe the initialiser, as the last cull taught.
  - sv6160_trigger_recovery was non-static with no prototype (the only
    build warning); all six callers are in-file.

The two generated firmware variants are gitignored: both are reproducible
outputs of the tracked, self-verifying gen_fw_patch.py, and the shipped
ssv6160-fw.bin is byte-identical to ssv6160-fw.bin.orig.

Parameters 36 -> 31.  Verified on hardware: reload back on the same AP and
IP, scan returns 11 BSSes (the now-unconditional RPU_CMD_SCAN path), 4 IGMP
groups joined with 4 MCST commands, ampdu_action firing, TX 1.85 MB/s / RX
1.93 MB/s, tx_frames == tx_done_events (6075), tx_resyncs 0, pio_body 0,
zero oops/-110/desc_id lines.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 10:35:18 -04:00
Paul KilarandClaude Opus 5 f08db05b73 sv6160: log the CQM level actually crossed, and confirm the path works
The CQM path added in 3436f64 had never once fired in production.  Both roams on
the real walk test came from iwd's periodic scans, and no CQM event was raised
all afternoon, because iwd's default RoamThreshold is -70 and our trigger is
thold - hyst, i.e. -75, which that environment never reached.

It can be exercised without walking anywhere.  iwd's RoamThreshold IS the CQM
threshold the driver receives -- netdev.c feeds it to NL80211_ATTR_CQM_RSSI_THOLD
with the hysteresis hardcoded to 5 -- so setting it just above the current signal
makes the trigger fire immediately.  Bind-mounting an iwd main.conf with
RoamThreshold=-40 while sitting at -48 dBm produced, for the first time:

    CQM: threshold -40 dBm, hysteresis 5 dB
    CQM: RSSI -46 dBm below -40 dBm -> LOW
    hw_scan: 3 channels -> hw_scan: 11 channels
    authenticate with 66:22:32:98:fc:4a -> Associated

So the whole chain works: RX-frame RSSI -> our EWMA -> ieee80211_cqm_rssi_notify
-> iwd scans -> iwd re-associates.  It stayed on the same AP, which is correct;
that one really is the strongest here.

The one thing wrong was this log line.  It printed the bare threshold, so a LOW
at the -45 gate read as "RSSI -46 dBm below -40 dBm", which looks like an
off-by-something in the comparison rather than hysteresis doing its job.  Print
the level actually crossed and show the arithmetic.

No behaviour change; the iwd config was bind-mounted from /storage for the test
and unmounted afterwards, since /etc is read-only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 08:53:00 -04:00
Paul KilarandClaude Opus 5 2a15c8c360 sv6160: record why the TX queues are stopped all together, not per-AC
Stopping every access category because one of them ran out of descriptors looks
plainly wrong -- the descriptor pool is per-AC, sv6160_get_token() gates on
tx_outstanding_ac[queue], and a BE burst says nothing about VO or VI.  The cost
is real and was already measured: 731 whole-device stops in 2645 frames of bulk
uplink, essentially all caused by one AC.

So it was changed to ieee80211_stop_queue(hw, ac), built, and deployed.  It
kills the link within minutes.  Captured over the serial console at the moment
of death:

    tx_outstanding 0
    queue_len      0
    tx_qstop       843 (by ac: 0 843 0 0 0)

The driver completely idle, nothing queued, nothing in flight -- and BE still
stopped.  Every wake path in this driver runs out of TX_DONE processing, so once
the last completion has been consumed there is nothing left that would re-wake a
single queue, and it stays stopped for ever.  Stopping everything is precisely
what makes the existing wake-everything paths sufficient; the two are a pair.

Reverted, with the finding written next to the call so the next person does not
spend the same evening on it.  Doing this properly needs a per-AC wake driven by
something other than a completion that may never arrive -- a timer, or the
pull-model path where mac80211 keeps the frames and none of this applies.

No functional change: the diff is comment-only, and the tree is byte-identical
to bd50428 apart from dev_dbg line numbering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-16 07:43:00 -04:00
Paul KilarandClaude Opus 5 665cb7b111 sv6160: write down what the SDIO write excursions are not
The per-byte cost of a TX write swings 4-5x -- around 7-9 B/us for stretches,
then ~2 B/us for stretches -- with no change in bus settings.  Over 848
alternating cycles the median was 6.79 B/us with 36% of cycles in the slow
state.  It is the whole remaining gap between ~1.2 and ~1.9 MB/s of uplink, and
the gap to the vendor's 2.5.

No more of it is going to be found from the host, so record what has already
been excluded instead of leaving the next person to re-derive it.

Two things are known rather than suspected.  It is write-specific: RX is
unaffected in the very same cycle, 2.55 vs 2.60 MB/s, on the same bus,
controller and DMA engine -- and an SD write can be followed by the card holding
DAT0 busy while a read cannot, so the card is stretching its own ingestion.  And
it moves on a timescale of tens of minutes: hourly medians across one night ran
7.55, 1.87, 6.62, 8.60 B/us.

That second property is the methodological trap, and it cost three wrong
answers.  Any window shorter than the regime measures the regime, not the
variable.  A block-designed A/B said RX activity mattered enormously (0% vs 55%
excursions), a corrected one said the opposite (90% vs 13%), and a paired design
alternating every cycle showed the truth: 50% vs 50%, paired median exactly
0.00, TX-only higher in 11 of 22 pairs.  Anything tested here has to alternate
arms every cycle and run for hours.

Ruled out, each by measurement: AP and signal; SDIO bus config (identical ios);
SoC and GPU temperature; CPU governor (performance was worse); PIO versus DMA
(excursions survived tx_dma eliminating every PIO fallback); air contention (the
cleanest air of the week had the worst excursions, and retries and MCS do not
move through a transition); RX activity; write burst size (flat 6.6-8.2 B/us
across tx_batch 8, 4, 2, 1, so the stretch is per-transfer rather than
per-burst); and offered duty cycle -- 424 pairs with a 20 s idle before every
transfer, 36% versus 36% excursions, paired median 0.00, faster in 49%.

The duty-cycle null is worth keeping in mind, because it contradicts the
observation that started all this: leaving the link idle for ~3 minutes does
seem to restore the fast state, yet a controlled 20 s pause before every single
transfer does nothing measurable.  "Sustained load accumulates something in the
chip" does not survive a paired test.

What remains varies on a tens-of-minutes timescale and the host can neither
control nor observe it, and this firmware offers no visibility: get_survey
cannot report channel busy time, RPU_CMD_MIB_STATS answers with a firmware
error, and the TXRX count dump returns 92 zero bytes.  Treat it as a property of
the part unless someone gets firmware-side instrumentation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-15 21:21:33 -04:00
Paul KilarandClaude Opus 5 bd50428975 sv6160: the TX stall was mostly our own 1000 ms timeout
Two 10-hour runs, same build, same AP, same deliberately IDLE traffic -- the
condition this fault needs, one descriptor outstanding, which is why saturated
load never reproduced it:

  tx_stall_ms=1000   99 resyncs; 44 of 103 reclaimed descriptors (43%) were
                     completed by the firmware afterwards
  tx_stall_ms=3000    2 resyncs; tx_frames == tx_done_events (95920 == 95920)

Not one descriptor lost in ten hours.  A 50x reduction, and the two survivors
were false positives too: their completions arrived 2 ms and 4 ms after the
resync gave up, which the new tx_latecomp counter measures directly.

So the firmware does not lose descriptors.  It is occasionally slow -- a tail
reaching about 3 s where the normal worst case is tx_done_max_ms 257 ms -- and a
1000 ms window cut straight into that tail.  Each premature reclaim then handed
the id back to a firmware that still owned it, which rejected it as
"desc_id(1) reused" and caused a real stall, which tripped the next resync.  The
bug hunted since 2026-09-11 was largely manufactured by this timeout, with the
id reuse turning each instance into a burst.

Raise the default to 3000 ms.  The quarantine from 43d2f3f stays: it is what
makes a premature reclaim survivable at all, it still guards the genuinely slow
cases, and its early-release path is what proved these descriptors were merely
late rather than lost.

tx_latecomp records how long after the resync gave up a completion for a
reclaimed descriptor arrives.  It needs no extra state -- the quarantine
deadline is retire_time + hold-off, so the retire time is recoverable -- and it
turns "is the window long enough" into a measurement instead of a guess.

Cost of the longer window: a descriptor that really is dead now pins its AC for
3 s instead of 1 s.  That is the right trade against a measured zero losses in
ten hours, and the AC's other descriptor keeps working meanwhile, but it is the
thing to revisit if a genuinely lost descriptor ever turns up.

Smoke-tested on hardware at the new default: TX 1.74/1.90 MB/s, RX 2.73,
1746 frames and 1746 completions, no resyncs, no PIO fallbacks, no oops.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-15 07:37:42 -04:00
Paul KilarandClaude Opus 5 43d2f3f15a sv6160: stop reusing a descriptor id the firmware still owns
The TX stall was not one event, it was a loop, and we were driving it.

When completions stop, sv6160_tx_resync_fn() retires the outstanding
descriptors and frees their tokens.  sv6160_get_token() then hands the same id
straight back: for a given AC it tries queue + 0 first, so BE always gets id 1
again.  The firmware never completed that descriptor and still owns it, and it
says so plainly in an FW_ERROR:

    RPU: firmware error!  "[19308661 F] desc_id(1) reused"

then drops the new descriptor.  That one never completes either, so the next
resync fires, and reuses the id again.

The per-descriptor counters added in cde6a9d caught it overnight, and every
number fits the loop rather than a firmware that loses bursts of traffic:

  tx_resyncs 20, tx_resync_descs 20   -- exactly ONE descriptor per resync
  tx_lost_desc  1:19  3:1             -- 19 of 20 on id 1, NEVER on id 6
  tx_lost_ac    0 19 0 1 0            -- AC1
  20 resyncs inside 13 minutes, then nothing for hours

id 1 is not special to the firmware; it is simply the first id get_token
returns for AC1, hence always the one reused immediately after a resync.  And
one descriptor per resync means the pipe was nearly idle at the time -- this
fires on light traffic, which is why an idle night produced 20 of them while
3.5 hours of saturated load produced none.

So: quarantine an id that a stall resync reclaimed.  sv6160_tx_retire_all()
gains a `stalled` flag, because the two callers mean different things -- on the
stall path the firmware still owns the descriptors, while on a link flush it has
been told to disconnect and its table is about to be rebuilt, where quarantining
would only stop the next association from putting its auth frame on the air.
get_token() skips a held id, so the AC falls through to its other descriptor and
then the spares instead of hammering the one the firmware is rejecting.  A
completion arriving for a quarantined id releases it immediately: that is the
firmware telling us it is finished, which beats any timeout.

Verified on hardware that the mechanism engages: 4 quarantines set, 3
allocations deflected, and the loss histogram spreads to ids 6, 8 and 10 where
before it was 19-on-id-1-and-nothing-else.  Normal traffic is unaffected --
TX 0.93-0.98 MB/s, RX 2.62, no new resyncs, no oops.

What is NOT verified is that this prevents a real cascade, because the primary
stall still cannot be reproduced on demand.  tx_stall_ms=1 forces resyncs but
not the fault: it retires descriptors the firmware completes normally a few ms
later, and produces no desc_id-reused errors at all.  The next natural stall
will show whether the loop is broken; tx_quarantine_ms=0 restores the old
behaviour for comparison.  This addresses the cascade -- 19 of last night's 20
events -- not whatever causes the first stall, which remains open.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-14 09:32:20 -04:00
Paul KilarandClaude Opus 5 cde6a9de8d sv6160: record which descriptors the TX stall loses, and retire the 55% figure
The TX stall has been described since 2026-09-11 as hitting "~55% of
associations, a few seconds into data traffic".  That is no longer true of this
driver, and leaving the number in the notes sends the next person hunting a bug
with the wrong shape.

Measured on the current build:

  - 12 forced re-associations, each followed immediately by a 6 MB transfer --
    precisely the scenario the 55% figure describes -- produced ZERO resyncs.
    Expected six or seven.
  - 3.5 hours of continuous TX+RX on one association: 1,171 cycles, ~14.7 GB,
    1,266,409 completions, ZERO resyncs.
  - The 8-hour soak the day before saw 5 stalls, i.e. ~0.6/hour, and they were
    BURSTY: three inside 27 minutes with 1h46m clean before and 2h55m after.

So it is rare and clustered, not a per-association coin flip.  Several fixes
since that figure was taken plausibly account for it (the RX aggregate cap, the
TX double-free, and the PIO->DMA change all touched this path).

What is still true, and is the useful part: when a resync does take a descriptor
back, NO completion ever arrives for it -- tx_late 0 and tx_skip_noskb 0 across
every run.  The firmware really does drop it.  And the stall window has a wide
margin: 1,266,409 completions with tx_done_max_ms of 170 against a 1000 ms
timeout, so the resync is not firing on merely-slow completions.  (Note the
signal there is tx_skip_noskb, not tx_late: the skip check runs first and goes to
out, so a late completion for a retired descriptor can never reach the tx_late
branch.)

Add the instrumentation the next stall needs, since they are hours apart and
there is no second chance:

  tx_lost_desc  per-descriptor-id count of what the resync took back
  tx_lost_ac    the same per access category
  oldest lost   how long the worst one had been outstanding

That answers the obvious questions directly -- always the same id? always one
AC? -- which is otherwise unanswerable from "resynchronised N descriptor(s)".

Also relax sv6160_fw_show_txrx_count() to decode a short reply.  This firmware
answers FW_PRIV_DUMP_TXRX_COUNT_INFO with 92 bytes where the vendor header
describes 228, so the old length check threw the whole thing away.  Worth noting
the older warning that this dump "wedges the bus" is stale -- it does not, and
almost certainly never did after the RX aggregate cap was fixed.  It is useless
for a different reason: all 92 bytes read ZERO after thousands of descriptors.
cmd_tx_send vs event_tx_done_recv would have been exactly the measurement this
bug wants, and this firmware does not keep it, just as RPU_CMD_MIB_STATS answers
with an FW_ERROR and fw_log comes back empty.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-14 03:07:18 -04:00
Paul KilarandClaude Opus 5 24e6aa5a74 sv6160: let mac80211 re-add the same vif, so wedge recovery keeps the link
Every SDIO-wedge recovery lost the connection, and the reason was one word in
.add_interface:

	if (sc->vif)
		return -EBUSY;

ieee80211_restart_hw() does NOT call .remove_interface.  ieee80211_reconfig()
calls .stop, then .start, then .add_interface on the interfaces it already has
-- the same ieee80211_vif object.  sc->vif was therefore still set, we returned
-EBUSY, and reconfig WARNed at net/mac80211/util.c:1870 (the drv_add_interface()
call), rolled the whole reconfig back and left the interface down.

The bitter part is that the hardware recovery underneath had already SUCCEEDED
every time: firmware re-uploaded, LMAC reset, "bring-up complete", "mac80211
started, RPU ready" -- and then the link died anyway and needed a module reload
over the serial console to come back.  An 8-hour soak hit this 5 times.

Only a genuinely different vif is a conflict.  Re-adding the same one is safe
and is exactly what reconfig needs: this is a single-VIF driver (vif_index is
always 0), .stop has already cleared operating/assoc, and the firmware has just
been reset and re-uploaded, so the VIF_CTRL that follows is the reprogramming
the fresh firmware is waiting for.

Also add a write-only debugfs "recover" file that fires the recovery path on
demand.  That path had no way to be tested deliberately -- it ran only when the
bus actually wedged, 5 times in 8 hours at unpredictable moments -- which is
precisely how a -EBUSY that broke every recovery survived this long.  Recovering
from a wedge is a correctness path and needs to be exercisable.

Verified with it: 4 forced restarts, 4 seamless recoveries, link back in ~5s
each time on the same BSS with the IP kept, throughput 1.48-1.69 MB/s after
versus 1.62 before, and zero new ieee80211_reconfig WARNINGs (the only two in
the ring buffer are from before this change).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-13 22:26:34 -04:00
Paul KilarandClaude Opus 5 512cf352e4 sv6160: implement get_survey, and record why it cannot report busy time
`iw survey dump` returned nothing at all because .get_survey was never wired
up.  Add it: one entry for the operating channel, marked in-use.  Verified on
hardware -- "frequency: 2412 MHz [in use]" where there was previously no output.

What it deliberately does NOT report is the thing survey is usually reached for,
channel utilisation, because this part cannot measure it.  The firmware's entire
statistics interface is RPU_CMD_MIB_STATS(27) -> RPU_EVENT_MAC_STATS(21), a flat
block of MAC and baseband event COUNTS: no busy time, no CCA counter, no noise
figure anywhere.  Even the vendor's "phy_stats" file is just csync/fsync/acdrop
and the CRC counts printed out of that same block.  Nothing there supports
SURVEY_INFO_TIME, SURVEY_INFO_TIME_BUSY or SURVEY_INFO_NOISE_DBM, and deriving
them from frame counts would put a number in front of userspace that looks like
a measurement and is not one, so `filled` carries only SURVEY_INFO_IN_USE.

MIB_STATS itself was implemented on the way here -- command, event, struct,
softc storage and a debugfs file exposing edca_win% (EDCA arbitrations won over
started, a medium-contention proxy) and tx_underrun_cnt (the MAC running dry
because the host did not feed it fast enough over SDIO).  Those were exactly the
counters wanted for the two uplink throughput regimes.  It is all removed again,
because the firmware cannot deliver the event: six commands produced zero
replies and an RPU_EVENT_FW_ERROR reading

    [27962 F] event length(184) overflow

The firmware builds its own 184-byte stats event and then overflows its own
event buffer.  (184-28 = 156 = 39 words, so its struct is also shorter than the
50 words the vendor header describes -- this firmware's MIB path looks
vestigial.)  The two ids are kept named in the enums with that finding attached,
so the next person reads it instead of re-deriving it; sending the command has
no effect except one firmware error per attempt.

One implementation note worth keeping, since it cost a hang: the first version
of the debugfs file sent the command from the read and waited on a completion.
That blocks uninterruptibly whenever the bus is unhealthy -- a `cat` wedged on a
stalled association, surviving `timeout 5` -- which is precisely when a
diagnostic needs to answer.  Any future firmware-query file here must kick the
request from a work item and return the previous sample.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-13 13:57:58 -04:00
Paul KilarandClaude Opus 5 c7564daee8 sv6160: every TX body was going out by PIO, not DMA
dw_mci_pre_dma_transfer() will not DMA a transfer unless every scatterlist
entry has a 4-byte-aligned offset AND length, and silently falls back to PIO
otherwise:

	if (sg->offset & 3 || sg->length & 3)
		return -EINVAL;

The SDIO core builds that scatterlist straight off the pointer we hand it
(mmc_io_rw_extended -> sg_init_one -> offset_in_page(buf)), so the alignment of
skb->data decides it.  A mac80211 TX skb can never satisfy the test: the 14-byte
ethernet header is replaced by a 26-byte QoS 802.11 header plus 8 bytes of
LLC/SNAP, which leaves skb->data at 2 mod 4.  Length was never the problem --
sv6160_tx_xfer_len() already rounds to 4.

New pio_desc/pio_body counters measure it rather than argue about it, and the
answer is total: pio_body == tx_done_entries on every run (4616/4616,
8998/8998, 13381/13381), while pio_desc stays 0 because the descriptor is
kmalloc'd and therefore always aligned.  100% of frame bodies, every run, since
the driver was written.

Fix by bouncing the body through the spare half of tx_buf, which is already
allocated (SV6160_TX_CMD_SIZE + SV6160_TX_CMD_BUF) and otherwise unused, at
ALIGN(SV6160_TX_CMD_SIZE, 4) so it is 4-aligned.  Same bytes, same length -- only
the source address changes, so the chip cannot tell, which matters on a part
this sensitive to CMD53 framing.  Pad bytes are zeroed instead of read from past
the frame.  Costs one ~1.5 KB memcpy against a write that takes hundreds of us.
Frames too big for the scratch area fall back to writing from the skb.

Measured interleaved WITHIN ONE association, because a module reload changes
both the AP (three same-SSID APs are in range and NM re-picks each time) and the
throughput regime below, which makes any A/B across a reload meaningless:

  degraded regime   tx_dma=0  0.66 / 0.64 / 0.66   tx_dma=1  1.04 / 1.02 / 1.03
  healthy regime    tx_dma=0  1.89 / 1.75 / 1.49   tx_dma=1  1.79 / 1.84 / 1.84

+58% where it is degraded, neutral where it is not, so it defaults on.  PIO only
bites while the chip is stretching the data phase: a stretched PIO transfer holds
the CPU babysitting the FIFO for its whole duration, DMA does not.

Two things this disproves, both recorded in comments until now:

- "a CMD53 costs ~500 us almost regardless of length".  Sweeping frame size
  within one association: 326-byte bodies 318 us, 1530-byte bodies 1592 us.  A
  straight line, 1.06 us/byte, intercept about -26 us.  There is no measurable
  fixed per-command cost, so saving commands is not a lever.  What the cost
  tracks is how busy the chip is: the same 581-byte descriptor takes 211 us at
  150 frames/s and 704 us at full blast, and at a matched 0.40 MB/s it takes
  317 us at 278 frames/s versus 670 us at 1092 frames/s.

- "DMA is not the issue, the CPU is asleep waiting on the card", inferred from
  sys+irq rising only ~18% of one core while the write path was 93% busy.  That
  is equally consistent with PIO at 1 MB/s, which is what it actually was.  Do
  not infer the DMA path from CPU load; count it.

Still open and NOT explained by any of this: the uplink runs in two regimes
about 3x apart (~1.9 MB/s vs ~0.65 MB/s) that it steps between mid-run, with
identical bus settings, AP, signal and temperature, and with PIO at 100% in
both.  Fourteen back-to-back 6 MB transfers on one association: twelve at
1.66-1.99, then 0.64 from the thirteenth on, body write time stepping 1.06s ->
6.56s for the same ~4400 frames.  It is load-triggered and recovers on idle
(~3 min restored 1.94 MB/s with no reset).  The air is not it -- retries stay at
0.13-0.16/frame, MCS 6-7, TX_DONE latency ~9 ms on both sides of the step.  Note
this means the throughput figure on record for this driver was the degraded one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-13 13:29:38 -04:00
Paul KilarandClaude Opus 5 d0dd816e1e sv6160: stop hex-dumping every RX aggregate at info level
RPU_EVENT_RX_SERIAS logged a dev_info line plus a 64-byte print_hex_dump for
every aggregate larger than a bare header, with no flag guarding it -- leftover
bring-up instrumentation that shipped enabled.  It is on the RX hot path: a
single 6 MB downlink drives ~1500 of these events, so it is thousands of printk
lines per transfer, enough to perturb the throughput measurements it sits in
the middle of, quite apart from what it does to the log.

Put it behind wt_trace, where the rest of the wire tracing already lives (the
neighbouring RXDATA dump in sv6160_rpu_rx_frame was already gated that way), and
drop the "RX_SERIAS as single frame" line to dev_dbg.  No behaviour change with
wt_trace set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-13 13:29:00 -04:00
Paul KilarandClaude Opus 5 312cdde09b sv6160: stop double-freeing TX skbs when the stall resync races the worker
This is the "link death" that has been chased for weeks: the link stays
associated, keeps its IP, and never carries another packet. It is a kernel
oops in our own TX worker, and the box does not reboot only because
panic_on_oops is 0 -- the worker thread dies and nothing transmits again.

Caught on the serial console:

  sv6160: sdio_write_tx(desc=581 body=122) failed: -110
  sv6160: TX write failed: -110
  Unable to handle kernel paging request at virtual address 000010000000032a
  pc : kfree_skb_list_reason   lr : ieee80211_report_used_skb [mac80211]
  Call trace:
    kfree_skb_list_reason -> ieee80211_report_used_skb
    -> ieee80211_free_txskb -> sv6160_tx_worker [sv6160]
  Workqueue: events sv6160_tx_worker

The worker publishes tx_pending[slot] BEFORE issuing the SDIO write, and that
is deliberate -- frame 0 is the ownership token, so a completion can never see
a half-built descriptor.  The cost is that sv6160_tx_retire_all() can claim the
descriptor while the write is still in flight and hand every frame in the batch
to mac80211, which frees them.  When the write then fails, the worker's error
path calls ieee80211_free_txskb() on those same skbs.  Second free, garbage
pointer, oops.

Two paths were not following the ownership protocol that TX_DONE already used.
Make it symmetric: whoever wins the cmpxchg on frame 0 owns the batch, the
skbs AND the token.

  - sv6160_tx_retire_all() freed the token unconditionally, even when it had
    lost the cmpxchg.  That handed the id back while a TX_DONE which had just
    won it was still copying tx_batch[id][] out, and free_token schedules
    tx_work, which can take the same id and overwrite those entries underneath
    it.  It now frees only inside the win branch.
  - The TX-write-failure path now claims frame 0 with the same cmpxchg before
    touching the batch, the skbs or the token.  If it lost, the frames are
    already reported and the token is already back.

Reproducing this on demand is the part that was missing.  tx_stall_ms is the
resync interval, so setting it to 1 makes retire_all run continuously instead
of once a second, and the race becomes near-certain under load:

  unfixed   the ssh that merely set tx_stall_ms=1 never returned; oops within
            seconds, TX worker dead, SDIO bus left at -16
  fixed     that same write returns normally, six load iterations run, and
            dmesg reports zero oopses -- the identical
            "TX write failed: -110" path now executes cleanly

Normal operation is unaffected: fresh load reports 34 parameters, connect at
0% loss, scan-while-associated returns 12 BSS with the link intact, counters
stay 1:1 (tx_frames == tx_done_events) with tx_resyncs 0 and token_bmp 0x000,
and an independent 20-ping check runs 20/20 at 5.4 ms average.

Worth recording for whoever reads the overnight campaign log: an 8.1 hour /
2500 cycle / ~30 GB soak the night before never triggered this at all, because
it never took a single resync.  The resync path is the precondition, not the
traffic.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JSNniou44nN9EFGqTmZ6my
2026-09-13 11:30:15 -04:00
Paul KilarandClaude Opus 5 f4e64e1038 sv6160: count TX retries, and record what the uplink is actually limited by
Adds a per-frame TX retry histogram and a failed-frame count from TX_DONE,
because the first question about slow uplink is always "is it airtime?" and
until now there was no way to answer it.

The answer is no.  Over a 6 MB uplink run: tx_retry_avg 0.25 retries per
frame, 4009 of 4546 frames succeeding first try, 6 failed, and use_mcs
overwhelmingly 7.  Frames are going out at the top HT20 rate and almost never
being retransmitted, so the air is not where the time goes.

Where it does go, measured per run rather than from the lifetime averages in
debugfs (avg*n recovers the sums, so differencing gives just that run):

  app 0.58-0.66 MB/s, ~900 descriptors per 6.29 MB, 4.8-5.0 frames and
  ~7400 body bytes per descriptor, body write ~6600 us per descriptor
  => SDIO write 1.12-1.16 MB/s, four runs, no resyncs

That is ~4.9 CMD53s of ~1510 bytes each at ~1347 us apiece, where 1510 bytes
at 50 MHz x 4-bit is about 24 us of bus time -- so 98% of it is not data
transfer.  The bus is confirmed 50 MHz, 4-bit, SD high-speed.  Descriptors are
well filled and there are no stalls during these runs, so neither batching nor
the TX-stall recovery explains it.

One clue for whoever picks this up: the same 581-byte descriptor write takes
about 210 us when the link is idle and about 693 us under load, so the write
slows down with offered load rather than being a fixed host-side cost.

Also records the batch-size scaling, measured over two interleaved rounds,
since it contradicts the older note that batching had saturated:

  tx_batch=1  0.42 / 0.39 MB/s      tx_batch=4  1.07 / 1.08 MB/s
  tx_batch=2  0.66 / 0.69 MB/s      tx_batch=8  1.37 / 1.50 MB/s

Those runs were taken back-to-back under an already-deep queue; a fresh load
settles at 0.60-0.66 MB/s at tx_batch=8, so treat the absolute numbers as
conditional and the shape as the finding.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 22:05:07 -04:00
Paul KilarandClaude Opus 5 7164196419 sv6160: retire connect_fix and disc_skip, and what they kept alive
The last two bisection knobs, held back from the previous cull only because
between them they gated twelve call sites.  Both defaulted to 0, so every line
below was already dead.

connect_fix was six experimental connect-time RX-arm workarounds, and its own
comment records the verdict: "None of these achieve association on their own."
Its bits were actively dangerous to reach -- the parameter description warns
that bit2 "REBOOTS THE BOARD, do not use" -- and bit0, the scan-hold, would
silently break roaming today by no-op'ing every scan while operating, which is
exactly the path that now has to work.

Removing it orphaned a whole mechanism: rx_keepalive was only ever scheduled
from connect_fix-gated sites, so the work item, its handler and its four
cancel sites are gone too, along with the scan_noop flag whose only writer was
the scan-hold path.

disc_skip bisected the post-disconnect wedge.  Every one of its bits is
recorded refuted in the code -- multicast teardown, BlockAck teardown, the
SETKEY DEL and the disconnect-time CMD_CHANNEL -- and the real cause was found
and fixed elsewhere (the stale-RECV_LEN guard, removed in the previous
commit).  Its was_connected field existed only to scope one of those bits.

34 parameters left, from 45 at the start of the cull.

Verified on hardware, not merely rebuilt: 34 parameters reported by the loaded
module, connect 0% loss, scan-while-associated 12 BSS with the link intact --
the check that matters most here, since the scan-hold path is gone -- a 60 s /
600 ping soak at 0% loss, reconnect at 0% loss, and counters token_bmp 0x000,
tx_frames 959 == tx_done_events 959, tx_resyncs 0, oversize 0, rx_nomem 0.  No
new dmesg errors; the ones present are from earlier in the same boot.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 21:31:38 -04:00
Paul KilarandClaude Opus 5 b385ab29c8 sv6160: release both IRQs when probe fails
A probe that got as far as registering interrupts and then failed returned
without tearing either of them down, which is both a leak and a hazard.

The in-band SDIO IRQ is not devm-managed, so it stayed claimed for good: the
next load reported "sdio_claim_irq failed: -16" and silently continued on
GPIO-only.  Observed exactly that after a probe failed on a missing firmware
file -- the retry 100 s later could not claim the interrupt it had itself left
behind.

The GPIO IRQ is worse in principle.  It is devm-managed, so it is released
when the device unbinds -- but that happens only after probe returns, while
ieee80211_free_hw() frees sc inside probe, and sc is the handler's dev_id.  A
host-wake arriving in that window would run the threaded handler against freed
memory.

Tear both down before ieee80211_free_hw(), mirroring sv6160_remove(), and drop
the wake enable with them.  sdio_release_irq() is safe even when the claim
failed: it no-ops on the handler and just clears the CCCR enable bit.

Verified by reproducing it in one boot -- remove the firmware file so probe
fails, restore it, load again.  The failing probe registers the in-band IRQ at
t=549 and fails with -2; the retry at t=555 logs "SDIO in-band IRQ registered"
instead of the -16 it used to, and the link comes up normally afterwards
(token_bmp 0x000, tx_frames 208 == tx_done_events 208, tx_resyncs 0).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 21:22:09 -04:00
Paul KilarandClaude Opus 5 7a92f60e4a sv6160: retire nine settled module parameters
45 knobs is more than anyone can hold in their head, and most of these were
bring-up scaffolding from when the driver could not associate.  Each one below
is retired because the code already records its answer; the answer itself is
kept as a comment at the code it explains, so nothing is forgotten -- only the
knob goes.

  mac_program   dead.  Declared and registered, never read anywhere; the
                eFuse-programming feature it advertises does not exist.
  int_gen       only one viable value.  0 was measured as "scan finds 0 APs,
                RX dead", so the writes are unconditional now.
  rf_keep       REFUTED on hardware and "measured to make no difference":
                writing the RF-enable register on the VENDOR while its RX
                counter was provably frozen moved that counter not at all over
                ten seconds.  Its only caller gone, sv6160_rpu_rf_set() goes
                too; the firmware-path notes stay as documentation.
  tx_pad_blk    REFUTED: setting it "kills the link instantly", the transfer
                stops dead and the wiphy disappears.
  notify_gate   MEASURED: gating the doorbell on a finished chain breaks TX
                (A/B, gated ping 0/4 vs ungated 4/4).  The condition collapses
                to `if (acked)`.
  system_rev    the vendor's hardcoded 0x494D47 is settled; it becomes
                SV6160_VENDOR_SYSTEM_REV.
  stale_guard   this WAS the reconnect bug.  Both clauses removed, and the
                site now says why there must never be a guard there: the
                firmware's delivery doorbell is one-shot, so a single skipped
                wake kills the FW->host pipe for good.
  txq_init      tested and negative ("does NOT fix the connected-mode-RX
                blocker"), and superseded by vendor_bringup.
  bringup_chan  enabling it latches channel_active, which turns the real
                connect-time CHANNEL into a no-op and leaves TX unarmed.

Worth noting one thing this turned up: int_gen's use site carried the comment
"Gated OFF by default to match the vendor" while the declaration read `= 1`.
It was written when the default was 0 and never updated after 0 was measured
to kill RX -- a comment that would have actively misled the next reader.

Every one of these defaulted to off or inert, so the deleted code provably
never executed and no behaviour should change.  Verified on hardware rather
than argued: fresh load reports 36 parameters, connect 0% loss, a
scan-while-associated returns 12 BSS with the link intact, a 60 s / 600 ping
soak is 0% loss, reconnect works at 0% loss, and the counters come back
token_bmp 0x000, tx_frames 1039 == tx_done_events 1039, tx_resyncs 0,
oversize 0, rx_nomem 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 21:19:42 -04:00
Paul KilarandClaude Opus 5 efa0b441cb sv6160: explain the post-suspend -110 instead of leaving a bare errno
Suspending with no driver bound to this SDIO function leaves the chip
unreachable, and the only symptom is `probe with driver sv6160 failed with
error -110` on every subsequent load.  That cost an afternoon to pin down, so
say what it means where it happens.

Isolated on hardware.  Across a real deep suspend (RTC alarm + `echo mem >
/sys/power/state`):

  driver loaded + associated   same BSS, same IP, 0% loss, 494/494 completions,
                               tx_resyncs 0, token_bmp 0x000
  driver loaded + rfkilled     resumes, reconnects, 0% loss
  driver UNLOADED              -110 on every later probe, permanently

rfkill was a red herring -- the middle case proves it is harmless.  The
variable is whether a driver is bound.  With none, nothing requests
MMC_PM_KEEP_POWER and on resume the wifi mmc host is never re-initialised at
all: the log carries bus-speed and phase-tuning lines for the storage host and
nothing for this one.  That is also why the mmc_hw_reset() already in probe
returns success and changes nothing -- the problem is the host, not the card --
and why rmmod/insmod cannot clear it.  Recovery is a controller power cycle:

  echo ff380000.mmc > /sys/bus/platform/drivers/dwmmc_rockchip/unbind
  echo ff380000.mmc > /sys/bus/platform/drivers/dwmmc_rockchip/bind

(ff380000.mmc is the wifi host; ff370000.mmc carries /storage, do not touch it.)

No automatic recovery is attempted here.  mmc_hw_reset() re-enumerates the
card and would re-enter probe, and the exposure is small: the driver normally
stays loaded, and ROCKNIX's idle "suspend" is rocknix-fake-suspend, which only
freezes processes and never writes /sys/power/state -- which is why the PM
callbacks in this file had never executed once before today.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 20:52:44 -04:00
Paul KilarandClaude Opus 5 b091a1d848 sv6160: measure power save, default it off, drop the inert idle timer
Power save on this chip cannot work the way the vendor does it, and measuring
it shows there is almost nothing to win anyway.

Measured on battery -- the only way, since on AC the fuel gauge sits pinned at
a ~7.7 mA trickle and does not move under load -- with screen brightness
pinned and two alternating rounds, median of 8 samples per arm:

  driver unloaded            360.9 / 360.5 mA
  associated idle, PS off    368.6 / 369.5 mA
  associated idle, PS on     375.3 / 372.4 mA

The entire wifi idle budget this driver controls is ~8 mA out of ~365 mA of
system draw, 2.3%, with the screen and SoC dominating; even flawless power
save would buy about 2% of battery life. Enabling PS made it worse in both
rounds (+6.7 and +2.9 mA) -- near the noise floor in magnitude, but consistent
in direction, and the mechanism is not mysterious: PS achieves nothing here
while mac80211's dynamic PS churns through a doze/awake transition every
~130 ms (310 of them in two minutes), each one a hw_config call plus timers.

Why it achieves nothing. There is no firmware sleep command: the vendor's
rpu_prog_ps_state() (rk915 src/rpu_if.c:1699) is a bare `return 0;` and its
whole session SDIO trace contains no RPU_CMD_PS. Its entire implementation is
ieee80211_hw_set(SUPPORTS_PS) (umac_if.c:1419) plus ORing IEEE80211_FCTL_PM
into outgoing data and bufferable management frames (umac_if.c:553). That PM
bit is inert under mac80211's dynamic PS, which clears IEEE80211_CONF_PS
before every transmit -- so by the time a frame reaches the TX path we are
always awake again. Measured: ps_pm_frames == 0 across 310 transitions.
Nothing ever tells the AP to buffer, and nothing sleeps. The PM=1 nullfunc
that would tell the AP is only sent under IEEE80211_HW_PS_NULLFUNC_STACK
(mac80211 mlme.c:3472), which neither driver sets.

So the plumbing is kept, vendor-shaped and correct, but behind a `ps`
parameter that defaults OFF. It stays because it is the precondition for any
real implementation -- one that sleeps the chip itself via NOTIFY_SLEEP /
FW_STATE_M0_SLEEP, as the suspend path already does. Against an 8 mA ceiling,
and at a transition every ~130 ms over SDIO, that is unlikely to be worth it.

Note that advertising the capability is not free: CONFIG_CFG80211_DEFAULT_PS=y
on this kernel, so IEEE80211_HW_SUPPORTS_PS alone flips power save on by
default (`iw dev X get power_save` goes from off to on).

Setting the PM bit where this does, after mac80211 has encrypted, is legal:
CCMP masks the Power Management bit out of the AAD (802.11-2016 12.5.3.3.3),
which is also why the vendor can set it at the same point.

Net effect is a deletion. Removed a driver-local 5-second idle_work timer,
ps_enabled, and sv6160_rpu_ps_config() -- the latter a documented no-op, so
the timer woke the CPU every 5 s to call a function that did nothing. The
doze/awake transition log is dev_dbg rather than dev_info for the same reason
the timer had to go: at ~130 ms intervals it floods the kernel log.

Verified on hardware after the change: ps parameter off, power_save off,
ps_transitions 0, link healthy at 25/25 pings and 0% loss.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 20:33:40 -04:00
Paul KilarandClaude Opus 5 3436f64c60 sv6160: generate CQM events ourselves so roaming can trigger
Autonomous roaming could never fire. The firmware stops delivering beacons
the moment it enters its connected-STA regime -- measured: the last
"RXCH: BCN" arrives during the pre-association scan and not one after it, and
"iw station dump" reports "beacon rx: 0" / "beacon signal avg: 0 dBm". Since
mac80211's software CQM is driven purely by beacons of the associated AP
(ieee80211_handle_beacon_sig), count_beacon_signal stayed 0 and no RSSI
threshold event was ever raised.

We then made it worse. mac80211 only refuses a CQM request when
IEEE80211_VIF_BEACON_FILTER is set without SUPPORTS_CQM_RSSI, and we declared
neither -- we set only IEEE80211_HW_CONNECTION_MONITOR. So mac80211 accepted
the request and then had no way to service it, and the supplicant waited
forever for an event that could not come. Measured with iwd: 0 autonomous
roams in 135 s with RoamThreshold=-35 against a -47 dBm link, with no
"CMD_SET_CQM not supported, falling back to polling" in its log. The vendor
rk915 avoids this by declaring BEACON_FILTER, so mac80211 returns -EOPNOTSUPP
and the supplicant polls RSSI instead.

Declare the beacon filtering honestly and do CQM in the driver, off the RSSI
of frames actually received from the AP (that path already works -- the same
value backs "signal avg" in the station dump). New cqm module parameter:

  0 = legacy: declare nothing. Kept only as an A/B control; autonomous
      roaming cannot work in this mode.
  1 = declare BEACON_FILTER only, so mac80211 returns -EOPNOTSUPP and the
      supplicant falls back to polling, like the vendor driver.
  2 = declare BEACON_FILTER | SUPPORTS_CQM_RSSI, take the threshold from
      BSS_CHANGED_CQM, and raise the events with ieee80211_cqm_rssi_notify()
      (default).

The threshold is also picked up from bss_conf at BSS_CHANGED_ASSOC, because
mac80211 only emits BSS_CHANGED_CQM while already associated and would
otherwise drop a threshold configured during the connect. The BSSID is
snapshotted rather than read back through sc->vif, since the RX path must
never dereference a VIF that may be tearing down.

Verified on hardware. The chain that was previously dead now runs end to end:

  sv6160: CQM: threshold -35 dBm, hysteresis 5 dB
  sv6160: CQM: RSSI -41 dBm below -35 dBm -> LOW
  iwd: station_roam_trigger_cb() -> station_roam_scan()
  iwd: StationDebug.Event(roam-scan-triggered)
  iwd: station_roam_timeout_rearm() Arming new roam timer for 5 seconds

Before the fix iwd's log stopped at the early neighbour report. Under stock
config it arms at iwd's real default: "CQM: threshold -70 dBm" then
"CQM: RSSI -41 dBm above -70 dBm -> HIGH".

Roam execution itself was already sound and is unchanged: 6/6 forced roams
via iwd's StationDebug.Roam, every one cross-channel (2437 -> 2412 -> 2462),
630-660 ms each, IP retained, tx_frames == tx_done_events, tx_resyncs 0,
token_bmp 0x000. Scanning while associated is likewise clean: 10/10 real
off-channel sweeps at 0% loss, and 120 s of roam-scanning every 5 s left
3109/3109 completions, 0 resyncs, oversize 0, rx_nomem 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 20:00:25 -04:00
Paul KilarandClaude Opus 5 af16910899 sv6160: implement the pull-model TX path - and measure that it is slower
Converting to mac80211's pull model was meant to unblock A-MSDU: the push shim
ieee80211_handle_wake_tx_queue() empties the txq on every wake, and
ieee80211_amsdu_aggregate() can only append to a frame already sitting in the fq
flow, so nothing ever aggregates.  txq=1 installs our own .wake_tx_queue and a
refill that pulls with ieee80211_tx_dequeue() only when a descriptor is free, so
frames can back up in mac80211 under load.

Two things it genuinely fixes, both counter-measured rather than inferred:

  tx_qstop    731 in 2645 frames  ->  0
  tx_avg_us   6374                ->  871   (desc_avg_us 557 -> 165)

A pull-model driver stops pulling instead of calling ieee80211_stop_queues(),
so one AC running out of descriptors no longer stops every other AC.  And the
SDIO write path gets much cheaper because far less is pushed at once.

But it does NOT pay off, and the honest measurement says so.  txq is runtime
writable and .wake_tx_queue re-reads it, so the two paths can be alternated
back-to-back on one link -- which matters, because this RF environment moved
4x within an afternoon and single samples are worthless here.  Eight
alternating rounds, 2 MB each:

  txq=0   605 594 617 597 598 557 606 627 kB/s   (median ~600)
  txq=1   420 434 422 438 408 411 441 421 kB/s   (median ~422)

The pull path is ~30% slower, 8 times out of 8.  The cause is visible in the
counters: pulling one frame per free descriptor leaves ~1.3 frames per
descriptor against ~5.6 under push, so the 2-descriptors-per-AC pipeline at
~5 ms per completion becomes the limit.  Staging more per descriptor to restore
batching makes it worse again, because this chip flow-controls on how much is
pushed at once:

  2009 bytes/descriptor -> 277 us write, 4 ms complete, 757-809 kB/s
  7433 bytes/descriptor -> 6233 us write, 13 ms complete, 609-636 kB/s

i.e. 7.25 MB/s per byte in small pieces against 1.19 MB/s in large ones.  Little
and often beats bulk on this hardware, but not by enough to beat push.

A-MSDU still never engages either way -- tx_max_frame stays 1542 in both modes.
Pulling only when a descriptor is free is still prompt enough that mac80211's
flow queue stays empty.  Making it aggregate would mean deliberately holding
frames back to build a backlog, i.e. trading latency for throughput, which is a
separate design decision and needs its own evaluation rather than being a side
effect of this change.

So: default off, kept for the tx_qstop fix it does deliver and as the base for
any future latency-vs-aggregation work.  An earlier reading of "757 vs 650 in
favour of pull" was RF noise from single samples and is superseded by the
alternating test above.

No regression with it off: 6 of 6 ping trials clean, tx_frames ==
tx_done_events exactly, oversize 0, RTT ~2.3 ms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 16:53:11 -04:00
Paul KilarandClaude Opus 5 fb145792ed sv6160: prepare for A-MSDU, and record why it cannot engage yet
A-MSDU is the one lever left on the TX bottleneck.  The cost is ~500 us per
CMD53 almost regardless of size, the chip insists on one CMD53 per frame,
padding the length kills the link and the vendor records that concatenating
does too -- so the only way to move more bytes per command is to make the
frames themselves bigger.

Two things done here, and one thing found.

Done: mac80211 builds an A-MSDU as a frag_list chain hanging off the head skb
(tx.c ieee80211_amsdu_aggregate), while our SDIO write pushes skb->data for
skb->len -- the LINEAR part only.  Handing that to the chip would put garbage on
the air.  sv6160_mac_tx() now flattens any nonlinear skb once, so everything
downstream can keep treating a frame as one contiguous buffer.  This was the
real reason the driver could not simply switch IEEE80211_HW_TX_AMSDU on.
`amsdu=1` sets TX_AMSDU and max_tx_fragments; tx_max_frame and linearise_fail
are exported so aggregation can be seen working.

Found: with amsdu=1 the largest frame we ever transmit is still 1542 bytes, so
nothing is being aggregated.  The reason is our own TX model.  We use

    .wake_tx_queue = ieee80211_handle_wake_tx_queue

which is the push-model compatibility shim: on every wake it drains the txq
completely into .tx() (util.c, `while ((queue = ieee80211_next_txq(...)))`).
ieee80211_amsdu_aggregate() works by appending a new skb to one already sitting
in the fq flow, so a queue that is emptied on every enqueue never has a head to
append to.  Dropping .wake_tx_queue entirely does not help either: then
sta->sta.txq[tid] is NULL and the aggregation path returns immediately.

So A-MSDU requires the pull model -- our own .wake_tx_queue that leaves frames
in the txq and dequeues with ieee80211_tx_dequeue() when descriptors are free.
That is a real refactor rather than a flag, because ieee80211_next_txq() and
ieee80211_return_txq() run under local->active_txq_lock (a spinlock) and our
SDIO write sleeps, so frames have to be pulled in bounded batches under the
lock and written outside it.  Worth doing: it would also retire the
stop-every-queue behaviour that tx_qstop measures (731 stops in 2645 frames
under bulk), since a pull-model driver simply stops pulling instead of calling
ieee80211_stop_queues().

Off by default and harmless: 6 of 6 ping trials clean, tx_frames ==
tx_done_events exactly, oversize 0, linearise_fail 0, RTT ~2.3 ms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 16:26:52 -04:00
Paul KilarandClaude Opus 5 b40d62a86d sv6160: locate the TX bottleneck - it is per-CMD53 cost, and padding cannot fix it
Split the single tx_avg_us timer into its parts to find where 7.4 ms per
sv6160_sdio_write_tx() actually goes.  It is not lock contention:

  tx_avg_us 6374
    mutex_avg_us  143    waiting for sc->lock
    claim_avg_us    5    waiting for the SDIO host
    desc_avg_us   557    the 581-byte descriptor CMD53
    body_avg_us  5805    the frame-body CMD53s (6608 bytes)

The descriptor is the useful datum because its size never changes: 581 bytes
takes ~600 us, where 581 bytes at 50 MHz x 4 bits should take 23 us.  The bus
is configured correctly (mmc2 ios: 50 MHz, 4-bit, high-speed; err_stats all
zero; no fifo-mode in DT so IDMAC is in use), so the cost is the command, not
the clock.  Working the two sizes (581 B in ~600 us, ~1500 B in ~1280 us) gives
roughly 500 us of fixed cost per CMD53 with a marginal rate around 1.35 MB/s --
so with ~7 CMD53s per batched descriptor the TX path spends ~4 ms in overhead
per descriptor, and that is the throughput ceiling.

The obvious lever is fewer commands.  sdio_memcpy_toio() splits a transfer that
is not a whole number of blocks into a block-mode CMD53 plus a byte-mode CMD53
for the tail, so padding to a block boundary should halve the command count.
tx_pad_blk does that, bounded by skb_tailroom() so it can never read past the
end of an skb.

REFUTED ON HARDWARE.  tx_pad_blk=1 kills the link instantly -- transfers stop
dead and the wiphy disappears -- so the chip really does care about the exact
CMD53 byte count.  That is the same sensitivity the vendor records as
"concatenating cmd+frames breaks it (tried)" (rpu_if.c rpu_send_cmd_datas),
seen from a different angle.  The knob is kept and defaulted off so the next
person does not spend a cycle rediscovering it.

No regression with it off: 6 of 6 ping trials clean, tx_frames ==
tx_done_events exactly, oversize 0, RTT ~2.3 ms.

Where this leaves the bottleneck: the command count per frame cannot be reduced
(one CMD53 per frame is the chip's contract, and padding is rejected), so the
remaining lever is carrying more bytes per frame -- A-MSDU.  We advertise
neither IEEE80211_HW_TX_AMSDU nor IEEE80211_HT_CAP_MAX_AMSDU today, so every
frame is one MSDU of at most ~1500 bytes paying a full ~500 us command.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 15:26:01 -04:00
Paul KilarandClaude Opus 5 a84b5ae44c sv6160: give rate control usable TX status - minstrel was stuck at MCS 1
Two bugs in the TX status path meant mac80211's rate control never learned
anything, and it parked the link at MCS 1 (13-19 Mbit/s) with the signal at
-52 dBm and the AP sending to us at MCS 5.

1. We destroyed the rate chain.  ieee80211_tx_info_clear_status() deliberately
   preserves status.rates[].idx/flags -- they alias control.rates -- and zeroes
   only the counts, "since you need to fill that in anyway".  We overwrote
   rates[0] with whatever rate the firmware reported and set rates[1].idx = -1,
   so minstrel could not attribute attempts to the rates it had asked for.  Now
   the chain is left intact and only the count on the entry the firmware
   actually used is filled in, which is what the vendor does (tx.c tx_status).

2. Worse, minstrel was discarding the status entirely.  clear_status() does NOT
   clear info->flags, so IEEE80211_TX_CTL_AMPDU survived from the control path,
   and minstrel_ht opens with

     /* This packet was aggregated but doesn't carry status info */
     if ((info->flags & IEEE80211_TX_CTL_AMPDU) &&
         !(info->flags & IEEE80211_TX_STAT_AMPDU))
             return;

   Since TX batching marks nearly every data frame TX_CTL_AMPDU, rate control
   was throwing away the status for almost all of them.  We report each frame
   to mac80211 individually against a per-frame frm_status -- we never get a
   BlockAck bitmap -- so the honest thing is to report them as ordinary MPDUs.
   The vendor clears exactly these two flags for the same reason.

Measured on hardware, same link, same AP:

  before   ask_mcs 1:1082   use_mcs 1:4477   tx bitrate 19.5 Mbit/s MCS 2
  after    ask_mcs 7:2689   use_mcs 7:13025  tx bitrate 72.2 Mbit/s MCS 7 SGI
                                             tx failed 0

The firmware was never the problem: rate_match 13154 / nomatch 104 shows it
honours whatever chain we hand it.  Confirmed independently with the new
fixed_mcs override -- forcing MCS 7 transmits at MCS 7 with zero failures, so
the rate was available all along and only the feedback was missing.

Throughput did NOT move (648-663 kB/s either way, and fixed_mcs=7 measured
back-to-back against default is identical), because the link is not rate
limited at the moment.  Counters at MCS 7 show where it actually goes:

  tx_avg_us 7422   lock_avg_us 2189   busy_avg_us 2077   drains 8311

7.4 ms per SDIO TX write, 6092 writes in a ~40 s test -- about 45 s of
TX-write time, i.e. the driver is serialised on the SDIO bus, with the RX
drain holding it ~2 ms per wake (including a deliberate 600-900 us settle
sleep at chain 0).  That is the next bottleneck, and it is a separate problem
from rate control.  An earlier 1.6 MB/s reading under fixed_mcs=7 was RF
variability, not the rate -- back-to-back measurement refuted it.

Also adds, all diagnostic and off/harmless by default:
- ask_mcs/use_mcs histograms and rate_match/nomatch, which is how the
  firmware-honours-our-chain question was settled.
- tx_qstop, counting how often one AC running out of descriptors stops EVERY
  mac80211 queue.  Measured 731 stops in 2645 frames under bulk, 730 of them
  from AC_BK -- the per-AC queue split the vendor has is still missing here.
- fixed_mcs, to force a rate and separate "rate control is choosing badly"
  from "the link cannot do better".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 14:57:30 -04:00
Paul KilarandClaude Opus 5 0170a39517 sv6160: the stale-RECV_LEN guard is what breaks reconnect - default it off
`nmcli con down` followed by `con up` failed every time, and a fresh module
load always worked.  The cause is the stale-RECV_LEN guard, not anything in the
connect path.

Case 1 fires when !assoc && !connecting && pkt_len == last_recv_len && >250 ms
since the last drain && >2 s since the last TX.  That is exactly the state after
a disconnect: every drain is carrying the same 28-byte COMMAND_PROC_DONE, and an
idle disconnected link satisfies both timers by definition.  The firmware's
delivery doorbell is one-shot, re-armed only by the DMA completion of a real
read, so the one skipped wake kills the whole firmware->host pipe and nothing
short of a module reload brings it back.  The guard's own comment already
described this failure mode for the scan-complete case; it turns out the
post-disconnect state reaches it too.

Caught in the trace as an RXEND with no RXLINK at all -- a drain that read
nothing:

  538.414  EVLOG 44 id=17                          <- last event, ever
  538.414  RXEND d=664 chain_done=1 recvlen=28
     ...20 s of silence...
  558.505  CMDLOG 38 id=1 (SCAN)
  558.505  RXEND d=665 chain_done=0 recvlen=28     <- guard skipped it
  574.627  scan timeout at ch 0

Bisected with a scan as the probe, because a scan is the one thing this
firmware always answers.  Scanning works fresh (10 BSS), works repeatedly,
works WHILE ASSOCIATED, and returns 0 BSS with the host-wake counter frozen
immediately after a disconnect -- so association does not do it, scanning does
not, and scanning while associated does not.  Refuted as the trigger, each with
that same verdict: multicast teardown (mcast=0), BlockAck teardown (ba_rx=0),
SETKEY DEL, the cleared-BSSID VIF_CFG, the STA_DISCONN VIF_CFG, and the
disconnect-time CMD_CHANNEL (the new disc_skip=1/2/4/8).

Also verified: mac80211 never calls .stop() on `nmcli con down` (no "mac80211
stopped" after the initial load), which is why nothing re-initialises the
firmware and only a reload recovers it.

With stale_guard=0: post-disconnect scan returns 12 BSS and `nmcli con up`
succeeds, twice out of two.  Regression check on the path that already worked:
6 of 6 ping trials clean, tx_frames == tx_done_events exactly, oversize 0, RTT
unchanged at ~2.4 ms.  The vendor has no such guard anywhere and simply always
reads; a spurious -110 is handled by the runtime recovery instead.

Supporting changes:
- The trace budgets are now restartable: writing a DIFFERENT value to the trace
  parameter resets them, so a harness can arm the trace immediately before the
  window it cares about.  Without this a reconnect trace came back byte-identical
  to the initial-connect trace, which looked like "nothing differs" but was
  really "the budget ran out during the first connect".
- disc_skip, a bisection knob for taking a disconnect apart one command at a
  time, kept for the next time something in teardown is suspect.
- was_connected, so disconnect-only behaviour can be told apart from the
  identical-looking pre-first-connect state.  The first attempt at the
  CMD_CHANNEL arm suppressed bring-up's channel program too and failed to
  connect at all; that arm was invalid, not a refutation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-12 08:31:54 -04:00
Paul KilarandClaude Opus 5 f10b5fd5fe sv6160: stop the TX resync from breaking reconnects, and delete group keys properly
Testing the normal NetworkManager path (rather than wpa_supplicant with a
static IP, which every harness here had been using) turned up three things.

The good news first: NM connects fine on a fresh load -- `nmcli con up` returns
0, DHCP completes, ping is 4/4 at 0% loss.

1. The hw-restart escalation added in 672fdf5 was doing real harm.  It fired
   during connection TEARDOWN, where frames in flight legitimately never
   complete because the firmware has been told to disconnect, called
   ieee80211_restart_hw(), and that produced

     WARNING ... ieee80211_reconfig+0x1ec  (net/mac80211/util.c:1870)
     WARNING ... ieee80211_del_chanctx+0x8c (net/mac80211/driver-ops.h:1038)

   leaving the interface unusable.  Now the resync does nothing unless we are
   associated, and the escalation is behind tx_resync_giveup, default 0 = never.
   It was only ever justified by argument; it has now been measured doing harm
   and never measured doing good, so it stays switchable rather than automatic.

2. Descriptors in flight when a link drops were never retired, so their AC
   stayed pinned at its two-descriptor limit for ever.  sv6160_get_token() then
   refuses that AC and the worker stops ALL mac80211 queues, which means the
   next connection attempt cannot even put its authentication frame on the air.
   Factored the pool retire out of the resync into sv6160_tx_retire_all() and
   call it from sv6160_tx_flush_link() when the BSSID is cleared and on
   disassociation.

3. The group key was deleted from the firmware under the wrong peer.  mac80211
   clears bss_conf.bssid BEFORE it deletes the keys -- measured:

     16315.790  Setting BSSID 00:00:00:00:00:00
     16315.868  set_key: DEL keyidx=1 group

   so reading bss_conf.bssid live sent the firmware a delete addressed to
   00:00:00:00:00:00 and the real group key was never removed.  The BSSID the
   key was filed under is now remembered in sc->key_bssid and reused for the
   delete.

Also adds the instrument all of this was found with: trace=1 logs an ordered
CMDLOG/EVLOG/TXLOG/RXLINK/RXEND stream, bounded so it cannot flood the 1.5 Mbaud
serial console.  RXLINK prints each chain link's read length and the next length
the firmware advertised, which is what made the RX aggregate cap visible in the
first place.

No regression on the path that works: 6 of 6 ping trials clean, tx_frames ==
tx_done_events exactly, oversize 0, RTT unchanged at ~2.4 ms.

NOT fixed, and now precisely located: after a disconnect the firmware's event
pipe goes quiet and the first management frames of the next connection are never
completed -- token_bmp 0x108, i.e. both AC_VO descriptors stuck, with the last
RXEND showing a normal chain_done=1 drain.  Association itself can still
succeed (one cycle authenticated in 8 ms and associated) but no data flows, so
DHCP times out and NM walks the other BSSIDs until it gives up.  connect_fix=32
(the pre-auth 1-channel scan re-arm) does not help.  Reconnect is therefore
still broken; a fresh module load is not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 23:37:01 -04:00
Paul KilarandClaude Opus 5 7ddda507ba sv6160: pack several frames into one TX descriptor
The firmware completes a DESCRIPTOR, not a frame, and an AC may hold two
descriptors.  With one frame per descriptor that caps TX at two frames per
completion round-trip -- ~4 ms measured -- however fast the radio is.  The
vendor packs whatever is queued for that AC into a single descriptor
(rpu_if.c:1881, num_frames_per_desc = skb_queue_len(txq)); cmd_tx_ctrl has
pkt_length[16] and per_pkt_crypto_params[16][12] for exactly this.

One descriptor carries one config_mac_header and one rate block, so a batch has
to share them.  Eligibility is the vendor's rule verbatim (tx.c
check_80211_aggregation): QoS data, marked IEEE80211_TX_CTL_AMPDU by mac80211,
and identical A1/A2/A3 -- "RPU has a limitation, it expects A1-A2-A3 to be same
for all MPDU's within an AMPDU".  Two more are implicit there because the vendor
keeps a queue per AC and per peer, and are checked explicitly here: same
firmware queue, and same protected-ness, since `encrypt` is descriptor-wide.
Each extra frame contributes only its length and its own seq_ctrl/qos_ctrl/IV.

On the wire it stays one CMD53 per frame after the descriptor, never a
concatenation -- the chip treats each CMD53 as one message and consumes them in
order against num_frames_per_desc (rpu_if.c rpu_send_cmd_datas: "one transfer
per frame ... concatenating cmd+frames breaks it (tried)") -- all still under a
single host claim.

Completion follows: frm_status[i] now means frame i WITHIN this descriptor,
which is the firmware's actual contract (vendor walks frm_status[pkt] for
pkt < num_frames_per_desc).  Frame 0 stays in tx_pending[] and remains the one
ownership token that TX_DONE and the stall resync race for with cmpxchg, so
batching needs no new locking; whoever claims it owns the rest.  The batch is
snapshotted BEFORE the descriptor is handed back, because the worker can reuse
that id the moment the token is free.

Measured, same build, alternating arms, 6 MB each way over ssh:

  tx_batch=1   device TX 450 kB/s   device RX 1.0 MB/s   6166 descriptors
  tx_batch=8   device TX 797 kB/s   device RX 1.6 MB/s   1097 descriptors

i.e. 5.56 frames per descriptor against 6103 netdev packets, 5.6x fewer SDIO
descriptor writes, TX +77% and RX +60% (RX gains because ACKs get out sooner).
tx_done_events == tx_frames exactly in both arms, 0 resyncs, oversize 0.
Separately, 6 of 6 ping trials clean with batching on and RTT unchanged at
~2.4 ms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 22:16:53 -04:00
Paul KilarandClaude Opus 5 ab19a1c3a7 sv6160: read RX into one persistent buffer instead of a per-read skb
Raising SV6160_MAX_RX_SIZE to 33280 in bc8b736 left a hazard behind: the drain
did dev_alloc_skb(pkt_len) and read straight into it, so every large aggregate
now asked for up to 33 KB of GFP_ATOMIC memory, and the failure path was

	skb = dev_alloc_skb(pkt_len);
	if (!skb)
		goto clear_and_done;      /* clears the IRQ *and rings notify* */

Ringing the doorbell means "I have consumed everything you queued".  Doing that
after reading nothing is exactly the condition that makes the firmware stop
asserting host-wake for good -- so an allocation failure would have reproduced
the permanent stall the larger cap was raised to fix.

The vendor never allocates on this path: it kzalloc's one MAX_RX_SERIAS_BYTES
buffer at init and reads every aggregate into it (rk915 init.c:145, hal_io.c
rk915_serias_read).  Do the same.  The delivery skb is then sized to the event
and filled by copy, and it is allocated with GFP_KERNEL rather than GFP_ATOMIC
because both drain callers are sleepable -- the GPIO handler is a *threaded*
IRQ and the other is a work item, and this path already usleep_range()s and
takes a mutex.

If that allocation still fails, take the vendor's exit instead of the old one:
clear the interrupt so the level line cannot storm, withhold the doorbell
because we consumed nothing, and re-trigger the drain -- the data is still
queued in the firmware and RECV_LEN still describes it.  rx_stats gains
rx_nomem so it is visible rather than silent.

Validated on the harness that produced 4 of 4 STALLED before bc8b736 and 6 of 6
CLEAN after it: still 6 of 6 CLEAN, tx_frames == tx_done_events exactly,
oversize 0, ping RTT unchanged at ~2.4 ms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 21:58:02 -04:00
Paul KilarandClaude Opus 5 bc8b7361fc sv6160: read RX aggregates the firmware's size, not a quarter of it
Root cause of the TX-completion stall, and of the throughput that never went
anywhere: SV6160_MAX_RX_SIZE was 4096.  The vendor's limit is 33280.

The firmware chains RX aggregates and advertises the NEXT chunk's size in the
current packet header's upper 16 bits.  Under real traffic it builds aggregates
bigger than 4096; our chain walk then hit `rx_next_len > SV6160_MAX_RX_SIZE`,
gave up, and left that data sitting in the firmware.  The firmware waits for the
host to collect it and never asserts host-wake again -- so RX, TX_DONE and
command replies stop together, permanently.  That is why TX descriptors looked
like they were leaking: their completions were queued behind bytes we refused to
read.

Caught by the per-chain-link trace added here (trace=1):

  RXLINK d=125 c=0 pktlen=2048 id=0 raw=0x1a000044 next=6656
  RXEND  d=125 chain_done=0 recvlen=2048 irqs=125     <- nothing, ever again

0x1a00 is 6656.  In every stalled trial gpio_irq_count == drains exactly and
both simply stop, with the last RECV_LEN always large (2048 or 1536).

The right value is the vendor's MAX_RX_SERIAS_BYTES verbatim:
MAX_RX_SERIAS_COUNT(16) * MAX_DATA_SIZE_2K(2048) + 512 = 33280 (rk915
inc/if_io.h:22-23, kzalloc'd in init.c:145, handed to rk915_serias_read as
max_len).  One chain "packet" is an aggregate of up to 16 sub-frames, so it is
not bounded by the 2304-byte 802.11 MTU -- which was the wrong assumption behind
4096.  The TX worker's scratch buffer was sized against the same constant for no
reason (it only ever holds the 581-byte descriptor), so it gets its own.

Measured on the harness that had just produced 4 of 4 STALLED: 6 of 6 CLEAN,
tx_frames == tx_done_events exactly, oversize 0.  Sustained 6 MB each way over
ssh: device RX 970 KB/s, device TX 351 KB/s.  A 6391-frame run completed all
6391 with every descriptor sent == seen == done and nothing stuck.
pkts_per_wake rose from ~1.3 to 2.47 -- the firmware's aggregation now works
instead of being truncated.

tx_stall_ms (the whole-pool resync from 672fdf5) stays as defence in depth, but
it is no longer what carries the link.  rx_stats gains an `oversize` counter so
a future cap hit is loud rather than silent, and the chain walk now warns when
it drops a chunk, because doing so is fatal.

Also adds the instrument that found this: trace=1 logs an ordered
CMDLOG/EVLOG/TXLOG/RXLINK/RXEND stream, bounded so it cannot flood the 1.5 Mbaud
serial console.  Off by default.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 21:40:43 -04:00
Paul KilarandClaude Opus 5 672fdf57c8 sv6160: recover the TX path when the firmware stops completing frames
The "descriptor leak" this started from is not a leak: our accounting was
right all along.  The firmware intermittently stops returning TX_DONE
altogether, a few seconds into the first real data traffic.  It is not one
lost completion either -- every descriptor in flight at that instant loses
its completion together (one capture: ids 1, 3 and 6, across two ACs, all
within 83 ms) and none ever arrives.  RX and COMMAND_PROC_DONE keep flowing
throughout, so the chip is alive; only the completion path dies.

That is the whole "a hard TX burst leaves an AC gated with ENOBUFS" report.
The gate is correct back-pressure -- an AC may hold two descriptors -- but
once its completions are lost there is no way out of it, because the only
thing that could release them is the TX_DONE that is never coming.  It is
not burst-specific: it usually fires around frame 15 of ordinary ping
traffic.

MEASURE FIRST.  Base rate ~55%: across 20 baseline trials only 9 carried
traffic.  When it does not happen the link is flawless -- 600/600 pings at
0% loss, 2.4 ms RTT, 650 frames with tx_frames == tx_done_events exactly.
A failure that intermittent makes single-trial A/Bs worthless, which is
precisely how the reverted watchdog (37e5335/61018c5) fooled itself, so
every claim below rests on repeated trials or on a counter.

  tx_tokens  now prints a per-descriptor ledger: busy/ac/skb/age plus
             sent/seen/done per id.  sent > seen means no completion ever
             arrived; seen > done would mean we threw one away.
  rx_stats   now prints a per-event-id census (count, min/max length) and a
             per-command-id census.

Fix: tx_stall_ms, a whole-pool TX resync, on by default at 1000 ms.  When
NOTHING has completed for the window while descriptors are outstanding,
retire the entire pool in one step and wake the queues; after three
consecutive resyncs with no completion in between, escalate to
sv6160_trigger_recovery() rather than keep telling mac80211 that frames
into a dead TX engine were transmitted.

  tx_stall_ms=0     3 of 5 trials carried traffic
  tx_stall_ms=1000  16 of 16, 600 pings each, 0% loss

In 5 of those 16 the resync visibly did the rescuing: it fired once, freed
one or two descriptors, and the link then ran to completion.  It is inert
on a healthy pipe -- 0 resyncs on trials that pushed 650 frames.

This is not the reverted watchdog again.  That one reclaimed descriptors
INDIVIDUALLY, so the worker re-issued an id the firmware still owned and
each reclaim manufactured the next.  This retires everything together, so
host and firmware both end at "nothing outstanding", and it only runs when
nothing at all completed in the whole window.

Also fixed: the TX_DONE guard was a tautology.  The handler walked all 16
frm_status entries mapping entry i onto descriptor desc_id + i, "guarded"
by tx_pending_desc[slot] != desc_id + i -- but slot is (desc_id + i) % 64
and every id we hand out is below 12, so that is always false and the guard
rejected nothing.  What kept it from completing a neighbouring AC's frame
was luck: the break on the first empty slot with a zero status.  We always
send num_frames_per_desc = 1, so it now reads entry 0 only.

Ruled out with data, not argument: TX BlockAck sessions (ba_tx=0 gives 3/5
stalls in BOTH arms over 10 trials); completions dropped for being shorter
than sizeof(struct rpu_event_tx_done) (tx_done_short 0, and the census
counts exactly as many id-1 events as we accounted for, all 96 bytes); a
host-wake swallowed by cancel_work_sync in the command path
(cmd_rx_cancelled 0 -- and the GPIO thread calls sv6160_rx_drain() directly,
it never goes through rx_work); power save (rpu_ps_config is already a
no-op); more_frms and the BA policy value (both already match the vendor).
RPU_CMD_MIB_STATS (27) is the vendor's own command but this firmware never
answers it, so the firmware-side tx_cmd_cnt/tx_done_cnt/tx_crypto_post
counters are not available.

Earlier single-trial results against ba_rx, multicast programming and the
AP were taken before the base rate was known.  One sample against a coin
flip settles nothing; they are inconclusive, not refuted.

Still open: why the firmware's completion path stops.  Not the AP (same
failure on two BSSIDs), not aggregation, not multicast.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 21:06:20 -04:00
Paul KilarandClaude Opus 5 0f71a30816 sv6160: turn the TX watchdog off by default - it caused what it was measuring
The previous commit reported that the firmware only completes about two thirds
of the frames it is given.  That was wrong, and the watchdog added two commits
ago was manufacturing it.  A/B on one build, back to back, same AP, switched by
the new tx_watchdog_ms parameter:

  tx_watchdog_ms=0     Connected at t=10s, t=25s and t=40s
                       tx_frames 9, tx_done_events 9  -- every frame completed,
                       tx_reclaimed 0
  tx_watchdog_ms=1000  tx_frames 24, tx_done_events 15, tx_reclaimed 9,
                       and the link drops within seconds of associating

With the watchdog off the firmware completes everything it is handed.  With it
on, reclaiming a descriptor lets the worker reuse that id straight away, which
desynchronises the firmware's descriptor state so the following frames on that
id are never completed either -- each reclaim creating the next.  The dropped
frames also broke association, which is why the link would not stay up.

So the watchdog is off by default.  The code and its accounting stay behind
tx_watchdog_ms for whoever wants to revisit descriptor reclaim, but any future
attempt needs to stop the reclaimed id being reused immediately, and must be
A/B'd against tx_watchdog_ms=0 before it is believed.

The descriptor leak that motivated it is still real and still unexplained: an
AC can end up with ac1_inflight stuck at 2 after a hard TX burst, which is
where this started.  It just cannot be papered over this way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 18:57:25 -04:00
Paul KilarandClaude Opus 5 61018c5d41 sv6160: measure TX completions; the firmware drops about a third of them
The watchdog added in the previous commit was reclaiming descriptors during
plain association traffic, which could equally have meant its one-second
timeout was stealing frames still legitimately in flight.  It is not.  Count
how long a real completion takes, how many arrive late, how many TX_DONE
events the firmware sends, and how many entries our slot/desc_id matching
throws away:

  tx_frames 24, tx_done_events 15, tx_done_n 15, tx_reclaimed 9
  tx_done_avg_ms 5, tx_done_max_ms 17, tx_late 0
  tx_skip_descmiss 0, tx_skip_noskb 55 (padding entries inside each event)

A genuine completion lands in 5ms, worst seen 17ms, against a 1000ms timeout,
and not one completion has ever arrived after its descriptor was reclaimed.
So the watchdog is not premature -- it is catching real losses.

The losses are the firmware's: 24 frames transmitted, 15 TX_DONE events
received.  tx_skip_descmiss 0 rules out our matching as the cause; the events
are simply never sent.  Without the watchdog those nine descriptors are gone
for good, which is exactly the wedge that made TX die after a burst.

This does not explain why the firmware skips them, but it does say where not
to look: not the drain, not the lock, not the write path (tx_ebusy 0), not the
completion matching.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 18:43:24 -04:00
Paul KilarandClaude Opus 5 37e53354dd sv6160: reclaim TX descriptors whose completion never arrives
Nothing ever took a TX descriptor back if its TX_DONE went missing, so a
single lost completion cost that access category one of its two in-flight
slots permanently, and two killed it outright: `token_bmp 0x042,
ac1_inflight 2 <-- GATED, queue_len 9`, with sendto() returning ENOBUFS from
then on and the interface silently unable to transmit.  Reproducible by
pushing TX hard -- a ping flood at ~500 pkt/s does it every time.

Stamp each descriptor when its frame goes out and run a watchdog that takes
back anything still outstanding after a second.  The skb is claimed with
cmpxchg so the watchdog and a real TX_DONE arriving at the same moment cannot
both own it; TX_DONE now claims the slot the same way.  The vendor has the
same idea, but only from firmware-error recovery (tx.c
rpu_tx_proc_unfi_tx_done synthesises a completion for every descriptor still
marked in flight) -- on a timer it also covers the ordinary lost-completion
case.  Verified on hardware: the counter climbs (tx_reclaimed 22) where before
the queue simply died.

Escalate when reclaiming does not help.  Measured after such a burst: the
firmware stops completing that queue altogether and never resumes -- RX keeps
flowing normally (drains and packets climb) while every frame handed to TX is
thrown away, so the watchdog frees a descriptor, the worker fills it, and
nothing completes, round and round.  After three consecutive reclaiming runs,
restart the hardware, which is what the vendor does for a firmware error.
NOT yet verified on hardware: the escalation path builds and is reasoned from
the observed failure, but the device became unreachable before it could be
exercised.

tx_tokens now also reports tx_reclaimed and tx_reclaim_runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 18:30:35 -04:00
Paul KilarandClaude Opus 5 218f5cc970 sv6160: add RX pipeline accounting to debugfs
Bulk throughput sits at a few KB/s while ping round-trips in 3-11ms with no
loss, and every attempt to explain that from the outside was guesswork.  The
numbers that matter are how often the firmware wakes us and how much each wake
yields, so count them: drains, packets delivered, wakes that found no valid
RECV_LEN, chained reads beyond the first, packets per wake, and the average and
worst gap between wakes.

What it says on a live 30-second download: 115 drains (3.8/s), 154 packets
(5.1/s), 1.33 packets per wake, gap_avg 166ms, only 3 wakes with no data.  So
the ceiling is the host-wake rate itself, not the drain, not the stale guard,
and not an empty-read path -- the firmware simply does not signal more often.

For reference on the same 30-second transfer against the same server, the
vendor rk915 driver on this kernel manages 1.2 KB/s, so this is the platform's
long-standing sustained-RX problem rather than a regression; we are currently
the faster of the two.  rx_chain=0, which would read exactly the advertised
length once per wake, is not a way out: the firmware then stops asserting
host-wake altogether and association never completes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 16:48:28 -04:00
Paul KilarandClaude Opus 5 b7cae8a17f sv6160: stop withholding the notify doorbell; free the descriptor on TX_DONE races
Ringing the notify doorbell only after a completed RX chain, added in the
previous commit as the vendor's rule, breaks TX.  The vendor's serias_read
hands back ONE sub-packet per call and re-reads the chain pointer on each, so
in practice it rings the doorbell on essentially every wake; mapping that rule
onto our read-the-whole-batch-at-once drain meant we withheld it, and the
firmware then stopped delivering TX_DONE.  A/B on otherwise identical runs:

  gate on   ping 0/4 (100% loss), tx_tokens: token_bmp 0x042,
            ac1_inflight 2 <-- GATED, queue_len 1 parked for ever
  gate off  ping 4/4 at 8.7ms avg, tx_tokens: token_bmp 0x000, nothing stuck

Default is now to always ring; notify_gate=1 restores the gating for anyone who
wants to retry it.  The chain-pointer fix from the same commit is unaffected
and stays -- that one is what made DHCP complete.

Publish the pending TX slot before the frame goes out.  The firmware returns
TX_DONE within a few milliseconds and the drain runs on another thread, so
filling tx_pending[]/tx_pending_desc[] after the SDIO write left a window where
the completion found an empty slot, took the "not ours" path and returned
without freeing the descriptor.  Every such miss permanently costs one of that
AC's two in-flight slots until the AC is gated and TX stops for good.  The
write-failure path leaked the same way: it freed the skb but never the token.

Add a tx_tokens debugfs file -- descriptor bitmap, per-AC in-flight count,
queue length, and a marker on any AC at its limit -- because a stuck gate is
otherwise indistinguishable from a dozen other causes of "TX went quiet", and
this is the second time it has had to be inferred.

Demote the per-frame logging (GPIOIRQ, EVENT, RPU_EVENT_RX, RXF, TX, TX_DONE,
COMMAND_PROC_DONE, RX_SERIAS) from dev_info to dev_dbg.  At four lines per
frame this is far too much for a driver that now passes traffic, and it makes
every throughput measurement a measurement of printk.  For the same reason
tools/serial_capture.py now sets `dmesg -n 4` rather than 8: at 8 the driver
flooded the 1.5Mbaud console until printk backed up and every process writing
to it wedged, which once cost a power cycle.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 16:31:32 -04:00
Paul KilarandClaude Opus 5 63c774c85e sv6160: take TX rates from mac80211 instead of a fixed 1 Mbps
The rate block was the last remaining difference between our TX descriptor
and the vendor's for the same frame: vendor num_rates=4, rate=80 80 80 80
(MCS 0), retries=02 02 02 02, rate_flags=08 08 08 08 (ENABLE_11N_FORMAT),
against our num_rates=1, rate=02 00 00 00, retries=05 00 00 00, flags zero.
Everything worked at 1 Mbps, which is a legal way to transmit and is why this
never showed up as a failure.

The vendor does not hardcode a rate either -- it passes mac80211's rate
control decision through, all four slots of it (rpu_if.c get_rate).  Do the
same: MCS rates become MARK_RATE_AS_MCS | idx with ENABLE_11N_FORMAT set,
legacy rates become the band entry's hw_value, and retries, preamble and
protection come from the per-rate flags.  The vendor's proc-tunable overrides
(fixed MCS, fixed legacy rate, multicast rate) are all disabled by default, so
only its normal path is reproduced.  Confirmed on the wire: minstrel_ht now
walks MCS 0 through 5 with rate_flags=0x08, where before every frame went out
at a fixed 1 Mbps.

The band table's hw_value was wrong, which is what made a faithful port
impossible.  It held a plain 0..11 index; the firmware wants the rate in units
of 500 kbps (vendor umac_if.c dsss_rates[]: 2, 4, 11, 22, 12, 18, 24, 36, 48,
72, 96, 108, and its proc path computes (rate * 10) / 5 to reach the same
encoding).  Nothing sent the table's value to the firmware before -- the rate
was hardcoded -- but the RX path already looked rate_or_mcs back up through it,
so the lookup missed on every legacy frame and rx_status->rate_idx was always
left at 0.  Also drop the short-preamble flag from 1 Mbps, which cannot use
one; the vendor flags only 2, 5.5 and 11.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 16:00:33 -04:00
Paul KilarandClaude Opus 5 34b3a2a7fa sv6160: follow the RX_SERIAS chain and stop skipping wakes once associated
The driver now completes DHCP and passes traffic:

    udhcpc: lease of 10.22.48.18 obtained from 10.22.48.1, lease time 3600
    8 packets transmitted, 8 packets received, 0% packet loss
    round-trip min/avg/max = 8.731/20.118/77.389 ms

Two independent stalls of the firmware-to-host pipe were in the way.  Both
end the same way: the firmware's delivery doorbell is one-shot, re-armed only
by the DMA completion of a real read, so anything that leaves data unread or
skips a wake silently kills every event -- no host-wake, no TX_DONE, no RX --
until the supplicant gives up.

An RX_SERIAS batch is not self-contained.  Its outer header's upper 16 bits
are its own first sub-packet's length, and following that reads data which was
never there, so we forced the chain pointer to zero and always cleared and
notified.  But the real chain pointer is the one carried by the batch's LAST
sub-packet, which we were masking off and discarding: the vendor clears the
IRQ and rings notify only once that is zero, and otherwise keeps reading
(hal_io.c rk915_serias_read, "End of the continuous rx 1").  Take it from
where the vendor takes it.  Caught on the wire: the DHCP OFFER arrived inside
a batch that advertised a follower, we dropped the pointer, and not one
interrupt, TX_DONE or frame ever followed -- the two DHCP REQUESTs after it
were written to the chip and never transmitted.

The stale-RECV_LEN guard has to stand down once associated.  Its first clause
skips a wake whose length equals the previous drain's, after 250ms of bus idle
and 2s without a TX.  On a live link equal lengths are the norm, not a symptom
-- a quiet minute of a real connection shows 92, 92, 124, 124, 280, 124 byte
drains -- and a link waiting on DHCP satisfies both timeouts within seconds of
the handshake.  Measured: GPIOIRQ #54 arrived 1.95s after the previous drain
and 5.98s after the last TX carrying the same length as the drain before it,
was skipped, and that single skip ended the connection.  The second clause had
already been hardened against exactly this and carries !assoc; the first never
was.  The vendor has no such guard at all and simply always reads.

RX BlockAck programming gets a ba_rx switch.  The stall appeared immediately
after this command went out, so it was the obvious suspect; an A/B with
ba_rx=0 reached exactly the same point, which exonerates it.  Left on, as the
vendor does, and left switchable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 15:23:01 -04:00
Paul KilarandClaude Opus 5 8df94ba23b sv6160: fix TX crypto, key peer, BA direction and descriptor concurrency
Found by capturing both this driver's and the vendor rk915's complete RPU
command streams with wiredump=1 and diffing them mechanically: every command
struct's sizeof against the vendor's wire length, then payload bytes per
command id.  All 11 struct sizes matched, and VIF_CTRL, MCST_ADDR_CFG,
MCST_FLTR_CTRL, CHANNEL, VIF_CFG, TXQ_PARAMS and PATCH_FEATURES came back
byte-identical.  Everything below is a difference that diff turned up.

TX descriptor concurrency (the one that was halting the firmware).  The
vendor refuses to allocate a descriptor once an AC already has
NUM_TX_DESCS_PER_AC (2) outstanding and leaves the frame in a pending queue
until a TX_DONE frees one (tx.c rpu_tx_alloc_token); its spare ids are an
aggregation-overflow path, not general supply.  Across a whole vendor connect
the wire shows only (queue 1, desc 1) x51, (1,6) x6, (1,10) x1 and
(queue 3, desc 3) x10.  We had the id layout right but no gate, so a burst on
BE took 1, 6 and both spares -- four in flight on one AC.  Measured: the first
two frames after the keys install complete normally, then four fired
back-to-back get no TX_DONE at all and the firmware stops delivering every
event (no TX_DONE, no RX, no command replies) until the supplicant gives up.
With the gate, netdev RX went from 392 bytes / 4 packets to 13066 / 29 and the
first unicast frame ever addressed to us arrived, decrypted under the pairwise
key with its geometry intact.

TX encryption was never requested.  cmd_tx_ctrl.encrypt was left at 0, so the
firmware put mac80211's still-plaintext payload on the air under a header with
the Protected bit set; the AP ACKs that at the MAC layer and then discards it
on the MIC check.  Set encrypt, copy the IV into per_pkt_crypto_params[4..11]
and the QoS control into [2..3], and count the IV in config_mac_hdr_len.  The
descriptor is now byte-identical to the vendor's for the same frame except the
rate block.

The group key was programmed against ff:ff:ff:ff:ff:ff.  mac_addr is the peer
the key belongs to, not the frames it covers; in STA mode the vendor programs
both keys against the AP and uses the BSSID for the group key.  This was the
single differing field in RPU_CMD_SETKEY.  Also declare the 6-byte zeroed RSC
the vendor always sends.

BlockAck sessions were inverted.  We programmed the firmware on TX_START and
did nothing on RX_START, on the assumption that the firmware managed RX
aggregation internally.  The vendor does exactly the opposite.  Without it the
AP starts aggregating on a TID, gets no BlockAck, falls back to BlockAckReq
and eventually stops delivering the TID -- both visible on the air.

MAC address is no longer invented.  eth_random_addr() gave the chip a new
identity on every module load (seven distinct addresses in one session), and
ethtool -P reported the random value as the permanent address, so that was
what went on the air.  Take it from of_get_mac_address() as the vendor does,
falling back to a stable address derived from the RK3326 OTP chip serial and
only then to random.  On this board that yields the same MAC the vendor uses.
vif_addr in VIF_CFG now comes from a copy of vif->addr saved in
.add_interface rather than wiphy->perm_addr, without dereferencing sc->vif
during teardown.

Remaining single-field differences, all now matched: RESET.system_rev 0 ->
0x494D47 (the only difference left in an otherwise byte-identical 554-byte
payload; it does not hang, contrary to the note it carried), TX_POWER 20 ->
15 dBm, and the FW_PRIV P2P MAC octet, which the vendor derives from the first
rather than duplicating it.

Diagnostics: wiredump now dumps commands at full length and covers the TX
descriptor, which never went through the command path; ampdu_action and the
frame tail are logged too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 14:57:37 -04:00
Paul KilarandClaude Opus 5 bcc4e5e6ba sv6160: tell mac80211 the firmware already decrypted the frame
After the WPA handshake completes, the firmware delivers encrypted data
frames with the Protected bit still set in the header and rx_pkt_status =
RX_MIC_SUCCESS -- it decrypted them.  We never set RX_FLAG_DECRYPTED, so
mac80211 took the Protected bit at face value, tried to decrypt plaintext,
failed the integrity check and dropped every one.

Measured with an ungated per-frame log: 550 frames arrived as
"data PROTECTED pkt_status=0" in one run and not one reached the stack, so
DHCP never completed and the supplicant deauthenticated.  The comment that
sat here already said this flag should be set for data frames; the code
never did it.

Link retention improves markedly -- 3.5s to 45s before the supplicant gives
up -- but DHCP still does not complete, so this is necessary and not yet
sufficient.

What the frames actually look like, dumped rather than assumed (an ARP
broadcast, wt_trace=1 shows these):

  08 62 00 00  ff ff ff ff ff ff  d6 21 f9 51 ab 82  74 ac b9 45 99 8f
  30 98 | 92 77 00 60 85 1b 00 00 | aa aa 03 00 00 00 08 06

fc 0x6208 is QoS data + protected; the eight bytes after the 24-byte header
are an intact CCMP IV (ExtIV set, key id 1 = the group key), then LLC/SNAP
and ethertype 0806.  So the IV is PRESENT and RX_FLAG_IV_STRIPPED must not
be set -- mac80211 strips it itself now that it knows the frame is
decrypted.

Next suspect for the remaining failure: this is a QoS frame (header 26
bytes) but it decodes cleanly as 24 + 8 CCMP, and sv6160_rx_frame() carries
a QoS special case that pulls two bytes fewer and trims two from the tail.
That trim lands on the CCMP MIC.

The per-frame log and the protected-frame hex dump are kept behind
wt_trace=1; both were essential here and neither should be ratelimited when
enabled -- net_ratelimit() capped the first attempt at ten messages and made
"zero frames after the keys" look like a finding.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 11:58:21 -04:00
Paul KilarandClaude Opus 5 a9a30440f1 docs: TX wedge fixed; the blocker is now the encrypted data path
Association and the WPA 4-way handshake both complete (CCMP group and
pairwise keys install).  What fails now is that no useful traffic flows
afterwards: DHCP never completes and the supplicant deauthenticates.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 11:19:14 -04:00
Paul KilarandClaude Opus 5 662677128e sv6160: TX descriptor ids are pooled tokens, not a counter
Fixes the post-association "TX-side busy wedge".  The firmware said what was
wrong; we were not listening.  Its FW_ERROR event (id 25) carries a text
string, and at the moment the link died it read:

  fw_err: [3243 F] Invalid desc id

sv6160_mac_tx() allocated descriptor ids from a free-running counter
(sc->tx_desc_id++).  The firmware's descriptor table has NUM_TX_DESCS = 12
entries -- rk915 shared/descriptors.h, (NUM_ACS 5 * NUM_TX_DESCS_PER_AC 2) +
NUM_SPARE_TX_DESCS 2 -- and it rejects any id outside it.  So roughly eleven
frames after association the counter walked off the end of the table, the
firmware faulted, and it then stopped delivering EVERY kind of event: no
TX_DONE, no RX, no command replies.  Our queue backed up behind the missing
completions, we kept writing, and the card eventually held DAT0 busy so the
writes returned -EBUSY.  The -16 was the last link in that chain, roughly
eleven seconds downstream of the actual fault, which is why it looked like a
bus problem.

Allocate a token from a bitmap instead, following rk915 get_token(): each AC
gets SV6160_TX_DESCS_PER_AC reserved ids, then a shared spare pool; the token
is released in the TX_DONE handler.  The allocation moves from .tx() into the
TX worker, because that is where the AC is known and where an empty pool can
push back on mac80211 -- the frame goes back on the queue and the queues stop
until a completion frees an id.

Measured: the link stayed up 48s through a full traffic window and was ended
only by the test script's own teardown (deauthenticating ... by local choice),
with zero FW_ERROR events.  Before this it wedged after 12-15s, every time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 11:12:14 -04:00
Paul KilarandClaude Opus 5 1e253af005 docs: RX side is clean; only the TX busy wedge remains
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 10:47:28 -04:00
Paul KilarandClaude Opus 5 7ad6193284 docs: correct the end-of-chain conclusion — a batch is self-contained
The previous section concluded there was no host-visible end-of-chain marker.
That was wrong.  The upper 16 bits of an RX_SERIAS header are the length of
its own first sub-packet, already delivered inside the batch -- not a pointer
to another packet on the bus.  Six refuted fixes were all aimed at the phantom
that produced.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 10:46:55 -04:00
Paul KilarandClaude Opus 5 c7914147dd sv6160: an RX_SERIAS batch does not continue the chain
Fixes the post-association wedge.  Found by dumping every link of a chain
rather than reasoning about it; one drain, three links:

  chain=0  id=17  length=0x00b0001c   this 28, next 176
  chain=1  id=30  length=0x001c0000   the 176-byte RX_SERIAS batch
           RX_SERIAS: 4 packets, [0] len=28 ...
  chain=2  read 28 -> -110, bus wedged

The batch header's upper 16 bits are 0x1c -- exactly the length of its own
FIRST SUB-PACKET, which had already been delivered inside the batch.  They
are sub-packet metadata, not a pointer to another packet on the bus.  We
followed them anyway, asked the firmware for a packet that was never there,
and the read timeout took the DW MMC controller down with it.

So a batch is self-contained: stop the chain when the event just read is
RPU_EVENT_RX_SERIAS.

Measured over two runs: zero RX read failures, three batches handled
cleanly including a 352-byte one that previously produced the 204-byte
"echo" this was mistaken for.  The link now ends only on the TX-side busy
wedge, at 15.4s and 12.0s associated with traffic flowing.

This also explains the six things that did not work, all of which were
treating the symptom.  The "stale wake re-presenting a consumed length" was
never a stale wake at all -- it was this over-read, arriving as a late -110
because the CMD53 timeout is most of a second.  Skipping the wake, settling
longer, releasing the bus, tolerating the failure, disabling the chain and
cross-checking RECV_LEN were all aimed at a phantom.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 10:46:44 -04:00
Paul KilarandClaude Opus 5 6c577e3d07 docs: the RX chain has no reliable end marker — five refutations
Records the measured dead ends for the post-association wedge so the space is
not re-searched: skipping the wake (stalls the one-shot doorbell), tolerating
the failed read (the next write -16s anyway), settling before every chained
link at 200us and at 2-3ms (no change), releasing the bus between links the
way the vendor does (no change, still 4-packet batches), and disabling the
chain entirely (no wedge, but no command replies and no association -- the
chain is required).

The fifth is the informative one: stopping on RECV_LEN instead of the packet
header's next-length fails identically, because RECV_LEN is unreliable too --
it reported 412 bytes available with nothing behind it.  BOTH signals the
firmware offers describe data that is not there once a chain is under way, so
there is no host-visible end-of-chain marker to get right.

That points at the clear+notify handshake instead.  The vendor does
rk915_clear_irq + rk915_notify when rx_next_len reaches 0, inside its
per-packet receive call; we do it once after the whole chain.  If that
handshake is what advances the firmware's read pointer, everything we read
after the first packet is served from a pointer that never moved -- which
would explain why both length signals lie.  Moving the handshake inside the
chain loop is the next experiment.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 09:25:48 -04:00
Paul KilarandClaude Opus 5 43558d2f82 docs: record the post-association wedge, and two fixes that do not work
Section 15.  The failure is always "RX read N failed: -110 (chain=2)", and
chain=2 says it is the chain walk reading one link too many off the end of a
burst -- not a phantom wake.

Two plausible fixes are refuted with measurements so they are not retried:

  - Tolerating the failed read the way the vendor does (log it, abandon the
    receive call, reset nothing) does not save the link.  The read fails, we
    carry on, and 600ms later the next write returns -16 anyway: the DW MMC
    controller is already stuck by the time the read returns.  The bad read
    has to not be issued at all.

  - Extending the pre-read settle from the first link to every chained link
    changes nothing.  Same chain, same length, same result.  It is not DMA
    latency.

The remaining lead is an asymmetry worth explaining: with the vendor's own
logging enabled at runtime (debug_mask=0x50000, no reload required) a few
seconds of real traffic produced ZERO multi-packet RX_SERIAS batches -- every
read was a single packet with next_pkt(0).  Our driver sees 4-packet batches
constantly under the same conditions.  Something about how we drain makes the
firmware aggregate where it does not for the vendor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 08:54:15 -04:00
Paul KilarandClaude Opus 5 4b7dd8be46 sv6160: say which link of the RX chain failed, and record a dead end
The read-failure warning could not distinguish the length the firmware
advertised in RECV_LEN from a length we derived ourselves by walking the
chain.  It now prints both, and the answer changes the picture:

  RX read 28 failed: -110 (chain=2, RECV_LEN was 28)

chain=2, so this is not a phantom wake at all -- it is the chain walk
reading one link too many.  Two of the three read failures seen today were
at chain>=1.

That also explains why the skip-the-wake guard added in 66d5c41 helps only
partially and has a cost of its own: sampling the firmware's counters
through a run shows the fwpeek replies stop dead at the instant the guard
skips a wake, because the delivery doorbell is one-shot and re-armed by the
DMA completion of a real read.  Skipping trades a bus wedge for a stalled
pipe, and the TX -16 a few seconds later is the downstream symptom.

Tried and reverted: continuing the chain from the LAST sub-packet's
next-length, the way the vendor does (rk915 hal_io.c:242 rk915_serias_read
keeps draining while rx_next_len is non-zero and only clears+notifies when
the batch is exhausted and the chain is empty).  Our batch walker discards
those upper 16 bits, so that looked like the missing piece.  It made things
strictly worse -- the link stopped associating at all -- so the difference
is not simply that we drop the trailing next-length.  Left out of tree;
noted here so it is not re-derived.

Best measured state remains the one in 66d5c41: 15.4s associated with
traffic flowing both ways.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 08:22:53 -04:00
Paul KilarandClaude Opus 5 049e8d0fec docs: the link now passes traffic; record the wedge progression
Associated uptime with traffic flowing went 0.7s -> 6.6s -> 15.4s across the
two fixes, which is worth keeping in the README as a regression check.  What
ends it now is the chip holding DAT0 busy under load -- the same
sustained-traffic wedge that limits the vendor driver.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 00:01:52 -04:00
Paul KilarandClaude Opus 5 66d5c416b0 sv6160: survive the post-association wedge — 0.7s associated becomes 15s
Two independent causes, found by loading the driver under serial capture and
watching what actually ends the link.

1. The RX_SERIAS echo.  The firmware delivers a batch, then re-presents the
   batch's FIRST sub-packet length on a later lone host-wake with no data
   behind it.  Measured twice: a 352B batch of (204,28,28,28) followed ~690ms
   later by a wake advertising 204, and a 1024B batch of (408,28,28,28) by one
   advertising 408.  Reading the absent bytes times out and wedges the bus.

   Neither existing clause catches it: Case 1 compares against last_recv_len,
   which holds the aggregate rather than a sub-packet, and Case 2 stands down
   at association.  Neither can lean on the idle heuristics either -- the echo
   lands well inside 2s of the assoc request we just sent, so a "no TX for 2s"
   condition never holds.  My first attempt keyed on every length the drain
   consumed and did not fire for exactly that reason.

   So match the one diagnostic thing: precisely the length that batch handed
   us, only in the window where the echo appears, and only once.

2. Giving up on a busy card.  -EBUSY on a CMD53 write is the chip holding
   DAT0 busy, which it does for hundreds of milliseconds under load -- the
   same behaviour that limits the vendor driver.  Three 5ms retries gave up
   roughly 30x too early, and we then declared the bus wedged and tore the
   link down.  Wait it out instead, ~400ms in 25ms steps, releasing the host
   between attempts so the RX drain can interleave (the chip may be busy
   precisely because it wants us to collect frames).  A retry always restarts
   from the descriptor: desc and body must reach the chip back-to-back under
   one claim, so a failure partway through is not retryable.

   -ETIMEDOUT is left alone: that means the transfer died, and retrying only
   flogs a dead controller.

Measured progression, associated uptime with traffic flowing both ways:

  before          0.7s   -> RX read 204 failed: -110
  after fix 1     6.6s   -> sdio_write_tx failed: -16
  after fix 2    15.4s   -> sdio_write_tx failed: -16, 12 TX_DONE / 28 RX events

The link is now genuinely usable for those seconds rather than dying on the
first batch.  What ends it is the familiar one: TX_DONE stops arriving, we
keep queuing, and a write eventually hits a busy card that never comes back.
That is the same sustained-traffic wedge the vendor driver has, and it is the
next thing to chase.

Also short-circuit the new retry budget once sdio_wedged is already set -- 400ms
per write turned teardown of a dead bus into minutes.  That last bit is built
but not yet exercised on hardware.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-11 00:01:35 -04:00
Paul KilarandClaude Opus 5 082f123e22 sv6160: recognise a stale RECV_LEN that re-presents a consumed sub-packet
Association now works, and dies about a second later.  Traced to the exact
wake, roughly 700ms after associating:

  EVENT: id=30 len=0 skb_len=352      <- RX_SERIAS batch
  RX_SERIAS: 4 packets
  RX_SERIAS[0]: id=0  len=204
  RX_SERIAS[1..3]: id=17 len=28
  ... 690ms later ...
  RX read 204 failed: -110
  SDIO bus wedged at runtime -> mac80211 restart

The firmware re-presented 204 -- the FIRST sub-packet of the batch we had
just drained -- on a later lone host-wake with no data behind it.  Reading
the absent bytes times out and wedges the bus, and every association ended
that way within a couple of seconds.

Neither existing clause catches it once the link is up.  Case 1 compares
against last_recv_len, which held the aggregate (352), not a sub-packet.
Case 2 stands down at association (!sc->assoc) on the reasoning that a live
link must not have real unsolicited RX skipped.

So key the new clause on evidence rather than link state: remember every
length this drain actually consumed -- chained packets and RX_SERIAS
sub-packets alike -- and skip a lone wake that re-presents one of them.
That cannot swallow an arbitrary real wake: a genuine frame whose length
happens to match still needs the bus idle 250ms AND no TX for 2s, which a
live link does not satisfy.

NOT YET TESTED.  The build is clean but could not be deployed: the wifi
link truncated three scp attempts of the module (md5 mismatch each time,
which is why the checks are there), gzip + rate-limited scp then died with
"Connection closed", and the board is now hard-hung -- no serial, no
network -- and needs a physical power cycle.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 23:27:52 -04:00
Paul KilarandClaude Opus 5 929a349442 tools: keep the serial console capture and command helpers
serial_capture.py is what finally caught the association-time panic: a hard
reset loses buffered writes to /storage, so an oops that kills the board is
only visible on the console.  It sends dmesg -n 8 first, then streams.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 23:14:06 -04:00
Paul KilarandClaude Opus 5 0393790caf docs: record that association works, and why the scan-gating theory was wrong
The measurements in firmware/README.md sections 12 and 13 were real; the
conclusion they built toward was not.  The firmware's RX counter tracked
scan state perfectly, but the variable that actually mattered was whether
the frame was broadcast: with vif_addr left at 00:00:00:00:00:00 the LMAC
could not address-match unicast, and broadcast only arrives while a scan
has the receiver in promiscuous beacon-receive mode.

Section 14 says so plainly rather than deleting the earlier sections, since
the negative results in them are still worth having -- RPU_CMD_CHANNEL does
leave the RF register at 0, the scan handler is the only thing that sets it,
and writing it from the host does nothing.  All true, all irrelevant.

README now reports the real state: scan, TX, authentication and association
all work; the SDIO bus wedges a few seconds after associating, which is the
next blocker.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 23:13:12 -04:00
Paul KilarandClaude Opus 5 a231f210df sv6160: stop clobbering ieee80211_tx_info; ASSOCIATION NOW WORKS
sv6160_mac_tx() stashed the TX descriptor id with

    *(u32 *)skb->cb = desc_id;

but skb->cb IS struct ieee80211_tx_info, whose first field is `flags`.
Every frame this driver has ever transmitted therefore went out with
mac80211's TX flags overwritten by a small integer.  Nothing complained
while only management frames flowed.  The first data frame after
association panicked the kernel:

  Unable to handle kernel NULL pointer dereference at 0000000000000080
  pc : skb_complete_wifi_ack+0x50/0x154
  lr : ieee80211_report_used_skb+0x478/0x628 [mac80211]
  Comm: irq/69-sv6160
   sv6160_rx_drain / sv6160_gpio_irq_thread
  Kernel panic - not syncing: Oops: Fatal exception in interrupt

-- the clobbered flags happened to claim the frame wanted a TX status
report, and mac80211 then dereferenced a NULL skb->sk.  Move the id into
IEEE80211_SKB_CB(skb)->driver_data, which is the region mac80211 reserves
for drivers, and read it back from there in the TX worker.

With this and the vif_addr fix in 4894a64, the driver associates:

  wlan1: authenticate with d6:21:f9:51:70:a6
  wlan1: authenticated                          (19ms)
  wlan1: associate with d6:21:f9:51:70:a6 (try 1/3)
  wlan1: RX AssocResp from d6:21:f9:51:70:a6 (capab=0x1431 status=0 aid=4)
  sv6160: Associated to d6:21:f9:51:70:a6
  wlan1: associated

That is the unicast auth and assoc responses being RECEIVED -- the thing
that has blocked this driver all along, and exactly what the wire diff
predicted would follow from telling the firmware our real MAC.  Reproduced
across two loads.

The blocker moves on rather than disappearing.  Roughly seven seconds
after associating, the first post-association control write hits

  sdio_write_data(0x00000, 88) failed: -16
  bring-up attempt 1: RESET failed (ret=0 wedged=1)
  ... fw_bringup: wedged after 4 attempts -> mac80211 restart

i.e. the long-standing SDIO -16/-110 bus wedge, now reached at the
association transition instead of before it.  That is the next problem,
and it is the same family as the sustained-traffic wedge documented for
the vendor driver.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 23:12:30 -04:00
Paul KilarandClaude Opus 5 4894a64ac3 sv6160: wire-diff the connect against the vendor; send vif_addr in VIF_CFG
Instrument both drivers to dump every control command in one format
(WIRECMD id=<n> len=<n> plus WIRE hex), capture a connect from each, and
diff them command for command.  tools/rk915-wiredump.patch is the vendor
side; wiredump=1 is ours.  Two things about the capture are worth writing
down: the vendor's scans are invisible at its default debug_mask of 0
(debug_mask=2 is RK915_DBG_SCAN), and the kernel ring buffer wraps well
inside a single connect, so dmesg has to be drained continuously or the
window silently disappears.

The vendor's window, from Scan Complete to associated:

  CHANNEL(48) VIF_CFG(88) VIF_CFG(88) [auth TX 581] VIF_CFG(88)
  MCST_ADDR_CFG(38) x6  MCST_FLTR_CTRL(32)  -> authenticated

Ours, same window:

  CHANNEL(48) VIF_CFG(88) VIF_CFG(88) VIF_CFG(88) [auth TX]
  MCST_ADDR_CFG(38) x6                          -> nothing

and the VIF_CFG payloads differ in a way that is hard to argue with.  The
vendor's carry its own MAC at vif_addr; ours carry 00:00:00:00:00:00,
because sv6160_rpu_vif_cfg() has never populated that field -- the struct
has it, the memset zeroes it, nothing ever writes it.  RPU_CMD_VIF_CTRL
also carries vif_addr, but FW_PRIV_INIT only ever carries the FIRST OCTET
of the MAC, so VIF_CFG/VIF_CTRL are the only places the firmware can learn
the whole address.  Without it the LMAC cannot address-match a unicast
frame to us, which is exactly the asymmetry we have been chasing:
broadcast beacons arrive, our unicast auth response never does.

Fill it in, from wiphy->perm_addr rather than sc->vif->addr -- this command
is also sent from paths that run while the VIF is being torn down, and
dereferencing sc->vif there rebooted the board twice.

NOT YET VALIDATED on hardware.  The runs after this change hit a corrupt
scp of the module (Invalid ELF section header overflow -- md5 the .ko after
copying, the link is not reliable), three reboots, and NetworkManager
refusing to activate the profile on the freshly created device.  The change
is a demonstrable correctness fix regardless of whether it is THE blocker.

Two smaller differences the diff turned up, not addressed here: we send
basic_rate_set 0x153 where the vendor sends its bss_conf->basic_rates (15
for this AP), and we send the beacon-interval VIF_CFG (bitmap 0x800) before
the auth frame where the vendor sends it after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 22:31:44 -04:00
Paul KilarandClaude Opus 5 224152f3c8 sv6160: firmware memory writes, and eliminate the RF-enable theory
Refresh the README: scanning and TX have worked for a while, and the status
table still said otherwise.  It now names the single blocker instead.

Add the write half of the firmware-memory path.  DUMP_REG_INFO's rw field
dispatches four ways (0x02009356-0x02009366): 0 read, 1 write, 2 LPW read,
3 LPW write.  The plain write at 0x0200976c is a bare `sw` with no range,
alignment or length check, so sv6160_fw_addr_ok() validates against the
documented memory map before we hand it an address.  Exposed as
fwpoke="0xADDR=0xVAL" with fwpoke_when=, and round-tripped on hardware:
0x1000BBA8 written and read back, through the vendor's debugfs and through
our own driver.

That capability existed to settle a specific question, and it did -- in the
negative.  The disassembly is unambiguous that the scan handler
(fcn.02007aa0) enables the receiver with two stores, *0x42000030 =
0x40021280 then *0x42000034 = 1, i.e. internal RF register 0x00084A00 = 1,
and that the scan-stop mirror fcn.02007ade writes it back to 0.  It is
equally unambiguous that RPU_CMD_CHANNEL is not innocent: rf_enable_disable
(fcn.0200076c) has exactly two callers, both inside the channel worker
fcn.02008d0e -- on at 0x02008dc2, off again at 0x02008ec2 -- so programming
a channel always leaves the radio off.  That is a tidy explanation of every
measurement in section 12.

It is also wrong, and the hardware says so twice.  Writing 0x00084A00 = 1 on
the VENDOR while it sat disconnected and idle, with its RX counter provably
frozen, moved the counter not at all over ten seconds.  And reading that
register on the vendor returns 0 in BOTH states -- while associated and
receiving ~80 frames/s, and while idle and frozen.  So it is genuinely the
only MMIO difference between the scan handler's entry and exit, and it is
genuinely not what gates frame delivery.  Reception must also require the
LMAC to be in a receive state, and the LMAC is the off-image tier-2
processor, so the next evidence has to come from the wire.

rf_keep= keeps the capability, default off, with the refutation recorded at
the definition so nobody re-derives it.

Also corrected in firmware/README.md: 0x42000030 is the address/command port
of an indirect register bus rather than "RF_MODE", 0x42000034 is that bus's
shared write-data port rather than a dedicated "RF_PLL", and RPU_CMD_CHANNEL
*does* program the synthesizer -- fcn.02007954's only callers are boot init
and the channel worker, never the scan path.  The "pre-scan to tune the PLL"
workaround was built on that false premise; what it actually did was switch
the RF on.

connect_fix=32 (replicate the vendor's real pre-auth order: a ONE-channel
scan, then RPU_CMD_CHANNEL, then auth -- captured with the vendor's scan
logging enabled, which is invisible at its default debug_mask of 0) is also
committed, also refuted: same order, same timing, receiver still dead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 21:34:59 -04:00
Paul KilarandClaude Opus 5 ee8f5c33ed docs: the receiver is gated by scan-in-progress; retire four dead ends
firmware/README.md gains section 12, the measurement itself: the
firmware's event_rx_pkt_recv advances only while a scan runs and freezes
the instant SCAN_COMPLETE fires.  In one capture the target AP's beacons
arrived on channel 6 during a scan, CH_PROG_DONE(ch=6) completed 250ms
later, and nothing was received again -- same channel, same AP.

Vendor control, same counter across a forced disconnect/reconnect:
climbing while associated, frozen for four consecutive samples while
idle, climbing again on reconnect, with "authenticated" 7ms and
"associated" 17ms after the auth frame and no scan anywhere in that
window.  So a receiver that is off outside scan is normal for this
firmware.  The open question is narrower than it looked: what in the
vendor's connect path arms reception, where ours does not?

Corrections to existing text, all of which had been misleading work:

  - The HOST_CMD sub-command table was guessed before the vendor's GPL
    source was available.  Add the authoritative enum fw_priv_cmd_type:
    3 is DUMP_REG_INFO (not SET_PHY_PARAMS) and 8 is FW_SET_PARAMS with
    a struct fw_params payload, not the guessed reset/debug/log bitmap.
  - "the firmware returns no reply for 0x1000xxxx SRAM addresses" was an
    instrumentation artifact.  SRAM reads fine; on the vendor the value
    lands in the fw_info debugfs file, not in the "read fw reg ... val
    0x..." dmesg line, whose val is only the request echo and always 0.
  - "Useful counters (not yet readable)" is now readable, and the whole
    tx_rx_count_info block is mapped onto 0x1000BA98.

VENDOR-DRIVER-FINDINGS.md documents how to drive the vendor driver as a
live control (params takes commands, fw_params takes parameters; the
value is in fw_info; always timeout the cat), its healthy baseline, the
two ways a read can kill it, and four avenues closed with evidence:
fw_priv params (the vendor zeroes them identically), dis_wifi_isr_thd
(set to 1 mid-association and RX continued at full rate), firmware
logging (fw_log is empty on the *working* vendor even at debug_level=3),
and crc_ok/crc_err (read 0 in every sample of every capture, including
while the RX counter climbed 16 -> 47 -- this firmware does not maintain
them, so they cannot tell a deaf PHY from an undecodable one).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 20:32:13 -04:00
Paul KilarandClaude Opus 5 0b7ed955d0 sv6160: read the firmware's own RX counters, and arm RX after each mgmt TX
The SRAM sweep could show that bytes changed but never what they meant.
The vendor's GPL source names both the fw-priv sub-commands and the reply
structs, so take them: fwinfo= issues the self-report dumps and decodes
tx_rx_count_info (FWCNT) and if_info (FWIF), and sweep_len= lets the
sweep cover a region shorter than the hardcoded 1KB.

Sub-command 1 is FW_STATUS_QUERY and returns the TX/RX statistics block
at 0x1000BA98, so the sweep can read the whole thing with the safe,
proven DUMP_REG_INFO path.  Laying the vendor's struct over that base
puts event_rx_pkt_recv at 0x1000BAA8 -- the counter we have been calling
"frames seen" all along, which corroborates the mapping.

What it measured (fwpeek=1 sweep_base=0x1000BA98 sweep_len=32):

  992.53  CH_PROG_DONE (ch=6) after 1 ms
  992.59  Setting BSSID d6:21:f9:51:70:a6 pre-auth operating=1
  992.59  connect RF-arm: 1-ch scan on operating ch=6
          ... 7 beacons from the target AP ...   counter 17 -> 25
  992.74  RPU: scan complete
  992.85  authenticate with d6:21:f9:51:70:a6
  993.06  counter 25    <- frozen from here, permanently

Reception is gated by scan-in-progress.  It starts when a scan starts and
stops the instant SCAN_COMPLETE fires; a bare RPU_CMD_CHANNEL tunes the
radio but does not arm the receiver.  So mac80211's auth frame is sent
into a window where nothing can be heard.  cmd_send/event_recv climb
throughout (the control path is healthy) and cmd_tx_send/tx_done track
1:1 (TX completes) -- only 802.11 reception is dead.

connect_fix=16 acts on that: arm one 1-channel passive scan after each
management TX so the firmware's own ~150ms dwell covers the reply.  It is
opt-in and UNVALIDATED -- across six runs none reached a management TX
before hitting the intermittent -110 wedge, so the hook has never fired.

The scan is handed to the rx_keepalive work item rather than sent inline
from sv6160_tx_worker: sv6160_rpu_send_cmd() does cancel_work_sync() on
rx_work, and waiting on another work item from inside one is exactly the
deadlock __sv6160_rpu_write_cmd() warns about -- the first version of
this hook rebooted the board.  rx_keepalive now re-arms itself only for
connect_fix&4, which reboots the board on its own (3/3) and says so.

fwinfo bit0 (DUMP_TXRX_COUNT_INFO) wedges the bus too: these dumps are
multi-part (dump_info.end == 0 means more follows, and the vendor loops
on it) and our RX drain has no continuation.  Every fwinfo bit is
therefore opt-in, and none is on by default.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Moos7zcsHdpW8DKMq2KM3G
2026-09-10 20:31:57 -04:00
Paul KilarandClaude Opus 5 86f5933fd9 sv6160: add SRAM block sweep and firmware-log dump to the peek
Extend sv6160_rpu_fw_peek() with a length (DUMP_REG_INFO accepts 4..1024,
multiple of 4) and add two diagnostic modes:

  fwpeek=1  sweep 1KB of firmware SRAM from sweep_base= in 92-byte reads,
            hex-dumping each reply.  Lets the state that gates a behaviour
            be found by DIFFING a sweep taken while it works against one
            taken while it does not, instead of guessing addresses.
  fwpeek=2  ask the firmware for its own log (sub-command 4, DUMP_FW_LOG).

Results so far with the sweeps:
  0x10005400..0x100057FF  identical between RX-alive and RX-dead
  0x10006400..0x100067FF  differs only in scan bookkeeping (an ascending
                          per-channel record series that fills in during a
                          scan) and the firmware's log-string buffer; the
                          BSSID we are authenticating with IS present, so
                          our VIF_CFG BSSID does reach the firmware
Two RX-dead sweeps differ in 0 lines, so the sweep is stable and the
comparison is meaningful.

DUMP_FW_LOG returns size=0 -- firmware logging is off by default
(DEBUG_LEVEL/DEBUG_FLAG are 0, settable via sub-command 8 FW_SET_PARAMS
bits 2 and 3, which is a write path and untried).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-10 08:05:32 -04:00
Paul KilarandClaude Opus 5 eff4f2fcec sv6160: don't let the stale-RX guard skip wakes during a connect attempt
Root cause of the auth timeout, found by sampling the firmware's own
frames_seen counter (0x1000BAA8) at 500ms while watching driver activity:

  frames_seen = 34 ... 44   climbing happily during the scan
  RPU: scan complete
  frames_seen = 44          frozen from that instant, forever

RX is not filtered and buffers are not exhausted -- the count sails past
the 34-buffer mark.  It stops exactly at scan-complete, and from then on
even replies to our own commands stop arriving.

The cause is our own stale-RECV_LEN guard.  Its second clause skips a
host-wake of ANY length when the RPU is up, we are not associated, no
scan is in flight and the bus has been quiet.  Both scan conditions
become true precisely at scan-complete, we are never associated, and
mac80211's auth retries leave >2s TX gaps -- so from scan-complete
onward it began skipping REAL host-wakes.

That is fatal rather than merely lossy: the firmware's delivery doorbell
(*0x10005474) is one-shot, armed only by the DMA-completion of an actual
host read (fcn.0200257e via the SDIO ISR).  Skip one real wake and
tx_notify never writes DATA_AVAIL again -- the entire FW->host pipe
stalls permanently.  Hence beacons during the scan, nothing after, and
an auth reply that could never arrive.

Add sc->connecting (BSSID picked, not yet associated) and require
!connecting for that clause, so while mac80211 is authenticating we
always read.  The genuinely-idle case still skips, and clause 1 (exact
length match) is untouched.

Verified along the way that removing the guard wholesale is NOT the fix:
stale_guard=0 reads every spurious wake, takes -110 and wedges the bus.
The guard is load-bearing; it just must not fire while a reply is due.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-10 06:20:51 -04:00
Paul KilarandClaude Opus 5 191b872e00 sv6160: trace the RX drain's register ops (wt_trace=3)
The RX/doorbell path uses the bare sdio_readb/writeb because it runs with
the host already claimed, and wt_trace only wraps sv6160_sdio_readb/writeb.
So the drain's register operations have never appeared in any trace -- I
spent a long time comparing our drain protocol against the vendor's while
being unable to see ours at all.

Route the RECV_LEN reads, the clear+notify writes and the write-completion
poll through traced helpers emitting the vendor's WT52 format, so the two
logs diff directly.

Gated behind wt_trace>=3, not the usual >=1: these sit in the threaded-IRQ
drain and fire several times per host-wake.  Enabling them at drain
frequency hung the board, so the level keeps them out of the way unless
someone explicitly asks for them, and even then they should be used for
short captures only.

Confirmed with this: our doorbell sequence matches the vendor's --
read RECV_LEN(2,3), read packet(s), W32=2, W17=1, poll R35 (register 35
is both INT_STA and WRITE_COMP).  So the handshake is not the difference.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 23:31:16 -04:00
Paul KilarandClaude Opus 5 c471f8fb61 sv6160: fix the fw-priv reply event id (28, not 29) -- peek now works
This firmware emits EVERY fw-priv reply with event id 28, hardcoded in
the reply builder (0x02009400: li a5,28 / sb a5,16(s8), likewise
0x02009812 and 0x02009aca).  The only other ids it ever emits are 25
and 32; it never emits 29.  We had 28 mapped to CALIBRATION_DONE and
discarded the payload, so DUMP_REG_INFO looked like it never answered
and I wrongly concluded the firmware did not support the read.

Also retract the previous commit's warning: sub-command 3 IS
DUMP_REG_INFO.  fcn.0200931c dispatches on rw and rw=0 performs a plain
`lw a5, 0(s11)` (0x0200949e) -- a pure load that writes nothing.  It
could not have damaged the radio.  The real hazard is that there is NO
address validation at all, so guard the address here instead: word
aligned, inside 0x10000000..0x1000BBB8, len a multiple of 4 in [4,1024].

With this the peek returns values, and they locate the fault:

  0x100064E4 RX kill switch   = 0     delivery enabled
  0x100054E4 channel_active   = 0     not set - that theory is refuted
  0x1000BAA8 frames seen      = 12 -> 35, then the firmware stops
                                       answering anything at all
  0x1000BBA8 frames dropped   = 0     always

Zero drops: the firmware never filters our unicast.  It simply runs out
of receive buffers -- fcn.020083fc posts 34 - and once they are gone
nothing more is delivered, not beacons, not the auth reply, not even
command replies.  We "only receive beacons" because beacons are what
arrives during the first ~34 frames; the auth reply comes later, after
the pipe is already dead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 23:08:53 -04:00
Paul KilarandClaude Opus 5 4671f21bc0 sv6160: flag the fw peek as dangerous -- sub-cmd 3 may be SET_PHY_PARAMS
I added the peek trusting the vendor driver's enum, which names HOST_CMD
sub-command 3 DUMP_REG_INFO.  Disassembly of THIS firmware's
sub-command switch labels 3 as SET_PHY_PARAMS
(0x020097dc: li a4,3 ; beq -> 0x20099de).

If that is correct, the "read" was writing a zero-filled PHY
configuration into the radio on every call.  Two observations fit:
the firmware never replied, and a run with fwpeek=1 hung the board.

Document it at the call site and in the parameter description rather
than leave a loaded gun in the tree.  The reply-decode path is correct
and stays; before using this again, establish from the firmware itself
which sub-command performs a read, instead of trusting vendor enum
names for this image.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 22:37:02 -04:00
Paul KilarandClaude Opus 5 9733cef80d firmware: document the RX delivery path, correct §9
Disassembly of the receive path, and corrections to claims in this file
that were guiding work in the wrong direction.

§9's "TX Enable Gate" was wrong: 0x10005474 is a per-transfer doorbell
consumed on each delivery and re-armed by the SDIO DMA-complete
interrupt, not an init gate requiring SET_PHY+SET_BSS+SET_CONFIG.  The
vendor's entire working session contains exactly one HOST_CMD, which
that claim could not explain.

The real RX on/off switch is 0x100064E4, written only from HOST_CMD
sub-cmd 6 offset 0x34 (fw_skip_rx_pkt_submit); if it reads 1 the
firmware frees every received frame.  We send 0, so it is not our bug.

Most usefully for the current investigation: this firmware applies NO
frame filtering at all.  The RX handoff function never reads the 802.11
frame body and has no type/subtype test, no address match and no
bcn_rcv_mode -- so the beacon-versus-unicast split must be made by the
LMAC before frames reach the firmware.  There is also no live
addr1-vs-MAC comparison anywhere in the image; the code that would do it
is linked in but unreferenced.

Also records that channel_active (0x100054E4) stops RX buffer recycling
while set, with only 34 buffers ever posted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 22:12:24 -04:00
Paul KilarandClaude Opus 5 6d550b4e19 sv6160: correct the fw_priv struct, add a firmware-memory peek
Firmware RE of the receive path turned up state worth reading directly
rather than inferring, so add HOST_CMD sub-command 3 (DUMP_REG_INFO,
struct fw_reg_info{reg,val,len,rw} at offset 32, rw=0 READ_REG) behind a
fwpeek= module parameter, and decode the RPU_EVENT_FW_PRIV_CMD_DONE
reply (a text dump_info{size,end,data[]}).

Also replace struct rpu_fw_priv_cmd, whose layout was wrong and unused,
with sv6160_fw_priv_cmd matching what we actually send.  Its offset 52
field is documented now for a specific reason: the firmware stores that
word into 0x100064E4 (0x020099c4), which its RX loop tests at
0x02000a64 -- if it reads 1, EVERY received frame is freed instead of
delivered.  We send 0, which is correct; the field simply deserves a
comment saying what it really is.

Status of the peek itself: the requests go out but the firmware sends no
reply for SRAM addresses (0x1000xxxx).  READ_REG may only serve MMIO
registers, with READ_REG_LPW a separate domain.  Left in place, default
off -- the decode path is written and works the moment a readable
address is found.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 22:11:42 -04:00
Paul KilarandClaude Opus 5 1de9761f65 sv6160: put the mapped queue in hdr.descriptor_id too
The firmware carries the transmit queue in TWO places: cmd_tx_ctrl.queue_num
and the top half of the message header's descriptor_id.  The vendor sets
both (rpu_if.c:1869: `descriptor_id |= (queue & 0xFFFF) << 16`), and its
dumped descriptor reads 0x00030003 -- queue 3 (VOICE), pool id 3.

The previous commit mapped queue_num but left this hardcoded at
`(0 << 16)`, so this half still said queue 0 (BACKGROUND).  The stale
comment on the line even read "queue | desc" while never putting the
queue in.  Compute the mapped queue once and use it for both.

Verified on hardware by dumping our own descriptor: it now reads
descriptor_id=0x00030000, queue_num=0x03, and is otherwise identical to
the vendor's for an equivalent frame -- same rate block (num_rates=1,
protection=0, preamble=1, retries=5, rate=2, spatial=1), same
config_mac_hdr_len=24, same frame_source, with a well-formed 802.11
header (frame_control 0x00b0 = Authentication, addr1 = the AP we receive
beacons from).

The auth timeout is unchanged, which is itself informative: with the TX
descriptor now byte-correct and every frame producing a TX_DONE, the
remaining fault is on the receive side -- we still see only 400-420 byte
beacons and never a small unicast frame.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 21:30:25 -04:00
Paul KilarandClaude Opus 5 4f9999c343 docs: checkpoint the byte-level vendor command diff
Record what the payload-diff campaign established, so the next session
starts from evidence rather than re-deriving it: the four real bugs it
turned up (TX descriptor size, malformed PS command, inverted TX queue
numbering, missing multicast commands) plus the atomic-context defect in
my own multicast work; the list of things now proven byte-identical and
not worth re-checking; and the retraction of the "vendor CHANNEL takes
52ms" signature, which was ack pacing misread as RF commit work.

Most importantly it records where the problem now sits.  Every auth frame
we transmit produces a TX_DONE and beacons arrive normally, but every
received frame is 400-420 bytes and we never see a small one -- the
firmware transmits for us but never delivers a unicast frame.  That
retires TX, channel programming and the command stream as suspects and
leaves a single question for next time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 21:17:44 -04:00
Paul KilarandClaude Opus 5 599cae5ff4 sv6160: map mac80211 ACs to the firmware's transmit queue numbering
mac80211 and the firmware number the access categories in OPPOSITE
directions:

  mac80211: IEEE80211_AC_VO=0, AC_VI=1, AC_BE=2, AC_BK=3
  firmware: WLAN_AC_BK=0, WLAN_AC_BE=1, WLAN_AC_VI=2, WLAN_AC_VO=3

so the firmware queue is 3 - ac.  That is exactly the vendor's
tx_queue_map() (rk915 src/tx.c:130), which it applies to every frame it
transmits (tx.c:990).  We had no mapping at all:

  - every TX frame went out with queue_num hardcoded to 0, which the
    firmware reads as BACKGROUND -- the lowest priority -- including
    auth and assoc frames.  Dumping the vendor's TX descriptor for an
    assoc request shows queue_num=3 (VOICE).  The stale comment on that
    line said "BE queue", which was wrong twice: 0 is BK, not BE.
  - conf_tx passed mac80211's index straight into TXQ_PARAMS, so the
    entire EDCA table was programmed onto inverted queues (VO params
    landed on BK and vice versa), as did the bring-up EDCA loops.

Add sv6160_tx_queue_map() and apply it in the TX path (from the frame's
own skb queue mapping rather than a constant), in conf_tx, and in both
bring-up EDCA loops.

Found by dumping and decoding the vendor's 581-byte TX descriptor; the
rate fields (num_rates=1, protection=0, preamble=1, retries=5, rate=2,
spatial=1) turned out to match ours exactly, but queue_num did not.

Does NOT fix the auth timeout on its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 21:13:24 -04:00
Paul KilarandClaude Opus 5 91b8100226 sv6160: log RX event ids in wt_trace
Log rpu_msg_hdr.id for each drained event, matching the same logging
added to the vendor driver's sdio_recv_data.  Comparing the two event
streams is what showed the CH_PROG_DONE "signature" was a
misinterpretation (see below), so keep the instrumentation.

Vendor event mix over ~12s of bring-up + connect:
  evid=0  (RPU_EVENT_RX)               x405
  evid=17 (COMMAND_PROC_DONE)          x62
  evid=1  (TX_DONE)                    x38

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 20:18:47 -04:00
Paul KilarandClaude Opus 5 fbe79f6d9a sv6160: don't send SDIO commands from .prepare_multicast (atomic callback)
mac80211 documents .prepare_multicast as an ATOMIC callback, and
sv6160_rpu_send_cmd() sleeps -- it takes a mutex and does a synchronous
CMD53.  Programming the multicast addresses straight from there slept in
atomic context and hung the board solid.  My bug, introduced in the
previous commit.

Snapshot the address list in .prepare_multicast instead (a few
ether_addr_copy calls, no sleeping) and do the actual MCST_ADDR_CFG
programming in .configure_filter, which runs from a workqueue and may
sleep -- as the bcn_mode VIF_CFG already sent from there relies on.

The vendor can send directly from its prepare_multicast because its
rpu_send() only takes a spin_lock_bh and hands the buffer to a queue;
ours writes the bus inline, so copying that shape was not safe.

Also make RESET.system_rev opt-in (system_rev= module parameter,
default 0).  Matching the vendor's 0x494D47 is still the right thing on
paper, but it is unvalidated and the only run that carried it also ended
in a hard hang, so it should be A/B tested on its own rather than
riding along with unrelated changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 20:05:09 -04:00
Paul KilarandClaude Opus 5 64e75e8da3 sv6160: send the multicast filter commands and the real short-slot value
Two remaining differences against the vendor's command stream, both from
diffing its SDIO trace: it sends MCST_ADDR_CFG(0x13) and
MCST_FLTR_CTRL(0x14), which were absent from our command enum entirely,
and its bring-up carries a third VIF_CFG with SHORTSLOT_CHANGED whose
value is 0.

Multicast: add the two commands (cmd_mcst_addr_cfg = 38B/wire 40,
cmd_mcst_filter_ctrl = 32B, both matching the firmware structs) plus a
prepare_multicast handler mirroring the vendor's (rk915 umac_if.c:925):
remove the previously programmed addresses, add the new list, remember it
for next time, and return the count.  configure_filter then follows the
vendor's rule (umac_if.c:980): FIF_ALLMULTI or an empty list disables
filtering, a non-empty list enables it.

The part that may actually matter is that the vendor sends an explicit
MCAST_FILTER_DISABLE whenever the list is empty.  We sent this command
never, so the LMAC's multicast filter sat at whatever the firmware
defaults to with an empty address list -- if that default is "enabled",
all multicast was being dropped.  That does not explain the unicast auth
timeout, but it would break ARP/DHCP on an otherwise working link.

Short slot: pass bss_conf->use_short_slot through instead of hardcoding
1, so we stop telling the firmware short-slot is in use when the BSS says
otherwise.  The vendor passes the real value (vif.c
rpu_prog_vif_short_slot).

Both are correct-by-reference; neither is validated on hardware yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 19:52:31 -04:00
Paul KilarandClaude Opus 5 f134cfe5f3 sv6160: set RESET system_rev to the vendor's value
Dumping both drivers' RESET command payloads on the same hardware shows
the 554-byte payload is byte-identical except for one field:

  num_spatial_streams @533 = 0x01        (both)
  system_rev          @534               vendor 0x00494D47, ours 0
  lmac_mode           @538 = 0x10        (both)
  antenna_sel         @542 = 1           (both)
  reserv[2]           @546               (both)

  vendor: ... 00 01 47 4d 49 00 10 00 00 00 01 00
  ours:   ... 00 01 00 00 00 00 10 00 00 00 01 00

The vendor hardcodes `unsigned int system_rev = 0x494D47` (umac_if.c:38)
-- ASCII "GMI" -- and copies it into RESET (rpu_if.c:1085).  Its own
header annotates the field "Unused", and that is probably true, but this
is the last differing byte in the command that starts the LMAC and the
firmware is the authority on what it reads, not a comment in a header
the firmware was not built from.  Cost of matching it is zero.

UNVALIDATED: the board hung during the run that would have measured
this, so this is a correct-by-reference change, not a demonstrated fix.
The trailing "00 00" length delta in the two dumps is ALIGN(len,4)
padding (we log pre-align, the vendor logs post-align), not a real
difference -- both put 554 bytes of content on the wire.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 19:46:29 -04:00
Paul KilarandClaude Opus 5 abbc580ce2 sv6160: add vendor-style control-command flow control (cmd_gate, default off)
The vendor never puts more than MAX_OUTSTANDING_CTRL_REQ (2) control
commands on the bus at once: rpu_send() (rk915 src/rpu_if.c:755) queues
the rest and releases them as RPU_EVENT_COMMAND_PROC_DONE retires the
earlier ones.  We wrote every command the instant mac80211 asked for it,
so a command could land while the LMAC was still busy with the previous
one -- the leading explanation for our CHANNEL being answered in ~1.6ms
(short-circuited) where the vendor's takes ~52ms (actually processed by
the LMAC).

Add the same gate behind a cmd_gate= module parameter, retiring on
COMMAND_PROC_DONE only (the vendor's CH_PROG_DONE retire call is
deliberately commented out, rpu_if.c:2797).

Measured on hardware, and the reason this ships DEFAULT OFF: this
firmware returns COMMAND_PROC_DONE for only a MINORITY of control
commands -- 3 acks arrived while 6 commands sat queued -- so a strict
credit gate starves and the CHANNEL never goes out at all, which is
strictly worse than no gate.  The vendor hits the same thing and
force-retires a slot after 300ms (OUTS_CMD_CHECK), but its check only
runs when a new command is submitted and so cannot drain a queue that
has gone quiet.  Drive it from a timer instead (cmd_gate_work) so the
queue always flows.

Also: the gate's send paths must not cancel_work_sync(&sc->rx_work).
They run either inside rx_work itself (the retire) or in cmd_gate_work,
and cancelling one work item from another that can re-enter the same
gate deadlocks; sv6160_sdio_write_data()'s sc->lock already serializes
against rx_work's CMD53 reads.  Thread a drain_rx flag through
__sv6160_rpu_write_cmd() to express that.

Not yet validated end-to-end: the board hung during the first
(starving) test and needs a power cycle before the timer-drained
version can be measured.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 19:26:10 -04:00
Paul KilarandClaude Opus 5 6a60fdc6f6 sv6160: fix TX descriptor size and malformed PS command
Two defects found by diffing our command structs against the BSP-5.10
vendor rk915 driver, with both drivers instrumented to dump their actual
SDIO command payloads on the same hardware and firmware.

TX descriptor was 512 bytes; the firmware expects 581 (wire 584).
The vendor's struct cmd_tx_ctrl ends with

    unsigned int *p_frame_ddr_pointer[MAX_TX_CMDS];

an array of HOST pointers -- 8 bytes each on a 64-bit kernel, so 128
bytes of tail we were missing entirely (453 + 128 = 581, and
ALIGN(581,4) = 584 is exactly the descriptor length in the vendor's SDIO
trace).  We wrote the 802.11 body immediately after a 512-byte
descriptor, so the body started 72 bytes before where the firmware looks
for it.  Add the field and set SV6160_TX_CMD_SIZE to 581, with a
static_assert so the size can never drift again.

RPU_CMD_PS was both mislaid and gratuitous.  The firmware's cmd_ps is
{ hdr; u32 if_index; u32 mode; } (36B) but we sent
{ hdr; ps_mode; idle_timeout_ms; listen_interval; } (40B), so the
firmware read if_index = <our mode> and mode = <our idle_timeout> = 200,
pushing a garbage power-save state into the LMAC from the idle worker.
The vendor never sends this command at all -- its rpu_prog_ps_state() is
a bare `return 0;` -- so make ours a no-op too and correct the struct so
re-enabling it is not a landmine.

Also add wt_trace=2, which dumps full command payloads.  The terse
trace (addr/len/id) hides content differences, and it was only by
diffing actual bytes that the CHANNEL command could be proven identical
between the two drivers.

Neither fix resolves the auth timeout on its own; both are correctness
fixes verified against the working vendor driver.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 19:11:12 -04:00
Paul KilarandClaude Opus 4.8 abf5d90109 sdio: make the post-CH_PROG_DONE settle tunable (chan_settle param)
Adds a chan_settle module param (default 60 ms, unchanged behaviour) for the
settle after CH_PROG_DONE in __sv6160_chan_prog, used to probe the RF-commit
timing.  Live BSP-vs-ours wire capture on the same AP/channel/firmware pinned
the auth failure: the firmware's CMD_CHANNEL commit worker runs ~51 ms for the
working rk915 driver (full RF + TX-chain arm) but bails in ~2 ms for us (commit
skipped → transmitter never armed → auth TX RETRY_LIMIT), while RX still works
from the scan's separate RX tune.  The gap is the firmware's internal RF-commit
gate, not the settle — but keep the knob for diagnosis.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 10:17:49 -04:00
Paul KilarandClaude Opus 4.8 6db03bda4e sdio: align RF setup with the BSP vendor driver (rf_arm default off, 0x8C thresh, CONF_CHANGE_POWER)
Three corrections keyed off the original BSP-5.10 vendor rk915 driver (the stack
that scans, authenticates, associates and sustains traffic on this exact
hardware), from a disassembly of the vendor .ko:

- rf_arm now defaults OFF.  The vendor never fires a pre-tune passive scan before
  the operating CMD_CHANNEL — it sends a single CMD_CHANNEL and blocks on
  CH_PROG_DONE.  Our pre-tune scan is an extra LMAC command whose throw-away RF
  poke collides with the async retune.  (Still available as rf_arm=1.)

- PHY sensitivity thresholds (reset rf_params[80..93]) set to 0x8C (140), not
  180.  The vendor binary fills its dapt threshold table with 0x8C and its
  default_phy_threshold module param is 0x8C; the 180 here came from a source
  comment the binary disproves.  0x8C already matches rf_params_base, so this
  just stops the reset path from over-desensitising the PHY.

- .config now reprograms TX power on IEEE80211_CONF_CHANGE_POWER, matching the
  vendor which reprograms TX power around channel/power changes rather than only
  once at bring-up.

These align our RF/connect path with the proven-working reference.  They do not
by themselves complete association: on the new kernel the connected-mode receiver
now arms on the operating channel (we hear the target AP's own beacons on it),
but the auth TX is still not ACKed (TX_DONE=RETRY_LIMIT) — the remaining blocker
is TX-chain-specific (the transmitter/PA not radiating while RX is armed), under
investigation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-09 06:47:57 -04:00
Paul KilarandClaude Opus 4.8 55a25df5af sdio: fix stale-RECV_LEN -110 wedge on a length-mismatched lone host-wake
The firmware periodically fires a spurious LONE host-wake ~700ms after a drain
with a stale RECV_LEN pointing at absent data; the CMD53 read of that data
times out -110 and hard-wedges the DW MMC controller (only mmc_hw_reset
recovers), which then storms ieee80211_restart_hw.  The existing stale-guard
skips such a read only when the wake's length equals the previous drain's
(last_recv_len).  But after a CHAINED drain — e.g. a CMD_CHANNEL's CH_PROG_DONE
delivered as a 176-byte serias of 4x28-byte events — the firmware re-presents
the last sub-packet's 28 bytes on the spurious wake while last_recv_len holds
the 176-byte aggregate, so the exact-length match misses it and the bus wedges.

This is precisely the wedge that made the vendor's pre-scan bring-up CMD_CHANNEL
un-sendable on our stack (a bring-up CHANNEL -> CH_PROG_DONE chain -> spurious
28-byte wake -> -110 -> restart storm), which is why an earlier change dropped
the bring-up CHANNEL entirely.

Add a second guard that skips a lone wake of ANY length, but only in the narrow
window where nothing is legitimately expected: RPU up (is_rpu_ready) and NOT in
the bring-up retry loop (bringup_active — where RESET_COMPLETE/CH_PROG_DONE/
FW_PRIV responses are awaited and must be delivered), no scan in flight (scan
beacons are unsolicited RX), not yet associated (no data path to protect; once
associated only Case 1 applies), bus idle >600ms (real responses land within
~100ms; the spurious wake is ~700ms out) and no frame TX'd in 2s (no auth/assoc
response expected).

Verified on hardware: eliminates the -110/restart storm; the driver now runs a
full bring-up-CHANNEL + scan + operating-CHANNEL + auth sequence with zero
wedges, and the default (no bring-up CHANNEL) config still scans all APs with
zero -110.  (The auth TX is still RETRY_LIMIT — the connected-mode TX arming is
an internal firmware/LMAC matter, unaffected by this fix — but the SDIO
robustness bug it exposes is real and now fixed.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 21:21:58 -04:00
Paul KilarandClaude Opus 4.8 ecab5130fe sdio: add wt_trace — SDIO CMD52/CMD53 wire-trace in vendor WT52/WT53 format
Adds a gated `wt_trace` module param (default 0) that logs every SDIO
register access (CMD52) and data transfer (CMD53) in the exact pr_info format
the instrumented vendor rk915 driver emits ("WT52 R/W <reg> = 0x..", "WT53
TX/RX addr=.. len=.. id=0x.."), so our runtime command/register stream can be
diffed byte-for-byte against a vendor capture.  Command id is read from
rpu_msg_hdr.id at buffer offset 16, matching the vendor's *(u32*)(buf+16).

Instruments all five primitives — sv6160_sdio_{writeb,readb,write_data,
write_tx,read_data} — plus the real RX-drain read in sv6160_rx_drain (which
uses a direct sdio_memcpy_fromio, not sv6160_sdio_read_data), so both TX and
RX are captured symmetrically.

Used to complete the vendor SDIO wire-trace: with this on, a full connect
capture on our driver diffs cleanly against the vendor's vtr.txt.  Result —
command payloads and sizes are byte-identical to the vendor's; the only
host-visible differences are command ORDER (we omit the vendor's pre-scan
bring-up CHANNEL, and our operating-channel set + auth overlap a live scan).

Off by default and free when off (a single branch per SDIO op).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 20:58:54 -04:00
Paul KilarandClaude Opus 4.8 6b1a6817d6 sdio: fix skb_complete_wifi_ack crash — verify per-slot desc_id on TX_DONE
sv6160_process_tx_done() iterated all SV6160_MAX_TX_CMDS(16) frm_status
entries of a TX_DONE and, for each, completed whatever skb sat in
tx_pending[(desc_id+i) % 64] — with no check that the slot actually belonged
to desc_id+i. A single-frame completion therefore swept 16 consecutive slots
of the 64-entry ring and could complete unrelated in-flight frames. Worse,
firmware-generated TX (active-scan probe requests) carries its own desc_ids
that alias into occupied slots, so mac80211 was handed a stale/foreign skb and
crashed in skb_complete_wifi_ack (NULL sk) from the RX-drain/tx-status path:

  skb_complete_wifi_ack <- ieee80211_report_used_skb <- ieee80211_tx_status_skb
  <- ... <- sv6160_rx_drain <- sv6160_gpio_irq_thread   (NULL deref @0x80)

Record each pending frame's desc_id (tx_pending_desc[]) at submit time and
complete a slot only when tx_pending_desc[slot] == desc_id+i. Foreign/padding
completions are now ignored. Confirmed on hardware: the crash no longer occurs
under an active-scan workload that previously triggered it.

Also parameterise sv6160_arm_scan_ch(active) — passive for a one-shot RF tune,
active for the (opt-in, connect_fix bit2) keepalive. Note: the active keepalive
is not a viable connect path — continuous active scanning overloads/wedges the
SDIO bus and triggers ieee80211_restart_hw storms — but it no longer crashes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 20:20:46 -04:00
Paul KilarandClaude Opus 4.8 6ed5b8d6ed sdio: fix channel_active latch — commit the operating channel at connect
Firmware RE of the connected-mode TX path found a structural bug in how we
program the channel. The firmware's async CMD_CHANNEL worker (fcn.02007d16) is
what performs the RF commit that ENABLES THE TX CHAIN (LO/divider 0x42000050..5c,
calibration 0x42002cac/cb0, rf_enable) — the scan path only programs the PLL
frequency (enough for RX, not TX). That worker runs only when channel_active
(*0x100054E4) is set, which:
  - is set ONLY by rpu_cmd_channel (fcn.0200154a),
  - is NEVER cleared anywhere in the firmware, and
  - rpu_cmd_channel early-returns if it is already 1.
So the operating channel can be committed only ONCE per boot, and the worker
zeroes the PLL table (*0x100064D0) after its first use.

Our bring-up sent RPU_CMD_CHANNEL(ch1), latching channel_active — which turned
the real connect-time RPU_CMD_CHANNEL into a no-op, so the RF/TX chain was never
committed for the operating channel. Match the vendor sequence instead:
  - bringup_chan=0 (default): do NOT send CHANNEL at bring-up (the firmware
    commits its default channel at boot); let the first CHANNEL be the connect.
  - rf_arm=1 (default): sv6160_rpu_channel() precedes the CHANNEL command with a
    1-channel native RPU_CMD_SCAN on the target channel so the LMAC repopulates
    the PLL table, then CHANNEL latches channel_active and the worker commits
    with fresh, channel-correct PLL data.

This is a correctness fix (the vendor's connect sequence) and removes the
bring-up worker hang seen when forcing the commit. Verified on hardware: the
new flow runs (no bring-up CHANNEL, connect CHANNEL fires CH_PROG_DONE, worker
runs), scan and 802.11 auth still work.

Does NOT complete association on its own: the worker's final TX enable still
depends on the LMAC mode2 handshake (LMAC_HS 0x100054D4==10), which the LMAC
co-processor does not complete for a runtime channel change — the same opaque
LMAC-side condition that blocks the connected-mode RX/TX commit. Params
bringup_chan and rf_arm let this be toggled for further investigation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 20:06:29 -04:00
Paul KilarandClaude Opus 4.8 033e80ebac sdio: arm connected-mode RX (MAC-stays-enabled fw patch + connect RF-arm)
Checkpoint of the connected-mode RX investigation. The multi-session "deaf
radio" wall was the firmware only enabling the MAC/PHY (wifi_mac_enable,
fcn.02000898) during a scan — the scan handler/scan-stop call enable(1) then
enable(0), so after any scan the MAC/PHY is powered down and a fixed-channel
connect finds a deaf receiver (RPU_CMD_CHANNEL never re-enables it; its worker's
PHY-ready gate 0x42048C00&0x100 never passes for us).

gen_fw_macfix.py: turn the scan's two wifi_mac_enable(0) disables into enable(1)
(@0x7AD6, @0x7AFE) + NOP the scan-stop RF_PLL clear (P2 @0x7AFA), so a scan
leaves the MAC/PHY powered and the RF tuned. Verified: does NOT break
multi-channel scan (P1@0x782 / P3@0x8CE do — leave them off).

sv6160_core.c connect_fix bitmask (all gated, default off):
  bit0 scan-hold   — no-op mac80211 off-channel scans while operating, so
                     NM's mid-connect sweeps don't drag the RF off-channel.
  bit1 reinit      — full fw re-bring-up on the operating channel (didn't help).
  bit3 RF-arm      — on BSS_CHANGED_BSSID, a 1-channel passive scan on the
                     operating channel (sv6160_arm_scan_ch) so the RF tunes
                     there while the macfix keeps the MAC/PHY on.
Plus params int_gen (default 1; reg34/33 INT_GEN required for our GPIO RX) and
txq_init (default 0; TXQ_PARAMS at bring-up — vendor sends them, no effect here).

RESULT (macfix fw + connect_fix=9): the CONNECTED-MODE RECEIVER ARMS — beacons
arrive on the operating channel after discovery (RPU_EVENT_RX). This is the
first time connected-mode RX works.

REMAINING BLOCKER (not fixed): connected-mode TX. The auth-request transmits
(TX_DONE retries=14) but is never ACKed by the AP (RETRY_LIMIT), so association
does not complete. The RX chain is up but the TX chain is not — gated by the
same firmware PHY-ready handshake, which the vendor passes on the identical
stock firmware but we cannot reproduce from the host.

Default build unchanged in behavior: native scan (scan_mode=1) + stock fw
scans and reaches 802.11 auth; all connect_fix experiments are off by default.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 19:05:41 -04:00
Paul KilarandClaude Opus 4.8 84aa4d7831 sdio: native RPU_CMD_SCAN by default; find all APs, reach 802.11 auth
The channel-sweep scan (bare RPU_CMD_CHANNEL per channel) delivered ZERO
beacons: a bare CHANNEL command does not re-tune the RF PLL at runtime, so
the sweep only ever tuned its first channel and was deaf on the rest.

Switch the default to native RPU_CMD_SCAN (scan_mode=1) — the path the
vendor uses. With the current firmware patch + the -110 wedge fix it now
delivers beacons via GPIO on every channel (verified: full 13-ch scan finds
all 12 APs on ch1/6/11, 80+ beacons, no wedge). The driver now reliably
scans, builds the BSS list, and reaches 802.11 authentication with a real AP.

Also:
- __sv6160_chan_prog(): send a bare CMD_CHANNEL (vendor-aligned; rf_arm=0
  default) and step the SDIO bus clock per channel before it, exactly like
  the vendor's rpu_prog_channel (50MHz default, 30 for ch7/8, 40 for ch9/10).
  The old pretune-scan RF-arm is kept only as an opt-in legacy fallback: a
  scan's teardown de-commits the RF, so it is not a viable connect-time arm.
- Factor the bring-up retry loop into sv6160_fw_bringup(sc, channel), reused
  by mac_start and (opt-in) the connect path.
- Experimental connect-time RX-arm workarounds behind connect_fix (default
  OFF, so the default is the clean vendor-aligned path): 1=scan-hold,
  2=reinit-connect (full re-bring-up on the operating channel). connect_fix=4
  (active-scan keepalive) is UNSAFE and left off.

Known remaining blocker (not fixed here): connected/normal-mode RX+TX are
dead — the firmware's async RF-PLL commit (LMAC handshake after CMD_CHANNEL)
never completes for us; only a SCAN commits the RF. Auth only completes when
a scan overlaps the window. The vendor's identical CMD_CHANNEL does commit
the RF; the difference is internal to the fw/LMAC co-processor. Association
therefore does not yet complete.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 15:22:58 -04:00
Paul KilarandClaude Opus 4.8 dde4b9e255 sdio: document post-scan RF-RX-deaf diagnostics (active-scan, 300ms settle)
No functional change — records what was ruled out for the "RF receive is
deaf on the fixed operating channel after a scan" blocker:
 - active scan (vs forced passive) does NOT restore post-scan fixed-channel
   RX, so it is not scan-type related; kept passive.
 - a longer 300ms post-CH_PROG_DONE settle does NOT help — post-scan RF-RX
   is stuck, not merely slow.
Decisive evidence gathered this session: with promiscuous beacons forced,
ZERO beacons are received on the operating channel during the auth window
(radio effectively deaf), and TX_DONE reports RETRY_LIMIT (auth never
ACKed). Next: byte-level compare of the vendor's RPU_CMD_SCAN command +
scan->connect teardown, or an LMAC reset between scan and connect.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 08:09:00 -04:00
Paul KilarandClaude Opus 4.8 caa5fedd66 sdio: vendor-align connect path; narrow blocker to post-scan RF-RX deaf
Follow-on from the -110 wedge fix. Vendor-aligned several connect-path
details and instrumented the auth exchange:

- bss_info_changed: at pre-auth (BSS_CHANGED_BSSID) send the BSSID ONLY,
  no connect_state — matching the vendor (vif.c rpu_prog_vif_bssid). We
  had been forcing VIF_CFG_CONNECT_STATE=STA_CONN pre-auth, which the
  vendor only does after assoc=true.
- rpu_vif_cfg pre-auth op_channel: pass the real operating channel
  (sc->cur_channel, tracked in rpu_channel) instead of 0.
- rpu_channel: add the ~50ms post-CH_PROG_DONE settle the vendor uses
  (CH_PROG_DONE fires early; the RF-PLL/RX-arm runs async after it), so a
  following LMAC command isn't issued mid-retune.
- rx_drain stale-guard: gate the "skip stale RECV_LEN" on "no frame TX in
  the last 2s" so a real auth/assoc response (same length as the prior
  TX_DONE, arriving ~600ms later) is never dropped, while the lone
  quiet-window spurious host-wake (the -110 trigger) is still skipped.

Instrumentation (WIP, to remove): GPIOIRQ# in the OOB IRQ thread; TX_DONE
promoted to dev_info; RXCH log in rx_frame; bss_info_changed dev_info.

FINDING: our auth frame's TX_DONE reports status=1 (TX_DONE_STAT_RETRY_LIM,
retries=14) — NOT ACKed. So the AP never hears our auth (or we never hear
its ACK). Unified root cause: RF RECEIVE is dead on the fixed operating
channel AFTER a scan (bring-up on a fresh channel receives fine; a
post-scan RPU_CMD_CHANNEL fires CH_PROG_DONE but the async RF-arm never
completes), so both the ACK and the auth response are missed. Next: force
a clean scan-mode exit / re-arm RX after the scan before connecting.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 06:44:08 -04:00
Paul KilarandClaude Opus 4.8 34fa536ae3 sdio: fix the -110 wedge (drop speculative TX-RX poll) + reach 802.11 auth
The multi-session -110/-16 DW MMC wedge is eliminated. Root cause: the
tx_rx_poll timer fired sv6160_trigger_rx() every 50ms for 3s after each
TX, forcing a SPECULATIVE rx_drain that read the firmware's never-zeroed
stale RECV_LEN; that CMD53 read of absent data timed out -110 and hard-
wedged the controller. It was a legacy workaround from when GPIO didn't
fire post-init; the deaf-radio gate is open now, so RX is pure-GPIO
(vendor model) and the poll is removed.

With the wedge gone the driver now scans, delivers beacons to cfg80211,
and reaches 802.11 authentication with a real AP (correct channel/MAC/
BSSID/STA_CONN, all verified).

Changes:
- sv6160_sdio.c: revert the 1-bit-SDIO force in device_init; keep the
  core-negotiated 4-bit path (the vendor's 1-bit is a suspend-only path,
  not init). Matches vendor sdio_device_init exactly.
- core: don't arm tx_rx_poll after TX (the wedge fix); rely on GPIO.
- core: sv6160_sdio_write_tx() writes the cmd_tx_ctrl descriptor and the
  frame body as two back-to-back CMD53s under ONE sdio_claim_host+lock,
  mirroring the vendor hal_send (the chip pairs the descriptor with the
  immediately-following CMD53; a split write let an RX drain slip between
  them and the frame was never transmitted).
- core: configure_filter now uses RCV_ALL_BCNS only for
  FIF_BCN_PRBRESP_PROMISC (scan) and RCV_ALL_NETWORK_ONLY otherwise,
  matching the vendor (was flooding all beacons during association).
- core/sdio: sdio_wedged flag + bring-up retry loop in mac_start and a
  runtime ieee80211_restart_hw recovery (mmc_hw_reset) for any residual
  wedge, matching the vendor rk915_sdio_power_cycle recovery model.

WIP: includes RXCH / bss_info_changed diagnostic logging (to be removed).
Open blocker: after the first auth TX the firmware RX goes silent, so the
AP's auth response is not received; investigating the post-TX host-wake
handshake.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-08 06:09:01 -04:00
Paul KilarandClaude Opus 4.8 7125fb4b19 sdio: fix cmd_reset layout (bgscan size) + set antenna_sel
Comparing the RESET command against the vendor's authoritative
`struct cmd_reset` (host_rpu_if.h) turned up two real correctness bugs:

- The `bg_scan` placeholder was 48 bytes, but `struct bgscan_params` is
  120 bytes (enabled + channel_list[50] + channel_flags[50] + scan_intval
  + channel_dur + serv_channel_dur + num_channels, packed). The undersized
  field shifted everything below it (num_spatial_streams, system_rev,
  lmac_mode, antenna_sel, reserv) by 72 bytes, so the firmware read garbage
  for those fields. Corrected to 120; cmd_channel and cmd_scan were checked
  and already match the vendor.
- antenna_sel was left 0; the vendor sends params->antenna_sel (=1).
  Leaving it 0 selects the wrong antenna. Now set to 1.

These make the RESET command byte-correct against the vendor. They do NOT
by themselves fix the current "deaf receiver" symptom (the firmware still
never raises host-wake for received beacons) — that root cause is deeper
(radio/MAC-enable path) and is under separate firmware-RE investigation.
Also note: the "read eFuse for rf_params" idea is a dead end — the vendor
has no eFuse/VPD read and uses the same built-in default rf_params table
this driver already carries.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-07 17:31:05 -04:00
Paul KilarandClaude Opus 4.8 c7ee2845a1 sdio: stop force-polling channel-command responses -> no more host wedge
This is the change that eliminates the DW MMC host wedge.

sv6160_rpu_channel() used to force-poll for the pretune SCAN_COMPLETE and the
RPU_CMD_CHANNEL CH_PROG_DONE by zeroing the stale guard and kicking the RX
worker in a loop. CH_PROG_DONE is 28 bytes -- the same length as the stale
RECV_LEN the firmware leaves after an RX_SERIAS burst, and it never zeroes
RECV_LEN -- so the force-read could not tell the real response from the stale
value and read the stale one, which finds no DMA and returns -110. A single
-110 hard-wedges the rockchip DW MMC controller (reboot-only recovery), which
then made every following command/data write fail -EBUSY (-16).

The channel is programmed by the command WRITE itself, so the response is
best-effort: send the command and wait for CH_PROG_DONE via the normal
GPIO-driven RX path, then proceed on timeout -- no force-read, no stale read.

Result on hardware (stock fw, serial): interface-up plus three back-to-back
full scans run with ZERO -110 and ZERO -16, IRQ 69 steady (no storm), driver
stays loaded and wlan up. The bus no longer wedges. (Scan still returns no
BSS -- beacon RX delivery during the sweep is the next problem, tracked
separately -- but the SDIO layer is finally stable.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-07 14:37:33 -04:00
Paul KilarandClaude Opus 4.8 49e2ba1ac7 sdio: serialize CMD53 writes vs RX; stop poll timers zeroing the guard
Two vendor-aligned hardening changes on top of the stale-guard fix:

- serialize command/TX CMD53 writes against the RX drain under sc->lock
  (previously init'd but unused), so a write cannot collide with an
  rx_worker read on the bus. write_data() skips the lock when reached from
  within rx_worker (process_event -> send_cmd) to avoid recursion.
- sv6160_tx_rx_poll_fn and sv6160_scan_poll_fn no longer reset
  last_recv_len=0. Like the GPIO handler and the old scan_poll, zeroing the
  guard from a periodic poll lets a stale (never-zeroed) RECV_LEN pass and
  the CMD53 read of stale data is a -110 that wedges the host.

Effect on hardware: IRQ-69 storm down further (181k earlier -> ~2.3k), and
the boot RX_SERIAS burst plus most stale re-reads are handled cleanly.

Not fixed: a single stale 28-byte read still slips through at interface-up
and wedges the DW MMC host. Root cause is now pinned precisely: a channel
command's response (CH_PROG_DONE) is 28 bytes -- the SAME length as the
stale RECV_LEN the firmware leaves after the RX_SERIAS burst -- and command
responses are NOT signalled by GPIO (must be polled). So rpu_channel's poll
loop has to zero the guard to read the 28-byte response, which also lets the
identically-sized stale value through; that read finds no DMA -> -110 -> and
on this rockchip host a single -110 hard-wedges the controller (only a
reboot recovers). The stale value and the real response are indistinguishable
by length, so the guard cannot separate them. Closing this needs a deeper
change: make clear+notify actually zero RECV_LEN, get responses GPIO-
signalled, or stop a -110 from wedging the host. See driver-state memory.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-07 14:32:10 -04:00
Paul KilarandClaude Opus 4.8 83c266463e sdio: make the stale-RECV_LEN guard survive level-IRQ re-fires
The host-wake line is LEVEL-triggered and the firmware never zeroes
RECV_LEN (firmware README §6), so after a drain the line re-asserts on the
SAME stale length. Two bugs let a stale read slip through and issue a CMD53
read of non-existent data — the -110 that hard-wedges the rockchip DW MMC
host (unrecoverable without a reboot):

- the GPIO handler reset last_recv_len=0 on every re-fire, defeating the
  stale guard; stop doing that (command-response wait loops still clear it
  explicitly when they expect a fresh reply).
- nothing recorded the post-drain stale length; clear_and_done now reads
  RECV_LEN back and records it into last_recv_len (ignoring transient
  0/0xFFFF), so the immediate re-fire is blocked by the guard and only a
  genuinely new event (different RECV_LEN) passes.

Measured on hardware (stock fw, over serial): the stale guard now blocks
the re-reads, -110 drops from a storm to a single occurrence, and the
level-IRQ storm drops ~35x (181k -> 5.2k on IRQ 69). Not fully fixed yet:
one stale read still slips through before last_recv_len is recorded and
wedges the bus; and the residual storm wants a mask-and-delayed-poll break.
Investigation notes for both are in the driver-state memory.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-07 14:17:32 -04:00
Paul KilarandClaude Opus 4.8 d282aa3f26 sdio: vendor-align RX/TX fault handling + warm-start boot fix
Hardware-tested on the Gusgu H7 (RK3326/PX30) over the serial console.
Brings the SDIO transaction handling closer to the working vendor rk915
driver and fixes several real bugs, though the core RX-drain wedge (see
below) still needs a structural rewrite.

Fixed / improved:
- sv6160_probe: mmc_hw_reset(func->card) before firmware upload. On a warm
  start (driver reload, or a prior driver leaving the MCU running) the first
  upload CMD53 to addr 0 timed out -110; resetting the MCU to WAIT_FW fixes
  it. Proven: firmware uploads, reaches M0_READY, wlan0 registers.
- hw_scan: keep the GPIO IRQ enabled during scan and drop the scan_poll
  force-reads, which raced the firmware DATA_AVAIL/DMA setup (firmware
  README §6) and stormed -110. Add scan_mode param (0=channel-sweep default,
  1=RPU_CMD_SCAN); the firmware buffers scan beacons and only flushes them
  via a channel command, so the sweep is the DMA-safe path.
- rpu_channel: reset last_recv_len each poll iteration in the pretune-drain
  and CH_PROG_DONE command-response loops, so a same-length response is not
  blocked by the never-zeroed RECV_LEN. Fixes ip-link-up timing out and the
  sweep stalling.
- rx/tx SDIO faults, matching the vendor: no longer poke the DW MMC host
  controller (sv6160_dwmmc_fifo_reset is now a no-op) — that raw
  FIFO/DMA-reset behind the MMC core's back is what escalated a transient
  -110 into a permanent host wedge. Retry the CMD53 read and write 3x on
  -110/-EBUSY instead, and drop the frame on a persistent fault.
- rx drain: stop re-writing INT_GEN(reg34)/INT_ENABLE(reg33) on every drain
  (they are one-time init enables in the vendor).
- rx_frame: correct the DELIVER printk format/args.
- firmware/README.md §7: fix the RF-PLL patch offsets (0x782/0x7AFA, were
  0x20 low) and record that the §7 patches are not applied in the committed
  fw. Add gen_fw_patch.py to apply them reproducibly.

Known remaining (root-caused, needs a follow-up RX-path rewrite): one stale
CMD53 read still hard-wedges the rockchip DW MMC host. After the initial
RX_SERIAS burst the firmware leaves a stale RECV_LEN and the level host-wake
GPIO asserted; the worker issues one speculative read of stale data -> -110
-> every later write -16 until reboot. The vendor avoids this by masking the
host-wake IRQ until the GPIO line deasserts and draining bursts by pkt_count
bookkeeping instead of re-reading RECV_LEN.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012N7oe7HZVU4Fb4FtpBLDgk
2026-09-07 13:17:57 -04:00
Joel Wirāmu Pauling 3160b3242f Merge pull request 'vendor-driver-findings' (#1) from pkilar/sv6160-rk915:vendor-driver-findings into main
Reviewed-on: https://codeberg.org/aenertia/sv6160-rk915/pulls/1
2026-09-05 23:27:41 +02:00
pkilar 6746a293a6 wifi: sv6160: don't clear+notify on an all-ones (busy) RECV_LEN
The RX worker reads RECV_LEN with two CMD52 byte reads. When the card is
internally busy it drives the bus high, so the read can succeed (ret == 0)
yet return 0xFF in each byte, giving pkt_len == 0xFFFF. Today that falls
through to the "RX oversized" branch and clear_and_done, which writes
clear+notify (and regs 33/34) onto a bus the card is not servicing. That
is the hammering the driver's own comments warn about — it is what turns a
transient stall into the permanent -110 that kills the DW MMC bus.

0xFFFF can never be a real length (> SV6160_MAX_RX_SIZE = 4096), so this
only diverts an already-invalid value: recognise it as "SDIO busy", back
off without touching the bus, consume the GPIO, and let the next assertion
retry. Deliberately does not update last_recv_len, so 0xFFFF cannot poison
the stale-RECV_LEN guard.

Found by inspection while cross-referencing the vendor-based driver for
this chip, where the same busy condition under sustained RX wedges every
SDIO transaction (-EBUSY) until a power cycle and surfaces as 0xF0F0 (that
driver folds the errno into the length). See VENDOR-DRIVER-FINDINGS.md.
Safe by construction; not runtime-tested here (this driver has not reached
sustained RX yet).
2026-09-05 11:59:11 -04:00
pkilar 267e1e5fec docs: findings from the vendor-based RK915 driver (sustained-RX SDIO wedge)
Adds VENDOR-DRIVER-FINDINGS.md and a README pointer. Contributed from work on
the out-of-tree vendor BSP port of this same chip (same byte-identical
firmware), which reached full association + data and hit walls this clean-room
driver has not yet:

- the throughput ceiling is a chip-side SDIO wedge under sustained RX: every
  transaction returns -EBUSY at once (a failing write plus RECV_LEN plus
  FW_STATE all read -16 together), FW_STATE stays M0_READY (not asleep), it
  clears only on a chip power cycle, and it matches the documented rx_buf_pool
  (15 entries) exhausting - the full form of this repo's Known Issue #3 and the
  last_recv_len bus-kill guard;
- length(61680)/0xF0F0 is that same -EBUSY wedge seen through the two-byte
  RECV_LEN read ((u8)(-16) = 0xF0 twice), not a bad frame length, so the byte
  pattern is not diagnostic;
- ruled-out dead ends (LMAC sleep, mac80211 PS, runtime LPW clock-gating write,
  host-side retries) so they need not be re-tried;
- reciprocal credit: this driver's "poll the RX worker during reset" idea fixed
  the vendor driver's intermittent boot race.

Documentation only.
2026-09-04 22:40:11 -04:00
Joel Wirāmu PaulingandClaude Opus 4.6 5c4a018cef wifi: sv6160: fix cancel_work_sync deadlock in RX path — SCAN WORKS!
sv6160_mark_active() is called from sv6160_rpu_rx_frame() which runs
inside the rx_work workqueue callback.  mark_active() calls
sv6160_rpu_ps_config() which calls rpu_send_cmd() which calls
cancel_work_sync(&sc->rx_work) — DEADLOCK: the work is trying to
cancel itself.

Fix: skip cancel_work_sync when called from within rx_work context
using current_work() check.

With this fix, WiFi scan results are delivered to mac80211 and
appear in 'iw dev wlan0 scan dump'.  First successful scan on
XF40H hardware with the SV6160 chip:

  BSS 94:83:c4:a8:6e:9b(on wlan0)
      freq: 2412.0
      signal: -22.00 dBm
      SSID: kainga-atawhai

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 22:10:28 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 d9a94fc286 wifi: sv6160: scan GPIO disable + rx debug + remove false decrypt flag
1. Disable GPIO IRQ during scan to prevent USB instability from
   original firmware's GPIO bit 19 clearing during scan_stop.
   Re-enable GPIO + clear state after scan complete/abort/timeout.

2. Remove incorrect RX_FLAG_DECRYPTED on unencrypted beacon frames.
   mic_status=0 doesn't mean "decrypted" for open beacons.

3. Add step-by-step rx_frame debug logging to trace where frame
   delivery to mac80211 fails. Current finding: function hangs
   between IE trim and ieee80211_rx_irqsafe call — investigating.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 21:49:47 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 c784f08e38 wifi: sv6160: disable GPIO IRQ during scan to prevent USB instability
The original (unpatched) firmware clears GPIO bit 19 during scan_stop
channel transitions.  With the level-triggered GPIO IRQ handler, this
causes the same rapid fire/disable/re-enable cycle that was fixed at
boot time in the previous commit — but now happening during scan.

Fix: disable GPIO IRQ at scan start, use scan_poll timer for RX
during scan.  Re-enable GPIO IRQ (with clear+notify to deassert
the line) after scan completes, aborts, or times out.

Also includes rx_frame debug logging for tracking frame delivery
to mac80211.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 20:33:13 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 4b8579a3c7 wifi: sv6160: fix GPIO boot race that destabilizes USB gadget
Move the boot GPIO clear+notify sequence BEFORE enable_irq() to
prevent a rapid IRQ fire/disable/re-enable cycle.

The SV6160 firmware asserts GPIO during power-on.  With the GPIO
level-triggered IRQ handler, enabling IRQ while GPIO is HIGH causes
immediate firing.  The handler disables the IRQ and schedules
rx_work.  When rx_work completes and re-enables the IRQ, GPIO may
still be HIGH, causing another immediate fire.  This rapid cycle
starves USB interrupt processing, destabilizing the USB gadget
network (udhcpd/link-local) used for device access.

Fix: clear GPIO state via SDIO clear+notify (which makes the
firmware deassert the GPIO line), wait 2ms for deassert, THEN
enable the level-triggered IRQ.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 20:27:21 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 51517ae10b wifi: sv6160: revert to original firmware + gamely-aligned init
CRITICAL FINDING: firmware patches (GPIO persistence + PLL NOPs)
cause "rpu hang without ready" during scan.  The original unpatched
firmware does NOT produce this error and successfully receives WiFi
frames (RPU_EVENT_RX id=0, 452-byte beacon).

Test results:
- Original FW: scan works, receives 1 beacon (452 bytes), BUT
  crashes after scan due to GPIO/PLL clearing (bus wedge)
- Patched FW (all 3 patches): "rpu hang without ready" error,
  no WiFi frames received
- GPIO-only patch: same "rpu hang" — the GPIO bit 19 NOP
  prevents firmware from managing WiFi MAC state during scan

The GPIO persistence patch (NOP at 0x08AE) is the cause — it
keeps bit 19 of 0x4009000C always set, but the firmware needs
to toggle this bit during scan channel transitions.

Next step: find a firmware patch that preserves GPIO notifications
without blocking MAC state transitions, OR handle GPIO loss in
the driver (re-enable GPIO after scan_stop, use polling fallback).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 19:53:53 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 699cc6942d wifi: sv6160: align init with gamely BSP + rf_params + wakeup notify
Major alignment with gamely-code/rk915 BSP based on full source analysis:

1. FW_PRIV_INIT simplified to gamely-only: just type=6 with MAC byte.
   Removed sub_cmd=3 (was DUMP_REG_INFO, not SET_PHY_PARAMS!),
   sub_cmd=6 (duplicate FW_PRIV_INIT), and sub_cmd=8 (FW_SET_PARAMS,
   production-mode only). The fw_priv_cmd.type enum:
   1=DUMP_TXRX_COUNT, 3=DUMP_REG, 6=FW_PRIV_INIT, 8=FW_SET_PARAMS.

2. MAC addr fields reverted to single bytes (gamely fw_priv_cmd.
   wlan_mac_addr and p2p_mac_addr are both u8, not u8[6]).

3. rf_params[369] filled with 0xFF before overlay (gamely does
   memset(0xFF) then conv_str_to_byte from rk915_rf_para.txt).

4. Added wakeup notify (reg 17 = IO_NOTIFY_WAKEUP=3) before reset —
   gamely calls rk915_notify_pm(1) before rpu_prog_reset.

5. Initial channel programming (ch1) after VIF add — gamely calls
   rpu_prog_channel right after rpu_prog_vif_ctrl.

Remaining issue: firmware reports "[NNNN F] rpu hang without ready"
during scan processing. The RPU watchdog detects the scan state
machine never reaches "ready". Needs deeper firmware RE of the
readiness flag mechanism.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 19:15:21 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 d40fc593e4 wifi: sv6160: add FW_ERROR hex dump + RX_SERIAS batch debug logging
Add hex dump to RPU_EVENT_FW_ERROR handler to decode firmware error
messages.  Add per-sub-packet logging to RX_SERIAS batch parser.

Testing reveals: firmware reports "rpu hang without ready" (from
firmware string at 0x020047F8) during scan.  The RPU doesn't reach
ready state after scan command — likely needs additional PHY/RF
configuration that SET_PHY_PARAMS (sent empty) should provide.

The batch parser correctly extracts 11 sub-packets from a 476-byte
RX_SERIAS event: 8x COMMAND_PROC_DONE, 1x ROC_STATUS, 1x
CH_PROG_DONE, and 1x FW_ERROR with the "rpu hang" message.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 18:58:03 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 342119de04 wifi: sv6160: fix stale RECV_LEN guard and GPIO IRQ interaction
Major rework of the stale RECV_LEN protection to work correctly with
GPIO level-triggered interrupts (CCCR 0x16=0x80 GPIO mode).

Key changes:

1. trigger_rx() no longer resets last_recv_len — init polling must
   not bypass the stale guard, as stale CMD53 reads permanently
   kill the DW MMC bus.

2. GPIO IRQ handler resets last_recv_len=0 on each edge — safe
   because the handler disables the IRQ (disable_irq_nosync) on
   entry, preventing re-fire until rx_worker explicitly re-enables.

3. SDIO in-band IRQ handler no longer resets last_recv_len.

4. Post-clear RECV_LEN readback removed — the firmware briefly
   returns 0 then snaps back to stale value, causing last_recv_len=0
   which defeats the stale guard on the next poll.

5. rpu_send_cmd() no longer resets last_recv_len — GPIO is the sole
   authority for "new data available" (gamely semaphore model).

6. cancel_work_sync(&rx_work) added to rpu_send_cmd() to prevent
   concurrent rx_worker CMD53 reads colliding with CMD53 writes.

7. Scan poll and TX-RX poll reset last_recv_len=0 before triggering
   — post-init, firmware TX path is enabled so RECV_LEN is genuine.

Result: Full init sequence completes without -110 errors.  Firmware
NOP data path verified.  Scan commands accepted and RX_SERIAS events
(aggregated WiFi frames) received from the radio.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 18:53:32 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 12c112d4ab wifi: sv6160: fix stale guard bypass in trigger_rx polling
sv6160_trigger_rx() was resetting recv_len_failed=false on every
call, defeating the stale RECV_LEN guard during init polling loops.
This caused repeated CMD53 reads on stale RECV_LEN=60 after
RESET_COMPLETE, resulting in -110 timeout that permanently poisons
the DW MMC bus.

Only the GPIO IRQ handler should reset the stale guard — a real
GPIO edge means the firmware has genuinely new data.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 18:31:36 +13:00
Joel Wirāmu PaulingandClaude Opus 4.6 17c2d5d43e wifi: sv6160: restore CCCR 0x16 GPIO mode + fix FW_PRIV_INIT MAC addr
Restore CCCR register 0x16=0x80 write before firmware boot to switch
the chip to GPIO interrupt mode.  The gamely BSP (working vendor
driver) requires this — without it, the firmware signals RX frame
availability via SDIO DATA1 in-band interrupts which may not cover
WiFi RX ISR events (beacons/probes), only command responses.

The previous removal was speculative based on observing GPIO IRQ
only firing during boot, but that was because the firmware was never
put into GPIO mode in the first place.

Also fix the FW_PRIV_INIT type=6 struct to use full 6-byte MAC
addresses for wlan_mac_addr and p2p_mac_addr instead of single bytes.
The firmware may use these for frame filtering — with only 1 byte
set, received frames would not match and could be silently discarded.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-09 17:11:40 +13:00
Joel Wirāmu Pauling 9ef430f801 docs: consolidate firmware RE documentation
Rewrite firmware/README.md with current verified findings:

- Fix header size: 256 bytes (0x100), not 32. Vector table at file
  offset 0x100, not 0xE0. r2 -m 0x02000000 maps directly.
- Complete function reference with all RE'd addresses and names
- Document RF PLL bug root cause: RPU_CMD_CHANNEL (fcn.0200154a)
  never writes 0x42000034, only scan handler (fcn.02007954) does
- Document DATA_AVAIL/RECV_LEN race: tx_notify and tx_dma_setup
  are separate functions in different call chains
- Document all three firmware binary patches with exact offsets
- Add GPIO_ENABLE register (0x4009000C bit 19) documentation
- Add key RAM state variables table (0x10005xxx, 0x10006xxx)
- Remove outdated testing logs, investigation diaries, and
  superseded theories (DW MMC bus poisoning, struct layout
  discovery, CCCR timing issues — all resolved)
- Remove duplicate/contradictory sections
- Correct packet type table (RPU_CMD_SCAN=1 vs FW_PKT_TYPE_SCAN=0x16)
2026-03-09 14:14:38 +13:00
Joel Wirāmu Pauling cee684fbf5 wifi: sv6160: PLL pretune scan + GPIO persistence firmware patch
Three firmware binary patches (all verified via radare2 disassembly):

1. GPIO bit 19 persistence (NEW): NOP the and+sw at 0x020008ce that
   clears bit 19 of 0x4009000C when WiFi MAC is disabled. Keeps GPIO
   notifications always enabled, preventing lost RX notifications
   after firmware disables the MAC between commands.

2-3. Scan stop PLL clear NOPs (existing): prevent firmware from
   zeroing RF PLL register 0x42000034 on scan stop/RF disable.

Driver changes:

- sv6160_rpu_channel(): Add RF PLL pre-tuning via single-channel
  passive scan before RPU_CMD_CHANNEL. Firmware RE confirmed that
  RPU_CMD_CHANNEL (fcn.0200154a) sends channel config to the LMAC
  but never writes the RF PLL register at 0x42000034. Only the scan
  handler (fcn.02007954) programs the PLL. The pretune scan uses
  FW_PKT_TYPE_SCAN (0x16) to reach the correct firmware handler.

- Remove broken post-scan PLL retune from SCAN_COMPLETE handler.
  It used RPU_CMD_SCAN (1) instead of FW_PKT_TYPE_SCAN (0x16),
  so it never reached the scan handler. The pretune in
  sv6160_rpu_channel() replaces this with correct per-channel tuning.
2026-03-09 14:00:55 +13:00
Joel Wirāmu Pauling 862f8ed766 wifi: sv6160: -110 graceful recovery instead of permanent bus wedge
On CMD53 read failure (-110):
- Do NOT set recv_len_failed (blocks all future reads permanently)
- Instead set last_recv_len = pkt_len (blocks only this stale size)
- Do clear+notify to reset firmware SDIO state
- Exit gracefully — bus can recover on next different-sized event

Restore last_recv_len=0 in rpu_send_cmd for all commands (not just
init). With -110 recovery, stale reads are no longer permanently fatal.

NOTE: the DW MMC IDMAC still wedges on -110 at the controller level.
The kernel MMC patch (sdio_is_io_busy µs polling + card present init)
is needed for full mitigation.
2026-03-09 09:40:35 +13:00
Joel Wirāmu Pauling 669257b00f wifi: sv6160: init-only last_recv_len reset (still -110 on some boots)
Reset last_recv_len=0 only during init (!is_started), never post-init.
The -110 occurs during init too — it's a fundamental SDIO timing issue:
firmware writes RECV_LEN before DMA source is configured, and the 5ms
delay isn't always sufficient.

The -110 is intermittent — some boots work, some don't. When it hits,
the DW MMC IDMAC wedges permanently (no recovery without reboot).

This is a hardware/firmware timing bug, not a driver logic issue.
2026-03-09 09:12:04 +13:00
Joel Wirāmu Pauling 4ea21fcc98 wifi: sv6160: remove last_recv_len=0 from rpu_send_cmd — zero -110
Removed the post-init last_recv_len=0 reset from rpu_send_cmd.
This eliminates ALL -110 bus wedge errors. However, init command
responses may be blocked by the stale guard when consecutive
events have the same size.

Trade-off identified:
- WITH reset: -110 on stale reads → bus wedge (fatal)
- WITHOUT reset: same-size events blocked → init incomplete

Next: modify stale guard to ONLY bypass when GPIO fires (which
indicates real data), not based on last_recv_len comparisons.
2026-03-09 09:01:39 +13:00
Joel Wirāmu Pauling 8c3f0ce810 wifi: sv6160: patched firmware — NOP scan stop PLL clear
Binary patch ssv6160-fw.bin: replaced both 'sw zero, 52(a4)'
instructions (scan stop PLL clear at 0x02007ADA and fcn.0200076c
disable at 0x02000762) with NOPs (addi x0, x0, 0).

This prevents the scan stop handler from clearing the RF PLL
register (0x42000034), keeping the radio tuned to the last
scanned channel's frequency after scan completes.

Original firmware backed up as ssv6160-fw.bin.orig.

NOTE: ROCKNIX squashfs is read-only — the patched firmware must
be deployed to /lib/firmware/ via an OTA update or full image
rebuild, not just copied at runtime.
2026-03-09 08:12:22 +13:00
Joel Wirāmu Pauling 7471129b98 wifi: sv6160: remove FW_PRIV_CALIBRATE (generates event 25 = FW_ERROR)
FW_PRIV_CALIBRATE (sub_cmd=12) is not recognized by the HOST_CMD
handler — generates event id=25 which is RPU_EVENT_FW_ERROR. This
causes iwd to restart the interface (mac80211 stopped).

Keep the PLL retune scan (1-channel RPU_CMD_SCAN on ch=1) after
scan_complete, guarded by is_started to avoid init interference.
The scan stop handler still resets PLL, but at least the firmware
internal PLL state is updated for the right channel.
2026-03-09 07:22:57 +13:00
Joel Wirāmu Pauling b23f158af7 wifi: sv6160: PLL retune at scan_complete (ch=1 fallback)
Send 1-channel RPU_CMD_SCAN on ch=1 after scan_complete to retune
RF PLL. Guard against infinite loop: only retune when scan_request
was set (main scan), not for our own retune scans.

Issue: scan stop handler (fcn.02007ade) writes 0x42000034=0 after
EVERY scan, including our retune scan. PLL is reset immediately.
The retune is ineffective because the PLL value doesn't persist.

GPIO fires 34+ times post-init (working). TX_DONE (EVENT 1) was
seen on clean boots. Auth times out due to PLL being on wrong
frequency or being reset by scan stop.
2026-03-09 07:13:09 +13:00
Joel Wirāmu Pauling 4ad2f3923a wifi: sv6160: clean base (0d1364a) + PLL retune after scan
Reverted to clean 0d1364a base (working init, GPIO fires, no
bus wedge). Added PLL retune: 1-channel RPU_CMD_SCAN after
scan_complete to re-tune RF PLL to auth channel.

Status:
- Init works (no -110 init failures)
- GPIO fires post-init (34+ interrupts)
- TX frames sent (EVENT 1 TX_DONE seen on some boots)
- PLL retune needs verification (chandef.chan may be NULL)
- Auth still times out (RETRY_LIMIT on most attempts)
2026-03-09 06:59:49 +13:00
Joel Wirāmu Pauling 023c9c448c wifi: sv6160: revert to original stale guard + 15ms DMA delay
INT_STA (reg 35) is always 0 — not usable as DMA readiness indicator.
Reverted to original pkt_len == last_recv_len stale guard with
last_recv_len=0 reset in rpu_send_cmd (needed for command responses).

Increased DMA delay from 5ms to 15ms — doesn't prevent -110 on
genuinely stale data (firmware hasn't set up DMA at all, not just
slow to set it up). The -110 still occurs and wedges the bus.

The stale guard architecture needs a fundamentally different approach:
- GPIO-driven reads (gamely BSP model) instead of polling
- Or: never read same-size consecutive events (accept the trade-off)
2026-03-09 06:34:56 +13:00
Joel Wirāmu Pauling b23d706b5f wifi: sv6160: INT_STA stale guard bypass + remove NOP from TX
Try INT_STA (reg 35) as secondary new-data indicator when RECV_LEN
matches last_recv_len. Remove NOP from TX path (causes -110 via
its own rpu_send_cmd last_recv_len=0 reset).

The fundamental issue remains: rpu_send_cmd resets last_recv_len=0
for ALL commands (needed for responses), but this makes the NEXT
rx_worker read stale RECV_LEN → -110 → permanent bus wedge.

Two separate bugs interact:
1. RF PLL not tuned after scan (fixed with retune scan)
2. Stale RECV_LEN -110 kills bus before TX_DONE arrives

Both must be solved for WiFi auth to work.
2026-03-09 06:27:34 +13:00
Joel Wirāmu Pauling dbfc96c9ee wifi: sv6160: PLL retune after scan + NOP-based stale guard
ROOT CAUSE found via firmware RE:
- 0x42000034 is the RF PLL/frequency register, NOT a simple enable
- Scan processing (0x020079C4) writes channel-specific tuning data
- RPU_CMD_CHANNEL NEVER writes 0x42000034 — RF stays on last scan freq
- After 13-ch scan, PLL is on ch=13 but auth expects ch=1

Fixes attempted:
- PLL retune: 1-channel RPU_CMD_SCAN after scan_complete to re-tune
  PLL to auth channel (with loop guard)
- NOP after TX to safely reset stale guard via rpu_send_cmd
- Removed dangerous last_recv_len=0 from tx_worker and tx_rx_poll

Remaining issue: stale RECV_LEN -110 still causes bus wedge.
Any last_recv_len=0 reset in a polling context reads stale data.
Need a fundamentally different approach to the stale guard.
2026-03-09 06:18:26 +13:00
Joel Wirāmu Pauling 0d1364aeb9 wifi: sv6160: clean up debug logging for production
- Demote verbose TX_DONE, bss_info_changed, channel, FW_PRIV
  logging from dev_info to dev_dbg
- Move tx_frame hex dump to print_hex_dump_debug
- Remove unused sv6160_fw_reg_access (DUMP_REG_INFO doesn't
  work — firmware generates CALIBRATION_DONE instead)
- Remove unused variable in mac_config
2026-03-09 05:05:54 +13:00
Joel Wirāmu Pauling a70f17b0ed wifi: sv6160: LMAC_DO_CALIB in lmac_mode, comprehensive RF RE
Key firmware RE findings:
- RF enable (0x42000034=1) ONLY written at ONE location: 0x02007AB0
  (tier-1 scan handler). NEVER during boot or LMAC channel handler.
- fcn.0200076c (RF enable/disable function) exists but is NEVER called
- Tier-1 scan handler (id=0x16) enables RF but scan stop disables it
- RPU_CMD_SCAN (id=1) goes through tier-2 LMAC, NOT tier-1 scan handler
- RPU_CMD_CHANNEL (id=23) goes through extended LMAC at fcn.020010d8
  which calls fcn.020005e6 → fcn.0200154a but NEVER fcn.0200076c
- DUMP_REG_INFO (sub_cmd=0x70616E63) generates CALIBRATION_DONE event
  but does NOT actually read/write registers
- gamely BSP sets LMAC_DO_CALIB in BOTH type AND lmac_mode fields

Reverted tier-1 scan trigger (breaks radio by disabling RF + GPIO).
Added LMAC_DO_CALIB to lmac_mode to match gamely BSP.
Still RETRY_LIMIT — RF monitoring required to determine root cause.
2026-03-09 04:55:30 +13:00
Joel Wirāmu Pauling fc691b7dd2 wifi: sv6160: RF register analysis, double channel send attempt
Firmware RE findings:
- Scan START: writes 0x42000030=0x40021280, 0x42000034=1 (RF enable)
- Scan STOP (fcn.02007ade): writes 0x42000034=0 (RF DISABLE)
- LMAC channel handler (fcn.020010d8) calls fcn.02000898(1) (RF enable)
  then fcn.020006fc (WiFi MAC config) — RF SHOULD be configured
- Scan stop also clears 0x4009000C bit 19 (GPIO notifications)

Added sv6160_fw_reg_access() for firmware register read/write via
DUMP_REG_INFO FW_PRIV_CMD (gamely BSP pattern).

Tried: double RPU_CMD_CHANNEL with 200ms delay — still RETRY_LIMIT.
The LMAC handler configures RF but something re-disables it.

RF monitoring confirmed: no frames on air despite TX_DONE firing.
Root cause remains at RF/PHY hardware level.
2026-03-09 04:35:49 +13:00
Joel Wirāmu Pauling 30dd93b9d0 wifi: sv6160: match gamely BSP rate/header params, two-write TX
Set rate parameters matching gamely BSP defaults for mgmt frames:
- num_rates=1, rate[0]=2 (1Mbps), rate_retries[0]=5
- rate_preamble_type[0]=1 (long preamble)
- num_spatial_streams[0]=1
- Copy MAC header into config_mac_header (gamely always does this)
- Copy seq_ctrl into per_pkt_crypto_params

Use two separate SDIO writes (gamely default non-SG path):
1. 512-byte cmd_tx_ctrl header
2. Raw 802.11 frame data

TX_DONE: status=1 RETRY_LIMIT, retries=14, rate=2 (1Mbps)
Firmware transmits at correct rate but AP never ACKs.
RF monitoring needed to verify frames reach the air.
2026-03-09 03:23:27 +13:00
Joel Wirāmu Pauling 7f5e378c54 wifi: sv6160: combined SDIO write for TX, investigate RETRY_LIMIT
Send cmd_tx_ctrl header + frame data in a single SDIO write
(matching gamely BSP's scatter-gather approach). Also tried
config_mac_hdr_len=0 to prevent header duplication.

Current status:
- TX protocol correct: EVENT 1 (RPU_EVENT_TX_DONE) fires
- Frame content verified correct via hex dump
- Status = 1 (RETRY_LIMIT), retries = 9, rate = 0 (auto)
- Both APs on ch=1 and ch=3, both auth types (SAE/Open) fail
- Channel programming fixed (200ms, was 6.3s)
- AP never ACKs — radio/RF level issue

Possible causes:
- Firmware not transmitting on correct RF frequency
- TX power misconfigured
- PHY/baseband parameters wrong
- Hardware TX path needs RF monitoring to verify
2026-03-09 02:48:46 +13:00
Joel Wirāmu Pauling 9938c51caa wifi: sv6160: fix channel programming stale guard + revert 32-byte align
Channel programming now completes in ~200ms (was 6.3s) by resetting
last_recv_len on each poll iteration. Previously, the stale guard
blocked CH_PROG_DONE (28 bytes, same as other events) indefinitely,
causing auth frames to go out on the wrong channel.

Revert 32-byte frame alignment — broke TX_DONE event generation.
Keep 4-byte alignment which produces correct event 1 (air TX
confirmed, but AP doesn't ACK — status=1 RETRY_LIMIT).
2026-03-09 02:29:59 +13:00
Joel Wirāmu Pauling 7979bd03bf wifi: sv6160: implement correct TX protocol from gamely BSP
ROOT CAUSE: the HOST_DATA (0x2C) path only generates event 32 (SDIO ack)
and does NOT transmit frames over the air. Confirmed via radare2 RE of
the firmware's HOST_DATA handler at fcn.02002b98.

The correct TX protocol from the gamely BSP (gamely-code/rk915) uses:
1. 512-byte cmd_tx_ctrl header (hdr.id = RPU_CMD_TX = 7) with frame
   metadata: num_frames_per_desc, pkt_length[], config_mac_header[],
   rate control, encryption settings
2. Raw 802.11 frame data written separately to SDIO addr 0

This produces EVENT 1 (RPU_EVENT_TX_DONE) — actual air TX completion
with per-frame status, retries, and rate info. Previously we only got
EVENT 32 (SDIO processing ack, no air TX).

Changes:
- New cmd_tx_ctrl struct matching gamely BSP layout (512 bytes)
- TX worker sends two SDIO writes: control header + frame data
- mac_tx simplified: raw 802.11 frame queued, no prepended header
- Beacon TX migrated to use same tx_queue/tx_worker path
2026-03-09 02:18:00 +13:00
Joel Wirāmu Pauling f1e6a186cd wifi: sv6160: RE confirms HOST_DATA is NOT radio TX path
Firmware RE of HOST_DATA handler (fcn.02002b98) via radare2:
- Allocates buffer from pool 3 (fcn.02002b4a → fcn.02002d48)
- Fills rpu_msg_hdr with id=32 (HOST_DATA_TX_DONE)
- Enqueues event 32 to SDIO output queue (fcn.020021cc)
- Returns — NO code path to radio TX queue

Full dispatcher flow for pkt_type=0x2C confirmed:
1. First dispatch: id=44 != 7 → tier-2 LMAC (fcn.02001bce)
2. Tier-2 LMAC: id=44 not in {7,15,4,24} → returns immediately
3. Second dispatch: id=44 == 44 → event 32 acknowledgment
4. Frame data is never referenced for radio TX

Reverted dual-offset config_bitmap (corrupted firmware state)
and PKT_INFO order change (no effect on TX behavior).

The actual WiFi TX mechanism in the gamely BSP remains unknown.
2026-03-09 02:04:50 +13:00
Joel Wirāmu Pauling d8b6c7e950 wifi: sv6160: document TX path investigation — no air TX confirmed
Tested all firmware pkt_type paths for management frame TX:
- 0x2C (HOST_DATA): event 32 fires but no air TX (no auth response
  from ANY AP, tested WPA2-PSK Open System + WPA3-SAE)
- 0x17 (MGMT): falls to tier-2 LMAC as RPU_CMD_CHANNEL, CH_PROG_DONE
  (SET_CONFIG config_bitmap at both +0x20 and +0x38 doesn't set the
  MGMT fast-path flag at 0x100064E8)
- 0x07 (RPU_CMD_TX): hits KEEPALIVE tier-1 handler

Event 32 = SDIO processing complete, NOT air TX complete.
Event 1 (RPU_EVENT_TX_DONE, actual air TX) never fires.

Also includes:
- Pre-auth STA_CONN with BSSID (firmware RX filter)
- Dual-offset SET_CONFIG config_bitmap attempt
- Channel and bss_info_changed diagnostic logging
2026-03-09 01:38:55 +13:00
22 changed files with 8313 additions and 1756 deletions

No files matched your search

+4
View File
@@ -8,6 +8,10 @@ Module.symvers
.tmp_versions/
*.bin
!firmware/*.bin
# ...except the patched variants, which gen_fw_patch.py reproduces from
# the tracked ssv6160-fw.bin.orig (it verifies the bytes it rewrites).
firmware/ssv6160-fw-patched.bin
firmware/ssv6160-fw-p3only.bin
repomix-output.xml
patchrk915.py
outstanding-issues.md
+372
View File
@@ -0,0 +1,372 @@
# Known issues
Open bugs in this driver, with the evidence gathered so far and — just as
importantly — what has already been ruled out, so nobody re-runs a dead
hypothesis. Everything here is measured on hardware (Gusgu H7, RK3326/PX30,
kernel 6.18.45).
Closed issues are not listed; they live in the code comments next to the thing
they explain, which is where someone reading that code will actually find them.
---
## 1. The wedge-prone mode (open, mitigated)
**Symptom.** The device intermittently enters a state in which TX wedges
repeatedly, then leaves it again. In the state, each wedge looks like one of
the two failures below. Outside it, the driver runs for hours without a single
event.
**It is a mode, not bad luck.** From an 8 h soak (2180 cycles, rotating
device-TX / device-RX / bidirectional load):
| | |
|---|---|
| wedges | 55 |
| span containing all 55 | **36 minutes** of a 480-minute run |
| expected span if uniformly random | ~463 minutes |
| inter-wedge gaps | median **28 s**; 48 of 54 under a minute |
| rest of the run | 7+ hours, zero wedges |
A median gap of 28 s is roughly every other cycle. So the device does not
suffer independent random failures — it switches into a regime where it fails
near-periodically for about half an hour, then switches out.
**Impact, with the recovery ladder in place.** Each event now costs roughly a
10-second outage instead of a dead radio. In that soak all 55 self-recovered
with no intervention (50 of them in 10–11 s). Before the ladder, every one of
them would have required an `unbind`/`bind` typed in over the serial console.
So this is mitigated, not fixed: 55 brief dropouts inside half an hour is still
user-visible.
### What has been ruled out
Each of these was tested with real sample sizes, not a single trial — this
driver has bursty base rates and a single-trial A/B on it is worthless.
| hypothesis | evidence against |
|---|---|
| `tx_batch` size | ~1173 transfers at the maximum, zero wedges |
| degraded SDIO write regime | 607+ transfers in the slow regime, zero wedges; and marginal probes pass in *both* regimes |
| module reload churn | 12 reload rounds, 78 transfers, zero wedges |
| concurrent TX+RX | 60 cycles of sustained bidirectional load, zero wedges |
| suspend while the driver is unloaded | reboot + repeated auto-suspends, then 0/6 and 0/6 at two batch sizes |
| **a wedge leaves residue that makes the next likelier** | `tx_batch=9` (last working value, so maximally marginal) used as a susceptibility probe, arms alternating: baseline **0/48** failures vs immediately-after-an-induced-wedge **0/48**. Eight wedges induced, each self-recovered, probe clean every time |
That last one matters most: the mode is **not self-sustaining**. Whatever
drives it is external to the wedge itself.
### Scope limit on the reproducer — read this before using it
`tx_batch>9` wedges the device on demand and is genuinely useful: it is how the
recovery ladder below was measured. But it reproduces the **fallout**
(descriptors never completed, bus wedge, escalation) and **not the mode**. An
induced wedge is a protocol violation — asking the firmware for more frames per
descriptor than it honours. The natural burst is something else and cannot
currently be summoned.
Do not conclude from "I induced a wedge and X happened" that X explains the
natural bursts.
### Instrumentation waiting for the next natural burst
`dmesg` does not survive a reboot and this board has no ramoops
(`CONFIG_PSTORE_RAM=y` but no reserved-memory region), so state is recorded to
persistent storage instead:
- `/storage/flightrec.sh` → appends to `/storage/flight.log` every 60 s:
uptime, battery %, AC online, signal, **SoC temperature**, and the descriptor
counters (`tx_frames`, `tx_done_events`, `tx_resyncs`) plus escalation counts.
- `/storage/.config/system.d/sv6160-boot.service` (enabled) loads this driver at
boot and stamps `=== BOOT <date> ===` into the same log.
The open question that log is meant to answer: **what is different during the
36 minutes?** Temperature and battery are the two obvious candidates that have
never been measured *during* a burst — the soak's health lines only printed on
non-wedge cycles, so there is no throughput or environment data from inside the
one burst that has been captured.
---
## 2. Two distinct failures underneath it — do not conflate them
These share the mode above but have different signatures, different triggers
and different fixes. Conflating them cost a full day of investigation.
### 2a. TX-completion link death
Descriptors are sent and never completed. The interface stays associated and
keeps its IP, so it looks healthy from userspace while passing nothing.
- `tx_frames` climbs away from `tx_done_events`
- `tx_resyncs` climbs
- `token_bmp` shows descriptors held
- **no** SDIO bus errors
Handled by `tx_resync_giveup` (default 3): three fruitless resyncs restart the
hw. Verified on a live instance — 71 lost descriptors and 40+ resyncs, ssh dead;
after the restart, ssh returned and the sent-vs-completed gap stayed at exactly
77 across the next 971 frames, i.e. every new descriptor completed.
### 2b. Hard SDIO bus wedge
The bus itself stops responding.
- `TX write failed: -16`
- `dwmmc_rockchip ff380000.mmc: Busy; trying anyway`
- `mmc_host mmc2: Timeout sending command`
- then every probe failing `-16` with no netdev
Handled by `host_rebind` (default 3): three bus recoveries inside 60 s means
`restart_hw` cannot fix it, so the driver asks the driver core to re-bind the
dw_mmc platform device, re-creating the host.
**Only re-creating the host clears this.** Measured on a real wedge:
| attempted | result |
|---|---|
| `ieee80211_restart_hw` | no effect on a hard wedge; on a softer one it made things *worse* (4→8 resyncs, 6→13 lost) — explained 2026-09-18: mac80211 re-enters `.start` without `.stop`, so the TX worker and resync kept writing to SDIO address 0 during the firmware re-upload; `mac_start` now quiesces first, re-measure |
| `mmc_hw_reset` | returns **success** and does not help — with one function probed it is just `mmc_power_cycle` + `mmc_sdio_reinit_card`, and the bus dutifully renegotiates 400 kHz→50 MHz while staying wedged |
| module reload | probe still fails `-16`, no interface |
| `unbind`/`bind` of `ff380000.mmc` | **clears it, every time** |
Note the recovery cannot be hooked into `probe()`: once the bus is hard-wedged
our probe is never entered at all. `sdio_bus_probe()` calls
`sdio_set_block_size()` before `drv->probe`, that CMD52 fails `-EBUSY`, and the
core logs "probe failed -16" without ever calling us — the failing reloads have
no probe entry line in `dmesg`. The driver can only rescue the host while it
still *holds* the device.
Corollary: only a test harness `rmmod`s a wedged driver. Production never does,
which is why this state is far rarer in normal use than the investigation made
it look.
---
## 3. Unexplained device reboot (open, low information)
The device rebooted once unattended with the battery at ~52 % and the charger
reporting online. No crash record survives — see the ramoops note above — and
`dmesg` had been cleared before the state was inspected, so the cause was not
recoverable. The flight recorder in §1 exists partly to catch the next one:
it records battery, voltage and AC state every minute, so a brownout should be
visible in the run-up.
---
## 4. Throughput below the vendor reference (open, levers largely exhausted)
~1.75–1.9 MB/s TX and ~2.6 MB/s RX, against a 2.5 MB/s vendor BSP reference.
- `tx_batch` ships at 8 (`SV6160_TX_BATCH_MAX`), one below the firmware's real ceiling of 9.
9 is worth ~3 % over 8 but is the last working value; 10 fails 6/6.
- `descs_per_ac` cannot help: the limit is per-descriptor, proven by
`descs_per_ac=1` + `tx_batch=16` (16 frames in flight, fewer than the 18 that
`descs_per_ac=2` + `tx_batch=9` runs happily on) still stalling.
- A-MSDU remains the one real lever and is blocked on the pull-model TX rewrite.
- The 2× SDIO write-speed regime swing is closed as not-host-fixable; see the
comment above `sv6160_tx_xfer_len()` for the full list of what was ruled out.
---
## 5. From the 2026-09-18 review: applied, and still open
Seven review passes over this branch, then a convergence pass over the fixes
themselves. Commits `9de36d7` (driver), `48a253d` (the convergence fixes),
`0e6129f`/`ac57ada` (tools), `f5a42b7`/`92cb227` (docs).
### Applied, and SOAKED (2026-09-19)
An 8-hour soak of `3f0f67e` on the handheld, **472 ifdown/ifup cycles inside a
single module lifetime** — the coverage the old harness structurally could not
provide, because it reloaded the module every trial and the unload freed the
evidence a second later.
| | result |
|---|---|
| cycles | 472 ifdown/ifup, 472 reconnects, **0 failures** |
| TX | 1,089,645 descriptors, completions **exactly 1:1** (final gap 0) |
| per-AC credit leak (`<-- GATED`) | **0 cycles** — final ledger all `busy=0`, `sent==seen==done` |
| wedges (gap persisting across a re-read) | **0** |
| `tx_resyncs` / `tx_ebusy` / `rx_nomem` / `oversize` | **0, no growth over 8 h** |
| recovery ladder | never fired: `tx_resync_giveup` 0, `host_rebind` 0 |
| independent 60 s sampler | 469 samples, TX gap never outside ±2; SoC 45.0–53.3 °C; mains throughout |
That settles the lifecycle and accounting class: `.stop`/`.start` were
re-entered 472 times on a module that stayed loaded, and the per-AC descriptor
credit came back clean every time. Under the old harness this class was
invisible for 8 hours.
**What it does NOT settle.** Do not read "0 wedges" as the wedge mode being
fixed — §1 records that mode as bursty (55 wedges inside 36 minutes of a
480-minute run, with 7+ clean hours either side), so a clean 8 hours is
exactly what the quiet periods look like. It is encouraging, not evidence.
The paired A/B below is still outstanding, and suspend was never exercised:
the soak does not suspend.
(Harness note: `dmesg | grep -c "mac80211 stopped"` reads 21 at the end, not
472 — the kernel ring wrapped and holds only the last ~1,400 s. 21 stops in
that window at ~58 s/cycle is one per cycle, which is the actual evidence.)
### Applied, still needs an ordinary soak for anything not covered above
Lifecycle and accounting bugs an 8-hour soak did not see: `remove()` freed the
softc under a live IRQ thread; `mac_stop`/`mac_flush` stranded
`tx_outstanding_ac[]` and leaked batched skbs; the per-AC counter had no lock;
the resync could free a frame a CMD53 was still reading; `cmd_gate=1`
self-deadlocked the IRQ-thread drain; several firmware-supplied lengths were
used without a lower bound.
Why the soak missed them is worth stating precisely, because the obvious
version is wrong. A `rmmod`/`insmod` recovery *does* run `remove()`, `.stop`
and `.flush` — `rmmod` → `sv6160_remove` → `ieee80211_unregister_hw` →
`ieee80211_remove_interfaces` → `cfg80211_shutdown_all_interfaces` →
`dev_close`, which both disconnects (→ `.flush`) and stops (→ `.stop`) — and
`backtoours.sh` brings the interface back up afterwards. What it never does is
run any of them on a module that then *stays loaded*: a credit or skb stranded
by `.stop` is freed by the unload a second later, so "never returned for the
module's life" leaves no trace, and the `.start` after a reload always meets a
fresh softc. Only three or four of the findings were of that shape; the rest
ran every cycle and survived because the knob that reaches them defaults off
(`cmd_gate`, `wt_trace`), because the firmware never sent the input that trips
them (runt `RX_SERIAS` links, event 32), or because the next unload erased the
damage.
**Add an ifdown/ifup cycle to the harness before the next soak** — that is the
gap, not the absence of `.stop`.
### Applied as experiments, needs a paired A/B
**Still outstanding after the 2026-09-19 soak** — that run exercised only the
new build, with no paired arms, so neither change below has been compared
against anything.
A/B against **`09fd788`**, the immediate pre-review parent. Not `a57846c`: that
is the last *soaked* build, but four commits touch the driver source between
the two (two of them `docs:`-prefixed; only `a7dfd19` changes executable
code), so it
cannot attribute a difference to either change below.
- **The `-EBUSY` back-off now drops `sc->lock`, not just the host claim.**
`write_tx()`/`write_data()` slept up to 16 × 25 ms holding the mutex, and the
RX drain takes that mutex *before* the host claim, so the "let RX interleave"
the comment promised could never happen. The chip may hold DAT0 busy
precisely because it wants its RX buffer collected, in which case the old
code ran the 16 tries out into a declared wedge. **Candidate mechanism for
the wedge mode in §1.**
Caveat found afterwards, and the reason this needs more than a wedge count:
`sc->lock` is the only thing serialising a control-command CMD53 against the
TX descriptor/body pair, and that pair must reach the chip back-to-back
because the firmware matches them by arrival order. A command landing
between a failed descriptor attempt and its retry is a new way to mis-pair a
frame. Measure `tx_ebusy` (debugfs `tx_tokens`) against
frames-never-transmitted, not only against the wedge rate.
- **The host-wake IRQ is no longer `IRQF_NO_SUSPEND`**, and the thread refuses
to drain while `is_suspended`. `IRQF_NO_SUSPEND` is documented as
incompatible with the `enable_irq_wake()` beside it, and the thread was
issuing CMD53s to a host being clock-gated.
Caveat: this changes suspend under RX load rather than simply fixing it. The
thread now refuses to clear a level line that only de-asserts after a drain,
so a host-wake pending at suspend time aborts the suspend, which then retries
after `.resume`. Previously it drained (badly) through. Neither behaviour has
been measured, and wake-on-GPIO through a real suspend has never been
verified either way.
### Behaviour changes worth knowing before the soak
- `.start` on a dead card now blocks for seconds under rtnl and the wiphy lock
instead of returning `-EIO` immediately, because the `is_firmware_loaded`
gate had to go — it was what made an exhausted bring-up permanent until
`rmmod`. Four bring-up attempts, each a full `mmc_hw_reset` plus image and
patch upload, then the host re-create. Expect `ip link set wlan0 up` to hang
a while on a wedged card rather than fail fast.
- `fwpoke`/`fwpoke_when` are mode 0400, so a harness that echoes into
`/sys/module/sv6160/parameters/` now gets `-EACCES`.
- `RXCH: BCN` is `dev_dbg`, so beacon-arrival evidence needs dynamic debug.
- `ieee80211_ready_on_channel()` makes remain-on-channel actually start for the
first time, so off-channel management TX goes live.
- `tx_bulk_done` in debugfs `tx_tokens` counts `RPU_EVENT_HOST_DATA_TX_DONE`
(id 32). If it ever moves, this firmware does emit it — and the handler it
replaced leaked every in-flight token, so that is worth knowing next time TX
dies.
### What the convergence pass caught in the fixes themselves
Three of the thirteen fixes did not do what their own comments claimed, all
caught only by re-reviewing the delta against its stated intent rather than
re-reading the code:
- the probe-window fix ADDED a second `is_firmware_loaded = true` without
removing the one in `boot_firmware`, so it closed nothing;
- the runt-length guard went on the first RX link but not on the chain walk
that re-enters with a firmware-supplied length;
- the pre-restart quiesce left `rx_work`/`rx_poll` running, the path most
likely to be queued when a wedge happens under scan traffic.
Two of the three are the same shape: a guard added to one of two paths reaching
the same code.
### Known, not fixed
Each has a mechanism and no measurement behind it:
- While the firmware uploads, and between `boot_firmware` and `core_init`, the
level host-wake line re-fires the (empty) IRQ thread continuously. The thread
sleeps 1 ms per empty pass, which turns a spin into a ~1 kHz poll; disabling
the IRQ across the upload would remove it.
- Firmware upload chunks (`request_firmware` → vmalloc) and on-stack command
structs go straight to `sdio_memcpy_toio()`, which cannot DMA either; dw_mmc
falls back to PIO silently. Bouncing them through a kmalloc'd buffer (as
`tx_dma` already does for frame bodies) would make the upload DMA and remove
a swiotlb hazard.
- `cmd_gate=1` was unusable until this review — it deadlocked the drain on the
first queued command — so its 300 ms force-retire path has never run. Keep
the default off until it has soak evidence.
- `sv6160_scan_abort_local()` and the drain's SCAN_COMPLETE handler both do an
unsynchronised `if (sc->scan_request) { ieee80211_scan_completed(); NULL; }`,
and `recover_work` runs concurrently with the drain, so both can pass the
test for one scan and trip `WARN_ON(!local->scan_req)`. Narrow and cosmetic,
but it is surface this review added.
- Zeroing `serias_next_len` on a truncated RX_SERIAS batch stops the chain, but
the drain then reads `next == 0` as a clean end and rings the notify
doorbell — telling the firmware we consumed a chain we abandoned, which this
file elsewhere records as its own fatal outcome. `done_no_ack` exists for
exactly that shape. Both outcomes are bad; the choice should be deliberate
and right now it is not.
- `bcn_timer` re-arms itself on `beacon_enabled && vif`, which `timer_delete_sync()`
cannot stop, and nothing clears `beacon_enabled` on the way down. Pre-existing
and shared with `mac_stop`; harmless today only because the TX worker's
`is_rpu_ready` gate catches the frames. AP/IBSS only.
### No outside-model coverage
Both Codex passes died on the provider's usage limit, twice. Every reader of
this branch so far has been some flavour of Claude, including the one that
found three of the fixes inert. Re-run `/codex:adversarial-review` before
upstreaming.
---
## Measurement rules for this driver
Learned the hard way; ignoring them has produced wrong conclusions in this repo
more than once.
- **Never trust a single-trial A/B.** Base rates here are bursty. Two
conclusions in this repo were published and later retracted on this basis.
- **Never A/B throughput across a module reload.** A reload changes both the AP
association and the write regime; the same binary has measured 0.65 and 1.83.
- **Alternate arms every cycle and analyse paired.** Block designs measure the
regime, not the variable.
- **Verify a module parameter actually took effect.** `tx_batch` is clamped by
`min3(mod_tx_batch, SV6160_TX_BATCH_MAX, …)`: it accepts 16, reads back 16,
and runs at 8. Check frames-per-descriptor in debugfs before trusting any
`tx_batch` result.
- **Never infer driver state from a proxy.** Throughput is not wedge state — a
starved link and a dead one look identical by bandwidth. A failed counter read
is not a dead device. An absolute `dmesg` count is not a delta. Each of these
produced a false "wedge detected" during this work; one of them nearly
published the exact opposite of the truth.
- **Keep sampling strides coprime with alternation periods.** A stride that
divides the number of arms hides whole arms of an experiment and the log looks
perfectly healthy while doing it.
+258 -25
View File
@@ -3,7 +3,14 @@
**Repository:** `codeberg.org/aenertia/sv6160-rk915`
**Target Platform:** Rockchip RK3326 (PX30) / ROCKNIX
**Kernel:** Linux 6.18+ (Mainline)
**Status:** SDIO bidirectional data path working. Scan in progress.
**Status:** Usable. Associates with WPA2, gets a DHCP lease, roams between APs,
survives suspend/resume, and sustains bidirectional traffic for hours — an 8-hour
soak moved 2,149,692 TX descriptors with every one completed. The SDIO wedge that
used to end a session now recovers automatically in about ten seconds.
Not yet prime-time: throughput is ~1.75-1.9 MB/s TX against a 2.5 MB/s vendor
reference, and the wedge still happens (it is recovered from, not prevented).
See [`KNOWN-ISSUES.md`](KNOWN-ISSUES.md).
## Overview
@@ -22,21 +29,204 @@ and `SDIO_ARCHITECTURE.md` for the SDIO protocol specification.
| Feature | Status |
|---------|--------|
| SDIO enumeration | Working |
| Firmware upload (48KB) + patch (16KB) | Working |
| Firmware upload (48056 B) + patch (16716 B) | Working |
| Firmware state machine (M0_READY) | Working |
| mac80211 registration (wlan0) | Working |
| mac80211 registration | Working — note the interface index increments on every reload, so it is rarely `wlan0` |
| SDIO CMD53 bidirectional data path | Working |
| RPU command/event protocol | Working |
| RPU_CMD_RESET → RESET_COMPLETE | Working |
| FW_PRIV_INIT (SET_CONFIG) | Working |
| NOP ping (data path verification) | Working |
| NOP ping (`FW_PRIV_NOP`) | Implemented but **unused** — `sv6160_rpu_fw_priv_nop()` has no callers; the data path is verified by real traffic now |
| VIF add/remove | Working |
| Channel programming | Working |
| WiFi scanning | SCAN_COMPLETE received; RX frames pending (rf_params fix) |
| WiFi association | Not yet |
| Data TX/RX | Not yet |
| WPA key management | Not yet |
| eFuse MAC address | Not yet (random MAC) |
| WiFi scanning (native `RPU_CMD_SCAN`) | Working — finds all APs, beacons reach cfg80211 |
| Frame TX | Working — every frame completes (`TX_DONE` 1:1) |
| Frame RX (broadcast + unicast) | Working |
| WiFi authentication | Working — `authenticated` ~10ms after the auth frame |
| WiFi association | Working — `RX AssocResp status=0`, `associated` |
| WPA2 key management | Working — 4-way handshake, CCMP group + pairwise keys |
| DHCP / usable connection | Working — carries ssh, the link this was developed over |
| Sustained link | Working — measured: 8h soak, 2,149,692 TX descriptors, all completed 1:1 |
| Suspend / resume | Working — measured once: same BSS and IP across a real deep suspend. Measured before the 2026-09-18 change that dropped `IRQF_NO_SUSPEND` from the host-wake IRQ; re-verify (see KNOWN-ISSUES §5) |
| Roaming | Working — measured on a real walk: 2 cross-channel roams, 40ms and 82ms handoffs, IP kept |
| CQM (RSSI thresholds) | Working — raised from RX-frame RSSI; drives iwd's roam trigger |
| Wedge recovery | Working — both failure modes self-recover unattended (see below) |
| Lifecycle under ifdown/ifup | **Soaked 2026-09-19**: 472 cycles in one module lifetime, 1.09 M descriptors 1:1, zero credit leaks, zero wedges, recovery ladder never fired |
| Power save | Measured and **deliberately rejected** — ~8mA of a ~365mA budget, PS measured *worse* |
| A-MSDU | Not engaged — root-caused to a missing `SUPPORT_FAST_XMIT`; adding it does aggregate but the chip cannot carry the result. Dead end, see below |
| MAC address | Stable and per-device — the factory MAC, via U-Boot into the DT; see below |
### A-MSDU: chased down, and it is a dead end
Root-caused rather than assumed, because the obvious explanations were all
wrong.
**Why it never engaged: we do not set `IEEE80211_HW_SUPPORT_FAST_XMIT`.**
`ieee80211_amsdu_aggregate()` has exactly one call site, inside
`ieee80211_xmit_fast()`; mac80211 only builds `sta->fast_tx` when the driver
advertises that flag, and `ieee80211_check_fast_xmit()` returns at its first
line without it. So the aggregation code was structurally unreachable. We
advertised `TX_AMSDU` -- "we can accept an A-MSDU" -- without the flag that
makes mac80211 take the path that *builds* one.
Adding the flag does work: `tx_max_frame` went from 1542 to **3080**, i.e. two
MSDUs in one frame, the first A-MSDU this driver has ever sent.
**And it is unusable.** Throughput collapsed from 0.77 MB/s to 0.02-0.08 MB/s,
with `sdio_write_data(...) failed: -16` in the log and the host-rebind recovery
firing. The chip cannot carry the larger frame bodies -- consistent with what
is already known about this SDIO path, where padding a CMD53 to the block size
kills the link and the vendor records that concatenating does too.
So A-MSDU is closed as a throughput lever, for a better reason than before.
Two earlier explanations, both refuted on hardware:
- *"the peer does not advertise a usable max_amsdu_len"* -- it does:
`iw` decodes the AP's HT capabilities as `Max AMSDU length: 7935 bytes`.
- *"the ADDBA Response clears the A-MSDU bit, so mac80211 latches
`IEEE80211_TXQ_NO_AMSDU` on the TID"* -- refusing TX BlockAck entirely left
`tx_max_frame` at 1542 while collapsing throughput 5x.
And the pull-model rewrite (`txq=1`) was built to unblock A-MSDU on the theory
that the push shim drains the txq before mac80211 can aggregate. That theory
was untestable: with fast-xmit off, no TX model could have produced an A-MSDU.
The rewrite costs throughput and is correctly left off, but it was never the
blocker.
**Testing note.** `SUPPORT_FAST_XMIT` is latched at probe from the `amsdu`
parameter, so it must be passed to `insmod` -- setting it by sysfs afterwards
silently measures the unflagged driver. Three runs were invalidated that way
before the probe build was made to log its own flag state and the harness to
discard any arm that could not prove it.
### Where the MAC comes from
It is the **factory** MAC and it is **per device**, despite the driver having a
random fallback that never runs here.
The factory address lives in Rockchip vendor storage (tag `0x524B5644`, sector
7296, item id 3) -- the same place the BSP read it from via
`rockchip_wifi_mac_addr()`. Vendor U-Boot reads that, exports `ethaddr`, and
`fdt_fixup_ethernet()` writes it into whatever `/aliases/ethernet0` resolves
to; ROCKNIX points that alias at the wifi node. So the node arrives carrying
`local-mac-address` and `of_get_mac_address()` picks it up:
sv6160 mmc2:0001:1: MAC 1e:28:78:e8:94:15 from device tree
`ethtool -P` reports the same value, and it survives reloads and reboots. The
`1e:28:78:` prefix is common to the family; the low three bytes are per unit.
Check it with:
od -tx1 /sys/firmware/devicetree/base/mmc@ff380000/wifi@1/local-mac-address
(`/proc/device-tree` is a symlink, so a plain `find` will not see that file.)
The driver's order is DT -> hash of the RK3326 OTP serial -> `eth_random_addr()`.
Only the first step runs on this board.
**Reading the SV6160's own eFuse is not implemented, and would gain nothing
here.** The registers are mapped (`EFUSE_CTRL` `0xC0000134`, offset in bits
0-5, busy in bit 7; `EFUSE_RDATA` `0xC0000138`; MAC at eFuse offset `0x10`) and
`fw_peek`'s `rw=0` is a plain load with no address validation in the firmware,
so the MMIO is reachable -- our `0x10000000..0x1000BBB8` guard is self-imposed.
It would need that guard widened, a write path for `EFUSE_CTRL` (only `rw=0`
has ever been exercised), and busy-polling. The reason not to bother: the
factory put the MAC in vendor storage, not in the chip's eFuse, which is why
the BSP reads vendor storage too -- so the likely result is a blank eFuse and a
fallback to the address we already have. It would only matter on a board with
neither a vendor-storage MAC nor a DT property.
### Recovery ladder
The driver rescues itself from both wedge modes rather than needing a human:
| condition | action |
|---|---|
| 3 fruitless TX resyncs | restart the hw (`tx_resync_giveup`) |
| 3 bus recoveries in 60s | re-create the SDIO host (`host_rebind`) |
In the 8-hour soak these fired 16 and 1 times respectively, and all 55 wedge
events recovered without intervention — 50 of them within 10-11 seconds. Before
it, each one needed an `unbind`/`bind` typed in over a serial console.
Two details fixed in the 2026-09-18 review, not yet re-soaked:
- The second rung counts only `-16`/`-110` bus faults. It used to count every
recovery, so three TX-link deaths inside a minute (the wedge mode's median
gap is 28 s) escalated to a host re-create instead of the `restart_hw` that
was measured to fix that failure.
- `ieee80211_restart_hw()` re-enters `.start` **without** calling `.stop`, so
`mac_start` now quiesces the driver's own state first (TX worker, resync,
command gate, descriptor pool). Before, the TX worker kept writing
descriptors to SDIO address 0 while the firmware image was being uploaded
to the same address, which is the likely reason `restart_hw` "made things
worse" in KNOWN-ISSUES.
`echo 1|2 > /sys/kernel/debug/ieee80211/phy*/sv6160/recover` drives the two
rungs by hand. It returns `-EINVAL` on any other input rather than silently
running the shallow rung, `-EBUSY` when the host re-create one-shot is already
spent or `host_rebind=0`, and `-ENODEV` for level 1 when the interface is down.
### History: how the encrypted data path was unblocked
This section used to describe the then-current blocker — association and the
WPA handshake completed, but DHCP never did and the supplicant gave up. That is
fixed; the driver now carries the ssh session it is developed over. The bugs
behind it are recorded below because the techniques that found them (byte-diffing
our command stream against the vendor's, and dumping raw bytes instead of
reasoning about them) keep paying off.
### How association was unblocked
Four bugs. The first two were found by diffing our control-command stream
against the vendor's byte for byte (`tools/rk915-wiredump.patch`); the last two
by dumping raw bytes rather than reasoning about them:
1. `sv6160_rpu_vif_cfg()` never populated `vif_addr`, so every VIF_CFG told
the firmware our MAC was `00:00:00:00:00:00`. `FW_PRIV_INIT` carries only
the first octet of the MAC, so VIF_CFG/VIF_CTRL are the only way the
firmware learns the whole address — and without it the LMAC cannot
address-match a unicast frame. Broadcast beacons arrived; our auth
response never did.
2. `sv6160_mac_tx()` stashed the TX descriptor id at `skb->cb`, which *is*
`struct ieee80211_tx_info` — overwriting mac80211's TX `flags` on every
frame. Harmless-looking until the first data frame after association
panicked the kernel in `skb_complete_wifi_ack`.
3. The RX chain followed an `RX_SERIAS` batch header's next-length, which is
really the length of the batch's own first sub-packet. That read a packet
that never existed, and the CMD53 timeout wedged the DW MMC controller.
4. TX descriptor ids came from a free-running counter. The firmware's table
has 12 entries and it rejects anything beyond — saying so in an FW_ERROR
event, `"[3243 F] Invalid desc id"` — then stops delivering *every* kind
of event. The `-16` bus wedge was eleven seconds downstream of that fault,
which is why it looked like a bus problem. Ids are now pooled tokens,
freed on TX_DONE, as in the vendor's `get_token()`.
### Superseded: the scan-gating theory
Measured from the firmware's own counters (`fwpeek=1 sweep_base=0x1000BA98
sweep_len=32`, which reads its TX/RX statistics block): reception starts when a
scan starts and stops the instant `SCAN_COMPLETE` fires. `RPU_CMD_CHANNEL` tunes
the radio but does **not** arm the receiver — in one capture the target AP's
beacons arrived on channel 6 during a scan, `CH_PROG_DONE(ch=6)` completed 250ms
later, and nothing was received again on that same channel.
So mac80211's authentication frame is transmitted into a window where nothing can
be heard. The control path stays healthy throughout (`cmd_send`/`event_recv` keep
climbing) and TX completes normally — only 802.11 reception is dead.
This is not a firmware limitation: the vendor driver's receiver is equally off
when idle, yet it goes from idle to `authenticated` in 17ms with no scan anywhere
in that window. `firmware/README.md` §12 has the captures.
### Known instability
Both faults that used to live here are fixed: the stale-RECV_LEN `-110` wedge
(the guard that caused it now defaults off) and the per-beacon `WARN` in
`ieee80211_rx_list`. What remains open — with the evidence and the ruled-out
hypotheses — is in [`KNOWN-ISSUES.md`](KNOWN-ISSUES.md), chiefly that the wedge
arrives in bursts whose trigger is still unidentified.
### Required Kernel Patch
@@ -106,13 +296,51 @@ make -C /path/to/kernel M=$PWD CONFIG_SV6160=m modules
## Module Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `coalescing` | bool | true | Enable RX IRQ coalescing |
| `rx_bundle` | int | 16 | Max RX packets per interrupt |
| `sdio_blksize` | int | 512 | SDIO block size (try 64/128 for debugging) |
| `mac_program` | string | — | Program eFuse MAC (xx:xx:xx:xx:xx:xx) |
| `patch` | string | ssv6160-patch.bin | Firmware patch file name |
31 in total; `modinfo sv6160` lists them all with descriptions. The ones that
change behaviour rather than instrument it:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `tx_stall_ms` | 3000 | Declare a TX descriptor stalled after this long and resync the pool |
| `tx_quarantine_ms` | 3000 | Hold a resync-reclaimed descriptor id back this long before reuse |
| `tx_resync_giveup` | 3 | Restart the hw after N fruitless resyncs (0 = never) |
| `host_rebind` | 3 | Re-create the SDIO host after N bus recoveries in 60s (0 = off) |
| `tx_batch` | 8 | Max frames per TX descriptor — **9 is the firmware's real ceiling**, see below |
| `tx_dma` | 1 | Bounce TX bodies through an aligned buffer so dw_mmc can DMA them |
| `descs_per_ac` | 2 | Descriptors in flight per AC |
| `cqm` | 2 | Declare BEACON_FILTER/SUPPORTS_CQM_RSSI so RSSI events drive roaming |
| `ba_rx` | 1 | Program RX BlockAck sessions to the firmware |
| `coalescing` | true | Enable RX IRQ coalescing |
| `rx_bundle` | 16 | Max RX packets processed per interrupt |
| `patch` | ssv6160-patch.bin | Firmware patch file name |
The rest (`fwpeek`, `fwinfo`, `sweep_base`, `sweep_len`, `fwpoke`, `wiredump`,
`trace`, `wt_trace`, `scan_passive`, `scan_single_ch`, `fixed_mcs`, `cmd_gate`,
`vendor_bringup`, `rf_arm`, `txq`, `amsdu`, `chan_settle`, `sdio_blksize`,
`fwpoke_when`) are diagnostics and experiments; several exist to keep a measured
answer switchable rather than lost. `fwpoke` and `fwpoke_when` are insmod-only
(mode 0400): they write firmware memory. `wiredump` and `wt_trace>=2` never dump
the `SETKEY` payload, so no `dmesg` carries session keys, and the `WBODY`/`RXDATA`
frame dumps stop after the 802.11 header plus IV.
`RXTAIL` is the exception and is deliberate: it prints the last 8 bytes of a
decrypted frame, which is the only way to tell whether the firmware left a CCMP
MIC there or ate 8 bytes of real payload. When the MIC is absent those 8 bytes
ARE payload. It needs `wt_trace=1`, so it is opt-in, but scrub a capture taken
with it before sharing.
**Older documents reference parameters that no longer exist.** `firmware/README.md`
and `VENDOR-DRIVER-FINDINGS.md` mention `rx_chain`, `rf_keep`, `int_gen`,
`system_rev`, `stale_guard`, `mac_program` and others. Those are records of
experiments, not current knobs — each one's answer is now a comment next to the
code it settled, and the parameter was culled. `modinfo` is the source of truth
for what exists today.
**`tx_batch` warning.** It is clamped by
`min3(mod_tx_batch, SV6160_TX_BATCH_MAX, …)`, so on a stock build it accepts 16,
reads back 16, and runs at 8. Verify frames-per-descriptor in debugfs before
trusting any `tx_batch` measurement — that trap invalidated ~1173 transfers of
evidence once already.
## Architecture
@@ -159,17 +387,22 @@ address — a brief delay or RINTSTS check prevents premature CMD53 reads.
## Known Issues
1. **No WiFi beacon/probe frames yet** — SCAN_COMPLETE received and RX_SERIAS
batches delivered, but sub-packets are all CMD_PROC_DONE (28 bytes), not
802.11 frames. Root cause: rf_params was all zeros → radio not calibrated
for RX. Fix: populated rf_params + LMAC_NO_SLEEP + PHY thresholds (testing).
See [`KNOWN-ISSUES.md`](KNOWN-ISSUES.md) for the open bugs, the evidence behind
them, and — most usefully — the hypotheses already ruled out with sample sizes,
so none of them gets re-run by accident.
2. **SDIO in-band IRQ not firing** — Despite sdio_claim_irq + cap-sdio-irq,
SDIO in-band interrupts never trigger. GPIO level-trigger IRQ is the working
path (fires 5-9 times per scan cycle).
In short: the SDIO wedge still occurs in bursts whose trigger is unidentified
(six hypotheses eliminated), it is recovered from automatically rather than
prevented, and throughput sits below the vendor reference with the obvious levers
exhausted.
3. **-110 recovery** — Stale RECV_LEN causes CMD53 reads before DMA is ready.
Graceful recovery: FIFO reset + skip (no clear+notify on failed reads).
The three issues that used to be listed here — no beacons/probe frames, SDIO
in-band IRQ not firing, and `-110` stale-RECV_LEN recovery — are all resolved.
The first was uncalibrated `rf_params`; the last was the RX aggregate cap being
4096 where the vendor uses 33280.
See [`VENDOR-DRIVER-FINDINGS.md`](VENDOR-DRIVER-FINDINGS.md) for measurements
from the vendor-based driver on the same silicon.
## License
+10 -1
View File
@@ -1,5 +1,12 @@
# SV6160 / RK915 SDIO Architecture
> **Status:** The register map, boot protocol, and packet sections below are
> still the reference. The "Implementation Status" and "Current Blocker"
> sections further down are a historical snapshot from commit 2303d96 — the
> -110 CMD53 read timeout they describe was resolved on the
> `sdio-rx-hardening` branch. See README.md and KNOWN-ISSUES.md for the
> current state.
## Critical Finding: SDIO Address Space
The SDIO CMD53 protocol only supports **17-bit addresses** (0x00000 - 0x1FFFF = 128 KiB).
@@ -133,7 +140,9 @@ Files studied from `stolen/rk915`:
- `src/sdio.c` — `sdio_send_data()`/`sdio_recv_data()` SDIO I/O (ANALYZED)
- `src/hal.c` — `hal_send()`/`rx_thread()` event dispatch (ANALYZED)
## Current Blocker: CMD53 Read Timeout (-110)
## Historical: CMD53 Read Timeout (-110), resolved
See README.md for the current state; this section is kept for history only.
### Symptom
SDIO CMD53 data reads at address 0 return -110 (ETIMEDOUT) on the XF40H's
+213
View File
@@ -0,0 +1,213 @@
# Findings from the vendor-based RK915 driver
Notes contributed from work on the *other* Linux driver for this chip — the
out-of-tree mainline port of the Rockchip/Seekwave vendor BSP (the
`sunshineinabox/rk915` 7.1 line, itself from `stolen/rk915`), running on a Gusgu
H7 (RK3326/PX30). That driver is a different codebase from this clean-room one,
but it targets the **same silicon and the same firmware**, and it has reached
full association + bidirectional data, so it has run into walls this driver has
not hit yet. This file records what was learned, in case it saves time here.
Contributed 2026-09; all data measured on hardware.
## Same firmware, confirmed
The firmware blobs are byte-identical to the vendor BSP's:
| this repo | md5 | vendor BSP name |
|---|---|---|
| `firmware/ssv6160-fw.bin` | `a0e5ed758324e15bc2ed62d0e29f12d8` | `rk915_fw.bin` |
| `firmware/ssv6160-patch.bin` | `6c1f8ec692e153ca61617d0d2dd5cd4d` | `rk915_patch.bin` |
So this repo's firmware reverse-engineering applies directly to the vendor
driver, and vice versa. The `firmware/README.md` register map matched the
vendor driver's independently-derived SDIO register defines
(NOTIFY=17, INT=32, WRITE_COMP=35, FW_STATE=64) exactly.
## Your reset-poll idea fixed the vendor driver's boot race
`sv6160_rpu_reset()` pumps the RX worker every 100 ms while waiting for
RESET_COMPLETE, with the comment *"Poll the RX worker manually since SDIO
interrupts may not be firing during early init."* The vendor port had the
opposite — a bare `wait_event_timeout()` — and suffered an intermittent
`RPUWIFI-UMAC: No reset complete after N ticks` on ~1 boot in 3. Adopting your
approach (kick the RX thread on a 100 ms slice during the wait) fixed it. Thanks.
## The wall this driver will hit at the data path: an SDIO wedge under sustained RX
The single unsolved fault in the vendor driver is a hard throughput ceiling, and
it is almost certainly the full form of the *"-110 that permanently kills DW MMC
bus"* hazard already noted in `sv6160_core.c` (the `last_recv_len` / stale
RECV_LEN guard) and Known Issue #3. Measured shape:
* **Rate-triggered.** Sustained transfer above roughly **15–29 KB/s** kills the
link within seconds — either direction, a single TCP connection is enough.
Below that rate the link is stable indefinitely (13 h+ observed). Bursty
traffic with idle gaps is fine; it is continuous throughput that does it.
* **The chip is not asleep.** `FW_STATE` (SDIO reg 64) reads `M0_READY` (5)
before, during and after the fault. Whatever happens, the MCU is alive.
* **The whole SDIO link wedges, not one transfer.** Instrumented a failing
CMD53 write to also read RECV_LEN and FW_STATE at that instant: **both reads
also return `-EBUSY` (-16).** So every transaction to the card — CMD52 read
and CMD53 write alike — fails at once. The card has stopped servicing the bus.
* **Host-side retry does not help.** Retrying a busy write up to 8 times over
~30 ms, dropping the host lock between attempts so the RX worker could drain,
rescued **zero** writes. The wedge persists until the chip is **power-cycled**
(the vendor driver's firmware-error recovery does exactly that, and the link
then comes straight back).
* **Most consistent with RX buffer exhaustion.** It matches `rx_buf_pool`
(`0x10006524`, max 15 entries) and `event_pending_count` (`0x10006520`) from
`firmware/README.md`: the chip's RX pool fills faster than it is drained over
SDIO, and past some fill level the SDIO slave stops responding. That is exactly
why a rate threshold exists — below it the pool never saturates.
Ruled out on hardware, so they need not be re-tried: LMAC sleep (FW stays
M0_READY); mac80211 power-save off (no change); a runtime `LPW_CTRL`
(`0xC0001000`) bit-4 "disable clock gating" write via the firmware's register
path (readback unchanged — that path does not reach the LPW block); host-side
write/length-read retries (wedge outlasts them).
**A real fix needs the chip's RX flow-control / buffer-credit protocol**, which
is not documented anywhere we have found. The proven workaround is to rate-limit
(`rsync --bwlimit=15` moves a 24 MB image cleanly); it works precisely because it
holds the chip under the saturation threshold.
## `length(61680) too long` / `0xF0F0` is the wedge, not a bad length
Worth knowing because this driver's RECV_LEN read has the same shape. The vendor
driver's `rk915_read_data_len()` reads the two RECV_LEN bytes via CMD52 and folds
them into a length. On a busy bus each byte read returns `-EBUSY`; cast to
`u8`, `(u8)(-16)` is `0xF0`, so the two bytes combine to `0xF0F0` = **61680**,
which then trips the "length too long" bound check. So `length(61680)` and a
write failing `-16` are the **same event** — the `-EBUSY` wedge — reached from
the read or the write side. The byte pattern is therefore **not diagnostic**: an
idle-time `0xF0F0` can be the chip having slept (cured by keeping the LMAC awake),
while an under-load `0xF0F0` is this bus wedge with the chip wide awake. Tell them
apart by reading `FW_STATE` plus one more register at the failure — if both also
return `-16`, it is the wedge.
---
## Checkpoint 2026-09-09: byte-level command diff against the vendor
Method that worked: instrument **both** drivers to dump their actual SDIO
payloads (`wt_trace=2` on ours; `print_hex_dump` in the vendor's
`sdio_send_data`/`sdio_recv_data`) and diff real bytes on the same hardware,
against byte-identical firmware. Every real bug below came from that. Every
conclusion reasoned forward from a mechanism instead turned out to be wrong.
### Bugs found and fixed
| Bug | Detail |
|---|---|
| **TX descriptor 512 vs 581** | The vendor's `cmd_tx_ctrl` ends with `unsigned int *p_frame_ddr_pointer[MAX_TX_CMDS]` — *host pointers*, 8B each on a 64-bit kernel = a 128B tail we omitted (453+128=581, wire `ALIGN(581,4)`=584). We wrote the 802.11 body after a 512B descriptor, so it began 72 bytes before where the firmware looks. |
| **`RPU_CMD_PS` malformed and gratuitous** | Firmware `cmd_ps` is `{hdr; if_index; mode}` (36B); we sent a 40B struct, so it read `if_index=<our mode>`, `mode=200`. The vendor never sends this command at all — `rpu_prog_ps_state()` is a bare `return 0;`. Ours is now a no-op. |
| **TX queue numbering inverted** | mac80211 numbers ACs `VO=0..BK=3`; the firmware numbers them `BK=0..VO=3`. The vendor maps every frame through `tx_queue_map()` (= `3-ac`, `src/tx.c:130`). We had no mapping: all TX went out on queue 0 = **Background** (the vendor's dumped assoc descriptor shows `queue_num=3` = Voice), and `conf_tx`/bring-up programmed the whole EDCA table onto inverted queues. |
| **Multicast commands never sent** | `MCST_ADDR_CFG`(0x13) and `MCST_FLTR_CTRL`(0x14) were absent from our command enum. The vendor sends an explicit `MCAST_FILTER_DISABLE` whenever the address list is empty; we left the LMAC filter at its power-on default. |
| **`.prepare_multicast` slept in atomic context** | mac80211 documents it as atomic; our send path takes a mutex and does a synchronous CMD53. Sending from there hung the board. The vendor can, because its `rpu_send()` only takes a `spin_lock_bh` and queues the buffer. Now the callback only snapshots the list; `.configure_filter` does the SDIO. |
### Proven identical (stop re-checking these)
CHANNEL payload (byte-for-byte, both drivers, incl. the ch11 variant), RESET
payload (byte-for-byte except `system_rev`, now matchable via a module param),
firmware + patch binaries (`a0e5ed75…` / `6c1f8ec6…`; our `ssv6160-fw.bin` ==
vendor `rockchip/rk915_fw.bin`), RF calibration (neither `rk915_cal.bin` nor
`rk915_rf_para.txt` exists on the device, so both run stock `rf_params`),
`FW_PRIV` type=6, `VIF_CTRL` layout, TX descriptor rate fields
(`num_rates=1, protection=0, preamble=1, retries=5, rate=2, spatial=1`),
`bcn_rcv_mode` values and usage.
### Retraction: the "vendor CHANNEL takes 52ms, ours 1.6ms" signature is not real
Decoding the vendor's RX **event ids** (`rpu_msg_hdr.id` at offset 16) shows its
`CH_PROG_DONE` (evid 18) arrives in **2.2ms** on an idle pipeline — the same
ballpark as ours. The "52ms" was the first post-CHANNEL event being a
`COMMAND_PROC_DONE` (evid 17), delivered on a ~53ms cadence when commands are
queued; it is ack pacing, not RF work, and it varies (2 / 104 / 159 ms) with
pipeline depth. Comparing gaps between untyped 28-byte reads produced a phantom
that drove a lot of wasted effort. **Decode event ids before timing anything.**
### Where the problem now sits: TX works, unicast RX does not
Measured over 22s with the gate off:
```
TX cmds (id=7) = 9 TX_DONE (evid=1) = 9 <-- perfect 1:1
RX: 48 frames, ALL 400-420 bytes (evid=0) <-- beacons/probe-resps only
53 x evid=17 PROC_DONE, 7 x evid=18 CH_PROG, 2 x evid=5, 1 x evid=8
```
Every auth frame we transmit produces a TX_DONE, so the firmware **is**
transmitting. Beacons arrive normally. But an auth reply would be ~60-90 bytes
with its descriptor and **we receive no small frames at all** — the firmware
never delivers a unicast frame to us. That retires TX, channel programming and
the command stream as suspects.
Open question: why beacons but never unicast? Candidates not yet examined —
whether the firmware needs the VIF in a particular state before forwarding
non-beacon frames, and how it learns our full MAC for RX address matching
(`VIF_CTRL` carries `vif_addr[6]`, while `FW_PRIV` carries only the first
octet).
### Also refuted
`cmd_gate` — the vendor's control-command serialization (max 2 outstanding,
retire on `COMMAND_PROC_DONE`) starves here and hard-hung the board twice; it
is committed but **default off**. With the gate off the firmware acks ~76% of
our commands (34 acks / 45 commands), so the LMAC does process them. Also no
help: `rf_arm=1`, `int_gen=0`, and replicating the vendor's full pre-CHANNEL
config sequence.
## The vendor's firmware self-report interface (2026-09-10)
The GPL vendor source is on disk and is the authority for anything fw-priv:
`rocknix/build.ROCKNIX-RK3326.aarch64/build/rk915-86f0d0e07afe156651ce5eec3e315f66ef79a59f/`
(`src/`, `inc/`, `shared/host_rpu_if.h`). The sub-command enum, the payload
struct and the dump reply structs all live there; the `enum fw_priv_subcmd` in
our `sv6160.h` predates it and is wrong.
### Using the vendor driver as a live control
`$D = /sys/kernel/debug/ieee80211/phyN/rk915`. Two writable files, and they
take different vocabularies — cross-writing just gives "Invalid parameter name":
- `$D/params` takes **commands**: `read_fw_reg=ADDR,LEN`, `write_fw_reg=ADDR,VAL`,
the `_lpw_` variants, `debug_mask=`, `econ_ps=`, `notify_pm=`, `simulate_fw_crash`.
- `$D/fw_params` takes **parameters**: `echo_mode=`, `ejtag_mode=`, `debug_level=`,
`debug_flag=`, `dis_wifi_isr_thd=`, `en_wifi_isr_thd=`, `dump_mem_info`.
A read is `echo read_fw_reg=0x1000BAA8,0x4 > $D/params` followed by
`timeout 5 cat $D/fw_info`. **The value is in `fw_info`** (`1000baa8: 00001f83`).
The `rk915: read fw reg ... val 0x0` dmesg line is only the request log and its
`val` is always 0 — reading dmesg instead makes every address look like zero.
Always put a `timeout` on the `cat`; it can block.
Healthy baseline, vendor associated and pulling ~180 frames/s: `0x1000BAA8`
climbing continuously, `0x1000BBA8` = 0, `0x100064E4` = 0, `0x100054E4` = 0,
`0x10005474` = 1 (doorbell armed).
Hazards, both measured: reading outside `0x10000000..0x1000BBB8` kills the
firmware (recoverable with a `dwmmc_rockchip` unbind/bind), and
`read_fw_reg=0x1000BA98,0x40` tipped rk915 into a permanent
`rx_thread: error datalen: 0` flood. **Do not `rmmod rk915` during that flood** —
it deadlocks the kernel and costs a physical power cycle. Silence the console
with `dmesg -n 1` first, then unbind/bind.
### Also refuted (2026-09-10)
**`fw_priv` params are not the difference.** The vendor's `fw_priv_init()`
(`src/rpu_if.c:943`) fills in only `production_test`, `fw_skip_rx_pkt_submit`,
`wlan_mac_addr` and `p2p_mac_addr`; it leaves `params` zeroed, exactly as we do.
The values `fw_params` prints are firmware defaults, read back live via
FW_GET_PARAMS(9) — not something the driver pushes.
**`dis_wifi_isr_thd` does not gate RX.** Set to 1 on the working vendor
mid-association: frames kept arriving at full rate and the link stayed up.
**Firmware logging does not exist to be enabled.** Reading `$D/fw_log` issues
DUMP_FW_LOG(4), and it returns empty on the *working* vendor even at
`debug_level=3` with `debug_flag=0xf`. This retires a long-standing "next lead".
+709 -54
View File
@@ -25,6 +25,9 @@
#define SDIO_VENDOR_ID_SSV_ALT 0x0296
#define SDIO_DEVICE_ID_SV6160_ALT 0x5348
/* RESET.system_rev, matching the vendor's hardcoded "GMI" byte for byte. */
#define SV6160_VENDOR_SYSTEM_REV 0x494D47
/* Firmware file names */
#define SV6160_FW_NAME "ssv6160-fw.bin"
#define SV6160_PATCH_NAME "ssv6160-patch.bin"
@@ -76,7 +79,27 @@ enum sv6160_fw_state {
#define SV6160_NUM_CHANNELS 14
#define SV6160_MAX_SCAN_CHANNELS 50
#define SV6160_RF_PARAMS_SIZE 369
#define SV6160_MAX_RX_SIZE 4096
/* Largest single RX read the firmware can ask us to perform.
*
* This is the vendor's MAX_RX_SERIAS_BYTES verbatim:
* MAX_RX_SERIAS_COUNT(16) * MAX_DATA_SIZE_2K(2048) + 512 = 33280
* (rk915 inc/if_io.h:22-23, allocated once in init.c:145 and passed to
* rk915_serias_read() as max_len). One "packet" in the chain is really an
* aggregate of up to 16 sub-frames, so it is NOT bounded by the 2304-byte
* 802.11 MTU.
*
* We had 4096 here, and that single number was the driver's worst bug. Under
* real traffic the firmware aggregates more than that and advertises the size
* in the previous packet header's upper 16 bits; the chain walk then hit
* `rx_next_len > SV6160_MAX_RX_SIZE`, gave up, and left the data queued in the
* firmware. The firmware waits for the host to collect it and NEVER ASSERTS
* HOST-WAKE AGAIN -- so RX, TX_DONE and command replies all stop together,
* permanently, which is what made TX descriptors look like they were leaking.
* Captured at the moment of death:
* RXLINK d=125 c=0 pktlen=2048 id=0 raw=0x1a000044 next=6656
* RXEND d=125 chain_done=0 recvlen=2048 irqs=125
* 6656 > 4096, so we dropped it; irqs and drains both stop at 125. */
#define SV6160_MAX_RX_SIZE 33280
/* ===================================================================
* Firmware Packet Dispatch Architecture
@@ -134,13 +157,35 @@ enum rpu_cmd_tag {
RPU_CMD_PS_ECON_CFG = 14,
RPU_CMD_VIF_CTRL = 15,
RPU_CMD_BA_SESSION_INFO = 18,
RPU_CMD_MCST_ADDR_CFG = 19,
RPU_CMD_MCST_FLTR_CTRL = 20,
RPU_CMD_ROC_CTRL = 22,
RPU_CMD_CHANNEL = 23,
RPU_CMD_VIF_CFG = 24,
RPU_CMD_TXQ_PARAMS = 26,
/* Asks for the firmware's MAC/BB counters; the reply would come back as
* RPU_EVENT_MAC_STATS, not as a MIB_STAT event, and the payload is a
* bare header (rk915 rpu_prog_mib_stats). DO NOT SEND IT: this
* firmware answers with RPU_EVENT_FW_ERROR "[27962 F] event
* length(184) overflow" and no data, every time. Kept named so the id
* is not mistaken for something else on the wire. See
* sv6160_get_survey() for the measurement this would have provided. */
RPU_CMD_MIB_STATS = 27,
RPU_CMD_FW_PRIV_CMD = 42,
RPU_CMD_PATCH_FEATURES = 100,
};
/* Firmware transmit-queue numbering (vendor enum UMAC_QUEUE_NUM). NOTE this
* runs opposite to mac80211's AC numbering -- see sv6160_tx_queue_map(). */
#define SV6160_WLAN_AC_BK 0
#define SV6160_WLAN_AC_BE 1
#define SV6160_WLAN_AC_VI 2
#define SV6160_WLAN_AC_VO 3
#define SV6160_WLAN_AC_BCN 4
/* PATCH_FEATURES feature_val flags (vendor host_rpu_if.h) */
#define LMAC_WATCHDOG_PHY_HANG_RESET_ENABLE 0x1
/* FW_PRIV_CMD sub-command IDs (firmware internal HOST_CMD routing) */
enum fw_priv_subcmd {
FW_PRIV_STATUS_QUERY = 1,
@@ -167,6 +212,7 @@ enum rpu_event_tag {
RPU_EVENT_RESET_COMPLETE = 8,
RPU_EVENT_COMMAND_PROC_DONE = 17,
RPU_EVENT_CH_PROG_DONE = 18,
RPU_EVENT_MAC_STATS = 21, /* never arrives; see RPU_CMD_MIB_STATS */
RPU_EVENT_ROC_STATUS = 24,
RPU_EVENT_FW_ERROR = 25,
RPU_EVENT_CALIBRATION_DONE = 28,
@@ -186,12 +232,19 @@ enum rpu_event_tag {
/* Rate flags */
#define ENABLE_11N_FORMAT 0x08
#define MARK_RATE_AS_MCS 0x80
#define ENABLE_SGI 0x04
/* Power save modes */
#define PS_MODE_DISABLED 0
#define PS_MODE_ENABLED 1
#define PS_MODE_DEEP 2
/* cmd_tx_ctrl rate-block encodings (vendor host_rpu_if.h) */
#define MARK_RATE_AS_RATE 0x00
#define USE_PROTECTION_NONE 0
#define USE_PROTECTION_RTS 1
#define USE_PROTECTION_CTS2SELF 2
#define USE_SHORT_PREAMBLE 0
#define DONT_USE_SHORT_PREAMBLE 1
#define AMPDU_AGGR_DISABLED 0
#define AMPDU_AGGR_ENABLED 1
#define SV6160_MAX_TX_RATES 4
#define MARK_RATE_AS_MCS 0x80
/* VIF control operations */
#define VIF_ADD 1
@@ -220,8 +273,18 @@ enum rpu_event_tag {
#define VIF_CFG_BASICRATES_CHANGED (1 << 0)
#define VIF_CFG_SHORTSLOT_CHANGED (1 << 1)
#define VIF_CFG_BCN_INT_CHANGED (1 << 11)
#define VIF_CFG_SHORTRETRY_CHANGED (1 << 7)
#define VIF_CFG_LONGRETRY_CHANGED (1 << 8)
#define VIF_CFG_DTIM_CHANGED (1 << 12)
#define VIF_CFG_OP_CHAN_CHANGED (1 << 15)
#define VIF_CFG_RCV_BCN_MODE_CHANGED (1 << 10)
/* Beacon receive mode (vendor host_rpu_if.h) — RCV_ALL_BCNS is promiscuous
* (every AP's beacons, needed only during a scan); RCV_ALL_NETWORK_ONLY keeps
* only the connected network's beacons. Flooding RCV_ALL_BCNS during
* association drowns the SDIO bus in beacon RX and wedges a concurrent TX. */
#define RCV_ALL_BCNS 0
#define RCV_ALL_NETWORK_ONLY 1
/* Connect state */
#define STA_CONN 0
@@ -258,7 +321,14 @@ struct rpu_cmd_reset {
__le32 unused2;
u8 rf_params[SV6160_RF_PARAMS_SIZE];
__le32 unused3;
u8 bg_scan[48]; /* bgscan_params placeholder */
/* struct bgscan_params: enabled(4) + channel_list[50] +
* channel_flags[50] + scan_intval(4) + channel_dur(4) +
* serv_channel_dur(4) + num_channels(4) = 120 bytes (packed).
* This MUST be 120, not 48 — an undersized placeholder shifts every
* field below (num_spatial_streams, antenna_sel, ...) to the wrong
* offset, so the firmware reads garbage for antenna_sel/streams and
* the radio comes up misconfigured (deaf receiver). */
u8 bg_scan[120];
u8 num_spatial_streams;
__le32 system_rev;
__le32 lmac_mode;
@@ -266,7 +336,11 @@ struct rpu_cmd_reset {
__le32 reserv[2];
} __packed;
#define SV6160_MAX_NUM_SSIDS 4
/* Vendor uses ENABLE_SPLIT_MULT_SSID_SCAN → cmd_scan.ssids[1] (one SSID per
* scan command). Our old ssids[4] shifted p2p_probe/extra_ies_len by 108B and
* the firmware read them from the wrong offset (scan struct 390 vs vendor 296,
* found by the SDIO trace diff). */
#define SV6160_MAX_NUM_SSIDS 1
#define SV6160_MAX_SSID_LEN 32
struct rpu_scan_ssid {
@@ -341,61 +415,323 @@ struct rpu_cmd_vif_cfg {
* +0x42: pad (2 bytes)
* +0x44: prod_test
*/
struct rpu_fw_priv_cmd {
struct rpu_msg_hdr hdr; /* 0x00-0x1B (28 bytes) */
__le32 sub_cmd; /* 0x1C */
u8 reserved[24]; /* 0x20-0x37 — firmware expects gap here */
__le32 config_bitmap; /* 0x38 — bit3=sleep, bit4=PS, bit5=rate */
u8 mac_addr[6]; /* 0x3C */
u8 pad[2]; /* 0x42 */
__le32 prod_test; /* 0x44 */
/* Verified against the firmware's HOST_CMD handler and the vendor's
* fw_priv_cmd: hdr(28), type@28, fw_reg_info@32 (reg,val,len,rw),
* production_test@48, fw_skip_rx_pkt_submit@52, params_mask@56,
* params[6]@60, sniffer@66, wlan_mac_addr@70, p2p_mac_addr@71 = 72B.
*
* NOTE offset 52 (fw_skip_rx_pkt_submit) is the word the firmware stores into
* 0x100064E4 at 0x020099c4 -- its RX kill switch. Set to 1 and EVERY received
* frame is freed instead of delivered. Keep it 0. */
struct sv6160_fw_priv_cmd {
struct rpu_msg_hdr hdr;
__le32 type;
__le32 reg_info[4]; /* fw_reg_info: reg, val, len, rw */
__le32 production_test;
__le32 fw_skip_rx_pkt_submit;
__le32 params_mask;
u8 params[6];
__le32 sniffer;
u8 wlan_mac_addr;
u8 p2p_mac_addr;
} __packed;
/* HOST_CMD (0x2A) sub-commands, vendor enum fw_priv_cmd_type
* (rk915 shared/host_rpu_if.h:530). The whole list is here because most of
* these ask the firmware to describe its own state, which is the only source
* of truth we have for what the LMAC thinks it is doing. */
#define FW_PRIV_DUMP_TXRX_COUNT_INFO 1
#define FW_PRIV_DUMP_TXRX_BUF_INFO 2
#define FW_PRIV_DUMP_REG_INFO 3
#define FW_PRIV_DUMP_FW_LOG 4
#define FW_PRIV_DUMP_TXRX_QUEUE_INFO 5
#define FW_PRIV_INIT_CMD 6
#define FW_PRIV_DUMP_FW_VERSION 7
#define FW_PRIV_SET_PARAMS 8
#define FW_PRIV_GET_PARAMS 9
#define FW_PRIV_DUMP_MEM_INFO 10
#define FW_PRIV_DUMP_IF_INFO 11
/* All fw-priv replies arrive as event 28 carrying dump_info{size,end,data[]}
* (rk915 shared/host_rpu_if.h:1377). Most sub-commands put a plain text
* report in data[]; DUMP_TXRX_COUNT_INFO and DUMP_IF_INFO put the two structs
* below there instead. */
/* rk915 src/procfs.c:400 -- firmware tick unit is 25ns. */
struct sv6160_fw_time_info {
__le32 count;
__le32 max_time;
__le64 total_time;
} __packed;
/* rk915 src/procfs.c:431. Only the head of the struct is decoded; the tail
* (per-path timing, filter counts) is left to the hex dump. */
struct sv6160_fw_txrx_count {
__le32 cmd_tx_send;
__le32 cmd_send;
__le32 event_recv;
__le32 event_rx_recv;
__le32 event_rx_pkt_recv;
__le32 event_rx_pkt_crc_ok;
__le32 event_rx_pkt_crc_err;
__le32 event_tx_done_recv;
__le32 event_rx_serias;
__le16 err_desc_id_lmac;
__le16 err_desc_id_host;
__le16 lpw_hang;
__le16 lpw_hang_cnt;
__le16 cmd_cnt_dur_lpw_hang;
__le16 cmd_txcnt_dur_lpw_hang;
__le16 cmd_rxcnt_dur_lpw_hang;
struct sv6160_fw_time_info wifi_isr_info;
struct sv6160_fw_time_info sdio_isr_info[4];
struct sv6160_fw_time_info cmd_send_info;
__le32 cmd_id;
__le64 total_tick;
struct sv6160_fw_time_info rx_notify;
struct sv6160_fw_time_info rx_begin;
struct sv6160_fw_time_info rx_end;
struct sv6160_fw_time_info rx_interval;
__le32 lpw_rx_q_min;
__le16 wifi_int_disabled;
} __packed;
/* rk915 src/procfs.c:406/419. MAX_IF is 2. */
#define SV6160_FW_MAX_IF 2
struct sv6160_fw_vif_info {
__le32 if_ctrl; /* IF_ADD == 1 */
__le32 if_idx;
__le32 if_mode; /* IF_MODE_STA_BSS == 0 */
__le32 if_conn_sta; /* STA_CONN == 0 */
u8 if_addr[6];
u8 bssid[6];
__le32 key_ctrl; /* KEY_CTRL_ADD == 0 */
__le32 key_type;
} __packed;
struct sv6160_fw_if_info {
__le32 num;
struct sv6160_fw_vif_info vif_info[SV6160_FW_MAX_IF];
} __packed;
/* Matches vendor struct cmd_tx_pwr EXACTLY: { hdr, if_index, tx_pwr } = 36B.
* The old layout had an extra `band` field and the wrong field order, so the
* firmware read the power value as if_index — a wire-size mismatch (40 vs 36)
* found by the SDIO trace diff. */
struct rpu_cmd_tx_power {
struct rpu_msg_hdr hdr;
__le32 tx_power;
__le32 band; /* 0 = 2.4 GHz */
__le32 if_index;
__le32 tx_pwr;
} __packed;
/* Multicast address programming / filter control. The vendor sends these
* from prepare_multicast()/configure_filter() (rk915 src/umac_if.c:925,980);
* we sent neither, so the LMAC's multicast filter was left at whatever the
* firmware defaults to with an empty address list. Note the vendor sends an
* explicit MCAST_FILTER_DISABLE whenever the list is empty. */
#define WLAN_MCAST_ADDR_ADD 0
#define WLAN_MCAST_ADDR_REM 1
#define MCAST_FILTER_DISABLE 0
#define MCAST_FILTER_ENABLE 1
/* Vendor MCST_ADDR_LIMIT; above this it disables filtering instead. */
#define SV6160_MCST_ADDR_LIMIT 8
/* Matches the firmware's struct cmd_mcst_addr_cfg = 38B (wire 40). */
struct rpu_cmd_mcst_addr_cfg {
struct rpu_msg_hdr hdr;
__le32 op;
u8 mac_addr[6];
} __packed;
/* Matches the firmware's struct cmd_mcst_filter_ctrl = 32B. */
struct rpu_cmd_mcst_filter_ctrl {
struct rpu_msg_hdr hdr;
__le32 ctrl;
} __packed;
/* Matches the firmware's struct cmd_ps EXACTLY = 36B. The old layout
* (ps_mode/idle_timeout_ms/listen_interval, 40B) was shifted by one field:
* the firmware read our mode as if_index and our idle_timeout as the PS mode.
* Note the vendor never sends this command at all (its rpu_prog_ps_state is a
* stub), so this command is never sent and the struct is unused — kept
* correct so re-enabling it is not a landmine. Power save is done entirely
* with the PM bit in outgoing frames instead; see ps_doze in the softc. */
struct rpu_cmd_ps {
struct rpu_msg_hdr hdr;
__le32 ps_mode;
__le32 idle_timeout_ms;
__le32 listen_interval;
__le32 if_index;
__le32 mode;
} __packed;
/* Matches vendor struct cmd_txq_params EXACTLY = 64B (all u32 + vif_addr[6]).
* The old layout was 44B with u16/u8 fields and no uapsd/vif_addr, so the
* firmware read 20 bytes short and misinterpreted every field — a wire-size
* mismatch (44 vs 64) found by the SDIO trace diff. */
struct rpu_cmd_txq_params {
struct rpu_msg_hdr hdr;
__le32 queue_num;
__le32 aifsn;
__le32 txop;
__le32 cwmin;
__le32 cwmax;
__le32 uapsd;
__le32 if_index;
__le32 queue;
__le16 txop;
__le16 cwmin;
__le16 cwmax;
u8 aifs;
u8 pad;
u8 vif_addr[6];
} __packed;
/* TX completion event (from firmware) */
#define SV6160_MAX_TX_CMDS 16
/* Most frames we will put in one TX descriptor. This is the firmware's own
* limit (SV6160_MAX_TX_CMDS); the vendor likewise fills a descriptor with
* whatever is queued for that AC up to its max_tx_cmds.
*
* It was 8, for no better reason than keeping tx_batch[] small, and that was
* costing real throughput: uplink scales almost linearly with the batch,
* measured over two interleaved rounds at 6 MB per run --
* tx_batch=1 0.42 / 0.39 MB/s
* tx_batch=2 0.66 / 0.69 MB/s
* tx_batch=4 1.07 / 1.08 MB/s
* tx_batch=8 1.37 / 1.50 MB/s
* -- with no sign of flattening at 8.
*
* MEASURED CEILING: the firmware honours at most 9 frames per descriptor,
* NOT the 16 its own SV6160_MAX_TX_CMDS advertises. Six trials at each value,
* on a build where the cap is actually raised:
* tx_batch= 8 0/6 stalled, 1.87 MB/s
* tx_batch= 9 0/6 stalled, 1.77 MB/s (fills to 7.9 frames/descriptor)
* tx_batch=10 6/6 stalled
* tx_batch=12 6/6 stalled
* tx_batch=16 stalled, and wedged the bus hard enough that recovery failed
* A sharp cliff between 9 and 10, not a probability dial: 0/12 below, 12/12
* above.
*
* ★ THE TRAP THAT COST A DAY, AND NEARLY PUT A FALSE RETRACTION IN THIS FILE:
* tx_batch is clamped by min3(mod_tx_batch, SV6160_TX_BATCH_MAX, ...), so on a
* build with this constant at 8 the parameter ACCEPTS 16, READS BACK 16, and
* runs at 8. An attempt to replicate the ceiling on such a build found "no
* stalls at 10/12/16" over ~1173 transfers and concluded the ceiling was an
* artefact -- when in fact not one of those transfers had left batch 8. The
* tell is frames/descriptor in debugfs tx_tokens: param=8 and param=16 both
* gave 7.0, while param=2 gave 1.99. ALWAYS verify the cap actually moved
* before trusting a tx_batch result.
*
* ★★ tx_batch>9 IS A RELIABLE REPRODUCER FOR THE LINK-DEATH / SDIO WEDGE, the
* open bug that otherwise arrives hours apart with no warning. It produces
* the exact signature -- descriptors sent and never completed (tx_frames >
* tx_done_events) with tx_resyncs climbing -- and at 16 it escalates to the
* full bus wedge: "TX write failed: -16", dwmmc "Busy; trying anyway", mmc2
* "Timeout sending command", then every probe failing -16 with no netdev.
*
* Escalation measured on one of those real wedges:
* ieee80211_restart_hw untestable once probe fails (no debugfs); separately
* observed NOT clearing a softer wedge, taking it from
* 4 to 8 resyncs and 6 to 13 lost descriptors
* module reload FAILED -- probe still -16, no interface
* SDIO unbind/bind of CLEARED it -- driver probes, associates, healthy
* ff380000.mmc
* So recovery has to reach the SDIO host, not just the 802.11 stack. Note
* sv6160_trigger_recovery already calls mmc_hw_reset (dmesg shows the bus
* renegotiating 400kHz->50MHz) and that is NOT enough; only tearing down and
* re-creating the dw_mmc host brought it back. tx_resync_giveup escalates to
* exactly the path that does not work, which is why it has never helped.
*
* 9 is worth about 3% over 8 -- 45 paired trials alternating the two every
* cycle with no reload between the arms, median 1.873 -> 1.937 MB/s, 9 ahead
* in 34 of 45, zero stalls -- but it is the LAST working value, and 10 fails
* 6 times out of 6 into a wedge that needs an SDIO unbind/bind. Left at 8:
* 3% does not pay for standing on the edge of that cliff. Every array here
* scales off this constant (bodies[], batch[], tx_batch[][]; frm_status[] in
* the event is already 16), so changing it stays a one-line edit. */
/* Window over which repeated bus recoveries are counted. */
#define SV6160_RECOVER_WINDOW_MS 60000
#define SV6160_TX_BATCH_MAX 8
/* Most pieces mac80211 may hand us in one (A-)MSDU; we flatten them anyway,
* this just bounds the copy. */
#define SV6160_TX_MAX_FRAGS 8
/* Scratch buffer the TX worker builds a descriptor in. Only the 581-byte
* cmd_tx_ctrl goes here -- the frame body is written straight from skb->data in
* the second half of the same SDIO transaction -- so this does not need to
* track the RX aggregate size, which it used to be sized against. */
#define SV6160_TX_CMD_BUF 4096
/*
* TX control header prepended to data frames for the firmware.
* Packet type 0x2C = HOST_DATA in the firmware's internal protocol.
* TX control header — RPU_CMD_TX (id=7) from gamely BSP cmd_tx_ctrl.
* Sent as a 512-byte block to SDIO addr 0, followed by raw 802.11
* frame data in a separate write. The firmware's tier-1 handler
* reads frame metadata from this struct and queues for radio TX.
*
* The old sv6160_cmd_tx_ctrl (44 bytes, pkt_type=0x2C) was incorrect —
* HOST_DATA only generates event 32 (SDIO ack), no air TX.
*/
/* sizeof(struct sv6160_cmd_tx_ctrl) — must equal the vendor's
* sizeof(struct cmd_tx_ctrl) = 581. Goes on the wire as ALIGN(581,4) = 584,
* matching the vendor SDIO trace. Was 512 (the p_frame_ddr_pointer tail was
* missing), which put the frame body 72 bytes before where the firmware
* looks for it. */
#define SV6160_TX_CMD_SIZE 581
#define SV6160_MAC_HDR_SIZE 52
/* cmd_tx_ctrl.encrypt (vendor host_rpu_if.h). ENCRYPT_ENABLE is what tells
* the firmware to run CCMP/TKIP over the frame body before it goes on the
* air; with ENCRYPT_DISABLE it transmits whatever bytes we handed it. */
#define SV6160_ENCRYPT_DISABLE 0
#define SV6160_ENCRYPT_ENABLE 1
/* Layout of cmd_tx_ctrl.per_pkt_crypto_params[pkt][12] */
#define SV6160_CRYPTO_SEQ_CTRL_OFFSET 0
#define SV6160_CRYPTO_QOS_CTRL_OFFSET 2
#define SV6160_CRYPTO_IV_OFFSET 4
#define SV6160_CRYPTO_PARAMS_SIZE 12
struct sv6160_cmd_tx_ctrl {
u8 hal_data[HAL_PRIV_DATA_SIZE];
struct rpu_msg_hdr hdr; /* 28 bytes, hdr.id = RPU_CMD_TX */
u8 if_index;
u8 queue_num;
__le32 descriptor_id;
__le32 payload_length;
__le32 pkt_type; /* 0x2C = HOST_DATA */
__le32 total_length;
__le32 data_ptr;
__le32 if_id;
u8 tid;
u8 pad1;
__le16 queue_idx;
__le32 flags;
__le16 frag_count;
u8 pad2[2];
__le32 num_frames_per_desc;
__le32 pkt_length[SV6160_MAX_TX_CMDS];
u8 more_frms;
__le32 force_tx;
__le32 tx_flags;
u8 num_rates;
u8 rate_protection_type[4];
u8 rate_preamble_type[4];
u8 rate_retries[4];
u8 rate[4];
u8 rate_flags[4];
u8 num_spatial_streams[4];
u8 stbc_enabled;
u8 bcc_or_ldpc;
u8 aggregate_mpdu;
u8 encrypt;
__le32 config_mac_hdr_len;
u8 frame_source;
u8 config_mac_header[SV6160_MAC_HDR_SIZE];
__le32 frame_ddr_pointer[SV6160_MAX_TX_CMDS];
u8 per_pkt_crypto_params[SV6160_MAX_TX_CMDS][12];
/* Vendor tail: `unsigned int *p_frame_ddr_pointer[MAX_TX_CMDS]`
* (host_rpu_if.h) — an array of HOST pointers, so 8 bytes each on a
* 64-bit kernel = 128 bytes. They are host-side bookkeeping the
* firmware never dereferences, but they are part of the descriptor
* that goes on the wire, and their size is what matters: they push
* sizeof() to 581, whose ALIGN(,4) = 584 is exactly the descriptor
* length seen in the vendor SDIO trace.
*
* The firmware locates the 802.11 frame body immediately after a
* descriptor of THIS size. Omitting these 128 bytes made our
* descriptor 512, so the body landed 72 bytes early and the firmware
* consumed the whole MAC header plus the start of the auth body as
* descriptor tail — frames went out malformed and the AP never ACKed
* them (auth TX -> RETRY_LIMIT) even though RX was fine. */
__le64 p_frame_ddr_pointer[SV6160_MAX_TX_CMDS];
} __packed;
/* Must match the vendor's sizeof(struct cmd_tx_ctrl) exactly — the firmware
* uses this size to find the frame body that follows the descriptor. */
static_assert(sizeof(struct sv6160_cmd_tx_ctrl) == 581,
"TX descriptor must be 581 bytes to match vendor cmd_tx_ctrl");
/* Key management constants */
#define TOTAL_KEY_LEN 32
#define RX_SEQ_SIZE 6
@@ -422,8 +758,6 @@ struct rpu_cmd_setkey {
u8 rsc[RX_SEQ_SIZE];
} __packed;
/* TX completion event (from firmware) */
#define SV6160_MAX_TX_CMDS 16
#define TX_DONE_STAT_SUCCESS 0
#define TX_DONE_STAT_RETRY_LIM 1
#define TX_DONE_STAT_LIFETIME 2
@@ -441,6 +775,13 @@ struct rpu_event_tx_done {
} __packed;
/* Block ACK session command */
/* TX_POWER.tx_pwr. The vendor asks for 15 dBm on this board; we asked for 20,
* which was the single differing byte in that command on the wire. */
#define SV6160_DEFAULT_TX_POWER_DBM 15
#define BLOCK_ACK_SESSION_STOP 0
#define BLOCK_ACK_SESSION_START 1
struct rpu_cmd_ba_session {
struct rpu_msg_hdr hdr;
__le32 if_index;
@@ -516,17 +857,38 @@ struct sv6160_coalescing {
* Driver State
* =================================================================== */
/* rk915 shared/descriptors.h: NUM_ACS 5, NUM_TX_DESCS_PER_AC 2,
* NUM_SPARE_TX_DESCS 2 -> NUM_TX_DESCS = 12. Valid descriptor ids are 0..11. */
#define SV6160_NUM_ACS 5
#define SV6160_TX_DESCS_PER_AC 2
#define SV6160_NUM_SPARE_TX_DESCS 2
/* How long a descriptor may sit in flight before the watchdog takes it back.
* Long enough that a slow but genuine completion is never stolen (the measured
* worst TX_DONE latency is a few ms), short enough that a lost one costs a
* hiccup rather than the access category. */
#define SV6160_TX_DONE_TIMEOUT_MS 1000
#define SV6160_NUM_TX_DESCS \
((SV6160_NUM_ACS * SV6160_TX_DESCS_PER_AC) + SV6160_NUM_SPARE_TX_DESCS)
struct sv6160_softc {
struct sdio_func *func;
struct ieee80211_hw *hw;
struct device *dev;
struct mutex lock;
/* Task holding sc->lock through sv6160_lock()/the RX drain. A path
* reached from inside the drain (either entry: IRQ thread or rx_work)
* compares against current and skips the mutex instead of deadlocking
* on it -- the old current_work() test was NULL in the IRQ thread. */
struct task_struct *lock_owner;
bool is_firmware_loaded;
bool is_started;
bool is_rpu_ready;
bool recovering; /* restart_hw recovery in flight */
bool bringup_active; /* mac_start retry loop running (owns recovery) */
struct work_struct recover_work; /* runtime SDIO-wedge recovery */
struct work_struct rx_work;
struct delayed_work rx_poll;
struct sk_buff_head rx_queue;
struct sv6160_coalescing coalescing;
struct workqueue_struct *wq;
@@ -535,7 +897,219 @@ struct sv6160_softc {
struct completion chan_prog_done;
struct completion cmd_done;
int vif_index;
u32 tx_desc_id;
/* TX descriptor ids are TOKENS from a small fixed pool, not a counter.
* The firmware's table is NUM_TX_DESCS entries and it rejects anything
* outside it -- literally, in an FW_ERROR event: "[3243 F] Invalid desc
* id". A free-running counter therefore faults the firmware the moment
* it passes the end of the table, which is why TX completions stopped
* after ~11 frames. Mirrors rk915 get_token()/free_token(). */
/* Chain pointer carried by the LAST sub-packet of an RX_SERIAS batch.
* The vendor clears the IRQ and rings the notify doorbell only when this
* is zero; a non-zero value means more data is queued and must be read
* first (hal_io.c rk915_serias_read, "End of the continuous rx 1"). */
u32 serias_next_len;
/* RX pipeline accounting (debugfs "rx_stats"). Bulk throughput sits at
* a few KB/s while ping is fine, so what matters is how often the
* firmware wakes us and how much each wake actually yields. */
u32 rxs_drains; /* host-wakes serviced */
u32 rxs_pkts; /* packets handed to mac80211 */
u32 rxs_nodata; /* wake with no valid RECV_LEN */
u32 rxs_chained; /* reads beyond the first */
u32 rxs_gap_max_ms;
/* Where a drain's time actually goes: waiting for sc->lock (i.e. behind
* a TX/command CMD53) versus doing the SDIO reads. Separates "the
* firmware is not signalling" from "we are too slow to come back". */
u64 rxs_lock_us_sum;
u32 rxs_lock_us_max;
u64 rxs_busy_us_sum;
u32 rxs_busy_us_max;
/* Same question on the TX side: how long a frame spends in the write
* path, and how often the card pushes back with -EBUSY (each retry
* sleeps 20-25ms, so a handful of them stalls TCP outright). */
u32 txs_frames;
/* Frames the worker dequeued and tried to send, whether or not the
* SDIO write happened -- txs_frames only counts writes that ran. */
u32 txs_attempts;
u32 tx_max_frame_seen;
u32 txs_linearise_fail;
u32 txs_txq_pulled;
u64 txs_us_sum;
u32 txs_us_max;
u32 txs_ebusy;
/* Where the 7.4 ms of an average sv6160_sdio_write_tx() actually goes:
* waiting for sc->lock, waiting for the SDIO host, the descriptor
* CMD53, and the frame-body CMD53s. */
u64 txs_mutex_us_sum;
u64 txs_claim_us_sum;
u64 txs_desc_us_sum;
u64 txs_body_us_sum;
u64 txs_body_bytes;
/* DMA eligibility of what we hand the SDIO core. dw_mmc refuses DMA
* for a transfer whose scatterlist offset or length is not 4-byte
* aligned (dw_mci_pre_dma_transfer: "if (sg->offset & 3 ||
* sg->length & 3) return -EINVAL") and silently falls back to PIO,
* and sg->offset is just offset_in_page() of the buffer we pass.
* Counted because the uplink flips between a ~6 B/us and a ~1 B/us
* write regime with identical bus settings, and PIO fallback is the
* one host-side thing that produces exactly that ratio. */
u32 txs_body_pio; /* body writes dw_mmc must PIO */
u32 txs_desc_pio; /* descriptor writes ditto */
/* Which descriptors the stall resync had to take back, so "the firmware
* stopped completing" can be asked the obvious next questions: is it
* always the same descriptor id, always the same AC, and how long had it
* been outstanding? Per-id because a pattern only shows across many
* stalls, and they are hours apart. */
/* Deadline (jiffies) before which a descriptor id must NOT be handed out
* again, or 0 when it is free. Set when a stall resync takes an id back
* WITHOUT the firmware having completed it: the firmware still owns it
* then, and reusing it immediately is what turned one stall into a
* storm (see sv6160_get_token). */
unsigned long tx_quarantine[SV6160_NUM_TX_DESCS];
u32 txs_quarantined; /* ids held back */
u32 txs_quarantine_hits; /* allocations deflected */
u32 txs_quarantine_freed; /* released by a late completion */
/* How late a completion for a reclaimed descriptor actually was, measured
* from the moment the resync gave up on it. This is what says whether
* tx_stall_ms is set too short: if these are all a few hundred ms, the
* window is simply too tight and the "stall" is mostly our own timeout. */
u32 txs_latecomp_max_ms;
u64 txs_latecomp_sum_ms;
u32 txs_latecomp_n;
u32 txs_lost_desc[SV6160_NUM_TX_DESCS];
u32 txs_lost_ac[SV6160_NUM_ACS];
u32 txs_resync_age_max; /* ms, oldest ever lost */
/* Rate asked for vs rate the firmware reports using. */
u32 txs_ask_mcs[16];
u32 txs_ask_legacy;
u32 txs_use_mcs[16];
u32 txs_use_legacy;
u32 txs_use_none;
u32 txs_rate_match;
u32 txs_rate_nomatch;
/* Times the worker stopped ALL mac80211 queues because one AC had no
* descriptor left, and which AC caused it. */
u32 txs_qstop;
u32 txs_qstop_ac[SV6160_NUM_ACS];
/* How long a genuine TX_DONE takes, and how many arrive for a descriptor
* the watchdog already took back. If completions normally land in a few
* ms and "late" stays 0, the watchdog is only catching real losses; if
* late climbs, its timeout is stealing frames still in flight. */
u32 txs_done_ms_max;
u64 txs_done_ms_sum;
u32 txs_done_n;
u32 txs_late;
/* Does a TX_DONE actually arrive for every frame? Count the events and
* the entries our slot/desc_id matching throws away, so "the firmware
* never completed it" can be told apart from "we discarded it". */
u32 txs_done_events;
u32 txs_done_entries;
u32 txs_skip_noskb;
u32 txs_skip_descmiss;
/* Per-descriptor-id ledger, to settle the burst leak. A descriptor
* that is stuck in flight shows up as sent[id] > done[id]; seen[id]
* says whether the firmware ever sent a TX_DONE naming that id, which
* is what separates "no completion ever came back" from "one came back
* and the handler failed to match it". */
u32 txs_sent_desc[SV6160_NUM_TX_DESCS];
u32 txs_seen_desc[SV6160_NUM_TX_DESCS];
u32 txs_done_desc[SV6160_NUM_TX_DESCS];
/* When each descriptor went out, so a completion that never arrives can
* be reclaimed instead of costing that AC a slot for ever. */
unsigned long tx_desc_jiffies[SV6160_NUM_TX_DESCS];
struct delayed_work tx_resync;
/* When a TX completion last arrived, so a pipe that has gone entirely
* silent can be told from one that is merely slow. */
unsigned long last_tx_done;
u32 txs_resyncs;
u32 txs_resync_descs;
/* Consecutive resyncs with no completion in between; reset by any real
* TX_DONE and by losing the association. */
u32 txs_resync_runs;
u64 rxs_gap_sum_ms;
unsigned long rxs_last_jiffies;
unsigned long tx_token_bmp;
/* Per-AC in-flight descriptor count, and the AC each token was taken
* for (spare tokens are not AC-derivable from the id alone). */
u8 tx_outstanding_ac[SV6160_NUM_ACS];
u8 tx_token_ac[SV6160_NUM_TX_DESCS];
/* Guards tx_token_bmp / tx_token_ac / tx_outstanding_ac / tx_quarantine.
* get_token runs in the TX worker, free_token from the IRQ-thread drain
* and the resync work, and a lost ++/-- on a per-AC count is permanent:
* the AC either sits at its limit with nothing in flight (get_token
* refuses it for good) or admits more than the firmware tolerates. */
spinlock_t tx_token_lock;
/* Set by the worker just before it publishes a descriptor, cleared when
* sv6160_sdio_write_tx() returns. A reclaim path that sees it leaves
* that descriptor alone: the CMD53 is still reading those skbs. */
bool tx_writing[SV6160_NUM_TX_DESCS];
u32 txs_bulk_done; /* event-32 bulk completions seen */
/* Control-command flow control, mirroring the vendor's rpu_send()
* (rk915 src/rpu_if.c:755): never put more than
* SV6160_MAX_OUTSTANDING_CTRL_REQ control commands on the bus at once.
* Further commands queue on cmd_pending and are released as
* RPU_EVENT_COMMAND_PROC_DONE retires the earlier ones. Without this
* we wrote every command immediately, so a command could land while
* the LMAC was still busy with the previous one. */
#define SV6160_MAX_OUTSTANDING_CTRL_REQ 2
spinlock_t cmd_gate_lock;
unsigned int cmd_inflight;
struct sk_buff_head cmd_pending;
unsigned long cmd_sent_jiffies;
u32 cmd_proc_done_count;
u32 cmd_gate_queued;
u32 cmd_gate_stalls;
/* Times a command send cancelled a merely-QUEUED RX drain. The wake
* itself survives (gpio_irq_pending is a latch and the host-wake IRQ
* is level-triggered) -- see __sv6160_rpu_write_cmd. Kept as the
* tripwire for that window, which has never been observed to open. */
u32 cmds_rx_cancelled;
/* Per-event-id census: how many arrived and in what size range. */
#define SV6160_EV_CENSUS_MAX 48
u32 evs_count[SV6160_EV_CENSUS_MAX];
u16 evs_minlen[SV6160_EV_CENSUS_MAX];
u16 evs_maxlen[SV6160_EV_CENSUS_MAX];
u32 evs_out_of_range;
u32 txs_done_short;
u16 txs_done_short_len;
#define SV6160_CMD_CENSUS_MAX 112
/* Sequence numbers for the ordered trace (mod_trace). */
#define SV6160_TRACE_EVENTS 260
#define SV6160_TRACE_CMDS 120
#define SV6160_TRACE_TX 80
#define SV6160_TRACE_DRAINS 200
u32 rxs_oversize;
u32 rxs_nomem;
/* One persistent RX aggregate buffer, like the vendor's
* rx_serias_buf: every chain read lands here, so no SDIO read ever
* depends on an allocation succeeding. */
u8 *rx_buf;
u32 evs_seq;
u32 cmds_seq;
u32 txs_trace_seq;
u32 rxs_trace_seq;
int trace_gen;
u32 cmds_by_id[SV6160_CMD_CENSUS_MAX];
u32 cmds_out_of_range;
/* Multicast addresses currently programmed into the LMAC, so they can
* be removed again on the next prepare_multicast (vendor mc_filters). */
u8 mc_filters[SV6160_MCST_ADDR_LIMIT][6];
int mc_filter_count;
u32 mc_filter_mode; /* 0xFF = unset */
u32 use_short_slot; /* real ERP slot value */
/* Snapshot taken by the atomic .prepare_multicast, applied later by
* .configure_filter where sleeping is allowed. */
u8 mc_pending[SV6160_MCST_ADDR_LIMIT][6];
int mc_pending_count;
bool mc_pending_valid;
struct delayed_work cmd_gate_work;
struct delayed_work fwpeek_work;
/* Sub-command of the fw-priv request currently in flight. The reply
* (event 28) carries no type field, so the decoder has to be told what
* was asked for. Only the fwpeek worker issues these, one at a time
* with a sleep in between, so a plain field is enough. */
u32 fw_info_type;
/* TX deferred work (mac_tx runs in softirq, SDIO needs process ctx) */
struct sk_buff_head tx_queue;
@@ -544,38 +1118,110 @@ struct sv6160_softc {
/* TX completion tracking */
#define SV6160_TX_PENDING_MAX 64
struct sk_buff *tx_pending[SV6160_TX_PENDING_MAX];
/* Frames 1..n-1 of a batched descriptor. Frame 0 stays in
* tx_pending[] and remains the single ownership token that TX_DONE and
* the stall resync race for with cmpxchg; whoever claims it owns these
* too, so the batching needs no new locking. */
struct sk_buff *tx_batch[SV6160_NUM_TX_DESCS][SV6160_TX_BATCH_MAX - 1];
u8 tx_batch_n[SV6160_NUM_TX_DESCS];
u32 tx_pending_desc[SV6160_TX_PENDING_MAX]; /* desc_id owning each slot (verify on completion) */
atomic_t tx_outstanding;
/* Power management */
bool is_suspended;
bool ps_enabled;
struct delayed_work idle_work;
unsigned long last_activity;
/* DW MMC controller registers (for debug diagnostics) */
void __iomem *dwmmc_regs;
/* Power save. There is no firmware command for it: the vendor's
* rpu_prog_ps_state() is a bare `return 0;` and its whole session SDIO
* trace contains no RPU_CMD_PS. The entire mechanism is the PM bit in
* outgoing frames -- the AP then buffers for us and the chip can doze
* between DTIMs. mac80211 drives the state through IEEE80211_CONF_PS
* once we advertise IEEE80211_HW_SUPPORTS_PS, and only ever enables it
* if userspace asks for it (`iw dev X set power_save on`). */
bool ps_doze;
u32 ps_pm_frames; /* frames sent with PM set */
u32 ps_transitions; /* awake <-> doze changes */
/* TX retry accounting. The firmware reports a per-frame retry count in
* TX_DONE; aggregating it says whether slow uplink is airtime (retries)
* or the SDIO write path. */
u32 txs_retry_hist[8];
u64 txs_retry_sum;
u64 txs_retry_n;
u32 txs_tx_failed; /* frm_status != SUCCESS */
/* GPIO interrupt */
int host_wake_irq;
bool gpio_irq_pending; /* GPIO fired, data ready */
bool gpio_irq_disabled; /* level IRQ disabled by handler */
u32 gpio_irq_count; /* total GPIO IRQs received */
/* debugfs */
struct dentry *debugfs_dir;
/* Smart RECV_LEN polling — detect stale vs new data without GPIO */
u16 last_recv_len; /* RECV_LEN from previous poll */
u16 last_recv_len; /* RECV_LEN of the last drained aggregate */
/* After an RX_SERIAS batch the firmware re-presents the batch's FIRST
* sub-packet length on a later lone host-wake, with no data behind it.
* Measured twice: a 352B batch of (204,28,28,28) was followed ~690ms
* later by a wake advertising 204, and a 1024B batch of (408,28,28,28)
* by one advertising 408. Reading the absent bytes times out and wedges
* the bus. last_recv_len cannot catch this -- it holds the aggregate,
* not the sub-packet -- so remember the one length that actually gets
* re-presented. */
bool recv_len_failed; /* last CMD53 at this RECV_LEN timed out */
/* SDIO bus wedge tracking — a -110 CMD53 read timeout (stale RECV_LEN)
* or a persistent -16/-EBUSY leaves the DW MMC controller with DAT0
* stuck; every later op returns -16. The low-level I/O helpers set this
* so bring-up (and future runtime paths) can trigger the vendor-style
* mmc_hw_reset recovery (sv6160_sdio_fw_reboot) and retry. */
bool sdio_wedged;
/* Rolling window used to tell "one bad moment" from "restart_hw is not
* fixing this" -- see sv6160_trigger_recovery. */
unsigned long recover_window;
u32 recover_count;
/* mac80211 state */
struct ieee80211_vif *vif;
/* Copy of vif->addr, taken in .add_interface while the VIF is alive.
* VIF_CFG is also sent from paths that run during VIF teardown, where
* dereferencing sc->vif rebooted the board; and wiphy->perm_addr is NOT
* this address -- NetworkManager randomises the MAC per connection, so
* perm_addr differs from the address actually on the air on every run. */
u8 vif_addr[ETH_ALEN];
/* BSSID the group key was filed under, kept because mac80211 clears
* bss_conf.bssid before deleting the keys on a disconnect. */
u8 key_bssid[ETH_ALEN];
/* Connection-quality monitoring.
* mac80211's software CQM is driven purely by beacons from the
* associated AP (ieee80211_handle_beacon_sig). This firmware delivers
* NO beacons once it enters its connected-STA regime -- measured: the
* last RXCH: BCN arrives during the pre-association scan and not one
* after it -- so count_beacon_signal stays 0, no threshold event is
* ever raised, and a supplicant never learns the link has weakened.
* That is why autonomous roaming never triggered while forced roams
* worked. We run CQM ourselves off the RSSI of frames actually
* received from the AP. The BSSID is snapshotted rather than read
* back through sc->vif, because the RX path must never dereference a
* VIF that may be tearing down (see vif_addr above). */
u8 cqm_bssid[ETH_ALEN];
s32 cqm_thold; /* dBm; 0 = CQM not configured */
u32 cqm_hyst; /* dB */
int cqm_avg_q3; /* EWMA of RSSI, 1/8 dBm units */
bool cqm_avg_valid;
int cqm_last_event; /* 0 none, -1 low, +1 high */
u32 cqm_events; /* debug: events raised */
u32 cqm_samples; /* debug: frames sampled */
struct ieee80211_channel channels[SV6160_NUM_CHANNELS];
struct ieee80211_rate rates[12];
struct ieee80211_supported_band band_2ghz;
u32 rx_filter;
bool connecting; /* AP picked, not yet associated */
u8 bcn_rcv_mode; /* last RCV_* beacon mode sent (0xFF=unset) */
u8 cur_channel; /* last channel programmed (for VIF op_channel) */
struct ieee80211_scan_request *scan_request;
bool scan_in_progress;
bool operating; /* a BSSID is programmed (connecting/associated) — hold the operating channel, don't sweep off it */
bool assoc; /* association completed (STA_CONN sent) */
int scan_ch_idx; /* current channel in sweep */
struct delayed_work scan_work; /* channel-sweep scan worker */
struct delayed_work scan_timeout;
@@ -601,6 +1247,9 @@ int sv6160_sdio_writeb(struct sv6160_softc *sc, u8 addr, u8 val);
int sv6160_sdio_readb(struct sv6160_softc *sc, u8 addr, u8 *val);
int sv6160_sdio_write_data(struct sv6160_softc *sc, u32 addr,
void *buf, size_t len);
int sv6160_sdio_write_tx(struct sv6160_softc *sc, void *desc, size_t desc_len,
u8 *bounce,
struct sk_buff **bodies, int n_bodies);
int sv6160_sdio_read_data(struct sv6160_softc *sc, u32 addr,
void *buf, size_t len);
@@ -609,11 +1258,10 @@ int sv6160_rpu_send_cmd(struct sv6160_softc *sc, void *cmd, size_t len,
u32 id);
int sv6160_rpu_reset(struct sv6160_softc *sc);
int sv6160_rpu_fw_priv_init(struct sv6160_softc *sc);
int sv6160_rpu_patch_feature(struct sv6160_softc *sc, u32 feature_val);
int sv6160_rpu_fw_priv_nop(struct sv6160_softc *sc);
int sv6160_rpu_phy_thresh(struct sv6160_softc *sc);
int sv6160_rpu_tx_power(struct sv6160_softc *sc, u32 power_dbm);
int sv6160_rpu_ps_config(struct sv6160_softc *sc, int mode,
u32 idle_timeout, u32 listen_interval);
int sv6160_rpu_add_vif(struct sv6160_softc *sc, const u8 *mac_addr, int mode);
int sv6160_rpu_remove_vif(struct sv6160_softc *sc);
int sv6160_rpu_scan(struct sv6160_softc *sc,
@@ -634,6 +1282,7 @@ void sv6160_rpu_process_rx_batch(struct sv6160_softc *sc, struct sk_buff *skb);
/* Firmware & Core */
int sv6160_boot_firmware(struct sv6160_softc *sc);
int sv6160_sdio_fw_reboot(struct sv6160_softc *sc);
int sv6160_core_init(struct sv6160_softc *sc);
void sv6160_core_exit(struct sv6160_softc *sc);
int sv6160_get_sdio_blksize(void);
@@ -641,11 +1290,17 @@ int sv6160_get_sdio_blksize(void);
/* Data Path */
int sv6160_hci_tx(struct sv6160_softc *sc, struct sk_buff *skb, bool is_cmd);
void sv6160_rx_worker(struct work_struct *work);
void sv6160_rx_drain(struct sv6160_softc *sc);
/* Queue Control */
void sv6160_stop_queues(struct sv6160_softc *sc);
void sv6160_start_queues(struct sv6160_softc *sc);
/* Last-resort wedge recovery: ask the driver core to re-create the dw_mmc host
* that owns our card. Takes the sdio_func, not the softc, because the wedge
* that most needs it is the one where PROBE fails -16 and no softc exists. */
bool sv6160_rebind_sdio_host(struct sdio_func *func);
/* PM Support */
void sv6160_notify_pm(struct sv6160_softc *sc, int wakeup);
File diff suppressed because it is too large. Load diff
@@ -6,8 +6,11 @@
#include <linux/module.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/host.h>
#include <linux/mmc/core.h>
#include <linux/pm_runtime.h>
#include <linux/delay.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>
@@ -21,33 +24,31 @@ static const struct sdio_device_id sv6160_id_table[] = {
};
MODULE_DEVICE_TABLE(sdio, sv6160_id_table);
/* GPIO interrupt handler — level-triggered (DTS: IRQ_TYPE_LEVEL_HIGH).
* Fires whenever GPIO is HIGH (data available). MUST disable_irq on
* EVERY call to prevent IRQ storms — level-triggered fires continuously
* while pin is HIGH. Re-enabled by rx_worker after clear+notify. */
static irqreturn_t sv6160_gpio_irq_handler(int irq, void *dev_id)
/* Threaded OOB host-wake IRQ (vendor rk915 model).
* Registered with a NULL primary handler + IRQF_ONESHOT, so the kernel masks
* the level line when it asserts, runs THIS in thread context, and unmasks it
* only when we return — after we have drained the aggregate and clear+notify'd
* the firmware (which de-asserts the line). This is the vendor's low-latency,
* kernel-managed masking model, replacing the old hardirq + workqueue + manual
* disable_irq/enable_irq scheme. */
static irqreturn_t sv6160_gpio_irq_thread(int irq, void *dev_id)
{
struct sv6160_softc *sc = dev_id;
/* Always disable to prevent level-triggered IRQ storm.
* Even before firmware is loaded, GPIO may be HIGH. */
disable_irq_nosync(irq);
if (sc && sc->is_firmware_loaded) {
sc->gpio_irq_disabled = true;
sc->gpio_irq_count++;
sc->gpio_irq_pending = true;
/* Reset stale guard so same-size events can be read.
* BUT if the last read failed (-110), the RECV_LEN is
* genuinely stale — don't reset, let the guard block it.
* The -110 handler sends clear+notify which deasserts GPIO.
* If GPIO re-fires despite recv_len_failed, the firmware
* has new data at a different RECV_LEN which will pass
* the guard naturally. */
if (!sc->recv_len_failed)
sc->last_recv_len = 0;
schedule_work(&sc->rx_work);
/* Nothing to drain into yet (firmware being uploaded, core_init not done)
* or the host is on its way into suspend: leave the wake where it is.
* The line is level-high and ONESHOT, so returning re-fires this thread
* as soon as it is unmasked; the sleep turns that spin into a 1 ms poll
* for the few ms either window lasts. Draining while suspended did
* CMD53s against a host being clock-gated and set sdio_wedged. */
if (!sc || !sc->is_firmware_loaded || sc->is_suspended) {
usleep_range(1000, 2000);
return IRQ_HANDLED;
}
sc->gpio_irq_count++;
dev_dbg(&sc->func->dev, "GPIOIRQ #%u\n", sc->gpio_irq_count);
sc->gpio_irq_pending = true;
sv6160_rx_drain(sc);
return IRQ_HANDLED;
}
@@ -62,18 +63,19 @@ static void sv6160_sdio_irq_handler(struct sdio_func *func)
if (sc && sc->is_firmware_loaded) {
sc->gpio_irq_count++; /* reuse counter for diagnostics */
sc->gpio_irq_pending = true;
if (!sc->recv_len_failed)
sc->last_recv_len = 0;
/* Do NOT reset last_recv_len — same reasoning as GPIO
* handler. Only rpu_send_cmd resets the stale guard
* (after sending a command that expects a response). */
schedule_work(&sc->rx_work);
}
}
/*
* SDIO device initialization — matches vendor rk915 BSP protocol:
* - Block size 512 (not 128)
* - CCCR interrupt enable
* - SDIO in-band interrupt mode (DATA1 line, NOT GPIO)
* - Function-specific interrupt enable
* SDIO device initialization — matches vendor rk915 BSP sdio_device_init():
* - CCCR 0x04 = 0x07 (interrupt enable, all functions + master)
* - CCCR 0x16 = 0x80 (route IRQ to the host-wake GPIO, not in-band DAT1)
* - Block size 512 in the core-negotiated 4-bit mode (bus width untouched)
* - reg34/reg33 = 0x02 (enable host interrupt generation), clear reg32
*/
static int sv6160_sdio_device_init(struct sdio_func *func)
{
@@ -87,12 +89,29 @@ static int sv6160_sdio_device_init(struct sdio_func *func)
if (error)
dev_warn(&func->dev, "CCCR IEN write failed: %d\n", error);
/* Do NOT set CCCR 0x16=0x80 (GPIO mode). Leave the firmware in
* its default SDIO in-band interrupt mode (DATA1 line). GPIO IRQ
* was observed to fire only during boot (4 edges), never for
* command responses or RX data. SDIO in-band interrupts are the
* standard mechanism and should work for all event types.
* Register sdio_claim_irq() in probe instead. */
/* Switch chip to GPIO interrupt mode (gamely BSP requirement).
* MUST be set BEFORE firmware boot — the firmware reads this
* during init to decide whether to signal via GPIO or SDIO DATA1.
* Without this, WiFi RX frame events may never reach the host
* even though command responses work via SDIO in-band. */
sdio_f0_writeb(func, 0x80, 0x16, &error);
if (error)
dev_warn(&func->dev, "CCCR 0x16 GPIO mode write failed: %d\n",
error);
else
dev_info(&func->dev, "CCCR 0x16=0x80: GPIO interrupt mode enabled\n");
/* Keep the core-negotiated 4-BIT bus width for the data path — this is
* what the vendor rk915 sdio_device_init() does (it never touches bus
* width). The vendor's 1-bit switch lives in sdio_disable_wide(), a
* SUSPEND-only path (io_ejtag) — "devices that remain active during a
* system suspend are put back into 1-bit mode". An earlier revision
* here force-switched to 1-bit at init after misreading that suspend
* path as the init path; 1-bit made the SDIO data path fragile
* (intermittent -110 CMD53 read timeouts that permanently wedge the DW
* MMC controller into -16/-EBUSY). The OOB host-wake GPIO IRQ we rely
* on is a separate physical line, independent of SDIO data bus width,
* so 4-bit does not affect async host-wake delivery. */
/* Set block size (configurable via sdio_blksize param, default 512) */
{
@@ -122,30 +141,85 @@ static int sv6160_sdio_device_init(struct sdio_func *func)
return 0;
}
/* PM Suspend/Resume */
/*
* Re-boot the firmware from cold — mirrors the vendor's down_fw_in_probe=0
* model. The vendor downloads+starts the firmware at .start (interface up),
* immediately before RPU_CMD_RESET, so RESET always runs on a freshly-booted
* MCU. Our probe boots at insmod; by the time mac_start runs RESET the MCU
* has been running a while and (measured) the firmware's async host-wake gate
* (tx_enabled) is shut after our RESET while the vendor's is open. Resetting
* the MCU to WAIT_FW and re-uploading right before RESET replicates the vendor.
*
* The OOB host-wake GPIO IRQ is a separate GPIO line and survives the card
* reset; only the in-band SDIO IRQ is card-bound, and we do not depend on it.
*/
int sv6160_sdio_fw_reboot(struct sv6160_softc *sc)
{
struct sdio_func *func = sc->func;
int ret;
sc->is_firmware_loaded = false;
sdio_claim_host(func);
ret = mmc_hw_reset(func->card);
if (ret)
dev_warn(&func->dev, "fw_reboot: mmc_hw_reset failed: %d\n", ret);
func->enable_timeout = jiffies_to_msecs(HZ);
ret = sdio_enable_func(func);
sdio_release_host(func);
if (ret) {
dev_err(&func->dev, "fw_reboot: sdio_enable_func failed: %d\n", ret);
return ret;
}
ret = sv6160_sdio_device_init(func);
if (ret) {
dev_err(&func->dev, "fw_reboot: device_init failed: %d\n", ret);
return ret;
}
ret = sv6160_boot_firmware(sc);
dev_info(&func->dev, "fw_reboot: fresh firmware boot ret=%d\n", ret);
if (!ret)
sc->is_firmware_loaded = true; /* IRQ paths may drain again */
return ret;
}
/* PM Suspend/Resume
*
* These had never executed once before 2026-09-12: ROCKNIX's idle "suspend" is
* /usr/bin/rocknix-fake-suspend, which only freezes and thaws processes and
* never writes /sys/power/state, so the kernel PM path -- and therefore these
* callbacks -- was never entered on this platform. They are logged because
* there is otherwise no way to tell whether they ran at all.
*/
static int __maybe_unused sv6160_pm_suspend(struct device *dev)
{
struct sdio_func *func = dev_to_sdio_func(dev);
struct sv6160_softc *sc = sdio_get_drvdata(func);
mmc_pm_flag_t flags = MMC_PM_KEEP_POWER;
int ret;
if (!sc || !sc->is_firmware_loaded)
return 0;
dev_info(sc->dev, "PM suspend: started=%d assoc=%d\n",
sc->is_started, sc->assoc);
sc->is_suspended = true;
cancel_delayed_work_sync(&sc->idle_work);
cancel_delayed_work_sync(&sc->rx_poll);
cancel_work_sync(&sc->rx_work);
sv6160_stop_queues(sc);
sv6160_rpu_ps_config(sc, PS_MODE_ENABLED, 200, 3);
sv6160_notify_pm(sc, 0); /* sleep */
if (device_may_wakeup(dev))
flags |= MMC_PM_WAKE_SDIO_IRQ;
return sdio_set_host_pm_flags(func, flags);
ret = sdio_set_host_pm_flags(func, flags);
dev_info(sc->dev, "PM suspend: keep_power%s -> %d\n",
(flags & MMC_PM_WAKE_SDIO_IRQ) ? "+wake_sdio_irq" : "", ret);
return ret;
}
static int __maybe_unused sv6160_pm_resume(struct device *dev)
@@ -156,16 +230,16 @@ static int __maybe_unused sv6160_pm_resume(struct device *dev)
if (!sc || !sc->is_firmware_loaded)
return 0;
dev_info(sc->dev, "PM resume: started=%d assoc=%d\n",
sc->is_started, sc->assoc);
sc->is_suspended = false;
sv6160_notify_pm(sc, 1); /* wakeup */
sv6160_rpu_ps_config(sc, PS_MODE_DISABLED, 0, 0);
sv6160_start_queues(sc);
sc->last_activity = jiffies;
if (sc->is_started) {
schedule_work(&sc->rx_work);
schedule_delayed_work(&sc->rx_poll, msecs_to_jiffies(10));
schedule_delayed_work(&sc->idle_work, msecs_to_jiffies(5000));
}
return 0;
@@ -195,6 +269,24 @@ static int sv6160_probe(struct sdio_func *func,
}
sdio_claim_host(func);
/*
* Reset the MCU to the WAIT_FW state before uploading firmware.
* On a warm start — a driver reload, or a prior driver (e.g. the
* rk915 BSP port) that left the MCU running its firmware — the chip
* is well past WAIT_FW, and the very first firmware-upload CMD53 write
* to SDIO addr 0 times out (-110) because the running firmware is not
* listening for an upload. mmc_hw_reset() re-runs the SDIO pwrseq
* (toggles the chip reset GPIO) so the MCU comes up cold. The vendor
* rk915 driver does the same in its probe/power-cycle path. Must be
* called with the host claimed (it does not self-claim).
*/
ret = mmc_hw_reset(func->card);
if (ret)
dev_warn(&func->dev, "mmc_hw_reset failed: %d (continuing)\n", ret);
/* the CIS re-parse after reset can leave a bogus 0 ms enable timeout */
func->enable_timeout = jiffies_to_msecs(HZ);
ret = sdio_enable_func(func);
if (ret) {
dev_err(&func->dev, "sdio_enable_func failed: %d\n", ret);
@@ -215,8 +307,43 @@ static int sv6160_probe(struct sdio_func *func,
/* Full SDIO device initialization (block size, interrupts, etc) */
ret = sv6160_sdio_device_init(func);
if (ret)
if (ret) {
/* A bare -110 here is almost always one specific thing, and it
* cost an afternoon to pin down: the system went through a real
* (deep) suspend while NO driver was bound to this function.
* Nothing then requested MMC_PM_KEEP_POWER, and on resume the
* mmc2 host is never re-initialised at all -- the resume log
* shows bus-speed/tuning lines for the storage host and none
* for this one -- so the card is unreachable. The
* mmc_hw_reset() above returns success and does not help,
* because the problem is the host, not the card. Reloading the
* module does not clear it either.
*
* Recovery is to power-cycle the controller:
* echo ff380000.mmc > /sys/bus/platform/drivers/dwmmc_rockchip/unbind
* echo ff380000.mmc > /sys/bus/platform/drivers/dwmmc_rockchip/bind
* Keeping the driver loaded across suspend avoids it entirely;
* that path is tested and works (link and IP survive).
*/
if (ret == -ETIMEDOUT)
dev_err(&func->dev,
"SDIO init timed out (-110). If the system suspended with this driver unloaded, the mmc host was not resumed; power-cycle it with unbind/bind on dwmmc_rockchip, or keep the driver loaded across suspend.\n");
/* Do NOT try to escalate to sv6160_rebind_sdio_host() here. It
* looks like the right place and it cannot work: once the bus is
* hard-wedged this probe is never entered at all. sdio_bus_probe()
* calls sdio_set_block_size() before drv->probe, that CMD52 fails
* -EBUSY, and the core logs "probe with driver sv6160 failed with
* error -16" without ever calling us -- verified on hardware, the
* failing reloads have no probe entry line in dmesg.
*
* The driver can only rescue the host while it still HOLDS the
* device, so the escalation lives in the bring-up retry path
* instead. A driver that has been rmmod'ed on a wedged bus is
* already past helping itself; that state needs the unbind/bind
* below, by hand. (It is also not something production does --
* only a test harness reloads a wedged driver.) */
goto err_disable;
}
/* Allocate mac80211 hardware struct */
hw = ieee80211_alloc_hw(sizeof(struct sv6160_softc), &sv6160_ops);
@@ -231,23 +358,6 @@ static int sv6160_probe(struct sdio_func *func,
sc->dev = &func->dev;
mutex_init(&sc->lock);
/* Map the DW MMC controller CTRL register for FIFO/DMA reset.
* The SDIO host controller's parent device has the MMIO resource.
* DW MMC CTRL register is at offset 0x000 from the controller base. */
{
struct device *host_dev = func->card->host->parent;
struct resource *res;
res = platform_get_resource(to_platform_device(host_dev), IORESOURCE_MEM, 0);
if (res) {
sc->dwmmc_regs = devm_ioremap(&func->dev, res->start, 0x100);
if (sc->dwmmc_regs)
dev_info(&func->dev, "DW MMC regs mapped at %pa\n",
&res->start);
else
dev_warn(&func->dev, "Failed to map DW MMC regs\n");
}
}
sdio_set_drvdata(func, sc);
@@ -278,9 +388,21 @@ static int sv6160_probe(struct sdio_func *func,
}
if (sc->host_wake_irq > 0) {
ret = devm_request_irq(&func->dev, sc->host_wake_irq,
sv6160_gpio_irq_handler,
IRQF_NO_SUSPEND,
/* Vendor model: THREADED IRQ, NULL primary + IRQF_ONESHOT.
* The DTS trigger (LEVEL_HIGH) is kept; the kernel masks the
* level line on assert and unmasks after the thread drains
* and ACKs the firmware. No IRQF_NO_SUSPEND: it is documented as
* incompatible with the enable_irq_wake() below (suspend-and-
* interrupts.rst), and it kept the thread draining a suspended
* host. With the wake armed the PM core does NOT mask the line
* for the suspend -- suspend_device_irq() takes the
* irqd_is_wakeup_set() branch, sets IRQD_WAKEUP_ARMED and returns
* before any __disable_irq(). The first assertion after that is
* what disables it, marks it pending and aborts the suspend in
* progress. The thread also refuses to drain while is_suspended. */
ret = devm_request_threaded_irq(&func->dev, sc->host_wake_irq,
NULL, sv6160_gpio_irq_thread,
IRQF_ONESHOT,
"sv6160", sc);
if (ret) {
dev_warn(&func->dev, "GPIO IRQ %d failed: %d\n",
@@ -288,13 +410,17 @@ static int sv6160_probe(struct sdio_func *func,
sc->host_wake_irq = 0;
} else {
enable_irq_wake(sc->host_wake_irq);
dev_info(&func->dev, "GPIO IRQ %d registered (level-triggered)\n",
dev_info(&func->dev, "GPIO IRQ %d registered (threaded, ONESHOT)\n",
sc->host_wake_irq);
}
}
}
/* Boot firmware and register with mac80211 */
/* Boot firmware and register with mac80211. Both IRQ paths are already
* registered and gate on is_firmware_loaded, which core_init raises only
* once the drain has its buffer, works and completion to land in. It
* used to flip inside boot_firmware, before any of that existed, so an
* early host-wake could drain into a NULL rx_buf. */
ret = sv6160_boot_firmware(sc);
if (ret == 0)
ret = sv6160_core_init(sc);
@@ -305,6 +431,35 @@ static int sv6160_probe(struct sdio_func *func,
return 0;
err_free:
/* Tear the interrupts down BEFORE ieee80211_free_hw(), which frees sc --
* both handlers take sc as their data.
*
* The GPIO IRQ is devm-managed, so it would otherwise stay live until the
* device unbinds, and that happens only after probe returns: a host-wake
* arriving in that window would run the threaded handler against freed
* memory. The in-band SDIO IRQ is not devm-managed at all, and leaving it
* claimed is why the load after a failed probe reports
* "sdio_claim_irq failed: -16" and silently drops to GPIO-only. Observed
* exactly that after a probe that failed on a missing firmware file.
*
* sdio_release_irq() is safe even when the claim above failed; it is a
* no-op on the handler and just clears the CCCR enable bit.
*/
if (sc->host_wake_irq > 0) {
disable_irq_wake(sc->host_wake_irq);
devm_free_irq(&func->dev, sc->host_wake_irq, sc);
}
sdio_claim_host(func);
sdio_release_irq(func);
sdio_release_host(func);
/* Freeing the IRQs synchronises their handlers but does not flush a
* work item one of them already queued (the in-band handler and the
* drain's OOM re-arm both schedule rx_work), and core_init has run far
* enough to have INIT_WORK'd it whenever the failure came from
* register_hw. */
sc->is_firmware_loaded = false;
cancel_work_sync(&sc->rx_work);
pm_runtime_disable(&func->dev);
ieee80211_free_hw(hw);
err_disable:
@@ -321,13 +476,29 @@ static void sv6160_remove(struct sdio_func *func)
if (!sc)
return;
sv6160_core_exit(sc);
/* GPIO IRQ is freed automatically by devm */
pm_runtime_disable(&func->dev);
/* Stop both handlers dispatching BEFORE core_exit, whose last statement is
* ieee80211_unregister_hw(): an event drained in that window reaches
* handlers that call into a wiphy being torn down (SCAN_COMPLETE ->
* ieee80211_scan_completed() after wiphy_unregister()'s final cancel).
* Clearing the flag is enough and costs nothing here -- the only command
* the teardown sends, remove_vif, is fire-and-forget and waits for no
* reply. */
sc->is_firmware_loaded = false;
sv6160_core_exit(sc);
/* Now free them for real, still BEFORE ieee80211_free_hw() frees sc: devm
* would do it only after this function returns, i.e. after the softc is
* gone, and on the rung-2 host re-create that runs this remove() the level
* line is typically stuck high with the thread mid-drain. */
if (sc->host_wake_irq > 0) {
disable_irq_wake(sc->host_wake_irq);
devm_free_irq(&func->dev, sc->host_wake_irq, sc);
}
sdio_claim_host(func);
sdio_release_irq(func);
sdio_release_host(func);
cancel_work_sync(&sc->rx_work); /* an in-band IRQ may have re-queued it */
pm_runtime_disable(&func->dev);
ieee80211_free_hw(sc->hw);
+828 -803
View File
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
"""Shared read/verify/apply/write logic for the firmware binary patch scripts.
Each patch is (name, file_offset, expected_original_bytes, replacement_bytes).
Every site is verified against its expected original bytes before anything is
written; a mismatch aborts (the firmware image is not the one the offsets
describe).
"""
import hashlib
import sys
def apply_patches(patches, src, dst):
data = bytearray(open(src, "rb").read())
print(f"in : {src} ({len(data)} bytes, md5 {hashlib.md5(data).hexdigest()})")
for name, off, orig, _repl in patches:
got = bytes(data[off:off + len(orig)])
if got != orig:
sys.exit(f"ABORT {name}: @0x{off:X} expected {orig.hex()} got {got.hex()}")
for name, off, orig, repl in patches:
data[off:off + len(repl)] = repl
print(f" applied {name}: @0x{off:X} {orig.hex()} -> {repl.hex()}")
open(dst, "wb").write(data)
print(f"out: {dst} ({len(data)} bytes, md5 {hashlib.md5(data).hexdigest()})")
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Apply the "MAC-stays-enabled" RX-arming firmware patch to ssv6160-fw.bin.
Connected-mode RX on this firmware requires the MAC/PHY to be enabled
(wifi_mac_enable, fcn.02000898). Only the scan path enables it — the scan
handler / scan-stop call wifi_mac_enable(1) then wifi_mac_enable(0), so after
any scan the MAC/PHY is powered DOWN and a fixed-channel connect finds a deaf
receiver (RPU_CMD_CHANNEL never re-enables it). These patches turn the scan's
two wifi_mac_enable(0) DISABLE calls into enable(1), so a scan leaves the
MAC/PHY powered, plus keep the RF PLL tuned across scan-stop (P2):
M1 scan_handler exit wifi_mac_enable(0) -> (1) (li a0,0 -> li a0,1)
M2 scan_stop wifi_mac_enable(0) -> (1) (li a0,0 -> li a0,1)
P2 scan_stop RF_PLL-clear -> nop (keep RF tuned after scan)
Verified on hardware (SV6160/RK915, RK3326): with this fw AND the sv6160
driver's connect_fix=9 (bit0 scan-hold + bit3 1-channel arm-scan on the
operating channel), the CONNECTED-MODE RECEIVER ARMS — beacons arrive on the
operating channel after discovery. Multi-channel scan still works (do NOT add
P1 @0x782 or P3 @0x8CE — the full P1/P2/P3 set breaks scan/GPIO).
KNOWN LIMITATION (not fixed): the auth/assoc TX is still not ACKed by the AP
(TX_DONE=RETRY_LIMIT) — connected-mode TX needs the firmware's PHY-ready gate
(0x42048C00 & 0x100, in the CMD_CHANNEL worker) to pass, which it does not for
this clean-room driver. So this arms RX but does not yet complete association.
Usage:
python3 gen_fw_macfix.py [in=firmware/ssv6160-fw.bin] [out=firmware/ssv6160-fw-macfix.bin]
"""
import sys
from fw_patch_common import apply_patches
# (name, file_offset, expected_original, replacement)
PATCHES = [
("M1 scan_handler wifi_mac_enable(0)->(1)", 0x7AD6,
bytes([0x01, 0x45]), bytes([0x05, 0x45])),
("M2 scan_stop wifi_mac_enable(0)->(1)", 0x7AFE,
bytes([0x01, 0x45]), bytes([0x05, 0x45])),
("P2 scan_stop RF_PLL-clear -> nop", 0x7AFA,
bytes([0x23, 0x2a, 0x07, 0x02]), bytes([0x13, 0x00, 0x00, 0x00])),
]
def main():
src = sys.argv[1] if len(sys.argv) > 1 else "firmware/ssv6160-fw.bin"
dst = sys.argv[2] if len(sys.argv) > 2 else "firmware/ssv6160-fw-macfix.bin"
apply_patches(PATCHES, src, dst)
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""
Apply the §7 firmware binary patches to ssv6160-fw.bin.
These are RISC-V instruction NOPs that fix two firmware bugs the driver
otherwise has to work around from the host side (see firmware/README.md §5-§7):
P1/P2 RF_PLL persistence: the firmware zeroes the RF PLL synthesizer
(0x42000034) on rf_enable_disable and on scan_stop. NOP'ing both
keeps the radio tuned so RPU_CMD_CHANNEL / post-scan TX land on the
right frequency.
P3 GPIO bit-19 persistence: wifi_mac_enable(a0=0) clears bit 19 of
0x4009000C (GPIO RX-notification enable) whenever the MAC is toggled
between commands, silently losing RX notifications. NOP'ing it keeps
GPIO notifications armed.
Each site is verified against its expected original bytes before writing;
a mismatch aborts (the firmware image is not the one these offsets describe).
Usage:
python3 gen_fw_patch.py [in=firmware/ssv6160-fw.bin] [out=firmware/ssv6160-fw-patched.bin]
"""
import sys
from fw_patch_common import apply_patches
# (name, file_offset, expected_original, replacement)
PATCHES = [
("P1 rf_enable_disable RF_PLL-clear -> nop", 0x782,
bytes([0x23, 0x2a, 0x07, 0x02]), bytes([0x13, 0x00, 0x00, 0x00])),
("P2 scan_stop RF_PLL-clear -> nop", 0x7AFA,
bytes([0x23, 0x2a, 0x07, 0x02]), bytes([0x13, 0x00, 0x00, 0x00])),
("P3 GPIO bit19 persistence (c.nop x2)", 0x8CE,
bytes([0xf9, 0x8f, 0xdc, 0xc6]), bytes([0x01, 0x00, 0x01, 0x00])),
]
def main():
src = sys.argv[1] if len(sys.argv) > 1 else "firmware/ssv6160-fw.bin"
dst = sys.argv[2] if len(sys.argv) > 2 else "firmware/ssv6160-fw-patched.bin"
apply_patches(PATCHES, src, dst)
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
# tools
## `rk915-wiredump.patch`
Instruments the vendor rk915 driver to hex-dump every control command it sends,
in the same `WIRECMD id=<n> len=<n>` + `WIRE <hex>` format the sv6160 driver
emits under `wiredump=1`. That makes the two connect sequences directly
diffable, command for command and byte for byte.
Apply it to a copy of the vendor source (do not edit the ROCKNIX build tree in
place), build against the same kernel, and load with `wiredump=1`:
```sh
cp -a .../build/rk915-<hash> /tmp/rk915v
patch -d /tmp/rk915v -p0 < tools/rk915-wiredump.patch
make -C <kernel-build-tree> M=/tmp/rk915v ARCH=arm64 \
CROSS_COMPILE=aarch64-rocknix-linux-gnu- CONFIG_RK915=m modules
# on the device
rmmod rk915 && insmod rk915.ko wiredump=1 debug_mask=2
```
`debug_mask=2` is `RK915_DBG_SCAN`, which makes the vendor log its scans — they
are invisible at the default mask of 0, and their absence from a capture is
easy to misread as "the vendor does not scan before authenticating". It does.
Drain dmesg continuously while capturing (`while true; do dmesg -c >> log;
sleep 0.2; done &`); the ring buffer wraps well inside a single connect and
will silently eat the window you care about.
## `serctl.py`, `serial_capture.py`
Host-side serial console helpers (`/dev/ttyUSB0`, 1.5 Mbaud; override with
`SV6160_SERIAL_PORT` / `SV6160_SERIAL_BAUD`). `serctl.py` runs one command on
the device and exits with the command's own status (0-255), or 124 when the end
marker never arrives inside the 25 s cap (124 as timeout(1) uses; 2 would
collide with a real remote status) — a hung device is no longer
indistinguishable from a successful one.
## `device/` — on-device harness scripts
These run **on the handheld**, not the build host, and are kept here because
they encode operational knowledge that is otherwise easy to get wrong and is
lost the moment the device is reflashed. Copy them to `/storage/`.
| script | purpose |
|---|---|
| `backtoours.sh` | Reload this driver, reconnect, and start the load-test listeners |
| `sdioreset.sh` | Deep recovery: unbind/bind the WiFi MMC controller, then hand off to `backtoours.sh` |
| `reloadp.sh` | Reload with explicit module parameters, e.g. `reloadp.sh "host_rebind=0"` |
| `flightrec.sh` | Flight recorder — append device state to `/storage/flight.log` every 60s |
`backtoours.sh` needs to know which NetworkManager connection to bring up.
It defaults to `sv6160-test`; override per device without editing the script:
```sh
echo SSID=my-network > /storage/sv6160.conf
```
Only the `SSID=` line is read (with `sed`), not the whole file sourced, and
any surrounding quotes are stripped — the file is never executed.
Three traps these exist to avoid:
**Pick the interface by wdev, not by name.** Userspace sometimes adds a second,
never-brought-up vif on our phy, and it can sort first — `ls /sys/class/net |
grep wlan | head -1` then selects a dead interface and the run looks like a
failed connect while the link is perfectly fine. `backtoours.sh` selects the
lowest wdev on the sv6160 phy and waits for a real association.
**Never unbind `ff370000.mmc`.** That is mmc1 and it holds `/storage`. The WiFi
controller is `ff380000.mmc` (mmc2). `sdioreset.sh` names only the latter and
prints the `/storage` mount count across the unbind as a guard.
**Verify the listeners actually bound.** A previous run's `socat` can outlive
the `pkill`, and a socat that loses the bind race dies silently — leaving the
harness with no listeners while still reporting success.
`flightrec.sh` exists because `dmesg` does not survive a reboot and this board
has no ramoops (`CONFIG_PSTORE_RAM=y` but no reserved-memory region), so an
unexplained reboot otherwise leaves no evidence at all. Pair it with a boot unit
in `/storage/.config/system.d/` so the driver loads at boot and each boot is
stamped into the same log — ROCKNIX will otherwise auto-suspend a fresh boot
before anyone can log in, and udev reclaims the card with the vendor `rk915`.
+83
View File
@@ -0,0 +1,83 @@
#!/bin/sh
# Reload our sv6160 driver and get back on the AP.
exec > /storage/backtoours.txt 2>&1
. /etc/profile 2>/dev/null
# Which NetworkManager connection to bring up. Override per device:
# echo SSID=my-network > /storage/sv6160.conf
# Read the one value, do not source the file: it lives on the user-data
# partition and this runs as root.
SSID=$(sed -n 's/^SSID=//p' /storage/sv6160.conf 2>/dev/null | head -1 | sed 's/^"\(.*\)"$/\1/')
: "${SSID:=sv6160-test}"
set_setting system.suspend.enable 0 2>/dev/null
# /lib/firmware is a tmpfs and is EMPTY after every reboot.
cp -f /storage/sv6160/fw/ssv6160-fw.bin /storage/sv6160/fw/ssv6160-patch.bin /lib/firmware/ 2>/dev/null
pkill socat 2>/dev/null
nmcli radio wifi on >/dev/null 2>&1; sleep 2
rmmod rk915 2>/dev/null; rmmod sv6160 2>/dev/null; sleep 3
insmod /storage/sv6160/sv6160-crc.ko; rc=$?; echo "insmod rc=$rc"; sleep 7
# Our netdevs, lowest wdev first. NOT `ls | head -1`: userspace adds a second
# managed vif on our phy that is never brought up, and its name can sort first
# (seen as wlan0/wdev2 beside the live wlan4/wdev1), so head -1 picks a dead
# interface and the run looks like a failed connect. mac80211 creates its own
# interface at register_hw, so the lowest wdev on the sv6160 phy is ours.
sv_ifaces() {
for i in $(ls /sys/class/net | /usr/bin/grep -E "^wlan"); do
phy=$(basename $(readlink -f /sys/class/net/$i/phy80211) 2>/dev/null)
[ -n "$phy" ] || continue
[ "$(basename $(readlink -f /sys/class/ieee80211/$phy/device/driver) 2>/dev/null)" = sv6160 ] || continue
wdev=$(iw dev $i info 2>/dev/null | sed -n "s/.*wdev \(.*\)/\1/p")
printf '%d %s\n' "$((wdev))" "$i"
done | sort -n | awk "{print \$2}"
}
# An interface that is both associated and has an address.
live_iface() {
for i in $(sv_ifaces); do
iw dev $i link 2>/dev/null | /usr/bin/grep -q "^Connected" || continue
ip -4 -o addr show $i 2>/dev/null | /usr/bin/grep -q inet || continue
echo $i; return
done
}
IFACES=$(sv_ifaces)
echo "sv6160 interfaces: $IFACES"
for i in $IFACES; do ip link set $i up 2>/dev/null; done
PRIMARY=$(echo $IFACES | awk "{print \$1}")
nmcli con up "$SSID" ifname $PRIMARY >/dev/null 2>&1 || nmcli con up "$SSID" >/dev/null 2>&1
# Wait for a real association rather than a fixed sleep.
IF=""
n=0
while [ $n -lt 40 ]; do
IF=$(live_iface)
[ -n "$IF" ] && break
n=$((n+1)); sleep 1
done
if [ -n "$IF" ]; then
echo "IF=$IF bss=$(iw dev $IF link 2>/dev/null | sed -n "s/^Connected to \([0-9a-f:]*\).*/\1/p") ip=$(ip -4 -o addr show $IF 2>/dev/null | sed -n "s/.*inet \([0-9.]*\)\/.*/\1/p") after=${n}s"
else
echo "IF= bss= ip= NOT CONNECTED after ${n}s (tried: $IFACES)"
for i in $IFACES; do echo " $i: $(iw dev $i link 2>/dev/null | head -1)"; done
fi
# Load-test listeners. Start them only once the ports are actually free: a
# previous run's socat can outlive the pkill above by a moment, and a socat
# that loses the bind race dies silently, leaving the harness with no listener.
port_free() { ! netstat -ltn 2>/dev/null | /usr/bin/grep -q ":$1 "; }
pkill socat 2>/dev/null
n=0
while [ $n -lt 15 ]; do
port_free 5301 && port_free 5302 && break
n=$((n+1)); sleep 1
done
socat -u TCP-LISTEN:5301,fork,reuseaddr /dev/null &
socat -u /dev/zero TCP-LISTEN:5302,fork,reuseaddr &
sleep 1
if port_free 5301 || port_free 5302; then
echo "WARNING: listeners did not bind (5301/5302)"
else
echo "listeners up on 5301/5302 (waited ${n}s)"
fi
echo "READY"
wait
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# Flight recorder: append a line of state every 60s to a PERSISTENT file, so an
# unexplained reboot leaves a record of the run-up to it. dmesg does not
# survive a reboot and this board has no ramoops (CONFIG_PSTORE_RAM=y but no
# reserved-memory region), so this is the only way to see what preceded one.
LOG=/storage/flight.log
while true; do
# Resolve the debugfs path EVERY iteration. It was once resolved here at
# start-up, which silently broke the whole point of this script: the phy
# number changes on every driver reload and host re-create, so after the
# first recovery the cached path was stale and every counter field logged
# empty -- while the timestamp, temperature and signal kept looking healthy.
# The recovery is exactly when the counters matter.
D=$(find /sys/kernel/debug/ieee80211 -maxdepth 2 -name sv6160 2>/dev/null | head -1)
up=$(cut -d. -f1 /proc/uptime)
bat=$(cat /sys/class/power_supply/battery/capacity 2>/dev/null)
vol=$(cat /sys/class/power_supply/battery/voltage_now 2>/dev/null)
cur=$(cat /sys/class/power_supply/battery/current_now 2>/dev/null)
ac=$(cat /sys/class/power_supply/rk817-charger/online 2>/dev/null)
tf=$(/usr/bin/grep -m1 "^tx_frames" $D/tx_tokens 2>/dev/null | awk "{print \$2}")
td=$(/usr/bin/grep -m1 "^tx_done_events" $D/tx_tokens 2>/dev/null | awk "{print \$2}")
rs=$(/usr/bin/grep -m1 "^tx_resyncs" $D/tx_tokens 2>/dev/null | awk "{print \$2}")
gu=$(dmesg | /usr/bin/grep -c "TX engine dead" 2>/dev/null)
hr=$(dmesg | /usr/bin/grep -c "re-creating the SDIO host to clear" 2>/dev/null)
# Only OUR interfaces (a foreign wlan can exist), and only one of them:
# two connected names here would break every `iw dev $IF` below.
IF=$(for i in $(ls /sys/class/net | /usr/bin/grep -E "^wlan"); do
phy=$(basename $(readlink -f /sys/class/net/$i/phy80211) 2>/dev/null); [ -n "$phy" ] || continue
[ "$(basename $(readlink -f /sys/class/ieee80211/$phy/device/driver) 2>/dev/null)" = sv6160 ] || continue
iw dev $i link 2>/dev/null | /usr/bin/grep -q Connected && echo $i
done | head -1)
sig=$(iw dev $IF link 2>/dev/null | sed -n "s/.*signal: \(-[0-9]*\).*/\1/p")
temp=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null)
[ -n "$D" ] || { tf=nodev; td=nodev; rs=nodev; }
echo "$(date +%H:%M:%S) up=$up bat=$bat v=$vol i=$cur ac=$ac if=$IF sig=$sig temp=$temp tx=$tf done=$td resync=$rs giveup=$gu rebind=$hr" >> $LOG
sleep 60
done
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Reload our driver with explicit module parameters: /storage/reloadp.sh "host_rebind=0"
exec > /storage/reloadp.txt 2>&1
. /etc/profile 2>/dev/null
set_setting system.suspend.enable 0 2>/dev/null
cp -f /storage/sv6160/fw/ssv6160-fw.bin /storage/sv6160/fw/ssv6160-patch.bin /lib/firmware/ 2>/dev/null
rmmod sv6160 2>/dev/null; rmmod rk915 2>/dev/null; sleep 2
insmod /storage/sv6160/sv6160-crc.ko $1; rc=$?
sleep 6
echo "insmod rc=$rc params=[$1]"
echo "probe_failures=$(dmesg | /usr/bin/grep -c "probe with driver sv6160 failed")"
echo "ifaces=$(ls /sys/class/net | /usr/bin/grep -c wlan)"
echo "RELOADP-DONE"
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Deep SDIO reset: tear down and re-create the dw_mmc host for the WiFi slot,
# which re-powers and re-enumerates the card. Strictly deeper than a module
# reload, which leaves the host controller and card state untouched.
#
# ff380000.mmc is mmc2 = the WiFi controller. NEVER ff370000.mmc: that is
# mmc1 and it holds /storage.
exec > /storage/sdioreset.txt 2>&1
DRV=/sys/bus/platform/drivers/dwmmc_rockchip
rmmod sv6160 2>/dev/null; rmmod rk915 2>/dev/null; sleep 2
echo "unbinding ff380000.mmc"
echo ff380000.mmc > $DRV/unbind 2>&1; sleep 4
echo "bound now: $(ls $DRV | /usr/bin/grep -c ff380000) storage mounts: $(mount | /usr/bin/grep -c storage)"
echo ff380000.mmc > $DRV/bind 2>&1; sleep 6
echo "rebound: $(ls $DRV | /usr/bin/grep -c ff380000)"
if [ "$(ls $DRV | /usr/bin/grep -c ff380000)" != 1 ]; then
echo "REBIND-FAILED: ff380000.mmc did not come back; not chaining into backtoours"
exit 1
fi
rmmod rk915 2>/dev/null; sleep 1
echo "SDIORESET-DONE"
exec /storage/backtoours.sh
+26
View File
@@ -0,0 +1,26 @@
--- /home/pkilar/Devel/rocknix/build.ROCKNIX-RK3326.aarch64/build/rk915-86f0d0e07afe156651ce5eec3e315f66ef79a59f/src/hal.c 2026-08-08 03:02:20.000000000 -0400
+++ /tmp/claude-1000/-home-pkilar-Devel-gusgu/c1ac0c7f-cdf3-4195-92c5-42ffe8e5463e/scratchpad/rk915v/src/hal.c 2026-09-10 21:47:17.950825261 -0400
@@ -303,9 +303,23 @@
}
}
+/* Byte-level wire dump of every control command, for diffing this driver's
+ * connect sequence against a clean-room reimplementation. Off by default. */
+unsigned int rk915_wiredump;
+module_param_named(wiredump, rk915_wiredump, uint, 0644);
+MODULE_PARM_DESC(wiredump, "hex-dump every control command payload (0=off)");
+
static void _hal_send(struct hal_priv *priv,
struct sk_buff *skb)
{
+ if (rk915_wiredump && skb->len >= sizeof(struct host_rpu_msg_hdr)) {
+ struct host_rpu_msg_hdr *h = (struct host_rpu_msg_hdr *)skb->data;
+
+ pr_info("WIRECMD id=%u len=%u\n", h->id, skb->len);
+ print_hex_dump(KERN_INFO, "WIRE ", DUMP_PREFIX_NONE, 32, 1,
+ skb->data,
+ skb->len > 256 ? 256 : skb->len, false);
+ }
skb_queue_tail(&priv->txq, skb);
//tasklet_schedule(&priv->tx_tasklet);
hal_tx_queue_work(priv);
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Run a shell command on the ROCKNIX device over the serial console.
Usage: serctl.py 'command' -> run, print output between markers
serctl.py --raw -> just drain whatever the console emits
Console: /dev/ttyUSB0 @ 1500000, root shell, no login.
Exit codes: 0 = remote command succeeded, 1-255 = remote command's own exit
status, 124 = timeout, no end marker seen within the cap (124 because that is
what timeout(1) uses, and because 2 collides with a real remote status -- `ls`
on a missing path and `grep` on an error both exit 2, so a hung handheld would
have been indistinguishable from those).
"""
import sys, time, serial, uuid
from serial_common import PORT, BAUD
def run(cmd, timeout=25.0):
tag = "M" + uuid.uuid4().hex[:8].upper()
with serial.Serial(PORT, BAUD, timeout=0.2) as s:
s.reset_input_buffer()
s.write(b"\n")
time.sleep(0.25)
s.reset_input_buffer()
s.write(("echo __%s_S__; { %s ; } 2>&1; echo __RC_%s__$?; echo __%s_E__\n"
% (tag, cmd, tag, tag)).encode())
s.flush()
buf = b""
end = ("__%s_E__" % tag).encode()
t0 = time.time()
while time.time() - t0 < timeout:
buf += s.read(4096)
if end in buf:
break
else:
raise TimeoutError("no end marker after %gs" % timeout)
txt = buf.decode("utf-8", "replace")
start = "__%s_S__" % tag
stop = "__%s_E__" % tag
if start in txt:
txt = txt.split(start, 1)[1]
# drop the echoed command line remnant up to first newline
txt = txt.split("\n", 1)[1] if "\n" in txt else txt
if stop in txt:
txt = txt.split(stop, 1)[0]
rc = 0
rc_marker = "__RC_%s__" % tag
if rc_marker in txt:
before, after = txt.split(rc_marker, 1)
digits = ""
i = 0
while i < len(after) and after[i].isdigit():
digits += after[i]
i += 1
rc = int(digits) if digits else 0
# drop the "__RC_<tag>__<digits>" line, including its newline
rest = after[i:].split("\n", 1)
txt = before + (rest[1] if len(rest) > 1 else "")
return txt.replace("\r", ""), rc
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--raw":
with serial.Serial(PORT, BAUD, timeout=3) as s:
sys.stdout.write(s.read(65536).decode("utf-8", "replace"))
sys.exit(0)
try:
out, rc = run(" ".join(sys.argv[1:]))
except TimeoutError as e:
sys.stderr.write("TIMEOUT: %s\n" % e)
sys.exit(124)
print(out, end="")
sys.exit(rc)
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Run a command on the device and stream the serial console to a file,
so a panic/oops that kills the box before /storage is flushed is still caught."""
import serial, sys, time
from serial_common import PORT, BAUD
cmd = sys.argv[1]
secs = float(sys.argv[2]) if len(sys.argv) > 2 else 90
out = sys.argv[3] if len(sys.argv) > 3 else "/tmp/serial_capture.log"
with serial.Serial(PORT, BAUD, timeout=0.3) as s, open(out, "wb") as f:
s.write(b"\n"); time.sleep(0.3); s.reset_input_buffer()
# Level 4, not 8: oopses/warnings still reach the console, but the
# driver's per-frame dev_info/dev_dbg does not. At 8 a chatty driver
# floods this 1.5Mbaud line, printk backs up, and every process that
# writes to the console wedges -- which is how a soak run once left the
# handheld needing a power cycle.
s.write(b"dmesg -n 4\n"); time.sleep(0.5)
s.write((cmd + "\n").encode()); s.flush()
t0 = time.time()
n = 0
while time.time() - t0 < secs:
d = s.read(8192)
if d:
f.write(d); f.flush(); n += len(d)
print(f"captured {n} bytes to {out}")
+9
View File
@@ -0,0 +1,9 @@
"""Shared serial console settings for the device tooling scripts.
Override per host without editing these scripts:
SV6160_SERIAL_PORT=/dev/ttyUSB1 SV6160_SERIAL_BAUD=115200 tools/serctl.py ...
"""
import os
PORT = os.environ.get("SV6160_SERIAL_PORT", "/dev/ttyUSB0")
BAUD = int(os.environ.get("SV6160_SERIAL_BAUD", "1500000"))