raspberry_pi_pico_2/
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 OxidOS Automotive 2025.
4
5//! Tock kernel for the Raspberry Pi Pico 2.
6//!
7//! It is based on RP2350SoC SoC (Cortex M33).
8
9#![no_std]
10// Disable this attribute when documenting, as a workaround for
11// https://github.com/rust-lang/rust/issues/62184.
12#![cfg_attr(not(doc), no_main)]
13#![deny(missing_docs)]
14
15use core::ptr::addr_of_mut;
16
17use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
18use components::gpio::GpioComponent;
19use components::led::LedsComponent;
20use enum_primitive::cast::FromPrimitive;
21use kernel::component::Component;
22use kernel::debug::PanicResources;
23use kernel::hil::led::LedHigh;
24use kernel::platform::{KernelResources, SyscallDriverLookup};
25use kernel::scheduler::round_robin::RoundRobinSched;
26use kernel::syscall::SyscallDriver;
27use kernel::utilities::single_thread_value::SingleThreadValue;
28use kernel::{capabilities, create_capability, static_init, Kernel};
29
30use rp2350::chip::{Rp2350, Rp2350DefaultPeripherals};
31use rp2350::clocks::{
32    AdcAuxiliaryClockSource, HstxAuxiliaryClockSource, PeripheralAuxiliaryClockSource, PllClock,
33    ReferenceAuxiliaryClockSource, ReferenceClockSource, SystemAuxiliaryClockSource,
34    SystemClockSource, UsbAuxiliaryClockSource,
35};
36use rp2350::gpio::{GpioFunction, RPGpio, RPGpioPin};
37use rp2350::resets::Peripheral;
38use rp2350::timer::RPTimer;
39#[allow(unused)]
40use rp2350::{xosc, BASE_VECTORS};
41
42mod io;
43
44mod flash_bootloader;
45
46/// Allocate memory for the stack
47//
48// When compiling for a macOS host, the `link_section` attribute is elided as
49// it yields the following error: `mach-o section specifier requires a segment
50// and section separated by a comma`.
51#[cfg_attr(not(target_os = "macos"), link_section = ".stack_buffer")]
52#[no_mangle]
53static mut STACK_MEMORY: [u8; 0x3000] = [0; 0x3000];
54
55// Manually setting the boot header section that contains the FCB header
56//
57// When compiling for a macOS host, the `link_section` attribute is elided as
58// it yields the following error: `mach-o section specifier requires a segment
59// and section separated by a comma`.
60#[cfg_attr(not(target_os = "macos"), link_section = ".flash_bootloader")]
61#[used]
62static FLASH_BOOTLOADER: [u8; 256] = flash_bootloader::FLASH_BOOTLOADER;
63
64// When compiling for a macOS host, the `link_section` attribute is elided as
65// it yields the following error: `mach-o section specifier requires a segment
66// and section separated by a comma`.
67#[cfg_attr(not(target_os = "macos"), link_section = ".metadata_block")]
68#[used]
69static METADATA_BLOCK: [u8; 28] = flash_bootloader::METADATA_BLOCK;
70
71// State for loading and holding applications.
72// How should the kernel respond when a process faults.
73const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
74    capsules_system::process_policies::PanicFaultPolicy {};
75
76// Number of concurrent processes this platform supports.
77const NUM_PROCS: usize = 4;
78
79type ChipHw = Rp2350<'static, Rp2350DefaultPeripherals<'static>>;
80type ProcessPrinterInUse = capsules_system::process_printer::ProcessPrinterText;
81
82/// Resources for when a board panics used by io.rs.
83static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinterInUse>> =
84    SingleThreadValue::new(PanicResources::new());
85
86/// Supported drivers by the platform
87pub struct RaspberryPiPico2 {
88    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
89    console: &'static capsules_core::console::Console<'static>,
90    scheduler: &'static RoundRobinSched<'static>,
91    systick: cortexm33::systick::SysTick,
92    alarm: &'static capsules_core::alarm::AlarmDriver<
93        'static,
94        VirtualMuxAlarm<'static, rp2350::timer::RPTimer<'static>>,
95    >,
96    gpio: &'static capsules_core::gpio::GPIO<'static, RPGpioPin<'static>>,
97    led: &'static capsules_core::led::LedDriver<'static, LedHigh<'static, RPGpioPin<'static>>, 1>,
98}
99
100impl SyscallDriverLookup for RaspberryPiPico2 {
101    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
102    where
103        F: FnOnce(Option<&dyn SyscallDriver>) -> R,
104    {
105        match driver_num {
106            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
107            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
108            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
109            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
110            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
111            _ => f(None),
112        }
113    }
114}
115
116impl KernelResources<Rp2350<'static, Rp2350DefaultPeripherals<'static>>> for RaspberryPiPico2 {
117    type SyscallDriverLookup = Self;
118    type SyscallFilter = ();
119    type ProcessFault = ();
120    type Scheduler = RoundRobinSched<'static>;
121    type SchedulerTimer = cortexm33::systick::SysTick;
122    type WatchDog = ();
123    type ContextSwitchCallback = ();
124
125    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
126        self
127    }
128    fn syscall_filter(&self) -> &Self::SyscallFilter {
129        &()
130    }
131    fn process_fault(&self) -> &Self::ProcessFault {
132        &()
133    }
134    fn scheduler(&self) -> &Self::Scheduler {
135        self.scheduler
136    }
137    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
138        &self.systick
139    }
140    fn watchdog(&self) -> &Self::WatchDog {
141        &()
142    }
143    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
144        &()
145    }
146}
147
148#[allow(dead_code)]
149extern "C" {
150    /// Entry point used for debugger
151    ///
152    /// When loaded using gdb, the Raspberry Pi Pico 2 is not reset
153    /// by default. Without this function, gdb sets the PC to the
154    /// beginning of the flash. This is not correct, as the RP2350
155    /// has a more complex boot process.
156    ///
157    /// This function is set to be the entry point for gdb and is used
158    /// to send the RP2350 back in the bootloader so that all the boot
159    /// sequence is performed.
160    fn jump_to_bootloader();
161}
162
163#[cfg(any(doc, all(target_arch = "arm", target_os = "none")))]
164core::arch::global_asm!(
165    "
166    .section .jump_to_bootloader, \"ax\"
167    .global jump_to_bootloader
168    .thumb_func
169  jump_to_bootloader:
170    movs r0, #0
171    ldr r1, =(0xe0000000 + 0x0000ed08)
172    str r0, [r1]
173    ldmia r0!, {{r1, r2}}
174    msr msp, r1
175    bx r2
176    "
177);
178
179fn init_clocks(peripherals: &Rp2350DefaultPeripherals) {
180    // // Start tick in watchdog
181    // peripherals.watchdog.start_tick(12);
182    //
183    // Disable the Resus clock
184    peripherals.clocks.disable_resus();
185
186    // Setup the external Oscillator
187    peripherals.xosc.init();
188
189    // disable ref and sys clock aux sources
190    peripherals.clocks.disable_sys_aux();
191    peripherals.clocks.disable_ref_aux();
192
193    peripherals
194        .resets
195        .reset(&[Peripheral::PllSys, Peripheral::PllUsb]);
196    peripherals
197        .resets
198        .unreset(&[Peripheral::PllSys, Peripheral::PllUsb], true);
199
200    // Configure PLLs (from Pico SDK)
201    //                   REF     FBDIV VCO            POSTDIV
202    // PLL SYS: 12 / 1 = 12MHz * 125 = 1500MHZ / 6 / 2 = 125MHz
203    // PLL USB: 12 / 1 = 12MHz * 40  = 480 MHz / 5 / 2 =  48MHz
204
205    // It seems that the external oscillator is clocked at 12 MHz
206
207    peripherals
208        .clocks
209        .pll_init(PllClock::Sys, 12, 1, 1500 * 1000000, 6, 2);
210    peripherals
211        .clocks
212        .pll_init(PllClock::Usb, 12, 1, 480 * 1000000, 5, 2);
213
214    // pico-sdk: // CLK_REF = XOSC (12MHz) / 1 = 12MHz
215    peripherals.clocks.configure_reference(
216        ReferenceClockSource::Xosc,
217        ReferenceAuxiliaryClockSource::PllUsb,
218        12000000,
219        12000000,
220    );
221    // pico-sdk: CLK SYS = PLL SYS (125MHz) / 1 = 125MHz
222    peripherals.clocks.configure_system(
223        SystemClockSource::Auxiliary,
224        SystemAuxiliaryClockSource::PllSys,
225        125000000,
226        125000000,
227    );
228
229    // pico-sdk: CLK USB = PLL USB (48MHz) / 1 = 48MHz
230    peripherals
231        .clocks
232        .configure_usb(UsbAuxiliaryClockSource::PllSys, 48000000, 48000000);
233    // pico-sdk: CLK ADC = PLL USB (48MHZ) / 1 = 48MHz
234    peripherals
235        .clocks
236        .configure_adc(AdcAuxiliaryClockSource::PllUsb, 48000000, 48000000);
237    // pico-sdk: CLK HSTX = PLL USB (48MHz) / 1024 = 46875Hz
238    peripherals
239        .clocks
240        .configure_hstx(HstxAuxiliaryClockSource::PllSys, 48000000, 46875);
241    // pico-sdk:
242    // CLK PERI = clk_sys. Used as reference clock for Peripherals. No dividers so just select and enable
243    // Normally choose clk_sys or clk_usb
244    peripherals
245        .clocks
246        .configure_peripheral(PeripheralAuxiliaryClockSource::System, 125000000);
247}
248
249unsafe fn get_peripherals() -> &'static mut Rp2350DefaultPeripherals<'static> {
250    static_init!(Rp2350DefaultPeripherals, Rp2350DefaultPeripherals::new())
251}
252
253/// Main function called after RAM initialized.
254#[no_mangle]
255pub unsafe fn main() {
256    rp2350::init();
257
258    // Initialize deferred calls very early.
259    kernel::deferred_call::initialize_deferred_call_state::<
260        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
261    >();
262
263    // Bind global variables to this thread.
264    PANIC_RESOURCES.bind_to_thread::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>();
265
266    let peripherals = get_peripherals();
267    peripherals.resolve_dependencies();
268
269    peripherals.resets.reset_all_except(&[
270        Peripheral::IOQSpi,
271        Peripheral::PadsQSpi,
272        Peripheral::PllUsb,
273        Peripheral::PllSys,
274    ]);
275
276    init_clocks(peripherals);
277
278    peripherals.resets.unreset_all_except(&[], true);
279
280    // Set the UART used for panic
281    (*addr_of_mut!(io::WRITER)).set_uart(&peripherals.uart0);
282
283    let gpio_tx = peripherals.pins.get_pin(RPGpio::GPIO0);
284    let gpio_rx = peripherals.pins.get_pin(RPGpio::GPIO1);
285    gpio_rx.set_function(GpioFunction::UART);
286    gpio_tx.set_function(GpioFunction::UART);
287
288    //// Disable IE for pads 26-29 (the Pico SDK runtime does this, not sure why)
289    for pin in 26..30 {
290        peripherals
291            .pins
292            .get_pin(RPGpio::from_usize(pin).unwrap())
293            .deactivate_pads();
294    }
295
296    let chip = static_init!(
297        Rp2350<Rp2350DefaultPeripherals>,
298        Rp2350::new(peripherals, &peripherals.sio)
299    );
300    PANIC_RESOURCES.get().map(|resources| {
301        resources.chip.put(chip);
302    });
303
304    // Create an array to hold process references.
305    let processes = components::process_array::ProcessArrayComponent::new()
306        .finalize(components::process_array_component_static!(NUM_PROCS));
307    PANIC_RESOURCES.get().map(|resources| {
308        resources.processes.put(processes.as_slice());
309    });
310
311    let board_kernel = static_init!(Kernel, Kernel::new(processes.as_slice()));
312
313    let process_management_capability =
314        create_capability!(capabilities::ProcessManagementCapability);
315    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
316
317    let mux_alarm = components::alarm::AlarmMuxComponent::new(&peripherals.timer0)
318        .finalize(components::alarm_mux_component_static!(RPTimer));
319
320    let alarm = components::alarm::AlarmDriverComponent::new(
321        board_kernel,
322        capsules_core::alarm::DRIVER_NUM,
323        mux_alarm,
324    )
325    .finalize(components::alarm_component_static!(RPTimer));
326
327    let uart_mux = components::console::UartMuxComponent::new(&peripherals.uart0, 115200)
328        .finalize(components::uart_mux_component_static!());
329
330    // Setup the console.
331    let console = components::console::ConsoleComponent::new(
332        board_kernel,
333        capsules_core::console::DRIVER_NUM,
334        uart_mux,
335    )
336    .finalize(components::console_component_static!());
337
338    let gpio = GpioComponent::new(
339        board_kernel,
340        capsules_core::gpio::DRIVER_NUM,
341        components::gpio_component_helper!(
342            RPGpioPin,
343            // Used for serial communication. Comment them in if you don't use serial.
344            // 0 => peripherals.pins.get_pin(RPGpio::GPIO0),
345            // 1 => peripherals.pins.get_pin(RPGpio::GPIO1),
346            2 => peripherals.pins.get_pin(RPGpio::GPIO2),
347            3 => peripherals.pins.get_pin(RPGpio::GPIO3),
348            4 => peripherals.pins.get_pin(RPGpio::GPIO4),
349            5 => peripherals.pins.get_pin(RPGpio::GPIO5),
350            6 => peripherals.pins.get_pin(RPGpio::GPIO6),
351            7 => peripherals.pins.get_pin(RPGpio::GPIO7),
352            8 => peripherals.pins.get_pin(RPGpio::GPIO8),
353            9 => peripherals.pins.get_pin(RPGpio::GPIO9),
354            10 => peripherals.pins.get_pin(RPGpio::GPIO10),
355            11 => peripherals.pins.get_pin(RPGpio::GPIO11),
356            12 => peripherals.pins.get_pin(RPGpio::GPIO12),
357            13 => peripherals.pins.get_pin(RPGpio::GPIO13),
358            14 => peripherals.pins.get_pin(RPGpio::GPIO14),
359            15 => peripherals.pins.get_pin(RPGpio::GPIO15),
360            16 => peripherals.pins.get_pin(RPGpio::GPIO16),
361            17 => peripherals.pins.get_pin(RPGpio::GPIO17),
362            18 => peripherals.pins.get_pin(RPGpio::GPIO18),
363            19 => peripherals.pins.get_pin(RPGpio::GPIO19),
364            20 => peripherals.pins.get_pin(RPGpio::GPIO20),
365            21 => peripherals.pins.get_pin(RPGpio::GPIO21),
366            22 => peripherals.pins.get_pin(RPGpio::GPIO22),
367            23 => peripherals.pins.get_pin(RPGpio::GPIO23),
368            24 => peripherals.pins.get_pin(RPGpio::GPIO24),
369            // LED pin
370            // 25 => peripherals.pins.get_pin(RPGpio::GPIO25),
371            26 => peripherals.pins.get_pin(RPGpio::GPIO26),
372            27 => peripherals.pins.get_pin(RPGpio::GPIO27),
373            28 => peripherals.pins.get_pin(RPGpio::GPIO28),
374            29 => peripherals.pins.get_pin(RPGpio::GPIO29)
375        ),
376    )
377    .finalize(components::gpio_component_static!(RPGpioPin<'static>));
378
379    let led = LedsComponent::new().finalize(components::led_component_static!(
380        LedHigh<'static, RPGpioPin<'static>>,
381        LedHigh::new(peripherals.pins.get_pin(RPGpio::GPIO25))
382    ));
383
384    // Create the debugger object that handles calls to `debug!()`.
385    components::debug_writer::DebugWriterComponent::new::<
386        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
387    >(
388        uart_mux,
389        create_capability!(capabilities::SetDebugWriterCapability),
390    )
391    .finalize(components::debug_writer_component_static!());
392
393    // PROCESS CONSOLE
394    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
395        .finalize(components::process_printer_text_component_static!());
396    PANIC_RESOURCES.get().map(|resources| {
397        resources.printer.put(process_printer);
398    });
399
400    let process_console = components::process_console::ProcessConsoleComponent::new(
401        board_kernel,
402        uart_mux,
403        mux_alarm,
404        process_printer,
405        Some(cortexm33::support::reset),
406    )
407    .finalize(components::process_console_component_static!(RPTimer));
408    let _ = process_console.start();
409
410    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
411        .finalize(components::round_robin_component_static!(NUM_PROCS));
412
413    let raspberry_pi_pico = RaspberryPiPico2 {
414        ipc: kernel::ipc::IPC::new(
415            board_kernel,
416            kernel::ipc::DRIVER_NUM,
417            &memory_allocation_capability,
418        ),
419        console,
420        alarm,
421        gpio,
422        led,
423        scheduler,
424        systick: cortexm33::systick::SysTick::new_with_calibration(125_000_000),
425    };
426
427    kernel::debug!("Initialization complete. Enter main loop");
428
429    // These symbols are defined in the linker script.
430    extern "C" {
431        /// Beginning of the ROM region containing app images.
432        static _sapps: u8;
433        /// End of the ROM region containing app images.
434        static _eapps: u8;
435        /// Beginning of the RAM region for app memory.
436        static mut _sappmem: u8;
437        /// End of the RAM region for app memory.
438        static _eappmem: u8;
439    }
440
441    kernel::process::load_processes(
442        board_kernel,
443        chip,
444        core::slice::from_raw_parts(
445            core::ptr::addr_of!(_sapps),
446            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
447        ),
448        core::slice::from_raw_parts_mut(
449            core::ptr::addr_of_mut!(_sappmem),
450            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
451        ),
452        &FAULT_RESPONSE,
453        &process_management_capability,
454    )
455    .unwrap_or_else(|err| {
456        kernel::debug!("Error loading processes!");
457        kernel::debug!("{:?}", err);
458    });
459
460    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
461
462    board_kernel.kernel_loop(
463        &raspberry_pi_pico,
464        chip,
465        Some(&raspberry_pi_pico.ipc),
466        &main_loop_capability,
467    );
468}