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