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