xref: /openbmc/qemu/hw/core/qdev.c (revision 587d82fa)
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/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     ObjectClass *oc = object_class_by_name(name);
151 #ifdef CONFIG_MODULES
152     if (!oc) {
153         int rv = module_load_qom(name, &error_fatal);
154         if (rv > 0) {
155             oc = object_class_by_name(name);
156         } else {
157             error_report("could not find a module for type '%s'", name);
158             exit(1);
159         }
160     }
161 #endif
162     if (!oc) {
163         error_report("unknown type '%s'", name);
164         abort();
165     }
166     return DEVICE(object_new(name));
167 }
168 
169 DeviceState *qdev_try_new(const char *name)
170 {
171     if (!module_object_class_by_name(name)) {
172         return NULL;
173     }
174     return DEVICE(object_new(name));
175 }
176 
177 static QTAILQ_HEAD(, DeviceListener) device_listeners
178     = QTAILQ_HEAD_INITIALIZER(device_listeners);
179 
180 enum ListenerDirection { Forward, Reverse };
181 
182 #define DEVICE_LISTENER_CALL(_callback, _direction, _args...)     \
183     do {                                                          \
184         DeviceListener *_listener;                                \
185                                                                   \
186         switch (_direction) {                                     \
187         case Forward:                                             \
188             QTAILQ_FOREACH(_listener, &device_listeners, link) {  \
189                 if (_listener->_callback) {                       \
190                     _listener->_callback(_listener, ##_args);     \
191                 }                                                 \
192             }                                                     \
193             break;                                                \
194         case Reverse:                                             \
195             QTAILQ_FOREACH_REVERSE(_listener, &device_listeners,  \
196                                    link) {                        \
197                 if (_listener->_callback) {                       \
198                     _listener->_callback(_listener, ##_args);     \
199                 }                                                 \
200             }                                                     \
201             break;                                                \
202         default:                                                  \
203             abort();                                              \
204         }                                                         \
205     } while (0)
206 
207 static int device_listener_add(DeviceState *dev, void *opaque)
208 {
209     DEVICE_LISTENER_CALL(realize, Forward, dev);
210 
211     return 0;
212 }
213 
214 void device_listener_register(DeviceListener *listener)
215 {
216     QTAILQ_INSERT_TAIL(&device_listeners, listener, link);
217 
218     qbus_walk_children(sysbus_get_default(), NULL, NULL, device_listener_add,
219                        NULL, NULL);
220 }
221 
222 void device_listener_unregister(DeviceListener *listener)
223 {
224     QTAILQ_REMOVE(&device_listeners, listener, link);
225 }
226 
227 bool qdev_should_hide_device(const QDict *opts, bool from_json, Error **errp)
228 {
229     ERRP_GUARD();
230     DeviceListener *listener;
231 
232     QTAILQ_FOREACH(listener, &device_listeners, link) {
233         if (listener->hide_device) {
234             if (listener->hide_device(listener, opts, from_json, errp)) {
235                 return true;
236             } else if (*errp) {
237                 return false;
238             }
239         }
240     }
241 
242     return false;
243 }
244 
245 void qdev_set_legacy_instance_id(DeviceState *dev, int alias_id,
246                                  int required_for_version)
247 {
248     assert(!dev->realized);
249     dev->instance_id_alias = alias_id;
250     dev->alias_required_for_version = required_for_version;
251 }
252 
253 static int qdev_prereset(DeviceState *dev, void *opaque)
254 {
255     trace_qdev_reset_tree(dev, object_get_typename(OBJECT(dev)));
256     return 0;
257 }
258 
259 static int qbus_prereset(BusState *bus, void *opaque)
260 {
261     trace_qbus_reset_tree(bus, object_get_typename(OBJECT(bus)));
262     return 0;
263 }
264 
265 static int qdev_reset_one(DeviceState *dev, void *opaque)
266 {
267     device_legacy_reset(dev);
268 
269     return 0;
270 }
271 
272 static int qbus_reset_one(BusState *bus, void *opaque)
273 {
274     BusClass *bc = BUS_GET_CLASS(bus);
275     trace_qbus_reset(bus, object_get_typename(OBJECT(bus)));
276     if (bc->reset) {
277         bc->reset(bus);
278     }
279     return 0;
280 }
281 
282 void qdev_reset_all(DeviceState *dev)
283 {
284     trace_qdev_reset_all(dev, object_get_typename(OBJECT(dev)));
285     qdev_walk_children(dev, qdev_prereset, qbus_prereset,
286                        qdev_reset_one, qbus_reset_one, NULL);
287 }
288 
289 void qdev_reset_all_fn(void *opaque)
290 {
291     qdev_reset_all(DEVICE(opaque));
292 }
293 
294 void qbus_reset_all(BusState *bus)
295 {
296     trace_qbus_reset_all(bus, object_get_typename(OBJECT(bus)));
297     qbus_walk_children(bus, qdev_prereset, qbus_prereset,
298                        qdev_reset_one, qbus_reset_one, NULL);
299 }
300 
301 void qbus_reset_all_fn(void *opaque)
302 {
303     BusState *bus = opaque;
304     qbus_reset_all(bus);
305 }
306 
307 void device_cold_reset(DeviceState *dev)
308 {
309     resettable_reset(OBJECT(dev), RESET_TYPE_COLD);
310 }
311 
312 bool device_is_in_reset(DeviceState *dev)
313 {
314     return resettable_is_in_reset(OBJECT(dev));
315 }
316 
317 static ResettableState *device_get_reset_state(Object *obj)
318 {
319     DeviceState *dev = DEVICE(obj);
320     return &dev->reset;
321 }
322 
323 static void device_reset_child_foreach(Object *obj, ResettableChildCallback cb,
324                                        void *opaque, ResetType type)
325 {
326     DeviceState *dev = DEVICE(obj);
327     BusState *bus;
328 
329     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
330         cb(OBJECT(bus), opaque, type);
331     }
332 }
333 
334 bool qdev_realize(DeviceState *dev, BusState *bus, Error **errp)
335 {
336     assert(!dev->realized && !dev->parent_bus);
337 
338     if (bus) {
339         if (!qdev_set_parent_bus(dev, bus, errp)) {
340             return false;
341         }
342     } else {
343         assert(!DEVICE_GET_CLASS(dev)->bus_type);
344     }
345 
346     return object_property_set_bool(OBJECT(dev), "realized", true, errp);
347 }
348 
349 bool qdev_realize_and_unref(DeviceState *dev, BusState *bus, Error **errp)
350 {
351     bool ret;
352 
353     ret = qdev_realize(dev, bus, errp);
354     object_unref(OBJECT(dev));
355     return ret;
356 }
357 
358 void qdev_unrealize(DeviceState *dev)
359 {
360     object_property_set_bool(OBJECT(dev), "realized", false, &error_abort);
361 }
362 
363 static int qdev_assert_realized_properly_cb(Object *obj, void *opaque)
364 {
365     DeviceState *dev = DEVICE(object_dynamic_cast(obj, TYPE_DEVICE));
366     DeviceClass *dc;
367 
368     if (dev) {
369         dc = DEVICE_GET_CLASS(dev);
370         assert(dev->realized);
371         assert(dev->parent_bus || !dc->bus_type);
372     }
373     return 0;
374 }
375 
376 void qdev_assert_realized_properly(void)
377 {
378     object_child_foreach_recursive(object_get_root(),
379                                    qdev_assert_realized_properly_cb, NULL);
380 }
381 
382 bool qdev_machine_modified(void)
383 {
384     return qdev_hot_added || qdev_hot_removed;
385 }
386 
387 BusState *qdev_get_parent_bus(DeviceState *dev)
388 {
389     return dev->parent_bus;
390 }
391 
392 BusState *qdev_get_child_bus(DeviceState *dev, const char *name)
393 {
394     BusState *bus;
395     Object *child = object_resolve_path_component(OBJECT(dev), name);
396 
397     bus = (BusState *)object_dynamic_cast(child, TYPE_BUS);
398     if (bus) {
399         return bus;
400     }
401 
402     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
403         if (strcmp(name, bus->name) == 0) {
404             return bus;
405         }
406     }
407     return NULL;
408 }
409 
410 int qdev_walk_children(DeviceState *dev,
411                        qdev_walkerfn *pre_devfn, qbus_walkerfn *pre_busfn,
412                        qdev_walkerfn *post_devfn, qbus_walkerfn *post_busfn,
413                        void *opaque)
414 {
415     BusState *bus;
416     int err;
417 
418     if (pre_devfn) {
419         err = pre_devfn(dev, opaque);
420         if (err) {
421             return err;
422         }
423     }
424 
425     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
426         err = qbus_walk_children(bus, pre_devfn, pre_busfn,
427                                  post_devfn, post_busfn, opaque);
428         if (err < 0) {
429             return err;
430         }
431     }
432 
433     if (post_devfn) {
434         err = post_devfn(dev, opaque);
435         if (err) {
436             return err;
437         }
438     }
439 
440     return 0;
441 }
442 
443 DeviceState *qdev_find_recursive(BusState *bus, const char *id)
444 {
445     BusChild *kid;
446     DeviceState *ret;
447     BusState *child;
448 
449     WITH_RCU_READ_LOCK_GUARD() {
450         QTAILQ_FOREACH_RCU(kid, &bus->children, sibling) {
451             DeviceState *dev = kid->child;
452 
453             if (dev->id && strcmp(dev->id, id) == 0) {
454                 return dev;
455             }
456 
457             QLIST_FOREACH(child, &dev->child_bus, sibling) {
458                 ret = qdev_find_recursive(child, id);
459                 if (ret) {
460                     return ret;
461                 }
462             }
463         }
464     }
465     return NULL;
466 }
467 
468 char *qdev_get_dev_path(DeviceState *dev)
469 {
470     BusClass *bc;
471 
472     if (!dev || !dev->parent_bus) {
473         return NULL;
474     }
475 
476     bc = BUS_GET_CLASS(dev->parent_bus);
477     if (bc->get_dev_path) {
478         return bc->get_dev_path(dev);
479     }
480 
481     return NULL;
482 }
483 
484 void qdev_add_unplug_blocker(DeviceState *dev, Error *reason)
485 {
486     dev->unplug_blockers = g_slist_prepend(dev->unplug_blockers, reason);
487 }
488 
489 void qdev_del_unplug_blocker(DeviceState *dev, Error *reason)
490 {
491     dev->unplug_blockers = g_slist_remove(dev->unplug_blockers, reason);
492 }
493 
494 bool qdev_unplug_blocked(DeviceState *dev, Error **errp)
495 {
496     if (dev->unplug_blockers) {
497         error_propagate(errp, error_copy(dev->unplug_blockers->data));
498         return true;
499     }
500 
501     return false;
502 }
503 
504 static bool device_get_realized(Object *obj, Error **errp)
505 {
506     DeviceState *dev = DEVICE(obj);
507     return dev->realized;
508 }
509 
510 static bool check_only_migratable(Object *obj, Error **errp)
511 {
512     DeviceClass *dc = DEVICE_GET_CLASS(obj);
513 
514     if (!vmstate_check_only_migratable(dc->vmsd)) {
515         error_setg(errp, "Device %s is not migratable, but "
516                    "--only-migratable was specified",
517                    object_get_typename(obj));
518         return false;
519     }
520 
521     return true;
522 }
523 
524 static void device_set_realized(Object *obj, bool value, Error **errp)
525 {
526     DeviceState *dev = DEVICE(obj);
527     DeviceClass *dc = DEVICE_GET_CLASS(dev);
528     HotplugHandler *hotplug_ctrl;
529     BusState *bus;
530     NamedClockList *ncl;
531     Error *local_err = NULL;
532     bool unattached_parent = false;
533     static int unattached_count;
534 
535     if (dev->hotplugged && !dc->hotpluggable) {
536         error_setg(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj));
537         return;
538     }
539 
540     if (value && !dev->realized) {
541         if (!check_only_migratable(obj, errp)) {
542             goto fail;
543         }
544 
545         if (!obj->parent) {
546             gchar *name = g_strdup_printf("device[%d]", unattached_count++);
547 
548             object_property_add_child(container_get(qdev_get_machine(),
549                                                     "/unattached"),
550                                       name, obj);
551             unattached_parent = true;
552             g_free(name);
553         }
554 
555         hotplug_ctrl = qdev_get_hotplug_handler(dev);
556         if (hotplug_ctrl) {
557             hotplug_handler_pre_plug(hotplug_ctrl, dev, &local_err);
558             if (local_err != NULL) {
559                 goto fail;
560             }
561         }
562 
563         if (dc->realize) {
564             dc->realize(dev, &local_err);
565             if (local_err != NULL) {
566                 goto fail;
567             }
568         }
569 
570         DEVICE_LISTENER_CALL(realize, Forward, dev);
571 
572         /*
573          * always free/re-initialize here since the value cannot be cleaned up
574          * in device_unrealize due to its usage later on in the unplug path
575          */
576         g_free(dev->canonical_path);
577         dev->canonical_path = object_get_canonical_path(OBJECT(dev));
578         QLIST_FOREACH(ncl, &dev->clocks, node) {
579             if (ncl->alias) {
580                 continue;
581             } else {
582                 clock_setup_canonical_path(ncl->clock);
583             }
584         }
585 
586         if (qdev_get_vmsd(dev)) {
587             if (vmstate_register_with_alias_id(VMSTATE_IF(dev),
588                                                VMSTATE_INSTANCE_ID_ANY,
589                                                qdev_get_vmsd(dev), dev,
590                                                dev->instance_id_alias,
591                                                dev->alias_required_for_version,
592                                                &local_err) < 0) {
593                 goto post_realize_fail;
594             }
595         }
596 
597         /*
598          * Clear the reset state, in case the object was previously unrealized
599          * with a dirty state.
600          */
601         resettable_state_clear(&dev->reset);
602 
603         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
604             if (!qbus_realize(bus, errp)) {
605                 goto child_realize_fail;
606             }
607         }
608         if (dev->hotplugged) {
609             /*
610              * Reset the device, as well as its subtree which, at this point,
611              * should be realized too.
612              */
613             resettable_assert_reset(OBJECT(dev), RESET_TYPE_COLD);
614             resettable_change_parent(OBJECT(dev), OBJECT(dev->parent_bus),
615                                      NULL);
616             resettable_release_reset(OBJECT(dev), RESET_TYPE_COLD);
617         }
618         dev->pending_deleted_event = false;
619 
620         if (hotplug_ctrl) {
621             hotplug_handler_plug(hotplug_ctrl, dev, &local_err);
622             if (local_err != NULL) {
623                 goto child_realize_fail;
624             }
625        }
626 
627        qatomic_store_release(&dev->realized, value);
628 
629     } else if (!value && dev->realized) {
630 
631         /*
632          * Change the value so that any concurrent users are aware
633          * that the device is going to be unrealized
634          *
635          * TODO: change .realized property to enum that states
636          * each phase of the device realization/unrealization
637          */
638 
639         qatomic_set(&dev->realized, value);
640         /*
641          * Ensure that concurrent users see this update prior to
642          * any other changes done by unrealize.
643          */
644         smp_wmb();
645 
646         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
647             qbus_unrealize(bus);
648         }
649         if (qdev_get_vmsd(dev)) {
650             vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
651         }
652         if (dc->unrealize) {
653             dc->unrealize(dev);
654         }
655         dev->pending_deleted_event = true;
656         DEVICE_LISTENER_CALL(unrealize, Reverse, dev);
657     }
658 
659     assert(local_err == NULL);
660     return;
661 
662 child_realize_fail:
663     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
664         qbus_unrealize(bus);
665     }
666 
667     if (qdev_get_vmsd(dev)) {
668         vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
669     }
670 
671 post_realize_fail:
672     g_free(dev->canonical_path);
673     dev->canonical_path = NULL;
674     if (dc->unrealize) {
675         dc->unrealize(dev);
676     }
677 
678 fail:
679     error_propagate(errp, local_err);
680     if (unattached_parent) {
681         /*
682          * Beware, this doesn't just revert
683          * object_property_add_child(), it also runs bus_remove()!
684          */
685         object_unparent(OBJECT(dev));
686         unattached_count--;
687     }
688 }
689 
690 static bool device_get_hotpluggable(Object *obj, Error **errp)
691 {
692     DeviceClass *dc = DEVICE_GET_CLASS(obj);
693     DeviceState *dev = DEVICE(obj);
694 
695     return dc->hotpluggable && (dev->parent_bus == NULL ||
696                                 qbus_is_hotpluggable(dev->parent_bus));
697 }
698 
699 static bool device_get_hotplugged(Object *obj, Error **errp)
700 {
701     DeviceState *dev = DEVICE(obj);
702 
703     return dev->hotplugged;
704 }
705 
706 static void device_initfn(Object *obj)
707 {
708     DeviceState *dev = DEVICE(obj);
709 
710     if (phase_check(PHASE_MACHINE_READY)) {
711         dev->hotplugged = 1;
712         qdev_hot_added = true;
713     }
714 
715     dev->instance_id_alias = -1;
716     dev->realized = false;
717     dev->allow_unplug_during_migration = false;
718 
719     QLIST_INIT(&dev->gpios);
720     QLIST_INIT(&dev->clocks);
721 }
722 
723 static void device_post_init(Object *obj)
724 {
725     /*
726      * Note: ordered so that the user's global properties take
727      * precedence.
728      */
729     object_apply_compat_props(obj);
730     qdev_prop_set_globals(DEVICE(obj));
731 }
732 
733 /* Unlink device from bus and free the structure.  */
734 static void device_finalize(Object *obj)
735 {
736     NamedGPIOList *ngl, *next;
737 
738     DeviceState *dev = DEVICE(obj);
739 
740     g_assert(!dev->unplug_blockers);
741 
742     QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) {
743         QLIST_REMOVE(ngl, node);
744         qemu_free_irqs(ngl->in, ngl->num_in);
745         g_free(ngl->name);
746         g_free(ngl);
747         /* ngl->out irqs are owned by the other end and should not be freed
748          * here
749          */
750     }
751 
752     qdev_finalize_clocklist(dev);
753 
754     /* Only send event if the device had been completely realized */
755     if (dev->pending_deleted_event) {
756         g_assert(dev->canonical_path);
757 
758         qapi_event_send_device_deleted(dev->id, dev->canonical_path);
759         g_free(dev->canonical_path);
760         dev->canonical_path = NULL;
761     }
762 
763     qobject_unref(dev->opts);
764     g_free(dev->id);
765 }
766 
767 static void device_class_base_init(ObjectClass *class, void *data)
768 {
769     DeviceClass *klass = DEVICE_CLASS(class);
770 
771     /* We explicitly look up properties in the superclasses,
772      * so do not propagate them to the subclasses.
773      */
774     klass->props_ = NULL;
775 }
776 
777 static void device_unparent(Object *obj)
778 {
779     DeviceState *dev = DEVICE(obj);
780     BusState *bus;
781 
782     if (dev->realized) {
783         qdev_unrealize(dev);
784     }
785     while (dev->num_child_bus) {
786         bus = QLIST_FIRST(&dev->child_bus);
787         object_unparent(OBJECT(bus));
788     }
789     if (dev->parent_bus) {
790         bus_remove_child(dev->parent_bus, dev);
791         object_unref(OBJECT(dev->parent_bus));
792         dev->parent_bus = NULL;
793     }
794 }
795 
796 static char *
797 device_vmstate_if_get_id(VMStateIf *obj)
798 {
799     DeviceState *dev = DEVICE(obj);
800 
801     return qdev_get_dev_path(dev);
802 }
803 
804 /**
805  * device_phases_reset:
806  * Transition reset method for devices to allow moving
807  * smoothly from legacy reset method to multi-phases
808  */
809 static void device_phases_reset(DeviceState *dev)
810 {
811     ResettableClass *rc = RESETTABLE_GET_CLASS(dev);
812 
813     if (rc->phases.enter) {
814         rc->phases.enter(OBJECT(dev), RESET_TYPE_COLD);
815     }
816     if (rc->phases.hold) {
817         rc->phases.hold(OBJECT(dev));
818     }
819     if (rc->phases.exit) {
820         rc->phases.exit(OBJECT(dev));
821     }
822 }
823 
824 static void device_transitional_reset(Object *obj)
825 {
826     DeviceClass *dc = DEVICE_GET_CLASS(obj);
827 
828     /*
829      * This will call either @device_phases_reset (for multi-phases transitioned
830      * devices) or a device's specific method for not-yet transitioned devices.
831      * In both case, it does not reset children.
832      */
833     if (dc->reset) {
834         dc->reset(DEVICE(obj));
835     }
836 }
837 
838 /**
839  * device_get_transitional_reset:
840  * check if the device's class is ready for multi-phase
841  */
842 static ResettableTrFunction device_get_transitional_reset(Object *obj)
843 {
844     DeviceClass *dc = DEVICE_GET_CLASS(obj);
845     if (dc->reset != device_phases_reset) {
846         /*
847          * dc->reset has been overridden by a subclass,
848          * the device is not ready for multi phase yet.
849          */
850         return device_transitional_reset;
851     }
852     return NULL;
853 }
854 
855 static void device_class_init(ObjectClass *class, void *data)
856 {
857     DeviceClass *dc = DEVICE_CLASS(class);
858     VMStateIfClass *vc = VMSTATE_IF_CLASS(class);
859     ResettableClass *rc = RESETTABLE_CLASS(class);
860 
861     class->unparent = device_unparent;
862 
863     /* by default all devices were considered as hotpluggable,
864      * so with intent to check it in generic qdev_unplug() /
865      * device_set_realized() functions make every device
866      * hotpluggable. Devices that shouldn't be hotpluggable,
867      * should override it in their class_init()
868      */
869     dc->hotpluggable = true;
870     dc->user_creatable = true;
871     vc->get_id = device_vmstate_if_get_id;
872     rc->get_state = device_get_reset_state;
873     rc->child_foreach = device_reset_child_foreach;
874 
875     /*
876      * @device_phases_reset is put as the default reset method below, allowing
877      * to do the multi-phase transition from base classes to leaf classes. It
878      * allows a legacy-reset Device class to extend a multi-phases-reset
879      * Device class for the following reason:
880      * + If a base class B has been moved to multi-phase, then it does not
881      *   override this default reset method and may have defined phase methods.
882      * + A child class C (extending class B) which uses
883      *   device_class_set_parent_reset() (or similar means) to override the
884      *   reset method will still work as expected. @device_phases_reset function
885      *   will be registered as the parent reset method and effectively call
886      *   parent reset phases.
887      */
888     dc->reset = device_phases_reset;
889     rc->get_transitional_function = device_get_transitional_reset;
890 
891     object_class_property_add_bool(class, "realized",
892                                    device_get_realized, device_set_realized);
893     object_class_property_add_bool(class, "hotpluggable",
894                                    device_get_hotpluggable, NULL);
895     object_class_property_add_bool(class, "hotplugged",
896                                    device_get_hotplugged, NULL);
897     object_class_property_add_link(class, "parent_bus", TYPE_BUS,
898                                    offsetof(DeviceState, parent_bus), NULL, 0);
899 }
900 
901 void device_class_set_parent_reset(DeviceClass *dc,
902                                    DeviceReset dev_reset,
903                                    DeviceReset *parent_reset)
904 {
905     *parent_reset = dc->reset;
906     dc->reset = dev_reset;
907 }
908 
909 void device_class_set_parent_realize(DeviceClass *dc,
910                                      DeviceRealize dev_realize,
911                                      DeviceRealize *parent_realize)
912 {
913     *parent_realize = dc->realize;
914     dc->realize = dev_realize;
915 }
916 
917 void device_class_set_parent_unrealize(DeviceClass *dc,
918                                        DeviceUnrealize dev_unrealize,
919                                        DeviceUnrealize *parent_unrealize)
920 {
921     *parent_unrealize = dc->unrealize;
922     dc->unrealize = dev_unrealize;
923 }
924 
925 void device_legacy_reset(DeviceState *dev)
926 {
927     DeviceClass *klass = DEVICE_GET_CLASS(dev);
928 
929     trace_qdev_reset(dev, object_get_typename(OBJECT(dev)));
930     if (klass->reset) {
931         klass->reset(dev);
932     }
933 }
934 
935 Object *qdev_get_machine(void)
936 {
937     static Object *dev;
938 
939     if (dev == NULL) {
940         dev = container_get(object_get_root(), "/machine");
941     }
942 
943     return dev;
944 }
945 
946 static MachineInitPhase machine_phase;
947 
948 bool phase_check(MachineInitPhase phase)
949 {
950     return machine_phase >= phase;
951 }
952 
953 void phase_advance(MachineInitPhase phase)
954 {
955     assert(machine_phase == phase - 1);
956     machine_phase = phase;
957 }
958 
959 static const TypeInfo device_type_info = {
960     .name = TYPE_DEVICE,
961     .parent = TYPE_OBJECT,
962     .instance_size = sizeof(DeviceState),
963     .instance_init = device_initfn,
964     .instance_post_init = device_post_init,
965     .instance_finalize = device_finalize,
966     .class_base_init = device_class_base_init,
967     .class_init = device_class_init,
968     .abstract = true,
969     .class_size = sizeof(DeviceClass),
970     .interfaces = (InterfaceInfo[]) {
971         { TYPE_VMSTATE_IF },
972         { TYPE_RESETTABLE_INTERFACE },
973         { }
974     }
975 };
976 
977 static void qdev_register_types(void)
978 {
979     type_register_static(&device_type_info);
980 }
981 
982 type_init(qdev_register_types)
983