nrf52840dk_test_kernel/
io.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
5use core::fmt::Write;
6use core::panic::PanicInfo;
7use cortexm4;
8use kernel::debug;
9use kernel::debug::IoWrite;
10use kernel::hil::led;
11use kernel::hil::uart;
12use kernel::hil::uart::Configure;
13use nrf52840::gpio::Pin;
14use nrf52840::uart::{Uarte, UARTE0_BASE};
15
16use crate::CHIP;
17use crate::PROCESSES;
18use crate::PROCESS_PRINTER;
19
20enum Writer {
21    WriterUart(/* initialized */ bool),
22    WriterRtt(&'static segger::rtt::SeggerRttMemory<'static>),
23}
24
25static mut WRITER: Writer = Writer::WriterUart(false);
26
27/// Set the RTT memory buffer used to output panic messages.
28pub unsafe fn set_rtt_memory(rtt_memory: &'static segger::rtt::SeggerRttMemory<'static>) {
29    WRITER = Writer::WriterRtt(rtt_memory);
30}
31
32impl Write for Writer {
33    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
34        self.write(s.as_bytes());
35        Ok(())
36    }
37}
38
39impl IoWrite for Writer {
40    fn write(&mut self, buf: &[u8]) -> usize {
41        match self {
42            Writer::WriterUart(ref mut initialized) => {
43                // Here, we create a second instance of the Uarte struct.
44                // This is okay because we only call this during a panic, and
45                // we will never actually process the interrupts
46                let uart = Uarte::new(UARTE0_BASE);
47                if !*initialized {
48                    *initialized = true;
49                    let _ = uart.configure(uart::Parameters {
50                        baud_rate: 115200,
51                        stop_bits: uart::StopBits::One,
52                        parity: uart::Parity::None,
53                        hw_flow_control: false,
54                        width: uart::Width::Eight,
55                    });
56                }
57                for &c in buf {
58                    unsafe { uart.send_byte(c) }
59                    while !uart.tx_ready() {}
60                }
61            }
62            Writer::WriterRtt(rtt_memory) => rtt_memory.write_sync(buf),
63        }
64        buf.len()
65    }
66}
67
68#[cfg(not(test))]
69#[no_mangle]
70#[panic_handler]
71/// Panic handler
72pub unsafe fn panic_fmt(pi: &PanicInfo) -> ! {
73    // The nRF52840DK LEDs (see back of board)
74
75    use core::ptr::{addr_of, addr_of_mut};
76    let led_kernel_pin = &nrf52840::gpio::GPIOPin::new(Pin::P0_13);
77    let led = &mut led::LedLow::new(led_kernel_pin);
78    let writer = &mut *addr_of_mut!(WRITER);
79    debug::panic(
80        &mut [led],
81        writer,
82        pi,
83        &cortexm4::support::nop,
84        &*addr_of!(PROCESSES),
85        &*addr_of!(CHIP),
86        &*addr_of!(PROCESS_PRINTER),
87    )
88}