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