blob: d44eb922fb83b0f29ac0964699f17f292d2cd061 [file] [log] [blame]
Andrew Walbranf2594882022-03-15 17:32:53 +00001// 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
17use crate::uart::Uart;
18use core::fmt::{write, Arguments, Write};
19use spin::mutex::SpinMutex;
20
21const BASE_ADDRESS: usize = 0x3f8;
22
23static CONSOLE: SpinMutex<Option<Uart>> = SpinMutex::new(None);
24
25/// Initialises a new instance of the UART driver and returns it.
26fn 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.
34pub 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.
42pub 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)]
50pub 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.
58pub fn emergency_write_str(s: &str) {
59 let mut uart = create();
60 let _ = uart.write_str(s);
61}