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