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