xref: /openbmc/qemu/hw/core/qdev.c (revision 778a2dc5)
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 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 bool qdev_hotplug = false;
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_remove_child(BusState *bus, DeviceState *child)
55 {
56     BusChild *kid;
57 
58     QTAILQ_FOREACH(kid, &bus->children, sibling) {
59         if (kid->child == child) {
60             char name[32];
61 
62             snprintf(name, sizeof(name), "child[%d]", kid->index);
63             QTAILQ_REMOVE(&bus->children, kid, sibling);
64 
65             bus->num_children--;
66 
67             /* This gives back ownership of kid->child back to us.  */
68             object_property_del(OBJECT(bus), name);
69             object_unref(OBJECT(kid->child));
70             g_free(kid);
71             return;
72         }
73     }
74 }
75 
76 static void bus_add_child(BusState *bus, DeviceState *child)
77 {
78     char name[32];
79     BusChild *kid = g_malloc0(sizeof(*kid));
80 
81     bus->num_children++;
82     kid->index = bus->max_index++;
83     kid->child = child;
84     object_ref(OBJECT(kid->child));
85 
86     QTAILQ_INSERT_HEAD(&bus->children, kid, sibling);
87 
88     /* This transfers ownership of kid->child to the property.  */
89     snprintf(name, sizeof(name), "child[%d]", kid->index);
90     object_property_add_link(OBJECT(bus), name,
91                              object_get_typename(OBJECT(child)),
92                              (Object **)&kid->child,
93                              NULL, /* read-only property */
94                              0);
95 }
96 
97 void qdev_set_parent_bus(DeviceState *dev, BusState *bus)
98 {
99     BusState *old_parent_bus = dev->parent_bus;
100     DeviceClass *dc = DEVICE_GET_CLASS(dev);
101 
102     assert(dc->bus_type && object_dynamic_cast(OBJECT(bus), dc->bus_type));
103 
104     if (old_parent_bus) {
105         trace_qdev_update_parent_bus(dev, object_get_typename(OBJECT(dev)),
106             old_parent_bus, object_get_typename(OBJECT(old_parent_bus)),
107             OBJECT(bus), object_get_typename(OBJECT(bus)));
108         /*
109          * Keep a reference to the device while it's not plugged into
110          * any bus, to avoid it potentially evaporating when it is
111          * dereffed in bus_remove_child().
112          * Also keep the ref of the parent bus until the end, so that
113          * we can safely call resettable_change_parent() below.
114          */
115         object_ref(OBJECT(dev));
116         bus_remove_child(dev->parent_bus, dev);
117     }
118     dev->parent_bus = bus;
119     object_ref(OBJECT(bus));
120     bus_add_child(bus, dev);
121     if (dev->realized) {
122         resettable_change_parent(OBJECT(dev), OBJECT(bus),
123                                  OBJECT(old_parent_bus));
124     }
125     if (old_parent_bus) {
126         object_unref(OBJECT(old_parent_bus));
127         object_unref(OBJECT(dev));
128     }
129 }
130 
131 /*
132  * Create a device on the heap.
133  * A type @name must exist.
134  * This only initializes the device state structure and allows
135  * properties to be set.  The device still needs to be realized.  See
136  * qdev-core.h.
137  */
138 DeviceState *qdev_new(const char *name)
139 {
140     if (!object_class_by_name(name)) {
141         module_load_qom_one(name);
142     }
143     return DEVICE(object_new(name));
144 }
145 
146 /*
147  * Try to create a device on the heap.
148  * This is like qdev_new(), except it returns %NULL when type @name
149  * does not exist.
150  */
151 DeviceState *qdev_try_new(const char *name)
152 {
153     if (!module_object_class_by_name(name)) {
154         return NULL;
155     }
156     return DEVICE(object_new(name));
157 }
158 
159 static QTAILQ_HEAD(, DeviceListener) device_listeners
160     = QTAILQ_HEAD_INITIALIZER(device_listeners);
161 
162 enum ListenerDirection { Forward, Reverse };
163 
164 #define DEVICE_LISTENER_CALL(_callback, _direction, _args...)     \
165     do {                                                          \
166         DeviceListener *_listener;                                \
167                                                                   \
168         switch (_direction) {                                     \
169         case Forward:                                             \
170             QTAILQ_FOREACH(_listener, &device_listeners, link) {  \
171                 if (_listener->_callback) {                       \
172                     _listener->_callback(_listener, ##_args);     \
173                 }                                                 \
174             }                                                     \
175             break;                                                \
176         case Reverse:                                             \
177             QTAILQ_FOREACH_REVERSE(_listener, &device_listeners,  \
178                                    link) {                        \
179                 if (_listener->_callback) {                       \
180                     _listener->_callback(_listener, ##_args);     \
181                 }                                                 \
182             }                                                     \
183             break;                                                \
184         default:                                                  \
185             abort();                                              \
186         }                                                         \
187     } while (0)
188 
189 static int device_listener_add(DeviceState *dev, void *opaque)
190 {
191     DEVICE_LISTENER_CALL(realize, Forward, dev);
192 
193     return 0;
194 }
195 
196 void device_listener_register(DeviceListener *listener)
197 {
198     QTAILQ_INSERT_TAIL(&device_listeners, listener, link);
199 
200     qbus_walk_children(sysbus_get_default(), NULL, NULL, device_listener_add,
201                        NULL, NULL);
202 }
203 
204 void device_listener_unregister(DeviceListener *listener)
205 {
206     QTAILQ_REMOVE(&device_listeners, listener, link);
207 }
208 
209 bool qdev_should_hide_device(QemuOpts *opts)
210 {
211     int rc = -1;
212     DeviceListener *listener;
213 
214     QTAILQ_FOREACH(listener, &device_listeners, link) {
215        if (listener->should_be_hidden) {
216             /*
217              * should_be_hidden_will return
218              *  1 if device matches opts and it should be hidden
219              *  0 if device matches opts and should not be hidden
220              *  -1 if device doesn't match ops
221              */
222             rc = listener->should_be_hidden(listener, opts);
223         }
224 
225         if (rc > 0) {
226             break;
227         }
228     }
229 
230     return rc > 0;
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 /*
382  * Realize @dev.
383  * @dev must not be plugged into a bus.
384  * If @bus, plug @dev into @bus.  This takes a reference to @dev.
385  * If @dev has no QOM parent, make one up, taking another reference.
386  * On success, return true.
387  * On failure, store an error through @errp and return false.
388  */
389 bool qdev_realize(DeviceState *dev, BusState *bus, Error **errp)
390 {
391     Error *err = NULL;
392 
393     assert(!dev->realized && !dev->parent_bus);
394 
395     if (bus) {
396         qdev_set_parent_bus(dev, bus);
397     } else {
398         assert(!DEVICE_GET_CLASS(dev)->bus_type);
399     }
400 
401     if (!object_property_set_bool(OBJECT(dev), "realized", true, &err)) {
402         error_propagate(errp, err);
403     }
404     return !err;
405 }
406 
407 /*
408  * Realize @dev and drop a reference.
409  * This is like qdev_realize(), except the caller must hold a
410  * (private) reference, which is dropped on return regardless of
411  * success or failure.  Intended use:
412  *     dev = qdev_new();
413  *     [...]
414  *     qdev_realize_and_unref(dev, bus, errp);
415  * Now @dev can go away without further ado.
416  */
417 bool qdev_realize_and_unref(DeviceState *dev, BusState *bus, Error **errp)
418 {
419     bool ret;
420 
421     ret = qdev_realize(dev, bus, errp);
422     object_unref(OBJECT(dev));
423     return ret;
424 }
425 
426 void qdev_unrealize(DeviceState *dev)
427 {
428     object_property_set_bool(OBJECT(dev), "realized", false, &error_abort);
429 }
430 
431 static int qdev_assert_realized_properly(Object *obj, void *opaque)
432 {
433     DeviceState *dev = DEVICE(object_dynamic_cast(obj, TYPE_DEVICE));
434     DeviceClass *dc;
435 
436     if (dev) {
437         dc = DEVICE_GET_CLASS(dev);
438         assert(dev->realized);
439         assert(dev->parent_bus || !dc->bus_type);
440     }
441     return 0;
442 }
443 
444 void qdev_machine_creation_done(void)
445 {
446     /*
447      * ok, initial machine setup is done, starting from now we can
448      * only create hotpluggable devices
449      */
450     qdev_hotplug = true;
451 
452     object_child_foreach_recursive(object_get_root(),
453                                    qdev_assert_realized_properly, NULL);
454 }
455 
456 bool qdev_machine_modified(void)
457 {
458     return qdev_hot_added || qdev_hot_removed;
459 }
460 
461 BusState *qdev_get_parent_bus(DeviceState *dev)
462 {
463     return dev->parent_bus;
464 }
465 
466 static NamedGPIOList *qdev_get_named_gpio_list(DeviceState *dev,
467                                                const char *name)
468 {
469     NamedGPIOList *ngl;
470 
471     QLIST_FOREACH(ngl, &dev->gpios, node) {
472         /* NULL is a valid and matchable name. */
473         if (g_strcmp0(name, ngl->name) == 0) {
474             return ngl;
475         }
476     }
477 
478     ngl = g_malloc0(sizeof(*ngl));
479     ngl->name = g_strdup(name);
480     QLIST_INSERT_HEAD(&dev->gpios, ngl, node);
481     return ngl;
482 }
483 
484 void qdev_init_gpio_in_named_with_opaque(DeviceState *dev,
485                                          qemu_irq_handler handler,
486                                          void *opaque,
487                                          const char *name, int n)
488 {
489     int i;
490     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
491 
492     assert(gpio_list->num_out == 0 || !name);
493     gpio_list->in = qemu_extend_irqs(gpio_list->in, gpio_list->num_in, handler,
494                                      opaque, n);
495 
496     if (!name) {
497         name = "unnamed-gpio-in";
498     }
499     for (i = gpio_list->num_in; i < gpio_list->num_in + n; i++) {
500         gchar *propname = g_strdup_printf("%s[%u]", name, i);
501 
502         object_property_add_child(OBJECT(dev), propname,
503                                   OBJECT(gpio_list->in[i]));
504         g_free(propname);
505     }
506 
507     gpio_list->num_in += n;
508 }
509 
510 void qdev_init_gpio_in(DeviceState *dev, qemu_irq_handler handler, int n)
511 {
512     qdev_init_gpio_in_named(dev, handler, NULL, n);
513 }
514 
515 void qdev_init_gpio_out_named(DeviceState *dev, qemu_irq *pins,
516                               const char *name, int n)
517 {
518     int i;
519     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
520 
521     assert(gpio_list->num_in == 0 || !name);
522 
523     if (!name) {
524         name = "unnamed-gpio-out";
525     }
526     memset(pins, 0, sizeof(*pins) * n);
527     for (i = 0; i < n; ++i) {
528         gchar *propname = g_strdup_printf("%s[%u]", name,
529                                           gpio_list->num_out + i);
530 
531         object_property_add_link(OBJECT(dev), propname, TYPE_IRQ,
532                                  (Object **)&pins[i],
533                                  object_property_allow_set_link,
534                                  OBJ_PROP_LINK_STRONG);
535         g_free(propname);
536     }
537     gpio_list->num_out += n;
538 }
539 
540 void qdev_init_gpio_out(DeviceState *dev, qemu_irq *pins, int n)
541 {
542     qdev_init_gpio_out_named(dev, pins, NULL, n);
543 }
544 
545 qemu_irq qdev_get_gpio_in_named(DeviceState *dev, const char *name, int n)
546 {
547     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
548 
549     assert(n >= 0 && n < gpio_list->num_in);
550     return gpio_list->in[n];
551 }
552 
553 qemu_irq qdev_get_gpio_in(DeviceState *dev, int n)
554 {
555     return qdev_get_gpio_in_named(dev, NULL, n);
556 }
557 
558 void qdev_connect_gpio_out_named(DeviceState *dev, const char *name, int n,
559                                  qemu_irq pin)
560 {
561     char *propname = g_strdup_printf("%s[%d]",
562                                      name ? name : "unnamed-gpio-out", n);
563     if (pin && !OBJECT(pin)->parent) {
564         /* We need a name for object_property_set_link to work */
565         object_property_add_child(container_get(qdev_get_machine(),
566                                                 "/unattached"),
567                                   "non-qdev-gpio[*]", OBJECT(pin));
568     }
569     object_property_set_link(OBJECT(dev), propname, OBJECT(pin), &error_abort);
570     g_free(propname);
571 }
572 
573 qemu_irq qdev_get_gpio_out_connector(DeviceState *dev, const char *name, int n)
574 {
575     g_autofree char *propname = g_strdup_printf("%s[%d]",
576                                      name ? name : "unnamed-gpio-out", n);
577 
578     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
579                                                       NULL);
580 
581     return ret;
582 }
583 
584 /* disconnect a GPIO output, returning the disconnected input (if any) */
585 
586 static qemu_irq qdev_disconnect_gpio_out_named(DeviceState *dev,
587                                                const char *name, int n)
588 {
589     char *propname = g_strdup_printf("%s[%d]",
590                                      name ? name : "unnamed-gpio-out", n);
591 
592     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
593                                                       NULL);
594     if (ret) {
595         object_property_set_link(OBJECT(dev), propname, NULL, NULL);
596     }
597     g_free(propname);
598     return ret;
599 }
600 
601 qemu_irq qdev_intercept_gpio_out(DeviceState *dev, qemu_irq icpt,
602                                  const char *name, int n)
603 {
604     qemu_irq disconnected = qdev_disconnect_gpio_out_named(dev, name, n);
605     qdev_connect_gpio_out_named(dev, name, n, icpt);
606     return disconnected;
607 }
608 
609 void qdev_connect_gpio_out(DeviceState * dev, int n, qemu_irq pin)
610 {
611     qdev_connect_gpio_out_named(dev, NULL, n, pin);
612 }
613 
614 void qdev_pass_gpios(DeviceState *dev, DeviceState *container,
615                      const char *name)
616 {
617     int i;
618     NamedGPIOList *ngl = qdev_get_named_gpio_list(dev, name);
619 
620     for (i = 0; i < ngl->num_in; i++) {
621         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-in";
622         char *propname = g_strdup_printf("%s[%d]", nm, i);
623 
624         object_property_add_alias(OBJECT(container), propname,
625                                   OBJECT(dev), propname);
626         g_free(propname);
627     }
628     for (i = 0; i < ngl->num_out; i++) {
629         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-out";
630         char *propname = g_strdup_printf("%s[%d]", nm, i);
631 
632         object_property_add_alias(OBJECT(container), propname,
633                                   OBJECT(dev), propname);
634         g_free(propname);
635     }
636     QLIST_REMOVE(ngl, node);
637     QLIST_INSERT_HEAD(&container->gpios, ngl, node);
638 }
639 
640 BusState *qdev_get_child_bus(DeviceState *dev, const char *name)
641 {
642     BusState *bus;
643     Object *child = object_resolve_path_component(OBJECT(dev), name);
644 
645     bus = (BusState *)object_dynamic_cast(child, TYPE_BUS);
646     if (bus) {
647         return bus;
648     }
649 
650     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
651         if (strcmp(name, bus->name) == 0) {
652             return bus;
653         }
654     }
655     return NULL;
656 }
657 
658 int qdev_walk_children(DeviceState *dev,
659                        qdev_walkerfn *pre_devfn, qbus_walkerfn *pre_busfn,
660                        qdev_walkerfn *post_devfn, qbus_walkerfn *post_busfn,
661                        void *opaque)
662 {
663     BusState *bus;
664     int err;
665 
666     if (pre_devfn) {
667         err = pre_devfn(dev, opaque);
668         if (err) {
669             return err;
670         }
671     }
672 
673     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
674         err = qbus_walk_children(bus, pre_devfn, pre_busfn,
675                                  post_devfn, post_busfn, opaque);
676         if (err < 0) {
677             return err;
678         }
679     }
680 
681     if (post_devfn) {
682         err = post_devfn(dev, opaque);
683         if (err) {
684             return err;
685         }
686     }
687 
688     return 0;
689 }
690 
691 DeviceState *qdev_find_recursive(BusState *bus, const char *id)
692 {
693     BusChild *kid;
694     DeviceState *ret;
695     BusState *child;
696 
697     QTAILQ_FOREACH(kid, &bus->children, sibling) {
698         DeviceState *dev = kid->child;
699 
700         if (dev->id && strcmp(dev->id, id) == 0) {
701             return dev;
702         }
703 
704         QLIST_FOREACH(child, &dev->child_bus, sibling) {
705             ret = qdev_find_recursive(child, id);
706             if (ret) {
707                 return ret;
708             }
709         }
710     }
711     return NULL;
712 }
713 
714 char *qdev_get_dev_path(DeviceState *dev)
715 {
716     BusClass *bc;
717 
718     if (!dev || !dev->parent_bus) {
719         return NULL;
720     }
721 
722     bc = BUS_GET_CLASS(dev->parent_bus);
723     if (bc->get_dev_path) {
724         return bc->get_dev_path(dev);
725     }
726 
727     return NULL;
728 }
729 
730 /**
731  * Legacy property handling
732  */
733 
734 static void qdev_get_legacy_property(Object *obj, Visitor *v,
735                                      const char *name, void *opaque,
736                                      Error **errp)
737 {
738     DeviceState *dev = DEVICE(obj);
739     Property *prop = opaque;
740 
741     char buffer[1024];
742     char *ptr = buffer;
743 
744     prop->info->print(dev, prop, buffer, sizeof(buffer));
745     visit_type_str(v, name, &ptr, errp);
746 }
747 
748 /**
749  * qdev_class_add_legacy_property:
750  * @dev: Device to add the property to.
751  * @prop: The qdev property definition.
752  *
753  * Add a legacy QOM property to @dev for qdev property @prop.
754  *
755  * Legacy properties are string versions of QOM properties.  The format of
756  * the string depends on the property type.  Legacy properties are only
757  * needed for "info qtree".
758  *
759  * Do not use this in new code!  QOM Properties added through this interface
760  * will be given names in the "legacy" namespace.
761  */
762 static void qdev_class_add_legacy_property(DeviceClass *dc, Property *prop)
763 {
764     g_autofree char *name = NULL;
765 
766     /* Register pointer properties as legacy properties */
767     if (!prop->info->print && prop->info->get) {
768         return;
769     }
770 
771     name = g_strdup_printf("legacy-%s", prop->name);
772     object_class_property_add(OBJECT_CLASS(dc), name, "str",
773         prop->info->print ? qdev_get_legacy_property : prop->info->get,
774         NULL, NULL, prop);
775 }
776 
777 void qdev_property_add_static(DeviceState *dev, Property *prop)
778 {
779     Object *obj = OBJECT(dev);
780     ObjectProperty *op;
781 
782     assert(!prop->info->create);
783 
784     op = object_property_add(obj, prop->name, prop->info->name,
785                              prop->info->get, prop->info->set,
786                              prop->info->release,
787                              prop);
788 
789     object_property_set_description(obj, prop->name,
790                                     prop->info->description);
791 
792     if (prop->set_default) {
793         prop->info->set_default_value(op, prop);
794         if (op->init) {
795             op->init(obj, op);
796         }
797     }
798 }
799 
800 static void qdev_class_add_property(DeviceClass *klass, Property *prop)
801 {
802     ObjectClass *oc = OBJECT_CLASS(klass);
803 
804     if (prop->info->create) {
805         prop->info->create(oc, prop);
806     } else {
807         ObjectProperty *op;
808 
809         op = object_class_property_add(oc,
810                                        prop->name, prop->info->name,
811                                        prop->info->get, prop->info->set,
812                                        prop->info->release,
813                                        prop);
814         if (prop->set_default) {
815             prop->info->set_default_value(op, prop);
816         }
817     }
818     object_class_property_set_description(oc, prop->name,
819                                           prop->info->description);
820 }
821 
822 /* @qdev_alias_all_properties - Add alias properties to the source object for
823  * all qdev properties on the target DeviceState.
824  */
825 void qdev_alias_all_properties(DeviceState *target, Object *source)
826 {
827     ObjectClass *class;
828     Property *prop;
829 
830     class = object_get_class(OBJECT(target));
831     do {
832         DeviceClass *dc = DEVICE_CLASS(class);
833 
834         for (prop = dc->props_; prop && prop->name; prop++) {
835             object_property_add_alias(source, prop->name,
836                                       OBJECT(target), prop->name);
837         }
838         class = object_class_get_parent(class);
839     } while (class != object_class_by_name(TYPE_DEVICE));
840 }
841 
842 static bool device_get_realized(Object *obj, Error **errp)
843 {
844     DeviceState *dev = DEVICE(obj);
845     return dev->realized;
846 }
847 
848 static bool check_only_migratable(Object *obj, Error **errp)
849 {
850     DeviceClass *dc = DEVICE_GET_CLASS(obj);
851 
852     if (!vmstate_check_only_migratable(dc->vmsd)) {
853         error_setg(errp, "Device %s is not migratable, but "
854                    "--only-migratable was specified",
855                    object_get_typename(obj));
856         return false;
857     }
858 
859     return true;
860 }
861 
862 static void device_set_realized(Object *obj, bool value, Error **errp)
863 {
864     DeviceState *dev = DEVICE(obj);
865     DeviceClass *dc = DEVICE_GET_CLASS(dev);
866     HotplugHandler *hotplug_ctrl;
867     BusState *bus;
868     NamedClockList *ncl;
869     Error *local_err = NULL;
870     bool unattached_parent = false;
871     static int unattached_count;
872 
873     if (dev->hotplugged && !dc->hotpluggable) {
874         error_setg(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj));
875         return;
876     }
877 
878     if (value && !dev->realized) {
879         if (!check_only_migratable(obj, &local_err)) {
880             goto fail;
881         }
882 
883         if (!obj->parent) {
884             gchar *name = g_strdup_printf("device[%d]", unattached_count++);
885 
886             object_property_add_child(container_get(qdev_get_machine(),
887                                                     "/unattached"),
888                                       name, obj);
889             unattached_parent = true;
890             g_free(name);
891         }
892 
893         hotplug_ctrl = qdev_get_hotplug_handler(dev);
894         if (hotplug_ctrl) {
895             hotplug_handler_pre_plug(hotplug_ctrl, dev, &local_err);
896             if (local_err != NULL) {
897                 goto fail;
898             }
899         }
900 
901         if (dc->realize) {
902             dc->realize(dev, &local_err);
903             if (local_err != NULL) {
904                 goto fail;
905             }
906         }
907 
908         DEVICE_LISTENER_CALL(realize, Forward, dev);
909 
910         /*
911          * always free/re-initialize here since the value cannot be cleaned up
912          * in device_unrealize due to its usage later on in the unplug path
913          */
914         g_free(dev->canonical_path);
915         dev->canonical_path = object_get_canonical_path(OBJECT(dev));
916         QLIST_FOREACH(ncl, &dev->clocks, node) {
917             if (ncl->alias) {
918                 continue;
919             } else {
920                 clock_setup_canonical_path(ncl->clock);
921             }
922         }
923 
924         if (qdev_get_vmsd(dev)) {
925             if (vmstate_register_with_alias_id(VMSTATE_IF(dev),
926                                                VMSTATE_INSTANCE_ID_ANY,
927                                                qdev_get_vmsd(dev), dev,
928                                                dev->instance_id_alias,
929                                                dev->alias_required_for_version,
930                                                &local_err) < 0) {
931                 goto post_realize_fail;
932             }
933         }
934 
935         /*
936          * Clear the reset state, in case the object was previously unrealized
937          * with a dirty state.
938          */
939         resettable_state_clear(&dev->reset);
940 
941         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
942             if (!qbus_realize(bus, errp)) {
943                 goto child_realize_fail;
944             }
945         }
946         if (dev->hotplugged) {
947             /*
948              * Reset the device, as well as its subtree which, at this point,
949              * should be realized too.
950              */
951             resettable_assert_reset(OBJECT(dev), RESET_TYPE_COLD);
952             resettable_change_parent(OBJECT(dev), OBJECT(dev->parent_bus),
953                                      NULL);
954             resettable_release_reset(OBJECT(dev), RESET_TYPE_COLD);
955         }
956         dev->pending_deleted_event = false;
957 
958         if (hotplug_ctrl) {
959             hotplug_handler_plug(hotplug_ctrl, dev, &local_err);
960             if (local_err != NULL) {
961                 goto child_realize_fail;
962             }
963        }
964 
965     } else if (!value && dev->realized) {
966         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
967             qbus_unrealize(bus);
968         }
969         if (qdev_get_vmsd(dev)) {
970             vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
971         }
972         if (dc->unrealize) {
973             dc->unrealize(dev);
974         }
975         dev->pending_deleted_event = true;
976         DEVICE_LISTENER_CALL(unrealize, Reverse, dev);
977     }
978 
979     assert(local_err == NULL);
980     dev->realized = value;
981     return;
982 
983 child_realize_fail:
984     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
985         qbus_unrealize(bus);
986     }
987 
988     if (qdev_get_vmsd(dev)) {
989         vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
990     }
991 
992 post_realize_fail:
993     g_free(dev->canonical_path);
994     dev->canonical_path = NULL;
995     if (dc->unrealize) {
996         dc->unrealize(dev);
997     }
998 
999 fail:
1000     error_propagate(errp, local_err);
1001     if (unattached_parent) {
1002         /*
1003          * Beware, this doesn't just revert
1004          * object_property_add_child(), it also runs bus_remove()!
1005          */
1006         object_unparent(OBJECT(dev));
1007         unattached_count--;
1008     }
1009 }
1010 
1011 static bool device_get_hotpluggable(Object *obj, Error **errp)
1012 {
1013     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1014     DeviceState *dev = DEVICE(obj);
1015 
1016     return dc->hotpluggable && (dev->parent_bus == NULL ||
1017                                 qbus_is_hotpluggable(dev->parent_bus));
1018 }
1019 
1020 static bool device_get_hotplugged(Object *obj, Error **errp)
1021 {
1022     DeviceState *dev = DEVICE(obj);
1023 
1024     return dev->hotplugged;
1025 }
1026 
1027 static void device_initfn(Object *obj)
1028 {
1029     DeviceState *dev = DEVICE(obj);
1030 
1031     if (qdev_hotplug) {
1032         dev->hotplugged = 1;
1033         qdev_hot_added = true;
1034     }
1035 
1036     dev->instance_id_alias = -1;
1037     dev->realized = false;
1038     dev->allow_unplug_during_migration = false;
1039 
1040     QLIST_INIT(&dev->gpios);
1041     QLIST_INIT(&dev->clocks);
1042 }
1043 
1044 static void device_post_init(Object *obj)
1045 {
1046     /*
1047      * Note: ordered so that the user's global properties take
1048      * precedence.
1049      */
1050     object_apply_compat_props(obj);
1051     qdev_prop_set_globals(DEVICE(obj));
1052 }
1053 
1054 /* Unlink device from bus and free the structure.  */
1055 static void device_finalize(Object *obj)
1056 {
1057     NamedGPIOList *ngl, *next;
1058 
1059     DeviceState *dev = DEVICE(obj);
1060 
1061     QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) {
1062         QLIST_REMOVE(ngl, node);
1063         qemu_free_irqs(ngl->in, ngl->num_in);
1064         g_free(ngl->name);
1065         g_free(ngl);
1066         /* ngl->out irqs are owned by the other end and should not be freed
1067          * here
1068          */
1069     }
1070 
1071     qdev_finalize_clocklist(dev);
1072 
1073     /* Only send event if the device had been completely realized */
1074     if (dev->pending_deleted_event) {
1075         g_assert(dev->canonical_path);
1076 
1077         qapi_event_send_device_deleted(!!dev->id, dev->id, dev->canonical_path);
1078         g_free(dev->canonical_path);
1079         dev->canonical_path = NULL;
1080     }
1081 
1082     qemu_opts_del(dev->opts);
1083 }
1084 
1085 static void device_class_base_init(ObjectClass *class, void *data)
1086 {
1087     DeviceClass *klass = DEVICE_CLASS(class);
1088 
1089     /* We explicitly look up properties in the superclasses,
1090      * so do not propagate them to the subclasses.
1091      */
1092     klass->props_ = NULL;
1093 }
1094 
1095 static void device_unparent(Object *obj)
1096 {
1097     DeviceState *dev = DEVICE(obj);
1098     BusState *bus;
1099 
1100     if (dev->realized) {
1101         qdev_unrealize(dev);
1102     }
1103     while (dev->num_child_bus) {
1104         bus = QLIST_FIRST(&dev->child_bus);
1105         object_unparent(OBJECT(bus));
1106     }
1107     if (dev->parent_bus) {
1108         bus_remove_child(dev->parent_bus, dev);
1109         object_unref(OBJECT(dev->parent_bus));
1110         dev->parent_bus = NULL;
1111     }
1112 }
1113 
1114 static char *
1115 device_vmstate_if_get_id(VMStateIf *obj)
1116 {
1117     DeviceState *dev = DEVICE(obj);
1118 
1119     return qdev_get_dev_path(dev);
1120 }
1121 
1122 /**
1123  * device_phases_reset:
1124  * Transition reset method for devices to allow moving
1125  * smoothly from legacy reset method to multi-phases
1126  */
1127 static void device_phases_reset(DeviceState *dev)
1128 {
1129     ResettableClass *rc = RESETTABLE_GET_CLASS(dev);
1130 
1131     if (rc->phases.enter) {
1132         rc->phases.enter(OBJECT(dev), RESET_TYPE_COLD);
1133     }
1134     if (rc->phases.hold) {
1135         rc->phases.hold(OBJECT(dev));
1136     }
1137     if (rc->phases.exit) {
1138         rc->phases.exit(OBJECT(dev));
1139     }
1140 }
1141 
1142 static void device_transitional_reset(Object *obj)
1143 {
1144     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1145 
1146     /*
1147      * This will call either @device_phases_reset (for multi-phases transitioned
1148      * devices) or a device's specific method for not-yet transitioned devices.
1149      * In both case, it does not reset children.
1150      */
1151     if (dc->reset) {
1152         dc->reset(DEVICE(obj));
1153     }
1154 }
1155 
1156 /**
1157  * device_get_transitional_reset:
1158  * check if the device's class is ready for multi-phase
1159  */
1160 static ResettableTrFunction device_get_transitional_reset(Object *obj)
1161 {
1162     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1163     if (dc->reset != device_phases_reset) {
1164         /*
1165          * dc->reset has been overridden by a subclass,
1166          * the device is not ready for multi phase yet.
1167          */
1168         return device_transitional_reset;
1169     }
1170     return NULL;
1171 }
1172 
1173 static void device_class_init(ObjectClass *class, void *data)
1174 {
1175     DeviceClass *dc = DEVICE_CLASS(class);
1176     VMStateIfClass *vc = VMSTATE_IF_CLASS(class);
1177     ResettableClass *rc = RESETTABLE_CLASS(class);
1178 
1179     class->unparent = device_unparent;
1180 
1181     /* by default all devices were considered as hotpluggable,
1182      * so with intent to check it in generic qdev_unplug() /
1183      * device_set_realized() functions make every device
1184      * hotpluggable. Devices that shouldn't be hotpluggable,
1185      * should override it in their class_init()
1186      */
1187     dc->hotpluggable = true;
1188     dc->user_creatable = true;
1189     vc->get_id = device_vmstate_if_get_id;
1190     rc->get_state = device_get_reset_state;
1191     rc->child_foreach = device_reset_child_foreach;
1192 
1193     /*
1194      * @device_phases_reset is put as the default reset method below, allowing
1195      * to do the multi-phase transition from base classes to leaf classes. It
1196      * allows a legacy-reset Device class to extend a multi-phases-reset
1197      * Device class for the following reason:
1198      * + If a base class B has been moved to multi-phase, then it does not
1199      *   override this default reset method and may have defined phase methods.
1200      * + A child class C (extending class B) which uses
1201      *   device_class_set_parent_reset() (or similar means) to override the
1202      *   reset method will still work as expected. @device_phases_reset function
1203      *   will be registered as the parent reset method and effectively call
1204      *   parent reset phases.
1205      */
1206     dc->reset = device_phases_reset;
1207     rc->get_transitional_function = device_get_transitional_reset;
1208 
1209     object_class_property_add_bool(class, "realized",
1210                                    device_get_realized, device_set_realized);
1211     object_class_property_add_bool(class, "hotpluggable",
1212                                    device_get_hotpluggable, NULL);
1213     object_class_property_add_bool(class, "hotplugged",
1214                                    device_get_hotplugged, NULL);
1215     object_class_property_add_link(class, "parent_bus", TYPE_BUS,
1216                                    offsetof(DeviceState, parent_bus), NULL, 0);
1217 }
1218 
1219 void device_class_set_props(DeviceClass *dc, Property *props)
1220 {
1221     Property *prop;
1222 
1223     dc->props_ = props;
1224     for (prop = props; prop && prop->name; prop++) {
1225         qdev_class_add_legacy_property(dc, prop);
1226         qdev_class_add_property(dc, prop);
1227     }
1228 }
1229 
1230 void device_class_set_parent_reset(DeviceClass *dc,
1231                                    DeviceReset dev_reset,
1232                                    DeviceReset *parent_reset)
1233 {
1234     *parent_reset = dc->reset;
1235     dc->reset = dev_reset;
1236 }
1237 
1238 void device_class_set_parent_realize(DeviceClass *dc,
1239                                      DeviceRealize dev_realize,
1240                                      DeviceRealize *parent_realize)
1241 {
1242     *parent_realize = dc->realize;
1243     dc->realize = dev_realize;
1244 }
1245 
1246 void device_class_set_parent_unrealize(DeviceClass *dc,
1247                                        DeviceUnrealize dev_unrealize,
1248                                        DeviceUnrealize *parent_unrealize)
1249 {
1250     *parent_unrealize = dc->unrealize;
1251     dc->unrealize = dev_unrealize;
1252 }
1253 
1254 void device_legacy_reset(DeviceState *dev)
1255 {
1256     DeviceClass *klass = DEVICE_GET_CLASS(dev);
1257 
1258     trace_qdev_reset(dev, object_get_typename(OBJECT(dev)));
1259     if (klass->reset) {
1260         klass->reset(dev);
1261     }
1262 }
1263 
1264 Object *qdev_get_machine(void)
1265 {
1266     static Object *dev;
1267 
1268     if (dev == NULL) {
1269         dev = container_get(object_get_root(), "/machine");
1270     }
1271 
1272     return dev;
1273 }
1274 
1275 static const TypeInfo device_type_info = {
1276     .name = TYPE_DEVICE,
1277     .parent = TYPE_OBJECT,
1278     .instance_size = sizeof(DeviceState),
1279     .instance_init = device_initfn,
1280     .instance_post_init = device_post_init,
1281     .instance_finalize = device_finalize,
1282     .class_base_init = device_class_base_init,
1283     .class_init = device_class_init,
1284     .abstract = true,
1285     .class_size = sizeof(DeviceClass),
1286     .interfaces = (InterfaceInfo[]) {
1287         { TYPE_VMSTATE_IF },
1288         { TYPE_RESETTABLE_INTERFACE },
1289         { }
1290     }
1291 };
1292 
1293 static void qdev_register_types(void)
1294 {
1295     type_register_static(&device_type_info);
1296 }
1297 
1298 type_init(qdev_register_types)
1299