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