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