fix(net): run the 82574L watchdog's PHY check and reset task as stepped work that waits at most 40 ms per link call, so a PHY hang reset never holds the processor for over a second

This commit is contained in:
Tyler Smith committed 2026-11-14 01:33:58 -05:00
1 parent b4a90775be
commit 8b0eaaae1f
2 files changed
+537 -167

No files matched your search

+363 -166
View File
@@ -62,11 +62,13 @@ use crate::{
},
registers,
};
use alloc::{format, string::String, vec::Vec};
use alloc::{format, rc::Rc, string::String, vec::Vec};
use core::{
mem::ManuallyDrop,
sync::atomic::{Ordering, fence},
task::Poll,
};
use stela_driver_base::stepped::{Allowance, Stepped, block_on};
const VENDOR: u16 = 0x8086;
const DEVICE: u16 = 0x10d3;
@@ -222,7 +224,14 @@ const STOP_WAITS: Waits = Waits {
/// `e1000e_down`).
const STOP_SETTLE_US: u64 = 10_000;
const MDIC_WAIT_US: u64 = 20_000;
/// A PHY reset's completion, polled every millisecond for at least this.
const PHY_WAIT_US: u64 = 500_000;
const PHY_POLL_US: u64 = 1_000;
/// Each link poll's share of waiting for a PHY check or reset under way:
/// up to this, plus the one piece that crosses it.
const STEP_US: u64 = 40_000;
/// The longest piece of one bounded wait in stepped work.
const PIECE_US: u64 = 10_000;
/// Linux runs the e1000e watchdog every two seconds.
const WATCHDOG_US: u64 = 2_000_000;
/// Copper inter-packet gaps: IPGT 8, IPGR1 8, IPGR2 6.
@@ -277,30 +286,6 @@ impl Timer for crate::timing::Timing {
}
}
fn ownership(device: &impl Registers, clock: &impl Timer) -> Result<(), BlockError> {
ownership_within(device, clock, OWNERSHIP_WAIT_US)
}
fn ownership_within(
device: &impl Registers,
clock: &impl Timer,
wait_us: u64,
) -> Result<(), BlockError> {
if clock.wait(wait_us, || {
device.write(EXTCNF_CTRL, device.read(EXTCNF_CTRL) | MDIO_OWN);
device.read(EXTCNF_CTRL) & MDIO_OWN != 0
}) {
Ok(())
} else {
release(device);
Err(BlockError::Timeout)
}
}
fn release(device: &impl Registers) {
device.write(EXTCNF_CTRL, device.read(EXTCNF_CTRL) & !MDIO_OWN);
}
/// How long a reset waits for the bus master and MDIO ownership, and
/// whether it waits for the PHY's configuration after the NVM load.
struct Waits {
@@ -316,50 +301,247 @@ const START_WAITS: Waits = Waits {
phy_configuration: true,
};
/// The reset and PHY sequences over one register interface and clock. Given
/// a per-step wait share ([`Self::sliced`]), they run as stepped work: each
/// bounded wait goes in pieces of at most [`PIECE_US`], and a step ends once
/// its share is spent, keeping the same overall bounds.
struct Hardware<'a, R, T> {
device: &'a R,
clock: &'a T,
slice: Option<&'a Allowance>,
}
impl<'a, R: Registers, T: Timer> Hardware<'a, R, T> {
fn new(device: &'a R, clock: &'a T) -> Self {
Self {
device,
clock,
slice: None,
}
}
fn sliced(self, slice: &'a Allowance) -> Self {
Self {
slice: Some(slice),
..self
}
}
/// At least `us` microseconds, in pieces when stepped.
async fn delay(&self, us: u64) -> Result<(), BlockError> {
let Some(slice) = self.slice else {
return self.clock.delay(us);
};
let mut left = us;
while left != 0 {
let piece = left.min(PIECE_US);
self.clock.delay(piece)?;
slice.spent(piece).await;
left -= piece;
}
Ok(())
}
/// [`Timer::wait`], in pieces when stepped.
async fn wait(&self, us: u64, mut ready: impl FnMut() -> bool) -> bool {
let Some(slice) = self.slice else {
return self.clock.wait(us, ready);
};
let mut left = us;
loop {
let piece = left.min(PIECE_US);
if self.clock.wait(piece, &mut ready) {
return true;
}
left -= piece;
if left == 0 {
return false;
}
slice.spent(piece).await;
}
}
async fn ownership(&self, wait_us: u64) -> Result<(), BlockError> {
let device = self.device;
if self
.wait(wait_us, || {
device.write(EXTCNF_CTRL, device.read(EXTCNF_CTRL) | MDIO_OWN);
device.read(EXTCNF_CTRL) & MDIO_OWN != 0
})
.await
{
Ok(())
} else {
release(device);
Err(BlockError::Timeout)
}
}
async fn reset(&self, waits: &Waits) -> Result<(), BlockError> {
let device = self.device;
device.write(IMC, u32::MAX);
device.write(RCTL, 0);
device.write(TCTL, device.read(TCTL) & !TCTL_EN);
device.write(CTRL, device.read(CTRL) | CTRL_MASTER_DISABLE);
if !self
.wait(waits.master_us, || device.read(STATUS) & STATUS_MASTER == 0)
.await
{
return Err(BlockError::Timeout);
}
device.read(STATUS); // flush posted PCIe writes before the settle time
self.delay(MASTER_SETTLE_US).await?;
self.ownership(waits.ownership_us).await?;
device.write(CTRL, device.read(CTRL) | CTRL_RST);
let reset_done = self
.wait(RESET_WAIT_US, || device.read(CTRL) & CTRL_RST == 0)
.await;
release(device);
if !reset_done
|| !self
.wait(RESET_WAIT_US, || device.read(EECD) & EECD_AUTO_RD != 0)
.await
{
return Err(BlockError::Timeout);
}
if waits.phy_configuration {
self.delay(PHY_CONFIGURATION_US).await?;
}
device.write(IMC, u32::MAX);
device.read(ICR);
Ok(())
}
/// Linux `e1000e_down`'s register sequence: receive, then transmit, off,
/// 10 ms for frames in flight, then `e1000_reset_hw_82571`'s bus master
/// drain and MAC reset. Only a completed reset proves the controller
/// writes no ring. Every wait fits a processor's exit ([`STOP_WAITS`]);
/// the PHY is not waited for, as nothing configures it after a stop.
async fn stop(&self) -> Result<(), BlockError> {
let device = self.device;
device.write(RCTL, device.read(RCTL) & !RCTL_EN);
device.write(TCTL, device.read(TCTL) & !TCTL_EN);
device.read(STATUS);
self.delay(STOP_SETTLE_US).await?;
self.reset(&STOP_WAITS).await
}
async fn mdic(&self, register: u16, data: Option<u16>) -> Result<u16, BlockError> {
let device = self.device;
let command = MDIC_PHY
| (u32::from(register) << 16)
| data.map_or(MDIC_READ, |data| MDIC_WRITE | u32::from(data));
device.write(MDIC, command);
if !self
.wait(MDIC_WAIT_US, || device.read(MDIC) & MDIC_READY != 0)
.await
{
return Err(BlockError::Timeout);
}
let result = device.read(MDIC);
if result & MDIC_ERROR != 0 || result & MDIC_REGISTER != command & MDIC_REGISTER {
return Err(BlockError::Device { status: result });
}
Ok(result as u16)
}
async fn reset_phy(&self) -> Result<(), BlockError> {
let control = self.mdic(PHY_CONTROL, None).await?;
self.mdic(PHY_CONTROL, Some(control | PHY_RESET)).await?;
// Each poll is an MDIO read with its own bounded wait, so the polls
// are counted delays rather than one wait.
let mut waited = 0;
loop {
match self.mdic(PHY_CONTROL, None).await {
Ok(value) if value & PHY_RESET != 0 => {}
last => return last.map(|_| ()),
}
if waited >= PHY_WAIT_US {
return Err(BlockError::Timeout);
}
self.delay(PHY_POLL_US).await?;
waited += PHY_POLL_US;
}
}
async fn configure_phy(&self) -> Result<(), BlockError> {
self.ownership(OWNERSHIP_WAIT_US).await?;
let result = self.configure_owned_phy().await;
release(self.device);
result
}
async fn configure_owned_phy(&self) -> Result<(), BlockError> {
self.mdic(PHY_PAGE, Some(0)).await?;
let id = u32::from(self.mdic(PHY_ID1, None).await?) << 16
| u32::from(self.mdic(PHY_ID2, None).await?);
if id != PHY_BM_REV2 {
return Err(BlockError::Unsupported("82574L with an unknown PHY"));
}
let mut specific = self.mdic(PHY_SPECIFIC, None).await?;
specific = (specific | PHY_AUTO_MDIX) & !PHY_POLARITY_DISABLE;
self.mdic(PHY_SPECIFIC, Some(specific & !PHY_DOWNSHIFT))
.await?;
self.reset_phy().await?;
self.mdic(PHY_SPECIFIC, Some(specific | PHY_DOWNSHIFT))
.await?;
self.mdic(PHY_BIAS1, Some(PHY_BIAS1_VALUE)).await?;
self.mdic(PHY_BIAS2, Some(PHY_BIAS2_VALUE)).await?;
self.reset_phy().await?;
self.mdic(PHY_ADVERTISE, Some(PHY_ADVERTISE_10_100)).await?;
let gigabit = self.mdic(PHY_GIGABIT, None).await?;
self.mdic(
PHY_GIGABIT,
Some((gigabit & !PHY_GIGABIT_FIELDS) | PHY_GIGABIT_FULL),
)
.await?;
let control = self.mdic(PHY_CONTROL, None).await?;
self.mdic(
PHY_CONTROL,
Some(
(control & !(PHY_RESET | PHY_LOOPBACK | PHY_POWERDOWN | PHY_ISOLATE))
| PHY_AUTONEG
| PHY_RESTART,
),
)
.await?;
Ok(())
}
/// Whether the BM PHY has hung: its receive error counter and
/// 1000BASE-T idle error count both saturated (Linux
/// `e1000_check_phy_82574`). A failed MDIO read is not a hang.
async fn phy_hung(&self) -> bool {
if self.ownership(OWNERSHIP_WAIT_US).await.is_err() {
return false;
}
let hung = self.mdic(PHY_RECEIVE_ERRORS, None).await == Ok(u16::MAX)
&& self
.mdic(PHY_GIGABIT_STATUS, None)
.await
.is_ok_and(|status| status & PHY_IDLE_ERRORS == PHY_IDLE_ERRORS);
release(self.device);
hung
}
/// Linux's reset task's hardware part: the MAC reset, then the PHY.
async fn reinitialize(&self) -> Result<(), BlockError> {
self.reset(&START_WAITS).await?;
self.configure_phy().await
}
}
fn release(device: &impl Registers) {
device.write(EXTCNF_CTRL, device.read(EXTCNF_CTRL) & !MDIO_OWN);
}
fn reset(device: &impl Registers, clock: &impl Timer) -> Result<(), BlockError> {
reset_within(device, clock, &START_WAITS)
block_on(Hardware::new(device, clock).reset(&START_WAITS))
}
fn reset_within(
device: &impl Registers,
clock: &impl Timer,
waits: &Waits,
) -> Result<(), BlockError> {
device.write(IMC, u32::MAX);
device.write(RCTL, 0);
device.write(TCTL, device.read(TCTL) & !TCTL_EN);
device.write(CTRL, device.read(CTRL) | CTRL_MASTER_DISABLE);
if !clock.wait(waits.master_us, || device.read(STATUS) & STATUS_MASTER == 0) {
return Err(BlockError::Timeout);
}
device.read(STATUS); // flush posted PCIe writes before the settle time
clock.delay(MASTER_SETTLE_US)?;
ownership_within(device, clock, waits.ownership_us)?;
device.write(CTRL, device.read(CTRL) | CTRL_RST);
let reset_done = clock.wait(RESET_WAIT_US, || device.read(CTRL) & CTRL_RST == 0);
release(device);
if !reset_done || !clock.wait(RESET_WAIT_US, || device.read(EECD) & EECD_AUTO_RD != 0) {
return Err(BlockError::Timeout);
}
if waits.phy_configuration {
clock.delay(PHY_CONFIGURATION_US)?;
}
device.write(IMC, u32::MAX);
device.read(ICR);
Ok(())
}
/// Linux `e1000e_down`'s register sequence: receive, then transmit, off,
/// 10 ms for frames in flight, then `e1000_reset_hw_82571`'s bus master
/// drain and MAC reset. Only a completed reset proves the controller writes
/// no ring. Every wait fits a processor's exit ([`STOP_WAITS`]); the PHY is
/// not waited for, as nothing configures it after a stop.
/// [`Hardware::stop`], run to completion.
fn stop(device: &impl Registers, clock: &impl Timer) -> Result<(), BlockError> {
device.write(RCTL, device.read(RCTL) & !RCTL_EN);
device.write(TCTL, device.read(TCTL) & !TCTL_EN);
device.read(STATUS);
clock.delay(STOP_SETTLE_US)?;
reset_within(device, clock, &STOP_WAITS)
block_on(Hardware::new(device, clock).stop())
}
/// `e1000e_release_hw_control`: hand the controller back to manageability
@@ -368,82 +550,8 @@ fn release_control(device: &impl Registers) {
device.write(CTRL_EXT, device.read(CTRL_EXT) & !CTRL_EXT_DRIVER);
}
fn mdic(
device: &impl Registers,
clock: &impl Timer,
register: u16,
data: Option<u16>,
) -> Result<u16, BlockError> {
let command = MDIC_PHY
| (u32::from(register) << 16)
| data.map_or(MDIC_READ, |data| MDIC_WRITE | u32::from(data));
device.write(MDIC, command);
if !clock.wait(MDIC_WAIT_US, || device.read(MDIC) & MDIC_READY != 0) {
return Err(BlockError::Timeout);
}
let result = device.read(MDIC);
if result & MDIC_ERROR != 0 || result & MDIC_REGISTER != command & MDIC_REGISTER {
return Err(BlockError::Device { status: result });
}
Ok(result as u16)
}
fn reset_phy(device: &impl Registers, clock: &impl Timer) -> Result<(), BlockError> {
let control = mdic(device, clock, PHY_CONTROL, None)?;
mdic(device, clock, PHY_CONTROL, Some(control | PHY_RESET))?;
let mut last = Ok(0);
if !clock.wait(PHY_WAIT_US, || {
last = mdic(device, clock, PHY_CONTROL, None);
match &last {
Ok(value) => value & PHY_RESET == 0,
Err(_) => true,
}
}) {
return Err(BlockError::Timeout);
}
last.map(|_| ())
}
fn configure_phy(device: &impl Registers, clock: &impl Timer) -> Result<(), BlockError> {
ownership(device, clock)?;
let result = (|| {
mdic(device, clock, PHY_PAGE, Some(0))?;
let id = u32::from(mdic(device, clock, PHY_ID1, None)?) << 16
| u32::from(mdic(device, clock, PHY_ID2, None)?);
if id != PHY_BM_REV2 {
return Err(BlockError::Unsupported("82574L with an unknown PHY"));
}
let mut specific = mdic(device, clock, PHY_SPECIFIC, None)?;
specific = (specific | PHY_AUTO_MDIX) & !PHY_POLARITY_DISABLE;
mdic(device, clock, PHY_SPECIFIC, Some(specific & !PHY_DOWNSHIFT))?;
reset_phy(device, clock)?;
mdic(device, clock, PHY_SPECIFIC, Some(specific | PHY_DOWNSHIFT))?;
mdic(device, clock, PHY_BIAS1, Some(PHY_BIAS1_VALUE))?;
mdic(device, clock, PHY_BIAS2, Some(PHY_BIAS2_VALUE))?;
reset_phy(device, clock)?;
mdic(device, clock, PHY_ADVERTISE, Some(PHY_ADVERTISE_10_100))?;
let gigabit = mdic(device, clock, PHY_GIGABIT, None)?;
mdic(
device,
clock,
PHY_GIGABIT,
Some((gigabit & !PHY_GIGABIT_FIELDS) | PHY_GIGABIT_FULL),
)?;
let control = mdic(device, clock, PHY_CONTROL, None)?;
mdic(
device,
clock,
PHY_CONTROL,
Some(
(control & !(PHY_RESET | PHY_LOOPBACK | PHY_POWERDOWN | PHY_ISOLATE))
| PHY_AUTONEG
| PHY_RESTART,
),
)?;
Ok(())
})();
release(device);
result
block_on(Hardware::new(device, clock).configure_phy())
}
fn station(low: u32, high: u32) -> Option<Mac> {
@@ -453,18 +561,9 @@ fn station(low: u32, high: u32) -> Option<Mac> {
(high & RAH_VALID != 0 && mac.0 != [0; 6] && !mac.is_multicast()).then_some(mac)
}
/// Whether the BM PHY has hung: its receive error counter and 1000BASE-T
/// idle error count both saturated (Linux `e1000_check_phy_82574`). A
/// failed MDIO read is not a hang.
#[cfg(test)]
fn phy_hung(device: &impl Registers, clock: &impl Timer) -> bool {
if ownership(device, clock).is_err() {
return false;
}
let hung = mdic(device, clock, PHY_RECEIVE_ERRORS, None) == Ok(u16::MAX)
&& mdic(device, clock, PHY_GIGABIT_STATUS, None)
.is_ok_and(|status| status & PHY_IDLE_ERRORS == PHY_IDLE_ERRORS);
release(device);
hung
block_on(Hardware::new(device, clock).phy_hung())
}
/// The 82574L owns these buffers until reboot. Polling never waits for a
@@ -486,6 +585,23 @@ pub struct E1000e {
pub location: String,
/// Whether MSI-X vector 0 sends the handoff's completion signal.
signalled: bool,
/// The watchdog's PHY check or reset under way.
work: Option<Work>,
}
/// What a watchdog job found.
enum Outcome {
Hung(bool),
Reinitialized(Result<(), BlockError>),
}
/// Linux's watchdog PHY check or reset task, run a step per link poll so no
/// poll holds the processor for its waits (MDIO ownership, the PHY resets).
struct Work {
task: Stepped<'static, Outcome>,
slice: Rc<Allowance>,
/// A reset: the rings are untouched and the carrier down until it ends.
resetting: bool,
}
impl E1000e {
@@ -552,6 +668,7 @@ impl E1000e {
timing_failure: None,
location: format!("{} Intel 82574L", function.address),
signalled,
work: None,
};
net.start();
Ok(net)
@@ -559,11 +676,19 @@ impl E1000e {
/// Linux's watchdog, driven by link polls: discard transmit work the
/// link took down with it, and reinitialize after two PHY hang reports
/// in a row. Returns the carrier.
/// in a row. Returns the carrier, down while a reset runs.
fn watchdog(&mut self) -> Result<bool, LinkError> {
if let Some(error) = &self.timing_failure {
return Err(LinkError::Pci(error.clone()));
}
if let Some(outcome) = self.advance()
&& self.finish(outcome)?
{
return Ok(false);
}
if self.resetting() {
return Ok(false);
}
let status = self.device.read32(STATUS);
self.faulted |= status == u32::MAX;
if self.faulted {
@@ -577,21 +702,76 @@ impl E1000e {
self.flush_transmit();
}
let now = self.clock.now_us();
if now >= self.watchdog_at {
if self.work.is_none() && now >= self.watchdog_at {
self.watchdog_at = now.saturating_add(WATCHDOG_US);
self.phy_hangs = match phy_hung(&self.device, &self.clock) {
true => self.phy_hangs + 1,
false => 0,
};
if self.phy_hangs > 1 {
self.phy_hangs = 0;
self.reinitialize()?;
if let Some(outcome) = self.begin(false)
&& self.finish(outcome)?
{
return Ok(false);
}
}
Ok(carrier)
}
/// Start a watchdog job and take its first step: its outcome if that
/// completed it, otherwise `None` with the rest left for later polls.
fn begin(&mut self, reinitialize: bool) -> Option<Outcome> {
let (device, clock) = (self.device, self.clock.clone());
let slice = Rc::new(Allowance::new(STEP_US));
let shared = slice.clone();
let mut task = Stepped::new(async move {
let hardware = Hardware::new(&device, &clock).sliced(&shared);
match reinitialize {
true => Outcome::Reinitialized(hardware.reinitialize().await),
false => Outcome::Hung(hardware.phy_hung().await),
}
});
match task.step() {
Poll::Ready(outcome) => Some(outcome),
Poll::Pending => {
self.work = Some(Work {
task,
slice,
resetting: reinitialize,
});
None
}
}
}
/// One step of the job under way, if any: its outcome once it ends.
fn advance(&mut self) -> Option<Outcome> {
let work = self.work.as_mut()?;
work.slice.refill();
let Poll::Ready(outcome) = work.task.step() else {
return None;
};
self.work = None;
Some(outcome)
}
fn resetting(&self) -> bool {
self.work.as_ref().is_some_and(|work| work.resetting)
}
/// Act on a finished job: count PHY hang reports, starting a reset on
/// the second in a row, or bring the rings back after a reset. Whether
/// a reset started or ended.
fn finish(&mut self, outcome: Outcome) -> Result<bool, LinkError> {
match outcome {
Outcome::Hung(hung) => {
self.phy_hangs = if hung { self.phy_hangs + 1 } else { 0 };
if self.phy_hangs > 1 {
self.phy_hangs = 0;
self.reinitialize()?;
return Ok(true);
}
Ok(false)
}
Outcome::Reinitialized(result) => self.reinitialized(result).map(|()| true),
}
}
/// Stop transmit, discard every queued descriptor and start again
/// empty, as Linux's reset does for work the link can no longer carry.
fn flush_transmit(&mut self) {
@@ -603,8 +783,20 @@ impl E1000e {
self.device.write32(TCTL, control);
}
/// Linux's reset task: reset the MAC and PHY and bring the rings back.
/// Linux's reset task: reset the MAC and PHY, then bring the rings
/// back. It runs in steps ([`Work`]): this call takes the first.
fn reinitialize(&mut self) -> Result<(), LinkError> {
if let Some(error) = &self.timing_failure {
return Err(LinkError::Pci(error.clone()));
}
match self.begin(true) {
Some(outcome) => self.finish(outcome).map(|_| ()),
None => Ok(()),
}
}
/// The rings back after a completed reset, or its failure reported.
fn reinitialized(&mut self, prepared: Result<(), BlockError>) -> Result<(), LinkError> {
let failed = |error: BlockError| {
if matches!(error, BlockError::PciPower(_)) {
return LinkError::Pci(error);
@@ -614,11 +806,6 @@ impl E1000e {
self.location
))
};
if let Some(error) = &self.timing_failure {
return Err(LinkError::Pci(error.clone()));
}
let prepared = reset(&self.device, &self.clock)
.and_then(|()| configure_phy(&self.device, &self.clock));
if let Err(error) = prepared {
if matches!(error, BlockError::PciPower(_)) {
self.timing_failure = Some(error.clone());
@@ -736,6 +923,8 @@ impl Drop for E1000e {
/// This drives the controller's registers, so the owner drops it where
/// its MMIO window is mapped; anywhere else the first read faults.
fn drop(&mut self) {
// A PHY check or reset under way ends here; the stop resets the MAC.
self.work = None;
if self.faulted || self.timing_failure.is_some() || self.device.read32(STATUS) == u32::MAX {
return;
}
@@ -812,6 +1001,14 @@ impl E1000e {
if let Some(error) = &self.timing_failure {
return Err(LinkError::Pci(error.clone()));
}
if self.resetting() {
if let Some(outcome) = self.advance() {
self.finish(outcome)?;
}
if self.resetting() {
return Ok(None);
}
}
// Bound processing even if a device continually supplies bad frames.
for _ in 0..DESCRIPTORS {
let index = self.receive.next;
+174 -1
View File
@@ -4,7 +4,7 @@ use crate::bus::{
pci::{Address, ConfigSpace},
};
use alloc::collections::BTreeMap;
use core::cell::RefCell;
use core::cell::{Cell, RefCell};
#[derive(Default)]
struct Model {
@@ -17,6 +17,11 @@ struct Model {
mdic_timeout: bool,
mdic_error: bool,
wrong_register: bool,
/// MDIO ownership claims refused before one is granted.
ownership_refusals: Cell<usize>,
/// Reads of the PHY control register that still show a PHY reset.
phy_reset_polls: Cell<usize>,
phy_reset_left: Cell<usize>,
}
impl Model {
@@ -39,6 +44,11 @@ impl Registers for Model {
if offset == EXTCNF_CTRL && self.ownership_blocked {
value &= !MDIO_OWN;
}
if offset == EXTCNF_CTRL && value & MDIO_OWN != 0 && self.ownership_refusals.get() != 0 {
self.ownership_refusals
.set(self.ownership_refusals.get() - 1);
value &= !MDIO_OWN;
}
if offset == CTRL {
if value & CTRL_RST != 0 && !self.reset_stuck {
value &= !CTRL_RST;
@@ -53,8 +63,15 @@ impl Registers for Model {
value |= MDIC_ERROR;
} else if value & MDIC_READ != 0 {
value |= u32::from(self.phy.borrow()[register]);
if register == usize::from(PHY_CONTROL) && self.phy_reset_left.get() != 0 {
self.phy_reset_left.set(self.phy_reset_left.get() - 1);
value |= u32::from(PHY_RESET);
}
} else {
let data = value as u16;
if register == usize::from(PHY_CONTROL) && data & PHY_RESET != 0 {
self.phy_reset_left.set(self.phy_reset_polls.get());
}
self.phy.borrow_mut()[register] = if register == usize::from(PHY_CONTROL) {
data & !(PHY_RESET | PHY_RESTART)
} else {
@@ -96,6 +113,161 @@ impl Timer for ModelTimer {
}
}
/// A clock whose waits poll every 100 us of model time, as a real deadline
/// wait polls, counting the time waited.
#[derive(Default)]
struct PollingTimer {
elapsed: Cell<u64>,
}
impl Timer for PollingTimer {
fn delay(&self, microseconds: u64) -> Result<(), BlockError> {
self.elapsed.set(self.elapsed.get() + microseconds);
Ok(())
}
fn wait(&self, microseconds: u64, mut ready: impl FnMut() -> bool) -> bool {
let mut waited = 0;
loop {
if ready() {
return true;
}
if waited >= microseconds {
return false;
}
waited += 100;
self.elapsed.set(self.elapsed.get() + 100);
}
}
}
/// A reset task waiting on MDIO ownership firmware holds and on slow PHY
/// resets, about a second in all, runs in steps: none waits more than
/// 60 ms, and it makes the same register writes as the blocking one.
#[test]
fn a_stepped_reinitialization_matches_the_blocking_one_and_waits_little_per_step() {
let run = |stepped: bool| {
let model = Model::ready();
model.ownership_refusals.set(1_500);
model.phy_reset_polls.set(300);
let timer = PollingTimer::default();
let mut steps = 0;
let result = if stepped {
let slice = Allowance::new(STEP_US);
let hardware = Hardware::new(&model, &timer).sliced(&slice);
let mut task = core::pin::pin!(hardware.reinitialize());
loop {
slice.refill();
let before = timer.elapsed.get();
let step = stela_driver_base::stepped::poll_once(task.as_mut());
let waited = timer.elapsed.get() - before;
assert!(waited <= 60_000, "step {steps} waited {waited} us");
steps += 1;
if let Poll::Ready(result) = step {
break result;
}
}
} else {
block_on(Hardware::new(&model, &timer).reinitialize())
};
let writes = model.writes.borrow().clone();
(result, steps, writes, timer.elapsed.get())
};
let (blocking, _, writes, waited) = run(false);
let (stepped, steps, stepped_writes, stepped_waited) = run(true);
assert_eq!(blocking, Ok(()));
assert_eq!(stepped, Ok(()));
assert_eq!(stepped_writes, writes);
assert!(waited > 700_000, "{waited}");
// A piece ends with one more poll at its expiry, so a little less.
assert!(
waited - stepped_waited < 10_000,
"{stepped_waited} {waited}"
);
assert!(steps > 15, "{steps}");
}
/// A PHY check on ownership firmware holds runs in steps too.
#[test]
fn a_stepped_phy_check_waits_little_per_step() {
let model = Model::ready();
model.phy.borrow_mut()[usize::from(PHY_RECEIVE_ERRORS)] = u16::MAX;
model.phy.borrow_mut()[usize::from(PHY_GIGABIT_STATUS)] = PHY_IDLE_ERRORS;
model.ownership_refusals.set(1_500);
let timer = PollingTimer::default();
let slice = Allowance::new(STEP_US);
let hardware = Hardware::new(&model, &timer).sliced(&slice);
let mut task = core::pin::pin!(hardware.phy_hung());
let mut steps = 0;
let hung = loop {
slice.refill();
let before = timer.elapsed.get();
let step = stela_driver_base::stepped::poll_once(task.as_mut());
assert!(timer.elapsed.get() - before <= 60_000);
steps += 1;
if let Poll::Ready(hung) = step {
break hung;
}
};
assert!(hung);
assert!(steps >= 4, "{steps}");
assert_eq!(model.read(EXTCNF_CTRL) & MDIO_OWN, 0);
}
/// While a reset runs, every link call takes one step of at most 60 ms:
/// the carrier is down, frames are refused and received frames wait, and
/// neither ring moves. Here the bus master never drains, so it fails
/// after its 160 ms, as the blocking reset did.
#[test]
fn link_calls_take_a_reset_a_step_at_a_time_and_leave_the_rings_alone() {
let mut fixture = Fixture::new();
let _clock = crate::test_clock::virtualize();
let nominal = Clock {
ticks_per_microsecond: 1,
};
let (timing, minimum) = crate::timing::counted_model(nominal);
fixture.net.clock = timing;
fixture.net.transmit(&[1; 60]).unwrap();
fixture.inject(0, 60, RX_DONE | RX_EOP, 0, 7);
fixture.registers[STATUS / 4] = STATUS_LU | STATUS_MASTER;
let spent = || nominal.now_us() + minimum.get();
let before = spent();
assert_eq!(fixture.net.reinitialize(), Ok(()));
assert!(spent() - before <= 60_000);
assert!(fixture.net.resetting());
let (tail, head) = (fixture.registers[TDT / 4], fixture.registers[RDT / 4]);
let receive = fixture.net.receive.descriptors.bytes().to_vec();
let mut calls = 0;
while fixture.net.resetting() {
let before = spent();
let result = match calls % 3 {
0 => Ok(fixture.net.carrier()).map(|up| assert!(!up)),
1 => fixture
.net
.transmit(&[2; 60])
.map(|()| panic!("sent while resetting")),
_ => fixture.net.receive().map(|frame| assert_eq!(frame, None)),
};
calls += 1;
assert!(spent() - before <= 60_000, "call {calls}");
match result {
// The call that ends the reset reports its failure.
Err(LinkError::Adapter(message)) => {
assert!(message.contains("reinitialization failed"), "{message}");
assert!(!fixture.net.resetting());
}
Err(LinkError::NoCarrier) | Ok(()) => {}
other => panic!("{other:?}"),
}
if fixture.net.resetting() {
assert_eq!(fixture.registers[TDT / 4], tail);
assert_eq!(fixture.registers[RDT / 4], head);
assert_eq!(fixture.net.receive.descriptors.bytes(), receive);
}
}
assert!(calls >= 3, "{calls}");
}
#[test]
fn a_stop_drains_the_bus_master_resets_the_mac_and_hands_control_back() {
let model = Model::ready();
@@ -339,6 +511,7 @@ impl Fixture {
timing_failure: None,
location: String::from("model"),
signalled: false,
work: None,
};
net.start();
registers[STATUS / 4] = STATUS_LU;