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