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