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
//! 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, 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, Ipv4Cidr,
},
};
use crate::{
config::InterfaceId,
consts::{ETHERNET_MAX_PENDING_PACKETS, STANDARD_MTU},
device::{ArpEntry, Device, ETH_ZLEN, EthernetFramePort, ProtocolEthernetFrame},
};
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>,
/// 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,
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())
}
/// 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, or 0 on
/// failure.
fn send_to<F>(
inner: &mut dyn EthernetFramePort,
dst: EthernetAddress,
size: usize,
f: F,
proto: EthernetProtocol,
) -> 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 tx_buf = match ProtocolEthernetFrame::new(total_frame_len) {
Ok(buf) => buf,
Err(err) => {
warn!("{}: alloc_tx_buffer failed: {:?}", inner.device_name(), err);
return 0;
}
};
let mut frame = EthernetFrame::new_unchecked(tx_buf.packet_mut());
repr.emit(&mut frame);
f(frame.payload_mut());
trace!(
"SEND {} bytes: {:02X?}",
tx_buf.packet_len(),
tx_buf.packet()
);
if let Err(err) = inner.transmit(&tx_buf) {
warn!("{}: transmit failed: {:?}", inner.device_name(), err);
0
} else {
wire_len
}
}
/// 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 => {
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 request_arp(&mut self, target_ip: IpAddress, timestamp: Instant) -> bool {
let IpAddress::Ipv4(target_ipv4) = target_ip else {
warn!("IPv6 address ARP is not supported: {}", target_ip);
self.deferred_tx_errors += 1;
return false;
};
let Some(ip) = self.ip else {
warn!("cannot request ARP for {target_ipv4}: ethernet IPv4 is not configured");
self.deferred_tx_errors += 1;
return false;
};
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,
);
if arp_frame_len == 0 {
warn!(
"{}: failed to send ARP request for {}",
self.name, target_ipv4
);
self.deferred_tx_errors += 1;
return false;
}
// 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,
},
);
true
}
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,
};
let arp_frame_len = Self::send_to(
&mut *self.inner,
source_hardware_addr,
response.buffer_len(),
|buf| response.emit(&mut ArpPacket::new_unchecked(buf)),
EthernetProtocol::Arp,
);
// ARP replies are successfully transmitted L2 frames — record
// their length so the protocol executor can count them in TX stats.
if arp_frame_len > 0 {
self.deferred_tx_frame_lens.push(arp_frame_len);
} else {
self.deferred_tx_errors += 1;
}
}
// 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
);
let payload_len = payload.len();
let frame_len = Self::send_to(
&mut *self.inner,
mac,
payload_len,
|b| b.copy_from_slice(&payload),
EthernetProtocol::Ipv4,
);
if frame_len > 0 {
self.deferred_tx_frame_lens.push(frame_len);
} else {
self.deferred_tx_errors += 1;
}
}
Action::Refresh(payload) => {
self.neighbors.remove(&next_hop);
// request_arp() internally increments deferred_tx_errors
// on failure. Each Refresh triggers independent
// accounting; repeated failures accumulate.
let _ = self.request_arp(next_hop, now);
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 {
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 send(&mut self, next_hop: IpAddress, packet: &[u8], timestamp: Instant) -> 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 {
let frame_len = Self::send_to(
&mut *self.inner,
EthernetAddress::BROADCAST,
packet.len(),
|buf| buf.copy_from_slice(packet),
EthernetProtocol::Ipv4,
);
if frame_len == 0 {
self.deferred_tx_errors += 1;
}
return frame_len;
}
let need_request = match self.neighbors.get(&next_hop) {
Some(neighbor) if neighbor.expires_at > timestamp => {
let frame_len = Self::send_to(
&mut *self.inner,
neighbor.hardware_address,
packet.len(),
|buf| buf.copy_from_slice(packet),
EthernetProtocol::Ipv4,
);
if frame_len == 0 {
self.deferred_tx_errors += 1;
}
return frame_len;
}
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) {
warn!(
"{}: ARP request failed for {}, dropping packet",
self.name, next_hop
);
// request_arp() internally increments deferred_tx_errors for all
// failure modes (hardware send_to failure, IPv6 not supported,
// IPv4 not configured), so the caller does not add a second counter.
return 0;
}
if self.pending_packets.is_full() {
warn!(
"{}: Pending packets buffer is full, dropping packet",
self.name
);
self.deferred_tx_drops += 1;
return 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 0;
};
dst_buffer.copy_from_slice(packet);
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)
}
fn set_ipv4_addr(&mut self, addr: Option<Ipv4Cidr>) {
self.ip = addr;
self.neighbors.clear();
self.pending_neighbors.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;
use smoltcp::wire::{Ipv4Address, Ipv4Cidr};
use super::*;
use crate::device::{NetDeviceError, NetDeviceResult};
// ── Mock protocol-port infrastructure ──────────────────────────────
/// Minimal protocol frame port for testing EthernetDevice ARP paths.
struct MockEthernetDriver {
mac: [u8; 6],
/// 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,
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 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)
}
}
// ── 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()))
}
/// 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 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, 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, 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, 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 send_to_alloc_failure_counts_tx_errors() {
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);
// Sending to broadcast path — send_to will fail in alloc_tx_buffer.
let broadcast = IpAddress::Ipv4(Ipv4Address::BROADCAST);
let result = device.send(broadcast, &[0u8; 64], ts);
assert_eq!(result, 0);
assert_eq!(device.drain_deferred_tx_errors(), 1);
assert_eq!(device.drain_deferred_tx_errors(), 0);
// No bytes/packets were counted on failure.
let tx_lens = device.drain_deferred_tx();
assert!(tx_lens.is_empty());
}
}