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