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