nrf52840dk_test_dynamic_app_load/
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::process::ProcessLoadingAsync;
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
23// The nRF52840DK LEDs (see back of board)
24const LED1_PIN: Pin = Pin::P0_13;
25const LED2_PIN: Pin = Pin::P0_14;
26const LED3_PIN: Pin = Pin::P0_15;
27const LED4_PIN: Pin = Pin::P0_16;
28
29// The nRF52840DK buttons (see back of board)
30const BUTTON1_PIN: Pin = Pin::P0_11;
31const BUTTON2_PIN: Pin = Pin::P0_12;
32const BUTTON3_PIN: Pin = Pin::P0_24;
33const BUTTON4_PIN: Pin = Pin::P0_25;
34const BUTTON_RST_PIN: Pin = Pin::P0_18;
35
36const UART_RTS: Option<Pin> = Some(Pin::P0_05);
37const UART_TXD: Pin = Pin::P0_06;
38const UART_CTS: Option<Pin> = Some(Pin::P0_07);
39const UART_RXD: Pin = Pin::P0_08;
40
41/// Debug Writer
42pub mod io;
43
44// State for loading and holding applications.
45// How should the kernel respond when a process faults.
46const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
47    capsules_system::process_policies::PanicFaultPolicy {};
48
49// Number of concurrent processes this platform supports.
50const NUM_PROCS: usize = 8;
51
52type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
53
54/// Static variables used by io.rs.
55static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
56static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
57// Static reference to process printer for panic dumps.
58static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
59    None;
60
61kernel::stack_size! {0x2000}
62
63//------------------------------------------------------------------------------
64// SYSCALL DRIVER TYPE DEFINITIONS
65//------------------------------------------------------------------------------
66
67type AlarmDriver = components::alarm::AlarmDriverComponentType<nrf52840::rtc::Rtc<'static>>;
68
69type NonVolatilePages = components::dynamic_binary_storage::NVPages<nrf52840::nvmc::Nvmc>;
70type DynamicBinaryStorage<'a> = kernel::dynamic_binary_storage::SequentialDynamicBinaryStorage<
71    'static,
72    'static,
73    nrf52840::chip::NRF52<'a, Nrf52840DefaultPeripherals<'a>>,
74    kernel::process::ProcessStandardDebugFull,
75    NonVolatilePages,
76>;
77
78/// Supported drivers by the platform
79pub struct Platform {
80    console: &'static capsules_core::console::Console<'static>,
81    button: &'static capsules_core::button::Button<'static, nrf52840::gpio::GPIOPin<'static>>,
82    adc: &'static capsules_core::adc::AdcDedicated<'static, nrf52840::adc::Adc<'static>>,
83    led: &'static capsules_core::led::LedDriver<
84        'static,
85        kernel::hil::led::LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
86        4,
87    >,
88    alarm: &'static AlarmDriver,
89    scheduler: &'static RoundRobinSched<'static>,
90    systick: cortexm4::systick::SysTick,
91    processes: &'static ProcessArray<NUM_PROCS>,
92    dynamic_app_loader: &'static capsules_extra::app_loader::AppLoader<
93        DynamicBinaryStorage<'static>,
94        DynamicBinaryStorage<'static>,
95    >,
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_core::button::DRIVER_NUM => f(Some(self.button)),
108            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
109            capsules_extra::app_loader::DRIVER_NUM => f(Some(self.dynamic_app_loader)),
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
167impl kernel::process::ProcessLoadingAsyncClient for Platform {
168    fn process_loaded(&self, _result: Result<(), kernel::process::ProcessLoadError>) {}
169
170    fn process_loading_finished(&self) {
171        kernel::debug!("Processes Loaded at Main:");
172
173        for (i, proc) in self.processes.as_slice().iter().enumerate() {
174            proc.get().map(|p| {
175                kernel::debug!("[{}] {}", i, p.get_process_name());
176                kernel::debug!("    ShortId: {}", p.short_app_id());
177            });
178        }
179    }
180}
181
182/// Main function called after RAM initialized.
183#[no_mangle]
184pub unsafe fn main() {
185    //--------------------------------------------------------------------------
186    // INITIAL SETUP
187    //--------------------------------------------------------------------------
188
189    // Apply errata fixes and enable interrupts.
190    nrf52840::init();
191
192    // Set up peripheral drivers. Called in separate function to reduce stack
193    // usage.
194    let nrf52840_peripherals = create_peripherals();
195
196    // Set up circular peripheral dependencies.
197    nrf52840_peripherals.init();
198    let base_peripherals = &nrf52840_peripherals.nrf52;
199
200    // Choose the channel for serial output. This board can be configured to use
201    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
202    // pins.
203    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
204
205    // Create an array to hold process references.
206    let processes = components::process_array::ProcessArrayComponent::new()
207        .finalize(components::process_array_component_static!(NUM_PROCS));
208    PROCESSES = Some(processes);
209
210    // Setup space to store the core kernel data structure.
211    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
212
213    // Create (and save for panic debugging) a chip object to setup low-level
214    // resources (e.g. MPU, systick).
215    let chip = static_init!(
216        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
217        nrf52840::chip::NRF52::new(nrf52840_peripherals)
218    );
219    CHIP = Some(chip);
220
221    // Do nRF configuration and setup. This is shared code with other nRF-based
222    // platforms.
223    nrf52_components::startup::NrfStartupComponent::new(
224        false,
225        BUTTON_RST_PIN,
226        nrf52840::uicr::Regulator0Output::DEFAULT,
227        &base_peripherals.nvmc,
228    )
229    .finalize(());
230
231    //--------------------------------------------------------------------------
232    // CAPABILITIES
233    //--------------------------------------------------------------------------
234
235    // Create capabilities that the board needs to call certain protected kernel
236    // functions.
237    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
238
239    //--------------------------------------------------------------------------
240    // LEDs
241    //--------------------------------------------------------------------------
242
243    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
244        LedLow<'static, nrf52840::gpio::GPIOPin>,
245        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
246        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
247        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
248        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
249    ));
250
251    //--------------------------------------------------------------------------
252    // TIMER
253    //--------------------------------------------------------------------------
254
255    let rtc = &base_peripherals.rtc;
256    let _ = rtc.start();
257    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
258        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
259    let alarm = components::alarm::AlarmDriverComponent::new(
260        board_kernel,
261        capsules_core::alarm::DRIVER_NUM,
262        mux_alarm,
263    )
264    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
265
266    //--------------------------------------------------------------------------
267    // UART & CONSOLE & DEBUG
268    //--------------------------------------------------------------------------
269
270    let uart_channel = nrf52_components::UartChannelComponent::new(
271        uart_channel,
272        mux_alarm,
273        &base_peripherals.uarte0,
274    )
275    .finalize(nrf52_components::uart_channel_component_static!(
276        nrf52840::rtc::Rtc
277    ));
278
279    // Virtualize the UART channel for the console and for kernel debug.
280    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
281        .finalize(components::uart_mux_component_static!());
282
283    // Setup the serial console for userspace.
284    let console = components::console::ConsoleComponent::new(
285        board_kernel,
286        capsules_core::console::DRIVER_NUM,
287        uart_mux,
288    )
289    .finalize(components::console_component_static!());
290
291    // Tool for displaying information about processes.
292    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
293        .finalize(components::process_printer_text_component_static!());
294    PROCESS_PRINTER = Some(process_printer);
295
296    // Create the process console, an interactive terminal for managing
297    // processes.
298    let pconsole = components::process_console::ProcessConsoleComponent::new(
299        board_kernel,
300        uart_mux,
301        mux_alarm,
302        process_printer,
303        Some(cortexm4::support::reset),
304    )
305    .finalize(components::process_console_component_static!(
306        nrf52840::rtc::Rtc<'static>
307    ));
308
309    // Create the debugger object that handles calls to `debug!()`.
310    components::debug_writer::DebugWriterComponent::new::<
311        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
312    >(
313        uart_mux,
314        create_capability!(capabilities::SetDebugWriterCapability),
315    )
316    .finalize(components::debug_writer_component_static!());
317
318    //--------------------------------------------------------------------------
319    // BUTTONS
320    //--------------------------------------------------------------------------
321
322    let button = components::button::ButtonComponent::new(
323        board_kernel,
324        capsules_core::button::DRIVER_NUM,
325        components::button_component_helper!(
326            nrf52840::gpio::GPIOPin,
327            (
328                &nrf52840_peripherals.gpio_port[BUTTON1_PIN],
329                kernel::hil::gpio::ActivationMode::ActiveLow,
330                kernel::hil::gpio::FloatingState::PullUp
331            ),
332            (
333                &nrf52840_peripherals.gpio_port[BUTTON2_PIN],
334                kernel::hil::gpio::ActivationMode::ActiveLow,
335                kernel::hil::gpio::FloatingState::PullUp
336            ),
337            (
338                &nrf52840_peripherals.gpio_port[BUTTON3_PIN],
339                kernel::hil::gpio::ActivationMode::ActiveLow,
340                kernel::hil::gpio::FloatingState::PullUp
341            ),
342            (
343                &nrf52840_peripherals.gpio_port[BUTTON4_PIN],
344                kernel::hil::gpio::ActivationMode::ActiveLow,
345                kernel::hil::gpio::FloatingState::PullUp
346            )
347        ),
348    )
349    .finalize(components::button_component_static!(
350        nrf52840::gpio::GPIOPin
351    ));
352
353    //--------------------------------------------------------------------------
354    // ADC
355    //--------------------------------------------------------------------------
356
357    let adc_channels = static_init!(
358        [nrf52840::adc::AdcChannelSetup; 6],
359        [
360            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput1),
361            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput2),
362            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput4),
363            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput5),
364            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput6),
365            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput7),
366        ]
367    );
368    let adc = components::adc::AdcDedicatedComponent::new(
369        &base_peripherals.adc,
370        adc_channels,
371        board_kernel,
372        capsules_core::adc::DRIVER_NUM,
373    )
374    .finalize(components::adc_dedicated_component_static!(
375        nrf52840::adc::Adc
376    ));
377
378    //--------------------------------------------------------------------------
379    // NRF CLOCK SETUP
380    //--------------------------------------------------------------------------
381
382    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
383
384    //--------------------------------------------------------------------------
385    // Credential Checking
386    //--------------------------------------------------------------------------
387
388    // Create the credential checker.
389    let checking_policy = components::appid::checker_null::AppCheckerNullComponent::new()
390        .finalize(components::app_checker_null_component_static!());
391
392    // Create the AppID assigner.
393    let assigner = components::appid::assigner_tbf::AppIdAssignerTbfHeaderComponent::new()
394        .finalize(components::appid_assigner_tbf_header_component_static!());
395
396    // Create the process checking machine.
397    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
398        .finalize(components::process_checker_machine_component_static!());
399
400    //--------------------------------------------------------------------------
401    // STORAGE PERMISSIONS
402    //--------------------------------------------------------------------------
403
404    let storage_permissions_policy =
405        components::storage_permissions::null::StoragePermissionsNullComponent::new().finalize(
406            components::storage_permissions_null_component_static!(
407                nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
408                kernel::process::ProcessStandardDebugFull,
409            ),
410        );
411
412    // These symbols are defined in the standard Tock linker script.
413    extern "C" {
414        /// Beginning of the ROM region containing app images.
415        static _sapps: u8;
416        /// End of the ROM region containing app images.
417        static _eapps: u8;
418        /// Beginning of the RAM region for app memory.
419        static mut _sappmem: u8;
420        /// End of the RAM region for app memory.
421        static _eappmem: u8;
422    }
423
424    let app_flash = core::slice::from_raw_parts(
425        core::ptr::addr_of!(_sapps),
426        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
427    );
428    let app_memory = core::slice::from_raw_parts_mut(
429        core::ptr::addr_of_mut!(_sappmem),
430        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
431    );
432
433    // Create and start the asynchronous process loader.
434    let loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
435        checker,
436        board_kernel,
437        chip,
438        &FAULT_RESPONSE,
439        assigner,
440        storage_permissions_policy,
441        app_flash,
442        app_memory,
443    )
444    .finalize(components::process_loader_sequential_component_static!(
445        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
446        kernel::process::ProcessStandardDebugFull,
447        NUM_PROCS
448    ));
449
450    //--------------------------------------------------------------------------
451    // Dynamic App Loading
452    //--------------------------------------------------------------------------
453
454    // Create the dynamic binary flasher.
455    let dynamic_binary_storage =
456        components::dynamic_binary_storage::SequentialBinaryStorageComponent::new(
457            &base_peripherals.nvmc,
458            loader,
459        )
460        .finalize(components::sequential_binary_storage_component_static!(
461            nrf52840::nvmc::Nvmc,
462            nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
463            kernel::process::ProcessStandardDebugFull,
464        ));
465
466    // Create the dynamic app loader capsule.
467    let dynamic_app_loader = components::app_loader::AppLoaderComponent::new(
468        board_kernel,
469        capsules_extra::app_loader::DRIVER_NUM,
470        dynamic_binary_storage,
471        dynamic_binary_storage,
472    )
473    .finalize(components::app_loader_component_static!(
474        DynamicBinaryStorage<'static>,
475        DynamicBinaryStorage<'static>,
476    ));
477
478    //--------------------------------------------------------------------------
479    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
480    //--------------------------------------------------------------------------
481
482    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
483        .finalize(components::round_robin_component_static!(NUM_PROCS));
484
485    let platform = static_init!(
486        Platform,
487        Platform {
488            console,
489            button,
490            adc,
491            led,
492            alarm,
493            scheduler,
494            systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
495            processes,
496            dynamic_app_loader,
497        }
498    );
499    loader.set_client(platform);
500
501    let _ = pconsole.start();
502
503    board_kernel.kernel_loop(
504        platform,
505        chip,
506        None::<&kernel::ipc::IPC<0>>,
507        &main_loop_capability,
508    );
509}