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