• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
ioport_read(int index,uint32_t address)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 
ioport_write(int index,uint32_t address,uint32_t data)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 
default_ioport_readb(void * opaque,uint32_t address)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 
default_ioport_writeb(void * opaque,uint32_t address,uint32_t data)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 */
default_ioport_readw(void * opaque,uint32_t address)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 
default_ioport_writew(void * opaque,uint32_t address,uint32_t data)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 
default_ioport_readl(void * opaque,uint32_t address)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 
default_ioport_writel(void * opaque,uint32_t address,uint32_t data)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  */
rotate_qemu_logs_handler(int signum)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  */
reset_rotate_qemu_logs_request(void)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  */
rotate_qemu_log(FILE * old_log_fd,const char * filename)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 
qemu_add_balloon_handler(QEMUBalloonEvent * func,void * opaque)570 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
571 {
572     qemu_balloon_event = func;
573     qemu_balloon_event_opaque = opaque;
574 }
575 
qemu_balloon(ram_addr_t target)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 
qemu_balloon_status(void)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 */
qemu_get_timedate(struct tm * tm,int offset)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 
qemu_timedate_diff(struct tm * tm)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 
start_tracing()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 
stop_tracing()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  */
sigusr_handler(int sig)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  */
sigint_handler(int sig)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" */
qemu_find_bt_vlan(int id)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 
null_hci_send(struct HCIInfo * hci,const uint8_t * data,int len)711 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
712 {
713 }
714 
null_hci_addr_set(struct HCIInfo * hci,const uint8_t * bd_addr)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 
qemu_next_hci(void)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 
hci_init(const char * str)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 
bt_hci_parse(const char * str)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 
bt_vhci_add(int vlan_id)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 
bt_device_add(const char * opt)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 
bt_parse(const char * opt)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 
drive_init_func(QemuOpts * opts,void * opaque)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 
drive_enable_snapshot(QemuOpts * opts,void * opaque)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
drive_opt_get_free_idx(void)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 
drive_get_free_idx(void)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 
drive_add(const char * file,const char * fmt,...)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 
drive_remove(int index)950 void drive_remove(int index)
951 {
952     drives_opt[index].used = 0;
953     nb_drives_opt--;
954 }
955 
drive_get_index(BlockInterfaceType type,int bus,int unit)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 
drive_get_max_bus(BlockInterfaceType type)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 
drive_get_serial(BlockDriverState * bdrv)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 
drive_get_onerror(BlockDriverState * bdrv)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 
bdrv_format_print(void * opaque,const char * name)1008 static void bdrv_format_print(void *opaque, const char *name)
1009 {
1010     fprintf(stderr, " %s", name);
1011 }
1012 
drive_uninit(BlockDriverState * bdrv)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 
drive_init(struct drive_opt * arg,int snapshot,void * opaque)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 
numa_add(const char * optarg)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.  */
qemu_register_usb_port(USBPort * port,void * opaque,int index,usb_attachfn attach)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 
usb_device_add_dev(USBDevice * dev)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->next) {
1467         USBDevice *hub;
1468 
1469         /* Create a new hub and chain it on.  */
1470         free_usb_ports = NULL;
1471         port->next = used_usb_ports;
1472         used_usb_ports = port;
1473 
1474         hub = usb_hub_init(VM_USB_HUB_SIZE);
1475         usb_attach(port, hub);
1476         port = free_usb_ports;
1477     }
1478 
1479     free_usb_ports = port->next;
1480     port->next = used_usb_ports;
1481     used_usb_ports = port;
1482     usb_attach(port, dev);
1483     return 0;
1484 }
1485 
1486 #if 0
1487 static void usb_msd_password_cb(void *opaque, int err)
1488 {
1489     USBDevice *dev = opaque;
1490 
1491     if (!err)
1492         usb_device_add_dev(dev);
1493     else
1494         dev->handle_destroy(dev);
1495 }
1496 #endif
1497 
usb_device_add(const char * devname,int is_hotplug)1498 static int usb_device_add(const char *devname, int is_hotplug)
1499 {
1500     const char *p;
1501     USBDevice *dev;
1502 
1503     if (!free_usb_ports)
1504         return -1;
1505 
1506     if (strstart(devname, "host:", &p)) {
1507         dev = usb_host_device_open(p);
1508     } else if (!strcmp(devname, "mouse")) {
1509         dev = usb_mouse_init();
1510     } else if (!strcmp(devname, "tablet")) {
1511         dev = usb_tablet_init();
1512     } else if (!strcmp(devname, "keyboard")) {
1513         dev = usb_keyboard_init();
1514     } else if (strstart(devname, "disk:", &p)) {
1515 #if 0
1516         BlockDriverState *bs;
1517 #endif
1518         dev = usb_msd_init(p);
1519         if (!dev)
1520             return -1;
1521 #if 0
1522         bs = usb_msd_get_bdrv(dev);
1523         if (bdrv_key_required(bs)) {
1524             autostart = 0;
1525             if (is_hotplug) {
1526                 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
1527                                             dev);
1528                 return 0;
1529             }
1530         }
1531     } else if (!strcmp(devname, "wacom-tablet")) {
1532         dev = usb_wacom_init();
1533     } else if (strstart(devname, "serial:", &p)) {
1534         dev = usb_serial_init(p);
1535 #ifdef CONFIG_BRLAPI
1536     } else if (!strcmp(devname, "braille")) {
1537         dev = usb_baum_init();
1538 #endif
1539     } else if (strstart(devname, "net:", &p)) {
1540         int nic = nb_nics;
1541 
1542         if (net_client_init("nic", p) < 0)
1543             return -1;
1544         nd_table[nic].model = "usb";
1545         dev = usb_net_init(&nd_table[nic]);
1546     } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1547         dev = usb_bt_init(devname[2] ? hci_init(p) :
1548                         bt_new_hci(qemu_find_bt_vlan(0)));
1549 #endif
1550     } else {
1551         return -1;
1552     }
1553     if (!dev)
1554         return -1;
1555 
1556     return usb_device_add_dev(dev);
1557 }
1558 
usb_device_del_addr(int bus_num,int addr)1559 int usb_device_del_addr(int bus_num, int addr)
1560 {
1561     USBPort *port;
1562     USBPort **lastp;
1563     USBDevice *dev;
1564 
1565     if (!used_usb_ports)
1566         return -1;
1567 
1568     if (bus_num != 0)
1569         return -1;
1570 
1571     lastp = &used_usb_ports;
1572     port = used_usb_ports;
1573     while (port && port->dev->addr != addr) {
1574         lastp = &port->next;
1575         port = port->next;
1576     }
1577 
1578     if (!port)
1579         return -1;
1580 
1581     dev = port->dev;
1582     *lastp = port->next;
1583     usb_attach(port, NULL);
1584     dev->handle_destroy(dev);
1585     port->next = free_usb_ports;
1586     free_usb_ports = port;
1587     return 0;
1588 }
1589 
usb_device_del(const char * devname)1590 static int usb_device_del(const char *devname)
1591 {
1592     int bus_num, addr;
1593     const char *p;
1594 
1595     if (strstart(devname, "host:", &p))
1596         return usb_host_device_close(p);
1597 
1598     if (!used_usb_ports)
1599         return -1;
1600 
1601     p = strchr(devname, '.');
1602     if (!p)
1603         return -1;
1604     bus_num = strtoul(devname, NULL, 0);
1605     addr = strtoul(p + 1, NULL, 0);
1606 
1607     return usb_device_del_addr(bus_num, addr);
1608 }
1609 
do_usb_add(Monitor * mon,const char * devname)1610 void do_usb_add(Monitor *mon, const char *devname)
1611 {
1612     usb_device_add(devname, 1);
1613 }
1614 
do_usb_del(Monitor * mon,const char * devname)1615 void do_usb_del(Monitor *mon, const char *devname)
1616 {
1617     usb_device_del(devname);
1618 }
1619 
usb_info(Monitor * mon)1620 void usb_info(Monitor *mon)
1621 {
1622     USBDevice *dev;
1623     USBPort *port;
1624     const char *speed_str;
1625 
1626     if (!usb_enabled) {
1627         monitor_printf(mon, "USB support not enabled\n");
1628         return;
1629     }
1630 
1631     for (port = used_usb_ports; port; port = port->next) {
1632         dev = port->dev;
1633         if (!dev)
1634             continue;
1635         switch(dev->speed) {
1636         case USB_SPEED_LOW:
1637             speed_str = "1.5";
1638             break;
1639         case USB_SPEED_FULL:
1640             speed_str = "12";
1641             break;
1642         case USB_SPEED_HIGH:
1643             speed_str = "480";
1644             break;
1645         default:
1646             speed_str = "?";
1647             break;
1648         }
1649         monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
1650                        0, dev->addr, speed_str, dev->devname);
1651     }
1652 }
1653 
1654 /***********************************************************/
1655 /* PCMCIA/Cardbus */
1656 
1657 static struct pcmcia_socket_entry_s {
1658     PCMCIASocket *socket;
1659     struct pcmcia_socket_entry_s *next;
1660 } *pcmcia_sockets = 0;
1661 
pcmcia_socket_register(PCMCIASocket * socket)1662 void pcmcia_socket_register(PCMCIASocket *socket)
1663 {
1664     struct pcmcia_socket_entry_s *entry;
1665 
1666     entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1667     entry->socket = socket;
1668     entry->next = pcmcia_sockets;
1669     pcmcia_sockets = entry;
1670 }
1671 
pcmcia_socket_unregister(PCMCIASocket * socket)1672 void pcmcia_socket_unregister(PCMCIASocket *socket)
1673 {
1674     struct pcmcia_socket_entry_s *entry, **ptr;
1675 
1676     ptr = &pcmcia_sockets;
1677     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1678         if (entry->socket == socket) {
1679             *ptr = entry->next;
1680             qemu_free(entry);
1681         }
1682 }
1683 
pcmcia_info(Monitor * mon)1684 void pcmcia_info(Monitor *mon)
1685 {
1686     struct pcmcia_socket_entry_s *iter;
1687 
1688     if (!pcmcia_sockets)
1689         monitor_printf(mon, "No PCMCIA sockets\n");
1690 
1691     for (iter = pcmcia_sockets; iter; iter = iter->next)
1692         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1693                        iter->socket->attached ? iter->socket->card_string :
1694                        "Empty");
1695 }
1696 
1697 /***********************************************************/
1698 /* machine registration */
1699 
1700 static QEMUMachine *first_machine = NULL;
1701 QEMUMachine *current_machine = NULL;
1702 
qemu_register_machine(QEMUMachine * m)1703 int qemu_register_machine(QEMUMachine *m)
1704 {
1705     QEMUMachine **pm;
1706     pm = &first_machine;
1707     while (*pm != NULL)
1708         pm = &(*pm)->next;
1709     m->next = NULL;
1710     *pm = m;
1711     return 0;
1712 }
1713 
find_machine(const char * name)1714 static QEMUMachine *find_machine(const char *name)
1715 {
1716     QEMUMachine *m;
1717 
1718     for(m = first_machine; m != NULL; m = m->next) {
1719         if (!strcmp(m->name, name))
1720             return m;
1721     }
1722     return NULL;
1723 }
1724 
find_default_machine(void)1725 static QEMUMachine *find_default_machine(void)
1726 {
1727     QEMUMachine *m;
1728 
1729     for(m = first_machine; m != NULL; m = m->next) {
1730         if (m->is_default) {
1731             return m;
1732         }
1733     }
1734     return NULL;
1735 }
1736 
1737 /***********************************************************/
1738 /* main execution loop */
1739 
gui_update(void * opaque)1740 static void gui_update(void *opaque)
1741 {
1742     uint64_t interval = GUI_REFRESH_INTERVAL;
1743     DisplayState *ds = opaque;
1744     DisplayChangeListener *dcl = ds->listeners;
1745 
1746     dpy_refresh(ds);
1747 
1748     while (dcl != NULL) {
1749         if (dcl->gui_timer_interval &&
1750             dcl->gui_timer_interval < interval)
1751             interval = dcl->gui_timer_interval;
1752         dcl = dcl->next;
1753     }
1754     qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1755 }
1756 
nographic_update(void * opaque)1757 static void nographic_update(void *opaque)
1758 {
1759     uint64_t interval = GUI_REFRESH_INTERVAL;
1760 
1761     qemu_mod_timer(nographic_timer, interval + qemu_get_clock_ms(rt_clock));
1762 }
1763 
1764 struct vm_change_state_entry {
1765     VMChangeStateHandler *cb;
1766     void *opaque;
1767     QLIST_ENTRY (vm_change_state_entry) entries;
1768 };
1769 
1770 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1771 
qemu_add_vm_change_state_handler(VMChangeStateHandler * cb,void * opaque)1772 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1773                                                      void *opaque)
1774 {
1775     VMChangeStateEntry *e;
1776 
1777     e = qemu_mallocz(sizeof (*e));
1778 
1779     e->cb = cb;
1780     e->opaque = opaque;
1781     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1782     return e;
1783 }
1784 
qemu_del_vm_change_state_handler(VMChangeStateEntry * e)1785 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1786 {
1787     QLIST_REMOVE (e, entries);
1788     qemu_free (e);
1789 }
1790 
vm_state_notify(int running,int reason)1791 void vm_state_notify(int running, int reason)
1792 {
1793     VMChangeStateEntry *e;
1794 
1795     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1796         e->cb(e->opaque, running, reason);
1797     }
1798 }
1799 
vm_start(void)1800 void vm_start(void)
1801 {
1802     if (!vm_running) {
1803         cpu_enable_ticks();
1804         vm_running = 1;
1805         vm_state_notify(1, 0);
1806         //qemu_rearm_alarm_timer(alarm_timer);
1807         resume_all_vcpus();
1808     }
1809 }
1810 
1811 /* reset/shutdown handler */
1812 
1813 typedef struct QEMUResetEntry {
1814     QEMUResetHandler *func;
1815     void *opaque;
1816     int order;
1817     struct QEMUResetEntry *next;
1818 } QEMUResetEntry;
1819 
1820 static QEMUResetEntry *first_reset_entry;
1821 static int reset_requested;
1822 static int shutdown_requested, shutdown_signal = -1;
1823 static pid_t shutdown_pid;
1824 static int powerdown_requested;
1825 int debug_requested;
1826 static int vmstop_requested;
1827 
qemu_shutdown_requested(void)1828 int qemu_shutdown_requested(void)
1829 {
1830     int r = shutdown_requested;
1831     shutdown_requested = 0;
1832     return r;
1833 }
1834 
qemu_reset_requested(void)1835 int qemu_reset_requested(void)
1836 {
1837     int r = reset_requested;
1838     reset_requested = 0;
1839     return r;
1840 }
1841 
qemu_powerdown_requested(void)1842 int qemu_powerdown_requested(void)
1843 {
1844     int r = powerdown_requested;
1845     powerdown_requested = 0;
1846     return r;
1847 }
1848 
qemu_debug_requested(void)1849 static int qemu_debug_requested(void)
1850 {
1851     int r = debug_requested;
1852     debug_requested = 0;
1853     return r;
1854 }
1855 
qemu_vmstop_requested(void)1856 static int qemu_vmstop_requested(void)
1857 {
1858     int r = vmstop_requested;
1859     vmstop_requested = 0;
1860     return r;
1861 }
1862 
qemu_register_reset(QEMUResetHandler * func,int order,void * opaque)1863 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
1864 {
1865     QEMUResetEntry **pre, *re;
1866 
1867     pre = &first_reset_entry;
1868     while (*pre != NULL && (*pre)->order >= order) {
1869         pre = &(*pre)->next;
1870     }
1871     re = qemu_mallocz(sizeof(QEMUResetEntry));
1872     re->func = func;
1873     re->opaque = opaque;
1874     re->order = order;
1875     re->next = NULL;
1876     *pre = re;
1877 }
1878 
qemu_system_reset(void)1879 void qemu_system_reset(void)
1880 {
1881     QEMUResetEntry *re;
1882 
1883     /* reset all devices */
1884     for(re = first_reset_entry; re != NULL; re = re->next) {
1885         re->func(re->opaque);
1886     }
1887 }
1888 
qemu_system_reset_request(void)1889 void qemu_system_reset_request(void)
1890 {
1891     if (no_reboot) {
1892         shutdown_requested = 1;
1893     } else {
1894         reset_requested = 1;
1895     }
1896     qemu_notify_event();
1897 }
1898 
qemu_system_killed(int signal,pid_t pid)1899 void qemu_system_killed(int signal, pid_t pid)
1900 {
1901     shutdown_signal = signal;
1902     shutdown_pid = pid;
1903     qemu_system_shutdown_request();
1904 }
1905 
qemu_system_shutdown_request(void)1906 void qemu_system_shutdown_request(void)
1907 {
1908     shutdown_requested = 1;
1909     qemu_notify_event();
1910 }
1911 
qemu_system_powerdown_request(void)1912 void qemu_system_powerdown_request(void)
1913 {
1914     powerdown_requested = 1;
1915     qemu_notify_event();
1916 }
1917 
1918 #ifdef CONFIG_IOTHREAD
qemu_system_vmstop_request(int reason)1919 static void qemu_system_vmstop_request(int reason)
1920 {
1921     vmstop_requested = reason;
1922     qemu_notify_event();
1923 }
1924 #endif
1925 
main_loop_wait(int timeout)1926 void main_loop_wait(int timeout)
1927 {
1928     fd_set rfds, wfds, xfds;
1929     int ret, nfds;
1930     struct timeval tv;
1931 
1932     qemu_bh_update_timeout(&timeout);
1933 
1934     os_host_main_loop_wait(&timeout);
1935 
1936 
1937     tv.tv_sec = timeout / 1000;
1938     tv.tv_usec = (timeout % 1000) * 1000;
1939 
1940     /* poll any events */
1941 
1942     /* XXX: separate device handlers from system ones */
1943     nfds = -1;
1944     FD_ZERO(&rfds);
1945     FD_ZERO(&wfds);
1946     FD_ZERO(&xfds);
1947     qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
1948     if (slirp_is_inited()) {
1949         slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1950     }
1951 
1952     qemu_mutex_unlock_iothread();
1953     ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1954     qemu_mutex_lock_iothread();
1955     qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
1956     if (slirp_is_inited()) {
1957         if (ret < 0) {
1958             FD_ZERO(&rfds);
1959             FD_ZERO(&wfds);
1960             FD_ZERO(&xfds);
1961         }
1962         slirp_select_poll(&rfds, &wfds, &xfds);
1963     }
1964     charpipe_poll();
1965 
1966     qemu_run_all_timers();
1967 
1968     /* Check bottom-halves last in case any of the earlier events triggered
1969        them.  */
1970     qemu_bh_poll();
1971 
1972 }
1973 
vm_can_run(void)1974 static int vm_can_run(void)
1975 {
1976     if (powerdown_requested)
1977         return 0;
1978     if (reset_requested)
1979         return 0;
1980     if (shutdown_requested)
1981         return 0;
1982     if (debug_requested)
1983         return 0;
1984     return 1;
1985 }
1986 
main_loop(void)1987 static void main_loop(void)
1988 {
1989     int r;
1990 
1991 #ifdef CONFIG_IOTHREAD
1992     qemu_system_ready = 1;
1993     qemu_cond_broadcast(&qemu_system_cond);
1994 #endif
1995 
1996 #ifdef CONFIG_HAX
1997     if (hax_enabled())
1998         hax_sync_vcpus();
1999 #endif
2000 
2001     for (;;) {
2002         do {
2003 #ifdef CONFIG_PROFILER
2004             int64_t ti;
2005 #endif
2006 #ifndef CONFIG_IOTHREAD
2007             tcg_cpu_exec();
2008 #endif
2009 #ifdef CONFIG_PROFILER
2010             ti = profile_getclock();
2011 #endif
2012             main_loop_wait(qemu_calculate_timeout());
2013 #ifdef CONFIG_PROFILER
2014             dev_time += profile_getclock() - ti;
2015 #endif
2016 
2017             if (rotate_logs_requested) {
2018                 FILE* new_dns_log_fd = rotate_qemu_log(get_slirp_dns_log_fd(),
2019                                                         dns_log_filename);
2020                 FILE* new_drop_log_fd = rotate_qemu_log(get_slirp_drop_log_fd(),
2021                                                          drop_log_filename);
2022                 slirp_dns_log_fd(new_dns_log_fd);
2023                 slirp_drop_log_fd(new_drop_log_fd);
2024                 reset_rotate_qemu_logs_request();
2025             }
2026 
2027         } while (vm_can_run());
2028 
2029         if (qemu_debug_requested())
2030             vm_stop(EXCP_DEBUG);
2031         if (qemu_shutdown_requested()) {
2032             if (no_shutdown) {
2033                 vm_stop(0);
2034                 no_shutdown = 0;
2035             } else {
2036                 if (savevm_on_exit != NULL) {
2037                   /* Prior to saving VM to the snapshot file, save HW config
2038                    * settings for that VM, so we can match them when VM gets
2039                    * loaded from the snapshot. */
2040                   snaphost_save_config(savevm_on_exit);
2041                   do_savevm(cur_mon, savevm_on_exit);
2042                 }
2043                 break;
2044             }
2045         }
2046         if (qemu_reset_requested()) {
2047             pause_all_vcpus();
2048             qemu_system_reset();
2049             resume_all_vcpus();
2050         }
2051         if (qemu_powerdown_requested())
2052             qemu_system_powerdown();
2053         if ((r = qemu_vmstop_requested()))
2054             vm_stop(r);
2055     }
2056     pause_all_vcpus();
2057 }
2058 
version(void)2059 void version(void)
2060 {
2061     printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2062 }
2063 
qemu_help(int exitcode)2064 void qemu_help(int exitcode)
2065 {
2066     version();
2067     printf("usage: %s [options] [disk_image]\n"
2068            "\n"
2069            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2070            "\n"
2071 #define DEF(option, opt_arg, opt_enum, opt_help)        \
2072            opt_help
2073 #define DEFHEADING(text) stringify(text) "\n"
2074 #include "qemu-options.def"
2075 #undef DEF
2076 #undef DEFHEADING
2077 #undef GEN_DOCS
2078            "\n"
2079            "During emulation, the following keys are useful:\n"
2080            "ctrl-alt-f      toggle full screen\n"
2081            "ctrl-alt-n      switch to virtual console 'n'\n"
2082            "ctrl-alt        toggle mouse and keyboard grab\n"
2083            "\n"
2084            "When using -nographic, press 'ctrl-a h' to get some help.\n"
2085            ,
2086            "qemu",
2087            DEFAULT_RAM_SIZE,
2088 #ifndef _WIN32
2089            DEFAULT_NETWORK_SCRIPT,
2090            DEFAULT_NETWORK_DOWN_SCRIPT,
2091 #endif
2092            DEFAULT_GDBSTUB_PORT,
2093            "/tmp/qemu.log");
2094     QEMU_EXIT(exitcode);
2095 }
2096 
2097 #define HAS_ARG 0x0001
2098 
2099 enum {
2100 #define DEF(option, opt_arg, opt_enum, opt_help)        \
2101     opt_enum,
2102 #define DEFHEADING(text)
2103 #include "qemu-options.def"
2104 #undef DEF
2105 #undef DEFHEADING
2106 #undef GEN_DOCS
2107 };
2108 
2109 typedef struct QEMUOption {
2110     const char *name;
2111     int flags;
2112     int index;
2113 } QEMUOption;
2114 
2115 static const QEMUOption qemu_options[] = {
2116     { "h", 0, QEMU_OPTION_h },
2117 #define DEF(option, opt_arg, opt_enum, opt_help)        \
2118     { option, opt_arg, opt_enum },
2119 #define DEFHEADING(text)
2120 #include "qemu-options.def"
2121 #undef DEF
2122 #undef DEFHEADING
2123 #undef GEN_DOCS
2124     { NULL, 0, 0 },
2125 };
2126 
select_vgahw(const char * p)2127 static void select_vgahw (const char *p)
2128 {
2129     const char *opts;
2130 
2131     cirrus_vga_enabled = 0;
2132     std_vga_enabled = 0;
2133     vmsvga_enabled = 0;
2134     xenfb_enabled = 0;
2135     if (strstart(p, "std", &opts)) {
2136         std_vga_enabled = 1;
2137     } else if (strstart(p, "cirrus", &opts)) {
2138         cirrus_vga_enabled = 1;
2139     } else if (strstart(p, "vmware", &opts)) {
2140         vmsvga_enabled = 1;
2141     } else if (strstart(p, "xenfb", &opts)) {
2142         xenfb_enabled = 1;
2143     } else if (!strstart(p, "none", &opts)) {
2144     invalid_vga:
2145         PANIC("Unknown vga type: %s", p);
2146     }
2147     while (*opts) {
2148         const char *nextopt;
2149 
2150         if (strstart(opts, ",retrace=", &nextopt)) {
2151             opts = nextopt;
2152             if (strstart(opts, "dumb", &nextopt))
2153                 vga_retrace_method = VGA_RETRACE_DUMB;
2154             else if (strstart(opts, "precise", &nextopt))
2155                 vga_retrace_method = VGA_RETRACE_PRECISE;
2156             else goto invalid_vga;
2157         } else goto invalid_vga;
2158         opts = nextopt;
2159     }
2160 }
2161 
2162 #define MAX_NET_CLIENTS 32
2163 
2164 #ifdef _WIN32
2165 /* Look for support files in the same directory as the executable.  */
find_datadir(const char * argv0)2166 static char *find_datadir(const char *argv0)
2167 {
2168     char *p;
2169     char buf[MAX_PATH];
2170     DWORD len;
2171 
2172     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2173     if (len == 0) {
2174         return NULL;
2175     }
2176 
2177     buf[len] = 0;
2178     p = buf + len - 1;
2179     while (p != buf && *p != '\\')
2180         p--;
2181     *p = 0;
2182     if (access(buf, R_OK) == 0) {
2183         return qemu_strdup(buf);
2184     }
2185     return NULL;
2186 }
2187 #else /* !_WIN32 */
2188 
2189 /* Similarly, return the location of the executable */
find_datadir(const char * argv0)2190 static char *find_datadir(const char *argv0)
2191 {
2192     char *p = NULL;
2193     char buf[PATH_MAX];
2194 
2195 #if defined(__linux__)
2196     {
2197         int len;
2198         len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2199         if (len > 0) {
2200             buf[len] = 0;
2201             p = buf;
2202         }
2203     }
2204 #elif defined(__FreeBSD__)
2205     {
2206         int len;
2207         len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
2208         if (len > 0) {
2209             buf[len] = 0;
2210             p = buf;
2211         }
2212     }
2213 #endif
2214     /* If we don't have any way of figuring out the actual executable
2215        location then try argv[0].  */
2216     if (!p) {
2217         p = realpath(argv0, buf);
2218         if (!p) {
2219             return NULL;
2220         }
2221     }
2222 
2223     return qemu_strdup(dirname(buf));
2224 }
2225 #endif
2226 
2227 static char*
qemu_find_file_with_subdir(const char * data_dir,const char * subdir,const char * name)2228 qemu_find_file_with_subdir(const char* data_dir, const char* subdir, const char* name)
2229 {
2230     int   len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2231     char* buf = qemu_mallocz(len);
2232 
2233     snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2234     VERBOSE_PRINT(init,"    trying to find: %s\n", buf);
2235     if (access(buf, R_OK)) {
2236         qemu_free(buf);
2237         return NULL;
2238     }
2239     return buf;
2240 }
2241 
qemu_find_file(int type,const char * name)2242 char *qemu_find_file(int type, const char *name)
2243 {
2244     const char *subdir;
2245     char *buf;
2246 
2247     /* If name contains path separators then try it as a straight path.  */
2248     if ((strchr(name, '/') || strchr(name, '\\'))
2249         && access(name, R_OK) == 0) {
2250         return strdup(name);
2251     }
2252     switch (type) {
2253     case QEMU_FILE_TYPE_BIOS:
2254         subdir = "";
2255         break;
2256     case QEMU_FILE_TYPE_KEYMAP:
2257         subdir = "keymaps/";
2258         break;
2259     default:
2260         abort();
2261     }
2262     buf = qemu_find_file_with_subdir(data_dir, subdir, name);
2263 #ifdef CONFIG_ANDROID
2264     if (type == QEMU_FILE_TYPE_BIOS) {
2265         /* This case corresponds to the emulator being used as part of an
2266          * SDK installation. NOTE: data_dir is really $bindir. */
2267         if (buf == NULL)
2268             buf = qemu_find_file_with_subdir(data_dir, "lib/pc-bios/", name);
2269         /* This case corresponds to platform builds. */
2270         if (buf == NULL)
2271             buf = qemu_find_file_with_subdir(data_dir, "../usr/share/pc-bios/", name);
2272         /* Finally, try this for standalone builds under external/qemu */
2273         if (buf == NULL)
2274             buf = qemu_find_file_with_subdir(data_dir, "../../../prebuilts/qemu-kernel/x86/pc-bios/", name);
2275     }
2276 #endif
2277     return buf;
2278 }
2279 
2280 static int
add_dns_server(const char * server_name)2281 add_dns_server( const char*  server_name )
2282 {
2283     SockAddress   addr;
2284 
2285     if (sock_address_init_resolve( &addr, server_name, 55, 0 ) < 0) {
2286         fprintf(stdout,
2287                 "### WARNING: can't resolve DNS server name '%s'\n",
2288                 server_name );
2289         return -1;
2290     }
2291 
2292     fprintf(stderr,
2293             "DNS server name '%s' resolved to %s\n", server_name, sock_address_to_string(&addr) );
2294 
2295     if ( slirp_add_dns_server( &addr ) < 0 ) {
2296         fprintf(stderr,
2297                 "### WARNING: could not add DNS server '%s' to the network stack\n", server_name);
2298         return -1;
2299     }
2300     return 0;
2301 }
2302 
2303 /* Parses an integer
2304  * Pararm:
2305  *  str      String containing a number to be parsed.
2306  *  result   Passes the parsed integer in this argument
2307  *  returns  0 if ok, -1 if failed
2308  */
2309 int
parse_int(const char * str,int * result)2310 parse_int(const char *str, int *result)
2311 {
2312     char* r;
2313     *result = strtol(str, &r, 0);
2314     if (r == NULL || *r != '\0')
2315       return -1;
2316 
2317     return 0;
2318 }
2319 
2320 #ifndef _WIN32
2321 /*
2322  * Initializes the SIGUSR1 signal handler to clear Qemu logs.
2323  */
init_qemu_clear_logs_sig()2324 void init_qemu_clear_logs_sig() {
2325   struct sigaction act;
2326   sigfillset(&act.sa_mask);
2327   act.sa_flags = 0;
2328   act.sa_handler = rotate_qemu_logs_handler;
2329   if (sigaction(SIGUSR1, &act, NULL) == -1) {
2330     fprintf(stderr, "Failed to setup SIGUSR1 handler to clear Qemu logs\n");
2331     exit(-1);
2332   }
2333 }
2334 #endif
2335 
2336 
2337 
2338 /* parses a null-terminated string specifying a network port (e.g., "80") or
2339  * port range (e.g., "[6666-7000]"). In case of a single port, lport and hport
2340  * are the same. Returns 0 on success, -1 on error. */
2341 
parse_port_range(const char * str,unsigned short * lport,unsigned short * hport)2342 int parse_port_range(const char *str, unsigned short *lport,
2343                      unsigned short *hport) {
2344 
2345   unsigned int low = 0, high = 0;
2346   char *p, *arg = strdup(str);
2347 
2348   if ((*arg == '[') && ((p = strrchr(arg, ']')) != NULL)) {
2349     p = arg + 1;   /* skip '[' */
2350     low  = atoi(strtok(p, "-"));
2351     high = atoi(strtok(NULL, "-"));
2352     if ((low > 0) && (high > 0) && (low < high) && (high < 65535)) {
2353       *lport = low;
2354       *hport = high;
2355     }
2356   }
2357   else {
2358     low = atoi(arg);
2359     if ((0 < low) && (low < 65535)) {
2360       *lport = low;
2361       *hport = low;
2362     }
2363   }
2364   free(arg);
2365   if (low != 0)
2366     return 0;
2367   return -1;
2368 }
2369 
2370 /*
2371  * Implements the generic port forwarding option
2372  */
2373 void
net_slirp_forward(const char * optarg)2374 net_slirp_forward(const char *optarg)
2375 {
2376     /*
2377      * we expect the following format:
2378      * dst_net:dst_mask:dst_port:redirect_ip:redirect_port OR
2379      * dst_net:dst_mask:[dp_range_start-dp_range_end]:redirect_ip:redirect_port
2380      */
2381     char *argument = strdup(optarg), *p = argument;
2382     char *dst_net, *dst_mask, *dst_port;
2383     char *redirect_ip, *redirect_port;
2384     uint32_t dnet, dmask, rip;
2385     unsigned short dlport = 0, dhport = 0, rport;
2386 
2387 
2388     dst_net = strtok(p, ":");
2389     dst_mask = strtok(NULL, ":");
2390     dst_port = strtok(NULL, ":");
2391     redirect_ip = strtok(NULL, ":");
2392     redirect_port = strtok(NULL, ":");
2393 
2394     if (dst_net == NULL || dst_mask == NULL || dst_port == NULL ||
2395         redirect_ip == NULL || redirect_port == NULL) {
2396         fprintf(stderr,
2397                 "Invalid argument for -net-forward, we expect "
2398                 "dst_net:dst_mask:dst_port:redirect_ip:redirect_port or "
2399                 "dst_net:dst_mask:[dp_range_start-dp_range_end]"
2400                 ":redirect_ip:redirect_port: %s\n",
2401                 optarg);
2402         exit(1);
2403     }
2404 
2405     /* inet_strtoip converts dotted address to host byte order */
2406     if (inet_strtoip(dst_net, &dnet) == -1) {
2407         fprintf(stderr, "Invalid destination IP net: %s\n", dst_net);
2408         exit(1);
2409     }
2410     if (inet_strtoip(dst_mask, &dmask) == -1) {
2411         fprintf(stderr, "Invalid destination IP mask: %s\n", dst_mask);
2412         exit(1);
2413     }
2414     if (inet_strtoip(redirect_ip, &rip) == -1) {
2415         fprintf(stderr, "Invalid redirect IP address: %s\n", redirect_ip);
2416         exit(1);
2417     }
2418 
2419     if (parse_port_range(dst_port, &dlport, &dhport) == -1) {
2420         fprintf(stderr, "Invalid destination port or port range\n");
2421         exit(1);
2422     }
2423 
2424     rport = atoi(redirect_port);
2425     if (!rport) {
2426         fprintf(stderr, "Invalid redirect port: %s\n", redirect_port);
2427         exit(1);
2428     }
2429 
2430     dnet &= dmask;
2431 
2432     slirp_add_net_forward(dnet, dmask, dlport, dhport,
2433                           rip, rport);
2434 
2435     free(argument);
2436 }
2437 
2438 
2439 /* Parses an -allow-tcp or -allow-udp argument and inserts a corresponding
2440  * entry in the allows list */
2441 void
slirp_allow(const char * optarg,u_int8_t proto)2442 slirp_allow(const char *optarg, u_int8_t proto)
2443 {
2444   /*
2445    * we expect the following format:
2446    * dst_ip:dst_port OR dst_ip:[dst_lport-dst_hport]
2447    */
2448   char *argument = strdup(optarg), *p = argument;
2449   char *dst_ip_str, *dst_port_str;
2450   uint32_t dst_ip;
2451   unsigned short dst_lport = 0, dst_hport = 0;
2452 
2453   dst_ip_str = strtok(p, ":");
2454   dst_port_str = strtok(NULL, ":");
2455 
2456   if (dst_ip_str == NULL || dst_port_str == NULL) {
2457     fprintf(stderr,
2458             "Invalid argument %s for -allow. We expect "
2459             "dst_ip:dst_port or dst_ip:[dst_lport-dst_hport]\n",
2460             optarg);
2461     exit(1);
2462   }
2463 
2464   if (inet_strtoip(dst_ip_str, &dst_ip) == -1) {
2465     fprintf(stderr, "Invalid destination IP address: %s\n", dst_ip_str);
2466     exit(1);
2467   }
2468   if (parse_port_range(dst_port_str, &dst_lport, &dst_hport) == -1) {
2469     fprintf(stderr, "Invalid destination port or port range\n");
2470     exit(1);
2471   }
2472 
2473   slirp_add_allow(dst_ip, dst_lport, dst_hport, proto);
2474 
2475   free(argument);
2476 }
2477 
2478 /* Add a serial device at a given location in the emulated hardware table.
2479  * On failure, this function aborts the program with an error message.
2480  */
2481 static void
serial_hds_add_at(int index,const char * devname)2482 serial_hds_add_at(int  index, const char* devname)
2483 {
2484     char label[32];
2485 
2486     if (!devname || !strcmp(devname,"none"))
2487         return;
2488 
2489     if (index >= MAX_SERIAL_PORTS) {
2490         PANIC("qemu: invalid serial index for %s (%d >= %d)",
2491               devname, index, MAX_SERIAL_PORTS);
2492     }
2493     if (serial_hds[index] != NULL) {
2494         PANIC("qemu: invalid serial index for %s (%d: already taken!)",
2495               devname, index);
2496     }
2497     snprintf(label, sizeof(label), "serial%d", index);
2498     serial_hds[index] = qemu_chr_open(label, devname, NULL);
2499     if (!serial_hds[index]) {
2500         PANIC("qemu: could not open serial device '%s'", devname);
2501     }
2502 }
2503 
2504 
2505 /* Find a free slot in the emulated serial device table, and register
2506  * it. Return the allocated table index.
2507  */
2508 static int
serial_hds_add(const char * devname)2509 serial_hds_add(const char* devname)
2510 {
2511     int  index;
2512 
2513     /* Find first free slot */
2514     for (index = 0; index < MAX_SERIAL_PORTS; index++) {
2515         if (serial_hds[index] == NULL) {
2516             serial_hds_add_at(index, devname);
2517             return index;
2518         }
2519     }
2520 
2521     PANIC("qemu: too many serial devices registered (%d)", index);
2522     return -1;  /* shouldn't happen */
2523 }
2524 
main(int argc,char ** argv,char ** envp)2525 int main(int argc, char **argv, char **envp)
2526 {
2527     const char *gdbstub_dev = NULL;
2528     uint32_t boot_devices_bitmap = 0;
2529     int i;
2530     int snapshot, linux_boot, net_boot;
2531     const char *icount_option = NULL;
2532     const char *initrd_filename;
2533     const char *kernel_filename, *kernel_cmdline;
2534     const char *boot_devices = "";
2535     DisplayState *ds;
2536     DisplayChangeListener *dcl;
2537     int cyls, heads, secs, translation;
2538     QemuOpts *hda_opts = NULL;
2539     QemuOpts *hdb_opts = NULL;
2540     const char *net_clients[MAX_NET_CLIENTS];
2541     int nb_net_clients;
2542     const char *bt_opts[MAX_BT_CMDLINE];
2543     int nb_bt_opts;
2544     int optind;
2545     const char *r, *optarg;
2546     CharDriverState *monitor_hd = NULL;
2547     const char *monitor_device;
2548     const char *serial_devices[MAX_SERIAL_PORTS];
2549     int serial_device_index;
2550     const char *parallel_devices[MAX_PARALLEL_PORTS];
2551     int parallel_device_index;
2552     const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
2553     int virtio_console_index;
2554     const char *loadvm = NULL;
2555     QEMUMachine *machine;
2556     const char *cpu_model;
2557     const char *usb_devices[MAX_USB_CMDLINE];
2558     int usb_devices_index;
2559     int tb_size;
2560     const char *pid_file = NULL;
2561     const char *incoming = NULL;
2562     CPUState *env;
2563     int show_vnc_port = 0;
2564     IniFile*  hw_ini = NULL;
2565     STRALLOC_DEFINE(kernel_params);
2566     STRALLOC_DEFINE(kernel_config);
2567     int    dns_count = 0;
2568 
2569     /* Initialize sockets before anything else, so we can properly report
2570      * initialization failures back to the UI. */
2571 #ifdef _WIN32
2572     socket_init();
2573 #endif
2574 
2575     init_clocks();
2576 
2577     qemu_cache_utils_init(envp);
2578 
2579     QLIST_INIT (&vm_change_state_head);
2580     os_setup_early_signal_handling();
2581 
2582     module_call_init(MODULE_INIT_MACHINE);
2583     machine = find_default_machine();
2584     cpu_model = NULL;
2585     initrd_filename = NULL;
2586     ram_size = 0;
2587     snapshot = 0;
2588     kernel_filename = NULL;
2589     kernel_cmdline = "";
2590 
2591     cyls = heads = secs = 0;
2592     translation = BIOS_ATA_TRANSLATION_AUTO;
2593     monitor_device = "vc:80Cx24C";
2594 
2595     serial_devices[0] = "vc:80Cx24C";
2596     for(i = 1; i < MAX_SERIAL_PORTS; i++)
2597         serial_devices[i] = NULL;
2598     serial_device_index = 0;
2599 
2600     parallel_devices[0] = "vc:80Cx24C";
2601     for(i = 1; i < MAX_PARALLEL_PORTS; i++)
2602         parallel_devices[i] = NULL;
2603     parallel_device_index = 0;
2604 
2605     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
2606         virtio_consoles[i] = NULL;
2607     virtio_console_index = 0;
2608 
2609     for (i = 0; i < MAX_NODES; i++) {
2610         node_mem[i] = 0;
2611         node_cpumask[i] = 0;
2612     }
2613 
2614     usb_devices_index = 0;
2615 
2616     nb_net_clients = 0;
2617     nb_bt_opts = 0;
2618 #ifdef MAX_DRIVES
2619     nb_drives = 0;
2620     nb_drives_opt = 0;
2621 #endif
2622     nb_numa_nodes = 0;
2623 
2624     nb_nics = 0;
2625 
2626     tb_size = 0;
2627     autostart= 1;
2628 
2629     register_watchdogs();
2630 
2631     /* Initialize boot properties. */
2632     boot_property_init_service();
2633     android_hw_control_init();
2634     android_net_pipes_init();
2635 
2636 #ifdef CONFIG_KVM
2637     /* By default, force auto-detection for kvm */
2638     kvm_allowed = -1;
2639 #endif
2640 
2641     optind = 1;
2642     for(;;) {
2643         if (optind >= argc)
2644             break;
2645         r = argv[optind];
2646         if (r[0] != '-') {
2647             hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2648         } else {
2649             const QEMUOption *popt;
2650 
2651             optind++;
2652             /* Treat --foo the same as -foo.  */
2653             if (r[1] == '-')
2654                 r++;
2655             popt = qemu_options;
2656             for(;;) {
2657                 if (!popt->name) {
2658                     PANIC("%s: invalid option -- '%s'",
2659                                       argv[0], r);
2660                 }
2661                 if (!strcmp(popt->name, r + 1))
2662                     break;
2663                 popt++;
2664             }
2665             if (popt->flags & HAS_ARG) {
2666                 if (optind >= argc) {
2667                     PANIC("%s: option '%s' requires an argument",
2668                                       argv[0], r);
2669                 }
2670                 optarg = argv[optind++];
2671             } else {
2672                 optarg = NULL;
2673             }
2674 
2675             switch(popt->index) {
2676             case QEMU_OPTION_M:
2677                 machine = find_machine(optarg);
2678                 if (!machine) {
2679                     QEMUMachine *m;
2680                     printf("Supported machines are:\n");
2681                     for(m = first_machine; m != NULL; m = m->next) {
2682                         printf("%-10s %s%s\n",
2683                                m->name, m->desc,
2684                                m->is_default ? " (default)" : "");
2685                     }
2686                     if (*optarg != '?') {
2687                         PANIC("Invalid machine parameter: %s",
2688                                           optarg);
2689                     } else {
2690                         QEMU_EXIT(0);
2691                     }
2692                 }
2693                 break;
2694             case QEMU_OPTION_cpu:
2695                 /* hw initialization will check this */
2696                 if (*optarg == '?') {
2697 /* XXX: implement xxx_cpu_list for targets that still miss it */
2698 #if defined(cpu_list)
2699                     cpu_list(stdout, &fprintf);
2700 #endif
2701                     QEMU_EXIT(0);
2702                 } else {
2703                     cpu_model = optarg;
2704                 }
2705                 break;
2706             case QEMU_OPTION_initrd:
2707                 initrd_filename = optarg;
2708                 break;
2709             case QEMU_OPTION_hda:
2710                 if (cyls == 0)
2711                     hda_opts = drive_add(optarg, HD_ALIAS, 0);
2712                 else
2713                     hda_opts = drive_add(optarg, HD_ALIAS
2714 			     ",cyls=%d,heads=%d,secs=%d%s",
2715                              0, cyls, heads, secs,
2716                              translation == BIOS_ATA_TRANSLATION_LBA ?
2717                                  ",trans=lba" :
2718                              translation == BIOS_ATA_TRANSLATION_NONE ?
2719                                  ",trans=none" : "");
2720                  break;
2721             case QEMU_OPTION_hdb:
2722                 hdb_opts = drive_add(optarg, HD_ALIAS, 1);
2723                 break;
2724 
2725             case QEMU_OPTION_hdc:
2726             case QEMU_OPTION_hdd:
2727                 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2728                 break;
2729             case QEMU_OPTION_drive:
2730                 drive_add(NULL, "%s", optarg);
2731 	        break;
2732             case QEMU_OPTION_mtdblock:
2733                 drive_add(optarg, MTD_ALIAS);
2734                 break;
2735             case QEMU_OPTION_sd:
2736                 drive_add(optarg, SD_ALIAS);
2737                 break;
2738             case QEMU_OPTION_pflash:
2739                 drive_add(optarg, PFLASH_ALIAS);
2740                 break;
2741             case QEMU_OPTION_snapshot:
2742                 snapshot = 1;
2743                 break;
2744             case QEMU_OPTION_hdachs:
2745                 {
2746                     const char *p;
2747                     p = optarg;
2748                     cyls = strtol(p, (char **)&p, 0);
2749                     if (cyls < 1 || cyls > 16383)
2750                         goto chs_fail;
2751                     if (*p != ',')
2752                         goto chs_fail;
2753                     p++;
2754                     heads = strtol(p, (char **)&p, 0);
2755                     if (heads < 1 || heads > 16)
2756                         goto chs_fail;
2757                     if (*p != ',')
2758                         goto chs_fail;
2759                     p++;
2760                     secs = strtol(p, (char **)&p, 0);
2761                     if (secs < 1 || secs > 63)
2762                         goto chs_fail;
2763                     if (*p == ',') {
2764                         p++;
2765                         if (!strcmp(p, "none"))
2766                             translation = BIOS_ATA_TRANSLATION_NONE;
2767                         else if (!strcmp(p, "lba"))
2768                             translation = BIOS_ATA_TRANSLATION_LBA;
2769                         else if (!strcmp(p, "auto"))
2770                             translation = BIOS_ATA_TRANSLATION_AUTO;
2771                         else
2772                             goto chs_fail;
2773                     } else if (*p != '\0') {
2774                     chs_fail:
2775                         PANIC("qemu: invalid physical CHS format");
2776                     }
2777 		    if (hda_opts != NULL) {
2778                         char num[16];
2779                         snprintf(num, sizeof(num), "%d", cyls);
2780                         qemu_opt_set(hda_opts, "cyls", num);
2781                         snprintf(num, sizeof(num), "%d", heads);
2782                         qemu_opt_set(hda_opts, "heads", num);
2783                         snprintf(num, sizeof(num), "%d", secs);
2784                         qemu_opt_set(hda_opts, "secs", num);
2785                         if (translation == BIOS_ATA_TRANSLATION_LBA)
2786                             qemu_opt_set(hda_opts, "trans", "lba");
2787                         if (translation == BIOS_ATA_TRANSLATION_NONE)
2788                             qemu_opt_set(hda_opts, "trans", "none");
2789                     }
2790                 }
2791                 break;
2792             case QEMU_OPTION_numa:
2793                 if (nb_numa_nodes >= MAX_NODES) {
2794                     PANIC("qemu: too many NUMA nodes");
2795                 }
2796                 numa_add(optarg);
2797                 break;
2798             case QEMU_OPTION_nographic:
2799                 display_type = DT_NOGRAPHIC;
2800                 break;
2801 #ifdef CONFIG_CURSES
2802             case QEMU_OPTION_curses:
2803                 display_type = DT_CURSES;
2804                 break;
2805 #endif
2806             case QEMU_OPTION_portrait:
2807                 graphic_rotate = 1;
2808                 break;
2809             case QEMU_OPTION_kernel:
2810                 kernel_filename = optarg;
2811                 break;
2812             case QEMU_OPTION_append:
2813                 kernel_cmdline = optarg;
2814                 break;
2815             case QEMU_OPTION_cdrom:
2816                 drive_add(optarg, CDROM_ALIAS);
2817                 break;
2818             case QEMU_OPTION_boot:
2819                 boot_devices = optarg;
2820                 /* We just do some generic consistency checks */
2821                 {
2822                     /* Could easily be extended to 64 devices if needed */
2823                     const char *p;
2824 
2825                     boot_devices_bitmap = 0;
2826                     for (p = boot_devices; *p != '\0'; p++) {
2827                         /* Allowed boot devices are:
2828                          * a b     : floppy disk drives
2829                          * c ... f : IDE disk drives
2830                          * g ... m : machine implementation dependant drives
2831                          * n ... p : network devices
2832                          * It's up to each machine implementation to check
2833                          * if the given boot devices match the actual hardware
2834                          * implementation and firmware features.
2835                          */
2836                         if (*p < 'a' || *p > 'q') {
2837                             PANIC("Invalid boot device '%c'", *p);
2838                         }
2839                         if (boot_devices_bitmap & (1 << (*p - 'a'))) {
2840                             PANIC(
2841                                     "Boot device '%c' was given twice",*p);
2842                         }
2843                         boot_devices_bitmap |= 1 << (*p - 'a');
2844                     }
2845                 }
2846                 break;
2847             case QEMU_OPTION_fda:
2848             case QEMU_OPTION_fdb:
2849                 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2850                 break;
2851 #ifdef TARGET_I386
2852             case QEMU_OPTION_no_fd_bootchk:
2853                 fd_bootchk = 0;
2854                 break;
2855 #endif
2856             case QEMU_OPTION_net:
2857                 if (nb_net_clients >= MAX_NET_CLIENTS) {
2858                     PANIC("qemu: too many network clients");
2859                 }
2860                 net_clients[nb_net_clients] = optarg;
2861                 nb_net_clients++;
2862                 break;
2863 #ifdef CONFIG_SLIRP
2864             case QEMU_OPTION_tftp:
2865 		tftp_prefix = optarg;
2866                 break;
2867             case QEMU_OPTION_bootp:
2868                 bootp_filename = optarg;
2869                 break;
2870             case QEMU_OPTION_redir:
2871                 net_slirp_redir(NULL, optarg, NULL);
2872                 break;
2873 #endif
2874             case QEMU_OPTION_bt:
2875                 if (nb_bt_opts >= MAX_BT_CMDLINE) {
2876                     PANIC("qemu: too many bluetooth options");
2877                 }
2878                 bt_opts[nb_bt_opts++] = optarg;
2879                 break;
2880 #ifdef HAS_AUDIO
2881             case QEMU_OPTION_audio_help:
2882                 AUD_help ();
2883                 QEMU_EXIT(0);
2884                 break;
2885             case QEMU_OPTION_soundhw:
2886                 select_soundhw (optarg);
2887                 break;
2888 #endif
2889             case QEMU_OPTION_h:
2890                 qemu_help(0);
2891                 break;
2892             case QEMU_OPTION_version:
2893                 version();
2894                 QEMU_EXIT(0);
2895                 break;
2896             case QEMU_OPTION_m: {
2897                 uint64_t value;
2898                 char *ptr;
2899 
2900                 value = strtoul(optarg, &ptr, 10);
2901                 switch (*ptr) {
2902                 case 0: case 'M': case 'm':
2903                     value <<= 20;
2904                     break;
2905                 case 'G': case 'g':
2906                     value <<= 30;
2907                     break;
2908                 default:
2909                     PANIC("qemu: invalid ram size: %s", optarg);
2910                 }
2911 
2912                 /* On 32-bit hosts, QEMU is limited by virtual address space */
2913                 if (value > (2047 << 20)
2914 #ifndef CONFIG_KQEMU
2915                     && HOST_LONG_BITS == 32
2916 #endif
2917                     ) {
2918                     PANIC("qemu: at most 2047 MB RAM can be simulated");
2919                 }
2920                 if (value != (uint64_t)(ram_addr_t)value) {
2921                     PANIC("qemu: ram size too large");
2922                 }
2923                 ram_size = value;
2924                 break;
2925             }
2926             case QEMU_OPTION_d:
2927                 {
2928                     int mask;
2929                     const CPULogItem *item;
2930 
2931                     mask = cpu_str_to_log_mask(optarg);
2932                     if (!mask) {
2933                         printf("Log items (comma separated):\n");
2934                         for(item = cpu_log_items; item->mask != 0; item++) {
2935                             printf("%-10s %s\n", item->name, item->help);
2936                         }
2937                         PANIC("Invalid parameter -d=%s", optarg);
2938                     }
2939                     cpu_set_log(mask);
2940                 }
2941                 break;
2942             case QEMU_OPTION_s:
2943                 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
2944                 break;
2945             case QEMU_OPTION_gdb:
2946                 gdbstub_dev = optarg;
2947                 break;
2948             case QEMU_OPTION_L:
2949                 data_dir = optarg;
2950                 break;
2951             case QEMU_OPTION_bios:
2952                 bios_name = optarg;
2953                 break;
2954             case QEMU_OPTION_singlestep:
2955                 singlestep = 1;
2956                 break;
2957             case QEMU_OPTION_S:
2958                 autostart = 0;
2959                 break;
2960 #ifndef _WIN32
2961 	    case QEMU_OPTION_k:
2962 		keyboard_layout = optarg;
2963 		break;
2964 #endif
2965             case QEMU_OPTION_localtime:
2966                 rtc_utc = 0;
2967                 break;
2968             case QEMU_OPTION_vga:
2969                 select_vgahw (optarg);
2970                 break;
2971 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2972             case QEMU_OPTION_g:
2973                 {
2974                     const char *p;
2975                     int w, h, depth;
2976                     p = optarg;
2977                     w = strtol(p, (char **)&p, 10);
2978                     if (w <= 0) {
2979                     graphic_error:
2980                         PANIC("qemu: invalid resolution or depth");
2981                     }
2982                     if (*p != 'x')
2983                         goto graphic_error;
2984                     p++;
2985                     h = strtol(p, (char **)&p, 10);
2986                     if (h <= 0)
2987                         goto graphic_error;
2988                     if (*p == 'x') {
2989                         p++;
2990                         depth = strtol(p, (char **)&p, 10);
2991                         if (depth != 8 && depth != 15 && depth != 16 &&
2992                             depth != 24 && depth != 32)
2993                             goto graphic_error;
2994                     } else if (*p == '\0') {
2995                         depth = graphic_depth;
2996                     } else {
2997                         goto graphic_error;
2998                     }
2999 
3000                     graphic_width = w;
3001                     graphic_height = h;
3002                     graphic_depth = depth;
3003                 }
3004                 break;
3005 #endif
3006             case QEMU_OPTION_echr:
3007                 {
3008                     char *r;
3009                     term_escape_char = strtol(optarg, &r, 0);
3010                     if (r == optarg)
3011                         printf("Bad argument to echr\n");
3012                     break;
3013                 }
3014             case QEMU_OPTION_monitor:
3015                 monitor_device = optarg;
3016                 break;
3017             case QEMU_OPTION_serial:
3018                 if (serial_device_index >= MAX_SERIAL_PORTS) {
3019                     PANIC("qemu: too many serial ports");
3020                 }
3021                 serial_devices[serial_device_index] = optarg;
3022                 serial_device_index++;
3023                 break;
3024             case QEMU_OPTION_watchdog:
3025                 i = select_watchdog(optarg);
3026                 if (i > 0) {
3027                     if (i == 1) {
3028                         PANIC("Invalid watchdog parameter: %s",
3029                                           optarg);
3030                     } else {
3031                         QEMU_EXIT(0);
3032                     }
3033                 }
3034                 break;
3035             case QEMU_OPTION_watchdog_action:
3036                 if (select_watchdog_action(optarg) == -1) {
3037                     PANIC("Unknown -watchdog-action parameter");
3038                 }
3039                 break;
3040             case QEMU_OPTION_virtiocon:
3041                 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
3042                     PANIC("qemu: too many virtio consoles");
3043                 }
3044                 virtio_consoles[virtio_console_index] = optarg;
3045                 virtio_console_index++;
3046                 break;
3047             case QEMU_OPTION_parallel:
3048                 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3049                     PANIC("qemu: too many parallel ports");
3050                 }
3051                 parallel_devices[parallel_device_index] = optarg;
3052                 parallel_device_index++;
3053                 break;
3054             case QEMU_OPTION_loadvm:
3055                 loadvm = optarg;
3056                 break;
3057             case QEMU_OPTION_savevm_on_exit:
3058                 savevm_on_exit = optarg;
3059                 break;
3060             case QEMU_OPTION_full_screen:
3061                 full_screen = 1;
3062                 break;
3063 #ifdef CONFIG_SDL
3064             case QEMU_OPTION_no_frame:
3065                 no_frame = 1;
3066                 break;
3067             case QEMU_OPTION_alt_grab:
3068                 alt_grab = 1;
3069                 break;
3070             case QEMU_OPTION_no_quit:
3071                 no_quit = 1;
3072                 break;
3073             case QEMU_OPTION_sdl:
3074                 display_type = DT_SDL;
3075                 break;
3076 #endif
3077             case QEMU_OPTION_pidfile:
3078                 pid_file = optarg;
3079                 break;
3080 #ifdef TARGET_I386
3081             case QEMU_OPTION_win2k_hack:
3082                 win2k_install_hack = 1;
3083                 break;
3084             case QEMU_OPTION_rtc_td_hack:
3085                 rtc_td_hack = 1;
3086                 break;
3087 #ifndef CONFIG_ANDROID
3088             case QEMU_OPTION_acpitable:
3089                 if(acpi_table_add(optarg) < 0) {
3090                     PANIC("Wrong acpi table provided");
3091                 }
3092                 break;
3093 #endif
3094             case QEMU_OPTION_smbios:
3095                 do_smbios_option(optarg);
3096                 break;
3097 #endif
3098 #ifdef CONFIG_KVM
3099             case QEMU_OPTION_enable_kvm:
3100                 kvm_allowed = 1;
3101                 break;
3102             case QEMU_OPTION_disable_kvm:
3103                 kvm_allowed = 0;
3104                 break;
3105 #endif /* CONFIG_KVM */
3106             case QEMU_OPTION_usb:
3107                 usb_enabled = 1;
3108                 break;
3109             case QEMU_OPTION_usbdevice:
3110                 usb_enabled = 1;
3111                 if (usb_devices_index >= MAX_USB_CMDLINE) {
3112                     PANIC("Too many USB devices");
3113                 }
3114                 usb_devices[usb_devices_index] = optarg;
3115                 usb_devices_index++;
3116                 break;
3117             case QEMU_OPTION_smp:
3118                 smp_cpus = atoi(optarg);
3119                 if (smp_cpus < 1) {
3120                     PANIC("Invalid number of CPUs");
3121                 }
3122                 break;
3123 	    case QEMU_OPTION_vnc:
3124                 display_type = DT_VNC;
3125 		vnc_display = optarg;
3126 		break;
3127 #ifdef TARGET_I386
3128             case QEMU_OPTION_no_acpi:
3129                 acpi_enabled = 0;
3130                 break;
3131             case QEMU_OPTION_no_hpet:
3132                 no_hpet = 1;
3133                 break;
3134             case QEMU_OPTION_no_virtio_balloon:
3135                 no_virtio_balloon = 1;
3136                 break;
3137 #endif
3138             case QEMU_OPTION_no_reboot:
3139                 no_reboot = 1;
3140                 break;
3141             case QEMU_OPTION_no_shutdown:
3142                 no_shutdown = 1;
3143                 break;
3144             case QEMU_OPTION_show_cursor:
3145                 cursor_hide = 0;
3146                 break;
3147             case QEMU_OPTION_uuid:
3148                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3149                     PANIC("Fail to parse UUID string. Wrong format.");
3150                 }
3151                 break;
3152 	    case QEMU_OPTION_option_rom:
3153 		if (nb_option_roms >= MAX_OPTION_ROMS) {
3154 		    PANIC("Too many option ROMs");
3155 		}
3156 		option_rom[nb_option_roms] = optarg;
3157 		nb_option_roms++;
3158 		break;
3159 #if defined(TARGET_ARM) || defined(TARGET_M68K)
3160             case QEMU_OPTION_semihosting:
3161                 semihosting_enabled = 1;
3162                 break;
3163 #endif
3164             case QEMU_OPTION_name:
3165                 qemu_name = optarg;
3166                 break;
3167 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
3168             case QEMU_OPTION_prom_env:
3169                 if (nb_prom_envs >= MAX_PROM_ENVS) {
3170                     PANIC("Too many prom variables");
3171                 }
3172                 prom_envs[nb_prom_envs] = optarg;
3173                 nb_prom_envs++;
3174                 break;
3175 #endif
3176 #ifdef TARGET_ARM
3177             case QEMU_OPTION_old_param:
3178                 old_param = 1;
3179                 break;
3180 #endif
3181             case QEMU_OPTION_clock:
3182                 configure_alarms(optarg);
3183                 break;
3184             case QEMU_OPTION_startdate:
3185                 {
3186                     struct tm tm;
3187                     time_t rtc_start_date = 0;
3188                     if (!strcmp(optarg, "now")) {
3189                         rtc_date_offset = -1;
3190                     } else {
3191                         if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
3192                                &tm.tm_year,
3193                                &tm.tm_mon,
3194                                &tm.tm_mday,
3195                                &tm.tm_hour,
3196                                &tm.tm_min,
3197                                &tm.tm_sec) == 6) {
3198                             /* OK */
3199                         } else if (sscanf(optarg, "%d-%d-%d",
3200                                           &tm.tm_year,
3201                                           &tm.tm_mon,
3202                                           &tm.tm_mday) == 3) {
3203                             tm.tm_hour = 0;
3204                             tm.tm_min = 0;
3205                             tm.tm_sec = 0;
3206                         } else {
3207                             goto date_fail;
3208                         }
3209                         tm.tm_year -= 1900;
3210                         tm.tm_mon--;
3211                         rtc_start_date = mktimegm(&tm);
3212                         if (rtc_start_date == -1) {
3213                         date_fail:
3214                             PANIC("Invalid date format. Valid format are:\n"
3215                                     "'now' or '2006-06-17T16:01:21' or '2006-06-17'");
3216                         }
3217                         rtc_date_offset = time(NULL) - rtc_start_date;
3218                     }
3219                 }
3220                 break;
3221 
3222             /* -------------------------------------------------------*/
3223             /* User mode network stack restrictions */
3224             case QEMU_OPTION_drop_udp:
3225                 slirp_drop_udp();
3226                 break;
3227             case QEMU_OPTION_drop_tcp:
3228                 slirp_drop_tcp();
3229                 break;
3230             case QEMU_OPTION_allow_tcp:
3231                 slirp_allow(optarg, IPPROTO_TCP);
3232                 break;
3233             case QEMU_OPTION_allow_udp:
3234                 slirp_allow(optarg, IPPROTO_UDP);
3235                 break;
3236              case QEMU_OPTION_drop_log:
3237                 {
3238                     FILE* drop_log_fd;
3239                     drop_log_filename = optarg;
3240                     drop_log_fd = fopen(optarg, "w+");
3241 
3242                     if (!drop_log_fd) {
3243                         fprintf(stderr, "Cannot open drop log: %s\n", optarg);
3244                         exit(1);
3245                     }
3246 
3247                     slirp_drop_log_fd(drop_log_fd);
3248                 }
3249                 break;
3250 
3251             case QEMU_OPTION_dns_log:
3252                 {
3253                     FILE* dns_log_fd;
3254                     dns_log_filename = optarg;
3255                     dns_log_fd = fopen(optarg, "wb+");
3256 
3257                     if (dns_log_fd == NULL) {
3258                         fprintf(stderr, "Cannot open dns log: %s\n", optarg);
3259                         exit(1);
3260                     }
3261 
3262                     slirp_dns_log_fd(dns_log_fd);
3263                 }
3264                 break;
3265 
3266 
3267             case QEMU_OPTION_max_dns_conns:
3268                 {
3269                     int max_dns_conns = 0;
3270                     if (parse_int(optarg, &max_dns_conns)) {
3271                       fprintf(stderr,
3272                               "qemu: syntax: -max-dns-conns max_connections\n");
3273                       exit(1);
3274                     }
3275                     if (max_dns_conns <= 0 ||  max_dns_conns == LONG_MAX) {
3276                       fprintf(stderr,
3277                               "Invalid arg for max dns connections: %s\n",
3278                               optarg);
3279                       exit(1);
3280                     }
3281                     slirp_set_max_dns_conns(max_dns_conns);
3282                 }
3283                 break;
3284 
3285             case QEMU_OPTION_net_forward:
3286                 net_slirp_forward(optarg);
3287                 break;
3288             case QEMU_OPTION_net_forward_tcp2sink:
3289                 {
3290                     SockAddress saddr;
3291 
3292                     if (parse_host_port(&saddr, optarg)) {
3293                         fprintf(stderr,
3294                                 "Invalid ip/port %s for "
3295                                 "-forward-dropped-tcp2sink. "
3296                                 "We expect 'sink_ip:sink_port'\n",
3297                                 optarg);
3298                         exit(1);
3299                     }
3300                     slirp_forward_dropped_tcp2sink(saddr.u.inet.address,
3301                                                    saddr.u.inet.port);
3302                 }
3303                 break;
3304             /* -------------------------------------------------------*/
3305 
3306             case QEMU_OPTION_tb_size:
3307                 tb_size = strtol(optarg, NULL, 0);
3308                 if (tb_size < 0)
3309                     tb_size = 0;
3310                 break;
3311             case QEMU_OPTION_icount:
3312                 icount_option = optarg;
3313                 break;
3314             case QEMU_OPTION_incoming:
3315                 incoming = optarg;
3316                 break;
3317 #ifdef CONFIG_XEN
3318             case QEMU_OPTION_xen_domid:
3319                 xen_domid = atoi(optarg);
3320                 break;
3321             case QEMU_OPTION_xen_create:
3322                 xen_mode = XEN_CREATE;
3323                 break;
3324             case QEMU_OPTION_xen_attach:
3325                 xen_mode = XEN_ATTACH;
3326                 break;
3327 #endif
3328 
3329 
3330             case QEMU_OPTION_mic:
3331                 audio_input_source = (char*)optarg;
3332                 break;
3333 #ifdef CONFIG_TRACE
3334             case QEMU_OPTION_trace:
3335                 trace_filename = optarg;
3336                 tracing = 1;
3337                 break;
3338 #if 0
3339             case QEMU_OPTION_trace_miss:
3340                 trace_cache_miss = 1;
3341                 break;
3342             case QEMU_OPTION_trace_addr:
3343                 trace_all_addr = 1;
3344                 break;
3345 #endif
3346             case QEMU_OPTION_tracing:
3347                 if (strcmp(optarg, "off") == 0)
3348                     tracing = 0;
3349                 else if (strcmp(optarg, "on") == 0 && trace_filename)
3350                     tracing = 1;
3351                 else {
3352                     PANIC("Unexpected option to -tracing ('%s')",
3353                             optarg);
3354                 }
3355                 break;
3356 #if 0
3357             case QEMU_OPTION_dcache_load_miss:
3358                 dcache_load_miss_penalty = atoi(optarg);
3359                 break;
3360             case QEMU_OPTION_dcache_store_miss:
3361                 dcache_store_miss_penalty = atoi(optarg);
3362                 break;
3363 #endif
3364 #endif
3365 #ifdef CONFIG_NAND
3366             case QEMU_OPTION_nand:
3367                 nand_add_dev(optarg);
3368                 break;
3369 
3370 #endif
3371             case QEMU_OPTION_disable_hax:
3372                 hax_disabled = 1;
3373                 break;
3374             case QEMU_OPTION_android_ports:
3375                 android_op_ports = (char*)optarg;
3376                 break;
3377 
3378             case QEMU_OPTION_android_port:
3379                 android_op_port = (char*)optarg;
3380                 break;
3381 
3382             case QEMU_OPTION_android_report_console:
3383                 android_op_report_console = (char*)optarg;
3384                 break;
3385 
3386             case QEMU_OPTION_http_proxy:
3387                 op_http_proxy = (char*)optarg;
3388                 break;
3389 
3390             case QEMU_OPTION_charmap:
3391                 op_charmap_file = (char*)optarg;
3392                 break;
3393 
3394             case QEMU_OPTION_android_hw:
3395                 android_op_hwini = (char*)optarg;
3396                 break;
3397 
3398             case QEMU_OPTION_dns_server:
3399                 android_op_dns_server = (char*)optarg;
3400                 break;
3401 
3402             case QEMU_OPTION_radio:
3403                 android_op_radio = (char*)optarg;
3404                 break;
3405 
3406             case QEMU_OPTION_gps:
3407                 android_op_gps = (char*)optarg;
3408                 break;
3409 
3410             case QEMU_OPTION_audio:
3411                 android_op_audio = (char*)optarg;
3412                 break;
3413 
3414             case QEMU_OPTION_cpu_delay:
3415                 android_op_cpu_delay = (char*)optarg;
3416                 break;
3417 
3418             case QEMU_OPTION_show_kernel:
3419                 android_kmsg_init(ANDROID_KMSG_PRINT_MESSAGES);
3420                 break;
3421 
3422 #ifdef CONFIG_NAND_LIMITS
3423             case QEMU_OPTION_nand_limits:
3424                 android_op_nand_limits = (char*)optarg;
3425                 break;
3426 #endif  // CONFIG_NAND_LIMITS
3427 
3428             case QEMU_OPTION_netspeed:
3429                 android_op_netspeed = (char*)optarg;
3430                 break;
3431 
3432             case QEMU_OPTION_netdelay:
3433                 android_op_netdelay = (char*)optarg;
3434                 break;
3435 
3436             case QEMU_OPTION_netfast:
3437                 android_op_netfast = 1;
3438                 break;
3439 
3440             case QEMU_OPTION_tcpdump:
3441                 android_op_tcpdump = (char*)optarg;
3442                 break;
3443 
3444             case QEMU_OPTION_boot_property:
3445                 boot_property_parse_option((char*)optarg);
3446                 break;
3447 
3448             case QEMU_OPTION_lcd_density:
3449                 android_op_lcd_density = (char*)optarg;
3450                 break;
3451 
3452             case QEMU_OPTION_ui_port:
3453                 android_op_ui_port = (char*)optarg;
3454                 break;
3455 
3456             case QEMU_OPTION_ui_settings:
3457                 android_op_ui_settings = (char*)optarg;
3458                 break;
3459 
3460             case QEMU_OPTION_audio_test_out:
3461                 android_audio_test_start_out();
3462                 break;
3463 
3464             case QEMU_OPTION_android_avdname:
3465                 android_op_avd_name = (char*)optarg;
3466                 break;
3467 
3468             case QEMU_OPTION_timezone:
3469                 if (timezone_set((char*)optarg)) {
3470                     fprintf(stderr, "emulator: it seems the timezone '%s' is not in zoneinfo format\n",
3471                             (char*)optarg);
3472                 }
3473                 break;
3474 
3475 #ifdef CONFIG_MEMCHECK
3476             case QEMU_OPTION_android_memcheck:
3477                 android_op_memcheck = (char*)optarg;
3478                 /* This will set ro.kernel.memcheck system property
3479                  * to memcheck's tracing flags. */
3480                 stralloc_add_format(kernel_config, " memcheck=%s", android_op_memcheck);
3481                 break;
3482 #endif // CONFIG_MEMCHECK
3483 
3484             case QEMU_OPTION_snapshot_no_time_update:
3485                 android_snapshot_update_time = 0;
3486                 break;
3487 
3488             case QEMU_OPTION_list_webcam:
3489                 android_list_web_cameras();
3490                 exit(0);
3491 
3492             default:
3493                 os_parse_cmd_args(popt->index, optarg);
3494             }
3495         }
3496     }
3497 
3498     /* Initialize character map. */
3499     if (android_charmap_setup(op_charmap_file)) {
3500         if (op_charmap_file) {
3501             PANIC(
3502                     "Unable to initialize character map from file %s.",
3503                     op_charmap_file);
3504         } else {
3505             PANIC(
3506                     "Unable to initialize default character map.");
3507         }
3508     }
3509 
3510     /* If no data_dir is specified then try to find it relative to the
3511        executable path.  */
3512     if (!data_dir) {
3513         data_dir = find_datadir(argv[0]);
3514     }
3515     /* If all else fails use the install patch specified when building.  */
3516     if (!data_dir) {
3517         data_dir = CONFIG_QEMU_SHAREDIR;
3518     }
3519 
3520     if (!android_op_hwini) {
3521         PANIC("Missing -android-hw <file> option!");
3522     }
3523     hw_ini = iniFile_newFromFile(android_op_hwini);
3524     if (hw_ini == NULL) {
3525         PANIC("Could not find %s file.", android_op_hwini);
3526     }
3527 
3528     androidHwConfig_init(android_hw, 0);
3529     androidHwConfig_read(android_hw, hw_ini);
3530 
3531     /* If we're loading VM from a snapshot, make sure that the current HW config
3532      * matches the one with which the VM has been saved. */
3533     if (loadvm && *loadvm && !snaphost_match_configs(hw_ini, loadvm)) {
3534         exit(0);
3535     }
3536 
3537     iniFile_free(hw_ini);
3538 
3539     {
3540         int width  = android_hw->hw_lcd_width;
3541         int height = android_hw->hw_lcd_height;
3542         int depth  = android_hw->hw_lcd_depth;
3543 
3544         /* A bit of sanity checking */
3545         if (width <= 0 || height <= 0    ||
3546             (depth != 16 && depth != 32) ||
3547             (((width|height) & 3) != 0)  )
3548         {
3549             PANIC("Invalid display configuration (%d,%d,%d)",
3550                   width, height, depth);
3551         }
3552         android_display_width  = width;
3553         android_display_height = height;
3554         android_display_bpp    = depth;
3555     }
3556 
3557 #ifdef CONFIG_NAND_LIMITS
3558     /* Init nand stuff. */
3559     if (android_op_nand_limits) {
3560         parse_nand_limits(android_op_nand_limits);
3561     }
3562 #endif  // CONFIG_NAND_LIMITS
3563 
3564     /* Initialize AVD name from hardware configuration if needed */
3565     if (!android_op_avd_name) {
3566         if (android_hw->avd_name && *android_hw->avd_name) {
3567             android_op_avd_name = android_hw->avd_name;
3568             VERBOSE_PRINT(init,"AVD Name: %s", android_op_avd_name);
3569         }
3570     }
3571 
3572     /* Initialize system partition image */
3573     {
3574         char        tmp[PATH_MAX+32];
3575         const char* sysImage = android_hw->disk_systemPartition_path;
3576         const char* initImage = android_hw->disk_systemPartition_initPath;
3577         uint64_t    sysBytes = android_hw->disk_systemPartition_size;
3578 
3579         if (sysBytes == 0) {
3580             PANIC("Invalid system partition size: %" PRIu64, sysBytes);
3581         }
3582 
3583         snprintf(tmp,sizeof(tmp),"system,size=0x%" PRIx64, sysBytes);
3584 
3585         if (sysImage && *sysImage) {
3586             if (filelock_create(sysImage) == NULL) {
3587                 fprintf(stderr,"WARNING: System image already in use, changes will not persist!\n");
3588                 /* If there is no file= parameters, nand_add_dev will create
3589                  * a temporary file to back the partition image. */
3590             } else {
3591                 pstrcat(tmp,sizeof(tmp),",file=");
3592                 pstrcat(tmp,sizeof(tmp),sysImage);
3593             }
3594         }
3595         if (initImage && *initImage) {
3596             if (!path_exists(initImage)) {
3597                 PANIC("Invalid initial system image path: %s", initImage);
3598             }
3599             pstrcat(tmp,sizeof(tmp),",initfile=");
3600             pstrcat(tmp,sizeof(tmp),initImage);
3601         } else {
3602             PANIC("Missing initial system image path!");
3603         }
3604         nand_add_dev(tmp);
3605     }
3606 
3607     /* Initialize data partition image */
3608     {
3609         char        tmp[PATH_MAX+32];
3610         const char* dataImage = android_hw->disk_dataPartition_path;
3611         const char* initImage = android_hw->disk_dataPartition_initPath;
3612         uint64_t    dataBytes = android_hw->disk_dataPartition_size;
3613 
3614         if (dataBytes == 0) {
3615             PANIC("Invalid data partition size: %" PRIu64, dataBytes);
3616         }
3617 
3618         snprintf(tmp,sizeof(tmp),"userdata,size=0x%" PRIx64, dataBytes);
3619 
3620         if (dataImage && *dataImage) {
3621             if (filelock_create(dataImage) == NULL) {
3622                 fprintf(stderr, "WARNING: Data partition already in use. Changes will not persist!\n");
3623                 /* Note: if there is no file= parameters, nand_add_dev() will
3624                  *       create a temporary file to back the partition image. */
3625             } else {
3626                 /* Create the file if needed */
3627                 if (!path_exists(dataImage)) {
3628                     if (path_empty_file(dataImage) < 0) {
3629                         PANIC("Could not create data image file %s: %s", dataImage, strerror(errno));
3630                     }
3631                 }
3632                 pstrcat(tmp, sizeof(tmp), ",file=");
3633                 pstrcat(tmp, sizeof(tmp), dataImage);
3634             }
3635         }
3636         if (initImage && *initImage) {
3637             pstrcat(tmp, sizeof(tmp), ",initfile=");
3638             pstrcat(tmp, sizeof(tmp), initImage);
3639         }
3640         nand_add_dev(tmp);
3641     }
3642 
3643     /* Init SD-Card stuff. For Android, it is always hda */
3644     /* If the -hda option was used, ignore the Android-provided one */
3645     if (hda_opts == NULL) {
3646         const char* sdPath = android_hw->hw_sdCard_path;
3647         if (sdPath && *sdPath) {
3648             if (!path_exists(sdPath)) {
3649                 fprintf(stderr, "WARNING: SD Card image is missing: %s\n", sdPath);
3650             } else if (filelock_create(sdPath) == NULL) {
3651                 fprintf(stderr, "WARNING: SD Card image already in use: %s\n", sdPath);
3652             } else {
3653                 /* Successful locking */
3654                 hda_opts = drive_add(sdPath, HD_ALIAS, 0);
3655                 /* Set this property of any operation involving the SD Card
3656                  * will be x100 slower, due to the corresponding file being
3657                  * mounted as O_DIRECT. Note that this is only 'unsafe' in
3658                  * the context of an emulator crash. The data is already
3659                  * synced properly when the emulator exits (either normally or through ^C).
3660                  */
3661                 qemu_opt_set(hda_opts, "cache", "unsafe");
3662             }
3663         }
3664     }
3665 
3666     if (hdb_opts == NULL) {
3667         const char* spath = android_hw->disk_snapStorage_path;
3668         if (spath && *spath) {
3669             if (!path_exists(spath)) {
3670                 PANIC("Snapshot storage file does not exist: %s", spath);
3671             }
3672             if (filelock_create(spath) == NULL) {
3673                 PANIC("Snapshot storage already in use: %s", spath);
3674             }
3675             hdb_opts = drive_add(spath, HD_ALIAS, 1);
3676             /* See comment above to understand why this is needed. */
3677             qemu_opt_set(hdb_opts, "cache", "unsafe");
3678         }
3679     }
3680 
3681     /* Set the VM's max heap size, passed as a boot property */
3682     if (android_hw->vm_heapSize > 0) {
3683         char  tmp[64];
3684         snprintf(tmp, sizeof(tmp), "%dm", android_hw->vm_heapSize);
3685         boot_property_add("dalvik.vm.heapsize",tmp);
3686     }
3687 
3688     /* Initialize net speed and delays stuff. */
3689     if (android_parse_network_speed(android_op_netspeed) < 0 ) {
3690         PANIC("invalid -netspeed parameter '%s'",
3691                 android_op_netspeed);
3692     }
3693 
3694     if ( android_parse_network_latency(android_op_netdelay) < 0 ) {
3695         PANIC("invalid -netdelay parameter '%s'",
3696                 android_op_netdelay);
3697     }
3698 
3699     if (android_op_netfast) {
3700         qemu_net_download_speed = 0;
3701         qemu_net_upload_speed = 0;
3702         qemu_net_min_latency = 0;
3703         qemu_net_max_latency = 0;
3704     }
3705 
3706     /* Initialize LCD density */
3707     if (android_hw->hw_lcd_density) {
3708         long density = android_hw->hw_lcd_density;
3709         if (density <= 0) {
3710             PANIC("Invalid hw.lcd.density value: %ld", density);
3711         }
3712         hwLcd_setBootProperty(density);
3713     }
3714 
3715     /* Initialize presence of hardware nav button */
3716     boot_property_add("qemu.hw.mainkeys", android_hw->hw_mainKeys ? "1" : "0");
3717 
3718     /* Initialize TCP dump */
3719     if (android_op_tcpdump) {
3720         if (qemu_tcpdump_start(android_op_tcpdump) < 0) {
3721             fprintf(stdout, "could not start packet capture: %s\n", strerror(errno));
3722         }
3723     }
3724 
3725     /* Initialize modem */
3726     if (android_op_radio) {
3727         CharDriverState*  cs = qemu_chr_open("radio", android_op_radio, NULL);
3728         if (cs == NULL) {
3729             PANIC("unsupported character device specification: %s\n"
3730                         "used -help-char-devices for list of available formats",
3731                     android_op_radio);
3732         }
3733         android_qemud_set_channel( ANDROID_QEMUD_GSM, cs);
3734     } else if (android_hw->hw_gsmModem != 0 ) {
3735         if ( android_qemud_get_channel( ANDROID_QEMUD_GSM, &android_modem_cs ) < 0 ) {
3736             PANIC("could not initialize qemud 'gsm' channel");
3737         }
3738     }
3739 
3740     /* Initialize GPS */
3741     if (android_op_gps) {
3742         CharDriverState*  cs = qemu_chr_open("gps", android_op_gps, NULL);
3743         if (cs == NULL) {
3744             PANIC("unsupported character device specification: %s\n"
3745                         "used -help-char-devices for list of available formats",
3746                     android_op_gps);
3747         }
3748         android_qemud_set_channel( ANDROID_QEMUD_GPS, cs);
3749     } else if (android_hw->hw_gps != 0) {
3750         if ( android_qemud_get_channel( "gps", &android_gps_cs ) < 0 ) {
3751             PANIC("could not initialize qemud 'gps' channel");
3752         }
3753     }
3754 
3755     /* Initialize audio. */
3756     if (android_op_audio) {
3757         if ( !audio_check_backend_name( 0, android_op_audio ) ) {
3758             PANIC("'%s' is not a valid audio output backend. see -help-audio-out",
3759                     android_op_audio);
3760         }
3761         setenv("QEMU_AUDIO_DRV", android_op_audio, 1);
3762     }
3763 
3764     /* Initialize OpenGLES emulation */
3765     //android_hw_opengles_init();
3766 
3767     /* Initialize fake camera */
3768     if (strcmp(android_hw->hw_camera_back, "emulated") &&
3769         strcmp(android_hw->hw_camera_front, "emulated")) {
3770         /* Fake camera is not used for camera emulation. */
3771         boot_property_add("qemu.sf.fake_camera", "none");
3772     } else {
3773         /* Fake camera is used for at least one camera emulation. */
3774         if (!strcmp(android_hw->hw_camera_back, "emulated") &&
3775             !strcmp(android_hw->hw_camera_front, "emulated")) {
3776             /* Fake camera is used for both, front and back camera emulation. */
3777             boot_property_add("qemu.sf.fake_camera", "both");
3778         } else if (!strcmp(android_hw->hw_camera_back, "emulated")) {
3779             boot_property_add("qemu.sf.fake_camera", "back");
3780         } else {
3781             boot_property_add("qemu.sf.fake_camera", "front");
3782         }
3783     }
3784 
3785     /* Set LCD density (if required by -qemu, and AVD is missing it. */
3786     if (android_op_lcd_density && !android_hw->hw_lcd_density) {
3787         int density;
3788         if (parse_int(android_op_lcd_density, &density) || density <= 0) {
3789             PANIC("-lcd-density : %d", density);
3790         }
3791         hwLcd_setBootProperty(density);
3792     }
3793 
3794     /* Initialize camera emulation. */
3795     android_camera_service_init();
3796 
3797     if (android_op_cpu_delay) {
3798         char*   end;
3799         long    delay = strtol(android_op_cpu_delay, &end, 0);
3800         if (end == NULL || *end || delay < 0 || delay > 1000 ) {
3801             PANIC("option -cpu-delay must be an integer between 0 and 1000" );
3802         }
3803         if (delay > 0)
3804             delay = (1000-delay);
3805 
3806         qemu_cpu_delay = (int) delay;
3807     }
3808 
3809     if (android_op_dns_server) {
3810         char*  x = strchr(android_op_dns_server, ',');
3811         dns_count = 0;
3812         if (x == NULL)
3813         {
3814             if ( add_dns_server( android_op_dns_server ) == 0 )
3815                 dns_count = 1;
3816         }
3817         else
3818         {
3819             x = android_op_dns_server;
3820             while (*x) {
3821                 char*  y = strchr(x, ',');
3822 
3823                 if (y != NULL) {
3824                     *y = 0;
3825                     y++;
3826                 } else {
3827                     y = x + strlen(x);
3828                 }
3829 
3830                 if (y > x && add_dns_server( x ) == 0) {
3831                     dns_count += 1;
3832                 }
3833                 x = y;
3834             }
3835         }
3836         if (dns_count == 0)
3837             fprintf( stdout, "### WARNING: will use system default DNS server\n" );
3838     }
3839 
3840     if (dns_count == 0)
3841         dns_count = slirp_get_system_dns_servers();
3842     if (dns_count) {
3843         stralloc_add_format(kernel_config, " ndns=%d", dns_count);
3844     }
3845 
3846 #ifdef CONFIG_MEMCHECK
3847     if (android_op_memcheck) {
3848         memcheck_init(android_op_memcheck);
3849     }
3850 #endif  // CONFIG_MEMCHECK
3851 
3852     /* Initialize cache partition, if any */
3853     if (android_hw->disk_cachePartition != 0) {
3854         char        tmp[PATH_MAX+32];
3855         const char* partPath = android_hw->disk_cachePartition_path;
3856         uint64_t    partSize = android_hw->disk_cachePartition_size;
3857 
3858         snprintf(tmp,sizeof(tmp),"cache,size=0x%" PRIx64, partSize);
3859 
3860         if (partPath && *partPath && strcmp(partPath, "<temp>") != 0) {
3861             if (filelock_create(partPath) == NULL) {
3862                 fprintf(stderr, "WARNING: Cache partition already in use. Changes will not persist!\n");
3863                 /* Note: if there is no file= parameters, nand_add_dev() will
3864                  *       create a temporary file to back the partition image. */
3865             } else {
3866                 /* Create the file if needed */
3867                 if (!path_exists(partPath)) {
3868                     if (path_empty_file(partPath) < 0) {
3869                         PANIC("Could not create cache image file %s: %s", partPath, strerror(errno));
3870                     }
3871                 }
3872                 pstrcat(tmp, sizeof(tmp), ",file=");
3873                 pstrcat(tmp, sizeof(tmp), partPath);
3874             }
3875         }
3876         nand_add_dev(tmp);
3877     }
3878 
3879     /* qemu.gles will be read by the OpenGL ES emulation libraries.
3880      * If set to 0, the software GL ES renderer will be used as a fallback.
3881      * If the parameter is undefined, this means the system image runs
3882      * inside an emulator that doesn't support GPU emulation at all.
3883      *
3884      * We always start the GL ES renderer so we can gather stats on the
3885      * underlying GL implementation. If GL ES acceleration is disabled,
3886      * we just shut it down again once we have the strings. */
3887     {
3888         int qemu_gles = 0;
3889         if (android_initOpenglesEmulation() == 0 &&
3890             android_startOpenglesRenderer(android_hw->hw_lcd_width, android_hw->hw_lcd_height) == 0)
3891         {
3892             android_getOpenglesHardwareStrings(
3893                     android_gl_vendor, sizeof(android_gl_vendor),
3894                     android_gl_renderer, sizeof(android_gl_renderer),
3895                     android_gl_version, sizeof(android_gl_version));
3896             if (android_hw->hw_gpu_enabled) {
3897                 qemu_gles = 1;
3898             } else {
3899                 android_stopOpenglesRenderer();
3900                 qemu_gles = 0;
3901             }
3902         } else {
3903             dwarning("Could not initialize OpenglES emulation, using software renderer.");
3904         }
3905         if (qemu_gles) {
3906             stralloc_add_str(kernel_params, " qemu.gles=1");
3907         } else {
3908             stralloc_add_str(kernel_params, " qemu.gles=0");
3909         }
3910     }
3911 
3912     /* We always force qemu=1 when running inside QEMU */
3913     stralloc_add_str(kernel_params, " qemu=1");
3914 
3915     /* We always initialize the first serial port for the android-kmsg
3916      * character device (used to send kernel messages) */
3917     serial_hds_add_at(0, "android-kmsg");
3918     stralloc_add_str(kernel_params, " console=ttyS0");
3919 
3920     /* We always initialize the second serial port for the android-qemud
3921      * character device as well */
3922     serial_hds_add_at(1, "android-qemud");
3923     stralloc_add_str(kernel_params, " android.qemud=ttyS1");
3924 
3925     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3926         os_pidfile_error();
3927         exit(1);
3928     }
3929 
3930 #if defined(CONFIG_KVM)
3931     if (kvm_allowed < 0) {
3932         kvm_allowed = kvm_check_allowed();
3933     }
3934 #endif
3935 
3936 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
3937     if (kvm_allowed && kqemu_allowed) {
3938         PANIC(
3939                 "You can not enable both KVM and kqemu at the same time");
3940     }
3941 #endif
3942 
3943     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3944     if (smp_cpus > machine->max_cpus) {
3945         PANIC("Number of SMP cpus requested (%d), exceeds max cpus "
3946                 "supported by machine `%s' (%d)", smp_cpus,  machine->name,
3947                 machine->max_cpus);
3948     }
3949 
3950     if (display_type == DT_NOGRAPHIC) {
3951        if (serial_device_index == 0)
3952            serial_devices[0] = "stdio";
3953        if (parallel_device_index == 0)
3954            parallel_devices[0] = "null";
3955        if (strncmp(monitor_device, "vc", 2) == 0)
3956            monitor_device = "stdio";
3957     }
3958 
3959 #ifdef CONFIG_KQEMU
3960     if (smp_cpus > 1)
3961         kqemu_allowed = 0;
3962 #endif
3963     if (qemu_init_main_loop()) {
3964         PANIC("qemu_init_main_loop failed");
3965     }
3966 
3967     if (kernel_filename == NULL) {
3968         kernel_filename = android_hw->kernel_path;
3969     }
3970     if (initrd_filename == NULL) {
3971         initrd_filename = android_hw->disk_ramdisk_path;
3972     }
3973 
3974     linux_boot = (kernel_filename != NULL);
3975     net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
3976 
3977     if (!linux_boot && *kernel_cmdline != '\0') {
3978         PANIC("-append only allowed with -kernel option");
3979     }
3980 
3981     if (!linux_boot && initrd_filename != NULL) {
3982         PANIC("-initrd only allowed with -kernel option");
3983     }
3984 
3985     /* boot to floppy or the default cd if no hard disk defined yet */
3986     if (!boot_devices[0]) {
3987         boot_devices = "cad";
3988     }
3989     os_set_line_buffering();
3990 
3991     if (init_timer_alarm() < 0) {
3992         PANIC("could not initialize alarm timer");
3993     }
3994     configure_icount(icount_option);
3995 
3996     /* init network clients */
3997     if (nb_net_clients == 0) {
3998         /* if no clients, we use a default config */
3999         net_clients[nb_net_clients++] = "nic";
4000 #ifdef CONFIG_SLIRP
4001         net_clients[nb_net_clients++] = "user";
4002 #endif
4003     }
4004 
4005     for(i = 0;i < nb_net_clients; i++) {
4006         if (net_client_parse(net_clients[i]) < 0) {
4007             PANIC("Unable to parse net clients");
4008         }
4009     }
4010     net_client_check();
4011 
4012 #ifdef TARGET_I386
4013     /* XXX: this should be moved in the PC machine instantiation code */
4014     if (net_boot != 0) {
4015         int netroms = 0;
4016 	for (i = 0; i < nb_nics && i < 4; i++) {
4017 	    const char *model = nd_table[i].model;
4018 	    char buf[1024];
4019             char *filename;
4020             if (net_boot & (1 << i)) {
4021                 if (model == NULL)
4022                     model = "ne2k_pci";
4023                 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
4024                 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
4025                 if (filename && get_image_size(filename) > 0) {
4026                     if (nb_option_roms >= MAX_OPTION_ROMS) {
4027                         PANIC("Too many option ROMs");
4028                     }
4029                     option_rom[nb_option_roms] = qemu_strdup(buf);
4030                     nb_option_roms++;
4031                     netroms++;
4032                 }
4033                 if (filename) {
4034                     qemu_free(filename);
4035                 }
4036             }
4037 	}
4038 	if (netroms == 0) {
4039 	    PANIC("No valid PXE rom found for network device");
4040 	}
4041     }
4042 #endif
4043 
4044     /* init the bluetooth world */
4045     for (i = 0; i < nb_bt_opts; i++)
4046         if (bt_parse(bt_opts[i])) {
4047             PANIC("Unable to parse bluetooth options");
4048         }
4049 
4050     /* init the memory */
4051     if (ram_size == 0) {
4052         ram_size = android_hw->hw_ramSize * 1024LL * 1024;
4053         if (ram_size == 0) {
4054             ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4055         }
4056     }
4057 
4058     /* Quite often (especially on older XP machines) attempts to allocate large
4059      * VM RAM is going to fail, and crash the emulator. Since it's failing deep
4060      * inside QEMU, it's not really possible to provide the user with a
4061      * meaningful explanation for the crash. So, lets see if QEMU is going to be
4062      * able to allocate requested amount of RAM, and if not, lets try to come up
4063      * with a recomendation. */
4064     {
4065         ram_addr_t r_ram = ram_size;
4066         void* alloc_check = malloc(r_ram);
4067         while (alloc_check == NULL && r_ram > 1024 * 1024) {
4068         /* Make it 25% less */
4069             r_ram -= r_ram / 4;
4070             alloc_check = malloc(r_ram);
4071         }
4072         if (alloc_check != NULL) {
4073             free(alloc_check);
4074         }
4075         if (r_ram != ram_size) {
4076             /* Requested RAM is too large. Report this, as well as calculated
4077              * recomendation. */
4078             dwarning("Requested RAM size of %dMB is too large for your environment, and is reduced to %dMB.",
4079                      (int)(ram_size / 1024 / 1024), (int)(r_ram / 1024 / 1024));
4080             ram_size = r_ram;
4081         }
4082     }
4083 
4084 #ifdef CONFIG_KQEMU
4085     /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
4086        guest ram allocation.  It needs to go away.  */
4087     if (kqemu_allowed) {
4088         kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
4089         kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
4090         if (!kqemu_phys_ram_base) {
4091             PANIC("Could not allocate physical memory");
4092         }
4093     }
4094 #endif
4095 
4096 #ifndef _WIN32
4097     init_qemu_clear_logs_sig();
4098 #endif
4099 
4100     /* init the dynamic translator */
4101     cpu_exec_init_all(tb_size * 1024 * 1024);
4102 
4103     bdrv_init();
4104 
4105     /* we always create the cdrom drive, even if no disk is there */
4106 #if 0
4107     if (nb_drives_opt < MAX_DRIVES)
4108         drive_add(NULL, CDROM_ALIAS);
4109 
4110     /* we always create at least one floppy */
4111 
4112     if (nb_drives_opt < MAX_DRIVES)
4113         drive_add(NULL, FD_ALIAS, 0);
4114     /* we always create one sd slot, even if no card is in it */
4115 
4116     if (1) {
4117         drive_add(NULL, SD_ALIAS);
4118     }
4119 #endif
4120 
4121     /* open the virtual block devices */
4122     if (snapshot)
4123         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
4124     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
4125         exit(1);
4126 
4127     //register_savevm("timer", 0, 2, timer_save, timer_load, &timers_state);
4128     register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
4129 
4130     /* must be after terminal init, SDL library changes signal handlers */
4131     os_setup_signal_handling();
4132 
4133     /* Maintain compatibility with multiple stdio monitors */
4134     if (!strcmp(monitor_device,"stdio")) {
4135         for (i = 0; i < MAX_SERIAL_PORTS; i++) {
4136             const char *devname = serial_devices[i];
4137             if (devname && !strcmp(devname,"mon:stdio")) {
4138                 monitor_device = NULL;
4139                 break;
4140             } else if (devname && !strcmp(devname,"stdio")) {
4141                 monitor_device = NULL;
4142                 serial_devices[i] = "mon:stdio";
4143                 break;
4144             }
4145         }
4146     }
4147 
4148     if (nb_numa_nodes > 0) {
4149         int i;
4150 
4151         if (nb_numa_nodes > smp_cpus) {
4152             nb_numa_nodes = smp_cpus;
4153         }
4154 
4155         /* If no memory size if given for any node, assume the default case
4156          * and distribute the available memory equally across all nodes
4157          */
4158         for (i = 0; i < nb_numa_nodes; i++) {
4159             if (node_mem[i] != 0)
4160                 break;
4161         }
4162         if (i == nb_numa_nodes) {
4163             uint64_t usedmem = 0;
4164 
4165             /* On Linux, the each node's border has to be 8MB aligned,
4166              * the final node gets the rest.
4167              */
4168             for (i = 0; i < nb_numa_nodes - 1; i++) {
4169                 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4170                 usedmem += node_mem[i];
4171             }
4172             node_mem[i] = ram_size - usedmem;
4173         }
4174 
4175         for (i = 0; i < nb_numa_nodes; i++) {
4176             if (node_cpumask[i] != 0)
4177                 break;
4178         }
4179         /* assigning the VCPUs round-robin is easier to implement, guest OSes
4180          * must cope with this anyway, because there are BIOSes out there in
4181          * real machines which also use this scheme.
4182          */
4183         if (i == nb_numa_nodes) {
4184             for (i = 0; i < smp_cpus; i++) {
4185                 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4186             }
4187         }
4188     }
4189 
4190     if (kvm_enabled()) {
4191         int ret;
4192 
4193         ret = kvm_init(smp_cpus);
4194         if (ret < 0) {
4195             PANIC("failed to initialize KVM");
4196         }
4197     }
4198 
4199 #ifdef CONFIG_HAX
4200     if (!hax_disabled)
4201     {
4202         int ret;
4203 
4204         hax_set_ramsize(ram_size);
4205         ret = hax_init(smp_cpus);
4206         fprintf(stderr, "HAX is %s and emulator runs in %s mode\n",
4207             !ret ? "working" :"not working", !ret ? "fast virt" : "emulation");
4208     }
4209 #endif
4210 
4211     if (monitor_device) {
4212         monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
4213         if (!monitor_hd) {
4214             PANIC("qemu: could not open monitor device '%s'",
4215                               monitor_device);
4216         }
4217     }
4218 
4219     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4220         serial_hds_add(serial_devices[i]);
4221     }
4222 
4223     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4224         const char *devname = parallel_devices[i];
4225         if (devname && strcmp(devname, "none")) {
4226             char label[32];
4227             snprintf(label, sizeof(label), "parallel%d", i);
4228             parallel_hds[i] = qemu_chr_open(label, devname, NULL);
4229             if (!parallel_hds[i]) {
4230                 PANIC("qemu: could not open parallel device '%s'",
4231                         devname);
4232             }
4233         }
4234     }
4235 
4236     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
4237         const char *devname = virtio_consoles[i];
4238         if (devname && strcmp(devname, "none")) {
4239             char label[32];
4240             snprintf(label, sizeof(label), "virtcon%d", i);
4241             virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
4242             if (!virtcon_hds[i]) {
4243                 PANIC("qemu: could not open virtio console '%s'",
4244                         devname);
4245             }
4246         }
4247     }
4248 
4249     module_call_init(MODULE_INIT_DEVICE);
4250 
4251 
4252 #ifdef CONFIG_TRACE
4253     if (trace_filename) {
4254         trace_init(trace_filename);
4255         fprintf(stderr, "-- When done tracing, exit the emulator. --\n");
4256     }
4257 #endif
4258 
4259     /* Check the CPU Architecture value */
4260 #if defined(TARGET_ARM)
4261     if (strcmp(android_hw->hw_cpu_arch,"arm") != 0) {
4262         fprintf(stderr, "-- Invalid CPU architecture: %s, expected 'arm'\n",
4263                 android_hw->hw_cpu_arch);
4264         exit(1);
4265     }
4266 #elif defined(TARGET_I386)
4267     if (strcmp(android_hw->hw_cpu_arch,"x86") != 0) {
4268         fprintf(stderr, "-- Invalid CPU architecture: %s, expected 'x86'\n",
4269                 android_hw->hw_cpu_arch);
4270         exit(1);
4271     }
4272 #endif
4273 
4274     /* Grab CPU model if provided in hardware.ini */
4275     if (    !cpu_model
4276          && android_hw->hw_cpu_model
4277          && android_hw->hw_cpu_model[0] != '\0')
4278     {
4279         cpu_model = android_hw->hw_cpu_model;
4280     }
4281 
4282     /* Combine kernel command line passed from the UI with parameters
4283      * collected during initialization.
4284      *
4285      * The order is the following:
4286      * - parameters from the hw configuration (kernel.parameters)
4287      * - additionnal parameters from options (e.g. -memcheck)
4288      * - the -append parameters.
4289      */
4290     {
4291         const char* kernel_parameters;
4292 
4293         if (android_hw->kernel_parameters) {
4294             stralloc_add_c(kernel_params, ' ');
4295             stralloc_add_str(kernel_params, android_hw->kernel_parameters);
4296         }
4297 
4298         /* If not empty, kernel_config always contains a leading space */
4299         stralloc_append(kernel_params, kernel_config);
4300 
4301         if (*kernel_cmdline) {
4302             stralloc_add_c(kernel_params, ' ');
4303             stralloc_add_str(kernel_params, kernel_cmdline);
4304         }
4305 
4306         /* Remove any leading/trailing spaces */
4307         stralloc_strip(kernel_params);
4308 
4309         kernel_parameters = stralloc_cstr(kernel_params);
4310         VERBOSE_PRINT(init, "Kernel parameters: %s", kernel_parameters);
4311 
4312         machine->init(ram_size,
4313                       boot_devices,
4314                       kernel_filename,
4315                       kernel_parameters,
4316                       initrd_filename,
4317                       cpu_model);
4318 
4319         /* Initialize multi-touch emulation. */
4320         if (androidHwConfig_isScreenMultiTouch(android_hw)) {
4321             mts_port_create(NULL);
4322         }
4323 
4324         stralloc_reset(kernel_params);
4325         stralloc_reset(kernel_config);
4326     }
4327 
4328     for (env = first_cpu; env != NULL; env = env->next_cpu) {
4329         for (i = 0; i < nb_numa_nodes; i++) {
4330             if (node_cpumask[i] & (1 << env->cpu_index)) {
4331                 env->numa_node = i;
4332             }
4333         }
4334     }
4335 
4336     current_machine = machine;
4337 
4338     /* Set KVM's vcpu state to qemu's initial CPUState. */
4339     if (kvm_enabled()) {
4340         int ret;
4341 
4342         ret = kvm_sync_vcpus();
4343         if (ret < 0) {
4344             PANIC("failed to initialize vcpus");
4345         }
4346     }
4347 
4348 #ifdef CONFIG_HAX
4349     if (hax_enabled())
4350         hax_sync_vcpus();
4351 #endif
4352 
4353     /* init USB devices */
4354     if (usb_enabled) {
4355         for(i = 0; i < usb_devices_index; i++) {
4356             if (usb_device_add(usb_devices[i], 0) < 0) {
4357                 fprintf(stderr, "Warning: could not add USB device %s\n",
4358                         usb_devices[i]);
4359             }
4360         }
4361     }
4362 
4363     /* just use the first displaystate for the moment */
4364     ds = get_displaystate();
4365 
4366     /* Initialize display from the command line parameters. */
4367     android_display_reset(ds,
4368                           android_display_width,
4369                           android_display_height,
4370                           android_display_bpp);
4371 
4372     if (display_type == DT_DEFAULT) {
4373 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4374         display_type = DT_SDL;
4375 #else
4376         display_type = DT_VNC;
4377         vnc_display = "localhost:0,to=99";
4378         show_vnc_port = 1;
4379 #endif
4380     }
4381 
4382 
4383     switch (display_type) {
4384     case DT_NOGRAPHIC:
4385         break;
4386 #if defined(CONFIG_CURSES)
4387     case DT_CURSES:
4388         curses_display_init(ds, full_screen);
4389         break;
4390 #endif
4391 #if defined(CONFIG_SDL) && !defined(CONFIG_STANDALONE_CORE)
4392     case DT_SDL:
4393         sdl_display_init(ds, full_screen, no_frame);
4394         break;
4395 #elif defined(CONFIG_COCOA)
4396     case DT_SDL:
4397         cocoa_display_init(ds, full_screen);
4398         break;
4399 #elif defined(CONFIG_STANDALONE_CORE)
4400     case DT_SDL:
4401         coredisplay_init(ds);
4402         break;
4403 #endif
4404     case DT_VNC:
4405         vnc_display_init(ds);
4406         if (vnc_display_open(ds, vnc_display) < 0) {
4407             PANIC("Unable to initialize VNC display");
4408         }
4409 
4410         if (show_vnc_port) {
4411             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4412         }
4413         break;
4414     default:
4415         break;
4416     }
4417     dpy_resize(ds);
4418 
4419     dcl = ds->listeners;
4420     while (dcl != NULL) {
4421         if (dcl->dpy_refresh != NULL) {
4422             ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
4423             qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
4424         }
4425         dcl = dcl->next;
4426     }
4427 
4428     if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4429         nographic_timer = qemu_new_timer_ms(rt_clock, nographic_update, NULL);
4430         qemu_mod_timer(nographic_timer, qemu_get_clock_ms(rt_clock));
4431     }
4432 
4433     text_consoles_set_display(ds);
4434     qemu_chr_initial_reset();
4435 
4436     if (monitor_device && monitor_hd)
4437         monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
4438 
4439     for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4440         const char *devname = serial_devices[i];
4441         if (devname && strcmp(devname, "none")) {
4442             if (strstart(devname, "vc", 0))
4443                 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
4444         }
4445     }
4446 
4447     for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4448         const char *devname = parallel_devices[i];
4449         if (devname && strcmp(devname, "none")) {
4450             if (strstart(devname, "vc", 0))
4451                 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
4452         }
4453     }
4454 
4455     for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
4456         const char *devname = virtio_consoles[i];
4457         if (virtcon_hds[i] && devname) {
4458             if (strstart(devname, "vc", 0))
4459                 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
4460         }
4461     }
4462 
4463     if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
4464         PANIC("qemu: could not open gdbserver on device '%s'",
4465                 gdbstub_dev);
4466     }
4467 
4468     /* call android-specific setup function */
4469     android_emulation_setup();
4470 
4471 #if !defined(CONFIG_STANDALONE_CORE)
4472     // For the standalone emulator (UI+core in one executable) we need to
4473     // set the window title here.
4474     android_emulator_set_base_port(android_base_port);
4475 #endif
4476 
4477     if (loadvm)
4478         do_loadvm(cur_mon, loadvm);
4479 
4480     if (incoming) {
4481         autostart = 0; /* fixme how to deal with -daemonize */
4482         qemu_start_incoming_migration(incoming);
4483     }
4484 
4485     if (autostart)
4486         vm_start();
4487 
4488     os_setup_post();
4489 
4490 #ifdef CONFIG_ANDROID
4491     // This will notify the UI that the core is successfuly initialized
4492     android_core_init_completed();
4493 #endif  // CONFIG_ANDROID
4494 
4495     main_loop();
4496     quit_timers();
4497     net_cleanup();
4498     android_emulation_teardown();
4499     return 0;
4500 }
4501 
4502 void
android_emulation_teardown(void)4503 android_emulation_teardown(void)
4504 {
4505     android_charmap_done();
4506 }
4507