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