1 // Copyright 2024 Red Hat, Inc. 2 // Author(s): Paolo Bonzini <pbonzini@redhat.com> 3 // SPDX-License-Identifier: GPL-2.0-or-later 4 5 use std::{ffi::CStr, ptr::addr_of_mut}; 6 7 pub use bindings::{SysBusDevice, SysBusDeviceClass}; 8 9 use crate::{ 10 bindings, 11 cell::bql_locked, 12 irq::{IRQState, InterruptSource}, 13 memory::MemoryRegion, 14 prelude::*, 15 qdev::{DeviceClass, DeviceState}, 16 qom::{ClassInitImpl, Owned}, 17 }; 18 19 unsafe impl ObjectType for SysBusDevice { 20 type Class = SysBusDeviceClass; 21 const TYPE_NAME: &'static CStr = 22 unsafe { CStr::from_bytes_with_nul_unchecked(bindings::TYPE_SYS_BUS_DEVICE) }; 23 } 24 qom_isa!(SysBusDevice: DeviceState, Object); 25 26 // TODO: add SysBusDeviceImpl 27 impl<T> ClassInitImpl<SysBusDeviceClass> for T 28 where 29 T: ClassInitImpl<DeviceClass>, 30 { 31 fn class_init(sdc: &mut SysBusDeviceClass) { 32 <T as ClassInitImpl<DeviceClass>>::class_init(&mut sdc.parent_class); 33 } 34 } 35 36 /// Trait for methods of [`SysBusDevice`] and its subclasses. 37 pub trait SysBusDeviceMethods: ObjectDeref 38 where 39 Self::Target: IsA<SysBusDevice>, 40 { 41 /// Expose a memory region to the board so that it can give it an address 42 /// in guest memory. Note that the ordering of calls to `init_mmio` is 43 /// important, since whoever creates the sysbus device will refer to the 44 /// region with a number that corresponds to the order of calls to 45 /// `init_mmio`. 46 fn init_mmio(&self, iomem: &MemoryRegion) { 47 assert!(bql_locked()); 48 unsafe { 49 bindings::sysbus_init_mmio(self.as_mut_ptr(), iomem.as_mut_ptr()); 50 } 51 } 52 53 /// Expose an interrupt source outside the device as a qdev GPIO output. 54 /// Note that the ordering of calls to `init_irq` is important, since 55 /// whoever creates the sysbus device will refer to the interrupts with 56 /// a number that corresponds to the order of calls to `init_irq`. 57 fn init_irq(&self, irq: &InterruptSource) { 58 assert!(bql_locked()); 59 unsafe { 60 bindings::sysbus_init_irq(self.as_mut_ptr(), irq.as_ptr()); 61 } 62 } 63 64 // TODO: do we want a type like GuestAddress here? 65 fn mmio_map(&self, id: u32, addr: u64) { 66 assert!(bql_locked()); 67 let id: i32 = id.try_into().unwrap(); 68 unsafe { 69 bindings::sysbus_mmio_map(self.as_mut_ptr(), id, addr); 70 } 71 } 72 73 // Owned<> is used here because sysbus_connect_irq (via 74 // object_property_set_link) adds a reference to the IRQState, 75 // which can prolong its life 76 fn connect_irq(&self, id: u32, irq: &Owned<IRQState>) { 77 assert!(bql_locked()); 78 let id: i32 = id.try_into().unwrap(); 79 unsafe { 80 bindings::sysbus_connect_irq(self.as_mut_ptr(), id, irq.as_mut_ptr()); 81 } 82 } 83 84 fn sysbus_realize(&self) { 85 // TODO: return an Error 86 assert!(bql_locked()); 87 unsafe { 88 bindings::sysbus_realize(self.as_mut_ptr(), addr_of_mut!(bindings::error_fatal)); 89 } 90 } 91 } 92 93 impl<R: ObjectDeref> SysBusDeviceMethods for R where R::Target: IsA<SysBusDevice> {} 94