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