nrf52840dk_test_dynamic_app_load/
main.rs1#![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
23const 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
29const 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
41pub mod io;
43
44const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
47    capsules_system::process_policies::PanicFaultPolicy {};
48
49const NUM_PROCS: usize = 8;
51
52type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
53
54static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
56static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
57static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
59    None;
60
61kernel::stack_size! {0x2000}
62
63type 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
78pub 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#[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    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#[no_mangle]
184pub unsafe fn main() {
185    nrf52840::init();
191
192    let nrf52840_peripherals = create_peripherals();
195
196    nrf52840_peripherals.init();
198    let base_peripherals = &nrf52840_peripherals.nrf52;
199
200    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
204
205    let processes = components::process_array::ProcessArrayComponent::new()
207        .finalize(components::process_array_component_static!(NUM_PROCS));
208    PROCESSES = Some(processes);
209
210    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
212
213    let chip = static_init!(
216        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
217        nrf52840::chip::NRF52::new(nrf52840_peripherals)
218    );
219    CHIP = Some(chip);
220
221    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    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
238
239    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    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    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    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
281        .finalize(components::uart_mux_component_static!());
282
283    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    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
293        .finalize(components::process_printer_text_component_static!());
294    PROCESS_PRINTER = Some(process_printer);
295
296    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    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    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    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    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
383
384    let checking_policy = components::appid::checker_null::AppCheckerNullComponent::new()
390        .finalize(components::app_checker_null_component_static!());
391
392    let assigner = components::appid::assigner_tbf::AppIdAssignerTbfHeaderComponent::new()
394        .finalize(components::appid_assigner_tbf_header_component_static!());
395
396    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
398        .finalize(components::process_checker_machine_component_static!());
399
400    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    extern "C" {
414        static _sapps: u8;
416        static _eapps: u8;
418        static mut _sappmem: u8;
420        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    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    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    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    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}