qemu/vl.c
<<
>>
Prefs
   1/*
   2 * QEMU System Emulator
   3 *
   4 * Copyright (c) 2003-2008 Fabrice Bellard
   5 *
   6 * Permission is hereby granted, free of charge, to any person obtaining a copy
   7 * of this software and associated documentation files (the "Software"), to deal
   8 * in the Software without restriction, including without limitation the rights
   9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10 * copies of the Software, and to permit persons to whom the Software is
  11 * furnished to do so, subject to the following conditions:
  12 *
  13 * The above copyright notice and this permission notice shall be included in
  14 * all copies or substantial portions of the Software.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22 * THE SOFTWARE.
  23 */
  24#include <unistd.h>
  25#include <fcntl.h>
  26#include <signal.h>
  27#include <time.h>
  28#include <errno.h>
  29#include <sys/time.h>
  30#include <zlib.h>
  31
  32/* Needed early for CONFIG_BSD etc. */
  33#include "config-host.h"
  34
  35#ifndef _WIN32
  36#include <libgen.h>
  37#include <sys/times.h>
  38#include <sys/wait.h>
  39#include <termios.h>
  40#include <sys/mman.h>
  41#include <sys/ioctl.h>
  42#include <sys/resource.h>
  43#include <sys/socket.h>
  44#include <netinet/in.h>
  45#include <net/if.h>
  46#include <arpa/inet.h>
  47#include <dirent.h>
  48#include <netdb.h>
  49#include <sys/select.h>
  50
  51#ifdef CONFIG_BSD
  52#include <sys/stat.h>
  53#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  54#include <libutil.h>
  55#include <sys/sysctl.h>
  56#else
  57#include <util.h>
  58#endif
  59#else
  60#ifdef __linux__
  61#include <pty.h>
  62#include <malloc.h>
  63
  64#include <linux/ppdev.h>
  65#include <linux/parport.h>
  66#endif
  67#ifdef __sun__
  68#include <sys/stat.h>
  69#include <sys/ethernet.h>
  70#include <sys/sockio.h>
  71#include <netinet/arp.h>
  72#include <netinet/in_systm.h>
  73#include <netinet/ip.h>
  74#include <netinet/ip_icmp.h> // must come after ip.h
  75#include <netinet/udp.h>
  76#include <netinet/tcp.h>
  77#include <net/if.h>
  78#include <syslog.h>
  79#include <stropts.h>
  80#endif
  81#endif
  82#endif
  83
  84#if defined(__OpenBSD__)
  85#include <util.h>
  86#endif
  87
  88#if defined(CONFIG_VDE)
  89#include <libvdeplug.h>
  90#endif
  91
  92#ifdef _WIN32
  93#include <windows.h>
  94#endif
  95
  96#ifdef CONFIG_SDL
  97#if defined(__APPLE__) || defined(main)
  98#include <SDL.h>
  99int qemu_main(int argc, char **argv, char **envp);
 100int main(int argc, char **argv)
 101{
 102    return qemu_main(argc, argv, NULL);
 103}
 104#undef main
 105#define main qemu_main
 106#endif
 107#endif /* CONFIG_SDL */
 108
 109#ifdef CONFIG_COCOA
 110#undef main
 111#define main qemu_main
 112#endif /* CONFIG_COCOA */
 113
 114#include "hw/hw.h"
 115#include "hw/boards.h"
 116#include "hw/usb.h"
 117#include "hw/pcmcia.h"
 118#include "hw/pc.h"
 119#include "hw/isa.h"
 120#include "hw/baum.h"
 121#include "hw/bt.h"
 122#include "hw/watchdog.h"
 123#include "hw/smbios.h"
 124#include "hw/xen.h"
 125#include "hw/qdev.h"
 126#include "hw/loader.h"
 127#include "bt-host.h"
 128#include "net.h"
 129#include "net/slirp.h"
 130#include "monitor.h"
 131#include "console.h"
 132#include "sysemu.h"
 133#include "gdbstub.h"
 134#include "qemu-timer.h"
 135#include "qemu-char.h"
 136#include "cache-utils.h"
 137#include "block.h"
 138#include "blockdev.h"
 139#include "block-migration.h"
 140#include "dma.h"
 141#include "audio/audio.h"
 142#include "migration.h"
 143#include "kvm.h"
 144#include "qemu-option.h"
 145#include "qemu-config.h"
 146#include "qemu-objects.h"
 147#include "qemu-options.h"
 148#ifdef CONFIG_VIRTFS
 149#include "fsdev/qemu-fsdev.h"
 150#endif
 151
 152#include "disas.h"
 153
 154#include "qemu_socket.h"
 155
 156#include "slirp/libslirp.h"
 157
 158#include "trace.h"
 159#include "simpletrace.h"
 160#include "qemu-queue.h"
 161#include "cpus.h"
 162#include "arch_init.h"
 163
 164#include "ui/qemu-spice.h"
 165
 166//#define DEBUG_NET
 167//#define DEBUG_SLIRP
 168
 169#define DEFAULT_RAM_SIZE 128
 170
 171#define MAX_VIRTIO_CONSOLES 1
 172
 173static const char *data_dir;
 174const char *bios_name = NULL;
 175enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
 176DisplayType display_type = DT_DEFAULT;
 177int display_remote = 0;
 178const char* keyboard_layout = NULL;
 179ram_addr_t ram_size;
 180const char *mem_path = NULL;
 181#ifdef MAP_POPULATE
 182int mem_prealloc = 0; /* force preallocation of physical target memory */
 183#endif
 184int nb_nics;
 185NICInfo nd_table[MAX_NICS];
 186int vm_running;
 187int autostart;
 188int incoming_expected; /* Started with -incoming and waiting for incoming */
 189static int rtc_utc = 1;
 190static int rtc_date_offset = -1; /* -1 means no change */
 191QEMUClock *rtc_clock;
 192int vga_interface_type = VGA_NONE;
 193static int full_screen = 0;
 194#ifdef CONFIG_SDL
 195static int no_frame = 0;
 196#endif
 197int no_quit = 0;
 198CharDriverState *serial_hds[MAX_SERIAL_PORTS];
 199CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
 200CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
 201int win2k_install_hack = 0;
 202int rtc_td_hack = 0;
 203int usb_enabled = 0;
 204int singlestep = 0;
 205int smp_cpus = 1;
 206int max_cpus = 0;
 207int smp_cores = 1;
 208int smp_threads = 1;
 209#ifdef CONFIG_VNC
 210const char *vnc_display;
 211#endif
 212int acpi_enabled = 1;
 213int no_hpet = 0;
 214int fd_bootchk = 1;
 215int no_reboot = 0;
 216int no_shutdown = 0;
 217int cursor_hide = 1;
 218int graphic_rotate = 0;
 219uint8_t irq0override = 1;
 220const char *watchdog;
 221QEMUOptionRom option_rom[MAX_OPTION_ROMS];
 222int nb_option_roms;
 223int semihosting_enabled = 0;
 224int old_param = 0;
 225const char *qemu_name;
 226int alt_grab = 0;
 227int ctrl_grab = 0;
 228unsigned int nb_prom_envs = 0;
 229const char *prom_envs[MAX_PROM_ENVS];
 230int boot_menu;
 231
 232typedef struct FWBootEntry FWBootEntry;
 233
 234struct FWBootEntry {
 235    QTAILQ_ENTRY(FWBootEntry) link;
 236    int32_t bootindex;
 237    DeviceState *dev;
 238    char *suffix;
 239};
 240
 241QTAILQ_HEAD(, FWBootEntry) fw_boot_order = QTAILQ_HEAD_INITIALIZER(fw_boot_order);
 242
 243int nb_numa_nodes;
 244uint64_t node_mem[MAX_NODES];
 245uint64_t node_cpumask[MAX_NODES];
 246
 247static QEMUTimer *nographic_timer;
 248
 249uint8_t qemu_uuid[16];
 250
 251static QEMUBootSetHandler *boot_set_handler;
 252static void *boot_set_opaque;
 253
 254static NotifierList exit_notifiers =
 255    NOTIFIER_LIST_INITIALIZER(exit_notifiers);
 256
 257static NotifierList machine_init_done_notifiers =
 258    NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
 259
 260static int tcg_allowed = 1;
 261int kvm_allowed = 0;
 262int xen_allowed = 0;
 263uint32_t xen_domid;
 264enum xen_mode xen_mode = XEN_EMULATE;
 265
 266static int default_serial = 1;
 267static int default_parallel = 1;
 268static int default_virtcon = 1;
 269static int default_monitor = 1;
 270static int default_vga = 1;
 271static int default_floppy = 1;
 272static int default_cdrom = 1;
 273static int default_sdcard = 1;
 274
 275static struct {
 276    const char *driver;
 277    int *flag;
 278} default_list[] = {
 279    { .driver = "isa-serial",           .flag = &default_serial    },
 280    { .driver = "isa-parallel",         .flag = &default_parallel  },
 281    { .driver = "isa-fdc",              .flag = &default_floppy    },
 282    { .driver = "ide-cd",               .flag = &default_cdrom     },
 283    { .driver = "ide-hd",               .flag = &default_cdrom     },
 284    { .driver = "ide-drive",            .flag = &default_cdrom     },
 285    { .driver = "scsi-cd",              .flag = &default_cdrom     },
 286    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
 287    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
 288    { .driver = "virtio-serial",        .flag = &default_virtcon   },
 289    { .driver = "VGA",                  .flag = &default_vga       },
 290    { .driver = "cirrus-vga",           .flag = &default_vga       },
 291    { .driver = "vmware-svga",          .flag = &default_vga       },
 292    { .driver = "isa-vga",              .flag = &default_vga       },
 293    { .driver = "qxl-vga",              .flag = &default_vga       },
 294};
 295
 296static int default_driver_check(QemuOpts *opts, void *opaque)
 297{
 298    const char *driver = qemu_opt_get(opts, "driver");
 299    int i;
 300
 301    if (!driver)
 302        return 0;
 303    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
 304        if (strcmp(default_list[i].driver, driver) != 0)
 305            continue;
 306        *(default_list[i].flag) = 0;
 307    }
 308    return 0;
 309}
 310
 311/***********************************************************/
 312/* real time host monotonic timer */
 313
 314/***********************************************************/
 315/* host time/date access */
 316void qemu_get_timedate(struct tm *tm, int offset)
 317{
 318    time_t ti;
 319    struct tm *ret;
 320
 321    time(&ti);
 322    ti += offset;
 323    if (rtc_date_offset == -1) {
 324        if (rtc_utc)
 325            ret = gmtime(&ti);
 326        else
 327            ret = localtime(&ti);
 328    } else {
 329        ti -= rtc_date_offset;
 330        ret = gmtime(&ti);
 331    }
 332
 333    memcpy(tm, ret, sizeof(struct tm));
 334}
 335
 336int qemu_timedate_diff(struct tm *tm)
 337{
 338    time_t seconds;
 339
 340    if (rtc_date_offset == -1)
 341        if (rtc_utc)
 342            seconds = mktimegm(tm);
 343        else
 344            seconds = mktime(tm);
 345    else
 346        seconds = mktimegm(tm) + rtc_date_offset;
 347
 348    return seconds - time(NULL);
 349}
 350
 351void rtc_change_mon_event(struct tm *tm)
 352{
 353    QObject *data;
 354
 355    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
 356    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
 357    qobject_decref(data);
 358}
 359
 360static void configure_rtc_date_offset(const char *startdate, int legacy)
 361{
 362    time_t rtc_start_date;
 363    struct tm tm;
 364
 365    if (!strcmp(startdate, "now") && legacy) {
 366        rtc_date_offset = -1;
 367    } else {
 368        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
 369                   &tm.tm_year,
 370                   &tm.tm_mon,
 371                   &tm.tm_mday,
 372                   &tm.tm_hour,
 373                   &tm.tm_min,
 374                   &tm.tm_sec) == 6) {
 375            /* OK */
 376        } else if (sscanf(startdate, "%d-%d-%d",
 377                          &tm.tm_year,
 378                          &tm.tm_mon,
 379                          &tm.tm_mday) == 3) {
 380            tm.tm_hour = 0;
 381            tm.tm_min = 0;
 382            tm.tm_sec = 0;
 383        } else {
 384            goto date_fail;
 385        }
 386        tm.tm_year -= 1900;
 387        tm.tm_mon--;
 388        rtc_start_date = mktimegm(&tm);
 389        if (rtc_start_date == -1) {
 390        date_fail:
 391            fprintf(stderr, "Invalid date format. Valid formats are:\n"
 392                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
 393            exit(1);
 394        }
 395        rtc_date_offset = time(NULL) - rtc_start_date;
 396    }
 397}
 398
 399static void configure_rtc(QemuOpts *opts)
 400{
 401    const char *value;
 402
 403    value = qemu_opt_get(opts, "base");
 404    if (value) {
 405        if (!strcmp(value, "utc")) {
 406            rtc_utc = 1;
 407        } else if (!strcmp(value, "localtime")) {
 408            rtc_utc = 0;
 409        } else {
 410            configure_rtc_date_offset(value, 0);
 411        }
 412    }
 413    value = qemu_opt_get(opts, "clock");
 414    if (value) {
 415        if (!strcmp(value, "host")) {
 416            rtc_clock = host_clock;
 417        } else if (!strcmp(value, "vm")) {
 418            rtc_clock = vm_clock;
 419        } else {
 420            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
 421            exit(1);
 422        }
 423    }
 424    value = qemu_opt_get(opts, "driftfix");
 425    if (value) {
 426        if (!strcmp(value, "slew")) {
 427            rtc_td_hack = 1;
 428        } else if (!strcmp(value, "none")) {
 429            rtc_td_hack = 0;
 430        } else {
 431            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
 432            exit(1);
 433        }
 434    }
 435}
 436
 437/***********************************************************/
 438/* Bluetooth support */
 439static int nb_hcis;
 440static int cur_hci;
 441static struct HCIInfo *hci_table[MAX_NICS];
 442
 443static struct bt_vlan_s {
 444    struct bt_scatternet_s net;
 445    int id;
 446    struct bt_vlan_s *next;
 447} *first_bt_vlan;
 448
 449/* find or alloc a new bluetooth "VLAN" */
 450static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
 451{
 452    struct bt_vlan_s **pvlan, *vlan;
 453    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
 454        if (vlan->id == id)
 455            return &vlan->net;
 456    }
 457    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
 458    vlan->id = id;
 459    pvlan = &first_bt_vlan;
 460    while (*pvlan != NULL)
 461        pvlan = &(*pvlan)->next;
 462    *pvlan = vlan;
 463    return &vlan->net;
 464}
 465
 466static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
 467{
 468}
 469
 470static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
 471{
 472    return -ENOTSUP;
 473}
 474
 475static struct HCIInfo null_hci = {
 476    .cmd_send = null_hci_send,
 477    .sco_send = null_hci_send,
 478    .acl_send = null_hci_send,
 479    .bdaddr_set = null_hci_addr_set,
 480};
 481
 482struct HCIInfo *qemu_next_hci(void)
 483{
 484    if (cur_hci == nb_hcis)
 485        return &null_hci;
 486
 487    return hci_table[cur_hci++];
 488}
 489
 490static struct HCIInfo *hci_init(const char *str)
 491{
 492    char *endp;
 493    struct bt_scatternet_s *vlan = 0;
 494
 495    if (!strcmp(str, "null"))
 496        /* null */
 497        return &null_hci;
 498    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
 499        /* host[:hciN] */
 500        return bt_host_hci(str[4] ? str + 5 : "hci0");
 501    else if (!strncmp(str, "hci", 3)) {
 502        /* hci[,vlan=n] */
 503        if (str[3]) {
 504            if (!strncmp(str + 3, ",vlan=", 6)) {
 505                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
 506                if (*endp)
 507                    vlan = 0;
 508            }
 509        } else
 510            vlan = qemu_find_bt_vlan(0);
 511        if (vlan)
 512           return bt_new_hci(vlan);
 513    }
 514
 515    fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
 516
 517    return 0;
 518}
 519
 520static int bt_hci_parse(const char *str)
 521{
 522    struct HCIInfo *hci;
 523    bdaddr_t bdaddr;
 524
 525    if (nb_hcis >= MAX_NICS) {
 526        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
 527        return -1;
 528    }
 529
 530    hci = hci_init(str);
 531    if (!hci)
 532        return -1;
 533
 534    bdaddr.b[0] = 0x52;
 535    bdaddr.b[1] = 0x54;
 536    bdaddr.b[2] = 0x00;
 537    bdaddr.b[3] = 0x12;
 538    bdaddr.b[4] = 0x34;
 539    bdaddr.b[5] = 0x56 + nb_hcis;
 540    hci->bdaddr_set(hci, bdaddr.b);
 541
 542    hci_table[nb_hcis++] = hci;
 543
 544    return 0;
 545}
 546
 547static void bt_vhci_add(int vlan_id)
 548{
 549    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
 550
 551    if (!vlan->slave)
 552        fprintf(stderr, "qemu: warning: adding a VHCI to "
 553                        "an empty scatternet %i\n", vlan_id);
 554
 555    bt_vhci_init(bt_new_hci(vlan));
 556}
 557
 558static struct bt_device_s *bt_device_add(const char *opt)
 559{
 560    struct bt_scatternet_s *vlan;
 561    int vlan_id = 0;
 562    char *endp = strstr(opt, ",vlan=");
 563    int len = (endp ? endp - opt : strlen(opt)) + 1;
 564    char devname[10];
 565
 566    pstrcpy(devname, MIN(sizeof(devname), len), opt);
 567
 568    if (endp) {
 569        vlan_id = strtol(endp + 6, &endp, 0);
 570        if (*endp) {
 571            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
 572            return 0;
 573        }
 574    }
 575
 576    vlan = qemu_find_bt_vlan(vlan_id);
 577
 578    if (!vlan->slave)
 579        fprintf(stderr, "qemu: warning: adding a slave device to "
 580                        "an empty scatternet %i\n", vlan_id);
 581
 582    if (!strcmp(devname, "keyboard"))
 583        return bt_keyboard_init(vlan);
 584
 585    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
 586    return 0;
 587}
 588
 589static int bt_parse(const char *opt)
 590{
 591    const char *endp, *p;
 592    int vlan;
 593
 594    if (strstart(opt, "hci", &endp)) {
 595        if (!*endp || *endp == ',') {
 596            if (*endp)
 597                if (!strstart(endp, ",vlan=", 0))
 598                    opt = endp + 1;
 599
 600            return bt_hci_parse(opt);
 601       }
 602    } else if (strstart(opt, "vhci", &endp)) {
 603        if (!*endp || *endp == ',') {
 604            if (*endp) {
 605                if (strstart(endp, ",vlan=", &p)) {
 606                    vlan = strtol(p, (char **) &endp, 0);
 607                    if (*endp) {
 608                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
 609                        return 1;
 610                    }
 611                } else {
 612                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
 613                    return 1;
 614                }
 615            } else
 616                vlan = 0;
 617
 618            bt_vhci_add(vlan);
 619            return 0;
 620        }
 621    } else if (strstart(opt, "device:", &endp))
 622        return !bt_device_add(endp);
 623
 624    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
 625    return 1;
 626}
 627
 628/***********************************************************/
 629/* QEMU Block devices */
 630
 631#define HD_OPTS "media=disk"
 632#define CDROM_OPTS "media=cdrom"
 633#define FD_OPTS ""
 634#define PFLASH_OPTS ""
 635#define MTD_OPTS ""
 636#define SD_OPTS ""
 637
 638static int drive_init_func(QemuOpts *opts, void *opaque)
 639{
 640    int *use_scsi = opaque;
 641
 642    return drive_init(opts, *use_scsi) == NULL;
 643}
 644
 645static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
 646{
 647    if (NULL == qemu_opt_get(opts, "snapshot")) {
 648        qemu_opt_set(opts, "snapshot", "on");
 649    }
 650    return 0;
 651}
 652
 653static void default_drive(int enable, int snapshot, int use_scsi,
 654                          BlockInterfaceType type, int index,
 655                          const char *optstr)
 656{
 657    QemuOpts *opts;
 658
 659    if (type == IF_DEFAULT) {
 660        type = use_scsi ? IF_SCSI : IF_IDE;
 661    }
 662
 663    if (!enable || drive_get_by_index(type, index)) {
 664        return;
 665    }
 666
 667    opts = drive_add(type, index, NULL, optstr);
 668    if (snapshot) {
 669        drive_enable_snapshot(opts, NULL);
 670    }
 671    if (!drive_init(opts, use_scsi)) {
 672        exit(1);
 673    }
 674}
 675
 676void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
 677{
 678    boot_set_handler = func;
 679    boot_set_opaque = opaque;
 680}
 681
 682int qemu_boot_set(const char *boot_devices)
 683{
 684    if (!boot_set_handler) {
 685        return -EINVAL;
 686    }
 687    return boot_set_handler(boot_set_opaque, boot_devices);
 688}
 689
 690static void validate_bootdevices(char *devices)
 691{
 692    /* We just do some generic consistency checks */
 693    const char *p;
 694    int bitmap = 0;
 695
 696    for (p = devices; *p != '\0'; p++) {
 697        /* Allowed boot devices are:
 698         * a-b: floppy disk drives
 699         * c-f: IDE disk drives
 700         * g-m: machine implementation dependant drives
 701         * n-p: network devices
 702         * It's up to each machine implementation to check if the given boot
 703         * devices match the actual hardware implementation and firmware
 704         * features.
 705         */
 706        if (*p < 'a' || *p > 'p') {
 707            fprintf(stderr, "Invalid boot device '%c'\n", *p);
 708            exit(1);
 709        }
 710        if (bitmap & (1 << (*p - 'a'))) {
 711            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
 712            exit(1);
 713        }
 714        bitmap |= 1 << (*p - 'a');
 715    }
 716}
 717
 718static void restore_boot_devices(void *opaque)
 719{
 720    char *standard_boot_devices = opaque;
 721    static int first = 1;
 722
 723    /* Restore boot order and remove ourselves after the first boot */
 724    if (first) {
 725        first = 0;
 726        return;
 727    }
 728
 729    qemu_boot_set(standard_boot_devices);
 730
 731    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
 732    qemu_free(standard_boot_devices);
 733}
 734
 735void add_boot_device_path(int32_t bootindex, DeviceState *dev,
 736                          const char *suffix)
 737{
 738    FWBootEntry *node, *i;
 739
 740    if (bootindex < 0) {
 741        return;
 742    }
 743
 744    assert(dev != NULL || suffix != NULL);
 745
 746    node = qemu_mallocz(sizeof(FWBootEntry));
 747    node->bootindex = bootindex;
 748    node->suffix = suffix ? qemu_strdup(suffix) : NULL;
 749    node->dev = dev;
 750
 751    QTAILQ_FOREACH(i, &fw_boot_order, link) {
 752        if (i->bootindex == bootindex) {
 753            fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
 754            exit(1);
 755        } else if (i->bootindex < bootindex) {
 756            continue;
 757        }
 758        QTAILQ_INSERT_BEFORE(i, node, link);
 759        return;
 760    }
 761    QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
 762}
 763
 764/*
 765 * This function returns null terminated string that consist of new line
 766 * separated device paths.
 767 *
 768 * memory pointed by "size" is assigned total length of the array in bytes
 769 *
 770 */
 771char *get_boot_devices_list(uint32_t *size)
 772{
 773    FWBootEntry *i;
 774    uint32_t total = 0;
 775    char *list = NULL;
 776
 777    QTAILQ_FOREACH(i, &fw_boot_order, link) {
 778        char *devpath = NULL, *bootpath;
 779        int len;
 780
 781        if (i->dev) {
 782            devpath = qdev_get_fw_dev_path(i->dev);
 783            assert(devpath);
 784        }
 785
 786        if (i->suffix && devpath) {
 787            size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
 788
 789            bootpath = qemu_malloc(bootpathlen);
 790            snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
 791            qemu_free(devpath);
 792        } else if (devpath) {
 793            bootpath = devpath;
 794        } else {
 795            bootpath = qemu_strdup(i->suffix);
 796            assert(bootpath);
 797        }
 798
 799        if (total) {
 800            list[total-1] = '\n';
 801        }
 802        len = strlen(bootpath) + 1;
 803        list = qemu_realloc(list, total + len);
 804        memcpy(&list[total], bootpath, len);
 805        total += len;
 806        qemu_free(bootpath);
 807    }
 808
 809    *size = total;
 810
 811    return list;
 812}
 813
 814static void numa_add(const char *optarg)
 815{
 816    char option[128];
 817    char *endptr;
 818    unsigned long long value, endvalue;
 819    int nodenr;
 820
 821    optarg = get_opt_name(option, 128, optarg, ',') + 1;
 822    if (!strcmp(option, "node")) {
 823        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
 824            nodenr = nb_numa_nodes;
 825        } else {
 826            nodenr = strtoull(option, NULL, 10);
 827        }
 828
 829        if (get_param_value(option, 128, "mem", optarg) == 0) {
 830            node_mem[nodenr] = 0;
 831        } else {
 832            int64_t sval;
 833            sval = strtosz(option, NULL);
 834            if (sval < 0) {
 835                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
 836                exit(1);
 837            }
 838            node_mem[nodenr] = sval;
 839        }
 840        if (get_param_value(option, 128, "cpus", optarg) == 0) {
 841            node_cpumask[nodenr] = 0;
 842        } else {
 843            value = strtoull(option, &endptr, 10);
 844            if (value >= 64) {
 845                value = 63;
 846                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
 847            } else {
 848                if (*endptr == '-') {
 849                    endvalue = strtoull(endptr+1, &endptr, 10);
 850                    if (endvalue >= 63) {
 851                        endvalue = 62;
 852                        fprintf(stderr,
 853                            "only 63 CPUs in NUMA mode supported.\n");
 854                    }
 855                    value = (2ULL << endvalue) - (1ULL << value);
 856                } else {
 857                    value = 1ULL << value;
 858                }
 859            }
 860            node_cpumask[nodenr] = value;
 861        }
 862        nb_numa_nodes++;
 863    }
 864    return;
 865}
 866
 867static void smp_parse(const char *optarg)
 868{
 869    int smp, sockets = 0, threads = 0, cores = 0;
 870    char *endptr;
 871    char option[128];
 872
 873    smp = strtoul(optarg, &endptr, 10);
 874    if (endptr != optarg) {
 875        if (*endptr == ',') {
 876            endptr++;
 877        }
 878    }
 879    if (get_param_value(option, 128, "sockets", endptr) != 0)
 880        sockets = strtoull(option, NULL, 10);
 881    if (get_param_value(option, 128, "cores", endptr) != 0)
 882        cores = strtoull(option, NULL, 10);
 883    if (get_param_value(option, 128, "threads", endptr) != 0)
 884        threads = strtoull(option, NULL, 10);
 885    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
 886        max_cpus = strtoull(option, NULL, 10);
 887
 888    /* compute missing values, prefer sockets over cores over threads */
 889    if (smp == 0 || sockets == 0) {
 890        sockets = sockets > 0 ? sockets : 1;
 891        cores = cores > 0 ? cores : 1;
 892        threads = threads > 0 ? threads : 1;
 893        if (smp == 0) {
 894            smp = cores * threads * sockets;
 895        }
 896    } else {
 897        if (cores == 0) {
 898            threads = threads > 0 ? threads : 1;
 899            cores = smp / (sockets * threads);
 900        } else {
 901            threads = smp / (cores * sockets);
 902        }
 903    }
 904    smp_cpus = smp;
 905    smp_cores = cores > 0 ? cores : 1;
 906    smp_threads = threads > 0 ? threads : 1;
 907    if (max_cpus == 0)
 908        max_cpus = smp_cpus;
 909}
 910
 911/***********************************************************/
 912/* USB devices */
 913
 914static int usb_device_add(const char *devname)
 915{
 916    const char *p;
 917    USBDevice *dev = NULL;
 918
 919    if (!usb_enabled)
 920        return -1;
 921
 922    /* drivers with .usbdevice_name entry in USBDeviceInfo */
 923    dev = usbdevice_create(devname);
 924    if (dev)
 925        goto done;
 926
 927    /* the other ones */
 928#ifndef CONFIG_LINUX
 929    /* only the linux version is qdev-ified, usb-bsd still needs this */
 930    if (strstart(devname, "host:", &p)) {
 931        dev = usb_host_device_open(p);
 932    } else
 933#endif
 934    if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
 935        dev = usb_bt_init(devname[2] ? hci_init(p) :
 936                        bt_new_hci(qemu_find_bt_vlan(0)));
 937    } else {
 938        return -1;
 939    }
 940    if (!dev)
 941        return -1;
 942
 943done:
 944    return 0;
 945}
 946
 947static int usb_device_del(const char *devname)
 948{
 949    int bus_num, addr;
 950    const char *p;
 951
 952    if (strstart(devname, "host:", &p))
 953        return usb_host_device_close(p);
 954
 955    if (!usb_enabled)
 956        return -1;
 957
 958    p = strchr(devname, '.');
 959    if (!p)
 960        return -1;
 961    bus_num = strtoul(devname, NULL, 0);
 962    addr = strtoul(p + 1, NULL, 0);
 963
 964    return usb_device_delete_addr(bus_num, addr);
 965}
 966
 967static int usb_parse(const char *cmdline)
 968{
 969    int r;
 970    r = usb_device_add(cmdline);
 971    if (r < 0) {
 972        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
 973    }
 974    return r;
 975}
 976
 977void do_usb_add(Monitor *mon, const QDict *qdict)
 978{
 979    const char *devname = qdict_get_str(qdict, "devname");
 980    if (usb_device_add(devname) < 0) {
 981        error_report("could not add USB device '%s'", devname);
 982    }
 983}
 984
 985void do_usb_del(Monitor *mon, const QDict *qdict)
 986{
 987    const char *devname = qdict_get_str(qdict, "devname");
 988    if (usb_device_del(devname) < 0) {
 989        error_report("could not delete USB device '%s'", devname);
 990    }
 991}
 992
 993/***********************************************************/
 994/* PCMCIA/Cardbus */
 995
 996static struct pcmcia_socket_entry_s {
 997    PCMCIASocket *socket;
 998    struct pcmcia_socket_entry_s *next;
 999} *pcmcia_sockets = 0;
1000
1001void pcmcia_socket_register(PCMCIASocket *socket)
1002{
1003    struct pcmcia_socket_entry_s *entry;
1004
1005    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1006    entry->socket = socket;
1007    entry->next = pcmcia_sockets;
1008    pcmcia_sockets = entry;
1009}
1010
1011void pcmcia_socket_unregister(PCMCIASocket *socket)
1012{
1013    struct pcmcia_socket_entry_s *entry, **ptr;
1014
1015    ptr = &pcmcia_sockets;
1016    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1017        if (entry->socket == socket) {
1018            *ptr = entry->next;
1019            qemu_free(entry);
1020        }
1021}
1022
1023void pcmcia_info(Monitor *mon)
1024{
1025    struct pcmcia_socket_entry_s *iter;
1026
1027    if (!pcmcia_sockets)
1028        monitor_printf(mon, "No PCMCIA sockets\n");
1029
1030    for (iter = pcmcia_sockets; iter; iter = iter->next)
1031        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1032                       iter->socket->attached ? iter->socket->card_string :
1033                       "Empty");
1034}
1035
1036/***********************************************************/
1037/* machine registration */
1038
1039static QEMUMachine *first_machine = NULL;
1040QEMUMachine *current_machine = NULL;
1041
1042int qemu_register_machine(QEMUMachine *m)
1043{
1044    QEMUMachine **pm;
1045    pm = &first_machine;
1046    while (*pm != NULL)
1047        pm = &(*pm)->next;
1048    m->next = NULL;
1049    *pm = m;
1050    return 0;
1051}
1052
1053static QEMUMachine *find_machine(const char *name)
1054{
1055    QEMUMachine *m;
1056
1057    for(m = first_machine; m != NULL; m = m->next) {
1058        if (!strcmp(m->name, name))
1059            return m;
1060        if (m->alias && !strcmp(m->alias, name))
1061            return m;
1062    }
1063    return NULL;
1064}
1065
1066static QEMUMachine *find_default_machine(void)
1067{
1068    QEMUMachine *m;
1069
1070    for(m = first_machine; m != NULL; m = m->next) {
1071        if (m->is_default) {
1072            return m;
1073        }
1074    }
1075    return NULL;
1076}
1077
1078/***********************************************************/
1079/* main execution loop */
1080
1081static void gui_update(void *opaque)
1082{
1083    uint64_t interval = GUI_REFRESH_INTERVAL;
1084    DisplayState *ds = opaque;
1085    DisplayChangeListener *dcl = ds->listeners;
1086
1087    qemu_flush_coalesced_mmio_buffer();
1088    dpy_refresh(ds);
1089
1090    while (dcl != NULL) {
1091        if (dcl->gui_timer_interval &&
1092            dcl->gui_timer_interval < interval)
1093            interval = dcl->gui_timer_interval;
1094        dcl = dcl->next;
1095    }
1096    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1097}
1098
1099static void nographic_update(void *opaque)
1100{
1101    uint64_t interval = GUI_REFRESH_INTERVAL;
1102
1103    qemu_flush_coalesced_mmio_buffer();
1104    qemu_mod_timer(nographic_timer, interval + qemu_get_clock_ms(rt_clock));
1105}
1106
1107struct vm_change_state_entry {
1108    VMChangeStateHandler *cb;
1109    void *opaque;
1110    QLIST_ENTRY (vm_change_state_entry) entries;
1111};
1112
1113static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1114
1115VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1116                                                     void *opaque)
1117{
1118    VMChangeStateEntry *e;
1119
1120    e = qemu_mallocz(sizeof (*e));
1121
1122    e->cb = cb;
1123    e->opaque = opaque;
1124    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1125    return e;
1126}
1127
1128void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1129{
1130    QLIST_REMOVE (e, entries);
1131    qemu_free (e);
1132}
1133
1134void vm_state_notify(int running, int reason)
1135{
1136    VMChangeStateEntry *e;
1137
1138    trace_vm_state_notify(running, reason);
1139
1140    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1141        e->cb(e->opaque, running, reason);
1142    }
1143}
1144
1145void vm_start(void)
1146{
1147    if (!vm_running) {
1148        cpu_enable_ticks();
1149        vm_running = 1;
1150        vm_state_notify(1, 0);
1151        resume_all_vcpus();
1152        monitor_protocol_event(QEVENT_RESUME, NULL);
1153    }
1154}
1155
1156/* reset/shutdown handler */
1157
1158typedef struct QEMUResetEntry {
1159    QTAILQ_ENTRY(QEMUResetEntry) entry;
1160    QEMUResetHandler *func;
1161    void *opaque;
1162} QEMUResetEntry;
1163
1164static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1165    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1166static int reset_requested;
1167static int shutdown_requested, shutdown_signal = -1;
1168static pid_t shutdown_pid;
1169static int powerdown_requested;
1170static int debug_requested;
1171static int vmstop_requested;
1172
1173int qemu_shutdown_requested_get(void)
1174{
1175    return shutdown_requested;
1176}
1177
1178int qemu_reset_requested_get(void)
1179{
1180    return reset_requested;
1181}
1182
1183int qemu_shutdown_requested(void)
1184{
1185    int r = shutdown_requested;
1186    shutdown_requested = 0;
1187    return r;
1188}
1189
1190void qemu_kill_report(void)
1191{
1192    if (shutdown_signal != -1) {
1193        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1194        if (shutdown_pid == 0) {
1195            /* This happens for eg ^C at the terminal, so it's worth
1196             * avoiding printing an odd message in that case.
1197             */
1198            fputc('\n', stderr);
1199        } else {
1200            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1201        }
1202        shutdown_signal = -1;
1203    }
1204}
1205
1206int qemu_reset_requested(void)
1207{
1208    int r = reset_requested;
1209    reset_requested = 0;
1210    return r;
1211}
1212
1213int qemu_powerdown_requested(void)
1214{
1215    int r = powerdown_requested;
1216    powerdown_requested = 0;
1217    return r;
1218}
1219
1220static int qemu_debug_requested(void)
1221{
1222    int r = debug_requested;
1223    debug_requested = 0;
1224    return r;
1225}
1226
1227static int qemu_vmstop_requested(void)
1228{
1229    int r = vmstop_requested;
1230    vmstop_requested = 0;
1231    return r;
1232}
1233
1234void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1235{
1236    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1237
1238    re->func = func;
1239    re->opaque = opaque;
1240    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1241}
1242
1243void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1244{
1245    QEMUResetEntry *re;
1246
1247    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1248        if (re->func == func && re->opaque == opaque) {
1249            QTAILQ_REMOVE(&reset_handlers, re, entry);
1250            qemu_free(re);
1251            return;
1252        }
1253    }
1254}
1255
1256void qemu_system_reset(bool report)
1257{
1258    QEMUResetEntry *re, *nre;
1259
1260    /* reset all devices */
1261    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1262        re->func(re->opaque);
1263    }
1264    if (report) {
1265        monitor_protocol_event(QEVENT_RESET, NULL);
1266    }
1267    cpu_synchronize_all_post_reset();
1268}
1269
1270void qemu_system_reset_request(void)
1271{
1272    if (no_reboot) {
1273        shutdown_requested = 1;
1274    } else {
1275        reset_requested = 1;
1276    }
1277    cpu_stop_current();
1278    qemu_notify_event();
1279}
1280
1281void qemu_system_killed(int signal, pid_t pid)
1282{
1283    shutdown_signal = signal;
1284    shutdown_pid = pid;
1285    qemu_system_shutdown_request();
1286}
1287
1288void qemu_system_shutdown_request(void)
1289{
1290    shutdown_requested = 1;
1291    qemu_notify_event();
1292}
1293
1294void qemu_system_powerdown_request(void)
1295{
1296    powerdown_requested = 1;
1297    qemu_notify_event();
1298}
1299
1300void qemu_system_debug_request(void)
1301{
1302    debug_requested = 1;
1303    qemu_notify_event();
1304}
1305
1306void qemu_system_vmstop_request(int reason)
1307{
1308    vmstop_requested = reason;
1309    qemu_notify_event();
1310}
1311
1312void main_loop_wait(int nonblocking)
1313{
1314    fd_set rfds, wfds, xfds;
1315    int ret, nfds;
1316    struct timeval tv;
1317    int timeout;
1318
1319    if (nonblocking)
1320        timeout = 0;
1321    else {
1322        timeout = qemu_calculate_timeout();
1323        qemu_bh_update_timeout(&timeout);
1324    }
1325
1326    os_host_main_loop_wait(&timeout);
1327
1328    tv.tv_sec = timeout / 1000;
1329    tv.tv_usec = (timeout % 1000) * 1000;
1330
1331    /* poll any events */
1332    /* XXX: separate device handlers from system ones */
1333    nfds = -1;
1334    FD_ZERO(&rfds);
1335    FD_ZERO(&wfds);
1336    FD_ZERO(&xfds);
1337    qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
1338    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1339
1340    qemu_mutex_unlock_iothread();
1341    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1342    qemu_mutex_lock_iothread();
1343
1344    qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
1345    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1346
1347    qemu_run_all_timers();
1348
1349    /* Check bottom-halves last in case any of the earlier events triggered
1350       them.  */
1351    qemu_bh_poll();
1352
1353}
1354
1355#ifndef CONFIG_IOTHREAD
1356static int vm_request_pending(void)
1357{
1358    return powerdown_requested ||
1359           reset_requested ||
1360           shutdown_requested ||
1361           debug_requested ||
1362           vmstop_requested;
1363}
1364#endif
1365
1366qemu_irq qemu_system_powerdown;
1367
1368static void main_loop(void)
1369{
1370    bool nonblocking = false;
1371#ifdef CONFIG_PROFILER
1372    int64_t ti;
1373#endif
1374    int r;
1375
1376    qemu_main_loop_start();
1377
1378    for (;;) {
1379#ifndef CONFIG_IOTHREAD
1380        nonblocking = cpu_exec_all();
1381        if (vm_request_pending()) {
1382            nonblocking = true;
1383        }
1384#endif
1385#ifdef CONFIG_PROFILER
1386        ti = profile_getclock();
1387#endif
1388        main_loop_wait(nonblocking);
1389#ifdef CONFIG_PROFILER
1390        dev_time += profile_getclock() - ti;
1391#endif
1392
1393        if (qemu_debug_requested()) {
1394            vm_stop(VMSTOP_DEBUG);
1395        }
1396        if (qemu_shutdown_requested()) {
1397            qemu_kill_report();
1398            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1399            if (no_shutdown) {
1400                vm_stop(VMSTOP_SHUTDOWN);
1401            } else
1402                break;
1403        }
1404        if (qemu_reset_requested()) {
1405            pause_all_vcpus();
1406            cpu_synchronize_all_states();
1407            qemu_system_reset(VMRESET_REPORT);
1408            resume_all_vcpus();
1409        }
1410        if (qemu_powerdown_requested()) {
1411            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1412            qemu_irq_raise(qemu_system_powerdown);
1413        }
1414        if ((r = qemu_vmstop_requested())) {
1415            vm_stop(r);
1416        }
1417    }
1418    bdrv_close_all();
1419    pause_all_vcpus();
1420}
1421
1422static void version(void)
1423{
1424    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1425}
1426
1427static void help(int exitcode)
1428{
1429    const char *options_help =
1430#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1431        opt_help
1432#define DEFHEADING(text) stringify(text) "\n"
1433#include "qemu-options.def"
1434#undef DEF
1435#undef DEFHEADING
1436#undef GEN_DOCS
1437        ;
1438    version();
1439    printf("usage: %s [options] [disk_image]\n"
1440           "\n"
1441           "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
1442           "\n"
1443           "%s\n"
1444           "During emulation, the following keys are useful:\n"
1445           "ctrl-alt-f      toggle full screen\n"
1446           "ctrl-alt-n      switch to virtual console 'n'\n"
1447           "ctrl-alt        toggle mouse and keyboard grab\n"
1448           "\n"
1449           "When using -nographic, press 'ctrl-a h' to get some help.\n",
1450           "qemu",
1451           options_help);
1452    exit(exitcode);
1453}
1454
1455#define HAS_ARG 0x0001
1456
1457typedef struct QEMUOption {
1458    const char *name;
1459    int flags;
1460    int index;
1461    uint32_t arch_mask;
1462} QEMUOption;
1463
1464static const QEMUOption qemu_options[] = {
1465    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1466#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1467    { option, opt_arg, opt_enum, arch_mask },
1468#define DEFHEADING(text)
1469#include "qemu-options.def"
1470#undef DEF
1471#undef DEFHEADING
1472#undef GEN_DOCS
1473    { NULL },
1474};
1475static void select_vgahw (const char *p)
1476{
1477    const char *opts;
1478
1479    default_vga = 0;
1480    vga_interface_type = VGA_NONE;
1481    if (strstart(p, "std", &opts)) {
1482        vga_interface_type = VGA_STD;
1483    } else if (strstart(p, "cirrus", &opts)) {
1484        vga_interface_type = VGA_CIRRUS;
1485    } else if (strstart(p, "vmware", &opts)) {
1486        vga_interface_type = VGA_VMWARE;
1487    } else if (strstart(p, "xenfb", &opts)) {
1488        vga_interface_type = VGA_XENFB;
1489    } else if (strstart(p, "qxl", &opts)) {
1490        vga_interface_type = VGA_QXL;
1491    } else if (!strstart(p, "none", &opts)) {
1492    invalid_vga:
1493        fprintf(stderr, "Unknown vga type: %s\n", p);
1494        exit(1);
1495    }
1496    while (*opts) {
1497        const char *nextopt;
1498
1499        if (strstart(opts, ",retrace=", &nextopt)) {
1500            opts = nextopt;
1501            if (strstart(opts, "dumb", &nextopt))
1502                vga_retrace_method = VGA_RETRACE_DUMB;
1503            else if (strstart(opts, "precise", &nextopt))
1504                vga_retrace_method = VGA_RETRACE_PRECISE;
1505            else goto invalid_vga;
1506        } else goto invalid_vga;
1507        opts = nextopt;
1508    }
1509}
1510
1511static DisplayType select_display(const char *p)
1512{
1513    const char *opts;
1514    DisplayType display = DT_DEFAULT;
1515
1516    if (strstart(p, "sdl", &opts)) {
1517#ifdef CONFIG_SDL
1518        display = DT_SDL;
1519        while (*opts) {
1520            const char *nextopt;
1521
1522            if (strstart(opts, ",frame=", &nextopt)) {
1523                opts = nextopt;
1524                if (strstart(opts, "on", &nextopt)) {
1525                    no_frame = 0;
1526                } else if (strstart(opts, "off", &nextopt)) {
1527                    no_frame = 1;
1528                } else {
1529                    goto invalid_sdl_args;
1530                }
1531            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
1532                opts = nextopt;
1533                if (strstart(opts, "on", &nextopt)) {
1534                    alt_grab = 1;
1535                } else if (strstart(opts, "off", &nextopt)) {
1536                    alt_grab = 0;
1537                } else {
1538                    goto invalid_sdl_args;
1539                }
1540            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1541                opts = nextopt;
1542                if (strstart(opts, "on", &nextopt)) {
1543                    ctrl_grab = 1;
1544                } else if (strstart(opts, "off", &nextopt)) {
1545                    ctrl_grab = 0;
1546                } else {
1547                    goto invalid_sdl_args;
1548                }
1549            } else if (strstart(opts, ",window_close=", &nextopt)) {
1550                opts = nextopt;
1551                if (strstart(opts, "on", &nextopt)) {
1552                    no_quit = 0;
1553                } else if (strstart(opts, "off", &nextopt)) {
1554                    no_quit = 1;
1555                } else {
1556                    goto invalid_sdl_args;
1557                }
1558            } else {
1559            invalid_sdl_args:
1560                fprintf(stderr, "Invalid SDL option string: %s\n", p);
1561                exit(1);
1562            }
1563            opts = nextopt;
1564        }
1565#else
1566        fprintf(stderr, "SDL support is disabled\n");
1567        exit(1);
1568#endif
1569    } else if (strstart(p, "vnc", &opts)) {
1570#ifdef CONFIG_VNC
1571        display_remote++;
1572
1573        if (*opts) {
1574            const char *nextopt;
1575
1576            if (strstart(opts, "=", &nextopt)) {
1577                vnc_display = nextopt;
1578            }
1579        }
1580        if (!vnc_display) {
1581            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1582            exit(1);
1583        }
1584#else
1585        fprintf(stderr, "VNC support is disabled\n");
1586        exit(1);
1587#endif
1588    } else if (strstart(p, "curses", &opts)) {
1589#ifdef CONFIG_CURSES
1590        display = DT_CURSES;
1591#else
1592        fprintf(stderr, "Curses support is disabled\n");
1593        exit(1);
1594#endif
1595    } else if (strstart(p, "none", &opts)) {
1596        display = DT_NONE;
1597    } else {
1598        fprintf(stderr, "Unknown display type: %s\n", p);
1599        exit(1);
1600    }
1601
1602    return display;
1603}
1604
1605static int balloon_parse(const char *arg)
1606{
1607    QemuOpts *opts;
1608
1609    if (strcmp(arg, "none") == 0) {
1610        return 0;
1611    }
1612
1613    if (!strncmp(arg, "virtio", 6)) {
1614        if (arg[6] == ',') {
1615            /* have params -> parse them */
1616            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1617            if (!opts)
1618                return  -1;
1619        } else {
1620            /* create empty opts */
1621            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
1622        }
1623        qemu_opt_set(opts, "driver", "virtio-balloon");
1624        return 0;
1625    }
1626
1627    return -1;
1628}
1629
1630char *qemu_find_file(int type, const char *name)
1631{
1632    int len;
1633    const char *subdir;
1634    char *buf;
1635
1636    /* If name contains path separators then try it as a straight path.  */
1637    if ((strchr(name, '/') || strchr(name, '\\'))
1638        && access(name, R_OK) == 0) {
1639        return qemu_strdup(name);
1640    }
1641    switch (type) {
1642    case QEMU_FILE_TYPE_BIOS:
1643        subdir = "";
1644        break;
1645    case QEMU_FILE_TYPE_KEYMAP:
1646        subdir = "keymaps/";
1647        break;
1648    default:
1649        abort();
1650    }
1651    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
1652    buf = qemu_mallocz(len);
1653    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
1654    if (access(buf, R_OK)) {
1655        qemu_free(buf);
1656        return NULL;
1657    }
1658    return buf;
1659}
1660
1661static int device_help_func(QemuOpts *opts, void *opaque)
1662{
1663    return qdev_device_help(opts);
1664}
1665
1666static int device_init_func(QemuOpts *opts, void *opaque)
1667{
1668    DeviceState *dev;
1669
1670    dev = qdev_device_add(opts);
1671    if (!dev)
1672        return -1;
1673    return 0;
1674}
1675
1676static int chardev_init_func(QemuOpts *opts, void *opaque)
1677{
1678    CharDriverState *chr;
1679
1680    chr = qemu_chr_open_opts(opts, NULL);
1681    if (!chr)
1682        return -1;
1683    return 0;
1684}
1685
1686#ifdef CONFIG_VIRTFS
1687static int fsdev_init_func(QemuOpts *opts, void *opaque)
1688{
1689    int ret;
1690    ret = qemu_fsdev_add(opts);
1691
1692    return ret;
1693}
1694#endif
1695
1696static int mon_init_func(QemuOpts *opts, void *opaque)
1697{
1698    CharDriverState *chr;
1699    const char *chardev;
1700    const char *mode;
1701    int flags;
1702
1703    mode = qemu_opt_get(opts, "mode");
1704    if (mode == NULL) {
1705        mode = "readline";
1706    }
1707    if (strcmp(mode, "readline") == 0) {
1708        flags = MONITOR_USE_READLINE;
1709    } else if (strcmp(mode, "control") == 0) {
1710        flags = MONITOR_USE_CONTROL;
1711    } else {
1712        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1713        exit(1);
1714    }
1715
1716    if (qemu_opt_get_bool(opts, "pretty", 0))
1717        flags |= MONITOR_USE_PRETTY;
1718
1719    if (qemu_opt_get_bool(opts, "default", 0))
1720        flags |= MONITOR_IS_DEFAULT;
1721
1722    chardev = qemu_opt_get(opts, "chardev");
1723    chr = qemu_chr_find(chardev);
1724    if (chr == NULL) {
1725        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1726        exit(1);
1727    }
1728
1729    monitor_init(chr, flags);
1730    return 0;
1731}
1732
1733static void monitor_parse(const char *optarg, const char *mode)
1734{
1735    static int monitor_device_index = 0;
1736    QemuOpts *opts;
1737    const char *p;
1738    char label[32];
1739    int def = 0;
1740
1741    if (strstart(optarg, "chardev:", &p)) {
1742        snprintf(label, sizeof(label), "%s", p);
1743    } else {
1744        snprintf(label, sizeof(label), "compat_monitor%d",
1745                 monitor_device_index);
1746        if (monitor_device_index == 0) {
1747            def = 1;
1748        }
1749        opts = qemu_chr_parse_compat(label, optarg);
1750        if (!opts) {
1751            fprintf(stderr, "parse error: %s\n", optarg);
1752            exit(1);
1753        }
1754    }
1755
1756    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);
1757    if (!opts) {
1758        fprintf(stderr, "duplicate chardev: %s\n", label);
1759        exit(1);
1760    }
1761    qemu_opt_set(opts, "mode", mode);
1762    qemu_opt_set(opts, "chardev", label);
1763    if (def)
1764        qemu_opt_set(opts, "default", "on");
1765    monitor_device_index++;
1766}
1767
1768struct device_config {
1769    enum {
1770        DEV_USB,       /* -usbdevice     */
1771        DEV_BT,        /* -bt            */
1772        DEV_SERIAL,    /* -serial        */
1773        DEV_PARALLEL,  /* -parallel      */
1774        DEV_VIRTCON,   /* -virtioconsole */
1775        DEV_DEBUGCON,  /* -debugcon */
1776    } type;
1777    const char *cmdline;
1778    QTAILQ_ENTRY(device_config) next;
1779};
1780QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1781
1782static void add_device_config(int type, const char *cmdline)
1783{
1784    struct device_config *conf;
1785
1786    conf = qemu_mallocz(sizeof(*conf));
1787    conf->type = type;
1788    conf->cmdline = cmdline;
1789    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1790}
1791
1792static int foreach_device_config(int type, int (*func)(const char *cmdline))
1793{
1794    struct device_config *conf;
1795    int rc;
1796
1797    QTAILQ_FOREACH(conf, &device_configs, next) {
1798        if (conf->type != type)
1799            continue;
1800        rc = func(conf->cmdline);
1801        if (0 != rc)
1802            return rc;
1803    }
1804    return 0;
1805}
1806
1807static int serial_parse(const char *devname)
1808{
1809    static int index = 0;
1810    char label[32];
1811
1812    if (strcmp(devname, "none") == 0)
1813        return 0;
1814    if (index == MAX_SERIAL_PORTS) {
1815        fprintf(stderr, "qemu: too many serial ports\n");
1816        exit(1);
1817    }
1818    snprintf(label, sizeof(label), "serial%d", index);
1819    serial_hds[index] = qemu_chr_open(label, devname, NULL);
1820    if (!serial_hds[index]) {
1821        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
1822                devname, strerror(errno));
1823        return -1;
1824    }
1825    index++;
1826    return 0;
1827}
1828
1829static int parallel_parse(const char *devname)
1830{
1831    static int index = 0;
1832    char label[32];
1833
1834    if (strcmp(devname, "none") == 0)
1835        return 0;
1836    if (index == MAX_PARALLEL_PORTS) {
1837        fprintf(stderr, "qemu: too many parallel ports\n");
1838        exit(1);
1839    }
1840    snprintf(label, sizeof(label), "parallel%d", index);
1841    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
1842    if (!parallel_hds[index]) {
1843        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
1844                devname, strerror(errno));
1845        return -1;
1846    }
1847    index++;
1848    return 0;
1849}
1850
1851static int virtcon_parse(const char *devname)
1852{
1853    QemuOptsList *device = qemu_find_opts("device");
1854    static int index = 0;
1855    char label[32];
1856    QemuOpts *bus_opts, *dev_opts;
1857
1858    if (strcmp(devname, "none") == 0)
1859        return 0;
1860    if (index == MAX_VIRTIO_CONSOLES) {
1861        fprintf(stderr, "qemu: too many virtio consoles\n");
1862        exit(1);
1863    }
1864
1865    bus_opts = qemu_opts_create(device, NULL, 0);
1866    qemu_opt_set(bus_opts, "driver", "virtio-serial");
1867
1868    dev_opts = qemu_opts_create(device, NULL, 0);
1869    qemu_opt_set(dev_opts, "driver", "virtconsole");
1870
1871    snprintf(label, sizeof(label), "virtcon%d", index);
1872    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
1873    if (!virtcon_hds[index]) {
1874        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
1875                devname, strerror(errno));
1876        return -1;
1877    }
1878    qemu_opt_set(dev_opts, "chardev", label);
1879
1880    index++;
1881    return 0;
1882}
1883
1884static int debugcon_parse(const char *devname)
1885{   
1886    QemuOpts *opts;
1887
1888    if (!qemu_chr_open("debugcon", devname, NULL)) {
1889        exit(1);
1890    }
1891    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);
1892    if (!opts) {
1893        fprintf(stderr, "qemu: already have a debugcon device\n");
1894        exit(1);
1895    }
1896    qemu_opt_set(opts, "driver", "isa-debugcon");
1897    qemu_opt_set(opts, "chardev", "debugcon");
1898    return 0;
1899}
1900
1901static QEMUMachine *machine_parse(const char *name)
1902{
1903    QEMUMachine *m, *machine = NULL;
1904
1905    if (name) {
1906        machine = find_machine(name);
1907    }
1908    if (machine) {
1909        return machine;
1910    }
1911    printf("Supported machines are:\n");
1912    for (m = first_machine; m != NULL; m = m->next) {
1913        if (m->alias) {
1914            printf("%-10s %s (alias of %s)\n", m->alias, m->desc, m->name);
1915        }
1916        printf("%-10s %s%s\n", m->name, m->desc,
1917               m->is_default ? " (default)" : "");
1918    }
1919    exit(!name || *name != '?');
1920}
1921
1922static int tcg_init(void)
1923{
1924    return 0;
1925}
1926
1927static struct {
1928    const char *opt_name;
1929    const char *name;
1930    int (*available)(void);
1931    int (*init)(void);
1932    int *allowed;
1933} accel_list[] = {
1934    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
1935    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
1936    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
1937};
1938
1939static int configure_accelerator(void)
1940{
1941    const char *p = NULL;
1942    char buf[10];
1943    int i, ret;
1944    bool accel_initalised = 0;
1945    bool init_failed = 0;
1946
1947    QemuOptsList *list = qemu_find_opts("machine");
1948    if (!QTAILQ_EMPTY(&list->head)) {
1949        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
1950    }
1951
1952    if (p == NULL) {
1953        /* Use the default "accelerator", tcg */
1954        p = "tcg";
1955    }
1956
1957    while (!accel_initalised && *p != '\0') {
1958        if (*p == ':') {
1959            p++;
1960        }
1961        p = get_opt_name(buf, sizeof (buf), p, ':');
1962        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
1963            if (strcmp(accel_list[i].opt_name, buf) == 0) {
1964                *(accel_list[i].allowed) = 1;
1965                ret = accel_list[i].init();
1966                if (ret < 0) {
1967                    init_failed = 1;
1968                    if (!accel_list[i].available()) {
1969                        printf("%s not supported for this target\n",
1970                               accel_list[i].name);
1971                    } else {
1972                        fprintf(stderr, "failed to initialize %s: %s\n",
1973                                accel_list[i].name,
1974                                strerror(-ret));
1975                    }
1976                    *(accel_list[i].allowed) = 0;
1977                } else {
1978                    accel_initalised = 1;
1979                }
1980                break;
1981            }
1982        }
1983        if (i == ARRAY_SIZE(accel_list)) {
1984            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
1985        }
1986    }
1987
1988    if (!accel_initalised) {
1989        fprintf(stderr, "No accelerator found!\n");
1990        exit(1);
1991    }
1992
1993    if (init_failed) {
1994        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
1995    }
1996
1997    return !accel_initalised;
1998}
1999
2000void qemu_add_exit_notifier(Notifier *notify)
2001{
2002    notifier_list_add(&exit_notifiers, notify);
2003}
2004
2005void qemu_remove_exit_notifier(Notifier *notify)
2006{
2007    notifier_list_remove(&exit_notifiers, notify);
2008}
2009
2010static void qemu_run_exit_notifiers(void)
2011{
2012    notifier_list_notify(&exit_notifiers, NULL);
2013}
2014
2015void qemu_add_machine_init_done_notifier(Notifier *notify)
2016{
2017    notifier_list_add(&machine_init_done_notifiers, notify);
2018}
2019
2020static void qemu_run_machine_init_done_notifiers(void)
2021{
2022    notifier_list_notify(&machine_init_done_notifiers, NULL);
2023}
2024
2025static const QEMUOption *lookup_opt(int argc, char **argv,
2026                                    const char **poptarg, int *poptind)
2027{
2028    const QEMUOption *popt;
2029    int optind = *poptind;
2030    char *r = argv[optind];
2031    const char *optarg;
2032
2033    loc_set_cmdline(argv, optind, 1);
2034    optind++;
2035    /* Treat --foo the same as -foo.  */
2036    if (r[1] == '-')
2037        r++;
2038    popt = qemu_options;
2039    for(;;) {
2040        if (!popt->name) {
2041            error_report("invalid option");
2042            exit(1);
2043        }
2044        if (!strcmp(popt->name, r + 1))
2045            break;
2046        popt++;
2047    }
2048    if (popt->flags & HAS_ARG) {
2049        if (optind >= argc) {
2050            error_report("requires an argument");
2051            exit(1);
2052        }
2053        optarg = argv[optind++];
2054        loc_set_cmdline(argv, optind - 2, 2);
2055    } else {
2056        optarg = NULL;
2057    }
2058
2059    *poptarg = optarg;
2060    *poptind = optind;
2061
2062    return popt;
2063}
2064
2065int main(int argc, char **argv, char **envp)
2066{
2067    const char *gdbstub_dev = NULL;
2068    int i;
2069    int snapshot, linux_boot;
2070    const char *icount_option = NULL;
2071    const char *initrd_filename;
2072    const char *kernel_filename, *kernel_cmdline;
2073    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2074    DisplayState *ds;
2075    DisplayChangeListener *dcl;
2076    int cyls, heads, secs, translation;
2077    QemuOpts *hda_opts = NULL, *opts;
2078    QemuOptsList *olist;
2079    int optind;
2080    const char *optarg;
2081    const char *loadvm = NULL;
2082    QEMUMachine *machine;
2083    const char *cpu_model;
2084    int tb_size;
2085    const char *pid_file = NULL;
2086    const char *incoming = NULL;
2087#ifdef CONFIG_VNC
2088    int show_vnc_port = 0;
2089#endif
2090    int defconfig = 1;
2091    const char *trace_file = NULL;
2092    const char *log_mask = NULL;
2093    const char *log_file = NULL;
2094
2095    atexit(qemu_run_exit_notifiers);
2096    error_set_progname(argv[0]);
2097
2098    init_clocks();
2099
2100    qemu_cache_utils_init(envp);
2101
2102    QLIST_INIT (&vm_change_state_head);
2103    os_setup_early_signal_handling();
2104
2105    module_call_init(MODULE_INIT_MACHINE);
2106    machine = find_default_machine();
2107    cpu_model = NULL;
2108    initrd_filename = NULL;
2109    ram_size = 0;
2110    snapshot = 0;
2111    kernel_filename = NULL;
2112    kernel_cmdline = "";
2113    cyls = heads = secs = 0;
2114    translation = BIOS_ATA_TRANSLATION_AUTO;
2115
2116    for (i = 0; i < MAX_NODES; i++) {
2117        node_mem[i] = 0;
2118        node_cpumask[i] = 0;
2119    }
2120
2121    nb_numa_nodes = 0;
2122    nb_nics = 0;
2123
2124    tb_size = 0;
2125    autostart= 1;
2126
2127    /* first pass of option parsing */
2128    optind = 1;
2129    while (optind < argc) {
2130        if (argv[optind][0] != '-') {
2131            /* disk image */
2132            optind++;
2133            continue;
2134        } else {
2135            const QEMUOption *popt;
2136
2137            popt = lookup_opt(argc, argv, &optarg, &optind);
2138            switch (popt->index) {
2139            case QEMU_OPTION_nodefconfig:
2140                defconfig=0;
2141                break;
2142            }
2143        }
2144    }
2145
2146    if (defconfig) {
2147        int ret;
2148
2149        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2150        if (ret < 0 && ret != -ENOENT) {
2151            exit(1);
2152        }
2153
2154        ret = qemu_read_config_file(arch_config_name);
2155        if (ret < 0 && ret != -ENOENT) {
2156            exit(1);
2157        }
2158    }
2159    cpudef_init();
2160
2161    /* second pass of option parsing */
2162    optind = 1;
2163    for(;;) {
2164        if (optind >= argc)
2165            break;
2166        if (argv[optind][0] != '-') {
2167            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2168        } else {
2169            const QEMUOption *popt;
2170
2171            popt = lookup_opt(argc, argv, &optarg, &optind);
2172            if (!(popt->arch_mask & arch_type)) {
2173                printf("Option %s not supported for this target\n", popt->name);
2174                exit(1);
2175            }
2176            switch(popt->index) {
2177            case QEMU_OPTION_M:
2178                machine = machine_parse(optarg);
2179                break;
2180            case QEMU_OPTION_cpu:
2181                /* hw initialization will check this */
2182                if (*optarg == '?') {
2183                    list_cpus(stdout, &fprintf, optarg);
2184                    exit(0);
2185                } else {
2186                    cpu_model = optarg;
2187                }
2188                break;
2189            case QEMU_OPTION_initrd:
2190                initrd_filename = optarg;
2191                break;
2192            case QEMU_OPTION_hda:
2193                {
2194                    char buf[256];
2195                    if (cyls == 0)
2196                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
2197                    else
2198                        snprintf(buf, sizeof(buf),
2199                                 "%s,cyls=%d,heads=%d,secs=%d%s",
2200                                 HD_OPTS , cyls, heads, secs,
2201                                 translation == BIOS_ATA_TRANSLATION_LBA ?
2202                                 ",trans=lba" :
2203                                 translation == BIOS_ATA_TRANSLATION_NONE ?
2204                                 ",trans=none" : "");
2205                    drive_add(IF_DEFAULT, 0, optarg, buf);
2206                    break;
2207                }
2208            case QEMU_OPTION_hdb:
2209            case QEMU_OPTION_hdc:
2210            case QEMU_OPTION_hdd:
2211                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2212                          HD_OPTS);
2213                break;
2214            case QEMU_OPTION_drive:
2215                if (drive_def(optarg) == NULL) {
2216                    exit(1);
2217                }
2218                break;
2219            case QEMU_OPTION_set:
2220                if (qemu_set_option(optarg) != 0)
2221                    exit(1);
2222                break;
2223            case QEMU_OPTION_global:
2224                if (qemu_global_option(optarg) != 0)
2225                    exit(1);
2226                break;
2227            case QEMU_OPTION_mtdblock:
2228                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2229                break;
2230            case QEMU_OPTION_sd:
2231                drive_add(IF_SD, 0, optarg, SD_OPTS);
2232                break;
2233            case QEMU_OPTION_pflash:
2234                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2235                break;
2236            case QEMU_OPTION_snapshot:
2237                snapshot = 1;
2238                break;
2239            case QEMU_OPTION_hdachs:
2240                {
2241                    const char *p;
2242                    p = optarg;
2243                    cyls = strtol(p, (char **)&p, 0);
2244                    if (cyls < 1 || cyls > 16383)
2245                        goto chs_fail;
2246                    if (*p != ',')
2247                        goto chs_fail;
2248                    p++;
2249                    heads = strtol(p, (char **)&p, 0);
2250                    if (heads < 1 || heads > 16)
2251                        goto chs_fail;
2252                    if (*p != ',')
2253                        goto chs_fail;
2254                    p++;
2255                    secs = strtol(p, (char **)&p, 0);
2256                    if (secs < 1 || secs > 63)
2257                        goto chs_fail;
2258                    if (*p == ',') {
2259                        p++;
2260                        if (!strcmp(p, "none"))
2261                            translation = BIOS_ATA_TRANSLATION_NONE;
2262                        else if (!strcmp(p, "lba"))
2263                            translation = BIOS_ATA_TRANSLATION_LBA;
2264                        else if (!strcmp(p, "auto"))
2265                            translation = BIOS_ATA_TRANSLATION_AUTO;
2266                        else
2267                            goto chs_fail;
2268                    } else if (*p != '\0') {
2269                    chs_fail:
2270                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2271                        exit(1);
2272                    }
2273                    if (hda_opts != NULL) {
2274                        char num[16];
2275                        snprintf(num, sizeof(num), "%d", cyls);
2276                        qemu_opt_set(hda_opts, "cyls", num);
2277                        snprintf(num, sizeof(num), "%d", heads);
2278                        qemu_opt_set(hda_opts, "heads", num);
2279                        snprintf(num, sizeof(num), "%d", secs);
2280                        qemu_opt_set(hda_opts, "secs", num);
2281                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2282                            qemu_opt_set(hda_opts, "trans", "lba");
2283                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2284                            qemu_opt_set(hda_opts, "trans", "none");
2285                    }
2286                }
2287                break;
2288            case QEMU_OPTION_numa:
2289                if (nb_numa_nodes >= MAX_NODES) {
2290                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2291                    exit(1);
2292                }
2293                numa_add(optarg);
2294                break;
2295            case QEMU_OPTION_display:
2296                display_type = select_display(optarg);
2297                break;
2298            case QEMU_OPTION_nographic:
2299                display_type = DT_NOGRAPHIC;
2300                break;
2301            case QEMU_OPTION_curses:
2302#ifdef CONFIG_CURSES
2303                display_type = DT_CURSES;
2304#else
2305                fprintf(stderr, "Curses support is disabled\n");
2306                exit(1);
2307#endif
2308                break;
2309            case QEMU_OPTION_portrait:
2310                graphic_rotate = 90;
2311                break;
2312            case QEMU_OPTION_rotate:
2313                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
2314                if (graphic_rotate != 0 && graphic_rotate != 90 &&
2315                    graphic_rotate != 180 && graphic_rotate != 270) {
2316                    fprintf(stderr,
2317                        "qemu: only 90, 180, 270 deg rotation is available\n");
2318                    exit(1);
2319                }
2320                break;
2321            case QEMU_OPTION_kernel:
2322                kernel_filename = optarg;
2323                break;
2324            case QEMU_OPTION_append:
2325                kernel_cmdline = optarg;
2326                break;
2327            case QEMU_OPTION_cdrom:
2328                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2329                break;
2330            case QEMU_OPTION_boot:
2331                {
2332                    static const char * const params[] = {
2333                        "order", "once", "menu", NULL
2334                    };
2335                    char buf[sizeof(boot_devices)];
2336                    char *standard_boot_devices;
2337                    int legacy = 0;
2338
2339                    if (!strchr(optarg, '=')) {
2340                        legacy = 1;
2341                        pstrcpy(buf, sizeof(buf), optarg);
2342                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2343                        fprintf(stderr,
2344                                "qemu: unknown boot parameter '%s' in '%s'\n",
2345                                buf, optarg);
2346                        exit(1);
2347                    }
2348
2349                    if (legacy ||
2350                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2351                        validate_bootdevices(buf);
2352                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2353                    }
2354                    if (!legacy) {
2355                        if (get_param_value(buf, sizeof(buf),
2356                                            "once", optarg)) {
2357                            validate_bootdevices(buf);
2358                            standard_boot_devices = qemu_strdup(boot_devices);
2359                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2360                            qemu_register_reset(restore_boot_devices,
2361                                                standard_boot_devices);
2362                        }
2363                        if (get_param_value(buf, sizeof(buf),
2364                                            "menu", optarg)) {
2365                            if (!strcmp(buf, "on")) {
2366                                boot_menu = 1;
2367                            } else if (!strcmp(buf, "off")) {
2368                                boot_menu = 0;
2369                            } else {
2370                                fprintf(stderr,
2371                                        "qemu: invalid option value '%s'\n",
2372                                        buf);
2373                                exit(1);
2374                            }
2375                        }
2376                    }
2377                }
2378                break;
2379            case QEMU_OPTION_fda:
2380            case QEMU_OPTION_fdb:
2381                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2382                          optarg, FD_OPTS);
2383                break;
2384            case QEMU_OPTION_no_fd_bootchk:
2385                fd_bootchk = 0;
2386                break;
2387            case QEMU_OPTION_netdev:
2388                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
2389                    exit(1);
2390                }
2391                break;
2392            case QEMU_OPTION_net:
2393                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
2394                    exit(1);
2395                }
2396                break;
2397#ifdef CONFIG_SLIRP
2398            case QEMU_OPTION_tftp:
2399                legacy_tftp_prefix = optarg;
2400                break;
2401            case QEMU_OPTION_bootp:
2402                legacy_bootp_filename = optarg;
2403                break;
2404            case QEMU_OPTION_redir:
2405                if (net_slirp_redir(optarg) < 0)
2406                    exit(1);
2407                break;
2408#endif
2409            case QEMU_OPTION_bt:
2410                add_device_config(DEV_BT, optarg);
2411                break;
2412            case QEMU_OPTION_audio_help:
2413                if (!(audio_available())) {
2414                    printf("Option %s not supported for this target\n", popt->name);
2415                    exit(1);
2416                }
2417                AUD_help ();
2418                exit (0);
2419                break;
2420            case QEMU_OPTION_soundhw:
2421                if (!(audio_available())) {
2422                    printf("Option %s not supported for this target\n", popt->name);
2423                    exit(1);
2424                }
2425                select_soundhw (optarg);
2426                break;
2427            case QEMU_OPTION_h:
2428                help(0);
2429                break;
2430            case QEMU_OPTION_version:
2431                version();
2432                exit(0);
2433                break;
2434            case QEMU_OPTION_m: {
2435                int64_t value;
2436
2437                value = strtosz(optarg, NULL);
2438                if (value < 0) {
2439                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2440                    exit(1);
2441                }
2442
2443                /* On 32-bit hosts, QEMU is limited by virtual address space */
2444                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
2445                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
2446                    exit(1);
2447                }
2448                if (value != (uint64_t)(ram_addr_t)value) {
2449                    fprintf(stderr, "qemu: ram size too large\n");
2450                    exit(1);
2451                }
2452                ram_size = value;
2453                break;
2454            }
2455            case QEMU_OPTION_mempath:
2456                mem_path = optarg;
2457                break;
2458#ifdef MAP_POPULATE
2459            case QEMU_OPTION_mem_prealloc:
2460                mem_prealloc = 1;
2461                break;
2462#endif
2463            case QEMU_OPTION_d:
2464                log_mask = optarg;
2465                break;
2466            case QEMU_OPTION_D:
2467                log_file = optarg;
2468                break;
2469            case QEMU_OPTION_s:
2470                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
2471                break;
2472            case QEMU_OPTION_gdb:
2473                gdbstub_dev = optarg;
2474                break;
2475            case QEMU_OPTION_L:
2476                data_dir = optarg;
2477                break;
2478            case QEMU_OPTION_bios:
2479                bios_name = optarg;
2480                break;
2481            case QEMU_OPTION_singlestep:
2482                singlestep = 1;
2483                break;
2484            case QEMU_OPTION_S:
2485                autostart = 0;
2486                break;
2487            case QEMU_OPTION_k:
2488                keyboard_layout = optarg;
2489                break;
2490            case QEMU_OPTION_localtime:
2491                rtc_utc = 0;
2492                break;
2493            case QEMU_OPTION_vga:
2494                select_vgahw (optarg);
2495                break;
2496            case QEMU_OPTION_g:
2497                {
2498                    const char *p;
2499                    int w, h, depth;
2500                    p = optarg;
2501                    w = strtol(p, (char **)&p, 10);
2502                    if (w <= 0) {
2503                    graphic_error:
2504                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2505                        exit(1);
2506                    }
2507                    if (*p != 'x')
2508                        goto graphic_error;
2509                    p++;
2510                    h = strtol(p, (char **)&p, 10);
2511                    if (h <= 0)
2512                        goto graphic_error;
2513                    if (*p == 'x') {
2514                        p++;
2515                        depth = strtol(p, (char **)&p, 10);
2516                        if (depth != 8 && depth != 15 && depth != 16 &&
2517                            depth != 24 && depth != 32)
2518                            goto graphic_error;
2519                    } else if (*p == '\0') {
2520                        depth = graphic_depth;
2521                    } else {
2522                        goto graphic_error;
2523                    }
2524
2525                    graphic_width = w;
2526                    graphic_height = h;
2527                    graphic_depth = depth;
2528                }
2529                break;
2530            case QEMU_OPTION_echr:
2531                {
2532                    char *r;
2533                    term_escape_char = strtol(optarg, &r, 0);
2534                    if (r == optarg)
2535                        printf("Bad argument to echr\n");
2536                    break;
2537                }
2538            case QEMU_OPTION_monitor:
2539                monitor_parse(optarg, "readline");
2540                default_monitor = 0;
2541                break;
2542            case QEMU_OPTION_qmp:
2543                monitor_parse(optarg, "control");
2544                default_monitor = 0;
2545                break;
2546            case QEMU_OPTION_mon:
2547                opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
2548                if (!opts) {
2549                    exit(1);
2550                }
2551                default_monitor = 0;
2552                break;
2553            case QEMU_OPTION_chardev:
2554                opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
2555                if (!opts) {
2556                    exit(1);
2557                }
2558                break;
2559            case QEMU_OPTION_fsdev:
2560                olist = qemu_find_opts("fsdev");
2561                if (!olist) {
2562                    fprintf(stderr, "fsdev is not supported by this qemu build.\n");
2563                    exit(1);
2564                }
2565                opts = qemu_opts_parse(olist, optarg, 1);
2566                if (!opts) {
2567                    fprintf(stderr, "parse error: %s\n", optarg);
2568                    exit(1);
2569                }
2570                break;
2571            case QEMU_OPTION_virtfs: {
2572                QemuOpts *fsdev;
2573                QemuOpts *device;
2574
2575                olist = qemu_find_opts("virtfs");
2576                if (!olist) {
2577                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");
2578                    exit(1);
2579                }
2580                opts = qemu_opts_parse(olist, optarg, 1);
2581                if (!opts) {
2582                    fprintf(stderr, "parse error: %s\n", optarg);
2583                    exit(1);
2584                }
2585
2586                if (qemu_opt_get(opts, "fstype") == NULL ||
2587                        qemu_opt_get(opts, "mount_tag") == NULL ||
2588                        qemu_opt_get(opts, "path") == NULL ||
2589                        qemu_opt_get(opts, "security_model") == NULL) {
2590                    fprintf(stderr, "Usage: -virtfs fstype,path=/share_path/,"
2591                            "security_model=[mapped|passthrough|none],"
2592                            "mount_tag=tag.\n");
2593                    exit(1);
2594                }
2595
2596                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
2597                                         qemu_opt_get(opts, "mount_tag"), 1);
2598                if (!fsdev) {
2599                    fprintf(stderr, "duplicate fsdev id: %s\n",
2600                            qemu_opt_get(opts, "mount_tag"));
2601                    exit(1);
2602                }
2603                qemu_opt_set(fsdev, "fstype", qemu_opt_get(opts, "fstype"));
2604                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
2605                qemu_opt_set(fsdev, "security_model",
2606                             qemu_opt_get(opts, "security_model"));
2607
2608                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2609                qemu_opt_set(device, "driver", "virtio-9p-pci");
2610                qemu_opt_set(device, "fsdev",
2611                             qemu_opt_get(opts, "mount_tag"));
2612                qemu_opt_set(device, "mount_tag",
2613                             qemu_opt_get(opts, "mount_tag"));
2614                break;
2615            }
2616            case QEMU_OPTION_serial:
2617                add_device_config(DEV_SERIAL, optarg);
2618                default_serial = 0;
2619                if (strncmp(optarg, "mon:", 4) == 0) {
2620                    default_monitor = 0;
2621                }
2622                break;
2623            case QEMU_OPTION_watchdog:
2624                if (watchdog) {
2625                    fprintf(stderr,
2626                            "qemu: only one watchdog option may be given\n");
2627                    return 1;
2628                }
2629                watchdog = optarg;
2630                break;
2631            case QEMU_OPTION_watchdog_action:
2632                if (select_watchdog_action(optarg) == -1) {
2633                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
2634                    exit(1);
2635                }
2636                break;
2637            case QEMU_OPTION_virtiocon:
2638                add_device_config(DEV_VIRTCON, optarg);
2639                default_virtcon = 0;
2640                if (strncmp(optarg, "mon:", 4) == 0) {
2641                    default_monitor = 0;
2642                }
2643                break;
2644            case QEMU_OPTION_parallel:
2645                add_device_config(DEV_PARALLEL, optarg);
2646                default_parallel = 0;
2647                if (strncmp(optarg, "mon:", 4) == 0) {
2648                    default_monitor = 0;
2649                }
2650                break;
2651            case QEMU_OPTION_debugcon:
2652                add_device_config(DEV_DEBUGCON, optarg);
2653                break;
2654            case QEMU_OPTION_loadvm:
2655                loadvm = optarg;
2656                break;
2657            case QEMU_OPTION_full_screen:
2658                full_screen = 1;
2659                break;
2660#ifdef CONFIG_SDL
2661            case QEMU_OPTION_no_frame:
2662                no_frame = 1;
2663                break;
2664            case QEMU_OPTION_alt_grab:
2665                alt_grab = 1;
2666                break;
2667            case QEMU_OPTION_ctrl_grab:
2668                ctrl_grab = 1;
2669                break;
2670            case QEMU_OPTION_no_quit:
2671                no_quit = 1;
2672                break;
2673            case QEMU_OPTION_sdl:
2674                display_type = DT_SDL;
2675                break;
2676#else
2677            case QEMU_OPTION_no_frame:
2678            case QEMU_OPTION_alt_grab:
2679            case QEMU_OPTION_ctrl_grab:
2680            case QEMU_OPTION_no_quit:
2681            case QEMU_OPTION_sdl:
2682                fprintf(stderr, "SDL support is disabled\n");
2683                exit(1);
2684#endif
2685            case QEMU_OPTION_pidfile:
2686                pid_file = optarg;
2687                break;
2688            case QEMU_OPTION_win2k_hack:
2689                win2k_install_hack = 1;
2690                break;
2691            case QEMU_OPTION_rtc_td_hack:
2692                rtc_td_hack = 1;
2693                break;
2694            case QEMU_OPTION_acpitable:
2695                do_acpitable_option(optarg);
2696                break;
2697            case QEMU_OPTION_smbios:
2698                do_smbios_option(optarg);
2699                break;
2700            case QEMU_OPTION_enable_kvm:
2701                olist = qemu_find_opts("machine");
2702                qemu_opts_reset(olist);
2703                qemu_opts_parse(olist, "accel=kvm", 0);
2704                break;
2705            case QEMU_OPTION_machine:
2706                olist = qemu_find_opts("machine");
2707                qemu_opts_reset(olist);
2708                opts = qemu_opts_parse(olist, optarg, 1);
2709                if (!opts) {
2710                    fprintf(stderr, "parse error: %s\n", optarg);
2711                    exit(1);
2712                }
2713                machine = machine_parse(qemu_opt_get(opts, "type"));
2714                break;
2715            case QEMU_OPTION_usb:
2716                usb_enabled = 1;
2717                break;
2718            case QEMU_OPTION_usbdevice:
2719                usb_enabled = 1;
2720                add_device_config(DEV_USB, optarg);
2721                break;
2722            case QEMU_OPTION_device:
2723                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
2724                    exit(1);
2725                }
2726                break;
2727            case QEMU_OPTION_smp:
2728                smp_parse(optarg);
2729                if (smp_cpus < 1) {
2730                    fprintf(stderr, "Invalid number of CPUs\n");
2731                    exit(1);
2732                }
2733                if (max_cpus < smp_cpus) {
2734                    fprintf(stderr, "maxcpus must be equal to or greater than "
2735                            "smp\n");
2736                    exit(1);
2737                }
2738                if (max_cpus > 255) {
2739                    fprintf(stderr, "Unsupported number of maxcpus\n");
2740                    exit(1);
2741                }
2742                break;
2743            case QEMU_OPTION_vnc:
2744#ifdef CONFIG_VNC
2745                display_remote++;
2746                vnc_display = optarg;
2747#else
2748                fprintf(stderr, "VNC support is disabled\n");
2749                exit(1);
2750#endif
2751                break;
2752            case QEMU_OPTION_no_acpi:
2753                acpi_enabled = 0;
2754                break;
2755            case QEMU_OPTION_no_hpet:
2756                no_hpet = 1;
2757                break;
2758            case QEMU_OPTION_balloon:
2759                if (balloon_parse(optarg) < 0) {
2760                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
2761                    exit(1);
2762                }
2763                break;
2764            case QEMU_OPTION_no_reboot:
2765                no_reboot = 1;
2766                break;
2767            case QEMU_OPTION_no_shutdown:
2768                no_shutdown = 1;
2769                break;
2770            case QEMU_OPTION_show_cursor:
2771                cursor_hide = 0;
2772                break;
2773            case QEMU_OPTION_uuid:
2774                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
2775                    fprintf(stderr, "Fail to parse UUID string."
2776                            " Wrong format.\n");
2777                    exit(1);
2778                }
2779                break;
2780            case QEMU_OPTION_option_rom:
2781                if (nb_option_roms >= MAX_OPTION_ROMS) {
2782                    fprintf(stderr, "Too many option ROMs\n");
2783                    exit(1);
2784                }
2785                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
2786                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
2787                option_rom[nb_option_roms].bootindex =
2788                    qemu_opt_get_number(opts, "bootindex", -1);
2789                if (!option_rom[nb_option_roms].name) {
2790                    fprintf(stderr, "Option ROM file is not specified\n");
2791                    exit(1);
2792                }
2793                nb_option_roms++;
2794                break;
2795            case QEMU_OPTION_semihosting:
2796                semihosting_enabled = 1;
2797                break;
2798            case QEMU_OPTION_name:
2799                qemu_name = qemu_strdup(optarg);
2800                 {
2801                     char *p = strchr(qemu_name, ',');
2802                     if (p != NULL) {
2803                        *p++ = 0;
2804                        if (strncmp(p, "process=", 8)) {
2805                            fprintf(stderr, "Unknown subargument %s to -name\n", p);
2806                            exit(1);
2807                        }
2808                        p += 8;
2809                        os_set_proc_name(p);
2810                     }  
2811                 }      
2812                break;
2813            case QEMU_OPTION_prom_env:
2814                if (nb_prom_envs >= MAX_PROM_ENVS) {
2815                    fprintf(stderr, "Too many prom variables\n");
2816                    exit(1);
2817                }
2818                prom_envs[nb_prom_envs] = optarg;
2819                nb_prom_envs++;
2820                break;
2821            case QEMU_OPTION_old_param:
2822                old_param = 1;
2823                break;
2824            case QEMU_OPTION_clock:
2825                configure_alarms(optarg);
2826                break;
2827            case QEMU_OPTION_startdate:
2828                configure_rtc_date_offset(optarg, 1);
2829                break;
2830            case QEMU_OPTION_rtc:
2831                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
2832                if (!opts) {
2833                    exit(1);
2834                }
2835                configure_rtc(opts);
2836                break;
2837            case QEMU_OPTION_tb_size:
2838                tb_size = strtol(optarg, NULL, 0);
2839                if (tb_size < 0)
2840                    tb_size = 0;
2841                break;
2842            case QEMU_OPTION_icount:
2843                icount_option = optarg;
2844                break;
2845            case QEMU_OPTION_incoming:
2846                incoming = optarg;
2847                incoming_expected = true;
2848                break;
2849            case QEMU_OPTION_nodefaults:
2850                default_serial = 0;
2851                default_parallel = 0;
2852                default_virtcon = 0;
2853                default_monitor = 0;
2854                default_vga = 0;
2855                default_net = 0;
2856                default_floppy = 0;
2857                default_cdrom = 0;
2858                default_sdcard = 0;
2859                break;
2860            case QEMU_OPTION_xen_domid:
2861                if (!(xen_available())) {
2862                    printf("Option %s not supported for this target\n", popt->name);
2863                    exit(1);
2864                }
2865                xen_domid = atoi(optarg);
2866                break;
2867            case QEMU_OPTION_xen_create:
2868                if (!(xen_available())) {
2869                    printf("Option %s not supported for this target\n", popt->name);
2870                    exit(1);
2871                }
2872                xen_mode = XEN_CREATE;
2873                break;
2874            case QEMU_OPTION_xen_attach:
2875                if (!(xen_available())) {
2876                    printf("Option %s not supported for this target\n", popt->name);
2877                    exit(1);
2878                }
2879                xen_mode = XEN_ATTACH;
2880                break;
2881#ifdef CONFIG_SIMPLE_TRACE
2882            case QEMU_OPTION_trace:
2883                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
2884                if (opts) {
2885                    trace_file = qemu_opt_get(opts, "file");
2886                }
2887                break;
2888#endif
2889            case QEMU_OPTION_readconfig:
2890                {
2891                    int ret = qemu_read_config_file(optarg);
2892                    if (ret < 0) {
2893                        fprintf(stderr, "read config %s: %s\n", optarg,
2894                            strerror(-ret));
2895                        exit(1);
2896                    }
2897                    break;
2898                }
2899            case QEMU_OPTION_spice:
2900                olist = qemu_find_opts("spice");
2901                if (!olist) {
2902                    fprintf(stderr, "spice is not supported by this qemu build.\n");
2903                    exit(1);
2904                }
2905                opts = qemu_opts_parse(olist, optarg, 0);
2906                if (!opts) {
2907                    fprintf(stderr, "parse error: %s\n", optarg);
2908                    exit(1);
2909                }
2910                break;
2911            case QEMU_OPTION_writeconfig:
2912                {
2913                    FILE *fp;
2914                    if (strcmp(optarg, "-") == 0) {
2915                        fp = stdout;
2916                    } else {
2917                        fp = fopen(optarg, "w");
2918                        if (fp == NULL) {
2919                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
2920                            exit(1);
2921                        }
2922                    }
2923                    qemu_config_write(fp);
2924                    fclose(fp);
2925                    break;
2926                }
2927            default:
2928                os_parse_cmd_args(popt->index, optarg);
2929            }
2930        }
2931    }
2932    loc_set_none();
2933
2934    /* Open the logfile at this point, if necessary. We can't open the logfile
2935     * when encountering either of the logging options (-d or -D) because the
2936     * other one may be encountered later on the command line, changing the
2937     * location or level of logging.
2938     */
2939    if (log_mask) {
2940        if (log_file) {
2941            set_cpu_log_filename(log_file);
2942        }
2943        set_cpu_log(log_mask);
2944    }
2945
2946    if (!st_init(trace_file)) {
2947        fprintf(stderr, "warning: unable to initialize simple trace backend\n");
2948    }
2949
2950    /* If no data_dir is specified then try to find it relative to the
2951       executable path.  */
2952    if (!data_dir) {
2953        data_dir = os_find_datadir(argv[0]);
2954    }
2955    /* If all else fails use the install patch specified when building.  */
2956    if (!data_dir) {
2957        data_dir = CONFIG_QEMU_DATADIR;
2958    }
2959
2960    /*
2961     * Default to max_cpus = smp_cpus, in case the user doesn't
2962     * specify a max_cpus value.
2963     */
2964    if (!max_cpus)
2965        max_cpus = smp_cpus;
2966
2967    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
2968    if (smp_cpus > machine->max_cpus) {
2969        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
2970                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
2971                machine->max_cpus);
2972        exit(1);
2973    }
2974
2975    /*
2976     * Get the default machine options from the machine if it is not already
2977     * specified either by the configuration file or by the command line.
2978     */
2979    if (machine->default_machine_opts) {
2980        QemuOptsList *list = qemu_find_opts("machine");
2981        const char *p = NULL;
2982
2983        if (!QTAILQ_EMPTY(&list->head)) {
2984            p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2985        }
2986        if (p == NULL) {
2987            qemu_opts_reset(list);
2988            opts = qemu_opts_parse(list, machine->default_machine_opts, 0);
2989            if (!opts) {
2990                fprintf(stderr, "parse error for machine %s: %s\n",
2991                        machine->name, machine->default_machine_opts);
2992                exit(1);
2993            }
2994        }
2995    }
2996
2997    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
2998    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
2999
3000    if (machine->no_serial) {
3001        default_serial = 0;
3002    }
3003    if (machine->no_parallel) {
3004        default_parallel = 0;
3005    }
3006    if (!machine->use_virtcon) {
3007        default_virtcon = 0;
3008    }
3009    if (machine->no_vga) {
3010        default_vga = 0;
3011    }
3012    if (machine->no_floppy) {
3013        default_floppy = 0;
3014    }
3015    if (machine->no_cdrom) {
3016        default_cdrom = 0;
3017    }
3018    if (machine->no_sdcard) {
3019        default_sdcard = 0;
3020    }
3021
3022    if (display_type == DT_NOGRAPHIC) {
3023        if (default_parallel)
3024            add_device_config(DEV_PARALLEL, "null");
3025        if (default_serial && default_monitor) {
3026            add_device_config(DEV_SERIAL, "mon:stdio");
3027        } else if (default_virtcon && default_monitor) {
3028            add_device_config(DEV_VIRTCON, "mon:stdio");
3029        } else {
3030            if (default_serial)
3031                add_device_config(DEV_SERIAL, "stdio");
3032            if (default_virtcon)
3033                add_device_config(DEV_VIRTCON, "stdio");
3034            if (default_monitor)
3035                monitor_parse("stdio", "readline");
3036        }
3037    } else {
3038        if (default_serial)
3039            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3040        if (default_parallel)
3041            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3042        if (default_monitor)
3043            monitor_parse("vc:80Cx24C", "readline");
3044        if (default_virtcon)
3045            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3046    }
3047    if (default_vga)
3048        vga_interface_type = VGA_CIRRUS;
3049
3050    socket_init();
3051
3052    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3053        exit(1);
3054#ifdef CONFIG_VIRTFS
3055    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3056        exit(1);
3057    }
3058#endif
3059
3060    os_daemonize();
3061
3062    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3063        os_pidfile_error();
3064        exit(1);
3065    }
3066
3067    configure_accelerator();
3068
3069    if (qemu_init_main_loop()) {
3070        fprintf(stderr, "qemu_init_main_loop failed\n");
3071        exit(1);
3072    }
3073    linux_boot = (kernel_filename != NULL);
3074
3075    if (!linux_boot && *kernel_cmdline != '\0') {
3076        fprintf(stderr, "-append only allowed with -kernel option\n");
3077        exit(1);
3078    }
3079
3080    if (!linux_boot && initrd_filename != NULL) {
3081        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3082        exit(1);
3083    }
3084
3085    os_set_line_buffering();
3086
3087    if (init_timer_alarm() < 0) {
3088        fprintf(stderr, "could not initialize alarm timer\n");
3089        exit(1);
3090    }
3091    configure_icount(icount_option);
3092
3093    if (net_init_clients() < 0) {
3094        exit(1);
3095    }
3096
3097    /* init the bluetooth world */
3098    if (foreach_device_config(DEV_BT, bt_parse))
3099        exit(1);
3100
3101    /* init the memory */
3102    if (ram_size == 0)
3103        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3104
3105    /* init the dynamic translator */
3106    cpu_exec_init_all(tb_size * 1024 * 1024);
3107
3108    bdrv_init_with_whitelist();
3109
3110    blk_mig_init();
3111
3112    /* open the virtual block devices */
3113    if (snapshot)
3114        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
3115    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
3116        exit(1);
3117
3118    default_drive(default_cdrom, snapshot, machine->use_scsi,
3119                  IF_DEFAULT, 2, CDROM_OPTS);
3120    default_drive(default_floppy, snapshot, machine->use_scsi,
3121                  IF_FLOPPY, 0, FD_OPTS);
3122    default_drive(default_sdcard, snapshot, machine->use_scsi,
3123                  IF_SD, 0, SD_OPTS);
3124
3125    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
3126                         ram_load, NULL);
3127
3128    if (nb_numa_nodes > 0) {
3129        int i;
3130
3131        if (nb_numa_nodes > MAX_NODES) {
3132            nb_numa_nodes = MAX_NODES;
3133        }
3134
3135        /* If no memory size if given for any node, assume the default case
3136         * and distribute the available memory equally across all nodes
3137         */
3138        for (i = 0; i < nb_numa_nodes; i++) {
3139            if (node_mem[i] != 0)
3140                break;
3141        }
3142        if (i == nb_numa_nodes) {
3143            uint64_t usedmem = 0;
3144
3145            /* On Linux, the each node's border has to be 8MB aligned,
3146             * the final node gets the rest.
3147             */
3148            for (i = 0; i < nb_numa_nodes - 1; i++) {
3149                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3150                usedmem += node_mem[i];
3151            }
3152            node_mem[i] = ram_size - usedmem;
3153        }
3154
3155        for (i = 0; i < nb_numa_nodes; i++) {
3156            if (node_cpumask[i] != 0)
3157                break;
3158        }
3159        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3160         * must cope with this anyway, because there are BIOSes out there in
3161         * real machines which also use this scheme.
3162         */
3163        if (i == nb_numa_nodes) {
3164            for (i = 0; i < smp_cpus; i++) {
3165                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3166            }
3167        }
3168    }
3169
3170    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3171        exit(1);
3172    }
3173
3174    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3175        exit(1);
3176    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3177        exit(1);
3178    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3179        exit(1);
3180    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3181        exit(1);
3182
3183    module_call_init(MODULE_INIT_DEVICE);
3184
3185    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)
3186        exit(0);
3187
3188    if (watchdog) {
3189        i = select_watchdog(watchdog);
3190        if (i > 0)
3191            exit (i == 1 ? 1 : 0);
3192    }
3193
3194    if (machine->compat_props) {
3195        qdev_prop_register_global_list(machine->compat_props);
3196    }
3197    qemu_add_globals();
3198
3199    machine->init(ram_size, boot_devices,
3200                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3201
3202    cpu_synchronize_all_post_init();
3203
3204    set_numa_modes();
3205
3206    current_machine = machine;
3207
3208    /* init USB devices */
3209    if (usb_enabled) {
3210        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3211            exit(1);
3212    }
3213
3214    /* init generic devices */
3215    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3216        exit(1);
3217
3218    net_check_clients();
3219
3220    /* just use the first displaystate for the moment */
3221    ds = get_displaystate();
3222
3223    if (using_spice)
3224        display_remote++;
3225    if (display_type == DT_DEFAULT && !display_remote) {
3226#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3227        display_type = DT_SDL;
3228#elif defined(CONFIG_VNC)
3229        vnc_display = "localhost:0,to=99";
3230        show_vnc_port = 1;
3231#else
3232        display_type = DT_NONE;
3233#endif
3234    }
3235
3236
3237    /* init local displays */
3238    switch (display_type) {
3239    case DT_NOGRAPHIC:
3240        break;
3241#if defined(CONFIG_CURSES)
3242    case DT_CURSES:
3243        curses_display_init(ds, full_screen);
3244        break;
3245#endif
3246#if defined(CONFIG_SDL)
3247    case DT_SDL:
3248        sdl_display_init(ds, full_screen, no_frame);
3249        break;
3250#elif defined(CONFIG_COCOA)
3251    case DT_SDL:
3252        cocoa_display_init(ds, full_screen);
3253        break;
3254#endif
3255    default:
3256        break;
3257    }
3258
3259    /* must be after terminal init, SDL library changes signal handlers */
3260    os_setup_signal_handling();
3261
3262#ifdef CONFIG_VNC
3263    /* init remote displays */
3264    if (vnc_display) {
3265        vnc_display_init(ds);
3266        if (vnc_display_open(ds, vnc_display) < 0)
3267            exit(1);
3268
3269        if (show_vnc_port) {
3270            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3271        }
3272    }
3273#endif
3274#ifdef CONFIG_SPICE
3275    if (using_spice && !qxl_enabled) {
3276        qemu_spice_display_init(ds);
3277    }
3278#endif
3279
3280    /* display setup */
3281    dpy_resize(ds);
3282    dcl = ds->listeners;
3283    while (dcl != NULL) {
3284        if (dcl->dpy_refresh != NULL) {
3285            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3286            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3287            break;
3288        }
3289        dcl = dcl->next;
3290    }
3291    if (ds->gui_timer == NULL) {
3292        nographic_timer = qemu_new_timer_ms(rt_clock, nographic_update, NULL);
3293        qemu_mod_timer(nographic_timer, qemu_get_clock_ms(rt_clock));
3294    }
3295    text_consoles_set_display(ds);
3296
3297    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3298        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3299                gdbstub_dev);
3300        exit(1);
3301    }
3302
3303    qdev_machine_creation_done();
3304
3305    if (rom_load_all() != 0) {
3306        fprintf(stderr, "rom loading failed\n");
3307        exit(1);
3308    }
3309
3310    /* TODO: once all bus devices are qdevified, this should be done
3311     * when bus is created by qdev.c */
3312    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3313    qemu_run_machine_init_done_notifiers();
3314
3315    qemu_system_reset(VMRESET_SILENT);
3316    if (loadvm) {
3317        if (load_vmstate(loadvm) < 0) {
3318            autostart = 0;
3319        }
3320    }
3321
3322    if (incoming) {
3323        int ret = qemu_start_incoming_migration(incoming);
3324        if (ret < 0) {
3325            fprintf(stderr, "Migration failed. Exit code %s(%d), exiting.\n",
3326                    incoming, ret);
3327            exit(ret);
3328        }
3329    } else if (autostart) {
3330        vm_start();
3331    }
3332
3333    os_setup_post();
3334
3335    main_loop();
3336    quit_timers();
3337    net_cleanup();
3338
3339    return 0;
3340}
3341