xref: /qemu/system/qdev-monitor.c (revision 159fb790)
1 /*
2  *  Dynamic device configuration and creation.
3  *
4  *  Copyright (c) 2009 CodeSourcery
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "hw/sysbus.h"
22 #include "monitor/hmp.h"
23 #include "monitor/monitor.h"
24 #include "monitor/qdev.h"
25 #include "sysemu/arch_init.h"
26 #include "qapi/error.h"
27 #include "qapi/qapi-commands-qdev.h"
28 #include "qapi/qmp/dispatch.h"
29 #include "qapi/qmp/qdict.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qstring.h"
32 #include "qapi/qobject-input-visitor.h"
33 #include "qemu/config-file.h"
34 #include "qemu/error-report.h"
35 #include "qemu/help_option.h"
36 #include "qemu/option.h"
37 #include "qemu/qemu-print.h"
38 #include "qemu/option_int.h"
39 #include "sysemu/block-backend.h"
40 #include "migration/misc.h"
41 #include "qemu/cutils.h"
42 #include "hw/qdev-properties.h"
43 #include "hw/clock.h"
44 #include "hw/boards.h"
45 
46 /*
47  * Aliases were a bad idea from the start.  Let's keep them
48  * from spreading further.
49  */
50 typedef struct QDevAlias
51 {
52     const char *typename;
53     const char *alias;
54     uint32_t arch_mask;
55 } QDevAlias;
56 
57 /* default virtio transport per architecture */
58 #define QEMU_ARCH_VIRTIO_PCI (QEMU_ARCH_ALPHA | QEMU_ARCH_ARM | \
59                               QEMU_ARCH_HPPA | QEMU_ARCH_I386 | \
60                               QEMU_ARCH_MIPS | QEMU_ARCH_PPC |  \
61                               QEMU_ARCH_RISCV | QEMU_ARCH_SH4 | \
62                               QEMU_ARCH_SPARC | QEMU_ARCH_XTENSA | \
63                               QEMU_ARCH_LOONGARCH)
64 #define QEMU_ARCH_VIRTIO_CCW (QEMU_ARCH_S390X)
65 #define QEMU_ARCH_VIRTIO_MMIO (QEMU_ARCH_M68K)
66 
67 /* Please keep this table sorted by typename. */
68 static const QDevAlias qdev_alias_table[] = {
69     { "AC97", "ac97" }, /* -soundhw name */
70     { "e1000", "e1000-82540em" },
71     { "ES1370", "es1370" }, /* -soundhw name */
72     { "ich9-ahci", "ahci" },
73     { "lsi53c895a", "lsi" },
74     { "virtio-9p-device", "virtio-9p", QEMU_ARCH_VIRTIO_MMIO },
75     { "virtio-9p-ccw", "virtio-9p", QEMU_ARCH_VIRTIO_CCW },
76     { "virtio-9p-pci", "virtio-9p", QEMU_ARCH_VIRTIO_PCI },
77     { "virtio-balloon-device", "virtio-balloon", QEMU_ARCH_VIRTIO_MMIO },
78     { "virtio-balloon-ccw", "virtio-balloon", QEMU_ARCH_VIRTIO_CCW },
79     { "virtio-balloon-pci", "virtio-balloon", QEMU_ARCH_VIRTIO_PCI },
80     { "virtio-blk-device", "virtio-blk", QEMU_ARCH_VIRTIO_MMIO },
81     { "virtio-blk-ccw", "virtio-blk", QEMU_ARCH_VIRTIO_CCW },
82     { "virtio-blk-pci", "virtio-blk", QEMU_ARCH_VIRTIO_PCI },
83     { "virtio-gpu-device", "virtio-gpu", QEMU_ARCH_VIRTIO_MMIO },
84     { "virtio-gpu-ccw", "virtio-gpu", QEMU_ARCH_VIRTIO_CCW },
85     { "virtio-gpu-pci", "virtio-gpu", QEMU_ARCH_VIRTIO_PCI },
86     { "virtio-gpu-gl-device", "virtio-gpu-gl", QEMU_ARCH_VIRTIO_MMIO },
87     { "virtio-gpu-gl-pci", "virtio-gpu-gl", QEMU_ARCH_VIRTIO_PCI },
88     { "virtio-gpu-rutabaga-device", "virtio-gpu-rutabaga",
89       QEMU_ARCH_VIRTIO_MMIO },
90     { "virtio-gpu-rutabaga-pci", "virtio-gpu-rutabaga", QEMU_ARCH_VIRTIO_PCI },
91     { "virtio-input-host-device", "virtio-input-host", QEMU_ARCH_VIRTIO_MMIO },
92     { "virtio-input-host-ccw", "virtio-input-host", QEMU_ARCH_VIRTIO_CCW },
93     { "virtio-input-host-pci", "virtio-input-host", QEMU_ARCH_VIRTIO_PCI },
94     { "virtio-iommu-pci", "virtio-iommu", QEMU_ARCH_VIRTIO_PCI },
95     { "virtio-keyboard-device", "virtio-keyboard", QEMU_ARCH_VIRTIO_MMIO },
96     { "virtio-keyboard-ccw", "virtio-keyboard", QEMU_ARCH_VIRTIO_CCW },
97     { "virtio-keyboard-pci", "virtio-keyboard", QEMU_ARCH_VIRTIO_PCI },
98     { "virtio-mouse-device", "virtio-mouse", QEMU_ARCH_VIRTIO_MMIO },
99     { "virtio-mouse-ccw", "virtio-mouse", QEMU_ARCH_VIRTIO_CCW },
100     { "virtio-mouse-pci", "virtio-mouse", QEMU_ARCH_VIRTIO_PCI },
101     { "virtio-net-device", "virtio-net", QEMU_ARCH_VIRTIO_MMIO },
102     { "virtio-net-ccw", "virtio-net", QEMU_ARCH_VIRTIO_CCW },
103     { "virtio-net-pci", "virtio-net", QEMU_ARCH_VIRTIO_PCI },
104     { "virtio-rng-device", "virtio-rng", QEMU_ARCH_VIRTIO_MMIO },
105     { "virtio-rng-ccw", "virtio-rng", QEMU_ARCH_VIRTIO_CCW },
106     { "virtio-rng-pci", "virtio-rng", QEMU_ARCH_VIRTIO_PCI },
107     { "virtio-scsi-device", "virtio-scsi", QEMU_ARCH_VIRTIO_MMIO },
108     { "virtio-scsi-ccw", "virtio-scsi", QEMU_ARCH_VIRTIO_CCW },
109     { "virtio-scsi-pci", "virtio-scsi", QEMU_ARCH_VIRTIO_PCI },
110     { "virtio-serial-device", "virtio-serial", QEMU_ARCH_VIRTIO_MMIO },
111     { "virtio-serial-ccw", "virtio-serial", QEMU_ARCH_VIRTIO_CCW },
112     { "virtio-serial-pci", "virtio-serial", QEMU_ARCH_VIRTIO_PCI},
113     { "virtio-sound-device", "virtio-sound", QEMU_ARCH_VIRTIO_MMIO },
114     { "virtio-sound-pci", "virtio-sound", QEMU_ARCH_VIRTIO_PCI },
115     { "virtio-tablet-device", "virtio-tablet", QEMU_ARCH_VIRTIO_MMIO },
116     { "virtio-tablet-ccw", "virtio-tablet", QEMU_ARCH_VIRTIO_CCW },
117     { "virtio-tablet-pci", "virtio-tablet", QEMU_ARCH_VIRTIO_PCI },
118     { }
119 };
120 
121 static const char *qdev_class_get_alias(DeviceClass *dc)
122 {
123     const char *typename = object_class_get_name(OBJECT_CLASS(dc));
124     int i;
125 
126     for (i = 0; qdev_alias_table[i].typename; i++) {
127         if (qdev_alias_table[i].arch_mask &&
128             !(qdev_alias_table[i].arch_mask & arch_type)) {
129             continue;
130         }
131 
132         if (strcmp(qdev_alias_table[i].typename, typename) == 0) {
133             return qdev_alias_table[i].alias;
134         }
135     }
136 
137     return NULL;
138 }
139 
140 static bool qdev_class_has_alias(DeviceClass *dc)
141 {
142     return (qdev_class_get_alias(dc) != NULL);
143 }
144 
145 static void qdev_print_devinfo(DeviceClass *dc)
146 {
147     qemu_printf("name \"%s\"", object_class_get_name(OBJECT_CLASS(dc)));
148     if (dc->bus_type) {
149         qemu_printf(", bus %s", dc->bus_type);
150     }
151     if (qdev_class_has_alias(dc)) {
152         qemu_printf(", alias \"%s\"", qdev_class_get_alias(dc));
153     }
154     if (dc->desc) {
155         qemu_printf(", desc \"%s\"", dc->desc);
156     }
157     if (!dc->user_creatable) {
158         qemu_printf(", no-user");
159     }
160     qemu_printf("\n");
161 }
162 
163 static void qdev_print_devinfos(bool show_no_user)
164 {
165     static const char *cat_name[DEVICE_CATEGORY_MAX + 1] = {
166         [DEVICE_CATEGORY_BRIDGE]  = "Controller/Bridge/Hub",
167         [DEVICE_CATEGORY_USB]     = "USB",
168         [DEVICE_CATEGORY_STORAGE] = "Storage",
169         [DEVICE_CATEGORY_NETWORK] = "Network",
170         [DEVICE_CATEGORY_INPUT]   = "Input",
171         [DEVICE_CATEGORY_DISPLAY] = "Display",
172         [DEVICE_CATEGORY_SOUND]   = "Sound",
173         [DEVICE_CATEGORY_MISC]    = "Misc",
174         [DEVICE_CATEGORY_CPU]     = "CPU",
175         [DEVICE_CATEGORY_WATCHDOG]= "Watchdog",
176         [DEVICE_CATEGORY_MAX]     = "Uncategorized",
177     };
178     GSList *list, *elt;
179     int i;
180     bool cat_printed;
181 
182     module_load_qom_all();
183     list = object_class_get_list_sorted(TYPE_DEVICE, false);
184 
185     for (i = 0; i <= DEVICE_CATEGORY_MAX; i++) {
186         cat_printed = false;
187         for (elt = list; elt; elt = elt->next) {
188             DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
189                                                  TYPE_DEVICE);
190             if ((i < DEVICE_CATEGORY_MAX
191                  ? !test_bit(i, dc->categories)
192                  : !bitmap_empty(dc->categories, DEVICE_CATEGORY_MAX))
193                 || (!show_no_user
194                     && !dc->user_creatable)) {
195                 continue;
196             }
197             if (!cat_printed) {
198                 qemu_printf("%s%s devices:\n", i ? "\n" : "", cat_name[i]);
199                 cat_printed = true;
200             }
201             qdev_print_devinfo(dc);
202         }
203     }
204 
205     g_slist_free(list);
206 }
207 
208 static const char *find_typename_by_alias(const char *alias)
209 {
210     int i;
211 
212     for (i = 0; qdev_alias_table[i].alias; i++) {
213         if (qdev_alias_table[i].arch_mask &&
214             !(qdev_alias_table[i].arch_mask & arch_type)) {
215             continue;
216         }
217 
218         if (strcmp(qdev_alias_table[i].alias, alias) == 0) {
219             return qdev_alias_table[i].typename;
220         }
221     }
222 
223     return NULL;
224 }
225 
226 static DeviceClass *qdev_get_device_class(const char **driver, Error **errp)
227 {
228     ObjectClass *oc;
229     DeviceClass *dc;
230     const char *original_name = *driver;
231 
232     oc = module_object_class_by_name(*driver);
233     if (!oc) {
234         const char *typename = find_typename_by_alias(*driver);
235 
236         if (typename) {
237             *driver = typename;
238             oc = module_object_class_by_name(*driver);
239         }
240     }
241 
242     if (!object_class_dynamic_cast(oc, TYPE_DEVICE)) {
243         if (*driver != original_name) {
244             error_setg(errp, "'%s' (alias '%s') is not a valid device model"
245                        " name", original_name, *driver);
246         } else {
247             error_setg(errp, "'%s' is not a valid device model name", *driver);
248         }
249         return NULL;
250     }
251 
252     if (object_class_is_abstract(oc)) {
253         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
254                    "a non-abstract device type");
255         return NULL;
256     }
257 
258     dc = DEVICE_CLASS(oc);
259     if (!dc->user_creatable ||
260         (phase_check(PHASE_MACHINE_READY) && !dc->hotpluggable)) {
261         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
262                    "a pluggable device type");
263         return NULL;
264     }
265 
266     if (object_class_dynamic_cast(oc, TYPE_SYS_BUS_DEVICE)) {
267         /* sysbus devices need to be allowed by the machine */
268         MachineClass *mc = MACHINE_CLASS(object_get_class(qdev_get_machine()));
269         if (!device_type_is_dynamic_sysbus(mc, *driver)) {
270             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
271                        "a dynamic sysbus device type for the machine");
272             return NULL;
273         }
274     }
275 
276     return dc;
277 }
278 
279 
280 int qdev_device_help(QemuOpts *opts)
281 {
282     Error *local_err = NULL;
283     const char *driver;
284     ObjectPropertyInfoList *prop_list;
285     ObjectPropertyInfoList *prop;
286     GPtrArray *array;
287     int i;
288 
289     driver = qemu_opt_get(opts, "driver");
290     if (driver && is_help_option(driver)) {
291         qdev_print_devinfos(false);
292         return 1;
293     }
294 
295     if (!driver || !qemu_opt_has_help_opt(opts)) {
296         return 0;
297     }
298 
299     if (!object_class_by_name(driver)) {
300         const char *typename = find_typename_by_alias(driver);
301 
302         if (typename) {
303             driver = typename;
304         }
305     }
306 
307     prop_list = qmp_device_list_properties(driver, &local_err);
308     if (local_err) {
309         goto error;
310     }
311 
312     if (prop_list) {
313         qemu_printf("%s options:\n", driver);
314     } else {
315         qemu_printf("There are no options for %s.\n", driver);
316     }
317     array = g_ptr_array_new();
318     for (prop = prop_list; prop; prop = prop->next) {
319         g_ptr_array_add(array,
320                         object_property_help(prop->value->name,
321                                              prop->value->type,
322                                              prop->value->default_value,
323                                              prop->value->description));
324     }
325     g_ptr_array_sort(array, (GCompareFunc)qemu_pstrcmp0);
326     for (i = 0; i < array->len; i++) {
327         qemu_printf("%s\n", (char *)array->pdata[i]);
328     }
329     g_ptr_array_set_free_func(array, g_free);
330     g_ptr_array_free(array, true);
331     qapi_free_ObjectPropertyInfoList(prop_list);
332     return 1;
333 
334 error:
335     error_report_err(local_err);
336     return 1;
337 }
338 
339 static Object *qdev_get_peripheral(void)
340 {
341     static Object *dev;
342 
343     if (dev == NULL) {
344         dev = container_get(qdev_get_machine(), "/peripheral");
345     }
346 
347     return dev;
348 }
349 
350 static Object *qdev_get_peripheral_anon(void)
351 {
352     static Object *dev;
353 
354     if (dev == NULL) {
355         dev = container_get(qdev_get_machine(), "/peripheral-anon");
356     }
357 
358     return dev;
359 }
360 
361 static void qbus_error_append_bus_list_hint(DeviceState *dev,
362                                             Error *const *errp)
363 {
364     BusState *child;
365     const char *sep = " ";
366 
367     error_append_hint(errp, "child buses at \"%s\":",
368                       dev->id ? dev->id : object_get_typename(OBJECT(dev)));
369     QLIST_FOREACH(child, &dev->child_bus, sibling) {
370         error_append_hint(errp, "%s\"%s\"", sep, child->name);
371         sep = ", ";
372     }
373     error_append_hint(errp, "\n");
374 }
375 
376 static void qbus_error_append_dev_list_hint(BusState *bus,
377                                             Error *const *errp)
378 {
379     BusChild *kid;
380     const char *sep = " ";
381 
382     error_append_hint(errp, "devices at \"%s\":", bus->name);
383     QTAILQ_FOREACH(kid, &bus->children, sibling) {
384         DeviceState *dev = kid->child;
385         error_append_hint(errp, "%s\"%s\"", sep,
386                           object_get_typename(OBJECT(dev)));
387         if (dev->id) {
388             error_append_hint(errp, "/\"%s\"", dev->id);
389         }
390         sep = ", ";
391     }
392     error_append_hint(errp, "\n");
393 }
394 
395 static BusState *qbus_find_bus(DeviceState *dev, char *elem)
396 {
397     BusState *child;
398 
399     QLIST_FOREACH(child, &dev->child_bus, sibling) {
400         if (strcmp(child->name, elem) == 0) {
401             return child;
402         }
403     }
404     return NULL;
405 }
406 
407 static DeviceState *qbus_find_dev(BusState *bus, char *elem)
408 {
409     BusChild *kid;
410 
411     /*
412      * try to match in order:
413      *   (1) instance id, if present
414      *   (2) driver name
415      *   (3) driver alias, if present
416      */
417     QTAILQ_FOREACH(kid, &bus->children, sibling) {
418         DeviceState *dev = kid->child;
419         if (dev->id  &&  strcmp(dev->id, elem) == 0) {
420             return dev;
421         }
422     }
423     QTAILQ_FOREACH(kid, &bus->children, sibling) {
424         DeviceState *dev = kid->child;
425         if (strcmp(object_get_typename(OBJECT(dev)), elem) == 0) {
426             return dev;
427         }
428     }
429     QTAILQ_FOREACH(kid, &bus->children, sibling) {
430         DeviceState *dev = kid->child;
431         DeviceClass *dc = DEVICE_GET_CLASS(dev);
432 
433         if (qdev_class_has_alias(dc) &&
434             strcmp(qdev_class_get_alias(dc), elem) == 0) {
435             return dev;
436         }
437     }
438     return NULL;
439 }
440 
441 static inline bool qbus_is_full(BusState *bus)
442 {
443     BusClass *bus_class;
444 
445     if (bus->full) {
446         return true;
447     }
448     bus_class = BUS_GET_CLASS(bus);
449     return bus_class->max_dev && bus->num_children >= bus_class->max_dev;
450 }
451 
452 /*
453  * Search the tree rooted at @bus for a bus.
454  * If @name, search for a bus with that name.  Note that bus names
455  * need not be unique.  Yes, that's screwed up.
456  * Else search for a bus that is a subtype of @bus_typename.
457  * If more than one exists, prefer one that can take another device.
458  * Return the bus if found, else %NULL.
459  */
460 static BusState *qbus_find_recursive(BusState *bus, const char *name,
461                                      const char *bus_typename)
462 {
463     BusChild *kid;
464     BusState *pick, *child, *ret;
465     bool match;
466 
467     assert(name || bus_typename);
468     if (name) {
469         match = !strcmp(bus->name, name);
470     } else {
471         match = !!object_dynamic_cast(OBJECT(bus), bus_typename);
472     }
473 
474     if (match && !qbus_is_full(bus)) {
475         return bus;             /* root matches and isn't full */
476     }
477 
478     pick = match ? bus : NULL;
479 
480     QTAILQ_FOREACH(kid, &bus->children, sibling) {
481         DeviceState *dev = kid->child;
482         QLIST_FOREACH(child, &dev->child_bus, sibling) {
483             ret = qbus_find_recursive(child, name, bus_typename);
484             if (ret && !qbus_is_full(ret)) {
485                 return ret;     /* a descendant matches and isn't full */
486             }
487             if (ret && !pick) {
488                 pick = ret;
489             }
490         }
491     }
492 
493     /* root or a descendant matches, but is full */
494     return pick;
495 }
496 
497 static BusState *qbus_find(const char *path, Error **errp)
498 {
499     DeviceState *dev;
500     BusState *bus;
501     char elem[128];
502     int pos, len;
503 
504     /* find start element */
505     if (path[0] == '/') {
506         bus = sysbus_get_default();
507         pos = 0;
508     } else {
509         if (sscanf(path, "%127[^/]%n", elem, &len) != 1) {
510             assert(!path[0]);
511             elem[0] = len = 0;
512         }
513         bus = qbus_find_recursive(sysbus_get_default(), elem, NULL);
514         if (!bus) {
515             error_setg(errp, "Bus '%s' not found", elem);
516             return NULL;
517         }
518         pos = len;
519     }
520 
521     for (;;) {
522         assert(path[pos] == '/' || !path[pos]);
523         while (path[pos] == '/') {
524             pos++;
525         }
526         if (path[pos] == '\0') {
527             break;
528         }
529 
530         /* find device */
531         if (sscanf(path+pos, "%127[^/]%n", elem, &len) != 1) {
532             g_assert_not_reached();
533             elem[0] = len = 0;
534         }
535         pos += len;
536         dev = qbus_find_dev(bus, elem);
537         if (!dev) {
538             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
539                       "Device '%s' not found", elem);
540             qbus_error_append_dev_list_hint(bus, errp);
541             return NULL;
542         }
543 
544         assert(path[pos] == '/' || !path[pos]);
545         while (path[pos] == '/') {
546             pos++;
547         }
548         if (path[pos] == '\0') {
549             /* last specified element is a device.  If it has exactly
550              * one child bus accept it nevertheless */
551             if (dev->num_child_bus == 1) {
552                 bus = QLIST_FIRST(&dev->child_bus);
553                 break;
554             }
555             if (dev->num_child_bus) {
556                 error_setg(errp, "Device '%s' has multiple child buses",
557                            elem);
558                 qbus_error_append_bus_list_hint(dev, errp);
559             } else {
560                 error_setg(errp, "Device '%s' has no child bus", elem);
561             }
562             return NULL;
563         }
564 
565         /* find bus */
566         if (sscanf(path+pos, "%127[^/]%n", elem, &len) != 1) {
567             g_assert_not_reached();
568             elem[0] = len = 0;
569         }
570         pos += len;
571         bus = qbus_find_bus(dev, elem);
572         if (!bus) {
573             error_setg(errp, "Bus '%s' not found", elem);
574             qbus_error_append_bus_list_hint(dev, errp);
575             return NULL;
576         }
577     }
578 
579     if (qbus_is_full(bus)) {
580         error_setg(errp, "Bus '%s' is full", path);
581         return NULL;
582     }
583     return bus;
584 }
585 
586 /* Takes ownership of @id, will be freed when deleting the device */
587 const char *qdev_set_id(DeviceState *dev, char *id, Error **errp)
588 {
589     ObjectProperty *prop;
590 
591     assert(!dev->id && !dev->realized);
592 
593     /*
594      * object_property_[try_]add_child() below will assert the device
595      * has no parent
596      */
597     if (id) {
598         prop = object_property_try_add_child(qdev_get_peripheral(), id,
599                                              OBJECT(dev), NULL);
600         if (prop) {
601             dev->id = id;
602         } else {
603             error_setg(errp, "Duplicate device ID '%s'", id);
604             g_free(id);
605             return NULL;
606         }
607     } else {
608         static int anon_count;
609         gchar *name = g_strdup_printf("device[%d]", anon_count++);
610         prop = object_property_add_child(qdev_get_peripheral_anon(), name,
611                                          OBJECT(dev));
612         g_free(name);
613     }
614 
615     return prop->name;
616 }
617 
618 DeviceState *qdev_device_add_from_qdict(const QDict *opts,
619                                         bool from_json, Error **errp)
620 {
621     ERRP_GUARD();
622     DeviceClass *dc;
623     const char *driver, *path;
624     char *id;
625     DeviceState *dev = NULL;
626     BusState *bus = NULL;
627 
628     driver = qdict_get_try_str(opts, "driver");
629     if (!driver) {
630         error_setg(errp, QERR_MISSING_PARAMETER, "driver");
631         return NULL;
632     }
633 
634     /* find driver */
635     dc = qdev_get_device_class(&driver, errp);
636     if (!dc) {
637         return NULL;
638     }
639 
640     /* find bus */
641     path = qdict_get_try_str(opts, "bus");
642     if (path != NULL) {
643         bus = qbus_find(path, errp);
644         if (!bus) {
645             return NULL;
646         }
647         if (!object_dynamic_cast(OBJECT(bus), dc->bus_type)) {
648             error_setg(errp, "Device '%s' can't go on %s bus",
649                        driver, object_get_typename(OBJECT(bus)));
650             return NULL;
651         }
652     } else if (dc->bus_type != NULL) {
653         bus = qbus_find_recursive(sysbus_get_default(), NULL, dc->bus_type);
654         if (!bus || qbus_is_full(bus)) {
655             error_setg(errp, "No '%s' bus found for device '%s'",
656                        dc->bus_type, driver);
657             return NULL;
658         }
659     }
660 
661     if (qdev_should_hide_device(opts, from_json, errp)) {
662         if (bus && !qbus_is_hotpluggable(bus)) {
663             error_setg(errp, "Bus '%s' does not support hotplugging",
664                        bus->name);
665         }
666         return NULL;
667     } else if (*errp) {
668         return NULL;
669     }
670 
671     if (phase_check(PHASE_MACHINE_READY) && bus && !qbus_is_hotpluggable(bus)) {
672         error_setg(errp, "Bus '%s' does not support hotplugging", bus->name);
673         return NULL;
674     }
675 
676     if (!migration_is_idle()) {
677         error_setg(errp, "device_add not allowed while migrating");
678         return NULL;
679     }
680 
681     /* create device */
682     dev = qdev_new(driver);
683 
684     /* Check whether the hotplug is allowed by the machine */
685     if (phase_check(PHASE_MACHINE_READY)) {
686         if (!qdev_hotplug_allowed(dev, errp)) {
687             goto err_del_dev;
688         }
689 
690         if (!bus && !qdev_get_machine_hotplug_handler(dev)) {
691             /* No bus, no machine hotplug handler --> device is not hotpluggable */
692             error_setg(errp, "Device '%s' can not be hotplugged on this machine",
693                        driver);
694             goto err_del_dev;
695         }
696     }
697 
698     /*
699      * set dev's parent and register its id.
700      * If it fails it means the id is already taken.
701      */
702     id = g_strdup(qdict_get_try_str(opts, "id"));
703     if (!qdev_set_id(dev, id, errp)) {
704         goto err_del_dev;
705     }
706 
707     /* set properties */
708     dev->opts = qdict_clone_shallow(opts);
709     qdict_del(dev->opts, "driver");
710     qdict_del(dev->opts, "bus");
711     qdict_del(dev->opts, "id");
712 
713     object_set_properties_from_keyval(&dev->parent_obj, dev->opts, from_json,
714                                       errp);
715     if (*errp) {
716         goto err_del_dev;
717     }
718 
719     if (!qdev_realize(dev, bus, errp)) {
720         goto err_del_dev;
721     }
722     return dev;
723 
724 err_del_dev:
725     if (dev) {
726         object_unparent(OBJECT(dev));
727         object_unref(OBJECT(dev));
728     }
729     return NULL;
730 }
731 
732 /* Takes ownership of @opts on success */
733 DeviceState *qdev_device_add(QemuOpts *opts, Error **errp)
734 {
735     QDict *qdict = qemu_opts_to_qdict(opts, NULL);
736     DeviceState *ret;
737 
738     ret = qdev_device_add_from_qdict(qdict, false, errp);
739     if (ret) {
740         qemu_opts_del(opts);
741     }
742     qobject_unref(qdict);
743     return ret;
744 }
745 
746 #define qdev_printf(fmt, ...) monitor_printf(mon, "%*s" fmt, indent, "", ## __VA_ARGS__)
747 
748 static void qdev_print_props(Monitor *mon, DeviceState *dev, Property *props,
749                              int indent)
750 {
751     if (!props)
752         return;
753     for (; props->name; props++) {
754         char *value;
755         char *legacy_name = g_strdup_printf("legacy-%s", props->name);
756 
757         if (object_property_get_type(OBJECT(dev), legacy_name, NULL)) {
758             value = object_property_get_str(OBJECT(dev), legacy_name, NULL);
759         } else {
760             value = object_property_print(OBJECT(dev), props->name, true,
761                                           NULL);
762         }
763         g_free(legacy_name);
764 
765         if (!value) {
766             continue;
767         }
768         qdev_printf("%s = %s\n", props->name,
769                     *value ? value : "<null>");
770         g_free(value);
771     }
772 }
773 
774 static void bus_print_dev(BusState *bus, Monitor *mon, DeviceState *dev, int indent)
775 {
776     BusClass *bc = BUS_GET_CLASS(bus);
777 
778     if (bc->print_dev) {
779         bc->print_dev(mon, dev, indent);
780     }
781 }
782 
783 static void qdev_print(Monitor *mon, DeviceState *dev, int indent)
784 {
785     ObjectClass *class;
786     NamedGPIOList *ngl;
787     NamedClockList *ncl;
788 
789     QLIST_FOREACH(ngl, &dev->gpios, node) {
790         if (ngl->num_in) {
791             qdev_printf("gpio-in \"%s\" %d\n", ngl->name ? ngl->name : "",
792                         ngl->num_in);
793         }
794         if (ngl->num_out) {
795             qdev_printf("gpio-out \"%s\" %d\n", ngl->name ? ngl->name : "",
796                         ngl->num_out);
797         }
798     }
799     QLIST_FOREACH(ncl, &dev->clocks, node) {
800         g_autofree char *freq_str = clock_display_freq(ncl->clock);
801         qdev_printf("clock-%s%s \"%s\" freq_hz=%s\n",
802                     ncl->output ? "out" : "in",
803                     ncl->alias ? " (alias)" : "",
804                     ncl->name, freq_str);
805     }
806     class = object_get_class(OBJECT(dev));
807     do {
808         qdev_print_props(mon, dev, DEVICE_CLASS(class)->props_, indent);
809         class = object_class_get_parent(class);
810     } while (class != object_class_by_name(TYPE_DEVICE));
811     bus_print_dev(dev->parent_bus, mon, dev, indent);
812 }
813 
814 static void qbus_print(Monitor *mon, BusState *bus, int indent, bool details)
815 {
816     BusChild *kid;
817 
818     qdev_printf("bus: %s\n", bus->name);
819     indent += 2;
820     qdev_printf("type %s\n", object_get_typename(OBJECT(bus)));
821     QTAILQ_FOREACH(kid, &bus->children, sibling) {
822         BusState *child_bus;
823         DeviceState *dev = kid->child;
824         qdev_printf("dev: %s, id \"%s\"\n", object_get_typename(OBJECT(dev)),
825                     dev->id ? dev->id : "");
826         if (details) {
827             qdev_print(mon, dev, indent + 2);
828         }
829         QLIST_FOREACH(child_bus, &dev->child_bus, sibling) {
830             qbus_print(mon, child_bus, indent + 2, details);
831         }
832     }
833 }
834 #undef qdev_printf
835 
836 void hmp_info_qtree(Monitor *mon, const QDict *qdict)
837 {
838     bool details = !qdict_get_try_bool(qdict, "brief", false);
839 
840     if (sysbus_get_default()) {
841         qbus_print(mon, sysbus_get_default(), 0, details);
842     }
843 }
844 
845 void hmp_info_qdm(Monitor *mon, const QDict *qdict)
846 {
847     qdev_print_devinfos(true);
848 }
849 
850 void qmp_device_add(QDict *qdict, QObject **ret_data, Error **errp)
851 {
852     QemuOpts *opts;
853     DeviceState *dev;
854 
855     opts = qemu_opts_from_qdict(qemu_find_opts("device"), qdict, errp);
856     if (!opts) {
857         return;
858     }
859     if (!monitor_cur_is_qmp() && qdev_device_help(opts)) {
860         qemu_opts_del(opts);
861         return;
862     }
863     dev = qdev_device_add(opts, errp);
864     if (!dev) {
865         /*
866          * Drain all pending RCU callbacks. This is done because
867          * some bus related operations can delay a device removal
868          * (in this case this can happen if device is added and then
869          * removed due to a configuration error)
870          * to a RCU callback, but user might expect that this interface
871          * will finish its job completely once qmp command returns result
872          * to the user
873          */
874         drain_call_rcu();
875 
876         qemu_opts_del(opts);
877         return;
878     }
879     object_unref(OBJECT(dev));
880 }
881 
882 static DeviceState *find_device_state(const char *id, Error **errp)
883 {
884     Object *obj = object_resolve_path_at(qdev_get_peripheral(), id);
885     DeviceState *dev;
886 
887     if (!obj) {
888         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
889                   "Device '%s' not found", id);
890         return NULL;
891     }
892 
893     dev = (DeviceState *)object_dynamic_cast(obj, TYPE_DEVICE);
894     if (!dev) {
895         error_setg(errp, "%s is not a device", id);
896         return NULL;
897     }
898 
899     return dev;
900 }
901 
902 void qdev_unplug(DeviceState *dev, Error **errp)
903 {
904     DeviceClass *dc = DEVICE_GET_CLASS(dev);
905     HotplugHandler *hotplug_ctrl;
906     HotplugHandlerClass *hdc;
907     Error *local_err = NULL;
908 
909     if (qdev_unplug_blocked(dev, errp)) {
910         return;
911     }
912 
913     if (dev->parent_bus && !qbus_is_hotpluggable(dev->parent_bus)) {
914         error_setg(errp, "Bus '%s' does not support hotplugging",
915                    dev->parent_bus->name);
916         return;
917     }
918 
919     if (!dc->hotpluggable) {
920         error_setg(errp, "Device '%s' does not support hotplugging",
921                    object_get_typename(OBJECT(dev)));
922         return;
923     }
924 
925     if (!migration_is_idle() && !dev->allow_unplug_during_migration) {
926         error_setg(errp, "device_del not allowed while migrating");
927         return;
928     }
929 
930     qdev_hot_removed = true;
931 
932     hotplug_ctrl = qdev_get_hotplug_handler(dev);
933     /* hotpluggable device MUST have HotplugHandler, if it doesn't
934      * then something is very wrong with it */
935     g_assert(hotplug_ctrl);
936 
937     /* If device supports async unplug just request it to be done,
938      * otherwise just remove it synchronously */
939     hdc = HOTPLUG_HANDLER_GET_CLASS(hotplug_ctrl);
940     if (hdc->unplug_request) {
941         hotplug_handler_unplug_request(hotplug_ctrl, dev, &local_err);
942     } else {
943         hotplug_handler_unplug(hotplug_ctrl, dev, &local_err);
944         if (!local_err) {
945             object_unparent(OBJECT(dev));
946         }
947     }
948     error_propagate(errp, local_err);
949 }
950 
951 void qmp_device_del(const char *id, Error **errp)
952 {
953     DeviceState *dev = find_device_state(id, errp);
954     if (dev != NULL) {
955         if (dev->pending_deleted_event &&
956             (dev->pending_deleted_expires_ms == 0 ||
957              dev->pending_deleted_expires_ms > qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL))) {
958             error_setg(errp, "Device %s is already in the "
959                              "process of unplug", id);
960             return;
961         }
962 
963         qdev_unplug(dev, errp);
964     }
965 }
966 
967 void hmp_device_add(Monitor *mon, const QDict *qdict)
968 {
969     Error *err = NULL;
970 
971     qmp_device_add((QDict *)qdict, NULL, &err);
972     hmp_handle_error(mon, err);
973 }
974 
975 void hmp_device_del(Monitor *mon, const QDict *qdict)
976 {
977     const char *id = qdict_get_str(qdict, "id");
978     Error *err = NULL;
979 
980     qmp_device_del(id, &err);
981     hmp_handle_error(mon, err);
982 }
983 
984 void device_add_completion(ReadLineState *rs, int nb_args, const char *str)
985 {
986     GSList *list, *elt;
987     size_t len;
988 
989     if (nb_args != 2) {
990         return;
991     }
992 
993     len = strlen(str);
994     readline_set_completion_index(rs, len);
995     list = elt = object_class_get_list(TYPE_DEVICE, false);
996     while (elt) {
997         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, elt->data,
998                                              TYPE_DEVICE);
999 
1000         if (dc->user_creatable) {
1001             readline_add_completion_of(rs, str,
1002                                 object_class_get_name(OBJECT_CLASS(dc)));
1003         }
1004         elt = elt->next;
1005     }
1006     g_slist_free(list);
1007 }
1008 
1009 static int qdev_add_hotpluggable_device(Object *obj, void *opaque)
1010 {
1011     GSList **list = opaque;
1012     DeviceState *dev = (DeviceState *)object_dynamic_cast(obj, TYPE_DEVICE);
1013 
1014     if (dev == NULL) {
1015         return 0;
1016     }
1017 
1018     if (dev->realized && object_property_get_bool(obj, "hotpluggable", NULL)) {
1019         *list = g_slist_append(*list, dev);
1020     }
1021 
1022     return 0;
1023 }
1024 
1025 static GSList *qdev_build_hotpluggable_device_list(Object *peripheral)
1026 {
1027     GSList *list = NULL;
1028 
1029     object_child_foreach(peripheral, qdev_add_hotpluggable_device, &list);
1030 
1031     return list;
1032 }
1033 
1034 static void peripheral_device_del_completion(ReadLineState *rs,
1035                                              const char *str)
1036 {
1037     Object *peripheral = container_get(qdev_get_machine(), "/peripheral");
1038     GSList *list, *item;
1039 
1040     list = qdev_build_hotpluggable_device_list(peripheral);
1041     if (!list) {
1042         return;
1043     }
1044 
1045     for (item = list; item; item = g_slist_next(item)) {
1046         DeviceState *dev = item->data;
1047 
1048         if (dev->id) {
1049             readline_add_completion_of(rs, str, dev->id);
1050         }
1051     }
1052 
1053     g_slist_free(list);
1054 }
1055 
1056 void device_del_completion(ReadLineState *rs, int nb_args, const char *str)
1057 {
1058     if (nb_args != 2) {
1059         return;
1060     }
1061 
1062     readline_set_completion_index(rs, strlen(str));
1063     peripheral_device_del_completion(rs, str);
1064 }
1065 
1066 BlockBackend *blk_by_qdev_id(const char *id, Error **errp)
1067 {
1068     DeviceState *dev;
1069     BlockBackend *blk;
1070 
1071     GLOBAL_STATE_CODE();
1072 
1073     dev = find_device_state(id, errp);
1074     if (dev == NULL) {
1075         return NULL;
1076     }
1077 
1078     blk = blk_by_dev(dev);
1079     if (!blk) {
1080         error_setg(errp, "Device does not have a block device backend");
1081     }
1082     return blk;
1083 }
1084 
1085 QemuOptsList qemu_device_opts = {
1086     .name = "device",
1087     .implied_opt_name = "driver",
1088     .head = QTAILQ_HEAD_INITIALIZER(qemu_device_opts.head),
1089     .desc = {
1090         /*
1091          * no elements => accept any
1092          * sanity checking will happen later
1093          * when setting device properties
1094          */
1095         { /* end of list */ }
1096     },
1097 };
1098 
1099 QemuOptsList qemu_global_opts = {
1100     .name = "global",
1101     .head = QTAILQ_HEAD_INITIALIZER(qemu_global_opts.head),
1102     .desc = {
1103         {
1104             .name = "driver",
1105             .type = QEMU_OPT_STRING,
1106         },{
1107             .name = "property",
1108             .type = QEMU_OPT_STRING,
1109         },{
1110             .name = "value",
1111             .type = QEMU_OPT_STRING,
1112         },
1113         { /* end of list */ }
1114     },
1115 };
1116 
1117 int qemu_global_option(const char *str)
1118 {
1119     char driver[64], property[64];
1120     QemuOpts *opts;
1121     int rc, offset;
1122 
1123     rc = sscanf(str, "%63[^.=].%63[^=]%n", driver, property, &offset);
1124     if (rc == 2 && str[offset] == '=') {
1125         opts = qemu_opts_create(&qemu_global_opts, NULL, 0, &error_abort);
1126         qemu_opt_set(opts, "driver", driver, &error_abort);
1127         qemu_opt_set(opts, "property", property, &error_abort);
1128         qemu_opt_set(opts, "value", str + offset + 1, &error_abort);
1129         return 0;
1130     }
1131 
1132     opts = qemu_opts_parse_noisily(&qemu_global_opts, str, false);
1133     if (!opts) {
1134         return -1;
1135     }
1136     if (!qemu_opt_get(opts, "driver")
1137         || !qemu_opt_get(opts, "property")
1138         || !qemu_opt_get(opts, "value")) {
1139         error_report("options 'driver', 'property', and 'value'"
1140                      " are required");
1141         return -1;
1142     }
1143 
1144     return 0;
1145 }
1146 
1147 bool qmp_command_available(const QmpCommand *cmd, Error **errp)
1148 {
1149     if (!phase_check(PHASE_MACHINE_READY) &&
1150         !(cmd->options & QCO_ALLOW_PRECONFIG)) {
1151         error_setg(errp, "The command '%s' is permitted only after machine initialization has completed",
1152                    cmd->name);
1153         return false;
1154     }
1155     return true;
1156 }
1157