]> Git Repo - qemu.git/blob - vl.c
qemu/osdep: Remove the need for qemu_init_auxval
[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
31 #include "config-host.h"
32
33 #ifdef CONFIG_SECCOMP
34 #include "sysemu/seccomp.h"
35 #endif
36
37 #if defined(CONFIG_VDE)
38 #include <libvdeplug.h>
39 #endif
40
41 #ifdef CONFIG_SDL
42 #if defined(__APPLE__) || defined(main)
43 #include <SDL.h>
44 int qemu_main(int argc, char **argv, char **envp);
45 int main(int argc, char **argv)
46 {
47     return qemu_main(argc, argv, NULL);
48 }
49 #undef main
50 #define main qemu_main
51 #endif
52 #endif /* CONFIG_SDL */
53
54 #ifdef CONFIG_COCOA
55 #undef main
56 #define main qemu_main
57 #endif /* CONFIG_COCOA */
58
59 #include <glib.h>
60
61 #include "qemu/sockets.h"
62 #include "hw/hw.h"
63 #include "hw/boards.h"
64 #include "hw/usb.h"
65 #include "hw/pcmcia.h"
66 #include "hw/i386/pc.h"
67 #include "hw/isa/isa.h"
68 #include "hw/bt.h"
69 #include "sysemu/watchdog.h"
70 #include "hw/i386/smbios.h"
71 #include "hw/xen/xen.h"
72 #include "hw/qdev.h"
73 #include "hw/loader.h"
74 #include "monitor/qdev.h"
75 #include "sysemu/bt.h"
76 #include "net/net.h"
77 #include "net/slirp.h"
78 #include "monitor/monitor.h"
79 #include "ui/console.h"
80 #include "sysemu/sysemu.h"
81 #include "exec/gdbstub.h"
82 #include "qemu/timer.h"
83 #include "sysemu/char.h"
84 #include "qemu/bitmap.h"
85 #include "qemu/cache-utils.h"
86 #include "sysemu/blockdev.h"
87 #include "hw/block/block.h"
88 #include "migration/block.h"
89 #include "sysemu/tpm.h"
90 #include "sysemu/dma.h"
91 #include "audio/audio.h"
92 #include "migration/migration.h"
93 #include "sysemu/kvm.h"
94 #include "qapi/qmp/qjson.h"
95 #include "qemu/option.h"
96 #include "qemu/config-file.h"
97 #include "qemu-options.h"
98 #include "qmp-commands.h"
99 #include "qemu/main-loop.h"
100 #ifdef CONFIG_VIRTFS
101 #include "fsdev/qemu-fsdev.h"
102 #endif
103 #include "sysemu/qtest.h"
104
105 #include "disas/disas.h"
106
107
108 #include "slirp/libslirp.h"
109
110 #include "trace.h"
111 #include "trace/control.h"
112 #include "qemu/queue.h"
113 #include "sysemu/cpus.h"
114 #include "sysemu/arch_init.h"
115 #include "qemu/osdep.h"
116
117 #include "ui/qemu-spice.h"
118 #include "qapi/string-input-visitor.h"
119 #include "qapi/opts-visitor.h"
120
121 #define DEFAULT_RAM_SIZE 128
122
123 #define MAX_VIRTIO_CONSOLES 1
124 #define MAX_SCLP_CONSOLES 1
125
126 static const char *data_dir[16];
127 static int data_dir_idx;
128 const char *bios_name = NULL;
129 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
130 DisplayType display_type = DT_DEFAULT;
131 static int display_remote;
132 const char* keyboard_layout = NULL;
133 ram_addr_t ram_size;
134 const char *mem_path = NULL;
135 int mem_prealloc = 0; /* force preallocation of physical target memory */
136 int nb_nics;
137 NICInfo nd_table[MAX_NICS];
138 int autostart;
139 static int rtc_utc = 1;
140 static int rtc_date_offset = -1; /* -1 means no change */
141 QEMUClockType rtc_clock;
142 int vga_interface_type = VGA_NONE;
143 static int full_screen = 0;
144 static int no_frame = 0;
145 int no_quit = 0;
146 #ifdef CONFIG_GTK
147 static bool grab_on_hover;
148 #endif
149 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
150 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
151 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
152 CharDriverState *sclp_hds[MAX_SCLP_CONSOLES];
153 int win2k_install_hack = 0;
154 int singlestep = 0;
155 int smp_cpus = 1;
156 int max_cpus = 0;
157 int smp_cores = 1;
158 int smp_threads = 1;
159 #ifdef CONFIG_VNC
160 const char *vnc_display;
161 #endif
162 int acpi_enabled = 1;
163 int no_hpet = 0;
164 int fd_bootchk = 1;
165 static int no_reboot;
166 int no_shutdown = 0;
167 int cursor_hide = 1;
168 int graphic_rotate = 0;
169 const char *watchdog;
170 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
171 int nb_option_roms;
172 int semihosting_enabled = 0;
173 int old_param = 0;
174 const char *qemu_name;
175 int alt_grab = 0;
176 int ctrl_grab = 0;
177 unsigned int nb_prom_envs = 0;
178 const char *prom_envs[MAX_PROM_ENVS];
179 int boot_menu;
180 static bool boot_strict;
181 uint8_t *boot_splash_filedata;
182 size_t boot_splash_filedata_size;
183 uint8_t qemu_extra_params_fw[2];
184
185 typedef struct FWBootEntry FWBootEntry;
186
187 struct FWBootEntry {
188     QTAILQ_ENTRY(FWBootEntry) link;
189     int32_t bootindex;
190     DeviceState *dev;
191     char *suffix;
192 };
193
194 static QTAILQ_HEAD(, FWBootEntry) fw_boot_order =
195     QTAILQ_HEAD_INITIALIZER(fw_boot_order);
196
197 int nb_numa_nodes;
198 NodeInfo numa_info[MAX_NODES];
199
200 uint8_t qemu_uuid[16];
201 bool qemu_uuid_set;
202
203 static QEMUBootSetHandler *boot_set_handler;
204 static void *boot_set_opaque;
205
206 static NotifierList exit_notifiers =
207     NOTIFIER_LIST_INITIALIZER(exit_notifiers);
208
209 static NotifierList machine_init_done_notifiers =
210     NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
211
212 static bool tcg_allowed = true;
213 bool xen_allowed;
214 uint32_t xen_domid;
215 enum xen_mode xen_mode = XEN_EMULATE;
216 static int tcg_tb_size;
217
218 static int has_defaults = 1;
219 static int default_serial = 1;
220 static int default_parallel = 1;
221 static int default_virtcon = 1;
222 static int default_sclp = 1;
223 static int default_monitor = 1;
224 static int default_floppy = 1;
225 static int default_cdrom = 1;
226 static int default_sdcard = 1;
227 static int default_vga = 1;
228
229 static struct {
230     const char *driver;
231     int *flag;
232 } default_list[] = {
233     { .driver = "isa-serial",           .flag = &default_serial    },
234     { .driver = "isa-parallel",         .flag = &default_parallel  },
235     { .driver = "isa-fdc",              .flag = &default_floppy    },
236     { .driver = "ide-cd",               .flag = &default_cdrom     },
237     { .driver = "ide-hd",               .flag = &default_cdrom     },
238     { .driver = "ide-drive",            .flag = &default_cdrom     },
239     { .driver = "scsi-cd",              .flag = &default_cdrom     },
240     { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
241     { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
242     { .driver = "virtio-serial",        .flag = &default_virtcon   },
243     { .driver = "VGA",                  .flag = &default_vga       },
244     { .driver = "isa-vga",              .flag = &default_vga       },
245     { .driver = "cirrus-vga",           .flag = &default_vga       },
246     { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
247     { .driver = "vmware-svga",          .flag = &default_vga       },
248     { .driver = "qxl-vga",              .flag = &default_vga       },
249 };
250
251 static QemuOptsList qemu_rtc_opts = {
252     .name = "rtc",
253     .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
254     .desc = {
255         {
256             .name = "base",
257             .type = QEMU_OPT_STRING,
258         },{
259             .name = "clock",
260             .type = QEMU_OPT_STRING,
261         },{
262             .name = "driftfix",
263             .type = QEMU_OPT_STRING,
264         },
265         { /* end of list */ }
266     },
267 };
268
269 static QemuOptsList qemu_sandbox_opts = {
270     .name = "sandbox",
271     .implied_opt_name = "enable",
272     .head = QTAILQ_HEAD_INITIALIZER(qemu_sandbox_opts.head),
273     .desc = {
274         {
275             .name = "enable",
276             .type = QEMU_OPT_BOOL,
277         },
278         { /* end of list */ }
279     },
280 };
281
282 static QemuOptsList qemu_trace_opts = {
283     .name = "trace",
284     .implied_opt_name = "trace",
285     .head = QTAILQ_HEAD_INITIALIZER(qemu_trace_opts.head),
286     .desc = {
287         {
288             .name = "events",
289             .type = QEMU_OPT_STRING,
290         },{
291             .name = "file",
292             .type = QEMU_OPT_STRING,
293         },
294         { /* end of list */ }
295     },
296 };
297
298 static QemuOptsList qemu_option_rom_opts = {
299     .name = "option-rom",
300     .implied_opt_name = "romfile",
301     .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
302     .desc = {
303         {
304             .name = "bootindex",
305             .type = QEMU_OPT_NUMBER,
306         }, {
307             .name = "romfile",
308             .type = QEMU_OPT_STRING,
309         },
310         { /* end of list */ }
311     },
312 };
313
314 static QemuOptsList qemu_machine_opts = {
315     .name = "machine",
316     .implied_opt_name = "type",
317     .merge_lists = true,
318     .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
319     .desc = {
320         {
321             .name = "type",
322             .type = QEMU_OPT_STRING,
323             .help = "emulated machine"
324         }, {
325             .name = "accel",
326             .type = QEMU_OPT_STRING,
327             .help = "accelerator list",
328         }, {
329             .name = "kernel_irqchip",
330             .type = QEMU_OPT_BOOL,
331             .help = "use KVM in-kernel irqchip",
332         }, {
333             .name = "kvm_shadow_mem",
334             .type = QEMU_OPT_SIZE,
335             .help = "KVM shadow MMU size",
336         }, {
337             .name = "kernel",
338             .type = QEMU_OPT_STRING,
339             .help = "Linux kernel image file",
340         }, {
341             .name = "initrd",
342             .type = QEMU_OPT_STRING,
343             .help = "Linux initial ramdisk file",
344         }, {
345             .name = "append",
346             .type = QEMU_OPT_STRING,
347             .help = "Linux kernel command line",
348         }, {
349             .name = "dtb",
350             .type = QEMU_OPT_STRING,
351             .help = "Linux kernel device tree file",
352         }, {
353             .name = "dumpdtb",
354             .type = QEMU_OPT_STRING,
355             .help = "Dump current dtb to a file and quit",
356         }, {
357             .name = "phandle_start",
358             .type = QEMU_OPT_NUMBER,
359             .help = "The first phandle ID we may generate dynamically",
360         }, {
361             .name = "dt_compatible",
362             .type = QEMU_OPT_STRING,
363             .help = "Overrides the \"compatible\" property of the dt root node",
364         }, {
365             .name = "dump-guest-core",
366             .type = QEMU_OPT_BOOL,
367             .help = "Include guest memory in  a core dump",
368         }, {
369             .name = "mem-merge",
370             .type = QEMU_OPT_BOOL,
371             .help = "enable/disable memory merge support",
372         },{
373             .name = "usb",
374             .type = QEMU_OPT_BOOL,
375             .help = "Set on/off to enable/disable usb",
376         },{
377             .name = "firmware",
378             .type = QEMU_OPT_STRING,
379             .help = "firmware image",
380         },{
381             .name = "kvm-type",
382             .type = QEMU_OPT_STRING,
383             .help = "Specifies the KVM virtualization mode (HV, PR)",
384         },
385         { /* End of list */ }
386     },
387 };
388
389 static QemuOptsList qemu_boot_opts = {
390     .name = "boot-opts",
391     .implied_opt_name = "order",
392     .merge_lists = true,
393     .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
394     .desc = {
395         {
396             .name = "order",
397             .type = QEMU_OPT_STRING,
398         }, {
399             .name = "once",
400             .type = QEMU_OPT_STRING,
401         }, {
402             .name = "menu",
403             .type = QEMU_OPT_BOOL,
404         }, {
405             .name = "splash",
406             .type = QEMU_OPT_STRING,
407         }, {
408             .name = "splash-time",
409             .type = QEMU_OPT_STRING,
410         }, {
411             .name = "reboot-timeout",
412             .type = QEMU_OPT_STRING,
413         }, {
414             .name = "strict",
415             .type = QEMU_OPT_BOOL,
416         },
417         { /*End of list */ }
418     },
419 };
420
421 static QemuOptsList qemu_add_fd_opts = {
422     .name = "add-fd",
423     .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
424     .desc = {
425         {
426             .name = "fd",
427             .type = QEMU_OPT_NUMBER,
428             .help = "file descriptor of which a duplicate is added to fd set",
429         },{
430             .name = "set",
431             .type = QEMU_OPT_NUMBER,
432             .help = "ID of the fd set to add fd to",
433         },{
434             .name = "opaque",
435             .type = QEMU_OPT_STRING,
436             .help = "free-form string used to describe fd",
437         },
438         { /* end of list */ }
439     },
440 };
441
442 static QemuOptsList qemu_object_opts = {
443     .name = "object",
444     .implied_opt_name = "qom-type",
445     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
446     .desc = {
447         { }
448     },
449 };
450
451 static QemuOptsList qemu_tpmdev_opts = {
452     .name = "tpmdev",
453     .implied_opt_name = "type",
454     .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
455     .desc = {
456         /* options are defined in the TPM backends */
457         { /* end of list */ }
458     },
459 };
460
461 static QemuOptsList qemu_realtime_opts = {
462     .name = "realtime",
463     .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
464     .desc = {
465         {
466             .name = "mlock",
467             .type = QEMU_OPT_BOOL,
468         },
469         { /* end of list */ }
470     },
471 };
472
473 static QemuOptsList qemu_msg_opts = {
474     .name = "msg",
475     .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
476     .desc = {
477         {
478             .name = "timestamp",
479             .type = QEMU_OPT_BOOL,
480         },
481         { /* end of list */ }
482     },
483 };
484
485 static QemuOptsList qemu_name_opts = {
486     .name = "name",
487     .implied_opt_name = "guest",
488     .merge_lists = true,
489     .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
490     .desc = {
491         {
492             .name = "guest",
493             .type = QEMU_OPT_STRING,
494             .help = "Sets the name of the guest.\n"
495                     "This name will be displayed in the SDL window caption.\n"
496                     "The name will also be used for the VNC server",
497         }, {
498             .name = "process",
499             .type = QEMU_OPT_STRING,
500             .help = "Sets the name of the QEMU process, as shown in top etc",
501         }, {
502             .name = "debug-threads",
503             .type = QEMU_OPT_BOOL,
504             .help = "When enabled, name the individual threads; defaults off.\n"
505                     "NOTE: The thread names are for debugging and not a\n"
506                     "stable API.",
507         },
508         { /* End of list */ }
509     },
510 };
511
512 static QemuOptsList qemu_mem_opts = {
513     .name = "memory",
514     .implied_opt_name = "size",
515     .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
516     .merge_lists = true,
517     .desc = {
518         {
519             .name = "size",
520             .type = QEMU_OPT_SIZE,
521         },
522         {
523             .name = "slots",
524             .type = QEMU_OPT_NUMBER,
525         },
526         {
527             .name = "maxmem",
528             .type = QEMU_OPT_SIZE,
529         },
530         { /* end of list */ }
531     },
532 };
533
534 /**
535  * Get machine options
536  *
537  * Returns: machine options (never null).
538  */
539 QemuOpts *qemu_get_machine_opts(void)
540 {
541     return qemu_find_opts_singleton("machine");
542 }
543
544 const char *qemu_get_vm_name(void)
545 {
546     return qemu_name;
547 }
548
549 static void res_free(void)
550 {
551     if (boot_splash_filedata != NULL) {
552         g_free(boot_splash_filedata);
553         boot_splash_filedata = NULL;
554     }
555 }
556
557 static int default_driver_check(QemuOpts *opts, void *opaque)
558 {
559     const char *driver = qemu_opt_get(opts, "driver");
560     int i;
561
562     if (!driver)
563         return 0;
564     for (i = 0; i < ARRAY_SIZE(default_list); i++) {
565         if (strcmp(default_list[i].driver, driver) != 0)
566             continue;
567         *(default_list[i].flag) = 0;
568     }
569     return 0;
570 }
571
572 /***********************************************************/
573 /* QEMU state */
574
575 static RunState current_run_state = RUN_STATE_PRELAUNCH;
576
577 /* We use RUN_STATE_MAX but any invalid value will do */
578 static RunState vmstop_requested = RUN_STATE_MAX;
579 static QemuMutex vmstop_lock;
580
581 typedef struct {
582     RunState from;
583     RunState to;
584 } RunStateTransition;
585
586 static const RunStateTransition runstate_transitions_def[] = {
587     /*     from      ->     to      */
588     { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
589     { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
590
591     { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
592     { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
593
594     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
595     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
596
597     { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
598     { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
599
600     { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
601     { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
602
603     { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
604     { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
605
606     { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
607     { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
608     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
609
610     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
611     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
612
613     { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
614
615     { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
616     { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
617     { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
618     { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
619     { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
620     { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
621     { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
622     { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
623     { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
624     { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
625
626     { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
627
628     { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
629     { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
630
631     { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
632     { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
633     { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
634     { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
635
636     { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
637     { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
638
639     { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
640     { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
641
642     { RUN_STATE_MAX, RUN_STATE_MAX },
643 };
644
645 static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
646
647 bool runstate_check(RunState state)
648 {
649     return current_run_state == state;
650 }
651
652 static void runstate_init(void)
653 {
654     const RunStateTransition *p;
655
656     memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
657     for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
658         runstate_valid_transitions[p->from][p->to] = true;
659     }
660
661     qemu_mutex_init(&vmstop_lock);
662 }
663
664 /* This function will abort() on invalid state transitions */
665 void runstate_set(RunState new_state)
666 {
667     assert(new_state < RUN_STATE_MAX);
668
669     if (!runstate_valid_transitions[current_run_state][new_state]) {
670         fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
671                 RunState_lookup[current_run_state],
672                 RunState_lookup[new_state]);
673         abort();
674     }
675     trace_runstate_set(new_state);
676     current_run_state = new_state;
677 }
678
679 int runstate_is_running(void)
680 {
681     return runstate_check(RUN_STATE_RUNNING);
682 }
683
684 bool runstate_needs_reset(void)
685 {
686     return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
687         runstate_check(RUN_STATE_SHUTDOWN);
688 }
689
690 StatusInfo *qmp_query_status(Error **errp)
691 {
692     StatusInfo *info = g_malloc0(sizeof(*info));
693
694     info->running = runstate_is_running();
695     info->singlestep = singlestep;
696     info->status = current_run_state;
697
698     return info;
699 }
700
701 static bool qemu_vmstop_requested(RunState *r)
702 {
703     qemu_mutex_lock(&vmstop_lock);
704     *r = vmstop_requested;
705     vmstop_requested = RUN_STATE_MAX;
706     qemu_mutex_unlock(&vmstop_lock);
707     return *r < RUN_STATE_MAX;
708 }
709
710 void qemu_system_vmstop_request_prepare(void)
711 {
712     qemu_mutex_lock(&vmstop_lock);
713 }
714
715 void qemu_system_vmstop_request(RunState state)
716 {
717     vmstop_requested = state;
718     qemu_mutex_unlock(&vmstop_lock);
719     qemu_notify_event();
720 }
721
722 void vm_start(void)
723 {
724     RunState requested;
725
726     qemu_vmstop_requested(&requested);
727     if (runstate_is_running() && requested == RUN_STATE_MAX) {
728         return;
729     }
730
731     /* Ensure that a STOP/RESUME pair of events is emitted if a
732      * vmstop request was pending.  The BLOCK_IO_ERROR event, for
733      * example, according to documentation is always followed by
734      * the STOP event.
735      */
736     if (runstate_is_running()) {
737         monitor_protocol_event(QEVENT_STOP, NULL);
738     } else {
739         cpu_enable_ticks();
740         runstate_set(RUN_STATE_RUNNING);
741         vm_state_notify(1, RUN_STATE_RUNNING);
742         resume_all_vcpus();
743     }
744
745     monitor_protocol_event(QEVENT_RESUME, NULL);
746 }
747
748
749 /***********************************************************/
750 /* real time host monotonic timer */
751
752 /***********************************************************/
753 /* host time/date access */
754 void qemu_get_timedate(struct tm *tm, int offset)
755 {
756     time_t ti;
757
758     time(&ti);
759     ti += offset;
760     if (rtc_date_offset == -1) {
761         if (rtc_utc)
762             gmtime_r(&ti, tm);
763         else
764             localtime_r(&ti, tm);
765     } else {
766         ti -= rtc_date_offset;
767         gmtime_r(&ti, tm);
768     }
769 }
770
771 int qemu_timedate_diff(struct tm *tm)
772 {
773     time_t seconds;
774
775     if (rtc_date_offset == -1)
776         if (rtc_utc)
777             seconds = mktimegm(tm);
778         else {
779             struct tm tmp = *tm;
780             tmp.tm_isdst = -1; /* use timezone to figure it out */
781             seconds = mktime(&tmp);
782         }
783     else
784         seconds = mktimegm(tm) + rtc_date_offset;
785
786     return seconds - time(NULL);
787 }
788
789 void rtc_change_mon_event(struct tm *tm)
790 {
791     QObject *data;
792
793     data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
794     monitor_protocol_event(QEVENT_RTC_CHANGE, data);
795     qobject_decref(data);
796 }
797
798 static void configure_rtc_date_offset(const char *startdate, int legacy)
799 {
800     time_t rtc_start_date;
801     struct tm tm;
802
803     if (!strcmp(startdate, "now") && legacy) {
804         rtc_date_offset = -1;
805     } else {
806         if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
807                    &tm.tm_year,
808                    &tm.tm_mon,
809                    &tm.tm_mday,
810                    &tm.tm_hour,
811                    &tm.tm_min,
812                    &tm.tm_sec) == 6) {
813             /* OK */
814         } else if (sscanf(startdate, "%d-%d-%d",
815                           &tm.tm_year,
816                           &tm.tm_mon,
817                           &tm.tm_mday) == 3) {
818             tm.tm_hour = 0;
819             tm.tm_min = 0;
820             tm.tm_sec = 0;
821         } else {
822             goto date_fail;
823         }
824         tm.tm_year -= 1900;
825         tm.tm_mon--;
826         rtc_start_date = mktimegm(&tm);
827         if (rtc_start_date == -1) {
828         date_fail:
829             fprintf(stderr, "Invalid date format. Valid formats are:\n"
830                             "'2006-06-17T16:01:21' or '2006-06-17'\n");
831             exit(1);
832         }
833         rtc_date_offset = time(NULL) - rtc_start_date;
834     }
835 }
836
837 static void configure_rtc(QemuOpts *opts)
838 {
839     const char *value;
840
841     value = qemu_opt_get(opts, "base");
842     if (value) {
843         if (!strcmp(value, "utc")) {
844             rtc_utc = 1;
845         } else if (!strcmp(value, "localtime")) {
846             rtc_utc = 0;
847         } else {
848             configure_rtc_date_offset(value, 0);
849         }
850     }
851     value = qemu_opt_get(opts, "clock");
852     if (value) {
853         if (!strcmp(value, "host")) {
854             rtc_clock = QEMU_CLOCK_HOST;
855         } else if (!strcmp(value, "rt")) {
856             rtc_clock = QEMU_CLOCK_REALTIME;
857         } else if (!strcmp(value, "vm")) {
858             rtc_clock = QEMU_CLOCK_VIRTUAL;
859         } else {
860             fprintf(stderr, "qemu: invalid option value '%s'\n", value);
861             exit(1);
862         }
863     }
864     value = qemu_opt_get(opts, "driftfix");
865     if (value) {
866         if (!strcmp(value, "slew")) {
867             static GlobalProperty slew_lost_ticks[] = {
868                 {
869                     .driver   = "mc146818rtc",
870                     .property = "lost_tick_policy",
871                     .value    = "slew",
872                 },
873                 { /* end of list */ }
874             };
875
876             qdev_prop_register_global_list(slew_lost_ticks);
877         } else if (!strcmp(value, "none")) {
878             /* discard is default */
879         } else {
880             fprintf(stderr, "qemu: invalid option value '%s'\n", value);
881             exit(1);
882         }
883     }
884 }
885
886 /***********************************************************/
887 /* Bluetooth support */
888 static int nb_hcis;
889 static int cur_hci;
890 static struct HCIInfo *hci_table[MAX_NICS];
891
892 struct HCIInfo *qemu_next_hci(void)
893 {
894     if (cur_hci == nb_hcis)
895         return &null_hci;
896
897     return hci_table[cur_hci++];
898 }
899
900 static int bt_hci_parse(const char *str)
901 {
902     struct HCIInfo *hci;
903     bdaddr_t bdaddr;
904
905     if (nb_hcis >= MAX_NICS) {
906         fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
907         return -1;
908     }
909
910     hci = hci_init(str);
911     if (!hci)
912         return -1;
913
914     bdaddr.b[0] = 0x52;
915     bdaddr.b[1] = 0x54;
916     bdaddr.b[2] = 0x00;
917     bdaddr.b[3] = 0x12;
918     bdaddr.b[4] = 0x34;
919     bdaddr.b[5] = 0x56 + nb_hcis;
920     hci->bdaddr_set(hci, bdaddr.b);
921
922     hci_table[nb_hcis++] = hci;
923
924     return 0;
925 }
926
927 static void bt_vhci_add(int vlan_id)
928 {
929     struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
930
931     if (!vlan->slave)
932         fprintf(stderr, "qemu: warning: adding a VHCI to "
933                         "an empty scatternet %i\n", vlan_id);
934
935     bt_vhci_init(bt_new_hci(vlan));
936 }
937
938 static struct bt_device_s *bt_device_add(const char *opt)
939 {
940     struct bt_scatternet_s *vlan;
941     int vlan_id = 0;
942     char *endp = strstr(opt, ",vlan=");
943     int len = (endp ? endp - opt : strlen(opt)) + 1;
944     char devname[10];
945
946     pstrcpy(devname, MIN(sizeof(devname), len), opt);
947
948     if (endp) {
949         vlan_id = strtol(endp + 6, &endp, 0);
950         if (*endp) {
951             fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
952             return 0;
953         }
954     }
955
956     vlan = qemu_find_bt_vlan(vlan_id);
957
958     if (!vlan->slave)
959         fprintf(stderr, "qemu: warning: adding a slave device to "
960                         "an empty scatternet %i\n", vlan_id);
961
962     if (!strcmp(devname, "keyboard"))
963         return bt_keyboard_init(vlan);
964
965     fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
966     return 0;
967 }
968
969 static int bt_parse(const char *opt)
970 {
971     const char *endp, *p;
972     int vlan;
973
974     if (strstart(opt, "hci", &endp)) {
975         if (!*endp || *endp == ',') {
976             if (*endp)
977                 if (!strstart(endp, ",vlan=", 0))
978                     opt = endp + 1;
979
980             return bt_hci_parse(opt);
981        }
982     } else if (strstart(opt, "vhci", &endp)) {
983         if (!*endp || *endp == ',') {
984             if (*endp) {
985                 if (strstart(endp, ",vlan=", &p)) {
986                     vlan = strtol(p, (char **) &endp, 0);
987                     if (*endp) {
988                         fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
989                         return 1;
990                     }
991                 } else {
992                     fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
993                     return 1;
994                 }
995             } else
996                 vlan = 0;
997
998             bt_vhci_add(vlan);
999             return 0;
1000         }
1001     } else if (strstart(opt, "device:", &endp))
1002         return !bt_device_add(endp);
1003
1004     fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1005     return 1;
1006 }
1007
1008 static int parse_sandbox(QemuOpts *opts, void *opaque)
1009 {
1010     /* FIXME: change this to true for 1.3 */
1011     if (qemu_opt_get_bool(opts, "enable", false)) {
1012 #ifdef CONFIG_SECCOMP
1013         if (seccomp_start() < 0) {
1014             qerror_report(ERROR_CLASS_GENERIC_ERROR,
1015                           "failed to install seccomp syscall filter in the kernel");
1016             return -1;
1017         }
1018 #else
1019         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1020                       "sandboxing request but seccomp is not compiled into this build");
1021         return -1;
1022 #endif
1023     }
1024
1025     return 0;
1026 }
1027
1028 static int parse_name(QemuOpts *opts, void *opaque)
1029 {
1030     const char *proc_name;
1031
1032     if (qemu_opt_get(opts, "debug-threads")) {
1033         qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
1034     }
1035     qemu_name = qemu_opt_get(opts, "guest");
1036
1037     proc_name = qemu_opt_get(opts, "process");
1038     if (proc_name) {
1039         os_set_proc_name(proc_name);
1040     }
1041
1042     return 0;
1043 }
1044
1045 bool usb_enabled(bool default_usb)
1046 {
1047     return qemu_opt_get_bool(qemu_get_machine_opts(), "usb",
1048                              has_defaults && default_usb);
1049 }
1050
1051 #ifndef _WIN32
1052 static int parse_add_fd(QemuOpts *opts, void *opaque)
1053 {
1054     int fd, dupfd, flags;
1055     int64_t fdset_id;
1056     const char *fd_opaque = NULL;
1057
1058     fd = qemu_opt_get_number(opts, "fd", -1);
1059     fdset_id = qemu_opt_get_number(opts, "set", -1);
1060     fd_opaque = qemu_opt_get(opts, "opaque");
1061
1062     if (fd < 0) {
1063         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1064                       "fd option is required and must be non-negative");
1065         return -1;
1066     }
1067
1068     if (fd <= STDERR_FILENO) {
1069         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1070                       "fd cannot be a standard I/O stream");
1071         return -1;
1072     }
1073
1074     /*
1075      * All fds inherited across exec() necessarily have FD_CLOEXEC
1076      * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
1077      */
1078     flags = fcntl(fd, F_GETFD);
1079     if (flags == -1 || (flags & FD_CLOEXEC)) {
1080         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1081                       "fd is not valid or already in use");
1082         return -1;
1083     }
1084
1085     if (fdset_id < 0) {
1086         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1087                       "set option is required and must be non-negative");
1088         return -1;
1089     }
1090
1091 #ifdef F_DUPFD_CLOEXEC
1092     dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1093 #else
1094     dupfd = dup(fd);
1095     if (dupfd != -1) {
1096         qemu_set_cloexec(dupfd);
1097     }
1098 #endif
1099     if (dupfd == -1) {
1100         qerror_report(ERROR_CLASS_GENERIC_ERROR,
1101                       "Error duplicating fd: %s", strerror(errno));
1102         return -1;
1103     }
1104
1105     /* add the duplicate fd, and optionally the opaque string, to the fd set */
1106     monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque ? true : false,
1107                          fd_opaque, NULL);
1108
1109     return 0;
1110 }
1111
1112 static int cleanup_add_fd(QemuOpts *opts, void *opaque)
1113 {
1114     int fd;
1115
1116     fd = qemu_opt_get_number(opts, "fd", -1);
1117     close(fd);
1118
1119     return 0;
1120 }
1121 #endif
1122
1123 /***********************************************************/
1124 /* QEMU Block devices */
1125
1126 #define HD_OPTS "media=disk"
1127 #define CDROM_OPTS "media=cdrom"
1128 #define FD_OPTS ""
1129 #define PFLASH_OPTS ""
1130 #define MTD_OPTS ""
1131 #define SD_OPTS ""
1132
1133 static int drive_init_func(QemuOpts *opts, void *opaque)
1134 {
1135     BlockInterfaceType *block_default_type = opaque;
1136
1137     return drive_new(opts, *block_default_type) == NULL;
1138 }
1139
1140 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1141 {
1142     if (NULL == qemu_opt_get(opts, "snapshot")) {
1143         qemu_opt_set(opts, "snapshot", "on");
1144     }
1145     return 0;
1146 }
1147
1148 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1149                           int index, const char *optstr)
1150 {
1151     QemuOpts *opts;
1152
1153     if (!enable || drive_get_by_index(type, index)) {
1154         return;
1155     }
1156
1157     opts = drive_add(type, index, NULL, optstr);
1158     if (snapshot) {
1159         drive_enable_snapshot(opts, NULL);
1160     }
1161     if (!drive_new(opts, type)) {
1162         exit(1);
1163     }
1164 }
1165
1166 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1167 {
1168     boot_set_handler = func;
1169     boot_set_opaque = opaque;
1170 }
1171
1172 int qemu_boot_set(const char *boot_order)
1173 {
1174     if (!boot_set_handler) {
1175         return -EINVAL;
1176     }
1177     return boot_set_handler(boot_set_opaque, boot_order);
1178 }
1179
1180 static void validate_bootdevices(const char *devices)
1181 {
1182     /* We just do some generic consistency checks */
1183     const char *p;
1184     int bitmap = 0;
1185
1186     for (p = devices; *p != '\0'; p++) {
1187         /* Allowed boot devices are:
1188          * a-b: floppy disk drives
1189          * c-f: IDE disk drives
1190          * g-m: machine implementation dependent drives
1191          * n-p: network devices
1192          * It's up to each machine implementation to check if the given boot
1193          * devices match the actual hardware implementation and firmware
1194          * features.
1195          */
1196         if (*p < 'a' || *p > 'p') {
1197             fprintf(stderr, "Invalid boot device '%c'\n", *p);
1198             exit(1);
1199         }
1200         if (bitmap & (1 << (*p - 'a'))) {
1201             fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1202             exit(1);
1203         }
1204         bitmap |= 1 << (*p - 'a');
1205     }
1206 }
1207
1208 static void restore_boot_order(void *opaque)
1209 {
1210     char *normal_boot_order = opaque;
1211     static int first = 1;
1212
1213     /* Restore boot order and remove ourselves after the first boot */
1214     if (first) {
1215         first = 0;
1216         return;
1217     }
1218
1219     qemu_boot_set(normal_boot_order);
1220
1221     qemu_unregister_reset(restore_boot_order, normal_boot_order);
1222     g_free(normal_boot_order);
1223 }
1224
1225 void add_boot_device_path(int32_t bootindex, DeviceState *dev,
1226                           const char *suffix)
1227 {
1228     FWBootEntry *node, *i;
1229
1230     if (bootindex < 0) {
1231         return;
1232     }
1233
1234     assert(dev != NULL || suffix != NULL);
1235
1236     node = g_malloc0(sizeof(FWBootEntry));
1237     node->bootindex = bootindex;
1238     node->suffix = g_strdup(suffix);
1239     node->dev = dev;
1240
1241     QTAILQ_FOREACH(i, &fw_boot_order, link) {
1242         if (i->bootindex == bootindex) {
1243             fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
1244             exit(1);
1245         } else if (i->bootindex < bootindex) {
1246             continue;
1247         }
1248         QTAILQ_INSERT_BEFORE(i, node, link);
1249         return;
1250     }
1251     QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
1252 }
1253
1254 DeviceState *get_boot_device(uint32_t position)
1255 {
1256     uint32_t counter = 0;
1257     FWBootEntry *i = NULL;
1258     DeviceState *res = NULL;
1259
1260     if (!QTAILQ_EMPTY(&fw_boot_order)) {
1261         QTAILQ_FOREACH(i, &fw_boot_order, link) {
1262             if (counter == position) {
1263                 res = i->dev;
1264                 break;
1265             }
1266             counter++;
1267         }
1268     }
1269     return res;
1270 }
1271
1272 /*
1273  * This function returns null terminated string that consist of new line
1274  * separated device paths.
1275  *
1276  * memory pointed by "size" is assigned total length of the array in bytes
1277  *
1278  */
1279 char *get_boot_devices_list(size_t *size, bool ignore_suffixes)
1280 {
1281     FWBootEntry *i;
1282     size_t total = 0;
1283     char *list = NULL;
1284
1285     QTAILQ_FOREACH(i, &fw_boot_order, link) {
1286         char *devpath = NULL, *bootpath;
1287         size_t len;
1288
1289         if (i->dev) {
1290             devpath = qdev_get_fw_dev_path(i->dev);
1291             assert(devpath);
1292         }
1293
1294         if (i->suffix && !ignore_suffixes && devpath) {
1295             size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
1296
1297             bootpath = g_malloc(bootpathlen);
1298             snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
1299             g_free(devpath);
1300         } else if (devpath) {
1301             bootpath = devpath;
1302         } else if (!ignore_suffixes) {
1303             assert(i->suffix);
1304             bootpath = g_strdup(i->suffix);
1305         } else {
1306             bootpath = g_strdup("");
1307         }
1308
1309         if (total) {
1310             list[total-1] = '\n';
1311         }
1312         len = strlen(bootpath) + 1;
1313         list = g_realloc(list, total + len);
1314         memcpy(&list[total], bootpath, len);
1315         total += len;
1316         g_free(bootpath);
1317     }
1318
1319     *size = total;
1320
1321     if (boot_strict && *size > 0) {
1322         list[total-1] = '\n';
1323         list = g_realloc(list, total + 5);
1324         memcpy(&list[total], "HALT", 5);
1325         *size = total + 5;
1326     }
1327     return list;
1328 }
1329
1330 static QemuOptsList qemu_smp_opts = {
1331     .name = "smp-opts",
1332     .implied_opt_name = "cpus",
1333     .merge_lists = true,
1334     .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1335     .desc = {
1336         {
1337             .name = "cpus",
1338             .type = QEMU_OPT_NUMBER,
1339         }, {
1340             .name = "sockets",
1341             .type = QEMU_OPT_NUMBER,
1342         }, {
1343             .name = "cores",
1344             .type = QEMU_OPT_NUMBER,
1345         }, {
1346             .name = "threads",
1347             .type = QEMU_OPT_NUMBER,
1348         }, {
1349             .name = "maxcpus",
1350             .type = QEMU_OPT_NUMBER,
1351         },
1352         { /*End of list */ }
1353     },
1354 };
1355
1356 static void smp_parse(QemuOpts *opts)
1357 {
1358     if (opts) {
1359
1360         unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
1361         unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
1362         unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
1363         unsigned threads = qemu_opt_get_number(opts, "threads", 0);
1364
1365         /* compute missing values, prefer sockets over cores over threads */
1366         if (cpus == 0 || sockets == 0) {
1367             sockets = sockets > 0 ? sockets : 1;
1368             cores = cores > 0 ? cores : 1;
1369             threads = threads > 0 ? threads : 1;
1370             if (cpus == 0) {
1371                 cpus = cores * threads * sockets;
1372             }
1373         } else {
1374             if (cores == 0) {
1375                 threads = threads > 0 ? threads : 1;
1376                 cores = cpus / (sockets * threads);
1377             } else {
1378                 threads = cpus / (cores * sockets);
1379             }
1380         }
1381
1382         max_cpus = qemu_opt_get_number(opts, "maxcpus", 0);
1383
1384         smp_cpus = cpus;
1385         smp_cores = cores > 0 ? cores : 1;
1386         smp_threads = threads > 0 ? threads : 1;
1387
1388     }
1389
1390     if (max_cpus == 0) {
1391         max_cpus = smp_cpus;
1392     }
1393
1394     if (max_cpus > MAX_CPUMASK_BITS) {
1395         fprintf(stderr, "Unsupported number of maxcpus\n");
1396         exit(1);
1397     }
1398     if (max_cpus < smp_cpus) {
1399         fprintf(stderr, "maxcpus must be equal to or greater than smp\n");
1400         exit(1);
1401     }
1402
1403 }
1404
1405 static void configure_realtime(QemuOpts *opts)
1406 {
1407     bool enable_mlock;
1408
1409     enable_mlock = qemu_opt_get_bool(opts, "mlock", true);
1410
1411     if (enable_mlock) {
1412         if (os_mlock() < 0) {
1413             fprintf(stderr, "qemu: locking memory failed\n");
1414             exit(1);
1415         }
1416     }
1417 }
1418
1419
1420 static void configure_msg(QemuOpts *opts)
1421 {
1422     enable_timestamp_msg = qemu_opt_get_bool(opts, "timestamp", true);
1423 }
1424
1425 /***********************************************************/
1426 /* USB devices */
1427
1428 static int usb_device_add(const char *devname)
1429 {
1430     USBDevice *dev = NULL;
1431 #ifndef CONFIG_LINUX
1432     const char *p;
1433 #endif
1434
1435     if (!usb_enabled(false)) {
1436         return -1;
1437     }
1438
1439     /* drivers with .usbdevice_name entry in USBDeviceInfo */
1440     dev = usbdevice_create(devname);
1441     if (dev)
1442         goto done;
1443
1444     /* the other ones */
1445 #ifndef CONFIG_LINUX
1446     /* only the linux version is qdev-ified, usb-bsd still needs this */
1447     if (strstart(devname, "host:", &p)) {
1448         dev = usb_host_device_open(usb_bus_find(-1), p);
1449     }
1450 #endif
1451     if (!dev)
1452         return -1;
1453
1454 done:
1455     return 0;
1456 }
1457
1458 static int usb_device_del(const char *devname)
1459 {
1460     int bus_num, addr;
1461     const char *p;
1462
1463     if (strstart(devname, "host:", &p)) {
1464         return -1;
1465     }
1466
1467     if (!usb_enabled(false)) {
1468         return -1;
1469     }
1470
1471     p = strchr(devname, '.');
1472     if (!p)
1473         return -1;
1474     bus_num = strtoul(devname, NULL, 0);
1475     addr = strtoul(p + 1, NULL, 0);
1476
1477     return usb_device_delete_addr(bus_num, addr);
1478 }
1479
1480 static int usb_parse(const char *cmdline)
1481 {
1482     int r;
1483     r = usb_device_add(cmdline);
1484     if (r < 0) {
1485         fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1486     }
1487     return r;
1488 }
1489
1490 void do_usb_add(Monitor *mon, const QDict *qdict)
1491 {
1492     const char *devname = qdict_get_str(qdict, "devname");
1493     if (usb_device_add(devname) < 0) {
1494         error_report("could not add USB device '%s'", devname);
1495     }
1496 }
1497
1498 void do_usb_del(Monitor *mon, const QDict *qdict)
1499 {
1500     const char *devname = qdict_get_str(qdict, "devname");
1501     if (usb_device_del(devname) < 0) {
1502         error_report("could not delete USB device '%s'", devname);
1503     }
1504 }
1505
1506 /***********************************************************/
1507 /* PCMCIA/Cardbus */
1508
1509 static struct pcmcia_socket_entry_s {
1510     PCMCIASocket *socket;
1511     struct pcmcia_socket_entry_s *next;
1512 } *pcmcia_sockets = 0;
1513
1514 void pcmcia_socket_register(PCMCIASocket *socket)
1515 {
1516     struct pcmcia_socket_entry_s *entry;
1517
1518     entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1519     entry->socket = socket;
1520     entry->next = pcmcia_sockets;
1521     pcmcia_sockets = entry;
1522 }
1523
1524 void pcmcia_socket_unregister(PCMCIASocket *socket)
1525 {
1526     struct pcmcia_socket_entry_s *entry, **ptr;
1527
1528     ptr = &pcmcia_sockets;
1529     for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1530         if (entry->socket == socket) {
1531             *ptr = entry->next;
1532             g_free(entry);
1533         }
1534 }
1535
1536 void pcmcia_info(Monitor *mon, const QDict *qdict)
1537 {
1538     struct pcmcia_socket_entry_s *iter;
1539
1540     if (!pcmcia_sockets)
1541         monitor_printf(mon, "No PCMCIA sockets\n");
1542
1543     for (iter = pcmcia_sockets; iter; iter = iter->next)
1544         monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1545                        iter->socket->attached ? iter->socket->card_string :
1546                        "Empty");
1547 }
1548
1549 /***********************************************************/
1550 /* machine registration */
1551
1552 MachineState *current_machine;
1553
1554 static void machine_class_init(ObjectClass *oc, void *data)
1555 {
1556     MachineClass *mc = MACHINE_CLASS(oc);
1557     QEMUMachine *qm = data;
1558
1559     mc->name = qm->name;
1560     mc->alias = qm->alias;
1561     mc->desc = qm->desc;
1562     mc->init = qm->init;
1563     mc->reset = qm->reset;
1564     mc->hot_add_cpu = qm->hot_add_cpu;
1565     mc->kvm_type = qm->kvm_type;
1566     mc->block_default_type = qm->block_default_type;
1567     mc->max_cpus = qm->max_cpus;
1568     mc->no_serial = qm->no_serial;
1569     mc->no_parallel = qm->no_parallel;
1570     mc->use_virtcon = qm->use_virtcon;
1571     mc->use_sclp = qm->use_sclp;
1572     mc->no_floppy = qm->no_floppy;
1573     mc->no_cdrom = qm->no_cdrom;
1574     mc->no_sdcard = qm->no_sdcard;
1575     mc->is_default = qm->is_default;
1576     mc->default_machine_opts = qm->default_machine_opts;
1577     mc->default_boot_order = qm->default_boot_order;
1578     mc->compat_props = qm->compat_props;
1579     mc->hw_version = qm->hw_version;
1580 }
1581
1582 int qemu_register_machine(QEMUMachine *m)
1583 {
1584     char *name = g_strconcat(m->name, TYPE_MACHINE_SUFFIX, NULL);
1585     TypeInfo ti = {
1586         .name       = name,
1587         .parent     = TYPE_MACHINE,
1588         .class_init = machine_class_init,
1589         .class_data = (void *)m,
1590     };
1591
1592     type_register(&ti);
1593     g_free(name);
1594
1595     return 0;
1596 }
1597
1598 static MachineClass *find_machine(const char *name)
1599 {
1600     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1601     MachineClass *mc = NULL;
1602
1603     for (el = machines; el; el = el->next) {
1604         MachineClass *temp = el->data;
1605
1606         if (!strcmp(temp->name, name)) {
1607             mc = temp;
1608             break;
1609         }
1610         if (temp->alias &&
1611             !strcmp(temp->alias, name)) {
1612             mc = temp;
1613             break;
1614         }
1615     }
1616
1617     g_slist_free(machines);
1618     return mc;
1619 }
1620
1621 MachineClass *find_default_machine(void)
1622 {
1623     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1624     MachineClass *mc = NULL;
1625
1626     for (el = machines; el; el = el->next) {
1627         MachineClass *temp = el->data;
1628
1629         if (temp->is_default) {
1630             mc = temp;
1631             break;
1632         }
1633     }
1634
1635     g_slist_free(machines);
1636     return mc;
1637 }
1638
1639 MachineInfoList *qmp_query_machines(Error **errp)
1640 {
1641     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
1642     MachineInfoList *mach_list = NULL;
1643
1644     for (el = machines; el; el = el->next) {
1645         MachineClass *mc = el->data;
1646         MachineInfoList *entry;
1647         MachineInfo *info;
1648
1649         info = g_malloc0(sizeof(*info));
1650         if (mc->is_default) {
1651             info->has_is_default = true;
1652             info->is_default = true;
1653         }
1654
1655         if (mc->alias) {
1656             info->has_alias = true;
1657             info->alias = g_strdup(mc->alias);
1658         }
1659
1660         info->name = g_strdup(mc->name);
1661         info->cpu_max = !mc->max_cpus ? 1 : mc->max_cpus;
1662
1663         entry = g_malloc0(sizeof(*entry));
1664         entry->value = info;
1665         entry->next = mach_list;
1666         mach_list = entry;
1667     }
1668
1669     g_slist_free(machines);
1670     return mach_list;
1671 }
1672
1673 /***********************************************************/
1674 /* main execution loop */
1675
1676 struct vm_change_state_entry {
1677     VMChangeStateHandler *cb;
1678     void *opaque;
1679     QLIST_ENTRY (vm_change_state_entry) entries;
1680 };
1681
1682 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1683
1684 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1685                                                      void *opaque)
1686 {
1687     VMChangeStateEntry *e;
1688
1689     e = g_malloc0(sizeof (*e));
1690
1691     e->cb = cb;
1692     e->opaque = opaque;
1693     QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1694     return e;
1695 }
1696
1697 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1698 {
1699     QLIST_REMOVE (e, entries);
1700     g_free (e);
1701 }
1702
1703 void vm_state_notify(int running, RunState state)
1704 {
1705     VMChangeStateEntry *e;
1706
1707     trace_vm_state_notify(running, state);
1708
1709     for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1710         e->cb(e->opaque, running, state);
1711     }
1712 }
1713
1714 /* reset/shutdown handler */
1715
1716 typedef struct QEMUResetEntry {
1717     QTAILQ_ENTRY(QEMUResetEntry) entry;
1718     QEMUResetHandler *func;
1719     void *opaque;
1720 } QEMUResetEntry;
1721
1722 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1723     QTAILQ_HEAD_INITIALIZER(reset_handlers);
1724 static int reset_requested;
1725 static int shutdown_requested, shutdown_signal = -1;
1726 static pid_t shutdown_pid;
1727 static int powerdown_requested;
1728 static int debug_requested;
1729 static int suspend_requested;
1730 static WakeupReason wakeup_reason;
1731 static NotifierList powerdown_notifiers =
1732     NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1733 static NotifierList suspend_notifiers =
1734     NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1735 static NotifierList wakeup_notifiers =
1736     NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1737 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1738
1739 int qemu_shutdown_requested_get(void)
1740 {
1741     return shutdown_requested;
1742 }
1743
1744 int qemu_reset_requested_get(void)
1745 {
1746     return reset_requested;
1747 }
1748
1749 static int qemu_shutdown_requested(void)
1750 {
1751     int r = shutdown_requested;
1752     shutdown_requested = 0;
1753     return r;
1754 }
1755
1756 static void qemu_kill_report(void)
1757 {
1758     if (!qtest_driver() && shutdown_signal != -1) {
1759         fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1760         if (shutdown_pid == 0) {
1761             /* This happens for eg ^C at the terminal, so it's worth
1762              * avoiding printing an odd message in that case.
1763              */
1764             fputc('\n', stderr);
1765         } else {
1766             fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1767         }
1768         shutdown_signal = -1;
1769     }
1770 }
1771
1772 static int qemu_reset_requested(void)
1773 {
1774     int r = reset_requested;
1775     reset_requested = 0;
1776     return r;
1777 }
1778
1779 static int qemu_suspend_requested(void)
1780 {
1781     int r = suspend_requested;
1782     suspend_requested = 0;
1783     return r;
1784 }
1785
1786 static WakeupReason qemu_wakeup_requested(void)
1787 {
1788     return wakeup_reason;
1789 }
1790
1791 static int qemu_powerdown_requested(void)
1792 {
1793     int r = powerdown_requested;
1794     powerdown_requested = 0;
1795     return r;
1796 }
1797
1798 static int qemu_debug_requested(void)
1799 {
1800     int r = debug_requested;
1801     debug_requested = 0;
1802     return r;
1803 }
1804
1805 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1806 {
1807     QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1808
1809     re->func = func;
1810     re->opaque = opaque;
1811     QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1812 }
1813
1814 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1815 {
1816     QEMUResetEntry *re;
1817
1818     QTAILQ_FOREACH(re, &reset_handlers, entry) {
1819         if (re->func == func && re->opaque == opaque) {
1820             QTAILQ_REMOVE(&reset_handlers, re, entry);
1821             g_free(re);
1822             return;
1823         }
1824     }
1825 }
1826
1827 void qemu_devices_reset(void)
1828 {
1829     QEMUResetEntry *re, *nre;
1830
1831     /* reset all devices */
1832     QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1833         re->func(re->opaque);
1834     }
1835 }
1836
1837 void qemu_system_reset(bool report)
1838 {
1839     MachineClass *mc;
1840
1841     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1842
1843     if (mc && mc->reset) {
1844         mc->reset();
1845     } else {
1846         qemu_devices_reset();
1847     }
1848     if (report) {
1849         monitor_protocol_event(QEVENT_RESET, NULL);
1850     }
1851     cpu_synchronize_all_post_reset();
1852 }
1853
1854 void qemu_system_reset_request(void)
1855 {
1856     if (no_reboot) {
1857         shutdown_requested = 1;
1858     } else {
1859         reset_requested = 1;
1860     }
1861     cpu_stop_current();
1862     qemu_notify_event();
1863 }
1864
1865 static void qemu_system_suspend(void)
1866 {
1867     pause_all_vcpus();
1868     notifier_list_notify(&suspend_notifiers, NULL);
1869     runstate_set(RUN_STATE_SUSPENDED);
1870     monitor_protocol_event(QEVENT_SUSPEND, NULL);
1871 }
1872
1873 void qemu_system_suspend_request(void)
1874 {
1875     if (runstate_check(RUN_STATE_SUSPENDED)) {
1876         return;
1877     }
1878     suspend_requested = 1;
1879     cpu_stop_current();
1880     qemu_notify_event();
1881 }
1882
1883 void qemu_register_suspend_notifier(Notifier *notifier)
1884 {
1885     notifier_list_add(&suspend_notifiers, notifier);
1886 }
1887
1888 void qemu_system_wakeup_request(WakeupReason reason)
1889 {
1890     trace_system_wakeup_request(reason);
1891
1892     if (!runstate_check(RUN_STATE_SUSPENDED)) {
1893         return;
1894     }
1895     if (!(wakeup_reason_mask & (1 << reason))) {
1896         return;
1897     }
1898     runstate_set(RUN_STATE_RUNNING);
1899     wakeup_reason = reason;
1900     qemu_notify_event();
1901 }
1902
1903 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1904 {
1905     if (enabled) {
1906         wakeup_reason_mask |= (1 << reason);
1907     } else {
1908         wakeup_reason_mask &= ~(1 << reason);
1909     }
1910 }
1911
1912 void qemu_register_wakeup_notifier(Notifier *notifier)
1913 {
1914     notifier_list_add(&wakeup_notifiers, notifier);
1915 }
1916
1917 void qemu_system_killed(int signal, pid_t pid)
1918 {
1919     shutdown_signal = signal;
1920     shutdown_pid = pid;
1921     no_shutdown = 0;
1922     qemu_system_shutdown_request();
1923 }
1924
1925 void qemu_system_shutdown_request(void)
1926 {
1927     shutdown_requested = 1;
1928     qemu_notify_event();
1929 }
1930
1931 static void qemu_system_powerdown(void)
1932 {
1933     monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1934     notifier_list_notify(&powerdown_notifiers, NULL);
1935 }
1936
1937 void qemu_system_powerdown_request(void)
1938 {
1939     powerdown_requested = 1;
1940     qemu_notify_event();
1941 }
1942
1943 void qemu_register_powerdown_notifier(Notifier *notifier)
1944 {
1945     notifier_list_add(&powerdown_notifiers, notifier);
1946 }
1947
1948 void qemu_system_debug_request(void)
1949 {
1950     debug_requested = 1;
1951     qemu_notify_event();
1952 }
1953
1954 static bool main_loop_should_exit(void)
1955 {
1956     RunState r;
1957     if (qemu_debug_requested()) {
1958         vm_stop(RUN_STATE_DEBUG);
1959     }
1960     if (qemu_suspend_requested()) {
1961         qemu_system_suspend();
1962     }
1963     if (qemu_shutdown_requested()) {
1964         qemu_kill_report();
1965         monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1966         if (no_shutdown) {
1967             vm_stop(RUN_STATE_SHUTDOWN);
1968         } else {
1969             return true;
1970         }
1971     }
1972     if (qemu_reset_requested()) {
1973         pause_all_vcpus();
1974         cpu_synchronize_all_states();
1975         qemu_system_reset(VMRESET_REPORT);
1976         resume_all_vcpus();
1977         if (runstate_needs_reset()) {
1978             runstate_set(RUN_STATE_PAUSED);
1979         }
1980     }
1981     if (qemu_wakeup_requested()) {
1982         pause_all_vcpus();
1983         cpu_synchronize_all_states();
1984         qemu_system_reset(VMRESET_SILENT);
1985         notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1986         wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1987         resume_all_vcpus();
1988         monitor_protocol_event(QEVENT_WAKEUP, NULL);
1989     }
1990     if (qemu_powerdown_requested()) {
1991         qemu_system_powerdown();
1992     }
1993     if (qemu_vmstop_requested(&r)) {
1994         vm_stop(r);
1995     }
1996     return false;
1997 }
1998
1999 static void main_loop(void)
2000 {
2001     bool nonblocking;
2002     int last_io = 0;
2003 #ifdef CONFIG_PROFILER
2004     int64_t ti;
2005 #endif
2006     do {
2007         nonblocking = !kvm_enabled() && !xen_enabled() && last_io > 0;
2008 #ifdef CONFIG_PROFILER
2009         ti = profile_getclock();
2010 #endif
2011         last_io = main_loop_wait(nonblocking);
2012 #ifdef CONFIG_PROFILER
2013         dev_time += profile_getclock() - ti;
2014 #endif
2015     } while (!main_loop_should_exit());
2016 }
2017
2018 static void version(void)
2019 {
2020     printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2021 }
2022
2023 static void help(int exitcode)
2024 {
2025     version();
2026     printf("usage: %s [options] [disk_image]\n\n"
2027            "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
2028             error_get_progname());
2029
2030 #define QEMU_OPTIONS_GENERATE_HELP
2031 #include "qemu-options-wrapper.h"
2032
2033     printf("\nDuring emulation, the following keys are useful:\n"
2034            "ctrl-alt-f      toggle full screen\n"
2035            "ctrl-alt-n      switch to virtual console 'n'\n"
2036            "ctrl-alt        toggle mouse and keyboard grab\n"
2037            "\n"
2038            "When using -nographic, press 'ctrl-a h' to get some help.\n");
2039
2040     exit(exitcode);
2041 }
2042
2043 #define HAS_ARG 0x0001
2044
2045 typedef struct QEMUOption {
2046     const char *name;
2047     int flags;
2048     int index;
2049     uint32_t arch_mask;
2050 } QEMUOption;
2051
2052 static const QEMUOption qemu_options[] = {
2053     { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2054 #define QEMU_OPTIONS_GENERATE_OPTIONS
2055 #include "qemu-options-wrapper.h"
2056     { NULL },
2057 };
2058
2059 static bool vga_available(void)
2060 {
2061     return object_class_by_name("VGA") || object_class_by_name("isa-vga");
2062 }
2063
2064 static bool cirrus_vga_available(void)
2065 {
2066     return object_class_by_name("cirrus-vga")
2067            || object_class_by_name("isa-cirrus-vga");
2068 }
2069
2070 static bool vmware_vga_available(void)
2071 {
2072     return object_class_by_name("vmware-svga");
2073 }
2074
2075 static bool qxl_vga_available(void)
2076 {
2077     return object_class_by_name("qxl-vga");
2078 }
2079
2080 static bool tcx_vga_available(void)
2081 {
2082     return object_class_by_name("SUNW,tcx");
2083 }
2084
2085 static bool cg3_vga_available(void)
2086 {
2087     return object_class_by_name("cgthree");
2088 }
2089
2090 static void select_vgahw (const char *p)
2091 {
2092     const char *opts;
2093
2094     assert(vga_interface_type == VGA_NONE);
2095     if (strstart(p, "std", &opts)) {
2096         if (vga_available()) {
2097             vga_interface_type = VGA_STD;
2098         } else {
2099             fprintf(stderr, "Error: standard VGA not available\n");
2100             exit(0);
2101         }
2102     } else if (strstart(p, "cirrus", &opts)) {
2103         if (cirrus_vga_available()) {
2104             vga_interface_type = VGA_CIRRUS;
2105         } else {
2106             fprintf(stderr, "Error: Cirrus VGA not available\n");
2107             exit(0);
2108         }
2109     } else if (strstart(p, "vmware", &opts)) {
2110         if (vmware_vga_available()) {
2111             vga_interface_type = VGA_VMWARE;
2112         } else {
2113             fprintf(stderr, "Error: VMWare SVGA not available\n");
2114             exit(0);
2115         }
2116     } else if (strstart(p, "xenfb", &opts)) {
2117         vga_interface_type = VGA_XENFB;
2118     } else if (strstart(p, "qxl", &opts)) {
2119         if (qxl_vga_available()) {
2120             vga_interface_type = VGA_QXL;
2121         } else {
2122             fprintf(stderr, "Error: QXL VGA not available\n");
2123             exit(0);
2124         }
2125     } else if (strstart(p, "tcx", &opts)) {
2126         if (tcx_vga_available()) {
2127             vga_interface_type = VGA_TCX;
2128         } else {
2129             fprintf(stderr, "Error: TCX framebuffer not available\n");
2130             exit(0);
2131         }
2132     } else if (strstart(p, "cg3", &opts)) {
2133         if (cg3_vga_available()) {
2134             vga_interface_type = VGA_CG3;
2135         } else {
2136             fprintf(stderr, "Error: CG3 framebuffer not available\n");
2137             exit(0);
2138         }
2139     } else if (!strstart(p, "none", &opts)) {
2140     invalid_vga:
2141         fprintf(stderr, "Unknown vga type: %s\n", p);
2142         exit(1);
2143     }
2144     while (*opts) {
2145         const char *nextopt;
2146
2147         if (strstart(opts, ",retrace=", &nextopt)) {
2148             opts = nextopt;
2149             if (strstart(opts, "dumb", &nextopt))
2150                 vga_retrace_method = VGA_RETRACE_DUMB;
2151             else if (strstart(opts, "precise", &nextopt))
2152                 vga_retrace_method = VGA_RETRACE_PRECISE;
2153             else goto invalid_vga;
2154         } else goto invalid_vga;
2155         opts = nextopt;
2156     }
2157 }
2158
2159 static DisplayType select_display(const char *p)
2160 {
2161     const char *opts;
2162     DisplayType display = DT_DEFAULT;
2163
2164     if (strstart(p, "sdl", &opts)) {
2165 #ifdef CONFIG_SDL
2166         display = DT_SDL;
2167         while (*opts) {
2168             const char *nextopt;
2169
2170             if (strstart(opts, ",frame=", &nextopt)) {
2171                 opts = nextopt;
2172                 if (strstart(opts, "on", &nextopt)) {
2173                     no_frame = 0;
2174                 } else if (strstart(opts, "off", &nextopt)) {
2175                     no_frame = 1;
2176                 } else {
2177                     goto invalid_sdl_args;
2178                 }
2179             } else if (strstart(opts, ",alt_grab=", &nextopt)) {
2180                 opts = nextopt;
2181                 if (strstart(opts, "on", &nextopt)) {
2182                     alt_grab = 1;
2183                 } else if (strstart(opts, "off", &nextopt)) {
2184                     alt_grab = 0;
2185                 } else {
2186                     goto invalid_sdl_args;
2187                 }
2188             } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
2189                 opts = nextopt;
2190                 if (strstart(opts, "on", &nextopt)) {
2191                     ctrl_grab = 1;
2192                 } else if (strstart(opts, "off", &nextopt)) {
2193                     ctrl_grab = 0;
2194                 } else {
2195                     goto invalid_sdl_args;
2196                 }
2197             } else if (strstart(opts, ",window_close=", &nextopt)) {
2198                 opts = nextopt;
2199                 if (strstart(opts, "on", &nextopt)) {
2200                     no_quit = 0;
2201                 } else if (strstart(opts, "off", &nextopt)) {
2202                     no_quit = 1;
2203                 } else {
2204                     goto invalid_sdl_args;
2205                 }
2206             } else {
2207             invalid_sdl_args:
2208                 fprintf(stderr, "Invalid SDL option string: %s\n", p);
2209                 exit(1);
2210             }
2211             opts = nextopt;
2212         }
2213 #else
2214         fprintf(stderr, "SDL support is disabled\n");
2215         exit(1);
2216 #endif
2217     } else if (strstart(p, "vnc", &opts)) {
2218 #ifdef CONFIG_VNC
2219         display_remote++;
2220
2221         if (*opts) {
2222             const char *nextopt;
2223
2224             if (strstart(opts, "=", &nextopt)) {
2225                 vnc_display = nextopt;
2226             }
2227         }
2228         if (!vnc_display) {
2229             fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
2230             exit(1);
2231         }
2232 #else
2233         fprintf(stderr, "VNC support is disabled\n");
2234         exit(1);
2235 #endif
2236     } else if (strstart(p, "curses", &opts)) {
2237 #ifdef CONFIG_CURSES
2238         display = DT_CURSES;
2239 #else
2240         fprintf(stderr, "Curses support is disabled\n");
2241         exit(1);
2242 #endif
2243     } else if (strstart(p, "gtk", &opts)) {
2244 #ifdef CONFIG_GTK
2245         display = DT_GTK;
2246         while (*opts) {
2247             const char *nextopt;
2248
2249             if (strstart(opts, ",grab_on_hover=", &nextopt)) {
2250                 opts = nextopt;
2251                 if (strstart(opts, "on", &nextopt)) {
2252                     grab_on_hover = true;
2253                 } else if (strstart(opts, "off", &nextopt)) {
2254                     grab_on_hover = false;
2255                 } else {
2256                     goto invalid_gtk_args;
2257                 }
2258             } else {
2259             invalid_gtk_args:
2260                 fprintf(stderr, "Invalid GTK option string: %s\n", p);
2261                 exit(1);
2262             }
2263             opts = nextopt;
2264         }
2265 #else
2266         fprintf(stderr, "GTK support is disabled\n");
2267         exit(1);
2268 #endif
2269     } else if (strstart(p, "none", &opts)) {
2270         display = DT_NONE;
2271     } else {
2272         fprintf(stderr, "Unknown display type: %s\n", p);
2273         exit(1);
2274     }
2275
2276     return display;
2277 }
2278
2279 static int balloon_parse(const char *arg)
2280 {
2281     QemuOpts *opts;
2282
2283     if (strcmp(arg, "none") == 0) {
2284         return 0;
2285     }
2286
2287     if (!strncmp(arg, "virtio", 6)) {
2288         if (arg[6] == ',') {
2289             /* have params -> parse them */
2290             opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
2291             if (!opts)
2292                 return  -1;
2293         } else {
2294             /* create empty opts */
2295             opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
2296                                     &error_abort);
2297         }
2298         qemu_opt_set(opts, "driver", "virtio-balloon");
2299         return 0;
2300     }
2301
2302     return -1;
2303 }
2304
2305 char *qemu_find_file(int type, const char *name)
2306 {
2307     int i;
2308     const char *subdir;
2309     char *buf;
2310
2311     /* Try the name as a straight path first */
2312     if (access(name, R_OK) == 0) {
2313         trace_load_file(name, name);
2314         return g_strdup(name);
2315     }
2316
2317     switch (type) {
2318     case QEMU_FILE_TYPE_BIOS:
2319         subdir = "";
2320         break;
2321     case QEMU_FILE_TYPE_KEYMAP:
2322         subdir = "keymaps/";
2323         break;
2324     default:
2325         abort();
2326     }
2327
2328     for (i = 0; i < data_dir_idx; i++) {
2329         buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2330         if (access(buf, R_OK) == 0) {
2331             trace_load_file(name, buf);
2332             return buf;
2333         }
2334         g_free(buf);
2335     }
2336     return NULL;
2337 }
2338
2339 static int device_help_func(QemuOpts *opts, void *opaque)
2340 {
2341     return qdev_device_help(opts);
2342 }
2343
2344 static int device_init_func(QemuOpts *opts, void *opaque)
2345 {
2346     DeviceState *dev;
2347
2348     dev = qdev_device_add(opts);
2349     if (!dev)
2350         return -1;
2351     object_unref(OBJECT(dev));
2352     return 0;
2353 }
2354
2355 static int chardev_init_func(QemuOpts *opts, void *opaque)
2356 {
2357     Error *local_err = NULL;
2358
2359     qemu_chr_new_from_opts(opts, NULL, &local_err);
2360     if (local_err) {
2361         error_report("%s", error_get_pretty(local_err));
2362         error_free(local_err);
2363         return -1;
2364     }
2365     return 0;
2366 }
2367
2368 #ifdef CONFIG_VIRTFS
2369 static int fsdev_init_func(QemuOpts *opts, void *opaque)
2370 {
2371     int ret;
2372     ret = qemu_fsdev_add(opts);
2373
2374     return ret;
2375 }
2376 #endif
2377
2378 static int mon_init_func(QemuOpts *opts, void *opaque)
2379 {
2380     CharDriverState *chr;
2381     const char *chardev;
2382     const char *mode;
2383     int flags;
2384
2385     mode = qemu_opt_get(opts, "mode");
2386     if (mode == NULL) {
2387         mode = "readline";
2388     }
2389     if (strcmp(mode, "readline") == 0) {
2390         flags = MONITOR_USE_READLINE;
2391     } else if (strcmp(mode, "control") == 0) {
2392         flags = MONITOR_USE_CONTROL;
2393     } else {
2394         fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2395         exit(1);
2396     }
2397
2398     if (qemu_opt_get_bool(opts, "pretty", 0))
2399         flags |= MONITOR_USE_PRETTY;
2400
2401     if (qemu_opt_get_bool(opts, "default", 0))
2402         flags |= MONITOR_IS_DEFAULT;
2403
2404     chardev = qemu_opt_get(opts, "chardev");
2405     chr = qemu_chr_find(chardev);
2406     if (chr == NULL) {
2407         fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2408         exit(1);
2409     }
2410
2411     qemu_chr_fe_claim_no_fail(chr);
2412     monitor_init(chr, flags);
2413     return 0;
2414 }
2415
2416 static void monitor_parse(const char *optarg, const char *mode)
2417 {
2418     static int monitor_device_index = 0;
2419     QemuOpts *opts;
2420     const char *p;
2421     char label[32];
2422     int def = 0;
2423
2424     if (strstart(optarg, "chardev:", &p)) {
2425         snprintf(label, sizeof(label), "%s", p);
2426     } else {
2427         snprintf(label, sizeof(label), "compat_monitor%d",
2428                  monitor_device_index);
2429         if (monitor_device_index == 0) {
2430             def = 1;
2431         }
2432         opts = qemu_chr_parse_compat(label, optarg);
2433         if (!opts) {
2434             fprintf(stderr, "parse error: %s\n", optarg);
2435             exit(1);
2436         }
2437     }
2438
2439     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, NULL);
2440     if (!opts) {
2441         fprintf(stderr, "duplicate chardev: %s\n", label);
2442         exit(1);
2443     }
2444     qemu_opt_set(opts, "mode", mode);
2445     qemu_opt_set(opts, "chardev", label);
2446     if (def)
2447         qemu_opt_set(opts, "default", "on");
2448     monitor_device_index++;
2449 }
2450
2451 struct device_config {
2452     enum {
2453         DEV_USB,       /* -usbdevice     */
2454         DEV_BT,        /* -bt            */
2455         DEV_SERIAL,    /* -serial        */
2456         DEV_PARALLEL,  /* -parallel      */
2457         DEV_VIRTCON,   /* -virtioconsole */
2458         DEV_DEBUGCON,  /* -debugcon */
2459         DEV_GDB,       /* -gdb, -s */
2460         DEV_SCLP,      /* s390 sclp */
2461     } type;
2462     const char *cmdline;
2463     Location loc;
2464     QTAILQ_ENTRY(device_config) next;
2465 };
2466
2467 static QTAILQ_HEAD(, device_config) device_configs =
2468     QTAILQ_HEAD_INITIALIZER(device_configs);
2469
2470 static void add_device_config(int type, const char *cmdline)
2471 {
2472     struct device_config *conf;
2473
2474     conf = g_malloc0(sizeof(*conf));
2475     conf->type = type;
2476     conf->cmdline = cmdline;
2477     loc_save(&conf->loc);
2478     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2479 }
2480
2481 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2482 {
2483     struct device_config *conf;
2484     int rc;
2485
2486     QTAILQ_FOREACH(conf, &device_configs, next) {
2487         if (conf->type != type)
2488             continue;
2489         loc_push_restore(&conf->loc);
2490         rc = func(conf->cmdline);
2491         loc_pop(&conf->loc);
2492         if (0 != rc)
2493             return rc;
2494     }
2495     return 0;
2496 }
2497
2498 static int serial_parse(const char *devname)
2499 {
2500     static int index = 0;
2501     char label[32];
2502
2503     if (strcmp(devname, "none") == 0)
2504         return 0;
2505     if (index == MAX_SERIAL_PORTS) {
2506         fprintf(stderr, "qemu: too many serial ports\n");
2507         exit(1);
2508     }
2509     snprintf(label, sizeof(label), "serial%d", index);
2510     serial_hds[index] = qemu_chr_new(label, devname, NULL);
2511     if (!serial_hds[index]) {
2512         fprintf(stderr, "qemu: could not connect serial device"
2513                 " to character backend '%s'\n", devname);
2514         return -1;
2515     }
2516     index++;
2517     return 0;
2518 }
2519
2520 static int parallel_parse(const char *devname)
2521 {
2522     static int index = 0;
2523     char label[32];
2524
2525     if (strcmp(devname, "none") == 0)
2526         return 0;
2527     if (index == MAX_PARALLEL_PORTS) {
2528         fprintf(stderr, "qemu: too many parallel ports\n");
2529         exit(1);
2530     }
2531     snprintf(label, sizeof(label), "parallel%d", index);
2532     parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2533     if (!parallel_hds[index]) {
2534         fprintf(stderr, "qemu: could not connect parallel device"
2535                 " to character backend '%s'\n", devname);
2536         return -1;
2537     }
2538     index++;
2539     return 0;
2540 }
2541
2542 static int virtcon_parse(const char *devname)
2543 {
2544     QemuOptsList *device = qemu_find_opts("device");
2545     static int index = 0;
2546     char label[32];
2547     QemuOpts *bus_opts, *dev_opts;
2548
2549     if (strcmp(devname, "none") == 0)
2550         return 0;
2551     if (index == MAX_VIRTIO_CONSOLES) {
2552         fprintf(stderr, "qemu: too many virtio consoles\n");
2553         exit(1);
2554     }
2555
2556     bus_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2557     if (arch_type == QEMU_ARCH_S390X) {
2558         qemu_opt_set(bus_opts, "driver", "virtio-serial-s390");
2559     } else {
2560         qemu_opt_set(bus_opts, "driver", "virtio-serial-pci");
2561     }
2562
2563     dev_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2564     qemu_opt_set(dev_opts, "driver", "virtconsole");
2565
2566     snprintf(label, sizeof(label), "virtcon%d", index);
2567     virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2568     if (!virtcon_hds[index]) {
2569         fprintf(stderr, "qemu: could not connect virtio console"
2570                 " to character backend '%s'\n", devname);
2571         return -1;
2572     }
2573     qemu_opt_set(dev_opts, "chardev", label);
2574
2575     index++;
2576     return 0;
2577 }
2578
2579 static int sclp_parse(const char *devname)
2580 {
2581     QemuOptsList *device = qemu_find_opts("device");
2582     static int index = 0;
2583     char label[32];
2584     QemuOpts *dev_opts;
2585
2586     if (strcmp(devname, "none") == 0) {
2587         return 0;
2588     }
2589     if (index == MAX_SCLP_CONSOLES) {
2590         fprintf(stderr, "qemu: too many sclp consoles\n");
2591         exit(1);
2592     }
2593
2594     assert(arch_type == QEMU_ARCH_S390X);
2595
2596     dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2597     qemu_opt_set(dev_opts, "driver", "sclpconsole");
2598
2599     snprintf(label, sizeof(label), "sclpcon%d", index);
2600     sclp_hds[index] = qemu_chr_new(label, devname, NULL);
2601     if (!sclp_hds[index]) {
2602         fprintf(stderr, "qemu: could not connect sclp console"
2603                 " to character backend '%s'\n", devname);
2604         return -1;
2605     }
2606     qemu_opt_set(dev_opts, "chardev", label);
2607
2608     index++;
2609     return 0;
2610 }
2611
2612 static int debugcon_parse(const char *devname)
2613 {
2614     QemuOpts *opts;
2615
2616     if (!qemu_chr_new("debugcon", devname, NULL)) {
2617         exit(1);
2618     }
2619     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2620     if (!opts) {
2621         fprintf(stderr, "qemu: already have a debugcon device\n");
2622         exit(1);
2623     }
2624     qemu_opt_set(opts, "driver", "isa-debugcon");
2625     qemu_opt_set(opts, "chardev", "debugcon");
2626     return 0;
2627 }
2628
2629 static MachineClass *machine_parse(const char *name)
2630 {
2631     MachineClass *mc = NULL;
2632     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
2633
2634     if (name) {
2635         mc = find_machine(name);
2636     }
2637     if (mc) {
2638         return mc;
2639     }
2640     if (name && !is_help_option(name)) {
2641         error_report("Unsupported machine type");
2642         error_printf("Use -machine help to list supported machines!\n");
2643     } else {
2644         printf("Supported machines are:\n");
2645         for (el = machines; el; el = el->next) {
2646             MachineClass *mc = el->data;
2647             if (mc->alias) {
2648                 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2649             }
2650             printf("%-20s %s%s\n", mc->name, mc->desc,
2651                    mc->is_default ? " (default)" : "");
2652         }
2653     }
2654
2655     g_slist_free(machines);
2656     exit(!name || !is_help_option(name));
2657 }
2658
2659 static int tcg_init(MachineClass *mc)
2660 {
2661     tcg_exec_init(tcg_tb_size * 1024 * 1024);
2662     return 0;
2663 }
2664
2665 static struct {
2666     const char *opt_name;
2667     const char *name;
2668     int (*available)(void);
2669     int (*init)(MachineClass *mc);
2670     bool *allowed;
2671 } accel_list[] = {
2672     { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2673     { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2674     { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2675     { "qtest", "QTest", qtest_available, qtest_init_accel, &qtest_allowed },
2676 };
2677
2678 static int configure_accelerator(MachineClass *mc)
2679 {
2680     const char *p;
2681     char buf[10];
2682     int i, ret;
2683     bool accel_initialised = false;
2684     bool init_failed = false;
2685
2686     p = qemu_opt_get(qemu_get_machine_opts(), "accel");
2687     if (p == NULL) {
2688         /* Use the default "accelerator", tcg */
2689         p = "tcg";
2690     }
2691
2692     while (!accel_initialised && *p != '\0') {
2693         if (*p == ':') {
2694             p++;
2695         }
2696         p = get_opt_name(buf, sizeof (buf), p, ':');
2697         for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2698             if (strcmp(accel_list[i].opt_name, buf) == 0) {
2699                 if (!accel_list[i].available()) {
2700                     printf("%s not supported for this target\n",
2701                            accel_list[i].name);
2702                     break;
2703                 }
2704                 *(accel_list[i].allowed) = true;
2705                 ret = accel_list[i].init(mc);
2706                 if (ret < 0) {
2707                     init_failed = true;
2708                     fprintf(stderr, "failed to initialize %s: %s\n",
2709                             accel_list[i].name,
2710                             strerror(-ret));
2711                     *(accel_list[i].allowed) = false;
2712                 } else {
2713                     accel_initialised = true;
2714                 }
2715                 break;
2716             }
2717         }
2718         if (i == ARRAY_SIZE(accel_list)) {
2719             fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2720         }
2721     }
2722
2723     if (!accel_initialised) {
2724         if (!init_failed) {
2725             fprintf(stderr, "No accelerator found!\n");
2726         }
2727         exit(1);
2728     }
2729
2730     if (init_failed) {
2731         fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2732     }
2733
2734     return !accel_initialised;
2735 }
2736
2737 void qemu_add_exit_notifier(Notifier *notify)
2738 {
2739     notifier_list_add(&exit_notifiers, notify);
2740 }
2741
2742 void qemu_remove_exit_notifier(Notifier *notify)
2743 {
2744     notifier_remove(notify);
2745 }
2746
2747 static void qemu_run_exit_notifiers(void)
2748 {
2749     notifier_list_notify(&exit_notifiers, NULL);
2750 }
2751
2752 void qemu_add_machine_init_done_notifier(Notifier *notify)
2753 {
2754     notifier_list_add(&machine_init_done_notifiers, notify);
2755 }
2756
2757 static void qemu_run_machine_init_done_notifiers(void)
2758 {
2759     notifier_list_notify(&machine_init_done_notifiers, NULL);
2760 }
2761
2762 static const QEMUOption *lookup_opt(int argc, char **argv,
2763                                     const char **poptarg, int *poptind)
2764 {
2765     const QEMUOption *popt;
2766     int optind = *poptind;
2767     char *r = argv[optind];
2768     const char *optarg;
2769
2770     loc_set_cmdline(argv, optind, 1);
2771     optind++;
2772     /* Treat --foo the same as -foo.  */
2773     if (r[1] == '-')
2774         r++;
2775     popt = qemu_options;
2776     for(;;) {
2777         if (!popt->name) {
2778             error_report("invalid option");
2779             exit(1);
2780         }
2781         if (!strcmp(popt->name, r + 1))
2782             break;
2783         popt++;
2784     }
2785     if (popt->flags & HAS_ARG) {
2786         if (optind >= argc) {
2787             error_report("requires an argument");
2788             exit(1);
2789         }
2790         optarg = argv[optind++];
2791         loc_set_cmdline(argv, optind - 2, 2);
2792     } else {
2793         optarg = NULL;
2794     }
2795
2796     *poptarg = optarg;
2797     *poptind = optind;
2798
2799     return popt;
2800 }
2801
2802 static gpointer malloc_and_trace(gsize n_bytes)
2803 {
2804     void *ptr = malloc(n_bytes);
2805     trace_g_malloc(n_bytes, ptr);
2806     return ptr;
2807 }
2808
2809 static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2810 {
2811     void *ptr = realloc(mem, n_bytes);
2812     trace_g_realloc(mem, n_bytes, ptr);
2813     return ptr;
2814 }
2815
2816 static void free_and_trace(gpointer mem)
2817 {
2818     trace_g_free(mem);
2819     free(mem);
2820 }
2821
2822 static int object_set_property(const char *name, const char *value, void *opaque)
2823 {
2824     Object *obj = OBJECT(opaque);
2825     StringInputVisitor *siv;
2826     Error *local_err = NULL;
2827
2828     if (strcmp(name, "qom-type") == 0 || strcmp(name, "id") == 0 ||
2829         strcmp(name, "type") == 0) {
2830         return 0;
2831     }
2832
2833     siv = string_input_visitor_new(value);
2834     object_property_set(obj, string_input_get_visitor(siv), name, &local_err);
2835     string_input_visitor_cleanup(siv);
2836
2837     if (local_err) {
2838         qerror_report_err(local_err);
2839         error_free(local_err);
2840         return -1;
2841     }
2842
2843     return 0;
2844 }
2845
2846 static int object_create(QemuOpts *opts, void *opaque)
2847 {
2848     Error *err = NULL;
2849     char *type = NULL;
2850     char *id = NULL;
2851     void *dummy = NULL;
2852     OptsVisitor *ov;
2853     QDict *pdict;
2854
2855     ov = opts_visitor_new(opts);
2856     pdict = qemu_opts_to_qdict(opts, NULL);
2857
2858     visit_start_struct(opts_get_visitor(ov), &dummy, NULL, NULL, 0, &err);
2859     if (err) {
2860         goto out;
2861     }
2862
2863     qdict_del(pdict, "qom-type");
2864     visit_type_str(opts_get_visitor(ov), &type, "qom-type", &err);
2865     if (err) {
2866         goto out;
2867     }
2868
2869     qdict_del(pdict, "id");
2870     visit_type_str(opts_get_visitor(ov), &id, "id", &err);
2871     if (err) {
2872         goto out;
2873     }
2874
2875     object_add(type, id, pdict, opts_get_visitor(ov), &err);
2876     if (err) {
2877         goto out;
2878     }
2879     visit_end_struct(opts_get_visitor(ov), &err);
2880     if (err) {
2881         qmp_object_del(id, NULL);
2882     }
2883
2884 out:
2885     opts_visitor_cleanup(ov);
2886
2887     QDECREF(pdict);
2888     g_free(id);
2889     g_free(type);
2890     g_free(dummy);
2891     if (err) {
2892         qerror_report_err(err);
2893         return -1;
2894     }
2895     return 0;
2896 }
2897
2898 int main(int argc, char **argv, char **envp)
2899 {
2900     int i;
2901     int snapshot, linux_boot;
2902     const char *icount_option = NULL;
2903     const char *initrd_filename;
2904     const char *kernel_filename, *kernel_cmdline;
2905     const char *boot_order;
2906     DisplayState *ds;
2907     int cyls, heads, secs, translation;
2908     QemuOpts *hda_opts = NULL, *opts, *machine_opts;
2909     QemuOptsList *olist;
2910     int optind;
2911     const char *optarg;
2912     const char *loadvm = NULL;
2913     MachineClass *machine_class;
2914     const char *cpu_model;
2915     const char *vga_model = NULL;
2916     const char *qtest_chrdev = NULL;
2917     const char *qtest_log = NULL;
2918     const char *pid_file = NULL;
2919     const char *incoming = NULL;
2920 #ifdef CONFIG_VNC
2921     int show_vnc_port = 0;
2922 #endif
2923     bool defconfig = true;
2924     bool userconfig = true;
2925     const char *log_mask = NULL;
2926     const char *log_file = NULL;
2927     GMemVTable mem_trace = {
2928         .malloc = malloc_and_trace,
2929         .realloc = realloc_and_trace,
2930         .free = free_and_trace,
2931     };
2932     const char *trace_events = NULL;
2933     const char *trace_file = NULL;
2934     const ram_addr_t default_ram_size = (ram_addr_t)DEFAULT_RAM_SIZE *
2935                                         1024 * 1024;
2936     ram_addr_t maxram_size = default_ram_size;
2937     uint64_t ram_slots = 0;
2938
2939     atexit(qemu_run_exit_notifiers);
2940     error_set_progname(argv[0]);
2941     qemu_init_exec_dir(argv[0]);
2942
2943     g_mem_set_vtable(&mem_trace);
2944
2945     module_call_init(MODULE_INIT_QOM);
2946
2947     qemu_add_opts(&qemu_drive_opts);
2948     qemu_add_drive_opts(&qemu_legacy_drive_opts);
2949     qemu_add_drive_opts(&qemu_common_drive_opts);
2950     qemu_add_drive_opts(&qemu_drive_opts);
2951     qemu_add_opts(&qemu_chardev_opts);
2952     qemu_add_opts(&qemu_device_opts);
2953     qemu_add_opts(&qemu_netdev_opts);
2954     qemu_add_opts(&qemu_net_opts);
2955     qemu_add_opts(&qemu_rtc_opts);
2956     qemu_add_opts(&qemu_global_opts);
2957     qemu_add_opts(&qemu_mon_opts);
2958     qemu_add_opts(&qemu_trace_opts);
2959     qemu_add_opts(&qemu_option_rom_opts);
2960     qemu_add_opts(&qemu_machine_opts);
2961     qemu_add_opts(&qemu_mem_opts);
2962     qemu_add_opts(&qemu_smp_opts);
2963     qemu_add_opts(&qemu_boot_opts);
2964     qemu_add_opts(&qemu_sandbox_opts);
2965     qemu_add_opts(&qemu_add_fd_opts);
2966     qemu_add_opts(&qemu_object_opts);
2967     qemu_add_opts(&qemu_tpmdev_opts);
2968     qemu_add_opts(&qemu_realtime_opts);
2969     qemu_add_opts(&qemu_msg_opts);
2970     qemu_add_opts(&qemu_name_opts);
2971     qemu_add_opts(&qemu_numa_opts);
2972
2973     runstate_init();
2974
2975     rtc_clock = QEMU_CLOCK_HOST;
2976
2977     qemu_cache_utils_init();
2978
2979     QLIST_INIT (&vm_change_state_head);
2980     os_setup_early_signal_handling();
2981
2982     module_call_init(MODULE_INIT_MACHINE);
2983     machine_class = find_default_machine();
2984     cpu_model = NULL;
2985     ram_size = default_ram_size;
2986     snapshot = 0;
2987     cyls = heads = secs = 0;
2988     translation = BIOS_ATA_TRANSLATION_AUTO;
2989
2990     for (i = 0; i < MAX_NODES; i++) {
2991         numa_info[i].node_mem = 0;
2992         bitmap_zero(numa_info[i].node_cpu, MAX_CPUMASK_BITS);
2993     }
2994
2995     nb_numa_nodes = 0;
2996     nb_nics = 0;
2997
2998     bdrv_init_with_whitelist();
2999
3000     autostart = 1;
3001
3002     /* first pass of option parsing */
3003     optind = 1;
3004     while (optind < argc) {
3005         if (argv[optind][0] != '-') {
3006             /* disk image */
3007             optind++;
3008         } else {
3009             const QEMUOption *popt;
3010
3011             popt = lookup_opt(argc, argv, &optarg, &optind);
3012             switch (popt->index) {
3013             case QEMU_OPTION_nodefconfig:
3014                 defconfig = false;
3015                 break;
3016             case QEMU_OPTION_nouserconfig:
3017                 userconfig = false;
3018                 break;
3019             }
3020         }
3021     }
3022
3023     if (defconfig) {
3024         int ret;
3025         ret = qemu_read_default_config_files(userconfig);
3026         if (ret < 0) {
3027             exit(1);
3028         }
3029     }
3030
3031     /* second pass of option parsing */
3032     optind = 1;
3033     for(;;) {
3034         if (optind >= argc)
3035             break;
3036         if (argv[optind][0] != '-') {
3037             hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3038         } else {
3039             const QEMUOption *popt;
3040
3041             popt = lookup_opt(argc, argv, &optarg, &optind);
3042             if (!(popt->arch_mask & arch_type)) {
3043                 printf("Option %s not supported for this target\n", popt->name);
3044                 exit(1);
3045             }
3046             switch(popt->index) {
3047             case QEMU_OPTION_M:
3048                 machine_class = machine_parse(optarg);
3049                 break;
3050             case QEMU_OPTION_no_kvm_irqchip: {
3051                 olist = qemu_find_opts("machine");
3052                 qemu_opts_parse(olist, "kernel_irqchip=off", 0);
3053                 break;
3054             }
3055             case QEMU_OPTION_cpu:
3056                 /* hw initialization will check this */
3057                 cpu_model = optarg;
3058                 break;
3059             case QEMU_OPTION_hda:
3060                 {
3061                     char buf[256];
3062                     if (cyls == 0)
3063                         snprintf(buf, sizeof(buf), "%s", HD_OPTS);
3064                     else
3065                         snprintf(buf, sizeof(buf),
3066                                  "%s,cyls=%d,heads=%d,secs=%d%s",
3067                                  HD_OPTS , cyls, heads, secs,
3068                                  translation == BIOS_ATA_TRANSLATION_LBA ?
3069                                  ",trans=lba" :
3070                                  translation == BIOS_ATA_TRANSLATION_NONE ?
3071                                  ",trans=none" : "");
3072                     drive_add(IF_DEFAULT, 0, optarg, buf);
3073                     break;
3074                 }
3075             case QEMU_OPTION_hdb:
3076             case QEMU_OPTION_hdc:
3077             case QEMU_OPTION_hdd:
3078                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3079                           HD_OPTS);
3080                 break;
3081             case QEMU_OPTION_drive:
3082                 if (drive_def(optarg) == NULL) {
3083                     exit(1);
3084                 }
3085                 break;
3086             case QEMU_OPTION_set:
3087                 if (qemu_set_option(optarg) != 0)
3088                     exit(1);
3089                 break;
3090             case QEMU_OPTION_global:
3091                 if (qemu_global_option(optarg) != 0)
3092                     exit(1);
3093                 break;
3094             case QEMU_OPTION_mtdblock:
3095                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3096                 break;
3097             case QEMU_OPTION_sd:
3098                 drive_add(IF_SD, -1, optarg, SD_OPTS);
3099                 break;
3100             case QEMU_OPTION_pflash:
3101                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3102                 break;
3103             case QEMU_OPTION_snapshot:
3104                 snapshot = 1;
3105                 break;
3106             case QEMU_OPTION_hdachs:
3107                 {
3108                     const char *p;
3109                     p = optarg;
3110                     cyls = strtol(p, (char **)&p, 0);
3111                     if (cyls < 1 || cyls > 16383)
3112                         goto chs_fail;
3113                     if (*p != ',')
3114                         goto chs_fail;
3115                     p++;
3116                     heads = strtol(p, (char **)&p, 0);
3117                     if (heads < 1 || heads > 16)
3118                         goto chs_fail;
3119                     if (*p != ',')
3120                         goto chs_fail;
3121                     p++;
3122                     secs = strtol(p, (char **)&p, 0);
3123                     if (secs < 1 || secs > 63)
3124                         goto chs_fail;
3125                     if (*p == ',') {
3126                         p++;
3127                         if (!strcmp(p, "large")) {
3128                             translation = BIOS_ATA_TRANSLATION_LARGE;
3129                         } else if (!strcmp(p, "rechs")) {
3130                             translation = BIOS_ATA_TRANSLATION_RECHS;
3131                         } else if (!strcmp(p, "none")) {
3132                             translation = BIOS_ATA_TRANSLATION_NONE;
3133                         } else if (!strcmp(p, "lba")) {
3134                             translation = BIOS_ATA_TRANSLATION_LBA;
3135                         } else if (!strcmp(p, "auto")) {
3136                             translation = BIOS_ATA_TRANSLATION_AUTO;
3137                         } else {
3138                             goto chs_fail;
3139                         }
3140                     } else if (*p != '\0') {
3141                     chs_fail:
3142                         fprintf(stderr, "qemu: invalid physical CHS format\n");
3143                         exit(1);
3144                     }
3145                     if (hda_opts != NULL) {
3146                         char num[16];
3147                         snprintf(num, sizeof(num), "%d", cyls);
3148                         qemu_opt_set(hda_opts, "cyls", num);
3149                         snprintf(num, sizeof(num), "%d", heads);
3150                         qemu_opt_set(hda_opts, "heads", num);
3151                         snprintf(num, sizeof(num), "%d", secs);
3152                         qemu_opt_set(hda_opts, "secs", num);
3153                         if (translation == BIOS_ATA_TRANSLATION_LARGE) {
3154                             qemu_opt_set(hda_opts, "trans", "large");
3155                         } else if (translation == BIOS_ATA_TRANSLATION_RECHS) {
3156                             qemu_opt_set(hda_opts, "trans", "rechs");
3157                         } else if (translation == BIOS_ATA_TRANSLATION_LBA) {
3158                             qemu_opt_set(hda_opts, "trans", "lba");
3159                         } else if (translation == BIOS_ATA_TRANSLATION_NONE) {
3160                             qemu_opt_set(hda_opts, "trans", "none");
3161                         }
3162                     }
3163                 }
3164                 break;
3165             case QEMU_OPTION_numa:
3166                 opts = qemu_opts_parse(qemu_find_opts("numa"), optarg, 1);
3167                 if (!opts) {
3168                     exit(1);
3169                 }
3170                 break;
3171             case QEMU_OPTION_display:
3172                 display_type = select_display(optarg);
3173                 break;
3174             case QEMU_OPTION_nographic:
3175                 display_type = DT_NOGRAPHIC;
3176                 break;
3177             case QEMU_OPTION_curses:
3178 #ifdef CONFIG_CURSES
3179                 display_type = DT_CURSES;
3180 #else
3181                 fprintf(stderr, "Curses support is disabled\n");
3182                 exit(1);
3183 #endif
3184                 break;
3185             case QEMU_OPTION_portrait:
3186                 graphic_rotate = 90;
3187                 break;
3188             case QEMU_OPTION_rotate:
3189                 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3190                 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3191                     graphic_rotate != 180 && graphic_rotate != 270) {
3192                     fprintf(stderr,
3193                         "qemu: only 90, 180, 270 deg rotation is available\n");
3194                     exit(1);
3195                 }
3196                 break;
3197             case QEMU_OPTION_kernel:
3198                 qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg);
3199                 break;
3200             case QEMU_OPTION_initrd:
3201                 qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg);
3202                 break;
3203             case QEMU_OPTION_append:
3204                 qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg);
3205                 break;
3206             case QEMU_OPTION_dtb:
3207                 qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg);
3208                 break;
3209             case QEMU_OPTION_cdrom:
3210                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3211                 break;
3212             case QEMU_OPTION_boot:
3213                 opts = qemu_opts_parse(qemu_find_opts("boot-opts"), optarg, 1);
3214                 if (!opts) {
3215                     exit(1);
3216                 }
3217                 break;
3218             case QEMU_OPTION_fda:
3219             case QEMU_OPTION_fdb:
3220                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3221                           optarg, FD_OPTS);
3222                 break;
3223             case QEMU_OPTION_no_fd_bootchk:
3224                 fd_bootchk = 0;
3225                 break;
3226             case QEMU_OPTION_netdev:
3227                 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3228                     exit(1);
3229                 }
3230                 break;
3231             case QEMU_OPTION_net:
3232                 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3233                     exit(1);
3234                 }
3235                 break;
3236 #ifdef CONFIG_LIBISCSI
3237             case QEMU_OPTION_iscsi:
3238                 opts = qemu_opts_parse(qemu_find_opts("iscsi"), optarg, 0);
3239                 if (!opts) {
3240                     exit(1);
3241                 }
3242                 break;
3243 #endif
3244 #ifdef CONFIG_SLIRP
3245             case QEMU_OPTION_tftp:
3246                 legacy_tftp_prefix = optarg;
3247                 break;
3248             case QEMU_OPTION_bootp:
3249                 legacy_bootp_filename = optarg;
3250                 break;
3251             case QEMU_OPTION_redir:
3252                 if (net_slirp_redir(optarg) < 0)
3253                     exit(1);
3254                 break;
3255 #endif
3256             case QEMU_OPTION_bt:
3257                 add_device_config(DEV_BT, optarg);
3258                 break;
3259             case QEMU_OPTION_audio_help:
3260                 AUD_help ();
3261                 exit (0);
3262                 break;
3263             case QEMU_OPTION_soundhw:
3264                 select_soundhw (optarg);
3265                 break;
3266             case QEMU_OPTION_h:
3267                 help(0);
3268                 break;
3269             case QEMU_OPTION_version:
3270                 version();
3271                 exit(0);
3272                 break;
3273             case QEMU_OPTION_m: {
3274                 uint64_t sz;
3275                 const char *mem_str;
3276                 const char *maxmem_str, *slots_str;
3277
3278                 opts = qemu_opts_parse(qemu_find_opts("memory"),
3279                                        optarg, 1);
3280                 if (!opts) {
3281                     exit(EXIT_FAILURE);
3282                 }
3283
3284                 mem_str = qemu_opt_get(opts, "size");
3285                 if (!mem_str) {
3286                     error_report("invalid -m option, missing 'size' option");
3287                     exit(EXIT_FAILURE);
3288                 }
3289                 if (!*mem_str) {
3290                     error_report("missing 'size' option value");
3291                     exit(EXIT_FAILURE);
3292                 }
3293
3294                 sz = qemu_opt_get_size(opts, "size", ram_size);
3295
3296                 /* Fix up legacy suffix-less format */
3297                 if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
3298                     uint64_t overflow_check = sz;
3299
3300                     sz <<= 20;
3301                     if ((sz >> 20) != overflow_check) {
3302                         error_report("too large 'size' option value");
3303                         exit(EXIT_FAILURE);
3304                     }
3305                 }
3306
3307                 /* backward compatibility behaviour for case "-m 0" */
3308                 if (sz == 0) {
3309                     sz = default_ram_size;
3310                 }
3311
3312                 sz = QEMU_ALIGN_UP(sz, 8192);
3313                 ram_size = sz;
3314                 if (ram_size != sz) {
3315                     error_report("ram size too large");
3316                     exit(EXIT_FAILURE);
3317                 }
3318
3319                 maxmem_str = qemu_opt_get(opts, "maxmem");
3320                 slots_str = qemu_opt_get(opts, "slots");
3321                 if (maxmem_str && slots_str) {
3322                     uint64_t slots;
3323
3324                     sz = qemu_opt_get_size(opts, "maxmem", 0);
3325                     if (sz < ram_size) {
3326                         fprintf(stderr, "qemu: invalid -m option value: maxmem "
3327                                 "(%" PRIu64 ") <= initial memory ("
3328                                 RAM_ADDR_FMT ")\n", sz, ram_size);
3329                         exit(EXIT_FAILURE);
3330                     }
3331
3332                     slots = qemu_opt_get_number(opts, "slots", 0);
3333                     if ((sz > ram_size) && !slots) {
3334                         fprintf(stderr, "qemu: invalid -m option value: maxmem "
3335                                 "(%" PRIu64 ") more than initial memory ("
3336                                 RAM_ADDR_FMT ") but no hotplug slots where "
3337                                 "specified\n", sz, ram_size);
3338                         exit(EXIT_FAILURE);
3339                     }
3340
3341                     if ((sz <= ram_size) && slots) {
3342                         fprintf(stderr, "qemu: invalid -m option value:  %"
3343                                 PRIu64 " hotplug slots where specified but "
3344                                 "maxmem (%" PRIu64 ") <= initial memory ("
3345                                 RAM_ADDR_FMT ")\n", slots, sz, ram_size);
3346                         exit(EXIT_FAILURE);
3347                     }
3348                     maxram_size = sz;
3349                     ram_slots = slots;
3350                 } else if ((!maxmem_str && slots_str) ||
3351                            (maxmem_str && !slots_str)) {
3352                     fprintf(stderr, "qemu: invalid -m option value: missing "
3353                             "'%s' option\n", slots_str ? "maxmem" : "slots");
3354                     exit(EXIT_FAILURE);
3355                 }
3356                 break;
3357             }
3358 #ifdef CONFIG_TPM
3359             case QEMU_OPTION_tpmdev:
3360                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3361                     exit(1);
3362                 }
3363                 break;
3364 #endif
3365             case QEMU_OPTION_mempath:
3366                 mem_path = optarg;
3367                 break;
3368             case QEMU_OPTION_mem_prealloc:
3369                 mem_prealloc = 1;
3370                 break;
3371             case QEMU_OPTION_d:
3372                 log_mask = optarg;
3373                 break;
3374             case QEMU_OPTION_D:
3375                 log_file = optarg;
3376                 break;
3377             case QEMU_OPTION_s:
3378                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3379                 break;
3380             case QEMU_OPTION_gdb:
3381                 add_device_config(DEV_GDB, optarg);
3382                 break;
3383             case QEMU_OPTION_L:
3384                 if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3385                     data_dir[data_dir_idx++] = optarg;
3386                 }
3387                 break;
3388             case QEMU_OPTION_bios:
3389                 qemu_opts_set(qemu_find_opts("machine"), 0, "firmware", optarg);
3390                 break;
3391             case QEMU_OPTION_singlestep:
3392                 singlestep = 1;
3393                 break;
3394             case QEMU_OPTION_S:
3395                 autostart = 0;
3396                 break;
3397             case QEMU_OPTION_k:
3398                 keyboard_layout = optarg;
3399                 break;
3400             case QEMU_OPTION_localtime:
3401                 rtc_utc = 0;
3402                 break;
3403             case QEMU_OPTION_vga:
3404                 vga_model = optarg;
3405                 default_vga = 0;
3406                 break;
3407             case QEMU_OPTION_g:
3408                 {
3409                     const char *p;
3410                     int w, h, depth;
3411                     p = optarg;
3412                     w = strtol(p, (char **)&p, 10);
3413                     if (w <= 0) {
3414                     graphic_error:
3415                         fprintf(stderr, "qemu: invalid resolution or depth\n");
3416                         exit(1);
3417                     }
3418                     if (*p != 'x')
3419                         goto graphic_error;
3420                     p++;
3421                     h = strtol(p, (char **)&p, 10);
3422                     if (h <= 0)
3423                         goto graphic_error;
3424                     if (*p == 'x') {
3425                         p++;
3426                         depth = strtol(p, (char **)&p, 10);
3427                         if (depth != 8 && depth != 15 && depth != 16 &&
3428                             depth != 24 && depth != 32)
3429                             goto graphic_error;
3430                     } else if (*p == '\0') {
3431                         depth = graphic_depth;
3432                     } else {
3433                         goto graphic_error;
3434                     }
3435
3436                     graphic_width = w;
3437                     graphic_height = h;
3438                     graphic_depth = depth;
3439                 }
3440                 break;
3441             case QEMU_OPTION_echr:
3442                 {
3443                     char *r;
3444                     term_escape_char = strtol(optarg, &r, 0);
3445                     if (r == optarg)
3446                         printf("Bad argument to echr\n");
3447                     break;
3448                 }
3449             case QEMU_OPTION_monitor:
3450                 default_monitor = 0;
3451                 if (strncmp(optarg, "none", 4)) {
3452                     monitor_parse(optarg, "readline");
3453                 }
3454                 break;
3455             case QEMU_OPTION_qmp:
3456                 monitor_parse(optarg, "control");
3457                 default_monitor = 0;
3458                 break;
3459             case QEMU_OPTION_mon:
3460                 opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
3461                 if (!opts) {
3462                     exit(1);
3463                 }
3464                 default_monitor = 0;
3465                 break;
3466             case QEMU_OPTION_chardev:
3467                 opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
3468                 if (!opts) {
3469                     exit(1);
3470                 }
3471                 break;
3472             case QEMU_OPTION_fsdev:
3473                 olist = qemu_find_opts("fsdev");
3474                 if (!olist) {
3475                     fprintf(stderr, "fsdev is not supported by this qemu build.\n");
3476                     exit(1);
3477                 }
3478                 opts = qemu_opts_parse(olist, optarg, 1);
3479                 if (!opts) {
3480                     exit(1);
3481                 }
3482                 break;
3483             case QEMU_OPTION_virtfs: {
3484                 QemuOpts *fsdev;
3485                 QemuOpts *device;
3486                 const char *writeout, *sock_fd, *socket;
3487
3488                 olist = qemu_find_opts("virtfs");
3489                 if (!olist) {
3490                     fprintf(stderr, "virtfs is not supported by this qemu build.\n");
3491                     exit(1);
3492                 }
3493                 opts = qemu_opts_parse(olist, optarg, 1);
3494                 if (!opts) {
3495                     exit(1);
3496                 }
3497
3498                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3499                     qemu_opt_get(opts, "mount_tag") == NULL) {
3500                     fprintf(stderr, "Usage: -virtfs fsdriver,mount_tag=tag.\n");
3501                     exit(1);
3502                 }
3503                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3504                                          qemu_opt_get(opts, "mount_tag"),
3505                                          1, NULL);
3506                 if (!fsdev) {
3507                     fprintf(stderr, "duplicate fsdev id: %s\n",
3508                             qemu_opt_get(opts, "mount_tag"));
3509                     exit(1);
3510                 }
3511
3512                 writeout = qemu_opt_get(opts, "writeout");
3513                 if (writeout) {
3514 #ifdef CONFIG_SYNC_FILE_RANGE
3515                     qemu_opt_set(fsdev, "writeout", writeout);
3516 #else
3517                     fprintf(stderr, "writeout=immediate not supported on "
3518                             "this platform\n");
3519                     exit(1);
3520 #endif
3521                 }
3522                 qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));
3523                 qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
3524                 qemu_opt_set(fsdev, "security_model",
3525                              qemu_opt_get(opts, "security_model"));
3526                 socket = qemu_opt_get(opts, "socket");
3527                 if (socket) {
3528                     qemu_opt_set(fsdev, "socket", socket);
3529                 }
3530                 sock_fd = qemu_opt_get(opts, "sock_fd");
3531                 if (sock_fd) {
3532                     qemu_opt_set(fsdev, "sock_fd", sock_fd);
3533                 }
3534
3535                 qemu_opt_set_bool(fsdev, "readonly",
3536                                 qemu_opt_get_bool(opts, "readonly", 0));
3537                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3538                                           &error_abort);
3539                 qemu_opt_set(device, "driver", "virtio-9p-pci");
3540                 qemu_opt_set(device, "fsdev",
3541                              qemu_opt_get(opts, "mount_tag"));
3542                 qemu_opt_set(device, "mount_tag",
3543                              qemu_opt_get(opts, "mount_tag"));
3544                 break;
3545             }
3546             case QEMU_OPTION_virtfs_synth: {
3547                 QemuOpts *fsdev;
3548                 QemuOpts *device;
3549
3550                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3551                                          1, NULL);
3552                 if (!fsdev) {
3553                     fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");
3554                     exit(1);
3555                 }
3556                 qemu_opt_set(fsdev, "fsdriver", "synth");
3557
3558                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3559                                           &error_abort);
3560                 qemu_opt_set(device, "driver", "virtio-9p-pci");
3561                 qemu_opt_set(device, "fsdev", "v_synth");
3562                 qemu_opt_set(device, "mount_tag", "v_synth");
3563                 break;
3564             }
3565             case QEMU_OPTION_serial:
3566                 add_device_config(DEV_SERIAL, optarg);
3567                 default_serial = 0;
3568                 if (strncmp(optarg, "mon:", 4) == 0) {
3569                     default_monitor = 0;
3570                 }
3571                 break;
3572             case QEMU_OPTION_watchdog:
3573                 if (watchdog) {
3574                     fprintf(stderr,
3575                             "qemu: only one watchdog option may be given\n");
3576                     return 1;
3577                 }
3578                 watchdog = optarg;
3579                 break;
3580             case QEMU_OPTION_watchdog_action:
3581                 if (select_watchdog_action(optarg) == -1) {
3582                     fprintf(stderr, "Unknown -watchdog-action parameter\n");
3583                     exit(1);
3584                 }
3585                 break;
3586             case QEMU_OPTION_virtiocon:
3587                 add_device_config(DEV_VIRTCON, optarg);
3588                 default_virtcon = 0;
3589                 if (strncmp(optarg, "mon:", 4) == 0) {
3590                     default_monitor = 0;
3591                 }
3592                 break;
3593             case QEMU_OPTION_parallel:
3594                 add_device_config(DEV_PARALLEL, optarg);
3595                 default_parallel = 0;
3596                 if (strncmp(optarg, "mon:", 4) == 0) {
3597                     default_monitor = 0;
3598                 }
3599                 break;
3600             case QEMU_OPTION_debugcon:
3601                 add_device_config(DEV_DEBUGCON, optarg);
3602                 break;
3603             case QEMU_OPTION_loadvm:
3604                 loadvm = optarg;
3605                 break;
3606             case QEMU_OPTION_full_screen:
3607                 full_screen = 1;
3608                 break;
3609             case QEMU_OPTION_no_frame:
3610                 no_frame = 1;
3611                 break;
3612             case QEMU_OPTION_alt_grab:
3613                 alt_grab = 1;
3614                 break;
3615             case QEMU_OPTION_ctrl_grab:
3616                 ctrl_grab = 1;
3617                 break;
3618             case QEMU_OPTION_no_quit:
3619                 no_quit = 1;
3620                 break;
3621             case QEMU_OPTION_sdl:
3622 #ifdef CONFIG_SDL
3623                 display_type = DT_SDL;
3624                 break;
3625 #else
3626                 fprintf(stderr, "SDL support is disabled\n");
3627                 exit(1);
3628 #endif
3629             case QEMU_OPTION_pidfile:
3630                 pid_file = optarg;
3631                 break;
3632             case QEMU_OPTION_win2k_hack:
3633                 win2k_install_hack = 1;
3634                 break;
3635             case QEMU_OPTION_rtc_td_hack: {
3636                 static GlobalProperty slew_lost_ticks[] = {
3637                     {
3638                         .driver   = "mc146818rtc",
3639                         .property = "lost_tick_policy",
3640                         .value    = "slew",
3641                     },
3642                     { /* end of list */ }
3643                 };
3644
3645                 qdev_prop_register_global_list(slew_lost_ticks);
3646                 break;
3647             }
3648             case QEMU_OPTION_acpitable:
3649                 opts = qemu_opts_parse(qemu_find_opts("acpi"), optarg, 1);
3650                 if (!opts) {
3651                     exit(1);
3652                 }
3653                 do_acpitable_option(opts);
3654                 break;
3655             case QEMU_OPTION_smbios:
3656                 opts = qemu_opts_parse(qemu_find_opts("smbios"), optarg, 0);
3657                 if (!opts) {
3658                     exit(1);
3659                 }
3660                 do_smbios_option(opts);
3661                 break;
3662             case QEMU_OPTION_enable_kvm:
3663                 olist = qemu_find_opts("machine");
3664                 qemu_opts_parse(olist, "accel=kvm", 0);
3665                 break;
3666             case QEMU_OPTION_machine:
3667                 olist = qemu_find_opts("machine");
3668                 opts = qemu_opts_parse(olist, optarg, 1);
3669                 if (!opts) {
3670                     exit(1);
3671                 }
3672                 optarg = qemu_opt_get(opts, "type");
3673                 if (optarg) {
3674                     machine_class = machine_parse(optarg);
3675                 }
3676                 break;
3677              case QEMU_OPTION_no_kvm:
3678                 olist = qemu_find_opts("machine");
3679                 qemu_opts_parse(olist, "accel=tcg", 0);
3680                 break;
3681             case QEMU_OPTION_no_kvm_pit: {
3682                 fprintf(stderr, "Warning: KVM PIT can no longer be disabled "
3683                                 "separately.\n");
3684                 break;
3685             }
3686             case QEMU_OPTION_no_kvm_pit_reinjection: {
3687                 static GlobalProperty kvm_pit_lost_tick_policy[] = {
3688                     {
3689                         .driver   = "kvm-pit",
3690                         .property = "lost_tick_policy",
3691                         .value    = "discard",
3692                     },
3693                     { /* end of list */ }
3694                 };
3695
3696                 fprintf(stderr, "Warning: option deprecated, use "
3697                         "lost_tick_policy property of kvm-pit instead.\n");
3698                 qdev_prop_register_global_list(kvm_pit_lost_tick_policy);
3699                 break;
3700             }
3701             case QEMU_OPTION_usb:
3702                 olist = qemu_find_opts("machine");
3703                 qemu_opts_parse(olist, "usb=on", 0);
3704                 break;
3705             case QEMU_OPTION_usbdevice:
3706                 olist = qemu_find_opts("machine");
3707                 qemu_opts_parse(olist, "usb=on", 0);
3708                 add_device_config(DEV_USB, optarg);
3709                 break;
3710             case QEMU_OPTION_device:
3711                 if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
3712                     exit(1);
3713                 }
3714                 break;
3715             case QEMU_OPTION_smp:
3716                 if (!qemu_opts_parse(qemu_find_opts("smp-opts"), optarg, 1)) {
3717                     exit(1);
3718                 }
3719                 break;
3720             case QEMU_OPTION_vnc:
3721 #ifdef CONFIG_VNC
3722                 display_remote++;
3723                 vnc_display = optarg;
3724 #else
3725                 fprintf(stderr, "VNC support is disabled\n");
3726                 exit(1);
3727 #endif
3728                 break;
3729             case QEMU_OPTION_no_acpi:
3730                 acpi_enabled = 0;
3731                 break;
3732             case QEMU_OPTION_no_hpet:
3733                 no_hpet = 1;
3734                 break;
3735             case QEMU_OPTION_balloon:
3736                 if (balloon_parse(optarg) < 0) {
3737                     fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3738                     exit(1);
3739                 }
3740                 break;
3741             case QEMU_OPTION_no_reboot:
3742                 no_reboot = 1;
3743                 break;
3744             case QEMU_OPTION_no_shutdown:
3745                 no_shutdown = 1;
3746                 break;
3747             case QEMU_OPTION_show_cursor:
3748                 cursor_hide = 0;
3749                 break;
3750             case QEMU_OPTION_uuid:
3751                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3752                     fprintf(stderr, "Fail to parse UUID string."
3753                             " Wrong format.\n");
3754                     exit(1);
3755                 }
3756                 qemu_uuid_set = true;
3757                 break;
3758             case QEMU_OPTION_option_rom:
3759                 if (nb_option_roms >= MAX_OPTION_ROMS) {
3760                     fprintf(stderr, "Too many option ROMs\n");
3761                     exit(1);
3762                 }
3763                 opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
3764                 if (!opts) {
3765                     exit(1);
3766                 }
3767                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3768                 option_rom[nb_option_roms].bootindex =
3769                     qemu_opt_get_number(opts, "bootindex", -1);
3770                 if (!option_rom[nb_option_roms].name) {
3771                     fprintf(stderr, "Option ROM file is not specified\n");
3772                     exit(1);
3773                 }
3774                 nb_option_roms++;
3775                 break;
3776             case QEMU_OPTION_semihosting:
3777                 semihosting_enabled = 1;
3778                 break;
3779             case QEMU_OPTION_tdf:
3780                 fprintf(stderr, "Warning: user space PIT time drift fix "
3781                                 "is no longer supported.\n");
3782                 break;
3783             case QEMU_OPTION_name:
3784                 opts = qemu_opts_parse(qemu_find_opts("name"), optarg, 1);
3785                 if (!opts) {
3786                     exit(1);
3787                 }
3788                 break;
3789             case QEMU_OPTION_prom_env:
3790                 if (nb_prom_envs >= MAX_PROM_ENVS) {
3791                     fprintf(stderr, "Too many prom variables\n");
3792                     exit(1);
3793                 }
3794                 prom_envs[nb_prom_envs] = optarg;
3795                 nb_prom_envs++;
3796                 break;
3797             case QEMU_OPTION_old_param:
3798                 old_param = 1;
3799                 break;
3800             case QEMU_OPTION_clock:
3801                 /* Clock options no longer exist.  Keep this option for
3802                  * backward compatibility.
3803                  */
3804                 break;
3805             case QEMU_OPTION_startdate:
3806                 configure_rtc_date_offset(optarg, 1);
3807                 break;
3808             case QEMU_OPTION_rtc:
3809                 opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
3810                 if (!opts) {
3811                     exit(1);
3812                 }
3813                 configure_rtc(opts);
3814                 break;
3815             case QEMU_OPTION_tb_size:
3816                 tcg_tb_size = strtol(optarg, NULL, 0);
3817                 if (tcg_tb_size < 0) {
3818                     tcg_tb_size = 0;
3819                 }
3820                 break;
3821             case QEMU_OPTION_icount:
3822                 icount_option = optarg;
3823                 break;
3824             case QEMU_OPTION_incoming:
3825                 incoming = optarg;
3826                 runstate_set(RUN_STATE_INMIGRATE);
3827                 break;
3828             case QEMU_OPTION_nodefaults:
3829                 has_defaults = 0;
3830                 break;
3831             case QEMU_OPTION_xen_domid:
3832                 if (!(xen_available())) {
3833                     printf("Option %s not supported for this target\n", popt->name);
3834                     exit(1);
3835                 }
3836                 xen_domid = atoi(optarg);
3837                 break;
3838             case QEMU_OPTION_xen_create:
3839                 if (!(xen_available())) {
3840                     printf("Option %s not supported for this target\n", popt->name);
3841                     exit(1);
3842                 }
3843                 xen_mode = XEN_CREATE;
3844                 break;
3845             case QEMU_OPTION_xen_attach:
3846                 if (!(xen_available())) {
3847                     printf("Option %s not supported for this target\n", popt->name);
3848                     exit(1);
3849                 }
3850                 xen_mode = XEN_ATTACH;
3851                 break;
3852             case QEMU_OPTION_trace:
3853             {
3854                 opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3855                 if (!opts) {
3856                     exit(1);
3857                 }
3858                 trace_events = qemu_opt_get(opts, "events");
3859                 trace_file = qemu_opt_get(opts, "file");
3860                 break;
3861             }
3862             case QEMU_OPTION_readconfig:
3863                 {
3864                     int ret = qemu_read_config_file(optarg);
3865                     if (ret < 0) {
3866                         fprintf(stderr, "read config %s: %s\n", optarg,
3867                             strerror(-ret));
3868                         exit(1);
3869                     }
3870                     break;
3871                 }
3872             case QEMU_OPTION_spice:
3873                 olist = qemu_find_opts("spice");
3874                 if (!olist) {
3875                     fprintf(stderr, "spice is not supported by this qemu build.\n");
3876                     exit(1);
3877                 }
3878                 opts = qemu_opts_parse(olist, optarg, 0);
3879                 if (!opts) {
3880                     exit(1);
3881                 }
3882                 display_remote++;
3883                 break;
3884             case QEMU_OPTION_writeconfig:
3885                 {
3886                     FILE *fp;
3887                     if (strcmp(optarg, "-") == 0) {
3888                         fp = stdout;
3889                     } else {
3890                         fp = fopen(optarg, "w");
3891                         if (fp == NULL) {
3892                             fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3893                             exit(1);
3894                         }
3895                     }
3896                     qemu_config_write(fp);
3897                     if (fp != stdout) {
3898                         fclose(fp);
3899                     }
3900                     break;
3901                 }
3902             case QEMU_OPTION_qtest:
3903                 qtest_chrdev = optarg;
3904                 break;
3905             case QEMU_OPTION_qtest_log:
3906                 qtest_log = optarg;
3907                 break;
3908             case QEMU_OPTION_sandbox:
3909                 opts = qemu_opts_parse(qemu_find_opts("sandbox"), optarg, 1);
3910                 if (!opts) {
3911                     exit(1);
3912                 }
3913                 break;
3914             case QEMU_OPTION_add_fd:
3915 #ifndef _WIN32
3916                 opts = qemu_opts_parse(qemu_find_opts("add-fd"), optarg, 0);
3917                 if (!opts) {
3918                     exit(1);
3919                 }
3920 #else
3921                 error_report("File descriptor passing is disabled on this "
3922                              "platform");
3923                 exit(1);
3924 #endif
3925                 break;
3926             case QEMU_OPTION_object:
3927                 opts = qemu_opts_parse(qemu_find_opts("object"), optarg, 1);
3928                 if (!opts) {
3929                     exit(1);
3930                 }
3931                 break;
3932             case QEMU_OPTION_realtime:
3933                 opts = qemu_opts_parse(qemu_find_opts("realtime"), optarg, 0);
3934                 if (!opts) {
3935                     exit(1);
3936                 }
3937                 configure_realtime(opts);
3938                 break;
3939             case QEMU_OPTION_msg:
3940                 opts = qemu_opts_parse(qemu_find_opts("msg"), optarg, 0);
3941                 if (!opts) {
3942                     exit(1);
3943                 }
3944                 configure_msg(opts);
3945                 break;
3946             default:
3947                 os_parse_cmd_args(popt->index, optarg);
3948             }
3949         }
3950     }
3951     loc_set_none();
3952
3953     os_daemonize();
3954
3955     if (qemu_init_main_loop()) {
3956         fprintf(stderr, "qemu_init_main_loop failed\n");
3957         exit(1);
3958     }
3959
3960     if (qemu_opts_foreach(qemu_find_opts("sandbox"), parse_sandbox, NULL, 0)) {
3961         exit(1);
3962     }
3963
3964     if (qemu_opts_foreach(qemu_find_opts("name"), parse_name, NULL, 1)) {
3965         exit(1);
3966     }
3967
3968 #ifndef _WIN32
3969     if (qemu_opts_foreach(qemu_find_opts("add-fd"), parse_add_fd, NULL, 1)) {
3970         exit(1);
3971     }
3972
3973     if (qemu_opts_foreach(qemu_find_opts("add-fd"), cleanup_add_fd, NULL, 1)) {
3974         exit(1);
3975     }
3976 #endif
3977
3978     if (machine_class == NULL) {
3979         fprintf(stderr, "No machine specified, and there is no default.\n"
3980                 "Use -machine help to list supported machines!\n");
3981         exit(1);
3982     }
3983
3984     cpu_exec_init_all();
3985
3986     current_machine = MACHINE(object_new(object_class_get_name(
3987                           OBJECT_CLASS(machine_class))));
3988     object_property_add_child(object_get_root(), "machine",
3989                               OBJECT(current_machine), &error_abort);
3990
3991     if (machine_class->hw_version) {
3992         qemu_set_version(machine_class->hw_version);
3993     }
3994
3995     if (qemu_opts_foreach(qemu_find_opts("object"),
3996                           object_create, NULL, 0) != 0) {
3997         exit(1);
3998     }
3999
4000     /* Init CPU def lists, based on config
4001      * - Must be called after all the qemu_read_config_file() calls
4002      * - Must be called before list_cpus()
4003      * - Must be called before machine->init()
4004      */
4005     cpudef_init();
4006
4007     if (cpu_model && is_help_option(cpu_model)) {
4008         list_cpus(stdout, &fprintf, cpu_model);
4009         exit(0);
4010     }
4011
4012     /* Open the logfile at this point, if necessary. We can't open the logfile
4013      * when encountering either of the logging options (-d or -D) because the
4014      * other one may be encountered later on the command line, changing the
4015      * location or level of logging.
4016      */
4017     if (log_mask) {
4018         int mask;
4019         if (log_file) {
4020             qemu_set_log_filename(log_file);
4021         }
4022
4023         mask = qemu_str_to_log_mask(log_mask);
4024         if (!mask) {
4025             qemu_print_log_usage(stdout);
4026             exit(1);
4027         }
4028         qemu_set_log(mask);
4029     }
4030
4031     if (!is_daemonized()) {
4032         if (!trace_init_backends(trace_events, trace_file)) {
4033             exit(1);
4034         }
4035     }
4036
4037     /* If no data_dir is specified then try to find it relative to the
4038        executable path.  */
4039     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4040         data_dir[data_dir_idx] = os_find_datadir();
4041         if (data_dir[data_dir_idx] != NULL) {
4042             data_dir_idx++;
4043         }
4044     }
4045     /* If all else fails use the install path specified when building. */
4046     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4047         data_dir[data_dir_idx++] = CONFIG_QEMU_DATADIR;
4048     }
4049
4050     smp_parse(qemu_opts_find(qemu_find_opts("smp-opts"), NULL));
4051
4052     machine_class->max_cpus = machine_class->max_cpus ?: 1; /* Default to UP */
4053     if (smp_cpus > machine_class->max_cpus) {
4054         fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4055                 "supported by machine `%s' (%d)\n", smp_cpus,
4056                 machine_class->name, machine_class->max_cpus);
4057         exit(1);
4058     }
4059
4060     /*
4061      * Get the default machine options from the machine if it is not already
4062      * specified either by the configuration file or by the command line.
4063      */
4064     if (machine_class->default_machine_opts) {
4065         qemu_opts_set_defaults(qemu_find_opts("machine"),
4066                                machine_class->default_machine_opts, 0);
4067     }
4068
4069     qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
4070     qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
4071
4072     if (!vga_model && !default_vga) {
4073         vga_interface_type = VGA_DEVICE;
4074     }
4075     if (!has_defaults || machine_class->no_serial) {
4076         default_serial = 0;
4077     }
4078     if (!has_defaults || machine_class->no_parallel) {
4079         default_parallel = 0;
4080     }
4081     if (!has_defaults || !machine_class->use_virtcon) {
4082         default_virtcon = 0;
4083     }
4084     if (!has_defaults || !machine_class->use_sclp) {
4085         default_sclp = 0;
4086     }
4087     if (!has_defaults || machine_class->no_floppy) {
4088         default_floppy = 0;
4089     }
4090     if (!has_defaults || machine_class->no_cdrom) {
4091         default_cdrom = 0;
4092     }
4093     if (!has_defaults || machine_class->no_sdcard) {
4094         default_sdcard = 0;
4095     }
4096     if (!has_defaults) {
4097         default_monitor = 0;
4098         default_net = 0;
4099         default_vga = 0;
4100     }
4101
4102     if (is_daemonized()) {
4103         /* According to documentation and historically, -nographic redirects
4104          * serial port, parallel port and monitor to stdio, which does not work
4105          * with -daemonize.  We can redirect these to null instead, but since
4106          * -nographic is legacy, let's just error out.
4107          * We disallow -nographic only if all other ports are not redirected
4108          * explicitly, to not break existing legacy setups which uses
4109          * -nographic _and_ redirects all ports explicitly - this is valid
4110          * usage, -nographic is just a no-op in this case.
4111          */
4112         if (display_type == DT_NOGRAPHIC
4113             && (default_parallel || default_serial
4114                 || default_monitor || default_virtcon)) {
4115             fprintf(stderr, "-nographic can not be used with -daemonize\n");
4116             exit(1);
4117         }
4118 #ifdef CONFIG_CURSES
4119         if (display_type == DT_CURSES) {
4120             fprintf(stderr, "curses display can not be used with -daemonize\n");
4121             exit(1);
4122         }
4123 #endif
4124     }
4125
4126     if (display_type == DT_NOGRAPHIC) {
4127         if (default_parallel)
4128             add_device_config(DEV_PARALLEL, "null");
4129         if (default_serial && default_monitor) {
4130             add_device_config(DEV_SERIAL, "mon:stdio");
4131         } else if (default_virtcon && default_monitor) {
4132             add_device_config(DEV_VIRTCON, "mon:stdio");
4133         } else if (default_sclp && default_monitor) {
4134             add_device_config(DEV_SCLP, "mon:stdio");
4135         } else {
4136             if (default_serial)
4137                 add_device_config(DEV_SERIAL, "stdio");
4138             if (default_virtcon)
4139                 add_device_config(DEV_VIRTCON, "stdio");
4140             if (default_sclp) {
4141                 add_device_config(DEV_SCLP, "stdio");
4142             }
4143             if (default_monitor)
4144                 monitor_parse("stdio", "readline");
4145         }
4146     } else {
4147         if (default_serial)
4148             add_device_config(DEV_SERIAL, "vc:80Cx24C");
4149         if (default_parallel)
4150             add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4151         if (default_monitor)
4152             monitor_parse("vc:80Cx24C", "readline");
4153         if (default_virtcon)
4154             add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4155         if (default_sclp) {
4156             add_device_config(DEV_SCLP, "vc:80Cx24C");
4157         }
4158     }
4159
4160     if (display_type == DT_DEFAULT && !display_remote) {
4161 #if defined(CONFIG_GTK)
4162         display_type = DT_GTK;
4163 #elif defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4164         display_type = DT_SDL;
4165 #elif defined(CONFIG_VNC)
4166         vnc_display = "localhost:0,to=99";
4167         show_vnc_port = 1;
4168 #else
4169         display_type = DT_NONE;
4170 #endif
4171     }
4172
4173     if ((no_frame || alt_grab || ctrl_grab) && display_type != DT_SDL) {
4174         fprintf(stderr, "-no-frame, -alt-grab and -ctrl-grab are only valid "
4175                         "for SDL, ignoring option\n");
4176     }
4177     if (no_quit && (display_type != DT_GTK && display_type != DT_SDL)) {
4178         fprintf(stderr, "-no-quit is only valid for GTK and SDL, "
4179                         "ignoring option\n");
4180     }
4181
4182 #if defined(CONFIG_GTK)
4183     if (display_type == DT_GTK) {
4184         early_gtk_display_init();
4185     }
4186 #endif
4187
4188     socket_init();
4189
4190     if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
4191         exit(1);
4192 #ifdef CONFIG_VIRTFS
4193     if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
4194         exit(1);
4195     }
4196 #endif
4197
4198     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4199         os_pidfile_error();
4200         exit(1);
4201     }
4202
4203     /* store value for the future use */
4204     qemu_opt_set_number(qemu_find_opts_singleton("memory"), "size", ram_size);
4205
4206     if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0)
4207         != 0) {
4208         exit(0);
4209     }
4210
4211     machine_opts = qemu_get_machine_opts();
4212     if (qemu_opt_foreach(machine_opts, object_set_property, current_machine,
4213                          1) < 0) {
4214         object_unref(OBJECT(current_machine));
4215         exit(1);
4216     }
4217
4218     configure_accelerator(machine_class);
4219
4220     if (qtest_chrdev) {
4221         Error *local_err = NULL;
4222         qtest_init(qtest_chrdev, qtest_log, &local_err);
4223         if (local_err) {
4224             error_report("%s", error_get_pretty(local_err));
4225             error_free(local_err);
4226             exit(1);
4227         }
4228     }
4229
4230     machine_opts = qemu_get_machine_opts();
4231     kernel_filename = qemu_opt_get(machine_opts, "kernel");
4232     initrd_filename = qemu_opt_get(machine_opts, "initrd");
4233     kernel_cmdline = qemu_opt_get(machine_opts, "append");
4234     bios_name = qemu_opt_get(machine_opts, "firmware");
4235
4236     boot_order = machine_class->default_boot_order;
4237     opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4238     if (opts) {
4239         char *normal_boot_order;
4240         const char *order, *once;
4241
4242         order = qemu_opt_get(opts, "order");
4243         if (order) {
4244             validate_bootdevices(order);
4245             boot_order = order;
4246         }
4247
4248         once = qemu_opt_get(opts, "once");
4249         if (once) {
4250             validate_bootdevices(once);
4251             normal_boot_order = g_strdup(boot_order);
4252             boot_order = once;
4253             qemu_register_reset(restore_boot_order, normal_boot_order);
4254         }
4255
4256         boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4257         boot_strict = qemu_opt_get_bool(opts, "strict", false);
4258     }
4259
4260     if (!kernel_cmdline) {
4261         kernel_cmdline = "";
4262         current_machine->kernel_cmdline = (char *)kernel_cmdline;
4263     }
4264
4265     linux_boot = (kernel_filename != NULL);
4266
4267     if (!linux_boot && *kernel_cmdline != '\0') {
4268         fprintf(stderr, "-append only allowed with -kernel option\n");
4269         exit(1);
4270     }
4271
4272     if (!linux_boot && initrd_filename != NULL) {
4273         fprintf(stderr, "-initrd only allowed with -kernel option\n");
4274         exit(1);
4275     }
4276
4277     if (!linux_boot && qemu_opt_get(machine_opts, "dtb")) {
4278         fprintf(stderr, "-dtb only allowed with -kernel option\n");
4279         exit(1);
4280     }
4281
4282     os_set_line_buffering();
4283
4284     qemu_init_cpu_loop();
4285     qemu_mutex_lock_iothread();
4286
4287 #ifdef CONFIG_SPICE
4288     /* spice needs the timers to be initialized by this point */
4289     qemu_spice_init();
4290 #endif
4291
4292     if (icount_option && (kvm_enabled() || xen_enabled())) {
4293         fprintf(stderr, "-icount is not allowed with kvm or xen\n");
4294         exit(1);
4295     }
4296     configure_icount(icount_option);
4297
4298     /* clean up network at qemu process termination */
4299     atexit(&net_cleanup);
4300
4301     if (net_init_clients() < 0) {
4302         exit(1);
4303     }
4304
4305 #ifdef CONFIG_TPM
4306     if (tpm_init() < 0) {
4307         exit(1);
4308     }
4309 #endif
4310
4311     /* init the bluetooth world */
4312     if (foreach_device_config(DEV_BT, bt_parse))
4313         exit(1);
4314
4315     if (!xen_enabled()) {
4316         /* On 32-bit hosts, QEMU is limited by virtual address space */
4317         if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4318             fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4319             exit(1);
4320         }
4321     }
4322
4323     blk_mig_init();
4324     ram_mig_init();
4325
4326     /* open the virtual block devices */
4327     if (snapshot)
4328         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
4329     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
4330                           &machine_class->block_default_type, 1) != 0) {
4331         exit(1);
4332     }
4333
4334     default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
4335                   CDROM_OPTS);
4336     default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
4337     default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
4338
4339     if (qemu_opts_foreach(qemu_find_opts("numa"), numa_init_func,
4340                           NULL, 1) != 0) {
4341         exit(1);
4342     }
4343
4344     set_numa_nodes();
4345
4346     if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
4347         exit(1);
4348     }
4349
4350     if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4351         exit(1);
4352     if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4353         exit(1);
4354     if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4355         exit(1);
4356     if (foreach_device_config(DEV_SCLP, sclp_parse) < 0) {
4357         exit(1);
4358     }
4359     if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4360         exit(1);
4361
4362     /* If no default VGA is requested, the default is "none".  */
4363     if (default_vga) {
4364         if (cirrus_vga_available()) {
4365             vga_model = "cirrus";
4366         } else if (vga_available()) {
4367             vga_model = "std";
4368         }
4369     }
4370     if (vga_model) {
4371         select_vgahw(vga_model);
4372     }
4373
4374     if (watchdog) {
4375         i = select_watchdog(watchdog);
4376         if (i > 0)
4377             exit (i == 1 ? 1 : 0);
4378     }
4379
4380     if (machine_class->compat_props) {
4381         qdev_prop_register_global_list(machine_class->compat_props);
4382     }
4383     qemu_add_globals();
4384
4385     qdev_machine_init();
4386
4387     current_machine->ram_size = ram_size;
4388     current_machine->maxram_size = maxram_size;
4389     current_machine->ram_slots = ram_slots;
4390     current_machine->boot_order = boot_order;
4391     current_machine->cpu_model = cpu_model;
4392
4393     machine_class->init(current_machine);
4394
4395     audio_init();
4396
4397     cpu_synchronize_all_post_init();
4398
4399     set_numa_modes();
4400
4401     /* init USB devices */
4402     if (usb_enabled(false)) {
4403         if (foreach_device_config(DEV_USB, usb_parse) < 0)
4404             exit(1);
4405     }
4406
4407     /* init generic devices */
4408     if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
4409         exit(1);
4410
4411     net_check_clients();
4412
4413     ds = init_displaystate();
4414
4415     /* init local displays */
4416     switch (display_type) {
4417     case DT_NOGRAPHIC:
4418         (void)ds;       /* avoid warning if no display is configured */
4419         break;
4420 #if defined(CONFIG_CURSES)
4421     case DT_CURSES:
4422         curses_display_init(ds, full_screen);
4423         break;
4424 #endif
4425 #if defined(CONFIG_SDL)
4426     case DT_SDL:
4427         sdl_display_init(ds, full_screen, no_frame);
4428         break;
4429 #elif defined(CONFIG_COCOA)
4430     case DT_SDL:
4431         cocoa_display_init(ds, full_screen);
4432         break;
4433 #endif
4434 #if defined(CONFIG_GTK)
4435     case DT_GTK:
4436         gtk_display_init(ds, full_screen, grab_on_hover);
4437         break;
4438 #endif
4439     default:
4440         break;
4441     }
4442
4443     /* must be after terminal init, SDL library changes signal handlers */
4444     os_setup_signal_handling();
4445
4446 #ifdef CONFIG_VNC
4447     /* init remote displays */
4448     if (vnc_display) {
4449         Error *local_err = NULL;
4450         vnc_display_init(ds);
4451         vnc_display_open(ds, vnc_display, &local_err);
4452         if (local_err != NULL) {
4453             error_report("Failed to start VNC server on `%s': %s",
4454                          vnc_display, error_get_pretty(local_err));
4455             error_free(local_err);
4456             exit(1);
4457         }
4458
4459         if (show_vnc_port) {
4460             printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4461         }
4462     }
4463 #endif
4464 #ifdef CONFIG_SPICE
4465     if (using_spice) {
4466         qemu_spice_display_init();
4467     }
4468 #endif
4469
4470     if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4471         exit(1);
4472     }
4473
4474     qdev_machine_creation_done();
4475
4476     if (rom_load_all() != 0) {
4477         fprintf(stderr, "rom loading failed\n");
4478         exit(1);
4479     }
4480
4481     /* TODO: once all bus devices are qdevified, this should be done
4482      * when bus is created by qdev.c */
4483     qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
4484     qemu_run_machine_init_done_notifiers();
4485
4486     /* Done notifiers can load ROMs */
4487     rom_load_done();
4488
4489     qemu_system_reset(VMRESET_SILENT);
4490     if (loadvm) {
4491         if (load_vmstate(loadvm) < 0) {
4492             autostart = 0;
4493         }
4494     }
4495
4496     qdev_prop_check_global();
4497
4498     if (incoming) {
4499         Error *local_err = NULL;
4500         qemu_start_incoming_migration(incoming, &local_err);
4501         if (local_err) {
4502             error_report("-incoming %s: %s", incoming,
4503                          error_get_pretty(local_err));
4504             error_free(local_err);
4505             exit(1);
4506         }
4507     } else if (autostart) {
4508         vm_start();
4509     }
4510
4511     os_setup_post();
4512
4513     if (is_daemonized()) {
4514         if (!trace_init_backends(trace_events, trace_file)) {
4515             exit(1);
4516         }
4517     }
4518
4519     main_loop();
4520     bdrv_close_all();
4521     pause_all_vcpus();
4522     res_free();
4523 #ifdef CONFIG_TPM
4524     tpm_cleanup();
4525 #endif
4526
4527     return 0;
4528 }
This page took 0.266277 seconds and 4 git commands to generate.