nrf52840dk_test_appid_sha256/
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 core::ptr::{addr_of, addr_of_mut};
12
13use kernel::component::Component;
14use kernel::hil::led::LedLow;
15use kernel::hil::time::Counter;
16use kernel::platform::{KernelResources, SyscallDriverLookup};
17use kernel::scheduler::round_robin::RoundRobinSched;
18use kernel::{capabilities, create_capability, static_init};
19use nrf52840::gpio::Pin;
20use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
21use nrf52_components::{UartChannel, UartPins};
22
23// The nRF52840DK LEDs (see back of board)
24const LED1_PIN: Pin = Pin::P0_13;
25const LED2_PIN: Pin = Pin::P0_14;
26const LED3_PIN: Pin = Pin::P0_15;
27const LED4_PIN: Pin = Pin::P0_16;
28
29const BUTTON_RST_PIN: Pin = Pin::P0_18;
30
31const UART_RTS: Option<Pin> = Some(Pin::P0_05);
32const UART_TXD: Pin = Pin::P0_06;
33const UART_CTS: Option<Pin> = Some(Pin::P0_07);
34const UART_RXD: Pin = Pin::P0_08;
35
36/// Debug Writer
37pub mod io;
38
39// State for loading and holding applications.
40// How should the kernel respond when a process faults.
41const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
42    capsules_system::process_policies::PanicFaultPolicy {};
43
44// Number of concurrent processes this platform supports.
45const NUM_PROCS: usize = 8;
46
47static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
48    [None; NUM_PROCS];
49
50static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
51
52/// Dummy buffer that causes the linker to reserve enough space for the stack.
53#[no_mangle]
54#[link_section = ".stack_buffer"]
55pub static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
56
57//------------------------------------------------------------------------------
58// SYSCALL DRIVER TYPE DEFINITIONS
59//------------------------------------------------------------------------------
60
61type AlarmDriver = components::alarm::AlarmDriverComponentType<nrf52840::rtc::Rtc<'static>>;
62
63/// Supported drivers by the platform
64pub struct Platform {
65    console: &'static capsules_core::console::Console<'static>,
66    led: &'static capsules_core::led::LedDriver<
67        'static,
68        kernel::hil::led::LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
69        4,
70    >,
71    alarm: &'static AlarmDriver,
72    scheduler: &'static RoundRobinSched<'static>,
73    systick: cortexm4::systick::SysTick,
74}
75
76impl SyscallDriverLookup for Platform {
77    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
78    where
79        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
80    {
81        match driver_num {
82            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
83            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
84            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
85            _ => f(None),
86        }
87    }
88}
89
90/// This is in a separate, inline(never) function so that its stack frame is
91/// removed when this function returns. Otherwise, the stack space used for
92/// these static_inits is wasted.
93#[inline(never)]
94unsafe fn create_peripherals() -> &'static mut Nrf52840DefaultPeripherals<'static> {
95    let ieee802154_ack_buf = static_init!(
96        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
97        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
98    );
99    // Initialize chip peripheral drivers
100    let nrf52840_peripherals = static_init!(
101        Nrf52840DefaultPeripherals,
102        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
103    );
104
105    nrf52840_peripherals
106}
107
108impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
109    for Platform
110{
111    type SyscallDriverLookup = Self;
112    type SyscallFilter = ();
113    type ProcessFault = ();
114    type Scheduler = RoundRobinSched<'static>;
115    type SchedulerTimer = cortexm4::systick::SysTick;
116    type WatchDog = ();
117    type ContextSwitchCallback = ();
118
119    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
120        self
121    }
122    fn syscall_filter(&self) -> &Self::SyscallFilter {
123        &()
124    }
125    fn process_fault(&self) -> &Self::ProcessFault {
126        &()
127    }
128    fn scheduler(&self) -> &Self::Scheduler {
129        self.scheduler
130    }
131    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
132        &self.systick
133    }
134    fn watchdog(&self) -> &Self::WatchDog {
135        &()
136    }
137    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
138        &()
139    }
140}
141
142/// Main function called after RAM initialized.
143#[no_mangle]
144pub unsafe fn main() {
145    //--------------------------------------------------------------------------
146    // INITIAL SETUP
147    //--------------------------------------------------------------------------
148
149    // Apply errata fixes and enable interrupts.
150    nrf52840::init();
151
152    // Set up peripheral drivers. Called in separate function to reduce stack
153    // usage.
154    let nrf52840_peripherals = create_peripherals();
155
156    // Set up circular peripheral dependencies.
157    nrf52840_peripherals.init();
158    let base_peripherals = &nrf52840_peripherals.nrf52;
159
160    // Choose the channel for serial output. This board can be configured to use
161    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
162    // pins.
163    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
164
165    // Setup space to store the core kernel data structure.
166    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
167
168    // Create (and save for panic debugging) a chip object to setup low-level
169    // resources (e.g. MPU, systick).
170    let chip = static_init!(
171        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
172        nrf52840::chip::NRF52::new(nrf52840_peripherals)
173    );
174    CHIP = Some(chip);
175
176    // Do nRF configuration and setup. This is shared code with other nRF-based
177    // platforms.
178    nrf52_components::startup::NrfStartupComponent::new(
179        false,
180        BUTTON_RST_PIN,
181        nrf52840::uicr::Regulator0Output::DEFAULT,
182        &base_peripherals.nvmc,
183    )
184    .finalize(());
185
186    //--------------------------------------------------------------------------
187    // CAPABILITIES
188    //--------------------------------------------------------------------------
189
190    // Create capabilities that the board needs to call certain protected kernel
191    // functions.
192    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
193
194    //--------------------------------------------------------------------------
195    // LEDs
196    //--------------------------------------------------------------------------
197
198    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
199        LedLow<'static, nrf52840::gpio::GPIOPin>,
200        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
201        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
202        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
203        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
204    ));
205
206    //--------------------------------------------------------------------------
207    // TIMER
208    //--------------------------------------------------------------------------
209
210    let rtc = &base_peripherals.rtc;
211    let _ = rtc.start();
212    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
213        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
214    let alarm = components::alarm::AlarmDriverComponent::new(
215        board_kernel,
216        capsules_core::alarm::DRIVER_NUM,
217        mux_alarm,
218    )
219    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
220
221    //--------------------------------------------------------------------------
222    // UART & CONSOLE & DEBUG
223    //--------------------------------------------------------------------------
224
225    let uart_channel = nrf52_components::UartChannelComponent::new(
226        uart_channel,
227        mux_alarm,
228        &base_peripherals.uarte0,
229    )
230    .finalize(nrf52_components::uart_channel_component_static!(
231        nrf52840::rtc::Rtc
232    ));
233
234    // Virtualize the UART channel for the console and for kernel debug.
235    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
236        .finalize(components::uart_mux_component_static!());
237
238    // Setup the serial console for userspace.
239    let console = components::console::ConsoleComponent::new(
240        board_kernel,
241        capsules_core::console::DRIVER_NUM,
242        uart_mux,
243    )
244    .finalize(components::console_component_static!());
245
246    //--------------------------------------------------------------------------
247    // NRF CLOCK SETUP
248    //--------------------------------------------------------------------------
249
250    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
251
252    //--------------------------------------------------------------------------
253    // Credential Checking
254    //--------------------------------------------------------------------------
255
256    // Create the software-based SHA engine.
257    let sha = components::sha::ShaSoftware256Component::new()
258        .finalize(components::sha_software_256_component_static!());
259
260    // Create the credential checker.
261    let checking_policy = components::appid::checker_sha::AppCheckerSha256Component::new(sha)
262        .finalize(components::app_checker_sha256_component_static!());
263
264    // Create the AppID assigner.
265    let assigner = components::appid::assigner_name::AppIdAssignerNamesComponent::new()
266        .finalize(components::appid_assigner_names_component_static!());
267
268    // Create the process checking machine.
269    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
270        .finalize(components::process_checker_machine_component_static!());
271
272    //--------------------------------------------------------------------------
273    // STORAGE PERMISSIONS
274    //--------------------------------------------------------------------------
275
276    let storage_permissions_policy =
277        components::storage_permissions::null::StoragePermissionsNullComponent::new().finalize(
278            components::storage_permissions_null_component_static!(
279                nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
280                kernel::process::ProcessStandardDebugFull,
281            ),
282        );
283
284    //--------------------------------------------------------------------------
285    // PROCESS LOADING
286    //--------------------------------------------------------------------------
287
288    // These symbols are defined in the standard Tock linker script.
289    extern "C" {
290        /// Beginning of the ROM region containing app images.
291        static _sapps: u8;
292        /// End of the ROM region containing app images.
293        static _eapps: u8;
294        /// Beginning of the RAM region for app memory.
295        static mut _sappmem: u8;
296        /// End of the RAM region for app memory.
297        static _eappmem: u8;
298    }
299
300    let app_flash = core::slice::from_raw_parts(
301        core::ptr::addr_of!(_sapps),
302        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
303    );
304    let app_memory = core::slice::from_raw_parts_mut(
305        core::ptr::addr_of_mut!(_sappmem),
306        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
307    );
308
309    // Create and start the asynchronous process loader.
310    let _loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
311        checker,
312        &mut *addr_of_mut!(PROCESSES),
313        board_kernel,
314        chip,
315        &FAULT_RESPONSE,
316        assigner,
317        storage_permissions_policy,
318        app_flash,
319        app_memory,
320    )
321    .finalize(components::process_loader_sequential_component_static!(
322        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
323        kernel::process::ProcessStandardDebugFull,
324        NUM_PROCS
325    ));
326
327    //--------------------------------------------------------------------------
328    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
329    //--------------------------------------------------------------------------
330
331    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
332        .finalize(components::round_robin_component_static!(NUM_PROCS));
333
334    let platform = Platform {
335        console,
336        led,
337        alarm,
338        scheduler,
339        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
340    };
341
342    board_kernel.kernel_loop(
343        &platform,
344        chip,
345        None::<&kernel::ipc::IPC<0>>,
346        &main_loop_capability,
347    );
348}