Home | History | Annotate | Download | only in qemu
      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 <pwd.h>
     38 #include <sys/times.h>
     39 #include <sys/wait.h>
     40 #include <termios.h>
     41 #include <sys/mman.h>
     42 #include <sys/ioctl.h>
     43 #include <sys/resource.h>
     44 #include <sys/socket.h>
     45 #include <netinet/in.h>
     46 #include <net/if.h>
     47 #if defined(__NetBSD__)
     48 #include <net/if_tap.h>
     49 #endif
     50 #ifdef __linux__
     51 #include <linux/if_tun.h>
     52 #endif
     53 #include <arpa/inet.h>
     54 #include <dirent.h>
     55 #include <netdb.h>
     56 #include <sys/select.h>
     57 #ifdef CONFIG_BSD
     58 #include <sys/stat.h>
     59 #if defined(__FreeBSD__) || defined(__DragonFly__)
     60 #include <libutil.h>
     61 #else
     62 #include <util.h>
     63 #endif
     64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
     65 #include <freebsd/stdlib.h>
     66 #else
     67 #ifdef __linux__
     68 #include <pty.h>
     69 #include <malloc.h>
     70 #include <linux/rtc.h>
     71 
     72 /* For the benefit of older linux systems which don't supply it,
     73    we use a local copy of hpet.h. */
     74 /* #include <linux/hpet.h> */
     75 #include "hpet.h"
     76 
     77 #include <linux/ppdev.h>
     78 #include <linux/parport.h>
     79 #endif
     80 #ifdef __sun__
     81 #include <sys/stat.h>
     82 #include <sys/ethernet.h>
     83 #include <sys/sockio.h>
     84 #include <netinet/arp.h>
     85 #include <netinet/in.h>
     86 #include <netinet/in_systm.h>
     87 #include <netinet/ip.h>
     88 #include <netinet/ip_icmp.h> // must come after ip.h
     89 #include <netinet/udp.h>
     90 #include <netinet/tcp.h>
     91 #include <net/if.h>
     92 #include <syslog.h>
     93 #include <stropts.h>
     94 #endif
     95 #endif
     96 #endif
     97 
     98 #if defined(__OpenBSD__)
     99 #include <util.h>
    100 #endif
    101 
    102 #if defined(CONFIG_VDE)
    103 #include <libvdeplug.h>
    104 #endif
    105 
    106 #ifdef _WIN32
    107 #include <windows.h>
    108 #include <malloc.h>
    109 #include <sys/timeb.h>
    110 #include <mmsystem.h>
    111 #define getopt_long_only getopt_long
    112 #define memalign(align, size) malloc(size)
    113 #endif
    114 
    115 #ifdef CONFIG_SDL
    116 #ifdef __APPLE__
    117 #include <SDL.h>
    118 int qemu_main(int argc, char **argv, char **envp);
    119 int main(int argc, char **argv)
    120 {
    121     qemu_main(argc, argv, NULL);
    122 }
    123 #undef main
    124 #define main qemu_main
    125 #endif
    126 #endif /* CONFIG_SDL */
    127 
    128 #ifdef CONFIG_COCOA
    129 #undef main
    130 #define main qemu_main
    131 #endif /* CONFIG_COCOA */
    132 
    133 #include "hw/hw.h"
    134 #include "hw/boards.h"
    135 #include "hw/usb.h"
    136 #include "hw/pcmcia.h"
    137 #include "hw/pc.h"
    138 #include "hw/audiodev.h"
    139 #include "hw/isa.h"
    140 #include "hw/baum.h"
    141 #include "hw/bt.h"
    142 #include "hw/watchdog.h"
    143 #include "hw/smbios.h"
    144 #include "hw/xen.h"
    145 #include "bt-host.h"
    146 #include "net.h"
    147 #include "monitor.h"
    148 #include "console.h"
    149 #include "sysemu.h"
    150 #include "gdbstub.h"
    151 #include "qemu-timer.h"
    152 #include "qemu-char.h"
    153 #include "cache-utils.h"
    154 #include "block.h"
    155 #include "dma.h"
    156 #include "audio/audio.h"
    157 #include "migration.h"
    158 #include "kvm.h"
    159 #include "balloon.h"
    160 #include "qemu-option.h"
    161 
    162 #include "disas.h"
    163 
    164 #include "exec-all.h"
    165 
    166 #include "qemu_socket.h"
    167 
    168 #if defined(CONFIG_SLIRP)
    169 #include "libslirp.h"
    170 #endif
    171 
    172 //#define DEBUG_UNUSED_IOPORT
    173 //#define DEBUG_IOPORT
    174 //#define DEBUG_NET
    175 //#define DEBUG_SLIRP
    176 
    177 
    178 #ifdef DEBUG_IOPORT
    179 #  define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
    180 #else
    181 #  define LOG_IOPORT(...) do { } while (0)
    182 #endif
    183 
    184 #define DEFAULT_RAM_SIZE 128
    185 
    186 /* Max number of USB devices that can be specified on the commandline.  */
    187 #define MAX_USB_CMDLINE 8
    188 
    189 /* Max number of bluetooth switches on the commandline.  */
    190 #define MAX_BT_CMDLINE 10
    191 
    192 /* XXX: use a two level table to limit memory usage */
    193 #define MAX_IOPORTS 65536
    194 
    195 static const char *data_dir;
    196 const char *bios_name = NULL;
    197 static void *ioport_opaque[MAX_IOPORTS];
    198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
    199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
    200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
    201    to store the VM snapshots */
    202 DriveInfo drives_table[MAX_DRIVES+1];
    203 int nb_drives;
    204 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
    205 static DisplayState *display_state;
    206 DisplayType display_type = DT_DEFAULT;
    207 const char* keyboard_layout = NULL;
    208 ram_addr_t ram_size;
    209 int nb_nics;
    210 NICInfo nd_table[MAX_NICS];
    211 int vm_running;
    212 static int autostart;
    213 static int rtc_utc = 1;
    214 static int rtc_date_offset = -1; /* -1 means no change */
    215 int cirrus_vga_enabled = 1;
    216 int std_vga_enabled = 0;
    217 int vmsvga_enabled = 0;
    218 int xenfb_enabled = 0;
    219 QEMUClock *rtc_clock;
    220 #ifdef TARGET_SPARC
    221 int graphic_width = 1024;
    222 int graphic_height = 768;
    223 int graphic_depth = 8;
    224 #else
    225 int graphic_width = 800;
    226 int graphic_height = 600;
    227 int graphic_depth = 15;
    228 #endif
    229 static int full_screen = 0;
    230 #ifdef CONFIG_SDL
    231 static int no_frame = 0;
    232 #endif
    233 int no_quit = 0;
    234 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
    235 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
    236 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
    237 #ifdef TARGET_I386
    238 int win2k_install_hack = 0;
    239 int rtc_td_hack = 0;
    240 #endif
    241 int usb_enabled = 0;
    242 int singlestep = 0;
    243 int smp_cpus = 1;
    244 const char *vnc_display;
    245 int acpi_enabled = 1;
    246 int no_hpet = 0;
    247 int no_virtio_balloon = 0;
    248 int fd_bootchk = 1;
    249 int no_reboot = 0;
    250 int no_shutdown = 0;
    251 int cursor_hide = 1;
    252 int graphic_rotate = 0;
    253 #ifndef _WIN32
    254 int daemonize = 0;
    255 #endif
    256 WatchdogTimerModel *watchdog = NULL;
    257 int watchdog_action = WDT_RESET;
    258 const char *option_rom[MAX_OPTION_ROMS];
    259 int nb_option_roms;
    260 int semihosting_enabled = 0;
    261 #ifdef TARGET_ARM
    262 int old_param = 0;
    263 #endif
    264 const char *qemu_name;
    265 int alt_grab = 0;
    266 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
    267 unsigned int nb_prom_envs = 0;
    268 const char *prom_envs[MAX_PROM_ENVS];
    269 #endif
    270 int nb_drives_opt;
    271 struct drive_opt drives_opt[MAX_DRIVES];
    272 
    273 int nb_numa_nodes;
    274 uint64_t node_mem[MAX_NODES];
    275 uint64_t node_cpumask[MAX_NODES];
    276 
    277 static CPUState *cur_cpu;
    278 static CPUState *next_cpu;
    279 static int timer_alarm_pending = 1;
    280 /* Conversion factor from emulated instructions to virtual clock ticks.  */
    281 static int icount_time_shift;
    282 /* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
    283 #define MAX_ICOUNT_SHIFT 10
    284 /* Compensate for varying guest execution speed.  */
    285 static int64_t qemu_icount_bias;
    286 static QEMUTimer *icount_rt_timer;
    287 static QEMUTimer *icount_vm_timer;
    288 static QEMUTimer *nographic_timer;
    289 
    290 uint8_t qemu_uuid[16];
    291 
    292 /***********************************************************/
    293 /* x86 ISA bus support */
    294 
    295 target_phys_addr_t isa_mem_base = 0;
    296 PicState2 *isa_pic;
    297 
    298 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
    299 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
    300 
    301 static uint32_t ioport_read(int index, uint32_t address)
    302 {
    303     static IOPortReadFunc *default_func[3] = {
    304         default_ioport_readb,
    305         default_ioport_readw,
    306         default_ioport_readl
    307     };
    308     IOPortReadFunc *func = ioport_read_table[index][address];
    309     if (!func)
    310         func = default_func[index];
    311     return func(ioport_opaque[address], address);
    312 }
    313 
    314 static void ioport_write(int index, uint32_t address, uint32_t data)
    315 {
    316     static IOPortWriteFunc *default_func[3] = {
    317         default_ioport_writeb,
    318         default_ioport_writew,
    319         default_ioport_writel
    320     };
    321     IOPortWriteFunc *func = ioport_write_table[index][address];
    322     if (!func)
    323         func = default_func[index];
    324     func(ioport_opaque[address], address, data);
    325 }
    326 
    327 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
    328 {
    329 #ifdef DEBUG_UNUSED_IOPORT
    330     fprintf(stderr, "unused inb: port=0x%04x\n", address);
    331 #endif
    332     return 0xff;
    333 }
    334 
    335 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
    336 {
    337 #ifdef DEBUG_UNUSED_IOPORT
    338     fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
    339 #endif
    340 }
    341 
    342 /* default is to make two byte accesses */
    343 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
    344 {
    345     uint32_t data;
    346     data = ioport_read(0, address);
    347     address = (address + 1) & (MAX_IOPORTS - 1);
    348     data |= ioport_read(0, address) << 8;
    349     return data;
    350 }
    351 
    352 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
    353 {
    354     ioport_write(0, address, data & 0xff);
    355     address = (address + 1) & (MAX_IOPORTS - 1);
    356     ioport_write(0, address, (data >> 8) & 0xff);
    357 }
    358 
    359 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
    360 {
    361 #ifdef DEBUG_UNUSED_IOPORT
    362     fprintf(stderr, "unused inl: port=0x%04x\n", address);
    363 #endif
    364     return 0xffffffff;
    365 }
    366 
    367 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
    368 {
    369 #ifdef DEBUG_UNUSED_IOPORT
    370     fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
    371 #endif
    372 }
    373 
    374 /* size is the word size in byte */
    375 int register_ioport_read(int start, int length, int size,
    376                          IOPortReadFunc *func, void *opaque)
    377 {
    378     int i, bsize;
    379 
    380     if (size == 1) {
    381         bsize = 0;
    382     } else if (size == 2) {
    383         bsize = 1;
    384     } else if (size == 4) {
    385         bsize = 2;
    386     } else {
    387         hw_error("register_ioport_read: invalid size");
    388         return -1;
    389     }
    390     for(i = start; i < start + length; i += size) {
    391         ioport_read_table[bsize][i] = func;
    392         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
    393             hw_error("register_ioport_read: invalid opaque");
    394         ioport_opaque[i] = opaque;
    395     }
    396     return 0;
    397 }
    398 
    399 /* size is the word size in byte */
    400 int register_ioport_write(int start, int length, int size,
    401                           IOPortWriteFunc *func, void *opaque)
    402 {
    403     int i, bsize;
    404 
    405     if (size == 1) {
    406         bsize = 0;
    407     } else if (size == 2) {
    408         bsize = 1;
    409     } else if (size == 4) {
    410         bsize = 2;
    411     } else {
    412         hw_error("register_ioport_write: invalid size");
    413         return -1;
    414     }
    415     for(i = start; i < start + length; i += size) {
    416         ioport_write_table[bsize][i] = func;
    417         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
    418             hw_error("register_ioport_write: invalid opaque");
    419         ioport_opaque[i] = opaque;
    420     }
    421     return 0;
    422 }
    423 
    424 void isa_unassign_ioport(int start, int length)
    425 {
    426     int i;
    427 
    428     for(i = start; i < start + length; i++) {
    429         ioport_read_table[0][i] = default_ioport_readb;
    430         ioport_read_table[1][i] = default_ioport_readw;
    431         ioport_read_table[2][i] = default_ioport_readl;
    432 
    433         ioport_write_table[0][i] = default_ioport_writeb;
    434         ioport_write_table[1][i] = default_ioport_writew;
    435         ioport_write_table[2][i] = default_ioport_writel;
    436 
    437         ioport_opaque[i] = NULL;
    438     }
    439 }
    440 
    441 /***********************************************************/
    442 
    443 void cpu_outb(CPUState *env, int addr, int val)
    444 {
    445     LOG_IOPORT("outb: %04x %02x\n", addr, val);
    446     ioport_write(0, addr, val);
    447 #ifdef CONFIG_KQEMU
    448     if (env)
    449         env->last_io_time = cpu_get_time_fast();
    450 #endif
    451 }
    452 
    453 void cpu_outw(CPUState *env, int addr, int val)
    454 {
    455     LOG_IOPORT("outw: %04x %04x\n", addr, val);
    456     ioport_write(1, addr, val);
    457 #ifdef CONFIG_KQEMU
    458     if (env)
    459         env->last_io_time = cpu_get_time_fast();
    460 #endif
    461 }
    462 
    463 void cpu_outl(CPUState *env, int addr, int val)
    464 {
    465     LOG_IOPORT("outl: %04x %08x\n", addr, val);
    466     ioport_write(2, addr, val);
    467 #ifdef CONFIG_KQEMU
    468     if (env)
    469         env->last_io_time = cpu_get_time_fast();
    470 #endif
    471 }
    472 
    473 int cpu_inb(CPUState *env, int addr)
    474 {
    475     int val;
    476     val = ioport_read(0, addr);
    477     LOG_IOPORT("inb : %04x %02x\n", addr, val);
    478 #ifdef CONFIG_KQEMU
    479     if (env)
    480         env->last_io_time = cpu_get_time_fast();
    481 #endif
    482     return val;
    483 }
    484 
    485 int cpu_inw(CPUState *env, int addr)
    486 {
    487     int val;
    488     val = ioport_read(1, addr);
    489     LOG_IOPORT("inw : %04x %04x\n", addr, val);
    490 #ifdef CONFIG_KQEMU
    491     if (env)
    492         env->last_io_time = cpu_get_time_fast();
    493 #endif
    494     return val;
    495 }
    496 
    497 int cpu_inl(CPUState *env, int addr)
    498 {
    499     int val;
    500     val = ioport_read(2, addr);
    501     LOG_IOPORT("inl : %04x %08x\n", addr, val);
    502 #ifdef CONFIG_KQEMU
    503     if (env)
    504         env->last_io_time = cpu_get_time_fast();
    505 #endif
    506     return val;
    507 }
    508 
    509 /***********************************************************/
    510 void hw_error(const char *fmt, ...)
    511 {
    512     va_list ap;
    513     CPUState *env;
    514 
    515     va_start(ap, fmt);
    516     fprintf(stderr, "qemu: hardware error: ");
    517     vfprintf(stderr, fmt, ap);
    518     fprintf(stderr, "\n");
    519     for(env = first_cpu; env != NULL; env = env->next_cpu) {
    520         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
    521 #ifdef TARGET_I386
    522         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
    523 #else
    524         cpu_dump_state(env, stderr, fprintf, 0);
    525 #endif
    526     }
    527     va_end(ap);
    528     abort();
    529 }
    530 
    531 static void set_proc_name(const char *s)
    532 {
    533 #if defined(__linux__) && defined(PR_SET_NAME)
    534     char name[16];
    535     if (!s)
    536         return;
    537     name[sizeof(name) - 1] = 0;
    538     strncpy(name, s, sizeof(name));
    539     /* Could rewrite argv[0] too, but that's a bit more complicated.
    540        This simple way is enough for `top'. */
    541     prctl(PR_SET_NAME, name);
    542 #endif
    543 }
    544 
    545 /***************/
    546 /* ballooning */
    547 
    548 static QEMUBalloonEvent *qemu_balloon_event;
    549 void *qemu_balloon_event_opaque;
    550 
    551 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
    552 {
    553     qemu_balloon_event = func;
    554     qemu_balloon_event_opaque = opaque;
    555 }
    556 
    557 void qemu_balloon(ram_addr_t target)
    558 {
    559     if (qemu_balloon_event)
    560         qemu_balloon_event(qemu_balloon_event_opaque, target);
    561 }
    562 
    563 ram_addr_t qemu_balloon_status(void)
    564 {
    565     if (qemu_balloon_event)
    566         return qemu_balloon_event(qemu_balloon_event_opaque, 0);
    567     return 0;
    568 }
    569 
    570 /***********************************************************/
    571 /* keyboard/mouse */
    572 
    573 static QEMUPutKBDEvent *qemu_put_kbd_event;
    574 static void *qemu_put_kbd_event_opaque;
    575 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
    576 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
    577 
    578 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
    579 {
    580     qemu_put_kbd_event_opaque = opaque;
    581     qemu_put_kbd_event = func;
    582 }
    583 
    584 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
    585                                                 void *opaque, int absolute,
    586                                                 const char *name)
    587 {
    588     QEMUPutMouseEntry *s, *cursor;
    589 
    590     s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
    591 
    592     s->qemu_put_mouse_event = func;
    593     s->qemu_put_mouse_event_opaque = opaque;
    594     s->qemu_put_mouse_event_absolute = absolute;
    595     s->qemu_put_mouse_event_name = qemu_strdup(name);
    596     s->next = NULL;
    597 
    598     if (!qemu_put_mouse_event_head) {
    599         qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
    600         return s;
    601     }
    602 
    603     cursor = qemu_put_mouse_event_head;
    604     while (cursor->next != NULL)
    605         cursor = cursor->next;
    606 
    607     cursor->next = s;
    608     qemu_put_mouse_event_current = s;
    609 
    610     return s;
    611 }
    612 
    613 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
    614 {
    615     QEMUPutMouseEntry *prev = NULL, *cursor;
    616 
    617     if (!qemu_put_mouse_event_head || entry == NULL)
    618         return;
    619 
    620     cursor = qemu_put_mouse_event_head;
    621     while (cursor != NULL && cursor != entry) {
    622         prev = cursor;
    623         cursor = cursor->next;
    624     }
    625 
    626     if (cursor == NULL) // does not exist or list empty
    627         return;
    628     else if (prev == NULL) { // entry is head
    629         qemu_put_mouse_event_head = cursor->next;
    630         if (qemu_put_mouse_event_current == entry)
    631             qemu_put_mouse_event_current = cursor->next;
    632         qemu_free(entry->qemu_put_mouse_event_name);
    633         qemu_free(entry);
    634         return;
    635     }
    636 
    637     prev->next = entry->next;
    638 
    639     if (qemu_put_mouse_event_current == entry)
    640         qemu_put_mouse_event_current = prev;
    641 
    642     qemu_free(entry->qemu_put_mouse_event_name);
    643     qemu_free(entry);
    644 }
    645 
    646 void kbd_put_keycode(int keycode)
    647 {
    648     if (qemu_put_kbd_event) {
    649         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
    650     }
    651 }
    652 
    653 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
    654 {
    655     QEMUPutMouseEvent *mouse_event;
    656     void *mouse_event_opaque;
    657     int width;
    658 
    659     if (!qemu_put_mouse_event_current) {
    660         return;
    661     }
    662 
    663     mouse_event =
    664         qemu_put_mouse_event_current->qemu_put_mouse_event;
    665     mouse_event_opaque =
    666         qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
    667 
    668     if (mouse_event) {
    669         if (graphic_rotate) {
    670             if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
    671                 width = 0x7fff;
    672             else
    673                 width = graphic_width - 1;
    674             mouse_event(mouse_event_opaque,
    675                                  width - dy, dx, dz, buttons_state);
    676         } else
    677             mouse_event(mouse_event_opaque,
    678                                  dx, dy, dz, buttons_state);
    679     }
    680 }
    681 
    682 int kbd_mouse_is_absolute(void)
    683 {
    684     if (!qemu_put_mouse_event_current)
    685         return 0;
    686 
    687     return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
    688 }
    689 
    690 void do_info_mice(Monitor *mon)
    691 {
    692     QEMUPutMouseEntry *cursor;
    693     int index = 0;
    694 
    695     if (!qemu_put_mouse_event_head) {
    696         monitor_printf(mon, "No mouse devices connected\n");
    697         return;
    698     }
    699 
    700     monitor_printf(mon, "Mouse devices available:\n");
    701     cursor = qemu_put_mouse_event_head;
    702     while (cursor != NULL) {
    703         monitor_printf(mon, "%c Mouse #%d: %s\n",
    704                        (cursor == qemu_put_mouse_event_current ? '*' : ' '),
    705                        index, cursor->qemu_put_mouse_event_name);
    706         index++;
    707         cursor = cursor->next;
    708     }
    709 }
    710 
    711 void do_mouse_set(Monitor *mon, int index)
    712 {
    713     QEMUPutMouseEntry *cursor;
    714     int i = 0;
    715 
    716     if (!qemu_put_mouse_event_head) {
    717         monitor_printf(mon, "No mouse devices connected\n");
    718         return;
    719     }
    720 
    721     cursor = qemu_put_mouse_event_head;
    722     while (cursor != NULL && index != i) {
    723         i++;
    724         cursor = cursor->next;
    725     }
    726 
    727     if (cursor != NULL)
    728         qemu_put_mouse_event_current = cursor;
    729     else
    730         monitor_printf(mon, "Mouse at given index not found\n");
    731 }
    732 
    733 /***********************************************************/
    734 /* real time host monotonic timer */
    735 
    736 /* compute with 96 bit intermediate result: (a*b)/c */
    737 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
    738 {
    739     union {
    740         uint64_t ll;
    741         struct {
    742 #ifdef HOST_WORDS_BIGENDIAN
    743             uint32_t high, low;
    744 #else
    745             uint32_t low, high;
    746 #endif
    747         } l;
    748     } u, res;
    749     uint64_t rl, rh;
    750 
    751     u.ll = a;
    752     rl = (uint64_t)u.l.low * (uint64_t)b;
    753     rh = (uint64_t)u.l.high * (uint64_t)b;
    754     rh += (rl >> 32);
    755     res.l.high = rh / c;
    756     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
    757     return res.ll;
    758 }
    759 
    760 static int64_t get_clock_realtime(void)
    761 {
    762     struct timeval tv;
    763 
    764     gettimeofday(&tv, NULL);
    765     return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
    766 }
    767 
    768 #ifdef WIN32
    769 
    770 static int64_t clock_freq;
    771 
    772 static void init_get_clock(void)
    773 {
    774     LARGE_INTEGER freq;
    775     int ret;
    776     ret = QueryPerformanceFrequency(&freq);
    777     if (ret == 0) {
    778         fprintf(stderr, "Could not calibrate ticks\n");
    779         exit(1);
    780     }
    781     clock_freq = freq.QuadPart;
    782 }
    783 
    784 static int64_t get_clock(void)
    785 {
    786     LARGE_INTEGER ti;
    787     QueryPerformanceCounter(&ti);
    788     return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
    789 }
    790 
    791 #else
    792 
    793 static int use_rt_clock;
    794 
    795 static void init_get_clock(void)
    796 {
    797     use_rt_clock = 0;
    798 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
    799     || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
    800     {
    801         struct timespec ts;
    802         if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
    803             use_rt_clock = 1;
    804         }
    805     }
    806 #endif
    807 }
    808 
    809 static int64_t get_clock(void)
    810 {
    811 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
    812 	|| defined(__DragonFly__) || defined(__FreeBSD_kernel__)
    813     if (use_rt_clock) {
    814         struct timespec ts;
    815         clock_gettime(CLOCK_MONOTONIC, &ts);
    816         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
    817     } else
    818 #endif
    819     {
    820         /* XXX: using gettimeofday leads to problems if the date
    821            changes, so it should be avoided. */
    822         return get_clock_realtime();
    823     }
    824 }
    825 #endif
    826 
    827 /* Return the virtual CPU time, based on the instruction counter.  */
    828 static int64_t cpu_get_icount(void)
    829 {
    830     int64_t icount;
    831     CPUState *env = cpu_single_env;;
    832     icount = qemu_icount;
    833     if (env) {
    834         if (!can_do_io(env))
    835             fprintf(stderr, "Bad clock read\n");
    836         icount -= (env->icount_decr.u16.low + env->icount_extra);
    837     }
    838     return qemu_icount_bias + (icount << icount_time_shift);
    839 }
    840 
    841 /***********************************************************/
    842 /* guest cycle counter */
    843 
    844 typedef struct TimersState {
    845     int64_t cpu_ticks_prev;
    846     int64_t cpu_ticks_offset;
    847     int64_t cpu_clock_offset;
    848     int32_t cpu_ticks_enabled;
    849     int64_t dummy;
    850 } TimersState;
    851 
    852 TimersState timers_state;
    853 
    854 /* return the host CPU cycle counter and handle stop/restart */
    855 int64_t cpu_get_ticks(void)
    856 {
    857     if (use_icount) {
    858         return cpu_get_icount();
    859     }
    860     if (!timers_state.cpu_ticks_enabled) {
    861         return timers_state.cpu_ticks_offset;
    862     } else {
    863         int64_t ticks;
    864         ticks = cpu_get_real_ticks();
    865         if (timers_state.cpu_ticks_prev > ticks) {
    866             /* Note: non increasing ticks may happen if the host uses
    867                software suspend */
    868             timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
    869         }
    870         timers_state.cpu_ticks_prev = ticks;
    871         return ticks + timers_state.cpu_ticks_offset;
    872     }
    873 }
    874 
    875 /* return the host CPU monotonic timer and handle stop/restart */
    876 static int64_t cpu_get_clock(void)
    877 {
    878     int64_t ti;
    879     if (!timers_state.cpu_ticks_enabled) {
    880         return timers_state.cpu_clock_offset;
    881     } else {
    882         ti = get_clock();
    883         return ti + timers_state.cpu_clock_offset;
    884     }
    885 }
    886 
    887 /* enable cpu_get_ticks() */
    888 void cpu_enable_ticks(void)
    889 {
    890     if (!timers_state.cpu_ticks_enabled) {
    891         timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
    892         timers_state.cpu_clock_offset -= get_clock();
    893         timers_state.cpu_ticks_enabled = 1;
    894     }
    895 }
    896 
    897 /* disable cpu_get_ticks() : the clock is stopped. You must not call
    898    cpu_get_ticks() after that.  */
    899 void cpu_disable_ticks(void)
    900 {
    901     if (timers_state.cpu_ticks_enabled) {
    902         timers_state.cpu_ticks_offset = cpu_get_ticks();
    903         timers_state.cpu_clock_offset = cpu_get_clock();
    904         timers_state.cpu_ticks_enabled = 0;
    905     }
    906 }
    907 
    908 /***********************************************************/
    909 /* timers */
    910 
    911 #define QEMU_CLOCK_REALTIME 0
    912 #define QEMU_CLOCK_VIRTUAL  1
    913 #define QEMU_CLOCK_HOST     2
    914 
    915 struct QEMUClock {
    916     int type;
    917     /* XXX: add frequency */
    918 };
    919 
    920 struct QEMUTimer {
    921     QEMUClock *clock;
    922     int64_t expire_time;
    923     QEMUTimerCB *cb;
    924     void *opaque;
    925     struct QEMUTimer *next;
    926 };
    927 
    928 struct qemu_alarm_timer {
    929     char const *name;
    930     unsigned int flags;
    931 
    932     int (*start)(struct qemu_alarm_timer *t);
    933     void (*stop)(struct qemu_alarm_timer *t);
    934     void (*rearm)(struct qemu_alarm_timer *t);
    935     void *priv;
    936 };
    937 
    938 #define ALARM_FLAG_DYNTICKS  0x1
    939 #define ALARM_FLAG_EXPIRED   0x2
    940 
    941 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
    942 {
    943     return t && (t->flags & ALARM_FLAG_DYNTICKS);
    944 }
    945 
    946 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
    947 {
    948     if (!alarm_has_dynticks(t))
    949         return;
    950 
    951     t->rearm(t);
    952 }
    953 
    954 /* TODO: MIN_TIMER_REARM_US should be optimized */
    955 #define MIN_TIMER_REARM_US 250
    956 
    957 static struct qemu_alarm_timer *alarm_timer;
    958 
    959 #ifdef _WIN32
    960 
    961 struct qemu_alarm_win32 {
    962     MMRESULT timerId;
    963     unsigned int period;
    964 } alarm_win32_data = {0, -1};
    965 
    966 static int win32_start_timer(struct qemu_alarm_timer *t);
    967 static void win32_stop_timer(struct qemu_alarm_timer *t);
    968 static void win32_rearm_timer(struct qemu_alarm_timer *t);
    969 
    970 #else
    971 
    972 static int unix_start_timer(struct qemu_alarm_timer *t);
    973 static void unix_stop_timer(struct qemu_alarm_timer *t);
    974 
    975 #ifdef __linux__
    976 
    977 static int dynticks_start_timer(struct qemu_alarm_timer *t);
    978 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
    979 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
    980 
    981 static int hpet_start_timer(struct qemu_alarm_timer *t);
    982 static void hpet_stop_timer(struct qemu_alarm_timer *t);
    983 
    984 static int rtc_start_timer(struct qemu_alarm_timer *t);
    985 static void rtc_stop_timer(struct qemu_alarm_timer *t);
    986 
    987 #endif /* __linux__ */
    988 
    989 #endif /* _WIN32 */
    990 
    991 /* Correlation between real and virtual time is always going to be
    992    fairly approximate, so ignore small variation.
    993    When the guest is idle real and virtual time will be aligned in
    994    the IO wait loop.  */
    995 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
    996 
    997 static void icount_adjust(void)
    998 {
    999     int64_t cur_time;
   1000     int64_t cur_icount;
   1001     int64_t delta;
   1002     static int64_t last_delta;
   1003     /* If the VM is not running, then do nothing.  */
   1004     if (!vm_running)
   1005         return;
   1006 
   1007     cur_time = cpu_get_clock();
   1008     cur_icount = qemu_get_clock(vm_clock);
   1009     delta = cur_icount - cur_time;
   1010     /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
   1011     if (delta > 0
   1012         && last_delta + ICOUNT_WOBBLE < delta * 2
   1013         && icount_time_shift > 0) {
   1014         /* The guest is getting too far ahead.  Slow time down.  */
   1015         icount_time_shift--;
   1016     }
   1017     if (delta < 0
   1018         && last_delta - ICOUNT_WOBBLE > delta * 2
   1019         && icount_time_shift < MAX_ICOUNT_SHIFT) {
   1020         /* The guest is getting too far behind.  Speed time up.  */
   1021         icount_time_shift++;
   1022     }
   1023     last_delta = delta;
   1024     qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
   1025 }
   1026 
   1027 static void icount_adjust_rt(void * opaque)
   1028 {
   1029     qemu_mod_timer(icount_rt_timer,
   1030                    qemu_get_clock(rt_clock) + 1000);
   1031     icount_adjust();
   1032 }
   1033 
   1034 static void icount_adjust_vm(void * opaque)
   1035 {
   1036     qemu_mod_timer(icount_vm_timer,
   1037                    qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
   1038     icount_adjust();
   1039 }
   1040 
   1041 static void init_icount_adjust(void)
   1042 {
   1043     /* Have both realtime and virtual time triggers for speed adjustment.
   1044        The realtime trigger catches emulated time passing too slowly,
   1045        the virtual time trigger catches emulated time passing too fast.
   1046        Realtime triggers occur even when idle, so use them less frequently
   1047        than VM triggers.  */
   1048     icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
   1049     qemu_mod_timer(icount_rt_timer,
   1050                    qemu_get_clock(rt_clock) + 1000);
   1051     icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
   1052     qemu_mod_timer(icount_vm_timer,
   1053                    qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
   1054 }
   1055 
   1056 static struct qemu_alarm_timer alarm_timers[] = {
   1057 #ifndef _WIN32
   1058 #ifdef __linux__
   1059     {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
   1060      dynticks_stop_timer, dynticks_rearm_timer, NULL},
   1061     /* HPET - if available - is preferred */
   1062     {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
   1063     /* ...otherwise try RTC */
   1064     {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
   1065 #endif
   1066     {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
   1067 #else
   1068     {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
   1069      win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
   1070     {"win32", 0, win32_start_timer,
   1071      win32_stop_timer, NULL, &alarm_win32_data},
   1072 #endif
   1073     {NULL, }
   1074 };
   1075 
   1076 static void show_available_alarms(void)
   1077 {
   1078     int i;
   1079 
   1080     printf("Available alarm timers, in order of precedence:\n");
   1081     for (i = 0; alarm_timers[i].name; i++)
   1082         printf("%s\n", alarm_timers[i].name);
   1083 }
   1084 
   1085 static void configure_alarms(char const *opt)
   1086 {
   1087     int i;
   1088     int cur = 0;
   1089     int count = ARRAY_SIZE(alarm_timers) - 1;
   1090     char *arg;
   1091     char *name;
   1092     struct qemu_alarm_timer tmp;
   1093 
   1094     if (!strcmp(opt, "?")) {
   1095         show_available_alarms();
   1096         exit(0);
   1097     }
   1098 
   1099     arg = qemu_strdup(opt);
   1100 
   1101     /* Reorder the array */
   1102     name = strtok(arg, ",");
   1103     while (name) {
   1104         for (i = 0; i < count && alarm_timers[i].name; i++) {
   1105             if (!strcmp(alarm_timers[i].name, name))
   1106                 break;
   1107         }
   1108 
   1109         if (i == count) {
   1110             fprintf(stderr, "Unknown clock %s\n", name);
   1111             goto next;
   1112         }
   1113 
   1114         if (i < cur)
   1115             /* Ignore */
   1116             goto next;
   1117 
   1118 	/* Swap */
   1119         tmp = alarm_timers[i];
   1120         alarm_timers[i] = alarm_timers[cur];
   1121         alarm_timers[cur] = tmp;
   1122 
   1123         cur++;
   1124 next:
   1125         name = strtok(NULL, ",");
   1126     }
   1127 
   1128     qemu_free(arg);
   1129 
   1130     if (cur) {
   1131         /* Disable remaining timers */
   1132         for (i = cur; i < count; i++)
   1133             alarm_timers[i].name = NULL;
   1134     } else {
   1135         show_available_alarms();
   1136         exit(1);
   1137     }
   1138 }
   1139 
   1140 #define QEMU_NUM_CLOCKS 3
   1141 
   1142 QEMUClock *rt_clock;
   1143 QEMUClock *vm_clock;
   1144 QEMUClock *host_clock;
   1145 
   1146 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
   1147 
   1148 static QEMUClock *qemu_new_clock(int type)
   1149 {
   1150     QEMUClock *clock;
   1151     clock = qemu_mallocz(sizeof(QEMUClock));
   1152     clock->type = type;
   1153     return clock;
   1154 }
   1155 
   1156 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
   1157 {
   1158     QEMUTimer *ts;
   1159 
   1160     ts = qemu_mallocz(sizeof(QEMUTimer));
   1161     ts->clock = clock;
   1162     ts->cb = cb;
   1163     ts->opaque = opaque;
   1164     return ts;
   1165 }
   1166 
   1167 void qemu_free_timer(QEMUTimer *ts)
   1168 {
   1169     qemu_free(ts);
   1170 }
   1171 
   1172 /* stop a timer, but do not dealloc it */
   1173 void qemu_del_timer(QEMUTimer *ts)
   1174 {
   1175     QEMUTimer **pt, *t;
   1176 
   1177     /* NOTE: this code must be signal safe because
   1178        qemu_timer_expired() can be called from a signal. */
   1179     pt = &active_timers[ts->clock->type];
   1180     for(;;) {
   1181         t = *pt;
   1182         if (!t)
   1183             break;
   1184         if (t == ts) {
   1185             *pt = t->next;
   1186             break;
   1187         }
   1188         pt = &t->next;
   1189     }
   1190 }
   1191 
   1192 /* modify the current timer so that it will be fired when current_time
   1193    >= expire_time. The corresponding callback will be called. */
   1194 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
   1195 {
   1196     QEMUTimer **pt, *t;
   1197 
   1198     qemu_del_timer(ts);
   1199 
   1200     /* add the timer in the sorted list */
   1201     /* NOTE: this code must be signal safe because
   1202        qemu_timer_expired() can be called from a signal. */
   1203     pt = &active_timers[ts->clock->type];
   1204     for(;;) {
   1205         t = *pt;
   1206         if (!t)
   1207             break;
   1208         if (t->expire_time > expire_time)
   1209             break;
   1210         pt = &t->next;
   1211     }
   1212     ts->expire_time = expire_time;
   1213     ts->next = *pt;
   1214     *pt = ts;
   1215 
   1216     /* Rearm if necessary  */
   1217     if (pt == &active_timers[ts->clock->type]) {
   1218         if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
   1219             qemu_rearm_alarm_timer(alarm_timer);
   1220         }
   1221         /* Interrupt execution to force deadline recalculation.  */
   1222         if (use_icount)
   1223             qemu_notify_event();
   1224     }
   1225 }
   1226 
   1227 int qemu_timer_pending(QEMUTimer *ts)
   1228 {
   1229     QEMUTimer *t;
   1230     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
   1231         if (t == ts)
   1232             return 1;
   1233     }
   1234     return 0;
   1235 }
   1236 
   1237 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
   1238 {
   1239     if (!timer_head)
   1240         return 0;
   1241     return (timer_head->expire_time <= current_time);
   1242 }
   1243 
   1244 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
   1245 {
   1246     QEMUTimer *ts;
   1247 
   1248     for(;;) {
   1249         ts = *ptimer_head;
   1250         if (!ts || ts->expire_time > current_time)
   1251             break;
   1252         /* remove timer from the list before calling the callback */
   1253         *ptimer_head = ts->next;
   1254         ts->next = NULL;
   1255 
   1256         /* run the callback (the timer list can be modified) */
   1257         ts->cb(ts->opaque);
   1258     }
   1259 }
   1260 
   1261 int64_t qemu_get_clock(QEMUClock *clock)
   1262 {
   1263     switch(clock->type) {
   1264     case QEMU_CLOCK_REALTIME:
   1265         return get_clock() / 1000000;
   1266     default:
   1267     case QEMU_CLOCK_VIRTUAL:
   1268         if (use_icount) {
   1269             return cpu_get_icount();
   1270         } else {
   1271             return cpu_get_clock();
   1272         }
   1273     case QEMU_CLOCK_HOST:
   1274         return get_clock_realtime();
   1275     }
   1276 }
   1277 
   1278 int64_t qemu_get_clock_ns(QEMUClock *clock)
   1279 {
   1280     switch(clock->type) {
   1281     case QEMU_CLOCK_REALTIME:
   1282         return get_clock();
   1283     default:
   1284     case QEMU_CLOCK_VIRTUAL:
   1285         if (use_icount) {
   1286             return cpu_get_icount();
   1287         } else {
   1288             return cpu_get_clock();
   1289         }
   1290     case QEMU_CLOCK_HOST:
   1291         return get_clock_realtime();
   1292     }
   1293 }
   1294 
   1295 static void init_clocks(void)
   1296 {
   1297     init_get_clock();
   1298     rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
   1299     vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
   1300     host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
   1301 
   1302     rtc_clock = host_clock;
   1303 }
   1304 
   1305 /* save a timer */
   1306 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
   1307 {
   1308     uint64_t expire_time;
   1309 
   1310     if (qemu_timer_pending(ts)) {
   1311         expire_time = ts->expire_time;
   1312     } else {
   1313         expire_time = -1;
   1314     }
   1315     qemu_put_be64(f, expire_time);
   1316 }
   1317 
   1318 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
   1319 {
   1320     uint64_t expire_time;
   1321 
   1322     expire_time = qemu_get_be64(f);
   1323     if (expire_time != -1) {
   1324         qemu_mod_timer(ts, expire_time);
   1325     } else {
   1326         qemu_del_timer(ts);
   1327     }
   1328 }
   1329 
   1330 static const VMStateDescription vmstate_timers = {
   1331     .name = "timer",
   1332     .version_id = 2,
   1333     .minimum_version_id = 1,
   1334     .minimum_version_id_old = 1,
   1335     .fields      = (VMStateField []) {
   1336         VMSTATE_INT64(cpu_ticks_offset, TimersState),
   1337         VMSTATE_INT64(dummy, TimersState),
   1338         VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
   1339         VMSTATE_END_OF_LIST()
   1340     }
   1341 };
   1342 
   1343 static void qemu_event_increment(void);
   1344 
   1345 #ifdef _WIN32
   1346 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
   1347                                         DWORD_PTR dwUser, DWORD_PTR dw1,
   1348                                         DWORD_PTR dw2)
   1349 #else
   1350 static void host_alarm_handler(int host_signum)
   1351 #endif
   1352 {
   1353 #if 0
   1354 #define DISP_FREQ 1000
   1355     {
   1356         static int64_t delta_min = INT64_MAX;
   1357         static int64_t delta_max, delta_cum, last_clock, delta, ti;
   1358         static int count;
   1359         ti = qemu_get_clock(vm_clock);
   1360         if (last_clock != 0) {
   1361             delta = ti - last_clock;
   1362             if (delta < delta_min)
   1363                 delta_min = delta;
   1364             if (delta > delta_max)
   1365                 delta_max = delta;
   1366             delta_cum += delta;
   1367             if (++count == DISP_FREQ) {
   1368                 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
   1369                        muldiv64(delta_min, 1000000, get_ticks_per_sec()),
   1370                        muldiv64(delta_max, 1000000, get_ticks_per_sec()),
   1371                        muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
   1372                        (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
   1373                 count = 0;
   1374                 delta_min = INT64_MAX;
   1375                 delta_max = 0;
   1376                 delta_cum = 0;
   1377             }
   1378         }
   1379         last_clock = ti;
   1380     }
   1381 #endif
   1382     if (alarm_has_dynticks(alarm_timer) ||
   1383         (!use_icount &&
   1384             qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
   1385                                qemu_get_clock(vm_clock))) ||
   1386         qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
   1387                            qemu_get_clock(rt_clock)) ||
   1388         qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
   1389                            qemu_get_clock(host_clock))) {
   1390         qemu_event_increment();
   1391         if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
   1392 
   1393 #ifndef CONFIG_IOTHREAD
   1394         if (next_cpu) {
   1395             /* stop the currently executing cpu because a timer occured */
   1396             cpu_exit(next_cpu);
   1397         }
   1398 #endif
   1399         timer_alarm_pending = 1;
   1400         qemu_notify_event();
   1401     }
   1402 }
   1403 
   1404 static int64_t qemu_next_deadline(void)
   1405 {
   1406     /* To avoid problems with overflow limit this to 2^32.  */
   1407     int64_t delta = INT32_MAX;
   1408 
   1409     if (active_timers[QEMU_CLOCK_VIRTUAL]) {
   1410         delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
   1411                      qemu_get_clock(vm_clock);
   1412     }
   1413     if (active_timers[QEMU_CLOCK_HOST]) {
   1414         int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
   1415                  qemu_get_clock(host_clock);
   1416         if (hdelta < delta)
   1417             delta = hdelta;
   1418     }
   1419 
   1420     if (delta < 0)
   1421         delta = 0;
   1422 
   1423     return delta;
   1424 }
   1425 
   1426 #if defined(__linux__)
   1427 static uint64_t qemu_next_deadline_dyntick(void)
   1428 {
   1429     int64_t delta;
   1430     int64_t rtdelta;
   1431 
   1432     if (use_icount)
   1433         delta = INT32_MAX;
   1434     else
   1435         delta = (qemu_next_deadline() + 999) / 1000;
   1436 
   1437     if (active_timers[QEMU_CLOCK_REALTIME]) {
   1438         rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
   1439                  qemu_get_clock(rt_clock))*1000;
   1440         if (rtdelta < delta)
   1441             delta = rtdelta;
   1442     }
   1443 
   1444     if (delta < MIN_TIMER_REARM_US)
   1445         delta = MIN_TIMER_REARM_US;
   1446 
   1447     return delta;
   1448 }
   1449 #endif
   1450 
   1451 #ifndef _WIN32
   1452 
   1453 /* Sets a specific flag */
   1454 static int fcntl_setfl(int fd, int flag)
   1455 {
   1456     int flags;
   1457 
   1458     flags = fcntl(fd, F_GETFL);
   1459     if (flags == -1)
   1460         return -errno;
   1461 
   1462     if (fcntl(fd, F_SETFL, flags | flag) == -1)
   1463         return -errno;
   1464 
   1465     return 0;
   1466 }
   1467 
   1468 #if defined(__linux__)
   1469 
   1470 #define RTC_FREQ 1024
   1471 
   1472 static void enable_sigio_timer(int fd)
   1473 {
   1474     struct sigaction act;
   1475 
   1476     /* timer signal */
   1477     sigfillset(&act.sa_mask);
   1478     act.sa_flags = 0;
   1479     act.sa_handler = host_alarm_handler;
   1480 
   1481     sigaction(SIGIO, &act, NULL);
   1482     fcntl_setfl(fd, O_ASYNC);
   1483     fcntl(fd, F_SETOWN, getpid());
   1484 }
   1485 
   1486 static int hpet_start_timer(struct qemu_alarm_timer *t)
   1487 {
   1488     struct hpet_info info;
   1489     int r, fd;
   1490 
   1491     fd = qemu_open("/dev/hpet", O_RDONLY);
   1492     if (fd < 0)
   1493         return -1;
   1494 
   1495     /* Set frequency */
   1496     r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
   1497     if (r < 0) {
   1498         fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
   1499                 "error, but for better emulation accuracy type:\n"
   1500                 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
   1501         goto fail;
   1502     }
   1503 
   1504     /* Check capabilities */
   1505     r = ioctl(fd, HPET_INFO, &info);
   1506     if (r < 0)
   1507         goto fail;
   1508 
   1509     /* Enable periodic mode */
   1510     r = ioctl(fd, HPET_EPI, 0);
   1511     if (info.hi_flags && (r < 0))
   1512         goto fail;
   1513 
   1514     /* Enable interrupt */
   1515     r = ioctl(fd, HPET_IE_ON, 0);
   1516     if (r < 0)
   1517         goto fail;
   1518 
   1519     enable_sigio_timer(fd);
   1520     t->priv = (void *)(long)fd;
   1521 
   1522     return 0;
   1523 fail:
   1524     close(fd);
   1525     return -1;
   1526 }
   1527 
   1528 static void hpet_stop_timer(struct qemu_alarm_timer *t)
   1529 {
   1530     int fd = (long)t->priv;
   1531 
   1532     close(fd);
   1533 }
   1534 
   1535 static int rtc_start_timer(struct qemu_alarm_timer *t)
   1536 {
   1537     int rtc_fd;
   1538     unsigned long current_rtc_freq = 0;
   1539 
   1540     TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
   1541     if (rtc_fd < 0)
   1542         return -1;
   1543     ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
   1544     if (current_rtc_freq != RTC_FREQ &&
   1545         ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
   1546         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
   1547                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
   1548                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
   1549         goto fail;
   1550     }
   1551     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
   1552     fail:
   1553         close(rtc_fd);
   1554         return -1;
   1555     }
   1556 
   1557     enable_sigio_timer(rtc_fd);
   1558 
   1559     t->priv = (void *)(long)rtc_fd;
   1560 
   1561     return 0;
   1562 }
   1563 
   1564 static void rtc_stop_timer(struct qemu_alarm_timer *t)
   1565 {
   1566     int rtc_fd = (long)t->priv;
   1567 
   1568     close(rtc_fd);
   1569 }
   1570 
   1571 static int dynticks_start_timer(struct qemu_alarm_timer *t)
   1572 {
   1573     struct sigevent ev;
   1574     timer_t host_timer;
   1575     struct sigaction act;
   1576 
   1577     sigfillset(&act.sa_mask);
   1578     act.sa_flags = 0;
   1579     act.sa_handler = host_alarm_handler;
   1580 
   1581     sigaction(SIGALRM, &act, NULL);
   1582 
   1583     /*
   1584      * Initialize ev struct to 0 to avoid valgrind complaining
   1585      * about uninitialized data in timer_create call
   1586      */
   1587     memset(&ev, 0, sizeof(ev));
   1588     ev.sigev_value.sival_int = 0;
   1589     ev.sigev_notify = SIGEV_SIGNAL;
   1590     ev.sigev_signo = SIGALRM;
   1591 
   1592     if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
   1593         perror("timer_create");
   1594 
   1595         /* disable dynticks */
   1596         fprintf(stderr, "Dynamic Ticks disabled\n");
   1597 
   1598         return -1;
   1599     }
   1600 
   1601     t->priv = (void *)(long)host_timer;
   1602 
   1603     return 0;
   1604 }
   1605 
   1606 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
   1607 {
   1608     timer_t host_timer = (timer_t)(long)t->priv;
   1609 
   1610     timer_delete(host_timer);
   1611 }
   1612 
   1613 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
   1614 {
   1615     timer_t host_timer = (timer_t)(long)t->priv;
   1616     struct itimerspec timeout;
   1617     int64_t nearest_delta_us = INT64_MAX;
   1618     int64_t current_us;
   1619 
   1620     if (!active_timers[QEMU_CLOCK_REALTIME] &&
   1621         !active_timers[QEMU_CLOCK_VIRTUAL] &&
   1622         !active_timers[QEMU_CLOCK_HOST])
   1623         return;
   1624 
   1625     nearest_delta_us = qemu_next_deadline_dyntick();
   1626 
   1627     /* check whether a timer is already running */
   1628     if (timer_gettime(host_timer, &timeout)) {
   1629         perror("gettime");
   1630         fprintf(stderr, "Internal timer error: aborting\n");
   1631         exit(1);
   1632     }
   1633     current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
   1634     if (current_us && current_us <= nearest_delta_us)
   1635         return;
   1636 
   1637     timeout.it_interval.tv_sec = 0;
   1638     timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
   1639     timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
   1640     timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
   1641     if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
   1642         perror("settime");
   1643         fprintf(stderr, "Internal timer error: aborting\n");
   1644         exit(1);
   1645     }
   1646 }
   1647 
   1648 #endif /* defined(__linux__) */
   1649 
   1650 static int unix_start_timer(struct qemu_alarm_timer *t)
   1651 {
   1652     struct sigaction act;
   1653     struct itimerval itv;
   1654     int err;
   1655 
   1656     /* timer signal */
   1657     sigfillset(&act.sa_mask);
   1658     act.sa_flags = 0;
   1659     act.sa_handler = host_alarm_handler;
   1660 
   1661     sigaction(SIGALRM, &act, NULL);
   1662 
   1663     itv.it_interval.tv_sec = 0;
   1664     /* for i386 kernel 2.6 to get 1 ms */
   1665     itv.it_interval.tv_usec = 999;
   1666     itv.it_value.tv_sec = 0;
   1667     itv.it_value.tv_usec = 10 * 1000;
   1668 
   1669     err = setitimer(ITIMER_REAL, &itv, NULL);
   1670     if (err)
   1671         return -1;
   1672 
   1673     return 0;
   1674 }
   1675 
   1676 static void unix_stop_timer(struct qemu_alarm_timer *t)
   1677 {
   1678     struct itimerval itv;
   1679 
   1680     memset(&itv, 0, sizeof(itv));
   1681     setitimer(ITIMER_REAL, &itv, NULL);
   1682 }
   1683 
   1684 #endif /* !defined(_WIN32) */
   1685 
   1686 
   1687 #ifdef _WIN32
   1688 
   1689 static int win32_start_timer(struct qemu_alarm_timer *t)
   1690 {
   1691     TIMECAPS tc;
   1692     struct qemu_alarm_win32 *data = t->priv;
   1693     UINT flags;
   1694 
   1695     memset(&tc, 0, sizeof(tc));
   1696     timeGetDevCaps(&tc, sizeof(tc));
   1697 
   1698     if (data->period < tc.wPeriodMin)
   1699         data->period = tc.wPeriodMin;
   1700 
   1701     timeBeginPeriod(data->period);
   1702 
   1703     flags = TIME_CALLBACK_FUNCTION;
   1704     if (alarm_has_dynticks(t))
   1705         flags |= TIME_ONESHOT;
   1706     else
   1707         flags |= TIME_PERIODIC;
   1708 
   1709     data->timerId = timeSetEvent(1,         // interval (ms)
   1710                         data->period,       // resolution
   1711                         host_alarm_handler, // function
   1712                         (DWORD)t,           // parameter
   1713                         flags);
   1714 
   1715     if (!data->timerId) {
   1716         fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
   1717                 GetLastError());
   1718         timeEndPeriod(data->period);
   1719         return -1;
   1720     }
   1721 
   1722     return 0;
   1723 }
   1724 
   1725 static void win32_stop_timer(struct qemu_alarm_timer *t)
   1726 {
   1727     struct qemu_alarm_win32 *data = t->priv;
   1728 
   1729     timeKillEvent(data->timerId);
   1730     timeEndPeriod(data->period);
   1731 }
   1732 
   1733 static void win32_rearm_timer(struct qemu_alarm_timer *t)
   1734 {
   1735     struct qemu_alarm_win32 *data = t->priv;
   1736 
   1737     if (!active_timers[QEMU_CLOCK_REALTIME] &&
   1738         !active_timers[QEMU_CLOCK_VIRTUAL] &&
   1739         !active_timers[QEMU_CLOCK_HOST])
   1740         return;
   1741 
   1742     timeKillEvent(data->timerId);
   1743 
   1744     data->timerId = timeSetEvent(1,
   1745                         data->period,
   1746                         host_alarm_handler,
   1747                         (DWORD)t,
   1748                         TIME_ONESHOT | TIME_PERIODIC);
   1749 
   1750     if (!data->timerId) {
   1751         fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
   1752                 GetLastError());
   1753 
   1754         timeEndPeriod(data->period);
   1755         exit(1);
   1756     }
   1757 }
   1758 
   1759 #endif /* _WIN32 */
   1760 
   1761 static int init_timer_alarm(void)
   1762 {
   1763     struct qemu_alarm_timer *t = NULL;
   1764     int i, err = -1;
   1765 
   1766     for (i = 0; alarm_timers[i].name; i++) {
   1767         t = &alarm_timers[i];
   1768 
   1769         err = t->start(t);
   1770         if (!err)
   1771             break;
   1772     }
   1773 
   1774     if (err) {
   1775         err = -ENOENT;
   1776         goto fail;
   1777     }
   1778 
   1779     alarm_timer = t;
   1780 
   1781     return 0;
   1782 
   1783 fail:
   1784     return err;
   1785 }
   1786 
   1787 static void quit_timers(void)
   1788 {
   1789     alarm_timer->stop(alarm_timer);
   1790     alarm_timer = NULL;
   1791 }
   1792 
   1793 /***********************************************************/
   1794 /* host time/date access */
   1795 void qemu_get_timedate(struct tm *tm, int offset)
   1796 {
   1797     time_t ti;
   1798     struct tm *ret;
   1799 
   1800     time(&ti);
   1801     ti += offset;
   1802     if (rtc_date_offset == -1) {
   1803         if (rtc_utc)
   1804             ret = gmtime(&ti);
   1805         else
   1806             ret = localtime(&ti);
   1807     } else {
   1808         ti -= rtc_date_offset;
   1809         ret = gmtime(&ti);
   1810     }
   1811 
   1812     memcpy(tm, ret, sizeof(struct tm));
   1813 }
   1814 
   1815 int qemu_timedate_diff(struct tm *tm)
   1816 {
   1817     time_t seconds;
   1818 
   1819     if (rtc_date_offset == -1)
   1820         if (rtc_utc)
   1821             seconds = mktimegm(tm);
   1822         else
   1823             seconds = mktime(tm);
   1824     else
   1825         seconds = mktimegm(tm) + rtc_date_offset;
   1826 
   1827     return seconds - time(NULL);
   1828 }
   1829 
   1830 #ifdef _WIN32
   1831 static void socket_cleanup(void)
   1832 {
   1833     WSACleanup();
   1834 }
   1835 
   1836 static int socket_init(void)
   1837 {
   1838     WSADATA Data;
   1839     int ret, err;
   1840 
   1841     ret = WSAStartup(MAKEWORD(2,2), &Data);
   1842     if (ret != 0) {
   1843         err = WSAGetLastError();
   1844         fprintf(stderr, "WSAStartup: %d\n", err);
   1845         return -1;
   1846     }
   1847     atexit(socket_cleanup);
   1848     return 0;
   1849 }
   1850 #endif
   1851 
   1852 int get_param_value(char *buf, int buf_size,
   1853                     const char *tag, const char *str)
   1854 {
   1855     const char *p;
   1856     char option[128];
   1857 
   1858     p = str;
   1859     for(;;) {
   1860         p = get_opt_name(option, sizeof(option), p, '=');
   1861         if (*p != '=')
   1862             break;
   1863         p++;
   1864         if (!strcmp(tag, option)) {
   1865             (void)get_opt_value(buf, buf_size, p);
   1866             return strlen(buf);
   1867         } else {
   1868             p = get_opt_value(NULL, 0, p);
   1869         }
   1870         if (*p != ',')
   1871             break;
   1872         p++;
   1873     }
   1874     return 0;
   1875 }
   1876 
   1877 int check_params(char *buf, int buf_size,
   1878                  const char * const *params, const char *str)
   1879 {
   1880     const char *p;
   1881     int i;
   1882 
   1883     p = str;
   1884     while (*p != '\0') {
   1885         p = get_opt_name(buf, buf_size, p, '=');
   1886         if (*p != '=') {
   1887             return -1;
   1888         }
   1889         p++;
   1890         for (i = 0; params[i] != NULL; i++) {
   1891             if (!strcmp(params[i], buf)) {
   1892                 break;
   1893             }
   1894         }
   1895         if (params[i] == NULL) {
   1896             return -1;
   1897         }
   1898         p = get_opt_value(NULL, 0, p);
   1899         if (*p != ',') {
   1900             break;
   1901         }
   1902         p++;
   1903     }
   1904     return 0;
   1905 }
   1906 
   1907 /***********************************************************/
   1908 /* Bluetooth support */
   1909 static int nb_hcis;
   1910 static int cur_hci;
   1911 static struct HCIInfo *hci_table[MAX_NICS];
   1912 
   1913 static struct bt_vlan_s {
   1914     struct bt_scatternet_s net;
   1915     int id;
   1916     struct bt_vlan_s *next;
   1917 } *first_bt_vlan;
   1918 
   1919 /* find or alloc a new bluetooth "VLAN" */
   1920 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
   1921 {
   1922     struct bt_vlan_s **pvlan, *vlan;
   1923     for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
   1924         if (vlan->id == id)
   1925             return &vlan->net;
   1926     }
   1927     vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
   1928     vlan->id = id;
   1929     pvlan = &first_bt_vlan;
   1930     while (*pvlan != NULL)
   1931         pvlan = &(*pvlan)->next;
   1932     *pvlan = vlan;
   1933     return &vlan->net;
   1934 }
   1935 
   1936 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
   1937 {
   1938 }
   1939 
   1940 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
   1941 {
   1942     return -ENOTSUP;
   1943 }
   1944 
   1945 static struct HCIInfo null_hci = {
   1946     .cmd_send = null_hci_send,
   1947     .sco_send = null_hci_send,
   1948     .acl_send = null_hci_send,
   1949     .bdaddr_set = null_hci_addr_set,
   1950 };
   1951 
   1952 struct HCIInfo *qemu_next_hci(void)
   1953 {
   1954     if (cur_hci == nb_hcis)
   1955         return &null_hci;
   1956 
   1957     return hci_table[cur_hci++];
   1958 }
   1959 
   1960 static struct HCIInfo *hci_init(const char *str)
   1961 {
   1962     char *endp;
   1963     struct bt_scatternet_s *vlan = 0;
   1964 
   1965     if (!strcmp(str, "null"))
   1966         /* null */
   1967         return &null_hci;
   1968     else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
   1969         /* host[:hciN] */
   1970         return bt_host_hci(str[4] ? str + 5 : "hci0");
   1971     else if (!strncmp(str, "hci", 3)) {
   1972         /* hci[,vlan=n] */
   1973         if (str[3]) {
   1974             if (!strncmp(str + 3, ",vlan=", 6)) {
   1975                 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
   1976                 if (*endp)
   1977                     vlan = 0;
   1978             }
   1979         } else
   1980             vlan = qemu_find_bt_vlan(0);
   1981         if (vlan)
   1982            return bt_new_hci(vlan);
   1983     }
   1984 
   1985     fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
   1986 
   1987     return 0;
   1988 }
   1989 
   1990 static int bt_hci_parse(const char *str)
   1991 {
   1992     struct HCIInfo *hci;
   1993     bdaddr_t bdaddr;
   1994 
   1995     if (nb_hcis >= MAX_NICS) {
   1996         fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
   1997         return -1;
   1998     }
   1999 
   2000     hci = hci_init(str);
   2001     if (!hci)
   2002         return -1;
   2003 
   2004     bdaddr.b[0] = 0x52;
   2005     bdaddr.b[1] = 0x54;
   2006     bdaddr.b[2] = 0x00;
   2007     bdaddr.b[3] = 0x12;
   2008     bdaddr.b[4] = 0x34;
   2009     bdaddr.b[5] = 0x56 + nb_hcis;
   2010     hci->bdaddr_set(hci, bdaddr.b);
   2011 
   2012     hci_table[nb_hcis++] = hci;
   2013 
   2014     return 0;
   2015 }
   2016 
   2017 static void bt_vhci_add(int vlan_id)
   2018 {
   2019     struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
   2020 
   2021     if (!vlan->slave)
   2022         fprintf(stderr, "qemu: warning: adding a VHCI to "
   2023                         "an empty scatternet %i\n", vlan_id);
   2024 
   2025     bt_vhci_init(bt_new_hci(vlan));
   2026 }
   2027 
   2028 static struct bt_device_s *bt_device_add(const char *opt)
   2029 {
   2030     struct bt_scatternet_s *vlan;
   2031     int vlan_id = 0;
   2032     char *endp = strstr(opt, ",vlan=");
   2033     int len = (endp ? endp - opt : strlen(opt)) + 1;
   2034     char devname[10];
   2035 
   2036     pstrcpy(devname, MIN(sizeof(devname), len), opt);
   2037 
   2038     if (endp) {
   2039         vlan_id = strtol(endp + 6, &endp, 0);
   2040         if (*endp) {
   2041             fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
   2042             return 0;
   2043         }
   2044     }
   2045 
   2046     vlan = qemu_find_bt_vlan(vlan_id);
   2047 
   2048     if (!vlan->slave)
   2049         fprintf(stderr, "qemu: warning: adding a slave device to "
   2050                         "an empty scatternet %i\n", vlan_id);
   2051 
   2052     if (!strcmp(devname, "keyboard"))
   2053         return bt_keyboard_init(vlan);
   2054 
   2055     fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
   2056     return 0;
   2057 }
   2058 
   2059 static int bt_parse(const char *opt)
   2060 {
   2061     const char *endp, *p;
   2062     int vlan;
   2063 
   2064     if (strstart(opt, "hci", &endp)) {
   2065         if (!*endp || *endp == ',') {
   2066             if (*endp)
   2067                 if (!strstart(endp, ",vlan=", 0))
   2068                     opt = endp + 1;
   2069 
   2070             return bt_hci_parse(opt);
   2071        }
   2072     } else if (strstart(opt, "vhci", &endp)) {
   2073         if (!*endp || *endp == ',') {
   2074             if (*endp) {
   2075                 if (strstart(endp, ",vlan=", &p)) {
   2076                     vlan = strtol(p, (char **) &endp, 0);
   2077                     if (*endp) {
   2078                         fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
   2079                         return 1;
   2080                     }
   2081                 } else {
   2082                     fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
   2083                     return 1;
   2084                 }
   2085             } else
   2086                 vlan = 0;
   2087 
   2088             bt_vhci_add(vlan);
   2089             return 0;
   2090         }
   2091     } else if (strstart(opt, "device:", &endp))
   2092         return !bt_device_add(endp);
   2093 
   2094     fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
   2095     return 1;
   2096 }
   2097 
   2098 /***********************************************************/
   2099 /* QEMU Block devices */
   2100 
   2101 #define HD_ALIAS "index=%d,media=disk"
   2102 #define CDROM_ALIAS "index=2,media=cdrom"
   2103 #define FD_ALIAS "index=%d,if=floppy"
   2104 #define PFLASH_ALIAS "if=pflash"
   2105 #define MTD_ALIAS "if=mtd"
   2106 #define SD_ALIAS "index=0,if=sd"
   2107 
   2108 static int drive_opt_get_free_idx(void)
   2109 {
   2110     int index;
   2111 
   2112     for (index = 0; index < MAX_DRIVES; index++)
   2113         if (!drives_opt[index].used) {
   2114             drives_opt[index].used = 1;
   2115             return index;
   2116         }
   2117 
   2118     return -1;
   2119 }
   2120 
   2121 static int drive_get_free_idx(void)
   2122 {
   2123     int index;
   2124 
   2125     for (index = 0; index < MAX_DRIVES; index++)
   2126         if (!drives_table[index].used) {
   2127             drives_table[index].used = 1;
   2128             return index;
   2129         }
   2130 
   2131     return -1;
   2132 }
   2133 
   2134 int drive_add(const char *file, const char *fmt, ...)
   2135 {
   2136     va_list ap;
   2137     int index = drive_opt_get_free_idx();
   2138 
   2139     if (nb_drives_opt >= MAX_DRIVES || index == -1) {
   2140         fprintf(stderr, "qemu: too many drives\n");
   2141         return -1;
   2142     }
   2143 
   2144     drives_opt[index].file = file;
   2145     va_start(ap, fmt);
   2146     vsnprintf(drives_opt[index].opt,
   2147               sizeof(drives_opt[0].opt), fmt, ap);
   2148     va_end(ap);
   2149 
   2150     nb_drives_opt++;
   2151     return index;
   2152 }
   2153 
   2154 void drive_remove(int index)
   2155 {
   2156     drives_opt[index].used = 0;
   2157     nb_drives_opt--;
   2158 }
   2159 
   2160 int drive_get_index(BlockInterfaceType type, int bus, int unit)
   2161 {
   2162     int index;
   2163 
   2164     /* seek interface, bus and unit */
   2165 
   2166     for (index = 0; index < MAX_DRIVES; index++)
   2167         if (drives_table[index].type == type &&
   2168 	    drives_table[index].bus == bus &&
   2169 	    drives_table[index].unit == unit &&
   2170 	    drives_table[index].used)
   2171         return index;
   2172 
   2173     return -1;
   2174 }
   2175 
   2176 int drive_get_max_bus(BlockInterfaceType type)
   2177 {
   2178     int max_bus;
   2179     int index;
   2180 
   2181     max_bus = -1;
   2182     for (index = 0; index < nb_drives; index++) {
   2183         if(drives_table[index].type == type &&
   2184            drives_table[index].bus > max_bus)
   2185             max_bus = drives_table[index].bus;
   2186     }
   2187     return max_bus;
   2188 }
   2189 
   2190 const char *drive_get_serial(BlockDriverState *bdrv)
   2191 {
   2192     int index;
   2193 
   2194     for (index = 0; index < nb_drives; index++)
   2195         if (drives_table[index].bdrv == bdrv)
   2196             return drives_table[index].serial;
   2197 
   2198     return "\0";
   2199 }
   2200 
   2201 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
   2202 {
   2203     int index;
   2204 
   2205     for (index = 0; index < nb_drives; index++)
   2206         if (drives_table[index].bdrv == bdrv)
   2207             return drives_table[index].onerror;
   2208 
   2209     return BLOCK_ERR_STOP_ENOSPC;
   2210 }
   2211 
   2212 static void bdrv_format_print(void *opaque, const char *name)
   2213 {
   2214     fprintf(stderr, " %s", name);
   2215 }
   2216 
   2217 void drive_uninit(BlockDriverState *bdrv)
   2218 {
   2219     int i;
   2220 
   2221     for (i = 0; i < MAX_DRIVES; i++)
   2222         if (drives_table[i].bdrv == bdrv) {
   2223             drives_table[i].bdrv = NULL;
   2224             drives_table[i].used = 0;
   2225             drive_remove(drives_table[i].drive_opt_idx);
   2226             nb_drives--;
   2227             break;
   2228         }
   2229 }
   2230 
   2231 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
   2232 {
   2233     char buf[128];
   2234     char file[1024];
   2235     char devname[128];
   2236     char serial[21];
   2237     const char *mediastr = "";
   2238     BlockInterfaceType type;
   2239     enum { MEDIA_DISK, MEDIA_CDROM } media;
   2240     int bus_id, unit_id;
   2241     int cyls, heads, secs, translation;
   2242     BlockDriverState *bdrv;
   2243     BlockDriver *drv = NULL;
   2244     QEMUMachine *machine = opaque;
   2245     int max_devs;
   2246     int index;
   2247     int cache;
   2248     int bdrv_flags, onerror;
   2249     int drives_table_idx;
   2250     char *str = arg->opt;
   2251     static const char * const params[] = { "bus", "unit", "if", "index",
   2252                                            "cyls", "heads", "secs", "trans",
   2253                                            "media", "snapshot", "file",
   2254                                            "cache", "format", "serial", "werror",
   2255                                            NULL };
   2256 
   2257     if (check_params(buf, sizeof(buf), params, str) < 0) {
   2258          fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
   2259                          buf, str);
   2260          return -1;
   2261     }
   2262 
   2263     file[0] = 0;
   2264     cyls = heads = secs = 0;
   2265     bus_id = 0;
   2266     unit_id = -1;
   2267     translation = BIOS_ATA_TRANSLATION_AUTO;
   2268     index = -1;
   2269     cache = 3;
   2270 
   2271     if (machine->use_scsi) {
   2272         type = IF_SCSI;
   2273         max_devs = MAX_SCSI_DEVS;
   2274         pstrcpy(devname, sizeof(devname), "scsi");
   2275     } else {
   2276         type = IF_IDE;
   2277         max_devs = MAX_IDE_DEVS;
   2278         pstrcpy(devname, sizeof(devname), "ide");
   2279     }
   2280     media = MEDIA_DISK;
   2281 
   2282     /* extract parameters */
   2283 
   2284     if (get_param_value(buf, sizeof(buf), "bus", str)) {
   2285         bus_id = strtol(buf, NULL, 0);
   2286 	if (bus_id < 0) {
   2287 	    fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
   2288 	    return -1;
   2289 	}
   2290     }
   2291 
   2292     if (get_param_value(buf, sizeof(buf), "unit", str)) {
   2293         unit_id = strtol(buf, NULL, 0);
   2294 	if (unit_id < 0) {
   2295 	    fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
   2296 	    return -1;
   2297 	}
   2298     }
   2299 
   2300     if (get_param_value(buf, sizeof(buf), "if", str)) {
   2301         pstrcpy(devname, sizeof(devname), buf);
   2302         if (!strcmp(buf, "ide")) {
   2303 	    type = IF_IDE;
   2304             max_devs = MAX_IDE_DEVS;
   2305         } else if (!strcmp(buf, "scsi")) {
   2306 	    type = IF_SCSI;
   2307             max_devs = MAX_SCSI_DEVS;
   2308         } else if (!strcmp(buf, "floppy")) {
   2309 	    type = IF_FLOPPY;
   2310             max_devs = 0;
   2311         } else if (!strcmp(buf, "pflash")) {
   2312 	    type = IF_PFLASH;
   2313             max_devs = 0;
   2314 	} else if (!strcmp(buf, "mtd")) {
   2315 	    type = IF_MTD;
   2316             max_devs = 0;
   2317 	} else if (!strcmp(buf, "sd")) {
   2318 	    type = IF_SD;
   2319             max_devs = 0;
   2320         } else if (!strcmp(buf, "virtio")) {
   2321             type = IF_VIRTIO;
   2322             max_devs = 0;
   2323 	} else if (!strcmp(buf, "xen")) {
   2324 	    type = IF_XEN;
   2325             max_devs = 0;
   2326 	} else {
   2327             fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
   2328             return -1;
   2329 	}
   2330     }
   2331 
   2332     if (get_param_value(buf, sizeof(buf), "index", str)) {
   2333         index = strtol(buf, NULL, 0);
   2334 	if (index < 0) {
   2335 	    fprintf(stderr, "qemu: '%s' invalid index\n", str);
   2336 	    return -1;
   2337 	}
   2338     }
   2339 
   2340     if (get_param_value(buf, sizeof(buf), "cyls", str)) {
   2341         cyls = strtol(buf, NULL, 0);
   2342     }
   2343 
   2344     if (get_param_value(buf, sizeof(buf), "heads", str)) {
   2345         heads = strtol(buf, NULL, 0);
   2346     }
   2347 
   2348     if (get_param_value(buf, sizeof(buf), "secs", str)) {
   2349         secs = strtol(buf, NULL, 0);
   2350     }
   2351 
   2352     if (cyls || heads || secs) {
   2353         if (cyls < 1 || cyls > 16383) {
   2354             fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
   2355 	    return -1;
   2356 	}
   2357         if (heads < 1 || heads > 16) {
   2358             fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
   2359 	    return -1;
   2360 	}
   2361         if (secs < 1 || secs > 63) {
   2362             fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
   2363 	    return -1;
   2364 	}
   2365     }
   2366 
   2367     if (get_param_value(buf, sizeof(buf), "trans", str)) {
   2368         if (!cyls) {
   2369             fprintf(stderr,
   2370                     "qemu: '%s' trans must be used with cyls,heads and secs\n",
   2371                     str);
   2372             return -1;
   2373         }
   2374         if (!strcmp(buf, "none"))
   2375             translation = BIOS_ATA_TRANSLATION_NONE;
   2376         else if (!strcmp(buf, "lba"))
   2377             translation = BIOS_ATA_TRANSLATION_LBA;
   2378         else if (!strcmp(buf, "auto"))
   2379             translation = BIOS_ATA_TRANSLATION_AUTO;
   2380 	else {
   2381             fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
   2382 	    return -1;
   2383 	}
   2384     }
   2385 
   2386     if (get_param_value(buf, sizeof(buf), "media", str)) {
   2387         if (!strcmp(buf, "disk")) {
   2388 	    media = MEDIA_DISK;
   2389 	} else if (!strcmp(buf, "cdrom")) {
   2390             if (cyls || secs || heads) {
   2391                 fprintf(stderr,
   2392                         "qemu: '%s' invalid physical CHS format\n", str);
   2393 	        return -1;
   2394             }
   2395 	    media = MEDIA_CDROM;
   2396 	} else {
   2397 	    fprintf(stderr, "qemu: '%s' invalid media\n", str);
   2398 	    return -1;
   2399 	}
   2400     }
   2401 
   2402     if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
   2403         if (!strcmp(buf, "on"))
   2404 	    snapshot = 1;
   2405         else if (!strcmp(buf, "off"))
   2406 	    snapshot = 0;
   2407 	else {
   2408 	    fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
   2409 	    return -1;
   2410 	}
   2411     }
   2412 
   2413     if (get_param_value(buf, sizeof(buf), "cache", str)) {
   2414         if (!strcmp(buf, "off") || !strcmp(buf, "none"))
   2415             cache = 0;
   2416         else if (!strcmp(buf, "writethrough"))
   2417             cache = 1;
   2418         else if (!strcmp(buf, "writeback"))
   2419             cache = 2;
   2420         else {
   2421            fprintf(stderr, "qemu: invalid cache option\n");
   2422            return -1;
   2423         }
   2424     }
   2425 
   2426     if (get_param_value(buf, sizeof(buf), "format", str)) {
   2427        if (strcmp(buf, "?") == 0) {
   2428             fprintf(stderr, "qemu: Supported formats:");
   2429             bdrv_iterate_format(bdrv_format_print, NULL);
   2430             fprintf(stderr, "\n");
   2431 	    return -1;
   2432         }
   2433         drv = bdrv_find_format(buf);
   2434         if (!drv) {
   2435             fprintf(stderr, "qemu: '%s' invalid format\n", buf);
   2436             return -1;
   2437         }
   2438     }
   2439 
   2440     if (arg->file == NULL)
   2441         get_param_value(file, sizeof(file), "file", str);
   2442     else
   2443         pstrcpy(file, sizeof(file), arg->file);
   2444 
   2445     if (!get_param_value(serial, sizeof(serial), "serial", str))
   2446 	    memset(serial, 0,  sizeof(serial));
   2447 
   2448     onerror = BLOCK_ERR_STOP_ENOSPC;
   2449     if (get_param_value(buf, sizeof(serial), "werror", str)) {
   2450         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
   2451             fprintf(stderr, "werror is no supported by this format\n");
   2452             return -1;
   2453         }
   2454         if (!strcmp(buf, "ignore"))
   2455             onerror = BLOCK_ERR_IGNORE;
   2456         else if (!strcmp(buf, "enospc"))
   2457             onerror = BLOCK_ERR_STOP_ENOSPC;
   2458         else if (!strcmp(buf, "stop"))
   2459             onerror = BLOCK_ERR_STOP_ANY;
   2460         else if (!strcmp(buf, "report"))
   2461             onerror = BLOCK_ERR_REPORT;
   2462         else {
   2463             fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
   2464             return -1;
   2465         }
   2466     }
   2467 
   2468     /* compute bus and unit according index */
   2469 
   2470     if (index != -1) {
   2471         if (bus_id != 0 || unit_id != -1) {
   2472             fprintf(stderr,
   2473                     "qemu: '%s' index cannot be used with bus and unit\n", str);
   2474             return -1;
   2475         }
   2476         if (max_devs == 0)
   2477         {
   2478             unit_id = index;
   2479             bus_id = 0;
   2480         } else {
   2481             unit_id = index % max_devs;
   2482             bus_id = index / max_devs;
   2483         }
   2484     }
   2485 
   2486     /* if user doesn't specify a unit_id,
   2487      * try to find the first free
   2488      */
   2489 
   2490     if (unit_id == -1) {
   2491        unit_id = 0;
   2492        while (drive_get_index(type, bus_id, unit_id) != -1) {
   2493            unit_id++;
   2494            if (max_devs && unit_id >= max_devs) {
   2495                unit_id -= max_devs;
   2496                bus_id++;
   2497            }
   2498        }
   2499     }
   2500 
   2501     /* check unit id */
   2502 
   2503     if (max_devs && unit_id >= max_devs) {
   2504         fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
   2505                         str, unit_id, max_devs - 1);
   2506         return -1;
   2507     }
   2508 
   2509     /*
   2510      * ignore multiple definitions
   2511      */
   2512 
   2513     if (drive_get_index(type, bus_id, unit_id) != -1)
   2514         return -2;
   2515 
   2516     /* init */
   2517 
   2518     if (type == IF_IDE || type == IF_SCSI)
   2519         mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
   2520     if (max_devs)
   2521         snprintf(buf, sizeof(buf), "%s%i%s%i",
   2522                  devname, bus_id, mediastr, unit_id);
   2523     else
   2524         snprintf(buf, sizeof(buf), "%s%s%i",
   2525                  devname, mediastr, unit_id);
   2526     bdrv = bdrv_new(buf);
   2527     drives_table_idx = drive_get_free_idx();
   2528     drives_table[drives_table_idx].bdrv = bdrv;
   2529     drives_table[drives_table_idx].type = type;
   2530     drives_table[drives_table_idx].bus = bus_id;
   2531     drives_table[drives_table_idx].unit = unit_id;
   2532     drives_table[drives_table_idx].onerror = onerror;
   2533     drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
   2534     strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
   2535     nb_drives++;
   2536 
   2537     switch(type) {
   2538     case IF_IDE:
   2539     case IF_SCSI:
   2540     case IF_XEN:
   2541         switch(media) {
   2542 	case MEDIA_DISK:
   2543             if (cyls != 0) {
   2544                 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
   2545                 bdrv_set_translation_hint(bdrv, translation);
   2546             }
   2547 	    break;
   2548 	case MEDIA_CDROM:
   2549             bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
   2550 	    break;
   2551 	}
   2552         break;
   2553     case IF_SD:
   2554         /* FIXME: This isn't really a floppy, but it's a reasonable
   2555            approximation.  */
   2556     case IF_FLOPPY:
   2557         bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
   2558         break;
   2559     case IF_PFLASH:
   2560     case IF_MTD:
   2561     case IF_VIRTIO:
   2562         break;
   2563     case IF_COUNT:
   2564         abort();
   2565     }
   2566     if (!file[0])
   2567         return -2;
   2568     bdrv_flags = 0;
   2569     if (snapshot) {
   2570         bdrv_flags |= BDRV_O_SNAPSHOT;
   2571         cache = 2; /* always use write-back with snapshot */
   2572     }
   2573     if (cache == 0) /* no caching */
   2574         bdrv_flags |= BDRV_O_NOCACHE;
   2575     else if (cache == 2) /* write-back */
   2576         bdrv_flags |= BDRV_O_CACHE_WB;
   2577     else if (cache == 3) /* not specified */
   2578         bdrv_flags |= BDRV_O_CACHE_DEF;
   2579     if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
   2580         fprintf(stderr, "qemu: could not open disk image %s\n",
   2581                         file);
   2582         return -1;
   2583     }
   2584     if (bdrv_key_required(bdrv))
   2585         autostart = 0;
   2586     return drives_table_idx;
   2587 }
   2588 
   2589 static void numa_add(const char *optarg)
   2590 {
   2591     char option[128];
   2592     char *endptr;
   2593     unsigned long long value, endvalue;
   2594     int nodenr;
   2595 
   2596     optarg = get_opt_name(option, 128, optarg, ',') + 1;
   2597     if (!strcmp(option, "node")) {
   2598         if (get_param_value(option, 128, "nodeid", optarg) == 0) {
   2599             nodenr = nb_numa_nodes;
   2600         } else {
   2601             nodenr = strtoull(option, NULL, 10);
   2602         }
   2603 
   2604         if (get_param_value(option, 128, "mem", optarg) == 0) {
   2605             node_mem[nodenr] = 0;
   2606         } else {
   2607             value = strtoull(option, &endptr, 0);
   2608             switch (*endptr) {
   2609             case 0: case 'M': case 'm':
   2610                 value <<= 20;
   2611                 break;
   2612             case 'G': case 'g':
   2613                 value <<= 30;
   2614                 break;
   2615             }
   2616             node_mem[nodenr] = value;
   2617         }
   2618         if (get_param_value(option, 128, "cpus", optarg) == 0) {
   2619             node_cpumask[nodenr] = 0;
   2620         } else {
   2621             value = strtoull(option, &endptr, 10);
   2622             if (value >= 64) {
   2623                 value = 63;
   2624                 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
   2625             } else {
   2626                 if (*endptr == '-') {
   2627                     endvalue = strtoull(endptr+1, &endptr, 10);
   2628                     if (endvalue >= 63) {
   2629                         endvalue = 62;
   2630                         fprintf(stderr,
   2631                             "only 63 CPUs in NUMA mode supported.\n");
   2632                     }
   2633                     value = (1 << (endvalue + 1)) - (1 << value);
   2634                 } else {
   2635                     value = 1 << value;
   2636                 }
   2637             }
   2638             node_cpumask[nodenr] = value;
   2639         }
   2640         nb_numa_nodes++;
   2641     }
   2642     return;
   2643 }
   2644 
   2645 /***********************************************************/
   2646 /* USB devices */
   2647 
   2648 static USBPort *used_usb_ports;
   2649 static USBPort *free_usb_ports;
   2650 
   2651 /* ??? Maybe change this to register a hub to keep track of the topology.  */
   2652 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
   2653                             usb_attachfn attach)
   2654 {
   2655     port->opaque = opaque;
   2656     port->index = index;
   2657     port->attach = attach;
   2658     port->next = free_usb_ports;
   2659     free_usb_ports = port;
   2660 }
   2661 
   2662 int usb_device_add_dev(USBDevice *dev)
   2663 {
   2664     USBPort *port;
   2665 
   2666     /* Find a USB port to add the device to.  */
   2667     port = free_usb_ports;
   2668     if (!port->next) {
   2669         USBDevice *hub;
   2670 
   2671         /* Create a new hub and chain it on.  */
   2672         free_usb_ports = NULL;
   2673         port->next = used_usb_ports;
   2674         used_usb_ports = port;
   2675 
   2676         hub = usb_hub_init(VM_USB_HUB_SIZE);
   2677         usb_attach(port, hub);
   2678         port = free_usb_ports;
   2679     }
   2680 
   2681     free_usb_ports = port->next;
   2682     port->next = used_usb_ports;
   2683     used_usb_ports = port;
   2684     usb_attach(port, dev);
   2685     return 0;
   2686 }
   2687 
   2688 static void usb_msd_password_cb(void *opaque, int err)
   2689 {
   2690     USBDevice *dev = opaque;
   2691 
   2692     if (!err)
   2693         usb_device_add_dev(dev);
   2694     else
   2695         dev->handle_destroy(dev);
   2696 }
   2697 
   2698 static int usb_device_add(const char *devname, int is_hotplug)
   2699 {
   2700     const char *p;
   2701     USBDevice *dev;
   2702 
   2703     if (!free_usb_ports)
   2704         return -1;
   2705 
   2706     if (strstart(devname, "host:", &p)) {
   2707         dev = usb_host_device_open(p);
   2708     } else if (!strcmp(devname, "mouse")) {
   2709         dev = usb_mouse_init();
   2710     } else if (!strcmp(devname, "tablet")) {
   2711         dev = usb_tablet_init();
   2712     } else if (!strcmp(devname, "keyboard")) {
   2713         dev = usb_keyboard_init();
   2714     } else if (strstart(devname, "disk:", &p)) {
   2715         BlockDriverState *bs;
   2716 
   2717         dev = usb_msd_init(p);
   2718         if (!dev)
   2719             return -1;
   2720         bs = usb_msd_get_bdrv(dev);
   2721         if (bdrv_key_required(bs)) {
   2722             autostart = 0;
   2723             if (is_hotplug) {
   2724                 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
   2725                                             dev);
   2726                 return 0;
   2727             }
   2728         }
   2729     } else if (!strcmp(devname, "wacom-tablet")) {
   2730         dev = usb_wacom_init();
   2731     } else if (strstart(devname, "serial:", &p)) {
   2732         dev = usb_serial_init(p);
   2733 #ifdef CONFIG_BRLAPI
   2734     } else if (!strcmp(devname, "braille")) {
   2735         dev = usb_baum_init();
   2736 #endif
   2737     } else if (strstart(devname, "net:", &p)) {
   2738         int nic = nb_nics;
   2739 
   2740         if (net_client_init(NULL, "nic", p) < 0)
   2741             return -1;
   2742         nd_table[nic].model = "usb";
   2743         dev = usb_net_init(&nd_table[nic]);
   2744     } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
   2745         dev = usb_bt_init(devname[2] ? hci_init(p) :
   2746                         bt_new_hci(qemu_find_bt_vlan(0)));
   2747     } else {
   2748         return -1;
   2749     }
   2750     if (!dev)
   2751         return -1;
   2752 
   2753     return usb_device_add_dev(dev);
   2754 }
   2755 
   2756 int usb_device_del_addr(int bus_num, int addr)
   2757 {
   2758     USBPort *port;
   2759     USBPort **lastp;
   2760     USBDevice *dev;
   2761 
   2762     if (!used_usb_ports)
   2763         return -1;
   2764 
   2765     if (bus_num != 0)
   2766         return -1;
   2767 
   2768     lastp = &used_usb_ports;
   2769     port = used_usb_ports;
   2770     while (port && port->dev->addr != addr) {
   2771         lastp = &port->next;
   2772         port = port->next;
   2773     }
   2774 
   2775     if (!port)
   2776         return -1;
   2777 
   2778     dev = port->dev;
   2779     *lastp = port->next;
   2780     usb_attach(port, NULL);
   2781     dev->handle_destroy(dev);
   2782     port->next = free_usb_ports;
   2783     free_usb_ports = port;
   2784     return 0;
   2785 }
   2786 
   2787 static int usb_device_del(const char *devname)
   2788 {
   2789     int bus_num, addr;
   2790     const char *p;
   2791 
   2792     if (strstart(devname, "host:", &p))
   2793         return usb_host_device_close(p);
   2794 
   2795     if (!used_usb_ports)
   2796         return -1;
   2797 
   2798     p = strchr(devname, '.');
   2799     if (!p)
   2800         return -1;
   2801     bus_num = strtoul(devname, NULL, 0);
   2802     addr = strtoul(p + 1, NULL, 0);
   2803 
   2804     return usb_device_del_addr(bus_num, addr);
   2805 }
   2806 
   2807 void do_usb_add(Monitor *mon, const char *devname)
   2808 {
   2809     usb_device_add(devname, 1);
   2810 }
   2811 
   2812 void do_usb_del(Monitor *mon, const char *devname)
   2813 {
   2814     usb_device_del(devname);
   2815 }
   2816 
   2817 void usb_info(Monitor *mon)
   2818 {
   2819     USBDevice *dev;
   2820     USBPort *port;
   2821     const char *speed_str;
   2822 
   2823     if (!usb_enabled) {
   2824         monitor_printf(mon, "USB support not enabled\n");
   2825         return;
   2826     }
   2827 
   2828     for (port = used_usb_ports; port; port = port->next) {
   2829         dev = port->dev;
   2830         if (!dev)
   2831             continue;
   2832         switch(dev->speed) {
   2833         case USB_SPEED_LOW:
   2834             speed_str = "1.5";
   2835             break;
   2836         case USB_SPEED_FULL:
   2837             speed_str = "12";
   2838             break;
   2839         case USB_SPEED_HIGH:
   2840             speed_str = "480";
   2841             break;
   2842         default:
   2843             speed_str = "?";
   2844             break;
   2845         }
   2846         monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
   2847                        0, dev->addr, speed_str, dev->devname);
   2848     }
   2849 }
   2850 
   2851 /***********************************************************/
   2852 /* PCMCIA/Cardbus */
   2853 
   2854 static struct pcmcia_socket_entry_s {
   2855     PCMCIASocket *socket;
   2856     struct pcmcia_socket_entry_s *next;
   2857 } *pcmcia_sockets = 0;
   2858 
   2859 void pcmcia_socket_register(PCMCIASocket *socket)
   2860 {
   2861     struct pcmcia_socket_entry_s *entry;
   2862 
   2863     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
   2864     entry->socket = socket;
   2865     entry->next = pcmcia_sockets;
   2866     pcmcia_sockets = entry;
   2867 }
   2868 
   2869 void pcmcia_socket_unregister(PCMCIASocket *socket)
   2870 {
   2871     struct pcmcia_socket_entry_s *entry, **ptr;
   2872 
   2873     ptr = &pcmcia_sockets;
   2874     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
   2875         if (entry->socket == socket) {
   2876             *ptr = entry->next;
   2877             qemu_free(entry);
   2878         }
   2879 }
   2880 
   2881 void pcmcia_info(Monitor *mon)
   2882 {
   2883     struct pcmcia_socket_entry_s *iter;
   2884 
   2885     if (!pcmcia_sockets)
   2886         monitor_printf(mon, "No PCMCIA sockets\n");
   2887 
   2888     for (iter = pcmcia_sockets; iter; iter = iter->next)
   2889         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
   2890                        iter->socket->attached ? iter->socket->card_string :
   2891                        "Empty");
   2892 }
   2893 
   2894 /***********************************************************/
   2895 /* register display */
   2896 
   2897 struct DisplayAllocator default_allocator = {
   2898     defaultallocator_create_displaysurface,
   2899     defaultallocator_resize_displaysurface,
   2900     defaultallocator_free_displaysurface
   2901 };
   2902 
   2903 void register_displaystate(DisplayState *ds)
   2904 {
   2905     DisplayState **s;
   2906     s = &display_state;
   2907     while (*s != NULL)
   2908         s = &(*s)->next;
   2909     ds->next = NULL;
   2910     *s = ds;
   2911 }
   2912 
   2913 DisplayState *get_displaystate(void)
   2914 {
   2915     return display_state;
   2916 }
   2917 
   2918 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
   2919 {
   2920     if(ds->allocator ==  &default_allocator) ds->allocator = da;
   2921     return ds->allocator;
   2922 }
   2923 
   2924 /* dumb display */
   2925 
   2926 static void dumb_display_init(void)
   2927 {
   2928     DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
   2929     ds->allocator = &default_allocator;
   2930     ds->surface = qemu_create_displaysurface(ds, 640, 480);
   2931     register_displaystate(ds);
   2932 }
   2933 
   2934 /***********************************************************/
   2935 /* I/O handling */
   2936 
   2937 typedef struct IOHandlerRecord {
   2938     int fd;
   2939     IOCanRWHandler *fd_read_poll;
   2940     IOHandler *fd_read;
   2941     IOHandler *fd_write;
   2942     int deleted;
   2943     void *opaque;
   2944     /* temporary data */
   2945     struct pollfd *ufd;
   2946     struct IOHandlerRecord *next;
   2947 } IOHandlerRecord;
   2948 
   2949 static IOHandlerRecord *first_io_handler;
   2950 
   2951 /* XXX: fd_read_poll should be suppressed, but an API change is
   2952    necessary in the character devices to suppress fd_can_read(). */
   2953 int qemu_set_fd_handler2(int fd,
   2954                          IOCanRWHandler *fd_read_poll,
   2955                          IOHandler *fd_read,
   2956                          IOHandler *fd_write,
   2957                          void *opaque)
   2958 {
   2959     IOHandlerRecord **pioh, *ioh;
   2960 
   2961     if (!fd_read && !fd_write) {
   2962         pioh = &first_io_handler;
   2963         for(;;) {
   2964             ioh = *pioh;
   2965             if (ioh == NULL)
   2966                 break;
   2967             if (ioh->fd == fd) {
   2968                 ioh->deleted = 1;
   2969                 break;
   2970             }
   2971             pioh = &ioh->next;
   2972         }
   2973     } else {
   2974         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
   2975             if (ioh->fd == fd)
   2976                 goto found;
   2977         }
   2978         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
   2979         ioh->next = first_io_handler;
   2980         first_io_handler = ioh;
   2981     found:
   2982         ioh->fd = fd;
   2983         ioh->fd_read_poll = fd_read_poll;
   2984         ioh->fd_read = fd_read;
   2985         ioh->fd_write = fd_write;
   2986         ioh->opaque = opaque;
   2987         ioh->deleted = 0;
   2988     }
   2989     return 0;
   2990 }
   2991 
   2992 int qemu_set_fd_handler(int fd,
   2993                         IOHandler *fd_read,
   2994                         IOHandler *fd_write,
   2995                         void *opaque)
   2996 {
   2997     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
   2998 }
   2999 
   3000 #ifdef _WIN32
   3001 /***********************************************************/
   3002 /* Polling handling */
   3003 
   3004 typedef struct PollingEntry {
   3005     PollingFunc *func;
   3006     void *opaque;
   3007     struct PollingEntry *next;
   3008 } PollingEntry;
   3009 
   3010 static PollingEntry *first_polling_entry;
   3011 
   3012 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
   3013 {
   3014     PollingEntry **ppe, *pe;
   3015     pe = qemu_mallocz(sizeof(PollingEntry));
   3016     pe->func = func;
   3017     pe->opaque = opaque;
   3018     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
   3019     *ppe = pe;
   3020     return 0;
   3021 }
   3022 
   3023 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
   3024 {
   3025     PollingEntry **ppe, *pe;
   3026     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
   3027         pe = *ppe;
   3028         if (pe->func == func && pe->opaque == opaque) {
   3029             *ppe = pe->next;
   3030             qemu_free(pe);
   3031             break;
   3032         }
   3033     }
   3034 }
   3035 
   3036 /***********************************************************/
   3037 /* Wait objects support */
   3038 typedef struct WaitObjects {
   3039     int num;
   3040     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
   3041     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
   3042     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
   3043 } WaitObjects;
   3044 
   3045 static WaitObjects wait_objects = {0};
   3046 
   3047 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
   3048 {
   3049     WaitObjects *w = &wait_objects;
   3050 
   3051     if (w->num >= MAXIMUM_WAIT_OBJECTS)
   3052         return -1;
   3053     w->events[w->num] = handle;
   3054     w->func[w->num] = func;
   3055     w->opaque[w->num] = opaque;
   3056     w->num++;
   3057     return 0;
   3058 }
   3059 
   3060 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
   3061 {
   3062     int i, found;
   3063     WaitObjects *w = &wait_objects;
   3064 
   3065     found = 0;
   3066     for (i = 0; i < w->num; i++) {
   3067         if (w->events[i] == handle)
   3068             found = 1;
   3069         if (found) {
   3070             w->events[i] = w->events[i + 1];
   3071             w->func[i] = w->func[i + 1];
   3072             w->opaque[i] = w->opaque[i + 1];
   3073         }
   3074     }
   3075     if (found)
   3076         w->num--;
   3077 }
   3078 #endif
   3079 
   3080 /***********************************************************/
   3081 /* ram save/restore */
   3082 
   3083 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
   3084 {
   3085     int v;
   3086 
   3087     v = qemu_get_byte(f);
   3088     switch(v) {
   3089     case 0:
   3090         if (qemu_get_buffer(f, buf, len) != len)
   3091             return -EIO;
   3092         break;
   3093     case 1:
   3094         v = qemu_get_byte(f);
   3095         memset(buf, v, len);
   3096         break;
   3097     default:
   3098         return -EINVAL;
   3099     }
   3100 
   3101     if (qemu_file_has_error(f))
   3102         return -EIO;
   3103 
   3104     return 0;
   3105 }
   3106 
   3107 static int ram_load_v1(QEMUFile *f, void *opaque)
   3108 {
   3109     int ret;
   3110     ram_addr_t i;
   3111 
   3112     if (qemu_get_be32(f) != last_ram_offset)
   3113         return -EINVAL;
   3114     for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
   3115         ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
   3116         if (ret)
   3117             return ret;
   3118     }
   3119     return 0;
   3120 }
   3121 
   3122 #define BDRV_HASH_BLOCK_SIZE 1024
   3123 #define IOBUF_SIZE 4096
   3124 #define RAM_CBLOCK_MAGIC 0xfabe
   3125 
   3126 typedef struct RamDecompressState {
   3127     z_stream zstream;
   3128     QEMUFile *f;
   3129     uint8_t buf[IOBUF_SIZE];
   3130 } RamDecompressState;
   3131 
   3132 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
   3133 {
   3134     int ret;
   3135     memset(s, 0, sizeof(*s));
   3136     s->f = f;
   3137     ret = inflateInit(&s->zstream);
   3138     if (ret != Z_OK)
   3139         return -1;
   3140     return 0;
   3141 }
   3142 
   3143 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
   3144 {
   3145     int ret, clen;
   3146 
   3147     s->zstream.avail_out = len;
   3148     s->zstream.next_out = buf;
   3149     while (s->zstream.avail_out > 0) {
   3150         if (s->zstream.avail_in == 0) {
   3151             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
   3152                 return -1;
   3153             clen = qemu_get_be16(s->f);
   3154             if (clen > IOBUF_SIZE)
   3155                 return -1;
   3156             qemu_get_buffer(s->f, s->buf, clen);
   3157             s->zstream.avail_in = clen;
   3158             s->zstream.next_in = s->buf;
   3159         }
   3160         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
   3161         if (ret != Z_OK && ret != Z_STREAM_END) {
   3162             return -1;
   3163         }
   3164     }
   3165     return 0;
   3166 }
   3167 
   3168 static void ram_decompress_close(RamDecompressState *s)
   3169 {
   3170     inflateEnd(&s->zstream);
   3171 }
   3172 
   3173 #define RAM_SAVE_FLAG_FULL	0x01
   3174 #define RAM_SAVE_FLAG_COMPRESS	0x02
   3175 #define RAM_SAVE_FLAG_MEM_SIZE	0x04
   3176 #define RAM_SAVE_FLAG_PAGE	0x08
   3177 #define RAM_SAVE_FLAG_EOS	0x10
   3178 
   3179 static int is_dup_page(uint8_t *page, uint8_t ch)
   3180 {
   3181     uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
   3182     uint32_t *array = (uint32_t *)page;
   3183     int i;
   3184 
   3185     for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
   3186         if (array[i] != val)
   3187             return 0;
   3188     }
   3189 
   3190     return 1;
   3191 }
   3192 
   3193 static int ram_save_block(QEMUFile *f)
   3194 {
   3195     static ram_addr_t current_addr = 0;
   3196     ram_addr_t saved_addr = current_addr;
   3197     ram_addr_t addr = 0;
   3198     int found = 0;
   3199 
   3200     while (addr < last_ram_offset) {
   3201         if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
   3202             uint8_t *p;
   3203 
   3204             cpu_physical_memory_reset_dirty(current_addr,
   3205                                             current_addr + TARGET_PAGE_SIZE,
   3206                                             MIGRATION_DIRTY_FLAG);
   3207 
   3208             p = qemu_get_ram_ptr(current_addr);
   3209 
   3210             if (is_dup_page(p, *p)) {
   3211                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
   3212                 qemu_put_byte(f, *p);
   3213             } else {
   3214                 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
   3215                 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
   3216             }
   3217 
   3218             found = 1;
   3219             break;
   3220         }
   3221         addr += TARGET_PAGE_SIZE;
   3222         current_addr = (saved_addr + addr) % last_ram_offset;
   3223     }
   3224 
   3225     return found;
   3226 }
   3227 
   3228 static uint64_t bytes_transferred;
   3229 
   3230 static ram_addr_t ram_save_remaining(void)
   3231 {
   3232     ram_addr_t addr;
   3233     ram_addr_t count = 0;
   3234 
   3235     for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
   3236         if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
   3237             count++;
   3238     }
   3239 
   3240     return count;
   3241 }
   3242 
   3243 uint64_t ram_bytes_remaining(void)
   3244 {
   3245     return ram_save_remaining() * TARGET_PAGE_SIZE;
   3246 }
   3247 
   3248 uint64_t ram_bytes_transferred(void)
   3249 {
   3250     return bytes_transferred;
   3251 }
   3252 
   3253 uint64_t ram_bytes_total(void)
   3254 {
   3255     return last_ram_offset;
   3256 }
   3257 
   3258 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
   3259 {
   3260     ram_addr_t addr;
   3261     uint64_t bytes_transferred_last;
   3262     double bwidth = 0;
   3263     uint64_t expected_time = 0;
   3264 
   3265     if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
   3266         qemu_file_set_error(f);
   3267         return 0;
   3268     }
   3269 
   3270     if (stage == 1) {
   3271         bytes_transferred = 0;
   3272 
   3273         /* Make sure all dirty bits are set */
   3274         for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
   3275             if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
   3276                 cpu_physical_memory_set_dirty(addr);
   3277         }
   3278 
   3279         /* Enable dirty memory tracking */
   3280         cpu_physical_memory_set_dirty_tracking(1);
   3281 
   3282         qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
   3283     }
   3284 
   3285     bytes_transferred_last = bytes_transferred;
   3286     bwidth = qemu_get_clock_ns(rt_clock);
   3287 
   3288     while (!qemu_file_rate_limit(f)) {
   3289         int ret;
   3290 
   3291         ret = ram_save_block(f);
   3292         bytes_transferred += ret * TARGET_PAGE_SIZE;
   3293         if (ret == 0) /* no more blocks */
   3294             break;
   3295     }
   3296 
   3297     bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
   3298     bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
   3299 
   3300     /* if we haven't transferred anything this round, force expected_time to a
   3301      * a very high value, but without crashing */
   3302     if (bwidth == 0)
   3303         bwidth = 0.000001;
   3304 
   3305     /* try transferring iterative blocks of memory */
   3306     if (stage == 3) {
   3307         /* flush all remaining blocks regardless of rate limiting */
   3308         while (ram_save_block(f) != 0) {
   3309             bytes_transferred += TARGET_PAGE_SIZE;
   3310         }
   3311         cpu_physical_memory_set_dirty_tracking(0);
   3312     }
   3313 
   3314     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
   3315 
   3316     expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
   3317 
   3318     return (stage == 2) && (expected_time <= migrate_max_downtime());
   3319 }
   3320 
   3321 static int ram_load_dead(QEMUFile *f, void *opaque)
   3322 {
   3323     RamDecompressState s1, *s = &s1;
   3324     uint8_t buf[10];
   3325     ram_addr_t i;
   3326 
   3327     if (ram_decompress_open(s, f) < 0)
   3328         return -EINVAL;
   3329     for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
   3330         if (ram_decompress_buf(s, buf, 1) < 0) {
   3331             fprintf(stderr, "Error while reading ram block header\n");
   3332             goto error;
   3333         }
   3334         if (buf[0] == 0) {
   3335             if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
   3336                                    BDRV_HASH_BLOCK_SIZE) < 0) {
   3337                 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
   3338                 goto error;
   3339             }
   3340         } else {
   3341         error:
   3342             printf("Error block header\n");
   3343             return -EINVAL;
   3344         }
   3345     }
   3346     ram_decompress_close(s);
   3347 
   3348     return 0;
   3349 }
   3350 
   3351 static int ram_load(QEMUFile *f, void *opaque, int version_id)
   3352 {
   3353     ram_addr_t addr;
   3354     int flags;
   3355 
   3356     if (version_id == 1)
   3357         return ram_load_v1(f, opaque);
   3358 
   3359     if (version_id == 2) {
   3360         if (qemu_get_be32(f) != last_ram_offset)
   3361             return -EINVAL;
   3362         return ram_load_dead(f, opaque);
   3363     }
   3364 
   3365     if (version_id != 3)
   3366         return -EINVAL;
   3367 
   3368     do {
   3369         addr = qemu_get_be64(f);
   3370 
   3371         flags = addr & ~TARGET_PAGE_MASK;
   3372         addr &= TARGET_PAGE_MASK;
   3373 
   3374         if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
   3375             if (addr != last_ram_offset)
   3376                 return -EINVAL;
   3377         }
   3378 
   3379         if (flags & RAM_SAVE_FLAG_FULL) {
   3380             if (ram_load_dead(f, opaque) < 0)
   3381                 return -EINVAL;
   3382         }
   3383 
   3384         if (flags & RAM_SAVE_FLAG_COMPRESS) {
   3385             uint8_t ch = qemu_get_byte(f);
   3386             memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
   3387         } else if (flags & RAM_SAVE_FLAG_PAGE)
   3388             qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
   3389     } while (!(flags & RAM_SAVE_FLAG_EOS));
   3390 
   3391     return 0;
   3392 }
   3393 
   3394 void qemu_service_io(void)
   3395 {
   3396     qemu_notify_event();
   3397 }
   3398 
   3399 /***********************************************************/
   3400 /* bottom halves (can be seen as timers which expire ASAP) */
   3401 
   3402 struct QEMUBH {
   3403     QEMUBHFunc *cb;
   3404     void *opaque;
   3405     int scheduled;
   3406     int idle;
   3407     int deleted;
   3408     QEMUBH *next;
   3409 };
   3410 
   3411 static QEMUBH *first_bh = NULL;
   3412 
   3413 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
   3414 {
   3415     QEMUBH *bh;
   3416     bh = qemu_mallocz(sizeof(QEMUBH));
   3417     bh->cb = cb;
   3418     bh->opaque = opaque;
   3419     bh->next = first_bh;
   3420     first_bh = bh;
   3421     return bh;
   3422 }
   3423 
   3424 int qemu_bh_poll(void)
   3425 {
   3426     QEMUBH *bh, **bhp;
   3427     int ret;
   3428 
   3429     ret = 0;
   3430     for (bh = first_bh; bh; bh = bh->next) {
   3431         if (!bh->deleted && bh->scheduled) {
   3432             bh->scheduled = 0;
   3433             if (!bh->idle)
   3434                 ret = 1;
   3435             bh->idle = 0;
   3436             bh->cb(bh->opaque);
   3437         }
   3438     }
   3439 
   3440     /* remove deleted bhs */
   3441     bhp = &first_bh;
   3442     while (*bhp) {
   3443         bh = *bhp;
   3444         if (bh->deleted) {
   3445             *bhp = bh->next;
   3446             qemu_free(bh);
   3447         } else
   3448             bhp = &bh->next;
   3449     }
   3450 
   3451     return ret;
   3452 }
   3453 
   3454 void qemu_bh_schedule_idle(QEMUBH *bh)
   3455 {
   3456     if (bh->scheduled)
   3457         return;
   3458     bh->scheduled = 1;
   3459     bh->idle = 1;
   3460 }
   3461 
   3462 void qemu_bh_schedule(QEMUBH *bh)
   3463 {
   3464     if (bh->scheduled)
   3465         return;
   3466     bh->scheduled = 1;
   3467     bh->idle = 0;
   3468     /* stop the currently executing CPU to execute the BH ASAP */
   3469     qemu_notify_event();
   3470 }
   3471 
   3472 void qemu_bh_cancel(QEMUBH *bh)
   3473 {
   3474     bh->scheduled = 0;
   3475 }
   3476 
   3477 void qemu_bh_delete(QEMUBH *bh)
   3478 {
   3479     bh->scheduled = 0;
   3480     bh->deleted = 1;
   3481 }
   3482 
   3483 static void qemu_bh_update_timeout(int *timeout)
   3484 {
   3485     QEMUBH *bh;
   3486 
   3487     for (bh = first_bh; bh; bh = bh->next) {
   3488         if (!bh->deleted && bh->scheduled) {
   3489             if (bh->idle) {
   3490                 /* idle bottom halves will be polled at least
   3491                  * every 10ms */
   3492                 *timeout = MIN(10, *timeout);
   3493             } else {
   3494                 /* non-idle bottom halves will be executed
   3495                  * immediately */
   3496                 *timeout = 0;
   3497                 break;
   3498             }
   3499         }
   3500     }
   3501 }
   3502 
   3503 /***********************************************************/
   3504 /* machine registration */
   3505 
   3506 static QEMUMachine *first_machine = NULL;
   3507 QEMUMachine *current_machine = NULL;
   3508 
   3509 int qemu_register_machine(QEMUMachine *m)
   3510 {
   3511     QEMUMachine **pm;
   3512     pm = &first_machine;
   3513     while (*pm != NULL)
   3514         pm = &(*pm)->next;
   3515     m->next = NULL;
   3516     *pm = m;
   3517     return 0;
   3518 }
   3519 
   3520 static QEMUMachine *find_machine(const char *name)
   3521 {
   3522     QEMUMachine *m;
   3523 
   3524     for(m = first_machine; m != NULL; m = m->next) {
   3525         if (!strcmp(m->name, name))
   3526             return m;
   3527     }
   3528     return NULL;
   3529 }
   3530 
   3531 static QEMUMachine *find_default_machine(void)
   3532 {
   3533     QEMUMachine *m;
   3534 
   3535     for(m = first_machine; m != NULL; m = m->next) {
   3536         if (m->is_default) {
   3537             return m;
   3538         }
   3539     }
   3540     return NULL;
   3541 }
   3542 
   3543 /***********************************************************/
   3544 /* main execution loop */
   3545 
   3546 static void gui_update(void *opaque)
   3547 {
   3548     uint64_t interval = GUI_REFRESH_INTERVAL;
   3549     DisplayState *ds = opaque;
   3550     DisplayChangeListener *dcl = ds->listeners;
   3551 
   3552     dpy_refresh(ds);
   3553 
   3554     while (dcl != NULL) {
   3555         if (dcl->gui_timer_interval &&
   3556             dcl->gui_timer_interval < interval)
   3557             interval = dcl->gui_timer_interval;
   3558         dcl = dcl->next;
   3559     }
   3560     qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
   3561 }
   3562 
   3563 static void nographic_update(void *opaque)
   3564 {
   3565     uint64_t interval = GUI_REFRESH_INTERVAL;
   3566 
   3567     qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
   3568 }
   3569 
   3570 struct vm_change_state_entry {
   3571     VMChangeStateHandler *cb;
   3572     void *opaque;
   3573     QLIST_ENTRY (vm_change_state_entry) entries;
   3574 };
   3575 
   3576 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
   3577 
   3578 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
   3579                                                      void *opaque)
   3580 {
   3581     VMChangeStateEntry *e;
   3582 
   3583     e = qemu_mallocz(sizeof (*e));
   3584 
   3585     e->cb = cb;
   3586     e->opaque = opaque;
   3587     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
   3588     return e;
   3589 }
   3590 
   3591 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
   3592 {
   3593     QLIST_REMOVE (e, entries);
   3594     qemu_free (e);
   3595 }
   3596 
   3597 static void vm_state_notify(int running, int reason)
   3598 {
   3599     VMChangeStateEntry *e;
   3600 
   3601     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
   3602         e->cb(e->opaque, running, reason);
   3603     }
   3604 }
   3605 
   3606 static void resume_all_vcpus(void);
   3607 static void pause_all_vcpus(void);
   3608 
   3609 void vm_start(void)
   3610 {
   3611     if (!vm_running) {
   3612         cpu_enable_ticks();
   3613         vm_running = 1;
   3614         vm_state_notify(1, 0);
   3615         qemu_rearm_alarm_timer(alarm_timer);
   3616         resume_all_vcpus();
   3617     }
   3618 }
   3619 
   3620 /* reset/shutdown handler */
   3621 
   3622 typedef struct QEMUResetEntry {
   3623     QEMUResetHandler *func;
   3624     void *opaque;
   3625     int order;
   3626     struct QEMUResetEntry *next;
   3627 } QEMUResetEntry;
   3628 
   3629 static QEMUResetEntry *first_reset_entry;
   3630 static int reset_requested;
   3631 static int shutdown_requested;
   3632 static int powerdown_requested;
   3633 static int debug_requested;
   3634 static int vmstop_requested;
   3635 
   3636 int qemu_shutdown_requested(void)
   3637 {
   3638     int r = shutdown_requested;
   3639     shutdown_requested = 0;
   3640     return r;
   3641 }
   3642 
   3643 int qemu_reset_requested(void)
   3644 {
   3645     int r = reset_requested;
   3646     reset_requested = 0;
   3647     return r;
   3648 }
   3649 
   3650 int qemu_powerdown_requested(void)
   3651 {
   3652     int r = powerdown_requested;
   3653     powerdown_requested = 0;
   3654     return r;
   3655 }
   3656 
   3657 static int qemu_debug_requested(void)
   3658 {
   3659     int r = debug_requested;
   3660     debug_requested = 0;
   3661     return r;
   3662 }
   3663 
   3664 static int qemu_vmstop_requested(void)
   3665 {
   3666     int r = vmstop_requested;
   3667     vmstop_requested = 0;
   3668     return r;
   3669 }
   3670 
   3671 static void do_vm_stop(int reason)
   3672 {
   3673     if (vm_running) {
   3674         cpu_disable_ticks();
   3675         vm_running = 0;
   3676         pause_all_vcpus();
   3677         vm_state_notify(0, reason);
   3678     }
   3679 }
   3680 
   3681 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
   3682 {
   3683     QEMUResetEntry **pre, *re;
   3684 
   3685     pre = &first_reset_entry;
   3686     while (*pre != NULL && (*pre)->order >= order) {
   3687         pre = &(*pre)->next;
   3688     }
   3689     re = qemu_mallocz(sizeof(QEMUResetEntry));
   3690     re->func = func;
   3691     re->opaque = opaque;
   3692     re->order = order;
   3693     re->next = NULL;
   3694     *pre = re;
   3695 }
   3696 
   3697 void qemu_system_reset(void)
   3698 {
   3699     QEMUResetEntry *re;
   3700 
   3701     /* reset all devices */
   3702     for(re = first_reset_entry; re != NULL; re = re->next) {
   3703         re->func(re->opaque);
   3704     }
   3705 }
   3706 
   3707 void qemu_system_reset_request(void)
   3708 {
   3709     if (no_reboot) {
   3710         shutdown_requested = 1;
   3711     } else {
   3712         reset_requested = 1;
   3713     }
   3714     qemu_notify_event();
   3715 }
   3716 
   3717 void qemu_system_shutdown_request(void)
   3718 {
   3719     shutdown_requested = 1;
   3720     qemu_notify_event();
   3721 }
   3722 
   3723 void qemu_system_powerdown_request(void)
   3724 {
   3725     powerdown_requested = 1;
   3726     qemu_notify_event();
   3727 }
   3728 
   3729 #ifdef CONFIG_IOTHREAD
   3730 static void qemu_system_vmstop_request(int reason)
   3731 {
   3732     vmstop_requested = reason;
   3733     qemu_notify_event();
   3734 }
   3735 #endif
   3736 
   3737 #ifndef _WIN32
   3738 static int io_thread_fd = -1;
   3739 
   3740 static void qemu_event_increment(void)
   3741 {
   3742     static const char byte = 0;
   3743 
   3744     if (io_thread_fd == -1)
   3745         return;
   3746 
   3747     write(io_thread_fd, &byte, sizeof(byte));
   3748 }
   3749 
   3750 static void qemu_event_read(void *opaque)
   3751 {
   3752     int fd = (unsigned long)opaque;
   3753     ssize_t len;
   3754 
   3755     /* Drain the notify pipe */
   3756     do {
   3757         char buffer[512];
   3758         len = read(fd, buffer, sizeof(buffer));
   3759     } while ((len == -1 && errno == EINTR) || len > 0);
   3760 }
   3761 
   3762 static int qemu_event_init(void)
   3763 {
   3764     int err;
   3765     int fds[2];
   3766 
   3767     err = pipe(fds);
   3768     if (err == -1)
   3769         return -errno;
   3770 
   3771     err = fcntl_setfl(fds[0], O_NONBLOCK);
   3772     if (err < 0)
   3773         goto fail;
   3774 
   3775     err = fcntl_setfl(fds[1], O_NONBLOCK);
   3776     if (err < 0)
   3777         goto fail;
   3778 
   3779     qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
   3780                          (void *)(unsigned long)fds[0]);
   3781 
   3782     io_thread_fd = fds[1];
   3783     return 0;
   3784 
   3785 fail:
   3786     close(fds[0]);
   3787     close(fds[1]);
   3788     return err;
   3789 }
   3790 #else
   3791 HANDLE qemu_event_handle;
   3792 
   3793 static void dummy_event_handler(void *opaque)
   3794 {
   3795 }
   3796 
   3797 static int qemu_event_init(void)
   3798 {
   3799     qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
   3800     if (!qemu_event_handle) {
   3801         perror("Failed CreateEvent");
   3802         return -1;
   3803     }
   3804     qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
   3805     return 0;
   3806 }
   3807 
   3808 static void qemu_event_increment(void)
   3809 {
   3810     SetEvent(qemu_event_handle);
   3811 }
   3812 #endif
   3813 
   3814 static int cpu_can_run(CPUState *env)
   3815 {
   3816     if (env->stop)
   3817         return 0;
   3818     if (env->stopped)
   3819         return 0;
   3820     if (!vm_running)
   3821         return 0;
   3822     return 1;
   3823 }
   3824 
   3825 #ifndef CONFIG_IOTHREAD
   3826 static int qemu_init_main_loop(void)
   3827 {
   3828     return qemu_event_init();
   3829 }
   3830 
   3831 void qemu_init_vcpu(void *_env)
   3832 {
   3833     CPUState *env = _env;
   3834 
   3835     if (kvm_enabled())
   3836         kvm_init_vcpu(env);
   3837     return;
   3838 }
   3839 
   3840 int qemu_cpu_self(void *env)
   3841 {
   3842     return 1;
   3843 }
   3844 
   3845 static void resume_all_vcpus(void)
   3846 {
   3847 }
   3848 
   3849 static void pause_all_vcpus(void)
   3850 {
   3851 }
   3852 
   3853 void qemu_cpu_kick(void *env)
   3854 {
   3855     return;
   3856 }
   3857 
   3858 void qemu_notify_event(void)
   3859 {
   3860     CPUState *env = cpu_single_env;
   3861 
   3862     if (env) {
   3863         cpu_exit(env);
   3864      }
   3865 }
   3866 
   3867 #define qemu_mutex_lock_iothread() do { } while (0)
   3868 #define qemu_mutex_unlock_iothread() do { } while (0)
   3869 
   3870 void vm_stop(int reason)
   3871 {
   3872     do_vm_stop(reason);
   3873 }
   3874 
   3875 #else /* CONFIG_IOTHREAD */
   3876 
   3877 #include "qemu-thread.h"
   3878 
   3879 QemuMutex qemu_global_mutex;
   3880 static QemuMutex qemu_fair_mutex;
   3881 
   3882 static QemuThread io_thread;
   3883 
   3884 static QemuThread *tcg_cpu_thread;
   3885 static QemuCond *tcg_halt_cond;
   3886 
   3887 static int qemu_system_ready;
   3888 /* cpu creation */
   3889 static QemuCond qemu_cpu_cond;
   3890 /* system init */
   3891 static QemuCond qemu_system_cond;
   3892 static QemuCond qemu_pause_cond;
   3893 
   3894 static void block_io_signals(void);
   3895 static void unblock_io_signals(void);
   3896 static int tcg_has_work(void);
   3897 
   3898 static int qemu_init_main_loop(void)
   3899 {
   3900     int ret;
   3901 
   3902     ret = qemu_event_init();
   3903     if (ret)
   3904         return ret;
   3905 
   3906     qemu_cond_init(&qemu_pause_cond);
   3907     qemu_mutex_init(&qemu_fair_mutex);
   3908     qemu_mutex_init(&qemu_global_mutex);
   3909     qemu_mutex_lock(&qemu_global_mutex);
   3910 
   3911     unblock_io_signals();
   3912     qemu_thread_self(&io_thread);
   3913 
   3914     return 0;
   3915 }
   3916 
   3917 static void qemu_wait_io_event(CPUState *env)
   3918 {
   3919     while (!tcg_has_work())
   3920         qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
   3921 
   3922     qemu_mutex_unlock(&qemu_global_mutex);
   3923 
   3924     /*
   3925      * Users of qemu_global_mutex can be starved, having no chance
   3926      * to acquire it since this path will get to it first.
   3927      * So use another lock to provide fairness.
   3928      */
   3929     qemu_mutex_lock(&qemu_fair_mutex);
   3930     qemu_mutex_unlock(&qemu_fair_mutex);
   3931 
   3932     qemu_mutex_lock(&qemu_global_mutex);
   3933     if (env->stop) {
   3934         env->stop = 0;
   3935         env->stopped = 1;
   3936         qemu_cond_signal(&qemu_pause_cond);
   3937     }
   3938 }
   3939 
   3940 static int qemu_cpu_exec(CPUState *env);
   3941 
   3942 static void *kvm_cpu_thread_fn(void *arg)
   3943 {
   3944     CPUState *env = arg;
   3945 
   3946     block_io_signals();
   3947     qemu_thread_self(env->thread);
   3948 
   3949     /* signal CPU creation */
   3950     qemu_mutex_lock(&qemu_global_mutex);
   3951     env->created = 1;
   3952     qemu_cond_signal(&qemu_cpu_cond);
   3953 
   3954     /* and wait for machine initialization */
   3955     while (!qemu_system_ready)
   3956         qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
   3957 
   3958     while (1) {
   3959         if (cpu_can_run(env))
   3960             qemu_cpu_exec(env);
   3961         qemu_wait_io_event(env);
   3962     }
   3963 
   3964     return NULL;
   3965 }
   3966 
   3967 static void tcg_cpu_exec(void);
   3968 
   3969 static void *tcg_cpu_thread_fn(void *arg)
   3970 {
   3971     CPUState *env = arg;
   3972 
   3973     block_io_signals();
   3974     qemu_thread_self(env->thread);
   3975 
   3976     /* signal CPU creation */
   3977     qemu_mutex_lock(&qemu_global_mutex);
   3978     for (env = first_cpu; env != NULL; env = env->next_cpu)
   3979         env->created = 1;
   3980     qemu_cond_signal(&qemu_cpu_cond);
   3981 
   3982     /* and wait for machine initialization */
   3983     while (!qemu_system_ready)
   3984         qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
   3985 
   3986     while (1) {
   3987         tcg_cpu_exec();
   3988         qemu_wait_io_event(cur_cpu);
   3989     }
   3990 
   3991     return NULL;
   3992 }
   3993 
   3994 void qemu_cpu_kick(void *_env)
   3995 {
   3996     CPUState *env = _env;
   3997     qemu_cond_broadcast(env->halt_cond);
   3998     if (kvm_enabled())
   3999         qemu_thread_signal(env->thread, SIGUSR1);
   4000 }
   4001 
   4002 int qemu_cpu_self(void *env)
   4003 {
   4004     return (cpu_single_env != NULL);
   4005 }
   4006 
   4007 static void cpu_signal(int sig)
   4008 {
   4009     if (cpu_single_env)
   4010         cpu_exit(cpu_single_env);
   4011 }
   4012 
   4013 static void block_io_signals(void)
   4014 {
   4015     sigset_t set;
   4016     struct sigaction sigact;
   4017 
   4018     sigemptyset(&set);
   4019     sigaddset(&set, SIGUSR2);
   4020     sigaddset(&set, SIGIO);
   4021     sigaddset(&set, SIGALRM);
   4022     pthread_sigmask(SIG_BLOCK, &set, NULL);
   4023 
   4024     sigemptyset(&set);
   4025     sigaddset(&set, SIGUSR1);
   4026     pthread_sigmask(SIG_UNBLOCK, &set, NULL);
   4027 
   4028     memset(&sigact, 0, sizeof(sigact));
   4029     sigact.sa_handler = cpu_signal;
   4030     sigaction(SIGUSR1, &sigact, NULL);
   4031 }
   4032 
   4033 static void unblock_io_signals(void)
   4034 {
   4035     sigset_t set;
   4036 
   4037     sigemptyset(&set);
   4038     sigaddset(&set, SIGUSR2);
   4039     sigaddset(&set, SIGIO);
   4040     sigaddset(&set, SIGALRM);
   4041     pthread_sigmask(SIG_UNBLOCK, &set, NULL);
   4042 
   4043     sigemptyset(&set);
   4044     sigaddset(&set, SIGUSR1);
   4045     pthread_sigmask(SIG_BLOCK, &set, NULL);
   4046 }
   4047 
   4048 static void qemu_signal_lock(unsigned int msecs)
   4049 {
   4050     qemu_mutex_lock(&qemu_fair_mutex);
   4051 
   4052     while (qemu_mutex_trylock(&qemu_global_mutex)) {
   4053         qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
   4054         if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
   4055             break;
   4056     }
   4057     qemu_mutex_unlock(&qemu_fair_mutex);
   4058 }
   4059 
   4060 static void qemu_mutex_lock_iothread(void)
   4061 {
   4062     if (kvm_enabled()) {
   4063         qemu_mutex_lock(&qemu_fair_mutex);
   4064         qemu_mutex_lock(&qemu_global_mutex);
   4065         qemu_mutex_unlock(&qemu_fair_mutex);
   4066     } else
   4067         qemu_signal_lock(100);
   4068 }
   4069 
   4070 static void qemu_mutex_unlock_iothread(void)
   4071 {
   4072     qemu_mutex_unlock(&qemu_global_mutex);
   4073 }
   4074 
   4075 static int all_vcpus_paused(void)
   4076 {
   4077     CPUState *penv = first_cpu;
   4078 
   4079     while (penv) {
   4080         if (!penv->stopped)
   4081             return 0;
   4082         penv = (CPUState *)penv->next_cpu;
   4083     }
   4084 
   4085     return 1;
   4086 }
   4087 
   4088 static void pause_all_vcpus(void)
   4089 {
   4090     CPUState *penv = first_cpu;
   4091 
   4092     while (penv) {
   4093         penv->stop = 1;
   4094         qemu_thread_signal(penv->thread, SIGUSR1);
   4095         qemu_cpu_kick(penv);
   4096         penv = (CPUState *)penv->next_cpu;
   4097     }
   4098 
   4099     while (!all_vcpus_paused()) {
   4100         qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
   4101         penv = first_cpu;
   4102         while (penv) {
   4103             qemu_thread_signal(penv->thread, SIGUSR1);
   4104             penv = (CPUState *)penv->next_cpu;
   4105         }
   4106     }
   4107 }
   4108 
   4109 static void resume_all_vcpus(void)
   4110 {
   4111     CPUState *penv = first_cpu;
   4112 
   4113     while (penv) {
   4114         penv->stop = 0;
   4115         penv->stopped = 0;
   4116         qemu_thread_signal(penv->thread, SIGUSR1);
   4117         qemu_cpu_kick(penv);
   4118         penv = (CPUState *)penv->next_cpu;
   4119     }
   4120 }
   4121 
   4122 static void tcg_init_vcpu(void *_env)
   4123 {
   4124     CPUState *env = _env;
   4125     /* share a single thread for all cpus with TCG */
   4126     if (!tcg_cpu_thread) {
   4127         env->thread = qemu_mallocz(sizeof(QemuThread));
   4128         env->halt_cond = qemu_mallocz(sizeof(QemuCond));
   4129         qemu_cond_init(env->halt_cond);
   4130         qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
   4131         while (env->created == 0)
   4132             qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
   4133         tcg_cpu_thread = env->thread;
   4134         tcg_halt_cond = env->halt_cond;
   4135     } else {
   4136         env->thread = tcg_cpu_thread;
   4137         env->halt_cond = tcg_halt_cond;
   4138     }
   4139 }
   4140 
   4141 static void kvm_start_vcpu(CPUState *env)
   4142 {
   4143     kvm_init_vcpu(env);
   4144     env->thread = qemu_mallocz(sizeof(QemuThread));
   4145     env->halt_cond = qemu_mallocz(sizeof(QemuCond));
   4146     qemu_cond_init(env->halt_cond);
   4147     qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
   4148     while (env->created == 0)
   4149         qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
   4150 }
   4151 
   4152 void qemu_init_vcpu(void *_env)
   4153 {
   4154     CPUState *env = _env;
   4155 
   4156     if (kvm_enabled())
   4157         kvm_start_vcpu(env);
   4158     else
   4159         tcg_init_vcpu(env);
   4160 }
   4161 
   4162 void qemu_notify_event(void)
   4163 {
   4164     qemu_event_increment();
   4165 }
   4166 
   4167 void vm_stop(int reason)
   4168 {
   4169     QemuThread me;
   4170     qemu_thread_self(&me);
   4171 
   4172     if (!qemu_thread_equal(&me, &io_thread)) {
   4173         qemu_system_vmstop_request(reason);
   4174         /*
   4175          * FIXME: should not return to device code in case
   4176          * vm_stop() has been requested.
   4177          */
   4178         if (cpu_single_env) {
   4179             cpu_exit(cpu_single_env);
   4180             cpu_single_env->stop = 1;
   4181         }
   4182         return;
   4183     }
   4184     do_vm_stop(reason);
   4185 }
   4186 
   4187 #endif
   4188 
   4189 
   4190 #ifdef _WIN32
   4191 static void host_main_loop_wait(int *timeout)
   4192 {
   4193     int ret, ret2, i;
   4194     PollingEntry *pe;
   4195 
   4196 
   4197     /* XXX: need to suppress polling by better using win32 events */
   4198     ret = 0;
   4199     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
   4200         ret |= pe->func(pe->opaque);
   4201     }
   4202     if (ret == 0) {
   4203         int err;
   4204         WaitObjects *w = &wait_objects;
   4205 
   4206         ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
   4207         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
   4208             if (w->func[ret - WAIT_OBJECT_0])
   4209                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
   4210 
   4211             /* Check for additional signaled events */
   4212             for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
   4213 
   4214                 /* Check if event is signaled */
   4215                 ret2 = WaitForSingleObject(w->events[i], 0);
   4216                 if(ret2 == WAIT_OBJECT_0) {
   4217                     if (w->func[i])
   4218                         w->func[i](w->opaque[i]);
   4219                 } else if (ret2 == WAIT_TIMEOUT) {
   4220                 } else {
   4221                     err = GetLastError();
   4222                     fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
   4223                 }
   4224             }
   4225         } else if (ret == WAIT_TIMEOUT) {
   4226         } else {
   4227             err = GetLastError();
   4228             fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
   4229         }
   4230     }
   4231 
   4232     *timeout = 0;
   4233 }
   4234 #else
   4235 static void host_main_loop_wait(int *timeout)
   4236 {
   4237 }
   4238 #endif
   4239 
   4240 void main_loop_wait(int timeout)
   4241 {
   4242     IOHandlerRecord *ioh;
   4243     fd_set rfds, wfds, xfds;
   4244     int ret, nfds;
   4245     struct timeval tv;
   4246 
   4247     qemu_bh_update_timeout(&timeout);
   4248 
   4249     host_main_loop_wait(&timeout);
   4250 
   4251     /* poll any events */
   4252     /* XXX: separate device handlers from system ones */
   4253     nfds = -1;
   4254     FD_ZERO(&rfds);
   4255     FD_ZERO(&wfds);
   4256     FD_ZERO(&xfds);
   4257     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
   4258         if (ioh->deleted)
   4259             continue;
   4260         if (ioh->fd_read &&
   4261             (!ioh->fd_read_poll ||
   4262              ioh->fd_read_poll(ioh->opaque) != 0)) {
   4263             FD_SET(ioh->fd, &rfds);
   4264             if (ioh->fd > nfds)
   4265                 nfds = ioh->fd;
   4266         }
   4267         if (ioh->fd_write) {
   4268             FD_SET(ioh->fd, &wfds);
   4269             if (ioh->fd > nfds)
   4270                 nfds = ioh->fd;
   4271         }
   4272     }
   4273 
   4274     tv.tv_sec = timeout / 1000;
   4275     tv.tv_usec = (timeout % 1000) * 1000;
   4276 
   4277 #if defined(CONFIG_SLIRP)
   4278     if (slirp_is_inited()) {
   4279         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
   4280     }
   4281 #endif
   4282     qemu_mutex_unlock_iothread();
   4283     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
   4284     qemu_mutex_lock_iothread();
   4285     if (ret > 0) {
   4286         IOHandlerRecord **pioh;
   4287 
   4288         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
   4289             if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
   4290                 ioh->fd_read(ioh->opaque);
   4291             }
   4292             if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
   4293                 ioh->fd_write(ioh->opaque);
   4294             }
   4295         }
   4296 
   4297 	/* remove deleted IO handlers */
   4298 	pioh = &first_io_handler;
   4299 	while (*pioh) {
   4300             ioh = *pioh;
   4301             if (ioh->deleted) {
   4302                 *pioh = ioh->next;
   4303                 qemu_free(ioh);
   4304             } else
   4305                 pioh = &ioh->next;
   4306         }
   4307     }
   4308 #if defined(CONFIG_SLIRP)
   4309     if (slirp_is_inited()) {
   4310         if (ret < 0) {
   4311             FD_ZERO(&rfds);
   4312             FD_ZERO(&wfds);
   4313             FD_ZERO(&xfds);
   4314         }
   4315         slirp_select_poll(&rfds, &wfds, &xfds);
   4316     }
   4317 #endif
   4318 
   4319     /* rearm timer, if not periodic */
   4320     if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
   4321         alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
   4322         qemu_rearm_alarm_timer(alarm_timer);
   4323     }
   4324 
   4325     /* vm time timers */
   4326     if (vm_running) {
   4327         if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
   4328             qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
   4329                 qemu_get_clock(vm_clock));
   4330     }
   4331 
   4332     /* real time timers */
   4333     qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
   4334                     qemu_get_clock(rt_clock));
   4335 
   4336     qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
   4337                     qemu_get_clock(host_clock));
   4338 
   4339     /* Check bottom-halves last in case any of the earlier events triggered
   4340        them.  */
   4341     qemu_bh_poll();
   4342 
   4343 }
   4344 
   4345 static int qemu_cpu_exec(CPUState *env)
   4346 {
   4347     int ret;
   4348 #ifdef CONFIG_PROFILER
   4349     int64_t ti;
   4350 #endif
   4351 
   4352 #ifdef CONFIG_PROFILER
   4353     ti = profile_getclock();
   4354 #endif
   4355     if (use_icount) {
   4356         int64_t count;
   4357         int decr;
   4358         qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
   4359         env->icount_decr.u16.low = 0;
   4360         env->icount_extra = 0;
   4361         count = qemu_next_deadline();
   4362         count = (count + (1 << icount_time_shift) - 1)
   4363                 >> icount_time_shift;
   4364         qemu_icount += count;
   4365         decr = (count > 0xffff) ? 0xffff : count;
   4366         count -= decr;
   4367         env->icount_decr.u16.low = decr;
   4368         env->icount_extra = count;
   4369     }
   4370     ret = cpu_exec(env);
   4371 #ifdef CONFIG_PROFILER
   4372     qemu_time += profile_getclock() - ti;
   4373 #endif
   4374     if (use_icount) {
   4375         /* Fold pending instructions back into the
   4376            instruction counter, and clear the interrupt flag.  */
   4377         qemu_icount -= (env->icount_decr.u16.low
   4378                         + env->icount_extra);
   4379         env->icount_decr.u32 = 0;
   4380         env->icount_extra = 0;
   4381     }
   4382     return ret;
   4383 }
   4384 
   4385 static void tcg_cpu_exec(void)
   4386 {
   4387     int ret = 0;
   4388 
   4389     if (next_cpu == NULL)
   4390         next_cpu = first_cpu;
   4391     for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
   4392         CPUState *env = cur_cpu = next_cpu;
   4393 
   4394         if (timer_alarm_pending) {
   4395             timer_alarm_pending = 0;
   4396             break;
   4397         }
   4398         if (cpu_can_run(env))
   4399             ret = qemu_cpu_exec(env);
   4400         else if (env->stop)
   4401             break;
   4402 
   4403         if (ret == EXCP_DEBUG) {
   4404             gdb_set_stop_cpu(env);
   4405             debug_requested = 1;
   4406             break;
   4407         }
   4408     }
   4409 }
   4410 
   4411 static int cpu_has_work(CPUState *env)
   4412 {
   4413     if (env->stop)
   4414         return 1;
   4415     if (env->stopped)
   4416         return 0;
   4417     if (!env->halted)
   4418         return 1;
   4419     if (qemu_cpu_has_work(env))
   4420         return 1;
   4421     return 0;
   4422 }
   4423 
   4424 static int tcg_has_work(void)
   4425 {
   4426     CPUState *env;
   4427 
   4428     for (env = first_cpu; env != NULL; env = env->next_cpu)
   4429         if (cpu_has_work(env))
   4430             return 1;
   4431     return 0;
   4432 }
   4433 
   4434 static int qemu_calculate_timeout(void)
   4435 {
   4436 #ifndef CONFIG_IOTHREAD
   4437     int timeout;
   4438 
   4439     if (!vm_running)
   4440         timeout = 5000;
   4441     else if (tcg_has_work())
   4442         timeout = 0;
   4443     else if (!use_icount)
   4444         timeout = 5000;
   4445     else {
   4446      /* XXX: use timeout computed from timers */
   4447         int64_t add;
   4448         int64_t delta;
   4449         /* Advance virtual time to the next event.  */
   4450         if (use_icount == 1) {
   4451             /* When not using an adaptive execution frequency
   4452                we tend to get badly out of sync with real time,
   4453                so just delay for a reasonable amount of time.  */
   4454             delta = 0;
   4455         } else {
   4456             delta = cpu_get_icount() - cpu_get_clock();
   4457         }
   4458         if (delta > 0) {
   4459             /* If virtual time is ahead of real time then just
   4460                wait for IO.  */
   4461             timeout = (delta / 1000000) + 1;
   4462         } else {
   4463             /* Wait for either IO to occur or the next
   4464                timer event.  */
   4465             add = qemu_next_deadline();
   4466             /* We advance the timer before checking for IO.
   4467                Limit the amount we advance so that early IO
   4468                activity won't get the guest too far ahead.  */
   4469             if (add > 10000000)
   4470                 add = 10000000;
   4471             delta += add;
   4472             add = (add + (1 << icount_time_shift) - 1)
   4473                   >> icount_time_shift;
   4474             qemu_icount += add;
   4475             timeout = delta / 1000000;
   4476             if (timeout < 0)
   4477                 timeout = 0;
   4478         }
   4479     }
   4480 
   4481     return timeout;
   4482 #else /* CONFIG_IOTHREAD */
   4483     return 1000;
   4484 #endif
   4485 }
   4486 
   4487 static int vm_can_run(void)
   4488 {
   4489     if (powerdown_requested)
   4490         return 0;
   4491     if (reset_requested)
   4492         return 0;
   4493     if (shutdown_requested)
   4494         return 0;
   4495     if (debug_requested)
   4496         return 0;
   4497     return 1;
   4498 }
   4499 
   4500 static void main_loop(void)
   4501 {
   4502     int r;
   4503 
   4504 #ifdef CONFIG_IOTHREAD
   4505     qemu_system_ready = 1;
   4506     qemu_cond_broadcast(&qemu_system_cond);
   4507 #endif
   4508 
   4509     for (;;) {
   4510         do {
   4511 #ifdef CONFIG_PROFILER
   4512             int64_t ti;
   4513 #endif
   4514 #ifndef CONFIG_IOTHREAD
   4515             tcg_cpu_exec();
   4516 #endif
   4517 #ifdef CONFIG_PROFILER
   4518             ti = profile_getclock();
   4519 #endif
   4520             main_loop_wait(qemu_calculate_timeout());
   4521 #ifdef CONFIG_PROFILER
   4522             dev_time += profile_getclock() - ti;
   4523 #endif
   4524         } while (vm_can_run());
   4525 
   4526         if (qemu_debug_requested())
   4527             vm_stop(EXCP_DEBUG);
   4528         if (qemu_shutdown_requested()) {
   4529             if (no_shutdown) {
   4530                 vm_stop(0);
   4531                 no_shutdown = 0;
   4532             } else
   4533                 break;
   4534         }
   4535         if (qemu_reset_requested()) {
   4536             pause_all_vcpus();
   4537             qemu_system_reset();
   4538             resume_all_vcpus();
   4539         }
   4540         if (qemu_powerdown_requested())
   4541             qemu_system_powerdown();
   4542         if ((r = qemu_vmstop_requested()))
   4543             vm_stop(r);
   4544     }
   4545     pause_all_vcpus();
   4546 }
   4547 
   4548 static void version(void)
   4549 {
   4550     printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
   4551 }
   4552 
   4553 static void help(int exitcode)
   4554 {
   4555     version();
   4556     printf("usage: %s [options] [disk_image]\n"
   4557            "\n"
   4558            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
   4559            "\n"
   4560 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   4561            opt_help
   4562 #define DEFHEADING(text) stringify(text) "\n"
   4563 #include "qemu-options.h"
   4564 #undef DEF
   4565 #undef DEFHEADING
   4566 #undef GEN_DOCS
   4567            "\n"
   4568            "During emulation, the following keys are useful:\n"
   4569            "ctrl-alt-f      toggle full screen\n"
   4570            "ctrl-alt-n      switch to virtual console 'n'\n"
   4571            "ctrl-alt        toggle mouse and keyboard grab\n"
   4572            "\n"
   4573            "When using -nographic, press 'ctrl-a h' to get some help.\n"
   4574            ,
   4575            "qemu",
   4576            DEFAULT_RAM_SIZE,
   4577 #ifndef _WIN32
   4578            DEFAULT_NETWORK_SCRIPT,
   4579            DEFAULT_NETWORK_DOWN_SCRIPT,
   4580 #endif
   4581            DEFAULT_GDBSTUB_PORT,
   4582            "/tmp/qemu.log");
   4583     exit(exitcode);
   4584 }
   4585 
   4586 #define HAS_ARG 0x0001
   4587 
   4588 enum {
   4589 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   4590     opt_enum,
   4591 #define DEFHEADING(text)
   4592 #include "qemu-options.h"
   4593 #undef DEF
   4594 #undef DEFHEADING
   4595 #undef GEN_DOCS
   4596 };
   4597 
   4598 typedef struct QEMUOption {
   4599     const char *name;
   4600     int flags;
   4601     int index;
   4602 } QEMUOption;
   4603 
   4604 static const QEMUOption qemu_options[] = {
   4605     { "h", 0, QEMU_OPTION_h },
   4606 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   4607     { option, opt_arg, opt_enum },
   4608 #define DEFHEADING(text)
   4609 #include "qemu-options.h"
   4610 #undef DEF
   4611 #undef DEFHEADING
   4612 #undef GEN_DOCS
   4613     { NULL },
   4614 };
   4615 
   4616 #ifdef HAS_AUDIO
   4617 struct soundhw soundhw[] = {
   4618 #ifdef HAS_AUDIO_CHOICE
   4619 #if defined(TARGET_I386) || defined(TARGET_MIPS)
   4620     {
   4621         "pcspk",
   4622         "PC speaker",
   4623         0,
   4624         1,
   4625         { .init_isa = pcspk_audio_init }
   4626     },
   4627 #endif
   4628 
   4629 #ifdef CONFIG_SB16
   4630     {
   4631         "sb16",
   4632         "Creative Sound Blaster 16",
   4633         0,
   4634         1,
   4635         { .init_isa = SB16_init }
   4636     },
   4637 #endif
   4638 
   4639 #ifdef CONFIG_CS4231A
   4640     {
   4641         "cs4231a",
   4642         "CS4231A",
   4643         0,
   4644         1,
   4645         { .init_isa = cs4231a_init }
   4646     },
   4647 #endif
   4648 
   4649 #ifdef CONFIG_ADLIB
   4650     {
   4651         "adlib",
   4652 #ifdef HAS_YMF262
   4653         "Yamaha YMF262 (OPL3)",
   4654 #else
   4655         "Yamaha YM3812 (OPL2)",
   4656 #endif
   4657         0,
   4658         1,
   4659         { .init_isa = Adlib_init }
   4660     },
   4661 #endif
   4662 
   4663 #ifdef CONFIG_GUS
   4664     {
   4665         "gus",
   4666         "Gravis Ultrasound GF1",
   4667         0,
   4668         1,
   4669         { .init_isa = GUS_init }
   4670     },
   4671 #endif
   4672 
   4673 #ifdef CONFIG_AC97
   4674     {
   4675         "ac97",
   4676         "Intel 82801AA AC97 Audio",
   4677         0,
   4678         0,
   4679         { .init_pci = ac97_init }
   4680     },
   4681 #endif
   4682 
   4683 #ifdef CONFIG_ES1370
   4684     {
   4685         "es1370",
   4686         "ENSONIQ AudioPCI ES1370",
   4687         0,
   4688         0,
   4689         { .init_pci = es1370_init }
   4690     },
   4691 #endif
   4692 
   4693 #endif /* HAS_AUDIO_CHOICE */
   4694 
   4695     { NULL, NULL, 0, 0, { NULL } }
   4696 };
   4697 
   4698 static void select_soundhw (const char *optarg)
   4699 {
   4700     struct soundhw *c;
   4701 
   4702     if (*optarg == '?') {
   4703     show_valid_cards:
   4704 
   4705         printf ("Valid sound card names (comma separated):\n");
   4706         for (c = soundhw; c->name; ++c) {
   4707             printf ("%-11s %s\n", c->name, c->descr);
   4708         }
   4709         printf ("\n-soundhw all will enable all of the above\n");
   4710         exit (*optarg != '?');
   4711     }
   4712     else {
   4713         size_t l;
   4714         const char *p;
   4715         char *e;
   4716         int bad_card = 0;
   4717 
   4718         if (!strcmp (optarg, "all")) {
   4719             for (c = soundhw; c->name; ++c) {
   4720                 c->enabled = 1;
   4721             }
   4722             return;
   4723         }
   4724 
   4725         p = optarg;
   4726         while (*p) {
   4727             e = strchr (p, ',');
   4728             l = !e ? strlen (p) : (size_t) (e - p);
   4729 
   4730             for (c = soundhw; c->name; ++c) {
   4731                 if (!strncmp (c->name, p, l)) {
   4732                     c->enabled = 1;
   4733                     break;
   4734                 }
   4735             }
   4736 
   4737             if (!c->name) {
   4738                 if (l > 80) {
   4739                     fprintf (stderr,
   4740                              "Unknown sound card name (too big to show)\n");
   4741                 }
   4742                 else {
   4743                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
   4744                              (int) l, p);
   4745                 }
   4746                 bad_card = 1;
   4747             }
   4748             p += l + (e != NULL);
   4749         }
   4750 
   4751         if (bad_card)
   4752             goto show_valid_cards;
   4753     }
   4754 }
   4755 #endif
   4756 
   4757 static void select_vgahw (const char *p)
   4758 {
   4759     const char *opts;
   4760 
   4761     cirrus_vga_enabled = 0;
   4762     std_vga_enabled = 0;
   4763     vmsvga_enabled = 0;
   4764     xenfb_enabled = 0;
   4765     if (strstart(p, "std", &opts)) {
   4766         std_vga_enabled = 1;
   4767     } else if (strstart(p, "cirrus", &opts)) {
   4768         cirrus_vga_enabled = 1;
   4769     } else if (strstart(p, "vmware", &opts)) {
   4770         vmsvga_enabled = 1;
   4771     } else if (strstart(p, "xenfb", &opts)) {
   4772         xenfb_enabled = 1;
   4773     } else if (!strstart(p, "none", &opts)) {
   4774     invalid_vga:
   4775         fprintf(stderr, "Unknown vga type: %s\n", p);
   4776         exit(1);
   4777     }
   4778     while (*opts) {
   4779         const char *nextopt;
   4780 
   4781         if (strstart(opts, ",retrace=", &nextopt)) {
   4782             opts = nextopt;
   4783             if (strstart(opts, "dumb", &nextopt))
   4784                 vga_retrace_method = VGA_RETRACE_DUMB;
   4785             else if (strstart(opts, "precise", &nextopt))
   4786                 vga_retrace_method = VGA_RETRACE_PRECISE;
   4787             else goto invalid_vga;
   4788         } else goto invalid_vga;
   4789         opts = nextopt;
   4790     }
   4791 }
   4792 
   4793 #ifdef _WIN32
   4794 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
   4795 {
   4796     exit(STATUS_CONTROL_C_EXIT);
   4797     return TRUE;
   4798 }
   4799 #endif
   4800 
   4801 int qemu_uuid_parse(const char *str, uint8_t *uuid)
   4802 {
   4803     int ret;
   4804 
   4805     if(strlen(str) != 36)
   4806         return -1;
   4807 
   4808     ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
   4809             &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
   4810             &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
   4811 
   4812     if(ret != 16)
   4813         return -1;
   4814 
   4815 #ifdef TARGET_I386
   4816     smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
   4817 #endif
   4818 
   4819     return 0;
   4820 }
   4821 
   4822 #define MAX_NET_CLIENTS 32
   4823 
   4824 #ifndef _WIN32
   4825 
   4826 static void termsig_handler(int signal)
   4827 {
   4828     qemu_system_shutdown_request();
   4829 }
   4830 
   4831 static void sigchld_handler(int signal)
   4832 {
   4833     waitpid(-1, NULL, WNOHANG);
   4834 }
   4835 
   4836 static void sighandler_setup(void)
   4837 {
   4838     struct sigaction act;
   4839 
   4840     memset(&act, 0, sizeof(act));
   4841     act.sa_handler = termsig_handler;
   4842     sigaction(SIGINT,  &act, NULL);
   4843     sigaction(SIGHUP,  &act, NULL);
   4844     sigaction(SIGTERM, &act, NULL);
   4845 
   4846     act.sa_handler = sigchld_handler;
   4847     act.sa_flags = SA_NOCLDSTOP;
   4848     sigaction(SIGCHLD, &act, NULL);
   4849 }
   4850 
   4851 #endif
   4852 
   4853 #ifdef _WIN32
   4854 /* Look for support files in the same directory as the executable.  */
   4855 static char *find_datadir(const char *argv0)
   4856 {
   4857     char *p;
   4858     char buf[MAX_PATH];
   4859     DWORD len;
   4860 
   4861     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
   4862     if (len == 0) {
   4863         return NULL;
   4864     }
   4865 
   4866     buf[len] = 0;
   4867     p = buf + len - 1;
   4868     while (p != buf && *p != '\\')
   4869         p--;
   4870     *p = 0;
   4871     if (access(buf, R_OK) == 0) {
   4872         return qemu_strdup(buf);
   4873     }
   4874     return NULL;
   4875 }
   4876 #else /* !_WIN32 */
   4877 
   4878 /* Find a likely location for support files using the location of the binary.
   4879    For installed binaries this will be "$bindir/../share/qemu".  When
   4880    running from the build tree this will be "$bindir/../pc-bios".  */
   4881 #define SHARE_SUFFIX "/share/qemu"
   4882 #define BUILD_SUFFIX "/pc-bios"
   4883 static char *find_datadir(const char *argv0)
   4884 {
   4885     char *dir;
   4886     char *p = NULL;
   4887     char *res;
   4888 #ifdef PATH_MAX
   4889     char buf[PATH_MAX];
   4890 #endif
   4891     size_t max_len;
   4892 
   4893 #if defined(__linux__)
   4894     {
   4895         int len;
   4896         len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
   4897         if (len > 0) {
   4898             buf[len] = 0;
   4899             p = buf;
   4900         }
   4901     }
   4902 #elif defined(__FreeBSD__)
   4903     {
   4904         int len;
   4905         len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
   4906         if (len > 0) {
   4907             buf[len] = 0;
   4908             p = buf;
   4909         }
   4910     }
   4911 #endif
   4912     /* If we don't have any way of figuring out the actual executable
   4913        location then try argv[0].  */
   4914     if (!p) {
   4915 #ifdef PATH_MAX
   4916         p = buf;
   4917 #endif
   4918         p = realpath(argv0, p);
   4919         if (!p) {
   4920             return NULL;
   4921         }
   4922     }
   4923     dir = dirname(p);
   4924     dir = dirname(dir);
   4925 
   4926     max_len = strlen(dir) +
   4927         MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
   4928     res = qemu_mallocz(max_len);
   4929     snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
   4930     if (access(res, R_OK)) {
   4931         snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
   4932         if (access(res, R_OK)) {
   4933             qemu_free(res);
   4934             res = NULL;
   4935         }
   4936     }
   4937 #ifndef PATH_MAX
   4938     free(p);
   4939 #endif
   4940     return res;
   4941 }
   4942 #undef SHARE_SUFFIX
   4943 #undef BUILD_SUFFIX
   4944 #endif
   4945 
   4946 char *qemu_find_file(int type, const char *name)
   4947 {
   4948     int len;
   4949     const char *subdir;
   4950     char *buf;
   4951 
   4952     /* If name contains path separators then try it as a straight path.  */
   4953     if ((strchr(name, '/') || strchr(name, '\\'))
   4954         && access(name, R_OK) == 0) {
   4955         return strdup(name);
   4956     }
   4957     switch (type) {
   4958     case QEMU_FILE_TYPE_BIOS:
   4959         subdir = "";
   4960         break;
   4961     case QEMU_FILE_TYPE_KEYMAP:
   4962         subdir = "keymaps/";
   4963         break;
   4964     default:
   4965         abort();
   4966     }
   4967     len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
   4968     buf = qemu_mallocz(len);
   4969     snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
   4970     if (access(buf, R_OK)) {
   4971         qemu_free(buf);
   4972         return NULL;
   4973     }
   4974     return buf;
   4975 }
   4976 
   4977 int main(int argc, char **argv, char **envp)
   4978 {
   4979     const char *gdbstub_dev = NULL;
   4980     uint32_t boot_devices_bitmap = 0;
   4981     int i;
   4982     int snapshot, linux_boot, net_boot;
   4983     const char *initrd_filename;
   4984     const char *kernel_filename, *kernel_cmdline;
   4985     const char *boot_devices = "";
   4986     DisplayState *ds;
   4987     DisplayChangeListener *dcl;
   4988     int cyls, heads, secs, translation;
   4989     const char *net_clients[MAX_NET_CLIENTS];
   4990     int nb_net_clients;
   4991     const char *bt_opts[MAX_BT_CMDLINE];
   4992     int nb_bt_opts;
   4993     int hda_index;
   4994     int optind;
   4995     const char *r, *optarg;
   4996     CharDriverState *monitor_hd = NULL;
   4997     const char *monitor_device;
   4998     const char *serial_devices[MAX_SERIAL_PORTS];
   4999     int serial_device_index;
   5000     const char *parallel_devices[MAX_PARALLEL_PORTS];
   5001     int parallel_device_index;
   5002     const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
   5003     int virtio_console_index;
   5004     const char *loadvm = NULL;
   5005     QEMUMachine *machine;
   5006     const char *cpu_model;
   5007     const char *usb_devices[MAX_USB_CMDLINE];
   5008     int usb_devices_index;
   5009 #ifndef _WIN32
   5010     int fds[2];
   5011 #endif
   5012     int tb_size;
   5013     const char *pid_file = NULL;
   5014     const char *incoming = NULL;
   5015 #ifndef _WIN32
   5016     int fd = 0;
   5017     struct passwd *pwd = NULL;
   5018     const char *chroot_dir = NULL;
   5019     const char *run_as = NULL;
   5020 #endif
   5021     CPUState *env;
   5022     int show_vnc_port = 0;
   5023 
   5024     init_clocks();
   5025 
   5026     qemu_cache_utils_init(envp);
   5027 
   5028     QLIST_INIT (&vm_change_state_head);
   5029 #ifndef _WIN32
   5030     {
   5031         struct sigaction act;
   5032         sigfillset(&act.sa_mask);
   5033         act.sa_flags = 0;
   5034         act.sa_handler = SIG_IGN;
   5035         sigaction(SIGPIPE, &act, NULL);
   5036     }
   5037 #else
   5038     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
   5039     /* Note: cpu_interrupt() is currently not SMP safe, so we force
   5040        QEMU to run on a single CPU */
   5041     {
   5042         HANDLE h;
   5043         DWORD mask, smask;
   5044         int i;
   5045         h = GetCurrentProcess();
   5046         if (GetProcessAffinityMask(h, &mask, &smask)) {
   5047             for(i = 0; i < 32; i++) {
   5048                 if (mask & (1 << i))
   5049                     break;
   5050             }
   5051             if (i != 32) {
   5052                 mask = 1 << i;
   5053                 SetProcessAffinityMask(h, mask);
   5054             }
   5055         }
   5056     }
   5057 #endif
   5058 
   5059     module_call_init(MODULE_INIT_MACHINE);
   5060     machine = find_default_machine();
   5061     cpu_model = NULL;
   5062     initrd_filename = NULL;
   5063     ram_size = 0;
   5064     snapshot = 0;
   5065     kernel_filename = NULL;
   5066     kernel_cmdline = "";
   5067     cyls = heads = secs = 0;
   5068     translation = BIOS_ATA_TRANSLATION_AUTO;
   5069     monitor_device = "vc:80Cx24C";
   5070 
   5071     serial_devices[0] = "vc:80Cx24C";
   5072     for(i = 1; i < MAX_SERIAL_PORTS; i++)
   5073         serial_devices[i] = NULL;
   5074     serial_device_index = 0;
   5075 
   5076     parallel_devices[0] = "vc:80Cx24C";
   5077     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
   5078         parallel_devices[i] = NULL;
   5079     parallel_device_index = 0;
   5080 
   5081     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
   5082         virtio_consoles[i] = NULL;
   5083     virtio_console_index = 0;
   5084 
   5085     for (i = 0; i < MAX_NODES; i++) {
   5086         node_mem[i] = 0;
   5087         node_cpumask[i] = 0;
   5088     }
   5089 
   5090     usb_devices_index = 0;
   5091 
   5092     nb_net_clients = 0;
   5093     nb_bt_opts = 0;
   5094     nb_drives = 0;
   5095     nb_drives_opt = 0;
   5096     nb_numa_nodes = 0;
   5097     hda_index = -1;
   5098 
   5099     nb_nics = 0;
   5100 
   5101     tb_size = 0;
   5102     autostart= 1;
   5103 
   5104     register_watchdogs();
   5105 
   5106     optind = 1;
   5107     for(;;) {
   5108         if (optind >= argc)
   5109             break;
   5110         r = argv[optind];
   5111         if (r[0] != '-') {
   5112 	    hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
   5113         } else {
   5114             const QEMUOption *popt;
   5115 
   5116             optind++;
   5117             /* Treat --foo the same as -foo.  */
   5118             if (r[1] == '-')
   5119                 r++;
   5120             popt = qemu_options;
   5121             for(;;) {
   5122                 if (!popt->name) {
   5123                     fprintf(stderr, "%s: invalid option -- '%s'\n",
   5124                             argv[0], r);
   5125                     exit(1);
   5126                 }
   5127                 if (!strcmp(popt->name, r + 1))
   5128                     break;
   5129                 popt++;
   5130             }
   5131             if (popt->flags & HAS_ARG) {
   5132                 if (optind >= argc) {
   5133                     fprintf(stderr, "%s: option '%s' requires an argument\n",
   5134                             argv[0], r);
   5135                     exit(1);
   5136                 }
   5137                 optarg = argv[optind++];
   5138             } else {
   5139                 optarg = NULL;
   5140             }
   5141 
   5142             switch(popt->index) {
   5143             case QEMU_OPTION_M:
   5144                 machine = find_machine(optarg);
   5145                 if (!machine) {
   5146                     QEMUMachine *m;
   5147                     printf("Supported machines are:\n");
   5148                     for(m = first_machine; m != NULL; m = m->next) {
   5149                         printf("%-10s %s%s\n",
   5150                                m->name, m->desc,
   5151                                m->is_default ? " (default)" : "");
   5152                     }
   5153                     exit(*optarg != '?');
   5154                 }
   5155                 break;
   5156             case QEMU_OPTION_cpu:
   5157                 /* hw initialization will check this */
   5158                 if (*optarg == '?') {
   5159 /* XXX: implement xxx_cpu_list for targets that still miss it */
   5160 #if defined(cpu_list)
   5161                     cpu_list(stdout, &fprintf);
   5162 #endif
   5163                     exit(0);
   5164                 } else {
   5165                     cpu_model = optarg;
   5166                 }
   5167                 break;
   5168             case QEMU_OPTION_initrd:
   5169                 initrd_filename = optarg;
   5170                 break;
   5171             case QEMU_OPTION_hda:
   5172                 if (cyls == 0)
   5173                     hda_index = drive_add(optarg, HD_ALIAS, 0);
   5174                 else
   5175                     hda_index = drive_add(optarg, HD_ALIAS
   5176 			     ",cyls=%d,heads=%d,secs=%d%s",
   5177                              0, cyls, heads, secs,
   5178                              translation == BIOS_ATA_TRANSLATION_LBA ?
   5179                                  ",trans=lba" :
   5180                              translation == BIOS_ATA_TRANSLATION_NONE ?
   5181                                  ",trans=none" : "");
   5182                  break;
   5183             case QEMU_OPTION_hdb:
   5184             case QEMU_OPTION_hdc:
   5185             case QEMU_OPTION_hdd:
   5186                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
   5187                 break;
   5188             case QEMU_OPTION_drive:
   5189                 drive_add(NULL, "%s", optarg);
   5190 	        break;
   5191             case QEMU_OPTION_mtdblock:
   5192                 drive_add(optarg, MTD_ALIAS);
   5193                 break;
   5194             case QEMU_OPTION_sd:
   5195                 drive_add(optarg, SD_ALIAS);
   5196                 break;
   5197             case QEMU_OPTION_pflash:
   5198                 drive_add(optarg, PFLASH_ALIAS);
   5199                 break;
   5200             case QEMU_OPTION_snapshot:
   5201                 snapshot = 1;
   5202                 break;
   5203             case QEMU_OPTION_hdachs:
   5204                 {
   5205                     const char *p;
   5206                     p = optarg;
   5207                     cyls = strtol(p, (char **)&p, 0);
   5208                     if (cyls < 1 || cyls > 16383)
   5209                         goto chs_fail;
   5210                     if (*p != ',')
   5211                         goto chs_fail;
   5212                     p++;
   5213                     heads = strtol(p, (char **)&p, 0);
   5214                     if (heads < 1 || heads > 16)
   5215                         goto chs_fail;
   5216                     if (*p != ',')
   5217                         goto chs_fail;
   5218                     p++;
   5219                     secs = strtol(p, (char **)&p, 0);
   5220                     if (secs < 1 || secs > 63)
   5221                         goto chs_fail;
   5222                     if (*p == ',') {
   5223                         p++;
   5224                         if (!strcmp(p, "none"))
   5225                             translation = BIOS_ATA_TRANSLATION_NONE;
   5226                         else if (!strcmp(p, "lba"))
   5227                             translation = BIOS_ATA_TRANSLATION_LBA;
   5228                         else if (!strcmp(p, "auto"))
   5229                             translation = BIOS_ATA_TRANSLATION_AUTO;
   5230                         else
   5231                             goto chs_fail;
   5232                     } else if (*p != '\0') {
   5233                     chs_fail:
   5234                         fprintf(stderr, "qemu: invalid physical CHS format\n");
   5235                         exit(1);
   5236                     }
   5237 		    if (hda_index != -1)
   5238                         snprintf(drives_opt[hda_index].opt,
   5239                                  sizeof(drives_opt[hda_index].opt),
   5240                                  HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
   5241                                  0, cyls, heads, secs,
   5242 			         translation == BIOS_ATA_TRANSLATION_LBA ?
   5243 			     	    ",trans=lba" :
   5244 			         translation == BIOS_ATA_TRANSLATION_NONE ?
   5245 			             ",trans=none" : "");
   5246                 }
   5247                 break;
   5248             case QEMU_OPTION_numa:
   5249                 if (nb_numa_nodes >= MAX_NODES) {
   5250                     fprintf(stderr, "qemu: too many NUMA nodes\n");
   5251                     exit(1);
   5252                 }
   5253                 numa_add(optarg);
   5254                 break;
   5255             case QEMU_OPTION_nographic:
   5256                 display_type = DT_NOGRAPHIC;
   5257                 break;
   5258 #ifdef CONFIG_CURSES
   5259             case QEMU_OPTION_curses:
   5260                 display_type = DT_CURSES;
   5261                 break;
   5262 #endif
   5263             case QEMU_OPTION_portrait:
   5264                 graphic_rotate = 1;
   5265                 break;
   5266             case QEMU_OPTION_kernel:
   5267                 kernel_filename = optarg;
   5268                 break;
   5269             case QEMU_OPTION_append:
   5270                 kernel_cmdline = optarg;
   5271                 break;
   5272             case QEMU_OPTION_cdrom:
   5273                 drive_add(optarg, CDROM_ALIAS);
   5274                 break;
   5275             case QEMU_OPTION_boot:
   5276                 boot_devices = optarg;
   5277                 /* We just do some generic consistency checks */
   5278                 {
   5279                     /* Could easily be extended to 64 devices if needed */
   5280                     const char *p;
   5281 
   5282                     boot_devices_bitmap = 0;
   5283                     for (p = boot_devices; *p != '\0'; p++) {
   5284                         /* Allowed boot devices are:
   5285                          * a b     : floppy disk drives
   5286                          * c ... f : IDE disk drives
   5287                          * g ... m : machine implementation dependant drives
   5288                          * n ... p : network devices
   5289                          * It's up to each machine implementation to check
   5290                          * if the given boot devices match the actual hardware
   5291                          * implementation and firmware features.
   5292                          */
   5293                         if (*p < 'a' || *p > 'q') {
   5294                             fprintf(stderr, "Invalid boot device '%c'\n", *p);
   5295                             exit(1);
   5296                         }
   5297                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
   5298                             fprintf(stderr,
   5299                                     "Boot device '%c' was given twice\n",*p);
   5300                             exit(1);
   5301                         }
   5302                         boot_devices_bitmap |= 1 << (*p - 'a');
   5303                     }
   5304                 }
   5305                 break;
   5306             case QEMU_OPTION_fda:
   5307             case QEMU_OPTION_fdb:
   5308                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
   5309                 break;
   5310 #ifdef TARGET_I386
   5311             case QEMU_OPTION_no_fd_bootchk:
   5312                 fd_bootchk = 0;
   5313                 break;
   5314 #endif
   5315             case QEMU_OPTION_net:
   5316                 if (nb_net_clients >= MAX_NET_CLIENTS) {
   5317                     fprintf(stderr, "qemu: too many network clients\n");
   5318                     exit(1);
   5319                 }
   5320                 net_clients[nb_net_clients] = optarg;
   5321                 nb_net_clients++;
   5322                 break;
   5323 #ifdef CONFIG_SLIRP
   5324             case QEMU_OPTION_tftp:
   5325 		tftp_prefix = optarg;
   5326                 break;
   5327             case QEMU_OPTION_bootp:
   5328                 bootp_filename = optarg;
   5329                 break;
   5330 #ifndef _WIN32
   5331             case QEMU_OPTION_smb:
   5332 		net_slirp_smb(optarg);
   5333                 break;
   5334 #endif
   5335             case QEMU_OPTION_redir:
   5336                 net_slirp_redir(NULL, optarg, NULL);
   5337                 break;
   5338 #endif
   5339             case QEMU_OPTION_bt:
   5340                 if (nb_bt_opts >= MAX_BT_CMDLINE) {
   5341                     fprintf(stderr, "qemu: too many bluetooth options\n");
   5342                     exit(1);
   5343                 }
   5344                 bt_opts[nb_bt_opts++] = optarg;
   5345                 break;
   5346 #ifdef HAS_AUDIO
   5347             case QEMU_OPTION_audio_help:
   5348                 AUD_help ();
   5349                 exit (0);
   5350                 break;
   5351             case QEMU_OPTION_soundhw:
   5352                 select_soundhw (optarg);
   5353                 break;
   5354 #endif
   5355             case QEMU_OPTION_h:
   5356                 help(0);
   5357                 break;
   5358             case QEMU_OPTION_version:
   5359                 version();
   5360                 exit(0);
   5361                 break;
   5362             case QEMU_OPTION_m: {
   5363                 uint64_t value;
   5364                 char *ptr;
   5365 
   5366                 value = strtoul(optarg, &ptr, 10);
   5367                 switch (*ptr) {
   5368                 case 0: case 'M': case 'm':
   5369                     value <<= 20;
   5370                     break;
   5371                 case 'G': case 'g':
   5372                     value <<= 30;
   5373                     break;
   5374                 default:
   5375                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
   5376                     exit(1);
   5377                 }
   5378 
   5379                 /* On 32-bit hosts, QEMU is limited by virtual address space */
   5380                 if (value > (2047 << 20)
   5381 #ifndef CONFIG_KQEMU
   5382                     && HOST_LONG_BITS == 32
   5383 #endif
   5384                     ) {
   5385                     fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
   5386                     exit(1);
   5387                 }
   5388                 if (value != (uint64_t)(ram_addr_t)value) {
   5389                     fprintf(stderr, "qemu: ram size too large\n");
   5390                     exit(1);
   5391                 }
   5392                 ram_size = value;
   5393                 break;
   5394             }
   5395             case QEMU_OPTION_d:
   5396                 {
   5397                     int mask;
   5398                     const CPULogItem *item;
   5399 
   5400                     mask = cpu_str_to_log_mask(optarg);
   5401                     if (!mask) {
   5402                         printf("Log items (comma separated):\n");
   5403                     for(item = cpu_log_items; item->mask != 0; item++) {
   5404                         printf("%-10s %s\n", item->name, item->help);
   5405                     }
   5406                     exit(1);
   5407                     }
   5408                     cpu_set_log(mask);
   5409                 }
   5410                 break;
   5411             case QEMU_OPTION_s:
   5412                 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
   5413                 break;
   5414             case QEMU_OPTION_gdb:
   5415                 gdbstub_dev = optarg;
   5416                 break;
   5417             case QEMU_OPTION_L:
   5418                 data_dir = optarg;
   5419                 break;
   5420             case QEMU_OPTION_bios:
   5421                 bios_name = optarg;
   5422                 break;
   5423             case QEMU_OPTION_singlestep:
   5424                 singlestep = 1;
   5425                 break;
   5426             case QEMU_OPTION_S:
   5427                 autostart = 0;
   5428                 break;
   5429 #ifndef _WIN32
   5430 	    case QEMU_OPTION_k:
   5431 		keyboard_layout = optarg;
   5432 		break;
   5433 #endif
   5434             case QEMU_OPTION_localtime:
   5435                 rtc_utc = 0;
   5436                 break;
   5437             case QEMU_OPTION_vga:
   5438                 select_vgahw (optarg);
   5439                 break;
   5440 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
   5441             case QEMU_OPTION_g:
   5442                 {
   5443                     const char *p;
   5444                     int w, h, depth;
   5445                     p = optarg;
   5446                     w = strtol(p, (char **)&p, 10);
   5447                     if (w <= 0) {
   5448                     graphic_error:
   5449                         fprintf(stderr, "qemu: invalid resolution or depth\n");
   5450                         exit(1);
   5451                     }
   5452                     if (*p != 'x')
   5453                         goto graphic_error;
   5454                     p++;
   5455                     h = strtol(p, (char **)&p, 10);
   5456                     if (h <= 0)
   5457                         goto graphic_error;
   5458                     if (*p == 'x') {
   5459                         p++;
   5460                         depth = strtol(p, (char **)&p, 10);
   5461                         if (depth != 8 && depth != 15 && depth != 16 &&
   5462                             depth != 24 && depth != 32)
   5463                             goto graphic_error;
   5464                     } else if (*p == '\0') {
   5465                         depth = graphic_depth;
   5466                     } else {
   5467                         goto graphic_error;
   5468                     }
   5469 
   5470                     graphic_width = w;
   5471                     graphic_height = h;
   5472                     graphic_depth = depth;
   5473                 }
   5474                 break;
   5475 #endif
   5476             case QEMU_OPTION_echr:
   5477                 {
   5478                     char *r;
   5479                     term_escape_char = strtol(optarg, &r, 0);
   5480                     if (r == optarg)
   5481                         printf("Bad argument to echr\n");
   5482                     break;
   5483                 }
   5484             case QEMU_OPTION_monitor:
   5485                 monitor_device = optarg;
   5486                 break;
   5487             case QEMU_OPTION_serial:
   5488                 if (serial_device_index >= MAX_SERIAL_PORTS) {
   5489                     fprintf(stderr, "qemu: too many serial ports\n");
   5490                     exit(1);
   5491                 }
   5492                 serial_devices[serial_device_index] = optarg;
   5493                 serial_device_index++;
   5494                 break;
   5495             case QEMU_OPTION_watchdog:
   5496                 i = select_watchdog(optarg);
   5497                 if (i > 0)
   5498                     exit (i == 1 ? 1 : 0);
   5499                 break;
   5500             case QEMU_OPTION_watchdog_action:
   5501                 if (select_watchdog_action(optarg) == -1) {
   5502                     fprintf(stderr, "Unknown -watchdog-action parameter\n");
   5503                     exit(1);
   5504                 }
   5505                 break;
   5506             case QEMU_OPTION_virtiocon:
   5507                 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
   5508                     fprintf(stderr, "qemu: too many virtio consoles\n");
   5509                     exit(1);
   5510                 }
   5511                 virtio_consoles[virtio_console_index] = optarg;
   5512                 virtio_console_index++;
   5513                 break;
   5514             case QEMU_OPTION_parallel:
   5515                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
   5516                     fprintf(stderr, "qemu: too many parallel ports\n");
   5517                     exit(1);
   5518                 }
   5519                 parallel_devices[parallel_device_index] = optarg;
   5520                 parallel_device_index++;
   5521                 break;
   5522 	    case QEMU_OPTION_loadvm:
   5523 		loadvm = optarg;
   5524 		break;
   5525             case QEMU_OPTION_full_screen:
   5526                 full_screen = 1;
   5527                 break;
   5528 #ifdef CONFIG_SDL
   5529             case QEMU_OPTION_no_frame:
   5530                 no_frame = 1;
   5531                 break;
   5532             case QEMU_OPTION_alt_grab:
   5533                 alt_grab = 1;
   5534                 break;
   5535             case QEMU_OPTION_no_quit:
   5536                 no_quit = 1;
   5537                 break;
   5538             case QEMU_OPTION_sdl:
   5539                 display_type = DT_SDL;
   5540                 break;
   5541 #endif
   5542             case QEMU_OPTION_pidfile:
   5543                 pid_file = optarg;
   5544                 break;
   5545 #ifdef TARGET_I386
   5546             case QEMU_OPTION_win2k_hack:
   5547                 win2k_install_hack = 1;
   5548                 break;
   5549             case QEMU_OPTION_rtc_td_hack:
   5550                 rtc_td_hack = 1;
   5551                 break;
   5552             case QEMU_OPTION_acpitable:
   5553                 if(acpi_table_add(optarg) < 0) {
   5554                     fprintf(stderr, "Wrong acpi table provided\n");
   5555                     exit(1);
   5556                 }
   5557                 break;
   5558             case QEMU_OPTION_smbios:
   5559                 if(smbios_entry_add(optarg) < 0) {
   5560                     fprintf(stderr, "Wrong smbios provided\n");
   5561                     exit(1);
   5562                 }
   5563                 break;
   5564 #endif
   5565 #ifdef CONFIG_KQEMU
   5566             case QEMU_OPTION_no_kqemu:
   5567                 kqemu_allowed = 0;
   5568                 break;
   5569             case QEMU_OPTION_kernel_kqemu:
   5570                 kqemu_allowed = 2;
   5571                 break;
   5572 #endif
   5573 #ifdef CONFIG_KVM
   5574             case QEMU_OPTION_enable_kvm:
   5575                 kvm_allowed = 1;
   5576 #ifdef CONFIG_KQEMU
   5577                 kqemu_allowed = 0;
   5578 #endif
   5579                 break;
   5580 #endif
   5581             case QEMU_OPTION_usb:
   5582                 usb_enabled = 1;
   5583                 break;
   5584             case QEMU_OPTION_usbdevice:
   5585                 usb_enabled = 1;
   5586                 if (usb_devices_index >= MAX_USB_CMDLINE) {
   5587                     fprintf(stderr, "Too many USB devices\n");
   5588                     exit(1);
   5589                 }
   5590                 usb_devices[usb_devices_index] = optarg;
   5591                 usb_devices_index++;
   5592                 break;
   5593             case QEMU_OPTION_smp:
   5594                 smp_cpus = atoi(optarg);
   5595                 if (smp_cpus < 1) {
   5596                     fprintf(stderr, "Invalid number of CPUs\n");
   5597                     exit(1);
   5598                 }
   5599                 break;
   5600 	    case QEMU_OPTION_vnc:
   5601                 display_type = DT_VNC;
   5602 		vnc_display = optarg;
   5603 		break;
   5604 #ifdef TARGET_I386
   5605             case QEMU_OPTION_no_acpi:
   5606                 acpi_enabled = 0;
   5607                 break;
   5608             case QEMU_OPTION_no_hpet:
   5609                 no_hpet = 1;
   5610                 break;
   5611             case QEMU_OPTION_no_virtio_balloon:
   5612                 no_virtio_balloon = 1;
   5613                 break;
   5614 #endif
   5615             case QEMU_OPTION_no_reboot:
   5616                 no_reboot = 1;
   5617                 break;
   5618             case QEMU_OPTION_no_shutdown:
   5619                 no_shutdown = 1;
   5620                 break;
   5621             case QEMU_OPTION_show_cursor:
   5622                 cursor_hide = 0;
   5623                 break;
   5624             case QEMU_OPTION_uuid:
   5625                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
   5626                     fprintf(stderr, "Fail to parse UUID string."
   5627                             " Wrong format.\n");
   5628                     exit(1);
   5629                 }
   5630                 break;
   5631 #ifndef _WIN32
   5632 	    case QEMU_OPTION_daemonize:
   5633 		daemonize = 1;
   5634 		break;
   5635 #endif
   5636 	    case QEMU_OPTION_option_rom:
   5637 		if (nb_option_roms >= MAX_OPTION_ROMS) {
   5638 		    fprintf(stderr, "Too many option ROMs\n");
   5639 		    exit(1);
   5640 		}
   5641 		option_rom[nb_option_roms] = optarg;
   5642 		nb_option_roms++;
   5643 		break;
   5644 #if defined(TARGET_ARM) || defined(TARGET_M68K)
   5645             case QEMU_OPTION_semihosting:
   5646                 semihosting_enabled = 1;
   5647                 break;
   5648 #endif
   5649             case QEMU_OPTION_name:
   5650                 qemu_name = optarg;
   5651                 break;
   5652 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
   5653             case QEMU_OPTION_prom_env:
   5654                 if (nb_prom_envs >= MAX_PROM_ENVS) {
   5655                     fprintf(stderr, "Too many prom variables\n");
   5656                     exit(1);
   5657                 }
   5658                 prom_envs[nb_prom_envs] = optarg;
   5659                 nb_prom_envs++;
   5660                 break;
   5661 #endif
   5662 #ifdef TARGET_ARM
   5663             case QEMU_OPTION_old_param:
   5664                 old_param = 1;
   5665                 break;
   5666 #endif
   5667             case QEMU_OPTION_clock:
   5668                 configure_alarms(optarg);
   5669                 break;
   5670             case QEMU_OPTION_startdate:
   5671                 {
   5672                     struct tm tm;
   5673                     time_t rtc_start_date;
   5674                     if (!strcmp(optarg, "now")) {
   5675                         rtc_date_offset = -1;
   5676                     } else {
   5677                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
   5678                                &tm.tm_year,
   5679                                &tm.tm_mon,
   5680                                &tm.tm_mday,
   5681                                &tm.tm_hour,
   5682                                &tm.tm_min,
   5683                                &tm.tm_sec) == 6) {
   5684                             /* OK */
   5685                         } else if (sscanf(optarg, "%d-%d-%d",
   5686                                           &tm.tm_year,
   5687                                           &tm.tm_mon,
   5688                                           &tm.tm_mday) == 3) {
   5689                             tm.tm_hour = 0;
   5690                             tm.tm_min = 0;
   5691                             tm.tm_sec = 0;
   5692                         } else {
   5693                             goto date_fail;
   5694                         }
   5695                         tm.tm_year -= 1900;
   5696                         tm.tm_mon--;
   5697                         rtc_start_date = mktimegm(&tm);
   5698                         if (rtc_start_date == -1) {
   5699                         date_fail:
   5700                             fprintf(stderr, "Invalid date format. Valid format are:\n"
   5701                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
   5702                             exit(1);
   5703                         }
   5704                         rtc_date_offset = time(NULL) - rtc_start_date;
   5705                     }
   5706                 }
   5707                 break;
   5708             case QEMU_OPTION_tb_size:
   5709                 tb_size = strtol(optarg, NULL, 0);
   5710                 if (tb_size < 0)
   5711                     tb_size = 0;
   5712                 break;
   5713             case QEMU_OPTION_icount:
   5714                 use_icount = 1;
   5715                 if (strcmp(optarg, "auto") == 0) {
   5716                     icount_time_shift = -1;
   5717                 } else {
   5718                     icount_time_shift = strtol(optarg, NULL, 0);
   5719                 }
   5720                 break;
   5721             case QEMU_OPTION_incoming:
   5722                 incoming = optarg;
   5723                 break;
   5724 #ifndef _WIN32
   5725             case QEMU_OPTION_chroot:
   5726                 chroot_dir = optarg;
   5727                 break;
   5728             case QEMU_OPTION_runas:
   5729                 run_as = optarg;
   5730                 break;
   5731 #endif
   5732 #ifdef CONFIG_XEN
   5733             case QEMU_OPTION_xen_domid:
   5734                 xen_domid = atoi(optarg);
   5735                 break;
   5736             case QEMU_OPTION_xen_create:
   5737                 xen_mode = XEN_CREATE;
   5738                 break;
   5739             case QEMU_OPTION_xen_attach:
   5740                 xen_mode = XEN_ATTACH;
   5741                 break;
   5742 #endif
   5743             }
   5744         }
   5745     }
   5746 
   5747     /* If no data_dir is specified then try to find it relative to the
   5748        executable path.  */
   5749     if (!data_dir) {
   5750         data_dir = find_datadir(argv[0]);
   5751     }
   5752     /* If all else fails use the install patch specified when building.  */
   5753     if (!data_dir) {
   5754         data_dir = CONFIG_QEMU_SHAREDIR;
   5755     }
   5756 
   5757 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
   5758     if (kvm_allowed && kqemu_allowed) {
   5759         fprintf(stderr,
   5760                 "You can not enable both KVM and kqemu at the same time\n");
   5761         exit(1);
   5762     }
   5763 #endif
   5764 
   5765     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
   5766     if (smp_cpus > machine->max_cpus) {
   5767         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
   5768                 "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
   5769                 machine->max_cpus);
   5770         exit(1);
   5771     }
   5772 
   5773     if (display_type == DT_NOGRAPHIC) {
   5774        if (serial_device_index == 0)
   5775            serial_devices[0] = "stdio";
   5776        if (parallel_device_index == 0)
   5777            parallel_devices[0] = "null";
   5778        if (strncmp(monitor_device, "vc", 2) == 0)
   5779            monitor_device = "stdio";
   5780     }
   5781 
   5782 #ifndef _WIN32
   5783     if (daemonize) {
   5784 	pid_t pid;
   5785 
   5786 	if (pipe(fds) == -1)
   5787 	    exit(1);
   5788 
   5789 	pid = fork();
   5790 	if (pid > 0) {
   5791 	    uint8_t status;
   5792 	    ssize_t len;
   5793 
   5794 	    close(fds[1]);
   5795 
   5796 	again:
   5797             len = read(fds[0], &status, 1);
   5798             if (len == -1 && (errno == EINTR))
   5799                 goto again;
   5800 
   5801             if (len != 1)
   5802                 exit(1);
   5803             else if (status == 1) {
   5804                 fprintf(stderr, "Could not acquire pidfile\n");
   5805                 exit(1);
   5806             } else
   5807                 exit(0);
   5808 	} else if (pid < 0)
   5809             exit(1);
   5810 
   5811 	setsid();
   5812 
   5813 	pid = fork();
   5814 	if (pid > 0)
   5815 	    exit(0);
   5816 	else if (pid < 0)
   5817 	    exit(1);
   5818 
   5819 	umask(027);
   5820 
   5821         signal(SIGTSTP, SIG_IGN);
   5822         signal(SIGTTOU, SIG_IGN);
   5823         signal(SIGTTIN, SIG_IGN);
   5824     }
   5825 
   5826     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
   5827         if (daemonize) {
   5828             uint8_t status = 1;
   5829             write(fds[1], &status, 1);
   5830         } else
   5831             fprintf(stderr, "Could not acquire pid file\n");
   5832         exit(1);
   5833     }
   5834 #endif
   5835 
   5836 #ifdef CONFIG_KQEMU
   5837     if (smp_cpus > 1)
   5838         kqemu_allowed = 0;
   5839 #endif
   5840     if (qemu_init_main_loop()) {
   5841         fprintf(stderr, "qemu_init_main_loop failed\n");
   5842         exit(1);
   5843     }
   5844     linux_boot = (kernel_filename != NULL);
   5845     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
   5846 
   5847     if (!linux_boot && *kernel_cmdline != '\0') {
   5848         fprintf(stderr, "-append only allowed with -kernel option\n");
   5849         exit(1);
   5850     }
   5851 
   5852     if (!linux_boot && initrd_filename != NULL) {
   5853         fprintf(stderr, "-initrd only allowed with -kernel option\n");
   5854         exit(1);
   5855     }
   5856 
   5857     /* boot to floppy or the default cd if no hard disk defined yet */
   5858     if (!boot_devices[0]) {
   5859         boot_devices = "cad";
   5860     }
   5861     setvbuf(stdout, NULL, _IOLBF, 0);
   5862 
   5863     if (init_timer_alarm() < 0) {
   5864         fprintf(stderr, "could not initialize alarm timer\n");
   5865         exit(1);
   5866     }
   5867     if (use_icount && icount_time_shift < 0) {
   5868         use_icount = 2;
   5869         /* 125MIPS seems a reasonable initial guess at the guest speed.
   5870            It will be corrected fairly quickly anyway.  */
   5871         icount_time_shift = 3;
   5872         init_icount_adjust();
   5873     }
   5874 
   5875 #ifdef _WIN32
   5876     socket_init();
   5877 #endif
   5878 
   5879     /* init network clients */
   5880     if (nb_net_clients == 0) {
   5881         /* if no clients, we use a default config */
   5882         net_clients[nb_net_clients++] = "nic";
   5883 #ifdef CONFIG_SLIRP
   5884         net_clients[nb_net_clients++] = "user";
   5885 #endif
   5886     }
   5887 
   5888     for(i = 0;i < nb_net_clients; i++) {
   5889         if (net_client_parse(net_clients[i]) < 0)
   5890             exit(1);
   5891     }
   5892     net_client_check();
   5893 
   5894 #ifdef TARGET_I386
   5895     /* XXX: this should be moved in the PC machine instantiation code */
   5896     if (net_boot != 0) {
   5897         int netroms = 0;
   5898 	for (i = 0; i < nb_nics && i < 4; i++) {
   5899 	    const char *model = nd_table[i].model;
   5900 	    char buf[1024];
   5901             char *filename;
   5902             if (net_boot & (1 << i)) {
   5903                 if (model == NULL)
   5904                     model = "ne2k_pci";
   5905                 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
   5906                 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
   5907                 if (filename && get_image_size(filename) > 0) {
   5908                     if (nb_option_roms >= MAX_OPTION_ROMS) {
   5909                         fprintf(stderr, "Too many option ROMs\n");
   5910                         exit(1);
   5911                     }
   5912                     option_rom[nb_option_roms] = qemu_strdup(buf);
   5913                     nb_option_roms++;
   5914                     netroms++;
   5915                 }
   5916                 if (filename) {
   5917                     qemu_free(filename);
   5918                 }
   5919             }
   5920 	}
   5921 	if (netroms == 0) {
   5922 	    fprintf(stderr, "No valid PXE rom found for network device\n");
   5923 	    exit(1);
   5924 	}
   5925     }
   5926 #endif
   5927 
   5928     /* init the bluetooth world */
   5929     for (i = 0; i < nb_bt_opts; i++)
   5930         if (bt_parse(bt_opts[i]))
   5931             exit(1);
   5932 
   5933     /* init the memory */
   5934     if (ram_size == 0)
   5935         ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
   5936 
   5937 #ifdef CONFIG_KQEMU
   5938     /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
   5939        guest ram allocation.  It needs to go away.  */
   5940     if (kqemu_allowed) {
   5941         kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
   5942         kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
   5943         if (!kqemu_phys_ram_base) {
   5944             fprintf(stderr, "Could not allocate physical memory\n");
   5945             exit(1);
   5946         }
   5947     }
   5948 #endif
   5949 
   5950     /* init the dynamic translator */
   5951     cpu_exec_init_all(tb_size * 1024 * 1024);
   5952 
   5953     bdrv_init();
   5954 
   5955     /* we always create the cdrom drive, even if no disk is there */
   5956 
   5957     if (nb_drives_opt < MAX_DRIVES)
   5958         drive_add(NULL, CDROM_ALIAS);
   5959 
   5960     /* we always create at least one floppy */
   5961 
   5962     if (nb_drives_opt < MAX_DRIVES)
   5963         drive_add(NULL, FD_ALIAS, 0);
   5964 
   5965     /* we always create one sd slot, even if no card is in it */
   5966 
   5967     if (nb_drives_opt < MAX_DRIVES)
   5968         drive_add(NULL, SD_ALIAS);
   5969 
   5970     /* open the virtual block devices */
   5971 
   5972     for(i = 0; i < nb_drives_opt; i++)
   5973         if (drive_init(&drives_opt[i], snapshot, machine) == -1)
   5974 	    exit(1);
   5975 
   5976     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
   5977     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
   5978 
   5979 #ifndef _WIN32
   5980     /* must be after terminal init, SDL library changes signal handlers */
   5981     sighandler_setup();
   5982 #endif
   5983 
   5984     /* Maintain compatibility with multiple stdio monitors */
   5985     if (!strcmp(monitor_device,"stdio")) {
   5986         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
   5987             const char *devname = serial_devices[i];
   5988             if (devname && !strcmp(devname,"mon:stdio")) {
   5989                 monitor_device = NULL;
   5990                 break;
   5991             } else if (devname && !strcmp(devname,"stdio")) {
   5992                 monitor_device = NULL;
   5993                 serial_devices[i] = "mon:stdio";
   5994                 break;
   5995             }
   5996         }
   5997     }
   5998 
   5999     if (nb_numa_nodes > 0) {
   6000         int i;
   6001 
   6002         if (nb_numa_nodes > smp_cpus) {
   6003             nb_numa_nodes = smp_cpus;
   6004         }
   6005 
   6006         /* If no memory size if given for any node, assume the default case
   6007          * and distribute the available memory equally across all nodes
   6008          */
   6009         for (i = 0; i < nb_numa_nodes; i++) {
   6010             if (node_mem[i] != 0)
   6011                 break;
   6012         }
   6013         if (i == nb_numa_nodes) {
   6014             uint64_t usedmem = 0;
   6015 
   6016             /* On Linux, the each node's border has to be 8MB aligned,
   6017              * the final node gets the rest.
   6018              */
   6019             for (i = 0; i < nb_numa_nodes - 1; i++) {
   6020                 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
   6021                 usedmem += node_mem[i];
   6022             }
   6023             node_mem[i] = ram_size - usedmem;
   6024         }
   6025 
   6026         for (i = 0; i < nb_numa_nodes; i++) {
   6027             if (node_cpumask[i] != 0)
   6028                 break;
   6029         }
   6030         /* assigning the VCPUs round-robin is easier to implement, guest OSes
   6031          * must cope with this anyway, because there are BIOSes out there in
   6032          * real machines which also use this scheme.
   6033          */
   6034         if (i == nb_numa_nodes) {
   6035             for (i = 0; i < smp_cpus; i++) {
   6036                 node_cpumask[i % nb_numa_nodes] |= 1 << i;
   6037             }
   6038         }
   6039     }
   6040 
   6041     if (kvm_enabled()) {
   6042         int ret;
   6043 
   6044         ret = kvm_init(smp_cpus);
   6045         if (ret < 0) {
   6046             fprintf(stderr, "failed to initialize KVM\n");
   6047             exit(1);
   6048         }
   6049     }
   6050 
   6051     if (monitor_device) {
   6052         monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
   6053         if (!monitor_hd) {
   6054             fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
   6055             exit(1);
   6056         }
   6057     }
   6058 
   6059     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   6060         const char *devname = serial_devices[i];
   6061         if (devname && strcmp(devname, "none")) {
   6062             char label[32];
   6063             snprintf(label, sizeof(label), "serial%d", i);
   6064             serial_hds[i] = qemu_chr_open(label, devname, NULL);
   6065             if (!serial_hds[i]) {
   6066                 fprintf(stderr, "qemu: could not open serial device '%s'\n",
   6067                         devname);
   6068                 exit(1);
   6069             }
   6070         }
   6071     }
   6072 
   6073     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   6074         const char *devname = parallel_devices[i];
   6075         if (devname && strcmp(devname, "none")) {
   6076             char label[32];
   6077             snprintf(label, sizeof(label), "parallel%d", i);
   6078             parallel_hds[i] = qemu_chr_open(label, devname, NULL);
   6079             if (!parallel_hds[i]) {
   6080                 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
   6081                         devname);
   6082                 exit(1);
   6083             }
   6084         }
   6085     }
   6086 
   6087     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   6088         const char *devname = virtio_consoles[i];
   6089         if (devname && strcmp(devname, "none")) {
   6090             char label[32];
   6091             snprintf(label, sizeof(label), "virtcon%d", i);
   6092             virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
   6093             if (!virtcon_hds[i]) {
   6094                 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
   6095                         devname);
   6096                 exit(1);
   6097             }
   6098         }
   6099     }
   6100 
   6101     module_call_init(MODULE_INIT_DEVICE);
   6102 
   6103     machine->init(ram_size, boot_devices,
   6104                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
   6105 
   6106 
   6107     for (env = first_cpu; env != NULL; env = env->next_cpu) {
   6108         for (i = 0; i < nb_numa_nodes; i++) {
   6109             if (node_cpumask[i] & (1 << env->cpu_index)) {
   6110                 env->numa_node = i;
   6111             }
   6112         }
   6113     }
   6114 
   6115     current_machine = machine;
   6116 
   6117     /* Set KVM's vcpu state to qemu's initial CPUState. */
   6118     if (kvm_enabled()) {
   6119         int ret;
   6120 
   6121         ret = kvm_sync_vcpus();
   6122         if (ret < 0) {
   6123             fprintf(stderr, "failed to initialize vcpus\n");
   6124             exit(1);
   6125         }
   6126     }
   6127 
   6128     /* init USB devices */
   6129     if (usb_enabled) {
   6130         for(i = 0; i < usb_devices_index; i++) {
   6131             if (usb_device_add(usb_devices[i], 0) < 0) {
   6132                 fprintf(stderr, "Warning: could not add USB device %s\n",
   6133                         usb_devices[i]);
   6134             }
   6135         }
   6136     }
   6137 
   6138     if (!display_state)
   6139         dumb_display_init();
   6140     /* just use the first displaystate for the moment */
   6141     ds = display_state;
   6142 
   6143     if (display_type == DT_DEFAULT) {
   6144 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
   6145         display_type = DT_SDL;
   6146 #else
   6147         display_type = DT_VNC;
   6148         vnc_display = "localhost:0,to=99";
   6149         show_vnc_port = 1;
   6150 #endif
   6151     }
   6152 
   6153 
   6154     switch (display_type) {
   6155     case DT_NOGRAPHIC:
   6156         break;
   6157 #if defined(CONFIG_CURSES)
   6158     case DT_CURSES:
   6159         curses_display_init(ds, full_screen);
   6160         break;
   6161 #endif
   6162 #if defined(CONFIG_SDL)
   6163     case DT_SDL:
   6164         sdl_display_init(ds, full_screen, no_frame);
   6165         break;
   6166 #elif defined(CONFIG_COCOA)
   6167     case DT_SDL:
   6168         cocoa_display_init(ds, full_screen);
   6169         break;
   6170 #endif
   6171     case DT_VNC:
   6172         vnc_display_init(ds);
   6173         if (vnc_display_open(ds, vnc_display) < 0)
   6174             exit(1);
   6175 
   6176         if (show_vnc_port) {
   6177             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
   6178         }
   6179         break;
   6180     default:
   6181         break;
   6182     }
   6183     dpy_resize(ds);
   6184 
   6185     dcl = ds->listeners;
   6186     while (dcl != NULL) {
   6187         if (dcl->dpy_refresh != NULL) {
   6188             ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
   6189             qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
   6190         }
   6191         dcl = dcl->next;
   6192     }
   6193 
   6194     if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
   6195         nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
   6196         qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
   6197     }
   6198 
   6199     text_consoles_set_display(display_state);
   6200     qemu_chr_initial_reset();
   6201 
   6202     if (monitor_device && monitor_hd)
   6203         monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
   6204 
   6205     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   6206         const char *devname = serial_devices[i];
   6207         if (devname && strcmp(devname, "none")) {
   6208             if (strstart(devname, "vc", 0))
   6209                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
   6210         }
   6211     }
   6212 
   6213     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   6214         const char *devname = parallel_devices[i];
   6215         if (devname && strcmp(devname, "none")) {
   6216             if (strstart(devname, "vc", 0))
   6217                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
   6218         }
   6219     }
   6220 
   6221     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   6222         const char *devname = virtio_consoles[i];
   6223         if (virtcon_hds[i] && devname) {
   6224             if (strstart(devname, "vc", 0))
   6225                 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
   6226         }
   6227     }
   6228 
   6229     if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
   6230         fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
   6231                 gdbstub_dev);
   6232         exit(1);
   6233     }
   6234 
   6235     if (loadvm)
   6236         do_loadvm(cur_mon, loadvm);
   6237 
   6238     if (incoming) {
   6239         autostart = 0; /* fixme how to deal with -daemonize */
   6240         qemu_start_incoming_migration(incoming);
   6241     }
   6242 
   6243     if (autostart)
   6244         vm_start();
   6245 
   6246 #ifndef _WIN32
   6247     if (daemonize) {
   6248 	uint8_t status = 0;
   6249 	ssize_t len;
   6250 
   6251     again1:
   6252 	len = write(fds[1], &status, 1);
   6253 	if (len == -1 && (errno == EINTR))
   6254 	    goto again1;
   6255 
   6256 	if (len != 1)
   6257 	    exit(1);
   6258 
   6259         if (chdir("/")) {
   6260             perror("not able to chdir to /");
   6261             exit(1);
   6262         }
   6263 	TFR(fd = qemu_open("/dev/null", O_RDWR));
   6264 	if (fd == -1)
   6265 	    exit(1);
   6266     }
   6267 
   6268     if (run_as) {
   6269         pwd = getpwnam(run_as);
   6270         if (!pwd) {
   6271             fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
   6272             exit(1);
   6273         }
   6274     }
   6275 
   6276     if (chroot_dir) {
   6277         if (chroot(chroot_dir) < 0) {
   6278             fprintf(stderr, "chroot failed\n");
   6279             exit(1);
   6280         }
   6281         if (chdir("/")) {
   6282             perror("not able to chdir to /");
   6283             exit(1);
   6284         }
   6285     }
   6286 
   6287     if (run_as) {
   6288         if (setgid(pwd->pw_gid) < 0) {
   6289             fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
   6290             exit(1);
   6291         }
   6292         if (setuid(pwd->pw_uid) < 0) {
   6293             fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
   6294             exit(1);
   6295         }
   6296         if (setuid(0) != -1) {
   6297             fprintf(stderr, "Dropping privileges failed\n");
   6298             exit(1);
   6299         }
   6300     }
   6301 
   6302     if (daemonize) {
   6303         dup2(fd, 0);
   6304         dup2(fd, 1);
   6305         dup2(fd, 2);
   6306 
   6307         close(fd);
   6308     }
   6309 #endif
   6310 
   6311     main_loop();
   6312     quit_timers();
   6313     net_cleanup();
   6314 
   6315     return 0;
   6316 }
   6317