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