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