]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - vl.c
apohw: A bit advanced virtual hd44780 driver. Needs fixes.
[lisovros/qemu_apohw.git] / vl.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <net/if.h>
46 #include <arpa/inet.h>
47 #include <dirent.h>
48 #include <netdb.h>
49 #include <sys/select.h>
50
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #include <sys/sysctl.h>
56 #else
57 #include <util.h>
58 #endif
59 #else
60 #ifdef __linux__
61 #include <pty.h>
62 #include <malloc.h>
63
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/ip.h>
74 #include <netinet/ip_icmp.h> // must come after ip.h
75 #include <netinet/udp.h>
76 #include <netinet/tcp.h>
77 #include <net/if.h>
78 #include <syslog.h>
79 #include <stropts.h>
80 #endif
81 #endif
82 #endif
83
84 #if defined(__OpenBSD__)
85 #include <util.h>
86 #endif
87
88 #if defined(CONFIG_VDE)
89 #include <libvdeplug.h>
90 #endif
91
92 #ifdef _WIN32
93 #include <windows.h>
94 #endif
95
96 #ifdef CONFIG_SDL
97 #if defined(__APPLE__) || defined(main)
98 #include <SDL.h>
99 int qemu_main(int argc, char **argv, char **envp);
100 int main(int argc, char **argv)
101 {
102     return qemu_main(argc, argv, NULL);
103 }
104 #undef main
105 #define main qemu_main
106 #endif
107 #endif /* CONFIG_SDL */
108
109 #ifdef CONFIG_COCOA
110 #undef main
111 #define main qemu_main
112 #endif /* CONFIG_COCOA */
113
114 #include <glib.h>
115
116 #include "hw/hw.h"
117 #include "hw/boards.h"
118 #include "hw/usb.h"
119 #include "hw/pcmcia.h"
120 #include "hw/pc.h"
121 #include "hw/isa.h"
122 #include "hw/baum.h"
123 #include "hw/bt.h"
124 #include "hw/watchdog.h"
125 #include "hw/smbios.h"
126 #include "hw/xen.h"
127 #include "hw/qdev.h"
128 #include "hw/loader.h"
129 #include "bt-host.h"
130 #include "net.h"
131 #include "net/slirp.h"
132 #include "monitor.h"
133 #include "console.h"
134 #include "sysemu.h"
135 #include "gdbstub.h"
136 #include "qemu-timer.h"
137 #include "qemu-char.h"
138 #include "cache-utils.h"
139 #include "block.h"
140 #include "blockdev.h"
141 #include "block-migration.h"
142 #include "dma.h"
143 #include "audio/audio.h"
144 #include "migration.h"
145 #include "kvm.h"
146 #include "qjson.h"
147 #include "qemu-option.h"
148 #include "qemu-config.h"
149 #include "qemu-options.h"
150 #include "qmp-commands.h"
151 #include "main-loop.h"
152 #ifdef CONFIG_VIRTFS
153 #include "fsdev/qemu-fsdev.h"
154 #endif
155
156 #include "disas.h"
157
158 #include "qemu_socket.h"
159
160 #include "slirp/libslirp.h"
161
162 #include "trace.h"
163 #include "trace/control.h"
164 #include "qemu-queue.h"
165 #include "cpus.h"
166 #include "arch_init.h"
167
168 #include "ui/qemu-spice.h"
169
170 //#define DEBUG_NET
171 //#define DEBUG_SLIRP
172
173 #define DEFAULT_RAM_SIZE 128
174
175 #define MAX_VIRTIO_CONSOLES 1
176
177 static const char *data_dir;
178 const char *bios_name = NULL;
179 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
180 DisplayType display_type = DT_DEFAULT;
181 int display_remote = 0;
182 const char* keyboard_layout = NULL;
183 ram_addr_t ram_size;
184 const char *mem_path = NULL;
185 #ifdef MAP_POPULATE
186 int mem_prealloc = 0; /* force preallocation of physical target memory */
187 #endif
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int autostart;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 QEMUClock *rtc_clock;
194 int vga_interface_type = VGA_NONE;
195 static int full_screen = 0;
196 #ifdef CONFIG_SDL
197 static int no_frame = 0;
198 #endif
199 int no_quit = 0;
200 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
201 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
202 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
203 int win2k_install_hack = 0;
204 int rtc_td_hack = 0;
205 int usb_enabled = 0;
206 int singlestep = 0;
207 int smp_cpus = 1;
208 int max_cpus = 0;
209 int smp_cores = 1;
210 int smp_threads = 1;
211 #ifdef CONFIG_VNC
212 const char *vnc_display;
213 #endif
214 int acpi_enabled = 1;
215 int no_hpet = 0;
216 int fd_bootchk = 1;
217 int no_reboot = 0;
218 int no_shutdown = 0;
219 int cursor_hide = 1;
220 int graphic_rotate = 0;
221 const char *watchdog;
222 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
223 int nb_option_roms;
224 int semihosting_enabled = 0;
225 int old_param = 0;
226 const char *qemu_name;
227 int alt_grab = 0;
228 int ctrl_grab = 0;
229 unsigned int nb_prom_envs = 0;
230 const char *prom_envs[MAX_PROM_ENVS];
231 int boot_menu;
232 uint8_t *boot_splash_filedata;
233 int boot_splash_filedata_size;
234 uint8_t qemu_extra_params_fw[2];
235
236 typedef struct FWBootEntry FWBootEntry;
237
238 struct FWBootEntry {
239     QTAILQ_ENTRY(FWBootEntry) link;
240     int32_t bootindex;
241     DeviceState *dev;
242     char *suffix;
243 };
244
245 QTAILQ_HEAD(, FWBootEntry) fw_boot_order = QTAILQ_HEAD_INITIALIZER(fw_boot_order);
246
247 int nb_numa_nodes;
248 uint64_t node_mem[MAX_NODES];
249 uint64_t node_cpumask[MAX_NODES];
250
251 uint8_t qemu_uuid[16];
252
253 static QEMUBootSetHandler *boot_set_handler;
254 static void *boot_set_opaque;
255
256 static NotifierList exit_notifiers =
257     NOTIFIER_LIST_INITIALIZER(exit_notifiers);
258
259 static NotifierList machine_init_done_notifiers =
260     NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
261
262 static int tcg_allowed = 1;
263 int kvm_allowed = 0;
264 int xen_allowed = 0;
265 uint32_t xen_domid;
266 enum xen_mode xen_mode = XEN_EMULATE;
267 static int tcg_tb_size;
268
269 static int default_serial = 1;
270 static int default_parallel = 1;
271 static int default_virtcon = 1;
272 static int default_monitor = 1;
273 static int default_floppy = 1;
274 static int default_cdrom = 1;
275 static int default_sdcard = 1;
276
277 static struct {
278     const char *driver;
279     int *flag;
280 } default_list[] = {
281     { .driver = "isa-serial",           .flag = &default_serial    },
282     { .driver = "isa-parallel",         .flag = &default_parallel  },
283     { .driver = "isa-fdc",              .flag = &default_floppy    },
284     { .driver = "ide-cd",               .flag = &default_cdrom     },
285     { .driver = "ide-hd",               .flag = &default_cdrom     },
286     { .driver = "ide-drive",            .flag = &default_cdrom     },
287     { .driver = "scsi-cd",              .flag = &default_cdrom     },
288     { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
289     { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
290     { .driver = "virtio-serial",        .flag = &default_virtcon   },
291 };
292
293 static void res_free(void)
294 {
295     if (boot_splash_filedata != NULL) {
296         g_free(boot_splash_filedata);
297         boot_splash_filedata = NULL;
298     }
299 }
300
301 static int default_driver_check(QemuOpts *opts, void *opaque)
302 {
303     const char *driver = qemu_opt_get(opts, "driver");
304     int i;
305
306     if (!driver)
307         return 0;
308     for (i = 0; i < ARRAY_SIZE(default_list); i++) {
309         if (strcmp(default_list[i].driver, driver) != 0)
310             continue;
311         *(default_list[i].flag) = 0;
312     }
313     return 0;
314 }
315
316 /***********************************************************/
317 /* QEMU state */
318
319 static RunState current_run_state = RUN_STATE_PRELAUNCH;
320
321 typedef struct {
322     RunState from;
323     RunState to;
324 } RunStateTransition;
325
326 static const RunStateTransition runstate_transitions_def[] = {
327     /*     from      ->     to      */
328     { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
329
330     { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
331     { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
332
333     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
334     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
335
336     { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
337     { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
338
339     { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
340     { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
341
342     { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
343     { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
344
345     { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
346     { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
347     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
348
349     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
350     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
351
352     { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
353
354     { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
355     { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
356     { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
357     { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
358     { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
359     { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
360     { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
361     { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
362     { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
363
364     { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
365
366     { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
367     { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
368
369     { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
370     { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
371
372     { RUN_STATE_MAX, RUN_STATE_MAX },
373 };
374
375 static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
376
377 bool runstate_check(RunState state)
378 {
379     return current_run_state == state;
380 }
381
382 void runstate_init(void)
383 {
384     const RunStateTransition *p;
385
386     memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
387
388     for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
389         runstate_valid_transitions[p->from][p->to] = true;
390     }
391 }
392
393 /* This function will abort() on invalid state transitions */
394 void runstate_set(RunState new_state)
395 {
396     assert(new_state < RUN_STATE_MAX);
397
398     if (!runstate_valid_transitions[current_run_state][new_state]) {
399         fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
400                 RunState_lookup[current_run_state],
401                 RunState_lookup[new_state]);
402         abort();
403     }
404
405     current_run_state = new_state;
406 }
407
408 int runstate_is_running(void)
409 {
410     return runstate_check(RUN_STATE_RUNNING);
411 }
412
413 StatusInfo *qmp_query_status(Error **errp)
414 {
415     StatusInfo *info = g_malloc0(sizeof(*info));
416
417     info->running = runstate_is_running();
418     info->singlestep = singlestep;
419     info->status = current_run_state;
420
421     return info;
422 }
423
424 /***********************************************************/
425 /* real time host monotonic timer */
426
427 /***********************************************************/
428 /* host time/date access */
429 void qemu_get_timedate(struct tm *tm, int offset)
430 {
431     time_t ti;
432     struct tm *ret;
433
434     time(&ti);
435     ti += offset;
436     if (rtc_date_offset == -1) {
437         if (rtc_utc)
438             ret = gmtime(&ti);
439         else
440             ret = localtime(&ti);
441     } else {
442         ti -= rtc_date_offset;
443         ret = gmtime(&ti);
444     }
445
446     memcpy(tm, ret, sizeof(struct tm));
447 }
448
449 int qemu_timedate_diff(struct tm *tm)
450 {
451     time_t seconds;
452
453     if (rtc_date_offset == -1)
454         if (rtc_utc)
455             seconds = mktimegm(tm);
456         else {
457             struct tm tmp = *tm;
458             tmp.tm_isdst = -1; /* use timezone to figure it out */
459             seconds = mktime(&tmp);
460         }
461     else
462         seconds = mktimegm(tm) + rtc_date_offset;
463
464     return seconds - time(NULL);
465 }
466
467 void rtc_change_mon_event(struct tm *tm)
468 {
469     QObject *data;
470
471     data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
472     monitor_protocol_event(QEVENT_RTC_CHANGE, data);
473     qobject_decref(data);
474 }
475
476 static void configure_rtc_date_offset(const char *startdate, int legacy)
477 {
478     time_t rtc_start_date;
479     struct tm tm;
480
481     if (!strcmp(startdate, "now") && legacy) {
482         rtc_date_offset = -1;
483     } else {
484         if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
485                    &tm.tm_year,
486                    &tm.tm_mon,
487                    &tm.tm_mday,
488                    &tm.tm_hour,
489                    &tm.tm_min,
490                    &tm.tm_sec) == 6) {
491             /* OK */
492         } else if (sscanf(startdate, "%d-%d-%d",
493                           &tm.tm_year,
494                           &tm.tm_mon,
495                           &tm.tm_mday) == 3) {
496             tm.tm_hour = 0;
497             tm.tm_min = 0;
498             tm.tm_sec = 0;
499         } else {
500             goto date_fail;
501         }
502         tm.tm_year -= 1900;
503         tm.tm_mon--;
504         rtc_start_date = mktimegm(&tm);
505         if (rtc_start_date == -1) {
506         date_fail:
507             fprintf(stderr, "Invalid date format. Valid formats are:\n"
508                             "'2006-06-17T16:01:21' or '2006-06-17'\n");
509             exit(1);
510         }
511         rtc_date_offset = time(NULL) - rtc_start_date;
512     }
513 }
514
515 static void configure_rtc(QemuOpts *opts)
516 {
517     const char *value;
518
519     value = qemu_opt_get(opts, "base");
520     if (value) {
521         if (!strcmp(value, "utc")) {
522             rtc_utc = 1;
523         } else if (!strcmp(value, "localtime")) {
524             rtc_utc = 0;
525         } else {
526             configure_rtc_date_offset(value, 0);
527         }
528     }
529     value = qemu_opt_get(opts, "clock");
530     if (value) {
531         if (!strcmp(value, "host")) {
532             rtc_clock = host_clock;
533         } else if (!strcmp(value, "vm")) {
534             rtc_clock = vm_clock;
535         } else {
536             fprintf(stderr, "qemu: invalid option value '%s'\n", value);
537             exit(1);
538         }
539     }
540     value = qemu_opt_get(opts, "driftfix");
541     if (value) {
542         if (!strcmp(value, "slew")) {
543             rtc_td_hack = 1;
544         } else if (!strcmp(value, "none")) {
545             rtc_td_hack = 0;
546         } else {
547             fprintf(stderr, "qemu: invalid option value '%s'\n", value);
548             exit(1);
549         }
550     }
551 }
552
553 /***********************************************************/
554 /* Bluetooth support */
555 static int nb_hcis;
556 static int cur_hci;
557 static struct HCIInfo *hci_table[MAX_NICS];
558
559 static struct bt_vlan_s {
560     struct bt_scatternet_s net;
561     int id;
562     struct bt_vlan_s *next;
563 } *first_bt_vlan;
564
565 /* find or alloc a new bluetooth "VLAN" */
566 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
567 {
568     struct bt_vlan_s **pvlan, *vlan;
569     for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
570         if (vlan->id == id)
571             return &vlan->net;
572     }
573     vlan = g_malloc0(sizeof(struct bt_vlan_s));
574     vlan->id = id;
575     pvlan = &first_bt_vlan;
576     while (*pvlan != NULL)
577         pvlan = &(*pvlan)->next;
578     *pvlan = vlan;
579     return &vlan->net;
580 }
581
582 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
583 {
584 }
585
586 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
587 {
588     return -ENOTSUP;
589 }
590
591 static struct HCIInfo null_hci = {
592     .cmd_send = null_hci_send,
593     .sco_send = null_hci_send,
594     .acl_send = null_hci_send,
595     .bdaddr_set = null_hci_addr_set,
596 };
597
598 struct HCIInfo *qemu_next_hci(void)
599 {
600     if (cur_hci == nb_hcis)
601         return &null_hci;
602
603     return hci_table[cur_hci++];
604 }
605
606 static struct HCIInfo *hci_init(const char *str)
607 {
608     char *endp;
609     struct bt_scatternet_s *vlan = 0;
610
611     if (!strcmp(str, "null"))
612         /* null */
613         return &null_hci;
614     else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
615         /* host[:hciN] */
616         return bt_host_hci(str[4] ? str + 5 : "hci0");
617     else if (!strncmp(str, "hci", 3)) {
618         /* hci[,vlan=n] */
619         if (str[3]) {
620             if (!strncmp(str + 3, ",vlan=", 6)) {
621                 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
622                 if (*endp)
623                     vlan = 0;
624             }
625         } else
626             vlan = qemu_find_bt_vlan(0);
627         if (vlan)
628            return bt_new_hci(vlan);
629     }
630
631     fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
632
633     return 0;
634 }
635
636 static int bt_hci_parse(const char *str)
637 {
638     struct HCIInfo *hci;
639     bdaddr_t bdaddr;
640
641     if (nb_hcis >= MAX_NICS) {
642         fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
643         return -1;
644     }
645
646     hci = hci_init(str);
647     if (!hci)
648         return -1;
649
650     bdaddr.b[0] = 0x52;
651     bdaddr.b[1] = 0x54;
652     bdaddr.b[2] = 0x00;
653     bdaddr.b[3] = 0x12;
654     bdaddr.b[4] = 0x34;
655     bdaddr.b[5] = 0x56 + nb_hcis;
656     hci->bdaddr_set(hci, bdaddr.b);
657
658     hci_table[nb_hcis++] = hci;
659
660     return 0;
661 }
662
663 static void bt_vhci_add(int vlan_id)
664 {
665     struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
666
667     if (!vlan->slave)
668         fprintf(stderr, "qemu: warning: adding a VHCI to "
669                         "an empty scatternet %i\n", vlan_id);
670
671     bt_vhci_init(bt_new_hci(vlan));
672 }
673
674 static struct bt_device_s *bt_device_add(const char *opt)
675 {
676     struct bt_scatternet_s *vlan;
677     int vlan_id = 0;
678     char *endp = strstr(opt, ",vlan=");
679     int len = (endp ? endp - opt : strlen(opt)) + 1;
680     char devname[10];
681
682     pstrcpy(devname, MIN(sizeof(devname), len), opt);
683
684     if (endp) {
685         vlan_id = strtol(endp + 6, &endp, 0);
686         if (*endp) {
687             fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
688             return 0;
689         }
690     }
691
692     vlan = qemu_find_bt_vlan(vlan_id);
693
694     if (!vlan->slave)
695         fprintf(stderr, "qemu: warning: adding a slave device to "
696                         "an empty scatternet %i\n", vlan_id);
697
698     if (!strcmp(devname, "keyboard"))
699         return bt_keyboard_init(vlan);
700
701     fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
702     return 0;
703 }
704
705 static int bt_parse(const char *opt)
706 {
707     const char *endp, *p;
708     int vlan;
709
710     if (strstart(opt, "hci", &endp)) {
711         if (!*endp || *endp == ',') {
712             if (*endp)
713                 if (!strstart(endp, ",vlan=", 0))
714                     opt = endp + 1;
715
716             return bt_hci_parse(opt);
717        }
718     } else if (strstart(opt, "vhci", &endp)) {
719         if (!*endp || *endp == ',') {
720             if (*endp) {
721                 if (strstart(endp, ",vlan=", &p)) {
722                     vlan = strtol(p, (char **) &endp, 0);
723                     if (*endp) {
724                         fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
725                         return 1;
726                     }
727                 } else {
728                     fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
729                     return 1;
730                 }
731             } else
732                 vlan = 0;
733
734             bt_vhci_add(vlan);
735             return 0;
736         }
737     } else if (strstart(opt, "device:", &endp))
738         return !bt_device_add(endp);
739
740     fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
741     return 1;
742 }
743
744 /***********************************************************/
745 /* QEMU Block devices */
746
747 #define HD_OPTS "media=disk"
748 #define CDROM_OPTS "media=cdrom"
749 #define FD_OPTS ""
750 #define PFLASH_OPTS ""
751 #define MTD_OPTS ""
752 #define SD_OPTS ""
753
754 static int drive_init_func(QemuOpts *opts, void *opaque)
755 {
756     int *use_scsi = opaque;
757
758     return drive_init(opts, *use_scsi) == NULL;
759 }
760
761 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
762 {
763     if (NULL == qemu_opt_get(opts, "snapshot")) {
764         qemu_opt_set(opts, "snapshot", "on");
765     }
766     return 0;
767 }
768
769 static void default_drive(int enable, int snapshot, int use_scsi,
770                           BlockInterfaceType type, int index,
771                           const char *optstr)
772 {
773     QemuOpts *opts;
774
775     if (type == IF_DEFAULT) {
776         type = use_scsi ? IF_SCSI : IF_IDE;
777     }
778
779     if (!enable || drive_get_by_index(type, index)) {
780         return;
781     }
782
783     opts = drive_add(type, index, NULL, optstr);
784     if (snapshot) {
785         drive_enable_snapshot(opts, NULL);
786     }
787     if (!drive_init(opts, use_scsi)) {
788         exit(1);
789     }
790 }
791
792 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
793 {
794     boot_set_handler = func;
795     boot_set_opaque = opaque;
796 }
797
798 int qemu_boot_set(const char *boot_devices)
799 {
800     if (!boot_set_handler) {
801         return -EINVAL;
802     }
803     return boot_set_handler(boot_set_opaque, boot_devices);
804 }
805
806 static void validate_bootdevices(char *devices)
807 {
808     /* We just do some generic consistency checks */
809     const char *p;
810     int bitmap = 0;
811
812     for (p = devices; *p != '\0'; p++) {
813         /* Allowed boot devices are:
814          * a-b: floppy disk drives
815          * c-f: IDE disk drives
816          * g-m: machine implementation dependent drives
817          * n-p: network devices
818          * It's up to each machine implementation to check if the given boot
819          * devices match the actual hardware implementation and firmware
820          * features.
821          */
822         if (*p < 'a' || *p > 'p') {
823             fprintf(stderr, "Invalid boot device '%c'\n", *p);
824             exit(1);
825         }
826         if (bitmap & (1 << (*p - 'a'))) {
827             fprintf(stderr, "Boot device '%c' was given twice\n", *p);
828             exit(1);
829         }
830         bitmap |= 1 << (*p - 'a');
831     }
832 }
833
834 static void restore_boot_devices(void *opaque)
835 {
836     char *standard_boot_devices = opaque;
837     static int first = 1;
838
839     /* Restore boot order and remove ourselves after the first boot */
840     if (first) {
841         first = 0;
842         return;
843     }
844
845     qemu_boot_set(standard_boot_devices);
846
847     qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
848     g_free(standard_boot_devices);
849 }
850
851 void add_boot_device_path(int32_t bootindex, DeviceState *dev,
852                           const char *suffix)
853 {
854     FWBootEntry *node, *i;
855
856     if (bootindex < 0) {
857         return;
858     }
859
860     assert(dev != NULL || suffix != NULL);
861
862     node = g_malloc0(sizeof(FWBootEntry));
863     node->bootindex = bootindex;
864     node->suffix = suffix ? g_strdup(suffix) : NULL;
865     node->dev = dev;
866
867     QTAILQ_FOREACH(i, &fw_boot_order, link) {
868         if (i->bootindex == bootindex) {
869             fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
870             exit(1);
871         } else if (i->bootindex < bootindex) {
872             continue;
873         }
874         QTAILQ_INSERT_BEFORE(i, node, link);
875         return;
876     }
877     QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
878 }
879
880 /*
881  * This function returns null terminated string that consist of new line
882  * separated device paths.
883  *
884  * memory pointed by "size" is assigned total length of the array in bytes
885  *
886  */
887 char *get_boot_devices_list(uint32_t *size)
888 {
889     FWBootEntry *i;
890     uint32_t total = 0;
891     char *list = NULL;
892
893     QTAILQ_FOREACH(i, &fw_boot_order, link) {
894         char *devpath = NULL, *bootpath;
895         int len;
896
897         if (i->dev) {
898             devpath = qdev_get_fw_dev_path(i->dev);
899             assert(devpath);
900         }
901
902         if (i->suffix && devpath) {
903             size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
904
905             bootpath = g_malloc(bootpathlen);
906             snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
907             g_free(devpath);
908         } else if (devpath) {
909             bootpath = devpath;
910         } else {
911             assert(i->suffix);
912             bootpath = g_strdup(i->suffix);
913         }
914
915         if (total) {
916             list[total-1] = '\n';
917         }
918         len = strlen(bootpath) + 1;
919         list = g_realloc(list, total + len);
920         memcpy(&list[total], bootpath, len);
921         total += len;
922         g_free(bootpath);
923     }
924
925     *size = total;
926
927     return list;
928 }
929
930 static void numa_add(const char *optarg)
931 {
932     char option[128];
933     char *endptr;
934     unsigned long long value, endvalue;
935     int nodenr;
936
937     optarg = get_opt_name(option, 128, optarg, ',') + 1;
938     if (!strcmp(option, "node")) {
939         if (get_param_value(option, 128, "nodeid", optarg) == 0) {
940             nodenr = nb_numa_nodes;
941         } else {
942             nodenr = strtoull(option, NULL, 10);
943         }
944
945         if (get_param_value(option, 128, "mem", optarg) == 0) {
946             node_mem[nodenr] = 0;
947         } else {
948             int64_t sval;
949             sval = strtosz(option, &endptr);
950             if (sval < 0 || *endptr) {
951                 fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
952                 exit(1);
953             }
954             node_mem[nodenr] = sval;
955         }
956         if (get_param_value(option, 128, "cpus", optarg) == 0) {
957             node_cpumask[nodenr] = 0;
958         } else {
959             value = strtoull(option, &endptr, 10);
960             if (value >= 64) {
961                 value = 63;
962                 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
963             } else {
964                 if (*endptr == '-') {
965                     endvalue = strtoull(endptr+1, &endptr, 10);
966                     if (endvalue >= 63) {
967                         endvalue = 62;
968                         fprintf(stderr,
969                             "only 63 CPUs in NUMA mode supported.\n");
970                     }
971                     value = (2ULL << endvalue) - (1ULL << value);
972                 } else {
973                     value = 1ULL << value;
974                 }
975             }
976             node_cpumask[nodenr] = value;
977         }
978         nb_numa_nodes++;
979     }
980     return;
981 }
982
983 static void smp_parse(const char *optarg)
984 {
985     int smp, sockets = 0, threads = 0, cores = 0;
986     char *endptr;
987     char option[128];
988
989     smp = strtoul(optarg, &endptr, 10);
990     if (endptr != optarg) {
991         if (*endptr == ',') {
992             endptr++;
993         }
994     }
995     if (get_param_value(option, 128, "sockets", endptr) != 0)
996         sockets = strtoull(option, NULL, 10);
997     if (get_param_value(option, 128, "cores", endptr) != 0)
998         cores = strtoull(option, NULL, 10);
999     if (get_param_value(option, 128, "threads", endptr) != 0)
1000         threads = strtoull(option, NULL, 10);
1001     if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1002         max_cpus = strtoull(option, NULL, 10);
1003
1004     /* compute missing values, prefer sockets over cores over threads */
1005     if (smp == 0 || sockets == 0) {
1006         sockets = sockets > 0 ? sockets : 1;
1007         cores = cores > 0 ? cores : 1;
1008         threads = threads > 0 ? threads : 1;
1009         if (smp == 0) {
1010             smp = cores * threads * sockets;
1011         }
1012     } else {
1013         if (cores == 0) {
1014             threads = threads > 0 ? threads : 1;
1015             cores = smp / (sockets * threads);
1016         } else {
1017             threads = smp / (cores * sockets);
1018         }
1019     }
1020     smp_cpus = smp;
1021     smp_cores = cores > 0 ? cores : 1;
1022     smp_threads = threads > 0 ? threads : 1;
1023     if (max_cpus == 0)
1024         max_cpus = smp_cpus;
1025 }
1026
1027 /***********************************************************/
1028 /* USB devices */
1029
1030 static int usb_device_add(const char *devname)
1031 {
1032     const char *p;
1033     USBDevice *dev = NULL;
1034
1035     if (!usb_enabled)
1036         return -1;
1037
1038     /* drivers with .usbdevice_name entry in USBDeviceInfo */
1039     dev = usbdevice_create(devname);
1040     if (dev)
1041         goto done;
1042
1043     /* the other ones */
1044 #ifndef CONFIG_LINUX
1045     /* only the linux version is qdev-ified, usb-bsd still needs this */
1046     if (strstart(devname, "host:", &p)) {
1047         dev = usb_host_device_open(p);
1048     } else
1049 #endif
1050     if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1051         dev = usb_bt_init(devname[2] ? hci_init(p) :
1052                         bt_new_hci(qemu_find_bt_vlan(0)));
1053     } else {
1054         return -1;
1055     }
1056     if (!dev)
1057         return -1;
1058
1059 done:
1060     return 0;
1061 }
1062
1063 static int usb_device_del(const char *devname)
1064 {
1065     int bus_num, addr;
1066     const char *p;
1067
1068     if (strstart(devname, "host:", &p))
1069         return usb_host_device_close(p);
1070
1071     if (!usb_enabled)
1072         return -1;
1073
1074     p = strchr(devname, '.');
1075     if (!p)
1076         return -1;
1077     bus_num = strtoul(devname, NULL, 0);
1078     addr = strtoul(p + 1, NULL, 0);
1079
1080     return usb_device_delete_addr(bus_num, addr);
1081 }
1082
1083 static int usb_parse(const char *cmdline)
1084 {
1085     int r;
1086     r = usb_device_add(cmdline);
1087     if (r < 0) {
1088         fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1089     }
1090     return r;
1091 }
1092
1093 void do_usb_add(Monitor *mon, const QDict *qdict)
1094 {
1095     const char *devname = qdict_get_str(qdict, "devname");
1096     if (usb_device_add(devname) < 0) {
1097         error_report("could not add USB device '%s'", devname);
1098     }
1099 }
1100
1101 void do_usb_del(Monitor *mon, const QDict *qdict)
1102 {
1103     const char *devname = qdict_get_str(qdict, "devname");
1104     if (usb_device_del(devname) < 0) {
1105         error_report("could not delete USB device '%s'", devname);
1106     }
1107 }
1108
1109 /***********************************************************/
1110 /* PCMCIA/Cardbus */
1111
1112 static struct pcmcia_socket_entry_s {
1113     PCMCIASocket *socket;
1114     struct pcmcia_socket_entry_s *next;
1115 } *pcmcia_sockets = 0;
1116
1117 void pcmcia_socket_register(PCMCIASocket *socket)
1118 {
1119     struct pcmcia_socket_entry_s *entry;
1120
1121     entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1122     entry->socket = socket;
1123     entry->next = pcmcia_sockets;
1124     pcmcia_sockets = entry;
1125 }
1126
1127 void pcmcia_socket_unregister(PCMCIASocket *socket)
1128 {
1129     struct pcmcia_socket_entry_s *entry, **ptr;
1130
1131     ptr = &pcmcia_sockets;
1132     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1133         if (entry->socket == socket) {
1134             *ptr = entry->next;
1135             g_free(entry);
1136         }
1137 }
1138
1139 void pcmcia_info(Monitor *mon)
1140 {
1141     struct pcmcia_socket_entry_s *iter;
1142
1143     if (!pcmcia_sockets)
1144         monitor_printf(mon, "No PCMCIA sockets\n");
1145
1146     for (iter = pcmcia_sockets; iter; iter = iter->next)
1147         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1148                        iter->socket->attached ? iter->socket->card_string :
1149                        "Empty");
1150 }
1151
1152 /***********************************************************/
1153 /* machine registration */
1154
1155 static QEMUMachine *first_machine = NULL;
1156 QEMUMachine *current_machine = NULL;
1157
1158 int qemu_register_machine(QEMUMachine *m)
1159 {
1160     QEMUMachine **pm;
1161     pm = &first_machine;
1162     while (*pm != NULL)
1163         pm = &(*pm)->next;
1164     m->next = NULL;
1165     *pm = m;
1166     return 0;
1167 }
1168
1169 static QEMUMachine *find_machine(const char *name)
1170 {
1171     QEMUMachine *m;
1172
1173     for(m = first_machine; m != NULL; m = m->next) {
1174         if (!strcmp(m->name, name))
1175             return m;
1176         if (m->alias && !strcmp(m->alias, name))
1177             return m;
1178     }
1179     return NULL;
1180 }
1181
1182 static QEMUMachine *find_default_machine(void)
1183 {
1184     QEMUMachine *m;
1185
1186     for(m = first_machine; m != NULL; m = m->next) {
1187         if (m->is_default) {
1188             return m;
1189         }
1190     }
1191     return NULL;
1192 }
1193
1194 /***********************************************************/
1195 /* main execution loop */
1196
1197 static void gui_update(void *opaque)
1198 {
1199     uint64_t interval = GUI_REFRESH_INTERVAL;
1200     DisplayState *ds = opaque;
1201     DisplayChangeListener *dcl = ds->listeners;
1202
1203     dpy_refresh(ds);
1204
1205     while (dcl != NULL) {
1206         if (dcl->gui_timer_interval &&
1207             dcl->gui_timer_interval < interval)
1208             interval = dcl->gui_timer_interval;
1209         dcl = dcl->next;
1210     }
1211     qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1212 }
1213
1214 struct vm_change_state_entry {
1215     VMChangeStateHandler *cb;
1216     void *opaque;
1217     QLIST_ENTRY (vm_change_state_entry) entries;
1218 };
1219
1220 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1221
1222 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1223                                                      void *opaque)
1224 {
1225     VMChangeStateEntry *e;
1226
1227     e = g_malloc0(sizeof (*e));
1228
1229     e->cb = cb;
1230     e->opaque = opaque;
1231     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1232     return e;
1233 }
1234
1235 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1236 {
1237     QLIST_REMOVE (e, entries);
1238     g_free (e);
1239 }
1240
1241 void vm_state_notify(int running, RunState state)
1242 {
1243     VMChangeStateEntry *e;
1244
1245     trace_vm_state_notify(running, state);
1246
1247     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1248         e->cb(e->opaque, running, state);
1249     }
1250 }
1251
1252 void vm_start(void)
1253 {
1254     if (!runstate_is_running()) {
1255         cpu_enable_ticks();
1256         runstate_set(RUN_STATE_RUNNING);
1257         vm_state_notify(1, RUN_STATE_RUNNING);
1258         resume_all_vcpus();
1259         monitor_protocol_event(QEVENT_RESUME, NULL);
1260     }
1261 }
1262
1263 /* reset/shutdown handler */
1264
1265 typedef struct QEMUResetEntry {
1266     QTAILQ_ENTRY(QEMUResetEntry) entry;
1267     QEMUResetHandler *func;
1268     void *opaque;
1269 } QEMUResetEntry;
1270
1271 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1272     QTAILQ_HEAD_INITIALIZER(reset_handlers);
1273 static int reset_requested;
1274 static int shutdown_requested, shutdown_signal = -1;
1275 static pid_t shutdown_pid;
1276 static int powerdown_requested;
1277 static int debug_requested;
1278 static RunState vmstop_requested = RUN_STATE_MAX;
1279
1280 int qemu_shutdown_requested_get(void)
1281 {
1282     return shutdown_requested;
1283 }
1284
1285 int qemu_reset_requested_get(void)
1286 {
1287     return reset_requested;
1288 }
1289
1290 int qemu_shutdown_requested(void)
1291 {
1292     int r = shutdown_requested;
1293     shutdown_requested = 0;
1294     return r;
1295 }
1296
1297 void qemu_kill_report(void)
1298 {
1299     if (shutdown_signal != -1) {
1300         fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1301         if (shutdown_pid == 0) {
1302             /* This happens for eg ^C at the terminal, so it's worth
1303              * avoiding printing an odd message in that case.
1304              */
1305             fputc('\n', stderr);
1306         } else {
1307             fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1308         }
1309         shutdown_signal = -1;
1310     }
1311 }
1312
1313 int qemu_reset_requested(void)
1314 {
1315     int r = reset_requested;
1316     reset_requested = 0;
1317     return r;
1318 }
1319
1320 int qemu_powerdown_requested(void)
1321 {
1322     int r = powerdown_requested;
1323     powerdown_requested = 0;
1324     return r;
1325 }
1326
1327 static int qemu_debug_requested(void)
1328 {
1329     int r = debug_requested;
1330     debug_requested = 0;
1331     return r;
1332 }
1333
1334 /* We use RUN_STATE_MAX but any invalid value will do */
1335 static bool qemu_vmstop_requested(RunState *r)
1336 {
1337     if (vmstop_requested < RUN_STATE_MAX) {
1338         *r = vmstop_requested;
1339         vmstop_requested = RUN_STATE_MAX;
1340         return true;
1341     }
1342
1343     return false;
1344 }
1345
1346 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1347 {
1348     QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1349
1350     re->func = func;
1351     re->opaque = opaque;
1352     QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1353 }
1354
1355 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1356 {
1357     QEMUResetEntry *re;
1358
1359     QTAILQ_FOREACH(re, &reset_handlers, entry) {
1360         if (re->func == func && re->opaque == opaque) {
1361             QTAILQ_REMOVE(&reset_handlers, re, entry);
1362             g_free(re);
1363             return;
1364         }
1365     }
1366 }
1367
1368 void qemu_system_reset(bool report)
1369 {
1370     QEMUResetEntry *re, *nre;
1371
1372     /* reset all devices */
1373     QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1374         re->func(re->opaque);
1375     }
1376     if (report) {
1377         monitor_protocol_event(QEVENT_RESET, NULL);
1378     }
1379     cpu_synchronize_all_post_reset();
1380 }
1381
1382 void qemu_system_reset_request(void)
1383 {
1384     if (no_reboot) {
1385         shutdown_requested = 1;
1386     } else {
1387         reset_requested = 1;
1388     }
1389     cpu_stop_current();
1390     qemu_notify_event();
1391 }
1392
1393 void qemu_system_killed(int signal, pid_t pid)
1394 {
1395     shutdown_signal = signal;
1396     shutdown_pid = pid;
1397     no_shutdown = 0;
1398     qemu_system_shutdown_request();
1399 }
1400
1401 void qemu_system_shutdown_request(void)
1402 {
1403     shutdown_requested = 1;
1404     qemu_notify_event();
1405 }
1406
1407 void qemu_system_powerdown_request(void)
1408 {
1409     powerdown_requested = 1;
1410     qemu_notify_event();
1411 }
1412
1413 void qemu_system_debug_request(void)
1414 {
1415     debug_requested = 1;
1416     qemu_notify_event();
1417 }
1418
1419 void qemu_system_vmstop_request(RunState state)
1420 {
1421     vmstop_requested = state;
1422     qemu_notify_event();
1423 }
1424
1425 qemu_irq qemu_system_powerdown;
1426
1427 static bool main_loop_should_exit(void)
1428 {
1429     RunState r;
1430     if (qemu_debug_requested()) {
1431         vm_stop(RUN_STATE_DEBUG);
1432     }
1433     if (qemu_shutdown_requested()) {
1434         qemu_kill_report();
1435         monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1436         if (no_shutdown) {
1437             vm_stop(RUN_STATE_SHUTDOWN);
1438         } else {
1439             return true;
1440         }
1441     }
1442     if (qemu_reset_requested()) {
1443         pause_all_vcpus();
1444         cpu_synchronize_all_states();
1445         qemu_system_reset(VMRESET_REPORT);
1446         resume_all_vcpus();
1447         if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||
1448             runstate_check(RUN_STATE_SHUTDOWN)) {
1449             runstate_set(RUN_STATE_PAUSED);
1450         }
1451     }
1452     if (qemu_powerdown_requested()) {
1453         monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1454         qemu_irq_raise(qemu_system_powerdown);
1455     }
1456     if (qemu_vmstop_requested(&r)) {
1457         vm_stop(r);
1458     }
1459     return false;
1460 }
1461
1462 static void main_loop(void)
1463 {
1464     bool nonblocking;
1465     int last_io = 0;
1466 #ifdef CONFIG_PROFILER
1467     int64_t ti;
1468 #endif
1469     do {
1470         nonblocking = !kvm_enabled() && last_io > 0;
1471 #ifdef CONFIG_PROFILER
1472         ti = profile_getclock();
1473 #endif
1474         last_io = main_loop_wait(nonblocking);
1475 #ifdef CONFIG_PROFILER
1476         dev_time += profile_getclock() - ti;
1477 #endif
1478     } while (!main_loop_should_exit());
1479 }
1480
1481 static void version(void)
1482 {
1483     printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1484 }
1485
1486 static void help(int exitcode)
1487 {
1488     version();
1489     printf("usage: %s [options] [disk_image]\n\n"
1490            "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1491             error_get_progname());
1492
1493 #define QEMU_OPTIONS_GENERATE_HELP
1494 #include "qemu-options-wrapper.h"
1495
1496     printf("\nDuring emulation, the following keys are useful:\n"
1497            "ctrl-alt-f      toggle full screen\n"
1498            "ctrl-alt-n      switch to virtual console 'n'\n"
1499            "ctrl-alt        toggle mouse and keyboard grab\n"
1500            "\n"
1501            "When using -nographic, press 'ctrl-a h' to get some help.\n");
1502
1503     exit(exitcode);
1504 }
1505
1506 #define HAS_ARG 0x0001
1507
1508 typedef struct QEMUOption {
1509     const char *name;
1510     int flags;
1511     int index;
1512     uint32_t arch_mask;
1513 } QEMUOption;
1514
1515 static const QEMUOption qemu_options[] = {
1516     { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1517 #define QEMU_OPTIONS_GENERATE_OPTIONS
1518 #include "qemu-options-wrapper.h"
1519     { NULL },
1520 };
1521
1522 static bool vga_available(void)
1523 {
1524     return qdev_exists("VGA") || qdev_exists("isa-vga");
1525 }
1526
1527 static bool cirrus_vga_available(void)
1528 {
1529     return qdev_exists("cirrus-vga") || qdev_exists("isa-cirrus-vga");
1530 }
1531
1532 static bool vmware_vga_available(void)
1533 {
1534     return qdev_exists("vmware-svga");
1535 }
1536
1537 static void select_vgahw (const char *p)
1538 {
1539     const char *opts;
1540
1541     vga_interface_type = VGA_NONE;
1542     if (strstart(p, "std", &opts)) {
1543         if (vga_available()) {
1544             vga_interface_type = VGA_STD;
1545         } else {
1546             fprintf(stderr, "Error: standard VGA not available\n");
1547             exit(0);
1548         }
1549     } else if (strstart(p, "cirrus", &opts)) {
1550         if (cirrus_vga_available()) {
1551             vga_interface_type = VGA_CIRRUS;
1552         } else {
1553             fprintf(stderr, "Error: Cirrus VGA not available\n");
1554             exit(0);
1555         }
1556     } else if (strstart(p, "vmware", &opts)) {
1557         if (vmware_vga_available()) {
1558             vga_interface_type = VGA_VMWARE;
1559         } else {
1560             fprintf(stderr, "Error: VMWare SVGA not available\n");
1561             exit(0);
1562         }
1563     } else if (strstart(p, "xenfb", &opts)) {
1564         vga_interface_type = VGA_XENFB;
1565     } else if (strstart(p, "qxl", &opts)) {
1566         vga_interface_type = VGA_QXL;
1567     } else if (!strstart(p, "none", &opts)) {
1568     invalid_vga:
1569         fprintf(stderr, "Unknown vga type: %s\n", p);
1570         exit(1);
1571     }
1572     while (*opts) {
1573         const char *nextopt;
1574
1575         if (strstart(opts, ",retrace=", &nextopt)) {
1576             opts = nextopt;
1577             if (strstart(opts, "dumb", &nextopt))
1578                 vga_retrace_method = VGA_RETRACE_DUMB;
1579             else if (strstart(opts, "precise", &nextopt))
1580                 vga_retrace_method = VGA_RETRACE_PRECISE;
1581             else goto invalid_vga;
1582         } else goto invalid_vga;
1583         opts = nextopt;
1584     }
1585 }
1586
1587 static DisplayType select_display(const char *p)
1588 {
1589     const char *opts;
1590     DisplayType display = DT_DEFAULT;
1591
1592     if (strstart(p, "sdl", &opts)) {
1593 #ifdef CONFIG_SDL
1594         display = DT_SDL;
1595         while (*opts) {
1596             const char *nextopt;
1597
1598             if (strstart(opts, ",frame=", &nextopt)) {
1599                 opts = nextopt;
1600                 if (strstart(opts, "on", &nextopt)) {
1601                     no_frame = 0;
1602                 } else if (strstart(opts, "off", &nextopt)) {
1603                     no_frame = 1;
1604                 } else {
1605                     goto invalid_sdl_args;
1606                 }
1607             } else if (strstart(opts, ",alt_grab=", &nextopt)) {
1608                 opts = nextopt;
1609                 if (strstart(opts, "on", &nextopt)) {
1610                     alt_grab = 1;
1611                 } else if (strstart(opts, "off", &nextopt)) {
1612                     alt_grab = 0;
1613                 } else {
1614                     goto invalid_sdl_args;
1615                 }
1616             } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1617                 opts = nextopt;
1618                 if (strstart(opts, "on", &nextopt)) {
1619                     ctrl_grab = 1;
1620                 } else if (strstart(opts, "off", &nextopt)) {
1621                     ctrl_grab = 0;
1622                 } else {
1623                     goto invalid_sdl_args;
1624                 }
1625             } else if (strstart(opts, ",window_close=", &nextopt)) {
1626                 opts = nextopt;
1627                 if (strstart(opts, "on", &nextopt)) {
1628                     no_quit = 0;
1629                 } else if (strstart(opts, "off", &nextopt)) {
1630                     no_quit = 1;
1631                 } else {
1632                     goto invalid_sdl_args;
1633                 }
1634             } else {
1635             invalid_sdl_args:
1636                 fprintf(stderr, "Invalid SDL option string: %s\n", p);
1637                 exit(1);
1638             }
1639             opts = nextopt;
1640         }
1641 #else
1642         fprintf(stderr, "SDL support is disabled\n");
1643         exit(1);
1644 #endif
1645     } else if (strstart(p, "vnc", &opts)) {
1646 #ifdef CONFIG_VNC
1647         display_remote++;
1648
1649         if (*opts) {
1650             const char *nextopt;
1651
1652             if (strstart(opts, "=", &nextopt)) {
1653                 vnc_display = nextopt;
1654             }
1655         }
1656         if (!vnc_display) {
1657             fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1658             exit(1);
1659         }
1660 #else
1661         fprintf(stderr, "VNC support is disabled\n");
1662         exit(1);
1663 #endif
1664     } else if (strstart(p, "curses", &opts)) {
1665 #ifdef CONFIG_CURSES
1666         display = DT_CURSES;
1667 #else
1668         fprintf(stderr, "Curses support is disabled\n");
1669         exit(1);
1670 #endif
1671     } else if (strstart(p, "none", &opts)) {
1672         display = DT_NONE;
1673     } else {
1674         fprintf(stderr, "Unknown display type: %s\n", p);
1675         exit(1);
1676     }
1677
1678     return display;
1679 }
1680
1681 static int balloon_parse(const char *arg)
1682 {
1683     QemuOpts *opts;
1684
1685     if (strcmp(arg, "none") == 0) {
1686         return 0;
1687     }
1688
1689     if (!strncmp(arg, "virtio", 6)) {
1690         if (arg[6] == ',') {
1691             /* have params -> parse them */
1692             opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1693             if (!opts)
1694                 return  -1;
1695         } else {
1696             /* create empty opts */
1697             opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
1698         }
1699         qemu_opt_set(opts, "driver", "virtio-balloon");
1700         return 0;
1701     }
1702
1703     return -1;
1704 }
1705
1706 char *qemu_find_file(int type, const char *name)
1707 {
1708     int len;
1709     const char *subdir;
1710     char *buf;
1711
1712     /* If name contains path separators then try it as a straight path.  */
1713     if ((strchr(name, '/') || strchr(name, '\\'))
1714         && access(name, R_OK) == 0) {
1715         return g_strdup(name);
1716     }
1717     switch (type) {
1718     case QEMU_FILE_TYPE_BIOS:
1719         subdir = "";
1720         break;
1721     case QEMU_FILE_TYPE_KEYMAP:
1722         subdir = "keymaps/";
1723         break;
1724     default:
1725         abort();
1726     }
1727     len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
1728     buf = g_malloc0(len);
1729     snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
1730     if (access(buf, R_OK)) {
1731         g_free(buf);
1732         return NULL;
1733     }
1734     return buf;
1735 }
1736
1737 static int device_help_func(QemuOpts *opts, void *opaque)
1738 {
1739     return qdev_device_help(opts);
1740 }
1741
1742 static int device_init_func(QemuOpts *opts, void *opaque)
1743 {
1744     DeviceState *dev;
1745
1746     dev = qdev_device_add(opts);
1747     if (!dev)
1748         return -1;
1749     return 0;
1750 }
1751
1752 static int chardev_init_func(QemuOpts *opts, void *opaque)
1753 {
1754     CharDriverState *chr;
1755
1756     chr = qemu_chr_new_from_opts(opts, NULL);
1757     if (!chr)
1758         return -1;
1759     return 0;
1760 }
1761
1762 #ifdef CONFIG_VIRTFS
1763 static int fsdev_init_func(QemuOpts *opts, void *opaque)
1764 {
1765     int ret;
1766     ret = qemu_fsdev_add(opts);
1767
1768     return ret;
1769 }
1770 #endif
1771
1772 static int mon_init_func(QemuOpts *opts, void *opaque)
1773 {
1774     CharDriverState *chr;
1775     const char *chardev;
1776     const char *mode;
1777     int flags;
1778
1779     mode = qemu_opt_get(opts, "mode");
1780     if (mode == NULL) {
1781         mode = "readline";
1782     }
1783     if (strcmp(mode, "readline") == 0) {
1784         flags = MONITOR_USE_READLINE;
1785     } else if (strcmp(mode, "control") == 0) {
1786         flags = MONITOR_USE_CONTROL;
1787     } else {
1788         fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1789         exit(1);
1790     }
1791
1792     if (qemu_opt_get_bool(opts, "pretty", 0))
1793         flags |= MONITOR_USE_PRETTY;
1794
1795     if (qemu_opt_get_bool(opts, "default", 0))
1796         flags |= MONITOR_IS_DEFAULT;
1797
1798     chardev = qemu_opt_get(opts, "chardev");
1799     chr = qemu_chr_find(chardev);
1800     if (chr == NULL) {
1801         fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1802         exit(1);
1803     }
1804
1805     monitor_init(chr, flags);
1806     return 0;
1807 }
1808
1809 static void monitor_parse(const char *optarg, const char *mode)
1810 {
1811     static int monitor_device_index = 0;
1812     QemuOpts *opts;
1813     const char *p;
1814     char label[32];
1815     int def = 0;
1816
1817     if (strstart(optarg, "chardev:", &p)) {
1818         snprintf(label, sizeof(label), "%s", p);
1819     } else {
1820         snprintf(label, sizeof(label), "compat_monitor%d",
1821                  monitor_device_index);
1822         if (monitor_device_index == 0) {
1823             def = 1;
1824         }
1825         opts = qemu_chr_parse_compat(label, optarg);
1826         if (!opts) {
1827             fprintf(stderr, "parse error: %s\n", optarg);
1828             exit(1);
1829         }
1830     }
1831
1832     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);
1833     if (!opts) {
1834         fprintf(stderr, "duplicate chardev: %s\n", label);
1835         exit(1);
1836     }
1837     qemu_opt_set(opts, "mode", mode);
1838     qemu_opt_set(opts, "chardev", label);
1839     if (def)
1840         qemu_opt_set(opts, "default", "on");
1841     monitor_device_index++;
1842 }
1843
1844 struct device_config {
1845     enum {
1846         DEV_USB,       /* -usbdevice     */
1847         DEV_BT,        /* -bt            */
1848         DEV_SERIAL,    /* -serial        */
1849         DEV_PARALLEL,  /* -parallel      */
1850         DEV_VIRTCON,   /* -virtioconsole */
1851         DEV_DEBUGCON,  /* -debugcon */
1852     } type;
1853     const char *cmdline;
1854     QTAILQ_ENTRY(device_config) next;
1855 };
1856 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1857
1858 static void add_device_config(int type, const char *cmdline)
1859 {
1860     struct device_config *conf;
1861
1862     conf = g_malloc0(sizeof(*conf));
1863     conf->type = type;
1864     conf->cmdline = cmdline;
1865     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1866 }
1867
1868 static int foreach_device_config(int type, int (*func)(const char *cmdline))
1869 {
1870     struct device_config *conf;
1871     int rc;
1872
1873     QTAILQ_FOREACH(conf, &device_configs, next) {
1874         if (conf->type != type)
1875             continue;
1876         rc = func(conf->cmdline);
1877         if (0 != rc)
1878             return rc;
1879     }
1880     return 0;
1881 }
1882
1883 static int serial_parse(const char *devname)
1884 {
1885     static int index = 0;
1886     char label[32];
1887
1888     if (strcmp(devname, "none") == 0)
1889         return 0;
1890     if (index == MAX_SERIAL_PORTS) {
1891         fprintf(stderr, "qemu: too many serial ports\n");
1892         exit(1);
1893     }
1894     snprintf(label, sizeof(label), "serial%d", index);
1895     serial_hds[index] = qemu_chr_new(label, devname, NULL);
1896     if (!serial_hds[index]) {
1897         fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
1898                 devname, strerror(errno));
1899         return -1;
1900     }
1901     index++;
1902     return 0;
1903 }
1904
1905 static int parallel_parse(const char *devname)
1906 {
1907     static int index = 0;
1908     char label[32];
1909
1910     if (strcmp(devname, "none") == 0)
1911         return 0;
1912     if (index == MAX_PARALLEL_PORTS) {
1913         fprintf(stderr, "qemu: too many parallel ports\n");
1914         exit(1);
1915     }
1916     snprintf(label, sizeof(label), "parallel%d", index);
1917     parallel_hds[index] = qemu_chr_new(label, devname, NULL);
1918     if (!parallel_hds[index]) {
1919         fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
1920                 devname, strerror(errno));
1921         return -1;
1922     }
1923     index++;
1924     return 0;
1925 }
1926
1927 static int virtcon_parse(const char *devname)
1928 {
1929     QemuOptsList *device = qemu_find_opts("device");
1930     static int index = 0;
1931     char label[32];
1932     QemuOpts *bus_opts, *dev_opts;
1933
1934     if (strcmp(devname, "none") == 0)
1935         return 0;
1936     if (index == MAX_VIRTIO_CONSOLES) {
1937         fprintf(stderr, "qemu: too many virtio consoles\n");
1938         exit(1);
1939     }
1940
1941     bus_opts = qemu_opts_create(device, NULL, 0);
1942     qemu_opt_set(bus_opts, "driver", "virtio-serial");
1943
1944     dev_opts = qemu_opts_create(device, NULL, 0);
1945     qemu_opt_set(dev_opts, "driver", "virtconsole");
1946
1947     snprintf(label, sizeof(label), "virtcon%d", index);
1948     virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
1949     if (!virtcon_hds[index]) {
1950         fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
1951                 devname, strerror(errno));
1952         return -1;
1953     }
1954     qemu_opt_set(dev_opts, "chardev", label);
1955
1956     index++;
1957     return 0;
1958 }
1959
1960 static int debugcon_parse(const char *devname)
1961 {   
1962     QemuOpts *opts;
1963
1964     if (!qemu_chr_new("debugcon", devname, NULL)) {
1965         exit(1);
1966     }
1967     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);
1968     if (!opts) {
1969         fprintf(stderr, "qemu: already have a debugcon device\n");
1970         exit(1);
1971     }
1972     qemu_opt_set(opts, "driver", "isa-debugcon");
1973     qemu_opt_set(opts, "chardev", "debugcon");
1974     return 0;
1975 }
1976
1977 static QEMUMachine *machine_parse(const char *name)
1978 {
1979     QEMUMachine *m, *machine = NULL;
1980
1981     if (name) {
1982         machine = find_machine(name);
1983     }
1984     if (machine) {
1985         return machine;
1986     }
1987     printf("Supported machines are:\n");
1988     for (m = first_machine; m != NULL; m = m->next) {
1989         if (m->alias) {
1990             printf("%-10s %s (alias of %s)\n", m->alias, m->desc, m->name);
1991         }
1992         printf("%-10s %s%s\n", m->name, m->desc,
1993                m->is_default ? " (default)" : "");
1994     }
1995     exit(!name || *name != '?');
1996 }
1997
1998 static int tcg_init(void)
1999 {
2000     tcg_exec_init(tcg_tb_size * 1024 * 1024);
2001     return 0;
2002 }
2003
2004 static struct {
2005     const char *opt_name;
2006     const char *name;
2007     int (*available)(void);
2008     int (*init)(void);
2009     int *allowed;
2010 } accel_list[] = {
2011     { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2012     { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2013     { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2014 };
2015
2016 static int configure_accelerator(void)
2017 {
2018     const char *p = NULL;
2019     char buf[10];
2020     int i, ret;
2021     bool accel_initalised = 0;
2022     bool init_failed = 0;
2023
2024     QemuOptsList *list = qemu_find_opts("machine");
2025     if (!QTAILQ_EMPTY(&list->head)) {
2026         p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2027     }
2028
2029     if (p == NULL) {
2030         /* Use the default "accelerator", tcg */
2031         p = "tcg";
2032     }
2033
2034     while (!accel_initalised && *p != '\0') {
2035         if (*p == ':') {
2036             p++;
2037         }
2038         p = get_opt_name(buf, sizeof (buf), p, ':');
2039         for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2040             if (strcmp(accel_list[i].opt_name, buf) == 0) {
2041                 *(accel_list[i].allowed) = 1;
2042                 ret = accel_list[i].init();
2043                 if (ret < 0) {
2044                     init_failed = 1;
2045                     if (!accel_list[i].available()) {
2046                         printf("%s not supported for this target\n",
2047                                accel_list[i].name);
2048                     } else {
2049                         fprintf(stderr, "failed to initialize %s: %s\n",
2050                                 accel_list[i].name,
2051                                 strerror(-ret));
2052                     }
2053                     *(accel_list[i].allowed) = 0;
2054                 } else {
2055                     accel_initalised = 1;
2056                 }
2057                 break;
2058             }
2059         }
2060         if (i == ARRAY_SIZE(accel_list)) {
2061             fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2062         }
2063     }
2064
2065     if (!accel_initalised) {
2066         fprintf(stderr, "No accelerator found!\n");
2067         exit(1);
2068     }
2069
2070     if (init_failed) {
2071         fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2072     }
2073
2074     return !accel_initalised;
2075 }
2076
2077 void qemu_add_exit_notifier(Notifier *notify)
2078 {
2079     notifier_list_add(&exit_notifiers, notify);
2080 }
2081
2082 void qemu_remove_exit_notifier(Notifier *notify)
2083 {
2084     notifier_list_remove(&exit_notifiers, notify);
2085 }
2086
2087 static void qemu_run_exit_notifiers(void)
2088 {
2089     notifier_list_notify(&exit_notifiers, NULL);
2090 }
2091
2092 void qemu_add_machine_init_done_notifier(Notifier *notify)
2093 {
2094     notifier_list_add(&machine_init_done_notifiers, notify);
2095 }
2096
2097 static void qemu_run_machine_init_done_notifiers(void)
2098 {
2099     notifier_list_notify(&machine_init_done_notifiers, NULL);
2100 }
2101
2102 static const QEMUOption *lookup_opt(int argc, char **argv,
2103                                     const char **poptarg, int *poptind)
2104 {
2105     const QEMUOption *popt;
2106     int optind = *poptind;
2107     char *r = argv[optind];
2108     const char *optarg;
2109
2110     loc_set_cmdline(argv, optind, 1);
2111     optind++;
2112     /* Treat --foo the same as -foo.  */
2113     if (r[1] == '-')
2114         r++;
2115     popt = qemu_options;
2116     for(;;) {
2117         if (!popt->name) {
2118             error_report("invalid option");
2119             exit(1);
2120         }
2121         if (!strcmp(popt->name, r + 1))
2122             break;
2123         popt++;
2124     }
2125     if (popt->flags & HAS_ARG) {
2126         if (optind >= argc) {
2127             error_report("requires an argument");
2128             exit(1);
2129         }
2130         optarg = argv[optind++];
2131         loc_set_cmdline(argv, optind - 2, 2);
2132     } else {
2133         optarg = NULL;
2134     }
2135
2136     *poptarg = optarg;
2137     *poptind = optind;
2138
2139     return popt;
2140 }
2141
2142 static gpointer malloc_and_trace(gsize n_bytes)
2143 {
2144     void *ptr = malloc(n_bytes);
2145     trace_g_malloc(n_bytes, ptr);
2146     return ptr;
2147 }
2148
2149 static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2150 {
2151     void *ptr = realloc(mem, n_bytes);
2152     trace_g_realloc(mem, n_bytes, ptr);
2153     return ptr;
2154 }
2155
2156 static void free_and_trace(gpointer mem)
2157 {
2158     trace_g_free(mem);
2159     free(mem);
2160 }
2161
2162 int main(int argc, char **argv, char **envp)
2163 {
2164     const char *gdbstub_dev = NULL;
2165     int i;
2166     int snapshot, linux_boot;
2167     const char *icount_option = NULL;
2168     const char *initrd_filename;
2169     const char *kernel_filename, *kernel_cmdline;
2170     char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2171     DisplayState *ds;
2172     DisplayChangeListener *dcl;
2173     int cyls, heads, secs, translation;
2174     QemuOpts *hda_opts = NULL, *opts;
2175     QemuOptsList *olist;
2176     int optind;
2177     const char *optarg;
2178     const char *loadvm = NULL;
2179     QEMUMachine *machine;
2180     const char *cpu_model;
2181     const char *vga_model = NULL;
2182     const char *pid_file = NULL;
2183     const char *incoming = NULL;
2184 #ifdef CONFIG_VNC
2185     int show_vnc_port = 0;
2186 #endif
2187     int defconfig = 1;
2188     const char *log_mask = NULL;
2189     const char *log_file = NULL;
2190     GMemVTable mem_trace = {
2191         .malloc = malloc_and_trace,
2192         .realloc = realloc_and_trace,
2193         .free = free_and_trace,
2194     };
2195     const char *trace_events = NULL;
2196     const char *trace_file = NULL;
2197
2198     atexit(qemu_run_exit_notifiers);
2199     error_set_progname(argv[0]);
2200
2201     g_mem_set_vtable(&mem_trace);
2202     if (!g_thread_supported()) {
2203 #if !GLIB_CHECK_VERSION(2, 31, 0)
2204         g_thread_init(NULL);
2205 #else
2206         fprintf(stderr, "glib threading failed to initialize.\n");
2207         exit(1);
2208 #endif
2209     }
2210
2211     runstate_init();
2212
2213     init_clocks();
2214     rtc_clock = host_clock;
2215
2216     qemu_cache_utils_init(envp);
2217
2218     QLIST_INIT (&vm_change_state_head);
2219     os_setup_early_signal_handling();
2220
2221     module_call_init(MODULE_INIT_MACHINE);
2222     machine = find_default_machine();
2223     cpu_model = NULL;
2224     initrd_filename = NULL;
2225     ram_size = 0;
2226     snapshot = 0;
2227     kernel_filename = NULL;
2228     kernel_cmdline = "";
2229     cyls = heads = secs = 0;
2230     translation = BIOS_ATA_TRANSLATION_AUTO;
2231
2232     for (i = 0; i < MAX_NODES; i++) {
2233         node_mem[i] = 0;
2234         node_cpumask[i] = 0;
2235     }
2236
2237     nb_numa_nodes = 0;
2238     nb_nics = 0;
2239
2240     autostart= 1;
2241
2242     /* first pass of option parsing */
2243     optind = 1;
2244     while (optind < argc) {
2245         if (argv[optind][0] != '-') {
2246             /* disk image */
2247             optind++;
2248             continue;
2249         } else {
2250             const QEMUOption *popt;
2251
2252             popt = lookup_opt(argc, argv, &optarg, &optind);
2253             switch (popt->index) {
2254             case QEMU_OPTION_nodefconfig:
2255                 defconfig=0;
2256                 break;
2257             }
2258         }
2259     }
2260
2261     if (defconfig) {
2262         int ret;
2263
2264         ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2265         if (ret < 0 && ret != -ENOENT) {
2266             exit(1);
2267         }
2268
2269         ret = qemu_read_config_file(arch_config_name);
2270         if (ret < 0 && ret != -ENOENT) {
2271             exit(1);
2272         }
2273     }
2274     cpudef_init();
2275
2276     /* second pass of option parsing */
2277     optind = 1;
2278     for(;;) {
2279         if (optind >= argc)
2280             break;
2281         if (argv[optind][0] != '-') {
2282             hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2283         } else {
2284             const QEMUOption *popt;
2285
2286             popt = lookup_opt(argc, argv, &optarg, &optind);
2287             if (!(popt->arch_mask & arch_type)) {
2288                 printf("Option %s not supported for this target\n", popt->name);
2289                 exit(1);
2290             }
2291             switch(popt->index) {
2292             case QEMU_OPTION_M:
2293                 machine = machine_parse(optarg);
2294                 break;
2295             case QEMU_OPTION_cpu:
2296                 /* hw initialization will check this */
2297                 if (*optarg == '?') {
2298                     list_cpus(stdout, &fprintf, optarg);
2299                     exit(0);
2300                 } else {
2301                     cpu_model = optarg;
2302                 }
2303                 break;
2304             case QEMU_OPTION_initrd:
2305                 initrd_filename = optarg;
2306                 break;
2307             case QEMU_OPTION_hda:
2308                 {
2309                     char buf[256];
2310                     if (cyls == 0)
2311                         snprintf(buf, sizeof(buf), "%s", HD_OPTS);
2312                     else
2313                         snprintf(buf, sizeof(buf),
2314                                  "%s,cyls=%d,heads=%d,secs=%d%s",
2315                                  HD_OPTS , cyls, heads, secs,
2316                                  translation == BIOS_ATA_TRANSLATION_LBA ?
2317                                  ",trans=lba" :
2318                                  translation == BIOS_ATA_TRANSLATION_NONE ?
2319                                  ",trans=none" : "");
2320                     drive_add(IF_DEFAULT, 0, optarg, buf);
2321                     break;
2322                 }
2323             case QEMU_OPTION_hdb:
2324             case QEMU_OPTION_hdc:
2325             case QEMU_OPTION_hdd:
2326                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2327                           HD_OPTS);
2328                 break;
2329             case QEMU_OPTION_drive:
2330                 if (drive_def(optarg) == NULL) {
2331                     exit(1);
2332                 }
2333                 break;
2334             case QEMU_OPTION_set:
2335                 if (qemu_set_option(optarg) != 0)
2336                     exit(1);
2337                 break;
2338             case QEMU_OPTION_global:
2339                 if (qemu_global_option(optarg) != 0)
2340                     exit(1);
2341                 break;
2342             case QEMU_OPTION_mtdblock:
2343                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2344                 break;
2345             case QEMU_OPTION_sd:
2346                 drive_add(IF_SD, 0, optarg, SD_OPTS);
2347                 break;
2348             case QEMU_OPTION_pflash:
2349                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2350                 break;
2351             case QEMU_OPTION_snapshot:
2352                 snapshot = 1;
2353                 break;
2354             case QEMU_OPTION_hdachs:
2355                 {
2356                     const char *p;
2357                     p = optarg;
2358                     cyls = strtol(p, (char **)&p, 0);
2359                     if (cyls < 1 || cyls > 16383)
2360                         goto chs_fail;
2361                     if (*p != ',')
2362                         goto chs_fail;
2363                     p++;
2364                     heads = strtol(p, (char **)&p, 0);
2365                     if (heads < 1 || heads > 16)
2366                         goto chs_fail;
2367                     if (*p != ',')
2368                         goto chs_fail;
2369                     p++;
2370                     secs = strtol(p, (char **)&p, 0);
2371                     if (secs < 1 || secs > 63)
2372                         goto chs_fail;
2373                     if (*p == ',') {
2374                         p++;
2375                         if (!strcmp(p, "none"))
2376                             translation = BIOS_ATA_TRANSLATION_NONE;
2377                         else if (!strcmp(p, "lba"))
2378                             translation = BIOS_ATA_TRANSLATION_LBA;
2379                         else if (!strcmp(p, "auto"))
2380                             translation = BIOS_ATA_TRANSLATION_AUTO;
2381                         else
2382                             goto chs_fail;
2383                     } else if (*p != '\0') {
2384                     chs_fail:
2385                         fprintf(stderr, "qemu: invalid physical CHS format\n");
2386                         exit(1);
2387                     }
2388                     if (hda_opts != NULL) {
2389                         char num[16];
2390                         snprintf(num, sizeof(num), "%d", cyls);
2391                         qemu_opt_set(hda_opts, "cyls", num);
2392                         snprintf(num, sizeof(num), "%d", heads);
2393                         qemu_opt_set(hda_opts, "heads", num);
2394                         snprintf(num, sizeof(num), "%d", secs);
2395                         qemu_opt_set(hda_opts, "secs", num);
2396                         if (translation == BIOS_ATA_TRANSLATION_LBA)
2397                             qemu_opt_set(hda_opts, "trans", "lba");
2398                         if (translation == BIOS_ATA_TRANSLATION_NONE)
2399                             qemu_opt_set(hda_opts, "trans", "none");
2400                     }
2401                 }
2402                 break;
2403             case QEMU_OPTION_numa:
2404                 if (nb_numa_nodes >= MAX_NODES) {
2405                     fprintf(stderr, "qemu: too many NUMA nodes\n");
2406                     exit(1);
2407                 }
2408                 numa_add(optarg);
2409                 break;
2410             case QEMU_OPTION_display:
2411                 display_type = select_display(optarg);
2412                 break;
2413             case QEMU_OPTION_nographic:
2414                 display_type = DT_NOGRAPHIC;
2415                 break;
2416             case QEMU_OPTION_curses:
2417 #ifdef CONFIG_CURSES
2418                 display_type = DT_CURSES;
2419 #else
2420                 fprintf(stderr, "Curses support is disabled\n");
2421                 exit(1);
2422 #endif
2423                 break;
2424             case QEMU_OPTION_portrait:
2425                 graphic_rotate = 90;
2426                 break;
2427             case QEMU_OPTION_rotate:
2428                 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
2429                 if (graphic_rotate != 0 && graphic_rotate != 90 &&
2430                     graphic_rotate != 180 && graphic_rotate != 270) {
2431                     fprintf(stderr,
2432                         "qemu: only 90, 180, 270 deg rotation is available\n");
2433                     exit(1);
2434                 }
2435                 break;
2436             case QEMU_OPTION_kernel:
2437                 kernel_filename = optarg;
2438                 break;
2439             case QEMU_OPTION_append:
2440                 kernel_cmdline = optarg;
2441                 break;
2442             case QEMU_OPTION_cdrom:
2443                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2444                 break;
2445             case QEMU_OPTION_boot:
2446                 {
2447                     static const char * const params[] = {
2448                         "order", "once", "menu",
2449                         "splash", "splash-time", NULL
2450                     };
2451                     char buf[sizeof(boot_devices)];
2452                     char *standard_boot_devices;
2453                     int legacy = 0;
2454
2455                     if (!strchr(optarg, '=')) {
2456                         legacy = 1;
2457                         pstrcpy(buf, sizeof(buf), optarg);
2458                     } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2459                         fprintf(stderr,
2460                                 "qemu: unknown boot parameter '%s' in '%s'\n",
2461                                 buf, optarg);
2462                         exit(1);
2463                     }
2464
2465                     if (legacy ||
2466                         get_param_value(buf, sizeof(buf), "order", optarg)) {
2467                         validate_bootdevices(buf);
2468                         pstrcpy(boot_devices, sizeof(boot_devices), buf);
2469                     }
2470                     if (!legacy) {
2471                         if (get_param_value(buf, sizeof(buf),
2472                                             "once", optarg)) {
2473                             validate_bootdevices(buf);
2474                             standard_boot_devices = g_strdup(boot_devices);
2475                             pstrcpy(boot_devices, sizeof(boot_devices), buf);
2476                             qemu_register_reset(restore_boot_devices,
2477                                                 standard_boot_devices);
2478                         }
2479                         if (get_param_value(buf, sizeof(buf),
2480                                             "menu", optarg)) {
2481                             if (!strcmp(buf, "on")) {
2482                                 boot_menu = 1;
2483                             } else if (!strcmp(buf, "off")) {
2484                                 boot_menu = 0;
2485                             } else {
2486                                 fprintf(stderr,
2487                                         "qemu: invalid option value '%s'\n",
2488                                         buf);
2489                                 exit(1);
2490                             }
2491                         }
2492                         qemu_opts_parse(qemu_find_opts("boot-opts"),
2493                                         optarg, 0);
2494                     }
2495                 }
2496                 break;
2497             case QEMU_OPTION_fda:
2498             case QEMU_OPTION_fdb:
2499                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2500                           optarg, FD_OPTS);
2501                 break;
2502             case QEMU_OPTION_no_fd_bootchk:
2503                 fd_bootchk = 0;
2504                 break;
2505             case QEMU_OPTION_netdev:
2506                 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
2507                     exit(1);
2508                 }
2509                 break;
2510             case QEMU_OPTION_net:
2511                 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
2512                     exit(1);
2513                 }
2514                 break;
2515 #ifdef CONFIG_SLIRP
2516             case QEMU_OPTION_tftp:
2517                 legacy_tftp_prefix = optarg;
2518                 break;
2519             case QEMU_OPTION_bootp:
2520                 legacy_bootp_filename = optarg;
2521                 break;
2522             case QEMU_OPTION_redir:
2523                 if (net_slirp_redir(optarg) < 0)
2524                     exit(1);
2525                 break;
2526 #endif
2527             case QEMU_OPTION_bt:
2528                 add_device_config(DEV_BT, optarg);
2529                 break;
2530             case QEMU_OPTION_audio_help:
2531                 if (!(audio_available())) {
2532                     printf("Option %s not supported for this target\n", popt->name);
2533                     exit(1);
2534                 }
2535                 AUD_help ();
2536                 exit (0);
2537                 break;
2538             case QEMU_OPTION_soundhw:
2539                 if (!(audio_available())) {
2540                     printf("Option %s not supported for this target\n", popt->name);
2541                     exit(1);
2542                 }
2543                 select_soundhw (optarg);
2544                 break;
2545             case QEMU_OPTION_h:
2546                 help(0);
2547                 break;
2548             case QEMU_OPTION_version:
2549                 version();
2550                 exit(0);
2551                 break;
2552             case QEMU_OPTION_m: {
2553                 int64_t value;
2554                 char *end;
2555
2556                 value = strtosz(optarg, &end);
2557                 if (value < 0 || *end) {
2558                     fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2559                     exit(1);
2560                 }
2561
2562                 if (value != (uint64_t)(ram_addr_t)value) {
2563                     fprintf(stderr, "qemu: ram size too large\n");
2564                     exit(1);
2565                 }
2566                 ram_size = value;
2567                 break;
2568             }
2569             case QEMU_OPTION_mempath:
2570                 mem_path = optarg;
2571                 break;
2572 #ifdef MAP_POPULATE
2573             case QEMU_OPTION_mem_prealloc:
2574                 mem_prealloc = 1;
2575                 break;
2576 #endif
2577             case QEMU_OPTION_d:
2578                 log_mask = optarg;
2579                 break;
2580             case QEMU_OPTION_D:
2581                 log_file = optarg;
2582                 break;
2583             case QEMU_OPTION_s:
2584                 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
2585                 break;
2586             case QEMU_OPTION_gdb:
2587                 gdbstub_dev = optarg;
2588                 break;
2589             case QEMU_OPTION_L:
2590                 data_dir = optarg;
2591                 break;
2592             case QEMU_OPTION_bios:
2593                 bios_name = optarg;
2594                 break;
2595             case QEMU_OPTION_singlestep:
2596                 singlestep = 1;
2597                 break;
2598             case QEMU_OPTION_S:
2599                 autostart = 0;
2600                 break;
2601             case QEMU_OPTION_k:
2602                 keyboard_layout = optarg;
2603                 break;
2604             case QEMU_OPTION_localtime:
2605                 rtc_utc = 0;
2606                 break;
2607             case QEMU_OPTION_vga:
2608                 vga_model = optarg;
2609                 break;
2610             case QEMU_OPTION_g:
2611                 {
2612                     const char *p;
2613                     int w, h, depth;
2614                     p = optarg;
2615                     w = strtol(p, (char **)&p, 10);
2616                     if (w <= 0) {
2617                     graphic_error:
2618                         fprintf(stderr, "qemu: invalid resolution or depth\n");
2619                         exit(1);
2620                     }
2621                     if (*p != 'x')
2622                         goto graphic_error;
2623                     p++;
2624                     h = strtol(p, (char **)&p, 10);
2625                     if (h <= 0)
2626                         goto graphic_error;
2627                     if (*p == 'x') {
2628                         p++;
2629                         depth = strtol(p, (char **)&p, 10);
2630                         if (depth != 8 && depth != 15 && depth != 16 &&
2631                             depth != 24 && depth != 32)
2632                             goto graphic_error;
2633                     } else if (*p == '\0') {
2634                         depth = graphic_depth;
2635                     } else {
2636                         goto graphic_error;
2637                     }
2638
2639                     graphic_width = w;
2640                     graphic_height = h;
2641                     graphic_depth = depth;
2642                 }
2643                 break;
2644             case QEMU_OPTION_echr:
2645                 {
2646                     char *r;
2647                     term_escape_char = strtol(optarg, &r, 0);
2648                     if (r == optarg)
2649                         printf("Bad argument to echr\n");
2650                     break;
2651                 }
2652             case QEMU_OPTION_monitor:
2653                 monitor_parse(optarg, "readline");
2654                 default_monitor = 0;
2655                 break;
2656             case QEMU_OPTION_qmp:
2657                 monitor_parse(optarg, "control");
2658                 default_monitor = 0;
2659                 break;
2660             case QEMU_OPTION_mon:
2661                 opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
2662                 if (!opts) {
2663                     exit(1);
2664                 }
2665                 default_monitor = 0;
2666                 break;
2667             case QEMU_OPTION_chardev:
2668                 opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
2669                 if (!opts) {
2670                     exit(1);
2671                 }
2672                 break;
2673             case QEMU_OPTION_fsdev:
2674                 olist = qemu_find_opts("fsdev");
2675                 if (!olist) {
2676                     fprintf(stderr, "fsdev is not supported by this qemu build.\n");
2677                     exit(1);
2678                 }
2679                 opts = qemu_opts_parse(olist, optarg, 1);
2680                 if (!opts) {
2681                     fprintf(stderr, "parse error: %s\n", optarg);
2682                     exit(1);
2683                 }
2684                 break;
2685             case QEMU_OPTION_virtfs: {
2686                 QemuOpts *fsdev;
2687                 QemuOpts *device;
2688                 const char *writeout, *sock_fd, *socket;
2689
2690                 olist = qemu_find_opts("virtfs");
2691                 if (!olist) {
2692                     fprintf(stderr, "virtfs is not supported by this qemu build.\n");
2693                     exit(1);
2694                 }
2695                 opts = qemu_opts_parse(olist, optarg, 1);
2696                 if (!opts) {
2697                     fprintf(stderr, "parse error: %s\n", optarg);
2698                     exit(1);
2699                 }
2700
2701                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
2702                     qemu_opt_get(opts, "mount_tag") == NULL) {
2703                     fprintf(stderr, "Usage: -virtfs fsdriver,mount_tag=tag.\n");
2704                     exit(1);
2705                 }
2706                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
2707                                          qemu_opt_get(opts, "mount_tag"), 1);
2708                 if (!fsdev) {
2709                     fprintf(stderr, "duplicate fsdev id: %s\n",
2710                             qemu_opt_get(opts, "mount_tag"));
2711                     exit(1);
2712                 }
2713
2714                 writeout = qemu_opt_get(opts, "writeout");
2715                 if (writeout) {
2716 #ifdef CONFIG_SYNC_FILE_RANGE
2717                     qemu_opt_set(fsdev, "writeout", writeout);
2718 #else
2719                     fprintf(stderr, "writeout=immediate not supported on "
2720                             "this platform\n");
2721                     exit(1);
2722 #endif
2723                 }
2724                 qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));
2725                 qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
2726                 qemu_opt_set(fsdev, "security_model",
2727                              qemu_opt_get(opts, "security_model"));
2728                 socket = qemu_opt_get(opts, "socket");
2729                 if (socket) {
2730                     qemu_opt_set(fsdev, "socket", socket);
2731                 }
2732                 sock_fd = qemu_opt_get(opts, "sock_fd");
2733                 if (sock_fd) {
2734                     qemu_opt_set(fsdev, "sock_fd", sock_fd);
2735                 }
2736
2737                 qemu_opt_set_bool(fsdev, "readonly",
2738                                 qemu_opt_get_bool(opts, "readonly", 0));
2739                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2740                 qemu_opt_set(device, "driver", "virtio-9p-pci");
2741                 qemu_opt_set(device, "fsdev",
2742                              qemu_opt_get(opts, "mount_tag"));
2743                 qemu_opt_set(device, "mount_tag",
2744                              qemu_opt_get(opts, "mount_tag"));
2745                 break;
2746             }
2747             case QEMU_OPTION_virtfs_synth: {
2748                 QemuOpts *fsdev;
2749                 QemuOpts *device;
2750
2751                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth", 1);
2752                 if (!fsdev) {
2753                     fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");
2754                     exit(1);
2755                 }
2756                 qemu_opt_set(fsdev, "fsdriver", "synth");
2757
2758                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2759                 qemu_opt_set(device, "driver", "virtio-9p-pci");
2760                 qemu_opt_set(device, "fsdev", "v_synth");
2761                 qemu_opt_set(device, "mount_tag", "v_synth");
2762                 break;
2763             }
2764             case QEMU_OPTION_serial:
2765                 add_device_config(DEV_SERIAL, optarg);
2766                 default_serial = 0;
2767                 if (strncmp(optarg, "mon:", 4) == 0) {
2768                     default_monitor = 0;
2769                 }
2770                 break;
2771             case QEMU_OPTION_watchdog:
2772                 if (watchdog) {
2773                     fprintf(stderr,
2774                             "qemu: only one watchdog option may be given\n");
2775                     return 1;
2776                 }
2777                 watchdog = optarg;
2778                 break;
2779             case QEMU_OPTION_watchdog_action:
2780                 if (select_watchdog_action(optarg) == -1) {
2781                     fprintf(stderr, "Unknown -watchdog-action parameter\n");
2782                     exit(1);
2783                 }
2784                 break;
2785             case QEMU_OPTION_virtiocon:
2786                 add_device_config(DEV_VIRTCON, optarg);
2787                 default_virtcon = 0;
2788                 if (strncmp(optarg, "mon:", 4) == 0) {
2789                     default_monitor = 0;
2790                 }
2791                 break;
2792             case QEMU_OPTION_parallel:
2793                 add_device_config(DEV_PARALLEL, optarg);
2794                 default_parallel = 0;
2795                 if (strncmp(optarg, "mon:", 4) == 0) {
2796                     default_monitor = 0;
2797                 }
2798                 break;
2799             case QEMU_OPTION_debugcon:
2800                 add_device_config(DEV_DEBUGCON, optarg);
2801                 break;
2802             case QEMU_OPTION_loadvm:
2803                 loadvm = optarg;
2804                 break;
2805             case QEMU_OPTION_full_screen:
2806                 full_screen = 1;
2807                 break;
2808 #ifdef CONFIG_SDL
2809             case QEMU_OPTION_no_frame:
2810                 no_frame = 1;
2811                 break;
2812             case QEMU_OPTION_alt_grab:
2813                 alt_grab = 1;
2814                 break;
2815             case QEMU_OPTION_ctrl_grab:
2816                 ctrl_grab = 1;
2817                 break;
2818             case QEMU_OPTION_no_quit:
2819                 no_quit = 1;
2820                 break;
2821             case QEMU_OPTION_sdl:
2822                 display_type = DT_SDL;
2823                 break;
2824 #else
2825             case QEMU_OPTION_no_frame:
2826             case QEMU_OPTION_alt_grab:
2827             case QEMU_OPTION_ctrl_grab:
2828             case QEMU_OPTION_no_quit:
2829             case QEMU_OPTION_sdl:
2830                 fprintf(stderr, "SDL support is disabled\n");
2831                 exit(1);
2832 #endif
2833             case QEMU_OPTION_pidfile:
2834                 pid_file = optarg;
2835                 break;
2836             case QEMU_OPTION_win2k_hack:
2837                 win2k_install_hack = 1;
2838                 break;
2839             case QEMU_OPTION_rtc_td_hack:
2840                 rtc_td_hack = 1;
2841                 break;
2842             case QEMU_OPTION_acpitable:
2843                 do_acpitable_option(optarg);
2844                 break;
2845             case QEMU_OPTION_smbios:
2846                 do_smbios_option(optarg);
2847                 break;
2848             case QEMU_OPTION_enable_kvm:
2849                 olist = qemu_find_opts("machine");
2850                 qemu_opts_reset(olist);
2851                 qemu_opts_parse(olist, "accel=kvm", 0);
2852                 break;
2853             case QEMU_OPTION_machine:
2854                 olist = qemu_find_opts("machine");
2855                 qemu_opts_reset(olist);
2856                 opts = qemu_opts_parse(olist, optarg, 1);
2857                 if (!opts) {
2858                     fprintf(stderr, "parse error: %s\n", optarg);
2859                     exit(1);
2860                 }
2861                 optarg = qemu_opt_get(opts, "type");
2862                 if (optarg) {
2863                     machine = machine_parse(optarg);
2864                 }
2865                 break;
2866             case QEMU_OPTION_usb:
2867                 usb_enabled = 1;
2868                 break;
2869             case QEMU_OPTION_usbdevice:
2870                 usb_enabled = 1;
2871                 add_device_config(DEV_USB, optarg);
2872                 break;
2873             case QEMU_OPTION_device:
2874                 if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
2875                     exit(1);
2876                 }
2877                 break;
2878             case QEMU_OPTION_smp:
2879                 smp_parse(optarg);
2880                 if (smp_cpus < 1) {
2881                     fprintf(stderr, "Invalid number of CPUs\n");
2882                     exit(1);
2883                 }
2884                 if (max_cpus < smp_cpus) {
2885                     fprintf(stderr, "maxcpus must be equal to or greater than "
2886                             "smp\n");
2887                     exit(1);
2888                 }
2889                 if (max_cpus > 255) {
2890                     fprintf(stderr, "Unsupported number of maxcpus\n");
2891                     exit(1);
2892                 }
2893                 break;
2894             case QEMU_OPTION_vnc:
2895 #ifdef CONFIG_VNC
2896                 display_remote++;
2897                 vnc_display = optarg;
2898 #else
2899                 fprintf(stderr, "VNC support is disabled\n");
2900                 exit(1);
2901 #endif
2902                 break;
2903             case QEMU_OPTION_no_acpi:
2904                 acpi_enabled = 0;
2905                 break;
2906             case QEMU_OPTION_no_hpet:
2907                 no_hpet = 1;
2908                 break;
2909             case QEMU_OPTION_balloon:
2910                 if (balloon_parse(optarg) < 0) {
2911                     fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
2912                     exit(1);
2913                 }
2914                 break;
2915             case QEMU_OPTION_no_reboot:
2916                 no_reboot = 1;
2917                 break;
2918             case QEMU_OPTION_no_shutdown:
2919                 no_shutdown = 1;
2920                 break;
2921             case QEMU_OPTION_show_cursor:
2922                 cursor_hide = 0;
2923                 break;
2924             case QEMU_OPTION_uuid:
2925                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
2926                     fprintf(stderr, "Fail to parse UUID string."
2927                             " Wrong format.\n");
2928                     exit(1);
2929                 }
2930                 break;
2931             case QEMU_OPTION_option_rom:
2932                 if (nb_option_roms >= MAX_OPTION_ROMS) {
2933                     fprintf(stderr, "Too many option ROMs\n");
2934                     exit(1);
2935                 }
2936                 opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
2937                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
2938                 option_rom[nb_option_roms].bootindex =
2939                     qemu_opt_get_number(opts, "bootindex", -1);
2940                 if (!option_rom[nb_option_roms].name) {
2941                     fprintf(stderr, "Option ROM file is not specified\n");
2942                     exit(1);
2943                 }
2944                 nb_option_roms++;
2945                 break;
2946             case QEMU_OPTION_semihosting:
2947                 semihosting_enabled = 1;
2948                 break;
2949             case QEMU_OPTION_name:
2950                 qemu_name = g_strdup(optarg);
2951                  {
2952                      char *p = strchr(qemu_name, ',');
2953                      if (p != NULL) {
2954                         *p++ = 0;
2955                         if (strncmp(p, "process=", 8)) {
2956                             fprintf(stderr, "Unknown subargument %s to -name\n", p);
2957                             exit(1);
2958                         }
2959                         p += 8;
2960                         os_set_proc_name(p);
2961                      }  
2962                  }      
2963                 break;
2964             case QEMU_OPTION_prom_env:
2965                 if (nb_prom_envs >= MAX_PROM_ENVS) {
2966                     fprintf(stderr, "Too many prom variables\n");
2967                     exit(1);
2968                 }
2969                 prom_envs[nb_prom_envs] = optarg;
2970                 nb_prom_envs++;
2971                 break;
2972             case QEMU_OPTION_old_param:
2973                 old_param = 1;
2974                 break;
2975             case QEMU_OPTION_clock:
2976                 configure_alarms(optarg);
2977                 break;
2978             case QEMU_OPTION_startdate:
2979                 configure_rtc_date_offset(optarg, 1);
2980                 break;
2981             case QEMU_OPTION_rtc:
2982                 opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
2983                 if (!opts) {
2984                     exit(1);
2985                 }
2986                 configure_rtc(opts);
2987                 break;
2988             case QEMU_OPTION_tb_size:
2989                 tcg_tb_size = strtol(optarg, NULL, 0);
2990                 if (tcg_tb_size < 0) {
2991                     tcg_tb_size = 0;
2992                 }
2993                 break;
2994             case QEMU_OPTION_icount:
2995                 icount_option = optarg;
2996                 break;
2997             case QEMU_OPTION_incoming:
2998                 incoming = optarg;
2999                 break;
3000             case QEMU_OPTION_nodefaults:
3001                 default_serial = 0;
3002                 default_parallel = 0;
3003                 default_virtcon = 0;
3004                 default_monitor = 0;
3005                 default_net = 0;
3006                 default_floppy = 0;
3007                 default_cdrom = 0;
3008                 default_sdcard = 0;
3009                 vga_model = "none";
3010                 break;
3011             case QEMU_OPTION_xen_domid:
3012                 if (!(xen_available())) {
3013                     printf("Option %s not supported for this target\n", popt->name);
3014                     exit(1);
3015                 }
3016                 xen_domid = atoi(optarg);
3017                 break;
3018             case QEMU_OPTION_xen_create:
3019                 if (!(xen_available())) {
3020                     printf("Option %s not supported for this target\n", popt->name);
3021                     exit(1);
3022                 }
3023                 xen_mode = XEN_CREATE;
3024                 break;
3025             case QEMU_OPTION_xen_attach:
3026                 if (!(xen_available())) {
3027                     printf("Option %s not supported for this target\n", popt->name);
3028                     exit(1);
3029                 }
3030                 xen_mode = XEN_ATTACH;
3031                 break;
3032             case QEMU_OPTION_trace:
3033             {
3034                 opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3035                 if (!opts) {
3036                     exit(1);
3037                 }
3038                 trace_events = qemu_opt_get(opts, "events");
3039                 trace_file = qemu_opt_get(opts, "file");
3040                 break;
3041             }
3042             case QEMU_OPTION_readconfig:
3043                 {
3044                     int ret = qemu_read_config_file(optarg);
3045                     if (ret < 0) {
3046                         fprintf(stderr, "read config %s: %s\n", optarg,
3047                             strerror(-ret));
3048                         exit(1);
3049                     }
3050                     break;
3051                 }
3052             case QEMU_OPTION_spice:
3053                 olist = qemu_find_opts("spice");
3054                 if (!olist) {
3055                     fprintf(stderr, "spice is not supported by this qemu build.\n");
3056                     exit(1);
3057                 }
3058                 opts = qemu_opts_parse(olist, optarg, 0);
3059                 if (!opts) {
3060                     fprintf(stderr, "parse error: %s\n", optarg);
3061                     exit(1);
3062                 }
3063                 break;
3064             case QEMU_OPTION_writeconfig:
3065                 {
3066                     FILE *fp;
3067                     if (strcmp(optarg, "-") == 0) {
3068                         fp = stdout;
3069                     } else {
3070                         fp = fopen(optarg, "w");
3071                         if (fp == NULL) {
3072                             fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3073                             exit(1);
3074                         }
3075                     }
3076                     qemu_config_write(fp);
3077                     fclose(fp);
3078                     break;
3079                 }
3080             default:
3081                 os_parse_cmd_args(popt->index, optarg);
3082             }
3083         }
3084     }
3085     loc_set_none();
3086
3087     /* Open the logfile at this point, if necessary. We can't open the logfile
3088      * when encountering either of the logging options (-d or -D) because the
3089      * other one may be encountered later on the command line, changing the
3090      * location or level of logging.
3091      */
3092     if (log_mask) {
3093         if (log_file) {
3094             set_cpu_log_filename(log_file);
3095         }
3096         set_cpu_log(log_mask);
3097     }
3098
3099     if (!trace_backend_init(trace_events, trace_file)) {
3100         exit(1);
3101     }
3102
3103     /* If no data_dir is specified then try to find it relative to the
3104        executable path.  */
3105     if (!data_dir) {
3106         data_dir = os_find_datadir(argv[0]);
3107     }
3108     /* If all else fails use the install path specified when building. */
3109     if (!data_dir) {
3110         data_dir = CONFIG_QEMU_DATADIR;
3111     }
3112
3113     if (machine == NULL) {
3114         fprintf(stderr, "No machine found.\n");
3115         exit(1);
3116     }
3117
3118     /*
3119      * Default to max_cpus = smp_cpus, in case the user doesn't
3120      * specify a max_cpus value.
3121      */
3122     if (!max_cpus)
3123         max_cpus = smp_cpus;
3124
3125     machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3126     if (smp_cpus > machine->max_cpus) {
3127         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3128                 "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3129                 machine->max_cpus);
3130         exit(1);
3131     }
3132
3133     /*
3134      * Get the default machine options from the machine if it is not already
3135      * specified either by the configuration file or by the command line.
3136      */
3137     if (machine->default_machine_opts) {
3138         QemuOptsList *list = qemu_find_opts("machine");
3139         const char *p = NULL;
3140
3141         if (!QTAILQ_EMPTY(&list->head)) {
3142             p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
3143         }
3144         if (p == NULL) {
3145             qemu_opts_reset(list);
3146             opts = qemu_opts_parse(list, machine->default_machine_opts, 0);
3147             if (!opts) {
3148                 fprintf(stderr, "parse error for machine %s: %s\n",
3149                         machine->name, machine->default_machine_opts);
3150                 exit(1);
3151             }
3152         }
3153     }
3154
3155     qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3156     qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3157
3158     if (machine->no_serial) {
3159         default_serial = 0;
3160     }
3161     if (machine->no_parallel) {
3162         default_parallel = 0;
3163     }
3164     if (!machine->use_virtcon) {
3165         default_virtcon = 0;
3166     }
3167     if (machine->no_floppy) {
3168         default_floppy = 0;
3169     }
3170     if (machine->no_cdrom) {
3171         default_cdrom = 0;
3172     }
3173     if (machine->no_sdcard) {
3174         default_sdcard = 0;
3175     }
3176
3177     if (display_type == DT_NOGRAPHIC) {
3178         if (default_parallel)
3179             add_device_config(DEV_PARALLEL, "null");
3180         if (default_serial && default_monitor) {
3181             add_device_config(DEV_SERIAL, "mon:stdio");
3182         } else if (default_virtcon && default_monitor) {
3183             add_device_config(DEV_VIRTCON, "mon:stdio");
3184         } else {
3185             if (default_serial)
3186                 add_device_config(DEV_SERIAL, "stdio");
3187             if (default_virtcon)
3188                 add_device_config(DEV_VIRTCON, "stdio");
3189             if (default_monitor)
3190                 monitor_parse("stdio", "readline");
3191         }
3192     } else {
3193         if (default_serial)
3194             add_device_config(DEV_SERIAL, "vc:80Cx24C");
3195         if (default_parallel)
3196             add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3197         if (default_monitor)
3198             monitor_parse("vc:80Cx24C", "readline");
3199         if (default_virtcon)
3200             add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3201     }
3202
3203     socket_init();
3204
3205     if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3206         exit(1);
3207 #ifdef CONFIG_VIRTFS
3208     if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3209         exit(1);
3210     }
3211 #endif
3212
3213     os_daemonize();
3214
3215     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3216         os_pidfile_error();
3217         exit(1);
3218     }
3219
3220     /* init the memory */
3221     if (ram_size == 0) {
3222         ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3223     }
3224
3225     configure_accelerator();
3226
3227     qemu_init_cpu_loop();
3228     if (qemu_init_main_loop()) {
3229         fprintf(stderr, "qemu_init_main_loop failed\n");
3230         exit(1);
3231     }
3232     linux_boot = (kernel_filename != NULL);
3233
3234     if (!linux_boot && *kernel_cmdline != '\0') {
3235         fprintf(stderr, "-append only allowed with -kernel option\n");
3236         exit(1);
3237     }
3238
3239     if (!linux_boot && initrd_filename != NULL) {
3240         fprintf(stderr, "-initrd only allowed with -kernel option\n");
3241         exit(1);
3242     }
3243
3244     os_set_line_buffering();
3245
3246     if (init_timer_alarm() < 0) {
3247         fprintf(stderr, "could not initialize alarm timer\n");
3248         exit(1);
3249     }
3250
3251     if (icount_option && (kvm_enabled() || xen_enabled())) {
3252         fprintf(stderr, "-icount is not allowed with kvm or xen\n");
3253         exit(1);
3254     }
3255     configure_icount(icount_option);
3256
3257     if (net_init_clients() < 0) {
3258         exit(1);
3259     }
3260
3261     /* init the bluetooth world */
3262     if (foreach_device_config(DEV_BT, bt_parse))
3263         exit(1);
3264
3265     if (!xen_enabled()) {
3266         /* On 32-bit hosts, QEMU is limited by virtual address space */
3267         if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
3268             fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3269             exit(1);
3270         }
3271     }
3272
3273     cpu_exec_init_all();
3274
3275     bdrv_init_with_whitelist();
3276
3277     blk_mig_init();
3278
3279     /* open the virtual block devices */
3280     if (snapshot)
3281         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
3282     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
3283         exit(1);
3284
3285     default_drive(default_cdrom, snapshot, machine->use_scsi,
3286                   IF_DEFAULT, 2, CDROM_OPTS);
3287     default_drive(default_floppy, snapshot, machine->use_scsi,
3288                   IF_FLOPPY, 0, FD_OPTS);
3289     default_drive(default_sdcard, snapshot, machine->use_scsi,
3290                   IF_SD, 0, SD_OPTS);
3291
3292     register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
3293                          ram_load, NULL);
3294
3295     if (nb_numa_nodes > 0) {
3296         int i;
3297
3298         if (nb_numa_nodes > MAX_NODES) {
3299             nb_numa_nodes = MAX_NODES;
3300         }
3301
3302         /* If no memory size if given for any node, assume the default case
3303          * and distribute the available memory equally across all nodes
3304          */
3305         for (i = 0; i < nb_numa_nodes; i++) {
3306             if (node_mem[i] != 0)
3307                 break;
3308         }
3309         if (i == nb_numa_nodes) {
3310             uint64_t usedmem = 0;
3311
3312             /* On Linux, the each node's border has to be 8MB aligned,
3313              * the final node gets the rest.
3314              */
3315             for (i = 0; i < nb_numa_nodes - 1; i++) {
3316                 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3317                 usedmem += node_mem[i];
3318             }
3319             node_mem[i] = ram_size - usedmem;
3320         }
3321
3322         for (i = 0; i < nb_numa_nodes; i++) {
3323             if (node_cpumask[i] != 0)
3324                 break;
3325         }
3326         /* assigning the VCPUs round-robin is easier to implement, guest OSes
3327          * must cope with this anyway, because there are BIOSes out there in
3328          * real machines which also use this scheme.
3329          */
3330         if (i == nb_numa_nodes) {
3331             for (i = 0; i < max_cpus; i++) {
3332                 node_cpumask[i % nb_numa_nodes] |= 1 << i;
3333             }
3334         }
3335     }
3336
3337     if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3338         exit(1);
3339     }
3340
3341     if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3342         exit(1);
3343     if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3344         exit(1);
3345     if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3346         exit(1);
3347     if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3348         exit(1);
3349
3350     module_call_init(MODULE_INIT_DEVICE);
3351
3352     /* must be after qdev registration but before machine init */
3353     if (vga_model) {
3354         select_vgahw(vga_model);
3355     } else if (cirrus_vga_available()) {
3356         select_vgahw("cirrus");
3357     } else {
3358         select_vgahw("none");
3359     }
3360
3361     if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)
3362         exit(0);
3363
3364     if (watchdog) {
3365         i = select_watchdog(watchdog);
3366         if (i > 0)
3367             exit (i == 1 ? 1 : 0);
3368     }
3369
3370     if (machine->compat_props) {
3371         qdev_prop_register_global_list(machine->compat_props);
3372     }
3373     qemu_add_globals();
3374
3375     qdev_machine_init();
3376
3377     machine->init(ram_size, boot_devices,
3378                   kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3379
3380     cpu_synchronize_all_post_init();
3381
3382     set_numa_modes();
3383
3384     current_machine = machine;
3385
3386     /* init USB devices */
3387     if (usb_enabled) {
3388         if (foreach_device_config(DEV_USB, usb_parse) < 0)
3389             exit(1);
3390     }
3391
3392     /* init generic devices */
3393     if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3394         exit(1);
3395
3396     net_check_clients();
3397
3398     /* just use the first displaystate for the moment */
3399     ds = get_displaystate();
3400
3401     if (using_spice)
3402         display_remote++;
3403     if (display_type == DT_DEFAULT && !display_remote) {
3404 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3405         display_type = DT_SDL;
3406 #elif defined(CONFIG_VNC)
3407         vnc_display = "localhost:0,to=99";
3408         show_vnc_port = 1;
3409 #else
3410         display_type = DT_NONE;
3411 #endif
3412     }
3413
3414
3415     /* init local displays */
3416     switch (display_type) {
3417     case DT_NOGRAPHIC:
3418         break;
3419 #if defined(CONFIG_CURSES)
3420     case DT_CURSES:
3421         curses_display_init(ds, full_screen);
3422         break;
3423 #endif
3424 #if defined(CONFIG_SDL)
3425     case DT_SDL:
3426         sdl_display_init(ds, full_screen, no_frame);
3427         break;
3428 #elif defined(CONFIG_COCOA)
3429     case DT_SDL:
3430         cocoa_display_init(ds, full_screen);
3431         break;
3432 #endif
3433     default:
3434         break;
3435     }
3436
3437     /* must be after terminal init, SDL library changes signal handlers */
3438     os_setup_signal_handling();
3439
3440 #ifdef CONFIG_VNC
3441     /* init remote displays */
3442     if (vnc_display) {
3443         vnc_display_init(ds);
3444         if (vnc_display_open(ds, vnc_display) < 0)
3445             exit(1);
3446
3447         if (show_vnc_port) {
3448             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3449         }
3450     }
3451 #endif
3452 #ifdef CONFIG_SPICE
3453     if (using_spice && !qxl_enabled) {
3454         qemu_spice_display_init(ds);
3455     }
3456 #endif
3457
3458     /* display setup */
3459     dpy_resize(ds);
3460     dcl = ds->listeners;
3461     while (dcl != NULL) {
3462         if (dcl->dpy_refresh != NULL) {
3463             ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3464             qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3465             break;
3466         }
3467         dcl = dcl->next;
3468     }
3469     text_consoles_set_display(ds);
3470
3471     if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3472         fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3473                 gdbstub_dev);
3474         exit(1);
3475     }
3476
3477     qdev_machine_creation_done();
3478
3479     if (rom_load_all() != 0) {
3480         fprintf(stderr, "rom loading failed\n");
3481         exit(1);
3482     }
3483
3484     /* TODO: once all bus devices are qdevified, this should be done
3485      * when bus is created by qdev.c */
3486     qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3487     qemu_run_machine_init_done_notifiers();
3488
3489     qemu_system_reset(VMRESET_SILENT);
3490     if (loadvm) {
3491         if (load_vmstate(loadvm) < 0) {
3492             autostart = 0;
3493         }
3494     }
3495
3496     if (incoming) {
3497         runstate_set(RUN_STATE_INMIGRATE);
3498         int ret = qemu_start_incoming_migration(incoming);
3499         if (ret < 0) {
3500             fprintf(stderr, "Migration failed. Exit code %s(%d), exiting.\n",
3501                     incoming, ret);
3502             exit(ret);
3503         }
3504     } else if (autostart) {
3505         vm_start();
3506     }
3507
3508     os_setup_post();
3509
3510     resume_all_vcpus();
3511     main_loop();
3512     bdrv_close_all();
3513     pause_all_vcpus();
3514     net_cleanup();
3515     res_free();
3516
3517     return 0;
3518 }