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