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