first
This commit is contained in:
@@ -0,0 +1,289 @@
|
||||
#pragma once
|
||||
|
||||
/* AckResponder — the hardware ACK engine as a first-class monitor-mode knob.
|
||||
*
|
||||
* The Realtek MAC's immediate-response engine is SIFS-timed with zero host
|
||||
* involvement. The shared recipe programs the port-0 MACID/BSSID and requests
|
||||
* AP net_type. On the Jaguar generations covered by the AP-mode measurements,
|
||||
* net_type participates in gating the engine. RTL8733B is different: it
|
||||
* matches MACID while net_type reads NoLink, so MAC bring-up already permits
|
||||
* responses to the adapter's own address and SetAckResponder retargets that
|
||||
* match to the requested address. See the measured truth table in
|
||||
* AdapterCaps.h and the RTL8733B/Jaguar1 clear implementations.
|
||||
*
|
||||
* This header carries that register recipe minus the beacon machinery. Which
|
||||
* half controls a live disarm is a measured per-die property: use the shared
|
||||
* gate-only clear only where net_type is sufficient; otherwise the backend
|
||||
* must also move the identity off the responder address with retarget() or an
|
||||
* exact captured-identity restore.
|
||||
*
|
||||
* On the adapter combinations exercised by tests/ampdu_ba_check.sh, the SAME
|
||||
* gate also enables the hardware BlockAck responder. RTL8733B has its own
|
||||
* air-side proof in tests/rtl8733b_blockack_onair.sh: a Jaguar2 TX forms real
|
||||
* A-MPDUs and an independent Jaguar1 witness observes retry copies collapse
|
||||
* only while the RTL8733B responder is armed.
|
||||
*
|
||||
* The registers are generation-neutral (same map on Jaguar1/2/3 and
|
||||
* RTL8733B):
|
||||
* 0x0610..0x0615 REG_MACID — the RA the ACK engine matches
|
||||
* 0x0618..0x061d REG_BSSID — port identity companion (the proven AP
|
||||
* recipe programs both)
|
||||
* 0x0102[1:0] MSR/net_type (REG_CR+2) — 0 NoLink / 1 Ad-hoc / 2 Infra /
|
||||
* 3 AP. We request AP (3); whether the field
|
||||
* gates responses is die-specific.
|
||||
*
|
||||
* Turning a passive monitor into an ACTIVE transmitter is a behavioral
|
||||
* change — hence opt-in only (DeviceConfig rx.ack_responder / the
|
||||
* SetAckResponder runtime call), never a default. The MAC must be UNICAST
|
||||
* (I/G bit clear) — a station cannot ACK-target a group address, and the
|
||||
* same footgun broke AP association (docs/ap-mode.md). */
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace ack {
|
||||
|
||||
/* The MACID pair, composed in ONE place. enable(), verify() and retarget()
|
||||
* previously each carried their own copy of this packing, in a header whose
|
||||
* verify() comment promises to keep the register map in one file: an
|
||||
* endianness or width fix applied to one copy would leave the others reading
|
||||
* the old layout while still reporting success. */
|
||||
inline uint32_t macid_lo(const uint8_t mac[6]) {
|
||||
return (uint32_t)mac[0] | ((uint32_t)mac[1] << 8) | ((uint32_t)mac[2] << 16) |
|
||||
((uint32_t)mac[3] << 24);
|
||||
}
|
||||
inline uint16_t macid_hi(const uint8_t mac[6]) {
|
||||
return (uint16_t)(mac[4] | (mac[5] << 8));
|
||||
}
|
||||
|
||||
/* Is the ACK-match identity currently `mac`? The engine matches MACID, so this
|
||||
* is the question "would this port answer for `mac`" — on the RTL8733B that is
|
||||
* the WHOLE question (see retarget()). Throws nothing; a transport failure
|
||||
* reads as "not this address". */
|
||||
inline bool macid_is(RtlAdapter &dev, const uint8_t mac[6]) noexcept {
|
||||
try {
|
||||
return dev.rtw_read<uint32_t>(0x0610) == macid_lo(mac) &&
|
||||
dev.rtw_read16(0x0614) == macid_hi(mac);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool enable(RtlAdapter &dev, const uint8_t mac[6]) noexcept {
|
||||
try {
|
||||
const uint8_t nt = dev.rtw_read8(0x0102);
|
||||
/* Close the gate before changing identity. Besides avoiding a transient
|
||||
* responder for a half-written MAC during retargeting, this makes every
|
||||
* failed identity write leave the radio passive. */
|
||||
if (!dev.rtw_write8(0x0102, static_cast<uint8_t>(nt & ~0x03u))) {
|
||||
/* The transfer status is not state readback. Retry the safety clear using
|
||||
* the value read before the failed transfer; callers verify it before
|
||||
* reporting a failed arm as passive. */
|
||||
(void)dev.rtw_write8(0x0102, static_cast<uint8_t>(nt & ~0x03u));
|
||||
return false;
|
||||
}
|
||||
if (!dev.rtw_write<uint32_t>(0x0610, macid_lo(mac)) ||
|
||||
!dev.rtw_write16(0x0614, macid_hi(mac)) ||
|
||||
!dev.rtw_write<uint32_t>(0x0618, macid_lo(mac)) ||
|
||||
!dev.rtw_write16(0x061c, macid_hi(mac)))
|
||||
return false;
|
||||
if (dev.rtw_write8(0x0102,
|
||||
static_cast<uint8_t>((nt & ~0x03u) | 0x03u)))
|
||||
return true;
|
||||
/* A failed status does not prove the gate write had no side effect. Make a
|
||||
* best-effort close before reporting failure; callers additionally verify
|
||||
* the passive rollback. */
|
||||
(void)dev.rtw_write8(0x0102, static_cast<uint8_t>(nt & ~0x03u));
|
||||
return false;
|
||||
} catch (...) {
|
||||
/* SetAckResponder is a bool contract. Its callers perform a verified
|
||||
* rollback and diagnose whichever register readbacks remain unavailable. */
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Shared gate-only clear for dies where net_type controls the responder.
|
||||
* RTL8733B and Jaguar1/CHIP_8812 callers must additionally retarget MACID. */
|
||||
inline bool disable(RtlAdapter &dev) {
|
||||
const uint8_t nt = dev.rtw_read8(0x0102);
|
||||
return dev.rtw_write8(0x0102, static_cast<uint8_t>(nt & ~0x03u));
|
||||
}
|
||||
|
||||
/* Point the ACK-match identity at another address WITHOUT touching the gate.
|
||||
*
|
||||
* On RTL8733B this is the ONLY thing that changes whether the port answers.
|
||||
* net_type is inert there — measured, three cells, single-shot ACK rate at
|
||||
* MCS3 with a Jaguar1 soliciting:
|
||||
*
|
||||
* never-armed port, peer solicits the adapter's own EFUSE MAC 85.2 %, 82.5 %
|
||||
* never-armed port, peer solicits an address nobody holds 0.0 % (control)
|
||||
* port armed to X, peer solicits X 83.3 %
|
||||
*
|
||||
* A never-armed monitor answers on its own MAC at the same rate as a
|
||||
* deliberately armed responder. So on this die the engine matches MACID and
|
||||
* nothing else: MAC bring-up's program_mac is what makes it answer, arming
|
||||
* merely repoints it, and 0x0102[1:0] does not gate it in either direction.
|
||||
* (The gate IS real on the generations the AP-mode work covered; this is a
|
||||
* per-die exception, not a correction to the recipe.)
|
||||
*
|
||||
* Consequences worth stating plainly, because they are easy to get backwards:
|
||||
* every never-armed RTL8733B monitor session already auto-ACKs unicast frames
|
||||
* addressed to its own EFUSE MAC — a pre-existing property of that die under
|
||||
* this library, not something an arm creates. And a disarm cannot make the port
|
||||
* silent; it can only take it off the responder address and put it back on the
|
||||
* one it shipped with.
|
||||
*
|
||||
* `mac` is that restore address, normally the adapter's own. Deliberately NOT
|
||||
* zero: many Realtek MAC TX paths refuse to schedule a frame when the MAC ID is
|
||||
* zero — the T1 canary bug that programming REG_MACID was introduced to fix
|
||||
* (src/jaguar1/HalModule.cpp, EepromManager.h) — and a radio being disarmed may
|
||||
* still be injecting. Zero would not remove the match either, only move it:
|
||||
* 00:00:00:00:00:00 has the I/G bit clear, so is_unicast() accepts it.
|
||||
* Jaguar1/CHIP_8812 has a distinct measured failure with the same remedy:
|
||||
* NoLink verifies after a gate-only clear, but the old MACID continues
|
||||
* answering until the backend restores its captured pre-arm port identity.
|
||||
* AdapterCaps.h owns that before/after evidence; the result is not generalized
|
||||
* to other Jaguar1 dies.
|
||||
*
|
||||
* Gate untouched on purpose: this is the identity half, so a caller composes it
|
||||
* with disable() in whichever order its die needs, and no generation gets a
|
||||
* behaviour change it was not measured for. */
|
||||
inline bool retarget(RtlAdapter &dev, const uint8_t mac[6]) noexcept {
|
||||
try {
|
||||
/* Sequenced into locals rather than `&&`: both halves must be ATTEMPTED.
|
||||
* Under short-circuit a failed low write would skip the high one — and by
|
||||
* this file's own doctrine (see enable(): "The transfer status is not
|
||||
* state readback") that low write may still have landed, leaving a
|
||||
* half-updated address with the high half never even tried. */
|
||||
const bool lo = dev.rtw_write<uint32_t>(0x0610, macid_lo(mac));
|
||||
const bool hi = dev.rtw_write16(0x0614, macid_hi(mac));
|
||||
return lo && hi;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool is_disabled(RtlAdapter &dev) {
|
||||
return (dev.rtw_read8(0x0102) & 0x03u) == 0;
|
||||
}
|
||||
|
||||
inline bool disable_verified(RtlAdapter &dev) noexcept {
|
||||
try {
|
||||
(void)disable(dev);
|
||||
/* Readback is the safety result: a control transfer may report failure even
|
||||
* though the write landed, while a successful transfer alone proves no
|
||||
* state. The caller only needs to know whether the active gate is closed. */
|
||||
return is_disabled(dev);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* Exact port-0 identity snapshot/restore for a backend that must return more
|
||||
* than MACID to its pre-arm state. Keep the packed register representation so
|
||||
* no byte-order conversion can diverge between capture and restore. */
|
||||
struct PortIdentity {
|
||||
uint32_t macid_lo = 0;
|
||||
uint16_t macid_hi = 0;
|
||||
uint32_t bssid_lo = 0;
|
||||
uint16_t bssid_hi = 0;
|
||||
};
|
||||
|
||||
inline bool snapshot_port_identity(RtlAdapter &dev, PortIdentity &out) noexcept {
|
||||
try {
|
||||
out = {.macid_lo = dev.rtw_read<uint32_t>(0x0610),
|
||||
.macid_hi = dev.rtw_read16(0x0614),
|
||||
.bssid_lo = dev.rtw_read<uint32_t>(0x0618),
|
||||
.bssid_hi = dev.rtw_read16(0x061c)};
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool port_mac_is(const PortIdentity &identity,
|
||||
const uint8_t mac[6]) noexcept {
|
||||
return identity.macid_lo == macid_lo(mac) &&
|
||||
identity.macid_hi == macid_hi(mac);
|
||||
}
|
||||
|
||||
inline bool restore_port_identity(RtlAdapter &dev,
|
||||
const PortIdentity &identity) noexcept {
|
||||
/* Keep each operation exception-contained so all four halves are attempted
|
||||
* even if a transport throws instead of returning false. */
|
||||
auto write32 = [&dev](uint16_t reg, uint32_t value) noexcept {
|
||||
try {
|
||||
return dev.rtw_write<uint32_t>(reg, value);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
auto write16 = [&dev](uint16_t reg, uint16_t value) noexcept {
|
||||
try {
|
||||
return dev.rtw_write16(reg, value);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const bool ml = write32(0x0610, identity.macid_lo);
|
||||
const bool mh = write16(0x0614, identity.macid_hi);
|
||||
const bool bl = write32(0x0618, identity.bssid_lo);
|
||||
const bool bh = write16(0x061c, identity.bssid_hi);
|
||||
return ml && mh && bl && bh;
|
||||
}
|
||||
|
||||
inline bool port_identity_is(RtlAdapter &dev,
|
||||
const PortIdentity &identity) noexcept {
|
||||
try {
|
||||
return dev.rtw_read<uint32_t>(0x0610) == identity.macid_lo &&
|
||||
dev.rtw_read16(0x0614) == identity.macid_hi &&
|
||||
dev.rtw_read<uint32_t>(0x0618) == identity.bssid_lo &&
|
||||
dev.rtw_read16(0x061c) == identity.bssid_hi;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* The MAC must be UNICAST: a station cannot ACK-target a group address, so an
|
||||
* arm on one can never fire. Lives here rather than in each backend because
|
||||
* the precondition is a property of the recipe, not of any one die. */
|
||||
inline bool is_unicast(const uint8_t mac[6]) { return (mac[0] & 0x01u) == 0; }
|
||||
|
||||
/* A rollback target must be a usable station identity, not merely readable.
|
||||
* An all-zero MAC has the I/G bit clear (so is_unicast accepts it), remains a
|
||||
* matchable address, and also stops TX scheduling on the Jaguar1 8812 path. */
|
||||
inline bool has_safe_restore_mac(const PortIdentity &identity) noexcept {
|
||||
return (identity.macid_lo != 0 || identity.macid_hi != 0) &&
|
||||
(identity.macid_lo & 0x01u) == 0;
|
||||
}
|
||||
|
||||
/* Retargeting can only move a responder off its armed address when the restore
|
||||
* identity differs. The caller owns both values and must reject equality on a
|
||||
* die where the gate clear alone was measured insufficient. */
|
||||
inline bool disarmable_by_retarget(const uint8_t responder[6],
|
||||
const PortIdentity &restore) noexcept {
|
||||
return !port_mac_is(restore, responder);
|
||||
}
|
||||
|
||||
/* Did the requested arm recipe land? Reads back net_type and the RA the ACK
|
||||
* engine matches (MACID), composed exactly as enable() writes them — keeping
|
||||
* the register map in ONE file, so a change to enable() cannot silently
|
||||
* diverge from a copy of it somewhere else.
|
||||
*
|
||||
* NB the BSSID companion at 0x0618 is written but not checked: the ACK engine
|
||||
* matches on MACID, and 0x0618 is programmed only because the proven AP recipe
|
||||
* programs both. Verifying the two behavior-relevant programmed fields keeps
|
||||
* this honest without asserting that both are gates on every die. */
|
||||
inline bool verify(RtlAdapter &dev, const uint8_t mac[6]) noexcept {
|
||||
try {
|
||||
return (dev.rtw_read8(0x0102) & 0x03u) == 0x03u && macid_is(dev, mac);
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace ack */
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,306 @@
|
||||
/* Aggregate adapter-capability report — what the opened radio actually IS and
|
||||
* what it can do, resolved from the chip identity devourer already determines at
|
||||
* construction (SYS_CFG2 chip-id + USB PID + EFUSE RF-type). A dependent app
|
||||
* (OpenIPC-FPV tooling, a link manager, a test harness) can enumerate the RF
|
||||
* frequency coverage, channel widths, spatial-stream / chain count, and the
|
||||
* per-family feature levers (per-packet TX power, narrowband, fast retune)
|
||||
* without hardcoding a chip table of its own or scraping bring-up logs.
|
||||
*
|
||||
* This is the identity+radio superset of the narrower GetTxCaps (modulation
|
||||
* features) and GetTxPowerCaps (power-knob range), which it composes by value so
|
||||
* there is one source of truth per fact. Like those, it is STATIC — resolved at
|
||||
* construction, safe from any thread, callable before Init/InitWrite. The live
|
||||
* "which antennas look connected" question is deliberately NOT here (it needs
|
||||
* traffic); see IRadio::GetActiveRxPaths / ActiveRxPaths in RxQuality.h.
|
||||
*
|
||||
* FREQUENCY COVERAGE. The 5 GHz synthesizer on these parts tunes well past the
|
||||
* regulatory UNII channels (the vendor rtl88x2bu "monitor_chan_override" hack:
|
||||
* chan 16..253, freq = 5000 + 5*chan, ~5080..6165 MHz). devourer drives that
|
||||
* whole span in monitor mode; `tune_5g` reports the tunable range while
|
||||
* `characterized_5g` reports the sub-range backed by the generated txpwr_lmt /
|
||||
* EFUSE PG tables (outside it, per-channel constants and TX power are
|
||||
* extrapolated from the nearest characterized channel — the radio still tunes,
|
||||
* but power is uncalibrated). Regulatory compliance is the CALLER's problem: the
|
||||
* library enforces none.
|
||||
*/
|
||||
#ifndef DEVOURER_ADAPTER_CAPS_H
|
||||
#define DEVOURER_ADAPTER_CAPS_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "TxCaps.h"
|
||||
#include "TxPower.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
enum class ChipGeneration : uint8_t {
|
||||
Unknown = 0,
|
||||
Jaguar1,
|
||||
Jaguar2,
|
||||
Jaguar3,
|
||||
Rtl8733b, /* HALMAC 87xx 802.11n: RTL8731BU / RTL8733BU */
|
||||
Kestrel, /* Wi-Fi 6 / 802.11ax (RTL8852BU/8852CU) */
|
||||
/* MediaTek MT7662 MAC (MT7612U / MT7662U, 2T2R 11ac USB) — the first
|
||||
* non-Realtek generation. Register width, the vendor-request opcodes and the
|
||||
* in-band MCU plane all differ; nothing that switches on this value may
|
||||
* assume a Realtek register map. */
|
||||
Mt7612u
|
||||
};
|
||||
|
||||
inline const char *generation_name(ChipGeneration g) {
|
||||
switch (g) {
|
||||
case ChipGeneration::Jaguar1:
|
||||
return "jaguar1";
|
||||
case ChipGeneration::Jaguar2:
|
||||
return "jaguar2";
|
||||
case ChipGeneration::Jaguar3:
|
||||
return "jaguar3";
|
||||
case ChipGeneration::Rtl8733b:
|
||||
return "rtl8733b";
|
||||
case ChipGeneration::Kestrel:
|
||||
return "kestrel";
|
||||
case ChipGeneration::Mt7612u:
|
||||
return "mt7612u";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/* Supported channel widths, one bit per width (MHz). A mask, not a max, because
|
||||
* the set is not contiguous per family: Jaguar2/Jaguar3 add 5/10 MHz narrowband
|
||||
* BELOW the 20/40/80 all AC families do. */
|
||||
constexpr uint8_t kBw5 = 1u << 0;
|
||||
constexpr uint8_t kBw10 = 1u << 1;
|
||||
constexpr uint8_t kBw20 = 1u << 2;
|
||||
constexpr uint8_t kBw40 = 1u << 3;
|
||||
constexpr uint8_t kBw80 = 1u << 4;
|
||||
constexpr uint8_t kBw160 = 1u << 5;
|
||||
|
||||
/* J1 does 20/40/80; J2 and J3 add the 5/10 MHz narrowband re-clock (J2 packs
|
||||
* the ADC/DAC clock word into 0x8ac, J3 into 0x9b0/0x9b4 — same RF-stays-20MHz
|
||||
* concept; the J2 8822B additionally needs an RF18 re-latch edge after the
|
||||
* re-clock). J1 has no vendor narrowband reference (the rtl8812au trees carry
|
||||
* only dead enum values). Pure; unit-tested in tests/adapter_caps_selftest.cpp. */
|
||||
inline uint8_t bw_mask_for_generation(ChipGeneration g) {
|
||||
const uint8_t ac = kBw20 | kBw40 | kBw80;
|
||||
/* Kestrel (11ax): 5/10 MHz is the BB small-BW field on both dies (vendor
|
||||
* bw_sup declares BW_CAP_5M|10M); 160 MHz is 8852C-only (rtl8852c_halinit.c
|
||||
* bw_sup has BW_CAP_160M, rtl8852b_halinit.c tops at 80) and is OR'd in by
|
||||
* the device layer per variant. */
|
||||
/* RTL8733B: 10 MHz qualified (SDR OBW + two-way cross-decode with a
|
||||
* Jaguar3 peer, both bands); 5 MHz is refused — its BB small-BW mode airs
|
||||
* no packets on this die (docs/rtl8733b.md "Narrowband status"). */
|
||||
/* MT7612U: 20/40/80 and nothing narrower. MT_RATE_BW encodes only
|
||||
* 20/40/80/160, so there is no 5 or 10 MHz to select — unlike the Realtek
|
||||
* BB small-BW modes the trailing arm below is describing. Named explicitly
|
||||
* because that trailing arm is the permissive one: without this case a
|
||||
* MediaTek adapter would inherit kBw5|kBw10 and advertise two bandwidths the
|
||||
* part cannot represent. 160 MHz is likewise absent (docs/mt7612u.md). */
|
||||
return g == ChipGeneration::Rtl8733b ? (kBw10 | kBw20 | kBw40)
|
||||
: g == ChipGeneration::Jaguar1 ? ac
|
||||
: g == ChipGeneration::Mt7612u ? ac
|
||||
: g == ChipGeneration::Unknown ? 0
|
||||
: (ac | kBw5 | kBw10);
|
||||
}
|
||||
|
||||
/* A tunable / characterized frequency span (MHz). valid=false = band absent. */
|
||||
struct BandRange {
|
||||
bool valid = false;
|
||||
uint16_t min_mhz = 0;
|
||||
uint16_t max_mhz = 0;
|
||||
};
|
||||
|
||||
struct AdapterCaps; /* fwd for the frequency-range helper below */
|
||||
|
||||
/* Fill the 2.4 + 5 GHz tunable / characterized spans shared by all three Jaguar
|
||||
* families. tune_* = what the synthesizer reaches in monitor mode; the 5 GHz
|
||||
* span runs past the UNII channels (the extended synth ~5080..6165 MHz, chan
|
||||
* 16..253 — per-chip lock varies, validated on the bench). characterized_* =
|
||||
* the sub-range the generated txpwr_lmt / EFUSE PG tables cover; outside it TX
|
||||
* power is extrapolated from the nearest characterized channel. Defined
|
||||
* out-of-line below (needs the full AdapterCaps). */
|
||||
inline void set_standard_freq_ranges(AdapterCaps &c);
|
||||
|
||||
struct AdapterCaps {
|
||||
bool supported = false; /* false on a generation that hasn't wired this */
|
||||
|
||||
/* --- identity --- */
|
||||
const char *chip_name = ""; /* silicon die, no bus suffix: "RTL8822C" */
|
||||
const char *marketing_names = "";/* alias list, e.g. "RTL8812CU/RTL8822CU" */
|
||||
uint8_t chip_id = 0; /* SYS_CFG2 (0x00FC) dispatch byte */
|
||||
ChipGeneration generation = ChipGeneration::Unknown;
|
||||
const char *variant = ""; /* per-family variant tag ("C8822B", ICType) */
|
||||
const char *transport = ""; /* "usb" | "pcie" */
|
||||
|
||||
/* --- chains (EFUSE RF-type on Jaguar1; per-variant on Jaguar2/3) --- */
|
||||
uint8_t tx_chains = 0;
|
||||
uint8_t rx_chains = 0;
|
||||
|
||||
/* --- composed sub-caps (single source of truth) --- */
|
||||
TxCaps tx; /* = GetTxCaps() — modulation features */
|
||||
TxPowerCaps txpwr; /* = GetTxPowerCaps() — power-knob range/step */
|
||||
|
||||
/* --- bandwidth + frequency --- */
|
||||
uint8_t bw_mask = 0; /* kBw* bits */
|
||||
BandRange tune_2g4, tune_5g; /* synthesizer-tunable spans */
|
||||
BandRange characterized_2g4, characterized_5g; /* txpwr-table-backed spans */
|
||||
|
||||
/* --- FEC RX (bench-derived truth table — deliberately NOT the vendor
|
||||
* driver's HAL_DEF_RX_LDPC, which is 2013-era interop-advertisement policy:
|
||||
* all-false on Jaguar1 while the 8812A baseband demonstrably decodes LDPC
|
||||
* on-air. The TX side lives in TxCaps.ldpc_ok. HT and VHT are separate
|
||||
* decoder paths in silicon, so the flags split: the RTL8821A field failure
|
||||
* ("PixelPilot can't RX LDPC from Eachine Sphere Link") is VHT-only. --- */
|
||||
bool ldpc_rx_ht = false; /* baseband decodes LDPC-coded HT PPDUs */
|
||||
bool ldpc_rx_vht = false; /* baseband decodes LDPC-coded VHT PPDUs */
|
||||
/* Per-frame LDPC *reporting*: RxAtrib.ldpc is populated (RX-descriptor bit
|
||||
* on the 8812A die, PHY-status byte7[5] on Jaguar2/3). False on the 8814A —
|
||||
* it decodes LDPC fine but the vendor wired no per-frame indicator (rxdesc
|
||||
* offsets 16/20 unparsed, and the Jaguar1 phy_status_rpt has no ldpc bit). */
|
||||
bool ldpc_rx_flag = false;
|
||||
|
||||
/* Bench-derived like the ldpc_rx_* trio above, and a TRANSMIT claim: the
|
||||
* baseband emits a VHT PPDU that a peer decodes on the 2.4 GHz band.
|
||||
* 802.11ac is a 5 GHz standard, so nothing guarantees a 2.4 GHz VHT frame
|
||||
* works at all; devourer's TX path
|
||||
* never reads the band when resolving a rate, which makes it *selectable*
|
||||
* everywhere, and this flag is the separate question of whether it flies.
|
||||
* False means unmeasured on that chip, not incapable.
|
||||
*
|
||||
* Scope: VHT *format* on 2.4 GHz. The 256-QAM points that motivate the
|
||||
* extension (the "NitroQAM" / "TurboQAM" marketing) are confirmed on the
|
||||
* 8812A only — VHT1SS_MCS8 at 20 MHz, decoded by an 8822BU peer. Measuring
|
||||
* them needs a chip that has been VBUS cold-cycled: high-order constellation
|
||||
* TX degrades across warm re-inits until 64-QAM and up stop decoding, which
|
||||
* reads exactly like a link too weak to carry them (docs/vht-on-2g4.md).
|
||||
* Note VHT MCS9 is not a legal rate at 20 MHz for 1-2 streams; hardware
|
||||
* falls back to MCS8 there, so 40 MHz is required to exercise MCS9 at all.
|
||||
*
|
||||
* A standards-only 802.11n receiver decodes none of it either way: this is a
|
||||
* strong-link, close-range mode, the opposite of a range mode. */
|
||||
bool vht_2g4_ok = false;
|
||||
|
||||
/* --- hardware-ARQ capability (bench-derived truth table, on-air responder
|
||||
* matrix + retry-knob A/B; the measured contract is docs/scheduled-mac.md).
|
||||
* ack_responder_ok: SetAckResponder measurably closes a hardware-ARQ loop
|
||||
* as the RESPONDER (SIFS ACKs that a soliciting TX's CCX reports confirm).
|
||||
* Measured true: 8812A (works, degraded — intermittent SIFS ACKs), 8814A,
|
||||
* 8821A (61–64% single-shot MCS3, 94% at retry 8 — an earlier "broken"
|
||||
* verdict was a harness artifact: the responder's arm was never verified,
|
||||
* so a silently dead responder read as on=0/off=0),
|
||||
* 8822B, 8812C/8822C, 8812E/8822E (the 8811A rides the 8812 die path and
|
||||
* inherits its row), 8733B (1725/1725 frames ACKed at retries_mean 0.00,
|
||||
* and retarget-proof: re-armed on a different MAC, 1728/1728 —
|
||||
* tests/ack_txreport_matrix.sh run with the 8733B as the responder).
|
||||
*
|
||||
* The `on`, `retarget`, and legacy `off` rows establish arming, retargeting,
|
||||
* and a never-armed control. A backend-owned `disarmed` row supports only
|
||||
* the live-disarm claim for the responder used in that run. On the reference
|
||||
* RTL8812AU, the old gate-only clear left every soliciting report ACKed;
|
||||
* restoring the captured pre-arm MACID produced no ACKs with retries pinned
|
||||
* at the configured limit. The own-MAC adversary also showed why an arm equal
|
||||
* to the captured MACID must be refused. docs/scheduled-mac.md owns the exact
|
||||
* counts. The implementation additionally restores and readback-verifies
|
||||
* BSSID as port-state hygiene; the ACK-rate result does not attribute the
|
||||
* behavioral change to BSSID. The implementation covers the shared CHIP_8812
|
||||
* path, but its 1T1R RTL8811AU cut was not separately measured; 8814A/8821A
|
||||
* and the HalMAC generations do not inherit the result.
|
||||
*
|
||||
* On the 8733B the net_type gate is INERT and the engine matches MACID
|
||||
* alone: at single-shot ACK rate a never-armed port answers on its own EFUSE
|
||||
* MAC at 85.2%/82.5% against 0.0% for an address nobody holds, and 83.3%
|
||||
* when deliberately armed. Two consequences: every never-armed monitor
|
||||
* session on that die already auto-ACKs unicast to its own MAC, and a disarm
|
||||
* there can only move the identity, never silence the port
|
||||
* (Rtl8733bDevice::disarm_ack_responder). Not known to hold on any other
|
||||
* generation — the AP-mode work proved the gate where it was measured.
|
||||
* False-as-unmeasured (the
|
||||
* vht_2g4_ok reading: unmeasured, not incapable): the 8821C — it shares
|
||||
* the recipe but no 8821CU/CE cell has run. FALSE on Kestrel:
|
||||
* SetAckResponder is not implemented on the AX generation.
|
||||
* tx_retry_limit_ok: DEVOURER_TX_RETRY_LIMIT drives hardware autonomous
|
||||
* retransmission (measured 12/0/12 A/B: 8821AU, 8812BU, 8822CU; the 8733B
|
||||
* by airtime dose-response instead, 0/3/12 -> 1.00/4.00/12.32–12.33 airings per
|
||||
* frame, because that die has no CCX path to judge its own frames
|
||||
* (tests/rtl8733b_retry_limit_onair.sh); Kestrel
|
||||
* 8832CU witness-measured — the AX WD DATA_TXCNT_LMT field counts
|
||||
* ATTEMPTS, folded +1 to the N-retries contract, limits {0,2,8} -> modal
|
||||
* on-air copies {1,3,8-9}). FALSE on the 8814A die (the vendor
|
||||
* DATA_RETRY_LIMIT=0 carve-out is kept — knob inert) and
|
||||
* false-as-unmeasured on the 8821C. */
|
||||
bool ack_responder_ok = false;
|
||||
bool tx_retry_limit_ok = false;
|
||||
|
||||
/* --- feature flags --- */
|
||||
/* Per-packet TX power: a per-frame power trim driven by radiotap
|
||||
* DBM_TX_POWER (dB delta vs the calibrated table / session base) or a
|
||||
* session default. Three hardware shapes:
|
||||
* - Jaguar2 (8822B/8821C) + 8814A: a fixed 6-rung LUT in the descriptor
|
||||
* ({0,-3,-7,-11,+3,+6} dB) — per_pkt_txpwr_steps = 6, step_qdb = 0.
|
||||
* - Jaguar3 (8822C/8822E): a 2-bit bank selector; the banks are
|
||||
* programmable 7-bit signed offsets (0x1e70) in per_pkt_txpwr_step_qdb
|
||||
* units (nominally 4 = 1 dB), 2 concurrent non-zero levels —
|
||||
* per_pkt_txpwr_steps = 0 (continuous), min/max give the travel.
|
||||
* - Kestrel (8852B/8852C): no descriptor field; the fixed-dBm BB target
|
||||
* is rewritten between frames on value change (2 RMWs, free while
|
||||
* constant; global, so HW beacons follow) — per_pkt_txpwr_steps = 0,
|
||||
* step_qdb = 1 (0.25 dB).
|
||||
* per_pkt_txpwr_measured stays false until the family's path has been
|
||||
* proven to move on-air power (tests/txpkt_pwr_ofset_onair.sh) — the
|
||||
* honest flag for a vendor-defined-but-unvalidated field (the 8814A
|
||||
* today). */
|
||||
bool per_packet_txpower = false;
|
||||
uint8_t per_pkt_txpwr_steps = 0; /* 6 = LUT rungs; 0 = continuous qdb */
|
||||
uint8_t per_pkt_txpwr_step_qdb = 0; /* Jaguar3 bank step (qdB); 0 for LUT */
|
||||
int16_t per_pkt_txpwr_min_qdb = 0; /* most negative per-packet trim */
|
||||
int16_t per_pkt_txpwr_max_qdb = 0; /* most positive per-packet trim */
|
||||
bool per_pkt_txpwr_measured = false; /* on-air-confirmed for this family */
|
||||
bool narrowband_ok = false; /* narrowband BB re-clock exists; which
|
||||
* widths via bw_mask kBw5/kBw10 (the
|
||||
* RTL8733B is 10 MHz only) */
|
||||
uint8_t xtal_cap_max = 0; /* crystal-cap trim range top (0 = no trim;
|
||||
* 0x3f on Jaguar1/2, 0x7f on Jaguar3) */
|
||||
uint8_t xtal_cap_default = 0; /* efuse/default crystal-cap code */
|
||||
bool fastretune_ok = false; /* lean FastRetune override exists */
|
||||
/* HE ER SU (802.11ax extended range, Kestrel only): TX airs the ER SU PPDU
|
||||
* per-packet via radiotap-HE FORMAT=EXT_SU (242-tone RU MCS0-2; 106-tone RU
|
||||
* MCS0 via a BW_RU_ALLOC of 106) plus HE DCM, and RX classifies the format
|
||||
* in RxAtrib.ppdu_type (7=HE_SU, 8=HE_ERSU). Pre-AX generations have no ER
|
||||
* equivalent. */
|
||||
bool he_er_su_ok = false;
|
||||
bool per_chain_rssi = false; /* frame parser fills per-chain rssi (>=2ch) */
|
||||
/* Hardware timing. hw_rx_timestamp: every received frame is stamped with the
|
||||
* MAC's microsecond TSF at receive (RxPacket.RxAtrib.tsfl) — true on all
|
||||
* generations. hw_beacon_txtsf: this adapter, as a transmitter, inserts its
|
||||
* live hardware TSF into the beacons it airs at the instant of transmission
|
||||
* (a genuine sub-µs TX-egress timestamp a receiver reads via
|
||||
* Packet::TxEgressTsf) — rides the hardware beacon function (StartBeacon);
|
||||
* true on all generations. Together they are the primitives for one-way
|
||||
* hardware time distribution (see TsfSync). */
|
||||
bool hw_rx_timestamp = false;
|
||||
bool hw_beacon_txtsf = false;
|
||||
/* 802.11ax scheduled UL (Kestrel/RTL8852 only). trigger_ul_ok: the adapter
|
||||
* can air an HE Trigger frame (UL-OFDMA grant) and program the fw UL-OFDMA
|
||||
* scheduler (SendTrigger / ConfigureUlOfdma). twt_ok: the fw exposes the TWT
|
||||
* agreement surface (ConfigureTwt / TwtBindSta). Pre-AX generations have no
|
||||
* trigger/TWT firmware surface. */
|
||||
bool trigger_ul_ok = false;
|
||||
bool twt_ok = false;
|
||||
/* sounding_ok: the adapter exposes the HE sounding command surface (NDPA ->
|
||||
* NDP -> BFRP via StartSounding / RegisterBeamformee). NB the shipped client
|
||||
* NIC firmware accepts SET_SND_PARA but does not air the sequence (the fw
|
||||
* sounding-transmit engine is AP-firmware-only, like the MP-only F2P path);
|
||||
* host-injected SendTrigger is what puts a Trigger on the air. */
|
||||
bool sounding_ok = false;
|
||||
};
|
||||
|
||||
inline void set_standard_freq_ranges(AdapterCaps &c) {
|
||||
c.tune_2g4 = BandRange{true, 2412, 2484};
|
||||
c.characterized_2g4 = BandRange{true, 2412, 2484};
|
||||
c.tune_5g = BandRange{true, 5080, 6165};
|
||||
c.characterized_5g = BandRange{true, 5180, 5825};
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_ADAPTER_CAPS_H */
|
||||
@@ -0,0 +1,220 @@
|
||||
/* Adapter-health probes + classifier — the "is my dongle dying" detector.
|
||||
*
|
||||
* Motivated by a field failure mode measured on a degrading RTL8812AU
|
||||
* (OpenIPC/devourer#205): the chip enumerates fine, USB transfers are clean,
|
||||
* init completes green — and the radio is stone-deaf, because
|
||||
*
|
||||
* (1) the EFUSE read path returns STOCHASTIC garbage — a different
|
||||
* EEPROM ID / calibration map on every physical read (a healthy chip
|
||||
* returns byte-identical content every time), so the driver configures
|
||||
* the wrong RFE type / PA / LNA tables; and
|
||||
* (2) the 8051 MCU never boots firmware — the download checksum report
|
||||
* never asserts (non-fatal for Jaguar1 monitor RX, so nothing aborts).
|
||||
*
|
||||
* Both are invisible to "did init succeed" checks. The probes here make them
|
||||
* measurable: N fresh physical EFUSE reads cross-compared for stability +
|
||||
* validity, the firmware-boot outcome of the last bring-up, and an RX smoke
|
||||
* count. The classifier maps those to a plain verdict + reason bits.
|
||||
*
|
||||
* IRtlRadio carries ProbeEfuseStability and IRadio carries GetFwBootStatus;
|
||||
* examples/doctor is the reference consumer.
|
||||
*/
|
||||
#ifndef DEVOURER_ADAPTER_HEALTH_H
|
||||
#define DEVOURER_ADAPTER_HEALTH_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Every Realtek WLAN EFUSE logical map opens with this ID; anything else on a
|
||||
* programmed retail adapter means the read is corrupt (a BLANK map — all
|
||||
* 0xFF, id 0xFFFF — is the separate "autoload fail" case: legitimate on
|
||||
* bare dev boards, odd on retail dongles). */
|
||||
constexpr uint16_t kRtlEepromId = 0x8129;
|
||||
|
||||
/* Result of N back-to-back physical EFUSE logical-map reads (not the cached
|
||||
* shadow — each pass re-runs the efuse controller read sequence). */
|
||||
struct EfuseStability {
|
||||
bool supported = false; /* family wired + chip brought up when probed */
|
||||
int reads = 0; /* passes performed */
|
||||
int mismatched_reads = 0; /* passes whose content != pass #0 */
|
||||
int invalid_id_reads = 0; /* passes with EEPROM ID != kRtlEepromId */
|
||||
uint16_t eeprom_id = 0; /* ID from the last pass */
|
||||
uint16_t map_len = 0; /* logical map bytes compared per pass */
|
||||
uint16_t first_mismatch_off = 0xFFFF; /* first differing offset, if any */
|
||||
};
|
||||
|
||||
/* Shared probe loop behind IRtlRadio::ProbeEfuseStability — each generation
|
||||
* supplies its own fresh-physical-map reader as `read_map(uint8_t *buf)`
|
||||
* (return false on transport failure) and this does the cross-compare. */
|
||||
template <typename ReadFn>
|
||||
inline EfuseStability ProbeEfuseStabilityImpl(ReadFn &&read_map,
|
||||
uint16_t map_len, int reads) {
|
||||
EfuseStability st;
|
||||
if (reads < 1 || map_len < 2)
|
||||
return st;
|
||||
st.supported = true;
|
||||
st.map_len = map_len;
|
||||
std::vector<uint8_t> ref(map_len), cur(map_len);
|
||||
for (int i = 0; i < reads; ++i) {
|
||||
uint8_t *buf = (i == 0) ? ref.data() : cur.data();
|
||||
if (!read_map(buf))
|
||||
break;
|
||||
st.reads++;
|
||||
st.eeprom_id = static_cast<uint16_t>(buf[0] | (buf[1] << 8));
|
||||
if (st.eeprom_id != kRtlEepromId)
|
||||
st.invalid_id_reads++;
|
||||
if (i > 0 && std::memcmp(ref.data(), cur.data(), map_len) != 0) {
|
||||
st.mismatched_reads++;
|
||||
if (st.first_mismatch_off == 0xFFFF) {
|
||||
for (uint16_t off = 0; off < map_len; ++off) {
|
||||
if (ref[off] != cur[off]) {
|
||||
st.first_mismatch_off = off;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
/* Outcome of the most recent firmware download (populated during
|
||||
* Init/InitWrite). On Jaguar1 a failed FW boot does NOT abort init — monitor
|
||||
* RX runs without the 8051 — which is exactly why it needs surfacing. */
|
||||
struct FwBootStatus {
|
||||
bool supported = false; /* family records this */
|
||||
bool attempted = false; /* a download ran this bring-up */
|
||||
bool checksum_ok = false;
|
||||
bool ready_ok = false; /* MCU signalled firmware-ready */
|
||||
};
|
||||
|
||||
enum class AdapterVerdict {
|
||||
Unknown, /* nothing conclusive was checked */
|
||||
Healthy,
|
||||
Suspect, /* one soft anomaly — re-run, or supply known traffic */
|
||||
Failing, /* hard evidence of dying silicon */
|
||||
};
|
||||
|
||||
/* Reason bits accompanying a verdict. */
|
||||
enum : uint32_t {
|
||||
kAdapterInitFailed = 1u << 0, /* bring-up aborted */
|
||||
kAdapterEfuseUnstable = 1u << 1, /* reads disagree — the smoking gun */
|
||||
kAdapterEfuseIdInvalid = 1u << 2, /* stable but ID != 0x8129 (not blank) */
|
||||
kAdapterEfuseBlank = 1u << 3, /* stable all-0xFF map (autoload fail) */
|
||||
kAdapterFwBootFailed = 1u << 4, /* download attempted, MCU never ready */
|
||||
kAdapterRxDeafToTraffic = 1u << 5, /* 0 frames with a known traffic source */
|
||||
kAdapterRxSilent = 1u << 6, /* 0 frames, no traffic guarantee (soft) */
|
||||
};
|
||||
|
||||
struct AdapterHealthInput {
|
||||
bool init_completed = false;
|
||||
EfuseStability efuse;
|
||||
FwBootStatus fw;
|
||||
bool rx_checked = false;
|
||||
/* Operator asserts a known traffic source on the listen channel (bench
|
||||
* flood / busy AP) — upgrades "heard nothing" from Suspect to Failing. */
|
||||
bool rx_traffic_expected = false;
|
||||
uint32_t rx_frames_ok = 0; /* FCS-clean frames heard */
|
||||
uint32_t rx_frames_crc = 0; /* corrupt frames heard (informational) */
|
||||
};
|
||||
|
||||
inline const char *AdapterVerdictName(AdapterVerdict v) {
|
||||
switch (v) {
|
||||
case AdapterVerdict::Healthy:
|
||||
return "HEALTHY";
|
||||
case AdapterVerdict::Suspect:
|
||||
return "SUSPECT";
|
||||
case AdapterVerdict::Failing:
|
||||
return "FAILING";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
/* Pure classifier — no I/O, unit-tested in tests/adapter_health_selftest.cpp.
|
||||
*
|
||||
* Grading (measured on the #205 dying unit vs its healthy twin):
|
||||
* - Cross-read EFUSE instability is conclusive by itself: healthy silicon
|
||||
* returns identical maps every read, cold or warm. → Failing.
|
||||
* - A stable-but-invalid ID (not blank) is corrupt calibration → Failing
|
||||
* when the FW also failed, else Suspect (one anomaly, re-run).
|
||||
* - A blank map (all-0xFF / autoload fail) is legitimate on some dev
|
||||
* boards → Suspect, look at the adapter's provenance.
|
||||
* - FW-boot failure alone → Suspect (state can be transient); with any
|
||||
* EFUSE anomaly → Failing (two independent subsystems = the signature).
|
||||
* - Deaf RX only counts as Failing when the operator vouched for traffic
|
||||
* (rx_traffic_expected); otherwise an RF-quiet room is indistinguishable
|
||||
* → Suspect. High corrupt-frame ratios are NOT graded — distant ambient
|
||||
* traffic legitimately decodes mostly-corrupt.
|
||||
*/
|
||||
inline AdapterVerdict ClassifyAdapterHealth(const AdapterHealthInput &in,
|
||||
uint32_t &reasons) {
|
||||
reasons = 0;
|
||||
bool checked = false;
|
||||
|
||||
if (!in.init_completed) {
|
||||
reasons |= kAdapterInitFailed;
|
||||
/* Enrich the abort with the fw stage that died (fatal-DLFW generations
|
||||
* throw out of bring-up; the status still says checksum vs boot). */
|
||||
if (in.fw.supported && in.fw.attempted && !in.fw.ready_ok)
|
||||
reasons |= kAdapterFwBootFailed;
|
||||
return AdapterVerdict::Failing;
|
||||
}
|
||||
|
||||
bool efuse_hard = false, efuse_soft = false;
|
||||
if (in.efuse.supported && in.efuse.reads > 0) {
|
||||
checked = true;
|
||||
const bool blank = in.efuse.mismatched_reads == 0 &&
|
||||
in.efuse.invalid_id_reads == in.efuse.reads &&
|
||||
in.efuse.eeprom_id == 0xFFFF;
|
||||
if (in.efuse.mismatched_reads > 0) {
|
||||
reasons |= kAdapterEfuseUnstable;
|
||||
efuse_hard = true;
|
||||
} else if (blank) {
|
||||
reasons |= kAdapterEfuseBlank;
|
||||
efuse_soft = true;
|
||||
} else if (in.efuse.invalid_id_reads > 0) {
|
||||
reasons |= kAdapterEfuseIdInvalid;
|
||||
efuse_soft = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool fw_bad = false;
|
||||
if (in.fw.supported && in.fw.attempted) {
|
||||
checked = true;
|
||||
if (!in.fw.ready_ok) {
|
||||
reasons |= kAdapterFwBootFailed;
|
||||
fw_bad = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool rx_hard = false, rx_soft = false;
|
||||
if (in.rx_checked) {
|
||||
checked = true;
|
||||
if (in.rx_frames_ok == 0) {
|
||||
if (in.rx_traffic_expected) {
|
||||
reasons |= kAdapterRxDeafToTraffic;
|
||||
rx_hard = true;
|
||||
} else {
|
||||
reasons |= kAdapterRxSilent;
|
||||
rx_soft = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!checked)
|
||||
return AdapterVerdict::Unknown;
|
||||
if (efuse_hard || rx_hard || (fw_bad && (efuse_soft || efuse_hard)) ||
|
||||
((reasons & kAdapterEfuseIdInvalid) && fw_bad))
|
||||
return AdapterVerdict::Failing;
|
||||
if (efuse_soft || fw_bad || rx_soft)
|
||||
return AdapterVerdict::Suspect;
|
||||
return AdapterVerdict::Healthy;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_ADAPTER_HEALTH_H */
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
|
||||
/* AmpduMode — the first-class 802.11 A-MPDU TX session knob, bundling the
|
||||
* recipe the spike + pacing sweep proved on-air (docs/aggregation.md). It
|
||||
* replaces the raw per-field spike knobs (DEVOURER_TX_QSEL / DEVOURER_TX_AMPDU,
|
||||
* which stay as a lower-level experimentation layer that composes on top).
|
||||
*
|
||||
* Two halves, both required for net goodput above plain singles:
|
||||
* 1. Per-frame descriptor: a data QSEL (aggregation only forms on a data
|
||||
* queue, never the monitor-inject MGMT queue 0x12), AGG_EN, MAX_AGG_NUM,
|
||||
* AMPDU_DENSITY, and — for the broadcast/no-BlockAck-peer case that
|
||||
* OpenIPC wfb wants — a per-frame retry limit of 0 (otherwise the MAC
|
||||
* re-airs each aggregate to the retry limit waiting for a BlockAck no
|
||||
* one sends: 92% wasted re-airings).
|
||||
* 2. MAC pacing registers (SetAmpduMode programs these live): the
|
||||
* aggregate-fill timer REG_AMPDU_MAX_TIME (0x0455 on the HalMAC chips,
|
||||
* 0x0456 on Jaguar1) and the burst-mode gate REG_SW_AMPDU_BURST_MODE_CTRL
|
||||
* (0x04BC). The bring-up timer value 0x70 paces each aggregate launch at
|
||||
* ~3 ms — 0x20 unlocks it to ~0.8 ms (the register is a CLIFF: values
|
||||
* <= 0x08 disable aggregation entirely). Clearing 0x04BC BIT6 (halmac
|
||||
* sets it) is worth ~+40% on the aggregated path (8822B-proven).
|
||||
*
|
||||
* The caller still has to keep the TX queue fed deep enough for the MAC to
|
||||
* have frames to aggregate — a shallow feed makes it SIFS-burst single-MPDU
|
||||
* aggregates (txdemo DEVOURER_TX_THREADS is the bench lever; a real feeder
|
||||
* pushes via send_packets with enough in flight). See docs/aggregation.md. */
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct AmpduMode {
|
||||
bool enabled = false; /* master switch — off keeps every TX byte-identical */
|
||||
|
||||
/* --- descriptor half --- */
|
||||
uint8_t tid = 0; /* QSEL / TID the aggregatable frames ride (0..7) */
|
||||
uint8_t max_num = 16; /* MAX_AGG_NUM: max MPDUs per A-MPDU (1..0x1f) */
|
||||
/* AMPDU_DENSITY (0..7 = min MPDU start spacing). Counter-intuitively 7 (the
|
||||
* most conservative spacing) is bench-fastest here — a permissive density
|
||||
* makes the MAC form well-shaped aggregates; density 0 measured ~10% slower.
|
||||
* Default 7 so a minimal "tid/max" spec is the full proven recipe. */
|
||||
uint8_t density = 7;
|
||||
/* Broadcast / no-BlockAck-peer flavor: per-frame retry limit 0, so each
|
||||
* aggregate airs exactly once (FEC covers loss, not ARQ). false = normal
|
||||
* retry limit (only sensible against a real BlockAck responder). */
|
||||
bool no_ack = true;
|
||||
|
||||
/* --- MAC pacing half (programmed by SetAmpduMode) --- */
|
||||
/* REG_AMPDU_MAX_TIME value. 0 = leave the bring-up default (0x70, ~3 ms).
|
||||
* 0x20 is the proven unlock; the register is a cliff — <= 0x08 kills
|
||||
* aggregation. */
|
||||
uint8_t max_time = 0x20;
|
||||
/* Clear REG_SW_AMPDU_BURST_MODE_CTRL BIT6 (halmac bring-up sets it).
|
||||
* 8822B-proven +40%; applied where the register exists (J2 / 8814A). */
|
||||
bool clear_burst_mode = true;
|
||||
};
|
||||
|
||||
/* Parse "tid/maxnum[/density[/noack[/maxtime_hex]]]" into an AmpduMode
|
||||
* (enabled=true). Returns false on a malformed leading field. Used by the
|
||||
* demos' DEVOURER_TX_AMPDU_MODE env front-end; the library itself takes the
|
||||
* struct. Examples: "0/16" (TID0, 16 MPDUs, defaults), "0/16/0/1/20"
|
||||
* (explicit no-ack, max_time 0x20). */
|
||||
inline bool parse_ampdu_mode(const char *spec, AmpduMode &out) {
|
||||
if (spec == nullptr || *spec == '\0')
|
||||
return false;
|
||||
char *end = nullptr;
|
||||
long tid = std::strtol(spec, &end, 0);
|
||||
if (tid < 0 || tid > 7 || end == spec)
|
||||
return false;
|
||||
AmpduMode m;
|
||||
m.enabled = true;
|
||||
m.tid = static_cast<uint8_t>(tid);
|
||||
if (end && *end == '/') {
|
||||
long mx = std::strtol(end + 1, &end, 0);
|
||||
if (mx > 0)
|
||||
m.max_num = static_cast<uint8_t>(mx & 0x1f);
|
||||
if (end && *end == '/') {
|
||||
m.density = static_cast<uint8_t>(std::strtol(end + 1, &end, 0) & 0x7);
|
||||
if (end && *end == '/') {
|
||||
m.no_ack = std::strtol(end + 1, &end, 0) != 0;
|
||||
if (end && *end == '/')
|
||||
m.max_time = static_cast<uint8_t>(std::strtol(end + 1, nullptr, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
out = m;
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,231 @@
|
||||
/* BeamformingSounder — Realtek 802.11ac explicit-sounding helpers for the
|
||||
* two-adapter "self-sounding" CSI path, shared across chip generations.
|
||||
*
|
||||
* With one adapter as beamformer and another as beamformee, an NDPA +
|
||||
* hardware-NDP exchange makes the beamformee emit a VHT Compressed Beamforming
|
||||
* report over the air, which a monitor RX captures — giving per-subcarrier
|
||||
* channel state the chip otherwise terminates in hardware. See
|
||||
* docs/beamforming-self-sounding.md.
|
||||
*
|
||||
* WHY THIS IS GENERATION-NEUTRAL: the MAC sounding registers are byte-identical
|
||||
* across the whole Realtek AC family — kSndPtclCtrl (0x718),
|
||||
* kBfmer0Info (0x6E4), REG_CSI_RPT_PARAM_BW20 (0x6F4), kBfmeeSel
|
||||
* (0x714), kTxbfCtrl (0x42C) are the same on 8192E/8703B/8723D/8812A/
|
||||
* 8814A/8822B/8822C/8822E (verified against every vendor include tree). The
|
||||
* beamformer arm (arm_sounder) is therefore fully shared. Only the beamformee
|
||||
* PHY details differ per generation, and those are captured in BfeeConfig:
|
||||
* - the sounding-protocol control byte (0xCB Jaguar-1 / 0xDB Jaguar-2/3);
|
||||
* - the BB CSI-content register 0x9B4 is CSI content on Jaguar-1 but the
|
||||
* NARROWBAND CLOCK DIVIDER on Jaguar-3 (RadioManagementJaguar3.h) — it
|
||||
* MUST NOT be written there, so csi_content_reg is 0 on Jaguar-2/3;
|
||||
* - Jaguar-2/3 additionally gate the responder behind RX-filter bits
|
||||
* (accept NDPA + action-no-ack) and an own-AID register (0x1680).
|
||||
*
|
||||
* Register values transcribed from the vendor beamformee-entry functions:
|
||||
* Jaguar-1 hal_txbf_jaguar_enter() (haltxbfjaguar.c)
|
||||
* Jaguar-2/3 hal_txbf_8822b_enter() (haltxbf8822b.c, shared 8822B/C/E)
|
||||
* Entry 0, P_AID = 0 (unassociated sounding — no CAM/macid entry).
|
||||
*/
|
||||
#ifndef BEAMFORMING_SOUNDER_H
|
||||
#define BEAMFORMING_SOUNDER_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace bf {
|
||||
|
||||
/* Shared MAC sounding registers (identical across the Realtek AC family).
|
||||
* k-prefixed to avoid colliding with the REG_* preprocessor macros in the
|
||||
* vendor hal_com_reg.h (macros ignore namespaces). */
|
||||
enum : uint16_t {
|
||||
kTxbfCtrl = 0x042C,
|
||||
kRxFltMap0 = 0x06A0, /* +1 bit6 = accept action-no-ack */
|
||||
kRxFltMap1 = 0x06A2, /* [5:4] = accept NDPA + BF report poll */
|
||||
kBfmer0Info = 0x06E4,
|
||||
kCsiRptParam20 = 0x06F4,
|
||||
kCsiRptParam40 = 0x06F8,
|
||||
kCsiRptParam80 = 0x06FC,
|
||||
kBfmeeSel = 0x0714,
|
||||
kSndPtclCtrl = 0x0718,
|
||||
kSndNdpStandby = 0x071B,
|
||||
kBbCsiContent = 0x09B4, /* Jaguar-1 only (clock divider on Jaguar-3) */
|
||||
kOurAid = 0x1680, /* Jaguar-2/3 only: our AID [11:0] */
|
||||
kBbpsfCtrl = 0x06DC, /* CSI GID select (BIT30 + gid BIT12) */
|
||||
kCsiRrsr = 0x1678, /* CSI response-rate set (= 0x550) */
|
||||
};
|
||||
|
||||
enum : uint8_t {
|
||||
kTxbfNdpaEnables = 0x10 | 0x40 | 0x80, /* 0x42F BIT4|6|7: NDPA TX enable */
|
||||
kRxFlt0ActNoAck = 0x40, /* 0x6A1 bit6 */
|
||||
kRxFlt1NdpaPoll = 0x30, /* 0x6A2 [5:4] */
|
||||
};
|
||||
|
||||
/* Per-generation beamformee knobs. */
|
||||
struct BfeeConfig {
|
||||
uint8_t snd_ptcl_ctrl; /* 0xCB Jaguar-1 / 0xDB Jaguar-2/3 */
|
||||
uint8_t ndp_standby; /* 0x50 */
|
||||
uint32_t csi_rpt_param; /* report matrix dims (1T1R VHT SU = 0x0109) */
|
||||
bool csi_rpt_param_16; /* 16-bit @0x6F4 (Jg2/3) vs 32-bit x3 (Jg1) */
|
||||
uint16_t csi_content_reg; /* 0x9B4 on Jaguar-1; 0 = skip on Jaguar-2/3 */
|
||||
uint32_t csi_content_val;
|
||||
bool set_our_aid; /* write 0 to 0x1680 (Jaguar-2/3) */
|
||||
bool set_rxflt; /* enable NDPA/action-no-ack RX (Jaguar-2/3) */
|
||||
};
|
||||
|
||||
/* Jaguar-1 (8812/8814/8821): BB CSI-content at 0x9B4, 32-bit params, no
|
||||
* RX-filter poke (monitor mode already accepts the frames). */
|
||||
constexpr BfeeConfig kBfeeJaguar1{
|
||||
/*snd_ptcl_ctrl*/ 0xCB, /*ndp_standby*/ 0x50,
|
||||
/*csi_rpt_param*/ 0x01080108, /*csi_rpt_param_16*/ false,
|
||||
/*csi_content_reg*/ kBbCsiContent, /*csi_content_val*/ 0x01081008,
|
||||
/*set_our_aid*/ false, /*set_rxflt*/ false};
|
||||
|
||||
/* Jaguar-2/3 (8822B/C/E): 0xDB, 16-bit param at 0x6F4, own-AID + RX-filter
|
||||
* gates, and NO 0x9B4 write (that address is the narrowband clock divider). */
|
||||
constexpr BfeeConfig kBfeeJaguar23{
|
||||
/*snd_ptcl_ctrl*/ 0xDB, /*ndp_standby*/ 0x50,
|
||||
/*csi_rpt_param*/ 0x0109, /*csi_rpt_param_16*/ true,
|
||||
/*csi_content_reg*/ 0, /*csi_content_val*/ 0,
|
||||
/*set_our_aid*/ true, /*set_rxflt*/ true};
|
||||
|
||||
/* Beamformer side (shared): arm the MAC sounding engine so a
|
||||
* TX-descriptor-marked NDPA is followed by a hardware-generated NDP.
|
||||
* Beamformee entry 0, P_AID = 0 (unassociated). The one per-generation byte is
|
||||
* the sounding-protocol control (0x718): 0xCB on Jaguar-1
|
||||
* (hal_txbf_jaguar_enter), 0xDB on Jaguar-2/3 (hal_txbf_8822b_enter). */
|
||||
inline void arm_sounder(RtlAdapter& dev, uint8_t snd_ptcl_ctrl = 0xCB) {
|
||||
dev.rtw_write8(kSndPtclCtrl, snd_ptcl_ctrl);
|
||||
dev.rtw_write8(kSndNdpStandby, 0x50);
|
||||
dev.rtw_write16(kTxbfCtrl, 0x0000); /* P_AID = 0 */
|
||||
uint8_t v = dev.rtw_read8(kTxbfCtrl + 3);
|
||||
dev.rtw_write8(kTxbfCtrl + 3, v | kTxbfNdpaEnables);
|
||||
uint8_t s = dev.rtw_read8(kBfmeeSel + 3);
|
||||
dev.rtw_write8(kBfmeeSel + 3, (s & 0x03) | 0x60);
|
||||
dev.rtw_write16(kBfmeeSel, 0x0200); /* entry-0 select */
|
||||
}
|
||||
|
||||
/* Beamformee side: arm the hardware CSI responder to reply to NDPA+NDP from
|
||||
* `beamformer_mac` (matched against the NDPA TA), no association required.
|
||||
* `cfg` selects the per-generation register recipe. */
|
||||
inline void arm_beamformee(RtlAdapter& dev, const uint8_t beamformer_mac[6],
|
||||
const BfeeConfig& cfg) {
|
||||
dev.rtw_write8(kSndPtclCtrl, cfg.snd_ptcl_ctrl);
|
||||
dev.rtw_write8(kSndNdpStandby, cfg.ndp_standby);
|
||||
for (uint16_t i = 0; i < 6; ++i)
|
||||
dev.rtw_write8(kBfmer0Info + i, beamformer_mac[i]);
|
||||
if (cfg.set_our_aid)
|
||||
dev.rtw_write16(kOurAid, 0x0000); /* our AID = 0 */
|
||||
if (cfg.set_rxflt) {
|
||||
uint8_t r0 = dev.rtw_read8(kRxFltMap0 + 1);
|
||||
dev.rtw_write8(kRxFltMap0 + 1, r0 | kRxFlt0ActNoAck);
|
||||
uint8_t r1 = dev.rtw_read8(kRxFltMap1);
|
||||
dev.rtw_write8(kRxFltMap1, r1 | kRxFlt1NdpaPoll);
|
||||
}
|
||||
if (cfg.csi_rpt_param_16) {
|
||||
dev.rtw_write16(kCsiRptParam20,
|
||||
static_cast<uint16_t>(cfg.csi_rpt_param));
|
||||
} else {
|
||||
dev.rtw_write32(kCsiRptParam20, cfg.csi_rpt_param);
|
||||
dev.rtw_write32(kCsiRptParam40, cfg.csi_rpt_param);
|
||||
dev.rtw_write32(kCsiRptParam80, cfg.csi_rpt_param);
|
||||
}
|
||||
if (cfg.csi_content_reg)
|
||||
dev.rtw_write32(cfg.csi_content_reg, cfg.csi_content_val);
|
||||
}
|
||||
|
||||
/* Beamformer-side steering entry — the TX-BF *apply* half, layered on top of
|
||||
* arm_sounder() (which already set SND_PTCL_CTRL, the TXBF_CTRL NDPA-enables +
|
||||
* P_AID=0, and BFMEE_SEL entry-0/TXUSER_ID0). This configures the entry so the
|
||||
* WMAC accepts the beamformee's Compressed Beamforming Report and builds the V
|
||||
* matrix from it IN HARDWARE (software never touches coefficients — see
|
||||
* reference/rtl88x2cu/hal/rtl8822c/rtl8822c_bf_monitor.c bf_monitor_config_*).
|
||||
* `peer_mac` = the beamformee we steer toward (each side writes the other's MAC
|
||||
* into BFMER0_INFO). `rx_nss` = GET_RX_NSS (2 on the 2T2R 8822B/C/E). Registers
|
||||
* are family-shared, so this is generation-neutral like arm_sounder. Apply is
|
||||
* NOT enabled here — call apply_vmatrix() once a CBR has been ingested. */
|
||||
inline void arm_beamformer_entry(RtlAdapter& dev, const uint8_t peer_mac[6],
|
||||
uint8_t rx_nss = 2, uint8_t g_id = 0) {
|
||||
for (uint16_t i = 0; i < 6; ++i)
|
||||
dev.rtw_write8(kBfmer0Info + i, peer_mac[i]);
|
||||
/* Expected CSI-report dims: nc=rx_nss-1, nr=1, grouping=0, codebook=1 (vht),
|
||||
* coeff=3 (bf_monitor_config_beamformer). */
|
||||
const uint8_t nc = rx_nss ? static_cast<uint8_t>(rx_nss - 1) : 0;
|
||||
const uint16_t csi_param =
|
||||
static_cast<uint16_t>((3u << 10) | (1u << 8) | (1u << 3) | nc);
|
||||
dev.rtw_write16(kCsiRptParam20, csi_param);
|
||||
dev.rtw_write8(kSndNdpStandby, 0x70); /* ndp_rx_standby_timer */
|
||||
uint32_t bbpsf = dev.rtw_read<uint32_t>(kBbpsfCtrl) | (1u << 30);
|
||||
bbpsf = (g_id == 63) ? (bbpsf | (1u << 12)) : (bbpsf & ~(1u << 12));
|
||||
dev.rtw_write<uint32_t>(kBbpsfCtrl, bbpsf);
|
||||
dev.rtw_write<uint32_t>(kCsiRrsr, 0x550);
|
||||
}
|
||||
|
||||
/* Flip the V-matrix apply toggle: TXBF_CTRL[11:9] per bandwidth (BIT9=20,
|
||||
* +BIT10=40, +BIT11=80) + DIS_NDP_BFEN (BIT15). Enable ONLY after the WMAC has
|
||||
* ingested a valid CBR (bf_monitor_enable_txbf gates on csi_matrix_len>0) —
|
||||
* enabling with no V degrades the link. `bw`: 0=20, 1=40, 2=80. */
|
||||
inline void apply_vmatrix(RtlAdapter& dev, bool enable, uint8_t bw) {
|
||||
uint32_t txbf = dev.rtw_read<uint32_t>(kTxbfCtrl);
|
||||
txbf &= ~((1u << 9) | (1u << 10) | (1u << 11));
|
||||
if (enable) {
|
||||
txbf |= (1u << 9);
|
||||
if (bw >= 1) txbf |= (1u << 10);
|
||||
if (bw >= 2) txbf |= (1u << 11);
|
||||
txbf |= (1u << 15); /* BIT_DIS_NDP_BFEN */
|
||||
}
|
||||
dev.rtw_write<uint32_t>(kTxbfCtrl, txbf);
|
||||
}
|
||||
|
||||
/* Jaguar-2/3 MU-beamformee registers (8822B/C/E). MU-BF group table. */
|
||||
enum : uint16_t {
|
||||
kMuTxCtl = 0x14C0, /* [10:8] STA-table index, [5:0] STA validity */
|
||||
kMuGidTab = 0x14C4, /* gid_valid table (reset to 0 here) */
|
||||
kMuUserPosL = 0x14C8, /* user-position low 32 */
|
||||
kMuUserPosH = 0x14CC, /* user-position high 32 */
|
||||
kMuBfmee0 = 0x1684, /* MU BFee entry 0 (2 bytes): [8:0] P_AID, BIT9 en */
|
||||
kNdpaRate = 0x045D, /* NDPA TX rate */
|
||||
kNdpaOpt = 0x045F, /* NDPA option ctrl */
|
||||
};
|
||||
|
||||
/* Beamformee MU layer: on top of arm_beamformee (which sets the SU responder
|
||||
* base — sounding enable, beamformer MAC, RX-filter), add the MU group-table
|
||||
* registers so the beamformee emits an MU report (which appends the per-tone
|
||||
* delta-SNR "MU Exclusive Beamforming Report" the SU report omits). For
|
||||
* self-sounding we program the group/user-position tables directly, skipping
|
||||
* the over-the-air VHT Group ID Management handshake the vendor normally does.
|
||||
* Recipe from hal_txbf_8822b_enter() MU BFee branch (haltxbf8822b.c:484-598),
|
||||
* MU register index 0: gid_valid=0x7fe, user_position_l=0x111110, p_aid=0. */
|
||||
inline void arm_beamformee_mu(RtlAdapter& dev, const uint8_t beamformer_mac[6],
|
||||
const BfeeConfig& cfg) {
|
||||
arm_beamformee(dev, beamformer_mac, cfg); /* SU responder base */
|
||||
|
||||
/* select MU STA table index 0 (0x14C0[10:8]=0), then mark it valid ([0]=1) */
|
||||
uint32_t mtc = dev.rtw_read<uint32_t>(kMuTxCtl);
|
||||
mtc &= ~0x0700u; /* index 0 */
|
||||
dev.rtw_write<uint32_t>(kMuTxCtl, mtc);
|
||||
mtc = (mtc & 0xFFFFFFC0u) | 0x01u; /* STA-0 valid */
|
||||
dev.rtw_write<uint32_t>(kMuTxCtl, mtc);
|
||||
|
||||
dev.rtw_write<uint32_t>(kMuGidTab, 0x00000000u); /* reset gid table */
|
||||
dev.rtw_write<uint32_t>(kMuUserPosL, 0x00111110u); /* index-0 user pos */
|
||||
dev.rtw_write<uint32_t>(kMuUserPosH, 0x00000000u);
|
||||
|
||||
uint16_t e = dev.rtw_read<uint16_t>(kMuBfmee0);
|
||||
e = (e & 0xFE00u) | 0x0200u; /* BIT9 enable, P_AID=0 */
|
||||
dev.rtw_write16(kMuBfmee0, e);
|
||||
|
||||
uint8_t t = dev.rtw_read8(kTxbfCtrl + 3);
|
||||
dev.rtw_write8(kTxbfCtrl + 3, t | 0xD0); /* CSI-report src bits */
|
||||
dev.rtw_write8(kNdpaRate, 0x04); /* NDPA 6M */
|
||||
uint8_t o = dev.rtw_read8(kNdpaOpt);
|
||||
dev.rtw_write8(kNdpaOpt, o & 0xFC);
|
||||
uint32_t sp = dev.rtw_read<uint32_t>(kSndPtclCtrl);
|
||||
dev.rtw_write<uint32_t>(kSndPtclCtrl, (sp & 0xFF0000FFu) | 0x00020200u);
|
||||
}
|
||||
|
||||
} // namespace bf
|
||||
} // namespace devourer
|
||||
|
||||
#endif // BEAMFORMING_SOUNDER_H
|
||||
@@ -0,0 +1,347 @@
|
||||
/* BfReportDecode — C++ decoder for 802.11ac VHT Compressed Beamforming reports.
|
||||
*
|
||||
* A direct port of the reference tool `tools/bf_report_decode.py`: it unpacks the
|
||||
* per-subcarrier Givens angles (phi, psi) out of a captured report frame, and a
|
||||
* `MotionMeter` turns a stream of reports into a Wi-Fi-sensing signal — the
|
||||
* per-tone cross-frame variance of psi. A moving person perturbs the channel, so
|
||||
* that variance rises across the whole band (broadband); a narrowband interferer
|
||||
* raises it on a few tones (localized). See docs/beamforming-victim-sensing.h.
|
||||
*
|
||||
* The compressed V matrix is the right singular vectors of the per-tone channel,
|
||||
* quantized as Givens rotation angles and packed LSB-first. For the 2-TX / 1-SS
|
||||
* sounding devourer drives (Nr=2, Nc=1) each subcarrier carries one phi then one
|
||||
* psi; psi = atan(|h_B|/|h_A|) is the relative per-tone channel between the
|
||||
* beamformer's two antennas — the quantity that jitters under channel motion.
|
||||
*
|
||||
* Header-only, like BeamformingSounder.h. No devourer runtime
|
||||
* dependency, so it is unit-testable in isolation (examples/sense/bf_report_decode_selftest.cpp). */
|
||||
#ifndef BF_REPORT_DECODE_H
|
||||
#define BF_REPORT_DECODE_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <vector>
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846
|
||||
#endif
|
||||
|
||||
namespace devourer::bf {
|
||||
|
||||
/* Subcarriers carried in a report, per bandwidth (0..3 = 20/40/80/160 MHz) and
|
||||
* grouping Ng (1/2/4). Matches NS_TABLE in the Python tool. 0 = unknown. */
|
||||
inline int report_ns(int bw, int ng) {
|
||||
static const int table[4][3] = {/* Ng=1, 2, 4 */
|
||||
{52, 30, 16},
|
||||
{108, 58, 30},
|
||||
{234, 122, 62},
|
||||
{468, 244, 124}};
|
||||
int gi = ng == 1 ? 0 : ng == 2 ? 1 : ng == 4 ? 2 : -1;
|
||||
if (bw < 0 || bw > 3 || gi < 0)
|
||||
return 0;
|
||||
return table[bw][gi];
|
||||
}
|
||||
|
||||
/* Parsed report header + the location of the V-angle bytes within the frame. */
|
||||
struct ReportHdr {
|
||||
int nc = 0, nr = 0; /* streams / rx antennas (already +1) */
|
||||
int bw = 0, ng = 0; /* bandwidth code, grouping */
|
||||
bool mu = false; /* feedback: MU (true) / SU (false) */
|
||||
bool vht = false; /* VHT (true) / HT (false) */
|
||||
int ns = 0; /* subcarriers (report_ns) */
|
||||
const uint8_t *angles = nullptr; /* first V-angle byte */
|
||||
size_t angle_len = 0; /* V-angle byte count (MU: clamped before the MU-SNR) */
|
||||
int per_sc_bits = 0; /* bits per subcarrier across all angles */
|
||||
};
|
||||
|
||||
/* True if `d`(n) is a VHT/HT Compressed Beamforming report; fills `hdr`. Mirrors
|
||||
* parse_frame() + the MU V-angle slice (ns*10 bits) in the Python tool. */
|
||||
/* fcs_present: does `d` still carry the trailing 4-byte FCS? Defaulted true
|
||||
* because that is what every Realtek backend delivers and what the captured
|
||||
* selftest fixture contains; pass RxAtrib.fcs_present when a Packet is in
|
||||
* reach, so a MediaTek frame is not shortened by four bytes of real payload. */
|
||||
inline bool parse_report(const uint8_t *d, size_t n, ReportHdr &hdr,
|
||||
bool fcs_present = true) {
|
||||
if (d == nullptr || n < 30)
|
||||
return false;
|
||||
uint8_t sub = d[0] & 0xF0;
|
||||
if (sub != 0xD0 && sub != 0xE0) /* Action / Action No-Ack */
|
||||
return false;
|
||||
uint8_t cat = d[24], act = d[25];
|
||||
bool vht = (cat == 0x15 && act == 0x00);
|
||||
bool ht = (cat == 0x07 && act == 0x00);
|
||||
if (!vht && !ht)
|
||||
return false;
|
||||
uint32_t mc = (uint32_t)d[26] | ((uint32_t)d[27] << 8) | ((uint32_t)d[28] << 16);
|
||||
hdr.nc = (int)(mc & 0x7) + 1;
|
||||
hdr.nr = (int)((mc >> 3) & 0x7) + 1;
|
||||
hdr.bw = (int)((mc >> 6) & 0x3);
|
||||
int ng_code = (int)((mc >> 8) & 0x3);
|
||||
hdr.ng = ng_code == 0 ? 1 : ng_code == 1 ? 2 : 4;
|
||||
hdr.mu = ((mc >> 11) & 0x1) != 0;
|
||||
hdr.vht = vht;
|
||||
hdr.ns = report_ns(hdr.bw, hdr.ng);
|
||||
const size_t fcs = fcs_present ? 4u : 0u;
|
||||
if (hdr.ns <= 0 || n < 30 + (size_t)hdr.nc + fcs)
|
||||
return false;
|
||||
const uint8_t *ab = d + 29 + hdr.nc; /* after per-column avg SNR */
|
||||
/* Drop the FCS only when the backend actually delivered one; the
|
||||
* MediaTek MAC strips it, and taking four bytes off there removes
|
||||
* real angle data (see rx_pkt_attrib::fcs_present). */
|
||||
size_t ab_len = n - (29 + (size_t)hdr.nc) - fcs;
|
||||
if (hdr.mu) {
|
||||
/* MU report: the V-angles are the first ns*10 bits (the Realtek compact 2x1
|
||||
* codebook); the MU Exclusive per-tone SNR follows and is not decoded here. */
|
||||
hdr.per_sc_bits = 10;
|
||||
size_t vbytes = ((size_t)hdr.ns * 10 + 7) / 8;
|
||||
if (vbytes > ab_len)
|
||||
return false;
|
||||
ab_len = vbytes;
|
||||
} else {
|
||||
size_t bits = ab_len * 8;
|
||||
if (bits % (size_t)hdr.ns != 0)
|
||||
return false;
|
||||
hdr.per_sc_bits = (int)(bits / (size_t)hdr.ns);
|
||||
}
|
||||
hdr.angles = ab;
|
||||
hdr.angle_len = ab_len;
|
||||
return hdr.per_sc_bits >= 2;
|
||||
}
|
||||
|
||||
/* LSB-first bit reader over the packed angle stream (802.11 packing order). */
|
||||
class BitReader {
|
||||
public:
|
||||
BitReader(const uint8_t *data, size_t len) : _d(data), _bits(len * 8) {}
|
||||
uint32_t read(int n) {
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (_pos >= _bits)
|
||||
break;
|
||||
uint32_t bit = (_d[_pos >> 3] >> (_pos & 7)) & 1u;
|
||||
v |= bit << i;
|
||||
++_pos;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
private:
|
||||
const uint8_t *_d;
|
||||
size_t _bits;
|
||||
size_t _pos = 0;
|
||||
};
|
||||
|
||||
inline double dequant_phi(uint32_t q, int b) {
|
||||
return (2.0 * q + 1.0) * M_PI / (double)(1u << b);
|
||||
}
|
||||
inline double dequant_psi(uint32_t q, int b) {
|
||||
return (2.0 * q + 1.0) * M_PI / (double)(1u << (b + 2));
|
||||
}
|
||||
|
||||
/* Number of (phi, psi) angle pairs per subcarrier for the compressed matrix
|
||||
* (802.11 §19.3.12.3.6). For the 2x1 case this is 1 phi + 1 psi. */
|
||||
inline void angle_counts(int nr, int nc, int &nphi, int &npsi) {
|
||||
nphi = 0;
|
||||
npsi = 0;
|
||||
int lim = nc < (nr - 1) ? nc : (nr - 1);
|
||||
for (int i = 1; i <= lim; ++i) {
|
||||
for (int r = i; r < nr; ++r)
|
||||
++nphi;
|
||||
for (int r = i; r < nr; ++r)
|
||||
++npsi;
|
||||
}
|
||||
if (nphi == 0 && npsi == 0) { /* defensive: treat as 2x1 */
|
||||
nphi = 1;
|
||||
npsi = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Decode the first phi and psi angle of every subcarrier for one report, given a
|
||||
* bit split. Returns false if the stream is too short. Layout per subcarrier is
|
||||
* nphi phi's (bphi bits each) then npsi psi's (bpsi bits each). Either output may
|
||||
* be null. */
|
||||
inline bool decode_angles(const ReportHdr &hdr, int bphi, int bpsi,
|
||||
std::vector<double> *phi_out,
|
||||
std::vector<double> *psi_out) {
|
||||
int nphi, npsi;
|
||||
angle_counts(hdr.nr, hdr.nc, nphi, npsi);
|
||||
size_t need = (size_t)hdr.ns * (size_t)(nphi * bphi + npsi * bpsi);
|
||||
if (need > hdr.angle_len * 8)
|
||||
return false;
|
||||
BitReader br(hdr.angles, hdr.angle_len);
|
||||
if (phi_out)
|
||||
phi_out->assign(hdr.ns, 0.0);
|
||||
if (psi_out)
|
||||
psi_out->assign(hdr.ns, 0.0);
|
||||
for (int k = 0; k < hdr.ns; ++k) {
|
||||
double first_phi = 0.0, first_psi = 0.0;
|
||||
for (int p = 0; p < nphi; ++p) {
|
||||
double phi = dequant_phi(br.read(bphi), bphi);
|
||||
if (p == 0)
|
||||
first_phi = phi;
|
||||
}
|
||||
for (int p = 0; p < npsi; ++p) {
|
||||
double psi = dequant_psi(br.read(bpsi), bpsi);
|
||||
if (p == 0)
|
||||
first_psi = psi;
|
||||
}
|
||||
if (phi_out)
|
||||
(*phi_out)[k] = first_phi;
|
||||
if (psi_out)
|
||||
(*psi_out)[k] = first_psi;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Convenience: decode only psi (the amplitude-ratio angle). */
|
||||
inline bool decode_psi(const ReportHdr &hdr, int bphi, int bpsi,
|
||||
std::vector<double> &psi_out) {
|
||||
return decode_angles(hdr, bphi, bpsi, nullptr, &psi_out);
|
||||
}
|
||||
|
||||
/* Pick (bphi, bpsi) for a per-subcarrier budget. The 802.11 compressed-Givens
|
||||
* codebook ALWAYS pairs b_phi = b_psi + 2 (the codebook table is
|
||||
* (bpsi,bphi) in {(1,3),(2,4),(3,5),(4,6),(5,7),(7,9)}), so we only ever
|
||||
* consider splits that satisfy it. This is essential, not cosmetic: an
|
||||
* unconstrained search that minimises cross-frame psi variance is fooled by a
|
||||
* too-coarse psi — e.g. at (bphi=8,bpsi=2) the 2-bit psi is trivially constant
|
||||
* (variance 0), so it "wins" the search, but that split is bit-misaligned and
|
||||
* its phi decodes to garbage that jitters ~30x more on a static channel than
|
||||
* the correct (6,4) split. Among the (usually one) valid Givens splits, break
|
||||
* ties by minimum cross-frame psi variance. Returns false if none fits. */
|
||||
inline bool pick_split(const std::vector<ReportHdr> &batch, int &bphi_out,
|
||||
int &bpsi_out) {
|
||||
if (batch.empty())
|
||||
return false;
|
||||
int per = batch[0].per_sc_bits, ns = batch[0].ns;
|
||||
int nphi, npsi;
|
||||
angle_counts(batch[0].nr, batch[0].nc, nphi, npsi);
|
||||
double best_var = 1e300;
|
||||
bool found = false;
|
||||
for (int bpsi = 1; bpsi <= per; ++bpsi) {
|
||||
int bphi = bpsi + 2; /* enforce the standard Givens codebook relationship */
|
||||
if (nphi * bphi + npsi * bpsi != per)
|
||||
continue;
|
||||
/* mean cross-frame variance of psi[k], averaged over tones */
|
||||
std::vector<double> sum(ns, 0.0), sumsq(ns, 0.0);
|
||||
int nfr = 0;
|
||||
bool ok = true;
|
||||
for (const auto &h : batch) {
|
||||
std::vector<double> psi;
|
||||
if (!decode_psi(h, bphi, bpsi, psi)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
for (int k = 0; k < ns; ++k) {
|
||||
sum[k] += psi[k];
|
||||
sumsq[k] += psi[k] * psi[k];
|
||||
}
|
||||
++nfr;
|
||||
}
|
||||
if (!ok || nfr == 0)
|
||||
continue;
|
||||
double var = 0.0;
|
||||
for (int k = 0; k < ns; ++k) {
|
||||
double m = sum[k] / nfr;
|
||||
var += sumsq[k] / nfr - m * m;
|
||||
}
|
||||
var /= ns;
|
||||
if (var < best_var) {
|
||||
best_var = var;
|
||||
bphi_out = bphi;
|
||||
bpsi_out = bpsi;
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/* Sliding-window Wi-Fi-sensing meter: per-tone cross-frame variance of psi over
|
||||
* the last `window` reports, and the aggregate "motion energy" (mean over tones).
|
||||
* Fixed split (calibrated once) so the variance is comparable frame to frame. */
|
||||
class MotionMeter {
|
||||
public:
|
||||
MotionMeter(int ns, int bphi, int bpsi, size_t window = 64)
|
||||
: _ns(ns), _bphi(bphi), _bpsi(bpsi), _window(window) {}
|
||||
|
||||
/* Decode one report and add its phi[k] to the window. phi (the inter-antenna
|
||||
* phase, finely quantized) is far more sensitive to motion than psi. Returns
|
||||
* false if the report's geometry doesn't match this meter (ns) or decode
|
||||
* failed. */
|
||||
bool push(const ReportHdr &hdr) {
|
||||
if (hdr.ns != _ns)
|
||||
return false;
|
||||
std::vector<double> phi;
|
||||
if (!decode_angles(hdr, _bphi, _bpsi, &phi, nullptr))
|
||||
return false;
|
||||
_buf.push_back(std::move(phi));
|
||||
while (_buf.size() > _window)
|
||||
_buf.pop_front();
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t count() const { return _buf.size(); }
|
||||
|
||||
/* Per-tone circular variance of phi over the window: 1 - |mean(e^{i*phi})|,
|
||||
* in [0,1]. 0 = the tone's phase is constant (static channel); toward 1 = the
|
||||
* phase is scattered (the channel is changing frame-to-frame). Circular so it
|
||||
* handles the 0/2*pi wrap. */
|
||||
std::vector<double> per_tone_var() const {
|
||||
std::vector<double> var(_ns, 0.0);
|
||||
size_t n = _buf.size();
|
||||
if (n < 2)
|
||||
return var;
|
||||
for (int k = 0; k < _ns; ++k) {
|
||||
double cr = 0.0, ci = 0.0;
|
||||
for (const auto &f : _buf) {
|
||||
cr += std::cos(f[k]);
|
||||
ci += std::sin(f[k]);
|
||||
}
|
||||
double r = std::sqrt(cr * cr + ci * ci) / n;
|
||||
var[k] = 1.0 - r;
|
||||
}
|
||||
return var;
|
||||
}
|
||||
|
||||
/* Aggregate motion energy in [0,1]: mean per-tone circular variance. */
|
||||
double motion_energy() const {
|
||||
auto v = per_tone_var();
|
||||
if (v.empty())
|
||||
return 0.0;
|
||||
double s = 0.0;
|
||||
for (double x : v)
|
||||
s += x;
|
||||
return s / v.size();
|
||||
}
|
||||
|
||||
/* True when the elevated variance is concentrated on a few adjacent tones (a
|
||||
* narrowband interferer) rather than spread across the band (human motion).
|
||||
* Heuristic: peak tone variance >> median. */
|
||||
bool localized() const {
|
||||
auto v = per_tone_var();
|
||||
if (v.size() < 6)
|
||||
return false;
|
||||
std::vector<double> s = v;
|
||||
std::sort(s.begin(), s.end());
|
||||
double median = s[s.size() / 2];
|
||||
double peak = s.back();
|
||||
/* count tones within 50% of the peak — few = localized, many = broadband */
|
||||
double thr = peak * 0.5;
|
||||
int hot = 0;
|
||||
for (double x : v)
|
||||
if (x >= thr)
|
||||
++hot;
|
||||
return median > 1e-9 && peak > 6.0 * median && hot <= (int)v.size() / 6;
|
||||
}
|
||||
|
||||
private:
|
||||
int _ns, _bphi, _bpsi;
|
||||
size_t _window;
|
||||
std::deque<std::vector<double>> _buf;
|
||||
};
|
||||
|
||||
} // namespace devourer::bf
|
||||
|
||||
#endif /* BF_REPORT_DECODE_H */
|
||||
@@ -0,0 +1,99 @@
|
||||
#ifndef DEVOURER_CFO_TRACKER_H
|
||||
#define DEVOURER_CFO_TRACKER_H
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Closed-loop carrier-frequency-offset tracker (issue #217). Ported from the
|
||||
* vendor phydm_cfo_tracking control law: accumulate the per-frame path-A CFO
|
||||
* tail from the RX phy-status, and on a periodic tick step the crystal-cap
|
||||
* trim (IRtlRadio::SetXtalCap) by ±1 to drive the average CFO toward zero.
|
||||
*
|
||||
* A bang-bang integrator with hysteresis: it starts correcting once |CFO|
|
||||
* exceeds an enable threshold and stops inside a deadband, so it doesn't
|
||||
* dither when already aligned. One cap step per tick keeps it gentle enough
|
||||
* to track slow crystal warm-up drift without hunting. The receiver trims its
|
||||
* OWN crystal to null the offset it measures against the transmitter — the
|
||||
* natural single-ended loop in monitor mode (the TX is passive).
|
||||
*
|
||||
* CFO units: the phy-status tail is a signed HW code; the vendor
|
||||
* CFO_HW_RPT_2_KHZ macro is code * 2.5, but that assumes the 20 MHz FFT grid —
|
||||
* for the narrowband (5/10 MHz) re-clock the true kHz scale is smaller (bench
|
||||
* cross-check against the SDR LO shift suggests the 2.5 figure reads ~10x
|
||||
* high here), so treat the reported magnitude as a relative error signal, not
|
||||
* a calibrated kHz. The controller only needs the SIGN (which way to trim) and
|
||||
* a deadband; both hold under an uncalibrated linear scale. Thresholds are the
|
||||
* vendor's 11/10 (in the same reported units). */
|
||||
class CfoTracker {
|
||||
public:
|
||||
/* Per-frame CFO tail from the OFDM phy-status (rx_pkt_attrib::cfo_tail). */
|
||||
void add(int8_t cfo_tail) {
|
||||
_sum += cfo_tail;
|
||||
++_cnt;
|
||||
}
|
||||
|
||||
/* Periodic control tick. `cur_cap` is the current crystal-cap code,
|
||||
* `cap_max` the trim ceiling. Returns the new cap to apply, or -1 for no
|
||||
* change (no frames since last tick, inside the deadband, or already at a
|
||||
* rail). `avg_khz_out` (optional) receives the measured average CFO. */
|
||||
int step(int cur_cap, int cap_max, double *avg_khz_out = nullptr) {
|
||||
if (_cnt == 0)
|
||||
return -1;
|
||||
const double avg_khz = (static_cast<double>(_sum) / _cnt) * 2.5;
|
||||
_sum = 0;
|
||||
_cnt = 0;
|
||||
if (avg_khz_out)
|
||||
*avg_khz_out = avg_khz;
|
||||
const double mag = std::fabs(avg_khz);
|
||||
|
||||
/* Auto-detect the cap->CFO polarity: the sign that reduces a positive CFO
|
||||
* flips per silicon (some cap circuits raise the LO with cap, some lower
|
||||
* it). If the previous step made |CFO| worse, the guess was backwards —
|
||||
* flip it, once. */
|
||||
if (_stepped && mag > _prev_mag + 1.0)
|
||||
_invert = !_invert;
|
||||
_stepped = false;
|
||||
|
||||
if (!_adjust) {
|
||||
if (mag > kEnableThKhz)
|
||||
_adjust = true;
|
||||
else {
|
||||
_prev_mag = mag;
|
||||
return -1;
|
||||
}
|
||||
} else if (mag <= kStopThKhz) {
|
||||
_adjust = false;
|
||||
_prev_mag = mag;
|
||||
return -1;
|
||||
}
|
||||
int dir = avg_khz > 0 ? +1 : -1;
|
||||
if (_invert)
|
||||
dir = -dir;
|
||||
int nc = cur_cap + dir;
|
||||
if (nc < 0)
|
||||
nc = 0;
|
||||
if (nc > cap_max)
|
||||
nc = cap_max;
|
||||
_prev_mag = mag;
|
||||
if (nc == cur_cap)
|
||||
return -1;
|
||||
_stepped = true;
|
||||
return nc;
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr double kEnableThKhz = 11.0;
|
||||
static constexpr double kStopThKhz = 10.0;
|
||||
long _sum = 0;
|
||||
int _cnt = 0;
|
||||
bool _adjust = false;
|
||||
bool _invert = false;
|
||||
bool _stepped = false;
|
||||
double _prev_mag = 0.0;
|
||||
};
|
||||
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CFO_TRACKER_H */
|
||||
@@ -0,0 +1,42 @@
|
||||
#ifndef CHANNEL_FREQ_H
|
||||
#define CHANNEL_FREQ_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
/* Wi-Fi channel <-> center-frequency mapping shared by the per-packet radiotap
|
||||
* CHANNEL hop path (library side, all generations) and the demos' hop/sweep
|
||||
* spec parsing. Generation-neutral, header-only. */
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Map a radiotap CHANNEL frequency (MHz) to a Wi-Fi channel number. Returns 0
|
||||
* for a frequency outside the bands devourer drives (caller ignores it).
|
||||
*
|
||||
* The 5 GHz clause deliberately runs past the UNII channels: the RF
|
||||
* synthesizer on these chips covers roughly 5080..6165 MHz (vendor
|
||||
* rtl88x2bu "monitor_chan_override": chan 16..253, freq = 5000 + 5*chan),
|
||||
* so any 5 MHz-gridded frequency up to chan 253 maps to a tunable channel.
|
||||
* Channel stays uint8_t everywhere; 253 is the ceiling. Not every chip
|
||||
* locks every frequency — out-of-band use is validated per chip, and TX
|
||||
* power there is extrapolated from the nearest characterized channel. */
|
||||
static inline int freq_to_chan(uint16_t freq_mhz) {
|
||||
if (freq_mhz == 2484)
|
||||
return 14;
|
||||
if (freq_mhz >= 2412 && freq_mhz <= 2472)
|
||||
return (freq_mhz - 2407) / 5; /* 2.4 GHz ch1..13 */
|
||||
if (freq_mhz >= 5000 && freq_mhz <= 6265)
|
||||
return (freq_mhz - 5000) / 5; /* 5 GHz ch, incl. extended synth range */
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Wi-Fi channel number -> center frequency (MHz), for the radiotap CHANNEL
|
||||
* field that drives the library's per-packet retune (DEVOURER_HOP_RADIOTAP). */
|
||||
static inline uint16_t chan_to_freq(int ch) {
|
||||
if (ch == 14) return 2484;
|
||||
if (ch <= 14) return static_cast<uint16_t>(2407 + 5 * ch);
|
||||
return static_cast<uint16_t>(5000 + 5 * ch);
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* CHANNEL_FREQ_H */
|
||||
@@ -0,0 +1,564 @@
|
||||
#pragma once
|
||||
|
||||
/* DeviceConfig — construction-time configuration, passed to
|
||||
* WiFiDriver::CreateRadio (defaulted: CreateRadio(handle) gives stock
|
||||
* behaviour). Fields are fixed for the device's lifetime; knobs that change
|
||||
* mid-session are runtime setters on IRadio / the concrete device classes
|
||||
* (SetTxMode, SetTxPowerOffsetQdb, SetRxPathMask, SetCcaMode, ...).
|
||||
*
|
||||
* The example binaries populate this from DEVOURER_* environment variables via
|
||||
* examples/common/env_config.{h,cpp}; each field's `env:` tag names its
|
||||
* spelling in that translator and its value grammar. */
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "AmpduMode.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* 6-byte MAC address carrier (replaces the per-site uint8_t[6] + sscanf). */
|
||||
struct MacAddr {
|
||||
std::array<uint8_t, 6> bytes{};
|
||||
const uint8_t *data() const { return bytes.data(); }
|
||||
};
|
||||
|
||||
/* "aa:bb:cc:dd:ee:ff" (hex, case-insensitive) -> MacAddr; nullopt on any
|
||||
* malformed input. */
|
||||
inline std::optional<MacAddr> parse_mac(std::string_view s) {
|
||||
MacAddr m;
|
||||
unsigned v[6];
|
||||
char tail;
|
||||
/* string_view is not NUL-terminated in general — bounce through a string. */
|
||||
std::string z(s);
|
||||
if (std::sscanf(z.c_str(), "%x:%x:%x:%x:%x:%x%c", &v[0], &v[1], &v[2], &v[3],
|
||||
&v[4], &v[5], &tail) != 6)
|
||||
return std::nullopt;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (v[i] > 0xFF)
|
||||
return std::nullopt;
|
||||
m.bytes[i] = static_cast<uint8_t>(v[i]);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Jaguar-1 regulatory domain for the efuse TX-power limit tables. */
|
||||
enum class Regulation : uint8_t { FCC = 0, ETSI = 1, MKK = 2, WW = 3 };
|
||||
|
||||
/* 8814A firmware-download path select. */
|
||||
enum class Fwdl8814Path : uint8_t {
|
||||
KernelBracket, /* kernel-faithful bracket (default) */
|
||||
Rtw88, /* legacy rtw88-mimic sequence (A/B fallback) */
|
||||
};
|
||||
|
||||
/* 8822E DPDT antenna-transfer-switch routing (board A/B). */
|
||||
enum class Dpdt8822eMode : uint8_t {
|
||||
EfemPinmux, /* kernel _efem_pinmux_config port — DPDT under HW TX/RX
|
||||
control, both RX chains live (default) */
|
||||
Legacy, /* improvised b5a6df7 static write: 0x4c[24] set, [22] clear
|
||||
(TX-favoring, RX chain B antenna-less) */
|
||||
Bit24, /* 0x4c[24] only (halmac WL_DPDT_SEL bit alone) */
|
||||
Skip, /* leave the DPDT/pin-mux untouched */
|
||||
};
|
||||
|
||||
/* USB RX-ring servicing strategy (UsbTransport::rx_loop). The default async
|
||||
* ring runs the consumer inline on the libusb pump thread before resubmitting
|
||||
* each URB, so a slow consumer under a burst can stall resubmit and collapse
|
||||
* the armed-URB depth. The other modes trade that coupling off for A/B study:
|
||||
* a blocking single-buffer reference, and two buffer-pool variants that re-arm
|
||||
* the ring with a spare buffer before consuming the received one. */
|
||||
enum class RxMode : uint8_t {
|
||||
Async, /* current: consume inline, then resubmit the same URB */
|
||||
Sync, /* blocking single-buffer bulk-IN read loop (legacy reference) */
|
||||
ReorderPool, /* swap a spare buffer onto the wire, resubmit, then consume */
|
||||
SpscFat, /* pool + SPSC hand-off to a consumer thread (deep absorption) */
|
||||
Decoupled, /* naive worker-thread hand-off (known-bad A/B control) */
|
||||
};
|
||||
|
||||
/* Hardware retry rate-fallback control for injected frames. The HalMAC
|
||||
* generations default to the firmware's fallback ladder, whose rate-space is
|
||||
* the descriptor's RA group (rateid_for_mgn, RateDefinitions.h) — with the
|
||||
* family-correct group the ladder is MCS-native, witness-measured per copy
|
||||
* (tests/retry_ladder_probe.sh): 8822B MCS3 -> MCS2 -> MCS1 -> MCS0 (pure),
|
||||
* 8822C MCS3 x4 -> MCS2 -> 6M floor (CCK floor at 2.4 GHz; VHT steps
|
||||
* M7 -> M4 -> M1 -> M0 -> 6M). Jaguar1's fw does not step at all — every
|
||||
* retry at the descriptor rate regardless of this knob (8821AU-measured).
|
||||
* Off pins every retry at the descriptor DATARATE (DISDATAFB / DISABLE_FB =
|
||||
* 1; measured: 1,200/1,200 retried frames re-aired at the original rate) —
|
||||
* for constant-rate links where a step-down retry costs extra airtime. A
|
||||
* DATA_RTY_LOWEST_RATE floor form was measured and REJECTED: the fw
|
||||
* reinterprets the bound inside the RA-group rate space, wandering retries
|
||||
* into VHT rates (final_rate 45 = VHT1SS_MCS1 on an HT frame) with a 20x
|
||||
* retry inflation — the field is not a plain DESC_RATE bound on this fw. */
|
||||
enum class RetryFallback : uint8_t { Default, Off };
|
||||
|
||||
/* What the spsc-fat ring does when its buffer pool runs dry (consumer behind
|
||||
* under sustained overload). The choice decides which side of the hardware-ARQ
|
||||
* contract survives overload — the chip ACKs on FIFO admission, so anything
|
||||
* the HOST discards afterwards is a loss the TX peer believes delivered. */
|
||||
enum class PoolExhaust : uint8_t {
|
||||
Backpressure, /* park the URB unarmed: the chip FIFO fills and the chip
|
||||
* declines further ACKs — congestion loss stays ARQ-visible
|
||||
* (bench: 14,214/14,214 forced drops reported ok=0 and
|
||||
* retried). Ring re-arms as the consumer returns buffers. */
|
||||
Drop, /* keep the ring armed and discard the payload — the chip
|
||||
* already ACKed it, so the TX peer logs it delivered and
|
||||
* never retries (counted as rx.ring pool_dropped). Smoother
|
||||
* under overload, but only for consumers that accept silent
|
||||
* loss (no ARQ / delivery accounting on top). */
|
||||
};
|
||||
|
||||
struct DeviceConfig {
|
||||
/* ---- RX ------------------------------------------------------------- */
|
||||
struct Rx {
|
||||
/* env: DEVOURER_RX_KEEP_CORRUPTED — pass frames that fail the 802.11 FCS
|
||||
* (CRC32) or decryption-ICV check up to the host instead of dropping them
|
||||
* at the WMAC filter (sets RCR ACRC32|AICV). Jaguar1 + Jaguar2. */
|
||||
bool keep_corrupted = false;
|
||||
/* env: DEVOURER_TX_WITH_RX — Jaguar3 only: keep the RX filters open and
|
||||
* enable the RX path during a TX (InitWrite) bring-up so StartRxLoop can
|
||||
* run on the same handle. Must be decided before InitWrite (retrofitting
|
||||
* RX onto a TX-only bring-up is unreliable on this generation). */
|
||||
bool enable_with_tx = false;
|
||||
/* env: DEVOURER_RX_CSI_MASK — "<f_lo>[-<f_hi>][/wgt]" MHz: de-weight a
|
||||
* frequency range in the RX equalizer's per-tone CSI mask (ToneMask.h).
|
||||
* Applied when the RX loop starts; a channel switch reverts it. */
|
||||
std::optional<std::string> csi_mask;
|
||||
/* env: DEVOURER_RX_NBI — "<f_mhz>": arm the narrowband-interference notch
|
||||
* at one in-channel frequency (LUT-quantized). Same lifecycle as
|
||||
* csi_mask. */
|
||||
std::optional<std::string> nbi;
|
||||
/* env: DEVOURER_RX_PATHS — Jaguar1 RX-chain mask spec: "0xNN" applies one
|
||||
* mask (sticky across channel sets, see SetRxPathMask); the toggle form
|
||||
* "0xAA:0xBB[:0xCC]@<ms>" cycles masks on a timer thread. */
|
||||
std::optional<std::string> path_spec;
|
||||
/* env: DEVOURER_RX_URBS — Jaguar1 async bulk-IN URB queue depth
|
||||
* (default 8, clamped to >= 1). */
|
||||
std::optional<int> urbs;
|
||||
/* env: DEVOURER_RX_URB_BYTES — per-URB bulk-IN buffer size on the 11ac
|
||||
* generations (default 16384, clamped to >= 4096). Keep it at 16 KB unless
|
||||
* you also raise the device-side RX aggregation thresholds: some MediaTek
|
||||
* Android xhci hosts never complete a bulk-IN read larger than 16 KB
|
||||
* (LIBUSB_ERROR_TIMEOUT forever, zero RX — OpenIPC/PixelPilot#6, fixed by
|
||||
* #19, regressed by the #213 transport split), and the device-side
|
||||
* aggregation caps (J1 0x3/4KB-pages, J2/J3 0x3) mean a bigger URB never
|
||||
* fills past 16 KB anyway. Kestrel ignores this knob: the 8852C RXAGG
|
||||
* LEN_TH is ~20 KB and its ring must hold a full aggregate (32 KB). */
|
||||
std::optional<int> urb_bytes;
|
||||
/* env: DEVOURER_RX_MODE — USB RX-ring servicing strategy (RxMode above).
|
||||
* Default async = the current inline-consume-then-resubmit ring. The other
|
||||
* modes are A/B / fix vehicles for the burst-starvation study. */
|
||||
RxMode rx_mode = RxMode::Async;
|
||||
/* env: DEVOURER_RX_POOL_SPARE — extra RX buffers beyond the URB count for
|
||||
* the buffer-pool modes (ReorderPool/SpscFat): a deeper pool absorbs a
|
||||
* burst backlog host-side instead of overflowing the chip RX FIFO. 0 =
|
||||
* pool of exactly urbs buffers (no spare). Ignored by async/sync. */
|
||||
int pool_spare = 0;
|
||||
/* env: DEVOURER_RX_POOL_EXHAUST — "backpressure" (default) | "drop":
|
||||
* the SpscFat pool-exhaustion policy (see PoolExhaust above). Only read
|
||||
* by SpscFat; the other modes never drop host-side (async/reorder degrade
|
||||
* to inline consume, which backpressures the chip by construction). */
|
||||
PoolExhaust pool_exhaust = PoolExhaust::Backpressure;
|
||||
/* env: DEVOURER_RX_RING_MS — cadence (ms) for the diagnostic rx.ring
|
||||
* telemetry event (armed-URB depth, min depth in the window, resubmit
|
||||
* failures, max inline-consume latency). Unset/0 = no telemetry (the
|
||||
* default RX path is then byte-for-byte unchanged). */
|
||||
std::optional<int> ring_ms;
|
||||
/* env: DEVOURER_8821C_NO_PHYST (inverted) — 8821C: prepend the 32-byte
|
||||
* PHY-status to RX frames (per-frame RSSI/SNR/EVM). Disable only for the
|
||||
* leanest possible RX path. */
|
||||
bool phy_status_8821c = true;
|
||||
/* env: DEVOURER_RX_NOISE_FLOOR — opt-in active/frame-free ABSOLUTE noise
|
||||
* floor (dBm) in GetRxEnergy/GetRxQuality (RxEnergy.abs_noise_floor_dbm).
|
||||
* OFF by default: the vendor idle-noise measurement adds ~10 ms of USB
|
||||
* round-trips. Jaguar2 measures it live (wedge-free HW idle-noise report);
|
||||
* Jaguar1 8812A/8821A measure it RX-idle (a CAL bracket); Jaguar3 and others
|
||||
* leave it invalid (no vendor path). */
|
||||
bool abs_noise_floor = false;
|
||||
/* env: DEVOURER_IGI — Jaguar2 fixed initial-gain index override, 7 bits
|
||||
* (unset = 0x40, the FA-rate-validated default). */
|
||||
std::optional<uint8_t> igi;
|
||||
/* env: DEVOURER_ACK_RESPONDER=<unicast mac> — arm the hardware ACK
|
||||
* responder at the end of bring-up (src/AckResponder.h): the MAC
|
||||
* auto-ACKs unicast frames addressed to this MAC while monitor RX and
|
||||
* injection continue unchanged. Runtime equivalent: SetAckResponder /
|
||||
* ClearAckResponder. Retargeting hardware responses to a caller-supplied
|
||||
* address is opt-in; some dies, notably RTL8733B, may already answer for
|
||||
* the initialization MAC before this option is set. */
|
||||
std::optional<MacAddr> ack_responder;
|
||||
} rx;
|
||||
|
||||
/* ---- TX ------------------------------------------------------------- */
|
||||
struct Tx {
|
||||
/* env: DEVOURER_TX_EP — bulk-OUT endpoint override (unset = first
|
||||
* descriptor-walked bulk-OUT endpoint, fallback 0x02). */
|
||||
std::optional<uint8_t> ep;
|
||||
/* env: DEVOURER_TX_TIMEOUT_MS — TX bulk-OUT transfer timeout (unset =
|
||||
* USB_TIMEOUT). */
|
||||
std::optional<unsigned> timeout_ms;
|
||||
/* env: DEVOURER_TX_LEGACY_8812_DESC — 8814A: keep the legacy 8812-style
|
||||
* TX-descriptor bits instead of the 8814-native layout. */
|
||||
bool legacy_8812_desc = false;
|
||||
/* env: DEVOURER_TX_PWR — Jaguar2: flat TXAGC index (0..63) applied at the
|
||||
* end of InitWrite via SetTxPowerIndexOverride (composes with the offset
|
||||
* knob and shows up in GetTxPowerState). Debug/SDR-visibility knob. */
|
||||
std::optional<int> power_index;
|
||||
/* env: DEVOURER_TX_RF_BW — Jaguar3 40 MHz: force the 0x9b0 TX_RF_BW field
|
||||
* (2 bits; kernel-stall study knob). */
|
||||
std::optional<uint8_t> rf_bw;
|
||||
/* env: DEVOURER_CW_TONE / DEVOURER_CW_TONE_GAIN — radiate a bare RF LO
|
||||
* carrier (MP single-tone) after bring-up; gain = RF 0x00[4:0], 0..31.
|
||||
* Runtime equivalent: StartCwTone/StopCwTone on the concrete device. */
|
||||
bool cw_tone = false;
|
||||
uint8_t cw_tone_gain = 0;
|
||||
/* env: DEVOURER_TX_RETRY_LIMIT — per-frame hardware retry limit (0..63;
|
||||
* Kestrel ceiling 62 — its attempts-counting WD field folds +1). Maps to
|
||||
* the TX descriptor DATA_RETRY_LIMIT / RTS_DATA_RTY_LMT field on the
|
||||
* 11ac generations and the RTL8733B, and wd_info DATA_TXCNT_LMT on
|
||||
* Kestrel. 0 = no retries
|
||||
* (WFB default: FEC provides reliability, not MAC retries). On a busy
|
||||
* half-duplex link retries flood the air and blind the receiver.
|
||||
* Hardware-ARQ (SetAckResponder + unicast TA, docs/scheduled-mac.md)
|
||||
* needs a nonzero value. Inert on the 8814A die only (vendor
|
||||
* DATA_RETRY_LIMIT=0 carve-out kept pending its bench). */
|
||||
int retry_limit = 0;
|
||||
/* env: DEVOURER_ACK_TIMEOUT_US — hardware ACK response window in µs
|
||||
* (1..255, clamped), the hardware-ARQ RANGE lever: the MAC writes a
|
||||
* frame off (and retries) when no ACK is counted within this window,
|
||||
* and round-trip propagation eats ~6.7 µs per km. ONE default, 128 µs,
|
||||
* programmed identically on every generation at bring-up — the same
|
||||
* knob value means the same range budget (~15 km round trip) no matter
|
||||
* which die is plugged. 128 is the vendor's interop-blessed J1/J2
|
||||
* value and covers the slowest narrowband ACK in the tree (the 5 MHz
|
||||
* per-bandwidth vendor value is 117 µs), so it also replaces the
|
||||
* per-chip / per-bandwidth vendor defaults (which ranged 33..128 µs
|
||||
* and made hardware-ARQ range silently die-dependent). The register:
|
||||
* REG_ACKTO 0x640 on the 11ac generations; RTL8733B programs both 0x640
|
||||
* (OFDM/HT) and its CCK companion 0x639. Kestrel uses
|
||||
* R_AX_RSP_CHK_SIG 0xCC00 byte0. The CTS window (REG_CTS2TO 0x641) is
|
||||
* separate and untouched. Sizing: ~6.7 µs x round-trip km plus ~50 µs
|
||||
* ACK flight/detection margin; a longer window is NOT free — every retry
|
||||
* of a LOST frame waits the full window, measured (dead RA, retry 8, max
|
||||
* duty): 2719 write-offs/8 s at 33 µs vs 2015 at 128 vs 1507 at 255.
|
||||
* Bench proof the register gates the ARQ verdict: at 8 µs (below the
|
||||
* ACK's flight time) retries pin at the limit with 0% ok against a
|
||||
* live responder; at 128/255 the responder cell runs 100% ok,
|
||||
* retries ~0. RTL8733B CCK direction check (11M, dead RA, retry 8,
|
||||
* max duty, 8 s): 1513 submissions at 33 µs versus 1129 at 200 µs;
|
||||
* this establishes that the CCK window is live, not precise timing. */
|
||||
int ack_timeout_us = 128;
|
||||
/* env: DEVOURER_TX_RETRY_FALLBACK — "off" | unset. Unset = the firmware
|
||||
* fallback ladder with its own floor (the current behaviour, descriptors
|
||||
* byte-identical). "off" disables per-retry rate fallback (DISDATAFB /
|
||||
* DISABLE_FB = 1): retries re-air at the descriptor rate. See the
|
||||
* RetryFallback enum for why there is no floor form. */
|
||||
RetryFallback retry_fallback = RetryFallback::Default;
|
||||
/* env: DEVOURER_TX_USB_AGG — USB TX aggregation: max frames packed into
|
||||
* one bulk-OUT URB by send_packets (0 = off, the default: send_packets
|
||||
* degrades to a per-frame loop and every TX path is byte-identical to
|
||||
* before the knob existed). Clamped to the 8-bit agg-num field (255; 64
|
||||
* on Jaguar1) and the vendor packing rules (see src/TxAggPlan.h). USB
|
||||
* only; the PCIe rings take frames individually. */
|
||||
unsigned usb_agg_max = 0;
|
||||
/* env: DEVOURER_TX_REPORT — per-frame TX-status reports (src/TxReport.h):
|
||||
* sets SPE_RPT in every data TX descriptor so the firmware answers each
|
||||
* transmission with a CCX report (delivered/retry-drop + hardware retry
|
||||
* count + queue time + final rate), decoded off the C2H RX path into
|
||||
* `tx.report` events. The TX-side link sensor. On the HalMAC chips the
|
||||
* descriptor SW_DEFINE also carries a rotating 8-bit tag the report
|
||||
* echoes (per-frame correlation). Default off (descriptors
|
||||
* byte-identical). Needs an RX loop to deliver the C2H reports. RTL8733B
|
||||
* is an explicit exception: its backend has no H2C/MEDIA_STATUS_RPT path,
|
||||
* warns that the request is unsupported, and emits no `tx.report` events.
|
||||
*
|
||||
* Value = sampling divisor N: 1 requests a report on EVERY frame, N > 1
|
||||
* on every Nth (0..255). The CCX emission path saturates at ~1.3–1.4 k
|
||||
* reports/s (docs/scheduled-mac.md), so above ~1.25 k fps pick
|
||||
* N >= fps/1300 and coverage of the SAMPLED frames stays deterministic
|
||||
* instead of load-collapsing. HalMAC dies stamp the SW_DEFINE tag on
|
||||
* every frame regardless of sampling, so consecutive received-report
|
||||
* tags differ by exactly N — any other delta is a dropped report
|
||||
* (consumers must know N; tests/txrpt_coverage_attrib.py --sample-n). */
|
||||
int report = 0;
|
||||
/* env: DEVOURER_TX_AMPDU_MODE="tid/maxnum[/density[/noack[/maxtime_hex]]]"
|
||||
* — arm the first-class A-MPDU TX mode (src/AmpduMode.h) at the end of
|
||||
* bring-up: mark data frames aggregatable and program the MAC pacing
|
||||
* registers. The product form of the DEVOURER_TX_QSEL / DEVOURER_TX_AMPDU
|
||||
* spike knobs (which still compose on top). Runtime equivalent:
|
||||
* SetAmpduMode. Unset = off (byte-identical). Pair with a deep feed
|
||||
* (send_packets / DEVOURER_TX_THREADS) for the goodput win. */
|
||||
std::optional<AmpduMode> ampdu;
|
||||
} tx;
|
||||
|
||||
/* ---- Beamforming (bring-up-time arming; see docs/beamforming-*.md) --- */
|
||||
struct Bf {
|
||||
/* env: DEVOURER_BF_ARM_SOUNDER — arm the MAC's hardware sounding engine
|
||||
* (beamformer side) so a descriptor-marked NDPA is followed by a
|
||||
* hardware-generated NDP. */
|
||||
bool arm_sounder = false;
|
||||
/* env: DEVOURER_BF_ARM_SOUNDER=<mac> — Jaguar2/3 also program the self-MAC
|
||||
* (0x0610) the sounding engine matches the NDPA TA against. Unset = bare
|
||||
* arming (Jaguar-1 semantics: MAC left unprogrammed). */
|
||||
std::optional<MacAddr> sounder_self_mac;
|
||||
/* env: DEVOURER_BF_ARM_BFEE=<mac> — arm the hardware CSI responder
|
||||
* (beamformee side) for NDPA+NDP from this beamformer MAC. */
|
||||
std::optional<MacAddr> beamformee_of;
|
||||
/* env: DEVOURER_BF_ARM_BFEE_MU — upgrade the responder to MU beamformee
|
||||
* (per-subcarrier delta-SNR report). Jaguar2/3, needs beamformee_of. */
|
||||
bool mu = false;
|
||||
/* env: DEVOURER_BF_TXBF=<mac> — Jaguar3: configure the beamformer entry
|
||||
* for closed-loop TX-beamforming apply toward this peer (the apply itself
|
||||
* gates on the first CBR seen by the RX loop; needs rx.enable_with_tx). */
|
||||
std::optional<MacAddr> txbf_peer;
|
||||
/* env: DEVOURER_TX_NDPA — 0 = off; 1 = mark every injected frame NDPA
|
||||
* (self-sounding capture); N>1 = every Nth frame (Jaguar3 periodic
|
||||
* re-sounding; Jaguar1/2 treat any nonzero as on). */
|
||||
int ndpa_period = 0;
|
||||
} bf;
|
||||
|
||||
/* ---- Bring-up / calibration experiment gates ------------------------ */
|
||||
struct Tuning {
|
||||
bool skip_iqk = false; /* env: DEVOURER_SKIP_IQK (J2, J3) */
|
||||
bool force_iqk = false; /* env: DEVOURER_FORCE_IQK (J1) */
|
||||
bool disable_iqk = false; /* env: DEVOURER_DISABLE_IQK (J1) */
|
||||
bool skip_txpwr = false; /* env: DEVOURER_SKIP_TXPWR (J1, J2) */
|
||||
bool skip_txgapk = false; /* env: DEVOURER_SKIP_TXGAPK (8822E) */
|
||||
bool skip_trx_reassert = false; /* env: DEVOURER_SKIP_TRX_REASSERT (J2) */
|
||||
bool skip_rfe_init = false; /* env: DEVOURER_SKIP_RFEINIT (J2) */
|
||||
bool skip_coex = false; /* env: DEVOURER_SKIP_COEX (J2) */
|
||||
bool skip_dig = false; /* env: DEVOURER_SKIP_DIG (J2) */
|
||||
/* env: DEVOURER_THERMAL_TRACK — Jaguar2 thermal TX-power tracking
|
||||
* (default ON; "0" disables). A ~2 s tick reads the RF 0x42 thermal
|
||||
* meter, computes the delta vs the efuse baseline, and writes the vendor
|
||||
* MIX_MODE swing compensation (0xc94/0xe94 TXAGC + 0xc1c/0xe1c BB scale)
|
||||
* so on-air power holds flat as the PA heats over a sustained TX link. */
|
||||
bool thermal_track = true;
|
||||
/* env: DEVOURER_FASTRETUNE_FW — FastRetune firmware fast path (H2C 0x1D
|
||||
* SINGLE_CHANNELSWITCH_V2, the switch the vendor drivers gate behind
|
||||
* rtw_ch_switch_offload) on the Jaguar2 dies (8822B, 8821C) and the
|
||||
* Jaguar3 dies (8822C, 8822E): 0 = off (software compose path), 1 = firmware switch for
|
||||
* intra-band 20/40 MHz hops, 2 = additionally accept cross-band hops
|
||||
* (the firmware reprograms the band block; TXAGC baseline stays the
|
||||
* bring-up band's — active power knobs re-fold). Bench + protocol:
|
||||
* docs/experiments/kernel-channel-switch-offload.md. */
|
||||
int fastretune_fw = 0;
|
||||
/* env: DEVOURER_KFR_OFLD — Kestrel FastRetune firmware IO-offload (mac_ax
|
||||
* fwofld.c): batch the whole same-sub-band hop (RF18/0xcf channel set + BB
|
||||
* reset + fixed TX power) into ONE FW_OFLD/CMD_OFLD_REG H2C the on-chip fw
|
||||
* replays, collapsing ~20 USB register round-trips into one bulk-OUT
|
||||
* (~9 ms -> ~0.15 ms host-side). Default 1 (on); 0 forces the direct
|
||||
* write-only path (self-paces the ~1.5 ms RF synth settle instead of
|
||||
* returning before it). No rtw89 firmware channel-switch H2C exists, so
|
||||
* this offloads the raw register writes, not a fw switch primitive. The
|
||||
* hop returns before the synth settles — the caller honours a ~1.5 ms
|
||||
* settle before TX (the demos' admission window). 8852B only. */
|
||||
int kestrel_fastretune_ofld = 1;
|
||||
/* env: DEVOURER_FW_TABLE_OFLD — Jaguar2 init-time firmware register
|
||||
* IO-offload (HalMAC cfg_param): route the static BB/AGC/RF phy-table write
|
||||
* stream through one FW_OFFLOAD/CFG_PARAM H2C per ~160-command batch that
|
||||
* the firmware replays on-chip, collapsing the per-init USB register control
|
||||
* transfers into a handful of bulk transfers. Bit flags: 1 = BB + AGC
|
||||
* tables, 2 = also the RF radio tables (RF_W, routed through the firmware's
|
||||
* RF write path). 0 = off (direct writes, byte-identical to before). Default
|
||||
* 0 — init is higher blast-radius than a hop. Jaguar3 (8822C/E) is a
|
||||
* follow-up: the fw replays cfg_param but lazily, and its rsvd-page download
|
||||
* stalls per batch. */
|
||||
int fw_table_offload = 0;
|
||||
/* env: DEVOURER_DIS_CCA — MAC carrier-sense disable at bring-up, every
|
||||
* generation (primary CCA 0x520[14] + EDCCA [15]; Jaguar1 additionally
|
||||
* programs/parks its BB EDCCA thresholds 0x8a4 — its init table leaves
|
||||
* them at never-trigger, and the explicit apply is what makes EDCCA
|
||||
* real on that family): injected/beacon TX stops deferring to a
|
||||
* busy channel and punches through co-channel traffic. Default false =
|
||||
* carrier-sense + EDCCA ENABLED (the standards-compliant default) on
|
||||
* Jaguar1/2/3 and the Kestrel 8852C; the Kestrel 8852B TX bring-up
|
||||
* clears the gates and warns pending its measurement arm
|
||||
* (tests/kestrel_cca_default_check.sh). Runtime equivalent: SetCcaMode.
|
||||
* Default-on on the streamtx FPV downlink (the link owns the
|
||||
* channel). */
|
||||
bool disable_cca = false;
|
||||
/* env: DEVOURER_TXPKT_STEP_QDB — Jaguar3 per-packet power-bank step size
|
||||
* in quarter-dB: the dB weight of one 0x1e70 offset-index step
|
||||
* (SetTxPacketPowerOffsetQdb / radiotap DBM_TX_POWER).
|
||||
* Default 4 (= 1 dB), the vendor-stated step for the 22C class ("each
|
||||
* tx_pwr_ofst step will be 1dB", phydm.h bb_ram block); override for
|
||||
* bench slope calibration (tests/txpkt_pwr_ofset_onair.sh). */
|
||||
int txpkt_step_qdb = 4;
|
||||
/* env: DEVOURER_RFE — Jaguar2 RFE type override (antenna/LNA switch
|
||||
* variant; unset = efuse, blank efuse falls back per vendor). */
|
||||
std::optional<uint8_t> rfe_type;
|
||||
/* env: DEVOURER_NB_DAC — 5/10 MHz divider-mapping experiments only.
|
||||
* Jaguar3: force the 3-bit DAC-divider code (0x9b4[10:8]). Jaguar2:
|
||||
* force the 0x8ac DAC clock field — bits [1:0] -> 0x8ac[21:20],
|
||||
* bit 2 -> 0x8ac[28]. RTL8733B: force the 0x9b4[10:8] code the
|
||||
* experimental narrowband path writes (stub default 1/2). */
|
||||
std::optional<uint8_t> nb_dac;
|
||||
/* env: DEVOURER_NB_ADC — 5/10 MHz divider-mapping experiments only.
|
||||
* Jaguar2: force the 0x8ac ADC clock field — bits [1:0] -> 0x8ac[9:8],
|
||||
* bit 2 -> 0x8ac[16]. RTL8733B: force the 0x9f0[3:0] ADC-clock code
|
||||
* (stub default 0xa/0xb). */
|
||||
std::optional<uint8_t> nb_adc;
|
||||
/* env: DEVOURER_XTAL_CAP — crystal-cap trim code applied at the end of
|
||||
* bring-up (IRtlRadio::SetXtalCap). The CFO lever for narrowband at the
|
||||
* edge of its budget; unset = efuse/default. Raw code, 0..0x3f (Jaguar1/2)
|
||||
* or 0..0x7f (Jaguar3). */
|
||||
std::optional<uint8_t> xtal_cap;
|
||||
/* env: DEVOURER_CFO_TRACK — closed-loop CFO tracking (Jaguar3): auto-trim
|
||||
* the crystal cap from the RX-measured per-frame CFO, tracking warm-up
|
||||
* drift so narrowband stays locked (issue #217). Off by default. */
|
||||
bool cfo_track = false;
|
||||
/* env: DEVOURER_REGULATION — Jaguar1 regulatory domain override for the
|
||||
* TX-power limit tables (unset = efuse). */
|
||||
std::optional<Regulation> regulation;
|
||||
/* env: DEVOURER_ENABLE_TXPWR_BY_RATE — Jaguar1: apply the efuse PG-table
|
||||
* per-rate offsets on top of the base index. */
|
||||
bool txpwr_by_rate = false;
|
||||
/* env: DEVOURER_PHYDM_WATCHDOG — Jaguar1: run the optional periodic phydm
|
||||
* watchdog (FA stats + DIG) thread. */
|
||||
bool phydm_watchdog = false;
|
||||
/* env: DEVOURER_8814_FWDL / DEVOURER_8814_FWDL_CHUNK — 8814A firmware
|
||||
* download path + reserved-page chunk size (validated 64..MAX at the use
|
||||
* site; out-of-range values are ignored). */
|
||||
Fwdl8814Path fwdl_8814 = Fwdl8814Path::KernelBracket;
|
||||
std::optional<uint32_t> fwdl_8814_chunk;
|
||||
/* env: DEVOURER_DPDT_MODE=efem|legacy|bit24|skip — 8822E DPDT
|
||||
* antenna-transfer-switch routing for board A/B. Default (efem) ports the
|
||||
* kernel eFEM pin-mux so the DPDT follows TX/RX in hardware (both RX chains
|
||||
* live); the others are the pre-fix static routes. See docs/8822e-quirks.md. */
|
||||
Dpdt8822eMode dpdt_8822e = Dpdt8822eMode::EfemPinmux;
|
||||
|
||||
/* env: DEVOURER_TEARDOWN_POWER_DOWN=0|1 — Jaguar1: run the die's
|
||||
* card-disable power sequence at Stop()/destruction (default on), instead
|
||||
* of leaving the chip in ACT with its RF front end live indefinitely.
|
||||
*
|
||||
* Turning it OFF is what a post-mortem needs: a powered-down chip answers
|
||||
* every register read with the CARDEMU fill (0xEA...), so the state a
|
||||
* session left behind is only inspectable (examples/chipstate) while the
|
||||
* chip is still up. It is also the A/B lever for measuring what the
|
||||
* power-down is actually worth. */
|
||||
bool teardown_power_down = true;
|
||||
} tuning;
|
||||
|
||||
/* ---- Diagnostics output --------------------------------------------- */
|
||||
struct Debug {
|
||||
/* env: DEVOURER_DUMP_CANARY — dump the per-chip BB/MAC/RF canary register
|
||||
* set after every channel set / fast retune (kernel-parity diffing). */
|
||||
bool dump_canary = false;
|
||||
/* env: DEVOURER_BB_DUMP — Jaguar2: full BB/RF dump in rtw_proc format. */
|
||||
bool bb_dump = false;
|
||||
/* env: DEVOURER_EFUSE_DUMP — Jaguar2: dump the efuse logical map. */
|
||||
bool efuse_dump = false;
|
||||
/* env: DEVOURER_LOG_WRITES — emit every vendor register write as a
|
||||
* debug.wreg event (addr/width/val mirror tests/decode_wseq.py). */
|
||||
bool log_writes = false;
|
||||
/* env: DEVOURER_LOG_TXPWR — Jaguar1: log the per-channel/per-rate TX-power
|
||||
* derivation. */
|
||||
bool log_txpwr = false;
|
||||
/* env: DEVOURER_HOP_PROF — per-stage FastRetune timing on stderr. */
|
||||
bool hop_prof = false;
|
||||
/* env: DEVOURER_GAINTAB_DBG — 8822E: log the TXGAPK gain-table backup. */
|
||||
bool gaintab_dbg = false;
|
||||
/* env: DEVOURER_REPLAY_WSEQ — golden-init replay (Jaguar2): path to a
|
||||
* register write-sequence file (lines: "<addr_hex> <width 1|2|4>
|
||||
* <val_hex>", e.g. extracted from a kernel-driver usbmon capture).
|
||||
* Applied verbatim at the end of Init, OVERRIDING devourer's own
|
||||
* configuration — a debugging lever for hardware-diffing devourer
|
||||
* against the vendor driver's end state. */
|
||||
std::string replay_wseq;
|
||||
/* env: DEVOURER_TX_QSEL — EXPERIMENTAL (A-MPDU spike, tests/ampdu_spike):
|
||||
* override the data TX-descriptor QSEL (default 0x12 = MGMT queue, the
|
||||
* monitor-inject convention). Data-queue values are the TID (0..7);
|
||||
* hardware A-MPDU formation is expected only on data queues. */
|
||||
std::optional<uint8_t> tx_qsel;
|
||||
/* env: DEVOURER_TX_RATEID — EXPERIMENTAL (retry-ladder probe,
|
||||
* tests/retry_ladder_probe.sh): override the TX-descriptor RATE_ID (the
|
||||
* RA group). The group defines the rate-space the firmware's retry
|
||||
* fallback ladder walks — the inherited inject value (9 = VHT_2SS on
|
||||
* the 8822C-era table; 8 = the CCK-only B group) is why an MCS frame's
|
||||
* retries fall back through legacy OFDM. Vendor group ids:
|
||||
* reference ieee80211.h RATEID_IDX_* (4 = GN 2SS, 5 = GN 1SS, ...). */
|
||||
std::optional<uint8_t> tx_rateid;
|
||||
/* env: DEVOURER_TX_AMPDU="max[/density]" — EXPERIMENTAL (A-MPDU spike):
|
||||
* set AGG_EN=1 + MAX_AGG_NUM (1..0x1f; hardware units of 2 MPDUs) +
|
||||
* AMPDU_DENSITY (0..7, default 0) on every data TX descriptor, asking the
|
||||
* MAC to aggregate co-queued same-RA/TID frames into A-MPDUs. Whether the
|
||||
* hardware honours it for host-pushed USE_RATE frames is exactly what the
|
||||
* spike measures. Pair with tx_qsel, QoS-Data frames (txdemo
|
||||
* DEVOURER_TX_QOS_DATA) and USB TX agg for co-queueing. */
|
||||
std::optional<uint8_t> tx_ampdu_max;
|
||||
uint8_t tx_ampdu_density = 0;
|
||||
/* Optional third component of DEVOURER_TX_AMPDU ("max[/density[/rty]]"):
|
||||
* override the per-frame data retry limit (RTY_LMT_EN stays 1). The
|
||||
* A-MPDU spike found the MAC retries an aggregate to the limit waiting
|
||||
* for a BlockAck no monitor-mode receiver sends — rty=0 airs each
|
||||
* aggregate exactly once (the broadcast/no-ack flavor). */
|
||||
std::optional<uint8_t> tx_ampdu_rty;
|
||||
/* env: DEVOURER_KESTREL_FWLOG — Kestrel diagnostic: route the firmware log
|
||||
* to C2H packets in InitWrite (mac_fw_log_cfg output=C2H). A decisive probe
|
||||
* of whether async packet-C2H (rpkt_type=10) reaches the host at all. */
|
||||
bool kestrel_fw_log = false;
|
||||
/* env: DEVOURER_KESTREL_CCA_ON — Kestrel experiment: leave the CMAC CCA
|
||||
* medium-busy gates enabled (carrier-sense TX) instead of clearing them,
|
||||
* to test whether the ported RX-DCK calibration fixed the perpetual-busy. */
|
||||
bool kestrel_cca_on = false;
|
||||
/* env: DEVOURER_KESTREL_TRIGGER_F2P — force SendTrigger down the fw F2P_TEST
|
||||
* command instead of host-injecting the raw Basic Trigger through the mgmt
|
||||
* TX path. F2P is an MP-only entry the shipped client fw silently drops (it
|
||||
* airs nothing on-air), so the default (false) host-injects a real Basic
|
||||
* Trigger frame that actually leaves the antenna. Set true only to reproduce
|
||||
* the F2P no-op for comparison. */
|
||||
bool kestrel_trigger_f2p = false;
|
||||
} debug;
|
||||
|
||||
/* ---- USB / process environment -------------------------------------- */
|
||||
struct Usb {
|
||||
/* env: TMPDIR — directory for the
|
||||
* devourer-usb-*.lock files. Empty = "/tmp". */
|
||||
std::string lock_dir;
|
||||
/* env: DEVOURER_RX_ZEROCOPY — allocate the async RX ring from kernel DMA
|
||||
* memory (libusb_dev_mem_alloc / USBDEVFS_ALLOC) so incoming frames DMA
|
||||
* straight into the userspace buffer, eliminating the per-URB usbfs copy on
|
||||
* reap. Linux + capable HCD only; the alloc falls back to heap buffers (the
|
||||
* historical copy-on-reap path) when unsupported, so leaving it on is safe.
|
||||
* 1 = on (default), 0 = force the heap path. */
|
||||
bool rx_zerocopy = true;
|
||||
} usb;
|
||||
|
||||
/* ---- PCIe (DEVOURER_PCIE builds; see src/PcieTransport.h) ------------ */
|
||||
struct Pcie {
|
||||
/* env: DEVOURER_PCIE_RX_POLL_US — RX ring hardware-index poll interval in
|
||||
* microseconds (unset = the transport default, 200). Demo-side only: the
|
||||
* demos fold it into PcieTransport::Config before Open(); device selection
|
||||
* (DEVOURER_PCIE_BDF) is likewise demo-local, like USB device selection. */
|
||||
std::optional<int> rx_poll_us;
|
||||
} pcie;
|
||||
|
||||
/* ---- MediaTek MT7612U (DEVOURER_MT7612U builds) ---------------------- */
|
||||
struct Mt7612u {
|
||||
/* env: DEVOURER_MT7612U_FW_DIR — directory holding mt7662_rom_patch.bin
|
||||
* and mt7662.bin. Unset = search /lib/firmware/mediatek then ./firmware.
|
||||
*
|
||||
* A path rather than an embedded blob, unlike every Realtek backend: this
|
||||
* firmware ships in linux-firmware under its own licence rather than being
|
||||
* generated into hal/, and it is zstd-compressed on most distributions, so
|
||||
* it can be neither vendored here nor assumed ready at a fixed path.
|
||||
* Decompress both and point this at the directory.
|
||||
*
|
||||
* Here rather than a getenv inside the backend so the library and the
|
||||
* device class both stay free of ambient process state; the demos fold the
|
||||
* variable in, the way they do for every other knob in this file. */
|
||||
std::optional<std::string> firmware_dir;
|
||||
/* No adapter selector here on purpose. devourer chooses the adapter before
|
||||
* a backend exists (DEVOURER_USB_BUS / _PORT / _VID / _PID) and hands the
|
||||
* backend an already-claimed handle, so a MediaTek-specific selector would
|
||||
* be read by nothing. The C library's own mt7612u_open_selected() is for a
|
||||
* consumer that opens the device itself; MT7612U_DEV drives the bring-up
|
||||
* tool, not devourer. */
|
||||
} mt7612u;
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,374 @@
|
||||
#ifndef DEVOURER_EVENT_H
|
||||
#define DEVOURER_EVENT_H
|
||||
|
||||
/* Machine event stream — JSON Lines on stdout (the data plane).
|
||||
*
|
||||
* One event = one line = one JSON object whose first field is always the
|
||||
* event name, serialized exactly as
|
||||
*
|
||||
* {"ev":"<name>", ...}
|
||||
*
|
||||
* That first-field guarantee is part of the contract: shell consumers may
|
||||
* `grep -F '"ev":"rx.txhit"'` without a JSON parser; everything richer goes
|
||||
* through json.loads (see tests/devourer_events.py). Schema: docs/logging.md.
|
||||
*
|
||||
* Emission is a single fwrite() of the complete line followed by fflush()
|
||||
* (FlushPolicy::EveryLine, the default) — fwrite locks the FILE* on every
|
||||
* supported libc, so concurrent threads interleave whole lines, never
|
||||
* characters, and a python subprocess reading the pipe sees each event the
|
||||
* moment it is emitted (stdout through a pipe is fully buffered otherwise).
|
||||
*
|
||||
* Usage:
|
||||
* Ev(sink, "thermal").t().f("raw", raw).f("delta", d).f("status", s);
|
||||
* // emits on destruction; or call .emit() explicitly.
|
||||
*
|
||||
* Dependency-free, no allocation for typical events (inline 768-byte buffer;
|
||||
* oversized bodies spill to a reused thread-local scratch). Numbers are
|
||||
* emitted via snprintf with long long/unsigned long long/double only — no
|
||||
* %zu-style portability traps. NaN/Inf serialize as null. A line is hard-
|
||||
* capped at 64 KiB: an overflowing field is dropped and "truncated":true is
|
||||
* appended. */
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class EventSink {
|
||||
public:
|
||||
enum class FlushPolicy { EveryLine, Never };
|
||||
|
||||
/* Configure before any worker threads spawn (demo main() start). */
|
||||
void configure(std::FILE *out, FlushPolicy fp = FlushPolicy::EveryLine) {
|
||||
_out = out;
|
||||
_flush = fp;
|
||||
_enabled = out != nullptr;
|
||||
}
|
||||
void disable() { _enabled = false; }
|
||||
bool enabled() const { return _enabled; }
|
||||
|
||||
/* p..p+n must be one complete line including the trailing '\n'. A single
|
||||
* fwrite keeps the line atomic across threads. */
|
||||
void write_line(const char *p, size_t n) {
|
||||
if (!_enabled)
|
||||
return;
|
||||
std::fwrite(p, 1, n, _out);
|
||||
if (_flush == FlushPolicy::EveryLine)
|
||||
std::fflush(_out);
|
||||
}
|
||||
|
||||
private:
|
||||
std::FILE *_out = stdout;
|
||||
FlushPolicy _flush = FlushPolicy::EveryLine;
|
||||
bool _enabled = true;
|
||||
};
|
||||
|
||||
/* Monotonic milliseconds since process start, for Ev::t(). The epoch is a
|
||||
* function-local static, so "start" is the first event emission — close
|
||||
* enough to main() for a telemetry timestamp, and safe under any static-init
|
||||
* order. */
|
||||
inline long long event_uptime_ms() {
|
||||
static const auto t0 = std::chrono::steady_clock::now();
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - t0)
|
||||
.count();
|
||||
}
|
||||
|
||||
class Ev {
|
||||
public:
|
||||
static constexpr size_t kMaxLine = 64 * 1024;
|
||||
|
||||
Ev(EventSink &sink, const char *name) : _sink(sink) {
|
||||
_buf = _sbuf;
|
||||
_cap = sizeof(_sbuf);
|
||||
if (!_sink.enabled()) {
|
||||
_dead = true;
|
||||
return;
|
||||
}
|
||||
raw("{\"ev\":\"", 7);
|
||||
raw(name, std::strlen(name)); /* event names are our literals: no escape */
|
||||
raw("\"", 1);
|
||||
}
|
||||
Ev(const Ev &) = delete;
|
||||
Ev &operator=(const Ev &) = delete;
|
||||
~Ev() { emit(); }
|
||||
|
||||
Ev &f(const char *k, long long v) {
|
||||
if (begin_field(k)) {
|
||||
char tmp[24];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "%lld", v));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Ev &f(const char *k, unsigned long long v) {
|
||||
if (begin_field(k)) {
|
||||
char tmp[24];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "%llu", v));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Ev &f(const char *k, int v) { return f(k, (long long)v); }
|
||||
Ev &f(const char *k, long v) { return f(k, (long long)v); }
|
||||
Ev &f(const char *k, unsigned v) { return f(k, (unsigned long long)v); }
|
||||
Ev &f(const char *k, unsigned long v) { return f(k, (unsigned long long)v); }
|
||||
Ev &f(const char *k, double v) {
|
||||
if (begin_field(k)) {
|
||||
if (std::isfinite(v)) {
|
||||
char tmp[32];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "%.10g", v));
|
||||
} else {
|
||||
raw("null", 4);
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Ev &f(const char *k, bool v) {
|
||||
if (begin_field(k))
|
||||
v ? raw("true", 4) : raw("false", 5);
|
||||
return *this;
|
||||
}
|
||||
Ev &f(const char *k, std::string_view v) {
|
||||
if (begin_field(k))
|
||||
str(v);
|
||||
return *this;
|
||||
}
|
||||
Ev &f(const char *k, const char *v) { return f(k, std::string_view(v)); }
|
||||
Ev &f(const char *k, std::nullptr_t) {
|
||||
if (begin_field(k))
|
||||
raw("null", 4);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* "k":"0x1c2" — register addresses/values/masks are hex strings by schema
|
||||
* convention. digits=0 emits the minimal width. */
|
||||
Ev &hexf(const char *k, unsigned long long v, int digits = 0) {
|
||||
if (begin_field(k)) {
|
||||
char tmp[24];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "\"0x%0*llx\"",
|
||||
digits, v));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* "k":"aabbcc..." — lowercase hex string of a byte blob (frame bodies). */
|
||||
Ev &hex(const char *k, const uint8_t *p, size_t n) {
|
||||
if (!begin_field(k))
|
||||
return *this;
|
||||
if (!ensure(n * 2 + 2)) { /* field key already written: close valuelessly */
|
||||
raw("null", 4);
|
||||
return *this;
|
||||
}
|
||||
static const char digits[] = "0123456789abcdef";
|
||||
_buf[_len++] = '"';
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
_buf[_len++] = digits[p[i] >> 4];
|
||||
_buf[_len++] = digits[p[i] & 0xf];
|
||||
}
|
||||
_buf[_len++] = '"';
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* "k":[1,-2,3] — per-chain metrics. */
|
||||
Ev &arr(const char *k, const int *v, size_t n) {
|
||||
if (!begin_field(k))
|
||||
return *this;
|
||||
raw("[", 1);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (i)
|
||||
raw(",", 1);
|
||||
char tmp[16];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "%d", v[i]));
|
||||
}
|
||||
raw("]", 1);
|
||||
return *this;
|
||||
}
|
||||
Ev &arr(const char *k, const double *v, size_t n) {
|
||||
if (!begin_field(k))
|
||||
return *this;
|
||||
raw("[", 1);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (i)
|
||||
raw(",", 1);
|
||||
if (std::isfinite(v[i])) {
|
||||
char tmp[32];
|
||||
raw(tmp, (size_t)std::snprintf(tmp, sizeof(tmp), "%.10g", v[i]));
|
||||
} else {
|
||||
raw("null", 4);
|
||||
}
|
||||
}
|
||||
raw("]", 1);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* "t":<monotonic ms since process start> — periodic/marker events carry it;
|
||||
* per-frame events rely on seq/tsfl instead. */
|
||||
Ev &t() { return f("t", event_uptime_ms()); }
|
||||
|
||||
void emit() {
|
||||
if (_dead)
|
||||
return;
|
||||
/* The closer consumes the kSlack reserve, so it always fits. */
|
||||
if (_truncated)
|
||||
closer(",\"truncated\":true", 17);
|
||||
closer("}\n", 2);
|
||||
_dead = true;
|
||||
_sink.write_line(_buf, _len);
|
||||
release_scratch();
|
||||
}
|
||||
|
||||
private:
|
||||
/* Reused per-thread spill buffer so oversized events (hex frame bodies)
|
||||
* don't allocate per emission. A busy flag guards the rare nested-Ev case;
|
||||
* the fallback then is a private heap vector. */
|
||||
struct Scratch {
|
||||
std::vector<char> buf;
|
||||
bool busy = false;
|
||||
};
|
||||
static Scratch &tls_scratch() {
|
||||
thread_local Scratch s;
|
||||
return s;
|
||||
}
|
||||
|
||||
bool begin_field(const char *k) {
|
||||
if (_dead)
|
||||
return false;
|
||||
/* key is always one of our literals — no escaping needed */
|
||||
size_t klen = std::strlen(k);
|
||||
if (!ensure(klen + 4))
|
||||
return false;
|
||||
_buf[_len++] = ',';
|
||||
_buf[_len++] = '"';
|
||||
std::memcpy(_buf + _len, k, klen);
|
||||
_len += klen;
|
||||
_buf[_len++] = '"';
|
||||
_buf[_len++] = ':';
|
||||
return true;
|
||||
}
|
||||
|
||||
void raw(const char *p, size_t n) {
|
||||
if (_dead || !ensure(n))
|
||||
return;
|
||||
std::memcpy(_buf + _len, p, n);
|
||||
_len += n;
|
||||
}
|
||||
|
||||
/* emit()-only append that spends the kSlack reserve (every successful
|
||||
* ensure() left _len <= kMaxLine - kSlack, so this cannot fail). */
|
||||
void closer(const char *p, size_t n) {
|
||||
if (!ensure(n, 0))
|
||||
return;
|
||||
std::memcpy(_buf + _len, p, n);
|
||||
_len += n;
|
||||
}
|
||||
|
||||
void str(std::string_view v) {
|
||||
/* worst case every char escapes to \u00XX (6 bytes) + quotes */
|
||||
if (!ensure(v.size() * 6 + 2)) {
|
||||
raw("null", 4);
|
||||
return;
|
||||
}
|
||||
_buf[_len++] = '"';
|
||||
for (unsigned char c : v) {
|
||||
switch (c) {
|
||||
case '"':
|
||||
_buf[_len++] = '\\';
|
||||
_buf[_len++] = '"';
|
||||
break;
|
||||
case '\\':
|
||||
_buf[_len++] = '\\';
|
||||
_buf[_len++] = '\\';
|
||||
break;
|
||||
case '\n':
|
||||
_buf[_len++] = '\\';
|
||||
_buf[_len++] = 'n';
|
||||
break;
|
||||
case '\t':
|
||||
_buf[_len++] = '\\';
|
||||
_buf[_len++] = 't';
|
||||
break;
|
||||
case '\r':
|
||||
_buf[_len++] = '\\';
|
||||
_buf[_len++] = 'r';
|
||||
break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
_len += (size_t)std::snprintf(_buf + _len, 8, "\\u%04x", c);
|
||||
} else {
|
||||
_buf[_len++] = (char)c;
|
||||
}
|
||||
}
|
||||
}
|
||||
_buf[_len++] = '"';
|
||||
}
|
||||
|
||||
/* Grow so that n more bytes fit, spilling from the inline buffer to the
|
||||
* thread-local scratch. Returns false (and flags truncation) if the line
|
||||
* would exceed kMaxLine minus slack for the truncated marker + "}\n". */
|
||||
static constexpr size_t kSlack = 32; /* reserved for the emit() closer */
|
||||
|
||||
bool ensure(size_t n, size_t slack = kSlack) {
|
||||
if (_len + n + slack > kMaxLine) {
|
||||
_truncated = true;
|
||||
return false;
|
||||
}
|
||||
if (_len + n <= _cap)
|
||||
return true;
|
||||
size_t want = _len + n;
|
||||
size_t newcap = _cap * 2 > want ? _cap * 2 : want;
|
||||
if (newcap > kMaxLine)
|
||||
newcap = kMaxLine;
|
||||
if (_buf == _sbuf) {
|
||||
Scratch &s = tls_scratch();
|
||||
if (!s.busy) {
|
||||
s.busy = true;
|
||||
_scratch = &s;
|
||||
if (s.buf.size() < newcap)
|
||||
s.buf.resize(newcap);
|
||||
std::memcpy(s.buf.data(), _sbuf, _len);
|
||||
_buf = s.buf.data();
|
||||
_cap = s.buf.size();
|
||||
return true;
|
||||
}
|
||||
_heap.resize(newcap);
|
||||
std::memcpy(_heap.data(), _sbuf, _len);
|
||||
_buf = _heap.data();
|
||||
_cap = _heap.size();
|
||||
return true;
|
||||
}
|
||||
if (_scratch) {
|
||||
_scratch->buf.resize(newcap);
|
||||
_buf = _scratch->buf.data();
|
||||
} else {
|
||||
_heap.resize(newcap);
|
||||
_buf = _heap.data();
|
||||
}
|
||||
_cap = newcap;
|
||||
return true;
|
||||
}
|
||||
|
||||
void release_scratch() {
|
||||
if (_scratch) {
|
||||
_scratch->busy = false;
|
||||
_scratch = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
EventSink &_sink;
|
||||
char *_buf = nullptr;
|
||||
size_t _cap = 0;
|
||||
size_t _len = 0;
|
||||
bool _dead = false;
|
||||
bool _truncated = false;
|
||||
Scratch *_scratch = nullptr;
|
||||
std::vector<char> _heap;
|
||||
char _sbuf[768];
|
||||
};
|
||||
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_EVENT_H */
|
||||
@@ -0,0 +1,54 @@
|
||||
#ifndef FIRMWARE_H
|
||||
#define FIRMWARE_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "HalVerDef.h"
|
||||
|
||||
#define CONFIG_RTL8812A
|
||||
#if defined(DEVOURER_HAVE_8814)
|
||||
#define CONFIG_RTL8814A
|
||||
#endif
|
||||
#define LOAD_FW_HEADER_FROM_DRIVER
|
||||
#define ODM_WIN 1
|
||||
#define DM_ODM_SUPPORT_TYPE ODM_WIN
|
||||
typedef uint8_t u8;
|
||||
typedef uint32_t u32;
|
||||
extern "C" {
|
||||
#include "hal8812a_fw.h"
|
||||
#if defined(DEVOURER_HAVE_8814)
|
||||
#include "hal8814a_fw.h"
|
||||
#endif
|
||||
/* CONFIG_RTL8821A is scoped tightly: hal/rtl8812a_spec.h has a vendor-pattern
|
||||
* `#ifdef CONFIG_RTL8821A #include "rtl8821a_spec.h"` block, and we don't
|
||||
* carry that spec header (8821AU register layout is covered by the shared
|
||||
* 8812 spec). Define just for the firmware-header include, then undef. */
|
||||
#define CONFIG_RTL8821A
|
||||
#include "hal8821a_fw.h"
|
||||
#undef CONFIG_RTL8821A
|
||||
}
|
||||
|
||||
struct FirmwareBlob {
|
||||
const u8 *buf;
|
||||
std::size_t len;
|
||||
};
|
||||
|
||||
/* Pick the right firmware NIC blob for the given chip. CHIP_8814A and
|
||||
* CHIP_8821 ship their own compiled-in arrays; CHIP_8812 (and the 1T1R 8811AU
|
||||
* cut that shares its HAL) rides on the 8812 blob. The 8821 blob carries the
|
||||
* IS_FW_HEADER_EXIST_8821 signature (0x2100) — the FW header dispatch in
|
||||
* jaguar_fw_header_present picks the right header parse based on ic_type. */
|
||||
inline FirmwareBlob PickFirmwareForChip(HAL_IC_TYPE_E ic_type) {
|
||||
#if defined(DEVOURER_HAVE_8814)
|
||||
if (ic_type == CHIP_8814A) {
|
||||
return {array_mp_8814a_fw_nic, sizeof(array_mp_8814a_fw_nic)};
|
||||
}
|
||||
#endif
|
||||
if (ic_type == CHIP_8821) {
|
||||
return {array_mp_8821a_fw_nic, sizeof(array_mp_8821a_fw_nic)};
|
||||
}
|
||||
return {array_mp_8812a_fw_nic, sizeof(array_mp_8812a_fw_nic)};
|
||||
}
|
||||
|
||||
#endif /* FIRMWARE_H */
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "HalmacCfgParam.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
namespace {
|
||||
constexpr uint8_t CMD_LEN = 0x0C; /* 12-byte command */
|
||||
inline void put_le32(uint8_t *p, uint32_t v) {
|
||||
p[0] = static_cast<uint8_t>(v);
|
||||
p[1] = static_cast<uint8_t>(v >> 8);
|
||||
p[2] = static_cast<uint8_t>(v >> 16);
|
||||
p[3] = static_cast<uint8_t>(v >> 24);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
HalmacCfgParam::HalmacCfgParam(Transport t, Logger_t logger)
|
||||
: _t(std::move(t)), _logger(std::move(logger)) {
|
||||
_buf.reserve((static_cast<size_t>(_t.max_cmds) + 1) * CMD_LEN);
|
||||
}
|
||||
|
||||
void HalmacCfgParam::push(uint8_t cmd, uint32_t addr_field, uint8_t /*path*/,
|
||||
uint32_t value) {
|
||||
/* addr_field is pre-shaped by the caller into word0[31:16] (MAC/BB addr) or
|
||||
* word0[31:16] = RF_ADDR<<0 | RF_PATH<<8 already positioned. MSK_EN=0 for the
|
||||
* full-register static writes this offload carries. */
|
||||
uint32_t w0 = CMD_LEN | (static_cast<uint32_t>(cmd) << 8) |
|
||||
(addr_field & 0xffff0000u);
|
||||
const size_t off = _buf.size();
|
||||
_buf.resize(off + CMD_LEN);
|
||||
put_le32(_buf.data() + off + 0, w0);
|
||||
put_le32(_buf.data() + off + 4, value);
|
||||
put_le32(_buf.data() + off + 8, 0); /* MASK unused (MSK_EN=0) */
|
||||
_num++;
|
||||
if (_num >= _t.max_cmds)
|
||||
flush();
|
||||
}
|
||||
|
||||
void HalmacCfgParam::bb_write(uint16_t addr, uint32_t value) {
|
||||
_last_was_bb = true;
|
||||
_last_bb_addr = addr;
|
||||
_last_bb_value = value;
|
||||
push(BB_W32, static_cast<uint32_t>(addr) << 16, 0, value);
|
||||
}
|
||||
|
||||
void HalmacCfgParam::mac_write(uint16_t addr, uint32_t value, uint8_t width) {
|
||||
const uint8_t cmd = width == 1 ? MAC_W8 : width == 2 ? MAC_W16 : MAC_W32;
|
||||
push(cmd, static_cast<uint32_t>(addr) << 16, 0, value);
|
||||
}
|
||||
|
||||
void HalmacCfgParam::rf_write(uint8_t path, uint8_t addr, uint32_t value) {
|
||||
/* word0[23:16] = RF_ADDR (8-bit), word0[31:24] = RF_PATH. */
|
||||
const uint32_t addr_field = (static_cast<uint32_t>(addr) << 16) |
|
||||
(static_cast<uint32_t>(path) << 24);
|
||||
push(RF_W, addr_field, path, value & 0x000fffffu);
|
||||
}
|
||||
|
||||
bool HalmacCfgParam::flush() {
|
||||
if (_num == 0)
|
||||
return _ok;
|
||||
/* Terminate the buffer with an END command (belt-and-suspenders alongside the
|
||||
* NUM field the trigger carries). */
|
||||
const size_t off = _buf.size();
|
||||
_buf.resize(off + CMD_LEN, 0);
|
||||
put_le32(_buf.data() + off + 0, CMD_LEN | (static_cast<uint32_t>(END) << 8));
|
||||
|
||||
const uint32_t num = _num;
|
||||
bool ok = _t.dl_rsvd_page(_t.cfg_pg_addr, _buf.data(),
|
||||
static_cast<uint32_t>(_buf.size()));
|
||||
if (ok) {
|
||||
uint8_t trig[32] = {0};
|
||||
trig[0] = 0x01;
|
||||
trig[1] = 0xff; /* CMD_ID_FW_OFFLOAD */
|
||||
trig[2] = 0x08; /* SUB_CMD_ID_CFG_PARAM */
|
||||
trig[4] = 8 + 4; /* header + 4-byte payload */
|
||||
trig[6] = _t.next_seq();
|
||||
/* byte 8..11: NUM[15:0] | INIT_CASE[16]=0 (drv mode) | LOC[31:24]. */
|
||||
put_le32(trig + 8,
|
||||
(num & 0xffffu) | (static_cast<uint32_t>(_t.cfg_loc) << 24));
|
||||
ok = _t.send_h2c_pkt(trig);
|
||||
if (ok && _t.settle)
|
||||
_t.settle(); /* trigger-consumed check (cheap; not the replay gate) */
|
||||
}
|
||||
|
||||
/* Confirm the firmware actually replayed the batch by polling the last BB
|
||||
* write back until it reads what was sent. This doubles as the completion
|
||||
* gate (the extra-info page is safe to reuse once the value lands) and the
|
||||
* correctness check (a dropped/mis-parsed H2C never lands → offload fails and
|
||||
* the caller redoes the batch direct). No fixed settle — the poll returns the
|
||||
* instant the on-chip replay reaches the final write. */
|
||||
if (ok && _last_was_bb && _t.verify_read) {
|
||||
uint32_t got = 0;
|
||||
bool matched = false;
|
||||
for (int i = 0; i < 40; ++i) { /* up to ~8 ms */
|
||||
got = _t.verify_read(_last_bb_addr);
|
||||
if (got == _last_bb_value) {
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(200));
|
||||
}
|
||||
if (!matched) {
|
||||
_logger->error("HalMAC cfg_param: readback 0x{:04x}=0x{:08x} != sent "
|
||||
"0x{:08x} — firmware did not replay the batch",
|
||||
_last_bb_addr, got, _last_bb_value);
|
||||
ok = false;
|
||||
}
|
||||
} else if (ok && _num > 0) {
|
||||
/* Batch ended on a non-BB (RF) write, which the BB read-back can't gate;
|
||||
* the shadow-window RF read-back isn't wired, so give the on-chip replay a
|
||||
* bounded margin before the page is reused. */
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
}
|
||||
|
||||
if (!ok) {
|
||||
_ok = false;
|
||||
_logger->error("HalMAC cfg_param: flush failed ({} cmds) — falling back",
|
||||
num);
|
||||
} else {
|
||||
_total += num;
|
||||
}
|
||||
_buf.clear();
|
||||
_num = 0;
|
||||
_last_was_bb = false;
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,101 @@
|
||||
#ifndef DEVOURER_HALMAC_CFG_PARAM_H
|
||||
#define DEVOURER_HALMAC_CFG_PARAM_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include "logger.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* HalMAC firmware register IO-offload (cfg_param). Accumulates a stream of
|
||||
* static register writes into a 12-byte-per-command buffer, then flushes each
|
||||
* batch as ONE FW_OFFLOAD/CFG_PARAM H2C the on-chip firmware replays locally —
|
||||
* collapsing the thousands of per-init phy-table USB control transfers into a
|
||||
* handful of bulk transfers. Generation-agnostic (8822B/8821C/8822C/8822E all
|
||||
* speak the same cfg_param wire format); the per-generation transport is
|
||||
* injected as callbacks.
|
||||
*
|
||||
* Command wire format (12 bytes LE, matches halmac add_param_buf_88xx):
|
||||
* word0 = LEN(0x0C)[7:0] | IO_CMD[14:8] | MSK_EN[15] |
|
||||
* { MAC/BB: ADDR[31:16] } | { RF: RF_ADDR[23:16] | RF_PATH[31:24] }
|
||||
* word1 = DATA (value)
|
||||
* word2 = MASK (only when MSK_EN=1)
|
||||
* Static table entries are full-register writes, so MSK_EN=0 / MASK=0 — the
|
||||
* firmware writes the value verbatim (no on-chip read-modify-write, so the
|
||||
* masked-value shift convention is irrelevant here).
|
||||
*
|
||||
* Trigger H2C (32 bytes): {0x01, 0xff, 0x08(CFG_PARAM), 0, len, 0, seq, 0} then
|
||||
* at byte 8: NUM[15:0] | INIT_CASE[16] | LOC[31:24]. Drv mode (INIT_CASE=0)
|
||||
* places the buffer at the reserved H2C-extra-info page (LOC = its page offset
|
||||
* from the rsvd boundary). */
|
||||
class HalmacCfgParam {
|
||||
public:
|
||||
/* IO_CMD ids (enum halmac_parameter_cmd). */
|
||||
enum Cmd : uint8_t {
|
||||
MAC_W8 = 0x4,
|
||||
MAC_W16 = 0x5,
|
||||
MAC_W32 = 0x6,
|
||||
RF_W = 0x7,
|
||||
BB_W8 = 0x8,
|
||||
BB_W16 = 0x9,
|
||||
BB_W32 = 0xA,
|
||||
END = 0xFF,
|
||||
};
|
||||
|
||||
struct Transport {
|
||||
/* DMA the packed command buffer to the reserved H2C-extra-info page
|
||||
* (dl_rsvd_page / send_fw_page with a data descriptor). */
|
||||
std::function<bool(uint16_t pg_addr, const uint8_t *buf, uint32_t len)>
|
||||
dl_rsvd_page;
|
||||
/* Send a 32-byte FW_OFFLOAD H2C packet (the CFG_PARAM trigger). */
|
||||
std::function<bool(const uint8_t pkt[32])> send_h2c_pkt;
|
||||
/* Next rolling H2C sequence number (halmac h2c_info.seq_num). */
|
||||
std::function<uint8_t()> next_seq;
|
||||
/* Block until the firmware has consumed the trigger + replayed the buffer,
|
||||
* so the extra-info page is safe to reuse for the next batch. */
|
||||
std::function<void()> settle;
|
||||
/* Read back a BB register (full dword). After each flush the last BB write
|
||||
* in the batch is read back and compared to what was sent — this both
|
||||
* confirms the firmware actually replayed the buffer (vs silently dropping
|
||||
* the H2C) and gates page reuse. A mismatch marks the offload failed so the
|
||||
* caller falls back to direct writes. Optional; skipped if unset. */
|
||||
std::function<uint32_t(uint16_t bb_addr)> verify_read;
|
||||
uint16_t cfg_pg_addr = 0; /* absolute TX-FIFO page of the extra-info buffer */
|
||||
uint16_t cfg_loc = 0; /* LOC field: that page's offset from rsvd boundary */
|
||||
uint32_t max_cmds = 160; /* flush threshold (extra-info page holds ~170) */
|
||||
};
|
||||
|
||||
HalmacCfgParam(Transport t, Logger_t logger);
|
||||
|
||||
void bb_write(uint16_t addr, uint32_t value);
|
||||
void mac_write(uint16_t addr, uint32_t value, uint8_t width);
|
||||
void rf_write(uint8_t path, uint8_t addr, uint32_t value);
|
||||
|
||||
/* Flush the accumulated batch. No-op if empty. Returns false on a transport
|
||||
* failure (the caller falls back to direct writes). Auto-invoked when the
|
||||
* buffer reaches max_cmds. */
|
||||
bool flush();
|
||||
|
||||
bool ok() const { return _ok; }
|
||||
uint64_t total() const { return _total; } /* commands offloaded this session */
|
||||
uint32_t pending() const { return _num; }
|
||||
|
||||
private:
|
||||
void push(uint8_t cmd, uint32_t addr_field, uint8_t path, uint32_t value);
|
||||
|
||||
Transport _t;
|
||||
Logger_t _logger;
|
||||
std::vector<uint8_t> _buf; /* packed 12-byte commands, current batch */
|
||||
uint32_t _num = 0;
|
||||
uint64_t _total = 0;
|
||||
bool _ok = true;
|
||||
bool _last_was_bb = false; /* for the per-flush read-back verify */
|
||||
uint16_t _last_bb_addr = 0;
|
||||
uint32_t _last_bb_value = 0;
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef HOP_PROF_H
|
||||
#define HOP_PROF_H
|
||||
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
|
||||
#include "Event.h"
|
||||
|
||||
/* Per-stage timing inside the fast_retune paths (DeviceConfig
|
||||
* debug.hop_prof), for driving the hop-latency work (FHSS wants every hop
|
||||
* microsecond accounted for). Each fast hop emits one event:
|
||||
*
|
||||
* {"ev":"hop.prof","gen":"<tag>","ch":N,"<stage>_us":N,...,"total_us":N}
|
||||
*
|
||||
* Stages are generation-specific labels passed at mark() time. Zero overhead
|
||||
* when disabled beyond a branch. */
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class HopProf {
|
||||
public:
|
||||
HopProf(EventSink &sink, bool enabled, const char *gen, unsigned channel)
|
||||
: _enabled(enabled) {
|
||||
if (!_enabled)
|
||||
return;
|
||||
_t0 = _last = std::chrono::steady_clock::now();
|
||||
_ev.emplace(sink, "hop.prof");
|
||||
_ev->f("gen", gen).f("ch", channel);
|
||||
}
|
||||
|
||||
/* Record the time since the previous mark under `stage`. */
|
||||
void mark(const char *stage) {
|
||||
if (!_enabled)
|
||||
return;
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const long long us =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(now - _last)
|
||||
.count();
|
||||
_last = now;
|
||||
char key[48];
|
||||
std::snprintf(key, sizeof(key), "%s_us", stage);
|
||||
_ev->f(key, us);
|
||||
}
|
||||
|
||||
~HopProf() {
|
||||
if (!_enabled)
|
||||
return;
|
||||
const long long total =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::steady_clock::now() - _t0)
|
||||
.count();
|
||||
_ev->f("total_us", total); /* _ev emits on destruction */
|
||||
}
|
||||
|
||||
private:
|
||||
bool _enabled = false;
|
||||
std::optional<Ev> _ev;
|
||||
std::chrono::steady_clock::time_point _t0{}, _last{};
|
||||
};
|
||||
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* HOP_PROF_H */
|
||||
@@ -0,0 +1,222 @@
|
||||
#ifndef DEVOURER_HOP_SCHEDULE_H
|
||||
#define DEVOURER_HOP_SCHEDULE_H
|
||||
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class HopSchedule {
|
||||
public:
|
||||
using Key = std::array<uint8_t, 16>;
|
||||
|
||||
explicit HopSchedule(Key key) : key_(key) {}
|
||||
|
||||
// A public, keyless round-robin (channels[slot % n]) that shares the lockstep
|
||||
// machinery — the "sequential-hop" peer of the keyed schedule. Same slot->
|
||||
// channel API and sync marker, but the order is predictable (which is the
|
||||
// point of the follower-jammer comparison: a reactive jammer can lock onto
|
||||
// sequential but not the keyed permutation).
|
||||
static HopSchedule sequential() {
|
||||
HopSchedule s{Key{}};
|
||||
s.sequential_ = true;
|
||||
return s;
|
||||
}
|
||||
|
||||
static Key parse_seed(const char *text) {
|
||||
if (!text || !*text)
|
||||
throw std::invalid_argument("empty hop seed");
|
||||
std::string s(text);
|
||||
if (s.size() >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
|
||||
s.erase(0, 2);
|
||||
if (s.empty() || s.size() > 32)
|
||||
throw std::invalid_argument(
|
||||
"DEVOURER_HOP_SEED must contain 1..32 hex digits");
|
||||
for (char c : s)
|
||||
if (!std::isxdigit(static_cast<unsigned char>(c)))
|
||||
throw std::invalid_argument(
|
||||
"DEVOURER_HOP_SEED contains a non-hex digit");
|
||||
if (s.size() & 1)
|
||||
s.insert(s.begin(), '0');
|
||||
Key key{};
|
||||
const size_t first = key.size() - s.size() / 2;
|
||||
for (size_t i = 0; i < s.size() / 2; ++i)
|
||||
key[first + i] =
|
||||
static_cast<uint8_t>((hex(s[2 * i]) << 4) | hex(s[2 * i + 1]));
|
||||
return key;
|
||||
}
|
||||
|
||||
static HopSchedule from_env(const char *name = "DEVOURER_HOP_SEED") {
|
||||
return HopSchedule(parse_seed(std::getenv(name)));
|
||||
}
|
||||
|
||||
bool is_sequential() const { return sequential_; }
|
||||
|
||||
uint32_t fingerprint() const {
|
||||
if (sequential_)
|
||||
return 0x53455131u; // "SEQ1" — fixed public-schedule id, no key
|
||||
static const uint8_t tag[] = {'d', 'e', 'v', 'o', 'u', 'r',
|
||||
'e', 'r', '-', 'h', 'o', 'p'};
|
||||
return static_cast<uint32_t>(siphash24(key_, tag, sizeof(tag)));
|
||||
}
|
||||
|
||||
std::vector<size_t> permutation(uint64_t round, size_t n) const {
|
||||
std::vector<size_t> p(n);
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
p[i] = i;
|
||||
uint64_t counter = 0;
|
||||
for (size_t i = n; i > 1; --i) {
|
||||
const uint64_t bound = static_cast<uint64_t>(i);
|
||||
const uint64_t limit = UINT64_MAX - (UINT64_MAX % bound);
|
||||
uint64_t r;
|
||||
do {
|
||||
r = word(round, counter++);
|
||||
} while (r >= limit);
|
||||
const size_t j = static_cast<size_t>(r % bound);
|
||||
const size_t t = p[i - 1];
|
||||
p[i - 1] = p[j];
|
||||
p[j] = t;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
size_t channel_index(uint64_t slot, size_t n) const {
|
||||
if (!n)
|
||||
throw std::invalid_argument("empty hopset");
|
||||
if (sequential_)
|
||||
return static_cast<size_t>(slot % n);
|
||||
const auto p = permutation(slot / n, n);
|
||||
return p[static_cast<size_t>(slot % n)];
|
||||
}
|
||||
|
||||
template <class T>
|
||||
const T &channel(uint64_t slot, const std::vector<T> &h) const {
|
||||
return h[channel_index(slot, h.size())];
|
||||
}
|
||||
|
||||
static uint64_t siphash24(const Key &key, const uint8_t *in, size_t len) {
|
||||
const uint64_t k0 = load64(key.data()), k1 = load64(key.data() + 8);
|
||||
uint64_t v0 = 0x736f6d6570736575ULL ^ k0, v1 = 0x646f72616e646f6dULL ^ k1;
|
||||
uint64_t v2 = 0x6c7967656e657261ULL ^ k0, v3 = 0x7465646279746573ULL ^ k1;
|
||||
const uint8_t *end = in + (len & ~size_t(7));
|
||||
for (; in != end; in += 8) {
|
||||
uint64_t m = load64(in);
|
||||
v3 ^= m;
|
||||
rounds(v0, v1, v2, v3, 2);
|
||||
v0 ^= m;
|
||||
}
|
||||
uint64_t b = static_cast<uint64_t>(len) << 56;
|
||||
for (size_t i = 0; i < (len & 7); ++i)
|
||||
b |= static_cast<uint64_t>(in[i]) << (8 * i);
|
||||
v3 ^= b;
|
||||
rounds(v0, v1, v2, v3, 2);
|
||||
v0 ^= b;
|
||||
v2 ^= 0xff;
|
||||
rounds(v0, v1, v2, v3, 4);
|
||||
return v0 ^ v1 ^ v2 ^ v3;
|
||||
}
|
||||
|
||||
private:
|
||||
Key key_;
|
||||
bool sequential_ = false;
|
||||
static unsigned hex(char c) {
|
||||
return c <= '9' ? c - '0' : (c <= 'F' ? c - 'A' + 10 : c - 'a' + 10);
|
||||
}
|
||||
static uint64_t load64(const uint8_t *p) {
|
||||
uint64_t v = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
v |= uint64_t(p[i]) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
static uint64_t rotl(uint64_t x, int b) { return (x << b) | (x >> (64 - b)); }
|
||||
static void round(uint64_t &a, uint64_t &b, uint64_t &c, uint64_t &d) {
|
||||
a += b;
|
||||
b = rotl(b, 13);
|
||||
b ^= a;
|
||||
a = rotl(a, 32);
|
||||
c += d;
|
||||
d = rotl(d, 16);
|
||||
d ^= c;
|
||||
a += d;
|
||||
d = rotl(d, 21);
|
||||
d ^= a;
|
||||
c += b;
|
||||
b = rotl(b, 17);
|
||||
b ^= c;
|
||||
c = rotl(c, 32);
|
||||
}
|
||||
static void rounds(uint64_t &a, uint64_t &b, uint64_t &c, uint64_t &d,
|
||||
int n) {
|
||||
while (n--)
|
||||
round(a, b, c, d);
|
||||
}
|
||||
uint64_t word(uint64_t round_no, uint64_t counter) const {
|
||||
uint8_t msg[17] = {'H'};
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
msg[1 + i] = uint8_t(round_no >> (8 * i));
|
||||
msg[9 + i] = uint8_t(counter >> (8 * i));
|
||||
}
|
||||
return siphash24(key_, msg, sizeof(msg));
|
||||
}
|
||||
};
|
||||
|
||||
struct HopSyncMarker {
|
||||
uint32_t fingerprint = 0, epoch = 0, phase_us = 0;
|
||||
uint64_t slot = 0;
|
||||
static constexpr size_t kSize = 29;
|
||||
static std::array<uint8_t, kSize> encode(const HopSyncMarker &m) {
|
||||
std::array<uint8_t, kSize> b{{221, 27, 0x57, 0x42, 0x75, 0x48, 1}};
|
||||
put32(b.data() + 7, m.fingerprint);
|
||||
put32(b.data() + 11, m.epoch);
|
||||
put64(b.data() + 15, m.slot);
|
||||
put32(b.data() + 23, m.phase_us);
|
||||
b[27] = 0xd7;
|
||||
b[28] = 0x3a;
|
||||
return b;
|
||||
}
|
||||
static bool decode(const uint8_t *p, size_t n, HopSyncMarker &m) {
|
||||
for (size_t i = 0; i + kSize <= n; ++i)
|
||||
if (p[i] == 221 && p[i + 1] == 27 && p[i + 2] == 0x57 &&
|
||||
p[i + 3] == 0x42 && p[i + 4] == 0x75 && p[i + 5] == 0x48 &&
|
||||
p[i + 6] == 1 && p[i + 27] == 0xd7 && p[i + 28] == 0x3a) {
|
||||
m.fingerprint = get32(p + i + 7);
|
||||
m.epoch = get32(p + i + 11);
|
||||
m.slot = get64(p + i + 15);
|
||||
m.phase_us = get32(p + i + 23);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
static void put32(uint8_t *p, uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i)
|
||||
p[i] = uint8_t(v >> (8 * i));
|
||||
}
|
||||
static void put64(uint8_t *p, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i)
|
||||
p[i] = uint8_t(v >> (8 * i));
|
||||
}
|
||||
static uint32_t get32(const uint8_t *p) {
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
v |= uint32_t(p[i]) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
static uint64_t get64(const uint8_t *p) {
|
||||
uint64_t v = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
v |= uint64_t(p[i]) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
#endif
|
||||
@@ -0,0 +1,564 @@
|
||||
#ifndef IRADIO_H
|
||||
#define IRADIO_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
|
||||
#include "AdapterCaps.h"
|
||||
#include "AmpduMode.h"
|
||||
#include "DeviceConfig.h"
|
||||
#include "AdapterHealth.h"
|
||||
#include "RxQuality.h"
|
||||
#include "SelectedChannel.h"
|
||||
#include "ThermalStatus.h"
|
||||
#include "Sounding.h"
|
||||
#include "TriggerTwt.h"
|
||||
#include "TxCaps.h"
|
||||
#include "TxMode.h"
|
||||
#include "TxPower.h"
|
||||
#include "TxStats.h"
|
||||
|
||||
/* Packet is the parsed-RX type handed to the RX callback. Forward-declared here
|
||||
* (a reference in the std::function signature needs only an incomplete type) so
|
||||
* the interface header stays light; the full definition lives in FrameParser.h. */
|
||||
struct Packet;
|
||||
|
||||
using Action_ParsedRadioPacket = std::function<void(const Packet &)>;
|
||||
|
||||
/* One TX frame handed to send_packets: radiotap header + 802.11 MPDU, the
|
||||
* same buffer contract as send_packet. */
|
||||
struct TxPacketView {
|
||||
const uint8_t *data;
|
||||
size_t len;
|
||||
};
|
||||
|
||||
/* IRadio is the vendor-neutral radio contract used by the demos and the
|
||||
* WiFiDriver factory (CreateRadio returns one). Optional members are virtual
|
||||
* with not-ported defaults; the pure-virtual core is Init / InitWrite /
|
||||
* StartRxLoop / SetMonitorChannel / send_packet / GetSelectedChannel /
|
||||
* SetCcaMode.
|
||||
*
|
||||
* Realtek-specific members (phydm energy counters, EFUSE stability, the
|
||||
* crystal-cap trim, the canary register dump) live on IRtlRadio
|
||||
* (src/IRtlRadio.h), which every Realtek backend derives from; per-generation
|
||||
* research helpers (BB-debug-port reads, the 8814 queue poller, ...) live on
|
||||
* the concrete classes. Callers that need either level dynamic_cast down and
|
||||
* treat nullptr as "not available on this radio". */
|
||||
class IRadio {
|
||||
public:
|
||||
virtual ~IRadio() = default;
|
||||
|
||||
virtual void Init(Action_ParsedRadioPacket packetProcessor,
|
||||
SelectedChannel channel) = 0;
|
||||
virtual void InitWrite(SelectedChannel channel) = 0;
|
||||
|
||||
/* Blocking RX worker loop. Assumes the chip is already brought up (a prior
|
||||
* Init or InitWrite on this device) — performs NO bring-up, channel set, or
|
||||
* beamforming arming. Runs on the CALLER's thread and returns once
|
||||
* StopRxLoop() is called or the global stop flag is set; it is restartable
|
||||
* after it returns. This is the piece that lets one process bring up once
|
||||
* (InitWrite) and then run TX and RX concurrently on the same claimed handle
|
||||
* — Init is the RX-only convenience wrapper (bring-up + StartRxLoop). */
|
||||
virtual void StartRxLoop(Action_ParsedRadioPacket packetProcessor) = 0;
|
||||
|
||||
/* Ask a running StartRxLoop to exit (sets a flag; the caller then joins
|
||||
* whatever thread runs StartRxLoop). Default no-op. */
|
||||
virtual void StopRxLoop() {}
|
||||
virtual void SetMonitorChannel(SelectedChannel channel) = 0;
|
||||
|
||||
/* Lean intra-band, same-bandwidth channel retune for hop/sweep dwells: the RF
|
||||
* channel switch only, skipping the per-rate TX-power loop and bandwidth
|
||||
* post-set a hop doesn't need (see docs/frequency-hopping.md). Generations
|
||||
* with a fast path override this (Jaguar1, Jaguar3 — both fall back to the
|
||||
* full path internally on a band change); the default is the full
|
||||
* SetMonitorChannel at the current width/offset, so callers may hop through
|
||||
* this unconditionally on any chip. `cache_rf` selects the cached-RF-write
|
||||
* variant where one exists (false = re-read per hop, for A/B measurement);
|
||||
* the default argument binds here, at the interface. */
|
||||
virtual void FastRetune(uint8_t channel, bool cache_rf = true) {
|
||||
(void)cache_rf;
|
||||
SelectedChannel c = GetSelectedChannel();
|
||||
c.Channel = channel;
|
||||
SetMonitorChannel(c);
|
||||
}
|
||||
|
||||
/* Lean same-channel bandwidth switch between 20 MHz and 5/10 MHz narrowband —
|
||||
* the bandwidth analogue of FastRetune. On the chips that support it the
|
||||
* whole switch collapses to a single BB dword write, because across a
|
||||
* 20<->5/10 toggle the RF stays in 20 MHz mode and only the baseband ADC/DAC
|
||||
* re-clock register changes (everything else — RF bandwidth, MAC BW, TX
|
||||
* power, IQK — is invariant, so it is skipped). Generations with a fast path
|
||||
* override this; the default falls back to a full SetMonitorChannel at the
|
||||
* current channel/offset, so callers may use it unconditionally. */
|
||||
virtual void FastSetBandwidth(ChannelWidth_t bw) {
|
||||
SelectedChannel c = GetSelectedChannel();
|
||||
c.ChannelWidth = bw;
|
||||
SetMonitorChannel(c);
|
||||
}
|
||||
|
||||
/* Force a flat absolute TXAGC index across all rates (the debug /
|
||||
* SDR-visibility knob — same knob as SetTxPowerIndexOverride, kept for
|
||||
* source compatibility; the override form has the explicit clear). NB this
|
||||
* is a REAL flat override on every generation now — it previously had three
|
||||
* divergent semantics (Jaguar1: pre-efuse fallback, silently ignored with
|
||||
* loaded EFUSE; Jaguar2: dead store; Jaguar3: flat reference). */
|
||||
virtual void SetTxPower(uint8_t power) {
|
||||
SetTxPowerIndexOverride(static_cast<int>(power));
|
||||
}
|
||||
|
||||
/* --- Runtime TX-power control (see src/TxPower.h for the full model) ---
|
||||
*
|
||||
* THREADING CONTRACT: like every other control-plane entry point
|
||||
* (SetMonitorChannel, FastRetune, SetTxMode, Start/StopCwTone), these are
|
||||
* single-control-thread calls — invoke them from the thread that owns the
|
||||
* device's control plane, never concurrently with a channel set. Jaguar3
|
||||
* additionally serializes against its coex/thermal tick internally; on
|
||||
* Jaguar1/2 the USB-touching apply itself is the caller's to sequence.
|
||||
* GetTxPowerCaps and the cached (non-readback) part of GetTxPowerState are
|
||||
* safe from any thread. */
|
||||
|
||||
/* Static capabilities of this family's TX-power knobs; supported=false on
|
||||
* the default (a generation without the API wired). */
|
||||
virtual devourer::TxPowerCaps GetTxPowerCaps() { return {}; }
|
||||
|
||||
/* Adjust TX power RELATIVE to the efuse-calibrated per-rate table (or the
|
||||
* flat override when one is active) in quarter-dB. Quantized to the family
|
||||
* step and clamped to the caps range; returns the APPLIED qdB (0 when
|
||||
* unsupported), so a closed-loop controller knows exactly what moved.
|
||||
* Sticky: survives SetMonitorChannel (re-folded against the new channel's
|
||||
* table) and FastRetune (hop paths never rewrite TXAGC). Refused (returns
|
||||
* 0, logs) while a CW tone holds the chip — TXAGC does not modulate a bare
|
||||
* LO carrier. */
|
||||
virtual int SetTxPowerOffsetQdb(int qdb) {
|
||||
(void)qdb;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Force / clear the flat absolute TXAGC index: idx >= 0 forces it for all
|
||||
* rates (composes with the offset), idx < 0 reverts to the efuse per-rate
|
||||
* baseline. The primary knob — SetTxPower forwards here; a generation
|
||||
* without the API wired ignores it (caps.supported=false). */
|
||||
virtual void SetTxPowerIndexOverride(int idx) { (void)idx; }
|
||||
|
||||
/* Program caller-supplied per-rate TXAGC diffs (signed qdB vs the
|
||||
* reference anchor) in place of the chip's default by-rate table.
|
||||
* std::nullopt clears back to the default. Applies live; persists across
|
||||
* SetMonitorChannel / FastRetune and override-set/clear (Runtime TX power
|
||||
* family contract). Returns false where unsupported (everything except
|
||||
* the 8822E). */
|
||||
virtual bool SetTxPowerRateDiffs(const std::optional<devourer::TxRateDiffsQdb>& diffs) {
|
||||
(void)diffs;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Re-program the TX-power registers from the current knob state at the
|
||||
* CURRENT channel — the hook tests use to force a re-apply without moving
|
||||
* any knob. Returns false when unsupported or the chip isn't brought up. */
|
||||
virtual bool ReApplyTxPower() { return false; }
|
||||
|
||||
/* Snapshot of the knob state + representative effective indices (register
|
||||
* readback where the family's TXAGC block is readable). */
|
||||
virtual devourer::TxPowerState GetTxPowerState() { return {}; }
|
||||
|
||||
/* Chip thermal-meter snapshot (RF 0x42 family; efuse baseline where the
|
||||
* family wires one — see src/ThermalStatus.h). The PA-heating input of the
|
||||
* adaptive-link controller. Default returns an all-invalid reading. */
|
||||
virtual devourer::ThermalStatus GetThermalStatus() { return {}; }
|
||||
|
||||
/* Per-chip TX capability report (see src/TxCaps.h): spatial streams, STBC /
|
||||
* LDPC / SGI support, max bandwidth — derived from the chip identity resolved
|
||||
* at construction. A caller (or send_packet) uses it to avoid requesting a
|
||||
* feature the silicon can't do (e.g. STBC on a 1T1R part, which produces a
|
||||
* frame that never decodes). Default returns supported=false. */
|
||||
virtual devourer::TxCaps GetTxCaps() { return {}; }
|
||||
|
||||
/* Aggregate STATIC adapter-capability report (see src/AdapterCaps.h):
|
||||
* identity (chip name, generation, variant, transport, chip-id), TX/RX chain
|
||||
* counts, the composed TxCaps + TxPowerCaps, the supported channel-width set,
|
||||
* per-band tunable + characterized frequency spans, and the per-family
|
||||
* feature flags (per-packet TX power, narrowband, fast retune, per-chain
|
||||
* RSSI). Resolved at construction — safe from any thread and callable BEFORE
|
||||
* Init/InitWrite (the demos emit it as the `adapter.caps` event right after
|
||||
* CreateRadio). Default returns supported=false. */
|
||||
virtual devourer::AdapterCaps GetAdapterCaps() { return {}; }
|
||||
|
||||
/* Best-effort live estimate of which RX chains are actually carrying signal
|
||||
* (see ActiveRxPaths in src/RxQuality.h) — derived from the per-frame
|
||||
* per-chain RSSI the frame parser fills, so it needs an RX loop running and
|
||||
* ambient traffic to mean anything. A chain whose mean RSSI sits far below
|
||||
* the strongest is reported inactive (a disconnected/blocked antenna, or a
|
||||
* software-masked path). Delta semantics like GetRxQuality: the window drains
|
||||
* on read. Default is an all-invalid snapshot; a generation with >=2 RX
|
||||
* chains overrides. NOT part of AdapterCaps, which is static. */
|
||||
virtual devourer::ActiveRxPaths GetActiveRxPaths() { return {}; }
|
||||
|
||||
virtual bool send_packet(const uint8_t *packet, size_t length) = 0;
|
||||
|
||||
/* Hardware ACK responder (src/AckResponder.h): program the port identity
|
||||
* (MACID/BSSID = `mac`, net_type = AP) so the MAC auto-ACKs — SIFS-timed,
|
||||
* zero host involvement — any unicast frame addressed to `mac`, while
|
||||
* monitor RX/injection continue unchanged. The reliable-unicast enabler:
|
||||
* a peer TXing to `mac` with normal ack-policy gets hardware
|
||||
* retransmissions until the ACK (its tx.report shows retries~0). `mac`
|
||||
* must be unicast (I/G clear). Retargeting hardware ACK behavior to a
|
||||
* caller-supplied address is opt-in only. Some implementations, notably
|
||||
* RTL8733B, may already respond for the initialization MAC. Returns false
|
||||
* when unsupported or when arm/verification fails; false is not proof of
|
||||
* passive state, so implementations log if rollback cannot be verified.
|
||||
* Clear is a non-throwing best effort to return net_type to No Link — and,
|
||||
* where clearing net_type does not end the measured response behavior, to
|
||||
* move the port identity off `mac` as well (see the RTL8733B and
|
||||
* Jaguar1/CHIP_8812 backends). Clear does not promise silence: a die that
|
||||
* matches MACID alone answers for whatever address is left programmed,
|
||||
* including the one MAC bring-up wrote. */
|
||||
virtual bool SetAckResponder(const devourer::MacAddr &mac) {
|
||||
(void)mac;
|
||||
return false;
|
||||
}
|
||||
virtual void ClearAckResponder() {}
|
||||
|
||||
/* 802.11 A-MPDU TX mode (src/AmpduMode.h): the first-class bundle of the
|
||||
* recipe the spike + pacing sweep proved on-air. When enabled, every data
|
||||
* frame is marked aggregatable (data QSEL + AGG_EN + MAX_AGG_NUM +
|
||||
* AMPDU_DENSITY, and — for the no-BlockAck-peer broadcast case — a per-frame
|
||||
* retry limit of 0), and the call programs the MAC aggregate-fill timer +
|
||||
* burst-mode gate live (the pacing that gates net goodput). Amortizes one
|
||||
* PHY preamble over many MPDUs: +30% on-air goodput at MCS7/20, more at
|
||||
* higher rates. The caller must keep the TX queue fed deep enough for the
|
||||
* MAC to aggregate (send_packets with enough in flight). Off keeps every TX
|
||||
* byte-identical. Returns false where unsupported (USB HalMAC + Jaguar1;
|
||||
* PCIe not wired). The lower-level DEVOURER_TX_QSEL / DEVOURER_TX_AMPDU
|
||||
* spike knobs still compose on top for register-level experimentation. */
|
||||
virtual bool SetAmpduMode(const devourer::AmpduMode & /*mode*/) {
|
||||
return false;
|
||||
}
|
||||
virtual void ClearAmpduMode() {}
|
||||
virtual devourer::AmpduMode GetAmpduMode() { return {}; }
|
||||
|
||||
/* 802.11ax trigger-based UL + TWT (src/TriggerTwt.h) — the standards-native
|
||||
* scheduled, contention-free UL access. Kestrel (RTL8852) only: the AP airs
|
||||
* an HE Trigger frame that grants each STA a resource unit and a start time
|
||||
* (SIFS after the trigger), and the STA MAC fires its UL-OFDMA TX at that
|
||||
* instant in hardware. Every method returns false where unsupported (the
|
||||
* Jaguar generations have no HE trigger/TWT firmware surface). */
|
||||
|
||||
/* Air one HE Basic Trigger (UL-OFDMA grant) via the firmware F2P command. */
|
||||
virtual bool SendTrigger(const devourer::TriggerConfig & /*cfg*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Create/modify a TWT agreement (wake window, interval, absolute target-wake
|
||||
* TSF); TeardownTwt deletes it. The AP owns the timetable. */
|
||||
virtual bool ConfigureTwt(const devourer::TwtConfig & /*cfg*/) { return false; }
|
||||
virtual bool TeardownTwt(const devourer::TwtConfig & /*cfg*/) { return false; }
|
||||
/* Bind/unbind a STA (macid) to a TWT config (add/del/terminate/...). */
|
||||
virtual bool TwtBindSta(const devourer::TwtStaAct & /*act*/) { return false; }
|
||||
|
||||
/* Program the fw-autonomous trigger cadence inside a TWT service period
|
||||
* (TWT-OFDMA). Returns false where the fw lacks the (non-canonical) command —
|
||||
* ConfigureUlOfdma is the canonical fallback. */
|
||||
virtual bool ConfigureTwtOfdma(const devourer::TwtOfdmaConfig & /*cfg*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Program the production UL-OFDMA scheduler table (UL_FIXINFO). With
|
||||
* mode=tf_periodic the fw airs Triggers autonomously at the configured
|
||||
* interval — the transport-independent scheduled-UL primitive. */
|
||||
virtual bool ConfigureUlOfdma(const devourer::UlOfdmaConfig & /*cfg*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Register an associated peer STA (a scheduled-UL client): its macid + ADDR_CAM
|
||||
* so a Trigger's per-user grant scores against it. `peer_mac` is the STA's
|
||||
* address, `addr_cam_idx` must be unique per peer. The AP-side companion to
|
||||
* SendTrigger/ConfigureUlOfdma for the end-to-end UL path. Returns false where
|
||||
* unsupported. */
|
||||
virtual bool RegisterPeerSta(const uint8_t /*peer_mac*/[6], uint8_t /*macid*/,
|
||||
uint8_t /*addr_cam_idx*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Register an associated HE STA (macid) as a beamformee to sound: program its
|
||||
* per-STA CSI/bf params (nc/nr/ng/cb/cs) + the sounding-status/CSI-buffer maps
|
||||
* so a BFRP to it solicits a decodable compressed-beamforming report. The
|
||||
* AP-side companion to StartSounding. Returns false where unsupported. */
|
||||
virtual bool RegisterBeamformee(const uint8_t /*peer_mac*/[6], uint8_t /*macid*/,
|
||||
uint8_t /*addr_cam_idx*/,
|
||||
const devourer::StaBfCaps & /*bf*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Drive one HE sounding: hand the fw the NDPA -> NDP -> BFRP descriptor set (a
|
||||
* BFRP is an 802.11ax Trigger-frame variant) to build and air, soliciting the
|
||||
* beamformee's report as a hardware-scheduled HE TB PPDU (RxAtrib.ppdu_type ==
|
||||
* 10). Measured: the shipped client NIC firmware accepts the H2C but does not
|
||||
* air the sequence (the fw sounding-transmit engine is AP-firmware-only) — the
|
||||
* path that actually airs a Trigger on this firmware is host-injection
|
||||
* (SendTrigger). Returns false where unsupported. See docs/he-trigger-ul.md. */
|
||||
virtual bool StartSounding(const devourer::SoundingConfig & /*cfg*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Batch TX: submit `count` frames (each buffer = radiotap header + 802.11
|
||||
* MPDU, the send_packet contract) in one call. With USB TX aggregation
|
||||
* enabled (DeviceConfig tx.usb_agg_max > 0) the USB generations pack
|
||||
* consecutive frames into shared bulk-OUT URBs (see src/TxAggPlan.h) — one
|
||||
* transfer per burst instead of one per frame, and the frames land in the
|
||||
* TXDMA back-to-back. The default (and the PCIe / agg-off behaviour) is a
|
||||
* plain send_packet loop, so callers may use this unconditionally.
|
||||
* Semantics notes: a frame whose radiotap CHANNEL differs from the current
|
||||
* channel flushes the pending URB before the retune (per-packet hopping
|
||||
* stays radiotap-driven); a malformed frame is skipped. Returns the number
|
||||
* of frames successfully submitted. */
|
||||
virtual size_t send_packets(const TxPacketView *pkts, size_t count) {
|
||||
size_t ok = 0;
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
if (pkts[i].data != nullptr && send_packet(pkts[i].data, pkts[i].len))
|
||||
++ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
virtual SelectedChannel GetSelectedChannel() = 0;
|
||||
|
||||
/* Per-unit hardware identity: the MAC address burned in the adapter's EFUSE —
|
||||
* the same value the vendor kernel driver programs into the netdev, and hence
|
||||
* the thing udev's predictable name `wlx<mac>` is derived from.
|
||||
*
|
||||
* Why this is on the interface at all: a consumer that keeps per-adapter state
|
||||
* (a measured TX-power curve, a calibration, anything tied to one specific
|
||||
* dongle) has to answer "is this the same physical adapter I measured last
|
||||
* time?" across a re-plug, a reboot and a port change. Neither key otherwise
|
||||
* available can answer it. A USB bus path identifies a *port*, not a device.
|
||||
* And the USB serial descriptor is not unique: on every RTL88x2 part measured
|
||||
* it is the constant placeholder "123456", burned into the EFUSE a few bytes
|
||||
* from the MAC itself. Keying on it is worse than useless — two adapters in
|
||||
* one host would share state and silently apply each other's measurements.
|
||||
*
|
||||
* `out` receives the 6 bytes in wire order. Returns false where the EFUSE
|
||||
* value is unprogrammed/unreadable — and, on any generation, possibly before
|
||||
* Init/InitWrite: the EFUSE is only guaranteed readable on a brought-up chip,
|
||||
* and this accessor never powers the chip on as a side effect (Kestrel serves
|
||||
* the bring-up parse; the others fall back to a best-effort pre-init read
|
||||
* that degrades to false on an unpowered adapter). Callers must treat false
|
||||
* as "no stable identity available" rather than substituting a weaker one
|
||||
* silently; for a guaranteed answer on a programmed unit, ask after bring-up.
|
||||
* Implemented on every generation (per-chip offsets at each HAL's perm_mac /
|
||||
* efuse parse); the interface default stays false so a future generation
|
||||
* degrades gracefully rather than fabricating an identity. */
|
||||
virtual bool GetPermanentMacAddress(uint8_t /*out*/[6]) { return false; }
|
||||
|
||||
/* Read the 64-bit hardware TSF (Timing Synchronization Function) timer — the
|
||||
* 802.11 MAC's free-running microsecond clock (REG_TSFTR). It runs off the
|
||||
* chip's crystal and is latched into every RX descriptor at receive
|
||||
* (rx_pkt_attrib::tsfl, the low 32 bits), so it is a precise, host-jitter-free
|
||||
* timing reference for multi-radio sync / TDOA / scheduled bursts. Returns 0
|
||||
* where unsupported (default). NB: a register read is a control transfer —
|
||||
* calling it concurrently with a heavy RX bulk-IN load can race (catch the
|
||||
* exception). */
|
||||
virtual uint64_t ReadTsf() { return 0; }
|
||||
|
||||
/* Write the 64-bit MAC TSF (REG_TSFTR). Sets the free-running microsecond clock
|
||||
* — the primitive for TSF *adoption* (a slave slewing its clock onto the
|
||||
* master's, so its per-frame `tsfl` reads in the master's timebase). The
|
||||
* counter keeps running, so a read-add-write shifts by an approximate delta (a
|
||||
* control loop absorbs the read→write latency). NOTE: this moves the reported
|
||||
* TSF (and the beacon-body timestamp) but NOT the beacon TBTT air-time — a
|
||||
* separate per-port timer drives the TBTT (bench-proven). To steer the
|
||||
* hardware-timed beacon (the uplink timing-advance actuator) use
|
||||
* AdjustBeaconTiming. No-op where unsupported. */
|
||||
virtual void WriteTsf(uint64_t tsf) { (void)tsf; }
|
||||
|
||||
/* Load a beacon into the beacon reserved-page + enable the MAC beacon function,
|
||||
* so the chip AUTO-TRANSMITS it at each TBTT — hardware-timed and
|
||||
* hardware-TSF-stamped (the MAC inserts the live 64-bit TSF into the beacon
|
||||
* timestamp at TX), fully host-jitter-free. `beacon` is a full 802.11 beacon
|
||||
* MPDU (a leading radiotap header, if present, is stripped); addr2/addr3 set
|
||||
* the port MAC/BSSID. `interval_tu` is the beacon interval in TU (1 TU =
|
||||
* 1024 µs). One call suffices — the hardware beacons indefinitely. Implemented
|
||||
* on all three generations (Jaguar2/3: HalMAC reserved-page download;
|
||||
* Jaguar1 incl. the 8814A: the pre-HalMAC BCNQ-boundary store bracket —
|
||||
* note the 8814A's stored beacon airs with the 802.11 sequence pinned at 0,
|
||||
* kernel rtw88 parity). See docs/time-distribution.md. */
|
||||
virtual bool StartBeacon(const uint8_t *beacon, size_t len,
|
||||
int interval_tu) {
|
||||
(void)beacon; (void)len; (void)interval_tu;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Replace the ACTIVE beacon's content in place — the dynamic-grant delivery
|
||||
* primitive (a scheduled MAC carries its DCI-style grant map in the beacon
|
||||
* body). Same buffer contract as StartBeacon (a leading radiotap header is
|
||||
* stripped; the raw 802.11 MPDU lands in the reserved page); the beacon
|
||||
* interval, TBTT phase and port identity are NOT touched — changing
|
||||
* addr2/addr3 mid-flight is unsupported (the port registers keep the
|
||||
* StartBeacon identity). Requires an active StartBeacon; returns false
|
||||
* otherwise. Rides the same reserved-page re-download the TBTT steers use,
|
||||
* so the cost bound is the steer's: at most one skipped beacon per update
|
||||
* while the valid latch re-arms, and the swap is NOT atomic versus TBTT (a
|
||||
* beacon airing during the download may still carry the previous content).
|
||||
* Measured per-generation skip/latency numbers: docs/scheduled-mac.md. */
|
||||
virtual bool UpdateBeaconPayload(const uint8_t *beacon, size_t len) {
|
||||
(void)beacon; (void)len;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Stop the hardware beacon: EN_BCN_FUNCTION off + net_type back to No Link.
|
||||
* The chip beacons AUTONOMOUSLY once StartBeacon arms it — killing the host
|
||||
* process does NOT silence it (bench-bitten: a killed probe's beacon kept
|
||||
* airing and contaminated the next test's witness) — so any beaconing
|
||||
* session that ends without a device power-cycle must call this. Idempotent;
|
||||
* returns false when no beacon was active. Jaguar1 additionally reads back
|
||||
* its three stop controls and returns false if any remains active; that
|
||||
* failure must be retried (or followed by hardware shutdown) before its
|
||||
* shared port is reused. */
|
||||
virtual bool StopBeacon() { return false; }
|
||||
|
||||
/* Disable / restore the MAC carrier-sense gate that defers TX — both primary
|
||||
* CCA (0x520[14], carrier-sense of a decodable preamble) and EDCCA (0x520[15],
|
||||
* energy detect). With it off the MAC does not defer TX to a busy channel, so
|
||||
* injected/beacon TX punches through co-channel traffic instead of backing off:
|
||||
* a TBTT beacon airs exactly on schedule (the sub-µs hardware-beacon downlink,
|
||||
* master-owns-the-channel), and host-injected data holds its rate through a
|
||||
* co-channel transmitter. Measured on-air (Jaguar3, 8822EU/8812CU): monitor
|
||||
* injection otherwise defers ~40-60% to a co-channel 802.11 flooder; clearing
|
||||
* the gate recovers ~1.5-2.2x, back to ~90% of the unimpeded rate
|
||||
* (tests/dis_cca_tx_onair.sh). The energy bit [15] alone is null
|
||||
* against a decodable preamble — the primary-CCA bit [14] is what recovers the
|
||||
* inject path. This is the MAC-gate only; the vendor's BB CCA-off writes are
|
||||
* NOT applied (they deafen the RX). Also DEVOURER_DIS_CCA at construction.
|
||||
*
|
||||
* Pure virtual: every generation implements or loudly refuses — a silent
|
||||
* no-op here reads as "carrier-sense changed" to the caller. Default
|
||||
* state on Jaguar1/2/3 is carrier-sense + EDCCA ENABLED (Jaguar1 programs
|
||||
* its BB EDCCA thresholds at bring-up — its init table parks them at
|
||||
* never-trigger); Kestrel's TX path keeps the gates cleared because
|
||||
* carrier-sense TX 103-stalls without the un-ported IQK/DPK cal
|
||||
* (perpetual-busy detectors) — it logs that loudly instead of
|
||||
* pretending. */
|
||||
virtual void SetCcaMode(bool disabled) = 0;
|
||||
|
||||
/* Shift the next hardware beacon TBTT by `microseconds` (>0 = later/retard,
|
||||
* <0 = earlier/advance), quantized to whole TU (1 TU = 1024 µs). One-shot
|
||||
* REG_BCN_INTERVAL tweak: runs one beacon interval at (nominal + round(µs/1024))
|
||||
* TU then restores nominal, so the next TBTT — and the cadence thereafter —
|
||||
* shifts by that many TU. This is the beacon-timing / uplink timing-advance
|
||||
* actuator: WriteTsf moves the reported TSF but NOT the TBTT air-time (a
|
||||
* separate per-port timer drives it), whereas the interval tweak steers it
|
||||
* deterministically (the 802.11 IBSS/TSF-merge mechanism; bench-proven to the
|
||||
* microsecond). Requires an active StartBeacon. BLOCKS the caller ~one beacon
|
||||
* interval (the tweaked interval must latch and fire once before restore).
|
||||
* Returns the actual applied shift in µs (TU-quantized); 0 if no active beacon
|
||||
* or |microseconds| < 512. Jaguar3 and Jaguar2: the J2 beacon engine loses its
|
||||
* bcn-valid latch on any TBTT re-latch (bench-proven), so the J2 path follows
|
||||
* the steer with a reserved-page re-download of the retained beacon — one
|
||||
* skipped beacon per correction. On Jaguar1 the interval tweak is inert
|
||||
* (bench-proven on the 8821AU), so the TU-quantized shift rides the fine
|
||||
* TSF-toggle mechanism instead — which also moves the reported TSF, unlike
|
||||
* J2/J3. Base is a no-op. */
|
||||
virtual int32_t AdjustBeaconTiming(int32_t microseconds) {
|
||||
(void)microseconds;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Fine (sub-TU, microsecond-granular) variant of AdjustBeaconTiming. Shifts the
|
||||
* next beacon TBTT by `microseconds` (>0 = later/retard, <0 = earlier/advance)
|
||||
* by toggling the MAC beacon function off, shifting the port-0 TSF, and toggling
|
||||
* it back on so the TBTT counter re-derives from the shifted TSF. Unlike the
|
||||
* interval-tweak AdjustBeaconTiming (quantized to whole TU), this steers at
|
||||
* microsecond resolution — the µs-fine uplink timing-advance actuator. Note it
|
||||
* also shifts this port's reported TSF (and the beacon-body timestamp) by the
|
||||
* same amount, which is the intended behaviour for a UE advancing its own
|
||||
* timebase. The USB read→write latency adds a sub-ms offset (~0.5–1.2 ms) that
|
||||
* a closed timing-advance loop absorbs — the *resolution* is microseconds.
|
||||
* Requires an active StartBeacon; returns the applied shift in µs. All three
|
||||
* generations: the J2 and J1 beacon engines drop their bcn-valid latch on the
|
||||
* toggle, so those paths re-download the retained reserved-page beacon after
|
||||
* the re-latch — one skipped beacon per correction. The 8814A additionally
|
||||
* pulses DUAL_TSF_RST (its TBTT counter free-runs across the toggle), which
|
||||
* re-derives the grid ABSOLUTELY from the shifted TSF — each steer also
|
||||
* cancels accumulated drift, so the TBTT ends up TSF-locked. Base is a
|
||||
* no-op. */
|
||||
virtual int32_t AdjustBeaconTimingFine(int32_t microseconds) {
|
||||
(void)microseconds;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* TSF-PRESERVING µs-fine TBTT actuator: pin the beacon TBTT so it fires at
|
||||
* TSF % interval == offset_us, WITHOUT disturbing the reported TSF.
|
||||
* AdjustBeaconTimingFine necessarily jumps the TSF (the TBTT re-derives from
|
||||
* a shifted TSF), which corrupts any controller whose phase estimate is a
|
||||
* fit against this port's TSF (ref = a·tsf + b — every steer breaks the
|
||||
* slope, and a high-authority loop chases the corrupted estimate into a
|
||||
* limit cycle; bench-observed on the 8821CE AP↔PTP loop). This variant does
|
||||
* the same shift + re-latch, then immediately writes the TSF back onto its
|
||||
* original timeline — a bare TSF write does not move the TBTT (bench-proven),
|
||||
* so the steered TBTT phase survives while the clock the loop reads stays
|
||||
* continuous. The residual TSF discontinuity is one register-write latency:
|
||||
* ~µs over PCIe MMIO, ~0.5–1 ms over USB (so on USB this only pays off for
|
||||
* steers larger than that).
|
||||
*
|
||||
* ABSOLUTE semantics (unlike the incremental AdjustBeaconTimingFine): each
|
||||
* call re-pins the TBTT to the TSF grid, so consecutive calls don't
|
||||
* accumulate, and a PTP-disciplined TSF drags the pinned TBTT with it
|
||||
* between corrections — the fit-free discipline pattern. Requires an active
|
||||
* StartBeacon; returns the applied offset (normalized into the beacon
|
||||
* period), 0 if no active beacon.
|
||||
*
|
||||
* Per generation (all bench-proven): Jaguar2 — full support, ~10 µs TSF
|
||||
* disturbance over PCIe MMIO (8821CE; the AP↔PTP loop holds ~±1 µs with
|
||||
* it). Jaguar3 — full support over USB (~0.5–1.5 ms restore-write
|
||||
* disturbance; still far below a fine steer's full-magnitude jump).
|
||||
* Jaguar1 — offset 0 only (arm/re-derive): its TBTT is hardware-locked to
|
||||
* the TSF grid, so a nonzero TSF-preserving pin cannot hold (refused); the
|
||||
* flip side is that steering/disciplining the J1 TSF steers the TBTT with
|
||||
* it in hardware, no actuator needed. Base is a no-op. */
|
||||
virtual int32_t PinBeaconTbtt(int32_t offset_us) {
|
||||
(void)offset_us;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Clean shutdown: halt TRX DMA and power the chip down to a re-enumerable
|
||||
* state (mirrors the kernel driver's card-disable on unbind). Call after the
|
||||
* RX/TX loop exits and BEFORE releasing/closing the USB interface, so the
|
||||
* adapter isn't abandoned with its USB core hung. Default no-op. */
|
||||
virtual void Stop() {}
|
||||
|
||||
/* Runtime TX-mode default: the modulation/rate/BW/GI/FEC used when a frame's
|
||||
* radiotap carries no rate (per-packet radiotap always wins). Both chip
|
||||
* families implement it; default no-op keeps other impls unaffected. Without
|
||||
* it, a rate-less frame falls back to MGN_1M — e.g. an MCS7 flood would
|
||||
* silently go on-air at 1 Mbps. */
|
||||
virtual void SetTxMode(const devourer::TxMode & /*mode*/) {}
|
||||
virtual void ClearTxMode() {}
|
||||
|
||||
/* TX submission health snapshot (see TxStats.h) — the driver-side drop /
|
||||
* congestion signal an adaptive-link controller uses to detect a full TX FIFO
|
||||
* (a bulk-OUT TIMEOUT = recoverable back-pressure) vs a hard error. Counted at
|
||||
* the shared USB bulk-OUT layer, so every generation reports it. Default is an
|
||||
* all-zero snapshot. */
|
||||
virtual devourer::TxStats GetTxStats() { return {}; }
|
||||
|
||||
/* Consolidated windowed RX link-quality snapshot (see RxQuality.h) — the
|
||||
* runtime feed a closed-loop adaptive-link controller reads instead of
|
||||
* scraping the demo's stdout. Fuses the per-frame RSSI/SNR/EVM aggregate the
|
||||
* device accumulates internally, a passive noise-floor estimate (rssi - snr,
|
||||
* the self-jamming signal), the frame-free FA/CCA/IGI energy, and the
|
||||
* LinkHealth verdict. Drains the window (delta semantics); on the Realtek
|
||||
* backends it consumes the same FA/CCA/IGI delta that IRtlRadio::GetRxEnergy
|
||||
* reads, so do not poll both on the same cadence. Default is an all-invalid
|
||||
* snapshot; each generation overrides. */
|
||||
virtual devourer::RxQuality GetRxQuality() { return {}; }
|
||||
|
||||
/* --- Adapter health (see src/AdapterHealth.h; examples/doctor is the
|
||||
* reference consumer; the EFUSE probe is on IRtlRadio) --- */
|
||||
|
||||
/* Outcome of the most recent firmware download (populated during
|
||||
* Init/InitWrite). On Jaguar1 a failed FW boot does not abort bring-up —
|
||||
* this is the only place the failure is visible to a caller. */
|
||||
virtual devourer::FwBootStatus GetFwBootStatus() { return {}; }
|
||||
|
||||
};
|
||||
|
||||
#endif /* IRADIO_H */
|
||||
@@ -0,0 +1,90 @@
|
||||
#ifndef IRTL_RADIO_H
|
||||
#define IRTL_RADIO_H
|
||||
|
||||
#include "IRadio.h"
|
||||
|
||||
#include "AdapterHealth.h" /* EfuseStability */
|
||||
#include "RxSense.h" /* RxEnergy */
|
||||
|
||||
/* IRtlRadio is the Realtek-family extension of IRadio: the members whose
|
||||
* semantics are defined by Realtek silicon (phydm false-alarm / CCA / IGI / NHM
|
||||
* counters, the EFUSE logical map and its 0x8129 EEPROM id, the AFE crystal-cap
|
||||
* register, the rtw canary register set) rather than by a vendor-neutral
|
||||
* concept. Every Realtek backend derives from it:
|
||||
* - RtlJaguarDevice — Realtek "Jaguar" wave-1 (8812AU/8811AU/8821AU/8814AU)
|
||||
* - RtlJaguar2Device — Realtek "Jaguar2" (8822BU/8812BU)
|
||||
* - RtlJaguar3Device — Realtek "Jaguar3" (8822CU/8812EU/8822EU)
|
||||
* - Rtl8733bDevice — Realtek HALMAC 87xx 11n (RTL8731BU/RTL8733BU)
|
||||
* - RtlKestrelDevice — Realtek G6 11ax (RTL8852BU/RTL8852CU)
|
||||
*
|
||||
* WiFiDriver::CreateRadio returns an IRadio; a caller that needs one of these
|
||||
* members dynamic_casts to IRtlRadio and treats nullptr as "not a Realtek
|
||||
* radio" — skip the feature with one diagnostic, never fake a reading.
|
||||
* Per-generation research helpers (BB-debug-port reads, the 8814 queue poller,
|
||||
* the CW tone) stay on the concrete classes: the same convention one level
|
||||
* further down. Every member here keeps the IRadio rule — virtual with a
|
||||
* not-ported default, never pure. */
|
||||
class IRtlRadio : public IRadio {
|
||||
public:
|
||||
/* Crystal (XTAL) load-capacitance trim — the CFO lever. Writes the AFE
|
||||
* crystal-cap field (a per-chip register), pulling the chip's reference
|
||||
* oscillator a few ppm to align a marginal TX/RX crystal pair; the payoff
|
||||
* is narrowband at the edge of its CFO budget (5 MHz at 5 GHz). `cap` is a
|
||||
* raw trim code in [0, GetAdapterCaps().xtal_cap_max]; cap < 0 reverts to
|
||||
* the efuse/default value. Both physical caps (Xi/Xo) are set together.
|
||||
* Returns the applied code, or -1 when unsupported. Sticky across channel
|
||||
* changes (an AFE register, untouched by the RF retune). */
|
||||
virtual int SetXtalCap(int cap) {
|
||||
(void)cap;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Current crystal-cap code (the last SetXtalCap value, or the efuse default
|
||||
* at bring-up). -1 when unsupported. */
|
||||
virtual int GetXtalCap() { return -1; }
|
||||
|
||||
/* Frame-free RX energy / channel-busy snapshot (see RxSense.h) — the read side
|
||||
* of the DEVOURER_CW_TONE emitter, used for spectrum-sensing / interferer
|
||||
* detection. Reads the chip's phydm false-alarm + CCA counters, DIG/IGI, and
|
||||
* (when asked) the NHM power histogram. FA/CCA counts are the delta since the
|
||||
* previous call. Default returns an all-invalid snapshot; each generation
|
||||
* overrides with a real reader.
|
||||
*
|
||||
* `with_nhm` is a cost decision, not a preference: the NHM read arms a ~2 ms
|
||||
* measurement window and then polls a ready bit at 1 ms granularity
|
||||
* (src/NhmReader.h), so it dominates the call — the scalar FA/CCA/IGI path is
|
||||
* a handful of register reads. Pass false for the throwaway read that resets
|
||||
* the delta counters before an observation window, and for any caller
|
||||
* sampling faster than a few times a second. */
|
||||
virtual RxEnergy GetRxEnergy(bool with_nhm) { (void)with_nhm; return {}; }
|
||||
|
||||
/* Perform `reads` fresh PHYSICAL EFUSE logical-map reads (each pass re-runs
|
||||
* the efuse-controller read sequence — not the cached shadow) and
|
||||
* cross-compare them. Dying silicon returns different content per read;
|
||||
* healthy silicon is byte-identical every time. Post-bring-up only: returns
|
||||
* supported=false before Init/InitWrite (on the 8814AU a pre-fwdl EFUSE
|
||||
* read breaks the RSVD-page firmware download). Control-plane threading
|
||||
* contract applies (same as SetMonitorChannel). */
|
||||
virtual devourer::EfuseStability ProbeEfuseStability(int reads = 4) {
|
||||
(void)reads;
|
||||
return {};
|
||||
}
|
||||
|
||||
/* Dump the chip's canary register set (BB / MAC / per-path RF) to the
|
||||
* diagnostic plane. Reads only — no writes, no calibration, no bring-up.
|
||||
*
|
||||
* The point is that it is callable on a device that has NOT been Init'ed, so
|
||||
* a chip left in whatever state a previous session abandoned it in can be
|
||||
* inspected AS IT IS. Every other path into this driver reconfigures the chip
|
||||
* on the way in, which destroys exactly the evidence a state bug leaves
|
||||
* behind. Pair it with an open that skips libusb_reset_device
|
||||
* (claim_interface_then_reset's `do_reset=false`) — a USB reset re-runs the
|
||||
* chip's own boot and is just as destructive.
|
||||
*
|
||||
* Output format matches DEVOURER_DUMP_CANARY, so two dumps diff directly with
|
||||
* tests/canary_diff.py. Reading a powered-down chip yields garbage or throws;
|
||||
* interpreting that is the caller's job. No-op where unsupported (default). */
|
||||
virtual void DumpChipState() {}
|
||||
};
|
||||
|
||||
#endif /* IRTL_RADIO_H */
|
||||
@@ -0,0 +1,54 @@
|
||||
#ifndef INIT_TIMER_H
|
||||
#define INIT_TIMER_H
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <utility>
|
||||
|
||||
#include "logger.h"
|
||||
|
||||
/* Stage timer for init-path profiling. Emits one event per checkpoint:
|
||||
*
|
||||
* {"ev":"init.timing","stage":"<scope>.<stage>","ms":N}
|
||||
*
|
||||
* `stage()` reports time since the previous checkpoint (or construction);
|
||||
* `total()` reports time since construction. Always-on: a handful of events
|
||||
* per init, negligible next to the USB transfers being measured.
|
||||
* tests/bench_init.py parses these events (docs/logging.md). */
|
||||
class InitTimer {
|
||||
using clock = std::chrono::steady_clock;
|
||||
|
||||
public:
|
||||
InitTimer(Logger_t logger, const char *scope)
|
||||
: _logger{std::move(logger)}, _scope{scope}, _start{clock::now()},
|
||||
_last{_start} {}
|
||||
|
||||
void stage(const char *name) {
|
||||
const auto now = clock::now();
|
||||
emit(name, ms(_last, now));
|
||||
_last = now;
|
||||
}
|
||||
|
||||
void total() { emit("total", ms(_start, clock::now())); }
|
||||
|
||||
private:
|
||||
void emit(const char *name, long long millis) {
|
||||
char stage[96];
|
||||
std::snprintf(stage, sizeof(stage), "%s.%s", _scope, name);
|
||||
devourer::Ev(_logger->events(), "init.timing")
|
||||
.f("stage", stage)
|
||||
.f("ms", millis);
|
||||
}
|
||||
|
||||
static long long ms(clock::time_point from, clock::time_point to) {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(to - from)
|
||||
.count();
|
||||
}
|
||||
|
||||
Logger_t _logger;
|
||||
const char *_scope;
|
||||
clock::time_point _start;
|
||||
clock::time_point _last;
|
||||
};
|
||||
|
||||
#endif /* INIT_TIMER_H */
|
||||
@@ -0,0 +1,340 @@
|
||||
#include "LaCapture.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
namespace {
|
||||
constexpr uint16_t kRegSysCfg = 0x00F0; /* liveness canary (BbDbgportReader) */
|
||||
|
||||
/* MAC-side LA block — identical across families
|
||||
* (phydm_la_set_mac_iq_dump / phydm_la_get_tx_pkt_buf). */
|
||||
constexpr uint16_t kRegLaCtrl = 0x07C0; /* [0]=en [1]/[2]=poll [5]=manual
|
||||
* [7:6]=mac sig [14:8]=trig time
|
||||
* [30:16]=finish [31]=wrap */
|
||||
constexpr uint16_t kRegLaMacMask = 0x07C4;
|
||||
constexpr uint16_t kRegLaMacSig = 0x07C8;
|
||||
constexpr uint16_t kRegLaConf = 0x07CC; /* trig-time unit; [30]=full buff */
|
||||
constexpr uint16_t kRegTxffPage = 0x0140; /* page = 0x780 + (addr>>12) */
|
||||
constexpr uint16_t kRegTxffDbgEn = 0x0106; /* 0x69 = TXFF debug access */
|
||||
constexpr uint16_t kTxffWindow = 0x8000; /* 4 KB readback window */
|
||||
constexpr uint16_t kRegMacDbgEn = 0x00F4; /* [16] MAC dbg port enable */
|
||||
constexpr uint16_t kRegMacDbgSel = 0x0038; /* [23:16] MAC dbg port */
|
||||
|
||||
/* 11AC dialect (phydm_la_set_bb, phydm_debug.c dbg-port routing). */
|
||||
constexpr uint16_t kAcLaEngine = 0x095C; /* [4:0]=trig bit [7:5]=rate
|
||||
* [11:8]=dma [23]=la clk [31]=edge */
|
||||
constexpr uint16_t kAcRptUpdate = 0x08B4; /* [7] update rpt every pkt */
|
||||
constexpr uint16_t kAcDbgPortSel = 0x08FC; /* selector (dword) */
|
||||
constexpr uint16_t kAcDbgPortHdr = 0x08F8; /* [25:22] header mux */
|
||||
constexpr uint16_t kAcDbgPortClk = 0x198C; /* [2:0] dbg-port clock (11AC-2) */
|
||||
|
||||
/* JGR3 dialect. */
|
||||
constexpr uint16_t kJ3LaEngine = 0x1CE4; /* [5:0]=dma [7:6]=mac-phy timing
|
||||
* [10:8]=rate [17:13]=trig bit
|
||||
* [26]=edge [27],[31:28]=adv AND */
|
||||
constexpr uint16_t kJ3LaOn = 0x1CF4; /* [23] LA mode on */
|
||||
constexpr uint16_t kJ3RptUpdate = 0x1EB4; /* [23] update rpt every pkt */
|
||||
constexpr uint16_t kJ3DbgPortSel = 0x1C3C; /* [19:8] selector */
|
||||
constexpr uint16_t kJ3AdvAnd123 = 0x1CE8; /* adv-trigger AND1..3 (reset 0) */
|
||||
constexpr uint16_t kJ3AdvAnd4 = 0x1CF0; /* adv-trigger AND4 mask */
|
||||
} // namespace
|
||||
|
||||
LaCapture::LaCapture(RtlAdapter device, Logger_t logger, LaRegs regs)
|
||||
: _device{device}, _logger{logger}, _regs{regs} {}
|
||||
|
||||
bool LaCapture::is_chip_alive() {
|
||||
uint32_t v = _device.rtw_read32(kRegSysCfg);
|
||||
if (v == 0 || v == 0xFFFFFFFFu) {
|
||||
_logger->error("LaCapture: SYS_CFG read 0x{:08x} — chip wedged. "
|
||||
"Recovery: libusb_reset_device, usbreset, power-cycle.",
|
||||
v);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void LaCapture::set_reg(uint16_t addr, uint32_t mask, uint32_t val) {
|
||||
_device.phy_set_bb_reg(addr, mask, val);
|
||||
}
|
||||
|
||||
void LaCapture::snapshot() {
|
||||
_saved.clear();
|
||||
auto save = [&](uint16_t addr) {
|
||||
_saved.emplace_back(addr, _device.rtw_read32(addr));
|
||||
};
|
||||
save(kRegLaCtrl);
|
||||
save(kRegLaMacMask);
|
||||
save(kRegLaMacSig);
|
||||
save(kRegLaConf);
|
||||
save(kRegTxffPage);
|
||||
save(kRegMacDbgEn);
|
||||
save(kRegMacDbgSel);
|
||||
if (_regs.dialect == LaBbDialect::Ac11) {
|
||||
save(kAcLaEngine);
|
||||
save(kAcRptUpdate);
|
||||
save(kAcDbgPortSel);
|
||||
save(kAcDbgPortHdr);
|
||||
if (_regs.dbgport_clk)
|
||||
save(kAcDbgPortClk);
|
||||
} else {
|
||||
save(kJ3LaEngine);
|
||||
save(kJ3LaOn);
|
||||
save(kJ3RptUpdate);
|
||||
save(kJ3DbgPortSel);
|
||||
save(kJ3AdvAnd123);
|
||||
save(kJ3AdvAnd4);
|
||||
}
|
||||
}
|
||||
|
||||
void LaCapture::restore() {
|
||||
/* Stop the LA block first so nothing samples while BB regs move, then
|
||||
* put every touched register back (reverse order). 0x0106 goes back to
|
||||
* 0 explicitly — the vendor flow leaks it set. */
|
||||
_device.rtw_write8(kRegLaCtrl, 0);
|
||||
_device.rtw_write8(kRegTxffDbgEn, 0);
|
||||
for (auto it = _saved.rbegin(); it != _saved.rend(); ++it)
|
||||
_device.rtw_write32(it->first, it->second);
|
||||
}
|
||||
|
||||
void LaCapture::setup_trigger_time(const LaParams &p) {
|
||||
/* phydm_la_set_mac_trigger_time: pick unit u so count < 128. */
|
||||
uint32_t unit = 0;
|
||||
while (unit < 6 && (p.trigger_time_us >> unit) >= 128)
|
||||
unit++;
|
||||
uint32_t count = (p.trigger_time_us >> unit) & 0x7f;
|
||||
set_reg(kRegLaConf, 0x7u << _regs.trig_time_unit_lsb, unit);
|
||||
set_reg(kRegLaCtrl, 0x7f00u, count);
|
||||
}
|
||||
|
||||
void LaCapture::setup_bb(const LaParams &p) {
|
||||
if (_regs.dialect == LaBbDialect::Ac11) {
|
||||
set_reg(kAcDbgPortHdr, 0x3c00000u, p.hdr_sel);
|
||||
set_reg(kAcRptUpdate, 1u << 7, 1); /* update rpt every pkt */
|
||||
set_reg(kAcLaEngine, 0xf00u, p.dma_type);
|
||||
set_reg(kAcLaEngine, 1u << 31, p.edge);
|
||||
set_reg(kAcLaEngine, 0xe0u, p.smp_rate);
|
||||
if (_regs.needs_la_clk) /* 8821C cut B+ (caller skips cut A) */
|
||||
set_reg(kAcLaEngine, 1u << 23, 1);
|
||||
} else {
|
||||
set_reg(kJ3RptUpdate, 1u << 23, 1); /* update rpt every pkt */
|
||||
set_reg(kJ3LaEngine, 0xc0u, 0); /* MAC-PHY timing */
|
||||
set_reg(kJ3LaOn, 1u << 23, 1); /* LA mode on */
|
||||
set_reg(kJ3LaEngine, 0x3fu, p.dma_type);
|
||||
set_reg(kJ3LaEngine, 1u << 26, p.edge);
|
||||
set_reg(kJ3LaEngine, 0x700u, p.smp_rate);
|
||||
/* Advanced AND-gate trigger at pass-through defaults
|
||||
* (phydm_la_bb_adv_trig_setting_jgr3, adv table zeroed). */
|
||||
set_reg(kJ3LaEngine, 1u << 27, 0);
|
||||
set_reg(kJ3LaEngine, 0xf0000000u, 0);
|
||||
set_reg(kJ3AdvAnd123, 1u << 5, 0);
|
||||
set_reg(kJ3AdvAnd123, 0x3c0u, 0);
|
||||
set_reg(kJ3AdvAnd123, 1u << 15, 0);
|
||||
set_reg(kJ3AdvAnd123, 0xf0000u, 0);
|
||||
set_reg(kJ3AdvAnd123, 1u << 25, 0);
|
||||
set_reg(kJ3AdvAnd4, 0xffffffffu, 0);
|
||||
set_reg(kJ3AdvAnd123, 1u << 26, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void LaCapture::setup_dbg_port(const LaParams &p) {
|
||||
/* phydm_set_bb_dbg_port(DBGPORT_PRI_3) + the trig-sel bit. */
|
||||
if (_regs.dialect == LaBbDialect::Ac11) {
|
||||
if (_regs.dbgport_clk)
|
||||
set_reg(kAcDbgPortClk, 0x7u, 0x7);
|
||||
_device.rtw_write32(kAcDbgPortSel, p.dbg_port);
|
||||
} else {
|
||||
set_reg(kJ3DbgPortSel, 0xfff00u, p.dbg_port);
|
||||
}
|
||||
uint32_t trig_sel =
|
||||
(p.trig_mode == LaTrigMode::MacDump) ? 0 : p.trig_sel;
|
||||
if (_regs.dialect == LaBbDialect::Ac11)
|
||||
set_reg(kAcLaEngine, 0x1fu, trig_sel);
|
||||
else
|
||||
set_reg(kJ3LaEngine, 0x3e000u, trig_sel);
|
||||
}
|
||||
|
||||
void LaCapture::setup_mac(const LaParams &p) {
|
||||
/* phydm_la_set_mac_iq_dump. */
|
||||
_device.rtw_write8(kRegLaCtrl, 0);
|
||||
set_reg(kRegLaCtrl, 1u << 0, 1); /* LA block on */
|
||||
|
||||
if (p.trig_mode == LaTrigMode::MacDump) {
|
||||
set_reg(kRegLaCtrl, 1u << 2, 1); /* poll bit, MAC mode */
|
||||
set_reg(kRegLaCtrl, 0x18u, p.edge);
|
||||
set_reg(kRegMacDbgEn, 1u << 16, 1);
|
||||
set_reg(kRegMacDbgSel, 0xff0000u, p.dbg_port);
|
||||
_device.rtw_write32(kRegLaMacMask, 0xffffffffu);
|
||||
_device.rtw_write32(kRegLaMacSig, 0);
|
||||
} else {
|
||||
if (p.trig_mode == LaTrigMode::AdcMacTrig) {
|
||||
set_reg(kRegLaCtrl, 1u << 3, 1); /* MAC-event trigger source */
|
||||
set_reg(kRegLaCtrl, 0xc0u, static_cast<uint32_t>(p.mac_sig));
|
||||
}
|
||||
set_reg(kRegLaCtrl, 1u << 1, 1); /* poll bit, BB-ADC mode */
|
||||
if (p.trig_mode == LaTrigMode::AdcMacTrig &&
|
||||
p.mac_sig == LaMacSig::Manual) {
|
||||
/* Fire the register trigger (0x7c0[5] 0->1) only after the dump
|
||||
* enable above is armed — the vendor sets it earlier in the same
|
||||
* function, but hardware-bisected here: an edge before the poll
|
||||
* bit arms is consumed and the capture never completes. */
|
||||
set_reg(kRegLaCtrl, 1u << 5, 0);
|
||||
set_reg(kRegLaCtrl, 1u << 5, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool LaCapture::poll(const LaParams &p) {
|
||||
const uint8_t polling_bit =
|
||||
(p.trig_mode == LaTrigMode::MacDump) ? (1u << 2) : (1u << 1);
|
||||
for (uint32_t i = 0; i < p.poll_tries; i++) {
|
||||
uint8_t v = _device.rtw_read8(kRegLaCtrl);
|
||||
_logger->debug("LaCapture: poll[{}] 0x7c0[7:0]=0x{:02x} (wait bit 0x{:02x} "
|
||||
"clear)", i, v, polling_bit);
|
||||
if (!(v & polling_bit)) {
|
||||
_logger->debug("LaCapture: capture complete after {} polls", i);
|
||||
return true;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(p.poll_ms));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void LaCapture::readback(const LaParams &p, LaResult &r) {
|
||||
/* phydm_la_get_tx_pkt_buf. */
|
||||
uint32_t buf_start = _regs.buf_start;
|
||||
const uint32_t buf_end = _regs.buf_end;
|
||||
if (p.buff_all && _regs.full_buff_capable)
|
||||
buf_start = buf_end - 2 * (buf_end - buf_start);
|
||||
|
||||
_device.rtw_write8(kRegTxffDbgEn, 0x69);
|
||||
const uint32_t v = _device.rtw_read32(kRegLaCtrl);
|
||||
r.round_up = (v >> 31) & 1;
|
||||
r.finish_addr = (v & 0x7FFF0000u) >> 16; /* unit: 8 bytes */
|
||||
|
||||
uint32_t addr; /* byte address of the oldest sample */
|
||||
uint32_t count; /* samples to read */
|
||||
const uint32_t window_samples = (buf_end - buf_start) >> 3;
|
||||
if (r.round_up) {
|
||||
addr = (r.finish_addr + 2) << 3; /* vendor: "+1 or +2 ??" */
|
||||
count = window_samples;
|
||||
} else {
|
||||
addr = buf_start;
|
||||
const uint32_t start8 = buf_start >> 3;
|
||||
count = r.finish_addr > start8 ? r.finish_addr - start8
|
||||
: start8 - r.finish_addr;
|
||||
}
|
||||
if (count > window_samples)
|
||||
count = window_samples;
|
||||
if (p.max_samples && count > p.max_samples) {
|
||||
/* Keep the NEWEST samples: the trigger event (and the frame that
|
||||
* fired it) sits at the finish end of the ring, so a cap that kept
|
||||
* the oldest end would drop exactly the content of interest. */
|
||||
uint32_t skip = count - p.max_samples;
|
||||
addr += skip * 8;
|
||||
while (addr >= buf_end)
|
||||
addr -= (buf_end - buf_start);
|
||||
count = p.max_samples;
|
||||
}
|
||||
|
||||
_logger->debug("LaCapture: readback {} samples from 0x{:05x} (finish=0x{:04x}"
|
||||
" wrap={})", count, addr, r.finish_addr, r.round_up);
|
||||
|
||||
r.samples.reserve(count);
|
||||
uint32_t page = 0xFFFFFFFFu;
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
if (addr >= buf_end)
|
||||
addr = buf_start; /* ring */
|
||||
const uint32_t pg = addr >> 12;
|
||||
if (pg != page) {
|
||||
page = pg;
|
||||
_device.rtw_write16(kRegTxffPage, static_cast<uint16_t>(0x780 + pg));
|
||||
}
|
||||
const uint16_t off = static_cast<uint16_t>(kTxffWindow + (addr & 0xfff));
|
||||
const uint32_t data_l = _device.rtw_read32(off);
|
||||
const uint32_t data_h = _device.rtw_read32(off + 4);
|
||||
r.samples.push_back((static_cast<uint64_t>(data_h) << 32) | data_l);
|
||||
addr += 8;
|
||||
}
|
||||
}
|
||||
|
||||
LaResult LaCapture::run(const LaParams &p) {
|
||||
LaResult r;
|
||||
if (_wedged) {
|
||||
r.wedged = true;
|
||||
return r;
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (p.buff_all && _regs.full_buff_capable)
|
||||
set_reg(kRegLaConf, 1u << 30, 1);
|
||||
else if (_regs.full_buff_capable)
|
||||
set_reg(kRegLaConf, 1u << 30, 0);
|
||||
|
||||
setup_trigger_time(p);
|
||||
setup_bb(p);
|
||||
setup_dbg_port(p);
|
||||
setup_mac(p);
|
||||
|
||||
if (!is_chip_alive()) {
|
||||
_wedged = true;
|
||||
r.wedged = true;
|
||||
restore();
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Post-arm register dump — the LA state the trigger sees. */
|
||||
if (_regs.dialect == LaBbDialect::Ac11)
|
||||
_logger->debug("LaCapture: armed 0x7c0=0x{:08x} 0x7cc=0x{:08x} "
|
||||
"0x95c=0x{:08x} 0x8b4=0x{:08x} 0x8fc=0x{:08x} "
|
||||
"0x8f8=0x{:08x} 0x198c=0x{:08x}",
|
||||
_device.rtw_read32(kRegLaCtrl),
|
||||
_device.rtw_read32(kRegLaConf),
|
||||
_device.rtw_read32(kAcLaEngine),
|
||||
_device.rtw_read32(kAcRptUpdate),
|
||||
_device.rtw_read32(kAcDbgPortSel),
|
||||
_device.rtw_read32(kAcDbgPortHdr),
|
||||
_device.rtw_read32(kAcDbgPortClk));
|
||||
else
|
||||
_logger->debug("LaCapture: armed 0x7c0=0x{:08x} 0x7cc=0x{:08x} "
|
||||
"0x1ce4=0x{:08x} 0x1cf4=0x{:08x} 0x1eb4=0x{:08x} "
|
||||
"0x1c3c=0x{:08x}",
|
||||
_device.rtw_read32(kRegLaCtrl),
|
||||
_device.rtw_read32(kRegLaConf),
|
||||
_device.rtw_read32(kJ3LaEngine),
|
||||
_device.rtw_read32(kJ3LaOn),
|
||||
_device.rtw_read32(kJ3RptUpdate),
|
||||
_device.rtw_read32(kJ3DbgPortSel));
|
||||
|
||||
/* The arm sequence set 0x7c0[0]=1 (+poll bit). A die without the LA
|
||||
* block reads the whole register back as zero — everything after would
|
||||
* be a false-positive read of stale TXFF content. */
|
||||
if ((_device.rtw_read32(kRegLaCtrl) & 0x3u) == 0) {
|
||||
r.no_la_block = true;
|
||||
_logger->warn("LaCapture: 0x7c0 did not latch the arm bits — no LA "
|
||||
"capture block on this die");
|
||||
restore();
|
||||
return r;
|
||||
}
|
||||
|
||||
if (poll(p)) {
|
||||
readback(p, r);
|
||||
r.ok = !r.samples.empty();
|
||||
} else {
|
||||
r.poll_timeout = true;
|
||||
_logger->warn("LaCapture: polling timeout after {} x {} ms — trigger "
|
||||
"never fired or no LA block on this die",
|
||||
p.poll_tries, p.poll_ms);
|
||||
}
|
||||
|
||||
restore();
|
||||
if (!is_chip_alive()) {
|
||||
_wedged = true;
|
||||
r.wedged = true;
|
||||
r.ok = false;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,180 @@
|
||||
/* LA-mode (phydm "logic analyzer" / ADC-sampling) IQ capture — the debug
|
||||
* escape hatch that DMAs a raw baseband sample bus into the top of the TX
|
||||
* packet buffer, host-readable through the 0x0140-page + 0x8000 window.
|
||||
* An offline FFT of a captured L-LTF is the full per-tone channel estimate
|
||||
* H(k), so this turns a dongle into a one-shot per-subcarrier channel
|
||||
* sounder (docs/la-capture.md; offline tools: tools/la_decode.py,
|
||||
* tools/la_csi.py).
|
||||
*
|
||||
* Ported from phydm_adc_sampling.c (vendored: reference/rtl88x2bu for the
|
||||
* 11AC dialect, reference/rtl88x2cu + rtl88x2eu for JGR3); the dbg-port
|
||||
* routing is phydm_debug.c (phydm_set_bb_dbg_port /
|
||||
* phydm_release_bb_dbg_port). The MAC half (trigger time, 0x7c0 capture
|
||||
* control, poll, TX-buffer readback) is identical across families; the BB
|
||||
* half has exactly two register dialects, so one implementation serves all
|
||||
* generations — LaRegs carries the per-chip parameters, mirroring
|
||||
* NhmReader's NhmRegs pattern.
|
||||
*
|
||||
* SILICON SUPPORT (PHYDM_IC_SUPPORT_LA_MODE, phydm_pre_define.h): 8814A,
|
||||
* 8822B, 8821C (cut B+ for the LA clock), 8822C, 8822E. The 8812A and
|
||||
* 8821A are NOT in the macro and have no buffer-geometry case — on those
|
||||
* dies la_regs_8812a_experimental() is a probe (expect a poll timeout).
|
||||
*
|
||||
* BRICK RISK — same class as BbDbgportReader: this pokes the BB dbg-port
|
||||
* mux (0x8fc / 0x1c3c) and LA engine registers while the demod may be
|
||||
* live. All touched registers are snapshotted at run() entry and restored
|
||||
* on every exit path, and chip liveness (SYS_CFG readable) is checked
|
||||
* after each phase; a dead read latches _wedged and the instance refuses
|
||||
* further register writes. Recovery ladder if RX stalls after a capture:
|
||||
* 1. libusb_reset_device (set DEVOURER_SKIP_RESET=0 on next launch)
|
||||
* 2. USB port-level usbreset (tests/regress.py style)
|
||||
* 3. power-cycle / replug
|
||||
* Treat first runs on a new chip as destructive until proven otherwise.
|
||||
*
|
||||
* THREADING / TX CONTRACT: single-control-thread like every control-plane
|
||||
* entry point. run() blocks for up to poll_ms*poll_tries + the readback
|
||||
* (two vendor-control reads per 8-byte sample: 16 K samples ~ tens of
|
||||
* seconds on USB2). The capture lands in the TOP of the TX packet buffer
|
||||
* (above the pages the TX path uses), but do not run a capture concurrent
|
||||
* with heavy TX — arm first, keep TX quiesced until readback completes.
|
||||
*/
|
||||
|
||||
#ifndef DEVOURER_LA_CAPTURE_H
|
||||
#define DEVOURER_LA_CAPTURE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
#include "logger.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
enum class LaBbDialect : uint8_t {
|
||||
Ac11, /* Jaguar1/2: 0x95c engine, 0x8fc dbg-port mux */
|
||||
Jgr3, /* Jaguar3: 0x1ce4/0x1cf4 engine, 0x1c3c dbg-port mux */
|
||||
};
|
||||
|
||||
/* Per-chip parameters (buffer geometry per phydm_la_set_buff_mode; HALF
|
||||
* mode window = [buf_end - size, buf_end)). */
|
||||
struct LaRegs {
|
||||
LaBbDialect dialect;
|
||||
uint32_t buf_start; /* HALF-mode window start (byte addr in TXFF) */
|
||||
uint32_t buf_end; /* window end (exclusive) */
|
||||
bool dbgport_clk; /* 11AC-2 dbg-port clock gate 0x198c[2:0] */
|
||||
bool needs_la_clk; /* 8821C cut B+: LA clock 0x95c[23] */
|
||||
bool full_buff_capable;/* 0x7cc[30] doubles the window (8821C/8822C/E) */
|
||||
uint8_t trig_time_unit_lsb; /* 0x7cc trigger-time unit field LSB: 18
|
||||
* (11AC / Jaguar2) or 16 (JGR3) */
|
||||
};
|
||||
|
||||
inline LaRegs la_regs_8814a() {
|
||||
return LaRegs{LaBbDialect::Ac11, 0x30000, 0x40000, true, false, false, 18};
|
||||
}
|
||||
inline LaRegs la_regs_8822b() {
|
||||
return LaRegs{LaBbDialect::Ac11, 0x20000, 0x40000, true, false, false, 18};
|
||||
}
|
||||
inline LaRegs la_regs_8821c() {
|
||||
/* needs_la_clk: 0x95c[23], skipped by the caller on cut A (vendor
|
||||
* phydm_la_clk_en does the same). */
|
||||
return LaRegs{LaBbDialect::Ac11, 0x8000, 0x10000, true, true, true, 18};
|
||||
}
|
||||
inline LaRegs la_regs_jgr3() { /* 8822C + 8822E */
|
||||
return LaRegs{LaBbDialect::Jgr3, 0x20000, 0x40000, false, false, true, 16};
|
||||
}
|
||||
/* Probe map for dies the vendor macro excludes (8812A/8821A): 8814A
|
||||
* geometry, no dbg-port clock gate (they are 11AC-1). A poll timeout here
|
||||
* is the expected "no LA block" answer, not a failure of the plumbing. */
|
||||
inline LaRegs la_regs_8812a_experimental() {
|
||||
return LaRegs{LaBbDialect::Ac11, 0x30000, 0x40000, false, false, false, 18};
|
||||
}
|
||||
|
||||
/* Vendor rt_adcsmp_trig_sel, minus the RF0/RF1 chain taps (reachable via
|
||||
* hdr_sel = 9/8 on 11AC if ever needed). */
|
||||
enum class LaTrigMode : uint8_t {
|
||||
BbTrig = 0, /* trigger on a BB dbg-port bit (trig_sel picks the bit) */
|
||||
AdcMacTrig = 1, /* ADC dump triggered by a MAC event (mac_sig) */
|
||||
MacDump = 4, /* pure MAC dbg-port dump (not an IQ capture) */
|
||||
};
|
||||
|
||||
enum class LaMacSig : uint8_t {
|
||||
CrcOk = 0, /* RX frame FCS pass */
|
||||
CrcFail = 1, /* RX frame FCS fail */
|
||||
Cca = 2, /* CCA assertion */
|
||||
Manual = 3, /* immediate register trigger (0x7c0[5]) */
|
||||
};
|
||||
|
||||
struct LaParams {
|
||||
LaTrigMode trig_mode = LaTrigMode::AdcMacTrig;
|
||||
LaMacSig mac_sig = LaMacSig::Manual;
|
||||
/* 0=80M 1=40M 2=20M 3=10M 4=5M 5=2.5M 6=1.25M 7=160M */
|
||||
uint8_t smp_rate = 2;
|
||||
/* 11AC 0x95c[11:8] / JGR3 0x1ce4[5:0] — selects the sampled bus. */
|
||||
uint8_t dma_type = 0;
|
||||
/* BB dbg-port mux value (11AC: full 0x8fc dword; JGR3: 0x1c3c[19:8]). */
|
||||
uint32_t dbg_port = 0;
|
||||
/* 11AC dbg-port header mux 0x8f8[25:22] (0 = ofdm_dbg[31:0]). */
|
||||
uint8_t hdr_sel = 0;
|
||||
/* BbTrig: which dbg-port bit arms the trigger. */
|
||||
uint8_t trig_sel = 0;
|
||||
uint8_t edge = 0; /* 0 = posedge, 1 = negedge */
|
||||
/* Post-trigger sampling time; the rest of the ring is pre-trigger. */
|
||||
uint32_t trigger_time_us = 100;
|
||||
bool buff_all = false; /* double the window (full_buff_capable only) */
|
||||
uint32_t poll_ms = 100;
|
||||
uint32_t poll_tries = 20;
|
||||
/* Cap readback (8-byte samples read, oldest-first); 0 = whole window. */
|
||||
uint32_t max_samples = 0;
|
||||
};
|
||||
|
||||
struct LaResult {
|
||||
bool ok = false;
|
||||
bool wedged = false;
|
||||
bool poll_timeout = false;
|
||||
/* 0x7c0 read back all-zero after arm: the LA capture block is not
|
||||
* implemented on this die (observed on 8812A — vendor's support macro
|
||||
* excludes it). Distinct from poll_timeout (block exists, no trigger). */
|
||||
bool no_la_block = false;
|
||||
bool round_up = false; /* ring wrapped (capture filled the window) */
|
||||
uint32_t finish_addr = 0; /* 0x7c0[30:16], unit 8 bytes */
|
||||
/* Time-ordered (oldest first, wrap unrolled); each entry is one 8-byte
|
||||
* LA word, (data_h << 32) | data_l — same order the vendor's
|
||||
* "%08x%08x" dump prints. Packing of I/Q inside the word is dma_type-
|
||||
* and dialect-dependent (tools/la_decode.py). */
|
||||
std::vector<uint64_t> samples;
|
||||
};
|
||||
|
||||
class LaCapture {
|
||||
public:
|
||||
LaCapture(RtlAdapter device, Logger_t logger, LaRegs regs);
|
||||
|
||||
/* Full one-shot sequence: arm → (trigger) → poll → readback → restore.
|
||||
* Safe to call repeatedly; after a wedge every call returns immediately
|
||||
* with wedged=true. */
|
||||
LaResult run(const LaParams &p);
|
||||
|
||||
bool is_wedged() const { return _wedged; }
|
||||
|
||||
private:
|
||||
void set_reg(uint16_t addr, uint32_t mask, uint32_t val);
|
||||
void setup_trigger_time(const LaParams &p);
|
||||
void setup_bb(const LaParams &p);
|
||||
void setup_dbg_port(const LaParams &p);
|
||||
void setup_mac(const LaParams &p);
|
||||
bool poll(const LaParams &p);
|
||||
void readback(const LaParams &p, LaResult &r);
|
||||
void snapshot();
|
||||
void restore();
|
||||
bool is_chip_alive();
|
||||
|
||||
RtlAdapter _device;
|
||||
Logger_t _logger;
|
||||
LaRegs _regs;
|
||||
bool _wedged = false;
|
||||
/* run()-scoped snapshot of every register the sequence touches. */
|
||||
std::vector<std::pair<uint16_t, uint32_t>> _saved;
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_LA_CAPTURE_H */
|
||||
@@ -0,0 +1,105 @@
|
||||
#include "LinkHealth.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
LinkHealthVerdict classify_link_health(const LinkHealthInput &in,
|
||||
const LinkHealthThresholds &th) {
|
||||
LinkHealthVerdict v;
|
||||
v.rssi_dbm = in.rssi_raw - 110;
|
||||
v.snr_db = in.snr_raw / 2.0;
|
||||
v.evm_db = in.evm_valid ? in.evm_raw / 2.0 : 0.0;
|
||||
if (in.igi_valid) {
|
||||
v.igi_at_floor = in.igi <= in.igi_min;
|
||||
v.igi_at_ceiling = in.igi >= in.igi_max;
|
||||
}
|
||||
|
||||
if (in.frames == 0) {
|
||||
v.verdict = LinkVerdict::NoSignal;
|
||||
v.label = "NO_SIGNAL";
|
||||
v.cause = "no frames decoded this window";
|
||||
v.fix = "check the TX is up, the channel/bandwidth matches, and the "
|
||||
"canonical SA is being sent";
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Signal-strength band and constellation cleanliness. EVM is the primary
|
||||
* discriminator (SNR misses saturation); RSSI splits strong-dirty from
|
||||
* weak-dirty. When EVM is absent (CCK-only stream), fall back to SNR. */
|
||||
const bool strong = in.rssi_raw >= th.rssi_strong;
|
||||
const bool weak = in.rssi_raw <= th.rssi_weak;
|
||||
const bool snr_poor = in.snr_raw < th.snr_lo;
|
||||
const bool snr_good = in.snr_raw >= th.snr_good;
|
||||
const bool evm_poor = in.evm_valid && in.evm_raw > th.evm_poor;
|
||||
const bool evm_good = !in.evm_valid || in.evm_raw < th.evm_good;
|
||||
const bool dirty = evm_poor || (!in.evm_valid && snr_poor);
|
||||
const bool noisy = in.energy_valid && in.fa_ofdm > th.fa_high;
|
||||
|
||||
/* Strong signal but a dirty constellation = the near-field failure the
|
||||
* classifier exists for: front-end saturation and/or the strong signal
|
||||
* self-jamming via wall reflections. IGI pinned at its floor (the AGC has
|
||||
* already backed gain all the way off and still can't cope) corroborates. */
|
||||
if (strong && dirty) {
|
||||
v.verdict = LinkVerdict::Saturated;
|
||||
v.label = "SATURATED";
|
||||
v.cause = "strong RSSI but poor EVM — receiver front-end overload and/or "
|
||||
"the strong signal self-jamming via reflections (near-field). "
|
||||
"SNR alone can look fine here";
|
||||
v.fix = "REDUCE TX power (SetTxPowerOffsetQdb, e.g. -40..-80 qdB), add an "
|
||||
"attenuator, or increase distance — do NOT add power/antenna";
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Not strong, but dirty AND the false-alarm rate is up = something other
|
||||
* than your own signal is raising the floor: external / co-channel. */
|
||||
if (!strong && dirty && noisy) {
|
||||
v.verdict = LinkVerdict::Interference;
|
||||
v.label = "INTERFERENCE";
|
||||
v.cause = "elevated false-alarm rate with a degraded constellation while "
|
||||
"the wanted signal is not strong — external / co-channel energy "
|
||||
"raising the noise floor";
|
||||
v.fix = "change channel (FastRetune / hop away from the interferer); a "
|
||||
"narrowband notch (DEVOURER_RX_NBI) only helps an in-band spur";
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Weak signal, poor SNR, AGC wide open = a genuine range/sensitivity limit. */
|
||||
if (weak && (snr_poor || !snr_good)) {
|
||||
v.verdict = LinkVerdict::Weak;
|
||||
v.label = "WEAK";
|
||||
v.cause = "low RSSI and low SNR — genuine range / sensitivity limit "
|
||||
"(this is where more power or a better antenna actually helps)";
|
||||
v.fix = "raise TX power, improve antenna gain/alignment, or reduce "
|
||||
"distance; consider a narrowband re-clock for link budget";
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Decodes cleanly with comfortable margin. */
|
||||
if (snr_good && evm_good && !strong) {
|
||||
v.verdict = LinkVerdict::Healthy;
|
||||
v.label = "HEALTHY";
|
||||
v.cause = "good SNR and EVM with RSSI in the linear range";
|
||||
v.fix = "none — link is in its comfortable operating region";
|
||||
return v;
|
||||
}
|
||||
/* A strong-but-clean link is healthy too, but flag that it is near the top
|
||||
* of the range (one step from the saturation regime on a near-field bench). */
|
||||
if (snr_good && evm_good && strong) {
|
||||
v.verdict = LinkVerdict::Healthy;
|
||||
v.label = "HEALTHY";
|
||||
v.cause = "good SNR and EVM, but RSSI is high — near the top of the linear "
|
||||
"range; a little more power or less distance risks saturation";
|
||||
v.fix = "fine as-is; leave headroom before adding TX power on a short link";
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Everything else: decoding but without a comfortable margin. */
|
||||
v.verdict = LinkVerdict::Marginal;
|
||||
v.label = "MARGINAL";
|
||||
v.cause = "decoding, but SNR/EVM is below a comfortable margin and no single "
|
||||
"cause dominates";
|
||||
v.fix = "watch the trend; if RSSI is high, try backing off power first "
|
||||
"(cheap to test), otherwise a small power/antenna improvement";
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,101 @@
|
||||
/* Link-health classifier — the "why is my link bad" interpreter.
|
||||
*
|
||||
* Devourer exposes rich RX telemetry (per-frame RSSI/SNR/EVM, frame-free
|
||||
* FA/CCA/IGI), but a user staring at raw numbers can't tell a near-field
|
||||
* saturation problem from a weak link from external interference — and the
|
||||
* instinct ("signal's bad, add power / swap the antenna") is often exactly
|
||||
* backwards. This maps the sensor tuple to a plain-language verdict + the fix.
|
||||
*
|
||||
* The load-bearing insight, measured on-air (tests/saturation_knee_sweep.sh):
|
||||
* as TX power rises on a near-field link, RSSI climbs but EVM *improves then
|
||||
* reverses* at the front-end saturation knee — SNR misses it entirely (it sat
|
||||
* flat at 18 dB across the whole sweep while EVM went from -28 dB to -13 dB).
|
||||
* So EVM is the discriminator for "strong but dirty" (overload / multipath
|
||||
* self-jam), and RSSI splits that from "weak and dirty" (noise / interference).
|
||||
*
|
||||
* Thresholds are raw devourer units, calibrated from that sweep + the AWGN
|
||||
* interference sweep (tests/j3_dig_penalty_sweep.sh):
|
||||
* RSSI raw PWDB byte, dBm ~= raw - 110; rises with power, ceilings ~73.
|
||||
* SNR signed half-dB (dB = raw/2); higher better.
|
||||
* EVM signed half-dB (dB = raw/2); LOWER (more negative) better; 0 = none.
|
||||
* FA OFDM false alarms per window; quiet ~ tens, interfered ~ hundreds.
|
||||
*/
|
||||
#ifndef DEVOURER_LINK_HEALTH_H
|
||||
#define DEVOURER_LINK_HEALTH_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
enum class LinkVerdict {
|
||||
NoSignal, /* no frames decoded this window */
|
||||
Saturated, /* strong RSSI + dirty EVM: near-field overload / self-jam */
|
||||
Interference, /* not-strong + dirty + high false-alarm: external / raised floor */
|
||||
Weak, /* low RSSI + low SNR: genuine range/sensitivity limit */
|
||||
Marginal, /* decodes, but SNR/EVM below a comfortable margin */
|
||||
Healthy, /* strong-enough RSSI, good SNR + EVM, in the linear range */
|
||||
};
|
||||
|
||||
/* Sensor snapshot over one window. Frame metrics are the path-A medians the
|
||||
* demo already aggregates; the *_valid flags let a caller pass only what it
|
||||
* has (frame-free energy and IGI are optional). Raw devourer units. */
|
||||
struct LinkHealthInput {
|
||||
uint32_t frames = 0; /* frames decoded in the window */
|
||||
/* rssi_raw is the STRENGTH signal — pass the window PEAK (rssi_max), not the
|
||||
* mean: near-field saturation trashes a fraction of frames to low apparent
|
||||
* power, dragging the mean down while the peak stays pegged near the PWDB
|
||||
* ceiling (measured: full-power near-field rssi_max ~81, backed-off ~77). */
|
||||
int rssi_raw = 0; /* path-A window peak PWDB (dBm ~= raw - 110) */
|
||||
int snr_raw = 0; /* path-A mean SNR, half-dB */
|
||||
int evm_raw = 0; /* path-A mean EVM, half-dB (lower better) */
|
||||
bool evm_valid = false;
|
||||
|
||||
bool energy_valid = false; /* fa_ofdm / cca_ofdm populated */
|
||||
uint32_t fa_ofdm = 0;
|
||||
uint32_t cca_ofdm = 0;
|
||||
|
||||
bool igi_valid = false; /* current IGI + its family rails (rail = a hint) */
|
||||
int igi = 0;
|
||||
int igi_min = 0;
|
||||
int igi_max = 0;
|
||||
};
|
||||
|
||||
struct LinkHealthVerdict {
|
||||
LinkVerdict verdict = LinkVerdict::NoSignal;
|
||||
const char *label = "NO_SIGNAL"; /* short tag for the marker line */
|
||||
const char *cause = ""; /* one-line mechanism */
|
||||
const char *fix = ""; /* one-line remedy */
|
||||
/* Converted, for display alongside the raw values. */
|
||||
int rssi_dbm = 0;
|
||||
double snr_db = 0.0;
|
||||
double evm_db = 0.0; /* 0 when evm_valid is false */
|
||||
bool igi_at_floor = false;
|
||||
bool igi_at_ceiling = false;
|
||||
};
|
||||
|
||||
/* Threshold set (raw units), exposed so a test/tool can reference the exact
|
||||
* boundaries the measurement calibrated. */
|
||||
struct LinkHealthThresholds {
|
||||
int rssi_strong = 66; /* >= this = strong signal (near-field regime) */
|
||||
int rssi_weak = 38; /* <= this = weak (~ -72 dBm) */
|
||||
/* EVM boundaries calibrated to the demo's window-aggregate (not the tight
|
||||
* sweep median): a near-field FULL-power link reads evm_mean ~ -40..-45,
|
||||
* the same geometry backed off to the EVM knee reads ~-51..-52. At strong
|
||||
* signal, EVM should be excellent (-28..-30 dB, raw -56..-60), so anything
|
||||
* worse than ~-23 dB (raw -47) at strong signal is degraded-for-its-strength
|
||||
* = the saturation / self-jam tell. */
|
||||
int evm_poor = -47; /* worse (greater) than this = dirty constellation */
|
||||
int evm_good = -49; /* better (less) than this = clean */
|
||||
int snr_lo = 16; /* < this (8 dB) = poor SNR */
|
||||
int snr_good = 30; /* >= this (15 dB) = comfortable */
|
||||
uint32_t fa_high = 300; /* OFDM FA/window above this = a noisy channel */
|
||||
};
|
||||
|
||||
/* Classify. Pure function of the snapshot + thresholds (defaulted from the
|
||||
* on-air calibration). No I/O — unit-tested in tests/link_health_selftest.cpp. */
|
||||
LinkHealthVerdict classify_link_health(const LinkHealthInput &in,
|
||||
const LinkHealthThresholds &th = {});
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_LINK_HEALTH_H */
|
||||
@@ -0,0 +1,115 @@
|
||||
#ifndef DEVOURER_NHM_READER_H
|
||||
#define DEVOURER_NHM_READER_H
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
|
||||
#include "RxSense.h"
|
||||
|
||||
/* NHM (Noise Histogram Measurement) — a frame-free, hardware in-band
|
||||
* power-distribution readout, ported from Realtek's phydm CCX
|
||||
* (phydm_ccx.c in each reference tree). The BB autonomously bins received signal
|
||||
* power into 12 IGI-referenced buckets over a measurement window; the driver
|
||||
* sets 11 thresholds, pulses a trigger, polls a ready bit, and reads back the
|
||||
* 12 one-byte bucket counters. Bucket 0 = power below threshold[0], bucket i
|
||||
* (1..10) = th[i-1]..th[i], bucket 11 = above threshold[10]. This is the richer
|
||||
* companion to the scalar FA/CCA/IGI energy sensor: a coarse spectrum-free power
|
||||
* histogram whose mass shifts up when an in-band interferer raises the floor.
|
||||
*
|
||||
* The algorithm is identical across chip generations; only the register map
|
||||
* differs (11AC: Jaguar1/2; JGR3: Jaguar3). NhmRegs carries the per-generation
|
||||
* addresses so a single implementation serves all three. */
|
||||
namespace devourer {
|
||||
|
||||
struct NhmRegs {
|
||||
uint16_t ctrl; /* [1]=trigger, [11:8]=cfg, [31:16]=th9|th10<<8 */
|
||||
uint16_t period; /* [31:16]=measurement period (4us units) */
|
||||
uint16_t th0_3; /* th[0..3], one byte each */
|
||||
uint16_t th4_7; /* th[4..7] */
|
||||
uint16_t th8; /* th[8] at th8_shift */
|
||||
uint8_t th8_shift; /* 0 (11AC, byte0) / 16 (JGR3, byte2) */
|
||||
uint16_t ready; /* [16]=ready, [15:0]=duration */
|
||||
uint16_t res0_3; /* bucket[0..3] */
|
||||
uint16_t res4_7; /* bucket[4..7] */
|
||||
uint16_t res8_11; /* bucket[8..11] */
|
||||
};
|
||||
|
||||
/* 11AC map — Jaguar1 (8812/8814/8821AU) and Jaguar2 (8822BU/8821CU). */
|
||||
inline NhmRegs nhm_regs_11ac() {
|
||||
return NhmRegs{0x994, 0x990, 0x998, 0x99c, 0x9a0, 0,
|
||||
0xfb4, 0xfa8, 0xfac, 0xfb0};
|
||||
}
|
||||
|
||||
/* JGR3 map — Jaguar3 (8822CU/8822EU). */
|
||||
inline NhmRegs nhm_regs_jgr3() {
|
||||
return NhmRegs{0x1e60, 0x1e40, 0x1e44, 0x1e48, 0x1e5c, 16,
|
||||
0x2d4c, 0x2d40, 0x2d44, 0x2d48};
|
||||
}
|
||||
|
||||
/* Run one NHM measurement and fill e.nhm[]/nhm_duration/valid_nhm.
|
||||
* read32(addr) — read a 32-bit BB register
|
||||
* set_bb(addr,mask,val) — masked BB-register write (phy_set_bb_reg)
|
||||
* igi7 — current 7-bit IGI (0xC50/0x1d70), the histogram reference
|
||||
* period — measurement window in 4us units (default 500 = ~2ms)
|
||||
* The thresholds follow phydm's NHM_BACKGROUND recipe (IGI-relative), so the
|
||||
* buckets are referenced to the receiver's own noise floor, not absolute dBm. */
|
||||
inline void read_nhm(const NhmRegs& r, uint8_t igi7,
|
||||
const std::function<uint32_t(uint16_t)>& read32,
|
||||
const std::function<void(uint16_t, uint32_t, uint32_t)>& set_bb,
|
||||
RxEnergy& e, uint16_t period = 500) {
|
||||
/* Thresholds (phydm_nhm_th_update_chk, NHM_BACKGROUND): unit PWdB U(8,1).
|
||||
* th[0] = (igi - CCA_CAP) * 2, th[i] = th[0] + 4*i for i=1..10. */
|
||||
constexpr int kCcaCap = 14;
|
||||
int base = (static_cast<int>(igi7) - kCcaCap) * 2;
|
||||
if (base < 0) base = 0;
|
||||
uint8_t th[11];
|
||||
for (int i = 0; i < 11; i++) {
|
||||
int v = base + 4 * i;
|
||||
th[i] = v > 255 ? 255 : static_cast<uint8_t>(v);
|
||||
}
|
||||
|
||||
/* Config [11:8] = (divi<<3)|(inc_tx<<2)|(inc_cca<<1)|ccx_en.
|
||||
* ccx_en=1, include_cca=1 (count busy so a CW interferer registers),
|
||||
* include_tx=0, divider=NHM_CNT_ALL(0) -> 0b0011. */
|
||||
set_bb(r.ctrl, 0xf00u, 0x3u);
|
||||
set_bb(r.period, 0xffff0000u, static_cast<uint32_t>(period));
|
||||
|
||||
set_bb(r.th0_3, 0xffffffffu,
|
||||
th[0] | (th[1] << 8) | (th[2] << 16) | (uint32_t(th[3]) << 24));
|
||||
set_bb(r.th4_7, 0xffffffffu,
|
||||
th[4] | (th[5] << 8) | (th[6] << 16) | (uint32_t(th[7]) << 24));
|
||||
set_bb(r.th8, 0xffu << r.th8_shift, uint32_t(th[8]) << r.th8_shift);
|
||||
set_bb(r.ctrl, 0xffff0000u, (th[9] | (uint32_t(th[10]) << 8)) << 16);
|
||||
|
||||
/* Trigger (pulse bit1 0->1). */
|
||||
set_bb(r.ctrl, 0x2u, 0);
|
||||
set_bb(r.ctrl, 0x2u, 1);
|
||||
|
||||
/* Poll ready (bit16). Window ~period*4us; cap the wait so a stuck read never
|
||||
* stalls the caller (holds a register lock on Jaguar3). */
|
||||
bool ready = false;
|
||||
for (int i = 0; i < 15 && !ready; i++) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
if (read32(r.ready) & (1u << 16))
|
||||
ready = true;
|
||||
}
|
||||
if (!ready) {
|
||||
e.valid_nhm = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const uint32_t a = read32(r.res0_3), b = read32(r.res4_7),
|
||||
c = read32(r.res8_11);
|
||||
const uint32_t words[3] = {a, b, c};
|
||||
for (int w = 0; w < 3; w++)
|
||||
for (int k = 0; k < 4; k++)
|
||||
e.nhm[w * 4 + k] = (words[w] >> (8 * k)) & 0xff;
|
||||
e.nhm_duration = static_cast<uint16_t>(read32(r.ready) & 0xffff);
|
||||
e.valid_nhm = true;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_NHM_READER_H */
|
||||
@@ -0,0 +1,49 @@
|
||||
/* Verbatim ports of the two phydm_math_lib helpers the active idle-noise-floor
|
||||
* measurement needs (reference/rtl8812au/hal/phydm/phydm_math_lib.c). Kept in a
|
||||
* standalone header so the per-generation noise-floor code and a selftest share
|
||||
* one copy. See docs/rx-spectrum-sensing.md.
|
||||
*
|
||||
* These drive the Jaguar1 (8812A/8821A) active-sampling path: the 0x0FA0 debug
|
||||
* port packs rx I/Q as 10-bit signed (sign_conversion), and the per-sample power
|
||||
* is 10*log10(I^2 + Q^2) approximated as 3*log2 via the leading set bit
|
||||
* (pwdb_conversion). */
|
||||
#ifndef DEVOURER_NOISE_FLOOR_MATH_H
|
||||
#define DEVOURER_NOISE_FLOOR_MATH_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
namespace nf {
|
||||
|
||||
/* odm_pwdb_conversion: Y = 10*log10(X) ~= 3*log2(X), read off the leading set
|
||||
* bit. `total_bit` bounds the bit search; `decimal_bit` is the fixed-point
|
||||
* fractional width of X. The measurement forms S(20,18) = I^2 + Q^2, so it is
|
||||
* called with (X, 20, 18). The next-lower bit adds a coarse ~2 dB decimal. */
|
||||
inline int32_t pwdb_conversion(int32_t X, uint32_t total_bit,
|
||||
uint32_t decimal_bit) {
|
||||
int32_t integer = 0, decimal = 0;
|
||||
if (X == 0)
|
||||
X = 1; /* log2(x): x can't be 0 */
|
||||
for (uint32_t i = (total_bit - 1); i > 0; i--) {
|
||||
if (X & (int32_t{1} << i)) {
|
||||
integer = static_cast<int32_t>(i);
|
||||
decimal = (X & (int32_t{1} << (i - 1))) ? 2 : 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 3 * (integer - static_cast<int32_t>(decimal_bit)) + decimal;
|
||||
}
|
||||
|
||||
/* odm_sign_conversion: interpret the low `total_bit` bits of `value` as a
|
||||
* two's-complement signed integer (rxi/rxq are 10-bit signed on the debug
|
||||
* port). */
|
||||
inline int32_t sign_conversion(int32_t value, uint32_t total_bit) {
|
||||
if (value & (int32_t{1} << (total_bit - 1)))
|
||||
value -= (int32_t{1} << total_bit);
|
||||
return value;
|
||||
}
|
||||
|
||||
} // namespace nf
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_NOISE_FLOOR_MATH_H */
|
||||
@@ -0,0 +1,682 @@
|
||||
#include "PcieTransport.h"
|
||||
|
||||
/* Linux-only (vfio). Compiled only when DEVOURER_PCIE=ON — the CMake option is
|
||||
* gated on Linux. */
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <linux/vfio.h>
|
||||
#include <poll.h>
|
||||
#include <sys/eventfd.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#include "Event.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
namespace {
|
||||
|
||||
/* ---- 88xx PCIe TRX ring register map (rtw88 pci.h, v6.12) ---- */
|
||||
constexpr uint16_t RTK_PCI_CTRL = 0x300;
|
||||
constexpr uint32_t BIT_RST_TRXDMA_INTF = 1u << 20;
|
||||
constexpr uint32_t BIT_RX_TAG_EN = 1u << 15;
|
||||
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_BCNQ = 0x308;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_H2CQ = 0x1320;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_MGMTQ = 0x310;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_BKQ = 0x330;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_BEQ = 0x328;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_VIQ = 0x320;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_VOQ = 0x318;
|
||||
constexpr uint16_t RTK_PCI_TXBD_DESA_HI0Q = 0x340;
|
||||
constexpr uint16_t RTK_PCI_RXBD_DESA_MPDUQ = 0x338;
|
||||
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_H2CQ = 0x1328;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_MGMTQ = 0x380;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_BKQ = 0x38A;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_BEQ = 0x388;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_VIQ = 0x386;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_VOQ = 0x384;
|
||||
constexpr uint16_t RTK_PCI_TXBD_NUM_HI0Q = 0x38C;
|
||||
constexpr uint16_t RTK_PCI_RXBD_NUM_MPDUQ = 0x382;
|
||||
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_H2CQ = 0x132C;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_MGMTQ = 0x3B0;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_BKQ = 0x3AC;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_BEQ = 0x3A8;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_VIQ = 0x3A4;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_VOQ = 0x3A0;
|
||||
constexpr uint16_t RTK_PCI_TXBD_IDX_HI0Q = 0x3B8;
|
||||
constexpr uint16_t RTK_PCI_RXBD_IDX_MPDUQ = 0x3B4;
|
||||
|
||||
constexpr uint16_t RTK_PCI_TXBD_RWPTR_CLR = 0x39C;
|
||||
constexpr uint16_t RTK_PCI_TXBD_H2CQ_CSR = 0x1330;
|
||||
constexpr uint32_t BIT_CLR_H2CQ_HOST_IDX = 1u << 16;
|
||||
constexpr uint32_t BIT_CLR_H2CQ_HW_IDX = 1u << 8;
|
||||
|
||||
constexpr uint16_t RTK_PCI_TXBD_BCN_WORK = 0x383;
|
||||
constexpr uint8_t BIT_PCI_BCNQ_FLAG = 1u << 4;
|
||||
|
||||
/* Interrupt registers (RX-relevant subset). */
|
||||
constexpr uint16_t RTK_PCI_HIMR0 = 0x0B0;
|
||||
constexpr uint16_t RTK_PCI_HISR0 = 0x0B4;
|
||||
constexpr uint32_t IMR_ROK = 1u << 0; /* RX DMA OK */
|
||||
constexpr uint32_t IMR_RDU = 1u << 1; /* RX descriptor unavailable */
|
||||
|
||||
constexpr uint32_t TRX_BD_IDX_MASK = 0xFFF;
|
||||
|
||||
/* 8821C (and all wcpu-11ac rtw88 chips we care about): 48-byte tx pkt desc,
|
||||
* 16-byte TX BD slot (a PAIR of 8-byte entries), 8-byte RX BD. */
|
||||
constexpr uint32_t TX_PKT_DESC_SZ = 48;
|
||||
constexpr uint32_t TX_BD_SLOT_SZ = 16;
|
||||
constexpr uint32_t RX_BD_SZ = 8;
|
||||
|
||||
constexpr uint32_t RING_LEN_DEFAULT = 128; /* RTK_DEFAULT_TX_DESC_NUM */
|
||||
constexpr uint32_t RING_LEN_BE = 256; /* RTK_BEQ_TX_DESC_NUM */
|
||||
constexpr uint32_t RING_LEN_BCN = 1;
|
||||
constexpr uint32_t TX_BOUNCE_SZ = 32 * 1024;
|
||||
|
||||
constexpr size_t PAGE_SZ = 4096;
|
||||
inline size_t page_align(size_t v) { return (v + PAGE_SZ - 1) & ~(PAGE_SZ - 1); }
|
||||
|
||||
/* 8-byte buffer-descriptor entry accessors (volatile LE stores). */
|
||||
inline void bd_write(volatile uint8_t *e, uint16_t buf_size, uint16_t psb_len,
|
||||
uint32_t dma) {
|
||||
e[0] = static_cast<uint8_t>(buf_size);
|
||||
e[1] = static_cast<uint8_t>(buf_size >> 8);
|
||||
e[2] = static_cast<uint8_t>(psb_len);
|
||||
e[3] = static_cast<uint8_t>(psb_len >> 8);
|
||||
e[4] = static_cast<uint8_t>(dma);
|
||||
e[5] = static_cast<uint8_t>(dma >> 8);
|
||||
e[6] = static_cast<uint8_t>(dma >> 16);
|
||||
e[7] = static_cast<uint8_t>(dma >> 24);
|
||||
}
|
||||
|
||||
void sleep_us(unsigned us) {
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(us));
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::shared_ptr<PcieTransport> PcieTransport::Open(const std::string &bdf,
|
||||
Logger_t logger) {
|
||||
return Open(bdf, std::move(logger), Config{});
|
||||
}
|
||||
|
||||
std::shared_ptr<PcieTransport> PcieTransport::Open(const std::string &bdf,
|
||||
Logger_t logger,
|
||||
const Config &cfg) {
|
||||
std::shared_ptr<PcieTransport> t(new PcieTransport(logger, cfg));
|
||||
t->_bdf = bdf;
|
||||
if (!t->open_vfio(bdf))
|
||||
return nullptr;
|
||||
if (!t->map_bar2())
|
||||
return nullptr;
|
||||
if (!t->setup_config_space())
|
||||
return nullptr;
|
||||
if (!t->init_dma())
|
||||
return nullptr;
|
||||
if (cfg.use_msi && !t->setup_msi())
|
||||
logger->warn("PcieTransport: MSI setup failed — RX falls back to polling");
|
||||
logger->info("PcieTransport: {} ready (BAR2 {} KiB, DMA slab {} KiB @ IOVA "
|
||||
"0x{:x}, RX {})",
|
||||
bdf, t->_mmio_len / 1024, t->_slab_len / 1024, t->_cfg.iova_base,
|
||||
t->_msi_evt >= 0 ? "MSI+eventfd" : "polled");
|
||||
return t;
|
||||
}
|
||||
|
||||
bool PcieTransport::setup_msi() {
|
||||
struct vfio_irq_info info{};
|
||||
info.argsz = sizeof(info);
|
||||
info.index = VFIO_PCI_MSI_IRQ_INDEX;
|
||||
if (ioctl(_device, VFIO_DEVICE_GET_IRQ_INFO, &info) < 0 || info.count < 1) {
|
||||
_logger->warn("PcieTransport: no MSI IRQ available");
|
||||
return false;
|
||||
}
|
||||
int evt = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
|
||||
if (evt < 0)
|
||||
return false;
|
||||
/* One MSI vector -> the eventfd. */
|
||||
char buf[sizeof(struct vfio_irq_set) + sizeof(int32_t)] = {};
|
||||
auto *is = reinterpret_cast<struct vfio_irq_set *>(buf);
|
||||
is->argsz = sizeof(buf);
|
||||
is->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
|
||||
is->index = VFIO_PCI_MSI_IRQ_INDEX;
|
||||
is->start = 0;
|
||||
is->count = 1;
|
||||
memcpy(is->data, &evt, sizeof(int32_t));
|
||||
if (ioctl(_device, VFIO_DEVICE_SET_IRQS, is) < 0) {
|
||||
_logger->warn("PcieTransport: VFIO_DEVICE_SET_IRQS(MSI) failed: {}",
|
||||
strerror(errno));
|
||||
close(evt);
|
||||
return false;
|
||||
}
|
||||
_msi_evt = evt;
|
||||
return true;
|
||||
}
|
||||
|
||||
PcieTransport::~PcieTransport() {
|
||||
if (_msi_evt >= 0) {
|
||||
if (_mmio)
|
||||
mw<uint32_t>(RTK_PCI_HIMR0, 0); /* mask before dropping the vector */
|
||||
struct vfio_irq_set off{};
|
||||
off.argsz = sizeof(off);
|
||||
off.flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER;
|
||||
off.index = VFIO_PCI_MSI_IRQ_INDEX;
|
||||
off.count = 0;
|
||||
ioctl(_device, VFIO_DEVICE_SET_IRQS, &off);
|
||||
close(_msi_evt);
|
||||
}
|
||||
if (_mmio)
|
||||
munmap(const_cast<uint8_t *>(_mmio), _mmio_len);
|
||||
if (_slab && _container >= 0) {
|
||||
struct vfio_iommu_type1_dma_unmap um{};
|
||||
um.argsz = sizeof(um);
|
||||
um.iova = _cfg.iova_base;
|
||||
um.size = _slab_len;
|
||||
ioctl(_container, VFIO_IOMMU_UNMAP_DMA, &um);
|
||||
}
|
||||
if (_slab)
|
||||
munmap(_slab, _slab_len);
|
||||
if (_device >= 0)
|
||||
close(_device);
|
||||
if (_group >= 0)
|
||||
close(_group);
|
||||
if (_container >= 0)
|
||||
close(_container);
|
||||
}
|
||||
|
||||
bool PcieTransport::open_vfio(const std::string &bdf) {
|
||||
/* IOMMU group number from sysfs. */
|
||||
std::string link = "/sys/bus/pci/devices/" + bdf + "/iommu_group";
|
||||
char buf[256];
|
||||
ssize_t n = readlink(link.c_str(), buf, sizeof(buf) - 1);
|
||||
if (n <= 0) {
|
||||
_logger->error("PcieTransport: readlink({}) failed: {}", link,
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
buf[n] = 0;
|
||||
const char *slash = strrchr(buf, '/');
|
||||
std::string group_num = slash ? slash + 1 : buf;
|
||||
|
||||
_container = open("/dev/vfio/vfio", O_RDWR);
|
||||
if (_container < 0) {
|
||||
_logger->error("PcieTransport: open /dev/vfio/vfio failed: {} (modprobe "
|
||||
"vfio-pci?)",
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
if (ioctl(_container, VFIO_GET_API_VERSION) != VFIO_API_VERSION) {
|
||||
_logger->error("PcieTransport: VFIO API version mismatch");
|
||||
return false;
|
||||
}
|
||||
int iommu_type = 0;
|
||||
if (ioctl(_container, VFIO_CHECK_EXTENSION, VFIO_TYPE1v2_IOMMU) == 1)
|
||||
iommu_type = VFIO_TYPE1v2_IOMMU;
|
||||
else if (ioctl(_container, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) == 1)
|
||||
iommu_type = VFIO_TYPE1_IOMMU;
|
||||
else {
|
||||
_logger->error("PcieTransport: no Type1 IOMMU support");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string group_path = "/dev/vfio/" + group_num;
|
||||
_group = open(group_path.c_str(), O_RDWR);
|
||||
if (_group < 0) {
|
||||
_logger->error("PcieTransport: open {} failed: {} (device bound to "
|
||||
"vfio-pci? permissions?)",
|
||||
group_path, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
struct vfio_group_status st{};
|
||||
st.argsz = sizeof(st);
|
||||
if (ioctl(_group, VFIO_GROUP_GET_STATUS, &st) < 0 ||
|
||||
!(st.flags & VFIO_GROUP_FLAGS_VIABLE)) {
|
||||
_logger->error("PcieTransport: IOMMU group {} not viable (all devices in "
|
||||
"the group must be bound to vfio-pci)",
|
||||
group_num);
|
||||
return false;
|
||||
}
|
||||
if (ioctl(_group, VFIO_GROUP_SET_CONTAINER, &_container) < 0) {
|
||||
_logger->error("PcieTransport: GROUP_SET_CONTAINER failed: {}",
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
if (ioctl(_container, VFIO_SET_IOMMU, iommu_type) < 0) {
|
||||
_logger->error("PcieTransport: SET_IOMMU failed: {}", strerror(errno));
|
||||
return false;
|
||||
}
|
||||
_device = ioctl(_group, VFIO_GROUP_GET_DEVICE_FD, bdf.c_str());
|
||||
if (_device < 0) {
|
||||
_logger->error("PcieTransport: GET_DEVICE_FD({}) failed: {}", bdf,
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
_logger->info("PcieTransport: vfio group {} opened for {}", group_num, bdf);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PcieTransport::map_bar2() {
|
||||
struct vfio_region_info reg{};
|
||||
reg.argsz = sizeof(reg);
|
||||
reg.index = VFIO_PCI_BAR2_REGION_INDEX;
|
||||
if (ioctl(_device, VFIO_DEVICE_GET_REGION_INFO, ®) < 0) {
|
||||
_logger->error("PcieTransport: BAR2 region info failed: {}",
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
if (!(reg.flags & VFIO_REGION_INFO_FLAG_MMAP) || reg.size == 0) {
|
||||
_logger->error("PcieTransport: BAR2 not mmap-able (size={} flags={:#x})",
|
||||
(unsigned long long)reg.size, reg.flags);
|
||||
return false;
|
||||
}
|
||||
void *p = mmap(nullptr, reg.size, PROT_READ | PROT_WRITE, MAP_SHARED,
|
||||
_device, reg.offset);
|
||||
if (p == MAP_FAILED) {
|
||||
_logger->error("PcieTransport: BAR2 mmap failed: {}", strerror(errno));
|
||||
return false;
|
||||
}
|
||||
_mmio = static_cast<volatile uint8_t *>(p);
|
||||
_mmio_len = reg.size;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PcieTransport::cfg_read(uint32_t off, void *buf, size_t len) {
|
||||
return pread(_device, buf, len, _cfg_region_off + off) ==
|
||||
static_cast<ssize_t>(len);
|
||||
}
|
||||
|
||||
bool PcieTransport::cfg_write(uint32_t off, const void *buf, size_t len) {
|
||||
return pwrite(_device, buf, len, _cfg_region_off + off) ==
|
||||
static_cast<ssize_t>(len);
|
||||
}
|
||||
|
||||
bool PcieTransport::setup_config_space() {
|
||||
struct vfio_region_info reg{};
|
||||
reg.argsz = sizeof(reg);
|
||||
reg.index = VFIO_PCI_CONFIG_REGION_INDEX;
|
||||
if (ioctl(_device, VFIO_DEVICE_GET_REGION_INFO, ®) < 0) {
|
||||
_logger->error("PcieTransport: config region info failed: {}",
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
_cfg_region_off = reg.offset;
|
||||
_cfg_region_len = reg.size;
|
||||
|
||||
uint16_t vid = 0, did = 0;
|
||||
cfg_read(0x00, &vid, 2);
|
||||
cfg_read(0x02, &did, 2);
|
||||
if (vid == 0xFFFF) {
|
||||
_logger->error("PcieTransport: config space reads 0xFFFF — link down?");
|
||||
return false;
|
||||
}
|
||||
_logger->info("PcieTransport: PCI device {:04x}:{:04x}", vid, did);
|
||||
|
||||
/* Memory + bus-master enable. Without bus-master every register read works
|
||||
* but no DMA moves — the classic silent-failure trap. */
|
||||
uint16_t cmd = 0;
|
||||
cfg_read(0x04, &cmd, 2);
|
||||
cmd |= 0x2 /* MEMORY */ | 0x4 /* MASTER */;
|
||||
cfg_write(0x04, &cmd, 2);
|
||||
|
||||
/* Find the PCI Express capability (id 0x10) for LNKCTL / DEVCTL2. */
|
||||
uint8_t cap_ptr = 0;
|
||||
cfg_read(0x34, &cap_ptr, 1);
|
||||
uint32_t pcie_cap = 0;
|
||||
for (int guard = 0; cap_ptr && guard < 48; guard++) {
|
||||
uint8_t id = 0, next = 0;
|
||||
cfg_read(cap_ptr, &id, 1);
|
||||
cfg_read(cap_ptr + 1, &next, 1);
|
||||
if (id == 0x10) {
|
||||
pcie_cap = cap_ptr;
|
||||
break;
|
||||
}
|
||||
cap_ptr = next;
|
||||
}
|
||||
if (pcie_cap) {
|
||||
/* Clear ASPM (LNKCTL[1:0]) during bring-up — L1 entry on a half-configured
|
||||
* link is a known hang source. */
|
||||
uint16_t lnkctl = 0;
|
||||
cfg_read(pcie_cap + 0x10, &lnkctl, 2);
|
||||
if (lnkctl & 0x3) {
|
||||
lnkctl &= ~0x3;
|
||||
cfg_write(pcie_cap + 0x10, &lnkctl, 2);
|
||||
_logger->info("PcieTransport: ASPM disabled for bring-up");
|
||||
}
|
||||
/* Disable completion timeout (DEVCTL2 bit4) — rtw88 does this specifically
|
||||
* for the 8821C (rtw_pci_phy_cfg). */
|
||||
uint16_t devctl2 = 0;
|
||||
cfg_read(pcie_cap + 0x28, &devctl2, 2);
|
||||
devctl2 |= 1u << 4;
|
||||
cfg_write(pcie_cap + 0x28, &devctl2, 2);
|
||||
} else {
|
||||
_logger->warn("PcieTransport: PCIe capability not found — skipping "
|
||||
"ASPM/completion-timeout config");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PcieTransport::init_dma() {
|
||||
/* Slab layout (page-aligned sections):
|
||||
* [0] 8 × TX BD rings (4 KiB each — BE at 256×16 = 4 KiB is the max)
|
||||
* [1] 8 × TX bounce (32 KiB each; sync TX = one in flight per queue)
|
||||
* [2] RX BD ring (rx_ring_len × 8)
|
||||
* [3] RX buffers (rx_ring_len × rx_buf_size) */
|
||||
const uint32_t rxn = _cfg.rx_ring_len;
|
||||
size_t off_txbd = 0;
|
||||
size_t off_bounce = off_txbd + Q_MAX * PAGE_SZ;
|
||||
size_t off_rxbd = off_bounce + Q_MAX * TX_BOUNCE_SZ;
|
||||
size_t off_rxbuf = off_rxbd + page_align(rxn * RX_BD_SZ);
|
||||
_slab_len = page_align(off_rxbuf + static_cast<size_t>(rxn) * _cfg.rx_buf_size);
|
||||
|
||||
void *p = mmap(nullptr, _slab_len, PROT_READ | PROT_WRITE,
|
||||
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
_logger->error("PcieTransport: DMA slab mmap({} KiB) failed: {}",
|
||||
_slab_len / 1024, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
_slab = static_cast<uint8_t *>(p);
|
||||
memset(_slab, 0, _slab_len);
|
||||
|
||||
if (_cfg.iova_base + _slab_len > (1ull << 32)) {
|
||||
_logger->error("PcieTransport: IOVA base 0x{:x} + slab exceeds 4 GiB (the "
|
||||
"descriptor dma fields are 32-bit)",
|
||||
_cfg.iova_base);
|
||||
return false;
|
||||
}
|
||||
struct vfio_iommu_type1_dma_map m{};
|
||||
m.argsz = sizeof(m);
|
||||
m.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE;
|
||||
m.vaddr = reinterpret_cast<uint64_t>(_slab);
|
||||
m.iova = _cfg.iova_base;
|
||||
m.size = _slab_len;
|
||||
if (ioctl(_container, VFIO_IOMMU_MAP_DMA, &m) < 0) {
|
||||
_logger->error("PcieTransport: VFIO_IOMMU_MAP_DMA failed: {}",
|
||||
strerror(errno));
|
||||
return false;
|
||||
}
|
||||
|
||||
auto va = [&](size_t off) { return _slab + off; };
|
||||
auto iova = [&](size_t off) { return _cfg.iova_base + off; };
|
||||
|
||||
static const struct {
|
||||
uint32_t len;
|
||||
uint16_t desa, num, idx;
|
||||
} kQ[Q_MAX] = {
|
||||
/* Q_BCN */ {RING_LEN_BCN, RTK_PCI_TXBD_DESA_BCNQ, 0, 0},
|
||||
/* Q_MGMT */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_MGMTQ, RTK_PCI_TXBD_NUM_MGMTQ,
|
||||
RTK_PCI_TXBD_IDX_MGMTQ},
|
||||
/* Q_VO */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_VOQ, RTK_PCI_TXBD_NUM_VOQ,
|
||||
RTK_PCI_TXBD_IDX_VOQ},
|
||||
/* Q_VI */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_VIQ, RTK_PCI_TXBD_NUM_VIQ,
|
||||
RTK_PCI_TXBD_IDX_VIQ},
|
||||
/* Q_BE */
|
||||
{RING_LEN_BE, RTK_PCI_TXBD_DESA_BEQ, RTK_PCI_TXBD_NUM_BEQ,
|
||||
RTK_PCI_TXBD_IDX_BEQ},
|
||||
/* Q_BK */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_BKQ, RTK_PCI_TXBD_NUM_BKQ,
|
||||
RTK_PCI_TXBD_IDX_BKQ},
|
||||
/* Q_HI0 */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_HI0Q, RTK_PCI_TXBD_NUM_HI0Q,
|
||||
RTK_PCI_TXBD_IDX_HI0Q},
|
||||
/* Q_H2C */
|
||||
{RING_LEN_DEFAULT, RTK_PCI_TXBD_DESA_H2CQ, RTK_PCI_TXBD_NUM_H2CQ,
|
||||
RTK_PCI_TXBD_IDX_H2CQ},
|
||||
};
|
||||
for (int q = 0; q < Q_MAX; q++) {
|
||||
size_t bd_off = off_txbd + static_cast<size_t>(q) * PAGE_SZ;
|
||||
size_t bo_off = off_bounce + static_cast<size_t>(q) * TX_BOUNCE_SZ;
|
||||
_tx[q].bd = va(bd_off);
|
||||
_tx[q].bd_iova = iova(bd_off);
|
||||
_tx[q].bounce = va(bo_off);
|
||||
_tx[q].bounce_iova = iova(bo_off);
|
||||
_tx[q].bounce_len = TX_BOUNCE_SZ;
|
||||
_tx[q].len = kQ[q].len;
|
||||
_tx[q].wp = 0;
|
||||
_tx[q].reg_desa = kQ[q].desa;
|
||||
_tx[q].reg_num = kQ[q].num;
|
||||
_tx[q].reg_idx = kQ[q].idx;
|
||||
}
|
||||
|
||||
_rx.bd = va(off_rxbd);
|
||||
_rx.bd_iova = iova(off_rxbd);
|
||||
_rx.bufs = va(off_rxbuf);
|
||||
_rx.bufs_iova = iova(off_rxbuf);
|
||||
_rx.len = rxn;
|
||||
_rx.rp = 0;
|
||||
for (uint32_t i = 0; i < rxn; i++)
|
||||
arm_rx_bd(i);
|
||||
return true;
|
||||
}
|
||||
|
||||
void PcieTransport::arm_rx_bd(uint32_t idx) {
|
||||
/* {buf_size, total_pkt_size = 0 (HW write-back), dma} — port of
|
||||
* rtw_pci_reset_rx_desc. */
|
||||
bd_write(_rx.bd + static_cast<size_t>(idx) * RX_BD_SZ,
|
||||
static_cast<uint16_t>(_cfg.rx_buf_size), 0,
|
||||
static_cast<uint32_t>(_rx.bufs_iova +
|
||||
static_cast<uint64_t>(idx) * _cfg.rx_buf_size));
|
||||
}
|
||||
|
||||
void PcieTransport::setup_trx_rings() {
|
||||
/* Port of rtw_pci_reset_buf_desc — EXACT order (register-level quirks:
|
||||
* 0x300+3 |= 0xf7 first, RWPTR clear + H2CQ CSR clear last), then
|
||||
* rtw_pci_dma_reset. */
|
||||
mw<uint8_t>(RTK_PCI_CTRL + 3,
|
||||
static_cast<uint8_t>(mr<uint8_t>(RTK_PCI_CTRL + 3) | 0xf7));
|
||||
|
||||
/* BCN has no NUM register ("specialized for rsvd page"). */
|
||||
mw<uint32_t>(RTK_PCI_TXBD_DESA_BCNQ, static_cast<uint32_t>(_tx[Q_BCN].bd_iova));
|
||||
|
||||
/* H2C (wcpu-11ac chips). */
|
||||
_tx[Q_H2C].wp = 0;
|
||||
mw<uint16_t>(RTK_PCI_TXBD_NUM_H2CQ,
|
||||
static_cast<uint16_t>(_tx[Q_H2C].len & TRX_BD_IDX_MASK));
|
||||
mw<uint32_t>(RTK_PCI_TXBD_DESA_H2CQ, static_cast<uint32_t>(_tx[Q_H2C].bd_iova));
|
||||
|
||||
for (int q : {Q_BK, Q_BE, Q_VO, Q_VI, Q_MGMT, Q_HI0}) {
|
||||
_tx[q].wp = 0;
|
||||
mw<uint16_t>(_tx[q].reg_num,
|
||||
static_cast<uint16_t>(_tx[q].len & TRX_BD_IDX_MASK));
|
||||
mw<uint32_t>(_tx[q].reg_desa, static_cast<uint32_t>(_tx[q].bd_iova));
|
||||
}
|
||||
|
||||
_rx.rp = 0;
|
||||
for (uint32_t i = 0; i < _rx.len; i++)
|
||||
arm_rx_bd(i);
|
||||
mw<uint16_t>(RTK_PCI_RXBD_NUM_MPDUQ,
|
||||
static_cast<uint16_t>(_rx.len & TRX_BD_IDX_MASK));
|
||||
mw<uint32_t>(RTK_PCI_RXBD_DESA_MPDUQ, static_cast<uint32_t>(_rx.bd_iova));
|
||||
|
||||
/* reset read/write pointers */
|
||||
mw<uint32_t>(RTK_PCI_TXBD_RWPTR_CLR, 0xffffffff);
|
||||
/* reset H2C queue indices in a single write (wcpu-11ac) */
|
||||
mw<uint32_t>(RTK_PCI_TXBD_H2CQ_CSR,
|
||||
mr<uint32_t>(RTK_PCI_TXBD_H2CQ_CSR) | BIT_CLR_H2CQ_HOST_IDX |
|
||||
BIT_CLR_H2CQ_HW_IDX);
|
||||
|
||||
/* rtw_pci_dma_reset */
|
||||
mw<uint32_t>(RTK_PCI_CTRL, mr<uint32_t>(RTK_PCI_CTRL) | BIT_RST_TRXDMA_INTF |
|
||||
BIT_RX_TAG_EN);
|
||||
_logger->info("PcieTransport: TRX rings programmed (RXBD {} slots @ IOVA "
|
||||
"0x{:x})",
|
||||
_rx.len, _rx.bd_iova);
|
||||
}
|
||||
|
||||
int PcieTransport::tx_sync(uint8_t ep, uint8_t *buf, size_t len,
|
||||
int timeout_ms) {
|
||||
(void)ep; /* USB addressing; the ring is chosen by descriptor QSEL */
|
||||
if (len < 48) {
|
||||
_tx_failed.fetch_add(1, std::memory_order_relaxed);
|
||||
return -1;
|
||||
}
|
||||
const uint8_t qsel = buf[5] & 0x1F;
|
||||
int queue;
|
||||
switch (qsel) {
|
||||
case 0x10: /* QSEL_BEACON — rsvd page / DLFW */
|
||||
queue = Q_BCN;
|
||||
break;
|
||||
case 0x11: /* high */
|
||||
queue = Q_HI0;
|
||||
break;
|
||||
case 0x12: /* mgmt (the monitor-inject descriptor) */
|
||||
queue = Q_MGMT;
|
||||
break;
|
||||
case 0x13: /* h2c command */
|
||||
queue = Q_H2C;
|
||||
break;
|
||||
default: /* AC data */
|
||||
queue = Q_BE;
|
||||
break;
|
||||
}
|
||||
_tx_submitted.fetch_add(1, std::memory_order_relaxed);
|
||||
int rc = tx_submit_sync(queue, buf, len, timeout_ms);
|
||||
if (rc < 0) {
|
||||
_tx_failed.fetch_add(1, std::memory_order_relaxed);
|
||||
_tx_last_rc.store(rc, std::memory_order_relaxed);
|
||||
devourer::Ev(_logger->events(), "tx.fail").f("rc", rc).f("timeout", true);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
devourer::TxStats PcieTransport::tx_stats() const {
|
||||
devourer::TxStats s;
|
||||
s.submitted = _tx_submitted.load(std::memory_order_relaxed);
|
||||
s.failed = _tx_failed.load(std::memory_order_relaxed);
|
||||
s.last_error_rc = _tx_last_rc.load(std::memory_order_relaxed);
|
||||
s.last_was_timeout = s.failed != 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
int PcieTransport::tx_submit_sync(int queue, const uint8_t *buf, size_t len,
|
||||
int timeout_ms) {
|
||||
if (queue < 0 || queue >= Q_MAX)
|
||||
return -1;
|
||||
TxRing &r = _tx[queue];
|
||||
if (len < TX_PKT_DESC_SZ || len > r.bounce_len) {
|
||||
_logger->error("PcieTransport: tx_submit_sync len {} out of range", len);
|
||||
return -1;
|
||||
}
|
||||
|
||||
memcpy(r.bounce, buf, len);
|
||||
|
||||
/* BD slot = a pair of 8-byte entries: entry0 -> the 48-byte tx desc (with
|
||||
* psb_len = total length in 128-byte units, plus OWN on the BCN queue),
|
||||
* entry1 -> the payload. Port of rtw_pci_tx_write_data. */
|
||||
uint16_t psb_len = static_cast<uint16_t>((len - 1) / 128 + 1);
|
||||
if (queue == Q_BCN)
|
||||
psb_len |= 1u << 15; /* RTK_PCI_TXBD_OWN_OFFSET */
|
||||
|
||||
volatile uint8_t *slot =
|
||||
r.bd + static_cast<size_t>(queue == Q_BCN ? 0 : r.wp) * TX_BD_SLOT_SZ;
|
||||
bd_write(slot, TX_PKT_DESC_SZ, psb_len, static_cast<uint32_t>(r.bounce_iova));
|
||||
bd_write(slot + RX_BD_SZ, static_cast<uint16_t>(len - TX_PKT_DESC_SZ), 0,
|
||||
static_cast<uint32_t>(r.bounce_iova + TX_PKT_DESC_SZ));
|
||||
|
||||
std::atomic_thread_fence(std::memory_order_seq_cst);
|
||||
|
||||
if (queue == Q_BCN) {
|
||||
/* Kick the beacon queue; completion is the caller-polled bcn-valid latch
|
||||
* (REG_FIFOPAGE_CTRL_2+1 bit7), same as the USB rsvd-page contract. */
|
||||
mw<uint8_t>(RTK_PCI_TXBD_BCN_WORK,
|
||||
static_cast<uint8_t>(mr<uint8_t>(RTK_PCI_TXBD_BCN_WORK) |
|
||||
BIT_PCI_BCNQ_FLAG));
|
||||
return static_cast<int>(len);
|
||||
}
|
||||
|
||||
r.wp = (r.wp + 1) % r.len;
|
||||
mw<uint16_t>(r.reg_idx, static_cast<uint16_t>(r.wp & TRX_BD_IDX_MASK));
|
||||
|
||||
/* Sync semantics: wait for the hardware read pointer to consume the slot. */
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::milliseconds(timeout_ms > 0 ? timeout_ms : 20);
|
||||
for (;;) {
|
||||
uint32_t idx = mr<uint32_t>(r.reg_idx);
|
||||
uint32_t hw_rp = (idx >> 16) & TRX_BD_IDX_MASK;
|
||||
if (hw_rp == r.wp)
|
||||
return static_cast<int>(len);
|
||||
if (std::chrono::steady_clock::now() > deadline) {
|
||||
_logger->error("PcieTransport: TX q{} completion timeout (wp={} hw_rp={})",
|
||||
queue, r.wp, hw_rp);
|
||||
return -1;
|
||||
}
|
||||
sleep_us(20);
|
||||
}
|
||||
}
|
||||
|
||||
void PcieTransport::rx_poll_loop(
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop) {
|
||||
const bool msi = _msi_evt >= 0;
|
||||
_logger->info("PcieTransport: RX loop started ({})",
|
||||
msi ? "MSI+eventfd, 100 ms safety timeout"
|
||||
: "polled");
|
||||
if (msi) {
|
||||
/* Clear any latched status, then unmask RX-OK + ring-underrun. */
|
||||
mw<uint32_t>(RTK_PCI_HISR0, mr<uint32_t>(RTK_PCI_HISR0));
|
||||
mw<uint32_t>(RTK_PCI_HIMR0, IMR_ROK | IMR_RDU);
|
||||
}
|
||||
uint64_t reaped = 0;
|
||||
while (!should_stop()) {
|
||||
uint32_t v = mr<uint32_t>(RTK_PCI_RXBD_IDX_MPDUQ);
|
||||
uint32_t hw_wp = (v >> 16) & TRX_BD_IDX_MASK;
|
||||
if (hw_wp == _rx.rp) {
|
||||
if (msi) {
|
||||
/* Wait for the MSI edge. 100 ms timeout = safety net against a lost
|
||||
* edge (the ring index re-check above makes a spurious/late wake
|
||||
* harmless); always drain the eventfd counter and W1C the HISR so the
|
||||
* next frame generates a fresh edge. */
|
||||
struct pollfd pfd {_msi_evt, POLLIN, 0};
|
||||
(void)::poll(&pfd, 1, 100);
|
||||
uint64_t cnt;
|
||||
while (read(_msi_evt, &cnt, sizeof(cnt)) == sizeof(cnt)) {
|
||||
}
|
||||
mw<uint32_t>(RTK_PCI_HISR0, mr<uint32_t>(RTK_PCI_HISR0));
|
||||
continue;
|
||||
}
|
||||
sleep_us(static_cast<unsigned>(_cfg.rx_poll_us));
|
||||
continue;
|
||||
}
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
while (_rx.rp != hw_wp && !should_stop()) {
|
||||
const uint8_t *buf = _rx.bufs + static_cast<size_t>(_rx.rp) * _cfg.rx_buf_size;
|
||||
/* Exactly one MPDU per RX BD on PCIe (no USB aggregation): usable length
|
||||
* = 24-byte rx desc + drvinfo + shift + pkt_len, computed from the
|
||||
* descriptor itself (the BD's total_pkt_size write-back carries the DMA
|
||||
* tag when RX_TAG_EN is set, not a length). */
|
||||
uint32_t d0 = static_cast<uint32_t>(buf[0]) | (buf[1] << 8) |
|
||||
(buf[2] << 16) | (static_cast<uint32_t>(buf[3]) << 24);
|
||||
uint32_t pkt_len = d0 & 0x3FFF;
|
||||
uint32_t drvinfo = ((d0 >> 16) & 0xF) * 8;
|
||||
uint32_t shift = (d0 >> 24) & 0x3;
|
||||
uint32_t used = 24 + drvinfo + shift + pkt_len;
|
||||
if (pkt_len != 0 && used <= _cfg.rx_buf_size)
|
||||
on_data(buf, static_cast<int>(used));
|
||||
|
||||
arm_rx_bd(_rx.rp); /* return the slot to hardware */
|
||||
_rx.rp = (_rx.rp + 1) % _rx.len;
|
||||
++reaped;
|
||||
std::atomic_thread_fence(std::memory_order_release);
|
||||
mw<uint16_t>(RTK_PCI_RXBD_IDX_MPDUQ,
|
||||
static_cast<uint16_t>(_rx.rp & TRX_BD_IDX_MASK));
|
||||
}
|
||||
}
|
||||
if (msi)
|
||||
mw<uint32_t>(RTK_PCI_HIMR0, 0); /* re-mask on exit */
|
||||
_logger->info("PcieTransport: RX loop exited ({} BDs reaped)", reaped);
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,233 @@
|
||||
#pragma once
|
||||
|
||||
/* PcieTransport — vfio-pci userspace transport for the PCIe RTL88xx variants
|
||||
* (first target: RTL8821CE, the PCIe sibling of the RTL8821CU).
|
||||
*
|
||||
* The caller owns vfio, mirroring the USB doctrine ("the caller owns libusb"):
|
||||
* PcieTransport::Open(bdf) is the recommended open path — it walks
|
||||
* /sys/bus/pci/devices/<bdf>/iommu_group, opens the vfio container + group,
|
||||
* maps BAR2 (the 64 KiB MMIO window exposing the same 0x0000..0xFFFF register
|
||||
* space the USB vendor-control path addresses), enables PCI bus mastering, and
|
||||
* DMA-maps one anonymous slab for the TX/RX buffer-descriptor rings + RX
|
||||
* buffers. The device must already be bound to vfio-pci
|
||||
* (tests/pcie_vfio_bind.sh).
|
||||
*
|
||||
* Registers: plain volatile loads/stores on the BAR2 mapping (rtw88 pci.c maps
|
||||
* bar_id=2 and uses readb/w/l at the register address).
|
||||
*
|
||||
* TRX: the 88xx PCIe buffer-descriptor rings, ported from rtw88 pci.{c,h}
|
||||
* (v6.12) — 8-byte BD entries, 16-byte TX BD slots (entry0 = 48-byte tx desc,
|
||||
* entry1 = payload), ring base/num/idx registers at 0x300..0x3B8 + the H2C
|
||||
* ring at 0x1320. RX completion is detected by polling the hardware write
|
||||
* index in RTK_PCI_RXBD_IDX_MPDUQ (0x3B4) — no interrupts (MSI/eventfd is a
|
||||
* later optimization; monitor-mode RX at beacon rates is comfortably within a
|
||||
* sub-millisecond poll).
|
||||
*
|
||||
* All descriptor `dma` fields and the DESA registers are 32-bit, so the slab
|
||||
* is mapped at a fixed IOVA below 4 GiB (VT-d lets us choose). x86 is
|
||||
* DMA-coherent — no cache sync beyond compiler ordering (volatile BD access +
|
||||
* the strongly-ordered MMIO doorbell write). */
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "Transport.h"
|
||||
#include "logger.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class PcieTransport final : public ITransport {
|
||||
public:
|
||||
/* TX queues, indexing _tx_rings. Order is fixed (ring register map). */
|
||||
enum Queue : int {
|
||||
Q_BCN = 0, /* beacon / reserved-page (the DLFW path) */
|
||||
Q_MGMT,
|
||||
Q_VO,
|
||||
Q_VI,
|
||||
Q_BE,
|
||||
Q_BK,
|
||||
Q_HI0,
|
||||
Q_H2C,
|
||||
Q_MAX
|
||||
};
|
||||
|
||||
struct Config {
|
||||
uint32_t rx_ring_len = 512; /* RTK_MAX_RX_DESC_NUM */
|
||||
uint32_t rx_buf_size = 11480; /* RTK_PCI_RX_BUF_SIZE (11478) 8-aligned */
|
||||
uint64_t iova_base = 0x10000000; /* slab IOVA; must stay < 4 GiB */
|
||||
int rx_poll_us = 200; /* RX hw-index poll interval */
|
||||
/* MSI-via-eventfd RX wakeups (VFIO_DEVICE_SET_IRQS). The reap logic is
|
||||
* identical; MSI only replaces the fixed-interval sleep with an eventfd
|
||||
* wait (100 ms safety timeout keeps a lost edge from ever stalling RX).
|
||||
* Falls back to pure polling automatically when MSI setup fails. */
|
||||
bool use_msi = true;
|
||||
};
|
||||
|
||||
/* Open the vfio-pci device at `bdf` ("0000:01:00.0"). Returns null and logs
|
||||
* on any failure (group not viable, BAR2 map failed, DMA map failed...).
|
||||
* Bus mastering + ASPM-off + completion-timeout-disable are applied here.
|
||||
* (Two overloads instead of a defaulted Config arg: a nested class with
|
||||
* default member initializers cannot be a default argument inside its own
|
||||
* enclosing class.) */
|
||||
static std::shared_ptr<PcieTransport> Open(const std::string &bdf,
|
||||
Logger_t logger,
|
||||
const Config &cfg);
|
||||
static std::shared_ptr<PcieTransport> Open(const std::string &bdf,
|
||||
Logger_t logger);
|
||||
~PcieTransport() override;
|
||||
PcieTransport(const PcieTransport &) = delete;
|
||||
PcieTransport &operator=(const PcieTransport &) = delete;
|
||||
|
||||
/* ---- ITransport: register plane (BAR2 MMIO) ---- */
|
||||
bool is_usb() const override { return false; }
|
||||
uint8_t read8(uint16_t reg) override { return guarded_read<uint8_t>(reg); }
|
||||
uint16_t read16(uint16_t reg) override { return guarded_read<uint16_t>(reg); }
|
||||
uint32_t read32(uint16_t reg) override { return guarded_read<uint32_t>(reg); }
|
||||
bool write8(uint16_t reg, uint8_t v) override { return guarded_write(reg, v); }
|
||||
bool write16(uint16_t reg, uint16_t v) override { return guarded_write(reg, v); }
|
||||
bool write32(uint16_t reg, uint32_t v) override { return guarded_write(reg, v); }
|
||||
bool write_bytes(uint16_t reg, const uint8_t *p, size_t n) override {
|
||||
/* MMIO burst: plain byte stores (the multi-byte users of this path — MAC
|
||||
* address / key material — have no width side-effects). */
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (!guarded_write<uint8_t>(reg + static_cast<uint16_t>(i), p[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ---- ITransport: frame plane (88xx BD rings) ---- */
|
||||
/* The ring is chosen from the tx-descriptor QSEL at buf[5] bits [4:0]
|
||||
* (identical position on every 88xx descriptor this library builds); the
|
||||
* `ep` hint is USB addressing and ignored. QSEL_BEACON -> BCN ring is the
|
||||
* DLFW rsvd-page path, exactly rtw88's write_data_rsvd_page ->
|
||||
* RTW_TX_QUEUE_BCN mapping. */
|
||||
bool tx_async(uint8_t ep, uint8_t *buf, size_t len,
|
||||
unsigned timeout_ms) override {
|
||||
return tx_sync(ep, buf, len, static_cast<int>(timeout_ms)) >= 0;
|
||||
}
|
||||
int tx_sync(uint8_t ep, uint8_t *buf, size_t len, int timeout_ms) override;
|
||||
void rx_loop(int buf_size, int n_xfers,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop) override {
|
||||
(void)buf_size; /* USB URB tuning; the ring depth is fixed at creation */
|
||||
(void)n_xfers;
|
||||
rx_poll_loop(on_data, should_stop);
|
||||
}
|
||||
void hci_setup() override { setup_trx_rings(); }
|
||||
TxStats tx_stats() const override;
|
||||
|
||||
volatile uint8_t *mmio() const { return _mmio; }
|
||||
size_t mmio_len() const { return _mmio_len; }
|
||||
|
||||
/* ---- PCI config space (via the vfio config region) ---- */
|
||||
bool cfg_read(uint32_t off, void *buf, size_t len);
|
||||
bool cfg_write(uint32_t off, const void *buf, size_t len);
|
||||
|
||||
/* ---- TRX rings ---- */
|
||||
/* Program the ring base/num/idx registers — port of rtw_pci_reset_buf_desc
|
||||
* + rtw_pci_dma_reset (exact order). Call per bring-up attempt, BEFORE the
|
||||
* power-on sequence (rtw88: rtw_hci_setup precedes rtw_mac_power_on). */
|
||||
void setup_trx_rings();
|
||||
|
||||
/* Synchronous TX submit on `queue`: copy into the queue's bounce buffer,
|
||||
* fill the BD slot, kick the doorbell. Non-BCN queues wait for the hardware
|
||||
* read pointer to consume the slot (timeout_ms); the BCN queue returns after
|
||||
* the kick — its completion signal is the caller-polled bcn-valid latch
|
||||
* (same contract as the USB DLFW path). Returns bytes submitted or <0. */
|
||||
int tx_submit_sync(int queue, const uint8_t *buf, size_t len, int timeout_ms);
|
||||
|
||||
/* Poll-driven RX reap loop: read the hw write index at 0x3B4, hand each
|
||||
* ready MPDU buffer (rx desc + drvinfo + PSDU — NO USB-style aggregation,
|
||||
* exactly one MPDU per BD) to on_data, re-arm the BD, advance the host
|
||||
* index. Runs until should_stop(). */
|
||||
void rx_poll_loop(const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop);
|
||||
|
||||
const Config &config() const { return _cfg; }
|
||||
const std::string &bdf() const { return _bdf; }
|
||||
|
||||
private:
|
||||
PcieTransport(Logger_t logger, Config cfg) : _logger(std::move(logger)), _cfg(cfg) {}
|
||||
|
||||
bool open_vfio(const std::string &bdf);
|
||||
bool map_bar2();
|
||||
bool setup_config_space();
|
||||
bool init_dma();
|
||||
bool setup_msi();
|
||||
|
||||
template <typename T> T mr(uint16_t reg) {
|
||||
return *reinterpret_cast<volatile T *>(_mmio + reg);
|
||||
}
|
||||
template <typename T> void mw(uint16_t reg, T v) {
|
||||
*reinterpret_cast<volatile T *>(_mmio + reg) = v;
|
||||
}
|
||||
|
||||
/* Register access with the USB-page guard: 0xFE00..0xFEFF is USB-only
|
||||
* register space — undefined over MMIO. The jaguar users (0xFE5B/0xFE10/
|
||||
* 0xFE11) are is_usb()-gated; catch any stragglers instead of poking a
|
||||
* hole in the BAR. */
|
||||
template <typename T> T guarded_read(uint16_t reg) {
|
||||
if (reg >= 0xFE00) {
|
||||
_logger->warn("read(0x{:04x}) on PCIe: USB-page register, returning 0",
|
||||
reg);
|
||||
return 0;
|
||||
}
|
||||
return mr<T>(reg);
|
||||
}
|
||||
template <typename T> bool guarded_write(uint16_t reg, T v) {
|
||||
if (reg >= 0xFE00) {
|
||||
_logger->warn("write(0x{:04x}) on PCIe: USB-page register, dropped", reg);
|
||||
return false;
|
||||
}
|
||||
mw<T>(reg, v);
|
||||
return true;
|
||||
}
|
||||
|
||||
struct TxRing {
|
||||
volatile uint8_t *bd = nullptr; /* BD slots (16 B each) in the DMA slab */
|
||||
uint64_t bd_iova = 0;
|
||||
uint8_t *bounce = nullptr; /* one in-flight frame per queue (sync TX) */
|
||||
uint64_t bounce_iova = 0;
|
||||
uint32_t bounce_len = 0;
|
||||
uint32_t len = 0; /* slots */
|
||||
uint32_t wp = 0;
|
||||
uint16_t reg_desa = 0, reg_num = 0, reg_idx = 0;
|
||||
};
|
||||
struct RxRing {
|
||||
volatile uint8_t *bd = nullptr; /* 8-byte BDs */
|
||||
uint64_t bd_iova = 0;
|
||||
uint8_t *bufs = nullptr; /* rx_ring_len × rx_buf_size */
|
||||
uint64_t bufs_iova = 0;
|
||||
uint32_t len = 0;
|
||||
uint32_t rp = 0;
|
||||
};
|
||||
|
||||
void arm_rx_bd(uint32_t idx);
|
||||
|
||||
Logger_t _logger;
|
||||
Config _cfg;
|
||||
std::string _bdf;
|
||||
|
||||
int _container = -1, _group = -1, _device = -1;
|
||||
int _msi_evt = -1; /* eventfd signalled per MSI; -1 = polling mode */
|
||||
volatile uint8_t *_mmio = nullptr;
|
||||
size_t _mmio_len = 0;
|
||||
uint64_t _cfg_region_off = 0;
|
||||
size_t _cfg_region_len = 0;
|
||||
|
||||
uint8_t *_slab = nullptr; /* DMA slab VA (anonymous, VFIO-pinned) */
|
||||
size_t _slab_len = 0;
|
||||
|
||||
/* TX submission counters (TxStats.h contract, like the USB transport). */
|
||||
std::atomic<uint64_t> _tx_submitted{0};
|
||||
std::atomic<uint64_t> _tx_failed{0};
|
||||
std::atomic<int> _tx_last_rc{0};
|
||||
|
||||
TxRing _tx[Q_MAX];
|
||||
RxRing _rx;
|
||||
};
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,105 @@
|
||||
#include "PhyTableLoader.h"
|
||||
|
||||
namespace {
|
||||
|
||||
/* Opcode encoding (high nibble of v1):
|
||||
* 0x8 — IF (c_cond bits 28-29 = 0b00)
|
||||
* 0x9 — ELSE_IF (c_cond bits 28-29 = 0b01)
|
||||
* 0xA — ELSE (c_cond bits 28-29 = 0b10)
|
||||
* 0xB — ENDIF (c_cond bits 28-29 = 0b11)
|
||||
* 0x4 — negative condition (second half of IF/ELSE_IF; carries c3/c4) */
|
||||
constexpr uint32_t BIT_POSITIVE = 1u << 31;
|
||||
constexpr uint32_t BIT_NEGATIVE = 1u << 30;
|
||||
constexpr uint32_t C_COND_MASK = (1u << 29) | (1u << 28);
|
||||
constexpr uint32_t C_COND_SHIFT = 28;
|
||||
|
||||
constexpr uint8_t COND_IF = 0;
|
||||
constexpr uint8_t COND_ELSE_IF = 1;
|
||||
constexpr uint8_t COND_ELSE = 2;
|
||||
constexpr uint8_t COND_ENDIF = 3;
|
||||
|
||||
constexpr uint8_t ODM_CUT_A = 0; /* matches upstream phydm */
|
||||
|
||||
} // namespace
|
||||
|
||||
/* Translated verbatim from check_positive() in upstream
|
||||
* hal/phydm/rtl8814a/halhwimg8814a_bb.c. Returns true if the runtime
|
||||
* configuration in `ctx` matches the (cond1..cond4) selector. */
|
||||
bool PhyTableLoader::CheckPositive(const JaguarPhyContext& ctx, uint32_t c1,
|
||||
uint32_t /*c2*/, uint32_t /*c3*/,
|
||||
uint32_t /*c4*/) {
|
||||
const uint8_t cut_for_para =
|
||||
(ctx.cut_version == ODM_CUT_A) ? 15 : ctx.cut_version;
|
||||
const uint8_t pkg_for_para = (ctx.package_type == 0) ? 15 : ctx.package_type;
|
||||
|
||||
const uint32_t driver1 =
|
||||
(static_cast<uint32_t>(cut_for_para) << 24) |
|
||||
((ctx.support_interface & 0xF0u) << 16) |
|
||||
(static_cast<uint32_t>(ctx.support_platform) << 16) |
|
||||
(static_cast<uint32_t>(pkg_for_para) << 12) |
|
||||
((ctx.support_interface & 0x0Fu) << 8) |
|
||||
static_cast<uint32_t>(ctx.rfe_type);
|
||||
|
||||
/* cut version [27:24] */
|
||||
if ((c1 & 0x0F000000u) != 0 && (c1 & 0x0F000000u) != (driver1 & 0x0F000000u))
|
||||
return false;
|
||||
/* pkg type [15:12] */
|
||||
if ((c1 & 0x0000F000u) != 0 && (c1 & 0x0000F000u) != (driver1 & 0x0000F000u))
|
||||
return false;
|
||||
/* interface [11:8] */
|
||||
if ((c1 & 0x00000F00u) != 0 && (c1 & 0x00000F00u) != (driver1 & 0x00000F00u))
|
||||
return false;
|
||||
|
||||
/* Low byte (rfe_type) — exact match required when both sides are nonzero. */
|
||||
return (c1 & 0xFFu) == (driver1 & 0xFFu);
|
||||
}
|
||||
|
||||
/* Walks the phydm table state machine. Mirrors odm_read_and_config_mp_8814a_*
|
||||
* in upstream. */
|
||||
void PhyTableLoader::Load(const uint32_t* table, std::size_t len,
|
||||
const JaguarPhyContext& ctx, const Writer& write) {
|
||||
bool is_matched = true;
|
||||
bool is_skipped = false;
|
||||
uint32_t pre_v1 = 0;
|
||||
uint32_t pre_v2 = 0;
|
||||
|
||||
std::size_t i = 0;
|
||||
while (i + 1 < len) {
|
||||
const uint32_t v1 = table[i];
|
||||
const uint32_t v2 = table[i + 1];
|
||||
|
||||
if (v1 & (BIT_POSITIVE | BIT_NEGATIVE)) {
|
||||
if (v1 & BIT_POSITIVE) {
|
||||
const uint8_t c_cond =
|
||||
static_cast<uint8_t>((v1 & C_COND_MASK) >> C_COND_SHIFT);
|
||||
if (c_cond == COND_ENDIF) {
|
||||
is_matched = true;
|
||||
is_skipped = false;
|
||||
} else if (c_cond == COND_ELSE) {
|
||||
is_matched = is_skipped ? false : true;
|
||||
} else {
|
||||
/* IF / ELSE_IF — save the positive half; the negative half on the
|
||||
* next iteration completes the condition group. */
|
||||
pre_v1 = v1;
|
||||
pre_v2 = v2;
|
||||
}
|
||||
} else if (v1 & BIT_NEGATIVE) {
|
||||
if (!is_skipped) {
|
||||
if (CheckPositive(ctx, pre_v1, pre_v2, v1, v2)) {
|
||||
is_matched = true;
|
||||
is_skipped = true;
|
||||
} else {
|
||||
is_matched = false;
|
||||
is_skipped = false;
|
||||
}
|
||||
} else {
|
||||
is_matched = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (is_matched)
|
||||
write(v1, v2);
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#ifndef PHY_TABLE_LOADER_H
|
||||
#define PHY_TABLE_LOADER_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
|
||||
/* Loader for the Realtek phydm-style register tables shipped with RTL8814AU
|
||||
* (BB / AGC / MAC). The on-disk format encodes runtime-conditional blocks via
|
||||
* opcode words in the high nibble; see hal/phydm/rtl8814a/halhwimg8814a_bb.c
|
||||
* for the canonical encoding upstream. This loader replicates upstream's
|
||||
* `check_positive` + state-machine walk without pulling in the phydm
|
||||
* subsystem — `JaguarPhyContext` is the minimal subset of `dm_struct` that
|
||||
* `check_positive` reads. */
|
||||
|
||||
struct JaguarPhyContext {
|
||||
uint8_t cut_version; /* HAL_CUT_VERSION_E from EepromManager */
|
||||
uint8_t support_interface; /* ODM_ITRF_USB == 0x02 in upstream phydm */
|
||||
uint8_t support_platform; /* ODM_CE == 0x04 in upstream phydm */
|
||||
uint8_t package_type; /* 0 unless EFUSE-overridden */
|
||||
uint8_t rfe_type; /* EFUSE rfe_type */
|
||||
uint16_t type_glna;
|
||||
uint16_t type_gpa;
|
||||
uint16_t type_alna;
|
||||
uint16_t type_apa;
|
||||
};
|
||||
|
||||
class PhyTableLoader {
|
||||
public:
|
||||
/* Writer is invoked once per (addr, value) entry that passes the conditional
|
||||
* filter. For BB/AGC tables, write is a full 32-bit register write; for the
|
||||
* MAC table the value's low byte holds the byte-wide write — the caller
|
||||
* decides via the writer it supplies. */
|
||||
using Writer = std::function<void(uint32_t addr, uint32_t value)>;
|
||||
|
||||
static void Load(const uint32_t* table, std::size_t len,
|
||||
const JaguarPhyContext& ctx, const Writer& write);
|
||||
|
||||
private:
|
||||
static bool CheckPositive(const JaguarPhyContext& ctx, uint32_t c1, uint32_t c2,
|
||||
uint32_t c3, uint32_t c4);
|
||||
};
|
||||
|
||||
#endif /* PHY_TABLE_LOADER_H */
|
||||
@@ -0,0 +1,639 @@
|
||||
/*
|
||||
* Radiotap parser
|
||||
*
|
||||
* Copyright 2007 Andy Green <andy@warmcat.com>
|
||||
* Copyright 2009 Johannes Berg <johannes@sipsolutions.net>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License version 2 as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* Alternatively, this software may be distributed under the terms of BSD
|
||||
* license.
|
||||
*
|
||||
* See COPYING for more details.
|
||||
*/
|
||||
|
||||
#include "ieee80211_radiotap.h"
|
||||
#include <stdio.h>
|
||||
#include <stddef.h> /* for size_t */
|
||||
#include <stdint.h> /* for uint8_t, uint16_t, etc. */
|
||||
|
||||
/* if not defined already */
|
||||
#ifndef ARRAY_SIZE
|
||||
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
|
||||
#endif
|
||||
|
||||
/* Make sure your type definitions for u8, u16 etc are available.
|
||||
For example:
|
||||
typedef uint8_t u8;
|
||||
typedef uint16_t u16;
|
||||
*/
|
||||
|
||||
enum MGN_RATE {
|
||||
MGN_1M = 0x02,
|
||||
MGN_2M = 0x04,
|
||||
MGN_5_5M = 0x0B,
|
||||
MGN_6M = 0x0C,
|
||||
MGN_9M = 0x12,
|
||||
MGN_11M = 0x16,
|
||||
MGN_12M = 0x18,
|
||||
MGN_18M = 0x24,
|
||||
MGN_24M = 0x30,
|
||||
MGN_36M = 0x48,
|
||||
MGN_48M = 0x60,
|
||||
MGN_54M = 0x6C,
|
||||
MGN_MCS32 = 0x7F,
|
||||
MGN_MCS0,
|
||||
MGN_MCS1,
|
||||
MGN_MCS2,
|
||||
MGN_MCS3,
|
||||
MGN_MCS4,
|
||||
MGN_MCS5,
|
||||
MGN_MCS6,
|
||||
MGN_MCS7,
|
||||
MGN_MCS8,
|
||||
MGN_MCS9,
|
||||
MGN_MCS10,
|
||||
MGN_MCS11,
|
||||
MGN_MCS12,
|
||||
MGN_MCS13,
|
||||
MGN_MCS14,
|
||||
MGN_MCS15,
|
||||
MGN_MCS16,
|
||||
MGN_MCS17,
|
||||
MGN_MCS18,
|
||||
MGN_MCS19,
|
||||
MGN_MCS20,
|
||||
MGN_MCS21,
|
||||
MGN_MCS22,
|
||||
MGN_MCS23,
|
||||
MGN_MCS24,
|
||||
MGN_MCS25,
|
||||
MGN_MCS26,
|
||||
MGN_MCS27,
|
||||
MGN_MCS28,
|
||||
MGN_MCS29,
|
||||
MGN_MCS30,
|
||||
MGN_MCS31,
|
||||
MGN_VHT1SS_MCS0,
|
||||
MGN_VHT1SS_MCS1,
|
||||
MGN_VHT1SS_MCS2,
|
||||
MGN_VHT1SS_MCS3,
|
||||
MGN_VHT1SS_MCS4,
|
||||
MGN_VHT1SS_MCS5,
|
||||
MGN_VHT1SS_MCS6,
|
||||
MGN_VHT1SS_MCS7,
|
||||
MGN_VHT1SS_MCS8,
|
||||
MGN_VHT1SS_MCS9,
|
||||
MGN_VHT2SS_MCS0,
|
||||
MGN_VHT2SS_MCS1,
|
||||
MGN_VHT2SS_MCS2,
|
||||
MGN_VHT2SS_MCS3,
|
||||
MGN_VHT2SS_MCS4,
|
||||
MGN_VHT2SS_MCS5,
|
||||
MGN_VHT2SS_MCS6,
|
||||
MGN_VHT2SS_MCS7,
|
||||
MGN_VHT2SS_MCS8,
|
||||
MGN_VHT2SS_MCS9,
|
||||
MGN_VHT3SS_MCS0,
|
||||
MGN_VHT3SS_MCS1,
|
||||
MGN_VHT3SS_MCS2,
|
||||
MGN_VHT3SS_MCS3,
|
||||
MGN_VHT3SS_MCS4,
|
||||
MGN_VHT3SS_MCS5,
|
||||
MGN_VHT3SS_MCS6,
|
||||
MGN_VHT3SS_MCS7,
|
||||
MGN_VHT3SS_MCS8,
|
||||
MGN_VHT3SS_MCS9,
|
||||
MGN_VHT4SS_MCS0,
|
||||
MGN_VHT4SS_MCS1,
|
||||
MGN_VHT4SS_MCS2,
|
||||
MGN_VHT4SS_MCS3,
|
||||
MGN_VHT4SS_MCS4,
|
||||
MGN_VHT4SS_MCS5,
|
||||
MGN_VHT4SS_MCS6,
|
||||
MGN_VHT4SS_MCS7,
|
||||
MGN_VHT4SS_MCS8,
|
||||
MGN_VHT4SS_MCS9,
|
||||
MGN_UNKNOWN
|
||||
};
|
||||
|
||||
/*
|
||||
* In order to support MSVC (which doesn’t support C99 designated
|
||||
* initializers), we replace the “[index] = { .align = …, .size = … }”
|
||||
* syntax with positional initializers. Note that the array is defined
|
||||
* to have 23 entries (0..22) corresponding to indices used in the enum.
|
||||
* Entries for undefined indices (e.g. 18) are set to {0,0}.
|
||||
*/
|
||||
|
||||
static const struct radiotap_align_size rtap_namespace_sizes[24] = {
|
||||
/* 0: IEEE80211_RADIOTAP_TSFT */ { 8, 8 },
|
||||
/* 1: IEEE80211_RADIOTAP_FLAGS */ { 1, 1 },
|
||||
/* 2: IEEE80211_RADIOTAP_RATE */ { 1, 1 },
|
||||
/* 3: IEEE80211_RADIOTAP_CHANNEL */ { 2, 4 },
|
||||
/* 4: IEEE80211_RADIOTAP_FHSS */ { 2, 2 },
|
||||
/* 5: IEEE80211_RADIOTAP_DBM_ANTSIGNAL */ { 1, 1 },
|
||||
/* 6: IEEE80211_RADIOTAP_DBM_ANTNOISE */ { 1, 1 },
|
||||
/* 7: IEEE80211_RADIOTAP_LOCK_QUALITY */ { 2, 2 },
|
||||
/* 8: IEEE80211_RADIOTAP_TX_ATTENUATION */ { 2, 2 },
|
||||
/* 9: IEEE80211_RADIOTAP_DB_TX_ATTENUATION */ { 2, 2 },
|
||||
/* 10: IEEE80211_RADIOTAP_DBM_TX_POWER */ { 1, 1 },
|
||||
/* 11: IEEE80211_RADIOTAP_ANTENNA */ { 1, 1 },
|
||||
/* 12: IEEE80211_RADIOTAP_DB_ANTSIGNAL */ { 1, 1 },
|
||||
/* 13: IEEE80211_RADIOTAP_DB_ANTNOISE */ { 1, 1 },
|
||||
/* 14: IEEE80211_RADIOTAP_RX_FLAGS */ { 2, 2 },
|
||||
/* 15: IEEE80211_RADIOTAP_TX_FLAGS */ { 2, 2 },
|
||||
/* 16: IEEE80211_RADIOTAP_RTS_RETRIES */ { 1, 1 },
|
||||
/* 17: IEEE80211_RADIOTAP_DATA_RETRIES */ { 1, 1 },
|
||||
/* 18: (unused) */ { 0, 0 },
|
||||
/* 19: IEEE80211_RADIOTAP_MCS */ { 1, 3 },
|
||||
/* 20: IEEE80211_RADIOTAP_AMPDU_STATUS */ { 4, 8 },
|
||||
/* 21: IEEE80211_RADIOTAP_VHT */ { 2, 12 },
|
||||
/* 22: IEEE80211_RADIOTAP_TIMESTAMP */ { 8, 12 },
|
||||
/* 23: IEEE80211_RADIOTAP_HE */ { 2, 12 },
|
||||
};
|
||||
|
||||
static const struct ieee80211_radiotap_namespace radiotap_ns = {
|
||||
rtap_namespace_sizes,
|
||||
(int)sizeof(rtap_namespace_sizes) / sizeof(rtap_namespace_sizes[0]),
|
||||
0, /* oui */
|
||||
0 /* subns */
|
||||
};
|
||||
|
||||
/**
|
||||
* ieee80211_radiotap_iterator_init - radiotap parser iterator initialization
|
||||
* @iterator: radiotap_iterator to initialize
|
||||
* @radiotap_header: radiotap header to parse
|
||||
* @max_length: total length we can parse into (eg, whole packet length)
|
||||
*
|
||||
* Returns: 0 or a negative error code if there is a problem.
|
||||
*
|
||||
* This function initializes an opaque iterator struct which can then
|
||||
* be passed to ieee80211_radiotap_iterator_next() to visit every radiotap
|
||||
* argument which is present in the header. It knows about extended
|
||||
* present headers and handles them.
|
||||
*
|
||||
* How to use:
|
||||
* call __ieee80211_radiotap_iterator_init() to init a semi-opaque iterator
|
||||
* struct ieee80211_radiotap_iterator (no need to init the struct beforehand)
|
||||
* checking for a good 0 return code. Then loop calling
|
||||
* __ieee80211_radiotap_iterator_next()... it returns either 0,
|
||||
* -ENOENT if there are no more args to parse, or -EINVAL if there is a problem.
|
||||
* The iterator's @this_arg member points to the start of the argument
|
||||
* associated with the current argument index that is present, which can be
|
||||
* found in the iterator's @this_arg_index member. This arg index corresponds
|
||||
* to the IEEE80211_RADIOTAP_... defines.
|
||||
*
|
||||
* Radiotap header length:
|
||||
* You can find the CPU-endian total radiotap header length in
|
||||
* iterator->max_length after executing ieee80211_radiotap_iterator_init()
|
||||
* successfully.
|
||||
*
|
||||
* Alignment Gotcha:
|
||||
* You must take care when dereferencing iterator.this_arg
|
||||
* for multibyte types... the pointer is not aligned. Use
|
||||
* get_unaligned((type *)iterator.this_arg) to dereference
|
||||
* iterator.this_arg for type "type" safely on all arches.
|
||||
*
|
||||
* Example code:
|
||||
* See Documentation/networking/radiotap-headers.txt
|
||||
*/
|
||||
|
||||
int ieee80211_radiotap_iterator_init(
|
||||
struct ieee80211_radiotap_iterator *iterator,
|
||||
struct ieee80211_radiotap_header *radiotap_header, int max_length,
|
||||
const struct ieee80211_radiotap_vendor_namespaces *vns) {
|
||||
/* check the radiotap header can actually be present */
|
||||
if (max_length < (int)sizeof(struct ieee80211_radiotap_header))
|
||||
return -EINVAL;
|
||||
|
||||
/* Linux only supports version 0 radiotap format */
|
||||
if (radiotap_header->it_version)
|
||||
return -EINVAL;
|
||||
|
||||
/* sanity check for allowed length and radiotap length field */
|
||||
if (max_length < get_unaligned_le16(&radiotap_header->it_len))
|
||||
return -EINVAL;
|
||||
|
||||
iterator->_rtheader = radiotap_header;
|
||||
iterator->_max_length = get_unaligned_le16(&radiotap_header->it_len);
|
||||
iterator->_arg_index = 0;
|
||||
iterator->_bitmap_shifter = get_unaligned_le32(&radiotap_header->it_present);
|
||||
iterator->_arg = (uint8_t *)radiotap_header + sizeof(*radiotap_header);
|
||||
iterator->_reset_on_ext = 0;
|
||||
iterator->_next_bitmap = &radiotap_header->it_present; // NOLINT(clang-diagnostic-address-of-packed-member)
|
||||
iterator->_next_bitmap++;
|
||||
iterator->_vns = vns;
|
||||
iterator->current_namespace = &radiotap_ns;
|
||||
iterator->is_radiotap_ns = 1;
|
||||
|
||||
/* find payload start allowing for extended bitmap(s) */
|
||||
|
||||
if (iterator->_bitmap_shifter & (1u << IEEE80211_RADIOTAP_EXT)) {
|
||||
if (((size_t)iterator->_arg - (size_t)iterator->_rtheader) + sizeof(uint32_t) >
|
||||
(size_t)iterator->_max_length)
|
||||
return -EINVAL;
|
||||
while (get_unaligned_le32(iterator->_arg) &
|
||||
(1u << IEEE80211_RADIOTAP_EXT)) {
|
||||
iterator->_arg += sizeof(uint32_t);
|
||||
if (((size_t)iterator->_arg - (size_t)iterator->_rtheader) + sizeof(uint32_t) >
|
||||
(size_t)iterator->_max_length)
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
iterator->_arg += sizeof(uint32_t);
|
||||
|
||||
/*
|
||||
* no need to check again for blowing past stated radiotap
|
||||
* header length, because ieee80211_radiotap_iterator_next
|
||||
* checks it before it is dereferenced
|
||||
*/
|
||||
}
|
||||
|
||||
iterator->this_arg = iterator->_arg;
|
||||
|
||||
/* we are all initialized happily */
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void find_ns(struct ieee80211_radiotap_iterator *iterator, uint32_t oui,
|
||||
uint8_t subns) {
|
||||
int i;
|
||||
|
||||
iterator->current_namespace = NULL;
|
||||
|
||||
if (!iterator->_vns)
|
||||
return;
|
||||
|
||||
for (i = 0; i < iterator->_vns->n_ns; i++) {
|
||||
if (iterator->_vns->ns[i].oui != oui)
|
||||
continue;
|
||||
if (iterator->_vns->ns[i].subns != subns)
|
||||
continue;
|
||||
|
||||
iterator->current_namespace = &iterator->_vns->ns[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ieee80211_radiotap_iterator_next - return next radiotap parser iterator arg
|
||||
* @iterator: radiotap_iterator to move to next arg (if any)
|
||||
*
|
||||
* Returns: 0 if there is an argument to handle,
|
||||
* -ENOENT if there are no more args or -EINVAL
|
||||
* if there is something else wrong.
|
||||
*
|
||||
* This function provides the next radiotap arg index (IEEE80211_RADIOTAP_*)
|
||||
* in @this_arg_index and sets @this_arg to point to the
|
||||
* payload for the field. It takes care of alignment handling and extended
|
||||
* present fields. @this_arg can be changed by the caller (eg,
|
||||
* incremented to move inside a compound argument like
|
||||
* IEEE80211_RADIOTAP_CHANNEL). The args pointed to are in
|
||||
* little-endian format whatever the endianess of your CPU.
|
||||
*
|
||||
* Alignment Gotcha:
|
||||
* You must take care when dereferencing iterator.this_arg
|
||||
* for multibyte types... the pointer is not aligned. Use
|
||||
* get_unaligned((type *)iterator.this_arg) to dereference
|
||||
* iterator.this_arg for type "type" safely on all arches.
|
||||
*/
|
||||
|
||||
int ieee80211_radiotap_iterator_next(
|
||||
struct ieee80211_radiotap_iterator *iterator) {
|
||||
while (1) {
|
||||
int hit = 0;
|
||||
int pad, align = 0, size = 0, subns;
|
||||
uint32_t oui;
|
||||
|
||||
if ((iterator->_arg_index % 32) == IEEE80211_RADIOTAP_EXT &&
|
||||
!(iterator->_bitmap_shifter & 1))
|
||||
return -ENOENT;
|
||||
|
||||
if (!(iterator->_bitmap_shifter & 1))
|
||||
goto next_entry;
|
||||
|
||||
switch (iterator->_arg_index % 32) {
|
||||
case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
|
||||
case IEEE80211_RADIOTAP_EXT:
|
||||
align = 1;
|
||||
size = 0;
|
||||
break;
|
||||
case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
|
||||
align = 2;
|
||||
size = 6;
|
||||
break;
|
||||
default:
|
||||
if (!iterator->current_namespace ||
|
||||
iterator->_arg_index >= iterator->current_namespace->n_bits) {
|
||||
if (iterator->current_namespace == &radiotap_ns)
|
||||
return -ENOENT;
|
||||
align = 0;
|
||||
} else {
|
||||
align =
|
||||
iterator->current_namespace->align_size[iterator->_arg_index].align;
|
||||
size =
|
||||
iterator->current_namespace->align_size[iterator->_arg_index].size;
|
||||
}
|
||||
if (!align) {
|
||||
iterator->_arg = iterator->_next_ns_data;
|
||||
iterator->current_namespace = NULL;
|
||||
goto next_entry;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
pad = (((size_t)iterator->_arg - (size_t)iterator->_rtheader) & (align - 1));
|
||||
if (pad)
|
||||
iterator->_arg += align - pad;
|
||||
|
||||
if (iterator->_arg_index % 32 == IEEE80211_RADIOTAP_VENDOR_NAMESPACE) {
|
||||
int vnslen;
|
||||
if (((size_t)iterator->_arg + size - (size_t)iterator->_rtheader) >
|
||||
(size_t)iterator->_max_length)
|
||||
return -EINVAL;
|
||||
|
||||
oui = (iterator->_arg[0] << 16) | (iterator->_arg[1] << 8) |
|
||||
iterator->_arg[2];
|
||||
subns = iterator->_arg[3];
|
||||
|
||||
find_ns(iterator, oui, subns);
|
||||
vnslen = get_unaligned_le16(iterator->_arg + 4);
|
||||
iterator->_next_ns_data = iterator->_arg + size + vnslen;
|
||||
if (!iterator->current_namespace)
|
||||
size += vnslen;
|
||||
}
|
||||
|
||||
/*
|
||||
* this is what we will return to user, but we need to
|
||||
* move on first so next call has something fresh to test
|
||||
*/
|
||||
iterator->this_arg_index = iterator->_arg_index;
|
||||
iterator->this_arg = iterator->_arg;
|
||||
iterator->this_arg_size = size;
|
||||
|
||||
/* internally move on the size of this arg */
|
||||
iterator->_arg += size;
|
||||
|
||||
/*
|
||||
* check for insanity where we are given a bitmap that
|
||||
* claims to have more arg content than the length of the
|
||||
* radiotap section. We will normally end up equalling this
|
||||
* max_length on the last arg, never exceeding it.
|
||||
*/
|
||||
|
||||
if (((size_t)iterator->_arg - (size_t)iterator->_rtheader) >
|
||||
(size_t)iterator->_max_length)
|
||||
return -EINVAL;
|
||||
|
||||
switch (iterator->_arg_index % 32) {
|
||||
case IEEE80211_RADIOTAP_VENDOR_NAMESPACE:
|
||||
iterator->_reset_on_ext = 1;
|
||||
|
||||
iterator->is_radiotap_ns = 0;
|
||||
/*
|
||||
* If parser didn't register this vendor
|
||||
* namespace with us, allow it to show it
|
||||
* as 'raw. Do do that, set argument index
|
||||
* to vendor namespace.
|
||||
*/
|
||||
iterator->this_arg_index = IEEE80211_RADIOTAP_VENDOR_NAMESPACE;
|
||||
if (!iterator->current_namespace)
|
||||
hit = 1;
|
||||
goto next_entry;
|
||||
case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE:
|
||||
iterator->_reset_on_ext = 1;
|
||||
iterator->current_namespace = &radiotap_ns;
|
||||
iterator->is_radiotap_ns = 1;
|
||||
goto next_entry;
|
||||
case IEEE80211_RADIOTAP_EXT:
|
||||
/*
|
||||
* bit 31 was set, there is more
|
||||
* -- move to next u32 bitmap
|
||||
*/
|
||||
iterator->_bitmap_shifter = get_unaligned_le32(iterator->_next_bitmap);
|
||||
iterator->_next_bitmap++;
|
||||
if (iterator->_reset_on_ext)
|
||||
iterator->_arg_index = 0;
|
||||
else
|
||||
iterator->_arg_index++;
|
||||
iterator->_reset_on_ext = 0;
|
||||
break;
|
||||
default:
|
||||
/* we've got a hit! */
|
||||
hit = 1;
|
||||
next_entry:
|
||||
iterator->_bitmap_shifter >>= 1;
|
||||
iterator->_arg_index++;
|
||||
}
|
||||
|
||||
/* if we found a valid arg earlier, return it now */
|
||||
if (hit)
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
u16 GetSequence(const u8 *packet) {
|
||||
u16 seqCtrl = (u16)(packet[22]) | (u16)(packet[23] << 8);
|
||||
u16 seqNum = (seqCtrl >> 4) & 0x0FFF;
|
||||
return seqNum;
|
||||
}
|
||||
|
||||
u8 MRateToHwRate(u8 rate) {
|
||||
u8 ret = DESC_RATE1M;
|
||||
switch (rate) {
|
||||
case MGN_1M: ret = DESC_RATE1M; break;
|
||||
case MGN_2M: ret = DESC_RATE2M; break;
|
||||
case MGN_5_5M: ret = DESC_RATE5_5M; break;
|
||||
case MGN_11M: ret = DESC_RATE11M; break;
|
||||
case MGN_6M: ret = DESC_RATE6M; break;
|
||||
case MGN_9M: ret = DESC_RATE9M; break;
|
||||
case MGN_12M: ret = DESC_RATE12M; break;
|
||||
case MGN_18M: ret = DESC_RATE18M; break;
|
||||
case MGN_24M: ret = DESC_RATE24M; break;
|
||||
case MGN_36M: ret = DESC_RATE36M; break;
|
||||
case MGN_48M: ret = DESC_RATE48M; break;
|
||||
case MGN_54M: ret = DESC_RATE54M; break;
|
||||
case MGN_MCS0: ret = DESC_RATEMCS0; break;
|
||||
case MGN_MCS1: ret = DESC_RATEMCS1; break;
|
||||
case MGN_MCS2: ret = DESC_RATEMCS2; break;
|
||||
case MGN_MCS3: ret = DESC_RATEMCS3; break;
|
||||
case MGN_MCS4: ret = DESC_RATEMCS4; break;
|
||||
case MGN_MCS5: ret = DESC_RATEMCS5; break;
|
||||
case MGN_MCS6: ret = DESC_RATEMCS6; break;
|
||||
case MGN_MCS7: ret = DESC_RATEMCS7; break;
|
||||
case MGN_MCS8: ret = DESC_RATEMCS8; break;
|
||||
case MGN_MCS9: ret = DESC_RATEMCS9; break;
|
||||
case MGN_MCS10: ret = DESC_RATEMCS10; break;
|
||||
case MGN_MCS11: ret = DESC_RATEMCS11; break;
|
||||
case MGN_MCS12: ret = DESC_RATEMCS12; break;
|
||||
case MGN_MCS13: ret = DESC_RATEMCS13; break;
|
||||
case MGN_MCS14: ret = DESC_RATEMCS14; break;
|
||||
case MGN_MCS15: ret = DESC_RATEMCS15; break;
|
||||
case MGN_MCS16: ret = DESC_RATEMCS16; break;
|
||||
case MGN_MCS17: ret = DESC_RATEMCS17; break;
|
||||
case MGN_MCS18: ret = DESC_RATEMCS18; break;
|
||||
case MGN_MCS19: ret = DESC_RATEMCS19; break;
|
||||
case MGN_MCS20: ret = DESC_RATEMCS20; break;
|
||||
case MGN_MCS21: ret = DESC_RATEMCS21; break;
|
||||
case MGN_MCS22: ret = DESC_RATEMCS22; break;
|
||||
case MGN_MCS23: ret = DESC_RATEMCS23; break;
|
||||
case MGN_MCS24: ret = DESC_RATEMCS24; break;
|
||||
case MGN_MCS25: ret = DESC_RATEMCS25; break;
|
||||
case MGN_MCS26: ret = DESC_RATEMCS26; break;
|
||||
case MGN_MCS27: ret = DESC_RATEMCS27; break;
|
||||
case MGN_MCS28: ret = DESC_RATEMCS28; break;
|
||||
case MGN_MCS29: ret = DESC_RATEMCS29; break;
|
||||
case MGN_MCS30: ret = DESC_RATEMCS30; break;
|
||||
case MGN_MCS31: ret = DESC_RATEMCS31; break;
|
||||
case MGN_VHT1SS_MCS0: ret = DESC_RATEVHTSS1MCS0; break;
|
||||
case MGN_VHT1SS_MCS1: ret = DESC_RATEVHTSS1MCS1; break;
|
||||
case MGN_VHT1SS_MCS2: ret = DESC_RATEVHTSS1MCS2; break;
|
||||
case MGN_VHT1SS_MCS3: ret = DESC_RATEVHTSS1MCS3; break;
|
||||
case MGN_VHT1SS_MCS4: ret = DESC_RATEVHTSS1MCS4; break;
|
||||
case MGN_VHT1SS_MCS5: ret = DESC_RATEVHTSS1MCS5; break;
|
||||
case MGN_VHT1SS_MCS6: ret = DESC_RATEVHTSS1MCS6; break;
|
||||
case MGN_VHT1SS_MCS7: ret = DESC_RATEVHTSS1MCS7; break;
|
||||
case MGN_VHT1SS_MCS8: ret = DESC_RATEVHTSS1MCS8; break;
|
||||
case MGN_VHT1SS_MCS9: ret = DESC_RATEVHTSS1MCS9; break;
|
||||
case MGN_VHT2SS_MCS0: ret = DESC_RATEVHTSS2MCS0; break;
|
||||
case MGN_VHT2SS_MCS1: ret = DESC_RATEVHTSS2MCS1; break;
|
||||
case MGN_VHT2SS_MCS2: ret = DESC_RATEVHTSS2MCS2; break;
|
||||
case MGN_VHT2SS_MCS3: ret = DESC_RATEVHTSS2MCS3; break;
|
||||
case MGN_VHT2SS_MCS4: ret = DESC_RATEVHTSS2MCS4; break;
|
||||
case MGN_VHT2SS_MCS5: ret = DESC_RATEVHTSS2MCS5; break;
|
||||
case MGN_VHT2SS_MCS6: ret = DESC_RATEVHTSS2MCS6; break;
|
||||
case MGN_VHT2SS_MCS7: ret = DESC_RATEVHTSS2MCS7; break;
|
||||
case MGN_VHT2SS_MCS8: ret = DESC_RATEVHTSS2MCS8; break;
|
||||
case MGN_VHT2SS_MCS9: ret = DESC_RATEVHTSS2MCS9; break;
|
||||
case MGN_VHT3SS_MCS0: ret = DESC_RATEVHTSS3MCS0; break;
|
||||
case MGN_VHT3SS_MCS1: ret = DESC_RATEVHTSS3MCS1; break;
|
||||
case MGN_VHT3SS_MCS2: ret = DESC_RATEVHTSS3MCS2; break;
|
||||
case MGN_VHT3SS_MCS3: ret = DESC_RATEVHTSS3MCS3; break;
|
||||
case MGN_VHT3SS_MCS4: ret = DESC_RATEVHTSS3MCS4; break;
|
||||
case MGN_VHT3SS_MCS5: ret = DESC_RATEVHTSS3MCS5; break;
|
||||
case MGN_VHT3SS_MCS6: ret = DESC_RATEVHTSS3MCS6; break;
|
||||
case MGN_VHT3SS_MCS7: ret = DESC_RATEVHTSS3MCS7; break;
|
||||
case MGN_VHT3SS_MCS8: ret = DESC_RATEVHTSS3MCS8; break;
|
||||
case MGN_VHT3SS_MCS9: ret = DESC_RATEVHTSS3MCS9; break;
|
||||
case MGN_VHT4SS_MCS0: ret = DESC_RATEVHTSS4MCS0; break;
|
||||
case MGN_VHT4SS_MCS1: ret = DESC_RATEVHTSS4MCS1; break;
|
||||
case MGN_VHT4SS_MCS2: ret = DESC_RATEVHTSS4MCS2; break;
|
||||
case MGN_VHT4SS_MCS3: ret = DESC_RATEVHTSS4MCS3; break;
|
||||
case MGN_VHT4SS_MCS4: ret = DESC_RATEVHTSS4MCS4; break;
|
||||
case MGN_VHT4SS_MCS5: ret = DESC_RATEVHTSS4MCS5; break;
|
||||
case MGN_VHT4SS_MCS6: ret = DESC_RATEVHTSS4MCS6; break;
|
||||
case MGN_VHT4SS_MCS7: ret = DESC_RATEVHTSS4MCS7; break;
|
||||
case MGN_VHT4SS_MCS8: ret = DESC_RATEVHTSS4MCS8; break;
|
||||
case MGN_VHT4SS_MCS9: ret = DESC_RATEVHTSS4MCS9; break;
|
||||
default: break;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int parse_radiotap() {
|
||||
int ret = 0;
|
||||
int rtap_len;
|
||||
int qos_len = 0;
|
||||
int dot11_hdr_len = 24;
|
||||
int snap_len = 6;
|
||||
unsigned char *pdata;
|
||||
u16 frame_ctl;
|
||||
unsigned char src_mac_addr[6];
|
||||
unsigned char dst_mac_addr[6];
|
||||
u8 fixed_rate = MGN_1M, sgi = 0, bwidth = 0, ldpc = 0, stbc = 0;
|
||||
u16 txflags = 0;
|
||||
|
||||
/* This packet is only 13 bytes long.
|
||||
We add an explicit cast to silence the warning. */
|
||||
uint8_t pkt[] = {
|
||||
0x00, 0x00, 0x0d, 0x00, 0x00, 0x80, 0x08,
|
||||
0x00, 0x08, 0x00, 0x37, 0x00, 0x01,
|
||||
};
|
||||
struct ieee80211_radiotap_header *rtap_hdr;
|
||||
rtap_hdr = (struct ieee80211_radiotap_header *)(void *)pkt;
|
||||
struct ieee80211_radiotap_iterator iterator;
|
||||
ret = ieee80211_radiotap_iterator_init(&iterator, rtap_hdr, 0x0d, NULL);
|
||||
while (!ret) {
|
||||
ret = ieee80211_radiotap_iterator_next(&iterator);
|
||||
|
||||
if (ret)
|
||||
continue;
|
||||
|
||||
/* see if this argument is something we can use */
|
||||
switch (iterator.this_arg_index) {
|
||||
|
||||
case IEEE80211_RADIOTAP_RATE: /* u8 */
|
||||
fixed_rate = *iterator.this_arg;
|
||||
break;
|
||||
|
||||
case IEEE80211_RADIOTAP_TX_FLAGS:
|
||||
txflags = get_unaligned_le16(iterator.this_arg);
|
||||
break;
|
||||
|
||||
case IEEE80211_RADIOTAP_MCS: { /* u8,u8,u8 */
|
||||
u8 mcs_have = iterator.this_arg[0];
|
||||
// printf("MCS value:%d %d %d\n", iterator.this_arg[0], iterator.this_arg[1],
|
||||
// iterator.this_arg[2]);
|
||||
// printf("mcs parse:%d\n", mcs_have);
|
||||
if (mcs_have & IEEE80211_RADIOTAP_MCS_HAVE_MCS) {
|
||||
fixed_rate = iterator.this_arg[2] & 0x7f;
|
||||
if (fixed_rate > 31)
|
||||
fixed_rate = 0;
|
||||
fixed_rate += MGN_MCS0;
|
||||
}
|
||||
// printf("mcs_have & 4 = %d,%d \n", (mcs_have & 4),
|
||||
// (iterator.this_arg[1] & 1));
|
||||
if ((mcs_have & 4) && (iterator.this_arg[1] & 4))
|
||||
sgi = 1;
|
||||
if ((mcs_have & 1) && (iterator.this_arg[1] & 1))
|
||||
bwidth = 1;
|
||||
if ((mcs_have & 0x10) && (iterator.this_arg[1] & 0x10))
|
||||
ldpc = 1;
|
||||
if ((mcs_have & 0x20))
|
||||
stbc = (iterator.this_arg[1] >> 5) & 3;
|
||||
} break;
|
||||
|
||||
case IEEE80211_RADIOTAP_VHT: {
|
||||
/* u16 known, u8 flags, u8 bandwidth, u8 mcs_nss[4], u8 coding, u8
|
||||
* group_id, u16 partial_aid */
|
||||
u8 known = iterator.this_arg[0];
|
||||
u8 flags = iterator.this_arg[2];
|
||||
unsigned int mcs, nss;
|
||||
if ((known & 4) && (flags & 4))
|
||||
sgi = 1;
|
||||
if ((known & 1) && (flags & 1))
|
||||
stbc = 1;
|
||||
if (known & 0x40) {
|
||||
bwidth = iterator.this_arg[3] & 0x1f;
|
||||
if (bwidth >= 1 && bwidth <= 3)
|
||||
bwidth = 1; // 40 MHz
|
||||
else if (bwidth >= 4 && bwidth <= 10)
|
||||
bwidth = 2; // 80 MHz
|
||||
else
|
||||
bwidth = 0; // 20 MHz
|
||||
}
|
||||
if (iterator.this_arg[8] & 1)
|
||||
ldpc = 1;
|
||||
mcs = (iterator.this_arg[4] >> 4) & 0x0f;
|
||||
nss = iterator.this_arg[4] & 0x0f;
|
||||
if (nss > 0) {
|
||||
if (nss > 4)
|
||||
nss = 4;
|
||||
if (mcs > 9)
|
||||
mcs = 9;
|
||||
fixed_rate = MGN_VHT1SS_MCS0 + ((nss - 1) * 10 + mcs);
|
||||
}
|
||||
} break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
printf("fixed rate:%d\n", fixed_rate);
|
||||
printf("sgi =%d, bandwdith=%d, ldpc=%d, stbc=%d\n", sgi, bwidth, ldpc, stbc);
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
#include "RadiotapBuilder.h"
|
||||
|
||||
#include "ieee80211_radiotap.h" /* HE field masks */
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint8_t kRadiotapVersion = 0;
|
||||
|
||||
/* it_present bit positions per radiotap spec. */
|
||||
constexpr uint32_t kPresentRate = 1u << 2;
|
||||
constexpr uint32_t kPresentTxFlags = 1u << 15;
|
||||
constexpr uint32_t kPresentMcs = 1u << 19;
|
||||
constexpr uint32_t kPresentVht = 1u << 21;
|
||||
constexpr uint32_t kPresentHe = 1u << 23;
|
||||
|
||||
constexpr uint16_t kTxFlagsNoAck = 0x0008;
|
||||
|
||||
void emit_u8(std::vector<uint8_t>& v, uint8_t x) { v.push_back(x); }
|
||||
void emit_u16_le(std::vector<uint8_t>& v, uint16_t x) {
|
||||
v.push_back(static_cast<uint8_t>(x & 0xFF));
|
||||
v.push_back(static_cast<uint8_t>((x >> 8) & 0xFF));
|
||||
}
|
||||
void emit_u32_le(std::vector<uint8_t>& v, uint32_t x) {
|
||||
v.push_back(static_cast<uint8_t>(x & 0xFF));
|
||||
v.push_back(static_cast<uint8_t>((x >> 8) & 0xFF));
|
||||
v.push_back(static_cast<uint8_t>((x >> 16) & 0xFF));
|
||||
v.push_back(static_cast<uint8_t>((x >> 24) & 0xFF));
|
||||
}
|
||||
|
||||
std::vector<uint8_t> build_legacy(const TxMode& cfg) {
|
||||
/* 13-byte legacy-OFDM radiotap. Byte 8 (RATE) carried from cfg; length stays
|
||||
* 13 so send_packet's vht-detection heuristic keeps this on the legacy path. */
|
||||
std::vector<uint8_t> r;
|
||||
r.reserve(13);
|
||||
emit_u8(r, kRadiotapVersion);
|
||||
emit_u8(r, 0); /* pad */
|
||||
emit_u16_le(r, 13); /* it_len */
|
||||
emit_u32_le(r, kPresentRate | kPresentTxFlags); /* it_present */
|
||||
emit_u8(r, cfg.legacy_rate_500kbps); /* RATE */
|
||||
emit_u8(r, 0); /* pad (TX_FLAGS u16 align) */
|
||||
emit_u16_le(r, kTxFlagsNoAck); /* TX_FLAGS */
|
||||
emit_u8(r, 0); /* trailing pad to 13 */
|
||||
return r;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> build_ht(const TxMode& cfg) {
|
||||
/* 13-byte HT radiotap: presence = TX_FLAGS | MCS, no RATE field. Length stays
|
||||
* 13 so send_packet keeps rate_id=8 (HT, not VHT).
|
||||
*
|
||||
* MCS field layout (3 bytes after TX_FLAGS): known mask, flags, MCS index. */
|
||||
constexpr uint8_t kKnownBw = 1u << 0;
|
||||
constexpr uint8_t kKnownMcs = 1u << 1;
|
||||
constexpr uint8_t kKnownGi = 1u << 2;
|
||||
constexpr uint8_t kKnownFec = 1u << 4;
|
||||
constexpr uint8_t kKnownStbc = 1u << 5;
|
||||
|
||||
uint8_t known = kKnownMcs | kKnownGi | kKnownFec | kKnownBw | kKnownStbc;
|
||||
uint8_t flags = 0;
|
||||
/* BW: 0=20, 1=40. */
|
||||
if (cfg.bw_mhz >= 40) flags |= 0x01;
|
||||
if (cfg.sgi) flags |= 0x04;
|
||||
if (cfg.ldpc) flags |= 0x10;
|
||||
if (cfg.stbc) flags |= 0x20; /* one STBC stream */
|
||||
|
||||
std::vector<uint8_t> r;
|
||||
r.reserve(13);
|
||||
emit_u8(r, kRadiotapVersion);
|
||||
emit_u8(r, 0);
|
||||
emit_u16_le(r, 13);
|
||||
emit_u32_le(r, kPresentTxFlags | kPresentMcs);
|
||||
emit_u16_le(r, kTxFlagsNoAck);
|
||||
emit_u8(r, known);
|
||||
emit_u8(r, flags);
|
||||
emit_u8(r, cfg.ht_mcs <= 31 ? cfg.ht_mcs : 0);
|
||||
return r;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> build_vht(const TxMode& cfg) {
|
||||
/* 22-byte VHT radiotap: header(8) + TX_FLAGS(2) + VHT info(12). Length > 13
|
||||
* triggers send_packet's vht=true branch (rate_id=9). */
|
||||
uint8_t bw_code;
|
||||
switch (cfg.bw_mhz) {
|
||||
case 40: bw_code = 1; break;
|
||||
case 80: bw_code = 4; break;
|
||||
case 160: bw_code = 11; break;
|
||||
default: bw_code = 0; break;
|
||||
}
|
||||
/* known mask: STBC(0) | GI(2) | BW(6) — matches send_packet's VHT decoder. */
|
||||
const uint16_t known = (1u << 0) | (1u << 2) | (1u << 6);
|
||||
uint8_t vht_flags = 0;
|
||||
if (cfg.stbc) vht_flags |= 0x01;
|
||||
if (cfg.sgi) vht_flags |= 0x04;
|
||||
const uint8_t mcs_nss_user0 = static_cast<uint8_t>(
|
||||
((cfg.vht_mcs & 0x0F) << 4) | (cfg.vht_nss & 0x0F));
|
||||
const uint8_t coding_user0 = cfg.ldpc ? 0x01 : 0x00;
|
||||
|
||||
std::vector<uint8_t> r;
|
||||
r.reserve(22);
|
||||
emit_u8(r, kRadiotapVersion);
|
||||
emit_u8(r, 0);
|
||||
emit_u16_le(r, 22);
|
||||
emit_u32_le(r, kPresentTxFlags | kPresentVht);
|
||||
emit_u16_le(r, kTxFlagsNoAck);
|
||||
emit_u16_le(r, known);
|
||||
emit_u8(r, vht_flags);
|
||||
emit_u8(r, bw_code);
|
||||
emit_u8(r, mcs_nss_user0);
|
||||
emit_u8(r, 0); /* user 1 mcs_nss */
|
||||
emit_u8(r, 0); /* user 2 mcs_nss */
|
||||
emit_u8(r, 0); /* user 3 mcs_nss */
|
||||
emit_u8(r, coding_user0);
|
||||
emit_u8(r, 0); /* group_id */
|
||||
emit_u16_le(r, 0); /* partial_aid */
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Map the chip's 3-bit GI/LTF code (enum rtw_gi_ltf) to the radiotap HE
|
||||
* (GI, LTF-size) pair for emission. GI: 0=0.8us 1=1.6us 2=3.2us; LTF: 1=1x
|
||||
* 2=2x 3=4x. Inverse of the Kestrel send_packet HE parser. */
|
||||
void he_giltf_to_radiotap(uint8_t gi_ltf, uint8_t* gi, uint8_t* ltf) {
|
||||
switch (gi_ltf) {
|
||||
case 0: *gi = 2; *ltf = 3; break; /* 4xLTF + 3.2us */
|
||||
case 1: *gi = 0; *ltf = 3; break; /* 4xLTF + 0.8us */
|
||||
case 2: *gi = 1; *ltf = 2; break; /* 2xLTF + 1.6us */
|
||||
case 4: *gi = 1; *ltf = 1; break; /* 1xLTF + 1.6us */
|
||||
case 5: *gi = 0; *ltf = 1; break; /* 1xLTF + 0.8us */
|
||||
case 3:
|
||||
default: *gi = 0; *ltf = 2; break; /* 2xLTF + 0.8us (HE-SU default) */
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<uint8_t> build_he(const TxMode& cfg) {
|
||||
/* 22-byte HE radiotap: header(8) + TX_FLAGS(2) + HE info(12, data1..data6).
|
||||
* The Kestrel send_packet HE parser reads MCS/coding/STBC (data3), BW+GI+LTF
|
||||
* (data5) and NSTS (data6) and maps them to the AX descriptor rate. */
|
||||
uint8_t bw_code; /* HE DATA5 BW_RU_ALLOC: 0=20 1=40 2=80 3=160; RU 6=106 7=242 */
|
||||
switch (cfg.bw_mhz) {
|
||||
case 40: bw_code = 1; break;
|
||||
case 80: bw_code = 2; break;
|
||||
case 160: bw_code = 3; break;
|
||||
default: bw_code = 0; break;
|
||||
}
|
||||
/* ER SU is a 20 MHz-only format: the BW_RU_ALLOC value names the RU size
|
||||
* (242-tone = full-width ER, 106-tone = the upper-bandwidth ~3dB variant)
|
||||
* and overrides any configured bw_mhz. */
|
||||
if (cfg.he_er == 1) bw_code = IEEE80211_RADIOTAP_HE_DATA5_RU_242;
|
||||
else if (cfg.he_er == 2) bw_code = IEEE80211_RADIOTAP_HE_DATA5_RU_106;
|
||||
uint8_t gi = 0, ltf = 2;
|
||||
he_giltf_to_radiotap(cfg.he_gi_ltf, &gi, <f);
|
||||
|
||||
uint16_t data1 =
|
||||
IEEE80211_RADIOTAP_HE_DATA1_DATA_MCS_KNOWN |
|
||||
IEEE80211_RADIOTAP_HE_DATA1_CODING_KNOWN |
|
||||
IEEE80211_RADIOTAP_HE_DATA1_STBC_KNOWN |
|
||||
IEEE80211_RADIOTAP_HE_DATA1_BW_RU_ALLOC_KNOWN; /* FORMAT=SU(0) */
|
||||
if (cfg.he_er) data1 |= IEEE80211_RADIOTAP_HE_DATA1_FORMAT_EXT_SU;
|
||||
if (cfg.he_dcm) data1 |= IEEE80211_RADIOTAP_HE_DATA1_DATA_DCM_KNOWN;
|
||||
const uint16_t data2 = IEEE80211_RADIOTAP_HE_DATA2_GI_KNOWN |
|
||||
IEEE80211_RADIOTAP_HE_DATA2_NUM_LTF_SYMS_KNOWN;
|
||||
uint16_t data3 =
|
||||
static_cast<uint16_t>((cfg.he_mcs & 0x0f) << 8) & /* DATA_MCS bits 8..11 */
|
||||
IEEE80211_RADIOTAP_HE_DATA3_DATA_MCS;
|
||||
if (cfg.ldpc) data3 |= IEEE80211_RADIOTAP_HE_DATA3_CODING;
|
||||
if (cfg.stbc) data3 |= IEEE80211_RADIOTAP_HE_DATA3_STBC;
|
||||
if (cfg.he_dcm) data3 |= IEEE80211_RADIOTAP_HE_DATA3_DATA_DCM;
|
||||
const uint16_t data5 = static_cast<uint16_t>(
|
||||
(bw_code & 0x0f) |
|
||||
((gi & 0x3) << IEEE80211_RADIOTAP_HE_DATA5_GI_SHIFT) |
|
||||
((ltf & 0x3) << IEEE80211_RADIOTAP_HE_DATA5_LTF_SIZE_SHIFT));
|
||||
const uint16_t data6 = static_cast<uint16_t>(cfg.he_nss & 0x0f); /* NSTS */
|
||||
|
||||
std::vector<uint8_t> r;
|
||||
r.reserve(22);
|
||||
emit_u8(r, kRadiotapVersion);
|
||||
emit_u8(r, 0);
|
||||
emit_u16_le(r, 22);
|
||||
emit_u32_le(r, kPresentTxFlags | kPresentHe);
|
||||
emit_u16_le(r, kTxFlagsNoAck);
|
||||
emit_u16_le(r, data1);
|
||||
emit_u16_le(r, data2);
|
||||
emit_u16_le(r, data3);
|
||||
emit_u16_le(r, 0); /* data4 */
|
||||
emit_u16_le(r, data5);
|
||||
emit_u16_le(r, data6);
|
||||
return r;
|
||||
}
|
||||
|
||||
std::string to_upper_stripped(const char* raw) {
|
||||
std::string s;
|
||||
for (const char* p = raw; *p; ++p) {
|
||||
if (*p == ' ' || *p == '\t' || *p == '\n') continue;
|
||||
s.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(*p))));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
bool parse_uint(const std::string& s, size_t pos, unsigned* out) {
|
||||
if (pos >= s.size()) return false;
|
||||
unsigned v = 0;
|
||||
size_t i = pos;
|
||||
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
|
||||
v = v * 10 + static_cast<unsigned>(s[i] - '0');
|
||||
++i;
|
||||
if (v > 1000) return false;
|
||||
}
|
||||
if (i == pos) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Parse the rate mnemonic (first '/'-token) into cfg. Returns false if the
|
||||
* token is not a recognised rate. */
|
||||
bool parse_rate_token(const std::string& s, TxMode* cfg) {
|
||||
/* CCK (2.4GHz only — the chip drops CCK at 5GHz, see RtlJaguarDevice). The
|
||||
* 500kbps count doubles as the MGN_* byte here too: 1M=2=MGN_1M, 2M=4=MGN_2M,
|
||||
* 5.5M=11=MGN_5_5M, 11M=22=MGN_11M. 1M CCK is the most robust rate (~9dB more
|
||||
* link budget than 6M OFDM) for a long-range beacon. */
|
||||
if (s == "1M") { cfg->legacy_rate_500kbps = 2; return true; }
|
||||
if (s == "2M") { cfg->legacy_rate_500kbps = 4; return true; }
|
||||
if (s == "5.5M" || s == "5_5M") { cfg->legacy_rate_500kbps = 11; return true; }
|
||||
if (s == "11M") { cfg->legacy_rate_500kbps = 22; return true; }
|
||||
|
||||
if (s == "6M") { cfg->legacy_rate_500kbps = 12; return true; }
|
||||
if (s == "9M") { cfg->legacy_rate_500kbps = 18; return true; }
|
||||
if (s == "12M") { cfg->legacy_rate_500kbps = 24; return true; }
|
||||
if (s == "18M") { cfg->legacy_rate_500kbps = 36; return true; }
|
||||
if (s == "24M") { cfg->legacy_rate_500kbps = 48; return true; }
|
||||
if (s == "36M") { cfg->legacy_rate_500kbps = 72; return true; }
|
||||
if (s == "48M") { cfg->legacy_rate_500kbps = 96; return true; }
|
||||
if (s == "54M") { cfg->legacy_rate_500kbps = 108; return true; }
|
||||
|
||||
/* HT: MCS<N>, 0..31. */
|
||||
if (s.rfind("MCS", 0) == 0) {
|
||||
unsigned mcs;
|
||||
if (parse_uint(s, 3, &mcs) && mcs <= 31) {
|
||||
cfg->mode = TxMode::Mode::HT;
|
||||
cfg->ht_mcs = static_cast<uint8_t>(mcs);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/* VHT: VHT<NSS>SS_MCS<MCS>, NSS 1..4, MCS 0..9. */
|
||||
if (s.rfind("VHT", 0) == 0) {
|
||||
unsigned nss;
|
||||
if (parse_uint(s, 3, &nss) && nss >= 1 && nss <= 4) {
|
||||
size_t after_nss = 3;
|
||||
while (after_nss < s.size() && s[after_nss] >= '0' && s[after_nss] <= '9')
|
||||
++after_nss;
|
||||
const std::string tail = "SS_MCS";
|
||||
if (s.compare(after_nss, tail.size(), tail) == 0) {
|
||||
unsigned mcs;
|
||||
if (parse_uint(s, after_nss + tail.size(), &mcs) && mcs <= 9) {
|
||||
cfg->mode = TxMode::Mode::VHT;
|
||||
cfg->vht_nss = static_cast<uint8_t>(nss);
|
||||
cfg->vht_mcs = static_cast<uint8_t>(mcs);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* HE (802.11ax, Kestrel): HE<NSS>SS_MCS<MCS>, NSS 1..4, MCS 0..11. */
|
||||
if (s.rfind("HE", 0) == 0) {
|
||||
unsigned nss;
|
||||
if (parse_uint(s, 2, &nss) && nss >= 1 && nss <= 4) {
|
||||
size_t after_nss = 2;
|
||||
while (after_nss < s.size() && s[after_nss] >= '0' && s[after_nss] <= '9')
|
||||
++after_nss;
|
||||
const std::string tail = "SS_MCS";
|
||||
if (s.compare(after_nss, tail.size(), tail) == 0) {
|
||||
unsigned mcs;
|
||||
if (parse_uint(s, after_nss + tail.size(), &mcs) && mcs <= 11) {
|
||||
cfg->mode = TxMode::Mode::HE;
|
||||
cfg->he_nss = static_cast<uint8_t>(nss);
|
||||
cfg->he_mcs = static_cast<uint8_t>(mcs);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> build_stream_radiotap(const TxMode& cfg) {
|
||||
switch (cfg.mode) {
|
||||
case TxMode::Mode::HT: return build_ht(cfg);
|
||||
case TxMode::Mode::VHT: return build_vht(cfg);
|
||||
case TxMode::Mode::HE: return build_he(cfg);
|
||||
case TxMode::Mode::Legacy:
|
||||
default: return build_legacy(cfg);
|
||||
}
|
||||
}
|
||||
|
||||
TxMode parse_tx_mode_str(const std::string& spec) {
|
||||
TxMode cfg; /* defaults: legacy 6M, 20 MHz, no SGI/LDPC/STBC */
|
||||
|
||||
if (spec.empty()) {
|
||||
return cfg;
|
||||
}
|
||||
const std::string s = to_upper_stripped(spec.c_str());
|
||||
|
||||
/* Split on '/': first token = rate, rest = bandwidth (numeric) or modifier
|
||||
* flags (SGI / LDPC / STBC). */
|
||||
std::vector<std::string> tokens;
|
||||
size_t start = 0;
|
||||
while (start <= s.size()) {
|
||||
size_t slash = s.find('/', start);
|
||||
if (slash == std::string::npos) {
|
||||
tokens.push_back(s.substr(start));
|
||||
break;
|
||||
}
|
||||
tokens.push_back(s.substr(start, slash - start));
|
||||
start = slash + 1;
|
||||
}
|
||||
if (tokens.empty() || tokens[0].empty() || !parse_rate_token(tokens[0], &cfg)) {
|
||||
/* free function, no Logger handle — hand-rolled diagnostic-plane line */
|
||||
std::fprintf(stderr,
|
||||
"devourer [W] unrecognised TX rate '%s', "
|
||||
"falling back to 6M legacy\n", spec.c_str());
|
||||
return TxMode{};
|
||||
}
|
||||
|
||||
for (size_t i = 1; i < tokens.size(); ++i) {
|
||||
const std::string& t = tokens[i];
|
||||
if (t == "SGI") cfg.sgi = true;
|
||||
else if (t == "LDPC") cfg.ldpc = true;
|
||||
else if (t == "STBC") cfg.stbc = true;
|
||||
else if (t == "ER" || t == "ER106" || t == "DCM") {
|
||||
/* HE ER SU / DCM are 802.11ax-only modifiers (Kestrel). */
|
||||
if (cfg.mode != TxMode::Mode::HE) {
|
||||
std::fprintf(stderr,
|
||||
"devourer [W] ignoring '%s': HE rates only\n", t.c_str());
|
||||
continue;
|
||||
}
|
||||
if (t == "DCM") cfg.he_dcm = true;
|
||||
else cfg.he_er = (t == "ER106") ? 2 : 1;
|
||||
}
|
||||
else if (t == "20" || t == "40" || t == "80" || t == "160")
|
||||
cfg.bw_mhz = static_cast<uint8_t>(std::atoi(t.c_str()));
|
||||
else if (!t.empty())
|
||||
std::fprintf(stderr,
|
||||
"devourer [W] ignoring unrecognised TX-mode token "
|
||||
"'%s'\n", t.c_str());
|
||||
}
|
||||
/* ER SU spec limits, applied at parse time so the configured default is
|
||||
* honest (the Kestrel send path clamps again defensively): 242-tone = MCS
|
||||
* 0-2, 106-tone = MCS 0, both NSS 1, 20 MHz. DCM pairs with MCS 0/1/3/4
|
||||
* (0/1 under ER) and excludes STBC. */
|
||||
if (cfg.mode == TxMode::Mode::HE && cfg.he_er) {
|
||||
const uint8_t mcs_max = (cfg.he_er == 2) ? 0 : 2;
|
||||
if (cfg.he_mcs > mcs_max || cfg.he_nss > 1) {
|
||||
std::fprintf(stderr,
|
||||
"devourer [W] HE ER SU clamp: nss %u->1, mcs %u->%u\n",
|
||||
cfg.he_nss, cfg.he_mcs,
|
||||
cfg.he_mcs > mcs_max ? mcs_max : cfg.he_mcs);
|
||||
cfg.he_nss = 1;
|
||||
if (cfg.he_mcs > mcs_max) cfg.he_mcs = mcs_max;
|
||||
}
|
||||
cfg.bw_mhz = 20;
|
||||
}
|
||||
if (cfg.mode == TxMode::Mode::HE && cfg.he_dcm) {
|
||||
const bool mcs_ok = cfg.he_er ? (cfg.he_mcs <= 1)
|
||||
: (cfg.he_mcs <= 1 || cfg.he_mcs == 3 ||
|
||||
cfg.he_mcs == 4);
|
||||
if (!mcs_ok) {
|
||||
std::fprintf(stderr,
|
||||
"devourer [W] HE DCM dropped: MCS%u not DCM-capable\n",
|
||||
cfg.he_mcs);
|
||||
cfg.he_dcm = false;
|
||||
} else if (cfg.stbc) {
|
||||
std::fprintf(stderr, "devourer [W] HE DCM excludes STBC: dropping STBC\n");
|
||||
cfg.stbc = false;
|
||||
}
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,49 @@
|
||||
/* Radiotap-header builder + env parser shared by the TX binaries.
|
||||
*
|
||||
* build_stream_radiotap() turns a devourer::TxMode into a complete, well-formed
|
||||
* radiotap header (Legacy OFDM / HT-MCS / VHT) that send_packet parses to set
|
||||
* the on-air rate. The demos parse DEVOURER_TX_RATE with parse_tx_mode_str
|
||||
* into a TxMode for the demos' command-line interface.
|
||||
*
|
||||
* Two wire-format facts send_packet relies on:
|
||||
* - A 13-byte (0x0d) radiotap keeps the legacy/HT path (rate_id=8). A length
|
||||
* other than 13 flips send_packet's vht heuristic (rate_id=9) — VHT needs a
|
||||
* 22-byte radiotap.
|
||||
* - The radiotap iterator parses all present fields; a 13-byte HT-MCS radiotap
|
||||
* (it_present=MCS|TX_FLAGS) is honoured directly — no env gate required.
|
||||
*/
|
||||
#ifndef RADIOTAP_BUILDER_H
|
||||
#define RADIOTAP_BUILDER_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "TxMode.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Build a radiotap header according to mode.mode. Output is always a complete,
|
||||
* well-formed radiotap header — no 802.11 frame body. */
|
||||
std::vector<uint8_t> build_stream_radiotap(const TxMode& mode);
|
||||
|
||||
/* Parse a TX-mode spec string into a TxMode. Single slash-separated string:
|
||||
* <rate>[/<bw>][/SGI][/LDPC][/STBC][/ER|/ER106][/DCM] (case-insensitive)
|
||||
* <rate> : 6M|9M|12M|18M|24M|36M|48M|54M | MCS0..MCS31 |
|
||||
* VHT1SS_MCS0..VHT4SS_MCS9 | HE1SS_MCS0..HE4SS_MCS11
|
||||
* <bw> : 20|40|80|160 (default 20)
|
||||
* ER / ER106 / DCM (HE rates only, Kestrel): HE ER SU extended-range PPDU
|
||||
* (242-tone RU, MCS0-2 / 106-tone RU, MCS0) and dual-carrier modulation
|
||||
* (MCS 0/1/3/4; excludes STBC). Out-of-spec combos are clamped (W log).
|
||||
* Empty or unrecognised falls back to 6M legacy.
|
||||
*
|
||||
* The rate is resolved without reference to the band, so a VHT rate on a
|
||||
* 2.4 GHz channel is accepted and aired — the non-standard vendor extension
|
||||
* ("NitroQAM"/"TurboQAM"). It is bench-confirmed on the chips whose
|
||||
* AdapterCaps.vht_2g4_ok is set; the peer must be able to decode it, since a
|
||||
* standards-only 802.11n receiver sees nothing. See docs/vht-on-2g4.md. */
|
||||
TxMode parse_tx_mode_str(const std::string& spec);
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif // RADIOTAP_BUILDER_H
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
/* RadiotapPeek — cheap pre-parse of a send_packet-contract buffer (radiotap
|
||||
* header + 802.11 MPDU) used by the send_packets batch packers: validate the
|
||||
* radiotap framing and peek the per-packet CHANNEL hop target WITHOUT building
|
||||
* a descriptor, so the packer can decide URB grouping (a channel change
|
||||
* flushes the pending URB) before handing the frame to the generation's
|
||||
* builder. Generation-neutral; the full parse stays in each HAL. */
|
||||
|
||||
#include <climits> /* INT_MIN — "field absent" sentinel */
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "ChannelFreq.h"
|
||||
/* Codebase convention: the radiotap iterator is C (Radiotap.c), so every
|
||||
* include site wraps the header in extern "C" — this header must too, or an
|
||||
* earlier bare include would poison the later wrapped ones with C++ linkage. */
|
||||
extern "C" {
|
||||
#include "ieee80211_radiotap.h"
|
||||
}
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Validate the buffer's radiotap framing (the same checks every generation's
|
||||
* send_packet front-end does) and return the radiotap header length; 0 on a
|
||||
* malformed buffer (too short / zero / no room for an MPDU). */
|
||||
inline uint16_t radiotap_hdr_len(const uint8_t *packet, size_t length) {
|
||||
if (packet == nullptr || length < sizeof(struct ieee80211_radiotap_header))
|
||||
return 0;
|
||||
const uint16_t rlen = get_unaligned_le16(packet + 2);
|
||||
if (rlen == 0 || static_cast<size_t>(rlen) >= length)
|
||||
return 0;
|
||||
return rlen;
|
||||
}
|
||||
|
||||
/* Peek the radiotap CHANNEL field's hop target: the mapped channel number, or
|
||||
* 0 when the field is absent (or the frequency unmappable). Mirrors the
|
||||
* CHANNEL handling in each generation's send_packet (frequency authoritative,
|
||||
* flags ignored). */
|
||||
inline int radiotap_peek_channel(const uint8_t *packet, size_t length) {
|
||||
const uint16_t rlen = radiotap_hdr_len(packet, length);
|
||||
if (rlen == 0)
|
||||
return 0;
|
||||
auto *hdr = reinterpret_cast<struct ieee80211_radiotap_header *>(
|
||||
const_cast<uint8_t *>(packet));
|
||||
struct ieee80211_radiotap_iterator it;
|
||||
if (ieee80211_radiotap_iterator_init(&it, hdr, rlen, nullptr) != 0)
|
||||
return 0;
|
||||
while (ieee80211_radiotap_iterator_next(&it) == 0) {
|
||||
if (it.this_arg_index == IEEE80211_RADIOTAP_CHANNEL) {
|
||||
const int chan = freq_to_chan(get_unaligned_le16(it.this_arg));
|
||||
return chan > 0 ? chan : 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Peek the radiotap DBM_TX_POWER field (signed per-packet power delta, dB).
|
||||
* Returns INT_MIN when absent — the same "no per-packet power" sentinel the
|
||||
* generations' send_packet parsers use. Lets a batch packer group frames by
|
||||
* requested power, so a power-bank reprogram (Jaguar3) lands between URBs,
|
||||
* never mid-URB. */
|
||||
inline int radiotap_peek_dbm_tx_power(const uint8_t *packet, size_t length) {
|
||||
const uint16_t rlen = radiotap_hdr_len(packet, length);
|
||||
if (rlen == 0)
|
||||
return INT_MIN;
|
||||
auto *hdr = reinterpret_cast<struct ieee80211_radiotap_header *>(
|
||||
const_cast<uint8_t *>(packet));
|
||||
struct ieee80211_radiotap_iterator it;
|
||||
if (ieee80211_radiotap_iterator_init(&it, hdr, rlen, nullptr) != 0)
|
||||
return INT_MIN;
|
||||
while (ieee80211_radiotap_iterator_next(&it) == 0) {
|
||||
if (it.this_arg_index == IEEE80211_RADIOTAP_DBM_TX_POWER)
|
||||
return *reinterpret_cast<const int8_t *>(it.this_arg);
|
||||
}
|
||||
return INT_MIN;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
/* Decoded view of the 3-byte radiotap MCS field (known, flags, index) on the
|
||||
* TX/inject path — the one shared reading for all three generations'
|
||||
* send_packet parsers (J1/J2/J3), so the HT LDPC/STBC known/flag bits can't
|
||||
* silently diverge again. Bit positions per the radiotap MCS spec and
|
||||
* RadiotapBuilder::build_ht. */
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
extern "C" {
|
||||
#include "ieee80211_radiotap.h"
|
||||
}
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct RadiotapMcsField {
|
||||
bool have_mcs = false;
|
||||
uint8_t mcs = 0; /* HT MCS index 0..31, valid when have_mcs */
|
||||
bool bw40 = false; /* MCS BW subfield == 40 MHz */
|
||||
uint8_t sgi = 0;
|
||||
uint8_t ldpc = 0;
|
||||
uint8_t stbc = 0; /* STBC stream count 0..3 */
|
||||
};
|
||||
|
||||
inline RadiotapMcsField decode_radiotap_mcs_field(const uint8_t *arg) {
|
||||
RadiotapMcsField f;
|
||||
const uint8_t known = arg[0];
|
||||
const uint8_t flags = arg[1];
|
||||
if ((flags & IEEE80211_RADIOTAP_MCS_BW_MASK) == IEEE80211_RADIOTAP_MCS_BW_40)
|
||||
f.bw40 = true;
|
||||
f.sgi = (flags & IEEE80211_RADIOTAP_MCS_SGI) ? 1 : 0;
|
||||
if ((known & IEEE80211_RADIOTAP_MCS_HAVE_FEC) &&
|
||||
(flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC))
|
||||
f.ldpc = 1;
|
||||
if (known & IEEE80211_RADIOTAP_MCS_HAVE_STBC) /* flags [6:5] = stream count */
|
||||
f.stbc = (flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >>
|
||||
IEEE80211_RADIOTAP_MCS_STBC_SHIFT;
|
||||
if ((known & IEEE80211_RADIOTAP_MCS_HAVE_MCS) && arg[2] <= 31) {
|
||||
f.have_mcs = true;
|
||||
f.mcs = arg[2];
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,120 @@
|
||||
#ifndef DEVOURER_RATE_DEFINITIONS_H
|
||||
#define DEVOURER_RATE_DEFINITIONS_H
|
||||
|
||||
/* Realtek MGN_* rate enumeration — the driver-internal rate index used across
|
||||
* both chip generations (Jaguar1 RadioManagementModule and Jaguar3
|
||||
* RadioManagementJaguar3). Kept in a neutral header so neither generation's
|
||||
* files depend on the other's. */
|
||||
enum MGN_RATE {
|
||||
MGN_1M = 0x02,
|
||||
MGN_2M = 0x04,
|
||||
MGN_5_5M = 0x0B,
|
||||
MGN_6M = 0x0C,
|
||||
MGN_9M = 0x12,
|
||||
MGN_11M = 0x16,
|
||||
MGN_12M = 0x18,
|
||||
MGN_18M = 0x24,
|
||||
MGN_24M = 0x30,
|
||||
MGN_36M = 0x48,
|
||||
MGN_48M = 0x60,
|
||||
MGN_54M = 0x6C,
|
||||
MGN_MCS32 = 0x7F,
|
||||
MGN_MCS0,
|
||||
MGN_MCS1,
|
||||
MGN_MCS2,
|
||||
MGN_MCS3,
|
||||
MGN_MCS4,
|
||||
MGN_MCS5,
|
||||
MGN_MCS6,
|
||||
MGN_MCS7,
|
||||
MGN_MCS8,
|
||||
MGN_MCS9,
|
||||
MGN_MCS10,
|
||||
MGN_MCS11,
|
||||
MGN_MCS12,
|
||||
MGN_MCS13,
|
||||
MGN_MCS14,
|
||||
MGN_MCS15,
|
||||
MGN_MCS16,
|
||||
MGN_MCS17,
|
||||
MGN_MCS18,
|
||||
MGN_MCS19,
|
||||
MGN_MCS20,
|
||||
MGN_MCS21,
|
||||
MGN_MCS22,
|
||||
MGN_MCS23,
|
||||
MGN_MCS24,
|
||||
MGN_MCS25,
|
||||
MGN_MCS26,
|
||||
MGN_MCS27,
|
||||
MGN_MCS28,
|
||||
MGN_MCS29,
|
||||
MGN_MCS30,
|
||||
MGN_MCS31,
|
||||
MGN_VHT1SS_MCS0,
|
||||
MGN_VHT1SS_MCS1,
|
||||
MGN_VHT1SS_MCS2,
|
||||
MGN_VHT1SS_MCS3,
|
||||
MGN_VHT1SS_MCS4,
|
||||
MGN_VHT1SS_MCS5,
|
||||
MGN_VHT1SS_MCS6,
|
||||
MGN_VHT1SS_MCS7,
|
||||
MGN_VHT1SS_MCS8,
|
||||
MGN_VHT1SS_MCS9,
|
||||
MGN_VHT2SS_MCS0,
|
||||
MGN_VHT2SS_MCS1,
|
||||
MGN_VHT2SS_MCS2,
|
||||
MGN_VHT2SS_MCS3,
|
||||
MGN_VHT2SS_MCS4,
|
||||
MGN_VHT2SS_MCS5,
|
||||
MGN_VHT2SS_MCS6,
|
||||
MGN_VHT2SS_MCS7,
|
||||
MGN_VHT2SS_MCS8,
|
||||
MGN_VHT2SS_MCS9,
|
||||
MGN_VHT3SS_MCS0,
|
||||
MGN_VHT3SS_MCS1,
|
||||
MGN_VHT3SS_MCS2,
|
||||
MGN_VHT3SS_MCS3,
|
||||
MGN_VHT3SS_MCS4,
|
||||
MGN_VHT3SS_MCS5,
|
||||
MGN_VHT3SS_MCS6,
|
||||
MGN_VHT3SS_MCS7,
|
||||
MGN_VHT3SS_MCS8,
|
||||
MGN_VHT3SS_MCS9,
|
||||
MGN_VHT4SS_MCS0,
|
||||
MGN_VHT4SS_MCS1,
|
||||
MGN_VHT4SS_MCS2,
|
||||
MGN_VHT4SS_MCS3,
|
||||
MGN_VHT4SS_MCS4,
|
||||
MGN_VHT4SS_MCS5,
|
||||
MGN_VHT4SS_MCS6,
|
||||
MGN_VHT4SS_MCS7,
|
||||
MGN_VHT4SS_MCS8,
|
||||
MGN_VHT4SS_MCS9,
|
||||
MGN_UNKNOWN
|
||||
};
|
||||
|
||||
/* TX-descriptor RATE_ID (RA group) for a forced-rate injected frame, from the
|
||||
* frame's rate family + NSS + band — the 8822B/8822C-era RATEID_IDX_* table
|
||||
* (vendor ieee80211.h). The group defines the rate-space the firmware retry
|
||||
* ladder walks, and a family-mismatched group is exactly how retries of an
|
||||
* MCS frame end up on the legacy chain (54M..6M on the 8822C, VHT wandering
|
||||
* on the 8822B) — witness-measured per copy, tests/retry_ladder_probe.sh:
|
||||
* with the family-correct group the 8822C fw steps MCSx -> MCS(x-1) -> 6M
|
||||
* floor at 5 GHz (VHT: M7 -> M4 -> M1 -> M0 -> 6M), and at 2.4 GHz the
|
||||
* B-containing group adds the CCK floor. 2SS group rows follow the vendor
|
||||
* table symmetrically (unmeasured — no 2SS retry cell has run). */
|
||||
inline unsigned char rateid_for_mgn(unsigned char mgn, bool band5g) {
|
||||
if (mgn >= MGN_VHT1SS_MCS0) /* VHT: 10 rates per NSS */
|
||||
return mgn >= MGN_VHT2SS_MCS0 ? 9 /* VHT_2SS */ : 10 /* VHT_1SS */;
|
||||
if (mgn >= MGN_MCS0) /* HT */
|
||||
return mgn >= MGN_MCS8 ? (band5g ? 4 /* GN_N2SS */ : 2 /* BGN_20M_2SS */)
|
||||
: (band5g ? 5 /* GN_N1SS */ : 3 /* BGN_20M_1SS */);
|
||||
if (mgn == MGN_MCS32) /* HT duplicate mode — 0x7F sorts BELOW MGN_MCS0 */
|
||||
return band5g ? 5 : 3;
|
||||
if (mgn == MGN_1M || mgn == MGN_2M || mgn == MGN_5_5M || mgn == MGN_11M)
|
||||
return 8; /* B */
|
||||
return band5g ? 7 /* G */ : 6 /* BG */;
|
||||
}
|
||||
|
||||
#endif /* DEVOURER_RATE_DEFINITIONS_H */
|
||||
@@ -0,0 +1,13 @@
|
||||
#ifndef RFPATH_H
|
||||
#define RFPATH_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
enum RfPath : uint8_t {
|
||||
RF_PATH_A = 0,
|
||||
RF_PATH_B = 1,
|
||||
RF_PATH_C = 2,
|
||||
RF_PATH_D = 3,
|
||||
};
|
||||
|
||||
#endif /* RFPATH_H */
|
||||
@@ -0,0 +1,273 @@
|
||||
/* UsbTransport.h (-> libusb.h -> windows.h on Windows) MUST precede the hal
|
||||
* headers: Hal8812PhyReg.h #defines identifiers like `bEnable` that
|
||||
* winuser.h uses as parameter names, so hal-first poisons the Windows headers
|
||||
* (MSVC C2143 inside winuser.h / mingw "expected ','" pointed at the
|
||||
* #define). The pre-seam RtlUsbAdapter.h guaranteed this order by including
|
||||
* libusb.h first; this TU is the only one mixing both after the split. */
|
||||
#include "UsbTransport.h"
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#include "Hal8812PhyReg.h"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
RtlAdapter::RtlAdapter(libusb_device_handle *dev_handle, Logger_t logger,
|
||||
libusb_context *ctx,
|
||||
std::shared_ptr<devourer::UsbDeviceLock> usb_lock,
|
||||
const devourer::DeviceConfig &cfg)
|
||||
: _transport{std::make_shared<devourer::UsbTransport>(
|
||||
dev_handle, logger, ctx, std::move(usb_lock), cfg.usb.rx_zerocopy,
|
||||
cfg.rx.rx_mode, cfg.rx.pool_spare, cfg.rx.ring_ms.value_or(0),
|
||||
cfg.rx.pool_exhaust)},
|
||||
_logger{std::move(logger)} {
|
||||
init_from_transport(cfg);
|
||||
}
|
||||
|
||||
RtlAdapter::RtlAdapter(std::shared_ptr<devourer::ITransport> transport,
|
||||
Logger_t logger, const devourer::DeviceConfig &cfg)
|
||||
: _transport{std::move(transport)}, _logger{std::move(logger)} {
|
||||
init_from_transport(cfg);
|
||||
}
|
||||
|
||||
void RtlAdapter::init_from_transport(const devourer::DeviceConfig &cfg) {
|
||||
_log_writes = cfg.debug.log_writes;
|
||||
_tx_ep_override = cfg.tx.ep;
|
||||
_tx_timeout_ms = cfg.tx.timeout_ms.value_or(500);
|
||||
_usb = _transport->usb_info();
|
||||
|
||||
if (_usb.valid) {
|
||||
if (_usb.speed > 3 /* > LIBUSB_SPEED_HIGH: USB 3.0 */) {
|
||||
rxagg_usb_size = 0x3; /* 16KB */
|
||||
rxagg_usb_timeout = 0x01;
|
||||
} else {
|
||||
/* the setting to reduce RX FIFO overflow on USB2.0 and increase rx
|
||||
* throughput */
|
||||
rxagg_usb_size = 0x1; /* 8KB */
|
||||
rxagg_usb_timeout = 0x01;
|
||||
}
|
||||
|
||||
/* Was GetChipOutEP8812: derive the TX queue selector from the number of
|
||||
* discovered bulk-OUT pipes. */
|
||||
switch (_usb.bulk_out_eps.size()) {
|
||||
case 4:
|
||||
OutEpQueueSel = TX_SELE_HQ | TX_SELE_LQ | TX_SELE_NQ | TX_SELE_EQ;
|
||||
OutEpNumber = 4;
|
||||
break;
|
||||
case 3:
|
||||
OutEpQueueSel = TX_SELE_HQ | TX_SELE_LQ | TX_SELE_NQ;
|
||||
OutEpNumber = 3;
|
||||
break;
|
||||
case 2:
|
||||
OutEpQueueSel = TX_SELE_HQ | TX_SELE_NQ;
|
||||
OutEpNumber = 2;
|
||||
break;
|
||||
case 1:
|
||||
OutEpQueueSel = TX_SELE_HQ;
|
||||
OutEpNumber = 1;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
_logger->info("OutEpQueueSel({}), OutEpNumber({})", (int)OutEpQueueSel,
|
||||
(int)OutEpNumber);
|
||||
}
|
||||
|
||||
uint8_t eeValue = rtw_read8(REG_9346CR);
|
||||
EepromOrEfuse = (eeValue & BOOT_FROM_EEPROM) != 0;
|
||||
AutoloadFailFlag = (eeValue & EEPROM_EN) == 0;
|
||||
|
||||
_logger->info("Boot from {}, Autoload {} !",
|
||||
EepromOrEfuse ? "EEPROM" : "EFUSE",
|
||||
(AutoloadFailFlag ? "Fail" : "OK"));
|
||||
}
|
||||
|
||||
bool RtlAdapter::send_packet(uint8_t *packet, size_t length) {
|
||||
/* TX endpoint selection (USB semantics; the PCIe transport ignores it):
|
||||
* DeviceConfig tx.ep override > first discovered OUT endpoint > historic
|
||||
* 8812AU default (0x02). */
|
||||
const uint8_t tx_ep = _tx_ep_override ? *_tx_ep_override
|
||||
: first_bulk_out_ep();
|
||||
return _transport->tx_async(tx_ep, packet, length, _tx_timeout_ms);
|
||||
}
|
||||
|
||||
void RtlAdapter::rtl8812au_hw_reset() {
|
||||
uint32_t reg_val = 0;
|
||||
|
||||
if ((rtw_read8(REG_MCUFWDL) & BIT7) != 0) {
|
||||
_8051Reset8812();
|
||||
rtw_write8(REG_MCUFWDL, 0x00);
|
||||
|
||||
/* before BB reset should do clock gated */
|
||||
rtw_write32(rFPGA0_XCD_RFPara, rtw_read32(rFPGA0_XCD_RFPara) | (BIT6));
|
||||
|
||||
/* reset BB */
|
||||
reg_val = rtw_read8(REG_SYS_FUNC_EN);
|
||||
reg_val = (uint8_t)(reg_val & ~(BIT0 | BIT1));
|
||||
rtw_write8(REG_SYS_FUNC_EN, (uint8_t)reg_val);
|
||||
|
||||
/* reset RF */
|
||||
rtw_write8(REG_RF_CTRL, 0);
|
||||
|
||||
/* reset TRX path */
|
||||
rtw_write16(REG_CR, 0);
|
||||
|
||||
/* reset MAC */
|
||||
reg_val = rtw_read8(REG_APS_FSMCO + 1);
|
||||
reg_val |= BIT1;
|
||||
rtw_write8(REG_APS_FSMCO + 1,
|
||||
(uint8_t)reg_val); /* reg0x5[1] ,auto FSM off */
|
||||
|
||||
reg_val = rtw_read8(REG_APS_FSMCO + 1);
|
||||
|
||||
/* check if reg0x5[1] auto cleared */
|
||||
while ((reg_val & BIT1) != 0) {
|
||||
std::this_thread::sleep_for(1ms);
|
||||
reg_val = rtw_read8(REG_APS_FSMCO + 1);
|
||||
}
|
||||
|
||||
reg_val |= BIT0;
|
||||
rtw_write8(REG_APS_FSMCO + 1,
|
||||
(uint8_t)reg_val); /* reg0x5[0] ,auto FSM on */
|
||||
|
||||
reg_val = rtw_read8(REG_SYS_FUNC_EN + 1);
|
||||
reg_val = (uint8_t)(reg_val & ~(BIT4 | BIT7));
|
||||
rtw_write8(REG_SYS_FUNC_EN + 1, (uint8_t)reg_val);
|
||||
reg_val = rtw_read8(REG_SYS_FUNC_EN + 1);
|
||||
reg_val = (uint8_t)(reg_val | BIT4 | BIT7);
|
||||
rtw_write8(REG_SYS_FUNC_EN + 1, (uint8_t)reg_val);
|
||||
}
|
||||
}
|
||||
|
||||
void RtlAdapter::_8051Reset8812() {
|
||||
uint8_t u1bTmp, u1bTmp2;
|
||||
|
||||
/* Reset MCU IO Wrapper- sugggest by SD1-Gimmy */
|
||||
u1bTmp2 = rtw_read8(REG_RSV_CTRL);
|
||||
rtw_write8(REG_RSV_CTRL, (uint8_t)(u1bTmp2 & (~BIT1)));
|
||||
u1bTmp2 = rtw_read8(REG_RSV_CTRL + 1);
|
||||
rtw_write8(REG_RSV_CTRL + 1, (uint8_t)(u1bTmp2 & (~BIT3)));
|
||||
|
||||
u1bTmp = rtw_read8(REG_SYS_FUNC_EN + 1);
|
||||
rtw_write8(REG_SYS_FUNC_EN + 1, (uint8_t)(u1bTmp & (~BIT2)));
|
||||
|
||||
/* Enable MCU IO Wrapper */
|
||||
u1bTmp2 = rtw_read8(REG_RSV_CTRL);
|
||||
rtw_write8(REG_RSV_CTRL, (uint8_t)(u1bTmp2 & (~BIT1)));
|
||||
u1bTmp2 = rtw_read8(REG_RSV_CTRL + 1);
|
||||
rtw_write8(REG_RSV_CTRL + 1, (uint8_t)(u1bTmp2 | (BIT3)));
|
||||
|
||||
rtw_write8(REG_SYS_FUNC_EN + 1, (uint8_t)(u1bTmp | (BIT2)));
|
||||
|
||||
_logger->info("=====> _8051Reset8812(): 8051 reset success .");
|
||||
}
|
||||
|
||||
/* 11/16/2008 MH Read one byte from real Efuse. */
|
||||
uint8_t RtlAdapter::efuse_OneByteRead(uint16_t addr, uint8_t *data) {
|
||||
u32 tmpidx = 0;
|
||||
u8 bResult;
|
||||
u8 readbyte;
|
||||
|
||||
/* -----------------e-fuse reg ctrl --------------------------------- */
|
||||
/* address */
|
||||
rtw_write8(EFUSE_CTRL + 1, (u8)(addr & 0xff));
|
||||
rtw_write8(EFUSE_CTRL + 2,
|
||||
((u8)((addr >> 8) & 0x03)) | (rtw_read8(EFUSE_CTRL + 2) & 0xFC));
|
||||
|
||||
/* rtw_write8(pAdapter, EFUSE_CTRL+3, 0x72); */ /* read cmd */
|
||||
/* Write bit 32 0 */
|
||||
readbyte = rtw_read8(EFUSE_CTRL + 3);
|
||||
rtw_write8(EFUSE_CTRL + 3, (readbyte & 0x7f));
|
||||
|
||||
while (!(0x80 & rtw_read8(EFUSE_CTRL + 3)) && (tmpidx < 1000)) {
|
||||
std::this_thread::sleep_for(1ms);
|
||||
tmpidx++;
|
||||
}
|
||||
if (tmpidx < 100) {
|
||||
*data = rtw_read8(EFUSE_CTRL);
|
||||
bResult = true;
|
||||
} else {
|
||||
*data = 0xff;
|
||||
bResult = false;
|
||||
_logger->error("addr=0x{:x} bResult={} time out 1s !!!", addr, bResult);
|
||||
_logger->error("EFUSE_CTRL =0x{:08x} !!!", rtw_read32(EFUSE_CTRL));
|
||||
}
|
||||
|
||||
return bResult;
|
||||
}
|
||||
|
||||
void RtlAdapter::ReadEFuseByte(uint16_t _offset, uint8_t *pbuf) {
|
||||
uint32_t value32;
|
||||
uint8_t readbyte;
|
||||
uint16_t retry;
|
||||
|
||||
/* Match the kernel `88XXau` driver's per-iteration EFUSE_TEST clear.
|
||||
* Cold-init usbmon diff (2026-05-28, devourer-testrig VM kernel-side
|
||||
* vs host devourer-side) shows the kernel does an RD-then-WR sequence
|
||||
* at REG_EFUSE_TEST (0x0034) = 0x0000 (16-bit) BEFORE every EFUSE byte
|
||||
* read, 312 times per init; devourer never touched 0x0034. We mirror
|
||||
* the sequence so the EFUSE state machine sees identical wire shape
|
||||
* across all 312 byte reads. Empirically harmless on its own (does
|
||||
* NOT fix the RTL8814AU TX-on-air gate per a sniffer run with this
|
||||
* patch + bulk-IN drainer enabled) but removes a known concrete
|
||||
* wire-level divergence flagged by tools/usbmon_pcap_diff.py. */
|
||||
(void)rtw_read16(REG_EFUSE_TEST);
|
||||
rtw_write16(REG_EFUSE_TEST, 0x0000);
|
||||
|
||||
/* Write Address */
|
||||
rtw_write8(EFUSE_CTRL + 1, (uint8_t)(_offset & 0xff));
|
||||
readbyte = rtw_read8(EFUSE_CTRL + 2);
|
||||
rtw_write8(EFUSE_CTRL + 2,
|
||||
(uint8_t)(((_offset >> 8) & 0x03) | (readbyte & 0xfc)));
|
||||
|
||||
/* Write bit 32 0 */
|
||||
readbyte = rtw_read8(EFUSE_CTRL + 3);
|
||||
rtw_write8(EFUSE_CTRL + 3, (uint8_t)(readbyte & 0x7f));
|
||||
|
||||
/* Check bit 32 read-ready */
|
||||
retry = 0;
|
||||
value32 = rtw_read32(EFUSE_CTRL);
|
||||
/* while(!(((value32 >> 24) & 0xff) & 0x80) && (retry<10)) */
|
||||
while ((((value32 >> 24) & 0xff) & 0x80) == 0 && (retry < 10000)) {
|
||||
value32 = rtw_read32(EFUSE_CTRL);
|
||||
retry++;
|
||||
}
|
||||
|
||||
/* 20100205 Joseph: Add delay suggested by SD1 Victor. */
|
||||
/* This fix the problem that Efuse read error in high temperature condition.
|
||||
*/
|
||||
/* Designer says that there shall be some delay after ready bit is set, or the
|
||||
*/
|
||||
/* result will always stay on last data we read. */
|
||||
|
||||
// TODO: decide to we really need it?
|
||||
// std::this_thread::sleep_for(50ms);
|
||||
value32 = rtw_read32(EFUSE_CTRL);
|
||||
|
||||
pbuf[0] = (uint8_t)(value32 & 0xff);
|
||||
}
|
||||
|
||||
void RtlAdapter::phy_set_bb_reg(uint16_t regAddr, uint32_t bitMask,
|
||||
uint32_t data) {
|
||||
PHY_SetBBReg8812(regAddr, bitMask, data);
|
||||
}
|
||||
|
||||
void RtlAdapter::PHY_SetBBReg8812(uint16_t regAddr, uint32_t bitMask,
|
||||
uint32_t dataOriginal) {
|
||||
uint32_t data = dataOriginal;
|
||||
if (bitMask != bMaskDWord) {
|
||||
/* if not "double word" write */
|
||||
auto OriginalValue = rtw_read32(regAddr);
|
||||
auto BitShift = PHY_CalculateBitShift(bitMask);
|
||||
data = ((OriginalValue) & (~bitMask)) |
|
||||
(((dataOriginal << (int)BitShift)) & bitMask);
|
||||
}
|
||||
|
||||
rtw_write32(regAddr, data);
|
||||
|
||||
/* RTW_INFO("BBW MASK=0x%x Addr[0x%x]=0x%x\n", BitMask, RegAddr, Data); */
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
#ifndef RTLADAPTER_H
|
||||
#define RTLADAPTER_H
|
||||
|
||||
/* RtlAdapter — the bus-neutral register/frame accessor every HAL component
|
||||
* holds BY VALUE (a copyable value type; every copy shares the one transport
|
||||
* via shared_ptr, so the transport — and with it the USB device lock or the
|
||||
* vfio fds + DMA rings — lives until the last copy dies).
|
||||
*
|
||||
* The bus specifics live behind ITransport (src/Transport.h): USB =
|
||||
* devourer::UsbTransport (libusb vendor-control registers + bulk endpoints),
|
||||
* PCIe = devourer::PcieTransport (BAR2 MMIO registers + 88xx DMA rings). The
|
||||
* adapter itself carries only bus-neutral chip helpers built on the register
|
||||
* plane (EFUSE byte reads, phy_set_bb_reg, the 8812 resets) plus the
|
||||
* config-derived knobs, and forwards the frame plane.
|
||||
*
|
||||
* (Historically this class WAS the USB transport; the old `RtlUsbAdapter`
|
||||
* name remains as a deprecated alias in RtlUsbAdapter.h.) */
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
#ifdef _WIN32
|
||||
/* The hal headers below lean on Windows types (BOOLEAN/VOID in rtw_efuse.h)
|
||||
* and #define identifiers winuser.h uses as parameter names (bEnable in
|
||||
* Hal8812PhyReg.h) — windows.h must be included BEFORE them, project-wide.
|
||||
* The pre-seam RtlUsbAdapter.h guaranteed this implicitly by including
|
||||
* libusb.h (-> windows.h) first; with libusb gone from this header, make the
|
||||
* dependency explicit. */
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include "DeviceConfig.h"
|
||||
#include "Transport.h"
|
||||
#include "TxStats.h"
|
||||
#include "drv_types.h"
|
||||
#include "hal_com_reg.h"
|
||||
#include "logger.h"
|
||||
|
||||
struct libusb_device_handle;
|
||||
struct libusb_context;
|
||||
namespace devourer {
|
||||
class UsbDeviceLock;
|
||||
}
|
||||
|
||||
#define rtw_read8 rtw_read<uint8_t>
|
||||
#define rtw_read16 rtw_read<uint16_t>
|
||||
#define rtw_read32 rtw_read<uint32_t>
|
||||
|
||||
#define rtw_write8 rtw_write<uint8_t>
|
||||
#define rtw_write16 rtw_write<uint16_t>
|
||||
#define rtw_write32 rtw_write<uint32_t>
|
||||
|
||||
enum TxSele {
|
||||
TX_SELE_HQ = 1 << (0), /* High Queue */
|
||||
TX_SELE_LQ = 1 << (1), /* Low Queue */
|
||||
TX_SELE_NQ = 1 << (2), /* Normal Queue */
|
||||
TX_SELE_EQ = 1 << (3), /* Extern Queue */
|
||||
};
|
||||
|
||||
class RtlAdapter {
|
||||
std::shared_ptr<devourer::ITransport> _transport;
|
||||
Logger_t _logger;
|
||||
|
||||
/* USB-descriptor-derived facts (defaults on PCIe), mirrored at construction
|
||||
* for the HALs that consume them (Jaguar1 queue mapping, RX-agg sizing). */
|
||||
devourer::UsbLinkInfo _usb;
|
||||
|
||||
/* From DeviceConfig (see there for semantics). Plain values — RtlAdapter
|
||||
* is a copyable value type, every copy carries them. */
|
||||
bool _log_writes = false; /* debug.log_writes */
|
||||
std::optional<uint8_t> _tx_ep_override; /* tx.ep */
|
||||
unsigned _tx_timeout_ms = 500; /* tx.timeout_ms */
|
||||
|
||||
public:
|
||||
/* USB: wraps the handle in a devourer::UsbTransport. The signature is the
|
||||
* historic one so USB construction sites are unchanged. */
|
||||
RtlAdapter(libusb_device_handle *dev_handle, Logger_t logger,
|
||||
libusb_context *ctx = nullptr,
|
||||
std::shared_ptr<devourer::UsbDeviceLock> usb_lock = nullptr,
|
||||
const devourer::DeviceConfig &cfg = {});
|
||||
/* Any transport (the PCIe factory path; also the seam for future buses). */
|
||||
RtlAdapter(std::shared_ptr<devourer::ITransport> transport,
|
||||
Logger_t logger, const devourer::DeviceConfig &cfg = {});
|
||||
|
||||
bool is_usb() const { return _transport->is_usb(); }
|
||||
/* Pre-power-on HCI programming (rtw88 rtw_hci_setup slot): PCIe TRX ring
|
||||
* registers; no-op on USB. Call per bring-up attempt, before power-on. */
|
||||
void hci_setup() { _transport->hci_setup(); }
|
||||
|
||||
/* Kernel-style async RX: keep n_urbs concurrent bulk-IN transfers in flight
|
||||
* (USB) or reap the RX buffer-descriptor ring (PCIe), invoking
|
||||
* on_data(buf,len) per delivery until `stop`. */
|
||||
void bulk_read_async_loop(int buf_size, int n_urbs,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop) {
|
||||
_transport->rx_loop(buf_size, n_urbs, on_data, should_stop);
|
||||
}
|
||||
/* Convenience overload for callers whose stop condition is a single flag. */
|
||||
void bulk_read_async_loop(int buf_size, int n_urbs,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const volatile bool &stop) {
|
||||
bulk_read_async_loop(buf_size, n_urbs, on_data,
|
||||
[&stop]() -> bool { return stop; });
|
||||
}
|
||||
|
||||
uint16_t idVendor() const { return _usb.vid; }
|
||||
uint16_t idProduct() const { return _usb.pid; }
|
||||
int speed() const { return _usb.speed; }
|
||||
/* First discovered bulk-OUT endpoint (HQ-equivalent), or 0x02 if none were
|
||||
* discovered. Used by the DLFW rsvd-page download; ignored by the PCIe
|
||||
* transport (its ring is chosen from the descriptor QSEL). */
|
||||
uint8_t first_bulk_out_ep() const {
|
||||
return _usb.bulk_out_eps.empty() ? 0x02 : _usb.bulk_out_eps[0];
|
||||
}
|
||||
/* Nth discovered bulk-OUT endpoint in descriptor order (0-based), or 0 if
|
||||
* out of range. The Kestrel FWDL/H2C path needs the CH12 endpoint, which the
|
||||
* vendor USB layer maps as BULKOUTID2 = the 3rd bulk-OUT (RtOutPipe[2]). */
|
||||
uint8_t nth_bulk_out_ep(size_t n) const {
|
||||
return n < _usb.bulk_out_eps.size() ? _usb.bulk_out_eps[n] : 0;
|
||||
}
|
||||
size_t bulk_out_ep_count() const { return _usb.bulk_out_eps.size(); }
|
||||
|
||||
bool AutoloadFailFlag = false;
|
||||
bool EepromOrEfuse = false;
|
||||
uint8_t OutEpQueueSel = 0;
|
||||
uint8_t OutEpNumber = 0;
|
||||
uint8_t rxagg_usb_size = 0;
|
||||
uint8_t rxagg_usb_timeout = 0;
|
||||
|
||||
bool send_packet(uint8_t *packet, size_t length);
|
||||
/* Synchronous TX that blocks until completion or timeout. Returns bytes
|
||||
* submitted, or negative on error. */
|
||||
int bulk_send_sync(uint8_t *packet, size_t length, int timeout_ms) {
|
||||
return bulk_send_sync_ep(0x02, packet, length, timeout_ms);
|
||||
}
|
||||
int bulk_send_sync_ep(uint8_t ep, uint8_t *packet, size_t length,
|
||||
int timeout_ms) {
|
||||
return _transport->tx_sync(ep, packet, length, timeout_ms);
|
||||
}
|
||||
void bulk_clear_halt(uint8_t ep) { _transport->clear_halt(ep); }
|
||||
|
||||
/* Stop TX and wait out everything already submitted (ITransport::
|
||||
* quiesce_tx). Must run while the caller's bus context is still alive —
|
||||
* the device Stop()/destructor does it, so callers rarely need this. */
|
||||
void quiesce_tx() { _transport->quiesce_tx(); }
|
||||
|
||||
/* Snapshot of the TX submission counters (see TxStats.h). */
|
||||
devourer::TxStats GetTxStats() const { return _transport->tx_stats(); }
|
||||
|
||||
/* Raw single-shot RX read (USB bulk-IN; -1 on PCIe — its RX is the ring
|
||||
* reap in bulk_read_async_loop). */
|
||||
int bulk_read_raw(uint8_t *buf, int len, int timeout_ms) {
|
||||
return _transport->rx_raw(buf, len, timeout_ms);
|
||||
}
|
||||
|
||||
uint8_t efuse_OneByteRead(uint16_t addr, uint8_t *data);
|
||||
void phy_set_bb_reg(uint16_t regAddr, uint32_t bitMask, uint32_t data);
|
||||
|
||||
/* 32-bit-address register write (see ITransport::write32_wide) — the
|
||||
* halbb/halrf BB window lives at addr + 0x10000 (wIndex=1 over USB), out of
|
||||
* reach of the 16-bit rtw_write path. */
|
||||
bool rtw_write32_wide(uint32_t addr, uint32_t value) {
|
||||
return _transport->write32_wide(addr, value);
|
||||
}
|
||||
uint32_t rtw_read32_wide(uint32_t addr) {
|
||||
return _transport->read32_wide(addr);
|
||||
}
|
||||
|
||||
template <typename T> T rtw_read(uint16_t reg_num) {
|
||||
if constexpr (sizeof(T) == 1)
|
||||
return _transport->read8(reg_num);
|
||||
else if constexpr (sizeof(T) == 2)
|
||||
return _transport->read16(reg_num);
|
||||
else
|
||||
return _transport->read32(reg_num);
|
||||
}
|
||||
|
||||
template <typename T> bool rtw_write(uint16_t reg_num, T value) {
|
||||
/* debug.log_writes: emit every register write as a debug.wreg event
|
||||
* (addr/width/val mirror tests/decode_wseq.py's tuple) so devourer's
|
||||
* bring-up write set can be diffed against the kernel golden — on either
|
||||
* bus. */
|
||||
if (_log_writes)
|
||||
devourer::Ev(_logger->events(), "debug.wreg")
|
||||
.hexf("addr", reg_num, 4)
|
||||
.f("width", sizeof(T))
|
||||
.hexf("val", (unsigned long long)value, (int)(sizeof(T) * 2));
|
||||
if constexpr (sizeof(T) == 1)
|
||||
return _transport->write8(reg_num, value);
|
||||
else if constexpr (sizeof(T) == 2)
|
||||
return _transport->write16(reg_num, value);
|
||||
else
|
||||
return _transport->write32(reg_num, value);
|
||||
}
|
||||
|
||||
bool WriteBytes(uint16_t reg_num, uint8_t *ptr, size_t size) {
|
||||
return _transport->write_bytes(reg_num, ptr, size);
|
||||
}
|
||||
|
||||
void rtl8812au_hw_reset();
|
||||
void _8051Reset8812();
|
||||
void ReadEFuseByte(uint16_t _offset, uint8_t *pbuf);
|
||||
|
||||
private:
|
||||
void init_from_transport(const devourer::DeviceConfig &cfg);
|
||||
void PHY_SetBBReg8812(uint16_t regAddr, uint32_t bitMask,
|
||||
uint32_t dataOriginal);
|
||||
};
|
||||
|
||||
#endif /* RTLADAPTER_H */
|
||||
@@ -0,0 +1,13 @@
|
||||
#ifndef RTLUSBADAPTER_H
|
||||
#define RTLUSBADAPTER_H
|
||||
|
||||
/* Compatibility shim. The class once named RtlUsbAdapter is now the
|
||||
* bus-neutral RtlAdapter (src/RtlAdapter.h); the USB wire specifics moved to
|
||||
* devourer::UsbTransport (src/UsbTransport.h) behind the ITransport seam
|
||||
* (src/Transport.h). Prefer RtlAdapter in new code. */
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
|
||||
using RtlUsbAdapter = RtlAdapter;
|
||||
|
||||
#endif /* RTLUSBADAPTER_H */
|
||||
@@ -0,0 +1,174 @@
|
||||
#ifndef DEVOURER_RX_PACKET_H
|
||||
#define DEVOURER_RX_PACKET_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
|
||||
/* Parsed RX packet types, shared across chip generations. The per-generation
|
||||
* frame parsers (Jaguar1 FrameParser, Jaguar3 FrameParserJaguar3) both produce
|
||||
* `Packet`s; the USB adapter and demos consume them. Kept neutral so neither
|
||||
* generation depends on the other's parser header. */
|
||||
|
||||
enum class RX_PACKET_TYPE
|
||||
{
|
||||
NORMAL_RX, /* Normal rx packet */
|
||||
TX_REPORT1, /* CCX */
|
||||
TX_REPORT2, /* TX RPT */
|
||||
HIS_REPORT, /* USB HISR RPT */
|
||||
C2H_PACKET
|
||||
};
|
||||
|
||||
/* How much of an rx_pkt_attrib's signal block a PHY-status report actually
|
||||
* filled. Reports are paged/typed per generation — a CCK page carries only
|
||||
* path-A power, while the per-stream EVM/SNR and the CFO tail live on one OFDM
|
||||
* page only — so a plain bool cannot tell a caller which of the fields below
|
||||
* are a measurement and which are still zero. Feeding an unfilled field into a
|
||||
* running average is not a null operation: it drags the mean toward zero. */
|
||||
enum class PhyStsFill : uint8_t
|
||||
{
|
||||
None, /* nothing filled: no report, too short, or a layout not decoded */
|
||||
Power, /* per-path RSSI, plus ldpc/stbc/bw on an OFDM page */
|
||||
Full /* Power, plus per-stream EVM/SNR and the path-A CFO tail */
|
||||
};
|
||||
|
||||
struct rx_pkt_attrib
|
||||
{
|
||||
uint16_t pkt_len;
|
||||
/* RX-descriptor PHY-status bit: the PHY wrote a status report into THIS
|
||||
* frame's drvinfo area. It is the RAW descriptor bit on every generation
|
||||
* that decodes it (Jaguar1, Jaguar2, Jaguar3, RTL8733B) — deliberately NOT
|
||||
* "the report parsed" and NOT "the signal fields below are valid", since a
|
||||
* parser can still decline an unrecognised page (that is PhyStsFill's job,
|
||||
* kept in a local at the parse site). The drvinfo area is reserved on every
|
||||
* frame (RX_DRVINFO_SZ is a global register), so this bit is the only thing
|
||||
* separating a written report from stale bytes left by an earlier frame —
|
||||
* notably on all-but-one subframe of an A-MPDU. Never set on Kestrel, whose
|
||||
* PHY status arrives as its own PPDU-status frame rather than in drvinfo. */
|
||||
bool physt;
|
||||
uint8_t drvinfo_sz;
|
||||
uint8_t shift_sz;
|
||||
bool qos;
|
||||
uint8_t priority;
|
||||
bool mdata;
|
||||
uint16_t seq_num;
|
||||
uint8_t frag_num;
|
||||
bool mfrag;
|
||||
bool bdecrypted;
|
||||
uint8_t encrypt; /* when 0 indicate no encrypt. when non-zero, indicate the
|
||||
encrypt algorith */
|
||||
bool crc_err;
|
||||
bool icv_err;
|
||||
/* TSF low (4 bytes at RX-descriptor offset 20) — chip-side timestamp
|
||||
* for the frame. With the seq_num just above it, a downstream layer
|
||||
* can drop duplicates by seq and measure one-way latency by diffing
|
||||
* the chip's TSF against its own wall clock. Populated by
|
||||
* FrameParser; surfaced through examples/rx/main.cpp's rx.frame event. */
|
||||
uint32_t tsfl;
|
||||
/* AX/VHT datarate code is 9-bit (HT 0x80+, VHT 0x100+, HE 0x180+), so a
|
||||
* uint8_t truncates the format bits — VHT2SS+ and every HE rate collapse
|
||||
* onto an HT/legacy code. Kept 16-bit so the reported RX rate is truthful
|
||||
* (needed to identify HE frames when a Kestrel acts as an HE monitor). */
|
||||
uint16_t data_rate;
|
||||
uint8_t bw;
|
||||
uint8_t stbc;
|
||||
uint8_t ldpc;
|
||||
uint8_t sgi;
|
||||
/* Descrambler seed the chip recovered from this frame's SERVICE field.
|
||||
* Trustworthy only on RTL8814AU (see FrameParser.cpp); surfaced for the
|
||||
* DEVOURER_DUMP_SCRAMBLER hook in examples/rx/main.cpp. */
|
||||
uint8_t scrambler;
|
||||
/* RSSI / SNR per RF path: A, B (Jaguar 8812/8811) plus C, D (8814AU). On
|
||||
* non-8814 chips the [2..3] slots are zero — the upstream RX phy-status
|
||||
* report reserves those bytes when only 2 paths are active. */
|
||||
uint8_t rssi[4];
|
||||
int8_t snr[4];
|
||||
/* Per-stream RX EVM (A,B on 8812/8811; plus C,D on 8814). Raw RX-status
|
||||
* bytes — a link-quality metric, NOT a per-subcarrier or content signal.
|
||||
* Surfaced for the DEVOURER_DUMP_BODY Tier-2 health diagnostic. */
|
||||
int8_t evm[4];
|
||||
/* Path-A CFO tail from the OFDM phy-status (signed HW units; kHz = raw *
|
||||
* 2.5, phydm CFO_HW_RPT_2_KHZ). The carrier-frequency offset between this
|
||||
* receiver's crystal and the transmitter's — the closed-loop CFO tracker's
|
||||
* input (see IRtlRadio::SetXtalCap). 0 when the phy-status carries none. */
|
||||
int8_t cfo_tail = 0;
|
||||
/* A-MPDU RX markers. paggr: this MPDU arrived inside an aggregated PPDU
|
||||
* (rx-desc PAGGR — 8812 dword1[15], same position in the halmac layout).
|
||||
* ppdu_cnt (halmac only): the MAC's 2-bit received-PPDU counter —
|
||||
* consecutive frames sharing a value shared one PPDU, THE ground-truth
|
||||
* A-MPDU detection signal on the RX side (with paggr and the fact that
|
||||
* only an aggregate's first subframe carries a PHY status). */
|
||||
bool paggr = false;
|
||||
uint8_t ppdu_cnt = 0;
|
||||
/* RX PPDU format classification (AX RX-descriptor dword1[3:0], Kestrel
|
||||
* only): 0/1=CCK 2=OFDM 3=HT 5/6=VHT 7=HE_SU 8=HE_ERSU 9=HE_MU 10=HE_TB.
|
||||
* The proof a received frame really was the HE ER SU extended-range
|
||||
* format. 0xff on pre-AX generations (their descriptors carry no such
|
||||
* field). */
|
||||
uint8_t ppdu_type = 0xff;
|
||||
/* Whether Data still carries the trailing 4-byte FCS.
|
||||
*
|
||||
* True on every Realtek generation, because each sets the MAC's append-FCS
|
||||
* bit at init (RCR_APPFCS on Jaguar1/2, bit 31 of RCR on Jaguar3 and
|
||||
* 8733B, B_AX_APPEND_FCS on Kestrel), so the RX descriptor's PKT_LEN
|
||||
* already counts those four bytes and the parser slices them in.
|
||||
*
|
||||
* False on MediaTek MT7612U: that MAC strips the FCS, and the four bytes
|
||||
* following the MPDU are the FCE info trailer, not a checksum (CRC-32
|
||||
* matched them on 0 of 4263 measured frames — docs/mt7612u.md). A consumer
|
||||
* that removes four bytes there deletes real payload.
|
||||
*
|
||||
* Defaulted true so a parser that does not set it keeps the historical
|
||||
* contract; adding this therefore changes nothing for existing backends.
|
||||
* It is per-frame rather than an AdapterCaps entry because the consumers
|
||||
* that need it — devourer::bf::parse_report() above all — are free
|
||||
* functions handed a pointer and a length, with no device in reach. */
|
||||
bool fcs_present = true;
|
||||
RX_PACKET_TYPE pkt_rpt_type;
|
||||
};
|
||||
|
||||
struct Packet
|
||||
{
|
||||
rx_pkt_attrib RxAtrib;
|
||||
/* The 802.11 frame. It carries the trailing FCS when
|
||||
* RxAtrib.fcs_present is set, which is the case on every Realtek
|
||||
* generation; a consumer that strips four bytes MUST check that flag
|
||||
* rather than assume, because the MediaTek backend delivers no FCS.
|
||||
* Keeping the FCS where the hardware supplies it lets
|
||||
* DEVOURER_RX_KEEP_CORRUPTED and fused-FEC salvage inspect a failed frame,
|
||||
* and tools/bf_report_decode.py trims those four bytes when decoding
|
||||
* beamforming reports (it reads the `fcs` field of the bf.report_raw
|
||||
* event to know whether to). */
|
||||
std::span<uint8_t> Data;
|
||||
|
||||
/* The transmitter's hardware TX-egress TSF, when the frame carries one.
|
||||
*
|
||||
* For the frames the 802.11 MAC regenerates itself — beacons and probe
|
||||
* responses — the sender's MAC overwrites the 8-byte timestamp field (MPDU
|
||||
* bytes 24-31) with its live TSF at the instant the frame is clocked onto
|
||||
* the air. That is a genuine hardware TX-egress timestamp, latched below the
|
||||
* CSMA/queueing layer (bench-measured sub-µs against an independent
|
||||
* receiver, vs ~100+ µs for any host-side "read the clock after send"
|
||||
* approximation). Paired with RxAtrib.tsfl (this receiver's hardware RX
|
||||
* timestamp), each such frame yields the {remote egress, local arrival}
|
||||
* pair that one-way hardware time distribution is built on — with no
|
||||
* host-clock jitter on either end, and against any beaconing AP, not just a
|
||||
* devourer transmitter.
|
||||
*
|
||||
* Returns nullopt for frames the MAC does not stamp (data frames and mgmt
|
||||
* frames other than beacon / probe-response). */
|
||||
std::optional<uint64_t> TxEgressTsf() const
|
||||
{
|
||||
if (Data.size() < 32)
|
||||
return std::nullopt;
|
||||
const uint8_t fc0 = Data[0]; /* proto=0, type=mgmt, subtype in [7:4] */
|
||||
if (fc0 != 0x80 /* beacon */ && fc0 != 0x50 /* probe response */)
|
||||
return std::nullopt;
|
||||
uint64_t tsf = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
tsf |= static_cast<uint64_t>(Data[24 + i]) << (8 * i);
|
||||
return tsf;
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* DEVOURER_RX_PACKET_H */
|
||||
@@ -0,0 +1,55 @@
|
||||
#ifndef DEVOURER_RX_PARSE_ABORT_H
|
||||
#define DEVOURER_RX_PARSE_ABORT_H
|
||||
|
||||
/* rx.parse_abort — the RX descriptor walk hit a malformed/truncated
|
||||
* descriptor mid-aggregate and abandoned the rest of the bulk-IN buffer.
|
||||
* Every abandoned frame was already admitted by the chip (and, with an ACK
|
||||
* responder armed, already ACKed to the peer), so this is post-admission
|
||||
* loss a hardware-ARQ peer counts as delivered — it must never be silent.
|
||||
* Normal end-of-aggregate zero padding (all-zero remainder) is excluded.
|
||||
* Shared by every generation's RX walk; schema: docs/logging.md. */
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "Event.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
inline bool rx_parse_remainder_is_zero_padding(const uint8_t *rem,
|
||||
size_t rem_len) {
|
||||
for (size_t i = 0; i < rem_len; ++i)
|
||||
if (rem[i] != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Returns true when an event was emitted, false for benign all-zero padding
|
||||
* or a disabled event sink. `total` is the caller's cumulative emitted-abort
|
||||
* counter. Call rx_parse_remainder_is_zero_padding() when classification must
|
||||
* remain independent of whether event output is enabled. */
|
||||
inline bool emit_rx_parse_abort(EventSink &sink, const uint8_t *rem,
|
||||
size_t rem_len, long long off,
|
||||
long long buf_len, long long frame_len,
|
||||
long long drvinfo, long long shift,
|
||||
long long &total) {
|
||||
if (rx_parse_remainder_is_zero_padding(rem, rem_len))
|
||||
return false;
|
||||
if (!sink.enabled())
|
||||
return false;
|
||||
++total;
|
||||
Ev(sink, "rx.parse_abort")
|
||||
.t()
|
||||
.f("off", off)
|
||||
.f("buf_len", buf_len)
|
||||
.f("remaining", static_cast<long long>(rem_len))
|
||||
.f("frame_len", frame_len)
|
||||
.f("drvinfo", drvinfo)
|
||||
.f("shift", shift)
|
||||
.f("total", total);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_RX_PARSE_ABORT_H */
|
||||
@@ -0,0 +1,384 @@
|
||||
/* Runtime RX link-quality feed — the consolidated per-window snapshot a
|
||||
* closed-loop adaptive-link controller (e.g. an alink / Fluke-style GS) reads
|
||||
* to steer the link, WITHOUT scraping the demo's stdout.
|
||||
*
|
||||
* devourer already exposes per-frame RSSI/SNR/EVM (the Packet callback) and
|
||||
* frame-free FA/CCA/IGI (GetRxEnergy), but the windowing + the LinkHealth
|
||||
* verdict lived only in examples/rx/main.cpp. This promotes that into the library: the
|
||||
* device aggregates per-frame RX quality internally, and GetRxQuality() returns
|
||||
* one struct fusing the frame aggregate, the frame-free energy, a passive
|
||||
* noise-floor estimate, and the plain-language verdict.
|
||||
*
|
||||
* NOISE FLOOR (passive): per decoded OFDM/HT frame, the effective noise+
|
||||
* interference floor the receiver sees is nf_dbm = rssi_dbm - snr_db =
|
||||
* (rssi_raw - 110) - snr_raw/2. It's a PASSIVE estimate — updated only when a
|
||||
* wanted frame arrives — but that is exactly the self-jamming quantity: raising
|
||||
* TX power on a near-field link raises reflections into the front end, SNR drops
|
||||
* while RSSI holds, so this rises (the "decrease txpower until NF returns to
|
||||
* normal" signal). Works on every family, including Jaguar3 where IGI can't
|
||||
* (no background DIG). The frame-free ABSOLUTE idle floor is a separate, heavier
|
||||
* measurement (see the active noise-floor path).
|
||||
*/
|
||||
#ifndef DEVOURER_RX_QUALITY_H
|
||||
#define DEVOURER_RX_QUALITY_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
|
||||
#include "LinkHealth.h"
|
||||
#include "RxSense.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Windowed RX link-quality snapshot. Angles: frame-driven aggregate
|
||||
* (rssi/snr/evm/noise-floor), frame-free energy (fa/cca/igi), and the fused
|
||||
* LinkHealth verdict. `valid` is false when no frames were decoded in the
|
||||
* window. Converted units (dBm / dB) so a controller doesn't repeat the raw
|
||||
* conversions. */
|
||||
struct RxQuality {
|
||||
bool valid = false;
|
||||
uint32_t frames = 0;
|
||||
|
||||
int rssi_mean_dbm = 0; /* window mean of path-A PWDB (raw - 110) */
|
||||
int rssi_max_dbm = 0; /* window peak — the strength signal (see LinkHealth) */
|
||||
double snr_mean_db = 0.0;
|
||||
double snr_min_db = 0.0;
|
||||
/* false when no frame in the window carried SNR (a CCK-only or non-type1
|
||||
* phy-status window); snr_mean_db / snr_min_db are 0 then, and are a mean
|
||||
* over the reporting frames only otherwise — not over every decoded frame. */
|
||||
bool snr_valid = false;
|
||||
double evm_mean_db = 0.0; /* 0 when evm_valid is false */
|
||||
bool evm_valid = false;
|
||||
|
||||
/* Passive noise-floor estimate (dBm), mean of per-frame rssi_dbm - snr_db
|
||||
* over OFDM/HT frames in the window. nf_valid false if none carried SNR. */
|
||||
double noise_floor_dbm = 0.0;
|
||||
bool nf_valid = false;
|
||||
|
||||
/* Active/frame-free ABSOLUTE noise floor (dBm) — the companion to the passive
|
||||
* floor above: the vendor idle-noise monitor, measured with no wanted signal
|
||||
* (site survey / channel selection). Present only when the caller opted in
|
||||
* (DEVOURER_RX_NOISE_FLOOR) and the generation supports it (Jaguar2 live,
|
||||
* Jaguar1 8812A/8821A RX-idle CAL; false elsewhere). */
|
||||
int8_t abs_noise_floor_dbm = 0;
|
||||
bool abs_nf_valid = false;
|
||||
|
||||
/* Frame-free energy (from GetRxEnergy — GetRxQuality subsumes it). */
|
||||
bool energy_valid = false;
|
||||
uint32_t fa_ofdm = 0;
|
||||
uint32_t cca_ofdm = 0;
|
||||
bool igi_valid = false;
|
||||
int igi = 0;
|
||||
|
||||
/* Fused verdict (classify_link_health). */
|
||||
LinkVerdict verdict = LinkVerdict::NoSignal;
|
||||
const char *label = "NO_SIGNAL";
|
||||
const char *cause = "";
|
||||
const char *fix = "";
|
||||
bool igi_at_floor = false;
|
||||
bool igi_at_ceiling = false;
|
||||
};
|
||||
|
||||
/* Drained per-window aggregate in raw devourer units (the accumulator's
|
||||
* output). Kept separate from RxQuality so the unit conversion + verdict live
|
||||
* in one place (build_rx_quality). */
|
||||
struct RxQualitySnapshot {
|
||||
uint32_t frames = 0;
|
||||
int rssi_mean_raw = 0;
|
||||
int rssi_max_raw = 0;
|
||||
int snr_mean_raw = 0;
|
||||
int snr_min_raw = 0;
|
||||
bool snr_valid = false; /* false when no frame in the window carried SNR */
|
||||
int evm_mean_raw = 0;
|
||||
bool evm_valid = false;
|
||||
double nf_mean_dbm = 0.0;
|
||||
bool nf_valid = false;
|
||||
};
|
||||
|
||||
/* Thread-safe rolling per-frame accumulator. The device feeds add() from the RX
|
||||
* loop for every decoded frame; a controller (or the energy emitter) drains it
|
||||
* with snapshot() on its own cadence. Mirrors the demo's RxAgg with a
|
||||
* passive-noise-floor term added. */
|
||||
class RxQualityAccumulator {
|
||||
public:
|
||||
/* Raw path-A values straight off rx_pkt_attrib. A frame with no phy-status
|
||||
* power (rssi_raw <= 0) is not a quality sample and is skipped. SNR/EVM are
|
||||
* folded only when present (raw != 0 — CCK / non-type1 phy-status leaves them
|
||||
* 0), so a mixed stream doesn't bias those means toward zero; snr_min_raw
|
||||
* likewise ignores the absent ones rather than pinning itself to 0. Each
|
||||
* carries its own sample count, so the window means are over the frames that
|
||||
* actually reported the metric. */
|
||||
void add(int rssi_raw, int snr_raw, int evm_raw) {
|
||||
if (rssi_raw <= 0)
|
||||
return;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
++n_;
|
||||
rssi_sum_ += rssi_raw;
|
||||
if (rssi_raw > rssi_max_)
|
||||
rssi_max_ = rssi_raw;
|
||||
if (snr_raw != 0) {
|
||||
snr_sum_ += snr_raw;
|
||||
++snr_n_;
|
||||
if (snr_raw < snr_min_)
|
||||
snr_min_ = snr_raw;
|
||||
}
|
||||
if (evm_raw != 0) {
|
||||
evm_sum_ += evm_raw;
|
||||
++evm_n_;
|
||||
}
|
||||
if (snr_raw != 0) {
|
||||
nf_sum_ += (rssi_raw - 110) - snr_raw / 2.0;
|
||||
++nf_n_;
|
||||
}
|
||||
}
|
||||
|
||||
/* Snapshot the window into raw aggregates and RESET (delta semantics, like
|
||||
* GetRxEnergy). */
|
||||
RxQualitySnapshot snapshot() {
|
||||
RxQualitySnapshot s;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
s.frames = n_;
|
||||
if (n_) {
|
||||
s.rssi_mean_raw = rssi_sum_ / static_cast<int>(n_);
|
||||
s.rssi_max_raw = rssi_max_;
|
||||
}
|
||||
if (snr_n_) {
|
||||
s.snr_mean_raw = snr_sum_ / static_cast<int>(snr_n_);
|
||||
s.snr_min_raw = snr_min_;
|
||||
s.snr_valid = true;
|
||||
}
|
||||
if (evm_n_) {
|
||||
s.evm_mean_raw = evm_sum_ / static_cast<int>(evm_n_);
|
||||
s.evm_valid = true;
|
||||
}
|
||||
if (nf_n_) {
|
||||
s.nf_mean_dbm = nf_sum_ / static_cast<double>(nf_n_);
|
||||
s.nf_valid = true;
|
||||
}
|
||||
n_ = 0;
|
||||
rssi_sum_ = 0;
|
||||
rssi_max_ = -128;
|
||||
snr_sum_ = 0;
|
||||
snr_n_ = 0;
|
||||
snr_min_ = 127;
|
||||
evm_sum_ = 0;
|
||||
evm_n_ = 0;
|
||||
nf_sum_ = 0.0;
|
||||
nf_n_ = 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_;
|
||||
uint32_t n_ = 0;
|
||||
int32_t rssi_sum_ = 0, rssi_max_ = -128;
|
||||
int32_t snr_sum_ = 0, snr_min_ = 127;
|
||||
uint32_t snr_n_ = 0;
|
||||
int32_t evm_sum_ = 0;
|
||||
uint32_t evm_n_ = 0;
|
||||
double nf_sum_ = 0.0;
|
||||
uint32_t nf_n_ = 0;
|
||||
};
|
||||
|
||||
/* Fuse the frame aggregate + frame-free energy into an RxQuality, running the
|
||||
* LinkHealth classifier once. Pure — no I/O; the device passes GetRxEnergy()'s
|
||||
* result in. IGI rails are the union J1/J2 DIG floor (saturation corroborator)
|
||||
* and the J3 ceiling (so a static J3 IGI never reads as a false 'weak' rail),
|
||||
* matching the demo's LinkHealth mapping. */
|
||||
inline RxQuality build_rx_quality(const RxQualitySnapshot &s, const RxEnergy &e,
|
||||
const LinkHealthThresholds &th = {}) {
|
||||
RxQuality q;
|
||||
q.frames = s.frames;
|
||||
q.valid = s.frames > 0;
|
||||
q.rssi_mean_dbm = s.rssi_mean_raw - 110;
|
||||
q.rssi_max_dbm = s.rssi_max_raw - 110;
|
||||
q.snr_mean_db = s.snr_mean_raw / 2.0;
|
||||
q.snr_min_db = s.snr_min_raw / 2.0;
|
||||
q.snr_valid = s.snr_valid;
|
||||
q.evm_valid = s.evm_valid;
|
||||
q.evm_mean_db = s.evm_mean_raw / 2.0;
|
||||
q.noise_floor_dbm = s.nf_mean_dbm;
|
||||
q.nf_valid = s.nf_valid;
|
||||
q.abs_noise_floor_dbm = e.abs_noise_floor_dbm; /* active floor rides RxEnergy */
|
||||
q.abs_nf_valid = e.valid_noise_floor;
|
||||
q.energy_valid = e.valid_fa;
|
||||
q.fa_ofdm = e.fa_ofdm;
|
||||
q.cca_ofdm = e.cca_ofdm;
|
||||
q.igi_valid = e.valid_igi;
|
||||
q.igi = e.igi;
|
||||
|
||||
LinkHealthInput in;
|
||||
in.frames = s.frames;
|
||||
in.rssi_raw = s.frames ? s.rssi_max_raw : 0; /* strength = window peak */
|
||||
in.snr_raw = s.snr_mean_raw;
|
||||
in.evm_raw = s.evm_mean_raw;
|
||||
in.evm_valid = s.evm_valid;
|
||||
in.energy_valid = e.valid_fa;
|
||||
in.fa_ofdm = e.fa_ofdm;
|
||||
in.cca_ofdm = e.cca_ofdm;
|
||||
in.igi_valid = e.valid_igi;
|
||||
in.igi = e.igi;
|
||||
in.igi_min = 0x1c;
|
||||
in.igi_max = 0x7f;
|
||||
LinkHealthVerdict h = classify_link_health(in, th);
|
||||
q.verdict = h.verdict;
|
||||
q.label = h.label;
|
||||
q.cause = h.cause;
|
||||
q.fix = h.fix;
|
||||
q.igi_at_floor = h.igi_at_floor;
|
||||
q.igi_at_ceiling = h.igi_at_ceiling;
|
||||
return q;
|
||||
}
|
||||
|
||||
/* --- Live per-chain RX-path activity (the companion to the static AdapterCaps
|
||||
* chain count) ---
|
||||
*
|
||||
* AdapterCaps.rx_chains says how many chains the silicon HAS; this says how many
|
||||
* currently look CONNECTED, inferred from the per-frame per-chain RSSI the frame
|
||||
* parser fills (RxAtrib.rssi[0..3]). It's the one antenna question that can't be
|
||||
* answered statically: a chain with a disconnected/blocked antenna (or one a
|
||||
* caller software-masked via SetRxPathMask) still exists, but its RSSI collapses
|
||||
* to the noise floor. Best-effort: only meaningful with an RX loop running and
|
||||
* ambient traffic; a strong near-field frame can briefly light a dead chain via
|
||||
* coupling, so treat single-window results as a hint, not a verdict. */
|
||||
struct ActiveRxPaths {
|
||||
bool valid = false; /* false when no frames were sampled in the window */
|
||||
uint32_t frames = 0;
|
||||
uint8_t n_chains = 0; /* chains considered (the adapter's rx_chains) */
|
||||
uint8_t n_active = 0; /* chains classified active */
|
||||
uint8_t active_mask = 0; /* bit i set = chain i active */
|
||||
int rssi_mean_dbm[4] = {0, 0, 0, 0}; /* per-chain window mean (raw - 110) */
|
||||
bool chain_sampled[4] = {false, false, false, false}; /* had any sample */
|
||||
/* Per-chain window-mean SNR / EVM (dB), sampled only when the frame's
|
||||
* phy-status carried a nonzero value for that chain (CCK and non-type1
|
||||
* phy-status leave them 0, so a mixed stream doesn't bias toward zero —
|
||||
* the RxQualityAccumulator convention, per chain). EVM follows the
|
||||
* phy-status sign: negative, more negative = cleaner constellation. */
|
||||
double snr_mean_db[4] = {0, 0, 0, 0};
|
||||
bool snr_sampled[4] = {false, false, false, false};
|
||||
double evm_mean_db[4] = {0, 0, 0, 0};
|
||||
bool evm_sampled[4] = {false, false, false, false};
|
||||
};
|
||||
|
||||
/* Classify which of `n_chains` are active: a chain is active if it was sampled
|
||||
* and its mean RSSI is within `margin_db` of the strongest sampled chain. Pure;
|
||||
* unit-tested in tests/adapter_caps_selftest.cpp. `rssi_mean_dbm` and
|
||||
* `sampled` are the per-chain window aggregates; fills `active_mask` and returns
|
||||
* the active count. A single strong chain → mask 0x1; two balanced → 0x3; a
|
||||
* chain pinned at the noise floor is excluded. */
|
||||
inline uint8_t classify_active_paths(const int *rssi_mean_dbm,
|
||||
const bool *sampled, uint8_t n_chains,
|
||||
int margin_db, uint8_t *active_mask) {
|
||||
int strongest = -1000;
|
||||
for (uint8_t i = 0; i < n_chains && i < 4; i++)
|
||||
if (sampled[i] && rssi_mean_dbm[i] > strongest)
|
||||
strongest = rssi_mean_dbm[i];
|
||||
uint8_t mask = 0, count = 0;
|
||||
if (strongest > -1000) {
|
||||
for (uint8_t i = 0; i < n_chains && i < 4; i++) {
|
||||
if (sampled[i] && (strongest - rssi_mean_dbm[i]) <= margin_db) {
|
||||
mask |= static_cast<uint8_t>(1u << i);
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (active_mask)
|
||||
*active_mask = mask;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Thread-safe per-chain RSSI/SNR/EVM accumulator — the ActiveRxPaths analogue
|
||||
* of RxQualityAccumulator. The device feeds add() the full [0..3] tuples for
|
||||
* every decoded frame; snapshot() drains the window (delta semantics) and
|
||||
* classifies. `margin_db` default 20 dB: a chain more than 20 dB below the
|
||||
* strongest is a disconnected/masked antenna, not thermal spread across
|
||||
* connected chains. */
|
||||
class RxPathActivityAccumulator {
|
||||
public:
|
||||
/* Feed the per-chain RSSI / SNR / EVM (raw devourer units: rssi = dBm+110,
|
||||
* snr/evm = half-dB) of one decoded frame; only the first `n_chains` are
|
||||
* considered. A chain reading 0 on a metric (no phy-status value) is not a
|
||||
* sample for that chain+metric — RSSI gates the frame count, SNR/EVM are
|
||||
* folded independently so CCK frames don't zero-bias their means. `snr_raw`
|
||||
* / `evm_raw` may be null (RSSI-only callers). */
|
||||
void add(const uint8_t *rssi_raw, const int8_t *snr_raw,
|
||||
const int8_t *evm_raw, uint8_t n_chains) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (n_chains > 4)
|
||||
n_chains = 4;
|
||||
n_chains_ = n_chains;
|
||||
bool any = false;
|
||||
for (uint8_t i = 0; i < n_chains; i++) {
|
||||
if (rssi_raw[i] == 0)
|
||||
continue;
|
||||
sum_[i] += rssi_raw[i];
|
||||
++cnt_[i];
|
||||
any = true;
|
||||
if (snr_raw && snr_raw[i] != 0) {
|
||||
snr_sum_[i] += snr_raw[i];
|
||||
++snr_cnt_[i];
|
||||
}
|
||||
/* -128 is the phy-status no-stream rail (a 1SS frame has no stream-2
|
||||
* EVM; the 11ac reports pin the byte at -128) — a sentinel, not a
|
||||
* measurement (on-air: J1/J2/J3 all rail chain 1 at -128 under 1SS
|
||||
* traffic while chain-1 RSSI/SNR stay live). */
|
||||
if (evm_raw && evm_raw[i] != 0 && evm_raw[i] != -128) {
|
||||
evm_sum_[i] += evm_raw[i];
|
||||
++evm_cnt_[i];
|
||||
}
|
||||
}
|
||||
if (any)
|
||||
++frames_;
|
||||
}
|
||||
|
||||
ActiveRxPaths snapshot(int margin_db = 20) {
|
||||
ActiveRxPaths s;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
s.frames = frames_;
|
||||
s.n_chains = n_chains_;
|
||||
s.valid = frames_ > 0;
|
||||
for (uint8_t i = 0; i < n_chains_ && i < 4; i++) {
|
||||
if (cnt_[i]) {
|
||||
s.rssi_mean_dbm[i] =
|
||||
static_cast<int>(sum_[i] / cnt_[i]) - 110;
|
||||
s.chain_sampled[i] = true;
|
||||
}
|
||||
if (snr_cnt_[i]) {
|
||||
s.snr_mean_db[i] = snr_sum_[i] / (2.0 * snr_cnt_[i]);
|
||||
s.snr_sampled[i] = true;
|
||||
}
|
||||
if (evm_cnt_[i]) {
|
||||
s.evm_mean_db[i] = evm_sum_[i] / (2.0 * evm_cnt_[i]);
|
||||
s.evm_sampled[i] = true;
|
||||
}
|
||||
}
|
||||
s.n_active = classify_active_paths(s.rssi_mean_dbm, s.chain_sampled,
|
||||
s.n_chains, margin_db, &s.active_mask);
|
||||
/* reset (delta semantics) */
|
||||
frames_ = 0;
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
sum_[i] = 0;
|
||||
cnt_[i] = 0;
|
||||
snr_sum_[i] = 0;
|
||||
snr_cnt_[i] = 0;
|
||||
evm_sum_[i] = 0;
|
||||
evm_cnt_[i] = 0;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_;
|
||||
uint32_t frames_ = 0;
|
||||
uint8_t n_chains_ = 0;
|
||||
uint64_t sum_[4] = {0, 0, 0, 0};
|
||||
uint32_t cnt_[4] = {0, 0, 0, 0};
|
||||
int64_t snr_sum_[4] = {0, 0, 0, 0};
|
||||
uint32_t snr_cnt_[4] = {0, 0, 0, 0};
|
||||
int64_t evm_sum_[4] = {0, 0, 0, 0};
|
||||
uint32_t evm_cnt_[4] = {0, 0, 0, 0};
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_RX_QUALITY_H */
|
||||
@@ -0,0 +1,62 @@
|
||||
#ifndef RX_SENSE_H
|
||||
#define RX_SENSE_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
/* RxEnergy — a frame-free RX energy / channel-busy snapshot. This is the read
|
||||
* side of the DEVOURER_CW_TONE emitter: a coarse "how much in-band energy /
|
||||
* channel activity is here" measurement that does NOT require receiving a frame.
|
||||
*
|
||||
* Filled by IRtlRadio::GetRxEnergy() from the chip's phydm facilities:
|
||||
* - false-alarm (FA) + CCA (channel-busy) counters,
|
||||
* - the DIG initial-gain index (a noise-floor proxy),
|
||||
* - and, where triggered, the NHM in-band power histogram.
|
||||
*
|
||||
* All values are channel-wide scalars — no Realtek 88xx chip exports
|
||||
* per-subcarrier CSI to the host, so this is energy, not a spectrum. Build a
|
||||
* coarse spectrum by sweeping channels/bins and sampling this per bin.
|
||||
*
|
||||
* FA/CCA counts are the DELTA since the previous GetRxEnergy() call (each read
|
||||
* resets the hardware counters), so a strong in-band carrier shows up as a jump
|
||||
* in cca_ofdm / fa_ofdm and a rise in igi. Every field carries a valid_* flag
|
||||
* because the facilities differ by chip generation.
|
||||
*
|
||||
* The read splits into two very different costs, which is why the caller picks
|
||||
* (`GetRxEnergy(bool with_nhm)`): the scalars below are a handful of register
|
||||
* reads, while the NHM histogram arms a ~2 ms measurement window and then polls
|
||||
* a ready bit at 1 ms granularity. Anything sampling at a sub-second cadence —
|
||||
* or throwing the read away to reset the counters before an observation
|
||||
* window — wants with_nhm=false. */
|
||||
struct RxEnergy {
|
||||
/* phydm false-alarm + CCA counters (delta since the previous read). */
|
||||
bool valid_fa = false;
|
||||
uint32_t fa_ofdm = 0; /* OFDM false-alarm count */
|
||||
uint32_t fa_cck = 0; /* CCK false-alarm count */
|
||||
uint32_t cca_ofdm = 0; /* OFDM CCA (channel-busy) count */
|
||||
uint32_t cca_cck = 0; /* CCK CCA count */
|
||||
|
||||
/* DIG initial-gain index (0x0c50[6:0] on the AC BB): the AGC backs the gain
|
||||
* off as the in-band floor rises, so a higher IGI means a busier/noisier
|
||||
* channel. Noise-floor proxy. */
|
||||
bool valid_igi = false;
|
||||
uint8_t igi = 0;
|
||||
|
||||
/* NHM in-band power histogram: 12 IGI-referenced power buckets and the
|
||||
* measurement duration. A frame-free power distribution (fuller than the
|
||||
* scalar FA counts). Only populated when the caller asked for it
|
||||
* (GetRxEnergy(with_nhm=true)). */
|
||||
bool valid_nhm = false;
|
||||
uint8_t nhm[12] = {};
|
||||
uint16_t nhm_duration = 0;
|
||||
|
||||
/* Active/frame-free ABSOLUTE noise floor (dBm) — the vendor idle-noise
|
||||
* monitor, distinct from the passive rssi-snr floor in RxQuality. Heavy
|
||||
* (~10 ms of USB round-trips), so it is only filled when the caller opted in
|
||||
* (DEVOURER_RX_NOISE_FLOOR). Jaguar2 fills it live (HW idle-noise report,
|
||||
* wedge-free); Jaguar1 8812A/8821A fill it from an RX-idle CAL measurement;
|
||||
* Jaguar3 and others leave it invalid (no vendor path). */
|
||||
bool valid_noise_floor = false;
|
||||
int8_t abs_noise_floor_dbm = 0;
|
||||
};
|
||||
|
||||
#endif /* RX_SENSE_H */
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef SELECTEDCHANNEL_H
|
||||
#define SELECTEDCHANNEL_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
enum ChannelWidth_t {
|
||||
CHANNEL_WIDTH_20 = 0,
|
||||
CHANNEL_WIDTH_40 = 1,
|
||||
CHANNEL_WIDTH_80 = 2,
|
||||
CHANNEL_WIDTH_160 = 3,
|
||||
CHANNEL_WIDTH_80_80 = 4,
|
||||
CHANNEL_WIDTH_5 = 5,
|
||||
CHANNEL_WIDTH_10 = 6,
|
||||
CHANNEL_WIDTH_MAX = 7,
|
||||
};
|
||||
|
||||
struct SelectedChannel {
|
||||
uint8_t Channel;
|
||||
uint8_t ChannelOffset;
|
||||
ChannelWidth_t ChannelWidth;
|
||||
/* Band selector. 0 = auto: 2.4 GHz when Channel<=14, else 5 GHz (the
|
||||
* historical behaviour). 6 = 6 GHz (WiFi 6E) — required because a 6 GHz
|
||||
* channel number collides with a 5 GHz one (e.g. ch 37 exists in both), so
|
||||
* the band cannot be inferred from Channel alone. Only the RTL8852C-family
|
||||
* (tri-band) honours 6; other chips ignore it. */
|
||||
uint8_t Band = 0;
|
||||
};
|
||||
|
||||
#endif /* SELECTEDCHANNEL_H */
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "SignalStop.h"
|
||||
|
||||
#include <csignal>
|
||||
|
||||
volatile bool g_devourer_should_stop = false;
|
||||
|
||||
static void devourer_stop_handler(int /*sig*/) { g_devourer_should_stop = true; }
|
||||
|
||||
void install_devourer_signal_handlers() {
|
||||
#ifdef _WIN32
|
||||
/* Windows has no POSIX sigaction; std::signal covers SIGINT/SIGTERM and is
|
||||
* enough for the demos' Ctrl-C / terminate stop semantics. */
|
||||
std::signal(SIGINT, devourer_stop_handler);
|
||||
std::signal(SIGTERM, devourer_stop_handler);
|
||||
#else
|
||||
struct sigaction sa {};
|
||||
sa.sa_handler = devourer_stop_handler;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_flags = 0; /* no SA_RESTART: let blocking syscalls return so loops re-check */
|
||||
sigaction(SIGINT, &sa, nullptr);
|
||||
sigaction(SIGTERM, &sa, nullptr);
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#ifndef SIGNAL_STOP_H
|
||||
#define SIGNAL_STOP_H
|
||||
|
||||
/* Process-global "please stop" flag, shared by the demos' signal handlers and
|
||||
* the device RX/TX loops. Without this, a SIGTERM (e.g. from the test harness's
|
||||
* `timeout`) or SIGINT killed the process instantly: the read/write loop never
|
||||
* broke, the chip was never powered down, and an abandoned adapter (RX DMA still
|
||||
* running, firmware still up) overflowed its RX FIFO and hung its USB core —
|
||||
* after which the device fails to re-enumerate (kernel logs error -71). The
|
||||
* kernel driver avoids this by running a clean card-disable on unbind; setting
|
||||
* this flag lets devourer do the same. async-signal-safe: a plain volatile bool
|
||||
* written by the handler and polled by the loops. */
|
||||
extern volatile bool g_devourer_should_stop;
|
||||
|
||||
/* Install SIGINT + SIGTERM handlers that set g_devourer_should_stop. Idempotent;
|
||||
* call once early in main(). */
|
||||
void install_devourer_signal_handlers();
|
||||
|
||||
#endif /* SIGNAL_STOP_H */
|
||||
@@ -0,0 +1,225 @@
|
||||
#pragma once
|
||||
|
||||
/* Sounding — the 802.11ax HE sounding (NDPA -> NDP -> BFRP) command surface.
|
||||
*
|
||||
* A BFRP (Beamforming Report Poll) is an 802.11ax Trigger-frame variant, so the
|
||||
* sounding sequence is the firmware's own use of the Trigger primitive: the H2C
|
||||
* (CL_SOUND / SET_SND_PARA, content-in-H2C, no pkt_ofld) hands the fw the whole
|
||||
* NDPA/NDP/BFRP descriptor set for it to build and air.
|
||||
*
|
||||
* On-air status (measured, both dies): the shipped client NIC firmware ACCEPTS
|
||||
* SET_SND_PARA (no SER) but does NOT air the sequence — the fw-command sounding-
|
||||
* transmit engine is present only in the vendor's AP-firmware image, and the
|
||||
* NIC-firmware host-NDPA path is unwired in the vendor tree. So, like the
|
||||
* F2P_TEST command, this is a byte-exact command surface the shipped fw does not
|
||||
* act on. The path that actually puts a Trigger on the air on this firmware is
|
||||
* host-injection (IRadio::SendTrigger, src/TriggerTwt.h). See
|
||||
* docs/he-trigger-ul.md.
|
||||
*
|
||||
* These aggregates are devourer-native; the Kestrel HAL maps them onto the
|
||||
* vendor mac_ax_fwcmd_snd via the SchedEncode.h encoder. The raw 72-/98-dword
|
||||
* vendor struct never surfaces here. */
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* One beamformee's STA Info in the HE NDPA (802.11ax NDP Announcement). */
|
||||
struct SoundingStaInfo {
|
||||
uint16_t aid = 0; /* 11-bit AID of the beamformee */
|
||||
uint16_t bw = 0; /* Sounding bandwidth (0 = 20 MHz) */
|
||||
uint8_t fb_ng = 0; /* Feedback Ng (subcarrier grouping: 0 = Ng4) */
|
||||
bool cb = false; /* Codebook size */
|
||||
uint8_t nc = 0; /* Nc-1 (number of columns of the feedback matrix) */
|
||||
};
|
||||
|
||||
/* One beamformee's User Info in the HE BFRP Trigger (what TB PPDU to send). */
|
||||
struct SoundingBfrpUser {
|
||||
uint16_t aid12 = 0; /* 12-bit AID of the polled STA */
|
||||
uint8_t ru_pos = 0; /* 8-bit RU Allocation subfield (61 = full 20 MHz) */
|
||||
bool ul_fec_code = false; /* false = BCC, true = LDPC */
|
||||
uint8_t ul_mcs = 0; /* 0..11 */
|
||||
bool ul_dcm = false;
|
||||
uint8_t ss_alloc = 0; /* SS Allocation subfield (0 = 1 SS starting at SS0) */
|
||||
uint8_t fbseg_rexmit_bmp = 0;
|
||||
uint8_t ul_tgt_rssi = 127; /* 7-bit target RSSI (127 = transmit at max power) */
|
||||
};
|
||||
|
||||
/* One entry of the sounding WD list (the TX descriptor the fw uses for each
|
||||
* frame in the NDPA/NDP/BFRP sequence). The frexgtype-specific fields
|
||||
* (txpktsize / snd_pkt_sel / ndpa / sifs_tx) are set by make_he_bfrp_sounding
|
||||
* to match the vendor mac_set_snd_para AX_MU_BFRP1 case. */
|
||||
struct SoundingWd {
|
||||
uint16_t txpktsize = 0;
|
||||
uint16_t ndpa_duration = 0;
|
||||
uint16_t datarate = 0; /* AX 9-bit rate code the frame airs at (0 = OFDM6) */
|
||||
uint8_t macid = 0;
|
||||
uint8_t data_bw = 0;
|
||||
uint8_t gi_ltf = 0;
|
||||
bool stf_mode = false;
|
||||
bool disdatafb = false;
|
||||
bool data_txcnt_lmt_sel = false;
|
||||
uint8_t data_txcnt_lmt = 0;
|
||||
bool sifs_tx = false;
|
||||
uint8_t snd_pkt_sel = 0; /* 1 = NDPA, 3 = NDP, 5 = BFRP (fw frame selector) */
|
||||
uint8_t ndpa = 0; /* 0 = none, 2 = VHT, 3 = HE */
|
||||
};
|
||||
|
||||
/* HE BFRP Trigger common info (the Trigger frame Common Info field). */
|
||||
struct SoundingBfrpCommon {
|
||||
uint8_t trigger_type = 0; /* 1 = BFRP */
|
||||
uint16_t ul_len = 0; /* L-SIG length of the solicited TB PPDU */
|
||||
uint8_t ul_bw = 0; /* 0 = 20 MHz */
|
||||
uint8_t gi_ltf = 0;
|
||||
uint8_t num_he_ltf = 0;
|
||||
uint8_t ap_tx_pwr = 0;
|
||||
uint16_t ul_sr = 0;
|
||||
};
|
||||
|
||||
/* A complete HE sounding command (mirrors mac_ax_fwcmd_snd for the devourer
|
||||
* surface). Defaults are zero; use make_he_bfrp_sounding() to build a valid
|
||||
* single-user HE BFRP sounding. */
|
||||
struct SoundingConfig {
|
||||
uint8_t frexgtype = 36; /* FRAME_EXCHANGE_SND_AX_MU_BFRP1 */
|
||||
uint8_t mode = 0;
|
||||
uint8_t bfrp0_user_num = 0;
|
||||
uint8_t bfrp1_user_num = 0;
|
||||
std::array<uint8_t, 16> macid{}; /* beamformee macids (macid[0] = STA) */
|
||||
|
||||
/* NDPA frame + STA-info list. */
|
||||
uint16_t ndpa_frame_ctl = 0x0054;
|
||||
uint16_t ndpa_duration = 0;
|
||||
std::array<uint8_t, 6> ndpa_addr1{}; /* RA (the beamformee / broadcast) */
|
||||
std::array<uint8_t, 6> ndpa_addr2{}; /* TA (AP SA) */
|
||||
std::array<uint8_t, 6> ndpa_addr3{}; /* BSSID */
|
||||
uint16_t ndpa_seq_control = 0;
|
||||
bool ndpa_dialog_he = true;
|
||||
uint8_t ndpa_dialog_token = 0;
|
||||
std::array<SoundingStaInfo, 8> he_sta{}; /* HE NDPA STA Info (index 0..7) */
|
||||
|
||||
/* BFRP frame headers (up to 3: BFRP0/1/2) + per-BFRP common+user. */
|
||||
std::array<uint16_t, 3> bfrp_frame_ctl{{0x0024, 0x0024, 0x0024}};
|
||||
std::array<uint16_t, 3> bfrp_duration{};
|
||||
std::array<std::array<uint8_t, 6>, 3> bfrp_addr1{}; /* RA */
|
||||
std::array<std::array<uint8_t, 6>, 3> bfrp_addr2{}; /* TA (AP SA) */
|
||||
std::array<SoundingBfrpCommon, 2> bfrp_common{};
|
||||
std::array<std::array<SoundingBfrpUser, 8>, 2> bfrp_user{};
|
||||
|
||||
/* WD list (5 entries) + F2P(BFRP) + SFP. */
|
||||
std::array<SoundingWd, 5> wd{};
|
||||
std::array<uint16_t, 2> csi_len_bfrp{}; /* f2p[0/1].csi_len_bfrp */
|
||||
std::array<uint8_t, 2> tb_t_pe_bfrp{};
|
||||
uint8_t f2p_type = 0; /* sfp.f2p_type (0 = add/one-shot) */
|
||||
uint8_t f2p_index = 0;
|
||||
uint16_t f2p_period = 0; /* 0 = one-shot; >0 = periodic sounding (units of TU) */
|
||||
bool sounding_en = false; /* sfp.sounding_en (periodic-sounding enable) */
|
||||
};
|
||||
|
||||
/* Per-STA beamformee capability the AP programs into the CCTL bf fields so a
|
||||
* BFRP to this STA solicits a decodable report. Values are the STA's advertised
|
||||
* HE beamformee params (Nc, Ng, codebook) + the CSI report rate/BW. */
|
||||
struct StaBfCaps {
|
||||
uint8_t nc = 0; /* Nc-1 */
|
||||
uint8_t nr = 0; /* Nr-1 (AP receive chains - 1) */
|
||||
uint8_t ng = 0; /* subcarrier grouping (0 = Ng4) */
|
||||
uint8_t cb = 1; /* codebook */
|
||||
uint8_t cs = 0; /* codebook subset */
|
||||
uint8_t csi_bw = 0; /* 0 = 20 MHz */
|
||||
uint8_t csi_gi_ltf = 0; /* CSI report GI/LTF */
|
||||
uint16_t csi_fix_rate = 0; /* 0 = auto (from RRSC) */
|
||||
};
|
||||
|
||||
/* Build a single-user HE BFRP sounding: the AP (ap_mac / bssid) sounds one
|
||||
* associated beamformee (sta_mac, aid, fw macid). Fills the NDPA + BFRP frame
|
||||
* content and the WD list per the vendor mac_set_snd_para AX_MU_BFRP1 case
|
||||
* (wd[0]=NDPA, wd[1]=NDP, wd[2]=BFRP). `dialog` is the rolling sounding dialog
|
||||
* token; `csi_bw` selects the sounding bandwidth (0 = 20 MHz). `air_rate` is
|
||||
* the AX rate code the NDPA/NDP/BFRP air at (0 = OFDM6, non-HT so any monitor
|
||||
* decodes the trigger). */
|
||||
/* `period` selects the fw sounding cadence: 0 = a one-shot sounding (SNDF2P_ONCE,
|
||||
* the caller re-issues each time — beware flooding the CH12 H2C queue if fast);
|
||||
* >0 = fw-autonomous periodic sounding (SNDF2P_ADD + sounding_en), so ONE H2C
|
||||
* arms repeated soundings at the fw's own cadence (units are the vendor
|
||||
* f2p_period field) — the analogue of UL_FIXINFO tf_periodic and the way to
|
||||
* sustain sounding without per-sounding H2Cs. */
|
||||
inline SoundingConfig make_he_bfrp_sounding(const uint8_t ap_mac[6],
|
||||
const uint8_t bssid[6],
|
||||
const uint8_t sta_mac[6],
|
||||
uint16_t aid, uint8_t macid,
|
||||
uint8_t dialog,
|
||||
uint16_t period = 0,
|
||||
uint8_t ap_macid = 0,
|
||||
uint16_t air_rate = 0,
|
||||
uint8_t ul_mcs = 0) {
|
||||
SoundingConfig c;
|
||||
c.frexgtype = 36; /* AX_MU_BFRP1 */
|
||||
c.bfrp0_user_num = 1;
|
||||
c.macid[0] = macid;
|
||||
|
||||
/* NDPA (type1/subtype5, FC 0x0054): RA = STA, TA = AP, BSSID. */
|
||||
c.ndpa_frame_ctl = 0x0054;
|
||||
std::memcpy(c.ndpa_addr1.data(), sta_mac, 6);
|
||||
std::memcpy(c.ndpa_addr2.data(), ap_mac, 6);
|
||||
std::memcpy(c.ndpa_addr3.data(), bssid, 6);
|
||||
c.ndpa_dialog_he = true;
|
||||
c.ndpa_dialog_token = dialog & 0x3f;
|
||||
c.he_sta[0].aid = aid & 0x7ff;
|
||||
c.he_sta[0].bw = 0;
|
||||
c.he_sta[0].fb_ng = 0;
|
||||
c.he_sta[0].cb = false;
|
||||
c.he_sta[0].nc = 0; /* Nc-1 = 0 -> 1 column */
|
||||
|
||||
/* BFRP0 Trigger (type1/subtype2, FC 0x0024): RA = STA, TA = AP. */
|
||||
c.bfrp_frame_ctl[0] = 0x0024;
|
||||
std::memcpy(c.bfrp_addr1[0].data(), sta_mac, 6);
|
||||
std::memcpy(c.bfrp_addr2[0].data(), ap_mac, 6);
|
||||
c.bfrp_common[0].trigger_type = 1; /* BFRP */
|
||||
c.bfrp_common[0].ul_len = 0x1ff; /* placeholder L-SIG len (tuned on-air) */
|
||||
c.bfrp_common[0].ul_bw = 0;
|
||||
c.bfrp_common[0].gi_ltf = 0;
|
||||
c.bfrp_common[0].num_he_ltf = 0;
|
||||
c.bfrp_common[0].ap_tx_pwr = 0x3f;
|
||||
c.bfrp_user[0][0].aid12 = aid & 0xfff;
|
||||
c.bfrp_user[0][0].ru_pos = 61; /* full 20 MHz (242-tone) */
|
||||
c.bfrp_user[0][0].ul_mcs = ul_mcs & 0xf;
|
||||
c.bfrp_user[0][0].ss_alloc = 0; /* 1 SS */
|
||||
c.bfrp_user[0][0].ul_tgt_rssi = 127; /* max power */
|
||||
c.csi_len_bfrp[0] = 0x1ff;
|
||||
|
||||
/* WD list per mac_set_snd_para AX_MU_BFRP1 (users = 1):
|
||||
* wd[0]=NDPA, wd[1]=NDP, wd[2]=BFRP. */
|
||||
const uint8_t users = 1;
|
||||
auto &w0 = c.wd[0];
|
||||
w0.txpktsize = static_cast<uint16_t>(17 + 4 * users);
|
||||
w0.stf_mode = true; w0.disdatafb = true;
|
||||
w0.data_txcnt_lmt_sel = true; w0.data_txcnt_lmt = 1;
|
||||
w0.sifs_tx = true; w0.snd_pkt_sel = 1; w0.ndpa = 3;
|
||||
w0.datarate = air_rate; w0.macid = ap_macid;
|
||||
auto &w1 = c.wd[1];
|
||||
w1.txpktsize = 0;
|
||||
w1.stf_mode = true; w1.disdatafb = true;
|
||||
w1.data_txcnt_lmt_sel = true; w1.data_txcnt_lmt = 1;
|
||||
w1.sifs_tx = true; w1.snd_pkt_sel = 3; w1.ndpa = 3;
|
||||
w1.datarate = air_rate; w1.macid = ap_macid;
|
||||
auto &w2 = c.wd[2];
|
||||
w2.txpktsize = static_cast<uint16_t>(24 + 6 * users);
|
||||
w2.stf_mode = true; w2.disdatafb = true;
|
||||
w2.data_txcnt_lmt_sel = true; w2.data_txcnt_lmt = 1;
|
||||
w2.sifs_tx = false; w2.snd_pkt_sel = 5; w2.ndpa = 3;
|
||||
w2.datarate = air_rate; w2.macid = ap_macid;
|
||||
|
||||
if (period > 0) {
|
||||
c.f2p_type = 1; /* SNDF2P_ADD — fw-autonomous periodic sounding */
|
||||
c.f2p_period = period;
|
||||
c.sounding_en = true;
|
||||
} else {
|
||||
c.f2p_type = 0; /* SNDF2P_ONCE — one-shot (caller re-issues) */
|
||||
c.f2p_period = 0;
|
||||
c.sounding_en = false;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,78 @@
|
||||
#ifndef SWEEP_SPEC_H
|
||||
#define SWEEP_SPEC_H
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "ChannelFreq.h"
|
||||
|
||||
/* Sweep/hop bin-list grammar shared by DEVOURER_RX_SWEEP (demo) and
|
||||
* DEVOURER_HOP_CHANNELS (txdemo). Comma-separated tokens, each either
|
||||
*
|
||||
* <ch> a channel number "1,6,11"
|
||||
* <a>-<b>[/<s>] an inclusive range with step s (def. 1) "36-48/4"
|
||||
* <fa>-<fb>[/<s>] a centre-frequency range in MHz "5170-5250/5"
|
||||
* (values >= 1000 are MHz; step in MHz — 5 MHz per channel
|
||||
* number, so "2412-2462/25" = every 5th 2.4 GHz channel)
|
||||
*
|
||||
* A frequency range maps through devourer::freq_to_chan (5 GHz channels sit on
|
||||
* the 5 MHz grid, so 5 MHz-wide narrowband bins get one bin per channel
|
||||
* number). Malformed / out-of-band tokens are dropped. */
|
||||
|
||||
namespace devourer {
|
||||
|
||||
inline std::vector<int> parse_sweep_spec(const char *spec) {
|
||||
std::vector<int> out;
|
||||
if (spec == nullptr || *spec == '\0')
|
||||
return out;
|
||||
const std::string s = spec;
|
||||
size_t pos = 0;
|
||||
while (pos < s.size()) {
|
||||
const size_t comma = s.find(',', pos);
|
||||
std::string tok = s.substr(
|
||||
pos, comma == std::string::npos ? std::string::npos : comma - pos);
|
||||
pos = (comma == std::string::npos) ? s.size() : comma + 1;
|
||||
if (tok.empty())
|
||||
continue;
|
||||
|
||||
long step = 1;
|
||||
const size_t slash = tok.find('/');
|
||||
if (slash != std::string::npos) {
|
||||
step = std::strtol(tok.c_str() + slash + 1, nullptr, 0);
|
||||
tok = tok.substr(0, slash);
|
||||
}
|
||||
if (step < 1)
|
||||
step = 1;
|
||||
|
||||
/* A '-' past position 0 splits a range (a leading '-' would just make the
|
||||
* token malformed; channels are positive). */
|
||||
const size_t dash = tok.find('-', 1);
|
||||
if (dash == std::string::npos) {
|
||||
const int ch = static_cast<int>(std::strtol(tok.c_str(), nullptr, 0));
|
||||
if (ch > 0)
|
||||
out.push_back(ch);
|
||||
continue;
|
||||
}
|
||||
const long a = std::strtol(tok.substr(0, dash).c_str(), nullptr, 0);
|
||||
const long b = std::strtol(tok.substr(dash + 1).c_str(), nullptr, 0);
|
||||
if (a <= 0 || b < a)
|
||||
continue;
|
||||
/* MHz ranges live on the 5 MHz channel grid — a finer step would only
|
||||
* emit duplicate bins. */
|
||||
if (a >= 1000 && step < 5)
|
||||
step = 5;
|
||||
for (long v = a; v <= b; v += step) {
|
||||
const int ch = (a >= 1000)
|
||||
? freq_to_chan(static_cast<uint16_t>(v))
|
||||
: static_cast<int>(v);
|
||||
if (ch > 0)
|
||||
out.push_back(ch);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* SWEEP_SPEC_H */
|
||||
@@ -0,0 +1,47 @@
|
||||
/* Chip thermal-meter snapshot, generation-agnostic (moved out of the Jaguar1
|
||||
* HAL when GetThermalStatus was promoted to IRadio — the meter register
|
||||
* family (RF 0x42) and the efuse-baseline semantics are common to all three
|
||||
* generations, only the field layout and baseline source differ per family).
|
||||
*/
|
||||
#ifndef DEVOURER_THERMAL_STATUS_H
|
||||
#define DEVOURER_THERMAL_STATUS_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Read-only snapshot of the chip's thermal meter. `raw` is the live
|
||||
* RF[A][0x42] reading (0..63, Realtek "thermal units" — roughly
|
||||
* 1.5-2 C each, NOT absolute degrees). `baseline` is the EFUSE
|
||||
* factory-calibrated reading (0xFF = autoload failed / no baseline; on the
|
||||
* 8822C, which wires no efuse baseline, it is the first-read cold reference,
|
||||
* so `delta` there means "since first read"). `delta = raw - baseline`
|
||||
* (signed) is the heat signal — positive means the chip is running hotter
|
||||
* than calibration. `valid` is false when no baseline of either kind is
|
||||
* available, in which case only `raw` is meaningful. */
|
||||
struct ThermalStatus {
|
||||
uint8_t raw = 0;
|
||||
uint8_t baseline = 0xFF;
|
||||
int delta = 0;
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
/* Coarse, honest health label for a thermal reading. The meter is NOT a
|
||||
* calibrated °C sensor (Realtek publishes no °C transfer function for the AU
|
||||
* family; the value is an RF/PA-bias tracking index), so we deliberately bucket
|
||||
* the delta-from-baseline rather than fake a precise temperature — the same
|
||||
* stance the rtl88x2eu driver takes (cool/warm/hot/...). Thresholds are in
|
||||
* thermal units above the EFUSE baseline; "hot" aligns with the default
|
||||
* DEVOURER_THERMAL_WARN_DELTA of 15. Returns "unknown" when no EFUSE baseline
|
||||
* is available (delta is meaningless without it). */
|
||||
inline const char *ThermalBucket(const ThermalStatus &s) {
|
||||
if (!s.valid) return "unknown";
|
||||
if (s.delta < 8) return "cool";
|
||||
if (s.delta < 15) return "warm";
|
||||
if (s.delta < 25) return "hot";
|
||||
return "critical";
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_THERMAL_STATUS_H */
|
||||
@@ -0,0 +1,459 @@
|
||||
/* ToneMask — RX-side per-subcarrier masking, shared across chip generations.
|
||||
*
|
||||
* Two receive-path mechanisms ported from vendor phydm (phydm_api.c):
|
||||
*
|
||||
* CSI mask — a per-tone receive-equalizer de-weight table. Tells the BB "these
|
||||
* subcarriers carry garbage" so a jammed slice stops dragging the whole-frame
|
||||
* channel estimate / equalization down. This is the closest an 11ac chip gets
|
||||
* to Wi-Fi 7 preamble puncturing, and only on the RX side: the vendor wrapper
|
||||
* (phydm_csi_mask_setting) masks a handful of tones around one interferer
|
||||
* frequency; here the low-level per-tone setter is looped so an entire 20 MHz
|
||||
* slice of an 80 MHz channel can be de-weighted (DEVOURER_RX_CSI_MASK).
|
||||
*
|
||||
* NBI notch — a narrowband-interference notch filter at one tone position
|
||||
* (phydm_nbi_setting). Much coarser lever (one notch, LUT-quantized), kept
|
||||
* for vendor parity as DEVOURER_RX_NBI.
|
||||
*
|
||||
* Neither touches the TX path — the silicon exposes no TX tone nulling, and a
|
||||
* VHT preamble must be contiguous full-band (true puncturing is 11be EHT-SIG
|
||||
* signaling). See docs/pseudo-preamble-puncturing.md.
|
||||
*
|
||||
* Register recipes transcribed from:
|
||||
* 11ac (Jaguar-1 8812/8811/8821/8814 + Jaguar-2 8822B):
|
||||
* reference/rtl8812au/hal/phydm/phydm_api.c — phydm_csi_mask_enable
|
||||
* (0x874[0]), phydm_set_csi_mask (bit arrays 0x880-0x88F positive /
|
||||
* 0x890-0x89F negative, one bit per 312.5 kHz subcarrier),
|
||||
* phydm_set_nbi_reg (LUT -> 0x87C[19:14]), phydm_nbi_enable (0x87C[13];
|
||||
* 8822B additionally 0xC20[28]/0xE20[28]).
|
||||
* Jaguar-3 (8822C/8822E):
|
||||
* reference/rtl88x2cu/hal/phydm/phydm_api.c — the _jgr3 variants: CSI mask
|
||||
* is an indexed table behind 0x1D94 (0x1EE8[1:0] write bracket, BYTE2 =
|
||||
* table address = tone_idx/2, [7:0] = two 4-bit tone entries: BIT3 enable |
|
||||
* 3-bit weight), enable 0xC0C[3]; NBI tone index at 0x1944/0x4044[20:12]
|
||||
* per path, enable 0x818[3] (inverted on 8822C/E) + 0x818[11] +
|
||||
* 0x1D3C[30:27] + 0x1940/0x4040[31].
|
||||
*
|
||||
* All tone math is in 312.5 kHz subcarrier units relative to the wide channel's
|
||||
* center frequency fc (phydm_find_fc port). The pure helpers (find_fc_mhz,
|
||||
* enumerate_tones, parse_*) have no device dependency so they can be unit-
|
||||
* checked headlessly.
|
||||
*/
|
||||
#ifndef DEVOURER_TONE_MASK_H
|
||||
#define DEVOURER_TONE_MASK_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
#include "SelectedChannel.h"
|
||||
#include "logger.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace tonemask {
|
||||
|
||||
/* Which register recipe applies. AC1 = 8812/8811/8821 (NBI LUT always
|
||||
* 256-FFT); AC2 = 8814A / 8822B (NBI LUT 128-FFT at 20/40, 256-FFT at 80;
|
||||
* 8822B adds the 0xC20/0xE20 NBI enable bits). */
|
||||
enum class Family { AC1, AC2_8814, AC2_8822B, JGR3 };
|
||||
|
||||
/* Vendor secondary-channel position (PHYDM_DONT_CARE/ABOVE/BELOW). */
|
||||
enum SecCh : int { kSecDontCare = 0, kSecAbove = 1, kSecBelow = 2 };
|
||||
|
||||
/* HAL_PRIME_CHNL_OFFSET_* (SelectedChannel.ChannelOffset) -> vendor secondary
|
||||
* position: primary LOWER means the secondary (and fc) sit ABOVE the primary. */
|
||||
inline int sec_from_prime_offset(uint8_t prime_offset) {
|
||||
if (prime_offset == 1) return kSecAbove; /* HAL_PRIME_CHNL_OFFSET_LOWER */
|
||||
if (prime_offset == 2) return kSecBelow; /* HAL_PRIME_CHNL_OFFSET_UPPER */
|
||||
return kSecDontCare;
|
||||
}
|
||||
|
||||
inline uint32_t bw_mhz_from(ChannelWidth_t bw) {
|
||||
switch (bw) {
|
||||
case CHANNEL_WIDTH_40: return 40;
|
||||
case CHANNEL_WIDTH_80: return 80;
|
||||
default: return 20; /* 20 + the Jaguar-3 5/10 MHz re-clocks tune as 20 */
|
||||
}
|
||||
}
|
||||
|
||||
/* phydm_find_fc port — wide-channel center frequency in MHz from the PRIMARY
|
||||
* 20 MHz channel + bandwidth (+ secondary position, 2.4 GHz 40 MHz only).
|
||||
* Returns 0 on an invalid combination. */
|
||||
inline uint32_t find_fc_mhz(uint32_t channel, uint32_t bw, int sec_ch) {
|
||||
/* 2.4G */
|
||||
if (channel >= 1 && channel <= 14) {
|
||||
if (bw == 80) return 0;
|
||||
uint32_t fc = 2412 + (channel - 1) * 5;
|
||||
if (bw == 40 && sec_ch == kSecAbove) {
|
||||
if (channel >= 10) return 0;
|
||||
fc += 10;
|
||||
} else if (bw == 40 && sec_ch == kSecBelow) {
|
||||
if (channel <= 2) return 0;
|
||||
fc -= 10;
|
||||
}
|
||||
return fc;
|
||||
}
|
||||
/* 5G */
|
||||
if (channel >= 16 && channel <= 253) {
|
||||
static constexpr uint32_t start_40m[] = {20, 28, 36, 44, 52, 60, 68, 76,
|
||||
84, 92, 100, 108, 116, 124, 132,
|
||||
140, 149, 157, 165, 173, 181, 189,
|
||||
197, 205, 213, 221, 229, 237, 245};
|
||||
static constexpr uint32_t start_80m[] = {20, 36, 52, 68, 84, 100, 116,
|
||||
132, 149, 165, 181, 197, 213, 229};
|
||||
if (bw == 40 || bw == 80) {
|
||||
const uint32_t *start = (bw == 40) ? start_40m : start_80m;
|
||||
size_t n = (bw == 40) ? sizeof(start_40m) / sizeof(start_40m[0])
|
||||
: sizeof(start_80m) / sizeof(start_80m[0]);
|
||||
uint32_t off = (bw == 40) ? 2 : 6; /* CH_OFFSET_40M / CH_OFFSET_80M */
|
||||
for (size_t i = 0; i + 1 < n; i++) {
|
||||
if (channel < start[i + 1]) {
|
||||
channel = start[i] + off;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 5080 + (channel - 16) * 5;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Signed subcarrier indices (312.5 kHz units, relative to fc) covering
|
||||
* [f_lo_khz, f_hi_khz], clipped to the RF bandwidth edge (bw_mhz * 1.6 =
|
||||
* bw/2 / 0.3125 subcarriers each side). */
|
||||
inline std::vector<int> enumerate_tones(uint32_t fc_mhz, uint32_t bw_mhz,
|
||||
uint32_t f_lo_khz, uint32_t f_hi_khz) {
|
||||
std::vector<int> tones;
|
||||
if (!fc_mhz || f_hi_khz < f_lo_khz) return tones;
|
||||
int64_t fc_khz = int64_t(fc_mhz) * 1000;
|
||||
int k_edge = int(bw_mhz * 8 / 5); /* bw/2 / 0.3125 */
|
||||
/* k*312.5 kHz = k*625/2 — ceil/floor in integer math on 2*offset/625. */
|
||||
int64_t lo2 = (int64_t(f_lo_khz) - fc_khz) * 2;
|
||||
int64_t hi2 = (int64_t(f_hi_khz) - fc_khz) * 2;
|
||||
auto div_ceil = [](int64_t a, int64_t b) {
|
||||
return (a >= 0) ? (a + b - 1) / b : -((-a) / b);
|
||||
};
|
||||
auto div_floor = [](int64_t a, int64_t b) {
|
||||
return (a >= 0) ? a / b : -((-a + b - 1) / b);
|
||||
};
|
||||
int k_lo = int(div_ceil(lo2, 625));
|
||||
int k_hi = int(div_floor(hi2, 625));
|
||||
if (k_lo > k_hi && f_lo_khz == f_hi_khz) {
|
||||
/* Single-frequency spec — mask the nearest tone (vendor rounding). */
|
||||
int64_t k10 = (int64_t(f_lo_khz) - fc_khz) * 32 / 1000; /* x10 units */
|
||||
k_lo = k_hi = int((k10 + ((k10 >= 0) ? 5 : -5)) / 10);
|
||||
}
|
||||
for (int k = k_lo; k <= k_hi; k++) {
|
||||
if (k < -k_edge || k > k_edge) continue;
|
||||
tones.push_back(k);
|
||||
}
|
||||
return tones;
|
||||
}
|
||||
|
||||
/* ---- env spec parsing ---------------------------------------------------- */
|
||||
|
||||
struct CsiMaskSpec {
|
||||
bool valid = false;
|
||||
uint32_t f_lo_khz = 0, f_hi_khz = 0;
|
||||
uint8_t wgt = 7; /* Jaguar-3 3-bit suppression weight (7 = strongest) */
|
||||
};
|
||||
|
||||
/* "5210-5230" (MHz range) | "5220" (single frequency) with optional "/W"
|
||||
* Jaguar-3 weight suffix, e.g. "5210-5230/7". */
|
||||
inline CsiMaskSpec parse_csi_spec(const char *s) {
|
||||
CsiMaskSpec spec;
|
||||
if (!s || !*s) return spec;
|
||||
char *end = nullptr;
|
||||
unsigned long lo = std::strtoul(s, &end, 10);
|
||||
if (end == s) return spec;
|
||||
unsigned long hi = lo;
|
||||
if (*end == '-') {
|
||||
const char *p = end + 1;
|
||||
hi = std::strtoul(p, &end, 10);
|
||||
if (end == p) return spec;
|
||||
}
|
||||
if (*end == '/') {
|
||||
const char *p = end + 1;
|
||||
unsigned long w = std::strtoul(p, &end, 10);
|
||||
if (end != p && w <= 7) spec.wgt = uint8_t(w);
|
||||
}
|
||||
if (*end != '\0' || hi < lo) return spec;
|
||||
spec.f_lo_khz = uint32_t(lo) * 1000;
|
||||
spec.f_hi_khz = uint32_t(hi) * 1000;
|
||||
spec.valid = true;
|
||||
return spec;
|
||||
}
|
||||
|
||||
/* ---- 11ac (Jaguar-1 + Jaguar-2) ------------------------------------------ */
|
||||
|
||||
/* CSI-mask bit arrays: 0x880-0x88F = positive tones 0..127 (one bit per
|
||||
* subcarrier), 0x890-0x89F = negative (bit index 128 - |k|). Builds the full
|
||||
* 32-byte shadow host-side and writes 8 dwords, then sets the 0x874[0] enable.
|
||||
* Returns the number of tones masked. */
|
||||
inline size_t csi_mask_apply_11ac(RtlAdapter &dev, uint32_t fc_mhz,
|
||||
uint32_t bw_mhz, const CsiMaskSpec &spec) {
|
||||
auto tones = enumerate_tones(fc_mhz, bw_mhz, spec.f_lo_khz, spec.f_hi_khz);
|
||||
uint8_t shadow[32] = {};
|
||||
for (int k : tones) {
|
||||
uint32_t idx;
|
||||
if (k >= 0) { /* FREQ_POSITIVE */
|
||||
idx = (uint32_t(k) >= 127) ? 127 : uint32_t(k);
|
||||
} else {
|
||||
uint32_t a = uint32_t(-k);
|
||||
idx = 128 + (128 - ((a >= 128) ? 128 : a));
|
||||
if (idx >= 256) idx = 255;
|
||||
}
|
||||
shadow[idx >> 3] |= uint8_t(1u << (idx & 7));
|
||||
}
|
||||
for (int i = 0; i < 8; i++) {
|
||||
uint32_t dw = uint32_t(shadow[i * 4]) | (uint32_t(shadow[i * 4 + 1]) << 8) |
|
||||
(uint32_t(shadow[i * 4 + 2]) << 16) |
|
||||
(uint32_t(shadow[i * 4 + 3]) << 24);
|
||||
dev.rtw_write32(uint16_t(0x880 + i * 4), dw);
|
||||
}
|
||||
dev.phy_set_bb_reg(0x874, 0x1, tones.empty() ? 0 : 1);
|
||||
return tones.size();
|
||||
}
|
||||
|
||||
inline void csi_mask_clear_11ac(RtlAdapter &dev) {
|
||||
for (int i = 0; i < 8; i++)
|
||||
dev.rtw_write32(uint16_t(0x880 + i * 4), 0);
|
||||
dev.phy_set_bb_reg(0x874, 0x1, 0);
|
||||
}
|
||||
|
||||
/* NBI notch, 11ac: quantize the tone offset (x10 fixed point, vendor units)
|
||||
* into the register LUT and write 0x87C[19:14] + the per-family enables.
|
||||
* f_intf must fall inside the tuned bandwidth. */
|
||||
inline bool nbi_apply_11ac(RtlAdapter &dev, Family fam, uint32_t fc_mhz,
|
||||
uint32_t bw_mhz, uint32_t f_intf_mhz,
|
||||
bool paths_ge_2t) {
|
||||
/* tone_idx x10 units */
|
||||
static constexpr uint32_t nbi_128[] = {25, 55, 85, 115, 135, 155, 185, 205,
|
||||
225, 245, 265, 285, 305, 335, 355,
|
||||
375, 395, 415, 435, 455, 485, 505,
|
||||
525, 555, 585, 615, 635};
|
||||
static constexpr uint32_t nbi_256[] = {
|
||||
25, 55, 85, 115, 135, 155, 175, 195, 225, 245, 265, 285,
|
||||
305, 325, 345, 365, 385, 405, 425, 445, 465, 485, 505, 525,
|
||||
545, 565, 585, 605, 625, 645, 665, 695, 715, 735, 755, 775,
|
||||
795, 815, 835, 855, 875, 895, 915, 935, 955, 975, 995, 1015,
|
||||
1035, 1055, 1085, 1105, 1125, 1145, 1175, 1195, 1225, 1255, 1275};
|
||||
uint32_t bw_up = fc_mhz + bw_mhz / 2, bw_low = fc_mhz - bw_mhz / 2;
|
||||
if (f_intf_mhz < bw_low || f_intf_mhz > bw_up) return false;
|
||||
uint32_t dist = (f_intf_mhz > fc_mhz) ? (f_intf_mhz - fc_mhz)
|
||||
: (fc_mhz - f_intf_mhz);
|
||||
uint32_t idx10 = dist << 5; /* 10 * (dist / 0.3125) */
|
||||
|
||||
bool use_256 = (fam == Family::AC1) || (bw_mhz == 80);
|
||||
const uint32_t *lut = use_256 ? nbi_256 : nbi_128;
|
||||
size_t n = use_256 ? sizeof(nbi_256) / sizeof(nbi_256[0])
|
||||
: sizeof(nbi_128) / sizeof(nbi_128[0]);
|
||||
uint32_t reg_idx = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (idx10 < lut[i]) {
|
||||
reg_idx = uint32_t(i) + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
dev.phy_set_bb_reg(0x87c, 0xfc000, reg_idx);
|
||||
dev.phy_set_bb_reg(0x87c, 1u << 13, 1);
|
||||
if (fam == Family::AC2_8822B) {
|
||||
dev.phy_set_bb_reg(0xc20, 1u << 28, 1);
|
||||
if (paths_ge_2t) dev.phy_set_bb_reg(0xe20, 1u << 28, 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void nbi_disable_11ac(RtlAdapter &dev, Family fam,
|
||||
bool paths_ge_2t) {
|
||||
dev.phy_set_bb_reg(0x87c, 1u << 13, 0);
|
||||
if (fam == Family::AC2_8822B) {
|
||||
dev.phy_set_bb_reg(0xc20, 1u << 28, 0);
|
||||
if (paths_ge_2t) dev.phy_set_bb_reg(0xe20, 1u << 28, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Jaguar-3 (8822C / 8822E) -------------------------------------------- */
|
||||
|
||||
/* The CSI-mask table lives behind an indexed window: 0x1EE8[1:0]=3 opens it,
|
||||
* 0x1D94[31:30]=1 selects write mode, BYTE2 = table address (= tone_idx/2),
|
||||
* [7:0] = two 4-bit entries (low nibble even tone, high nibble odd tone),
|
||||
* each BIT3-enable | 3-bit weight. tone_num tracks the RF bandwidth via
|
||||
* 0x9B0[3:2] (RF80 -> 128, else 64). Adjacent tones share a table byte, so the
|
||||
* per-address byte is accumulated host-side first — the vendor's one-tone
|
||||
* setter would clobber its neighbour's nibble when looped over a range. */
|
||||
inline size_t csi_mask_apply_jgr3(RtlAdapter &dev, uint32_t fc_mhz,
|
||||
uint32_t bw_mhz, const CsiMaskSpec &spec) {
|
||||
uint8_t rf_bw = dev.rtw_read8(0x9b0);
|
||||
uint32_t tone_num = (((rf_bw & 0xc) >> 2) == 0x2) ? 128 : 64;
|
||||
auto tones = enumerate_tones(fc_mhz, bw_mhz, spec.f_lo_khz, spec.f_hi_khz);
|
||||
|
||||
uint8_t table[128] = {}; /* 256 tone entries / 2 per byte */
|
||||
uint8_t nib = uint8_t(0x8 | (spec.wgt & 0x7));
|
||||
for (int k : tones) {
|
||||
uint32_t idx;
|
||||
if (k >= 0) {
|
||||
idx = (uint32_t(k) >= tone_num - 1) ? (tone_num - 1) : uint32_t(k);
|
||||
} else {
|
||||
uint32_t a = uint32_t(-k);
|
||||
if (a >= tone_num) a = tone_num;
|
||||
idx = (tone_num << 1) - a;
|
||||
}
|
||||
if (idx >= 256) continue;
|
||||
table[idx >> 1] |= (idx & 1) ? uint8_t(nib << 4) : nib;
|
||||
}
|
||||
|
||||
uint32_t idx_lmt = tone_num; /* full table for the current FFT size */
|
||||
dev.phy_set_bb_reg(0x1ee8, 0x3, 0x3);
|
||||
dev.phy_set_bb_reg(0x1d94, 0xc0000000, 0x1);
|
||||
for (uint32_t a = 0; a < idx_lmt; a++) {
|
||||
dev.phy_set_bb_reg(0x1d94, 0x00ff0000, a);
|
||||
dev.phy_set_bb_reg(0x1d94, 0x000000ff, table[a]);
|
||||
}
|
||||
dev.phy_set_bb_reg(0x1ee8, 0x3, 0x0);
|
||||
dev.phy_set_bb_reg(0xc0c, 1u << 3, tones.empty() ? 0 : 1);
|
||||
return tones.size();
|
||||
}
|
||||
|
||||
inline void csi_mask_clear_jgr3(RtlAdapter &dev) {
|
||||
dev.phy_set_bb_reg(0x1ee8, 0x3, 0x3);
|
||||
dev.phy_set_bb_reg(0x1d94, 0xc0000000, 0x1);
|
||||
for (uint32_t a = 0; a < 128; a++) {
|
||||
dev.phy_set_bb_reg(0x1d94, 0x00ff0000, a);
|
||||
dev.phy_set_bb_reg(0x1d94, 0x000000ff, 0);
|
||||
}
|
||||
dev.phy_set_bb_reg(0x1ee8, 0x3, 0x0);
|
||||
dev.phy_set_bb_reg(0xc0c, 1u << 3, 0);
|
||||
}
|
||||
|
||||
/* NBI notch, Jaguar-3: tone index (312.5 kHz units, kHz-exact per the x2cu
|
||||
* tree) into 0x1944/0x4044[20:12] per path; enable 0x818[3]=0 (inverted on
|
||||
* 8822C/E) + 0x818[11]=1 + 0x1D3C[30:27]=0xF + 0x1940/0x4040[31]. */
|
||||
inline bool nbi_apply_jgr3(RtlAdapter &dev, uint32_t fc_mhz,
|
||||
uint32_t bw_mhz, uint32_t f_intf_khz, int n_paths) {
|
||||
uint32_t fc_khz = fc_mhz * 1000;
|
||||
uint32_t bw_up = fc_khz + bw_mhz * 500, bw_low = fc_khz - bw_mhz * 500;
|
||||
if (f_intf_khz < bw_low || f_intf_khz > bw_up) return false;
|
||||
uint32_t dist = (f_intf_khz > fc_khz) ? (f_intf_khz - fc_khz)
|
||||
: (fc_khz - f_intf_khz);
|
||||
uint32_t idx = dist / 312;
|
||||
|
||||
uint8_t rf_bw = dev.rtw_read8(0x9b0);
|
||||
uint32_t tone_num = (((rf_bw & 0xc) >> 2) == 0x2) ? 128 : 64;
|
||||
if (f_intf_khz >= fc_khz) { /* FREQ_POSITIVE */
|
||||
if (idx >= tone_num - 1) idx = tone_num - 1;
|
||||
} else {
|
||||
if (idx >= tone_num) idx = tone_num;
|
||||
idx = (tone_num << 1) - idx;
|
||||
}
|
||||
|
||||
static constexpr uint16_t tone_reg[] = {0x1944, 0x4044};
|
||||
static constexpr uint16_t en_reg[] = {0x1940, 0x4040};
|
||||
if (n_paths > 2) n_paths = 2; /* 8822C/E are 2T2R */
|
||||
for (int p = 0; p < n_paths; p++)
|
||||
dev.phy_set_bb_reg(tone_reg[p], 0x001FF000, idx);
|
||||
|
||||
dev.phy_set_bb_reg(0x818, 1u << 3, 0); /* !enable on 8822C/8822E */
|
||||
dev.phy_set_bb_reg(0x818, 1u << 11, 1);
|
||||
dev.phy_set_bb_reg(0x1d3c, 0x78000000, 0xf);
|
||||
for (int p = 0; p < n_paths; p++)
|
||||
dev.phy_set_bb_reg(en_reg[p], 1u << 31, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* phydm_nbi_reset_jgr3 (8822C/E subset). */
|
||||
inline void nbi_disable_jgr3(RtlAdapter &dev) {
|
||||
dev.phy_set_bb_reg(0x818, 1u << 3, 1);
|
||||
dev.phy_set_bb_reg(0x1d3c, 0x78000000, 0);
|
||||
dev.phy_set_bb_reg(0x818, 1u << 3, 0);
|
||||
dev.phy_set_bb_reg(0x818, 1u << 11, 0);
|
||||
dev.phy_set_bb_reg(0x1940, 1u << 31, 0);
|
||||
dev.phy_set_bb_reg(0x4040, 1u << 31, 0);
|
||||
}
|
||||
|
||||
/* ---- spec-driven entry point ----------------------------------------------
|
||||
*
|
||||
* Applies whichever of the two specs is non-null (DeviceConfig rx.csi_mask /
|
||||
* rx.nbi), for the current channel state. Call after the channel set (like
|
||||
* rx.path_spec, the mask is the final word for a single-channel capture; a
|
||||
* later channel switch does not re-derive it). n_paths: RX chains to arm for
|
||||
* the Jaguar-3 NBI / the 8822B second-path enable. */
|
||||
inline void apply(RtlAdapter &dev, Logger_t logger, Family fam,
|
||||
const SelectedChannel &ch, int n_paths,
|
||||
const char *csi_env, const char *nbi_env) {
|
||||
if (!csi_env && !nbi_env) return;
|
||||
|
||||
uint32_t bw_mhz = bw_mhz_from(ch.ChannelWidth);
|
||||
int sec = sec_from_prime_offset(ch.ChannelOffset);
|
||||
uint32_t fc = find_fc_mhz(ch.Channel, bw_mhz, sec);
|
||||
if (!fc) {
|
||||
logger->error("ToneMask: no fc for ch={} bw={} sec={} — knobs ignored",
|
||||
unsigned(ch.Channel), bw_mhz, sec);
|
||||
return;
|
||||
}
|
||||
|
||||
if (csi_env) {
|
||||
CsiMaskSpec spec = parse_csi_spec(csi_env);
|
||||
if (!spec.valid) {
|
||||
logger->error("DEVOURER_RX_CSI_MASK — bad spec '{}' "
|
||||
"(want <fstart>[-<fend>][/wgt], MHz)", csi_env);
|
||||
} else {
|
||||
size_t masked = (fam == Family::JGR3)
|
||||
? csi_mask_apply_jgr3(dev, fc, bw_mhz, spec)
|
||||
: csi_mask_apply_11ac(dev, fc, bw_mhz, spec);
|
||||
if (fam == Family::JGR3) {
|
||||
logger->info("DEVOURER_RX_CSI_MASK: {} tones masked (fc={} MHz, "
|
||||
"wgt={}), 0xc0c=0x{:08x}",
|
||||
masked, fc, spec.wgt, dev.rtw_read32(0xc0c));
|
||||
} else {
|
||||
logger->info("DEVOURER_RX_CSI_MASK: {} tones masked (fc={} MHz), "
|
||||
"0x874=0x{:08x} mask[0x880..0x89c]={:08x} {:08x} {:08x} "
|
||||
"{:08x} {:08x} {:08x} {:08x} {:08x}",
|
||||
masked, fc, dev.rtw_read32(0x874), dev.rtw_read32(0x880),
|
||||
dev.rtw_read32(0x884), dev.rtw_read32(0x888),
|
||||
dev.rtw_read32(0x88c), dev.rtw_read32(0x890),
|
||||
dev.rtw_read32(0x894), dev.rtw_read32(0x898),
|
||||
dev.rtw_read32(0x89c));
|
||||
}
|
||||
if (!masked)
|
||||
logger->warn("DEVOURER_RX_CSI_MASK: spec '{}' covers no tone inside "
|
||||
"the tuned {} MHz channel — mask disabled", csi_env,
|
||||
bw_mhz);
|
||||
}
|
||||
}
|
||||
|
||||
if (nbi_env) {
|
||||
char *end = nullptr;
|
||||
unsigned long f_mhz = std::strtoul(nbi_env, &end, 10);
|
||||
if (end == nbi_env || *end != '\0') {
|
||||
logger->error("DEVOURER_RX_NBI — bad frequency '{}' (want MHz)", nbi_env);
|
||||
} else {
|
||||
bool ok = (fam == Family::JGR3)
|
||||
? nbi_apply_jgr3(dev, fc, bw_mhz, uint32_t(f_mhz) * 1000,
|
||||
n_paths)
|
||||
: nbi_apply_11ac(dev, fam, fc, bw_mhz, uint32_t(f_mhz),
|
||||
n_paths >= 2);
|
||||
if (ok) {
|
||||
if (fam == Family::JGR3)
|
||||
logger->info("DEVOURER_RX_NBI: notch at {} MHz (fc={}), "
|
||||
"0x818=0x{:08x} 0x1944=0x{:08x}",
|
||||
f_mhz, fc, dev.rtw_read32(0x818),
|
||||
dev.rtw_read32(0x1944));
|
||||
else
|
||||
logger->info("DEVOURER_RX_NBI: notch at {} MHz (fc={}), "
|
||||
"0x87c=0x{:08x}",
|
||||
f_mhz, fc, dev.rtw_read32(0x87c));
|
||||
} else {
|
||||
logger->warn("DEVOURER_RX_NBI: {} MHz outside the tuned {} MHz "
|
||||
"channel (fc={}) — notch not armed", f_mhz, bw_mhz, fc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace tonemask */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_TONE_MASK_H */
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
/* ITransport — the bus seam. USB (libusb) and PCIe (vfio) are independent
|
||||
* transports implementing this one interface; RtlAdapter (the copyable value
|
||||
* type every HAL holds) owns a shared_ptr to one of them and forwards. Nothing
|
||||
* here depends on libusb or vfio.
|
||||
*
|
||||
* Two planes, mirroring how the chips are built:
|
||||
* - register plane: 8/16/32-bit accesses into the 0x0000..0xFFFF MAC/BB
|
||||
* register space (USB: vendor control transfers; PCIe: BAR2 MMIO).
|
||||
* - frame plane: TX submissions and the blocking RX delivery loop
|
||||
* (USB: bulk endpoints; PCIe: 88xx buffer-descriptor DMA rings).
|
||||
*
|
||||
* hci_setup() is the rtw88-style pre-power hook: programming that must happen
|
||||
* before the power-on sequence each bring-up attempt (PCIe TRX ring
|
||||
* registers; nothing on USB). */
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include "TxStats.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* USB-descriptor-derived link facts consumed by the HALs (queue mapping,
|
||||
* RX-aggregation sizing). A PCIe transport returns the defaults. */
|
||||
/* libusb_speed numeric values, mirrored so HAL code comparing link speed does
|
||||
* not need libusb.h (the whole point of the transport seam). */
|
||||
constexpr int kUsbSpeedHigh = 3; /* LIBUSB_SPEED_HIGH (480 MBit/s) */
|
||||
constexpr int kUsbSpeedSuper = 4; /* LIBUSB_SPEED_SUPER (5 GBit/s) */
|
||||
|
||||
struct UsbLinkInfo {
|
||||
bool valid = false; /* true only on the USB transport */
|
||||
int speed = 0; /* libusb_speed numeric value */
|
||||
uint16_t vid = 0, pid = 0;
|
||||
uint8_t bulk_in_ep = 0x81;
|
||||
std::vector<uint8_t> bulk_out_eps; /* descriptor order */
|
||||
};
|
||||
|
||||
class ITransport {
|
||||
public:
|
||||
virtual ~ITransport() = default;
|
||||
|
||||
virtual bool is_usb() const = 0;
|
||||
|
||||
/* ---- register plane ---- */
|
||||
virtual uint8_t read8(uint16_t reg) = 0;
|
||||
virtual uint16_t read16(uint16_t reg) = 0;
|
||||
virtual uint32_t read32(uint16_t reg) = 0;
|
||||
virtual bool write8(uint16_t reg, uint8_t v) = 0;
|
||||
virtual bool write16(uint16_t reg, uint16_t v) = 0;
|
||||
virtual bool write32(uint16_t reg, uint32_t v) = 0;
|
||||
virtual bool write_bytes(uint16_t reg, const uint8_t *p, size_t n) = 0;
|
||||
/* 32-bit *address* register write. Realtek splits the register address as
|
||||
* (wIndex << 16) | wValue over USB, so addresses >= 0x10000 (the halbb/halrf
|
||||
* BB register window at addr + 0x10000) need the high half in wIndex — the
|
||||
* plain 16-bit write forces wIndex=0 and would corrupt the MAC/system space.
|
||||
* The default forwards to the 16-bit path (correct for addr < 0x10000); the
|
||||
* USB transport overrides it to carry the full address. */
|
||||
virtual bool write32_wide(uint32_t addr, uint32_t v) {
|
||||
return write32(static_cast<uint16_t>(addr), v);
|
||||
}
|
||||
/* 32-bit-address register read (the read counterpart of write32_wide;
|
||||
* needed for masked BB read-modify-write and RF-window reads). */
|
||||
virtual uint32_t read32_wide(uint32_t addr) {
|
||||
return read32(static_cast<uint16_t>(addr));
|
||||
}
|
||||
|
||||
/* ---- frame plane ---- */
|
||||
/* Fire-and-forget data TX (the send_packet hot path). `ep` is the USB
|
||||
* bulk-OUT endpoint choice; the PCIe transport ignores it (the ring is
|
||||
* chosen from the descriptor's QSEL). */
|
||||
virtual bool tx_async(uint8_t ep, uint8_t *buf, size_t len,
|
||||
unsigned timeout_ms) = 0;
|
||||
/* Synchronous TX that blocks until the transport confirms consumption
|
||||
* (USB: bulk completion; PCIe: hardware read-pointer / BCN kick). Returns
|
||||
* bytes submitted or a negative error. */
|
||||
virtual int tx_sync(uint8_t ep, uint8_t *buf, size_t len, int timeout_ms) = 0;
|
||||
/* Blocking RX delivery loop until should_stop(). buf_size/n_xfers are USB
|
||||
* URB-queue tuning; the PCIe ring depth is fixed at transport creation. */
|
||||
virtual void rx_loop(int buf_size, int n_xfers,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop) = 0;
|
||||
/* Single-shot raw RX read (USB bulk-IN); unsupported (-1) on PCIe. */
|
||||
virtual int rx_raw(uint8_t *buf, int len, int timeout_ms) {
|
||||
(void)buf; (void)len; (void)timeout_ms;
|
||||
return -1;
|
||||
}
|
||||
virtual void clear_halt(uint8_t ep) { (void)ep; }
|
||||
/* Stop the TX engine and return only once nothing is in flight: cancel every
|
||||
* outstanding transfer, reap the completions, and refuse further sends. The
|
||||
* caller-owned bus context (libusb here) must still be alive, so this has to
|
||||
* run BEFORE any of it is torn down — which is exactly why it is an explicit
|
||||
* call and not destructor work. Idempotent. Default no-op: a transport whose
|
||||
* TX is synchronous has nothing outstanding by construction. */
|
||||
virtual void quiesce_tx() {}
|
||||
|
||||
/* ---- lifecycle / info ---- */
|
||||
/* Pre-power-on HCI programming, re-run per bring-up attempt (rtw88's
|
||||
* rtw_hci_setup slot: PCIe TRX buffer-descriptor ring registers; no-op on
|
||||
* USB). */
|
||||
virtual void hci_setup() {}
|
||||
virtual UsbLinkInfo usb_info() const { return {}; }
|
||||
virtual TxStats tx_stats() const { return {}; }
|
||||
};
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
/* TriggerParse — decode a received 802.11ax Trigger frame.
|
||||
*
|
||||
* A Trigger is an 802.11 CONTROL frame (FC type 1, subtype 2) aired in a
|
||||
* legacy/non-HT PPDU, so ANY monitor — including an 11ac witness that cannot
|
||||
* decode HE data — captures the bytes and this parser reads them. That is the
|
||||
* validation lever for the F2P/UL_FIXINFO scheduled-UL path: point rxdemo at
|
||||
* the AP and confirm the aired trigger's fields match what was commanded, which
|
||||
* also empirically resolves the fw's RU/mode encoding.
|
||||
*
|
||||
* Symmetric with build_basic_trigger() (TriggerTwt.h); the round-trip is a
|
||||
* headless selftest (tests/trigger_parse_selftest.cpp). Header-only, no deps,
|
||||
* neutral namespace — same shape as RxPacket.h / RadiotapPeek.h. */
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct TriggerUserInfo {
|
||||
uint16_t aid12 = 0;
|
||||
uint8_t ru_alloc = 0;
|
||||
bool ldpc = false;
|
||||
uint8_t mcs = 0;
|
||||
bool dcm = false;
|
||||
uint8_t ss = 0;
|
||||
int8_t tgt_rssi_dbm = 0;
|
||||
};
|
||||
|
||||
struct TriggerInfo {
|
||||
uint8_t trigger_type = 0; /* 0 = Basic, 1 = Beamforming Report Poll, ... */
|
||||
uint16_t ul_length = 0;
|
||||
uint8_t ul_bw = 0; /* 0 = 20, 1 = 40, 2 = 80, 3 = 160 */
|
||||
uint8_t gi_ltf = 0;
|
||||
uint8_t num_he_ltf = 0;
|
||||
uint8_t ap_tx_power = 0;
|
||||
uint8_t ta[6] = {0}; /* transmitter (AP) address */
|
||||
uint8_t ra[6] = {0}; /* receiver address */
|
||||
uint8_t n_users = 0; /* User Info fields decoded (capped at cap below) */
|
||||
TriggerUserInfo users[8];
|
||||
};
|
||||
|
||||
/* True iff `frame` (an 802.11 frame body, no radiotap, no FCS) is a Trigger
|
||||
* control frame. Cheap FC check for an RX-loop fast path. */
|
||||
inline bool is_trigger_frame(const uint8_t *frame, size_t len) {
|
||||
/* FC byte0: version[1:0]=0, type[3:2]=01(control), subtype[7:4]=0010 -> 0x24. */
|
||||
return frame != nullptr && len >= 2 && frame[0] == 0x24;
|
||||
}
|
||||
|
||||
/* Parse a Basic-Trigger-style frame into `out`. Returns false if the frame is
|
||||
* not a trigger or is too short for the fixed header + one User Info. The FCS
|
||||
* (last 4 bytes on a monitor capture that includes it) is ignored; pass either
|
||||
* with or without it. Up to 8 User Info fields are decoded. */
|
||||
inline bool parse_trigger(const uint8_t *frame, size_t len, TriggerInfo &out) {
|
||||
/* FC(2) + Duration(2) + RA(6) + TA(6) + Common(8) = 24, then >=1 user (5). */
|
||||
if (!is_trigger_frame(frame, len) || len < 24 + 5)
|
||||
return false;
|
||||
out = TriggerInfo{};
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
out.ra[i] = frame[4 + i];
|
||||
out.ta[i] = frame[10 + i];
|
||||
}
|
||||
/* Common Info: little-endian 8-byte bitfield (see build_basic_trigger). */
|
||||
uint64_t common = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
common |= static_cast<uint64_t>(frame[16 + i]) << (8 * i);
|
||||
out.trigger_type = static_cast<uint8_t>(common & 0xf);
|
||||
out.ul_length = static_cast<uint16_t>((common >> 4) & 0xfff);
|
||||
out.ul_bw = static_cast<uint8_t>((common >> 18) & 0x3);
|
||||
out.gi_ltf = static_cast<uint8_t>((common >> 20) & 0x3);
|
||||
out.num_he_ltf = static_cast<uint8_t>((common >> 23) & 0x7);
|
||||
out.ap_tx_power = static_cast<uint8_t>((common >> 28) & 0x3f);
|
||||
/* User Info fields until the frame ends. Each is 5 common bytes + a
|
||||
* Trigger-Dependent User Info whose size is set by the trigger type (Basic=1
|
||||
* byte, per 802.11ax). A Padding field (AID12 == 4095) or a sub-6-byte tail
|
||||
* (a capture's trailing FCS) ends the list. */
|
||||
const size_t tdep = out.trigger_type == 0 ? 1 : 0; /* Basic Trigger: 1 byte */
|
||||
const size_t ustride = 5 + tdep;
|
||||
size_t o = 24;
|
||||
out.n_users = 0;
|
||||
while (o + ustride <= len && out.n_users < 8) {
|
||||
uint64_t ui = 0;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
ui |= static_cast<uint64_t>(frame[o + i]) << (8 * i);
|
||||
const uint16_t aid = static_cast<uint16_t>(ui & 0xfff);
|
||||
/* AID12 == 0xFFF marks a Padding User Info — end of the user list. */
|
||||
if (aid == 0xfff)
|
||||
break;
|
||||
TriggerUserInfo &u = out.users[out.n_users];
|
||||
u.aid12 = aid;
|
||||
u.ru_alloc = static_cast<uint8_t>((ui >> 12) & 0xff);
|
||||
u.ldpc = ((ui >> 20) & 0x1) != 0;
|
||||
u.mcs = static_cast<uint8_t>((ui >> 21) & 0xf);
|
||||
u.dcm = ((ui >> 25) & 0x1) != 0;
|
||||
u.ss = static_cast<uint8_t>((ui >> 26) & 0x3f);
|
||||
/* Target RSSI subfield [38:32]: 0..90 = -110..-20 dBm; 127 = max power (0). */
|
||||
uint8_t rssi7 = static_cast<uint8_t>((ui >> 32) & 0x7f);
|
||||
u.tgt_rssi_dbm =
|
||||
(rssi7 >= 91) ? 0 : static_cast<int8_t>(static_cast<int>(rssi7) - 110);
|
||||
out.n_users++;
|
||||
o += ustride;
|
||||
}
|
||||
return out.n_users > 0;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,273 @@
|
||||
#pragma once
|
||||
|
||||
/* TriggerTwt — the 802.11ax trigger-based UL + TWT session knobs.
|
||||
*
|
||||
* These are devourer-native aggregates: the small set of fields a caller
|
||||
* actually sets to make the firmware air an HE Trigger frame (UL-OFDMA grant)
|
||||
* or to program a TWT / UL-OFDMA schedule. The Kestrel HAL maps them onto the
|
||||
* vendor fw command surface (F2P trigger, TWT info/act/announce/OFDMA,
|
||||
* UL_FIXINFO); the raw 46-/72-dword vendor structs never surface here.
|
||||
*
|
||||
* The plane split, same as the rest of the AX MAC surface:
|
||||
* - The AP (this driver) owns the schedule and builds the frames the fw airs.
|
||||
* - The STA MAC fires its UL-OFDMA transmission at trigger+SIFS in hardware.
|
||||
* TWT negotiation (the S1G Action frames) is host-built like any mgmt frame;
|
||||
* what the fw provides is the *scheduling* machinery these structs drive.
|
||||
*
|
||||
* Only trigger frames are 802.11 CONTROL frames (FC type 1, subtype 2), aired
|
||||
* in a legacy/non-HT PPDU — so any monitor, including an 11ac witness, captures
|
||||
* and decodes the bytes (see TriggerParse.h); no HE PHY is needed to validate
|
||||
* what flew. Docs: docs/he-extended-range.md is the sibling per-packet path;
|
||||
* this is the scheduled-UL path. */
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* One user's UL grant inside a Basic Trigger (one HE User Info field). */
|
||||
struct TrigUser {
|
||||
uint16_t aid12 = 0; /* 12-bit association id of the granted STA (0 = the
|
||||
* unassociated/random-access slot) */
|
||||
uint8_t macid = 0; /* fw macid the grant is scored against */
|
||||
/* 8-bit RU Allocation subfield (802.11ax Trigger User Info). 61 = 242-tone =
|
||||
* a full 20 MHz RU. Build it with he_ru_alloc(). NOTE: whether the fw's
|
||||
* ru_pos field wants this exact 802.11 code or its own RU index is verified
|
||||
* on-air from the aired trigger's decoded User Info (runtime discovery). */
|
||||
uint8_t ru_alloc = 61;
|
||||
uint8_t ul_mcs = 0; /* 0..11 */
|
||||
uint8_t ss = 1; /* spatial-stream count for this user (1..8) */
|
||||
bool ldpc = false; /* UL FEC: false = BCC, true = LDPC */
|
||||
bool dcm = false; /* dual-carrier modulation */
|
||||
int8_t tgt_rssi_dbm = -60; /* AP's requested UL receive level (dBm) */
|
||||
uint8_t pref_ac = 0; /* 0 = BE, 1 = BK, 2 = VI, 3 = VO */
|
||||
};
|
||||
|
||||
/* A Basic Trigger (UL-OFDMA) — the one-shot F2P command config. Defaults air a
|
||||
* single-user, full-20 MHz, MCS0 Basic Trigger, so a demo needs only a macid /
|
||||
* aid to fire one. */
|
||||
struct TriggerConfig {
|
||||
uint8_t ul_bw = 0; /* solicited UL BW: 0 = 20, 1 = 40, 2 = 80, 3 = 160 */
|
||||
uint8_t gi_ltf = 0; /* HE GI+LTF combo (0 = 1x/1.6us short) */
|
||||
uint8_t num_he_ltf = 1; /* HE-LTF symbol count (0..7) */
|
||||
uint8_t ap_tx_power = 20; /* AP TX power field, 0..63 (Common Info) */
|
||||
/* UL Length (Common Info B4-B15): the L-SIG Length the solicited TB PPDU
|
||||
* carries — a station computes its TB-PPDU duration from it, so a Basic
|
||||
* Trigger with UL Length 0 elicits NO response. 0x1F4 (~a few-hundred-us TB
|
||||
* PPDU, enough for a QoS-Null even with no buffered data) is a safe default;
|
||||
* tune to the granted RU/MCS/duration for a data grant. */
|
||||
uint16_t ul_length = 0x1F4;
|
||||
uint8_t pri20_bitmap = 0x1; /* primary-20 punctured-channel bitmap */
|
||||
uint16_t trig_rate = 0; /* the trigger frame's OWN legacy-PPDU TX rate
|
||||
* (AX 9-bit rate code; 0 = lowest OFDM). Trigger
|
||||
* frames air non-HT so any RX can decode them. */
|
||||
uint8_t mode = 0; /* fw f2p "mode" (2-bit) — undocumented, swept in
|
||||
* kestrelprobe (runtime discovery) */
|
||||
uint8_t frexch_type = 0; /* fw frame-exchange type (6-bit) — undocumented */
|
||||
/* Transmitter Address of the aired Trigger (host-injection path). A station
|
||||
* only answers a Trigger whose TA equals the BSSID it associated to, so this
|
||||
* MUST be the AP's own address; all-zero falls back to the injection SA. */
|
||||
std::array<uint8_t, 6> ta{};
|
||||
/* Receiver Address. Zero = broadcast (a Basic Trigger addresses its users by
|
||||
* AID12, so broadcast RA is standard); set to a STA MAC to unicast. */
|
||||
std::array<uint8_t, 6> ra{};
|
||||
std::array<TrigUser, 8> users{}; /* up to 4 on the 8852B (v0), 8 on the 8852C
|
||||
* (v1); n_users above the die max is clamped */
|
||||
uint8_t n_users = 1;
|
||||
};
|
||||
|
||||
/* Encode a target-RSSI dBm into the 7-bit 802.11ax Target RSSI subfield:
|
||||
* 0..90 = -110..-20 dBm (encoded = dBm + 110); 127 = "transmit at max power"
|
||||
* (no RSSI target, selected by dbm >= 0). Out-of-range dBm clamps into 0..90. */
|
||||
inline uint8_t he_tgt_rssi_enc(int dbm) {
|
||||
if (dbm >= 0)
|
||||
return 127;
|
||||
int v = dbm + 110;
|
||||
if (v < 0)
|
||||
v = 0;
|
||||
if (v > 90)
|
||||
v = 90;
|
||||
return static_cast<uint8_t>(v);
|
||||
}
|
||||
|
||||
/* Encode the 8-bit RU Allocation subfield (802.11ax Trigger User Info) for a
|
||||
* whole-RU-size allocation. `index` selects among equal-size RUs in the BW.
|
||||
* 242-tone (index 0) = a full 20 MHz RU = 61 (the TriggerConfig default). This
|
||||
* is the 802.11 standard code; the fw's own ru_pos convention is verified
|
||||
* on-air (see TrigUser::ru_alloc). */
|
||||
inline uint8_t he_ru_alloc(unsigned tones, unsigned index = 0) {
|
||||
switch (tones) {
|
||||
case 26:
|
||||
return static_cast<uint8_t>(index <= 36 ? index : 0); /* 26-tone RU #index */
|
||||
case 52:
|
||||
return static_cast<uint8_t>(37 + (index & 0xf)); /* 52-tone */
|
||||
case 106:
|
||||
return static_cast<uint8_t>(53 + (index & 0x7)); /* 106-tone */
|
||||
case 242:
|
||||
return static_cast<uint8_t>(61 + (index & 0x3)); /* 242-tone / full 20 MHz */
|
||||
case 484:
|
||||
return static_cast<uint8_t>(65 + (index & 0x1)); /* 484-tone / full 40 MHz */
|
||||
case 996:
|
||||
return 67; /* 996-tone / full 80 MHz */
|
||||
default:
|
||||
return 61; /* fallback: full 20 MHz */
|
||||
}
|
||||
}
|
||||
|
||||
/* TWT agreement config (mac_twt_info_upd). The AP owns the timetable; trgt_tsf
|
||||
* is an absolute 64-bit TSF instant (read ReadTsf(), add lead time). */
|
||||
struct TwtConfig {
|
||||
bool broadcast = false; /* false = individual TWT, true = broadcast TWT */
|
||||
bool trigger = true; /* trigger-enabled TWT (AP sends triggers in the SP) */
|
||||
bool announced = false; /* announced (true) vs unannounced (false) flow */
|
||||
bool protection = false;
|
||||
uint8_t flow_id = 0; /* TWT flow id (0..7) */
|
||||
uint8_t config_id = 0; /* fw TWT config slot (0..7) */
|
||||
uint8_t port = 0; /* MAC port (0..3) */
|
||||
uint8_t band = 0; /* 0 = band0/2.4-5G, 1 = band1 */
|
||||
uint8_t wake_exp = 10; /* wake-interval exponent (interval = man << exp us) */
|
||||
uint16_t wake_man = 512; /* wake-interval mantissa */
|
||||
uint8_t min_wake_dur = 255; /* nominal minimum wake duration (unit below) */
|
||||
bool wake_dur_us256 = false; /* dur unit: false = 256us, true = 1 TU */
|
||||
uint64_t trgt_tsf = 0; /* absolute target wake time (TSF microseconds) */
|
||||
bool ap_role = true; /* nic_role: AP (true) vs STA (false) */
|
||||
};
|
||||
|
||||
/* Bind / unbind a STA (macid) to a TWT agreement (mac_twt_act). */
|
||||
struct TwtStaAct {
|
||||
uint8_t macid = 0;
|
||||
uint8_t config_id = 0;
|
||||
uint8_t action = 0; /* 0 add, 1 del, 2 terminate, 3 suspend, 4 resume */
|
||||
};
|
||||
|
||||
/* TWT-OFDMA cadence (mac_twt_ofdma_info_upd, fw func 0x03). This is the "fw
|
||||
* autonomously airs trigger rounds inside the TWT SP" lever. The func is
|
||||
* non-canonical in the vendor tree (gated MAC_FEAT_TWT_OFDMA_EN, default 0) —
|
||||
* whether the shipped fw implements it is a runtime discovery; UlOfdmaConfig is
|
||||
* the canonical fallback. */
|
||||
struct TwtOfdmaConfig {
|
||||
uint8_t option = 0;
|
||||
uint8_t twt_id = 0; /* which TWT config to schedule */
|
||||
uint8_t max_tf_retry = 3; /* max Basic-Trigger retries per round */
|
||||
uint8_t max_dl_retry = 0;
|
||||
uint8_t round_num = 1; /* UL-OFDMA rounds per TWT service period */
|
||||
uint8_t preferred_ac = 0; /* 0 BE / 1 BK / 2 VI / 3 VO */
|
||||
bool htc_bsr_ctrl_en = false;
|
||||
uint16_t round_interval_us = 0; /* spacing between rounds */
|
||||
};
|
||||
|
||||
/* One STA in the UL_FIXINFO scheduler table. */
|
||||
struct UlOfdmaSta {
|
||||
uint8_t macid = 0;
|
||||
uint8_t pref_ac = 0;
|
||||
uint8_t ru_pos = 0; /* fw RU index (verified on-air, see he_ru_alloc) */
|
||||
int8_t tgt_rssi_dbm = -60;
|
||||
uint8_t mcs = 0;
|
||||
uint8_t ss = 1;
|
||||
bool ldpc = false;
|
||||
bool dcm = false;
|
||||
uint16_t bsr_length = 0; /* buffer-status hint (0 = fw decides) */
|
||||
};
|
||||
|
||||
/* UL_FIXINFO — the fw's production UL-OFDMA scheduler table (mac_upd_ul_fixinfo,
|
||||
* CLASS_UL_FIXINFO). mode=tf_periodic makes the fw air Triggers autonomously at
|
||||
* `interval` seconds. Canonical (MAC_FEAT_ULOFDMA), so it is the fallback when
|
||||
* TWT-OFDMA is absent from the shipped fw. */
|
||||
struct UlOfdmaConfig {
|
||||
uint8_t mode = 3; /* 0 periodic, 1 normal, 2 non-trigger, 3 tf_periodic */
|
||||
uint8_t interval_s = 1; /* schedule interval (seconds) */
|
||||
uint8_t bsr_thold = 0;
|
||||
uint8_t store_mode = 0;
|
||||
uint8_t tf_type = 0; /* trigger type (0 = Basic) */
|
||||
uint16_t data_rate = 0; /* trigger PPDU rate (AX 9-bit code) */
|
||||
uint16_t apep_len = 0;
|
||||
bool istwt = false;
|
||||
uint8_t ppdu_bw = 0; /* 0 = 20, 1 = 40, 2 = 80, 3 = 160 */
|
||||
uint8_t gi_ltf = 0;
|
||||
uint8_t multiport_id = 0;
|
||||
std::array<UlOfdmaSta, 8> stas{};
|
||||
uint8_t n_stas = 1;
|
||||
};
|
||||
|
||||
/* Decoded TWT C2H event (twt.notify / twt.wait_anno), emitted by the RX loop. */
|
||||
struct TwtNotify {
|
||||
uint8_t type = 0; /* fw notify type (TWT_NOTIFY_EVT) */
|
||||
uint8_t twt_id = 0;
|
||||
uint64_t tsf = 0; /* TSF-stamped notify instant */
|
||||
bool wait_anno = false; /* true = WAIT_ANNOUNCE (macid list), false = NOTIFY */
|
||||
uint8_t wait_case = 0;
|
||||
uint8_t macid0 = 0, macid1 = 0, macid2 = 0;
|
||||
};
|
||||
|
||||
/* -------- host-side Basic Trigger frame builder (step-0 raw injection) --------
|
||||
*
|
||||
* Assembles an 802.11 Basic Trigger control frame body (no radiotap, no FCS —
|
||||
* the caller prepends radiotap for send_packet and the MAC appends the FCS)
|
||||
* into `out` (>= 32 bytes for one user). Returns the byte length written, or 0
|
||||
* on overflow. Symmetric with parse_trigger() (TriggerParse.h); the round-trip
|
||||
* is a headless selftest. This path exists to (a) validate witness tooling
|
||||
* before the fw path, and (b) probe whether the Kestrel TX path even accepts a
|
||||
* control-frame subtype. The fw F2P path (SendTrigger) is the production one. */
|
||||
inline size_t build_basic_trigger(const TriggerConfig &cfg,
|
||||
const uint8_t ra[6], const uint8_t ta[6],
|
||||
uint8_t *out, size_t cap) {
|
||||
const uint8_t nuser = cfg.n_users == 0 ? 1 : cfg.n_users;
|
||||
/* Basic-Trigger User Info is 6 bytes (5 common + 1 Trigger Dependent). A
|
||||
* Padding field (a User Info with AID12=4095 then 0xFF octets) marks the end
|
||||
* of the list and gives the responder preparation time. */
|
||||
const size_t kPad = 4;
|
||||
const size_t need = 2 /*FC*/ + 2 /*dur*/ + 6 /*RA*/ + 6 /*TA*/ + 8 /*common*/ +
|
||||
static_cast<size_t>(nuser) * 6 /*user info*/ +
|
||||
2 /*pad marker*/ + kPad /*padding*/;
|
||||
if (out == nullptr || cap < need)
|
||||
return 0;
|
||||
size_t o = 0;
|
||||
out[o++] = 0x24; /* FC: version0 | type1(control) | subtype2(trigger) */
|
||||
out[o++] = 0x00; /* FC flags */
|
||||
out[o++] = 0x00; /* Duration lo (fw/HW may overwrite) */
|
||||
out[o++] = 0x00; /* Duration hi */
|
||||
for (int i = 0; i < 6; ++i)
|
||||
out[o++] = ra ? ra[i] : 0xff; /* RA (default broadcast) */
|
||||
for (int i = 0; i < 6; ++i)
|
||||
out[o++] = ta ? ta[i] : 0x00; /* TA */
|
||||
/* Common Info (8 bytes, little-endian bitfield): Trigger Type[3:0]=0 (Basic),
|
||||
* UL Length[15:4], More TF[16], CS Required[17], UL BW[19:18], GI/LTF[21:20],
|
||||
* MU-MIMO LTF[22], Num HE-LTF[25:23], ... AP TX Power[33:28]. */
|
||||
uint64_t common = 0;
|
||||
common |= (static_cast<uint64_t>(cfg.ul_length) & 0xfff) << 4;
|
||||
common |= (static_cast<uint64_t>(cfg.ul_bw) & 0x3) << 18;
|
||||
common |= (static_cast<uint64_t>(cfg.gi_ltf) & 0x3) << 20;
|
||||
common |= (static_cast<uint64_t>(cfg.num_he_ltf) & 0x7) << 23;
|
||||
common |= (static_cast<uint64_t>(cfg.ap_tx_power) & 0x3f) << 28;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
out[o++] = static_cast<uint8_t>((common >> (8 * i)) & 0xff);
|
||||
/* Per-user info (5 bytes = 40 bits, little-endian): AID12[11:0],
|
||||
* RU Alloc[19:12], UL FEC/coding[20], UL MCS[24:21], UL DCM[25],
|
||||
* SS Alloc[31:26], Target RSSI[38:32]. */
|
||||
for (uint8_t u = 0; u < nuser; ++u) {
|
||||
const TrigUser &tu = cfg.users[u];
|
||||
uint64_t ui = 0;
|
||||
ui |= static_cast<uint64_t>(tu.aid12) & 0xfff;
|
||||
ui |= (static_cast<uint64_t>(tu.ru_alloc) & 0xff) << 12;
|
||||
ui |= (static_cast<uint64_t>(tu.ldpc ? 1 : 0)) << 20;
|
||||
ui |= (static_cast<uint64_t>(tu.ul_mcs) & 0xf) << 21;
|
||||
ui |= (static_cast<uint64_t>(tu.dcm ? 1 : 0)) << 25;
|
||||
ui |= (static_cast<uint64_t>(tu.ss) & 0x3f) << 26;
|
||||
ui |= (static_cast<uint64_t>(he_tgt_rssi_enc(tu.tgt_rssi_dbm)) & 0x7f) << 32;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
out[o++] = static_cast<uint8_t>((ui >> (8 * i)) & 0xff);
|
||||
/* Trigger Dependent User Info (Basic Trigger): MPDU MU Spacing Factor[1:0],
|
||||
* TID Aggregation Limit[4:2], reserved[5], Preferred AC[7:6]. */
|
||||
out[o++] = static_cast<uint8_t>((tu.pref_ac & 0x3) << 6);
|
||||
}
|
||||
/* Padding: a User Info whose AID12 = 4095 marks the end of the user list,
|
||||
* then 0xFF octets give the responder time to prepare its TB PPDU. */
|
||||
out[o++] = 0xff;
|
||||
out[o++] = 0x0f; /* AID12 = 0xFFF (4095) in the low 12 bits */
|
||||
for (size_t i = 0; i < kPad; ++i)
|
||||
out[o++] = 0xff;
|
||||
return o;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,120 @@
|
||||
#ifndef DEVOURER_TSF_SYNC_H
|
||||
#define DEVOURER_TSF_SYNC_H
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
#include "RxPacket.h"
|
||||
|
||||
/* One-way hardware time distribution from beacon TSFs.
|
||||
*
|
||||
* A transmitter — any AP, or a devourer StartBeacon master — inserts its live
|
||||
* hardware TSF into every beacon at the instant of transmission: a genuine
|
||||
* sub-µs TX-egress timestamp (Packet::TxEgressTsf). A receiver latches its own
|
||||
* hardware TSF when the beacon arrives (RxPacket::RxAtrib::tsfl). Feeding both
|
||||
* into TsfSync fits the receiver's clock to the transmitter's:
|
||||
*
|
||||
* local_tsf ≈ skew · remote_tsf + offset
|
||||
*
|
||||
* Both endpoints are hardware-latched below the CSMA/queueing layer, so the fit
|
||||
* converges to the two crystals' relationship, not the medium's jitter — the
|
||||
* basis of the reference-broadcast (RBIS) one-way sync that is the only sub-µs
|
||||
* option on Wi-Fi silicon lacking a host-reported TX-egress timestamp. Once
|
||||
* Ready(), LocalForRemote()/RemoteForLocal() translate a timestamp between the
|
||||
* two clocks (e.g. to schedule a local action at a transmitter-defined instant).
|
||||
*
|
||||
* Least-squares in offset coordinates for numerical conditioning; the local
|
||||
* 32-bit tsfl is reconstructed to 64 bits across its ~71.6 min wrap. Header-only,
|
||||
* no chip dependency. Not internally synchronised — feed it from one thread
|
||||
* (typically the RX callback). */
|
||||
namespace devourer {
|
||||
|
||||
class TsfSync {
|
||||
public:
|
||||
/* Feed one beacon: the transmitter's 64-bit hardware egress TSF (µs, from
|
||||
* Packet::TxEgressTsf) and this receiver's 32-bit RX TSF low word (µs,
|
||||
* RxAtrib.tsfl). */
|
||||
void Add(uint64_t remote_tsf, uint32_t local_tsfl) {
|
||||
const int64_t local = ReconLocal(local_tsfl);
|
||||
const int64_t remote = static_cast<int64_t>(remote_tsf);
|
||||
if (!_init) {
|
||||
_x0 = static_cast<double>(remote);
|
||||
_y0 = static_cast<double>(local);
|
||||
_init = true;
|
||||
}
|
||||
const double xi = static_cast<double>(remote) - _x0;
|
||||
const double yi = static_cast<double>(local) - _y0;
|
||||
++_n;
|
||||
_sx += xi;
|
||||
_sy += yi;
|
||||
_sxx += xi * xi;
|
||||
_sxy += xi * yi;
|
||||
_last_remote = remote;
|
||||
_last_local = local;
|
||||
}
|
||||
|
||||
/* Convenience: feed a received Packet. Returns true iff it carried an egress
|
||||
* TSF (a beacon / probe response) and was ingested — so a caller can simply
|
||||
* `sync.Add(packet)` on every frame and let non-beacons fall through. */
|
||||
bool Add(const Packet &p) {
|
||||
const auto tx = p.TxEgressTsf();
|
||||
if (!tx) return false;
|
||||
Add(*tx, p.RxAtrib.tsfl);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Enough samples for a stable line. */
|
||||
bool Ready() const { return _n >= 16; }
|
||||
long long Count() const { return _n; }
|
||||
|
||||
/* Local clock rate relative to the transmitter, in ppm (positive = the local
|
||||
* crystal runs fast). ~0 until a few samples in. */
|
||||
double SkewPpm() const { return (Slope() - 1.0) * 1e6; }
|
||||
|
||||
/* Fitted slope of local vs remote (≈ 1 + skew). */
|
||||
double Slope() const {
|
||||
const double den = static_cast<double>(_n) * _sxx - _sx * _sx;
|
||||
if (den == 0.0) return 1.0;
|
||||
return (static_cast<double>(_n) * _sxy - _sx * _sy) / den;
|
||||
}
|
||||
|
||||
/* Translate a transmitter (remote) TSF to the equivalent local TSF (µs). */
|
||||
int64_t LocalForRemote(uint64_t remote_tsf) const {
|
||||
const double a = Slope();
|
||||
const double b = Intercept(a);
|
||||
return llround(_y0 + a * (static_cast<double>(static_cast<int64_t>(remote_tsf)) - _x0) + b);
|
||||
}
|
||||
|
||||
/* Translate a local TSF to the equivalent transmitter (remote) TSF (µs). */
|
||||
int64_t RemoteForLocal(uint64_t local_tsf) const {
|
||||
const double a = Slope();
|
||||
if (a == 0.0) return static_cast<int64_t>(local_tsf);
|
||||
const double b = Intercept(a);
|
||||
return llround(_x0 + ((static_cast<double>(static_cast<int64_t>(local_tsf)) - _y0) - b) / a);
|
||||
}
|
||||
|
||||
/* Instantaneous (local − remote) offset at the most recent beacon, µs — the
|
||||
* raw crystal offset before the fit, useful as a coarse health readout. */
|
||||
int64_t OffsetUs() const { return _last_local - _last_remote; }
|
||||
|
||||
private:
|
||||
double Intercept(double a) const {
|
||||
return (_sy - a * _sx) / (_n ? static_cast<double>(_n) : 1.0);
|
||||
}
|
||||
int64_t ReconLocal(uint32_t lo) {
|
||||
if (_linit && lo < _plo) _hi += (1LL << 32);
|
||||
_plo = lo;
|
||||
_linit = true;
|
||||
return _hi + lo;
|
||||
}
|
||||
|
||||
bool _init = false, _linit = false;
|
||||
double _x0 = 0, _y0 = 0, _sx = 0, _sy = 0, _sxx = 0, _sxy = 0;
|
||||
long long _n = 0;
|
||||
int64_t _hi = 0, _last_remote = 0, _last_local = 0;
|
||||
uint32_t _plo = 0;
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_TSF_SYNC_H */
|
||||
@@ -0,0 +1,134 @@
|
||||
#pragma once
|
||||
|
||||
/* TxAggPlan — pure layout planning for USB bulk-OUT TX aggregation: packing N
|
||||
* [txdesc][frame] blocks into one URB so the whole burst costs one bulk
|
||||
* transfer (and lands in the TXDMA together, which is what lets the MAC see
|
||||
* back-to-back frames). Mirrors the vendor xmitframe_complete packing rules
|
||||
* (rtl8812au_xmit.c / rtl8822bu_xmit.c):
|
||||
*
|
||||
* - each block starts 8-byte aligned (_RND8);
|
||||
* - the FIRST descriptor carries the block count in dword7[31:24]
|
||||
* (USB_TXAGG_NUM on Jaguar1, DMA_TXAGG_NUM on the HalMAC 88xx chips) —
|
||||
* the caller sets that after building, then re-checksums (dword7 is inside
|
||||
* the checksummed region on every generation);
|
||||
* - the first block MAY carry an 8-byte reserve between its descriptor and
|
||||
* frame, advertised via the descriptor PKT_OFFSET field (unit 8 bytes).
|
||||
* Two per-family policies (lim.first_reserve):
|
||||
* true — Jaguar1 / vendor rtl8812au parity: the reserve is present on
|
||||
* every aggregated transfer and removed exactly when the total
|
||||
* would land on a bulk-MPS multiple (the vendor "usb bulk-out
|
||||
* block check").
|
||||
* false — HalMAC (8822B/8821C/J3) / mainline-rtw88 parity: no reserve
|
||||
* (bench-proven on the 8822BU: the TXDMA block walker does NOT
|
||||
* account PKT_OFFSET in its next-descriptor stride, so a
|
||||
* reserved first block makes the chip re-air block 1
|
||||
* DMA_TXAGG_NUM times). The reserve is ADDED only when the
|
||||
* total would land on a bulk-MPS multiple (the sync bulk path
|
||||
* has no ZLP; an exact multiple stalls the chip-side DMA);
|
||||
* - the OQT guard: at most `descs_per_bulk` descriptors may START inside one
|
||||
* bulk-size window (the vendor UsbTxAggDescNum / halmac BLK_DESC_NUM
|
||||
* discipline — 8812A silicon overflows its output-queue tracker beyond 1
|
||||
* per window, HalMAC chips take 3). Packing stops when the guard trips;
|
||||
* the remainder goes into the next URB.
|
||||
*
|
||||
* Pure math, no I/O — unit-tested headless in tests/txagg_selftest.cpp. */
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct TxAggLimits {
|
||||
size_t desc_size = 48; /* TX descriptor bytes: 40 (Jaguar1) / 48 (J2/J3) */
|
||||
size_t bulk_size = 512; /* USB bulk max packet: 64 FS / 512 HS / 1024 SS */
|
||||
size_t max_bytes = 20480; /* URB buffer cap (vendor MAX_XMITBUF_SZ, USB) */
|
||||
unsigned max_frames = 255; /* agg-num field is 8-bit; Jaguar1 caps at 64.
|
||||
* HalMAC chips parse at most 3 descriptors per
|
||||
* bulk transfer (rtw88 usb_tx_agg_desc_num /
|
||||
* halmac BLK_DESC_NUM) — the caller clamps. */
|
||||
unsigned descs_per_bulk = 0; /* Jaguar1 OQT guard (descriptor STARTS per
|
||||
* bulk window): 1 (8812A), 3 (8814A),
|
||||
* 6 (8821A). 0 = off (HalMAC uses the flat
|
||||
* max_frames cap instead). */
|
||||
bool first_reserve = false; /* first-block 8-byte PKT_OFFSET reserve policy
|
||||
* (see the header comment). */
|
||||
};
|
||||
|
||||
/* One packed block: `offset` is the descriptor start within the URB buffer;
|
||||
* `length` covers desc + (shim pad, first block only) + frame. */
|
||||
struct TxAggBlock {
|
||||
size_t offset;
|
||||
size_t length;
|
||||
};
|
||||
|
||||
struct TxAggPlan {
|
||||
std::vector<TxAggBlock> blocks; /* one per accepted input frame, in order */
|
||||
size_t total = 0; /* final URB length (reserve included) */
|
||||
bool shim = false; /* first desc gets PKT_OFFSET=1 (an 8-byte
|
||||
* pad between it and its frame) — presence
|
||||
* follows lim.first_reserve, flipped when
|
||||
* the total lands on a bulk multiple. */
|
||||
size_t frames() const { return blocks.size(); }
|
||||
};
|
||||
|
||||
inline size_t txagg_rnd8(size_t v) { return (v + 7) & ~static_cast<size_t>(7); }
|
||||
|
||||
/* Greedily pack frames [0..n) (802.11 payload lengths, radiotap already
|
||||
* stripped) into ONE URB under `lim`. Returns the accepted prefix as a block
|
||||
* layout; frames() < n means the caller submits this URB and re-plans the
|
||||
* rest. An empty plan means frame 0 alone exceeds max_bytes (caller falls
|
||||
* back to the single-frame path, which has no cap). */
|
||||
inline TxAggPlan plan_tx_agg(const size_t *frame_lens, size_t n,
|
||||
const TxAggLimits &lim) {
|
||||
TxAggPlan p;
|
||||
if (n == 0 || lim.bulk_size == 0)
|
||||
return p;
|
||||
p.shim = lim.first_reserve;
|
||||
/* Reserve headroom so the boundary escape can ADD the reserve when the
|
||||
* policy starts without one. */
|
||||
const size_t cap =
|
||||
lim.first_reserve ? lim.max_bytes
|
||||
: (lim.max_bytes > 8 ? lim.max_bytes - 8 : 0);
|
||||
size_t tail = 0; /* end of last block (unaligned) */
|
||||
size_t next = 0; /* aligned start of the next block */
|
||||
unsigned desc_count = 0;
|
||||
size_t bulk_ptr = lim.bulk_size; /* end of the bulk window being filled */
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const size_t blk =
|
||||
lim.desc_size + frame_lens[i] + (p.blocks.empty() && p.shim ? 8 : 0);
|
||||
if (next + blk > cap)
|
||||
break;
|
||||
p.blocks.push_back({next, blk});
|
||||
tail = next + blk;
|
||||
next = txagg_rnd8(tail);
|
||||
if (p.blocks.size() >= lim.max_frames)
|
||||
break;
|
||||
/* Jaguar1 OQT guard, evaluated on the NEXT descriptor's start position:
|
||||
* another desc starting inside the current bulk window counts against
|
||||
* descs_per_bulk; crossing into a fresh window resets the count. */
|
||||
if (next < bulk_ptr) {
|
||||
if (lim.descs_per_bulk != 0 && ++desc_count >= lim.descs_per_bulk)
|
||||
break;
|
||||
} else {
|
||||
desc_count = 0;
|
||||
bulk_ptr = (next / lim.bulk_size + 1) * lim.bulk_size;
|
||||
}
|
||||
}
|
||||
p.total = tail;
|
||||
/* Never submit an exact bulk-size multiple (chip-side transfer-end
|
||||
* ambiguity): flip the first-block reserve — drop it when present, insert
|
||||
* it when absent. Either way every later block shifts by 8 and alignment
|
||||
* is preserved. */
|
||||
if (p.total != 0 && p.total % lim.bulk_size == 0) {
|
||||
const int d = p.shim ? -8 : 8;
|
||||
p.shim = !p.shim;
|
||||
p.blocks[0].length += d;
|
||||
for (size_t i = 1; i < p.blocks.size(); ++i)
|
||||
p.blocks[i].offset += d;
|
||||
p.total += d;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Per-chip TX capability report — what modulation features a given adapter can
|
||||
* actually transmit. An adaptive link (or wfb-ng) that blindly sets STBC/LDPC
|
||||
* radiotap flags on a card that lacks them produces malformed frames that never
|
||||
* decode — a well-known OpenIPC-FPV footgun ("LDPC/STBC forced on a card that
|
||||
* lacks them → link dies", e.g. the 1T1R 8811AU/8821AU/8821CU where STBC needs
|
||||
* ≥2 TX chains). devourer already resolves chip identity at construction; this
|
||||
* surfaces it so callers can gate features, and send_packet drops an
|
||||
* unsupported STBC request rather than airing garbage.
|
||||
*/
|
||||
#ifndef DEVOURER_TX_CAPS_H
|
||||
#define DEVOURER_TX_CAPS_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct TxCaps {
|
||||
bool supported = false; /* false on a generation that hasn't wired this */
|
||||
uint8_t n_ss = 0; /* spatial streams the RF supports (1/2/3/4) */
|
||||
bool stbc_ok = false; /* STBC needs ≥2 TX chains — false on 1T1R parts */
|
||||
bool ldpc_ok = false; /* LDPC coding supported */
|
||||
bool sgi_ok = false; /* short guard interval */
|
||||
uint8_t bw_max_mhz = 20; /* widest TX bandwidth (20/40/80) */
|
||||
};
|
||||
|
||||
/* Build caps from the chain count. The load-bearing rule: STBC needs ≥2 TX
|
||||
* chains, so a 1T1R part (chains==1) reports stbc_ok=false — the invariant the
|
||||
* send_packet guard relies on. Pure; unit-tested in tests/tx_caps_selftest.cpp.
|
||||
* LDPC/SGI/bw default true/80 for the 802.11ac Jaguar family. */
|
||||
inline TxCaps tx_caps_for_chains(uint8_t chains, bool ldpc = true,
|
||||
bool sgi = true, uint8_t bw_max_mhz = 80) {
|
||||
TxCaps c;
|
||||
c.supported = true;
|
||||
c.n_ss = chains;
|
||||
c.stbc_ok = chains >= 2;
|
||||
c.ldpc_ok = ldpc;
|
||||
c.sgi_ok = sgi;
|
||||
c.bw_max_mhz = bw_max_mhz;
|
||||
return c;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_TX_CAPS_H */
|
||||
@@ -0,0 +1,56 @@
|
||||
#ifndef DEVOURER_TX_DESC_BITS_H
|
||||
#define DEVOURER_TX_DESC_BITS_H
|
||||
|
||||
/* Little-endian TX-descriptor bit-field write helpers, shared across chip
|
||||
* generations (Jaguar1 FrameParser SET_TX_DESC_*_8812 macros and Jaguar3
|
||||
* FrameParserJaguar3 SET_TX_DESC_*_8822C macros all build on
|
||||
* SET_BITS_TO_LE_4BYTE). Kept neutral so neither generation depends on the
|
||||
* other's parser header. The cpu_to_le and le32_to_cpu helpers used by the macro
|
||||
* bodies come from hal/basic_types.h at the expansion site (as before). */
|
||||
|
||||
typedef unsigned int __u32;
|
||||
|
||||
#ifndef __u16
|
||||
typedef unsigned short __u16;
|
||||
#endif
|
||||
|
||||
typedef signed char s8;
|
||||
typedef unsigned char u8;
|
||||
|
||||
typedef signed short s16;
|
||||
typedef unsigned short u16;
|
||||
|
||||
typedef signed int s32;
|
||||
typedef unsigned int u32;
|
||||
|
||||
#define WriteLE4Byte(_ptr, _val) ((*((u32*)(_ptr))) = cpu_to_le32(_val))
|
||||
#define WriteLE2Byte(_ptr, _val) ((*((u16*)(_ptr))) = cpu_to_le16(_val))
|
||||
#define WriteLE1Byte(_ptr, _val) ((*((u8*)(_ptr))) = ((u8)(_val)))
|
||||
|
||||
#ifndef BIT_LEN_MASK_32
|
||||
#define BIT_LEN_MASK_32(__BitLen) ((u32)(0xFFFFFFFF >> (32 - (__BitLen))))
|
||||
#endif
|
||||
|
||||
#ifndef LE_P4BYTE_TO_HOST_4BYTE
|
||||
#define LE_P4BYTE_TO_HOST_4BYTE(__pStart) (le32_to_cpu(*((u32*)(__pStart))))
|
||||
#endif
|
||||
|
||||
#define BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen) ((u32)(BIT_LEN_MASK_32(__BitLen) << (__BitOffset)))
|
||||
|
||||
#define LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) \
|
||||
(LE_P4BYTE_TO_HOST_4BYTE(__pStart) & (~BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen)))
|
||||
|
||||
#define SET_BITS_TO_LE_4BYTE(__pStart, __BitOffset, __BitLen, __Value) \
|
||||
do \
|
||||
{ \
|
||||
if (__BitOffset == 0 && __BitLen == 32) \
|
||||
WriteLE4Byte(__pStart, __Value); \
|
||||
else \
|
||||
{ \
|
||||
WriteLE4Byte(__pStart, \
|
||||
LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) | \
|
||||
((((u32)__Value) & BIT_LEN_MASK_32(__BitLen)) << (__BitOffset))); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#endif /* DEVOURER_TX_DESC_BITS_H */
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "TxMode.h"
|
||||
|
||||
#include "RateDefinitions.h" // enum MGN_RATE
|
||||
|
||||
namespace devourer {
|
||||
|
||||
TxParams tx_mode_to_params(const TxMode& m) {
|
||||
TxParams p{};
|
||||
p.sgi = m.sgi ? 1 : 0;
|
||||
p.ldpc = m.ldpc ? 1 : 0;
|
||||
p.stbc = m.stbc ? 1 : 0;
|
||||
|
||||
switch (m.bw_mhz) {
|
||||
case 40: p.bwidth = CHANNEL_WIDTH_40; break;
|
||||
case 80: p.bwidth = CHANNEL_WIDTH_80; break;
|
||||
/* The TX descriptor caps at 80 MHz (BWSettingOfDesc 0/1/2); map 160 down. */
|
||||
case 160: p.bwidth = CHANNEL_WIDTH_80; break;
|
||||
default: p.bwidth = CHANNEL_WIDTH_20; break;
|
||||
}
|
||||
|
||||
switch (m.mode) {
|
||||
case TxMode::Mode::HT: {
|
||||
const uint8_t mcs = m.ht_mcs <= 31 ? m.ht_mcs : 0;
|
||||
p.fixed_rate = static_cast<uint8_t>(MGN_MCS0 + mcs);
|
||||
p.vht = false;
|
||||
break;
|
||||
}
|
||||
case TxMode::Mode::VHT: {
|
||||
uint8_t nss = m.vht_nss < 1 ? 1 : (m.vht_nss > 4 ? 4 : m.vht_nss);
|
||||
uint8_t mcs = m.vht_mcs > 9 ? 9 : m.vht_mcs;
|
||||
p.fixed_rate =
|
||||
static_cast<uint8_t>(MGN_VHT1SS_MCS0 + (nss - 1) * 10 + mcs);
|
||||
p.vht = true;
|
||||
break;
|
||||
}
|
||||
case TxMode::Mode::HE: {
|
||||
/* HE is Kestrel-only and flows env -> radiotap -> the Kestrel send_packet
|
||||
* HE parser, NOT through TxParams. This branch is only reached if HE is
|
||||
* set via SetTxMode on a non-HE (Jaguar) chip; map to the closest VHT
|
||||
* rate as a best-effort fallback (MCS clamped to VHT's 0..9). */
|
||||
uint8_t nss = m.he_nss < 1 ? 1 : (m.he_nss > 4 ? 4 : m.he_nss);
|
||||
uint8_t mcs = m.he_mcs > 9 ? 9 : m.he_mcs;
|
||||
p.fixed_rate =
|
||||
static_cast<uint8_t>(MGN_VHT1SS_MCS0 + (nss - 1) * 10 + mcs);
|
||||
p.vht = true;
|
||||
break;
|
||||
}
|
||||
case TxMode::Mode::Legacy:
|
||||
default:
|
||||
/* legacy_rate_500kbps already equals the MGN_* OFDM byte value. */
|
||||
p.fixed_rate = m.legacy_rate_500kbps;
|
||||
p.vht = false;
|
||||
break;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,77 @@
|
||||
/* Programmatic TX-mode descriptor for the Jaguar TX path.
|
||||
*
|
||||
* A TxMode names the modulation class (legacy OFDM / HT / VHT), the rate
|
||||
* (MCS / NSS / legacy rate), bandwidth, and the GI / FEC / STBC modifiers —
|
||||
* everything that decides a frame's on-air PHY rate. It is the type accepted
|
||||
* by RtlJaguarDevice::SetTxMode (the runtime default applied when a frame's
|
||||
* radiotap carries no rate) and produced by RadiotapBuilder's env parser.
|
||||
*
|
||||
* Replaces the former per-knob DEVOURER_TX_* environment variables and the
|
||||
* DEVOURER_TX_HT_MCS library gate: send_packet now honours the radiotap rate
|
||||
* fields unconditionally, and a TxMode supplies the default when there is none.
|
||||
*/
|
||||
#ifndef DEVOURER_TX_MODE_H
|
||||
#define DEVOURER_TX_MODE_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "SelectedChannel.h" // ChannelWidth_t
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct TxMode {
|
||||
enum class Mode { Legacy, HT, VHT, HE };
|
||||
Mode mode = Mode::Legacy;
|
||||
|
||||
/* Legacy OFDM rate in 500 kbps units (the radiotap RATE convention, which is
|
||||
* identical to the MGN_* OFDM enum value): 12=6M, 18=9M, 24=12M, 36=18M,
|
||||
* 48=24M, 72=36M, 96=48M, 108=54M. Default 6M. */
|
||||
uint8_t legacy_rate_500kbps = 12;
|
||||
|
||||
/* HT MCS index 0..31 (NSS implicit: MCS0-7=1ss, 8-15=2ss, ...). */
|
||||
uint8_t ht_mcs = 0;
|
||||
|
||||
/* VHT per 802.11ac: mcs 0..9, nss 1..4. */
|
||||
uint8_t vht_mcs = 0;
|
||||
uint8_t vht_nss = 1;
|
||||
|
||||
/* HE per 802.11ax (Kestrel only): mcs 0..11, nss 1..4. `he_gi_ltf` is the
|
||||
* chip's 3-bit GI/LTF code (enum rtw_gi_ltf): 0=4xLTF+3.2us, 1=4xLTF+0.8us,
|
||||
* 2=2xLTF+1.6us, 3=2xLTF+0.8us, 4=1xLTF+1.6us, 5=1xLTF+0.8us. Default 3
|
||||
* (2xLTF + 0.8us, the common HE-SU choice). */
|
||||
uint8_t he_mcs = 0;
|
||||
uint8_t he_nss = 1;
|
||||
uint8_t he_gi_ltf = 3;
|
||||
|
||||
/* HE ER SU (extended range, Kestrel only): 0 = off (normal HE SU),
|
||||
* 1 = ER 242-tone RU (MCS 0-2, NSS 1, 20 MHz), 2 = ER 106-tone RU (MCS 0
|
||||
* only, ~3 dB more margin). `he_dcm` = dual-carrier modulation (MCS 0/1/3/4;
|
||||
* 0/1 under ER; excludes STBC), stacks with either ER flavour or plain SU. */
|
||||
uint8_t he_er = 0;
|
||||
bool he_dcm = false;
|
||||
|
||||
/* Bandwidth in MHz. Legacy is always 20; HT honours 20/40; VHT/HE 20/40/80. */
|
||||
uint8_t bw_mhz = 20;
|
||||
|
||||
bool sgi = false;
|
||||
bool ldpc = false;
|
||||
bool stbc = false;
|
||||
};
|
||||
|
||||
/* The descriptor inputs send_packet writes, derived from a TxMode. `fixed_rate`
|
||||
* is an MGN_* value (see RadioManagementModule.h); `vht` drives the TX-desc
|
||||
* rate_id (8 for legacy/HT, 9 for VHT). */
|
||||
struct TxParams {
|
||||
uint8_t fixed_rate;
|
||||
bool vht;
|
||||
uint8_t sgi;
|
||||
uint8_t ldpc;
|
||||
uint8_t stbc;
|
||||
ChannelWidth_t bwidth;
|
||||
};
|
||||
|
||||
TxParams tx_mode_to_params(const TxMode& mode);
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif // DEVOURER_TX_MODE_H
|
||||
@@ -0,0 +1,87 @@
|
||||
#include "TxPower.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
int quantize_offset_qdb(int qdb, const TxPowerCaps &caps, int *steps_out) {
|
||||
if (steps_out)
|
||||
*steps_out = 0;
|
||||
if (!caps.supported || caps.step_qdb == 0)
|
||||
return 0;
|
||||
/* Clamp the request to the representable range first so the rounding below
|
||||
* cannot step past a rail. */
|
||||
if (qdb > caps.offset_max_qdb)
|
||||
qdb = caps.offset_max_qdb;
|
||||
if (qdb < caps.offset_min_qdb)
|
||||
qdb = caps.offset_min_qdb;
|
||||
/* Round to the nearest whole step, ties away from zero: a controller asking
|
||||
* for +1 qdB on a 0.5 dB-step family gets +1 step (0.5 dB), not silence. */
|
||||
const int step = caps.step_qdb;
|
||||
int steps;
|
||||
if (qdb >= 0)
|
||||
steps = (qdb + step / 2) / step;
|
||||
else
|
||||
steps = -((-qdb + step / 2) / step);
|
||||
if (steps_out)
|
||||
*steps_out = steps;
|
||||
return steps * step;
|
||||
}
|
||||
|
||||
int rate_diff_steps(int qdb, uint8_t step_qdb) {
|
||||
if (step_qdb == 0)
|
||||
return 0;
|
||||
const int step = step_qdb;
|
||||
if (qdb >= 0)
|
||||
return (qdb + step / 2) / step;
|
||||
return -((-qdb + step / 2) / step);
|
||||
}
|
||||
|
||||
int rate_diff_qdb_for_rate(uint8_t mgn_rate, const TxRateDiffsQdb &d) {
|
||||
/* MGN_* values from RateDefinitions.h, spelled numerically so this stays a
|
||||
* neutral translation unit: CCK 1M/2M/5.5M/11M = 0x02/0x04/0x0b/0x16, the
|
||||
* eight OFDM rates 6M..54M, HT MCS0..7 = 0x80..0x87. */
|
||||
switch (mgn_rate) {
|
||||
case 0x02:
|
||||
case 0x04:
|
||||
case 0x0b:
|
||||
case 0x16:
|
||||
return d.cck;
|
||||
case 0x0c:
|
||||
case 0x12:
|
||||
case 0x18:
|
||||
case 0x24:
|
||||
case 0x30:
|
||||
case 0x48:
|
||||
case 0x60:
|
||||
case 0x6c:
|
||||
return d.legacy;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (mgn_rate >= 0x80 && mgn_rate <= 0x87)
|
||||
return d.mcs[mgn_rate - 0x80];
|
||||
/* HT MCS8+, all VHT/HE, every 2SS+ stream: no diff, i.e. the anchor. */
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::optional<TxRateDiffsQdb>
|
||||
clamp_rate_diffs(const std::optional<TxRateDiffsQdb> &d) {
|
||||
if (!d)
|
||||
return std::nullopt;
|
||||
auto cl = [](int8_t v) -> int8_t { return v < -64 ? -64 : (v > 63 ? 63 : v); };
|
||||
TxRateDiffsQdb out = *d;
|
||||
out.cck = cl(out.cck);
|
||||
out.legacy = cl(out.legacy);
|
||||
for (int i = 0; i < 8; ++i)
|
||||
out.mcs[i] = cl(out.mcs[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
uint32_t pack_rate_diff_word(int8_t d0, int8_t d1, int8_t d2, int8_t d3) {
|
||||
const uint32_t b0 = static_cast<uint32_t>(d0) & 0x7fu;
|
||||
const uint32_t b1 = static_cast<uint32_t>(d1) & 0x7fu;
|
||||
const uint32_t b2 = static_cast<uint32_t>(d2) & 0x7fu;
|
||||
const uint32_t b3 = static_cast<uint32_t>(d3) & 0x7fu;
|
||||
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,189 @@
|
||||
/* Runtime TX-power control types for the adaptive link.
|
||||
*
|
||||
* The TX-power lever has three knobs on IRadio, all live (applied
|
||||
* immediately on a brought-up chip, recorded and applied at InitWrite
|
||||
* otherwise) and all sticky across channel switches:
|
||||
*
|
||||
* - SetTxPowerOffsetQdb(qdb): adjust power RELATIVE to the efuse-calibrated
|
||||
* per-rate table in quarter-dB units, preserving the calibrated per-rate
|
||||
* shape until individual rates saturate at the hardware rails. This is
|
||||
* the closed-loop controller's knob ("back off 2 dB, keep the shape").
|
||||
* - SetTxPowerIndexOverride(idx): force a flat absolute TXAGC index across
|
||||
* all rates (the debug/SDR-visibility knob; -1 reverts to the table).
|
||||
* - SetTxPowerRateDiffs(table): REPLACE the calibrated per-rate shape with a
|
||||
* caller-supplied one (see TxRateDiffsQdb below). The other two knobs keep
|
||||
* composing on top of it.
|
||||
*
|
||||
* The first two compose: effective = clamp(baseline + offset_steps, 0,
|
||||
* index_max), where baseline is the flat index when set, else the per-rate
|
||||
* table value (the caller's when SetTxPowerRateDiffs supplied one).
|
||||
* The offset folds AFTER the per-rate regulatory min() (worldwide-min
|
||||
* txpwr_lmt tables where the family has them), clamped only at the hardware
|
||||
* max — headroom above the generated table is deliberate; compliance is the
|
||||
* operator's call, exactly as with the flat override.
|
||||
*
|
||||
* Units: one TXAGC index step is family-specific (0.5 dB on Jaguar1/Jaguar2's
|
||||
* 6-bit index, 0.25 dB on Jaguar3's 7-bit reference), so the API speaks
|
||||
* quarter-dB (qdB) and reports what was actually applied after quantization.
|
||||
*/
|
||||
#ifndef DEVOURER_TX_POWER_H
|
||||
#define DEVOURER_TX_POWER_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Static per-family capabilities of the TX-power knobs. `step_qdb` is the
|
||||
* quarter-dB value of one hardware index step (2 = 0.5 dB Jaguar1/2,
|
||||
* 1 = 0.25 dB Jaguar3/Kestrel); `step_measured` stays false until the family's
|
||||
* dB-per-step slope has been confirmed on-air (SDR least-squares ramp) —
|
||||
* until then the step is vendor-documentation truth, not measured truth.
|
||||
*
|
||||
* The `rate_diffs*` trio describes SetTxPowerRateDiffs. `rate_diffs_hw_table`
|
||||
* separates the two mechanisms, because they have different costs and
|
||||
* different reach: a hardware per-rate TXAGC table shapes every PPDU the chip
|
||||
* emits (host frames and hardware-timed beacons alike) at no per-frame cost,
|
||||
* while a software send-time fold (Kestrel's fixed-dBm BB target) only shapes
|
||||
* frames the host sequences, costs a register rewrite at each rate change, and
|
||||
* leaves a beacon airing between host frames at the last frame's level. */
|
||||
struct TxPowerCaps {
|
||||
bool supported = false;
|
||||
uint8_t index_max = 0; /* 63 (Jaguar1/2), 127 (Jaguar3), 0 = dBm model */
|
||||
uint8_t step_qdb = 0; /* qdB per index step */
|
||||
bool step_measured = false; /* on-air slope validated for this family */
|
||||
int16_t offset_min_qdb = 0; /* most negative representable offset */
|
||||
int16_t offset_max_qdb = 0; /* most positive representable offset */
|
||||
bool rate_diffs = false; /* SetTxPowerRateDiffs is honoured */
|
||||
bool rate_diffs_hw_table = false; /* false = software send-time fold */
|
||||
bool rate_diffs_measured = false; /* on-air effect confirmed for this variant */
|
||||
};
|
||||
|
||||
/* Snapshot of the TX-power knobs plus representative effective indices.
|
||||
* `flat_index` = -1 means the efuse per-rate baseline is active. The three
|
||||
* representative indices are path-A values for CCK 1M, OFDM 6M and HT MCS7;
|
||||
* `hw_readback` says whether they were read back from the TXAGC registers
|
||||
* (8814A's packed TXAGC port is write-only, so it reports the software
|
||||
* shadow with hw_readback=false). `saturated_low/high` are set when the
|
||||
* last apply clamped at least one rate at a rail — the signal a closed-loop
|
||||
* controller uses to know the knob has run out of travel. */
|
||||
struct TxPowerState {
|
||||
bool valid = false;
|
||||
int16_t flat_index = -1;
|
||||
int16_t offset_qdb = 0; /* quantized offset currently folded, in qdB */
|
||||
int16_t offset_steps = 0; /* same, in hardware index steps */
|
||||
bool saturated_low = false;
|
||||
bool saturated_high = false;
|
||||
int16_t cck_index = -1;
|
||||
int16_t ofdm_index = -1;
|
||||
int16_t mcs7_index = -1;
|
||||
bool hw_readback = false;
|
||||
bool rate_diffs_custom = false; /* A caller-supplied per-rate diff table is
|
||||
* CONFIGURED (SetTxPowerRateDiffs), not
|
||||
* necessarily live on the chip right now:
|
||||
* a flat override (flat_index >= 0)
|
||||
* temporarily flattens the chip's per-rate
|
||||
* table to zero diffs, and re-applies the
|
||||
* configured table once the override
|
||||
* clears. The cck/ofdm/mcs7_index summary
|
||||
* fields always report chip truth for the
|
||||
* current moment (flat during an override,
|
||||
* ref+diff otherwise). */
|
||||
};
|
||||
|
||||
/* Quantize a quarter-dB offset request to a family's step size: round to
|
||||
* nearest step, ties away from zero, then clamp to the caps' offset range.
|
||||
* Returns the applied qdB (what SetTxPowerOffsetQdb reports); the step count
|
||||
* lands in *steps_out when non-null. Returns 0 for unsupported caps. */
|
||||
int quantize_offset_qdb(int qdb, const TxPowerCaps &caps, int *steps_out);
|
||||
|
||||
/* Per-packet TX-power LUT quantizer, shared by the families whose TX
|
||||
* descriptor carries the 3-bit hardware TXPWR_OFSET LUT (Jaguar2 8822B/8821C
|
||||
* at txdesc+0x14[30:28]; 8814A same position via its own descriptor macro).
|
||||
* The field is discrete — {0, -3, -7, -11, +3, +6} dB — so an adaptive
|
||||
* link's continuous request lands on the closest rung. Pure; unit-tested in
|
||||
* tests/txpkt_pwr_selftest.cpp. */
|
||||
inline uint8_t txpkt_pwr_step_for_db(int db) {
|
||||
static const struct { int db; uint8_t step; } lut[] = {
|
||||
{0, 0}, {-3, 1}, {-7, 2}, {-11, 3}, {3, 4}, {6, 5}};
|
||||
uint8_t best = 0;
|
||||
int best_err = 1 << 30;
|
||||
for (const auto &e : lut) {
|
||||
int err = db > e.db ? db - e.db : e.db - db;
|
||||
if (err < best_err) {
|
||||
best_err = err;
|
||||
best = e.step;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/* Inverse: the nominal dB of a LUT step (for readback / logging). */
|
||||
inline int txpkt_pwr_db_for_step(uint8_t step) {
|
||||
static const int db[] = {0, -3, -7, -11, 3, 6};
|
||||
return step < 6 ? db[step] : 0;
|
||||
}
|
||||
|
||||
/* Caller-supplied per-rate TX-power diffs (signed qdB vs the reference anchor),
|
||||
* programmed by IRadio::SetTxPowerRateDiffs. Motivating consumer: a
|
||||
* wall-equalized rate ladder — each rate parked a uniform margin below its
|
||||
* measured PA-compression wall.
|
||||
*
|
||||
* THE CONTRACT, identical on every generation that reports `rate_diffs`: the
|
||||
* table REPLACES the chip's calibrated per-rate shape. Every rate's level is
|
||||
*
|
||||
* anchor + its caller diff (quantized to step_qdb) + the runtime offset
|
||||
*
|
||||
* clamped to the hardware rail. The `anchor` is the level the chip's own
|
||||
* default walk produces for the section reference rate HT MCS7 (1SS, current
|
||||
* channel and bandwidth), so a table of zeros is a no-op at MCS7 and flattens
|
||||
* every other rate onto MCS7's level. Rates this struct does not describe —
|
||||
* HT MCS8+, all VHT/HE, every 2SS+ stream — sit at the anchor.
|
||||
*
|
||||
* Caller diffs are NOT clamped to the regulatory tables: the same operator's-
|
||||
* call permissiveness the offset and flat-override knobs document above.
|
||||
*
|
||||
* Resolution is the family's step: one qdB is one index step on Jaguar3 and
|
||||
* Kestrel, but Jaguar1/Jaguar2 quantize to 0.5 dB, so an odd qdB rounds (ties
|
||||
* away from zero). Storage range is [-64, 63] everywhere — the width of the
|
||||
* Jaguar3 hardware diff field; SetTxPowerRateDiffs clamps before storing.
|
||||
*
|
||||
* Kestrel is the one family without a per-rate hardware table (`rate_diffs_
|
||||
* hw_table` false): its fixed-dBm BB target is rewritten per frame from the
|
||||
* frame's own rate, so there is no calibrated shape underneath and "replace"
|
||||
* reads as "add to the flat session target". See src/kestrel/CLAUDE.md for
|
||||
* the two consequences (per-rate-change register cost, and a hardware-timed
|
||||
* beacon inheriting the last host frame's level).
|
||||
*
|
||||
* Not to be confused with Jaguar1's FastSetTxPowerOffsetQdb: the BB-swing
|
||||
* TxScale it drives sits downstream of the per-rate TXAGC table and is
|
||||
* rate-independent, so the two compose but neither can implement the other. */
|
||||
struct TxRateDiffsQdb {
|
||||
int8_t cck = 0; /* CCK 1..11M rows; [-64, 63] qdB */
|
||||
int8_t legacy = 0; /* OFDM 6..54M control frames; [-64, 63] */
|
||||
int8_t mcs[8] = {0, 0, 0, 0, 0, 0, 0, 0}; /* HT MCS0..7; [-64, 63] each */
|
||||
};
|
||||
|
||||
/* Pack four signed per-rate diffs into one 0x3a00-table word: byte j =
|
||||
* (diff_j & 0x7f), the Jaguar3 7-bit two's-complement diff field. */
|
||||
uint32_t pack_rate_diff_word(int8_t d0, int8_t d1, int8_t d2, int8_t d3);
|
||||
|
||||
/* Quantize one caller diff (qdB) to whole hardware index steps for a family
|
||||
* whose step is `step_qdb`, rounding to nearest with ties away from zero — the
|
||||
* same rule quantize_offset_qdb uses, so a request that vanishes on one knob
|
||||
* vanishes on the other rather than the two disagreeing. 0 for step_qdb 0. */
|
||||
int rate_diff_steps(int qdb, uint8_t step_qdb);
|
||||
|
||||
/* The caller diff (qdB) that applies to one MGN_* rate: CCK 1..11M -> .cck,
|
||||
* OFDM 6..54M -> .legacy, HT MCS0..7 -> .mcs[n], everything else 0 (the anchor).
|
||||
* Takes the raw enum value so this header stays free of RateDefinitions.h. */
|
||||
int rate_diff_qdb_for_rate(uint8_t mgn_rate, const TxRateDiffsQdb &d);
|
||||
|
||||
/* Clamp every field to the [-64, 63] storage range each family shares.
|
||||
* std::nullopt passes through (= restore the chip's calibrated shape). */
|
||||
std::optional<TxRateDiffsQdb>
|
||||
clamp_rate_diffs(const std::optional<TxRateDiffsQdb> &d);
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_TX_POWER_H */
|
||||
@@ -0,0 +1,130 @@
|
||||
#pragma once
|
||||
|
||||
/* TxReport — per-frame TX-status feedback (the vendor "CCX report"): when a
|
||||
* frame's TX descriptor carries SPE_RPT=1 (DeviceConfig tx.report), the
|
||||
* firmware answers each transmission with a C2H report saying whether the
|
||||
* frame was delivered (ACKed — or simply completed, for broadcast/no-ack),
|
||||
* how many hardware retransmissions it took, how long it sat in the TX queue,
|
||||
* and the final rate after any fallback. That is the TX-side link sensor: the
|
||||
* retry count is the ground truth an adaptive rate/power controller wants,
|
||||
* and queue time is the TX-pacing signal.
|
||||
*
|
||||
* Two on-wire formats:
|
||||
* - Jaguar1 (8812/8821): C2H id 0x03 (CCX_TX_RPT), 6-byte payload after the
|
||||
* 2-byte C2H envelope (vendor GET_8812_C2H_TX_RPT_*; queue time in 256 µs
|
||||
* units). The 8814A firmware uses its own TX_RPT layout — not parsed here
|
||||
* (examples/rx decodes it behind DEVOURER_TX_STATUS).
|
||||
* - HalMAC (8822B/8821C/8822C/8822E): a C2H "pkt" — cmd_id 0xFF (C2H_EXTEND),
|
||||
* sub_cmd_id 0x0F (CCX_RPT) — parsed INCLUDING its 4-byte header (vendor
|
||||
* halmac_fw_offload_c2h_nic.h CCX_RPT_GET_*). Echoes the descriptor
|
||||
* SW_DEFINE low byte, so reports correlate to frames per-packet: the
|
||||
* devices stamp a rotating tag into SW_DEFINE when tx.report is on.
|
||||
*
|
||||
* Decode is header-only and pure; the devices emit the result as a
|
||||
* `tx.report` machine event (docs/logging.md) from their C2H RX sites. */
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "Event.h"
|
||||
|
||||
namespace devourer {
|
||||
|
||||
struct TxReport {
|
||||
bool valid = false;
|
||||
/* Delivery state: 0 = done (ACKed, or completed for BMC/no-ack), 1 =
|
||||
* retry-drop (retry limit exhausted without ACK), 2/3 = firmware-specific
|
||||
* (halmac tx_state passthrough; Jaguar1 maps lifetime-drop to 2). */
|
||||
uint8_t state = 0;
|
||||
bool bmc = false; /* broadcast/multicast frame (no ACK expected) */
|
||||
uint8_t macid = 0;
|
||||
uint8_t qsel = 0; /* Jaguar1 only (halmac reports it too) */
|
||||
uint8_t data_retries = 0; /* hardware retransmissions used (0 = first try) */
|
||||
uint8_t rts_retries = 0; /* halmac only */
|
||||
uint16_t queue_time_raw = 0; /* Jaguar1: 256 µs units; halmac: raw fw units */
|
||||
uint8_t final_rate = 0; /* DESC_RATE* hw index of the final attempt */
|
||||
uint8_t sw_define = 0; /* halmac: descriptor SW_DEFINE byte-0 echo */
|
||||
uint8_t missed_rpt = 0; /* halmac MISSED_RPT_NUM — bench-measured on the
|
||||
* 8812CU: the fw stuffs a CONSTANT (4) here on
|
||||
* every report, drops or no drops, so the field
|
||||
* carries no drop accounting on Jaguar3. Detect
|
||||
* emission drops from SW_DEFINE tag gaps instead;
|
||||
* the measured emission ceiling and gap shape are
|
||||
* in docs/scheduled-mac.md. */
|
||||
};
|
||||
|
||||
/* Jaguar1 (8812/8821) CCX payload: `p` points AFTER the 2-byte C2H envelope
|
||||
* (cmd_id, seq). */
|
||||
inline TxReport parse_ccx_8812(const uint8_t *p, size_t len) {
|
||||
TxReport r;
|
||||
if (p == nullptr || len < 6)
|
||||
return r;
|
||||
r.valid = true;
|
||||
r.qsel = p[0] & 0x1f;
|
||||
r.bmc = (p[0] >> 5) & 1;
|
||||
const bool lifetime_over = (p[0] >> 6) & 1;
|
||||
const bool retry_over = (p[0] >> 7) & 1;
|
||||
r.state = retry_over ? 1 : lifetime_over ? 2 : 0;
|
||||
r.macid = p[1];
|
||||
r.data_retries = p[2] & 0x3f;
|
||||
r.queue_time_raw = static_cast<uint16_t>(p[3] | (p[4] << 8));
|
||||
r.final_rate = p[5];
|
||||
return r;
|
||||
}
|
||||
|
||||
/* HalMAC C2H pkt: `c2h` = the report INCLUDING the 4-byte header
|
||||
* (cmd_id[7:0], seq[15:8], sub_cmd_id[23:16], len[31:24]). */
|
||||
inline bool is_ccx_halmac(const uint8_t *c2h, size_t len) {
|
||||
return c2h != nullptr && len >= 16 && c2h[0] == 0xFF && c2h[2] == 0x0F;
|
||||
}
|
||||
|
||||
inline TxReport parse_ccx_halmac(const uint8_t *c2h, size_t len) {
|
||||
TxReport r;
|
||||
if (!is_ccx_halmac(c2h, len))
|
||||
return r;
|
||||
auto dw = [&](size_t off) -> uint32_t {
|
||||
return static_cast<uint32_t>(c2h[off]) |
|
||||
(static_cast<uint32_t>(c2h[off + 1]) << 8) |
|
||||
(static_cast<uint32_t>(c2h[off + 2]) << 16) |
|
||||
(static_cast<uint32_t>(c2h[off + 3]) << 24);
|
||||
};
|
||||
const uint32_t d1 = dw(4), d2 = dw(8), d3 = dw(12);
|
||||
r.valid = true;
|
||||
r.qsel = (d1 >> 8) & 0x1f;
|
||||
r.missed_rpt = (d1 >> 13) & 0x7;
|
||||
r.macid = (d1 >> 16) & 0x7f;
|
||||
r.queue_time_raw = static_cast<uint16_t>(d2 & 0xffff);
|
||||
r.sw_define = (d2 >> 16) & 0xff;
|
||||
r.rts_retries = (d2 >> 24) & 0xf;
|
||||
r.bmc = (d2 >> 29) & 1;
|
||||
r.state = (d2 >> 30) & 0x3;
|
||||
r.data_retries = d3 & 0x3f;
|
||||
r.final_rate = (d3 >> 8) & 0x7f;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Emit the `tx.report` machine event (schema: docs/logging.md). `fmt` names
|
||||
* the on-wire format ("8812" / "halmac"); sw_define/rts fields are
|
||||
* halmac-only and emitted only there. */
|
||||
inline void emit_tx_report(EventSink &sink, const TxReport &r,
|
||||
const char *fmt) {
|
||||
Ev ev(sink, "tx.report");
|
||||
/* t (host monotonic ms): the achieved-report-rate instrument — the CCX
|
||||
* emission ceiling is a reports-per-second quantity, unmeasurable from a
|
||||
* stream with no timebase. */
|
||||
ev.t()
|
||||
.f("state", static_cast<unsigned>(r.state))
|
||||
.f("ok", r.state == 0)
|
||||
.f("retries", static_cast<unsigned>(r.data_retries))
|
||||
.f("final_rate", static_cast<unsigned>(r.final_rate))
|
||||
.f("queue_time_raw", static_cast<unsigned>(r.queue_time_raw))
|
||||
.f("bmc", r.bmc)
|
||||
.f("macid", static_cast<unsigned>(r.macid))
|
||||
.f("fmt", fmt);
|
||||
if (fmt[0] == 'h') /* halmac extras */
|
||||
ev.f("tag", static_cast<unsigned>(r.sw_define))
|
||||
.f("rts_retries", static_cast<unsigned>(r.rts_retries))
|
||||
.f("missed", static_cast<unsigned>(r.missed_rpt));
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef DEVOURER_TX_STATS_H
|
||||
#define DEVOURER_TX_STATS_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* TX submission health — the driver-side drop signal an adaptive-link
|
||||
* controller uses to detect congestion (the "xtx" cut-bitrate trigger). Counted
|
||||
* at the USB bulk-OUT layer, so it is family-agnostic (all three HALs push TX
|
||||
* through the same RtlAdapter).
|
||||
*
|
||||
* `submitted` counts every frame handed to the USB stack; `failed` counts those
|
||||
* that did not complete OK — either a synchronous submit/transfer error or an
|
||||
* async URB completion with a non-OK status. The distinction that matters for
|
||||
* congestion vs. a dead path is `last_was_timeout`: a bulk-OUT TIMEOUT
|
||||
* (LIBUSB_ERROR_TIMEOUT / LIBUSB_TRANSFER_TIMED_OUT) is the chip NAKing because
|
||||
* its TX FIFO is full — recoverable back-pressure, the xtx case — whereas a
|
||||
* hard error (NO_DEVICE, pipe stall, ...) is a broken link. `last_error_rc` is
|
||||
* the raw libusb code of the most recent failure (0 = none yet), or
|
||||
* kTxShortWriteRc for a transfer libusb reported OK but short — the
|
||||
* full-write contract counts that as a failure, and libusb has no code for
|
||||
* it. */
|
||||
|
||||
/* Sentinel for a short bulk write (libusb success, fewer bytes than asked).
|
||||
* Chosen outside every libusb error code (-1..-99) and negated-transfer-status
|
||||
* value so it can never be mistaken for one. */
|
||||
constexpr int kTxShortWriteRc = -1000;
|
||||
|
||||
struct TxStats {
|
||||
uint64_t submitted = 0;
|
||||
uint64_t failed = 0;
|
||||
int last_error_rc = 0; /* raw libusb rc / negated transfer status /
|
||||
* kTxShortWriteRc */
|
||||
bool last_was_timeout = false;
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_TX_STATS_H */
|
||||
@@ -0,0 +1,154 @@
|
||||
#include "UsbDeviceLock.h"
|
||||
|
||||
#if defined(__ANDROID__) || defined(_MSC_VER) || defined(__APPLE__)
|
||||
#include <libusb.h>
|
||||
#else
|
||||
#include <libusb-1.0/libusb.h>
|
||||
#endif
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
namespace {
|
||||
/* Stable identity of the physical adapter: bus number + USB port path, e.g.
|
||||
* "3-1.4" (bus 3, hub-port chain 1 -> 4). The port path is what a real OS keys a
|
||||
* device node to; it survives a VID:PID re-enumeration (unlike the device
|
||||
* address, which the kernel reassigns on every reset). Falls back to the device
|
||||
* address only when the backend can't report a port path. */
|
||||
std::string device_key(libusb_device *dev) {
|
||||
if (dev == nullptr)
|
||||
return "unknown";
|
||||
std::string key = std::to_string(libusb_get_bus_number(dev));
|
||||
uint8_t ports[8] = {0};
|
||||
int pc = libusb_get_port_numbers(dev, ports, sizeof(ports));
|
||||
if (pc > 0) {
|
||||
for (int i = 0; i < pc; ++i)
|
||||
key += (i == 0 ? "-" : ".") + std::to_string(ports[i]);
|
||||
} else {
|
||||
key += "-a" + std::to_string(libusb_get_device_address(dev));
|
||||
}
|
||||
return key;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#if defined(_WIN32)
|
||||
/* ------------------------------------------------------------------ Windows */
|
||||
#include <windows.h>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
UsbDeviceLock::Result UsbDeviceLock::try_acquire(libusb_device *dev,
|
||||
std::string *reason,
|
||||
const std::string &) {
|
||||
if (held())
|
||||
return Result::Acquired;
|
||||
_key = device_key(dev);
|
||||
/* Named mutex in the session-local namespace (no "Global\\" prefix — one user
|
||||
* session's devourer instances are what must not collide). A named mutex is
|
||||
* released when the owning process exits; a crash leaves it ABANDONED, which
|
||||
* the next waiter still acquires — so no stale lock either way. */
|
||||
const std::string name = "devourer-usb-" + _key;
|
||||
_handle = ::CreateMutexA(nullptr, FALSE, name.c_str());
|
||||
if (_handle == nullptr) {
|
||||
if (reason != nullptr)
|
||||
*reason = "cannot create lock mutex for adapter " + _key;
|
||||
return Result::Error;
|
||||
}
|
||||
DWORD w = ::WaitForSingleObject(static_cast<HANDLE>(_handle), 0);
|
||||
if (w == WAIT_TIMEOUT) {
|
||||
::CloseHandle(static_cast<HANDLE>(_handle));
|
||||
_handle = nullptr;
|
||||
if (reason != nullptr)
|
||||
*reason = "adapter " + _key +
|
||||
" is already in use by another devourer process";
|
||||
return Result::Busy;
|
||||
}
|
||||
/* WAIT_OBJECT_0 (clean) or WAIT_ABANDONED (prior owner crashed) -> we own it */
|
||||
return Result::Acquired;
|
||||
}
|
||||
|
||||
bool UsbDeviceLock::held() const { return _handle != nullptr; }
|
||||
|
||||
UsbDeviceLock::~UsbDeviceLock() {
|
||||
if (_handle != nullptr) {
|
||||
::ReleaseMutex(static_cast<HANDLE>(_handle));
|
||||
::CloseHandle(static_cast<HANDLE>(_handle));
|
||||
_handle = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#else
|
||||
/* -------------------------------------------------------------------- POSIX */
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
UsbDeviceLock::Result UsbDeviceLock::try_acquire(libusb_device *dev,
|
||||
std::string *reason,
|
||||
const std::string &lock_dir) {
|
||||
if (held())
|
||||
return Result::Acquired;
|
||||
_key = device_key(dev);
|
||||
|
||||
std::string dir = lock_dir.empty() ? std::string("/tmp") : lock_dir;
|
||||
while (!dir.empty() && dir.back() == '/')
|
||||
dir.pop_back();
|
||||
_path = dir + "/devourer-usb-" + _key + ".lock";
|
||||
|
||||
/* 0666 so a second user on the same host can still open O_RDWR and flock the
|
||||
* same inode (cross-user contention on one adapter must still be caught);
|
||||
* O_NOFOLLOW so a pre-planted symlink in the world-writable tmpdir can't
|
||||
* redirect the open. */
|
||||
_fd = ::open(_path.c_str(), O_CREAT | O_RDWR | O_NOFOLLOW, 0666);
|
||||
if (_fd < 0) {
|
||||
if (reason != nullptr)
|
||||
*reason = "cannot open lock file " + _path;
|
||||
return Result::Error;
|
||||
}
|
||||
/* Non-blocking exclusive advisory lock. flock is tied to the open file
|
||||
* description and is dropped by the kernel when the fd is closed — including
|
||||
* the implicit close on process exit / SIGKILL — so it self-heals. */
|
||||
if (::flock(_fd, LOCK_EX | LOCK_NB) != 0) {
|
||||
::close(_fd);
|
||||
_fd = -1;
|
||||
if (reason != nullptr)
|
||||
*reason = "adapter " + _key +
|
||||
" is already in use by another devourer process";
|
||||
return Result::Busy;
|
||||
}
|
||||
/* Best-effort: record our pid in the file for a human debugging a refusal.
|
||||
* Purely diagnostic — the lock is the flock, not the file contents. */
|
||||
if (::ftruncate(_fd, 0) == 0) {
|
||||
const std::string pid = std::to_string(::getpid()) + "\n";
|
||||
ssize_t wr = ::write(_fd, pid.data(), pid.size());
|
||||
(void)wr;
|
||||
}
|
||||
return Result::Acquired;
|
||||
}
|
||||
|
||||
bool UsbDeviceLock::held() const { return _fd >= 0; }
|
||||
|
||||
UsbDeviceLock::~UsbDeviceLock() {
|
||||
if (_fd >= 0) {
|
||||
/* Closing the fd releases the flock. Deliberately do NOT unlink the lock
|
||||
* file: unlinking races a concurrent waiter (it could lock a now-orphaned
|
||||
* inode while a third process re-creates and locks a fresh one). The file
|
||||
* is a 0-to-few-byte pid stamp reused across runs — the standard lockfile
|
||||
* trade-off. */
|
||||
::flock(_fd, LOCK_UN);
|
||||
::close(_fd);
|
||||
_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,71 @@
|
||||
#ifndef DEVOURER_USB_DEVICE_LOCK_H
|
||||
#define DEVOURER_USB_DEVICE_LOCK_H
|
||||
|
||||
#include <string>
|
||||
|
||||
struct libusb_device;
|
||||
|
||||
namespace devourer {
|
||||
|
||||
/* Cross-platform advisory *exclusive* lock for a single physical USB adapter,
|
||||
* keyed to its bus number + port path (stable across a VID:PID re-enumeration).
|
||||
*
|
||||
* WHY: nothing in userspace stops two devourer instances from opening and
|
||||
* driving the same adapter at once. When that happens the two bring-ups race
|
||||
* the chip reset / firmware download / register writes and wedge it (observed:
|
||||
* processes stuck in uninterruptible USB I/O that even `kill -9` won't clear).
|
||||
* A real OS serialises access to a device node; this gives devourer the same
|
||||
* guarantee at the library boundary — the second instance's acquisition fails,
|
||||
* so `CreateRadio` refuses instead of racing.
|
||||
*
|
||||
* LIFETIME: the lock is held for this object's lifetime and released
|
||||
* automatically when the owning process exits — normally, via SIGKILL, or on a
|
||||
* crash — because the kernel closes the backing fd (POSIX) / handle (Windows)
|
||||
* on process death. There are therefore never stale locks to clean up, which is
|
||||
* exactly the failure mode a PID-file scheme suffers after `kill -9`.
|
||||
*
|
||||
* FAIL-OPEN vs FAIL-CLOSED: genuine contention (another live process holds the
|
||||
* adapter) returns Busy — the caller should refuse. An *infrastructure* failure
|
||||
* (can't create the lock file, e.g. a read-only tmpdir) returns Error — the
|
||||
* caller should log and proceed without exclusivity, so a quirky environment
|
||||
* never bricks an otherwise-working open. */
|
||||
class UsbDeviceLock {
|
||||
public:
|
||||
enum class Result {
|
||||
Acquired, /* we now hold the exclusive lock */
|
||||
Busy, /* another process holds it — caller should refuse */
|
||||
Error, /* couldn't create/lock the primitive — caller may proceed */
|
||||
};
|
||||
|
||||
UsbDeviceLock() = default;
|
||||
~UsbDeviceLock();
|
||||
UsbDeviceLock(const UsbDeviceLock &) = delete;
|
||||
UsbDeviceLock &operator=(const UsbDeviceLock &) = delete;
|
||||
UsbDeviceLock(UsbDeviceLock &&) = delete;
|
||||
UsbDeviceLock &operator=(UsbDeviceLock &&) = delete;
|
||||
|
||||
/* Try to take the exclusive lock for the adapter behind `dev`. On a non-null
|
||||
* `reason`, a human-readable explanation is written for Busy/Error. Idempotent
|
||||
* guard: calling twice on an already-held lock returns Acquired. `lock_dir`
|
||||
* is the lock-file directory (empty = "/tmp"; DeviceConfig usb.lock_dir — the
|
||||
* demos map TMPDIR onto it); ignored on Windows (named mutex, no file). */
|
||||
Result try_acquire(libusb_device *dev, std::string *reason,
|
||||
const std::string &lock_dir = {});
|
||||
|
||||
bool held() const;
|
||||
/* The lock key (e.g. "3-1.4" = bus 3, port path 1.4). Empty until acquired. */
|
||||
const std::string &key() const { return _key; }
|
||||
|
||||
private:
|
||||
std::string _key;
|
||||
#if defined(_WIN32)
|
||||
void *_handle = nullptr; /* HANDLE from CreateMutex, kept opaque in the header */
|
||||
#else
|
||||
int _fd = -1;
|
||||
std::string _path;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_USB_DEVICE_LOCK_H */
|
||||
@@ -0,0 +1,243 @@
|
||||
#include "UsbOpen.h"
|
||||
|
||||
#include "UsbDeviceLock.h"
|
||||
#include "kestrel/KestrelUsbIds.h"
|
||||
|
||||
#if defined(__ANDROID__) || defined(_MSC_VER) || defined(__APPLE__)
|
||||
#include <libusb.h>
|
||||
#else
|
||||
#include <libusb-1.0/libusb.h>
|
||||
#endif
|
||||
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace devourer {
|
||||
|
||||
int find_wifi_interface(libusb_device_handle *handle) {
|
||||
if (handle == nullptr)
|
||||
return 0;
|
||||
|
||||
libusb_device *device = libusb_get_device(handle);
|
||||
libusb_device_descriptor device_descriptor{};
|
||||
if (libusb_get_device_descriptor(device, &device_descriptor) != LIBUSB_SUCCESS)
|
||||
return 0;
|
||||
|
||||
for (uint8_t config_index = 0;
|
||||
config_index < device_descriptor.bNumConfigurations; ++config_index) {
|
||||
libusb_config_descriptor *config = nullptr;
|
||||
if (libusb_get_config_descriptor(device, config_index, &config) !=
|
||||
LIBUSB_SUCCESS)
|
||||
continue;
|
||||
|
||||
for (uint8_t interface_index = 0;
|
||||
interface_index < config->bNumInterfaces; ++interface_index) {
|
||||
const libusb_interface *interface = &config->interface[interface_index];
|
||||
if (interface->num_altsetting == 0)
|
||||
continue;
|
||||
|
||||
/* libusb uses altsetting 0 unless a caller explicitly selects another.
|
||||
* Match that active layout rather than discovering endpoints that are not
|
||||
* live on the wire. */
|
||||
const libusb_interface_descriptor *candidate = &interface->altsetting[0];
|
||||
if (candidate->bInterfaceClass != LIBUSB_CLASS_VENDOR_SPEC)
|
||||
continue;
|
||||
|
||||
bool has_bulk_in = false;
|
||||
bool has_bulk_out = false;
|
||||
for (uint8_t endpoint_index = 0;
|
||||
endpoint_index < candidate->bNumEndpoints; ++endpoint_index) {
|
||||
const libusb_endpoint_descriptor *endpoint =
|
||||
&candidate->endpoint[endpoint_index];
|
||||
if ((endpoint->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) !=
|
||||
LIBUSB_TRANSFER_TYPE_BULK)
|
||||
continue;
|
||||
if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN)
|
||||
has_bulk_in = true;
|
||||
else
|
||||
has_bulk_out = true;
|
||||
}
|
||||
if (has_bulk_in && has_bulk_out) {
|
||||
const int interface_number = candidate->bInterfaceNumber;
|
||||
libusb_free_config_descriptor(config);
|
||||
return interface_number;
|
||||
}
|
||||
}
|
||||
libusb_free_config_descriptor(config);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int claim_interface_then_reset(libusb_device_handle *handle, int iface,
|
||||
const Logger_t &logger, bool do_reset,
|
||||
std::shared_ptr<UsbDeviceLock> &out_lock,
|
||||
const std::string &lock_dir) {
|
||||
if (handle == nullptr)
|
||||
return LIBUSB_ERROR_NO_DEVICE;
|
||||
libusb_device *dev = libusb_get_device(handle);
|
||||
|
||||
/* Advisory exclusive lock FIRST — before detach / claim / reset — so a second
|
||||
* devourer is turned away without disturbing the device at all. This is the
|
||||
* gate that actually holds on platforms where the kernel claim below does not
|
||||
* arbitrate (WinUSB). Genuine contention -> refuse; a lock-infrastructure
|
||||
* failure (e.g. read-only tmpdir) degrades to a warning and we lean on the
|
||||
* kernel claim instead. */
|
||||
auto lock = std::make_shared<UsbDeviceLock>();
|
||||
std::string why;
|
||||
switch (lock->try_acquire(dev, &why, lock_dir)) {
|
||||
case UsbDeviceLock::Result::Busy:
|
||||
logger->error("USB adapter in use — refusing to open ({})", why);
|
||||
return LIBUSB_ERROR_BUSY;
|
||||
case UsbDeviceLock::Result::Error:
|
||||
logger->warn("USB adapter lock unavailable ({}) — leaning on the kernel "
|
||||
"interface claim for exclusivity",
|
||||
why);
|
||||
lock.reset();
|
||||
break;
|
||||
case UsbDeviceLock::Result::Acquired:
|
||||
logger->info("USB adapter {} locked for exclusive access", lock->key());
|
||||
break;
|
||||
}
|
||||
|
||||
if (libusb_kernel_driver_active(handle, iface) == 1)
|
||||
libusb_detach_kernel_driver(handle, iface);
|
||||
|
||||
/* Configure before claiming: a chip that was never kernel-configured is in
|
||||
* config 0, where claim / bulk I/O fail with ESRCH. No-op if already set. */
|
||||
int cfg = 0;
|
||||
if (libusb_get_configuration(handle, &cfg) != 0 || cfg != 1)
|
||||
libusb_set_configuration(handle, 1);
|
||||
|
||||
/* The kernel's exclusive claim — a redundant second gate on Linux usbfs
|
||||
* (reports BUSY); a no-op success on WinUSB, where the lock above is the
|
||||
* real guard. */
|
||||
int rc = libusb_claim_interface(handle, iface);
|
||||
if (rc != 0) {
|
||||
if (rc == LIBUSB_ERROR_BUSY)
|
||||
logger->error("USB interface {} is BUSY — another process is already "
|
||||
"using this adapter; refusing to open",
|
||||
iface);
|
||||
else
|
||||
logger->error("libusb_claim_interface({}) failed: {} ({})", iface,
|
||||
libusb_error_name(rc), rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Kestrel (11ax) adapters never want the USB reset: their power-on sequence
|
||||
* forces the MAC off from any retained state (the real cleaner), while a
|
||||
* USB reset on running/half-torn firmware drops the chip back to its ROM —
|
||||
* a stale-handle re-enumeration that can land in the dead ZeroCD DISK id
|
||||
* (0bda:1a2b). Bench-measured: KILLed-session churn is 6/6 clean without
|
||||
* the reset vs ZeroCD roulette with it (issue #294). */
|
||||
if (do_reset) {
|
||||
libusb_device_descriptor dd{};
|
||||
if (libusb_get_device_descriptor(dev, &dd) == 0 &&
|
||||
kestrel::variant_for_usb_id(dd.idVendor, dd.idProduct).has_value()) {
|
||||
logger->info("Kestrel adapter: skipping USB reset (power-on owns state "
|
||||
"cleanup; a reset drops running firmware into ROM/ZeroCD)");
|
||||
do_reset = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (do_reset) {
|
||||
/* We hold the lock and the interface, so this re-enumeration can't disturb
|
||||
* anyone else. If the reset invalidates the handle, report it; otherwise
|
||||
* re-assert the claim (the reset may have released it). */
|
||||
int rrc = libusb_reset_device(handle);
|
||||
if (rrc == LIBUSB_ERROR_NOT_FOUND) {
|
||||
logger->error("libusb_reset_device: device re-enumerated, handle is "
|
||||
"stale — close and reopen");
|
||||
return rrc;
|
||||
}
|
||||
rc = libusb_claim_interface(handle, iface);
|
||||
if (rc != 0) {
|
||||
logger->error("re-claim of interface {} after reset failed: {} ({})",
|
||||
iface, libusb_error_name(rc), rc);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
|
||||
out_lock = std::move(lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int claim_interface_reset_reopen(libusb_context *ctx,
|
||||
libusb_device_handle *&handle,
|
||||
const Logger_t &logger, bool do_reset,
|
||||
std::shared_ptr<UsbDeviceLock> &out_lock,
|
||||
const std::string &lock_dir,
|
||||
unsigned reopen_timeout_ms) {
|
||||
if (handle == nullptr)
|
||||
return LIBUSB_ERROR_NO_DEVICE;
|
||||
|
||||
/* Record the physical identity BEFORE the reset can invalidate the handle:
|
||||
* bus number + port path name the socket; VID:PID names the device we wait
|
||||
* for (a mid-re-enumeration ZeroCD id at the same port is NOT a match). */
|
||||
libusb_device *dev = libusb_get_device(handle);
|
||||
const uint8_t bus = libusb_get_bus_number(dev);
|
||||
uint8_t ports[8] = {};
|
||||
const int nports = libusb_get_port_numbers(dev, ports, sizeof(ports));
|
||||
libusb_device_descriptor dd{};
|
||||
libusb_get_device_descriptor(dev, &dd);
|
||||
|
||||
int rc = claim_interface_then_reset(handle, find_wifi_interface(handle),
|
||||
logger, do_reset, out_lock, lock_dir);
|
||||
/* Recovery is only meaningful when we could have reset: with do_reset=false
|
||||
* a NOT_FOUND is a claim failure (interface absent), not a re-enumeration —
|
||||
* closing the handle and polling for a comeback would just burn the timeout
|
||||
* (and on Termux would orphan a wrapped fd device-list scans can't find). */
|
||||
if (rc != LIBUSB_ERROR_NOT_FOUND || !do_reset)
|
||||
return rc;
|
||||
|
||||
/* The reset re-enumerated the device (firmware reload through ROM). Close
|
||||
* the stale handle and wait for the same bus+port to come back under the
|
||||
* original VID:PID, then claim WITHOUT another reset — resetting again
|
||||
* would just drop the freshly loaded firmware once more. */
|
||||
libusb_close(handle);
|
||||
handle = nullptr;
|
||||
logger->warn("USB reset re-enumerated the device — waiting for it to "
|
||||
"return on bus {} (up to {} ms)",
|
||||
bus, reopen_timeout_ms);
|
||||
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::milliseconds(reopen_timeout_ms);
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
libusb_device **list = nullptr;
|
||||
const ssize_t n = libusb_get_device_list(ctx, &list);
|
||||
for (ssize_t i = 0; i < n && handle == nullptr; ++i) {
|
||||
if (libusb_get_bus_number(list[i]) != bus)
|
||||
continue;
|
||||
uint8_t p[8] = {};
|
||||
const int np = libusb_get_port_numbers(list[i], p, sizeof(p));
|
||||
if (np != nports || memcmp(p, ports, static_cast<size_t>(np)) != 0)
|
||||
continue;
|
||||
libusb_device_descriptor d{};
|
||||
if (libusb_get_device_descriptor(list[i], &d) != 0)
|
||||
continue;
|
||||
if (d.idVendor != dd.idVendor || d.idProduct != dd.idProduct)
|
||||
continue; /* ZeroCD / transient ROM id — keep waiting */
|
||||
if (libusb_open(list[i], &handle) != 0)
|
||||
handle = nullptr;
|
||||
}
|
||||
if (list != nullptr)
|
||||
libusb_free_device_list(list, 1);
|
||||
if (handle != nullptr)
|
||||
break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(250));
|
||||
}
|
||||
if (handle == nullptr) {
|
||||
logger->error("device did not re-enumerate as {:04x}:{:04x} within {} ms",
|
||||
dd.idVendor, dd.idProduct, reopen_timeout_ms);
|
||||
return LIBUSB_ERROR_NOT_FOUND;
|
||||
}
|
||||
logger->info("re-opened {:04x}:{:04x} after reset re-enumeration",
|
||||
dd.idVendor, dd.idProduct);
|
||||
return claim_interface_then_reset(handle, find_wifi_interface(handle),
|
||||
logger, /*do_reset=*/false, out_lock,
|
||||
lock_dir);
|
||||
}
|
||||
|
||||
} // namespace devourer
|
||||
@@ -0,0 +1,77 @@
|
||||
#ifndef DEVOURER_USB_OPEN_H
|
||||
#define DEVOURER_USB_OPEN_H
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "logger.h"
|
||||
|
||||
struct libusb_device_handle;
|
||||
struct libusb_context;
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class UsbDeviceLock;
|
||||
|
||||
/* Return the vendor Wi-Fi interface that owns bulk IN and OUT endpoints. This
|
||||
* must run before claim_interface_then_reset(): composite RTL8822BU adapters
|
||||
* expose Bluetooth on interfaces 0/1 and Wi-Fi on interface 2. Fall back to
|
||||
* interface 0 for legacy single-interface adapters whose descriptor does not
|
||||
* identify a vendor bulk interface. */
|
||||
int find_wifi_interface(libusb_device_handle *handle);
|
||||
|
||||
/* Prepare an already-opened USB handle for use with the OS-friendly ordering —
|
||||
* *lock and claim before reset*:
|
||||
*
|
||||
* 1. take the advisory exclusive UsbDeviceLock (see UsbDeviceLock.h) FIRST,
|
||||
* before touching the device. This is the cross-platform gate: on Windows
|
||||
* (WinUSB) libusb_claim_interface is not a kernel arbitration point and
|
||||
* does not report BUSY, so the lock — not the claim — is what turns a
|
||||
* second devourer away there, and taking it up front means that second
|
||||
* process resets nothing. `out_lock` receives it; the caller must keep it
|
||||
* alive for as long as it drives the adapter (hand it to CreateRadio,
|
||||
* which then does NOT re-acquire);
|
||||
* 2. detach an attached kernel driver on `iface`;
|
||||
* 3. set configuration 1 (a cold, never-kernel-configured chip sits in config
|
||||
* 0, where claim / bulk I/O fail with ESRCH); no-op if already set;
|
||||
* 4. libusb_claim_interface(iface) — the kernel's exclusive per-interface lock
|
||||
* (this reports BUSY on Linux usbfs, a redundant second gate);
|
||||
* 5. only now, holding both the lock and the interface, and only if `do_reset`,
|
||||
* libusb_reset_device() — safe, since we are the sole owner — then re-claim.
|
||||
*
|
||||
* Returns 0 on success; a libusb error code otherwise (already logged via
|
||||
* `logger`). LIBUSB_ERROR_BUSY means "adapter in use by another process" (from
|
||||
* either the lock or the claim) — the caller should close the handle and exit
|
||||
* without touching the device. On success `out_lock` holds the exclusive lock
|
||||
* (or is null if the lock could only degrade to a warning — e.g. a read-only
|
||||
* tmpdir — in which case the kernel claim still guards). `lock_dir` is the
|
||||
* lock-file directory (empty = "/tmp"; see UsbDeviceLock::try_acquire). */
|
||||
int claim_interface_then_reset(libusb_device_handle *handle, int iface,
|
||||
const Logger_t &logger, bool do_reset,
|
||||
std::shared_ptr<UsbDeviceLock> &out_lock,
|
||||
const std::string &lock_dir = {});
|
||||
|
||||
/* claim_interface_then_reset plus transparent recovery from the reset
|
||||
* re-enumeration: on some chips (Kestrel 35bc:xxxx) libusb_reset_device on a
|
||||
* warm adapter drops the firmware back to ROM and the device re-enumerates —
|
||||
* the handle goes stale (LIBUSB_ERROR_NOT_FOUND) and, on the way through ROM,
|
||||
* the dongle can transiently surface as its ZeroCD id (0bda:1a2b DISK). This
|
||||
* wrapper closes the stale handle, waits (bounded) for the SAME physical
|
||||
* device — bus + port path — to come back under its original VID:PID, then
|
||||
* re-opens and re-claims WITHOUT a second reset: the re-enumeration itself
|
||||
* reloaded the firmware, so its state is fresh. `handle` is replaced in place
|
||||
* on that path (the old handle is closed); `iface` is re-resolved on the new
|
||||
* handle via find_wifi_interface(). All other outcomes are exactly
|
||||
* claim_interface_then_reset() — including NOT_FOUND when `do_reset` is
|
||||
* false, which then can only be a claim failure, not a re-enumeration. `ctx`
|
||||
* must be the context `handle` was opened on. */
|
||||
int claim_interface_reset_reopen(libusb_context *ctx,
|
||||
libusb_device_handle *&handle,
|
||||
const Logger_t &logger, bool do_reset,
|
||||
std::shared_ptr<UsbDeviceLock> &out_lock,
|
||||
const std::string &lock_dir = {},
|
||||
unsigned reopen_timeout_ms = 30000);
|
||||
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_USB_OPEN_H */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
#pragma once
|
||||
|
||||
/* UsbTransport — the libusb implementation of ITransport. Everything
|
||||
* USB-wire-specific that used to live inside the adapter is here: vendor
|
||||
* control transfers for the register plane, sync/async bulk-OUT TX with the
|
||||
* wedge (mid-stream stall) recovery and TX submission counters, the
|
||||
* kernel-rtw88-style async RX URB queue, and the interface-descriptor walk
|
||||
* that discovers the bulk endpoints. The exclusive per-adapter UsbDeviceLock
|
||||
* rides here too — its lifetime is the transport's. */
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include <libusb.h>
|
||||
|
||||
#include "DeviceConfig.h"
|
||||
#include "Transport.h"
|
||||
#include "logger.h"
|
||||
|
||||
namespace devourer {
|
||||
class UsbDeviceLock;
|
||||
}
|
||||
|
||||
#define REALTEK_USB_VENQT_READ 0xC0
|
||||
#define REALTEK_USB_VENQT_WRITE 0x40
|
||||
#define USB_TIMEOUT 500
|
||||
|
||||
namespace devourer {
|
||||
|
||||
class UsbTransport final : public ITransport {
|
||||
public:
|
||||
UsbTransport(libusb_device_handle *dev_handle, Logger_t logger,
|
||||
libusb_context *ctx = nullptr,
|
||||
std::shared_ptr<devourer::UsbDeviceLock> usb_lock = nullptr,
|
||||
bool rx_zerocopy = true, RxMode rx_mode = RxMode::Async,
|
||||
int pool_spare = 0, int ring_ms = 0,
|
||||
PoolExhaust pool_exhaust = PoolExhaust::Backpressure);
|
||||
~UsbTransport() override;
|
||||
|
||||
bool is_usb() const override { return true; }
|
||||
|
||||
uint8_t read8(uint16_t reg) override { return ctrl_read<uint8_t>(reg); }
|
||||
uint16_t read16(uint16_t reg) override { return ctrl_read<uint16_t>(reg); }
|
||||
uint32_t read32(uint16_t reg) override { return ctrl_read<uint32_t>(reg); }
|
||||
bool write8(uint16_t reg, uint8_t v) override { return ctrl_write(reg, v); }
|
||||
bool write16(uint16_t reg, uint16_t v) override { return ctrl_write(reg, v); }
|
||||
bool write32(uint16_t reg, uint32_t v) override { return ctrl_write(reg, v); }
|
||||
bool write32_wide(uint32_t addr, uint32_t v) override {
|
||||
/* Realtek USB register addressing: wValue = addr[15:0], wIndex =
|
||||
* addr[31:16]. Lets the BB/RF window (addr + 0x10000) reach wIndex=1
|
||||
* instead of colliding with the MAC/system space at wIndex=0. */
|
||||
return libusb_control_transfer(
|
||||
_dev_handle, REALTEK_USB_VENQT_WRITE, 5,
|
||||
static_cast<uint16_t>(addr & 0xFFFF),
|
||||
static_cast<uint16_t>(addr >> 16), (uint8_t *)&v, sizeof(v),
|
||||
USB_TIMEOUT) == static_cast<int>(sizeof(v));
|
||||
}
|
||||
uint32_t read32_wide(uint32_t addr) override {
|
||||
uint32_t data = 0;
|
||||
if (libusb_control_transfer(_dev_handle, REALTEK_USB_VENQT_READ, 5,
|
||||
static_cast<uint16_t>(addr & 0xFFFF),
|
||||
static_cast<uint16_t>(addr >> 16),
|
||||
(uint8_t *)&data, sizeof(data),
|
||||
USB_TIMEOUT) == static_cast<int>(sizeof(data)))
|
||||
return data;
|
||||
return 0xFFFFFFFFu; /* INVALID_RF_DATA-style sentinel on a failed read */
|
||||
}
|
||||
bool write_bytes(uint16_t reg, const uint8_t *p, size_t n) override;
|
||||
|
||||
bool tx_async(uint8_t ep, uint8_t *buf, size_t len,
|
||||
unsigned timeout_ms) override;
|
||||
int tx_sync(uint8_t ep, uint8_t *buf, size_t len, int timeout_ms) override;
|
||||
void rx_loop(int buf_size, int n_urbs,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop) override;
|
||||
int rx_raw(uint8_t *buf, int len, int timeout_ms) override;
|
||||
void clear_halt(uint8_t ep) override { libusb_clear_halt(_dev_handle, ep); }
|
||||
void quiesce_tx() override;
|
||||
|
||||
UsbLinkInfo usb_info() const override { return _info; }
|
||||
TxStats tx_stats() const override;
|
||||
|
||||
private:
|
||||
template <typename T> T ctrl_read(uint16_t reg);
|
||||
template <typename T> bool ctrl_write(uint16_t reg, T value);
|
||||
void discover_endpoints(); /* was InitDvObj */
|
||||
const char *speed_str() const;
|
||||
static void transfer_callback(struct libusb_transfer *transfer);
|
||||
|
||||
libusb_device_handle *_dev_handle;
|
||||
libusb_context *_ctx = nullptr;
|
||||
Logger_t _logger;
|
||||
UsbLinkInfo _info;
|
||||
|
||||
/* Set by transfer_callback when an async TX bulk-OUT completes non-OK
|
||||
* (TIMED_OUT / stall). Consumed at the top of the next tx_async on the TX
|
||||
* thread to re-clear_halt the endpoint — a mid-stream stall (e.g. hardware
|
||||
* NDP generation on some xhci hosts) would otherwise stay wedged, since the
|
||||
* first-send clear_halt only runs once. */
|
||||
std::atomic<bool> _tx_wedged{false};
|
||||
|
||||
/* TX submission counters (the driver-drop / congestion signal, TxStats.h).
|
||||
* The async transfer_callback increments them from the libusb event thread. */
|
||||
std::atomic<uint64_t> _tx_submitted{0};
|
||||
std::atomic<uint64_t> _tx_failed{0};
|
||||
std::atomic<int> _tx_last_rc{0};
|
||||
std::atomic<bool> _tx_last_timeout{false};
|
||||
|
||||
/* Async-TX completions must be reaped by libusb_handle_events or the kernel
|
||||
* URB queue fills, submits start failing, and TX throughput collapses (the
|
||||
* Jaguar1 issue #240: its send path is tx_async and a TX-only session has no
|
||||
* other event pump). We reap in the CALLER's thread — each tx_async drains
|
||||
* completed transfers before submitting the next — rather than a background
|
||||
* pump thread, which would race the caller-owned libusb teardown (an earlier
|
||||
* attempt crashed on a usbi_mutex assertion). _tx_inflight tracks
|
||||
* submitted-but-not-yet-reaped transfers so the destructor can drain them
|
||||
* before the device handle / context go away, and so a soft cap can throttle
|
||||
* over-submission. */
|
||||
std::atomic<int> _tx_inflight{0};
|
||||
|
||||
/* Submitted-but-not-yet-completed transfers, so quiesce_tx can cancel them
|
||||
* by handle. transfer_callback removes its own entry, and it runs on
|
||||
* whichever thread pumped the event — the submitting one, or another
|
||||
* tx_async caller under DEVOURER_TX_THREADS. Never hold _tx_mu across a
|
||||
* libusb_handle_events call: the callback re-enters and takes it. */
|
||||
std::mutex _tx_mu;
|
||||
std::vector<libusb_transfer *> _tx_live;
|
||||
|
||||
/* Latched by quiesce_tx. Refuses further submissions (and further event
|
||||
* pumping) so nothing re-enters libusb once teardown has begun, and makes
|
||||
* quiesce idempotent for the Stop()-then-destructor path. */
|
||||
std::atomic<bool> _tx_shutdown{false};
|
||||
|
||||
/* Allocate the async RX ring from kernel DMA memory (dev_mem_alloc) for a
|
||||
* zerocopy bulk-IN path; falls back to heap buffers per-URB when the alloc is
|
||||
* unsupported. See rx_loop and DeviceConfig::Usb::rx_zerocopy. */
|
||||
bool _rx_zerocopy = true;
|
||||
|
||||
/* RX-ring servicing strategy + buffer-pool depth + diagnostic telemetry
|
||||
* cadence, from DeviceConfig::Rx. rx_loop reads these; the defaults preserve
|
||||
* the historic inline async ring with no extra buffers and no telemetry. */
|
||||
RxMode _rx_mode = RxMode::Async;
|
||||
int _pool_spare = 0;
|
||||
int _ring_ms = 0;
|
||||
PoolExhaust _pool_exhaust = PoolExhaust::Backpressure;
|
||||
|
||||
/* rx_loop helpers for the servicing strategies dispatched off _rx_mode. */
|
||||
void rx_loop_sync(int buf_size,
|
||||
const std::function<void(const uint8_t *, int)> &on_data,
|
||||
const std::function<bool()> &should_stop);
|
||||
|
||||
/* Exclusive per-adapter USB lock (UsbDeviceLock.h), held for the transport
|
||||
* lifetime; released when the device (and thus the transport) dies. */
|
||||
std::shared_ptr<devourer::UsbDeviceLock> _usb_lock;
|
||||
};
|
||||
|
||||
template <typename T> T UsbTransport::ctrl_read(uint16_t reg_num) {
|
||||
T data = 0;
|
||||
if (libusb_control_transfer(_dev_handle, REALTEK_USB_VENQT_READ, 5, reg_num,
|
||||
0, (uint8_t *)&data, sizeof(T),
|
||||
USB_TIMEOUT) == sizeof(T)) {
|
||||
return data;
|
||||
}
|
||||
_logger->error("rtw_read({:04x}), sizeof(T) = {}", reg_num, sizeof(T));
|
||||
throw std::ios_base::failure("rtw_read");
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <typename T> bool UsbTransport::ctrl_write(uint16_t reg_num, T value) {
|
||||
return libusb_control_transfer(_dev_handle, REALTEK_USB_VENQT_WRITE, 5,
|
||||
reg_num, 0, (uint8_t *)&value, sizeof(T),
|
||||
USB_TIMEOUT) == sizeof(T);
|
||||
}
|
||||
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,377 @@
|
||||
#include "WiFiDriver.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include <libusb.h>
|
||||
|
||||
#include "RtlAdapter.h"
|
||||
#include "UsbDeviceLock.h"
|
||||
#include "UsbTransport.h" /* REALTEK_USB_VENQT_READ / USB_TIMEOUT for read_chip_id */
|
||||
#if defined(DEVOURER_HAVE_PCIE)
|
||||
#include "PcieTransport.h"
|
||||
#endif
|
||||
#if defined(DEVOURER_HAVE_JAGUAR1)
|
||||
#include "jaguar1/RtlJaguarDevice.h"
|
||||
#endif
|
||||
#if defined(DEVOURER_HAVE_JAGUAR2)
|
||||
#include "jaguar2/RtlJaguar2Device.h"
|
||||
#endif
|
||||
#if defined(DEVOURER_HAVE_JAGUAR3)
|
||||
#include "jaguar3/RtlJaguar3Device.h"
|
||||
#endif
|
||||
#if defined(DEVOURER_HAVE_KESTREL)
|
||||
#include "kestrel/RtlKestrelDevice.h"
|
||||
#endif
|
||||
#include "kestrel/KestrelUsbIds.h" /* header-only PID table, always compiled */
|
||||
#if defined(DEVOURER_HAVE_8733B)
|
||||
#include "rtl8733b/Rtl8733bDevice.h"
|
||||
#endif
|
||||
#include "rtl8733b/Rtl8733bUsbIds.h"
|
||||
#include "mt7612u/Mt7612uUsbIds.h" /* header-only VID:PID table, always compiled */
|
||||
#if defined(DEVOURER_HAVE_MT7612U)
|
||||
#include "mt7612u/Mt7612uRadio.h"
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
/* Hardware chip-id at REG_SYS_CFG2 (0x00FC), read with a single vendor control
|
||||
* transfer (no full RtlAdapter, so the Jaguar1 construction path is unchanged
|
||||
* and only one extra control read is added). Port of halmac get_chip_info
|
||||
* (chip_id = REG_READ_8(REG_SYS_CFG2)):
|
||||
* 0x04 / 0x05 / 0x08 = 8812A / 8821A / 8814A -> Jaguar1
|
||||
* 0x09 = RTL8821C (RTL8811CU / RTL8821CU, 1T1R) -> Jaguar2
|
||||
* 0x0a = RTL8822B (RTL8822BU, 2T2R) -> Jaguar2
|
||||
* 0x13 = RTL8822C, 0x17 = RTL8822E (RTL8812EU / RTL8822EU) -> Jaguar3
|
||||
* 0x16 = RTL8733B (RTL8731BU / RTL8733BU, 1T1R) -> RTL8733B
|
||||
* The chip-id (not the USB PID) is authoritative because the rtl8822e RTL8812EU
|
||||
* shares PID 0x8812 with the Jaguar1 RTL8812AU. (8821C = 0x09 hardware-verified
|
||||
* on a CF-811AC; it is a HalMAC/phydm Jaguar2 chip, NOT the page-write Jaguar1
|
||||
* the "8821C" name might suggest — routing it to Jaguar1 would fail at DLFW.)
|
||||
*
|
||||
* Returns nullopt when the control transfer itself failed, which is NOT the same
|
||||
* as reading 0x00 and matters: this request is Realtek's vendor protocol, so a
|
||||
* device that does not answer it is not Realtek silicon. Measured on the bench,
|
||||
* same transfer, both arms:
|
||||
* RTL8812AU 0bda:8812 rc=1 chip_id=0x04
|
||||
* MT7612U 0e8d:7612 rc=-7 LIBUSB_ERROR_TIMEOUT, destination byte UNTOUCHED
|
||||
* (the MediaTek arm was run with a 0xAA poison byte, which survived — so the
|
||||
* value the caller sees is its own initialiser, never a reading). Discarding the
|
||||
* return code turned that into a plain 0, and 0 matches no id below, so the
|
||||
* device reached the unconditional Jaguar1 fallback and came up as an RTL8812AU.
|
||||
* Distinguishing the two lets CreateRadio refuse instead. A successful read of
|
||||
* 0x00 is deliberately still returned as a value, so any cold-boot transient
|
||||
* keeps its existing fall-through behaviour. */
|
||||
std::optional<uint8_t> read_chip_id(libusb_device_handle *dev_handle) {
|
||||
uint8_t id = 0;
|
||||
int rc = libusb_control_transfer(dev_handle, REALTEK_USB_VENQT_READ, 5, 0x00FC,
|
||||
0, &id, sizeof(id), USB_TIMEOUT);
|
||||
if (rc != static_cast<int>(sizeof(id)))
|
||||
return std::nullopt;
|
||||
return id;
|
||||
}
|
||||
|
||||
/* RTL8822B (Jaguar2) SYS_CFG2 chip-id. Read off a TP-Link Archer T3U
|
||||
* (RTL8822BU): REG_SYS_CFG2 (0x00FC) reads 0x0a in steady state (and in the
|
||||
* demo's post-libusb_reset path), with a transient 0x50 for a brief window
|
||||
* right after a cold VBUS power-cycle before the chip settles. Accept both.
|
||||
* Neither collides with the Jaguar1 (0x04/05/08/09) or Jaguar3 (0x13/0x17)
|
||||
* ids. (SYS_CFG1's low bytes are volatile, so 0xFC is the dispatch signal.)
|
||||
* CAVEAT: on Kestrel (11ax) silicon 0x00FC is R_AX_SYS_CHIPINFO, and the
|
||||
* 8852A die-id is 0x50 — indistinguishable from the 8822B cold transient by
|
||||
* this byte alone. Kestrel PIDs are therefore gated before this read; an
|
||||
* out-of-scope 8852A (PID not in the Kestrel table) falls through here and
|
||||
* fails at the Jaguar2 DLFW rather than being detected. */
|
||||
constexpr uint8_t kChipId8822B = 0x0a;
|
||||
constexpr uint8_t kChipId8822B_cold = 0x50;
|
||||
bool is_8822b_chip_id(uint8_t id) {
|
||||
return id == kChipId8822B || id == kChipId8822B_cold;
|
||||
}
|
||||
|
||||
/* RTL8821C (Jaguar2, 1T1R) SYS_CFG2 chip-id, hardware-verified on a CF-811AC
|
||||
* (RTL8811CU, 0bda:c811): 0x00FC reads 0x09 in steady state. Does not collide
|
||||
* with the Jaguar1 ids (0x04/05/08) it used to be lumped with, nor 8822B (0x0a)
|
||||
* or Jaguar3 (0x13/0x17). */
|
||||
constexpr uint8_t kChipId8821C = 0x09;
|
||||
|
||||
} /* namespace */
|
||||
|
||||
WiFiDriver::WiFiDriver(Logger_t logger) : _logger{std::move(logger)} {}
|
||||
|
||||
std::unique_ptr<IRadio>
|
||||
WiFiDriver::CreateRadio(libusb_device_handle *dev_handle,
|
||||
libusb_context *ctx,
|
||||
std::shared_ptr<devourer::UsbDeviceLock> usb_lock,
|
||||
const devourer::DeviceConfig &cfg) {
|
||||
uint16_t pid = 0;
|
||||
libusb_device *dev = libusb_get_device(dev_handle);
|
||||
if (dev != nullptr) {
|
||||
libusb_device_descriptor desc{};
|
||||
if (libusb_get_device_descriptor(dev, &desc) == 0)
|
||||
pid = desc.idProduct;
|
||||
}
|
||||
|
||||
/* Exclusive per-adapter USB lock (see UsbDeviceLock.h). The recommended open
|
||||
* path (devourer::claim_interface_then_reset) already took this lock BEFORE
|
||||
* the reset and hands it in here — in that case we must NOT re-acquire (a
|
||||
* same-process flock on the same file would self-conflict); we just hold it
|
||||
* for the device lifetime. A caller that opened/claimed the handle itself
|
||||
* passes null, so acquire our own here as a best-effort second gate: genuine
|
||||
* contention -> refuse (return nullptr, same contract as an unsupported chip);
|
||||
* a lock-infrastructure error degrades to a warning. Either way the lock rides
|
||||
* into the RtlAdapter below and is released at device destruction. */
|
||||
if (!usb_lock) {
|
||||
auto lock = std::make_shared<devourer::UsbDeviceLock>();
|
||||
std::string lock_why;
|
||||
switch (lock->try_acquire(dev, &lock_why, cfg.usb.lock_dir)) {
|
||||
case devourer::UsbDeviceLock::Result::Busy:
|
||||
_logger->error("USB adapter in use — refusing to open ({})", lock_why);
|
||||
return nullptr;
|
||||
case devourer::UsbDeviceLock::Result::Error:
|
||||
_logger->warn("USB adapter lock unavailable ({}) — proceeding without "
|
||||
"exclusive access",
|
||||
lock_why);
|
||||
break;
|
||||
case devourer::UsbDeviceLock::Result::Acquired:
|
||||
_logger->info("USB adapter {} locked for exclusive access", lock->key());
|
||||
usb_lock = std::move(lock);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Kestrel (Wi-Fi 6 / 802.11ax, RTL8852B/8852C) gates on the USB VID:PID
|
||||
* BEFORE the SYS_CFG2 read: on AX silicon 0x00FC is R_AX_SYS_CHIPINFO (the
|
||||
* D-die id), not the 11ac chip-id — and the 8852A die-id (0x50) collides
|
||||
* with the 8822B cold-boot transient accepted below, so the register byte
|
||||
* alone cannot dispatch this generation. The Kestrel PID set (vendor
|
||||
* usb_intf.c id tables, see kestrel/KestrelUsbIds.h) is disjoint from every
|
||||
* 11ac PID devourer handles, which makes the PID gate authoritative here
|
||||
* while SYS_CFG2 stays authoritative for the 11ac families (the RTL8812EU /
|
||||
* RTL8812AU PID collision rationale below is untouched). The die-id is read
|
||||
* back inside the HAL as confirmation. */
|
||||
uint16_t vid = 0;
|
||||
if (dev != nullptr) {
|
||||
libusb_device_descriptor desc{};
|
||||
if (libusb_get_device_descriptor(dev, &desc) == 0)
|
||||
vid = desc.idVendor;
|
||||
}
|
||||
if (auto kvariant = kestrel::variant_for_usb_id(vid, pid)) {
|
||||
#if defined(DEVOURER_HAVE_KESTREL)
|
||||
const bool is_8852b = *kvariant == kestrel::ChipVariant::C8852B;
|
||||
#if !defined(DEVOURER_HAVE_KESTREL_8852B)
|
||||
if (is_8852b) {
|
||||
_logger->error("RTL8852B ({:04x}:{:04x}) detected but 8852B support not "
|
||||
"compiled in (DEVOURER_KESTREL_8852B=OFF)",
|
||||
vid, pid);
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
#if !defined(DEVOURER_HAVE_KESTREL_8852C)
|
||||
if (!is_8852b) {
|
||||
_logger->error("RTL8852C ({:04x}:{:04x}) detected but 8852C support not "
|
||||
"compiled in (DEVOURER_KESTREL_8852C=OFF)",
|
||||
vid, pid);
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
_logger->info("Creating RtlKestrelDevice {} ({:04x}:{:04x})",
|
||||
is_8852b ? "C8852B" : "C8852C", vid, pid);
|
||||
return std::make_unique<RtlKestrelDevice>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger, *kvariant,
|
||||
cfg);
|
||||
#else
|
||||
_logger->error("Kestrel chip ({:04x}:{:04x}) detected but Kestrel support "
|
||||
"not compiled in (DEVOURER_KESTREL_8852B/_8852C=OFF)",
|
||||
vid, pid);
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* MediaTek MT7612U gates on the USB VID:PID BEFORE the SYS_CFG2 read, for the
|
||||
* same reason Kestrel does above — but with a sharper failure mode. On this
|
||||
* silicon the Realtek vendor request read_chip_id() issues (bRequest 5) is not
|
||||
* implemented at all, so the control transfer stalls. Before the nullopt
|
||||
* return below existed, that failure was discarded, `id` stayed 0, 0 matched
|
||||
* no Realtek chip-id, and the adapter reached the unconditional Jaguar1
|
||||
* fallback at the end of this function — coming up as an RTL8812AU with every
|
||||
* subsequent register access addressed at the wrong MAC.
|
||||
*
|
||||
* The pair set is disjoint from all 91 Realtek ids devourer can serve, but the
|
||||
* VENDOR ids are NOT: six of them ship both silicon families, and Netgear,
|
||||
* ELECOM and ASUS interleave the two within one vendor's product-id range. So
|
||||
* this must stay a vid:pid test and must never be widened to "not a Realtek
|
||||
* vendor id". Mt7612uUsbIds.h carries the table and the evidence;
|
||||
* Mt7612uUsbIdsSelftest.cpp fails if a later id addition breaks it. */
|
||||
if (mt7612u::is_usb_id(vid, pid)) {
|
||||
#if defined(DEVOURER_HAVE_MT7612U)
|
||||
_logger->info("Creating Mt7612uRadio ({:04x}:{:04x})", vid, pid);
|
||||
return std::make_unique<Mt7612uRadio>(dev_handle, ctx, std::move(usb_lock),
|
||||
_logger, cfg);
|
||||
#else
|
||||
_logger->error("MediaTek MT7612U ({:04x}:{:04x}) detected but MediaTek "
|
||||
"support is not compiled in (DEVOURER_MT7612U=OFF) — "
|
||||
"refusing rather than misdetecting it as Realtek",
|
||||
vid, pid);
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* A vendor read that did not complete means this device is not speaking the
|
||||
* Realtek protocol at all — refuse instead of dropping through to the Jaguar1
|
||||
* fallback at the end of this function, which would bring an unknown part up
|
||||
* as an RTL8812AU. This is the generation-independent half of the same guard
|
||||
* the MediaTek gate above applies by id: the gate names the parts we know,
|
||||
* this catches the ones we do not. It deliberately keys on TRANSFER FAILURE
|
||||
* and not on "vid is not 0x0bda": devourer already serves Realtek silicon
|
||||
* behind ASUS, Edimax, D-Link, ZyXEL, MSI and Mercury vendor ids, and every
|
||||
* one of those answers this read normally (measured: an RTL8812AU returns
|
||||
* 0x04), so a vendor-id rule would refuse working adapters. */
|
||||
std::optional<uint8_t> chip_id_read = read_chip_id(dev_handle);
|
||||
if (!chip_id_read) {
|
||||
_logger->error("SYS_CFG2 chip-id read failed on {:04x}:{:04x} — not a "
|
||||
"Realtek vendor-protocol device; refusing rather than "
|
||||
"falling through to Jaguar1",
|
||||
vid, pid);
|
||||
return nullptr;
|
||||
}
|
||||
uint8_t chip_id = *chip_id_read;
|
||||
|
||||
if (rtl8733b::is_chip_id(chip_id)) {
|
||||
#if defined(DEVOURER_HAVE_8733B)
|
||||
_logger->info("Creating Rtl8733bDevice ({:04x}:{:04x}, chip-id 0x{:02x})",
|
||||
vid, pid, chip_id);
|
||||
return std::make_unique<Rtl8733bDevice>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger, cfg);
|
||||
#else
|
||||
_logger->error("RTL8733B (chip-id 0x16) detected but support not compiled "
|
||||
"in (DEVOURER_8733B=OFF)");
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* A failed/transient register read on a known 8733B PID must not route the
|
||||
* adapter into Jaguar1 merely because that is the historical fallback. */
|
||||
if (rtl8733b::is_usb_id(vid, pid)) {
|
||||
_logger->error("Known RTL8733B USB device {:04x}:{:04x} reported unexpected "
|
||||
"SYS_CFG2 chip-id 0x{:02x}; refusing Jaguar fallback",
|
||||
vid, pid, chip_id);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (is_8822b_chip_id(chip_id)) {
|
||||
#if defined(DEVOURER_HAVE_JAGUAR2)
|
||||
_logger->info("Creating RtlJaguar2Device (PID 0x{:04x}, chip-id 0x{:02x})",
|
||||
pid, chip_id);
|
||||
return std::make_unique<RtlJaguar2Device>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger,
|
||||
jaguar2::ChipVariant::C8822B, cfg);
|
||||
#else
|
||||
_logger->error("RTL8822B (chip-id 0x{:02x}) detected but Jaguar2 support "
|
||||
"not compiled in (DEVOURER_JAGUAR2=OFF)",
|
||||
chip_id);
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (chip_id == kChipId8821C) {
|
||||
#if defined(DEVOURER_HAVE_JAGUAR2_8821C)
|
||||
_logger->info("Creating RtlJaguar2Device C8821C (PID 0x{:04x}, chip-id "
|
||||
"0x{:02x})",
|
||||
pid, chip_id);
|
||||
return std::make_unique<RtlJaguar2Device>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger,
|
||||
jaguar2::ChipVariant::C8821C, cfg);
|
||||
#else
|
||||
_logger->error("RTL8821C (chip-id 0x09) detected but 8821C support not "
|
||||
"compiled in (DEVOURER_JAGUAR2_8821C=OFF)");
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (chip_id == 0x13 || chip_id == 0x17) {
|
||||
#if defined(DEVOURER_HAVE_JAGUAR3)
|
||||
/* Reject the variant whose support wasn't compiled in (0x13 = 8822C,
|
||||
* 0x17 = 8822E) rather than construct a device whose PHY-table /
|
||||
* calibration dispatchers were built out. */
|
||||
#if !defined(DEVOURER_HAVE_JAGUAR3_8822C)
|
||||
if (chip_id == 0x13) {
|
||||
_logger->error("RTL8822C (chip-id 0x13) support not compiled in "
|
||||
"(DEVOURER_JAGUAR3_8822C=OFF)");
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
#if !defined(DEVOURER_HAVE_JAGUAR3_8822E)
|
||||
if (chip_id == 0x17) {
|
||||
_logger->error("RTL8822E (chip-id 0x17) support not compiled in "
|
||||
"(DEVOURER_JAGUAR3_8822E=OFF)");
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
auto variant = chip_id == 0x17 ? jaguar3::ChipVariant::C8822E
|
||||
: jaguar3::ChipVariant::C8822C;
|
||||
_logger->info("Creating RtlJaguar3Device (PID 0x{:04x}, chip-id 0x{:02x})",
|
||||
pid, chip_id);
|
||||
return std::make_unique<RtlJaguar3Device>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger, variant,
|
||||
cfg);
|
||||
#else
|
||||
_logger->error("Jaguar3 chip (chip-id 0x{:02x}) detected but Jaguar3 "
|
||||
"support not compiled in",
|
||||
chip_id);
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(DEVOURER_HAVE_JAGUAR1)
|
||||
_logger->info("Creating RtlJaguarDevice (PID 0x{:04x}, chip-id 0x{:02x})", pid,
|
||||
chip_id);
|
||||
/* Pass ctx so RtlAdapter::_ctx is set: the Jaguar1 RX loop now drives an
|
||||
* async URB queue (bulk_read_async_loop) whose event pump needs the same
|
||||
* libusb context the handle was opened on (as Jaguar2/3 already do above). */
|
||||
return std::make_unique<RtlJaguarDevice>(
|
||||
RtlAdapter(dev_handle, _logger, ctx, usb_lock, cfg), _logger, cfg);
|
||||
#else
|
||||
_logger->error("Jaguar1 chip (PID 0x{:04x}, chip-id 0x{:02x}) detected but "
|
||||
"Jaguar1 support not compiled in",
|
||||
pid, chip_id);
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(DEVOURER_HAVE_PCIE)
|
||||
std::unique_ptr<IRadio> WiFiDriver::CreateRadioPcie(
|
||||
std::shared_ptr<devourer::PcieTransport> transport,
|
||||
const devourer::DeviceConfig &cfg) {
|
||||
if (!transport) {
|
||||
_logger->error("CreateRadioPcie: null transport");
|
||||
return nullptr;
|
||||
}
|
||||
/* Chip identity from SYS_CFG2 (0x00FC) over BAR2 MMIO — the same dispatch
|
||||
* signal the USB factory reads via a vendor control transfer. */
|
||||
const uint8_t chip_id =
|
||||
*reinterpret_cast<volatile uint8_t *>(transport->mmio() + 0x00FC);
|
||||
|
||||
if (chip_id == kChipId8821C) {
|
||||
#if defined(DEVOURER_HAVE_JAGUAR2_8821C)
|
||||
_logger->info("Creating RtlJaguar2Device C8821C over PCIe ({}; chip-id "
|
||||
"0x{:02x})",
|
||||
transport->bdf(), chip_id);
|
||||
return std::make_unique<RtlJaguar2Device>(
|
||||
RtlAdapter(std::move(transport), _logger, cfg), _logger,
|
||||
jaguar2::ChipVariant::C8821C, cfg);
|
||||
#else
|
||||
_logger->error("RTL8821C[E] (chip-id 0x09) detected but 8821C support not "
|
||||
"compiled in (DEVOURER_JAGUAR2_8821C=OFF)");
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
_logger->error("PCIe chip-id 0x{:02x} at {} is not supported over PCIe "
|
||||
"(only RTL8821C[E], chip-id 0x09, for now)",
|
||||
chip_id, transport->bdf());
|
||||
return nullptr;
|
||||
}
|
||||
#endif /* DEVOURER_HAVE_PCIE */
|
||||
@@ -0,0 +1,60 @@
|
||||
#ifndef WIFI_DRIVER_H
|
||||
#define WIFI_DRIVER_H
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "DeviceConfig.h"
|
||||
#include "IRadio.h"
|
||||
#include "logger.h"
|
||||
|
||||
struct libusb_device_handle;
|
||||
struct libusb_context;
|
||||
|
||||
namespace devourer {
|
||||
class UsbDeviceLock;
|
||||
class PcieTransport;
|
||||
}
|
||||
|
||||
class WiFiDriver {
|
||||
Logger_t _logger;
|
||||
|
||||
public:
|
||||
explicit WiFiDriver(Logger_t logger);
|
||||
|
||||
/* Constructs the right device for the chip behind `dev_handle`:
|
||||
* RtlJaguarDevice for Jaguar wave-1 (8812/8811/8821/8814AU), the later
|
||||
* Jaguar/Kestrel backends, or the dedicated RTL8733B backend. Returns the
|
||||
* common IRadio interface. See CreateRadio() for dispatch rules.
|
||||
*
|
||||
* `usb_lock` is the exclusive per-adapter lock. Pass the one returned by
|
||||
* devourer::claim_interface_then_reset (the recommended open path) so it is
|
||||
* held for the device lifetime and not re-acquired. When null (a caller that
|
||||
* opened/claimed the handle itself), CreateRadio acquires its own as a
|
||||
* best-effort second gate, and returns nullptr if the adapter is already in
|
||||
* use.
|
||||
*
|
||||
* `cfg` is the construction-time configuration (see DeviceConfig.h); the
|
||||
* default gives stock behaviour. Fixed for the device's lifetime. */
|
||||
std::unique_ptr<IRadio>
|
||||
CreateRadio(libusb_device_handle *dev_handle,
|
||||
libusb_context *ctx = nullptr,
|
||||
std::shared_ptr<devourer::UsbDeviceLock> usb_lock = nullptr,
|
||||
const devourer::DeviceConfig &cfg = {});
|
||||
|
||||
#if defined(DEVOURER_HAVE_PCIE)
|
||||
/* PCIe counterpart (DEVOURER_PCIE=ON, Linux/vfio only). The caller owns
|
||||
* vfio, mirroring the USB doctrine: open the transport first —
|
||||
* devourer::PcieTransport::Open("0000:01:00.0", logger) is the recommended
|
||||
* path (the device must be bound to vfio-pci, see tests/pcie_vfio_bind.sh) —
|
||||
* then hand it in here. Chip identity is read from SYS_CFG2 over MMIO;
|
||||
* currently only chip-id 0x09 (RTL8821C — the RTL8821CE) is accepted,
|
||||
* anything else logs and returns nullptr (same contract as an unsupported
|
||||
* chip on USB). No UsbDeviceLock: a vfio device fd is exclusive by
|
||||
* construction (a second open fails). */
|
||||
std::unique_ptr<IRadio>
|
||||
CreateRadioPcie(std::shared_ptr<devourer::PcieTransport> transport,
|
||||
const devourer::DeviceConfig &cfg = {});
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif /* WIFI_DRIVER_H */
|
||||
@@ -0,0 +1,270 @@
|
||||
/* Windowed RX receipts — app-layer delivery truth for a TX peer.
|
||||
*
|
||||
* The hardware ACK's horizon is chip-FIFO admission (SIFS timing: it can
|
||||
* never confirm host delivery), and per-frame CCX reports are rate-bounded
|
||||
* by the fw's ~1.3k reports/s emission ceiling. This is the tier above both:
|
||||
* the RECEIVER's application counts what it actually consumed and mails a
|
||||
* compact bitmap back on its existing feedback path; the transmitter merges
|
||||
* those receipts into a delivered-set that is true at the only layer that
|
||||
* matters. Same caller-side contract as UeRxAttribution: the demos feed
|
||||
* frames in from the Packet callback, the device RX loops are untouched, and
|
||||
* the library never assumes a payload convention — the caller supplies the
|
||||
* u32 frame index (the bench wires txdemo's QoS-Data payload counter).
|
||||
*
|
||||
* Wire format (versioned TLV, little-endian, one transmitter per TLV):
|
||||
* [0..2) magic "DR"
|
||||
* [2] version (1)
|
||||
* [3] flags (0)
|
||||
* [4..10) ta — the transmitter this receipt covers; the TX side absorbs
|
||||
* only receipts naming its own SA, which (with magic + version +
|
||||
* exact-length) keeps arbitrary payloads from parsing as receipts
|
||||
* [10..14) base — first frame index the bitmap covers
|
||||
* [14..16) nbits — window length in frames
|
||||
* [16..) bitmap, LSB-first: bit i set => frame base+i was received
|
||||
*
|
||||
* Receipts OVERLAP: every emission covers the last `window_bits` indices, so
|
||||
* each frame appears in many consecutive receipts and individual receipt
|
||||
* loss is harmless — the merge is idempotent. A frame index arriving BELOW
|
||||
* the current window (reordered by more than window_bits) is counted as
|
||||
* `late` and never receipted; size the window against the emission cadence
|
||||
* (2048 bits at 2.4k fps ≈ 0.85 s of slack, orders beyond USB reordering).
|
||||
*/
|
||||
#ifndef DEVOURER_CELL_RX_RECEIPT_H
|
||||
#define DEVOURER_CELL_RX_RECEIPT_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
namespace cell {
|
||||
|
||||
constexpr size_t kReceiptHeader = 16;
|
||||
constexpr uint8_t kReceiptVersion = 1;
|
||||
|
||||
constexpr size_t receipt_tlv_size(uint16_t nbits) {
|
||||
return kReceiptHeader + (static_cast<size_t>(nbits) + 7) / 8;
|
||||
}
|
||||
|
||||
/* Receiver half: a ring bitmap over the last `window_bits` frame indices.
|
||||
*
|
||||
* SIZING: the window must exceed the largest index jump the receiver's own
|
||||
* buffering can produce between two encodes, or a post-stall backlog drain
|
||||
* evicts frames before any receipt covers them (measured: a 150 ms consumer
|
||||
* stall behind a 104-buffer spsc-fat pool drained ~3k frames in one receipt
|
||||
* interval and a 2048-bit window leaked 2,846 delivered frames out of
|
||||
* coverage). Rule: window_bits > pool_bytes / min_frame_bytes + one encode
|
||||
* interval of arrivals. The 8192 default gives ~2.7x margin over that bench
|
||||
* worst case at ~1 KB of bitmap per receipt (~1.4 ms at 6M). */
|
||||
class ReceiptWindow {
|
||||
public:
|
||||
explicit ReceiptWindow(uint16_t window_bits = 8192)
|
||||
: _w(window_bits ? window_bits : 8192),
|
||||
_bits((_w + 63) / 64, 0) {}
|
||||
|
||||
/* Record a received frame index. Indices may repeat (duplicates are
|
||||
* idempotent) and skip forward arbitrarily; an index below the current
|
||||
* window is counted, not receipted. */
|
||||
void note(uint32_t idx) {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
if (!_any) {
|
||||
_any = true;
|
||||
_max = idx;
|
||||
set_bit(idx);
|
||||
return;
|
||||
}
|
||||
if (idx > _max) {
|
||||
/* Advance: every ring slot between the old and new max is a NEW index
|
||||
* whose bit must start clear. A jump >= _w wipes the whole ring. */
|
||||
const uint32_t advance = idx - _max;
|
||||
const uint32_t to_clear = advance < _w ? advance : _w;
|
||||
for (uint32_t k = 0; k < to_clear; ++k)
|
||||
clear_bit(_max + 1 + k + (advance - to_clear));
|
||||
_max = idx;
|
||||
set_bit(idx);
|
||||
return;
|
||||
}
|
||||
if (_max - idx >= _w) {
|
||||
++_late; /* below the window — reordered past the receipt horizon */
|
||||
return;
|
||||
}
|
||||
set_bit(idx);
|
||||
}
|
||||
|
||||
/* Encode the current window into `out` (>= receipt_tlv_size(window_bits)).
|
||||
* Returns the TLV length, or 0 if nothing has been noted yet. */
|
||||
size_t encode(const uint8_t ta[6], uint8_t *out, size_t out_len) const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
if (!_any)
|
||||
return 0;
|
||||
const uint32_t base = _max >= _w - 1 ? _max - (_w - 1) : 0;
|
||||
const uint16_t nbits = static_cast<uint16_t>(_max - base + 1);
|
||||
const size_t need = receipt_tlv_size(nbits);
|
||||
if (out_len < need)
|
||||
return 0;
|
||||
out[0] = 'D';
|
||||
out[1] = 'R';
|
||||
out[2] = kReceiptVersion;
|
||||
out[3] = 0;
|
||||
std::memcpy(out + 4, ta, 6);
|
||||
put32(out + 10, base);
|
||||
put16(out + 14, nbits);
|
||||
std::memset(out + kReceiptHeader, 0, need - kReceiptHeader);
|
||||
for (uint32_t i = 0; i < nbits; ++i)
|
||||
if (get_bit(base + i))
|
||||
out[kReceiptHeader + i / 8] |= static_cast<uint8_t>(1u << (i % 8));
|
||||
return need;
|
||||
}
|
||||
|
||||
uint64_t late() const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
return _late;
|
||||
}
|
||||
|
||||
private:
|
||||
/* Ring addressing: index -> bit slot idx % _w, and BOTH the word and the
|
||||
* bit offset derive from the slot — deriving the bit from idx % 64 is only
|
||||
* equivalent when _w is a multiple of 64, and the window size is caller-
|
||||
* chosen. Valid because the window invariant keeps every live index within
|
||||
* [_max - _w + 1, _max]. */
|
||||
void set_bit(uint32_t idx) {
|
||||
const uint32_t s = idx % _w;
|
||||
_bits[s / 64] |= 1ull << (s % 64);
|
||||
}
|
||||
void clear_bit(uint32_t idx) {
|
||||
const uint32_t s = idx % _w;
|
||||
_bits[s / 64] &= ~(1ull << (s % 64));
|
||||
}
|
||||
bool get_bit(uint32_t idx) const {
|
||||
const uint32_t s = idx % _w;
|
||||
return (_bits[s / 64] >> (s % 64)) & 1u;
|
||||
}
|
||||
static void put32(uint8_t *p, uint32_t v) {
|
||||
p[0] = v & 0xff;
|
||||
p[1] = (v >> 8) & 0xff;
|
||||
p[2] = (v >> 16) & 0xff;
|
||||
p[3] = (v >> 24) & 0xff;
|
||||
}
|
||||
static void put16(uint8_t *p, uint16_t v) {
|
||||
p[0] = v & 0xff;
|
||||
p[1] = (v >> 8) & 0xff;
|
||||
}
|
||||
|
||||
mutable std::mutex _mu;
|
||||
uint32_t _w;
|
||||
std::vector<uint64_t> _bits;
|
||||
bool _any = false;
|
||||
uint32_t _max = 0;
|
||||
uint64_t _late = 0;
|
||||
};
|
||||
|
||||
/* One decoded receipt, viewing the caller's buffer (no copy). */
|
||||
struct ReceiptView {
|
||||
const uint8_t *ta = nullptr;
|
||||
uint32_t base = 0;
|
||||
uint16_t nbits = 0;
|
||||
const uint8_t *bitmap = nullptr;
|
||||
bool bit(uint32_t i) const { return (bitmap[i / 8] >> (i % 8)) & 1u; }
|
||||
};
|
||||
|
||||
/* Strict-prefix parse: magic + version + a bitmap fully inside the buffer.
|
||||
* Trailing bytes are accepted — a received MPDU body carries the 4-byte FCS
|
||||
* after the TLV (parsers deliver it; an ACK frame logs len 14 = 10 + FCS),
|
||||
* and the absorb side additionally requires the 6-byte TA match, which keeps
|
||||
* arbitrary payloads from parsing as receipts. */
|
||||
inline bool receipt_decode(const uint8_t *p, size_t len, ReceiptView &out) {
|
||||
if (!p || len < kReceiptHeader || p[0] != 'D' || p[1] != 'R' ||
|
||||
p[2] != kReceiptVersion)
|
||||
return false;
|
||||
const uint16_t nbits =
|
||||
static_cast<uint16_t>(p[14] | (static_cast<uint16_t>(p[15]) << 8));
|
||||
if (nbits == 0 || len < receipt_tlv_size(nbits))
|
||||
return false;
|
||||
out.ta = p + 4;
|
||||
out.base = static_cast<uint32_t>(p[10]) | (static_cast<uint32_t>(p[11]) << 8) |
|
||||
(static_cast<uint32_t>(p[12]) << 16) |
|
||||
(static_cast<uint32_t>(p[13]) << 24);
|
||||
out.nbits = nbits;
|
||||
out.bitmap = p + kReceiptHeader;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Transmitter half: merge receipts into the delivered-set.
|
||||
*
|
||||
* `max_index` bounds the bitmap: receipts arrive OVER THE AIR, so `base` is
|
||||
* attacker-influencable and an unbounded resize would let one crafted TLV
|
||||
* (base near 2^32) allocate half a gigabyte. The default cap (2^26 frames =
|
||||
* 8 MB of bitmap, ~7.7 h at 2.4 k fps) is far above any bench run; a peer
|
||||
* whose real index space outgrows it should shard by session. */
|
||||
class ReceiptLedger {
|
||||
public:
|
||||
explicit ReceiptLedger(uint64_t max_index = 1ull << 26)
|
||||
: _max_index(max_index) {}
|
||||
|
||||
/* Absorb a receipt covering our TA. Returns the number of NEWLY-learned
|
||||
* delivered indices (0 for a pure re-receipt), or -1 if the TLV does not
|
||||
* parse, names a different transmitter, or claims indices beyond the
|
||||
* ledger's cap. */
|
||||
long absorb(const uint8_t *tlv, size_t len, const uint8_t own_ta[6]) {
|
||||
ReceiptView v;
|
||||
if (!receipt_decode(tlv, len, v) || std::memcmp(v.ta, own_ta, 6) != 0)
|
||||
return -1;
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
const uint64_t top = static_cast<uint64_t>(v.base) + v.nbits;
|
||||
if (top > _max_index)
|
||||
return -1;
|
||||
if (top > _bits.size() * 64)
|
||||
_bits.resize((top + 63) / 64, 0);
|
||||
long fresh = 0;
|
||||
for (uint32_t i = 0; i < v.nbits; ++i) {
|
||||
if (!v.bit(i))
|
||||
continue;
|
||||
const uint64_t idx = static_cast<uint64_t>(v.base) + i;
|
||||
uint64_t &word = _bits[idx / 64];
|
||||
const uint64_t m = 1ull << (idx % 64);
|
||||
if (!(word & m)) {
|
||||
word |= m;
|
||||
++fresh;
|
||||
++_total;
|
||||
}
|
||||
}
|
||||
if (top > _highest_covered)
|
||||
_highest_covered = top; /* exclusive: indices below this were covered */
|
||||
++_receipts;
|
||||
return fresh;
|
||||
}
|
||||
|
||||
bool delivered(uint64_t idx) const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
return idx / 64 < _bits.size() && ((_bits[idx / 64] >> (idx % 64)) & 1u);
|
||||
}
|
||||
uint64_t delivered_total() const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
return _total;
|
||||
}
|
||||
/* Exclusive upper bound of receipt coverage: every index below it has been
|
||||
* inside at least one absorbed receipt's window. */
|
||||
uint64_t highest_covered() const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
return _highest_covered;
|
||||
}
|
||||
uint64_t receipts() const {
|
||||
std::lock_guard<std::mutex> lk(_mu);
|
||||
return _receipts;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex _mu;
|
||||
uint64_t _max_index;
|
||||
std::vector<uint64_t> _bits;
|
||||
uint64_t _total = 0;
|
||||
uint64_t _highest_covered = 0;
|
||||
uint64_t _receipts = 0;
|
||||
};
|
||||
|
||||
} /* namespace cell */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CELL_RX_RECEIPT_H */
|
||||
@@ -0,0 +1,191 @@
|
||||
/* Per-UE RX attribution — the M0 seed of the scheduled-MAC UeRegistry (5G-NR
|
||||
* RAN epic, src/cell/ = the per-cell DU library).
|
||||
*
|
||||
* GetRxQuality() is deliberately device-wide: one draining accumulator fed by
|
||||
* every decoded frame, regardless of transmitter. A cell scheduler adapting
|
||||
* per-UE rate/power needs the same window statistics ATTRIBUTED to each
|
||||
* transmitter (the 802.11 addr2 / TA). All the primitives already exist per
|
||||
* frame — RSSI/SNR/EVM in rx_pkt_attrib, the raw MPDU (and thus the TA) in
|
||||
* Packet.Data — so this stays pure caller-side logic: the demos/probes feed
|
||||
* add() from the Packet callback, the device RX loops are untouched.
|
||||
*
|
||||
* Same conventions as RxQualityAccumulator (src/RxQuality.h): raw path-A
|
||||
* units in, drain-and-reset snapshot() out (delta semantics), rssi_raw <= 0
|
||||
* is not a sample, SNR/EVM folded only when present, passive noise floor =
|
||||
* (rssi_raw - 110) - snr_raw/2 per OFDM frame. */
|
||||
#ifndef DEVOURER_CELL_UE_RX_ATTRIBUTION_H
|
||||
#define DEVOURER_CELL_UE_RX_ATTRIBUTION_H
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace devourer {
|
||||
namespace cell {
|
||||
|
||||
/* Extract the transmitter address (addr2) from an 802.11 MPDU. Every frame
|
||||
* type carries addr2 at bytes [10..16) EXCEPT the two shortest control
|
||||
* subtypes — CTS (fc0 0xc4) and ACK (0xd4) — which end at addr1. Returns
|
||||
* false for those, for truncated buffers, and for a zero TA (never a legal
|
||||
* transmitter; a parser artifact). */
|
||||
inline bool extract_ta(const uint8_t *mpdu, size_t len, uint8_t out[6]) {
|
||||
if (!mpdu || len < 16)
|
||||
return false;
|
||||
const uint8_t fc0 = mpdu[0];
|
||||
if ((fc0 & 0x0c) == 0x04) { /* control frame */
|
||||
const uint8_t subtype = fc0 & 0xf0;
|
||||
if (subtype == 0xc0 /* CTS */ || subtype == 0xd0 /* ACK */)
|
||||
return false;
|
||||
}
|
||||
std::memcpy(out, mpdu + 10, 6);
|
||||
static const uint8_t zero[6] = {0, 0, 0, 0, 0, 0};
|
||||
return std::memcmp(out, zero, 6) != 0;
|
||||
}
|
||||
|
||||
/* One UE's drained window — RxQualitySnapshot's frame-driven half, keyed and
|
||||
* converted (dBm / dB, so a scheduler doesn't repeat the raw conversions). */
|
||||
struct UeRxWindow {
|
||||
std::array<uint8_t, 6> ta{};
|
||||
uint32_t frames = 0;
|
||||
int rssi_mean_dbm = 0; /* window mean of path-A PWDB (raw - 110) */
|
||||
int rssi_max_dbm = 0;
|
||||
double snr_mean_db = 0.0;
|
||||
double snr_min_db = 0.0;
|
||||
double evm_mean_db = 0.0; /* 0 when evm_valid is false */
|
||||
bool evm_valid = false;
|
||||
double noise_floor_dbm = 0.0; /* passive: mean rssi_dbm - snr_db */
|
||||
bool nf_valid = false;
|
||||
uint32_t last_tsfl = 0; /* hardware RX TSF of the newest frame (staleness) */
|
||||
};
|
||||
|
||||
/* A drained attribution window: per-UE stats plus the frames the table had to
|
||||
* drop because it was full (a nonzero count means the cap is too small for
|
||||
* the environment, or a foreign-traffic filter belongs upstream). */
|
||||
struct UeRxSnapshot {
|
||||
std::vector<UeRxWindow> ues;
|
||||
uint32_t evicted_frames = 0;
|
||||
};
|
||||
|
||||
/* Thread-safe per-TA windowed accumulator. add() from the Packet callback for
|
||||
* every decoded frame; snapshot() drains the whole table (delta semantics —
|
||||
* UEs reappear with their next frame). Bounded: at most `cap` distinct TAs
|
||||
* per window; frames from further TAs are counted in evicted_frames, never
|
||||
* silently lost. */
|
||||
class UeRxAttribution {
|
||||
public:
|
||||
explicit UeRxAttribution(size_t cap = 64) : cap_(cap) {}
|
||||
|
||||
/* Raw path-A values straight off rx_pkt_attrib, plus the frame's TA and
|
||||
* hardware RX timestamp. Mirrors RxQualityAccumulator::add. */
|
||||
void add(const uint8_t ta[6], int rssi_raw, int snr_raw, int evm_raw,
|
||||
uint32_t tsfl) {
|
||||
if (rssi_raw <= 0)
|
||||
return;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
Entry *e = find_or_insert(ta);
|
||||
if (!e) {
|
||||
++evicted_;
|
||||
return;
|
||||
}
|
||||
++e->n;
|
||||
e->rssi_sum += rssi_raw;
|
||||
if (rssi_raw > e->rssi_max)
|
||||
e->rssi_max = rssi_raw;
|
||||
e->snr_sum += snr_raw;
|
||||
if (snr_raw < e->snr_min)
|
||||
e->snr_min = snr_raw;
|
||||
if (evm_raw != 0) {
|
||||
e->evm_sum += evm_raw;
|
||||
++e->evm_n;
|
||||
}
|
||||
if (snr_raw != 0) {
|
||||
e->nf_sum += (rssi_raw - 110) - snr_raw / 2.0;
|
||||
++e->nf_n;
|
||||
}
|
||||
e->last_tsfl = tsfl;
|
||||
}
|
||||
|
||||
/* Convenience: extract the TA from the MPDU and add. Returns false when the
|
||||
* frame carries no TA (CTS/ACK/truncated) — not a quality sample. */
|
||||
bool add_mpdu(const uint8_t *mpdu, size_t len, int rssi_raw, int snr_raw,
|
||||
int evm_raw, uint32_t tsfl) {
|
||||
uint8_t ta[6];
|
||||
if (!extract_ta(mpdu, len, ta))
|
||||
return false;
|
||||
add(ta, rssi_raw, snr_raw, evm_raw, tsfl);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Drain the window: one UeRxWindow per TA seen, then reset the table. */
|
||||
UeRxSnapshot snapshot() {
|
||||
UeRxSnapshot s;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
s.ues.reserve(entries_.size());
|
||||
for (const Entry &e : entries_) {
|
||||
UeRxWindow w;
|
||||
w.ta = e.ta;
|
||||
w.frames = e.n;
|
||||
if (e.n) {
|
||||
w.rssi_mean_dbm = static_cast<int>(e.rssi_sum / static_cast<int64_t>(e.n)) - 110;
|
||||
w.rssi_max_dbm = e.rssi_max - 110;
|
||||
w.snr_mean_db = (e.snr_sum / static_cast<double>(e.n)) / 2.0;
|
||||
w.snr_min_db = e.snr_min / 2.0;
|
||||
}
|
||||
if (e.evm_n) {
|
||||
w.evm_mean_db = (e.evm_sum / static_cast<double>(e.evm_n)) / 2.0;
|
||||
w.evm_valid = true;
|
||||
}
|
||||
if (e.nf_n) {
|
||||
w.noise_floor_dbm = e.nf_sum / static_cast<double>(e.nf_n);
|
||||
w.nf_valid = true;
|
||||
}
|
||||
w.last_tsfl = e.last_tsfl;
|
||||
s.ues.push_back(w);
|
||||
}
|
||||
s.evicted_frames = evicted_;
|
||||
entries_.clear();
|
||||
evicted_ = 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
std::array<uint8_t, 6> ta{};
|
||||
uint32_t n = 0;
|
||||
int64_t rssi_sum = 0;
|
||||
int rssi_max = -128;
|
||||
int64_t snr_sum = 0;
|
||||
int snr_min = 127;
|
||||
int64_t evm_sum = 0;
|
||||
uint32_t evm_n = 0;
|
||||
double nf_sum = 0.0;
|
||||
uint32_t nf_n = 0;
|
||||
uint32_t last_tsfl = 0;
|
||||
};
|
||||
|
||||
/* Linear scan — the table is small (cap defaults to 64) and drains every
|
||||
* window, so a map's overhead buys nothing. Caller holds mu_. */
|
||||
Entry *find_or_insert(const uint8_t ta[6]) {
|
||||
for (Entry &e : entries_)
|
||||
if (std::memcmp(e.ta.data(), ta, 6) == 0)
|
||||
return &e;
|
||||
if (entries_.size() >= cap_)
|
||||
return nullptr;
|
||||
Entry e;
|
||||
std::memcpy(e.ta.data(), ta, 6);
|
||||
entries_.push_back(e);
|
||||
return &entries_.back();
|
||||
}
|
||||
|
||||
std::mutex mu_;
|
||||
size_t cap_;
|
||||
std::vector<Entry> entries_;
|
||||
uint32_t evicted_ = 0;
|
||||
};
|
||||
|
||||
} // namespace cell
|
||||
} // namespace devourer
|
||||
|
||||
#endif /* DEVOURER_CELL_UE_RX_ATTRIBUTION_H */
|
||||
@@ -0,0 +1,208 @@
|
||||
/* Active-link evidence — the primary receiver's view of the LIVE video
|
||||
* channel, the authoritative half of a migration decision.
|
||||
*
|
||||
* The asymmetry the whole stack is built around: on the active channel the
|
||||
* scout's energy reading is confounded by the wanted video's own airtime, so
|
||||
* it is NOT the impairment signal — the primary receiver's DELIVERY is. This
|
||||
* models that delivery as a rolling window of `ActiveLinkWindow` records
|
||||
* (fed from the primary's rx.txhit / rx.quality / rx.energy JSONL) and
|
||||
* classifies each window as impaired-or-not with a fault domain, so a policy
|
||||
* can require PERSISTENT channel-attributable impairment before it even looks
|
||||
* at candidates.
|
||||
*
|
||||
* Fault domains matter because migration cannot fix them: a weak signal is a
|
||||
* range problem (add power / close distance, not change channel), near-field
|
||||
* saturation is an overload problem (back power off), and a broad multi-band
|
||||
* degradation is not this channel's fault. Only "decodes are being lost to
|
||||
* something local to this channel" is a migration trigger.
|
||||
*
|
||||
* Pure: no clocks (caller passes now), no I/O. Selftested via ChannelScore. */
|
||||
#ifndef DEVOURER_CHANMIG_ACTIVE_LINK_H
|
||||
#define DEVOURER_CHANMIG_ACTIVE_LINK_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "LinkHealth.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
/* 12-bit 802.11 sequence-number loss estimator (wrap-aware). Fed the seq of
|
||||
* each delivered canonical-SA frame; a gap up to half the space is counted as
|
||||
* that many expected-but-missing frames, a larger jump is a TX restart (one
|
||||
* expected). delivered/expected over a window give the loss ratio. */
|
||||
class SeqLossEstimator {
|
||||
public:
|
||||
void observe(uint16_t seq) {
|
||||
++delivered_;
|
||||
if (have_prev_) {
|
||||
const uint16_t gap = static_cast<uint16_t>((seq - prev_) & 0xFFF);
|
||||
expected_ += (gap >= 1 && gap < 2048) ? gap : 1;
|
||||
} else {
|
||||
expected_ += 1;
|
||||
have_prev_ = true;
|
||||
}
|
||||
prev_ = seq;
|
||||
}
|
||||
uint32_t delivered() const { return delivered_; }
|
||||
uint32_t expected() const { return expected_ < delivered_ ? delivered_
|
||||
: expected_; }
|
||||
double loss_ratio() const {
|
||||
const uint32_t e = expected();
|
||||
return e ? 1.0 - static_cast<double>(delivered_) / e : 0.0;
|
||||
}
|
||||
void reset() {
|
||||
delivered_ = 0;
|
||||
expected_ = 0;
|
||||
have_prev_ = false;
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t delivered_ = 0, expected_ = 0;
|
||||
uint16_t prev_ = 0;
|
||||
bool have_prev_ = false;
|
||||
};
|
||||
|
||||
/* One primary-telemetry window on the active channel. Optional fields carry a
|
||||
* validity flag; the impairment test uses whatever delivery evidence is
|
||||
* present, preferring the strongest (FEC margin > seq loss > crc/icv rate >
|
||||
* frame collapse). */
|
||||
struct ActiveLinkWindow {
|
||||
int64_t t_ms = 0;
|
||||
|
||||
bool have_delivery = false;
|
||||
uint32_t delivered = 0; /* frames this window */
|
||||
uint32_t expected = 0; /* seq-gap estimate; 0 = unknown */
|
||||
|
||||
bool have_fec = false;
|
||||
double fec_margin = 0.0; /* external feeder (wfb-ng); <=0 = at/over the edge */
|
||||
|
||||
bool have_crc = false;
|
||||
uint32_t crc_err = 0, icv_err = 0; /* DEVOURER_RX_KEEP_CORRUPTED */
|
||||
|
||||
bool have_quality = false;
|
||||
LinkVerdict verdict = LinkVerdict::NoSignal;
|
||||
int rssi_max_dbm = 0;
|
||||
double snr_mean_db = 0.0, evm_mean_db = 0.0;
|
||||
|
||||
bool telemetry_ok = true; /* false when the primary feed went stale/missing */
|
||||
};
|
||||
|
||||
/* Impairment verdict for one window: whether it counts as impaired, and if
|
||||
* not-channel-attributable, why (so a policy can say "don't migrate, it's
|
||||
* weak-signal"). */
|
||||
enum class Impair {
|
||||
Healthy, /* delivering fine */
|
||||
Channel, /* losing decodes to something on THIS channel — migratable */
|
||||
WeakSignal, /* range/sensitivity limit — migration won't help */
|
||||
Saturation, /* near-field overload — back power off */
|
||||
TelemetryDown, /* no trustworthy primary evidence */
|
||||
};
|
||||
|
||||
inline const char *verdict_label(LinkVerdict v) {
|
||||
switch (v) {
|
||||
case LinkVerdict::NoSignal: return "NO_SIGNAL";
|
||||
case LinkVerdict::Saturated: return "SATURATED";
|
||||
case LinkVerdict::Interference: return "INTERFERENCE";
|
||||
case LinkVerdict::Weak: return "WEAK";
|
||||
case LinkVerdict::Marginal: return "MARGINAL";
|
||||
case LinkVerdict::Healthy: return "HEALTHY";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
struct ActivePolicy {
|
||||
double loss_impair = 0.05; /* >5% seq loss = impaired */
|
||||
double crc_impair = 0.10; /* >10% crc/icv of delivered = impaired */
|
||||
double fec_margin_impair = 0.0; /* fec_margin <= this = impaired */
|
||||
uint32_t min_frames = 20; /* fewer = window not judgeable on delivery */
|
||||
};
|
||||
|
||||
/* Classify one window. LinkHealth's verdict is reused as the fault-domain
|
||||
* discriminator (its EVM/RSSI split already separates weak from saturated
|
||||
* from interfered — we do not re-derive it). */
|
||||
inline Impair classify_window(const ActiveLinkWindow &w,
|
||||
const ActivePolicy &p) {
|
||||
if (!w.telemetry_ok)
|
||||
return Impair::TelemetryDown;
|
||||
|
||||
/* Fault domain first: a weak or saturated link is not a channel problem no
|
||||
* matter what delivery does. */
|
||||
if (w.have_quality) {
|
||||
if (w.verdict == LinkVerdict::Weak)
|
||||
return Impair::WeakSignal;
|
||||
if (w.verdict == LinkVerdict::Saturated)
|
||||
return Impair::Saturation;
|
||||
if (w.verdict == LinkVerdict::NoSignal && w.delivered == 0)
|
||||
return Impair::WeakSignal; /* nothing at all: treat as range, not channel */
|
||||
}
|
||||
|
||||
bool impaired = false;
|
||||
if (w.have_fec)
|
||||
impaired = impaired || w.fec_margin <= p.fec_margin_impair;
|
||||
if (w.have_delivery && w.expected >= p.min_frames) {
|
||||
const double loss =
|
||||
w.expected ? 1.0 - static_cast<double>(w.delivered) / w.expected : 0.0;
|
||||
impaired = impaired || loss > p.loss_impair;
|
||||
}
|
||||
if (w.have_crc && w.delivered >= p.min_frames) {
|
||||
const double bad = static_cast<double>(w.crc_err + w.icv_err) /
|
||||
(w.delivered + w.crc_err + w.icv_err);
|
||||
impaired = impaired || bad > p.crc_impair;
|
||||
}
|
||||
/* A window with quality evidence but INTERFERENCE verdict and no delivery
|
||||
* signal still counts as channel-impaired (raised floor, high FA). */
|
||||
if (!impaired && w.have_quality && w.verdict == LinkVerdict::Interference &&
|
||||
!w.have_delivery && !w.have_fec && !w.have_crc)
|
||||
impaired = true;
|
||||
|
||||
return impaired ? Impair::Channel : Impair::Healthy;
|
||||
}
|
||||
|
||||
/* Rolling window of active-link records + the derived persistence signals a
|
||||
* decision needs: consecutive channel-impaired windows, and whether the
|
||||
* newest window's fault domain is a non-channel one (which forces a hold). */
|
||||
class ActiveLinkTrack {
|
||||
public:
|
||||
explicit ActiveLinkTrack(ActivePolicy p = {}, size_t cap = 64)
|
||||
: policy_(p), cap_(cap) {}
|
||||
|
||||
void add(const ActiveLinkWindow &w) {
|
||||
const Impair im = classify_window(w, policy_);
|
||||
if (im == Impair::Channel)
|
||||
++consec_channel_;
|
||||
else
|
||||
consec_channel_ = 0;
|
||||
last_ = im;
|
||||
last_t_ms_ = w.t_ms;
|
||||
have_last_ = true;
|
||||
if (win_.size() >= cap_)
|
||||
win_.erase(win_.begin());
|
||||
win_.push_back(w);
|
||||
}
|
||||
|
||||
int consecutive_channel_impaired() const { return consec_channel_; }
|
||||
Impair last_domain() const { return last_; }
|
||||
bool have() const { return have_last_; }
|
||||
int64_t last_t_ms() const { return last_t_ms_; }
|
||||
|
||||
/* Newest window's verdict, for the decision's active_verdict field. */
|
||||
LinkVerdict last_verdict() const {
|
||||
return win_.empty() ? LinkVerdict::NoSignal : win_.back().verdict;
|
||||
}
|
||||
|
||||
private:
|
||||
ActivePolicy policy_;
|
||||
size_t cap_;
|
||||
std::vector<ActiveLinkWindow> win_;
|
||||
int consec_channel_ = 0;
|
||||
Impair last_ = Impair::TelemetryDown;
|
||||
int64_t last_t_ms_ = 0;
|
||||
bool have_last_ = false;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_ACTIVE_LINK_H */
|
||||
@@ -0,0 +1,49 @@
|
||||
# src/chanmig/ — adaptive channel migration
|
||||
|
||||
Deep facts for this subtree, loaded alongside the root CLAUDE.md. Slow,
|
||||
evidence-driven whole-link channel moves — the deliberate complement to
|
||||
per-slot FHSS (`src/hopset/`). Namespace `devourer::chanmig`, header-mostly,
|
||||
each piece ctest-covered and pure: the library reads no env, the demos map it.
|
||||
Docs: `docs/adaptive-channel-migration.md`,
|
||||
`docs/channel-migration-protocol.md`, `docs/channel-migration-validation.md`.
|
||||
|
||||
## Five composable layers
|
||||
|
||||
- **Scout** (`chanscout`, `ScanPlan.h` / `SurveyRecord.h`): a second adapter
|
||||
passively surveys a candidate plan (`DEVOURER_SCOUT_PLAN`) while the primary
|
||||
RX stays on the video channel, emitting versioned `survey.dwell` records
|
||||
with a counter-hygiene discard barrier — the FA/CCA counters are
|
||||
delta-on-read. Measures only; retunes nothing but itself. Grid-legality
|
||||
validation, **no regulatory DB** — the caller owns compliance.
|
||||
- **Scoring** (`ChannelScore`, `DEVOURER_SCOUT_ADVISE`): a pure two-leg
|
||||
recommendation engine. The primary receiver's *delivery* is authoritative on
|
||||
the active channel (scout energy there is confounded by the wanted video);
|
||||
the scout's occupancy is authoritative on candidates. Emits explainable
|
||||
`channel.recommend` / `channel.hold`.
|
||||
- **Protocol** (`examples/chanmig --role ground|drone`): an authenticated
|
||||
ground-proposes / drone-commits migration — SipHash-MAC'd wire codec
|
||||
(`MigWire.h`), pure `MigProposer` / `MigResponder` state machines, random
|
||||
per-boot epochs. The drone arms activation only after the ground echoes its
|
||||
nonce, and the ground follows the drone's authoritative STATUS; every
|
||||
failure-matrix row converges without split-brain. Control frames are their
|
||||
own canonical-SA 802.11 frames — video PSDUs are never touched.
|
||||
- **Automation** (`MigGate`, `DEVOURER_MIG_MODE=off|advisory|manual|automatic`,
|
||||
default `advisory`): a pure, deterministic gate hedged with cooldown /
|
||||
residency / per-channel backoff / move-cap / probation, plus an operator kill
|
||||
switch.
|
||||
- **Drone-side validation**: legality and caps checks are the free product
|
||||
default; the pre-commit probe (`DEVOURER_MIG_PROBE`) is opt-in research with
|
||||
a real outage cost. Probation belongs to the gate.
|
||||
|
||||
## Validation
|
||||
|
||||
Headless: `chanmig_wire_kat`, `chanmig_proto_matrix` (a 14-row failure matrix +
|
||||
a drop-every-message sweep), `chan_score_policy`, `chanmig_gate_policy`,
|
||||
`chanmig_clock_math`.
|
||||
|
||||
On-air: `tests/chanmig_endurance.sh`, `tests/chanscout_stress.sh`,
|
||||
`tests/chanmig_soak.sh`.
|
||||
|
||||
**Near-field bench note**: two adapters ~30 cm apart saturate the RX front end
|
||||
at full power (`link.health` SATURATED), so migration tests reduce TX power
|
||||
(`DEVOURER_TX_PWR=12`). See `docs/bench-testing-near-field.md`.
|
||||
@@ -0,0 +1,406 @@
|
||||
/* ChannelDef — the channel identity the adaptive-channel-migration stack
|
||||
* (scout survey → scoring → migration protocol) agrees on.
|
||||
*
|
||||
* Identity is the exact tuple SetMonitorChannel consumes — (band, primary,
|
||||
* width, offset) — because that is what both endpoints must ultimately tune;
|
||||
* the center frequency is derived, never stored. Validation here is GRID
|
||||
* legality only (a 40 MHz pair must be a real pair, an 80 MHz primary must
|
||||
* sit inside a real quad): there is no regulatory database anywhere in
|
||||
* devourer — the caller owns compliance, and the no_ir/dfs flags are
|
||||
* caller-provided attributes carried through so policy can honor them.
|
||||
*
|
||||
* Offset semantics match SelectedChannel::ChannelOffset:
|
||||
* 40 MHz: 1 = primary is the lower half (secondary above), 2 = upper.
|
||||
* 80 MHz: 1..4 = primary position lowest..highest within the quad
|
||||
* (the HALs derive the block center as primary +6/+2/-2/-6).
|
||||
* On the 5 GHz grid both are fully determined by the primary, so the parser
|
||||
* derives them and an explicit contradicting suffix is an error; a 2.4 GHz
|
||||
* 40 MHz pair is genuinely ambiguous (ch 6 pairs either way) and needs the
|
||||
* suffix. */
|
||||
#ifndef DEVOURER_CHANMIG_CHANNEL_DEF_H
|
||||
#define DEVOURER_CHANMIG_CHANNEL_DEF_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "ChannelFreq.h"
|
||||
#include "SelectedChannel.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
struct ChannelDef {
|
||||
uint8_t band = 0; /* 2 = 2.4 GHz, 5 = 5 GHz */
|
||||
uint8_t primary = 0; /* primary 20 MHz channel number */
|
||||
ChannelWidth_t width = CHANNEL_WIDTH_20;
|
||||
uint8_t offset = 0; /* SelectedChannel::ChannelOffset semantics (above) */
|
||||
/* Caller-provided attributes (not identity): */
|
||||
bool no_ir = false; /* receive-only — never a migration target */
|
||||
bool dfs = false; /* informational */
|
||||
bool backup = false; /* preferred backup — higher scout revisit cadence */
|
||||
|
||||
/* Identity key over the RF tuple only (flags are attributes). */
|
||||
uint32_t key() const {
|
||||
return (uint32_t(band) << 24) | (uint32_t(primary) << 16) |
|
||||
(uint32_t(width) << 8) | offset;
|
||||
}
|
||||
bool same_rf(const ChannelDef &o) const { return key() == o.key(); }
|
||||
|
||||
/* Occupied width in half-MHz units (5 MHz narrowband needs the half). */
|
||||
int span_halfmhz() const {
|
||||
switch (width) {
|
||||
case CHANNEL_WIDTH_5: return 10;
|
||||
case CHANNEL_WIDTH_10: return 20;
|
||||
case CHANNEL_WIDTH_40: return 80;
|
||||
case CHANNEL_WIDTH_80: return 160;
|
||||
default: return 40; /* 20 MHz */
|
||||
}
|
||||
}
|
||||
|
||||
/* Center of the occupied block, half-MHz units (MHz * 2). */
|
||||
int center_halfmhz() const {
|
||||
const int p = 2 * static_cast<int>(chan_to_freq(primary));
|
||||
if (width == CHANNEL_WIDTH_40)
|
||||
return p + (offset == 1 ? 20 : -20);
|
||||
if (width == CHANNEL_WIDTH_80) {
|
||||
/* offset = primary position 1..4 → center at +6/+2/-2/-6 channels. */
|
||||
static const int off_ch[4] = {6, 2, -2, -6};
|
||||
const int i = (offset >= 1 && offset <= 4) ? offset - 1 : 0;
|
||||
return p + 2 * 5 * off_ch[i];
|
||||
}
|
||||
return p; /* 20 / 5 / 10 MHz: primary is the center */
|
||||
}
|
||||
uint16_t center_mhz() const {
|
||||
return static_cast<uint16_t>(center_halfmhz() / 2);
|
||||
}
|
||||
|
||||
SelectedChannel to_selected() const {
|
||||
return SelectedChannel{primary, offset, width, 0};
|
||||
}
|
||||
|
||||
/* Canonical text: "<band>:<primary>/<width>[u|l]" — "5:104/40l", "5:36/80",
|
||||
* "2:6/40u", "5:149/20". The 40 MHz suffix is always emitted (u = secondary
|
||||
* above / primary lower, l = secondary below); 80 MHz needs none (position
|
||||
* derives from the primary). Buffer must hold >= 16 bytes. */
|
||||
void format(char *out, size_t n) const {
|
||||
static const char *w[] = {"20", "40", "80", "160", "80+80", "5", "10"};
|
||||
const char *ws = (width < CHANNEL_WIDTH_MAX) ? w[width] : "?";
|
||||
const char *suf = "";
|
||||
if (width == CHANNEL_WIDTH_40)
|
||||
suf = (offset == 1) ? "u" : "l";
|
||||
std::snprintf(out, n, "%u:%u/%s%s", band, primary, ws, suf);
|
||||
}
|
||||
std::string str() const {
|
||||
char b[20];
|
||||
format(b, sizeof(b));
|
||||
return b;
|
||||
}
|
||||
};
|
||||
|
||||
enum class DefError {
|
||||
Ok,
|
||||
BadBand, /* band not 2 or 5 */
|
||||
BadPrimary, /* primary outside the band's channel range */
|
||||
BadWidth, /* width unsupported as a migration candidate (160/80+80) */
|
||||
BadOffset, /* offset contradicts the grid-derived one, or out of range */
|
||||
OffGrid40, /* no legal 40 MHz pair contains this primary */
|
||||
OffGrid80, /* no legal 80 MHz quad contains this primary */
|
||||
AmbiguousOffset, /* 2.4 GHz 40 MHz with no explicit u/l */
|
||||
};
|
||||
|
||||
inline const char *def_error_name(DefError e) {
|
||||
switch (e) {
|
||||
case DefError::Ok: return "ok";
|
||||
case DefError::BadBand: return "bad_band";
|
||||
case DefError::BadPrimary: return "bad_primary";
|
||||
case DefError::BadWidth: return "bad_width";
|
||||
case DefError::BadOffset: return "bad_offset";
|
||||
case DefError::OffGrid40: return "off_grid_40";
|
||||
case DefError::OffGrid80: return "off_grid_80";
|
||||
case DefError::AmbiguousOffset: return "ambiguous_offset";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Validate grid legality and derive a missing offset where the grid fully
|
||||
* determines it (5 GHz 40/80). Mutates only the offset field. */
|
||||
inline DefError normalize(ChannelDef &d) {
|
||||
if (d.band != 2 && d.band != 5)
|
||||
return DefError::BadBand;
|
||||
if (d.band == 2 && (d.primary < 1 || d.primary > 14))
|
||||
return DefError::BadPrimary;
|
||||
/* 5 GHz: the synth grid runs past the UNII channels (chan_to_freq covers
|
||||
* 16..253); grid math below constrains 40/80 further. */
|
||||
if (d.band == 5 && (d.primary < 16 || d.primary > 253))
|
||||
return DefError::BadPrimary;
|
||||
|
||||
switch (d.width) {
|
||||
case CHANNEL_WIDTH_20:
|
||||
case CHANNEL_WIDTH_5:
|
||||
case CHANNEL_WIDTH_10:
|
||||
if (d.offset != 0)
|
||||
return DefError::BadOffset;
|
||||
return DefError::Ok;
|
||||
|
||||
case CHANNEL_WIDTH_40:
|
||||
if (d.band == 2) {
|
||||
/* Any ±4 pair inside ch1..13. Ch14 sits 12 MHz above ch13 (not on the
|
||||
* 5 MHz grid), so it can be neither primary nor secondary of a pair. */
|
||||
if (d.primary == 14)
|
||||
return DefError::OffGrid40;
|
||||
const bool up_ok = d.primary + 4 <= 13;
|
||||
const bool dn_ok = d.primary >= 5;
|
||||
if (!up_ok && !dn_ok)
|
||||
return DefError::OffGrid40;
|
||||
if (d.offset == 0) {
|
||||
if (up_ok && dn_ok)
|
||||
return DefError::AmbiguousOffset;
|
||||
d.offset = up_ok ? 1 : 2;
|
||||
return DefError::Ok;
|
||||
}
|
||||
if (d.offset == 1)
|
||||
return up_ok ? DefError::Ok : DefError::OffGrid40;
|
||||
if (d.offset == 2)
|
||||
return dn_ok ? DefError::Ok : DefError::OffGrid40;
|
||||
return DefError::BadOffset;
|
||||
}
|
||||
{
|
||||
/* 5 GHz pairs are grid-fixed. The raster restarts at 149 (5745) — the
|
||||
* UNII-3 block is not on the 36-anchored raster. */
|
||||
const int anchor = d.primary >= 149 ? 149 : 36;
|
||||
const int rel = d.primary - anchor;
|
||||
if (rel < 0 || rel % 4 != 0)
|
||||
return DefError::OffGrid40;
|
||||
const uint8_t derived = (rel % 8 == 0) ? 1 : 2;
|
||||
if (d.offset == 0) {
|
||||
d.offset = derived;
|
||||
return DefError::Ok;
|
||||
}
|
||||
return d.offset == derived ? DefError::Ok : DefError::BadOffset;
|
||||
}
|
||||
|
||||
case CHANNEL_WIDTH_80: {
|
||||
if (d.band == 2)
|
||||
return DefError::BadWidth;
|
||||
const int anchor = d.primary >= 149 ? 149 : 36;
|
||||
const int rel = d.primary - anchor;
|
||||
if (rel < 0 || rel % 4 != 0)
|
||||
return DefError::OffGrid80;
|
||||
const uint8_t derived = static_cast<uint8_t>((rel % 16) / 4 + 1);
|
||||
if (d.offset == 0) {
|
||||
d.offset = derived;
|
||||
return DefError::Ok;
|
||||
}
|
||||
return d.offset == derived ? DefError::Ok : DefError::BadOffset;
|
||||
}
|
||||
|
||||
default:
|
||||
return DefError::BadWidth;
|
||||
}
|
||||
}
|
||||
|
||||
inline DefError validate(const ChannelDef &d) {
|
||||
ChannelDef copy = d;
|
||||
const DefError e = normalize(copy);
|
||||
if (e != DefError::Ok)
|
||||
return e;
|
||||
/* An unset offset that normalize() had to fill means the caller's def was
|
||||
* incomplete but derivable — treat as valid (identical key after fill). */
|
||||
return DefError::Ok;
|
||||
}
|
||||
|
||||
/* The 20 MHz constituent bins of the occupied block, ascending. Returns the
|
||||
* bin count (1/2/4); out must hold 4. Narrowband occupies within one bin. */
|
||||
inline int constituent_bins(const ChannelDef &d, uint8_t out[4]) {
|
||||
switch (d.width) {
|
||||
case CHANNEL_WIDTH_40: {
|
||||
const uint8_t lo = (d.offset == 1) ? d.primary
|
||||
: static_cast<uint8_t>(d.primary - 4);
|
||||
out[0] = lo;
|
||||
out[1] = static_cast<uint8_t>(lo + 4);
|
||||
return 2;
|
||||
}
|
||||
case CHANNEL_WIDTH_80: {
|
||||
const uint8_t pos = (d.offset >= 1 && d.offset <= 4) ? d.offset : 1;
|
||||
const uint8_t base = static_cast<uint8_t>(d.primary - 4 * (pos - 1));
|
||||
for (int i = 0; i < 4; i++)
|
||||
out[i] = static_cast<uint8_t>(base + 4 * i);
|
||||
return 4;
|
||||
}
|
||||
default:
|
||||
out[0] = d.primary;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Span intersection in MHz (0 when disjoint or cross-band). */
|
||||
inline int overlap_mhz(const ChannelDef &a, const ChannelDef &b) {
|
||||
if (a.band != b.band)
|
||||
return 0;
|
||||
const int alo = a.center_halfmhz() - a.span_halfmhz() / 2;
|
||||
const int ahi = a.center_halfmhz() + a.span_halfmhz() / 2;
|
||||
const int blo = b.center_halfmhz() - b.span_halfmhz() / 2;
|
||||
const int bhi = b.center_halfmhz() + b.span_halfmhz() / 2;
|
||||
const int lo = alo > blo ? alo : blo;
|
||||
const int hi = ahi < bhi ? ahi : bhi;
|
||||
return hi > lo ? (hi - lo) / 2 : 0;
|
||||
}
|
||||
|
||||
/* Disjoint but with an edge gap under 20 MHz — the adjacent-channel-leakage
|
||||
* regime a scoring policy penalizes. */
|
||||
inline bool adjacent(const ChannelDef &a, const ChannelDef &b) {
|
||||
if (a.band != b.band || overlap_mhz(a, b) > 0)
|
||||
return false;
|
||||
const int ahi = a.center_halfmhz() + a.span_halfmhz() / 2;
|
||||
const int alo = a.center_halfmhz() - a.span_halfmhz() / 2;
|
||||
const int bhi = b.center_halfmhz() + b.span_halfmhz() / 2;
|
||||
const int blo = b.center_halfmhz() - b.span_halfmhz() / 2;
|
||||
const int gap = (alo >= bhi) ? alo - bhi : blo - ahi;
|
||||
return gap >= 0 && gap < 40; /* half-MHz units */
|
||||
}
|
||||
|
||||
/* --- scan-plan grammar ---
|
||||
*
|
||||
* plan = tok[,tok...]
|
||||
* tok = <primary>[/<width>[u|l]][:<flags>]
|
||||
* width = 5 | 10 | 20 (default) | 40 | 80
|
||||
* u/l = 40 MHz secondary above / below (required on 2.4 GHz, derived and
|
||||
* checked on 5 GHz)
|
||||
* flags = any of b (preferred backup) p (no-IR / receive-only)
|
||||
* d (DFS, informational)
|
||||
*
|
||||
* e.g. "104/40l:b,36/80,132/20:p"
|
||||
*
|
||||
* Band derives from the primary (<=14 → 2.4 GHz); mixed-band plans are
|
||||
* rejected because the scout's cheap retune path is intra-band. Malformed and
|
||||
* off-grid tokens are REPORTED, never silently dropped — a silently missing
|
||||
* migration candidate is a field hazard. */
|
||||
struct PlanParseError {
|
||||
std::string token;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
inline bool parse_chan_token(const std::string &tok, ChannelDef &out,
|
||||
std::string &err) {
|
||||
out = ChannelDef{};
|
||||
std::string t = tok;
|
||||
/* Optional canonical band prefix ("5:104/40l" — what format() emits), so
|
||||
* formatted defs round-trip through the parser. Checked against the band
|
||||
* the primary derives. */
|
||||
int want_band = 0;
|
||||
if (t.size() >= 2 && (t[0] == '2' || t[0] == '5') && t[1] == ':') {
|
||||
want_band = t[0] - '0';
|
||||
t = t.substr(2);
|
||||
}
|
||||
/* flags suffix */
|
||||
const size_t colon = t.find(':');
|
||||
if (colon != std::string::npos) {
|
||||
for (size_t i = colon + 1; i < t.size(); ++i) {
|
||||
switch (t[i]) {
|
||||
case 'b': out.backup = true; break;
|
||||
case 'p': out.no_ir = true; break;
|
||||
case 'd': out.dfs = true; break;
|
||||
default:
|
||||
err = "unknown flag";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
t = t.substr(0, colon);
|
||||
}
|
||||
/* width (+ u/l) */
|
||||
ChannelWidth_t width = CHANNEL_WIDTH_20;
|
||||
uint8_t offset = 0;
|
||||
const size_t slash = t.find('/');
|
||||
if (slash != std::string::npos) {
|
||||
std::string w = t.substr(slash + 1);
|
||||
t = t.substr(0, slash);
|
||||
if (!w.empty() && (w.back() == 'u' || w.back() == 'l')) {
|
||||
offset = (w.back() == 'u') ? 1 : 2;
|
||||
w.pop_back();
|
||||
}
|
||||
if (w == "5") width = CHANNEL_WIDTH_5;
|
||||
else if (w == "10") width = CHANNEL_WIDTH_10;
|
||||
else if (w == "20") width = CHANNEL_WIDTH_20;
|
||||
else if (w == "40") width = CHANNEL_WIDTH_40;
|
||||
else if (w == "80") width = CHANNEL_WIDTH_80;
|
||||
else {
|
||||
err = "bad width";
|
||||
return false;
|
||||
}
|
||||
if (offset != 0 && width != CHANNEL_WIDTH_40) {
|
||||
err = "u/l suffix is 40 MHz-only";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
char *end = nullptr;
|
||||
const long ch = std::strtol(t.c_str(), &end, 10);
|
||||
if (t.empty() || end == nullptr || *end != '\0' || ch <= 0 || ch > 253) {
|
||||
err = "bad primary channel";
|
||||
return false;
|
||||
}
|
||||
out.primary = static_cast<uint8_t>(ch);
|
||||
out.band = (ch <= 14) ? 2 : 5;
|
||||
if (want_band != 0 && want_band != out.band) {
|
||||
err = "band prefix contradicts the primary";
|
||||
return false;
|
||||
}
|
||||
out.width = width;
|
||||
out.offset = offset;
|
||||
const DefError e = normalize(out);
|
||||
if (e != DefError::Ok) {
|
||||
err = def_error_name(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool parse_scan_plan(const char *text, std::vector<ChannelDef> &out,
|
||||
std::vector<PlanParseError> &errors) {
|
||||
out.clear();
|
||||
errors.clear();
|
||||
if (text == nullptr || *text == '\0') {
|
||||
errors.push_back({"", "empty plan"});
|
||||
return false;
|
||||
}
|
||||
const std::string s = text;
|
||||
size_t pos = 0;
|
||||
while (pos <= s.size()) {
|
||||
const size_t comma = s.find(',', pos);
|
||||
const std::string tok = s.substr(
|
||||
pos, comma == std::string::npos ? std::string::npos : comma - pos);
|
||||
pos = (comma == std::string::npos) ? s.size() + 1 : comma + 1;
|
||||
if (tok.empty())
|
||||
continue;
|
||||
ChannelDef d;
|
||||
std::string err;
|
||||
if (!parse_chan_token(tok, d, err)) {
|
||||
errors.push_back({tok, err});
|
||||
continue;
|
||||
}
|
||||
if (!out.empty() && d.band != out.front().band) {
|
||||
errors.push_back({tok, "mixed band (scout plans are single-band)"});
|
||||
continue;
|
||||
}
|
||||
bool dup = false;
|
||||
for (const ChannelDef &o : out)
|
||||
if (o.same_rf(d)) {
|
||||
errors.push_back({tok, "duplicate candidate"});
|
||||
dup = true;
|
||||
break;
|
||||
}
|
||||
if (!dup)
|
||||
out.push_back(d);
|
||||
}
|
||||
if (out.empty() && errors.empty())
|
||||
errors.push_back({"", "empty plan"});
|
||||
return errors.empty() && !out.empty();
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_CHANNEL_DEF_H */
|
||||
@@ -0,0 +1,94 @@
|
||||
/* channel.recommend / channel.hold / channel.reject JSONL binding — the
|
||||
* advisory engine's output, emitted from a Decision. One header so the schema
|
||||
* has a single definition (chanscout emits; the migration controller and the
|
||||
* dashboard parse). Every event carries the evidence generation, plan hash,
|
||||
* and policy hash, so any decision is reproducible from the logs. */
|
||||
#ifndef DEVOURER_CHANMIG_CHANNEL_EVENTS_H
|
||||
#define DEVOURER_CHANMIG_CHANNEL_EVENTS_H
|
||||
|
||||
#include "Event.h"
|
||||
#include "chanmig/ChannelScore.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
inline const char *impair_name(Impair im) {
|
||||
switch (im) {
|
||||
case Impair::Healthy: return "healthy";
|
||||
case Impair::Channel: return "channel";
|
||||
case Impair::WeakSignal: return "weak_signal";
|
||||
case Impair::Saturation: return "saturation";
|
||||
case Impair::TelemetryDown: return "telemetry_down";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Emit the decision. `recommend` and `hold` share one envelope (kind field);
|
||||
* a candidate that lost qualification since the previous decision is emitted
|
||||
* as a separate channel.reject so a consumer watching only rejects sees it. */
|
||||
inline void emit_decision(EventSink &sink, const Decision &d,
|
||||
const ChannelDef &active) {
|
||||
Ev ev(sink, d.kind == Decision::Kind::Recommend ? "channel.recommend"
|
||||
: "channel.hold");
|
||||
ev.t().f("v", 1);
|
||||
ev.hexf("gen", d.evidence_gen, 0);
|
||||
ev.hexf("plan", d.plan_hash, 8);
|
||||
ev.hexf("policy", d.policy_hash, 8);
|
||||
char from[20];
|
||||
active.format(from, sizeof(from));
|
||||
ev.f("from", from).f("reason", reason_name(d.primary_reason));
|
||||
ev.f("active_verdict", verdict_label(d.active_verdict));
|
||||
ev.f("active_domain", impair_name(d.active_domain))
|
||||
.f("impaired_windows", d.active_impaired_windows);
|
||||
if (d.kind == Decision::Kind::Recommend) {
|
||||
char to[20];
|
||||
d.target.format(to, sizeof(to));
|
||||
ev.f("to", to);
|
||||
for (const CandidateScore &c : d.ranking)
|
||||
if (c.def.same_rf(d.target)) {
|
||||
ev.f("score", c.score).f("conf", c.confidence).f("occ", c.occ_q50)
|
||||
.f("rounds", (unsigned long long)c.rounds)
|
||||
.f("obs_ms", (unsigned long long)c.observe_ms);
|
||||
break;
|
||||
}
|
||||
}
|
||||
ev.f("text", d.human_reason.c_str());
|
||||
}
|
||||
|
||||
/* Full per-candidate ranking as one line, so the dashboard can render the
|
||||
* counterfactual (why NOT each candidate) purely from the log. */
|
||||
inline void emit_ranking(EventSink &sink, const Decision &d) {
|
||||
Ev ev(sink, "channel.ranking");
|
||||
ev.t().hexf("gen", d.evidence_gen, 0).f("n", (long long)d.ranking.size());
|
||||
int rank = 0;
|
||||
for (const CandidateScore &c : d.ranking) {
|
||||
char chan[20];
|
||||
c.def.format(chan, sizeof(chan));
|
||||
/* one flat field per candidate, keyed by rank index — no nested objects */
|
||||
char key[8];
|
||||
std::snprintf(key, sizeof(key), "c%d", rank);
|
||||
char buf[112];
|
||||
std::snprintf(buf, sizeof(buf), "%s q=%d score=%.2f occ=%.2f rej=%d", chan,
|
||||
c.qualified ? 1 : 0, c.score, c.occ_q50, c.n_rejections);
|
||||
ev.f(key, buf);
|
||||
++rank;
|
||||
}
|
||||
}
|
||||
|
||||
/* Emit a candidate that just lost qualification (a channel.reject watcher). */
|
||||
inline void emit_reject(EventSink &sink, const CandidateScore &c,
|
||||
uint64_t gen) {
|
||||
Ev ev(sink, "channel.reject");
|
||||
char chan[20];
|
||||
c.def.format(chan, sizeof(chan));
|
||||
ev.t().hexf("gen", gen, 0).f("chan", chan);
|
||||
if (c.n_rejections > 0)
|
||||
ev.f("reason", reason_name(c.rejections[0]));
|
||||
ev.f("occ", c.occ_q50).f("age_ms", (long long)c.evidence_age_ms)
|
||||
.f("rounds", (unsigned long long)c.rounds);
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_CHANNEL_EVENTS_H */
|
||||
@@ -0,0 +1,353 @@
|
||||
#include "chanmig/ChannelScore.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
const char *reason_name(Reason r) {
|
||||
switch (r) {
|
||||
case Reason::RecommendBetterCandidate: return "RecommendBetterCandidate";
|
||||
case Reason::HoldActiveHealthy: return "HoldActiveHealthy";
|
||||
case Reason::HoldImpairmentNotPersistent: return "HoldImpairmentNotPersistent";
|
||||
case Reason::HoldImpairmentNotChannel: return "HoldImpairmentNotChannel";
|
||||
case Reason::HoldBroadDegradation: return "HoldBroadDegradation";
|
||||
case Reason::HoldCooldown: return "HoldCooldown";
|
||||
case Reason::HoldPrimaryTelemetryStale: return "HoldPrimaryTelemetryStale";
|
||||
case Reason::HoldNoQualifiedCandidate: return "HoldNoQualifiedCandidate";
|
||||
case Reason::HoldImprovementMargin: return "HoldImprovementMargin";
|
||||
case Reason::HoldScoutUnhealthy: return "HoldScoutUnhealthy";
|
||||
case Reason::RejEvidenceStale: return "RejEvidenceStale";
|
||||
case Reason::RejInsufficientObservation: return "RejInsufficientObservation";
|
||||
case Reason::RejInsufficientRounds: return "RejInsufficientRounds";
|
||||
case Reason::RejIncompleteWidth: return "RejIncompleteWidth";
|
||||
case Reason::RejIllegalDef: return "RejIllegalDef";
|
||||
case Reason::RejNoIr: return "RejNoIr";
|
||||
case Reason::RejOccupied: return "RejOccupied";
|
||||
case Reason::RejBursty: return "RejBursty";
|
||||
case Reason::RejOverlapPenalty: return "RejOverlapPenalty";
|
||||
case Reason::RejMixedAdapter: return "RejMixedAdapter";
|
||||
case Reason::RejScoutUnhealthy: return "RejScoutUnhealthy";
|
||||
case Reason::RejActiveChannel: return "RejActiveChannel";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
uint32_t PolicyConfig::policy_hash() const {
|
||||
uint32_t h = 2166136261u;
|
||||
auto fold = [&h](const void *p, size_t n) {
|
||||
const uint8_t *b = static_cast<const uint8_t *>(p);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
h ^= b[i];
|
||||
h *= 16777619u;
|
||||
}
|
||||
};
|
||||
fold(&impaired_windows_min, sizeof(impaired_windows_min));
|
||||
fold(&active.loss_impair, sizeof(active.loss_impair));
|
||||
fold(&active.crc_impair, sizeof(active.crc_impair));
|
||||
fold(&active.fec_margin_impair, sizeof(active.fec_margin_impair));
|
||||
fold(&active.min_frames, sizeof(active.min_frames));
|
||||
fold(&min_rounds, sizeof(min_rounds));
|
||||
fold(&min_clean_obs_ms, sizeof(min_clean_obs_ms));
|
||||
fold(&max_evidence_age_ms, sizeof(max_evidence_age_ms));
|
||||
fold(&qualify_max_occupancy, sizeof(qualify_max_occupancy));
|
||||
fold(&bursty_max, sizeof(bursty_max));
|
||||
fold(&improvement_margin, sizeof(improvement_margin));
|
||||
fold(&min_recommend_interval_ms, sizeof(min_recommend_interval_ms));
|
||||
fold(&broad_degrade_frac, sizeof(broad_degrade_frac));
|
||||
fold(&fa_half_rate, sizeof(fa_half_rate));
|
||||
fold(&overlap_penalty, sizeof(overlap_penalty));
|
||||
fold(&age_decay_tau_ms, sizeof(age_decay_tau_ms));
|
||||
return h;
|
||||
}
|
||||
|
||||
bool parse_policy_file(const char *path, PolicyConfig &cfg, std::string *err) {
|
||||
std::FILE *f = std::fopen(path, "r");
|
||||
if (f == nullptr) {
|
||||
if (err)
|
||||
*err = "cannot open policy file";
|
||||
return false;
|
||||
}
|
||||
char line[256];
|
||||
while (std::fgets(line, sizeof(line), f)) {
|
||||
char key[64];
|
||||
double val;
|
||||
/* `key value`, '#' comments, blank lines ignored. */
|
||||
if (line[0] == '#' || line[0] == '\n')
|
||||
continue;
|
||||
if (std::sscanf(line, "%63s %lf", key, &val) != 2)
|
||||
continue;
|
||||
if (!std::strcmp(key, "impaired_windows_min"))
|
||||
cfg.impaired_windows_min = static_cast<int>(val);
|
||||
else if (!std::strcmp(key, "loss_impair"))
|
||||
cfg.active.loss_impair = val;
|
||||
else if (!std::strcmp(key, "crc_impair"))
|
||||
cfg.active.crc_impair = val;
|
||||
else if (!std::strcmp(key, "fec_margin_impair"))
|
||||
cfg.active.fec_margin_impair = val;
|
||||
else if (!std::strcmp(key, "active_min_frames"))
|
||||
cfg.active.min_frames = static_cast<uint32_t>(val);
|
||||
else if (!std::strcmp(key, "min_rounds"))
|
||||
cfg.min_rounds = static_cast<uint64_t>(val < 0 ? 0 : val);
|
||||
else if (!std::strcmp(key, "min_clean_obs_ms"))
|
||||
cfg.min_clean_obs_ms = static_cast<int64_t>(val);
|
||||
else if (!std::strcmp(key, "max_evidence_age_ms"))
|
||||
cfg.max_evidence_age_ms = static_cast<int64_t>(val);
|
||||
else if (!std::strcmp(key, "qualify_max_occupancy"))
|
||||
cfg.qualify_max_occupancy = val;
|
||||
else if (!std::strcmp(key, "bursty_max"))
|
||||
cfg.bursty_max = val;
|
||||
else if (!std::strcmp(key, "improvement_margin"))
|
||||
cfg.improvement_margin = val;
|
||||
else if (!std::strcmp(key, "min_recommend_interval_ms"))
|
||||
cfg.min_recommend_interval_ms = static_cast<int64_t>(val);
|
||||
else if (!std::strcmp(key, "broad_degrade_frac"))
|
||||
cfg.broad_degrade_frac = val;
|
||||
else if (!std::strcmp(key, "fa_half_rate"))
|
||||
cfg.fa_half_rate = val;
|
||||
else if (!std::strcmp(key, "overlap_penalty"))
|
||||
cfg.overlap_penalty = val;
|
||||
else if (!std::strcmp(key, "age_decay_tau_ms"))
|
||||
cfg.age_decay_tau_ms = val;
|
||||
}
|
||||
std::fclose(f);
|
||||
return true;
|
||||
}
|
||||
|
||||
RecommendEngine::RecommendEngine(PolicyConfig policy,
|
||||
std::vector<ChannelDef> candidates,
|
||||
uint32_t plan_hash, ChannelDef active)
|
||||
: policy_(policy), plan_hash_(plan_hash), active_(active),
|
||||
store_(std::move(candidates), plan_hash, policy.max_evidence_age_ms),
|
||||
track_(policy.active) {}
|
||||
|
||||
/* Per-cell occupancy proxy in [0,1] from the two physical-ish signals that
|
||||
* on-air-track real occupancy across generations: decoded foreign airtime,
|
||||
* and a bounded false-alarm term (NHM is deliberately excluded — its absolute
|
||||
* floor is generation-dependent, e.g. the 8822B reads busy on a quiet
|
||||
* channel). */
|
||||
static double cell_occupancy(const BinCell &c, double fa_half) {
|
||||
const double fa_term = c.fa_rate / (c.fa_rate + fa_half);
|
||||
double occ = c.oth_air_frac + fa_term;
|
||||
if (occ > 1.0)
|
||||
occ = 1.0;
|
||||
return occ;
|
||||
}
|
||||
|
||||
static double quantile(std::vector<double> v, double q) {
|
||||
if (v.empty())
|
||||
return 0.0;
|
||||
std::sort(v.begin(), v.end());
|
||||
const double idx = q * (v.size() - 1);
|
||||
const size_t lo = static_cast<size_t>(idx);
|
||||
const size_t hi = lo + 1 < v.size() ? lo + 1 : lo;
|
||||
const double frac = idx - lo;
|
||||
return v[lo] * (1.0 - frac) + v[hi] * frac;
|
||||
}
|
||||
|
||||
CandidateScore RecommendEngine::score_candidate(size_t i,
|
||||
int64_t now_ms) const {
|
||||
CandidateScore s;
|
||||
s.def = store_.candidate(i);
|
||||
uint8_t bins[4];
|
||||
const int nb = constituent_bins(s.def, bins);
|
||||
s.bins_total = nb;
|
||||
s.bins_covered = store_.bins_covered(i, now_ms);
|
||||
s.evidence_age_ms = store_.evidence_age_ms(i, now_ms);
|
||||
s.rounds = store_.rounds_covered(i, now_ms);
|
||||
|
||||
auto reject = [&s](Reason r) {
|
||||
if (s.n_rejections < 6)
|
||||
s.rejections[s.n_rejections++] = r;
|
||||
};
|
||||
|
||||
/* Occupancy = the WORST constituent bin (a wide channel is only as clean as
|
||||
* its dirtiest 20 MHz slice). Per bin, q50/q90 of cell occupancy. */
|
||||
double worst_q50 = 0.0, worst_q90 = 0.0;
|
||||
uint64_t total_obs = 0;
|
||||
bool any_cells = false;
|
||||
int64_t min_bin_clean_ms = INT64_MAX;
|
||||
for (int b = 0; b < nb; b++) {
|
||||
std::vector<const BinCell *> cells;
|
||||
store_.fresh_cells(bins[b], now_ms, cells);
|
||||
int64_t bin_obs = 0;
|
||||
std::vector<double> occ;
|
||||
for (const BinCell *c : cells) {
|
||||
occ.push_back(cell_occupancy(*c, policy_.fa_half_rate));
|
||||
bin_obs += c->observe_ms;
|
||||
total_obs += static_cast<uint64_t>(c->observe_ms);
|
||||
any_cells = true;
|
||||
}
|
||||
if (!occ.empty()) {
|
||||
const double q50 = quantile(occ, 0.5), q90 = quantile(occ, 0.9);
|
||||
if (q50 > worst_q50)
|
||||
worst_q50 = q50;
|
||||
if (q90 > worst_q90)
|
||||
worst_q90 = q90;
|
||||
}
|
||||
if (bin_obs < min_bin_clean_ms)
|
||||
min_bin_clean_ms = bin_obs;
|
||||
}
|
||||
s.observe_ms = total_obs;
|
||||
s.occ_q50 = worst_q50;
|
||||
s.occ_q90 = worst_q90;
|
||||
s.burstiness = worst_q90 - worst_q50;
|
||||
|
||||
/* Overlap penalty: a candidate overlapping or adjacent to the (impaired)
|
||||
* active channel may inherit its interferer. */
|
||||
if (overlap_mhz(s.def, active_) > 0 || adjacent(s.def, active_))
|
||||
s.overlap_pen = policy_.overlap_penalty;
|
||||
|
||||
const double occupancy =
|
||||
std::min(1.0, s.occ_q50 + s.overlap_pen);
|
||||
s.score = 1.0 - occupancy;
|
||||
|
||||
/* Confidence: an engineering scalar (not a formal CI) folding observation
|
||||
* volume, round coverage, and evidence age. Documented in the doc. */
|
||||
const double obs_factor =
|
||||
std::min(1.0, static_cast<double>(total_obs) /
|
||||
std::max<int64_t>(1, policy_.min_clean_obs_ms * nb * 2));
|
||||
const double rounds_factor =
|
||||
std::min(1.0, static_cast<double>(s.rounds) /
|
||||
std::max<uint64_t>(1, policy_.min_rounds * 2));
|
||||
const double age_factor =
|
||||
s.evidence_age_ms < 0
|
||||
? 0.0
|
||||
: std::exp(-static_cast<double>(s.evidence_age_ms) /
|
||||
policy_.age_decay_tau_ms);
|
||||
s.confidence = obs_factor * rounds_factor * age_factor;
|
||||
|
||||
/* Gates (order = most-fundamental first; all recorded). */
|
||||
if (s.def.no_ir)
|
||||
reject(Reason::RejNoIr);
|
||||
if (validate(s.def) != DefError::Ok)
|
||||
reject(Reason::RejIllegalDef);
|
||||
if (s.def.same_rf(active_))
|
||||
reject(Reason::RejActiveChannel);
|
||||
if (!scout_healthy_)
|
||||
reject(Reason::RejScoutUnhealthy);
|
||||
if (!any_cells || s.evidence_age_ms < 0)
|
||||
reject(Reason::RejEvidenceStale);
|
||||
else if (s.evidence_age_ms > policy_.max_evidence_age_ms)
|
||||
reject(Reason::RejEvidenceStale);
|
||||
if (s.bins_covered < s.bins_total)
|
||||
reject(Reason::RejIncompleteWidth);
|
||||
if (any_cells && min_bin_clean_ms < policy_.min_clean_obs_ms)
|
||||
reject(Reason::RejInsufficientObservation);
|
||||
if (s.rounds < policy_.min_rounds)
|
||||
reject(Reason::RejInsufficientRounds);
|
||||
if (any_cells && occupancy > policy_.qualify_max_occupancy)
|
||||
reject(Reason::RejOccupied);
|
||||
if (any_cells && s.burstiness > policy_.bursty_max)
|
||||
reject(Reason::RejBursty);
|
||||
|
||||
s.qualified = (s.n_rejections == 0);
|
||||
return s;
|
||||
}
|
||||
|
||||
Decision RecommendEngine::decide(int64_t now_ms) {
|
||||
Decision d;
|
||||
d.plan_hash = plan_hash_;
|
||||
d.policy_hash = policy_.policy_hash();
|
||||
d.evidence_gen = store_.generation();
|
||||
d.active_impaired_windows = track_.consecutive_channel_impaired();
|
||||
d.active_verdict = track_.last_verdict();
|
||||
d.active_domain = track_.last_domain();
|
||||
|
||||
/* Score + rank every candidate (best score first, deterministic tie-break
|
||||
* by ascending RF key). */
|
||||
for (size_t i = 0; i < store_.candidate_count(); ++i)
|
||||
d.ranking.push_back(score_candidate(i, now_ms));
|
||||
std::sort(d.ranking.begin(), d.ranking.end(),
|
||||
[](const CandidateScore &a, const CandidateScore &b) {
|
||||
if (a.qualified != b.qualified)
|
||||
return a.qualified; /* qualified first */
|
||||
if (a.score != b.score)
|
||||
return a.score > b.score;
|
||||
return a.def.key() < b.def.key();
|
||||
});
|
||||
|
||||
auto finish = [&](Decision::Kind k, Reason r, const std::string &text) {
|
||||
d.kind = k;
|
||||
d.primary_reason = r;
|
||||
d.human_reason = text;
|
||||
return d;
|
||||
};
|
||||
|
||||
/* leg 1 — active-channel fault domain and persistence. */
|
||||
if (!track_.have() || d.active_domain == Impair::TelemetryDown)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldPrimaryTelemetryStale,
|
||||
"no trustworthy primary delivery telemetry");
|
||||
if (!scout_healthy_)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldScoutUnhealthy,
|
||||
"scout unhealthy — candidate evidence untrusted");
|
||||
if (d.active_domain == Impair::WeakSignal)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldImpairmentNotChannel,
|
||||
"active link weak (range/sensitivity) — a move will not help");
|
||||
if (d.active_domain == Impair::Saturation)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldImpairmentNotChannel,
|
||||
"active link saturated (near-field) — reduce power, do not move");
|
||||
if (d.active_domain == Impair::Healthy &&
|
||||
d.active_impaired_windows < policy_.impaired_windows_min)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldActiveHealthy,
|
||||
"active video delivering — hold");
|
||||
if (d.active_impaired_windows < policy_.impaired_windows_min)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldImpairmentNotPersistent,
|
||||
"impairment not yet persistent enough to act");
|
||||
|
||||
/* Broad degradation: if most candidates are ALSO busy, the interference is
|
||||
* not this channel's — moving won't escape it. */
|
||||
int busy = 0, scored = 0;
|
||||
for (const CandidateScore &c : d.ranking) {
|
||||
if (c.evidence_age_ms < 0)
|
||||
continue;
|
||||
++scored;
|
||||
if (std::min(1.0, c.occ_q50 + c.overlap_pen) > policy_.qualify_max_occupancy)
|
||||
++busy;
|
||||
}
|
||||
if (scored > 0 &&
|
||||
static_cast<double>(busy) / scored >= policy_.broad_degrade_frac)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldBroadDegradation,
|
||||
"interference spans most candidates — broad, not channel-local");
|
||||
|
||||
/* leg 2 — a qualified, materially-clean candidate. */
|
||||
const CandidateScore &best = d.ranking.front();
|
||||
if (!best.qualified)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldNoQualifiedCandidate,
|
||||
"no candidate passed all qualification gates");
|
||||
/* Materially better than merely-acceptable: score must clear the qualify
|
||||
* floor by the configured margin (a barely-clean candidate is not worth a
|
||||
* whole-link move). */
|
||||
const double floor = 1.0 - policy_.qualify_max_occupancy;
|
||||
if (best.score < floor + policy_.improvement_margin)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldImprovementMargin,
|
||||
"best candidate clean but not by the required margin");
|
||||
|
||||
/* Cooldown: rate-limit recommendations so a rank alternation between two
|
||||
* near-equal candidates cannot churn the operator. */
|
||||
if (last_recommend_ms_ != INT64_MIN &&
|
||||
now_ms - last_recommend_ms_ < policy_.min_recommend_interval_ms)
|
||||
return finish(Decision::Kind::Hold, Reason::HoldCooldown,
|
||||
"within the minimum interval since the last recommendation");
|
||||
|
||||
last_recommend_ms_ = now_ms;
|
||||
d.target = best.def;
|
||||
char from[20], to[20];
|
||||
active_.format(from, sizeof(from));
|
||||
best.def.format(to, sizeof(to));
|
||||
char text[160];
|
||||
std::snprintf(text, sizeof(text),
|
||||
"%s impaired %d windows; %s clean (occ %.2f, %llu rounds, "
|
||||
"%llu ms) — recommend move",
|
||||
from, d.active_impaired_windows, to, best.occ_q50,
|
||||
(unsigned long long)best.rounds,
|
||||
(unsigned long long)best.observe_ms);
|
||||
return finish(Decision::Kind::Recommend, Reason::RecommendBetterCandidate,
|
||||
text);
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,164 @@
|
||||
/* RecommendEngine — the pure, explainable channel-recommendation policy.
|
||||
*
|
||||
* Inputs are timestamped records (scout survey folds + primary active-link
|
||||
* windows); output is a Decision that is either Hold or Recommend, carrying a
|
||||
* full per-candidate ranking with exact reason/rejection codes and the
|
||||
* evidence generation it was computed at. The engine reads no clock (the
|
||||
* caller passes now), no env, no device — it only ever emits advice, so it
|
||||
* structurally cannot retune anything.
|
||||
*
|
||||
* The recommendation law has two independent legs, deliberately kept in
|
||||
* separate unit worlds (the "never compare raw across adapters / across the
|
||||
* primary-scout boundary" rule):
|
||||
* leg 1 the ACTIVE channel is PERSISTENTLY impaired by DELIVERY evidence
|
||||
* (the primary receiver's loss/FEC/CRC), and the impairment's fault
|
||||
* domain is channel-attributable — not weak-signal, not near-field
|
||||
* saturation, not a broad multi-candidate degradation;
|
||||
* leg 2 a CANDIDATE is sufficiently observed (rounds, per-bin clean time,
|
||||
* full-width coverage, freshness), legal, and materially clean in
|
||||
* the scout's own within-scout-normalized occupancy terms.
|
||||
* A single threshold crossing on either leg never recommends a move.
|
||||
*
|
||||
* Thresholds live in PolicyConfig, loadable from a bare `key value` file so
|
||||
* the exact policy artifact is versionable and hashable; policy_hash is
|
||||
* stamped into every decision, making any output reproducible from the logs.
|
||||
*
|
||||
* Pure; selftested against the issue's offline scenario matrix. */
|
||||
#ifndef DEVOURER_CHANMIG_CHANNEL_SCORE_H
|
||||
#define DEVOURER_CHANMIG_CHANNEL_SCORE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ActiveLink.h"
|
||||
#include "chanmig/ChannelDef.h"
|
||||
#include "chanmig/EvidenceStore.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
enum class Reason {
|
||||
/* recommend */
|
||||
RecommendBetterCandidate,
|
||||
/* holds (whole-decision) */
|
||||
HoldActiveHealthy,
|
||||
HoldImpairmentNotPersistent,
|
||||
HoldImpairmentNotChannel,
|
||||
HoldBroadDegradation,
|
||||
HoldCooldown,
|
||||
HoldPrimaryTelemetryStale,
|
||||
HoldNoQualifiedCandidate,
|
||||
HoldImprovementMargin,
|
||||
HoldScoutUnhealthy,
|
||||
/* per-candidate rejections */
|
||||
RejEvidenceStale,
|
||||
RejInsufficientObservation,
|
||||
RejInsufficientRounds,
|
||||
RejIncompleteWidth,
|
||||
RejIllegalDef,
|
||||
RejNoIr,
|
||||
RejOccupied,
|
||||
RejBursty,
|
||||
RejOverlapPenalty,
|
||||
RejMixedAdapter,
|
||||
RejScoutUnhealthy,
|
||||
RejActiveChannel,
|
||||
};
|
||||
|
||||
const char *reason_name(Reason r);
|
||||
|
||||
struct PolicyConfig {
|
||||
/* leg 1 — active-channel impairment */
|
||||
int impaired_windows_min = 5; /* consecutive channel-impaired windows */
|
||||
ActivePolicy active;
|
||||
|
||||
/* leg 2 — candidate qualification */
|
||||
uint64_t min_rounds = 3; /* distinct complete scan rounds */
|
||||
int64_t min_clean_obs_ms = 3000; /* fresh observation per constituent bin */
|
||||
int64_t max_evidence_age_ms = 60000;
|
||||
double qualify_max_occupancy = 0.20; /* candidate occupancy above = Occupied */
|
||||
double bursty_max = 0.30; /* q90-q50 above = Bursty */
|
||||
/* A candidate can be acceptable (qualifies) yet not worth a whole-link move.
|
||||
* To RECOMMEND, its score must clear the qualify floor (1 - occupancy bar)
|
||||
* by this margin — hysteresis between "fine to sit on" and "worth escaping
|
||||
* to". Kept small enough that floor + margin stays <= 1. */
|
||||
double improvement_margin = 0.08;
|
||||
|
||||
/* anti-churn / broad-degradation */
|
||||
int64_t min_recommend_interval_ms = 30000;
|
||||
double broad_degrade_frac = 0.75; /* fraction of candidates busy = broad */
|
||||
|
||||
/* occupancy model + confidence */
|
||||
double fa_half_rate = 200.0; /* fa/s giving a 0.5 fa occupancy term */
|
||||
double overlap_penalty = 0.15; /* added occupancy for an active-adjacent cand */
|
||||
double age_decay_tau_ms = 30000.0; /* confidence decay constant */
|
||||
|
||||
uint32_t policy_hash() const;
|
||||
};
|
||||
|
||||
/* Parse a bare `key value` policy file into cfg (unknown keys ignored, values
|
||||
* clamped to sane ranges). Returns false only on an unreadable file. */
|
||||
bool parse_policy_file(const char *path, PolicyConfig &cfg,
|
||||
std::string *err = nullptr);
|
||||
|
||||
struct CandidateScore {
|
||||
ChannelDef def;
|
||||
bool qualified = false;
|
||||
double score = 0.0; /* [0,1], 1 = clean */
|
||||
double confidence = 0.0; /* [0,1] engineering scalar (obs, rounds, age) */
|
||||
double occ_q50 = 0.0, occ_q90 = 0.0;
|
||||
double burstiness = 0.0;
|
||||
double overlap_pen = 0.0;
|
||||
int64_t evidence_age_ms = -1;
|
||||
uint64_t observe_ms = 0;
|
||||
uint64_t rounds = 0;
|
||||
int bins_covered = 0, bins_total = 0;
|
||||
Reason rejections[6] = {};
|
||||
int n_rejections = 0;
|
||||
};
|
||||
|
||||
struct Decision {
|
||||
enum class Kind { Hold, Recommend } kind = Kind::Hold;
|
||||
Reason primary_reason = Reason::HoldPrimaryTelemetryStale;
|
||||
ChannelDef target; /* Recommend only */
|
||||
std::vector<CandidateScore> ranking; /* every candidate, best first */
|
||||
int active_impaired_windows = 0;
|
||||
LinkVerdict active_verdict = LinkVerdict::NoSignal;
|
||||
Impair active_domain = Impair::TelemetryDown;
|
||||
uint64_t evidence_gen = 0;
|
||||
uint32_t plan_hash = 0, policy_hash = 0;
|
||||
std::string human_reason;
|
||||
};
|
||||
|
||||
class RecommendEngine {
|
||||
public:
|
||||
RecommendEngine(PolicyConfig policy, std::vector<ChannelDef> candidates,
|
||||
uint32_t plan_hash, ChannelDef active);
|
||||
|
||||
EvidenceStore::Fold ingest_dwell(const SurveyDwell &d, int64_t now_ms) {
|
||||
return store_.ingest(d, now_ms);
|
||||
}
|
||||
void ingest_active(const ActiveLinkWindow &w) { track_.add(w); }
|
||||
void note_scout_health(bool healthy) { scout_healthy_ = healthy; }
|
||||
|
||||
uint64_t generation() const { return store_.generation(); }
|
||||
|
||||
Decision decide(int64_t now_ms);
|
||||
|
||||
private:
|
||||
CandidateScore score_candidate(size_t i, int64_t now_ms) const;
|
||||
|
||||
PolicyConfig policy_;
|
||||
uint32_t plan_hash_;
|
||||
ChannelDef active_;
|
||||
EvidenceStore store_;
|
||||
ActiveLinkTrack track_;
|
||||
bool scout_healthy_ = true;
|
||||
int64_t last_recommend_ms_ = INT64_MIN;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_CHANNEL_SCORE_H */
|
||||
@@ -0,0 +1,295 @@
|
||||
/* EvidenceStore — the rolling per-candidate evidence the scoring engine
|
||||
* decides from, fed by SurveyDwell records (live from the dwell executor, or
|
||||
* replayed from JSONL).
|
||||
*
|
||||
* Structure follows the physics: evidence is stored per 20 MHz BIN (a dwell
|
||||
* observes one bin; two candidates sharing a bin share its evidence), and a
|
||||
* candidate's occupancy derives from its constituent bins at decision time
|
||||
* with worst-bin gating — a wide channel is only clean if every bin is clean.
|
||||
*
|
||||
* The fold path is the trust boundary. A record is folded only when it
|
||||
* carries the same plan hash (same immutable candidate set), the same scout
|
||||
* identity (raw energy units are only comparable within one adapter — a
|
||||
* record from a different scout resets the store rather than silently mixing
|
||||
* calibration domains), no failure flags, a plausible counter delta for its
|
||||
* observation window (a hardware counter wrap or mid-read reset shows up as
|
||||
* an absurd rate — better to drop one dwell than to poison a ranking), and
|
||||
* an age inside the freshness bound. Every rejection is counted by reason so
|
||||
* a health layer can tell "quiet" from "being fed garbage".
|
||||
*
|
||||
* Pure: no clocks (caller passes now), no I/O, no env. Selftested. */
|
||||
#ifndef DEVOURER_CHANMIG_EVIDENCE_STORE_H
|
||||
#define DEVOURER_CHANMIG_EVIDENCE_STORE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
#include "chanmig/SurveyRecord.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
/* One accepted dwell, reduced to the rate/fraction form scoring consumes.
|
||||
* Rates are per-second of valid observation. nhm_busy_pct 255 = absent. */
|
||||
struct BinCell {
|
||||
int64_t t_ms = 0; /* record time (dwell end, producer's monotonic clock) */
|
||||
int64_t observe_ms = 0;
|
||||
double cca_rate = 0.0;
|
||||
double fa_rate = 0.0;
|
||||
uint8_t nhm_busy_pct = 255;
|
||||
double dvr_air_frac = 0.0; /* recognized own-video airtime / observe */
|
||||
double oth_air_frac = 0.0; /* other decoded airtime / observe */
|
||||
uint32_t frames = 0;
|
||||
uint64_t round = 0;
|
||||
};
|
||||
|
||||
class EvidenceStore {
|
||||
public:
|
||||
enum class Fold {
|
||||
Accepted,
|
||||
RejectedFlags, /* dwell aborted / truncated / read failed */
|
||||
RejectedSuspect, /* counter delta implausible for the window */
|
||||
RejectedStale, /* record older than max_age at ingest */
|
||||
RejectedUnknownBin, /* bin serves no configured candidate */
|
||||
RejectedMixedScout, /* different scout_id — store reset */
|
||||
RejectedPlanMismatch, /* produced under a different plan hash */
|
||||
};
|
||||
static constexpr int kFoldReasons = 7;
|
||||
|
||||
EvidenceStore(std::vector<ChannelDef> candidates, uint32_t plan_hash,
|
||||
int64_t max_age_ms, size_t ring_cap = 32)
|
||||
: plan_hash_(plan_hash), max_age_ms_(max_age_ms), ring_cap_(ring_cap) {
|
||||
for (const ChannelDef &c : candidates) {
|
||||
Cand cd;
|
||||
cd.def = c;
|
||||
cd.n_bins = constituent_bins(c, cd.bins);
|
||||
cands_.push_back(cd);
|
||||
for (int i = 0; i < cd.n_bins; i++)
|
||||
if (find_bin(cd.bins[i]) == nullptr)
|
||||
bins_.push_back(BinRing{cd.bins[i], {}});
|
||||
}
|
||||
}
|
||||
|
||||
/* Counter-plausibility ceiling: no chip emits more than ~1000 CCA or FA
|
||||
* events per millisecond of observation; a wrapped/reset hardware counter
|
||||
* reads orders of magnitude above it. */
|
||||
static constexpr uint64_t kMaxCountsPerMs = 1000;
|
||||
|
||||
Fold ingest(const SurveyDwell &d, int64_t now_ms) {
|
||||
if (d.plan_hash != plan_hash_)
|
||||
return count(Fold::RejectedPlanMismatch);
|
||||
if (d.flags & (kFlagRetuneFailed | kFlagReadFailed | kFlagTruncated))
|
||||
return count(Fold::RejectedFlags);
|
||||
if (scout_id_ != 0 && d.scout_id != scout_id_) {
|
||||
/* Calibration domain changed: raw units are no longer comparable with
|
||||
* what the rings hold. Reset rather than mix. */
|
||||
for (BinRing &b : bins_)
|
||||
b.cells.clear();
|
||||
scout_id_ = d.scout_id;
|
||||
return count(Fold::RejectedMixedScout);
|
||||
}
|
||||
if (scout_id_ == 0)
|
||||
scout_id_ = d.scout_id;
|
||||
if (now_ms - d.t_end_ms > max_age_ms_)
|
||||
return count(Fold::RejectedStale);
|
||||
if (d.flags & kFlagCounterSuspect)
|
||||
return count(Fold::RejectedSuspect);
|
||||
if (d.valid_fa) {
|
||||
const uint64_t ceiling =
|
||||
kMaxCountsPerMs * static_cast<uint64_t>(
|
||||
d.observe_ms > 0 ? d.observe_ms : 1);
|
||||
if (d.cca_ofdm > ceiling || d.fa_ofdm > ceiling ||
|
||||
d.cca_cck > ceiling || d.fa_cck > ceiling)
|
||||
return count(Fold::RejectedSuspect);
|
||||
}
|
||||
if (d.observe_ms <= 0)
|
||||
return count(Fold::RejectedFlags);
|
||||
|
||||
if (d.flags & kFlagFullWidth) {
|
||||
Cand *c = find_cand(d.def);
|
||||
if (c == nullptr)
|
||||
return count(Fold::RejectedUnknownBin);
|
||||
push_cell(c->wide, d);
|
||||
bump();
|
||||
return count(Fold::Accepted);
|
||||
}
|
||||
BinRing *b = find_bin(d.def.primary);
|
||||
if (b == nullptr)
|
||||
return count(Fold::RejectedUnknownBin);
|
||||
push_cell(b->cells, d);
|
||||
bump();
|
||||
return count(Fold::Accepted);
|
||||
}
|
||||
|
||||
/* Evidence generation: increments on every accepted fold. Decisions cite
|
||||
* the generation they were computed at, making any output reproducible
|
||||
* from the record stream. */
|
||||
uint64_t generation() const { return gen_; }
|
||||
uint32_t scout_id() const { return scout_id_; }
|
||||
uint32_t fold_count(Fold f) const {
|
||||
return fold_counts_[static_cast<int>(f)];
|
||||
}
|
||||
|
||||
size_t candidate_count() const { return cands_.size(); }
|
||||
const ChannelDef &candidate(size_t i) const { return cands_[i].def; }
|
||||
|
||||
/* Coverage: how many of the candidate's constituent bins hold at least one
|
||||
* fresh cell (age <= max_age at `now`). A wide candidate with partial
|
||||
* coverage must never rank — the missing bin could hide the interferer. */
|
||||
int bins_covered(size_t cand, int64_t now_ms) const {
|
||||
const Cand &c = cands_[cand];
|
||||
int n = 0;
|
||||
for (int i = 0; i < c.n_bins; i++) {
|
||||
const BinRing *b = find_bin_const(c.bins[i]);
|
||||
if (b && newest_fresh(*b, now_ms) != nullptr)
|
||||
++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
int bin_count(size_t cand) const { return cands_[cand].n_bins; }
|
||||
|
||||
/* Age of the candidate's OLDEST freshest-per-bin cell — the evidence age a
|
||||
* decision must cite (the least-recently-observed constituent bin bounds
|
||||
* how much can have changed unseen). -1 when any bin has no fresh cell. */
|
||||
int64_t evidence_age_ms(size_t cand, int64_t now_ms) const {
|
||||
const Cand &c = cands_[cand];
|
||||
int64_t worst = -1;
|
||||
for (int i = 0; i < c.n_bins; i++) {
|
||||
const BinRing *b = find_bin_const(c.bins[i]);
|
||||
const BinCell *cell = b ? newest_fresh(*b, now_ms) : nullptr;
|
||||
if (cell == nullptr)
|
||||
return -1;
|
||||
const int64_t age = now_ms - cell->t_ms;
|
||||
if (age > worst)
|
||||
worst = age;
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
/* All fresh cells of one constituent bin (newest last), for the scoring
|
||||
* layer's quantile/burstiness derivations. */
|
||||
void fresh_cells(uint8_t bin_ch, int64_t now_ms,
|
||||
std::vector<const BinCell *> &out) const {
|
||||
out.clear();
|
||||
const BinRing *b = find_bin_const(bin_ch);
|
||||
if (b == nullptr)
|
||||
return;
|
||||
for (const BinCell &cell : b->cells)
|
||||
if (now_ms - cell.t_ms <= max_age_ms_)
|
||||
out.push_back(&cell);
|
||||
}
|
||||
void wide_cells(size_t cand, int64_t now_ms,
|
||||
std::vector<const BinCell *> &out) const {
|
||||
out.clear();
|
||||
for (const BinCell &cell : cands_[cand].wide)
|
||||
if (now_ms - cell.t_ms <= max_age_ms_)
|
||||
out.push_back(&cell);
|
||||
}
|
||||
|
||||
/* Distinct sweep rounds represented in the candidate's fresh evidence —
|
||||
* the min-rounds gate input (a single lucky round is not persistence). */
|
||||
uint64_t rounds_covered(size_t cand, int64_t now_ms) const {
|
||||
const Cand &c = cands_[cand];
|
||||
uint64_t lo = UINT64_MAX, hi = 0;
|
||||
bool any = false;
|
||||
for (int i = 0; i < c.n_bins; i++) {
|
||||
const BinRing *b = find_bin_const(c.bins[i]);
|
||||
if (b == nullptr)
|
||||
continue;
|
||||
for (const BinCell &cell : b->cells) {
|
||||
if (now_ms - cell.t_ms > max_age_ms_)
|
||||
continue;
|
||||
any = true;
|
||||
if (cell.round < lo)
|
||||
lo = cell.round;
|
||||
if (cell.round > hi)
|
||||
hi = cell.round;
|
||||
}
|
||||
}
|
||||
return any ? hi - lo + 1 : 0;
|
||||
}
|
||||
|
||||
int64_t max_age_ms() const { return max_age_ms_; }
|
||||
|
||||
private:
|
||||
struct BinRing {
|
||||
uint8_t ch;
|
||||
std::vector<BinCell> cells; /* bounded ring, newest last */
|
||||
};
|
||||
struct Cand {
|
||||
ChannelDef def;
|
||||
uint8_t bins[4] = {};
|
||||
int n_bins = 0;
|
||||
std::vector<BinCell> wide; /* full-width verification dwells */
|
||||
};
|
||||
|
||||
BinRing *find_bin(uint8_t ch) {
|
||||
for (BinRing &b : bins_)
|
||||
if (b.ch == ch)
|
||||
return &b;
|
||||
return nullptr;
|
||||
}
|
||||
const BinRing *find_bin_const(uint8_t ch) const {
|
||||
for (const BinRing &b : bins_)
|
||||
if (b.ch == ch)
|
||||
return &b;
|
||||
return nullptr;
|
||||
}
|
||||
Cand *find_cand(const ChannelDef &d) {
|
||||
for (Cand &c : cands_)
|
||||
if (c.def.same_rf(d))
|
||||
return &c;
|
||||
return nullptr;
|
||||
}
|
||||
const BinCell *newest_fresh(const BinRing &b, int64_t now_ms) const {
|
||||
for (auto it = b.cells.rbegin(); it != b.cells.rend(); ++it)
|
||||
if (now_ms - it->t_ms <= max_age_ms_)
|
||||
return &*it;
|
||||
return nullptr;
|
||||
}
|
||||
void push_cell(std::vector<BinCell> &ring, const SurveyDwell &d) {
|
||||
BinCell cell;
|
||||
cell.t_ms = d.t_end_ms;
|
||||
cell.observe_ms = d.observe_ms;
|
||||
const double sec = static_cast<double>(d.observe_ms) / 1000.0;
|
||||
if (d.valid_fa && sec > 0) {
|
||||
cell.cca_rate = (d.cca_ofdm + d.cca_cck) / sec;
|
||||
cell.fa_rate = (d.fa_ofdm + d.fa_cck) / sec;
|
||||
}
|
||||
cell.nhm_busy_pct = d.valid_nhm ? d.nhm_busy_pct : 255;
|
||||
if (d.observe_ms > 0) {
|
||||
const double us = static_cast<double>(d.observe_ms) * 1000.0;
|
||||
cell.dvr_air_frac = static_cast<double>(d.dvr_air_us) / us;
|
||||
cell.oth_air_frac = static_cast<double>(d.oth_air_us) / us;
|
||||
if (cell.dvr_air_frac > 1.0)
|
||||
cell.dvr_air_frac = 1.0;
|
||||
if (cell.oth_air_frac > 1.0)
|
||||
cell.oth_air_frac = 1.0;
|
||||
}
|
||||
cell.frames = d.frames;
|
||||
cell.round = d.round;
|
||||
if (ring.size() >= ring_cap_)
|
||||
ring.erase(ring.begin());
|
||||
ring.push_back(cell);
|
||||
}
|
||||
Fold count(Fold f) {
|
||||
++fold_counts_[static_cast<int>(f)];
|
||||
return f;
|
||||
}
|
||||
void bump() { ++gen_; }
|
||||
|
||||
uint32_t plan_hash_;
|
||||
int64_t max_age_ms_;
|
||||
size_t ring_cap_;
|
||||
uint32_t scout_id_ = 0;
|
||||
uint64_t gen_ = 0;
|
||||
std::vector<Cand> cands_;
|
||||
std::vector<BinRing> bins_;
|
||||
uint32_t fold_counts_[kFoldReasons] = {};
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_EVIDENCE_STORE_H */
|
||||
@@ -0,0 +1,191 @@
|
||||
/* JsonlLite — minimal field extraction from devourer machine-event lines.
|
||||
*
|
||||
* Devourer events are FLAT JSON objects, one per line, first field always
|
||||
* "ev" (src/Event.h contract). Consumers inside the chanmig stack (the scout
|
||||
* tail-following the primary receiver's JSONL, the replay tools) need a
|
||||
* handful of typed lookups, not a JSON library: this is a single-pass scanner
|
||||
* that tracks string state (so a "text" value containing '"key":' can never
|
||||
* false-match), understands the exact value shapes Ev emits — numbers,
|
||||
* strings with its escape set, true/false/null, flat arrays of numbers — and
|
||||
* nothing else. Non-event lines (stderr noise, partial writes) simply fail
|
||||
* every lookup. Pure, header-only, selftested. */
|
||||
#ifndef DEVOURER_CHANMIG_JSONL_LITE_H
|
||||
#define DEVOURER_CHANMIG_JSONL_LITE_H
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
namespace jsonl_detail {
|
||||
/* Locate the raw value span of "key": in a flat object. Returns false when
|
||||
* the key is absent (or only occurs inside a string value). */
|
||||
inline bool find_value(std::string_view line, std::string_view key,
|
||||
size_t &vbegin, size_t &vend) {
|
||||
size_t i = 0;
|
||||
const size_t n = line.size();
|
||||
while (i < n) {
|
||||
const char c = line[i];
|
||||
if (c == '"') {
|
||||
/* A string at top level is either a key (followed by ':') or a string
|
||||
* value. Scan it with escapes. */
|
||||
const size_t sbegin = i + 1;
|
||||
size_t j = sbegin;
|
||||
while (j < n && line[j] != '"') {
|
||||
if (line[j] == '\\')
|
||||
++j;
|
||||
++j;
|
||||
}
|
||||
if (j >= n)
|
||||
return false; /* unterminated — not a complete event line */
|
||||
const size_t send = j; /* exclusive */
|
||||
i = j + 1;
|
||||
/* key? */
|
||||
if (i < n && line[i] == ':') {
|
||||
++i;
|
||||
if (line.substr(sbegin, send - sbegin) == key) {
|
||||
vbegin = i;
|
||||
/* value runs to the matching top-level ',' or '}'. Strings and
|
||||
* arrays are skipped structurally; nested objects don't occur in
|
||||
* this schema but are skipped defensively. */
|
||||
int depth = 0;
|
||||
size_t k = i;
|
||||
while (k < n) {
|
||||
const char v = line[k];
|
||||
if (v == '"') {
|
||||
++k;
|
||||
while (k < n && line[k] != '"') {
|
||||
if (line[k] == '\\')
|
||||
++k;
|
||||
++k;
|
||||
}
|
||||
if (k >= n)
|
||||
return false;
|
||||
} else if (v == '[' || v == '{') {
|
||||
++depth;
|
||||
} else if (v == ']' || v == '}') {
|
||||
if (depth == 0)
|
||||
break;
|
||||
--depth;
|
||||
} else if (v == ',' && depth == 0) {
|
||||
break;
|
||||
}
|
||||
++k;
|
||||
}
|
||||
vend = k;
|
||||
return vend > vbegin;
|
||||
}
|
||||
/* not our key: fall through, the value scanner below advances */
|
||||
}
|
||||
continue;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} /* namespace jsonl_detail */
|
||||
|
||||
/* True when the line is an event line named `name` (first-field contract:
|
||||
* the line starts with {"ev":"<name>"). */
|
||||
inline bool jsonl_ev_is(std::string_view line, std::string_view name) {
|
||||
static const char prefix[] = "{\"ev\":\"";
|
||||
if (line.size() < sizeof(prefix) - 1 + name.size() + 1)
|
||||
return false;
|
||||
if (line.compare(0, sizeof(prefix) - 1, prefix) != 0)
|
||||
return false;
|
||||
if (line.compare(sizeof(prefix) - 1, name.size(), name) != 0)
|
||||
return false;
|
||||
return line[sizeof(prefix) - 1 + name.size()] == '"';
|
||||
}
|
||||
|
||||
/* Number lookup. false when absent, null, or not a number. */
|
||||
inline bool jsonl_num(std::string_view line, std::string_view key,
|
||||
double *out) {
|
||||
size_t b, e;
|
||||
if (!jsonl_detail::find_value(line, key, b, e))
|
||||
return false;
|
||||
const std::string v(line.substr(b, e - b));
|
||||
if (v == "null" || v.empty() || v[0] == '"' || v[0] == '[')
|
||||
return false;
|
||||
char *end = nullptr;
|
||||
const double d = std::strtod(v.c_str(), &end);
|
||||
if (end == v.c_str())
|
||||
return false;
|
||||
*out = d;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool jsonl_int(std::string_view line, std::string_view key,
|
||||
long long *out) {
|
||||
double d;
|
||||
if (!jsonl_num(line, key, &d))
|
||||
return false;
|
||||
*out = static_cast<long long>(d);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* String lookup with the Ev escape set unescaped (\" \\ \n \t \r; \uXXXX
|
||||
* folds to '?' — the schema only emits it for control bytes). */
|
||||
inline bool jsonl_str(std::string_view line, std::string_view key,
|
||||
std::string *out) {
|
||||
size_t b, e;
|
||||
if (!jsonl_detail::find_value(line, key, b, e))
|
||||
return false;
|
||||
if (e - b < 2 || line[b] != '"' || line[e - 1] != '"')
|
||||
return false;
|
||||
out->clear();
|
||||
for (size_t i = b + 1; i < e - 1; ++i) {
|
||||
char c = line[i];
|
||||
if (c == '\\' && i + 1 < e - 1) {
|
||||
const char x = line[++i];
|
||||
switch (x) {
|
||||
case 'n': c = '\n'; break;
|
||||
case 't': c = '\t'; break;
|
||||
case 'r': c = '\r'; break;
|
||||
case 'u':
|
||||
i += 4 < e - 1 - i ? 4 : e - 2 - i;
|
||||
c = '?';
|
||||
break;
|
||||
default: c = x; break;
|
||||
}
|
||||
}
|
||||
out->push_back(c);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Flat numeric array lookup: fills out[0..max) and sets *n to the element
|
||||
* count found (clamped to max). false when absent or not an array. */
|
||||
inline bool jsonl_arr(std::string_view line, std::string_view key, int *out,
|
||||
int max, int *n) {
|
||||
size_t b, e;
|
||||
if (!jsonl_detail::find_value(line, key, b, e))
|
||||
return false;
|
||||
if (line[b] != '[')
|
||||
return false;
|
||||
int count = 0;
|
||||
size_t i = b + 1;
|
||||
while (i < e && count < max) {
|
||||
while (i < e && (line[i] == ',' || line[i] == ' '))
|
||||
++i;
|
||||
if (i >= e || line[i] == ']')
|
||||
break;
|
||||
const std::string v(line.substr(i, e - i));
|
||||
char *end = nullptr;
|
||||
const long val = std::strtol(v.c_str(), &end, 10);
|
||||
if (end == v.c_str())
|
||||
break;
|
||||
out[count++] = static_cast<int>(val);
|
||||
i += static_cast<size_t>(end - v.c_str());
|
||||
}
|
||||
*n = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_JSONL_LITE_H */
|
||||
@@ -0,0 +1,92 @@
|
||||
/* MigClock — the ground side's estimate of the drone's activation instant,
|
||||
* and the guard time around it.
|
||||
*
|
||||
* The drone stamps its hardware TSF (tx_tsf) into every commit/status; the
|
||||
* ground feeds (tx_tsf, local RX tsfl) pairs into the existing TsfSync fit.
|
||||
* Because tx_tsf is software-stamped (not a beacon's hardware egress), the fit
|
||||
* residual carries the host->air latency — floor tens of µs but a CSMA tail in
|
||||
* the low ms. PeerClock wraps TsfSync with a ring of recent residuals so the
|
||||
* guard is derived from the MEASURED p99, never a fixed guess.
|
||||
*
|
||||
* Scheduling itself does not need the fit: the machines schedule activation
|
||||
* from the RELATIVE offset (activate_tsf - commit.tx_tsf), whose error is one
|
||||
* frame's one-way latency, absorbed by the lead + verify window. The fit only
|
||||
* tightens the guard and is the health readout. Pure, header-only. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_CLOCK_H
|
||||
#define DEVOURER_CHANMIG_MIG_CLOCK_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "TsfSync.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
class PeerClock {
|
||||
public:
|
||||
/* Feed one (drone tx_tsf, local RX tsfl) pair. */
|
||||
void add(uint64_t remote_tsf, uint32_t local_tsfl) {
|
||||
if (sync_.Ready()) {
|
||||
const int64_t predicted = sync_.LocalForRemote(remote_tsf);
|
||||
/* the reconstructed local time of this sample */
|
||||
const int64_t observed = recon_local(local_tsfl);
|
||||
int64_t resid = observed - predicted;
|
||||
if (resid < 0)
|
||||
resid = -resid;
|
||||
if (ring_.size() >= kRing)
|
||||
ring_.erase(ring_.begin());
|
||||
ring_.push_back(resid);
|
||||
} else {
|
||||
(void)recon_local(local_tsfl); /* keep the local wrap tracker warm */
|
||||
}
|
||||
sync_.Add(remote_tsf, local_tsfl);
|
||||
}
|
||||
|
||||
bool ready() const { return sync_.Ready() && ring_.size() >= 8; }
|
||||
double skew_ppm() const { return sync_.SkewPpm(); }
|
||||
int64_t offset_us() const { return sync_.OffsetUs(); }
|
||||
long long samples() const { return sync_.Count(); }
|
||||
|
||||
int64_t residual_p50() const { return percentile(0.50); }
|
||||
int64_t residual_p99() const { return percentile(0.99); }
|
||||
|
||||
/* The activation guard (µs): the measured fit residual p99, plus the TX
|
||||
* drain p99.9 and the worst retune the demo passes in, plus a margin. All
|
||||
* measured, none guessed. Falls back to a floor when the fit isn't ready. */
|
||||
int64_t guard_us(int64_t drain_p999_us, int64_t retune_worst_us,
|
||||
int64_t margin_us = 2000) const {
|
||||
const int64_t resid = ready() ? residual_p99() : 3000;
|
||||
return resid + drain_p999_us + retune_worst_us + margin_us;
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr size_t kRing = 64;
|
||||
int64_t recon_local(uint32_t lo) {
|
||||
if (linit_ && lo < plo_)
|
||||
hi_ += (1LL << 32);
|
||||
plo_ = lo;
|
||||
linit_ = true;
|
||||
return hi_ + lo;
|
||||
}
|
||||
int64_t percentile(double q) const {
|
||||
if (ring_.empty())
|
||||
return 0;
|
||||
std::vector<int64_t> v = ring_;
|
||||
std::sort(v.begin(), v.end());
|
||||
size_t idx = static_cast<size_t>(q * (v.size() - 1));
|
||||
return v[idx];
|
||||
}
|
||||
|
||||
TsfSync sync_;
|
||||
std::vector<int64_t> ring_;
|
||||
int64_t hi_ = 0;
|
||||
uint32_t plo_ = 0;
|
||||
bool linit_ = false;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_CLOCK_H */
|
||||
@@ -0,0 +1,152 @@
|
||||
/* MigConfig — timer/bound parameters for the migration state machines, plus
|
||||
* the pure string parsers the demo uses to map env → config (the library
|
||||
* reads no env; the demo does, matching the rest of devourer).
|
||||
*
|
||||
* The defaults are conservative starting points; the on-air clock bench
|
||||
* (tests/chanmig_clock_bench.sh) measures the real guard and the demo may
|
||||
* raise lead_ms from it. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_CONFIG_H
|
||||
#define DEVOURER_CHANMIG_MIG_CONFIG_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
struct MigParams {
|
||||
/* proposal (ground) */
|
||||
int64_t proposal_interval_ms = 200;
|
||||
int proposal_max_tries = 25;
|
||||
/* commit (drone) + status ack (ground) */
|
||||
int64_t commit_interval_ms = 100;
|
||||
int64_t status_interval_ms = 500; /* 2 Hz drone status */
|
||||
int64_t ack_timeout_ms = 2000; /* drone: no ground ack -> abort */
|
||||
/* activation */
|
||||
int64_t countdown_ms = 500; /* drone: activation lead it picks */
|
||||
int64_t lead_ms = 40; /* ground: retune this early (from clock) */
|
||||
int64_t min_lead_ms = 50; /* activation bounds (drone TSF) */
|
||||
int64_t max_horizon_ms = 5000;
|
||||
int64_t drain_deadline_ms = 20;
|
||||
int64_t blank_window_ms = 5; /* ground: drop stale post-retune frames */
|
||||
/* verify (ground) */
|
||||
int64_t verify_ms = 3000;
|
||||
int verify_markers = 3;
|
||||
int verify_video = 10;
|
||||
/* rollback / recovery */
|
||||
int64_t rollback_ms = 5000; /* drone: rollback if unconfirmed by */
|
||||
int64_t recovery_dwell_ms = 500; /* ground: per-channel scan dwell */
|
||||
int64_t recovery_giveup_ms = 60000;
|
||||
int64_t proposal_hold_down_ms = 10000; /* drone: after a rollback */
|
||||
};
|
||||
|
||||
/* Parse a channel spec token, "5:104/40l" or "104/40u" or "36/80" — reuses the
|
||||
* ChannelDef grammar (parse_chan_token). Returns false + fills err on a bad
|
||||
* token. */
|
||||
inline bool parse_mig_chanspec(const std::string &tok, ChannelDef &out,
|
||||
std::string &err) {
|
||||
return parse_chan_token(tok, out, err);
|
||||
}
|
||||
|
||||
/* Parse a comma-separated allowed-channel list. Malformed tokens are reported
|
||||
* in errs; the caller decides whether to run. */
|
||||
inline bool parse_mig_allowed(const char *text, std::vector<ChannelDef> &out,
|
||||
std::vector<PlanParseError> &errs) {
|
||||
out.clear();
|
||||
errs.clear();
|
||||
if (text == nullptr || *text == '\0')
|
||||
return false;
|
||||
const std::string s = text;
|
||||
size_t pos = 0;
|
||||
while (pos <= s.size()) {
|
||||
const size_t comma = s.find(',', pos);
|
||||
const std::string tok = s.substr(
|
||||
pos, comma == std::string::npos ? std::string::npos : comma - pos);
|
||||
pos = (comma == std::string::npos) ? s.size() + 1 : comma + 1;
|
||||
if (tok.empty())
|
||||
continue;
|
||||
ChannelDef d;
|
||||
std::string err;
|
||||
if (parse_chan_token(tok, d, err))
|
||||
out.push_back(d);
|
||||
else
|
||||
errs.push_back({tok, err});
|
||||
}
|
||||
return errs.empty() && !out.empty();
|
||||
}
|
||||
|
||||
/* Fault-injection drop spec (demo-side, deterministic): "type:spec[,...]",
|
||||
* spec = N | N-M | * | every:K. Parsed into a per-type matcher the demo's
|
||||
* send/receive seam consults. Kept here so the grammar has one definition
|
||||
* shared by the on-air scripts' documentation and the code. */
|
||||
struct DropRule {
|
||||
uint8_t type = 0; /* MigMsgType, 0 = any */
|
||||
int lo = -1, hi = -1; /* index range, -1 = unset */
|
||||
int every = 0; /* every:K, 0 = off */
|
||||
bool all = false; /* '*' */
|
||||
};
|
||||
|
||||
inline bool parse_drop_spec(const char *text, std::vector<DropRule> &out) {
|
||||
out.clear();
|
||||
if (text == nullptr || *text == '\0')
|
||||
return true;
|
||||
const std::string s = text;
|
||||
size_t pos = 0;
|
||||
while (pos <= s.size()) {
|
||||
const size_t comma = s.find(',', pos);
|
||||
std::string tok = s.substr(
|
||||
pos, comma == std::string::npos ? std::string::npos : comma - pos);
|
||||
pos = (comma == std::string::npos) ? s.size() + 1 : comma + 1;
|
||||
if (tok.empty())
|
||||
continue;
|
||||
DropRule r;
|
||||
const size_t colon = tok.find(':');
|
||||
std::string tstr = tok.substr(0, colon);
|
||||
r.type = static_cast<uint8_t>(std::strtoul(tstr.c_str(), nullptr, 0));
|
||||
if (colon == std::string::npos) {
|
||||
out.push_back(r);
|
||||
continue;
|
||||
}
|
||||
std::string spec = tok.substr(colon + 1);
|
||||
if (spec == "*") {
|
||||
r.all = true;
|
||||
} else if (spec.rfind("every:", 0) == 0) {
|
||||
r.every = std::atoi(spec.c_str() + 6);
|
||||
} else {
|
||||
const size_t dash = spec.find('-');
|
||||
if (dash == std::string::npos) {
|
||||
r.lo = r.hi = std::atoi(spec.c_str());
|
||||
} else {
|
||||
r.lo = std::atoi(spec.substr(0, dash).c_str());
|
||||
r.hi = std::atoi(spec.substr(dash + 1).c_str());
|
||||
}
|
||||
}
|
||||
out.push_back(r);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Should the index-th message of `type` be dropped under these rules? */
|
||||
inline bool drop_matches(const std::vector<DropRule> &rules, uint8_t type,
|
||||
int index) {
|
||||
for (const DropRule &r : rules) {
|
||||
if (r.type != 0 && r.type != type)
|
||||
continue;
|
||||
if (r.all)
|
||||
return true;
|
||||
if (r.every > 0 && index % r.every == 0)
|
||||
return true;
|
||||
if (r.lo >= 0 && index >= r.lo && index <= r.hi)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_CONFIG_H */
|
||||
@@ -0,0 +1,199 @@
|
||||
#include "chanmig/MigGate.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
const char *gate_reason_name(GateReason r) {
|
||||
switch (r) {
|
||||
case GateReason::ModeOff: return "MODE_OFF";
|
||||
case GateReason::Advisory: return "ADVISORY";
|
||||
case GateReason::NotImpaired: return "NOT_IMPAIRED";
|
||||
case GateReason::FaultWeakLink: return "FAULT_WEAK_LINK";
|
||||
case GateReason::FaultBroadband: return "FAULT_BROADBAND";
|
||||
case GateReason::FaultSaturation: return "FAULT_SATURATION";
|
||||
case GateReason::FaultScout: return "FAULT_SCOUT";
|
||||
case GateReason::FaultUsb: return "FAULT_USB";
|
||||
case GateReason::TelemetryUnhealthy: return "TELEMETRY_UNHEALTHY";
|
||||
case GateReason::ClockUnsynced: return "CLOCK_UNSYNCED";
|
||||
case GateReason::ScoutStale: return "SCOUT_STALE";
|
||||
case GateReason::EvidenceStale: return "EVIDENCE_STALE";
|
||||
case GateReason::EvidenceIncomplete: return "EVIDENCE_INCOMPLETE";
|
||||
case GateReason::Illegal: return "ILLEGAL";
|
||||
case GateReason::MarginLow: return "MARGIN_LOW";
|
||||
case GateReason::ConfidenceLow: return "CONFIDENCE_LOW";
|
||||
case GateReason::Cooldown: return "COOLDOWN";
|
||||
case GateReason::MoveCap: return "MOVE_CAP";
|
||||
case GateReason::Residency: return "RESIDENCY";
|
||||
case GateReason::HolddownChannel: return "HOLDDOWN_CHANNEL";
|
||||
case GateReason::Backoff: return "BACKOFF";
|
||||
case GateReason::InFlight: return "IN_FLIGHT";
|
||||
case GateReason::Pinned: return "PINNED";
|
||||
case GateReason::Inhibited: return "INHIBITED";
|
||||
case GateReason::ApproveRequired: return "APPROVE_REQUIRED";
|
||||
case GateReason::ControlMarginLow: return "CONTROL_MARGIN_LOW";
|
||||
case GateReason::NoRescueVerified: return "NO_RESCUE_VERIFIED";
|
||||
case GateReason::ProbationActive: return "PROBATION_ACTIVE";
|
||||
case GateReason::ProbationRollback: return "PROBATION_ROLLBACK";
|
||||
case GateReason::MaterialChange: return "MATERIAL_CHANGE";
|
||||
case GateReason::Propose: return "PROPOSE";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
static GateOutcome hold(GateReason r) {
|
||||
GateOutcome o;
|
||||
o.verdict = GateVerdict::Hold;
|
||||
o.reason = r;
|
||||
return o;
|
||||
}
|
||||
|
||||
GateOutcome mig_gate_decide(const GateInputs &in, GateState &st,
|
||||
const GatePolicy &pol, int64_t now_ms) {
|
||||
/* --- operator overrides + mode (highest precedence) --- */
|
||||
if (in.mode == MigMode::Off)
|
||||
return hold(GateReason::ModeOff);
|
||||
if (in.pinned != nullptr)
|
||||
return hold(GateReason::Pinned);
|
||||
if (in.inhibit_until_ms != INT64_MIN && now_ms < in.inhibit_until_ms)
|
||||
return hold(GateReason::Inhibited);
|
||||
|
||||
/* --- probation: destination must prove itself, else roll back --- */
|
||||
if (in.probation_active) {
|
||||
if (!in.probation_delivery_ok) {
|
||||
GateOutcome o;
|
||||
o.verdict = GateVerdict::ProposeRollback;
|
||||
o.reason = GateReason::ProbationRollback;
|
||||
return o;
|
||||
}
|
||||
return hold(GateReason::ProbationActive);
|
||||
}
|
||||
|
||||
/* --- an in-flight migration: only abort on a material evidence change --- */
|
||||
if (in.in_flight) {
|
||||
if (st.have_frozen && in.rec != nullptr &&
|
||||
in.rec->kind == Decision::Kind::Recommend) {
|
||||
const bool target_moved = !in.rec->target.same_rf(st.frozen_target);
|
||||
double best = 0.0;
|
||||
for (const CandidateScore &c : in.rec->ranking)
|
||||
if (c.def.same_rf(st.frozen_target)) {
|
||||
best = c.score;
|
||||
break;
|
||||
}
|
||||
const bool score_dropped =
|
||||
best < st.frozen_score - pol.material_change_frac * 0.1;
|
||||
if (target_moved || score_dropped) {
|
||||
GateOutcome o;
|
||||
o.verdict = GateVerdict::AbortInFlight;
|
||||
o.reason = GateReason::MaterialChange;
|
||||
return o;
|
||||
}
|
||||
}
|
||||
return hold(GateReason::InFlight);
|
||||
}
|
||||
|
||||
/* Advisory mode never proposes (but still reports the counterfactual). */
|
||||
if (in.mode == MigMode::Advisory)
|
||||
return hold(GateReason::Advisory);
|
||||
|
||||
/* --- health / fault domains --- */
|
||||
if (!in.telemetry_ok)
|
||||
return hold(GateReason::TelemetryUnhealthy);
|
||||
if (!in.clock_synced)
|
||||
return hold(GateReason::ClockUnsynced);
|
||||
if (!in.usb_ok)
|
||||
return hold(GateReason::FaultUsb);
|
||||
if (!in.scout_healthy)
|
||||
return hold(GateReason::FaultScout);
|
||||
if (in.scout_survey_age_ms > in.scout_max_age_ms)
|
||||
return hold(GateReason::ScoutStale);
|
||||
|
||||
/* --- the advisory recommendation must itself be a Recommend --- */
|
||||
if (in.rec == nullptr)
|
||||
return hold(GateReason::NotImpaired);
|
||||
if (in.rec->kind != Decision::Kind::Recommend)
|
||||
return hold(gate_reason_for_hold(in.rec->primary_reason));
|
||||
|
||||
/* find the recommended target's score/confidence in the ranking */
|
||||
double conf = 0.0;
|
||||
bool found = false;
|
||||
for (const CandidateScore &c : in.rec->ranking)
|
||||
if (c.def.same_rf(in.rec->target)) {
|
||||
conf = c.confidence;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if (!found)
|
||||
return hold(GateReason::EvidenceIncomplete);
|
||||
if (conf < pol.confidence_min)
|
||||
return hold(GateReason::ConfidenceLow);
|
||||
|
||||
/* --- anti-oscillation gates --- */
|
||||
if (st.last_move_ms != INT64_MIN && now_ms - st.last_move_ms < pol.cooldown_ms)
|
||||
return hold(GateReason::Cooldown);
|
||||
if (st.residency_start_ms != INT64_MIN &&
|
||||
now_ms - st.residency_start_ms < pol.residency_ms)
|
||||
return hold(GateReason::Residency);
|
||||
if (st.moves_session >= pol.move_cap)
|
||||
return hold(GateReason::MoveCap);
|
||||
const int64_t hd = st.holddown_for(in.rec->target.key());
|
||||
if (hd != INT64_MIN && now_ms < hd)
|
||||
return hold(GateReason::HolddownChannel);
|
||||
|
||||
/* --- can we actually complete the move? --- */
|
||||
if (in.control_link_margin < pol.control_margin_min)
|
||||
return hold(GateReason::ControlMarginLow);
|
||||
if (!in.rescue_verified)
|
||||
return hold(GateReason::NoRescueVerified);
|
||||
|
||||
/* --- manual mode requires an explicit one-shot approval --- */
|
||||
if (in.mode == MigMode::Manual && !in.approve_next)
|
||||
return hold(GateReason::ApproveRequired);
|
||||
|
||||
/* all gates passed — propose, and freeze the evidence for the
|
||||
* material-change abort test. */
|
||||
st.have_frozen = true;
|
||||
st.frozen_gen = in.rec->evidence_gen;
|
||||
st.frozen_target = in.rec->target;
|
||||
double best = 0.0;
|
||||
for (const CandidateScore &c : in.rec->ranking)
|
||||
if (c.def.same_rf(in.rec->target)) {
|
||||
best = c.score;
|
||||
break;
|
||||
}
|
||||
st.frozen_score = best;
|
||||
|
||||
GateOutcome o;
|
||||
o.verdict = GateVerdict::Propose;
|
||||
o.reason = GateReason::Propose;
|
||||
o.target = in.rec->target;
|
||||
o.evidence_gen = in.rec->evidence_gen;
|
||||
return o;
|
||||
}
|
||||
|
||||
void mig_gate_on_confirmed(GateState &st, const ChannelDef &now_on,
|
||||
int64_t now_ms) {
|
||||
(void)now_on;
|
||||
st.last_move_ms = now_ms;
|
||||
st.residency_start_ms = now_ms;
|
||||
++st.moves_session;
|
||||
st.rollback_streak = 0;
|
||||
st.have_frozen = false;
|
||||
}
|
||||
|
||||
void mig_gate_on_rolledback(GateState &st, const ChannelDef &target,
|
||||
const GatePolicy &pol, int64_t now_ms) {
|
||||
++st.rollback_streak;
|
||||
int64_t backoff = pol.holddown_base_ms;
|
||||
for (int i = 1; i < st.rollback_streak && backoff < pol.holddown_cap_ms; ++i)
|
||||
backoff *= 2;
|
||||
if (backoff > pol.holddown_cap_ms)
|
||||
backoff = pol.holddown_cap_ms;
|
||||
st.set_holddown(target.key(), now_ms + backoff);
|
||||
st.have_frozen = false;
|
||||
/* a rollback also counts against the move budget so a flapping channel
|
||||
* cannot exhaust retries silently */
|
||||
st.last_move_ms = now_ms;
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
@@ -0,0 +1,197 @@
|
||||
/* MigGate — the conservative autonomous-migration policy (issue #279).
|
||||
*
|
||||
* It sits between the advisory engine (a ChannelScore Decision) and the
|
||||
* migration protocol (MigProposer): it may submit a proposal automatically,
|
||||
* but only when a conjunction of conservative conditions holds, and it hedges
|
||||
* every migration with cooldown, residency, per-channel backoff, a session
|
||||
* move cap, probation, and an operator kill switch. Stable single-channel
|
||||
* video is the normal state; migrations are exceptional.
|
||||
*
|
||||
* Pure and deterministic: no clock reads (the caller passes now), no RNG, no
|
||||
* device — same input trace ⇒ same decisions, so the whole policy is replayable
|
||||
* and selftested against the issue's scenario matrix. The gate does not
|
||||
* actuate; it returns a verdict the ground controller feeds to MigProposer. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_GATE_H
|
||||
#define DEVOURER_CHANMIG_MIG_GATE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
#include "chanmig/ChannelScore.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
enum class MigMode : uint8_t { Off, Advisory, Manual, Automatic };
|
||||
|
||||
inline const char *mig_mode_name(MigMode m) {
|
||||
switch (m) {
|
||||
case MigMode::Off: return "off";
|
||||
case MigMode::Advisory: return "advisory";
|
||||
case MigMode::Manual: return "manual";
|
||||
case MigMode::Automatic: return "automatic";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
enum class GateVerdict : uint8_t { Hold, Propose, AbortInFlight, ProposeRollback };
|
||||
|
||||
enum class GateReason : uint8_t {
|
||||
ModeOff,
|
||||
Advisory,
|
||||
NotImpaired, /* the recommendation was a hold */
|
||||
FaultWeakLink, /* migration cannot fix a range problem */
|
||||
FaultBroadband,
|
||||
FaultSaturation,
|
||||
FaultScout,
|
||||
FaultUsb,
|
||||
TelemetryUnhealthy,
|
||||
ClockUnsynced,
|
||||
ScoutStale,
|
||||
EvidenceStale,
|
||||
EvidenceIncomplete,
|
||||
Illegal,
|
||||
MarginLow,
|
||||
ConfidenceLow,
|
||||
Cooldown,
|
||||
MoveCap,
|
||||
Residency,
|
||||
HolddownChannel,
|
||||
Backoff,
|
||||
InFlight,
|
||||
Pinned,
|
||||
Inhibited,
|
||||
ApproveRequired,
|
||||
ControlMarginLow,
|
||||
NoRescueVerified,
|
||||
ProbationActive,
|
||||
ProbationRollback,
|
||||
MaterialChange, /* in-flight evidence changed → abort + rescore */
|
||||
Propose, /* all gates passed */
|
||||
};
|
||||
|
||||
const char *gate_reason_name(GateReason r);
|
||||
|
||||
struct GatePolicy {
|
||||
double confidence_min = 0.9;
|
||||
int64_t cooldown_ms = 300000; /* 5 min between moves */
|
||||
int64_t residency_ms = 120000; /* 2 min minimum on a channel */
|
||||
int move_cap = 10; /* per session */
|
||||
int64_t holddown_base_ms = 60000; /* per-channel backoff base (×2^streak) */
|
||||
int64_t holddown_cap_ms = 3600000;
|
||||
int64_t probation_ms = 60000;
|
||||
double control_margin_min = 0.3; /* min recent control-frame delivery */
|
||||
double material_change_frac = 0.5; /* score drop (× margin) that aborts in-flight */
|
||||
};
|
||||
|
||||
/* Everything the gate reads for one decision. `rec` is the newest advisory
|
||||
* Decision (from ChannelScore); the rest are health/fault flags the ground
|
||||
* controller assembles from the primary + scout + control link. */
|
||||
struct GateInputs {
|
||||
MigMode mode = MigMode::Advisory;
|
||||
const Decision *rec = nullptr; /* null = no recommendation yet */
|
||||
|
||||
bool telemetry_ok = true;
|
||||
bool clock_synced = true;
|
||||
bool scout_healthy = true;
|
||||
int64_t scout_survey_age_ms = 0;
|
||||
int64_t scout_max_age_ms = 60000;
|
||||
bool usb_ok = true;
|
||||
|
||||
double control_link_margin = 1.0; /* recent status/ack delivery rate */
|
||||
bool rescue_verified = true;
|
||||
bool in_flight = false;
|
||||
|
||||
bool probation_active = false;
|
||||
bool probation_delivery_ok = true;
|
||||
|
||||
/* operator surface */
|
||||
bool approve_next = false; /* manual mode: one-shot approval armed */
|
||||
int64_t inhibit_until_ms = INT64_MIN;
|
||||
const ChannelDef *pinned = nullptr;
|
||||
};
|
||||
|
||||
/* Mutable anti-oscillation state the gate carries across decisions. */
|
||||
struct GateState {
|
||||
int64_t last_move_ms = INT64_MIN;
|
||||
int moves_session = 0;
|
||||
int64_t residency_start_ms = INT64_MIN;
|
||||
int rollback_streak = 0;
|
||||
struct Holddown {
|
||||
uint32_t key;
|
||||
int64_t until_ms;
|
||||
};
|
||||
std::vector<Holddown> holddowns;
|
||||
/* frozen in-flight proposal, for the material-change abort test */
|
||||
bool have_frozen = false;
|
||||
uint64_t frozen_gen = 0;
|
||||
ChannelDef frozen_target;
|
||||
double frozen_score = 0.0;
|
||||
|
||||
int64_t holddown_for(uint32_t key) const {
|
||||
for (const Holddown &h : holddowns)
|
||||
if (h.key == key)
|
||||
return h.until_ms;
|
||||
return INT64_MIN;
|
||||
}
|
||||
void set_holddown(uint32_t key, int64_t until) {
|
||||
for (Holddown &h : holddowns)
|
||||
if (h.key == key) {
|
||||
h.until_ms = until;
|
||||
return;
|
||||
}
|
||||
holddowns.push_back({key, until});
|
||||
}
|
||||
};
|
||||
|
||||
struct GateOutcome {
|
||||
GateVerdict verdict = GateVerdict::Hold;
|
||||
GateReason reason = GateReason::Advisory;
|
||||
ChannelDef target;
|
||||
uint64_t evidence_gen = 0;
|
||||
};
|
||||
|
||||
/* Map a ChannelScore hold reason to the gate's fault taxonomy, so a hold's
|
||||
* cause is preserved in the migrate.gate event. */
|
||||
inline GateReason gate_reason_for_hold(Reason r) {
|
||||
switch (r) {
|
||||
case Reason::HoldActiveHealthy:
|
||||
case Reason::HoldImpairmentNotPersistent:
|
||||
return GateReason::NotImpaired;
|
||||
case Reason::HoldImpairmentNotChannel:
|
||||
return GateReason::FaultWeakLink; /* weak OR saturated — both non-channel */
|
||||
case Reason::HoldBroadDegradation:
|
||||
return GateReason::FaultBroadband;
|
||||
case Reason::HoldScoutUnhealthy:
|
||||
return GateReason::FaultScout;
|
||||
case Reason::HoldPrimaryTelemetryStale:
|
||||
return GateReason::TelemetryUnhealthy;
|
||||
case Reason::HoldImprovementMargin:
|
||||
return GateReason::MarginLow;
|
||||
case Reason::HoldCooldown:
|
||||
return GateReason::Cooldown;
|
||||
case Reason::HoldNoQualifiedCandidate:
|
||||
return GateReason::EvidenceIncomplete;
|
||||
default:
|
||||
return GateReason::NotImpaired;
|
||||
}
|
||||
}
|
||||
|
||||
/* The decision. Pure; `now_ms` is caller-supplied. Mutates only GateState
|
||||
* (cooldown/holddown/frozen latches); it does NOT record a move — the caller
|
||||
* calls on_confirmed()/on_rolledback() when the protocol resolves. */
|
||||
GateOutcome mig_gate_decide(const GateInputs &in, GateState &st,
|
||||
const GatePolicy &pol, int64_t now_ms);
|
||||
|
||||
/* Protocol-resolution callbacks the controller invokes so the anti-oscillation
|
||||
* state stays honest. */
|
||||
void mig_gate_on_confirmed(GateState &st, const ChannelDef &now_on,
|
||||
int64_t now_ms);
|
||||
void mig_gate_on_rolledback(GateState &st, const ChannelDef &target,
|
||||
const GatePolicy &pol, int64_t now_ms);
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_GATE_H */
|
||||
@@ -0,0 +1,435 @@
|
||||
/* MigProposer — the GROUND state machine (pure).
|
||||
*
|
||||
* Ground proposes a target and, on an authenticated matching COMMIT, becomes a
|
||||
* follower of the drone's activation schedule: it acks the commit (its nonce
|
||||
* echo IS the ack the drone waits for), retunes its primary RX at the relative
|
||||
* activation instant, verifies generation-tagged markers + video on the new
|
||||
* channel, and confirms — or falls into a bounded recovery scan of
|
||||
* old/new/rescue. It reads no clock and does no crypto: inputs are decoded
|
||||
* MigMsgs + local observations + monotonic `now`; outputs are MigActions the
|
||||
* demo executes (stamping tx_tsf and encoding on the way out).
|
||||
*
|
||||
* Convergence invariants (proven per row in the failure-matrix selftest):
|
||||
* I1 never retune before adopting a nonce+generation-matched commit
|
||||
* I2 every post-activation path has a bounded route back to a channel in
|
||||
* the recovery scan set
|
||||
* I5 a replayed/forged exchange can never be adopted (nonce+gen gate) */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_PROPOSER_H
|
||||
#define DEVOURER_CHANMIG_MIG_PROPOSER_H
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/MigConfig.h"
|
||||
#include "chanmig/MigTypes.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
/* Deterministic nonce: unpredictable across sessions (the epoch is random,
|
||||
* seeded by the demo from std::random_device), reproducible within a trace. */
|
||||
inline uint32_t mig_mix_nonce(uint32_t epoch, uint32_t gen, uint32_t salt) {
|
||||
uint32_t h = epoch * 2654435761u + gen * 40503u + salt * 2246822519u;
|
||||
h ^= h >> 15;
|
||||
h *= 2246822519u;
|
||||
h ^= h >> 13;
|
||||
return h ? h : 1u;
|
||||
}
|
||||
|
||||
class MigProposer {
|
||||
public:
|
||||
MigProposer(MigParams params, uint32_t link_id, uint32_t ground_epoch,
|
||||
ChannelDef source)
|
||||
: p_(params), link_id_(link_id), epoch_(ground_epoch), source_(source),
|
||||
current_(source) {}
|
||||
|
||||
MigState state() const { return st_; }
|
||||
ChannelDef current_channel() const { return current_; }
|
||||
uint32_t generation() const { return gen_; }
|
||||
uint32_t wrong_channel_frames() const { return wrong_channel_; }
|
||||
|
||||
/* Operator/gate trigger. No-op unless Stable. */
|
||||
std::vector<MigAction> start(const ChannelDef &target, uint32_t evidence_gen,
|
||||
const ChannelDef &rescue, int64_t now) {
|
||||
std::vector<MigAction> a;
|
||||
if (st_ != MigState::Stable)
|
||||
return a;
|
||||
++gen_;
|
||||
nonce_ = mig_mix_nonce(epoch_, gen_, 0xA1);
|
||||
target_ = target;
|
||||
rescue_ = rescue;
|
||||
evidence_gen_ = evidence_gen;
|
||||
st_ = MigState::Proposed;
|
||||
tries_ = 1;
|
||||
next_send_ms_ = now + p_.proposal_interval_ms;
|
||||
a.push_back(send(MT_PROPOSAL, make_proposal(), true));
|
||||
a.push_back(ev());
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_message(const MigMsg &m, int64_t now) {
|
||||
switch (m.type) {
|
||||
case MT_COMMIT: return on_commit(m, now);
|
||||
case MT_STATUS: return on_status(m, now);
|
||||
case MT_MARKER: return on_marker(m, now);
|
||||
case MT_ABORT: return on_abort(m, now);
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_tick(int64_t now) {
|
||||
switch (st_) {
|
||||
case MigState::Proposed: return tick_proposed(now);
|
||||
case MigState::Committed: return tick_committed(now);
|
||||
case MigState::Verifying: return tick_verifying(now);
|
||||
case MigState::Recovery: return tick_recovery(now);
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
/* The demo's RX retune finished. */
|
||||
std::vector<MigAction> on_retune_done(int64_t now) {
|
||||
if (st_ != MigState::Switching)
|
||||
return {};
|
||||
if (follow_pending_) {
|
||||
/* we were retuning to follow the drone's reported settled channel */
|
||||
follow_pending_ = false;
|
||||
st_ = MigState::Stable;
|
||||
current_ = follow_channel_;
|
||||
const uint8_t code = follow_channel_.same_rf(commit_target_) ? 0 : 1;
|
||||
return {ev(), gate(code), done(code)};
|
||||
}
|
||||
st_ = MigState::Verifying;
|
||||
verify_deadline_ms_ = activate_local_ms_ + p_.verify_ms;
|
||||
markers_seen_ = 0;
|
||||
video_seen_ = 0;
|
||||
got_gen_marker_ = false;
|
||||
verified_ = false;
|
||||
current_ = commit_target_;
|
||||
return {ev()};
|
||||
}
|
||||
|
||||
/* A canonical-SA video frame decoded on the current channel. */
|
||||
std::vector<MigAction> on_video(int64_t now) {
|
||||
if (st_ == MigState::Verifying) {
|
||||
if (now < blank_until_ms_ || !got_gen_marker_)
|
||||
return {}; /* blank window / pre-marker: stale, ignore */
|
||||
++video_seen_;
|
||||
return maybe_confirm(now);
|
||||
}
|
||||
if (st_ == MigState::Recovery)
|
||||
return recover_to(recov_channel(), now);
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
MigMsg make_proposal() const {
|
||||
MigMsg m;
|
||||
m.type = MT_PROPOSAL;
|
||||
m.link_id = link_id_;
|
||||
m.ground_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.source = source_;
|
||||
m.target = target_;
|
||||
m.evidence_gen = evidence_gen_;
|
||||
m.fallback_mode = 0;
|
||||
m.rescue = rescue_;
|
||||
m.ground_nonce = nonce_;
|
||||
return m;
|
||||
}
|
||||
MigMsg make_status_ack() const {
|
||||
MigMsg m;
|
||||
m.type = MT_STATUS;
|
||||
m.link_id = link_id_;
|
||||
m.role = 0;
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.state = static_cast<uint8_t>(st_);
|
||||
m.current = current_;
|
||||
m.peer_nonce_echo = drone_nonce_; /* THE commit-ack */
|
||||
return m;
|
||||
}
|
||||
MigMsg make_confirm() const {
|
||||
MigMsg m;
|
||||
m.type = MT_CONFIRM;
|
||||
m.link_id = link_id_;
|
||||
m.ground_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.drone_nonce_echo = drone_nonce_;
|
||||
m.marker_count = static_cast<uint16_t>(markers_seen_);
|
||||
m.video_frames = static_cast<uint16_t>(video_seen_);
|
||||
return m;
|
||||
}
|
||||
MigAction send(MigMsgType t, const MigMsg &m, bool unicast) const {
|
||||
MigAction a;
|
||||
a.kind = unicast ? MigAction::SendUnicast : MigAction::SendBroadcast;
|
||||
a.msg = m;
|
||||
a.msg.type = t;
|
||||
return a;
|
||||
}
|
||||
MigAction retune(const ChannelDef &c) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::RetuneTo;
|
||||
a.channel = c;
|
||||
return a;
|
||||
}
|
||||
MigAction ev() const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::EmitEvent;
|
||||
a.code = static_cast<uint8_t>(st_);
|
||||
return a;
|
||||
}
|
||||
MigAction gate(uint8_t code) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::GateNotify;
|
||||
a.code = code;
|
||||
return a;
|
||||
}
|
||||
MigAction done(uint8_t code) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::Done;
|
||||
a.code = code;
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_commit(const MigMsg &m, int64_t now) {
|
||||
/* nonce + generation gate — the replay/forgery wall (I5). */
|
||||
if (m.generation != gen_ || m.ground_nonce_echo != nonce_)
|
||||
return {};
|
||||
if (st_ == MigState::Proposed) {
|
||||
drone_epoch_ = m.drone_epoch;
|
||||
drone_nonce_ = m.drone_nonce;
|
||||
commit_target_ = m.target;
|
||||
commit_rescue_ = m.rescue;
|
||||
activate_tsf_ = m.activate_tsf;
|
||||
commit_tx_tsf_ = m.tx_tsf;
|
||||
const int64_t offset_ms =
|
||||
static_cast<int64_t>((activate_tsf_ - commit_tx_tsf_) / 1000);
|
||||
activate_local_ms_ = now + offset_ms;
|
||||
retune_at_ms_ = activate_local_ms_ - p_.lead_ms;
|
||||
if (retune_at_ms_ < now)
|
||||
retune_at_ms_ = now;
|
||||
st_ = MigState::Committed;
|
||||
next_status_ms_ = now;
|
||||
/* The ground follows the drone's authoritative settled STATUS; this
|
||||
* deadline (past the drone's own rollback deadline) is the backstop for
|
||||
* a total control-path loss, after which the ground recovers by scan. */
|
||||
follow_deadline_ms_ = activate_local_ms_ + p_.rollback_ms + 2000;
|
||||
std::vector<MigAction> a;
|
||||
a.push_back(ev());
|
||||
auto t = tick_committed(now); /* sends the first ack immediately */
|
||||
a.insert(a.end(), t.begin(), t.end());
|
||||
return a;
|
||||
}
|
||||
if (st_ == MigState::Committed) /* drone retransmit: re-ack */
|
||||
return {send(MT_STATUS, make_status_ack(), false)};
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_status(const MigMsg &m, int64_t now) {
|
||||
if (st_ == MigState::Proposed && m.reason != 0) {
|
||||
/* the drone rejected our proposal (source mismatch / illegal / busy) */
|
||||
st_ = MigState::Stable;
|
||||
current_ = source_;
|
||||
MigAction e;
|
||||
e.kind = MigAction::EmitEvent;
|
||||
e.code = m.reason;
|
||||
return {e, done(1)};
|
||||
}
|
||||
/* Follow the drone's authoritative settled channel. The drone is the
|
||||
* schedule authority: once it reports Stable somewhere, the ground goes
|
||||
* there (this is what closes every dropped-confirm / rollback split-brain
|
||||
* — the ground never unilaterally commits to a channel the drone left). */
|
||||
if (m.role == 1 && m.generation == gen_ &&
|
||||
(st_ == MigState::Committed || st_ == MigState::Switching ||
|
||||
st_ == MigState::Verifying) &&
|
||||
m.state == static_cast<uint8_t>(MigState::Stable))
|
||||
return follow_drone(m.current, now);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> follow_drone(const ChannelDef &chan, int64_t now) {
|
||||
(void)now;
|
||||
if (current_.same_rf(chan)) {
|
||||
st_ = MigState::Stable;
|
||||
current_ = chan;
|
||||
const uint8_t code = chan.same_rf(commit_target_) ? 0 : 1;
|
||||
std::vector<MigAction> a;
|
||||
if (chan.same_rf(commit_target_))
|
||||
a.push_back(send(MT_CONFIRM, make_confirm(), true)); /* ack the drone */
|
||||
a.push_back(ev());
|
||||
a.push_back(gate(code));
|
||||
a.push_back(done(code));
|
||||
return a;
|
||||
}
|
||||
/* retune to where the drone settled, then go Stable there */
|
||||
follow_channel_ = chan;
|
||||
follow_pending_ = true;
|
||||
st_ = MigState::Switching;
|
||||
return {retune(chan), ev()};
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_marker(const MigMsg &m, int64_t now) {
|
||||
if (m.generation != gen_ || m.drone_epoch != drone_epoch_)
|
||||
return {}; /* foreign / stale generation */
|
||||
if (st_ == MigState::Verifying) {
|
||||
if (!m.aired_on.same_rf(commit_target_)) {
|
||||
++wrong_channel_; /* delayed-USB / wrong-channel frame */
|
||||
return {};
|
||||
}
|
||||
if (now < blank_until_ms_)
|
||||
return {};
|
||||
got_gen_marker_ = true;
|
||||
++markers_seen_;
|
||||
return maybe_confirm(now);
|
||||
}
|
||||
if (st_ == MigState::Recovery)
|
||||
return recover_to(m.aired_on, now);
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_abort(const MigMsg &m, int64_t now) {
|
||||
if (m.effective == 0) { /* pre-activation cancel: nothing moved */
|
||||
st_ = MigState::Stable;
|
||||
current_ = source_;
|
||||
return {ev(), done(1)};
|
||||
}
|
||||
/* drone rolled back — scan to reunite */
|
||||
enter_recovery(now);
|
||||
return {ev(), retune(recov_channel())};
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_proposed(int64_t now) {
|
||||
if (now < next_send_ms_)
|
||||
return {};
|
||||
if (tries_ >= p_.proposal_max_tries) {
|
||||
st_ = MigState::Stable;
|
||||
current_ = source_;
|
||||
return {ev(), done(1)}; /* gave up; stayed on old */
|
||||
}
|
||||
++tries_;
|
||||
next_send_ms_ = now + p_.proposal_interval_ms;
|
||||
return {send(MT_PROPOSAL, make_proposal(), true)};
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_committed(int64_t now) {
|
||||
std::vector<MigAction> a;
|
||||
if (now >= next_status_ms_) {
|
||||
a.push_back(send(MT_STATUS, make_status_ack(), false));
|
||||
next_status_ms_ = now + p_.commit_interval_ms;
|
||||
}
|
||||
if (now >= retune_at_ms_) {
|
||||
st_ = MigState::Switching;
|
||||
blank_until_ms_ = now + p_.blank_window_ms;
|
||||
a.push_back(retune(commit_target_));
|
||||
a.push_back(ev());
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_verifying(int64_t now) {
|
||||
std::vector<MigAction> a;
|
||||
/* Once the markers prove the channel, tell the drone we followed (CONFIRM,
|
||||
* repeated) — but do NOT declare success: the ground reaches Stable only
|
||||
* when the drone's own STATUS says it settled on the target (follow_drone),
|
||||
* so a dropped CONFIRM + drone rollback can never strand the ground here. */
|
||||
if (verified_ && now >= next_confirm_ms_) {
|
||||
a.push_back(send(MT_CONFIRM, make_confirm(), true));
|
||||
next_confirm_ms_ = now + p_.commit_interval_ms;
|
||||
}
|
||||
/* Control-path-loss backstop: no authoritative drone STATUS by the follow
|
||||
* deadline -> scan to reunite. */
|
||||
if (now >= follow_deadline_ms_) {
|
||||
enter_recovery(now);
|
||||
a.push_back(ev());
|
||||
a.push_back(retune(recov_channel()));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_recovery(int64_t now) {
|
||||
if (now < recov_next_ms_)
|
||||
return {};
|
||||
recov_idx_ = (recov_idx_ + 1) % recov_len_;
|
||||
recov_next_ms_ = now + p_.recovery_dwell_ms;
|
||||
std::vector<MigAction> a{retune(recov_channel())};
|
||||
if (now - recov_start_ms_ > p_.recovery_giveup_ms) {
|
||||
MigAction e;
|
||||
e.kind = MigAction::EmitEvent;
|
||||
e.code = 255; /* recovery exhausted */
|
||||
a.push_back(e);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> maybe_confirm(int64_t now) {
|
||||
/* Markers proved the channel — start confirming (the drone needs to learn
|
||||
* the ground followed), but the ground stays Verifying until the drone's
|
||||
* STATUS confirms it settled (follow_drone). */
|
||||
if (!verified_ &&
|
||||
(markers_seen_ >= p_.verify_markers || video_seen_ >= p_.verify_video)) {
|
||||
verified_ = true;
|
||||
next_confirm_ms_ = now + p_.commit_interval_ms;
|
||||
return {send(MT_CONFIRM, make_confirm(), true)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void enter_recovery(int64_t now) {
|
||||
recov_pattern_[0] = source_;
|
||||
recov_pattern_[1] = commit_target_;
|
||||
recov_pattern_[2] = source_;
|
||||
recov_pattern_[3] = commit_rescue_;
|
||||
recov_len_ = 4;
|
||||
recov_idx_ = 0;
|
||||
recov_start_ms_ = now;
|
||||
recov_next_ms_ = now + p_.recovery_dwell_ms;
|
||||
st_ = MigState::Recovery;
|
||||
current_ = recov_channel();
|
||||
}
|
||||
ChannelDef recov_channel() const { return recov_pattern_[recov_idx_]; }
|
||||
|
||||
std::vector<MigAction> recover_to(const ChannelDef &c, int64_t now) {
|
||||
(void)now;
|
||||
st_ = MigState::Stable;
|
||||
current_ = c;
|
||||
const uint8_t code = c.same_rf(commit_target_) ? 0 : 1;
|
||||
return {ev(), gate(code), done(code)};
|
||||
}
|
||||
|
||||
MigParams p_;
|
||||
uint32_t link_id_, epoch_;
|
||||
ChannelDef source_, current_;
|
||||
MigState st_ = MigState::Stable;
|
||||
|
||||
/* current exchange */
|
||||
uint32_t gen_ = 0, nonce_ = 0, evidence_gen_ = 0;
|
||||
ChannelDef target_, rescue_;
|
||||
int tries_ = 0;
|
||||
int64_t next_send_ms_ = 0;
|
||||
|
||||
/* committed */
|
||||
uint32_t drone_epoch_ = 0, drone_nonce_ = 0;
|
||||
ChannelDef commit_target_, commit_rescue_;
|
||||
uint64_t activate_tsf_ = 0, commit_tx_tsf_ = 0;
|
||||
int64_t activate_local_ms_ = 0, retune_at_ms_ = 0, next_status_ms_ = 0;
|
||||
|
||||
/* verify */
|
||||
int64_t verify_deadline_ms_ = 0, blank_until_ms_ = 0, next_confirm_ms_ = 0;
|
||||
int64_t follow_deadline_ms_ = 0;
|
||||
int markers_seen_ = 0, video_seen_ = 0;
|
||||
bool got_gen_marker_ = false, verified_ = false;
|
||||
uint32_t wrong_channel_ = 0;
|
||||
/* following the drone's authoritative settled channel */
|
||||
ChannelDef follow_channel_;
|
||||
bool follow_pending_ = false;
|
||||
|
||||
/* recovery */
|
||||
ChannelDef recov_pattern_[4];
|
||||
int recov_len_ = 0, recov_idx_ = 0;
|
||||
int64_t recov_next_ms_ = 0, recov_start_ms_ = 0;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_PROPOSER_H */
|
||||
@@ -0,0 +1,549 @@
|
||||
/* MigResponder — the DRONE (video TX) state machine (pure).
|
||||
*
|
||||
* The drone is the final schedule authority: it validates a ground proposal,
|
||||
* fixes an absolute activation instant on its own TSF, and — crucially —
|
||||
* arms that activation ONLY after it has seen the ground echo its nonce (the
|
||||
* commit-ack). That single rule closes every replay-initiated and
|
||||
* control-loss split-brain row: a commit the current ground never heard is
|
||||
* never activated, so the drone can never strand itself on a channel the
|
||||
* ground isn't following.
|
||||
*
|
||||
* At activation it drains/deterministically-drops pending TX, retunes through
|
||||
* the safe gate, re-arms its ACK responder, and airs generation-tagged low-MCS
|
||||
* markers; if the ground never confirms by the rollback deadline it returns to
|
||||
* the fallback channel. Pure: inputs are decoded MigMsgs + local observations
|
||||
* + monotonic `now` + the drone's own TSF (needed once, to fix the absolute
|
||||
* activation instant); outputs are MigActions.
|
||||
*
|
||||
* The #280 target-validation hook lives in validate_target(); stage 3 ships
|
||||
* the variant-A instant checks (legality / caps / allowed-list), stage 5 adds
|
||||
* the pre-commit probe. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_RESPONDER_H
|
||||
#define DEVOURER_CHANMIG_MIG_RESPONDER_H
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/MigConfig.h"
|
||||
#include "chanmig/MigProposer.h" /* mig_mix_nonce */
|
||||
#include "chanmig/MigTypes.h"
|
||||
#include "chanmig/MigWire.h" /* ReplayWindow */
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
/* Static capabilities + policy the drone validates a target against. */
|
||||
struct MigCaps {
|
||||
uint8_t bands = 0x02 | 0x04; /* bit1 = 2.4, bit2 = 5 (matches ChannelDef.band as a set) */
|
||||
uint8_t widths = 0xFF; /* 1<<ChannelWidth_t supported */
|
||||
std::vector<ChannelDef> allowed; /* empty = any legal channel */
|
||||
bool band_ok(uint8_t band) const {
|
||||
if (band == 2)
|
||||
return bands & 0x02;
|
||||
if (band == 5)
|
||||
return bands & 0x04;
|
||||
return false;
|
||||
}
|
||||
bool width_ok(ChannelWidth_t w) const { return widths & (1u << w); }
|
||||
bool allowed_ok(const ChannelDef &d) const {
|
||||
if (allowed.empty())
|
||||
return true;
|
||||
for (const ChannelDef &c : allowed)
|
||||
if (c.same_rf(d))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
/* #280 variant B: opt-in single-radio pre-commit probe (research). Off by
|
||||
* default — variant A (these checks) is the product baseline. When on, the
|
||||
* drone briefly retunes to the target before committing and vetoes an
|
||||
* extreme-occupancy destination. */
|
||||
bool probe = false;
|
||||
double veto_busy_frac = 0.6;
|
||||
};
|
||||
|
||||
class MigResponder {
|
||||
public:
|
||||
MigResponder(MigParams params, uint32_t link_id, uint32_t drone_epoch,
|
||||
ChannelDef current, MigCaps caps)
|
||||
: p_(params), link_id_(link_id), epoch_(drone_epoch), current_(current),
|
||||
caps_(caps) {}
|
||||
|
||||
MigState state() const { return st_; }
|
||||
ChannelDef current_channel() const { return current_; }
|
||||
uint32_t generation() const { return gen_; }
|
||||
|
||||
std::vector<MigAction> on_message(const MigMsg &m, int64_t now,
|
||||
uint64_t now_tsf) {
|
||||
switch (m.type) {
|
||||
case MT_PROPOSAL: return on_proposal(m, now, now_tsf);
|
||||
case MT_STATUS: return on_status(m, now);
|
||||
case MT_CONFIRM: return on_confirm(m, now);
|
||||
case MT_ABORT: return {}; /* ground doesn't abort us */
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_tick(int64_t now, uint64_t now_tsf) {
|
||||
std::vector<MigAction> a;
|
||||
/* Periodic STATUS is the ground's authoritative signal for where the
|
||||
* drone actually settled — the ground FOLLOWS it, so it must keep flowing
|
||||
* for a grace window after the drone reaches a terminal state. */
|
||||
if (now >= next_status_ms_ &&
|
||||
(st_ != MigState::Stable || now < settle_status_until_ms_) &&
|
||||
gen_ != 0) {
|
||||
a.push_back(send(make_status(), false));
|
||||
next_status_ms_ = now + p_.status_interval_ms;
|
||||
}
|
||||
switch (st_) {
|
||||
case MigState::Committed: {
|
||||
auto t = tick_committed(now, now_tsf);
|
||||
a.insert(a.end(), t.begin(), t.end());
|
||||
break;
|
||||
}
|
||||
case MigState::Switching: {
|
||||
/* Drain-stall backstop: if the drain callback never lands by its
|
||||
* deadline, drop the pending TX deterministically and retune anyway —
|
||||
* the migration must not hang on a stuck USB completion. */
|
||||
if (phase_ == Phase::Draining && now >= drain_deadline_ms_) {
|
||||
phase_ = Phase::Retuning;
|
||||
a.push_back(retune(commit_target_));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MigState::Verifying: {
|
||||
auto t = tick_verifying(now, now_tsf);
|
||||
a.insert(a.end(), t.begin(), t.end());
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_drain_done(int64_t now) {
|
||||
(void)now;
|
||||
if (st_ == MigState::Switching && phase_ == Phase::Draining) {
|
||||
phase_ = Phase::Retuning;
|
||||
return {retune(commit_target_)};
|
||||
}
|
||||
if (st_ == MigState::Validating && pp_ == ProbePhase::Drain) {
|
||||
pp_ = ProbePhase::Retune;
|
||||
return {retune(commit_target_)}; /* probe: hop to the target to sample */
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/* #280 variant B: the demo samples GetRxEnergy after the probe retune settles
|
||||
* and reports the destination's occupancy here. valid=false ⇒ unknown. */
|
||||
std::vector<MigAction> on_probe_sample(double busy_frac, bool valid,
|
||||
int64_t now) {
|
||||
(void)now;
|
||||
if (st_ != MigState::Validating || pp_ != ProbePhase::Sampling)
|
||||
return {};
|
||||
probe_busy_ = busy_frac;
|
||||
probe_valid_ = valid;
|
||||
probe_veto_ = valid && busy_frac > caps_.veto_busy_frac;
|
||||
pp_ = ProbePhase::Return;
|
||||
return {retune(commit_source_)}; /* always return to source before deciding */
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_retune_done(bool ok, int64_t now, uint64_t now_tsf) {
|
||||
(void)now;
|
||||
(void)now_tsf;
|
||||
if (st_ == MigState::Switching && phase_ == Phase::Retuning) {
|
||||
if (ok) {
|
||||
current_ = commit_target_;
|
||||
st_ = MigState::Verifying;
|
||||
MigAction arm;
|
||||
arm.kind = MigAction::ArmMarkers;
|
||||
arm.channel = commit_target_;
|
||||
MigAction rp;
|
||||
rp.kind = MigAction::ResumePump;
|
||||
return {arm, rp, ev()};
|
||||
}
|
||||
/* retune failed: fall back to the source, then rescue */
|
||||
phase_ = Phase::RollbackRetune;
|
||||
current_ = fallback_channel(); /* provisional */
|
||||
return {retune(fallback_channel())};
|
||||
}
|
||||
if (st_ == MigState::Switching && phase_ == Phase::RollbackRetune) {
|
||||
if (ok) {
|
||||
current_ = fallback_channel();
|
||||
return finish_rollback(now);
|
||||
}
|
||||
/* even the fallback retune failed: rescue + abort */
|
||||
current_ = commit_rescue_;
|
||||
st_ = MigState::Stable;
|
||||
hold_down_until_ms_ = now + p_.proposal_hold_down_ms;
|
||||
return {retune(commit_rescue_), abort_msg(MigReason::RetuneFail, 1),
|
||||
gate(1), done(2)};
|
||||
}
|
||||
if (st_ == MigState::Rollback) {
|
||||
current_ = fallback_channel();
|
||||
return finish_rollback(now);
|
||||
}
|
||||
/* --- probe (variant B) retune callbacks --- */
|
||||
if (st_ == MigState::Validating && pp_ == ProbePhase::Retune) {
|
||||
if (ok) {
|
||||
current_ = commit_target_; /* on the target, awaiting the sample */
|
||||
pp_ = ProbePhase::Sampling;
|
||||
MigAction e; /* tell the demo to sample GetRxEnergy now */
|
||||
e.kind = MigAction::EmitEvent;
|
||||
e.code = kProbeSampleNow;
|
||||
return {e};
|
||||
}
|
||||
/* couldn't even reach the target: return to source, veto */
|
||||
probe_veto_ = true;
|
||||
probe_valid_ = false;
|
||||
pp_ = ProbePhase::Return;
|
||||
return {retune(commit_source_)};
|
||||
}
|
||||
if (st_ == MigState::Validating && pp_ == ProbePhase::Return) {
|
||||
current_ = ok ? commit_source_ : commit_rescue_;
|
||||
pp_ = ProbePhase::None;
|
||||
MigAction resume;
|
||||
resume.kind = MigAction::ResumePump;
|
||||
if (!ok) {
|
||||
/* return retune failed — land on rescue, reject the migration */
|
||||
st_ = MigState::Stable;
|
||||
rw_.clear_in_flight();
|
||||
return {resume,
|
||||
validation_msg(commit_target_, 1, 1, MigReason::RetuneFail),
|
||||
status_reject(ground_epoch_, gen_, MigReason::RetuneFail),
|
||||
ev()};
|
||||
}
|
||||
if (probe_veto_) {
|
||||
st_ = MigState::Stable;
|
||||
rw_.clear_in_flight();
|
||||
return {resume,
|
||||
validation_msg(commit_target_, 1, 1, MigReason::Veto),
|
||||
status_reject(ground_epoch_, gen_, MigReason::Veto), ev()};
|
||||
}
|
||||
/* accepted — report it and commit for real */
|
||||
auto acts = enter_committed(now, now_tsf);
|
||||
acts.insert(acts.begin(), resume);
|
||||
acts.insert(acts.begin() + 1,
|
||||
validation_msg(commit_target_, 1, 0, MigReason::None));
|
||||
return acts;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private:
|
||||
enum class Phase { None, Draining, Retuning, RollbackRetune };
|
||||
enum class ProbePhase { None, Drain, Retune, Sampling, Return };
|
||||
static constexpr uint8_t kProbeSampleNow = 200;
|
||||
|
||||
std::vector<MigAction> enter_probe(int64_t now) {
|
||||
(void)now;
|
||||
st_ = MigState::Validating;
|
||||
pp_ = ProbePhase::Drain;
|
||||
probe_veto_ = false;
|
||||
probe_valid_ = false;
|
||||
MigAction d;
|
||||
d.kind = MigAction::StartDrain;
|
||||
return {d, ev()};
|
||||
}
|
||||
|
||||
MigAction validation_msg(const ChannelDef &target, uint8_t method,
|
||||
uint8_t result, MigReason reason) const {
|
||||
MigMsg m = base(MT_VALIDATION);
|
||||
m.drone_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.target = target;
|
||||
m.method = method;
|
||||
m.result = result;
|
||||
m.reason = static_cast<uint8_t>(reason);
|
||||
m.nhm_busy_pct = static_cast<uint8_t>(probe_busy_ * 100.0);
|
||||
m.energy_valid = probe_valid_ ? 1 : 0;
|
||||
return send(m, false);
|
||||
}
|
||||
|
||||
MigMsg base(MigMsgType t) const {
|
||||
MigMsg m;
|
||||
m.type = t;
|
||||
m.link_id = link_id_;
|
||||
return m;
|
||||
}
|
||||
MigAction send(const MigMsg &m, bool unicast) const {
|
||||
MigAction a;
|
||||
a.kind = unicast ? MigAction::SendUnicast : MigAction::SendBroadcast;
|
||||
a.msg = m;
|
||||
return a;
|
||||
}
|
||||
MigAction retune(const ChannelDef &c) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::RetuneTo;
|
||||
a.channel = c;
|
||||
return a;
|
||||
}
|
||||
MigAction ev() const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::EmitEvent;
|
||||
a.code = static_cast<uint8_t>(st_);
|
||||
return a;
|
||||
}
|
||||
MigAction gate(uint8_t code) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::GateNotify;
|
||||
a.code = code;
|
||||
return a;
|
||||
}
|
||||
MigAction done(uint8_t code) const {
|
||||
MigAction a;
|
||||
a.kind = MigAction::Done;
|
||||
a.code = code;
|
||||
return a;
|
||||
}
|
||||
MigAction abort_msg(MigReason r, uint8_t effective) const {
|
||||
MigMsg m = base(MT_ABORT);
|
||||
m.role = 1;
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.reason = static_cast<uint8_t>(r);
|
||||
m.effective = effective;
|
||||
return send(m, false);
|
||||
}
|
||||
MigAction status_reject(uint32_t ground_epoch, uint32_t gen,
|
||||
MigReason r) const {
|
||||
MigMsg m = base(MT_STATUS);
|
||||
m.role = 1;
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = gen;
|
||||
m.state = static_cast<uint8_t>(MigState::Stable);
|
||||
m.current = current_;
|
||||
m.reason = static_cast<uint8_t>(r);
|
||||
(void)ground_epoch;
|
||||
return send(m, false);
|
||||
}
|
||||
MigMsg make_status() const {
|
||||
MigMsg m = base(MT_STATUS);
|
||||
m.role = 1;
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = gen_;
|
||||
m.state = static_cast<uint8_t>(st_);
|
||||
m.current = current_;
|
||||
return m;
|
||||
}
|
||||
ChannelDef fallback_channel() const {
|
||||
return fallback_mode_ == 1 ? commit_rescue_ : commit_source_;
|
||||
}
|
||||
|
||||
/* #280 variant-A validation: legality + caps + allowed list. */
|
||||
MigReason validate_target(const ChannelDef &t) const {
|
||||
if (validate(t) != DefError::Ok)
|
||||
return MigReason::IllegalTarget;
|
||||
if (!caps_.band_ok(t.band))
|
||||
return MigReason::UnsupportedWidth;
|
||||
if (!caps_.width_ok(t.width))
|
||||
return MigReason::UnsupportedWidth;
|
||||
if (t.no_ir)
|
||||
return MigReason::IllegalTarget;
|
||||
if (!caps_.allowed_ok(t))
|
||||
return MigReason::IllegalTarget;
|
||||
return MigReason::None;
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_proposal(const MigMsg &m, int64_t now,
|
||||
uint64_t now_tsf) {
|
||||
/* epoch handling: a proposal may introduce/adopt a ground epoch. A ground
|
||||
* restart (fresh epoch) orphans our in-flight migration (I4). Crucially,
|
||||
* if we have already left the source channel, we must ROLL BACK to it —
|
||||
* the restarted ground believes we are on source, so sitting on the target
|
||||
* would strand us (a split-brain). Reject the triggering proposal as Busy
|
||||
* while the rollback runs; the ground reunites with us on source. */
|
||||
const bool epoch_change =
|
||||
rw_.have_peer && m.ground_epoch != rw_.peer_epoch;
|
||||
if (epoch_change && st_ != MigState::Stable) {
|
||||
const bool moved = gen_ != 0 && !current_.same_rf(commit_source_);
|
||||
phase_ = Phase::None;
|
||||
rw_.accept_epoch(m.ground_epoch, /*may_introduce=*/true);
|
||||
if (moved) {
|
||||
st_ = MigState::Rollback;
|
||||
rw_.clear_in_flight();
|
||||
return {retune(commit_source_),
|
||||
status_reject(m.ground_epoch, m.generation, MigReason::Busy),
|
||||
ev()};
|
||||
}
|
||||
st_ = MigState::Stable; /* still on source: just orphan and re-evaluate */
|
||||
}
|
||||
if (!rw_.accept_epoch(m.ground_epoch, /*may_introduce=*/true))
|
||||
return {status_reject(m.ground_epoch, m.generation, MigReason::StaleEpoch)};
|
||||
|
||||
const int cls = rw_.classify_proposal(m.generation);
|
||||
if (cls == 0) /* replay */
|
||||
return {};
|
||||
if (cls == 1) { /* idempotent: re-send the cached commit */
|
||||
if (st_ == MigState::Committed)
|
||||
return {send(cached_commit_, true)};
|
||||
return {};
|
||||
}
|
||||
/* fresh proposal */
|
||||
if (st_ != MigState::Stable || now < hold_down_until_ms_) {
|
||||
rw_.clear_in_flight();
|
||||
return {status_reject(m.ground_epoch, m.generation, MigReason::Busy)};
|
||||
}
|
||||
/* source must match where we actually are */
|
||||
if (!m.source.same_rf(current_)) {
|
||||
rw_.clear_in_flight();
|
||||
return {status_reject(m.ground_epoch, m.generation,
|
||||
MigReason::SourceMismatch)};
|
||||
}
|
||||
const MigReason vr = validate_target(m.target); /* variant A checks */
|
||||
if (vr != MigReason::None) {
|
||||
rw_.clear_in_flight();
|
||||
return {status_reject(m.ground_epoch, m.generation, vr),
|
||||
validation_msg(m.target, 0 /*A*/, 1 /*veto*/, vr)};
|
||||
}
|
||||
|
||||
/* stash the accepted proposal (used by enter_committed, and by the probe
|
||||
* before it commits). */
|
||||
gen_ = m.generation;
|
||||
ground_epoch_ = m.ground_epoch;
|
||||
ground_nonce_ = m.ground_nonce;
|
||||
commit_target_ = m.target;
|
||||
commit_source_ = m.source;
|
||||
commit_rescue_ = m.rescue;
|
||||
fallback_mode_ = m.fallback_mode;
|
||||
|
||||
/* Variant B: run the single-radio pre-commit probe before committing.
|
||||
* Off by default (variant A is the product baseline). */
|
||||
if (caps_.probe)
|
||||
return enter_probe(now);
|
||||
|
||||
return enter_committed(now, now_tsf);
|
||||
}
|
||||
|
||||
/* Build the commit + arm the Committed timers from the stashed proposal. */
|
||||
std::vector<MigAction> enter_committed(int64_t now, uint64_t now_tsf) {
|
||||
drone_nonce_ = mig_mix_nonce(epoch_, gen_, 0xD2);
|
||||
activate_tsf_ = now_tsf + p_.countdown_ms * 1000;
|
||||
rollback_deadline_tsf_ = activate_tsf_ + p_.rollback_ms * 1000;
|
||||
armed_ = false;
|
||||
ack_deadline_ms_ = now + p_.ack_timeout_ms;
|
||||
next_commit_ms_ = now + p_.commit_interval_ms;
|
||||
next_status_ms_ = now + p_.status_interval_ms;
|
||||
cached_commit_ = make_commit();
|
||||
st_ = MigState::Committed;
|
||||
return {send(cached_commit_, true), ev()};
|
||||
}
|
||||
|
||||
MigMsg make_commit() const {
|
||||
MigMsg m = base(MT_COMMIT);
|
||||
m.drone_epoch = epoch_;
|
||||
m.ground_epoch = ground_epoch_;
|
||||
m.generation = gen_;
|
||||
m.target = commit_target_;
|
||||
m.activate_tsf = activate_tsf_;
|
||||
m.confirm_window_us = static_cast<uint32_t>(p_.verify_ms * 1000);
|
||||
m.rollback_deadline_tsf = rollback_deadline_tsf_;
|
||||
m.rescue = commit_rescue_;
|
||||
m.ground_nonce_echo = ground_nonce_;
|
||||
m.drone_nonce = drone_nonce_;
|
||||
m.armed = 0;
|
||||
return m;
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_status(const MigMsg &m, int64_t now) {
|
||||
(void)now;
|
||||
/* the ground ack: it echoes OUR nonce. */
|
||||
if (st_ == MigState::Committed && m.peer_nonce_echo == drone_nonce_ &&
|
||||
m.generation == gen_)
|
||||
armed_ = true;
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> on_confirm(const MigMsg &m, int64_t now) {
|
||||
(void)now;
|
||||
if (st_ == MigState::Verifying && m.generation == gen_ &&
|
||||
m.drone_nonce_echo == drone_nonce_) {
|
||||
st_ = MigState::Stable;
|
||||
current_ = commit_target_;
|
||||
settle_status_until_ms_ = now + kSettleStatusMs;
|
||||
next_status_ms_ = now; /* let the ground learn we settled on target */
|
||||
MigAction stop;
|
||||
stop.kind = MigAction::StopMarkers;
|
||||
return {stop, ev(), gate(0), done(0)};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_committed(int64_t now, uint64_t now_tsf) {
|
||||
std::vector<MigAction> a;
|
||||
if (!armed_ && now >= ack_deadline_ms_) {
|
||||
/* never heard the ground ack: abort, never activate unheard */
|
||||
st_ = MigState::Stable;
|
||||
settle_status_until_ms_ = now + kSettleStatusMs;
|
||||
next_status_ms_ = now;
|
||||
rw_.clear_in_flight();
|
||||
a.push_back(abort_msg(MigReason::NoAck, 0));
|
||||
a.push_back(ev());
|
||||
return a;
|
||||
}
|
||||
if (now >= next_commit_ms_) {
|
||||
a.push_back(send(cached_commit_, true)); /* tx_tsf re-stamped by demo */
|
||||
next_commit_ms_ = now + p_.commit_interval_ms;
|
||||
}
|
||||
const uint64_t drain_budget_tsf =
|
||||
static_cast<uint64_t>(p_.drain_deadline_ms) * 1000;
|
||||
if (armed_ && now_tsf + drain_budget_tsf >= activate_tsf_) {
|
||||
st_ = MigState::Switching;
|
||||
phase_ = Phase::Draining;
|
||||
drain_deadline_ms_ = now + p_.drain_deadline_ms;
|
||||
MigAction d;
|
||||
d.kind = MigAction::StartDrain;
|
||||
a.push_back(d);
|
||||
a.push_back(ev());
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
std::vector<MigAction> tick_verifying(int64_t now, uint64_t now_tsf) {
|
||||
if (now_tsf >= rollback_deadline_tsf_) {
|
||||
st_ = MigState::Rollback;
|
||||
(void)now;
|
||||
MigAction stop;
|
||||
stop.kind = MigAction::StopMarkers;
|
||||
return {stop, retune(fallback_channel()), ev()};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<MigAction> finish_rollback(int64_t now) {
|
||||
st_ = MigState::Stable;
|
||||
hold_down_until_ms_ = now + p_.proposal_hold_down_ms;
|
||||
settle_status_until_ms_ = now + kSettleStatusMs;
|
||||
next_status_ms_ = now; /* tell the ground we returned to the fallback */
|
||||
rw_.clear_in_flight();
|
||||
MigAction stop;
|
||||
stop.kind = MigAction::StopMarkers;
|
||||
return {stop, ev(), gate(1), done(1)};
|
||||
}
|
||||
|
||||
static constexpr int64_t kSettleStatusMs = 8000;
|
||||
|
||||
MigParams p_;
|
||||
uint32_t link_id_, epoch_;
|
||||
ChannelDef current_;
|
||||
MigCaps caps_;
|
||||
MigState st_ = MigState::Stable;
|
||||
Phase phase_ = Phase::None;
|
||||
ReplayWindow rw_;
|
||||
|
||||
uint32_t gen_ = 0, ground_epoch_ = 0, ground_nonce_ = 0, drone_nonce_ = 0;
|
||||
ChannelDef commit_target_, commit_source_, commit_rescue_;
|
||||
uint8_t fallback_mode_ = 0;
|
||||
uint64_t activate_tsf_ = 0, rollback_deadline_tsf_ = 0;
|
||||
bool armed_ = false;
|
||||
int64_t ack_deadline_ms_ = 0, next_commit_ms_ = 0, hold_down_until_ms_ = 0;
|
||||
int64_t next_status_ms_ = 0, settle_status_until_ms_ = 0, drain_deadline_ms_ = 0;
|
||||
MigMsg cached_commit_;
|
||||
/* variant-B probe */
|
||||
ProbePhase pp_ = ProbePhase::None;
|
||||
double probe_busy_ = 0.0;
|
||||
bool probe_valid_ = false, probe_veto_ = false;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_RESPONDER_H */
|
||||
@@ -0,0 +1,185 @@
|
||||
/* Shared types for the coordinated channel-migration protocol (ground proposes,
|
||||
* drone commits). The state/reason/action enums both pure machines
|
||||
* (MigProposer, MigResponder) speak, kept in one header so the wire codec, the
|
||||
* machines, the demo, and the selftests agree on every code.
|
||||
*
|
||||
* Authority model: ground proposes a target, the drone (the video TX) validates
|
||||
* and becomes the final schedule authority by committing an activation instant
|
||||
* on its own clock. Neither endpoint retunes on a PROPOSAL; both act only on an
|
||||
* authenticated, matching, acknowledged COMMIT. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_TYPES_H
|
||||
#define DEVOURER_CHANMIG_MIG_TYPES_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
enum MigMsgType : uint8_t {
|
||||
MT_PROPOSAL = 1,
|
||||
MT_COMMIT = 2,
|
||||
MT_STATUS = 3,
|
||||
MT_CONFIRM = 4,
|
||||
MT_ABORT = 5,
|
||||
MT_MARKER = 6,
|
||||
MT_VALIDATION = 7,
|
||||
};
|
||||
|
||||
/* Canonical migration state names (issue #278). Both roles use this enum;
|
||||
* a role only visits the states meaningful to it. */
|
||||
enum class MigState : uint8_t {
|
||||
Stable,
|
||||
Proposed, /* ground: proposal sent, awaiting commit */
|
||||
Validating, /* drone: proposal received, running target validation (#280) */
|
||||
Committed, /* commit exchanged; activation scheduled */
|
||||
Switching, /* draining + retuning at the activation instant */
|
||||
Verifying, /* on the new channel, checking generation-tagged evidence */
|
||||
Confirmed, /* the move succeeded */
|
||||
Rollback, /* returning to the fallback channel */
|
||||
Recovery, /* ground: lost the peer, scanning old/new/rescue */
|
||||
};
|
||||
|
||||
inline const char *mig_state_name(MigState s) {
|
||||
switch (s) {
|
||||
case MigState::Stable: return "STABLE";
|
||||
case MigState::Proposed: return "PROPOSED";
|
||||
case MigState::Validating: return "VALIDATING";
|
||||
case MigState::Committed: return "COMMITTED";
|
||||
case MigState::Switching: return "SWITCHING";
|
||||
case MigState::Verifying: return "VERIFYING";
|
||||
case MigState::Confirmed: return "CONFIRMED";
|
||||
case MigState::Rollback: return "ROLLBACK";
|
||||
case MigState::Recovery: return "RECOVERY";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Reject / status reason codes (wire byte + event string). */
|
||||
enum class MigReason : uint8_t {
|
||||
None = 0,
|
||||
BadMac,
|
||||
BadVersion,
|
||||
BadType,
|
||||
BadLinkId,
|
||||
Truncated,
|
||||
ReplayGen,
|
||||
StaleEpoch,
|
||||
SourceMismatch,
|
||||
UnknownChannel,
|
||||
UnsupportedWidth,
|
||||
IllegalTarget,
|
||||
ActivationBounds,
|
||||
Busy,
|
||||
NoAck,
|
||||
RetuneFail,
|
||||
Veto,
|
||||
NonceMismatch,
|
||||
};
|
||||
|
||||
inline const char *mig_reason_name(MigReason r) {
|
||||
switch (r) {
|
||||
case MigReason::None: return "none";
|
||||
case MigReason::BadMac: return "bad_mac";
|
||||
case MigReason::BadVersion: return "bad_version";
|
||||
case MigReason::BadType: return "bad_type";
|
||||
case MigReason::BadLinkId: return "bad_link_id";
|
||||
case MigReason::Truncated: return "truncated";
|
||||
case MigReason::ReplayGen: return "replay_gen";
|
||||
case MigReason::StaleEpoch: return "stale_epoch";
|
||||
case MigReason::SourceMismatch: return "source_mismatch";
|
||||
case MigReason::UnknownChannel: return "unknown_channel";
|
||||
case MigReason::UnsupportedWidth: return "unsupported_width";
|
||||
case MigReason::IllegalTarget: return "illegal_target";
|
||||
case MigReason::ActivationBounds: return "activation_bounds";
|
||||
case MigReason::Busy: return "busy";
|
||||
case MigReason::NoAck: return "no_ack";
|
||||
case MigReason::RetuneFail: return "retune_fail";
|
||||
case MigReason::Veto: return "veto";
|
||||
case MigReason::NonceMismatch: return "nonce_mismatch";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* The decoded control message — a flat superset; each type populates its own
|
||||
* fields (kept flat, no variant, so the state machines read fields by name).
|
||||
* The pure machines produce and consume these; the demo/LinkSim does the
|
||||
* crypto (encode/decode/MAC via MigWire) and the TSF stamping. */
|
||||
struct MigMsg {
|
||||
MigMsgType type = MT_PROPOSAL;
|
||||
uint32_t link_id = 0;
|
||||
|
||||
/* identity / anti-replay */
|
||||
uint32_t ground_epoch = 0, drone_epoch = 0, sender_epoch = 0;
|
||||
uint32_t generation = 0;
|
||||
uint32_t ground_nonce = 0, drone_nonce = 0;
|
||||
uint32_t ground_nonce_echo = 0, drone_nonce_echo = 0, peer_nonce_echo = 0;
|
||||
|
||||
/* channels */
|
||||
ChannelDef source, target, rescue, current, aired_on;
|
||||
|
||||
/* proposal */
|
||||
uint32_t evidence_gen = 0;
|
||||
uint64_t evidence_digest = 0;
|
||||
uint64_t earliest_tsf = 0, latest_tsf = 0;
|
||||
uint8_t fallback_mode = 0; /* 0 = source, 1 = rescue */
|
||||
|
||||
/* commit */
|
||||
uint64_t activate_tsf = 0, rollback_deadline_tsf = 0;
|
||||
uint32_t confirm_window_us = 0;
|
||||
uint8_t armed = 0; /* bit0: activation armed (ground ack seen) */
|
||||
|
||||
/* status */
|
||||
uint8_t role = 0; /* 0 = ground, 1 = drone */
|
||||
uint8_t state = 0; /* MigState */
|
||||
|
||||
/* confirm */
|
||||
uint16_t marker_count = 0, video_frames = 0;
|
||||
uint32_t first_marker_tsfl = 0;
|
||||
|
||||
/* abort / reason-carrying */
|
||||
uint8_t reason = 0; /* MigReason */
|
||||
uint8_t effective = 0; /* 0 = cancel pre-activation, 1 = rollback */
|
||||
|
||||
/* marker */
|
||||
uint32_t seq = 0;
|
||||
uint8_t marker_flags = 0; /* bit0 rollback, bit1 probe-return */
|
||||
|
||||
/* validation (#280) */
|
||||
uint8_t method = 0; /* 0 checks / 1 probe / 2 probation / 3 scout */
|
||||
uint8_t result = 0; /* 0 accept / 1 veto / 2 unknown */
|
||||
uint32_t obs_age_ms = 0, obs_dur_ms = 0, cca_delta = 0, fa_delta = 0;
|
||||
uint8_t igi = 0, nhm_busy_pct = 0, energy_valid = 0;
|
||||
uint16_t cost_est_ms = 0;
|
||||
|
||||
/* clock: the sender's TSF, stamped by the demo at send time */
|
||||
uint64_t tx_tsf = 0;
|
||||
};
|
||||
|
||||
/* An action the pure machine asks its host (the demo) to perform. The machine
|
||||
* itself does no I/O and no crypto — it returns a list of these from every
|
||||
* input; the host stamps tx_tsf, encodes+MACs a `msg`, and transmits. */
|
||||
struct MigAction {
|
||||
enum Kind : uint8_t {
|
||||
SendUnicast, /* msg -> the peer's unicast address (+ tx.report) */
|
||||
SendBroadcast, /* msg -> broadcast (status / markers) */
|
||||
RetuneTo, /* channel */
|
||||
StartDrain, /* stop the TX pump, drain/deadline-drop pending frames */
|
||||
ResumePump, /* resume the TX pump (probe return / post-switch) */
|
||||
ArmMarkers, /* channel = the channel; emit gen-tagged markers there */
|
||||
StopMarkers,
|
||||
EmitEvent, /* code = a MigReason or a state; for logging */
|
||||
GateNotify, /* code: 0=confirmed 1=rolledback — tell the #279 gate */
|
||||
Done, /* code: terminal result */
|
||||
} kind;
|
||||
MigMsg msg;
|
||||
ChannelDef channel;
|
||||
uint8_t code = 0;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_TYPES_H */
|
||||
@@ -0,0 +1,398 @@
|
||||
/* MigWire — the canonical, authenticated wire codec for the channel-migration
|
||||
* control protocol. Byte-packed little-endian (put/get helpers, no struct
|
||||
* casts — portable and KAT-stable, the HopSyncMarker style), every message
|
||||
* MAC'd with SipHash-2-4 (the codebase's existing primitive, src/HopSchedule.h)
|
||||
* under a control key domain-separated from any hop/link key.
|
||||
*
|
||||
* Anti-replay is structural: epochs are random per process start and never
|
||||
* persisted, so a restart orphans every in-flight generation for free (there
|
||||
* is no persisted in-flight state at all). A receiver adopts a peer epoch only
|
||||
* from a PROPOSAL/STATUS, tracks the max generation, and binds COMMIT/CONFIRM
|
||||
* to the nonce it issued — so a replayed old exchange can never be acked by
|
||||
* the current peer, and since the drone activates only after an ack, a replay
|
||||
* can never move it.
|
||||
*
|
||||
* Every message is <= 96 bytes (asserted in the KAT), so a control frame is
|
||||
* ~120 µs of 6M air. Pure, header-only, selftested. */
|
||||
#ifndef DEVOURER_CHANMIG_MIG_WIRE_H
|
||||
#define DEVOURER_CHANMIG_MIG_WIRE_H
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "HopSchedule.h"
|
||||
#include "chanmig/ChannelDef.h"
|
||||
#include "chanmig/MigTypes.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
inline constexpr uint16_t kMigMagic = 0x4D43; /* bytes 0x43 0x4D = "CM" */
|
||||
inline constexpr uint8_t kMigVersion = 1;
|
||||
inline constexpr size_t kMigHeader = 8; /* magic(2) ver(1) type(1) link(4) */
|
||||
inline constexpr size_t kMigMacLen = 8;
|
||||
inline constexpr size_t kMigMaxLen = 96;
|
||||
|
||||
/* 16-byte control key, domain-separated from a master seed. */
|
||||
struct MigKey {
|
||||
std::array<uint8_t, 16> k{};
|
||||
static MigKey derive(const HopSchedule::Key &master) {
|
||||
MigKey out;
|
||||
static const uint8_t d0[] = {'d', 'e', 'v', 'o', 'u', 'r', 'e', 'r',
|
||||
'-', 'm', 'i', 'g', '-', 'c', '0'};
|
||||
static const uint8_t d1[] = {'d', 'e', 'v', 'o', 'u', 'r', 'e', 'r',
|
||||
'-', 'm', 'i', 'g', '-', 'c', '1'};
|
||||
const uint64_t lo = HopSchedule::siphash24(master, d0, sizeof(d0));
|
||||
const uint64_t hi = HopSchedule::siphash24(master, d1, sizeof(d1));
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out.k[i] = static_cast<uint8_t>(lo >> (8 * i));
|
||||
out.k[8 + i] = static_cast<uint8_t>(hi >> (8 * i));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/* From DEVOURER_MIG_KEY hex text (reuses the hop seed parser). */
|
||||
static MigKey from_seed(const char *text) {
|
||||
return derive(HopSchedule::parse_seed(text));
|
||||
}
|
||||
uint64_t mac(const uint8_t *p, size_t n) const {
|
||||
return HopSchedule::siphash24(k, p, n);
|
||||
}
|
||||
};
|
||||
|
||||
namespace wire {
|
||||
inline void p8(std::vector<uint8_t> &b, uint8_t v) { b.push_back(v); }
|
||||
inline void p16(std::vector<uint8_t> &b, uint16_t v) {
|
||||
b.push_back(uint8_t(v));
|
||||
b.push_back(uint8_t(v >> 8));
|
||||
}
|
||||
inline void p32(std::vector<uint8_t> &b, uint32_t v) {
|
||||
for (int i = 0; i < 4; i++)
|
||||
b.push_back(uint8_t(v >> (8 * i)));
|
||||
}
|
||||
inline void p64(std::vector<uint8_t> &b, uint64_t v) {
|
||||
for (int i = 0; i < 8; i++)
|
||||
b.push_back(uint8_t(v >> (8 * i)));
|
||||
}
|
||||
inline void pdef(std::vector<uint8_t> &b, const ChannelDef &d) {
|
||||
p8(b, d.band);
|
||||
p8(b, d.primary);
|
||||
p8(b, static_cast<uint8_t>(d.center_mhz() >= 5000
|
||||
? (d.center_mhz() - 5000) / 5
|
||||
: (d.center_mhz() - 2407) / 5));
|
||||
p8(b, static_cast<uint8_t>(d.width));
|
||||
p8(b, d.offset);
|
||||
p8(b, static_cast<uint8_t>((d.no_ir ? 1 : 0) | (d.dfs ? 2 : 0) |
|
||||
(d.backup ? 4 : 0)));
|
||||
}
|
||||
inline uint8_t g8(const uint8_t *p, size_t &o) { return p[o++]; }
|
||||
inline uint16_t g16(const uint8_t *p, size_t &o) {
|
||||
uint16_t v = uint16_t(p[o]) | uint16_t(p[o + 1]) << 8;
|
||||
o += 2;
|
||||
return v;
|
||||
}
|
||||
inline uint32_t g32(const uint8_t *p, size_t &o) {
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < 4; i++)
|
||||
v |= uint32_t(p[o + i]) << (8 * i);
|
||||
o += 4;
|
||||
return v;
|
||||
}
|
||||
inline uint64_t g64(const uint8_t *p, size_t &o) {
|
||||
uint64_t v = 0;
|
||||
for (int i = 0; i < 8; i++)
|
||||
v |= uint64_t(p[o + i]) << (8 * i);
|
||||
o += 8;
|
||||
return v;
|
||||
}
|
||||
inline ChannelDef gdef(const uint8_t *p, size_t &o) {
|
||||
ChannelDef d;
|
||||
d.band = g8(p, o);
|
||||
d.primary = g8(p, o);
|
||||
(void)g8(p, o); /* center: derived + re-validated, carried for cross-check */
|
||||
d.width = static_cast<ChannelWidth_t>(g8(p, o));
|
||||
d.offset = g8(p, o);
|
||||
const uint8_t fl = g8(p, o);
|
||||
d.no_ir = fl & 1;
|
||||
d.dfs = fl & 2;
|
||||
d.backup = fl & 4;
|
||||
return d;
|
||||
}
|
||||
} /* namespace wire */
|
||||
|
||||
/* Finish a partially-built frame: append the SipHash MAC over everything so
|
||||
* far, returning the complete frame. */
|
||||
inline std::vector<uint8_t> mig_seal(std::vector<uint8_t> b, const MigKey &key) {
|
||||
const uint64_t mac = key.mac(b.data(), b.size());
|
||||
wire::p64(b, mac);
|
||||
return b;
|
||||
}
|
||||
|
||||
inline void mig_header(std::vector<uint8_t> &b, MigMsgType t, uint32_t link_id) {
|
||||
wire::p16(b, kMigMagic);
|
||||
wire::p8(b, kMigVersion);
|
||||
wire::p8(b, static_cast<uint8_t>(t));
|
||||
wire::p32(b, link_id);
|
||||
}
|
||||
|
||||
/* --- per-type encoders (input is a fully-populated MigMsg) --- */
|
||||
inline std::vector<uint8_t> mig_encode(const MigMsg &m, const MigKey &key) {
|
||||
std::vector<uint8_t> b;
|
||||
mig_header(b, m.type, m.link_id);
|
||||
switch (m.type) {
|
||||
case MT_PROPOSAL:
|
||||
wire::p32(b, m.ground_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::pdef(b, m.source);
|
||||
wire::pdef(b, m.target);
|
||||
wire::p32(b, m.evidence_gen);
|
||||
wire::p64(b, m.evidence_digest);
|
||||
wire::p64(b, m.earliest_tsf);
|
||||
wire::p64(b, m.latest_tsf);
|
||||
wire::p8(b, m.fallback_mode);
|
||||
wire::pdef(b, m.rescue);
|
||||
wire::p32(b, m.ground_nonce);
|
||||
break;
|
||||
case MT_COMMIT:
|
||||
wire::p32(b, m.drone_epoch);
|
||||
wire::p32(b, m.ground_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::pdef(b, m.target);
|
||||
wire::p64(b, m.activate_tsf);
|
||||
wire::p64(b, m.tx_tsf);
|
||||
wire::p32(b, m.confirm_window_us);
|
||||
wire::p64(b, m.rollback_deadline_tsf);
|
||||
wire::pdef(b, m.rescue);
|
||||
wire::p32(b, m.ground_nonce_echo);
|
||||
wire::p32(b, m.drone_nonce);
|
||||
wire::p8(b, m.armed);
|
||||
break;
|
||||
case MT_STATUS:
|
||||
wire::p8(b, m.role);
|
||||
wire::p32(b, m.sender_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::p8(b, m.state);
|
||||
wire::pdef(b, m.current);
|
||||
wire::p64(b, m.tx_tsf);
|
||||
wire::p8(b, m.reason);
|
||||
wire::p32(b, m.peer_nonce_echo);
|
||||
break;
|
||||
case MT_CONFIRM:
|
||||
wire::p32(b, m.ground_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::p32(b, m.drone_nonce_echo);
|
||||
wire::p16(b, m.marker_count);
|
||||
wire::p16(b, m.video_frames);
|
||||
wire::p32(b, m.first_marker_tsfl);
|
||||
break;
|
||||
case MT_ABORT:
|
||||
wire::p8(b, m.role);
|
||||
wire::p32(b, m.sender_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::p8(b, m.reason);
|
||||
wire::p8(b, m.effective);
|
||||
wire::p64(b, m.tx_tsf);
|
||||
break;
|
||||
case MT_MARKER:
|
||||
wire::p32(b, m.drone_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::p32(b, m.seq);
|
||||
wire::pdef(b, m.aired_on);
|
||||
wire::p8(b, m.marker_flags);
|
||||
wire::p64(b, m.tx_tsf);
|
||||
break;
|
||||
case MT_VALIDATION:
|
||||
wire::p32(b, m.drone_epoch);
|
||||
wire::p32(b, m.generation);
|
||||
wire::pdef(b, m.target);
|
||||
wire::p8(b, m.method);
|
||||
wire::p8(b, m.result);
|
||||
wire::p8(b, m.reason);
|
||||
wire::p32(b, m.obs_age_ms);
|
||||
wire::p32(b, m.obs_dur_ms);
|
||||
wire::p32(b, m.cca_delta);
|
||||
wire::p32(b, m.fa_delta);
|
||||
wire::p8(b, m.igi);
|
||||
wire::p8(b, m.nhm_busy_pct);
|
||||
wire::p8(b, m.energy_valid);
|
||||
wire::p16(b, m.cost_est_ms);
|
||||
wire::p64(b, m.tx_tsf);
|
||||
break;
|
||||
}
|
||||
return mig_seal(std::move(b), key);
|
||||
}
|
||||
|
||||
/* Decode + authenticate. Returns MigReason::None on success (out filled), or
|
||||
* the specific rejection. link_id 0 skips the link check (KATs). */
|
||||
inline MigReason mig_decode(const uint8_t *p, size_t n, const MigKey &key,
|
||||
uint32_t expect_link, MigMsg &out) {
|
||||
/* n may exceed the message length: an on-air RX frame carries a trailing
|
||||
* 4-byte FCS (and some parsers pad), so the message occupies a PREFIX of the
|
||||
* buffer. The body length is fixed per type, so the decoder advances `o`
|
||||
* through the fixed fields, then locates the MAC right after — any bytes
|
||||
* beyond that (FCS/pad) are ignored. The upper bound allows the message +
|
||||
* a small trailer. */
|
||||
if (n < kMigHeader + kMigMacLen || n > kMigMaxLen + 8)
|
||||
return MigReason::Truncated;
|
||||
size_t o = 0;
|
||||
if (wire::g16(p, o) != kMigMagic)
|
||||
return MigReason::BadType;
|
||||
if (wire::g8(p, o) != kMigVersion)
|
||||
return MigReason::BadVersion;
|
||||
const uint8_t type = wire::g8(p, o);
|
||||
const uint32_t link = wire::g32(p, o);
|
||||
if (type < MT_PROPOSAL || type > MT_VALIDATION)
|
||||
return MigReason::BadType;
|
||||
if (expect_link != 0 && link != expect_link)
|
||||
return MigReason::BadLinkId;
|
||||
|
||||
out = MigMsg{};
|
||||
out.type = static_cast<MigMsgType>(type);
|
||||
out.link_id = link;
|
||||
/* A per-type body reader; `o` ends at the byte after the fixed body, where
|
||||
* the MAC begins. A body that would read past the buffer is a truncation
|
||||
* (guarded after the switch). */
|
||||
switch (type) {
|
||||
case MT_PROPOSAL:
|
||||
out.ground_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.source = wire::gdef(p, o);
|
||||
out.target = wire::gdef(p, o);
|
||||
out.evidence_gen = wire::g32(p, o);
|
||||
out.evidence_digest = wire::g64(p, o);
|
||||
out.earliest_tsf = wire::g64(p, o);
|
||||
out.latest_tsf = wire::g64(p, o);
|
||||
out.fallback_mode = wire::g8(p, o);
|
||||
out.rescue = wire::gdef(p, o);
|
||||
out.ground_nonce = wire::g32(p, o);
|
||||
break;
|
||||
case MT_COMMIT:
|
||||
out.drone_epoch = wire::g32(p, o);
|
||||
out.ground_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.target = wire::gdef(p, o);
|
||||
out.activate_tsf = wire::g64(p, o);
|
||||
out.tx_tsf = wire::g64(p, o);
|
||||
out.confirm_window_us = wire::g32(p, o);
|
||||
out.rollback_deadline_tsf = wire::g64(p, o);
|
||||
out.rescue = wire::gdef(p, o);
|
||||
out.ground_nonce_echo = wire::g32(p, o);
|
||||
out.drone_nonce = wire::g32(p, o);
|
||||
out.armed = wire::g8(p, o);
|
||||
break;
|
||||
case MT_STATUS:
|
||||
out.role = wire::g8(p, o);
|
||||
out.sender_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.state = wire::g8(p, o);
|
||||
out.current = wire::gdef(p, o);
|
||||
out.tx_tsf = wire::g64(p, o);
|
||||
out.reason = wire::g8(p, o);
|
||||
out.peer_nonce_echo = wire::g32(p, o);
|
||||
break;
|
||||
case MT_CONFIRM:
|
||||
out.ground_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.drone_nonce_echo = wire::g32(p, o);
|
||||
out.marker_count = wire::g16(p, o);
|
||||
out.video_frames = wire::g16(p, o);
|
||||
out.first_marker_tsfl = wire::g32(p, o);
|
||||
break;
|
||||
case MT_ABORT:
|
||||
out.role = wire::g8(p, o);
|
||||
out.sender_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.reason = wire::g8(p, o);
|
||||
out.effective = wire::g8(p, o);
|
||||
out.tx_tsf = wire::g64(p, o);
|
||||
break;
|
||||
case MT_MARKER:
|
||||
out.drone_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.seq = wire::g32(p, o);
|
||||
out.aired_on = wire::gdef(p, o);
|
||||
out.marker_flags = wire::g8(p, o);
|
||||
out.tx_tsf = wire::g64(p, o);
|
||||
break;
|
||||
case MT_VALIDATION:
|
||||
out.drone_epoch = wire::g32(p, o);
|
||||
out.generation = wire::g32(p, o);
|
||||
out.target = wire::gdef(p, o);
|
||||
out.method = wire::g8(p, o);
|
||||
out.result = wire::g8(p, o);
|
||||
out.reason = wire::g8(p, o);
|
||||
out.obs_age_ms = wire::g32(p, o);
|
||||
out.obs_dur_ms = wire::g32(p, o);
|
||||
out.cca_delta = wire::g32(p, o);
|
||||
out.fa_delta = wire::g32(p, o);
|
||||
out.igi = wire::g8(p, o);
|
||||
out.nhm_busy_pct = wire::g8(p, o);
|
||||
out.energy_valid = wire::g8(p, o);
|
||||
out.cost_est_ms = wire::g16(p, o);
|
||||
out.tx_tsf = wire::g64(p, o);
|
||||
break;
|
||||
}
|
||||
/* the MAC sits immediately after the fixed body; trailing bytes (FCS/pad)
|
||||
* are ignored. Verify over exactly [0..o). */
|
||||
if (o + kMigMacLen > n)
|
||||
return MigReason::Truncated; /* body ran past the buffer */
|
||||
const uint64_t want = key.mac(p, o);
|
||||
size_t mo = o;
|
||||
const uint64_t got = wire::g64(p, mo);
|
||||
if (want != got)
|
||||
return MigReason::BadMac;
|
||||
return MigReason::None;
|
||||
}
|
||||
|
||||
/* Anti-replay window: what a receiver remembers about one peer. Epochs are
|
||||
* random per boot (the caller seeds them from std::random_device), never
|
||||
* persisted. */
|
||||
struct ReplayWindow {
|
||||
bool have_peer = false;
|
||||
uint32_t peer_epoch = 0;
|
||||
uint32_t max_gen = 0;
|
||||
uint32_t in_flight_gen = 0; /* 0 = none in flight */
|
||||
|
||||
/* Adopt/verify a peer epoch. Only PROPOSAL/STATUS may introduce a new
|
||||
* epoch; a new epoch resets the generation ceiling (a fresh process). */
|
||||
bool accept_epoch(uint32_t epoch, bool may_introduce) {
|
||||
if (!have_peer) {
|
||||
if (!may_introduce)
|
||||
return false;
|
||||
have_peer = true;
|
||||
peer_epoch = epoch;
|
||||
max_gen = 0;
|
||||
in_flight_gen = 0;
|
||||
return true;
|
||||
}
|
||||
if (epoch == peer_epoch)
|
||||
return true;
|
||||
if (may_introduce) { /* peer restarted */
|
||||
peer_epoch = epoch;
|
||||
max_gen = 0;
|
||||
in_flight_gen = 0;
|
||||
return true;
|
||||
}
|
||||
return false; /* unknown epoch on a non-introducing message */
|
||||
}
|
||||
|
||||
/* A proposal's generation: reject a replay (< max), idempotent re-answer
|
||||
* (== in-flight), or a fresh exchange (> max). Returns:
|
||||
* 0 = replay (reject), 1 = idempotent, 2 = fresh (adopt as in-flight). */
|
||||
int classify_proposal(uint32_t gen) {
|
||||
if (in_flight_gen != 0 && gen == in_flight_gen)
|
||||
return 1;
|
||||
if (gen <= max_gen)
|
||||
return 0;
|
||||
max_gen = gen;
|
||||
in_flight_gen = gen;
|
||||
return 2;
|
||||
}
|
||||
void clear_in_flight() { in_flight_gen = 0; }
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_MIG_WIRE_H */
|
||||
@@ -0,0 +1,131 @@
|
||||
/* PrimaryFeed — turn the primary receiver's JSONL stream into ActiveLinkWindow
|
||||
* records the RecommendEngine consumes.
|
||||
*
|
||||
* The primary receiver (rxdemo parked on the video channel) is a SEPARATE
|
||||
* process; its stdout is redirected to a file the scout tail-follows. Its
|
||||
* relevant events:
|
||||
* rx.txhit per canonical-SA frame — seq feeds the loss estimator
|
||||
* rx.quality windowed verdict + rssi/snr/evm (DEVOURER_RXQUALITY)
|
||||
* link.health windowed verdict (DEVOURER_LINKHEALTH)
|
||||
* rx.energy window boundary + crc_err/icv_err (DEVOURER_RX_KEEP_CORRUPTED)
|
||||
* A windowed event (rx.quality preferred, else link.health) closes an
|
||||
* ActiveLinkWindow: the frames seen since the last close become its delivery,
|
||||
* the verdict its fault domain. Pure line-in / windows-out — no file I/O
|
||||
* (the demo does the tailing) and no clock (the caller stamps arrival time).
|
||||
*
|
||||
* Never a FIFO on the producer side: a wedged scout must not be able to block
|
||||
* the primary video receiver, so the contract is an append-only file the
|
||||
* scout polls. */
|
||||
#ifndef DEVOURER_CHANMIG_PRIMARY_FEED_H
|
||||
#define DEVOURER_CHANMIG_PRIMARY_FEED_H
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include "LinkHealth.h"
|
||||
#include "chanmig/ActiveLink.h"
|
||||
#include "chanmig/JsonlLite.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
inline LinkVerdict verdict_from_label(std::string_view s) {
|
||||
if (s == "HEALTHY")
|
||||
return LinkVerdict::Healthy;
|
||||
if (s == "SATURATED")
|
||||
return LinkVerdict::Saturated;
|
||||
if (s == "INTERFERENCE")
|
||||
return LinkVerdict::Interference;
|
||||
if (s == "WEAK")
|
||||
return LinkVerdict::Weak;
|
||||
if (s == "MARGINAL")
|
||||
return LinkVerdict::Marginal;
|
||||
return LinkVerdict::NoSignal;
|
||||
}
|
||||
|
||||
class PrimaryFeedReader {
|
||||
public:
|
||||
/* Feed one line; returns true and fills `out` when this line closed a
|
||||
* window. arrival_ms is the scout's own monotonic clock at read time (the
|
||||
* two processes share no clock; window granularity dwarfs the skew). */
|
||||
bool line(std::string_view l, int64_t arrival_ms, ActiveLinkWindow &out) {
|
||||
if (jsonl_ev_is(l, "rx.txhit")) {
|
||||
long long seq;
|
||||
if (jsonl_int(l, "seq", &seq))
|
||||
seq_.observe(static_cast<uint16_t>(seq));
|
||||
++frames_since_;
|
||||
saw_frames_ = true;
|
||||
return false;
|
||||
}
|
||||
if (jsonl_ev_is(l, "rx.energy")) {
|
||||
long long v;
|
||||
if (jsonl_int(l, "crc_err", &v)) {
|
||||
crc_ += static_cast<uint32_t>(v);
|
||||
have_crc_ = true;
|
||||
}
|
||||
if (jsonl_int(l, "icv_err", &v))
|
||||
icv_ += static_cast<uint32_t>(v);
|
||||
return false;
|
||||
}
|
||||
const bool q = jsonl_ev_is(l, "rx.quality");
|
||||
const bool h = !q && jsonl_ev_is(l, "link.health");
|
||||
if (!q && !h)
|
||||
return false;
|
||||
/* link.health is skipped when rx.quality is also on (avoid double-closing
|
||||
* one window); prefer rx.quality's richer fields. */
|
||||
if (h && seen_quality_)
|
||||
return false;
|
||||
if (q)
|
||||
seen_quality_ = true;
|
||||
|
||||
out = ActiveLinkWindow{};
|
||||
out.t_ms = arrival_ms;
|
||||
out.telemetry_ok = true;
|
||||
std::string label;
|
||||
if (jsonl_str(l, "verdict", &label)) {
|
||||
out.have_quality = true;
|
||||
out.verdict = verdict_from_label(label);
|
||||
}
|
||||
double d;
|
||||
if (jsonl_num(l, "rssi_max_dbm", &d))
|
||||
out.rssi_max_dbm = static_cast<int>(d);
|
||||
else if (jsonl_num(l, "rssi_dbm", &d))
|
||||
out.rssi_max_dbm = static_cast<int>(d);
|
||||
if (jsonl_num(l, "snr_mean_db", &d))
|
||||
out.snr_mean_db = d;
|
||||
else if (jsonl_num(l, "snr_db", &d))
|
||||
out.snr_mean_db = d;
|
||||
if (jsonl_num(l, "evm_db", &d))
|
||||
out.evm_mean_db = d;
|
||||
|
||||
if (saw_frames_) {
|
||||
out.have_delivery = true;
|
||||
out.delivered = seq_.delivered();
|
||||
out.expected = seq_.expected();
|
||||
}
|
||||
if (have_crc_) {
|
||||
out.have_crc = true;
|
||||
out.crc_err = crc_;
|
||||
out.icv_err = icv_;
|
||||
}
|
||||
/* reset per-window accumulators */
|
||||
seq_.reset();
|
||||
frames_since_ = 0;
|
||||
saw_frames_ = false;
|
||||
crc_ = icv_ = 0;
|
||||
have_crc_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
SeqLossEstimator seq_;
|
||||
uint32_t frames_since_ = 0, crc_ = 0, icv_ = 0;
|
||||
bool saw_frames_ = false, have_crc_ = false, seen_quality_ = false;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_PRIMARY_FEED_H */
|
||||
@@ -0,0 +1,203 @@
|
||||
/* ScanScheduler — the pure dwell scheduler behind the chanscout demo.
|
||||
*
|
||||
* The scout surveys CANDIDATES but tunes 20 MHz BINS (a 40/80 MHz candidate
|
||||
* is its constituent bins; two candidates sharing a bin share its evidence).
|
||||
* Each bin carries a revisit deadline: bins belonging to a preferred-backup
|
||||
* candidate get the fast cadence, everything else the background cadence, and
|
||||
* next() always returns the most-overdue bin — so the scout scans at 100%
|
||||
* duty while backup bins are simply revisited more often. Deterministic:
|
||||
* deadline order, ties broken by plan position; no clock reads (the caller
|
||||
* passes now), no RNG.
|
||||
*
|
||||
* The round counter advances only when EVERY bin has been successfully
|
||||
* observed since the last advance. That is the structural anti-positive-
|
||||
* feedback guard: backup favoritism can never starve the full rescan a
|
||||
* scoring policy's min-rounds gate keys on.
|
||||
*
|
||||
* Wide candidates optionally get a periodic full-width verification dwell
|
||||
* (the demo pays a full SetMonitorChannel for it); those ride their own
|
||||
* cadence and never count toward bin coverage. */
|
||||
#ifndef DEVOURER_CHANMIG_SCAN_PLAN_H
|
||||
#define DEVOURER_CHANMIG_SCAN_PLAN_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
struct ScanPlanConfig {
|
||||
std::vector<ChannelDef> candidates; /* immutable for the process lifetime */
|
||||
int dwell_ms = 100;
|
||||
int settle_ms = 30;
|
||||
int backup_revisit_ms = 1000; /* bins of backup candidates */
|
||||
int bg_revisit_ms = 5000; /* everything else */
|
||||
int fail_retry_ms = 250; /* deadline pushback after a failed dwell */
|
||||
int fullwidth_ms = 0; /* 0 = no wide verification dwells */
|
||||
int64_t max_age_ms = 60000; /* evidence-freshness bound (consumers) */
|
||||
|
||||
/* Stable identity of the whole plan (candidates + cadences). Emitted in
|
||||
* scout.plan and stamped into every record so a consumer can refuse to fold
|
||||
* records produced under a different plan. FNV-1a over the canonical
|
||||
* candidate formats and the cadence fields. */
|
||||
uint32_t plan_hash() const {
|
||||
uint32_t h = 2166136261u;
|
||||
auto fold = [&h](const void *p, size_t n) {
|
||||
const uint8_t *b = static_cast<const uint8_t *>(p);
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
h ^= b[i];
|
||||
h *= 16777619u;
|
||||
}
|
||||
};
|
||||
for (const ChannelDef &c : candidates) {
|
||||
const uint32_t k = c.key();
|
||||
const uint8_t fl = static_cast<uint8_t>((c.backup ? 1 : 0) |
|
||||
(c.no_ir ? 2 : 0) |
|
||||
(c.dfs ? 4 : 0));
|
||||
fold(&k, sizeof(k));
|
||||
fold(&fl, 1);
|
||||
}
|
||||
const int32_t cad[4] = {dwell_ms, settle_ms, backup_revisit_ms,
|
||||
bg_revisit_ms};
|
||||
fold(cad, sizeof(cad));
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
class ScanScheduler {
|
||||
public:
|
||||
struct DwellPlan {
|
||||
bool valid = false;
|
||||
uint8_t bin_ch = 0;
|
||||
ChannelDef def; /* what to tune: 20 MHz bin def, or the wide candidate
|
||||
when full_width */
|
||||
uint64_t round = 0;
|
||||
bool full_width = false;
|
||||
int plan_index = -1; /* internal: bin slot / wide-candidate slot */
|
||||
};
|
||||
|
||||
explicit ScanScheduler(const ScanPlanConfig &cfg) : cfg_(cfg) {
|
||||
for (size_t ci = 0; ci < cfg_.candidates.size(); ++ci) {
|
||||
const ChannelDef &c = cfg_.candidates[ci];
|
||||
uint8_t bins[4];
|
||||
const int n = constituent_bins(c, bins);
|
||||
const int cadence =
|
||||
c.backup ? cfg_.backup_revisit_ms : cfg_.bg_revisit_ms;
|
||||
for (int i = 0; i < n; i++) {
|
||||
Bin *b = find_bin(bins[i]);
|
||||
if (b == nullptr) {
|
||||
bins_.push_back(Bin{bins[i], c.band, cadence, INT64_MIN, false, 0});
|
||||
} else if (cadence < b->cadence_ms) {
|
||||
b->cadence_ms = cadence; /* fastest containing candidate wins */
|
||||
}
|
||||
}
|
||||
if (c.width == CHANNEL_WIDTH_40 || c.width == CHANNEL_WIDTH_80)
|
||||
wide_.push_back(static_cast<int>(ci));
|
||||
}
|
||||
}
|
||||
|
||||
size_t bin_count() const { return bins_.size(); }
|
||||
uint64_t rounds_complete() const { return rounds_; }
|
||||
int consecutive_failures() const { return consec_fail_; }
|
||||
|
||||
/* Pick the next dwell: the periodic wide verification dwell when due,
|
||||
* otherwise the most-overdue bin (ties by plan position — which also makes
|
||||
* the very first sweep visit every bin exactly once in plan order, since
|
||||
* all deadlines start equal). */
|
||||
DwellPlan next(int64_t now_ms) {
|
||||
DwellPlan p;
|
||||
if (bins_.empty())
|
||||
return p;
|
||||
/* Arm the wide-dwell cadence off the first call, so the initial full
|
||||
* sweep is always plain bins. */
|
||||
if (next_wide_ms_ == INT64_MIN)
|
||||
next_wide_ms_ = now_ms + cfg_.fullwidth_ms;
|
||||
if (cfg_.fullwidth_ms > 0 && !wide_.empty() && now_ms >= next_wide_ms_) {
|
||||
const int ci = wide_[wide_rr_ % wide_.size()];
|
||||
p.valid = true;
|
||||
p.full_width = true;
|
||||
p.def = cfg_.candidates[static_cast<size_t>(ci)];
|
||||
p.bin_ch = p.def.primary;
|
||||
p.round = rounds_;
|
||||
p.plan_index = ci;
|
||||
return p;
|
||||
}
|
||||
int best = 0;
|
||||
for (size_t i = 1; i < bins_.size(); ++i)
|
||||
if (bins_[i].deadline_ms < bins_[best].deadline_ms)
|
||||
best = static_cast<int>(i);
|
||||
const Bin &b = bins_[static_cast<size_t>(best)];
|
||||
p.valid = true;
|
||||
p.bin_ch = b.ch;
|
||||
p.def.band = b.band;
|
||||
p.def.primary = b.ch;
|
||||
p.def.width = CHANNEL_WIDTH_20;
|
||||
p.round = rounds_;
|
||||
p.plan_index = best;
|
||||
return p;
|
||||
}
|
||||
|
||||
void complete(const DwellPlan &p, int64_t now_ms, bool ok) {
|
||||
if (!p.valid)
|
||||
return;
|
||||
if (p.full_width) {
|
||||
wide_rr_++;
|
||||
next_wide_ms_ = now_ms + cfg_.fullwidth_ms;
|
||||
/* wide dwells never touch bin coverage or the failure streak */
|
||||
return;
|
||||
}
|
||||
if (p.plan_index < 0 || p.plan_index >= static_cast<int>(bins_.size()))
|
||||
return;
|
||||
Bin &b = bins_[static_cast<size_t>(p.plan_index)];
|
||||
if (ok) {
|
||||
b.deadline_ms = now_ms + b.cadence_ms;
|
||||
b.fails = 0;
|
||||
consec_fail_ = 0;
|
||||
if (!b.covered) {
|
||||
b.covered = true;
|
||||
if (++covered_n_ == bins_.size()) {
|
||||
++rounds_;
|
||||
covered_n_ = 0;
|
||||
for (Bin &x : bins_)
|
||||
x.covered = false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
b.deadline_ms = now_ms + cfg_.fail_retry_ms;
|
||||
++b.fails;
|
||||
++consec_fail_;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
struct Bin {
|
||||
uint8_t ch;
|
||||
uint8_t band;
|
||||
int cadence_ms;
|
||||
int64_t deadline_ms;
|
||||
bool covered;
|
||||
int fails;
|
||||
};
|
||||
Bin *find_bin(uint8_t ch) {
|
||||
for (Bin &b : bins_)
|
||||
if (b.ch == ch)
|
||||
return &b;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ScanPlanConfig cfg_;
|
||||
std::vector<Bin> bins_;
|
||||
std::vector<int> wide_;
|
||||
size_t covered_n_ = 0;
|
||||
uint64_t rounds_ = 0;
|
||||
size_t wide_rr_ = 0;
|
||||
int64_t next_wide_ms_ = INT64_MIN;
|
||||
int consec_fail_ = 0;
|
||||
};
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_SCAN_PLAN_H */
|
||||
@@ -0,0 +1,167 @@
|
||||
/* survey.dwell JSONL binding — the one place the record schema exists.
|
||||
*
|
||||
* chanscout emits through emit_survey_dwell(); every C++ consumer (the
|
||||
* advise-mode replay path, the aggregator selftest) parses through
|
||||
* survey_dwell_from_jsonl(). Keeping both directions in one header means the
|
||||
* schema cannot drift between producer and consumer, and the selftest
|
||||
* round-trips a record through both to pin it. Python consumers read the
|
||||
* same fields via tests/devourer_events.py.
|
||||
*
|
||||
* Nullable-field convention follows rx.energy: a chip counter the generation
|
||||
* doesn't expose is JSON null, never a fake zero — so "quiet channel" and
|
||||
* "sensor absent" stay distinguishable offline. */
|
||||
#ifndef DEVOURER_CHANMIG_SURVEY_JSONL_H
|
||||
#define DEVOURER_CHANMIG_SURVEY_JSONL_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "Event.h"
|
||||
#include "chanmig/JsonlLite.h"
|
||||
#include "chanmig/SurveyRecord.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
inline void emit_survey_dwell(EventSink &sink, const SurveyDwell &d) {
|
||||
Ev ev(sink, "survey.dwell");
|
||||
ev.f("v", kSurveySchemaV).f("seq", (unsigned long long)d.seq);
|
||||
char chan[20];
|
||||
d.def.format(chan, sizeof(chan));
|
||||
ev.f("chan", chan).f("round", (unsigned long long)d.round);
|
||||
ev.hexf("plan", d.plan_hash, 8);
|
||||
ev.f("start_ms", (long long)d.t_start_ms)
|
||||
.f("end_ms", (long long)d.t_end_ms)
|
||||
.f("retune_us", (long long)d.retune_us)
|
||||
.f("settle_ms", d.settle_ms)
|
||||
.f("observe_ms", (long long)d.observe_ms);
|
||||
if (d.valid_fa)
|
||||
ev.f("cca_ofdm", d.cca_ofdm)
|
||||
.f("cca_cck", d.cca_cck)
|
||||
.f("fa_ofdm", d.fa_ofdm)
|
||||
.f("fa_cck", d.fa_cck);
|
||||
else
|
||||
ev.f("cca_ofdm", nullptr)
|
||||
.f("cca_cck", nullptr)
|
||||
.f("fa_ofdm", nullptr)
|
||||
.f("fa_cck", nullptr);
|
||||
if (d.valid_igi)
|
||||
ev.f("igi", d.igi);
|
||||
else
|
||||
ev.f("igi", nullptr);
|
||||
if (d.valid_nhm) {
|
||||
int hist[12];
|
||||
for (int i = 0; i < 12; i++)
|
||||
hist[i] = d.nhm[i];
|
||||
ev.f("nhm_busy", d.nhm_busy_pct)
|
||||
.f("nhm_peak", d.nhm_peak)
|
||||
.f("nhm_dur", d.nhm_dur)
|
||||
.arr("nhm", hist, 12);
|
||||
} else {
|
||||
ev.f("nhm_busy", nullptr);
|
||||
}
|
||||
ev.f("frames", d.frames)
|
||||
.f("rssi_mean", d.rssi_mean_raw)
|
||||
.f("rssi_max", d.rssi_max_raw)
|
||||
.f("snr_mean", d.snr_mean_raw)
|
||||
.f("snr_min", d.snr_min_raw);
|
||||
if (d.evm_valid)
|
||||
ev.f("evm_mean", d.evm_mean_raw);
|
||||
else
|
||||
ev.f("evm_mean", nullptr);
|
||||
ev.f("dvr_frames", d.dvr_frames)
|
||||
.f("dvr_air_us", (unsigned long long)d.dvr_air_us)
|
||||
.f("oth_air_us", (unsigned long long)d.oth_air_us)
|
||||
.f("flags", d.flags);
|
||||
ev.hexf("scout_id", d.scout_id, 8);
|
||||
ev.f("agen", d.adapter_gen);
|
||||
}
|
||||
|
||||
/* Parse one survey.dwell line. False for any other event line, a schema
|
||||
* version this build doesn't know, or an unparseable channel token. */
|
||||
inline bool survey_dwell_from_jsonl(std::string_view line, SurveyDwell &d) {
|
||||
if (!jsonl_ev_is(line, "survey.dwell"))
|
||||
return false;
|
||||
long long v = 0;
|
||||
if (!jsonl_int(line, "v", &v) || v != kSurveySchemaV)
|
||||
return false;
|
||||
d = SurveyDwell{};
|
||||
std::string chan, err, hex;
|
||||
if (!jsonl_str(line, "chan", &chan) || !parse_chan_token(chan, d.def, err))
|
||||
return false;
|
||||
long long x = 0;
|
||||
if (jsonl_int(line, "seq", &x))
|
||||
d.seq = static_cast<uint64_t>(x);
|
||||
if (jsonl_int(line, "round", &x))
|
||||
d.round = static_cast<uint64_t>(x);
|
||||
if (jsonl_str(line, "plan", &hex))
|
||||
d.plan_hash = static_cast<uint32_t>(std::strtoul(hex.c_str(), nullptr, 16));
|
||||
if (jsonl_int(line, "start_ms", &x))
|
||||
d.t_start_ms = x;
|
||||
if (jsonl_int(line, "end_ms", &x))
|
||||
d.t_end_ms = x;
|
||||
if (jsonl_int(line, "retune_us", &x))
|
||||
d.retune_us = x;
|
||||
if (jsonl_int(line, "settle_ms", &x))
|
||||
d.settle_ms = static_cast<int>(x);
|
||||
if (jsonl_int(line, "observe_ms", &x))
|
||||
d.observe_ms = x;
|
||||
if (jsonl_int(line, "cca_ofdm", &x)) {
|
||||
d.valid_fa = true;
|
||||
d.cca_ofdm = static_cast<uint32_t>(x);
|
||||
if (jsonl_int(line, "cca_cck", &x))
|
||||
d.cca_cck = static_cast<uint32_t>(x);
|
||||
if (jsonl_int(line, "fa_ofdm", &x))
|
||||
d.fa_ofdm = static_cast<uint32_t>(x);
|
||||
if (jsonl_int(line, "fa_cck", &x))
|
||||
d.fa_cck = static_cast<uint32_t>(x);
|
||||
}
|
||||
if (jsonl_int(line, "igi", &x)) {
|
||||
d.valid_igi = true;
|
||||
d.igi = static_cast<uint8_t>(x);
|
||||
}
|
||||
if (jsonl_int(line, "nhm_busy", &x)) {
|
||||
d.valid_nhm = true;
|
||||
d.nhm_busy_pct = static_cast<uint8_t>(x);
|
||||
if (jsonl_int(line, "nhm_peak", &x))
|
||||
d.nhm_peak = static_cast<uint8_t>(x);
|
||||
if (jsonl_int(line, "nhm_dur", &x))
|
||||
d.nhm_dur = static_cast<uint16_t>(x);
|
||||
int hist[12] = {};
|
||||
int n = 0;
|
||||
if (jsonl_arr(line, "nhm", hist, 12, &n))
|
||||
for (int i = 0; i < n; i++)
|
||||
d.nhm[i] = static_cast<uint8_t>(hist[i]);
|
||||
}
|
||||
if (jsonl_int(line, "frames", &x))
|
||||
d.frames = static_cast<uint32_t>(x);
|
||||
if (jsonl_int(line, "rssi_mean", &x))
|
||||
d.rssi_mean_raw = static_cast<int>(x);
|
||||
if (jsonl_int(line, "rssi_max", &x))
|
||||
d.rssi_max_raw = static_cast<int>(x);
|
||||
if (jsonl_int(line, "snr_mean", &x))
|
||||
d.snr_mean_raw = static_cast<int>(x);
|
||||
if (jsonl_int(line, "snr_min", &x))
|
||||
d.snr_min_raw = static_cast<int>(x);
|
||||
if (jsonl_int(line, "evm_mean", &x)) {
|
||||
d.evm_valid = true;
|
||||
d.evm_mean_raw = static_cast<int>(x);
|
||||
}
|
||||
if (jsonl_int(line, "dvr_frames", &x))
|
||||
d.dvr_frames = static_cast<uint32_t>(x);
|
||||
if (jsonl_int(line, "dvr_air_us", &x))
|
||||
d.dvr_air_us = static_cast<uint64_t>(x);
|
||||
if (jsonl_int(line, "oth_air_us", &x))
|
||||
d.oth_air_us = static_cast<uint64_t>(x);
|
||||
if (jsonl_int(line, "flags", &x))
|
||||
d.flags = static_cast<uint16_t>(x);
|
||||
if (jsonl_str(line, "scout_id", &hex))
|
||||
d.scout_id = static_cast<uint32_t>(std::strtoul(hex.c_str(), nullptr, 16));
|
||||
if (jsonl_int(line, "agen", &x))
|
||||
d.adapter_gen = static_cast<uint8_t>(x);
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_SURVEY_JSONL_H */
|
||||
@@ -0,0 +1,128 @@
|
||||
/* SurveyDwell — the versioned record one scout dwell produces, and the
|
||||
* airtime approximation that splits decoded occupancy into "our own video"
|
||||
* vs "other traffic".
|
||||
*
|
||||
* A dwell is one visit to one 20 MHz bin (or, for the optional wide
|
||||
* verification dwell, one full-width candidate): retune → settle → discard
|
||||
* barrier (reset the chip's delta counters + drain frames still in the USB
|
||||
* pipeline from the previous channel) → observe → read. The FA/CCA fields
|
||||
* are therefore deltas over exactly the observe window — the counter hygiene
|
||||
* the plain rxdemo sweep does not do (its per-bin delta includes its own
|
||||
* retune+settle).
|
||||
*
|
||||
* Every field that can be invalid carries a flag bit instead of a fake zero:
|
||||
* a consumer must be able to tell "quiet channel" from "sensor absent" from
|
||||
* "dwell aborted". */
|
||||
#ifndef DEVOURER_CHANMIG_SURVEY_RECORD_H
|
||||
#define DEVOURER_CHANMIG_SURVEY_RECORD_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "chanmig/ChannelDef.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace chanmig {
|
||||
|
||||
inline constexpr int kSurveySchemaV = 1;
|
||||
|
||||
enum SurveyFlag : uint16_t {
|
||||
kFlagTruncated = 1u << 0, /* dwell cut short (shutdown) */
|
||||
kFlagRetuneFailed = 1u << 1, /* retune threw — no observation happened */
|
||||
kFlagReadFailed = 1u << 2, /* energy read invalid at dwell end */
|
||||
kFlagCounterSuspect = 1u << 3, /* delta implausible for the window (wrap) */
|
||||
kFlagNhmMissing = 1u << 4, /* generation exposes no NHM this dwell */
|
||||
kFlagFullWidth = 1u << 5, /* wide verification dwell (full retune) */
|
||||
};
|
||||
|
||||
struct SurveyDwell {
|
||||
uint64_t seq = 0; /* monotonic dwell counter — a gap = a lost record */
|
||||
ChannelDef def; /* what was tuned: a 20 MHz bin def, or the wide
|
||||
candidate when kFlagFullWidth */
|
||||
uint64_t round = 0; /* completed-full-sweep count at dwell time */
|
||||
uint32_t plan_hash = 0;
|
||||
|
||||
int64_t t_start_ms = 0; /* caller monotonic clock, dwell start (pre-retune) */
|
||||
int64_t t_end_ms = 0;
|
||||
int64_t retune_us = 0;
|
||||
int settle_ms = 0;
|
||||
int64_t observe_ms = 0; /* the valid observation window the deltas span */
|
||||
|
||||
/* Frame-free energy (deltas over observe; validity per source). */
|
||||
bool valid_fa = false;
|
||||
uint32_t fa_ofdm = 0, fa_cck = 0, cca_ofdm = 0, cca_cck = 0;
|
||||
bool valid_igi = false;
|
||||
uint8_t igi = 0;
|
||||
bool valid_nhm = false;
|
||||
uint8_t nhm[12] = {};
|
||||
uint16_t nhm_dur = 0;
|
||||
uint8_t nhm_busy_pct = 0; /* % of NHM samples above the lowest bucket */
|
||||
uint8_t nhm_peak = 0; /* fullest bucket index */
|
||||
|
||||
/* Frame-driven aggregate over the observe window (raw devourer units). */
|
||||
uint32_t frames = 0;
|
||||
int rssi_mean_raw = 0, rssi_max_raw = 0;
|
||||
int snr_mean_raw = 0, snr_min_raw = 0;
|
||||
int evm_mean_raw = 0;
|
||||
bool evm_valid = false;
|
||||
|
||||
/* Occupancy attribution: canonical-SA (our own video) vs everything else,
|
||||
* as decoded-airtime estimates. Undecodable energy shows only in FA/CCA/
|
||||
* NHM — that asymmetry is why the scoring layer treats these as a SPLIT of
|
||||
* explained occupancy, never as total occupancy. */
|
||||
uint32_t dvr_frames = 0;
|
||||
uint64_t dvr_air_us = 0;
|
||||
uint64_t oth_air_us = 0;
|
||||
|
||||
uint16_t flags = 0;
|
||||
uint32_t scout_id = 0; /* stable adapter identity — calibration domain */
|
||||
uint8_t adapter_gen = 0;
|
||||
};
|
||||
|
||||
/* Approximate on-air duration of one decoded frame from its DESC_RATE code:
|
||||
* preamble + payload bits at the code's data rate. Deliberately coarse (long
|
||||
* preamble assumed for CCK, one PPDU per MPDU, no aggregation accounting) —
|
||||
* it only SPLITS explained occupancy between transmitters, it is never an
|
||||
* absolute energy unit. `bw` is the rx-descriptor code (0=20,1=40,2=80). */
|
||||
inline uint32_t frame_airtime_us(uint16_t desc_rate, uint32_t len_bytes,
|
||||
uint8_t bw, bool sgi) {
|
||||
static const uint32_t kCck[4] = {1000, 2000, 5500, 11000};
|
||||
static const uint32_t kOfdm[8] = {6000, 9000, 12000, 18000,
|
||||
24000, 36000, 48000, 54000};
|
||||
static const uint32_t kMcs20[10] = {6500, 13000, 19500, 26000, 39000,
|
||||
52000, 58500, 65000, 78000, 86700};
|
||||
uint32_t kbps = 6000, preamble_us = 20;
|
||||
if (desc_rate <= 3) {
|
||||
kbps = kCck[desc_rate];
|
||||
preamble_us = 192;
|
||||
} else if (desc_rate <= 11) {
|
||||
kbps = kOfdm[desc_rate - 4];
|
||||
} else if (desc_rate <= 43) { /* HT MCS0..31 */
|
||||
const uint32_t mcs = desc_rate - 12;
|
||||
kbps = kMcs20[mcs % 8] * (mcs / 8 + 1);
|
||||
if (bw >= 1)
|
||||
kbps = kbps * 27 / 13; /* 40 MHz: 108/52 data subcarriers */
|
||||
preamble_us = 36;
|
||||
} else if (desc_rate <= 83) { /* VHT 1SS..4SS MCS0..9 */
|
||||
const uint32_t idx = desc_rate - 44;
|
||||
kbps = kMcs20[idx % 10] * (idx / 10 + 1);
|
||||
if (bw == 1)
|
||||
kbps = kbps * 27 / 13;
|
||||
else if (bw >= 2)
|
||||
kbps = kbps * 9 / 2; /* 80 MHz: 234/52 */
|
||||
preamble_us = 40;
|
||||
}
|
||||
if (sgi)
|
||||
kbps = kbps * 10 / 9;
|
||||
if (kbps == 0)
|
||||
kbps = 6000;
|
||||
const uint64_t bits = static_cast<uint64_t>(len_bytes) * 8u;
|
||||
uint64_t us = preamble_us + (bits * 1000u + kbps - 1) / kbps;
|
||||
if (us > 20000)
|
||||
us = 20000; /* one frame never plausibly exceeds ~20 ms of air */
|
||||
return static_cast<uint32_t>(us);
|
||||
}
|
||||
|
||||
} /* namespace chanmig */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_CHANMIG_SURVEY_RECORD_H */
|
||||
@@ -0,0 +1,126 @@
|
||||
# src/hopset/ — keyed FHSS, adaptive hopset, TX sensing
|
||||
|
||||
Deep facts for this subtree, loaded alongside the root CLAUDE.md. Everything
|
||||
here is header-only and pure (no device access, no env reads) and ctest-gated;
|
||||
the demos map the env vars. The device-side primitives these build on
|
||||
(`FastRetune`, `FastSetBandwidth`, the radiotap `CHANNEL` field) live in the
|
||||
core and are described in the root file. Article-length treatment:
|
||||
`docs/fhss.md`, `docs/frequency-hopping.md`, `docs/jammer-resilience.md`.
|
||||
|
||||
## Demo knobs
|
||||
|
||||
Hop set and pacing: `DEVOURER_HOP_CHANNELS` (SweepSpec grammar: `1,6,11`,
|
||||
`36-48/4`, `5170-5250/5` MHz) + `DEVOURER_HOP_DWELL_FRAMES` / `_ROUNDS` /
|
||||
`_FAST` / `_RADIOTAP` / `_BW` / `_OFFSET`. `DEVOURER_HOP_PROF=1` emits
|
||||
per-stage `debug.hop_prof` timing.
|
||||
|
||||
Keyed slot mode: `DEVOURER_HOP_SLOT_MS` (monotonic wall-clock slots) and
|
||||
`DEVOURER_HOP_SEED` (≤32 hex, a 128-bit key). `DEVOURER_HOP_SYNC_EVERY` is
|
||||
`streamtx`'s sync-marker cadence.
|
||||
|
||||
Adaptive: `DEVOURER_HOP_ADAPTIVE=1` (keyed slot mode only),
|
||||
`DEVOURER_HOP_ADAPTIVE_SCRIPT="slot:mask,..."`, `DEVOURER_HOP_MIN_ACTIVE`,
|
||||
`DEVOURER_HOP_POLICY=1`, `DEVOURER_HOP_PROBE_ROUNDS` (default 8, **must match
|
||||
both ends**), `DEVOURER_HOP_FUSION=rx|veto|either|failsafe`.
|
||||
|
||||
Sensing: `DEVOURER_TX_SENSE=1` + `_WINDOW_US` / `_POSTBURST_US` / `_SETTLE_US`
|
||||
/ `_EVERY` / `_NHM`.
|
||||
|
||||
## Keyed FHSS + lockstep RX
|
||||
|
||||
`src/HopSchedule.h`: the seed replaces the public round-robin with a stateless
|
||||
SipHash-2-4 Fisher-Yates permutation per round, so a receiver joins without RNG
|
||||
state. In slot mode the TX demos emit a sync marker (`txdemo` its beacon;
|
||||
`streamtx` its own frame every `DEVOURER_HOP_SYNC_EVERY`, FEC PSDU untouched),
|
||||
and `rxdemo` hops in lockstep when `DEVOURER_HOP_CHANNELS` + `_SLOT_MS` are set
|
||||
(seed optional → keyed/sequential), emitting `hop.rx` acquire/track/retune
|
||||
events.
|
||||
|
||||
## Adaptive hopset
|
||||
|
||||
The immutable base hopset carries a per-generation `active_mask`. **TX is the
|
||||
schedule authority**: RX proposes, TX commits an absolute future activation
|
||||
slot, repeated until it arrives, over SipHash-MAC'd Proposal/Commit/Status
|
||||
frames whose schedule and control keys are domain-separated from
|
||||
`DEVOURER_HOP_SEED`. Generation 0 ≡ the legacy fixed schedule byte-for-byte;
|
||||
gen ≥ 1 re-keys the permutation from (subkey, generation, round, mask).
|
||||
|
||||
Acquisition always scans the base hopset; the v2 sync marker advertises
|
||||
(generation, mask fp) so a follower that missed the commits recovers from the
|
||||
status beacon.
|
||||
|
||||
## Exclusion policy (`HopsetPolicy.h`)
|
||||
|
||||
Per-dwell delivery evidence drives conservative exclude/restore decisions.
|
||||
**Delivery is authoritative** — energy and link verdicts only classify. The
|
||||
guards, all deliberate:
|
||||
|
||||
- ≥8 scored rounds before anything is proposed
|
||||
- one channel per update
|
||||
- <30% delivery for 5 visits **with a healthy alternative**
|
||||
- hard `max(3, configured)` active floor
|
||||
- ≥10 rounds between updates — a *refused* proposal spends the budget too, so
|
||||
bouncing proposals cannot flood control
|
||||
- nothing under broad degradation; excluded-fraction cap
|
||||
|
||||
Proposals air from rxdemo's own claimed handle; txdemo hears them under
|
||||
`DEVOURER_TX_WITH_RX=thread`, and the authority enforces its own shape limits
|
||||
(`max_mask_delta`, `min_update_gap_rounds`).
|
||||
|
||||
Excluded channels are revisited by **keyed recovery probes**: every P rounds
|
||||
one data slot is replaced, with round, position and channel all keyed so
|
||||
recovery is not a periodic target. Probes carry sync/control only, never caller
|
||||
FEC payload. Events: `hopset.*`, including `hopset.decision` and
|
||||
`hopset.probe`.
|
||||
|
||||
## TX sensing + endpoint fusion (`HopsetSense.h`, `HopsetFusion.h`)
|
||||
|
||||
The transmitter opens quiet windows (retune → settle → discard barrier →
|
||||
window → read) and scores occupancy from CCA/FA/IGI/NHM. It refuses to arm
|
||||
beside `DEVOURER_TX_THREADS>1`, under a ~1.5 ms window, or while committing (a
|
||||
commit inside the window is self-jamming that would feed the veto).
|
||||
|
||||
Saturation constants are **measured**: ~3 events/ms = fully jammed, ~0.6 =
|
||||
clean. A railed IGI or NHM contributes nothing.
|
||||
|
||||
The veto may only argue *"this move leaves ME worse off"* — broad TX
|
||||
degradation → delay; every survivor worse → reject. It may never argue "I
|
||||
disagree about your target": that signature IS the hidden-node case, where the
|
||||
RX is right. Autonomous changes go through `start_local_change` (structural
|
||||
limits apply; the scripted lever stays exempt).
|
||||
|
||||
The classifier needs `_POSTBURST_US` armed before it proposes anything of its
|
||||
own — without it the TX observes and holds, which looks exactly like a TX that
|
||||
is not sensing.
|
||||
|
||||
Test levers, **not production knobs**: `DEVOURER_TX_SENSE_INJECT="<idx>:<occ>[,*:<occ>]"`
|
||||
fabricates the TX's per-channel view (bypasses the hardware read, keeps the
|
||||
window timing) — the only way to build the hidden-node case and its mirror on a
|
||||
bench where both adapters hear the same interferer. `DEVOURER_TX_STDIN=1` makes
|
||||
txdemo carry caller PSDU bodies from stdin (`streamtx` framing) so FEC delivery
|
||||
can be measured across an adaptation. `DEVOURER_HOP_MUTE=1` on rxdemo injects a
|
||||
one-way outage.
|
||||
|
||||
## Validation
|
||||
|
||||
`tests/run_hop_validation.sh`, `tests/hop_parity_check.sh` (register parity
|
||||
full-vs-fast), `tests/run_jammer_resilience.sh` +
|
||||
`tests/sdr_follower_jammer.py` (B210 follower, reactive vs predictive),
|
||||
`tests/hopset_adaptive_onair.sh` (protocol), `tests/tx_sense_probe.sh` (is the
|
||||
telemetry live at all), and `tests/hopset_adaptive_jammer.sh` (B210 interferer;
|
||||
`MODE=parked|herding|sense|failsafe|hidden|mirror|fusionmatrix|policycost|prepost|overhead`,
|
||||
every mode reporting FEC delivery beside the marker proxy over a window that
|
||||
opens only once the RX is tracking).
|
||||
|
||||
**Pick adapters by band** — a 5 GHz-only PA part senses nothing and cannot
|
||||
answer on 2.4 GHz.
|
||||
|
||||
### What the measurements actually say
|
||||
|
||||
Sensing costs ~8% of frames (25 ms window, 1-in-2 dwells) — a throughput cost,
|
||||
not a delivery-ratio one; FEC delivery is unchanged.
|
||||
|
||||
**The marker proxy overstates adaptation.** Against a parked jammer it reads
|
||||
0.762 → 0.946, where payload reads 0.861 → 0.927 and the delivered packet rate
|
||||
does not move at all — carrier sense already keeps the TX out of the jammed
|
||||
dwells. Quote both numbers together or the feature reads better than it is.
|
||||
@@ -0,0 +1,350 @@
|
||||
/* HopsetAuthority — the TX-side pure state machine for adaptive hopset
|
||||
* changes. The transmitter is the schedule authority: it validates proposals
|
||||
* against policy (mask legality, diversity floor, monotonic generation,
|
||||
* activation lead), then repeatedly broadcasts an identical authenticated
|
||||
* commit naming an absolute future activation slot until that slot arrives,
|
||||
* and swaps its own committed state exactly there. It also beacons a status
|
||||
* message so a follower that missed every commit can recover.
|
||||
*
|
||||
* Pure: no I/O, no crypto, no clock — the host feeds MAC-verified decoded
|
||||
* messages plus the current absolute slot, and executes the returned actions
|
||||
* (encode+MAC+send, apply-to-schedule-view, emit-event). */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_AUTHORITY_H
|
||||
#define DEVOURER_HOPSET_HOPSET_AUTHORITY_H
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "hopset/HopsetTypes.h"
|
||||
#include "hopset/HopsetWire.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
class HopsetAuthority {
|
||||
public:
|
||||
/* epoch: random per boot, host-seeded (std::random_device). The authority
|
||||
* starts at generation 0 = the legacy full-mask fixed schedule. */
|
||||
HopsetAuthority(const HopsetParams ¶ms, uint32_t epoch)
|
||||
: p_(params), epoch_(epoch) {
|
||||
cur_.epoch = epoch;
|
||||
cur_.generation = 0;
|
||||
cur_.active_mask = full_mask(p_.n_base);
|
||||
}
|
||||
|
||||
const HopsetState &state() const { return cur_; }
|
||||
bool committing() const { return committing_; }
|
||||
const HopsetState &pending() const { return pend_; }
|
||||
|
||||
/* Adopt a committed state wholesale (test rigs, or a host resuming a
|
||||
* session it persisted itself — the protocol never persists state). */
|
||||
void restore(const HopsetState &st) {
|
||||
cur_ = st;
|
||||
cur_.epoch = epoch_;
|
||||
committing_ = false;
|
||||
}
|
||||
|
||||
/* A follower proposal (already MAC-verified by the host's decode). */
|
||||
std::vector<HopsetAction> on_proposal(const HopsetMsg &m,
|
||||
uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
/* Liveness, stamped before any validation branch: this message was
|
||||
* MAC-verified by the host, so whatever we go on to think of its
|
||||
* contents, the return channel demonstrably works. A proposer whose
|
||||
* proposals keep bouncing off Busy or Cooldown is manifestly present, and
|
||||
* counting that as silence would arm the failsafe against a live peer. */
|
||||
note_feedback(now_slot);
|
||||
if (m.base_fp != p_.base_fp)
|
||||
return reject(out, m, HopsetReason::BadBaseFp, now_slot);
|
||||
if (replays_.contains(m.rx_epoch, m.rx_nonce)) {
|
||||
/* the exact exchange we already answered: if it is the one still being
|
||||
* committed, re-answer idempotently; anything else is a replay. */
|
||||
if (committing_ && m.rx_epoch == pend_echo_epoch_ &&
|
||||
m.rx_nonce == pend_echo_nonce_) {
|
||||
push_commit(out, now_slot);
|
||||
return out;
|
||||
}
|
||||
return reject(out, m, HopsetReason::ReplayGen, now_slot);
|
||||
}
|
||||
if (committing_)
|
||||
return reject(out, m, HopsetReason::Busy, now_slot);
|
||||
if (m.generation != 0 && m.generation != cur_.generation + 1)
|
||||
return reject(out, m, HopsetReason::NonMonotonicGen, now_slot);
|
||||
const HopsetReason mr = mask_reason(m.active_mask);
|
||||
if (mr != HopsetReason::None)
|
||||
return reject(out, m, mr, now_slot);
|
||||
/* Structural limits the authority enforces on its own account: a
|
||||
* follower is the decision-maker but not trusted with the shape of the
|
||||
* change. One channel per update, a floor on how often updates may
|
||||
* happen — a buggy or hostile proposer cannot walk the link down in one
|
||||
* step or by flooding. Locally-originated changes (start_change) are
|
||||
* exempt: they are the operator's own lever. */
|
||||
if (p_.max_mask_delta &&
|
||||
popcount64(m.active_mask ^ cur_.active_mask) > p_.max_mask_delta)
|
||||
return reject(out, m, HopsetReason::MaskDelta, now_slot);
|
||||
if (p_.min_update_gap_rounds && have_activation_ &&
|
||||
round_of(now_slot) - last_activation_round_ < p_.min_update_gap_rounds)
|
||||
return reject(out, m, HopsetReason::Cooldown, now_slot);
|
||||
replays_.remember(m.rx_epoch, m.rx_nonce);
|
||||
pend_echo_epoch_ = m.rx_epoch;
|
||||
pend_echo_nonce_ = m.rx_nonce;
|
||||
start_commit(out, m.active_mask, m.earliest_activate_round, now_slot);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Propose;
|
||||
ev.msg = m;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Liveness from any other authenticated frame the peer sent (its status
|
||||
* heartbeat). The host calls this; the authority itself only sees
|
||||
* proposals. */
|
||||
void note_feedback(uint64_t now_slot) {
|
||||
last_feedback_round_ = round_of(now_slot);
|
||||
have_feedback_ = true;
|
||||
}
|
||||
bool have_feedback() const { return have_feedback_; }
|
||||
/* Rounds since the peer was last heard, or kNoFeedbackAge if never. Note
|
||||
* the round numbering rebases at each activation, so this reads low just
|
||||
* after one — which is harmless, since an activation implies the exchange
|
||||
* that produced it was recent. */
|
||||
static constexpr uint64_t kNoFeedbackAge = ~uint64_t(0);
|
||||
uint64_t feedback_age_rounds(uint64_t now_slot) const {
|
||||
if (!have_feedback_)
|
||||
return kNoFeedbackAge;
|
||||
const uint64_t r = round_of(now_slot);
|
||||
return r > last_feedback_round_ ? r - last_feedback_round_ : 0;
|
||||
}
|
||||
|
||||
/* A change the transmitter decided for itself, from its own sensing. This
|
||||
* is NOT start_change: that one is the operator's lever and is deliberately
|
||||
* exempt from the structural limits. A machine reacting to local evidence
|
||||
* is exactly the actor those limits exist to bound — an adversary who can
|
||||
* make a channel look bad at the transmitter would otherwise have a freer
|
||||
* hand than one who fools the receiver. */
|
||||
std::vector<HopsetAction> start_local_change(uint64_t mask,
|
||||
uint64_t now_slot,
|
||||
uint32_t reason_bitmap = 0) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (committing_)
|
||||
return local_reject(out, HopsetReason::Busy);
|
||||
const HopsetReason mr = mask_reason(mask);
|
||||
if (mr != HopsetReason::None)
|
||||
return local_reject(out, mr);
|
||||
if (p_.max_mask_delta &&
|
||||
popcount64(mask ^ cur_.active_mask) > p_.max_mask_delta)
|
||||
return local_reject(out, HopsetReason::MaskDelta);
|
||||
if (p_.min_update_gap_rounds && have_activation_ &&
|
||||
round_of(now_slot) - last_activation_round_ < p_.min_update_gap_rounds)
|
||||
return local_reject(out, HopsetReason::Cooldown);
|
||||
pend_echo_epoch_ = pend_echo_nonce_ = 0;
|
||||
pend_reasons_ = reason_bitmap;
|
||||
start_commit(out, mask, 0, now_slot);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Refuse a proposal the host's fusion layer objected to, so the follower
|
||||
* learns why immediately instead of waiting out its retries. */
|
||||
std::vector<HopsetAction> reject_proposal(const HopsetMsg &m,
|
||||
HopsetReason reason,
|
||||
uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
return reject(out, m, reason, now_slot);
|
||||
}
|
||||
|
||||
/* A locally-originated change (scripted commits — the operator's lever,
|
||||
* exempt from the structural limits by design). rx_epoch_echo stays 0. */
|
||||
std::vector<HopsetAction> start_change(uint64_t mask, uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (committing_) {
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = HopsetReason::Busy;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
const HopsetReason mr = mask_reason(mask);
|
||||
if (mr != HopsetReason::None) {
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = mr;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
pend_echo_epoch_ = pend_echo_nonce_ = 0;
|
||||
pend_reasons_ = 0;
|
||||
start_commit(out, mask, 0, now_slot);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Slot heartbeat: commit repetition, the activation swap, status beacon. */
|
||||
std::vector<HopsetAction> on_tick(uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (committing_) {
|
||||
if (now_slot >= pend_.activate_slot) {
|
||||
cur_ = pend_;
|
||||
committing_ = false;
|
||||
last_activation_round_ = round_of(now_slot);
|
||||
have_activation_ = true;
|
||||
HopsetAction act{};
|
||||
act.kind = HopsetAction::Activate;
|
||||
act.state = cur_;
|
||||
out.push_back(act);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Activate;
|
||||
ev.state = cur_;
|
||||
out.push_back(ev);
|
||||
} else if (now_slot - last_commit_slot_ >= p_.commit_repeat_slots) {
|
||||
push_commit(out, now_slot);
|
||||
}
|
||||
}
|
||||
/* Jitter the beacon so it cannot alias with a scanning follower. A fixed
|
||||
* interval is commensurate with the follower's fixed scan step, so the
|
||||
* beacon keeps arriving at the same point in its scan cycle — landing on
|
||||
* the same channel every time, which is either always right or, as often,
|
||||
* always wrong. A follower that never coincides never recovers, and it
|
||||
* looks like bad luck rather than arithmetic. Deterministic and pure: the
|
||||
* spread comes from the slot number itself, not a clock or an RNG. */
|
||||
if (now_slot - last_status_slot_ >=
|
||||
p_.status_interval_slots + (now_slot % 7)) {
|
||||
last_status_slot_ = now_slot;
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
a.msg = status_msg(now_slot, HopsetReason::None);
|
||||
out.push_back(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Round index of `slot` in the current generation's numbering. */
|
||||
uint64_t round_of(uint64_t slot) const {
|
||||
const size_t k = cur_.generation == 0 ? p_.n_base
|
||||
: popcount64(cur_.active_mask);
|
||||
return (slot - cur_.activate_slot) / k;
|
||||
}
|
||||
|
||||
private:
|
||||
HopsetReason mask_reason(uint64_t mask) const {
|
||||
if (cur_.generation + 1 >= kGenCeiling)
|
||||
return HopsetReason::GenCeiling;
|
||||
if (mask & ~full_mask(p_.n_base))
|
||||
return HopsetReason::BadMask;
|
||||
if (popcount64(mask) < p_.min_active)
|
||||
return HopsetReason::LowDiversity;
|
||||
if (p_.max_excluded_frac_pct < 100 &&
|
||||
popcount64(full_mask(p_.n_base) & ~mask) * 100 >
|
||||
p_.max_excluded_frac_pct * p_.n_base)
|
||||
return HopsetReason::LowDiversity;
|
||||
if (mask == cur_.active_mask && cur_.generation != 0)
|
||||
return HopsetReason::NoChange;
|
||||
return HopsetReason::None;
|
||||
}
|
||||
|
||||
void start_commit(std::vector<HopsetAction> &out, uint64_t mask,
|
||||
uint64_t earliest_round, uint64_t now_slot) {
|
||||
const size_t k_cur = cur_.generation == 0 ? p_.n_base
|
||||
: popcount64(cur_.active_mask);
|
||||
const uint64_t cur_round = round_of(now_slot);
|
||||
uint64_t lead = p_.lead_rounds < 8 ? 8 : p_.lead_rounds;
|
||||
uint64_t act_round = cur_round + lead;
|
||||
if (earliest_round > act_round)
|
||||
act_round = earliest_round;
|
||||
pend_ = cur_;
|
||||
pend_.generation = cur_.generation + 1;
|
||||
pend_.active_mask = mask;
|
||||
pend_.activate_round = act_round;
|
||||
pend_.activate_slot = cur_.activate_slot + act_round * k_cur;
|
||||
pend_.epoch = epoch_;
|
||||
committing_ = true;
|
||||
push_commit(out, now_slot);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Commit;
|
||||
ev.state = pend_;
|
||||
out.push_back(ev);
|
||||
}
|
||||
|
||||
void push_commit(std::vector<HopsetAction> &out, uint64_t now_slot) {
|
||||
last_commit_slot_ = now_slot;
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
HopsetMsg &m = a.msg;
|
||||
m.type = HT_COMMIT;
|
||||
m.link_id = p_.link_id;
|
||||
m.tx_epoch = epoch_;
|
||||
m.rx_epoch_echo = pend_echo_epoch_;
|
||||
m.generation = pend_.generation;
|
||||
m.active_mask = pend_.active_mask;
|
||||
m.base_fp = p_.base_fp;
|
||||
m.activate_round = pend_.activate_round;
|
||||
m.activate_slot = pend_.activate_slot;
|
||||
m.current_round = round_of(now_slot);
|
||||
m.rx_nonce_echo = pend_echo_nonce_;
|
||||
m.reason_bitmap = pend_reasons_;
|
||||
out.push_back(a);
|
||||
}
|
||||
|
||||
std::vector<HopsetAction> &local_reject(std::vector<HopsetAction> &out,
|
||||
HopsetReason r) {
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = r;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
HopsetMsg status_msg(uint64_t now_slot, HopsetReason reason) const {
|
||||
HopsetMsg m;
|
||||
m.type = HT_STATUS;
|
||||
m.link_id = p_.link_id;
|
||||
m.role = 1;
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = cur_.generation;
|
||||
m.active_mask = cur_.active_mask;
|
||||
m.base_fp = p_.base_fp;
|
||||
m.current_round = round_of(now_slot);
|
||||
m.activate_slot = cur_.activate_slot;
|
||||
m.reason = static_cast<uint8_t>(reason);
|
||||
return m;
|
||||
}
|
||||
|
||||
std::vector<HopsetAction> &reject(std::vector<HopsetAction> &out,
|
||||
const HopsetMsg &m, HopsetReason r,
|
||||
uint64_t now_slot) {
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
a.msg = status_msg(now_slot, r);
|
||||
a.msg.rx_nonce_echo = m.rx_nonce;
|
||||
out.push_back(a);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = r;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
HopsetParams p_;
|
||||
uint32_t epoch_;
|
||||
HopsetState cur_{};
|
||||
HopsetState pend_{};
|
||||
bool committing_ = false;
|
||||
uint32_t pend_echo_epoch_ = 0, pend_echo_nonce_ = 0;
|
||||
uint32_t pend_reasons_ = 0;
|
||||
uint64_t last_commit_slot_ = 0;
|
||||
uint64_t last_status_slot_ = 0;
|
||||
uint64_t last_activation_round_ = 0;
|
||||
bool have_activation_ = false;
|
||||
uint64_t last_feedback_round_ = 0;
|
||||
bool have_feedback_ = false;
|
||||
ProposalReplayRing replays_;
|
||||
};
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_AUTHORITY_H */
|
||||
@@ -0,0 +1,199 @@
|
||||
/* hopset.* JSONL binding — one emitter for every action the pure machines
|
||||
* report, so the TX and RX demos (and the tests' log assertions) share one
|
||||
* schema. Every line carries the generation and mask so any transition is
|
||||
* reproducible from the logs alone. */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_EVENTS_H
|
||||
#define DEVOURER_HOPSET_HOPSET_EVENTS_H
|
||||
|
||||
#include "Event.h"
|
||||
#include "hopset/HopsetFusion.h"
|
||||
#include "hopset/HopsetPolicy.h"
|
||||
#include "hopset/HopsetSense.h"
|
||||
#include "hopset/HopsetTypes.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
/* Emit one machine-reported Event action. role: "tx" | "rx". */
|
||||
inline void emit_action(EventSink &sink, const HopsetAction &a,
|
||||
const char *role, uint64_t now_slot) {
|
||||
if (a.kind != HopsetAction::Event)
|
||||
return;
|
||||
Ev ev(sink, hopset_event_name(a.event));
|
||||
ev.t().f("v", 1).f("role", role).f("slot", (unsigned long long)now_slot);
|
||||
switch (a.event) {
|
||||
case HopsetEvent::Propose:
|
||||
ev.f("gen", (unsigned long long)a.msg.generation)
|
||||
.hexf("mask", a.msg.active_mask, 0)
|
||||
.f("obs", (unsigned long long)a.msg.observation_count)
|
||||
.hexf("reasons", a.msg.reason_bitmap, 0);
|
||||
break;
|
||||
case HopsetEvent::Commit:
|
||||
case HopsetEvent::Activate:
|
||||
case HopsetEvent::Recover:
|
||||
ev.f("gen", (unsigned long long)a.state.generation)
|
||||
.hexf("mask", a.state.active_mask, 0)
|
||||
.f("activate_round", (unsigned long long)a.state.activate_round)
|
||||
.f("activate_slot", (unsigned long long)a.state.activate_slot);
|
||||
break;
|
||||
case HopsetEvent::Reject:
|
||||
ev.f("reason", hopset_reason_name(a.reason));
|
||||
break;
|
||||
case HopsetEvent::GenMismatch:
|
||||
ev.f("seen_gen", (unsigned long long)a.msg.generation)
|
||||
.f("cur_gen", (unsigned long long)a.state.generation)
|
||||
.hexf("cur_mask", a.state.active_mask, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* One policy verdict. `verbose` adds the per-channel evidence the decision
|
||||
* was made from, so a log replay can re-derive it without the receiver. */
|
||||
inline void emit_decision(EventSink &sink, const HopsetDecision &d,
|
||||
uint64_t slot, uint64_t round, bool verbose) {
|
||||
Ev ev(sink, "hopset.decision");
|
||||
ev.t().f("v", 1).f("role", "rx").f("slot", (unsigned long long)slot)
|
||||
.f("round", (unsigned long long)round);
|
||||
ev.f("kind", d.kind == HopsetDecision::Kind::ProposeExclude ? "exclude"
|
||||
: d.kind == HopsetDecision::Kind::ProposeRestore ? "restore"
|
||||
: "hold");
|
||||
ev.f("obs", (unsigned long long)d.observation_count)
|
||||
.hexf("policy", d.policy_hash, 8);
|
||||
if (d.kind == HopsetDecision::Kind::Hold) {
|
||||
ev.f("hold", hopset_hold_name(d.hold));
|
||||
} else {
|
||||
ev.hexf("mask", d.proposed_mask, 0)
|
||||
.hexf("reasons", d.reason_bitmap, 0)
|
||||
.f("target", (unsigned long long)d.target_index);
|
||||
}
|
||||
if (!verbose)
|
||||
return;
|
||||
for (size_t i = 0; i < d.chans.size(); ++i) {
|
||||
char key[8], buf[64];
|
||||
std::snprintf(key, sizeof(key), "c%zu", i);
|
||||
std::snprintf(buf, sizeof(buf), "%s d=%.2f p=%.2f v=%u imp=%u",
|
||||
d.chans[i].active ? "on" : "off", d.chans[i].delivery,
|
||||
d.chans[i].probe_delivery, d.chans[i].visits,
|
||||
d.chans[i].impaired_run);
|
||||
ev.f(key, buf);
|
||||
}
|
||||
}
|
||||
|
||||
/* One transmitter quiet-window observation. Raw deltas AND the window they
|
||||
* span, because the classifier normalizes them itself and a pre-divided rate
|
||||
* loses the low end; `rate` is a convenience for log-scraping harnesses. */
|
||||
inline void emit_sense(EventSink &sink, const TxSenseSample &s,
|
||||
int channel, uint32_t generation, uint32_t settle_us,
|
||||
uint32_t read_us, double occupancy, bool scored) {
|
||||
Ev ev(sink, "hopset.sense");
|
||||
ev.t().f("v", 1).f("role", "tx")
|
||||
.f("slot", (unsigned long long)s.slot)
|
||||
.f("round", (unsigned long long)s.round)
|
||||
.f("gen", (unsigned long long)generation)
|
||||
.f("base_idx", (unsigned long long)s.base_index)
|
||||
.f("ch", channel)
|
||||
.f("phase", s.phase == SensePhase::PostBurst ? "post" : "pre")
|
||||
.f("probe", s.probe)
|
||||
.f("window_us", (unsigned long long)s.window_us)
|
||||
.f("settle_us", (unsigned long long)settle_us)
|
||||
.f("read_us", (unsigned long long)read_us);
|
||||
ev.f("valid_fa", s.valid_fa);
|
||||
if (s.valid_fa) {
|
||||
ev.f("cca_ofdm", (unsigned long long)s.cca_ofdm)
|
||||
.f("cca_cck", (unsigned long long)s.cca_cck)
|
||||
.f("fa_ofdm", (unsigned long long)s.fa_ofdm)
|
||||
.f("fa_cck", (unsigned long long)s.fa_cck);
|
||||
const double ms = s.window_us ? s.window_us / 1000.0 : 1.0;
|
||||
ev.f("cca_rate", (s.cca_ofdm + s.cca_cck) / ms)
|
||||
.f("fa_rate", (s.fa_ofdm + s.fa_cck) / ms);
|
||||
}
|
||||
ev.f("valid_igi", s.valid_igi);
|
||||
if (s.valid_igi)
|
||||
ev.f("igi", (unsigned long long)s.igi);
|
||||
ev.f("valid_nhm", s.valid_nhm);
|
||||
if (s.valid_nhm)
|
||||
ev.f("nhm_busy", (unsigned long long)s.nhm_busy_pct)
|
||||
.f("nhm_dur", (unsigned long long)s.nhm_duration);
|
||||
if (s.injected)
|
||||
ev.f("inject", 1);
|
||||
ev.hexf("flags", s.flags, 0).f("scored", scored);
|
||||
if (scored)
|
||||
ev.f("occ", occupancy);
|
||||
}
|
||||
|
||||
/* Why this side's sensor proposed nothing. Held is not the same as blind, and
|
||||
* neither is the same as content: without this, a sensor sitting on a floor,
|
||||
* a sensor with no evidence and a sensor that is not running all produce the
|
||||
* same silence. Rate-limited by the caller to the shape of the answer. */
|
||||
inline void emit_sense_eval(EventSink &sink, const TxSenseCandidate &c,
|
||||
uint64_t slot, uint64_t round) {
|
||||
Ev(sink, "hopset.sense_eval")
|
||||
.t()
|
||||
.f("v", 1)
|
||||
.f("role", "tx")
|
||||
.f("slot", (unsigned long long)slot)
|
||||
.f("round", (unsigned long long)round)
|
||||
.f("hold", tx_sense_hold_name(c.hold))
|
||||
.f("chans", (unsigned long long)c.chans_with_evidence)
|
||||
.f("samples", (unsigned long long)c.sample_count)
|
||||
.f("band_min", c.band_min_occ)
|
||||
.f("band_max", c.band_max_occ)
|
||||
.f("broad", c.broad_occupancy)
|
||||
.f("flat", c.flat_band);
|
||||
}
|
||||
|
||||
/* One fused verdict. Both endpoints' views are on the line so a log reader can
|
||||
* see the argument, not just the conclusion — the whole point of surfacing a
|
||||
* disagreement rather than averaging it. */
|
||||
inline void emit_fusion(EventSink &sink, const FusedDecision &d, uint64_t slot,
|
||||
uint64_t round, const char *mode) {
|
||||
Ev ev(sink, "hopset.decision");
|
||||
ev.t().f("v", 1).f("role", "tx")
|
||||
.f("slot", (unsigned long long)slot)
|
||||
.f("round", (unsigned long long)round)
|
||||
.f("mode", mode)
|
||||
.f("origin", decision_origin_name(d.origin))
|
||||
.f("kind", fused_action_name(d.action));
|
||||
if (d.action == FusedAction::Hold || d.action == FusedAction::Delay)
|
||||
ev.f("hold", fusion_hold_name(d.hold));
|
||||
if (d.action != FusedAction::Hold && d.action != FusedAction::Delay)
|
||||
ev.hexf("mask", d.mask, 0);
|
||||
ev.f("target", (unsigned long long)d.target_index)
|
||||
.hexf("reasons", d.reason_bitmap, 0)
|
||||
.f("veto", fusion_veto_name(d.veto))
|
||||
.f("rx_wanted", d.rx_wanted_exclude)
|
||||
.f("tx_wanted", d.tx_wanted_exclude)
|
||||
.f("disagree", d.endpoints_disagree_on_target)
|
||||
.f("tx_valid", d.tx_evidence_valid);
|
||||
if (d.tx_evidence_valid)
|
||||
ev.f("tx_target_occ", d.tx_target_occupancy)
|
||||
.f("tx_band_min", d.tx_band_min_occupancy)
|
||||
.f("tx_band_max", d.tx_band_max_occupancy);
|
||||
if (d.feedback_age_rounds == kNoFeedback)
|
||||
ev.f("fb_age", "never");
|
||||
else
|
||||
ev.f("fb_age", (unsigned long long)d.feedback_age_rounds);
|
||||
ev.hexf("fusion", d.fusion_hash, 8);
|
||||
}
|
||||
|
||||
/* One keyed recovery-probe dwell: the transmitter logs that it aired on the
|
||||
* excluded channel, the receiver logs whether anything arrived. */
|
||||
inline void emit_probe(EventSink &sink, const char *role, uint64_t slot,
|
||||
uint64_t round, uint32_t base_index, int channel,
|
||||
bool delivered, uint32_t frames) {
|
||||
Ev(sink, "hopset.probe")
|
||||
.t()
|
||||
.f("v", 1)
|
||||
.f("role", role)
|
||||
.f("slot", (unsigned long long)slot)
|
||||
.f("round", (unsigned long long)round)
|
||||
.f("base_idx", (unsigned long long)base_index)
|
||||
.f("ch", channel)
|
||||
.f("delivered", delivered)
|
||||
.f("frames", (unsigned long long)frames);
|
||||
}
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_EVENTS_H */
|
||||
@@ -0,0 +1,356 @@
|
||||
/* HopsetFollower — the RX-side pure state machine for adaptive hopset
|
||||
* changes. The follower proposes mask changes (the observation policy that
|
||||
* decides WHAT to propose is a separate layer — here it is caller input),
|
||||
* adopts only
|
||||
* authenticated commits/statuses from the authority, activates exactly at the
|
||||
* committed absolute slot, and recovers from a missed transition: a sync
|
||||
* marker advertising a generation/mask it doesn't hold sends it to Recovering
|
||||
* (the host falls back to the base-hopset acquire scan, which is always legal
|
||||
* because acquisition scans the immutable base hopset), until a repeated
|
||||
* commit or the authority's status beacon re-synchronizes it.
|
||||
*
|
||||
* Pure: no I/O, no crypto, no clock, no randomness — the host feeds
|
||||
* MAC-verified messages, the current absolute slot, and its own per-boot
|
||||
* random epoch/nonces. */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_FOLLOWER_H
|
||||
#define DEVOURER_HOPSET_HOPSET_FOLLOWER_H
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "hopset/HopsetTypes.h"
|
||||
#include "hopset/HopsetWire.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
class HopsetFollower {
|
||||
public:
|
||||
enum class State : uint8_t { Synced, Proposing, Pending, Recovering };
|
||||
|
||||
HopsetFollower(const HopsetParams ¶ms, uint32_t epoch)
|
||||
: p_(params), epoch_(epoch) {
|
||||
cur_.generation = 0;
|
||||
cur_.active_mask = full_mask(p_.n_base);
|
||||
}
|
||||
|
||||
State fsm() const { return st_; }
|
||||
const HopsetState &state() const { return cur_; }
|
||||
const HopsetState &pending() const { return pend_; }
|
||||
bool has_pending() const { return st_ == State::Pending; }
|
||||
|
||||
/* Ask the authority for a mask change. nonce: host-random per proposal. */
|
||||
std::vector<HopsetAction> propose(uint64_t mask, uint32_t observation_count,
|
||||
uint32_t reason_bitmap, uint32_t nonce,
|
||||
uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (st_ != State::Synced) {
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = HopsetReason::Busy;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
prop_ = HopsetMsg{};
|
||||
prop_.type = HT_PROPOSAL;
|
||||
prop_.link_id = p_.link_id;
|
||||
prop_.rx_epoch = epoch_;
|
||||
prop_.generation = 0; /* 0 = "next" — the authority numbers it */
|
||||
prop_.active_mask = mask;
|
||||
prop_.base_fp = p_.base_fp;
|
||||
prop_.observation_count = observation_count;
|
||||
prop_.reason_bitmap = reason_bitmap;
|
||||
prop_.rx_nonce = nonce;
|
||||
tries_ = 1;
|
||||
last_prop_slot_ = now_slot;
|
||||
st_ = State::Proposing;
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
a.msg = prop_;
|
||||
out.push_back(a);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Propose;
|
||||
ev.msg = prop_;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* An authenticated commit from the authority. */
|
||||
std::vector<HopsetAction> on_commit(const HopsetMsg &m, uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (m.base_fp != p_.base_fp)
|
||||
return drop(out, HopsetReason::BadBaseFp);
|
||||
if (m.generation >= kGenCeiling)
|
||||
return drop(out, HopsetReason::GenCeiling);
|
||||
if (!mask_valid(m.active_mask, p_.n_base, p_.min_active))
|
||||
return drop(out, m.active_mask & ~full_mask(p_.n_base)
|
||||
? HopsetReason::BadMask
|
||||
: HopsetReason::LowDiversity);
|
||||
const bool same_epoch = have_auth_ && m.tx_epoch == auth_epoch_;
|
||||
if (same_epoch) {
|
||||
if (st_ == State::Pending && m.generation == pend_.generation &&
|
||||
m.active_mask == pend_.active_mask &&
|
||||
m.activate_slot == pend_.activate_slot)
|
||||
return out; /* repeated commit — already armed */
|
||||
if (m.generation <= cur_.generation)
|
||||
return drop(out, HopsetReason::ReplayGen);
|
||||
}
|
||||
/* A commit echoing OUR epoch must echo our outstanding nonce. */
|
||||
if (m.rx_epoch_echo == epoch_ && epoch_ != 0 &&
|
||||
(st_ != State::Proposing || m.rx_nonce_echo != prop_.rx_nonce))
|
||||
return drop(out, HopsetReason::NonceMismatch);
|
||||
/* Activation window: a future activation must sit within the allowed
|
||||
* lead; a past one is only ever adopted as recovery (the transition
|
||||
* already happened — join it now). */
|
||||
if (m.activate_slot > now_slot &&
|
||||
m.activate_slot - now_slot > p_.max_lead_slots)
|
||||
return drop(out, HopsetReason::ActivationWindow);
|
||||
adopt_epoch(m.tx_epoch);
|
||||
const bool was_recovering = st_ == State::Recovering;
|
||||
pend_.epoch = m.tx_epoch;
|
||||
pend_.generation = m.generation;
|
||||
pend_.active_mask = m.active_mask;
|
||||
pend_.activate_round = m.activate_round;
|
||||
pend_.activate_slot = m.activate_slot;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = was_recovering ? HopsetEvent::Recover : HopsetEvent::Commit;
|
||||
ev.state = pend_;
|
||||
out.push_back(ev);
|
||||
if (m.activate_slot <= now_slot) {
|
||||
activate(out);
|
||||
} else {
|
||||
st_ = State::Pending;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* The authority's status beacon (also carries proposal rejections). */
|
||||
std::vector<HopsetAction> on_status(const HopsetMsg &m, uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (m.role != 1)
|
||||
return out; /* peer-follower chatter — not authority state */
|
||||
if (m.base_fp != p_.base_fp)
|
||||
return drop(out, HopsetReason::BadBaseFp);
|
||||
/* A nonzero reason echoing our outstanding nonce: proposal denied. */
|
||||
if (m.reason != static_cast<uint8_t>(HopsetReason::None) &&
|
||||
st_ == State::Proposing && m.rx_nonce_echo == prop_.rx_nonce) {
|
||||
st_ = State::Synced;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = static_cast<HopsetReason>(m.reason);
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
if (!mask_valid(m.active_mask, p_.n_base, p_.min_active) &&
|
||||
m.generation != 0)
|
||||
return drop(out, HopsetReason::BadMask);
|
||||
/* The same activation-window bound a commit gets. The status path adopts
|
||||
* outright, and its anchor is what the in-flight-marker grace measures
|
||||
* against — an activation slot far in the future would stretch that grace
|
||||
* over every marker the follower will ever decode and silently disable
|
||||
* the only hot-path mismatch tripwire. */
|
||||
if (m.activate_slot > now_slot &&
|
||||
m.activate_slot - now_slot > p_.max_lead_slots)
|
||||
return drop(out, HopsetReason::ActivationWindow);
|
||||
const bool same_epoch = have_auth_ && m.sender_epoch == auth_epoch_;
|
||||
if (same_epoch && m.generation < cur_.generation)
|
||||
return drop(out, HopsetReason::ReplayGen);
|
||||
if (same_epoch && m.generation == cur_.generation)
|
||||
return resync_check(out); /* in agreement */
|
||||
/* Newer generation (or a restarted authority): adopt its current state
|
||||
* outright — the status carries the full mask and the activation anchor,
|
||||
* which is exactly the recovery an RX that missed the commits needs. */
|
||||
adopt_epoch(m.sender_epoch);
|
||||
pend_.epoch = m.sender_epoch;
|
||||
pend_.generation = m.generation;
|
||||
pend_.active_mask =
|
||||
m.generation == 0 ? full_mask(p_.n_base) : m.active_mask;
|
||||
pend_.activate_round = 0;
|
||||
pend_.activate_slot = m.activate_slot;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Recover;
|
||||
ev.state = pend_;
|
||||
out.push_back(ev);
|
||||
activate(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Hot-path check from a decoded v2 sync marker. fp_matches: host-computed
|
||||
* "the marker's (generation, mask_fp) equals mask_fp(keys, gen, mask) of
|
||||
* the state we hold for that generation" (current or pending).
|
||||
* marker_slot is the slot the MARKER was stamped in — the transmitter's
|
||||
* clock at composition, not the local clock at decode, which is what makes
|
||||
* a boundary-crossing frame recognizable as one. */
|
||||
std::vector<HopsetAction> on_marker(uint32_t marker_gen, bool fp_matches,
|
||||
uint64_t marker_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
const bool known = (marker_gen == cur_.generation ||
|
||||
(st_ == State::Pending &&
|
||||
marker_gen == pend_.generation)) &&
|
||||
fp_matches;
|
||||
if (known)
|
||||
return out;
|
||||
/* A marker carrying the generation we just left, STAMPED at or before the
|
||||
* activation slot, is a frame that crossed the boundary in flight — the
|
||||
* transmitter was telling the truth when it composed it. Acting on it
|
||||
* drops lockstep at the one moment the link can least afford it (see
|
||||
* HopsetParams::stale_marker_slots). A transmitter that really has not
|
||||
* moved keeps stamping fresh slots, so it clears the grace within
|
||||
* milliseconds and the mismatch stands. */
|
||||
if (have_prev_ && marker_gen == prev_generation_ &&
|
||||
marker_slot < activated_slot_ + p_.stale_marker_slots)
|
||||
return out;
|
||||
if (st_ == State::Recovering && marker_gen == last_mismatch_gen_)
|
||||
return out; /* already recovering from this one — don't spam */
|
||||
last_mismatch_gen_ = marker_gen;
|
||||
st_ = State::Recovering;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::GenMismatch;
|
||||
ev.msg.generation = marker_gen;
|
||||
ev.state = cur_;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Slot heartbeat: pending activation, proposal retry/backoff. */
|
||||
std::vector<HopsetAction> on_tick(uint64_t now_slot) {
|
||||
std::vector<HopsetAction> out;
|
||||
if (st_ == State::Pending && now_slot >= pend_.activate_slot) {
|
||||
activate(out);
|
||||
return out;
|
||||
}
|
||||
if (st_ == State::Proposing &&
|
||||
now_slot - last_prop_slot_ >= p_.proposal_backoff_slots) {
|
||||
if (tries_ >= p_.proposal_retries) {
|
||||
st_ = State::Synced;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = HopsetReason::Timeout;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
++tries_;
|
||||
last_prop_slot_ = now_slot;
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
a.msg = prop_;
|
||||
out.push_back(a);
|
||||
}
|
||||
/* Announce ourselves even with nothing to propose. A receiver that is
|
||||
* simply content sends no proposals, which from the transmitter's side
|
||||
* looks exactly like a receiver that has gone deaf — and a transmitter
|
||||
* failsafe keyed on that silence would fire on a perfectly good link.
|
||||
* The status also carries our committed generation and mask, so the
|
||||
* transmitter can see a split-brain rather than infer one. */
|
||||
/* The receiver's slot clock is FITTED from received markers, so unlike
|
||||
* the authority's it can jump backwards when the fit is re-anchored
|
||||
* during acquisition. An unsigned difference would underflow there and
|
||||
* fire the heartbeat on every tick — the receiver would spend its air
|
||||
* time transmitting instead of listening, and never re-acquire. Re-anchor
|
||||
* on a backwards jump instead of announcing. And say nothing at all while
|
||||
* recovering: there is no useful state to report, and transmitting is the
|
||||
* opposite of what re-acquisition needs. */
|
||||
if (!have_status_anchor_ || now_slot < last_status_slot_) {
|
||||
have_status_anchor_ = true;
|
||||
last_status_slot_ = now_slot;
|
||||
} else if (p_.follower_status_slots && st_ != State::Recovering &&
|
||||
now_slot - last_status_slot_ >= p_.follower_status_slots) {
|
||||
last_status_slot_ = now_slot;
|
||||
HopsetAction a{};
|
||||
a.kind = HopsetAction::SendControl;
|
||||
HopsetMsg &m = a.msg;
|
||||
m.type = HT_STATUS;
|
||||
m.link_id = p_.link_id;
|
||||
m.role = 0; /* follower */
|
||||
m.sender_epoch = epoch_;
|
||||
m.generation = cur_.generation;
|
||||
m.active_mask = cur_.active_mask;
|
||||
m.base_fp = p_.base_fp;
|
||||
m.activate_slot = cur_.activate_slot;
|
||||
m.reason = static_cast<uint8_t>(HopsetReason::None);
|
||||
out.push_back(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
void adopt_epoch(uint32_t e) {
|
||||
if (!have_auth_ || auth_epoch_ != e) {
|
||||
have_auth_ = true;
|
||||
auth_epoch_ = e;
|
||||
}
|
||||
}
|
||||
|
||||
void activate(std::vector<HopsetAction> &out) {
|
||||
/* Remember what we just left, and when: a marker stamped with the old
|
||||
* generation can still be in flight across the boundary. */
|
||||
prev_generation_ = cur_.generation;
|
||||
have_prev_ = true;
|
||||
activated_slot_ = pend_.activate_slot;
|
||||
cur_ = pend_;
|
||||
st_ = State::Synced;
|
||||
HopsetAction act{};
|
||||
act.kind = HopsetAction::Activate;
|
||||
act.state = cur_;
|
||||
out.push_back(act);
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Activate;
|
||||
ev.state = cur_;
|
||||
out.push_back(ev);
|
||||
}
|
||||
|
||||
std::vector<HopsetAction> &resync_check(std::vector<HopsetAction> &out) {
|
||||
if (st_ == State::Recovering) {
|
||||
/* the authority's state matches what we already hold — the mismatch
|
||||
* was transient (e.g. a marker raced its own activation) */
|
||||
st_ = State::Synced;
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Recover;
|
||||
ev.state = cur_;
|
||||
out.push_back(ev);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<HopsetAction> &drop(std::vector<HopsetAction> &out,
|
||||
HopsetReason r) {
|
||||
HopsetAction ev{};
|
||||
ev.kind = HopsetAction::Event;
|
||||
ev.event = HopsetEvent::Reject;
|
||||
ev.reason = r;
|
||||
out.push_back(ev);
|
||||
return out;
|
||||
}
|
||||
|
||||
HopsetParams p_;
|
||||
uint32_t epoch_;
|
||||
State st_ = State::Synced;
|
||||
HopsetState cur_{};
|
||||
HopsetState pend_{};
|
||||
HopsetMsg prop_{};
|
||||
unsigned tries_ = 0;
|
||||
uint64_t last_prop_slot_ = 0;
|
||||
uint64_t last_status_slot_ = 0;
|
||||
bool have_status_anchor_ = false;
|
||||
bool have_auth_ = false;
|
||||
uint32_t auth_epoch_ = 0;
|
||||
uint32_t last_mismatch_gen_ = 0;
|
||||
/* The generation we left at the last activation, and where that was, for
|
||||
* the in-flight-marker grace. */
|
||||
uint32_t prev_generation_ = 0;
|
||||
uint64_t activated_slot_ = 0;
|
||||
bool have_prev_ = false;
|
||||
};
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_FOLLOWER_H */
|
||||
@@ -0,0 +1,457 @@
|
||||
/* HopsetFusion — arbitrating between what the receiver measured and what the
|
||||
* transmitter sensed, without letting the blinder endpoint overrule the other.
|
||||
*
|
||||
* The naive design is to let the transmitter veto a receiver proposal it
|
||||
* disagrees with: "the receiver wants to drop channel 3, but my own CCA says 3
|
||||
* is quiet, so refuse." That is wrong, and it is wrong in exactly the case
|
||||
* this feature exists to serve. A hidden interferer sitting next to the
|
||||
* receiver produces precisely that signature — delivery on 3 collapses while
|
||||
* the transmitter, far away, hears nothing. The naive veto fires and blocks
|
||||
* the correct decision, and it does so most confidently when the
|
||||
* transmitter's reading is cleanest, so its confidence is anti-correlated
|
||||
* with its correctness.
|
||||
*
|
||||
* The framing that works: the transmitter has no standing to contradict the
|
||||
* receiver ABOUT THE TARGET, because the receiver measured the endpoint that
|
||||
* has to decode and the transmitter measured a different point in space. The
|
||||
* only thing the transmitter knows that the receiver cannot is its own local
|
||||
* conditions — whether it can get on air at all on the channels the move would
|
||||
* leave it with. So the veto answers one question and only one:
|
||||
*
|
||||
* does this move leave the transmitter worse off, at the transmitter?
|
||||
*
|
||||
* Two grounds qualify. Neither is a disagreement about the target.
|
||||
*
|
||||
* BroadTxDegradation -> Delay. The whole band reads uniformly occupied, so
|
||||
* the transmitter cannot tell channels apart and has no opinion to offer
|
||||
* about this one. Not a refusal: "I cannot see well enough to judge; look
|
||||
* again." It does not spend the receiver's update budget.
|
||||
*
|
||||
* RemainingWorse -> Reject. Every channel that would survive the exclusion
|
||||
* is markedly more occupied here than the target is. The transmitter may
|
||||
* fully believe the receiver that the target is dead; it is saying the
|
||||
* alternatives are a cul-de-sac. That is a fact only it possesses.
|
||||
*
|
||||
* Everything else is reported and ignored. Disagreement is information, not
|
||||
* authority, so it is surfaced in the decision and never averaged into it —
|
||||
* the returned mask is always one endpoint's proposal verbatim.
|
||||
*
|
||||
* Pure: no I/O, no clock, no state. The host supplies both endpoints' views. */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_FUSION_H
|
||||
#define DEVOURER_HOPSET_HOPSET_FUSION_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "hopset/HopsetPolicy.h"
|
||||
#include "hopset/HopsetSense.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
enum class FusionMode : uint8_t {
|
||||
RxAuthoritative = 0, /* the transmitter observes but never acts */
|
||||
RxPlusTxVeto = 1, /* default: receiver proposes, transmitter may object */
|
||||
EitherEndpoint = 2, /* either may originate; the receiver still preempts */
|
||||
TxFailsafe = 3, /* transmitter originates only once feedback is gone */
|
||||
};
|
||||
|
||||
inline const char *fusion_mode_name(FusionMode m) {
|
||||
switch (m) {
|
||||
case FusionMode::RxAuthoritative: return "rx";
|
||||
case FusionMode::RxPlusTxVeto: return "veto";
|
||||
case FusionMode::EitherEndpoint: return "either";
|
||||
case FusionMode::TxFailsafe: return "failsafe";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Parsed from the demo's DEVOURER_HOP_FUSION. Returns false on an unknown
|
||||
* spelling rather than silently picking a mode. */
|
||||
inline bool parse_fusion_mode(const char *s, FusionMode &out) {
|
||||
if (!s)
|
||||
return false;
|
||||
const std::string v(s);
|
||||
if (v == "rx") { out = FusionMode::RxAuthoritative; return true; }
|
||||
if (v == "veto") { out = FusionMode::RxPlusTxVeto; return true; }
|
||||
if (v == "either") { out = FusionMode::EitherEndpoint; return true; }
|
||||
if (v == "failsafe") { out = FusionMode::TxFailsafe; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
enum class DecisionOrigin : uint8_t { Rx = 0, Tx = 1, Fused = 2, Failsafe = 3 };
|
||||
|
||||
inline const char *decision_origin_name(DecisionOrigin o) {
|
||||
switch (o) {
|
||||
case DecisionOrigin::Rx: return "rx";
|
||||
case DecisionOrigin::Tx: return "tx";
|
||||
case DecisionOrigin::Fused: return "fused";
|
||||
case DecisionOrigin::Failsafe: return "failsafe";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Origin rides the spare bits of the proposal's existing reason bitmap, so it
|
||||
* costs no wire change and no marker version. Rx == 0 means every bitmap
|
||||
* written before this layer existed decodes with the right origin. */
|
||||
inline uint32_t rb_set_origin(uint32_t bm, DecisionOrigin o) {
|
||||
return (bm & ~uint32_t(RB_ORIGIN_MASK)) | (uint32_t(o) << RB_ORIGIN_SHIFT);
|
||||
}
|
||||
inline DecisionOrigin rb_origin(uint32_t bm) {
|
||||
return DecisionOrigin((bm & RB_ORIGIN_MASK) >> RB_ORIGIN_SHIFT);
|
||||
}
|
||||
|
||||
enum class FusedAction : uint8_t { Hold, Exclude, Restore, Delay };
|
||||
|
||||
inline const char *fused_action_name(FusedAction a) {
|
||||
switch (a) {
|
||||
case FusedAction::Hold: return "hold";
|
||||
case FusedAction::Exclude: return "exclude";
|
||||
case FusedAction::Restore: return "restore";
|
||||
case FusedAction::Delay: return "delay";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
enum class FusionVeto : uint8_t {
|
||||
None = 0,
|
||||
BroadTxDegradation, /* -> Delay */
|
||||
RemainingWorse, /* -> Reject */
|
||||
SensorAbsent, /* recorded; can never block */
|
||||
InsufficientTxEvidence, /* recorded; can never block */
|
||||
};
|
||||
|
||||
inline const char *fusion_veto_name(FusionVeto v) {
|
||||
switch (v) {
|
||||
case FusionVeto::None: return "none";
|
||||
case FusionVeto::BroadTxDegradation: return "tx_broad";
|
||||
case FusionVeto::RemainingWorse: return "tx_alt_dirty";
|
||||
case FusionVeto::SensorAbsent: return "tx_sensor_absent";
|
||||
case FusionVeto::InsufficientTxEvidence: return "tx_insufficient";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
enum class FusionHold : uint8_t {
|
||||
None = 0,
|
||||
RxHeld,
|
||||
ModeForbidsTxOrigin,
|
||||
FeedbackAlive,
|
||||
VetoDelay,
|
||||
VetoReject,
|
||||
};
|
||||
|
||||
inline const char *fusion_hold_name(FusionHold h) {
|
||||
switch (h) {
|
||||
case FusionHold::None: return "none";
|
||||
case FusionHold::RxHeld: return "rx_held";
|
||||
case FusionHold::ModeForbidsTxOrigin: return "mode_forbids_tx_origin";
|
||||
case FusionHold::FeedbackAlive: return "feedback_alive";
|
||||
case FusionHold::VetoDelay: return "veto_delay";
|
||||
case FusionHold::VetoReject: return "veto_reject";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* "Never heard from the peer" — maximally stale, so a session that starts with
|
||||
* a dead return channel still adapts once the observation bar is met. */
|
||||
inline constexpr uint64_t kNoFeedback = ~uint64_t(0);
|
||||
|
||||
struct FusionConfig {
|
||||
FusionMode mode = FusionMode::RxPlusTxVeto;
|
||||
|
||||
uint64_t feedback_timeout_rounds = 30;
|
||||
|
||||
bool veto_on_broad_tx = true;
|
||||
bool veto_on_remaining_worse = true;
|
||||
double remaining_worse_margin = 0.20;
|
||||
uint32_t veto_min_chans_scored = 3;
|
||||
/* A flat band is only doubt when it is flat AND dirty. Flat and quiet is a
|
||||
* clean band — exactly what the transmitter sees when the interferer is at
|
||||
* the far end — and must not read as confusion. */
|
||||
double veto_broad_floor = 0.35;
|
||||
/* A persistently flat transmitter view must not suppress the receiver
|
||||
* forever; after this many consecutive delays the veto yields. */
|
||||
uint32_t max_consecutive_delays = 3;
|
||||
|
||||
bool reexamine_tx_exclusions = true;
|
||||
uint64_t reexamine_grace_rounds = 30;
|
||||
/* Below this delivery the receiver is taken to have corroborated an
|
||||
* autonomous exclusion, so it is left standing. */
|
||||
double corroborate_delivery = 0.50;
|
||||
|
||||
uint32_t policy_hash() const {
|
||||
uint32_t h = 2166136261u;
|
||||
auto fold = [&h](uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
h ^= static_cast<uint32_t>((v >> (8 * i)) & 0xff);
|
||||
h *= 16777619u;
|
||||
}
|
||||
};
|
||||
auto foldd = [&fold](double d) {
|
||||
fold(static_cast<uint64_t>(static_cast<int64_t>(d * 10000.0 + 0.5)));
|
||||
};
|
||||
fold(uint64_t(mode));
|
||||
fold(feedback_timeout_rounds);
|
||||
fold(veto_on_broad_tx ? 1 : 0);
|
||||
fold(veto_on_remaining_worse ? 1 : 0);
|
||||
foldd(remaining_worse_margin);
|
||||
fold(veto_min_chans_scored);
|
||||
foldd(veto_broad_floor);
|
||||
fold(max_consecutive_delays);
|
||||
fold(reexamine_tx_exclusions ? 1 : 0);
|
||||
fold(reexamine_grace_rounds);
|
||||
foldd(corroborate_delivery);
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
struct FusedDecision {
|
||||
DecisionOrigin origin = DecisionOrigin::Rx;
|
||||
FusedAction action = FusedAction::Hold;
|
||||
uint64_t mask = 0;
|
||||
size_t target_index = 0;
|
||||
uint32_t reason_bitmap = 0;
|
||||
FusionHold hold = FusionHold::None;
|
||||
FusionVeto veto = FusionVeto::None;
|
||||
uint64_t feedback_age_rounds = 0;
|
||||
uint32_t fusion_hash = 0;
|
||||
|
||||
/* Conflict surfacing — populated on every call, acted on by nobody. */
|
||||
bool rx_wanted_exclude = false;
|
||||
bool tx_wanted_exclude = false;
|
||||
bool endpoints_disagree_on_target = false;
|
||||
bool tx_evidence_valid = false;
|
||||
double tx_target_occupancy = 0.0;
|
||||
double tx_band_min_occupancy = 0.0;
|
||||
double tx_band_max_occupancy = 0.0;
|
||||
};
|
||||
|
||||
/* What a caller assembles per decision point. `tx_originated_mask`,
|
||||
* `consecutive_delays` and `feedback_fresh_since_round` are host-held so this
|
||||
* function stays stateless. */
|
||||
struct FusionInput {
|
||||
const HopsetDecision *rx = nullptr;
|
||||
const TxSenseCandidate *tx = nullptr;
|
||||
uint64_t active_mask = 0;
|
||||
uint64_t feedback_age_rounds = kNoFeedback;
|
||||
uint64_t now_round = 0;
|
||||
uint64_t tx_originated_mask = 0;
|
||||
uint64_t feedback_fresh_since_round = 0;
|
||||
uint32_t consecutive_delays = 0;
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline bool tx_has(const TxSenseCandidate &tx, size_t i) {
|
||||
return i < tx.chans.size() && tx.chans[i].have_evidence();
|
||||
}
|
||||
inline double tx_occ(const TxSenseCandidate &tx, size_t i) {
|
||||
return i < tx.chans.size() ? tx.chans[i].occupancy() : 0.0;
|
||||
}
|
||||
|
||||
/* The two veto grounds, against an exclusion the receiver proposed. Returns
|
||||
* the ground, or None to let the proposal through untouched. */
|
||||
inline FusionVeto veto_for(const FusionConfig &cfg, const TxSenseCandidate &tx,
|
||||
uint64_t active_mask, size_t target,
|
||||
uint32_t consecutive_delays) {
|
||||
/* Without our own evidence we have nothing to say. Recorded so the log
|
||||
* shows the veto was unreachable rather than merely unused. */
|
||||
if (tx.chans_with_evidence == 0) {
|
||||
for (const auto &c : tx.chans)
|
||||
if (c.sensor_absent)
|
||||
return FusionVeto::SensorAbsent;
|
||||
return FusionVeto::InsufficientTxEvidence;
|
||||
}
|
||||
if (tx.chans_with_evidence < cfg.veto_min_chans_scored || !tx_has(tx, target))
|
||||
return FusionVeto::InsufficientTxEvidence;
|
||||
|
||||
/* (a) The band is uniform AND dirty: nothing can be attributed to a
|
||||
* channel. A uniform QUIET band is not confusion — it is the ordinary
|
||||
* reading when the interferer sits at the far end — hence the floor. */
|
||||
if (cfg.veto_on_broad_tx && consecutive_delays < cfg.max_consecutive_delays &&
|
||||
(tx.broad_occupancy ||
|
||||
(tx.flat_band && tx.band_max_occ >= cfg.veto_broad_floor)))
|
||||
return FusionVeto::BroadTxDegradation;
|
||||
|
||||
/* (b) Every survivor is worse here than the target. Unanimity-gated: one
|
||||
* acceptable survivor, or one we have not measured, kills the veto — an
|
||||
* unmeasured escape route is not a road we may declare closed. */
|
||||
if (cfg.veto_on_remaining_worse) {
|
||||
const double t = tx_occ(tx, target);
|
||||
bool any_survivor = false;
|
||||
for (size_t i = 0; i < tx.chans.size(); ++i) {
|
||||
if (i == target || !(active_mask & (uint64_t(1) << i)))
|
||||
continue;
|
||||
if (!tx_has(tx, i))
|
||||
return FusionVeto::None; /* unmeasured survivor */
|
||||
if (tx_occ(tx, i) < t + cfg.remaining_worse_margin)
|
||||
return FusionVeto::None; /* an acceptable survivor exists */
|
||||
any_survivor = true;
|
||||
}
|
||||
if (any_survivor)
|
||||
return FusionVeto::RemainingWorse;
|
||||
}
|
||||
return FusionVeto::None;
|
||||
}
|
||||
|
||||
} /* namespace detail */
|
||||
|
||||
inline FusedDecision fuse(const FusionConfig &cfg, const FusionInput &in) {
|
||||
FusedDecision d;
|
||||
d.fusion_hash = cfg.policy_hash();
|
||||
d.feedback_age_rounds = in.feedback_age_rounds;
|
||||
|
||||
const HopsetDecision rx_none;
|
||||
const TxSenseCandidate tx_none;
|
||||
const HopsetDecision &rx = in.rx ? *in.rx : rx_none;
|
||||
const TxSenseCandidate &tx = in.tx ? *in.tx : tx_none;
|
||||
|
||||
d.rx_wanted_exclude = rx.kind == HopsetDecision::Kind::ProposeExclude;
|
||||
d.tx_wanted_exclude = tx.kind == TxSenseCandidate::Kind::ProposeExclude;
|
||||
d.tx_evidence_valid = tx.chans_with_evidence > 0;
|
||||
d.tx_band_min_occupancy = tx.band_min_occ;
|
||||
d.tx_band_max_occupancy = tx.band_max_occ;
|
||||
/* Whichever endpoint named a target, report OUR occupancy on it — when the
|
||||
* receiver named one that is the number the veto turns on, and when only
|
||||
* this side did it is the number a reader needs to judge a disagreement the
|
||||
* mode forbids acting on. */
|
||||
if (d.rx_wanted_exclude && detail::tx_has(tx, rx.target_index))
|
||||
d.tx_target_occupancy = detail::tx_occ(tx, rx.target_index);
|
||||
else if (d.tx_wanted_exclude && detail::tx_has(tx, tx.target_index))
|
||||
d.tx_target_occupancy = detail::tx_occ(tx, tx.target_index);
|
||||
d.endpoints_disagree_on_target =
|
||||
(d.rx_wanted_exclude != d.tx_wanted_exclude) ||
|
||||
(d.rx_wanted_exclude && d.tx_wanted_exclude &&
|
||||
rx.target_index != tx.target_index);
|
||||
if (d.endpoints_disagree_on_target)
|
||||
d.reason_bitmap |= RB_FUSE_TX_DISAGREES;
|
||||
if (!d.tx_evidence_valid)
|
||||
for (const auto &c : tx.chans)
|
||||
if (c.sensor_absent) {
|
||||
d.reason_bitmap |= RB_TX_SENSOR_ABSENT;
|
||||
break;
|
||||
}
|
||||
|
||||
const bool feedback_fresh =
|
||||
in.feedback_age_rounds != kNoFeedback &&
|
||||
in.feedback_age_rounds <= cfg.feedback_timeout_rounds;
|
||||
|
||||
/* Nothing the transmitter decided while blind survives without the
|
||||
* receiver's ratification. Once the uplink is back and the receiver has had
|
||||
* a grace window to form an opinion, an un-corroborated autonomous
|
||||
* exclusion is handed back — the receiver will take it again under its own
|
||||
* authority if the channel really is bad, which is the outcome we want. */
|
||||
if (cfg.reexamine_tx_exclusions && in.tx_originated_mask && feedback_fresh &&
|
||||
in.now_round >=
|
||||
in.feedback_fresh_since_round + cfg.reexamine_grace_rounds) {
|
||||
for (size_t i = 0; i < kMaxBaseChannels; ++i) {
|
||||
if (!(in.tx_originated_mask & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const bool corroborated = i < rx.chans.size() && rx.chans[i].scored &&
|
||||
rx.chans[i].delivery < cfg.corroborate_delivery;
|
||||
if (corroborated)
|
||||
continue;
|
||||
d.origin = DecisionOrigin::Fused;
|
||||
d.action = FusedAction::Restore;
|
||||
d.target_index = i;
|
||||
d.mask = in.active_mask | (uint64_t(1) << i);
|
||||
d.reason_bitmap |= RB_TX_REEXAMINED;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, DecisionOrigin::Fused);
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
/* Handing a channel back outranks taking one away, as on the receiver. */
|
||||
if (rx.kind == HopsetDecision::Kind::ProposeRestore) {
|
||||
d.origin = DecisionOrigin::Rx;
|
||||
d.action = FusedAction::Restore;
|
||||
d.mask = rx.proposed_mask;
|
||||
d.target_index = rx.target_index;
|
||||
d.reason_bitmap |= rx.reason_bitmap;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, DecisionOrigin::Rx);
|
||||
return d; /* restores are never vetoed: they only enlarge the option set */
|
||||
}
|
||||
|
||||
if (d.rx_wanted_exclude) {
|
||||
FusionVeto v = FusionVeto::None;
|
||||
if (cfg.mode != FusionMode::RxAuthoritative)
|
||||
v = detail::veto_for(cfg, tx, in.active_mask, rx.target_index,
|
||||
in.consecutive_delays);
|
||||
d.veto = v;
|
||||
d.target_index = rx.target_index;
|
||||
d.reason_bitmap |= rx.reason_bitmap;
|
||||
if (v == FusionVeto::BroadTxDegradation) {
|
||||
d.origin = DecisionOrigin::Fused;
|
||||
d.action = FusedAction::Delay;
|
||||
d.hold = FusionHold::VetoDelay;
|
||||
d.reason_bitmap |= RB_FUSE_VETO_BROAD;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, DecisionOrigin::Fused);
|
||||
return d;
|
||||
}
|
||||
if (v == FusionVeto::RemainingWorse) {
|
||||
d.origin = DecisionOrigin::Fused;
|
||||
d.action = FusedAction::Hold;
|
||||
d.hold = FusionHold::VetoReject;
|
||||
d.reason_bitmap |= RB_FUSE_VETO_REMAIN;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, DecisionOrigin::Fused);
|
||||
return d;
|
||||
}
|
||||
d.origin = DecisionOrigin::Rx;
|
||||
d.action = FusedAction::Exclude;
|
||||
d.mask = rx.proposed_mask;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, DecisionOrigin::Rx);
|
||||
return d;
|
||||
}
|
||||
|
||||
/* The receiver had nothing to say. Whether the transmitter may speak is a
|
||||
* question of mode and, for the failsafe, of whether the uplink is gone. */
|
||||
if (tx.kind == TxSenseCandidate::Kind::None) {
|
||||
d.origin = DecisionOrigin::Rx;
|
||||
d.action = FusedAction::Hold;
|
||||
d.hold = FusionHold::RxHeld;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* Held or not, the record names what this side wanted: an unacted-upon
|
||||
* disagreement still has to be legible after the fact. */
|
||||
d.target_index = tx.target_index;
|
||||
|
||||
DecisionOrigin origin = DecisionOrigin::Tx;
|
||||
switch (cfg.mode) {
|
||||
case FusionMode::RxAuthoritative:
|
||||
case FusionMode::RxPlusTxVeto:
|
||||
d.origin = DecisionOrigin::Rx;
|
||||
d.action = FusedAction::Hold;
|
||||
d.hold = FusionHold::ModeForbidsTxOrigin;
|
||||
return d;
|
||||
case FusionMode::TxFailsafe:
|
||||
if (feedback_fresh) {
|
||||
d.origin = DecisionOrigin::Rx;
|
||||
d.action = FusedAction::Hold;
|
||||
d.hold = FusionHold::FeedbackAlive;
|
||||
return d;
|
||||
}
|
||||
origin = DecisionOrigin::Failsafe;
|
||||
break;
|
||||
case FusionMode::EitherEndpoint:
|
||||
origin = DecisionOrigin::Tx;
|
||||
break;
|
||||
}
|
||||
|
||||
d.origin = origin;
|
||||
d.action = tx.kind == TxSenseCandidate::Kind::ProposeRestore
|
||||
? FusedAction::Restore
|
||||
: FusedAction::Exclude;
|
||||
d.mask = tx.proposed_mask;
|
||||
d.target_index = tx.target_index;
|
||||
d.reason_bitmap |= tx.reason_bitmap;
|
||||
d.reason_bitmap = rb_set_origin(d.reason_bitmap, origin);
|
||||
return d;
|
||||
}
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_FUSION_H */
|
||||
@@ -0,0 +1,470 @@
|
||||
/* HopsetPolicy — the receiver-side exclusion/restoration decision engine for
|
||||
* adaptive FHSS. The receiver decides because its delivery measurement
|
||||
* describes the endpoint that must actually decode; the transmitter validates
|
||||
* the proposal structurally and owns the commit.
|
||||
*
|
||||
* Delivery is authoritative. RSSI/SNR/EVM, energy counters and link verdicts
|
||||
* only *classify* an impairment (interference vs weak signal vs lost
|
||||
* synchronization) — they set explanation bits and never independently
|
||||
* trigger an exclusion, because a quiet channel with a dead link and a noisy
|
||||
* channel that still delivers are opposite decisions.
|
||||
*
|
||||
* Everything here is conservative by construction, because an adaptive
|
||||
* exclusion loop is an attack surface: an adversary who can make a channel
|
||||
* look bad can otherwise herd the link onto a single channel it then jams.
|
||||
* Hence the hard active-channel floor, one exclusion per update, the update
|
||||
* cooldown, the broad-degradation stop, the excluded-fraction cap, and
|
||||
* mandatory keyed probes before anything is restored.
|
||||
*
|
||||
* Pure: no I/O, no clock, no env, no randomness — the host feeds closed-slot
|
||||
* observations plus the current round and executes the decision. */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_POLICY_H
|
||||
#define DEVOURER_HOPSET_HOPSET_POLICY_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
#include "hopset/HopsetState.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
/* Explanation bits carried in the proposal's reason_bitmap. Bits 0..2 are the
|
||||
* decision's own evidence; 3..6 classify the impairment (never triggers);
|
||||
* 7..8 are the probe-driven restoration evidence. */
|
||||
enum HopsetReasonBit : uint32_t {
|
||||
RB_DELIVERY_FLOOR = 1u << 0, /* target delivery below the exclusion floor */
|
||||
RB_PERSISTENT = 1u << 1, /* sustained for impaired_rounds rounds */
|
||||
RB_HEALTHY_ALT = 1u << 2, /* another active channel is healthy */
|
||||
RB_CRC_DOMINANT = 1u << 3, /* frames arrive but fail FCS */
|
||||
RB_ENERGY_INTERFERENCE = 1u << 4, /* link verdict says interference */
|
||||
RB_WEAK_SIGNAL = 1u << 5, /* link verdict says weak signal */
|
||||
RB_SYNC_LOSS = 1u << 6, /* nothing decoded at all on the visit */
|
||||
RB_PROBE_RECOVERY = 1u << 7, /* probes cleared the restoration bar */
|
||||
RB_PROBE_EVIDENCE = 1u << 8, /* decision used keyed-probe observations */
|
||||
|
||||
/* Bits 9..23 belong to the transmitter-side sensing and fusion layers
|
||||
* (hopset/HopsetSense.h, hopset/HopsetFusion.h). They ride the same
|
||||
* reason_bitmap the proposal wire already carries, so adding them costs no
|
||||
* wire change and no marker version — and because the origin field encodes
|
||||
* "receiver" as zero, every proposal produced before those layers existed
|
||||
* still decodes with the right origin. */
|
||||
RB_ORIGIN_SHIFT = 9,
|
||||
RB_ORIGIN_MASK = 3u << 9, /* DecisionOrigin: 0=rx 1=tx 2=fused 3=failsafe */
|
||||
|
||||
RB_TX_CCA_HIGH = 1u << 11,
|
||||
RB_TX_NHM_BUSY = 1u << 12,
|
||||
RB_TX_IGI_ELEVATED = 1u << 13,
|
||||
RB_TX_POST_BURST = 1u << 14, /* post-burst evidence — a reactive emitter */
|
||||
RB_TX_PRE_BURST = 1u << 15,
|
||||
|
||||
RB_TX_CLEANER_ALT = 1u << 16,
|
||||
RB_TX_PERSISTENT = 1u << 17,
|
||||
RB_TX_SENSOR_ABSENT = 1u << 18,
|
||||
RB_TX_IGI_RAILED = 1u << 19,
|
||||
|
||||
RB_FUSE_TX_DISAGREES = 1u << 20, /* endpoints differ; NOT itself a veto */
|
||||
RB_FUSE_VETO_BROAD = 1u << 21,
|
||||
RB_FUSE_VETO_REMAIN = 1u << 22,
|
||||
RB_TX_REEXAMINED = 1u << 23, /* restoring a TX-originated exclusion */
|
||||
};
|
||||
|
||||
/* Why a decide() returned Hold — every path names exactly one. */
|
||||
enum class HopsetHold : uint8_t {
|
||||
None = 0,
|
||||
InsufficientRounds,
|
||||
Cooldown,
|
||||
ProposalOutstanding,
|
||||
NoImpairment,
|
||||
NotPersistent,
|
||||
BroadDegradation,
|
||||
NoHealthyAlternative,
|
||||
MinActiveFloor,
|
||||
MaxExcludedFrac,
|
||||
ProbeHysteresisPending,
|
||||
};
|
||||
|
||||
inline const char *hopset_hold_name(HopsetHold h) {
|
||||
switch (h) {
|
||||
case HopsetHold::None: return "none";
|
||||
case HopsetHold::InsufficientRounds: return "insufficient_rounds";
|
||||
case HopsetHold::Cooldown: return "cooldown";
|
||||
case HopsetHold::ProposalOutstanding: return "proposal_outstanding";
|
||||
case HopsetHold::NoImpairment: return "no_impairment";
|
||||
case HopsetHold::NotPersistent: return "not_persistent";
|
||||
case HopsetHold::BroadDegradation: return "broad_degradation";
|
||||
case HopsetHold::NoHealthyAlternative: return "no_healthy_alternative";
|
||||
case HopsetHold::MinActiveFloor: return "min_active_floor";
|
||||
case HopsetHold::MaxExcludedFrac: return "max_excluded_frac";
|
||||
case HopsetHold::ProbeHysteresisPending: return "probe_hysteresis_pending";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* Conservative shipping defaults. Every field is caller-tunable; the hash
|
||||
* stamps the exact configuration into each decision so a log replay is
|
||||
* reproducible. */
|
||||
struct HopsetPolicyConfig {
|
||||
uint32_t min_obs_rounds = 8; /* scored rounds before any decision */
|
||||
uint32_t impaired_rounds = 5; /* consecutive impaired visits required */
|
||||
double exclude_delivery = 0.30; /* per-visit delivery below this = impaired */
|
||||
double healthy_delivery = 0.70; /* windowed delivery at/above this = healthy */
|
||||
uint32_t min_active = 3; /* hard floor on active channels */
|
||||
uint64_t update_cooldown_rounds = 10;
|
||||
double restore_delivery = 0.70; /* probe delivery above this counts */
|
||||
uint32_t restore_probes = 3; /* consecutive good probes to restore */
|
||||
double broad_degrade_frac = 0.50; /* impaired share that stops exclusion */
|
||||
double max_excluded_frac = 0.50; /* cap on excluded/base */
|
||||
uint32_t ring_rounds = 16; /* per-channel sliding window depth */
|
||||
|
||||
uint32_t policy_hash() const {
|
||||
uint32_t h = 2166136261u;
|
||||
auto fold = [&h](uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
h ^= static_cast<uint32_t>((v >> (8 * i)) & 0xff);
|
||||
h *= 16777619u;
|
||||
}
|
||||
};
|
||||
/* doubles fold as fixed-point so the hash is bit-identical everywhere */
|
||||
auto foldd = [&fold](double d) {
|
||||
fold(static_cast<uint64_t>(static_cast<int64_t>(d * 10000.0 + 0.5)));
|
||||
};
|
||||
fold(min_obs_rounds);
|
||||
fold(impaired_rounds);
|
||||
foldd(exclude_delivery);
|
||||
foldd(healthy_delivery);
|
||||
fold(min_active);
|
||||
fold(update_cooldown_rounds);
|
||||
foldd(restore_delivery);
|
||||
fold(restore_probes);
|
||||
foldd(broad_degrade_frac);
|
||||
foldd(max_excluded_frac);
|
||||
fold(ring_rounds);
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
/* One closed slot, snapshotted by the host at the dwell boundary. `decoded`
|
||||
* is the schedule-level fact (did the transmitter's marker arrive at all);
|
||||
* frames/crc_errs refine it into a ratio when the receiver surfaces corrupt
|
||||
* frames. verdict is an optional LinkVerdict value — classification only. */
|
||||
struct SlotObservation {
|
||||
uint64_t slot = 0;
|
||||
uint64_t round = 0;
|
||||
uint32_t base_index = 0;
|
||||
bool is_probe = false;
|
||||
bool decoded = false;
|
||||
uint32_t frames = 0; /* own-transmitter frames delivered in the dwell */
|
||||
uint32_t crc_errs = 0; /* frames that arrived corrupt (when surfaced) */
|
||||
int rssi = -1; /* raw PWDB mean, <0 = no reading */
|
||||
int snr = 0;
|
||||
int evm = 0;
|
||||
uint32_t dead_us = 0; /* retune -> first decode; 0 when nothing decoded */
|
||||
uint8_t verdict = 255; /* LinkVerdict, 255 = none */
|
||||
};
|
||||
|
||||
/* A per-channel evidence summary, carried on the decision so the event log
|
||||
* explains it without re-deriving anything. */
|
||||
struct HopsetChanScore {
|
||||
uint32_t visits = 0;
|
||||
uint32_t decoded = 0;
|
||||
double delivery = 0.0; /* windowed, data visits */
|
||||
double probe_delivery = 0.0; /* windowed, probe visits */
|
||||
uint32_t probes = 0;
|
||||
uint32_t impaired_run = 0;
|
||||
bool active = false;
|
||||
bool scored = false;
|
||||
};
|
||||
|
||||
struct HopsetDecision {
|
||||
enum class Kind : uint8_t { Hold, ProposeExclude, ProposeRestore } kind =
|
||||
Kind::Hold;
|
||||
uint64_t proposed_mask = 0;
|
||||
uint32_t reason_bitmap = 0;
|
||||
uint32_t observation_count = 0;
|
||||
HopsetHold hold = HopsetHold::None;
|
||||
size_t target_index = 0;
|
||||
uint32_t policy_hash = 0;
|
||||
std::vector<HopsetChanScore> chans;
|
||||
};
|
||||
|
||||
class HopsetPolicy {
|
||||
public:
|
||||
HopsetPolicy(const HopsetPolicyConfig &cfg, size_t n_base)
|
||||
: cfg_(cfg), n_(n_base), ch_(n_base) {
|
||||
if (!n_base || n_base > kMaxBaseChannels)
|
||||
throw std::invalid_argument("base hopset size out of range");
|
||||
mask_ = full_mask(n_base);
|
||||
}
|
||||
|
||||
const HopsetPolicyConfig &config() const { return cfg_; }
|
||||
uint64_t active_mask() const { return mask_; }
|
||||
|
||||
/* Fold one closed slot. Each active channel is visited exactly once per
|
||||
* round, so a data visit *is* that channel's round score — no separate
|
||||
* round-closing step, and a probe-displaced visit simply doesn't advance
|
||||
* that channel's run. */
|
||||
void ingest(const SlotObservation &o) {
|
||||
if (o.base_index >= n_)
|
||||
return;
|
||||
if (!any_seen_) {
|
||||
any_seen_ = true;
|
||||
rounds_seen_ = 1;
|
||||
last_round_ = o.round;
|
||||
} else if (o.round != last_round_) {
|
||||
++rounds_seen_;
|
||||
last_round_ = o.round;
|
||||
}
|
||||
Chan &c = ch_[o.base_index];
|
||||
const double d = delivery_of(o);
|
||||
if (o.is_probe) {
|
||||
push(c.probe_ring, c.probe_n, c.probe_head, d);
|
||||
c.probe_good_run = d > cfg_.restore_delivery ? c.probe_good_run + 1 : 0;
|
||||
c.probes++;
|
||||
c.saw_probe = true;
|
||||
} else {
|
||||
push(c.ring, c.ring_n, c.ring_head, d);
|
||||
c.visits++;
|
||||
if (d > 0.0)
|
||||
c.decoded++;
|
||||
c.impaired_run = d < cfg_.exclude_delivery ? c.impaired_run + 1 : 0;
|
||||
/* classification: never a trigger, only an explanation */
|
||||
if (o.frames > 0 && o.crc_errs * 2 >= o.frames)
|
||||
c.crc_dominant = true;
|
||||
if (!o.decoded && o.frames == 0)
|
||||
c.sync_loss = true;
|
||||
if (o.verdict == kVerdictInterference)
|
||||
c.energy_interference = true;
|
||||
if (o.verdict == kVerdictWeak)
|
||||
c.weak_signal = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* A committed state took effect: re-anchor the cooldown, adopt the mask,
|
||||
* and clear the evidence of whatever just changed so a restored channel
|
||||
* starts from a clean slate instead of its pre-exclusion history. */
|
||||
void on_activation(uint64_t mask, uint64_t now_round) {
|
||||
const uint64_t changed = mask ^ mask_;
|
||||
for (size_t i = 0; i < n_; ++i)
|
||||
if (changed & (uint64_t(1) << i))
|
||||
ch_[i] = Chan{};
|
||||
mask_ = mask;
|
||||
last_update_round_ = now_round;
|
||||
have_update_ = true;
|
||||
outstanding_ = false;
|
||||
}
|
||||
|
||||
/* The proposal was answered (rejected, or timed out) without activating.
|
||||
* A refused attempt still consumes the update budget: otherwise a receiver
|
||||
* whose proposals keep bouncing — exactly what happens against a jammer
|
||||
* that moves after every exclusion — re-proposes on every round boundary
|
||||
* and floods the control channel. */
|
||||
void clear_outstanding(uint64_t now_round) {
|
||||
outstanding_ = false;
|
||||
last_update_round_ = now_round;
|
||||
have_update_ = true;
|
||||
}
|
||||
bool proposal_outstanding() const { return outstanding_; }
|
||||
|
||||
HopsetDecision decide(uint64_t now_round) {
|
||||
HopsetDecision d;
|
||||
d.policy_hash = cfg_.policy_hash();
|
||||
d.observation_count = rounds_seen_;
|
||||
d.chans = summarize();
|
||||
|
||||
if (rounds_seen_ < cfg_.min_obs_rounds)
|
||||
return hold(d, HopsetHold::InsufficientRounds);
|
||||
if (outstanding_)
|
||||
return hold(d, HopsetHold::ProposalOutstanding);
|
||||
if (have_update_ && now_round - last_update_round_ <
|
||||
cfg_.update_cooldown_rounds)
|
||||
return hold(d, HopsetHold::Cooldown);
|
||||
|
||||
/* --- restoration first: giving a channel back is the safer move, and
|
||||
* it keeps a herding adversary from ratcheting the set down --- */
|
||||
const uint64_t excluded = full_mask(n_) & ~mask_;
|
||||
bool probe_pending = false;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(excluded & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (c.probe_good_run >= cfg_.restore_probes) {
|
||||
d.kind = HopsetDecision::Kind::ProposeRestore;
|
||||
d.target_index = i;
|
||||
d.proposed_mask = mask_ | (uint64_t(1) << i);
|
||||
d.reason_bitmap = RB_PROBE_RECOVERY | RB_PROBE_EVIDENCE;
|
||||
outstanding_ = true;
|
||||
return d;
|
||||
}
|
||||
if (c.saw_probe)
|
||||
probe_pending = true;
|
||||
}
|
||||
|
||||
/* --- exclusion: the worst sustained-impaired active channel --- */
|
||||
size_t worst = 0;
|
||||
bool have_worst = false;
|
||||
double worst_delivery = 1.0;
|
||||
unsigned impaired_active = 0, active_scored = 0;
|
||||
bool healthy_alt = false, any_impaired = false;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(mask_ & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (!c.ring_n)
|
||||
continue;
|
||||
++active_scored;
|
||||
const double w = window_delivery(c);
|
||||
if (w < cfg_.healthy_delivery)
|
||||
++impaired_active;
|
||||
if (c.impaired_run > 0)
|
||||
any_impaired = true;
|
||||
/* the trigger is the sustained run of impaired visits, exactly as the
|
||||
* policy is stated; the windowed mean only ranks the candidates */
|
||||
if (c.impaired_run >= cfg_.impaired_rounds &&
|
||||
(!have_worst || w < worst_delivery)) {
|
||||
have_worst = true;
|
||||
worst = i;
|
||||
worst_delivery = w;
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(mask_ & (uint64_t(1) << i)) || (have_worst && i == worst))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (c.ring_n && window_delivery(c) >= cfg_.healthy_delivery)
|
||||
healthy_alt = true;
|
||||
}
|
||||
|
||||
if (!have_worst) {
|
||||
if (probe_pending)
|
||||
return hold(d, HopsetHold::ProbeHysteresisPending);
|
||||
return hold(d, any_impaired ? HopsetHold::NotPersistent
|
||||
: HopsetHold::NoImpairment);
|
||||
}
|
||||
/* When most of the band degrades together the problem is not the
|
||||
* channel — excluding would only shrink diversity for nothing. */
|
||||
if (active_scored &&
|
||||
static_cast<double>(impaired_active) /
|
||||
static_cast<double>(active_scored) >=
|
||||
cfg_.broad_degrade_frac)
|
||||
return hold(d, HopsetHold::BroadDegradation);
|
||||
if (!healthy_alt)
|
||||
return hold(d, HopsetHold::NoHealthyAlternative);
|
||||
|
||||
const uint64_t after = mask_ & ~(uint64_t(1) << worst);
|
||||
const uint32_t floor_active =
|
||||
cfg_.min_active < 3u ? 3u : cfg_.min_active;
|
||||
if (popcount64(after) < floor_active)
|
||||
return hold(d, HopsetHold::MinActiveFloor);
|
||||
if (static_cast<double>(popcount64(full_mask(n_) & ~after)) /
|
||||
static_cast<double>(n_) >
|
||||
cfg_.max_excluded_frac)
|
||||
return hold(d, HopsetHold::MaxExcludedFrac);
|
||||
|
||||
d.kind = HopsetDecision::Kind::ProposeExclude;
|
||||
d.target_index = worst;
|
||||
d.proposed_mask = after;
|
||||
d.reason_bitmap = RB_DELIVERY_FLOOR | RB_PERSISTENT | RB_HEALTHY_ALT;
|
||||
const Chan &c = ch_[worst];
|
||||
if (c.crc_dominant)
|
||||
d.reason_bitmap |= RB_CRC_DOMINANT;
|
||||
if (c.sync_loss)
|
||||
d.reason_bitmap |= RB_SYNC_LOSS;
|
||||
if (c.energy_interference)
|
||||
d.reason_bitmap |= RB_ENERGY_INTERFERENCE;
|
||||
if (c.weak_signal)
|
||||
d.reason_bitmap |= RB_WEAK_SIGNAL;
|
||||
outstanding_ = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
private:
|
||||
/* LinkVerdict values used for classification, kept as plain constants so
|
||||
* this header stays free of the RX-sensor headers. */
|
||||
static constexpr uint8_t kVerdictInterference = 2;
|
||||
static constexpr uint8_t kVerdictWeak = 3;
|
||||
static constexpr size_t kRing = 64;
|
||||
|
||||
struct Chan {
|
||||
/* rings hold the per-visit delivery RATIO, not a pass/fail bit: the
|
||||
* windowed mean is what "another channel remains healthy" and "most
|
||||
* channels degraded together" have to read, and a bit would score a
|
||||
* half-delivering channel as healthy. */
|
||||
double ring[kRing]{};
|
||||
uint32_t ring_n = 0, ring_head = 0;
|
||||
double probe_ring[kRing]{};
|
||||
uint32_t probe_n = 0, probe_head = 0;
|
||||
uint32_t visits = 0, decoded = 0, probes = 0;
|
||||
uint32_t impaired_run = 0, probe_good_run = 0;
|
||||
bool crc_dominant = false, sync_loss = false;
|
||||
bool energy_interference = false, weak_signal = false;
|
||||
bool saw_probe = false;
|
||||
};
|
||||
|
||||
void push(double *ring, uint32_t &n, uint32_t &head, double v) {
|
||||
const uint32_t depth =
|
||||
cfg_.ring_rounds < kRing ? cfg_.ring_rounds : uint32_t(kRing);
|
||||
ring[head] = v;
|
||||
head = (head + 1) % (depth ? depth : 1);
|
||||
if (n < depth)
|
||||
++n;
|
||||
}
|
||||
|
||||
static double ratio(const double *ring, uint32_t n) {
|
||||
if (!n)
|
||||
return 0.0;
|
||||
double sum = 0.0;
|
||||
for (uint32_t i = 0; i < n; ++i)
|
||||
sum += ring[i];
|
||||
return sum / static_cast<double>(n);
|
||||
}
|
||||
|
||||
static double window_delivery(const Chan &c) { return ratio(c.ring, c.ring_n); }
|
||||
|
||||
double delivery_of(const SlotObservation &o) const {
|
||||
if (!o.decoded)
|
||||
return 0.0;
|
||||
if (o.frames == 0)
|
||||
return 1.0; /* the marker decoded; no per-frame detail surfaced */
|
||||
const uint32_t good = o.frames > o.crc_errs ? o.frames - o.crc_errs : 0;
|
||||
return static_cast<double>(good) / static_cast<double>(o.frames);
|
||||
}
|
||||
|
||||
std::vector<HopsetChanScore> summarize() const {
|
||||
std::vector<HopsetChanScore> out(n_);
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
const Chan &c = ch_[i];
|
||||
HopsetChanScore &s = out[i];
|
||||
s.visits = c.visits;
|
||||
s.decoded = c.decoded;
|
||||
s.delivery = window_delivery(c);
|
||||
s.probe_delivery = ratio(c.probe_ring, c.probe_n);
|
||||
s.probes = c.probes;
|
||||
s.impaired_run = c.impaired_run;
|
||||
s.active = (mask_ & (uint64_t(1) << i)) != 0;
|
||||
s.scored = c.ring_n != 0 || c.probe_n != 0;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static HopsetDecision &hold(HopsetDecision &d, HopsetHold h) {
|
||||
d.kind = HopsetDecision::Kind::Hold;
|
||||
d.hold = h;
|
||||
return d;
|
||||
}
|
||||
|
||||
HopsetPolicyConfig cfg_;
|
||||
size_t n_;
|
||||
std::vector<Chan> ch_;
|
||||
uint64_t mask_ = 0;
|
||||
uint64_t last_round_ = 0, last_update_round_ = 0;
|
||||
uint32_t rounds_seen_ = 0;
|
||||
bool any_seen_ = false, have_update_ = false, outstanding_ = false;
|
||||
};
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_POLICY_H */
|
||||
@@ -0,0 +1,711 @@
|
||||
/* HopsetSense — the transmitter's own view of the band, and the conservative
|
||||
* classifier that turns it into an exclusion candidate.
|
||||
*
|
||||
* The transmitter measures interference where the transmitter sits, which is
|
||||
* not where the receiver sits. That single fact governs every threshold here:
|
||||
* TX energy is a *proxy* for the thing we care about (does the video arrive),
|
||||
* whereas the receiver's delivery is a direct measurement of it. A proxy needs
|
||||
* more evidence before it may act, so everything in this module is stricter
|
||||
* than its receiver-side counterpart — more samples, longer runs, longer
|
||||
* cooldown, and two demonstrably cleaner alternatives instead of one.
|
||||
*
|
||||
* Two structural rules that are easy to get wrong:
|
||||
*
|
||||
* - "No sensor" is not "clean". A generation with no false-alarm/CCA/IGI
|
||||
* facility (Kestrel) must report absence, never a quiet reading, or the
|
||||
* fusion layer will happily conclude the band is empty.
|
||||
* - Pre-burst and post-burst observations answer different questions and are
|
||||
* never pooled. A reactive jammer keys up only after it hears us, so it is
|
||||
* structurally invisible before our burst and plainly visible after it;
|
||||
* averaging the two halves hides exactly the adversary they exist to find.
|
||||
*
|
||||
* Pure: no I/O, no clock, no randomness. The host samples the chip and feeds
|
||||
* closed windows in. */
|
||||
#ifndef DEVOURER_HOPSET_HOPSET_SENSE_H
|
||||
#define DEVOURER_HOPSET_HOPSET_SENSE_H
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
#include "hopset/HopsetPolicy.h"
|
||||
#include "hopset/HopsetState.h"
|
||||
|
||||
namespace devourer {
|
||||
namespace hopset {
|
||||
|
||||
/* Which question a sample answers. */
|
||||
enum class SensePhase : uint8_t { PreBurst = 0, PostBurst = 1 };
|
||||
inline constexpr size_t kSensePhases = 2;
|
||||
|
||||
/* Why a sample may be inadmissible. Recorded, never silently dropped. */
|
||||
enum TxSenseFlag : uint16_t {
|
||||
kTsRetuneFailed = 1u << 0,
|
||||
kTsReadFailed = 1u << 1,
|
||||
kTsCounterSuspect = 1u << 2,
|
||||
kTsBarrierMissed = 1u << 3, /* taken without the discard barrier */
|
||||
kTsTruncated = 1u << 4,
|
||||
kTsNhmMissing = 1u << 5,
|
||||
kTsInjected = 1u << 6, /* synthetic evidence, no hardware behind it */
|
||||
};
|
||||
|
||||
/* One quiet-window observation. The counters are deltas spanning exactly
|
||||
* window_us (measured, not nominal — the hardware keeps counting during the
|
||||
* read's own bus round-trips), so rates are comparable across windows of
|
||||
* different length. Every optional source carries its own valid flag. */
|
||||
struct TxSenseSample {
|
||||
uint64_t slot = 0;
|
||||
uint64_t round = 0;
|
||||
uint32_t base_index = 0;
|
||||
SensePhase phase = SensePhase::PreBurst;
|
||||
uint32_t window_us = 0;
|
||||
bool probe = false; /* taken on a keyed recovery-probe dwell */
|
||||
|
||||
bool valid_fa = false;
|
||||
uint32_t fa_ofdm = 0, fa_cck = 0, cca_ofdm = 0, cca_cck = 0;
|
||||
|
||||
bool valid_igi = false;
|
||||
uint8_t igi = 0;
|
||||
|
||||
bool valid_nhm = false;
|
||||
uint8_t nhm_busy_pct = 0; /* 100*(total-bucket0)/total, host-derived */
|
||||
uint16_t nhm_duration = 0;
|
||||
|
||||
/* Synthetic evidence. A caller that sets this hands the scorer an occupancy
|
||||
* directly instead of counters, and every stage downstream — ring depth,
|
||||
* dirty-run hysteresis, the cleaner-alternative rule, the floors — treats it
|
||||
* exactly like a measured one. It exists so the two endpoint-disagreement
|
||||
* scenarios can be built on a bench where both adapters hear the same
|
||||
* interferer: the only way to give the transmitter a view that genuinely
|
||||
* differs from the receiver's is to construct it. */
|
||||
bool injected = false;
|
||||
double injected_occupancy = 0.0;
|
||||
|
||||
uint16_t flags = 0;
|
||||
};
|
||||
|
||||
/* Which sources contributed to a score — so a consumer can tell a confident
|
||||
* three-source reading from a lone noisy one. */
|
||||
enum TxSenseSource : uint8_t {
|
||||
kSrcCca = 1u << 0,
|
||||
kSrcFa = 1u << 1,
|
||||
kSrcIgi = 1u << 2,
|
||||
kSrcNhm = 1u << 3,
|
||||
kSrcInjected = 1u << 4,
|
||||
};
|
||||
|
||||
struct TxSenseConfig {
|
||||
/* --- admission --- */
|
||||
uint32_t min_window_us = 800;
|
||||
uint32_t max_counts_per_ms = 1000; /* beyond this the counter wrapped */
|
||||
uint8_t igi_floor = 0x1c;
|
||||
uint8_t igi_ceiling = 0x7f;
|
||||
|
||||
/* --- occupancy scoring ---
|
||||
* The saturation rates are MEASURED, not guessed: an 8812CU sensing its own
|
||||
* dwell against a narrowband interferer that destroys delivery reads about
|
||||
* 2.8 CCA and 3.0 false alarms per millisecond, against roughly 0.6 on a
|
||||
* clean channel. Earlier estimates of 40 and 20 per millisecond were about
|
||||
* thirty times too high, which scored a fully jammed channel at 0.03 of full
|
||||
* scale — it could never have crossed any sensible threshold.
|
||||
*
|
||||
* False alarms carry more weight than CCA because they separate better: the
|
||||
* same measurement puts false alarms at roughly 5.6:1 jammed-to-clean and
|
||||
* CCA at 4.8:1, and CCA also counts legitimate traffic. */
|
||||
double cca_rate_sat = 3.0; /* events/ms mapping to 1.0 */
|
||||
double fa_rate_sat = 3.0;
|
||||
double igi_span = 32.0; /* IGI counts above the floor mapping to 1.0 */
|
||||
double w_cca = 0.30, w_fa = 0.35, w_igi = 0.15, w_nhm = 0.20;
|
||||
|
||||
/* --- evidence sufficiency (deliberately stricter than the RX policy) --- */
|
||||
uint32_t min_samples_per_chan = 12;
|
||||
uint32_t min_channels_scored = 3;
|
||||
uint32_t ring_samples = 24;
|
||||
uint32_t min_obs_rounds = 24;
|
||||
|
||||
/* --- exclusion trigger --- */
|
||||
double occupancy_dirty = 0.60;
|
||||
uint32_t dirty_run = 10;
|
||||
double cleaner_margin = 0.30;
|
||||
uint32_t min_cleaner_chans = 2;
|
||||
double broad_occupancy_frac = 0.50;
|
||||
double broad_spread_min = 0.25;
|
||||
bool require_post_burst = true;
|
||||
|
||||
/* --- restoration through keyed probes (the TX's own recovery evidence) --- */
|
||||
double restore_occupancy = 0.25;
|
||||
uint32_t restore_probes = 3;
|
||||
|
||||
/* --- pacing + the anti-herding floors, re-checked here --- */
|
||||
uint64_t cooldown_rounds = 40;
|
||||
uint32_t min_active = 3;
|
||||
double max_excluded_frac = 0.50;
|
||||
|
||||
uint32_t policy_hash() const {
|
||||
uint32_t h = 2166136261u;
|
||||
auto fold = [&h](uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
h ^= static_cast<uint32_t>((v >> (8 * i)) & 0xff);
|
||||
h *= 16777619u;
|
||||
}
|
||||
};
|
||||
auto foldd = [&fold](double d) {
|
||||
fold(static_cast<uint64_t>(static_cast<int64_t>(d * 10000.0 + 0.5)));
|
||||
};
|
||||
fold(min_window_us);
|
||||
fold(max_counts_per_ms);
|
||||
fold(igi_floor);
|
||||
fold(igi_ceiling);
|
||||
foldd(cca_rate_sat);
|
||||
foldd(fa_rate_sat);
|
||||
foldd(igi_span);
|
||||
foldd(w_cca);
|
||||
foldd(w_fa);
|
||||
foldd(w_igi);
|
||||
foldd(w_nhm);
|
||||
fold(min_samples_per_chan);
|
||||
fold(min_channels_scored);
|
||||
fold(ring_samples);
|
||||
fold(min_obs_rounds);
|
||||
foldd(occupancy_dirty);
|
||||
fold(dirty_run);
|
||||
foldd(cleaner_margin);
|
||||
fold(min_cleaner_chans);
|
||||
foldd(broad_occupancy_frac);
|
||||
foldd(broad_spread_min);
|
||||
fold(require_post_burst ? 1 : 0);
|
||||
foldd(restore_occupancy);
|
||||
fold(restore_probes);
|
||||
fold(cooldown_rounds);
|
||||
fold(min_active);
|
||||
foldd(max_excluded_frac);
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
struct SenseScore {
|
||||
double occupancy = 0.0;
|
||||
uint8_t sources = 0;
|
||||
};
|
||||
|
||||
/* Normalize one sample to [0,1]. Returns false when NO source was valid — the
|
||||
* caller must not treat that as 0.0 occupancy, which is the whole point. */
|
||||
inline bool score_sample(const TxSenseSample &s, const TxSenseConfig &cfg,
|
||||
SenseScore &out) {
|
||||
const double win_ms = static_cast<double>(s.window_us) / 1000.0;
|
||||
if (win_ms <= 0.0)
|
||||
return false;
|
||||
/* Synthetic evidence is returned verbatim: the four-source weighting exists
|
||||
* to turn counters into an occupancy, and here the occupancy is what the
|
||||
* caller handed us. Back-solving it through the weights would make the
|
||||
* lever approximate, and an approximate lever proves nothing. */
|
||||
if (s.injected) {
|
||||
const double v = s.injected_occupancy;
|
||||
out.occupancy = v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v);
|
||||
out.sources = kSrcInjected;
|
||||
return true;
|
||||
}
|
||||
double acc = 0.0, wsum = 0.0;
|
||||
uint8_t src = 0;
|
||||
auto clamp01 = [](double v) { return v < 0.0 ? 0.0 : (v > 1.0 ? 1.0 : v); };
|
||||
if (s.valid_fa) {
|
||||
const double cca = static_cast<double>(s.cca_ofdm + s.cca_cck) / win_ms;
|
||||
acc += cfg.w_cca * clamp01(cca / cfg.cca_rate_sat);
|
||||
wsum += cfg.w_cca;
|
||||
src |= kSrcCca;
|
||||
const double fa = static_cast<double>(s.fa_ofdm + s.fa_cck) / win_ms;
|
||||
acc += cfg.w_fa * clamp01(fa / cfg.fa_rate_sat);
|
||||
wsum += cfg.w_fa;
|
||||
src |= kSrcFa;
|
||||
}
|
||||
/* A railed IGI is not a reading: at the floor there is nothing to see, at
|
||||
* the ceiling the value is off-scale. Neither is linear, so neither
|
||||
* contributes — and the ceiling must never be mistaken for "maximally
|
||||
* busy". */
|
||||
if (s.valid_igi && s.igi > cfg.igi_floor && s.igi < cfg.igi_ceiling) {
|
||||
acc += cfg.w_igi *
|
||||
clamp01((static_cast<double>(s.igi) - cfg.igi_floor) / cfg.igi_span);
|
||||
wsum += cfg.w_igi;
|
||||
src |= kSrcIgi;
|
||||
}
|
||||
/* The histogram's buckets are placed relative to the gain index, so when
|
||||
* that index sits at its floor the buckets sit below the real noise floor
|
||||
* and every channel reads fully busy. A railed reading is not a measurement
|
||||
* — same rule as the gain index itself. */
|
||||
if (s.valid_nhm && s.nhm_duration > 0 && s.nhm_busy_pct > 0 &&
|
||||
s.nhm_busy_pct < 100) {
|
||||
acc += cfg.w_nhm * clamp01(static_cast<double>(s.nhm_busy_pct) / 100.0);
|
||||
wsum += cfg.w_nhm;
|
||||
src |= kSrcNhm;
|
||||
}
|
||||
if (!src || wsum <= 0.0)
|
||||
return false;
|
||||
out.occupancy = acc / wsum;
|
||||
out.sources = src;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct TxPhaseEvidence {
|
||||
uint32_t samples = 0;
|
||||
uint32_t dropped = 0;
|
||||
double occupancy = 0.0;
|
||||
double occupancy_max = 0.0;
|
||||
uint32_t dirty_run = 0;
|
||||
uint32_t clean_run = 0;
|
||||
uint8_t sources_seen = 0;
|
||||
bool scored = false;
|
||||
bool igi_railed = false;
|
||||
};
|
||||
|
||||
struct TxChanEvidence {
|
||||
TxPhaseEvidence pre, post;
|
||||
bool active = false;
|
||||
bool sensor_absent = false;
|
||||
uint32_t probe_good_run = 0;
|
||||
uint32_t probes = 0;
|
||||
|
||||
bool have_evidence() const { return post.scored || pre.scored; }
|
||||
/* Post-burst is the sharper instrument when we have it. Only ever read
|
||||
* this after have_evidence(). */
|
||||
double occupancy() const {
|
||||
return post.scored ? post.occupancy : pre.occupancy;
|
||||
}
|
||||
};
|
||||
|
||||
enum class TxSenseHold : uint8_t {
|
||||
None = 0,
|
||||
SensorAbsent,
|
||||
InsufficientRounds,
|
||||
InsufficientSamples,
|
||||
InsufficientChannels,
|
||||
Cooldown,
|
||||
ProposalOutstanding,
|
||||
NoOccupancy,
|
||||
NotPersistent,
|
||||
PostBurstMissing,
|
||||
BroadOccupancy,
|
||||
FlatBand,
|
||||
NoCleanerAlternative,
|
||||
MinActiveFloor,
|
||||
MaxExcludedFrac,
|
||||
};
|
||||
|
||||
inline const char *tx_sense_hold_name(TxSenseHold h) {
|
||||
switch (h) {
|
||||
case TxSenseHold::None: return "none";
|
||||
case TxSenseHold::SensorAbsent: return "sensor_absent";
|
||||
case TxSenseHold::InsufficientRounds: return "insufficient_rounds";
|
||||
case TxSenseHold::InsufficientSamples: return "insufficient_samples";
|
||||
case TxSenseHold::InsufficientChannels: return "insufficient_channels";
|
||||
case TxSenseHold::Cooldown: return "cooldown";
|
||||
case TxSenseHold::ProposalOutstanding: return "proposal_outstanding";
|
||||
case TxSenseHold::NoOccupancy: return "no_occupancy";
|
||||
case TxSenseHold::NotPersistent: return "not_persistent";
|
||||
case TxSenseHold::PostBurstMissing: return "post_burst_missing";
|
||||
case TxSenseHold::BroadOccupancy: return "broad_occupancy";
|
||||
case TxSenseHold::FlatBand: return "flat_band";
|
||||
case TxSenseHold::NoCleanerAlternative: return "no_cleaner_alternative";
|
||||
case TxSenseHold::MinActiveFloor: return "min_active_floor";
|
||||
case TxSenseHold::MaxExcludedFrac: return "max_excluded_frac";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
struct TxSenseCandidate {
|
||||
enum class Kind : uint8_t { None, ProposeExclude, ProposeRestore } kind =
|
||||
Kind::None;
|
||||
size_t target_index = 0;
|
||||
uint64_t proposed_mask = 0;
|
||||
uint32_t reason_bitmap = 0;
|
||||
TxSenseHold hold = TxSenseHold::None;
|
||||
uint32_t sample_count = 0;
|
||||
uint32_t policy_hash = 0;
|
||||
/* Band-level facts the fusion layer needs and must not re-derive. Reported
|
||||
* even when kind == None: the veto path needs the broad-degradation fact
|
||||
* regardless of whether the sensor itself wanted to act. */
|
||||
bool broad_occupancy = false;
|
||||
bool flat_band = false;
|
||||
double band_min_occ = 0.0, band_max_occ = 0.0;
|
||||
uint32_t chans_with_evidence = 0;
|
||||
std::vector<TxChanEvidence> chans;
|
||||
};
|
||||
|
||||
class HopsetSensor {
|
||||
public:
|
||||
HopsetSensor(const TxSenseConfig &cfg, size_t n_base)
|
||||
: cfg_(cfg), n_(n_base), ch_(n_base) {
|
||||
if (!n_base || n_base > kMaxBaseChannels)
|
||||
throw std::invalid_argument("base hopset size out of range");
|
||||
mask_ = full_mask(n_base);
|
||||
}
|
||||
|
||||
const TxSenseConfig &config() const { return cfg_; }
|
||||
uint64_t active_mask() const { return mask_; }
|
||||
bool proposal_outstanding() const { return outstanding_; }
|
||||
|
||||
void ingest(const TxSenseSample &s) {
|
||||
if (s.base_index >= n_)
|
||||
return;
|
||||
if (!any_seen_) {
|
||||
any_seen_ = true;
|
||||
rounds_seen_ = 1;
|
||||
last_round_ = s.round;
|
||||
} else if (s.round != last_round_) {
|
||||
++rounds_seen_;
|
||||
last_round_ = s.round;
|
||||
}
|
||||
Chan &c = ch_[s.base_index];
|
||||
Phase &p = s.phase == SensePhase::PostBurst ? c.post : c.pre;
|
||||
|
||||
/* A sample taken without the discard barrier carries the previous
|
||||
* channel's counters — worse than no sample, because it manufactures
|
||||
* cross-channel correlation. Hard drop, like a failed read. */
|
||||
if (s.flags & (kTsRetuneFailed | kTsReadFailed | kTsTruncated |
|
||||
kTsBarrierMissed | kTsCounterSuspect)) {
|
||||
++p.dropped;
|
||||
return;
|
||||
}
|
||||
if (s.window_us < cfg_.min_window_us) {
|
||||
++p.dropped;
|
||||
return;
|
||||
}
|
||||
if (implausible(s)) {
|
||||
++p.dropped;
|
||||
return;
|
||||
}
|
||||
if (s.valid_igi &&
|
||||
(s.igi <= cfg_.igi_floor || s.igi >= cfg_.igi_ceiling))
|
||||
p.igi_railed = true;
|
||||
|
||||
SenseScore sc;
|
||||
if (!score_sample(s, cfg_, sc)) {
|
||||
++p.dropped;
|
||||
if (!c.pre.n && !c.post.n)
|
||||
c.sensor_absent = true;
|
||||
return;
|
||||
}
|
||||
c.sensor_absent = false;
|
||||
p.sources_seen |= sc.sources;
|
||||
push(p, sc.occupancy);
|
||||
p.dirty_run = sc.occupancy >= cfg_.occupancy_dirty ? p.dirty_run + 1 : 0;
|
||||
p.clean_run = sc.occupancy < cfg_.occupancy_dirty ? p.clean_run + 1 : 0;
|
||||
++total_samples_;
|
||||
|
||||
/* Probe dwells are the TX's own recovery evidence: they are the only
|
||||
* visits an excluded channel gets, and the payload is already suppressed
|
||||
* on them, so they cost nothing extra. */
|
||||
if (s.probe) {
|
||||
++c.probes;
|
||||
c.probe_good_run =
|
||||
sc.occupancy <= cfg_.restore_occupancy ? c.probe_good_run + 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
void on_activation(uint64_t mask, uint64_t now_round) {
|
||||
const uint64_t changed = mask ^ mask_;
|
||||
for (size_t i = 0; i < n_; ++i)
|
||||
if (changed & (uint64_t(1) << i))
|
||||
ch_[i] = Chan{};
|
||||
mask_ = mask;
|
||||
last_update_round_ = now_round;
|
||||
have_update_ = true;
|
||||
outstanding_ = false;
|
||||
}
|
||||
|
||||
/* The proposal was answered without activating. Like the RX policy, a
|
||||
* refused attempt still spends the update budget. */
|
||||
void clear_outstanding(uint64_t now_round) {
|
||||
outstanding_ = false;
|
||||
last_update_round_ = now_round;
|
||||
have_update_ = true;
|
||||
}
|
||||
|
||||
TxSenseCandidate evaluate(uint64_t now_round) {
|
||||
TxSenseCandidate d;
|
||||
d.policy_hash = cfg_.policy_hash();
|
||||
d.sample_count = total_samples_;
|
||||
d.chans = summarize();
|
||||
band_stats(d);
|
||||
|
||||
if (rounds_seen_ < cfg_.min_obs_rounds)
|
||||
return hold(d, TxSenseHold::InsufficientRounds);
|
||||
if (outstanding_)
|
||||
return hold(d, TxSenseHold::ProposalOutstanding);
|
||||
if (have_update_ && now_round - last_update_round_ < cfg_.cooldown_rounds)
|
||||
return hold(d, TxSenseHold::Cooldown);
|
||||
if (d.chans_with_evidence == 0) {
|
||||
for (size_t i = 0; i < n_; ++i)
|
||||
if (ch_[i].sensor_absent)
|
||||
return hold(d, TxSenseHold::SensorAbsent);
|
||||
return hold(d, TxSenseHold::InsufficientSamples);
|
||||
}
|
||||
|
||||
/* Restoration first, as on the receiver side: handing a channel back
|
||||
* enlarges the option set, and it is the path that keeps an autonomous
|
||||
* exclusion from being permanent. */
|
||||
const uint64_t excluded = full_mask(n_) & ~mask_;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(excluded & (uint64_t(1) << i)))
|
||||
continue;
|
||||
if (ch_[i].probe_good_run >= cfg_.restore_probes) {
|
||||
d.kind = TxSenseCandidate::Kind::ProposeRestore;
|
||||
d.target_index = i;
|
||||
d.proposed_mask = mask_ | (uint64_t(1) << i);
|
||||
d.reason_bitmap = 0;
|
||||
outstanding_ = true;
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
if (d.chans_with_evidence < cfg_.min_channels_scored)
|
||||
return hold(d, TxSenseHold::InsufficientChannels);
|
||||
|
||||
/* The worst sustained-dirty active channel. When post-burst evidence is
|
||||
* required, the run that counts is the post-burst one — that is the
|
||||
* population a reactive jammer shows up in. */
|
||||
bool have_worst = false, any_dirty = false, post_missing = false;
|
||||
size_t worst = 0;
|
||||
double worst_occ = -1.0;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(mask_ & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (!c.have_evidence())
|
||||
continue;
|
||||
const Phase &gate = cfg_.require_post_burst ? c.post : worse_phase(c);
|
||||
if (gate.dirty_run > 0)
|
||||
any_dirty = true;
|
||||
if (gate.dirty_run < cfg_.dirty_run)
|
||||
continue;
|
||||
if (cfg_.require_post_burst && !ph_scored(c.post)) {
|
||||
post_missing = true;
|
||||
continue;
|
||||
}
|
||||
const double occ = c.occupancy();
|
||||
if (!have_worst || occ > worst_occ) {
|
||||
have_worst = true;
|
||||
worst = i;
|
||||
worst_occ = occ;
|
||||
}
|
||||
}
|
||||
/* Pre-burst dirt with no post-burst corroboration is reported as its own
|
||||
* hold, not folded into "nothing here": it is the signature of a parked
|
||||
* interferer the receiver is better placed to judge. */
|
||||
if (!have_worst && cfg_.require_post_burst && !post_missing)
|
||||
for (size_t i = 0; i < n_; ++i)
|
||||
if ((mask_ & (uint64_t(1) << i)) && ph_scored(ch_[i].pre) &&
|
||||
ch_[i].pre.dirty_run >= cfg_.dirty_run &&
|
||||
!ph_scored(ch_[i].post))
|
||||
post_missing = true;
|
||||
|
||||
if (!have_worst) {
|
||||
if (post_missing)
|
||||
return hold(d, TxSenseHold::PostBurstMissing);
|
||||
return hold(d, any_dirty ? TxSenseHold::NotPersistent
|
||||
: TxSenseHold::NoOccupancy);
|
||||
}
|
||||
if (samples_of(ch_[worst]) < cfg_.min_samples_per_chan)
|
||||
return hold(d, TxSenseHold::InsufficientSamples);
|
||||
/* A band with no spread cannot be attributed to a channel, and a band
|
||||
* where most of it is dirty is not a channel fault at all. */
|
||||
if (d.flat_band)
|
||||
return hold(d, TxSenseHold::FlatBand);
|
||||
if (d.broad_occupancy)
|
||||
return hold(d, TxSenseHold::BroadOccupancy);
|
||||
|
||||
/* Two demonstrably cleaner alternatives, not one: a single clean channel
|
||||
* is exactly what a herding jammer manufactures by parking on everything
|
||||
* else. */
|
||||
uint32_t cleaner = 0;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (i == worst || !(mask_ & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (c.have_evidence() && c.occupancy() <= worst_occ - cfg_.cleaner_margin)
|
||||
++cleaner;
|
||||
}
|
||||
if (cleaner < cfg_.min_cleaner_chans)
|
||||
return hold(d, TxSenseHold::NoCleanerAlternative);
|
||||
|
||||
const uint64_t after = mask_ & ~(uint64_t(1) << worst);
|
||||
const uint32_t floor_active = cfg_.min_active < 3u ? 3u : cfg_.min_active;
|
||||
if (popcount64(after) < floor_active)
|
||||
return hold(d, TxSenseHold::MinActiveFloor);
|
||||
if (static_cast<double>(popcount64(full_mask(n_) & ~after)) /
|
||||
static_cast<double>(n_) >
|
||||
cfg_.max_excluded_frac)
|
||||
return hold(d, TxSenseHold::MaxExcludedFrac);
|
||||
|
||||
d.kind = TxSenseCandidate::Kind::ProposeExclude;
|
||||
d.target_index = worst;
|
||||
d.proposed_mask = after;
|
||||
d.reason_bitmap = build_reasons(ch_[worst]);
|
||||
outstanding_ = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Phase {
|
||||
double ring[64]{};
|
||||
uint32_t n = 0, head = 0;
|
||||
uint32_t samples = 0, dropped = 0;
|
||||
uint32_t dirty_run = 0, clean_run = 0;
|
||||
uint8_t sources_seen = 0;
|
||||
bool igi_railed = false;
|
||||
};
|
||||
struct Chan {
|
||||
Phase pre, post;
|
||||
bool sensor_absent = false;
|
||||
uint32_t probe_good_run = 0, probes = 0;
|
||||
bool have_evidence() const { return pre.n || post.n; }
|
||||
double occupancy() const {
|
||||
return post.n ? mean(post) : mean(pre);
|
||||
}
|
||||
static double mean(const Phase &p) {
|
||||
if (!p.n)
|
||||
return 0.0;
|
||||
double s = 0.0;
|
||||
for (uint32_t i = 0; i < p.n; ++i)
|
||||
s += p.ring[i];
|
||||
return s / static_cast<double>(p.n);
|
||||
}
|
||||
};
|
||||
|
||||
bool ph_scored(const Phase &p) const {
|
||||
return p.samples >= cfg_.min_samples_per_chan;
|
||||
}
|
||||
static const Phase &worse_phase(const Chan &c) {
|
||||
return c.post.n >= c.pre.n ? c.post : c.pre;
|
||||
}
|
||||
uint32_t samples_of(const Chan &c) const {
|
||||
return cfg_.require_post_burst ? c.post.samples
|
||||
: c.pre.samples + c.post.samples;
|
||||
}
|
||||
/* "We have a usable read of this channel" — either phase will do. Whether
|
||||
* post-burst corroboration is REQUIRED to act on it is the exclusion
|
||||
* trigger's rule, not a property of the evidence. */
|
||||
bool scored(const Chan &c) const {
|
||||
return ph_scored(c.pre) || ph_scored(c.post);
|
||||
}
|
||||
|
||||
void push(Phase &p, double v) {
|
||||
const uint32_t depth =
|
||||
cfg_.ring_samples < 64 ? cfg_.ring_samples : 64u;
|
||||
p.ring[p.head] = v;
|
||||
p.head = (p.head + 1) % (depth ? depth : 1);
|
||||
if (p.n < depth)
|
||||
++p.n;
|
||||
++p.samples;
|
||||
}
|
||||
|
||||
bool implausible(const TxSenseSample &s) const {
|
||||
if (!s.valid_fa)
|
||||
return false;
|
||||
const double win_ms = static_cast<double>(s.window_us) / 1000.0;
|
||||
const double cap = cfg_.max_counts_per_ms * win_ms;
|
||||
return s.cca_ofdm > cap || s.cca_cck > cap || s.fa_ofdm > cap ||
|
||||
s.fa_cck > cap;
|
||||
}
|
||||
|
||||
uint32_t build_reasons(const Chan &c) const {
|
||||
uint32_t r = 0;
|
||||
const Phase &p = c.post.n ? c.post : c.pre;
|
||||
if (p.sources_seen & kSrcCca)
|
||||
r |= RB_TX_CCA_HIGH;
|
||||
if (p.sources_seen & kSrcNhm)
|
||||
r |= RB_TX_NHM_BUSY;
|
||||
if (p.sources_seen & kSrcIgi)
|
||||
r |= RB_TX_IGI_ELEVATED;
|
||||
if (c.post.n)
|
||||
r |= RB_TX_POST_BURST;
|
||||
if (c.pre.n)
|
||||
r |= RB_TX_PRE_BURST;
|
||||
if (p.igi_railed)
|
||||
r |= RB_TX_IGI_RAILED;
|
||||
r |= RB_TX_CLEANER_ALT | RB_TX_PERSISTENT;
|
||||
return r;
|
||||
}
|
||||
|
||||
std::vector<TxChanEvidence> summarize() const {
|
||||
std::vector<TxChanEvidence> out(n_);
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
const Chan &c = ch_[i];
|
||||
TxChanEvidence &e = out[i];
|
||||
auto fill = [&](const Phase &p, TxPhaseEvidence &o, bool is_post) {
|
||||
o.samples = p.samples;
|
||||
o.dropped = p.dropped;
|
||||
o.occupancy = Chan::mean(p);
|
||||
o.dirty_run = p.dirty_run;
|
||||
o.clean_run = p.clean_run;
|
||||
o.sources_seen = p.sources_seen;
|
||||
o.igi_railed = p.igi_railed;
|
||||
double mx = 0.0;
|
||||
for (uint32_t k = 0; k < p.n; ++k)
|
||||
mx = p.ring[k] > mx ? p.ring[k] : mx;
|
||||
o.occupancy_max = mx;
|
||||
o.scored = p.samples >= cfg_.min_samples_per_chan;
|
||||
(void)is_post;
|
||||
};
|
||||
fill(c.pre, e.pre, false);
|
||||
fill(c.post, e.post, true);
|
||||
e.active = (mask_ & (uint64_t(1) << i)) != 0;
|
||||
e.sensor_absent = c.sensor_absent;
|
||||
e.probe_good_run = c.probe_good_run;
|
||||
e.probes = c.probes;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void band_stats(TxSenseCandidate &d) const {
|
||||
double mn = 2.0, mx = -1.0;
|
||||
uint32_t scored_n = 0, dirty_n = 0;
|
||||
for (size_t i = 0; i < n_; ++i) {
|
||||
if (!(mask_ & (uint64_t(1) << i)))
|
||||
continue;
|
||||
const Chan &c = ch_[i];
|
||||
if (!c.have_evidence() || !scored(c))
|
||||
continue;
|
||||
++scored_n;
|
||||
const double o = c.occupancy();
|
||||
if (o < mn)
|
||||
mn = o;
|
||||
if (o > mx)
|
||||
mx = o;
|
||||
if (o >= cfg_.occupancy_dirty)
|
||||
++dirty_n;
|
||||
}
|
||||
d.chans_with_evidence = scored_n;
|
||||
d.band_min_occ = scored_n ? mn : 0.0;
|
||||
d.band_max_occ = scored_n ? mx : 0.0;
|
||||
d.broad_occupancy =
|
||||
scored_n && static_cast<double>(dirty_n) /
|
||||
static_cast<double>(scored_n) >=
|
||||
cfg_.broad_occupancy_frac;
|
||||
/* Raw geometry only: "the channels look alike". Whether that means doubt
|
||||
* (alike and dirty) or confidence (alike and clean) is the fusion layer's
|
||||
* call, which is where the dirty floor lives. The sensor's own use below
|
||||
* is unambiguous because it is only reached once something was dirty. */
|
||||
d.flat_band = scored_n >= cfg_.min_channels_scored &&
|
||||
(d.band_max_occ - d.band_min_occ) < cfg_.broad_spread_min;
|
||||
}
|
||||
|
||||
static TxSenseCandidate &hold(TxSenseCandidate &d, TxSenseHold h) {
|
||||
d.kind = TxSenseCandidate::Kind::None;
|
||||
d.hold = h;
|
||||
return d;
|
||||
}
|
||||
|
||||
TxSenseConfig cfg_;
|
||||
size_t n_;
|
||||
std::vector<Chan> ch_;
|
||||
uint64_t mask_ = 0;
|
||||
uint64_t last_round_ = 0, last_update_round_ = 0;
|
||||
uint32_t rounds_seen_ = 0, total_samples_ = 0;
|
||||
bool any_seen_ = false, have_update_ = false, outstanding_ = false;
|
||||
};
|
||||
|
||||
} /* namespace hopset */
|
||||
} /* namespace devourer */
|
||||
|
||||
#endif /* DEVOURER_HOPSET_HOPSET_SENSE_H */
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user