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