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