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