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