netstack3_core/
context.rs

1// Copyright 2019 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//! Execution contexts.
6//!
7//! This module defines "context" traits, which allow code in this crate to be
8//! written agnostic to their execution context.
9//!
10//! All of the code in this crate operates in terms of "events". When an event
11//! occurs (for example, a packet is received, an application makes a request,
12//! or a timer fires), a function is called to handle that event. In response to
13//! that event, the code may wish to emit new events (for example, to send a
14//! packet, to respond to an application request, or to install a new timer).
15//! The traits in this module provide the ability to emit new events. For
16//! example, if, in order to handle some event, we need the ability to install
17//! new timers, then the function to handle that event would take a
18//! [`TimerContext`] parameter, which it could use to install new timers.
19//!
20//! Structuring code this way allows us to write code which is agnostic to
21//! execution context - a test fake or any number of possible "real-world"
22//! implementations of these traits all appear as indistinguishable, opaque
23//! trait implementations to our code.
24//!
25//! The benefits are deeper than this, though. Large units of code can be
26//! subdivided into smaller units that view each other as "contexts". For
27//! example, the ARP implementation in the [`crate::device::arp`] module defines
28//! the [`ArpContext`] trait, which is an execution context for ARP operations.
29//! It is implemented both by the test fakes in that module, and also by the
30//! Ethernet device implementation in the [`crate::device::ethernet`] module.
31//!
32//! This subdivision of code into small units in turn enables modularity. If,
33//! for example, the IP code sees transport layer protocols as execution
34//! contexts, then customizing which transport layer protocols are supported is
35//! just a matter of providing a different implementation of the transport layer
36//! context traits (this isn't what we do today, but we may in the future).
37
38use lock_order::Unlocked;
39
40use netstack3_base::ContextProvider;
41use {netstack3_device as device, netstack3_ip as ip, netstack3_udp as udp};
42
43use crate::marker::{BindingsContext, BindingsTypes};
44use crate::state::StackState;
45
46// Enable all blanket implementations on CoreCtx.
47//
48// Some blanket implementations are enabled individually to sidestep coherence
49// issues with the fake context implementations in tests. We treat each of them
50// individually so it's easier to split things into separate crates and avoids
51// playing whack-a-mole with single markers that work for some traits/crates but
52// not others.
53impl<BC: BindingsContext, L> ip::marker::UseTransportIpContextBlanket for CoreCtx<'_, BC, L> {}
54impl<BC: BindingsContext, L> ip::marker::UseIpSocketContextBlanket for CoreCtx<'_, BC, L> {}
55impl<BC: BindingsContext, L> ip::marker::UseIpSocketHandlerBlanket for CoreCtx<'_, BC, L> {}
56impl<BC: BindingsContext, L> ip::marker::UseDeviceIpSocketHandlerBlanket for CoreCtx<'_, BC, L> {}
57impl<BC: BindingsContext, L> udp::UseUdpIpTransportContextBlanket for CoreCtx<'_, BC, L> {}
58impl<BC: BindingsContext, L> device::marker::UseArpFrameMetadataBlanket for CoreCtx<'_, BC, L> {}
59
60/// Provides access to core context implementations.
61///
62/// `L` is the current lock level of `CoreCtx`. The alias [`UnlockedCoreCtx`] is
63/// provided at the [`Unlocked`] level.
64pub type CoreCtx<'a, BT, L> = Locked<&'a StackState<BT>, L>;
65
66pub(crate) type CoreCtxAndResource<'a, BT, R, L> =
67    Locked<lock_order::OwnedTupleWrapper<&'a StackState<BT>, &'a R>, L>;
68
69/// An alias for an unlocked [`CoreCtx`].
70pub type UnlockedCoreCtx<'a, BT> = CoreCtx<'a, BT, Unlocked>;
71
72impl<'a, BT, L> ContextProvider for CoreCtx<'a, BT, L>
73where
74    BT: BindingsTypes,
75{
76    type Context = Self;
77
78    fn context(&mut self) -> &mut Self::Context {
79        self
80    }
81}
82
83pub(crate) use locked::{Locked, WrapLockLevel};
84
85/// Prelude import to enable the lock wrapper traits.
86pub(crate) mod prelude {
87    #[cfg(no_lock_order)]
88    pub(crate) use lock_order::wrap::disable::prelude::*;
89    #[cfg(not(no_lock_order))]
90    pub(crate) use lock_order::wrap::prelude::*;
91}
92
93/// Provides a crate-local wrapper for `[lock_order::Locked]`.
94///
95/// This module is intentionally private so usage is limited to the type alias
96/// in [`CoreCtx`].
97mod locked {
98    use super::{BindingsTypes, CoreCtx, StackState};
99
100    use core::ops::Deref;
101    use lock_order::wrap::LockedWrapper;
102    use lock_order::{Locked as ExternalLocked, TupleWrapper, Unlocked};
103
104    /// A crate-local wrapper on [`lock_order::Locked`].
105    pub struct Locked<T, L>(ExternalLocked<T, L>);
106
107    // SAFETY: This is only compiled when lock ordering is disabled.
108    unsafe impl<T, L> lock_order::wrap::disable::DisabledLockWrapper for Locked<T, L> {}
109
110    impl<T, L> LockedWrapper<T, L> for Locked<T, L>
111    where
112        T: Deref,
113        T::Target: Sized,
114    {
115        type AtLockLevel<'l, M>
116            = Locked<&'l T::Target, M>
117        where
118            M: 'l,
119            T: 'l;
120
121        type CastWrapper<X>
122            = Locked<X, L>
123        where
124            X: Deref,
125            X::Target: Sized;
126
127        fn wrap<'l, M>(locked: ExternalLocked<&'l T::Target, M>) -> Self::AtLockLevel<'l, M>
128        where
129            M: 'l,
130            T: 'l,
131        {
132            Locked(locked)
133        }
134
135        fn wrap_cast<R: Deref>(locked: ExternalLocked<R, L>) -> Self::CastWrapper<R>
136        where
137            R::Target: Sized,
138        {
139            Locked(locked)
140        }
141
142        fn get_mut(&mut self) -> &mut ExternalLocked<T, L> {
143            let Self(locked) = self;
144            locked
145        }
146
147        fn get(&self) -> &ExternalLocked<T, L> {
148            let Self(locked) = self;
149            locked
150        }
151    }
152
153    impl<'a, BT: BindingsTypes> CoreCtx<'a, BT, Unlocked> {
154        /// Creates a new `CoreCtx` from a borrowed [`StackState`].
155        pub fn new(stack_state: &'a StackState<BT>) -> Self {
156            Self(ExternalLocked::new(stack_state))
157        }
158    }
159
160    impl<'a, BT, R, L, T> Locked<T, L>
161    where
162        R: 'a,
163        T: Deref<Target = TupleWrapper<&'a StackState<BT>, &'a R>>,
164        BT: BindingsTypes,
165    {
166        pub(crate) fn cast_core_ctx(&mut self) -> CoreCtx<'_, BT, L> {
167            let Self(locked) = self;
168            crate::CoreCtx::<BT, L>::wrap(locked.cast_with(|c| c.left()))
169        }
170    }
171
172    /// Enables the [`WrapLockLevel`] type alias.
173    pub trait WrappedLockLevel {
174        type LockLevel;
175    }
176
177    impl<L> WrappedLockLevel for L {
178        /// All lock levels are actually [`Unlocked`].
179        #[cfg(no_lock_order)]
180        type LockLevel = Unlocked;
181        /// All lock levels are themselves.
182        #[cfg(not(no_lock_order))]
183        type LockLevel = L;
184    }
185
186    /// Wraps lock level `L` in [`WrappedLockLevel::LockLevel`], which allows
187    /// lock ordering to be disabled by build configuration.
188    ///
189    /// Whenever using a concrete instantiation of a lock level (i.e. not in a
190    /// `LockBefore` trait bound) it must be wrapped in `WrapLockLevel` for
191    /// compilation with `cfg(no_lock_order)` to succeed.
192    pub(crate) type WrapLockLevel<L> = <L as WrappedLockLevel>::LockLevel;
193}