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