ax-net 0.13.1

Unified network stack for TGOSKits (ArceOS, StarryOS, Axvisor)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
//! Ethernet device adapter.
//!
//! The adapter translates between the generic ax-net device contract and
//! Ethernet NIC drivers. It owns neighbor discovery state, emits Ethernet/ARP
//! frames and feeds IP packets into the router RX buffer. Hardware readiness is
//! owned below this adapter by fixed-CPU queue executors.
//!
//! # Responsibilities
//!
//! - Wrap complete IP packets in Ethernet frames for TX.
//! - Parse inbound Ethernet frames, update ARP state, and deliver IP payloads
//!   to the router's RX packet buffer.
//! - Buffer a bounded number of packets while ARP resolution for a next hop is
//!   pending.
//! - Consume and publish frames through the protocol-side SPSC port.
//!
//! # Non-Responsibilities
//!
//! The adapter does not decide which interface should be used for a destination
//! and does not inspect TCP/UDP socket state. Route selection is performed by
//! the router before Ethernet sees the packet.

use alloc::{boxed::Box, collections::VecDeque, string::String, vec, vec::Vec};

use hashbrown::HashMap;
use smoltcp::{
    storage::{PacketBuffer, PacketMetadata},
    time::{Duration, Instant},
    wire::{
        ArpOperation, ArpPacket, ArpRepr, EthernetAddress, EthernetFrame, EthernetProtocol,
        EthernetRepr, IpAddress, IpVersion, Ipv4Cidr,
    },
};

use crate::{
    config::InterfaceId,
    consts::{ETHERNET_MAX_PENDING_PACKETS, STANDARD_MTU},
    device::{
        ArpEntry, Device, DeviceRxPacket, DeviceRxPoll, ETH_ZLEN, EthernetFramePort,
        NetDeviceError, NetDeviceResult, ProtocolEthernetFrame, TxNotify, TxSubmitOptions,
    },
};

const EMPTY_MAC: EthernetAddress = EthernetAddress([0; 6]);
struct Neighbor {
    hardware_address: EthernetAddress,
    expires_at: Instant,
}

struct PendingNeighbor {
    requested_at: Instant,
}

pub struct EthernetDevice {
    name: String,
    inner: Box<dyn EthernetFramePort>,
    neighbors: HashMap<IpAddress, Neighbor>,
    pending_neighbors: HashMap<IpAddress, PendingNeighbor>,
    ip: Option<Ipv4Cidr>,

    pending_packets: PacketBuffer<'static, IpAddress>,
    /// Replies owned by the protocol executor until TX space is available.
    /// A full data queue must not prevent a peer from resolving our address.
    pending_arp_replies: VecDeque<(EthernetAddress, ArpRepr)>,
    /// Individual L2 frame lengths of packets transmitted on a side path
    /// during ARP resolution (inside `recv()`/`process_arp()`). Drained by
    /// the protocol executor via [`Device::drain_deferred_tx`].
    deferred_tx_frame_lens: Vec<usize>,
    /// Individual L2 frame lengths of non-IP frames (ARP) received during
    /// `recv()`. These frames are processed internally and never enqueued
    /// into the IP buffer, but must still count toward RX statistics.
    /// Drained by the protocol executor via [`Device::drain_deferred_rx`].
    deferred_rx_frame_lens: Vec<usize>,
    /// Count of TX errors accumulated during device operations (buffer
    /// allocation failures, transmit hardware errors). Drained by the
    /// protocol executor via [`Device::drain_deferred_tx_errors`].
    deferred_tx_errors: u64,
    /// Count of TX drops accumulated during device operations (pending
    /// buffer overflow, enqueue failure). Drained by the protocol executor
    /// via [`Device::drain_deferred_tx_drops`].
    deferred_tx_drops: u64,
    /// Count of RX errors accumulated during device operations (driver
    /// receive errors, malformed frames). Drained by the protocol executor
    /// via [`Device::drain_deferred_rx_errors`].
    deferred_rx_errors: u64,
    /// Count of RX drops accumulated during device operations (frames with
    /// unsupported EtherType that were successfully received at L2 but
    /// cannot be processed by the stack). Drained by the protocol executor
    /// via [`Device::drain_deferred_rx_drops`].
    deferred_rx_drops: u64,
}

impl EthernetDevice {
    /// Lifetime of a resolved unicast neighbour entry.  Linux uses 5 minutes
    /// for unicast neighbours; sticking to that value keeps long-running
    /// streams (e.g. a cold-start API response that takes >60 s to begin
    /// flowing) from invalidating the gateway entry mid-flow, which would
    /// otherwise force every queued ACK back into the ARP-pending buffer
    /// at once.
    const NEIGHBOR_TTL: Duration = Duration::from_secs(300);
    const ARP_REQUEST_RETRY: Duration = Duration::from_secs(1);

    /// Creates the protocol-side adapter for an IRQ-backed queue pipeline.
    pub fn new(name: String, inner: Box<dyn EthernetFramePort>, ip: Option<Ipv4Cidr>) -> Self {
        let pending_packets = PacketBuffer::new(
            vec![PacketMetadata::EMPTY; ETHERNET_MAX_PENDING_PACKETS],
            vec![
                0u8;
                (STANDARD_MTU + EthernetFrame::<&[u8]>::header_len())
                    * ETHERNET_MAX_PENDING_PACKETS
            ],
        );
        Self {
            name,
            inner,
            neighbors: HashMap::new(),
            pending_neighbors: HashMap::new(),
            ip,

            pending_packets,
            pending_arp_replies: VecDeque::new(),
            deferred_tx_frame_lens: Vec::new(),
            deferred_rx_frame_lens: Vec::new(),
            deferred_tx_errors: 0,
            deferred_tx_drops: 0,
            deferred_rx_errors: 0,
            deferred_rx_drops: 0,
        }
    }

    #[inline]
    fn hardware_address(&self) -> EthernetAddress {
        EthernetAddress(self.inner.mac_address())
    }

    fn transmit_ip_to(
        &mut self,
        destination: EthernetAddress,
        packet: &[u8],
    ) -> NetDeviceResult<usize> {
        if !self.flush_arp_replies() {
            return Err(NetDeviceError::Again);
        }
        let protocol = match IpVersion::of_packet(packet) {
            Ok(IpVersion::Ipv4) => EthernetProtocol::Ipv4,
            Ok(IpVersion::Ipv6) => EthernetProtocol::Ipv6,
            Err(_) => return Err(NetDeviceError::InvalidParam),
        };
        Self::send_to_with_options(
            &mut *self.inner,
            destination,
            packet.len(),
            |buffer| buffer.copy_from_slice(packet),
            protocol,
            TxNotify::Deferred,
        )
    }

    /// Builds an Ethernet frame around `size` bytes of payload written by `f`,
    /// emits it via `inner.transmit()`, and returns the total L2 frame length
    /// (including padding to [`ETH_ZLEN`], excluding FCS) on success.
    /// [`NetDeviceError::Again`] leaves ownership with the caller so it can
    /// retain and retry the packet after TX descriptors become available.
    fn send_to<F>(
        inner: &mut dyn EthernetFramePort,
        dst: EthernetAddress,
        size: usize,
        f: F,
        proto: EthernetProtocol,
    ) -> NetDeviceResult<usize>
    where
        F: FnOnce(&mut [u8]),
    {
        Self::send_to_with_options(inner, dst, size, f, proto, TxNotify::Immediate)
    }

    fn send_to_with_options<F>(
        inner: &mut dyn EthernetFramePort,
        dst: EthernetAddress,
        size: usize,
        f: F,
        proto: EthernetProtocol,
        notify: TxNotify,
    ) -> NetDeviceResult<usize>
    where
        F: FnOnce(&mut [u8]),
    {
        let repr = EthernetRepr {
            src_addr: EthernetAddress(inner.mac_address()),
            dst_addr: dst,
            ethertype: proto,
        };

        let total_frame_len = repr.buffer_len() + size;
        // Drivers pad short frames to ETH_ZLEN (60 bytes) in transmit(). The
        // returned length reflects the actual on-wire frame length excluding
        // FCS, aligned with Linux /proc/net/dev semantics.
        let wire_len = total_frame_len.max(ETH_ZLEN);

        let mut fill_once = Some(f);
        let mut fill = |packet: &mut [u8]| {
            let mut frame = EthernetFrame::new_unchecked(packet);
            repr.emit(&mut frame);
            fill_once
                .take()
                .expect("frame port must fill each packet exactly once")(
                frame.payload_mut()
            );
            trace!(
                "SEND {} bytes: {:02X?}",
                frame.as_ref().len(),
                frame.as_ref()
            );
        };
        inner.transmit_frame_with_options(
            total_frame_len,
            TxSubmitOptions {
                checksum: None,
                notify,
            },
            &mut fill,
        )?;
        Ok(wire_len)
    }

    fn flush_arp_replies(&mut self) -> bool {
        while let Some((destination, reply)) = self.pending_arp_replies.front().copied() {
            match Self::send_to(
                &mut *self.inner,
                destination,
                reply.buffer_len(),
                |buffer| reply.emit(&mut ArpPacket::new_unchecked(buffer)),
                EthernetProtocol::Arp,
            ) {
                Ok(frame_len) => self.deferred_tx_frame_lens.push(frame_len),
                Err(NetDeviceError::Again) => return false,
                Err(error) => {
                    warn!("{}: failed to send ARP reply: {error:?}", self.name);
                    self.deferred_tx_errors += 1;
                }
            }
            self.pending_arp_replies.pop_front();
        }
        true
    }

    /// Parses and handles a single Ethernet frame.
    ///
    /// Returns the raw Ethernet frame length (excluding FCS) for IP packets
    /// delivered into `buffer`, or 0 for non-IP frames (ARP, unknown
    /// EtherType), malformed frames, or frames not addressed to this device.
    fn handle_frame(
        &mut self,
        frame: &[u8],
        interface_id: InterfaceId,
        buffer: &mut PacketBuffer<InterfaceId>,
        timestamp: Instant,
        snoop: &mut dyn FnMut(&[u8]),
    ) -> usize {
        let frame_len = frame.len();
        let frame = EthernetFrame::new_unchecked(frame);
        let Ok(repr) = EthernetRepr::parse(&frame) else {
            warn!("Dropping malformed Ethernet frame");
            self.deferred_rx_errors += 1;
            return 0;
        };

        if !repr.dst_addr.is_broadcast()
            && repr.dst_addr != EMPTY_MAC
            && repr.dst_addr != self.hardware_address()
        {
            return 0;
        }

        match repr.ethertype {
            EthernetProtocol::Ipv4 | EthernetProtocol::Ipv6 => {
                snoop(frame.payload());
                buffer
                    .enqueue(frame.payload().len(), interface_id)
                    .expect(
                        "recv precondition: buffer checked !rx_buffer.is_full() before calling \
                         recv()",
                    )
                    .copy_from_slice(frame.payload());
                frame_len
            }
            EthernetProtocol::Arp => {
                self.process_arp(frame.payload(), timestamp);
                // ARP frames are successfully received L2 frames — record
                // their length for RX statistics even though they were not
                // enqueued into the IP buffer.
                self.deferred_rx_frame_lens.push(frame_len);
                0
            }
            _ => {
                // Any other EtherType that has already passed the L2 validity
                // and destination-MAC filter is a good frame the host received
                // from the device. Per Linux rtnl_link_stats64, rx_packets /
                // rx_bytes count every good packet received. Linux also
                // increments rx_dropped (and sometimes rx_nohandler) for the
                // same frame because the protocol is unsupported by the stack.
                self.deferred_rx_frame_lens.push(frame_len);
                self.deferred_rx_drops += 1;
                0
            }
        }
    }

    fn handle_non_ip_frame(&mut self, frame: &[u8], timestamp: Instant) {
        let frame_len = frame.len();
        let frame = EthernetFrame::new_unchecked(frame);
        let Ok(repr) = EthernetRepr::parse(&frame) else {
            self.deferred_rx_errors += 1;
            return;
        };
        match repr.ethertype {
            EthernetProtocol::Arp => {
                self.process_arp(frame.payload(), timestamp);
                self.deferred_rx_frame_lens.push(frame_len);
            }
            EthernetProtocol::Ipv4 | EthernetProtocol::Ipv6 => {}
            _ => {
                self.deferred_rx_frame_lens.push(frame_len);
                self.deferred_rx_drops += 1;
            }
        }
    }

    fn request_arp(&mut self, target_ip: IpAddress, timestamp: Instant) -> NetDeviceResult {
        let IpAddress::Ipv4(target_ipv4) = target_ip else {
            warn!("IPv6 address ARP is not supported: {}", target_ip);
            return Err(NetDeviceError::InvalidParam);
        };
        let Some(ip) = self.ip else {
            warn!("cannot request ARP for {target_ipv4}: ethernet IPv4 is not configured");
            return Err(NetDeviceError::InvalidParam);
        };
        info!("{}: requesting ARP for {}", self.name, target_ipv4);

        let arp_repr = ArpRepr::EthernetIpv4 {
            operation: ArpOperation::Request,
            source_hardware_addr: self.hardware_address(),
            source_protocol_addr: ip.address(),
            target_hardware_addr: EMPTY_MAC,
            target_protocol_addr: target_ipv4,
        };

        let arp_frame_len = Self::send_to(
            &mut *self.inner,
            EthernetAddress::BROADCAST,
            arp_repr.buffer_len(),
            |buf| arp_repr.emit(&mut ArpPacket::new_unchecked(buf)),
            EthernetProtocol::Arp,
        )?;
        // ARP requests are successfully transmitted L2 frames — record
        // their length so the protocol executor can count them in TX stats.
        self.deferred_tx_frame_lens.push(arp_frame_len);

        self.pending_neighbors.insert(
            target_ip,
            PendingNeighbor {
                requested_at: timestamp,
            },
        );
        Ok(())
    }

    fn process_arp(&mut self, payload: &[u8], now: Instant) {
        let Ok(repr) = ArpPacket::new_checked(payload).and_then(|packet| ArpRepr::parse(&packet))
        else {
            warn!("Dropping malformed ARP packet");
            self.deferred_rx_errors += 1;
            return;
        };

        if let ArpRepr::EthernetIpv4 {
            operation,
            source_hardware_addr,
            source_protocol_addr,
            target_hardware_addr,
            target_protocol_addr,
        } = repr
        {
            let is_unicast_mac =
                target_hardware_addr != EMPTY_MAC && !target_hardware_addr.is_broadcast();
            if is_unicast_mac && self.hardware_address() != target_hardware_addr {
                // Only process packet that are for us
                return;
            }

            if let ArpOperation::Unknown(_) = operation {
                return;
            }

            if !source_hardware_addr.is_unicast()
                || source_protocol_addr.is_broadcast()
                || source_protocol_addr.is_multicast()
                || source_protocol_addr.is_unspecified()
            {
                return;
            }
            let Some(ip) = self.ip else {
                return;
            };
            if ip.address() != target_protocol_addr {
                return;
            }

            info!(
                "{}: ARP {} -> {}",
                self.name, source_protocol_addr, source_hardware_addr
            );
            self.pending_neighbors
                .remove(&IpAddress::Ipv4(source_protocol_addr));
            self.neighbors.insert(
                IpAddress::Ipv4(source_protocol_addr),
                Neighbor {
                    hardware_address: source_hardware_addr,
                    expires_at: now + Self::NEIGHBOR_TTL,
                },
            );

            if let ArpOperation::Request = operation {
                let response = ArpRepr::EthernetIpv4 {
                    operation: ArpOperation::Reply,
                    source_hardware_addr: self.hardware_address(),
                    source_protocol_addr: ip.address(),
                    target_hardware_addr: source_hardware_addr,
                    target_protocol_addr: source_protocol_addr,
                };

                // Coalesce repeated probes while blocked, and bound storage
                // independently of the number of peers sending requests.
                let reply = (source_hardware_addr, response);
                if !self.pending_arp_replies.contains(&reply) {
                    if self.pending_arp_replies.len() < ETHERNET_MAX_PENDING_PACKETS {
                        self.pending_arp_replies.push_back(reply);
                    } else {
                        self.deferred_tx_drops += 1;
                    }
                }
                self.flush_arp_replies();
            }

            // Drain every entry in the pending queue and either send it (if
            // the next-hop is now resolved) or re-queue it in arrival order.
            // Peeking the head and stopping on the first mismatch would
            // permanently block packets queued behind an unresolvable
            // next-hop (e.g. a SYN to a fake IP at the head holds back a
            // SYN to the gateway behind it).
            //
            // The kept buffer is pre-sized so the drain does not have to
            // grow it through reallocations while a high-priority ARP IRQ
            // is being processed.
            let mut kept: Vec<(IpAddress, Vec<u8>)> =
                Vec::with_capacity(ETHERNET_MAX_PENDING_PACKETS);
            for _ in 0..ETHERNET_MAX_PENDING_PACKETS {
                let Ok((&next_hop, buf)) = self.pending_packets.peek() else {
                    break;
                };
                enum Action {
                    Send(EthernetAddress, Vec<u8>),
                    Refresh(Vec<u8>),
                    Keep(Vec<u8>),
                }
                let action = match self.neighbors.get(&next_hop) {
                    Some(neighbor) if neighbor.expires_at > now => {
                        Action::Send(neighbor.hardware_address, buf.to_vec())
                    }
                    Some(_) => Action::Refresh(buf.to_vec()),
                    None => Action::Keep(buf.to_vec()),
                };
                self.pending_packets
                    .dequeue()
                    .expect("peek succeeded moments ago; dequeue must succeed");

                match action {
                    Action::Send(mac, payload) => {
                        info!(
                            "{}: sending pending IPv4 packet to {} via {}",
                            self.name, next_hop, mac
                        );
                        match self.transmit_ip_to(mac, &payload) {
                            Ok(frame_len) => self.deferred_tx_frame_lens.push(frame_len),
                            Err(NetDeviceError::Again) => kept.push((next_hop, payload)),
                            Err(err) => {
                                warn!(
                                    "{}: failed to send pending packet to {}: {err:?}",
                                    self.name, next_hop
                                );
                                self.deferred_tx_errors += 1;
                            }
                        }
                    }
                    Action::Refresh(payload) => {
                        self.neighbors.remove(&next_hop);
                        if let Err(err) = self.request_arp(next_hop, now)
                            && !matches!(err, NetDeviceError::Again)
                        {
                            warn!(
                                "{}: failed to refresh ARP entry for {}: {err:?}",
                                self.name, next_hop
                            );
                            self.deferred_tx_errors += 1;
                        }
                        kept.push((next_hop, payload));
                    }
                    Action::Keep(payload) => {
                        kept.push((next_hop, payload));
                    }
                }
            }
            for (next_hop, payload) in kept {
                let Ok(dst) = self.pending_packets.enqueue(payload.len(), next_hop) else {
                    warn!(
                        "{}: pending buffer overflow while restoring queue entry to {}",
                        self.name, next_hop
                    );
                    break;
                };
                dst.copy_from_slice(&payload);
            }
        }
    }
}

impl Device for EthernetDevice {
    fn name(&self) -> &str {
        &self.name
    }

    fn recv(
        &mut self,
        interface_id: InterfaceId,
        buffer: &mut PacketBuffer<InterfaceId>,
        timestamp: Instant,
        snoop: &mut dyn FnMut(&[u8]),
    ) -> usize {
        // TX completions already wake the protocol executor. Retry control
        // traffic on that poll even if no new RX packet or IP send arrives.
        self.flush_arp_replies();
        loop {
            let rx_buf = match self.inner.receive() {
                Ok(buf) => buf,
                Err(err) => {
                    if !matches!(err, crate::device::NetDeviceError::Again) {
                        warn!("receive failed: {:?}", err);
                        self.deferred_rx_errors += 1;
                    }
                    return 0;
                }
            };
            trace!(
                "RECV {} bytes: {:02X?}",
                rx_buf.packet_len(),
                rx_buf.packet()
            );

            let frame_len =
                self.handle_frame(rx_buf.packet(), interface_id, buffer, timestamp, snoop);
            if frame_len > 0 {
                return frame_len;
            }
        }
    }

    fn poll_owned_rx(&mut self, timestamp: Instant) -> DeviceRxPoll {
        self.flush_arp_replies();
        loop {
            let frame = match self.inner.receive_owned() {
                Ok(Some(frame)) => frame,
                Ok(None) => return DeviceRxPoll::Unsupported,
                Err(NetDeviceError::Again) => return DeviceRxPoll::Idle,
                Err(err) => {
                    warn!("receive failed: {err:?}");
                    self.deferred_rx_errors += 1;
                    return DeviceRxPoll::Idle;
                }
            };
            let hardware_address = self.hardware_address();
            let mut malformed = false;
            let mut side_frame = false;
            let packet_range = frame.read_with(|packet| {
                trace!("RECV {} bytes: {:02X?}", packet.len(), packet);
                let Ok(ethernet) = EthernetFrame::new_checked(packet) else {
                    malformed = true;
                    return None;
                };
                let Ok(repr) = EthernetRepr::parse(&ethernet) else {
                    malformed = true;
                    return None;
                };
                if !repr.dst_addr.is_broadcast()
                    && repr.dst_addr != EMPTY_MAC
                    && repr.dst_addr != hardware_address
                {
                    return None;
                }
                match repr.ethertype {
                    EthernetProtocol::Ipv4 | EthernetProtocol::Ipv6 => {
                        let payload_len = ethernet.payload().len();
                        let payload_start = packet.len() - payload_len;
                        Some(payload_start..payload_start + payload_len)
                    }
                    _ => {
                        side_frame = true;
                        None
                    }
                }
            });
            if malformed {
                self.deferred_rx_errors += 1;
            }
            if side_frame {
                frame.read_with(|packet| self.handle_non_ip_frame(packet, timestamp));
            }
            if let Some(packet_range) = packet_range {
                let frame_len = frame.packet_len();
                return DeviceRxPoll::Packet(DeviceRxPacket::with_packet_range(
                    frame_len,
                    frame,
                    packet_range,
                ));
            }
        }
    }

    fn recv_direct(
        &mut self,
        timestamp: Instant,
        deliver: &mut dyn FnMut(&[u8]) -> bool,
        snoop: &mut dyn FnMut(&[u8]),
    ) -> Option<usize> {
        self.flush_arp_replies();
        loop {
            let hardware_address = self.hardware_address();
            let mut side_frame = None;
            let mut malformed = false;
            let mut dropped = false;
            let result = self.inner.receive_with(&mut |packet| {
                trace!("RECV {} bytes: {:02X?}", packet.len(), packet);
                let Ok(frame) = EthernetFrame::new_checked(packet) else {
                    malformed = true;
                    return 0;
                };
                let Ok(repr) = EthernetRepr::parse(&frame) else {
                    malformed = true;
                    return 0;
                };
                if !repr.dst_addr.is_broadcast()
                    && repr.dst_addr != EMPTY_MAC
                    && repr.dst_addr != hardware_address
                {
                    return 0;
                }
                match repr.ethertype {
                    EthernetProtocol::Ipv4 | EthernetProtocol::Ipv6 => {
                        snoop(frame.payload());
                        if deliver(frame.payload()) {
                            packet.len()
                        } else {
                            dropped = true;
                            0
                        }
                    }
                    _ => {
                        match ProtocolEthernetFrame::copy_from_slice(packet) {
                            Ok(frame) => side_frame = Some(frame),
                            Err(_) => malformed = true,
                        }
                        0
                    }
                }
            });
            let frame_len = match result {
                Ok(frame_len) => frame_len,
                Err(NetDeviceError::Again) => return Some(0),
                Err(err) => {
                    warn!("receive failed: {err:?}");
                    self.deferred_rx_errors += 1;
                    return Some(0);
                }
            };
            if malformed {
                self.deferred_rx_errors += 1;
            }
            if dropped {
                self.deferred_rx_drops += 1;
            }
            if let Some(frame) = side_frame {
                self.handle_non_ip_frame(frame.packet(), timestamp);
            }
            if frame_len > 0 {
                return Some(frame_len);
            }
        }
    }

    fn send(&mut self, next_hop: IpAddress, packet: &[u8], timestamp: Instant) -> usize {
        match self.try_send(next_hop, packet, timestamp) {
            Ok(frame_len) => frame_len,
            Err(NetDeviceError::Again) => {
                // This compatibility entry point cannot retain the caller's
                // packet for retry after transient queue pressure.
                self.deferred_tx_drops += 1;
                0
            }
            Err(err) => {
                warn!("{}: transmit failed: {err:?}", self.name);
                self.deferred_tx_errors += 1;
                0
            }
        }
    }

    fn try_send(
        &mut self,
        next_hop: IpAddress,
        packet: &[u8],
        timestamp: Instant,
    ) -> NetDeviceResult<usize> {
        let is_subnet_broadcast =
            self.ip.and_then(|ip| ip.broadcast()).map(IpAddress::Ipv4) == Some(next_hop);
        if next_hop.is_broadcast() || is_subnet_broadcast {
            return self.transmit_ip_to(EthernetAddress::BROADCAST, packet);
        }
        if next_hop.is_multicast() {
            let hardware_address = match next_hop {
                IpAddress::Ipv4(address) => {
                    // RFC 1112 section 6.4: retain only the low 23 address bits.
                    let octets = address.octets();
                    EthernetAddress([0x01, 0x00, 0x5e, octets[1] & 0x7f, octets[2], octets[3]])
                }
                IpAddress::Ipv6(address) => {
                    // RFC 2464 section 7: 33:33 followed by the low 32 bits.
                    let octets = address.octets();
                    EthernetAddress([0x33, 0x33, octets[12], octets[13], octets[14], octets[15]])
                }
            };
            return self.transmit_ip_to(hardware_address, packet);
        }

        let need_request = match self.neighbors.get(&next_hop) {
            Some(neighbor) if neighbor.expires_at > timestamp => {
                let hardware_address = neighbor.hardware_address;
                return self.transmit_ip_to(hardware_address, packet);
            }
            Some(_) => {
                self.neighbors.remove(&next_hop);
                true
            }
            None => self
                .pending_neighbors
                .get(&next_hop)
                .is_none_or(|pending| timestamp >= pending.requested_at + Self::ARP_REQUEST_RETRY),
        };
        if need_request {
            self.request_arp(next_hop, timestamp)?;
        }
        if self.pending_packets.is_full() {
            warn!(
                "{}: Pending packets buffer is full, dropping packet",
                self.name
            );
            self.deferred_tx_drops += 1;
            return Ok(0);
        }
        let Ok(dst_buffer) = self.pending_packets.enqueue(packet.len(), next_hop) else {
            warn!("Failed to enqueue packet in pending packets buffer");
            self.deferred_tx_drops += 1;
            return Ok(0);
        };
        dst_buffer.copy_from_slice(packet);
        Ok(0)
    }

    fn drain_deferred_tx(&mut self) -> Vec<usize> {
        core::mem::take(&mut self.deferred_tx_frame_lens)
    }

    fn drain_deferred_rx(&mut self) -> Vec<usize> {
        core::mem::take(&mut self.deferred_rx_frame_lens)
    }

    fn drain_deferred_tx_errors(&mut self) -> u64 {
        core::mem::take(&mut self.deferred_tx_errors)
    }

    fn drain_deferred_tx_drops(&mut self) -> u64 {
        core::mem::take(&mut self.deferred_tx_drops)
    }

    fn drain_deferred_rx_errors(&mut self) -> u64 {
        core::mem::take(&mut self.deferred_rx_errors)
    }

    fn drain_deferred_rx_drops(&mut self) -> u64 {
        core::mem::take(&mut self.deferred_rx_drops) + self.inner.drain_rx_drops()
    }

    fn set_ipv4_addr(&mut self, addr: Option<Ipv4Cidr>) {
        self.ip = addr;
        self.neighbors.clear();
        self.pending_neighbors.clear();
        self.deferred_tx_drops += self.pending_arp_replies.len() as u64;
        self.pending_arp_replies.clear();
        // The deferred TX/RX frame-length accumulators are deliberately left
        // intact. They hold L2 frames that were already successfully
        // transmitted to or received from the device before this call; those
        // are completed link-layer events. Per Linux rtnl_link_stats64,
        // interface counters are cumulative and survive routine interface
        // operations such as an IPv4 reconfiguration, so an IP context change
        // must not retract counts that the protocol executor has not drained yet.
        // Neighbor/pending state above is IP-context specific and is cleared.
    }

    fn arp_entries(&self, timestamp: Instant) -> Vec<ArpEntry> {
        self.neighbors
            .iter()
            .filter_map(|(ip_addr, neighbor)| {
                if neighbor.expires_at <= timestamp {
                    return None;
                }
                let IpAddress::Ipv4(ip_addr) = ip_addr else {
                    return None;
                };
                Some(ArpEntry {
                    ip_addr: ip_addr.octets(),
                    hw_type: 1,
                    flags: 2,
                    hw_addr: neighbor.hardware_address.0,
                    device: self.name.clone(),
                })
            })
            .collect()
    }
}

#[cfg(test)]
/// Unit tests for EthernetDevice counters: ARP, frame-length, and
/// error/drop paths.
mod ethernet_counter_tests {
    use alloc::{collections::VecDeque, sync::Arc};

    use ax_sync::SpinLock;
    use smoltcp::wire::{Ipv4Address, Ipv4Cidr};

    use super::*;
    use crate::device::{NetDeviceError, NetDeviceResult, TxChecksumCapabilities};

    // ── Mock protocol-port infrastructure ──────────────────────────────

    /// Minimal protocol frame port for testing EthernetDevice ARP paths.
    struct MockEthernetDriver {
        mac: [u8; 6],
        checksum_capabilities: TxChecksumCapabilities,
        /// Pre-canned frames returned by `receive()` in FIFO order.
        rx_frames: VecDeque<Vec<u8>>,
        /// Frames transmitted through `transmit()`, captured for inspection.
        tx_frames: Vec<Vec<u8>>,
        /// When set, frame publication returns an error.
        tx_alloc_fail: bool,
    }

    impl MockEthernetDriver {
        fn new(mac: [u8; 6]) -> Self {
            Self {
                mac,
                checksum_capabilities: TxChecksumCapabilities::NONE,
                rx_frames: VecDeque::new(),
                tx_frames: Vec::new(),
                tx_alloc_fail: false,
            }
        }

        fn enqueue_rx_frame(&mut self, frame: Vec<u8>) {
            self.rx_frames.push_back(frame);
        }
    }

    impl EthernetFramePort for MockEthernetDriver {
        fn device_name(&self) -> &str {
            "mock"
        }

        fn mac_address(&self) -> [u8; 6] {
            self.mac
        }

        fn checksum_capabilities(&self) -> TxChecksumCapabilities {
            self.checksum_capabilities
        }

        fn transmit(&mut self, frame: &ProtocolEthernetFrame) -> NetDeviceResult {
            if self.tx_alloc_fail {
                return Err(NetDeviceError::Again);
            }
            self.tx_frames.push(frame.packet().to_vec());
            Ok(())
        }

        fn receive(&mut self) -> NetDeviceResult<ProtocolEthernetFrame> {
            self.rx_frames
                .pop_front()
                .map(|packet| ProtocolEthernetFrame::copy_from_slice(&packet).unwrap())
                .ok_or(NetDeviceError::Again)
        }
    }

    #[derive(Default)]
    struct TxProbe {
        requests: SpinLock<Vec<(Vec<u8>, TxSubmitOptions)>>,
        failure: SpinLock<Option<NetDeviceError>>,
        rx_frames: SpinLock<VecDeque<Vec<u8>>>,
        blocked: SpinLock<bool>,
    }

    struct RecordingFramePort {
        probe: Arc<TxProbe>,
        checksum_capabilities: TxChecksumCapabilities,
    }

    impl EthernetFramePort for RecordingFramePort {
        fn device_name(&self) -> &str {
            "recording"
        }

        fn mac_address(&self) -> [u8; 6] {
            DEV_MAC
        }

        fn checksum_capabilities(&self) -> TxChecksumCapabilities {
            self.checksum_capabilities
        }

        fn transmit(&mut self, frame: &ProtocolEthernetFrame) -> NetDeviceResult {
            if *self.probe.blocked.lock_irqsave() {
                return Err(NetDeviceError::Again);
            }
            if let Some(error) = self.probe.failure.lock_irqsave().take() {
                return Err(error);
            }
            self.probe
                .requests
                .lock_irqsave()
                .push((frame.packet().to_vec(), TxSubmitOptions::default()));
            Ok(())
        }

        fn transmit_frame_with_options(
            &mut self,
            frame_len: usize,
            options: TxSubmitOptions,
            fill: &mut dyn FnMut(&mut [u8]),
        ) -> NetDeviceResult {
            if *self.probe.blocked.lock_irqsave() {
                return Err(NetDeviceError::Again);
            }
            if let Some(error) = self.probe.failure.lock_irqsave().take() {
                return Err(error);
            }
            let mut frame = vec![0u8; frame_len];
            fill(&mut frame);
            self.probe.requests.lock_irqsave().push((frame, options));
            Ok(())
        }

        fn receive(&mut self) -> NetDeviceResult<ProtocolEthernetFrame> {
            self.probe
                .rx_frames
                .lock_irqsave()
                .pop_front()
                .map(|packet| ProtocolEthernetFrame::copy_from_slice(&packet).unwrap())
                .ok_or(NetDeviceError::Again)
        }
    }

    // ── Helpers ────────────────────────────────────────────────────────

    const DEV_MAC: [u8; 6] = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
    const REMOTE_MAC: [u8; 6] = [0x02, 0x00, 0x00, 0x00, 0x00, 0x01];
    const DEV_IP: Ipv4Address = Ipv4Address::new(10, 0, 0, 2);
    const REMOTE_IP: Ipv4Address = Ipv4Address::new(10, 0, 0, 1);

    fn device_ip_cidr() -> Ipv4Cidr {
        Ipv4Cidr::new(DEV_IP, 24)
    }

    fn make_test_device(mock: MockEthernetDriver) -> EthernetDevice {
        EthernetDevice::new("mock0".into(), Box::new(mock), Some(device_ip_cidr()))
    }

    fn make_recording_device(
        checksum_capabilities: TxChecksumCapabilities,
    ) -> (EthernetDevice, Arc<TxProbe>) {
        let probe = Arc::new(TxProbe::default());
        let port = RecordingFramePort {
            probe: Arc::clone(&probe),
            checksum_capabilities,
        };
        (
            EthernetDevice::new("recording0".into(), Box::new(port), Some(device_ip_cidr())),
            probe,
        )
    }

    fn raw_tcp_packet() -> Vec<u8> {
        let mut packet = vec![0u8; 60];
        let packet_len = packet.len() as u16;
        packet[0] = 0x45;
        packet[2..4].copy_from_slice(&packet_len.to_be_bytes());
        packet[8] = 64;
        packet[9] = 6;
        packet[12..16].copy_from_slice(&DEV_IP.octets());
        packet[16..20].copy_from_slice(&REMOTE_IP.octets());
        packet[20..22].copy_from_slice(&41000u16.to_be_bytes());
        packet[22..24].copy_from_slice(&5201u16.to_be_bytes());
        packet[32] = 5 << 4;
        packet
    }

    fn enqueue_pending_packet(device: &mut EthernetDevice, packet: &[u8]) {
        device
            .pending_packets
            .enqueue(packet.len(), IpAddress::Ipv4(REMOTE_IP))
            .expect("the empty pending queue has capacity")
            .copy_from_slice(packet);
    }

    fn process_remote_arp_reply(device: &mut EthernetDevice, timestamp: Instant) {
        let reply = build_arp_frame(
            ArpOperation::Reply,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            DEV_MAC,
        );
        device.process_arp(&reply[EthernetFrame::<&[u8]>::header_len()..], timestamp);
    }

    /// Builds a complete Ethernet frame containing an ARP packet.
    fn build_arp_frame(
        operation: ArpOperation,
        src_mac: [u8; 6],
        dst_mac: [u8; 6],
        src_ip: Ipv4Address,
        dst_ip: Ipv4Address,
        target_mac: [u8; 6],
    ) -> Vec<u8> {
        let arp_repr = ArpRepr::EthernetIpv4 {
            operation,
            source_hardware_addr: EthernetAddress(src_mac),
            source_protocol_addr: src_ip,
            target_hardware_addr: EthernetAddress(target_mac),
            target_protocol_addr: dst_ip,
        };
        let eth_repr = EthernetRepr {
            src_addr: EthernetAddress(src_mac),
            dst_addr: EthernetAddress(dst_mac),
            ethertype: EthernetProtocol::Arp,
        };

        let total_len = eth_repr.buffer_len() + arp_repr.buffer_len();
        let mut buf = alloc::vec![0u8; total_len];
        let mut frame = EthernetFrame::new_unchecked(&mut buf);
        eth_repr.emit(&mut frame);
        arp_repr.emit(&mut ArpPacket::new_unchecked(frame.payload_mut()));
        buf
    }

    fn test_packet_buffer() -> PacketBuffer<'static, InterfaceId> {
        PacketBuffer::new(vec![PacketMetadata::EMPTY; 4], vec![0u8; STANDARD_MTU * 4])
    }

    // ── ARP RX: received ARP frames are counted in drain_deferred_rx ─────

    #[test]
    fn arp_request_rx_is_counted_in_drain_deferred_rx() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let arp_frame = build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            EMPTY_MAC.0,
        );
        let frame_len = arp_frame.len();
        mock.enqueue_rx_frame(arp_frame);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);

        // recv() processes the ARP request and returns 0 (no IP packet).
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);

        // The ARP frame length is recorded in the async RX side-channel.
        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens, &[frame_len]);

        // Second drain is empty.
        assert!(device.drain_deferred_rx().is_empty());
    }

    #[test]
    fn arp_reply_rx_is_counted_in_drain_deferred_rx() {
        let ts = Instant::from_millis(0);

        // Build a device with both a pending neighbor entry and a
        // queued ARP reply frame.
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let arp_reply = build_arp_frame(
            ArpOperation::Reply,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            DEV_MAC,
        );
        let frame_len = arp_reply.len();
        mock.enqueue_rx_frame(arp_reply);

        let mut device = make_test_device(mock);
        // A pending neighbor is required for process_arp() to handle the
        // reply as relevant.
        device.pending_neighbors.insert(
            IpAddress::Ipv4(REMOTE_IP),
            PendingNeighbor { requested_at: ts },
        );

        let mut buffer = test_packet_buffer();
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0); // ARP reply is not an IP packet

        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens, &[frame_len]);
    }

    // ── ARP TX: transmitted ARP frames are counted in drain_deferred_tx ──

    #[test]
    fn arp_request_tx_is_counted_in_drain_deferred_tx() {
        let mock = MockEthernetDriver::new(DEV_MAC);
        let mut device = make_test_device(mock);
        let ts = Instant::from_millis(0);

        // Sending to an unknown neighbor triggers ARP request.
        let result = device.send(IpAddress::Ipv4(REMOTE_IP), &[0u8; 64], ts);
        // Packet is queued pending ARP; send() returns 0.
        assert_eq!(result, 0);

        // The ARP request frame length should be in drain_deferred_tx.
        let tx_lens = device.drain_deferred_tx();
        assert_eq!(tx_lens.len(), 1);
        // ARP request over Ethernet: 14 (eth hdr) + 28 (ARP) = 42 bytes.
        // With ETH_ZLEN padding: max(42, 60) = 60.
        assert_eq!(tx_lens[0], 60);
    }

    #[test]
    fn arp_reply_tx_is_counted_in_drain_deferred_tx() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        // ARP request addressed to device from remote.
        let arp_request = build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            EMPTY_MAC.0,
        );
        mock.enqueue_rx_frame(arp_request);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);

        // recv() processes the ARP request, which triggers an ARP reply.
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);

        // Both the ARP request RX and ARP reply TX should be counted.
        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens.len(), 1); // ARP request RX

        let tx_lens = device.drain_deferred_tx();
        assert_eq!(tx_lens.len(), 1); // ARP reply TX
        // ARP reply over Ethernet: 14 (eth hdr) + 28 (ARP) = 42 → padded to 60.
        assert_eq!(tx_lens[0], 60);
    }

    #[test]
    fn arp_reply_survives_tx_backpressure_and_precedes_bulk_ip() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::NONE);
        probe.rx_frames.lock_irqsave().push_back(build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            EMPTY_MAC.0,
        ));
        *probe.failure.lock_irqsave() = Some(NetDeviceError::Again);
        device.recv(
            InterfaceId::new(1),
            &mut test_packet_buffer(),
            Instant::ZERO,
            &mut |_| {},
        );

        let packet = raw_tcp_packet();
        device
            .try_send(IpAddress::Ipv4(REMOTE_IP), &packet, Instant::ZERO)
            .unwrap();

        let requests = probe.requests.lock_irqsave();
        assert_eq!(requests.len(), 2, "queue pressure lost the ARP reply");
        let reply = EthernetFrame::new_checked(&requests[0].0).unwrap();
        assert_eq!(reply.ethertype(), EthernetProtocol::Arp);
        assert_eq!(reply.dst_addr(), EthernetAddress(REMOTE_MAC));
        assert_eq!(
            ArpRepr::parse(&ArpPacket::new_checked(reply.payload()).unwrap()).unwrap(),
            ArpRepr::EthernetIpv4 {
                operation: ArpOperation::Reply,
                source_hardware_addr: EthernetAddress(DEV_MAC),
                source_protocol_addr: DEV_IP,
                target_hardware_addr: EthernetAddress(REMOTE_MAC),
                target_protocol_addr: REMOTE_IP,
            }
        );
        assert_eq!(requests[0].1.notify, TxNotify::Immediate);
        assert_eq!(&requests[1].0[14..], &packet);
        drop(requests);
        assert_eq!(device.drain_deferred_tx(), vec![ETH_ZLEN]);
        assert_eq!(device.drain_deferred_tx_drops(), 0);
    }

    #[test]
    fn arp_reply_retries_on_tx_completion_poll_without_new_rx() {
        for receive_path in 0..3 {
            let (mut device, probe) = make_recording_device(TxChecksumCapabilities::NONE);
            *probe.blocked.lock_irqsave() = true;
            for _ in 0..3 {
                probe.rx_frames.lock_irqsave().push_back(build_arp_frame(
                    ArpOperation::Request,
                    REMOTE_MAC,
                    DEV_MAC,
                    REMOTE_IP,
                    DEV_IP,
                    EMPTY_MAC.0,
                ));
            }
            let mut buffer = test_packet_buffer();
            device.recv(InterfaceId::new(1), &mut buffer, Instant::ZERO, &mut |_| {});
            *probe.blocked.lock_irqsave() = false;

            match receive_path {
                0 => {
                    device.recv(InterfaceId::new(1), &mut buffer, Instant::ZERO, &mut |_| {});
                }
                1 => {
                    let _ = device.poll_owned_rx(Instant::ZERO);
                }
                _ => {
                    let _ = device.recv_direct(Instant::ZERO, &mut |_| false, &mut |_| {});
                }
            }

            let requests = probe.requests.lock_irqsave();
            assert_eq!(
                requests.len(),
                1,
                "poll path {receive_path} lost or duplicated the reply"
            );
            let frame = EthernetFrame::new_checked(&requests[0].0).unwrap();
            assert_eq!(frame.ethertype(), EthernetProtocol::Arp);
            assert_eq!(frame.dst_addr(), EthernetAddress(REMOTE_MAC));
            drop(requests);
            assert_eq!(device.drain_deferred_tx(), vec![ETH_ZLEN]);
            assert_eq!(device.drain_deferred_tx_drops(), 0);
        }
    }

    #[test]
    fn pending_arp_replies_are_bounded_and_cancelled_on_address_change() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::NONE);
        *probe.blocked.lock_irqsave() = true;
        for index in 0..=ETHERNET_MAX_PENDING_PACKETS {
            probe.rx_frames.lock_irqsave().push_back(build_arp_frame(
                ArpOperation::Request,
                REMOTE_MAC,
                DEV_MAC,
                Ipv4Address::from((0x0a00_0101 + index as u32).to_be_bytes()),
                DEV_IP,
                EMPTY_MAC.0,
            ));
        }
        device.recv(
            InterfaceId::new(1),
            &mut test_packet_buffer(),
            Instant::ZERO,
            &mut |_| {},
        );
        assert_eq!(device.drain_deferred_tx_drops(), 1);
        device.set_ipv4_addr(None);
        *probe.blocked.lock_irqsave() = false;
        let _ = device.poll_owned_rx(Instant::ZERO);
        assert!(
            probe.requests.lock_irqsave().is_empty(),
            "sent replies for a removed address"
        );
        assert_eq!(
            device.drain_deferred_tx_drops(),
            ETHERNET_MAX_PENDING_PACKETS as u64
        );
    }

    #[test]
    fn pending_raw_tcp_packet_preserves_checksum_after_arp_resolution() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::TCP_UDP);
        let packet = raw_tcp_packet();
        enqueue_pending_packet(&mut device, &packet);

        process_remote_arp_reply(&mut device, Instant::from_millis(0));

        let requests = probe.requests.lock_irqsave();
        assert_eq!(requests.len(), 1);
        assert_eq!(
            &requests[0].0[EthernetFrame::<&[u8]>::header_len()..],
            &packet
        );
        assert_eq!(requests[0].1.notify, TxNotify::Deferred);
        assert_eq!(requests[0].1.checksum, None);
    }

    #[test]
    fn ethernet_preserves_raw_udp_checksum_without_requesting_offload() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::TCP_UDP);
        for len in [32usize, 60] {
            for checksum in [0u16, 0x1234] {
                let mut packet = vec![0u8; len];
                packet[0] = 0x45;
                packet[2..4].copy_from_slice(&(len as u16).to_be_bytes());
                packet[8] = 64;
                packet[9] = 17;
                packet[12..16].copy_from_slice(&DEV_IP.octets());
                packet[16..20].copy_from_slice(&REMOTE_IP.octets());
                packet[24..26].copy_from_slice(&((len - 20) as u16).to_be_bytes());
                packet[26..28].copy_from_slice(&checksum.to_be_bytes());
                device
                    .transmit_ip_to(EthernetAddress(REMOTE_MAC), &packet)
                    .unwrap();
                let requests = probe.requests.lock_irqsave();
                let (frame, options) = requests.last().unwrap();
                assert_eq!(
                    &frame[14..14 + len],
                    &packet,
                    "Ethernet rewrote raw UDP transport bytes"
                );
                assert_eq!(
                    options.checksum, None,
                    "zero checksum is not an offload request"
                );
            }
        }
    }

    #[test]
    fn pending_packet_survives_arp_resolution_tx_backpressure() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::TCP_UDP);
        let packet = raw_tcp_packet();
        enqueue_pending_packet(&mut device, &packet);
        *probe.failure.lock_irqsave() = Some(NetDeviceError::Again);

        process_remote_arp_reply(&mut device, Instant::from_millis(0));

        let (&next_hop, queued) = device
            .pending_packets
            .peek()
            .expect("transient queue pressure must retain the pending packet");
        assert_eq!(next_hop, IpAddress::Ipv4(REMOTE_IP));
        assert_eq!(queued, packet);
        assert_eq!(device.drain_deferred_tx_errors(), 0);
        assert_eq!(device.drain_deferred_tx_drops(), 0);
    }

    #[test]
    fn multicast_egress_uses_the_ip_version_specific_destination_mac() {
        use smoltcp::wire::Ipv6Address;

        let destinations = [
            (
                IpAddress::Ipv4(Ipv4Address::new(224, 0, 0, 1)),
                [1, 0, 0x5e, 0, 0, 1],
            ),
            (
                IpAddress::Ipv4(Ipv4Address::new(239, 255, 18, 52)),
                [1, 0, 0x5e, 0x7f, 18, 52],
            ),
            (
                IpAddress::Ipv6(Ipv6Address::new(0xff02, 0, 0, 0, 0, 1, 0xff12, 0x3456)),
                [0x33, 0x33, 0xff, 0x12, 0x34, 0x56],
            ),
            (IpAddress::Ipv4(Ipv4Address::BROADCAST), [0xff; 6]),
            (IpAddress::Ipv4(Ipv4Address::new(10, 0, 0, 255)), [0xff; 6]),
        ];
        for (destination, expected_mac) in destinations {
            let (mut device, probe) = make_recording_device(TxChecksumCapabilities::TCP_UDP);
            let packet = match destination {
                IpAddress::Ipv4(address) => {
                    let mut packet = raw_tcp_packet();
                    packet[16..20].copy_from_slice(&address.octets());
                    packet
                }
                IpAddress::Ipv6(address) => {
                    let mut packet = vec![0u8; 40];
                    packet[0] = 0x60;
                    packet[24..40].copy_from_slice(&address.octets());
                    packet
                }
            };
            *probe.failure.lock_irqsave() = Some(NetDeviceError::Again);
            assert_eq!(
                device.try_send(destination, &packet, Instant::ZERO),
                Err(NetDeviceError::Again)
            );
            assert!(probe.requests.lock_irqsave().is_empty());
            assert!(device.pending_packets.is_empty());
            assert!(device.pending_neighbors.is_empty());
            assert!(
                device
                    .try_send(destination, &packet, Instant::ZERO)
                    .unwrap()
                    > 0
            );
            let requests = probe.requests.lock_irqsave();
            assert_eq!(requests.len(), 1);
            let frame = EthernetFrame::new_checked(&requests[0].0).unwrap();
            assert_eq!(
                frame.dst_addr(),
                EthernetAddress(expected_mac),
                "destination {destination}"
            );
            assert_eq!(&frame.payload()[..packet.len()], packet);
            assert_eq!(requests[0].1.checksum, None);
            assert_eq!(device.drain_deferred_tx_errors(), 0);
            assert_eq!(device.drain_deferred_tx_drops(), 0);
        }
    }

    #[test]
    fn arp_request_backpressure_is_returned_to_the_router() {
        let (mut device, probe) = make_recording_device(TxChecksumCapabilities::TCP_UDP);
        let packet = raw_tcp_packet();
        *probe.failure.lock_irqsave() = Some(NetDeviceError::Again);

        let result = device.try_send(IpAddress::Ipv4(REMOTE_IP), &packet, Instant::from_millis(0));

        assert_eq!(result, Err(NetDeviceError::Again));
        assert!(device.pending_packets.is_empty());
        assert_eq!(device.drain_deferred_tx_errors(), 0);
        assert_eq!(device.drain_deferred_tx_drops(), 0);
    }

    #[test]
    fn consecutive_arp_frames_accumulate_in_drain_deferred_rx() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let frame1 = build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            EMPTY_MAC.0,
        );
        let frame2 = build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            Ipv4Address::new(10, 0, 0, 3),
            DEV_IP,
            EMPTY_MAC.0,
        );
        let len1 = frame1.len();
        let len2 = frame2.len();
        mock.enqueue_rx_frame(frame1);
        mock.enqueue_rx_frame(frame2);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);

        // First recv() call processes one ARP frame then returns 0 (no IP).
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);

        // Both ARP frame lengths should be accumulated.
        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens, &[len1, len2]);

        // Drain clears the accumulator.
        assert!(device.drain_deferred_rx().is_empty());
    }

    // ── set_ipv4_addr preserves undrained frame length accumulators ───────

    /// Verifies that set_ipv4_addr() does NOT clear deferred TX/RX frame
    /// length accumulators. Per Linux rtnl_link_stats64, tx_packets counts
    /// frames successfully transmitted to the device, and IP reconfiguration
    /// cannot retract those events. If the protocol executor has not yet drained
    /// deferred_tx_frame_lens after a successful ARP TX, those lengths must
    /// still be available after set_ipv4_addr() so the protocol executor can count them.
    #[test]
    fn set_ipv4_addr_preserves_undrained_frame_lens() {
        let mock = MockEthernetDriver::new(DEV_MAC);
        let mut device = make_test_device(mock);
        let ts = Instant::from_millis(0);

        // Trigger an ARP request TX by sending to an unknown neighbor.
        let result = device.send(IpAddress::Ipv4(REMOTE_IP), &[0u8; 64], ts);
        assert_eq!(result, 0); // Packet is queued pending ARP

        // The ARP request frame length is in deferred_tx_frame_lens.
        let tx_lens_before = device.drain_deferred_tx();
        assert_eq!(tx_lens_before.len(), 1);
        assert_eq!(tx_lens_before[0], 60); // ARP request padded to ETH_ZLEN

        // Simulate another ARP request before the protocol executor drains.
        let result = device.send(
            IpAddress::Ipv4(Ipv4Address::new(10, 0, 0, 99)),
            &[0u8; 64],
            ts,
        );
        assert_eq!(result, 0);

        // Now there's one undrained ARP TX.
        assert_eq!(device.deferred_tx_frame_lens.len(), 1);

        // Runtime reconfigures the IPv4 address (e.g., DHCP renew).
        device.set_ipv4_addr(Some(Ipv4Cidr::new(Ipv4Address::new(10, 0, 0, 99), 24)));

        // The undrained ARP TX length must still be present so the protocol executor
        // can drain and count it. Clearing it here would permanently lose the
        // tx_packets/tx_bytes for an event that already succeeded.
        let tx_lens_after = device.drain_deferred_tx();
        assert_eq!(tx_lens_after.len(), 1);
        assert_eq!(tx_lens_after[0], 60);
    }

    // ── Non-ARP frames are counted in drain_deferred_rx ───────────────────

    /// Verifies that valid L2 frames with an unknown EtherType (not ARP, not
    /// IPv4) are counted in both drain_deferred_rx() (for rx_packets/rx_bytes)
    /// and drain_deferred_rx_drops() (for rx_dropped). Per Linux semantics,
    /// rx_packets includes all good packets received from the device, and
    /// rx_dropped is also incremented for the same frame because the protocol
    /// is unsupported by the stack.
    #[test]
    fn unknown_ethertype_frame_is_counted_in_drain_deferred_rx() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);

        // Build a frame with EtherType 0x8100 (802.1Q VLAN tag), which this
        // stack does not support. The frame is well-formed and addressed to
        // the device, so it should count as a received packet.
        let eth_repr = EthernetRepr {
            src_addr: EthernetAddress(REMOTE_MAC),
            dst_addr: EthernetAddress(DEV_MAC),
            ethertype: EthernetProtocol::Unknown(0x8100),
        };
        let payload = [0xAAu8; 46]; // 14 + 46 = 60 bytes (ETH_ZLEN)
        let mut frame_buf = alloc::vec![0u8; eth_repr.buffer_len() + payload.len()];
        let mut frame = EthernetFrame::new_unchecked(&mut frame_buf);
        eth_repr.emit(&mut frame);
        frame.payload_mut().copy_from_slice(&payload);
        let frame_len = frame_buf.len();

        mock.enqueue_rx_frame(frame_buf);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);

        // recv() processes the unknown frame and returns 0 (no IP packet).
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);

        // The frame length is recorded in the RX side-channel.
        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens, &[frame_len]);

        // Also verify that the unsupported EtherType frame is counted as
        // rx_dropped, matching Linux behaviour for protocol-unsupported frames.
        let rx_drops = device.drain_deferred_rx_drops();
        assert_eq!(rx_drops, 1);
    }

    // ── ETH_ZLEN boundary test for send_to() wire_len ──────────────────

    /// Verifies that `send_to()` pads short frames to ETH_ZLEN (60 bytes)
    /// and returns the actual frame length for longer payloads. Covers
    /// below-ETH_ZLEN (0), at-ETH_ZLEN (46), and above-ETH_ZLEN (100).
    #[test]
    fn send_to_wire_len_respects_eth_zlen_padding() {
        let dst = EthernetAddress(REMOTE_MAC);

        // 0-byte payload: 14 + 0 = 14 → padded to 60.
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let wire_len =
            EthernetDevice::send_to(&mut mock, dst, 0, |_buf| {}, EthernetProtocol::Ipv4);
        assert_eq!(wire_len, Ok(60));

        // 46-byte payload: 14 + 46 = 60 → exactly at ETH_ZLEN, no padding needed.
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let wire_len = EthernetDevice::send_to(
            &mut mock,
            dst,
            46,
            |buf| buf.copy_from_slice(&[0xAAu8; 46]),
            EthernetProtocol::Ipv4,
        );
        assert_eq!(wire_len, Ok(60));

        // 100-byte payload: 14 + 100 = 114 → above ETH_ZLEN, no padding.
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        let wire_len = EthernetDevice::send_to(
            &mut mock,
            dst,
            100,
            |buf| buf.copy_from_slice(&[0xAAu8; 100]),
            EthernetProtocol::Ipv4,
        );
        assert_eq!(wire_len, Ok(114));
    }

    // ── Integration: combined ARP + IP recv/drain cycle ────────────────

    /// Simulates one protocol-executor drain cycle: receive IP frames, drain
    /// deferred TX (ARP replies/requests), and drain deferred RX (received
    /// ARP frames). Verifies that all three counting paths produce correct
    /// byte counts in a single combined cycle.
    #[test]
    fn combined_arp_ip_recv_drain_cycle() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);

        // Preload one ARP request frame addressed to the device.
        let arp_req = build_arp_frame(
            ArpOperation::Request,
            REMOTE_MAC,
            DEV_MAC,
            REMOTE_IP,
            DEV_IP,
            DEV_MAC,
        );
        mock.enqueue_rx_frame(arp_req);

        // Preload one IP frame addressed to the device.
        let eth = EthernetRepr {
            src_addr: EthernetAddress(REMOTE_MAC),
            dst_addr: EthernetAddress(DEV_MAC),
            ethertype: EthernetProtocol::Ipv4,
        };
        let ip_payload = [0x11u8; 64];
        let mut ip_frame = alloc::vec![0u8; eth.buffer_len() + ip_payload.len()];
        let mut frame = EthernetFrame::new_unchecked(&mut ip_frame);
        eth.emit(&mut frame);
        frame.payload_mut().copy_from_slice(&ip_payload);
        let expected_ip_frame_len = ip_frame.len();
        mock.enqueue_rx_frame(ip_frame);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let iface = InterfaceId::new(1);

        // recv() loops internally — the ARP request is processed first
        // (returns 0, loop continues), then the IP packet is enqueued
        // and its L2 frame length is returned.
        let frame_len = device.recv(iface, &mut buffer, Instant::from_millis(0), &mut |_| {});
        assert_eq!(frame_len, expected_ip_frame_len);

        // Drain deferred RX: the received ARP request was stored.
        // RX uses the raw frame length from the driver (42 bytes); ETH_ZLEN
        // padding applies only on the TX path.
        let rx_lens = device.drain_deferred_rx();
        assert_eq!(rx_lens.len(), 1);
        assert_eq!(rx_lens[0], 42); // 14 eth hdr + 28 ARP

        // Drain deferred TX: the ARP reply that process_arp() sent.
        let tx_lens = device.drain_deferred_tx();
        assert_eq!(tx_lens.len(), 1);
        assert_eq!(tx_lens[0], 60); // 42-byte ARP reply padded to ETH_ZLEN

        // Second drain is idempotent.
        assert!(device.drain_deferred_rx().is_empty());
        assert!(device.drain_deferred_tx().is_empty());
    }

    // ── Error / drop counter tests ────────────────────────────────────

    #[test]
    fn malformed_ethernet_frame_counts_rx_errors() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        mock.enqueue_rx_frame(alloc::vec![0xFF]); // too short for Ethernet header
        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);

        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);
        assert_eq!(device.drain_deferred_rx_errors(), 1);
        // Drain is idempotent.
        assert_eq!(device.drain_deferred_rx_errors(), 0);
    }

    #[test]
    fn malformed_arp_payload_counts_rx_errors() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        // Build a valid Ethernet frame wrapping garbage ARP payload.
        let eth = EthernetRepr {
            src_addr: EthernetAddress(REMOTE_MAC),
            dst_addr: EthernetAddress(DEV_MAC),
            ethertype: EthernetProtocol::Arp,
        };
        let mut frame = alloc::vec![0u8; eth.buffer_len() + 16];
        let mut eth_frame = EthernetFrame::new_unchecked(&mut frame);
        eth.emit(&mut eth_frame);
        // Overwrite ARP payload with garbage that ArpRepr::parse will reject.
        eth_frame.payload_mut()[..16].fill(0xFF);
        mock.enqueue_rx_frame(frame);

        let mut device = make_test_device(mock);
        let mut buffer = test_packet_buffer();
        let ts = Instant::from_millis(0);
        let result = device.recv(InterfaceId::new(1), &mut buffer, ts, &mut |_| {});
        assert_eq!(result, 0);
        // Malformed ARP → rx_errors.  The outer Ethernet frame was valid
        // so deferred_rx_frame_lens also records it.
        assert_eq!(device.drain_deferred_rx_errors(), 1);
        assert!(!device.drain_deferred_rx().is_empty());
    }

    #[test]
    fn pending_buffer_full_counts_tx_drops() {
        let mock = MockEthernetDriver::new(DEV_MAC);
        let mut device = make_test_device(mock);
        let ts = Instant::from_millis(0);

        // Fill the pending buffer — each send to a distinct unknown
        // neighbour triggers one ARP request and enqueues the packet.
        // After N fills the buffer the next send increments tx_drops.
        let base = Ipv4Address::new(10, 0, 0, 100);
        for i in 0..crate::consts::ETHERNET_MAX_PENDING_PACKETS {
            let ip = IpAddress::Ipv4(Ipv4Address::from(u32::from(base) + i as u32));
            let result = device.send(ip, &[0u8; 64], ts);
            assert_eq!(result, 0, "packet {i} should be queued, not dropped");
            // Drain deferred TX (ARP requests) so they don't accumulate
            // and complicate assertions.
            let _ = device.drain_deferred_tx();
        }

        // Buffer is full — this send must increment tx_drops.
        let extra_ip = IpAddress::Ipv4(Ipv4Address::new(10, 0, 1, 1));
        let result = device.send(extra_ip, &[0u8; 64], ts);
        assert_eq!(result, 0);
        assert_eq!(device.drain_deferred_tx_drops(), 1);
        assert_eq!(device.drain_deferred_tx_drops(), 0);
    }

    #[test]
    fn compatibility_send_counts_transient_backpressure_as_a_drop() {
        let mut mock = MockEthernetDriver::new(DEV_MAC);
        mock.tx_alloc_fail = true;

        let mut device = make_test_device(mock);
        let ts = Instant::from_millis(0);

        // The compatibility send path cannot retain the caller's packet.
        let broadcast = IpAddress::Ipv4(Ipv4Address::BROADCAST);
        let packet = raw_tcp_packet();
        let result = device.send(broadcast, &packet, ts);
        assert_eq!(result, 0);
        assert_eq!(device.drain_deferred_tx_errors(), 0);
        assert_eq!(device.drain_deferred_tx_drops(), 1);
        assert_eq!(device.drain_deferred_tx_drops(), 0);
        // No bytes/packets were counted on failure.
        let tx_lens = device.drain_deferred_tx();
        assert!(tx_lens.is_empty());
    }
}