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