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