xref: /qemu/rust/hw/char/pl011/src/device.rs (revision 6b4f7b0705be31c7df6ea01c81a42a42950959a9)
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 use core::ptr::{addr_of_mut, NonNull};
6 use std::{
7     ffi::CStr,
8     os::raw::{c_int, c_uchar, c_uint, c_void},
9 };
10 
11 use qemu_api::{
12     bindings::{self, *},
13     c_str,
14     irq::InterruptSource,
15     prelude::*,
16     qdev::DeviceImpl,
17     qom::ObjectImpl,
18 };
19 
20 use crate::{
21     device_class,
22     memory_ops::PL011_OPS,
23     registers::{self, Interrupt},
24     RegisterOffset,
25 };
26 
27 /// Integer Baud Rate Divider, `UARTIBRD`
28 const IBRD_MASK: u32 = 0xffff;
29 
30 /// Fractional Baud Rate Divider, `UARTFBRD`
31 const FBRD_MASK: u32 = 0x3f;
32 
33 /// QEMU sourced constant.
34 pub const PL011_FIFO_DEPTH: u32 = 16;
35 
36 #[derive(Clone, Copy, Debug)]
37 enum DeviceId {
38     #[allow(dead_code)]
39     Arm = 0,
40     Luminary,
41 }
42 
43 impl std::ops::Index<hwaddr> for DeviceId {
44     type Output = c_uchar;
45 
46     fn index(&self, idx: hwaddr) -> &Self::Output {
47         match self {
48             Self::Arm => &Self::PL011_ID_ARM[idx as usize],
49             Self::Luminary => &Self::PL011_ID_LUMINARY[idx as usize],
50         }
51     }
52 }
53 
54 impl DeviceId {
55     const PL011_ID_ARM: [c_uchar; 8] = [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1];
56     const PL011_ID_LUMINARY: [c_uchar; 8] = [0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1];
57 }
58 
59 // FIFOs use 32-bit indices instead of usize, for compatibility with
60 // the migration stream produced by the C version of this device.
61 #[repr(transparent)]
62 #[derive(Debug, Default)]
63 pub struct Fifo([registers::Data; PL011_FIFO_DEPTH as usize]);
64 
65 impl Fifo {
66     const fn len(&self) -> u32 {
67         self.0.len() as u32
68     }
69 }
70 
71 impl std::ops::IndexMut<u32> for Fifo {
72     fn index_mut(&mut self, idx: u32) -> &mut Self::Output {
73         &mut self.0[idx as usize]
74     }
75 }
76 
77 impl std::ops::Index<u32> for Fifo {
78     type Output = registers::Data;
79 
80     fn index(&self, idx: u32) -> &Self::Output {
81         &self.0[idx as usize]
82     }
83 }
84 
85 #[repr(C)]
86 #[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]
87 /// PL011 Device Model in QEMU
88 pub struct PL011State {
89     pub parent_obj: SysBusDevice,
90     pub iomem: MemoryRegion,
91     #[doc(alias = "fr")]
92     pub flags: registers::Flags,
93     #[doc(alias = "lcr")]
94     pub line_control: registers::LineControl,
95     #[doc(alias = "rsr")]
96     pub receive_status_error_clear: registers::ReceiveStatusErrorClear,
97     #[doc(alias = "cr")]
98     pub control: registers::Control,
99     pub dmacr: u32,
100     pub int_enabled: u32,
101     pub int_level: u32,
102     pub read_fifo: Fifo,
103     pub ilpr: u32,
104     pub ibrd: u32,
105     pub fbrd: u32,
106     pub ifl: u32,
107     pub read_pos: u32,
108     pub read_count: u32,
109     pub read_trigger: u32,
110     #[doc(alias = "chr")]
111     pub char_backend: CharBackend,
112     /// QEMU interrupts
113     ///
114     /// ```text
115     ///  * sysbus MMIO region 0: device registers
116     ///  * sysbus IRQ 0: `UARTINTR` (combined interrupt line)
117     ///  * sysbus IRQ 1: `UARTRXINTR` (receive FIFO interrupt line)
118     ///  * sysbus IRQ 2: `UARTTXINTR` (transmit FIFO interrupt line)
119     ///  * sysbus IRQ 3: `UARTRTINTR` (receive timeout interrupt line)
120     ///  * sysbus IRQ 4: `UARTMSINTR` (momem status interrupt line)
121     ///  * sysbus IRQ 5: `UARTEINTR` (error interrupt line)
122     /// ```
123     #[doc(alias = "irq")]
124     pub interrupts: [InterruptSource; IRQMASK.len()],
125     #[doc(alias = "clk")]
126     pub clock: NonNull<Clock>,
127     #[doc(alias = "migrate_clk")]
128     pub migrate_clock: bool,
129     /// The byte string that identifies the device.
130     device_id: DeviceId,
131 }
132 
133 qom_isa!(PL011State : SysBusDevice, DeviceState, Object);
134 
135 unsafe impl ObjectType for PL011State {
136     type Class = <SysBusDevice as ObjectType>::Class;
137     const TYPE_NAME: &'static CStr = crate::TYPE_PL011;
138 }
139 
140 impl ObjectImpl for PL011State {
141     type ParentType = SysBusDevice;
142 
143     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
144 }
145 
146 impl DeviceImpl for PL011State {
147     fn properties() -> &'static [Property] {
148         &device_class::PL011_PROPERTIES
149     }
150     fn vmsd() -> Option<&'static VMStateDescription> {
151         Some(&device_class::VMSTATE_PL011)
152     }
153     const REALIZE: Option<fn(&mut Self)> = Some(Self::realize);
154     const RESET: Option<fn(&mut Self)> = Some(Self::reset);
155 }
156 
157 impl PL011State {
158     /// Initializes a pre-allocated, unitialized instance of `PL011State`.
159     ///
160     /// # Safety
161     ///
162     /// `self` must point to a correctly sized and aligned location for the
163     /// `PL011State` type. It must not be called more than once on the same
164     /// location/instance. All its fields are expected to hold unitialized
165     /// values with the sole exception of `parent_obj`.
166     unsafe fn init(&mut self) {
167         const CLK_NAME: &CStr = c_str!("clk");
168 
169         // SAFETY:
170         //
171         // self and self.iomem are guaranteed to be valid at this point since callers
172         // must make sure the `self` reference is valid.
173         unsafe {
174             memory_region_init_io(
175                 addr_of_mut!(self.iomem),
176                 addr_of_mut!(*self).cast::<Object>(),
177                 &PL011_OPS,
178                 addr_of_mut!(*self).cast::<c_void>(),
179                 Self::TYPE_NAME.as_ptr(),
180                 0x1000,
181             );
182 
183             let sbd: &mut SysBusDevice = self.upcast_mut();
184             sysbus_init_mmio(sbd, addr_of_mut!(self.iomem));
185         }
186 
187         for irq in self.interrupts.iter() {
188             let sbd: &SysBusDevice = self.upcast();
189             sbd.init_irq(irq);
190         }
191 
192         // SAFETY:
193         //
194         // self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
195         // we can overwrite the undefined value without side effects. This is
196         // safe since all PL011State instances are created by QOM code which
197         // calls this function to initialize the fields; therefore no code is
198         // able to access an invalid self.clock value.
199         unsafe {
200             let dev: &mut DeviceState = self.upcast_mut();
201             self.clock = NonNull::new(qdev_init_clock_in(
202                 dev,
203                 CLK_NAME.as_ptr(),
204                 None, /* pl011_clock_update */
205                 addr_of_mut!(*self).cast::<c_void>(),
206                 ClockEvent::ClockUpdate.0,
207             ))
208             .unwrap();
209         }
210     }
211 
212     pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u64, u64> {
213         use RegisterOffset::*;
214 
215         let value = match RegisterOffset::try_from(offset) {
216             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
217                 u32::from(self.device_id[(offset - 0xfe0) >> 2])
218             }
219             Err(_) => {
220                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
221                 0
222             }
223             Ok(DR) => {
224                 self.flags.set_receive_fifo_full(false);
225                 let c = self.read_fifo[self.read_pos];
226                 if self.read_count > 0 {
227                     self.read_count -= 1;
228                     self.read_pos = (self.read_pos + 1) & (self.fifo_depth() - 1);
229                 }
230                 if self.read_count == 0 {
231                     self.flags.set_receive_fifo_empty(true);
232                 }
233                 if self.read_count + 1 == self.read_trigger {
234                     self.int_level &= !registers::INT_RX;
235                 }
236                 // Update error bits.
237                 self.receive_status_error_clear.set_from_data(c);
238                 self.update();
239                 // Must call qemu_chr_fe_accept_input, so return Continue:
240                 let c = u32::from(c);
241                 return std::ops::ControlFlow::Continue(u64::from(c));
242             }
243             Ok(RSR) => u32::from(self.receive_status_error_clear),
244             Ok(FR) => u32::from(self.flags),
245             Ok(FBRD) => self.fbrd,
246             Ok(ILPR) => self.ilpr,
247             Ok(IBRD) => self.ibrd,
248             Ok(LCR_H) => u32::from(self.line_control),
249             Ok(CR) => u32::from(self.control),
250             Ok(FLS) => self.ifl,
251             Ok(IMSC) => self.int_enabled,
252             Ok(RIS) => self.int_level,
253             Ok(MIS) => self.int_level & self.int_enabled,
254             Ok(ICR) => {
255                 // "The UARTICR Register is the interrupt clear register and is write-only"
256                 // Source: ARM DDI 0183G 3.3.13 Interrupt Clear Register, UARTICR
257                 0
258             }
259             Ok(DMACR) => self.dmacr,
260         };
261         std::ops::ControlFlow::Break(value.into())
262     }
263 
264     pub fn write(&mut self, offset: hwaddr, value: u64) {
265         // eprintln!("write offset {offset} value {value}");
266         use RegisterOffset::*;
267         let value: u32 = value as u32;
268         match RegisterOffset::try_from(offset) {
269             Err(_bad_offset) => {
270                 eprintln!("write bad offset {offset} value {value}");
271             }
272             Ok(DR) => {
273                 // ??? Check if transmitter is enabled.
274                 let ch: u8 = value as u8;
275                 // XXX this blocks entire thread. Rewrite to use
276                 // qemu_chr_fe_write and background I/O callbacks
277 
278                 // SAFETY: self.char_backend is a valid CharBackend instance after it's been
279                 // initialized in realize().
280                 unsafe {
281                     qemu_chr_fe_write_all(addr_of_mut!(self.char_backend), &ch, 1);
282                 }
283                 self.loopback_tx(value);
284                 self.int_level |= registers::INT_TX;
285                 self.update();
286             }
287             Ok(RSR) => {
288                 self.receive_status_error_clear.reset();
289             }
290             Ok(FR) => {
291                 // flag writes are ignored
292             }
293             Ok(ILPR) => {
294                 self.ilpr = value;
295             }
296             Ok(IBRD) => {
297                 self.ibrd = value;
298             }
299             Ok(FBRD) => {
300                 self.fbrd = value;
301             }
302             Ok(LCR_H) => {
303                 let new_val: registers::LineControl = value.into();
304                 // Reset the FIFO state on FIFO enable or disable
305                 if bool::from(self.line_control.fifos_enabled())
306                     ^ bool::from(new_val.fifos_enabled())
307                 {
308                     self.reset_rx_fifo();
309                     self.reset_tx_fifo();
310                 }
311                 if self.line_control.send_break() ^ new_val.send_break() {
312                     let mut break_enable: c_int = new_val.send_break().into();
313                     // SAFETY: self.char_backend is a valid CharBackend instance after it's been
314                     // initialized in realize().
315                     unsafe {
316                         qemu_chr_fe_ioctl(
317                             addr_of_mut!(self.char_backend),
318                             CHR_IOCTL_SERIAL_SET_BREAK as i32,
319                             addr_of_mut!(break_enable).cast::<c_void>(),
320                         );
321                     }
322                     self.loopback_break(break_enable > 0);
323                 }
324                 self.line_control = new_val;
325                 self.set_read_trigger();
326             }
327             Ok(CR) => {
328                 // ??? Need to implement the enable bit.
329                 self.control = value.into();
330                 self.loopback_mdmctrl();
331             }
332             Ok(FLS) => {
333                 self.ifl = value;
334                 self.set_read_trigger();
335             }
336             Ok(IMSC) => {
337                 self.int_enabled = value;
338                 self.update();
339             }
340             Ok(RIS) => {}
341             Ok(MIS) => {}
342             Ok(ICR) => {
343                 self.int_level &= !value;
344                 self.update();
345             }
346             Ok(DMACR) => {
347                 self.dmacr = value;
348                 if value & 3 > 0 {
349                     // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n");
350                     eprintln!("pl011: DMA not implemented");
351                 }
352             }
353         }
354     }
355 
356     #[inline]
357     fn loopback_tx(&mut self, value: u32) {
358         if !self.loopback_enabled() {
359             return;
360         }
361 
362         // Caveat:
363         //
364         // In real hardware, TX loopback happens at the serial-bit level
365         // and then reassembled by the RX logics back into bytes and placed
366         // into the RX fifo. That is, loopback happens after TX fifo.
367         //
368         // Because the real hardware TX fifo is time-drained at the frame
369         // rate governed by the configured serial format, some loopback
370         // bytes in TX fifo may still be able to get into the RX fifo
371         // that could be full at times while being drained at software
372         // pace.
373         //
374         // In such scenario, the RX draining pace is the major factor
375         // deciding which loopback bytes get into the RX fifo, unless
376         // hardware flow-control is enabled.
377         //
378         // For simplicity, the above described is not emulated.
379         self.put_fifo(value);
380     }
381 
382     fn loopback_mdmctrl(&mut self) {
383         if !self.loopback_enabled() {
384             return;
385         }
386 
387         /*
388          * Loopback software-driven modem control outputs to modem status inputs:
389          *   FR.RI  <= CR.Out2
390          *   FR.DCD <= CR.Out1
391          *   FR.CTS <= CR.RTS
392          *   FR.DSR <= CR.DTR
393          *
394          * The loopback happens immediately even if this call is triggered
395          * by setting only CR.LBE.
396          *
397          * CTS/RTS updates due to enabled hardware flow controls are not
398          * dealt with here.
399          */
400 
401         self.flags.set_ring_indicator(self.control.out_2());
402         self.flags.set_data_carrier_detect(self.control.out_1());
403         self.flags.set_clear_to_send(self.control.request_to_send());
404         self.flags
405             .set_data_set_ready(self.control.data_transmit_ready());
406 
407         // Change interrupts based on updated FR
408         let mut il = self.int_level;
409 
410         il &= !Interrupt::MS;
411 
412         if self.flags.data_set_ready() {
413             il |= Interrupt::DSR as u32;
414         }
415         if self.flags.data_carrier_detect() {
416             il |= Interrupt::DCD as u32;
417         }
418         if self.flags.clear_to_send() {
419             il |= Interrupt::CTS as u32;
420         }
421         if self.flags.ring_indicator() {
422             il |= Interrupt::RI as u32;
423         }
424         self.int_level = il;
425         self.update();
426     }
427 
428     fn loopback_break(&mut self, enable: bool) {
429         if enable {
430             self.loopback_tx(registers::Data::BREAK.into());
431         }
432     }
433 
434     fn set_read_trigger(&mut self) {
435         self.read_trigger = 1;
436     }
437 
438     pub fn realize(&mut self) {
439         // SAFETY: self.char_backend has the correct size and alignment for a
440         // CharBackend object, and its callbacks are of the correct types.
441         unsafe {
442             qemu_chr_fe_set_handlers(
443                 addr_of_mut!(self.char_backend),
444                 Some(pl011_can_receive),
445                 Some(pl011_receive),
446                 Some(pl011_event),
447                 None,
448                 addr_of_mut!(*self).cast::<c_void>(),
449                 core::ptr::null_mut(),
450                 true,
451             );
452         }
453     }
454 
455     pub fn reset(&mut self) {
456         self.line_control.reset();
457         self.receive_status_error_clear.reset();
458         self.dmacr = 0;
459         self.int_enabled = 0;
460         self.int_level = 0;
461         self.ilpr = 0;
462         self.ibrd = 0;
463         self.fbrd = 0;
464         self.read_trigger = 1;
465         self.ifl = 0x12;
466         self.control.reset();
467         self.flags.reset();
468         self.reset_rx_fifo();
469         self.reset_tx_fifo();
470     }
471 
472     pub fn reset_rx_fifo(&mut self) {
473         self.read_count = 0;
474         self.read_pos = 0;
475 
476         // Reset FIFO flags
477         self.flags.set_receive_fifo_full(false);
478         self.flags.set_receive_fifo_empty(true);
479     }
480 
481     pub fn reset_tx_fifo(&mut self) {
482         // Reset FIFO flags
483         self.flags.set_transmit_fifo_full(false);
484         self.flags.set_transmit_fifo_empty(true);
485     }
486 
487     pub fn can_receive(&self) -> bool {
488         // trace_pl011_can_receive(s->lcr, s->read_count, r);
489         self.read_count < self.fifo_depth()
490     }
491 
492     pub fn event(&mut self, event: QEMUChrEvent) {
493         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
494             self.put_fifo(registers::Data::BREAK.into());
495         }
496     }
497 
498     #[inline]
499     pub fn fifo_enabled(&self) -> bool {
500         matches!(self.line_control.fifos_enabled(), registers::Mode::FIFO)
501     }
502 
503     #[inline]
504     pub fn loopback_enabled(&self) -> bool {
505         self.control.enable_loopback()
506     }
507 
508     #[inline]
509     pub fn fifo_depth(&self) -> u32 {
510         // Note: FIFO depth is expected to be power-of-2
511         if self.fifo_enabled() {
512             return PL011_FIFO_DEPTH;
513         }
514         1
515     }
516 
517     pub fn put_fifo(&mut self, value: c_uint) {
518         let depth = self.fifo_depth();
519         assert!(depth > 0);
520         let slot = (self.read_pos + self.read_count) & (depth - 1);
521         self.read_fifo[slot] = registers::Data::from(value);
522         self.read_count += 1;
523         self.flags.set_receive_fifo_empty(false);
524         if self.read_count == depth {
525             self.flags.set_receive_fifo_full(true);
526         }
527 
528         if self.read_count == self.read_trigger {
529             self.int_level |= registers::INT_RX;
530             self.update();
531         }
532     }
533 
534     pub fn update(&self) {
535         let flags = self.int_level & self.int_enabled;
536         for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
537             irq.set(flags & i != 0);
538         }
539     }
540 
541     pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
542         /* Sanity-check input state */
543         if self.read_pos >= self.read_fifo.len() || self.read_count > self.read_fifo.len() {
544             return Err(());
545         }
546 
547         if !self.fifo_enabled() && self.read_count > 0 && self.read_pos > 0 {
548             // Older versions of PL011 didn't ensure that the single
549             // character in the FIFO in FIFO-disabled mode is in
550             // element 0 of the array; convert to follow the current
551             // code's assumptions.
552             self.read_fifo[0] = self.read_fifo[self.read_pos];
553             self.read_pos = 0;
554         }
555 
556         self.ibrd &= IBRD_MASK;
557         self.fbrd &= FBRD_MASK;
558 
559         Ok(())
560     }
561 }
562 
563 /// Which bits in the interrupt status matter for each outbound IRQ line ?
564 pub const IRQMASK: [u32; 6] = [
565     /* combined IRQ */
566     Interrupt::E
567         | Interrupt::MS
568         | Interrupt::RT as u32
569         | Interrupt::TX as u32
570         | Interrupt::RX as u32,
571     Interrupt::RX as u32,
572     Interrupt::TX as u32,
573     Interrupt::RT as u32,
574     Interrupt::MS,
575     Interrupt::E,
576 ];
577 
578 /// # Safety
579 ///
580 /// We expect the FFI user of this function to pass a valid pointer, that has
581 /// the same size as [`PL011State`]. We also expect the device is
582 /// readable/writeable from one thread at any time.
583 pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int {
584     unsafe {
585         debug_assert!(!opaque.is_null());
586         let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
587         state.as_ref().can_receive().into()
588     }
589 }
590 
591 /// # Safety
592 ///
593 /// We expect the FFI user of this function to pass a valid pointer, that has
594 /// the same size as [`PL011State`]. We also expect the device is
595 /// readable/writeable from one thread at any time.
596 ///
597 /// The buffer and size arguments must also be valid.
598 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) {
599     unsafe {
600         debug_assert!(!opaque.is_null());
601         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
602         if state.as_ref().loopback_enabled() {
603             return;
604         }
605         if size > 0 {
606             debug_assert!(!buf.is_null());
607             state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))
608         }
609     }
610 }
611 
612 /// # Safety
613 ///
614 /// We expect the FFI user of this function to pass a valid pointer, that has
615 /// the same size as [`PL011State`]. We also expect the device is
616 /// readable/writeable from one thread at any time.
617 pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) {
618     unsafe {
619         debug_assert!(!opaque.is_null());
620         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
621         state.as_mut().event(event)
622     }
623 }
624 
625 /// # Safety
626 ///
627 /// We expect the FFI user of this function to pass a valid pointer for `chr`.
628 #[no_mangle]
629 pub unsafe extern "C" fn pl011_create(
630     addr: u64,
631     irq: qemu_irq,
632     chr: *mut Chardev,
633 ) -> *mut DeviceState {
634     unsafe {
635         let dev: *mut DeviceState = qdev_new(PL011State::TYPE_NAME.as_ptr());
636         let sysbus: *mut SysBusDevice = dev.cast::<SysBusDevice>();
637 
638         qdev_prop_set_chr(dev, c_str!("chardev").as_ptr(), chr);
639         sysbus_realize_and_unref(sysbus, addr_of_mut!(error_fatal));
640         sysbus_mmio_map(sysbus, 0, addr);
641         sysbus_connect_irq(sysbus, 0, irq);
642         dev
643     }
644 }
645 
646 #[repr(C)]
647 #[derive(Debug, qemu_api_macros::Object)]
648 /// PL011 Luminary device model.
649 pub struct PL011Luminary {
650     parent_obj: PL011State,
651 }
652 
653 impl PL011Luminary {
654     /// Initializes a pre-allocated, unitialized instance of `PL011Luminary`.
655     ///
656     /// # Safety
657     ///
658     /// We expect the FFI user of this function to pass a valid pointer, that
659     /// has the same size as [`PL011Luminary`]. We also expect the device is
660     /// readable/writeable from one thread at any time.
661     unsafe fn init(&mut self) {
662         self.parent_obj.device_id = DeviceId::Luminary;
663     }
664 }
665 
666 qom_isa!(PL011Luminary : PL011State, SysBusDevice, DeviceState, Object);
667 
668 unsafe impl ObjectType for PL011Luminary {
669     type Class = <PL011State as ObjectType>::Class;
670     const TYPE_NAME: &'static CStr = crate::TYPE_PL011_LUMINARY;
671 }
672 
673 impl ObjectImpl for PL011Luminary {
674     type ParentType = PL011State;
675 
676     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
677 }
678 
679 impl DeviceImpl for PL011Luminary {}
680