nrf52840dk_test_appid_tbf/
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
29const BUTTON_RST_PIN: Pin = Pin::P0_18;
30
31const UART_RTS: Option<Pin> = Some(Pin::P0_05);
32const UART_TXD: Pin = Pin::P0_06;
33const UART_CTS: Option<Pin> = Some(Pin::P0_07);
34const UART_RXD: Pin = Pin::P0_08;
35
36/// Debug Writer
37pub mod io;
38
39// State for loading and holding applications.
40// How should the kernel respond when a process faults.
41const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
42    capsules_system::process_policies::PanicFaultPolicy {};
43
44// Number of concurrent processes this platform supports.
45const NUM_PROCS: usize = 8;
46
47/// Static variables used by io.rs.
48static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
49static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
50
51kernel::stack_size! {0x2000}
52
53//------------------------------------------------------------------------------
54// SYSCALL DRIVER TYPE DEFINITIONS
55//------------------------------------------------------------------------------
56
57type AlarmDriver = components::alarm::AlarmDriverComponentType<nrf52840::rtc::Rtc<'static>>;
58
59/// Supported drivers by the platform
60pub struct Platform {
61    console: &'static capsules_core::console::Console<'static>,
62    led: &'static capsules_core::led::LedDriver<
63        'static,
64        kernel::hil::led::LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
65        4,
66    >,
67    alarm: &'static AlarmDriver,
68    scheduler: &'static RoundRobinSched<'static>,
69    systick: cortexm4::systick::SysTick,
70    processes: &'static ProcessArray<NUM_PROCS>,
71}
72
73impl SyscallDriverLookup for Platform {
74    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
75    where
76        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
77    {
78        match driver_num {
79            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
80            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
81            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
82            _ => f(None),
83        }
84    }
85}
86
87/// This is in a separate, inline(never) function so that its stack frame is
88/// removed when this function returns. Otherwise, the stack space used for
89/// these static_inits is wasted.
90#[inline(never)]
91unsafe fn create_peripherals() -> &'static mut Nrf52840DefaultPeripherals<'static> {
92    let ieee802154_ack_buf = static_init!(
93        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
94        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
95    );
96    // Initialize chip peripheral drivers
97    let nrf52840_peripherals = static_init!(
98        Nrf52840DefaultPeripherals,
99        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
100    );
101
102    nrf52840_peripherals
103}
104
105impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
106    for Platform
107{
108    type SyscallDriverLookup = Self;
109    type SyscallFilter = ();
110    type ProcessFault = ();
111    type Scheduler = RoundRobinSched<'static>;
112    type SchedulerTimer = cortexm4::systick::SysTick;
113    type WatchDog = ();
114    type ContextSwitchCallback = ();
115
116    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
117        self
118    }
119    fn syscall_filter(&self) -> &Self::SyscallFilter {
120        &()
121    }
122    fn process_fault(&self) -> &Self::ProcessFault {
123        &()
124    }
125    fn scheduler(&self) -> &Self::Scheduler {
126        self.scheduler
127    }
128    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
129        &self.systick
130    }
131    fn watchdog(&self) -> &Self::WatchDog {
132        &()
133    }
134    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
135        &()
136    }
137}
138
139impl kernel::process::ProcessLoadingAsyncClient for Platform {
140    fn process_loaded(&self, _result: Result<(), kernel::process::ProcessLoadError>) {}
141
142    fn process_loading_finished(&self) {
143        kernel::debug!("Processes Loaded:");
144
145        for (i, proc) in self.processes.as_slice().iter().enumerate() {
146            proc.get().map(|p| {
147                kernel::debug!("[{}] {}", i, p.get_process_name());
148                kernel::debug!("    ShortId: {}", p.short_app_id());
149            });
150        }
151    }
152}
153
154/// Main function called after RAM initialized.
155#[no_mangle]
156pub unsafe fn main() {
157    //--------------------------------------------------------------------------
158    // INITIAL SETUP
159    //--------------------------------------------------------------------------
160
161    // Apply errata fixes and enable interrupts.
162    nrf52840::init();
163
164    // Set up peripheral drivers. Called in separate function to reduce stack
165    // usage.
166    let nrf52840_peripherals = create_peripherals();
167
168    // Set up circular peripheral dependencies.
169    nrf52840_peripherals.init();
170    let base_peripherals = &nrf52840_peripherals.nrf52;
171
172    // Choose the channel for serial output. This board can be configured to use
173    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
174    // pins.
175    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
176
177    // Create an array to hold process references.
178    let processes = components::process_array::ProcessArrayComponent::new()
179        .finalize(components::process_array_component_static!(NUM_PROCS));
180    PROCESSES = Some(processes);
181
182    // Setup space to store the core kernel data structure.
183    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
184
185    // Create (and save for panic debugging) a chip object to setup low-level
186    // resources (e.g. MPU, systick).
187    let chip = static_init!(
188        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
189        nrf52840::chip::NRF52::new(nrf52840_peripherals)
190    );
191    CHIP = Some(chip);
192
193    // Do nRF configuration and setup. This is shared code with other nRF-based
194    // platforms.
195    nrf52_components::startup::NrfStartupComponent::new(
196        false,
197        BUTTON_RST_PIN,
198        nrf52840::uicr::Regulator0Output::DEFAULT,
199        &base_peripherals.nvmc,
200    )
201    .finalize(());
202
203    //--------------------------------------------------------------------------
204    // CAPABILITIES
205    //--------------------------------------------------------------------------
206
207    // Create capabilities that the board needs to call certain protected kernel
208    // functions.
209    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
210
211    //--------------------------------------------------------------------------
212    // LEDs
213    //--------------------------------------------------------------------------
214
215    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
216        LedLow<'static, nrf52840::gpio::GPIOPin>,
217        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
218        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
219        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
220        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
221    ));
222
223    //--------------------------------------------------------------------------
224    // TIMER
225    //--------------------------------------------------------------------------
226
227    let rtc = &base_peripherals.rtc;
228    let _ = rtc.start();
229    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
230        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
231    let alarm = components::alarm::AlarmDriverComponent::new(
232        board_kernel,
233        capsules_core::alarm::DRIVER_NUM,
234        mux_alarm,
235    )
236    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
237
238    //--------------------------------------------------------------------------
239    // UART & CONSOLE & DEBUG
240    //--------------------------------------------------------------------------
241
242    let uart_channel = nrf52_components::UartChannelComponent::new(
243        uart_channel,
244        mux_alarm,
245        &base_peripherals.uarte0,
246    )
247    .finalize(nrf52_components::uart_channel_component_static!(
248        nrf52840::rtc::Rtc
249    ));
250
251    // Virtualize the UART channel for the console and for kernel debug.
252    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
253        .finalize(components::uart_mux_component_static!());
254
255    // Setup the serial console for userspace.
256    let console = components::console::ConsoleComponent::new(
257        board_kernel,
258        capsules_core::console::DRIVER_NUM,
259        uart_mux,
260    )
261    .finalize(components::console_component_static!());
262
263    // Tool for displaying information about processes.
264    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
265        .finalize(components::process_printer_text_component_static!());
266
267    // Create the process console, an interactive terminal for managing
268    // processes.
269    let pconsole = components::process_console::ProcessConsoleComponent::new(
270        board_kernel,
271        uart_mux,
272        mux_alarm,
273        process_printer,
274        Some(cortexm4::support::reset),
275    )
276    .finalize(components::process_console_component_static!(
277        nrf52840::rtc::Rtc<'static>
278    ));
279
280    // Create the debugger object that handles calls to `debug!()`.
281    components::debug_writer::DebugWriterComponent::new(
282        uart_mux,
283        create_capability!(capabilities::SetDebugWriterCapability),
284    )
285    .finalize(components::debug_writer_component_static!());
286
287    //--------------------------------------------------------------------------
288    // NRF CLOCK SETUP
289    //--------------------------------------------------------------------------
290
291    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
292
293    //--------------------------------------------------------------------------
294    // Credential Checking
295    //--------------------------------------------------------------------------
296
297    // Create the credential checker.
298    let checking_policy = components::appid::checker_null::AppCheckerNullComponent::new()
299        .finalize(components::app_checker_null_component_static!());
300
301    // Create the AppID assigner.
302    let assigner = components::appid::assigner_tbf::AppIdAssignerTbfHeaderComponent::new()
303        .finalize(components::appid_assigner_tbf_header_component_static!());
304
305    // Create the process checking machine.
306    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
307        .finalize(components::process_checker_machine_component_static!());
308
309    //--------------------------------------------------------------------------
310    // STORAGE PERMISSIONS
311    //--------------------------------------------------------------------------
312
313    let storage_permissions_policy =
314        components::storage_permissions::null::StoragePermissionsNullComponent::new().finalize(
315            components::storage_permissions_null_component_static!(
316                nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
317                kernel::process::ProcessStandardDebugFull,
318            ),
319        );
320
321    //--------------------------------------------------------------------------
322    // PROCESS LOADING
323    //--------------------------------------------------------------------------
324
325    // These symbols are defined in the standard Tock linker script.
326    extern "C" {
327        /// Beginning of the ROM region containing app images.
328        static _sapps: u8;
329        /// End of the ROM region containing app images.
330        static _eapps: u8;
331        /// Beginning of the RAM region for app memory.
332        static mut _sappmem: u8;
333        /// End of the RAM region for app memory.
334        static _eappmem: u8;
335    }
336
337    let app_flash = core::slice::from_raw_parts(
338        core::ptr::addr_of!(_sapps),
339        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
340    );
341    let app_memory = core::slice::from_raw_parts_mut(
342        core::ptr::addr_of_mut!(_sappmem),
343        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
344    );
345
346    // Create and start the asynchronous process loader.
347    let loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
348        checker,
349        board_kernel,
350        chip,
351        &FAULT_RESPONSE,
352        assigner,
353        storage_permissions_policy,
354        app_flash,
355        app_memory,
356    )
357    .finalize(components::process_loader_sequential_component_static!(
358        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
359        kernel::process::ProcessStandardDebugFull,
360        NUM_PROCS
361    ));
362
363    //--------------------------------------------------------------------------
364    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
365    //--------------------------------------------------------------------------
366
367    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
368        .finalize(components::round_robin_component_static!(NUM_PROCS));
369
370    let platform = static_init!(
371        Platform,
372        Platform {
373            console,
374            led,
375            alarm,
376            scheduler,
377            systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
378            processes,
379        }
380    );
381    loader.set_client(platform);
382
383    let _ = pconsole.start();
384
385    board_kernel.kernel_loop(
386        platform,
387        chip,
388        None::<&kernel::ipc::IPC<0>>,
389        &main_loop_capability,
390    );
391}