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