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