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