Home | History | Annotate | Download | only in qemu
      1 /*
      2  * QEMU System Emulator
      3  *
      4  * Copyright (c) 2003-2008 Fabrice Bellard
      5  *
      6  * Permission is hereby granted, free of charge, to any person obtaining a copy
      7  * of this software and associated documentation files (the "Software"), to deal
      8  * in the Software without restriction, including without limitation the rights
      9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     10  * copies of the Software, and to permit persons to whom the Software is
     11  * furnished to do so, subject to the following conditions:
     12  *
     13  * The above copyright notice and this permission notice shall be included in
     14  * all copies or substantial portions of the Software.
     15  *
     16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     22  * THE SOFTWARE.
     23  */
     24 
     25 /* the following is needed on Linux to define ptsname() in stdlib.h */
     26 #if defined(__linux__)
     27 #define _GNU_SOURCE 1
     28 #endif
     29 
     30 #include "qemu-common.h"
     31 #include "hw/hw.h"
     32 #include "hw/boards.h"
     33 #include "hw/usb.h"
     34 #include "hw/pcmcia.h"
     35 #include "hw/pc.h"
     36 #include "hw/audiodev.h"
     37 #include "hw/isa.h"
     38 #include "hw/baum.h"
     39 #include "hw/goldfish_nand.h"
     40 #include "net.h"
     41 #include "console.h"
     42 #include "sysemu.h"
     43 #include "gdbstub.h"
     44 #include "qemu-timer.h"
     45 #include "qemu-char.h"
     46 #include "blockdev.h"
     47 #include "audio/audio.h"
     48 
     49 #include "qemu_file.h"
     50 #include "android/android.h"
     51 #include "charpipe.h"
     52 #include "modem_driver.h"
     53 #include "android/gps.h"
     54 #include "android/hw-kmsg.h"
     55 #include "android/hw-pipe-net.h"
     56 #include "android/hw-qemud.h"
     57 #include "android/camera/camera-service.h"
     58 #include "android/multitouch-port.h"
     59 #include "android/charmap.h"
     60 #include "android/globals.h"
     61 #include "android/utils/bufprint.h"
     62 #include "android/utils/debug.h"
     63 #include "android/utils/filelock.h"
     64 #include "android/utils/path.h"
     65 #include "android/utils/stralloc.h"
     66 #include "android/utils/tempfile.h"
     67 #include "android/display-core.h"
     68 #include "android/utils/timezone.h"
     69 #include "android/snapshot.h"
     70 #include "android/opengles.h"
     71 #include "android/multitouch-screen.h"
     72 #include "targphys.h"
     73 #include "tcpdump.h"
     74 
     75 #ifdef CONFIG_MEMCHECK
     76 #include "memcheck/memcheck.h"
     77 #endif  // CONFIG_MEMCHECK
     78 
     79 #include <unistd.h>
     80 #include <fcntl.h>
     81 #include <signal.h>
     82 #include <time.h>
     83 #include <errno.h>
     84 #include <sys/time.h>
     85 #include <zlib.h>
     86 
     87 /* Needed early for CONFIG_BSD etc. */
     88 #include "config-host.h"
     89 
     90 #ifndef _WIN32
     91 #include <libgen.h>
     92 #include <sys/times.h>
     93 #include <sys/wait.h>
     94 #include <termios.h>
     95 #include <sys/mman.h>
     96 #include <sys/ioctl.h>
     97 #include <sys/resource.h>
     98 #include <sys/socket.h>
     99 #include <netinet/in.h>
    100 #include <net/if.h>
    101 #if defined(__NetBSD__)
    102 #include <net/if_tap.h>
    103 #endif
    104 #ifdef __linux__
    105 #include <linux/if_tun.h>
    106 #endif
    107 #include <arpa/inet.h>
    108 #include <dirent.h>
    109 #include <netdb.h>
    110 #include <sys/select.h>
    111 #ifdef CONFIG_BSD
    112 #include <sys/stat.h>
    113 #if defined(__FreeBSD__) || defined(__DragonFly__)
    114 #include <libutil.h>
    115 #else
    116 #include <util.h>
    117 #endif
    118 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
    119 #include <freebsd/stdlib.h>
    120 #else
    121 #ifdef __linux__
    122 #include <pty.h>
    123 #include <malloc.h>
    124 #include <linux/rtc.h>
    125 
    126 /* For the benefit of older linux systems which don't supply it,
    127    we use a local copy of hpet.h. */
    128 /* #include <linux/hpet.h> */
    129 #include "hpet.h"
    130 
    131 #include <linux/ppdev.h>
    132 #include <linux/parport.h>
    133 #endif
    134 #ifdef __sun__
    135 #include <sys/stat.h>
    136 #include <sys/ethernet.h>
    137 #include <sys/sockio.h>
    138 #include <netinet/arp.h>
    139 #include <netinet/in.h>
    140 #include <netinet/in_systm.h>
    141 #include <netinet/ip.h>
    142 #include <netinet/ip_icmp.h> // must come after ip.h
    143 #include <netinet/udp.h>
    144 #include <netinet/tcp.h>
    145 #include <net/if.h>
    146 #include <syslog.h>
    147 #include <stropts.h>
    148 #endif
    149 #endif
    150 #endif
    151 
    152 #if defined(__OpenBSD__)
    153 #include <util.h>
    154 #endif
    155 
    156 #if defined(CONFIG_VDE)
    157 #include <libvdeplug.h>
    158 #endif
    159 
    160 #ifdef _WIN32
    161 #include <windows.h>
    162 #include <malloc.h>
    163 #include <sys/timeb.h>
    164 #include <mmsystem.h>
    165 #define getopt_long_only getopt_long
    166 #define memalign(align, size) malloc(size)
    167 #endif
    168 
    169 #include "cpus.h"
    170 #include "arch_init.h"
    171 
    172 #ifdef CONFIG_COCOA
    173 int qemu_main(int argc, char **argv, char **envp);
    174 #undef main
    175 #define main qemu_main
    176 #endif /* CONFIG_COCOA */
    177 
    178 #include "hw/hw.h"
    179 #include "hw/boards.h"
    180 #include "hw/usb.h"
    181 #include "hw/pcmcia.h"
    182 #include "hw/pc.h"
    183 #include "hw/isa.h"
    184 #include "hw/baum.h"
    185 #include "hw/bt.h"
    186 #include "hw/watchdog.h"
    187 #include "hw/smbios.h"
    188 #include "hw/xen.h"
    189 #include "bt-host.h"
    190 #include "net.h"
    191 #include "monitor.h"
    192 #include "console.h"
    193 #include "sysemu.h"
    194 #include "gdbstub.h"
    195 #include "qemu-timer.h"
    196 #include "qemu-char.h"
    197 #include "cache-utils.h"
    198 #include "block.h"
    199 #include "dma.h"
    200 #include "audio/audio.h"
    201 #include "migration.h"
    202 #include "kvm.h"
    203 #include "hax.h"
    204 #ifdef CONFIG_KVM
    205 #include "kvm-android.h"
    206 #endif
    207 #include "balloon.h"
    208 #include "android/hw-lcd.h"
    209 #include "android/boot-properties.h"
    210 #include "android/hw-control.h"
    211 #include "android/core-init-utils.h"
    212 #include "android/audio-test.h"
    213 
    214 #include "android/snaphost-android.h"
    215 
    216 #ifdef CONFIG_STANDALONE_CORE
    217 /* Verbose value used by the standalone emulator core (without UI) */
    218 unsigned long   android_verbose;
    219 #endif  // CONFIG_STANDALONE_CORE
    220 
    221 #if !defined(CONFIG_STANDALONE_CORE)
    222 /* in android/qemulator.c */
    223 extern void  android_emulator_set_base_port(int  port);
    224 #endif
    225 
    226 #if defined(CONFIG_SKINS) && !defined(CONFIG_STANDALONE_CORE)
    227 #undef main
    228 #define main qemu_main
    229 #endif
    230 
    231 #include "disas.h"
    232 
    233 #ifdef CONFIG_TRACE
    234 #include "android-trace.h"
    235 #endif
    236 
    237 #include "qemu_socket.h"
    238 
    239 #if defined(CONFIG_SLIRP)
    240 #include "libslirp.h"
    241 #endif
    242 
    243 #define DEFAULT_RAM_SIZE 128
    244 
    245 /* Max number of USB devices that can be specified on the commandline.  */
    246 #define MAX_USB_CMDLINE 8
    247 
    248 /* Max number of bluetooth switches on the commandline.  */
    249 #define MAX_BT_CMDLINE 10
    250 
    251 /* XXX: use a two level table to limit memory usage */
    252 
    253 static const char *data_dir;
    254 const char *bios_name = NULL;
    255 static void *ioport_opaque[MAX_IOPORTS];
    256 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
    257 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
    258 #ifdef MAX_DRIVES
    259 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
    260    to store the VM snapshots */
    261 DriveInfo drives_table[MAX_DRIVES+1];
    262 int nb_drives;
    263 #endif
    264 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
    265 DisplayType display_type = DT_DEFAULT;
    266 const char* keyboard_layout = NULL;
    267 int64_t ticks_per_sec;
    268 ram_addr_t ram_size;
    269 const char *mem_path = NULL;
    270 #ifdef MAP_POPULATE
    271 int mem_prealloc = 0; /* force preallocation of physical target memory */
    272 #endif
    273 int nb_nics;
    274 NICInfo nd_table[MAX_NICS];
    275 int vm_running;
    276 int autostart;
    277 static int rtc_utc = 1;
    278 static int rtc_date_offset = -1; /* -1 means no change */
    279 int cirrus_vga_enabled = 1;
    280 int std_vga_enabled = 0;
    281 int vmsvga_enabled = 0;
    282 int xenfb_enabled = 0;
    283 QEMUClock *rtc_clock;
    284 static int full_screen = 0;
    285 #ifdef CONFIG_SDL
    286 static int no_frame = 0;
    287 #endif
    288 int no_quit = 0;
    289 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
    290 int              serial_hds_count;
    291 
    292 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
    293 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
    294 #ifdef TARGET_I386
    295 int win2k_install_hack = 0;
    296 int rtc_td_hack = 0;
    297 #endif
    298 int usb_enabled = 0;
    299 int singlestep = 0;
    300 int smp_cpus = 1;
    301 const char *vnc_display;
    302 int acpi_enabled = 1;
    303 int no_hpet = 0;
    304 int hax_disabled = 0;
    305 int no_virtio_balloon = 0;
    306 int fd_bootchk = 1;
    307 int no_reboot = 0;
    308 int no_shutdown = 0;
    309 int cursor_hide = 1;
    310 int graphic_rotate = 0;
    311 WatchdogTimerModel *watchdog = NULL;
    312 int watchdog_action = WDT_RESET;
    313 const char *option_rom[MAX_OPTION_ROMS];
    314 int nb_option_roms;
    315 int semihosting_enabled = 0;
    316 #ifdef TARGET_ARM
    317 int old_param = 0;
    318 #endif
    319 const char *qemu_name;
    320 int alt_grab = 0;
    321 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
    322 unsigned int nb_prom_envs = 0;
    323 const char *prom_envs[MAX_PROM_ENVS];
    324 #endif
    325 #ifdef MAX_DRIVES
    326 int nb_drives_opt;
    327 struct drive_opt drives_opt[MAX_DRIVES];
    328 #endif
    329 int nb_numa_nodes;
    330 uint64_t node_mem[MAX_NODES];
    331 uint64_t node_cpumask[MAX_NODES];
    332 
    333 static QEMUTimer *nographic_timer;
    334 
    335 uint8_t qemu_uuid[16];
    336 
    337 
    338 int   qemu_cpu_delay;
    339 extern char* audio_input_source;
    340 
    341 extern char* android_op_ports;
    342 extern char* android_op_port;
    343 extern char* android_op_report_console;
    344 extern char* op_http_proxy;
    345 // Path to the file containing specific key character map.
    346 char* op_charmap_file = NULL;
    347 
    348 /* Path to hardware initialization file passed with -android-hw option. */
    349 char* android_op_hwini = NULL;
    350 
    351 /* Memory checker options. */
    352 char* android_op_memcheck = NULL;
    353 
    354 /* -dns-server option value. */
    355 char* android_op_dns_server = NULL;
    356 
    357 /* -radio option value. */
    358 char* android_op_radio = NULL;
    359 
    360 /* -gps option value. */
    361 char* android_op_gps = NULL;
    362 
    363 /* -audio option value. */
    364 char* android_op_audio = NULL;
    365 
    366 /* -cpu-delay option value. */
    367 char* android_op_cpu_delay = NULL;
    368 
    369 #ifdef CONFIG_NAND_LIMITS
    370 /* -nand-limits option value. */
    371 char* android_op_nand_limits = NULL;
    372 #endif  // CONFIG_NAND_LIMITS
    373 
    374 /* -netspeed option value. */
    375 char* android_op_netspeed = NULL;
    376 
    377 /* -netdelay option value. */
    378 char* android_op_netdelay = NULL;
    379 
    380 /* -netfast option value. */
    381 int android_op_netfast = 0;
    382 
    383 /* -tcpdump option value. */
    384 char* android_op_tcpdump = NULL;
    385 
    386 /* -lcd-density option value. */
    387 char* android_op_lcd_density = NULL;
    388 
    389 /* -ui-port option value. This port will be used to report the core
    390  * initialization completion.
    391  */
    392 char* android_op_ui_port = NULL;
    393 
    394 /* -ui-settings option value. This value will be passed to the UI when new UI
    395  * process is attaching to the core.
    396  */
    397 char* android_op_ui_settings = NULL;
    398 
    399 /* -android-avdname option value. */
    400 char* android_op_avd_name = "unknown";
    401 
    402 extern int android_display_width;
    403 extern int android_display_height;
    404 extern int android_display_bpp;
    405 
    406 extern void  dprint( const char* format, ... );
    407 
    408 const char* dns_log_filename = NULL;
    409 const char* drop_log_filename = NULL;
    410 static int rotate_logs_requested = 0;
    411 
    412 const char* savevm_on_exit = NULL;
    413 
    414 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
    415 
    416 /* Reports the core initialization failure to the error stdout and to the UI
    417  * socket before exiting the application.
    418  * Parameters that are passed to this macro are used to format the error
    419  * mesage using sprintf routine.
    420  */
    421 #ifdef CONFIG_ANDROID
    422 #define  PANIC(...) android_core_init_failure(__VA_ARGS__)
    423 #else
    424 #define  PANIC(...) do { fprintf(stderr, __VA_ARGS__);  \
    425                          exit(1);                       \
    426                     } while (0)
    427 #endif  // CONFIG_ANDROID
    428 
    429 /* Exits the core during initialization. */
    430 #ifdef CONFIG_ANDROID
    431 #define  QEMU_EXIT(exit_code) android_core_init_exit(exit_code)
    432 #else
    433 #define  QEMU_EXIT(exit_code) exit(exit_code)
    434 #endif  // CONFIG_ANDROID
    435 
    436 /***********************************************************/
    437 /* x86 ISA bus support */
    438 
    439 target_phys_addr_t isa_mem_base = 0;
    440 PicState2 *isa_pic;
    441 
    442 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
    443 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
    444 
    445 static uint32_t ioport_read(int index, uint32_t address)
    446 {
    447     static IOPortReadFunc *default_func[3] = {
    448         default_ioport_readb,
    449         default_ioport_readw,
    450         default_ioport_readl
    451     };
    452     IOPortReadFunc *func = ioport_read_table[index][address];
    453     if (!func)
    454         func = default_func[index];
    455     return func(ioport_opaque[address], address);
    456 }
    457 
    458 static void ioport_write(int index, uint32_t address, uint32_t data)
    459 {
    460     static IOPortWriteFunc *default_func[3] = {
    461         default_ioport_writeb,
    462         default_ioport_writew,
    463         default_ioport_writel
    464     };
    465     IOPortWriteFunc *func = ioport_write_table[index][address];
    466     if (!func)
    467         func = default_func[index];
    468     func(ioport_opaque[address], address, data);
    469 }
    470 
    471 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
    472 {
    473 #ifdef DEBUG_UNUSED_IOPORT
    474     fprintf(stderr, "unused inb: port=0x%04x\n", address);
    475 #endif
    476     return 0xff;
    477 }
    478 
    479 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
    480 {
    481 #ifdef DEBUG_UNUSED_IOPORT
    482     fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
    483 #endif
    484 }
    485 
    486 /* default is to make two byte accesses */
    487 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
    488 {
    489     uint32_t data;
    490     data = ioport_read(0, address);
    491     address = (address + 1) & (MAX_IOPORTS - 1);
    492     data |= ioport_read(0, address) << 8;
    493     return data;
    494 }
    495 
    496 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
    497 {
    498     ioport_write(0, address, data & 0xff);
    499     address = (address + 1) & (MAX_IOPORTS - 1);
    500     ioport_write(0, address, (data >> 8) & 0xff);
    501 }
    502 
    503 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
    504 {
    505 #ifdef DEBUG_UNUSED_IOPORT
    506     fprintf(stderr, "unused inl: port=0x%04x\n", address);
    507 #endif
    508     return 0xffffffff;
    509 }
    510 
    511 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
    512 {
    513 #ifdef DEBUG_UNUSED_IOPORT
    514     fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
    515 #endif
    516 }
    517 
    518 /*
    519  * Sets a flag (rotate_logs_requested) to clear both the DNS and the
    520  * drop logs upon receiving a SIGUSR1 signal. We need to clear the logs
    521  * between the tasks that do not require restarting Qemu.
    522  */
    523 void rotate_qemu_logs_handler(int signum) {
    524   rotate_logs_requested = 1;
    525 }
    526 
    527 /*
    528  * Resets the rotate_log_requested_flag. Normally called after qemu
    529  * logs has been rotated.
    530  */
    531 void reset_rotate_qemu_logs_request(void) {
    532   rotate_logs_requested = 0;
    533 }
    534 
    535 /*
    536  * Clears the passed qemu log when the rotate_logs_requested
    537  * is set. We need to clear the logs between the tasks that do not
    538  * require restarting Qemu.
    539  */
    540 FILE* rotate_qemu_log(FILE* old_log_fd, const char* filename) {
    541   FILE* new_log_fd = NULL;
    542   if (old_log_fd) {
    543     if (fclose(old_log_fd) == -1) {
    544       fprintf(stderr, "Cannot close old_log fd\n");
    545       exit(errno);
    546     }
    547   }
    548 
    549   if (!filename) {
    550     fprintf(stderr, "The log filename to be rotated is not provided");
    551     exit(-1);
    552   }
    553 
    554   new_log_fd = fopen(filename , "wb+");
    555   if (new_log_fd == NULL) {
    556     fprintf(stderr, "Cannot open the log file: %s for write.\n",
    557             filename);
    558     exit(1);
    559   }
    560 
    561   return new_log_fd;
    562 }
    563 
    564 /***************/
    565 /* ballooning */
    566 
    567 static QEMUBalloonEvent *qemu_balloon_event;
    568 void *qemu_balloon_event_opaque;
    569 
    570 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
    571 {
    572     qemu_balloon_event = func;
    573     qemu_balloon_event_opaque = opaque;
    574 }
    575 
    576 void qemu_balloon(ram_addr_t target)
    577 {
    578     if (qemu_balloon_event)
    579         qemu_balloon_event(qemu_balloon_event_opaque, target);
    580 }
    581 
    582 ram_addr_t qemu_balloon_status(void)
    583 {
    584     if (qemu_balloon_event)
    585         return qemu_balloon_event(qemu_balloon_event_opaque, 0);
    586     return 0;
    587 }
    588 
    589 /***********************************************************/
    590 /* host time/date access */
    591 void qemu_get_timedate(struct tm *tm, int offset)
    592 {
    593     time_t ti;
    594     struct tm *ret;
    595 
    596     time(&ti);
    597     ti += offset;
    598     if (rtc_date_offset == -1) {
    599         if (rtc_utc)
    600             ret = gmtime(&ti);
    601         else
    602             ret = localtime(&ti);
    603     } else {
    604         ti -= rtc_date_offset;
    605         ret = gmtime(&ti);
    606     }
    607 
    608     memcpy(tm, ret, sizeof(struct tm));
    609 }
    610 
    611 int qemu_timedate_diff(struct tm *tm)
    612 {
    613     time_t seconds;
    614 
    615     if (rtc_date_offset == -1)
    616         if (rtc_utc)
    617             seconds = mktimegm(tm);
    618         else
    619             seconds = mktime(tm);
    620     else
    621         seconds = mktimegm(tm) + rtc_date_offset;
    622 
    623     return seconds - time(NULL);
    624 }
    625 
    626 
    627 #ifdef CONFIG_TRACE
    628 int tbflush_requested;
    629 static int exit_requested;
    630 
    631 void start_tracing()
    632 {
    633   if (trace_filename == NULL)
    634     return;
    635   if (!tracing) {
    636     fprintf(stderr,"-- start tracing --\n");
    637     start_time = Now();
    638   }
    639   tracing = 1;
    640   tbflush_requested = 1;
    641   qemu_notify_event();
    642 }
    643 
    644 void stop_tracing()
    645 {
    646   if (trace_filename == NULL)
    647     return;
    648   if (tracing) {
    649     end_time = Now();
    650     elapsed_usecs += end_time - start_time;
    651     fprintf(stderr,"-- stop tracing --\n");
    652   }
    653   tracing = 0;
    654   tbflush_requested = 1;
    655   qemu_notify_event();
    656 }
    657 
    658 #ifndef _WIN32
    659 /* This is the handler for the SIGUSR1 and SIGUSR2 signals.
    660  * SIGUSR1 turns tracing on.  SIGUSR2 turns tracing off.
    661  */
    662 void sigusr_handler(int sig)
    663 {
    664   if (sig == SIGUSR1)
    665     start_tracing();
    666   else
    667     stop_tracing();
    668 }
    669 #endif
    670 
    671 /* This is the handler to catch control-C so that we can exit cleanly.
    672  * This is needed when tracing to flush the buffers to disk.
    673  */
    674 void sigint_handler(int sig)
    675 {
    676   exit_requested = 1;
    677   qemu_notify_event();
    678 }
    679 #endif /* CONFIG_TRACE */
    680 
    681 
    682 /***********************************************************/
    683 /* Bluetooth support */
    684 static int nb_hcis;
    685 static int cur_hci;
    686 static struct HCIInfo *hci_table[MAX_NICS];
    687 
    688 static struct bt_vlan_s {
    689     struct bt_scatternet_s net;
    690     int id;
    691     struct bt_vlan_s *next;
    692 } *first_bt_vlan;
    693 
    694 /* find or alloc a new bluetooth "VLAN" */
    695 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
    696 {
    697     struct bt_vlan_s **pvlan, *vlan;
    698     for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
    699         if (vlan->id == id)
    700             return &vlan->net;
    701     }
    702     vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
    703     vlan->id = id;
    704     pvlan = &first_bt_vlan;
    705     while (*pvlan != NULL)
    706         pvlan = &(*pvlan)->next;
    707     *pvlan = vlan;
    708     return &vlan->net;
    709 }
    710 
    711 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
    712 {
    713 }
    714 
    715 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
    716 {
    717     return -ENOTSUP;
    718 }
    719 
    720 static struct HCIInfo null_hci = {
    721     .cmd_send = null_hci_send,
    722     .sco_send = null_hci_send,
    723     .acl_send = null_hci_send,
    724     .bdaddr_set = null_hci_addr_set,
    725 };
    726 
    727 struct HCIInfo *qemu_next_hci(void)
    728 {
    729     if (cur_hci == nb_hcis)
    730         return &null_hci;
    731 
    732     return hci_table[cur_hci++];
    733 }
    734 
    735 static struct HCIInfo *hci_init(const char *str)
    736 {
    737     char *endp;
    738     struct bt_scatternet_s *vlan = 0;
    739 
    740     if (!strcmp(str, "null"))
    741         /* null */
    742         return &null_hci;
    743     else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
    744         /* host[:hciN] */
    745         return bt_host_hci(str[4] ? str + 5 : "hci0");
    746     else if (!strncmp(str, "hci", 3)) {
    747         /* hci[,vlan=n] */
    748         if (str[3]) {
    749             if (!strncmp(str + 3, ",vlan=", 6)) {
    750                 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
    751                 if (*endp)
    752                     vlan = 0;
    753             }
    754         } else
    755             vlan = qemu_find_bt_vlan(0);
    756         if (vlan)
    757            return bt_new_hci(vlan);
    758     }
    759 
    760     fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
    761 
    762     return 0;
    763 }
    764 
    765 static int bt_hci_parse(const char *str)
    766 {
    767     struct HCIInfo *hci;
    768     bdaddr_t bdaddr;
    769 
    770     if (nb_hcis >= MAX_NICS) {
    771         fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
    772         return -1;
    773     }
    774 
    775     hci = hci_init(str);
    776     if (!hci)
    777         return -1;
    778 
    779     bdaddr.b[0] = 0x52;
    780     bdaddr.b[1] = 0x54;
    781     bdaddr.b[2] = 0x00;
    782     bdaddr.b[3] = 0x12;
    783     bdaddr.b[4] = 0x34;
    784     bdaddr.b[5] = 0x56 + nb_hcis;
    785     hci->bdaddr_set(hci, bdaddr.b);
    786 
    787     hci_table[nb_hcis++] = hci;
    788 
    789     return 0;
    790 }
    791 
    792 static void bt_vhci_add(int vlan_id)
    793 {
    794     struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
    795 
    796     if (!vlan->slave)
    797         fprintf(stderr, "qemu: warning: adding a VHCI to "
    798                         "an empty scatternet %i\n", vlan_id);
    799 
    800     bt_vhci_init(bt_new_hci(vlan));
    801 }
    802 
    803 static struct bt_device_s *bt_device_add(const char *opt)
    804 {
    805     struct bt_scatternet_s *vlan;
    806     int vlan_id = 0;
    807     char *endp = strstr(opt, ",vlan=");
    808     int len = (endp ? endp - opt : strlen(opt)) + 1;
    809     char devname[10];
    810 
    811     pstrcpy(devname, MIN(sizeof(devname), len), opt);
    812 
    813     if (endp) {
    814         vlan_id = strtol(endp + 6, &endp, 0);
    815         if (*endp) {
    816             fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
    817             return 0;
    818         }
    819     }
    820 
    821     vlan = qemu_find_bt_vlan(vlan_id);
    822 
    823     if (!vlan->slave)
    824         fprintf(stderr, "qemu: warning: adding a slave device to "
    825                         "an empty scatternet %i\n", vlan_id);
    826 
    827     if (!strcmp(devname, "keyboard"))
    828         return bt_keyboard_init(vlan);
    829 
    830     fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
    831     return 0;
    832 }
    833 
    834 static int bt_parse(const char *opt)
    835 {
    836     const char *endp, *p;
    837     int vlan;
    838 
    839     if (strstart(opt, "hci", &endp)) {
    840         if (!*endp || *endp == ',') {
    841             if (*endp)
    842                 if (!strstart(endp, ",vlan=", 0))
    843                     opt = endp + 1;
    844 
    845             return bt_hci_parse(opt);
    846        }
    847     } else if (strstart(opt, "vhci", &endp)) {
    848         if (!*endp || *endp == ',') {
    849             if (*endp) {
    850                 if (strstart(endp, ",vlan=", &p)) {
    851                     vlan = strtol(p, (char **) &endp, 0);
    852                     if (*endp) {
    853                         fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
    854                         return 1;
    855                     }
    856                 } else {
    857                     fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
    858                     return 1;
    859                 }
    860             } else
    861                 vlan = 0;
    862 
    863             bt_vhci_add(vlan);
    864             return 0;
    865         }
    866     } else if (strstart(opt, "device:", &endp))
    867         return !bt_device_add(endp);
    868 
    869     fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
    870     return 1;
    871 }
    872 
    873 /***********************************************************/
    874 /* QEMU Block devices */
    875 
    876 #define HD_ALIAS "index=%d,media=disk"
    877 #define CDROM_ALIAS "index=2,media=cdrom"
    878 #define FD_ALIAS "index=%d,if=floppy"
    879 #define PFLASH_ALIAS "if=pflash"
    880 #define MTD_ALIAS "if=mtd"
    881 #define SD_ALIAS "index=0,if=sd"
    882 
    883 static int drive_init_func(QemuOpts *opts, void *opaque)
    884 {
    885     int *use_scsi = opaque;
    886     int fatal_error = 0;
    887 
    888     if (drive_init(opts, *use_scsi, &fatal_error) == NULL) {
    889         if (fatal_error)
    890             return 1;
    891     }
    892     return 0;
    893 }
    894 
    895 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
    896 {
    897     if (NULL == qemu_opt_get(opts, "snapshot")) {
    898         qemu_opt_set(opts, "snapshot", "on");
    899     }
    900     return 0;
    901 }
    902 
    903 #ifdef MAX_DRIVES
    904 static int drive_opt_get_free_idx(void)
    905 {
    906     int index;
    907 
    908     for (index = 0; index < MAX_DRIVES; index++)
    909         if (!drives_opt[index].used) {
    910             drives_opt[index].used = 1;
    911             return index;
    912         }
    913 
    914     return -1;
    915 }
    916 
    917 static int drive_get_free_idx(void)
    918 {
    919     int index;
    920 
    921     for (index = 0; index < MAX_DRIVES; index++)
    922         if (!drives_table[index].used) {
    923             drives_table[index].used = 1;
    924             return index;
    925         }
    926 
    927     return -1;
    928 }
    929 
    930 int drive_add(const char *file, const char *fmt, ...)
    931 {
    932     va_list ap;
    933     int index = drive_opt_get_free_idx();
    934 
    935     if (nb_drives_opt >= MAX_DRIVES || index == -1) {
    936         fprintf(stderr, "qemu: too many drives\n");
    937         return -1;
    938     }
    939 
    940     drives_opt[index].file = file;
    941     va_start(ap, fmt);
    942     vsnprintf(drives_opt[index].opt,
    943               sizeof(drives_opt[0].opt), fmt, ap);
    944     va_end(ap);
    945 
    946     nb_drives_opt++;
    947     return index;
    948 }
    949 
    950 void drive_remove(int index)
    951 {
    952     drives_opt[index].used = 0;
    953     nb_drives_opt--;
    954 }
    955 
    956 int drive_get_index(BlockInterfaceType type, int bus, int unit)
    957 {
    958     int index;
    959 
    960     /* seek interface, bus and unit */
    961 
    962     for (index = 0; index < MAX_DRIVES; index++)
    963         if (drives_table[index].type == type &&
    964 	    drives_table[index].bus == bus &&
    965 	    drives_table[index].unit == unit &&
    966 	    drives_table[index].used)
    967         return index;
    968 
    969     return -1;
    970 }
    971 
    972 int drive_get_max_bus(BlockInterfaceType type)
    973 {
    974     int max_bus;
    975     int index;
    976 
    977     max_bus = -1;
    978     for (index = 0; index < nb_drives; index++) {
    979         if(drives_table[index].type == type &&
    980            drives_table[index].bus > max_bus)
    981             max_bus = drives_table[index].bus;
    982     }
    983     return max_bus;
    984 }
    985 
    986 const char *drive_get_serial(BlockDriverState *bdrv)
    987 {
    988     int index;
    989 
    990     for (index = 0; index < nb_drives; index++)
    991         if (drives_table[index].bdrv == bdrv)
    992             return drives_table[index].serial;
    993 
    994     return "\0";
    995 }
    996 
    997 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
    998 {
    999     int index;
   1000 
   1001     for (index = 0; index < nb_drives; index++)
   1002         if (drives_table[index].bdrv == bdrv)
   1003             return drives_table[index].onerror;
   1004 
   1005     return BLOCK_ERR_STOP_ENOSPC;
   1006 }
   1007 
   1008 static void bdrv_format_print(void *opaque, const char *name)
   1009 {
   1010     fprintf(stderr, " %s", name);
   1011 }
   1012 
   1013 void drive_uninit(BlockDriverState *bdrv)
   1014 {
   1015     int i;
   1016 
   1017     for (i = 0; i < MAX_DRIVES; i++)
   1018         if (drives_table[i].bdrv == bdrv) {
   1019             drives_table[i].bdrv = NULL;
   1020             drives_table[i].used = 0;
   1021             drive_remove(drives_table[i].drive_opt_idx);
   1022             nb_drives--;
   1023             break;
   1024         }
   1025 }
   1026 
   1027 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
   1028 {
   1029     char buf[128];
   1030     char file[1024];
   1031     char devname[128];
   1032     char serial[21];
   1033     const char *mediastr = "";
   1034     BlockInterfaceType type;
   1035     enum { MEDIA_DISK, MEDIA_CDROM } media;
   1036     int bus_id, unit_id;
   1037     int cyls, heads, secs, translation;
   1038     BlockDriverState *bdrv;
   1039     BlockDriver *drv = NULL;
   1040     QEMUMachine *machine = opaque;
   1041     int max_devs;
   1042     int index;
   1043     int cache;
   1044     int bdrv_flags, onerror;
   1045     int drives_table_idx;
   1046     char *str = arg->opt;
   1047     static const char * const params[] = { "bus", "unit", "if", "index",
   1048                                            "cyls", "heads", "secs", "trans",
   1049                                            "media", "snapshot", "file",
   1050                                            "cache", "format", "serial", "werror",
   1051                                            NULL };
   1052 
   1053     if (check_params(buf, sizeof(buf), params, str) < 0) {
   1054          fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
   1055                          buf, str);
   1056          return -1;
   1057     }
   1058 
   1059     file[0] = 0;
   1060     cyls = heads = secs = 0;
   1061     bus_id = 0;
   1062     unit_id = -1;
   1063     translation = BIOS_ATA_TRANSLATION_AUTO;
   1064     index = -1;
   1065     cache = 3;
   1066 
   1067     if (machine->use_scsi) {
   1068         type = IF_SCSI;
   1069         max_devs = MAX_SCSI_DEVS;
   1070         pstrcpy(devname, sizeof(devname), "scsi");
   1071     } else {
   1072         type = IF_IDE;
   1073         max_devs = MAX_IDE_DEVS;
   1074         pstrcpy(devname, sizeof(devname), "ide");
   1075     }
   1076     media = MEDIA_DISK;
   1077 
   1078     /* extract parameters */
   1079 
   1080     if (get_param_value(buf, sizeof(buf), "bus", str)) {
   1081         bus_id = strtol(buf, NULL, 0);
   1082 	if (bus_id < 0) {
   1083 	    fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
   1084 	    return -1;
   1085 	}
   1086     }
   1087 
   1088     if (get_param_value(buf, sizeof(buf), "unit", str)) {
   1089         unit_id = strtol(buf, NULL, 0);
   1090 	if (unit_id < 0) {
   1091 	    fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
   1092 	    return -1;
   1093 	}
   1094     }
   1095 
   1096     if (get_param_value(buf, sizeof(buf), "if", str)) {
   1097         pstrcpy(devname, sizeof(devname), buf);
   1098         if (!strcmp(buf, "ide")) {
   1099 	    type = IF_IDE;
   1100             max_devs = MAX_IDE_DEVS;
   1101         } else if (!strcmp(buf, "scsi")) {
   1102 	    type = IF_SCSI;
   1103             max_devs = MAX_SCSI_DEVS;
   1104         } else if (!strcmp(buf, "floppy")) {
   1105 	    type = IF_FLOPPY;
   1106             max_devs = 0;
   1107         } else if (!strcmp(buf, "pflash")) {
   1108 	    type = IF_PFLASH;
   1109             max_devs = 0;
   1110 	} else if (!strcmp(buf, "mtd")) {
   1111 	    type = IF_MTD;
   1112             max_devs = 0;
   1113 	} else if (!strcmp(buf, "sd")) {
   1114 	    type = IF_SD;
   1115             max_devs = 0;
   1116         } else if (!strcmp(buf, "virtio")) {
   1117             type = IF_VIRTIO;
   1118             max_devs = 0;
   1119 	} else if (!strcmp(buf, "xen")) {
   1120 	    type = IF_XEN;
   1121             max_devs = 0;
   1122 	} else {
   1123             fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
   1124             return -1;
   1125 	}
   1126     }
   1127 
   1128     if (get_param_value(buf, sizeof(buf), "index", str)) {
   1129         index = strtol(buf, NULL, 0);
   1130 	if (index < 0) {
   1131 	    fprintf(stderr, "qemu: '%s' invalid index\n", str);
   1132 	    return -1;
   1133 	}
   1134     }
   1135 
   1136     if (get_param_value(buf, sizeof(buf), "cyls", str)) {
   1137         cyls = strtol(buf, NULL, 0);
   1138     }
   1139 
   1140     if (get_param_value(buf, sizeof(buf), "heads", str)) {
   1141         heads = strtol(buf, NULL, 0);
   1142     }
   1143 
   1144     if (get_param_value(buf, sizeof(buf), "secs", str)) {
   1145         secs = strtol(buf, NULL, 0);
   1146     }
   1147 
   1148     if (cyls || heads || secs) {
   1149         if (cyls < 1 || cyls > 16383) {
   1150             fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
   1151 	    return -1;
   1152 	}
   1153         if (heads < 1 || heads > 16) {
   1154             fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
   1155 	    return -1;
   1156 	}
   1157         if (secs < 1 || secs > 63) {
   1158             fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
   1159 	    return -1;
   1160 	}
   1161     }
   1162 
   1163     if (get_param_value(buf, sizeof(buf), "trans", str)) {
   1164         if (!cyls) {
   1165             fprintf(stderr,
   1166                     "qemu: '%s' trans must be used with cyls,heads and secs\n",
   1167                     str);
   1168             return -1;
   1169         }
   1170         if (!strcmp(buf, "none"))
   1171             translation = BIOS_ATA_TRANSLATION_NONE;
   1172         else if (!strcmp(buf, "lba"))
   1173             translation = BIOS_ATA_TRANSLATION_LBA;
   1174         else if (!strcmp(buf, "auto"))
   1175             translation = BIOS_ATA_TRANSLATION_AUTO;
   1176 	else {
   1177             fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
   1178 	    return -1;
   1179 	}
   1180     }
   1181 
   1182     if (get_param_value(buf, sizeof(buf), "media", str)) {
   1183         if (!strcmp(buf, "disk")) {
   1184 	    media = MEDIA_DISK;
   1185 	} else if (!strcmp(buf, "cdrom")) {
   1186             if (cyls || secs || heads) {
   1187                 fprintf(stderr,
   1188                         "qemu: '%s' invalid physical CHS format\n", str);
   1189 	        return -1;
   1190             }
   1191 	    media = MEDIA_CDROM;
   1192 	} else {
   1193 	    fprintf(stderr, "qemu: '%s' invalid media\n", str);
   1194 	    return -1;
   1195 	}
   1196     }
   1197 
   1198     if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
   1199         if (!strcmp(buf, "on"))
   1200 	    snapshot = 1;
   1201         else if (!strcmp(buf, "off"))
   1202 	    snapshot = 0;
   1203 	else {
   1204 	    fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
   1205 	    return -1;
   1206 	}
   1207     }
   1208 
   1209     if (get_param_value(buf, sizeof(buf), "cache", str)) {
   1210         if (!strcmp(buf, "off") || !strcmp(buf, "none"))
   1211             cache = 0;
   1212         else if (!strcmp(buf, "writethrough"))
   1213             cache = 1;
   1214         else if (!strcmp(buf, "writeback"))
   1215             cache = 2;
   1216         else {
   1217            fprintf(stderr, "qemu: invalid cache option\n");
   1218            return -1;
   1219         }
   1220     }
   1221 
   1222     if (get_param_value(buf, sizeof(buf), "format", str)) {
   1223        if (strcmp(buf, "?") == 0) {
   1224             fprintf(stderr, "qemu: Supported formats:");
   1225             bdrv_iterate_format(bdrv_format_print, NULL);
   1226             fprintf(stderr, "\n");
   1227 	    return -1;
   1228         }
   1229         drv = bdrv_find_format(buf);
   1230         if (!drv) {
   1231             fprintf(stderr, "qemu: '%s' invalid format\n", buf);
   1232             return -1;
   1233         }
   1234     }
   1235 
   1236     if (arg->file == NULL)
   1237         get_param_value(file, sizeof(file), "file", str);
   1238     else
   1239         pstrcpy(file, sizeof(file), arg->file);
   1240 
   1241     if (!get_param_value(serial, sizeof(serial), "serial", str))
   1242 	    memset(serial, 0,  sizeof(serial));
   1243 
   1244     onerror = BLOCK_ERR_STOP_ENOSPC;
   1245     if (get_param_value(buf, sizeof(serial), "werror", str)) {
   1246         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
   1247             fprintf(stderr, "werror is no supported by this format\n");
   1248             return -1;
   1249         }
   1250         if (!strcmp(buf, "ignore"))
   1251             onerror = BLOCK_ERR_IGNORE;
   1252         else if (!strcmp(buf, "enospc"))
   1253             onerror = BLOCK_ERR_STOP_ENOSPC;
   1254         else if (!strcmp(buf, "stop"))
   1255             onerror = BLOCK_ERR_STOP_ANY;
   1256         else if (!strcmp(buf, "report"))
   1257             onerror = BLOCK_ERR_REPORT;
   1258         else {
   1259             fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
   1260             return -1;
   1261         }
   1262     }
   1263 
   1264     /* compute bus and unit according index */
   1265 
   1266     if (index != -1) {
   1267         if (bus_id != 0 || unit_id != -1) {
   1268             fprintf(stderr,
   1269                     "qemu: '%s' index cannot be used with bus and unit\n", str);
   1270             return -1;
   1271         }
   1272         if (max_devs == 0)
   1273         {
   1274             unit_id = index;
   1275             bus_id = 0;
   1276         } else {
   1277             unit_id = index % max_devs;
   1278             bus_id = index / max_devs;
   1279         }
   1280     }
   1281 
   1282     /* if user doesn't specify a unit_id,
   1283      * try to find the first free
   1284      */
   1285 
   1286     if (unit_id == -1) {
   1287        unit_id = 0;
   1288        while (drive_get_index(type, bus_id, unit_id) != -1) {
   1289            unit_id++;
   1290            if (max_devs && unit_id >= max_devs) {
   1291                unit_id -= max_devs;
   1292                bus_id++;
   1293            }
   1294        }
   1295     }
   1296 
   1297     /* check unit id */
   1298 
   1299     if (max_devs && unit_id >= max_devs) {
   1300         fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
   1301                         str, unit_id, max_devs - 1);
   1302         return -1;
   1303     }
   1304 
   1305     /*
   1306      * ignore multiple definitions
   1307      */
   1308 
   1309     if (drive_get_index(type, bus_id, unit_id) != -1)
   1310         return -2;
   1311 
   1312     /* init */
   1313 
   1314     if (type == IF_IDE || type == IF_SCSI)
   1315         mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
   1316     if (max_devs)
   1317         snprintf(buf, sizeof(buf), "%s%i%s%i",
   1318                  devname, bus_id, mediastr, unit_id);
   1319     else
   1320         snprintf(buf, sizeof(buf), "%s%s%i",
   1321                  devname, mediastr, unit_id);
   1322     bdrv = bdrv_new(buf);
   1323     drives_table_idx = drive_get_free_idx();
   1324     drives_table[drives_table_idx].bdrv = bdrv;
   1325     drives_table[drives_table_idx].type = type;
   1326     drives_table[drives_table_idx].bus = bus_id;
   1327     drives_table[drives_table_idx].unit = unit_id;
   1328     drives_table[drives_table_idx].onerror = onerror;
   1329     drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
   1330     strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
   1331     nb_drives++;
   1332 
   1333     switch(type) {
   1334     case IF_IDE:
   1335     case IF_SCSI:
   1336     case IF_XEN:
   1337         switch(media) {
   1338 	case MEDIA_DISK:
   1339             if (cyls != 0) {
   1340                 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
   1341                 bdrv_set_translation_hint(bdrv, translation);
   1342             }
   1343 	    break;
   1344 	case MEDIA_CDROM:
   1345             bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
   1346 	    break;
   1347 	}
   1348         break;
   1349     case IF_SD:
   1350         /* FIXME: This isn't really a floppy, but it's a reasonable
   1351            approximation.  */
   1352     case IF_FLOPPY:
   1353         bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
   1354         break;
   1355     case IF_PFLASH:
   1356     case IF_MTD:
   1357     case IF_VIRTIO:
   1358         break;
   1359     case IF_COUNT:
   1360     case IF_NONE:
   1361         abort();
   1362     }
   1363     if (!file[0])
   1364         return -2;
   1365     bdrv_flags = 0;
   1366     if (snapshot) {
   1367         bdrv_flags |= BDRV_O_SNAPSHOT;
   1368         cache = 2; /* always use write-back with snapshot */
   1369     }
   1370     if (cache == 0) /* no caching */
   1371         bdrv_flags |= BDRV_O_NOCACHE;
   1372     else if (cache == 2) /* write-back */
   1373         bdrv_flags |= BDRV_O_CACHE_WB;
   1374     else if (cache == 3) /* not specified */
   1375         bdrv_flags |= BDRV_O_CACHE_DEF;
   1376     if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
   1377         fprintf(stderr, "qemu: could not open disk image %s\n",
   1378                         file);
   1379         return -1;
   1380     }
   1381     if (bdrv_key_required(bdrv))
   1382         autostart = 0;
   1383     return drives_table_idx;
   1384 }
   1385 #endif /* MAX_DRIVES */
   1386 
   1387 static void numa_add(const char *optarg)
   1388 {
   1389     char option[128];
   1390     char *endptr;
   1391     unsigned long long value, endvalue;
   1392     int nodenr;
   1393 
   1394     optarg = get_opt_name(option, 128, optarg, ',') + 1;
   1395     if (!strcmp(option, "node")) {
   1396         if (get_param_value(option, 128, "nodeid", optarg) == 0) {
   1397             nodenr = nb_numa_nodes;
   1398         } else {
   1399             nodenr = strtoull(option, NULL, 10);
   1400         }
   1401 
   1402         if (get_param_value(option, 128, "mem", optarg) == 0) {
   1403             node_mem[nodenr] = 0;
   1404         } else {
   1405             value = strtoull(option, &endptr, 0);
   1406             switch (*endptr) {
   1407             case 0: case 'M': case 'm':
   1408                 value <<= 20;
   1409                 break;
   1410             case 'G': case 'g':
   1411                 value <<= 30;
   1412                 break;
   1413             }
   1414             node_mem[nodenr] = value;
   1415         }
   1416         if (get_param_value(option, 128, "cpus", optarg) == 0) {
   1417             node_cpumask[nodenr] = 0;
   1418         } else {
   1419             value = strtoull(option, &endptr, 10);
   1420             if (value >= 64) {
   1421                 value = 63;
   1422                 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
   1423             } else {
   1424                 if (*endptr == '-') {
   1425                     endvalue = strtoull(endptr+1, &endptr, 10);
   1426                     if (endvalue >= 63) {
   1427                         endvalue = 62;
   1428                         fprintf(stderr,
   1429                             "only 63 CPUs in NUMA mode supported.\n");
   1430                     }
   1431                     value = (1 << (endvalue + 1)) - (1 << value);
   1432                 } else {
   1433                     value = 1 << value;
   1434                 }
   1435             }
   1436             node_cpumask[nodenr] = value;
   1437         }
   1438         nb_numa_nodes++;
   1439     }
   1440     return;
   1441 }
   1442 
   1443 /***********************************************************/
   1444 /* USB devices */
   1445 
   1446 static USBPort *used_usb_ports;
   1447 static USBPort *free_usb_ports;
   1448 
   1449 /* ??? Maybe change this to register a hub to keep track of the topology.  */
   1450 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
   1451                             usb_attachfn attach)
   1452 {
   1453     port->opaque = opaque;
   1454     port->index = index;
   1455     port->attach = attach;
   1456     port->next = free_usb_ports;
   1457     free_usb_ports = port;
   1458 }
   1459 
   1460 int usb_device_add_dev(USBDevice *dev)
   1461 {
   1462     USBPort *port;
   1463 
   1464     /* Find a USB port to add the device to.  */
   1465     port = free_usb_ports;
   1466     if (!port){
   1467         USBDevice *hub = usb_hub_init(VM_USB_HUB_SIZE);
   1468         port = free_usb_ports;
   1469         usb_attach(port, hub);
   1470     }
   1471     else if (!port->next){
   1472         USBDevice *hub;
   1473 
   1474         /* Create a new hub and chain it on.  */
   1475         free_usb_ports = NULL;
   1476         port->next = used_usb_ports;
   1477         used_usb_ports = port;
   1478 
   1479         hub = usb_hub_init(VM_USB_HUB_SIZE);
   1480         usb_attach(port, hub);
   1481         port = free_usb_ports;
   1482     }
   1483 
   1484     free_usb_ports = port->next;
   1485     port->next = used_usb_ports;
   1486     used_usb_ports = port;
   1487     usb_attach(port, dev);
   1488     return 0;
   1489 }
   1490 
   1491 #if 0
   1492 static void usb_msd_password_cb(void *opaque, int err)
   1493 {
   1494     USBDevice *dev = opaque;
   1495 
   1496     if (!err)
   1497         usb_device_add_dev(dev);
   1498     else
   1499         dev->handle_destroy(dev);
   1500 }
   1501 #endif
   1502 
   1503 static int usb_device_add(const char *devname, int is_hotplug)
   1504 {
   1505     const char *p;
   1506     USBDevice *dev;
   1507 
   1508     if (strstart(devname, "host:", &p)) {
   1509         dev = usb_host_device_open(p);
   1510     } else if (!strcmp(devname, "mouse")) {
   1511         dev = usb_mouse_init();
   1512     } else if (!strcmp(devname, "tablet")) {
   1513         dev = usb_tablet_init();
   1514     } else if (!strcmp(devname, "keyboard")) {
   1515         dev = usb_keyboard_init();
   1516     } else if (strstart(devname, "disk:", &p)) {
   1517 #if 0
   1518         BlockDriverState *bs;
   1519 #endif
   1520         dev = usb_msd_init(p);
   1521         if (!dev)
   1522             return -1;
   1523 #if 0
   1524         bs = usb_msd_get_bdrv(dev);
   1525         if (bdrv_key_required(bs)) {
   1526             autostart = 0;
   1527             if (is_hotplug) {
   1528                 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
   1529                                             dev);
   1530                 return 0;
   1531             }
   1532         }
   1533     } else if (!strcmp(devname, "wacom-tablet")) {
   1534         dev = usb_wacom_init();
   1535     } else if (strstart(devname, "serial:", &p)) {
   1536         dev = usb_serial_init(p);
   1537 #ifdef CONFIG_BRLAPI
   1538     } else if (!strcmp(devname, "braille")) {
   1539         dev = usb_baum_init();
   1540 #endif
   1541     } else if (strstart(devname, "net:", &p)) {
   1542         int nic = nb_nics;
   1543 
   1544         if (net_client_init("nic", p) < 0)
   1545             return -1;
   1546         nd_table[nic].model = "usb";
   1547         dev = usb_net_init(&nd_table[nic]);
   1548     } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
   1549         dev = usb_bt_init(devname[2] ? hci_init(p) :
   1550                         bt_new_hci(qemu_find_bt_vlan(0)));
   1551 #endif
   1552     } else {
   1553         return -1;
   1554     }
   1555     if (!dev)
   1556         return -1;
   1557 
   1558     return usb_device_add_dev(dev);
   1559 }
   1560 
   1561 int usb_device_del_addr(int bus_num, int addr)
   1562 {
   1563     USBPort *port;
   1564     USBPort **lastp;
   1565     USBDevice *dev;
   1566 
   1567     if (!used_usb_ports)
   1568         return -1;
   1569 
   1570     if (bus_num != 0)
   1571         return -1;
   1572 
   1573     lastp = &used_usb_ports;
   1574     port = used_usb_ports;
   1575     while (port && port->dev->addr != addr) {
   1576         lastp = &port->next;
   1577         port = port->next;
   1578     }
   1579 
   1580     if (!port)
   1581         return -1;
   1582 
   1583     dev = port->dev;
   1584     *lastp = port->next;
   1585     usb_attach(port, NULL);
   1586     dev->handle_destroy(dev);
   1587     port->next = free_usb_ports;
   1588     free_usb_ports = port;
   1589     return 0;
   1590 }
   1591 
   1592 static int usb_device_del(const char *devname)
   1593 {
   1594     int bus_num, addr;
   1595     const char *p;
   1596 
   1597     if (strstart(devname, "host:", &p))
   1598         return usb_host_device_close(p);
   1599 
   1600     if (!used_usb_ports)
   1601         return -1;
   1602 
   1603     p = strchr(devname, '.');
   1604     if (!p)
   1605         return -1;
   1606     bus_num = strtoul(devname, NULL, 0);
   1607     addr = strtoul(p + 1, NULL, 0);
   1608 
   1609     return usb_device_del_addr(bus_num, addr);
   1610 }
   1611 
   1612 void do_usb_add(Monitor *mon, const char *devname)
   1613 {
   1614     usb_device_add(devname, 1);
   1615 }
   1616 
   1617 void do_usb_del(Monitor *mon, const char *devname)
   1618 {
   1619     usb_device_del(devname);
   1620 }
   1621 
   1622 void usb_info(Monitor *mon)
   1623 {
   1624     USBDevice *dev;
   1625     USBPort *port;
   1626     const char *speed_str;
   1627 
   1628     if (!usb_enabled) {
   1629         monitor_printf(mon, "USB support not enabled\n");
   1630         return;
   1631     }
   1632 
   1633     for (port = used_usb_ports; port; port = port->next) {
   1634         dev = port->dev;
   1635         if (!dev)
   1636             continue;
   1637         switch(dev->speed) {
   1638         case USB_SPEED_LOW:
   1639             speed_str = "1.5";
   1640             break;
   1641         case USB_SPEED_FULL:
   1642             speed_str = "12";
   1643             break;
   1644         case USB_SPEED_HIGH:
   1645             speed_str = "480";
   1646             break;
   1647         default:
   1648             speed_str = "?";
   1649             break;
   1650         }
   1651         monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
   1652                        0, dev->addr, speed_str, dev->devname);
   1653     }
   1654 }
   1655 
   1656 /***********************************************************/
   1657 /* PCMCIA/Cardbus */
   1658 
   1659 static struct pcmcia_socket_entry_s {
   1660     PCMCIASocket *socket;
   1661     struct pcmcia_socket_entry_s *next;
   1662 } *pcmcia_sockets = 0;
   1663 
   1664 void pcmcia_socket_register(PCMCIASocket *socket)
   1665 {
   1666     struct pcmcia_socket_entry_s *entry;
   1667 
   1668     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
   1669     entry->socket = socket;
   1670     entry->next = pcmcia_sockets;
   1671     pcmcia_sockets = entry;
   1672 }
   1673 
   1674 void pcmcia_socket_unregister(PCMCIASocket *socket)
   1675 {
   1676     struct pcmcia_socket_entry_s *entry, **ptr;
   1677 
   1678     ptr = &pcmcia_sockets;
   1679     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
   1680         if (entry->socket == socket) {
   1681             *ptr = entry->next;
   1682             qemu_free(entry);
   1683         }
   1684 }
   1685 
   1686 void pcmcia_info(Monitor *mon)
   1687 {
   1688     struct pcmcia_socket_entry_s *iter;
   1689 
   1690     if (!pcmcia_sockets)
   1691         monitor_printf(mon, "No PCMCIA sockets\n");
   1692 
   1693     for (iter = pcmcia_sockets; iter; iter = iter->next)
   1694         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
   1695                        iter->socket->attached ? iter->socket->card_string :
   1696                        "Empty");
   1697 }
   1698 
   1699 /***********************************************************/
   1700 /* machine registration */
   1701 
   1702 static QEMUMachine *first_machine = NULL;
   1703 QEMUMachine *current_machine = NULL;
   1704 
   1705 int qemu_register_machine(QEMUMachine *m)
   1706 {
   1707     QEMUMachine **pm;
   1708     pm = &first_machine;
   1709     while (*pm != NULL)
   1710         pm = &(*pm)->next;
   1711     m->next = NULL;
   1712     *pm = m;
   1713     return 0;
   1714 }
   1715 
   1716 static QEMUMachine *find_machine(const char *name)
   1717 {
   1718     QEMUMachine *m;
   1719 
   1720     for(m = first_machine; m != NULL; m = m->next) {
   1721         if (!strcmp(m->name, name))
   1722             return m;
   1723     }
   1724     return NULL;
   1725 }
   1726 
   1727 static QEMUMachine *find_default_machine(void)
   1728 {
   1729     QEMUMachine *m;
   1730 
   1731     for(m = first_machine; m != NULL; m = m->next) {
   1732         if (m->is_default) {
   1733             return m;
   1734         }
   1735     }
   1736     return NULL;
   1737 }
   1738 
   1739 /***********************************************************/
   1740 /* main execution loop */
   1741 
   1742 static void gui_update(void *opaque)
   1743 {
   1744     uint64_t interval = GUI_REFRESH_INTERVAL;
   1745     DisplayState *ds = opaque;
   1746     DisplayChangeListener *dcl = ds->listeners;
   1747 
   1748     dpy_refresh(ds);
   1749 
   1750     while (dcl != NULL) {
   1751         if (dcl->gui_timer_interval &&
   1752             dcl->gui_timer_interval < interval)
   1753             interval = dcl->gui_timer_interval;
   1754         dcl = dcl->next;
   1755     }
   1756     qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
   1757 }
   1758 
   1759 static void nographic_update(void *opaque)
   1760 {
   1761     uint64_t interval = GUI_REFRESH_INTERVAL;
   1762 
   1763     qemu_mod_timer(nographic_timer, interval + qemu_get_clock_ms(rt_clock));
   1764 }
   1765 
   1766 struct vm_change_state_entry {
   1767     VMChangeStateHandler *cb;
   1768     void *opaque;
   1769     QLIST_ENTRY (vm_change_state_entry) entries;
   1770 };
   1771 
   1772 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
   1773 
   1774 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
   1775                                                      void *opaque)
   1776 {
   1777     VMChangeStateEntry *e;
   1778 
   1779     e = qemu_mallocz(sizeof (*e));
   1780 
   1781     e->cb = cb;
   1782     e->opaque = opaque;
   1783     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
   1784     return e;
   1785 }
   1786 
   1787 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
   1788 {
   1789     QLIST_REMOVE (e, entries);
   1790     qemu_free (e);
   1791 }
   1792 
   1793 void vm_state_notify(int running, int reason)
   1794 {
   1795     VMChangeStateEntry *e;
   1796 
   1797     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
   1798         e->cb(e->opaque, running, reason);
   1799     }
   1800 }
   1801 
   1802 void vm_start(void)
   1803 {
   1804     if (!vm_running) {
   1805         cpu_enable_ticks();
   1806         vm_running = 1;
   1807         vm_state_notify(1, 0);
   1808         //qemu_rearm_alarm_timer(alarm_timer);
   1809         resume_all_vcpus();
   1810     }
   1811 }
   1812 
   1813 /* reset/shutdown handler */
   1814 
   1815 typedef struct QEMUResetEntry {
   1816     QEMUResetHandler *func;
   1817     void *opaque;
   1818     int order;
   1819     struct QEMUResetEntry *next;
   1820 } QEMUResetEntry;
   1821 
   1822 static QEMUResetEntry *first_reset_entry;
   1823 static int reset_requested;
   1824 static int shutdown_requested, shutdown_signal = -1;
   1825 static pid_t shutdown_pid;
   1826 static int powerdown_requested;
   1827 int debug_requested;
   1828 static int vmstop_requested;
   1829 
   1830 int qemu_shutdown_requested(void)
   1831 {
   1832     int r = shutdown_requested;
   1833     shutdown_requested = 0;
   1834     return r;
   1835 }
   1836 
   1837 int qemu_reset_requested(void)
   1838 {
   1839     int r = reset_requested;
   1840     reset_requested = 0;
   1841     return r;
   1842 }
   1843 
   1844 int qemu_powerdown_requested(void)
   1845 {
   1846     int r = powerdown_requested;
   1847     powerdown_requested = 0;
   1848     return r;
   1849 }
   1850 
   1851 static int qemu_debug_requested(void)
   1852 {
   1853     int r = debug_requested;
   1854     debug_requested = 0;
   1855     return r;
   1856 }
   1857 
   1858 static int qemu_vmstop_requested(void)
   1859 {
   1860     int r = vmstop_requested;
   1861     vmstop_requested = 0;
   1862     return r;
   1863 }
   1864 
   1865 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
   1866 {
   1867     QEMUResetEntry **pre, *re;
   1868 
   1869     pre = &first_reset_entry;
   1870     while (*pre != NULL && (*pre)->order >= order) {
   1871         pre = &(*pre)->next;
   1872     }
   1873     re = qemu_mallocz(sizeof(QEMUResetEntry));
   1874     re->func = func;
   1875     re->opaque = opaque;
   1876     re->order = order;
   1877     re->next = NULL;
   1878     *pre = re;
   1879 }
   1880 
   1881 void qemu_system_reset(void)
   1882 {
   1883     QEMUResetEntry *re;
   1884 
   1885     /* reset all devices */
   1886     for(re = first_reset_entry; re != NULL; re = re->next) {
   1887         re->func(re->opaque);
   1888     }
   1889 }
   1890 
   1891 void qemu_system_reset_request(void)
   1892 {
   1893     if (no_reboot) {
   1894         shutdown_requested = 1;
   1895     } else {
   1896         reset_requested = 1;
   1897     }
   1898     qemu_notify_event();
   1899 }
   1900 
   1901 void qemu_system_killed(int signal, pid_t pid)
   1902 {
   1903     shutdown_signal = signal;
   1904     shutdown_pid = pid;
   1905     qemu_system_shutdown_request();
   1906 }
   1907 
   1908 void qemu_system_shutdown_request(void)
   1909 {
   1910     shutdown_requested = 1;
   1911     qemu_notify_event();
   1912 }
   1913 
   1914 void qemu_system_powerdown_request(void)
   1915 {
   1916     powerdown_requested = 1;
   1917     qemu_notify_event();
   1918 }
   1919 
   1920 #ifdef CONFIG_IOTHREAD
   1921 static void qemu_system_vmstop_request(int reason)
   1922 {
   1923     vmstop_requested = reason;
   1924     qemu_notify_event();
   1925 }
   1926 #endif
   1927 
   1928 void main_loop_wait(int timeout)
   1929 {
   1930     fd_set rfds, wfds, xfds;
   1931     int ret, nfds;
   1932     struct timeval tv;
   1933 
   1934     qemu_bh_update_timeout(&timeout);
   1935 
   1936     os_host_main_loop_wait(&timeout);
   1937 
   1938 
   1939     tv.tv_sec = timeout / 1000;
   1940     tv.tv_usec = (timeout % 1000) * 1000;
   1941 
   1942     /* poll any events */
   1943 
   1944     /* XXX: separate device handlers from system ones */
   1945     nfds = -1;
   1946     FD_ZERO(&rfds);
   1947     FD_ZERO(&wfds);
   1948     FD_ZERO(&xfds);
   1949     qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
   1950     if (slirp_is_inited()) {
   1951         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
   1952     }
   1953 
   1954     qemu_mutex_unlock_iothread();
   1955     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
   1956     qemu_mutex_lock_iothread();
   1957     qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
   1958     if (slirp_is_inited()) {
   1959         if (ret < 0) {
   1960             FD_ZERO(&rfds);
   1961             FD_ZERO(&wfds);
   1962             FD_ZERO(&xfds);
   1963         }
   1964         slirp_select_poll(&rfds, &wfds, &xfds);
   1965     }
   1966     charpipe_poll();
   1967 
   1968     qemu_run_all_timers();
   1969 
   1970     /* Check bottom-halves last in case any of the earlier events triggered
   1971        them.  */
   1972     qemu_bh_poll();
   1973 
   1974 }
   1975 
   1976 static int vm_can_run(void)
   1977 {
   1978     if (powerdown_requested)
   1979         return 0;
   1980     if (reset_requested)
   1981         return 0;
   1982     if (shutdown_requested)
   1983         return 0;
   1984     if (debug_requested)
   1985         return 0;
   1986     return 1;
   1987 }
   1988 
   1989 static void main_loop(void)
   1990 {
   1991     int r;
   1992 
   1993 #ifdef CONFIG_IOTHREAD
   1994     qemu_system_ready = 1;
   1995     qemu_cond_broadcast(&qemu_system_cond);
   1996 #endif
   1997 
   1998 #ifdef CONFIG_HAX
   1999     if (hax_enabled())
   2000         hax_sync_vcpus();
   2001 #endif
   2002 
   2003     for (;;) {
   2004         do {
   2005 #ifdef CONFIG_PROFILER
   2006             int64_t ti;
   2007 #endif
   2008 #ifndef CONFIG_IOTHREAD
   2009             tcg_cpu_exec();
   2010 #endif
   2011 #ifdef CONFIG_PROFILER
   2012             ti = profile_getclock();
   2013 #endif
   2014             main_loop_wait(qemu_calculate_timeout());
   2015 #ifdef CONFIG_PROFILER
   2016             dev_time += profile_getclock() - ti;
   2017 #endif
   2018 
   2019             if (rotate_logs_requested) {
   2020                 FILE* new_dns_log_fd = rotate_qemu_log(get_slirp_dns_log_fd(),
   2021                                                         dns_log_filename);
   2022                 FILE* new_drop_log_fd = rotate_qemu_log(get_slirp_drop_log_fd(),
   2023                                                          drop_log_filename);
   2024                 slirp_dns_log_fd(new_dns_log_fd);
   2025                 slirp_drop_log_fd(new_drop_log_fd);
   2026                 reset_rotate_qemu_logs_request();
   2027             }
   2028 
   2029         } while (vm_can_run());
   2030 
   2031         if (qemu_debug_requested())
   2032             vm_stop(EXCP_DEBUG);
   2033         if (qemu_shutdown_requested()) {
   2034             if (no_shutdown) {
   2035                 vm_stop(0);
   2036                 no_shutdown = 0;
   2037             } else {
   2038                 if (savevm_on_exit != NULL) {
   2039                   /* Prior to saving VM to the snapshot file, save HW config
   2040                    * settings for that VM, so we can match them when VM gets
   2041                    * loaded from the snapshot. */
   2042                   snaphost_save_config(savevm_on_exit);
   2043                   do_savevm(cur_mon, savevm_on_exit);
   2044                 }
   2045                 break;
   2046             }
   2047         }
   2048         if (qemu_reset_requested()) {
   2049             pause_all_vcpus();
   2050             qemu_system_reset();
   2051             resume_all_vcpus();
   2052         }
   2053         if (qemu_powerdown_requested())
   2054             qemu_system_powerdown();
   2055         if ((r = qemu_vmstop_requested()))
   2056             vm_stop(r);
   2057     }
   2058     pause_all_vcpus();
   2059 }
   2060 
   2061 void version(void)
   2062 {
   2063     printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
   2064 }
   2065 
   2066 void qemu_help(int exitcode)
   2067 {
   2068     version();
   2069     printf("usage: %s [options] [disk_image]\n"
   2070            "\n"
   2071            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
   2072            "\n"
   2073 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   2074            opt_help
   2075 #define DEFHEADING(text) stringify(text) "\n"
   2076 #include "qemu-options.def"
   2077 #undef DEF
   2078 #undef DEFHEADING
   2079 #undef GEN_DOCS
   2080            "\n"
   2081            "During emulation, the following keys are useful:\n"
   2082            "ctrl-alt-f      toggle full screen\n"
   2083            "ctrl-alt-n      switch to virtual console 'n'\n"
   2084            "ctrl-alt        toggle mouse and keyboard grab\n"
   2085            "\n"
   2086            "When using -nographic, press 'ctrl-a h' to get some help.\n"
   2087            ,
   2088            "qemu",
   2089            DEFAULT_RAM_SIZE,
   2090 #ifndef _WIN32
   2091            DEFAULT_NETWORK_SCRIPT,
   2092            DEFAULT_NETWORK_DOWN_SCRIPT,
   2093 #endif
   2094            DEFAULT_GDBSTUB_PORT,
   2095            "/tmp/qemu.log");
   2096     QEMU_EXIT(exitcode);
   2097 }
   2098 
   2099 #define HAS_ARG 0x0001
   2100 
   2101 enum {
   2102 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   2103     opt_enum,
   2104 #define DEFHEADING(text)
   2105 #include "qemu-options.def"
   2106 #undef DEF
   2107 #undef DEFHEADING
   2108 #undef GEN_DOCS
   2109 };
   2110 
   2111 typedef struct QEMUOption {
   2112     const char *name;
   2113     int flags;
   2114     int index;
   2115 } QEMUOption;
   2116 
   2117 static const QEMUOption qemu_options[] = {
   2118     { "h", 0, QEMU_OPTION_h },
   2119 #define DEF(option, opt_arg, opt_enum, opt_help)        \
   2120     { option, opt_arg, opt_enum },
   2121 #define DEFHEADING(text)
   2122 #include "qemu-options.def"
   2123 #undef DEF
   2124 #undef DEFHEADING
   2125 #undef GEN_DOCS
   2126     { NULL, 0, 0 },
   2127 };
   2128 
   2129 static void select_vgahw (const char *p)
   2130 {
   2131     const char *opts;
   2132 
   2133     cirrus_vga_enabled = 0;
   2134     std_vga_enabled = 0;
   2135     vmsvga_enabled = 0;
   2136     xenfb_enabled = 0;
   2137     if (strstart(p, "std", &opts)) {
   2138         std_vga_enabled = 1;
   2139     } else if (strstart(p, "cirrus", &opts)) {
   2140         cirrus_vga_enabled = 1;
   2141     } else if (strstart(p, "vmware", &opts)) {
   2142         vmsvga_enabled = 1;
   2143     } else if (strstart(p, "xenfb", &opts)) {
   2144         xenfb_enabled = 1;
   2145     } else if (!strstart(p, "none", &opts)) {
   2146     invalid_vga:
   2147         PANIC("Unknown vga type: %s", p);
   2148     }
   2149     while (*opts) {
   2150         const char *nextopt;
   2151 
   2152         if (strstart(opts, ",retrace=", &nextopt)) {
   2153             opts = nextopt;
   2154             if (strstart(opts, "dumb", &nextopt))
   2155                 vga_retrace_method = VGA_RETRACE_DUMB;
   2156             else if (strstart(opts, "precise", &nextopt))
   2157                 vga_retrace_method = VGA_RETRACE_PRECISE;
   2158             else goto invalid_vga;
   2159         } else goto invalid_vga;
   2160         opts = nextopt;
   2161     }
   2162 }
   2163 
   2164 #define MAX_NET_CLIENTS 32
   2165 
   2166 #ifdef _WIN32
   2167 /* Look for support files in the same directory as the executable.  */
   2168 static char *find_datadir(const char *argv0)
   2169 {
   2170     char *p;
   2171     char buf[MAX_PATH];
   2172     DWORD len;
   2173 
   2174     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
   2175     if (len == 0) {
   2176         return NULL;
   2177     }
   2178 
   2179     buf[len] = 0;
   2180     p = buf + len - 1;
   2181     while (p != buf && *p != '\\')
   2182         p--;
   2183     *p = 0;
   2184     if (access(buf, R_OK) == 0) {
   2185         return qemu_strdup(buf);
   2186     }
   2187     return NULL;
   2188 }
   2189 #else /* !_WIN32 */
   2190 
   2191 /* Similarly, return the location of the executable */
   2192 static char *find_datadir(const char *argv0)
   2193 {
   2194     char *p = NULL;
   2195     char buf[PATH_MAX];
   2196 
   2197 #if defined(__linux__)
   2198     {
   2199         int len;
   2200         len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
   2201         if (len > 0) {
   2202             buf[len] = 0;
   2203             p = buf;
   2204         }
   2205     }
   2206 #elif defined(__FreeBSD__)
   2207     {
   2208         int len;
   2209         len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
   2210         if (len > 0) {
   2211             buf[len] = 0;
   2212             p = buf;
   2213         }
   2214     }
   2215 #endif
   2216     /* If we don't have any way of figuring out the actual executable
   2217        location then try argv[0].  */
   2218     if (!p) {
   2219         p = realpath(argv0, buf);
   2220         if (!p) {
   2221             return NULL;
   2222         }
   2223     }
   2224 
   2225     return qemu_strdup(dirname(buf));
   2226 }
   2227 #endif
   2228 
   2229 static char*
   2230 qemu_find_file_with_subdir(const char* data_dir, const char* subdir, const char* name)
   2231 {
   2232     int   len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
   2233     char* buf = qemu_mallocz(len);
   2234 
   2235     snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
   2236     VERBOSE_PRINT(init,"    trying to find: %s\n", buf);
   2237     if (access(buf, R_OK)) {
   2238         qemu_free(buf);
   2239         return NULL;
   2240     }
   2241     return buf;
   2242 }
   2243 
   2244 char *qemu_find_file(int type, const char *name)
   2245 {
   2246     const char *subdir;
   2247     char *buf;
   2248 
   2249     /* If name contains path separators then try it as a straight path.  */
   2250     if ((strchr(name, '/') || strchr(name, '\\'))
   2251         && access(name, R_OK) == 0) {
   2252         return strdup(name);
   2253     }
   2254     switch (type) {
   2255     case QEMU_FILE_TYPE_BIOS:
   2256         subdir = "";
   2257         break;
   2258     case QEMU_FILE_TYPE_KEYMAP:
   2259         subdir = "keymaps/";
   2260         break;
   2261     default:
   2262         abort();
   2263     }
   2264     buf = qemu_find_file_with_subdir(data_dir, subdir, name);
   2265 #ifdef CONFIG_ANDROID
   2266     if (type == QEMU_FILE_TYPE_BIOS) {
   2267         /* This case corresponds to the emulator being used as part of an
   2268          * SDK installation. NOTE: data_dir is really $bindir. */
   2269         if (buf == NULL)
   2270             buf = qemu_find_file_with_subdir(data_dir, "lib/pc-bios/", name);
   2271         /* This case corresponds to platform builds. */
   2272         if (buf == NULL)
   2273             buf = qemu_find_file_with_subdir(data_dir, "../usr/share/pc-bios/", name);
   2274         /* Finally, try this for standalone builds under external/qemu */
   2275         if (buf == NULL)
   2276             buf = qemu_find_file_with_subdir(data_dir, "../../../prebuilts/qemu-kernel/x86/pc-bios/", name);
   2277     }
   2278 #endif
   2279     return buf;
   2280 }
   2281 
   2282 static int
   2283 add_dns_server( const char*  server_name )
   2284 {
   2285     SockAddress   addr;
   2286 
   2287     if (sock_address_init_resolve( &addr, server_name, 55, 0 ) < 0) {
   2288         fprintf(stdout,
   2289                 "### WARNING: can't resolve DNS server name '%s'\n",
   2290                 server_name );
   2291         return -1;
   2292     }
   2293 
   2294     fprintf(stderr,
   2295             "DNS server name '%s' resolved to %s\n", server_name, sock_address_to_string(&addr) );
   2296 
   2297     if ( slirp_add_dns_server( &addr ) < 0 ) {
   2298         fprintf(stderr,
   2299                 "### WARNING: could not add DNS server '%s' to the network stack\n", server_name);
   2300         return -1;
   2301     }
   2302     return 0;
   2303 }
   2304 
   2305 /* Parses an integer
   2306  * Pararm:
   2307  *  str      String containing a number to be parsed.
   2308  *  result   Passes the parsed integer in this argument
   2309  *  returns  0 if ok, -1 if failed
   2310  */
   2311 int
   2312 parse_int(const char *str, int *result)
   2313 {
   2314     char* r;
   2315     *result = strtol(str, &r, 0);
   2316     if (r == NULL || *r != '\0')
   2317       return -1;
   2318 
   2319     return 0;
   2320 }
   2321 
   2322 #ifndef _WIN32
   2323 /*
   2324  * Initializes the SIGUSR1 signal handler to clear Qemu logs.
   2325  */
   2326 void init_qemu_clear_logs_sig() {
   2327   struct sigaction act;
   2328   sigfillset(&act.sa_mask);
   2329   act.sa_flags = 0;
   2330   act.sa_handler = rotate_qemu_logs_handler;
   2331   if (sigaction(SIGUSR1, &act, NULL) == -1) {
   2332     fprintf(stderr, "Failed to setup SIGUSR1 handler to clear Qemu logs\n");
   2333     exit(-1);
   2334   }
   2335 }
   2336 #endif
   2337 
   2338 
   2339 
   2340 /* parses a null-terminated string specifying a network port (e.g., "80") or
   2341  * port range (e.g., "[6666-7000]"). In case of a single port, lport and hport
   2342  * are the same. Returns 0 on success, -1 on error. */
   2343 
   2344 int parse_port_range(const char *str, unsigned short *lport,
   2345                      unsigned short *hport) {
   2346 
   2347   unsigned int low = 0, high = 0;
   2348   char *p, *arg = strdup(str);
   2349 
   2350   if ((*arg == '[') && ((p = strrchr(arg, ']')) != NULL)) {
   2351     p = arg + 1;   /* skip '[' */
   2352     low  = atoi(strtok(p, "-"));
   2353     high = atoi(strtok(NULL, "-"));
   2354     if ((low > 0) && (high > 0) && (low < high) && (high < 65535)) {
   2355       *lport = low;
   2356       *hport = high;
   2357     }
   2358   }
   2359   else {
   2360     low = atoi(arg);
   2361     if ((0 < low) && (low < 65535)) {
   2362       *lport = low;
   2363       *hport = low;
   2364     }
   2365   }
   2366   free(arg);
   2367   if (low != 0)
   2368     return 0;
   2369   return -1;
   2370 }
   2371 
   2372 /*
   2373  * Implements the generic port forwarding option
   2374  */
   2375 void
   2376 net_slirp_forward(const char *optarg)
   2377 {
   2378     /*
   2379      * we expect the following format:
   2380      * dst_net:dst_mask:dst_port:redirect_ip:redirect_port OR
   2381      * dst_net:dst_mask:[dp_range_start-dp_range_end]:redirect_ip:redirect_port
   2382      */
   2383     char *argument = strdup(optarg), *p = argument;
   2384     char *dst_net, *dst_mask, *dst_port;
   2385     char *redirect_ip, *redirect_port;
   2386     uint32_t dnet, dmask, rip;
   2387     unsigned short dlport = 0, dhport = 0, rport;
   2388 
   2389 
   2390     dst_net = strtok(p, ":");
   2391     dst_mask = strtok(NULL, ":");
   2392     dst_port = strtok(NULL, ":");
   2393     redirect_ip = strtok(NULL, ":");
   2394     redirect_port = strtok(NULL, ":");
   2395 
   2396     if (dst_net == NULL || dst_mask == NULL || dst_port == NULL ||
   2397         redirect_ip == NULL || redirect_port == NULL) {
   2398         fprintf(stderr,
   2399                 "Invalid argument for -net-forward, we expect "
   2400                 "dst_net:dst_mask:dst_port:redirect_ip:redirect_port or "
   2401                 "dst_net:dst_mask:[dp_range_start-dp_range_end]"
   2402                 ":redirect_ip:redirect_port: %s\n",
   2403                 optarg);
   2404         exit(1);
   2405     }
   2406 
   2407     /* inet_strtoip converts dotted address to host byte order */
   2408     if (inet_strtoip(dst_net, &dnet) == -1) {
   2409         fprintf(stderr, "Invalid destination IP net: %s\n", dst_net);
   2410         exit(1);
   2411     }
   2412     if (inet_strtoip(dst_mask, &dmask) == -1) {
   2413         fprintf(stderr, "Invalid destination IP mask: %s\n", dst_mask);
   2414         exit(1);
   2415     }
   2416     if (inet_strtoip(redirect_ip, &rip) == -1) {
   2417         fprintf(stderr, "Invalid redirect IP address: %s\n", redirect_ip);
   2418         exit(1);
   2419     }
   2420 
   2421     if (parse_port_range(dst_port, &dlport, &dhport) == -1) {
   2422         fprintf(stderr, "Invalid destination port or port range\n");
   2423         exit(1);
   2424     }
   2425 
   2426     rport = atoi(redirect_port);
   2427     if (!rport) {
   2428         fprintf(stderr, "Invalid redirect port: %s\n", redirect_port);
   2429         exit(1);
   2430     }
   2431 
   2432     dnet &= dmask;
   2433 
   2434     slirp_add_net_forward(dnet, dmask, dlport, dhport,
   2435                           rip, rport);
   2436 
   2437     free(argument);
   2438 }
   2439 
   2440 
   2441 /* Parses an -allow-tcp or -allow-udp argument and inserts a corresponding
   2442  * entry in the allows list */
   2443 void
   2444 slirp_allow(const char *optarg, u_int8_t proto)
   2445 {
   2446   /*
   2447    * we expect the following format:
   2448    * dst_ip:dst_port OR dst_ip:[dst_lport-dst_hport]
   2449    */
   2450   char *argument = strdup(optarg), *p = argument;
   2451   char *dst_ip_str, *dst_port_str;
   2452   uint32_t dst_ip;
   2453   unsigned short dst_lport = 0, dst_hport = 0;
   2454 
   2455   dst_ip_str = strtok(p, ":");
   2456   dst_port_str = strtok(NULL, ":");
   2457 
   2458   if (dst_ip_str == NULL || dst_port_str == NULL) {
   2459     fprintf(stderr,
   2460             "Invalid argument %s for -allow. We expect "
   2461             "dst_ip:dst_port or dst_ip:[dst_lport-dst_hport]\n",
   2462             optarg);
   2463     exit(1);
   2464   }
   2465 
   2466   if (inet_strtoip(dst_ip_str, &dst_ip) == -1) {
   2467     fprintf(stderr, "Invalid destination IP address: %s\n", dst_ip_str);
   2468     exit(1);
   2469   }
   2470   if (parse_port_range(dst_port_str, &dst_lport, &dst_hport) == -1) {
   2471     fprintf(stderr, "Invalid destination port or port range\n");
   2472     exit(1);
   2473   }
   2474 
   2475   slirp_add_allow(dst_ip, dst_lport, dst_hport, proto);
   2476 
   2477   free(argument);
   2478 }
   2479 
   2480 /* Add a serial device at a given location in the emulated hardware table.
   2481  * On failure, this function aborts the program with an error message.
   2482  */
   2483 static void
   2484 serial_hds_add_at(int  index, const char* devname)
   2485 {
   2486     char label[32];
   2487 
   2488     if (!devname || !strcmp(devname,"none"))
   2489         return;
   2490 
   2491     if (index >= MAX_SERIAL_PORTS) {
   2492         PANIC("qemu: invalid serial index for %s (%d >= %d)",
   2493               devname, index, MAX_SERIAL_PORTS);
   2494     }
   2495     if (serial_hds[index] != NULL) {
   2496         PANIC("qemu: invalid serial index for %s (%d: already taken!)",
   2497               devname, index);
   2498     }
   2499     snprintf(label, sizeof(label), "serial%d", index);
   2500     serial_hds[index] = qemu_chr_open(label, devname, NULL);
   2501     if (!serial_hds[index]) {
   2502         PANIC("qemu: could not open serial device '%s'", devname);
   2503     }
   2504 }
   2505 
   2506 
   2507 /* Find a free slot in the emulated serial device table, and register
   2508  * it. Return the allocated table index.
   2509  */
   2510 static int
   2511 serial_hds_add(const char* devname)
   2512 {
   2513     int  index;
   2514 
   2515     /* Find first free slot */
   2516     for (index = 0; index < MAX_SERIAL_PORTS; index++) {
   2517         if (serial_hds[index] == NULL) {
   2518             serial_hds_add_at(index, devname);
   2519             return index;
   2520         }
   2521     }
   2522 
   2523     PANIC("qemu: too many serial devices registered (%d)", index);
   2524     return -1;  /* shouldn't happen */
   2525 }
   2526 
   2527 int main(int argc, char **argv, char **envp)
   2528 {
   2529     const char *gdbstub_dev = NULL;
   2530     uint32_t boot_devices_bitmap = 0;
   2531     int i;
   2532     int snapshot, linux_boot, net_boot;
   2533     const char *icount_option = NULL;
   2534     const char *initrd_filename;
   2535     const char *kernel_filename, *kernel_cmdline;
   2536     const char *boot_devices = "";
   2537     DisplayState *ds;
   2538     DisplayChangeListener *dcl;
   2539     int cyls, heads, secs, translation;
   2540     QemuOpts *hda_opts = NULL;
   2541     QemuOpts *hdb_opts = NULL;
   2542     const char *net_clients[MAX_NET_CLIENTS];
   2543     int nb_net_clients;
   2544     const char *bt_opts[MAX_BT_CMDLINE];
   2545     int nb_bt_opts;
   2546     int optind;
   2547     const char *r, *optarg;
   2548     CharDriverState *monitor_hd = NULL;
   2549     const char *monitor_device;
   2550     const char *serial_devices[MAX_SERIAL_PORTS];
   2551     int serial_device_index;
   2552     const char *parallel_devices[MAX_PARALLEL_PORTS];
   2553     int parallel_device_index;
   2554     const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
   2555     int virtio_console_index;
   2556     const char *loadvm = NULL;
   2557     QEMUMachine *machine;
   2558     const char *cpu_model;
   2559     const char *usb_devices[MAX_USB_CMDLINE];
   2560     int usb_devices_index;
   2561     int tb_size;
   2562     const char *pid_file = NULL;
   2563     const char *incoming = NULL;
   2564     CPUState *env;
   2565     int show_vnc_port = 0;
   2566     IniFile*  hw_ini = NULL;
   2567     STRALLOC_DEFINE(kernel_params);
   2568     STRALLOC_DEFINE(kernel_config);
   2569     int    dns_count = 0;
   2570 
   2571     /* Initialize sockets before anything else, so we can properly report
   2572      * initialization failures back to the UI. */
   2573 #ifdef _WIN32
   2574     socket_init();
   2575 #endif
   2576 
   2577     init_clocks();
   2578 
   2579     qemu_cache_utils_init(envp);
   2580 
   2581     QLIST_INIT (&vm_change_state_head);
   2582     os_setup_early_signal_handling();
   2583 
   2584     module_call_init(MODULE_INIT_MACHINE);
   2585     machine = find_default_machine();
   2586     cpu_model = NULL;
   2587     initrd_filename = NULL;
   2588     ram_size = 0;
   2589     snapshot = 0;
   2590     kernel_filename = NULL;
   2591     kernel_cmdline = "";
   2592 
   2593     cyls = heads = secs = 0;
   2594     translation = BIOS_ATA_TRANSLATION_AUTO;
   2595     monitor_device = "vc:80Cx24C";
   2596 
   2597     serial_devices[0] = "vc:80Cx24C";
   2598     for(i = 1; i < MAX_SERIAL_PORTS; i++)
   2599         serial_devices[i] = NULL;
   2600     serial_device_index = 0;
   2601 
   2602     parallel_devices[0] = "vc:80Cx24C";
   2603     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
   2604         parallel_devices[i] = NULL;
   2605     parallel_device_index = 0;
   2606 
   2607     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
   2608         virtio_consoles[i] = NULL;
   2609     virtio_console_index = 0;
   2610 
   2611     for (i = 0; i < MAX_NODES; i++) {
   2612         node_mem[i] = 0;
   2613         node_cpumask[i] = 0;
   2614     }
   2615 
   2616     usb_devices_index = 0;
   2617 
   2618     nb_net_clients = 0;
   2619     nb_bt_opts = 0;
   2620 #ifdef MAX_DRIVES
   2621     nb_drives = 0;
   2622     nb_drives_opt = 0;
   2623 #endif
   2624     nb_numa_nodes = 0;
   2625 
   2626     nb_nics = 0;
   2627 
   2628     tb_size = 0;
   2629     autostart= 1;
   2630 
   2631     register_watchdogs();
   2632 
   2633     /* Initialize boot properties. */
   2634     boot_property_init_service();
   2635     android_hw_control_init();
   2636     android_net_pipes_init();
   2637 
   2638 #ifdef CONFIG_KVM
   2639     /* By default, force auto-detection for kvm */
   2640     kvm_allowed = -1;
   2641 #endif
   2642 
   2643     optind = 1;
   2644     for(;;) {
   2645         if (optind >= argc)
   2646             break;
   2647         r = argv[optind];
   2648         if (r[0] != '-') {
   2649             hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
   2650         } else {
   2651             const QEMUOption *popt;
   2652 
   2653             optind++;
   2654             /* Treat --foo the same as -foo.  */
   2655             if (r[1] == '-')
   2656                 r++;
   2657             popt = qemu_options;
   2658             for(;;) {
   2659                 if (!popt->name) {
   2660                     PANIC("%s: invalid option -- '%s'",
   2661                                       argv[0], r);
   2662                 }
   2663                 if (!strcmp(popt->name, r + 1))
   2664                     break;
   2665                 popt++;
   2666             }
   2667             if (popt->flags & HAS_ARG) {
   2668                 if (optind >= argc) {
   2669                     PANIC("%s: option '%s' requires an argument",
   2670                                       argv[0], r);
   2671                 }
   2672                 optarg = argv[optind++];
   2673             } else {
   2674                 optarg = NULL;
   2675             }
   2676 
   2677             switch(popt->index) {
   2678             case QEMU_OPTION_M:
   2679                 machine = find_machine(optarg);
   2680                 if (!machine) {
   2681                     QEMUMachine *m;
   2682                     printf("Supported machines are:\n");
   2683                     for(m = first_machine; m != NULL; m = m->next) {
   2684                         printf("%-10s %s%s\n",
   2685                                m->name, m->desc,
   2686                                m->is_default ? " (default)" : "");
   2687                     }
   2688                     if (*optarg != '?') {
   2689                         PANIC("Invalid machine parameter: %s",
   2690                                           optarg);
   2691                     } else {
   2692                         QEMU_EXIT(0);
   2693                     }
   2694                 }
   2695                 break;
   2696             case QEMU_OPTION_cpu:
   2697                 /* hw initialization will check this */
   2698                 if (*optarg == '?') {
   2699 /* XXX: implement xxx_cpu_list for targets that still miss it */
   2700 #if defined(cpu_list)
   2701                     cpu_list(stdout, &fprintf);
   2702 #endif
   2703                     QEMU_EXIT(0);
   2704                 } else {
   2705                     cpu_model = optarg;
   2706                 }
   2707                 break;
   2708             case QEMU_OPTION_initrd:
   2709                 initrd_filename = optarg;
   2710                 break;
   2711             case QEMU_OPTION_hda:
   2712                 if (cyls == 0)
   2713                     hda_opts = drive_add(optarg, HD_ALIAS, 0);
   2714                 else
   2715                     hda_opts = drive_add(optarg, HD_ALIAS
   2716 			     ",cyls=%d,heads=%d,secs=%d%s",
   2717                              0, cyls, heads, secs,
   2718                              translation == BIOS_ATA_TRANSLATION_LBA ?
   2719                                  ",trans=lba" :
   2720                              translation == BIOS_ATA_TRANSLATION_NONE ?
   2721                                  ",trans=none" : "");
   2722                  break;
   2723             case QEMU_OPTION_hdb:
   2724                 hdb_opts = drive_add(optarg, HD_ALIAS, 1);
   2725                 break;
   2726 
   2727             case QEMU_OPTION_hdc:
   2728             case QEMU_OPTION_hdd:
   2729                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
   2730                 break;
   2731             case QEMU_OPTION_drive:
   2732                 drive_add(NULL, "%s", optarg);
   2733 	        break;
   2734             case QEMU_OPTION_mtdblock:
   2735                 drive_add(optarg, MTD_ALIAS);
   2736                 break;
   2737             case QEMU_OPTION_sd:
   2738                 drive_add(optarg, SD_ALIAS);
   2739                 break;
   2740             case QEMU_OPTION_pflash:
   2741                 drive_add(optarg, PFLASH_ALIAS);
   2742                 break;
   2743             case QEMU_OPTION_snapshot:
   2744                 snapshot = 1;
   2745                 break;
   2746             case QEMU_OPTION_hdachs:
   2747                 {
   2748                     const char *p;
   2749                     p = optarg;
   2750                     cyls = strtol(p, (char **)&p, 0);
   2751                     if (cyls < 1 || cyls > 16383)
   2752                         goto chs_fail;
   2753                     if (*p != ',')
   2754                         goto chs_fail;
   2755                     p++;
   2756                     heads = strtol(p, (char **)&p, 0);
   2757                     if (heads < 1 || heads > 16)
   2758                         goto chs_fail;
   2759                     if (*p != ',')
   2760                         goto chs_fail;
   2761                     p++;
   2762                     secs = strtol(p, (char **)&p, 0);
   2763                     if (secs < 1 || secs > 63)
   2764                         goto chs_fail;
   2765                     if (*p == ',') {
   2766                         p++;
   2767                         if (!strcmp(p, "none"))
   2768                             translation = BIOS_ATA_TRANSLATION_NONE;
   2769                         else if (!strcmp(p, "lba"))
   2770                             translation = BIOS_ATA_TRANSLATION_LBA;
   2771                         else if (!strcmp(p, "auto"))
   2772                             translation = BIOS_ATA_TRANSLATION_AUTO;
   2773                         else
   2774                             goto chs_fail;
   2775                     } else if (*p != '\0') {
   2776                     chs_fail:
   2777                         PANIC("qemu: invalid physical CHS format");
   2778                     }
   2779 		    if (hda_opts != NULL) {
   2780                         char num[16];
   2781                         snprintf(num, sizeof(num), "%d", cyls);
   2782                         qemu_opt_set(hda_opts, "cyls", num);
   2783                         snprintf(num, sizeof(num), "%d", heads);
   2784                         qemu_opt_set(hda_opts, "heads", num);
   2785                         snprintf(num, sizeof(num), "%d", secs);
   2786                         qemu_opt_set(hda_opts, "secs", num);
   2787                         if (translation == BIOS_ATA_TRANSLATION_LBA)
   2788                             qemu_opt_set(hda_opts, "trans", "lba");
   2789                         if (translation == BIOS_ATA_TRANSLATION_NONE)
   2790                             qemu_opt_set(hda_opts, "trans", "none");
   2791                     }
   2792                 }
   2793                 break;
   2794             case QEMU_OPTION_numa:
   2795                 if (nb_numa_nodes >= MAX_NODES) {
   2796                     PANIC("qemu: too many NUMA nodes");
   2797                 }
   2798                 numa_add(optarg);
   2799                 break;
   2800             case QEMU_OPTION_nographic:
   2801                 display_type = DT_NOGRAPHIC;
   2802                 break;
   2803 #ifdef CONFIG_CURSES
   2804             case QEMU_OPTION_curses:
   2805                 display_type = DT_CURSES;
   2806                 break;
   2807 #endif
   2808             case QEMU_OPTION_portrait:
   2809                 graphic_rotate = 1;
   2810                 break;
   2811             case QEMU_OPTION_kernel:
   2812                 kernel_filename = optarg;
   2813                 break;
   2814             case QEMU_OPTION_append:
   2815                 kernel_cmdline = optarg;
   2816                 break;
   2817             case QEMU_OPTION_cdrom:
   2818                 drive_add(optarg, CDROM_ALIAS);
   2819                 break;
   2820             case QEMU_OPTION_boot:
   2821                 boot_devices = optarg;
   2822                 /* We just do some generic consistency checks */
   2823                 {
   2824                     /* Could easily be extended to 64 devices if needed */
   2825                     const char *p;
   2826 
   2827                     boot_devices_bitmap = 0;
   2828                     for (p = boot_devices; *p != '\0'; p++) {
   2829                         /* Allowed boot devices are:
   2830                          * a b     : floppy disk drives
   2831                          * c ... f : IDE disk drives
   2832                          * g ... m : machine implementation dependant drives
   2833                          * n ... p : network devices
   2834                          * It's up to each machine implementation to check
   2835                          * if the given boot devices match the actual hardware
   2836                          * implementation and firmware features.
   2837                          */
   2838                         if (*p < 'a' || *p > 'q') {
   2839                             PANIC("Invalid boot device '%c'", *p);
   2840                         }
   2841                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
   2842                             PANIC(
   2843                                     "Boot device '%c' was given twice",*p);
   2844                         }
   2845                         boot_devices_bitmap |= 1 << (*p - 'a');
   2846                     }
   2847                 }
   2848                 break;
   2849             case QEMU_OPTION_fda:
   2850             case QEMU_OPTION_fdb:
   2851                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
   2852                 break;
   2853 #ifdef TARGET_I386
   2854             case QEMU_OPTION_no_fd_bootchk:
   2855                 fd_bootchk = 0;
   2856                 break;
   2857 #endif
   2858             case QEMU_OPTION_net:
   2859                 if (nb_net_clients >= MAX_NET_CLIENTS) {
   2860                     PANIC("qemu: too many network clients");
   2861                 }
   2862                 net_clients[nb_net_clients] = optarg;
   2863                 nb_net_clients++;
   2864                 break;
   2865 #ifdef CONFIG_SLIRP
   2866             case QEMU_OPTION_tftp:
   2867 		tftp_prefix = optarg;
   2868                 break;
   2869             case QEMU_OPTION_bootp:
   2870                 bootp_filename = optarg;
   2871                 break;
   2872             case QEMU_OPTION_redir:
   2873                 net_slirp_redir(NULL, optarg, NULL);
   2874                 break;
   2875 #endif
   2876             case QEMU_OPTION_bt:
   2877                 if (nb_bt_opts >= MAX_BT_CMDLINE) {
   2878                     PANIC("qemu: too many bluetooth options");
   2879                 }
   2880                 bt_opts[nb_bt_opts++] = optarg;
   2881                 break;
   2882 #ifdef HAS_AUDIO
   2883             case QEMU_OPTION_audio_help:
   2884                 AUD_help ();
   2885                 QEMU_EXIT(0);
   2886                 break;
   2887             case QEMU_OPTION_soundhw:
   2888                 select_soundhw (optarg);
   2889                 break;
   2890 #endif
   2891             case QEMU_OPTION_h:
   2892                 qemu_help(0);
   2893                 break;
   2894             case QEMU_OPTION_version:
   2895                 version();
   2896                 QEMU_EXIT(0);
   2897                 break;
   2898             case QEMU_OPTION_m: {
   2899                 uint64_t value;
   2900                 char *ptr;
   2901 
   2902                 value = strtoul(optarg, &ptr, 10);
   2903                 switch (*ptr) {
   2904                 case 0: case 'M': case 'm':
   2905                     value <<= 20;
   2906                     break;
   2907                 case 'G': case 'g':
   2908                     value <<= 30;
   2909                     break;
   2910                 default:
   2911                     PANIC("qemu: invalid ram size: %s", optarg);
   2912                 }
   2913 
   2914                 /* On 32-bit hosts, QEMU is limited by virtual address space */
   2915                 if (value > (2047 << 20)
   2916 #ifndef CONFIG_KQEMU
   2917                     && HOST_LONG_BITS == 32
   2918 #endif
   2919                     ) {
   2920                     PANIC("qemu: at most 2047 MB RAM can be simulated");
   2921                 }
   2922                 if (value != (uint64_t)(ram_addr_t)value) {
   2923                     PANIC("qemu: ram size too large");
   2924                 }
   2925                 ram_size = value;
   2926                 break;
   2927             }
   2928             case QEMU_OPTION_d:
   2929                 {
   2930                     int mask;
   2931                     const CPULogItem *item;
   2932 
   2933                     mask = cpu_str_to_log_mask(optarg);
   2934                     if (!mask) {
   2935                         printf("Log items (comma separated):\n");
   2936                         for(item = cpu_log_items; item->mask != 0; item++) {
   2937                             printf("%-10s %s\n", item->name, item->help);
   2938                         }
   2939                         PANIC("Invalid parameter -d=%s", optarg);
   2940                     }
   2941                     cpu_set_log(mask);
   2942                 }
   2943                 break;
   2944             case QEMU_OPTION_s:
   2945                 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
   2946                 break;
   2947             case QEMU_OPTION_gdb:
   2948                 gdbstub_dev = optarg;
   2949                 break;
   2950             case QEMU_OPTION_L:
   2951                 data_dir = optarg;
   2952                 break;
   2953             case QEMU_OPTION_bios:
   2954                 bios_name = optarg;
   2955                 break;
   2956             case QEMU_OPTION_singlestep:
   2957                 singlestep = 1;
   2958                 break;
   2959             case QEMU_OPTION_S:
   2960                 autostart = 0;
   2961                 break;
   2962 #ifndef _WIN32
   2963 	    case QEMU_OPTION_k:
   2964 		keyboard_layout = optarg;
   2965 		break;
   2966 #endif
   2967             case QEMU_OPTION_localtime:
   2968                 rtc_utc = 0;
   2969                 break;
   2970             case QEMU_OPTION_vga:
   2971                 select_vgahw (optarg);
   2972                 break;
   2973 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
   2974             case QEMU_OPTION_g:
   2975                 {
   2976                     const char *p;
   2977                     int w, h, depth;
   2978                     p = optarg;
   2979                     w = strtol(p, (char **)&p, 10);
   2980                     if (w <= 0) {
   2981                     graphic_error:
   2982                         PANIC("qemu: invalid resolution or depth");
   2983                     }
   2984                     if (*p != 'x')
   2985                         goto graphic_error;
   2986                     p++;
   2987                     h = strtol(p, (char **)&p, 10);
   2988                     if (h <= 0)
   2989                         goto graphic_error;
   2990                     if (*p == 'x') {
   2991                         p++;
   2992                         depth = strtol(p, (char **)&p, 10);
   2993                         if (depth != 8 && depth != 15 && depth != 16 &&
   2994                             depth != 24 && depth != 32)
   2995                             goto graphic_error;
   2996                     } else if (*p == '\0') {
   2997                         depth = graphic_depth;
   2998                     } else {
   2999                         goto graphic_error;
   3000                     }
   3001 
   3002                     graphic_width = w;
   3003                     graphic_height = h;
   3004                     graphic_depth = depth;
   3005                 }
   3006                 break;
   3007 #endif
   3008             case QEMU_OPTION_echr:
   3009                 {
   3010                     char *r;
   3011                     term_escape_char = strtol(optarg, &r, 0);
   3012                     if (r == optarg)
   3013                         printf("Bad argument to echr\n");
   3014                     break;
   3015                 }
   3016             case QEMU_OPTION_monitor:
   3017                 monitor_device = optarg;
   3018                 break;
   3019             case QEMU_OPTION_serial:
   3020                 if (serial_device_index >= MAX_SERIAL_PORTS) {
   3021                     PANIC("qemu: too many serial ports");
   3022                 }
   3023                 serial_devices[serial_device_index] = optarg;
   3024                 serial_device_index++;
   3025                 break;
   3026             case QEMU_OPTION_watchdog:
   3027                 i = select_watchdog(optarg);
   3028                 if (i > 0) {
   3029                     if (i == 1) {
   3030                         PANIC("Invalid watchdog parameter: %s",
   3031                                           optarg);
   3032                     } else {
   3033                         QEMU_EXIT(0);
   3034                     }
   3035                 }
   3036                 break;
   3037             case QEMU_OPTION_watchdog_action:
   3038                 if (select_watchdog_action(optarg) == -1) {
   3039                     PANIC("Unknown -watchdog-action parameter");
   3040                 }
   3041                 break;
   3042             case QEMU_OPTION_virtiocon:
   3043                 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
   3044                     PANIC("qemu: too many virtio consoles");
   3045                 }
   3046                 virtio_consoles[virtio_console_index] = optarg;
   3047                 virtio_console_index++;
   3048                 break;
   3049             case QEMU_OPTION_parallel:
   3050                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
   3051                     PANIC("qemu: too many parallel ports");
   3052                 }
   3053                 parallel_devices[parallel_device_index] = optarg;
   3054                 parallel_device_index++;
   3055                 break;
   3056             case QEMU_OPTION_loadvm:
   3057                 loadvm = optarg;
   3058                 break;
   3059             case QEMU_OPTION_savevm_on_exit:
   3060                 savevm_on_exit = optarg;
   3061                 break;
   3062             case QEMU_OPTION_full_screen:
   3063                 full_screen = 1;
   3064                 break;
   3065 #ifdef CONFIG_SDL
   3066             case QEMU_OPTION_no_frame:
   3067                 no_frame = 1;
   3068                 break;
   3069             case QEMU_OPTION_alt_grab:
   3070                 alt_grab = 1;
   3071                 break;
   3072             case QEMU_OPTION_no_quit:
   3073                 no_quit = 1;
   3074                 break;
   3075             case QEMU_OPTION_sdl:
   3076                 display_type = DT_SDL;
   3077                 break;
   3078 #endif
   3079             case QEMU_OPTION_pidfile:
   3080                 pid_file = optarg;
   3081                 break;
   3082 #ifdef TARGET_I386
   3083             case QEMU_OPTION_win2k_hack:
   3084                 win2k_install_hack = 1;
   3085                 break;
   3086             case QEMU_OPTION_rtc_td_hack:
   3087                 rtc_td_hack = 1;
   3088                 break;
   3089 #ifndef CONFIG_ANDROID
   3090             case QEMU_OPTION_acpitable:
   3091                 if(acpi_table_add(optarg) < 0) {
   3092                     PANIC("Wrong acpi table provided");
   3093                 }
   3094                 break;
   3095 #endif
   3096             case QEMU_OPTION_smbios:
   3097                 do_smbios_option(optarg);
   3098                 break;
   3099 #endif
   3100 #ifdef CONFIG_KVM
   3101             case QEMU_OPTION_enable_kvm:
   3102                 kvm_allowed = 1;
   3103                 break;
   3104             case QEMU_OPTION_disable_kvm:
   3105                 kvm_allowed = 0;
   3106                 break;
   3107 #endif /* CONFIG_KVM */
   3108             case QEMU_OPTION_usb:
   3109                 usb_enabled = 1;
   3110                 break;
   3111             case QEMU_OPTION_usbdevice:
   3112                 usb_enabled = 1;
   3113                 if (usb_devices_index >= MAX_USB_CMDLINE) {
   3114                     PANIC("Too many USB devices");
   3115                 }
   3116                 usb_devices[usb_devices_index] = optarg;
   3117                 usb_devices_index++;
   3118                 break;
   3119             case QEMU_OPTION_smp:
   3120                 smp_cpus = atoi(optarg);
   3121                 if (smp_cpus < 1) {
   3122                     PANIC("Invalid number of CPUs");
   3123                 }
   3124                 break;
   3125 	    case QEMU_OPTION_vnc:
   3126                 display_type = DT_VNC;
   3127 		vnc_display = optarg;
   3128 		break;
   3129 #ifdef TARGET_I386
   3130             case QEMU_OPTION_no_acpi:
   3131                 acpi_enabled = 0;
   3132                 break;
   3133             case QEMU_OPTION_no_hpet:
   3134                 no_hpet = 1;
   3135                 break;
   3136             case QEMU_OPTION_no_virtio_balloon:
   3137                 no_virtio_balloon = 1;
   3138                 break;
   3139 #endif
   3140             case QEMU_OPTION_no_reboot:
   3141                 no_reboot = 1;
   3142                 break;
   3143             case QEMU_OPTION_no_shutdown:
   3144                 no_shutdown = 1;
   3145                 break;
   3146             case QEMU_OPTION_show_cursor:
   3147                 cursor_hide = 0;
   3148                 break;
   3149             case QEMU_OPTION_uuid:
   3150                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
   3151                     PANIC("Fail to parse UUID string. Wrong format.");
   3152                 }
   3153                 break;
   3154 	    case QEMU_OPTION_option_rom:
   3155 		if (nb_option_roms >= MAX_OPTION_ROMS) {
   3156 		    PANIC("Too many option ROMs");
   3157 		}
   3158 		option_rom[nb_option_roms] = optarg;
   3159 		nb_option_roms++;
   3160 		break;
   3161 #if defined(TARGET_ARM) || defined(TARGET_M68K)
   3162             case QEMU_OPTION_semihosting:
   3163                 semihosting_enabled = 1;
   3164                 break;
   3165 #endif
   3166             case QEMU_OPTION_name:
   3167                 qemu_name = optarg;
   3168                 break;
   3169 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
   3170             case QEMU_OPTION_prom_env:
   3171                 if (nb_prom_envs >= MAX_PROM_ENVS) {
   3172                     PANIC("Too many prom variables");
   3173                 }
   3174                 prom_envs[nb_prom_envs] = optarg;
   3175                 nb_prom_envs++;
   3176                 break;
   3177 #endif
   3178 #ifdef TARGET_ARM
   3179             case QEMU_OPTION_old_param:
   3180                 old_param = 1;
   3181                 break;
   3182 #endif
   3183             case QEMU_OPTION_clock:
   3184                 configure_alarms(optarg);
   3185                 break;
   3186             case QEMU_OPTION_startdate:
   3187                 {
   3188                     struct tm tm;
   3189                     time_t rtc_start_date = 0;
   3190                     if (!strcmp(optarg, "now")) {
   3191                         rtc_date_offset = -1;
   3192                     } else {
   3193                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
   3194                                &tm.tm_year,
   3195                                &tm.tm_mon,
   3196                                &tm.tm_mday,
   3197                                &tm.tm_hour,
   3198                                &tm.tm_min,
   3199                                &tm.tm_sec) == 6) {
   3200                             /* OK */
   3201                         } else if (sscanf(optarg, "%d-%d-%d",
   3202                                           &tm.tm_year,
   3203                                           &tm.tm_mon,
   3204                                           &tm.tm_mday) == 3) {
   3205                             tm.tm_hour = 0;
   3206                             tm.tm_min = 0;
   3207                             tm.tm_sec = 0;
   3208                         } else {
   3209                             goto date_fail;
   3210                         }
   3211                         tm.tm_year -= 1900;
   3212                         tm.tm_mon--;
   3213                         rtc_start_date = mktimegm(&tm);
   3214                         if (rtc_start_date == -1) {
   3215                         date_fail:
   3216                             PANIC("Invalid date format. Valid format are:\n"
   3217                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'");
   3218                         }
   3219                         rtc_date_offset = time(NULL) - rtc_start_date;
   3220                     }
   3221                 }
   3222                 break;
   3223 
   3224             /* -------------------------------------------------------*/
   3225             /* User mode network stack restrictions */
   3226             case QEMU_OPTION_drop_udp:
   3227                 slirp_drop_udp();
   3228                 break;
   3229             case QEMU_OPTION_drop_tcp:
   3230                 slirp_drop_tcp();
   3231                 break;
   3232             case QEMU_OPTION_allow_tcp:
   3233                 slirp_allow(optarg, IPPROTO_TCP);
   3234                 break;
   3235             case QEMU_OPTION_allow_udp:
   3236                 slirp_allow(optarg, IPPROTO_UDP);
   3237                 break;
   3238              case QEMU_OPTION_drop_log:
   3239                 {
   3240                     FILE* drop_log_fd;
   3241                     drop_log_filename = optarg;
   3242                     drop_log_fd = fopen(optarg, "w+");
   3243 
   3244                     if (!drop_log_fd) {
   3245                         fprintf(stderr, "Cannot open drop log: %s\n", optarg);
   3246                         exit(1);
   3247                     }
   3248 
   3249                     slirp_drop_log_fd(drop_log_fd);
   3250                 }
   3251                 break;
   3252 
   3253             case QEMU_OPTION_dns_log:
   3254                 {
   3255                     FILE* dns_log_fd;
   3256                     dns_log_filename = optarg;
   3257                     dns_log_fd = fopen(optarg, "wb+");
   3258 
   3259                     if (dns_log_fd == NULL) {
   3260                         fprintf(stderr, "Cannot open dns log: %s\n", optarg);
   3261                         exit(1);
   3262                     }
   3263 
   3264                     slirp_dns_log_fd(dns_log_fd);
   3265                 }
   3266                 break;
   3267 
   3268 
   3269             case QEMU_OPTION_max_dns_conns:
   3270                 {
   3271                     int max_dns_conns = 0;
   3272                     if (parse_int(optarg, &max_dns_conns)) {
   3273                       fprintf(stderr,
   3274                               "qemu: syntax: -max-dns-conns max_connections\n");
   3275                       exit(1);
   3276                     }
   3277                     if (max_dns_conns <= 0 ||  max_dns_conns == LONG_MAX) {
   3278                       fprintf(stderr,
   3279                               "Invalid arg for max dns connections: %s\n",
   3280                               optarg);
   3281                       exit(1);
   3282                     }
   3283                     slirp_set_max_dns_conns(max_dns_conns);
   3284                 }
   3285                 break;
   3286 
   3287             case QEMU_OPTION_net_forward:
   3288                 net_slirp_forward(optarg);
   3289                 break;
   3290             case QEMU_OPTION_net_forward_tcp2sink:
   3291                 {
   3292                     SockAddress saddr;
   3293 
   3294                     if (parse_host_port(&saddr, optarg)) {
   3295                         fprintf(stderr,
   3296                                 "Invalid ip/port %s for "
   3297                                 "-forward-dropped-tcp2sink. "
   3298                                 "We expect 'sink_ip:sink_port'\n",
   3299                                 optarg);
   3300                         exit(1);
   3301                     }
   3302                     slirp_forward_dropped_tcp2sink(saddr.u.inet.address,
   3303                                                    saddr.u.inet.port);
   3304                 }
   3305                 break;
   3306             /* -------------------------------------------------------*/
   3307 
   3308             case QEMU_OPTION_tb_size:
   3309                 tb_size = strtol(optarg, NULL, 0);
   3310                 if (tb_size < 0)
   3311                     tb_size = 0;
   3312                 break;
   3313             case QEMU_OPTION_icount:
   3314                 icount_option = optarg;
   3315                 break;
   3316             case QEMU_OPTION_incoming:
   3317                 incoming = optarg;
   3318                 break;
   3319 #ifdef CONFIG_XEN
   3320             case QEMU_OPTION_xen_domid:
   3321                 xen_domid = atoi(optarg);
   3322                 break;
   3323             case QEMU_OPTION_xen_create:
   3324                 xen_mode = XEN_CREATE;
   3325                 break;
   3326             case QEMU_OPTION_xen_attach:
   3327                 xen_mode = XEN_ATTACH;
   3328                 break;
   3329 #endif
   3330 
   3331 
   3332             case QEMU_OPTION_mic:
   3333                 audio_input_source = (char*)optarg;
   3334                 break;
   3335 #ifdef CONFIG_TRACE
   3336             case QEMU_OPTION_trace:
   3337                 trace_filename = optarg;
   3338                 tracing = 1;
   3339                 break;
   3340 #if 0
   3341             case QEMU_OPTION_trace_miss:
   3342                 trace_cache_miss = 1;
   3343                 break;
   3344             case QEMU_OPTION_trace_addr:
   3345                 trace_all_addr = 1;
   3346                 break;
   3347 #endif
   3348             case QEMU_OPTION_tracing:
   3349                 if (strcmp(optarg, "off") == 0)
   3350                     tracing = 0;
   3351                 else if (strcmp(optarg, "on") == 0 && trace_filename)
   3352                     tracing = 1;
   3353                 else {
   3354                     PANIC("Unexpected option to -tracing ('%s')",
   3355                             optarg);
   3356                 }
   3357                 break;
   3358 #if 0
   3359             case QEMU_OPTION_dcache_load_miss:
   3360                 dcache_load_miss_penalty = atoi(optarg);
   3361                 break;
   3362             case QEMU_OPTION_dcache_store_miss:
   3363                 dcache_store_miss_penalty = atoi(optarg);
   3364                 break;
   3365 #endif
   3366 #endif
   3367 #ifdef CONFIG_NAND
   3368             case QEMU_OPTION_nand:
   3369                 nand_add_dev(optarg);
   3370                 break;
   3371 
   3372 #endif
   3373             case QEMU_OPTION_disable_hax:
   3374                 hax_disabled = 1;
   3375                 break;
   3376             case QEMU_OPTION_android_ports:
   3377                 android_op_ports = (char*)optarg;
   3378                 break;
   3379 
   3380             case QEMU_OPTION_android_port:
   3381                 android_op_port = (char*)optarg;
   3382                 break;
   3383 
   3384             case QEMU_OPTION_android_report_console:
   3385                 android_op_report_console = (char*)optarg;
   3386                 break;
   3387 
   3388             case QEMU_OPTION_http_proxy:
   3389                 op_http_proxy = (char*)optarg;
   3390                 break;
   3391 
   3392             case QEMU_OPTION_charmap:
   3393                 op_charmap_file = (char*)optarg;
   3394                 break;
   3395 
   3396             case QEMU_OPTION_android_hw:
   3397                 android_op_hwini = (char*)optarg;
   3398                 break;
   3399 
   3400             case QEMU_OPTION_dns_server:
   3401                 android_op_dns_server = (char*)optarg;
   3402                 break;
   3403 
   3404             case QEMU_OPTION_radio:
   3405                 android_op_radio = (char*)optarg;
   3406                 break;
   3407 
   3408             case QEMU_OPTION_gps:
   3409                 android_op_gps = (char*)optarg;
   3410                 break;
   3411 
   3412             case QEMU_OPTION_audio:
   3413                 android_op_audio = (char*)optarg;
   3414                 break;
   3415 
   3416             case QEMU_OPTION_cpu_delay:
   3417                 android_op_cpu_delay = (char*)optarg;
   3418                 break;
   3419 
   3420             case QEMU_OPTION_show_kernel:
   3421                 android_kmsg_init(ANDROID_KMSG_PRINT_MESSAGES);
   3422                 break;
   3423 
   3424 #ifdef CONFIG_NAND_LIMITS
   3425             case QEMU_OPTION_nand_limits:
   3426                 android_op_nand_limits = (char*)optarg;
   3427                 break;
   3428 #endif  // CONFIG_NAND_LIMITS
   3429 
   3430             case QEMU_OPTION_netspeed:
   3431                 android_op_netspeed = (char*)optarg;
   3432                 break;
   3433 
   3434             case QEMU_OPTION_netdelay:
   3435                 android_op_netdelay = (char*)optarg;
   3436                 break;
   3437 
   3438             case QEMU_OPTION_netfast:
   3439                 android_op_netfast = 1;
   3440                 break;
   3441 
   3442             case QEMU_OPTION_tcpdump:
   3443                 android_op_tcpdump = (char*)optarg;
   3444                 break;
   3445 
   3446             case QEMU_OPTION_boot_property:
   3447                 boot_property_parse_option((char*)optarg);
   3448                 break;
   3449 
   3450             case QEMU_OPTION_lcd_density:
   3451                 android_op_lcd_density = (char*)optarg;
   3452                 break;
   3453 
   3454             case QEMU_OPTION_ui_port:
   3455                 android_op_ui_port = (char*)optarg;
   3456                 break;
   3457 
   3458             case QEMU_OPTION_ui_settings:
   3459                 android_op_ui_settings = (char*)optarg;
   3460                 break;
   3461 
   3462             case QEMU_OPTION_audio_test_out:
   3463                 android_audio_test_start_out();
   3464                 break;
   3465 
   3466             case QEMU_OPTION_android_avdname:
   3467                 android_op_avd_name = (char*)optarg;
   3468                 break;
   3469 
   3470             case QEMU_OPTION_timezone:
   3471                 if (timezone_set((char*)optarg)) {
   3472                     fprintf(stderr, "emulator: it seems the timezone '%s' is not in zoneinfo format\n",
   3473                             (char*)optarg);
   3474                 }
   3475                 break;
   3476 
   3477 #ifdef CONFIG_MEMCHECK
   3478             case QEMU_OPTION_android_memcheck:
   3479                 android_op_memcheck = (char*)optarg;
   3480                 /* This will set ro.kernel.memcheck system property
   3481                  * to memcheck's tracing flags. */
   3482                 stralloc_add_format(kernel_config, " memcheck=%s", android_op_memcheck);
   3483                 break;
   3484 #endif // CONFIG_MEMCHECK
   3485 
   3486             case QEMU_OPTION_snapshot_no_time_update:
   3487                 android_snapshot_update_time = 0;
   3488                 break;
   3489 
   3490             case QEMU_OPTION_list_webcam:
   3491                 android_list_web_cameras();
   3492                 exit(0);
   3493 
   3494             default:
   3495                 os_parse_cmd_args(popt->index, optarg);
   3496             }
   3497         }
   3498     }
   3499 
   3500     /* Initialize character map. */
   3501     if (android_charmap_setup(op_charmap_file)) {
   3502         if (op_charmap_file) {
   3503             PANIC(
   3504                     "Unable to initialize character map from file %s.",
   3505                     op_charmap_file);
   3506         } else {
   3507             PANIC(
   3508                     "Unable to initialize default character map.");
   3509         }
   3510     }
   3511 
   3512     /* If no data_dir is specified then try to find it relative to the
   3513        executable path.  */
   3514     if (!data_dir) {
   3515         data_dir = find_datadir(argv[0]);
   3516     }
   3517     /* If all else fails use the install patch specified when building.  */
   3518     if (!data_dir) {
   3519         data_dir = CONFIG_QEMU_SHAREDIR;
   3520     }
   3521 
   3522     if (!android_op_hwini) {
   3523         PANIC("Missing -android-hw <file> option!");
   3524     }
   3525     hw_ini = iniFile_newFromFile(android_op_hwini);
   3526     if (hw_ini == NULL) {
   3527         PANIC("Could not find %s file.", android_op_hwini);
   3528     }
   3529 
   3530     androidHwConfig_init(android_hw, 0);
   3531     androidHwConfig_read(android_hw, hw_ini);
   3532 
   3533     /* If we're loading VM from a snapshot, make sure that the current HW config
   3534      * matches the one with which the VM has been saved. */
   3535     if (loadvm && *loadvm && !snaphost_match_configs(hw_ini, loadvm)) {
   3536         exit(0);
   3537     }
   3538 
   3539     iniFile_free(hw_ini);
   3540 
   3541     {
   3542         int width  = android_hw->hw_lcd_width;
   3543         int height = android_hw->hw_lcd_height;
   3544         int depth  = android_hw->hw_lcd_depth;
   3545 
   3546         /* A bit of sanity checking */
   3547         if (width <= 0 || height <= 0    ||
   3548             (depth != 16 && depth != 32) ||
   3549             (((width|height) & 3) != 0)  )
   3550         {
   3551             PANIC("Invalid display configuration (%d,%d,%d)",
   3552                   width, height, depth);
   3553         }
   3554         android_display_width  = width;
   3555         android_display_height = height;
   3556         android_display_bpp    = depth;
   3557     }
   3558 
   3559 #ifdef CONFIG_NAND_LIMITS
   3560     /* Init nand stuff. */
   3561     if (android_op_nand_limits) {
   3562         parse_nand_limits(android_op_nand_limits);
   3563     }
   3564 #endif  // CONFIG_NAND_LIMITS
   3565 
   3566     /* Initialize AVD name from hardware configuration if needed */
   3567     if (!android_op_avd_name) {
   3568         if (android_hw->avd_name && *android_hw->avd_name) {
   3569             android_op_avd_name = android_hw->avd_name;
   3570             VERBOSE_PRINT(init,"AVD Name: %s", android_op_avd_name);
   3571         }
   3572     }
   3573 
   3574     /* Initialize system partition image */
   3575     {
   3576         char        tmp[PATH_MAX+32];
   3577         const char* sysImage = android_hw->disk_systemPartition_path;
   3578         const char* initImage = android_hw->disk_systemPartition_initPath;
   3579         uint64_t    sysBytes = android_hw->disk_systemPartition_size;
   3580 
   3581         if (sysBytes == 0) {
   3582             PANIC("Invalid system partition size: %" PRIu64, sysBytes);
   3583         }
   3584 
   3585         snprintf(tmp,sizeof(tmp),"system,size=0x%" PRIx64, sysBytes);
   3586 
   3587         if (sysImage && *sysImage) {
   3588             if (filelock_create(sysImage) == NULL) {
   3589                 fprintf(stderr,"WARNING: System image already in use, changes will not persist!\n");
   3590                 /* If there is no file= parameters, nand_add_dev will create
   3591                  * a temporary file to back the partition image. */
   3592             } else {
   3593                 pstrcat(tmp,sizeof(tmp),",file=");
   3594                 pstrcat(tmp,sizeof(tmp),sysImage);
   3595             }
   3596         }
   3597         if (initImage && *initImage) {
   3598             if (!path_exists(initImage)) {
   3599                 PANIC("Invalid initial system image path: %s", initImage);
   3600             }
   3601             pstrcat(tmp,sizeof(tmp),",initfile=");
   3602             pstrcat(tmp,sizeof(tmp),initImage);
   3603         } else {
   3604             PANIC("Missing initial system image path!");
   3605         }
   3606         nand_add_dev(tmp);
   3607     }
   3608 
   3609     /* Initialize data partition image */
   3610     {
   3611         char        tmp[PATH_MAX+32];
   3612         const char* dataImage = android_hw->disk_dataPartition_path;
   3613         const char* initImage = android_hw->disk_dataPartition_initPath;
   3614         uint64_t    dataBytes = android_hw->disk_dataPartition_size;
   3615 
   3616         if (dataBytes == 0) {
   3617             PANIC("Invalid data partition size: %" PRIu64, dataBytes);
   3618         }
   3619 
   3620         snprintf(tmp,sizeof(tmp),"userdata,size=0x%" PRIx64, dataBytes);
   3621 
   3622         if (dataImage && *dataImage) {
   3623             if (filelock_create(dataImage) == NULL) {
   3624                 fprintf(stderr, "WARNING: Data partition already in use. Changes will not persist!\n");
   3625                 /* Note: if there is no file= parameters, nand_add_dev() will
   3626                  *       create a temporary file to back the partition image. */
   3627             } else {
   3628                 /* Create the file if needed */
   3629                 if (!path_exists(dataImage)) {
   3630                     if (path_empty_file(dataImage) < 0) {
   3631                         PANIC("Could not create data image file %s: %s", dataImage, strerror(errno));
   3632                     }
   3633                 }
   3634                 pstrcat(tmp, sizeof(tmp), ",file=");
   3635                 pstrcat(tmp, sizeof(tmp), dataImage);
   3636             }
   3637         }
   3638         if (initImage && *initImage) {
   3639             pstrcat(tmp, sizeof(tmp), ",initfile=");
   3640             pstrcat(tmp, sizeof(tmp), initImage);
   3641         }
   3642         nand_add_dev(tmp);
   3643     }
   3644 
   3645     /* Init SD-Card stuff. For Android, it is always hda */
   3646     /* If the -hda option was used, ignore the Android-provided one */
   3647     if (hda_opts == NULL) {
   3648         const char* sdPath = android_hw->hw_sdCard_path;
   3649         if (sdPath && *sdPath) {
   3650             if (!path_exists(sdPath)) {
   3651                 fprintf(stderr, "WARNING: SD Card image is missing: %s\n", sdPath);
   3652             } else if (filelock_create(sdPath) == NULL) {
   3653                 fprintf(stderr, "WARNING: SD Card image already in use: %s\n", sdPath);
   3654             } else {
   3655                 /* Successful locking */
   3656                 hda_opts = drive_add(sdPath, HD_ALIAS, 0);
   3657                 /* Set this property of any operation involving the SD Card
   3658                  * will be x100 slower, due to the corresponding file being
   3659                  * mounted as O_DIRECT. Note that this is only 'unsafe' in
   3660                  * the context of an emulator crash. The data is already
   3661                  * synced properly when the emulator exits (either normally or through ^C).
   3662                  */
   3663                 qemu_opt_set(hda_opts, "cache", "unsafe");
   3664             }
   3665         }
   3666     }
   3667 
   3668     if (hdb_opts == NULL) {
   3669         const char* spath = android_hw->disk_snapStorage_path;
   3670         if (spath && *spath) {
   3671             if (!path_exists(spath)) {
   3672                 PANIC("Snapshot storage file does not exist: %s", spath);
   3673             }
   3674             if (filelock_create(spath) == NULL) {
   3675                 PANIC("Snapshot storage already in use: %s", spath);
   3676             }
   3677             hdb_opts = drive_add(spath, HD_ALIAS, 1);
   3678             /* See comment above to understand why this is needed. */
   3679             qemu_opt_set(hdb_opts, "cache", "unsafe");
   3680         }
   3681     }
   3682 
   3683     /* Set the VM's max heap size, passed as a boot property */
   3684     if (android_hw->vm_heapSize > 0) {
   3685         char  tmp[64];
   3686         snprintf(tmp, sizeof(tmp), "%dm", android_hw->vm_heapSize);
   3687         boot_property_add("dalvik.vm.heapsize",tmp);
   3688     }
   3689 
   3690     /* Initialize net speed and delays stuff. */
   3691     if (android_parse_network_speed(android_op_netspeed) < 0 ) {
   3692         PANIC("invalid -netspeed parameter '%s'",
   3693                 android_op_netspeed);
   3694     }
   3695 
   3696     if ( android_parse_network_latency(android_op_netdelay) < 0 ) {
   3697         PANIC("invalid -netdelay parameter '%s'",
   3698                 android_op_netdelay);
   3699     }
   3700 
   3701     if (android_op_netfast) {
   3702         qemu_net_download_speed = 0;
   3703         qemu_net_upload_speed = 0;
   3704         qemu_net_min_latency = 0;
   3705         qemu_net_max_latency = 0;
   3706     }
   3707 
   3708     /* Initialize LCD density */
   3709     if (android_hw->hw_lcd_density) {
   3710         long density = android_hw->hw_lcd_density;
   3711         if (density <= 0) {
   3712             PANIC("Invalid hw.lcd.density value: %ld", density);
   3713         }
   3714         hwLcd_setBootProperty(density);
   3715     }
   3716 
   3717     /* Initialize presence of hardware nav button */
   3718     boot_property_add("qemu.hw.mainkeys", android_hw->hw_mainKeys ? "1" : "0");
   3719 
   3720     /* Initialize TCP dump */
   3721     if (android_op_tcpdump) {
   3722         if (qemu_tcpdump_start(android_op_tcpdump) < 0) {
   3723             fprintf(stdout, "could not start packet capture: %s\n", strerror(errno));
   3724         }
   3725     }
   3726 
   3727     /* Initialize modem */
   3728     if (android_op_radio) {
   3729         CharDriverState*  cs = qemu_chr_open("radio", android_op_radio, NULL);
   3730         if (cs == NULL) {
   3731             PANIC("unsupported character device specification: %s\n"
   3732                         "used -help-char-devices for list of available formats",
   3733                     android_op_radio);
   3734         }
   3735         android_qemud_set_channel( ANDROID_QEMUD_GSM, cs);
   3736     } else if (android_hw->hw_gsmModem != 0 ) {
   3737         if ( android_qemud_get_channel( ANDROID_QEMUD_GSM, &android_modem_cs ) < 0 ) {
   3738             PANIC("could not initialize qemud 'gsm' channel");
   3739         }
   3740     }
   3741 
   3742     /* Initialize GPS */
   3743     if (android_op_gps) {
   3744         CharDriverState*  cs = qemu_chr_open("gps", android_op_gps, NULL);
   3745         if (cs == NULL) {
   3746             PANIC("unsupported character device specification: %s\n"
   3747                         "used -help-char-devices for list of available formats",
   3748                     android_op_gps);
   3749         }
   3750         android_qemud_set_channel( ANDROID_QEMUD_GPS, cs);
   3751     } else if (android_hw->hw_gps != 0) {
   3752         if ( android_qemud_get_channel( "gps", &android_gps_cs ) < 0 ) {
   3753             PANIC("could not initialize qemud 'gps' channel");
   3754         }
   3755     }
   3756 
   3757     /* Initialize audio. */
   3758     if (android_op_audio) {
   3759         if ( !audio_check_backend_name( 0, android_op_audio ) ) {
   3760             PANIC("'%s' is not a valid audio output backend. see -help-audio-out",
   3761                     android_op_audio);
   3762         }
   3763         setenv("QEMU_AUDIO_DRV", android_op_audio, 1);
   3764     }
   3765 
   3766     /* Initialize OpenGLES emulation */
   3767     //android_hw_opengles_init();
   3768 
   3769     /* Initialize fake camera */
   3770     if (strcmp(android_hw->hw_camera_back, "emulated") &&
   3771         strcmp(android_hw->hw_camera_front, "emulated")) {
   3772         /* Fake camera is not used for camera emulation. */
   3773         boot_property_add("qemu.sf.fake_camera", "none");
   3774     } else {
   3775         /* Fake camera is used for at least one camera emulation. */
   3776         if (!strcmp(android_hw->hw_camera_back, "emulated") &&
   3777             !strcmp(android_hw->hw_camera_front, "emulated")) {
   3778             /* Fake camera is used for both, front and back camera emulation. */
   3779             boot_property_add("qemu.sf.fake_camera", "both");
   3780         } else if (!strcmp(android_hw->hw_camera_back, "emulated")) {
   3781             boot_property_add("qemu.sf.fake_camera", "back");
   3782         } else {
   3783             boot_property_add("qemu.sf.fake_camera", "front");
   3784         }
   3785     }
   3786 
   3787     /* Set LCD density (if required by -qemu, and AVD is missing it. */
   3788     if (android_op_lcd_density && !android_hw->hw_lcd_density) {
   3789         int density;
   3790         if (parse_int(android_op_lcd_density, &density) || density <= 0) {
   3791             PANIC("-lcd-density : %d", density);
   3792         }
   3793         hwLcd_setBootProperty(density);
   3794     }
   3795 
   3796     /* Initialize camera emulation. */
   3797     android_camera_service_init();
   3798 
   3799     if (android_op_cpu_delay) {
   3800         char*   end;
   3801         long    delay = strtol(android_op_cpu_delay, &end, 0);
   3802         if (end == NULL || *end || delay < 0 || delay > 1000 ) {
   3803             PANIC("option -cpu-delay must be an integer between 0 and 1000" );
   3804         }
   3805         if (delay > 0)
   3806             delay = (1000-delay);
   3807 
   3808         qemu_cpu_delay = (int) delay;
   3809     }
   3810 
   3811     if (android_op_dns_server) {
   3812         char*  x = strchr(android_op_dns_server, ',');
   3813         dns_count = 0;
   3814         if (x == NULL)
   3815         {
   3816             if ( add_dns_server( android_op_dns_server ) == 0 )
   3817                 dns_count = 1;
   3818         }
   3819         else
   3820         {
   3821             x = android_op_dns_server;
   3822             while (*x) {
   3823                 char*  y = strchr(x, ',');
   3824 
   3825                 if (y != NULL) {
   3826                     *y = 0;
   3827                     y++;
   3828                 } else {
   3829                     y = x + strlen(x);
   3830                 }
   3831 
   3832                 if (y > x && add_dns_server( x ) == 0) {
   3833                     dns_count += 1;
   3834                 }
   3835                 x = y;
   3836             }
   3837         }
   3838         if (dns_count == 0)
   3839             fprintf( stdout, "### WARNING: will use system default DNS server\n" );
   3840     }
   3841 
   3842     if (dns_count == 0)
   3843         dns_count = slirp_get_system_dns_servers();
   3844     if (dns_count) {
   3845         stralloc_add_format(kernel_config, " ndns=%d", dns_count);
   3846     }
   3847 
   3848 #ifdef CONFIG_MEMCHECK
   3849     if (android_op_memcheck) {
   3850         memcheck_init(android_op_memcheck);
   3851     }
   3852 #endif  // CONFIG_MEMCHECK
   3853 
   3854     /* Initialize cache partition, if any */
   3855     if (android_hw->disk_cachePartition != 0) {
   3856         char        tmp[PATH_MAX+32];
   3857         const char* partPath = android_hw->disk_cachePartition_path;
   3858         uint64_t    partSize = android_hw->disk_cachePartition_size;
   3859 
   3860         snprintf(tmp,sizeof(tmp),"cache,size=0x%" PRIx64, partSize);
   3861 
   3862         if (partPath && *partPath && strcmp(partPath, "<temp>") != 0) {
   3863             if (filelock_create(partPath) == NULL) {
   3864                 fprintf(stderr, "WARNING: Cache partition already in use. Changes will not persist!\n");
   3865                 /* Note: if there is no file= parameters, nand_add_dev() will
   3866                  *       create a temporary file to back the partition image. */
   3867             } else {
   3868                 /* Create the file if needed */
   3869                 if (!path_exists(partPath)) {
   3870                     if (path_empty_file(partPath) < 0) {
   3871                         PANIC("Could not create cache image file %s: %s", partPath, strerror(errno));
   3872                     }
   3873                 }
   3874                 pstrcat(tmp, sizeof(tmp), ",file=");
   3875                 pstrcat(tmp, sizeof(tmp), partPath);
   3876             }
   3877         }
   3878         nand_add_dev(tmp);
   3879     }
   3880 
   3881     /* qemu.gles will be read by the OpenGL ES emulation libraries.
   3882      * If set to 0, the software GL ES renderer will be used as a fallback.
   3883      * If the parameter is undefined, this means the system image runs
   3884      * inside an emulator that doesn't support GPU emulation at all.
   3885      *
   3886      * We always start the GL ES renderer so we can gather stats on the
   3887      * underlying GL implementation. If GL ES acceleration is disabled,
   3888      * we just shut it down again once we have the strings. */
   3889     {
   3890         int qemu_gles = 0;
   3891         if (android_initOpenglesEmulation() == 0 &&
   3892             android_startOpenglesRenderer(android_hw->hw_lcd_width, android_hw->hw_lcd_height) == 0)
   3893         {
   3894             android_getOpenglesHardwareStrings(
   3895                     android_gl_vendor, sizeof(android_gl_vendor),
   3896                     android_gl_renderer, sizeof(android_gl_renderer),
   3897                     android_gl_version, sizeof(android_gl_version));
   3898             if (android_hw->hw_gpu_enabled) {
   3899                 qemu_gles = 1;
   3900             } else {
   3901                 android_stopOpenglesRenderer();
   3902                 qemu_gles = 0;
   3903             }
   3904         } else {
   3905             dwarning("Could not initialize OpenglES emulation, using software renderer.");
   3906         }
   3907         if (qemu_gles) {
   3908             stralloc_add_str(kernel_params, " qemu.gles=1");
   3909         } else {
   3910             stralloc_add_str(kernel_params, " qemu.gles=0");
   3911         }
   3912     }
   3913 
   3914     /* We always force qemu=1 when running inside QEMU */
   3915     stralloc_add_str(kernel_params, " qemu=1");
   3916 
   3917     /* We always initialize the first serial port for the android-kmsg
   3918      * character device (used to send kernel messages) */
   3919     serial_hds_add_at(0, "android-kmsg");
   3920     stralloc_add_str(kernel_params, " console=ttyS0");
   3921 
   3922     /* We always initialize the second serial port for the android-qemud
   3923      * character device as well */
   3924     serial_hds_add_at(1, "android-qemud");
   3925     stralloc_add_str(kernel_params, " android.qemud=ttyS1");
   3926 
   3927     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
   3928         os_pidfile_error();
   3929         exit(1);
   3930     }
   3931 
   3932 #if defined(CONFIG_KVM)
   3933     if (kvm_allowed < 0) {
   3934         kvm_allowed = kvm_check_allowed();
   3935     }
   3936 #endif
   3937 
   3938 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
   3939     if (kvm_allowed && kqemu_allowed) {
   3940         PANIC(
   3941                 "You can not enable both KVM and kqemu at the same time");
   3942     }
   3943 #endif
   3944 
   3945     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
   3946     if (smp_cpus > machine->max_cpus) {
   3947         PANIC("Number of SMP cpus requested (%d), exceeds max cpus "
   3948                 "supported by machine `%s' (%d)", smp_cpus,  machine->name,
   3949                 machine->max_cpus);
   3950     }
   3951 
   3952     if (display_type == DT_NOGRAPHIC) {
   3953        if (serial_device_index == 0)
   3954            serial_devices[0] = "stdio";
   3955        if (parallel_device_index == 0)
   3956            parallel_devices[0] = "null";
   3957        if (strncmp(monitor_device, "vc", 2) == 0)
   3958            monitor_device = "stdio";
   3959     }
   3960 
   3961 #ifdef CONFIG_KQEMU
   3962     if (smp_cpus > 1)
   3963         kqemu_allowed = 0;
   3964 #endif
   3965     if (qemu_init_main_loop()) {
   3966         PANIC("qemu_init_main_loop failed");
   3967     }
   3968 
   3969     if (kernel_filename == NULL) {
   3970         kernel_filename = android_hw->kernel_path;
   3971     }
   3972     if (initrd_filename == NULL) {
   3973         initrd_filename = android_hw->disk_ramdisk_path;
   3974     }
   3975 
   3976     linux_boot = (kernel_filename != NULL);
   3977     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
   3978 
   3979     if (!linux_boot && *kernel_cmdline != '\0') {
   3980         PANIC("-append only allowed with -kernel option");
   3981     }
   3982 
   3983     if (!linux_boot && initrd_filename != NULL) {
   3984         PANIC("-initrd only allowed with -kernel option");
   3985     }
   3986 
   3987     /* boot to floppy or the default cd if no hard disk defined yet */
   3988     if (!boot_devices[0]) {
   3989         boot_devices = "cad";
   3990     }
   3991     os_set_line_buffering();
   3992 
   3993     if (init_timer_alarm() < 0) {
   3994         PANIC("could not initialize alarm timer");
   3995     }
   3996     configure_icount(icount_option);
   3997 
   3998     /* init network clients */
   3999     if (nb_net_clients == 0) {
   4000         /* if no clients, we use a default config */
   4001         net_clients[nb_net_clients++] = "nic";
   4002 #ifdef CONFIG_SLIRP
   4003         net_clients[nb_net_clients++] = "user";
   4004 #endif
   4005     }
   4006 
   4007     for(i = 0;i < nb_net_clients; i++) {
   4008         if (net_client_parse(net_clients[i]) < 0) {
   4009             PANIC("Unable to parse net clients");
   4010         }
   4011     }
   4012     net_client_check();
   4013 
   4014 #ifdef TARGET_I386
   4015     /* XXX: this should be moved in the PC machine instantiation code */
   4016     if (net_boot != 0) {
   4017         int netroms = 0;
   4018 	for (i = 0; i < nb_nics && i < 4; i++) {
   4019 	    const char *model = nd_table[i].model;
   4020 	    char buf[1024];
   4021             char *filename;
   4022             if (net_boot & (1 << i)) {
   4023                 if (model == NULL)
   4024                     model = "ne2k_pci";
   4025                 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
   4026                 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
   4027                 if (filename && get_image_size(filename) > 0) {
   4028                     if (nb_option_roms >= MAX_OPTION_ROMS) {
   4029                         PANIC("Too many option ROMs");
   4030                     }
   4031                     option_rom[nb_option_roms] = qemu_strdup(buf);
   4032                     nb_option_roms++;
   4033                     netroms++;
   4034                 }
   4035                 if (filename) {
   4036                     qemu_free(filename);
   4037                 }
   4038             }
   4039 	}
   4040 	if (netroms == 0) {
   4041 	    PANIC("No valid PXE rom found for network device");
   4042 	}
   4043     }
   4044 #endif
   4045 
   4046     /* init the bluetooth world */
   4047     for (i = 0; i < nb_bt_opts; i++)
   4048         if (bt_parse(bt_opts[i])) {
   4049             PANIC("Unable to parse bluetooth options");
   4050         }
   4051 
   4052     /* init the memory */
   4053     if (ram_size == 0) {
   4054         ram_size = android_hw->hw_ramSize * 1024LL * 1024;
   4055         if (ram_size == 0) {
   4056             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
   4057         }
   4058     }
   4059 
   4060     /* Quite often (especially on older XP machines) attempts to allocate large
   4061      * VM RAM is going to fail, and crash the emulator. Since it's failing deep
   4062      * inside QEMU, it's not really possible to provide the user with a
   4063      * meaningful explanation for the crash. So, lets see if QEMU is going to be
   4064      * able to allocate requested amount of RAM, and if not, lets try to come up
   4065      * with a recomendation. */
   4066     {
   4067         ram_addr_t r_ram = ram_size;
   4068         void* alloc_check = malloc(r_ram);
   4069         while (alloc_check == NULL && r_ram > 1024 * 1024) {
   4070         /* Make it 25% less */
   4071             r_ram -= r_ram / 4;
   4072             alloc_check = malloc(r_ram);
   4073         }
   4074         if (alloc_check != NULL) {
   4075             free(alloc_check);
   4076         }
   4077         if (r_ram != ram_size) {
   4078             /* Requested RAM is too large. Report this, as well as calculated
   4079              * recomendation. */
   4080             dwarning("Requested RAM size of %dMB is too large for your environment, and is reduced to %dMB.",
   4081                      (int)(ram_size / 1024 / 1024), (int)(r_ram / 1024 / 1024));
   4082             ram_size = r_ram;
   4083         }
   4084     }
   4085 
   4086 #ifdef CONFIG_KQEMU
   4087     /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
   4088        guest ram allocation.  It needs to go away.  */
   4089     if (kqemu_allowed) {
   4090         kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
   4091         kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
   4092         if (!kqemu_phys_ram_base) {
   4093             PANIC("Could not allocate physical memory");
   4094         }
   4095     }
   4096 #endif
   4097 
   4098 #ifndef _WIN32
   4099     init_qemu_clear_logs_sig();
   4100 #endif
   4101 
   4102     /* init the dynamic translator */
   4103     cpu_exec_init_all(tb_size * 1024 * 1024);
   4104 
   4105     bdrv_init();
   4106 
   4107     /* we always create the cdrom drive, even if no disk is there */
   4108 #if 0
   4109     if (nb_drives_opt < MAX_DRIVES)
   4110         drive_add(NULL, CDROM_ALIAS);
   4111 
   4112     /* we always create at least one floppy */
   4113 
   4114     if (nb_drives_opt < MAX_DRIVES)
   4115         drive_add(NULL, FD_ALIAS, 0);
   4116     /* we always create one sd slot, even if no card is in it */
   4117 
   4118     if (1) {
   4119         drive_add(NULL, SD_ALIAS);
   4120     }
   4121 #endif
   4122 
   4123     /* open the virtual block devices */
   4124     if (snapshot)
   4125         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
   4126     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
   4127         exit(1);
   4128 
   4129     //register_savevm("timer", 0, 2, timer_save, timer_load, &timers_state);
   4130     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
   4131 
   4132     /* must be after terminal init, SDL library changes signal handlers */
   4133     os_setup_signal_handling();
   4134 
   4135     /* Maintain compatibility with multiple stdio monitors */
   4136     if (!strcmp(monitor_device,"stdio")) {
   4137         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
   4138             const char *devname = serial_devices[i];
   4139             if (devname && !strcmp(devname,"mon:stdio")) {
   4140                 monitor_device = NULL;
   4141                 break;
   4142             } else if (devname && !strcmp(devname,"stdio")) {
   4143                 monitor_device = NULL;
   4144                 serial_devices[i] = "mon:stdio";
   4145                 break;
   4146             }
   4147         }
   4148     }
   4149 
   4150     if (nb_numa_nodes > 0) {
   4151         int i;
   4152 
   4153         if (nb_numa_nodes > smp_cpus) {
   4154             nb_numa_nodes = smp_cpus;
   4155         }
   4156 
   4157         /* If no memory size if given for any node, assume the default case
   4158          * and distribute the available memory equally across all nodes
   4159          */
   4160         for (i = 0; i < nb_numa_nodes; i++) {
   4161             if (node_mem[i] != 0)
   4162                 break;
   4163         }
   4164         if (i == nb_numa_nodes) {
   4165             uint64_t usedmem = 0;
   4166 
   4167             /* On Linux, the each node's border has to be 8MB aligned,
   4168              * the final node gets the rest.
   4169              */
   4170             for (i = 0; i < nb_numa_nodes - 1; i++) {
   4171                 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
   4172                 usedmem += node_mem[i];
   4173             }
   4174             node_mem[i] = ram_size - usedmem;
   4175         }
   4176 
   4177         for (i = 0; i < nb_numa_nodes; i++) {
   4178             if (node_cpumask[i] != 0)
   4179                 break;
   4180         }
   4181         /* assigning the VCPUs round-robin is easier to implement, guest OSes
   4182          * must cope with this anyway, because there are BIOSes out there in
   4183          * real machines which also use this scheme.
   4184          */
   4185         if (i == nb_numa_nodes) {
   4186             for (i = 0; i < smp_cpus; i++) {
   4187                 node_cpumask[i % nb_numa_nodes] |= 1 << i;
   4188             }
   4189         }
   4190     }
   4191 
   4192     if (kvm_enabled()) {
   4193         int ret;
   4194 
   4195         ret = kvm_init(smp_cpus);
   4196         if (ret < 0) {
   4197             PANIC("failed to initialize KVM");
   4198         }
   4199     }
   4200 
   4201 #ifdef CONFIG_HAX
   4202     if (!hax_disabled)
   4203     {
   4204         int ret;
   4205 
   4206         hax_set_ramsize(ram_size);
   4207         ret = hax_init(smp_cpus);
   4208         fprintf(stderr, "HAX is %s and emulator runs in %s mode\n",
   4209             !ret ? "working" :"not working", !ret ? "fast virt" : "emulation");
   4210     }
   4211 #endif
   4212 
   4213     if (monitor_device) {
   4214         monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
   4215         if (!monitor_hd) {
   4216             PANIC("qemu: could not open monitor device '%s'",
   4217                               monitor_device);
   4218         }
   4219     }
   4220 
   4221     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   4222         serial_hds_add(serial_devices[i]);
   4223     }
   4224 
   4225     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   4226         const char *devname = parallel_devices[i];
   4227         if (devname && strcmp(devname, "none")) {
   4228             char label[32];
   4229             snprintf(label, sizeof(label), "parallel%d", i);
   4230             parallel_hds[i] = qemu_chr_open(label, devname, NULL);
   4231             if (!parallel_hds[i]) {
   4232                 PANIC("qemu: could not open parallel device '%s'",
   4233                         devname);
   4234             }
   4235         }
   4236     }
   4237 
   4238     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   4239         const char *devname = virtio_consoles[i];
   4240         if (devname && strcmp(devname, "none")) {
   4241             char label[32];
   4242             snprintf(label, sizeof(label), "virtcon%d", i);
   4243             virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
   4244             if (!virtcon_hds[i]) {
   4245                 PANIC("qemu: could not open virtio console '%s'",
   4246                         devname);
   4247             }
   4248         }
   4249     }
   4250 
   4251     module_call_init(MODULE_INIT_DEVICE);
   4252 
   4253 
   4254 #ifdef CONFIG_TRACE
   4255     if (trace_filename) {
   4256         trace_init(trace_filename);
   4257         fprintf(stderr, "-- When done tracing, exit the emulator. --\n");
   4258     }
   4259 #endif
   4260 
   4261     /* Check the CPU Architecture value */
   4262 #if defined(TARGET_ARM)
   4263     if (strcmp(android_hw->hw_cpu_arch,"arm") != 0) {
   4264         fprintf(stderr, "-- Invalid CPU architecture: %s, expected 'arm'\n",
   4265                 android_hw->hw_cpu_arch);
   4266         exit(1);
   4267     }
   4268 #elif defined(TARGET_I386)
   4269     if (strcmp(android_hw->hw_cpu_arch,"x86") != 0) {
   4270         fprintf(stderr, "-- Invalid CPU architecture: %s, expected 'x86'\n",
   4271                 android_hw->hw_cpu_arch);
   4272         exit(1);
   4273     }
   4274 #endif
   4275 
   4276     /* Grab CPU model if provided in hardware.ini */
   4277     if (    !cpu_model
   4278          && android_hw->hw_cpu_model
   4279          && android_hw->hw_cpu_model[0] != '\0')
   4280     {
   4281         cpu_model = android_hw->hw_cpu_model;
   4282     }
   4283 
   4284     /* Combine kernel command line passed from the UI with parameters
   4285      * collected during initialization.
   4286      *
   4287      * The order is the following:
   4288      * - parameters from the hw configuration (kernel.parameters)
   4289      * - additionnal parameters from options (e.g. -memcheck)
   4290      * - the -append parameters.
   4291      */
   4292     {
   4293         const char* kernel_parameters;
   4294 
   4295         if (android_hw->kernel_parameters) {
   4296             stralloc_add_c(kernel_params, ' ');
   4297             stralloc_add_str(kernel_params, android_hw->kernel_parameters);
   4298         }
   4299 
   4300         /* If not empty, kernel_config always contains a leading space */
   4301         stralloc_append(kernel_params, kernel_config);
   4302 
   4303         if (*kernel_cmdline) {
   4304             stralloc_add_c(kernel_params, ' ');
   4305             stralloc_add_str(kernel_params, kernel_cmdline);
   4306         }
   4307 
   4308         /* Remove any leading/trailing spaces */
   4309         stralloc_strip(kernel_params);
   4310 
   4311         kernel_parameters = stralloc_cstr(kernel_params);
   4312         VERBOSE_PRINT(init, "Kernel parameters: %s", kernel_parameters);
   4313 
   4314         machine->init(ram_size,
   4315                       boot_devices,
   4316                       kernel_filename,
   4317                       kernel_parameters,
   4318                       initrd_filename,
   4319                       cpu_model);
   4320 
   4321         /* Initialize multi-touch emulation. */
   4322         if (androidHwConfig_isScreenMultiTouch(android_hw)) {
   4323             mts_port_create(NULL);
   4324         }
   4325 
   4326         stralloc_reset(kernel_params);
   4327         stralloc_reset(kernel_config);
   4328     }
   4329 
   4330     for (env = first_cpu; env != NULL; env = env->next_cpu) {
   4331         for (i = 0; i < nb_numa_nodes; i++) {
   4332             if (node_cpumask[i] & (1 << env->cpu_index)) {
   4333                 env->numa_node = i;
   4334             }
   4335         }
   4336     }
   4337 
   4338     current_machine = machine;
   4339 
   4340     /* Set KVM's vcpu state to qemu's initial CPUState. */
   4341     if (kvm_enabled()) {
   4342         int ret;
   4343 
   4344         ret = kvm_sync_vcpus();
   4345         if (ret < 0) {
   4346             PANIC("failed to initialize vcpus");
   4347         }
   4348     }
   4349 
   4350 #ifdef CONFIG_HAX
   4351     if (hax_enabled())
   4352         hax_sync_vcpus();
   4353 #endif
   4354 
   4355     /* init USB devices */
   4356     if (usb_enabled) {
   4357         for(i = 0; i < usb_devices_index; i++) {
   4358             if (usb_device_add(usb_devices[i], 0) < 0) {
   4359                 fprintf(stderr, "Warning: could not add USB device %s\n",
   4360                         usb_devices[i]);
   4361             }
   4362         }
   4363     }
   4364 
   4365     /* just use the first displaystate for the moment */
   4366     ds = get_displaystate();
   4367 
   4368     /* Initialize display from the command line parameters. */
   4369     android_display_reset(ds,
   4370                           android_display_width,
   4371                           android_display_height,
   4372                           android_display_bpp);
   4373 
   4374     if (display_type == DT_DEFAULT) {
   4375 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
   4376         display_type = DT_SDL;
   4377 #else
   4378         display_type = DT_VNC;
   4379         vnc_display = "localhost:0,to=99";
   4380         show_vnc_port = 1;
   4381 #endif
   4382     }
   4383 
   4384 
   4385     switch (display_type) {
   4386     case DT_NOGRAPHIC:
   4387         break;
   4388 #if defined(CONFIG_CURSES)
   4389     case DT_CURSES:
   4390         curses_display_init(ds, full_screen);
   4391         break;
   4392 #endif
   4393 #if defined(CONFIG_SDL) && !defined(CONFIG_STANDALONE_CORE)
   4394     case DT_SDL:
   4395         sdl_display_init(ds, full_screen, no_frame);
   4396         break;
   4397 #elif defined(CONFIG_COCOA)
   4398     case DT_SDL:
   4399         cocoa_display_init(ds, full_screen);
   4400         break;
   4401 #elif defined(CONFIG_STANDALONE_CORE)
   4402     case DT_SDL:
   4403         coredisplay_init(ds);
   4404         break;
   4405 #endif
   4406     case DT_VNC:
   4407         vnc_display_init(ds);
   4408         if (vnc_display_open(ds, vnc_display) < 0) {
   4409             PANIC("Unable to initialize VNC display");
   4410         }
   4411 
   4412         if (show_vnc_port) {
   4413             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
   4414         }
   4415         break;
   4416     default:
   4417         break;
   4418     }
   4419     dpy_resize(ds);
   4420 
   4421     dcl = ds->listeners;
   4422     while (dcl != NULL) {
   4423         if (dcl->dpy_refresh != NULL) {
   4424             ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
   4425             qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
   4426         }
   4427         dcl = dcl->next;
   4428     }
   4429 
   4430     if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
   4431         nographic_timer = qemu_new_timer_ms(rt_clock, nographic_update, NULL);
   4432         qemu_mod_timer(nographic_timer, qemu_get_clock_ms(rt_clock));
   4433     }
   4434 
   4435     text_consoles_set_display(ds);
   4436     qemu_chr_initial_reset();
   4437 
   4438     if (monitor_device && monitor_hd)
   4439         monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
   4440 
   4441     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
   4442         const char *devname = serial_devices[i];
   4443         if (devname && strcmp(devname, "none")) {
   4444             if (strstart(devname, "vc", 0))
   4445                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
   4446         }
   4447     }
   4448 
   4449     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
   4450         const char *devname = parallel_devices[i];
   4451         if (devname && strcmp(devname, "none")) {
   4452             if (strstart(devname, "vc", 0))
   4453                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
   4454         }
   4455     }
   4456 
   4457     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
   4458         const char *devname = virtio_consoles[i];
   4459         if (virtcon_hds[i] && devname) {
   4460             if (strstart(devname, "vc", 0))
   4461                 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
   4462         }
   4463     }
   4464 
   4465     if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
   4466         PANIC("qemu: could not open gdbserver on device '%s'",
   4467                 gdbstub_dev);
   4468     }
   4469 
   4470     /* call android-specific setup function */
   4471     android_emulation_setup();
   4472 
   4473 #if !defined(CONFIG_STANDALONE_CORE)
   4474     // For the standalone emulator (UI+core in one executable) we need to
   4475     // set the window title here.
   4476     android_emulator_set_base_port(android_base_port);
   4477 #endif
   4478 
   4479     if (loadvm)
   4480         do_loadvm(cur_mon, loadvm);
   4481 
   4482     if (incoming) {
   4483         autostart = 0; /* fixme how to deal with -daemonize */
   4484         qemu_start_incoming_migration(incoming);
   4485     }
   4486 
   4487     if (autostart)
   4488         vm_start();
   4489 
   4490     os_setup_post();
   4491 
   4492 #ifdef CONFIG_ANDROID
   4493     // This will notify the UI that the core is successfuly initialized
   4494     android_core_init_completed();
   4495 #endif  // CONFIG_ANDROID
   4496 
   4497     main_loop();
   4498     quit_timers();
   4499     net_cleanup();
   4500     android_emulation_teardown();
   4501     return 0;
   4502 }
   4503 
   4504 void
   4505 android_emulation_teardown(void)
   4506 {
   4507     android_charmap_done();
   4508 }
   4509