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