Skip to main content

e1000/
lib.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23#![no_std]
24
25use core::ptr;
26use intel_ethernet::{
27    ctrl, eerd, int_bits, rctl, regs, rx_errors, rx_status, tctl, tx_status, LegacyRxDesc,
28    LegacyTxDesc,
29};
30use net_core::NetError;
31use nic_buffers::{DmaAllocator, DmaRegion};
32use nic_queues::{RxDescriptor, RxRing, TxDescriptor, TxRing};
33
34pub const NUM_RX: usize = 128;
35pub const NUM_TX: usize = 128;
36pub const RX_BUF_SIZE: usize = 4096;
37/// Update the RX tail in batches instead of once per packet.
38const RX_REFILL_BATCH: usize = 8;
39
40const RESET_MAX_POLLS: u32 = 200_000;
41const EEPROM_MAX_POLLS: u32 = 50_000;
42
43/// Watchdog timeout in successful TX completions. If no TX completes
44/// within this many transmit attempts the link is considered stalled.
45const WATCHDOG_TX_THRESHOLD: u64 = 10_000;
46
47pub const E1000_DEVICE_IDS: &[u16] = &[0x100E, 0x100F, 0x10D3, 0x153A, 0x1539];
48pub const INTEL_VENDOR: u16 = 0x8086;
49
50/// Hardware statistics maintained by the driver.
51pub struct E1000Stats {
52    pub rx_ok: u64,
53    pub rx_errors: u64,
54    pub rx_crc_errors: u64,
55    pub rx_length_errors: u64,
56    pub tx_ok: u64,
57    pub tx_errors: u64,
58    pub tx_dropped: u64,
59    pub tx_late_collision: u64,
60    pub tx_underrun: u64,
61    pub watchdog_resets: u64,
62}
63
64impl E1000Stats {
65    const fn new() -> Self {
66        Self {
67            rx_ok: 0,
68            rx_errors: 0,
69            rx_crc_errors: 0,
70            rx_length_errors: 0,
71            tx_ok: 0,
72            tx_errors: 0,
73            tx_dropped: 0,
74            tx_late_collision: 0,
75            tx_underrun: 0,
76            watchdog_resets: 0,
77        }
78    }
79}
80
81pub struct E1000Nic {
82    mmio: u64,
83    rx: RxRing<LegacyRxDesc>,
84    rx_bufs: [DmaRegion; NUM_RX],
85    rx_ring_phys: u64,
86    tx: TxRing<LegacyTxDesc>,
87    tx_bufs: [DmaRegion; NUM_TX],
88    tx_ring_phys: u64,
89    mac: [u8; 6],
90    link_up: bool,
91    stats: E1000Stats,
92    tx_since_last_reclaim: u64,
93    /// Last known TDH value for watchdog stall detection.
94    last_tdh: usize,
95    /// Number of RX descriptors recycled since the last RDT write.
96    rx_refill: usize,
97}
98
99// SAFETY: E1000Nic owns its MMIO region and DMA buffers. It is safe to send
100// across threads as long as only one thread accesses the hardware at a time.
101unsafe impl Send for E1000Nic {}
102
103#[inline]
104unsafe fn rd(base: u64, reg: usize) -> u32 {
105    ptr::read_volatile((base + reg as u64) as *const u32)
106}
107
108#[inline]
109unsafe fn wr(base: u64, reg: usize, val: u32) {
110    ptr::write_volatile((base + reg as u64) as *mut u32, val)
111}
112
113impl E1000Nic {
114    pub fn init(mmio_base: u64, alloc: &dyn DmaAllocator) -> Result<Self, NetError> {
115        unsafe {
116            // --- Reset ---
117            let c = rd(mmio_base, regs::CTRL);
118            log::trace!("e1000: assert CTRL.RST (ctrl={:#x})", c);
119            wr(mmio_base, regs::CTRL, c | ctrl::RST);
120            let mut reset_done = false;
121            for poll in 0..RESET_MAX_POLLS {
122                let ctrl = rd(mmio_base, regs::CTRL);
123                if ctrl & ctrl::RST == 0 {
124                    log::trace!(
125                        "e1000: reset complete after {} polls (ctrl={:#x})",
126                        poll + 1,
127                        ctrl
128                    );
129                    reset_done = true;
130                    break;
131                }
132                core::hint::spin_loop();
133            }
134            if !reset_done {
135                log::warn!(
136                    "e1000: reset timeout after {} CTRL polls (RST never cleared)",
137                    RESET_MAX_POLLS
138                );
139                return Err(NetError::NotReady);
140            }
141
142            // Disable interrupts during setup
143            wr(mmio_base, regs::IMC, 0xFFFF_FFFF);
144            let _ = rd(mmio_base, regs::ICR);
145
146            // --- MAC address ---
147            log::trace!("e1000: read MAC");
148            let mac = Self::read_mac(mmio_base)?;
149            log::trace!(
150                "e1000: MAC {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
151                mac[0],
152                mac[1],
153                mac[2],
154                mac[3],
155                mac[4],
156                mac[5]
157            );
158
159            // Program the unicast receive filter explicitly. A software reset
160            // (CTRL.RST above) does not reliably reload RAL0/RAH0 from the NVM
161            // on real PCH/LOM parts (I217/I218/I219, e1000e); only QEMU's 82540
162            // does. Left empty, the Address-Valid bit stays 0, so the NIC honours
163            // only RCTL.BAM (broadcast): DHCP succeeds while every unicast frame
164            // (ARP replies, ICMP echo, TCP) is silently dropped and the host is
165            // unreachable. Writing the station MAC with AV set fixes bare metal.
166            const RAH_AV: u32 = 1 << 31; // Address Valid
167            let ral = u32::from(mac[0])
168                | (u32::from(mac[1]) << 8)
169                | (u32::from(mac[2]) << 16)
170                | (u32::from(mac[3]) << 24);
171            let rah = u32::from(mac[4]) | (u32::from(mac[5]) << 8) | RAH_AV;
172            wr(mmio_base, regs::RAL0, ral);
173            wr(mmio_base, regs::RAH0, rah);
174
175            // NOTE: VET (0x0008) and VFTA (0x5200+) writes are intentionally
176            // skipped. On the 82540EM, offset 0x0008 is the read-only STATUS
177            // register : writing VET there triggers a VERIFY assertion in
178            // VMware's e1000 emulation. The VFTA loop writes 128 entries to
179            // register space that VMware's 82540EM model does not implement.
180            // These are cosmetic (802.1Q is not used) so they are safe to omit.
181            // TODO: re-enable with per-hypervisor detection when VLAN support
182            // is needed.
183
184            // --- RX ring ---
185            let rx_ring_region = alloc
186                .alloc_dma(NUM_RX * core::mem::size_of::<LegacyRxDesc>())
187                .map_err(|_| NetError::NotReady)?;
188            ptr::write_bytes(rx_ring_region.virt, 0, rx_ring_region.size);
189            let rx_descs = rx_ring_region.virt as *mut LegacyRxDesc;
190
191            let mut rx_bufs = [DmaRegion::ZERO; NUM_RX];
192            for rx_buf in rx_bufs.iter_mut().take(NUM_RX) {
193                let buf = alloc
194                    .alloc_dma(RX_BUF_SIZE)
195                    .map_err(|_| NetError::NotReady)?;
196                ptr::write_bytes(buf.virt, 0, RX_BUF_SIZE);
197                *rx_buf = buf;
198            }
199
200            wr(mmio_base, regs::RDBAL, rx_ring_region.device_addr() as u32);
201            wr(
202                mmio_base,
203                regs::RDBAH,
204                (rx_ring_region.device_addr() >> 32) as u32,
205            );
206            wr(mmio_base, regs::RDLEN, rx_ring_region.size as u32);
207            wr(mmio_base, regs::RDH, 0);
208            wr(mmio_base, regs::RDT, (NUM_RX - 1) as u32);
209
210            for (i, buf) in rx_bufs.iter().enumerate().take(NUM_RX) {
211                (*rx_descs.add(i)).addr = buf.device_addr();
212            }
213
214            // --- TX ring ---
215            let tx_ring_region = alloc
216                .alloc_dma(NUM_TX * core::mem::size_of::<LegacyTxDesc>())
217                .map_err(|_| NetError::NotReady)?;
218            ptr::write_bytes(tx_ring_region.virt, 0, tx_ring_region.size);
219            let tx_descs = tx_ring_region.virt as *mut LegacyTxDesc;
220
221            wr(mmio_base, regs::TDBAL, tx_ring_region.device_addr() as u32);
222            wr(
223                mmio_base,
224                regs::TDBAH,
225                (tx_ring_region.device_addr() >> 32) as u32,
226            );
227            wr(mmio_base, regs::TDLEN, tx_ring_region.size as u32);
228            wr(mmio_base, regs::TDH, 0);
229            wr(mmio_base, regs::TDT, 0);
230
231            // Pre-allocate TX buffer pool (avoid per-packet DMA alloc).
232            let mut tx_bufs = [DmaRegion::ZERO; NUM_TX];
233            for tx_buf in tx_bufs.iter_mut().take(NUM_TX) {
234                let buf = alloc
235                    .alloc_dma(net_core::MTU)
236                    .map_err(|_| NetError::NotReady)?;
237                ptr::write_bytes(buf.virt, 0, net_core::MTU);
238                *tx_buf = buf;
239            }
240
241            // Enable TX
242            wr(
243                mmio_base,
244                regs::TCTL,
245                tctl::EN | tctl::PSP | (0x10 << tctl::CT_SHIFT) | (0x40 << tctl::COLD_SHIFT),
246            );
247
248            // --- RX control: BSIZE_4096 (BSEX=1, BSIZE=10 => 4096 bytes) ---
249            // RX_BUF_SIZE is 4096; the hardware must match.
250            wr(
251                mmio_base,
252                regs::RCTL,
253                rctl::EN | rctl::BAM | rctl::BSIZE_4096 | rctl::SECRC,
254            );
255
256            // --- Link up + interrupts ---
257            let c = rd(mmio_base, regs::CTRL);
258            wr(mmio_base, regs::CTRL, c | ctrl::SLU);
259
260            // --- Interrupt coalescing ---
261            // ITR    = 1950 =>  approx. 2000 irq/s max (1950 × 256 ns ≈ 500 µs between IRQs).
262            // RDTR   = 0 => fire interrupt after first packet (baseline)
263            // RADV   = 128 => absolute timer: force an interrupt after 128 µs even
264            //                if no new packets arrive (keeps latency bounded).
265            // TIDV   = 0 => transmit: fire on first descriptor writeback
266            // TADV   = 64 => absolute timer: flush TX interrupts after 64 µs.
267            //
268            // ITR uses 256 ns units on 8254x; on e1000e/I210 the same register
269            // uses 1024 ns units : the value still provides adequate coalescing.
270            //
271            // 488 × 256 ns ≈ 125 µs => approx 8 000 irq/s max.  Low enough to keep the
272            // CPU from being swamped under heavy load, high enough for interactive
273            // responsiveness (sub-ms ping).
274            wr(mmio_base, regs::ITR, 488);
275            wr(mmio_base, regs::RDTR, 0);
276            wr(mmio_base, regs::RADV, 128);
277            wr(mmio_base, regs::TIDV, 0);
278            wr(mmio_base, regs::TADV, 64);
279
280            wr(
281                mmio_base,
282                regs::IMS,
283                int_bits::RXT0
284                    | int_bits::LSC
285                    | int_bits::RXDMT0
286                    | int_bits::RXO
287                    | int_bits::TXDW
288                    | int_bits::TXQE,
289            );
290            let status = rd(mmio_base, regs::STATUS);
291            let link_up = (status & 0x02) != 0;
292
293            Ok(Self {
294                mmio: mmio_base,
295                rx: RxRing::new(rx_descs, NUM_RX),
296                rx_bufs,
297                rx_ring_phys: rx_ring_region.device_addr(),
298                tx: TxRing::new(tx_descs, NUM_TX),
299                tx_bufs,
300                tx_ring_phys: tx_ring_region.device_addr(),
301                mac,
302                link_up,
303                stats: E1000Stats::new(),
304                tx_since_last_reclaim: 0,
305                last_tdh: 0,
306                rx_refill: 0,
307            })
308        }
309    }
310
311    pub fn mac_address(&self) -> [u8; 6] {
312        self.mac
313    }
314
315    pub fn link_up(&self) -> bool {
316        self.link_up
317    }
318
319    pub fn check_link(&mut self) -> bool {
320        unsafe {
321            let status = rd(self.mmio, regs::STATUS);
322            self.link_up = (status & 0x02) != 0;
323        }
324        self.link_up
325    }
326
327    pub fn stats(&self) -> &E1000Stats {
328        &self.stats
329    }
330
331    /// Recycle an RX descriptor: clear status, restore buffer address, and
332    /// periodically publish the new tail.  Writing RDT on every packet is a
333    /// costly MMIO round trip; batching keeps the ring full without stalling
334    /// the device (128 descriptors, batch of 8).
335    fn recycle_rx_desc(&mut self, idx: usize) {
336        self.rx.desc_mut(idx).clear_status();
337        self.rx
338            .desc_mut(idx)
339            .set_buffer_addr(self.rx_bufs[idx].device_addr());
340        let new_tail = self.rx.advance();
341        self.rx_refill += 1;
342        if self.rx_refill >= RX_REFILL_BATCH || new_tail == 0 {
343            self.rx_refill = 0;
344            unsafe {
345                wr(self.mmio, regs::RDT, new_tail as u32);
346            }
347        }
348    }
349
350    pub fn receive(&mut self, buf: &mut [u8]) -> Result<usize, NetError> {
351        if !self.link_up {
352            return Err(NetError::LinkDown);
353        }
354
355        let (idx, pkt_len) = self.rx.poll().ok_or(NetError::NoPacket)?;
356
357        // --- RX error checking ---
358        let err = self.rx.desc(idx).errors;
359        let st = self.rx.desc(idx).status;
360
361        if (err & rx_errors::CE) != 0 {
362            log::warn!("e1000: RX CRC error on descriptor {}", idx);
363            self.recycle_rx_desc(idx);
364            self.stats.rx_crc_errors += 1;
365            self.stats.rx_errors += 1;
366            return Err(NetError::NoPacket);
367        }
368        if (err & rx_errors::SE) != 0 {
369            log::warn!("e1000: RX symbol error on descriptor {}", idx);
370            self.recycle_rx_desc(idx);
371            self.stats.rx_errors += 1;
372            return Err(NetError::NoPacket);
373        }
374        if (err & rx_errors::TCPE) != 0 {
375            log::trace!("e1000: RX TCP/UDP checksum error on descriptor {}", idx);
376            self.recycle_rx_desc(idx);
377            self.stats.rx_errors += 1;
378            return Err(NetError::NoPacket);
379        }
380        if (err & rx_errors::IPE) != 0 {
381            log::trace!("e1000: RX IP checksum error on descriptor {}", idx);
382            self.recycle_rx_desc(idx);
383            self.stats.rx_errors += 1;
384            return Err(NetError::NoPacket);
385        }
386        if (st & rx_status::EOP) == 0 {
387            log::warn!(
388                "e1000: RX descriptor {} missing EOP : fragment dropped",
389                idx
390            );
391            self.recycle_rx_desc(idx);
392            self.stats.rx_length_errors += 1;
393            self.stats.rx_errors += 1;
394            return Err(NetError::NoPacket);
395        }
396
397        // pkt_len comes from the DMA descriptor, i.e. from the device.
398        // A buggy or hostile device reporting a length larger than the RX
399        // buffer would make the copy below read past the DMA allocation
400        // (heap info-leak). Clamp to what was actually allocated.
401        let len = (pkt_len as usize).min(RX_BUF_SIZE);
402        if buf.len() < len {
403            self.recycle_rx_desc(idx);
404            return Err(NetError::BufferTooSmall);
405        }
406
407        unsafe {
408            ptr::copy_nonoverlapping(self.rx_bufs[idx].virt, buf.as_mut_ptr(), len);
409        }
410
411        self.recycle_rx_desc(idx);
412        self.stats.rx_ok += 1;
413        Ok(len)
414    }
415
416    pub fn transmit(&mut self, buf: &[u8]) -> Result<(), NetError> {
417        if !self.link_up {
418            return Err(NetError::LinkDown);
419        }
420
421        if buf.len() > net_core::MTU {
422            return Err(NetError::BufferTooSmall);
423        }
424
425        let idx = self.tx.tail();
426
427        // Reclaim completed TX buffers before checking fullness.
428        self.reclaim_completed_tx_buffers();
429
430        // Check if slot is still busy after reclaim.
431        if self.tx.desc(idx).cmd != 0 && !self.tx.is_done(idx) {
432            self.stats.tx_dropped += 1;
433            return Err(NetError::TxQueueFull);
434        }
435
436        // Copy into the pre-allocated TX buffer pool slot.
437        unsafe {
438            ptr::copy_nonoverlapping(buf.as_ptr(), self.tx_bufs[idx].virt, buf.len());
439        }
440
441        let _submitted = self
442            .tx
443            .submit(self.tx_bufs[idx].device_addr(), buf.len() as u16);
444        unsafe {
445            wr(self.mmio, regs::TDT, self.tx.tail() as u32);
446        }
447
448        self.tx_since_last_reclaim += 1;
449        self.stats.tx_ok += 1;
450        Ok(())
451    }
452
453    /// Reclaim TX descriptors that the hardware has completed (DD bit set).
454    /// No per-packet DMA free is needed because the buffer pool is
455    /// pre-allocated; we only reset the descriptor for reuse.
456    fn reclaim_completed_tx_buffers(&mut self) {
457        // Scan all slots that might be in-flight.
458        let head = unsafe { rd(self.mmio, regs::TDH) } as usize % NUM_TX;
459        let tail = self.tx.tail();
460
461        let mut idx = head;
462        while idx != tail {
463            if self.tx.is_done(idx) {
464                let st = self.tx.desc(idx).status;
465                if (st & tx_status::LC) != 0 {
466                    log::warn!("e1000: TX late collision at descriptor {}", idx);
467                    self.stats.tx_late_collision += 1;
468                    self.stats.tx_errors += 1;
469                }
470                if (st & tx_status::TU) != 0 {
471                    log::warn!("e1000: TX underrun at descriptor {}", idx);
472                    self.stats.tx_underrun += 1;
473                    self.stats.tx_errors += 1;
474                }
475                // Reset the descriptor for reuse.
476                self.tx.desc_mut(idx).clear();
477            }
478            idx = (idx + 1) % NUM_TX;
479        }
480        self.tx_since_last_reclaim = 0;
481    }
482
483    /// Non-blocking: check if the last submitted TX has completed.
484    pub fn is_transmit_complete(&self) -> bool {
485        let idx = self.tx.tail();
486        self.tx.is_done(idx)
487    }
488
489    /// Blocking spin until the last TX completes.
490    pub fn wait_for_transmit(&self) {
491        while !self.is_transmit_complete() {
492            core::hint::spin_loop();
493        }
494    }
495
496    pub fn tx_is_done(&self, idx: usize) -> bool {
497        self.tx.is_done(idx % NUM_TX)
498    }
499
500    /// Process a hardware interrupt.  Returns the raw ICR value so the
501    /// kernel adapter can decide what to do (e.g. wake a receive task).
502    pub fn handle_interrupt(&mut self) -> u32 {
503        let icr = unsafe { rd(self.mmio, regs::ICR) };
504
505        if (icr & int_bits::LSC) != 0 {
506            let status = unsafe { rd(self.mmio, regs::STATUS) };
507            let was_up = self.link_up;
508            self.link_up = (status & 0x02) != 0;
509            if was_up != self.link_up {
510                log::info!("e1000: link {}", if self.link_up { "up" } else { "down" });
511            }
512        }
513
514        if (icr & (int_bits::RXT0 | int_bits::RXDMT0 | int_bits::RXO)) != 0 {
515            log::trace!("e1000: RX interrupt (icr={:#x})", icr);
516        }
517
518        if (icr & int_bits::TXDW) != 0 {
519            self.reclaim_completed_tx_buffers();
520            log::trace!("e1000: TX descriptor writeback");
521        }
522
523        if (icr & int_bits::TXQE) != 0 {
524            log::trace!("e1000: TX queue empty");
525        }
526
527        if (icr & int_bits::RXO) != 0 {
528            log::warn!("e1000: RX overflow : descriptor ring full");
529        }
530
531        icr
532    }
533
534    /// Watchdog check: called periodically (e.g. from timer IRQ) to detect
535    /// and recover from a stalled link.  Returns `true` if a reset was
536    /// performed.
537    ///
538    /// Stall detection logic:
539    ///   - If `tx_since_last_reclaim` exceeds `WATCHDOG_TX_THRESHOLD` the
540    ///     software has been submitting without any reclaim happening.
541    ///   - If TDH (hardware head) == `last_tdh` => the hardware has not
542    ///     advanced => stall => reset.
543    ///   - If TDH advanced => update `last_tdh` and reset counter (progress).
544    ///   - If TDH == tail (ring empty) => normal idle => reset counter.
545    pub fn watchdog_tick(&mut self, alloc: &dyn DmaAllocator) -> bool {
546        if self.tx_since_last_reclaim < WATCHDOG_TX_THRESHOLD {
547            return false;
548        }
549
550        let tdh = unsafe { rd(self.mmio, regs::TDH) } as usize;
551        let tail = self.tx.tail();
552
553        if tdh != tail {
554            // Descriptors are in-flight : check if head has moved.
555            if tdh == self.last_tdh {
556                log::warn!(
557                    "e1000: watchdog : TX stalled (TDH={} TDT={} last_tdh={}), resetting",
558                    tdh,
559                    tail,
560                    self.last_tdh
561                );
562                self.reinit_hardware(alloc);
563                self.stats.watchdog_resets += 1;
564                return true;
565            }
566            // Head advanced: record new position, reset counter.
567            self.last_tdh = tdh;
568            self.tx_since_last_reclaim = 0;
569        } else {
570            // Ring empty : normal idle.
571            self.tx_since_last_reclaim = 0;
572        }
573        false
574    }
575
576    /// Stop RX/TX and mask interrupts.  Safe to call before reset/hot-unplug.
577    pub fn quiesce(&mut self) {
578        unsafe {
579            wr(self.mmio, regs::IMC, 0xFFFF_FFFF);
580            let _ = rd(self.mmio, regs::ICR);
581            wr(self.mmio, regs::RCTL, 0);
582            wr(self.mmio, regs::TCTL, 0);
583        }
584        self.link_up = false;
585    }
586
587    /// Reset the controller and re-point the existing rings.
588    pub fn reset(&mut self, alloc: &dyn DmaAllocator) {
589        self.reinit_hardware(alloc);
590    }
591
592    /// Re-initialise hardware without tearing down the DMA rings.  Used by
593    /// the watchdog and by the hotplug resume path.
594    pub fn reinit_hardware(&mut self, _alloc: &dyn DmaAllocator) {
595        unsafe {
596            // Mask all interrupts while we re-init.
597            wr(self.mmio, regs::IMC, 0xFFFF_FFFF);
598            let _ = rd(self.mmio, regs::ICR);
599
600            // Soft-reset the controller.
601            let c = rd(self.mmio, regs::CTRL);
602            wr(self.mmio, regs::CTRL, c | ctrl::RST);
603            for _ in 0..RESET_MAX_POLLS {
604                if rd(self.mmio, regs::CTRL) & ctrl::RST == 0 {
605                    break;
606                }
607                core::hint::spin_loop();
608            }
609
610            // Re-point the rings using the stored physical addresses.
611            wr(self.mmio, regs::RDBAL, self.rx_ring_phys as u32);
612            wr(self.mmio, regs::RDBAH, (self.rx_ring_phys >> 32) as u32);
613            wr(
614                self.mmio,
615                regs::RDLEN,
616                (NUM_RX * core::mem::size_of::<LegacyRxDesc>()) as u32,
617            );
618            wr(self.mmio, regs::RDH, 0);
619            wr(self.mmio, regs::RDT, (NUM_RX - 1) as u32);
620
621            wr(self.mmio, regs::TDBAL, self.tx_ring_phys as u32);
622            wr(self.mmio, regs::TDBAH, (self.tx_ring_phys >> 32) as u32);
623            wr(
624                self.mmio,
625                regs::TDLEN,
626                (NUM_TX * core::mem::size_of::<LegacyTxDesc>()) as u32,
627            );
628            wr(self.mmio, regs::TDH, 0);
629            wr(self.mmio, regs::TDT, 0);
630
631            // Re-enable interrupts.
632            wr(
633                self.mmio,
634                regs::IMS,
635                int_bits::RXT0
636                    | int_bits::LSC
637                    | int_bits::RXDMT0
638                    | int_bits::RXO
639                    | int_bits::TXDW
640                    | int_bits::TXQE,
641            );
642
643            // Force link up.
644            let c = rd(self.mmio, regs::CTRL);
645            wr(self.mmio, regs::CTRL, c | ctrl::SLU);
646
647            // Reconfigure RX: BSIZE_4096.
648            wr(
649                self.mmio,
650                regs::RCTL,
651                rctl::EN | rctl::BAM | rctl::BSIZE_4096 | rctl::SECRC,
652            );
653
654            // Reconfigure TX.
655            wr(
656                self.mmio,
657                regs::TCTL,
658                tctl::EN | tctl::PSP | (0x10 << tctl::CT_SHIFT) | (0x40 << tctl::COLD_SHIFT),
659            );
660
661            // Reconfigure interrupt coalescing.
662            wr(self.mmio, regs::ITR, 488);
663            wr(self.mmio, regs::RDTR, 0);
664            wr(self.mmio, regs::RADV, 128);
665            wr(self.mmio, regs::TIDV, 0);
666            wr(self.mmio, regs::TADV, 64);
667        }
668
669        self.tx_since_last_reclaim = 0;
670        self.last_tdh = 0;
671        self.rx_refill = 0;
672        self.check_link();
673    }
674
675    unsafe fn read_mac(base: u64) -> Result<[u8; 6], NetError> {
676        let ral = rd(base, regs::RAL0);
677        let rah = rd(base, regs::RAH0);
678        log::trace!("e1000: RAL0={:#x} RAH0={:#x}", ral, rah);
679
680        if ral != 0 || rah != 0 {
681            return Ok([
682                (ral) as u8,
683                (ral >> 8) as u8,
684                (ral >> 16) as u8,
685                (ral >> 24) as u8,
686                (rah) as u8,
687                (rah >> 8) as u8,
688            ]);
689        }
690
691        log::trace!("e1000: RAL/RAH empty : reading MAC words from EEPROM");
692        let mut mac = [0u8; 6];
693        for i in 0u32..3 {
694            let w = Self::eeprom_read(base, i as u8)?;
695            mac[(i * 2) as usize] = w as u8;
696            mac[(i * 2 + 1) as usize] = (w >> 8) as u8;
697        }
698        if mac == [0; 6] || mac == [0xFF; 6] {
699            return Err(NetError::NotReady);
700        }
701        Ok(mac)
702    }
703
704    unsafe fn eeprom_read(base: u64, addr: u8) -> Result<u16, NetError> {
705        log::trace!("e1000: EEPROM read addr={}", addr);
706        wr(
707            base,
708            regs::EERD,
709            eerd::START | ((addr as u32) << eerd::ADDR_SHIFT),
710        );
711        for poll in 0..EEPROM_MAX_POLLS {
712            let v = rd(base, regs::EERD);
713            if v & eerd::DONE != 0 {
714                let data = ((v >> eerd::DATA_SHIFT) & 0xFFFF) as u16;
715                log::trace!(
716                    "e1000: EEPROM addr={} ok after {} polls data={:#x}",
717                    addr,
718                    poll + 1,
719                    data
720                );
721                return Ok(data);
722            }
723            core::hint::spin_loop();
724        }
725        log::warn!(
726            "e1000: EEPROM addr={} timeout after {} EERD polls",
727            addr,
728            EEPROM_MAX_POLLS
729        );
730        Err(NetError::NotReady)
731    }
732}