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