xref: /openbmc/qemu/hw/core/qdev.c (revision cac720ec)
1 /*
2  *  Dynamic device configuration and creation.
3  *
4  *  Copyright (c) 2009 CodeSourcery
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 /* The theory here is that it should be possible to create a machine without
21    knowledge of specific devices.  Historically board init routines have
22    passed a bunch of arguments to each device, requiring the board know
23    exactly which device it is dealing with.  This file provides an abstract
24    API for device configuration and initialization.  Devices will generally
25    inherit from a particular bus (e.g. PCI or I2C) rather than
26    this API directly.  */
27 
28 #include "qemu/osdep.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-events-qdev.h"
31 #include "qapi/qmp/qdict.h"
32 #include "qapi/qmp/qerror.h"
33 #include "qapi/visitor.h"
34 #include "qemu/error-report.h"
35 #include "qemu/option.h"
36 #include "hw/hotplug.h"
37 #include "hw/irq.h"
38 #include "hw/qdev-properties.h"
39 #include "hw/boards.h"
40 #include "hw/sysbus.h"
41 #include "hw/qdev-clock.h"
42 #include "migration/vmstate.h"
43 #include "trace.h"
44 
45 static bool qdev_hot_added = false;
46 bool qdev_hot_removed = false;
47 
48 const VMStateDescription *qdev_get_vmsd(DeviceState *dev)
49 {
50     DeviceClass *dc = DEVICE_GET_CLASS(dev);
51     return dc->vmsd;
52 }
53 
54 static void bus_free_bus_child(BusChild *kid)
55 {
56     object_unref(OBJECT(kid->child));
57     g_free(kid);
58 }
59 
60 static void bus_remove_child(BusState *bus, DeviceState *child)
61 {
62     BusChild *kid;
63 
64     QTAILQ_FOREACH(kid, &bus->children, sibling) {
65         if (kid->child == child) {
66             char name[32];
67 
68             snprintf(name, sizeof(name), "child[%d]", kid->index);
69             QTAILQ_REMOVE_RCU(&bus->children, kid, sibling);
70 
71             bus->num_children--;
72 
73             /* This gives back ownership of kid->child back to us.  */
74             object_property_del(OBJECT(bus), name);
75 
76             /* free the bus kid, when it is safe to do so*/
77             call_rcu(kid, bus_free_bus_child, rcu);
78             break;
79         }
80     }
81 }
82 
83 static void bus_add_child(BusState *bus, DeviceState *child)
84 {
85     char name[32];
86     BusChild *kid = g_malloc0(sizeof(*kid));
87 
88     bus->num_children++;
89     kid->index = bus->max_index++;
90     kid->child = child;
91     object_ref(OBJECT(kid->child));
92 
93     QTAILQ_INSERT_HEAD_RCU(&bus->children, kid, sibling);
94 
95     /* This transfers ownership of kid->child to the property.  */
96     snprintf(name, sizeof(name), "child[%d]", kid->index);
97     object_property_add_link(OBJECT(bus), name,
98                              object_get_typename(OBJECT(child)),
99                              (Object **)&kid->child,
100                              NULL, /* read-only property */
101                              0);
102 }
103 
104 static bool bus_check_address(BusState *bus, DeviceState *child, Error **errp)
105 {
106     BusClass *bc = BUS_GET_CLASS(bus);
107     return !bc->check_address || bc->check_address(bus, child, errp);
108 }
109 
110 bool qdev_set_parent_bus(DeviceState *dev, BusState *bus, Error **errp)
111 {
112     BusState *old_parent_bus = dev->parent_bus;
113     DeviceClass *dc = DEVICE_GET_CLASS(dev);
114 
115     assert(dc->bus_type && object_dynamic_cast(OBJECT(bus), dc->bus_type));
116 
117     if (!bus_check_address(bus, dev, errp)) {
118         return false;
119     }
120 
121     if (old_parent_bus) {
122         trace_qdev_update_parent_bus(dev, object_get_typename(OBJECT(dev)),
123             old_parent_bus, object_get_typename(OBJECT(old_parent_bus)),
124             OBJECT(bus), object_get_typename(OBJECT(bus)));
125         /*
126          * Keep a reference to the device while it's not plugged into
127          * any bus, to avoid it potentially evaporating when it is
128          * dereffed in bus_remove_child().
129          * Also keep the ref of the parent bus until the end, so that
130          * we can safely call resettable_change_parent() below.
131          */
132         object_ref(OBJECT(dev));
133         bus_remove_child(dev->parent_bus, dev);
134     }
135     dev->parent_bus = bus;
136     object_ref(OBJECT(bus));
137     bus_add_child(bus, dev);
138     if (dev->realized) {
139         resettable_change_parent(OBJECT(dev), OBJECT(bus),
140                                  OBJECT(old_parent_bus));
141     }
142     if (old_parent_bus) {
143         object_unref(OBJECT(old_parent_bus));
144         object_unref(OBJECT(dev));
145     }
146     return true;
147 }
148 
149 DeviceState *qdev_new(const char *name)
150 {
151     if (!object_class_by_name(name)) {
152         module_load_qom_one(name);
153     }
154     return DEVICE(object_new(name));
155 }
156 
157 DeviceState *qdev_try_new(const char *name)
158 {
159     if (!module_object_class_by_name(name)) {
160         return NULL;
161     }
162     return DEVICE(object_new(name));
163 }
164 
165 static QTAILQ_HEAD(, DeviceListener) device_listeners
166     = QTAILQ_HEAD_INITIALIZER(device_listeners);
167 
168 enum ListenerDirection { Forward, Reverse };
169 
170 #define DEVICE_LISTENER_CALL(_callback, _direction, _args...)     \
171     do {                                                          \
172         DeviceListener *_listener;                                \
173                                                                   \
174         switch (_direction) {                                     \
175         case Forward:                                             \
176             QTAILQ_FOREACH(_listener, &device_listeners, link) {  \
177                 if (_listener->_callback) {                       \
178                     _listener->_callback(_listener, ##_args);     \
179                 }                                                 \
180             }                                                     \
181             break;                                                \
182         case Reverse:                                             \
183             QTAILQ_FOREACH_REVERSE(_listener, &device_listeners,  \
184                                    link) {                        \
185                 if (_listener->_callback) {                       \
186                     _listener->_callback(_listener, ##_args);     \
187                 }                                                 \
188             }                                                     \
189             break;                                                \
190         default:                                                  \
191             abort();                                              \
192         }                                                         \
193     } while (0)
194 
195 static int device_listener_add(DeviceState *dev, void *opaque)
196 {
197     DEVICE_LISTENER_CALL(realize, Forward, dev);
198 
199     return 0;
200 }
201 
202 void device_listener_register(DeviceListener *listener)
203 {
204     QTAILQ_INSERT_TAIL(&device_listeners, listener, link);
205 
206     qbus_walk_children(sysbus_get_default(), NULL, NULL, device_listener_add,
207                        NULL, NULL);
208 }
209 
210 void device_listener_unregister(DeviceListener *listener)
211 {
212     QTAILQ_REMOVE(&device_listeners, listener, link);
213 }
214 
215 bool qdev_should_hide_device(const QDict *opts, bool from_json, Error **errp)
216 {
217     ERRP_GUARD();
218     DeviceListener *listener;
219 
220     QTAILQ_FOREACH(listener, &device_listeners, link) {
221         if (listener->hide_device) {
222             if (listener->hide_device(listener, opts, from_json, errp)) {
223                 return true;
224             } else if (*errp) {
225                 return false;
226             }
227         }
228     }
229 
230     return false;
231 }
232 
233 void qdev_set_legacy_instance_id(DeviceState *dev, int alias_id,
234                                  int required_for_version)
235 {
236     assert(!dev->realized);
237     dev->instance_id_alias = alias_id;
238     dev->alias_required_for_version = required_for_version;
239 }
240 
241 HotplugHandler *qdev_get_machine_hotplug_handler(DeviceState *dev)
242 {
243     MachineState *machine;
244     MachineClass *mc;
245     Object *m_obj = qdev_get_machine();
246 
247     if (object_dynamic_cast(m_obj, TYPE_MACHINE)) {
248         machine = MACHINE(m_obj);
249         mc = MACHINE_GET_CLASS(machine);
250         if (mc->get_hotplug_handler) {
251             return mc->get_hotplug_handler(machine, dev);
252         }
253     }
254 
255     return NULL;
256 }
257 
258 bool qdev_hotplug_allowed(DeviceState *dev, Error **errp)
259 {
260     MachineState *machine;
261     MachineClass *mc;
262     Object *m_obj = qdev_get_machine();
263 
264     if (object_dynamic_cast(m_obj, TYPE_MACHINE)) {
265         machine = MACHINE(m_obj);
266         mc = MACHINE_GET_CLASS(machine);
267         if (mc->hotplug_allowed) {
268             return mc->hotplug_allowed(machine, dev, errp);
269         }
270     }
271 
272     return true;
273 }
274 
275 HotplugHandler *qdev_get_bus_hotplug_handler(DeviceState *dev)
276 {
277     if (dev->parent_bus) {
278         return dev->parent_bus->hotplug_handler;
279     }
280     return NULL;
281 }
282 
283 HotplugHandler *qdev_get_hotplug_handler(DeviceState *dev)
284 {
285     HotplugHandler *hotplug_ctrl = qdev_get_machine_hotplug_handler(dev);
286 
287     if (hotplug_ctrl == NULL && dev->parent_bus) {
288         hotplug_ctrl = qdev_get_bus_hotplug_handler(dev);
289     }
290     return hotplug_ctrl;
291 }
292 
293 static int qdev_prereset(DeviceState *dev, void *opaque)
294 {
295     trace_qdev_reset_tree(dev, object_get_typename(OBJECT(dev)));
296     return 0;
297 }
298 
299 static int qbus_prereset(BusState *bus, void *opaque)
300 {
301     trace_qbus_reset_tree(bus, object_get_typename(OBJECT(bus)));
302     return 0;
303 }
304 
305 static int qdev_reset_one(DeviceState *dev, void *opaque)
306 {
307     device_legacy_reset(dev);
308 
309     return 0;
310 }
311 
312 static int qbus_reset_one(BusState *bus, void *opaque)
313 {
314     BusClass *bc = BUS_GET_CLASS(bus);
315     trace_qbus_reset(bus, object_get_typename(OBJECT(bus)));
316     if (bc->reset) {
317         bc->reset(bus);
318     }
319     return 0;
320 }
321 
322 void qdev_reset_all(DeviceState *dev)
323 {
324     trace_qdev_reset_all(dev, object_get_typename(OBJECT(dev)));
325     qdev_walk_children(dev, qdev_prereset, qbus_prereset,
326                        qdev_reset_one, qbus_reset_one, NULL);
327 }
328 
329 void qdev_reset_all_fn(void *opaque)
330 {
331     qdev_reset_all(DEVICE(opaque));
332 }
333 
334 void qbus_reset_all(BusState *bus)
335 {
336     trace_qbus_reset_all(bus, object_get_typename(OBJECT(bus)));
337     qbus_walk_children(bus, qdev_prereset, qbus_prereset,
338                        qdev_reset_one, qbus_reset_one, NULL);
339 }
340 
341 void qbus_reset_all_fn(void *opaque)
342 {
343     BusState *bus = opaque;
344     qbus_reset_all(bus);
345 }
346 
347 void device_cold_reset(DeviceState *dev)
348 {
349     resettable_reset(OBJECT(dev), RESET_TYPE_COLD);
350 }
351 
352 bool device_is_in_reset(DeviceState *dev)
353 {
354     return resettable_is_in_reset(OBJECT(dev));
355 }
356 
357 static ResettableState *device_get_reset_state(Object *obj)
358 {
359     DeviceState *dev = DEVICE(obj);
360     return &dev->reset;
361 }
362 
363 static void device_reset_child_foreach(Object *obj, ResettableChildCallback cb,
364                                        void *opaque, ResetType type)
365 {
366     DeviceState *dev = DEVICE(obj);
367     BusState *bus;
368 
369     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
370         cb(OBJECT(bus), opaque, type);
371     }
372 }
373 
374 /* can be used as ->unplug() callback for the simple cases */
375 void qdev_simple_device_unplug_cb(HotplugHandler *hotplug_dev,
376                                   DeviceState *dev, Error **errp)
377 {
378     qdev_unrealize(dev);
379 }
380 
381 bool qdev_realize(DeviceState *dev, BusState *bus, Error **errp)
382 {
383     assert(!dev->realized && !dev->parent_bus);
384 
385     if (bus) {
386         if (!qdev_set_parent_bus(dev, bus, errp)) {
387             return false;
388         }
389     } else {
390         assert(!DEVICE_GET_CLASS(dev)->bus_type);
391     }
392 
393     return object_property_set_bool(OBJECT(dev), "realized", true, errp);
394 }
395 
396 bool qdev_realize_and_unref(DeviceState *dev, BusState *bus, Error **errp)
397 {
398     bool ret;
399 
400     ret = qdev_realize(dev, bus, errp);
401     object_unref(OBJECT(dev));
402     return ret;
403 }
404 
405 void qdev_unrealize(DeviceState *dev)
406 {
407     object_property_set_bool(OBJECT(dev), "realized", false, &error_abort);
408 }
409 
410 static int qdev_assert_realized_properly_cb(Object *obj, void *opaque)
411 {
412     DeviceState *dev = DEVICE(object_dynamic_cast(obj, TYPE_DEVICE));
413     DeviceClass *dc;
414 
415     if (dev) {
416         dc = DEVICE_GET_CLASS(dev);
417         assert(dev->realized);
418         assert(dev->parent_bus || !dc->bus_type);
419     }
420     return 0;
421 }
422 
423 void qdev_assert_realized_properly(void)
424 {
425     object_child_foreach_recursive(object_get_root(),
426                                    qdev_assert_realized_properly_cb, NULL);
427 }
428 
429 bool qdev_machine_modified(void)
430 {
431     return qdev_hot_added || qdev_hot_removed;
432 }
433 
434 BusState *qdev_get_parent_bus(DeviceState *dev)
435 {
436     return dev->parent_bus;
437 }
438 
439 static NamedGPIOList *qdev_get_named_gpio_list(DeviceState *dev,
440                                                const char *name)
441 {
442     NamedGPIOList *ngl;
443 
444     QLIST_FOREACH(ngl, &dev->gpios, node) {
445         /* NULL is a valid and matchable name. */
446         if (g_strcmp0(name, ngl->name) == 0) {
447             return ngl;
448         }
449     }
450 
451     ngl = g_malloc0(sizeof(*ngl));
452     ngl->name = g_strdup(name);
453     QLIST_INSERT_HEAD(&dev->gpios, ngl, node);
454     return ngl;
455 }
456 
457 void qdev_init_gpio_in_named_with_opaque(DeviceState *dev,
458                                          qemu_irq_handler handler,
459                                          void *opaque,
460                                          const char *name, int n)
461 {
462     int i;
463     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
464 
465     assert(gpio_list->num_out == 0 || !name);
466     gpio_list->in = qemu_extend_irqs(gpio_list->in, gpio_list->num_in, handler,
467                                      opaque, n);
468 
469     if (!name) {
470         name = "unnamed-gpio-in";
471     }
472     for (i = gpio_list->num_in; i < gpio_list->num_in + n; i++) {
473         gchar *propname = g_strdup_printf("%s[%u]", name, i);
474 
475         object_property_add_child(OBJECT(dev), propname,
476                                   OBJECT(gpio_list->in[i]));
477         g_free(propname);
478     }
479 
480     gpio_list->num_in += n;
481 }
482 
483 void qdev_init_gpio_in(DeviceState *dev, qemu_irq_handler handler, int n)
484 {
485     qdev_init_gpio_in_named(dev, handler, NULL, n);
486 }
487 
488 void qdev_init_gpio_out_named(DeviceState *dev, qemu_irq *pins,
489                               const char *name, int n)
490 {
491     int i;
492     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
493 
494     assert(gpio_list->num_in == 0 || !name);
495 
496     if (!name) {
497         name = "unnamed-gpio-out";
498     }
499     memset(pins, 0, sizeof(*pins) * n);
500     for (i = 0; i < n; ++i) {
501         gchar *propname = g_strdup_printf("%s[%u]", name,
502                                           gpio_list->num_out + i);
503 
504         object_property_add_link(OBJECT(dev), propname, TYPE_IRQ,
505                                  (Object **)&pins[i],
506                                  object_property_allow_set_link,
507                                  OBJ_PROP_LINK_STRONG);
508         g_free(propname);
509     }
510     gpio_list->num_out += n;
511 }
512 
513 void qdev_init_gpio_out(DeviceState *dev, qemu_irq *pins, int n)
514 {
515     qdev_init_gpio_out_named(dev, pins, NULL, n);
516 }
517 
518 qemu_irq qdev_get_gpio_in_named(DeviceState *dev, const char *name, int n)
519 {
520     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
521 
522     assert(n >= 0 && n < gpio_list->num_in);
523     return gpio_list->in[n];
524 }
525 
526 qemu_irq qdev_get_gpio_in(DeviceState *dev, int n)
527 {
528     return qdev_get_gpio_in_named(dev, NULL, n);
529 }
530 
531 void qdev_connect_gpio_out_named(DeviceState *dev, const char *name, int n,
532                                  qemu_irq pin)
533 {
534     char *propname = g_strdup_printf("%s[%d]",
535                                      name ? name : "unnamed-gpio-out", n);
536     if (pin && !OBJECT(pin)->parent) {
537         /* We need a name for object_property_set_link to work */
538         object_property_add_child(container_get(qdev_get_machine(),
539                                                 "/unattached"),
540                                   "non-qdev-gpio[*]", OBJECT(pin));
541     }
542     object_property_set_link(OBJECT(dev), propname, OBJECT(pin), &error_abort);
543     g_free(propname);
544 }
545 
546 qemu_irq qdev_get_gpio_out_connector(DeviceState *dev, const char *name, int n)
547 {
548     g_autofree char *propname = g_strdup_printf("%s[%d]",
549                                      name ? name : "unnamed-gpio-out", n);
550 
551     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
552                                                       NULL);
553 
554     return ret;
555 }
556 
557 /* disconnect a GPIO output, returning the disconnected input (if any) */
558 
559 static qemu_irq qdev_disconnect_gpio_out_named(DeviceState *dev,
560                                                const char *name, int n)
561 {
562     char *propname = g_strdup_printf("%s[%d]",
563                                      name ? name : "unnamed-gpio-out", n);
564 
565     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
566                                                       NULL);
567     if (ret) {
568         object_property_set_link(OBJECT(dev), propname, NULL, NULL);
569     }
570     g_free(propname);
571     return ret;
572 }
573 
574 qemu_irq qdev_intercept_gpio_out(DeviceState *dev, qemu_irq icpt,
575                                  const char *name, int n)
576 {
577     qemu_irq disconnected = qdev_disconnect_gpio_out_named(dev, name, n);
578     qdev_connect_gpio_out_named(dev, name, n, icpt);
579     return disconnected;
580 }
581 
582 void qdev_connect_gpio_out(DeviceState * dev, int n, qemu_irq pin)
583 {
584     qdev_connect_gpio_out_named(dev, NULL, n, pin);
585 }
586 
587 void qdev_pass_gpios(DeviceState *dev, DeviceState *container,
588                      const char *name)
589 {
590     int i;
591     NamedGPIOList *ngl = qdev_get_named_gpio_list(dev, name);
592 
593     for (i = 0; i < ngl->num_in; i++) {
594         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-in";
595         char *propname = g_strdup_printf("%s[%d]", nm, i);
596 
597         object_property_add_alias(OBJECT(container), propname,
598                                   OBJECT(dev), propname);
599         g_free(propname);
600     }
601     for (i = 0; i < ngl->num_out; i++) {
602         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-out";
603         char *propname = g_strdup_printf("%s[%d]", nm, i);
604 
605         object_property_add_alias(OBJECT(container), propname,
606                                   OBJECT(dev), propname);
607         g_free(propname);
608     }
609     QLIST_REMOVE(ngl, node);
610     QLIST_INSERT_HEAD(&container->gpios, ngl, node);
611 }
612 
613 BusState *qdev_get_child_bus(DeviceState *dev, const char *name)
614 {
615     BusState *bus;
616     Object *child = object_resolve_path_component(OBJECT(dev), name);
617 
618     bus = (BusState *)object_dynamic_cast(child, TYPE_BUS);
619     if (bus) {
620         return bus;
621     }
622 
623     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
624         if (strcmp(name, bus->name) == 0) {
625             return bus;
626         }
627     }
628     return NULL;
629 }
630 
631 int qdev_walk_children(DeviceState *dev,
632                        qdev_walkerfn *pre_devfn, qbus_walkerfn *pre_busfn,
633                        qdev_walkerfn *post_devfn, qbus_walkerfn *post_busfn,
634                        void *opaque)
635 {
636     BusState *bus;
637     int err;
638 
639     if (pre_devfn) {
640         err = pre_devfn(dev, opaque);
641         if (err) {
642             return err;
643         }
644     }
645 
646     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
647         err = qbus_walk_children(bus, pre_devfn, pre_busfn,
648                                  post_devfn, post_busfn, opaque);
649         if (err < 0) {
650             return err;
651         }
652     }
653 
654     if (post_devfn) {
655         err = post_devfn(dev, opaque);
656         if (err) {
657             return err;
658         }
659     }
660 
661     return 0;
662 }
663 
664 DeviceState *qdev_find_recursive(BusState *bus, const char *id)
665 {
666     BusChild *kid;
667     DeviceState *ret;
668     BusState *child;
669 
670     WITH_RCU_READ_LOCK_GUARD() {
671         QTAILQ_FOREACH_RCU(kid, &bus->children, sibling) {
672             DeviceState *dev = kid->child;
673 
674             if (dev->id && strcmp(dev->id, id) == 0) {
675                 return dev;
676             }
677 
678             QLIST_FOREACH(child, &dev->child_bus, sibling) {
679                 ret = qdev_find_recursive(child, id);
680                 if (ret) {
681                     return ret;
682                 }
683             }
684         }
685     }
686     return NULL;
687 }
688 
689 char *qdev_get_dev_path(DeviceState *dev)
690 {
691     BusClass *bc;
692 
693     if (!dev || !dev->parent_bus) {
694         return NULL;
695     }
696 
697     bc = BUS_GET_CLASS(dev->parent_bus);
698     if (bc->get_dev_path) {
699         return bc->get_dev_path(dev);
700     }
701 
702     return NULL;
703 }
704 
705 static bool device_get_realized(Object *obj, Error **errp)
706 {
707     DeviceState *dev = DEVICE(obj);
708     return dev->realized;
709 }
710 
711 static bool check_only_migratable(Object *obj, Error **errp)
712 {
713     DeviceClass *dc = DEVICE_GET_CLASS(obj);
714 
715     if (!vmstate_check_only_migratable(dc->vmsd)) {
716         error_setg(errp, "Device %s is not migratable, but "
717                    "--only-migratable was specified",
718                    object_get_typename(obj));
719         return false;
720     }
721 
722     return true;
723 }
724 
725 static void device_set_realized(Object *obj, bool value, Error **errp)
726 {
727     DeviceState *dev = DEVICE(obj);
728     DeviceClass *dc = DEVICE_GET_CLASS(dev);
729     HotplugHandler *hotplug_ctrl;
730     BusState *bus;
731     NamedClockList *ncl;
732     Error *local_err = NULL;
733     bool unattached_parent = false;
734     static int unattached_count;
735 
736     if (dev->hotplugged && !dc->hotpluggable) {
737         error_setg(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj));
738         return;
739     }
740 
741     if (value && !dev->realized) {
742         if (!check_only_migratable(obj, errp)) {
743             goto fail;
744         }
745 
746         if (!obj->parent) {
747             gchar *name = g_strdup_printf("device[%d]", unattached_count++);
748 
749             object_property_add_child(container_get(qdev_get_machine(),
750                                                     "/unattached"),
751                                       name, obj);
752             unattached_parent = true;
753             g_free(name);
754         }
755 
756         hotplug_ctrl = qdev_get_hotplug_handler(dev);
757         if (hotplug_ctrl) {
758             hotplug_handler_pre_plug(hotplug_ctrl, dev, &local_err);
759             if (local_err != NULL) {
760                 goto fail;
761             }
762         }
763 
764         if (dc->realize) {
765             dc->realize(dev, &local_err);
766             if (local_err != NULL) {
767                 goto fail;
768             }
769         }
770 
771         DEVICE_LISTENER_CALL(realize, Forward, dev);
772 
773         /*
774          * always free/re-initialize here since the value cannot be cleaned up
775          * in device_unrealize due to its usage later on in the unplug path
776          */
777         g_free(dev->canonical_path);
778         dev->canonical_path = object_get_canonical_path(OBJECT(dev));
779         QLIST_FOREACH(ncl, &dev->clocks, node) {
780             if (ncl->alias) {
781                 continue;
782             } else {
783                 clock_setup_canonical_path(ncl->clock);
784             }
785         }
786 
787         if (qdev_get_vmsd(dev)) {
788             if (vmstate_register_with_alias_id(VMSTATE_IF(dev),
789                                                VMSTATE_INSTANCE_ID_ANY,
790                                                qdev_get_vmsd(dev), dev,
791                                                dev->instance_id_alias,
792                                                dev->alias_required_for_version,
793                                                &local_err) < 0) {
794                 goto post_realize_fail;
795             }
796         }
797 
798         /*
799          * Clear the reset state, in case the object was previously unrealized
800          * with a dirty state.
801          */
802         resettable_state_clear(&dev->reset);
803 
804         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
805             if (!qbus_realize(bus, errp)) {
806                 goto child_realize_fail;
807             }
808         }
809         if (dev->hotplugged) {
810             /*
811              * Reset the device, as well as its subtree which, at this point,
812              * should be realized too.
813              */
814             resettable_assert_reset(OBJECT(dev), RESET_TYPE_COLD);
815             resettable_change_parent(OBJECT(dev), OBJECT(dev->parent_bus),
816                                      NULL);
817             resettable_release_reset(OBJECT(dev), RESET_TYPE_COLD);
818         }
819         dev->pending_deleted_event = false;
820 
821         if (hotplug_ctrl) {
822             hotplug_handler_plug(hotplug_ctrl, dev, &local_err);
823             if (local_err != NULL) {
824                 goto child_realize_fail;
825             }
826        }
827 
828        qatomic_store_release(&dev->realized, value);
829 
830     } else if (!value && dev->realized) {
831 
832         /*
833          * Change the value so that any concurrent users are aware
834          * that the device is going to be unrealized
835          *
836          * TODO: change .realized property to enum that states
837          * each phase of the device realization/unrealization
838          */
839 
840         qatomic_set(&dev->realized, value);
841         /*
842          * Ensure that concurrent users see this update prior to
843          * any other changes done by unrealize.
844          */
845         smp_wmb();
846 
847         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
848             qbus_unrealize(bus);
849         }
850         if (qdev_get_vmsd(dev)) {
851             vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
852         }
853         if (dc->unrealize) {
854             dc->unrealize(dev);
855         }
856         dev->pending_deleted_event = true;
857         DEVICE_LISTENER_CALL(unrealize, Reverse, dev);
858     }
859 
860     assert(local_err == NULL);
861     return;
862 
863 child_realize_fail:
864     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
865         qbus_unrealize(bus);
866     }
867 
868     if (qdev_get_vmsd(dev)) {
869         vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
870     }
871 
872 post_realize_fail:
873     g_free(dev->canonical_path);
874     dev->canonical_path = NULL;
875     if (dc->unrealize) {
876         dc->unrealize(dev);
877     }
878 
879 fail:
880     error_propagate(errp, local_err);
881     if (unattached_parent) {
882         /*
883          * Beware, this doesn't just revert
884          * object_property_add_child(), it also runs bus_remove()!
885          */
886         object_unparent(OBJECT(dev));
887         unattached_count--;
888     }
889 }
890 
891 static bool device_get_hotpluggable(Object *obj, Error **errp)
892 {
893     DeviceClass *dc = DEVICE_GET_CLASS(obj);
894     DeviceState *dev = DEVICE(obj);
895 
896     return dc->hotpluggable && (dev->parent_bus == NULL ||
897                                 qbus_is_hotpluggable(dev->parent_bus));
898 }
899 
900 static bool device_get_hotplugged(Object *obj, Error **errp)
901 {
902     DeviceState *dev = DEVICE(obj);
903 
904     return dev->hotplugged;
905 }
906 
907 static void device_initfn(Object *obj)
908 {
909     DeviceState *dev = DEVICE(obj);
910 
911     if (phase_check(PHASE_MACHINE_READY)) {
912         dev->hotplugged = 1;
913         qdev_hot_added = true;
914     }
915 
916     dev->instance_id_alias = -1;
917     dev->realized = false;
918     dev->allow_unplug_during_migration = false;
919 
920     QLIST_INIT(&dev->gpios);
921     QLIST_INIT(&dev->clocks);
922 }
923 
924 static void device_post_init(Object *obj)
925 {
926     /*
927      * Note: ordered so that the user's global properties take
928      * precedence.
929      */
930     object_apply_compat_props(obj);
931     qdev_prop_set_globals(DEVICE(obj));
932 }
933 
934 /* Unlink device from bus and free the structure.  */
935 static void device_finalize(Object *obj)
936 {
937     NamedGPIOList *ngl, *next;
938 
939     DeviceState *dev = DEVICE(obj);
940 
941     QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) {
942         QLIST_REMOVE(ngl, node);
943         qemu_free_irqs(ngl->in, ngl->num_in);
944         g_free(ngl->name);
945         g_free(ngl);
946         /* ngl->out irqs are owned by the other end and should not be freed
947          * here
948          */
949     }
950 
951     qdev_finalize_clocklist(dev);
952 
953     /* Only send event if the device had been completely realized */
954     if (dev->pending_deleted_event) {
955         g_assert(dev->canonical_path);
956 
957         qapi_event_send_device_deleted(!!dev->id, dev->id, dev->canonical_path);
958         g_free(dev->canonical_path);
959         dev->canonical_path = NULL;
960     }
961 
962     qobject_unref(dev->opts);
963     g_free(dev->id);
964 }
965 
966 static void device_class_base_init(ObjectClass *class, void *data)
967 {
968     DeviceClass *klass = DEVICE_CLASS(class);
969 
970     /* We explicitly look up properties in the superclasses,
971      * so do not propagate them to the subclasses.
972      */
973     klass->props_ = NULL;
974 }
975 
976 static void device_unparent(Object *obj)
977 {
978     DeviceState *dev = DEVICE(obj);
979     BusState *bus;
980 
981     if (dev->realized) {
982         qdev_unrealize(dev);
983     }
984     while (dev->num_child_bus) {
985         bus = QLIST_FIRST(&dev->child_bus);
986         object_unparent(OBJECT(bus));
987     }
988     if (dev->parent_bus) {
989         bus_remove_child(dev->parent_bus, dev);
990         object_unref(OBJECT(dev->parent_bus));
991         dev->parent_bus = NULL;
992     }
993 }
994 
995 static char *
996 device_vmstate_if_get_id(VMStateIf *obj)
997 {
998     DeviceState *dev = DEVICE(obj);
999 
1000     return qdev_get_dev_path(dev);
1001 }
1002 
1003 /**
1004  * device_phases_reset:
1005  * Transition reset method for devices to allow moving
1006  * smoothly from legacy reset method to multi-phases
1007  */
1008 static void device_phases_reset(DeviceState *dev)
1009 {
1010     ResettableClass *rc = RESETTABLE_GET_CLASS(dev);
1011 
1012     if (rc->phases.enter) {
1013         rc->phases.enter(OBJECT(dev), RESET_TYPE_COLD);
1014     }
1015     if (rc->phases.hold) {
1016         rc->phases.hold(OBJECT(dev));
1017     }
1018     if (rc->phases.exit) {
1019         rc->phases.exit(OBJECT(dev));
1020     }
1021 }
1022 
1023 static void device_transitional_reset(Object *obj)
1024 {
1025     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1026 
1027     /*
1028      * This will call either @device_phases_reset (for multi-phases transitioned
1029      * devices) or a device's specific method for not-yet transitioned devices.
1030      * In both case, it does not reset children.
1031      */
1032     if (dc->reset) {
1033         dc->reset(DEVICE(obj));
1034     }
1035 }
1036 
1037 /**
1038  * device_get_transitional_reset:
1039  * check if the device's class is ready for multi-phase
1040  */
1041 static ResettableTrFunction device_get_transitional_reset(Object *obj)
1042 {
1043     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1044     if (dc->reset != device_phases_reset) {
1045         /*
1046          * dc->reset has been overridden by a subclass,
1047          * the device is not ready for multi phase yet.
1048          */
1049         return device_transitional_reset;
1050     }
1051     return NULL;
1052 }
1053 
1054 static void device_class_init(ObjectClass *class, void *data)
1055 {
1056     DeviceClass *dc = DEVICE_CLASS(class);
1057     VMStateIfClass *vc = VMSTATE_IF_CLASS(class);
1058     ResettableClass *rc = RESETTABLE_CLASS(class);
1059 
1060     class->unparent = device_unparent;
1061 
1062     /* by default all devices were considered as hotpluggable,
1063      * so with intent to check it in generic qdev_unplug() /
1064      * device_set_realized() functions make every device
1065      * hotpluggable. Devices that shouldn't be hotpluggable,
1066      * should override it in their class_init()
1067      */
1068     dc->hotpluggable = true;
1069     dc->user_creatable = true;
1070     vc->get_id = device_vmstate_if_get_id;
1071     rc->get_state = device_get_reset_state;
1072     rc->child_foreach = device_reset_child_foreach;
1073 
1074     /*
1075      * @device_phases_reset is put as the default reset method below, allowing
1076      * to do the multi-phase transition from base classes to leaf classes. It
1077      * allows a legacy-reset Device class to extend a multi-phases-reset
1078      * Device class for the following reason:
1079      * + If a base class B has been moved to multi-phase, then it does not
1080      *   override this default reset method and may have defined phase methods.
1081      * + A child class C (extending class B) which uses
1082      *   device_class_set_parent_reset() (or similar means) to override the
1083      *   reset method will still work as expected. @device_phases_reset function
1084      *   will be registered as the parent reset method and effectively call
1085      *   parent reset phases.
1086      */
1087     dc->reset = device_phases_reset;
1088     rc->get_transitional_function = device_get_transitional_reset;
1089 
1090     object_class_property_add_bool(class, "realized",
1091                                    device_get_realized, device_set_realized);
1092     object_class_property_add_bool(class, "hotpluggable",
1093                                    device_get_hotpluggable, NULL);
1094     object_class_property_add_bool(class, "hotplugged",
1095                                    device_get_hotplugged, NULL);
1096     object_class_property_add_link(class, "parent_bus", TYPE_BUS,
1097                                    offsetof(DeviceState, parent_bus), NULL, 0);
1098 }
1099 
1100 void device_class_set_parent_reset(DeviceClass *dc,
1101                                    DeviceReset dev_reset,
1102                                    DeviceReset *parent_reset)
1103 {
1104     *parent_reset = dc->reset;
1105     dc->reset = dev_reset;
1106 }
1107 
1108 void device_class_set_parent_realize(DeviceClass *dc,
1109                                      DeviceRealize dev_realize,
1110                                      DeviceRealize *parent_realize)
1111 {
1112     *parent_realize = dc->realize;
1113     dc->realize = dev_realize;
1114 }
1115 
1116 void device_class_set_parent_unrealize(DeviceClass *dc,
1117                                        DeviceUnrealize dev_unrealize,
1118                                        DeviceUnrealize *parent_unrealize)
1119 {
1120     *parent_unrealize = dc->unrealize;
1121     dc->unrealize = dev_unrealize;
1122 }
1123 
1124 void device_legacy_reset(DeviceState *dev)
1125 {
1126     DeviceClass *klass = DEVICE_GET_CLASS(dev);
1127 
1128     trace_qdev_reset(dev, object_get_typename(OBJECT(dev)));
1129     if (klass->reset) {
1130         klass->reset(dev);
1131     }
1132 }
1133 
1134 Object *qdev_get_machine(void)
1135 {
1136     static Object *dev;
1137 
1138     if (dev == NULL) {
1139         dev = container_get(object_get_root(), "/machine");
1140     }
1141 
1142     return dev;
1143 }
1144 
1145 static MachineInitPhase machine_phase;
1146 
1147 bool phase_check(MachineInitPhase phase)
1148 {
1149     return machine_phase >= phase;
1150 }
1151 
1152 void phase_advance(MachineInitPhase phase)
1153 {
1154     assert(machine_phase == phase - 1);
1155     machine_phase = phase;
1156 }
1157 
1158 static const TypeInfo device_type_info = {
1159     .name = TYPE_DEVICE,
1160     .parent = TYPE_OBJECT,
1161     .instance_size = sizeof(DeviceState),
1162     .instance_init = device_initfn,
1163     .instance_post_init = device_post_init,
1164     .instance_finalize = device_finalize,
1165     .class_base_init = device_class_base_init,
1166     .class_init = device_class_init,
1167     .abstract = true,
1168     .class_size = sizeof(DeviceClass),
1169     .interfaces = (InterfaceInfo[]) {
1170         { TYPE_VMSTATE_IF },
1171         { TYPE_RESETTABLE_INTERFACE },
1172         { }
1173     }
1174 };
1175 
1176 static void qdev_register_types(void)
1177 {
1178     type_register_static(&device_type_info);
1179 }
1180 
1181 type_init(qdev_register_types)
1182