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