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