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