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