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