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