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    // Initialize deferred calls very early.
193    kernel::deferred_call::initialize_deferred_call_state::<
194        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
195    >();
196
197    // Set up peripheral drivers. Called in separate function to reduce stack
198    // usage.
199    let nrf52840_peripherals = create_peripherals();
200
201    // Set up circular peripheral dependencies.
202    nrf52840_peripherals.init();
203    let base_peripherals = &nrf52840_peripherals.nrf52;
204
205    // Choose the channel for serial output. This board can be configured to use
206    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
207    // pins.
208    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
209
210    // Create an array to hold process references.
211    let processes = components::process_array::ProcessArrayComponent::new()
212        .finalize(components::process_array_component_static!(NUM_PROCS));
213    PROCESSES = Some(processes);
214
215    // Setup space to store the core kernel data structure.
216    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
217
218    // Create (and save for panic debugging) a chip object to setup low-level
219    // resources (e.g. MPU, systick).
220    let chip = static_init!(
221        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
222        nrf52840::chip::NRF52::new(nrf52840_peripherals)
223    );
224    CHIP = Some(chip);
225
226    // Do nRF configuration and setup. This is shared code with other nRF-based
227    // platforms.
228    nrf52_components::startup::NrfStartupComponent::new(
229        false,
230        BUTTON_RST_PIN,
231        nrf52840::uicr::Regulator0Output::DEFAULT,
232        &base_peripherals.nvmc,
233    )
234    .finalize(());
235
236    //--------------------------------------------------------------------------
237    // CAPABILITIES
238    //--------------------------------------------------------------------------
239
240    // Create capabilities that the board needs to call certain protected kernel
241    // functions.
242    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
243
244    //--------------------------------------------------------------------------
245    // LEDs
246    //--------------------------------------------------------------------------
247
248    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
249        LedLow<'static, nrf52840::gpio::GPIOPin>,
250        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
251        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
252        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
253        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
254    ));
255
256    //--------------------------------------------------------------------------
257    // TIMER
258    //--------------------------------------------------------------------------
259
260    let rtc = &base_peripherals.rtc;
261    let _ = rtc.start();
262    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
263        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
264    let alarm = components::alarm::AlarmDriverComponent::new(
265        board_kernel,
266        capsules_core::alarm::DRIVER_NUM,
267        mux_alarm,
268    )
269    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
270
271    //--------------------------------------------------------------------------
272    // UART & CONSOLE & DEBUG
273    //--------------------------------------------------------------------------
274
275    let uart_channel = nrf52_components::UartChannelComponent::new(
276        uart_channel,
277        mux_alarm,
278        &base_peripherals.uarte0,
279    )
280    .finalize(nrf52_components::uart_channel_component_static!(
281        nrf52840::rtc::Rtc
282    ));
283
284    // Virtualize the UART channel for the console and for kernel debug.
285    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
286        .finalize(components::uart_mux_component_static!());
287
288    // Setup the serial console for userspace.
289    let console = components::console::ConsoleComponent::new(
290        board_kernel,
291        capsules_core::console::DRIVER_NUM,
292        uart_mux,
293    )
294    .finalize(components::console_component_static!());
295
296    // Tool for displaying information about processes.
297    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
298        .finalize(components::process_printer_text_component_static!());
299    PROCESS_PRINTER = Some(process_printer);
300
301    // Create the process console, an interactive terminal for managing
302    // processes.
303    let pconsole = components::process_console::ProcessConsoleComponent::new(
304        board_kernel,
305        uart_mux,
306        mux_alarm,
307        process_printer,
308        Some(cortexm4::support::reset),
309    )
310    .finalize(components::process_console_component_static!(
311        nrf52840::rtc::Rtc<'static>
312    ));
313
314    // Create the debugger object that handles calls to `debug!()`.
315    components::debug_writer::DebugWriterComponent::new::<
316        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
317    >(
318        uart_mux,
319        create_capability!(capabilities::SetDebugWriterCapability),
320    )
321    .finalize(components::debug_writer_component_static!());
322
323    //--------------------------------------------------------------------------
324    // BUTTONS
325    //--------------------------------------------------------------------------
326
327    let button = components::button::ButtonComponent::new(
328        board_kernel,
329        capsules_core::button::DRIVER_NUM,
330        components::button_component_helper!(
331            nrf52840::gpio::GPIOPin,
332            (
333                &nrf52840_peripherals.gpio_port[BUTTON1_PIN],
334                kernel::hil::gpio::ActivationMode::ActiveLow,
335                kernel::hil::gpio::FloatingState::PullUp
336            ),
337            (
338                &nrf52840_peripherals.gpio_port[BUTTON2_PIN],
339                kernel::hil::gpio::ActivationMode::ActiveLow,
340                kernel::hil::gpio::FloatingState::PullUp
341            ),
342            (
343                &nrf52840_peripherals.gpio_port[BUTTON3_PIN],
344                kernel::hil::gpio::ActivationMode::ActiveLow,
345                kernel::hil::gpio::FloatingState::PullUp
346            ),
347            (
348                &nrf52840_peripherals.gpio_port[BUTTON4_PIN],
349                kernel::hil::gpio::ActivationMode::ActiveLow,
350                kernel::hil::gpio::FloatingState::PullUp
351            )
352        ),
353    )
354    .finalize(components::button_component_static!(
355        nrf52840::gpio::GPIOPin
356    ));
357
358    //--------------------------------------------------------------------------
359    // ADC
360    //--------------------------------------------------------------------------
361
362    let adc_channels = static_init!(
363        [nrf52840::adc::AdcChannelSetup; 6],
364        [
365            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput1),
366            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput2),
367            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput4),
368            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput5),
369            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput6),
370            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput7),
371        ]
372    );
373    let adc = components::adc::AdcDedicatedComponent::new(
374        &base_peripherals.adc,
375        adc_channels,
376        board_kernel,
377        capsules_core::adc::DRIVER_NUM,
378    )
379    .finalize(components::adc_dedicated_component_static!(
380        nrf52840::adc::Adc
381    ));
382
383    //--------------------------------------------------------------------------
384    // NRF CLOCK SETUP
385    //--------------------------------------------------------------------------
386
387    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
388
389    //--------------------------------------------------------------------------
390    // Credential Checking
391    //--------------------------------------------------------------------------
392
393    // Create the credential checker.
394    let checking_policy = components::appid::checker_null::AppCheckerNullComponent::new()
395        .finalize(components::app_checker_null_component_static!());
396
397    // Create the AppID assigner.
398    let assigner = components::appid::assigner_tbf::AppIdAssignerTbfHeaderComponent::new()
399        .finalize(components::appid_assigner_tbf_header_component_static!());
400
401    // Create the process checking machine.
402    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
403        .finalize(components::process_checker_machine_component_static!());
404
405    //--------------------------------------------------------------------------
406    // STORAGE PERMISSIONS
407    //--------------------------------------------------------------------------
408
409    let storage_permissions_policy =
410        components::storage_permissions::null::StoragePermissionsNullComponent::new().finalize(
411            components::storage_permissions_null_component_static!(
412                nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
413                kernel::process::ProcessStandardDebugFull,
414            ),
415        );
416
417    // These symbols are defined in the standard Tock linker script.
418    extern "C" {
419        /// Beginning of the ROM region containing app images.
420        static _sapps: u8;
421        /// End of the ROM region containing app images.
422        static _eapps: u8;
423        /// Beginning of the RAM region for app memory.
424        static mut _sappmem: u8;
425        /// End of the RAM region for app memory.
426        static _eappmem: u8;
427    }
428
429    let app_flash = core::slice::from_raw_parts(
430        core::ptr::addr_of!(_sapps),
431        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
432    );
433    let app_memory = core::slice::from_raw_parts_mut(
434        core::ptr::addr_of_mut!(_sappmem),
435        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
436    );
437
438    // Create and start the asynchronous process loader.
439    let loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
440        checker,
441        board_kernel,
442        chip,
443        &FAULT_RESPONSE,
444        assigner,
445        storage_permissions_policy,
446        app_flash,
447        app_memory,
448    )
449    .finalize(components::process_loader_sequential_component_static!(
450        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
451        kernel::process::ProcessStandardDebugFull,
452        NUM_PROCS
453    ));
454
455    //--------------------------------------------------------------------------
456    // Dynamic App Loading
457    //--------------------------------------------------------------------------
458
459    // Create the dynamic binary flasher.
460    let dynamic_binary_storage =
461        components::dynamic_binary_storage::SequentialBinaryStorageComponent::new(
462            &base_peripherals.nvmc,
463            loader,
464        )
465        .finalize(components::sequential_binary_storage_component_static!(
466            nrf52840::nvmc::Nvmc,
467            nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
468            kernel::process::ProcessStandardDebugFull,
469        ));
470
471    // Create the dynamic app loader capsule.
472    let dynamic_app_loader = components::app_loader::AppLoaderComponent::new(
473        board_kernel,
474        capsules_extra::app_loader::DRIVER_NUM,
475        dynamic_binary_storage,
476        dynamic_binary_storage,
477    )
478    .finalize(components::app_loader_component_static!(
479        DynamicBinaryStorage<'static>,
480        DynamicBinaryStorage<'static>,
481    ));
482
483    //--------------------------------------------------------------------------
484    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
485    //--------------------------------------------------------------------------
486
487    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
488        .finalize(components::round_robin_component_static!(NUM_PROCS));
489
490    let platform = static_init!(
491        Platform,
492        Platform {
493            console,
494            button,
495            adc,
496            led,
497            alarm,
498            scheduler,
499            systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
500            processes,
501            dynamic_app_loader,
502        }
503    );
504    loader.set_client(platform);
505
506    let _ = pconsole.start();
507
508    board_kernel.kernel_loop(
509        platform,
510        chip,
511        None::<&kernel::ipc::IPC<0>>,
512        &main_loop_capability,
513    );
514}