xref: /qemu/hw/core/qdev-hotplug.c (revision 1bff035be76cc30ff0fc4e8f0b0fbda84db7d1dc)
1 /*
2  * QDev Hotplug handlers
3  *
4  * Copyright (c) Red Hat
5  *
6  * SPDX-License-Identifier: GPL-2.0-or-later
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "hw/qdev-core.h"
14 #include "hw/boards.h"
15 #include "qapi/error.h"
16 
17 HotplugHandler *qdev_get_machine_hotplug_handler(DeviceState *dev)
18 {
19     MachineState *machine;
20     MachineClass *mc;
21     Object *m_obj = qdev_get_machine();
22 
23     if (object_dynamic_cast(m_obj, TYPE_MACHINE)) {
24         machine = MACHINE(m_obj);
25         mc = MACHINE_GET_CLASS(machine);
26         if (mc->get_hotplug_handler) {
27             return mc->get_hotplug_handler(machine, dev);
28         }
29     }
30 
31     return NULL;
32 }
33 
34 static bool qdev_hotplug_unplug_allowed_common(DeviceState *dev, BusState *bus,
35                                                Error **errp)
36 {
37     DeviceClass *dc = DEVICE_GET_CLASS(dev);
38 
39     if (!dc->hotpluggable) {
40         error_setg(errp, "Device '%s' does not support hotplugging",
41                    object_get_typename(OBJECT(dev)));
42         return false;
43     }
44 
45     return true;
46 }
47 
48 bool qdev_hotplug_allowed(DeviceState *dev, BusState *bus, Error **errp)
49 {
50     MachineState *machine;
51     MachineClass *mc;
52     Object *m_obj = qdev_get_machine();
53 
54     if (!qdev_hotplug_unplug_allowed_common(dev, bus, errp)) {
55         return false;
56     }
57 
58     if (object_dynamic_cast(m_obj, TYPE_MACHINE)) {
59         machine = MACHINE(m_obj);
60         mc = MACHINE_GET_CLASS(machine);
61         if (mc->hotplug_allowed) {
62             return mc->hotplug_allowed(machine, dev, errp);
63         }
64     }
65 
66     return true;
67 }
68 
69 bool qdev_hotunplug_allowed(DeviceState *dev, Error **errp)
70 {
71     return !qdev_unplug_blocked(dev, errp) &&
72            qdev_hotplug_unplug_allowed_common(dev, dev->parent_bus, errp);
73 }
74 
75 HotplugHandler *qdev_get_bus_hotplug_handler(DeviceState *dev)
76 {
77     if (dev->parent_bus) {
78         return dev->parent_bus->hotplug_handler;
79     }
80     return NULL;
81 }
82 
83 HotplugHandler *qdev_get_hotplug_handler(DeviceState *dev)
84 {
85     HotplugHandler *hotplug_ctrl = qdev_get_machine_hotplug_handler(dev);
86 
87     if (hotplug_ctrl == NULL && dev->parent_bus) {
88         hotplug_ctrl = qdev_get_bus_hotplug_handler(dev);
89     }
90     return hotplug_ctrl;
91 }
92 
93 /* can be used as ->unplug() callback for the simple cases */
94 void qdev_simple_device_unplug_cb(HotplugHandler *hotplug_dev,
95                                   DeviceState *dev, Error **errp)
96 {
97     qdev_unrealize(dev);
98 }
99