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