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