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