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