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