xref: /qemu/rust/hw/char/pl011/src/lib.rs (revision d2c12785be06da708fe1c8e4e81d7134f4f3c56a)
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, qemu_api_macros::TryInto)]
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 pub mod registers {
106     //! Device registers exposed as typed structs which are backed by arbitrary
107     //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc.
108     use bilge::prelude::*;
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 
176     impl Data {
177         // bilge is not very const-friendly, unfortunately
178         pub const BREAK: Self = Self { value: 1 << 10 };
179     }
180 
181     // TODO: FIFO Mode has different semantics
182     /// Receive Status Register / Error Clear Register, `UARTRSR/UARTECR`
183     ///
184     /// The UARTRSR/UARTECR register is the receive status register/error clear
185     /// register. Receive status can also be read from the `UARTRSR`
186     /// register. If the status is read from this register, then the status
187     /// information for break, framing and parity corresponds to the
188     /// data character read from the [Data register](Data), `UARTDR` prior to
189     /// reading the UARTRSR register. The status information for overrun is
190     /// set immediately when an overrun condition occurs.
191     ///
192     ///
193     /// # Note
194     /// The received data character must be read first from the [Data
195     /// Register](Data), `UARTDR` before reading the error status associated
196     /// with that data character from the `UARTRSR` register. This read
197     /// sequence cannot be reversed, because the `UARTRSR` register is
198     /// updated only when a read occurs from the `UARTDR` register. However,
199     /// the status information can also be obtained by reading the `UARTDR`
200     /// register
201     ///
202     /// # Source
203     /// ARM DDI 0183G 3.3.2 Receive Status Register/Error Clear Register,
204     /// UARTRSR/UARTECR
205     #[bitsize(32)]
206     #[derive(Clone, Copy, DebugBits, FromBits)]
207     pub struct ReceiveStatusErrorClear {
208         pub errors: Errors,
209         _reserved_unpredictable: u24,
210     }
211 
212     impl ReceiveStatusErrorClear {
213         pub fn set_from_data(&mut self, data: Data) {
214             self.set_errors(data.errors());
215         }
216 
217         pub fn reset(&mut self) {
218             // All the bits are cleared to 0 on reset.
219             *self = Self::default();
220         }
221     }
222 
223     impl Default for ReceiveStatusErrorClear {
224         fn default() -> Self {
225             0.into()
226         }
227     }
228 
229     #[bitsize(32)]
230     #[derive(Clone, Copy, DebugBits, FromBits)]
231     /// Flag Register, `UARTFR`
232     #[doc(alias = "UARTFR")]
233     pub struct Flags {
234         /// CTS Clear to send. This bit is the complement of the UART clear to
235         /// send, `nUARTCTS`, modem status input. That is, the bit is 1
236         /// when `nUARTCTS` is LOW.
237         pub clear_to_send: bool,
238         /// DSR Data set ready. This bit is the complement of the UART data set
239         /// ready, `nUARTDSR`, modem status input. That is, the bit is 1 when
240         /// `nUARTDSR` is LOW.
241         pub data_set_ready: bool,
242         /// DCD Data carrier detect. This bit is the complement of the UART data
243         /// carrier detect, `nUARTDCD`, modem status input. That is, the bit is
244         /// 1 when `nUARTDCD` is LOW.
245         pub data_carrier_detect: bool,
246         /// BUSY UART busy. If this bit is set to 1, the UART is busy
247         /// transmitting data. This bit remains set until the complete
248         /// byte, including all the stop bits, has been sent from the
249         /// shift register. This bit is set as soon as the transmit FIFO
250         /// becomes non-empty, regardless of whether the UART is enabled
251         /// or not.
252         pub busy: bool,
253         /// RXFE Receive FIFO empty. The meaning of this bit depends on the
254         /// state of the FEN bit in the UARTLCR_H register. If the FIFO
255         /// is disabled, this bit is set when the receive holding
256         /// register is empty. If the FIFO is enabled, the RXFE bit is
257         /// set when the receive FIFO is empty.
258         pub receive_fifo_empty: bool,
259         /// TXFF Transmit FIFO full. The meaning of this bit depends on the
260         /// state of the FEN bit in the UARTLCR_H register. If the FIFO
261         /// is disabled, this bit is set when the transmit holding
262         /// register is full. If the FIFO is enabled, the TXFF bit is
263         /// set when the transmit FIFO is full.
264         pub transmit_fifo_full: bool,
265         /// RXFF Receive FIFO full. The meaning of this bit depends on the state
266         /// of the FEN bit in the UARTLCR_H register. If the FIFO is
267         /// disabled, this bit is set when the receive holding register
268         /// is full. If the FIFO is enabled, the RXFF bit is set when
269         /// the receive FIFO is full.
270         pub receive_fifo_full: bool,
271         /// Transmit FIFO empty. The meaning of this bit depends on the state of
272         /// the FEN bit in the [Line Control register](LineControl),
273         /// `UARTLCR_H`. If the FIFO is disabled, this bit is set when the
274         /// transmit holding register is empty. If the FIFO is enabled,
275         /// the TXFE bit is set when the transmit FIFO is empty. This
276         /// bit does not indicate if there is data in the transmit shift
277         /// register.
278         pub transmit_fifo_empty: bool,
279         /// `RI`, is `true` when `nUARTRI` is `LOW`.
280         pub ring_indicator: bool,
281         _reserved_zero_no_modify: u23,
282     }
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 
358     impl LineControl {
359         pub fn reset(&mut self) {
360             // All the bits are cleared to 0 when reset.
361             *self = 0.into();
362         }
363     }
364 
365     impl Default for LineControl {
366         fn default() -> Self {
367             0.into()
368         }
369     }
370 
371     #[bitsize(1)]
372     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
373     /// `EPS` "Even parity select", field of [Line Control
374     /// register](LineControl).
375     pub enum Parity {
376         /// - 0 = odd parity. The UART generates or checks for an odd number of
377         ///   1s in the data and parity bits.
378         Odd = 0,
379         /// - 1 = even parity. The UART generates or checks for an even number
380         ///   of 1s in the data and parity bits.
381         Even = 1,
382     }
383 
384     #[bitsize(1)]
385     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
386     /// `FEN` "Enable FIFOs" or Device mode, field of [Line Control
387     /// register](LineControl).
388     pub enum Mode {
389         /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become
390         /// 1-byte-deep holding registers
391         Character = 0,
392         /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode).
393         FIFO = 1,
394     }
395 
396     #[bitsize(2)]
397     #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)]
398     /// `WLEN` Word length, field of [Line Control register](LineControl).
399     ///
400     /// These bits indicate the number of data bits transmitted or received in a
401     /// frame as follows:
402     pub enum WordLength {
403         /// b11 = 8 bits
404         _8Bits = 0b11,
405         /// b10 = 7 bits
406         _7Bits = 0b10,
407         /// b01 = 6 bits
408         _6Bits = 0b01,
409         /// b00 = 5 bits.
410         _5Bits = 0b00,
411     }
412 
413     /// Control Register, `UARTCR`
414     ///
415     /// The `UARTCR` register is the control register. All the bits are cleared
416     /// to `0` on reset except for bits `9` and `8` that are set to `1`.
417     ///
418     /// # Source
419     /// ARM DDI 0183G, 3.3.8 Control Register, `UARTCR`, Table 3-12
420     #[bitsize(32)]
421     #[doc(alias = "UARTCR")]
422     #[derive(Clone, Copy, DebugBits, FromBits)]
423     pub struct Control {
424         /// `UARTEN` UART enable: 0 = UART is disabled. If the UART is disabled
425         /// in the middle of transmission or reception, it completes the current
426         /// character before stopping. 1 = the UART is enabled. Data
427         /// transmission and reception occurs for either UART signals or SIR
428         /// signals depending on the setting of the SIREN bit.
429         pub enable_uart: bool,
430         /// `SIREN` `SIR` enable: 0 = IrDA SIR ENDEC is disabled. `nSIROUT`
431         /// remains LOW (no light pulse generated), and signal transitions on
432         /// SIRIN have no effect. 1 = IrDA SIR ENDEC is enabled. Data is
433         /// transmitted and received on nSIROUT and SIRIN. UARTTXD remains HIGH,
434         /// in the marking state. Signal transitions on UARTRXD or modem status
435         /// inputs have no effect. This bit has no effect if the UARTEN bit
436         /// disables the UART.
437         pub enable_sir: bool,
438         /// `SIRLP` SIR low-power IrDA mode. This bit selects the IrDA encoding
439         /// mode. If this bit is cleared to 0, low-level bits are transmitted as
440         /// an active high pulse with a width of 3/ 16th of the bit period. If
441         /// this bit is set to 1, low-level bits are transmitted with a pulse
442         /// width that is 3 times the period of the IrLPBaud16 input signal,
443         /// regardless of the selected bit rate. Setting this bit uses less
444         /// power, but might reduce transmission distances.
445         pub sir_lowpower_irda_mode: u1,
446         /// Reserved, do not modify, read as zero.
447         _reserved_zero_no_modify: u4,
448         /// `LBE` Loopback enable. If this bit is set to 1 and the SIREN bit is
449         /// set to 1 and the SIRTEST bit in the Test Control register, UARTTCR
450         /// on page 4-5 is set to 1, then the nSIROUT path is inverted, and fed
451         /// through to the SIRIN path. The SIRTEST bit in the test register must
452         /// be set to 1 to override the normal half-duplex SIR operation. This
453         /// must be the requirement for accessing the test registers during
454         /// normal operation, and SIRTEST must be cleared to 0 when loopback
455         /// testing is finished. This feature reduces the amount of external
456         /// coupling required during system test. If this bit is set to 1, and
457         /// the SIRTEST bit is set to 0, the UARTTXD path is fed through to the
458         /// UARTRXD path. In either SIR mode or UART mode, when this bit is set,
459         /// the modem outputs are also fed through to the modem inputs. This bit
460         /// is cleared to 0 on reset, to disable loopback.
461         pub enable_loopback: bool,
462         /// `TXE` Transmit enable. If this bit is set to 1, the transmit section
463         /// of the UART is enabled. Data transmission occurs for either UART
464         /// signals, or SIR signals depending on the setting of the SIREN bit.
465         /// When the UART is disabled in the middle of transmission, it
466         /// completes the current character before stopping.
467         pub enable_transmit: bool,
468         /// `RXE` Receive enable. If this bit is set to 1, the receive section
469         /// of the UART is enabled. Data reception occurs for either UART
470         /// signals or SIR signals depending on the setting of the SIREN bit.
471         /// When the UART is disabled in the middle of reception, it completes
472         /// the current character before stopping.
473         pub enable_receive: bool,
474         /// `DTR` Data transmit ready. This bit is the complement of the UART
475         /// data transmit ready, `nUARTDTR`, modem status output. That is, when
476         /// the bit is programmed to a 1 then `nUARTDTR` is LOW.
477         pub data_transmit_ready: bool,
478         /// `RTS` Request to send. This bit is the complement of the UART
479         /// request to send, `nUARTRTS`, modem status output. That is, when the
480         /// bit is programmed to a 1 then `nUARTRTS` is LOW.
481         pub request_to_send: bool,
482         /// `Out1` This bit is the complement of the UART Out1 (`nUARTOut1`)
483         /// modem status output. That is, when the bit is programmed to a 1 the
484         /// output is 0. For DTE this can be used as Data Carrier Detect (DCD).
485         pub out_1: bool,
486         /// `Out2` This bit is the complement of the UART Out2 (`nUARTOut2`)
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 Ring Indicator (RI).
489         pub out_2: bool,
490         /// `RTSEn` RTS hardware flow control enable. If this bit is set to 1,
491         /// RTS hardware flow control is enabled. Data is only requested when
492         /// there is space in the receive FIFO for it to be received.
493         pub rts_hardware_flow_control_enable: bool,
494         /// `CTSEn` CTS hardware flow control enable. If this bit is set to 1,
495         /// CTS hardware flow control is enabled. Data is only transmitted when
496         /// the `nUARTCTS` signal is asserted.
497         pub cts_hardware_flow_control_enable: bool,
498         /// 31:16 - Reserved, do not modify, read as zero.
499         _reserved_zero_no_modify2: u16,
500     }
501 
502     impl Control {
503         pub fn reset(&mut self) {
504             *self = 0.into();
505             self.set_enable_receive(true);
506             self.set_enable_transmit(true);
507         }
508     }
509 
510     impl Default for Control {
511         fn default() -> Self {
512             let mut ret: Self = 0.into();
513             ret.reset();
514             ret
515         }
516     }
517 
518     /// Interrupt status bits in UARTRIS, UARTMIS, UARTIMSC
519     pub const INT_OE: u32 = 1 << 10;
520     pub const INT_BE: u32 = 1 << 9;
521     pub const INT_PE: u32 = 1 << 8;
522     pub const INT_FE: u32 = 1 << 7;
523     pub const INT_RT: u32 = 1 << 6;
524     pub const INT_TX: u32 = 1 << 5;
525     pub const INT_RX: u32 = 1 << 4;
526     pub const INT_DSR: u32 = 1 << 3;
527     pub const INT_DCD: u32 = 1 << 2;
528     pub const INT_CTS: u32 = 1 << 1;
529     pub const INT_RI: u32 = 1 << 0;
530     pub const INT_E: u32 = INT_OE | INT_BE | INT_PE | INT_FE;
531     pub const INT_MS: u32 = INT_RI | INT_DSR | INT_DCD | INT_CTS;
532 
533     #[repr(u32)]
534     pub enum Interrupt {
535         OE = 1 << 10,
536         BE = 1 << 9,
537         PE = 1 << 8,
538         FE = 1 << 7,
539         RT = 1 << 6,
540         TX = 1 << 5,
541         RX = 1 << 4,
542         DSR = 1 << 3,
543         DCD = 1 << 2,
544         CTS = 1 << 1,
545         RI = 1 << 0,
546     }
547 
548     impl Interrupt {
549         pub const E: u32 = INT_OE | INT_BE | INT_PE | INT_FE;
550         pub const MS: u32 = INT_RI | INT_DSR | INT_DCD | INT_CTS;
551     }
552 }
553 
554 // TODO: You must disable the UART before any of the control registers are
555 // reprogrammed. When the UART is disabled in the middle of transmission or
556 // reception, it completes the current character before stopping
557