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