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
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! The Ethernet protocol.

use alloc::vec::Vec;
use core::fmt::Debug;
use core::num::NonZeroU32;
use lock_order::lock::{OrderedLockAccess, OrderedLockRef};

use const_unwrap::const_unwrap_option;
use log::{debug, trace};
use net_types::ethernet::Mac;
use net_types::ip::{GenericOverIp, Ip, IpMarked, Ipv4, Ipv6, Mtu};
use net_types::{MulticastAddr, UnicastAddr, Witness};
use netstack3_base::ref_counted_hash_map::{InsertResult, RefCountedHashSet, RemoveResult};
use netstack3_base::sync::{Mutex, RwLock};
use netstack3_base::{
    trace_duration, BroadcastIpExt, CoreTimerContext, Device, DeviceIdContext, FrameDestination,
    HandleableTimer, LinkDevice, NestedIntoCoreTimerCtx, ReceivableFrameMeta, RecvFrameContext,
    RecvIpFrameMeta, ResourceCounterContext, RngContext, SendFrameError, SendFrameErrorReason,
    SendableFrameMeta, TimerContext, TimerHandler, TracingContext, WeakDeviceIdentifier,
    WrapBroadcastMarker,
};
use netstack3_ip::nud::{
    LinkResolutionContext, NudBindingsTypes, NudHandler, NudState, NudTimerId, NudUserConfig,
};
use netstack3_ip::IpPacketDestination;
use packet::{Buf, BufferMut, Serializer};
use packet_formats::arp::{peek_arp_types, ArpHardwareType, ArpNetworkType};
use packet_formats::ethernet::{
    EtherType, EthernetFrame, EthernetFrameBuilder, EthernetFrameLengthCheck, EthernetIpExt,
    ETHERNET_HDR_LEN_NO_TAG,
};

use crate::internal::arp::{ArpFrameMetadata, ArpPacketHandler, ArpState, ArpTimerId};
use crate::internal::base::{
    DeviceCounters, DeviceLayerTypes, DeviceReceiveFrameSpec, EthernetDeviceCounters,
};
use crate::internal::id::{DeviceId, EthernetDeviceId};
use crate::internal::queue::tx::{
    BufVecU8Allocator, TransmitQueue, TransmitQueueHandler, TransmitQueueState,
};
use crate::internal::queue::{DequeueState, TransmitQueueFrameError};
use crate::internal::socket::{
    DeviceSocketHandler, DeviceSocketMetadata, DeviceSocketSendTypes, EthernetHeaderParams,
    ReceivedFrame,
};
use crate::internal::state::{DeviceStateSpec, IpLinkDeviceState};

const ETHERNET_HDR_LEN_NO_TAG_U32: u32 = ETHERNET_HDR_LEN_NO_TAG as u32;

/// The execution context for an Ethernet device provided by bindings.
pub trait EthernetIpLinkDeviceBindingsContext:
    RngContext + TimerContext + DeviceLayerTypes
{
}
impl<BC: RngContext + TimerContext + DeviceLayerTypes> EthernetIpLinkDeviceBindingsContext for BC {}

/// Provides access to an ethernet device's static state.
pub trait EthernetIpLinkDeviceStaticStateContext: DeviceIdContext<EthernetLinkDevice> {
    /// Calls the function with an immutable reference to the ethernet device's
    /// static state.
    fn with_static_ethernet_device_state<O, F: FnOnce(&StaticEthernetDeviceState) -> O>(
        &mut self,
        device_id: &Self::DeviceId,
        cb: F,
    ) -> O;
}

/// Provides access to an ethernet device's dynamic state.
pub trait EthernetIpLinkDeviceDynamicStateContext<BC: EthernetIpLinkDeviceBindingsContext>:
    EthernetIpLinkDeviceStaticStateContext
{
    /// Calls the function with the ethernet device's static state and immutable
    /// reference to the dynamic state.
    fn with_ethernet_state<
        O,
        F: FnOnce(&StaticEthernetDeviceState, &DynamicEthernetDeviceState) -> O,
    >(
        &mut self,
        device_id: &Self::DeviceId,
        cb: F,
    ) -> O;

    /// Calls the function with the ethernet device's static state and mutable
    /// reference to the dynamic state.
    fn with_ethernet_state_mut<
        O,
        F: FnOnce(&StaticEthernetDeviceState, &mut DynamicEthernetDeviceState) -> O,
    >(
        &mut self,
        device_id: &Self::DeviceId,
        cb: F,
    ) -> O;
}

/// Send an Ethernet frame `body` directly to `dst_mac` with `ether_type`.
pub fn send_as_ethernet_frame_to_dst<S, BC, CC>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &CC::DeviceId,
    dst_mac: Mac,
    body: S,
    ether_type: EtherType,
) -> Result<(), SendFrameError<S>>
where
    S: Serializer,
    S::Buffer: BufferMut,
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>
        + TransmitQueueHandler<EthernetLinkDevice, BC, Meta = ()>
        + ResourceCounterContext<CC::DeviceId, DeviceCounters>,
{
    /// The minimum body length for the Ethernet frame.
    ///
    /// Using a frame length of 0 improves efficiency by avoiding unnecessary
    /// padding at this layer. The expectation is that the implementation of
    /// bindings will add any padding required by the implementation.
    const MIN_BODY_LEN: usize = 0;

    let local_mac = get_mac(core_ctx, device_id);
    let frame = body.encapsulate(EthernetFrameBuilder::new(
        local_mac.get(),
        dst_mac,
        ether_type,
        MIN_BODY_LEN,
    ));
    send_ethernet_frame(core_ctx, bindings_ctx, device_id, frame).map_err(|err| err.into_inner())
}

fn send_ethernet_frame<S, BC, CC>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &CC::DeviceId,
    frame: S,
) -> Result<(), SendFrameError<S>>
where
    S: Serializer,
    S::Buffer: BufferMut,
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>
        + TransmitQueueHandler<EthernetLinkDevice, BC, Meta = ()>
        + ResourceCounterContext<CC::DeviceId, DeviceCounters>,
{
    core_ctx.increment(device_id, |counters| &counters.send_total_frames);
    match TransmitQueueHandler::<EthernetLinkDevice, _>::queue_tx_frame(
        core_ctx,
        bindings_ctx,
        device_id,
        (),
        frame,
    ) {
        Ok(()) => {
            core_ctx.increment(device_id, |counters| &counters.send_frame);
            Ok(())
        }
        Err(TransmitQueueFrameError::NoQueue(err)) => {
            core_ctx.increment(device_id, |counters| &counters.send_dropped_no_queue);
            debug!("device {device_id:?} failed to send frame: {err:?}.");
            Ok(())
        }
        Err(TransmitQueueFrameError::QueueFull(serializer)) => {
            core_ctx.increment(device_id, |counters| &counters.send_queue_full);
            Err(SendFrameError { serializer, error: SendFrameErrorReason::QueueFull })
        }
        Err(TransmitQueueFrameError::SerializeError(err)) => {
            core_ctx.increment(device_id, |counters| &counters.send_serialize_error);
            Err(err.err_into())
        }
    }
}

/// The maximum frame size one ethernet device can send.
///
/// The frame size includes the ethernet header, the data payload, but excludes
/// the 4 bytes from FCS (frame check sequence) as we don't calculate CRC and it
/// is normally handled by the device.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct MaxEthernetFrameSize(NonZeroU32);

impl MaxEthernetFrameSize {
    /// The minimum ethernet frame size.
    ///
    /// We don't care about FCS, so the minimum frame size for us is 64 - 4.
    pub const MIN: MaxEthernetFrameSize =
        MaxEthernetFrameSize(const_unwrap_option(NonZeroU32::new(60)));

    /// Creates from the maximum size of ethernet header and ethernet payload,
    /// checks that it is valid, i.e., larger than the minimum frame size.
    pub const fn new(frame_size: u32) -> Option<Self> {
        if frame_size < Self::MIN.get().get() {
            return None;
        }
        Some(Self(const_unwrap_option(NonZeroU32::new(frame_size))))
    }

    const fn get(&self) -> NonZeroU32 {
        let Self(frame_size) = *self;
        frame_size
    }

    /// Converts the maximum frame size to its corresponding MTU.
    pub const fn as_mtu(&self) -> Mtu {
        // MTU must be positive because of the limit on minimum ethernet frame size
        Mtu::new(self.get().get().saturating_sub(ETHERNET_HDR_LEN_NO_TAG_U32))
    }

    /// Creates the maximum ethernet frame size from MTU.
    pub const fn from_mtu(mtu: Mtu) -> Option<MaxEthernetFrameSize> {
        let frame_size = mtu.get().saturating_add(ETHERNET_HDR_LEN_NO_TAG_U32);
        Self::new(frame_size)
    }
}

/// Base properties to create a new Ethernet device.
#[derive(Debug)]
pub struct EthernetCreationProperties {
    /// The device's MAC address.
    pub mac: UnicastAddr<Mac>,
    /// The maximum frame size this device supports.
    // TODO(https://fxbug.dev/42072516): Add a minimum frame size for all
    // Ethernet devices such that you can't create an `EthernetDeviceState`
    // with a `MaxEthernetFrameSize` smaller than the minimum. The absolute minimum
    // needs to be at least the minimum body size of an Ethernet frame. For
    // IPv6-capable devices, the minimum needs to be higher - the frame size
    // implied by the IPv6 minimum MTU. The easy path is to simply use that
    // frame size as the minimum in all cases, although we may at some point
    // want to figure out how to configure devices which don't support IPv6,
    // and allow smaller frame sizes for those devices.
    pub max_frame_size: MaxEthernetFrameSize,
}

/// Ethernet device state that can change at runtime.
pub struct DynamicEthernetDeviceState {
    /// The value this netstack assumes as the device's maximum frame size.
    max_frame_size: MaxEthernetFrameSize,

    /// Link multicast groups this device has joined.
    /// TODO(https://fxbug.dev/42136929): Plumb this information down to the
    /// device driver.
    link_multicast_groups: RefCountedHashSet<MulticastAddr<Mac>>,
}

impl DynamicEthernetDeviceState {
    fn new(max_frame_size: MaxEthernetFrameSize) -> Self {
        Self { max_frame_size, link_multicast_groups: Default::default() }
    }
}

/// Ethernet device state that is fixed after creation.
pub struct StaticEthernetDeviceState {
    /// Mac address of the device this state is for.
    mac: UnicastAddr<Mac>,

    /// The maximum frame size allowed by the hardware.
    max_frame_size: MaxEthernetFrameSize,
}

/// The state associated with an Ethernet device.
pub struct EthernetDeviceState<BT: NudBindingsTypes<EthernetLinkDevice>> {
    /// Ethernet device counters.
    pub counters: EthernetDeviceCounters,
    /// Immutable Ethernet device state.
    pub static_state: StaticEthernetDeviceState,
    /// Ethernet device transmit queue.
    pub tx_queue: TransmitQueue<(), Buf<Vec<u8>>, BufVecU8Allocator>,
    ipv4_arp: Mutex<ArpState<EthernetLinkDevice, BT>>,
    ipv6_nud: Mutex<NudState<Ipv6, EthernetLinkDevice, BT>>,
    ipv4_nud_config: RwLock<IpMarked<Ipv4, NudUserConfig>>,
    ipv6_nud_config: RwLock<IpMarked<Ipv6, NudUserConfig>>,
    dynamic_state: RwLock<DynamicEthernetDeviceState>,
}

impl<BT: DeviceLayerTypes, I: Ip> OrderedLockAccess<IpMarked<I, NudUserConfig>>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = RwLock<IpMarked<I, NudUserConfig>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(I::map_ip(
            (),
            |()| &self.link.ipv4_nud_config,
            |()| &self.link.ipv6_nud_config,
        ))
    }
}

impl<BT: DeviceLayerTypes> OrderedLockAccess<DynamicEthernetDeviceState>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = RwLock<DynamicEthernetDeviceState>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.dynamic_state)
    }
}

impl<BT: DeviceLayerTypes> OrderedLockAccess<NudState<Ipv6, EthernetLinkDevice, BT>>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = Mutex<NudState<Ipv6, EthernetLinkDevice, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.ipv6_nud)
    }
}

impl<BT: DeviceLayerTypes> OrderedLockAccess<ArpState<EthernetLinkDevice, BT>>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = Mutex<ArpState<EthernetLinkDevice, BT>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.ipv4_arp)
    }
}

impl<BT: DeviceLayerTypes>
    OrderedLockAccess<TransmitQueueState<(), Buf<Vec<u8>>, BufVecU8Allocator>>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = Mutex<TransmitQueueState<(), Buf<Vec<u8>>, BufVecU8Allocator>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.tx_queue.queue)
    }
}

impl<BT: DeviceLayerTypes> OrderedLockAccess<DequeueState<(), Buf<Vec<u8>>>>
    for IpLinkDeviceState<EthernetLinkDevice, BT>
{
    type Lock = Mutex<DequeueState<(), Buf<Vec<u8>>>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.tx_queue.deque)
    }
}

/// A timer ID for Ethernet devices.
///
/// `D` is the type of device ID that identifies different Ethernet devices.
#[derive(Clone, Eq, PartialEq, Debug, Hash, GenericOverIp)]
#[generic_over_ip()]
#[allow(missing_docs)]
pub enum EthernetTimerId<D: WeakDeviceIdentifier> {
    Arp(ArpTimerId<EthernetLinkDevice, D>),
    Nudv6(NudTimerId<Ipv6, EthernetLinkDevice, D>),
}

impl<I: Ip, D: WeakDeviceIdentifier> From<NudTimerId<I, EthernetLinkDevice, D>>
    for EthernetTimerId<D>
{
    fn from(id: NudTimerId<I, EthernetLinkDevice, D>) -> EthernetTimerId<D> {
        I::map_ip(id, EthernetTimerId::Arp, EthernetTimerId::Nudv6)
    }
}

impl<CC, BC> HandleableTimer<CC, BC> for EthernetTimerId<CC::WeakDeviceId>
where
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>
        + TimerHandler<BC, NudTimerId<Ipv6, EthernetLinkDevice, CC::WeakDeviceId>>
        + TimerHandler<BC, ArpTimerId<EthernetLinkDevice, CC::WeakDeviceId>>,
{
    fn handle(self, core_ctx: &mut CC, bindings_ctx: &mut BC, timer: BC::UniqueTimerId) {
        match self {
            EthernetTimerId::Arp(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
            EthernetTimerId::Nudv6(id) => core_ctx.handle_timer(bindings_ctx, id, timer),
        }
    }
}

/// Send an IP packet in an Ethernet frame.
///
/// `send_ip_frame` accepts a device ID, a local IP address, and a
/// serializer. It computes the routing information, serializes
/// the serializer, and sends the resulting buffer in a new Ethernet
/// frame.
pub fn send_ip_frame<BC, CC, I, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &CC::DeviceId,
    destination: IpPacketDestination<I, &DeviceId<BC>>,
    body: S,
) -> Result<(), SendFrameError<S>>
where
    BC: EthernetIpLinkDeviceBindingsContext + LinkResolutionContext<EthernetLinkDevice>,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>
        + NudHandler<I, EthernetLinkDevice, BC>
        + TransmitQueueHandler<EthernetLinkDevice, BC, Meta = ()>
        + ResourceCounterContext<CC::DeviceId, DeviceCounters>,
    I: EthernetIpExt + BroadcastIpExt,
    S: Serializer,
    S::Buffer: BufferMut,
{
    core_ctx.increment(device_id, DeviceCounters::send_frame::<I>);

    trace!("ethernet::send_ip_frame: destination = {:?}; device = {:?}", destination, device_id);

    let body = body.with_size_limit(get_mtu(core_ctx, device_id).get() as usize);

    match destination {
        IpPacketDestination::Broadcast(marker) => {
            I::map_ip::<_, ()>(
                WrapBroadcastMarker(marker),
                |WrapBroadcastMarker(())| (),
                |WrapBroadcastMarker(never)| match never {},
            );
            send_as_ethernet_frame_to_dst(
                core_ctx,
                bindings_ctx,
                device_id,
                Mac::BROADCAST,
                body,
                I::ETHER_TYPE,
            )
        }
        IpPacketDestination::Multicast(multicast_ip) => send_as_ethernet_frame_to_dst(
            core_ctx,
            bindings_ctx,
            device_id,
            Mac::from(&multicast_ip),
            body,
            I::ETHER_TYPE,
        ),
        IpPacketDestination::Neighbor(ip) => NudHandler::<I, _, _>::send_ip_packet_to_neighbor(
            core_ctx,
            bindings_ctx,
            device_id,
            ip,
            body,
        ),
        IpPacketDestination::Loopback(_) => {
            unreachable!("Loopback packets must be delivered through the loopback device")
        }
    }
    .map_err(|e| e.into_inner())
}

/// Metadata for received ethernet frames.
pub struct RecvEthernetFrameMeta<D> {
    /// The device a frame was received on.
    pub device_id: D,
}

impl DeviceReceiveFrameSpec for EthernetLinkDevice {
    type FrameMetadata<D> = RecvEthernetFrameMeta<D>;
}

impl<CC, BC> ReceivableFrameMeta<CC, BC> for RecvEthernetFrameMeta<CC::DeviceId>
where
    BC: EthernetIpLinkDeviceBindingsContext + TracingContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>
        + RecvFrameContext<RecvIpFrameMeta<CC::DeviceId, Ipv4>, BC>
        + RecvFrameContext<RecvIpFrameMeta<CC::DeviceId, Ipv6>, BC>
        + ArpPacketHandler<EthernetLinkDevice, BC>
        + DeviceSocketHandler<EthernetLinkDevice, BC>
        + ResourceCounterContext<CC::DeviceId, DeviceCounters>
        + ResourceCounterContext<CC::DeviceId, EthernetDeviceCounters>,
{
    fn receive_meta<B: BufferMut + Debug>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        mut buffer: B,
    ) {
        trace_duration!(bindings_ctx, c"device::ethernet::receive_frame");
        let Self { device_id } = self;
        trace!("ethernet::receive_frame: device_id = {:?}", device_id);
        core_ctx.increment(&device_id, |counters: &DeviceCounters| &counters.recv_frame);
        // NOTE(joshlf): We do not currently validate that the Ethernet frame
        // satisfies the minimum length requirement. We expect that if this
        // requirement is necessary (due to requirements of the physical medium),
        // the driver or hardware will have checked it, and that if this requirement
        // is not necessary, it is acceptable for us to operate on a smaller
        // Ethernet frame. If this becomes insufficient in the future, we may want
        // to consider making this behavior configurable (at compile time, at
        // runtime on a global basis, or at runtime on a per-device basis).
        let (ethernet, whole_frame) = if let Ok(frame) =
            buffer.parse_with_view::<_, EthernetFrame<_>>(EthernetFrameLengthCheck::NoCheck)
        {
            frame
        } else {
            core_ctx.increment(&device_id, |counters: &DeviceCounters| &counters.recv_parse_error);
            trace!("ethernet::receive_frame: failed to parse ethernet frame");
            return;
        };

        let dst = ethernet.dst_mac();

        let frame_dst = core_ctx.with_static_ethernet_device_state(&device_id, |static_state| {
            FrameDestination::from_dest(dst, static_state.mac.get())
        });

        let ethertype = ethernet.ethertype();

        core_ctx.handle_frame(
            bindings_ctx,
            &device_id,
            ReceivedFrame::from_ethernet(ethernet, frame_dst).into(),
            whole_frame,
        );

        match ethertype {
            Some(EtherType::Arp) => {
                let types = if let Ok(types) = peek_arp_types(buffer.as_ref()) {
                    types
                } else {
                    return;
                };
                match types {
                    (ArpHardwareType::Ethernet, ArpNetworkType::Ipv4) => {
                        ArpPacketHandler::handle_packet(
                            core_ctx,
                            bindings_ctx,
                            device_id,
                            frame_dst,
                            buffer,
                        )
                    }
                }
            }
            Some(EtherType::Ipv4) => {
                core_ctx.increment(&device_id, |counters: &DeviceCounters| {
                    &counters.recv_ipv4_delivered
                });
                core_ctx.receive_frame(
                    bindings_ctx,
                    RecvIpFrameMeta::<_, Ipv4>::new(device_id, Some(frame_dst)),
                    buffer,
                )
            }
            Some(EtherType::Ipv6) => {
                core_ctx.increment(&device_id, |counters: &DeviceCounters| {
                    &counters.recv_ipv6_delivered
                });
                core_ctx.receive_frame(
                    bindings_ctx,
                    RecvIpFrameMeta::<_, Ipv6>::new(device_id, Some(frame_dst)),
                    buffer,
                )
            }
            Some(EtherType::Other(_)) => {
                core_ctx.increment(&device_id, |counters: &EthernetDeviceCounters| {
                    &counters.recv_unsupported_ethertype
                });
            }
            None => {
                core_ctx.increment(&device_id, |counters: &EthernetDeviceCounters| {
                    &counters.recv_no_ethertype
                });
            }
        }
    }
}

/// Add `device_id` to a link multicast group `multicast_addr`.
///
/// Calling `join_link_multicast` with the same `device_id` and `multicast_addr`
/// is completely safe. A counter will be kept for the number of times
/// `join_link_multicast` has been called with the same `device_id` and
/// `multicast_addr` pair. To completely leave a multicast group,
/// [`leave_link_multicast`] must be called the same number of times
/// `join_link_multicast` has been called for the same `device_id` and
/// `multicast_addr` pair. The first time `join_link_multicast` is called for a
/// new `device` and `multicast_addr` pair, the device will actually join the
/// multicast group.
///
/// `join_link_multicast` is different from [`join_ip_multicast`] as
/// `join_link_multicast` joins an L2 multicast group, whereas
/// `join_ip_multicast` joins an L3 multicast group.
pub fn join_link_multicast<
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>,
>(
    core_ctx: &mut CC,
    _bindings_ctx: &mut BC,
    device_id: &CC::DeviceId,
    multicast_addr: MulticastAddr<Mac>,
) {
    core_ctx.with_ethernet_state_mut(device_id, |_static_state, dynamic_state| {
        let groups = &mut dynamic_state.link_multicast_groups;

        match groups.insert(multicast_addr) {
            InsertResult::Inserted(()) => {
                trace!(
                    "ethernet::join_link_multicast: joining link multicast {:?}",
                    multicast_addr
                );
            }
            InsertResult::AlreadyPresent => {
                trace!(
                    "ethernet::join_link_multicast: already joined link multicast {:?}",
                    multicast_addr,
                );
            }
        }
    })
}

/// Remove `device_id` from a link multicast group `multicast_addr`.
///
/// `leave_link_multicast` will attempt to remove `device_id` from the multicast
/// group `multicast_addr`. `device_id` may have "joined" the same multicast
/// address multiple times, so `device_id` will only leave the multicast group
/// once `leave_ip_multicast` has been called for each corresponding
/// [`join_link_multicast`]. That is, if `join_link_multicast` gets called 3
/// times and `leave_link_multicast` gets called two times (after all 3
/// `join_link_multicast` calls), `device_id` will still be in the multicast
/// group until the next (final) call to `leave_link_multicast`.
///
/// `leave_link_multicast` is different from [`leave_ip_multicast`] as
/// `leave_link_multicast` leaves an L2 multicast group, whereas
/// `leave_ip_multicast` leaves an L3 multicast group.
///
/// # Panics
///
/// If `device_id` is not in the multicast group `multicast_addr`.
pub fn leave_link_multicast<
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>,
>(
    core_ctx: &mut CC,
    _bindings_ctx: &mut BC,
    device_id: &CC::DeviceId,
    multicast_addr: MulticastAddr<Mac>,
) {
    core_ctx.with_ethernet_state_mut(device_id, |_static_state, dynamic_state| {
        let groups = &mut dynamic_state.link_multicast_groups;

        match groups.remove(multicast_addr) {
            RemoveResult::Removed(()) => {
                trace!("ethernet::leave_link_multicast: leaving link multicast {:?}", multicast_addr);
            }
            RemoveResult::StillPresent => {
                trace!(
                    "ethernet::leave_link_multicast: not leaving link multicast {:?} as there are still listeners for it",
                    multicast_addr,
                );
            }
            RemoveResult::NotPresent => {
                panic!(
                    "ethernet::leave_link_multicast: device {:?} has not yet joined link multicast {:?}",
                    device_id,
                    multicast_addr,
                );
            }
        }
    })
}

/// Get the MTU associated with this device.
pub fn get_mtu<
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>,
>(
    core_ctx: &mut CC,
    device_id: &CC::DeviceId,
) -> Mtu {
    core_ctx.with_ethernet_state(device_id, |_static_state, dynamic_state| {
        dynamic_state.max_frame_size.as_mtu()
    })
}

/// Enables a blanket implementation of [`SendableFrameData`] for
/// [`ArpFrameMetadata`].
///
/// Implementing this marker trait for a type enables a blanket implementation
/// of `SendableFrameData` given the other requirements are met.
pub trait UseArpFrameMetadataBlanket {}

impl<
        BC: EthernetIpLinkDeviceBindingsContext,
        CC: EthernetIpLinkDeviceDynamicStateContext<BC>
            + TransmitQueueHandler<EthernetLinkDevice, BC, Meta = ()>
            + ResourceCounterContext<CC::DeviceId, DeviceCounters>
            + UseArpFrameMetadataBlanket,
    > SendableFrameMeta<CC, BC> for ArpFrameMetadata<EthernetLinkDevice, CC::DeviceId>
{
    fn send_meta<S>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        body: S,
    ) -> Result<(), SendFrameError<S>>
    where
        S: Serializer,
        S::Buffer: BufferMut,
    {
        let Self { device_id, dst_addr } = self;
        send_as_ethernet_frame_to_dst(
            core_ctx,
            bindings_ctx,
            &device_id,
            dst_addr,
            body,
            EtherType::Arp,
        )
    }
}

impl DeviceSocketSendTypes for EthernetLinkDevice {
    /// When `None`, data will be sent as a raw Ethernet frame without any
    /// system-applied headers.
    type Metadata = Option<EthernetHeaderParams>;
}

impl<
        BC: EthernetIpLinkDeviceBindingsContext,
        CC: EthernetIpLinkDeviceDynamicStateContext<BC>
            + TransmitQueueHandler<EthernetLinkDevice, BC, Meta = ()>
            + ResourceCounterContext<CC::DeviceId, DeviceCounters>,
    > SendableFrameMeta<CC, BC> for DeviceSocketMetadata<EthernetLinkDevice, EthernetDeviceId<BC>>
where
    CC: DeviceIdContext<EthernetLinkDevice, DeviceId = EthernetDeviceId<BC>>,
{
    fn send_meta<S>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        body: S,
    ) -> Result<(), SendFrameError<S>>
    where
        S: Serializer,
        S::Buffer: BufferMut,
    {
        let Self { device_id, metadata } = self;
        match metadata {
            Some(EthernetHeaderParams { dest_addr, protocol }) => send_as_ethernet_frame_to_dst(
                core_ctx,
                bindings_ctx,
                &device_id,
                dest_addr,
                body,
                protocol,
            ),
            None => send_ethernet_frame(core_ctx, bindings_ctx, &device_id, body),
        }
    }
}

/// Gets `device_id`'s MAC address.
pub fn get_mac<
    'a,
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>,
>(
    core_ctx: &'a mut CC,
    device_id: &CC::DeviceId,
) -> UnicastAddr<Mac> {
    core_ctx.with_static_ethernet_device_state(device_id, |state| state.mac)
}

/// Sets `device_id`'s MTU.
pub fn set_mtu<
    BC: EthernetIpLinkDeviceBindingsContext,
    CC: EthernetIpLinkDeviceDynamicStateContext<BC>,
>(
    core_ctx: &mut CC,
    device_id: &CC::DeviceId,
    mtu: Mtu,
) {
    core_ctx.with_ethernet_state_mut(device_id, |static_state, dynamic_state| {
        if let Some(mut frame_size ) = MaxEthernetFrameSize::from_mtu(mtu) {
            // If `frame_size` is greater than what the device supports, set it
            // to maximum frame size the device supports.
            if frame_size > static_state.max_frame_size {
                trace!("ethernet::ndp_device::set_mtu: MTU of {:?} is greater than the device {:?}'s max MTU of {:?}, using device's max MTU instead", mtu, device_id, static_state.max_frame_size.as_mtu());
                frame_size = static_state.max_frame_size;
            }
            trace!("ethernet::ndp_device::set_mtu: setting link MTU to {:?}", mtu);
            dynamic_state.max_frame_size = frame_size;
        }
    })
}

/// An implementation of the [`LinkDevice`] trait for Ethernet devices.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum EthernetLinkDevice {}

impl Device for EthernetLinkDevice {}

impl LinkDevice for EthernetLinkDevice {
    type Address = Mac;
}

impl DeviceStateSpec for EthernetLinkDevice {
    type Link<BT: DeviceLayerTypes> = EthernetDeviceState<BT>;
    type External<BT: DeviceLayerTypes> = BT::EthernetDeviceState;
    type CreationProperties = EthernetCreationProperties;
    type Counters = EthernetDeviceCounters;
    type TimerId<D: WeakDeviceIdentifier> = EthernetTimerId<D>;

    fn new_link_state<
        CC: CoreTimerContext<Self::TimerId<CC::WeakDeviceId>, BC> + DeviceIdContext<Self>,
        BC: DeviceLayerTypes + TimerContext,
    >(
        bindings_ctx: &mut BC,
        self_id: CC::WeakDeviceId,
        EthernetCreationProperties { mac, max_frame_size }: Self::CreationProperties,
    ) -> Self::Link<BC> {
        let ipv4_arp = Mutex::new(ArpState::new::<_, NestedIntoCoreTimerCtx<CC, _>>(
            bindings_ctx,
            self_id.clone(),
        ));
        let ipv6_nud =
            Mutex::new(NudState::new::<_, NestedIntoCoreTimerCtx<CC, _>>(bindings_ctx, self_id));
        EthernetDeviceState {
            counters: Default::default(),
            ipv4_arp,
            ipv6_nud,
            ipv4_nud_config: Default::default(),
            ipv6_nud_config: Default::default(),
            static_state: StaticEthernetDeviceState { mac, max_frame_size },
            dynamic_state: RwLock::new(DynamicEthernetDeviceState::new(max_frame_size)),
            tx_queue: Default::default(),
        }
    }
    const IS_LOOPBACK: bool = false;
    const DEBUG_TYPE: &'static str = "Ethernet";
}

#[cfg(any(test, feature = "testutils"))]
pub(crate) mod testutil {
    use super::*;

    /// The mimum implied maximum Ethernet frame size for IPv6.
    pub const IPV6_MIN_IMPLIED_MAX_FRAME_SIZE: MaxEthernetFrameSize =
        const_unwrap::const_unwrap_option(MaxEthernetFrameSize::from_mtu(Ipv6::MINIMUM_LINK_MTU));
}

#[cfg(test)]
mod tests {
    use alloc::vec;
    use core::convert::Infallible as Never;

    use net_types::ip::{Ipv4Addr, Ipv6Addr};
    use net_types::SpecifiedAddr;
    use netstack3_base::testutil::{FakeDeviceId, FakeInstant, FakeWeakDeviceId, TEST_ADDRS_V4};
    use netstack3_base::{CounterContext, CtxPair, IntoCoreTimerCtx};
    use netstack3_ip::nud::{
        self, DelegateNudContext, DynamicNeighborUpdateSource, NeighborApi, UseDelegateNudContext,
    };
    use packet_formats::testutil::parse_ethernet_frame;

    use super::*;
    use crate::internal::arp::{
        ArpConfigContext, ArpContext, ArpCounters, ArpNudCtx, ArpSenderContext,
    };
    use crate::internal::base::DeviceSendFrameError;
    use crate::internal::ethernet::testutil::IPV6_MIN_IMPLIED_MAX_FRAME_SIZE;
    use crate::internal::queue::tx::{
        TransmitQueueBindingsContext, TransmitQueueCommon, TransmitQueueContext,
    };
    use crate::internal::socket::{Frame, ParseSentFrameError, SentFrame};

    struct FakeEthernetCtx {
        static_state: StaticEthernetDeviceState,
        dynamic_state: DynamicEthernetDeviceState,
        tx_queue: TransmitQueueState<(), Buf<Vec<u8>>, BufVecU8Allocator>,
        counters: DeviceCounters,
        per_device_counters: DeviceCounters,
        ethernet_counters: EthernetDeviceCounters,
        arp_counters: ArpCounters,
    }

    impl FakeEthernetCtx {
        fn new(mac: UnicastAddr<Mac>, max_frame_size: MaxEthernetFrameSize) -> FakeEthernetCtx {
            FakeEthernetCtx {
                static_state: StaticEthernetDeviceState { max_frame_size, mac },
                dynamic_state: DynamicEthernetDeviceState::new(max_frame_size),
                tx_queue: Default::default(),
                counters: Default::default(),
                per_device_counters: Default::default(),
                ethernet_counters: Default::default(),
                arp_counters: Default::default(),
            }
        }
    }

    type FakeBindingsCtx = netstack3_base::testutil::FakeBindingsCtx<
        EthernetTimerId<FakeWeakDeviceId<FakeDeviceId>>,
        nud::Event<Mac, FakeDeviceId, Ipv4, FakeInstant>,
        (),
        (),
    >;

    type FakeInnerCtx =
        netstack3_base::testutil::FakeCoreCtx<FakeEthernetCtx, FakeDeviceId, FakeDeviceId>;

    struct FakeCoreCtx {
        arp_state: ArpState<EthernetLinkDevice, FakeBindingsCtx>,
        inner: FakeInnerCtx,
    }

    fn new_context() -> CtxPair<FakeCoreCtx, FakeBindingsCtx> {
        CtxPair::with_default_bindings_ctx(|bindings_ctx| FakeCoreCtx {
            arp_state: ArpState::new::<_, IntoCoreTimerCtx>(
                bindings_ctx,
                FakeWeakDeviceId(FakeDeviceId),
            ),
            inner: FakeInnerCtx::with_state(FakeEthernetCtx::new(
                TEST_ADDRS_V4.local_mac,
                IPV6_MIN_IMPLIED_MAX_FRAME_SIZE,
            )),
        })
    }

    impl DeviceSocketHandler<EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtx {
        fn handle_frame(
            &mut self,
            bindings_ctx: &mut FakeBindingsCtx,
            device: &Self::DeviceId,
            frame: Frame<&[u8]>,
            whole_frame: &[u8],
        ) {
            self.inner.handle_frame(bindings_ctx, device, frame, whole_frame)
        }
    }

    impl CounterContext<DeviceCounters> for FakeCoreCtx {
        fn with_counters<O, F: FnOnce(&DeviceCounters) -> O>(&self, cb: F) -> O {
            cb(&self.inner.state.counters)
        }
    }

    impl CounterContext<DeviceCounters> for FakeInnerCtx {
        fn with_counters<O, F: FnOnce(&DeviceCounters) -> O>(&self, cb: F) -> O {
            cb(&self.state.counters)
        }
    }

    impl ResourceCounterContext<FakeDeviceId, DeviceCounters> for FakeCoreCtx {
        fn with_per_resource_counters<O, F: FnOnce(&DeviceCounters) -> O>(
            &mut self,
            &FakeDeviceId: &FakeDeviceId,
            cb: F,
        ) -> O {
            cb(&self.inner.state.per_device_counters)
        }
    }

    impl ResourceCounterContext<FakeDeviceId, DeviceCounters> for FakeInnerCtx {
        fn with_per_resource_counters<O, F: FnOnce(&DeviceCounters) -> O>(
            &mut self,
            &FakeDeviceId: &FakeDeviceId,
            cb: F,
        ) -> O {
            cb(&self.state.per_device_counters)
        }
    }

    impl CounterContext<EthernetDeviceCounters> for FakeCoreCtx {
        fn with_counters<O, F: FnOnce(&EthernetDeviceCounters) -> O>(&self, cb: F) -> O {
            cb(&self.inner.state.ethernet_counters)
        }
    }

    impl CounterContext<EthernetDeviceCounters> for FakeInnerCtx {
        fn with_counters<O, F: FnOnce(&EthernetDeviceCounters) -> O>(&self, cb: F) -> O {
            cb(&self.state.ethernet_counters)
        }
    }

    impl DeviceSocketHandler<EthernetLinkDevice, FakeBindingsCtx> for FakeInnerCtx {
        fn handle_frame(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            _device: &Self::DeviceId,
            _frame: Frame<&[u8]>,
            _whole_frame: &[u8],
        ) {
            // No-op: don't deliver frames.
        }
    }

    impl EthernetIpLinkDeviceStaticStateContext for FakeCoreCtx {
        fn with_static_ethernet_device_state<O, F: FnOnce(&StaticEthernetDeviceState) -> O>(
            &mut self,
            device_id: &FakeDeviceId,
            cb: F,
        ) -> O {
            self.inner.with_static_ethernet_device_state(device_id, cb)
        }
    }

    impl EthernetIpLinkDeviceStaticStateContext for FakeInnerCtx {
        fn with_static_ethernet_device_state<O, F: FnOnce(&StaticEthernetDeviceState) -> O>(
            &mut self,
            &FakeDeviceId: &FakeDeviceId,
            cb: F,
        ) -> O {
            cb(&self.state.static_state)
        }
    }

    impl EthernetIpLinkDeviceDynamicStateContext<FakeBindingsCtx> for FakeCoreCtx {
        fn with_ethernet_state<
            O,
            F: FnOnce(&StaticEthernetDeviceState, &DynamicEthernetDeviceState) -> O,
        >(
            &mut self,
            device_id: &FakeDeviceId,
            cb: F,
        ) -> O {
            self.inner.with_ethernet_state(device_id, cb)
        }

        fn with_ethernet_state_mut<
            O,
            F: FnOnce(&StaticEthernetDeviceState, &mut DynamicEthernetDeviceState) -> O,
        >(
            &mut self,
            device_id: &FakeDeviceId,
            cb: F,
        ) -> O {
            self.inner.with_ethernet_state_mut(device_id, cb)
        }
    }

    impl EthernetIpLinkDeviceDynamicStateContext<FakeBindingsCtx> for FakeInnerCtx {
        fn with_ethernet_state<
            O,
            F: FnOnce(&StaticEthernetDeviceState, &DynamicEthernetDeviceState) -> O,
        >(
            &mut self,
            &FakeDeviceId: &FakeDeviceId,
            cb: F,
        ) -> O {
            let FakeEthernetCtx { static_state, dynamic_state, .. } = &self.state;
            cb(static_state, dynamic_state)
        }

        fn with_ethernet_state_mut<
            O,
            F: FnOnce(&StaticEthernetDeviceState, &mut DynamicEthernetDeviceState) -> O,
        >(
            &mut self,
            &FakeDeviceId: &FakeDeviceId,
            cb: F,
        ) -> O {
            let FakeEthernetCtx { static_state, dynamic_state, .. } = &mut self.state;
            cb(static_state, dynamic_state)
        }
    }

    impl NudHandler<Ipv6, EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtx {
        fn handle_neighbor_update(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            _device_id: &Self::DeviceId,
            _neighbor: SpecifiedAddr<Ipv6Addr>,
            _link_addr: Mac,
            _is_confirmation: DynamicNeighborUpdateSource,
        ) {
            unimplemented!()
        }

        fn flush(&mut self, _bindings_ctx: &mut FakeBindingsCtx, _device_id: &Self::DeviceId) {
            unimplemented!()
        }

        fn send_ip_packet_to_neighbor<S>(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            _device_id: &Self::DeviceId,
            _neighbor: SpecifiedAddr<Ipv6Addr>,
            _body: S,
        ) -> Result<(), SendFrameError<S>> {
            unimplemented!()
        }
    }

    struct FakeCoreCtxWithDeviceId<'a> {
        core_ctx: &'a mut FakeInnerCtx,
        device_id: &'a FakeDeviceId,
    }

    impl<'a> DeviceIdContext<EthernetLinkDevice> for FakeCoreCtxWithDeviceId<'a> {
        type DeviceId = FakeDeviceId;
        type WeakDeviceId = FakeWeakDeviceId<FakeDeviceId>;
    }

    impl<'a> ArpConfigContext for FakeCoreCtxWithDeviceId<'a> {
        fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O {
            cb(&NudUserConfig::default())
        }
    }

    impl UseArpFrameMetadataBlanket for FakeCoreCtx {}

    impl ArpContext<EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtx {
        type ConfigCtx<'a> = FakeCoreCtxWithDeviceId<'a>;

        type ArpSenderCtx<'a> = FakeCoreCtxWithDeviceId<'a>;

        fn with_arp_state_mut_and_sender_ctx<
            O,
            F: FnOnce(
                &mut ArpState<EthernetLinkDevice, FakeBindingsCtx>,
                &mut Self::ArpSenderCtx<'_>,
            ) -> O,
        >(
            &mut self,
            device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            let Self { arp_state, inner } = self;
            cb(arp_state, &mut FakeCoreCtxWithDeviceId { core_ctx: inner, device_id })
        }

        fn get_protocol_addr(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            _device_id: &Self::DeviceId,
        ) -> Option<Ipv4Addr> {
            unimplemented!()
        }

        fn get_hardware_addr(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            _device_id: &Self::DeviceId,
        ) -> UnicastAddr<Mac> {
            self.inner.state.static_state.mac
        }

        fn with_arp_state_mut<
            O,
            F: FnOnce(
                &mut ArpState<EthernetLinkDevice, FakeBindingsCtx>,
                &mut Self::ConfigCtx<'_>,
            ) -> O,
        >(
            &mut self,
            device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            let Self { arp_state, inner } = self;
            cb(arp_state, &mut FakeCoreCtxWithDeviceId { core_ctx: inner, device_id })
        }

        fn with_arp_state<O, F: FnOnce(&ArpState<EthernetLinkDevice, FakeBindingsCtx>) -> O>(
            &mut self,
            FakeDeviceId: &Self::DeviceId,
            cb: F,
        ) -> O {
            cb(&mut self.arp_state)
        }
    }

    impl UseDelegateNudContext for FakeCoreCtx {}
    impl DelegateNudContext<Ipv4> for FakeCoreCtx {
        type Delegate<T> = ArpNudCtx<T>;
    }

    impl ArpConfigContext for FakeInnerCtx {
        fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O {
            cb(&NudUserConfig::default())
        }
    }

    impl<'a> ArpSenderContext<EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtxWithDeviceId<'a> {
        fn send_ip_packet_to_neighbor_link_addr<S>(
            &mut self,
            bindings_ctx: &mut FakeBindingsCtx,
            link_addr: Mac,
            body: S,
        ) -> Result<(), SendFrameError<S>>
        where
            S: Serializer,
            S::Buffer: BufferMut,
        {
            let Self { core_ctx, device_id } = self;
            send_as_ethernet_frame_to_dst(
                *core_ctx,
                bindings_ctx,
                device_id,
                link_addr,
                body,
                EtherType::Ipv4,
            )
        }
    }

    impl TransmitQueueBindingsContext<FakeDeviceId> for FakeBindingsCtx {
        fn wake_tx_task(&mut self, FakeDeviceId: &FakeDeviceId) {
            unimplemented!("unused by tests")
        }
    }

    impl TransmitQueueCommon<EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtx {
        type Meta = ();
        type Allocator = BufVecU8Allocator;
        type Buffer = Buf<Vec<u8>>;
        type DequeueContext = Never;

        fn parse_outgoing_frame<'a>(
            buf: &'a [u8],
            meta: &'a Self::Meta,
        ) -> Result<SentFrame<&'a [u8]>, ParseSentFrameError> {
            FakeInnerCtx::parse_outgoing_frame(buf, meta)
        }
    }

    impl TransmitQueueCommon<EthernetLinkDevice, FakeBindingsCtx> for FakeInnerCtx {
        type Meta = ();
        type Allocator = BufVecU8Allocator;
        type Buffer = Buf<Vec<u8>>;
        type DequeueContext = Never;

        fn parse_outgoing_frame<'a, 'b>(
            buf: &'a [u8],
            (): &'b Self::Meta,
        ) -> Result<SentFrame<&'a [u8]>, ParseSentFrameError> {
            SentFrame::try_parse_as_ethernet(buf)
        }
    }

    impl TransmitQueueContext<EthernetLinkDevice, FakeBindingsCtx> for FakeCoreCtx {
        fn with_transmit_queue_mut<
            O,
            F: FnOnce(&mut TransmitQueueState<Self::Meta, Self::Buffer, Self::Allocator>) -> O,
        >(
            &mut self,
            device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            self.inner.with_transmit_queue_mut(device_id, cb)
        }

        fn with_transmit_queue<
            O,
            F: FnOnce(&TransmitQueueState<Self::Meta, Self::Buffer, Self::Allocator>) -> O,
        >(
            &mut self,
            device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            self.inner.with_transmit_queue(device_id, cb)
        }

        fn send_frame(
            &mut self,
            bindings_ctx: &mut FakeBindingsCtx,
            device_id: &Self::DeviceId,
            dequeue_context: Option<&mut Never>,
            (): Self::Meta,
            buf: Self::Buffer,
        ) -> Result<(), DeviceSendFrameError> {
            TransmitQueueContext::send_frame(
                &mut self.inner,
                bindings_ctx,
                device_id,
                dequeue_context,
                (),
                buf,
            )
        }
    }

    impl TransmitQueueContext<EthernetLinkDevice, FakeBindingsCtx> for FakeInnerCtx {
        fn with_transmit_queue_mut<
            O,
            F: FnOnce(&mut TransmitQueueState<Self::Meta, Self::Buffer, Self::Allocator>) -> O,
        >(
            &mut self,
            _device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            cb(&mut self.state.tx_queue)
        }

        fn with_transmit_queue<
            O,
            F: FnOnce(&TransmitQueueState<Self::Meta, Self::Buffer, Self::Allocator>) -> O,
        >(
            &mut self,
            _device_id: &Self::DeviceId,
            cb: F,
        ) -> O {
            cb(&self.state.tx_queue)
        }

        fn send_frame(
            &mut self,
            _bindings_ctx: &mut FakeBindingsCtx,
            device_id: &Self::DeviceId,
            dequeue_context: Option<&mut Never>,
            (): Self::Meta,
            buf: Self::Buffer,
        ) -> Result<(), DeviceSendFrameError> {
            match dequeue_context {
                Some(never) => match *never {},
                None => (),
            }
            self.frames.push(device_id.clone(), buf.as_ref().to_vec());
            Ok(())
        }
    }

    impl DeviceIdContext<EthernetLinkDevice> for FakeCoreCtx {
        type DeviceId = FakeDeviceId;
        type WeakDeviceId = FakeWeakDeviceId<FakeDeviceId>;
    }

    impl DeviceIdContext<EthernetLinkDevice> for FakeInnerCtx {
        type DeviceId = FakeDeviceId;
        type WeakDeviceId = FakeWeakDeviceId<FakeDeviceId>;
    }

    impl CounterContext<ArpCounters> for FakeCoreCtx {
        fn with_counters<O, F: FnOnce(&ArpCounters) -> O>(&self, cb: F) -> O {
            cb(&self.inner.state.arp_counters)
        }
    }

    #[test]
    fn test_mtu() {
        // Test that we send an Ethernet frame whose size is less than the MTU,
        // and that we don't send an Ethernet frame whose size is greater than
        // the MTU.
        fn test(size: usize, expect_frames_sent: bool) {
            let mut ctx = new_context();
            NeighborApi::<Ipv4, EthernetLinkDevice, _>::new(ctx.as_mut())
                .insert_static_entry(
                    &FakeDeviceId,
                    TEST_ADDRS_V4.remote_ip.get(),
                    TEST_ADDRS_V4.remote_mac.get(),
                )
                .unwrap();
            let CtxPair { core_ctx, bindings_ctx } = &mut ctx;
            let result = send_ip_frame(
                core_ctx,
                bindings_ctx,
                &FakeDeviceId,
                IpPacketDestination::<Ipv4, _>::Neighbor(TEST_ADDRS_V4.remote_ip),
                Buf::new(&mut vec![0; size], ..),
            )
            .map_err(|_serializer| ());
            let sent_frames = core_ctx.inner.frames().len();
            if expect_frames_sent {
                assert_eq!(sent_frames, 1);
                result.expect("should succeed");
            } else {
                assert_eq!(sent_frames, 0);
                result.expect_err("should fail");
            }
        }

        test(usize::try_from(u32::from(Ipv6::MINIMUM_LINK_MTU)).unwrap(), true);
        test(usize::try_from(u32::from(Ipv6::MINIMUM_LINK_MTU)).unwrap() + 1, false);
    }

    #[test]
    fn broadcast() {
        let mut ctx = new_context();
        let CtxPair { core_ctx, bindings_ctx } = &mut ctx;
        send_ip_frame(
            core_ctx,
            bindings_ctx,
            &FakeDeviceId,
            IpPacketDestination::<Ipv4, _>::Broadcast(()),
            Buf::new(&mut vec![0; 100], ..),
        )
        .map_err(|_serializer| ())
        .expect("send_ip_frame should succeed");
        let sent_frames = core_ctx.inner.frames().len();
        assert_eq!(sent_frames, 1);
        let (FakeDeviceId, frame) = core_ctx.inner.frames()[0].clone();
        let (_body, _src_mac, dst_mac, _ether_type) =
            parse_ethernet_frame(&frame, EthernetFrameLengthCheck::NoCheck).unwrap();
        assert_eq!(dst_mac, Mac::BROADCAST);
    }
}