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