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