We give QOM objects a reference count. This means that if you are going to try to use one, you can take a ref to it, and then you're guaranteed that it won't disappear while you're working with it.
For QDEV devices, we add the "realize" and "unrealize" steps to the lifecycle. There is no "reference count for having a realized device". So what do we intend here? (1) We could say that if you have a reference to the device then you can assume it's not going to be unrealized under your feet, and have very careful rules about who can unrealize a device and when. (2) We could say that if you have a reference to the device then it might be unrealized, but it won't be deinitialized, and you can assume that all the API calls you might make on it will in some sense still work, and at any rate at least won't try to access memory that's been freed or crash. In fact we don't say either of those. What we have instead is: (a) Some devices will free memory in unrealize, so aren't safe to make calls on after unrealize (b) Some code will call qdev_unrealize() on a device even if it has a ton of references on it and is likely still in use by unrelated code. The specific example here is the problem described in https://gitlab.com/qemu-project/qemu/-/work_items/4854 where if something writes to the PCI hot-unplug memory mapped register then the PCIe code will immediately call pcie_cap_slot_unplug_cb(), which calls qdev_unrealize on the PCI device. For PCI devices, pci_config_free() gets called in the PCI base class unrealize, which means that all the PCI functions which look at e.g. pci_dev->config are now instantly not valid to call (the one that gets called in this example is pci_set_irq()). So if you can get a PCI device to do DMA to its own hot-unplug register then it's probably going to fall over. Should the PCIe hot-unplug code be more cautious about when it actually unrealizes the device being hot-unplugged? Or should the PCI base class code be being careful to make sure that all its functions continue to work right up until the device is deinited? (Or both, or something else?) My fix for #4854, now on-list at: https://lore.kernel.org/qemu-devel/[email protected]/ is "make sure this particular device can't do DMA to non-memory", but I feel like this is pointing to an entire class of bugs where the underlying problem is "hot-unplug can make things vanish under your feet". We already put a bandaid on the hcd-xhci USB controller in commit 89e653b773 and the lsi53c895a in commit 4862d2c95104d, and no doubt there are more... thanks -- PMM
