xref: /qemu/rust/hw/char/pl011/src/device.rs (revision e4a8e093dc74be049f4829831dce76e5edab0003)
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 self.line_control.fifos_enabled() != new_val.fifos_enabled() {
306                     self.reset_rx_fifo();
307                     self.reset_tx_fifo();
308                 }
309                 if self.line_control.send_break() ^ new_val.send_break() {
310                     let mut break_enable: c_int = new_val.send_break().into();
311                     // SAFETY: self.char_backend is a valid CharBackend instance after it's been
312                     // initialized in realize().
313                     unsafe {
314                         qemu_chr_fe_ioctl(
315                             addr_of_mut!(self.char_backend),
316                             CHR_IOCTL_SERIAL_SET_BREAK as i32,
317                             addr_of_mut!(break_enable).cast::<c_void>(),
318                         );
319                     }
320                     self.loopback_break(break_enable > 0);
321                 }
322                 self.line_control = new_val;
323                 self.set_read_trigger();
324             }
325             Ok(CR) => {
326                 // ??? Need to implement the enable bit.
327                 self.control = value.into();
328                 self.loopback_mdmctrl();
329             }
330             Ok(FLS) => {
331                 self.ifl = value;
332                 self.set_read_trigger();
333             }
334             Ok(IMSC) => {
335                 self.int_enabled = value;
336                 self.update();
337             }
338             Ok(RIS) => {}
339             Ok(MIS) => {}
340             Ok(ICR) => {
341                 self.int_level &= !value;
342                 self.update();
343             }
344             Ok(DMACR) => {
345                 self.dmacr = value;
346                 if value & 3 > 0 {
347                     // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n");
348                     eprintln!("pl011: DMA not implemented");
349                 }
350             }
351         }
352     }
353 
354     #[inline]
355     fn loopback_tx(&mut self, value: u32) {
356         if !self.loopback_enabled() {
357             return;
358         }
359 
360         // Caveat:
361         //
362         // In real hardware, TX loopback happens at the serial-bit level
363         // and then reassembled by the RX logics back into bytes and placed
364         // into the RX fifo. That is, loopback happens after TX fifo.
365         //
366         // Because the real hardware TX fifo is time-drained at the frame
367         // rate governed by the configured serial format, some loopback
368         // bytes in TX fifo may still be able to get into the RX fifo
369         // that could be full at times while being drained at software
370         // pace.
371         //
372         // In such scenario, the RX draining pace is the major factor
373         // deciding which loopback bytes get into the RX fifo, unless
374         // hardware flow-control is enabled.
375         //
376         // For simplicity, the above described is not emulated.
377         self.put_fifo(value);
378     }
379 
380     fn loopback_mdmctrl(&mut self) {
381         if !self.loopback_enabled() {
382             return;
383         }
384 
385         /*
386          * Loopback software-driven modem control outputs to modem status inputs:
387          *   FR.RI  <= CR.Out2
388          *   FR.DCD <= CR.Out1
389          *   FR.CTS <= CR.RTS
390          *   FR.DSR <= CR.DTR
391          *
392          * The loopback happens immediately even if this call is triggered
393          * by setting only CR.LBE.
394          *
395          * CTS/RTS updates due to enabled hardware flow controls are not
396          * dealt with here.
397          */
398 
399         self.flags.set_ring_indicator(self.control.out_2());
400         self.flags.set_data_carrier_detect(self.control.out_1());
401         self.flags.set_clear_to_send(self.control.request_to_send());
402         self.flags
403             .set_data_set_ready(self.control.data_transmit_ready());
404 
405         // Change interrupts based on updated FR
406         let mut il = self.int_level;
407 
408         il &= !Interrupt::MS;
409 
410         if self.flags.data_set_ready() {
411             il |= Interrupt::DSR as u32;
412         }
413         if self.flags.data_carrier_detect() {
414             il |= Interrupt::DCD as u32;
415         }
416         if self.flags.clear_to_send() {
417             il |= Interrupt::CTS as u32;
418         }
419         if self.flags.ring_indicator() {
420             il |= Interrupt::RI as u32;
421         }
422         self.int_level = il;
423         self.update();
424     }
425 
426     fn loopback_break(&mut self, enable: bool) {
427         if enable {
428             self.loopback_tx(registers::Data::BREAK.into());
429         }
430     }
431 
432     fn set_read_trigger(&mut self) {
433         self.read_trigger = 1;
434     }
435 
436     pub fn realize(&mut self) {
437         // SAFETY: self.char_backend has the correct size and alignment for a
438         // CharBackend object, and its callbacks are of the correct types.
439         unsafe {
440             qemu_chr_fe_set_handlers(
441                 addr_of_mut!(self.char_backend),
442                 Some(pl011_can_receive),
443                 Some(pl011_receive),
444                 Some(pl011_event),
445                 None,
446                 addr_of_mut!(*self).cast::<c_void>(),
447                 core::ptr::null_mut(),
448                 true,
449             );
450         }
451     }
452 
453     pub fn reset(&mut self) {
454         self.line_control.reset();
455         self.receive_status_error_clear.reset();
456         self.dmacr = 0;
457         self.int_enabled = 0;
458         self.int_level = 0;
459         self.ilpr = 0;
460         self.ibrd = 0;
461         self.fbrd = 0;
462         self.read_trigger = 1;
463         self.ifl = 0x12;
464         self.control.reset();
465         self.flags.reset();
466         self.reset_rx_fifo();
467         self.reset_tx_fifo();
468     }
469 
470     pub fn reset_rx_fifo(&mut self) {
471         self.read_count = 0;
472         self.read_pos = 0;
473 
474         // Reset FIFO flags
475         self.flags.set_receive_fifo_full(false);
476         self.flags.set_receive_fifo_empty(true);
477     }
478 
479     pub fn reset_tx_fifo(&mut self) {
480         // Reset FIFO flags
481         self.flags.set_transmit_fifo_full(false);
482         self.flags.set_transmit_fifo_empty(true);
483     }
484 
485     pub fn can_receive(&self) -> bool {
486         // trace_pl011_can_receive(s->lcr, s->read_count, r);
487         self.read_count < self.fifo_depth()
488     }
489 
490     pub fn event(&mut self, event: QEMUChrEvent) {
491         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
492             self.put_fifo(registers::Data::BREAK.into());
493         }
494     }
495 
496     #[inline]
497     pub fn fifo_enabled(&self) -> bool {
498         self.line_control.fifos_enabled() == registers::Mode::FIFO
499     }
500 
501     #[inline]
502     pub fn loopback_enabled(&self) -> bool {
503         self.control.enable_loopback()
504     }
505 
506     #[inline]
507     pub fn fifo_depth(&self) -> u32 {
508         // Note: FIFO depth is expected to be power-of-2
509         if self.fifo_enabled() {
510             return PL011_FIFO_DEPTH;
511         }
512         1
513     }
514 
515     pub fn put_fifo(&mut self, value: c_uint) {
516         let depth = self.fifo_depth();
517         assert!(depth > 0);
518         let slot = (self.read_pos + self.read_count) & (depth - 1);
519         self.read_fifo[slot] = registers::Data::from(value);
520         self.read_count += 1;
521         self.flags.set_receive_fifo_empty(false);
522         if self.read_count == depth {
523             self.flags.set_receive_fifo_full(true);
524         }
525 
526         if self.read_count == self.read_trigger {
527             self.int_level |= registers::INT_RX;
528             self.update();
529         }
530     }
531 
532     pub fn update(&self) {
533         let flags = self.int_level & self.int_enabled;
534         for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
535             irq.set(flags & i != 0);
536         }
537     }
538 
539     pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
540         /* Sanity-check input state */
541         if self.read_pos >= self.read_fifo.len() || self.read_count > self.read_fifo.len() {
542             return Err(());
543         }
544 
545         if !self.fifo_enabled() && self.read_count > 0 && self.read_pos > 0 {
546             // Older versions of PL011 didn't ensure that the single
547             // character in the FIFO in FIFO-disabled mode is in
548             // element 0 of the array; convert to follow the current
549             // code's assumptions.
550             self.read_fifo[0] = self.read_fifo[self.read_pos];
551             self.read_pos = 0;
552         }
553 
554         self.ibrd &= IBRD_MASK;
555         self.fbrd &= FBRD_MASK;
556 
557         Ok(())
558     }
559 }
560 
561 /// Which bits in the interrupt status matter for each outbound IRQ line ?
562 pub const IRQMASK: [u32; 6] = [
563     /* combined IRQ */
564     Interrupt::E
565         | Interrupt::MS
566         | Interrupt::RT as u32
567         | Interrupt::TX as u32
568         | Interrupt::RX as u32,
569     Interrupt::RX as u32,
570     Interrupt::TX as u32,
571     Interrupt::RT as u32,
572     Interrupt::MS,
573     Interrupt::E,
574 ];
575 
576 /// # Safety
577 ///
578 /// We expect the FFI user of this function to pass a valid pointer, that has
579 /// the same size as [`PL011State`]. We also expect the device is
580 /// readable/writeable from one thread at any time.
581 pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int {
582     unsafe {
583         debug_assert!(!opaque.is_null());
584         let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
585         state.as_ref().can_receive().into()
586     }
587 }
588 
589 /// # Safety
590 ///
591 /// We expect the FFI user of this function to pass a valid pointer, that has
592 /// the same size as [`PL011State`]. We also expect the device is
593 /// readable/writeable from one thread at any time.
594 ///
595 /// The buffer and size arguments must also be valid.
596 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) {
597     unsafe {
598         debug_assert!(!opaque.is_null());
599         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
600         if state.as_ref().loopback_enabled() {
601             return;
602         }
603         if size > 0 {
604             debug_assert!(!buf.is_null());
605             state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))
606         }
607     }
608 }
609 
610 /// # Safety
611 ///
612 /// We expect the FFI user of this function to pass a valid pointer, that has
613 /// the same size as [`PL011State`]. We also expect the device is
614 /// readable/writeable from one thread at any time.
615 pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) {
616     unsafe {
617         debug_assert!(!opaque.is_null());
618         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
619         state.as_mut().event(event)
620     }
621 }
622 
623 /// # Safety
624 ///
625 /// We expect the FFI user of this function to pass a valid pointer for `chr`.
626 #[no_mangle]
627 pub unsafe extern "C" fn pl011_create(
628     addr: u64,
629     irq: qemu_irq,
630     chr: *mut Chardev,
631 ) -> *mut DeviceState {
632     unsafe {
633         let dev: *mut DeviceState = qdev_new(PL011State::TYPE_NAME.as_ptr());
634         let sysbus: *mut SysBusDevice = dev.cast::<SysBusDevice>();
635 
636         qdev_prop_set_chr(dev, c_str!("chardev").as_ptr(), chr);
637         sysbus_realize_and_unref(sysbus, addr_of_mut!(error_fatal));
638         sysbus_mmio_map(sysbus, 0, addr);
639         sysbus_connect_irq(sysbus, 0, irq);
640         dev
641     }
642 }
643 
644 #[repr(C)]
645 #[derive(Debug, qemu_api_macros::Object)]
646 /// PL011 Luminary device model.
647 pub struct PL011Luminary {
648     parent_obj: PL011State,
649 }
650 
651 impl PL011Luminary {
652     /// Initializes a pre-allocated, unitialized instance of `PL011Luminary`.
653     ///
654     /// # Safety
655     ///
656     /// We expect the FFI user of this function to pass a valid pointer, that
657     /// has the same size as [`PL011Luminary`]. We also expect the device is
658     /// readable/writeable from one thread at any time.
659     unsafe fn init(&mut self) {
660         self.parent_obj.device_id = DeviceId::Luminary;
661     }
662 }
663 
664 qom_isa!(PL011Luminary : PL011State, SysBusDevice, DeviceState, Object);
665 
666 unsafe impl ObjectType for PL011Luminary {
667     type Class = <PL011State as ObjectType>::Class;
668     const TYPE_NAME: &'static CStr = crate::TYPE_PL011_LUMINARY;
669 }
670 
671 impl ObjectImpl for PL011Luminary {
672     type ParentType = PL011State;
673 
674     const INSTANCE_INIT: Option<unsafe fn(&mut Self)> = Some(Self::init);
675 }
676 
677 impl DeviceImpl for PL011Luminary {}
678