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