xref: /qemu/rust/hw/char/pl011/src/device.rs (revision 897c68fb795cf03b89b6688a6f945d68a765c3e4)
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 => {
194                 self.flags.set_receive_fifo_full(false);
195                 let c = self.read_fifo[self.read_pos];
196                 if self.read_count > 0 {
197                     self.read_count -= 1;
198                     self.read_pos = (self.read_pos + 1) & (self.fifo_depth() - 1);
199                 }
200                 if self.read_count == 0 {
201                     self.flags.set_receive_fifo_empty(true);
202                 }
203                 if self.read_count + 1 == self.read_trigger {
204                     self.int_level &= !Interrupt::RX.0;
205                 }
206                 // Update error bits.
207                 self.receive_status_error_clear.set_from_data(c);
208                 // Must call qemu_chr_fe_accept_input
209                 update = true;
210                 u32::from(c)
211             }
212             RSR => u32::from(self.receive_status_error_clear),
213             FR => u32::from(self.flags),
214             FBRD => self.fbrd,
215             ILPR => self.ilpr,
216             IBRD => self.ibrd,
217             LCR_H => u32::from(self.line_control),
218             CR => u32::from(self.control),
219             FLS => self.ifl,
220             IMSC => self.int_enabled,
221             RIS => self.int_level,
222             MIS => self.int_level & self.int_enabled,
223             ICR => {
224                 // "The UARTICR Register is the interrupt clear register and is write-only"
225                 // Source: ARM DDI 0183G 3.3.13 Interrupt Clear Register, UARTICR
226                 0
227             }
228             DMACR => self.dmacr,
229         };
230         (update, result)
231     }
232 
233     pub(self) fn write(
234         &mut self,
235         offset: RegisterOffset,
236         value: u32,
237         char_backend: &CharBackend,
238     ) -> bool {
239         // eprintln!("write offset {offset} value {value}");
240         use RegisterOffset::*;
241         match offset {
242             DR => {
243                 // interrupts always checked
244                 let _ = self.loopback_tx(value.into());
245                 self.int_level |= Interrupt::TX.0;
246                 return true;
247             }
248             RSR => {
249                 self.receive_status_error_clear = 0.into();
250             }
251             FR => {
252                 // flag writes are ignored
253             }
254             ILPR => {
255                 self.ilpr = value;
256             }
257             IBRD => {
258                 self.ibrd = value;
259             }
260             FBRD => {
261                 self.fbrd = value;
262             }
263             LCR_H => {
264                 let new_val: registers::LineControl = value.into();
265                 // Reset the FIFO state on FIFO enable or disable
266                 if self.line_control.fifos_enabled() != new_val.fifos_enabled() {
267                     self.reset_rx_fifo();
268                     self.reset_tx_fifo();
269                 }
270                 let update = (self.line_control.send_break() != new_val.send_break()) && {
271                     let break_enable = new_val.send_break();
272                     let _ = char_backend.send_break(break_enable);
273                     self.loopback_break(break_enable)
274                 };
275                 self.line_control = new_val;
276                 self.set_read_trigger();
277                 return update;
278             }
279             CR => {
280                 // ??? Need to implement the enable bit.
281                 self.control = value.into();
282                 return self.loopback_mdmctrl();
283             }
284             FLS => {
285                 self.ifl = value;
286                 self.set_read_trigger();
287             }
288             IMSC => {
289                 self.int_enabled = value;
290                 return true;
291             }
292             RIS => {}
293             MIS => {}
294             ICR => {
295                 self.int_level &= !value;
296                 return true;
297             }
298             DMACR => {
299                 self.dmacr = value;
300                 if value & 3 > 0 {
301                     // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n");
302                     eprintln!("pl011: DMA not implemented");
303                 }
304             }
305         }
306         false
307     }
308 
309     #[inline]
310     #[must_use]
311     fn loopback_tx(&mut self, value: registers::Data) -> bool {
312         // Caveat:
313         //
314         // In real hardware, TX loopback happens at the serial-bit level
315         // and then reassembled by the RX logics back into bytes and placed
316         // into the RX fifo. That is, loopback happens after TX fifo.
317         //
318         // Because the real hardware TX fifo is time-drained at the frame
319         // rate governed by the configured serial format, some loopback
320         // bytes in TX fifo may still be able to get into the RX fifo
321         // that could be full at times while being drained at software
322         // pace.
323         //
324         // In such scenario, the RX draining pace is the major factor
325         // deciding which loopback bytes get into the RX fifo, unless
326         // hardware flow-control is enabled.
327         //
328         // For simplicity, the above described is not emulated.
329         self.loopback_enabled() && self.put_fifo(value)
330     }
331 
332     #[must_use]
333     fn loopback_mdmctrl(&mut self) -> bool {
334         if !self.loopback_enabled() {
335             return false;
336         }
337 
338         /*
339          * Loopback software-driven modem control outputs to modem status inputs:
340          *   FR.RI  <= CR.Out2
341          *   FR.DCD <= CR.Out1
342          *   FR.CTS <= CR.RTS
343          *   FR.DSR <= CR.DTR
344          *
345          * The loopback happens immediately even if this call is triggered
346          * by setting only CR.LBE.
347          *
348          * CTS/RTS updates due to enabled hardware flow controls are not
349          * dealt with here.
350          */
351 
352         self.flags.set_ring_indicator(self.control.out_2());
353         self.flags.set_data_carrier_detect(self.control.out_1());
354         self.flags.set_clear_to_send(self.control.request_to_send());
355         self.flags
356             .set_data_set_ready(self.control.data_transmit_ready());
357 
358         // Change interrupts based on updated FR
359         let mut il = self.int_level;
360 
361         il &= !Interrupt::MS.0;
362 
363         if self.flags.data_set_ready() {
364             il |= Interrupt::DSR.0;
365         }
366         if self.flags.data_carrier_detect() {
367             il |= Interrupt::DCD.0;
368         }
369         if self.flags.clear_to_send() {
370             il |= Interrupt::CTS.0;
371         }
372         if self.flags.ring_indicator() {
373             il |= Interrupt::RI.0;
374         }
375         self.int_level = il;
376         true
377     }
378 
379     fn loopback_break(&mut self, enable: bool) -> bool {
380         enable && self.loopback_tx(registers::Data::BREAK)
381     }
382 
383     fn set_read_trigger(&mut self) {
384         self.read_trigger = 1;
385     }
386 
387     pub fn reset(&mut self) {
388         self.line_control.reset();
389         self.receive_status_error_clear.reset();
390         self.dmacr = 0;
391         self.int_enabled = 0;
392         self.int_level = 0;
393         self.ilpr = 0;
394         self.ibrd = 0;
395         self.fbrd = 0;
396         self.read_trigger = 1;
397         self.ifl = 0x12;
398         self.control.reset();
399         self.flags.reset();
400         self.reset_rx_fifo();
401         self.reset_tx_fifo();
402     }
403 
404     pub fn reset_rx_fifo(&mut self) {
405         self.read_count = 0;
406         self.read_pos = 0;
407 
408         // Reset FIFO flags
409         self.flags.set_receive_fifo_full(false);
410         self.flags.set_receive_fifo_empty(true);
411     }
412 
413     pub fn reset_tx_fifo(&mut self) {
414         // Reset FIFO flags
415         self.flags.set_transmit_fifo_full(false);
416         self.flags.set_transmit_fifo_empty(true);
417     }
418 
419     #[inline]
420     pub fn fifo_enabled(&self) -> bool {
421         self.line_control.fifos_enabled() == registers::Mode::FIFO
422     }
423 
424     #[inline]
425     pub fn loopback_enabled(&self) -> bool {
426         self.control.enable_loopback()
427     }
428 
429     #[inline]
430     pub fn fifo_depth(&self) -> u32 {
431         // Note: FIFO depth is expected to be power-of-2
432         if self.fifo_enabled() {
433             return PL011_FIFO_DEPTH;
434         }
435         1
436     }
437 
438     #[must_use]
439     pub fn put_fifo(&mut self, value: registers::Data) -> bool {
440         let depth = self.fifo_depth();
441         assert!(depth > 0);
442         let slot = (self.read_pos + self.read_count) & (depth - 1);
443         self.read_fifo[slot] = value;
444         self.read_count += 1;
445         self.flags.set_receive_fifo_empty(false);
446         if self.read_count == depth {
447             self.flags.set_receive_fifo_full(true);
448         }
449 
450         if self.read_count == self.read_trigger {
451             self.int_level |= Interrupt::RX.0;
452             return true;
453         }
454         false
455     }
456 
457     pub fn post_load(&mut self) -> Result<(), ()> {
458         /* Sanity-check input state */
459         if self.read_pos >= self.read_fifo.len() || self.read_count > self.read_fifo.len() {
460             return Err(());
461         }
462 
463         if !self.fifo_enabled() && self.read_count > 0 && self.read_pos > 0 {
464             // Older versions of PL011 didn't ensure that the single
465             // character in the FIFO in FIFO-disabled mode is in
466             // element 0 of the array; convert to follow the current
467             // code's assumptions.
468             self.read_fifo[0] = self.read_fifo[self.read_pos];
469             self.read_pos = 0;
470         }
471 
472         self.ibrd &= IBRD_MASK;
473         self.fbrd &= FBRD_MASK;
474 
475         Ok(())
476     }
477 }
478 
479 impl PL011State {
480     /// Initializes a pre-allocated, unitialized instance of `PL011State`.
481     ///
482     /// # Safety
483     ///
484     /// `self` must point to a correctly sized and aligned location for the
485     /// `PL011State` type. It must not be called more than once on the same
486     /// location/instance. All its fields are expected to hold unitialized
487     /// values with the sole exception of `parent_obj`.
488     unsafe fn init(&mut self) {
489         static PL011_OPS: MemoryRegionOps<PL011State> = MemoryRegionOpsBuilder::<PL011State>::new()
490             .read(&PL011State::read)
491             .write(&PL011State::write)
492             .native_endian()
493             .impl_sizes(4, 4)
494             .build();
495 
496         // SAFETY:
497         //
498         // self and self.iomem are guaranteed to be valid at this point since callers
499         // must make sure the `self` reference is valid.
500         MemoryRegion::init_io(
501             unsafe { &mut *addr_of_mut!(self.iomem) },
502             addr_of_mut!(*self),
503             &PL011_OPS,
504             "pl011",
505             0x1000,
506         );
507 
508         self.regs = Default::default();
509 
510         // SAFETY:
511         //
512         // self.clock is not initialized at this point; but since `Owned<_>` is
513         // not Drop, we can overwrite the undefined value without side effects;
514         // it's not sound but, because for all PL011State instances are created
515         // by QOM code which calls this function to initialize the fields, at
516         // leastno code is able to access an invalid self.clock value.
517         self.clock = self.init_clock_in("clk", &Self::clock_update, ClockEvent::ClockUpdate);
518     }
519 
520     const fn clock_update(&self, _event: ClockEvent) {
521         /* pl011_trace_baudrate_change(s); */
522     }
523 
524     fn post_init(&self) {
525         self.init_mmio(&self.iomem);
526         for irq in self.interrupts.iter() {
527             self.init_irq(irq);
528         }
529     }
530 
531     fn read(&self, offset: hwaddr, _size: u32) -> u64 {
532         match RegisterOffset::try_from(offset) {
533             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
534                 let device_id = self.get_class().device_id;
535                 u64::from(device_id[(offset - 0xfe0) >> 2])
536             }
537             Err(_) => {
538                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
539                 0
540             }
541             Ok(field) => {
542                 let (update_irq, result) = self.regs.borrow_mut().read(field);
543                 if update_irq {
544                     self.update();
545                     self.char_backend.accept_input();
546                 }
547                 result.into()
548             }
549         }
550     }
551 
552     fn write(&self, offset: hwaddr, value: u64, _size: u32) {
553         let mut update_irq = false;
554         if let Ok(field) = RegisterOffset::try_from(offset) {
555             // qemu_chr_fe_write_all() calls into the can_receive
556             // callback, so handle writes before entering PL011Registers.
557             if field == RegisterOffset::DR {
558                 // ??? Check if transmitter is enabled.
559                 let ch: [u8; 1] = [value as u8];
560                 // XXX this blocks entire thread. Rewrite to use
561                 // qemu_chr_fe_write and background I/O callbacks
562                 let _ = self.char_backend.write_all(&ch);
563             }
564 
565             update_irq = self
566                 .regs
567                 .borrow_mut()
568                 .write(field, value as u32, &self.char_backend);
569         } else {
570             eprintln!("write bad offset {offset} value {value}");
571         }
572         if update_irq {
573             self.update();
574         }
575     }
576 
577     fn can_receive(&self) -> u32 {
578         let regs = self.regs.borrow();
579         // trace_pl011_can_receive(s->lcr, s->read_count, r);
580         u32::from(regs.read_count < regs.fifo_depth())
581     }
582 
583     fn receive(&self, buf: &[u8]) {
584         if buf.is_empty() {
585             return;
586         }
587         let mut regs = self.regs.borrow_mut();
588         let c: u32 = buf[0].into();
589         let update_irq = !regs.loopback_enabled() && regs.put_fifo(c.into());
590         // Release the BqlRefCell before calling self.update()
591         drop(regs);
592 
593         if update_irq {
594             self.update();
595         }
596     }
597 
598     fn event(&self, event: Event) {
599         let mut update_irq = false;
600         let mut regs = self.regs.borrow_mut();
601         if event == Event::CHR_EVENT_BREAK && !regs.loopback_enabled() {
602             update_irq = regs.put_fifo(registers::Data::BREAK);
603         }
604         // Release the BqlRefCell before calling self.update()
605         drop(regs);
606 
607         if update_irq {
608             self.update()
609         }
610     }
611 
612     fn realize(&self) {
613         self.char_backend
614             .enable_handlers(self, Self::can_receive, Self::receive, Self::event);
615     }
616 
617     fn reset_hold(&self, _type: ResetType) {
618         self.regs.borrow_mut().reset();
619     }
620 
621     fn update(&self) {
622         let regs = self.regs.borrow();
623         let flags = regs.int_level & regs.int_enabled;
624         for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
625             irq.set(flags & i != 0);
626         }
627     }
628 
629     pub fn post_load(&self, _version_id: u32) -> Result<(), ()> {
630         self.regs.borrow_mut().post_load()
631     }
632 }
633 
634 /// Which bits in the interrupt status matter for each outbound IRQ line ?
635 const IRQMASK: [u32; 6] = [
636     /* combined IRQ */
637     Interrupt::E.0 | Interrupt::MS.0 | Interrupt::RT.0 | Interrupt::TX.0 | Interrupt::RX.0,
638     Interrupt::RX.0,
639     Interrupt::TX.0,
640     Interrupt::RT.0,
641     Interrupt::MS.0,
642     Interrupt::E.0,
643 ];
644 
645 /// # Safety
646 ///
647 /// We expect the FFI user of this function to pass a valid pointer for `chr`
648 /// and `irq`.
649 #[no_mangle]
650 pub unsafe extern "C" fn pl011_create(
651     addr: u64,
652     irq: *mut IRQState,
653     chr: *mut Chardev,
654 ) -> *mut DeviceState {
655     // SAFETY: The callers promise that they have owned references.
656     // They do not gift them to pl011_create, so use `Owned::from`.
657     let irq = unsafe { Owned::<IRQState>::from(&*irq) };
658 
659     let dev = PL011State::new();
660     if !chr.is_null() {
661         let chr = unsafe { Owned::<Chardev>::from(&*chr) };
662         dev.prop_set_chr("chardev", &chr);
663     }
664     dev.sysbus_realize();
665     dev.mmio_map(0, addr);
666     dev.connect_irq(0, &irq);
667 
668     // The pointer is kept alive by the QOM tree; drop the owned ref
669     dev.as_mut_ptr()
670 }
671 
672 #[repr(C)]
673 #[derive(qemu_api_macros::Object)]
674 /// PL011 Luminary device model.
675 pub struct PL011Luminary {
676     parent_obj: ParentField<PL011State>,
677 }
678 
679 qom_isa!(PL011Luminary : PL011State, SysBusDevice, DeviceState, Object);
680 
681 unsafe impl ObjectType for PL011Luminary {
682     type Class = <PL011State as ObjectType>::Class;
683     const TYPE_NAME: &'static CStr = crate::TYPE_PL011_LUMINARY;
684 }
685 
686 impl ObjectImpl for PL011Luminary {
687     type ParentType = PL011State;
688 
689     const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::<Self>;
690 }
691 
692 impl PL011Impl for PL011Luminary {
693     const DEVICE_ID: DeviceId = DeviceId(&[0x11, 0x00, 0x18, 0x01, 0x0d, 0xf0, 0x05, 0xb1]);
694 }
695 
696 impl DeviceImpl for PL011Luminary {}
697 impl ResettablePhasesImpl for PL011Luminary {}
698 impl SysBusDeviceImpl for PL011Luminary {}
699