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