xref: /qemu/rust/hw/char/pl011/src/lib.rs (revision fd363a14f68a7bcbede024fb5155371c19b8f5d2)
1 // Copyright 2024, Linaro Limited
2 // Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 //
5 // PL011 QEMU Device Model
6 //
7 // This library implements a device model for the PrimeCell® UART (PL011)
8 // device in QEMU.
9 //
10 #![doc = include_str!("../README.md")]
11 //! # Library crate
12 //!
13 //! See [`PL011State`](crate::device::PL011State) for the device model type and
14 //! the [`registers`] module for register types.
15 
16 #![deny(
17     clippy::correctness,
18     clippy::suspicious,
19     clippy::complexity,
20     clippy::perf,
21     clippy::cargo,
22     clippy::nursery,
23     clippy::style
24 )]
25 #![allow(clippy::upper_case_acronyms)]
26 #![allow(clippy::result_unit_err)]
27 
28 extern crate bilge;
29 extern crate bilge_impl;
30 extern crate qemu_api;
31 
32 use qemu_api::c_str;
33 
34 pub mod device;
35 pub mod device_class;
36 pub mod memory_ops;
37 
38 pub const TYPE_PL011: &::std::ffi::CStr = c_str!("pl011");
39 pub const TYPE_PL011_LUMINARY: &::std::ffi::CStr = c_str!("pl011_luminary");
40 
41 /// Offset of each register from the base memory address of the device.
42 ///
43 /// # Source
44 /// ARM DDI 0183G, Table 3-1 p.3-3
45 #[doc(alias = "offset")]
46 #[allow(non_camel_case_types)]
47 #[repr(u64)]
48 #[derive(Debug)]
49 pub enum RegisterOffset {
50     /// Data Register
51     ///
52     /// A write to this register initiates the actual data transmission
53     #[doc(alias = "UARTDR")]
54     DR = 0x000,
55     /// Receive Status Register or Error Clear Register
56     #[doc(alias = "UARTRSR")]
57     #[doc(alias = "UARTECR")]
58     RSR = 0x004,
59     /// Flag Register
60     ///
61     /// A read of this register shows if transmission is complete
62     #[doc(alias = "UARTFR")]
63     FR = 0x018,
64     /// Fractional Baud Rate Register
65     ///
66     /// responsible for baud rate speed
67     #[doc(alias = "UARTFBRD")]
68     FBRD = 0x028,
69     /// `IrDA` Low-Power Counter Register
70     #[doc(alias = "UARTILPR")]
71     ILPR = 0x020,
72     /// Integer Baud Rate Register
73     ///
74     /// Responsible for baud rate speed
75     #[doc(alias = "UARTIBRD")]
76     IBRD = 0x024,
77     /// line control register (data frame format)
78     #[doc(alias = "UARTLCR_H")]
79     LCR_H = 0x02C,
80     /// Toggle UART, transmission or reception
81     #[doc(alias = "UARTCR")]
82     CR = 0x030,
83     /// Interrupt FIFO Level Select Register
84     #[doc(alias = "UARTIFLS")]
85     FLS = 0x034,
86     /// Interrupt Mask Set/Clear Register
87     #[doc(alias = "UARTIMSC")]
88     IMSC = 0x038,
89     /// Raw Interrupt Status Register
90     #[doc(alias = "UARTRIS")]
91     RIS = 0x03C,
92     /// Masked Interrupt Status Register
93     #[doc(alias = "UARTMIS")]
94     MIS = 0x040,
95     /// Interrupt Clear Register
96     #[doc(alias = "UARTICR")]
97     ICR = 0x044,
98     /// DMA control Register
99     #[doc(alias = "UARTDMACR")]
100     DMACR = 0x048,
101     ///// Reserved, offsets `0x04C` to `0x07C`.
102     //Reserved = 0x04C,
103 }
104 
105 impl core::convert::TryFrom<u64> for RegisterOffset {
106     type Error = u64;
107 
108     fn try_from(value: u64) -> Result<Self, Self::Error> {
109         macro_rules! case {
110             ($($discriminant:ident),*$(,)*) => {
111                 /* check that matching on all macro arguments compiles, which means we are not
112                  * missing any enum value; if the type definition ever changes this will stop
113                  * compiling.
114                  */
115                 const fn _assert_exhaustive(val: RegisterOffset) {
116                     match val {
117                         $(RegisterOffset::$discriminant => (),)*
118                     }
119                 }
120 
121                 match value {
122                     $(x if x == Self::$discriminant as u64 => Ok(Self::$discriminant),)*
123                      _ => Err(value),
124                 }
125             }
126         }
127         case! { DR, RSR, FR, FBRD, ILPR, IBRD, LCR_H, CR, FLS, IMSC, RIS, MIS, ICR, DMACR }
128     }
129 }
130 
131 pub mod registers {
132     //! Device registers exposed as typed structs which are backed by arbitrary
133     //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc.
134     //!
135     //! All PL011 registers are essentially 32-bit wide, but are typed here as
136     //! bitmaps with only the necessary width. That is, if a struct bitmap
137     //! in this module is for example 16 bits long, it should be conceived
138     //! as a 32-bit register where the unmentioned higher bits are always
139     //! unused thus treated as zero when read or written.
140     use bilge::prelude::*;
141 
142     // TODO: FIFO Mode has different semantics
143     /// Data Register, `UARTDR`
144     ///
145     /// The `UARTDR` register is the data register.
146     ///
147     /// For words to be transmitted:
148     ///
149     /// - if the FIFOs are enabled, data written to this location is pushed onto
150     ///   the transmit
151     /// FIFO
152     /// - if the FIFOs are not enabled, data is stored in the transmitter
153     ///   holding register (the
154     /// bottom word of the transmit FIFO).
155     ///
156     /// The write operation initiates transmission from the UART. The data is
157     /// prefixed with a start bit, appended with the appropriate parity bit
158     /// (if parity is enabled), and a stop bit. The resultant word is then
159     /// transmitted.
160     ///
161     /// For received words:
162     ///
163     /// - if the FIFOs are enabled, the data byte and the 4-bit status (break,
164     ///   frame, parity,
165     /// and overrun) is pushed onto the 12-bit wide receive FIFO
166     /// - if the FIFOs are not enabled, the data byte and status are stored in
167     ///   the receiving
168     /// holding register (the bottom word of the receive FIFO).
169     ///
170     /// The received data byte is read by performing reads from the `UARTDR`
171     /// register along with the corresponding status information. The status
172     /// information can also be read by a read of the `UARTRSR/UARTECR`
173     /// register.
174     ///
175     /// # Note
176     ///
177     /// You must disable the UART before any of the control registers are
178     /// reprogrammed. When the UART is disabled in the middle of
179     /// transmission or reception, it completes the current character before
180     /// stopping.
181     ///
182     /// # Source
183     /// ARM DDI 0183G 3.3.1 Data Register, UARTDR
184     #[bitsize(16)]
185     #[derive(Clone, Copy, DebugBits, FromBits)]
186     #[doc(alias = "UARTDR")]
187     pub struct Data {
188         _reserved: u4,
189         pub data: u8,
190         pub framing_error: bool,
191         pub parity_error: bool,
192         pub break_error: bool,
193         pub overrun_error: bool,
194     }
195 
196     // TODO: FIFO Mode has different semantics
197     /// Receive Status Register / Error Clear Register, `UARTRSR/UARTECR`
198     ///
199     /// The UARTRSR/UARTECR register is the receive status register/error clear
200     /// register. Receive status can also be read from the `UARTRSR`
201     /// register. If the status is read from this register, then the status
202     /// information for break, framing and parity corresponds to the
203     /// data character read from the [Data register](Data), `UARTDR` prior to
204     /// reading the UARTRSR register. The status information for overrun is
205     /// set immediately when an overrun condition occurs.
206     ///
207     ///
208     /// # Note
209     /// The received data character must be read first from the [Data
210     /// Register](Data), `UARTDR` before reading the error status associated
211     /// with that data character from the `UARTRSR` register. This read
212     /// sequence cannot be reversed, because the `UARTRSR` register is
213     /// updated only when a read occurs from the `UARTDR` register. However,
214     /// the status information can also be obtained by reading the `UARTDR`
215     /// register
216     ///
217     /// # Source
218     /// ARM DDI 0183G 3.3.2 Receive Status Register/Error Clear Register,
219     /// UARTRSR/UARTECR
220     #[bitsize(8)]
221     #[derive(Clone, Copy, DebugBits, FromBits)]
222     pub struct ReceiveStatusErrorClear {
223         pub framing_error: bool,
224         pub parity_error: bool,
225         pub break_error: bool,
226         pub overrun_error: bool,
227         _reserved_unpredictable: u4,
228     }
229 
230     impl ReceiveStatusErrorClear {
231         pub fn reset(&mut self) {
232             // All the bits are cleared to 0 on reset.
233             *self = 0.into();
234         }
235     }
236 
237     impl Default for ReceiveStatusErrorClear {
238         fn default() -> Self {
239             0.into()
240         }
241     }
242 
243     #[bitsize(16)]
244     #[derive(Clone, Copy, DebugBits, FromBits)]
245     /// Flag Register, `UARTFR`
246     #[doc(alias = "UARTFR")]
247     pub struct Flags {
248         /// CTS Clear to send. This bit is the complement of the UART clear to
249         /// send, `nUARTCTS`, modem status input. That is, the bit is 1
250         /// when `nUARTCTS` is LOW.
251         pub clear_to_send: bool,
252         /// DSR Data set ready. This bit is the complement of the UART data set
253         /// ready, `nUARTDSR`, modem status input. That is, the bit is 1 when
254         /// `nUARTDSR` is LOW.
255         pub data_set_ready: bool,
256         /// DCD Data carrier detect. This bit is the complement of the UART data
257         /// carrier detect, `nUARTDCD`, modem status input. That is, the bit is
258         /// 1 when `nUARTDCD` is LOW.
259         pub data_carrier_detect: bool,
260         /// BUSY UART busy. If this bit is set to 1, the UART is busy
261         /// transmitting data. This bit remains set until the complete
262         /// byte, including all the stop bits, has been sent from the
263         /// shift register. This bit is set as soon as the transmit FIFO
264         /// becomes non-empty, regardless of whether the UART is enabled
265         /// or not.
266         pub busy: bool,
267         /// RXFE Receive FIFO empty. The meaning of this bit depends on the
268         /// state of the FEN bit in the UARTLCR_H register. If the FIFO
269         /// is disabled, this bit is set when the receive holding
270         /// register is empty. If the FIFO is enabled, the RXFE bit is
271         /// set when the receive FIFO is empty.
272         pub receive_fifo_empty: bool,
273         /// TXFF Transmit FIFO full. The meaning of this bit depends on the
274         /// state of the FEN bit in the UARTLCR_H register. If the FIFO
275         /// is disabled, this bit is set when the transmit holding
276         /// register is full. If the FIFO is enabled, the TXFF bit is
277         /// set when the transmit FIFO is full.
278         pub transmit_fifo_full: bool,
279         /// RXFF Receive FIFO full. The meaning of this bit depends on the state
280         /// of the FEN bit in the UARTLCR_H register. If the FIFO is
281         /// disabled, this bit is set when the receive holding register
282         /// is full. If the FIFO is enabled, the RXFF bit is set when
283         /// the receive FIFO is full.
284         pub receive_fifo_full: bool,
285         /// Transmit FIFO empty. The meaning of this bit depends on the state of
286         /// the FEN bit in the [Line Control register](LineControl),
287         /// `UARTLCR_H`. If the FIFO is disabled, this bit is set when the
288         /// transmit holding register is empty. If the FIFO is enabled,
289         /// the TXFE bit is set when the transmit FIFO is empty. This
290         /// bit does not indicate if there is data in the transmit shift
291         /// register.
292         pub transmit_fifo_empty: bool,
293         /// `RI`, is `true` when `nUARTRI` is `LOW`.
294         pub ring_indicator: bool,
295         _reserved_zero_no_modify: u7,
296     }
297 
298     impl Flags {
299         pub fn reset(&mut self) {
300             // After reset TXFF, RXFF, and BUSY are 0, and TXFE and RXFE are 1
301             self.set_receive_fifo_full(false);
302             self.set_transmit_fifo_full(false);
303             self.set_busy(false);
304             self.set_receive_fifo_empty(true);
305             self.set_transmit_fifo_empty(true);
306         }
307     }
308 
309     impl Default for Flags {
310         fn default() -> Self {
311             let mut ret: Self = 0.into();
312             ret.reset();
313             ret
314         }
315     }
316 
317     #[bitsize(16)]
318     #[derive(Clone, Copy, DebugBits, FromBits)]
319     /// Line Control Register, `UARTLCR_H`
320     #[doc(alias = "UARTLCR_H")]
321     pub struct LineControl {
322         /// 15:8 - Reserved, do not modify, read as zero.
323         _reserved_zero_no_modify: u8,
324         /// 7 SPS Stick parity select.
325         /// 0 = stick parity is disabled
326         /// 1 = either:
327         /// • if the EPS bit is 0 then the parity bit is transmitted and checked
328         /// as a 1 • if the EPS bit is 1 then the parity bit is
329         /// transmitted and checked as a 0. This bit has no effect when
330         /// the PEN bit disables parity checking and generation. See Table 3-11
331         /// on page 3-14 for the parity truth table.
332         pub sticky_parity: bool,
333         /// WLEN Word length. These bits indicate the number of data bits
334         /// transmitted or received in a frame as follows: b11 = 8 bits
335         /// b10 = 7 bits
336         /// b01 = 6 bits
337         /// b00 = 5 bits.
338         pub word_length: WordLength,
339         /// FEN Enable FIFOs:
340         /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become
341         /// 1-byte-deep holding registers 1 = transmit and receive FIFO
342         /// buffers are enabled (FIFO mode).
343         pub fifos_enabled: Mode,
344         /// 3 STP2 Two stop bits select. If this bit is set to 1, two stop bits
345         /// are transmitted at the end of the frame. The receive
346         /// logic does not check for two stop bits being received.
347         pub two_stops_bits: bool,
348         /// EPS Even parity select. Controls the type of parity the UART uses
349         /// during transmission and reception:
350         /// - 0 = odd parity. The UART generates or checks for an odd number of
351         ///   1s in the data and parity bits.
352         /// - 1 = even parity. The UART generates or checks for an even number
353         ///   of 1s in the data and parity bits.
354         /// This bit has no effect when the `PEN` bit disables parity checking
355         /// and generation. See Table 3-11 on page 3-14 for the parity
356         /// truth table.
357         pub parity: Parity,
358         /// 1 PEN Parity enable:
359         ///
360         /// - 0 = parity is disabled and no parity bit added to the data frame
361         /// - 1 = parity checking and generation is enabled.
362         ///
363         /// See Table 3-11 on page 3-14 for the parity truth table.
364         pub parity_enabled: bool,
365         /// BRK Send break.
366         ///
367         /// If this bit is set to `1`, a low-level is continually output on the
368         /// `UARTTXD` output, after completing transmission of the
369         /// current character. For the proper execution of the break command,
370         /// the software must set this bit for at least two complete
371         /// frames. For normal use, this bit must be cleared to `0`.
372         pub send_break: bool,
373     }
374 
375     impl LineControl {
376         pub fn reset(&mut self) {
377             // All the bits are cleared to 0 when reset.
378             *self = 0.into();
379         }
380     }
381 
382     impl Default for LineControl {
383         fn default() -> Self {
384             0.into()
385         }
386     }
387 
388     #[bitsize(1)]
389     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
390     /// `EPS` "Even parity select", field of [Line Control
391     /// register](LineControl).
392     pub enum Parity {
393         /// - 0 = odd parity. The UART generates or checks for an odd number of
394         ///   1s in the data and parity bits.
395         Odd = 0,
396         /// - 1 = even parity. The UART generates or checks for an even number
397         ///   of 1s in the data and parity bits.
398         Even = 1,
399     }
400 
401     #[bitsize(1)]
402     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
403     /// `FEN` "Enable FIFOs" or Device mode, field of [Line Control
404     /// register](LineControl).
405     pub enum Mode {
406         /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become
407         /// 1-byte-deep holding registers
408         Character = 0,
409         /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode).
410         FIFO = 1,
411     }
412 
413     impl From<Mode> for bool {
414         fn from(val: Mode) -> Self {
415             matches!(val, Mode::FIFO)
416         }
417     }
418 
419     #[bitsize(2)]
420     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
421     /// `WLEN` Word length, field of [Line Control register](LineControl).
422     ///
423     /// These bits indicate the number of data bits transmitted or received in a
424     /// frame as follows:
425     pub enum WordLength {
426         /// b11 = 8 bits
427         _8Bits = 0b11,
428         /// b10 = 7 bits
429         _7Bits = 0b10,
430         /// b01 = 6 bits
431         _6Bits = 0b01,
432         /// b00 = 5 bits.
433         _5Bits = 0b00,
434     }
435 
436     /// Control Register, `UARTCR`
437     ///
438     /// The `UARTCR` register is the control register. All the bits are cleared
439     /// to `0` on reset except for bits `9` and `8` that are set to `1`.
440     ///
441     /// # Source
442     /// ARM DDI 0183G, 3.3.8 Control Register, `UARTCR`, Table 3-12
443     #[bitsize(16)]
444     #[doc(alias = "UARTCR")]
445     #[derive(Clone, Copy, DebugBits, FromBits)]
446     pub struct Control {
447         /// `UARTEN` UART enable: 0 = UART is disabled. If the UART is disabled
448         /// in the middle of transmission or reception, it completes the current
449         /// character before stopping. 1 = the UART is enabled. Data
450         /// transmission and reception occurs for either UART signals or SIR
451         /// signals depending on the setting of the SIREN bit.
452         pub enable_uart: bool,
453         /// `SIREN` `SIR` enable: 0 = IrDA SIR ENDEC is disabled. `nSIROUT`
454         /// remains LOW (no light pulse generated), and signal transitions on
455         /// SIRIN have no effect. 1 = IrDA SIR ENDEC is enabled. Data is
456         /// transmitted and received on nSIROUT and SIRIN. UARTTXD remains HIGH,
457         /// in the marking state. Signal transitions on UARTRXD or modem status
458         /// inputs have no effect. This bit has no effect if the UARTEN bit
459         /// disables the UART.
460         pub enable_sir: bool,
461         /// `SIRLP` SIR low-power IrDA mode. This bit selects the IrDA encoding
462         /// mode. If this bit is cleared to 0, low-level bits are transmitted as
463         /// an active high pulse with a width of 3/ 16th of the bit period. If
464         /// this bit is set to 1, low-level bits are transmitted with a pulse
465         /// width that is 3 times the period of the IrLPBaud16 input signal,
466         /// regardless of the selected bit rate. Setting this bit uses less
467         /// power, but might reduce transmission distances.
468         pub sir_lowpower_irda_mode: u1,
469         /// Reserved, do not modify, read as zero.
470         _reserved_zero_no_modify: u4,
471         /// `LBE` Loopback enable. If this bit is set to 1 and the SIREN bit is
472         /// set to 1 and the SIRTEST bit in the Test Control register, UARTTCR
473         /// on page 4-5 is set to 1, then the nSIROUT path is inverted, and fed
474         /// through to the SIRIN path. The SIRTEST bit in the test register must
475         /// be set to 1 to override the normal half-duplex SIR operation. This
476         /// must be the requirement for accessing the test registers during
477         /// normal operation, and SIRTEST must be cleared to 0 when loopback
478         /// testing is finished. This feature reduces the amount of external
479         /// coupling required during system test. If this bit is set to 1, and
480         /// the SIRTEST bit is set to 0, the UARTTXD path is fed through to the
481         /// UARTRXD path. In either SIR mode or UART mode, when this bit is set,
482         /// the modem outputs are also fed through to the modem inputs. This bit
483         /// is cleared to 0 on reset, to disable loopback.
484         pub enable_loopback: bool,
485         /// `TXE` Transmit enable. If this bit is set to 1, the transmit section
486         /// of the UART is enabled. Data transmission occurs for either UART
487         /// signals, or SIR signals depending on the setting of the SIREN bit.
488         /// When the UART is disabled in the middle of transmission, it
489         /// completes the current character before stopping.
490         pub enable_transmit: bool,
491         /// `RXE` Receive enable. If this bit is set to 1, the receive section
492         /// of the UART is enabled. Data reception occurs for either UART
493         /// signals or SIR signals depending on the setting of the SIREN bit.
494         /// When the UART is disabled in the middle of reception, it completes
495         /// the current character before stopping.
496         pub enable_receive: bool,
497         /// `DTR` Data transmit ready. This bit is the complement of the UART
498         /// data transmit ready, `nUARTDTR`, modem status output. That is, when
499         /// the bit is programmed to a 1 then `nUARTDTR` is LOW.
500         pub data_transmit_ready: bool,
501         /// `RTS` Request to send. This bit is the complement of the UART
502         /// request to send, `nUARTRTS`, modem status output. That is, when the
503         /// bit is programmed to a 1 then `nUARTRTS` is LOW.
504         pub request_to_send: bool,
505         /// `Out1` This bit is the complement of the UART Out1 (`nUARTOut1`)
506         /// modem status output. That is, when the bit is programmed to a 1 the
507         /// output is 0. For DTE this can be used as Data Carrier Detect (DCD).
508         pub out_1: bool,
509         /// `Out2` This bit is the complement of the UART Out2 (`nUARTOut2`)
510         /// modem status output. That is, when the bit is programmed to a 1, the
511         /// output is 0. For DTE this can be used as Ring Indicator (RI).
512         pub out_2: bool,
513         /// `RTSEn` RTS hardware flow control enable. If this bit is set to 1,
514         /// RTS hardware flow control is enabled. Data is only requested when
515         /// there is space in the receive FIFO for it to be received.
516         pub rts_hardware_flow_control_enable: bool,
517         /// `CTSEn` CTS hardware flow control enable. If this bit is set to 1,
518         /// CTS hardware flow control is enabled. Data is only transmitted when
519         /// the `nUARTCTS` signal is asserted.
520         pub cts_hardware_flow_control_enable: bool,
521     }
522 
523     impl Control {
524         pub fn reset(&mut self) {
525             *self = 0.into();
526             self.set_enable_receive(true);
527             self.set_enable_transmit(true);
528         }
529     }
530 
531     impl Default for Control {
532         fn default() -> Self {
533             let mut ret: Self = 0.into();
534             ret.reset();
535             ret
536         }
537     }
538 
539     /// Interrupt status bits in UARTRIS, UARTMIS, UARTIMSC
540     pub const INT_OE: u32 = 1 << 10;
541     pub const INT_BE: u32 = 1 << 9;
542     pub const INT_PE: u32 = 1 << 8;
543     pub const INT_FE: u32 = 1 << 7;
544     pub const INT_RT: u32 = 1 << 6;
545     pub const INT_TX: u32 = 1 << 5;
546     pub const INT_RX: u32 = 1 << 4;
547     pub const INT_DSR: u32 = 1 << 3;
548     pub const INT_DCD: u32 = 1 << 2;
549     pub const INT_CTS: u32 = 1 << 1;
550     pub const INT_RI: u32 = 1 << 0;
551     pub const INT_E: u32 = INT_OE | INT_BE | INT_PE | INT_FE;
552     pub const INT_MS: u32 = INT_RI | INT_DSR | INT_DCD | INT_CTS;
553 
554     #[repr(u32)]
555     pub enum Interrupt {
556         OE = 1 << 10,
557         BE = 1 << 9,
558         PE = 1 << 8,
559         FE = 1 << 7,
560         RT = 1 << 6,
561         TX = 1 << 5,
562         RX = 1 << 4,
563         DSR = 1 << 3,
564         DCD = 1 << 2,
565         CTS = 1 << 1,
566         RI = 1 << 0,
567     }
568 
569     impl Interrupt {
570         pub const E: u32 = INT_OE | INT_BE | INT_PE | INT_FE;
571         pub const MS: u32 = INT_RI | INT_DSR | INT_DCD | INT_CTS;
572     }
573 }
574 
575 // TODO: You must disable the UART before any of the control registers are
576 // reprogrammed. When the UART is disabled in the middle of transmission or
577 // reception, it completes the current character before stopping
578