fix(net): run an I217/I218/I219 link change as stepped work that waits at most 40 ms per call on the PHY semaphore and management bus, keeping Linux's bounds, so a link poll never holds the processor for up to a second

This commit is contained in:
Tyler Smith committed 2026-11-14 01:33:58 -05:00
1 parent 692fadf758
commit 57fc2be493
5 files changed
+533 -171

No files matched your search

+84 -26
View File
@@ -14,6 +14,9 @@ pub mod cold;
pub mod io;
pub mod nvm;
use alloc::rc::Rc;
use stela_driver_base::stepped::{Allowance, block_on};
const MDIC: u32 = 0x20;
const FWSM: u32 = 0x5b54;
const EXTCNF_CTRL: u32 = 0xf00;
@@ -160,6 +163,9 @@ pub struct Phy<R: Registers, D: Delay> {
poisoned: bool,
retry_count: u8,
retry_enabled: bool,
/// The wait share of the stepped work running this PHY's operations,
/// if any: its delays end a step once the share is spent.
allowance: Option<Rc<Allowance>>,
}
impl<R: Registers, D: Delay> Phy<R, D> {
/// # Safety
@@ -178,6 +184,7 @@ impl<R: Registers, D: Delay> Phy<R, D> {
poisoned: false,
retry_count: 0,
retry_enabled: false,
allowance: None,
}
}
@@ -222,6 +229,14 @@ impl<R: Registers, D: Delay> Phy<R, D> {
}
}
}
/// [`Self::wait_minimum`], then the step ends if it spent its share.
async fn pause(&mut self, us: u64) -> Result<(), Fault> {
self.wait_minimum(us)?;
if let Some(allowance) = &self.allowance {
allowance.spent(us).await;
}
Ok(())
}
fn read_mac(&mut self, at: u32) -> Result<u32, Fault> {
self.check_minimum()?;
let value = self
@@ -246,6 +261,9 @@ impl<R: Registers, D: Delay> Phy<R, D> {
/// `e1000_acquire_swflag_ich8lan`: the software flag the Intel ME
/// honours as well, so a managed adapter's PHY is shared through it.
fn acquire(&mut self) -> Result<(), Error> {
block_on(self.acquire_steps())
}
async fn acquire_steps(&mut self) -> Result<(), Error> {
let mut value = 0;
let mut available = false;
for _ in 0..100 {
@@ -254,7 +272,7 @@ impl<R: Registers, D: Delay> Phy<R, D> {
available = true;
break;
}
self.wait_minimum(1000)?;
self.pause(1000).await?;
}
if !available {
return Err(Fault::SemaphoreBusy.into());
@@ -264,7 +282,7 @@ impl<R: Registers, D: Delay> Phy<R, D> {
if self.read_mac(EXTCNF_CTRL)? & SWFLAG != 0 {
return Ok(());
}
self.wait_minimum(1000)?;
self.pause(1000).await?;
}
// An unacknowledged claim is uncertain. Try the source's clear, keep
// the owner on the final failure, and never retry this access epoch.
@@ -293,6 +311,13 @@ impl<R: Registers, D: Delay> Phy<R, D> {
fn transaction<T>(
&mut self,
operation: impl FnOnce(&mut Self) -> Result<T, Fault>,
) -> Result<T, Error> {
block_on(self.transaction_steps(async move |this: &mut Self| operation(this)))
}
/// The semaphore held around `operation`, which may wait across steps.
async fn transaction_steps<T>(
&mut self,
operation: impl AsyncFnOnce(&mut Self) -> Result<T, Fault>,
) -> Result<T, Error> {
if let Some(error) = self.minimum_failure {
return Err(Fault::Minimum(error).into());
@@ -301,11 +326,11 @@ impl<R: Registers, D: Delay> Phy<R, D> {
return Err(Fault::Poisoned.into());
}
self.check_minimum()?;
if let Err(error) = self.acquire() {
if let Err(error) = self.acquire_steps().await {
self.poisoned = true;
return Err(error);
}
let result = operation(self);
let result = operation(self).await;
let cleanup = self.release();
match (result, cleanup) {
(Ok(value), Ok(())) => Ok(value),
@@ -324,22 +349,35 @@ impl<R: Registers, D: Delay> Phy<R, D> {
}
fn mdic(&mut self, address: u8, index: u16, write: Option<u16>) -> Result<u16, Fault> {
block_on(self.mdic_steps(address, index, write))
}
async fn mdic_steps(
&mut self,
address: u8,
index: u16,
write: Option<u16>,
) -> Result<u16, Fault> {
let retries = if self.retry_enabled {
self.retry_count
} else {
0
};
for attempt in 0..=retries {
match self.mdic_once(address, index, write) {
match self.mdic_once(address, index, write).await {
Err(Fault::MdicTimeout | Fault::MdicResponse(_)) if attempt < retries => {
self.wait_minimum(10_000)?;
self.pause(10_000).await?;
}
result => return result,
}
}
unreachable!("bounded MDIC loop returns its last actual outcome")
}
fn mdic_once(&mut self, address: u8, index: u16, write: Option<u16>) -> Result<u16, Fault> {
async fn mdic_once(
&mut self,
address: u8,
index: u16,
write: Option<u16>,
) -> Result<u16, Fault> {
if address > 31 || index > 31 {
return Err(Fault::InvalidRegister);
}
@@ -350,7 +388,7 @@ impl<R: Registers, D: Delay> Phy<R, D> {
let mut response = 0;
let mut ready = false;
for _ in 0..MDIC_POLLS {
self.wait_minimum(50)?;
self.pause(50).await?;
response = self.read_mac(MDIC)?;
if response & MDIC_READY != 0 {
ready = true;
@@ -359,7 +397,7 @@ impl<R: Registers, D: Delay> Phy<R, D> {
}
// 82579 requires this quiet interval even when the transaction fails.
if self.kind == Kind::I82579 {
self.wait_minimum(100)?;
self.pause(100).await?;
}
if !ready {
return Err(Fault::MdicTimeout);
@@ -371,43 +409,63 @@ impl<R: Registers, D: Delay> Phy<R, D> {
}
fn page(&mut self, page: u16) -> Result<(), Fault> {
self.mdic(1, PHY_PAGE, Some(page << 5)).map(|_| ())
block_on(self.page_steps(page))
}
async fn page_steps(&mut self, page: u16) -> Result<(), Fault> {
self.mdic_steps(1, PHY_PAGE, Some(page << 5))
.await
.map(|_| ())
}
fn access(&mut self, register: Register, value: Option<u16>) -> Result<u16, Fault> {
block_on(self.access_steps(register, value))
}
async fn access_steps(&mut self, register: Register, value: Option<u16>) -> Result<u16, Fault> {
let Register { page, index } = register;
if page == WAKE_PAGE {
return self.wakeup(index, value);
return self.wakeup(index, value).await;
}
if page > 0 && page < 768 {
// All supported PHY types use I82577's debug address/data pair.
self.mdic(2, 16, Some(((page << 5) | index) & 0x3f))?;
return self.mdic(2, 17, value);
self.mdic_steps(2, 16, Some(((page << 5) | index) & 0x3f))
.await?;
return self.mdic_steps(2, 17, value).await;
}
let address = if page >= 768 { 1 } else { 2 };
if index > 15 {
self.page(if page == 768 { 0 } else { page })?;
self.page_steps(if page == 768 { 0 } else { page }).await?;
}
self.mdic(address, index, value)
self.mdic_steps(address, index, value).await
}
fn wakeup(&mut self, index: u16, value: Option<u16>) -> Result<u16, Fault> {
self.page(PORT_PAGE)?;
let saved = self.mdic(1, WAKE_ENABLE, None)?;
self.mdic(1, WAKE_ENABLE, Some((saved | WAKE_ACCESS) & !WAKE_ME_HOST))?;
self.page(WAKE_PAGE)?;
self.mdic(1, WAKE_ADDRESS, Some(index))?;
let result = self.mdic(1, WAKE_DATA, value)?;
self.page(PORT_PAGE)?;
self.mdic(1, WAKE_ENABLE, Some(saved))?;
async fn wakeup(&mut self, index: u16, value: Option<u16>) -> Result<u16, Fault> {
self.page_steps(PORT_PAGE).await?;
let saved = self.mdic_steps(1, WAKE_ENABLE, None).await?;
self.mdic_steps(1, WAKE_ENABLE, Some((saved | WAKE_ACCESS) & !WAKE_ME_HOST))
.await?;
self.page_steps(WAKE_PAGE).await?;
self.mdic_steps(1, WAKE_ADDRESS, Some(index)).await?;
let result = self.mdic_steps(1, WAKE_DATA, value).await?;
self.page_steps(PORT_PAGE).await?;
self.mdic_steps(1, WAKE_ENABLE, Some(saved)).await?;
Ok(result)
}
pub fn read(&mut self, register: Register) -> Result<u16, Error> {
self.transaction(|this| this.access(register, None))
block_on(self.read_steps(register))
}
pub fn write(&mut self, register: Register, value: u16) -> Result<(), Error> {
self.transaction(|this| this.access(register, Some(value)).map(|_| ()))
block_on(self.write_steps(register, value))
}
async fn read_steps(&mut self, register: Register) -> Result<u16, Error> {
self.transaction_steps(async |this: &mut Self| this.access_steps(register, None).await)
.await
}
async fn write_steps(&mut self, register: Register, value: u16) -> Result<(), Error> {
self.transaction_steps(async |this: &mut Self| {
this.access_steps(register, Some(value)).await.map(|_| ())
})
.await
}
/// Change `register` of a PHY that may not answer: a PHY that does not
/// answer is an answer (`false`), not a failure of the transport.
+24 -4
View File
@@ -12,6 +12,7 @@
use super::{Delay, Fault, Identity, Kind, Phy, Register, Registers, nvm};
use alloc::{rc::Rc, vec::Vec};
use core::cell::RefCell;
use stela_driver_base::stepped::block_on;
pub mod attach;
pub mod i219;
@@ -116,6 +117,8 @@ pub enum Error {
/// The Intel ME blocked the PHY after its reset.
BlockedAfterReset,
DescriptorFlushRequired,
/// A PHY link change was still under way when the adapter had to stop.
LinkChangeUnfinished,
Dma(crate::block::BlockError),
Stopped,
Poisoned,
@@ -182,6 +185,9 @@ impl core::fmt::Display for Error {
Self::DescriptorFlushRequired => {
f.write_str("the firmware left its rings needing a flush")
}
Self::LinkChangeUnfinished => {
f.write_str("a PHY link change was still under way when it had to stop")
}
Self::Dma(error) => write!(f, "its DMA memory failed ({error})"),
Self::Stopped => f.write_str("it is stopped"),
Self::Poisoned => f.write_str("an earlier failure left it unusable"),
@@ -614,13 +620,27 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Controller<R, D> {
Ok(())
}
fn modify(&mut self, page: u16, index: u16, clear: u16, set: u16) -> Result<(), Error> {
block_on(self.modify_steps(page, index, clear, set))
}
async fn modify_steps(
&mut self,
page: u16,
index: u16,
clear: u16,
set: u16,
) -> Result<(), Error> {
let reg = Register::new(page, index)?;
let value = self.phy.read(reg)?;
Ok(self.phy.write(reg, (value & !clear) | set)?)
let value = self.phy.read_steps(reg).await?;
Ok(self.phy.write_steps(reg, (value & !clear) | set).await?)
}
fn emi(p: &mut Phy<Bus<R>, D>, at: u16, data: u16) -> Result<(), Fault> {
p.access(Register { page: 0, index: 16 }, Some(at))?;
p.access(Register { page: 0, index: 17 }, Some(data))?;
block_on(Self::emi_steps(p, at, data))
}
async fn emi_steps(p: &mut Phy<Bus<R>, D>, at: u16, data: u16) -> Result<(), Fault> {
p.access_steps(Register { page: 0, index: 16 }, Some(at))
.await?;
p.access_steps(Register { page: 0, index: 17 }, Some(data))
.await?;
Ok(())
}
fn post_reset(&mut self) -> Result<(), Error> {
@@ -6,10 +6,17 @@
//! jumbo workaround is explicitly restored to its non-jumbo settings. FCS is
//! received and removed in software as in that source profile. No IRQ, EEE,
//! pause, VLAN, jumbo, managed firmware or power-transition profile is claimed.
use super::{Controller, Delay, Error, Registers, i219, lpt, nvm, spt};
use super::{Bus, Controller, Delay, Error, Registers, i219, lpt, nvm, spt};
use crate::{Link, LinkError, MAX_FRAME, MIN_FRAME, Mac, bus::dma::DmaAllocator};
use alloc::{format, vec::Vec};
use core::sync::atomic::{Ordering, fence};
use alloc::{format, rc::Rc, vec::Vec};
use core::{
ops::{Deref, DerefMut},
sync::atomic::{Ordering, fence},
task::Poll,
};
use stela_driver_base::stepped::{Allowance, Stepped, block_on};
type Phy<R, D> = super::super::Phy<Bus<R>, D>;
// Common descriptor storage only; the 82574-specific programming/reset/start
// routines are never called. Addresses are boot-lifetime coherent DMA RAM.
@@ -91,12 +98,49 @@ const LPI_PLL_SHUT: u16 = 0x4412;
const EEE_PCS_STATUS: u16 = 0x182e;
const EEE_ADVERTISEMENT: u16 = 0x040e;
const LPI_ENABLE: u16 = 0x6000;
/// The most one call waits on a link change, ending its step: the change
/// goes on at the next call.
const STEP_US: u64 = 40_000;
/// The steps a stop or drop gives a link change under way to finish.
const SETTLE_STEPS: usize = 2;
/// The controller, lent whole to the link change under way, if any. Every
/// path that reaches it checks [`Ethernet::change`] first.
struct Kept<T>(Option<T>);
impl<T> Deref for Kept<T> {
type Target = T;
fn deref(&self) -> &T {
self.0
.as_ref()
.expect("PCH controller lent to a link change")
}
}
impl<T> DerefMut for Kept<T> {
fn deref_mut(&mut self) -> &mut T {
self.0
.as_mut()
.expect("PCH controller lent to a link change")
}
}
/// The link to remember and whether it is up.
type Changed = (Option<u32>, bool);
/// A link change under way, holding the controller until it completes.
struct Change<R: Registers + nvm::Registers, D: Delay + Clone + 'static> {
task: Stepped<'static, (Controller<R, D>, Result<Changed, Error>)>,
slice: Rc<Allowance>,
}
/// The controller owner and DMA storage remain held after an
/// uncertain doorbell, timeout, removal or control failure. A fresh object is
/// not a retry mechanism; only an external real reset/recovery grants one.
pub struct Ethernet<R: Registers + nvm::Registers, D: Delay + Clone> {
controller: Controller<R, D>,
pub struct Ethernet<R: Registers + nvm::Registers, D: Delay + Clone + 'static> {
controller: Kept<Controller<R, D>>,
change: Option<Change<R, D>>,
station: Mac,
nvm_repair_left_out: bool,
ulp_exit_failed: bool,
receive: Ring,
transmit: Ring,
next_rx: usize,
@@ -107,7 +151,7 @@ pub struct Ethernet<R: Registers + nvm::Registers, D: Delay + Clone> {
stopped: bool,
failure: Option<Error>,
}
impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
impl<R: Registers + nvm::Registers, D: Delay + Clone + 'static> Ethernet<R, D> {
/// # Safety
/// `dma` grants coherent boot-lifetime CPU/DMA RAM reachable by the
/// same PCI requester as `controller`, using the allocator's real
@@ -130,7 +174,11 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
let receive = Ring::new(dma).map_err(Error::Dma)?;
let transmit = Ring::new(dma).map_err(Error::Dma)?;
let mut this = Self {
controller,
station: controller.station,
nvm_repair_left_out: controller.nvm.repair_left_out(),
ulp_exit_failed: controller.ulp_exit_failed(),
controller: Kept(Some(controller)),
change: None,
receive,
transmit,
next_rx: 0,
@@ -157,11 +205,11 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
/// Whether the NVM's checksum valid bit was clear, which Linux repairs
/// in flash and Stela leaves unwritten.
pub fn nvm_repair_left_out(&self) -> bool {
self.controller.nvm.repair_left_out()
self.nvm_repair_left_out
}
/// Whether the PHY did not leave ULP when asked and the start went on.
pub fn ulp_exit_failed(&self) -> bool {
self.controller.ulp_exit_failed()
self.ulp_exit_failed
}
fn check(&mut self) -> Result<(), Error> {
if let Some(error) = &self.failure
@@ -169,6 +217,10 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
{
return Err(error.clone());
}
if self.change.is_some() {
// The link change holds the controller and checks it itself.
return Ok(());
}
if let Some(error) = self.controller.minimum_failure() {
return Err(super::Fault::Minimum(error).into());
}
@@ -182,8 +234,11 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
}
}
fn modify_mac(&mut self, at: u32, clear: u32, set: u32) -> Result<(), Error> {
let value = self.controller.read(at)?;
self.controller.write(at, (value & !clear) | set)
Self::modify_in(&mut self.controller, at, clear, set)
}
fn modify_in(c: &mut Controller<R, D>, at: u32, clear: u32, set: u32) -> Result<(), Error> {
let value = c.read(at)?;
c.write(at, (value & !clear) | set)
}
fn kmrn(&mut self, index: u8, write: Option<u16>) -> Result<u16, Error> {
Ok(self.controller.phy.transaction(|p| {
@@ -399,172 +454,235 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
Ok(())
}
fn disable_eee(&mut self) -> Result<(), Error> {
let lpt = self.controller.profile.is_lpt_or_newer();
self.controller.phy.transaction(|p| {
Controller::<R, D>::emi(
p,
if lpt {
lpt::EEE_ADVERTISEMENT
} else {
EEE_ADVERTISEMENT
},
0,
)?;
let control = super::super::Register {
page: 772,
index: 20,
};
let value = p.access(control, None)? & !LPI_ENABLE;
if !lpt {
p.access(
block_on(Self::disable_eee_steps(&mut self.controller))
}
async fn disable_eee_steps(c: &mut Controller<R, D>) -> Result<(), Error> {
let lpt = c.profile.is_lpt_or_newer();
c.phy
.transaction_steps(async |p: &mut Phy<R, D>| {
Controller::<R, D>::emi_steps(
p,
if lpt {
lpt::EEE_ADVERTISEMENT
} else {
EEE_ADVERTISEMENT
},
0,
)
.await?;
let control = super::super::Register {
page: 772,
index: 20,
};
let value = p.access_steps(control, None).await? & !LPI_ENABLE;
if !lpt {
p.access_steps(
super::super::Register { page: 0, index: 16 },
Some(LPI_PLL_SHUT),
)
.await?;
let pll = p
.access_steps(super::super::Register { page: 0, index: 17 }, None)
.await?;
Controller::<R, D>::emi_steps(p, LPI_PLL_SHUT, pll & !4).await?;
}
p.access_steps(
super::super::Register { page: 0, index: 16 },
Some(LPI_PLL_SHUT),
)?;
let pll = p.access(super::super::Register { page: 0, index: 17 }, None)?;
Controller::<R, D>::emi(p, LPI_PLL_SHUT, pll & !4)?;
}
p.access(
super::super::Register { page: 0, index: 16 },
Some(if lpt {
lpt::EEE_PCS_STATUS
} else {
EEE_PCS_STATUS
}),
)?;
p.access(super::super::Register { page: 0, index: 17 }, None)?;
p.access(control, Some(value))?;
Ok(())
})?;
Some(if lpt {
lpt::EEE_PCS_STATUS
} else {
EEE_PCS_STATUS
}),
)
.await?;
p.access_steps(super::super::Register { page: 0, index: 17 }, None)
.await?;
p.access_steps(control, Some(value)).await?;
Ok(())
})
.await?;
Ok(())
}
/// Poll the link: two MAC reads while nothing changed. A change runs
/// the PHY and K1 workarounds as stepped work that holds the controller
/// and waits at most [`STEP_US`] (plus the one delay that crosses it)
/// per call, so a PHY semaphore the Intel ME holds or a slow management
/// bus never holds the processor for long; the link stays down until
/// the work completes.
fn update_link(&mut self) -> Result<bool, Error> {
self.check()?;
let status = self.controller.read(super::STATUS)? & LINK_SUMMARY;
// IMC masks interrupts, but ICR still latches link-status changes.
// Consume that event so same-speed reconnects cannot bypass
// PHY/K1 workarounds because the MAC summary is unchanged.
let event = self.controller.read(super::ICR)?;
if self.link == Some(status) && event & LINK_EVENT == 0 {
return Ok(status & LINK_UP != 0);
if self.change.is_none() {
self.check()?;
let status = self.controller.read(super::STATUS)? & LINK_SUMMARY;
// IMC masks interrupts, but ICR still latches link-status changes.
// Consume that event so same-speed reconnects cannot bypass
// PHY/K1 workarounds because the MAC summary is unchanged.
let event = self.controller.read(super::ICR)?;
if self.link == Some(status) && event & LINK_EVENT == 0 {
return Ok(status & LINK_UP != 0);
}
let mut controller = self.controller.0.take().expect("kept PCH controller");
let slice = Rc::new(Allowance::new(STEP_US));
controller.phy.allowance = Some(slice.clone());
let task = Stepped::new(async move {
let result = Self::link_change(&mut controller, status).await;
controller.phy.allowance = None;
(controller, result)
});
self.change = Some(Change { task, slice });
}
self.advance()
}
/// One step of the link change under way: its result once complete,
/// with the controller back; `false` (no link yet) until then.
fn advance(&mut self) -> Result<bool, Error> {
let Some(change) = &mut self.change else {
return Ok(self.link.is_some_and(|status| status & LINK_UP != 0));
};
change.slice.refill();
let Poll::Ready((controller, result)) = change.task.step() else {
return Ok(false);
};
self.change = None;
self.controller.0 = Some(controller);
let (link, up) = result?;
self.link = link;
Ok(up)
}
/// Finish a link change under way in at most `steps` steps, for a stop.
fn settle(&mut self, steps: usize) -> Result<(), Error> {
for _ in 0..steps {
if self.change.is_none() {
return Ok(());
}
if let Err(error) = self.advance() {
self.failure.get_or_insert_with(|| error.clone());
self.poison();
return Err(error);
}
}
if self.change.is_none() {
Ok(())
} else {
Err(Error::LinkChangeUnfinished)
}
}
/// The PHY, K1 and MAC workarounds for an observed link `status`: the
/// link to remember and whether it is up.
async fn link_change(c: &mut Controller<R, D>, status: u32) -> Result<Changed, Error> {
let mii = super::super::Register::new(0, 1)?;
self.controller.phy.read(mii)?; // clear latched-low observation
let phy = self.controller.phy.read(mii)?;
c.phy.read_steps(mii).await?; // clear latched-low observation
let phy = c.phy.read_steps(mii).await?;
if status & LINK_UP == 0 || phy & PHY_LINK_READY != PHY_LINK_READY {
self.controller
.lpt_link_common(if status & LINK_UP != 0 && phy & 4 != 0 {
Some(status)
} else {
None
})?;
self.link = if status & LINK_UP == 0 {
c.lpt_link_common(if status & LINK_UP != 0 && phy & 4 != 0 {
Some(status)
} else {
None
})?;
let link = if status & LINK_UP == 0 {
Some(status)
} else {
None
};
return Ok(false);
return Ok((link, false));
}
let half_ten = status & (FULL_DUPLEX | SPEED_MASK) == 0;
self.modify_mac(
TIPG,
0x3ff,
if half_ten {
0xff
} else if self.controller.is_i219()
&& status & FULL_DUPLEX != 0
&& status & (1 << 7) == 0
{
0xc
} else {
8
},
)?;
let lpt = self.controller.profile.is_lpt_or_newer();
let mtp = self.controller.mtp_family().is_some();
self.controller.phy.transaction(|p| {
Controller::<R, D>::emi(
p,
if lpt { lpt::RX_CONFIG } else { RX_CONFIG },
u16::from(!half_ten),
)?;
if lpt {
let gate = lpt::PLL_CLOCK_GATE;
let word = p.access(gate, None)?;
p.access(
gate,
Some(
(word & !lpt::PLL_CLOCK_GATE_MASK)
| if status & (1 << 7) != 0 {
if mtp {
super::mtp::GIGABIT_PLL_CLOCK_GATE
let gap = if half_ten {
0xff
} else if c.is_i219() && status & FULL_DUPLEX != 0 && status & (1 << 7) == 0 {
0xc
} else {
8
};
Self::modify_in(c, TIPG, 0x3ff, gap)?;
let lpt = c.profile.is_lpt_or_newer();
let mtp = c.mtp_family().is_some();
c.phy
.transaction_steps(async |p: &mut Phy<R, D>| {
Controller::<R, D>::emi_steps(
p,
if lpt { lpt::RX_CONFIG } else { RX_CONFIG },
u16::from(!half_ten),
)
.await?;
if lpt {
let gate = lpt::PLL_CLOCK_GATE;
let word = p.access_steps(gate, None).await?;
p.access_steps(
gate,
Some(
(word & !lpt::PLL_CLOCK_GATE_MASK)
| if status & (1 << 7) != 0 {
if mtp {
super::mtp::GIGABIT_PLL_CLOCK_GATE
} else {
lpt::PLL_CLOCK_GATE_GIGABIT
}
} else {
lpt::PLL_CLOCK_GATE_GIGABIT
}
} else {
lpt::PLL_CLOCK_GATE_SLOW
},
),
)?;
if status & (1 << 7) != 0 {
let pm = super::super::Register {
page: 770,
index: 17,
};
let word = p.access(pm, None)?;
p.access(pm, Some(word | lpt::K1_CLOCK_REQUEST))?;
lpt::PLL_CLOCK_GATE_SLOW
},
),
)
.await?;
if status & (1 << 7) != 0 {
let pm = super::super::Register {
page: 770,
index: 17,
};
let word = p.access_steps(pm, None).await?;
p.access_steps(pm, Some(word | lpt::K1_CLOCK_REQUEST))
.await?;
}
}
}
Ok(())
})?;
if self.controller.is_i219() {
Ok(())
})
.await?;
if c.is_i219() {
let gap = super::super::Register {
page: 776,
index: 20,
};
if status & (1 << 7) != 0 {
let word = self.controller.phy.read(gap)?;
let word = c.phy.read_steps(gap).await?;
if ((word >> 2) & 0x3ff) < 0x18 {
self.controller
.phy
.write(gap, (word & !(0x3ff << 2)) | (0x18 << 2))?;
c.phy
.write_steps(gap, (word & !(0x3ff << 2)) | (0x18 << 2))
.await?;
}
} else {
self.controller.phy.write(gap, 0xc023)?;
c.phy.write_steps(gap, 0xc023).await?;
}
}
if lpt {
self.controller.lpt_link_common(Some(status))?;
self.disable_eee()?;
self.modify_mac(super::TCTL, 0x3ff << 12, 63 << 12)?;
self.modify_mac(super::CTRL, PAUSE, 0)?;
self.link = Some(status);
return Ok(true);
c.lpt_link_common(Some(status))?;
Self::disable_eee_steps(c).await?;
Self::modify_in(c, super::TCTL, 0x3ff << 12, 63 << 12)?;
Self::modify_in(c, super::CTRL, PAUSE, 0)?;
return Ok((Some(status), true));
}
// 82579 K1 and half-duplex preamble workarounds apply on every observed
// speed/duplex transition, including a cable reconnection while polling.
let hv = self
.controller
let hv = c
.phy
.read(super::super::Register::new(0, 26)?)?;
.read_steps(super::super::Register::new(0, 26)?)
.await?;
if hv & 0x1040 != 0x1040 || u32::from((hv & 0x300) >> 8) != (status & SPEED_MASK) >> 6 {
self.link = None;
return Ok(false);
return Ok((None, false));
}
if hv & 0x300 != 0 {
self.controller.modify(770, 17, 1 << 14, 0)?;
c.modify_steps(770, 17, 1 << 14, 0).await?;
} else {
self.modify_mac(FEXTNVM4, 7, 3)?;
Self::modify_in(c, FEXTNVM4, 7, 3)?;
}
self.controller.modify(
c.modify_steps(
770,
16,
0x7000,
if status & FULL_DUPLEX == 0 { 0x1000 } else { 0 },
)?;
self.modify_mac(super::TCTL, 0x3ff << 12, 63 << 12)?;
self.modify_mac(super::CTRL, PAUSE, 0)?;
self.link = Some(status);
Ok(true)
)
.await?;
Self::modify_in(c, super::TCTL, 0x3ff << 12, 63 << 12)?;
Self::modify_in(c, super::CTRL, PAUSE, 0)?;
Ok((Some(status), true))
}
fn offer(&mut self, index: usize) {
let base = index * DESCRIPTOR;
@@ -647,6 +765,7 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
if self.stopped {
return Ok(());
}
self.settle(SETTLE_STEPS)?;
self.check()?;
let result = (|| {
self.controller.write(super::IMC, u32::MAX)?;
@@ -693,8 +812,16 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Ethernet<R, D> {
LinkError::Adapter(format!("PCH: {error}"))
}
}
impl<R: Registers + nvm::Registers, D: Delay + Clone> Drop for Ethernet<R, D> {
impl<R: Registers + nvm::Registers, D: Delay + Clone + 'static> Drop for Ethernet<R, D> {
fn drop(&mut self) {
if self.settle(SETTLE_STEPS).is_err()
&& let Some(change) = self.change.take()
{
// The PHY is mid-operation, perhaps holding its semaphore:
// keep the controller owner it holds, as a poisoned PHY does.
core::mem::forget(change);
return;
}
if !self.stopped && !self.controller.is_poisoned() {
let _ = self.shutdown();
}
@@ -702,9 +829,9 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Drop for Ethernet<R, D> {
// DMA RAM is independently boot-lifetime, including after uncertainty.
}
}
impl<R: Registers + nvm::Registers, D: Delay + Clone> Link for Ethernet<R, D> {
impl<R: Registers + nvm::Registers, D: Delay + Clone + 'static> Link for Ethernet<R, D> {
fn mac(&self) -> Mac {
self.controller.station
self.station
}
fn carrier(&mut self) -> bool {
match self.update_link() {
@@ -759,6 +886,10 @@ impl<R: Registers + nvm::Registers, D: Delay + Clone> Link for Ethernet<R, D> {
fn receive_reusing(&mut self, frame: &mut Vec<u8>) -> Result<bool, LinkError> {
self.check().map_err(|e| self.error(e))?;
self.update_link().map_err(|e| self.error(e))?;
if self.change.is_some() {
// The link change holds the controller, and with it RDT.
return Ok(false);
}
for _ in 0..DESCRIPTORS {
let index = self.next_rx;
let base = index * DESCRIPTOR;
@@ -353,6 +353,144 @@ fn link_reconnect_and_speed_changes_apply_82579_workarounds() {
assert!(net.carrier());
assert!(!net.controller.is_poisoned());
}
/// Drive a link change through carrier, transmit and receive calls in
/// turn until it completes, checking that no call waits more than 60 ms of
/// model time and that, while it runs, the link is down and neither ring
/// moves. Returns the calls taken.
fn step_link_change(net: &mut Net, state: &Rc<RefCell<Model>>) -> usize {
let mut calls = 0;
loop {
let before = state.borrow().time;
let tails = (
state.borrow().mac.get(&TDT).copied(),
state.borrow().mac.get(&RDT).copied(),
);
match calls % 3 {
0 => {
let up = net.carrier();
assert_eq!(up, net.change.is_none());
}
1 => {
let sent = net.transmit(&[0x5a; 60]);
if net.change.is_some() {
assert_eq!(sent, Err(LinkError::NoCarrier));
}
}
_ => {
let received = net.receive();
if net.change.is_some() {
assert_eq!(received, Ok(None));
}
}
}
calls += 1;
let waited = state.borrow().time - before;
assert!(waited <= 60_000, "call {calls} waited {waited} us");
if net.change.is_none() {
return calls;
}
assert_eq!(
(
state.borrow().mac.get(&TDT).copied(),
state.borrow().mac.get(&RDT).copied()
),
tails
);
}
}
/// A link change waits on the PHY semaphore the Intel ME holds and on a
/// slow management bus a step at a time, as Linux sleeps in
/// `e1000_acquire_swflag_ich8lan` and `e1000e_read_phy_reg_mdic`: no call
/// waits more than 60 ms, and the change ends with the same PHY, EMI and
/// MAC registers as one that never waited.
#[test]
fn a_link_change_waits_in_steps_and_ends_as_an_uncontended_one() {
let run = |contended: bool| {
let mut memory = Memory::new();
let (state, _released, controller) = setup_lpt(0x15a0, 0);
let mut net = open(controller, &mut memory);
assert!(net.carrier());
let start = {
let mut m = state.borrow_mut();
m.mac
.insert(super::super::STATUS, LINK_UP | FULL_DUPLEX | (1 << 6));
if contended {
m.firmware_flag_until = m.time + 90_000;
m.mdic_cycle_us = 30_000;
}
m.time
};
let calls = step_link_change(&mut net, &state);
assert!(net.carrier());
assert_eq!(net.failure(), None);
assert!(!net.controller.is_poisoned());
let m = state.borrow();
// The call that completes the change may then send or offer, and
// each run has its own ring memory.
let mut mac = m.mac.clone();
for at in [TDT, RDT, TDBAL, RDBAL] {
mac.remove(&at);
}
(calls, m.time - start, m.phy.clone(), m.emi.clone(), mac)
};
let (calls, waited, phy, emi, mac) = run(true);
let (quick, _, unwaited_phy, unwaited_emi, unwaited_mac) = run(false);
assert_eq!(quick, 1);
assert!(waited > 500_000, "{waited}");
assert!(calls > 10, "{calls}");
assert_eq!(phy, unwaited_phy);
assert_eq!(emi, unwaited_emi);
assert_eq!(mac, unwaited_mac);
}
/// A semaphore the Intel ME never gives back fails the link change after
/// Linux's 100 ms, a step at a time, and keeps the owner; a stop or drop
/// gives a change under way on a slow management bus two steps, then keeps
/// the controller it holds.
#[test]
fn a_link_change_on_a_held_semaphore_fails_in_steps_and_a_drop_keeps_the_owner() {
let mut memory = Memory::new();
let (state, _released, controller) = setup_lpt(0x15a0, 0);
let mut net = open(controller, &mut memory);
assert!(net.carrier());
{
let mut m = state.borrow_mut();
m.mac.insert(super::super::STATUS, LINK_UP | FULL_DUPLEX);
m.firmware_flag_until = u64::MAX;
}
let mut calls = 0;
while net.failure().is_none() {
let before = state.borrow().time;
assert!(!net.carrier());
assert!(state.borrow().time - before <= 60_000);
calls += 1;
}
assert!(calls >= 3);
assert!(matches!(
net.failure(),
Some(Error::Phy(super::super::super::Error {
primary: super::super::Fault::SemaphoreBusy,
..
}))
));
assert!(net.controller.is_poisoned());
assert!(net.transmit(&[1; 60]).is_err());
let (state, released, controller) = setup_lpt(0x15a0, 0);
let mut net = open(controller, &mut memory);
assert!(net.carrier());
{
let mut m = state.borrow_mut();
m.mac.insert(super::super::STATUS, LINK_UP | FULL_DUPLEX);
m.mdic_cycle_us = 30_000;
}
assert!(!net.carrier());
assert!(net.change.is_some());
assert_eq!(net.shutdown(), Err(Error::LinkChangeUnfinished));
let before = state.borrow().time;
drop(net);
assert!(state.borrow().time - before <= 100_000);
assert_eq!(released.load(Ordering::SeqCst), 0);
}
/// A full ring refuses the frame as busy at once, without waiting, and
/// overwrites no descriptor the controller still holds; the adapter stays
/// usable, as Linux's `NETDEV_TX_BUSY` leaves it.
@@ -40,6 +40,11 @@ pub(super) struct Model {
pub(super) flash_control: u16,
pub(super) time: u64,
pub(super) quiet_until: u64,
/// The Intel ME holds the PHY semaphore until this model time.
pub(super) firmware_flag_until: u64,
/// Each MDIO cycle takes this long before MDIC reports it ready.
pub(super) mdic_cycle_us: u64,
pub(super) mdic_ready_at: u64,
pub(super) master_busy: usize,
pub(super) mdic_failures: usize,
/// The MDIC attempt the `mdic_failures` window starts at.
@@ -104,6 +109,9 @@ impl Model {
flash_control: 0,
time: 0,
quiet_until: 0,
firmware_flag_until: 0,
mdic_cycle_us: 0,
mdic_ready_at: 0,
master_busy: 0,
mdic_failures: 0,
mdic_fail_after: 0,
@@ -177,6 +185,12 @@ unsafe impl Registers for Io {
let mut m = self.0.borrow_mut();
m.enter()?;
let mut value = m.mac.get(&at).copied().unwrap_or(0);
if at == super::super::EXTCNF_CTRL && m.time < m.firmware_flag_until {
value |= super::super::SWFLAG;
}
if at == super::super::MDIC && m.time < m.mdic_ready_at {
value &= !super::super::MDIC_READY;
}
if at == STATUS && m.master_busy != 0 {
m.master_busy -= 1;
value |= MASTER_ENABLED;
@@ -272,6 +286,7 @@ unsafe impl Registers for Io {
smb && m.smb_hidden && m.mac.get(&0x18).copied().unwrap_or(0) & (1 << 11) == 0;
m.phy_load(address, index)
};
m.mdic_ready_at = m.time + m.mdic_cycle_us;
let failed =
(m.mdic_fail_after..m.mdic_fail_after + m.mdic_failures).contains(&m.mdic_attempts);
m.mdic_attempts += 1;