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