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