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