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