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
12use crate::CHIP;
13use crate::PROCESSES;
14use crate::PROCESS_PRINTER;
15
16struct Writer {
17    initialized: bool,
18}
19
20static mut WRITER: Writer = Writer { initialized: false };
21
22impl Write for Writer {
23    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
24        self.write(s.as_bytes());
25        Ok(())
26    }
27}
28
29impl IoWrite for Writer {
30    fn write(&mut self, buf: &[u8]) -> usize {
31        // Here, we create a second instance of the USART3 struct.
32        // This is okay because we only call this during a panic, and
33        // we will never actually process the interrupts
34        let uart = unsafe { sam4l::usart::USART::new_usart3(CHIP.unwrap().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        let mut total = 0;
49        for &c in buf {
50            uart.send_byte(regs_manager, c);
51            while !uart.tx_ready(regs_manager) {}
52            total += 1;
53        }
54        total
55    }
56}
57
58/// Panic handler.
59#[cfg(not(test))]
60#[no_mangle]
61#[panic_handler]
62pub unsafe fn panic_fmt(pi: &PanicInfo) -> ! {
63    use core::ptr::{addr_of, addr_of_mut};
64
65    let led_pin = sam4l::gpio::GPIOPin::new(sam4l::gpio::Pin::PC22);
66    let led = &mut led::LedLow::new(&led_pin);
67    let writer = &mut *addr_of_mut!(WRITER);
68    debug::panic(
69        &mut [led],
70        writer,
71        pi,
72        &cortexm4::support::nop,
73        &*addr_of!(PROCESSES),
74        &*addr_of!(CHIP),
75        &*addr_of!(PROCESS_PRINTER),
76    )
77}