hail/
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 core::str;
8use kernel::debug;
9use kernel::debug::IoWrite;
10use kernel::hil::led;
11use kernel::hil::uart::{self, Configure};
12
13struct Writer {
14    initialized: bool,
15}
16
17static mut WRITER: Writer = Writer { initialized: false };
18
19impl Write for Writer {
20    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
21        self.write(s.as_bytes());
22        Ok(())
23    }
24}
25
26impl IoWrite for Writer {
27    fn write(&mut self, buf: &[u8]) -> usize {
28        // Here, we create a second instance of the USART0 struct.
29        // This is okay because we only call this during a panic, and
30        // we will never actually process the interrupts
31        let pm = unsafe {
32            kernel::static_init!(sam4l::pm::PowerManager, sam4l::pm::PowerManager::new())
33        };
34        let uart = sam4l::usart::USART::new_usart0(pm);
35        let regs_manager = &sam4l::usart::USARTRegManager::panic_new(&uart);
36        if !self.initialized {
37            self.initialized = true;
38            let _ = uart.configure(uart::Parameters {
39                baud_rate: 115200,
40                width: uart::Width::Eight,
41                stop_bits: uart::StopBits::One,
42                parity: uart::Parity::None,
43                hw_flow_control: false,
44            });
45            uart.enable_tx(regs_manager);
46        }
47        // XXX: I'd like to get this working the "right" way, but I'm not sure how
48        for &c in buf {
49            uart.send_byte(regs_manager, c);
50            while !uart.tx_ready(regs_manager) {}
51        }
52        buf.len()
53    }
54}
55
56/// Panic handler.
57#[cfg(not(test))]
58#[panic_handler]
59pub unsafe fn panic_fmt(pi: &PanicInfo) -> ! {
60    // turn off the non panic leds, just in case
61
62    use core::ptr::addr_of_mut;
63    let led_green = sam4l::gpio::GPIOPin::new(sam4l::gpio::Pin::PA14);
64    led_green.enable_output();
65    led_green.set();
66    let led_blue = sam4l::gpio::GPIOPin::new(sam4l::gpio::Pin::PA15);
67    led_blue.enable_output();
68    led_blue.set();
69
70    let red_pin = sam4l::gpio::GPIOPin::new(sam4l::gpio::Pin::PA13);
71    let led_red = &mut led::LedLow::new(&red_pin);
72    let writer = &mut *addr_of_mut!(WRITER);
73    debug::panic(
74        &mut [led_red],
75        writer,
76        pi,
77        &cortexm4::support::nop,
78        crate::PANIC_RESOURCES.get(),
79    )
80}