nrf52840_dongle/
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 dongle.
6//!
7//! It is based on nRF52840 SoC (Cortex M4 core with a BLE transceiver) with
8//! many exported I/O and peripherals.
9
10#![no_std]
11// Disable this attribute when documenting, as a workaround for
12// https://github.com/rust-lang/rust/issues/62184.
13#![cfg_attr(not(doc), no_main)]
14#![deny(missing_docs)]
15
16use core::ptr::{addr_of, addr_of_mut};
17
18use capsules_core::virtualizers::virtual_aes_ccm::MuxAES128CCM;
19use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
20use kernel::component::Component;
21use kernel::deferred_call::DeferredCallClient;
22use kernel::hil::led::LedLow;
23use kernel::hil::symmetric_encryption::AES128;
24use kernel::hil::time::Counter;
25use kernel::platform::{KernelResources, SyscallDriverLookup};
26use kernel::scheduler::round_robin::RoundRobinSched;
27#[allow(unused_imports)]
28use kernel::{capabilities, create_capability, debug, debug_gpio, debug_verbose, static_init};
29use nrf52840::gpio::Pin;
30use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
31use nrf52_components::{UartChannel, UartPins};
32
33// The nRF52840 Dongle LEDs
34const LED1_PIN: Pin = Pin::P0_06;
35const LED2_R_PIN: Pin = Pin::P0_08;
36const LED2_G_PIN: Pin = Pin::P1_09;
37const LED2_B_PIN: Pin = Pin::P0_12;
38
39// The nRF52840 Dongle button
40const BUTTON_PIN: Pin = Pin::P1_06;
41const BUTTON_RST_PIN: Pin = Pin::P0_18;
42
43const UART_RTS: Option<Pin> = Some(Pin::P0_13);
44const UART_TXD: Pin = Pin::P0_15;
45const UART_CTS: Option<Pin> = Some(Pin::P0_17);
46const UART_RXD: Pin = Pin::P0_20;
47
48// SPI pins not currently in use, but left here for convenience
49const _SPI_MOSI: Pin = Pin::P1_01;
50const _SPI_MISO: Pin = Pin::P1_02;
51const _SPI_CLK: Pin = Pin::P1_04;
52
53// Constants related to the configuration of the 15.4 network stack; DEFAULT_EXT_SRC_MAC
54// should be replaced by an extended src address generated from device serial number
55const SRC_MAC: u16 = 0xf00f;
56const PAN_ID: u16 = 0xABCD;
57const DEFAULT_EXT_SRC_MAC: [u8; 8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77];
58
59/// UART Writer
60pub mod io;
61
62// State for loading and holding applications.
63// How should the kernel respond when a process faults.
64const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
65    capsules_system::process_policies::PanicFaultPolicy {};
66
67// Number of concurrent processes this platform supports.
68const NUM_PROCS: usize = 8;
69
70static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
71    [None; NUM_PROCS];
72
73// Static reference to chip for panic dumps
74static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
75// Static reference to process printer for panic dumps
76static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
77    None;
78
79/// Dummy buffer that causes the linker to reserve enough space for the stack.
80#[no_mangle]
81#[link_section = ".stack_buffer"]
82pub static mut STACK_MEMORY: [u8; 0x1000] = [0; 0x1000];
83
84type TemperatureDriver =
85    components::temperature::TemperatureComponentType<nrf52840::temperature::Temp<'static>>;
86type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
87
88type Ieee802154Driver = components::ieee802154::Ieee802154ComponentType<
89    nrf52840::ieee802154_radio::Radio<'static>,
90    nrf52840::aes::AesECB<'static>,
91>;
92
93/// Supported drivers by the platform
94pub struct Platform {
95    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
96        'static,
97        nrf52840::ble_radio::Radio<'static>,
98        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
99    >,
100    ieee802154_radio: &'static Ieee802154Driver,
101    button: &'static capsules_core::button::Button<'static, nrf52840::gpio::GPIOPin<'static>>,
102    pconsole: &'static capsules_core::process_console::ProcessConsole<
103        'static,
104        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
105        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
106        components::process_console::Capability,
107    >,
108    console: &'static capsules_core::console::Console<'static>,
109    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52840::gpio::GPIOPin<'static>>,
110    led: &'static capsules_core::led::LedDriver<
111        'static,
112        LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
113        4,
114    >,
115    rng: &'static RngDriver,
116    temp: &'static TemperatureDriver,
117    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
118    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
119        'static,
120        nrf52840::acomp::Comparator<'static>,
121    >,
122    alarm: &'static capsules_core::alarm::AlarmDriver<
123        'static,
124        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
125            'static,
126            nrf52840::rtc::Rtc<'static>,
127        >,
128    >,
129    scheduler: &'static RoundRobinSched<'static>,
130    systick: cortexm4::systick::SysTick,
131}
132
133impl SyscallDriverLookup for Platform {
134    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
135    where
136        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
137    {
138        match driver_num {
139            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
140            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
141            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
142            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
143            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
144            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
145            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
146            capsules_extra::ieee802154::DRIVER_NUM => f(Some(self.ieee802154_radio)),
147            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
148            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
149            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
150            _ => f(None),
151        }
152    }
153}
154
155impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
156    for Platform
157{
158    type SyscallDriverLookup = Self;
159    type SyscallFilter = ();
160    type ProcessFault = ();
161    type Scheduler = RoundRobinSched<'static>;
162    type SchedulerTimer = cortexm4::systick::SysTick;
163    type WatchDog = ();
164    type ContextSwitchCallback = ();
165
166    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
167        self
168    }
169    fn syscall_filter(&self) -> &Self::SyscallFilter {
170        &()
171    }
172    fn process_fault(&self) -> &Self::ProcessFault {
173        &()
174    }
175    fn scheduler(&self) -> &Self::Scheduler {
176        self.scheduler
177    }
178    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
179        &self.systick
180    }
181    fn watchdog(&self) -> &Self::WatchDog {
182        &()
183    }
184    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
185        &()
186    }
187}
188
189/// This is in a separate, inline(never) function so that its stack frame is
190/// removed when this function returns. Otherwise, the stack space used for
191/// these static_inits is wasted.
192#[inline(never)]
193pub unsafe fn start() -> (
194    &'static kernel::Kernel,
195    Platform,
196    &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
197) {
198    nrf52840::init();
199
200    let ieee802154_ack_buf = static_init!(
201        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
202        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
203    );
204    // Initialize chip peripheral drivers
205    let nrf52840_peripherals = static_init!(
206        Nrf52840DefaultPeripherals,
207        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
208    );
209
210    // set up circular peripheral dependencies
211    nrf52840_peripherals.init();
212    let base_peripherals = &nrf52840_peripherals.nrf52;
213
214    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
215
216    // GPIOs
217    let gpio = components::gpio::GpioComponent::new(
218        board_kernel,
219        capsules_core::gpio::DRIVER_NUM,
220        components::gpio_component_helper!(
221            nrf52840::gpio::GPIOPin,
222            // left side of the USB plug
223            0 => &nrf52840_peripherals.gpio_port[Pin::P0_13],
224            1 => &nrf52840_peripherals.gpio_port[Pin::P0_15],
225            2 => &nrf52840_peripherals.gpio_port[Pin::P0_17],
226            3 => &nrf52840_peripherals.gpio_port[Pin::P0_20],
227            4 => &nrf52840_peripherals.gpio_port[Pin::P0_22],
228            5 => &nrf52840_peripherals.gpio_port[Pin::P0_24],
229            6 => &nrf52840_peripherals.gpio_port[Pin::P1_00],
230            7 => &nrf52840_peripherals.gpio_port[Pin::P0_09],
231            8 => &nrf52840_peripherals.gpio_port[Pin::P0_10],
232            // right side of the USB plug
233            9 => &nrf52840_peripherals.gpio_port[Pin::P0_31],
234            10 => &nrf52840_peripherals.gpio_port[Pin::P0_29],
235            11 => &nrf52840_peripherals.gpio_port[Pin::P0_02],
236            12 => &nrf52840_peripherals.gpio_port[Pin::P1_15],
237            13 => &nrf52840_peripherals.gpio_port[Pin::P1_13],
238            14 => &nrf52840_peripherals.gpio_port[Pin::P1_10],
239            // Below the PCB
240            15 => &nrf52840_peripherals.gpio_port[Pin::P0_26],
241            16 => &nrf52840_peripherals.gpio_port[Pin::P0_04],
242            17 => &nrf52840_peripherals.gpio_port[Pin::P0_11],
243            18 => &nrf52840_peripherals.gpio_port[Pin::P0_14],
244            19 => &nrf52840_peripherals.gpio_port[Pin::P1_11],
245            20 => &nrf52840_peripherals.gpio_port[Pin::P1_07],
246            21 => &nrf52840_peripherals.gpio_port[Pin::P1_01],
247            22 => &nrf52840_peripherals.gpio_port[Pin::P1_04],
248            23 => &nrf52840_peripherals.gpio_port[Pin::P1_02]
249        ),
250    )
251    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
252
253    let button = components::button::ButtonComponent::new(
254        board_kernel,
255        capsules_core::button::DRIVER_NUM,
256        components::button_component_helper!(
257            nrf52840::gpio::GPIOPin,
258            (
259                &nrf52840_peripherals.gpio_port[BUTTON_PIN],
260                kernel::hil::gpio::ActivationMode::ActiveLow,
261                kernel::hil::gpio::FloatingState::PullUp
262            )
263        ),
264    )
265    .finalize(components::button_component_static!(
266        nrf52840::gpio::GPIOPin
267    ));
268
269    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
270        LedLow<'static, nrf52840::gpio::GPIOPin>,
271        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
272        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_R_PIN]),
273        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_G_PIN]),
274        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_B_PIN]),
275    ));
276
277    let chip = static_init!(
278        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
279        nrf52840::chip::NRF52::new(nrf52840_peripherals)
280    );
281    CHIP = Some(chip);
282
283    nrf52_components::startup::NrfStartupComponent::new(
284        false,
285        BUTTON_RST_PIN,
286        nrf52840::uicr::Regulator0Output::V3_0,
287        &base_peripherals.nvmc,
288    )
289    .finalize(());
290
291    // Create capabilities that the board needs to call certain protected kernel
292    // functions.
293    let process_management_capability =
294        create_capability!(capabilities::ProcessManagementCapability);
295    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
296
297    let gpio_port = &nrf52840_peripherals.gpio_port;
298
299    // Configure kernel debug gpios as early as possible
300    kernel::debug::assign_gpios(
301        Some(&gpio_port[LED2_R_PIN]),
302        Some(&gpio_port[LED2_G_PIN]),
303        Some(&gpio_port[LED2_B_PIN]),
304    );
305
306    let rtc = &base_peripherals.rtc;
307    let _ = rtc.start();
308    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
309        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
310    let alarm = components::alarm::AlarmDriverComponent::new(
311        board_kernel,
312        capsules_core::alarm::DRIVER_NUM,
313        mux_alarm,
314    )
315    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
316    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
317    let channel = nrf52_components::UartChannelComponent::new(
318        uart_channel,
319        mux_alarm,
320        &base_peripherals.uarte0,
321    )
322    .finalize(nrf52_components::uart_channel_component_static!(
323        nrf52840::rtc::Rtc
324    ));
325
326    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
327        .finalize(components::process_printer_text_component_static!());
328    PROCESS_PRINTER = Some(process_printer);
329
330    // Create a shared UART channel for the console and for kernel debug.
331    let uart_mux = components::console::UartMuxComponent::new(channel, 115200)
332        .finalize(components::uart_mux_component_static!());
333
334    let pconsole = components::process_console::ProcessConsoleComponent::new(
335        board_kernel,
336        uart_mux,
337        mux_alarm,
338        process_printer,
339        Some(cortexm4::support::reset),
340    )
341    .finalize(components::process_console_component_static!(
342        nrf52840::rtc::Rtc<'static>
343    ));
344
345    // Setup the console.
346    let console = components::console::ConsoleComponent::new(
347        board_kernel,
348        capsules_core::console::DRIVER_NUM,
349        uart_mux,
350    )
351    .finalize(components::console_component_static!());
352    // Create the debugger object that handles calls to `debug!()`.
353    components::debug_writer::DebugWriterComponent::new(uart_mux)
354        .finalize(components::debug_writer_component_static!());
355
356    let ble_radio = components::ble::BLEComponent::new(
357        board_kernel,
358        capsules_extra::ble_advertising_driver::DRIVER_NUM,
359        &base_peripherals.ble_radio,
360        mux_alarm,
361    )
362    .finalize(components::ble_component_static!(
363        nrf52840::rtc::Rtc,
364        nrf52840::ble_radio::Radio
365    ));
366
367    let aes_mux = static_init!(
368        MuxAES128CCM<'static, nrf52840::aes::AesECB>,
369        MuxAES128CCM::new(&base_peripherals.ecb,)
370    );
371    aes_mux.register();
372    base_peripherals.ecb.set_client(aes_mux);
373
374    let (ieee802154_radio, _mux_mac) = components::ieee802154::Ieee802154Component::new(
375        board_kernel,
376        capsules_extra::ieee802154::DRIVER_NUM,
377        &nrf52840_peripherals.ieee802154_radio,
378        aes_mux,
379        PAN_ID,
380        SRC_MAC,
381        DEFAULT_EXT_SRC_MAC,
382    )
383    .finalize(components::ieee802154_component_static!(
384        nrf52840::ieee802154_radio::Radio,
385        nrf52840::aes::AesECB<'static>
386    ));
387
388    let temp = components::temperature::TemperatureComponent::new(
389        board_kernel,
390        capsules_extra::temperature::DRIVER_NUM,
391        &base_peripherals.temp,
392    )
393    .finalize(components::temperature_component_static!(
394        nrf52840::temperature::Temp
395    ));
396
397    let rng = components::rng::RngComponent::new(
398        board_kernel,
399        capsules_core::rng::DRIVER_NUM,
400        &base_peripherals.trng,
401    )
402    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
403
404    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
405    // These are hardcoded pin assignments specified in the driver
406    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
407        &base_peripherals.acomp,
408        components::analog_comparator_component_helper!(
409            nrf52840::acomp::Channel,
410            &*addr_of!(nrf52840::acomp::CHANNEL_AC0)
411        ),
412        board_kernel,
413        capsules_extra::analog_comparator::DRIVER_NUM,
414    )
415    .finalize(components::analog_comparator_component_static!(
416        nrf52840::acomp::Comparator
417    ));
418
419    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
420
421    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
422        .finalize(components::round_robin_component_static!(NUM_PROCS));
423
424    let platform = Platform {
425        button,
426        ble_radio,
427        ieee802154_radio,
428        pconsole,
429        console,
430        led,
431        gpio,
432        rng,
433        temp,
434        alarm,
435        analog_comparator,
436        ipc: kernel::ipc::IPC::new(
437            board_kernel,
438            kernel::ipc::DRIVER_NUM,
439            &memory_allocation_capability,
440        ),
441        scheduler,
442        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
443    };
444
445    let _ = platform.pconsole.start();
446    debug!("Initialization complete. Entering main loop\r");
447    debug!("{}", &*addr_of!(nrf52840::ficr::FICR_INSTANCE));
448
449    // These symbols are defined in the linker script.
450    extern "C" {
451        /// Beginning of the ROM region containing app images.
452        static _sapps: u8;
453        /// End of the ROM region containing app images.
454        static _eapps: u8;
455        /// Beginning of the RAM region for app memory.
456        static mut _sappmem: u8;
457        /// End of the RAM region for app memory.
458        static _eappmem: u8;
459    }
460
461    kernel::process::load_processes(
462        board_kernel,
463        chip,
464        core::slice::from_raw_parts(
465            core::ptr::addr_of!(_sapps),
466            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
467        ),
468        core::slice::from_raw_parts_mut(
469            core::ptr::addr_of_mut!(_sappmem),
470            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
471        ),
472        &mut *addr_of_mut!(PROCESSES),
473        &FAULT_RESPONSE,
474        &process_management_capability,
475    )
476    .unwrap_or_else(|err| {
477        debug!("Error loading processes!");
478        debug!("{:?}", err);
479    });
480
481    (board_kernel, platform, chip)
482}
483
484/// Main function called after RAM initialized.
485#[no_mangle]
486pub unsafe fn main() {
487    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
488
489    let (board_kernel, platform, chip) = start();
490    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
491}