qemu/vl.c
<<
>>
Prefs
   1/*
   2 * QEMU System Emulator
   3 *
   4 * Copyright (c) 2003-2008 Fabrice Bellard
   5 *
   6 * Permission is hereby granted, free of charge, to any person obtaining a copy
   7 * of this software and associated documentation files (the "Software"), to deal
   8 * in the Software without restriction, including without limitation the rights
   9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10 * copies of the Software, and to permit persons to whom the Software is
  11 * furnished to do so, subject to the following conditions:
  12 *
  13 * The above copyright notice and this permission notice shall be included in
  14 * all copies or substantial portions of the Software.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22 * THE SOFTWARE.
  23 */
  24
  25#include "qemu/osdep.h"
  26#include "qemu-common.h"
  27#include "qemu/units.h"
  28#include "hw/qdev-properties.h"
  29#include "qapi/error.h"
  30#include "qemu-version.h"
  31#include "qemu/cutils.h"
  32#include "qemu/help_option.h"
  33#include "qemu/uuid.h"
  34#include "sysemu/reset.h"
  35#include "sysemu/runstate.h"
  36#include "sysemu/seccomp.h"
  37#include "sysemu/tcg.h"
  38
  39#ifdef CONFIG_SDL
  40#if defined(__APPLE__) || defined(main)
  41#include <SDL.h>
  42int qemu_main(int argc, char **argv, char **envp);
  43int main(int argc, char **argv)
  44{
  45    return qemu_main(argc, argv, NULL);
  46}
  47#undef main
  48#define main qemu_main
  49#endif
  50#endif /* CONFIG_SDL */
  51
  52#ifdef CONFIG_COCOA
  53#undef main
  54#define main qemu_main
  55#endif /* CONFIG_COCOA */
  56
  57
  58#include "qemu/error-report.h"
  59#include "qemu/sockets.h"
  60#include "sysemu/accel.h"
  61#include "hw/usb.h"
  62#include "hw/isa/isa.h"
  63#include "hw/scsi/scsi.h"
  64#include "hw/display/vga.h"
  65#include "hw/bt.h"
  66#include "sysemu/watchdog.h"
  67#include "hw/firmware/smbios.h"
  68#include "hw/acpi/acpi.h"
  69#include "hw/xen/xen.h"
  70#include "hw/loader.h"
  71#include "monitor/qdev.h"
  72#include "sysemu/bt.h"
  73#include "net/net.h"
  74#include "net/slirp.h"
  75#include "monitor/monitor.h"
  76#include "ui/console.h"
  77#include "ui/input.h"
  78#include "sysemu/sysemu.h"
  79#include "sysemu/numa.h"
  80#include "exec/gdbstub.h"
  81#include "qemu/timer.h"
  82#include "chardev/char.h"
  83#include "qemu/bitmap.h"
  84#include "qemu/log.h"
  85#include "sysemu/blockdev.h"
  86#include "hw/block/block.h"
  87#include "migration/misc.h"
  88#include "migration/snapshot.h"
  89#include "migration/global_state.h"
  90#include "sysemu/tpm.h"
  91#include "sysemu/dma.h"
  92#include "hw/audio/soundhw.h"
  93#include "audio/audio.h"
  94#include "sysemu/cpus.h"
  95#include "migration/colo.h"
  96#include "migration/postcopy-ram.h"
  97#include "sysemu/kvm.h"
  98#include "sysemu/hax.h"
  99#include "qapi/qobject-input-visitor.h"
 100#include "qemu/option.h"
 101#include "qemu/config-file.h"
 102#include "qemu-options.h"
 103#include "qemu/main-loop.h"
 104#ifdef CONFIG_VIRTFS
 105#include "fsdev/qemu-fsdev.h"
 106#endif
 107#include "sysemu/qtest.h"
 108
 109#include "disas/disas.h"
 110
 111#include "trace-root.h"
 112#include "trace/control.h"
 113#include "qemu/plugin.h"
 114#include "qemu/queue.h"
 115#include "sysemu/arch_init.h"
 116
 117#include "ui/qemu-spice.h"
 118#include "qapi/string-input-visitor.h"
 119#include "qapi/opts-visitor.h"
 120#include "qapi/clone-visitor.h"
 121#include "qom/object_interfaces.h"
 122#include "hw/semihosting/semihost.h"
 123#include "crypto/init.h"
 124#include "sysemu/replay.h"
 125#include "qapi/qapi-events-run-state.h"
 126#include "qapi/qapi-visit-block-core.h"
 127#include "qapi/qapi-visit-ui.h"
 128#include "qapi/qapi-commands-block-core.h"
 129#include "qapi/qapi-commands-run-state.h"
 130#include "qapi/qapi-commands-ui.h"
 131#include "qapi/qmp/qerror.h"
 132#include "sysemu/iothread.h"
 133#include "qemu/guest-random.h"
 134
 135#define MAX_VIRTIO_CONSOLES 1
 136
 137static const char *data_dir[16];
 138static int data_dir_idx;
 139const char *bios_name = NULL;
 140enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
 141int display_opengl;
 142const char* keyboard_layout = NULL;
 143ram_addr_t ram_size;
 144const char *mem_path = NULL;
 145int mem_prealloc = 0; /* force preallocation of physical target memory */
 146bool enable_mlock = false;
 147bool enable_cpu_pm = false;
 148int nb_nics;
 149NICInfo nd_table[MAX_NICS];
 150int autostart;
 151static enum {
 152    RTC_BASE_UTC,
 153    RTC_BASE_LOCALTIME,
 154    RTC_BASE_DATETIME,
 155} rtc_base_type = RTC_BASE_UTC;
 156static time_t rtc_ref_start_datetime;
 157static int rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
 158static int rtc_host_datetime_offset = -1; /* valid & used only with
 159                                             RTC_BASE_DATETIME */
 160QEMUClockType rtc_clock;
 161int vga_interface_type = VGA_NONE;
 162static DisplayOptions dpy;
 163static int num_serial_hds;
 164static Chardev **serial_hds;
 165Chardev *parallel_hds[MAX_PARALLEL_PORTS];
 166int win2k_install_hack = 0;
 167int singlestep = 0;
 168int acpi_enabled = 1;
 169int no_hpet = 0;
 170int fd_bootchk = 1;
 171static int no_reboot;
 172int no_shutdown = 0;
 173int cursor_hide = 1;
 174int graphic_rotate = 0;
 175const char *watchdog;
 176QEMUOptionRom option_rom[MAX_OPTION_ROMS];
 177int nb_option_roms;
 178int old_param = 0;
 179const char *qemu_name;
 180int alt_grab = 0;
 181int ctrl_grab = 0;
 182unsigned int nb_prom_envs = 0;
 183const char *prom_envs[MAX_PROM_ENVS];
 184int boot_menu;
 185bool boot_strict;
 186uint8_t *boot_splash_filedata;
 187int only_migratable; /* turn it off unless user states otherwise */
 188bool wakeup_suspend_enabled;
 189
 190int icount_align_option;
 191
 192/* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
 193 * little-endian "wire format" described in the SMBIOS 2.6 specification.
 194 */
 195QemuUUID qemu_uuid;
 196bool qemu_uuid_set;
 197
 198static NotifierList exit_notifiers =
 199    NOTIFIER_LIST_INITIALIZER(exit_notifiers);
 200
 201static NotifierList machine_init_done_notifiers =
 202    NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
 203
 204bool xen_allowed;
 205uint32_t xen_domid;
 206enum xen_mode xen_mode = XEN_EMULATE;
 207bool xen_domid_restrict;
 208
 209static int has_defaults = 1;
 210static int default_serial = 1;
 211static int default_parallel = 1;
 212static int default_monitor = 1;
 213static int default_floppy = 1;
 214static int default_cdrom = 1;
 215static int default_sdcard = 1;
 216static int default_vga = 1;
 217static int default_net = 1;
 218
 219static struct {
 220    const char *driver;
 221    int *flag;
 222} default_list[] = {
 223    { .driver = "isa-serial",           .flag = &default_serial    },
 224    { .driver = "isa-parallel",         .flag = &default_parallel  },
 225    { .driver = "isa-fdc",              .flag = &default_floppy    },
 226    { .driver = "floppy",               .flag = &default_floppy    },
 227    { .driver = "ide-cd",               .flag = &default_cdrom     },
 228    { .driver = "ide-hd",               .flag = &default_cdrom     },
 229    { .driver = "ide-drive",            .flag = &default_cdrom     },
 230    { .driver = "scsi-cd",              .flag = &default_cdrom     },
 231    { .driver = "scsi-hd",              .flag = &default_cdrom     },
 232    { .driver = "VGA",                  .flag = &default_vga       },
 233    { .driver = "isa-vga",              .flag = &default_vga       },
 234    { .driver = "cirrus-vga",           .flag = &default_vga       },
 235    { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
 236    { .driver = "vmware-svga",          .flag = &default_vga       },
 237    { .driver = "qxl-vga",              .flag = &default_vga       },
 238    { .driver = "virtio-vga",           .flag = &default_vga       },
 239    { .driver = "ati-vga",              .flag = &default_vga       },
 240    { .driver = "vhost-user-vga",       .flag = &default_vga       },
 241};
 242
 243static QemuOptsList qemu_rtc_opts = {
 244    .name = "rtc",
 245    .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
 246    .merge_lists = true,
 247    .desc = {
 248        {
 249            .name = "base",
 250            .type = QEMU_OPT_STRING,
 251        },{
 252            .name = "clock",
 253            .type = QEMU_OPT_STRING,
 254        },{
 255            .name = "driftfix",
 256            .type = QEMU_OPT_STRING,
 257        },
 258        { /* end of list */ }
 259    },
 260};
 261
 262static QemuOptsList qemu_option_rom_opts = {
 263    .name = "option-rom",
 264    .implied_opt_name = "romfile",
 265    .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
 266    .desc = {
 267        {
 268            .name = "bootindex",
 269            .type = QEMU_OPT_NUMBER,
 270        }, {
 271            .name = "romfile",
 272            .type = QEMU_OPT_STRING,
 273        },
 274        { /* end of list */ }
 275    },
 276};
 277
 278static QemuOptsList qemu_machine_opts = {
 279    .name = "machine",
 280    .implied_opt_name = "type",
 281    .merge_lists = true,
 282    .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
 283    .desc = {
 284        /*
 285         * no elements => accept any
 286         * sanity checking will happen later
 287         * when setting machine properties
 288         */
 289        { }
 290    },
 291};
 292
 293static QemuOptsList qemu_accel_opts = {
 294    .name = "accel",
 295    .implied_opt_name = "accel",
 296    .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
 297    .merge_lists = true,
 298    .desc = {
 299        {
 300            .name = "accel",
 301            .type = QEMU_OPT_STRING,
 302            .help = "Select the type of accelerator",
 303        },
 304        {
 305            .name = "thread",
 306            .type = QEMU_OPT_STRING,
 307            .help = "Enable/disable multi-threaded TCG",
 308        },
 309        { /* end of list */ }
 310    },
 311};
 312
 313static QemuOptsList qemu_boot_opts = {
 314    .name = "boot-opts",
 315    .implied_opt_name = "order",
 316    .merge_lists = true,
 317    .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
 318    .desc = {
 319        {
 320            .name = "order",
 321            .type = QEMU_OPT_STRING,
 322        }, {
 323            .name = "once",
 324            .type = QEMU_OPT_STRING,
 325        }, {
 326            .name = "menu",
 327            .type = QEMU_OPT_BOOL,
 328        }, {
 329            .name = "splash",
 330            .type = QEMU_OPT_STRING,
 331        }, {
 332            .name = "splash-time",
 333            .type = QEMU_OPT_NUMBER,
 334        }, {
 335            .name = "reboot-timeout",
 336            .type = QEMU_OPT_NUMBER,
 337        }, {
 338            .name = "strict",
 339            .type = QEMU_OPT_BOOL,
 340        },
 341        { /*End of list */ }
 342    },
 343};
 344
 345static QemuOptsList qemu_add_fd_opts = {
 346    .name = "add-fd",
 347    .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
 348    .desc = {
 349        {
 350            .name = "fd",
 351            .type = QEMU_OPT_NUMBER,
 352            .help = "file descriptor of which a duplicate is added to fd set",
 353        },{
 354            .name = "set",
 355            .type = QEMU_OPT_NUMBER,
 356            .help = "ID of the fd set to add fd to",
 357        },{
 358            .name = "opaque",
 359            .type = QEMU_OPT_STRING,
 360            .help = "free-form string used to describe fd",
 361        },
 362        { /* end of list */ }
 363    },
 364};
 365
 366static QemuOptsList qemu_object_opts = {
 367    .name = "object",
 368    .implied_opt_name = "qom-type",
 369    .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
 370    .desc = {
 371        { }
 372    },
 373};
 374
 375static QemuOptsList qemu_tpmdev_opts = {
 376    .name = "tpmdev",
 377    .implied_opt_name = "type",
 378    .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
 379    .desc = {
 380        /* options are defined in the TPM backends */
 381        { /* end of list */ }
 382    },
 383};
 384
 385static QemuOptsList qemu_realtime_opts = {
 386    .name = "realtime",
 387    .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
 388    .desc = {
 389        {
 390            .name = "mlock",
 391            .type = QEMU_OPT_BOOL,
 392        },
 393        { /* end of list */ }
 394    },
 395};
 396
 397static QemuOptsList qemu_overcommit_opts = {
 398    .name = "overcommit",
 399    .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
 400    .desc = {
 401        {
 402            .name = "mem-lock",
 403            .type = QEMU_OPT_BOOL,
 404        },
 405        {
 406            .name = "cpu-pm",
 407            .type = QEMU_OPT_BOOL,
 408        },
 409        { /* end of list */ }
 410    },
 411};
 412
 413static QemuOptsList qemu_msg_opts = {
 414    .name = "msg",
 415    .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
 416    .desc = {
 417        {
 418            .name = "timestamp",
 419            .type = QEMU_OPT_BOOL,
 420        },
 421        { /* end of list */ }
 422    },
 423};
 424
 425static QemuOptsList qemu_name_opts = {
 426    .name = "name",
 427    .implied_opt_name = "guest",
 428    .merge_lists = true,
 429    .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
 430    .desc = {
 431        {
 432            .name = "guest",
 433            .type = QEMU_OPT_STRING,
 434            .help = "Sets the name of the guest.\n"
 435                    "This name will be displayed in the SDL window caption.\n"
 436                    "The name will also be used for the VNC server",
 437        }, {
 438            .name = "process",
 439            .type = QEMU_OPT_STRING,
 440            .help = "Sets the name of the QEMU process, as shown in top etc",
 441        }, {
 442            .name = "debug-threads",
 443            .type = QEMU_OPT_BOOL,
 444            .help = "When enabled, name the individual threads; defaults off.\n"
 445                    "NOTE: The thread names are for debugging and not a\n"
 446                    "stable API.",
 447        },
 448        { /* End of list */ }
 449    },
 450};
 451
 452static QemuOptsList qemu_mem_opts = {
 453    .name = "memory",
 454    .implied_opt_name = "size",
 455    .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
 456    .merge_lists = true,
 457    .desc = {
 458        {
 459            .name = "size",
 460            .type = QEMU_OPT_SIZE,
 461        },
 462        {
 463            .name = "slots",
 464            .type = QEMU_OPT_NUMBER,
 465        },
 466        {
 467            .name = "maxmem",
 468            .type = QEMU_OPT_SIZE,
 469        },
 470        { /* end of list */ }
 471    },
 472};
 473
 474static QemuOptsList qemu_icount_opts = {
 475    .name = "icount",
 476    .implied_opt_name = "shift",
 477    .merge_lists = true,
 478    .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
 479    .desc = {
 480        {
 481            .name = "shift",
 482            .type = QEMU_OPT_STRING,
 483        }, {
 484            .name = "align",
 485            .type = QEMU_OPT_BOOL,
 486        }, {
 487            .name = "sleep",
 488            .type = QEMU_OPT_BOOL,
 489        }, {
 490            .name = "rr",
 491            .type = QEMU_OPT_STRING,
 492        }, {
 493            .name = "rrfile",
 494            .type = QEMU_OPT_STRING,
 495        }, {
 496            .name = "rrsnapshot",
 497            .type = QEMU_OPT_STRING,
 498        },
 499        { /* end of list */ }
 500    },
 501};
 502
 503static QemuOptsList qemu_fw_cfg_opts = {
 504    .name = "fw_cfg",
 505    .implied_opt_name = "name",
 506    .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
 507    .desc = {
 508        {
 509            .name = "name",
 510            .type = QEMU_OPT_STRING,
 511            .help = "Sets the fw_cfg name of the blob to be inserted",
 512        }, {
 513            .name = "file",
 514            .type = QEMU_OPT_STRING,
 515            .help = "Sets the name of the file from which "
 516                    "the fw_cfg blob will be loaded",
 517        }, {
 518            .name = "string",
 519            .type = QEMU_OPT_STRING,
 520            .help = "Sets content of the blob to be inserted from a string",
 521        },
 522        { /* end of list */ }
 523    },
 524};
 525
 526/**
 527 * Get machine options
 528 *
 529 * Returns: machine options (never null).
 530 */
 531QemuOpts *qemu_get_machine_opts(void)
 532{
 533    return qemu_find_opts_singleton("machine");
 534}
 535
 536const char *qemu_get_vm_name(void)
 537{
 538    return qemu_name;
 539}
 540
 541static void res_free(void)
 542{
 543    g_free(boot_splash_filedata);
 544    boot_splash_filedata = NULL;
 545}
 546
 547static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
 548{
 549    const char *driver = qemu_opt_get(opts, "driver");
 550    int i;
 551
 552    if (!driver)
 553        return 0;
 554    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
 555        if (strcmp(default_list[i].driver, driver) != 0)
 556            continue;
 557        *(default_list[i].flag) = 0;
 558    }
 559    return 0;
 560}
 561
 562/***********************************************************/
 563/* QEMU state */
 564
 565static RunState current_run_state = RUN_STATE_PRECONFIG;
 566
 567/* We use RUN_STATE__MAX but any invalid value will do */
 568static RunState vmstop_requested = RUN_STATE__MAX;
 569static QemuMutex vmstop_lock;
 570
 571typedef struct {
 572    RunState from;
 573    RunState to;
 574} RunStateTransition;
 575
 576static const RunStateTransition runstate_transitions_def[] = {
 577    /*     from      ->     to      */
 578    { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
 579      /* Early switch to inmigrate state to allow  -incoming CLI option work
 580       * as it used to. TODO: delay actual switching to inmigrate state to
 581       * the point after machine is built and remove this hack.
 582       */
 583    { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
 584
 585    { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
 586    { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
 587    { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
 588
 589    { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
 590    { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
 591    { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
 592    { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
 593    { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
 594    { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
 595    { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
 596    { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
 597    { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
 598    { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
 599    { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
 600    { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
 601
 602    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
 603    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
 604    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
 605
 606    { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
 607    { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
 608    { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
 609
 610    { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
 611    { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
 612    { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
 613    { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
 614    { RUN_STATE_PAUSED, RUN_STATE_COLO},
 615
 616    { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
 617    { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
 618    { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
 619
 620    { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
 621    { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
 622    { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
 623
 624    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
 625    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
 626    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
 627    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
 628    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
 629
 630    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
 631    { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
 632
 633    { RUN_STATE_COLO, RUN_STATE_RUNNING },
 634
 635    { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
 636    { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
 637    { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
 638    { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
 639    { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
 640    { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
 641    { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
 642    { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
 643    { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
 644    { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
 645    { RUN_STATE_RUNNING, RUN_STATE_COLO},
 646
 647    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
 648
 649    { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
 650    { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
 651    { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
 652
 653    { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
 654    { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
 655    { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
 656    { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
 657    { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
 658    { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
 659
 660    { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
 661    { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
 662    { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
 663    { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
 664
 665    { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
 666    { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
 667    { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
 668
 669    { RUN_STATE__MAX, RUN_STATE__MAX },
 670};
 671
 672static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
 673
 674bool runstate_check(RunState state)
 675{
 676    return current_run_state == state;
 677}
 678
 679bool runstate_store(char *str, size_t size)
 680{
 681    const char *state = RunState_str(current_run_state);
 682    size_t len = strlen(state) + 1;
 683
 684    if (len > size) {
 685        return false;
 686    }
 687    memcpy(str, state, len);
 688    return true;
 689}
 690
 691static void runstate_init(void)
 692{
 693    const RunStateTransition *p;
 694
 695    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
 696    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
 697        runstate_valid_transitions[p->from][p->to] = true;
 698    }
 699
 700    qemu_mutex_init(&vmstop_lock);
 701}
 702
 703/* This function will abort() on invalid state transitions */
 704void runstate_set(RunState new_state)
 705{
 706    assert(new_state < RUN_STATE__MAX);
 707
 708    trace_runstate_set(current_run_state, RunState_str(current_run_state),
 709                       new_state, RunState_str(new_state));
 710
 711    if (current_run_state == new_state) {
 712        return;
 713    }
 714
 715    if (!runstate_valid_transitions[current_run_state][new_state]) {
 716        error_report("invalid runstate transition: '%s' -> '%s'",
 717                     RunState_str(current_run_state),
 718                     RunState_str(new_state));
 719        abort();
 720    }
 721
 722    current_run_state = new_state;
 723}
 724
 725int runstate_is_running(void)
 726{
 727    return runstate_check(RUN_STATE_RUNNING);
 728}
 729
 730bool runstate_needs_reset(void)
 731{
 732    return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
 733        runstate_check(RUN_STATE_SHUTDOWN);
 734}
 735
 736StatusInfo *qmp_query_status(Error **errp)
 737{
 738    StatusInfo *info = g_malloc0(sizeof(*info));
 739
 740    info->running = runstate_is_running();
 741    info->singlestep = singlestep;
 742    info->status = current_run_state;
 743
 744    return info;
 745}
 746
 747bool qemu_vmstop_requested(RunState *r)
 748{
 749    qemu_mutex_lock(&vmstop_lock);
 750    *r = vmstop_requested;
 751    vmstop_requested = RUN_STATE__MAX;
 752    qemu_mutex_unlock(&vmstop_lock);
 753    return *r < RUN_STATE__MAX;
 754}
 755
 756void qemu_system_vmstop_request_prepare(void)
 757{
 758    qemu_mutex_lock(&vmstop_lock);
 759}
 760
 761void qemu_system_vmstop_request(RunState state)
 762{
 763    vmstop_requested = state;
 764    qemu_mutex_unlock(&vmstop_lock);
 765    qemu_notify_event();
 766}
 767
 768/***********************************************************/
 769/* RTC reference time/date access */
 770static time_t qemu_ref_timedate(QEMUClockType clock)
 771{
 772    time_t value = qemu_clock_get_ms(clock) / 1000;
 773    switch (clock) {
 774    case QEMU_CLOCK_REALTIME:
 775        value -= rtc_realtime_clock_offset;
 776        /* fall through */
 777    case QEMU_CLOCK_VIRTUAL:
 778        value += rtc_ref_start_datetime;
 779        break;
 780    case QEMU_CLOCK_HOST:
 781        if (rtc_base_type == RTC_BASE_DATETIME) {
 782            value -= rtc_host_datetime_offset;
 783        }
 784        break;
 785    default:
 786        assert(0);
 787    }
 788    return value;
 789}
 790
 791void qemu_get_timedate(struct tm *tm, int offset)
 792{
 793    time_t ti = qemu_ref_timedate(rtc_clock);
 794
 795    ti += offset;
 796
 797    switch (rtc_base_type) {
 798    case RTC_BASE_DATETIME:
 799    case RTC_BASE_UTC:
 800        gmtime_r(&ti, tm);
 801        break;
 802    case RTC_BASE_LOCALTIME:
 803        localtime_r(&ti, tm);
 804        break;
 805    }
 806}
 807
 808int qemu_timedate_diff(struct tm *tm)
 809{
 810    time_t seconds;
 811
 812    switch (rtc_base_type) {
 813    case RTC_BASE_DATETIME:
 814    case RTC_BASE_UTC:
 815        seconds = mktimegm(tm);
 816        break;
 817    case RTC_BASE_LOCALTIME:
 818    {
 819        struct tm tmp = *tm;
 820        tmp.tm_isdst = -1; /* use timezone to figure it out */
 821        seconds = mktime(&tmp);
 822        break;
 823    }
 824    default:
 825        abort();
 826    }
 827
 828    return seconds - qemu_ref_timedate(QEMU_CLOCK_HOST);
 829}
 830
 831static void configure_rtc_base_datetime(const char *startdate)
 832{
 833    time_t rtc_start_datetime;
 834    struct tm tm;
 835
 836    if (sscanf(startdate, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon,
 837               &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
 838        /* OK */
 839    } else if (sscanf(startdate, "%d-%d-%d",
 840                      &tm.tm_year, &tm.tm_mon, &tm.tm_mday) == 3) {
 841        tm.tm_hour = 0;
 842        tm.tm_min = 0;
 843        tm.tm_sec = 0;
 844    } else {
 845        goto date_fail;
 846    }
 847    tm.tm_year -= 1900;
 848    tm.tm_mon--;
 849    rtc_start_datetime = mktimegm(&tm);
 850    if (rtc_start_datetime == -1) {
 851    date_fail:
 852        error_report("invalid datetime format");
 853        error_printf("valid formats: "
 854                     "'2006-06-17T16:01:21' or '2006-06-17'\n");
 855        exit(1);
 856    }
 857    rtc_host_datetime_offset = rtc_ref_start_datetime - rtc_start_datetime;
 858    rtc_ref_start_datetime = rtc_start_datetime;
 859}
 860
 861static void configure_rtc(QemuOpts *opts)
 862{
 863    const char *value;
 864
 865    /* Set defaults */
 866    rtc_clock = QEMU_CLOCK_HOST;
 867    rtc_ref_start_datetime = qemu_clock_get_ms(QEMU_CLOCK_HOST) / 1000;
 868    rtc_realtime_clock_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) / 1000;
 869
 870    value = qemu_opt_get(opts, "base");
 871    if (value) {
 872        if (!strcmp(value, "utc")) {
 873            rtc_base_type = RTC_BASE_UTC;
 874        } else if (!strcmp(value, "localtime")) {
 875            Error *blocker = NULL;
 876            rtc_base_type = RTC_BASE_LOCALTIME;
 877            error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
 878                      "-rtc base=localtime");
 879            replay_add_blocker(blocker);
 880        } else {
 881            rtc_base_type = RTC_BASE_DATETIME;
 882            configure_rtc_base_datetime(value);
 883        }
 884    }
 885    value = qemu_opt_get(opts, "clock");
 886    if (value) {
 887        if (!strcmp(value, "host")) {
 888            rtc_clock = QEMU_CLOCK_HOST;
 889        } else if (!strcmp(value, "rt")) {
 890            rtc_clock = QEMU_CLOCK_REALTIME;
 891        } else if (!strcmp(value, "vm")) {
 892            rtc_clock = QEMU_CLOCK_VIRTUAL;
 893        } else {
 894            error_report("invalid option value '%s'", value);
 895            exit(1);
 896        }
 897    }
 898    value = qemu_opt_get(opts, "driftfix");
 899    if (value) {
 900        if (!strcmp(value, "slew")) {
 901            static GlobalProperty slew_lost_ticks = {
 902                .driver   = "mc146818rtc",
 903                .property = "lost_tick_policy",
 904                .value    = "slew",
 905            };
 906
 907            qdev_prop_register_global(&slew_lost_ticks);
 908        } else if (!strcmp(value, "none")) {
 909            /* discard is default */
 910        } else {
 911            error_report("invalid option value '%s'", value);
 912            exit(1);
 913        }
 914    }
 915}
 916
 917/***********************************************************/
 918/* Bluetooth support */
 919static int nb_hcis;
 920static int cur_hci;
 921static struct HCIInfo *hci_table[MAX_NICS];
 922
 923struct HCIInfo *qemu_next_hci(void)
 924{
 925    if (cur_hci == nb_hcis)
 926        return &null_hci;
 927
 928    return hci_table[cur_hci++];
 929}
 930
 931static int bt_hci_parse(const char *str)
 932{
 933    struct HCIInfo *hci;
 934    bdaddr_t bdaddr;
 935
 936    if (nb_hcis >= MAX_NICS) {
 937        error_report("too many bluetooth HCIs (max %i)", MAX_NICS);
 938        return -1;
 939    }
 940
 941    hci = hci_init(str);
 942    if (!hci)
 943        return -1;
 944
 945    bdaddr.b[0] = 0x52;
 946    bdaddr.b[1] = 0x54;
 947    bdaddr.b[2] = 0x00;
 948    bdaddr.b[3] = 0x12;
 949    bdaddr.b[4] = 0x34;
 950    bdaddr.b[5] = 0x56 + nb_hcis;
 951    hci->bdaddr_set(hci, bdaddr.b);
 952
 953    hci_table[nb_hcis++] = hci;
 954
 955    return 0;
 956}
 957
 958static void bt_vhci_add(int vlan_id)
 959{
 960    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
 961
 962    if (!vlan->slave)
 963        warn_report("adding a VHCI to an empty scatternet %i",
 964                    vlan_id);
 965
 966    bt_vhci_init(bt_new_hci(vlan));
 967}
 968
 969static struct bt_device_s *bt_device_add(const char *opt)
 970{
 971    struct bt_scatternet_s *vlan;
 972    int vlan_id = 0;
 973    char *endp = strstr(opt, ",vlan=");
 974    int len = (endp ? endp - opt : strlen(opt)) + 1;
 975    char devname[10];
 976
 977    pstrcpy(devname, MIN(sizeof(devname), len), opt);
 978
 979    if (endp) {
 980        vlan_id = strtol(endp + 6, &endp, 0);
 981        if (*endp) {
 982            error_report("unrecognised bluetooth vlan Id");
 983            return 0;
 984        }
 985    }
 986
 987    vlan = qemu_find_bt_vlan(vlan_id);
 988
 989    if (!vlan->slave)
 990        warn_report("adding a slave device to an empty scatternet %i",
 991                    vlan_id);
 992
 993    if (!strcmp(devname, "keyboard"))
 994        return bt_keyboard_init(vlan);
 995
 996    error_report("unsupported bluetooth device '%s'", devname);
 997    return 0;
 998}
 999
1000static int bt_parse(const char *opt)
1001{
1002    const char *endp, *p;
1003    int vlan;
1004
1005    if (strstart(opt, "hci", &endp)) {
1006        if (!*endp || *endp == ',') {
1007            if (*endp)
1008                if (!strstart(endp, ",vlan=", 0))
1009                    opt = endp + 1;
1010
1011            return bt_hci_parse(opt);
1012       }
1013    } else if (strstart(opt, "vhci", &endp)) {
1014        if (!*endp || *endp == ',') {
1015            if (*endp) {
1016                if (strstart(endp, ",vlan=", &p)) {
1017                    vlan = strtol(p, (char **) &endp, 0);
1018                    if (*endp) {
1019                        error_report("bad scatternet '%s'", p);
1020                        return 1;
1021                    }
1022                } else {
1023                    error_report("bad parameter '%s'", endp + 1);
1024                    return 1;
1025                }
1026            } else
1027                vlan = 0;
1028
1029            bt_vhci_add(vlan);
1030            return 0;
1031        }
1032    } else if (strstart(opt, "device:", &endp))
1033        return !bt_device_add(endp);
1034
1035    error_report("bad bluetooth parameter '%s'", opt);
1036    return 1;
1037}
1038
1039static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
1040{
1041    const char *proc_name;
1042
1043    if (qemu_opt_get(opts, "debug-threads")) {
1044        qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
1045    }
1046    qemu_name = qemu_opt_get(opts, "guest");
1047
1048    proc_name = qemu_opt_get(opts, "process");
1049    if (proc_name) {
1050        os_set_proc_name(proc_name);
1051    }
1052
1053    return 0;
1054}
1055
1056bool defaults_enabled(void)
1057{
1058    return has_defaults;
1059}
1060
1061#ifndef _WIN32
1062static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1063{
1064    int fd, dupfd, flags;
1065    int64_t fdset_id;
1066    const char *fd_opaque = NULL;
1067    AddfdInfo *fdinfo;
1068
1069    fd = qemu_opt_get_number(opts, "fd", -1);
1070    fdset_id = qemu_opt_get_number(opts, "set", -1);
1071    fd_opaque = qemu_opt_get(opts, "opaque");
1072
1073    if (fd < 0) {
1074        error_setg(errp, "fd option is required and must be non-negative");
1075        return -1;
1076    }
1077
1078    if (fd <= STDERR_FILENO) {
1079        error_setg(errp, "fd cannot be a standard I/O stream");
1080        return -1;
1081    }
1082
1083    /*
1084     * All fds inherited across exec() necessarily have FD_CLOEXEC
1085     * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
1086     */
1087    flags = fcntl(fd, F_GETFD);
1088    if (flags == -1 || (flags & FD_CLOEXEC)) {
1089        error_setg(errp, "fd is not valid or already in use");
1090        return -1;
1091    }
1092
1093    if (fdset_id < 0) {
1094        error_setg(errp, "set option is required and must be non-negative");
1095        return -1;
1096    }
1097
1098#ifdef F_DUPFD_CLOEXEC
1099    dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1100#else
1101    dupfd = dup(fd);
1102    if (dupfd != -1) {
1103        qemu_set_cloexec(dupfd);
1104    }
1105#endif
1106    if (dupfd == -1) {
1107        error_setg(errp, "error duplicating fd: %s", strerror(errno));
1108        return -1;
1109    }
1110
1111    /* add the duplicate fd, and optionally the opaque string, to the fd set */
1112    fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
1113                                  &error_abort);
1114    g_free(fdinfo);
1115
1116    return 0;
1117}
1118
1119static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1120{
1121    int fd;
1122
1123    fd = qemu_opt_get_number(opts, "fd", -1);
1124    close(fd);
1125
1126    return 0;
1127}
1128#endif
1129
1130/***********************************************************/
1131/* QEMU Block devices */
1132
1133#define HD_OPTS "media=disk"
1134#define CDROM_OPTS "media=cdrom"
1135#define FD_OPTS ""
1136#define PFLASH_OPTS ""
1137#define MTD_OPTS ""
1138#define SD_OPTS ""
1139
1140static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
1141{
1142    BlockInterfaceType *block_default_type = opaque;
1143
1144    return drive_new(opts, *block_default_type, errp) == NULL;
1145}
1146
1147static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
1148{
1149    if (qemu_opt_get(opts, "snapshot") == NULL) {
1150        qemu_opt_set(opts, "snapshot", "on", &error_abort);
1151    }
1152    return 0;
1153}
1154
1155static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1156                          int index, const char *optstr)
1157{
1158    QemuOpts *opts;
1159    DriveInfo *dinfo;
1160
1161    if (!enable || drive_get_by_index(type, index)) {
1162        return;
1163    }
1164
1165    opts = drive_add(type, index, NULL, optstr);
1166    if (snapshot) {
1167        drive_enable_snapshot(NULL, opts, NULL);
1168    }
1169
1170    dinfo = drive_new(opts, type, &error_abort);
1171    dinfo->is_default = true;
1172
1173}
1174
1175typedef struct BlockdevOptionsQueueEntry {
1176    BlockdevOptions *bdo;
1177    Location loc;
1178    QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
1179} BlockdevOptionsQueueEntry;
1180
1181typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
1182
1183static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
1184                               MachineClass *machine_class, int snapshot)
1185{
1186    /*
1187     * If the currently selected machine wishes to override the
1188     * units-per-bus property of its default HBA interface type, do so
1189     * now.
1190     */
1191    if (machine_class->units_per_default_bus) {
1192        override_max_devs(machine_class->block_default_type,
1193                          machine_class->units_per_default_bus);
1194    }
1195
1196    /* open the virtual block devices */
1197    while (!QSIMPLEQ_EMPTY(bdo_queue)) {
1198        BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
1199
1200        QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
1201        loc_push_restore(&bdo->loc);
1202        qmp_blockdev_add(bdo->bdo, &error_fatal);
1203        loc_pop(&bdo->loc);
1204        qapi_free_BlockdevOptions(bdo->bdo);
1205        g_free(bdo);
1206    }
1207    if (snapshot) {
1208        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
1209                          NULL, NULL);
1210    }
1211    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
1212                          &machine_class->block_default_type, &error_fatal)) {
1213        /* We printed help */
1214        exit(0);
1215    }
1216
1217    default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
1218                  CDROM_OPTS);
1219    default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
1220    default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
1221
1222}
1223
1224static QemuOptsList qemu_smp_opts = {
1225    .name = "smp-opts",
1226    .implied_opt_name = "cpus",
1227    .merge_lists = true,
1228    .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1229    .desc = {
1230        {
1231            .name = "cpus",
1232            .type = QEMU_OPT_NUMBER,
1233        }, {
1234            .name = "sockets",
1235            .type = QEMU_OPT_NUMBER,
1236        }, {
1237            .name = "dies",
1238            .type = QEMU_OPT_NUMBER,
1239        }, {
1240            .name = "cores",
1241            .type = QEMU_OPT_NUMBER,
1242        }, {
1243            .name = "threads",
1244            .type = QEMU_OPT_NUMBER,
1245        }, {
1246            .name = "maxcpus",
1247            .type = QEMU_OPT_NUMBER,
1248        },
1249        { /*End of list */ }
1250    },
1251};
1252
1253static void realtime_init(void)
1254{
1255    if (enable_mlock) {
1256        if (os_mlock() < 0) {
1257            error_report("locking memory failed");
1258            exit(1);
1259        }
1260    }
1261}
1262
1263
1264static void configure_msg(QemuOpts *opts)
1265{
1266    enable_timestamp_msg = qemu_opt_get_bool(opts, "timestamp", true);
1267}
1268
1269
1270/* Now we still need this for compatibility with XEN. */
1271bool has_igd_gfx_passthru;
1272static void igd_gfx_passthru(void)
1273{
1274    has_igd_gfx_passthru = current_machine->igd_gfx_passthru;
1275}
1276
1277/***********************************************************/
1278/* USB devices */
1279
1280static int usb_device_add(const char *devname)
1281{
1282    USBDevice *dev = NULL;
1283
1284    if (!machine_usb(current_machine)) {
1285        return -1;
1286    }
1287
1288    dev = usbdevice_create(devname);
1289    if (!dev)
1290        return -1;
1291
1292    return 0;
1293}
1294
1295static int usb_parse(const char *cmdline)
1296{
1297    int r;
1298    r = usb_device_add(cmdline);
1299    if (r < 0) {
1300        error_report("could not add USB device '%s'", cmdline);
1301    }
1302    return r;
1303}
1304
1305/***********************************************************/
1306/* machine registration */
1307
1308MachineState *current_machine;
1309
1310static MachineClass *find_machine(const char *name, GSList *machines)
1311{
1312    GSList *el;
1313
1314    for (el = machines; el; el = el->next) {
1315        MachineClass *mc = el->data;
1316
1317        if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1318            return mc;
1319        }
1320    }
1321
1322    return NULL;
1323}
1324
1325static MachineClass *find_default_machine(GSList *machines)
1326{
1327    GSList *el;
1328
1329    for (el = machines; el; el = el->next) {
1330        MachineClass *mc = el->data;
1331
1332        if (mc->is_default) {
1333            return mc;
1334        }
1335    }
1336
1337    return NULL;
1338}
1339
1340static int machine_help_func(QemuOpts *opts, MachineState *machine)
1341{
1342    ObjectProperty *prop;
1343    ObjectPropertyIterator iter;
1344
1345    if (!qemu_opt_has_help_opt(opts)) {
1346        return 0;
1347    }
1348
1349    object_property_iter_init(&iter, OBJECT(machine));
1350    while ((prop = object_property_iter_next(&iter))) {
1351        if (!prop->set) {
1352            continue;
1353        }
1354
1355        printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1356               prop->name, prop->type);
1357        if (prop->description) {
1358            printf(" (%s)\n", prop->description);
1359        } else {
1360            printf("\n");
1361        }
1362    }
1363
1364    return 1;
1365}
1366
1367struct VMChangeStateEntry {
1368    VMChangeStateHandler *cb;
1369    void *opaque;
1370    QTAILQ_ENTRY(VMChangeStateEntry) entries;
1371    int priority;
1372};
1373
1374static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head;
1375
1376/**
1377 * qemu_add_vm_change_state_handler_prio:
1378 * @cb: the callback to invoke
1379 * @opaque: user data passed to the callback
1380 * @priority: low priorities execute first when the vm runs and the reverse is
1381 *            true when the vm stops
1382 *
1383 * Register a callback function that is invoked when the vm starts or stops
1384 * running.
1385 *
1386 * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1387 */
1388VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1389        VMChangeStateHandler *cb, void *opaque, int priority)
1390{
1391    VMChangeStateEntry *e;
1392    VMChangeStateEntry *other;
1393
1394    e = g_malloc0(sizeof(*e));
1395    e->cb = cb;
1396    e->opaque = opaque;
1397    e->priority = priority;
1398
1399    /* Keep list sorted in ascending priority order */
1400    QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1401        if (priority < other->priority) {
1402            QTAILQ_INSERT_BEFORE(other, e, entries);
1403            return e;
1404        }
1405    }
1406
1407    QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1408    return e;
1409}
1410
1411VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1412                                                     void *opaque)
1413{
1414    return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1415}
1416
1417void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1418{
1419    QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1420    g_free(e);
1421}
1422
1423void vm_state_notify(int running, RunState state)
1424{
1425    VMChangeStateEntry *e, *next;
1426
1427    trace_vm_state_notify(running, state, RunState_str(state));
1428
1429    if (running) {
1430        QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1431            e->cb(e->opaque, running, state);
1432        }
1433    } else {
1434        QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1435            e->cb(e->opaque, running, state);
1436        }
1437    }
1438}
1439
1440static ShutdownCause reset_requested;
1441static ShutdownCause shutdown_requested;
1442static int shutdown_signal;
1443static pid_t shutdown_pid;
1444static int powerdown_requested;
1445static int debug_requested;
1446static int suspend_requested;
1447static bool preconfig_exit_requested = true;
1448static WakeupReason wakeup_reason;
1449static NotifierList powerdown_notifiers =
1450    NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1451static NotifierList suspend_notifiers =
1452    NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1453static NotifierList wakeup_notifiers =
1454    NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1455static NotifierList shutdown_notifiers =
1456    NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1457static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1458
1459ShutdownCause qemu_shutdown_requested_get(void)
1460{
1461    return shutdown_requested;
1462}
1463
1464ShutdownCause qemu_reset_requested_get(void)
1465{
1466    return reset_requested;
1467}
1468
1469static int qemu_shutdown_requested(void)
1470{
1471    return atomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1472}
1473
1474static void qemu_kill_report(void)
1475{
1476    if (!qtest_driver() && shutdown_signal) {
1477        if (shutdown_pid == 0) {
1478            /* This happens for eg ^C at the terminal, so it's worth
1479             * avoiding printing an odd message in that case.
1480             */
1481            error_report("terminating on signal %d", shutdown_signal);
1482        } else {
1483            char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1484
1485            error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1486                         shutdown_signal, shutdown_pid,
1487                         shutdown_cmd ? shutdown_cmd : "<unknown process>");
1488            g_free(shutdown_cmd);
1489        }
1490        shutdown_signal = 0;
1491    }
1492}
1493
1494static ShutdownCause qemu_reset_requested(void)
1495{
1496    ShutdownCause r = reset_requested;
1497
1498    if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1499        reset_requested = SHUTDOWN_CAUSE_NONE;
1500        return r;
1501    }
1502    return SHUTDOWN_CAUSE_NONE;
1503}
1504
1505static int qemu_suspend_requested(void)
1506{
1507    int r = suspend_requested;
1508    if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1509        suspend_requested = 0;
1510        return r;
1511    }
1512    return false;
1513}
1514
1515static WakeupReason qemu_wakeup_requested(void)
1516{
1517    return wakeup_reason;
1518}
1519
1520static int qemu_powerdown_requested(void)
1521{
1522    int r = powerdown_requested;
1523    powerdown_requested = 0;
1524    return r;
1525}
1526
1527static int qemu_debug_requested(void)
1528{
1529    int r = debug_requested;
1530    debug_requested = 0;
1531    return r;
1532}
1533
1534void qemu_exit_preconfig_request(void)
1535{
1536    preconfig_exit_requested = true;
1537}
1538
1539/*
1540 * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1541 */
1542void qemu_system_reset(ShutdownCause reason)
1543{
1544    MachineClass *mc;
1545
1546    mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1547
1548    cpu_synchronize_all_states();
1549
1550    if (mc && mc->reset) {
1551        mc->reset(current_machine);
1552    } else {
1553        qemu_devices_reset();
1554    }
1555    if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1556        qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1557    }
1558    cpu_synchronize_all_post_reset();
1559}
1560
1561/*
1562 * Wake the VM after suspend.
1563 */
1564static void qemu_system_wakeup(void)
1565{
1566    MachineClass *mc;
1567
1568    mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1569
1570    if (mc && mc->wakeup) {
1571        mc->wakeup(current_machine);
1572    }
1573}
1574
1575void qemu_system_guest_panicked(GuestPanicInformation *info)
1576{
1577    qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1578
1579    if (current_cpu) {
1580        current_cpu->crash_occurred = true;
1581    }
1582    qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1583                                   !!info, info);
1584    vm_stop(RUN_STATE_GUEST_PANICKED);
1585    if (!no_shutdown) {
1586        qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1587                                       !!info, info);
1588        qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1589    }
1590
1591    if (info) {
1592        if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1593            qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1594                          " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1595                          info->u.hyper_v.arg1,
1596                          info->u.hyper_v.arg2,
1597                          info->u.hyper_v.arg3,
1598                          info->u.hyper_v.arg4,
1599                          info->u.hyper_v.arg5);
1600        } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1601            qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1602                          "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1603                          info->u.s390.core,
1604                          S390CrashReason_str(info->u.s390.reason),
1605                          info->u.s390.psw_mask,
1606                          info->u.s390.psw_addr);
1607        }
1608        qapi_free_GuestPanicInformation(info);
1609    }
1610}
1611
1612void qemu_system_reset_request(ShutdownCause reason)
1613{
1614    if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1615        shutdown_requested = reason;
1616    } else {
1617        reset_requested = reason;
1618    }
1619    cpu_stop_current();
1620    qemu_notify_event();
1621}
1622
1623static void qemu_system_suspend(void)
1624{
1625    pause_all_vcpus();
1626    notifier_list_notify(&suspend_notifiers, NULL);
1627    runstate_set(RUN_STATE_SUSPENDED);
1628    qapi_event_send_suspend();
1629}
1630
1631void qemu_system_suspend_request(void)
1632{
1633    if (runstate_check(RUN_STATE_SUSPENDED)) {
1634        return;
1635    }
1636    suspend_requested = 1;
1637    cpu_stop_current();
1638    qemu_notify_event();
1639}
1640
1641void qemu_register_suspend_notifier(Notifier *notifier)
1642{
1643    notifier_list_add(&suspend_notifiers, notifier);
1644}
1645
1646void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1647{
1648    trace_system_wakeup_request(reason);
1649
1650    if (!runstate_check(RUN_STATE_SUSPENDED)) {
1651        error_setg(errp,
1652                   "Unable to wake up: guest is not in suspended state");
1653        return;
1654    }
1655    if (!(wakeup_reason_mask & (1 << reason))) {
1656        return;
1657    }
1658    runstate_set(RUN_STATE_RUNNING);
1659    wakeup_reason = reason;
1660    qemu_notify_event();
1661}
1662
1663void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1664{
1665    if (enabled) {
1666        wakeup_reason_mask |= (1 << reason);
1667    } else {
1668        wakeup_reason_mask &= ~(1 << reason);
1669    }
1670}
1671
1672void qemu_register_wakeup_notifier(Notifier *notifier)
1673{
1674    notifier_list_add(&wakeup_notifiers, notifier);
1675}
1676
1677void qemu_register_wakeup_support(void)
1678{
1679    wakeup_suspend_enabled = true;
1680}
1681
1682bool qemu_wakeup_suspend_enabled(void)
1683{
1684    return wakeup_suspend_enabled;
1685}
1686
1687void qemu_system_killed(int signal, pid_t pid)
1688{
1689    shutdown_signal = signal;
1690    shutdown_pid = pid;
1691    no_shutdown = 0;
1692
1693    /* Cannot call qemu_system_shutdown_request directly because
1694     * we are in a signal handler.
1695     */
1696    shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1697    qemu_notify_event();
1698}
1699
1700void qemu_system_shutdown_request(ShutdownCause reason)
1701{
1702    trace_qemu_system_shutdown_request(reason);
1703    replay_shutdown_request(reason);
1704    shutdown_requested = reason;
1705    qemu_notify_event();
1706}
1707
1708static void qemu_system_powerdown(void)
1709{
1710    qapi_event_send_powerdown();
1711    notifier_list_notify(&powerdown_notifiers, NULL);
1712}
1713
1714static void qemu_system_shutdown(ShutdownCause cause)
1715{
1716    qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1717    notifier_list_notify(&shutdown_notifiers, &cause);
1718}
1719
1720void qemu_system_powerdown_request(void)
1721{
1722    trace_qemu_system_powerdown_request();
1723    powerdown_requested = 1;
1724    qemu_notify_event();
1725}
1726
1727void qemu_register_powerdown_notifier(Notifier *notifier)
1728{
1729    notifier_list_add(&powerdown_notifiers, notifier);
1730}
1731
1732void qemu_register_shutdown_notifier(Notifier *notifier)
1733{
1734    notifier_list_add(&shutdown_notifiers, notifier);
1735}
1736
1737void qemu_system_debug_request(void)
1738{
1739    debug_requested = 1;
1740    qemu_notify_event();
1741}
1742
1743static bool main_loop_should_exit(void)
1744{
1745    RunState r;
1746    ShutdownCause request;
1747
1748    if (preconfig_exit_requested) {
1749        if (runstate_check(RUN_STATE_PRECONFIG)) {
1750            runstate_set(RUN_STATE_PRELAUNCH);
1751        }
1752        preconfig_exit_requested = false;
1753        return true;
1754    }
1755    if (qemu_debug_requested()) {
1756        vm_stop(RUN_STATE_DEBUG);
1757    }
1758    if (qemu_suspend_requested()) {
1759        qemu_system_suspend();
1760    }
1761    request = qemu_shutdown_requested();
1762    if (request) {
1763        qemu_kill_report();
1764        qemu_system_shutdown(request);
1765        if (no_shutdown) {
1766            vm_stop(RUN_STATE_SHUTDOWN);
1767        } else {
1768            return true;
1769        }
1770    }
1771    request = qemu_reset_requested();
1772    if (request) {
1773        pause_all_vcpus();
1774        qemu_system_reset(request);
1775        resume_all_vcpus();
1776        /*
1777         * runstate can change in pause_all_vcpus()
1778         * as iothread mutex is unlocked
1779         */
1780        if (!runstate_check(RUN_STATE_RUNNING) &&
1781                !runstate_check(RUN_STATE_INMIGRATE) &&
1782                !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1783            runstate_set(RUN_STATE_PRELAUNCH);
1784        }
1785    }
1786    if (qemu_wakeup_requested()) {
1787        pause_all_vcpus();
1788        qemu_system_wakeup();
1789        notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1790        wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1791        resume_all_vcpus();
1792        qapi_event_send_wakeup();
1793    }
1794    if (qemu_powerdown_requested()) {
1795        qemu_system_powerdown();
1796    }
1797    if (qemu_vmstop_requested(&r)) {
1798        vm_stop(r);
1799    }
1800    return false;
1801}
1802
1803static void main_loop(void)
1804{
1805#ifdef CONFIG_PROFILER
1806    int64_t ti;
1807#endif
1808    while (!main_loop_should_exit()) {
1809#ifdef CONFIG_PROFILER
1810        ti = profile_getclock();
1811#endif
1812        main_loop_wait(false);
1813#ifdef CONFIG_PROFILER
1814        dev_time += profile_getclock() - ti;
1815#endif
1816    }
1817}
1818
1819static void version(void)
1820{
1821    printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1822           QEMU_COPYRIGHT "\n");
1823}
1824
1825static void help(int exitcode)
1826{
1827    version();
1828    printf("usage: %s [options] [disk_image]\n\n"
1829           "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1830            error_get_progname());
1831
1832#define QEMU_OPTIONS_GENERATE_HELP
1833#include "qemu-options-wrapper.h"
1834
1835    printf("\nDuring emulation, the following keys are useful:\n"
1836           "ctrl-alt-f      toggle full screen\n"
1837           "ctrl-alt-n      switch to virtual console 'n'\n"
1838           "ctrl-alt        toggle mouse and keyboard grab\n"
1839           "\n"
1840           "When using -nographic, press 'ctrl-a h' to get some help.\n"
1841           "\n"
1842           QEMU_HELP_BOTTOM "\n");
1843
1844    exit(exitcode);
1845}
1846
1847#define HAS_ARG 0x0001
1848
1849typedef struct QEMUOption {
1850    const char *name;
1851    int flags;
1852    int index;
1853    uint32_t arch_mask;
1854} QEMUOption;
1855
1856static const QEMUOption qemu_options[] = {
1857    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1858#define QEMU_OPTIONS_GENERATE_OPTIONS
1859#include "qemu-options-wrapper.h"
1860    { NULL },
1861};
1862
1863typedef struct VGAInterfaceInfo {
1864    const char *opt_name;    /* option name */
1865    const char *name;        /* human-readable name */
1866    /* Class names indicating that support is available.
1867     * If no class is specified, the interface is always available */
1868    const char *class_names[2];
1869} VGAInterfaceInfo;
1870
1871static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1872    [VGA_NONE] = {
1873        .opt_name = "none",
1874        .name = "no graphic card",
1875    },
1876    [VGA_STD] = {
1877        .opt_name = "std",
1878        .name = "standard VGA",
1879        .class_names = { "VGA", "isa-vga" },
1880    },
1881    [VGA_CIRRUS] = {
1882        .opt_name = "cirrus",
1883        .name = "Cirrus VGA",
1884        .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1885    },
1886    [VGA_VMWARE] = {
1887        .opt_name = "vmware",
1888        .name = "VMWare SVGA",
1889        .class_names = { "vmware-svga" },
1890    },
1891    [VGA_VIRTIO] = {
1892        .opt_name = "virtio",
1893        .name = "Virtio VGA",
1894        .class_names = { "virtio-vga" },
1895    },
1896    [VGA_QXL] = {
1897        .opt_name = "qxl",
1898        .name = "QXL VGA",
1899        .class_names = { "qxl-vga" },
1900    },
1901    [VGA_TCX] = {
1902        .opt_name = "tcx",
1903        .name = "TCX framebuffer",
1904        .class_names = { "SUNW,tcx" },
1905    },
1906    [VGA_CG3] = {
1907        .opt_name = "cg3",
1908        .name = "CG3 framebuffer",
1909        .class_names = { "cgthree" },
1910    },
1911    [VGA_XENFB] = {
1912        .opt_name = "xenfb",
1913        .name = "Xen paravirtualized framebuffer",
1914    },
1915};
1916
1917static bool vga_interface_available(VGAInterfaceType t)
1918{
1919    const VGAInterfaceInfo *ti = &vga_interfaces[t];
1920
1921    assert(t < VGA_TYPE_MAX);
1922    return !ti->class_names[0] ||
1923           object_class_by_name(ti->class_names[0]) ||
1924           object_class_by_name(ti->class_names[1]);
1925}
1926
1927static const char *
1928get_default_vga_model(const MachineClass *machine_class)
1929{
1930    if (machine_class->default_display) {
1931        return machine_class->default_display;
1932    } else if (vga_interface_available(VGA_CIRRUS)) {
1933        return "cirrus";
1934    } else if (vga_interface_available(VGA_STD)) {
1935        return "std";
1936    }
1937
1938    return NULL;
1939}
1940
1941static void select_vgahw(const MachineClass *machine_class, const char *p)
1942{
1943    const char *opts;
1944    int t;
1945
1946    if (g_str_equal(p, "help")) {
1947        const char *def = get_default_vga_model(machine_class);
1948
1949        for (t = 0; t < VGA_TYPE_MAX; t++) {
1950            const VGAInterfaceInfo *ti = &vga_interfaces[t];
1951
1952            if (vga_interface_available(t) && ti->opt_name) {
1953                printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1954                       g_str_equal(ti->opt_name, def) ? " (default)" : "");
1955            }
1956        }
1957        exit(0);
1958    }
1959
1960    assert(vga_interface_type == VGA_NONE);
1961    for (t = 0; t < VGA_TYPE_MAX; t++) {
1962        const VGAInterfaceInfo *ti = &vga_interfaces[t];
1963        if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1964            if (!vga_interface_available(t)) {
1965                error_report("%s not available", ti->name);
1966                exit(1);
1967            }
1968            vga_interface_type = t;
1969            break;
1970        }
1971    }
1972    if (t == VGA_TYPE_MAX) {
1973    invalid_vga:
1974        error_report("unknown vga type: %s", p);
1975        exit(1);
1976    }
1977    while (*opts) {
1978        const char *nextopt;
1979
1980        if (strstart(opts, ",retrace=", &nextopt)) {
1981            opts = nextopt;
1982            if (strstart(opts, "dumb", &nextopt))
1983                vga_retrace_method = VGA_RETRACE_DUMB;
1984            else if (strstart(opts, "precise", &nextopt))
1985                vga_retrace_method = VGA_RETRACE_PRECISE;
1986            else goto invalid_vga;
1987        } else goto invalid_vga;
1988        opts = nextopt;
1989    }
1990}
1991
1992static void parse_display_qapi(const char *optarg)
1993{
1994    DisplayOptions *opts;
1995    Visitor *v;
1996
1997    v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1998
1999    visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
2000    QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
2001
2002    qapi_free_DisplayOptions(opts);
2003    visit_free(v);
2004}
2005
2006DisplayOptions *qmp_query_display_options(Error **errp)
2007{
2008    return QAPI_CLONE(DisplayOptions, &dpy);
2009}
2010
2011static void parse_display(const char *p)
2012{
2013    const char *opts;
2014
2015    if (strstart(p, "sdl", &opts)) {
2016        /*
2017         * sdl DisplayType needs hand-crafted parser instead of
2018         * parse_display_qapi() due to some options not in
2019         * DisplayOptions, specifically:
2020         *   - frame
2021         *     Already deprecated.
2022         *   - ctrl_grab + alt_grab
2023         *     Not clear yet what happens to them long-term.  Should
2024         *     replaced by something better or deprecated and dropped.
2025         */
2026        dpy.type = DISPLAY_TYPE_SDL;
2027        while (*opts) {
2028            const char *nextopt;
2029
2030            if (strstart(opts, ",alt_grab=", &nextopt)) {
2031                opts = nextopt;
2032                if (strstart(opts, "on", &nextopt)) {
2033                    alt_grab = 1;
2034                } else if (strstart(opts, "off", &nextopt)) {
2035                    alt_grab = 0;
2036                } else {
2037                    goto invalid_sdl_args;
2038                }
2039            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
2040                opts = nextopt;
2041                if (strstart(opts, "on", &nextopt)) {
2042                    ctrl_grab = 1;
2043                } else if (strstart(opts, "off", &nextopt)) {
2044                    ctrl_grab = 0;
2045                } else {
2046                    goto invalid_sdl_args;
2047                }
2048            } else if (strstart(opts, ",window_close=", &nextopt)) {
2049                opts = nextopt;
2050                dpy.has_window_close = true;
2051                if (strstart(opts, "on", &nextopt)) {
2052                    dpy.window_close = true;
2053                } else if (strstart(opts, "off", &nextopt)) {
2054                    dpy.window_close = false;
2055                } else {
2056                    goto invalid_sdl_args;
2057                }
2058            } else if (strstart(opts, ",gl=", &nextopt)) {
2059                opts = nextopt;
2060                dpy.has_gl = true;
2061                if (strstart(opts, "on", &nextopt)) {
2062                    dpy.gl = DISPLAYGL_MODE_ON;
2063                } else if (strstart(opts, "core", &nextopt)) {
2064                    dpy.gl = DISPLAYGL_MODE_CORE;
2065                } else if (strstart(opts, "es", &nextopt)) {
2066                    dpy.gl = DISPLAYGL_MODE_ES;
2067                } else if (strstart(opts, "off", &nextopt)) {
2068                    dpy.gl = DISPLAYGL_MODE_OFF;
2069                } else {
2070                    goto invalid_sdl_args;
2071                }
2072            } else {
2073            invalid_sdl_args:
2074                error_report("invalid SDL option string");
2075                exit(1);
2076            }
2077            opts = nextopt;
2078        }
2079    } else if (strstart(p, "vnc", &opts)) {
2080        /*
2081         * vnc isn't a (local) DisplayType but a protocol for remote
2082         * display access.
2083         */
2084        if (*opts == '=') {
2085            vnc_parse(opts + 1, &error_fatal);
2086        } else {
2087            error_report("VNC requires a display argument vnc=<display>");
2088            exit(1);
2089        }
2090    } else {
2091        parse_display_qapi(p);
2092    }
2093}
2094
2095char *qemu_find_file(int type, const char *name)
2096{
2097    int i;
2098    const char *subdir;
2099    char *buf;
2100
2101    /* Try the name as a straight path first */
2102    if (access(name, R_OK) == 0) {
2103        trace_load_file(name, name);
2104        return g_strdup(name);
2105    }
2106
2107    switch (type) {
2108    case QEMU_FILE_TYPE_BIOS:
2109        subdir = "";
2110        break;
2111    case QEMU_FILE_TYPE_KEYMAP:
2112        subdir = "keymaps/";
2113        break;
2114    default:
2115        abort();
2116    }
2117
2118    for (i = 0; i < data_dir_idx; i++) {
2119        buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2120        if (access(buf, R_OK) == 0) {
2121            trace_load_file(name, buf);
2122            return buf;
2123        }
2124        g_free(buf);
2125    }
2126    return NULL;
2127}
2128
2129static void qemu_add_data_dir(const char *path)
2130{
2131    int i;
2132
2133    if (path == NULL) {
2134        return;
2135    }
2136    if (data_dir_idx == ARRAY_SIZE(data_dir)) {
2137        return;
2138    }
2139    for (i = 0; i < data_dir_idx; i++) {
2140        if (strcmp(data_dir[i], path) == 0) {
2141            return; /* duplicate */
2142        }
2143    }
2144    data_dir[data_dir_idx++] = g_strdup(path);
2145}
2146
2147static inline bool nonempty_str(const char *str)
2148{
2149    return str && *str;
2150}
2151
2152static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2153{
2154    gchar *buf;
2155    size_t size;
2156    const char *name, *file, *str;
2157    FWCfgState *fw_cfg = (FWCfgState *) opaque;
2158
2159    if (fw_cfg == NULL) {
2160        error_setg(errp, "fw_cfg device not available");
2161        return -1;
2162    }
2163    name = qemu_opt_get(opts, "name");
2164    file = qemu_opt_get(opts, "file");
2165    str = qemu_opt_get(opts, "string");
2166
2167    /* we need name and either a file or the content string */
2168    if (!(nonempty_str(name) && (nonempty_str(file) || nonempty_str(str)))) {
2169        error_setg(errp, "invalid argument(s)");
2170        return -1;
2171    }
2172    if (nonempty_str(file) && nonempty_str(str)) {
2173        error_setg(errp, "file and string are mutually exclusive");
2174        return -1;
2175    }
2176    if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2177        error_setg(errp, "name too long (max. %d char)",
2178                   FW_CFG_MAX_FILE_PATH - 1);
2179        return -1;
2180    }
2181    if (strncmp(name, "opt/", 4) != 0) {
2182        warn_report("externally provided fw_cfg item names "
2183                    "should be prefixed with \"opt/\"");
2184    }
2185    if (nonempty_str(str)) {
2186        size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2187        buf = g_memdup(str, size);
2188    } else {
2189        GError *err = NULL;
2190        if (!g_file_get_contents(file, &buf, &size, &err)) {
2191            error_setg(errp, "can't load %s: %s", file, err->message);
2192            g_error_free(err);
2193            return -1;
2194        }
2195    }
2196    /* For legacy, keep user files in a specific global order. */
2197    fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2198    fw_cfg_add_file(fw_cfg, name, buf, size);
2199    fw_cfg_reset_order_override(fw_cfg);
2200    return 0;
2201}
2202
2203static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2204{
2205    return qdev_device_help(opts);
2206}
2207
2208static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2209{
2210    DeviceState *dev;
2211
2212    dev = qdev_device_add(opts, errp);
2213    if (!dev && *errp) {
2214        error_report_err(*errp);
2215        return -1;
2216    } else if (dev) {
2217        object_unref(OBJECT(dev));
2218    }
2219    return 0;
2220}
2221
2222static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2223{
2224    Error *local_err = NULL;
2225
2226    if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
2227        if (local_err) {
2228            error_propagate(errp, local_err);
2229            return -1;
2230        }
2231        exit(0);
2232    }
2233    return 0;
2234}
2235
2236#ifdef CONFIG_VIRTFS
2237static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2238{
2239    return qemu_fsdev_add(opts, errp);
2240}
2241#endif
2242
2243static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2244{
2245    Chardev *chr;
2246    bool qmp;
2247    bool pretty = false;
2248    const char *chardev;
2249    const char *mode;
2250
2251    mode = qemu_opt_get(opts, "mode");
2252    if (mode == NULL) {
2253        mode = "readline";
2254    }
2255    if (strcmp(mode, "readline") == 0) {
2256        qmp = false;
2257    } else if (strcmp(mode, "control") == 0) {
2258        qmp = true;
2259    } else {
2260        error_setg(errp, "unknown monitor mode \"%s\"", mode);
2261        return -1;
2262    }
2263
2264    if (!qmp && qemu_opt_get(opts, "pretty")) {
2265        warn_report("'pretty' is deprecated for HMP monitors, it has no effect "
2266                    "and will be removed in future versions");
2267    }
2268    if (qemu_opt_get_bool(opts, "pretty", 0)) {
2269        pretty = true;
2270    }
2271
2272    chardev = qemu_opt_get(opts, "chardev");
2273    if (!chardev) {
2274        error_report("chardev is required");
2275        exit(1);
2276    }
2277    chr = qemu_chr_find(chardev);
2278    if (chr == NULL) {
2279        error_setg(errp, "chardev \"%s\" not found", chardev);
2280        return -1;
2281    }
2282
2283    if (qmp) {
2284        monitor_init_qmp(chr, pretty);
2285    } else {
2286        monitor_init_hmp(chr, true);
2287    }
2288    return 0;
2289}
2290
2291static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2292{
2293    static int monitor_device_index = 0;
2294    QemuOpts *opts;
2295    const char *p;
2296    char label[32];
2297
2298    if (strstart(optarg, "chardev:", &p)) {
2299        snprintf(label, sizeof(label), "%s", p);
2300    } else {
2301        snprintf(label, sizeof(label), "compat_monitor%d",
2302                 monitor_device_index);
2303        opts = qemu_chr_parse_compat(label, optarg, true);
2304        if (!opts) {
2305            error_report("parse error: %s", optarg);
2306            exit(1);
2307        }
2308    }
2309
2310    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2311    qemu_opt_set(opts, "mode", mode, &error_abort);
2312    qemu_opt_set(opts, "chardev", label, &error_abort);
2313    if (!strcmp(mode, "control")) {
2314        qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2315    } else {
2316        assert(pretty == false);
2317    }
2318    monitor_device_index++;
2319}
2320
2321struct device_config {
2322    enum {
2323        DEV_USB,       /* -usbdevice     */
2324        DEV_BT,        /* -bt            */
2325        DEV_SERIAL,    /* -serial        */
2326        DEV_PARALLEL,  /* -parallel      */
2327        DEV_DEBUGCON,  /* -debugcon */
2328        DEV_GDB,       /* -gdb, -s */
2329        DEV_SCLP,      /* s390 sclp */
2330    } type;
2331    const char *cmdline;
2332    Location loc;
2333    QTAILQ_ENTRY(device_config) next;
2334};
2335
2336static QTAILQ_HEAD(, device_config) device_configs =
2337    QTAILQ_HEAD_INITIALIZER(device_configs);
2338
2339static void add_device_config(int type, const char *cmdline)
2340{
2341    struct device_config *conf;
2342
2343    conf = g_malloc0(sizeof(*conf));
2344    conf->type = type;
2345    conf->cmdline = cmdline;
2346    loc_save(&conf->loc);
2347    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2348}
2349
2350static int foreach_device_config(int type, int (*func)(const char *cmdline))
2351{
2352    struct device_config *conf;
2353    int rc;
2354
2355    QTAILQ_FOREACH(conf, &device_configs, next) {
2356        if (conf->type != type)
2357            continue;
2358        loc_push_restore(&conf->loc);
2359        rc = func(conf->cmdline);
2360        loc_pop(&conf->loc);
2361        if (rc) {
2362            return rc;
2363        }
2364    }
2365    return 0;
2366}
2367
2368static int serial_parse(const char *devname)
2369{
2370    int index = num_serial_hds;
2371    char label[32];
2372
2373    if (strcmp(devname, "none") == 0)
2374        return 0;
2375    snprintf(label, sizeof(label), "serial%d", index);
2376    serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2377
2378    serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2379    if (!serial_hds[index]) {
2380        error_report("could not connect serial device"
2381                     " to character backend '%s'", devname);
2382        return -1;
2383    }
2384    num_serial_hds++;
2385    return 0;
2386}
2387
2388Chardev *serial_hd(int i)
2389{
2390    assert(i >= 0);
2391    if (i < num_serial_hds) {
2392        return serial_hds[i];
2393    }
2394    return NULL;
2395}
2396
2397int serial_max_hds(void)
2398{
2399    return num_serial_hds;
2400}
2401
2402static int parallel_parse(const char *devname)
2403{
2404    static int index = 0;
2405    char label[32];
2406
2407    if (strcmp(devname, "none") == 0)
2408        return 0;
2409    if (index == MAX_PARALLEL_PORTS) {
2410        error_report("too many parallel ports");
2411        exit(1);
2412    }
2413    snprintf(label, sizeof(label), "parallel%d", index);
2414    parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2415    if (!parallel_hds[index]) {
2416        error_report("could not connect parallel device"
2417                     " to character backend '%s'", devname);
2418        return -1;
2419    }
2420    index++;
2421    return 0;
2422}
2423
2424static int debugcon_parse(const char *devname)
2425{
2426    QemuOpts *opts;
2427
2428    if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2429        error_report("invalid character backend '%s'", devname);
2430        exit(1);
2431    }
2432    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2433    if (!opts) {
2434        error_report("already have a debugcon device");
2435        exit(1);
2436    }
2437    qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2438    qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2439    return 0;
2440}
2441
2442static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2443{
2444    const MachineClass *mc1 = a, *mc2 = b;
2445    int res;
2446
2447    if (mc1->family == NULL) {
2448        if (mc2->family == NULL) {
2449            /* Compare standalone machine types against each other; they sort
2450             * in increasing order.
2451             */
2452            return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2453                          object_class_get_name(OBJECT_CLASS(mc2)));
2454        }
2455
2456        /* Standalone machine types sort after families. */
2457        return 1;
2458    }
2459
2460    if (mc2->family == NULL) {
2461        /* Families sort before standalone machine types. */
2462        return -1;
2463    }
2464
2465    /* Families sort between each other alphabetically increasingly. */
2466    res = strcmp(mc1->family, mc2->family);
2467    if (res != 0) {
2468        return res;
2469    }
2470
2471    /* Within the same family, machine types sort in decreasing order. */
2472    return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2473                  object_class_get_name(OBJECT_CLASS(mc1)));
2474}
2475
2476static MachineClass *machine_parse(const char *name, GSList *machines)
2477{
2478    MachineClass *mc;
2479    GSList *el;
2480
2481    if (is_help_option(name)) {
2482        printf("Supported machines are:\n");
2483        machines = g_slist_sort(machines, machine_class_cmp);
2484        for (el = machines; el; el = el->next) {
2485            MachineClass *mc = el->data;
2486            if (mc->alias) {
2487                printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2488            }
2489            printf("%-20s %s%s%s\n", mc->name, mc->desc,
2490                   mc->is_default ? " (default)" : "",
2491                   mc->deprecation_reason ? " (deprecated)" : "");
2492        }
2493        exit(0);
2494    }
2495
2496    mc = find_machine(name, machines);
2497    if (!mc) {
2498        error_report("unsupported machine type");
2499        error_printf("Use -machine help to list supported machines\n");
2500        exit(1);
2501    }
2502    return mc;
2503}
2504
2505void qemu_add_exit_notifier(Notifier *notify)
2506{
2507    notifier_list_add(&exit_notifiers, notify);
2508}
2509
2510void qemu_remove_exit_notifier(Notifier *notify)
2511{
2512    notifier_remove(notify);
2513}
2514
2515static void qemu_run_exit_notifiers(void)
2516{
2517    notifier_list_notify(&exit_notifiers, NULL);
2518}
2519
2520static const char *pid_file;
2521static Notifier qemu_unlink_pidfile_notifier;
2522
2523static void qemu_unlink_pidfile(Notifier *n, void *data)
2524{
2525    if (pid_file) {
2526        unlink(pid_file);
2527    }
2528}
2529
2530bool machine_init_done;
2531
2532void qemu_add_machine_init_done_notifier(Notifier *notify)
2533{
2534    notifier_list_add(&machine_init_done_notifiers, notify);
2535    if (machine_init_done) {
2536        notify->notify(notify, NULL);
2537    }
2538}
2539
2540void qemu_remove_machine_init_done_notifier(Notifier *notify)
2541{
2542    notifier_remove(notify);
2543}
2544
2545static void qemu_run_machine_init_done_notifiers(void)
2546{
2547    machine_init_done = true;
2548    notifier_list_notify(&machine_init_done_notifiers, NULL);
2549}
2550
2551static const QEMUOption *lookup_opt(int argc, char **argv,
2552                                    const char **poptarg, int *poptind)
2553{
2554    const QEMUOption *popt;
2555    int optind = *poptind;
2556    char *r = argv[optind];
2557    const char *optarg;
2558
2559    loc_set_cmdline(argv, optind, 1);
2560    optind++;
2561    /* Treat --foo the same as -foo.  */
2562    if (r[1] == '-')
2563        r++;
2564    popt = qemu_options;
2565    for(;;) {
2566        if (!popt->name) {
2567            error_report("invalid option");
2568            exit(1);
2569        }
2570        if (!strcmp(popt->name, r + 1))
2571            break;
2572        popt++;
2573    }
2574    if (popt->flags & HAS_ARG) {
2575        if (optind >= argc) {
2576            error_report("requires an argument");
2577            exit(1);
2578        }
2579        optarg = argv[optind++];
2580        loc_set_cmdline(argv, optind - 2, 2);
2581    } else {
2582        optarg = NULL;
2583    }
2584
2585    *poptarg = optarg;
2586    *poptind = optind;
2587
2588    return popt;
2589}
2590
2591static MachineClass *select_machine(void)
2592{
2593    GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2594    MachineClass *machine_class = find_default_machine(machines);
2595    const char *optarg;
2596    QemuOpts *opts;
2597    Location loc;
2598
2599    loc_push_none(&loc);
2600
2601    opts = qemu_get_machine_opts();
2602    qemu_opts_loc_restore(opts);
2603
2604    optarg = qemu_opt_get(opts, "type");
2605    if (optarg) {
2606        machine_class = machine_parse(optarg, machines);
2607    }
2608
2609    if (!machine_class) {
2610        error_report("No machine specified, and there is no default");
2611        error_printf("Use -machine help to list supported machines\n");
2612        exit(1);
2613    }
2614
2615    loc_pop(&loc);
2616    g_slist_free(machines);
2617    return machine_class;
2618}
2619
2620static int machine_set_property(void *opaque,
2621                                const char *name, const char *value,
2622                                Error **errp)
2623{
2624    Object *obj = OBJECT(opaque);
2625    Error *local_err = NULL;
2626    char *p, *qom_name;
2627
2628    if (strcmp(name, "type") == 0) {
2629        return 0;
2630    }
2631
2632    qom_name = g_strdup(name);
2633    for (p = qom_name; *p; p++) {
2634        if (*p == '_') {
2635            *p = '-';
2636        }
2637    }
2638
2639    object_property_parse(obj, value, qom_name, &local_err);
2640    g_free(qom_name);
2641
2642    if (local_err) {
2643        error_propagate(errp, local_err);
2644        return -1;
2645    }
2646
2647    return 0;
2648}
2649
2650
2651/*
2652 * Initial object creation happens before all other
2653 * QEMU data types are created. The majority of objects
2654 * can be created at this point. The rng-egd object
2655 * cannot be created here, as it depends on the chardev
2656 * already existing.
2657 */
2658static bool object_create_initial(const char *type, QemuOpts *opts)
2659{
2660    if (user_creatable_print_help(type, opts)) {
2661        exit(0);
2662    }
2663
2664    /*
2665     * Objects should not be made "delayed" without a reason.  If you
2666     * add one, state the reason in a comment!
2667     */
2668
2669    /* Reason: rng-egd property "chardev" */
2670    if (g_str_equal(type, "rng-egd")) {
2671        return false;
2672    }
2673
2674#if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2675    /* Reason: cryptodev-vhost-user property "chardev" */
2676    if (g_str_equal(type, "cryptodev-vhost-user")) {
2677        return false;
2678    }
2679#endif
2680
2681    /*
2682     * Reason: filter-* property "netdev" etc.
2683     */
2684    if (g_str_equal(type, "filter-buffer") ||
2685        g_str_equal(type, "filter-dump") ||
2686        g_str_equal(type, "filter-mirror") ||
2687        g_str_equal(type, "filter-redirector") ||
2688        g_str_equal(type, "colo-compare") ||
2689        g_str_equal(type, "filter-rewriter") ||
2690        g_str_equal(type, "filter-replay")) {
2691        return false;
2692    }
2693
2694    /* Memory allocation by backends needs to be done
2695     * after configure_accelerator() (due to the tcg_enabled()
2696     * checks at memory_region_init_*()).
2697     *
2698     * Also, allocation of large amounts of memory may delay
2699     * chardev initialization for too long, and trigger timeouts
2700     * on software that waits for a monitor socket to be created
2701     * (e.g. libvirt).
2702     */
2703    if (g_str_has_prefix(type, "memory-backend-")) {
2704        return false;
2705    }
2706
2707    return true;
2708}
2709
2710
2711/*
2712 * The remainder of object creation happens after the
2713 * creation of chardev, fsdev, net clients and device data types.
2714 */
2715static bool object_create_delayed(const char *type, QemuOpts *opts)
2716{
2717    return !object_create_initial(type, opts);
2718}
2719
2720
2721static void set_memory_options(uint64_t *ram_slots, ram_addr_t *maxram_size,
2722                               MachineClass *mc)
2723{
2724    uint64_t sz;
2725    const char *mem_str;
2726    const ram_addr_t default_ram_size = mc->default_ram_size;
2727    QemuOpts *opts = qemu_find_opts_singleton("memory");
2728    Location loc;
2729
2730    loc_push_none(&loc);
2731    qemu_opts_loc_restore(opts);
2732
2733    sz = 0;
2734    mem_str = qemu_opt_get(opts, "size");
2735    if (mem_str) {
2736        if (!*mem_str) {
2737            error_report("missing 'size' option value");
2738            exit(EXIT_FAILURE);
2739        }
2740
2741        sz = qemu_opt_get_size(opts, "size", ram_size);
2742
2743        /* Fix up legacy suffix-less format */
2744        if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2745            uint64_t overflow_check = sz;
2746
2747            sz *= MiB;
2748            if (sz / MiB != overflow_check) {
2749                error_report("too large 'size' option value");
2750                exit(EXIT_FAILURE);
2751            }
2752        }
2753    }
2754
2755    /* backward compatibility behaviour for case "-m 0" */
2756    if (sz == 0) {
2757        sz = default_ram_size;
2758    }
2759
2760    sz = QEMU_ALIGN_UP(sz, 8192);
2761    ram_size = sz;
2762    if (ram_size != sz) {
2763        error_report("ram size too large");
2764        exit(EXIT_FAILURE);
2765    }
2766
2767    /* store value for the future use */
2768    qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2769    *maxram_size = ram_size;
2770
2771    if (qemu_opt_get(opts, "maxmem")) {
2772        uint64_t slots;
2773
2774        sz = qemu_opt_get_size(opts, "maxmem", 0);
2775        slots = qemu_opt_get_number(opts, "slots", 0);
2776        if (sz < ram_size) {
2777            error_report("invalid value of -m option maxmem: "
2778                         "maximum memory size (0x%" PRIx64 ") must be at least "
2779                         "the initial memory size (0x" RAM_ADDR_FMT ")",
2780                         sz, ram_size);
2781            exit(EXIT_FAILURE);
2782        } else if (slots && sz == ram_size) {
2783            error_report("invalid value of -m option maxmem: "
2784                         "memory slots were specified but maximum memory size "
2785                         "(0x%" PRIx64 ") is equal to the initial memory size "
2786                         "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2787            exit(EXIT_FAILURE);
2788        }
2789
2790        *maxram_size = sz;
2791        *ram_slots = slots;
2792    } else if (qemu_opt_get(opts, "slots")) {
2793        error_report("invalid -m option value: missing 'maxmem' option");
2794        exit(EXIT_FAILURE);
2795    }
2796
2797    loc_pop(&loc);
2798}
2799
2800static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2801{
2802    GlobalProperty *g;
2803
2804    g = g_malloc0(sizeof(*g));
2805    g->driver   = qemu_opt_get(opts, "driver");
2806    g->property = qemu_opt_get(opts, "property");
2807    g->value    = qemu_opt_get(opts, "value");
2808    qdev_prop_register_global(g);
2809    return 0;
2810}
2811
2812static int qemu_read_default_config_file(void)
2813{
2814    int ret;
2815
2816    ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2817    if (ret < 0 && ret != -ENOENT) {
2818        return ret;
2819    }
2820
2821    return 0;
2822}
2823
2824static void user_register_global_props(void)
2825{
2826    qemu_opts_foreach(qemu_find_opts("global"),
2827                      global_init_func, NULL, NULL);
2828}
2829
2830int main(int argc, char **argv, char **envp)
2831{
2832    int i;
2833    int snapshot, linux_boot;
2834    const char *initrd_filename;
2835    const char *kernel_filename, *kernel_cmdline;
2836    const char *boot_order = NULL;
2837    const char *boot_once = NULL;
2838    DisplayState *ds;
2839    QemuOpts *opts, *machine_opts;
2840    QemuOpts *icount_opts = NULL, *accel_opts = NULL;
2841    QemuOptsList *olist;
2842    int optind;
2843    const char *optarg;
2844    const char *loadvm = NULL;
2845    MachineClass *machine_class;
2846    const char *cpu_option;
2847    const char *vga_model = NULL;
2848    const char *qtest_chrdev = NULL;
2849    const char *qtest_log = NULL;
2850    const char *incoming = NULL;
2851    bool userconfig = true;
2852    bool nographic = false;
2853    int display_remote = 0;
2854    const char *log_mask = NULL;
2855    const char *log_file = NULL;
2856    char *trace_file = NULL;
2857    ram_addr_t maxram_size;
2858    uint64_t ram_slots = 0;
2859    FILE *vmstate_dump_file = NULL;
2860    Error *main_loop_err = NULL;
2861    Error *err = NULL;
2862    bool list_data_dirs = false;
2863    char *dir, **dirs;
2864    BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
2865    QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
2866
2867    os_set_line_buffering();
2868
2869    error_init(argv[0]);
2870    module_call_init(MODULE_INIT_TRACE);
2871
2872    qemu_init_cpu_list();
2873    qemu_init_cpu_loop();
2874
2875    qemu_mutex_lock_iothread();
2876
2877    atexit(qemu_run_exit_notifiers);
2878    qemu_init_exec_dir(argv[0]);
2879
2880    module_call_init(MODULE_INIT_QOM);
2881
2882    qemu_add_opts(&qemu_drive_opts);
2883    qemu_add_drive_opts(&qemu_legacy_drive_opts);
2884    qemu_add_drive_opts(&qemu_common_drive_opts);
2885    qemu_add_drive_opts(&qemu_drive_opts);
2886    qemu_add_drive_opts(&bdrv_runtime_opts);
2887    qemu_add_opts(&qemu_chardev_opts);
2888    qemu_add_opts(&qemu_device_opts);
2889    qemu_add_opts(&qemu_netdev_opts);
2890    qemu_add_opts(&qemu_nic_opts);
2891    qemu_add_opts(&qemu_net_opts);
2892    qemu_add_opts(&qemu_rtc_opts);
2893    qemu_add_opts(&qemu_global_opts);
2894    qemu_add_opts(&qemu_mon_opts);
2895    qemu_add_opts(&qemu_trace_opts);
2896    qemu_plugin_add_opts();
2897    qemu_add_opts(&qemu_option_rom_opts);
2898    qemu_add_opts(&qemu_machine_opts);
2899    qemu_add_opts(&qemu_accel_opts);
2900    qemu_add_opts(&qemu_mem_opts);
2901    qemu_add_opts(&qemu_smp_opts);
2902    qemu_add_opts(&qemu_boot_opts);
2903    qemu_add_opts(&qemu_add_fd_opts);
2904    qemu_add_opts(&qemu_object_opts);
2905    qemu_add_opts(&qemu_tpmdev_opts);
2906    qemu_add_opts(&qemu_realtime_opts);
2907    qemu_add_opts(&qemu_overcommit_opts);
2908    qemu_add_opts(&qemu_msg_opts);
2909    qemu_add_opts(&qemu_name_opts);
2910    qemu_add_opts(&qemu_numa_opts);
2911    qemu_add_opts(&qemu_icount_opts);
2912    qemu_add_opts(&qemu_semihosting_config_opts);
2913    qemu_add_opts(&qemu_fw_cfg_opts);
2914    module_call_init(MODULE_INIT_OPTS);
2915
2916    runstate_init();
2917    precopy_infrastructure_init();
2918    postcopy_infrastructure_init();
2919    monitor_init_globals();
2920
2921    if (qcrypto_init(&err) < 0) {
2922        error_reportf_err(err, "cannot initialize crypto: ");
2923        exit(1);
2924    }
2925
2926    QTAILQ_INIT(&vm_change_state_head);
2927    os_setup_early_signal_handling();
2928
2929    cpu_option = NULL;
2930    snapshot = 0;
2931
2932    nb_nics = 0;
2933
2934    bdrv_init_with_whitelist();
2935
2936    autostart = 1;
2937
2938    /* first pass of option parsing */
2939    optind = 1;
2940    while (optind < argc) {
2941        if (argv[optind][0] != '-') {
2942            /* disk image */
2943            optind++;
2944        } else {
2945            const QEMUOption *popt;
2946
2947            popt = lookup_opt(argc, argv, &optarg, &optind);
2948            switch (popt->index) {
2949            case QEMU_OPTION_nouserconfig:
2950                userconfig = false;
2951                break;
2952            }
2953        }
2954    }
2955
2956    if (userconfig) {
2957        if (qemu_read_default_config_file() < 0) {
2958            exit(1);
2959        }
2960    }
2961
2962    /* second pass of option parsing */
2963    optind = 1;
2964    for(;;) {
2965        if (optind >= argc)
2966            break;
2967        if (argv[optind][0] != '-') {
2968            loc_set_cmdline(argv, optind, 1);
2969            drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2970        } else {
2971            const QEMUOption *popt;
2972
2973            popt = lookup_opt(argc, argv, &optarg, &optind);
2974            if (!(popt->arch_mask & arch_type)) {
2975                error_report("Option not supported for this target");
2976                exit(1);
2977            }
2978            switch(popt->index) {
2979            case QEMU_OPTION_cpu:
2980                /* hw initialization will check this */
2981                cpu_option = optarg;
2982                break;
2983            case QEMU_OPTION_hda:
2984            case QEMU_OPTION_hdb:
2985            case QEMU_OPTION_hdc:
2986            case QEMU_OPTION_hdd:
2987                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2988                          HD_OPTS);
2989                break;
2990            case QEMU_OPTION_blockdev:
2991                {
2992                    Visitor *v;
2993                    BlockdevOptionsQueueEntry *bdo;
2994
2995                    v = qobject_input_visitor_new_str(optarg, "driver",
2996                                                      &error_fatal);
2997
2998                    bdo = g_new(BlockdevOptionsQueueEntry, 1);
2999                    visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3000                                               &error_fatal);
3001                    visit_free(v);
3002                    loc_save(&bdo->loc);
3003                    QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3004                    break;
3005                }
3006            case QEMU_OPTION_drive:
3007                if (drive_def(optarg) == NULL) {
3008                    exit(1);
3009                }
3010                break;
3011            case QEMU_OPTION_set:
3012                if (qemu_set_option(optarg) != 0)
3013                    exit(1);
3014                break;
3015            case QEMU_OPTION_global:
3016                if (qemu_global_option(optarg) != 0)
3017                    exit(1);
3018                break;
3019            case QEMU_OPTION_mtdblock:
3020                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3021                break;
3022            case QEMU_OPTION_sd:
3023                drive_add(IF_SD, -1, optarg, SD_OPTS);
3024                break;
3025            case QEMU_OPTION_pflash:
3026                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3027                break;
3028            case QEMU_OPTION_snapshot:
3029                {
3030                    Error *blocker = NULL;
3031                    snapshot = 1;
3032                    error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3033                               "-snapshot");
3034                    replay_add_blocker(blocker);
3035                }
3036                break;
3037            case QEMU_OPTION_numa:
3038                opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3039                                               optarg, true);
3040                if (!opts) {
3041                    exit(1);
3042                }
3043                break;
3044            case QEMU_OPTION_display:
3045                parse_display(optarg);
3046                break;
3047            case QEMU_OPTION_nographic:
3048                olist = qemu_find_opts("machine");
3049                qemu_opts_parse_noisily(olist, "graphics=off", false);
3050                nographic = true;
3051                dpy.type = DISPLAY_TYPE_NONE;
3052                break;
3053            case QEMU_OPTION_curses:
3054#ifdef CONFIG_CURSES
3055                dpy.type = DISPLAY_TYPE_CURSES;
3056#else
3057                error_report("curses or iconv support is disabled");
3058                exit(1);
3059#endif
3060                break;
3061            case QEMU_OPTION_portrait:
3062                graphic_rotate = 90;
3063                break;
3064            case QEMU_OPTION_rotate:
3065                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3066                if (graphic_rotate != 0 && graphic_rotate != 90 &&
3067                    graphic_rotate != 180 && graphic_rotate != 270) {
3068                    error_report("only 90, 180, 270 deg rotation is available");
3069                    exit(1);
3070                }
3071                break;
3072            case QEMU_OPTION_kernel:
3073                qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg,
3074                              &error_abort);
3075                break;
3076            case QEMU_OPTION_initrd:
3077                qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg,
3078                              &error_abort);
3079                break;
3080            case QEMU_OPTION_append:
3081                qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg,
3082                              &error_abort);
3083                break;
3084            case QEMU_OPTION_dtb:
3085                qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg,
3086                              &error_abort);
3087                break;
3088            case QEMU_OPTION_cdrom:
3089                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3090                break;
3091            case QEMU_OPTION_boot:
3092                opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3093                                               optarg, true);
3094                if (!opts) {
3095                    exit(1);
3096                }
3097                break;
3098            case QEMU_OPTION_fda:
3099            case QEMU_OPTION_fdb:
3100                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3101                          optarg, FD_OPTS);
3102                break;
3103            case QEMU_OPTION_no_fd_bootchk:
3104                fd_bootchk = 0;
3105                break;
3106            case QEMU_OPTION_netdev:
3107                default_net = 0;
3108                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3109                    exit(1);
3110                }
3111                break;
3112            case QEMU_OPTION_nic:
3113                default_net = 0;
3114                if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3115                    exit(1);
3116                }
3117                break;
3118            case QEMU_OPTION_net:
3119                default_net = 0;
3120                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3121                    exit(1);
3122                }
3123                break;
3124#ifdef CONFIG_LIBISCSI
3125            case QEMU_OPTION_iscsi:
3126                opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3127                                               optarg, false);
3128                if (!opts) {
3129                    exit(1);
3130                }
3131                break;
3132#endif
3133            case QEMU_OPTION_bt:
3134                warn_report("The bluetooth subsystem is deprecated and will "
3135                            "be removed soon. If the bluetooth subsystem is "
3136                            "still useful for you, please send a mail to "
3137                            "qemu-devel@nongnu.org with your usecase.");
3138                add_device_config(DEV_BT, optarg);
3139                break;
3140            case QEMU_OPTION_audio_help:
3141                audio_legacy_help();
3142                exit (0);
3143                break;
3144            case QEMU_OPTION_audiodev:
3145                audio_parse_option(optarg);
3146                break;
3147            case QEMU_OPTION_soundhw:
3148                select_soundhw (optarg);
3149                break;
3150            case QEMU_OPTION_h:
3151                help(0);
3152                break;
3153            case QEMU_OPTION_version:
3154                version();
3155                exit(0);
3156                break;
3157            case QEMU_OPTION_m:
3158                opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3159                                               optarg, true);
3160                if (!opts) {
3161                    exit(EXIT_FAILURE);
3162                }
3163                break;
3164#ifdef CONFIG_TPM
3165            case QEMU_OPTION_tpmdev:
3166                if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3167                    exit(1);
3168                }
3169                break;
3170#endif
3171            case QEMU_OPTION_mempath:
3172                mem_path = optarg;
3173                break;
3174            case QEMU_OPTION_mem_prealloc:
3175                mem_prealloc = 1;
3176                break;
3177            case QEMU_OPTION_d:
3178                log_mask = optarg;
3179                break;
3180            case QEMU_OPTION_D:
3181                log_file = optarg;
3182                break;
3183            case QEMU_OPTION_DFILTER:
3184                qemu_set_dfilter_ranges(optarg, &error_fatal);
3185                break;
3186            case QEMU_OPTION_seed:
3187                qemu_guest_random_seed_main(optarg, &error_fatal);
3188                break;
3189            case QEMU_OPTION_s:
3190                add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3191                break;
3192            case QEMU_OPTION_gdb:
3193                add_device_config(DEV_GDB, optarg);
3194                break;
3195            case QEMU_OPTION_L:
3196                if (is_help_option(optarg)) {
3197                    list_data_dirs = true;
3198                } else {
3199                    qemu_add_data_dir(optarg);
3200                }
3201                break;
3202            case QEMU_OPTION_bios:
3203                qemu_opts_set(qemu_find_opts("machine"), 0, "firmware", optarg,
3204                              &error_abort);
3205                break;
3206            case QEMU_OPTION_singlestep:
3207                singlestep = 1;
3208                break;
3209            case QEMU_OPTION_S:
3210                autostart = 0;
3211                break;
3212            case QEMU_OPTION_k:
3213                keyboard_layout = optarg;
3214                break;
3215            case QEMU_OPTION_vga:
3216                vga_model = optarg;
3217                default_vga = 0;
3218                break;
3219            case QEMU_OPTION_g:
3220                {
3221                    const char *p;
3222                    int w, h, depth;
3223                    p = optarg;
3224                    w = strtol(p, (char **)&p, 10);
3225                    if (w <= 0) {
3226                    graphic_error:
3227                        error_report("invalid resolution or depth");
3228                        exit(1);
3229                    }
3230                    if (*p != 'x')
3231                        goto graphic_error;
3232                    p++;
3233                    h = strtol(p, (char **)&p, 10);
3234                    if (h <= 0)
3235                        goto graphic_error;
3236                    if (*p == 'x') {
3237                        p++;
3238                        depth = strtol(p, (char **)&p, 10);
3239                        if (depth != 1 && depth != 2 && depth != 4 &&
3240                            depth != 8 && depth != 15 && depth != 16 &&
3241                            depth != 24 && depth != 32)
3242                            goto graphic_error;
3243                    } else if (*p == '\0') {
3244                        depth = graphic_depth;
3245                    } else {
3246                        goto graphic_error;
3247                    }
3248
3249                    graphic_width = w;
3250                    graphic_height = h;
3251                    graphic_depth = depth;
3252                }
3253                break;
3254            case QEMU_OPTION_echr:
3255                {
3256                    char *r;
3257                    term_escape_char = strtol(optarg, &r, 0);
3258                    if (r == optarg)
3259                        printf("Bad argument to echr\n");
3260                    break;
3261                }
3262            case QEMU_OPTION_monitor:
3263                default_monitor = 0;
3264                if (strncmp(optarg, "none", 4)) {
3265                    monitor_parse(optarg, "readline", false);
3266                }
3267                break;
3268            case QEMU_OPTION_qmp:
3269                monitor_parse(optarg, "control", false);
3270                default_monitor = 0;
3271                break;
3272            case QEMU_OPTION_qmp_pretty:
3273                monitor_parse(optarg, "control", true);
3274                default_monitor = 0;
3275                break;
3276            case QEMU_OPTION_mon:
3277                opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3278                                               true);
3279                if (!opts) {
3280                    exit(1);
3281                }
3282                default_monitor = 0;
3283                break;
3284            case QEMU_OPTION_chardev:
3285                opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3286                                               optarg, true);
3287                if (!opts) {
3288                    exit(1);
3289                }
3290                break;
3291            case QEMU_OPTION_fsdev:
3292                olist = qemu_find_opts("fsdev");
3293                if (!olist) {
3294                    error_report("fsdev support is disabled");
3295                    exit(1);
3296                }
3297                opts = qemu_opts_parse_noisily(olist, optarg, true);
3298                if (!opts) {
3299                    exit(1);
3300                }
3301                break;
3302            case QEMU_OPTION_virtfs: {
3303                QemuOpts *fsdev;
3304                QemuOpts *device;
3305                const char *writeout, *sock_fd, *socket, *path, *security_model,
3306                           *multidevs;
3307
3308                olist = qemu_find_opts("virtfs");
3309                if (!olist) {
3310                    error_report("virtfs support is disabled");
3311                    exit(1);
3312                }
3313                opts = qemu_opts_parse_noisily(olist, optarg, true);
3314                if (!opts) {
3315                    exit(1);
3316                }
3317
3318                if (qemu_opt_get(opts, "fsdriver") == NULL ||
3319                    qemu_opt_get(opts, "mount_tag") == NULL) {
3320                    error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3321                    exit(1);
3322                }
3323                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3324                                         qemu_opts_id(opts) ?:
3325                                         qemu_opt_get(opts, "mount_tag"),
3326                                         1, NULL);
3327                if (!fsdev) {
3328                    error_report("duplicate or invalid fsdev id: %s",
3329                                 qemu_opt_get(opts, "mount_tag"));
3330                    exit(1);
3331                }
3332
3333                writeout = qemu_opt_get(opts, "writeout");
3334                if (writeout) {
3335#ifdef CONFIG_SYNC_FILE_RANGE
3336                    qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3337#else
3338                    error_report("writeout=immediate not supported "
3339                                 "on this platform");
3340                    exit(1);
3341#endif
3342                }
3343                qemu_opt_set(fsdev, "fsdriver",
3344                             qemu_opt_get(opts, "fsdriver"), &error_abort);
3345                path = qemu_opt_get(opts, "path");
3346                if (path) {
3347                    qemu_opt_set(fsdev, "path", path, &error_abort);
3348                }
3349                security_model = qemu_opt_get(opts, "security_model");
3350                if (security_model) {
3351                    qemu_opt_set(fsdev, "security_model", security_model,
3352                                 &error_abort);
3353                }
3354                socket = qemu_opt_get(opts, "socket");
3355                if (socket) {
3356                    qemu_opt_set(fsdev, "socket", socket, &error_abort);
3357                }
3358                sock_fd = qemu_opt_get(opts, "sock_fd");
3359                if (sock_fd) {
3360                    qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3361                }
3362
3363                qemu_opt_set_bool(fsdev, "readonly",
3364                                  qemu_opt_get_bool(opts, "readonly", 0),
3365                                  &error_abort);
3366                multidevs = qemu_opt_get(opts, "multidevs");
3367                if (multidevs) {
3368                    qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3369                }
3370                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3371                                          &error_abort);
3372                qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3373                qemu_opt_set(device, "fsdev",
3374                             qemu_opts_id(fsdev), &error_abort);
3375                qemu_opt_set(device, "mount_tag",
3376                             qemu_opt_get(opts, "mount_tag"), &error_abort);
3377                break;
3378            }
3379            case QEMU_OPTION_virtfs_synth: {
3380                QemuOpts *fsdev;
3381                QemuOpts *device;
3382
3383                warn_report("'-virtfs_synth' is deprecated, please use "
3384                             "'-fsdev synth' and '-device virtio-9p-...' "
3385                            "instead");
3386
3387                fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3388                                         1, NULL);
3389                if (!fsdev) {
3390                    error_report("duplicate option: %s", "virtfs_synth");
3391                    exit(1);
3392                }
3393                qemu_opt_set(fsdev, "fsdriver", "synth", &error_abort);
3394
3395                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3396                                          &error_abort);
3397                qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3398                qemu_opt_set(device, "fsdev", "v_synth", &error_abort);
3399                qemu_opt_set(device, "mount_tag", "v_synth", &error_abort);
3400                break;
3401            }
3402            case QEMU_OPTION_serial:
3403                add_device_config(DEV_SERIAL, optarg);
3404                default_serial = 0;
3405                if (strncmp(optarg, "mon:", 4) == 0) {
3406                    default_monitor = 0;
3407                }
3408                break;
3409            case QEMU_OPTION_watchdog:
3410                if (watchdog) {
3411                    error_report("only one watchdog option may be given");
3412                    return 1;
3413                }
3414                watchdog = optarg;
3415                break;
3416            case QEMU_OPTION_watchdog_action:
3417                if (select_watchdog_action(optarg) == -1) {
3418                    error_report("unknown -watchdog-action parameter");
3419                    exit(1);
3420                }
3421                break;
3422            case QEMU_OPTION_parallel:
3423                add_device_config(DEV_PARALLEL, optarg);
3424                default_parallel = 0;
3425                if (strncmp(optarg, "mon:", 4) == 0) {
3426                    default_monitor = 0;
3427                }
3428                break;
3429            case QEMU_OPTION_debugcon:
3430                add_device_config(DEV_DEBUGCON, optarg);
3431                break;
3432            case QEMU_OPTION_loadvm:
3433                loadvm = optarg;
3434                break;
3435            case QEMU_OPTION_full_screen:
3436                dpy.has_full_screen = true;
3437                dpy.full_screen = true;
3438                break;
3439            case QEMU_OPTION_alt_grab:
3440                alt_grab = 1;
3441                break;
3442            case QEMU_OPTION_ctrl_grab:
3443                ctrl_grab = 1;
3444                break;
3445            case QEMU_OPTION_no_quit:
3446                dpy.has_window_close = true;
3447                dpy.window_close = false;
3448                break;
3449            case QEMU_OPTION_sdl:
3450#ifdef CONFIG_SDL
3451                dpy.type = DISPLAY_TYPE_SDL;
3452                break;
3453#else
3454                error_report("SDL support is disabled");
3455                exit(1);
3456#endif
3457            case QEMU_OPTION_pidfile:
3458                pid_file = optarg;
3459                break;
3460            case QEMU_OPTION_win2k_hack:
3461                win2k_install_hack = 1;
3462                break;
3463            case QEMU_OPTION_acpitable:
3464                opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3465                                               optarg, true);
3466                if (!opts) {
3467                    exit(1);
3468                }
3469                acpi_table_add(opts, &error_fatal);
3470                break;
3471            case QEMU_OPTION_smbios:
3472                opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3473                                               optarg, false);
3474                if (!opts) {
3475                    exit(1);
3476                }
3477                smbios_entry_add(opts, &error_fatal);
3478                break;
3479            case QEMU_OPTION_fwcfg:
3480                opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3481                                               optarg, true);
3482                if (opts == NULL) {
3483                    exit(1);
3484                }
3485                break;
3486            case QEMU_OPTION_preconfig:
3487                preconfig_exit_requested = false;
3488                break;
3489            case QEMU_OPTION_enable_kvm:
3490                olist = qemu_find_opts("machine");
3491                qemu_opts_parse_noisily(olist, "accel=kvm", false);
3492                break;
3493            case QEMU_OPTION_M:
3494            case QEMU_OPTION_machine:
3495                olist = qemu_find_opts("machine");
3496                opts = qemu_opts_parse_noisily(olist, optarg, true);
3497                if (!opts) {
3498                    exit(1);
3499                }
3500                break;
3501             case QEMU_OPTION_no_kvm:
3502                olist = qemu_find_opts("machine");
3503                qemu_opts_parse_noisily(olist, "accel=tcg", false);
3504                break;
3505            case QEMU_OPTION_accel:
3506                accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3507                                                     optarg, true);
3508                optarg = qemu_opt_get(accel_opts, "accel");
3509                if (!optarg || is_help_option(optarg)) {
3510                    printf("Accelerators supported in QEMU binary:\n");
3511                    GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3512                                                                    false);
3513                    for (el = accel_list; el; el = el->next) {
3514                        gchar *typename = g_strdup(object_class_get_name(
3515                                                   OBJECT_CLASS(el->data)));
3516                        /* omit qtest which is used for tests only */
3517                        if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3518                            g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3519                            gchar **optname = g_strsplit(typename,
3520                                                         ACCEL_CLASS_SUFFIX, 0);
3521                            printf("%s\n", optname[0]);
3522                            g_free(optname);
3523                        }
3524                        g_free(typename);
3525                    }
3526                    g_slist_free(accel_list);
3527                    exit(0);
3528                }
3529                if (optarg && strchr(optarg, ':')) {
3530                    error_report("Don't use ':' with -accel, "
3531                                 "use -M accel=... for now instead");
3532                    exit(1);
3533                }
3534                opts = qemu_opts_create(qemu_find_opts("machine"), NULL,
3535                                        false, &error_abort);
3536                qemu_opt_set(opts, "accel", optarg, &error_abort);
3537                break;
3538            case QEMU_OPTION_usb:
3539                olist = qemu_find_opts("machine");
3540                qemu_opts_parse_noisily(olist, "usb=on", false);
3541                break;
3542            case QEMU_OPTION_usbdevice:
3543                error_report("'-usbdevice' is deprecated, please use "
3544                             "'-device usb-...' instead");
3545                olist = qemu_find_opts("machine");
3546                qemu_opts_parse_noisily(olist, "usb=on", false);
3547                add_device_config(DEV_USB, optarg);
3548                break;
3549            case QEMU_OPTION_device:
3550                if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3551                                             optarg, true)) {
3552                    exit(1);
3553                }
3554                break;
3555            case QEMU_OPTION_smp:
3556                if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3557                                             optarg, true)) {
3558                    exit(1);
3559                }
3560                break;
3561            case QEMU_OPTION_vnc:
3562                vnc_parse(optarg, &error_fatal);
3563                break;
3564            case QEMU_OPTION_no_acpi:
3565                acpi_enabled = 0;
3566                break;
3567            case QEMU_OPTION_no_hpet:
3568                no_hpet = 1;
3569                break;
3570            case QEMU_OPTION_no_reboot:
3571                no_reboot = 1;
3572                break;
3573            case QEMU_OPTION_no_shutdown:
3574                no_shutdown = 1;
3575                break;
3576            case QEMU_OPTION_show_cursor:
3577                cursor_hide = 0;
3578                break;
3579            case QEMU_OPTION_uuid:
3580                if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3581                    error_report("failed to parse UUID string: wrong format");
3582                    exit(1);
3583                }
3584                qemu_uuid_set = true;
3585                break;
3586            case QEMU_OPTION_option_rom:
3587                if (nb_option_roms >= MAX_OPTION_ROMS) {
3588                    error_report("too many option ROMs");
3589                    exit(1);
3590                }
3591                opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3592                                               optarg, true);
3593                if (!opts) {
3594                    exit(1);
3595                }
3596                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3597                option_rom[nb_option_roms].bootindex =
3598                    qemu_opt_get_number(opts, "bootindex", -1);
3599                if (!option_rom[nb_option_roms].name) {
3600                    error_report("Option ROM file is not specified");
3601                    exit(1);
3602                }
3603                nb_option_roms++;
3604                break;
3605            case QEMU_OPTION_semihosting:
3606                qemu_semihosting_enable();
3607                break;
3608            case QEMU_OPTION_semihosting_config:
3609                if (qemu_semihosting_config_options(optarg) != 0) {
3610                    exit(1);
3611                }
3612                break;
3613            case QEMU_OPTION_name:
3614                opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3615                                               optarg, true);
3616                if (!opts) {
3617                    exit(1);
3618                }
3619                break;
3620            case QEMU_OPTION_prom_env:
3621                if (nb_prom_envs >= MAX_PROM_ENVS) {
3622                    error_report("too many prom variables");
3623                    exit(1);
3624                }
3625                prom_envs[nb_prom_envs] = optarg;
3626                nb_prom_envs++;
3627                break;
3628            case QEMU_OPTION_old_param:
3629                old_param = 1;
3630                break;
3631            case QEMU_OPTION_rtc:
3632                opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3633                                               false);
3634                if (!opts) {
3635                    exit(1);
3636                }
3637                break;
3638            case QEMU_OPTION_tb_size:
3639#ifndef CONFIG_TCG
3640                error_report("TCG is disabled");
3641                exit(1);
3642#endif
3643                if (qemu_strtoul(optarg, NULL, 0, &tcg_tb_size) < 0) {
3644                    error_report("Invalid argument to -tb-size");
3645                    exit(1);
3646                }
3647                break;
3648            case QEMU_OPTION_icount:
3649                icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3650                                                      optarg, true);
3651                if (!icount_opts) {
3652                    exit(1);
3653                }
3654                break;
3655            case QEMU_OPTION_incoming:
3656                if (!incoming) {
3657                    runstate_set(RUN_STATE_INMIGRATE);
3658                }
3659                incoming = optarg;
3660                break;
3661            case QEMU_OPTION_only_migratable:
3662                only_migratable = 1;
3663                break;
3664            case QEMU_OPTION_nodefaults:
3665                has_defaults = 0;
3666                break;
3667            case QEMU_OPTION_xen_domid:
3668                if (!(xen_available())) {
3669                    error_report("Option not supported for this target");
3670                    exit(1);
3671                }
3672                xen_domid = atoi(optarg);
3673                break;
3674            case QEMU_OPTION_xen_attach:
3675                if (!(xen_available())) {
3676                    error_report("Option not supported for this target");
3677                    exit(1);
3678                }
3679                xen_mode = XEN_ATTACH;
3680                break;
3681            case QEMU_OPTION_xen_domid_restrict:
3682                if (!(xen_available())) {
3683                    error_report("Option not supported for this target");
3684                    exit(1);
3685                }
3686                xen_domid_restrict = true;
3687                break;
3688            case QEMU_OPTION_trace:
3689                g_free(trace_file);
3690                trace_file = trace_opt_parse(optarg);
3691                break;
3692            case QEMU_OPTION_plugin:
3693                qemu_plugin_opt_parse(optarg, &plugin_list);
3694                break;
3695            case QEMU_OPTION_readconfig:
3696                {
3697                    int ret = qemu_read_config_file(optarg);
3698                    if (ret < 0) {
3699                        error_report("read config %s: %s", optarg,
3700                                     strerror(-ret));
3701                        exit(1);
3702                    }
3703                    break;
3704                }
3705            case QEMU_OPTION_spice:
3706                olist = qemu_find_opts("spice");
3707                if (!olist) {
3708                    error_report("spice support is disabled");
3709                    exit(1);
3710                }
3711                opts = qemu_opts_parse_noisily(olist, optarg, false);
3712                if (!opts) {
3713                    exit(1);
3714                }
3715                display_remote++;
3716                break;
3717            case QEMU_OPTION_writeconfig:
3718                {
3719                    FILE *fp;
3720                    if (strcmp(optarg, "-") == 0) {
3721                        fp = stdout;
3722                    } else {
3723                        fp = fopen(optarg, "w");
3724                        if (fp == NULL) {
3725                            error_report("open %s: %s", optarg,
3726                                         strerror(errno));
3727                            exit(1);
3728                        }
3729                    }
3730                    qemu_config_write(fp);
3731                    if (fp != stdout) {
3732                        fclose(fp);
3733                    }
3734                    break;
3735                }
3736            case QEMU_OPTION_qtest:
3737                qtest_chrdev = optarg;
3738                break;
3739            case QEMU_OPTION_qtest_log:
3740                qtest_log = optarg;
3741                break;
3742            case QEMU_OPTION_sandbox:
3743                olist = qemu_find_opts("sandbox");
3744                if (!olist) {
3745#ifndef CONFIG_SECCOMP
3746                    error_report("-sandbox support is not enabled "
3747                                 "in this QEMU binary");
3748#endif
3749                    exit(1);
3750                }
3751
3752                opts = qemu_opts_parse_noisily(olist, optarg, true);
3753                if (!opts) {
3754                    exit(1);
3755                }
3756                break;
3757            case QEMU_OPTION_add_fd:
3758#ifndef _WIN32
3759                opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
3760                                               optarg, false);
3761                if (!opts) {
3762                    exit(1);
3763                }
3764#else
3765                error_report("File descriptor passing is disabled on this "
3766                             "platform");
3767                exit(1);
3768#endif
3769                break;
3770            case QEMU_OPTION_object:
3771                opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
3772                                               optarg, true);
3773                if (!opts) {
3774                    exit(1);
3775                }
3776                break;
3777            case QEMU_OPTION_realtime:
3778                warn_report("'-realtime mlock=...' is deprecated, please use "
3779                             "'-overcommit mem-lock=...' instead");
3780                opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
3781                                               optarg, false);
3782                if (!opts) {
3783                    exit(1);
3784                }
3785                /* Don't override the -overcommit option if set */
3786                enable_mlock = enable_mlock ||
3787                    qemu_opt_get_bool(opts, "mlock", true);
3788                break;
3789            case QEMU_OPTION_overcommit:
3790                opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
3791                                               optarg, false);
3792                if (!opts) {
3793                    exit(1);
3794                }
3795                /* Don't override the -realtime option if set */
3796                enable_mlock = enable_mlock ||
3797                    qemu_opt_get_bool(opts, "mem-lock", false);
3798                enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
3799                break;
3800            case QEMU_OPTION_msg:
3801                opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
3802                                               false);
3803                if (!opts) {
3804                    exit(1);
3805                }
3806                configure_msg(opts);
3807                break;
3808            case QEMU_OPTION_dump_vmstate:
3809                if (vmstate_dump_file) {
3810                    error_report("only one '-dump-vmstate' "
3811                                 "option may be given");
3812                    exit(1);
3813                }
3814                vmstate_dump_file = fopen(optarg, "w");
3815                if (vmstate_dump_file == NULL) {
3816                    error_report("open %s: %s", optarg, strerror(errno));
3817                    exit(1);
3818                }
3819                break;
3820            case QEMU_OPTION_enable_sync_profile:
3821                qsp_enable();
3822                break;
3823            case QEMU_OPTION_nouserconfig:
3824                /* Nothing to be parsed here. Especially, do not error out below. */
3825                break;
3826            default:
3827                if (os_parse_cmd_args(popt->index, optarg)) {
3828                    error_report("Option not supported in this build");
3829                    exit(1);
3830                }
3831            }
3832        }
3833    }
3834    /*
3835     * Clear error location left behind by the loop.
3836     * Best done right after the loop.  Do not insert code here!
3837     */
3838    loc_set_none();
3839
3840    user_register_global_props();
3841
3842    replay_configure(icount_opts);
3843
3844    if (incoming && !preconfig_exit_requested) {
3845        error_report("'preconfig' and 'incoming' options are "
3846                     "mutually exclusive");
3847        exit(EXIT_FAILURE);
3848    }
3849
3850    configure_rtc(qemu_find_opts_singleton("rtc"));
3851
3852    machine_class = select_machine();
3853    object_set_machine_compat_props(machine_class->compat_props);
3854
3855    set_memory_options(&ram_slots, &maxram_size, machine_class);
3856
3857    os_daemonize();
3858    rcu_disable_atfork();
3859
3860    if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
3861        error_reportf_err(err, "cannot create PID file: ");
3862        exit(1);
3863    }
3864
3865    qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
3866    qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
3867
3868    if (qemu_init_main_loop(&main_loop_err)) {
3869        error_report_err(main_loop_err);
3870        exit(1);
3871    }
3872
3873#ifdef CONFIG_SECCOMP
3874    olist = qemu_find_opts_err("sandbox", NULL);
3875    if (olist) {
3876        qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
3877    }
3878#endif
3879
3880    qemu_opts_foreach(qemu_find_opts("name"),
3881                      parse_name, NULL, &error_fatal);
3882
3883#ifndef _WIN32
3884    qemu_opts_foreach(qemu_find_opts("add-fd"),
3885                      parse_add_fd, NULL, &error_fatal);
3886
3887    qemu_opts_foreach(qemu_find_opts("add-fd"),
3888                      cleanup_add_fd, NULL, &error_fatal);
3889#endif
3890
3891    current_machine = MACHINE(object_new(object_class_get_name(
3892                          OBJECT_CLASS(machine_class))));
3893    if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
3894        exit(0);
3895    }
3896    object_property_add_child(object_get_root(), "machine",
3897                              OBJECT(current_machine), &error_abort);
3898    object_property_add_child(container_get(OBJECT(current_machine),
3899                                            "/unattached"),
3900                              "sysbus", OBJECT(sysbus_get_default()),
3901                              NULL);
3902
3903    if (machine_class->minimum_page_bits) {
3904        if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
3905            /* This would be a board error: specifying a minimum smaller than
3906             * a target's compile-time fixed setting.
3907             */
3908            g_assert_not_reached();
3909        }
3910    }
3911
3912    cpu_exec_init_all();
3913
3914    if (machine_class->hw_version) {
3915        qemu_set_hw_version(machine_class->hw_version);
3916    }
3917
3918    if (cpu_option && is_help_option(cpu_option)) {
3919        list_cpus(cpu_option);
3920        exit(0);
3921    }
3922
3923    if (!trace_init_backends()) {
3924        exit(1);
3925    }
3926    trace_init_file(trace_file);
3927
3928    /* Open the logfile at this point and set the log mask if necessary.
3929     */
3930    if (log_file) {
3931        qemu_set_log_filename(log_file, &error_fatal);
3932    }
3933
3934    if (log_mask) {
3935        int mask;
3936        mask = qemu_str_to_log_mask(log_mask);
3937        if (!mask) {
3938            qemu_print_log_usage(stdout);
3939            exit(1);
3940        }
3941        qemu_set_log(mask);
3942    } else {
3943        qemu_set_log(0);
3944    }
3945
3946    /* add configured firmware directories */
3947    dirs = g_strsplit(CONFIG_QEMU_FIRMWAREPATH, G_SEARCHPATH_SEPARATOR_S, 0);
3948    for (i = 0; dirs[i] != NULL; i++) {
3949        qemu_add_data_dir(dirs[i]);
3950    }
3951    g_strfreev(dirs);
3952
3953    /* try to find datadir relative to the executable path */
3954    dir = os_find_datadir();
3955    qemu_add_data_dir(dir);
3956    g_free(dir);
3957
3958    /* add the datadir specified when building */
3959    qemu_add_data_dir(CONFIG_QEMU_DATADIR);
3960
3961    /* -L help lists the data directories and exits. */
3962    if (list_data_dirs) {
3963        for (i = 0; i < data_dir_idx; i++) {
3964            printf("%s\n", data_dir[i]);
3965        }
3966        exit(0);
3967    }
3968
3969    /* machine_class: default to UP */
3970    machine_class->max_cpus = machine_class->max_cpus ?: 1;
3971    machine_class->min_cpus = machine_class->min_cpus ?: 1;
3972    machine_class->default_cpus = machine_class->default_cpus ?: 1;
3973
3974    /* default to machine_class->default_cpus */
3975    current_machine->smp.cpus = machine_class->default_cpus;
3976    current_machine->smp.max_cpus = machine_class->default_cpus;
3977    current_machine->smp.cores = 1;
3978    current_machine->smp.threads = 1;
3979
3980    machine_class->smp_parse(current_machine,
3981        qemu_opts_find(qemu_find_opts("smp-opts"), NULL));
3982
3983    /* sanity-check smp_cpus and max_cpus against machine_class */
3984    if (current_machine->smp.cpus < machine_class->min_cpus) {
3985        error_report("Invalid SMP CPUs %d. The min CPUs "
3986                     "supported by machine '%s' is %d",
3987                     current_machine->smp.cpus,
3988                     machine_class->name, machine_class->min_cpus);
3989        exit(1);
3990    }
3991    if (current_machine->smp.max_cpus > machine_class->max_cpus) {
3992        error_report("Invalid SMP CPUs %d. The max CPUs "
3993                     "supported by machine '%s' is %d",
3994                     current_machine->smp.max_cpus,
3995                     machine_class->name, machine_class->max_cpus);
3996        exit(1);
3997    }
3998
3999    /*
4000     * Get the default machine options from the machine if it is not already
4001     * specified either by the configuration file or by the command line.
4002     */
4003    if (machine_class->default_machine_opts) {
4004        qemu_opts_set_defaults(qemu_find_opts("machine"),
4005                               machine_class->default_machine_opts, 0);
4006    }
4007
4008    /* process plugin before CPUs are created, but once -smp has been parsed */
4009    if (qemu_plugin_load_list(&plugin_list)) {
4010        exit(1);
4011    }
4012
4013    qemu_opts_foreach(qemu_find_opts("device"),
4014                      default_driver_check, NULL, NULL);
4015    qemu_opts_foreach(qemu_find_opts("global"),
4016                      default_driver_check, NULL, NULL);
4017
4018    if (!vga_model && !default_vga) {
4019        vga_interface_type = VGA_DEVICE;
4020    }
4021    if (!has_defaults || machine_class->no_serial) {
4022        default_serial = 0;
4023    }
4024    if (!has_defaults || machine_class->no_parallel) {
4025        default_parallel = 0;
4026    }
4027    if (!has_defaults || machine_class->no_floppy) {
4028        default_floppy = 0;
4029    }
4030    if (!has_defaults || machine_class->no_cdrom) {
4031        default_cdrom = 0;
4032    }
4033    if (!has_defaults || machine_class->no_sdcard) {
4034        default_sdcard = 0;
4035    }
4036    if (!has_defaults) {
4037        default_monitor = 0;
4038        default_net = 0;
4039        default_vga = 0;
4040    }
4041
4042    if (is_daemonized()) {
4043        if (!preconfig_exit_requested) {
4044            error_report("'preconfig' and 'daemonize' options are "
4045                         "mutually exclusive");
4046            exit(EXIT_FAILURE);
4047        }
4048
4049        /* According to documentation and historically, -nographic redirects
4050         * serial port, parallel port and monitor to stdio, which does not work
4051         * with -daemonize.  We can redirect these to null instead, but since
4052         * -nographic is legacy, let's just error out.
4053         * We disallow -nographic only if all other ports are not redirected
4054         * explicitly, to not break existing legacy setups which uses
4055         * -nographic _and_ redirects all ports explicitly - this is valid
4056         * usage, -nographic is just a no-op in this case.
4057         */
4058        if (nographic
4059            && (default_parallel || default_serial || default_monitor)) {
4060            error_report("-nographic cannot be used with -daemonize");
4061            exit(1);
4062        }
4063#ifdef CONFIG_CURSES
4064        if (dpy.type == DISPLAY_TYPE_CURSES) {
4065            error_report("curses display cannot be used with -daemonize");
4066            exit(1);
4067        }
4068#endif
4069    }
4070
4071    if (nographic) {
4072        if (default_parallel)
4073            add_device_config(DEV_PARALLEL, "null");
4074        if (default_serial && default_monitor) {
4075            add_device_config(DEV_SERIAL, "mon:stdio");
4076        } else {
4077            if (default_serial)
4078                add_device_config(DEV_SERIAL, "stdio");
4079            if (default_monitor)
4080                monitor_parse("stdio", "readline", false);
4081        }
4082    } else {
4083        if (default_serial)
4084            add_device_config(DEV_SERIAL, "vc:80Cx24C");
4085        if (default_parallel)
4086            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4087        if (default_monitor)
4088            monitor_parse("vc:80Cx24C", "readline", false);
4089    }
4090
4091#if defined(CONFIG_VNC)
4092    if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
4093        display_remote++;
4094    }
4095#endif
4096    if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
4097        if (!qemu_display_find_default(&dpy)) {
4098            dpy.type = DISPLAY_TYPE_NONE;
4099#if defined(CONFIG_VNC)
4100            vnc_parse("localhost:0,to=99,id=default", &error_abort);
4101#endif
4102        }
4103    }
4104    if (dpy.type == DISPLAY_TYPE_DEFAULT) {
4105        dpy.type = DISPLAY_TYPE_NONE;
4106    }
4107
4108    if ((alt_grab || ctrl_grab) && dpy.type != DISPLAY_TYPE_SDL) {
4109        error_report("-alt-grab and -ctrl-grab are only valid "
4110                     "for SDL, ignoring option");
4111    }
4112    if (dpy.has_window_close &&
4113        (dpy.type != DISPLAY_TYPE_GTK && dpy.type != DISPLAY_TYPE_SDL)) {
4114        error_report("-no-quit is only valid for GTK and SDL, "
4115                     "ignoring option");
4116    }
4117
4118    qemu_display_early_init(&dpy);
4119    qemu_console_early_init();
4120
4121    if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
4122#if defined(CONFIG_OPENGL)
4123        error_report("OpenGL is not supported by the display");
4124#else
4125        error_report("OpenGL support is disabled");
4126#endif
4127        exit(1);
4128    }
4129
4130    page_size_init();
4131    socket_init();
4132
4133    qemu_opts_foreach(qemu_find_opts("object"),
4134                      user_creatable_add_opts_foreach,
4135                      object_create_initial, &error_fatal);
4136
4137    qemu_opts_foreach(qemu_find_opts("chardev"),
4138                      chardev_init_func, NULL, &error_fatal);
4139    /* now chardevs have been created we may have semihosting to connect */
4140    qemu_semihosting_connect_chardevs();
4141
4142#ifdef CONFIG_VIRTFS
4143    qemu_opts_foreach(qemu_find_opts("fsdev"),
4144                      fsdev_init_func, NULL, &error_fatal);
4145#endif
4146
4147    if (qemu_opts_foreach(qemu_find_opts("device"),
4148                          device_help_func, NULL, NULL)) {
4149        exit(0);
4150    }
4151
4152    /*
4153     * Note: we need to create block backends before
4154     * machine_set_property(), so machine properties can refer to
4155     * them.
4156     */
4157    configure_blockdev(&bdo_queue, machine_class, snapshot);
4158
4159    machine_opts = qemu_get_machine_opts();
4160    qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
4161                     &error_fatal);
4162    current_machine->ram_size = ram_size;
4163    current_machine->maxram_size = maxram_size;
4164    current_machine->ram_slots = ram_slots;
4165
4166    /*
4167     * Note: uses machine properties such as kernel-irqchip, must run
4168     * after machine_set_property().
4169     */
4170    configure_accelerator(current_machine, argv[0]);
4171
4172    /*
4173     * Beware, QOM objects created before this point miss global and
4174     * compat properties.
4175     *
4176     * Global properties get set up by qdev_prop_register_global(),
4177     * called from user_register_global_props(), and certain option
4178     * desugaring.  Also in CPU feature desugaring (buried in
4179     * parse_cpu_option()), which happens below this point, but may
4180     * only target the CPU type, which can only be created after
4181     * parse_cpu_option() returned the type.
4182     *
4183     * Machine compat properties: object_set_machine_compat_props().
4184     * Accelerator compat props: object_set_accelerator_compat_props(),
4185     * called from configure_accelerator().
4186     */
4187
4188    if (!qtest_enabled() && machine_class->deprecation_reason) {
4189        error_report("Machine type '%s' is deprecated: %s",
4190                     machine_class->name, machine_class->deprecation_reason);
4191    }
4192
4193    /*
4194     * Note: creates a QOM object, must run only after global and
4195     * compat properties have been set up.
4196     */
4197    migration_object_init();
4198
4199    if (qtest_chrdev) {
4200        qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
4201    }
4202
4203    machine_opts = qemu_get_machine_opts();
4204    kernel_filename = qemu_opt_get(machine_opts, "kernel");
4205    initrd_filename = qemu_opt_get(machine_opts, "initrd");
4206    kernel_cmdline = qemu_opt_get(machine_opts, "append");
4207    bios_name = qemu_opt_get(machine_opts, "firmware");
4208
4209    opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4210    if (opts) {
4211        boot_order = qemu_opt_get(opts, "order");
4212        if (boot_order) {
4213            validate_bootdevices(boot_order, &error_fatal);
4214        }
4215
4216        boot_once = qemu_opt_get(opts, "once");
4217        if (boot_once) {
4218            validate_bootdevices(boot_once, &error_fatal);
4219        }
4220
4221        boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4222        boot_strict = qemu_opt_get_bool(opts, "strict", false);
4223    }
4224
4225    if (!boot_order) {
4226        boot_order = machine_class->default_boot_order;
4227    }
4228
4229    if (!kernel_cmdline) {
4230        kernel_cmdline = "";
4231        current_machine->kernel_cmdline = (char *)kernel_cmdline;
4232    }
4233
4234    linux_boot = (kernel_filename != NULL);
4235
4236    if (!linux_boot && *kernel_cmdline != '\0') {
4237        error_report("-append only allowed with -kernel option");
4238        exit(1);
4239    }
4240
4241    if (!linux_boot && initrd_filename != NULL) {
4242        error_report("-initrd only allowed with -kernel option");
4243        exit(1);
4244    }
4245
4246    if (semihosting_enabled() && !semihosting_get_argc() && kernel_filename) {
4247        /* fall back to the -kernel/-append */
4248        semihosting_arg_fallback(kernel_filename, kernel_cmdline);
4249    }
4250
4251    /* spice needs the timers to be initialized by this point */
4252    qemu_spice_init();
4253
4254    cpu_ticks_init();
4255    if (icount_opts) {
4256        if (!tcg_enabled()) {
4257            error_report("-icount is not allowed with hardware virtualization");
4258            exit(1);
4259        }
4260        configure_icount(icount_opts, &error_abort);
4261        qemu_opts_del(icount_opts);
4262    }
4263
4264    if (tcg_enabled()) {
4265        qemu_tcg_configure(accel_opts, &error_fatal);
4266    }
4267
4268    if (default_net) {
4269        QemuOptsList *net = qemu_find_opts("net");
4270        qemu_opts_set(net, NULL, "type", "nic", &error_abort);
4271#ifdef CONFIG_SLIRP
4272        qemu_opts_set(net, NULL, "type", "user", &error_abort);
4273#endif
4274    }
4275
4276    if (net_init_clients(&err) < 0) {
4277        error_report_err(err);
4278        exit(1);
4279    }
4280
4281    qemu_opts_foreach(qemu_find_opts("object"),
4282                      user_creatable_add_opts_foreach,
4283                      object_create_delayed, &error_fatal);
4284
4285    tpm_init();
4286
4287    /* init the bluetooth world */
4288    if (foreach_device_config(DEV_BT, bt_parse))
4289        exit(1);
4290
4291    if (!xen_enabled()) {
4292        /* On 32-bit hosts, QEMU is limited by virtual address space */
4293        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4294            error_report("at most 2047 MB RAM can be simulated");
4295            exit(1);
4296        }
4297    }
4298
4299    blk_mig_init();
4300    ram_mig_init();
4301    dirty_bitmap_mig_init();
4302
4303    qemu_opts_foreach(qemu_find_opts("mon"),
4304                      mon_init_func, NULL, &error_fatal);
4305
4306    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4307        exit(1);
4308    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4309        exit(1);
4310    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4311        exit(1);
4312
4313    /* If no default VGA is requested, the default is "none".  */
4314    if (default_vga) {
4315        vga_model = get_default_vga_model(machine_class);
4316    }
4317    if (vga_model) {
4318        select_vgahw(machine_class, vga_model);
4319    }
4320
4321    if (watchdog) {
4322        i = select_watchdog(watchdog);
4323        if (i > 0)
4324            exit (i == 1 ? 1 : 0);
4325    }
4326
4327    /* This checkpoint is required by replay to separate prior clock
4328       reading from the other reads, because timer polling functions query
4329       clock values from the log. */
4330    replay_checkpoint(CHECKPOINT_INIT);
4331    qdev_machine_init();
4332
4333    current_machine->boot_order = boot_order;
4334
4335    /* parse features once if machine provides default cpu_type */
4336    current_machine->cpu_type = machine_class->default_cpu_type;
4337    if (cpu_option) {
4338        current_machine->cpu_type = parse_cpu_option(cpu_option);
4339    }
4340    parse_numa_opts(current_machine);
4341
4342    /* do monitor/qmp handling at preconfig state if requested */
4343    main_loop();
4344
4345    audio_init_audiodevs();
4346
4347    /* from here on runstate is RUN_STATE_PRELAUNCH */
4348    machine_run_board_init(current_machine);
4349
4350    realtime_init();
4351
4352    soundhw_init();
4353
4354    if (hax_enabled()) {
4355        hax_sync_vcpus();
4356    }
4357
4358    qemu_opts_foreach(qemu_find_opts("fw_cfg"),
4359                      parse_fw_cfg, fw_cfg_find(), &error_fatal);
4360
4361    /* init USB devices */
4362    if (machine_usb(current_machine)) {
4363        if (foreach_device_config(DEV_USB, usb_parse) < 0)
4364            exit(1);
4365    }
4366
4367    /* Check if IGD GFX passthrough. */
4368    igd_gfx_passthru();
4369
4370    /* init generic devices */
4371    rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
4372    qemu_opts_foreach(qemu_find_opts("device"),
4373                      device_init_func, NULL, &error_fatal);
4374
4375    cpu_synchronize_all_post_init();
4376
4377    rom_reset_order_override();
4378
4379    /* Did we create any drives that we failed to create a device for? */
4380    drive_check_orphaned();
4381
4382    /* Don't warn about the default network setup that you get if
4383     * no command line -net or -netdev options are specified. There
4384     * are two cases that we would otherwise complain about:
4385     * (1) board doesn't support a NIC but the implicit "-net nic"
4386     * requested one
4387     * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
4388     * sets up a nic that isn't connected to anything.
4389     */
4390    if (!default_net && (!qtest_enabled() || has_defaults)) {
4391        net_check_clients();
4392    }
4393
4394    if (boot_once) {
4395        qemu_boot_set(boot_once, &error_fatal);
4396        qemu_register_reset(restore_boot_order, g_strdup(boot_order));
4397    }
4398
4399    /* init local displays */
4400    ds = init_displaystate();
4401    qemu_display_init(ds, &dpy);
4402
4403    /* must be after terminal init, SDL library changes signal handlers */
4404    os_setup_signal_handling();
4405
4406    /* init remote displays */
4407#ifdef CONFIG_VNC
4408    qemu_opts_foreach(qemu_find_opts("vnc"),
4409                      vnc_init_func, NULL, &error_fatal);
4410#endif
4411
4412    if (using_spice) {
4413        qemu_spice_display_init();
4414    }
4415
4416    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4417        exit(1);
4418    }
4419
4420    qdev_machine_creation_done();
4421
4422    /* TODO: once all bus devices are qdevified, this should be done
4423     * when bus is created by qdev.c */
4424    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
4425    qemu_run_machine_init_done_notifiers();
4426
4427    if (rom_check_and_register_reset() != 0) {
4428        error_report("rom check and register reset failed");
4429        exit(1);
4430    }
4431
4432    replay_start();
4433
4434    /* This checkpoint is required by replay to separate prior clock
4435       reading from the other reads, because timer polling functions query
4436       clock values from the log. */
4437    replay_checkpoint(CHECKPOINT_RESET);
4438    qemu_system_reset(SHUTDOWN_CAUSE_NONE);
4439    register_global_state();
4440    if (loadvm) {
4441        Error *local_err = NULL;
4442        if (load_snapshot(loadvm, &local_err) < 0) {
4443            error_report_err(local_err);
4444            autostart = 0;
4445            exit(1);
4446        }
4447    }
4448    if (replay_mode != REPLAY_MODE_NONE) {
4449        replay_vmstate_init();
4450    }
4451
4452    qdev_prop_check_globals();
4453    if (vmstate_dump_file) {
4454        /* dump and exit */
4455        dump_vmstate_json_to_file(vmstate_dump_file);
4456        return 0;
4457    }
4458
4459    if (incoming) {
4460        Error *local_err = NULL;
4461        qemu_start_incoming_migration(incoming, &local_err);
4462        if (local_err) {
4463            error_reportf_err(local_err, "-incoming %s: ", incoming);
4464            exit(1);
4465        }
4466    } else if (autostart) {
4467        vm_start();
4468    }
4469
4470    accel_setup_post(current_machine);
4471    os_setup_post();
4472
4473    main_loop();
4474
4475    gdbserver_cleanup();
4476
4477    /*
4478     * cleaning up the migration object cancels any existing migration
4479     * try to do this early so that it also stops using devices.
4480     */
4481    migration_shutdown();
4482
4483    /*
4484     * We must cancel all block jobs while the block layer is drained,
4485     * or cancelling will be affected by throttling and thus may block
4486     * for an extended period of time.
4487     * vm_shutdown() will bdrv_drain_all(), so we may as well include
4488     * it in the drained section.
4489     * We do not need to end this section, because we do not want any
4490     * requests happening from here on anyway.
4491     */
4492    bdrv_drain_all_begin();
4493
4494    /* No more vcpu or device emulation activity beyond this point */
4495    vm_shutdown();
4496    replay_finish();
4497
4498    job_cancel_sync_all();
4499    bdrv_close_all();
4500
4501    res_free();
4502
4503    /* vhost-user must be cleaned up before chardevs.  */
4504    tpm_cleanup();
4505    net_cleanup();
4506    audio_cleanup();
4507    monitor_cleanup();
4508    qemu_chr_cleanup();
4509    user_creatable_cleanup();
4510    /* TODO: unref root container, check all devices are ok */
4511
4512    return 0;
4513}
4514