nrf52840dk_test_kernel/
main.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Tock kernel for the Nordic Semiconductor nRF52840 development kit (DK).
6
7#![no_std]
8#![no_main]
9#![deny(missing_docs)]
10
11use capsules_core::test::capsule_test::{CapsuleTestClient, CapsuleTestError};
12use core::cell::Cell;
13use kernel::component::Component;
14use kernel::hil::time::Counter;
15use kernel::platform::{KernelResources, SyscallDriverLookup};
16use kernel::process::ProcessArray;
17use kernel::scheduler::round_robin::RoundRobinSched;
18use kernel::utilities::cells::NumericCellExt;
19use kernel::{capabilities, create_capability, static_init};
20use nrf52840::chip::Nrf52DefaultPeripherals;
21use nrf52840::gpio::Pin;
22use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
23use nrf52_components::{UartChannel, UartPins};
24
25mod test;
26
27const BUTTON_RST_PIN: Pin = Pin::P0_18;
28
29const UART_RTS: Option<Pin> = Some(Pin::P0_05);
30const UART_TXD: Pin = Pin::P0_06;
31const UART_CTS: Option<Pin> = Some(Pin::P0_07);
32const UART_RXD: Pin = Pin::P0_08;
33
34/// Debug Writer
35pub mod io;
36
37// Number of concurrent processes this platform supports.
38const NUM_PROCS: usize = 0;
39
40type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
41
42/// Static variables used by io.rs.
43static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
44static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
45static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
46    None;
47
48kernel::stack_size! {0x2000}
49
50//------------------------------------------------------------------------------
51// SYSCALL DRIVER TYPE DEFINITIONS
52//------------------------------------------------------------------------------
53
54/// Supported drivers by the platform
55pub struct Platform {
56    scheduler: &'static RoundRobinSched<'static>,
57    systick: cortexm4::systick::SysTick,
58}
59
60impl SyscallDriverLookup for Platform {
61    fn with_driver<F, R>(&self, _driver_num: usize, f: F) -> R
62    where
63        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
64    {
65        f(None)
66    }
67}
68
69//------------------------------------------------------------------------------
70// TEST LAUNCHER FOR RUNNING TESTS
71//------------------------------------------------------------------------------
72
73struct TestLauncher {
74    test_index: Cell<usize>,
75    peripherals: &'static Nrf52DefaultPeripherals<'static>,
76}
77impl TestLauncher {
78    fn new(peripherals: &'static Nrf52DefaultPeripherals<'static>) -> Self {
79        Self {
80            test_index: Cell::new(0),
81            peripherals,
82        }
83    }
84
85    fn next(&'static self) {
86        let index = self.test_index.get();
87        self.test_index.increment();
88        match index {
89            0 => unsafe { test::sha256_test::run_sha256(self) },
90            1 => unsafe { test::hmac_sha256_test::run_hmacsha256(self) },
91            2 => unsafe { test::siphash24_test::run_siphash24(self) },
92            3 => unsafe { test::aes_test::run_aes128_ctr(&self.peripherals.ecb, self) },
93            4 => unsafe { test::aes_test::run_aes128_cbc(&self.peripherals.ecb, self) },
94            5 => unsafe { test::aes_test::run_aes128_ecb(&self.peripherals.ecb, self) },
95            6 => unsafe { test::ecdsa_p256_test::run_ecdsa_p256(self) },
96            _ => kernel::debug!("All tests finished."),
97        }
98    }
99}
100impl CapsuleTestClient for TestLauncher {
101    fn done(&'static self, _result: Result<(), CapsuleTestError>) {
102        self.next();
103    }
104}
105
106/// This is in a separate, inline(never) function so that its stack frame is
107/// removed when this function returns. Otherwise, the stack space used for
108/// these static_inits is wasted.
109#[inline(never)]
110unsafe fn create_peripherals() -> &'static mut Nrf52840DefaultPeripherals<'static> {
111    let ieee802154_ack_buf = static_init!(
112        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
113        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
114    );
115    // Initialize chip peripheral drivers
116    let nrf52840_peripherals = static_init!(
117        Nrf52840DefaultPeripherals,
118        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
119    );
120
121    nrf52840_peripherals
122}
123
124impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
125    for Platform
126{
127    type SyscallDriverLookup = Self;
128    type SyscallFilter = ();
129    type ProcessFault = ();
130    type Scheduler = RoundRobinSched<'static>;
131    type SchedulerTimer = cortexm4::systick::SysTick;
132    type WatchDog = ();
133    type ContextSwitchCallback = ();
134
135    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
136        self
137    }
138    fn syscall_filter(&self) -> &Self::SyscallFilter {
139        &()
140    }
141    fn process_fault(&self) -> &Self::ProcessFault {
142        &()
143    }
144    fn scheduler(&self) -> &Self::Scheduler {
145        self.scheduler
146    }
147    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
148        &self.systick
149    }
150    fn watchdog(&self) -> &Self::WatchDog {
151        &()
152    }
153    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
154        &()
155    }
156}
157
158/// Main function called after RAM initialized.
159#[no_mangle]
160pub unsafe fn main() {
161    //--------------------------------------------------------------------------
162    // INITIAL SETUP
163    //--------------------------------------------------------------------------
164
165    // Apply errata fixes and enable interrupts.
166    nrf52840::init();
167
168    // Initialize deferred calls very early.
169    kernel::deferred_call::initialize_deferred_call_state::<
170        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
171    >();
172
173    // Set up peripheral drivers. Called in separate function to reduce stack
174    // usage.
175    let nrf52840_peripherals = create_peripherals();
176
177    // Set up circular peripheral dependencies.
178    nrf52840_peripherals.init();
179    let base_peripherals = &nrf52840_peripherals.nrf52;
180
181    // Create an array to hold process references.
182    let processes = components::process_array::ProcessArrayComponent::new()
183        .finalize(components::process_array_component_static!(NUM_PROCS));
184    PROCESSES = Some(processes);
185
186    // Setup space to store the core kernel data structure.
187    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
188
189    // Create (and save for panic debugging) a chip object to setup low-level
190    // resources (e.g. MPU, systick).
191    let chip = static_init!(
192        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
193        nrf52840::chip::NRF52::new(nrf52840_peripherals)
194    );
195    CHIP = Some(chip);
196
197    // Do nRF configuration and setup. This is shared code with other nRF-based
198    // platforms.
199    nrf52_components::startup::NrfStartupComponent::new(
200        false,
201        BUTTON_RST_PIN,
202        nrf52840::uicr::Regulator0Output::DEFAULT,
203        &base_peripherals.nvmc,
204    )
205    .finalize(());
206
207    //--------------------------------------------------------------------------
208    // CAPABILITIES
209    //--------------------------------------------------------------------------
210
211    // Create capabilities that the board needs to call certain protected kernel
212    // functions.
213    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
214
215    //--------------------------------------------------------------------------
216    // TIMER
217    //--------------------------------------------------------------------------
218
219    let rtc = &base_peripherals.rtc;
220    let _ = rtc.start();
221    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
222        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
223
224    //--------------------------------------------------------------------------
225    // UART & CONSOLE & DEBUG
226    //--------------------------------------------------------------------------
227
228    let uart_channel = nrf52_components::UartChannelComponent::new(
229        UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD)),
230        mux_alarm,
231        &base_peripherals.uarte0,
232    )
233    .finalize(nrf52_components::uart_channel_component_static!(
234        nrf52840::rtc::Rtc
235    ));
236
237    // Virtualize the UART channel for the console and for kernel debug.
238    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
239        .finalize(components::uart_mux_component_static!());
240
241    // Create the debugger object that handles calls to `debug!()`.
242    components::debug_writer::DebugWriterComponent::new::<
243        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
244    >(
245        uart_mux,
246        create_capability!(capabilities::SetDebugWriterCapability),
247    )
248    .finalize(components::debug_writer_component_static!());
249
250    //--------------------------------------------------------------------------
251    // NRF CLOCK SETUP
252    //--------------------------------------------------------------------------
253
254    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
255
256    //--------------------------------------------------------------------------
257    // PLATFORM AND SCHEDULER
258    //--------------------------------------------------------------------------
259
260    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
261        .finalize(components::round_robin_component_static!(NUM_PROCS));
262
263    let platform = Platform {
264        scheduler,
265        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
266    };
267
268    let test_launcher = static_init!(TestLauncher, TestLauncher::new(base_peripherals));
269
270    //--------------------------------------------------------------------------
271    // TESTS
272    //--------------------------------------------------------------------------
273
274    test_launcher.next();
275
276    //--------------------------------------------------------------------------
277    // KERNEL LOOP
278    //--------------------------------------------------------------------------
279
280    board_kernel.kernel_loop(
281        &platform,
282        chip,
283        None::<&kernel::ipc::IPC<0>>,
284        &main_loop_capability,
285    );
286}