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