ostd/console/
uart_ns16650a.rs1use core::fmt;
11
12use bitflags::bitflags;
13
14#[repr(u8)]
16#[derive(Clone, Copy, Debug)]
17pub enum Ns16550aRegister {
18 DataOrDivisorLo,
20 IntEnOrDivisorHi,
22 FifoCtrl,
24 LineCtrl,
26 ModemCtrl,
28 LineStat,
30 ModemStat,
32}
33
34impl Ns16550aRegister {
35 pub const MAX: Self = Self::ModemStat;
37}
38
39pub trait Ns16550aAccess {
41 fn read(&self, reg: Ns16550aRegister) -> u8;
43
44 fn write(&mut self, reg: Ns16550aRegister, val: u8);
46}
47
48#[derive(Debug)]
50pub struct Ns16550aUart<A: Ns16550aAccess> {
51 access: A,
52}
53
54bitflags! {
55 #[derive(Clone, Copy, Debug)]
56 struct LineStat: u8 {
57 const DR = 1 << 0;
59 const THRE = 1 << 5;
61 }
62}
63
64impl<A: Ns16550aAccess> Ns16550aUart<A> {
65 pub const fn new(access: A) -> Self {
67 Self { access }
68 }
69
70 pub fn init(&mut self) {
75 const DLAB: u8 = 0x80;
77
78 self.access.write(Ns16550aRegister::LineCtrl, DLAB);
80 self.access.write(Ns16550aRegister::DataOrDivisorLo, 0x01);
81 self.access.write(Ns16550aRegister::IntEnOrDivisorHi, 0x00);
82
83 self.access.write(Ns16550aRegister::LineCtrl, 0x03);
85 self.access.write(Ns16550aRegister::FifoCtrl, 0x00);
87 self.access.write(Ns16550aRegister::ModemCtrl, 0x0B);
89 self.access.write(Ns16550aRegister::IntEnOrDivisorHi, 0x01);
91 }
92
93 pub fn send(&mut self, data: u8) {
97 while !self.line_stat().contains(LineStat::THRE) {
98 core::hint::spin_loop();
99 }
100
101 self.access.write(Ns16550aRegister::DataOrDivisorLo, data);
102 }
103
104 pub fn recv(&mut self) -> Option<u8> {
108 if !self.line_stat().contains(LineStat::DR) {
109 return None;
110 }
111
112 Some(self.access.read(Ns16550aRegister::DataOrDivisorLo))
113 }
114
115 fn line_stat(&self) -> LineStat {
116 LineStat::from_bits_truncate(self.access.read(Ns16550aRegister::LineStat))
117 }
118}
119
120impl<A: Ns16550aAccess> fmt::Write for Ns16550aUart<A> {
121 fn write_str(&mut self, s: &str) -> fmt::Result {
122 for c in s.as_bytes() {
123 if *c == b'\n' {
124 self.send(b'\r');
125 }
126 self.send(*c);
127 }
128 Ok(())
129 }
130}