File:  [Qemu by Fabrice Bellard] / qemu / vl.c
Revision 1.1.1.16 (vendor branch): download - view: text, annotated - select for diffs
Tue Apr 24 18:06:10 2018 UTC (2 years, 1 month ago) by root
Branches: qemu, MAIN
CVS tags: qemu0125, qemu0124, HEAD
qemu 0.12.4

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

unix.superglobalmegacorp.com