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