Merge tag 'v2.7.0' into develop_qemu_2.7
[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 {
2265             invalid_maru_qt_args:
2266                 error_report(FAILED_TO_DISPLAY_PARSING);
2267                 exit(1);
2268             }
2269             opts = nextopt;
2270         }
2271 # else
2272         error_report("maru_qt is disabled.\n");
2273
2274         exit(1);
2275 # endif
2276 #endif /* CONFIG_MARU */
2277     } else if (strstart(p, "none", &opts)) {
2278         display = DT_NONE;
2279     } else {
2280         error_report("unknown display type");
2281         exit(1);
2282     }
2283
2284     return display;
2285 }
2286
2287 static int balloon_parse(const char *arg)
2288 {
2289     QemuOpts *opts;
2290
2291     if (strcmp(arg, "none") == 0) {
2292         return 0;
2293     }
2294
2295     if (!strncmp(arg, "virtio", 6)) {
2296         if (arg[6] == ',') {
2297             /* have params -> parse them */
2298             opts = qemu_opts_parse_noisily(qemu_find_opts("device"), arg + 7,
2299                                            false);
2300             if (!opts)
2301                 return  -1;
2302         } else {
2303             /* create empty opts */
2304             opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
2305                                     &error_abort);
2306         }
2307         qemu_opt_set(opts, "driver", "virtio-balloon", &error_abort);
2308         return 0;
2309     }
2310
2311     return -1;
2312 }
2313
2314 char *qemu_find_file(int type, const char *name)
2315 {
2316     int i;
2317     const char *subdir;
2318     char *buf;
2319
2320     /* Try the name as a straight path first */
2321     if (access(name, R_OK) == 0) {
2322         trace_load_file(name, name);
2323         return g_strdup(name);
2324     }
2325
2326     switch (type) {
2327     case QEMU_FILE_TYPE_BIOS:
2328         subdir = "";
2329         break;
2330     case QEMU_FILE_TYPE_KEYMAP:
2331         subdir = "keymaps/";
2332         break;
2333     default:
2334         abort();
2335     }
2336
2337     for (i = 0; i < data_dir_idx; i++) {
2338         buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2339         if (access(buf, R_OK) == 0) {
2340             trace_load_file(name, buf);
2341             return buf;
2342         }
2343         g_free(buf);
2344     }
2345     return NULL;
2346 }
2347
2348 static inline bool nonempty_str(const char *str)
2349 {
2350     return str && *str;
2351 }
2352
2353 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2354 {
2355     gchar *buf;
2356     size_t size;
2357     const char *name, *file, *str;
2358     FWCfgState *fw_cfg = (FWCfgState *) opaque;
2359
2360     if (fw_cfg == NULL) {
2361         error_report("fw_cfg device not available");
2362         return -1;
2363     }
2364     name = qemu_opt_get(opts, "name");
2365     file = qemu_opt_get(opts, "file");
2366     str = qemu_opt_get(opts, "string");
2367
2368     /* we need name and either a file or the content string */
2369     if (!(nonempty_str(name) && (nonempty_str(file) || nonempty_str(str)))) {
2370         error_report("invalid argument(s)");
2371         return -1;
2372     }
2373     if (nonempty_str(file) && nonempty_str(str)) {
2374         error_report("file and string are mutually exclusive");
2375         return -1;
2376     }
2377     if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2378         error_report("name too long (max. %d char)", FW_CFG_MAX_FILE_PATH - 1);
2379         return -1;
2380     }
2381     if (strncmp(name, "opt/", 4) != 0) {
2382         error_report("warning: externally provided fw_cfg item names "
2383                      "should be prefixed with \"opt/\"");
2384     }
2385     if (nonempty_str(str)) {
2386         size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2387         buf = g_memdup(str, size);
2388     } else {
2389         if (!g_file_get_contents(file, &buf, &size, NULL)) {
2390             error_report("can't load %s", file);
2391             return -1;
2392         }
2393     }
2394     /* For legacy, keep user files in a specific global order. */
2395     fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2396     fw_cfg_add_file(fw_cfg, name, buf, size);
2397     fw_cfg_reset_order_override(fw_cfg);
2398     return 0;
2399 }
2400
2401 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2402 {
2403     return qdev_device_help(opts);
2404 }
2405
2406 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2407 {
2408     Error *err = NULL;
2409     DeviceState *dev;
2410
2411     dev = qdev_device_add(opts, &err);
2412     if (!dev) {
2413         error_report_err(err);
2414         return -1;
2415     }
2416     object_unref(OBJECT(dev));
2417     return 0;
2418 }
2419
2420 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2421 {
2422     Error *local_err = NULL;
2423
2424     qemu_chr_new_from_opts(opts, NULL, &local_err);
2425     if (local_err) {
2426         error_report_err(local_err);
2427         return -1;
2428     }
2429     return 0;
2430 }
2431
2432 #ifdef CONFIG_VIRTFS
2433 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2434 {
2435     return qemu_fsdev_add(opts);
2436 }
2437 #endif
2438
2439 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2440 {
2441     CharDriverState *chr;
2442     const char *chardev;
2443     const char *mode;
2444     int flags;
2445
2446     mode = qemu_opt_get(opts, "mode");
2447     if (mode == NULL) {
2448         mode = "readline";
2449     }
2450     if (strcmp(mode, "readline") == 0) {
2451         flags = MONITOR_USE_READLINE;
2452     } else if (strcmp(mode, "control") == 0) {
2453         flags = MONITOR_USE_CONTROL;
2454     } else {
2455         error_report("unknown monitor mode \"%s\"", mode);
2456         exit(1);
2457     }
2458
2459     if (qemu_opt_get_bool(opts, "pretty", 0))
2460         flags |= MONITOR_USE_PRETTY;
2461
2462     if (qemu_opt_get_bool(opts, "default", 0))
2463         flags |= MONITOR_IS_DEFAULT;
2464
2465     chardev = qemu_opt_get(opts, "chardev");
2466     chr = qemu_chr_find(chardev);
2467     if (chr == NULL) {
2468         error_report("chardev \"%s\" not found", chardev);
2469         exit(1);
2470     }
2471
2472     qemu_chr_fe_claim_no_fail(chr);
2473     monitor_init(chr, flags);
2474     return 0;
2475 }
2476
2477 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2478 {
2479     static int monitor_device_index = 0;
2480     QemuOpts *opts;
2481     const char *p;
2482     char label[32];
2483     int def = 0;
2484
2485     if (strstart(optarg, "chardev:", &p)) {
2486         snprintf(label, sizeof(label), "%s", p);
2487     } else {
2488         snprintf(label, sizeof(label), "compat_monitor%d",
2489                  monitor_device_index);
2490         if (monitor_device_index == 0) {
2491             def = 1;
2492         }
2493         opts = qemu_chr_parse_compat(label, optarg);
2494         if (!opts) {
2495             error_report("parse error: %s", optarg);
2496             exit(1);
2497         }
2498     }
2499
2500     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2501     qemu_opt_set(opts, "mode", mode, &error_abort);
2502     qemu_opt_set(opts, "chardev", label, &error_abort);
2503     qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2504     if (def)
2505         qemu_opt_set(opts, "default", "on", &error_abort);
2506     monitor_device_index++;
2507 }
2508
2509 struct device_config {
2510     enum {
2511         DEV_USB,       /* -usbdevice     */
2512         DEV_BT,        /* -bt            */
2513         DEV_SERIAL,    /* -serial        */
2514         DEV_PARALLEL,  /* -parallel      */
2515         DEV_VIRTCON,   /* -virtioconsole */
2516         DEV_DEBUGCON,  /* -debugcon */
2517         DEV_GDB,       /* -gdb, -s */
2518         DEV_SCLP,      /* s390 sclp */
2519     } type;
2520     const char *cmdline;
2521     Location loc;
2522     QTAILQ_ENTRY(device_config) next;
2523 };
2524
2525 static QTAILQ_HEAD(, device_config) device_configs =
2526     QTAILQ_HEAD_INITIALIZER(device_configs);
2527
2528 static void add_device_config(int type, const char *cmdline)
2529 {
2530     struct device_config *conf;
2531
2532     conf = g_malloc0(sizeof(*conf));
2533     conf->type = type;
2534     conf->cmdline = cmdline;
2535     loc_save(&conf->loc);
2536     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2537 }
2538
2539 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2540 {
2541     struct device_config *conf;
2542     int rc;
2543
2544     QTAILQ_FOREACH(conf, &device_configs, next) {
2545         if (conf->type != type)
2546             continue;
2547         loc_push_restore(&conf->loc);
2548         rc = func(conf->cmdline);
2549         loc_pop(&conf->loc);
2550         if (rc) {
2551             return rc;
2552         }
2553     }
2554     return 0;
2555 }
2556
2557 static int serial_parse(const char *devname)
2558 {
2559     static int index = 0;
2560     char label[32];
2561
2562     if (strcmp(devname, "none") == 0)
2563         return 0;
2564     if (index == MAX_SERIAL_PORTS) {
2565         error_report("too many serial ports");
2566         exit(1);
2567     }
2568     snprintf(label, sizeof(label), "serial%d", index);
2569     serial_hds[index] = qemu_chr_new(label, devname, NULL);
2570     if (!serial_hds[index]) {
2571         error_report("could not connect serial device"
2572                      " to character backend '%s'", devname);
2573         return -1;
2574     }
2575     index++;
2576     return 0;
2577 }
2578
2579 static int parallel_parse(const char *devname)
2580 {
2581     static int index = 0;
2582     char label[32];
2583
2584     if (strcmp(devname, "none") == 0)
2585         return 0;
2586     if (index == MAX_PARALLEL_PORTS) {
2587         error_report("too many parallel ports");
2588         exit(1);
2589     }
2590     snprintf(label, sizeof(label), "parallel%d", index);
2591     parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2592     if (!parallel_hds[index]) {
2593         error_report("could not connect parallel device"
2594                      " to character backend '%s'", devname);
2595         return -1;
2596     }
2597     index++;
2598     return 0;
2599 }
2600
2601 static int virtcon_parse(const char *devname)
2602 {
2603     QemuOptsList *device = qemu_find_opts("device");
2604     static int index = 0;
2605     char label[32];
2606     QemuOpts *bus_opts, *dev_opts;
2607
2608     if (strcmp(devname, "none") == 0)
2609         return 0;
2610     if (index == MAX_VIRTIO_CONSOLES) {
2611         error_report("too many virtio consoles");
2612         exit(1);
2613     }
2614
2615     bus_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2616     qemu_opt_set(bus_opts, "driver", "virtio-serial", &error_abort);
2617
2618     dev_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2619     qemu_opt_set(dev_opts, "driver", "virtconsole", &error_abort);
2620
2621     snprintf(label, sizeof(label), "virtcon%d", index);
2622     virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2623     if (!virtcon_hds[index]) {
2624         error_report("could not connect virtio console"
2625                      " to character backend '%s'", devname);
2626         return -1;
2627     }
2628     qemu_opt_set(dev_opts, "chardev", label, &error_abort);
2629
2630     index++;
2631     return 0;
2632 }
2633
2634 static int sclp_parse(const char *devname)
2635 {
2636     QemuOptsList *device = qemu_find_opts("device");
2637     static int index = 0;
2638     char label[32];
2639     QemuOpts *dev_opts;
2640
2641     if (strcmp(devname, "none") == 0) {
2642         return 0;
2643     }
2644     if (index == MAX_SCLP_CONSOLES) {
2645         error_report("too many sclp consoles");
2646         exit(1);
2647     }
2648
2649     assert(arch_type == QEMU_ARCH_S390X);
2650
2651     dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2652     qemu_opt_set(dev_opts, "driver", "sclpconsole", &error_abort);
2653
2654     snprintf(label, sizeof(label), "sclpcon%d", index);
2655     sclp_hds[index] = qemu_chr_new(label, devname, NULL);
2656     if (!sclp_hds[index]) {
2657         error_report("could not connect sclp console"
2658                      " to character backend '%s'", devname);
2659         return -1;
2660     }
2661     qemu_opt_set(dev_opts, "chardev", label, &error_abort);
2662
2663     index++;
2664     return 0;
2665 }
2666
2667 static int debugcon_parse(const char *devname)
2668 {
2669     QemuOpts *opts;
2670
2671     if (!qemu_chr_new("debugcon", devname, NULL)) {
2672         exit(1);
2673     }
2674     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2675     if (!opts) {
2676         error_report("already have a debugcon device");
2677         exit(1);
2678     }
2679     qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2680     qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2681     return 0;
2682 }
2683
2684 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2685 {
2686     const MachineClass *mc1 = a, *mc2 = b;
2687     int res;
2688
2689     if (mc1->family == NULL) {
2690         if (mc2->family == NULL) {
2691             /* Compare standalone machine types against each other; they sort
2692              * in increasing order.
2693              */
2694             return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2695                           object_class_get_name(OBJECT_CLASS(mc2)));
2696         }
2697
2698         /* Standalone machine types sort after families. */
2699         return 1;
2700     }
2701
2702     if (mc2->family == NULL) {
2703         /* Families sort before standalone machine types. */
2704         return -1;
2705     }
2706
2707     /* Families sort between each other alphabetically increasingly. */
2708     res = strcmp(mc1->family, mc2->family);
2709     if (res != 0) {
2710         return res;
2711     }
2712
2713     /* Within the same family, machine types sort in decreasing order. */
2714     return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2715                   object_class_get_name(OBJECT_CLASS(mc1)));
2716 }
2717
2718  static MachineClass *machine_parse(const char *name)
2719 {
2720     MachineClass *mc = NULL;
2721     GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);
2722
2723     if (name) {
2724         mc = find_machine(name);
2725     }
2726     if (mc) {
2727         g_slist_free(machines);
2728         return mc;
2729     }
2730     if (name && !is_help_option(name)) {
2731         error_report("unsupported machine type");
2732         error_printf("Use -machine help to list supported machines\n");
2733     } else {
2734         printf("Supported machines are:\n");
2735         machines = g_slist_sort(machines, machine_class_cmp);
2736         for (el = machines; el; el = el->next) {
2737             MachineClass *mc = el->data;
2738             if (mc->alias) {
2739                 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2740             }
2741             printf("%-20s %s%s\n", mc->name, mc->desc,
2742                    mc->is_default ? " (default)" : "");
2743         }
2744     }
2745
2746     g_slist_free(machines);
2747     exit(!name || !is_help_option(name));
2748 }
2749
2750 void qemu_add_exit_notifier(Notifier *notify)
2751 {
2752     notifier_list_add(&exit_notifiers, notify);
2753 }
2754
2755 void qemu_remove_exit_notifier(Notifier *notify)
2756 {
2757     notifier_remove(notify);
2758 }
2759
2760 static void qemu_run_exit_notifiers(void)
2761 {
2762     notifier_list_notify(&exit_notifiers, NULL);
2763 }
2764
2765 static bool machine_init_done;
2766
2767 void qemu_add_machine_init_done_notifier(Notifier *notify)
2768 {
2769     notifier_list_add(&machine_init_done_notifiers, notify);
2770     if (machine_init_done) {
2771         notify->notify(notify, NULL);
2772     }
2773 }
2774
2775 void qemu_remove_machine_init_done_notifier(Notifier *notify)
2776 {
2777     notifier_remove(notify);
2778 }
2779
2780 static void qemu_run_machine_init_done_notifiers(void)
2781 {
2782     notifier_list_notify(&machine_init_done_notifiers, NULL);
2783     machine_init_done = true;
2784 }
2785
2786 static const QEMUOption *lookup_opt(int argc, char **argv,
2787                                     const char **poptarg, int *poptind)
2788 {
2789     const QEMUOption *popt;
2790     int optind = *poptind;
2791     char *r = argv[optind];
2792     const char *optarg;
2793
2794     loc_set_cmdline(argv, optind, 1);
2795     optind++;
2796     /* Treat --foo the same as -foo.  */
2797     if (r[1] == '-')
2798         r++;
2799     popt = qemu_options;
2800     for(;;) {
2801         if (!popt->name) {
2802             error_report("invalid option");
2803             exit(1);
2804         }
2805         if (!strcmp(popt->name, r + 1))
2806             break;
2807         popt++;
2808     }
2809     if (popt->flags & HAS_ARG) {
2810         if (optind >= argc) {
2811             error_report("requires an argument");
2812             exit(1);
2813         }
2814         optarg = argv[optind++];
2815         loc_set_cmdline(argv, optind - 2, 2);
2816     } else {
2817         optarg = NULL;
2818     }
2819
2820     *poptarg = optarg;
2821     *poptind = optind;
2822
2823     return popt;
2824 }
2825
2826 static MachineClass *select_machine(void)
2827 {
2828     MachineClass *machine_class = find_default_machine();
2829     const char *optarg;
2830     QemuOpts *opts;
2831     Location loc;
2832
2833     loc_push_none(&loc);
2834
2835     opts = qemu_get_machine_opts();
2836     qemu_opts_loc_restore(opts);
2837
2838     optarg = qemu_opt_get(opts, "type");
2839     if (optarg) {
2840         machine_class = machine_parse(optarg);
2841     }
2842
2843     if (!machine_class) {
2844         error_report("No machine specified, and there is no default");
2845         error_printf("Use -machine help to list supported machines\n");
2846         exit(1);
2847     }
2848
2849     loc_pop(&loc);
2850     return machine_class;
2851 }
2852
2853 static int machine_set_property(void *opaque,
2854                                 const char *name, const char *value,
2855                                 Error **errp)
2856 {
2857     Object *obj = OBJECT(opaque);
2858     Error *local_err = NULL;
2859     char *c, *qom_name;
2860
2861     if (strcmp(name, "type") == 0) {
2862         return 0;
2863     }
2864
2865     qom_name = g_strdup(name);
2866     c = qom_name;
2867     while (*c++) {
2868         if (*c == '_') {
2869             *c = '-';
2870         }
2871     }
2872
2873     object_property_parse(obj, value, qom_name, &local_err);
2874     g_free(qom_name);
2875
2876     if (local_err) {
2877         error_report_err(local_err);
2878         return -1;
2879     }
2880
2881     return 0;
2882 }
2883
2884
2885 /*
2886  * Initial object creation happens before all other
2887  * QEMU data types are created. The majority of objects
2888  * can be created at this point. The rng-egd object
2889  * cannot be created here, as it depends on the chardev
2890  * already existing.
2891  */
2892 static bool object_create_initial(const char *type)
2893 {
2894     if (g_str_equal(type, "rng-egd")) {
2895         return false;
2896     }
2897
2898     /*
2899      * return false for concrete netfilters since
2900      * they depend on netdevs already existing
2901      */
2902     if (g_str_equal(type, "filter-buffer") ||
2903         g_str_equal(type, "filter-dump") ||
2904         g_str_equal(type, "filter-mirror") ||
2905         g_str_equal(type, "filter-redirector")) {
2906         return false;
2907     }
2908
2909     return true;
2910 }
2911
2912
2913 /*
2914  * The remainder of object creation happens after the
2915  * creation of chardev, fsdev, net clients and device data types.
2916  */
2917 static bool object_create_delayed(const char *type)
2918 {
2919     return !object_create_initial(type);
2920 }
2921
2922
2923 static void set_memory_options(uint64_t *ram_slots, ram_addr_t *maxram_size,
2924                                MachineClass *mc)
2925 {
2926     uint64_t sz;
2927     const char *mem_str;
2928     const char *maxmem_str, *slots_str;
2929     const ram_addr_t default_ram_size = mc->default_ram_size;
2930     QemuOpts *opts = qemu_find_opts_singleton("memory");
2931     Location loc;
2932
2933     loc_push_none(&loc);
2934     qemu_opts_loc_restore(opts);
2935
2936     sz = 0;
2937     mem_str = qemu_opt_get(opts, "size");
2938     if (mem_str) {
2939         if (!*mem_str) {
2940             error_report("missing 'size' option value");
2941             exit(EXIT_FAILURE);
2942         }
2943
2944         sz = qemu_opt_get_size(opts, "size", ram_size);
2945
2946         /* Fix up legacy suffix-less format */
2947         if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2948             uint64_t overflow_check = sz;
2949
2950             sz <<= 20;
2951             if ((sz >> 20) != overflow_check) {
2952                 error_report("too large 'size' option value");
2953                 exit(EXIT_FAILURE);
2954             }
2955         }
2956     }
2957
2958     /* backward compatibility behaviour for case "-m 0" */
2959     if (sz == 0) {
2960         sz = default_ram_size;
2961     }
2962
2963     sz = QEMU_ALIGN_UP(sz, 8192);
2964     ram_size = sz;
2965     if (ram_size != sz) {
2966         error_report("ram size too large");
2967         exit(EXIT_FAILURE);
2968     }
2969
2970     /* store value for the future use */
2971     qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2972     *maxram_size = ram_size;
2973
2974     maxmem_str = qemu_opt_get(opts, "maxmem");
2975     slots_str = qemu_opt_get(opts, "slots");
2976     if (maxmem_str && slots_str) {
2977         uint64_t slots;
2978
2979         sz = qemu_opt_get_size(opts, "maxmem", 0);
2980         slots = qemu_opt_get_number(opts, "slots", 0);
2981         if (sz < ram_size) {
2982             error_report("invalid value of -m option maxmem: "
2983                          "maximum memory size (0x%" PRIx64 ") must be at least "
2984                          "the initial memory size (0x" RAM_ADDR_FMT ")",
2985                          sz, ram_size);
2986             exit(EXIT_FAILURE);
2987         } else if (sz > ram_size) {
2988             if (!slots) {
2989                 error_report("invalid value of -m option: maxmem was "
2990                              "specified, but no hotplug slots were specified");
2991                 exit(EXIT_FAILURE);
2992             }
2993         } else if (slots) {
2994             error_report("invalid value of -m option maxmem: "
2995                          "memory slots were specified but maximum memory size "
2996                          "(0x%" PRIx64 ") is equal to the initial memory size "
2997                          "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2998             exit(EXIT_FAILURE);
2999         }
3000
3001         *maxram_size = sz;
3002         *ram_slots = slots;
3003     } else if ((!maxmem_str && slots_str) ||
3004             (maxmem_str && !slots_str)) {
3005         error_report("invalid -m option value: missing "
3006                 "'%s' option", slots_str ? "maxmem" : "slots");
3007         exit(EXIT_FAILURE);
3008     }
3009
3010     loc_pop(&loc);
3011 }
3012
3013 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
3014 {
3015     GlobalProperty *g;
3016
3017     g = g_malloc0(sizeof(*g));
3018     g->driver   = qemu_opt_get(opts, "driver");
3019     g->property = qemu_opt_get(opts, "property");
3020     g->value    = qemu_opt_get(opts, "value");
3021     g->user_provided = true;
3022     g->errp = &error_fatal;
3023     qdev_prop_register_global(g);
3024     return 0;
3025 }
3026
3027 #ifdef CONFIG_MARU
3028 // W/A for preserve larger continuous heap for RAM.
3029 extern void *preallocated_ram_ptr;
3030 extern int preallocated_ram_size;
3031 // FIXME
3032 extern bool nodisplay;
3033 #endif
3034
3035 int main(int argc, char **argv, char **envp)
3036 {
3037     int i;
3038     int snapshot, linux_boot;
3039     const char *initrd_filename;
3040     const char *kernel_filename, *kernel_cmdline;
3041     const char *boot_order = NULL;
3042     const char *boot_once = NULL;
3043     DisplayState *ds;
3044     int cyls, heads, secs, translation;
3045     QemuOpts *hda_opts = NULL, *opts, *machine_opts, *icount_opts = NULL;
3046     QemuOptsList *olist;
3047     int optind;
3048     const char *optarg;
3049     const char *loadvm = NULL;
3050     MachineClass *machine_class;
3051     const char *cpu_model;
3052     const char *vga_model = NULL;
3053     const char *qtest_chrdev = NULL;
3054     const char *qtest_log = NULL;
3055     const char *pid_file = NULL;
3056     const char *incoming = NULL;
3057     bool defconfig = true;
3058     bool userconfig = true;
3059     bool nographic = false;
3060     DisplayType display_type = DT_DEFAULT;
3061     int display_remote = 0;
3062     const char *log_mask = NULL;
3063     const char *log_file = NULL;
3064     char *trace_file = NULL;
3065     ram_addr_t maxram_size;
3066     uint64_t ram_slots = 0;
3067     FILE *vmstate_dump_file = NULL;
3068     Error *main_loop_err = NULL;
3069     Error *err = NULL;
3070     bool list_data_dirs = false;
3071 #ifdef CONFIG_YAGL
3072     static bool yagl_enabled = false;
3073 #endif /* CONFIG_YAGL */
3074 #ifdef CONFIG_VIGS
3075     static bool vigs_enabled = false;
3076     static char *vigs_backend = NULL;
3077 #endif /* CONFIG_VIGS */
3078
3079     qemu_init_cpu_loop();
3080     qemu_mutex_lock_iothread();
3081
3082     atexit(qemu_run_exit_notifiers);
3083     error_set_progname(argv[0]);
3084     qemu_init_exec_dir(argv[0]);
3085
3086     module_call_init(MODULE_INIT_QOM);
3087
3088     qemu_add_opts(&qemu_drive_opts);
3089     qemu_add_drive_opts(&qemu_legacy_drive_opts);
3090     qemu_add_drive_opts(&qemu_common_drive_opts);
3091     qemu_add_drive_opts(&qemu_drive_opts);
3092     qemu_add_opts(&qemu_chardev_opts);
3093     qemu_add_opts(&qemu_device_opts);
3094     qemu_add_opts(&qemu_netdev_opts);
3095     qemu_add_opts(&qemu_net_opts);
3096     qemu_add_opts(&qemu_rtc_opts);
3097     qemu_add_opts(&qemu_global_opts);
3098     qemu_add_opts(&qemu_mon_opts);
3099     qemu_add_opts(&qemu_trace_opts);
3100     qemu_add_opts(&qemu_option_rom_opts);
3101     qemu_add_opts(&qemu_machine_opts);
3102     qemu_add_opts(&qemu_mem_opts);
3103     qemu_add_opts(&qemu_smp_opts);
3104     qemu_add_opts(&qemu_boot_opts);
3105     qemu_add_opts(&qemu_sandbox_opts);
3106     qemu_add_opts(&qemu_add_fd_opts);
3107     qemu_add_opts(&qemu_object_opts);
3108     qemu_add_opts(&qemu_tpmdev_opts);
3109     qemu_add_opts(&qemu_realtime_opts);
3110     qemu_add_opts(&qemu_msg_opts);
3111     qemu_add_opts(&qemu_name_opts);
3112     qemu_add_opts(&qemu_numa_opts);
3113     qemu_add_opts(&qemu_icount_opts);
3114     qemu_add_opts(&qemu_semihosting_config_opts);
3115     qemu_add_opts(&qemu_fw_cfg_opts);
3116     module_call_init(MODULE_INIT_OPTS);
3117
3118     runstate_init();
3119
3120     if (qcrypto_init(&err) < 0) {
3121         error_reportf_err(err, "cannot initialize crypto: ");
3122         exit(1);
3123     }
3124     rtc_clock = QEMU_CLOCK_HOST;
3125
3126     QLIST_INIT (&vm_change_state_head);
3127     os_setup_early_signal_handling();
3128
3129     cpu_model = NULL;
3130     snapshot = 0;
3131     cyls = heads = secs = 0;
3132     translation = BIOS_ATA_TRANSLATION_AUTO;
3133
3134     nb_nics = 0;
3135
3136     bdrv_init_with_whitelist();
3137
3138     autostart = 1;
3139
3140     /* first pass of option parsing */
3141     optind = 1;
3142     while (optind < argc) {
3143         if (argv[optind][0] != '-') {
3144             /* disk image */
3145             optind++;
3146         } else {
3147             const QEMUOption *popt;
3148
3149             popt = lookup_opt(argc, argv, &optarg, &optind);
3150             switch (popt->index) {
3151             case QEMU_OPTION_nodefconfig:
3152                 defconfig = false;
3153                 break;
3154             case QEMU_OPTION_nouserconfig:
3155                 userconfig = false;
3156                 break;
3157             }
3158         }
3159     }
3160
3161     if (defconfig) {
3162         int ret;
3163         ret = qemu_read_default_config_files(userconfig);
3164         if (ret < 0) {
3165             exit(1);
3166         }
3167     }
3168
3169     /* second pass of option parsing */
3170     optind = 1;
3171     for(;;) {
3172         if (optind >= argc)
3173             break;
3174         if (argv[optind][0] != '-') {
3175             hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3176         } else {
3177             const QEMUOption *popt;
3178
3179             popt = lookup_opt(argc, argv, &optarg, &optind);
3180             if (!(popt->arch_mask & arch_type)) {
3181                 error_report("Option not supported for this target");
3182                 exit(1);
3183             }
3184             switch(popt->index) {
3185             case QEMU_OPTION_no_kvm_irqchip: {
3186                 olist = qemu_find_opts("machine");
3187                 qemu_opts_parse_noisily(olist, "kernel_irqchip=off", false);
3188                 break;
3189             }
3190             case QEMU_OPTION_cpu:
3191                 /* hw initialization will check this */
3192                 cpu_model = optarg;
3193                 break;
3194             case QEMU_OPTION_hda:
3195                 {
3196                     char buf[256];
3197                     if (cyls == 0)
3198                         snprintf(buf, sizeof(buf), "%s", HD_OPTS);
3199                     else
3200                         snprintf(buf, sizeof(buf),
3201                                  "%s,cyls=%d,heads=%d,secs=%d%s",
3202                                  HD_OPTS , cyls, heads, secs,
3203                                  translation == BIOS_ATA_TRANSLATION_LBA ?
3204                                  ",trans=lba" :
3205                                  translation == BIOS_ATA_TRANSLATION_NONE ?
3206                                  ",trans=none" : "");
3207                     drive_add(IF_DEFAULT, 0, optarg, buf);
3208                     break;
3209                 }
3210             case QEMU_OPTION_hdb:
3211             case QEMU_OPTION_hdc:
3212             case QEMU_OPTION_hdd:
3213                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3214                           HD_OPTS);
3215                 break;
3216             case QEMU_OPTION_drive:
3217                 if (drive_def(optarg) == NULL) {
3218                     exit(1);
3219                 }
3220                 break;
3221             case QEMU_OPTION_set:
3222                 if (qemu_set_option(optarg) != 0)
3223                     exit(1);
3224                 break;
3225             case QEMU_OPTION_global:
3226                 if (qemu_global_option(optarg) != 0)
3227                     exit(1);
3228                 break;
3229             case QEMU_OPTION_mtdblock:
3230                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3231                 break;
3232             case QEMU_OPTION_sd:
3233                 drive_add(IF_SD, -1, optarg, SD_OPTS);
3234                 break;
3235             case QEMU_OPTION_pflash:
3236                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3237                 break;
3238             case QEMU_OPTION_snapshot:
3239                 snapshot = 1;
3240                 break;
3241             case QEMU_OPTION_hdachs:
3242                 {
3243                     const char *p;
3244                     p = optarg;
3245                     cyls = strtol(p, (char **)&p, 0);
3246                     if (cyls < 1 || cyls > 16383)
3247                         goto chs_fail;
3248                     if (*p != ',')
3249                         goto chs_fail;
3250                     p++;
3251                     heads = strtol(p, (char **)&p, 0);
3252                     if (heads < 1 || heads > 16)
3253                         goto chs_fail;
3254                     if (*p != ',')
3255                         goto chs_fail;
3256                     p++;
3257                     secs = strtol(p, (char **)&p, 0);
3258                     if (secs < 1 || secs > 63)
3259                         goto chs_fail;
3260                     if (*p == ',') {
3261                         p++;
3262                         if (!strcmp(p, "large")) {
3263                             translation = BIOS_ATA_TRANSLATION_LARGE;
3264                         } else if (!strcmp(p, "rechs")) {
3265                             translation = BIOS_ATA_TRANSLATION_RECHS;
3266                         } else if (!strcmp(p, "none")) {
3267                             translation = BIOS_ATA_TRANSLATION_NONE;
3268                         } else if (!strcmp(p, "lba")) {
3269                             translation = BIOS_ATA_TRANSLATION_LBA;
3270                         } else if (!strcmp(p, "auto")) {
3271                             translation = BIOS_ATA_TRANSLATION_AUTO;
3272                         } else {
3273                             goto chs_fail;
3274                         }
3275                     } else if (*p != '\0') {
3276                     chs_fail:
3277                         error_report("invalid physical CHS format");
3278                         exit(1);
3279                     }
3280                     if (hda_opts != NULL) {
3281                         qemu_opt_set_number(hda_opts, "cyls", cyls,
3282                                             &error_abort);
3283                         qemu_opt_set_number(hda_opts, "heads", heads,
3284                                             &error_abort);
3285                         qemu_opt_set_number(hda_opts, "secs", secs,
3286                                             &error_abort);
3287                         if (translation == BIOS_ATA_TRANSLATION_LARGE) {
3288                             qemu_opt_set(hda_opts, "trans", "large",
3289                                          &error_abort);
3290                         } else if (translation == BIOS_ATA_TRANSLATION_RECHS) {
3291                             qemu_opt_set(hda_opts, "trans", "rechs",
3292                                          &error_abort);
3293                         } else if (translation == BIOS_ATA_TRANSLATION_LBA) {
3294                             qemu_opt_set(hda_opts, "trans", "lba",
3295                                          &error_abort);
3296                         } else if (translation == BIOS_ATA_TRANSLATION_NONE) {
3297                             qemu_opt_set(hda_opts, "trans", "none",
3298                                          &error_abort);
3299                         }
3300                     }
3301                 }
3302                 break;
3303             case QEMU_OPTION_numa:
3304                 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3305                                                optarg, true);
3306                 if (!opts) {
3307                     exit(1);
3308                 }
3309                 break;
3310             case QEMU_OPTION_display:
3311                 display_type = select_display(optarg);
3312                 break;
3313             case QEMU_OPTION_nographic:
3314                 olist = qemu_find_opts("machine");
3315                 qemu_opts_parse_noisily(olist, "graphics=off", false);
3316                 nographic = true;
3317                 display_type = DT_NONE;
3318                 break;
3319             case QEMU_OPTION_curses:
3320 #ifdef CONFIG_CURSES
3321                 display_type = DT_CURSES;
3322 #else
3323                 error_report("curses support is disabled");
3324                 exit(1);
3325 #endif
3326                 break;
3327             case QEMU_OPTION_portrait:
3328                 graphic_rotate = 90;
3329                 break;
3330             case QEMU_OPTION_rotate:
3331                 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3332                 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3333                     graphic_rotate != 180 && graphic_rotate != 270) {
3334                     error_report("only 90, 180, 270 deg rotation is available");
3335                     exit(1);
3336                 }
3337                 break;
3338             case QEMU_OPTION_kernel:
3339                 qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg,
3340                               &error_abort);
3341                 break;
3342             case QEMU_OPTION_initrd:
3343                 qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg,
3344                               &error_abort);
3345                 break;
3346             case QEMU_OPTION_append:
3347                 qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg,
3348                               &error_abort);
3349                 break;
3350             case QEMU_OPTION_dtb:
3351                 qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg,
3352                               &error_abort);
3353                 break;
3354             case QEMU_OPTION_cdrom:
3355                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3356                 break;
3357             case QEMU_OPTION_boot:
3358                 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3359                                                optarg, true);
3360                 if (!opts) {
3361                     exit(1);
3362                 }
3363                 break;
3364             case QEMU_OPTION_fda:
3365             case QEMU_OPTION_fdb:
3366                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3367                           optarg, FD_OPTS);
3368                 break;
3369             case QEMU_OPTION_no_fd_bootchk:
3370                 fd_bootchk = 0;
3371                 break;
3372             case QEMU_OPTION_netdev:
3373                 default_net = 0;
3374                 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3375                     exit(1);
3376                 }
3377                 break;
3378             case QEMU_OPTION_net:
3379                 default_net = 0;
3380                 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3381                     exit(1);
3382                 }
3383                 break;
3384 #ifdef CONFIG_LIBISCSI
3385             case QEMU_OPTION_iscsi:
3386                 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3387                                                optarg, false);
3388                 if (!opts) {
3389                     exit(1);
3390                 }
3391                 break;
3392 #endif
3393 #ifdef CONFIG_SLIRP
3394             case QEMU_OPTION_tftp:
3395                 error_report("The -tftp option is deprecated. "
3396                              "Please use '-netdev user,tftp=...' instead.");
3397                 legacy_tftp_prefix = optarg;
3398                 break;
3399             case QEMU_OPTION_bootp:
3400                 error_report("The -bootp option is deprecated. "
3401                              "Please use '-netdev user,bootfile=...' instead.");
3402                 legacy_bootp_filename = optarg;
3403                 break;
3404             case QEMU_OPTION_redir:
3405                 error_report("The -redir option is deprecated. "
3406                              "Please use '-netdev user,hostfwd=...' instead.");
3407                 if (net_slirp_redir(optarg) < 0)
3408                     exit(1);
3409                 break;
3410 #endif
3411             case QEMU_OPTION_bt:
3412                 add_device_config(DEV_BT, optarg);
3413                 break;
3414             case QEMU_OPTION_audio_help:
3415                 AUD_help ();
3416                 exit (0);
3417                 break;
3418             case QEMU_OPTION_soundhw:
3419                 select_soundhw (optarg);
3420                 break;
3421             case QEMU_OPTION_h:
3422                 help(0);
3423                 break;
3424             case QEMU_OPTION_version:
3425                 version();
3426                 exit(0);
3427                 break;
3428             case QEMU_OPTION_m:
3429                 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3430                                                optarg, true);
3431                 if (!opts) {
3432                     exit(EXIT_FAILURE);
3433                 }
3434                 break;
3435 #ifdef CONFIG_TPM
3436             case QEMU_OPTION_tpmdev:
3437                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3438                     exit(1);
3439                 }
3440                 break;
3441 #endif
3442             case QEMU_OPTION_mempath:
3443                 mem_path = optarg;
3444                 break;
3445             case QEMU_OPTION_mem_prealloc:
3446                 mem_prealloc = 1;
3447                 break;
3448             case QEMU_OPTION_d:
3449                 log_mask = optarg;
3450                 break;
3451             case QEMU_OPTION_D:
3452                 log_file = optarg;
3453                 break;
3454             case QEMU_OPTION_DFILTER:
3455                 qemu_set_dfilter_ranges(optarg, &error_fatal);
3456                 break;
3457             case QEMU_OPTION_s:
3458                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3459                 break;
3460             case QEMU_OPTION_gdb:
3461                 add_device_config(DEV_GDB, optarg);
3462                 break;
3463             case QEMU_OPTION_L:
3464                 if (is_help_option(optarg)) {
3465                     list_data_dirs = true;
3466                 } else if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3467                     data_dir[data_dir_idx++] = optarg;
3468                 }
3469                 break;
3470             case QEMU_OPTION_bios:
3471                 qemu_opts_set(qemu_find_opts("machine"), 0, "firmware", optarg,
3472                               &error_abort);
3473                 break;
3474             case QEMU_OPTION_singlestep:
3475                 singlestep = 1;
3476                 break;
3477             case QEMU_OPTION_S:
3478                 autostart = 0;
3479                 break;
3480             case QEMU_OPTION_k:
3481                 keyboard_layout = optarg;
3482                 break;
3483             case QEMU_OPTION_localtime:
3484                 rtc_utc = 0;
3485                 break;
3486             case QEMU_OPTION_vga:
3487                 vga_model = optarg;
3488                 default_vga = 0;
3489                 break;
3490             case QEMU_OPTION_g:
3491                 {
3492                     const char *p;
3493                     int w, h, depth;
3494                     p = optarg;
3495                     w = strtol(p, (char **)&p, 10);
3496                     if (w <= 0) {
3497                     graphic_error:
3498                         error_report("invalid resolution or depth");
3499                         exit(1);
3500                     }
3501                     if (*p != 'x')
3502                         goto graphic_error;
3503                     p++;
3504                     h = strtol(p, (char **)&p, 10);
3505                     if (h <= 0)
3506                         goto graphic_error;
3507                     if (*p == 'x') {
3508                         p++;
3509                         depth = strtol(p, (char **)&p, 10);
3510                         if (depth != 8 && depth != 15 && depth != 16 &&
3511                             depth != 24 && depth != 32)
3512                             goto graphic_error;
3513                     } else if (*p == '\0') {
3514                         depth = graphic_depth;
3515                     } else {
3516                         goto graphic_error;
3517                     }
3518
3519                     graphic_width = w;
3520                     graphic_height = h;
3521                     graphic_depth = depth;
3522                 }
3523                 break;
3524             case QEMU_OPTION_echr:
3525                 {
3526                     char *r;
3527                     term_escape_char = strtol(optarg, &r, 0);
3528                     if (r == optarg)
3529                         printf("Bad argument to echr\n");
3530                     break;
3531                 }
3532             case QEMU_OPTION_monitor:
3533                 default_monitor = 0;
3534                 if (strncmp(optarg, "none", 4)) {
3535                     monitor_parse(optarg, "readline", false);
3536                 }
3537                 break;
3538             case QEMU_OPTION_qmp:
3539                 monitor_parse(optarg, "control", false);
3540                 default_monitor = 0;
3541                 break;
3542             case QEMU_OPTION_qmp_pretty:
3543                 monitor_parse(optarg, "control", true);
3544                 default_monitor = 0;
3545                 break;
3546             case QEMU_OPTION_mon:
3547                 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3548                                                true);
3549                 if (!opts) {
3550                     exit(1);
3551                 }
3552                 default_monitor = 0;
3553                 break;
3554             case QEMU_OPTION_chardev:
3555                 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3556                                                optarg, true);
3557                 if (!opts) {
3558                     exit(1);
3559                 }
3560                 break;
3561             case QEMU_OPTION_fsdev:
3562                 olist = qemu_find_opts("fsdev");
3563                 if (!olist) {
3564                     error_report("fsdev support is disabled");
3565                     exit(1);
3566                 }
3567                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3568                 if (!opts) {
3569                     exit(1);
3570                 }
3571                 break;
3572             case QEMU_OPTION_virtfs: {
3573                 QemuOpts *fsdev;
3574                 QemuOpts *device;
3575                 const char *writeout, *sock_fd, *socket;
3576
3577                 olist = qemu_find_opts("virtfs");
3578                 if (!olist) {
3579                     error_report("virtfs support is disabled");
3580                     exit(1);
3581                 }
3582                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3583                 if (!opts) {
3584                     exit(1);
3585                 }
3586
3587                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3588                     qemu_opt_get(opts, "mount_tag") == NULL) {
3589                     error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3590                     exit(1);
3591                 }
3592                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3593                                          qemu_opt_get(opts, "mount_tag"),
3594                                          1, NULL);
3595                 if (!fsdev) {
3596                     error_report("duplicate fsdev id: %s",
3597                                  qemu_opt_get(opts, "mount_tag"));
3598                     exit(1);
3599                 }
3600
3601                 writeout = qemu_opt_get(opts, "writeout");
3602                 if (writeout) {
3603 #ifdef CONFIG_SYNC_FILE_RANGE
3604                     qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3605 #else
3606                     error_report("writeout=immediate not supported "
3607                                  "on this platform");
3608                     exit(1);
3609 #endif
3610                 }
3611                 qemu_opt_set(fsdev, "fsdriver",
3612                              qemu_opt_get(opts, "fsdriver"), &error_abort);
3613                 qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"),
3614                              &error_abort);
3615                 qemu_opt_set(fsdev, "security_model",
3616                              qemu_opt_get(opts, "security_model"),
3617                              &error_abort);
3618                 socket = qemu_opt_get(opts, "socket");
3619                 if (socket) {
3620                     qemu_opt_set(fsdev, "socket", socket, &error_abort);
3621                 }
3622                 sock_fd = qemu_opt_get(opts, "sock_fd");
3623                 if (sock_fd) {
3624                     qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3625                 }
3626
3627                 qemu_opt_set_bool(fsdev, "readonly",
3628                                   qemu_opt_get_bool(opts, "readonly", 0),
3629                                   &error_abort);
3630                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3631                                           &error_abort);
3632                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3633                 qemu_opt_set(device, "fsdev",
3634                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3635                 qemu_opt_set(device, "mount_tag",
3636                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3637                 break;
3638             }
3639             case QEMU_OPTION_virtfs_synth: {
3640                 QemuOpts *fsdev;
3641                 QemuOpts *device;
3642
3643                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3644                                          1, NULL);
3645                 if (!fsdev) {
3646                     error_report("duplicate option: %s", "virtfs_synth");
3647                     exit(1);
3648                 }
3649                 qemu_opt_set(fsdev, "fsdriver", "synth", &error_abort);
3650
3651                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3652                                           &error_abort);
3653                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3654                 qemu_opt_set(device, "fsdev", "v_synth", &error_abort);
3655                 qemu_opt_set(device, "mount_tag", "v_synth", &error_abort);
3656                 break;
3657             }
3658             case QEMU_OPTION_serial:
3659                 add_device_config(DEV_SERIAL, optarg);
3660                 default_serial = 0;
3661                 if (strncmp(optarg, "mon:", 4) == 0) {
3662                     default_monitor = 0;
3663                 }
3664                 break;
3665             case QEMU_OPTION_watchdog:
3666                 if (watchdog) {
3667                     error_report("only one watchdog option may be given");
3668                     return 1;
3669                 }
3670                 watchdog = optarg;
3671                 break;
3672             case QEMU_OPTION_watchdog_action:
3673                 if (select_watchdog_action(optarg) == -1) {
3674                     error_report("unknown -watchdog-action parameter");
3675                     exit(1);
3676                 }
3677                 break;
3678             case QEMU_OPTION_virtiocon:
3679                 add_device_config(DEV_VIRTCON, optarg);
3680                 default_virtcon = 0;
3681                 if (strncmp(optarg, "mon:", 4) == 0) {
3682                     default_monitor = 0;
3683                 }
3684                 break;
3685             case QEMU_OPTION_parallel:
3686                 add_device_config(DEV_PARALLEL, optarg);
3687                 default_parallel = 0;
3688                 if (strncmp(optarg, "mon:", 4) == 0) {
3689                     default_monitor = 0;
3690                 }
3691                 break;
3692             case QEMU_OPTION_debugcon:
3693                 add_device_config(DEV_DEBUGCON, optarg);
3694                 break;
3695             case QEMU_OPTION_loadvm:
3696                 loadvm = optarg;
3697                 break;
3698             case QEMU_OPTION_full_screen:
3699                 full_screen = 1;
3700                 break;
3701             case QEMU_OPTION_no_frame:
3702                 no_frame = 1;
3703                 break;
3704             case QEMU_OPTION_alt_grab:
3705                 alt_grab = 1;
3706                 break;
3707             case QEMU_OPTION_ctrl_grab:
3708                 ctrl_grab = 1;
3709                 break;
3710             case QEMU_OPTION_no_quit:
3711                 no_quit = 1;
3712                 break;
3713             case QEMU_OPTION_sdl:
3714 #ifdef CONFIG_SDL
3715                 display_type = DT_SDL;
3716                 break;
3717 #else
3718                 error_report("SDL support is disabled");
3719                 exit(1);
3720 #endif
3721             case QEMU_OPTION_pidfile:
3722                 pid_file = optarg;
3723                 break;
3724             case QEMU_OPTION_win2k_hack:
3725                 win2k_install_hack = 1;
3726                 break;
3727             case QEMU_OPTION_rtc_td_hack: {
3728                 static GlobalProperty slew_lost_ticks = {
3729                     .driver   = "mc146818rtc",
3730                     .property = "lost_tick_policy",
3731                     .value    = "slew",
3732                 };
3733
3734                 qdev_prop_register_global(&slew_lost_ticks);
3735                 break;
3736             }
3737             case QEMU_OPTION_acpitable:
3738                 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3739                                                optarg, true);
3740                 if (!opts) {
3741                     exit(1);
3742                 }
3743                 do_acpitable_option(opts);
3744                 break;
3745             case QEMU_OPTION_smbios:
3746                 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3747                                                optarg, false);
3748                 if (!opts) {
3749                     exit(1);
3750                 }
3751                 do_smbios_option(opts);
3752                 break;
3753             case QEMU_OPTION_fwcfg:
3754                 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3755                                                optarg, true);
3756                 if (opts == NULL) {
3757                     exit(1);
3758                 }
3759                 break;
3760             case QEMU_OPTION_enable_kvm:
3761                 olist = qemu_find_opts("machine");
3762                 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3763                 break;
3764            case QEMU_OPTION_enable_yagl:
3765 #if defined(CONFIG_YAGL)
3766                 yagl_enabled = true;
3767 #else
3768                 fprintf(stderr, "YaGL openGLES passthrough support is disabled,"
3769                     " ignoring -enable-yagl\n");
3770 #endif
3771                 break;
3772            case QEMU_OPTION_enable_vigs:
3773 #if defined(CONFIG_VIGS)
3774                 vigs_enabled = true;
3775 #else
3776                 fprintf(stderr, "VIGS support is disabled,"
3777                     " ignoring -enable-vigs\n");
3778 #endif
3779                 break;
3780            case QEMU_OPTION_vigs_backend:
3781 #if defined(CONFIG_VIGS)
3782                 vigs_backend = g_strdup(optarg);
3783 #else
3784                 fprintf(stderr, "VIGS support is disabled,"
3785                     " ignoring -vigs-backend\n");
3786 #endif
3787                 break;
3788             case QEMU_OPTION_M:
3789             case QEMU_OPTION_machine:
3790                 olist = qemu_find_opts("machine");
3791                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3792                 if (!opts) {
3793                     exit(1);
3794                 }
3795                 break;
3796              case QEMU_OPTION_no_kvm:
3797                 olist = qemu_find_opts("machine");
3798                 qemu_opts_parse_noisily(olist, "accel=tcg", false);
3799                 break;
3800             case QEMU_OPTION_no_kvm_pit: {
3801                 error_report("warning: ignoring deprecated option");
3802                 break;
3803             }
3804             case QEMU_OPTION_no_kvm_pit_reinjection: {
3805                 static GlobalProperty kvm_pit_lost_tick_policy = {
3806                     .driver   = "kvm-pit",
3807                     .property = "lost_tick_policy",
3808                     .value    = "discard",
3809                 };
3810
3811                 error_report("warning: deprecated, replaced by "
3812                              "-global kvm-pit.lost_tick_policy=discard");
3813                 qdev_prop_register_global(&kvm_pit_lost_tick_policy);
3814                 break;
3815             }
3816             case QEMU_OPTION_usb:
3817                 olist = qemu_find_opts("machine");
3818                 qemu_opts_parse_noisily(olist, "usb=on", false);
3819                 break;
3820             case QEMU_OPTION_usbdevice:
3821                 olist = qemu_find_opts("machine");
3822                 qemu_opts_parse_noisily(olist, "usb=on", false);
3823                 add_device_config(DEV_USB, optarg);
3824                 break;
3825             case QEMU_OPTION_device:
3826                 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3827                                              optarg, true)) {
3828                     exit(1);
3829                 }
3830                 break;
3831             case QEMU_OPTION_smp:
3832                 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3833                                              optarg, true)) {
3834                     exit(1);
3835                 }
3836                 break;
3837             case QEMU_OPTION_vnc:
3838                 vnc_parse(optarg, &error_fatal);
3839                 break;
3840             case QEMU_OPTION_no_acpi:
3841                 acpi_enabled = 0;
3842                 break;
3843             case QEMU_OPTION_no_hpet:
3844                 no_hpet = 1;
3845                 break;
3846             case QEMU_OPTION_balloon:
3847                 if (balloon_parse(optarg) < 0) {
3848                     error_report("unknown -balloon argument %s", optarg);
3849                     exit(1);
3850                 }
3851                 break;
3852             case QEMU_OPTION_no_reboot:
3853                 no_reboot = 1;
3854                 break;
3855             case QEMU_OPTION_no_shutdown:
3856                 no_shutdown = 1;
3857                 break;
3858             case QEMU_OPTION_show_cursor:
3859                 cursor_hide = 0;
3860                 break;
3861             case QEMU_OPTION_uuid:
3862                 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3863                     error_report("failed to parse UUID string: wrong format");
3864                     exit(1);
3865                 }
3866                 qemu_uuid_set = true;
3867                 break;
3868             case QEMU_OPTION_option_rom:
3869                 if (nb_option_roms >= MAX_OPTION_ROMS) {
3870                     error_report("too many option ROMs");
3871                     exit(1);
3872                 }
3873                 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3874                                                optarg, true);
3875                 if (!opts) {
3876                     exit(1);
3877                 }
3878                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3879                 option_rom[nb_option_roms].bootindex =
3880                     qemu_opt_get_number(opts, "bootindex", -1);
3881                 if (!option_rom[nb_option_roms].name) {
3882                     error_report("Option ROM file is not specified");
3883                     exit(1);
3884                 }
3885                 nb_option_roms++;
3886                 break;
3887             case QEMU_OPTION_semihosting:
3888                 semihosting.enabled = true;
3889                 semihosting.target = SEMIHOSTING_TARGET_AUTO;
3890                 break;
3891             case QEMU_OPTION_semihosting_config:
3892                 semihosting.enabled = true;
3893                 opts = qemu_opts_parse_noisily(qemu_find_opts("semihosting-config"),
3894                                                optarg, false);
3895                 if (opts != NULL) {
3896                     semihosting.enabled = qemu_opt_get_bool(opts, "enable",
3897                                                             true);
3898                     const char *target = qemu_opt_get(opts, "target");
3899                     if (target != NULL) {
3900                         if (strcmp("native", target) == 0) {
3901                             semihosting.target = SEMIHOSTING_TARGET_NATIVE;
3902                         } else if (strcmp("gdb", target) == 0) {
3903                             semihosting.target = SEMIHOSTING_TARGET_GDB;
3904                         } else  if (strcmp("auto", target) == 0) {
3905                             semihosting.target = SEMIHOSTING_TARGET_AUTO;
3906                         } else {
3907                             error_report("unsupported semihosting-config %s",
3908                                          optarg);
3909                             exit(1);
3910                         }
3911                     } else {
3912                         semihosting.target = SEMIHOSTING_TARGET_AUTO;
3913                     }
3914                     /* Set semihosting argument count and vector */
3915                     qemu_opt_foreach(opts, add_semihosting_arg,
3916                                      &semihosting, NULL);
3917                 } else {
3918                     error_report("unsupported semihosting-config %s", optarg);
3919                     exit(1);
3920                 }
3921                 break;
3922             case QEMU_OPTION_tdf:
3923                 error_report("warning: ignoring deprecated option");
3924                 break;
3925             case QEMU_OPTION_name:
3926                 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3927                                                optarg, true);
3928                 if (!opts) {
3929                     exit(1);
3930                 }
3931                 break;
3932             case QEMU_OPTION_prom_env:
3933                 if (nb_prom_envs >= MAX_PROM_ENVS) {
3934                     error_report("too many prom variables");
3935                     exit(1);
3936                 }
3937                 prom_envs[nb_prom_envs] = optarg;
3938                 nb_prom_envs++;
3939                 break;
3940             case QEMU_OPTION_old_param:
3941                 old_param = 1;
3942                 break;
3943             case QEMU_OPTION_clock:
3944                 /* Clock options no longer exist.  Keep this option for
3945                  * backward compatibility.
3946                  */
3947                 break;
3948             case QEMU_OPTION_startdate:
3949                 configure_rtc_date_offset(optarg, 1);
3950                 break;
3951             case QEMU_OPTION_rtc:
3952                 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3953                                                false);
3954                 if (!opts) {
3955                     exit(1);
3956                 }
3957                 configure_rtc(opts);
3958                 break;
3959             case QEMU_OPTION_tb_size:
3960                 tcg_tb_size = strtol(optarg, NULL, 0);
3961                 if (tcg_tb_size < 0) {
3962                     tcg_tb_size = 0;
3963                 }
3964                 break;
3965             case QEMU_OPTION_icount:
3966                 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3967                                                       optarg, true);
3968                 if (!icount_opts) {
3969                     exit(1);
3970                 }
3971                 break;
3972             case QEMU_OPTION_incoming:
3973                 if (!incoming) {
3974                     runstate_set(RUN_STATE_INMIGRATE);
3975                 }
3976                 incoming = optarg;
3977                 break;
3978             case QEMU_OPTION_nodefaults:
3979                 has_defaults = 0;
3980                 break;
3981             case QEMU_OPTION_xen_domid:
3982                 if (!(xen_available())) {
3983                     error_report("Option not supported for this target");
3984                     exit(1);
3985                 }
3986                 xen_domid = atoi(optarg);
3987                 break;
3988             case QEMU_OPTION_xen_create:
3989                 if (!(xen_available())) {
3990                     error_report("Option not supported for this target");
3991                     exit(1);
3992                 }
3993                 xen_mode = XEN_CREATE;
3994                 break;
3995             case QEMU_OPTION_xen_attach:
3996                 if (!(xen_available())) {
3997                     error_report("Option not supported for this target");
3998                     exit(1);
3999                 }
4000                 xen_mode = XEN_ATTACH;
4001                 break;
4002             case QEMU_OPTION_trace:
4003                 g_free(trace_file);
4004                 trace_file = trace_opt_parse(optarg);
4005                 break;
4006             case QEMU_OPTION_readconfig:
4007                 {
4008                     int ret = qemu_read_config_file(optarg);
4009                     if (ret < 0) {
4010                         error_report("read config %s: %s", optarg,
4011                                      strerror(-ret));
4012                         exit(1);
4013                     }
4014                     break;
4015                 }
4016             case QEMU_OPTION_spice:
4017                 olist = qemu_find_opts("spice");
4018                 if (!olist) {
4019                     error_report("spice support is disabled");
4020                     exit(1);
4021                 }
4022                 opts = qemu_opts_parse_noisily(olist, optarg, false);
4023                 if (!opts) {
4024                     exit(1);
4025                 }
4026                 display_remote++;
4027                 break;
4028             case QEMU_OPTION_writeconfig:
4029                 {
4030                     FILE *fp;
4031                     if (strcmp(optarg, "-") == 0) {
4032                         fp = stdout;
4033                     } else {
4034                         fp = fopen(optarg, "w");
4035                         if (fp == NULL) {
4036                             error_report("open %s: %s", optarg,
4037                                          strerror(errno));
4038                             exit(1);
4039                         }
4040                     }
4041                     qemu_config_write(fp);
4042                     if (fp != stdout) {
4043                         fclose(fp);
4044                     }
4045                     break;
4046                 }
4047             case QEMU_OPTION_qtest:
4048                 qtest_chrdev = optarg;
4049                 break;
4050             case QEMU_OPTION_qtest_log:
4051                 qtest_log = optarg;
4052                 break;
4053             case QEMU_OPTION_sandbox:
4054                 opts = qemu_opts_parse_noisily(qemu_find_opts("sandbox"),
4055                                                optarg, true);
4056                 if (!opts) {
4057                     exit(1);
4058                 }
4059                 break;
4060             case QEMU_OPTION_enable_hax:
4061                 olist = qemu_find_opts("machine");
4062                 qemu_opts_parse_noisily(olist, "accel=hax", false);
4063                 break;
4064             case QEMU_OPTION_add_fd:
4065 #ifndef _WIN32
4066                 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4067                                                optarg, false);
4068                 if (!opts) {
4069                     exit(1);
4070                 }
4071 #else
4072                 error_report("File descriptor passing is disabled on this "
4073                              "platform");
4074                 exit(1);
4075 #endif
4076                 break;
4077 #if defined(CONFIG_MARU)
4078             case QEMU_OPTION_enable_suspend:
4079                 ecs_set_suspend_state(SUSPEND_UNLOCK);
4080                 break;
4081 #endif
4082             case QEMU_OPTION_object:
4083                 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4084                                                optarg, true);
4085                 if (!opts) {
4086                     exit(1);
4087                 }
4088                 break;
4089             case QEMU_OPTION_realtime:
4090                 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4091                                                optarg, false);
4092                 if (!opts) {
4093                     exit(1);
4094                 }
4095                 enable_mlock = qemu_opt_get_bool(opts, "mlock", true);
4096                 break;
4097             case QEMU_OPTION_msg:
4098                 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4099                                                false);
4100                 if (!opts) {
4101                     exit(1);
4102                 }
4103                 configure_msg(opts);
4104                 break;
4105             case QEMU_OPTION_dump_vmstate:
4106                 if (vmstate_dump_file) {
4107                     error_report("only one '-dump-vmstate' "
4108                                  "option may be given");
4109                     exit(1);
4110                 }
4111                 vmstate_dump_file = fopen(optarg, "w");
4112                 if (vmstate_dump_file == NULL) {
4113                     error_report("open %s: %s", optarg, strerror(errno));
4114                     exit(1);
4115                 }
4116                 break;
4117             default:
4118                 os_parse_cmd_args(popt->index, optarg);
4119             }
4120         }
4121     }
4122     /*
4123      * Clear error location left behind by the loop.
4124      * Best done right after the loop.  Do not insert code here!
4125      */
4126     loc_set_none();
4127
4128     replay_configure(icount_opts);
4129
4130     machine_class = select_machine();
4131
4132 #if defined(CONFIG_MARU)
4133     if (is_maru_machine(machine_class)) {
4134         preallocated_ram_ptr = qemu_anon_ram_alloc(ram_size, NULL);
4135         if (preallocated_ram_ptr) {
4136             preallocated_ram_size = ram_size;
4137         }
4138     }
4139 #endif
4140
4141     set_memory_options(&ram_slots, &maxram_size, machine_class);
4142
4143     os_daemonize();
4144
4145     if (qemu_init_main_loop(&main_loop_err)) {
4146         error_report_err(main_loop_err);
4147         exit(1);
4148     }
4149
4150     if (qemu_opts_foreach(qemu_find_opts("sandbox"),
4151                           parse_sandbox, NULL, NULL)) {
4152         exit(1);
4153     }
4154
4155     if (qemu_opts_foreach(qemu_find_opts("name"),
4156                           parse_name, NULL, NULL)) {
4157         exit(1);
4158     }
4159
4160 #ifndef _WIN32
4161     if (qemu_opts_foreach(qemu_find_opts("add-fd"),
4162                           parse_add_fd, NULL, NULL)) {
4163         exit(1);
4164     }
4165
4166     if (qemu_opts_foreach(qemu_find_opts("add-fd"),
4167                           cleanup_add_fd, NULL, NULL)) {
4168         exit(1);
4169     }
4170 #endif
4171
4172     current_machine = MACHINE(object_new(object_class_get_name(
4173                           OBJECT_CLASS(machine_class))));
4174     if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
4175         exit(0);
4176     }
4177     object_property_add_child(object_get_root(), "machine",
4178                               OBJECT(current_machine), &error_abort);
4179     cpu_exec_init_all();
4180
4181     if (machine_class->hw_version) {
4182         qemu_set_hw_version(machine_class->hw_version);
4183     }
4184
4185     if (cpu_model && is_help_option(cpu_model)) {
4186         list_cpus(stdout, &fprintf, cpu_model);
4187         exit(0);
4188     }
4189
4190     if (!trace_init_backends()) {
4191         exit(1);
4192     }
4193     trace_init_file(trace_file);
4194
4195     /* Open the logfile at this point and set the log mask if necessary.
4196      */
4197     if (log_file) {
4198         qemu_set_log_filename(log_file, &error_fatal);
4199     }
4200
4201     if (log_mask) {
4202         int mask;
4203         mask = qemu_str_to_log_mask(log_mask);
4204         if (!mask) {
4205             qemu_print_log_usage(stdout);
4206             exit(1);
4207         }
4208         qemu_set_log(mask);
4209     } else {
4210         qemu_set_log(0);
4211     }
4212
4213     /* If no data_dir is specified then try to find it relative to the
4214        executable path.  */
4215     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4216         data_dir[data_dir_idx] = os_find_datadir();
4217         if (data_dir[data_dir_idx] != NULL) {
4218             data_dir_idx++;
4219         }
4220     }
4221     /* If all else fails use the install path specified when building. */
4222     if (data_dir_idx < ARRAY_SIZE(data_dir)) {
4223         data_dir[data_dir_idx++] = CONFIG_QEMU_DATADIR;
4224     }
4225
4226     /* -L help lists the data directories and exits. */
4227     if (list_data_dirs) {
4228         for (i = 0; i < data_dir_idx; i++) {
4229             printf("%s\n", data_dir[i]);
4230         }
4231         exit(0);
4232     }
4233
4234     smp_parse(qemu_opts_find(qemu_find_opts("smp-opts"), NULL));
4235
4236     machine_class->max_cpus = machine_class->max_cpus ?: 1; /* Default to UP */
4237     if (max_cpus > machine_class->max_cpus) {
4238         error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "
4239                      "supported by machine '%s' (%d)", max_cpus,
4240                      machine_class->name, machine_class->max_cpus);
4241         exit(1);
4242     }
4243
4244     /*
4245      * Get the default machine options from the machine if it is not already
4246      * specified either by the configuration file or by the command line.
4247      */
4248     if (machine_class->default_machine_opts) {
4249         qemu_opts_set_defaults(qemu_find_opts("machine"),
4250                                machine_class->default_machine_opts, 0);
4251     }
4252
4253     qemu_opts_foreach(qemu_find_opts("device"),
4254                       default_driver_check, NULL, NULL);
4255     qemu_opts_foreach(qemu_find_opts("global"),
4256                       default_driver_check, NULL, NULL);
4257
4258     if (!vga_model && !default_vga) {
4259         vga_interface_type = VGA_DEVICE;
4260     }
4261     if (!has_defaults || machine_class->no_serial) {
4262         default_serial = 0;
4263     }
4264     if (!has_defaults || machine_class->no_parallel) {
4265         default_parallel = 0;
4266     }
4267     if (!has_defaults || !machine_class->use_virtcon) {
4268         default_virtcon = 0;
4269     }
4270     if (!has_defaults || !machine_class->use_sclp) {
4271         default_sclp = 0;
4272     }
4273     if (!has_defaults || machine_class->no_floppy) {
4274         default_floppy = 0;
4275     }
4276     if (!has_defaults || machine_class->no_cdrom) {
4277         default_cdrom = 0;
4278     }
4279     if (!has_defaults || machine_class->no_sdcard) {
4280         default_sdcard = 0;
4281     }
4282     if (!has_defaults) {
4283         default_monitor = 0;
4284         default_net = 0;
4285         default_vga = 0;
4286     }
4287
4288     if (is_daemonized()) {
4289         /* According to documentation and historically, -nographic redirects
4290          * serial port, parallel port and monitor to stdio, which does not work
4291          * with -daemonize.  We can redirect these to null instead, but since
4292          * -nographic is legacy, let's just error out.
4293          * We disallow -nographic only if all other ports are not redirected
4294          * explicitly, to not break existing legacy setups which uses
4295          * -nographic _and_ redirects all ports explicitly - this is valid
4296          * usage, -nographic is just a no-op in this case.
4297          */
4298         if (nographic
4299             && (default_parallel || default_serial
4300                 || default_monitor || default_virtcon)) {
4301             error_report("-nographic cannot be used with -daemonize");
4302             exit(1);
4303         }
4304 #ifdef CONFIG_CURSES
4305         if (display_type == DT_CURSES) {
4306             error_report("curses display cannot be used with -daemonize");
4307             exit(1);
4308         }
4309 #endif
4310     }
4311
4312     if (nographic) {
4313         if (default_parallel)
4314             add_device_config(DEV_PARALLEL, "null");
4315         if (default_serial && default_monitor) {
4316             add_device_config(DEV_SERIAL, "mon:stdio");
4317         } else if (default_virtcon && default_monitor) {
4318             add_device_config(DEV_VIRTCON, "mon:stdio");
4319         } else if (default_sclp && default_monitor) {
4320             add_device_config(DEV_SCLP, "mon:stdio");
4321         } else {
4322             if (default_serial)
4323                 add_device_config(DEV_SERIAL, "stdio");
4324             if (default_virtcon)
4325                 add_device_config(DEV_VIRTCON, "stdio");
4326             if (default_sclp) {
4327                 add_device_config(DEV_SCLP, "stdio");
4328             }
4329             if (default_monitor)
4330                 monitor_parse("stdio", "readline", false);
4331         }
4332     } else {
4333         if (default_serial)
4334             add_device_config(DEV_SERIAL, "vc:80Cx24C");
4335         if (default_parallel)
4336             add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4337         if (default_monitor)
4338             monitor_parse("vc:80Cx24C", "readline", false);
4339         if (default_virtcon)
4340             add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4341         if (default_sclp) {
4342             add_device_config(DEV_SCLP, "vc:80Cx24C");
4343         }
4344     }
4345
4346 #if defined(CONFIG_VNC)
4347     if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
4348         display_remote++;
4349     }
4350 #endif
4351     if (display_type == DT_DEFAULT && !display_remote) {
4352 #if defined(CONFIG_GTK)
4353         display_type = DT_GTK;
4354 #elif defined(CONFIG_SDL)
4355         display_type = DT_SDL;
4356 #elif defined(CONFIG_COCOA)
4357         display_type = DT_COCOA;
4358 #elif defined(CONFIG_VNC)
4359         vnc_parse("localhost:0,to=99,id=default", &error_abort);
4360 #else
4361         display_type = DT_NONE;
4362 #endif
4363     }
4364
4365     if ((no_frame || alt_grab || ctrl_grab) && display_type != DT_SDL) {
4366         error_report("-no-frame, -alt-grab and -ctrl-grab are only valid "
4367                      "for SDL, ignoring option");
4368     }
4369     if (no_quit && (display_type != DT_GTK && display_type != DT_SDL)) {
4370         error_report("-no-quit is only valid for GTK and SDL, "
4371                      "ignoring option");
4372     }
4373
4374     if (display_type == DT_GTK) {
4375         early_gtk_display_init(request_opengl);
4376     }
4377
4378     if (display_type == DT_SDL) {
4379         sdl_display_early_init(request_opengl);
4380     }
4381
4382     if (request_opengl == 1 && display_opengl == 0) {
4383 #if defined(CONFIG_OPENGL)
4384         error_report("OpenGL is not supported by the display");
4385 #else
4386         error_report("OpenGL support is disabled");
4387 #endif
4388         exit(1);
4389     }
4390
4391 #ifdef CONFIG_MARU
4392 # if defined(CONFIG_QT)
4393     if (display_type == DT_MARU_QT_ONSCREEN) {
4394         maru_early_qt5_display_init(true);
4395     } else if (display_type == DT_MARU_QT_OFFSCREEN) {
4396         maru_early_qt5_display_init(false);
4397     }
4398 # endif
4399 #endif
4400
4401     page_size_init();
4402     socket_init();
4403
4404     if (qemu_opts_foreach(qemu_find_opts("object"),
4405                           user_creatable_add_opts_foreach,
4406                           object_create_initial, NULL)) {
4407         exit(1);
4408     }
4409
4410     if (qemu_opts_foreach(qemu_find_opts("chardev"),
4411                           chardev_init_func, NULL, NULL)) {
4412         exit(1);
4413     }
4414
4415 #ifdef CONFIG_VIRTFS
4416     if (qemu_opts_foreach(qemu_find_opts("fsdev"),
4417                           fsdev_init_func, NULL, NULL)) {
4418         exit(1);
4419     }
4420 #endif
4421
4422     if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4423         error_report("could not acquire pid file: %s", strerror(errno));
4424         exit(1);
4425     }
4426
4427     if (qemu_opts_foreach(qemu_find_opts("device"),
4428                           device_help_func, NULL, NULL)) {
4429         exit(0);
4430     }
4431
4432     machine_opts = qemu_get_machine_opts();
4433     if (qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
4434                          NULL)) {
4435         object_unref(OBJECT(current_machine));
4436         exit(1);
4437     }
4438
4439     if (qtest_chrdev) {
4440         qtest_init(qtest_chrdev, qtest_log, &error_fatal);
4441     }
4442
4443     machine_opts = qemu_get_machine_opts();
4444     kernel_filename = qemu_opt_get(machine_opts, "kernel");
4445     initrd_filename = qemu_opt_get(machine_opts, "initrd");
4446     kernel_cmdline = qemu_opt_get(machine_opts, "append");
4447     bios_name = qemu_opt_get(machine_opts, "firmware");
4448
4449     opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4450     if (opts) {
4451         boot_order = qemu_opt_get(opts, "order");
4452         if (boot_order) {
4453             validate_bootdevices(boot_order, &error_fatal);
4454         }
4455
4456         boot_once = qemu_opt_get(opts, "once");
4457         if (boot_once) {
4458             validate_bootdevices(boot_once, &error_fatal);
4459         }
4460
4461         boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4462         boot_strict = qemu_opt_get_bool(opts, "strict", false);
4463     }
4464
4465     if (!boot_order) {
4466         boot_order = machine_class->default_boot_order;
4467     }
4468
4469     if (!kernel_cmdline) {
4470         kernel_cmdline = "";
4471         current_machine->kernel_cmdline = (char *)kernel_cmdline;
4472     }
4473
4474     linux_boot = (kernel_filename != NULL);
4475
4476     if (!linux_boot && *kernel_cmdline != '\0') {
4477         error_report("-append only allowed with -kernel option");
4478         exit(1);
4479     }
4480
4481     if (!linux_boot && initrd_filename != NULL) {
4482         error_report("-initrd only allowed with -kernel option");
4483         exit(1);
4484     }
4485
4486     if (!linux_boot && qemu_opt_get(machine_opts, "dtb")) {
4487         error_report("-dtb only allowed with -kernel option");
4488         exit(1);
4489     }
4490
4491     if (semihosting_enabled() && !semihosting_get_argc() && kernel_filename) {
4492         /* fall back to the -kernel/-append */
4493         semihosting_arg_fallback(kernel_filename, kernel_cmdline);
4494     }
4495
4496     os_set_line_buffering();
4497
4498     /* spice needs the timers to be initialized by this point */
4499     qemu_spice_init();
4500
4501     cpu_ticks_init();
4502     if (icount_opts) {
4503         if (kvm_enabled() || xen_enabled() || hax_enabled()) {
4504             error_report("-icount is not allowed with kvm or xen");
4505             exit(1);
4506         }
4507         configure_icount(icount_opts, &error_abort);
4508         qemu_opts_del(icount_opts);
4509     }
4510
4511     if (default_net) {
4512         QemuOptsList *net = qemu_find_opts("net");
4513         qemu_opts_set(net, NULL, "type", "nic", &error_abort);
4514 #ifdef CONFIG_SLIRP
4515         qemu_opts_set(net, NULL, "type", "user", &error_abort);
4516 #endif
4517     }
4518
4519     if (net_init_clients() < 0) {
4520         exit(1);
4521     }
4522
4523     if (qemu_opts_foreach(qemu_find_opts("object"),
4524                           user_creatable_add_opts_foreach,
4525                           object_create_delayed, NULL)) {
4526         exit(1);
4527     }
4528
4529 #ifdef CONFIG_TPM
4530     if (tpm_init() < 0) {
4531         exit(1);
4532     }
4533 #endif
4534
4535     /* init the bluetooth world */
4536     if (foreach_device_config(DEV_BT, bt_parse))
4537         exit(1);
4538
4539     if (!xen_enabled()) {
4540         /* On 32-bit hosts, QEMU is limited by virtual address space */
4541         if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4542             error_report("at most 2047 MB RAM can be simulated");
4543             exit(1);
4544         }
4545     }
4546
4547     blk_mig_init();
4548     ram_mig_init();
4549
4550     /* If the currently selected machine wishes to override the units-per-bus
4551      * property of its default HBA interface type, do so now. */
4552     if (machine_class->units_per_default_bus) {
4553         override_max_devs(machine_class->block_default_type,
4554                           machine_class->units_per_default_bus);
4555     }
4556
4557     /* open the virtual block devices */
4558     if (snapshot || replay_mode != REPLAY_MODE_NONE) {
4559         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
4560                           NULL, NULL);
4561     }
4562     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
4563                           &machine_class->block_default_type, NULL)) {
4564         exit(1);
4565     }
4566
4567     default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
4568                   CDROM_OPTS);
4569     default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
4570     default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
4571
4572     parse_numa_opts(machine_class);
4573
4574     if (qemu_opts_foreach(qemu_find_opts("mon"),
4575                           mon_init_func, NULL, NULL)) {
4576         exit(1);
4577     }
4578
4579     if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4580         exit(1);
4581     if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4582         exit(1);
4583     if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4584         exit(1);
4585     if (foreach_device_config(DEV_SCLP, sclp_parse) < 0) {
4586         exit(1);
4587     }
4588     if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4589         exit(1);
4590
4591     /* If no default VGA is requested, the default is "none".  */
4592     if (default_vga) {
4593         if (machine_class->default_display) {
4594             vga_model = machine_class->default_display;
4595         } else if (vga_interface_available(VGA_CIRRUS)) {
4596             vga_model = "cirrus";
4597         } else if (vga_interface_available(VGA_STD)) {
4598             vga_model = "std";
4599         }
4600     }
4601     if (vga_model) {
4602         select_vgahw(vga_model);
4603     }
4604
4605     if (watchdog) {
4606         i = select_watchdog(watchdog);
4607         if (i > 0)
4608             exit (i == 1 ? 1 : 0);
4609     }
4610
4611     machine_register_compat_props(current_machine);
4612
4613     qemu_opts_foreach(qemu_find_opts("global"),
4614                       global_init_func, NULL, NULL);
4615
4616     /* This checkpoint is required by replay to separate prior clock
4617        reading from the other reads, because timer polling functions query
4618        clock values from the log. */
4619     replay_checkpoint(CHECKPOINT_INIT);
4620     qdev_machine_init();
4621
4622     current_machine->ram_size = ram_size;
4623     current_machine->maxram_size = maxram_size;
4624     current_machine->ram_slots = ram_slots;
4625     current_machine->boot_order = boot_order;
4626     current_machine->cpu_model = cpu_model;
4627
4628     configure_accelerator(current_machine);
4629
4630 #if defined(CONFIG_MARU)
4631     if (is_maru_machine(machine_class)) {
4632         kernel_cmdline = qemu_opt_get(machine_opts, "append");
4633         // Returned variable points different address from input variable.
4634         kernel_cmdline = prepare_maru(kernel_cmdline);
4635         qemu_opt_set(qemu_get_machine_opts(), "append",
4636                 kernel_cmdline, &error_abort);
4637
4638         current_machine->kernel_cmdline = (char *)kernel_cmdline;
4639         if (display_type == DT_NONE) {
4640             nodisplay = true;
4641         }
4642     }
4643 #endif
4644
4645     machine_class->init(current_machine);
4646
4647     realtime_init();
4648
4649     // TODO: Check about it...
4650     audio_init();
4651
4652     cpu_synchronize_all_post_init();
4653
4654     numa_post_machine_init();
4655
4656     if (qemu_opts_foreach(qemu_find_opts("fw_cfg"),
4657                           parse_fw_cfg, fw_cfg_find(), NULL) != 0) {
4658         exit(1);
4659     }
4660
4661     if (hax_enabled()) {
4662         hax_sync_vcpus();
4663     }
4664
4665     /* init USB devices */
4666     if (machine_usb(current_machine)) {
4667         if (foreach_device_config(DEV_USB, usb_parse) < 0)
4668             exit(1);
4669     }
4670
4671     /* Check if IGD GFX passthrough. */
4672     igd_gfx_passthru();
4673
4674     /* init generic devices */
4675     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
4676     if (qemu_opts_foreach(qemu_find_opts("device"),
4677                           device_init_func, NULL, NULL)) {
4678         exit(1);
4679     }
4680     rom_reset_order_override();
4681
4682 #if defined(CONFIG_MARU)
4683     if (is_maru_machine(machine_class)) {
4684         prepare_maru_after_device_init();
4685     }
4686 #endif
4687 #ifdef CONFIG_VIGS
4688     // To support legacy VIGS options
4689     if (vigs_enabled) {
4690         PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
4691         PCIDevice *pci_dev = pci_create(pci_bus, -1, "vigs");
4692         if (vigs_backend) {
4693             qdev_prop_set_string(&pci_dev->qdev, "backend", vigs_backend);
4694         } else {
4695             qdev_prop_set_string(&pci_dev->qdev, "backend", "gl");
4696         }
4697         qdev_prop_set_string(&pci_dev->qdev, "wsi", "wsi0");
4698         qdev_init_nofail(&pci_dev->qdev);
4699     }
4700 #endif
4701 #ifdef CONFIG_YAGL
4702     // To support legacy YaGL options
4703     if (yagl_enabled) {
4704         PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
4705         PCIDevice *pci_dev = pci_create(pci_bus, -1, "yagl");
4706         if (vigs_enabled) {
4707             qdev_prop_set_string(&pci_dev->qdev, "wsi", "wsi0");
4708         }
4709         qdev_init_nofail(&pci_dev->qdev);
4710     }
4711 #endif
4712
4713     /* Did we create any drives that we failed to create a device for? */
4714     drive_check_orphaned();
4715
4716     /* Don't warn about the default network setup that you get if
4717      * no command line -net or -netdev options are specified. There
4718      * are two cases that we would otherwise complain about:
4719      * (1) board doesn't support a NIC but the implicit "-net nic"
4720      * requested one
4721      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
4722      * sets up a nic that isn't connected to anything.
4723      */
4724     if (!default_net) {
4725         net_check_clients();
4726     }
4727
4728
4729     if (boot_once) {
4730         qemu_boot_set(boot_once, &error_fatal);
4731         qemu_register_reset(restore_boot_order, g_strdup(boot_order));
4732     }
4733
4734     ds = init_displaystate();
4735
4736     /* init local displays */
4737     switch (display_type) {
4738     case DT_CURSES:
4739         curses_display_init(ds, full_screen);
4740         break;
4741     case DT_SDL:
4742         sdl_display_init(ds, full_screen, no_frame);
4743         break;
4744     case DT_COCOA:
4745         cocoa_display_init(ds, full_screen);
4746         break;
4747     case DT_GTK:
4748         gtk_display_init(ds, full_screen, grab_on_hover);
4749         break;
4750 #if defined(CONFIG_MARU)
4751  #if defined(CONFIG_QT)
4752     case DT_MARU_QT_ONSCREEN:
4753     case DT_MARU_QT_OFFSCREEN:
4754         if (!is_maru_machine(machine_class)) {
4755             error_report("maru_qt can not work"
4756                     " without maru machine");
4757             exit(1);
4758         }
4759         maru_qt5_display_init(ds, full_screen);
4760         break;
4761  #endif
4762 #endif
4763     default:
4764         break;
4765     }
4766
4767     /* must be after terminal init, SDL library changes signal handlers */
4768     os_setup_signal_handling();
4769
4770     /* init remote displays */
4771 #ifdef CONFIG_VNC
4772     qemu_opts_foreach(qemu_find_opts("vnc"),
4773                       vnc_init_func, NULL, NULL);
4774 #endif
4775
4776     if (using_spice) {
4777         qemu_spice_display_init();
4778     }
4779
4780     if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4781         exit(1);
4782     }
4783
4784     qdev_machine_creation_done();
4785
4786     /* TODO: once all bus devices are qdevified, this should be done
4787      * when bus is created by qdev.c */
4788     qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
4789     qemu_run_machine_init_done_notifiers();
4790
4791     if (rom_check_and_register_reset() != 0) {
4792         error_report("rom check and register reset failed");
4793         exit(1);
4794     }
4795
4796     replay_start();
4797
4798     /* This checkpoint is required by replay to separate prior clock
4799        reading from the other reads, because timer polling functions query
4800        clock values from the log. */
4801     replay_checkpoint(CHECKPOINT_RESET);
4802     qemu_system_reset(VMRESET_SILENT);
4803     register_global_state();
4804     if (loadvm) {
4805         if (load_vmstate(loadvm) < 0) {
4806             autostart = 0;
4807         }
4808     }
4809
4810     qdev_prop_check_globals();
4811     if (vmstate_dump_file) {
4812         /* dump and exit */
4813         dump_vmstate_json_to_file(vmstate_dump_file);
4814         return 0;
4815     }
4816
4817     if (incoming) {
4818         Error *local_err = NULL;
4819         qemu_start_incoming_migration(incoming, &local_err);
4820         if (local_err) {
4821             error_reportf_err(local_err, "-incoming %s: ", incoming);
4822             exit(1);
4823         }
4824     } else if (autostart) {
4825         vm_start();
4826     }
4827
4828     os_setup_post();
4829
4830 #ifdef CONFIG_MARU
4831     enable_print_backtrace_at_normal_exit();
4832 #endif
4833     trace_init_vcpu_events();
4834     main_loop();
4835     replay_disable_events();
4836
4837     bdrv_close_all();
4838     pause_all_vcpus();
4839     res_free();
4840 #ifdef CONFIG_TPM
4841     tpm_cleanup();
4842 #endif
4843
4844     /* vhost-user must be cleaned up before chardevs.  */
4845     net_cleanup();
4846     audio_cleanup();
4847     monitor_cleanup();
4848     qemu_chr_cleanup();
4849
4850     return 0;
4851 }