netstack3_device/
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//! Device layer api.
6
7use alloc::fmt::Debug;
8use core::marker::PhantomData;
9
10use log::debug;
11use net_types::ip::{Ipv4, Ipv6};
12use netstack3_base::{
13    AnyDevice, ContextPair, CoreTimerContext, Device, DeviceIdAnyCompatContext, DeviceIdContext,
14    Inspector, RecvFrameContext, ReferenceNotifiers, ReferenceNotifiersExt as _,
15    RemoveResourceResultWithContext, ResourceCounterContext, TimerContext,
16};
17use netstack3_ip::device::{
18    IpAddressIdSpecContext, IpDeviceBindingsContext, IpDeviceConfigurationContext, IpDeviceTimerId,
19    Ipv6DeviceConfigurationContext,
20};
21use netstack3_ip::gmp::{IgmpCounters, MldCounters};
22use netstack3_ip::{self as ip, RawMetric};
23use packet::BufferMut;
24
25use crate::internal::base::{
26    DeviceCollectionContext, DeviceCounters, DeviceLayerStateTypes, DeviceLayerTypes,
27    DeviceReceiveFrameSpec, OriginTrackerContext,
28};
29use crate::internal::blackhole::BlackholeDevice;
30use crate::internal::config::{
31    ArpConfiguration, ArpConfigurationUpdate, DeviceConfiguration, DeviceConfigurationContext,
32    DeviceConfigurationUpdate, DeviceConfigurationUpdateError, NdpConfiguration,
33    NdpConfigurationUpdate,
34};
35use crate::internal::ethernet::EthernetLinkDevice;
36use crate::internal::id::{
37    for_any_device_id, BaseDeviceId, BasePrimaryDeviceId, BaseWeakDeviceId, DeviceId,
38    DeviceProvider,
39};
40use crate::internal::loopback::LoopbackDevice;
41use crate::internal::pure_ip::PureIpDevice;
42use crate::internal::state::{BaseDeviceState, DeviceStateSpec, IpLinkDeviceStateInner};
43
44/// Pending device configuration update.
45///
46/// This type is a witness for a valid [`DeviceConfigurationUpdate`] for some
47/// device ID `D` and is obtained through
48/// [`DeviceApi::new_configuration_update`].
49///
50/// The configuration is only applied when [`DeviceApi::apply_configuration`] is
51/// called.
52pub struct PendingDeviceConfigurationUpdate<'a, D>(DeviceConfigurationUpdate, &'a D);
53
54/// The device API.
55pub struct DeviceApi<D, C>(C, PhantomData<D>);
56
57impl<D, C> DeviceApi<D, C> {
58    /// Creates a new [`DeviceApi`] from `ctx`.
59    pub fn new(ctx: C) -> Self {
60        Self(ctx, PhantomData)
61    }
62}
63
64impl<D, C> DeviceApi<D, C>
65where
66    D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
67    C: ContextPair,
68    C::CoreContext: DeviceApiCoreContext<D, C::BindingsContext>,
69    C::BindingsContext: DeviceApiBindingsContext,
70{
71    pub(crate) fn contexts(&mut self) -> (&mut C::CoreContext, &mut C::BindingsContext) {
72        let Self(pair, PhantomData) = self;
73        pair.contexts()
74    }
75
76    pub(crate) fn core_ctx(&mut self) -> &mut C::CoreContext {
77        let Self(pair, PhantomData) = self;
78        pair.core_ctx()
79    }
80
81    /// Adds a new device to the stack and returns its identifier.
82    ///
83    /// # Panics
84    ///
85    /// Panics if more than 1 loopback device is added to the stack.
86    pub fn add_device(
87        &mut self,
88        bindings_id: <C::BindingsContext as DeviceLayerStateTypes>::DeviceIdentifier,
89        properties: D::CreationProperties,
90        metric: RawMetric,
91        external_state: D::External<C::BindingsContext>,
92    ) -> <C::CoreContext as DeviceIdContext<D>>::DeviceId
93    where
94        C::CoreContext: DeviceApiIpLayerCoreContext<D, C::BindingsContext>,
95    {
96        debug!("adding {} device with {:?} metric:{metric}", D::DEBUG_TYPE, properties);
97        let (core_ctx, bindings_ctx) = self.contexts();
98        let origin = core_ctx.origin_tracker();
99        let primary = BasePrimaryDeviceId::new(
100            |weak_ref| {
101                let link = D::new_device_state::<C::CoreContext, _>(
102                    bindings_ctx,
103                    weak_ref.clone(),
104                    properties,
105                );
106                IpLinkDeviceStateInner::new::<_, _, C::CoreContext>(
107                    bindings_ctx,
108                    weak_ref.into(),
109                    link,
110                    metric,
111                    origin,
112                )
113            },
114            external_state,
115            bindings_id,
116        );
117        let id = primary.clone_strong();
118        core_ctx.insert(primary);
119        id
120    }
121
122    /// Like [`DeviceApi::add_device`] but using default values for
123    /// `bindings_id` and `external_state`.
124    ///
125    /// This is provided as a convenience method for tests with faked bindings
126    /// contexts that have simple implementations for bindings state.
127    #[cfg(any(test, feature = "testutils"))]
128    pub fn add_device_with_default_state(
129        &mut self,
130        properties: D::CreationProperties,
131        metric: RawMetric,
132    ) -> <C::CoreContext as DeviceIdContext<D>>::DeviceId
133    where
134        <C::BindingsContext as DeviceLayerStateTypes>::DeviceIdentifier: Default,
135        D::External<C::BindingsContext>: Default,
136        C::CoreContext: DeviceApiIpLayerCoreContext<D, C::BindingsContext>,
137    {
138        self.add_device(Default::default(), properties, metric, Default::default())
139    }
140
141    /// Removes `device` from the stack.
142    ///
143    /// If the return value is `RemoveDeviceResult::Removed` the device is
144    /// immediately removed from the stack, otherwise
145    /// `RemoveDeviceResult::Deferred` indicates that the device was marked for
146    /// destruction but there are still references to it. It carries a
147    /// `ReferenceReceiver` from the bindings context that can be awaited on
148    /// until removal is complete.
149    ///
150    /// # Panics
151    ///
152    /// Panics if the device is not currently in the stack.
153    pub fn remove_device(
154        &mut self,
155        device: BaseDeviceId<D, C::BindingsContext>,
156    ) -> RemoveResourceResultWithContext<D::External<C::BindingsContext>, C::BindingsContext>
157    where
158        // Required to call into IP layer for cleanup on removal:
159        BaseDeviceId<D, C::BindingsContext>: Into<DeviceId<C::BindingsContext>>,
160        C::CoreContext: IpDeviceConfigurationContext<Ipv4, C::BindingsContext>
161            + Ipv6DeviceConfigurationContext<C::BindingsContext>
162            + DeviceIdContext<AnyDevice, DeviceId = DeviceId<C::BindingsContext>>,
163        C::BindingsContext: IpDeviceBindingsContext<Ipv4, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>
164            + IpDeviceBindingsContext<Ipv6, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
165    {
166        // Start cleaning up the device by disabling IP state. This removes timers
167        // for the device that would otherwise hold references to defunct device
168        // state.
169        let (core_ctx, bindings_ctx) = self.contexts();
170        {
171            let device = device.clone().into();
172            ip::device::clear_ipv4_device_state(core_ctx, bindings_ctx, &device);
173            ip::device::clear_ipv6_device_state(core_ctx, bindings_ctx, &device);
174        };
175
176        debug!("removing {device:?}");
177        let primary = core_ctx.remove(&device).expect("tried to remove device not in stack");
178        assert_eq!(device, primary);
179        core::mem::drop(device);
180        C::BindingsContext::unwrap_or_notify_with_new_reference_notifier(
181            primary.into_inner(),
182            |state: BaseDeviceState<_, _>| state.external_state,
183        )
184    }
185
186    /// Receive a device layer frame from the network.
187    pub fn receive_frame<B: BufferMut + Debug>(
188        &mut self,
189        meta: D::FrameMetadata<BaseDeviceId<D, C::BindingsContext>>,
190        frame: B,
191    ) {
192        let (core_ctx, bindings_ctx) = self.contexts();
193        core_ctx.receive_frame(bindings_ctx, meta, frame)
194    }
195
196    /// Applies the configuration and returns a [`DeviceConfigurationUpdate`]
197    /// with the previous values for all configurations for all `Some` fields.
198    ///
199    /// Note that even if the previous value matched the requested value, it is
200    /// still populated in the returned `DeviceConfigurationUpdate`.
201    pub fn apply_configuration(
202        &mut self,
203        pending: PendingDeviceConfigurationUpdate<'_, BaseDeviceId<D, C::BindingsContext>>,
204    ) -> DeviceConfigurationUpdate {
205        let PendingDeviceConfigurationUpdate(DeviceConfigurationUpdate { arp, ndp }, device_id) =
206            pending;
207        let core_ctx = self.core_ctx();
208        let arp = core_ctx.with_nud_config_mut::<Ipv4, _, _>(device_id, move |device_config| {
209            let device_config = match device_config {
210                Some(c) => c,
211                None => {
212                    // Can't set ARP configuration if device doesn't support it,
213                    // this is validated when creating the
214                    // `PendingDeviceConfigurationUpdate`.
215                    assert!(arp.is_none());
216                    return None;
217                }
218            };
219            arp.map(|ArpConfigurationUpdate { nud }| {
220                let nud = nud.map(|config| config.apply_and_take_previous(device_config));
221                ArpConfigurationUpdate { nud }
222            })
223        });
224        let ndp = core_ctx.with_nud_config_mut::<Ipv6, _, _>(device_id, move |device_config| {
225            let device_config = match device_config {
226                Some(c) => c,
227                None => {
228                    // Can't set NDP configuration if device doesn't support it,
229                    // this is validated when creating the
230                    // `PendingDeviceConfigurationUpdate`.
231                    assert!(ndp.is_none());
232                    return None;
233                }
234            };
235            ndp.map(|NdpConfigurationUpdate { nud }| {
236                let nud = nud.map(|config| config.apply_and_take_previous(device_config));
237                NdpConfigurationUpdate { nud }
238            })
239        });
240        DeviceConfigurationUpdate { arp, ndp }
241    }
242
243    /// Creates a new device configuration update for the given device.
244    ///
245    /// This method only validates that `config` is valid for `device`.
246    /// [`DeviceApi::apply`] must be called to apply the configuration.
247    pub fn new_configuration_update<'a>(
248        &mut self,
249        device: &'a BaseDeviceId<D, C::BindingsContext>,
250        config: DeviceConfigurationUpdate,
251    ) -> Result<
252        PendingDeviceConfigurationUpdate<'a, BaseDeviceId<D, C::BindingsContext>>,
253        DeviceConfigurationUpdateError,
254    > {
255        let core_ctx = self.core_ctx();
256        let DeviceConfigurationUpdate { arp, ndp } = &config;
257        if arp.is_some() && core_ctx.with_nud_config::<Ipv4, _, _>(device, |c| c.is_none()) {
258            return Err(DeviceConfigurationUpdateError::ArpNotSupported);
259        }
260        if ndp.is_some() && core_ctx.with_nud_config::<Ipv6, _, _>(device, |c| c.is_none()) {
261            return Err(DeviceConfigurationUpdateError::NdpNotSupported);
262        }
263        Ok(PendingDeviceConfigurationUpdate(config, device))
264    }
265
266    /// Returns a snapshot of the given device's configuration.
267    pub fn get_configuration(
268        &mut self,
269        device: &BaseDeviceId<D, C::BindingsContext>,
270    ) -> DeviceConfiguration {
271        let core_ctx = self.core_ctx();
272        let arp = core_ctx
273            .with_nud_config::<Ipv4, _, _>(device, |config| config.cloned())
274            .map(|nud| ArpConfiguration { nud });
275        let ndp = core_ctx
276            .with_nud_config::<Ipv6, _, _>(device, |config| config.cloned())
277            .map(|nud| NdpConfiguration { nud });
278        DeviceConfiguration { arp, ndp }
279    }
280
281    /// Exports state for `device` into `inspector`.
282    pub fn inspect<N: Inspector>(
283        &mut self,
284        device: &BaseDeviceId<D, C::BindingsContext>,
285        inspector: &mut N,
286    ) {
287        inspector.record_child("Counters", |inspector| {
288            inspector.delegate_inspectable(
289                ResourceCounterContext::<_, DeviceCounters>::per_resource_counters(
290                    self.core_ctx(),
291                    device,
292                ),
293            );
294            inspector.delegate_inspectable(
295                ResourceCounterContext::<_, D::Counters>::per_resource_counters(
296                    self.core_ctx(),
297                    device,
298                ),
299            );
300            inspector.record_child("IGMP", |inspector| {
301                inspector.delegate_inspectable(
302                    ResourceCounterContext::<_, IgmpCounters>::per_resource_counters(
303                        self.core_ctx(),
304                        device,
305                    ),
306                );
307            });
308            inspector.record_child("MLD", |inspector| {
309                inspector.delegate_inspectable(
310                    ResourceCounterContext::<_, MldCounters>::per_resource_counters(
311                        self.core_ctx(),
312                        device,
313                    ),
314                );
315            });
316        });
317    }
318}
319
320/// The device API interacting with any kind of supported device.
321pub struct DeviceAnyApi<C>(C);
322
323impl<C> DeviceAnyApi<C> {
324    /// Creates a new [`DeviceAnyApi`] from `ctx`.
325    pub fn new(ctx: C) -> Self {
326        Self(ctx)
327    }
328}
329
330impl<C> DeviceAnyApi<C>
331where
332    C: ContextPair,
333    C::CoreContext: DeviceApiCoreContext<EthernetLinkDevice, C::BindingsContext>
334        + DeviceApiCoreContext<LoopbackDevice, C::BindingsContext>
335        + DeviceApiCoreContext<PureIpDevice, C::BindingsContext>
336        + DeviceApiCoreContext<BlackholeDevice, C::BindingsContext>,
337    C::BindingsContext: DeviceApiBindingsContext,
338{
339    fn device<D>(&mut self) -> DeviceApi<D, &mut C> {
340        let Self(pair) = self;
341        DeviceApi::new(pair)
342    }
343
344    /// Like [`DeviceApi::apply_configuration`] but for any device types.
345    pub fn apply_configuration(
346        &mut self,
347        pending: PendingDeviceConfigurationUpdate<'_, DeviceId<C::BindingsContext>>,
348    ) -> DeviceConfigurationUpdate {
349        let PendingDeviceConfigurationUpdate(config, device) = pending;
350        for_any_device_id!(DeviceId, device,
351            device => {
352                self.device().apply_configuration(PendingDeviceConfigurationUpdate(config, device))
353            }
354        )
355    }
356
357    /// Like [`DeviceApi::new_configuration_update`] but for any device
358    /// types.
359    pub fn new_configuration_update<'a>(
360        &mut self,
361        device: &'a DeviceId<C::BindingsContext>,
362        config: DeviceConfigurationUpdate,
363    ) -> Result<
364        PendingDeviceConfigurationUpdate<'a, DeviceId<C::BindingsContext>>,
365        DeviceConfigurationUpdateError,
366    > {
367        for_any_device_id!(DeviceId, device,
368            inner => {
369                self.device()
370                .new_configuration_update(inner, config)
371                .map(|PendingDeviceConfigurationUpdate(config, _)| {
372                    PendingDeviceConfigurationUpdate(config, device)
373                })
374            }
375        )
376    }
377
378    /// Like [`DeviceApi::get_configuration`] but for any device types.
379    pub fn get_configuration(
380        &mut self,
381        device: &DeviceId<C::BindingsContext>,
382    ) -> DeviceConfiguration {
383        for_any_device_id!(DeviceId, device,
384            device => self.device().get_configuration(device))
385    }
386
387    /// Like [`DeviceApi::inspect`] but for any device type.
388    pub fn inspect<N: Inspector>(
389        &mut self,
390        device: &DeviceId<C::BindingsContext>,
391        inspector: &mut N,
392    ) {
393        for_any_device_id!(DeviceId, DeviceProvider, D, device,
394            device => self.device::<D>().inspect(device, inspector))
395    }
396}
397
398/// A marker trait for all the core context traits required to fulfill the
399/// [`DeviceApi`].
400pub trait DeviceApiCoreContext<
401    D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
402    BC: DeviceApiBindingsContext,
403>:
404    DeviceIdContext<D, DeviceId = BaseDeviceId<D, BC>, WeakDeviceId = BaseWeakDeviceId<D, BC>>
405    + OriginTrackerContext
406    + DeviceCollectionContext<D, BC>
407    + DeviceConfigurationContext<D>
408    + RecvFrameContext<D::FrameMetadata<BaseDeviceId<D, BC>>, BC>
409    + ResourceCounterContext<Self::DeviceId, DeviceCounters>
410    + ResourceCounterContext<Self::DeviceId, D::Counters>
411    + ResourceCounterContext<Self::DeviceId, IgmpCounters>
412    + ResourceCounterContext<Self::DeviceId, MldCounters>
413    + CoreTimerContext<D::TimerId<Self::WeakDeviceId>, BC>
414{
415}
416
417impl<CC, D, BC> DeviceApiCoreContext<D, BC> for CC
418where
419    D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
420    BC: DeviceApiBindingsContext,
421    CC: DeviceIdContext<D, DeviceId = BaseDeviceId<D, BC>, WeakDeviceId = BaseWeakDeviceId<D, BC>>
422        + OriginTrackerContext
423        + DeviceCollectionContext<D, BC>
424        + DeviceConfigurationContext<D>
425        + RecvFrameContext<D::FrameMetadata<BaseDeviceId<D, BC>>, BC>
426        + ResourceCounterContext<Self::DeviceId, DeviceCounters>
427        + ResourceCounterContext<Self::DeviceId, D::Counters>
428        + ResourceCounterContext<Self::DeviceId, IgmpCounters>
429        + ResourceCounterContext<Self::DeviceId, MldCounters>
430        + CoreTimerContext<D::TimerId<Self::WeakDeviceId>, BC>,
431{
432}
433
434/// A marker trait for all the bindings context traits required to fulfill the
435/// [`DeviceApi`].
436pub trait DeviceApiBindingsContext: DeviceLayerTypes + ReferenceNotifiers + TimerContext {}
437
438impl<O> DeviceApiBindingsContext for O where O: DeviceLayerTypes + ReferenceNotifiers + TimerContext {}
439
440/// A marker trait with traits required to tie the device layer with the IP
441/// layer to fulfill [`DeviceApi`].
442pub trait DeviceApiIpLayerCoreContext<D: Device, BC: DeviceLayerTypes>:
443    DeviceIdAnyCompatContext<D>
444    + IpAddressIdSpecContext
445    + CoreTimerContext<
446        IpDeviceTimerId<
447            Ipv6,
448            <Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
449            Self::AddressIdSpec,
450        >,
451        BC,
452    > + CoreTimerContext<
453        IpDeviceTimerId<
454            Ipv4,
455            <Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
456            Self::AddressIdSpec,
457        >,
458        BC,
459    >
460{
461}
462
463impl<O, D, BC> DeviceApiIpLayerCoreContext<D, BC> for O
464where
465    D: Device,
466    BC: DeviceLayerTypes,
467    O: DeviceIdAnyCompatContext<D>
468        + IpAddressIdSpecContext
469        + CoreTimerContext<
470            IpDeviceTimerId<
471                Ipv6,
472                <Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
473                Self::AddressIdSpec,
474            >,
475            BC,
476        > + CoreTimerContext<
477            IpDeviceTimerId<
478                Ipv4,
479                <Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
480                Self::AddressIdSpec,
481            >,
482            BC,
483        >,
484{
485}