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