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