feat(wifi): give a Bluetooth game controller an RTL8822C's second antenna

This commit is contained in:
Tyler Smith committed 2026-10-31 10:28:36 +00:00
1 parent 5abbf8dacd
commit 9c5ca7f2a2
8 files changed
+428 -39

No files matched your search

+131 -26
View File
@@ -14,7 +14,7 @@ mod tables;
use self::{
actions::{Phase, Plan},
bluetooth::{Bluetooth, Changes, Status, rssi_high},
bluetooth::{Bluetooth, Changes, HID_DEVICE, HID_LIST, HidDevices, Status, rssi_high},
tables::*,
};
use super::{
@@ -122,6 +122,7 @@ const COMMAND_IGNORE_WLAN: u32 = 0x63;
const COMMAND_CHANNEL_INFO: u32 = 0x66;
const COMMAND_QUERY_BT_MP: u32 = 0x67;
const COMMAND_BT_WIFI_CONTROL: u32 = 0x69;
const COMMAND_QUERY_HID: u32 = 0x73;
const CONTROL_TOGGLE_TABLE_B: u8 = 0x7;
const CONTROL_TDMA_SLOT: u8 = 0xb;
const CONTROL_LEAK_AP: u8 = 0xc;
@@ -185,6 +186,8 @@ impl From<rf::Error> for Error {
enum Mode {
TwoGhz,
FiveGhz,
/// `COEX_WLINK_2GFREE`: one antenna each, for a game controller.
Free,
}
/// What the Wi-Fi side is doing, which `rtw_coex_run_coex` schedules around.
@@ -237,6 +240,8 @@ pub enum Event<'a> {
Watchdog,
/// `rtw_coex_bt_info_notify`.
Bluetooth(&'a [u8]),
/// `rtw_coex_bt_hid_info_notify`.
BluetoothHid([u8; 8]),
/// `rtw_coex_info_response`.
Answer(&'a [u8]),
/// Time passed: rtw88's delayed works.
@@ -258,6 +263,8 @@ enum Reason {
Bluetooth,
/// `COEX_RSN_LPS`.
Sleep,
/// `COEX_RSN_2GMEDIA`.
Media,
/// Any other.
Status,
}
@@ -269,14 +276,14 @@ pub enum Order {
Command((u32, u32)),
/// `rtw_leave_lps`.
Wake,
/// `rtw_set_txrx_1ss`.
SingleStream(bool),
}
/// What a step of the arbiter leaves undone.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct Run {
pub orders: Vec<Order>,
/// What this arbiter does not yet do that the moment called for.
pub limitation: Option<&'static str>,
}
/// What waits in the firmware's answer: `rtw_coex_info_request`.
@@ -318,6 +325,8 @@ fn due(timer: &mut Option<u64>, now: u64) -> bool {
/// `coex_stat`'s Bluetooth counters, from `rtw_coex_monitor_bt_ctr`.
#[derive(Debug, Default)]
struct Counters {
high_tx: u32,
high_rx: u32,
low_tx: u32,
low_rx: u32,
/// `bt_ctr_ok`.
@@ -367,6 +376,14 @@ fn query(operation: u8, parameter: u8) -> (u32, u32) {
)
}
/// `rtw_fw_coex_query_hid_info`.
fn query_hid(kind: u8, data: u8) -> (u32, u32) {
(
COMMAND_QUERY_HID | (u32::from(kind) << 8) | (u32::from(data) << 16),
0,
)
}
/// An arbiter's state.
#[derive(Debug)]
pub struct Coex {
@@ -421,12 +438,17 @@ pub struct Coex {
/// `bt_iqk_state`.
calibration: u8,
bluetooth: Bluetooth,
hid: HidDevices,
counters: Counters,
timers: Timers,
/// What the mailbox holds and what waits behind it, with when to stop
/// waiting for an answer.
asked: Option<(Request, u64)>,
requests: VecDeque<Request>,
/// `coex_stat->wl_coex_mode`.
mode: Option<Mode>,
/// `coex_stat->wl_mimo_ps`.
single_stream: bool,
/// `coex_stat->gnt_workaround_state`.
workaround: Option<Mode>,
/// `coex_dm->cur_ant_pos_type`.
@@ -492,10 +514,13 @@ impl Coex {
inquiry_remains: false,
calibration: 0,
bluetooth: Bluetooth::default(),
hid: HidDevices::default(),
counters: Counters::default(),
timers: Timers::default(),
asked: None,
requests: VecDeque::new(),
mode: None,
single_stream: false,
workaround: None,
phase: None,
bluetooth_power: 0,
@@ -766,11 +791,11 @@ impl Coex {
}
/// `rtw8822c_coex_cfg_gnt_fix`.
fn gnt_fix<I: Io>(&mut self, step: &mut Step<'_, I>, mode: Mode) -> Result<(), Error> {
if self.workaround == Some(mode) {
fn gnt_fix<I: Io>(&mut self, step: &mut Step<'_, I>) -> Result<(), Error> {
if self.workaround == self.mode {
return Ok(());
}
self.workaround = Some(mode);
self.workaround = self.mode;
let mut rf_1 = if (self.version == 0 && self.five_ghz) || self.freerun {
0x40021
} else {
@@ -785,11 +810,19 @@ impl Coex {
rf.write(Path::B, RF_MODOPT, RF_MASK, rf_1)?;
}
let io = &mut *step.io;
Self::write8_set(io, REG_ANAPAR + 2, ANAPAR_BTPS)?;
Self::write8_clear(io, REG_RSTB_SEL + 1, DAC_OFF_ENABLE)?;
Self::write8_set(io, REG_RSTB_SEL + 3, DAC_OFF_ENABLE)?;
let free = self.mode == Some(Mode::Free);
if free {
Self::write8_clear(io, REG_ANAPAR + 2, ANAPAR_BTPS)?;
} else {
Self::write8_set(io, REG_ANAPAR + 2, ANAPAR_BTPS)?;
Self::write8_clear(io, REG_RSTB_SEL + 1, DAC_OFF_ENABLE)?;
Self::write8_set(io, REG_RSTB_SEL + 3, DAC_OFF_ENABLE)?;
}
Self::write8_set(io, REG_IGN_GNTBT4, IGNORE_GNT_BT)?;
if mode == Mode::FiveGhz || self.five_ghz || !self.shared {
if free {
Self::write8_set(io, REG_IGN_GNT_BT1, IGNORE_GNT_BT)?;
Self::write8_set(io, REG_NOMASK_TXBT, NOMASK_TXBT)
} else if self.mode == Some(Mode::FiveGhz) || self.five_ghz || !self.shared {
if self.version >= 3 {
Self::write8_clear(io, REG_IGN_GNT_BT1, IGNORE_GNT_BT)?;
Self::write8_set(io, REG_NOMASK_TXBT, NOMASK_TXBT)
@@ -940,7 +973,8 @@ impl Coex {
/// `rtw_coex_set_tdma`, from `rtw_coex_power_save_state` of a schedule
/// firmware keeps only awake or of none.
fn set_tdma<I>(&mut self, step: &mut Step<'_, I>, para: [u8; 5]) {
self.stays_awake = para[0] & (1 << 4) != 0 && para[0] & (1 << 5) == 0;
self.stays_awake =
(para[0] & (1 << 4) != 0 && para[0] & (1 << 5) == 0) || self.mode == Some(Mode::Free);
if step.wifi.asleep {
if self.stays_awake {
step.command(tdma([0; 5]));
@@ -988,11 +1022,12 @@ impl Coex {
}
/// `rtw_coex_update_wl_ch_info`, with no 5 GHz hop map: a shared antenna
/// leaves Bluetooth all of 2.4 GHz, and a separate one has it skip the
/// leaves Bluetooth all of 2.4 GHz, and one of its own has it skip the
/// channel.
fn channel_info<I>(&self, step: &mut Step<'_, I>, connected: bool) {
let (mut link, mut channel, mut width) = (0, 0, 0);
if connected && step.wifi.channel != 0 && !(self.shared && step.wifi.channel <= 14) {
let leaves_all = self.shared && self.mode != Some(Mode::Free);
if connected && step.wifi.channel != 0 && !(leaves_all && step.wifi.channel <= 14) {
channel = step.wifi.channel;
width = step.wifi.width;
if channel <= 14 {
@@ -1061,7 +1096,7 @@ impl Coex {
self.five_ghz = match step.reason {
Reason::FiveGhz => true,
Reason::Scanning | Reason::Connecting | Reason::TwoGhz => false,
_ => wifi.five_ghz,
Reason::Bluetooth | Reason::Sleep | Reason::Media | Reason::Status => wifi.five_ghz,
};
Ok(())
}
@@ -1118,6 +1153,9 @@ impl Coex {
/// What `plan` settles, in the order rtw88's actions take it.
fn enact<I: Io>(&mut self, step: &mut Step<'_, I>, plan: Plan) -> Result<(), Error> {
if plan.free {
self.mode = Some(Mode::Free);
}
if plan.freerun {
self.freerun = true;
self.channel_info(step, true);
@@ -1144,26 +1182,61 @@ impl Coex {
return Ok(());
}
self.freerun = false;
let mode = if self.five_ghz {
if self.five_ghz {
// rtw_coex_action_wl_under5g.
self.mode = Some(if self.bluetooth.game_controller && self.linkscan {
Mode::Free
} else {
Mode::FiveGhz
});
self.set_path(step.io, true, Phase::FiveGhz)?;
self.set_rf(step, RECEIVE_RF[0])?;
self.scoreboard(step.io, SCORE_FIX_2M, false)?;
let case = if self.shared { 0 } else { 100 };
self.table(step, false, case)?;
self.tdma(step, false, case, false)?;
Mode::FiveGhz
} else {
self.mode = Some(Mode::TwoGhz);
self.enact(step, self.plan())?;
Mode::TwoGhz
};
self.gnt_fix(step, mode)?;
let idle = self.bluetooth.status == Status::NotConnectedIdle;
self.limit_transmissions(step.io, !self.five_ghz && !idle)?;
if self.bluetooth.hid {
step.run.limitation = Some("telling a Bluetooth game controller from other input");
}
Ok(())
let free = self.mode == Some(Mode::Free);
self.set_single_stream(step, free && reason == Reason::Media, free);
self.gnt_fix(step)?;
let idle = self.bluetooth.status == Status::NotConnectedIdle;
self.limit_transmissions(step.io, !self.five_ghz && !idle)
}
/// `rtw_coex_mimo_ps`.
fn set_single_stream<I>(&mut self, step: &mut Step<'_, I>, force: bool, single: bool) {
if force || single != self.single_stream {
self.single_stream = single;
step.run.orders.push(Order::SingleStream(single));
self.channel_info(step, step.wifi.connected);
}
}
/// `rtw_coex_bt_hid_info_notify`.
fn hid_report<I: Io>(&mut self, step: &mut Step<'_, I>, bytes: [u8; 8]) -> Result<(), Error> {
let Some(game) = self.hid.report(bytes) else {
return Ok(());
};
if game == self.bluetooth.game_controller {
return Ok(());
}
self.bluetooth.game_controller = game;
self.run_coex(step, Reason::Status)
}
/// `rtw_coex_query_bt_hid_list`.
fn query_hid_devices<I>(&self, step: &mut Step<'_, I>) {
let high_priority = self.counters.high_tx + self.counters.high_rx;
if !self.bluetooth.may_hold_a_controller(high_priority) {
return;
}
step.command(query_hid(HID_LIST, 0));
for handle in self.hid.unknown() {
step.command(query_hid(HID_DEVICE, handle));
}
}
/// `rtw_coex_scan_notify` of a start on 2.4 GHz.
@@ -1262,6 +1335,8 @@ impl Coex {
io.write8(REG_BT_COEX_ENH_INTR_CTRL, COUNT_BLUETOOTH)?;
let (high_tx, high_rx) = (high & 0xffff, high >> 16);
let (low_tx, low_rx) = (low & 0xffff, low >> 16);
self.counters.high_tx = high_tx;
self.counters.high_rx = high_rx;
self.counters.low_tx = low_tx;
self.counters.low_rx = low_rx;
let saturated = high_rx > 60000 && high_tx == 60000 && low_rx > 60000 && low_tx == 60000;
@@ -1371,7 +1446,7 @@ impl Coex {
self.scoreboard(step.io, SCORE_ACTIVE, true)?;
self.set_path(step.io, true, Phase::TwoGhz)?;
Self::priority(step.io, PRIORITY_RX_CCK, true)?;
self.run_coex(&mut step, Reason::Status)?;
self.run_coex(&mut step, Reason::Media)?;
self.channel_info(&mut step, true);
}
Event::Media { connected: false } => {
@@ -1397,9 +1472,11 @@ impl Coex {
Event::Watchdog => {
if !self.sleeping || self.stays_awake {
self.read_counters(step.io)?;
self.query_hid_devices(&mut step);
}
}
Event::Bluetooth(bytes) => self.bluetooth_report(&mut step, bytes)?,
Event::BluetoothHid(bytes) => self.hid_report(&mut step, bytes)?,
Event::Answer(payload) => self.answered(&mut step, payload),
Event::Tick => self.tick(&mut step)?,
}
@@ -1562,7 +1639,7 @@ mod tests {
.iter()
.filter_map(|order| match order {
Order::Command(command) => Some(*command),
Order::Wake => None,
_ => None,
})
.collect()
}
@@ -1829,6 +1906,34 @@ mod tests {
assert!(!rig.coex.reenabling);
}
#[test]
fn a_game_controller_takes_an_antenna_of_its_own() {
let mut rig = Rig::new(true);
rig.bluetooth(1 | 0x20, 0, 0);
rig.bus
.write32(REG_BT_ACT_STATISTICS, 500 | (500 << 16))
.unwrap();
let run = rig.event(Event::Watchdog);
assert_eq!(commands(&run), [query_hid(HID_LIST, 0)]);
rig.event(Event::BluetoothHid([0, 6, 0, 1, 3, 0xff, 0xff, 0xff]));
let run = rig.event(Event::Watchdog);
assert!(commands(&run).contains(&query_hid(HID_DEVICE, 3)));
let run = rig.event(Event::BluetoothHid([0, 6, 1, 3, 0x46, 0x58, 0x62, 0x6f]));
assert!(run.orders.contains(&Order::SingleStream(true)));
assert_eq!(rig.bus.word(REG_BT_COEX_TABLE1), SHARED_TABLES[33].wifi);
assert_eq!(rig.coex.mode, Some(Mode::Free));
assert_eq!(rig.bus.get(REG_NOMASK_TXBT) & NOMASK_TXBT, NOMASK_TXBT);
// Bluetooth now hops around the channel, shared antenna or not.
let info = (
COMMAND_CHANNEL_INFO | (1 << 8) | (6 << 16) | (0x24 << 24),
0,
);
assert!(commands(&run).contains(&info));
let run = rig.event(Event::BluetoothHid([0, 6, 0, 0, 0, 0, 0, 1]));
assert!(run.orders.contains(&Order::SingleStream(false)));
assert_eq!(rig.coex.mode, Some(Mode::TwoGhz));
}
#[test]
fn a_stopped_arbiter_answers_nothing() {
let mut rig = Rig::new(true);
@@ -30,6 +30,8 @@ pub(super) struct Plan {
pub toggle: Option<u8>,
/// `rtw_coex_action_freerun`.
pub freerun: bool,
/// `COEX_WLINK_2GFREE`.
pub free: bool,
}
/// The normal `wl_rf_para_rx[0]`.
@@ -45,6 +47,7 @@ impl Plan {
four_slot: false,
toggle: None,
freerun: false,
free: false,
}
}
@@ -62,6 +65,13 @@ impl Plan {
self.toggle = toggle;
self
}
/// `COEX_WLINK_2GFREE` at `rf`.
fn free(mut self, rf: RfLevels) -> Self {
self.free = true;
self.rf = rf;
self
}
}
impl Coex {
@@ -78,6 +88,9 @@ impl Coex {
if self.sleeping && !self.stays_awake {
return self.action_native_sleep();
}
if bluetooth.game_controller && self.connected {
return self.action_game_controller();
}
if bluetooth.certification {
return self.action_wifi_only();
}
@@ -124,13 +137,47 @@ impl Coex {
/// `rtw_coex_action_wl_native_lps`.
fn action_native_sleep(&self) -> Plan {
if self.shared {
let plan = if self.shared {
Plan::new(28, 0)
} else {
Plan::new(100, 100)
};
if self.bluetooth.game_controller {
plan.free(self.free_rf())
} else {
plan
}
}
/// `wl_rf_para_tx[6]` or `wl_rf_para_rx[5]`, for a controller's sake.
fn free_rf(&self) -> RfLevels {
if self.transmitting {
TRANSMIT_RF[6]
} else {
RECEIVE_RF[5]
}
}
/// `rtw_coex_action_bt_game_hid`.
fn action_game_controller(&self) -> Plan {
let bluetooth = &self.bluetooth;
if !self.shared {
return Plan::new(121, if self.rssi_high[1] { 112 } else { 113 });
}
let table = if bluetooth.certification {
2
} else if self.linkscan || bluetooth.hid {
33
} else if bluetooth.setting_up || bluetooth.inquiring {
0
} else if bluetooth.a2dp {
34
} else {
33
};
Plan::new(table, 0).free(self.free_rf())
}
/// `rtw_coex_action_bt_relink`.
fn action_relink(&self) -> Plan {
let bluetooth = &self.bluetooth;
@@ -16,6 +16,87 @@ const INFO_HID: u8 = 1 << 5;
const INFO_A2DP: u8 = 1 << 6;
const INFO_FTP: u8 = 1 << 7;
/// `COEX_BT_GAMEHID_CNT`.
const HID_TRAFFIC: u32 = 800;
/// `COEX_BT_HIDINFO_LIST` and `COEX_BT_HIDINFO_A`.
pub(super) const HID_LIST: u8 = 0;
pub(super) const HID_DEVICE: u8 = 1;
/// `COEX_BT_HIDINFO_NOTCON` and `COEX_BT_BLE_HANDLE_THRS`.
const HANDLE_NOT_CONNECTED: u8 = 0xff;
const HANDLE_LOW_ENERGY: u8 = 0x10;
/// `COEX_BT_HIDINFO_MTK`, and the names of `coex_bt_hidinfo_ps` and
/// `coex_bt_hidinfo_xb`.
const VENDOR_MEDIATEK: u8 = 0x46;
const GAME_NAMES: [[u8; 3]; 2] = [[0x57, 0x69, 0x72], [0x58, 0x62, 0x6f]];
/// A `rtw_coex_hid`.
#[derive(Clone, Copy, Debug, Default)]
struct HidDevice {
handle: u8,
vendor: u8,
name: [u8; 3],
complete: bool,
}
impl HidDevice {
fn classic(&self) -> bool {
self.handle != 0 && self.handle != HANDLE_NOT_CONNECTED && self.handle < HANDLE_LOW_ENERGY
}
/// What of `rtw_coex_bt_hid_info_notify` says a game is on the end of it.
fn game(&self) -> bool {
self.complete
&& self.classic()
&& self.vendor == VENDOR_MEDIATEK
&& GAME_NAMES.contains(&self.name)
}
}
/// `hid_handle_list` and `hid_info`.
#[derive(Debug, Default)]
pub(super) struct HidDevices {
list: [u8; 8],
devices: [HidDevice; 4],
}
impl HidDevices {
/// `rtw_coex_bt_hid_info_notify` of what firmware sent. None means
/// nothing changed; otherwise whether a game controller is connected.
pub fn report(&mut self, bytes: [u8; 8]) -> Option<bool> {
match bytes[2] {
HID_LIST => {
if bytes == self.list {
return None;
}
self.list = bytes;
self.devices = Default::default();
for (device, &handle) in self.devices.iter_mut().zip(&bytes[4..]) {
if handle != HANDLE_NOT_CONNECTED {
device.handle = handle;
}
}
}
HID_DEVICE => {
if let Some(device) = self.devices.iter_mut().find(|d| d.handle == bytes[3]) {
device.vendor = bytes[4];
device.name = [bytes[5], bytes[6], bytes[7]];
device.complete = true;
}
}
_ => {}
}
Some(self.devices.iter().any(HidDevice::game))
}
/// The handles rtw88 still asks about.
pub fn unknown(&self) -> impl Iterator<Item = u8> + '_ {
self.devices
.iter()
.filter(|device| device.classic() && !device.complete)
.map(|device| device.handle)
}
}
/// `coex_bt_status`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(super) enum Status {
@@ -98,6 +179,8 @@ pub(super) struct Bluetooth {
pub hid_pairs: u8,
/// `bt_418_hid_exist`: a controller polled every 4.18 ms.
pub hid_418: bool,
/// `bt_game_hid_exist`.
pub game_controller: bool,
/// `bt_rssi`.
rssi: u8,
/// `coex_dm->bt_rssi_state`, each `COEX_RSSI_HIGH`.
@@ -204,6 +287,11 @@ impl Bluetooth {
self.scan_type = 0;
}
/// `rtw_coex_query_bt_hid_list`'s gate: a controller could be there.
pub fn may_hold_a_controller(&self, high_priority: u32) -> bool {
self.hid || (self.info[0] & INFO_CONNECTION != 0 && high_priority > HID_TRAFFIC)
}
/// `bt_ble_scan_type` as `BT_MP_INFO_OP_SCAN_TYPE` answers.
pub fn scan_answer(&mut self, kind: u8) {
self.scan_type = kind;
@@ -229,6 +317,30 @@ mod tests {
assert_eq!(bluetooth.report(&report), None, "nothing new");
}
#[test]
fn a_controller_is_a_classic_link_of_a_known_vendor_and_name() {
let mut devices = HidDevices::default();
assert_eq!(devices.report([0, 6, 0, 2, 3, 0x20, 0xff, 0]), Some(false));
assert_eq!(devices.unknown().collect::<alloc::vec::Vec<_>>(), [3]);
assert_eq!(devices.report([0, 6, 0, 2, 3, 0x20, 0xff, 0]), None);
assert_eq!(
devices.report([0, 6, 1, 3, 0x46, 1, 2, 3]),
Some(false),
"another device of the vendor"
);
assert_eq!(
devices.report([0, 6, 1, 3, 0x46, 0x58, 0x62, 0x6f]),
Some(true)
);
assert_eq!(devices.unknown().count(), 0);
assert_eq!(
devices.report([0, 6, 1, 0x20, 0x46, 0x57, 0x69, 0x72]),
Some(true),
"a Low Energy handle is not asked about or counted"
);
assert_eq!(devices.report([0, 6, 0, 0, 0, 0, 0, 1]), Some(false));
}
#[test]
fn a_short_report_is_no_report() {
assert_eq!(Bluetooth::default().report(&[1, 0x49]), None);
@@ -23,9 +23,10 @@ const SCAN_RESULT: u8 = 0x38;
const RESERVED_PAGES: u32 = 0;
const POWER_MODE: u32 = 0x20;
/// `C2H_BT_INFO` and `C2H_BT_MP_INFO`.
/// `C2H_BT_INFO`, `C2H_BT_MP_INFO` and `C2H_BT_HID_INFO`.
const BT_INFO: u8 = 0x09;
const BT_MP_INFO: u8 = 0x0b;
const BT_HID_INFO: u8 = 0x45;
/// `C2H_CCX_TX_RPT`.
const CCX_TX_REPORT: u8 = 0x03;
/// `C2H_RA_RPT`.
@@ -145,6 +146,14 @@ pub fn adaptivity(mode: u8, gain: u8, threshold: u8, density: u8) -> (u32, u32)
)
}
/// What fits of a report's `payload`, the rest of it zero.
fn first_bytes(payload: &[u8]) -> [u8; 8] {
let mut bytes = [0; 8];
let length = payload.len().min(bytes.len());
bytes[..length].copy_from_slice(&payload[..length]);
bytes
}
/// One report in a firmware packet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Report {
@@ -162,6 +171,8 @@ pub enum Report {
Bluetooth { bytes: [u8; 10], length: u8 },
/// `rtw_coex_info_response`.
BluetoothAnswer([u8; 8]),
/// `rtw_coex_bt_hid_info_notify`.
BluetoothHid([u8; 8]),
/// A report a station does not act on, by ID.
Other(u8),
}
@@ -195,12 +206,8 @@ impl Report {
length: length as u8,
}
}
BT_MP_INFO => {
let mut answer = [0; 8];
let length = payload.len().min(answer.len());
answer[..length].copy_from_slice(&payload[..length]);
Self::BluetoothAnswer(answer)
}
BT_MP_INFO => Self::BluetoothAnswer(first_bytes(payload)),
BT_HID_INFO => Self::BluetoothHid(first_bytes(payload)),
_ => Self::Other(id),
})
}
@@ -277,7 +284,7 @@ mod tests {
acknowledged: true
})
);
assert_eq!(Report::parse(&[0x45, 0, 1]), Some(Report::Other(0x45)));
assert_eq!(Report::parse(&[0x46, 0, 1]), Some(Report::Other(0x46)));
assert_eq!(Report::parse(&[3, 0, 1]), None);
}
}
@@ -802,6 +802,46 @@ impl Dynamic {
Ok(())
}
/// `rtw8822c_config_trx_mode` for path A alone, or both.
pub fn set_paths<I: Io>(io: &mut I, single: bool) -> Result<(), io::Error> {
let both = u32::from(!single);
let second_path = if single { 0x11111 } else { 0x33312 };
let paths = if single { 1 } else { 3 };
for (register, mask, value) in [
(0x1800, 0xfffff, 0x33312),
(0x4100, 0xfffff, second_path),
(0x1a2c, 0x00060000, both),
(0x1a2c, 0x00600000, both),
(0x1a04, 0x0f000000, both),
(0x1d30, 0x300, both),
(0x1d30, 0x600000, both),
(0xc44, 1 << 17, both),
(0xc54, 1 << 20, both),
(0xc38, 1 << 24, both),
(0x824, 0x0f000000, paths),
(0x824, 0x000f0000, paths),
(0x1a04, 0xf0000000, 8),
] {
set_mask(io, register, mask, value)?;
}
reset_baseband(io)?;
let (antennas, legacy_mask, legacy) = if single {
(0x11, 0xff, 0)
} else {
(0x31, 0xffff, 0x0400)
};
set_mask(io, 0x820, 0xff, antennas)?;
set_mask(io, 0x1e2c, legacy_mask, legacy)?;
reset_baseband(io)?;
reset_baseband(io)?;
// rtw8822c_toggle_igi.
let gain = mask_of(io, 0x1d70, 0x7f)?;
set_mask(io, 0x1d70, 0x7f, gain - 2)?;
set_mask(io, 0x1d70, 0x7f00, gain - 2)?;
set_mask(io, 0x1d70, 0x7f, gain)?;
set_mask(io, 0x1d70, 0x7f00, gain)
}
/// `rtw_phy_tx_path_div_select`: one stream leaves by the stronger path.
pub fn choose_path<I: Io>(&mut self, io: &mut I) -> Result<(), io::Error> {
let mean = |path: usize| match self.path_counts[path] {
@@ -1419,6 +1459,22 @@ mod tests {
assert_eq!(dynamic.current_gain(), MAX_COVERAGE);
}
#[test]
fn one_stream_stands_on_path_a_and_two_come_back() {
let mut bus = Bus(BTreeMap::new());
bus.write32(0x1d70, 0x2020).unwrap();
Dynamic::set_paths(&mut bus, true).unwrap();
assert_eq!(bus.get(0x4100) & 0xfffff, 0x11111);
assert_eq!(bus.get(0x820) & 0xff, 0x11);
assert_eq!(bus.get(0x824), 0x0101_0000);
assert_eq!(bus.get(0x1d70), 0x2020, "the gain toggled back");
Dynamic::set_paths(&mut bus, false).unwrap();
assert_eq!(bus.get(0x4100) & 0xfffff, 0x33312);
assert_eq!(bus.get(0x820) & 0xff, 0x31);
assert_eq!(bus.get(0x1e2c) & 0xffff, 0x0400);
assert_eq!(bus.get(0x824), 0x0303_0000);
}
#[test]
fn a_gain_swinging_with_its_alarms_is_left_alone_until_the_signal_moves() {
let mut dynamic = at_gain(0x24);
@@ -37,7 +37,7 @@ use crate::{
phy::{AccessCategory, Width},
},
};
use alloc::{format, string::String, vec::Vec};
use alloc::{collections::VecDeque, format, string::String, vec::Vec};
use core::fmt::Debug;
/// `REG_TCR`'s `BIT_PWRMGT_HWDATA_EN` and `BIT_TCR_UPDATE_TIMIE`.
@@ -169,6 +169,9 @@ pub struct Hardware {
scanning: bool,
busy: bool,
asleep: bool,
/// `hal.txrx_1ss`, and each change of it the AP has not heard of.
single_stream: bool,
stream_changes: VecDeque<bool>,
/// `coex_stat->wl_beacon_interval`.
beacon_interval: u16,
/// `dm_info.cck_ok_cnt + cck_err_cnt`.
@@ -253,6 +256,8 @@ impl Hardware {
scanning: false,
busy: false,
asleep: false,
single_stream: false,
stream_changes: VecDeque::new(),
beacon_interval: 0,
cck_frames: 0,
now: 0,
@@ -286,7 +291,6 @@ impl Hardware {
// SAFETY: this worker owns the radio, and its frames wait for it.
let run = unsafe { self.coex.notify(io, &self.report, now, wifi, event) }
.map_err(failed("coex"))?;
self.limitations.extend(run.limitation);
for order in run.orders {
match order {
Order::Command(command) => self
@@ -294,6 +298,13 @@ impl Hardware {
.command(command)
.map_err(failed("coex command"))?,
Order::Wake => self.set_power_save(false)?,
Order::SingleStream(single) if single != self.single_stream => {
self.single_stream = single;
let io = self.control.io().map_err(failed("registers"))?;
Dynamic::set_paths(io, single).map_err(failed("paths"))?;
self.stream_changes.push_back(single);
}
Order::SingleStream(_) => {}
}
}
Ok(())
@@ -572,7 +583,9 @@ impl Device for Hardware {
};
match &item {
Incoming::Report(
report @ (Report::Bluetooth { .. } | Report::BluetoothAnswer(_)),
report @ (Report::Bluetooth { .. }
| Report::BluetoothAnswer(_)
| Report::BluetoothHid(_)),
) => bluetooth.push(*report),
Incoming::Report(report) => dynamic.reported(report),
Incoming::Frame(frame) => dynamic.frame(&frame.bytes, signal, address, bssid),
@@ -592,6 +605,7 @@ impl Device for Hardware {
self.arbitrate(Event::Bluetooth(&bytes[..usize::from(length)]))?;
}
Report::BluetoothAnswer(answer) => self.arbitrate(Event::Answer(&answer))?,
Report::BluetoothHid(bytes) => self.arbitrate(Event::BluetoothHid(bytes))?,
_ => {}
}
}
@@ -658,6 +672,10 @@ impl Device for Hardware {
.map_err(failed("dtim"))
}
fn stream_change(&mut self) -> Option<bool> {
self.stream_changes.pop_front()
}
/// The arbiter's time, and rtw88's delayed works that came due.
fn coexist(&mut self, now: u64) -> Result<(), String> {
self.now = now;
@@ -757,7 +775,9 @@ impl Device for Hardware {
.command(self.dynamic.phy_info())
.map_err(failed("phy info"))?;
let io = self.control.io().map_err(failed("registers"))?;
if linked {
// rtw88 would put the second transmit path back here; a game
// controller holds it, so one path has none to choose from.
if linked && !self.single_stream {
let rates = if band == Band::Ghz5 {
RESPONSE_RATES_5GHZ
} else {
@@ -72,6 +72,9 @@ pub const PORT: u8 = 0;
const PAIRWISE_CAM: u8 = 4;
/// `RTW_CAM_AES`.
const CAM_AES: u8 = 4;
/// `WLAN_HT_SMPS_CONTROL_DISABLED` and `WLAN_HT_SMPS_CONTROL_STATIC`.
const SMPS_DISABLED: u8 = 0;
const SMPS_STATIC: u8 = 1;
/// `IEEE80211_MIN_AMPDU_BUF`'s window, which `HT_RX_REORDER_BUF_TIMEOUT` serves.
const RECEIVE_WINDOW: u16 = 64;
/// mac80211's `max_tx_aggregation_subframes`, which rtw88 leaves alone.
@@ -151,6 +154,10 @@ pub trait Device {
fn set_beacon(&mut self, _interval_tu: u16, _dtim_period: u8) -> Result<(), String> {
Ok(())
}
/// `rtw_vif_smps_iter`: the next change to one stream or back to two.
fn stream_change(&mut self) -> Option<bool> {
None
}
/// A look at the Bluetooth arbiter's timers, at `now`.
fn coexist(&mut self, _now: u64) -> Result<(), String> {
Ok(())
@@ -733,6 +740,23 @@ impl<D: Device> Rtl8822c<D> {
Ok(())
}
/// `ieee80211_request_smps` of each change the radio made.
fn announce_streams(&mut self) -> Result<(), Error> {
while let Some(single) = self.device.stream_change() {
if let Some(context) = &self.context
&& context.negotiated().ht.is_some()
{
let control = if single { SMPS_STATIC } else { SMPS_DISABLED };
let frame = self
.station
.spatial_power_save(context, control)
.map_err(Error::Station)?;
self.outbox.push_back((None, frame));
}
}
Ok(())
}
/// `rtw_enter_lps` and `rtw_leave_lps`.
fn power_save(&mut self, on: bool) -> Result<(), Error> {
Self::hardware(self.device.set_power_save(on))
@@ -1517,6 +1541,7 @@ impl<D: Device> Rtl8822c<D> {
let now = self.clock.now_us();
self.take_incoming(now)?;
Self::hardware(self.device.coexist(now))?;
self.announce_streams()?;
self.watchdog(now)?;
self.walk(now)?;
self.release_expired(now);
@@ -76,6 +76,8 @@ struct Air {
templates: Vec<templates::Templates>,
/// A watchdog run finds too many frames for power save.
busy: bool,
/// What Bluetooth changes of the stream count.
stream_changes: Vec<bool>,
/// The AP stopped beaconing on its channel.
quiet: bool,
/// The AP takes no frame at all.
@@ -194,6 +196,9 @@ impl Device for Model {
self.0.borrow_mut().cleared.push(entry);
Ok(())
}
fn stream_change(&mut self) -> Option<bool> {
self.0.borrow_mut().stream_changes.pop()
}
fn set_templates(&mut self, templates: &templates::Templates) -> Result<(), String> {
self.0.borrow_mut().templates.push(templates.clone());
Ok(())
@@ -640,6 +645,18 @@ fn nullfuncs(air: &Air) -> usize {
air.sent.iter().filter(|sent| sent.2[0] == 0x48).count()
}
#[test]
fn a_change_of_streams_is_told_to_the_ap() {
let (mut wifi, model) = connected();
model.0.borrow_mut().stream_changes.push(true);
let action = |air: &Air| {
air.sent
.iter()
.any(|(_, _, frame)| frame[0] == 0xd0 && frame[24..] == [7, 1, 1])
};
assert!(run(&mut wifi, &model, |_, air| action(air)));
}
#[test]
fn an_association_leaves_firmware_its_frames() {
let (_, model) = connected();