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