nrf52840dk_test_invs/
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
23mod invs_permissions;
24
25// The nRF52840DK LEDs (see back of board)
26const LED1_PIN: Pin = Pin::P0_13;
27const LED2_PIN: Pin = Pin::P0_14;
28const LED3_PIN: Pin = Pin::P0_15;
29const LED4_PIN: Pin = Pin::P0_16;
30
31const BUTTON_RST_PIN: Pin = Pin::P0_18;
32
33const UART_RTS: Option<Pin> = Some(Pin::P0_05);
34const UART_TXD: Pin = Pin::P0_06;
35const UART_CTS: Option<Pin> = Some(Pin::P0_07);
36const UART_RXD: Pin = Pin::P0_08;
37
38const SPI_MOSI: Pin = Pin::P0_20;
39const SPI_MISO: Pin = Pin::P0_21;
40const SPI_CLK: Pin = Pin::P0_19;
41
42const SPI_MX25R6435F_CHIP_SELECT: Pin = Pin::P0_17;
43const SPI_MX25R6435F_WRITE_PROTECT_PIN: Pin = Pin::P0_22;
44const SPI_MX25R6435F_HOLD_PIN: Pin = Pin::P0_23;
45
46/// Debug Writer
47pub mod io;
48
49// State for loading and holding applications.
50// How should the kernel respond when a process faults.
51const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
52    capsules_system::process_policies::PanicFaultPolicy {};
53
54// Number of concurrent processes this platform supports.
55const NUM_PROCS: usize = 8;
56
57static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
58    [None; NUM_PROCS];
59
60static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
61
62/// Dummy buffer that causes the linker to reserve enough space for the stack.
63#[no_mangle]
64#[link_section = ".stack_buffer"]
65pub static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
66
67const APP_STORAGE_REGION_SIZE: usize = 4096;
68
69//------------------------------------------------------------------------------
70// SYSCALL DRIVER TYPE DEFINITIONS
71//------------------------------------------------------------------------------
72
73type AlarmDriver = components::alarm::AlarmDriverComponentType<nrf52840::rtc::Rtc<'static>>;
74
75type Mx25r6435f = components::mx25r6435f::Mx25r6435fComponentType<
76    nrf52840::spi::SPIM<'static>,
77    nrf52840::gpio::GPIOPin<'static>,
78    nrf52840::rtc::Rtc<'static>,
79>;
80type InvsDriver = components::isolated_nonvolatile_storage::IsolatedNonvolatileStorageComponentType<
81    APP_STORAGE_REGION_SIZE,
82>;
83
84/// Supported drivers by the platform
85pub struct Platform {
86    console: &'static capsules_core::console::Console<'static>,
87    led: &'static capsules_core::led::LedDriver<
88        'static,
89        kernel::hil::led::LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
90        4,
91    >,
92    alarm: &'static AlarmDriver,
93    invs: &'static InvsDriver,
94    scheduler: &'static RoundRobinSched<'static>,
95    systick: cortexm4::systick::SysTick,
96}
97
98impl SyscallDriverLookup for Platform {
99    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
100    where
101        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
102    {
103        match driver_num {
104            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
105            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
106            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
107            capsules_extra::isolated_nonvolatile_storage_driver::DRIVER_NUM => f(Some(self.invs)),
108            _ => f(None),
109        }
110    }
111}
112
113/// This is in a separate, inline(never) function so that its stack frame is
114/// removed when this function returns. Otherwise, the stack space used for
115/// these static_inits is wasted.
116#[inline(never)]
117unsafe fn create_peripherals() -> &'static mut Nrf52840DefaultPeripherals<'static> {
118    let ieee802154_ack_buf = static_init!(
119        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
120        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
121    );
122    // Initialize chip peripheral drivers
123    let nrf52840_peripherals = static_init!(
124        Nrf52840DefaultPeripherals,
125        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
126    );
127
128    nrf52840_peripherals
129}
130
131impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
132    for Platform
133{
134    type SyscallDriverLookup = Self;
135    type SyscallFilter = ();
136    type ProcessFault = ();
137    type Scheduler = RoundRobinSched<'static>;
138    type SchedulerTimer = cortexm4::systick::SysTick;
139    type WatchDog = ();
140    type ContextSwitchCallback = ();
141
142    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
143        self
144    }
145    fn syscall_filter(&self) -> &Self::SyscallFilter {
146        &()
147    }
148    fn process_fault(&self) -> &Self::ProcessFault {
149        &()
150    }
151    fn scheduler(&self) -> &Self::Scheduler {
152        self.scheduler
153    }
154    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
155        &self.systick
156    }
157    fn watchdog(&self) -> &Self::WatchDog {
158        &()
159    }
160    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
161        &()
162    }
163}
164
165/// Main function called after RAM initialized.
166#[no_mangle]
167pub unsafe fn main() {
168    //--------------------------------------------------------------------------
169    // INITIAL SETUP
170    //--------------------------------------------------------------------------
171
172    // Apply errata fixes and enable interrupts.
173    nrf52840::init();
174
175    // Set up peripheral drivers. Called in separate function to reduce stack
176    // usage.
177    let nrf52840_peripherals = create_peripherals();
178
179    // Set up circular peripheral dependencies.
180    nrf52840_peripherals.init();
181    let base_peripherals = &nrf52840_peripherals.nrf52;
182
183    // Choose the channel for serial output. This board can be configured to use
184    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
185    // pins.
186    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
187
188    // Setup space to store the core kernel data structure.
189    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
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    CHIP = Some(chip);
198
199    // Do nRF configuration and setup. This is shared code with other nRF-based
200    // platforms.
201    nrf52_components::startup::NrfStartupComponent::new(
202        false,
203        BUTTON_RST_PIN,
204        nrf52840::uicr::Regulator0Output::DEFAULT,
205        &base_peripherals.nvmc,
206    )
207    .finalize(());
208
209    //--------------------------------------------------------------------------
210    // CAPABILITIES
211    //--------------------------------------------------------------------------
212
213    // Create capabilities that the board needs to call certain protected kernel
214    // functions.
215    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
216
217    //--------------------------------------------------------------------------
218    // LEDs
219    //--------------------------------------------------------------------------
220
221    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
222        LedLow<'static, nrf52840::gpio::GPIOPin>,
223        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
224        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
225        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
226        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
227    ));
228
229    //--------------------------------------------------------------------------
230    // TIMER
231    //--------------------------------------------------------------------------
232
233    let rtc = &base_peripherals.rtc;
234    let _ = rtc.start();
235    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
236        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
237    let alarm = components::alarm::AlarmDriverComponent::new(
238        board_kernel,
239        capsules_core::alarm::DRIVER_NUM,
240        mux_alarm,
241    )
242    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
243
244    //--------------------------------------------------------------------------
245    // UART & CONSOLE & DEBUG
246    //--------------------------------------------------------------------------
247
248    let uart_channel = nrf52_components::UartChannelComponent::new(
249        uart_channel,
250        mux_alarm,
251        &base_peripherals.uarte0,
252    )
253    .finalize(nrf52_components::uart_channel_component_static!(
254        nrf52840::rtc::Rtc
255    ));
256
257    // Virtualize the UART channel for the console and for kernel debug.
258    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
259        .finalize(components::uart_mux_component_static!());
260
261    // Setup the serial console for userspace.
262    let console = components::console::ConsoleComponent::new(
263        board_kernel,
264        capsules_core::console::DRIVER_NUM,
265        uart_mux,
266    )
267    .finalize(components::console_component_static!());
268
269    //--------------------------------------------------------------------------
270    // ONBOARD EXTERNAL FLASH
271    //--------------------------------------------------------------------------
272
273    let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim0)
274        .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
275
276    base_peripherals.spim0.configure(
277        nrf52840::pinmux::Pinmux::new(SPI_MOSI as u32),
278        nrf52840::pinmux::Pinmux::new(SPI_MISO as u32),
279        nrf52840::pinmux::Pinmux::new(SPI_CLK as u32),
280    );
281
282    let mx25r6435f = components::mx25r6435f::Mx25r6435fComponent::new(
283        Some(&nrf52840_peripherals.gpio_port[SPI_MX25R6435F_WRITE_PROTECT_PIN]),
284        Some(&nrf52840_peripherals.gpio_port[SPI_MX25R6435F_HOLD_PIN]),
285        &nrf52840_peripherals.gpio_port[SPI_MX25R6435F_CHIP_SELECT],
286        mux_alarm,
287        mux_spi,
288    )
289    .finalize(components::mx25r6435f_component_static!(
290        nrf52840::spi::SPIM,
291        nrf52840::gpio::GPIOPin,
292        nrf52840::rtc::Rtc
293    ));
294
295    //--------------------------------------------------------------------------
296    // NONVOLATILE STORAGE
297    //--------------------------------------------------------------------------
298
299    let invs = components::isolated_nonvolatile_storage::IsolatedNonvolatileStorageComponent::new(
300        board_kernel,
301        capsules_extra::isolated_nonvolatile_storage_driver::DRIVER_NUM,
302        mx25r6435f,
303        0x40000,  // start address
304        0x100000, // length
305    )
306    .finalize(components::isolated_nonvolatile_storage_component_static!(
307        Mx25r6435f,
308        APP_STORAGE_REGION_SIZE
309    ));
310
311    //--------------------------------------------------------------------------
312    // NRF CLOCK SETUP
313    //--------------------------------------------------------------------------
314
315    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
316
317    //--------------------------------------------------------------------------
318    // Credential Checking
319    //--------------------------------------------------------------------------
320
321    // Create the software-based SHA engine.
322    let sha = components::sha::ShaSoftware256Component::new()
323        .finalize(components::sha_software_256_component_static!());
324
325    // Create the credential checker.
326    let checking_policy = components::appid::checker_sha::AppCheckerSha256Component::new(sha)
327        .finalize(components::app_checker_sha256_component_static!());
328
329    // Create the AppID assigner.
330    let assigner = components::appid::assigner_name::AppIdAssignerNamesComponent::new()
331        .finalize(components::appid_assigner_names_component_static!());
332
333    // Create the process checking machine.
334    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
335        .finalize(components::process_checker_machine_component_static!());
336
337    //--------------------------------------------------------------------------
338    // STORAGE PERMISSIONS
339    //--------------------------------------------------------------------------
340
341    // We use a custom storage permissions assigner that is based on the TBF
342    // header if present, and otherwise defaults to allowing apps to access
343    // their own state.
344
345    #[derive(Clone)]
346    pub struct AppStoreCapability;
347    unsafe impl capabilities::ApplicationStorageCapability for AppStoreCapability {}
348
349    let storage_permissions_policy = static_init!(
350        invs_permissions::InvsStoragePermissions<
351            nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
352            kernel::process::ProcessStandardDebugFull,
353            AppStoreCapability,
354        >,
355        invs_permissions::InvsStoragePermissions::new(AppStoreCapability)
356    );
357
358    //--------------------------------------------------------------------------
359    // PROCESS LOADING
360    //--------------------------------------------------------------------------
361
362    // These symbols are defined in the standard Tock linker script.
363    extern "C" {
364        /// Beginning of the ROM region containing app images.
365        static _sapps: u8;
366        /// End of the ROM region containing app images.
367        static _eapps: u8;
368        /// Beginning of the RAM region for app memory.
369        static mut _sappmem: u8;
370        /// End of the RAM region for app memory.
371        static _eappmem: u8;
372    }
373
374    let app_flash = core::slice::from_raw_parts(
375        core::ptr::addr_of!(_sapps),
376        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
377    );
378    let app_memory = core::slice::from_raw_parts_mut(
379        core::ptr::addr_of_mut!(_sappmem),
380        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
381    );
382
383    // Create and start the asynchronous process loader.
384    let _loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
385        checker,
386        &mut *addr_of_mut!(PROCESSES),
387        board_kernel,
388        chip,
389        &FAULT_RESPONSE,
390        assigner,
391        storage_permissions_policy,
392        app_flash,
393        app_memory,
394    )
395    .finalize(components::process_loader_sequential_component_static!(
396        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
397        kernel::process::ProcessStandardDebugFull,
398        NUM_PROCS
399    ));
400
401    //--------------------------------------------------------------------------
402    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
403    //--------------------------------------------------------------------------
404
405    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
406        .finalize(components::round_robin_component_static!(NUM_PROCS));
407
408    let platform = Platform {
409        console,
410        led,
411        alarm,
412        invs,
413        scheduler,
414        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
415    };
416
417    board_kernel.kernel_loop(
418        &platform,
419        chip,
420        None::<&kernel::ipc::IPC<0>>,
421        &main_loop_capability,
422    );
423}