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