Skip to main content

netstack3_ip/multicast_forwarding/
api.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Declares the API for configuring multicast forwarding within the netstack.
6
7use alloc::collections::btree_map;
8use core::sync::atomic::Ordering;
9
10use log::warn;
11use net_types::SpecifiedAddr;
12use net_types::ip::{Ip, IpVersionMarker};
13use netstack3_base::{
14    AnyDevice, AtomicInstant, ContextPair, CoreTimerContext, CounterContext, DeviceIdContext,
15    Inspector, InspectorDeviceExt, InstantBindingsTypes, InstantContext, StrongDeviceIdentifier,
16    WeakDeviceIdentifier,
17};
18
19use crate::internal::base::IpLayerForwardingContext;
20use crate::internal::multicast_forwarding::counters::MulticastForwardingCounters;
21use crate::internal::multicast_forwarding::packet_queue::{PacketQueue, QueuedPacket};
22use crate::internal::multicast_forwarding::route::{
23    Action, MulticastRoute, MulticastRouteEntry, MulticastRouteKey, MulticastRouteStats,
24    MulticastRouteTarget,
25};
26use crate::internal::multicast_forwarding::state::{
27    MulticastForwardingEnabledState, MulticastForwardingPendingPacketsContext as _,
28    MulticastForwardingState, MulticastForwardingStateContext, MulticastRouteTableContext as _,
29};
30use crate::internal::multicast_forwarding::{
31    MulticastForwardingBindingsTypes, MulticastForwardingDeviceContext, MulticastForwardingEvent,
32    MulticastForwardingTimerId,
33};
34use crate::{IpLayerBindingsContext, IpLayerIpExt, IpPacketDestination};
35
36/// The API action can not be performed while multicast forwarding is disabled.
37#[derive(Debug, Eq, PartialEq)]
38pub struct MulticastForwardingDisabledError {}
39
40trait MulticastForwardingStateExt<
41    I: IpLayerIpExt,
42    D: StrongDeviceIdentifier,
43    BT: MulticastForwardingBindingsTypes,
44>
45{
46    fn try_enabled(
47        &self,
48    ) -> Result<&MulticastForwardingEnabledState<I, D, BT>, MulticastForwardingDisabledError>;
49}
50
51impl<I: IpLayerIpExt, D: StrongDeviceIdentifier, BT: MulticastForwardingBindingsTypes>
52    MulticastForwardingStateExt<I, D, BT> for MulticastForwardingState<I, D, BT>
53{
54    fn try_enabled(
55        &self,
56    ) -> Result<&MulticastForwardingEnabledState<I, D, BT>, MulticastForwardingDisabledError> {
57        self.enabled().ok_or(MulticastForwardingDisabledError {})
58    }
59}
60
61/// The multicast forwarding API.
62pub struct MulticastForwardingApi<I: Ip, C> {
63    ctx: C,
64    _ip_mark: IpVersionMarker<I>,
65}
66
67impl<I: Ip, C> MulticastForwardingApi<I, C> {
68    /// Constructs a new multicast forwarding API.
69    pub fn new(ctx: C) -> Self {
70        Self { ctx, _ip_mark: IpVersionMarker::new() }
71    }
72}
73
74impl<I: IpLayerIpExt, C> MulticastForwardingApi<I, C>
75where
76    C: ContextPair,
77    C::CoreContext: MulticastForwardingStateContext<I, C::BindingsContext>
78        + MulticastForwardingDeviceContext<I>
79        + IpLayerForwardingContext<I, C::BindingsContext>
80        + CounterContext<MulticastForwardingCounters<I>>
81        + CoreTimerContext<MulticastForwardingTimerId<I>, C::BindingsContext>,
82    C::BindingsContext:
83        IpLayerBindingsContext<I, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
84{
85    pub(crate) fn core_ctx(&mut self) -> &mut C::CoreContext {
86        let Self { ctx, _ip_mark } = self;
87        ctx.core_ctx()
88    }
89
90    pub(crate) fn contexts(&mut self) -> (&mut C::CoreContext, &mut C::BindingsContext) {
91        let Self { ctx, _ip_mark } = self;
92        ctx.contexts()
93    }
94
95    /// Enables multicast forwarding.
96    ///
97    /// Returns whether multicast forwarding was newly enabled.
98    pub fn enable(&mut self) -> bool {
99        let (core_ctx, bindings_ctx) = self.contexts();
100        core_ctx.with_state_mut(|state, _ctx| match state {
101            MulticastForwardingState::Enabled(_) => false,
102            MulticastForwardingState::Disabled => {
103                *state = MulticastForwardingState::Enabled(MulticastForwardingEnabledState::new::<
104                    C::CoreContext,
105                >(bindings_ctx));
106                true
107            }
108        })
109    }
110
111    /// Disables multicast forwarding.
112    ///
113    /// Returns whether multicast forwarding was newly disabled.
114    ///
115    /// Upon being disabled, the multicast route table will be cleared,
116    /// and all pending packets will be dropped.
117    pub fn disable(&mut self) -> bool {
118        self.core_ctx().with_state_mut(|state, _ctx| match state {
119            MulticastForwardingState::Disabled => false,
120            MulticastForwardingState::Enabled(_) => {
121                *state = MulticastForwardingState::Disabled;
122                true
123            }
124        })
125    }
126
127    /// Add the route to the multicast route table.
128    ///
129    /// If a route already exists with the same key, it will be replaced, and
130    /// the original route will be returned.
131    pub fn add_multicast_route(
132        &mut self,
133        key: MulticastRouteKey<I>,
134        route: MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
135    ) -> Result<
136        Option<MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>>,
137        MulticastForwardingDisabledError,
138    > {
139        let (core_ctx, bindings_ctx) = self.contexts();
140        let (orig_route, packet_queue_and_new_route) = core_ctx.with_state_mut(|state, ctx| {
141            let state = state.try_enabled()?;
142            ctx.with_route_table_mut(state, |route_table, ctx| {
143                let stats = MulticastRouteStats { last_used: bindings_ctx.now_atomic() };
144                match route_table.entry(key.clone()) {
145                    btree_map::Entry::Occupied(mut entry) => {
146                        // NB: We consider the stats to be associated with the
147                        // `route` rather than the route's key. As such we
148                        // replace the stats instead of preserving them.
149                        let MulticastRouteEntry { route: orig_route, stats: _ } =
150                            entry.insert(MulticastRouteEntry { route, stats });
151                        // NB: Check the invariant that any key present in the
152                        // route table is not also present in the pending table.
153                        #[cfg(debug_assertions)]
154                        ctx.with_pending_table_mut(state, |pending_table| {
155                            debug_assert!(!pending_table.contains(&key));
156                        });
157                        Ok((Some(orig_route), None))
158                    }
159                    btree_map::Entry::Vacant(entry) => {
160                        let MulticastRouteEntry { route: new_route_ref, stats: _ } =
161                            entry.insert(MulticastRouteEntry { route, stats });
162                        let packet_queue_and_new_route = ctx
163                            .with_pending_table_mut(state, |pending_table| {
164                                pending_table.remove(&key, bindings_ctx)
165                            })
166                            .map(|packet_queue| (packet_queue, new_route_ref.clone()));
167                        Ok((None, packet_queue_and_new_route))
168                    }
169                }
170            })
171        })?;
172
173        if let Some((packet_queue, new_route)) = packet_queue_and_new_route {
174            // NB: we cloned the route out to a context that's no longer holding
175            // the routing table lock. This means the route could have been
176            // removed. In general, that's okay. We'll operate on the
177            // potentially stale route as if it still exists. This mirrors the
178            // lookup pattern used by the unicast/multicast route tables in
179            // other parts of the stack.
180            handle_pending_packets(core_ctx, bindings_ctx, packet_queue, key, new_route)
181        }
182
183        Ok(orig_route)
184    }
185
186    /// Remove the route from the multicast route table.
187    ///
188    /// Returns `None` if the route did not exist.
189    pub fn remove_multicast_route(
190        &mut self,
191        key: &MulticastRouteKey<I>,
192    ) -> Result<
193        Option<MulticastRoute<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>>,
194        MulticastForwardingDisabledError,
195    > {
196        self.core_ctx().with_state_mut(|state, ctx| {
197            let state = state.try_enabled()?;
198            ctx.with_route_table_mut(state, |route_table, _ctx| {
199                Ok(route_table.remove(key).map(|MulticastRouteEntry { route, stats: _ }| route))
200            })
201        })
202    }
203
204    /// Remove all references to the device from the multicast forwarding state.
205    ///
206    /// Typically, this is called as part of device removal to purge all strong
207    /// device references.
208    ///
209    /// Any routes that reference the device as an `input_interface` will be
210    /// removed. Any routes that reference the device as a
211    /// [`MulticastRouteTarget`] will have that target removed (and will
212    /// themselves be removed if it's the only target).
213    pub fn remove_references_to_device(
214        &mut self,
215        dev: &<C::CoreContext as DeviceIdContext<AnyDevice>>::WeakDeviceId,
216    ) {
217        self.core_ctx().with_state_mut(|state, ctx| {
218            let Some(state) = state.enabled() else {
219                // There's no state to update if forwarding is disabled.
220                return;
221            };
222            ctx.with_route_table_mut(state, |route_table, _ctx| {
223                route_table.retain(
224                    |_route_key,
225                     MulticastRouteEntry {
226                         route: MulticastRoute { action, input_interface },
227                         stats: _,
228                     }| {
229                        if dev == &*input_interface {
230                            return false;
231                        }
232                        match action {
233                            Action::Forward(targets) => {
234                                // If all targets reference the device, we should
235                                // discard the route entirely.
236                                if targets.iter().all(|target| dev == &target.output_interface) {
237                                    return false;
238                                }
239                                // Otherwise, if any target references the device,
240                                // we should remove it from the set of targets.
241                                if targets.iter().any(|target| dev == &target.output_interface) {
242                                    *targets = targets
243                                        .iter()
244                                        .filter(|target| dev != &target.output_interface)
245                                        .cloned()
246                                        .collect();
247                                }
248                            }
249                        }
250                        true
251                    },
252                )
253            })
254        })
255    }
256
257    /// Returns the [`MulticastRouteStats`], if any, for the given key.
258    pub fn get_route_stats(
259        &mut self,
260        key: &MulticastRouteKey<I>,
261    ) -> Result<
262        Option<MulticastRouteStats<<C::BindingsContext as InstantBindingsTypes>::Instant>>,
263        MulticastForwardingDisabledError,
264    > {
265        self.core_ctx().with_state(|state, ctx| {
266            let state = state.try_enabled()?;
267            ctx.with_route_table(state, |route_table, _ctx| {
268                Ok(route_table.get(key).map(
269                    |MulticastRouteEntry { route: _, stats: MulticastRouteStats { last_used } }| {
270                        MulticastRouteStats { last_used: last_used.load(Ordering::Relaxed) }
271                    },
272                ))
273            })
274        })
275    }
276
277    /// Writes multicast routing table information to the provided `inspector`.
278    pub fn inspect<
279        N: Inspector + InspectorDeviceExt<<C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
280    >(
281        &mut self,
282        inspector: &mut N,
283    ) {
284        self.core_ctx().with_state(|state, ctx| match state {
285            MulticastForwardingState::Disabled => {
286                inspector.record_bool("ForwardingEnabled", false);
287            }
288            MulticastForwardingState::Enabled(state) => {
289                inspector.record_bool("ForwardingEnabled", true);
290                inspector.record_child("Routes", |inspector| {
291                    ctx.with_route_table(state, |route_table, _ctx| {
292                        for (route_key, route_entry) in route_table.iter() {
293                            inspector.record_unnamed_child(|inspector| {
294                                inspector.delegate_inspectable(route_key);
295                                route_entry.inspect::<_, N>(inspector);
296                            })
297                        }
298                    })
299                });
300                // NB: All other operations on the pending table require mutable
301                // access; don't bother introducing an immutable accessor just
302                // for inspect.
303                ctx.with_pending_table_mut(state, |pending_table| {
304                    inspector.record_inspectable("PendingRoutes", pending_table);
305                });
306            }
307        })
308    }
309}
310
311/// Attempt to forward the packets from a pending [`PacketQueue`] according to a
312/// newly installed [`MulticastRoute`].
313fn handle_pending_packets<I: IpLayerIpExt, CC, BC>(
314    core_ctx: &mut CC,
315    bindings_ctx: &mut BC,
316    packet_queue: PacketQueue<I, CC::WeakDeviceId, BC>,
317    key: MulticastRouteKey<I>,
318    route: MulticastRoute<CC::DeviceId>,
319) where
320    CC: IpLayerForwardingContext<I, BC>
321        + MulticastForwardingDeviceContext<I>
322        + CounterContext<MulticastForwardingCounters<I>>,
323    BC: IpLayerBindingsContext<I, CC::DeviceId>,
324{
325    let MulticastRoute { input_interface, action } = route;
326
327    // NB: We checked that forwarding was enabled on the device before the
328    // packet was enqueued in the pending table. However, the packet may sit in
329    // the queue for an extended period of time, during which forwarding may
330    // have been disabled on the device. Check again here just in case.
331    if !core_ctx.is_device_multicast_forwarding_enabled(&input_interface) {
332        // The user just installed a multicast route, but also disabled
333        // forwarding on the device. Log a warning because that likely indicates
334        // incorrect API usage.
335        warn!(
336            "Dropping pending packets for newly installed multicast route: {key:?}. \
337            Multicast forwarding is disabled on input interface: {input_interface:?}"
338        );
339        CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
340            .pending_packet_drops_disabled_dev
341            .increment();
342        return;
343    }
344
345    let MulticastRouteKey { src_addr, dst_addr } = key.clone();
346    let dst_ip: SpecifiedAddr<I::Addr> = dst_addr.into();
347    let src_ip: I::RecvSrcAddr = src_addr.into();
348
349    for QueuedPacket { device, packet, frame_dst, max_fragment_len, marks } in
350        packet_queue.into_iter()
351    {
352        let device = match device.upgrade() {
353            // Short circuit if the device was removed while the packet was
354            // pending.
355            None => continue,
356            Some(d) => d,
357        };
358        // Short circuit if the queued packet arrived on the wrong device.
359        if device != input_interface {
360            CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
361                .pending_packet_drops_wrong_dev
362                .increment();
363            bindings_ctx.on_event(
364                MulticastForwardingEvent::WrongInputInterface {
365                    key: key.clone(),
366                    actual_input_interface: device,
367                    expected_input_interface: input_interface.clone(),
368                }
369                .into(),
370            );
371            continue;
372        }
373
374        // NB: We could choose to update the `last_used` value on the route's
375        // statistics here, but that's probably overkill. We only end up in this
376        // function as part of route installation, which will have appropriately
377        // initialized `last_used`. It's not worth re-acquiring the route table
378        // lock to update it again here, as the change in time will be
379        // negligible.
380
381        match &action {
382            Action::Forward(targets) => {
383                CounterContext::<MulticastForwardingCounters<I>>::counters(core_ctx)
384                    .pending_packet_tx
385                    .increment();
386                let packet_iter = core::iter::repeat_n(packet, targets.len());
387                for (mut packet, MulticastRouteTarget { output_interface, min_ttl }) in
388                    packet_iter.zip(targets.iter())
389                {
390                    let packet_metadata =
391                        crate::internal::base::IpLayerPacketMetadata::new_local_tx(
392                            Default::default(),
393                            marks,
394                            None,
395                        );
396                    crate::internal::base::determine_ip_packet_forwarding_action::<I, _, _>(
397                        core_ctx,
398                        packet.parse_ip_packet_mut(),
399                        packet_metadata,
400                        Some(*min_ttl),
401                        &input_interface,
402                        &output_interface,
403                        IpPacketDestination::from_addr(dst_ip),
404                        frame_dst,
405                        src_ip,
406                        dst_ip,
407                    )
408                    .perform_action_with_buffer(
409                        core_ctx,
410                        bindings_ctx,
411                        packet.into_inner(),
412                        max_fragment_len,
413                    );
414                }
415            }
416        }
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    use alloc::vec;
425    use core::num::NonZeroU8;
426    use core::ops::Deref;
427    use core::time::Duration;
428
429    use assert_matches::assert_matches;
430    use ip_test_macro::ip_test;
431    use net_types::MulticastAddr;
432    use netstack3_base::testutil::MultipleDevicesId;
433    use netstack3_base::{LocalFrameDestination, StrongDeviceIdentifier};
434    use packet::ParseBuffer;
435    use test_case::test_case;
436
437    use crate::IpLayerEvent;
438    use crate::internal::multicast_forwarding;
439    use crate::internal::multicast_forwarding::packet_queue::QueuePacketOutcome;
440    use crate::internal::multicast_forwarding::testutil::{SentPacket, TestIpExt};
441    use crate::multicast_forwarding::{MulticastRoute, MulticastRouteKey, MulticastRouteTarget};
442
443    const MIN_TTL: NonZeroU8 = NonZeroU8::new(1).unwrap();
444
445    #[ip_test(I)]
446    fn enable_disable<I: IpLayerIpExt>() {
447        let mut api = multicast_forwarding::testutil::new_api::<I>();
448
449        assert_matches!(
450            api.core_ctx().state.multicast_forwarding.borrow().deref(),
451            &MulticastForwardingState::Disabled
452        );
453        assert!(api.enable());
454        assert!(!api.enable());
455        assert_matches!(
456            api.core_ctx().state.multicast_forwarding.borrow().deref(),
457            &MulticastForwardingState::Enabled(_)
458        );
459        assert!(api.disable());
460        assert!(!api.disable());
461        assert_matches!(
462            api.core_ctx().state.multicast_forwarding.borrow().deref(),
463            &MulticastForwardingState::Disabled
464        );
465    }
466
467    #[ip_test(I)]
468    fn add_remove_route<I: TestIpExt>() {
469        let key1 = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
470        let key2 = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
471        let forward_to_b = MulticastRoute::new_forward(
472            MultipleDevicesId::A,
473            [MulticastRouteTarget { output_interface: MultipleDevicesId::B, min_ttl: MIN_TTL }]
474                .into(),
475        )
476        .unwrap();
477        let forward_to_c = MulticastRoute::new_forward(
478            MultipleDevicesId::A,
479            [MulticastRouteTarget { output_interface: MultipleDevicesId::C, min_ttl: MIN_TTL }]
480                .into(),
481        )
482        .unwrap();
483
484        let mut api = multicast_forwarding::testutil::new_api::<I>();
485
486        // Adding/removing routes before multicast forwarding is enabled should
487        // fail.
488        assert_eq!(
489            api.add_multicast_route(key1.clone(), forward_to_b.clone()),
490            Err(MulticastForwardingDisabledError {})
491        );
492        assert_eq!(api.remove_multicast_route(&key1), Err(MulticastForwardingDisabledError {}));
493
494        // Enable the API and observe success.
495        assert!(api.enable());
496        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
497        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_b.clone())));
498
499        // Removing a route that doesn't exist should return `None`.
500        assert_eq!(api.remove_multicast_route(&key1), Ok(None));
501
502        // Adding a route with the same key as an existing route should
503        // overwrite the original.
504        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
505        assert_eq!(
506            api.add_multicast_route(key1.clone(), forward_to_c.clone()),
507            Ok(Some(forward_to_b.clone()))
508        );
509        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_c.clone())));
510
511        // Routes with different keys can co-exist.
512        assert_eq!(api.add_multicast_route(key1.clone(), forward_to_b.clone()), Ok(None));
513        assert_eq!(api.add_multicast_route(key2.clone(), forward_to_c.clone()), Ok(None));
514        assert_eq!(api.remove_multicast_route(&key1), Ok(Some(forward_to_b)));
515        assert_eq!(api.remove_multicast_route(&key2), Ok(Some(forward_to_c)));
516    }
517
518    #[ip_test(I)]
519    #[test_case(false, true; "forwarding_disabled")]
520    #[test_case(true, false; "forwarding_enabled_and_wrong_dev")]
521    #[test_case(true, true; "forwarding_enabled_and_right_dev")]
522    fn add_route_with_pending_packets<I: TestIpExt>(
523        forwarding_enabled_for_dev: bool,
524        right_dev: bool,
525    ) {
526        const FRAME_DST: Option<LocalFrameDestination> = None;
527        const MAX_FRAGMENT_LEN: Option<usize> = None;
528        const OUTPUT_DEV: MultipleDevicesId = MultipleDevicesId::C;
529        let right_key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
530        let wrong_key = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
531        let expected_dev = MultipleDevicesId::A;
532        let actual_dev = if right_dev { expected_dev } else { MultipleDevicesId::B };
533
534        let route = MulticastRoute::new_forward(
535            expected_dev,
536            [MulticastRouteTarget { output_interface: OUTPUT_DEV, min_ttl: MIN_TTL }].into(),
537        )
538        .unwrap();
539
540        let mut api = multicast_forwarding::testutil::new_api::<I>();
541        assert!(api.enable());
542        api.core_ctx()
543            .state
544            .set_multicast_forwarding_enabled_for_dev(expected_dev, forwarding_enabled_for_dev);
545
546        // Setup a queued packet for `right_key`.
547        let (core_ctx, bindings_ctx) = api.contexts();
548        multicast_forwarding::testutil::with_pending_table(core_ctx, |pending_table| {
549            let buf = multicast_forwarding::testutil::new_ip_packet_buf::<I>(I::SRC1, I::DST1);
550            let mut buf_ref = buf.as_ref();
551            let packet = buf_ref.parse::<I::Packet<_>>().expect("parse should succeed");
552            assert_eq!(
553                pending_table.try_queue_packet(
554                    bindings_ctx,
555                    right_key.clone(),
556                    &packet,
557                    &actual_dev,
558                    FRAME_DST,
559                    MAX_FRAGMENT_LEN,
560                    Default::default(),
561                ),
562                QueuePacketOutcome::QueuedInNewQueue,
563            );
564        });
565
566        // Add a route with the wrong key and expect that the packet queue is
567        // unaffected.
568        assert_eq!(api.add_multicast_route(wrong_key, route.clone()), Ok(None));
569        assert!(multicast_forwarding::testutil::with_pending_table(
570            api.core_ctx(),
571            |pending_table| pending_table.contains(&right_key)
572        ));
573
574        // Add a route with the right key and expect that the packet queue is
575        // removed.
576        assert_eq!(api.add_multicast_route(right_key.clone(), route), Ok(None));
577        assert!(multicast_forwarding::testutil::with_pending_table(
578            api.core_ctx(),
579            |pending_table| !pending_table.contains(&right_key)
580        ));
581
582        let expect_sent_packet = forwarding_enabled_for_dev && right_dev;
583        let mut expected_sent_packets = vec![];
584        if expect_sent_packet {
585            expected_sent_packets.push(SentPacket {
586                dst: MulticastAddr::new(right_key.dst_addr()).unwrap(),
587                device: OUTPUT_DEV,
588            });
589        }
590        assert_eq!(api.core_ctx().state.take_sent_packets(), expected_sent_packets);
591
592        // Verify that multicast routing events are generated.
593        let mut expected_events = vec![];
594        if !right_dev {
595            expected_events.push(IpLayerEvent::MulticastForwarding(
596                MulticastForwardingEvent::WrongInputInterface {
597                    key: right_key,
598                    actual_input_interface: actual_dev,
599                    expected_input_interface: expected_dev,
600                },
601            ));
602        }
603
604        let (_core_ctx, bindings_ctx) = api.contexts();
605        assert_eq!(bindings_ctx.take_events(), expected_events);
606
607        // Verify that counters are updated.
608        let counters: &MulticastForwardingCounters<I> = api.core_ctx().counters();
609        assert_eq!(counters.pending_packet_tx.get(), if expect_sent_packet { 1 } else { 0 });
610        assert_eq!(
611            counters.pending_packet_drops_disabled_dev.get(),
612            if forwarding_enabled_for_dev { 0 } else { 1 }
613        );
614        assert_eq!(counters.pending_packet_drops_wrong_dev.get(), if right_dev { 0 } else { 1 });
615    }
616
617    #[ip_test(I)]
618    fn remove_references_to_device<I: TestIpExt>() {
619        // NB: 4 arbitrary keys, that are unique from each other.
620        let key1 = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
621        let key2 = MulticastRouteKey::new(I::SRC2, I::DST1).unwrap();
622        let key3 = MulticastRouteKey::new(I::SRC1, I::DST2).unwrap();
623        let key4 = MulticastRouteKey::new(I::SRC2, I::DST2).unwrap();
624
625        // Create 4 routes, each exercising a different edge case.
626        const GOOD_DEV1: MultipleDevicesId = MultipleDevicesId::A;
627        const GOOD_DEV2: MultipleDevicesId = MultipleDevicesId::B;
628        const BAD_DEV: MultipleDevicesId = MultipleDevicesId::C;
629        const GOOD_TARGET1: MulticastRouteTarget<MultipleDevicesId> =
630            MulticastRouteTarget { output_interface: GOOD_DEV1, min_ttl: MIN_TTL };
631        const GOOD_TARGET2: MulticastRouteTarget<MultipleDevicesId> =
632            MulticastRouteTarget { output_interface: GOOD_DEV2, min_ttl: MIN_TTL };
633        const BAD_TARGET: MulticastRouteTarget<MultipleDevicesId> =
634            MulticastRouteTarget { output_interface: BAD_DEV, min_ttl: MIN_TTL };
635        let dev_is_input = MulticastRoute::new_forward(BAD_DEV, [GOOD_TARGET1].into()).unwrap();
636        let dev_is_only_output =
637            MulticastRoute::new_forward(GOOD_DEV1, [BAD_TARGET].into()).unwrap();
638        let dev_is_one_output =
639            MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2, BAD_TARGET].into()).unwrap();
640        let no_ref_to_dev = MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2].into()).unwrap();
641
642        // Verify that removing device references is a no-op when multicast
643        // forwarding is disabled.
644        let mut api = multicast_forwarding::testutil::new_api::<I>();
645        api.remove_references_to_device(&BAD_DEV.downgrade());
646        assert!(api.enable());
647
648        // Add the four routes, remove references to `Dev`, and verify that:
649        // * `dev_is_input` & `dev_is_only_output`, were both removed.
650        // * `dev_is_one_output` was updated to not list the dev in its
651        //    targets.
652        // * `no_ref_to_dev` was not updated.
653        assert_eq!(api.add_multicast_route(key1.clone(), dev_is_input), Ok(None));
654        assert_eq!(api.add_multicast_route(key2.clone(), dev_is_only_output), Ok(None));
655        assert_eq!(api.add_multicast_route(key3.clone(), dev_is_one_output), Ok(None));
656        assert_eq!(api.add_multicast_route(key4.clone(), no_ref_to_dev.clone()), Ok(None));
657        api.remove_references_to_device(&BAD_DEV.downgrade());
658        assert_eq!(api.remove_multicast_route(&key1), Ok(None));
659        assert_eq!(api.remove_multicast_route(&key2), Ok(None));
660        // NB: Equal to `dev_is_one_output`, but with `BAD_TARGET` removed.
661        assert_eq!(
662            api.remove_multicast_route(&key3),
663            Ok(Some(MulticastRoute::new_forward(GOOD_DEV1, [GOOD_TARGET2].into()).unwrap()))
664        );
665        assert_eq!(api.remove_multicast_route(&key4), Ok(Some(no_ref_to_dev)));
666    }
667
668    #[ip_test(I)]
669    fn get_route_stats<I: TestIpExt>() {
670        let key = MulticastRouteKey::new(I::SRC1, I::DST1).unwrap();
671
672        let mut api = multicast_forwarding::testutil::new_api::<I>();
673
674        // Verify that get_route_stats fails when forwarding is disabled.
675        assert_eq!(api.get_route_stats(&key), Err(MulticastForwardingDisabledError {}));
676
677        // Verify that get_route_stats returns `None` if the route doesn't exist.
678        assert!(api.enable());
679        assert_eq!(api.get_route_stats(&key), Ok(None));
680
681        // Install a route and verify that get_route_stats succeeds.
682        let route = MulticastRoute::new_forward(
683            MultipleDevicesId::A,
684            [MulticastRouteTarget { output_interface: MultipleDevicesId::B, min_ttl: MIN_TTL }]
685                .into(),
686        )
687        .unwrap();
688        assert_eq!(api.add_multicast_route(key.clone(), route.clone()), Ok(None));
689        let original_time = api.ctx.bindings_ctx().now();
690        let expected_stats = MulticastRouteStats { last_used: original_time };
691        assert_eq!(api.get_route_stats(&key), Ok(Some(expected_stats)));
692
693        // Advance the timer and overwrite the route to prove we initialize
694        // stats with an up-to-date instant.
695        api.ctx.bindings_ctx().timers.instant.sleep(Duration::from_secs(5));
696        let new_time = api.ctx.bindings_ctx().now();
697        assert!(new_time > original_time);
698        let expected_stats = MulticastRouteStats { last_used: new_time };
699        assert_eq!(api.add_multicast_route(key.clone(), route.clone()), Ok(Some(route)));
700        assert_eq!(api.get_route_stats(&key), Ok(Some(expected_stats)));
701    }
702}