xref: /openbmc/qemu/hw/core/qdev.c (revision cd7c50a48dd484637aec36c351728ad0f140805a)
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 "hw/qdev.h"
29 #include "hw/fw-path-provider.h"
30 #include "sysemu/sysemu.h"
31 #include "qapi/error.h"
32 #include "qapi/qmp/qerror.h"
33 #include "qapi/visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "hw/hotplug.h"
36 #include "hw/boards.h"
37 #include "qapi-event.h"
38 
39 int qdev_hotplug = 0;
40 static bool qdev_hot_added = false;
41 static bool qdev_hot_removed = false;
42 
43 const VMStateDescription *qdev_get_vmsd(DeviceState *dev)
44 {
45     DeviceClass *dc = DEVICE_GET_CLASS(dev);
46     return dc->vmsd;
47 }
48 
49 const char *qdev_fw_name(DeviceState *dev)
50 {
51     DeviceClass *dc = DEVICE_GET_CLASS(dev);
52 
53     if (dc->fw_name) {
54         return dc->fw_name;
55     }
56 
57     return object_get_typename(OBJECT(dev));
58 }
59 
60 static void qdev_property_add_legacy(DeviceState *dev, Property *prop,
61                                      Error **errp);
62 
63 static void bus_remove_child(BusState *bus, DeviceState *child)
64 {
65     BusChild *kid;
66 
67     QTAILQ_FOREACH(kid, &bus->children, sibling) {
68         if (kid->child == child) {
69             char name[32];
70 
71             snprintf(name, sizeof(name), "child[%d]", kid->index);
72             QTAILQ_REMOVE(&bus->children, kid, sibling);
73 
74             /* This gives back ownership of kid->child back to us.  */
75             object_property_del(OBJECT(bus), name, NULL);
76             object_unref(OBJECT(kid->child));
77             g_free(kid);
78             return;
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     kid->index = bus->max_index++;
89     kid->child = child;
90     object_ref(OBJECT(kid->child));
91 
92     QTAILQ_INSERT_HEAD(&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, /* return ownership on prop deletion */
101                              NULL);
102 }
103 
104 void qdev_set_parent_bus(DeviceState *dev, BusState *bus)
105 {
106     dev->parent_bus = bus;
107     object_ref(OBJECT(bus));
108     bus_add_child(bus, dev);
109 }
110 
111 static void qbus_set_hotplug_handler_internal(BusState *bus, Object *handler,
112                                               Error **errp)
113 {
114 
115     object_property_set_link(OBJECT(bus), OBJECT(handler),
116                              QDEV_HOTPLUG_HANDLER_PROPERTY, errp);
117 }
118 
119 void qbus_set_hotplug_handler(BusState *bus, DeviceState *handler, Error **errp)
120 {
121     qbus_set_hotplug_handler_internal(bus, OBJECT(handler), errp);
122 }
123 
124 void qbus_set_bus_hotplug_handler(BusState *bus, Error **errp)
125 {
126     qbus_set_hotplug_handler_internal(bus, OBJECT(bus), errp);
127 }
128 
129 /* Create a new device.  This only initializes the device state structure
130    and allows properties to be set.  qdev_init should be called to
131    initialize the actual device emulation.  */
132 DeviceState *qdev_create(BusState *bus, const char *name)
133 {
134     DeviceState *dev;
135 
136     dev = qdev_try_create(bus, name);
137     if (!dev) {
138         if (bus) {
139             error_report("Unknown device '%s' for bus '%s'", name,
140                          object_get_typename(OBJECT(bus)));
141         } else {
142             error_report("Unknown device '%s' for default sysbus", name);
143         }
144         abort();
145     }
146 
147     return dev;
148 }
149 
150 DeviceState *qdev_try_create(BusState *bus, const char *type)
151 {
152     DeviceState *dev;
153 
154     if (object_class_by_name(type) == NULL) {
155         return NULL;
156     }
157     dev = DEVICE(object_new(type));
158     if (!dev) {
159         return NULL;
160     }
161 
162     if (!bus) {
163         bus = sysbus_get_default();
164     }
165 
166     qdev_set_parent_bus(dev, bus);
167     object_unref(OBJECT(dev));
168     return dev;
169 }
170 
171 /* Initialize a device.  Device properties should be set before calling
172    this function.  IRQs and MMIO regions should be connected/mapped after
173    calling this function.
174    On failure, destroy the device and return negative value.
175    Return 0 on success.  */
176 int qdev_init(DeviceState *dev)
177 {
178     Error *local_err = NULL;
179 
180     assert(!dev->realized);
181 
182     object_property_set_bool(OBJECT(dev), true, "realized", &local_err);
183     if (local_err != NULL) {
184         qerror_report_err(local_err);
185         error_free(local_err);
186         object_unparent(OBJECT(dev));
187         return -1;
188     }
189     return 0;
190 }
191 
192 static QTAILQ_HEAD(device_listeners, DeviceListener) device_listeners
193     = QTAILQ_HEAD_INITIALIZER(device_listeners);
194 
195 enum ListenerDirection { Forward, Reverse };
196 
197 #define DEVICE_LISTENER_CALL(_callback, _direction, _args...)     \
198     do {                                                          \
199         DeviceListener *_listener;                                \
200                                                                   \
201         switch (_direction) {                                     \
202         case Forward:                                             \
203             QTAILQ_FOREACH(_listener, &device_listeners, link) {  \
204                 if (_listener->_callback) {                       \
205                     _listener->_callback(_listener, ##_args);     \
206                 }                                                 \
207             }                                                     \
208             break;                                                \
209         case Reverse:                                             \
210             QTAILQ_FOREACH_REVERSE(_listener, &device_listeners,  \
211                                    device_listeners, link) {      \
212                 if (_listener->_callback) {                       \
213                     _listener->_callback(_listener, ##_args);     \
214                 }                                                 \
215             }                                                     \
216             break;                                                \
217         default:                                                  \
218             abort();                                              \
219         }                                                         \
220     } while (0)
221 
222 static int device_listener_add(DeviceState *dev, void *opaque)
223 {
224     DEVICE_LISTENER_CALL(realize, Forward, dev);
225 
226     return 0;
227 }
228 
229 void device_listener_register(DeviceListener *listener)
230 {
231     QTAILQ_INSERT_TAIL(&device_listeners, listener, link);
232 
233     qbus_walk_children(sysbus_get_default(), NULL, NULL, device_listener_add,
234                        NULL, NULL);
235 }
236 
237 void device_listener_unregister(DeviceListener *listener)
238 {
239     QTAILQ_REMOVE(&device_listeners, listener, link);
240 }
241 
242 static void device_realize(DeviceState *dev, Error **errp)
243 {
244     DeviceClass *dc = DEVICE_GET_CLASS(dev);
245 
246     if (dc->init) {
247         int rc = dc->init(dev);
248         if (rc < 0) {
249             error_setg(errp, "Device initialization failed.");
250             return;
251         }
252     }
253 }
254 
255 static void device_unrealize(DeviceState *dev, Error **errp)
256 {
257     DeviceClass *dc = DEVICE_GET_CLASS(dev);
258 
259     if (dc->exit) {
260         int rc = dc->exit(dev);
261         if (rc < 0) {
262             error_setg(errp, "Device exit failed.");
263             return;
264         }
265     }
266 }
267 
268 void qdev_set_legacy_instance_id(DeviceState *dev, int alias_id,
269                                  int required_for_version)
270 {
271     assert(!dev->realized);
272     dev->instance_id_alias = alias_id;
273     dev->alias_required_for_version = required_for_version;
274 }
275 
276 static HotplugHandler *qdev_get_hotplug_handler(DeviceState *dev)
277 {
278     HotplugHandler *hotplug_ctrl = NULL;
279 
280     if (dev->parent_bus && dev->parent_bus->hotplug_handler) {
281         hotplug_ctrl = dev->parent_bus->hotplug_handler;
282     } else if (object_dynamic_cast(qdev_get_machine(), TYPE_MACHINE)) {
283         MachineState *machine = MACHINE(qdev_get_machine());
284         MachineClass *mc = MACHINE_GET_CLASS(machine);
285 
286         if (mc->get_hotplug_handler) {
287             hotplug_ctrl = mc->get_hotplug_handler(machine, dev);
288         }
289     }
290     return hotplug_ctrl;
291 }
292 
293 void qdev_unplug(DeviceState *dev, Error **errp)
294 {
295     DeviceClass *dc = DEVICE_GET_CLASS(dev);
296     HotplugHandler *hotplug_ctrl;
297     HotplugHandlerClass *hdc;
298 
299     if (dev->parent_bus && !qbus_is_hotpluggable(dev->parent_bus)) {
300         error_set(errp, QERR_BUS_NO_HOTPLUG, dev->parent_bus->name);
301         return;
302     }
303 
304     if (!dc->hotpluggable) {
305         error_set(errp, QERR_DEVICE_NO_HOTPLUG,
306                   object_get_typename(OBJECT(dev)));
307         return;
308     }
309 
310     qdev_hot_removed = true;
311 
312     hotplug_ctrl = qdev_get_hotplug_handler(dev);
313     /* hotpluggable device MUST have HotplugHandler, if it doesn't
314      * then something is very wrong with it */
315     g_assert(hotplug_ctrl);
316 
317     /* If device supports async unplug just request it to be done,
318      * otherwise just remove it synchronously */
319     hdc = HOTPLUG_HANDLER_GET_CLASS(hotplug_ctrl);
320     if (hdc->unplug_request) {
321         hotplug_handler_unplug_request(hotplug_ctrl, dev, errp);
322     } else {
323         hotplug_handler_unplug(hotplug_ctrl, dev, errp);
324     }
325 }
326 
327 static int qdev_reset_one(DeviceState *dev, void *opaque)
328 {
329     device_reset(dev);
330 
331     return 0;
332 }
333 
334 static int qbus_reset_one(BusState *bus, void *opaque)
335 {
336     BusClass *bc = BUS_GET_CLASS(bus);
337     if (bc->reset) {
338         bc->reset(bus);
339     }
340     return 0;
341 }
342 
343 void qdev_reset_all(DeviceState *dev)
344 {
345     qdev_walk_children(dev, NULL, NULL, qdev_reset_one, qbus_reset_one, NULL);
346 }
347 
348 void qbus_reset_all(BusState *bus)
349 {
350     qbus_walk_children(bus, NULL, NULL, qdev_reset_one, qbus_reset_one, NULL);
351 }
352 
353 void qbus_reset_all_fn(void *opaque)
354 {
355     BusState *bus = opaque;
356     qbus_reset_all(bus);
357 }
358 
359 /* can be used as ->unplug() callback for the simple cases */
360 void qdev_simple_device_unplug_cb(HotplugHandler *hotplug_dev,
361                                   DeviceState *dev, Error **errp)
362 {
363     /* just zap it */
364     object_unparent(OBJECT(dev));
365 }
366 
367 /* Like qdev_init(), but terminate program via error_report() instead of
368    returning an error value.  This is okay during machine creation.
369    Don't use for hotplug, because there callers need to recover from
370    failure.  Exception: if you know the device's init() callback can't
371    fail, then qdev_init_nofail() can't fail either, and is therefore
372    usable even then.  But relying on the device implementation that
373    way is somewhat unclean, and best avoided.  */
374 void qdev_init_nofail(DeviceState *dev)
375 {
376     Error *err = NULL;
377 
378     assert(!dev->realized);
379 
380     object_property_set_bool(OBJECT(dev), true, "realized", &err);
381     if (err) {
382         error_report("Initialization of device %s failed: %s",
383                      object_get_typename(OBJECT(dev)),
384                      error_get_pretty(err));
385         exit(1);
386     }
387 }
388 
389 void qdev_machine_creation_done(void)
390 {
391     /*
392      * ok, initial machine setup is done, starting from now we can
393      * only create hotpluggable devices
394      */
395     qdev_hotplug = 1;
396 }
397 
398 bool qdev_machine_modified(void)
399 {
400     return qdev_hot_added || qdev_hot_removed;
401 }
402 
403 BusState *qdev_get_parent_bus(DeviceState *dev)
404 {
405     return dev->parent_bus;
406 }
407 
408 static NamedGPIOList *qdev_get_named_gpio_list(DeviceState *dev,
409                                                const char *name)
410 {
411     NamedGPIOList *ngl;
412 
413     QLIST_FOREACH(ngl, &dev->gpios, node) {
414         /* NULL is a valid and matchable name, otherwise do a normal
415          * strcmp match.
416          */
417         if ((!ngl->name && !name) ||
418                 (name && ngl->name && strcmp(name, ngl->name) == 0)) {
419             return ngl;
420         }
421     }
422 
423     ngl = g_malloc0(sizeof(*ngl));
424     ngl->name = g_strdup(name);
425     QLIST_INSERT_HEAD(&dev->gpios, ngl, node);
426     return ngl;
427 }
428 
429 void qdev_init_gpio_in_named(DeviceState *dev, qemu_irq_handler handler,
430                              const char *name, int n)
431 {
432     int i;
433     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
434     char *propname = g_strdup_printf("%s[*]", name ? name : "unnamed-gpio-in");
435 
436     assert(gpio_list->num_out == 0 || !name);
437     gpio_list->in = qemu_extend_irqs(gpio_list->in, gpio_list->num_in, handler,
438                                      dev, n);
439 
440     for (i = gpio_list->num_in; i < gpio_list->num_in + n; i++) {
441         object_property_add_child(OBJECT(dev), propname,
442                                   OBJECT(gpio_list->in[i]), &error_abort);
443     }
444     g_free(propname);
445 
446     gpio_list->num_in += n;
447 }
448 
449 void qdev_init_gpio_in(DeviceState *dev, qemu_irq_handler handler, int n)
450 {
451     qdev_init_gpio_in_named(dev, handler, NULL, n);
452 }
453 
454 void qdev_init_gpio_out_named(DeviceState *dev, qemu_irq *pins,
455                               const char *name, int n)
456 {
457     int i;
458     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
459     char *propname = g_strdup_printf("%s[*]", name ? name : "unnamed-gpio-out");
460 
461     assert(gpio_list->num_in == 0 || !name);
462     gpio_list->num_out += n;
463 
464     for (i = 0; i < n; ++i) {
465         memset(&pins[i], 0, sizeof(*pins));
466         object_property_add_link(OBJECT(dev), propname, TYPE_IRQ,
467                                  (Object **)&pins[i],
468                                  object_property_allow_set_link,
469                                  OBJ_PROP_LINK_UNREF_ON_RELEASE,
470                                  &error_abort);
471     }
472     g_free(propname);
473 }
474 
475 void qdev_init_gpio_out(DeviceState *dev, qemu_irq *pins, int n)
476 {
477     qdev_init_gpio_out_named(dev, pins, NULL, n);
478 }
479 
480 qemu_irq qdev_get_gpio_in_named(DeviceState *dev, const char *name, int n)
481 {
482     NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
483 
484     assert(n >= 0 && n < gpio_list->num_in);
485     return gpio_list->in[n];
486 }
487 
488 qemu_irq qdev_get_gpio_in(DeviceState *dev, int n)
489 {
490     return qdev_get_gpio_in_named(dev, NULL, n);
491 }
492 
493 void qdev_connect_gpio_out_named(DeviceState *dev, const char *name, int n,
494                                  qemu_irq pin)
495 {
496     char *propname = g_strdup_printf("%s[%d]",
497                                      name ? name : "unnamed-gpio-out", n);
498     if (pin) {
499         /* We need a name for object_property_set_link to work.  If the
500          * object has a parent, object_property_add_child will come back
501          * with an error without doing anything.  If it has none, it will
502          * never fail.  So we can just call it with a NULL Error pointer.
503          */
504         object_property_add_child(qdev_get_machine(), "non-qdev-gpio[*]",
505                                   OBJECT(pin), NULL);
506     }
507     object_property_set_link(OBJECT(dev), OBJECT(pin), propname, &error_abort);
508     g_free(propname);
509 }
510 
511 qemu_irq qdev_get_gpio_out_connector(DeviceState *dev, const char *name, int n)
512 {
513     char *propname = g_strdup_printf("%s[%d]",
514                                      name ? name : "unnamed-gpio-out", n);
515 
516     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
517                                                       NULL);
518 
519     return ret;
520 }
521 
522 /* disconnect a GPIO ouput, returning the disconnected input (if any) */
523 
524 static qemu_irq qdev_disconnect_gpio_out_named(DeviceState *dev,
525                                                const char *name, int n)
526 {
527     char *propname = g_strdup_printf("%s[%d]",
528                                      name ? name : "unnamed-gpio-out", n);
529 
530     qemu_irq ret = (qemu_irq)object_property_get_link(OBJECT(dev), propname,
531                                                       NULL);
532     if (ret) {
533         object_property_set_link(OBJECT(dev), NULL, propname, NULL);
534     }
535     g_free(propname);
536     return ret;
537 }
538 
539 qemu_irq qdev_intercept_gpio_out(DeviceState *dev, qemu_irq icpt,
540                                  const char *name, int n)
541 {
542     qemu_irq disconnected = qdev_disconnect_gpio_out_named(dev, name, n);
543     qdev_connect_gpio_out_named(dev, name, n, icpt);
544     return disconnected;
545 }
546 
547 void qdev_connect_gpio_out(DeviceState * dev, int n, qemu_irq pin)
548 {
549     qdev_connect_gpio_out_named(dev, NULL, n, pin);
550 }
551 
552 void qdev_pass_gpios(DeviceState *dev, DeviceState *container,
553                      const char *name)
554 {
555     int i;
556     NamedGPIOList *ngl = qdev_get_named_gpio_list(dev, name);
557 
558     for (i = 0; i < ngl->num_in; i++) {
559         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-in";
560         char *propname = g_strdup_printf("%s[%d]", nm, i);
561 
562         object_property_add_alias(OBJECT(container), propname,
563                                   OBJECT(dev), propname,
564                                   &error_abort);
565     }
566     for (i = 0; i < ngl->num_out; i++) {
567         const char *nm = ngl->name ? ngl->name : "unnamed-gpio-out";
568         char *propname = g_strdup_printf("%s[%d]", nm, i);
569 
570         object_property_add_alias(OBJECT(container), propname,
571                                   OBJECT(dev), propname,
572                                   &error_abort);
573     }
574     QLIST_REMOVE(ngl, node);
575     QLIST_INSERT_HEAD(&container->gpios, ngl, node);
576 }
577 
578 BusState *qdev_get_child_bus(DeviceState *dev, const char *name)
579 {
580     BusState *bus;
581 
582     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
583         if (strcmp(name, bus->name) == 0) {
584             return bus;
585         }
586     }
587     return NULL;
588 }
589 
590 int qbus_walk_children(BusState *bus,
591                        qdev_walkerfn *pre_devfn, qbus_walkerfn *pre_busfn,
592                        qdev_walkerfn *post_devfn, qbus_walkerfn *post_busfn,
593                        void *opaque)
594 {
595     BusChild *kid;
596     int err;
597 
598     if (pre_busfn) {
599         err = pre_busfn(bus, opaque);
600         if (err) {
601             return err;
602         }
603     }
604 
605     QTAILQ_FOREACH(kid, &bus->children, sibling) {
606         err = qdev_walk_children(kid->child,
607                                  pre_devfn, pre_busfn,
608                                  post_devfn, post_busfn, opaque);
609         if (err < 0) {
610             return err;
611         }
612     }
613 
614     if (post_busfn) {
615         err = post_busfn(bus, opaque);
616         if (err) {
617             return err;
618         }
619     }
620 
621     return 0;
622 }
623 
624 int qdev_walk_children(DeviceState *dev,
625                        qdev_walkerfn *pre_devfn, qbus_walkerfn *pre_busfn,
626                        qdev_walkerfn *post_devfn, qbus_walkerfn *post_busfn,
627                        void *opaque)
628 {
629     BusState *bus;
630     int err;
631 
632     if (pre_devfn) {
633         err = pre_devfn(dev, opaque);
634         if (err) {
635             return err;
636         }
637     }
638 
639     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
640         err = qbus_walk_children(bus, pre_devfn, pre_busfn,
641                                  post_devfn, post_busfn, opaque);
642         if (err < 0) {
643             return err;
644         }
645     }
646 
647     if (post_devfn) {
648         err = post_devfn(dev, opaque);
649         if (err) {
650             return err;
651         }
652     }
653 
654     return 0;
655 }
656 
657 DeviceState *qdev_find_recursive(BusState *bus, const char *id)
658 {
659     BusChild *kid;
660     DeviceState *ret;
661     BusState *child;
662 
663     QTAILQ_FOREACH(kid, &bus->children, sibling) {
664         DeviceState *dev = kid->child;
665 
666         if (dev->id && strcmp(dev->id, id) == 0) {
667             return dev;
668         }
669 
670         QLIST_FOREACH(child, &dev->child_bus, sibling) {
671             ret = qdev_find_recursive(child, id);
672             if (ret) {
673                 return ret;
674             }
675         }
676     }
677     return NULL;
678 }
679 
680 static void qbus_realize(BusState *bus, DeviceState *parent, const char *name)
681 {
682     const char *typename = object_get_typename(OBJECT(bus));
683     BusClass *bc;
684     char *buf;
685     int i, len, bus_id;
686 
687     bus->parent = parent;
688 
689     if (name) {
690         bus->name = g_strdup(name);
691     } else if (bus->parent && bus->parent->id) {
692         /* parent device has id -> use it plus parent-bus-id for bus name */
693         bus_id = bus->parent->num_child_bus;
694 
695         len = strlen(bus->parent->id) + 16;
696         buf = g_malloc(len);
697         snprintf(buf, len, "%s.%d", bus->parent->id, bus_id);
698         bus->name = buf;
699     } else {
700         /* no id -> use lowercase bus type plus global bus-id for bus name */
701         bc = BUS_GET_CLASS(bus);
702         bus_id = bc->automatic_ids++;
703 
704         len = strlen(typename) + 16;
705         buf = g_malloc(len);
706         len = snprintf(buf, len, "%s.%d", typename, bus_id);
707         for (i = 0; i < len; i++) {
708             buf[i] = qemu_tolower(buf[i]);
709         }
710         bus->name = buf;
711     }
712 
713     if (bus->parent) {
714         QLIST_INSERT_HEAD(&bus->parent->child_bus, bus, sibling);
715         bus->parent->num_child_bus++;
716         object_property_add_child(OBJECT(bus->parent), bus->name, OBJECT(bus), NULL);
717         object_unref(OBJECT(bus));
718     } else if (bus != sysbus_get_default()) {
719         /* TODO: once all bus devices are qdevified,
720            only reset handler for main_system_bus should be registered here. */
721         qemu_register_reset(qbus_reset_all_fn, bus);
722     }
723 }
724 
725 static void bus_unparent(Object *obj)
726 {
727     BusState *bus = BUS(obj);
728     BusChild *kid;
729 
730     while ((kid = QTAILQ_FIRST(&bus->children)) != NULL) {
731         DeviceState *dev = kid->child;
732         object_unparent(OBJECT(dev));
733     }
734     if (bus->parent) {
735         QLIST_REMOVE(bus, sibling);
736         bus->parent->num_child_bus--;
737         bus->parent = NULL;
738     } else {
739         assert(bus != sysbus_get_default()); /* main_system_bus is never freed */
740         qemu_unregister_reset(qbus_reset_all_fn, bus);
741     }
742 }
743 
744 static bool bus_get_realized(Object *obj, Error **errp)
745 {
746     BusState *bus = BUS(obj);
747 
748     return bus->realized;
749 }
750 
751 static void bus_set_realized(Object *obj, bool value, Error **errp)
752 {
753     BusState *bus = BUS(obj);
754     BusClass *bc = BUS_GET_CLASS(bus);
755     BusChild *kid;
756     Error *local_err = NULL;
757 
758     if (value && !bus->realized) {
759         if (bc->realize) {
760             bc->realize(bus, &local_err);
761         }
762 
763         /* TODO: recursive realization */
764     } else if (!value && bus->realized) {
765         QTAILQ_FOREACH(kid, &bus->children, sibling) {
766             DeviceState *dev = kid->child;
767             object_property_set_bool(OBJECT(dev), false, "realized",
768                                      &local_err);
769             if (local_err != NULL) {
770                 break;
771             }
772         }
773         if (bc->unrealize && local_err == NULL) {
774             bc->unrealize(bus, &local_err);
775         }
776     }
777 
778     if (local_err != NULL) {
779         error_propagate(errp, local_err);
780         return;
781     }
782 
783     bus->realized = value;
784 }
785 
786 void qbus_create_inplace(void *bus, size_t size, const char *typename,
787                          DeviceState *parent, const char *name)
788 {
789     object_initialize(bus, size, typename);
790     qbus_realize(bus, parent, name);
791 }
792 
793 BusState *qbus_create(const char *typename, DeviceState *parent, const char *name)
794 {
795     BusState *bus;
796 
797     bus = BUS(object_new(typename));
798     qbus_realize(bus, parent, name);
799 
800     return bus;
801 }
802 
803 static char *bus_get_fw_dev_path(BusState *bus, DeviceState *dev)
804 {
805     BusClass *bc = BUS_GET_CLASS(bus);
806 
807     if (bc->get_fw_dev_path) {
808         return bc->get_fw_dev_path(dev);
809     }
810 
811     return NULL;
812 }
813 
814 static char *qdev_get_fw_dev_path_from_handler(BusState *bus, DeviceState *dev)
815 {
816     Object *obj = OBJECT(dev);
817     char *d = NULL;
818 
819     while (!d && obj->parent) {
820         obj = obj->parent;
821         d = fw_path_provider_try_get_dev_path(obj, bus, dev);
822     }
823     return d;
824 }
825 
826 static int qdev_get_fw_dev_path_helper(DeviceState *dev, char *p, int size)
827 {
828     int l = 0;
829 
830     if (dev && dev->parent_bus) {
831         char *d;
832         l = qdev_get_fw_dev_path_helper(dev->parent_bus->parent, p, size);
833         d = qdev_get_fw_dev_path_from_handler(dev->parent_bus, dev);
834         if (!d) {
835             d = bus_get_fw_dev_path(dev->parent_bus, dev);
836         }
837         if (d) {
838             l += snprintf(p + l, size - l, "%s", d);
839             g_free(d);
840         } else {
841             return l;
842         }
843     }
844     l += snprintf(p + l , size - l, "/");
845 
846     return l;
847 }
848 
849 char* qdev_get_fw_dev_path(DeviceState *dev)
850 {
851     char path[128];
852     int l;
853 
854     l = qdev_get_fw_dev_path_helper(dev, path, 128);
855 
856     path[l-1] = '\0';
857 
858     return g_strdup(path);
859 }
860 
861 char *qdev_get_dev_path(DeviceState *dev)
862 {
863     BusClass *bc;
864 
865     if (!dev || !dev->parent_bus) {
866         return NULL;
867     }
868 
869     bc = BUS_GET_CLASS(dev->parent_bus);
870     if (bc->get_dev_path) {
871         return bc->get_dev_path(dev);
872     }
873 
874     return NULL;
875 }
876 
877 /**
878  * Legacy property handling
879  */
880 
881 static void qdev_get_legacy_property(Object *obj, Visitor *v, void *opaque,
882                                      const char *name, Error **errp)
883 {
884     DeviceState *dev = DEVICE(obj);
885     Property *prop = opaque;
886 
887     char buffer[1024];
888     char *ptr = buffer;
889 
890     prop->info->print(dev, prop, buffer, sizeof(buffer));
891     visit_type_str(v, &ptr, name, errp);
892 }
893 
894 /**
895  * @qdev_add_legacy_property - adds a legacy property
896  *
897  * Do not use this is new code!  Properties added through this interface will
898  * be given names and types in the "legacy" namespace.
899  *
900  * Legacy properties are string versions of other OOM properties.  The format
901  * of the string depends on the property type.
902  */
903 static void qdev_property_add_legacy(DeviceState *dev, Property *prop,
904                                      Error **errp)
905 {
906     gchar *name;
907 
908     /* Register pointer properties as legacy properties */
909     if (!prop->info->print && prop->info->get) {
910         return;
911     }
912 
913     name = g_strdup_printf("legacy-%s", prop->name);
914     object_property_add(OBJECT(dev), name, "str",
915                         prop->info->print ? qdev_get_legacy_property : prop->info->get,
916                         NULL,
917                         NULL,
918                         prop, errp);
919 
920     g_free(name);
921 }
922 
923 /**
924  * @qdev_property_add_static - add a @Property to a device.
925  *
926  * Static properties access data in a struct.  The actual type of the
927  * property and the field depends on the property type.
928  */
929 void qdev_property_add_static(DeviceState *dev, Property *prop,
930                               Error **errp)
931 {
932     Error *local_err = NULL;
933     Object *obj = OBJECT(dev);
934 
935     /*
936      * TODO qdev_prop_ptr does not have getters or setters.  It must
937      * go now that it can be replaced with links.  The test should be
938      * removed along with it: all static properties are read/write.
939      */
940     if (!prop->info->get && !prop->info->set) {
941         return;
942     }
943 
944     object_property_add(obj, prop->name, prop->info->name,
945                         prop->info->get, prop->info->set,
946                         prop->info->release,
947                         prop, &local_err);
948 
949     if (local_err) {
950         error_propagate(errp, local_err);
951         return;
952     }
953 
954     object_property_set_description(obj, prop->name,
955                                     prop->info->description,
956                                     &error_abort);
957 
958     if (prop->qtype == QTYPE_NONE) {
959         return;
960     }
961 
962     if (prop->qtype == QTYPE_QBOOL) {
963         object_property_set_bool(obj, prop->defval, prop->name, &error_abort);
964     } else if (prop->info->enum_table) {
965         object_property_set_str(obj, prop->info->enum_table[prop->defval],
966                                 prop->name, &error_abort);
967     } else if (prop->qtype == QTYPE_QINT) {
968         object_property_set_int(obj, prop->defval, prop->name, &error_abort);
969     }
970 }
971 
972 /* @qdev_alias_all_properties - Add alias properties to the source object for
973  * all qdev properties on the target DeviceState.
974  */
975 void qdev_alias_all_properties(DeviceState *target, Object *source)
976 {
977     ObjectClass *class;
978     Property *prop;
979 
980     class = object_get_class(OBJECT(target));
981     do {
982         DeviceClass *dc = DEVICE_CLASS(class);
983 
984         for (prop = dc->props; prop && prop->name; prop++) {
985             object_property_add_alias(source, prop->name,
986                                       OBJECT(target), prop->name,
987                                       &error_abort);
988         }
989         class = object_class_get_parent(class);
990     } while (class != object_class_by_name(TYPE_DEVICE));
991 }
992 
993 static int qdev_add_hotpluggable_device(Object *obj, void *opaque)
994 {
995     GSList **list = opaque;
996     DeviceState *dev = (DeviceState *)object_dynamic_cast(OBJECT(obj),
997                                                           TYPE_DEVICE);
998 
999     if (dev == NULL) {
1000         return 0;
1001     }
1002 
1003     if (dev->realized && object_property_get_bool(obj, "hotpluggable", NULL)) {
1004         *list = g_slist_append(*list, dev);
1005     }
1006 
1007     return 0;
1008 }
1009 
1010 GSList *qdev_build_hotpluggable_device_list(Object *peripheral)
1011 {
1012     GSList *list = NULL;
1013 
1014     object_child_foreach(peripheral, qdev_add_hotpluggable_device, &list);
1015 
1016     return list;
1017 }
1018 
1019 static bool device_get_realized(Object *obj, Error **errp)
1020 {
1021     DeviceState *dev = DEVICE(obj);
1022     return dev->realized;
1023 }
1024 
1025 static void device_set_realized(Object *obj, bool value, Error **errp)
1026 {
1027     DeviceState *dev = DEVICE(obj);
1028     DeviceClass *dc = DEVICE_GET_CLASS(dev);
1029     HotplugHandler *hotplug_ctrl;
1030     BusState *bus;
1031     Error *local_err = NULL;
1032 
1033     if (dev->hotplugged && !dc->hotpluggable) {
1034         error_set(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj));
1035         return;
1036     }
1037 
1038     if (value && !dev->realized) {
1039         if (!obj->parent) {
1040             static int unattached_count;
1041             gchar *name = g_strdup_printf("device[%d]", unattached_count++);
1042 
1043             object_property_add_child(container_get(qdev_get_machine(),
1044                                                     "/unattached"),
1045                                       name, obj, &error_abort);
1046             g_free(name);
1047         }
1048 
1049         if (dc->realize) {
1050             dc->realize(dev, &local_err);
1051         }
1052 
1053         if (local_err != NULL) {
1054             goto fail;
1055         }
1056 
1057         DEVICE_LISTENER_CALL(realize, Forward, dev);
1058 
1059         hotplug_ctrl = qdev_get_hotplug_handler(dev);
1060         if (hotplug_ctrl) {
1061             hotplug_handler_plug(hotplug_ctrl, dev, &local_err);
1062         }
1063 
1064         if (local_err != NULL) {
1065             goto post_realize_fail;
1066         }
1067 
1068         if (qdev_get_vmsd(dev)) {
1069             vmstate_register_with_alias_id(dev, -1, qdev_get_vmsd(dev), dev,
1070                                            dev->instance_id_alias,
1071                                            dev->alias_required_for_version);
1072         }
1073 
1074         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
1075             object_property_set_bool(OBJECT(bus), true, "realized",
1076                                          &local_err);
1077             if (local_err != NULL) {
1078                 goto child_realize_fail;
1079             }
1080         }
1081         if (dev->hotplugged) {
1082             device_reset(dev);
1083         }
1084         dev->pending_deleted_event = false;
1085     } else if (!value && dev->realized) {
1086         Error **local_errp = NULL;
1087         QLIST_FOREACH(bus, &dev->child_bus, sibling) {
1088             local_errp = local_err ? NULL : &local_err;
1089             object_property_set_bool(OBJECT(bus), false, "realized",
1090                                      local_errp);
1091         }
1092         if (qdev_get_vmsd(dev)) {
1093             vmstate_unregister(dev, qdev_get_vmsd(dev), dev);
1094         }
1095         if (dc->unrealize) {
1096             local_errp = local_err ? NULL : &local_err;
1097             dc->unrealize(dev, local_errp);
1098         }
1099         dev->pending_deleted_event = true;
1100         DEVICE_LISTENER_CALL(unrealize, Reverse, dev);
1101     }
1102 
1103     if (local_err != NULL) {
1104         goto fail;
1105     }
1106 
1107     dev->realized = value;
1108     return;
1109 
1110 child_realize_fail:
1111     QLIST_FOREACH(bus, &dev->child_bus, sibling) {
1112         object_property_set_bool(OBJECT(bus), false, "realized",
1113                                  NULL);
1114     }
1115 
1116     if (qdev_get_vmsd(dev)) {
1117         vmstate_unregister(dev, qdev_get_vmsd(dev), dev);
1118     }
1119 
1120 post_realize_fail:
1121     if (dc->unrealize) {
1122         dc->unrealize(dev, NULL);
1123     }
1124 
1125 fail:
1126     error_propagate(errp, local_err);
1127     return;
1128 }
1129 
1130 static bool device_get_hotpluggable(Object *obj, Error **errp)
1131 {
1132     DeviceClass *dc = DEVICE_GET_CLASS(obj);
1133     DeviceState *dev = DEVICE(obj);
1134 
1135     return dc->hotpluggable && (dev->parent_bus == NULL ||
1136                                 qbus_is_hotpluggable(dev->parent_bus));
1137 }
1138 
1139 static bool device_get_hotplugged(Object *obj, Error **err)
1140 {
1141     DeviceState *dev = DEVICE(obj);
1142 
1143     return dev->hotplugged;
1144 }
1145 
1146 static void device_set_hotplugged(Object *obj, bool value, Error **err)
1147 {
1148     DeviceState *dev = DEVICE(obj);
1149 
1150     dev->hotplugged = value;
1151 }
1152 
1153 static void device_initfn(Object *obj)
1154 {
1155     DeviceState *dev = DEVICE(obj);
1156     ObjectClass *class;
1157     Property *prop;
1158 
1159     if (qdev_hotplug) {
1160         dev->hotplugged = 1;
1161         qdev_hot_added = true;
1162     }
1163 
1164     dev->instance_id_alias = -1;
1165     dev->realized = false;
1166 
1167     object_property_add_bool(obj, "realized",
1168                              device_get_realized, device_set_realized, NULL);
1169     object_property_add_bool(obj, "hotpluggable",
1170                              device_get_hotpluggable, NULL, NULL);
1171     object_property_add_bool(obj, "hotplugged",
1172                              device_get_hotplugged, device_set_hotplugged,
1173                              &error_abort);
1174 
1175     class = object_get_class(OBJECT(dev));
1176     do {
1177         for (prop = DEVICE_CLASS(class)->props; prop && prop->name; prop++) {
1178             qdev_property_add_legacy(dev, prop, &error_abort);
1179             qdev_property_add_static(dev, prop, &error_abort);
1180         }
1181         class = object_class_get_parent(class);
1182     } while (class != object_class_by_name(TYPE_DEVICE));
1183 
1184     object_property_add_link(OBJECT(dev), "parent_bus", TYPE_BUS,
1185                              (Object **)&dev->parent_bus, NULL, 0,
1186                              &error_abort);
1187     QLIST_INIT(&dev->gpios);
1188 }
1189 
1190 static void device_post_init(Object *obj)
1191 {
1192     Error *err = NULL;
1193     qdev_prop_set_globals(DEVICE(obj), &err);
1194     if (err) {
1195         qerror_report_err(err);
1196         error_free(err);
1197         exit(EXIT_FAILURE);
1198     }
1199 }
1200 
1201 /* Unlink device from bus and free the structure.  */
1202 static void device_finalize(Object *obj)
1203 {
1204     NamedGPIOList *ngl, *next;
1205 
1206     DeviceState *dev = DEVICE(obj);
1207     qemu_opts_del(dev->opts);
1208 
1209     QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) {
1210         QLIST_REMOVE(ngl, node);
1211         qemu_free_irqs(ngl->in, ngl->num_in);
1212         g_free(ngl->name);
1213         g_free(ngl);
1214         /* ngl->out irqs are owned by the other end and should not be freed
1215          * here
1216          */
1217     }
1218 }
1219 
1220 static void device_class_base_init(ObjectClass *class, void *data)
1221 {
1222     DeviceClass *klass = DEVICE_CLASS(class);
1223 
1224     /* We explicitly look up properties in the superclasses,
1225      * so do not propagate them to the subclasses.
1226      */
1227     klass->props = NULL;
1228 }
1229 
1230 static void device_unparent(Object *obj)
1231 {
1232     DeviceState *dev = DEVICE(obj);
1233     BusState *bus;
1234 
1235     if (dev->realized) {
1236         object_property_set_bool(obj, false, "realized", NULL);
1237     }
1238     while (dev->num_child_bus) {
1239         bus = QLIST_FIRST(&dev->child_bus);
1240         object_unparent(OBJECT(bus));
1241     }
1242     if (dev->parent_bus) {
1243         bus_remove_child(dev->parent_bus, dev);
1244         object_unref(OBJECT(dev->parent_bus));
1245         dev->parent_bus = NULL;
1246     }
1247 
1248     /* Only send event if the device had been completely realized */
1249     if (dev->pending_deleted_event) {
1250         gchar *path = object_get_canonical_path(OBJECT(dev));
1251 
1252         qapi_event_send_device_deleted(!!dev->id, dev->id, path, &error_abort);
1253         g_free(path);
1254     }
1255 }
1256 
1257 static void device_class_init(ObjectClass *class, void *data)
1258 {
1259     DeviceClass *dc = DEVICE_CLASS(class);
1260 
1261     class->unparent = device_unparent;
1262     dc->realize = device_realize;
1263     dc->unrealize = device_unrealize;
1264 
1265     /* by default all devices were considered as hotpluggable,
1266      * so with intent to check it in generic qdev_unplug() /
1267      * device_set_realized() functions make every device
1268      * hotpluggable. Devices that shouldn't be hotpluggable,
1269      * should override it in their class_init()
1270      */
1271     dc->hotpluggable = true;
1272 }
1273 
1274 void device_reset(DeviceState *dev)
1275 {
1276     DeviceClass *klass = DEVICE_GET_CLASS(dev);
1277 
1278     if (klass->reset) {
1279         klass->reset(dev);
1280     }
1281 }
1282 
1283 Object *qdev_get_machine(void)
1284 {
1285     static Object *dev;
1286 
1287     if (dev == NULL) {
1288         dev = container_get(object_get_root(), "/machine");
1289     }
1290 
1291     return dev;
1292 }
1293 
1294 static const TypeInfo device_type_info = {
1295     .name = TYPE_DEVICE,
1296     .parent = TYPE_OBJECT,
1297     .instance_size = sizeof(DeviceState),
1298     .instance_init = device_initfn,
1299     .instance_post_init = device_post_init,
1300     .instance_finalize = device_finalize,
1301     .class_base_init = device_class_base_init,
1302     .class_init = device_class_init,
1303     .abstract = true,
1304     .class_size = sizeof(DeviceClass),
1305 };
1306 
1307 static void qbus_initfn(Object *obj)
1308 {
1309     BusState *bus = BUS(obj);
1310 
1311     QTAILQ_INIT(&bus->children);
1312     object_property_add_link(obj, QDEV_HOTPLUG_HANDLER_PROPERTY,
1313                              TYPE_HOTPLUG_HANDLER,
1314                              (Object **)&bus->hotplug_handler,
1315                              object_property_allow_set_link,
1316                              OBJ_PROP_LINK_UNREF_ON_RELEASE,
1317                              NULL);
1318     object_property_add_bool(obj, "realized",
1319                              bus_get_realized, bus_set_realized, NULL);
1320 }
1321 
1322 static char *default_bus_get_fw_dev_path(DeviceState *dev)
1323 {
1324     return g_strdup(object_get_typename(OBJECT(dev)));
1325 }
1326 
1327 static void bus_class_init(ObjectClass *class, void *data)
1328 {
1329     BusClass *bc = BUS_CLASS(class);
1330 
1331     class->unparent = bus_unparent;
1332     bc->get_fw_dev_path = default_bus_get_fw_dev_path;
1333 }
1334 
1335 static void qbus_finalize(Object *obj)
1336 {
1337     BusState *bus = BUS(obj);
1338 
1339     g_free((char *)bus->name);
1340 }
1341 
1342 static const TypeInfo bus_info = {
1343     .name = TYPE_BUS,
1344     .parent = TYPE_OBJECT,
1345     .instance_size = sizeof(BusState),
1346     .abstract = true,
1347     .class_size = sizeof(BusClass),
1348     .instance_init = qbus_initfn,
1349     .instance_finalize = qbus_finalize,
1350     .class_init = bus_class_init,
1351 };
1352 
1353 static void qdev_register_types(void)
1354 {
1355     type_register_static(&bus_info);
1356     type_register_static(&device_type_info);
1357 }
1358 
1359 type_init(qdev_register_types)
1360