Andrew Walbran | f259488 | 2022-03-15 17:32:53 +0000 | [diff] [blame^] | 1 | // Copyright 2022, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Console driver for 8250 UART. |
| 16 | |
| 17 | use crate::uart::Uart; |
| 18 | use core::fmt::{write, Arguments, Write}; |
| 19 | use spin::mutex::SpinMutex; |
| 20 | |
| 21 | const BASE_ADDRESS: usize = 0x3f8; |
| 22 | |
| 23 | static CONSOLE: SpinMutex<Option<Uart>> = SpinMutex::new(None); |
| 24 | |
| 25 | /// Initialises a new instance of the UART driver and returns it. |
| 26 | fn create() -> Uart { |
| 27 | // Safe because BASE_ADDRESS is the base of the MMIO region for a UART and is mapped as device |
| 28 | // memory. |
| 29 | unsafe { Uart::new(BASE_ADDRESS) } |
| 30 | } |
| 31 | |
| 32 | /// Initialises the global instance of the UART driver. This must be called before using |
| 33 | /// the `print!` and `println!` macros. |
| 34 | pub fn init() { |
| 35 | let uart = create(); |
| 36 | CONSOLE.lock().replace(uart); |
| 37 | } |
| 38 | |
| 39 | /// Writes a string to the console. |
| 40 | /// |
| 41 | /// Panics if [`init`] was not called first. |
| 42 | pub fn write_str(s: &str) { |
| 43 | CONSOLE.lock().as_mut().unwrap().write_str(s).unwrap(); |
| 44 | } |
| 45 | |
| 46 | /// Writes a formatted string to the console. |
| 47 | /// |
| 48 | /// Panics if [`init`] was not called first. |
| 49 | #[allow(unused)] |
| 50 | pub fn write_args(format_args: Arguments) { |
| 51 | write(CONSOLE.lock().as_mut().unwrap(), format_args).unwrap(); |
| 52 | } |
| 53 | |
| 54 | /// Reinitialises the UART driver and writes a string to it. |
| 55 | /// |
| 56 | /// This is intended for use in situations where the UART may be in an unknown state or the global |
| 57 | /// instance may be locked, such as in an exception handler or panic handler. |
| 58 | pub fn emergency_write_str(s: &str) { |
| 59 | let mut uart = create(); |
| 60 | let _ = uart.write_str(s); |
| 61 | } |