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