1 /*
   2  * QEMU System Emulator
   3  * 
   4  * Copyright (c) 2003-2007 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 "vl.h"
  25 
  26 #include <unistd.h>
  27 #include <fcntl.h>
  28 #include <signal.h>
  29 #include <time.h>
  30 #include <errno.h>
  31 #include <sys/time.h>
  32 #include <zlib.h>
  33 
  34 #ifndef _WIN32
  35 #include <sys/times.h>
  36 #include <sys/wait.h>
  37 #include <termios.h>
  38 #include <sys/poll.h>
  39 #include <sys/mman.h>
  40 #include <sys/ioctl.h>
  41 #include <sys/socket.h>
  42 #include <netinet/in.h>
  43 #include <arpa/inet.h>
  44 #include <dirent.h>
  45 #include <netdb.h>
  46 #ifdef _BSD
  47 #include <sys/stat.h>
  48 #ifndef __APPLE__
  49 #include <libutil.h>
  50 #endif
  51 #else
  52 #ifdef __sun__
  53 #include <libdlpi.h>
  54 #include <sys/ethernet.h>
  55 #include <stropts.h>
  56 #include <sys/bufmod.h>
  57 #else
  58 #include <linux/if.h>
  59 #include <linux/if_tun.h>
  60 #include <pty.h>
  61 #include <malloc.h>
  62 #include <linux/rtc.h>
  63 #include <linux/ppdev.h>
  64 #endif
  65 #endif
  66 #endif
  67 
  68 #if defined(CONFIG_SLIRP)
  69 #include "libslirp.h"
  70 #endif
  71 
  72 #ifdef _WIN32
  73 #include <malloc.h>
  74 #include <sys/timeb.h>
  75 #include <windows.h>
  76 #define getopt_long_only getopt_long
  77 #define memalign(align, size) malloc(size)
  78 #endif
  79 
  80 #include "qemu_socket.h"
  81 
  82 #ifdef CONFIG_SDL
  83 #ifdef __APPLE__
  84 #include <SDL/SDL.h>
  85 #endif
  86 #endif /* CONFIG_SDL */
  87 
  88 #ifdef CONFIG_COCOA
  89 #undef main
  90 #define main qemu_main
  91 #endif /* CONFIG_COCOA */
  92 
  93 #include "disas.h"
  94 
  95 #include "exec-all.h"
  96 
  97 #include <xen/hvm/params.h>
  98 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
  99 #define DEFAULT_BRIDGE "xenbr0"
 100 #ifdef __sun__
 101 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
 102 #else
 103 #define SMBD_COMMAND "/usr/sbin/smbd"
 104 #endif
 105 
 106 //#define DEBUG_UNUSED_IOPORT
 107 //#define DEBUG_IOPORT
 108 
 109 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
 110 
 111 #ifdef TARGET_PPC
 112 #define DEFAULT_RAM_SIZE 144
 113 #else
 114 #define DEFAULT_RAM_SIZE 128
 115 #endif
 116 /* in ms */
 117 #define GUI_REFRESH_INTERVAL 30
 118 
 119 /* Max number of USB devices that can be specified on the commandline.  */
 120 #define MAX_USB_CMDLINE 8
 121 
 122 /* XXX: use a two level table to limit memory usage */
 123 #define MAX_IOPORTS 65536
 124 
 125 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
 126 char phys_ram_file[1024];
 127 void *ioport_opaque[MAX_IOPORTS];
 128 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
 129 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
 130 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
 131    to store the VM snapshots */
 132 BlockDriverState *bs_table[MAX_DISKS + MAX_SCSI_DISKS + 1], *fd_table[MAX_FD];
 133 /* point to the block driver where the snapshots are managed */
 134 BlockDriverState *bs_snapshots;
 135 int vga_ram_size;
 136 int bios_size;
 137 static DisplayState display_state;
 138 int nographic;
 139 int vncviewer;
 140 int vncunused;
 141 struct sockaddr_in vnclisten_addr;
 142 const char* keyboard_layout = NULL;
 143 int64_t ticks_per_sec;
 144 char *boot_device = NULL;
 145 uint64_t ram_size;
 146 int pit_min_timer_count = 0;
 147 int nb_nics;
 148 NICInfo nd_table[MAX_NICS];
 149 QEMUTimer *gui_timer;
 150 int vm_running;
 151 int rtc_utc = 1;
 152 int cirrus_vga_enabled = 1;
 153 #ifdef TARGET_SPARC
 154 int graphic_width = 1024;
 155 int graphic_height = 768;
 156 #else
 157 int graphic_width = 800;
 158 int graphic_height = 600;
 159 #endif
 160 int graphic_depth = 15;
 161 int full_screen = 0;
 162 int no_quit = 0;
 163 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
 164 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
 165 #ifdef TARGET_I386
 166 int win2k_install_hack = 0;
 167 #endif
 168 int usb_enabled = 0;
 169 static VLANState *first_vlan;
 170 int smp_cpus = 1;
 171 const char *vnc_display;
 172 #if defined(TARGET_SPARC)
 173 #define MAX_CPUS 16
 174 #elif defined(TARGET_I386)
 175 #define MAX_CPUS 255
 176 #else
 177 #define MAX_CPUS 1
 178 #endif
 179 int acpi_enabled = 0;
 180 int fd_bootchk = 1;
 181 int no_reboot = 0;
 182 int daemonize = 0;
 183 const char *option_rom[MAX_OPTION_ROMS];
 184 int nb_option_roms;
 185 int semihosting_enabled = 0;
 186 int autostart = 1;
 187 
 188 extern int vcpus;
 189 
 190 int xc_handle;
 191 
 192 time_t timeoffset = 0;
 193 
 194 char domain_name[64] = "xVM-HVM-no-name";
 195 extern int domid;
 196 
 197 char vncpasswd[64];
 198 unsigned char challenge[AUTHCHALLENGESIZE];
 199 
 200 /***********************************************************/
 201 /* x86 ISA bus support */
 202 
 203 target_phys_addr_t isa_mem_base = 0;
 204 PicState2 *isa_pic;
 205 
 206 uint32_t default_ioport_readb(void *opaque, uint32_t address)
 207 {
 208 #ifdef DEBUG_UNUSED_IOPORT
 209     fprintf(stderr, "inb: port=0x%04x\n", address);
 210 #endif
 211     return 0xff;
 212 }
 213 
 214 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
 215 {
 216 #ifdef DEBUG_UNUSED_IOPORT
 217     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
 218 #endif
 219 }
 220 
 221 /* default is to make two byte accesses */
 222 uint32_t default_ioport_readw(void *opaque, uint32_t address)
 223 {
 224     uint32_t data;
 225     IOPortReadFunc *func = ioport_read_table[0][address];
 226     if (!func)
 227             func = default_ioport_readb;
 228     data = func(ioport_opaque[address], address);
 229     address = (address + 1) & (MAX_IOPORTS - 1);
 230     func = ioport_read_table[0][address];
 231     if (!func)
 232             func = default_ioport_readb;
 233     data |= func(ioport_opaque[address], address) << 8;
 234     return data;
 235 }
 236 
 237 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
 238 {
 239     IOPortWriteFunc *func = ioport_write_table[0][address];
 240     if (!func)
 241             func = default_ioport_writeb;
 242     func(ioport_opaque[address], address, data & 0xff);
 243     address = (address + 1) & (MAX_IOPORTS - 1);
 244     func = ioport_write_table[0][address];
 245     if (!func)
 246             func = default_ioport_writeb;
 247     func(ioport_opaque[address], address, (data >> 8) & 0xff);
 248 }
 249 
 250 uint32_t default_ioport_readl(void *opaque, uint32_t address)
 251 {
 252 #ifdef DEBUG_UNUSED_IOPORT
 253     fprintf(stderr, "inl: port=0x%04x\n", address);
 254 #endif
 255     return 0xffffffff;
 256 }
 257 
 258 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
 259 {
 260 #ifdef DEBUG_UNUSED_IOPORT
 261     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
 262 #endif
 263 }
 264 
 265 void init_ioports(void)
 266 {
 267 }
 268 
 269 /* size is the word size in byte */
 270 int register_ioport_read(int start, int length, int size, 
 271                          IOPortReadFunc *func, void *opaque)
 272 {
 273     int i, bsize;
 274 
 275     if (size == 1) {
 276         bsize = 0;
 277     } else if (size == 2) {
 278         bsize = 1;
 279     } else if (size == 4) {
 280         bsize = 2;
 281     } else {
 282         hw_error("register_ioport_read: invalid size");
 283         return -1;
 284     }
 285     for(i = start; i < start + length; i += size) {
 286         ioport_read_table[bsize][i] = func;
 287         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
 288             hw_error("register_ioport_write: invalid opaque");
 289         ioport_opaque[i] = opaque;
 290     }
 291     return 0;
 292 }
 293 
 294 /* size is the word size in byte */
 295 int register_ioport_write(int start, int length, int size, 
 296                           IOPortWriteFunc *func, void *opaque)
 297 {
 298     int i, bsize;
 299 
 300     if (size == 1) {
 301         bsize = 0;
 302     } else if (size == 2) {
 303         bsize = 1;
 304     } else if (size == 4) {
 305         bsize = 2;
 306     } else {
 307         hw_error("register_ioport_write: invalid size");
 308         return -1;
 309     }
 310     for(i = start; i < start + length; i += size) {
 311         ioport_write_table[bsize][i] = func;
 312         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
 313             hw_error("register_ioport_write: invalid opaque");
 314         ioport_opaque[i] = opaque;
 315     }
 316     return 0;
 317 }
 318 
 319 void isa_unassign_ioport(int start, int length)
 320 {
 321     int i;
 322 
 323     for(i = start; i < start + length; i++) {
 324         ioport_read_table[0][i] = default_ioport_readb;
 325         ioport_read_table[1][i] = default_ioport_readw;
 326         ioport_read_table[2][i] = default_ioport_readl;
 327 
 328         ioport_write_table[0][i] = default_ioport_writeb;
 329         ioport_write_table[1][i] = default_ioport_writew;
 330         ioport_write_table[2][i] = default_ioport_writel;
 331     }
 332 }
 333 
 334 /***********************************************************/
 335 
 336 void cpu_outb(CPUState *env, int addr, int val)
 337 {
 338     IOPortWriteFunc *func = ioport_write_table[0][addr];
 339     if (!func)
 340             func = default_ioport_writeb;
 341 #ifdef DEBUG_IOPORT
 342     if (loglevel & CPU_LOG_IOPORT)
 343         fprintf(logfile, "outb: %04x %02x\n", addr, val);
 344 #endif    
 345     func(ioport_opaque[addr], addr, val);
 346 #ifdef USE_KQEMU
 347     if (env)
 348         env->last_io_time = cpu_get_time_fast();
 349 #endif
 350 }
 351 
 352 void cpu_outw(CPUState *env, int addr, int val)
 353 {
 354     IOPortWriteFunc *func = ioport_write_table[1][addr];
 355     if (!func)
 356             func = default_ioport_writew;
 357 #ifdef DEBUG_IOPORT
 358     if (loglevel & CPU_LOG_IOPORT)
 359         fprintf(logfile, "outw: %04x %04x\n", addr, val);
 360 #endif    
 361     func(ioport_opaque[addr], addr, val);
 362 #ifdef USE_KQEMU
 363     if (env)
 364         env->last_io_time = cpu_get_time_fast();
 365 #endif
 366 }
 367 
 368 void cpu_outl(CPUState *env, int addr, int val)
 369 {
 370     IOPortWriteFunc *func = ioport_write_table[2][addr];
 371     if (!func)
 372             func = default_ioport_writel;
 373 #ifdef DEBUG_IOPORT
 374     if (loglevel & CPU_LOG_IOPORT)
 375         fprintf(logfile, "outl: %04x %08x\n", addr, val);
 376 #endif
 377     func(ioport_opaque[addr], addr, val);
 378 #ifdef USE_KQEMU
 379     if (env)
 380         env->last_io_time = cpu_get_time_fast();
 381 #endif
 382 }
 383 
 384 int cpu_inb(CPUState *env, int addr)
 385 {
 386     int val;
 387     IOPortReadFunc *func = ioport_read_table[0][addr];
 388     if (!func)
 389             func = default_ioport_readb;
 390     val = func(ioport_opaque[addr], addr);
 391 #ifdef DEBUG_IOPORT
 392     if (loglevel & CPU_LOG_IOPORT)
 393         fprintf(logfile, "inb : %04x %02x\n", addr, val);
 394 #endif
 395 #ifdef USE_KQEMU
 396     if (env)
 397         env->last_io_time = cpu_get_time_fast();
 398 #endif
 399     return val;
 400 }
 401 
 402 int cpu_inw(CPUState *env, int addr)
 403 {
 404     int val;
 405     IOPortReadFunc *func = ioport_read_table[1][addr];
 406     if (!func)
 407             func = default_ioport_readw;
 408     val = func(ioport_opaque[addr], addr);
 409 #ifdef DEBUG_IOPORT
 410     if (loglevel & CPU_LOG_IOPORT)
 411         fprintf(logfile, "inw : %04x %04x\n", addr, val);
 412 #endif
 413 #ifdef USE_KQEMU
 414     if (env)
 415         env->last_io_time = cpu_get_time_fast();
 416 #endif
 417     return val;
 418 }
 419 
 420 int cpu_inl(CPUState *env, int addr)
 421 {
 422     int val;
 423     IOPortReadFunc *func = ioport_read_table[2][addr];
 424     if (!func)
 425             func = default_ioport_readl;
 426     val = func(ioport_opaque[addr], addr);
 427 #ifdef DEBUG_IOPORT
 428     if (loglevel & CPU_LOG_IOPORT)
 429         fprintf(logfile, "inl : %04x %08x\n", addr, val);
 430 #endif
 431 #ifdef USE_KQEMU
 432     if (env)
 433         env->last_io_time = cpu_get_time_fast();
 434 #endif
 435     return val;
 436 }
 437 
 438 /***********************************************************/
 439 void hw_error(const char *fmt, ...)
 440 {
 441     va_list ap;
 442 #ifndef CONFIG_DM
 443     CPUState *env;
 444 #endif /* !CONFIG_DM */
 445 
 446     va_start(ap, fmt);
 447     fprintf(stderr, "qemu: hardware error: ");
 448     vfprintf(stderr, fmt, ap);
 449     fprintf(stderr, "\n");
 450 #ifndef CONFIG_DM
 451     for(env = first_cpu; env != NULL; env = env->next_cpu) {
 452         fprintf(stderr, "CPU #%d:\n", env->cpu_index);
 453 #ifdef TARGET_I386
 454         cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
 455 #else
 456         cpu_dump_state(env, stderr, fprintf, 0);
 457 #endif
 458     }
 459 #endif /* !CONFIG_DM */
 460     va_end(ap);
 461     abort();
 462 }
 463 
 464 /***********************************************************/
 465 /* keyboard/mouse */
 466 
 467 static QEMUPutKBDEvent *qemu_put_kbd_event;
 468 static void *qemu_put_kbd_event_opaque;
 469 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
 470 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
 471 
 472 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
 473 {
 474     qemu_put_kbd_event_opaque = opaque;
 475     qemu_put_kbd_event = func;
 476 }
 477 
 478 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
 479                                                 void *opaque, int absolute,
 480                                                 const char *name)
 481 {
 482     QEMUPutMouseEntry *s, *cursor;
 483 
 484     s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
 485     if (!s)
 486         return NULL;
 487 
 488     s->qemu_put_mouse_event = func;
 489     s->qemu_put_mouse_event_opaque = opaque;
 490     s->qemu_put_mouse_event_absolute = absolute;
 491     s->qemu_put_mouse_event_name = qemu_strdup(name);
 492     s->next = NULL;
 493 
 494     if (!qemu_put_mouse_event_head) {
 495         qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
 496         return s;
 497     }
 498 
 499     cursor = qemu_put_mouse_event_head;
 500     while (cursor->next != NULL)
 501         cursor = cursor->next;
 502 
 503     cursor->next = s;
 504     qemu_put_mouse_event_current = s;
 505 
 506     return s;
 507 }
 508 
 509 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
 510 {
 511     QEMUPutMouseEntry *prev = NULL, *cursor;
 512 
 513     if (!qemu_put_mouse_event_head || entry == NULL)
 514         return;
 515 
 516     cursor = qemu_put_mouse_event_head;
 517     while (cursor != NULL && cursor != entry) {
 518         prev = cursor;
 519         cursor = cursor->next;
 520     }
 521 
 522     if (cursor == NULL) // does not exist or list empty
 523         return;
 524     else if (prev == NULL) { // entry is head
 525         qemu_put_mouse_event_head = cursor->next;
 526         if (qemu_put_mouse_event_current == entry)
 527             qemu_put_mouse_event_current = cursor->next;
 528         qemu_free(entry->qemu_put_mouse_event_name);
 529         qemu_free(entry);
 530         return;
 531     }
 532 
 533     prev->next = entry->next;
 534 
 535     if (qemu_put_mouse_event_current == entry)
 536         qemu_put_mouse_event_current = prev;
 537 
 538     qemu_free(entry->qemu_put_mouse_event_name);
 539     qemu_free(entry);
 540 }
 541 
 542 void kbd_put_keycode(int keycode)
 543 {
 544     if (qemu_put_kbd_event) {
 545         qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
 546     }
 547 }
 548 
 549 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
 550 {
 551     QEMUPutMouseEvent *mouse_event;
 552     void *mouse_event_opaque;
 553 
 554     if (!qemu_put_mouse_event_current) {
 555         return;
 556     }
 557 
 558     mouse_event =
 559         qemu_put_mouse_event_current->qemu_put_mouse_event;
 560     mouse_event_opaque =
 561         qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
 562 
 563     if (mouse_event) {
 564         mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
 565     }
 566 }
 567 
 568 int kbd_mouse_is_absolute(void)
 569 {
 570     if (!qemu_put_mouse_event_current)
 571         return 0;
 572 
 573     return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
 574 }
 575 
 576 void do_info_mice(void)
 577 {
 578     QEMUPutMouseEntry *cursor;
 579     int index = 0;
 580 
 581     if (!qemu_put_mouse_event_head) {
 582         term_printf("No mouse devices connected\n");
 583         return;
 584     }
 585 
 586     term_printf("Mouse devices available:\n");
 587     cursor = qemu_put_mouse_event_head;
 588     while (cursor != NULL) {
 589         term_printf("%c Mouse #%d: %s\n",
 590                     (cursor == qemu_put_mouse_event_current ? '*' : ' '),
 591                     index, cursor->qemu_put_mouse_event_name);
 592         index++;
 593         cursor = cursor->next;
 594     }
 595 }
 596 
 597 void do_mouse_set(int index)
 598 {
 599     QEMUPutMouseEntry *cursor;
 600     int i = 0;
 601 
 602     if (!qemu_put_mouse_event_head) {
 603         term_printf("No mouse devices connected\n");
 604         return;
 605     }
 606 
 607     cursor = qemu_put_mouse_event_head;
 608     while (cursor != NULL && index != i) {
 609         i++;
 610         cursor = cursor->next;
 611     }
 612 
 613     if (cursor != NULL)
 614         qemu_put_mouse_event_current = cursor;
 615     else
 616         term_printf("Mouse at given index not found\n");
 617 }
 618 
 619 /* compute with 96 bit intermediate result: (a*b)/c */
 620 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
 621 {
 622     union {
 623         uint64_t ll;
 624         struct {
 625 #ifdef WORDS_BIGENDIAN
 626             uint32_t high, low;
 627 #else
 628             uint32_t low, high;
 629 #endif            
 630         } l;
 631     } u, res;
 632     uint64_t rl, rh;
 633 
 634     u.ll = a;
 635     rl = (uint64_t)u.l.low * (uint64_t)b;
 636     rh = (uint64_t)u.l.high * (uint64_t)b;
 637     rh += (rl >> 32);
 638     res.l.high = rh / c;
 639     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
 640     return res.ll;
 641 }
 642 
 643 /***********************************************************/
 644 /* real time host monotonic timer */
 645 
 646 #define QEMU_TIMER_BASE 1000000000LL
 647 
 648 #ifdef WIN32
 649 
 650 static int64_t clock_freq;
 651 
 652 static void init_get_clock(void)
 653 {
 654     LARGE_INTEGER freq;
 655     int ret;
 656     ret = QueryPerformanceFrequency(&freq);
 657     if (ret == 0) {
 658         fprintf(stderr, "Could not calibrate ticks\n");
 659         exit(1);
 660     }
 661     clock_freq = freq.QuadPart;
 662 }
 663 
 664 static int64_t get_clock(void)
 665 {
 666     LARGE_INTEGER ti;
 667     QueryPerformanceCounter(&ti);
 668     return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
 669 }
 670 
 671 #else
 672 
 673 static int use_rt_clock;
 674 
 675 static void init_get_clock(void)
 676 {
 677     use_rt_clock = 0;
 678 #if defined(__linux__)
 679     {
 680         struct timespec ts;
 681         if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
 682             use_rt_clock = 1;
 683         }
 684     }
 685 #endif
 686 }
 687 
 688 static int64_t get_clock(void)
 689 {
 690 #if defined(__linux__)
 691     if (use_rt_clock) {
 692         struct timespec ts;
 693         clock_gettime(CLOCK_MONOTONIC, &ts);
 694         return ts.tv_sec * 1000000000LL + ts.tv_nsec;
 695     } else 
 696 #endif
 697     {
 698         /* XXX: using gettimeofday leads to problems if the date
 699            changes, so it should be avoided. */
 700         struct timeval tv;
 701         gettimeofday(&tv, NULL);
 702         return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
 703     }
 704 }
 705 
 706 #endif
 707 
 708 /***********************************************************/
 709 /* guest cycle counter */
 710 
 711 static int64_t cpu_ticks_prev;
 712 static int64_t cpu_ticks_offset;
 713 static int64_t cpu_clock_offset;
 714 static int cpu_ticks_enabled;
 715 
 716 /* return the host CPU cycle counter and handle stop/restart */
 717 int64_t cpu_get_ticks(void)
 718 {
 719     if (!cpu_ticks_enabled) {
 720         return cpu_ticks_offset;
 721     } else {
 722         int64_t ticks;
 723         ticks = cpu_get_real_ticks();
 724         if (cpu_ticks_prev > ticks) {
 725             /* Note: non increasing ticks may happen if the host uses
 726                software suspend */
 727             cpu_ticks_offset += cpu_ticks_prev - ticks;
 728         }
 729         cpu_ticks_prev = ticks;
 730         return ticks + cpu_ticks_offset;
 731     }
 732 }
 733 
 734 /* return the host CPU monotonic timer and handle stop/restart */
 735 static int64_t cpu_get_clock(void)
 736 {
 737     int64_t ti;
 738     if (!cpu_ticks_enabled) {
 739         return cpu_clock_offset;
 740     } else {
 741         ti = get_clock();
 742         return ti + cpu_clock_offset;
 743     }
 744 }
 745 
 746 /* enable cpu_get_ticks() */
 747 void cpu_enable_ticks(void)
 748 {
 749     if (!cpu_ticks_enabled) {
 750         cpu_ticks_offset -= cpu_get_real_ticks();
 751         cpu_clock_offset -= get_clock();
 752         cpu_ticks_enabled = 1;
 753     }
 754 }
 755 
 756 /* disable cpu_get_ticks() : the clock is stopped. You must not call
 757    cpu_get_ticks() after that.  */
 758 void cpu_disable_ticks(void)
 759 {
 760     if (cpu_ticks_enabled) {
 761         cpu_ticks_offset = cpu_get_ticks();
 762         cpu_clock_offset = cpu_get_clock();
 763         cpu_ticks_enabled = 0;
 764     }
 765 }
 766 
 767 /***********************************************************/
 768 /* timers */
 769  
 770 #define QEMU_TIMER_REALTIME 0
 771 #define QEMU_TIMER_VIRTUAL  1
 772 
 773 struct QEMUClock {
 774     int type;
 775     /* XXX: add frequency */
 776 };
 777 
 778 struct QEMUTimer {
 779     QEMUClock *clock;
 780     int64_t expire_time;
 781     QEMUTimerCB *cb;
 782     void *opaque;
 783     struct QEMUTimer *next;
 784 };
 785 
 786 QEMUClock *rt_clock;
 787 QEMUClock *vm_clock;
 788 
 789 static QEMUTimer *active_timers[2];
 790 #ifdef _WIN32
 791 static MMRESULT timerID;
 792 static HANDLE host_alarm = NULL;
 793 static unsigned int period = 1;
 794 #else
 795 /* frequency of the times() clock tick */
 796 static int timer_freq;
 797 #endif
 798 
 799 QEMUClock *qemu_new_clock(int type)
 800 {
 801     QEMUClock *clock;
 802     clock = qemu_mallocz(sizeof(QEMUClock));
 803     if (!clock)
 804         return NULL;
 805     clock->type = type;
 806     return clock;
 807 }
 808 
 809 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
 810 {
 811     QEMUTimer *ts;
 812 
 813     ts = qemu_mallocz(sizeof(QEMUTimer));
 814     ts->clock = clock;
 815     ts->cb = cb;
 816     ts->opaque = opaque;
 817     return ts;
 818 }
 819 
 820 void qemu_free_timer(QEMUTimer *ts)
 821 {
 822     qemu_free(ts);
 823 }
 824 
 825 /* stop a timer, but do not dealloc it */
 826 void qemu_del_timer(QEMUTimer *ts)
 827 {
 828     QEMUTimer **pt, *t;
 829 
 830     /* NOTE: this code must be signal safe because
 831        qemu_timer_expired() can be called from a signal. */
 832     pt = &active_timers[ts->clock->type];
 833     for(;;) {
 834         t = *pt;
 835         if (!t)
 836             break;
 837         if (t == ts) {
 838             *pt = t->next;
 839             break;
 840         }
 841         pt = &t->next;
 842     }
 843 }
 844 
 845 void qemu_advance_timer(QEMUTimer *ts, int64_t expire_time)
 846 {
 847     if (ts->expire_time > expire_time || !qemu_timer_pending(ts))
 848         qemu_mod_timer(ts, expire_time);
 849 }
 850 
 851 /* modify the current timer so that it will be fired when current_time
 852    >= expire_time. The corresponding callback will be called. */
 853 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
 854 {
 855     QEMUTimer **pt, *t;
 856 
 857     qemu_del_timer(ts);
 858 
 859     /* add the timer in the sorted list */
 860     /* NOTE: this code must be signal safe because
 861        qemu_timer_expired() can be called from a signal. */
 862     pt = &active_timers[ts->clock->type];
 863     for(;;) {
 864         t = *pt;
 865         if (!t)
 866             break;
 867         if (t->expire_time > expire_time) 
 868             break;
 869         pt = &t->next;
 870     }
 871     ts->expire_time = expire_time;
 872     ts->next = *pt;
 873     *pt = ts;
 874 }
 875 
 876 int qemu_timer_pending(QEMUTimer *ts)
 877 {
 878     QEMUTimer *t;
 879     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
 880         if (t == ts)
 881             return 1;
 882     }
 883     return 0;
 884 }
 885 
 886 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
 887 {
 888     if (!timer_head)
 889         return 0;
 890     return (timer_head->expire_time <= current_time);
 891 }
 892 
 893 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
 894 {
 895     QEMUTimer *ts;
 896     
 897     for(;;) {
 898         ts = *ptimer_head;
 899         if (!ts || ts->expire_time > current_time)
 900             break;
 901         /* remove timer from the list before calling the callback */
 902         *ptimer_head = ts->next;
 903         ts->next = NULL;
 904         
 905         /* run the callback (the timer list can be modified) */
 906         ts->cb(ts->opaque);
 907     }
 908 }
 909 
 910 int64_t qemu_get_clock(QEMUClock *clock)
 911 {
 912     switch(clock->type) {
 913     case QEMU_TIMER_REALTIME:
 914         return get_clock() / 1000000;
 915     default:
 916     case QEMU_TIMER_VIRTUAL:
 917         return cpu_get_clock();
 918     }
 919 }
 920 
 921 static void init_timers(void)
 922 {
 923     init_get_clock();
 924     ticks_per_sec = QEMU_TIMER_BASE;
 925     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
 926     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
 927 }
 928 
 929 /* save a timer */
 930 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
 931 {
 932     uint64_t expire_time;
 933 
 934     if (qemu_timer_pending(ts)) {
 935         expire_time = ts->expire_time;
 936     } else {
 937         expire_time = -1;
 938     }
 939     qemu_put_be64(f, expire_time);
 940 }
 941 
 942 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
 943 {
 944     uint64_t expire_time;
 945 
 946     expire_time = qemu_get_be64(f);
 947     if (expire_time != -1) {
 948         qemu_mod_timer(ts, expire_time);
 949     } else {
 950         qemu_del_timer(ts);
 951     }
 952 }
 953 
 954 #ifdef CONFIG_DM
 955 static void timer_save(QEMUFile *f, void *opaque)
 956 {
 957     /* need timer for save/restoe qemu_timer in usb_uhci */
 958     if (cpu_ticks_enabled) {
 959         hw_error("cannot save state if virtual timers are running");
 960     }
 961     qemu_put_be64s(f, &cpu_clock_offset);
 962 }
 963 
 964 static int timer_load(QEMUFile *f, void *opaque, int version_id)
 965 {
 966     if (version_id != 1 && version_id != 2)
 967         return -EINVAL;
 968     if (cpu_ticks_enabled) {
 969         return -EINVAL;
 970     }
 971 
 972     qemu_get_be64s(f, &cpu_clock_offset);
 973     return 0;
 974 }
 975 #else  /* !CONFIG_DM */
 976 static void timer_save(QEMUFile *f, void *opaque)
 977 {
 978     if (cpu_ticks_enabled) {
 979         hw_error("cannot save state if virtual timers are running");
 980     }
 981     qemu_put_be64s(f, &cpu_ticks_offset);
 982     qemu_put_be64s(f, &ticks_per_sec);
 983     qemu_put_be64s(f, &cpu_clock_offset);
 984 }
 985 
 986 static int timer_load(QEMUFile *f, void *opaque, int version_id)
 987 {
 988     if (version_id != 1 && version_id != 2)
 989         return -EINVAL;
 990     if (cpu_ticks_enabled) {
 991         return -EINVAL;
 992     }
 993     qemu_get_be64s(f, &cpu_ticks_offset);
 994     qemu_get_be64s(f, &ticks_per_sec);
 995     if (version_id == 2) {
 996         qemu_get_be64s(f, &cpu_clock_offset);
 997     }
 998     return 0;
 999 }
1000 
1001 #ifdef _WIN32
1002 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
1003                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1004 #else
1005 static void host_alarm_handler(int host_signum)
1006 #endif
1007 {
1008 #if 0
1009 #define DISP_FREQ 1000
1010     {
1011         static int64_t delta_min = INT64_MAX;
1012         static int64_t delta_max, delta_cum, last_clock, delta, ti;
1013         static int count;
1014         ti = qemu_get_clock(vm_clock);
1015         if (last_clock != 0) {
1016             delta = ti - last_clock;
1017             if (delta < delta_min)
1018                 delta_min = delta;
1019             if (delta > delta_max)
1020                 delta_max = delta;
1021             delta_cum += delta;
1022             if (++count == DISP_FREQ) {
1023                 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1024                        muldiv64(delta_min, 1000000, ticks_per_sec),
1025                        muldiv64(delta_max, 1000000, ticks_per_sec),
1026                        muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1027                        (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1028                 count = 0;
1029                 delta_min = INT64_MAX;
1030                 delta_max = 0;
1031                 delta_cum = 0;
1032             }
1033         }
1034         last_clock = ti;
1035     }
1036 #endif
1037     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1038                            qemu_get_clock(vm_clock)) ||
1039         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1040                            qemu_get_clock(rt_clock))) {
1041 #ifdef _WIN32
1042         SetEvent(host_alarm);
1043 #endif
1044         CPUState *env = cpu_single_env;
1045         if (env) {
1046             /* stop the currently executing cpu because a timer occured */
1047             cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1048 #ifdef USE_KQEMU
1049             if (env->kqemu_enabled) {
1050                 kqemu_cpu_interrupt(env);
1051             }
1052 #endif
1053         }
1054     }
1055 }
1056 
1057 #ifndef _WIN32
1058 
1059 #if defined(__linux__)
1060 
1061 #define RTC_FREQ 1024
1062 
1063 static int rtc_fd;
1064 
1065 static int start_rtc_timer(void)
1066 {
1067     rtc_fd = open("/dev/rtc", O_RDONLY);
1068     if (rtc_fd < 0)
1069         return -1;
1070     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1071         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1072                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1073                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1074         goto fail;
1075     }
1076     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1077     fail:
1078         close(rtc_fd);
1079         return -1;
1080     }
1081     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1082     return 0;
1083 }
1084 
1085 #else
1086 
1087 static int start_rtc_timer(void)
1088 {
1089     return -1;
1090 }
1091 
1092 #endif /* !defined(__linux__) */
1093 
1094 #endif /* !defined(_WIN32) */
1095 
1096 #endif /* !CONFIG_DM */
1097 
1098 static void init_timer_alarm(void)
1099 {
1100 #ifdef _WIN32
1101     {
1102         int count=0;
1103         TIMECAPS tc;
1104 
1105         ZeroMemory(&tc, sizeof(TIMECAPS));
1106         timeGetDevCaps(&tc, sizeof(TIMECAPS));
1107         if (period < tc.wPeriodMin)
1108             period = tc.wPeriodMin;
1109         timeBeginPeriod(period);
1110         timerID = timeSetEvent(1,     // interval (ms)
1111                                period,     // resolution
1112                                host_alarm_handler, // function
1113                                (DWORD)&count,  // user parameter
1114                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1115         if( !timerID ) {
1116             perror("failed timer alarm");
1117             exit(1);
1118         }
1119         host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1120         if (!host_alarm) {
1121             perror("failed CreateEvent");
1122             exit(1);
1123         }
1124         qemu_add_wait_object(host_alarm, NULL, NULL);
1125     }
1126     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1127 #else
1128     {
1129 #ifndef CONFIG_DM
1130         struct sigaction act;
1131         struct itimerval itv;
1132 #endif
1133         
1134         /* get times() syscall frequency */
1135         timer_freq = sysconf(_SC_CLK_TCK);
1136         
1137 #ifndef CONFIG_DM
1138         /* timer signal */
1139         sigfillset(&act.sa_mask);
1140        act.sa_flags = 0;
1141 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1142         act.sa_flags |= SA_ONSTACK;
1143 #endif
1144         act.sa_handler = host_alarm_handler;
1145         sigaction(SIGALRM, &act, NULL);
1146 
1147         itv.it_interval.tv_sec = 0;
1148         itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1149         itv.it_value.tv_sec = 0;
1150         itv.it_value.tv_usec = 10 * 1000;
1151         setitimer(ITIMER_REAL, &itv, NULL);
1152         /* we probe the tick duration of the kernel to inform the user if
1153            the emulated kernel requested a too high timer frequency */
1154         getitimer(ITIMER_REAL, &itv);
1155 
1156 #if defined(__linux__)
1157         /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1158            have timers with 1 ms resolution. The correct solution will
1159            be to use the POSIX real time timers available in recent
1160            2.6 kernels */
1161         if (itv.it_interval.tv_usec > 1000 || 1) {
1162             /* try to use /dev/rtc to have a faster timer */
1163             if (start_rtc_timer() < 0)
1164                 goto use_itimer;
1165             /* disable itimer */
1166             itv.it_interval.tv_sec = 0;
1167             itv.it_interval.tv_usec = 0;
1168             itv.it_value.tv_sec = 0;
1169             itv.it_value.tv_usec = 0;
1170             setitimer(ITIMER_REAL, &itv, NULL);
1171 
1172             /* use the RTC */
1173             sigaction(SIGIO, &act, NULL);
1174             fcntl(rtc_fd, F_SETFL, O_ASYNC);
1175             fcntl(rtc_fd, F_SETOWN, getpid());
1176         } else 
1177 #endif /* defined(__linux__) */
1178         {
1179         use_itimer:
1180             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1181                                    PIT_FREQ) / 1000000;
1182         }
1183 #endif /* CONFIG_DM */
1184     }
1185 #endif
1186 }
1187 
1188 void quit_timers(void)
1189 {
1190 #ifdef _WIN32
1191     timeKillEvent(timerID);
1192     timeEndPeriod(period);
1193     if (host_alarm) {
1194         CloseHandle(host_alarm);
1195         host_alarm = NULL;
1196     }
1197 #endif
1198 }
1199 
1200 /***********************************************************/
1201 /* character device */
1202 
1203 static void qemu_chr_event(CharDriverState *s, int event)
1204 {
1205     if (!s->chr_event)
1206         return;
1207     s->chr_event(s->handler_opaque, event);
1208 }
1209 
1210 static void qemu_chr_reset_bh(void *opaque)
1211 {
1212     CharDriverState *s = opaque;
1213     qemu_chr_event(s, CHR_EVENT_RESET);
1214     qemu_bh_delete(s->bh);
1215     s->bh = NULL;
1216 }
1217 
1218 void qemu_chr_reset(CharDriverState *s)
1219 {
1220     if (s->bh == NULL) {
1221         s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1222         qemu_bh_schedule(s->bh);
1223     }
1224 }
1225 
1226 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1227 {
1228     return s->chr_write(s, buf, len);
1229 }
1230 
1231 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1232 {
1233     if (!s->chr_ioctl)
1234         return -ENOTSUP;
1235     return s->chr_ioctl(s, cmd, arg);
1236 }
1237 
1238 int qemu_chr_can_read(CharDriverState *s)
1239 {
1240     if (!s->chr_can_read)
1241         return 0;
1242     return s->chr_can_read(s->handler_opaque);
1243 }
1244 
1245 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1246 {
1247     s->chr_read(s->handler_opaque, buf, len);
1248 }
1249 
1250 
1251 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1252 {
1253     char buf[4096];
1254     va_list ap;
1255     va_start(ap, fmt);
1256     vsnprintf(buf, sizeof(buf), fmt, ap);
1257     qemu_chr_write(s, buf, strlen(buf));
1258     va_end(ap);
1259 }
1260 
1261 void qemu_chr_send_event(CharDriverState *s, int event)
1262 {
1263     if (s->chr_send_event)
1264         s->chr_send_event(s, event);
1265 }
1266 
1267 void qemu_chr_add_handlers(CharDriverState *s, 
1268                            IOCanRWHandler *fd_can_read, 
1269                            IOReadHandler *fd_read,
1270                            IOEventHandler *fd_event,
1271                            void *opaque)
1272 {
1273     s->chr_can_read = fd_can_read;
1274     s->chr_read = fd_read;
1275     s->chr_event = fd_event;
1276     s->handler_opaque = opaque;
1277     if (s->chr_update_read_handler)
1278         s->chr_update_read_handler(s);
1279 }
1280              
1281 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1282 {
1283     return len;
1284 }
1285 
1286 static CharDriverState *qemu_chr_open_null(void)
1287 {
1288     CharDriverState *chr;
1289 
1290     chr = qemu_mallocz(sizeof(CharDriverState));
1291     if (!chr)
1292         return NULL;
1293     chr->chr_write = null_chr_write;
1294     return chr;
1295 }
1296 
1297 #ifdef _WIN32
1298 
1299 static void socket_cleanup(void)
1300 {
1301     WSACleanup();
1302 }
1303 
1304 static int socket_init(void)
1305 {
1306     WSADATA Data;
1307     int ret, err;
1308 
1309     ret = WSAStartup(MAKEWORD(2,2), &Data);
1310     if (ret != 0) {
1311         err = WSAGetLastError();
1312         fprintf(stderr, "WSAStartup: %d\n", err);
1313         return -1;
1314     }
1315     atexit(socket_cleanup);
1316     return 0;
1317 }
1318 
1319 static int send_all(int fd, const uint8_t *buf, int len1)
1320 {
1321     int ret, len;
1322     
1323     len = len1;
1324     while (len > 0) {
1325         ret = send(fd, buf, len, 0);
1326         if (ret < 0) {
1327             int errno;
1328             errno = WSAGetLastError();
1329             if (errno != WSAEWOULDBLOCK) {
1330                 return -1;
1331             }
1332         } else if (ret == 0) {
1333             break;
1334         } else {
1335             buf += ret;
1336             len -= ret;
1337         }
1338     }
1339     return len1 - len;
1340 }
1341 
1342 void socket_set_nonblock(int fd)
1343 {
1344     unsigned long opt = 1;
1345     ioctlsocket(fd, FIONBIO, &opt);
1346 }
1347 
1348 #else
1349 
1350 static int unix_write(int fd, const uint8_t *buf, int len1)
1351 {
1352     int ret, sel_ret, len;
1353     int max_fd;
1354     fd_set writefds;
1355     struct timeval timeout;
1356 
1357     max_fd = fd;
1358 
1359     len = len1;
1360     while (len > 0) {
1361         FD_ZERO(&writefds);
1362         FD_SET(fd, &writefds);
1363         timeout.tv_sec = 0;
1364         timeout.tv_usec = 0;
1365         sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
1366         if (sel_ret <= 0) {
1367             /* Timeout or select error */
1368             return -1;
1369         } else {
1370             ret = write(fd, buf, len);
1371             if (ret < 0) {
1372                 if (errno != EINTR && errno != EAGAIN)
1373                     return -1;
1374             } else if (ret == 0) {
1375                 break;
1376             } else {
1377                 buf += ret;
1378                 len -= ret;
1379             }
1380         }
1381     }
1382     return len1 - len;
1383 }
1384 
1385 static inline int send_all(int fd, const uint8_t *buf, int len1)
1386 {
1387     return unix_write(fd, buf, len1);
1388 }
1389 
1390 void socket_set_nonblock(int fd)
1391 {
1392     fcntl(fd, F_SETFL, O_NONBLOCK);
1393 }
1394 #endif /* !_WIN32 */
1395 
1396 #ifndef _WIN32
1397 
1398 typedef struct {
1399     int fd_in, fd_out;
1400     int max_size;
1401 } FDCharDriver;
1402 
1403 #define STDIO_MAX_CLIENTS 2
1404 
1405 static int stdio_nb_clients;
1406 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1407 
1408 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1409 {
1410     FDCharDriver *s = chr->opaque;
1411     return unix_write(s->fd_out, buf, len);
1412 }
1413 
1414 static int fd_chr_read_poll(void *opaque)
1415 {
1416     CharDriverState *chr = opaque;
1417     FDCharDriver *s = chr->opaque;
1418 
1419     s->max_size = qemu_chr_can_read(chr);
1420     return s->max_size;
1421 }
1422 
1423 static void fd_chr_read(void *opaque)
1424 {
1425     CharDriverState *chr = opaque;
1426     FDCharDriver *s = chr->opaque;
1427     int size, len;
1428     uint8_t buf[1024];
1429     
1430     len = sizeof(buf);
1431     if (len > s->max_size)
1432         len = s->max_size;
1433     if (len == 0)
1434         return;
1435     size = read(s->fd_in, buf, len);
1436     if (size == 0) {
1437         /* FD has been closed. Remove it from the active list.  */
1438         qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1439         return;
1440     }
1441     if (size > 0) {
1442         qemu_chr_read(chr, buf, size);
1443     }
1444 }
1445 
1446 static void fd_chr_update_read_handler(CharDriverState *chr)
1447 {
1448     FDCharDriver *s = chr->opaque;
1449 
1450     if (s->fd_in >= 0) {
1451         if (nographic && s->fd_in == 0) {
1452         } else {
1453             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1454                                  fd_chr_read, NULL, chr);
1455         }
1456     }
1457 }
1458 
1459 /* open a character device to a unix fd */
1460 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1461 {
1462     CharDriverState *chr;
1463     FDCharDriver *s;
1464 
1465     chr = qemu_mallocz(sizeof(CharDriverState));
1466     if (!chr)
1467         return NULL;
1468     s = qemu_mallocz(sizeof(FDCharDriver));
1469     if (!s) {
1470         free(chr);
1471         return NULL;
1472     }
1473     s->fd_in = fd_in;
1474     s->fd_out = fd_out;
1475     chr->opaque = s;
1476     chr->chr_write = fd_chr_write;
1477     chr->chr_update_read_handler = fd_chr_update_read_handler;
1478 
1479     qemu_chr_reset(chr);
1480 
1481     return chr;
1482 }
1483 
1484 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1485 {
1486     int fd_out;
1487 
1488     fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1489     if (fd_out < 0)
1490         return NULL;
1491     return qemu_chr_open_fd(-1, fd_out);
1492 }
1493 
1494 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1495 {
1496     int fd_in, fd_out;
1497     char filename_in[256], filename_out[256];
1498 
1499     snprintf(filename_in, 256, "%s.in", filename);
1500     snprintf(filename_out, 256, "%s.out", filename);
1501     fd_in = open(filename_in, O_RDWR | O_BINARY);
1502     fd_out = open(filename_out, O_RDWR | O_BINARY);
1503     if (fd_in < 0 || fd_out < 0) {
1504         if (fd_in >= 0)
1505             close(fd_in);
1506         if (fd_out >= 0)
1507             close(fd_out);
1508         fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1509         if (fd_in < 0)
1510             return NULL;
1511     }
1512     return qemu_chr_open_fd(fd_in, fd_out);
1513 }
1514 
1515 
1516 /* for STDIO, we handle the case where several clients use it
1517    (nographic mode) */
1518 
1519 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1520 
1521 #define TERM_FIFO_MAX_SIZE 1
1522 
1523 static int term_got_escape, client_index;
1524 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1525 static int term_fifo_size;
1526 static int term_timestamps;
1527 static int64_t term_timestamps_start;
1528 
1529 void term_print_help(void)
1530 {
1531     printf("\n"
1532            "C-a h    print this help\n"
1533            "C-a x    exit emulator\n"
1534            "C-a s    save disk data back to file (if -snapshot)\n"
1535            "C-a b    send break (magic sysrq)\n"
1536            "C-a t    toggle console timestamps\n"
1537            "C-a c    switch between console and monitor\n"
1538            "C-a C-a  send C-a\n"
1539            );
1540 }
1541 
1542 /* called when a char is received */
1543 static void stdio_received_byte(int ch)
1544 {
1545     if (term_got_escape) {
1546         term_got_escape = 0;
1547         switch(ch) {
1548         case 'h':
1549             term_print_help();
1550             break;
1551         case 'x':
1552             exit(0);
1553             break;
1554         case 's': 
1555             {
1556                 int i;
1557                 for (i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
1558                     if (bs_table[i])
1559                         bdrv_commit(bs_table[i]);
1560                 }
1561             }
1562             break;
1563         case 'b':
1564             if (client_index < stdio_nb_clients) {
1565                 CharDriverState *chr;
1566                 FDCharDriver *s;
1567 
1568                 chr = stdio_clients[client_index];
1569                 s = chr->opaque;
1570                 qemu_chr_event(chr, CHR_EVENT_BREAK);
1571             }
1572             break;
1573         case 'c':
1574             client_index++;
1575             if (client_index >= stdio_nb_clients)
1576                 client_index = 0;
1577             if (client_index == 0) {
1578                 /* send a new line in the monitor to get the prompt */
1579                 ch = '\r';
1580                 goto send_char;
1581             }
1582             break;
1583         case 't':
1584             term_timestamps = !term_timestamps;
1585             term_timestamps_start = -1;
1586             break;
1587         case TERM_ESCAPE:
1588             goto send_char;
1589         }
1590     } else if (ch == TERM_ESCAPE) {
1591         term_got_escape = 1;
1592     } else {
1593     send_char:
1594         if (client_index < stdio_nb_clients) {
1595             uint8_t buf[1];
1596             CharDriverState *chr;
1597             
1598             chr = stdio_clients[client_index];
1599             if (qemu_chr_can_read(chr) > 0) {
1600                 buf[0] = ch;
1601                 qemu_chr_read(chr, buf, 1);
1602             } else if (term_fifo_size == 0) {
1603                 term_fifo[term_fifo_size++] = ch;
1604             }
1605         }
1606     }
1607 }
1608 
1609 static int stdio_read_poll(void *opaque)
1610 {
1611     CharDriverState *chr;
1612 
1613     if (client_index < stdio_nb_clients) {
1614         chr = stdio_clients[client_index];
1615         /* try to flush the queue if needed */
1616         if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1617             qemu_chr_read(chr, term_fifo, 1);
1618             term_fifo_size = 0;
1619         }
1620         /* see if we can absorb more chars */
1621         if (term_fifo_size == 0)
1622             return 1;
1623         else
1624             return 0;
1625     } else {
1626         return 1;
1627     }
1628 }
1629 
1630 static void stdio_read(void *opaque)
1631 {
1632     int size;
1633     uint8_t buf[1];
1634     
1635     size = read(0, buf, 1);
1636     if (size == 0) {
1637         /* stdin has been closed. Remove it from the active list.  */
1638         qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1639         return;
1640     }
1641     if (size > 0)
1642         stdio_received_byte(buf[0]);
1643 }
1644 
1645 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1646 {
1647     FDCharDriver *s = chr->opaque;
1648     if (!term_timestamps) {
1649         return unix_write(s->fd_out, buf, len);
1650     } else {
1651         int i;
1652         char buf1[64];
1653 
1654         for(i = 0; i < len; i++) {
1655             unix_write(s->fd_out, buf + i, 1);
1656             if (buf[i] == '\n') {
1657                 int64_t ti;
1658                 int secs;
1659 
1660                 ti = get_clock();
1661                 if (term_timestamps_start == -1)
1662                     term_timestamps_start = ti;
1663                 ti -= term_timestamps_start;
1664                 secs = ti / 1000000000;
1665                 snprintf(buf1, sizeof(buf1), 
1666                          "[%02d:%02d:%02d.%03d] ",
1667                          secs / 3600,
1668                          (secs / 60) % 60,
1669                          secs % 60,
1670                          (int)((ti / 1000000) % 1000));
1671                 unix_write(s->fd_out, buf1, strlen(buf1));
1672             }
1673         }
1674         return len;
1675     }
1676 }
1677 
1678 /* init terminal so that we can grab keys */
1679 static struct termios oldtty;
1680 static int old_fd0_flags;
1681 
1682 static void term_exit(void)
1683 {
1684     tcsetattr (0, TCSANOW, &oldtty);
1685     fcntl(0, F_SETFL, old_fd0_flags);
1686 }
1687 
1688 static void term_init(void)
1689 {
1690     struct termios tty;
1691 
1692     tcgetattr (0, &tty);
1693     oldtty = tty;
1694     old_fd0_flags = fcntl(0, F_GETFL);
1695 
1696     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1697                           |INLCR|IGNCR|ICRNL|IXON);
1698     tty.c_oflag |= OPOST;
1699     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1700     /* if graphical mode, we allow Ctrl-C handling */
1701     if (nographic)
1702         tty.c_lflag &= ~ISIG;
1703     tty.c_cflag &= ~(CSIZE|PARENB);
1704     tty.c_cflag |= CS8;
1705     tty.c_cc[VMIN] = 1;
1706     tty.c_cc[VTIME] = 0;
1707     
1708     tcsetattr (0, TCSANOW, &tty);
1709 
1710     atexit(term_exit);
1711 
1712     fcntl(0, F_SETFL, O_NONBLOCK);
1713 }
1714 
1715 static CharDriverState *qemu_chr_open_stdio(void)
1716 {
1717     CharDriverState *chr;
1718 
1719     if (nographic) {
1720         if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1721             return NULL;
1722         chr = qemu_chr_open_fd(0, 1);
1723         chr->chr_write = stdio_write;
1724         if (stdio_nb_clients == 0)
1725             qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1726         client_index = stdio_nb_clients;
1727     } else {
1728         if (stdio_nb_clients != 0)
1729             return NULL;
1730         chr = qemu_chr_open_fd(0, 1);
1731     }
1732     stdio_clients[stdio_nb_clients++] = chr;
1733     if (stdio_nb_clients == 1) {
1734         /* set the terminal in raw mode */
1735         term_init();
1736     }
1737     return chr;
1738 }
1739 
1740 /*
1741  * Create a store entry for a device (e.g., monitor, serial/parallel lines).
1742  * The entry is <domain-path><storeString>/tty and the value is the name
1743  * of the pty associated with the device.
1744  */
1745 static int store_dev_info(char *devName, int domid,
1746                           CharDriverState *cState, char *storeString)
1747 {
1748     int xc_handle;
1749     struct xs_handle *xs;
1750     char *path;
1751     char *newpath;
1752     FDCharDriver *s;
1753     char *pts;
1754 
1755     /* Check for valid arguments (at least, prevent segfaults). */
1756     if ((devName == NULL) || (cState == NULL) || (storeString == NULL)) {
1757         fprintf(logfile, "%s - invalid arguments\n", __FUNCTION__);
1758         return EINVAL;
1759     }
1760 
1761     /*
1762      * Only continue if we're talking to a pty
1763      * Actually, the following code works for any CharDriverState using
1764      * FDCharDriver, but we really only care about pty's here
1765      */
1766     if (strcmp(devName, "pty"))
1767         return 0;
1768 
1769     s = cState->opaque;
1770     if (s == NULL) {
1771         fprintf(logfile, "%s - unable to retrieve fd for '%s'/'%s'\n",
1772                 __FUNCTION__, storeString, devName);
1773         return EBADF;
1774     }
1775 
1776     pts = ptsname(s->fd_in);
1777     if (pts == NULL) {
1778         fprintf(logfile, "%s - unable to determine ptsname '%s'/'%s', "
1779                 "error %d (%s)\n",
1780                 __FUNCTION__, storeString, devName, errno, strerror(errno));
1781         return errno;
1782     }
1783 
1784     /* We now have everything we need to set the xenstore entry. */
1785     xs = xs_daemon_open();
1786     if (xs == NULL) {
1787         fprintf(logfile, "Could not contact XenStore\n");
1788         return -1;
1789     }
1790 
1791     xc_handle = xc_interface_open();
1792     if (xc_handle == -1) {
1793         fprintf(logfile, "xc_interface_open() error\n");
1794         return -1;
1795     }
1796 
1797     path = xs_get_domain_path(xs, domid);
1798     if (path == NULL) {
1799         fprintf(logfile, "xs_get_domain_path() error\n");
1800         return -1;
1801     }
1802     newpath = realloc(path, (strlen(path) + strlen(storeString) +
1803                              strlen("/tty") + 1));
1804     if (newpath == NULL) {
1805         free(path); /* realloc errors leave old block */
1806         fprintf(logfile, "realloc error\n");
1807         return -1;
1808     }
1809     path = newpath;
1810 
1811     strcat(path, storeString);
1812     strcat(path, "/tty");
1813     if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1814         fprintf(logfile, "xs_write for '%s' fail", storeString);
1815         return -1;
1816     }
1817 
1818     free(path);
1819     xs_daemon_close(xs);
1820     close(xc_handle);
1821 
1822     return 0;
1823 }
1824 
1825 #if defined(__linux__)
1826 static CharDriverState *qemu_chr_open_pty(void)
1827 {
1828     struct termios tty;
1829     int master_fd, slave_fd;
1830     
1831     /* Not satisfying */
1832     if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
1833         return NULL;
1834     }
1835     
1836     /* Set raw attributes on the pty. */
1837     cfmakeraw(&tty);
1838     tcsetattr(slave_fd, TCSAFLUSH, &tty);
1839     
1840     fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1841 
1842     return qemu_chr_open_fd(master_fd, master_fd);
1843 }
1844 
1845 static void tty_serial_init(int fd, int speed, 
1846                             int parity, int data_bits, int stop_bits)
1847 {
1848     struct termios tty;
1849     speed_t spd;
1850 
1851 #if 0
1852     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1853            speed, parity, data_bits, stop_bits);
1854 #endif
1855     tcgetattr (fd, &tty);
1856 
1857     switch(speed) {
1858     case 50:
1859         spd = B50;
1860         break;
1861     case 75:
1862         spd = B75;
1863         break;
1864     case 300:
1865         spd = B300;
1866         break;
1867     case 600:
1868         spd = B600;
1869         break;
1870     case 1200:
1871         spd = B1200;
1872         break;
1873     case 2400:
1874         spd = B2400;
1875         break;
1876     case 4800:
1877         spd = B4800;
1878         break;
1879     case 9600:
1880         spd = B9600;
1881         break;
1882     case 19200:
1883         spd = B19200;
1884         break;
1885     case 38400:
1886         spd = B38400;
1887         break;
1888     case 57600:
1889         spd = B57600;
1890         break;
1891     default:
1892     case 115200:
1893         spd = B115200;
1894         break;
1895     }
1896 
1897     cfsetispeed(&tty, spd);
1898     cfsetospeed(&tty, spd);
1899 
1900     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1901                           |INLCR|IGNCR|ICRNL|IXON);
1902     tty.c_oflag &= ~OPOST; /* no output mangling of raw serial stream */
1903     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1904     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1905     switch(data_bits) {
1906     default:
1907     case 8:
1908         tty.c_cflag |= CS8;
1909         break;
1910     case 7:
1911         tty.c_cflag |= CS7;
1912         break;
1913     case 6:
1914         tty.c_cflag |= CS6;
1915         break;
1916     case 5:
1917         tty.c_cflag |= CS5;
1918         break;
1919     }
1920     switch(parity) {
1921     default:
1922     case 'N':
1923         break;
1924     case 'E':
1925         tty.c_cflag |= PARENB;
1926         break;
1927     case 'O':
1928         tty.c_cflag |= PARENB | PARODD;
1929         break;
1930     }
1931     if (stop_bits == 2)
1932         tty.c_cflag |= CSTOPB;
1933     
1934     tcsetattr (fd, TCSANOW, &tty);
1935 }
1936 
1937 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1938 {
1939     FDCharDriver *s = chr->opaque;
1940     
1941     switch(cmd) {
1942     case CHR_IOCTL_SERIAL_SET_PARAMS:
1943         {
1944             QEMUSerialSetParams *ssp = arg;
1945             tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1946                             ssp->data_bits, ssp->stop_bits);
1947         }
1948         break;
1949     case CHR_IOCTL_SERIAL_SET_BREAK:
1950         {
1951             int enable = *(int *)arg;
1952             if (enable)
1953                 tcsendbreak(s->fd_in, 1);
1954         }
1955         break;
1956     default:
1957         return -ENOTSUP;
1958     }
1959     return 0;
1960 }
1961 
1962 static CharDriverState *qemu_chr_open_tty(const char *filename)
1963 {
1964     CharDriverState *chr;
1965     int fd;
1966 
1967     fd = open(filename, O_RDWR | O_NONBLOCK);
1968     if (fd < 0)
1969         return NULL;
1970     fcntl(fd, F_SETFL, O_NONBLOCK);
1971     tty_serial_init(fd, 115200, 'N', 8, 1);
1972     chr = qemu_chr_open_fd(fd, fd);
1973     if (!chr)
1974         return NULL;
1975     chr->chr_ioctl = tty_serial_ioctl;
1976     qemu_chr_reset(chr);
1977     return chr;
1978 }
1979 
1980 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1981 {
1982     int fd = (int)chr->opaque;
1983     uint8_t b;
1984 
1985     switch(cmd) {
1986     case CHR_IOCTL_PP_READ_DATA:
1987         if (ioctl(fd, PPRDATA, &b) < 0)
1988             return -ENOTSUP;
1989         *(uint8_t *)arg = b;
1990         break;
1991     case CHR_IOCTL_PP_WRITE_DATA:
1992         b = *(uint8_t *)arg;
1993         if (ioctl(fd, PPWDATA, &b) < 0)
1994             return -ENOTSUP;
1995         break;
1996     case CHR_IOCTL_PP_READ_CONTROL:
1997         if (ioctl(fd, PPRCONTROL, &b) < 0)
1998             return -ENOTSUP;
1999         *(uint8_t *)arg = b;
2000         break;
2001     case CHR_IOCTL_PP_WRITE_CONTROL:
2002         b = *(uint8_t *)arg;
2003         if (ioctl(fd, PPWCONTROL, &b) < 0)
2004             return -ENOTSUP;
2005         break;
2006     case CHR_IOCTL_PP_READ_STATUS:
2007         if (ioctl(fd, PPRSTATUS, &b) < 0)
2008             return -ENOTSUP;
2009         *(uint8_t *)arg = b;
2010         break;
2011     default:
2012         return -ENOTSUP;
2013     }
2014     return 0;
2015 }
2016 
2017 static CharDriverState *qemu_chr_open_pp(const char *filename)
2018 {
2019     CharDriverState *chr;
2020     int fd;
2021 
2022     fd = open(filename, O_RDWR);
2023     if (fd < 0)
2024         return NULL;
2025 
2026     if (ioctl(fd, PPCLAIM) < 0) {
2027         close(fd);
2028         return NULL;
2029     }
2030 
2031     chr = qemu_mallocz(sizeof(CharDriverState));
2032     if (!chr) {
2033         close(fd);
2034         return NULL;
2035     }
2036     chr->opaque = (void *)fd;
2037     chr->chr_write = null_chr_write;
2038     chr->chr_ioctl = pp_ioctl;
2039 
2040     qemu_chr_reset(chr);
2041 
2042     return chr;
2043 }
2044 
2045 #else
2046 static CharDriverState *qemu_chr_open_pty(void)
2047 {
2048     return NULL;
2049 }
2050 #endif
2051 
2052 #endif /* !defined(_WIN32) */
2053 
2054 #ifdef _WIN32
2055 typedef struct {
2056     CharDriverState *chr;
2057     int max_size;
2058     HANDLE hcom, hrecv, hsend;
2059     OVERLAPPED orecv, osend;
2060     BOOL fpipe;
2061     DWORD len;
2062 } WinCharState;
2063 
2064 #define NSENDBUF 2048
2065 #define NRECVBUF 2048
2066 #define MAXCONNECT 1
2067 #define NTIMEOUT 5000
2068 
2069 static int win_chr_poll(void *opaque);
2070 static int win_chr_pipe_poll(void *opaque);
2071 
2072 static void win_chr_close2(WinCharState *s)
2073 {
2074     if (s->hsend) {
2075         CloseHandle(s->hsend);
2076         s->hsend = NULL;
2077     }
2078     if (s->hrecv) {
2079         CloseHandle(s->hrecv);
2080         s->hrecv = NULL;
2081     }
2082     if (s->hcom) {
2083         CloseHandle(s->hcom);
2084         s->hcom = NULL;
2085     }
2086     if (s->fpipe)
2087         qemu_del_polling_cb(win_chr_pipe_poll, s);
2088     else
2089         qemu_del_polling_cb(win_chr_poll, s);
2090 }
2091 
2092 static void win_chr_close(CharDriverState *chr)
2093 {
2094     WinCharState *s = chr->opaque;
2095     win_chr_close2(s);
2096 }
2097 
2098 static int win_chr_init(WinCharState *s, CharDriverState *chr, const char *filename)
2099 {
2100     COMMCONFIG comcfg;
2101     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2102     COMSTAT comstat;
2103     DWORD size;
2104     DWORD err;
2105     
2106     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2107     if (!s->hsend) {
2108         fprintf(stderr, "Failed CreateEvent\n");
2109         goto fail;
2110     }
2111     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2112     if (!s->hrecv) {
2113         fprintf(stderr, "Failed CreateEvent\n");
2114         goto fail;
2115     }
2116 
2117     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2118                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2119     if (s->hcom == INVALID_HANDLE_VALUE) {
2120         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2121         s->hcom = NULL;
2122         goto fail;
2123     }
2124     
2125     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2126         fprintf(stderr, "Failed SetupComm\n");
2127         goto fail;
2128     }
2129     
2130     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2131     size = sizeof(COMMCONFIG);
2132     GetDefaultCommConfig(filename, &comcfg, &size);
2133     comcfg.dcb.DCBlength = sizeof(DCB);
2134     CommConfigDialog(filename, NULL, &comcfg);
2135 
2136     if (!SetCommState(s->hcom, &comcfg.dcb)) {
2137         fprintf(stderr, "Failed SetCommState\n");
2138         goto fail;
2139     }
2140 
2141     if (!SetCommMask(s->hcom, EV_ERR)) {
2142         fprintf(stderr, "Failed SetCommMask\n");
2143         goto fail;
2144     }
2145 
2146     cto.ReadIntervalTimeout = MAXDWORD;
2147     if (!SetCommTimeouts(s->hcom, &cto)) {
2148         fprintf(stderr, "Failed SetCommTimeouts\n");
2149         goto fail;
2150     }
2151     
2152     if (!ClearCommError(s->hcom, &err, &comstat)) {
2153         fprintf(stderr, "Failed ClearCommError\n");
2154         goto fail;
2155     }
2156     s->chr = chr;
2157     qemu_add_polling_cb(win_chr_poll, s);
2158     return 0;
2159 
2160  fail:
2161     win_chr_close2(s);
2162     return -1;
2163 }
2164 
2165 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2166 {
2167     WinCharState *s = chr->opaque;
2168     DWORD len, ret, size, err;
2169 
2170     len = len1;
2171     ZeroMemory(&s->osend, sizeof(s->osend));
2172     s->osend.hEvent = s->hsend;
2173     while (len > 0) {
2174         if (s->hsend)
2175             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2176         else
2177             ret = WriteFile(s->hcom, buf, len, &size, NULL);
2178         if (!ret) {
2179             err = GetLastError();
2180             if (err == ERROR_IO_PENDING) {
2181                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2182                 if (ret) {
2183                     buf += size;
2184                     len -= size;
2185                 } else {
2186                     break;
2187                 }
2188             } else {
2189                 break;
2190             }
2191         } else {
2192             buf += size;
2193             len -= size;
2194         }
2195     }
2196     return len1 - len;
2197 }
2198 
2199 static int win_chr_read_poll(WinCharState *s)
2200 {
2201     s->max_size = qemu_chr_can_read(s->chr);
2202     return s->max_size;
2203 }
2204 
2205 static void win_chr_readfile(WinCharState *s)
2206 {
2207     int ret, err;
2208     uint8_t buf[1024];
2209     DWORD size;
2210     
2211     ZeroMemory(&s->orecv, sizeof(s->orecv));
2212     s->orecv.hEvent = s->hrecv;
2213     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2214     if (!ret) {
2215         err = GetLastError();
2216         if (err == ERROR_IO_PENDING) {
2217             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2218         }
2219     }
2220 
2221     if (size > 0) {
2222         qemu_chr_read(s->chr, buf, size);
2223     }
2224 }
2225 
2226 static void win_chr_read(WinCharState *s)
2227 {
2228     if (s->len > s->max_size)
2229         s->len = s->max_size;
2230     if (s->len == 0)
2231         return;
2232     
2233     win_chr_readfile(s);
2234 }
2235 
2236 static int win_chr_poll(void *opaque)
2237 {
2238     WinCharState *s = opaque;
2239     COMSTAT status;
2240     DWORD comerr;
2241     
2242     ClearCommError(s->hcom, &comerr, &status);
2243     if (status.cbInQue > 0) {
2244         s->len = status.cbInQue;
2245         win_chr_read_poll(s);
2246         win_chr_read(s);
2247         return 1;
2248     }
2249     return 0;
2250 }
2251 
2252 static CharDriverState *qemu_chr_open_win(const char *filename)
2253 {
2254     CharDriverState *chr;
2255     WinCharState *s;
2256     
2257     chr = qemu_mallocz(sizeof(CharDriverState));
2258     if (!chr)
2259         return NULL;
2260     s = qemu_mallocz(sizeof(WinCharState));
2261     if (!s) {
2262         free(chr);
2263         return NULL;
2264     }
2265     chr->opaque = s;
2266     chr->chr_write = win_chr_write;
2267     chr->chr_close = win_chr_close;
2268 
2269     if (win_chr_init(s, chr, filename) < 0) {
2270         free(s);
2271         free(chr);
2272         return NULL;
2273     }
2274     qemu_chr_reset(chr);
2275     return chr;
2276 }
2277 
2278 static int win_chr_pipe_poll(void *opaque)
2279 {
2280     WinCharState *s = opaque;
2281     DWORD size;
2282 
2283     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2284     if (size > 0) {
2285         s->len = size;
2286         win_chr_read_poll(s);
2287         win_chr_read(s);
2288         return 1;
2289     }
2290     return 0;
2291 }
2292 
2293 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2294 {
2295     OVERLAPPED ov;
2296     int ret;
2297     DWORD size;
2298     char openname[256];
2299     
2300     s->fpipe = TRUE;
2301 
2302     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2303     if (!s->hsend) {
2304         fprintf(stderr, "Failed CreateEvent\n");
2305         goto fail;
2306     }
2307     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2308     if (!s->hrecv) {
2309         fprintf(stderr, "Failed CreateEvent\n");
2310         goto fail;
2311     }
2312     
2313     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2314     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2315                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2316                               PIPE_WAIT,
2317                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2318     if (s->hcom == INVALID_HANDLE_VALUE) {
2319         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2320         s->hcom = NULL;
2321         goto fail;
2322     }
2323 
2324     ZeroMemory(&ov, sizeof(ov));
2325     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2326     ret = ConnectNamedPipe(s->hcom, &ov);
2327     if (ret) {
2328         fprintf(stderr, "Failed ConnectNamedPipe\n");
2329         goto fail;
2330     }
2331 
2332     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2333     if (!ret) {
2334         fprintf(stderr, "Failed GetOverlappedResult\n");
2335         if (ov.hEvent) {
2336             CloseHandle(ov.hEvent);
2337             ov.hEvent = NULL;
2338         }
2339         goto fail;
2340     }
2341 
2342     if (ov.hEvent) {
2343         CloseHandle(ov.hEvent);
2344         ov.hEvent = NULL;
2345     }
2346     qemu_add_polling_cb(win_chr_pipe_poll, s);
2347     return 0;
2348 
2349  fail:
2350     win_chr_close2(s);
2351     return -1;
2352 }
2353 
2354 
2355 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2356 {
2357     CharDriverState *chr;
2358     WinCharState *s;
2359 
2360     chr = qemu_mallocz(sizeof(CharDriverState));
2361     if (!chr)
2362         return NULL;
2363     s = qemu_mallocz(sizeof(WinCharState));
2364     if (!s) {
2365         free(chr);
2366         return NULL;
2367     }
2368     chr->opaque = s;
2369     chr->chr_write = win_chr_write;
2370     chr->chr_close = win_chr_close;
2371     
2372     if (win_chr_pipe_init(s, filename) < 0) {
2373         free(s);
2374         free(chr);
2375         return NULL;
2376     }
2377     qemu_chr_reset(chr);
2378     return chr;
2379 }
2380 
2381 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2382 {
2383     CharDriverState *chr;
2384     WinCharState *s;
2385 
2386     chr = qemu_mallocz(sizeof(CharDriverState));
2387     if (!chr)
2388         return NULL;
2389     s = qemu_mallocz(sizeof(WinCharState));
2390     if (!s) {
2391         free(chr);
2392         return NULL;
2393     }
2394     s->hcom = fd_out;
2395     chr->opaque = s;
2396     chr->chr_write = win_chr_write;
2397     qemu_chr_reset(chr);
2398     return chr;
2399 }
2400     
2401 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2402 {
2403     HANDLE fd_out;
2404     
2405     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2406                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2407     if (fd_out == INVALID_HANDLE_VALUE)
2408         return NULL;
2409 
2410     return qemu_chr_open_win_file(fd_out);
2411 }
2412 #endif
2413 
2414 /***********************************************************/
2415 /* UDP Net console */
2416 
2417 typedef struct {
2418     int fd;
2419     struct sockaddr_in daddr;
2420     char buf[1024];
2421     int bufcnt;
2422     int bufptr;
2423     int max_size;
2424 } NetCharDriver;
2425 
2426 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2427 {
2428     NetCharDriver *s = chr->opaque;
2429 
2430     return sendto(s->fd, buf, len, 0,
2431                   (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2432 }
2433 
2434 static int udp_chr_read_poll(void *opaque)
2435 {
2436     CharDriverState *chr = opaque;
2437     NetCharDriver *s = chr->opaque;
2438 
2439     s->max_size = qemu_chr_can_read(chr);
2440 
2441     /* If there were any stray characters in the queue process them
2442      * first
2443      */
2444     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2445         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2446         s->bufptr++;
2447         s->max_size = qemu_chr_can_read(chr);
2448     }
2449     return s->max_size;
2450 }
2451 
2452 static void udp_chr_read(void *opaque)
2453 {
2454     CharDriverState *chr = opaque;
2455     NetCharDriver *s = chr->opaque;
2456 
2457     if (s->max_size == 0)
2458         return;
2459     s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2460     s->bufptr = s->bufcnt;
2461     if (s->bufcnt <= 0)
2462         return;
2463 
2464     s->bufptr = 0;
2465     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2466         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2467         s->bufptr++;
2468         s->max_size = qemu_chr_can_read(chr);
2469     }
2470 }
2471 
2472 static void udp_chr_update_read_handler(CharDriverState *chr)
2473 {
2474     NetCharDriver *s = chr->opaque;
2475 
2476     if (s->fd >= 0) {
2477         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2478                              udp_chr_read, NULL, chr);
2479     }
2480 }
2481 
2482 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2483 #ifndef _WIN32
2484 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2485 #endif
2486 int parse_host_src_port(struct sockaddr_in *haddr,
2487                         struct sockaddr_in *saddr,
2488                         const char *str);
2489 
2490 static CharDriverState *qemu_chr_open_udp(const char *def)
2491 {
2492     CharDriverState *chr = NULL;
2493     NetCharDriver *s = NULL;
2494     int fd = -1;
2495     struct sockaddr_in saddr;
2496 
2497     chr = qemu_mallocz(sizeof(CharDriverState));
2498     if (!chr)
2499         goto return_err;
2500     s = qemu_mallocz(sizeof(NetCharDriver));
2501     if (!s)
2502         goto return_err;
2503 
2504     fd = socket(PF_INET, SOCK_DGRAM, 0);
2505     if (fd < 0) {
2506         perror("socket(PF_INET, SOCK_DGRAM)");
2507         goto return_err;
2508     }
2509 
2510     if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2511         printf("Could not parse: %s\n", def);
2512         goto return_err;
2513     }
2514 
2515     if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2516     {
2517         perror("bind");
2518         goto return_err;
2519     }
2520 
2521     s->fd = fd;
2522     s->bufcnt = 0;
2523     s->bufptr = 0;
2524     chr->opaque = s;
2525     chr->chr_write = udp_chr_write;
2526     chr->chr_update_read_handler = udp_chr_update_read_handler;
2527     return chr;
2528 
2529 return_err:
2530     if (chr)
2531         free(chr);
2532     if (s)
2533         free(s);
2534     if (fd >= 0)
2535         closesocket(fd);
2536     return NULL;
2537 }
2538 
2539 /***********************************************************/
2540 /* TCP Net console */
2541 
2542 typedef struct {
2543     int fd, listen_fd;
2544     int connected;
2545     int max_size;
2546     int do_telnetopt;
2547     int do_nodelay;
2548     int is_unix;
2549     int is_localhost;
2550 } TCPCharDriver;
2551 
2552 static void tcp_chr_accept(void *opaque);
2553 
2554 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2555 {
2556     TCPCharDriver *s = chr->opaque;
2557     if (s->connected) {
2558         return send_all(s->fd, buf, len);
2559     } else {
2560         /* XXX: indicate an error ? */
2561         return len;
2562     }
2563 }
2564 
2565 static int tcp_chr_read_poll(void *opaque)
2566 {
2567     CharDriverState *chr = opaque;
2568     TCPCharDriver *s = chr->opaque;
2569     if (!s->connected)
2570         return 0;
2571     s->max_size = qemu_chr_can_read(chr);
2572     return s->max_size;
2573 }
2574 
2575 #define IAC 255
2576 #define IAC_BREAK 243
2577 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2578                                       TCPCharDriver *s,
2579                                       char *buf, int *size)
2580 {
2581     /* Handle any telnet client's basic IAC options to satisfy char by
2582      * char mode with no echo.  All IAC options will be removed from
2583      * the buf and the do_telnetopt variable will be used to track the
2584      * state of the width of the IAC information.
2585      *
2586      * IAC commands come in sets of 3 bytes with the exception of the
2587      * "IAC BREAK" command and the double IAC.
2588      */
2589 
2590     int i;
2591     int j = 0;
2592 
2593     for (i = 0; i < *size; i++) {
2594         if (s->do_telnetopt > 1) {
2595             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2596                 /* Double IAC means send an IAC */
2597                 if (j != i)
2598                     buf[j] = buf[i];
2599                 j++;
2600                 s->do_telnetopt = 1;
2601             } else {
2602                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2603                     /* Handle IAC break commands by sending a serial break */
2604                     qemu_chr_event(chr, CHR_EVENT_BREAK);
2605                     s->do_telnetopt++;
2606                 }
2607                 s->do_telnetopt++;
2608             }
2609             if (s->do_telnetopt >= 4) {
2610                 s->do_telnetopt = 1;
2611             }
2612         } else {
2613             if ((unsigned char)buf[i] == IAC) {
2614                 s->do_telnetopt = 2;
2615             } else {
2616                 if (j != i)
2617                     buf[j] = buf[i];
2618                 j++;
2619             }
2620         }
2621     }
2622     *size = j;
2623 }
2624 
2625 static void tcp_chr_read(void *opaque)
2626 {
2627     CharDriverState *chr = opaque;
2628     TCPCharDriver *s = chr->opaque;
2629     uint8_t buf[1024];
2630     int len, size;
2631 
2632     if (!s->connected || s->max_size <= 0)
2633         return;
2634     len = sizeof(buf);
2635     if (len > s->max_size)
2636         len = s->max_size;
2637     size = recv(s->fd, buf, len, 0);
2638     if (size == 0) {
2639         /* connection closed */
2640         s->connected = 0;
2641         if (s->listen_fd >= 0) {
2642             qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2643         }
2644         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2645         closesocket(s->fd);
2646         s->fd = -1;
2647     } else if (size > 0) {
2648         if (s->do_telnetopt)
2649             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2650         if (size > 0)
2651             qemu_chr_read(chr, buf, size);
2652     }
2653 }
2654 
2655 static void tcp_chr_connect(void *opaque)
2656 {
2657     CharDriverState *chr = opaque;
2658     TCPCharDriver *s = chr->opaque;
2659 
2660     s->connected = 1;
2661     qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2662                          tcp_chr_read, NULL, chr);
2663     qemu_chr_reset(chr);
2664 }
2665 
2666 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2667 static void tcp_chr_telnet_init(int fd)
2668 {
2669     char buf[3];
2670     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2671     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2672     send(fd, (char *)buf, 3, 0);
2673     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2674     send(fd, (char *)buf, 3, 0);
2675     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2676     send(fd, (char *)buf, 3, 0);
2677     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2678     send(fd, (char *)buf, 3, 0);
2679 }
2680 
2681 static void socket_set_nodelay(int fd)
2682 {
2683     int val = 1;
2684     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2685 }
2686 
2687 #ifdef __sun__
2688 
2689 #include <priv.h>
2690 #include <ucred.h>
2691 
2692 #ifndef PRIV_VIRT_MANAGE
2693 #define PRIV_VIRT_MANAGE ((const char *)("virt_manage"))
2694 #endif
2695 
2696 /*
2697  * The logic is as follows: if the user has asked for a localhost-only
2698  * connection, then anyone connecting must be privileged.  Otherwise,
2699  * it's a remote connection explicitly specified by the user, and we
2700  * don't check.
2701  */
2702 static int connection_allowed(TCPCharDriver *s, int fd)
2703 {
2704         ucred_t *ucred = NULL;
2705         const priv_set_t *privs;
2706         int ret = 0;
2707 
2708         if (!s->is_localhost)
2709             return 1;
2710 
2711         if (getpeerucred(fd, &ucred) == -1 ||
2712             (privs = ucred_getprivset(ucred, PRIV_EFFECTIVE)) == NULL)
2713                 goto out;
2714 
2715         ret = priv_ismember(privs, PRIV_VIRT_MANAGE);
2716 
2717 out:
2718         if (ucred != NULL)
2719                 ucred_free(ucred);
2720         return ret;
2721 }
2722 
2723 #else
2724 #define connection_allowed(s, fd) 1
2725 #endif
2726 
2727 static void tcp_chr_accept(void *opaque)
2728 {
2729     CharDriverState *chr = opaque;
2730     TCPCharDriver *s = chr->opaque;
2731     struct sockaddr_in saddr;
2732 #ifndef _WIN32
2733     struct sockaddr_un uaddr;
2734 #endif
2735     struct sockaddr *addr;
2736     socklen_t len;
2737     int fd;
2738 
2739     for(;;) {
2740 #ifndef _WIN32
2741         if (s->is_unix) {
2742             len = sizeof(uaddr);
2743             addr = (struct sockaddr *)&uaddr;
2744         } else
2745 #endif
2746         {
2747             len = sizeof(saddr);
2748             addr = (struct sockaddr *)&saddr;
2749         }
2750         fd = accept(s->listen_fd, addr, &len);
2751         if (fd < 0 && errno != EINTR) {
2752             return;
2753         } else if (fd >= 0) {
2754             if (s->do_telnetopt)
2755                 tcp_chr_telnet_init(fd);
2756             break;
2757         }
2758     }
2759 
2760     if (!connection_allowed(s, fd)) {
2761         close(fd);
2762         return;
2763     }
2764 
2765     socket_set_nonblock(fd);
2766     if (s->do_nodelay)
2767         socket_set_nodelay(fd);
2768     s->fd = fd;
2769     qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2770     tcp_chr_connect(chr);
2771 }
2772 
2773 static void tcp_chr_close(CharDriverState *chr)
2774 {
2775     TCPCharDriver *s = chr->opaque;
2776     if (s->fd >= 0)
2777         closesocket(s->fd);
2778     if (s->listen_fd >= 0)
2779         closesocket(s->listen_fd);
2780     qemu_free(s);
2781 }
2782 
2783 static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2784                                           int is_telnet,
2785                                           int is_unix)
2786 {
2787     CharDriverState *chr = NULL;
2788     TCPCharDriver *s = NULL;
2789     int fd = -1, ret, err, val;
2790     int is_listen = 0;
2791     int is_waitconnect = 1;
2792     int do_nodelay = 0;
2793     int is_localhost = 0;
2794     const char *ptr;
2795     struct sockaddr_in saddr;
2796 #ifndef _WIN32
2797     struct sockaddr_un uaddr;
2798 #endif
2799     struct sockaddr *addr;
2800     socklen_t addrlen;
2801 
2802 #ifndef _WIN32
2803     if (is_unix) {
2804         is_localhost = 1;
2805         addr = (struct sockaddr *)&uaddr;
2806         addrlen = sizeof(uaddr);
2807         if (parse_unix_path(&uaddr, host_str) < 0)
2808             goto fail;
2809     } else
2810 #endif
2811     {
2812         addr = (struct sockaddr *)&saddr;
2813         addrlen = sizeof(saddr);
2814         if (parse_host_port(&saddr, host_str) < 0)
2815             goto fail;
2816     }
2817 
2818     if (!strncmp("localhost", host_str, sizeof("localhost") - 1) ||
2819         !strncmp("127.0.0.1", host_str, sizeof("127.0.0.1") - 1))
2820         is_localhost = 1;
2821          
2822     ptr = host_str;
2823     while((ptr = strchr(ptr,','))) {
2824         ptr++;
2825         if (!strncmp(ptr,"server",6)) {
2826             is_listen = 1;
2827         } else if (!strncmp(ptr,"nowait",6)) {
2828             is_waitconnect = 0;
2829         } else if (!strncmp(ptr,"nodelay",6)) {
2830             do_nodelay = 1;
2831         } else {
2832             printf("Unknown option: %s\n", ptr);
2833             goto fail;
2834         }
2835     }
2836     if (!is_listen)
2837         is_waitconnect = 0;
2838 
2839     chr = qemu_mallocz(sizeof(CharDriverState));
2840     if (!chr)
2841         goto fail;
2842     s = qemu_mallocz(sizeof(TCPCharDriver));
2843     if (!s)
2844         goto fail;
2845 
2846 #ifndef _WIN32
2847     if (is_unix)
2848         fd = socket(PF_UNIX, SOCK_STREAM, 0);
2849     else
2850 #endif
2851         fd = socket(PF_INET, SOCK_STREAM, 0);
2852         
2853     if (fd < 0) 
2854         goto fail;
2855 
2856     if (!is_waitconnect)
2857         socket_set_nonblock(fd);
2858 
2859     s->connected = 0;
2860     s->fd = -1;
2861     s->listen_fd = -1;
2862     s->is_unix = is_unix;
2863     s->is_localhost = is_localhost;
2864     s->do_nodelay = do_nodelay && !is_unix;
2865 
2866     chr->opaque = s;
2867     chr->chr_write = tcp_chr_write;
2868     chr->chr_close = tcp_chr_close;
2869 
2870     if (is_listen) {
2871         /* allow fast reuse */
2872 #ifndef _WIN32
2873         if (is_unix) {
2874             char path[109];
2875             strncpy(path, uaddr.sun_path, 108);
2876             path[108] = 0;
2877             unlink(path);
2878         } else
2879 #endif
2880         {
2881             val = 1;
2882             setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2883         }
2884         
2885         ret = bind(fd, addr, addrlen);
2886         if (ret < 0)
2887             goto fail;
2888 
2889         ret = listen(fd, 0);
2890         if (ret < 0)
2891             goto fail;
2892 
2893         s->listen_fd = fd;
2894         qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2895         if (is_telnet)
2896             s->do_telnetopt = 1;
2897     } else {
2898         for(;;) {
2899             ret = connect(fd, addr, addrlen);
2900             if (ret < 0) {
2901                 err = socket_error();
2902                 if (err == EINTR || err == EWOULDBLOCK) {
2903                 } else if (err == EINPROGRESS) {
2904                     break;
2905                 } else {
2906                     goto fail;
2907                 }
2908             } else {
2909                 s->connected = 1;
2910                 break;
2911             }
2912         }
2913         s->fd = fd;
2914         socket_set_nodelay(fd);
2915         if (s->connected)
2916             tcp_chr_connect(chr);
2917         else
2918             qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2919     }
2920     
2921     if (is_listen && is_waitconnect) {
2922         printf("QEMU waiting for connection on: %s\n", host_str);
2923         tcp_chr_accept(chr);
2924         socket_set_nonblock(s->listen_fd);
2925     }
2926 
2927     return chr;
2928  fail:
2929     if (fd >= 0)
2930         closesocket(fd);
2931     qemu_free(s);
2932     qemu_free(chr);
2933     return NULL;
2934 }
2935 
2936 CharDriverState *qemu_chr_open(const char *filename)
2937 {
2938     const char *p;
2939 
2940     if (!strcmp(filename, "vc")) {
2941         return text_console_init(&display_state);
2942     } else if (!strcmp(filename, "null")) {
2943         return qemu_chr_open_null();
2944     } else 
2945     if (strstart(filename, "tcp:", &p)) {
2946         return qemu_chr_open_tcp(p, 0, 0);
2947     } else
2948     if (strstart(filename, "telnet:", &p)) {
2949         return qemu_chr_open_tcp(p, 1, 0);
2950     } else
2951     if (strstart(filename, "udp:", &p)) {
2952         return qemu_chr_open_udp(p);
2953     } else
2954 #ifndef _WIN32
2955     if (strstart(filename, "unix:", &p)) {
2956         return qemu_chr_open_tcp(p, 0, 1);
2957     } else if (strstart(filename, "file:", &p)) {
2958         return qemu_chr_open_file_out(p);
2959     } else if (strstart(filename, "pipe:", &p)) {
2960         return qemu_chr_open_pipe(p);
2961     } else if (!strcmp(filename, "pty")) {
2962         return qemu_chr_open_pty();
2963     } else if (!strcmp(filename, "stdio")) {
2964         return qemu_chr_open_stdio();
2965     } else 
2966 #endif
2967 #if defined(__linux__)
2968     if (strstart(filename, "/dev/parport", NULL)) {
2969         return qemu_chr_open_pp(filename);
2970     } else 
2971     if (strstart(filename, "/dev/", NULL)) {
2972         return qemu_chr_open_tty(filename);
2973     } else 
2974 #endif
2975 #ifdef _WIN32
2976     if (strstart(filename, "COM", NULL)) {
2977         return qemu_chr_open_win(filename);
2978     } else
2979     if (strstart(filename, "pipe:", &p)) {
2980         return qemu_chr_open_win_pipe(p);
2981     } else
2982     if (strstart(filename, "file:", &p)) {
2983         return qemu_chr_open_win_file_out(p);
2984     }
2985 #endif
2986     {
2987         return NULL;
2988     }
2989 }
2990 
2991 void qemu_chr_close(CharDriverState *chr)
2992 {
2993     if (chr->chr_close)
2994         chr->chr_close(chr);
2995 }
2996 
2997 /***********************************************************/
2998 /* network device redirectors */
2999 
3000 void hex_dump(FILE *f, const uint8_t *buf, int size)
3001 {
3002     int len, i, j, c;
3003 
3004     for(i=0;i<size;i+=16) {
3005         len = size - i;
3006         if (len > 16)
3007             len = 16;
3008         fprintf(f, "%08x ", i);
3009         for(j=0;j<16;j++) {
3010             if (j < len)
3011                 fprintf(f, " %02x", buf[i+j]);
3012             else
3013                 fprintf(f, "   ");
3014         }
3015         fprintf(f, " ");
3016         for(j=0;j<len;j++) {
3017             c = buf[i+j];
3018             if (c < ' ' || c > '~')
3019                 c = '.';
3020             fprintf(f, "%c", c);
3021         }
3022         fprintf(f, "\n");
3023     }
3024 }
3025 
3026 static int parse_macaddr(uint8_t *macaddr, const char *p)
3027 {
3028     int i;
3029     for(i = 0; i < 6; i++) {
3030         macaddr[i] = strtol(p, (char **)&p, 16);
3031         if (i == 5) {
3032             if (*p != '\0') 
3033                 return -1;
3034         } else {
3035             if (*p != ':') 
3036                 return -1;
3037             p++;
3038         }
3039     }
3040     return 0;
3041 }
3042 
3043 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3044 {
3045     const char *p, *p1;
3046     int len;
3047     p = *pp;
3048     p1 = strchr(p, sep);
3049     if (!p1)
3050         return -1;
3051     len = p1 - p;
3052     p1++;
3053     if (buf_size > 0) {
3054         if (len > buf_size - 1)
3055             len = buf_size - 1;
3056         memcpy(buf, p, len);
3057         buf[len] = '\0';
3058     }
3059     *pp = p1;
3060     return 0;
3061 }
3062 
3063 int parse_host_src_port(struct sockaddr_in *haddr,
3064                         struct sockaddr_in *saddr,
3065                         const char *input_str)
3066 {
3067     char *str = strdup(input_str);
3068     char *host_str = str;
3069     char *src_str;
3070     char *ptr;
3071 
3072     /*
3073      * Chop off any extra arguments at the end of the string which
3074      * would start with a comma, then fill in the src port information
3075      * if it was provided else use the "any address" and "any port".
3076      */
3077     if ((ptr = strchr(str,',')))
3078         *ptr = '\0';
3079 
3080     if ((src_str = strchr(input_str,'@'))) {
3081         *src_str = '\0';
3082         src_str++;
3083     }
3084 
3085     if (parse_host_port(haddr, host_str) < 0)
3086         goto fail;
3087 
3088     if (!src_str || *src_str == '\0')
3089         src_str = ":0";
3090 
3091     if (parse_host_port(saddr, src_str) < 0)
3092         goto fail;
3093 
3094     free(str);
3095     return(0);
3096 
3097 fail:
3098     free(str);
3099     return -1;
3100 }
3101 
3102 int parse_host(struct sockaddr_in *saddr, const char *buf)
3103 {
3104     struct hostent *he;
3105 
3106     if ((he = gethostbyname(buf)) != NULL) {
3107         saddr->sin_addr = *(struct in_addr *)he->h_addr;
3108     } else {
3109         if (!inet_aton(buf, &saddr->sin_addr))
3110             return -1;
3111     }
3112     return 0;
3113 }
3114 
3115 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3116 {
3117     char buf[512];
3118     const char *p, *r;
3119     int port;
3120 
3121     p = str;
3122     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3123         return -1;
3124     saddr->sin_family = AF_INET;
3125     if (buf[0] == '\0') {
3126         saddr->sin_addr.s_addr = 0;
3127     } else {
3128         if (parse_host(saddr, buf) == -1)
3129             return -1;
3130     }
3131     port = strtol(p, (char **)&r, 0);
3132     if (r == p)
3133         return -1;
3134     saddr->sin_port = htons(port);
3135     return 0;
3136 }
3137 
3138 #ifndef _WIN32
3139 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3140 {
3141     const char *p;
3142     int len;
3143 
3144     len = MIN(108, strlen(str));
3145     p = strchr(str, ',');
3146     if (p)
3147         len = MIN(len, p - str);
3148 
3149     memset(uaddr, 0, sizeof(*uaddr));
3150 
3151     uaddr->sun_family = AF_UNIX;
3152     memcpy(uaddr->sun_path, str, len);
3153 
3154     return 0;
3155 }
3156 #endif
3157 
3158 /* find or alloc a new VLAN */
3159 VLANState *qemu_find_vlan(int id)
3160 {
3161     VLANState **pvlan, *vlan;
3162     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3163         if (vlan->id == id)
3164             return vlan;
3165     }
3166     vlan = qemu_mallocz(sizeof(VLANState));
3167     if (!vlan)
3168         return NULL;
3169     vlan->id = id;
3170     vlan->next = NULL;
3171     pvlan = &first_vlan;
3172     while (*pvlan != NULL)
3173         pvlan = &(*pvlan)->next;
3174     *pvlan = vlan;
3175     return vlan;
3176 }
3177 
3178 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3179                                       IOReadHandler *fd_read,
3180                                       IOCanRWHandler *fd_can_read,
3181                                       void *opaque)
3182 {
3183     VLANClientState *vc, **pvc;
3184     vc = qemu_mallocz(sizeof(VLANClientState));
3185     if (!vc)
3186         return NULL;
3187     vc->fd_read = fd_read;
3188     vc->fd_can_read = fd_can_read;
3189     vc->opaque = opaque;
3190     vc->vlan = vlan;
3191 
3192     vc->next = NULL;
3193     pvc = &vlan->first_client;
3194     while (*pvc != NULL)
3195         pvc = &(*pvc)->next;
3196     *pvc = vc;
3197     return vc;
3198 }
3199 
3200 int qemu_can_send_packet(VLANClientState *vc1)
3201 {
3202     VLANState *vlan = vc1->vlan;
3203     VLANClientState *vc;
3204 
3205     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3206         if (vc != vc1) {
3207             if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3208                 return 0;
3209         }
3210     }
3211     return 1;
3212 }
3213 
3214 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3215 {
3216     VLANState *vlan = vc1->vlan;
3217     VLANClientState *vc;
3218 
3219 #if 0
3220     printf("vlan %d send:\n", vlan->id);
3221     hex_dump(stdout, buf, size);
3222 #endif
3223     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3224         if (vc != vc1) {
3225             vc->fd_read(vc->opaque, buf, size);
3226         }
3227     }
3228 }
3229 
3230 #if defined(CONFIG_SLIRP)
3231 
3232 /* slirp network adapter */
3233 
3234 static int slirp_inited;
3235 static VLANClientState *slirp_vc;
3236 
3237 int slirp_can_output(void)
3238 {
3239     return !slirp_vc || qemu_can_send_packet(slirp_vc);
3240 }
3241 
3242 void slirp_output(const uint8_t *pkt, int pkt_len)
3243 {
3244 #if 0
3245     printf("slirp output:\n");
3246     hex_dump(stdout, pkt, pkt_len);
3247 #endif
3248     if (!slirp_vc)
3249         return;
3250     qemu_send_packet(slirp_vc, pkt, pkt_len);
3251 }
3252 
3253 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3254 {
3255 #if 0
3256     printf("slirp input:\n");
3257     hex_dump(stdout, buf, size);
3258 #endif
3259     slirp_input(buf, size);
3260 }
3261 
3262 static int net_slirp_init(VLANState *vlan)
3263 {
3264     if (!slirp_inited) {
3265         slirp_inited = 1;
3266         slirp_init();
3267     }
3268     slirp_vc = qemu_new_vlan_client(vlan, 
3269                                     slirp_receive, NULL, NULL);
3270     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3271     return 0;
3272 }
3273 
3274 static void net_slirp_redir(const char *redir_str)
3275 {
3276     int is_udp;
3277     char buf[256], *r;
3278     const char *p;
3279     struct in_addr guest_addr;
3280     int host_port, guest_port;
3281     
3282     if (!slirp_inited) {
3283         slirp_inited = 1;
3284         slirp_init();
3285     }
3286 
3287     p = redir_str;
3288     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3289         goto fail;
3290     if (!strcmp(buf, "tcp")) {
3291         is_udp = 0;
3292     } else if (!strcmp(buf, "udp")) {
3293         is_udp = 1;
3294     } else {
3295         goto fail;
3296     }
3297 
3298     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3299         goto fail;
3300     host_port = strtol(buf, &r, 0);
3301     if (r == buf)
3302         goto fail;
3303 
3304     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3305         goto fail;
3306     if (buf[0] == '\0') {
3307         pstrcpy(buf, sizeof(buf), "10.0.2.15");
3308     }
3309     if (!inet_aton(buf, &guest_addr))
3310         goto fail;
3311     
3312     guest_port = strtol(p, &r, 0);
3313     if (r == p)
3314         goto fail;
3315     
3316     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3317         fprintf(stderr, "qemu: could not set up redirection\n");
3318         exit(1);
3319     }
3320     return;
3321  fail:
3322     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3323     exit(1);
3324 }
3325     
3326 #ifndef _WIN32
3327 
3328 char smb_dir[1024];
3329 
3330 static void smb_exit(void)
3331 {
3332     DIR *d;
3333     struct dirent *de;
3334     char filename[1024];
3335 
3336     /* erase all the files in the directory */
3337     d = opendir(smb_dir);
3338     for(;;) {
3339         de = readdir(d);
3340         if (!de)
3341             break;
3342         if (strcmp(de->d_name, ".") != 0 &&
3343             strcmp(de->d_name, "..") != 0) {
3344             snprintf(filename, sizeof(filename), "%s/%s", 
3345                      smb_dir, de->d_name);
3346             unlink(filename);
3347         }
3348     }
3349     closedir(d);
3350     rmdir(smb_dir);
3351 }
3352 
3353 /* automatic user mode samba server configuration */
3354 void net_slirp_smb(const char *exported_dir)
3355 {
3356     char smb_conf[1024];
3357     char smb_cmdline[1024];
3358     FILE *f;
3359 
3360     if (!slirp_inited) {
3361         slirp_inited = 1;
3362         slirp_init();
3363     }
3364 
3365     /* XXX: better tmp dir construction */
3366     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
3367     if (mkdir(smb_dir, 0700) < 0) {
3368         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3369         exit(1);
3370     }
3371     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3372     
3373     f = fopen(smb_conf, "w");
3374     if (!f) {
3375         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3376         exit(1);
3377     }
3378     fprintf(f, 
3379             "[global]\n"
3380             "private dir=%s\n"
3381             "smb ports=0\n"
3382             "socket address=127.0.0.1\n"
3383             "pid directory=%s\n"
3384             "lock directory=%s\n"
3385             "log file=%s/log.smbd\n"
3386             "smb passwd file=%s/smbpasswd\n"
3387             "security = share\n"
3388             "[qemu]\n"
3389             "path=%s\n"
3390             "read only=no\n"
3391             "guest ok=yes\n",
3392             smb_dir,
3393             smb_dir,
3394             smb_dir,
3395             smb_dir,
3396             smb_dir,
3397             exported_dir
3398             );
3399     fclose(f);
3400     atexit(smb_exit);
3401 
3402     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3403              SMBD_COMMAND, smb_conf);
3404     
3405     slirp_add_exec(0, smb_cmdline, 4, 139);
3406 }
3407 
3408 #endif /* !defined(_WIN32) */
3409 
3410 #endif /* CONFIG_SLIRP */
3411 
3412 #if !defined(_WIN32)
3413 
3414 typedef struct TAPState {
3415     VLANClientState *vc;
3416     int fd;
3417 #ifdef __sun__
3418     uint8_t mac_addr[ETHERADDRL];
3419     dlpi_handle_t dh;
3420 #endif /* __sun__ */
3421 } TAPState;
3422 
3423 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3424 {
3425     TAPState *s = opaque;
3426     int ret;
3427 
3428 #if 0
3429     fprintf(logfile, "tap_receive: sending %d @ %p:\n", size, buf);
3430     hex_dump(logfile, buf, size);
3431 #endif
3432     for(;;) {
3433         ret = write(s->fd, buf, size);
3434         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3435         } else {
3436             break;
3437         }
3438     }
3439 }
3440 
3441 static void tap_send(void *opaque)
3442 {
3443     TAPState *s = opaque;
3444     uint8_t buf[4096];
3445     size_t size;
3446 
3447 #ifdef __sun__
3448     size = sizeof (buf);
3449     if (dlpi_recv(s->dh, NULL, NULL, buf, &size, -1, NULL) != DLPI_SUCCESS)
3450         return;
3451 #else /* _!sun__ */
3452     size = read(s->fd, buf, sizeof(buf));
3453 #endif /* __sun__ */
3454     if (size > 0)
3455         qemu_send_packet(s->vc, buf, size);
3456 }
3457 
3458 /* fd support */
3459 
3460 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3461 {
3462     TAPState *s;
3463 
3464     s = qemu_mallocz(sizeof(TAPState));
3465     if (!s)
3466         return NULL;
3467     s->fd = fd;
3468     s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3469     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3470     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3471     return s;
3472 }
3473 
3474 #ifdef _BSD
3475 static int tap_open(char *ifname, int ifname_size)
3476 {
3477     int fd;
3478     char *dev;
3479     struct stat s;
3480 
3481     fd = open("/dev/tap", O_RDWR);
3482     if (fd < 0) {
3483         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3484         return -1;
3485     }
3486 
3487     fstat(fd, &s);
3488     dev = devname(s.st_rdev, S_IFCHR);
3489     pstrcpy(ifname, ifname_size, dev);
3490 
3491     fcntl(fd, F_SETFL, O_NONBLOCK);
3492     return fd;
3493 }
3494 #elif defined(__sun__)
3495 static char *net_tap_get_nic(int nth, boolean_t *setphysaddr,
3496     boolean_t *promiscuous, uint8_t *mac_addr)
3497 {
3498         struct xs_handle *xs = NULL;
3499         char *nic = NULL, *dompath, *bepath, *status = NULL, path[MAXPATHLEN];
3500         unsigned int l;
3501         boolean_t hotplug_connected = 0;
3502         int hotplug_wait = 30; /* seconds */
3503 
3504         xs = xs_daemon_open();
3505         if (xs == NULL) {
3506                 fprintf(logfile, "net_tap_get_nic: cannot open store\n");
3507                 goto fail;
3508         }
3509         
3510         dompath = xs_get_domain_path(xs, domid);
3511         if (dompath == NULL) {
3512                 fprintf(logfile,
3513                     "net_tap_get_nic: cannot get domain path for %d\n",
3514                     domid);
3515                 goto fail;
3516         }
3517 
3518         sprintf(path, "%s/device/vif/%d/backend", dompath, nth);
3519         free(dompath);
3520         dompath = NULL;
3521 
3522         bepath = xs_read(xs, XBT_NULL, path, &l);
3523         if (bepath == NULL) {
3524                 fprintf(logfile,
3525                     "net_tap_get_nic: cannot read backend pathname from %s\n",
3526                     path);
3527                 goto fail;
3528         }
3529 
3530         sprintf(path, "%s/hotplug-status", bepath);
3531         do {
3532                 status = xs_read(xs, XBT_NULL, path, &l);
3533                 if (status != NULL) {
3534                         if (strcmp(status, "connected") == 0) {
3535                                 hotplug_connected = 1;
3536                                 break;
3537                         }
3538                         if (strcmp(status, "error") == 0) {
3539                                 /* It's not going to work. */
3540                                 break;
3541                         }
3542                 }
3543                 free(status);
3544                 status = NULL;
3545 
3546                 sleep(1);
3547 
3548                 hotplug_wait--;
3549         } while (hotplug_wait > 0);
3550 
3551         free(status);
3552 
3553         if (!hotplug_connected) {
3554                 fprintf(logfile,
3555                     "net_tap_get_nic: timeout waiting for hotplug at %s\n",
3556                     path);
3557                 goto fail;
3558         }
3559 
3560         sprintf(path, "%s/nic", bepath);
3561         nic = xs_read(xs, XBT_NULL, path, &l);
3562 
3563         if (nic != NULL) {
3564                 char *v;
3565                 struct ether_addr *eap;
3566 
3567                 sprintf(path, "%s/SUNW-need-set-physaddr", bepath);
3568                 v = xs_read(xs, XBT_NULL, path, &l);
3569                 if (v == NULL) {
3570                         *setphysaddr = 0;
3571                 } else {
3572                         int i = atoi(v);
3573 
3574                         if (i == 0)
3575                                 *setphysaddr = 0;
3576                         else
3577                                 *setphysaddr = 1;
3578                 }
3579                 free(v);
3580 
3581                 sprintf(path, "%s/SUNW-need-promiscuous", bepath);
3582                 v = xs_read(xs, XBT_NULL, path, &l);
3583                 if (v == NULL) {
3584                         *promiscuous = 0;
3585                 } else {
3586                         int i = atoi(v);
3587 
3588                         if (i == 0)
3589                                 *promiscuous = 0;
3590                         else
3591                                 *promiscuous = 1;
3592                 }
3593                 free(v);
3594 
3595                 sprintf(path, "%s/mac", bepath);
3596                 v = xs_read(xs, XBT_NULL, path, &l);
3597                 if ((v == NULL) || ((eap = ether_aton(v)) == NULL)) {
3598                         /*
3599                          * It doesn't really matter what we do here -
3600                          * if the mac address was needed then things
3601                          * won't work without the correct mac address
3602                          * being specified.
3603                          */
3604                         fprintf(logfile,
3605                             "net_tap_get_nic: cannot find mac address at %s",
3606                             path);
3607                         memset(mac_addr, 0xff, ETHERADDRL);
3608                 } else {
3609                         memcpy(mac_addr, eap->ether_addr_octet, ETHERADDRL);
3610                 }
3611                 free(v);
3612         }
3613 
3614         free(bepath);
3615 
3616 fail:
3617         if (xs != NULL)
3618                 xs_daemon_close(xs);
3619 
3620         return (nic);
3621 }
3622 
3623 static int net_tap_init(VLANState *vlan, const char *ifname1,
3624     const char *setup_script, const char *bridge)
3625 {
3626         char *nic;
3627         boolean_t need_setphysaddr, need_promiscuous;
3628         uint8_t mac_addr[ETHERADDRL];
3629         int fd = -1, ret = 0, r;
3630         dlpi_handle_t dh = NULL;
3631         dlpi_info_t info;
3632         TAPState *s = NULL;
3633 
3634         /*
3635          * We rely on the hotplug script having written a 'nic' entry
3636          * into the store.  It's the name of a device that we can open
3637          * and speak DLPI.
3638          *
3639          * XXPV dme: is 'nic' a mac device name or a link device name?
3640          * xnbo requires that it be a mac device name - this code
3641          * would appear to need a link device name.  Obviously they
3642          * are generally the same, but when Clearview vanity naming
3643          * arrives, they could be different...
3644          */
3645         nic = net_tap_get_nic(vlan->id, &need_setphysaddr,
3646             &need_promiscuous, mac_addr);
3647 
3648         fprintf(logfile, "net_tap_init: nic = %s, setphysaddr = %d\n",
3649             nic ? nic : "NULL", need_setphysaddr);
3650         if (nic == NULL) {
3651                 ret = -1;
3652                 goto done;
3653         }
3654 
3655         if ((r = dlpi_open(nic, &dh, DLPI_RAW)) != DLPI_SUCCESS) {
3656                 fprintf(logfile, "net_tap_init: "
3657                     "cannot open dlpi interface (%d)\n", r);
3658                 ret = -1;
3659                 goto done;
3660         }
3661 
3662         if ((r = dlpi_info(dh, &info, 0)) != DLPI_SUCCESS) {
3663                 fprintf(logfile, "net_tap_init: dlpi_info failed (%d)\n", r);
3664                 ret = -1;
3665                 goto done;
3666         }
3667 
3668         if (info.di_mactype != DL_ETHER) {
3669                 fprintf(logfile, "net_tap_init: not DL_ETHER\n");
3670                 ret = -1;
3671                 goto done;
3672         }
3673 
3674         if ((r = dlpi_bind(dh, DLPI_ANY_SAP, NULL)) != DLPI_SUCCESS) {
3675                 fprintf(logfile, "net_tap_init: dlpi_bind failed (%d)\n", r);
3676                 ret = -1;
3677                 goto done;
3678         }
3679 
3680         if (need_setphysaddr) {
3681                 if ((r = dlpi_set_physaddr(dh, DL_CURR_PHYS_ADDR,
3682                          mac_addr, ETHERADDRL)) != DLPI_SUCCESS) {
3683                         fprintf(logfile,
3684                             "net_tap_init: cannot set physaddr (%d)\n",
3685                             r);
3686                         ret = -1;
3687                         goto done;
3688                 }
3689         }
3690 
3691         if ((r = dlpi_promiscon(dh, DL_PROMISC_SAP)) != DLPI_SUCCESS) {
3692                 ret = -1;
3693                 goto done;
3694         }
3695 
3696         /*
3697          * If the NIC needs to be in promiscuous mode for relevant
3698          * traffic to arrive, make it so.
3699          *
3700          * Even if it doesn't need to be fully promiscuous, we don't
3701          * know which multicast addresses the guest domain cares
3702          * about, so we send it packets addressed to all of them.
3703          */
3704         if ((r = dlpi_promiscon(dh,
3705                  (need_promiscuous ? DL_PROMISC_PHYS : DL_PROMISC_MULTI)))
3706             != DLPI_SUCCESS) {
3707                 ret = -1;
3708                 goto done;
3709         }
3710 
3711         if ((fd = dlpi_fd(dh)) < 0) {
3712                 fprintf(logfile, "net_tap_init: cannot get fd (%d)\n", fd);
3713                 ret = -1;
3714                 goto done;
3715         }
3716 
3717         s = net_tap_fd_init(vlan, fd);
3718         if (s == NULL) {
3719                 ret = -1;
3720                 goto done;
3721         }
3722 
3723         memcpy(s->mac_addr, mac_addr, ETHERADDRL);
3724         snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3725             "tap: ifname=%s", nic);
3726         s->dh = dh;
3727 
3728 done:
3729         if (ret < 0)
3730                 dlpi_close(dh);
3731         free(nic);
3732 
3733         return (ret);
3734 }
3735 #else
3736 static int tap_open(char *ifname, int ifname_size)
3737 {
3738     struct ifreq ifr;
3739     int fd, ret, retries = 0;
3740     
3741     fd = open("/dev/net/tun", O_RDWR);
3742     if (fd < 0) {
3743         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3744         return -1;
3745     }
3746     memset(&ifr, 0, sizeof(ifr));
3747     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3748     if (ifname[0] != '\0')
3749         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3750     else
3751         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3752     do {
3753         ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3754     } while ((ret != 0) && (retries++ < 3));
3755     if (ret != 0) {
3756         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3757         close(fd);
3758         return -1;
3759     }
3760     pstrcpy(ifname, ifname_size, ifr.ifr_name);
3761     fcntl(fd, F_SETFL, O_NONBLOCK);
3762     return fd;
3763 }
3764 
3765 static int net_tap_init(VLANState *vlan, const char *ifname1,
3766                         const char *setup_script, const char *bridge)
3767 {
3768     TAPState *s;
3769     int pid, status, fd;
3770     char *args[4];
3771     char **parg;
3772     char ifname[128];
3773 
3774     if (ifname1 != NULL)
3775         pstrcpy(ifname, sizeof(ifname), ifname1);
3776     else
3777         ifname[0] = '\0';
3778     fd = tap_open(ifname, sizeof(ifname));
3779     if (fd < 0)
3780         return -1;
3781 
3782     if (!setup_script || !strcmp(setup_script, "no"))
3783         setup_script = "";
3784     if (setup_script[0] != '\0') {
3785         /* try to launch network init script */
3786         pid = fork();
3787         if (pid >= 0) {
3788             if (pid == 0) {
3789                 int open_max = sysconf(_SC_OPEN_MAX), i;
3790                 for (i = 0; i < open_max; i++)
3791                     if (i != STDIN_FILENO &&
3792                         i != STDOUT_FILENO &&
3793                         i != STDERR_FILENO &&
3794                         i != fd)
3795                         close(i);
3796 
3797                 parg = args;
3798                 *parg++ = (char *)setup_script;
3799                 *parg++ = ifname;
3800                 *parg++ = (char *)bridge;
3801                 *parg++ = NULL;
3802                 execv(setup_script, args);
3803                 _exit(1);
3804             }
3805             while (waitpid(pid, &status, 0) != pid);
3806             if (!WIFEXITED(status) ||
3807                 WEXITSTATUS(status) != 0) {
3808                 fprintf(stderr, "%s: could not launch network script\n",
3809                         setup_script);
3810                 return -1;
3811             }
3812         }
3813     }
3814     s = net_tap_fd_init(vlan, fd);
3815     if (!s)
3816         return -1;
3817     snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3818              "tap: ifname=%s setup_script=%s", ifname, setup_script);
3819     return 0;
3820 }
3821 #endif
3822 #endif /* !_WIN32 */
3823 
3824 /* network connection */
3825 typedef struct NetSocketState {
3826     VLANClientState *vc;
3827     int fd;
3828     int state; /* 0 = getting length, 1 = getting data */
3829     int index;
3830     int packet_len;
3831     uint8_t buf[4096];
3832     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3833 } NetSocketState;
3834 
3835 typedef struct NetSocketListenState {
3836     VLANState *vlan;
3837     int fd;
3838 } NetSocketListenState;
3839 
3840 /* XXX: we consider we can send the whole packet without blocking */
3841 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3842 {
3843     NetSocketState *s = opaque;
3844     uint32_t len;
3845     len = htonl(size);
3846 
3847     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3848     send_all(s->fd, buf, size);
3849 }
3850 
3851 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3852 {
3853     NetSocketState *s = opaque;
3854     sendto(s->fd, buf, size, 0, 
3855            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3856 }
3857 
3858 static void net_socket_send(void *opaque)
3859 {
3860     NetSocketState *s = opaque;
3861     int l, size, err;
3862     uint8_t buf1[4096];
3863     const uint8_t *buf;
3864 
3865     size = recv(s->fd, buf1, sizeof(buf1), 0);
3866     if (size < 0) {
3867         err = socket_error();
3868         if (err != EWOULDBLOCK) 
3869             goto eoc;
3870     } else if (size == 0) {
3871         /* end of connection */
3872     eoc:
3873         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3874         closesocket(s->fd);
3875         return;
3876     }
3877     buf = buf1;
3878     while (size > 0) {
3879         /* reassemble a packet from the network */
3880         switch(s->state) {
3881         case 0:
3882             l = 4 - s->index;
3883             if (l > size)
3884                 l = size;
3885             memcpy(s->buf + s->index, buf, l);
3886             buf += l;
3887             size -= l;
3888             s->index += l;
3889             if (s->index == 4) {
3890                 /* got length */
3891                 s->packet_len = ntohl(*(uint32_t *)s->buf);
3892                 s->index = 0;
3893                 s->state = 1;
3894             }
3895             break;
3896         case 1:
3897             l = s->packet_len - s->index;
3898             if (l > size)
3899                 l = size;
3900             memcpy(s->buf + s->index, buf, l);
3901             s->index += l;
3902             buf += l;
3903             size -= l;
3904             if (s->index >= s->packet_len) {
3905                 qemu_send_packet(s->vc, s->buf, s->packet_len);
3906                 s->index = 0;
3907                 s->state = 0;
3908             }
3909             break;
3910         }
3911     }
3912 }
3913 
3914 static void net_socket_send_dgram(void *opaque)
3915 {
3916     NetSocketState *s = opaque;
3917     int size;
3918 
3919     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3920     if (size < 0) 
3921         return;
3922     if (size == 0) {
3923         /* end of connection */
3924         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3925         return;
3926     }
3927     qemu_send_packet(s->vc, s->buf, size);
3928 }
3929 
3930 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3931 {
3932     struct ip_mreq imr;
3933     int fd;
3934     int val, ret;
3935     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3936         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3937                 inet_ntoa(mcastaddr->sin_addr), 
3938                 (int)ntohl(mcastaddr->sin_addr.s_addr));
3939         return -1;
3940 
3941     }
3942     fd = socket(PF_INET, SOCK_DGRAM, 0);
3943     if (fd < 0) {
3944         perror("socket(PF_INET, SOCK_DGRAM)");
3945         return -1;
3946     }
3947 
3948     val = 1;
3949     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3950                    (const char *)&val, sizeof(val));
3951     if (ret < 0) {
3952         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3953         goto fail;
3954     }
3955 
3956     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3957     if (ret < 0) {
3958         perror("bind");
3959         goto fail;
3960     }
3961     
3962     /* Add host to multicast group */
3963     imr.imr_multiaddr = mcastaddr->sin_addr;
3964     imr.imr_interface.s_addr = htonl(INADDR_ANY);
3965 
3966     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3967                      (const char *)&imr, sizeof(struct ip_mreq));
3968     if (ret < 0) {
3969         perror("setsockopt(IP_ADD_MEMBERSHIP)");
3970         goto fail;
3971     }
3972 
3973     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3974     val = 1;
3975     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3976                    (const char *)&val, sizeof(val));
3977     if (ret < 0) {
3978         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3979         goto fail;
3980     }
3981 
3982     socket_set_nonblock(fd);
3983     return fd;
3984 fail:
3985     if (fd >= 0) 
3986         closesocket(fd);
3987     return -1;
3988 }
3989 
3990 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3991                                           int is_connected)
3992 {
3993     struct sockaddr_in saddr;
3994     int newfd;
3995     socklen_t saddr_len;
3996     NetSocketState *s;
3997 
3998     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3999      * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
4000      * by ONLY ONE process: we must "clone" this dgram socket --jjo
4001      */
4002 
4003     if (is_connected) {
4004         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4005             /* must be bound */
4006             if (saddr.sin_addr.s_addr==0) {
4007                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4008                         fd);
4009                 return NULL;
4010             }
4011             /* clone dgram socket */
4012             newfd = net_socket_mcast_create(&saddr);
4013             if (newfd < 0) {
4014                 /* error already reported by net_socket_mcast_create() */
4015                 close(fd);
4016                 return NULL;
4017             }
4018             /* clone newfd to fd, close newfd */
4019             dup2(newfd, fd);
4020             close(newfd);
4021         
4022         } else {
4023             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4024                     fd, strerror(errno));
4025             return NULL;
4026         }
4027     }
4028 
4029     s = qemu_mallocz(sizeof(NetSocketState));
4030     if (!s)
4031         return NULL;
4032     s->fd = fd;
4033 
4034     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4035     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4036 
4037     /* mcast: save bound address as dst */
4038     if (is_connected) s->dgram_dst=saddr;
4039 
4040     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4041             "socket: fd=%d (%s mcast=%s:%d)", 
4042             fd, is_connected? "cloned" : "",
4043             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4044     return s;
4045 }
4046 
4047 static void net_socket_connect(void *opaque)
4048 {
4049     NetSocketState *s = opaque;
4050     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4051 }
4052 
4053 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
4054                                           int is_connected)
4055 {
4056     NetSocketState *s;
4057     s = qemu_mallocz(sizeof(NetSocketState));
4058     if (!s)
4059         return NULL;
4060     s->fd = fd;
4061     s->vc = qemu_new_vlan_client(vlan, 
4062                                  net_socket_receive, NULL, s);
4063     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4064              "socket: fd=%d", fd);
4065     if (is_connected) {
4066         net_socket_connect(s);
4067     } else {
4068         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4069     }
4070     return s;
4071 }
4072 
4073 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
4074                                           int is_connected)
4075 {
4076     int so_type=-1, optlen=sizeof(so_type);
4077 
4078     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4079         fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
4080         return NULL;
4081     }
4082     switch(so_type) {
4083     case SOCK_DGRAM:
4084         return net_socket_fd_init_dgram(vlan, fd, is_connected);
4085     case SOCK_STREAM:
4086         return net_socket_fd_init_stream(vlan, fd, is_connected);
4087     default:
4088         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4089         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4090         return net_socket_fd_init_stream(vlan, fd, is_connected);
4091     }
4092     return NULL;
4093 }
4094 
4095 static void net_socket_accept(void *opaque)
4096 {
4097     NetSocketListenState *s = opaque;    
4098     NetSocketState *s1;
4099     struct sockaddr_in saddr;
4100     socklen_t len;
4101     int fd;
4102 
4103     for(;;) {
4104         len = sizeof(saddr);
4105         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4106         if (fd < 0 && errno != EINTR) {
4107             return;
4108         } else if (fd >= 0) {
4109             break;
4110         }
4111     }
4112     s1 = net_socket_fd_init(s->vlan, fd, 1); 
4113     if (!s1) {
4114         closesocket(fd);
4115     } else {
4116         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4117                  "socket: connection from %s:%d", 
4118                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4119     }
4120 }
4121 
4122 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4123 {
4124     NetSocketListenState *s;
4125     int fd, val, ret;
4126     struct sockaddr_in saddr;
4127 
4128     if (parse_host_port(&saddr, host_str) < 0)
4129         return -1;
4130     
4131     s = qemu_mallocz(sizeof(NetSocketListenState));
4132     if (!s)
4133         return -1;
4134 
4135     fd = socket(PF_INET, SOCK_STREAM, 0);
4136     if (fd < 0) {
4137         perror("socket");
4138         return -1;
4139     }
4140     socket_set_nonblock(fd);
4141 
4142     /* allow fast reuse */
4143     val = 1;
4144     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4145     
4146     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4147     if (ret < 0) {
4148         perror("bind");
4149         return -1;
4150     }
4151     ret = listen(fd, 0);
4152     if (ret < 0) {
4153         perror("listen");
4154         return -1;
4155     }
4156     s->vlan = vlan;
4157     s->fd = fd;
4158     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4159     return 0;
4160 }
4161 
4162 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4163 {
4164     NetSocketState *s;
4165     int fd, connected, ret, err;
4166     struct sockaddr_in saddr;
4167 
4168     if (parse_host_port(&saddr, host_str) < 0)
4169         return -1;
4170 
4171     fd = socket(PF_INET, SOCK_STREAM, 0);
4172     if (fd < 0) {
4173         perror("socket");
4174         return -1;
4175     }
4176     socket_set_nonblock(fd);
4177 
4178     connected = 0;
4179     for(;;) {
4180         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4181         if (ret < 0) {
4182             err = socket_error();
4183             if (err == EINTR || err == EWOULDBLOCK) {
4184             } else if (err == EINPROGRESS) {
4185                 break;
4186             } else {
4187                 perror("connect");
4188                 closesocket(fd);
4189                 return -1;
4190             }
4191         } else {
4192             connected = 1;
4193             break;
4194         }
4195     }
4196     s = net_socket_fd_init(vlan, fd, connected);
4197     if (!s)
4198         return -1;
4199     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4200              "socket: connect to %s:%d", 
4201              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4202     return 0;
4203 }
4204 
4205 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4206 {
4207     NetSocketState *s;
4208     int fd;
4209     struct sockaddr_in saddr;
4210 
4211     if (parse_host_port(&saddr, host_str) < 0)
4212         return -1;
4213 
4214 
4215     fd = net_socket_mcast_create(&saddr);
4216     if (fd < 0)
4217         return -1;
4218 
4219     s = net_socket_fd_init(vlan, fd, 0);
4220     if (!s)
4221         return -1;
4222 
4223     s->dgram_dst = saddr;
4224     
4225     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4226              "socket: mcast=%s:%d", 
4227              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4228     return 0;
4229 
4230 }
4231 
4232 static int get_param_value(char *buf, int buf_size,
4233                            const char *tag, const char *str)
4234 {
4235     const char *p;
4236     char *q;
4237     char option[128];
4238 
4239     p = str;
4240     for(;;) {
4241         q = option;
4242         while (*p != '\0' && *p != '=') {
4243             if ((q - option) < sizeof(option) - 1)
4244                 *q++ = *p;
4245             p++;
4246         }
4247         *q = '\0';
4248         if (*p != '=')
4249             break;
4250         p++;
4251         if (!strcmp(tag, option)) {
4252             q = buf;
4253             while (*p != '\0' && *p != ',') {
4254                 if ((q - buf) < buf_size - 1)
4255                     *q++ = *p;
4256                 p++;
4257             }
4258             *q = '\0';
4259             return q - buf;
4260         } else {
4261             while (*p != '\0' && *p != ',') {
4262                 p++;
4263             }
4264         }
4265         if (*p != ',')
4266             break;
4267         p++;
4268     }
4269     return 0;
4270 }
4271 
4272 static int net_client_init(const char *str)
4273 {
4274     const char *p;
4275     char *q;
4276     char device[64];
4277     char buf[1024];
4278     int vlan_id, ret;
4279     VLANState *vlan;
4280 
4281     p = str;
4282     q = device;
4283     while (*p != '\0' && *p != ',') {
4284         if ((q - device) < sizeof(device) - 1)
4285             *q++ = *p;
4286         p++;
4287     }
4288     *q = '\0';
4289     if (*p == ',')
4290         p++;
4291     vlan_id = 0;
4292     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4293         vlan_id = strtol(buf, NULL, 0);
4294     }
4295     vlan = qemu_find_vlan(vlan_id);
4296     if (!vlan) {
4297         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4298         return -1;
4299     }
4300     if (!strcmp(device, "nic")) {
4301         NICInfo *nd;
4302         uint8_t *macaddr;
4303 
4304         if (nb_nics >= MAX_NICS) {
4305             fprintf(stderr, "Too Many NICs\n");
4306             return -1;
4307         }
4308         nd = &nd_table[nb_nics];
4309         macaddr = nd->macaddr;
4310         macaddr[0] = 0x52;
4311         macaddr[1] = 0x54;
4312         macaddr[2] = 0x00;
4313         macaddr[3] = 0x12;
4314         macaddr[4] = 0x34;
4315         macaddr[5] = 0x56 + nb_nics;
4316 
4317         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4318             if (parse_macaddr(macaddr, buf) < 0) {
4319                 fprintf(stderr, "invalid syntax for ethernet address\n");
4320                 return -1;
4321             }
4322         }
4323         if (get_param_value(buf, sizeof(buf), "model", p)) {
4324             nd->model = strdup(buf);
4325         }
4326         nd->vlan = vlan;
4327         nb_nics++;
4328         ret = 0;
4329     } else
4330     if (!strcmp(device, "none")) {
4331         /* does nothing. It is needed to signal that no network cards
4332            are wanted */
4333         ret = 0;
4334     } else
4335 #ifdef CONFIG_SLIRP
4336     if (!strcmp(device, "user")) {
4337         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4338             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4339         }
4340         ret = net_slirp_init(vlan);
4341     } else
4342 #endif
4343 #ifdef _WIN32
4344     if (!strcmp(device, "tap")) {
4345         char ifname[64];
4346         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4347             fprintf(stderr, "tap: no interface name\n");
4348             return -1;
4349         }
4350         ret = tap_win32_init(vlan, ifname);
4351     } else
4352 #else
4353     if (!strcmp(device, "tap")) {
4354         char ifname[64];
4355         char setup_script[1024];
4356         char bridge[16];
4357         int fd;
4358         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4359             fd = strtol(buf, NULL, 0);
4360             ret = -1;
4361             if (net_tap_fd_init(vlan, fd))
4362                 ret = 0;
4363         } else {
4364             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4365                 ifname[0] = '\0';
4366             }
4367             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4368                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4369             }
4370             if (get_param_value(bridge, sizeof(bridge), "bridge", p) == 0) {
4371                 pstrcpy(bridge, sizeof(bridge), DEFAULT_BRIDGE);
4372             }
4373             ret = net_tap_init(vlan, ifname, setup_script, bridge);
4374         }
4375     } else
4376 #endif
4377     if (!strcmp(device, "socket")) {
4378         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4379             int fd;
4380             fd = strtol(buf, NULL, 0);
4381             ret = -1;
4382             if (net_socket_fd_init(vlan, fd, 1))
4383                 ret = 0;
4384         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4385             ret = net_socket_listen_init(vlan, buf);
4386         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4387             ret = net_socket_connect_init(vlan, buf);
4388         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4389             ret = net_socket_mcast_init(vlan, buf);
4390         } else {
4391             fprintf(stderr, "Unknown socket options: %s\n", p);
4392             return -1;
4393         }
4394     } else
4395     {
4396         fprintf(stderr, "Unknown network device: %s\n", device);
4397         return -1;
4398     }
4399     if (ret < 0) {
4400         fprintf(stderr, "Could not initialize device '%s'\n", device);
4401     }
4402     
4403     return ret;
4404 }
4405 
4406 void do_info_network(void)
4407 {
4408     VLANState *vlan;
4409     VLANClientState *vc;
4410 
4411     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4412         term_printf("VLAN %d devices:\n", vlan->id);
4413         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4414             term_printf("  %s\n", vc->info_str);
4415     }
4416 }
4417 
4418 /***********************************************************/
4419 /* USB devices */
4420 
4421 static USBPort *used_usb_ports;
4422 static USBPort *free_usb_ports;
4423 
4424 /* ??? Maybe change this to register a hub to keep track of the topology.  */
4425 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4426                             usb_attachfn attach)
4427 {
4428     port->opaque = opaque;
4429     port->index = index;
4430     port->attach = attach;
4431     port->next = free_usb_ports;
4432     free_usb_ports = port;
4433 }
4434 
4435 static int usb_device_add(const char *devname)
4436 {
4437     const char *p;
4438     USBDevice *dev;
4439     USBPort *port;
4440     char usb_name[256] = "USB ";
4441 
4442     if (!free_usb_ports)
4443         return -1;
4444 
4445     if (strstart(devname, "host:", &p)) {
4446         dev = usb_host_device_open(p);
4447     } else if (!strcmp(devname, "mouse")) {
4448         dev = usb_mouse_init();
4449     } else if (!strcmp(devname, "tablet")) {
4450         dev = usb_tablet_init();
4451     } else if (strstart(devname, "disk:", &p)) {
4452         dev = usb_msd_init(p);
4453     } else {
4454         return -1;
4455     }
4456     if (!dev)
4457         return -1;
4458 
4459     /* Find a USB port to add the device to.  */
4460     port = free_usb_ports;
4461     if (!port->next) {
4462         USBDevice *hub;
4463 
4464         /* Create a new hub and chain it on.  */
4465         free_usb_ports = NULL;
4466         port->next = used_usb_ports;
4467         used_usb_ports = port;
4468 
4469         hub = usb_hub_init(VM_USB_HUB_SIZE);
4470         usb_attach(port, hub);
4471         port = free_usb_ports;
4472     }
4473 
4474     free_usb_ports = port->next;
4475     port->next = used_usb_ports;
4476     used_usb_ports = port;
4477 
4478     pstrcpy(usb_name + strlen(usb_name), 
4479             sizeof(usb_name) - strlen(usb_name), 
4480             devname);
4481     register_savevm(usb_name, 0, 1, generic_usb_save, generic_usb_load, dev);
4482     
4483     usb_attach(port, dev);
4484     return 0;
4485 }
4486 
4487 static int usb_device_del(const char *devname)
4488 {
4489     USBPort *port;
4490     USBPort **lastp;
4491     USBDevice *dev;
4492     int bus_num, addr;
4493     const char *p;
4494 
4495     if (!used_usb_ports)
4496         return -1;
4497 
4498     p = strchr(devname, '.');
4499     if (!p) 
4500         return -1;
4501     bus_num = strtoul(devname, NULL, 0);
4502     addr = strtoul(p + 1, NULL, 0);
4503     if (bus_num != 0)
4504         return -1;
4505 
4506     lastp = &used_usb_ports;
4507     port = used_usb_ports;
4508     while (port && port->dev->addr != addr) {
4509         lastp = &port->next;
4510         port = port->next;
4511     }
4512 
4513     if (!port)
4514         return -1;
4515 
4516     dev = port->dev;
4517     *lastp = port->next;
4518     usb_attach(port, NULL);
4519     dev->handle_destroy(dev);
4520     port->next = free_usb_ports;
4521     free_usb_ports = port;
4522     return 0;
4523 }
4524 
4525 void do_usb_add(const char *devname)
4526 {
4527     int ret;
4528     ret = usb_device_add(devname);
4529     if (ret < 0) 
4530         term_printf("Could not add USB device '%s'\n", devname);
4531 }
4532 
4533 void do_usb_del(const char *devname)
4534 {
4535     int ret;
4536     ret = usb_device_del(devname);
4537     if (ret < 0) 
4538         term_printf("Could not remove USB device '%s'\n", devname);
4539 }
4540 
4541 void usb_info(void)
4542 {
4543     USBDevice *dev;
4544     USBPort *port;
4545     const char *speed_str;
4546 
4547     if (!usb_enabled) {
4548         term_printf("USB support not enabled\n");
4549         return;
4550     }
4551 
4552     for (port = used_usb_ports; port; port = port->next) {
4553         dev = port->dev;
4554         if (!dev)
4555             continue;
4556         switch(dev->speed) {
4557         case USB_SPEED_LOW: 
4558             speed_str = "1.5"; 
4559             break;
4560         case USB_SPEED_FULL: 
4561             speed_str = "12"; 
4562             break;
4563         case USB_SPEED_HIGH: 
4564             speed_str = "480"; 
4565             break;
4566         default:
4567             speed_str = "?"; 
4568             break;
4569         }
4570         term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4571                     0, dev->addr, speed_str, dev->devname);
4572     }
4573 }
4574 
4575 /***********************************************************/
4576 /* pid file */
4577 
4578 static char *pid_filename;
4579 
4580 /* Remove PID file. Called on normal exit */
4581 
4582 static void remove_pidfile(void) 
4583 {
4584     unlink (pid_filename);
4585 }
4586 
4587 static void create_pidfile(const char *filename)
4588 {
4589     struct stat pidstat;
4590     FILE *f;
4591 
4592     /* Try to write our PID to the named file */
4593     if (stat(filename, &pidstat) < 0) {
4594         if (errno == ENOENT) {
4595             if ((f = fopen (filename, "w")) == NULL) {
4596                 perror("Opening pidfile");
4597                 exit(1);
4598             }
4599             fprintf(f, "%ld\n", (long)getpid());
4600             fclose(f);
4601             pid_filename = qemu_strdup(filename);
4602             if (!pid_filename) {
4603                 fprintf(stderr, "Could not save PID filename");
4604                 exit(1);
4605             }
4606             atexit(remove_pidfile);
4607         }
4608     } else {
4609         fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4610                 filename);
4611         exit(1);
4612     }
4613 }
4614 
4615 /***********************************************************/
4616 /* dumb display */
4617 
4618 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4619 {
4620 }
4621 
4622 static void dumb_resize(DisplayState *ds, int w, int h)
4623 {
4624 }
4625 
4626 static void dumb_refresh(DisplayState *ds)
4627 {
4628     vga_hw_update();
4629 }
4630 
4631 void dumb_display_init(DisplayState *ds)
4632 {
4633     ds->data = NULL;
4634     ds->linesize = 0;
4635     ds->depth = 0;
4636     ds->dpy_update = dumb_update;
4637     ds->dpy_resize = dumb_resize;
4638     ds->dpy_refresh = dumb_refresh;
4639 }
4640 
4641 /***********************************************************/
4642 /* I/O handling */
4643 
4644 #define MAX_IO_HANDLERS 64
4645 
4646 typedef struct IOHandlerRecord {
4647     int fd;
4648     IOCanRWHandler *fd_read_poll;
4649     IOHandler *fd_read;
4650     IOHandler *fd_write;
4651     int deleted;
4652     void *opaque;
4653     /* temporary data */
4654     struct pollfd *ufd;
4655     struct IOHandlerRecord *next;
4656 } IOHandlerRecord;
4657 
4658 static IOHandlerRecord *first_io_handler;
4659 
4660 /* XXX: fd_read_poll should be suppressed, but an API change is
4661    necessary in the character devices to suppress fd_can_read(). */
4662 int qemu_set_fd_handler2(int fd, 
4663                          IOCanRWHandler *fd_read_poll, 
4664                          IOHandler *fd_read, 
4665                          IOHandler *fd_write, 
4666                          void *opaque)
4667 {
4668     IOHandlerRecord **pioh, *ioh;
4669 
4670     if (!fd_read && !fd_write) {
4671         pioh = &first_io_handler;
4672         for(;;) {
4673             ioh = *pioh;
4674             if (ioh == NULL)
4675                 break;
4676             if (ioh->fd == fd) {
4677                 ioh->deleted = 1;
4678                 break;
4679             }
4680             pioh = &ioh->next;
4681         }
4682     } else {
4683         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4684             if (ioh->fd == fd)
4685                 goto found;
4686         }
4687         ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4688         if (!ioh)
4689             return -1;
4690         ioh->next = first_io_handler;
4691         first_io_handler = ioh;
4692     found:
4693         ioh->fd = fd;
4694         ioh->fd_read_poll = fd_read_poll;
4695         ioh->fd_read = fd_read;
4696         ioh->fd_write = fd_write;
4697         ioh->opaque = opaque;
4698         ioh->deleted = 0;
4699     }
4700     return 0;
4701 }
4702 
4703 int qemu_set_fd_handler(int fd, 
4704                         IOHandler *fd_read, 
4705                         IOHandler *fd_write, 
4706                         void *opaque)
4707 {
4708     return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4709 }
4710 
4711 /***********************************************************/
4712 /* Polling handling */
4713 
4714 typedef struct PollingEntry {
4715     PollingFunc *func;
4716     void *opaque;
4717     struct PollingEntry *next;
4718 } PollingEntry;
4719 
4720 static PollingEntry *first_polling_entry;
4721 
4722 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4723 {
4724     PollingEntry **ppe, *pe;
4725     pe = qemu_mallocz(sizeof(PollingEntry));
4726     if (!pe)
4727         return -1;
4728     pe->func = func;
4729     pe->opaque = opaque;
4730     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4731     *ppe = pe;
4732     return 0;
4733 }
4734 
4735 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4736 {
4737     PollingEntry **ppe, *pe;
4738     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4739         pe = *ppe;
4740         if (pe->func == func && pe->opaque == opaque) {
4741             *ppe = pe->next;
4742             qemu_free(pe);
4743             break;
4744         }
4745     }
4746 }
4747 
4748 #ifdef _WIN32
4749 /***********************************************************/
4750 /* Wait objects support */
4751 typedef struct WaitObjects {
4752     int num;
4753     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4754     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4755     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4756 } WaitObjects;
4757 
4758 static WaitObjects wait_objects = {0};
4759     
4760 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4761 {
4762     WaitObjects *w = &wait_objects;
4763 
4764     if (w->num >= MAXIMUM_WAIT_OBJECTS)
4765         return -1;
4766     w->events[w->num] = handle;
4767     w->func[w->num] = func;
4768     w->opaque[w->num] = opaque;
4769     w->num++;
4770     return 0;
4771 }
4772 
4773 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4774 {
4775     int i, found;
4776     WaitObjects *w = &wait_objects;
4777 
4778     found = 0;
4779     for (i = 0; i < w->num; i++) {
4780         if (w->events[i] == handle)
4781             found = 1;
4782         if (found) {
4783             w->events[i] = w->events[i + 1];
4784             w->func[i] = w->func[i + 1];
4785             w->opaque[i] = w->opaque[i + 1];
4786         }            
4787     }
4788     if (found)
4789         w->num--;
4790 }
4791 #endif
4792 
4793 /***********************************************************/
4794 /* savevm/loadvm support */
4795 
4796 #define IO_BUF_SIZE 32768
4797 
4798 struct QEMUFile {
4799     FILE *outfile;
4800     BlockDriverState *bs;
4801     int is_file;
4802     int is_writable;
4803     int64_t base_offset;
4804     int64_t buf_offset; /* start of buffer when writing, end of buffer
4805                            when reading */
4806     int buf_index;
4807     int buf_size; /* 0 when writing */
4808     uint8_t buf[IO_BUF_SIZE];
4809 };
4810 
4811 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4812 {
4813     QEMUFile *f;
4814 
4815     f = qemu_mallocz(sizeof(QEMUFile));
4816     if (!f)
4817         return NULL;
4818     if (!strcmp(mode, "wb")) {
4819         f->is_writable = 1;
4820     } else if (!strcmp(mode, "rb")) {
4821         f->is_writable = 0;
4822     } else {
4823         goto fail;
4824     }
4825     f->outfile = fopen(filename, mode);
4826     if (!f->outfile)
4827         goto fail;
4828     f->is_file = 1;
4829     return f;
4830  fail:
4831     if (f->outfile)
4832         fclose(f->outfile);
4833     qemu_free(f);
4834     return NULL;
4835 }
4836 
4837 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4838 {
4839     QEMUFile *f;
4840 
4841     f = qemu_mallocz(sizeof(QEMUFile));
4842     if (!f)
4843         return NULL;
4844     f->is_file = 0;
4845     f->bs = bs;
4846     f->is_writable = is_writable;
4847     f->base_offset = offset;
4848     return f;
4849 }
4850 
4851 void qemu_fflush(QEMUFile *f)
4852 {
4853     if (!f->is_writable)
4854         return;
4855     if (f->buf_index > 0) {
4856         if (f->is_file) {
4857             fseek(f->outfile, f->buf_offset, SEEK_SET);
4858             fwrite(f->buf, 1, f->buf_index, f->outfile);
4859         } else {
4860             bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4861                         f->buf, f->buf_index);
4862         }
4863         f->buf_offset += f->buf_index;
4864         f->buf_index = 0;
4865     }
4866 }
4867 
4868 static void qemu_fill_buffer(QEMUFile *f)
4869 {
4870     int len;
4871 
4872     if (f->is_writable)
4873         return;
4874     if (f->is_file) {
4875         fseek(f->outfile, f->buf_offset, SEEK_SET);
4876         len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4877         if (len < 0)
4878             len = 0;
4879     } else {
4880         len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4881                          f->buf, IO_BUF_SIZE);
4882         if (len < 0)
4883             len = 0;
4884     }
4885     f->buf_index = 0;
4886     f->buf_size = len;
4887     f->buf_offset += len;
4888 }
4889 
4890 void qemu_fclose(QEMUFile *f)
4891 {
4892     if (f->is_writable)
4893         qemu_fflush(f);
4894     if (f->is_file) {
4895         fclose(f->outfile);
4896     }
4897     qemu_free(f);
4898 }
4899 
4900 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4901 {
4902     int l;
4903     while (size > 0) {
4904         l = IO_BUF_SIZE - f->buf_index;
4905         if (l > size)
4906             l = size;
4907         memcpy(f->buf + f->buf_index, buf, l);
4908         f->buf_index += l;
4909         buf += l;
4910         size -= l;
4911         if (f->buf_index >= IO_BUF_SIZE)
4912             qemu_fflush(f);
4913     }
4914 }
4915 
4916 void qemu_put_byte(QEMUFile *f, int v)
4917 {
4918     f->buf[f->buf_index++] = v;
4919     if (f->buf_index >= IO_BUF_SIZE)
4920         qemu_fflush(f);
4921 }
4922 
4923 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4924 {
4925     int size, l;
4926 
4927     size = size1;
4928     while (size > 0) {
4929         l = f->buf_size - f->buf_index;
4930         if (l == 0) {
4931             qemu_fill_buffer(f);
4932             l = f->buf_size - f->buf_index;
4933             if (l == 0)
4934                 break;
4935         }
4936         if (l > size)
4937             l = size;
4938         memcpy(buf, f->buf + f->buf_index, l);
4939         f->buf_index += l;
4940         buf += l;
4941         size -= l;
4942     }
4943     return size1 - size;
4944 }
4945 
4946 int qemu_get_byte(QEMUFile *f)
4947 {
4948     if (f->buf_index >= f->buf_size) {
4949         qemu_fill_buffer(f);
4950         if (f->buf_index >= f->buf_size)
4951             return 0;
4952     }
4953     return f->buf[f->buf_index++];
4954 }
4955 
4956 int64_t qemu_ftell(QEMUFile *f)
4957 {
4958     return f->buf_offset - f->buf_size + f->buf_index;
4959 }
4960 
4961 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4962 {
4963     if (whence == SEEK_SET) {
4964         /* nothing to do */
4965     } else if (whence == SEEK_CUR) {
4966         pos += qemu_ftell(f);
4967     } else {
4968         /* SEEK_END not supported */
4969         return -1;
4970     }
4971     if (f->is_writable) {
4972         qemu_fflush(f);
4973         f->buf_offset = pos;
4974     } else {
4975         f->buf_offset = pos;
4976         f->buf_index = 0;
4977         f->buf_size = 0;
4978     }
4979     return pos;
4980 }
4981 
4982 void qemu_put_be16(QEMUFile *f, unsigned int v)
4983 {
4984     qemu_put_byte(f, v >> 8);
4985     qemu_put_byte(f, v);
4986 }
4987 
4988 void qemu_put_be32(QEMUFile *f, unsigned int v)
4989 {
4990     qemu_put_byte(f, v >> 24);
4991     qemu_put_byte(f, v >> 16);
4992     qemu_put_byte(f, v >> 8);
4993     qemu_put_byte(f, v);
4994 }
4995 
4996 void qemu_put_be64(QEMUFile *f, uint64_t v)
4997 {
4998     qemu_put_be32(f, v >> 32);
4999     qemu_put_be32(f, v);
5000 }
5001 
5002 unsigned int qemu_get_be16(QEMUFile *f)
5003 {
5004     unsigned int v;
5005     v = qemu_get_byte(f) << 8;
5006     v |= qemu_get_byte(f);
5007     return v;
5008 }
5009 
5010 unsigned int qemu_get_be32(QEMUFile *f)
5011 {
5012     unsigned int v;
5013     v = qemu_get_byte(f) << 24;
5014     v |= qemu_get_byte(f) << 16;
5015     v |= qemu_get_byte(f) << 8;
5016     v |= qemu_get_byte(f);
5017     return v;
5018 }
5019 
5020 uint64_t qemu_get_be64(QEMUFile *f)
5021 {
5022     uint64_t v;
5023     v = (uint64_t)qemu_get_be32(f) << 32;
5024     v |= qemu_get_be32(f);
5025     return v;
5026 }
5027 
5028 typedef struct SaveStateEntry {
5029     char idstr[256];
5030     int instance_id;
5031     int version_id;
5032     SaveStateHandler *save_state;
5033     LoadStateHandler *load_state;
5034     void *opaque;
5035     struct SaveStateEntry *next;
5036 } SaveStateEntry;
5037 
5038 static SaveStateEntry *first_se;
5039 
5040 int register_savevm(const char *idstr, 
5041                     int instance_id, 
5042                     int version_id,
5043                     SaveStateHandler *save_state,
5044                     LoadStateHandler *load_state,
5045                     void *opaque)
5046 {
5047     SaveStateEntry *se, **pse;
5048 
5049     se = qemu_malloc(sizeof(SaveStateEntry));
5050     if (!se)
5051         return -1;
5052     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5053     se->instance_id = instance_id;
5054     se->version_id = version_id;
5055     se->save_state = save_state;
5056     se->load_state = load_state;
5057     se->opaque = opaque;
5058     se->next = NULL;
5059 
5060     /* add at the end of list */
5061     pse = &first_se;
5062     while (*pse != NULL)
5063         pse = &(*pse)->next;
5064     *pse = se;
5065     return 0;
5066 }
5067 
5068 #define QEMU_VM_FILE_MAGIC   0x5145564d
5069 #define QEMU_VM_FILE_VERSION 0x00000002
5070 
5071 int qemu_savevm_state(QEMUFile *f)
5072 {
5073     SaveStateEntry *se;
5074     int len, ret;
5075     int64_t cur_pos, len_pos, total_len_pos;
5076 
5077     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5078     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5079     total_len_pos = qemu_ftell(f);
5080     qemu_put_be64(f, 0); /* total size */
5081 
5082     for(se = first_se; se != NULL; se = se->next) {
5083         /* ID string */
5084         len = strlen(se->idstr);
5085         qemu_put_byte(f, len);
5086         qemu_put_buffer(f, se->idstr, len);
5087 
5088         qemu_put_be32(f, se->instance_id);
5089         qemu_put_be32(f, se->version_id);
5090 
5091         /* record size: filled later */
5092         len_pos = qemu_ftell(f);
5093         qemu_put_be32(f, 0);
5094         
5095         se->save_state(f, se->opaque);
5096 
5097         /* fill record size */
5098         cur_pos = qemu_ftell(f);
5099         len = cur_pos - len_pos - 4;
5100         qemu_fseek(f, len_pos, SEEK_SET);
5101         qemu_put_be32(f, len);
5102         qemu_fseek(f, cur_pos, SEEK_SET);
5103     }
5104     cur_pos = qemu_ftell(f);
5105     qemu_fseek(f, total_len_pos, SEEK_SET);
5106     qemu_put_be64(f, cur_pos - total_len_pos - 8);
5107     qemu_fseek(f, cur_pos, SEEK_SET);
5108 
5109     ret = 0;
5110     return ret;
5111 }
5112 
5113 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5114 {
5115     SaveStateEntry *se;
5116 
5117     for(se = first_se; se != NULL; se = se->next) {
5118         if (!strcmp(se->idstr, idstr) && 
5119             instance_id == se->instance_id)
5120             return se;
5121     }
5122     return NULL;
5123 }
5124 
5125 int qemu_loadvm_state(QEMUFile *f)
5126 {
5127     SaveStateEntry *se;
5128     int len, ret, instance_id, record_len, version_id;
5129     int64_t total_len, end_pos, cur_pos;
5130     unsigned int v;
5131     char idstr[256];
5132     
5133     v = qemu_get_be32(f);
5134     if (v != QEMU_VM_FILE_MAGIC)
5135         goto fail;
5136     v = qemu_get_be32(f);
5137     if (v != QEMU_VM_FILE_VERSION) {
5138     fail:
5139         ret = -1;
5140         goto the_end;
5141     }
5142     total_len = qemu_get_be64(f);
5143     end_pos = total_len + qemu_ftell(f);
5144     for(;;) {
5145         if (qemu_ftell(f) >= end_pos)
5146             break;
5147         len = qemu_get_byte(f);
5148         qemu_get_buffer(f, idstr, len);
5149         idstr[len] = '\0';
5150         instance_id = qemu_get_be32(f);
5151         version_id = qemu_get_be32(f);
5152         record_len = qemu_get_be32(f);
5153 #if 0
5154         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
5155                idstr, instance_id, version_id, record_len);
5156 #endif
5157         cur_pos = qemu_ftell(f);
5158         se = find_se(idstr, instance_id);
5159         if (!se) {
5160             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
5161                     instance_id, idstr);
5162         } else {
5163             ret = se->load_state(f, se->opaque, version_id);
5164             if (ret < 0) {
5165                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
5166                         instance_id, idstr);
5167             }
5168         }
5169         /* always seek to exact end of record */
5170         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5171     }
5172     ret = 0;
5173  the_end:
5174     return ret;
5175 }
5176 
5177 /* device can contain snapshots */
5178 static int bdrv_can_snapshot(BlockDriverState *bs)
5179 {
5180     return (bs &&
5181             !bdrv_is_removable(bs) &&
5182             !bdrv_is_read_only(bs));
5183 }
5184 
5185 /* device must be snapshots in order to have a reliable snapshot */
5186 static int bdrv_has_snapshot(BlockDriverState *bs)
5187 {
5188     return (bs &&
5189             !bdrv_is_removable(bs) &&
5190             !bdrv_is_read_only(bs));
5191 }
5192 
5193 static BlockDriverState *get_bs_snapshots(void)
5194 {
5195     BlockDriverState *bs;
5196     int i;
5197 
5198     if (bs_snapshots)
5199         return bs_snapshots;
5200     for(i = 0; i <= MAX_DISKS; i++) {
5201         bs = bs_table[i];
5202         if (bdrv_can_snapshot(bs))
5203             goto ok;
5204     }
5205     return NULL;
5206  ok:
5207     bs_snapshots = bs;
5208     return bs;
5209 }
5210 
5211 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5212                               const char *name)
5213 {
5214     QEMUSnapshotInfo *sn_tab, *sn;
5215     int nb_sns, i, ret;
5216     
5217     ret = -ENOENT;
5218     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5219     if (nb_sns < 0)
5220         return ret;
5221     for(i = 0; i < nb_sns; i++) {
5222         sn = &sn_tab[i];
5223         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5224             *sn_info = *sn;
5225             ret = 0;
5226             break;
5227         }
5228     }
5229     qemu_free(sn_tab);
5230     return ret;
5231 }
5232 
5233 #ifdef CONFIG_DM
5234 /* We use simpler state save/load functions for Xen */
5235 void do_savevm(const char *name)
5236 {
5237     QEMUFile *f;
5238     int saved_vm_running, ret;
5239 
5240     f = qemu_fopen(name, "wb");
5241     
5242     /* ??? Should this occur after vm_stop?  */
5243     qemu_aio_flush();
5244 
5245     saved_vm_running = vm_running;
5246     vm_stop(0);
5247 
5248     if (!f) {
5249         fprintf(logfile, "Failed to open savevm file '%s'\n", name);
5250         goto the_end;
5251     }
5252     
5253     ret = qemu_savevm_state(f);
5254     qemu_fclose(f);
5255 
5256     if (ret < 0)
5257         fprintf(logfile, "Error %d while writing VM to savevm file '%s'\n",
5258                 ret, name);
5259 
5260  the_end:
5261     if (saved_vm_running)
5262         vm_start();
5263 
5264     return;
5265 }
5266 void do_loadvm(const char *name)
5267 {
5268     QEMUFile *f;
5269     int saved_vm_running, ret;
5270 
5271     /* Flush all IO requests so they don't interfere with the new state.  */
5272     qemu_aio_flush();
5273 
5274     saved_vm_running = vm_running;
5275     vm_stop(0);
5276 
5277     /* restore the VM state */
5278     f = qemu_fopen(name, "rb");
5279     if (!f) {
5280         fprintf(logfile, "Could not open VM state file\n");
5281         goto the_end;
5282     }
5283 
5284     ret = qemu_loadvm_state(f);
5285     qemu_fclose(f);
5286     if (ret < 0) {
5287         fprintf(logfile, "Error %d while loading savevm file '%s'\n",
5288                 ret, name);
5289         goto the_end; 
5290     }
5291 
5292 #if 0 
5293     /* del tmp file */
5294     if (unlink(name) == -1)
5295         fprintf(stderr, "delete tmp qemu state file failed.\n");
5296 #endif
5297 
5298 
5299  the_end:
5300     if (saved_vm_running)
5301         vm_start();
5302 }
5303 #else 
5304 void do_savevm(const char *name)
5305 {
5306     BlockDriverState *bs, *bs1;
5307     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5308     int must_delete, ret, i;
5309     BlockDriverInfo bdi1, *bdi = &bdi1;
5310     QEMUFile *f;
5311     int saved_vm_running;
5312 #ifdef _WIN32
5313     struct _timeb tb;
5314 #else
5315     struct timeval tv;
5316 #endif
5317 
5318     bs = get_bs_snapshots();
5319     if (!bs) {
5320         term_printf("No block device can accept snapshots\n");
5321         return;
5322     }
5323 
5324     /* ??? Should this occur after vm_stop?  */
5325     qemu_aio_flush();
5326 
5327     saved_vm_running = vm_running;
5328     vm_stop(0);
5329     
5330     must_delete = 0;
5331     if (name) {
5332         ret = bdrv_snapshot_find(bs, old_sn, name);
5333         if (ret >= 0) {
5334             must_delete = 1;
5335         }
5336     }
5337     memset(sn, 0, sizeof(*sn));
5338     if (must_delete) {
5339         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5340         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5341     } else {
5342         if (name)
5343             pstrcpy(sn->name, sizeof(sn->name), name);
5344     }
5345 
5346     /* fill auxiliary fields */
5347 #ifdef _WIN32
5348     _ftime(&tb);
5349     sn->date_sec = tb.time;
5350     sn->date_nsec = tb.millitm * 1000000;
5351 #else
5352     gettimeofday(&tv, NULL);
5353     sn->date_sec = tv.tv_sec;
5354     sn->date_nsec = tv.tv_usec * 1000;
5355 #endif
5356     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5357     
5358     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5359         term_printf("Device %s does not support VM state snapshots\n",
5360                     bdrv_get_device_name(bs));
5361         goto the_end;
5362     }
5363     
5364     /* save the VM state */
5365     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5366     if (!f) {
5367         term_printf("Could not open VM state file\n");
5368         goto the_end;
5369     }
5370     ret = qemu_savevm_state(f);
5371     sn->vm_state_size = qemu_ftell(f);
5372     qemu_fclose(f);
5373     if (ret < 0) {
5374         term_printf("Error %d while writing VM\n", ret);
5375         goto the_end;
5376     }
5377     
5378     /* create the snapshots */
5379 
5380     for(i = 0; i < MAX_DISKS; i++) {
5381         bs1 = bs_table[i];
5382         if (bdrv_has_snapshot(bs1)) {
5383             if (must_delete) {
5384                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5385                 if (ret < 0) {
5386                     term_printf("Error while deleting snapshot on '%s'\n",
5387                                 bdrv_get_device_name(bs1));
5388                 }
5389             }
5390             ret = bdrv_snapshot_create(bs1, sn);
5391             if (ret < 0) {
5392                 term_printf("Error while creating snapshot on '%s'\n",
5393                             bdrv_get_device_name(bs1));
5394             }
5395         }
5396     }
5397 
5398  the_end:
5399     if (saved_vm_running)
5400         vm_start();
5401 }
5402 
5403 void do_loadvm(const char *name)
5404 {
5405     BlockDriverState *bs, *bs1;
5406     BlockDriverInfo bdi1, *bdi = &bdi1;
5407     QEMUFile *f;
5408     int i, ret;
5409     int saved_vm_running;
5410 
5411     bs = get_bs_snapshots();
5412     if (!bs) {
5413         term_printf("No block device supports snapshots\n");
5414         return;
5415     }
5416     
5417     /* Flush all IO requests so they don't interfere with the new state.  */
5418     qemu_aio_flush();
5419 
5420     saved_vm_running = vm_running;
5421     vm_stop(0);
5422 
5423     for(i = 0; i <= MAX_DISKS; i++) {
5424         bs1 = bs_table[i];
5425         if (bdrv_has_snapshot(bs1)) {
5426             ret = bdrv_snapshot_goto(bs1, name);
5427             if (ret < 0) {
5428                 if (bs != bs1)
5429                     term_printf("Warning: ");
5430                 switch(ret) {
5431                 case -ENOTSUP:
5432                     term_printf("Snapshots not supported on device '%s'\n",
5433                                 bdrv_get_device_name(bs1));
5434                     break;
5435                 case -ENOENT:
5436                     term_printf("Could not find snapshot '%s' on device '%s'\n",
5437                                 name, bdrv_get_device_name(bs1));
5438                     break;
5439                 default:
5440                     term_printf("Error %d while activating snapshot on '%s'\n",
5441                                 ret, bdrv_get_device_name(bs1));
5442                     break;
5443                 }
5444                 /* fatal on snapshot block device */
5445                 if (bs == bs1)
5446                     goto the_end;
5447             }
5448         }
5449     }
5450 
5451     if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5452         term_printf("Device %s does not support VM state snapshots\n",
5453                     bdrv_get_device_name(bs));
5454         return;
5455     }
5456     
5457     /* restore the VM state */
5458     f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5459     if (!f) {
5460         term_printf("Could not open VM state file\n");
5461         goto the_end;
5462     }
5463     ret = qemu_loadvm_state(f);
5464     qemu_fclose(f);
5465     if (ret < 0) {
5466         term_printf("Error %d while loading VM state\n", ret);
5467     }
5468 
5469     /* del tmp file */
5470     if (unlink(name) == -1)
5471         fprintf(stderr, "delete tmp qemu state file failed.\n");
5472 
5473  the_end:
5474     if (saved_vm_running)
5475         vm_start();
5476 }
5477 #endif
5478 
5479 void do_delvm(const char *name)
5480 {
5481     BlockDriverState *bs, *bs1;
5482     int i, ret;
5483 
5484     bs = get_bs_snapshots();
5485     if (!bs) {
5486         term_printf("No block device supports snapshots\n");
5487         return;
5488     }
5489     
5490     for(i = 0; i <= MAX_DISKS; i++) {
5491         bs1 = bs_table[i];
5492         if (bdrv_has_snapshot(bs1)) {
5493             ret = bdrv_snapshot_delete(bs1, name);
5494             if (ret < 0) {
5495                 if (ret == -ENOTSUP)
5496                     term_printf("Snapshots not supported on device '%s'\n",
5497                                 bdrv_get_device_name(bs1));
5498                 else
5499                     term_printf("Error %d while deleting snapshot on '%s'\n",
5500                                 ret, bdrv_get_device_name(bs1));
5501             }
5502         }
5503     }
5504 }
5505 
5506 void do_info_snapshots(void)
5507 {
5508     BlockDriverState *bs, *bs1;
5509     QEMUSnapshotInfo *sn_tab, *sn;
5510     int nb_sns, i;
5511     char buf[256];
5512 
5513     bs = get_bs_snapshots();
5514     if (!bs) {
5515         term_printf("No available block device supports snapshots\n");
5516         return;
5517     }
5518     term_printf("Snapshot devices:");
5519     for(i = 0; i <= MAX_DISKS; i++) {
5520         bs1 = bs_table[i];
5521         if (bdrv_has_snapshot(bs1)) {
5522             if (bs == bs1)
5523                 term_printf(" %s", bdrv_get_device_name(bs1));
5524         }
5525     }
5526     term_printf("\n");
5527 
5528     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5529     if (nb_sns < 0) {
5530         term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5531         return;
5532     }
5533     term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5534     term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5535     for(i = 0; i < nb_sns; i++) {
5536         sn = &sn_tab[i];
5537         term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5538     }
5539     qemu_free(sn_tab);
5540 }
5541 
5542 #ifndef CONFIG_DM
5543 /***********************************************************/
5544 /* cpu save/restore */
5545 
5546 #if defined(TARGET_I386)
5547 
5548 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5549 {
5550     qemu_put_be32(f, dt->selector);
5551     qemu_put_betl(f, dt->base);
5552     qemu_put_be32(f, dt->limit);
5553     qemu_put_be32(f, dt->flags);
5554 }
5555 
5556 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5557 {
5558     dt->selector = qemu_get_be32(f);
5559     dt->base = qemu_get_betl(f);
5560     dt->limit = qemu_get_be32(f);
5561     dt->flags = qemu_get_be32(f);
5562 }
5563 
5564 void cpu_save(QEMUFile *f, void *opaque)
5565 {
5566     CPUState *env = opaque;
5567     uint16_t fptag, fpus, fpuc, fpregs_format;
5568     uint32_t hflags;
5569     int i;
5570     
5571     for(i = 0; i < CPU_NB_REGS; i++)
5572         qemu_put_betls(f, &env->regs[i]);
5573     qemu_put_betls(f, &env->eip);
5574     qemu_put_betls(f, &env->eflags);
5575     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5576     qemu_put_be32s(f, &hflags);
5577     
5578     /* FPU */
5579     fpuc = env->fpuc;
5580     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5581     fptag = 0;
5582     for(i = 0; i < 8; i++) {
5583         fptag |= ((!env->fptags[i]) << i);
5584     }
5585     
5586     qemu_put_be16s(f, &fpuc);
5587     qemu_put_be16s(f, &fpus);
5588     qemu_put_be16s(f, &fptag);
5589 
5590 #ifdef USE_X86LDOUBLE
5591     fpregs_format = 0;
5592 #else
5593     fpregs_format = 1;
5594 #endif
5595     qemu_put_be16s(f, &fpregs_format);
5596     
5597     for(i = 0; i < 8; i++) {
5598 #ifdef USE_X86LDOUBLE
5599         {
5600             uint64_t mant;
5601             uint16_t exp;
5602             /* we save the real CPU data (in case of MMX usage only 'mant'
5603                contains the MMX register */
5604             cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5605             qemu_put_be64(f, mant);
5606             qemu_put_be16(f, exp);
5607         }
5608 #else
5609         /* if we use doubles for float emulation, we save the doubles to
5610            avoid losing information in case of MMX usage. It can give
5611            problems if the image is restored on a CPU where long
5612            doubles are used instead. */
5613         qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5614 #endif
5615     }
5616 
5617     for(i = 0; i < 6; i++)
5618         cpu_put_seg(f, &env->segs[i]);
5619     cpu_put_seg(f, &env->ldt);
5620     cpu_put_seg(f, &env->tr);
5621     cpu_put_seg(f, &env->gdt);
5622     cpu_put_seg(f, &env->idt);
5623     
5624     qemu_put_be32s(f, &env->sysenter_cs);
5625     qemu_put_be32s(f, &env->sysenter_esp);
5626     qemu_put_be32s(f, &env->sysenter_eip);
5627     
5628     qemu_put_betls(f, &env->cr[0]);
5629     qemu_put_betls(f, &env->cr[2]);
5630     qemu_put_betls(f, &env->cr[3]);
5631     qemu_put_betls(f, &env->cr[4]);
5632     
5633     for(i = 0; i < 8; i++)
5634         qemu_put_betls(f, &env->dr[i]);
5635 
5636     /* MMU */
5637     qemu_put_be32s(f, &env->a20_mask);
5638 
5639     /* XMM */
5640     qemu_put_be32s(f, &env->mxcsr);
5641     for(i = 0; i < CPU_NB_REGS; i++) {
5642         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5643         qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5644     }
5645 
5646 #ifdef TARGET_X86_64
5647     qemu_put_be64s(f, &env->efer);
5648     qemu_put_be64s(f, &env->star);
5649     qemu_put_be64s(f, &env->lstar);
5650     qemu_put_be64s(f, &env->cstar);
5651     qemu_put_be64s(f, &env->fmask);
5652     qemu_put_be64s(f, &env->kernelgsbase);
5653 #endif
5654     qemu_put_be32s(f, &env->smbase);
5655 }
5656 
5657 #ifdef USE_X86LDOUBLE
5658 /* XXX: add that in a FPU generic layer */
5659 union x86_longdouble {
5660     uint64_t mant;
5661     uint16_t exp;
5662 };
5663 
5664 #define MANTD1(fp)      (fp & ((1LL << 52) - 1))
5665 #define EXPBIAS1 1023
5666 #define EXPD1(fp)       ((fp >> 52) & 0x7FF)
5667 #define SIGND1(fp)      ((fp >> 32) & 0x80000000)
5668 
5669 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5670 {
5671     int e;
5672     /* mantissa */
5673     p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5674     /* exponent + sign */
5675     e = EXPD1(temp) - EXPBIAS1 + 16383;
5676     e |= SIGND1(temp) >> 16;
5677     p->exp = e;
5678 }
5679 #endif
5680 
5681 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5682 {
5683     CPUState *env = opaque;
5684     int i, guess_mmx;
5685     uint32_t hflags;
5686     uint16_t fpus, fpuc, fptag, fpregs_format;
5687 
5688     if (version_id != 3 && version_id != 4)
5689         return -EINVAL;
5690     for(i = 0; i < CPU_NB_REGS; i++)
5691         qemu_get_betls(f, &env->regs[i]);
5692     qemu_get_betls(f, &env->eip);
5693     qemu_get_betls(f, &env->eflags);
5694     qemu_get_be32s(f, &hflags);
5695 
5696     qemu_get_be16s(f, &fpuc);
5697     qemu_get_be16s(f, &fpus);
5698     qemu_get_be16s(f, &fptag);
5699     qemu_get_be16s(f, &fpregs_format);
5700     
5701     /* NOTE: we cannot always restore the FPU state if the image come
5702        from a host with a different 'USE_X86LDOUBLE' define. We guess
5703        if we are in an MMX state to restore correctly in that case. */
5704     guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5705     for(i = 0; i < 8; i++) {
5706         uint64_t mant;
5707         uint16_t exp;
5708         
5709         switch(fpregs_format) {
5710         case 0:
5711             mant = qemu_get_be64(f);
5712             exp = qemu_get_be16(f);
5713 #ifdef USE_X86LDOUBLE
5714             env->fpregs[i].d = cpu_set_fp80(mant, exp);
5715 #else
5716             /* difficult case */
5717             if (guess_mmx)
5718                 env->fpregs[i].mmx.MMX_Q(0) = mant;
5719             else
5720                 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5721 #endif
5722             break;
5723         case 1:
5724             mant = qemu_get_be64(f);
5725 #ifdef USE_X86LDOUBLE
5726             {
5727                 union x86_longdouble *p;
5728                 /* difficult case */
5729                 p = (void *)&env->fpregs[i];
5730                 if (guess_mmx) {
5731                     p->mant = mant;
5732                     p->exp = 0xffff;
5733                 } else {
5734                     fp64_to_fp80(p, mant);
5735                 }
5736             }
5737 #else
5738             env->fpregs[i].mmx.MMX_Q(0) = mant;
5739 #endif            
5740             break;
5741         default:
5742             return -EINVAL;
5743         }
5744     }
5745 
5746     env->fpuc = fpuc;
5747     /* XXX: restore FPU round state */
5748     env->fpstt = (fpus >> 11) & 7;
5749     env->fpus = fpus & ~0x3800;
5750     fptag ^= 0xff;
5751     for(i = 0; i < 8; i++) {
5752         env->fptags[i] = (fptag >> i) & 1;
5753     }
5754     
5755     for(i = 0; i < 6; i++)
5756         cpu_get_seg(f, &env->segs[i]);
5757     cpu_get_seg(f, &env->ldt);
5758     cpu_get_seg(f, &env->tr);
5759     cpu_get_seg(f, &env->gdt);
5760     cpu_get_seg(f, &env->idt);
5761     
5762     qemu_get_be32s(f, &env->sysenter_cs);
5763     qemu_get_be32s(f, &env->sysenter_esp);
5764     qemu_get_be32s(f, &env->sysenter_eip);
5765     
5766     qemu_get_betls(f, &env->cr[0]);
5767     qemu_get_betls(f, &env->cr[2]);
5768     qemu_get_betls(f, &env->cr[3]);
5769     qemu_get_betls(f, &env->cr[4]);
5770     
5771     for(i = 0; i < 8; i++)
5772         qemu_get_betls(f, &env->dr[i]);
5773 
5774     /* MMU */
5775     qemu_get_be32s(f, &env->a20_mask);
5776 
5777     qemu_get_be32s(f, &env->mxcsr);
5778     for(i = 0; i < CPU_NB_REGS; i++) {
5779         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5780         qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5781     }
5782 
5783 #ifdef TARGET_X86_64
5784     qemu_get_be64s(f, &env->efer);
5785     qemu_get_be64s(f, &env->star);
5786     qemu_get_be64s(f, &env->lstar);
5787     qemu_get_be64s(f, &env->cstar);
5788     qemu_get_be64s(f, &env->fmask);
5789     qemu_get_be64s(f, &env->kernelgsbase);
5790 #endif
5791     if (version_id >= 4) 
5792         qemu_get_be32s(f, &env->smbase);
5793 
5794     /* XXX: compute hflags from scratch, except for CPL and IIF */
5795     env->hflags = hflags;
5796     tlb_flush(env, 1);
5797     return 0;
5798 }
5799 
5800 #elif defined(TARGET_PPC)
5801 void cpu_save(QEMUFile *f, void *opaque)
5802 {
5803 }
5804 
5805 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5806 {
5807     return 0;
5808 }
5809 
5810 #elif defined(TARGET_MIPS)
5811 void cpu_save(QEMUFile *f, void *opaque)
5812 {
5813 }
5814 
5815 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5816 {
5817     return 0;
5818 }
5819 
5820 #elif defined(TARGET_SPARC)
5821 void cpu_save(QEMUFile *f, void *opaque)
5822 {
5823     CPUState *env = opaque;
5824     int i;
5825     uint32_t tmp;
5826 
5827     for(i = 0; i < 8; i++)
5828         qemu_put_betls(f, &env->gregs[i]);
5829     for(i = 0; i < NWINDOWS * 16; i++)
5830         qemu_put_betls(f, &env->regbase[i]);
5831 
5832     /* FPU */
5833     for(i = 0; i < TARGET_FPREGS; i++) {
5834         union {
5835             float32 f;
5836             uint32_t i;
5837         } u;
5838         u.f = env->fpr[i];
5839         qemu_put_be32(f, u.i);
5840     }
5841 
5842     qemu_put_betls(f, &env->pc);
5843     qemu_put_betls(f, &env->npc);
5844     qemu_put_betls(f, &env->y);
5845     tmp = GET_PSR(env);
5846     qemu_put_be32(f, tmp);
5847     qemu_put_betls(f, &env->fsr);
5848     qemu_put_betls(f, &env->tbr);
5849 #ifndef TARGET_SPARC64
5850     qemu_put_be32s(f, &env->wim);
5851     /* MMU */
5852     for(i = 0; i < 16; i++)
5853         qemu_put_be32s(f, &env->mmuregs[i]);
5854 #endif
5855 }
5856 
5857 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5858 {
5859     CPUState *env = opaque;
5860     int i;
5861     uint32_t tmp;
5862 
5863     for(i = 0; i < 8; i++)
5864         qemu_get_betls(f, &env->gregs[i]);
5865     for(i = 0; i < NWINDOWS * 16; i++)
5866         qemu_get_betls(f, &env->regbase[i]);
5867 
5868     /* FPU */
5869     for(i = 0; i < TARGET_FPREGS; i++) {
5870         union {
5871             float32 f;
5872             uint32_t i;
5873         } u;
5874         u.i = qemu_get_be32(f);
5875         env->fpr[i] = u.f;
5876     }
5877 
5878     qemu_get_betls(f, &env->pc);
5879     qemu_get_betls(f, &env->npc);
5880     qemu_get_betls(f, &env->y);
5881     tmp = qemu_get_be32(f);
5882     env->cwp = 0; /* needed to ensure that the wrapping registers are
5883                      correctly updated */
5884     PUT_PSR(env, tmp);
5885     qemu_get_betls(f, &env->fsr);
5886     qemu_get_betls(f, &env->tbr);
5887 #ifndef TARGET_SPARC64
5888     qemu_get_be32s(f, &env->wim);
5889     /* MMU */
5890     for(i = 0; i < 16; i++)
5891         qemu_get_be32s(f, &env->mmuregs[i]);
5892 #endif
5893     tlb_flush(env, 1);
5894     return 0;
5895 }
5896 
5897 #elif defined(TARGET_ARM)
5898 
5899 /* ??? Need to implement these.  */
5900 void cpu_save(QEMUFile *f, void *opaque)
5901 {
5902 }
5903 
5904 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5905 {
5906     return 0;
5907 }
5908 
5909 #else
5910 
5911 #warning No CPU save/restore functions
5912 
5913 #endif
5914 
5915 /***********************************************************/
5916 /* ram save/restore */
5917 
5918 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5919 {
5920     int v;
5921 
5922     v = qemu_get_byte(f);
5923     switch(v) {
5924     case 0:
5925         if (qemu_get_buffer(f, buf, len) != len)
5926             return -EIO;
5927         break;
5928     case 1:
5929         v = qemu_get_byte(f);
5930         memset(buf, v, len);
5931         break;
5932     default:
5933         return -EINVAL;
5934     }
5935     return 0;
5936 }
5937 
5938 static int ram_load_v1(QEMUFile *f, void *opaque)
5939 {
5940     int i, ret;
5941 
5942     if (qemu_get_be32(f) != phys_ram_size)
5943         return -EINVAL;
5944     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5945         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5946         if (ret)
5947             return ret;
5948     }
5949     return 0;
5950 }
5951 
5952 #define BDRV_HASH_BLOCK_SIZE 1024
5953 #define IOBUF_SIZE 4096
5954 #define RAM_CBLOCK_MAGIC 0xfabe
5955 
5956 typedef struct RamCompressState {
5957     z_stream zstream;
5958     QEMUFile *f;
5959     uint8_t buf[IOBUF_SIZE];
5960 } RamCompressState;
5961 
5962 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5963 {
5964     int ret;
5965     memset(s, 0, sizeof(*s));
5966     s->f = f;
5967     ret = deflateInit2(&s->zstream, 1,
5968                        Z_DEFLATED, 15, 
5969                        9, Z_DEFAULT_STRATEGY);
5970     if (ret != Z_OK)
5971         return -1;
5972     s->zstream.avail_out = IOBUF_SIZE;
5973     s->zstream.next_out = s->buf;
5974     return 0;
5975 }
5976 
5977 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5978 {
5979     qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5980     qemu_put_be16(s->f, len);
5981     qemu_put_buffer(s->f, buf, len);
5982 }
5983 
5984 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5985 {
5986     int ret;
5987 
5988     s->zstream.avail_in = len;
5989     s->zstream.next_in = (uint8_t *)buf;
5990     while (s->zstream.avail_in > 0) {
5991         ret = deflate(&s->zstream, Z_NO_FLUSH);
5992         if (ret != Z_OK)
5993             return -1;
5994         if (s->zstream.avail_out == 0) {
5995             ram_put_cblock(s, s->buf, IOBUF_SIZE);
5996             s->zstream.avail_out = IOBUF_SIZE;
5997             s->zstream.next_out = s->buf;
5998         }
5999     }
6000     return 0;
6001 }
6002 
6003 static void ram_compress_close(RamCompressState *s)
6004 {
6005     int len, ret;
6006 
6007     /* compress last bytes */
6008     for(;;) {
6009         ret = deflate(&s->zstream, Z_FINISH);
6010         if (ret == Z_OK || ret == Z_STREAM_END) {
6011             len = IOBUF_SIZE - s->zstream.avail_out;
6012             if (len > 0) {
6013                 ram_put_cblock(s, s->buf, len);
6014             }
6015             s->zstream.avail_out = IOBUF_SIZE;
6016             s->zstream.next_out = s->buf;
6017             if (ret == Z_STREAM_END)
6018                 break;
6019         } else {
6020             goto fail;
6021         }
6022     }
6023 fail:
6024     deflateEnd(&s->zstream);
6025 }
6026 
6027 typedef struct RamDecompressState {
6028     z_stream zstream;
6029     QEMUFile *f;
6030     uint8_t buf[IOBUF_SIZE];
6031 } RamDecompressState;
6032 
6033 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6034 {
6035     int ret;
6036     memset(s, 0, sizeof(*s));
6037     s->f = f;
6038     ret = inflateInit(&s->zstream);
6039     if (ret != Z_OK)
6040         return -1;
6041     return 0;
6042 }
6043 
6044 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6045 {
6046     int ret, clen;
6047 
6048     s->zstream.avail_out = len;
6049     s->zstream.next_out = buf;
6050     while (s->zstream.avail_out > 0) {
6051         if (s->zstream.avail_in == 0) {
6052             if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6053                 return -1;
6054             clen = qemu_get_be16(s->f);
6055             if (clen > IOBUF_SIZE)
6056                 return -1;
6057             qemu_get_buffer(s->f, s->buf, clen);
6058             s->zstream.avail_in = clen;
6059             s->zstream.next_in = s->buf;
6060         }
6061         ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6062         if (ret != Z_OK && ret != Z_STREAM_END) {
6063             return -1;
6064         }
6065     }
6066     return 0;
6067 }
6068 
6069 static void ram_decompress_close(RamDecompressState *s)
6070 {
6071     inflateEnd(&s->zstream);
6072 }
6073 
6074 static void ram_save(QEMUFile *f, void *opaque)
6075 {
6076     int i;
6077     RamCompressState s1, *s = &s1;
6078     uint8_t buf[10];
6079     
6080     qemu_put_be32(f, phys_ram_size);
6081     if (ram_compress_open(s, f) < 0)
6082         return;
6083     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6084 #if 0
6085         if (tight_savevm_enabled) {
6086             int64_t sector_num;
6087             int j;
6088 
6089             /* find if the memory block is available on a virtual
6090                block device */
6091             sector_num = -1;
6092             for(j = 0; j < MAX_DISKS; j++) {
6093                 if (bs_table[j]) {
6094                     sector_num = bdrv_hash_find(bs_table[j], 
6095                                                 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6096                     if (sector_num >= 0)
6097                         break;
6098                 }
6099             }
6100             if (j == MAX_DISKS)
6101                 goto normal_compress;
6102             buf[0] = 1;
6103             buf[1] = j;
6104             cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6105             ram_compress_buf(s, buf, 10);
6106         } else 
6107 #endif
6108         {
6109             //        normal_compress:
6110             buf[0] = 0;
6111             ram_compress_buf(s, buf, 1);
6112             ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6113         }
6114     }
6115     ram_compress_close(s);
6116 }
6117 
6118 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6119 {
6120     RamDecompressState s1, *s = &s1;
6121     uint8_t buf[10];
6122     int i;
6123 
6124     if (version_id == 1)
6125         return ram_load_v1(f, opaque);
6126     if (version_id != 2)
6127         return -EINVAL;
6128     if (qemu_get_be32(f) != phys_ram_size)
6129         return -EINVAL;
6130     if (ram_decompress_open(s, f) < 0)
6131         return -EINVAL;
6132     for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6133         if (ram_decompress_buf(s, buf, 1) < 0) {
6134             fprintf(stderr, "Error while reading ram block header\n");
6135             goto error;
6136         }
6137         if (buf[0] == 0) {
6138             if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6139                 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6140                 goto error;
6141             }
6142         } else 
6143 #if 0
6144         if (buf[0] == 1) {
6145             int bs_index;
6146             int64_t sector_num;
6147 
6148             ram_decompress_buf(s, buf + 1, 9);
6149             bs_index = buf[1];
6150             sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6151             if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6152                 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6153                 goto error;
6154             }
6155             if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
6156                           BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6157                 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
6158                         bs_index, sector_num);
6159                 goto error;
6160             }
6161         } else 
6162 #endif
6163         {
6164         error:
6165             printf("Error block header\n");
6166             return -EINVAL;
6167         }
6168     }
6169     ram_decompress_close(s);
6170     return 0;
6171 }
6172 #else  /* CONFIG_DM */
6173 void cpu_save(QEMUFile *f, void *opaque)
6174 {
6175 }
6176 
6177 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6178 {
6179     return 0;
6180 }
6181 
6182 static void ram_save(QEMUFile *f, void *opaque)
6183 {
6184 }
6185 
6186 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6187 {
6188     return 0;
6189 }
6190 #endif /* CONFIG_DM */
6191 
6192 /***********************************************************/
6193 /* bottom halves (can be seen as timers which expire ASAP) */
6194 
6195 struct QEMUBH {
6196     QEMUBHFunc *cb;
6197     void *opaque;
6198     int scheduled;
6199     QEMUBH *next;
6200 };
6201 
6202 static QEMUBH *first_bh = NULL;
6203 
6204 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6205 {
6206     QEMUBH *bh;
6207     bh = qemu_mallocz(sizeof(QEMUBH));
6208     if (!bh)
6209         return NULL;
6210     bh->cb = cb;
6211     bh->opaque = opaque;
6212     return bh;
6213 }
6214 
6215 int qemu_bh_poll(void)
6216 {
6217     QEMUBH *bh, **pbh;
6218     int ret;
6219 
6220     ret = 0;
6221     for(;;) {
6222         pbh = &first_bh;
6223         bh = *pbh;
6224         if (!bh)
6225             break;
6226         ret = 1;
6227         *pbh = bh->next;
6228         bh->scheduled = 0;
6229         bh->cb(bh->opaque);
6230     }
6231     return ret;
6232 }
6233 
6234 void qemu_bh_schedule(QEMUBH *bh)
6235 {
6236     CPUState *env = cpu_single_env;
6237     if (bh->scheduled)
6238         return;
6239     bh->scheduled = 1;
6240     bh->next = first_bh;
6241     first_bh = bh;
6242 
6243     /* stop the currently executing CPU to execute the BH ASAP */
6244     if (env) {
6245         cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6246     }
6247 }
6248 
6249 void qemu_bh_cancel(QEMUBH *bh)
6250 {
6251     QEMUBH **pbh;
6252     if (bh->scheduled) {
6253         pbh = &first_bh;
6254         while (*pbh != bh)
6255             pbh = &(*pbh)->next;
6256         *pbh = bh->next;
6257         bh->scheduled = 0;
6258     }
6259 }
6260 
6261 void qemu_bh_delete(QEMUBH *bh)
6262 {
6263     qemu_bh_cancel(bh);
6264     qemu_free(bh);
6265 }
6266 
6267 /***********************************************************/
6268 /* machine registration */
6269 
6270 QEMUMachine *first_machine = NULL;
6271 
6272 int qemu_register_machine(QEMUMachine *m)
6273 {
6274     QEMUMachine **pm;
6275     pm = &first_machine;
6276     while (*pm != NULL)
6277         pm = &(*pm)->next;
6278     m->next = NULL;
6279     *pm = m;
6280     return 0;
6281 }
6282 
6283 QEMUMachine *find_machine(const char *name)
6284 {
6285     QEMUMachine *m;
6286 
6287     for(m = first_machine; m != NULL; m = m->next) {
6288         if (!strcmp(m->name, name))
6289             return m;
6290     }
6291     return NULL;
6292 }
6293 
6294 /***********************************************************/
6295 /* main execution loop */
6296 
6297 void gui_update(void *opaque)
6298 {
6299     display_state.dpy_refresh(&display_state);
6300     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6301 }
6302 
6303 struct vm_change_state_entry {
6304     VMChangeStateHandler *cb;
6305     void *opaque;
6306     LIST_ENTRY (vm_change_state_entry) entries;
6307 };
6308 
6309 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6310 
6311 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6312                                                      void *opaque)
6313 {
6314     VMChangeStateEntry *e;
6315 
6316     e = qemu_mallocz(sizeof (*e));
6317     if (!e)
6318         return NULL;
6319 
6320     e->cb = cb;
6321     e->opaque = opaque;
6322     LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6323     return e;
6324 }
6325 
6326 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6327 {
6328     LIST_REMOVE (e, entries);
6329     qemu_free (e);
6330 }
6331 
6332 static void vm_state_notify(int running)
6333 {
6334     VMChangeStateEntry *e;
6335 
6336     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6337         e->cb(e->opaque, running);
6338     }
6339 }
6340 
6341 /* XXX: support several handlers */
6342 static VMStopHandler *vm_stop_cb;
6343 static void *vm_stop_opaque;
6344 
6345 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6346 {
6347     vm_stop_cb = cb;
6348     vm_stop_opaque = opaque;
6349     return 0;
6350 }
6351 
6352 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6353 {
6354     vm_stop_cb = NULL;
6355 }
6356 
6357 void vm_start(void)
6358 {
6359     if (!vm_running) {
6360         cpu_enable_ticks();
6361         vm_running = 1;
6362         vm_state_notify(1);
6363     }
6364 }
6365 
6366 void vm_stop(int reason) 
6367 {
6368     if (vm_running) {
6369         cpu_disable_ticks();
6370         vm_running = 0;
6371         if (reason != 0) {
6372             if (vm_stop_cb) {
6373                 vm_stop_cb(vm_stop_opaque, reason);
6374             }
6375         }
6376         vm_state_notify(0);
6377     }
6378 }
6379 
6380 /* reset/shutdown handler */
6381 
6382 typedef struct QEMUResetEntry {
6383     QEMUResetHandler *func;
6384     void *opaque;
6385     struct QEMUResetEntry *next;
6386 } QEMUResetEntry;
6387 
6388 static QEMUResetEntry *first_reset_entry;
6389 int reset_requested;
6390 int shutdown_requested;
6391 int suspend_requested;
6392 static int powerdown_requested;
6393 
6394 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6395 {
6396     QEMUResetEntry **pre, *re;
6397 
6398     pre = &first_reset_entry;
6399     while (*pre != NULL)
6400         pre = &(*pre)->next;
6401     re = qemu_mallocz(sizeof(QEMUResetEntry));
6402     re->func = func;
6403     re->opaque = opaque;
6404     re->next = NULL;
6405     *pre = re;
6406 }
6407 
6408 void qemu_system_reset(void)
6409 {
6410     QEMUResetEntry *re;
6411 
6412     /* reset all devices */
6413     for(re = first_reset_entry; re != NULL; re = re->next) {
6414         re->func(re->opaque);
6415     }
6416 }
6417 
6418 void qemu_system_reset_request(void)
6419 {
6420     if (no_reboot) {
6421         shutdown_requested = 1;
6422     } else {
6423         reset_requested = 1;
6424     }
6425     if (cpu_single_env)
6426         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6427 }
6428 
6429 void qemu_system_shutdown_request(void)
6430 {
6431     shutdown_requested = 1;
6432     if (cpu_single_env)
6433         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6434 }
6435 
6436 void qemu_system_powerdown_request(void)
6437 {
6438     powerdown_requested = 1;
6439     if (cpu_single_env)
6440         cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6441 }
6442 
6443 void main_loop_wait(int timeout)
6444 {
6445     IOHandlerRecord *ioh;
6446     fd_set rfds, wfds, xfds;
6447     int ret, nfds;
6448     struct timeval tv;
6449     PollingEntry *pe;
6450 
6451 
6452     /* XXX: need to suppress polling by better using win32 events */
6453     ret = 0;
6454     for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6455         ret |= pe->func(pe->opaque);
6456     }
6457 #ifdef _WIN32
6458     if (ret == 0 && timeout > 0) {
6459         int err;
6460         WaitObjects *w = &wait_objects;
6461         
6462         ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6463         if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6464             if (w->func[ret - WAIT_OBJECT_0])
6465                 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6466         } else if (ret == WAIT_TIMEOUT) {
6467         } else {
6468             err = GetLastError();
6469             fprintf(stderr, "Wait error %d %d\n", ret, err);
6470         }
6471     }
6472 #endif
6473     /* poll any events */
6474     /* XXX: separate device handlers from system ones */
6475     nfds = -1;
6476     FD_ZERO(&rfds);
6477     FD_ZERO(&wfds);
6478     FD_ZERO(&xfds);
6479     for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6480         if (ioh->deleted)
6481             continue;
6482         if (ioh->fd_read &&
6483             (!ioh->fd_read_poll ||
6484              ioh->fd_read_poll(ioh->opaque) != 0)) {
6485             FD_SET(ioh->fd, &rfds);
6486             if (ioh->fd > nfds)
6487                 nfds = ioh->fd;
6488         }
6489         if (ioh->fd_write) {
6490             FD_SET(ioh->fd, &wfds);
6491             if (ioh->fd > nfds)
6492                 nfds = ioh->fd;
6493         }
6494     }
6495     
6496     tv.tv_sec = 0;
6497 #ifdef _WIN32
6498     tv.tv_usec = 0;
6499 #else
6500     tv.tv_usec = timeout * 1000;
6501 #endif
6502 #if defined(CONFIG_SLIRP)
6503     if (slirp_inited) {
6504         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6505     }
6506 #endif
6507     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6508     if (ret > 0) {
6509         IOHandlerRecord **pioh;
6510 
6511         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6512             if (ioh->deleted)
6513                 continue;
6514             if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6515                 ioh->fd_read(ioh->opaque);
6516             }
6517             if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6518                 ioh->fd_write(ioh->opaque);
6519             }
6520         }
6521 
6522         /* remove deleted IO handlers */
6523         pioh = &first_io_handler;
6524         while (*pioh) {
6525             ioh = *pioh;
6526             if (ioh->deleted) {
6527                 *pioh = ioh->next;
6528                 qemu_free(ioh);
6529             } else 
6530                 pioh = &ioh->next;
6531         }
6532     }
6533 #if defined(CONFIG_SLIRP)
6534     if (slirp_inited) {
6535         if (ret < 0) {
6536             FD_ZERO(&rfds);
6537             FD_ZERO(&wfds);
6538             FD_ZERO(&xfds);
6539         }
6540         slirp_select_poll(&rfds, &wfds, &xfds);
6541     }
6542 #endif
6543     qemu_aio_poll();
6544     qemu_bh_poll();
6545 
6546     if (vm_running) {
6547         qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6548                         qemu_get_clock(vm_clock));
6549         /* run dma transfers, if any */
6550         DMA_run();
6551     }
6552     
6553     /* real time timers */
6554     qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6555                     qemu_get_clock(rt_clock));
6556 }
6557 
6558 #ifndef CONFIG_DM
6559 static CPUState *cur_cpu;
6560 
6561 int main_loop(void)
6562 {
6563     int ret, timeout;
6564 #ifdef CONFIG_PROFILER
6565     int64_t ti;
6566 #endif
6567     CPUState *env;
6568 
6569     cur_cpu = first_cpu;
6570     for(;;) {
6571         if (vm_running) {
6572 
6573             env = cur_cpu;
6574             for(;;) {
6575                 /* get next cpu */
6576                 env = env->next_cpu;
6577                 if (!env)
6578                     env = first_cpu;
6579 #ifdef CONFIG_PROFILER
6580                 ti = profile_getclock();
6581 #endif
6582                 ret = cpu_exec(env);
6583 #ifdef CONFIG_PROFILER
6584                 qemu_time += profile_getclock() - ti;
6585 #endif
6586                 if (ret != EXCP_HALTED)
6587                     break;
6588                 /* all CPUs are halted ? */
6589                 if (env == cur_cpu) {
6590                     ret = EXCP_HLT;
6591                     break;
6592                 }
6593             }
6594             cur_cpu = env;
6595 
6596             if (shutdown_requested) {
6597                 ret = EXCP_INTERRUPT;
6598                 break;
6599             }
6600             if (reset_requested) {
6601                 reset_requested = 0;
6602                 qemu_system_reset();
6603                 ret = EXCP_INTERRUPT;
6604             }
6605             if (powerdown_requested) {
6606                 powerdown_requested = 0;
6607                 qemu_system_powerdown();
6608                 ret = EXCP_INTERRUPT;
6609             }
6610             if (ret == EXCP_DEBUG) {
6611                 vm_stop(EXCP_DEBUG);
6612             }
6613             /* if hlt instruction, we wait until the next IRQ */
6614             /* XXX: use timeout computed from timers */
6615             if (ret == EXCP_HLT)
6616                 timeout = 10;
6617             else
6618                 timeout = 0;
6619         } else {
6620             timeout = 10;
6621         }
6622 #ifdef CONFIG_PROFILER
6623         ti = profile_getclock();
6624 #endif
6625         main_loop_wait(timeout);
6626 #ifdef CONFIG_PROFILER
6627         dev_time += profile_getclock() - ti;
6628 #endif
6629     }
6630     cpu_disable_ticks();
6631     return ret;
6632 }
6633 #endif /* !CONFIG_DM */
6634 
6635 void help(void)
6636 {
6637     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6638            "usage: %s [options] [disk_image]\n"
6639            "\n"
6640            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6641            "\n"
6642            "Standard options:\n"
6643            "-M machine      select emulated machine (-M ? for list)\n"
6644            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6645 #ifndef CONFIG_DM
6646            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6647            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6648            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6649 #endif /* !CONFIG_DM */
6650            "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6651            "-snapshot       write to temporary files instead of disk image files\n"
6652 #ifdef CONFIG_SDL
6653            "-no-quit        disable SDL window close capability\n"
6654 #endif
6655 #ifdef TARGET_I386
6656            "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6657 #endif
6658            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6659            "-smp n          set the number of CPUs to 'n' [default=1]\n"
6660            "-nographic      disable graphical output and redirect serial I/Os to console\n"
6661            "-vcpus          set CPU number of guest platform\n"
6662 #ifndef _WIN32
6663            "-k language     use keyboard layout (for example \"fr\" for French)\n"
6664 #endif
6665 #ifdef HAS_AUDIO
6666            "-audio-help     print list of audio drivers and their options\n"
6667            "-soundhw c1,... enable audio support\n"
6668            "                and only specified sound cards (comma separated list)\n"
6669            "                use -soundhw ? to get the list of supported cards\n"
6670            "                use -soundhw all to enable all of them\n"
6671 #endif
6672            "-localtime      set the real time clock to local time [default=utc]\n"
6673            "-full-screen    start in full screen\n"
6674 #ifdef TARGET_I386
6675            "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6676 #endif
6677            "-usb            enable the USB driver (will be the default soon)\n"
6678            "-usbdevice name add the host or guest USB device 'name'\n"
6679 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6680            "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6681 #endif
6682            "\n"
6683            "Network options:\n"
6684            "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6685            "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6686 #ifdef CONFIG_SLIRP
6687            "-net user[,vlan=n][,hostname=host]\n"
6688            "                connect the user mode network stack to VLAN 'n' and send\n"
6689            "                hostname 'host' to DHCP clients\n"
6690 #endif
6691 #ifdef _WIN32
6692            "-net tap[,vlan=n],ifname=name\n"
6693            "                connect the host TAP network interface to VLAN 'n'\n"
6694 #else
6695            "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,bridge=br]\n"
6696            "                connect the host TAP network interface to VLAN 'n' and use\n"
6697            "                the network script 'file' (default=%s);\n"
6698            "                use 'script=no' to disable script execution;\n"
6699            "                use 'fd=h' to connect to an already opened TAP interface\n"
6700 #endif
6701            "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6702            "                connect the vlan 'n' to another VLAN using a socket connection\n"
6703            "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6704            "                connect the vlan 'n' to multicast maddr and port\n"
6705            "-net none       use it alone to have zero network devices; if no -net option\n"
6706            "                is provided, the default is '-net nic -net user'\n"
6707            "\n"
6708 #ifdef CONFIG_SLIRP
6709            "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
6710 #ifndef _WIN32
6711            "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6712 #endif
6713            "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6714            "                redirect TCP or UDP connections from host to guest [-net user]\n"
6715 #endif
6716            "\n"
6717            "Linux boot specific:\n"
6718            "-kernel bzImage use 'bzImage' as kernel image\n"
6719            "-append cmdline use 'cmdline' as kernel command line\n"
6720            "-initrd file    use 'file' as initial ram disk\n"
6721            "\n"
6722            "Debug/Expert options:\n"
6723            "-monitor dev    redirect the monitor to char device 'dev'\n"
6724            "-serial dev     redirect the serial port to char device 'dev'\n"
6725            "-parallel dev   redirect the parallel port to char device 'dev'\n"
6726            "-pidfile file   Write PID to 'file'\n"
6727            "-S              freeze CPU at startup (use 'c' to start execution)\n"
6728            "-s              wait gdb connection to port %d\n"
6729            "-p port         change gdb connection port\n"
6730            "-l item1,...    output log to %s (use -d ? for a list of log items)\n"
6731            "-d domain       domain that we're serving\n"
6732            "-domain-name    domain name that we're serving\n"
6733            "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6734            "                translation (t=none or lba) (usually qemu can guess them)\n"
6735            "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6736 #ifdef USE_KQEMU
6737            "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6738            "-no-kqemu       disable KQEMU kernel module usage\n"
6739 #endif
6740 #ifdef USE_CODE_COPY
6741            "-no-code-copy   disable code copy acceleration\n"
6742 #endif
6743 #ifdef TARGET_I386
6744            "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6745            "                (default is CL-GD5446 PCI VGA)\n"
6746            "-no-acpi        disable ACPI\n"
6747 #endif
6748            "-no-reboot      exit instead of rebooting\n"
6749            "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6750            "-vnc display    start a VNC server on display\n"
6751            "-vncviewer      start a vncviewer process for this domain\n"
6752            "-vncunused      bind the VNC server to an unused port\n"
6753            "-vnclisten      bind the VNC server to this address\n"
6754            "-timeoffset     time offset (in seconds) from local time\n"
6755 #ifndef _WIN32
6756            "-daemonize      daemonize QEMU after initializing\n"
6757 #endif
6758            "-option-rom rom load a file, rom, into the option ROM space\n"
6759            "-acpi           disable or enable ACPI of HVM domain \n"
6760            "\n"
6761            "During emulation, the following keys are useful:\n"
6762            "ctrl-alt-f      toggle full screen\n"
6763            "ctrl-alt-n      switch to virtual console 'n'\n"
6764            "ctrl-alt        toggle mouse and keyboard grab\n"
6765            "\n"
6766            "When using -nographic, press 'ctrl-a h' to get some help.\n"
6767            ,
6768            "qemu",
6769            DEFAULT_RAM_SIZE,
6770 #ifndef _WIN32
6771            DEFAULT_NETWORK_SCRIPT,
6772 #endif
6773            DEFAULT_GDBSTUB_PORT,
6774            "/tmp/qemu.log");
6775     exit(1);
6776 }
6777 
6778 #define HAS_ARG 0x0001
6779 
6780 enum {
6781     QEMU_OPTION_h,
6782 
6783     QEMU_OPTION_M,
6784     QEMU_OPTION_fda,
6785     QEMU_OPTION_fdb,
6786 #ifndef CONFIG_DM
6787     QEMU_OPTION_hda,
6788     QEMU_OPTION_hdb,
6789     QEMU_OPTION_hdc,
6790     QEMU_OPTION_hdd,
6791     QEMU_OPTION_cdrom,
6792 #endif /* !CONFIG_DM */
6793     QEMU_OPTION_boot,
6794     QEMU_OPTION_snapshot,
6795 #ifdef TARGET_I386
6796     QEMU_OPTION_no_fd_bootchk,
6797 #endif
6798     QEMU_OPTION_m,
6799     QEMU_OPTION_nographic,
6800 #ifdef HAS_AUDIO
6801     QEMU_OPTION_audio_help,
6802     QEMU_OPTION_soundhw,
6803 #endif
6804 
6805     QEMU_OPTION_net,
6806     QEMU_OPTION_tftp,
6807     QEMU_OPTION_smb,
6808     QEMU_OPTION_redir,
6809 
6810     QEMU_OPTION_kernel,
6811     QEMU_OPTION_append,
6812     QEMU_OPTION_initrd,
6813 
6814     QEMU_OPTION_S,
6815     QEMU_OPTION_s,
6816     QEMU_OPTION_p,
6817     QEMU_OPTION_l,
6818     QEMU_OPTION_hdachs,
6819     QEMU_OPTION_L,
6820 #ifdef USE_CODE_COPY
6821     QEMU_OPTION_no_code_copy,
6822 #endif
6823     QEMU_OPTION_k,
6824     QEMU_OPTION_localtime,
6825     QEMU_OPTION_cirrusvga,
6826     QEMU_OPTION_g,
6827     QEMU_OPTION_std_vga,
6828     QEMU_OPTION_monitor,
6829     QEMU_OPTION_domainname,
6830     QEMU_OPTION_serial,
6831     QEMU_OPTION_parallel,
6832     QEMU_OPTION_loadvm,
6833     QEMU_OPTION_full_screen,
6834     QEMU_OPTION_no_quit,
6835     QEMU_OPTION_pidfile,
6836     QEMU_OPTION_no_kqemu,
6837     QEMU_OPTION_kernel_kqemu,
6838     QEMU_OPTION_win2k_hack,
6839     QEMU_OPTION_usb,
6840     QEMU_OPTION_usbdevice,
6841     QEMU_OPTION_smp,
6842     QEMU_OPTION_vnc,
6843     QEMU_OPTION_no_acpi,
6844     QEMU_OPTION_no_reboot,
6845     QEMU_OPTION_daemonize,
6846     QEMU_OPTION_option_rom,
6847     QEMU_OPTION_semihosting
6848     ,
6849     QEMU_OPTION_d,
6850     QEMU_OPTION_vcpus,
6851     QEMU_OPTION_timeoffset,
6852     QEMU_OPTION_acpi,
6853     QEMU_OPTION_vncviewer,
6854     QEMU_OPTION_vncunused,
6855     QEMU_OPTION_vnclisten,
6856 };
6857 
6858 typedef struct QEMUOption {
6859     const char *name;
6860     int flags;
6861     int index;
6862 } QEMUOption;
6863 
6864 const QEMUOption qemu_options[] = {
6865     { "h", 0, QEMU_OPTION_h },
6866     { "help", 0, QEMU_OPTION_h },
6867 
6868     { "M", HAS_ARG, QEMU_OPTION_M },
6869     { "fda", HAS_ARG, QEMU_OPTION_fda },
6870     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6871 #ifndef CONFIG_DM
6872     { "hda", HAS_ARG, QEMU_OPTION_hda },
6873     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6874     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6875     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6876     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6877 #endif /* !CONFIG_DM */
6878     { "boot", HAS_ARG, QEMU_OPTION_boot },
6879     { "snapshot", 0, QEMU_OPTION_snapshot },
6880 #ifdef TARGET_I386
6881     { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6882 #endif
6883     { "m", HAS_ARG, QEMU_OPTION_m },
6884     { "nographic", 0, QEMU_OPTION_nographic },
6885     { "k", HAS_ARG, QEMU_OPTION_k },
6886 #ifdef HAS_AUDIO
6887     { "audio-help", 0, QEMU_OPTION_audio_help },
6888     { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6889 #endif
6890 
6891     { "net", HAS_ARG, QEMU_OPTION_net},
6892 #ifdef CONFIG_SLIRP
6893     { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6894 #ifndef _WIN32
6895     { "smb", HAS_ARG, QEMU_OPTION_smb },
6896 #endif
6897     { "redir", HAS_ARG, QEMU_OPTION_redir },
6898 #endif
6899 
6900     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6901     { "append", HAS_ARG, QEMU_OPTION_append },
6902     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6903 
6904     { "S", 0, QEMU_OPTION_S },
6905     { "s", 0, QEMU_OPTION_s },
6906     { "p", HAS_ARG, QEMU_OPTION_p },
6907     { "l", HAS_ARG, QEMU_OPTION_l },
6908     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6909     { "L", HAS_ARG, QEMU_OPTION_L },
6910 #ifdef USE_CODE_COPY
6911     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6912 #endif
6913 #ifdef USE_KQEMU
6914     { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6915     { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6916 #endif
6917 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6918     { "g", 1, QEMU_OPTION_g },
6919 #endif
6920     { "localtime", 0, QEMU_OPTION_localtime },
6921     { "std-vga", 0, QEMU_OPTION_std_vga },
6922     { "monitor", 1, QEMU_OPTION_monitor },
6923     { "domain-name", 1, QEMU_OPTION_domainname },
6924     { "serial", 1, QEMU_OPTION_serial },
6925     { "parallel", 1, QEMU_OPTION_parallel },
6926     { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6927     { "full-screen", 0, QEMU_OPTION_full_screen },
6928 #ifdef CONFIG_SDL
6929     { "no-quit", 0, QEMU_OPTION_no_quit },
6930 #endif
6931     { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6932     { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6933     { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6934     { "smp", HAS_ARG, QEMU_OPTION_smp },
6935     { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6936     { "vncviewer", 0, QEMU_OPTION_vncviewer },
6937     { "vncunused", 0, QEMU_OPTION_vncunused },
6938     { "vnclisten", HAS_ARG, QEMU_OPTION_vnclisten },
6939 
6940     /* temporary options */
6941     { "usb", 0, QEMU_OPTION_usb },
6942     { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6943     { "no-acpi", 0, QEMU_OPTION_no_acpi },
6944     { "no-reboot", 0, QEMU_OPTION_no_reboot },
6945     { "daemonize", 0, QEMU_OPTION_daemonize },
6946     { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6947 #if defined(TARGET_ARM)
6948     { "semihosting", 0, QEMU_OPTION_semihosting },
6949 #endif
6950     
6951     { "d", HAS_ARG, QEMU_OPTION_d },
6952     { "vcpus", 1, QEMU_OPTION_vcpus },
6953     { "timeoffset", HAS_ARG, QEMU_OPTION_timeoffset },
6954     { "acpi", 0, QEMU_OPTION_acpi },
6955     { NULL },
6956 };
6957 
6958 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6959 
6960 /* this stack is only used during signal handling */
6961 #define SIGNAL_STACK_SIZE 32768
6962 
6963 static uint8_t *signal_stack;
6964 
6965 #endif
6966 
6967 /* password input */
6968 
6969 static BlockDriverState *get_bdrv(int index)
6970 {
6971     BlockDriverState *bs;
6972 
6973     if (index < 4) {
6974         bs = bs_table[index];
6975     } else if (index < 6) {
6976         bs = fd_table[index - 4];
6977     } else {
6978         bs = NULL;
6979     }
6980     return bs;
6981 }
6982 
6983 static void read_passwords(void)
6984 {
6985     BlockDriverState *bs;
6986     int i, j;
6987     char password[256];
6988 
6989     for(i = 0; i < 6; i++) {
6990         bs = get_bdrv(i);
6991         if (bs && bdrv_is_encrypted(bs)) {
6992             term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6993             for(j = 0; j < 3; j++) {
6994                 monitor_readline("Password: ", 
6995                                  1, password, sizeof(password));
6996                 if (bdrv_set_key(bs, password) == 0)
6997                     break;
6998                 term_printf("invalid password\n");
6999             }
7000         }
7001     }
7002 }
7003 
7004 /* XXX: currently we cannot use simultaneously different CPUs */
7005 void register_machines(void)
7006 {
7007 #if defined(TARGET_I386)
7008     qemu_register_machine(&pc_machine);
7009     qemu_register_machine(&isapc_machine);
7010 #elif defined(TARGET_PPC)
7011     qemu_register_machine(&heathrow_machine);
7012     qemu_register_machine(&core99_machine);
7013     qemu_register_machine(&prep_machine);
7014 #elif defined(TARGET_MIPS)
7015     qemu_register_machine(&mips_machine);
7016     qemu_register_machine(&mips_malta_machine);
7017 #elif defined(TARGET_SPARC)
7018 #ifdef TARGET_SPARC64
7019     qemu_register_machine(&sun4u_machine);
7020 #else
7021     qemu_register_machine(&sun4m_machine);
7022 #endif
7023 #elif defined(TARGET_ARM)
7024     qemu_register_machine(&integratorcp926_machine);
7025     qemu_register_machine(&integratorcp1026_machine);
7026     qemu_register_machine(&versatilepb_machine);
7027     qemu_register_machine(&versatileab_machine);
7028     qemu_register_machine(&realview_machine);
7029 #elif defined(TARGET_SH4)
7030     qemu_register_machine(&shix_machine);
7031 #else
7032 #error unsupported CPU
7033 #endif
7034 }
7035 
7036 #ifdef HAS_AUDIO
7037 struct soundhw soundhw[] = {
7038 #ifndef CONFIG_DM
7039 #ifdef TARGET_I386
7040     {
7041         "pcspk",
7042         "PC speaker",
7043         0,
7044         1,
7045         { .init_isa = pcspk_audio_init }
7046     },
7047 #endif
7048 #endif /* !CONFIG_DM */
7049     {
7050         "sb16",
7051         "Creative Sound Blaster 16",
7052         0,
7053         1,
7054         { .init_isa = SB16_init }
7055     },
7056 
7057 #ifdef CONFIG_ADLIB
7058     {
7059         "adlib",
7060 #ifdef HAS_YMF262
7061         "Yamaha YMF262 (OPL3)",
7062 #else
7063         "Yamaha YM3812 (OPL2)",
7064 #endif
7065         0,
7066         1,
7067         { .init_isa = Adlib_init }
7068     },
7069 #endif
7070 
7071 #ifdef CONFIG_GUS
7072     {
7073         "gus",
7074         "Gravis Ultrasound GF1",
7075         0,
7076         1,
7077         { .init_isa = GUS_init }
7078     },
7079 #endif
7080 
7081     {
7082         "es1370",
7083         "ENSONIQ AudioPCI ES1370",
7084         0,
7085         0,
7086         { .init_pci = es1370_init }
7087     },
7088 
7089     { NULL, NULL, 0, 0, { NULL } }
7090 };
7091 
7092 static void select_soundhw (const char *optarg)
7093 {
7094     struct soundhw *c;
7095 
7096     if (*optarg == '?') {
7097     show_valid_cards:
7098 
7099         printf ("Valid sound card names (comma separated):\n");
7100         for (c = soundhw; c->name; ++c) {
7101             printf ("%-11s %s\n", c->name, c->descr);
7102         }
7103         printf ("\n-soundhw all will enable all of the above\n");
7104         exit (*optarg != '?');
7105     }
7106     else {
7107         size_t l;
7108         const char *p;
7109         char *e;
7110         int bad_card = 0;
7111 
7112         if (!strcmp (optarg, "all")) {
7113             for (c = soundhw; c->name; ++c) {
7114                 c->enabled = 1;
7115             }
7116             return;
7117         }
7118 
7119         p = optarg;
7120         while (*p) {
7121             e = strchr (p, ',');
7122             l = !e ? strlen (p) : (size_t) (e - p);
7123 
7124             for (c = soundhw; c->name; ++c) {
7125                 if (!strncmp (c->name, p, l)) {
7126                     c->enabled = 1;
7127                     break;
7128                 }
7129             }
7130 
7131             if (!c->name) {
7132                 if (l > 80) {
7133                     fprintf (stderr,
7134                              "Unknown sound card name (too big to show)\n");
7135                 }
7136                 else {
7137                     fprintf (stderr, "Unknown sound card name `%.*s'\n",
7138                              (int) l, p);
7139                 }
7140                 bad_card = 1;
7141             }
7142             p += l + (e != NULL);
7143         }
7144 
7145         if (bad_card)
7146             goto show_valid_cards;
7147     }
7148 }
7149 #endif
7150 
7151 #ifdef _WIN32
7152 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7153 {
7154     exit(STATUS_CONTROL_C_EXIT);
7155     return TRUE;
7156 }
7157 #endif
7158 
7159 #define MAX_NET_CLIENTS 32
7160 
7161 #include <xg_private.h>
7162 
7163 /* FIXME Flush the shadow page */
7164 int unset_mm_mapping(int xc_handle, uint32_t domid,
7165                      unsigned long nr_pages, unsigned int address_bits,
7166                      xen_pfn_t *extent_start)
7167 {
7168     int err = 0;
7169     xc_dominfo_t info;
7170 
7171     xc_domain_getinfo(xc_handle, domid, 1, &info);
7172     if ((info.nr_pages - nr_pages) <= 0) {
7173         fprintf(stderr, "unset_mm_mapping: error nr_pages\n");
7174         err = -1;
7175     }
7176 
7177     err = xc_domain_memory_decrease_reservation(xc_handle, domid,
7178                                                 nr_pages, 0, extent_start);
7179     if (err)
7180         fprintf(stderr, "Failed to decrease physmap\n");
7181 
7182 
7183     if (xc_domain_setmaxmem(xc_handle, domid, (info.nr_pages - nr_pages) *
7184                             PAGE_SIZE/1024) != 0) {
7185         fprintf(logfile, "set maxmem returned error %d\n", errno);
7186         err = -1;
7187     }
7188 
7189     return err;
7190 }
7191 
7192 int set_mm_mapping(int xc_handle, uint32_t domid,
7193                    unsigned long nr_pages, unsigned int address_bits,
7194                    xen_pfn_t *extent_start)
7195 {
7196     xc_dominfo_t info;
7197     int err = 0;
7198 
7199     xc_domain_getinfo(xc_handle, domid, 1, &info);
7200 
7201     if (xc_domain_setmaxmem(xc_handle, domid, info.max_memkb +
7202                             nr_pages * PAGE_SIZE/1024) != 0) {
7203         fprintf(logfile, "set maxmem returned error %d\n", errno);
7204         return -1;
7205     }
7206 
7207     err = xc_domain_memory_populate_physmap(xc_handle, domid, nr_pages, 0,
7208                                             address_bits, extent_start);
7209     if (err) {
7210         fprintf(stderr, "Failed to populate physmap\n");
7211         return -1;
7212     }
7213 
7214     return 0;
7215 }
7216 
7217 void suspend(int sig)
7218 {
7219     fprintf(logfile, "suspend sig handler called with requested=%d!\n",
7220             suspend_requested);
7221     if (sig != SIGUSR1)
7222         fprintf(logfile, "suspend signal dismatch, get sig=%d!\n", sig);
7223     suspend_requested = 1;
7224 }
7225 
7226 #if defined(MAPCACHE)
7227 
7228 #if defined(__i386__) 
7229 #define MAX_MCACHE_SIZE    0x40000000 /* 1GB max for x86 */
7230 #define MCACHE_BUCKET_SHIFT 16
7231 #elif defined(__x86_64__)
7232 #define MAX_MCACHE_SIZE    0x1000000000 /* 64GB max for x86_64 */
7233 #define MCACHE_BUCKET_SHIFT 20
7234 #endif
7235 
7236 #define MCACHE_BUCKET_SIZE (1UL << MCACHE_BUCKET_SHIFT)
7237 
7238 #define BITS_PER_LONG (sizeof(long)*8)
7239 #define BITS_TO_LONGS(bits) \
7240     (((bits)+BITS_PER_LONG-1)/BITS_PER_LONG)
7241 #define DECLARE_BITMAP(name,bits) \
7242     unsigned long name[BITS_TO_LONGS(bits)]
7243 #define test_bit(bit,map) \
7244     (!!((map)[(bit)/BITS_PER_LONG] & (1UL << ((bit)%BITS_PER_LONG))))
7245 
7246 struct map_cache {
7247     unsigned long paddr_index;
7248     uint8_t      *vaddr_base;
7249     DECLARE_BITMAP(valid_mapping, MCACHE_BUCKET_SIZE>>PAGE_SHIFT);
7250 };
7251 
7252 static struct map_cache *mapcache_entry;
7253 static unsigned long nr_buckets;
7254 
7255 /* For most cases (>99.9%), the page address is the same. */
7256 static unsigned long last_address_index = ~0UL;
7257 static uint8_t      *last_address_vaddr;
7258 
7259 static int qemu_map_cache_init(void)
7260 {
7261     unsigned long size;
7262 
7263     nr_buckets = (((MAX_MCACHE_SIZE >> PAGE_SHIFT) +
7264                    (1UL << (MCACHE_BUCKET_SHIFT - PAGE_SHIFT)) - 1) >>
7265                   (MCACHE_BUCKET_SHIFT - PAGE_SHIFT));
7266     fprintf(logfile, "qemu_map_cache_init nr_buckets = %lx\n", nr_buckets);
7267 
7268     /*
7269      * Use mmap() directly: lets us allocate a big hash table with no up-front
7270      * cost in storage space. The OS will allocate memory only for the buckets
7271      * that we actually use. All others will contain all zeroes.
7272      */
7273     size = nr_buckets * sizeof(struct map_cache);
7274     size = (size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
7275     mapcache_entry = mmap(NULL, size, PROT_READ|PROT_WRITE,
7276                           MAP_SHARED|MAP_ANONYMOUS, -1, 0);
7277     if (mapcache_entry == MAP_FAILED) {
7278         errno = ENOMEM;
7279         return -1;
7280     }
7281 
7282     return 0;
7283 }
7284 
7285 static void qemu_remap_bucket(struct map_cache *entry,
7286                               unsigned long address_index)
7287 {
7288     uint8_t *vaddr_base;
7289     unsigned long pfns[MCACHE_BUCKET_SIZE >> PAGE_SHIFT];
7290     unsigned int i, j;
7291 
7292     if (entry->vaddr_base != NULL) {
7293         errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
7294         if (errno) {
7295             fprintf(logfile, "unmap fails %d\n", errno);
7296             exit(-1);
7297         }
7298     }
7299 
7300     for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i++)
7301         pfns[i] = (address_index << (MCACHE_BUCKET_SHIFT-PAGE_SHIFT)) + i;
7302 
7303     vaddr_base = xc_map_foreign_batch(xc_handle, domid, PROT_READ|PROT_WRITE,
7304                                       pfns, MCACHE_BUCKET_SIZE >> PAGE_SHIFT);
7305     if (vaddr_base == NULL) {
7306         fprintf(logfile, "xc_map_foreign_batch error %d\n", errno);
7307         exit(-1);
7308     }
7309 
7310     entry->vaddr_base  = vaddr_base;
7311     entry->paddr_index = address_index;
7312 
7313     for (i = 0; i < MCACHE_BUCKET_SIZE >> PAGE_SHIFT; i += BITS_PER_LONG) {
7314         unsigned long word = 0;
7315         j = ((i + BITS_PER_LONG) > (MCACHE_BUCKET_SIZE >> PAGE_SHIFT)) ?
7316             (MCACHE_BUCKET_SIZE >> PAGE_SHIFT) % BITS_PER_LONG : BITS_PER_LONG;
7317         while (j > 0)
7318             word = (word << 1) | (((pfns[i + --j] >> 28) & 0xf) != 0xf);
7319         entry->valid_mapping[i / BITS_PER_LONG] = word;
7320     }
7321 }
7322 
7323 uint8_t *qemu_map_cache(target_phys_addr_t phys_addr)
7324 {
7325     struct map_cache *entry;
7326     unsigned long address_index  = phys_addr >> MCACHE_BUCKET_SHIFT;
7327     unsigned long address_offset = phys_addr & (MCACHE_BUCKET_SIZE-1);
7328 
7329     if (address_index == last_address_index)
7330         return last_address_vaddr + address_offset;
7331 
7332     entry = &mapcache_entry[address_index % nr_buckets];
7333 
7334     if (entry->vaddr_base == NULL || entry->paddr_index != address_index ||
7335         !test_bit(address_offset>>PAGE_SHIFT, entry->valid_mapping))
7336         qemu_remap_bucket(entry, address_index);
7337 
7338     if (!test_bit(address_offset>>PAGE_SHIFT, entry->valid_mapping))
7339         return NULL;
7340 
7341     last_address_index = address_index;
7342     last_address_vaddr = entry->vaddr_base;
7343 
7344     return last_address_vaddr + address_offset;
7345 }
7346 
7347 void qemu_invalidate_map_cache(void)
7348 {
7349     unsigned long i;
7350 
7351     mapcache_lock();
7352 
7353     for (i = 0; i < nr_buckets; i++) {
7354         struct map_cache *entry = &mapcache_entry[i];
7355 
7356         if (entry->vaddr_base == NULL)
7357             continue;
7358 
7359         errno = munmap(entry->vaddr_base, MCACHE_BUCKET_SIZE);
7360         if (errno) {
7361             fprintf(logfile, "unmap fails %d\n", errno);
7362             exit(-1);
7363         }
7364 
7365         entry->paddr_index = 0;
7366         entry->vaddr_base  = NULL;
7367     }
7368 
7369     last_address_index =  ~0UL;
7370     last_address_vaddr = NULL;
7371 
7372     mapcache_unlock();
7373 }
7374 
7375 #endif /* defined(MAPCACHE) */
7376 
7377 int main(int argc, char **argv)
7378 {
7379 #ifdef CONFIG_GDBSTUB
7380     int use_gdbstub, gdbstub_port;
7381 #endif
7382     int i;
7383 #ifndef CONFIG_DM
7384     int cdrom_index;
7385 #endif /* !CONFIG_DM */
7386     int snapshot, linux_boot;
7387     const char *initrd_filename;
7388 #ifndef CONFIG_DM
7389     const char *hd_filename[MAX_DISKS + MAX_SCSI_DISKS];
7390 #endif /* !CONFIG_DM */
7391     const char *fd_filename[MAX_FD];
7392     const char *kernel_filename, *kernel_cmdline;
7393     DisplayState *ds = &display_state;
7394     int cyls, heads, secs, translation;
7395     char net_clients[MAX_NET_CLIENTS][256];
7396     int nb_net_clients;
7397     int optind;
7398     const char *r, *optarg;
7399     CharDriverState *monitor_hd;
7400     char monitor_device[128];
7401     char serial_devices[MAX_SERIAL_PORTS][128];
7402     int serial_device_index;
7403     char parallel_devices[MAX_PARALLEL_PORTS][128];
7404     int parallel_device_index;
7405     const char *loadvm = NULL;
7406     QEMUMachine *machine;
7407     char usb_devices[MAX_USB_CMDLINE][128];
7408     int usb_devices_index;
7409     int fds[2];
7410     unsigned long ioreq_pfn;
7411     extern void *shared_page;
7412     extern void *buffered_io_page;
7413 #ifdef __ia64__
7414     unsigned long nr_pages;
7415     xen_pfn_t *page_array;
7416     extern void *buffered_pio_page;
7417 #endif
7418 
7419     char qemu_dm_logfilename[64];
7420 
7421     LIST_INIT (&vm_change_state_head);
7422 #ifndef _WIN32
7423     {
7424         struct sigaction act;
7425         sigfillset(&act.sa_mask);
7426         act.sa_flags = 0;
7427         act.sa_handler = SIG_IGN;
7428         sigaction(SIGPIPE, &act, NULL);
7429     }
7430 #else
7431     SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7432     /* Note: cpu_interrupt() is currently not SMP safe, so we force
7433        QEMU to run on a single CPU */
7434     {
7435         HANDLE h;
7436         DWORD mask, smask;
7437         int i;
7438         h = GetCurrentProcess();
7439         if (GetProcessAffinityMask(h, &mask, &smask)) {
7440             for(i = 0; i < 32; i++) {
7441                 if (mask & (1 << i))
7442                     break;
7443             }
7444             if (i != 32) {
7445                 mask = 1 << i;
7446                 SetProcessAffinityMask(h, mask);
7447             }
7448         }
7449     }
7450 #endif
7451 
7452     register_machines();
7453     machine = first_machine;
7454     initrd_filename = NULL;
7455     for(i = 0; i < MAX_FD; i++)
7456         fd_filename[i] = NULL;
7457 #ifndef CONFIG_DM
7458     for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++)
7459         hd_filename[i] = NULL;
7460 #endif /* !CONFIG_DM */
7461     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7462     vga_ram_size = VGA_RAM_SIZE;
7463     bios_size = BIOS_SIZE;
7464 #ifdef CONFIG_GDBSTUB
7465     use_gdbstub = 0;
7466     gdbstub_port = DEFAULT_GDBSTUB_PORT;
7467 #endif
7468     snapshot = 0;
7469     nographic = 0;
7470     vncviewer = 0;
7471     vncunused = 0;
7472     kernel_filename = NULL;
7473     kernel_cmdline = "";
7474     *vncpasswd = '\0';
7475 #ifndef CONFIG_DM
7476 #ifdef TARGET_PPC
7477     cdrom_index = 1;
7478 #else
7479     cdrom_index = 2;
7480 #endif
7481 #endif /* !CONFIG_DM */
7482     cyls = heads = secs = 0;
7483     translation = BIOS_ATA_TRANSLATION_AUTO;
7484     pstrcpy(monitor_device, sizeof(monitor_device), "null");
7485 
7486     for(i = 0; i < MAX_SERIAL_PORTS; i++)
7487         serial_devices[i][0] = '\0';
7488     serial_device_index = 0;
7489 
7490     pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7491     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7492         parallel_devices[i][0] = '\0';
7493     parallel_device_index = 0;
7494     
7495     usb_devices_index = 0;
7496     
7497     nb_net_clients = 0;
7498 
7499     nb_nics = 0;
7500     /* default mac address of the first network interface */
7501 
7502     memset(&vnclisten_addr.sin_addr, 0, sizeof(vnclisten_addr.sin_addr));
7503     
7504     /* init debug */
7505     sprintf(qemu_dm_logfilename, "/var/log/xen/qemu-dm.%ld.log", (long)getpid());
7506     cpu_set_log_filename(qemu_dm_logfilename);
7507     cpu_set_log(0);
7508     
7509     optind = 1;
7510     for(;;) {
7511         if (optind >= argc)
7512             break;
7513         r = argv[optind];
7514         if (r[0] != '-') {
7515 #ifndef CONFIG_DM
7516             hd_filename[0] = argv[optind++];
7517 #else
7518             help();
7519 #endif /* !CONFIG_DM */
7520         } else {
7521             const QEMUOption *popt;
7522 
7523             optind++;
7524             /* Treat --foo the same as -foo.  */
7525             if (r[1] == '-')
7526                 r++;
7527             popt = qemu_options;
7528             for(;;) {
7529                 if (!popt->name) {
7530                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
7531                             argv[0], r);
7532                     exit(1);
7533                 }
7534                 if (!strcmp(popt->name, r + 1))
7535                     break;
7536                 popt++;
7537             }
7538             if (popt->flags & HAS_ARG) {
7539                 if (optind >= argc) {
7540                     fprintf(stderr, "%s: option '%s' requires an argument\n",
7541                             argv[0], r);
7542                     exit(1);
7543                 }
7544                 optarg = argv[optind++];
7545             } else {
7546                 optarg = NULL;
7547             }
7548 
7549             switch(popt->index) {
7550             case QEMU_OPTION_M:
7551                 machine = find_machine(optarg);
7552                 if (!machine) {
7553                     QEMUMachine *m;
7554                     printf("Supported machines are:\n");
7555                     for(m = first_machine; m != NULL; m = m->next) {
7556                         printf("%-10s %s%s\n",
7557                                m->name, m->desc, 
7558                                m == first_machine ? " (default)" : "");
7559                     }
7560                     exit(1);
7561                 }
7562                 break;
7563             case QEMU_OPTION_initrd:
7564                 initrd_filename = optarg;
7565                 break;
7566 #ifndef CONFIG_DM
7567             case QEMU_OPTION_hda:
7568             case QEMU_OPTION_hdb:
7569             case QEMU_OPTION_hdc:
7570             case QEMU_OPTION_hdd:
7571                 {
7572                     int hd_index;
7573                     hd_index = popt->index - QEMU_OPTION_hda;
7574                     hd_filename[hd_index] = optarg;
7575                     if (hd_index == cdrom_index)
7576                         cdrom_index = -1;
7577                 }
7578                 break;
7579 #endif /* !CONFIG_DM */
7580             case QEMU_OPTION_snapshot:
7581                 snapshot = 1;
7582                 break;
7583             case QEMU_OPTION_hdachs:
7584                 {
7585                     const char *p;
7586                     p = optarg;
7587                     cyls = strtol(p, (char **)&p, 0);
7588                     if (cyls < 1 || cyls > 16383)
7589                         goto chs_fail;
7590                     if (*p != ',')
7591                         goto chs_fail;
7592                     p++;
7593                     heads = strtol(p, (char **)&p, 0);
7594                     if (heads < 1 || heads > 16)
7595                         goto chs_fail;
7596                     if (*p != ',')
7597                         goto chs_fail;
7598                     p++;
7599                     secs = strtol(p, (char **)&p, 0);
7600                     if (secs < 1 || secs > 63)
7601                         goto chs_fail;
7602                     if (*p == ',') {
7603                         p++;
7604                         if (!strcmp(p, "none"))
7605                             translation = BIOS_ATA_TRANSLATION_NONE;
7606                         else if (!strcmp(p, "lba"))
7607                             translation = BIOS_ATA_TRANSLATION_LBA;
7608                         else if (!strcmp(p, "auto"))
7609                             translation = BIOS_ATA_TRANSLATION_AUTO;
7610                         else
7611                             goto chs_fail;
7612                     } else if (*p != '\0') {
7613                     chs_fail:
7614                         fprintf(stderr, "qemu: invalid physical CHS format\n");
7615                         exit(1);
7616                     }
7617                 }
7618                 break;
7619             case QEMU_OPTION_nographic:
7620                 if(!strcmp(monitor_device, "vc"))
7621                     pstrcpy(monitor_device, sizeof(monitor_device), "null");
7622                 if(!strcmp(serial_devices[0], "vc"))
7623                     pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
7624                             "null");
7625                 nographic = 1;
7626                 break;
7627             case QEMU_OPTION_kernel:
7628                 kernel_filename = optarg;
7629                 break;
7630             case QEMU_OPTION_append:
7631                 kernel_cmdline = optarg;
7632                 break;
7633 #ifndef CONFIG_DM
7634             case QEMU_OPTION_cdrom:
7635                 if (cdrom_index >= 0) {
7636                     hd_filename[cdrom_index] = optarg;
7637                 }
7638                 break;
7639 #endif /* !CONFIG_DM */
7640             case QEMU_OPTION_boot:
7641                 boot_device = strdup(optarg);
7642                 if (strspn(boot_device, "a"
7643 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7644                     // Network boot
7645                     "n"
7646 #endif
7647                     "cd") != strlen(boot_device)) {
7648                     fprintf(stderr, "qemu: invalid boot device in '%s'\n", boot_device);
7649                     exit(1);
7650                 }
7651                 break;
7652             case QEMU_OPTION_fda:
7653                 fd_filename[0] = optarg;
7654                 break;
7655             case QEMU_OPTION_fdb:
7656                 fd_filename[1] = optarg;
7657                 break;
7658 #ifdef TARGET_I386
7659             case QEMU_OPTION_no_fd_bootchk:
7660                 fd_bootchk = 0;
7661                 break;
7662 #endif
7663 #ifdef USE_CODE_COPY
7664             case QEMU_OPTION_no_code_copy:
7665                 code_copy_enabled = 0;
7666                 break;
7667 #endif
7668             case QEMU_OPTION_net:
7669                 if (nb_net_clients >= MAX_NET_CLIENTS) {
7670                     fprintf(stderr, "qemu: too many network clients\n");
7671                     exit(1);
7672                 }
7673                 pstrcpy(net_clients[nb_net_clients],
7674                         sizeof(net_clients[0]),
7675                         optarg);
7676                 nb_net_clients++;
7677                 break;
7678 #ifdef CONFIG_SLIRP
7679             case QEMU_OPTION_tftp:
7680                 tftp_prefix = optarg;
7681                 break;
7682 #ifndef _WIN32
7683             case QEMU_OPTION_smb:
7684                 net_slirp_smb(optarg);
7685                 break;
7686 #endif
7687             case QEMU_OPTION_redir:
7688                 net_slirp_redir(optarg);                
7689                 break;
7690 #endif
7691 #ifdef HAS_AUDIO
7692             case QEMU_OPTION_audio_help:
7693                 AUD_help ();
7694                 exit (0);
7695                 break;
7696             case QEMU_OPTION_soundhw:
7697                 select_soundhw (optarg);
7698                 break;
7699 #endif
7700             case QEMU_OPTION_h:
7701                 help();
7702                 break;
7703             case QEMU_OPTION_m:
7704                 ram_size = atol(optarg) * 1024 * 1024;
7705                 ram_size = (uint64_t)atol(optarg) * 1024 * 1024;
7706                 if (ram_size <= 0)
7707                     help();
7708 #ifndef CONFIG_DM
7709                 if (ram_size > PHYS_RAM_MAX_SIZE) {
7710                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7711                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
7712                     exit(1);
7713                 }
7714 #endif /* !CONFIG_DM */
7715                 break;
7716             case QEMU_OPTION_l:
7717                 {
7718                     int mask;
7719                     CPULogItem *item;
7720                     
7721                     mask = cpu_str_to_log_mask(optarg);
7722                     if (!mask) {
7723                         printf("Log items (comma separated):\n");
7724                     for(item = cpu_log_items; item->mask != 0; item++) {
7725                         printf("%-10s %s\n", item->name, item->help);
7726                     }
7727                     exit(1);
7728                     }
7729                     cpu_set_log(mask);
7730                 }
7731                 break;
7732 #ifdef CONFIG_GDBSTUB
7733             case QEMU_OPTION_s:
7734                 use_gdbstub = 1;
7735                 break;
7736             case QEMU_OPTION_p:
7737                 gdbstub_port = atoi(optarg);
7738                 break;
7739 #endif
7740             case QEMU_OPTION_L:
7741                 bios_dir = optarg;
7742                 break;
7743             case QEMU_OPTION_S:
7744                 autostart = 0;
7745                 break;
7746             case QEMU_OPTION_k:
7747                 keyboard_layout = optarg;
7748                 break;
7749             case QEMU_OPTION_localtime:
7750                 rtc_utc = 0;
7751                 break;
7752             case QEMU_OPTION_cirrusvga:
7753                 cirrus_vga_enabled = 1;
7754                 break;
7755             case QEMU_OPTION_std_vga:
7756                 cirrus_vga_enabled = 0;
7757                 break;
7758             case QEMU_OPTION_g:
7759                 {
7760                     const char *p;
7761                     int w, h, depth;
7762                     p = optarg;
7763                     w = strtol(p, (char **)&p, 10);
7764                     if (w <= 0) {
7765                     graphic_error:
7766                         fprintf(stderr, "qemu: invalid resolution or depth\n");
7767                         exit(1);
7768                     }
7769                     if (*p != 'x')
7770                         goto graphic_error;
7771                     p++;
7772                     h = strtol(p, (char **)&p, 10);
7773                     if (h <= 0)
7774                         goto graphic_error;
7775                     if (*p == 'x') {
7776                         p++;
7777                         depth = strtol(p, (char **)&p, 10);
7778                         if (depth != 8 && depth != 15 && depth != 16 && 
7779                             depth != 24 && depth != 32)
7780                             goto graphic_error;
7781                     } else if (*p == '\0') {
7782                         depth = graphic_depth;
7783                     } else {
7784                         goto graphic_error;
7785                     }
7786                     
7787                     graphic_width = w;
7788                     graphic_height = h;
7789                     graphic_depth = depth;
7790                 }
7791                 break;
7792             case QEMU_OPTION_monitor:
7793                 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7794                 break;
7795             case QEMU_OPTION_serial:
7796                 if (serial_device_index >= MAX_SERIAL_PORTS) {
7797                     fprintf(stderr, "qemu: too many serial ports\n");
7798                     exit(1);
7799                 }
7800                 pstrcpy(serial_devices[serial_device_index], 
7801                         sizeof(serial_devices[0]), optarg);
7802                 serial_device_index++;
7803                 break;
7804             case QEMU_OPTION_parallel:
7805                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7806                     fprintf(stderr, "qemu: too many parallel ports\n");
7807                     exit(1);
7808                 }
7809                 pstrcpy(parallel_devices[parallel_device_index], 
7810                         sizeof(parallel_devices[0]), optarg);
7811                 parallel_device_index++;
7812                 break;
7813             case QEMU_OPTION_loadvm:
7814                 loadvm = optarg;
7815                 break;
7816             case QEMU_OPTION_full_screen:
7817                 full_screen = 1;
7818                 break;
7819 #ifdef CONFIG_SDL
7820             case QEMU_OPTION_no_quit:
7821                 no_quit = 1;
7822                 break;
7823 #endif
7824             case QEMU_OPTION_pidfile:
7825                 create_pidfile(optarg);
7826                 break;
7827 #ifdef TARGET_I386
7828             case QEMU_OPTION_win2k_hack:
7829                 win2k_install_hack = 1;
7830                 break;
7831 #endif
7832 #ifdef USE_KQEMU
7833             case QEMU_OPTION_no_kqemu:
7834                 kqemu_allowed = 0;
7835                 break;
7836             case QEMU_OPTION_kernel_kqemu:
7837                 kqemu_allowed = 2;
7838                 break;
7839 #endif
7840             case QEMU_OPTION_usb:
7841                 usb_enabled = 1;
7842                 break;
7843             case QEMU_OPTION_usbdevice:
7844                 usb_enabled = 1;
7845                 if (usb_devices_index >= MAX_USB_CMDLINE) {
7846                     fprintf(stderr, "Too many USB devices\n");
7847                     exit(1);
7848                 }
7849                 pstrcpy(usb_devices[usb_devices_index],
7850                         sizeof(usb_devices[usb_devices_index]),
7851                         optarg);
7852                 usb_devices_index++;
7853                 break;
7854             case QEMU_OPTION_smp:
7855                 smp_cpus = atoi(optarg);
7856                 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7857                     fprintf(stderr, "Invalid number of CPUs\n");
7858                     exit(1);
7859                 }
7860                 break;
7861             case QEMU_OPTION_vnc:
7862                 vnc_display = optarg;
7863                 break;
7864             case QEMU_OPTION_no_acpi:
7865                 acpi_enabled = 0;
7866                 break;
7867             case QEMU_OPTION_no_reboot:
7868                 no_reboot = 1;
7869                 break;
7870             case QEMU_OPTION_daemonize:
7871                 daemonize = 1;
7872                 break;
7873             case QEMU_OPTION_option_rom:
7874                 if (nb_option_roms >= MAX_OPTION_ROMS) {
7875                     fprintf(stderr, "Too many option ROMs\n");
7876                     exit(1);
7877                 }
7878                 option_rom[nb_option_roms] = optarg;
7879                 nb_option_roms++;
7880                 break;
7881             case QEMU_OPTION_semihosting:
7882                 semihosting_enabled = 1;
7883                 break;
7884             case QEMU_OPTION_domainname:
7885                 snprintf(domain_name, sizeof(domain_name),
7886                          "xVM-HVM-%s", optarg);
7887                 break;
7888             case QEMU_OPTION_d:
7889                 domid = atoi(optarg);
7890                 fprintf(logfile, "domid: %d\n", domid);
7891                 break;
7892             case QEMU_OPTION_vcpus:
7893                 vcpus = atoi(optarg);
7894                 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
7895                 break;
7896             case QEMU_OPTION_timeoffset:
7897                 timeoffset = strtol(optarg, NULL, 0);
7898                 break;
7899             case QEMU_OPTION_acpi:
7900                 acpi_enabled = 1;
7901                 break;
7902             case QEMU_OPTION_vncviewer:
7903                 vncviewer++;
7904                 break;
7905             case QEMU_OPTION_vncunused:
7906                 vncunused++;
7907                 break;
7908             case QEMU_OPTION_vnclisten:
7909                 parse_host(&vnclisten_addr, optarg);
7910                 break;
7911             }
7912         }
7913     }
7914 
7915 #ifndef _WIN32
7916     if (daemonize && !nographic && vnc_display == NULL && vncunused == 0) {
7917         fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7918         daemonize = 0;
7919     }
7920 
7921     if (daemonize) {
7922         pid_t pid;
7923 
7924         if (pipe(fds) == -1)
7925             exit(1);
7926 
7927         pid = fork();
7928         if (pid > 0) {
7929             uint8_t status;
7930             ssize_t len;
7931 
7932             close(fds[1]);
7933 
7934         again:
7935             len = read(fds[0], &status, 1);
7936             if (len == -1 && (errno == EINTR))
7937                 goto again;
7938             
7939             if (len != 1 || status != 0)
7940                 exit(1);
7941             else
7942                 exit(0);
7943         } else if (pid < 0)
7944             exit(1);
7945 
7946         setsid();
7947 
7948         pid = fork();
7949         if (pid > 0)
7950             exit(0);
7951         else if (pid < 0)
7952             exit(1);
7953 
7954         umask(027);
7955         chdir("/");
7956 
7957         signal(SIGTSTP, SIG_IGN);
7958         signal(SIGTTOU, SIG_IGN);
7959         signal(SIGTTIN, SIG_IGN);
7960     }
7961 #endif
7962 
7963 #ifdef CONFIG_DM
7964     bdrv_init();
7965     xenstore_parse_domain_config(domid);
7966 #endif /* CONFIG_DM */
7967 
7968 #ifdef USE_KQEMU
7969     if (smp_cpus > 1)
7970         kqemu_allowed = 0;
7971 #endif
7972     linux_boot = (kernel_filename != NULL);
7973 
7974 #ifndef CONFIG_DM
7975     if (!linux_boot &&
7976         hd_filename[0] == '\0' && 
7977         (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7978         fd_filename[0] == '\0')
7979         help();
7980 
7981     /* boot to floppy or the default cd if no hard disk defined yet */
7982     if (hd_filename[0] == '\0' && boot_device == 'c') {
7983         if (fd_filename[0] != '\0')
7984             boot_device = 'a';
7985         else
7986             boot_device = 'd';
7987     }
7988 #endif /* !CONFIG_DM */
7989 
7990     setvbuf(stdout, NULL, _IOLBF, 0);
7991     
7992     init_timers();
7993     init_timer_alarm();
7994     qemu_aio_init();
7995 
7996 #ifdef _WIN32
7997     socket_init();
7998 #endif
7999 
8000 #ifndef CONFIG_DM
8001     /* init network clients */
8002     if (nb_net_clients == 0) {
8003         /* if no clients, we use a default config */
8004         pstrcpy(net_clients[0], sizeof(net_clients[0]),
8005                 "nic");
8006         pstrcpy(net_clients[1], sizeof(net_clients[0]),
8007                 "user");
8008         nb_net_clients = 2;
8009     }
8010 #endif /* !CONFIG_DM */
8011 
8012     for(i = 0;i < nb_net_clients; i++) {
8013         if (net_client_init(net_clients[i]) < 0)
8014             exit(1);
8015     }
8016 
8017 #ifndef CONFIG_DM
8018 #ifdef TARGET_I386
8019     if (boot_device == 'n') {
8020         for (i = 0; i < nb_nics; i++) {
8021             const char *model = nd_table[i].model;
8022             char buf[1024];
8023             if (model == NULL)
8024                 model = "ne2k_pci";
8025             snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8026             if (get_image_size(buf) > 0) {
8027                 option_rom[nb_option_roms] = strdup(buf);
8028                 nb_option_roms++;
8029                 break;
8030             }
8031         }
8032         if (i == nb_nics) {
8033             fprintf(stderr, "No valid PXE rom found for network device\n");
8034             exit(1);
8035         }
8036         boot_device = 'c'; /* to prevent confusion by the BIOS */
8037     }
8038 #endif
8039 #endif /* !CONFIG_DM */
8040 
8041 #if defined (__ia64__)
8042     if (ram_size > MMIO_START)
8043         ram_size += 1 * MEM_G; /* skip 3G-4G MMIO, LEGACY_IO_SPACE etc. */
8044 #endif
8045 
8046     /* init the memory */
8047     phys_ram_size = ram_size + vga_ram_size + bios_size;
8048 
8049 #ifndef CONFIG_DM
8050     for (i = 0; i < nb_option_roms; i++) {
8051         int ret = get_image_size(option_rom[i]);
8052         if (ret == -1) {
8053             fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
8054             exit(1);
8055         }
8056         phys_ram_size += ret;
8057     }
8058 #endif /* !CONFIG_DM */
8059 
8060 #ifdef CONFIG_DM
8061 
8062     xc_handle = xc_interface_open();
8063 
8064 #if defined(__i386__) || defined(__x86_64__)
8065 
8066     if (qemu_map_cache_init()) {
8067         fprintf(logfile, "qemu_map_cache_init returned: error %d\n", errno);
8068         exit(-1);
8069     }
8070 
8071     xc_get_hvm_param(xc_handle, domid, HVM_PARAM_IOREQ_PFN, &ioreq_pfn);
8072     fprintf(logfile, "shared page at pfn %lx\n", ioreq_pfn);
8073     shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
8074                                        PROT_READ|PROT_WRITE, ioreq_pfn);
8075     if (shared_page == NULL) {
8076         fprintf(logfile, "map shared IO page returned error %d\n", errno);
8077         exit(-1);
8078     }
8079 
8080     xc_get_hvm_param(xc_handle, domid, HVM_PARAM_BUFIOREQ_PFN, &ioreq_pfn);
8081     fprintf(logfile, "buffered io page at pfn %lx\n", ioreq_pfn);
8082     buffered_io_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
8083                                             PROT_READ|PROT_WRITE, ioreq_pfn);
8084     if (buffered_io_page == NULL) {
8085         fprintf(logfile, "map buffered IO page returned error %d\n", errno);
8086         exit(-1);
8087     }
8088 
8089 #elif defined(__ia64__)
8090 
8091     nr_pages = ram_size/PAGE_SIZE;
8092 
8093     page_array = (xen_pfn_t *)malloc(nr_pages * sizeof(xen_pfn_t));
8094     if (page_array == NULL) {
8095         fprintf(logfile, "malloc returned error %d\n", errno);
8096         exit(-1);
8097     }
8098 
8099     shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
8100                                        PROT_READ|PROT_WRITE,
8101                                        IO_PAGE_START >> PAGE_SHIFT);
8102 
8103     buffered_io_page =xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
8104                                        PROT_READ|PROT_WRITE,
8105                                        BUFFER_IO_PAGE_START >> PAGE_SHIFT);
8106 
8107     buffered_pio_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
8108                                        PROT_READ|PROT_WRITE,
8109                                        BUFFER_PIO_PAGE_START >> PAGE_SHIFT);
8110 
8111     for (i = 0; i < nr_pages; i++)
8112         page_array[i] = i;
8113         
8114     /* VTI will not use memory between 3G~4G, so we just pass a legal pfn
8115        to make QEMU map continuous virtual memory space */
8116     if (ram_size > MMIO_START) {     
8117         for (i = 0 ; i < (MEM_G >> PAGE_SHIFT); i++)
8118             page_array[(MMIO_START >> PAGE_SHIFT) + i] =
8119                 (STORE_PAGE_START >> PAGE_SHIFT); 
8120     }
8121 
8122     phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
8123                                          PROT_READ|PROT_WRITE,
8124                                          page_array, nr_pages);
8125     if (phys_ram_base == 0) {
8126         fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
8127         exit(-1);
8128     }
8129     free(page_array);
8130 #endif
8131 
8132     timeoffset_get();
8133 
8134 #else  /* !CONFIG_DM */
8135 
8136     phys_ram_base = qemu_vmalloc(phys_ram_size);
8137     if (!phys_ram_base) {
8138         fprintf(stderr, "Could not allocate physical memory\n");
8139         exit(1);
8140     }
8141 
8142 #endif /* !CONFIG_DM */
8143 
8144 #ifndef CONFIG_DM
8145     /* we always create the cdrom drive, even if no disk is there */
8146     bdrv_init();
8147     if (cdrom_index >= 0) {
8148         bs_table[cdrom_index] = bdrv_new("cdrom");
8149         bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8150     }
8151 
8152     /* open the virtual block devices */
8153     for(i = 0; i < MAX_DISKS + MAX_SCSI_DISKS; i++) {
8154         if (hd_filename[i]) {
8155             if (!bs_table[i]) {
8156                 char buf[64];
8157                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8158                 bs_table[i] = bdrv_new(buf);
8159             }
8160             if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8161                 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8162                         hd_filename[i]);
8163                 exit(1);
8164             }
8165             if (i == 0 && cyls != 0) {
8166                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8167                 bdrv_set_translation_hint(bs_table[i], translation);
8168             }
8169         }
8170     }
8171 #endif /* !CONFIG_DM */
8172 
8173     /* we always create at least one floppy disk */
8174     fd_table[0] = bdrv_new("fda");
8175     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8176 
8177     for(i = 0; i < MAX_FD; i++) {
8178         if (fd_filename[i]) {
8179             if (!fd_table[i]) {
8180                 char buf[64];
8181                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8182                 fd_table[i] = bdrv_new(buf);
8183                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8184             }
8185             if (fd_filename[i] != '\0') {
8186                 if (bdrv_open(fd_table[i], fd_filename[i],
8187                               snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8188                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8189                             fd_filename[i]);
8190                     exit(1);
8191                 }
8192             }
8193         }
8194     }
8195 
8196     register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8197     register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8198 
8199     init_ioports();
8200 
8201     /* read vncpasswd from xenstore */
8202     if (0 > xenstore_read_vncpasswd(domid))
8203         exit(1);
8204 
8205     /* terminal init */
8206     if (nographic) {
8207         dumb_display_init(ds);
8208     } else if (vnc_display != NULL || vncunused != 0) {
8209         int vnc_display_port;
8210         vnc_display_port = vnc_display_init(ds, vnc_display, vncunused,
8211                                             &vnclisten_addr);
8212         if (vncviewer)
8213             vnc_start_viewer(vnc_display_port);
8214         xenstore_write_vncport(vnc_display_port);
8215     } else {
8216 #if defined(CONFIG_SDL)
8217         sdl_display_init(ds, full_screen);
8218 #elif defined(CONFIG_COCOA)
8219         cocoa_display_init(ds, full_screen);
8220 #else
8221         dumb_display_init(ds);
8222 #endif
8223     }
8224 
8225     monitor_hd = qemu_chr_open(monitor_device);
8226     if (!monitor_hd) {
8227         fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8228         exit(1);
8229     }
8230     store_dev_info(monitor_device, domid, monitor_hd, "/monitor");
8231     monitor_init(monitor_hd, !nographic);
8232 
8233     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8234         const char *devname = serial_devices[i];
8235         if (devname[0] != '\0' && strcmp(devname, "none")) {
8236             char buf[16];
8237             serial_hds[i] = qemu_chr_open(devname);
8238             if (!serial_hds[i]) {
8239                 fprintf(stderr, "qemu: could not open serial device '%s'\n", 
8240                         devname);
8241                 exit(1);
8242             }
8243             snprintf(buf, sizeof(buf), "/serial/%d", i);
8244             store_dev_info(serial_devices[i], domid, serial_hds[i], buf);
8245             if (i == 0) /* serial 0 is also called the console */
8246                 store_dev_info(serial_devices[i], domid,
8247                                serial_hds[i], "/console");
8248             if (!strcmp(devname, "vc"))
8249                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8250         }
8251     }
8252 
8253     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8254         const char *devname = parallel_devices[i];
8255         if (devname[0] != '\0' && strcmp(devname, "none")) {
8256             char buf[16];
8257             parallel_hds[i] = qemu_chr_open(devname);
8258             if (!parallel_hds[i]) {
8259                 fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
8260                         devname);
8261                 exit(1);
8262             }
8263             snprintf(buf, sizeof(buf), "/parallel/%d", i);
8264             store_dev_info(parallel_devices[i], domid, parallel_hds[i], buf);
8265             if (!strcmp(devname, "vc"))
8266                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8267         }
8268     }
8269 
8270     qemu_set_fd_handler(xenstore_fd(), xenstore_process_event, NULL, NULL);
8271 
8272     machine->init(ram_size, vga_ram_size, boot_device,
8273                   ds, fd_filename, snapshot,
8274                   kernel_filename, kernel_cmdline, initrd_filename,
8275                   timeoffset);
8276     free(boot_device);
8277 
8278     /* init USB devices */
8279     if (usb_enabled) {
8280         for(i = 0; i < usb_devices_index; i++) {
8281             if (usb_device_add(usb_devices[i]) < 0) {
8282                 fprintf(stderr, "Warning: could not add USB device %s\n",
8283                         usb_devices[i]);
8284             }
8285         }
8286     }
8287 
8288     if (vnc_display == NULL && vncunused == 0) {
8289         gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
8290         qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
8291     }
8292 
8293 #ifdef CONFIG_GDBSTUB
8294     if (use_gdbstub) {
8295         /* XXX: use standard host:port notation and modify options
8296            accordingly. */
8297         if (gdbserver_start_port(gdbstub_port) < 0) {
8298             fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
8299                     gdbstub_port);
8300             exit(1);
8301         }
8302     } else 
8303 #endif
8304     if (loadvm)
8305         do_loadvm(loadvm);
8306 
8307     {
8308         /* XXX: simplify init */
8309         read_passwords();
8310         if (autostart) {
8311             vm_start();
8312         }
8313     }
8314 
8315     if (daemonize) {
8316         uint8_t status = 0;
8317         ssize_t len;
8318         int fd;
8319 
8320     again1:
8321         len = write(fds[1], &status, 1);
8322         if (len == -1 && (errno == EINTR))
8323             goto again1;
8324 
8325         if (len != 1)
8326             exit(1);
8327 
8328         fd = open("/dev/null", O_RDWR);
8329         if (fd == -1)
8330             exit(1);
8331 
8332         dup2(fd, 0);
8333         dup2(fd, 1);
8334         dup2(fd, 2);
8335 
8336         close(fd);
8337     }
8338 
8339     /* register signal for the suspend request when save */
8340     {
8341         struct sigaction act;
8342         sigset_t set;
8343         act.sa_handler = suspend;
8344         act.sa_flags = SA_RESTART;
8345         sigemptyset(&act.sa_mask);
8346 
8347         sigaction(SIGUSR1, &act, NULL);
8348 
8349         /* control panel mask some signals when spawn qemu, need unmask here*/
8350         sigemptyset(&set);
8351         sigaddset(&set, SIGUSR1);
8352         sigaddset(&set, SIGTERM);
8353         if (sigprocmask(SIG_UNBLOCK, &set, NULL) == -1)
8354             fprintf(stderr, "unblock signal fail, possible issue for HVM save!\n");
8355 
8356     }
8357 
8358     main_loop();
8359     quit_timers();
8360     return 0;
8361 }