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::debug::PanicResources;
15use kernel::hil::time::Counter;
16use kernel::platform::{KernelResources, SyscallDriverLookup};
17use kernel::scheduler::round_robin::RoundRobinSched;
18use kernel::utilities::cells::NumericCellExt;
19use kernel::utilities::single_thread_value::SingleThreadValue;
20use kernel::{capabilities, create_capability, static_init};
21use nrf52840::chip::Nrf52DefaultPeripherals;
22use nrf52840::gpio::Pin;
23use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
24use nrf52_components::{UartChannel, UartPins};
25
26mod test;
27
28const BUTTON_RST_PIN: Pin = Pin::P0_18;
29
30const UART_RTS: Option<Pin> = Some(Pin::P0_05);
31const UART_TXD: Pin = Pin::P0_06;
32const UART_CTS: Option<Pin> = Some(Pin::P0_07);
33const UART_RXD: Pin = Pin::P0_08;
34
35/// Debug Writer
36pub mod io;
37
38// Number of concurrent processes this platform supports.
39const NUM_PROCS: usize = 0;
40
41type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
42type ProcessPrinter = capsules_system::process_printer::ProcessPrinterNull;
43
44/// Resources for when a board panics used by io.rs.
45static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinter>> =
46    SingleThreadValue::new(PanicResources::new());
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    PANIC_RESOURCES.get().map(|resources| {
185        resources.processes.put(processes.as_slice());
186    });
187
188    // Setup space to store the core kernel data structure.
189    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
190
191    // Create (and save for panic debugging) a chip object to setup low-level
192    // resources (e.g. MPU, systick).
193    let chip = static_init!(
194        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
195        nrf52840::chip::NRF52::new(nrf52840_peripherals)
196    );
197    PANIC_RESOURCES.get().map(|resources| {
198        resources.chip.put(chip);
199    });
200
201    // Do nRF configuration and setup. This is shared code with other nRF-based
202    // platforms.
203    nrf52_components::startup::NrfStartupComponent::new(
204        false,
205        BUTTON_RST_PIN,
206        nrf52840::uicr::Regulator0Output::DEFAULT,
207        &base_peripherals.nvmc,
208    )
209    .finalize(());
210
211    //--------------------------------------------------------------------------
212    // CAPABILITIES
213    //--------------------------------------------------------------------------
214
215    // Create capabilities that the board needs to call certain protected kernel
216    // functions.
217    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
218
219    //--------------------------------------------------------------------------
220    // TIMER
221    //--------------------------------------------------------------------------
222
223    let rtc = &base_peripherals.rtc;
224    let _ = rtc.start();
225    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
226        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
227
228    //--------------------------------------------------------------------------
229    // UART & CONSOLE & DEBUG
230    //--------------------------------------------------------------------------
231
232    let uart_channel = nrf52_components::UartChannelComponent::new(
233        UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD)),
234        mux_alarm,
235        &base_peripherals.uarte0,
236    )
237    .finalize(nrf52_components::uart_channel_component_static!(
238        nrf52840::rtc::Rtc
239    ));
240
241    // Virtualize the UART channel for the console and for kernel debug.
242    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
243        .finalize(components::uart_mux_component_static!());
244
245    // Create the debugger object that handles calls to `debug!()`.
246    components::debug_writer::DebugWriterComponent::new::<
247        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
248    >(
249        uart_mux,
250        create_capability!(capabilities::SetDebugWriterCapability),
251    )
252    .finalize(components::debug_writer_component_static!());
253
254    //--------------------------------------------------------------------------
255    // NRF CLOCK SETUP
256    //--------------------------------------------------------------------------
257
258    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
259
260    //--------------------------------------------------------------------------
261    // PLATFORM AND SCHEDULER
262    //--------------------------------------------------------------------------
263
264    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
265        .finalize(components::round_robin_component_static!(NUM_PROCS));
266
267    let platform = Platform {
268        scheduler,
269        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
270    };
271
272    let test_launcher = static_init!(TestLauncher, TestLauncher::new(base_peripherals));
273
274    //--------------------------------------------------------------------------
275    // TESTS
276    //--------------------------------------------------------------------------
277
278    test_launcher.next();
279
280    //--------------------------------------------------------------------------
281    // KERNEL LOOP
282    //--------------------------------------------------------------------------
283
284    board_kernel.kernel_loop(
285        &platform,
286        chip,
287        None::<&kernel::ipc::IPC<0>>,
288        &main_loop_capability,
289    );
290}