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