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#![no_main]
12#![deny(missing_docs)]
13
14use core::ptr::addr_of;
15
16use capsules_core::virtualizers::virtual_aes_ccm::MuxAES128CCM;
17use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
18use kernel::component::Component;
19use kernel::debug::PanicResources;
20use kernel::deferred_call::DeferredCallClient;
21use kernel::hil::led::LedLow;
22use kernel::hil::symmetric_encryption::AES128;
23use kernel::hil::time::Counter;
24use kernel::platform::{KernelResources, SyscallDriverLookup};
25use kernel::scheduler::round_robin::RoundRobinSched;
26use kernel::utilities::single_thread_value::SingleThreadValue;
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
70type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
71type ProcessPrinterInUse = capsules_system::process_printer::ProcessPrinterText;
72
73/// Resources for when a board panics used by io.rs.
74static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinterInUse>> =
75    SingleThreadValue::new(PanicResources::new());
76
77kernel::stack_size! {0x1000}
78
79type TemperatureDriver =
80    components::temperature::TemperatureComponentType<nrf52840::temperature::Temp<'static>>;
81type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
82
83type Ieee802154Driver = components::ieee802154::Ieee802154ComponentType<
84    nrf52840::ieee802154_radio::Radio<'static>,
85    nrf52840::aes::AesECB<'static>,
86>;
87
88/// Supported drivers by the platform
89pub struct Platform {
90    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
91        'static,
92        nrf52840::ble_radio::Radio<'static>,
93        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
94    >,
95    ieee802154_radio: &'static Ieee802154Driver,
96    button: &'static capsules_core::button::Button<'static, nrf52840::gpio::GPIOPin<'static>>,
97    pconsole: &'static capsules_core::process_console::ProcessConsole<
98        'static,
99        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
100        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
101        components::process_console::Capability,
102    >,
103    console: &'static capsules_core::console::Console<'static>,
104    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52840::gpio::GPIOPin<'static>>,
105    led: &'static capsules_core::led::LedDriver<
106        'static,
107        LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
108        4,
109    >,
110    rng: &'static RngDriver,
111    temp: &'static TemperatureDriver,
112    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
113    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
114        'static,
115        nrf52840::acomp::Comparator<'static>,
116    >,
117    alarm: &'static capsules_core::alarm::AlarmDriver<
118        'static,
119        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
120            'static,
121            nrf52840::rtc::Rtc<'static>,
122        >,
123    >,
124    scheduler: &'static RoundRobinSched<'static>,
125    systick: cortexm4::systick::SysTick,
126}
127
128impl SyscallDriverLookup for Platform {
129    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
130    where
131        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
132    {
133        match driver_num {
134            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
135            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
136            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
137            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
138            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
139            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
140            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
141            capsules_extra::ieee802154::DRIVER_NUM => f(Some(self.ieee802154_radio)),
142            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
143            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
144            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
145            _ => f(None),
146        }
147    }
148}
149
150impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
151    for Platform
152{
153    type SyscallDriverLookup = Self;
154    type SyscallFilter = ();
155    type ProcessFault = ();
156    type Scheduler = RoundRobinSched<'static>;
157    type SchedulerTimer = cortexm4::systick::SysTick;
158    type WatchDog = ();
159    type ContextSwitchCallback = ();
160
161    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
162        self
163    }
164    fn syscall_filter(&self) -> &Self::SyscallFilter {
165        &()
166    }
167    fn process_fault(&self) -> &Self::ProcessFault {
168        &()
169    }
170    fn scheduler(&self) -> &Self::Scheduler {
171        self.scheduler
172    }
173    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
174        &self.systick
175    }
176    fn watchdog(&self) -> &Self::WatchDog {
177        &()
178    }
179    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
180        &()
181    }
182}
183
184/// This is in a separate, inline(never) function so that its stack frame is
185/// removed when this function returns. Otherwise, the stack space used for
186/// these static_inits is wasted.
187#[inline(never)]
188pub unsafe fn start() -> (
189    &'static kernel::Kernel,
190    Platform,
191    &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
192) {
193    nrf52840::init();
194
195    // Initialize deferred calls very early.
196    kernel::deferred_call::initialize_deferred_call_state::<
197        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
198    >();
199
200    // Bind global variables to this thread.
201    PANIC_RESOURCES.bind_to_thread::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>();
202
203    let ieee802154_ack_buf = static_init!(
204        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
205        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
206    );
207    // Initialize chip peripheral drivers
208    let nrf52840_peripherals = static_init!(
209        Nrf52840DefaultPeripherals,
210        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
211    );
212
213    // set up circular peripheral dependencies
214    nrf52840_peripherals.init();
215    let base_peripherals = &nrf52840_peripherals.nrf52;
216
217    // Create an array to hold process references.
218    let processes = components::process_array::ProcessArrayComponent::new()
219        .finalize(components::process_array_component_static!(NUM_PROCS));
220    PANIC_RESOURCES.get().map(|resources| {
221        resources.processes.put(processes.as_slice());
222    });
223
224    // Setup space to store the core kernel data structure.
225    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
226
227    // GPIOs
228    let gpio = components::gpio::GpioComponent::new(
229        board_kernel,
230        capsules_core::gpio::DRIVER_NUM,
231        components::gpio_component_helper!(
232            nrf52840::gpio::GPIOPin,
233            // left side of the USB plug
234            0 => &nrf52840_peripherals.gpio_port[Pin::P0_13],
235            1 => &nrf52840_peripherals.gpio_port[Pin::P0_15],
236            2 => &nrf52840_peripherals.gpio_port[Pin::P0_17],
237            3 => &nrf52840_peripherals.gpio_port[Pin::P0_20],
238            4 => &nrf52840_peripherals.gpio_port[Pin::P0_22],
239            5 => &nrf52840_peripherals.gpio_port[Pin::P0_24],
240            6 => &nrf52840_peripherals.gpio_port[Pin::P1_00],
241            7 => &nrf52840_peripherals.gpio_port[Pin::P0_09],
242            8 => &nrf52840_peripherals.gpio_port[Pin::P0_10],
243            // right side of the USB plug
244            9 => &nrf52840_peripherals.gpio_port[Pin::P0_31],
245            10 => &nrf52840_peripherals.gpio_port[Pin::P0_29],
246            11 => &nrf52840_peripherals.gpio_port[Pin::P0_02],
247            12 => &nrf52840_peripherals.gpio_port[Pin::P1_15],
248            13 => &nrf52840_peripherals.gpio_port[Pin::P1_13],
249            14 => &nrf52840_peripherals.gpio_port[Pin::P1_10],
250            // Below the PCB
251            15 => &nrf52840_peripherals.gpio_port[Pin::P0_26],
252            16 => &nrf52840_peripherals.gpio_port[Pin::P0_04],
253            17 => &nrf52840_peripherals.gpio_port[Pin::P0_11],
254            18 => &nrf52840_peripherals.gpio_port[Pin::P0_14],
255            19 => &nrf52840_peripherals.gpio_port[Pin::P1_11],
256            20 => &nrf52840_peripherals.gpio_port[Pin::P1_07],
257            21 => &nrf52840_peripherals.gpio_port[Pin::P1_01],
258            22 => &nrf52840_peripherals.gpio_port[Pin::P1_04],
259            23 => &nrf52840_peripherals.gpio_port[Pin::P1_02]
260        ),
261    )
262    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
263
264    let button = components::button::ButtonComponent::new(
265        board_kernel,
266        capsules_core::button::DRIVER_NUM,
267        components::button_component_helper!(
268            nrf52840::gpio::GPIOPin,
269            (
270                &nrf52840_peripherals.gpio_port[BUTTON_PIN],
271                kernel::hil::gpio::ActivationMode::ActiveLow,
272                kernel::hil::gpio::FloatingState::PullUp
273            )
274        ),
275    )
276    .finalize(components::button_component_static!(
277        nrf52840::gpio::GPIOPin
278    ));
279
280    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
281        LedLow<'static, nrf52840::gpio::GPIOPin>,
282        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
283        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_R_PIN]),
284        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_G_PIN]),
285        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_B_PIN]),
286    ));
287
288    let chip = static_init!(
289        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
290        nrf52840::chip::NRF52::new(nrf52840_peripherals)
291    );
292    PANIC_RESOURCES.get().map(|resources| {
293        resources.chip.put(chip);
294    });
295
296    nrf52_components::startup::NrfStartupComponent::new(
297        false,
298        BUTTON_RST_PIN,
299        nrf52840::uicr::Regulator0Output::V3_0,
300        &base_peripherals.nvmc,
301    )
302    .finalize(());
303
304    // Create capabilities that the board needs to call certain protected kernel
305    // functions.
306    let process_management_capability =
307        create_capability!(capabilities::ProcessManagementCapability);
308    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
309
310    let gpio_port = &nrf52840_peripherals.gpio_port;
311
312    // Configure kernel debug gpios as early as possible
313    let debug_gpios = static_init!(
314        [&'static dyn kernel::hil::gpio::Pin; 3],
315        [
316            &gpio_port[LED2_R_PIN],
317            &gpio_port[LED2_G_PIN],
318            &gpio_port[LED2_B_PIN]
319        ]
320    );
321    kernel::debug::initialize_debug_gpio::<
322        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
323    >();
324    kernel::debug::assign_gpios(debug_gpios);
325
326    let rtc = &base_peripherals.rtc;
327    let _ = rtc.start();
328    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
329        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
330    let alarm = components::alarm::AlarmDriverComponent::new(
331        board_kernel,
332        capsules_core::alarm::DRIVER_NUM,
333        mux_alarm,
334    )
335    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
336    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
337    let channel = nrf52_components::UartChannelComponent::new(
338        uart_channel,
339        mux_alarm,
340        &base_peripherals.uarte0,
341    )
342    .finalize(nrf52_components::uart_channel_component_static!(
343        nrf52840::rtc::Rtc
344    ));
345
346    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
347        .finalize(components::process_printer_text_component_static!());
348    PANIC_RESOURCES.get().map(|resources| {
349        resources.printer.put(process_printer);
350    });
351
352    // Create a shared UART channel for the console and for kernel debug.
353    let uart_mux = components::console::UartMuxComponent::new(channel, 115200)
354        .finalize(components::uart_mux_component_static!());
355
356    let pconsole = components::process_console::ProcessConsoleComponent::new(
357        board_kernel,
358        uart_mux,
359        mux_alarm,
360        process_printer,
361        Some(cortexm4::support::reset),
362    )
363    .finalize(components::process_console_component_static!(
364        nrf52840::rtc::Rtc<'static>
365    ));
366
367    // Setup the console.
368    let console = components::console::ConsoleComponent::new(
369        board_kernel,
370        capsules_core::console::DRIVER_NUM,
371        uart_mux,
372    )
373    .finalize(components::console_component_static!());
374    // Create the debugger object that handles calls to `debug!()`.
375    components::debug_writer::DebugWriterComponent::new::<
376        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
377    >(
378        uart_mux,
379        create_capability!(capabilities::SetDebugWriterCapability),
380    )
381    .finalize(components::debug_writer_component_static!());
382
383    let ble_radio = components::ble::BLEComponent::new(
384        board_kernel,
385        capsules_extra::ble_advertising_driver::DRIVER_NUM,
386        &base_peripherals.ble_radio,
387        mux_alarm,
388    )
389    .finalize(components::ble_component_static!(
390        nrf52840::rtc::Rtc,
391        nrf52840::ble_radio::Radio
392    ));
393
394    let aes_mux = static_init!(
395        MuxAES128CCM<'static, nrf52840::aes::AesECB>,
396        MuxAES128CCM::new(&base_peripherals.ecb,)
397    );
398    aes_mux.register();
399    base_peripherals.ecb.set_client(aes_mux);
400
401    let (ieee802154_radio, _mux_mac) = components::ieee802154::Ieee802154Component::new(
402        board_kernel,
403        capsules_extra::ieee802154::DRIVER_NUM,
404        &nrf52840_peripherals.ieee802154_radio,
405        aes_mux,
406        PAN_ID,
407        SRC_MAC,
408        DEFAULT_EXT_SRC_MAC,
409    )
410    .finalize(components::ieee802154_component_static!(
411        nrf52840::ieee802154_radio::Radio,
412        nrf52840::aes::AesECB<'static>
413    ));
414
415    let temp = components::temperature::TemperatureComponent::new(
416        board_kernel,
417        capsules_extra::temperature::DRIVER_NUM,
418        &base_peripherals.temp,
419    )
420    .finalize(components::temperature_component_static!(
421        nrf52840::temperature::Temp
422    ));
423
424    let rng = components::rng::RngComponent::new(
425        board_kernel,
426        capsules_core::rng::DRIVER_NUM,
427        &base_peripherals.trng,
428    )
429    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
430
431    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
432    // These are hardcoded pin assignments specified in the driver
433    let analog_comparator_channel = static_init!(
434        nrf52840::acomp::Channel,
435        nrf52840::acomp::Channel::new(nrf52840::acomp::ChannelNumber::AC0)
436    );
437    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
438        &base_peripherals.acomp,
439        components::analog_comparator_component_helper!(
440            nrf52840::acomp::Channel,
441            analog_comparator_channel,
442        ),
443        board_kernel,
444        capsules_extra::analog_comparator::DRIVER_NUM,
445    )
446    .finalize(components::analog_comparator_component_static!(
447        nrf52840::acomp::Comparator
448    ));
449
450    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
451
452    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
453        .finalize(components::round_robin_component_static!(NUM_PROCS));
454
455    let platform = Platform {
456        button,
457        ble_radio,
458        ieee802154_radio,
459        pconsole,
460        console,
461        led,
462        gpio,
463        rng,
464        temp,
465        alarm,
466        analog_comparator,
467        ipc: kernel::ipc::IPC::new(
468            board_kernel,
469            kernel::ipc::DRIVER_NUM,
470            &memory_allocation_capability,
471        ),
472        scheduler,
473        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
474    };
475
476    let _ = platform.pconsole.start();
477    debug!("Initialization complete. Entering main loop\r");
478    debug!("{}", &*addr_of!(nrf52840::ficr::FICR_INSTANCE));
479
480    // These symbols are defined in the linker script.
481    extern "C" {
482        /// Beginning of the ROM region containing app images.
483        static _sapps: u8;
484        /// End of the ROM region containing app images.
485        static _eapps: u8;
486        /// Beginning of the RAM region for app memory.
487        static mut _sappmem: u8;
488        /// End of the RAM region for app memory.
489        static _eappmem: u8;
490    }
491
492    kernel::process::load_processes(
493        board_kernel,
494        chip,
495        core::slice::from_raw_parts(
496            core::ptr::addr_of!(_sapps),
497            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
498        ),
499        core::slice::from_raw_parts_mut(
500            core::ptr::addr_of_mut!(_sappmem),
501            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
502        ),
503        &FAULT_RESPONSE,
504        &process_management_capability,
505    )
506    .unwrap_or_else(|err| {
507        debug!("Error loading processes!");
508        debug!("{:?}", err);
509    });
510
511    (board_kernel, platform, chip)
512}
513
514/// Main function called after RAM initialized.
515#[no_mangle]
516pub unsafe fn main() {
517    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
518
519    let (board_kernel, platform, chip) = start();
520    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
521}