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