]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
rework -monitor handling, switch to QemuOpts
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
1df912cf
FB
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.
0824d6fc 23 */
0824d6fc 24#include <unistd.h>
0824d6fc
FB
25#include <fcntl.h>
26#include <signal.h>
27#include <time.h>
0824d6fc 28#include <errno.h>
67b915a5 29#include <sys/time.h>
c88676f8 30#include <zlib.h>
67b915a5 31
71e72a19 32/* Needed early for CONFIG_BSD etc. */
d40cdb10
BS
33#include "config-host.h"
34
67b915a5 35#ifndef _WIN32
5cea8590 36#include <libgen.h>
0858532e 37#include <pwd.h>
67b915a5 38#include <sys/times.h>
f1510b2c 39#include <sys/wait.h>
67b915a5 40#include <termios.h>
67b915a5 41#include <sys/mman.h>
f1510b2c 42#include <sys/ioctl.h>
24646c7e 43#include <sys/resource.h>
f1510b2c 44#include <sys/socket.h>
c94c8d64 45#include <netinet/in.h>
24646c7e 46#include <net/if.h>
24646c7e 47#include <arpa/inet.h>
9d728e8c 48#include <dirent.h>
7c9d8e07 49#include <netdb.h>
cb4b976b 50#include <sys/select.h>
71e72a19 51#ifdef CONFIG_BSD
7d3505c5 52#include <sys/stat.h>
a167ba50 53#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
7d3505c5 54#include <libutil.h>
24646c7e
BS
55#else
56#include <util.h>
128ab2ff 57#endif
bbe813a2 58#else
223f0d72 59#ifdef __linux__
7d3505c5
FB
60#include <pty.h>
61#include <malloc.h>
fd872598 62#include <linux/rtc.h>
1889465a 63#include <sys/prctl.h>
bd494f4c
TS
64
65/* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67/* #include <linux/hpet.h> */
68#include "hpet.h"
69
e57a8c0e 70#include <linux/ppdev.h>
5867c88a 71#include <linux/parport.h>
223f0d72
BS
72#endif
73#ifdef __sun__
d5d10bc3
TS
74#include <sys/stat.h>
75#include <sys/ethernet.h>
76#include <sys/sockio.h>
d5d10bc3
TS
77#include <netinet/arp.h>
78#include <netinet/in.h>
79#include <netinet/in_systm.h>
80#include <netinet/ip.h>
81#include <netinet/ip_icmp.h> // must come after ip.h
82#include <netinet/udp.h>
83#include <netinet/tcp.h>
84#include <net/if.h>
85#include <syslog.h>
86#include <stropts.h>
8d32cf0e
BS
87/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89extern int madvise(caddr_t, size_t, int);
67b915a5 90#endif
7d3505c5 91#endif
ec530c81 92#endif
67b915a5 93
9892fbfb
BS
94#if defined(__OpenBSD__)
95#include <util.h>
96#endif
97
8a16d273
TS
98#if defined(CONFIG_VDE)
99#include <libvdeplug.h>
100#endif
101
67b915a5 102#ifdef _WIN32
49dc768d 103#include <windows.h>
4fddf62a 104#include <mmsystem.h>
67b915a5
FB
105#endif
106
73332e5c 107#ifdef CONFIG_SDL
59a36a2f 108#if defined(__APPLE__) || defined(main)
6693665a 109#include <SDL.h>
880fec5d 110int qemu_main(int argc, char **argv, char **envp);
111int main(int argc, char **argv)
112{
59a36a2f 113 return qemu_main(argc, argv, NULL);
880fec5d 114}
115#undef main
116#define main qemu_main
96bcd4f8 117#endif
73332e5c 118#endif /* CONFIG_SDL */
0824d6fc 119
5b0753e0
FB
120#ifdef CONFIG_COCOA
121#undef main
122#define main qemu_main
123#endif /* CONFIG_COCOA */
124
511d2b14
BS
125#include "hw/hw.h"
126#include "hw/boards.h"
127#include "hw/usb.h"
128#include "hw/pcmcia.h"
129#include "hw/pc.h"
130#include "hw/audiodev.h"
131#include "hw/isa.h"
132#include "hw/baum.h"
133#include "hw/bt.h"
9dd986cc 134#include "hw/watchdog.h"
b6f6e3d3 135#include "hw/smbios.h"
e37630ca 136#include "hw/xen.h"
bd3c948d 137#include "hw/qdev.h"
45a50b16 138#include "hw/loader.h"
5ef4efa4 139#include "bt-host.h"
511d2b14 140#include "net.h"
68ac40d2 141#include "net/slirp.h"
511d2b14
BS
142#include "monitor.h"
143#include "console.h"
144#include "sysemu.h"
145#include "gdbstub.h"
146#include "qemu-timer.h"
147#include "qemu-char.h"
148#include "cache-utils.h"
149#include "block.h"
c163b5ca
LS
150#include "block_int.h"
151#include "block-migration.h"
a718acec 152#include "dma.h"
511d2b14
BS
153#include "audio/audio.h"
154#include "migration.h"
155#include "kvm.h"
156#include "balloon.h"
d3f24367 157#include "qemu-option.h"
7282a033 158#include "qemu-config.h"
511d2b14 159
0824d6fc 160#include "disas.h"
fc01f7e7 161
8a7ddc38 162#include "exec-all.h"
0824d6fc 163
511d2b14
BS
164#include "qemu_socket.h"
165
d918f23e 166#include "slirp/libslirp.h"
511d2b14 167
72cf2d4f
BS
168#include "qemu-queue.h"
169
9dc63a1e
BS
170//#define DEBUG_NET
171//#define DEBUG_SLIRP
330d0414 172
1bfe856e 173#define DEFAULT_RAM_SIZE 128
313aa567 174
5cea8590 175static const char *data_dir;
1192dad8 176const char *bios_name = NULL;
e4bcb14c 177/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
faea38e7 178 to store the VM snapshots */
72cf2d4f
BS
179struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
180struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
cb5a7aa8 181enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
3023f332 182static DisplayState *display_state;
993fbfdb 183DisplayType display_type = DT_DEFAULT;
3d11d0eb 184const char* keyboard_layout = NULL;
c227f099 185ram_addr_t ram_size;
c4b1fcc0 186int nb_nics;
7c9d8e07 187NICInfo nd_table[MAX_NICS];
8a7ddc38 188int vm_running;
d399f677 189int autostart;
f6503059
AZ
190static int rtc_utc = 1;
191static int rtc_date_offset = -1; /* -1 means no change */
6875204c 192QEMUClock *rtc_clock;
64465297 193int vga_interface_type = VGA_NONE;
d827220b
FB
194#ifdef TARGET_SPARC
195int graphic_width = 1024;
196int graphic_height = 768;
eee0b836 197int graphic_depth = 8;
d827220b 198#else
1bfe856e
FB
199int graphic_width = 800;
200int graphic_height = 600;
e9b137c2 201int graphic_depth = 15;
eee0b836 202#endif
dbed7e40 203static int full_screen = 0;
634a21f6 204#ifdef CONFIG_SDL
dbed7e40 205static int no_frame = 0;
634a21f6 206#endif
667accab 207int no_quit = 0;
8d11df9e 208CharDriverState *serial_hds[MAX_SERIAL_PORTS];
6508fe59 209CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
9ede2fde 210CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
a09db21f
FB
211#ifdef TARGET_I386
212int win2k_install_hack = 0;
73822ec8 213int rtc_td_hack = 0;
a09db21f 214#endif
bb36d470 215int usb_enabled = 0;
1b530a6d 216int singlestep = 0;
6a00d601 217int smp_cpus = 1;
6be68d7e 218int max_cpus = 0;
dc6b1c09
AP
219int smp_cores = 1;
220int smp_threads = 1;
73fc9742 221const char *vnc_display;
6515b203 222int acpi_enabled = 1;
16b29ae1 223int no_hpet = 0;
52ca8d6a 224int fd_bootchk = 1;
d1beab82 225int no_reboot = 0;
b2f76161 226int no_shutdown = 0;
9467cd46 227int cursor_hide = 1;
a171fe39 228int graphic_rotate = 0;
6b35e7bf 229uint8_t irq0override = 1;
b9e82a59 230#ifndef _WIN32
71e3ceb8 231int daemonize = 0;
b9e82a59 232#endif
09aaa160 233const char *watchdog;
9ae02555
TS
234const char *option_rom[MAX_OPTION_ROMS];
235int nb_option_roms;
8e71621f 236int semihosting_enabled = 0;
2b8f2d41
AZ
237#ifdef TARGET_ARM
238int old_param = 0;
239#endif
c35734b2 240const char *qemu_name;
3780e197 241int alt_grab = 0;
0ca9f8a4 242int ctrl_grab = 0;
95efd11c 243#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
244unsigned int nb_prom_envs = 0;
245const char *prom_envs[MAX_PROM_ENVS];
246#endif
95387491 247int boot_menu;
0824d6fc 248
268a362c
AL
249int nb_numa_nodes;
250uint64_t node_mem[MAX_NODES];
251uint64_t node_cpumask[MAX_NODES];
252
ee5605e5
AZ
253static CPUState *cur_cpu;
254static CPUState *next_cpu;
43b96858 255static int timer_alarm_pending = 1;
bf20dc07 256/* Conversion factor from emulated instructions to virtual clock ticks. */
2e70f6ef 257static int icount_time_shift;
bf20dc07 258/* Arbitrarily pick 1MIPS as the minimum allowable speed. */
2e70f6ef
PB
259#define MAX_ICOUNT_SHIFT 10
260/* Compensate for varying guest execution speed. */
261static int64_t qemu_icount_bias;
dbed7e40
BS
262static QEMUTimer *icount_rt_timer;
263static QEMUTimer *icount_vm_timer;
9043b62d 264static QEMUTimer *nographic_timer;
ee5605e5 265
8fcb1b90
BS
266uint8_t qemu_uuid[16];
267
76e30d0f
JK
268static QEMUBootSetHandler *boot_set_handler;
269static void *boot_set_opaque;
270
998bbd74 271static int default_serial = 1;
6a5e8b0e 272static int default_parallel = 1;
abdeed06 273static int default_monitor = 1;
64465297 274static int default_vga = 1;
aa40fc9c 275static int default_drive = 1;
998bbd74
GH
276
277static struct {
278 const char *driver;
279 int *flag;
280} default_list[] = {
6a5e8b0e
GH
281 { .driver = "isa-serial", .flag = &default_serial },
282 { .driver = "isa-parallel", .flag = &default_parallel },
64465297
GH
283 { .driver = "VGA", .flag = &default_vga },
284 { .driver = "Cirrus VGA", .flag = &default_vga },
285 { .driver = "QEMUware SVGA", .flag = &default_vga },
998bbd74
GH
286};
287
288static int default_driver_check(QemuOpts *opts, void *opaque)
289{
290 const char *driver = qemu_opt_get(opts, "driver");
291 int i;
292
293 if (!driver)
294 return 0;
295 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
296 if (strcmp(default_list[i].driver, driver) != 0)
297 continue;
298 *(default_list[i].flag) = 0;
299 }
300 return 0;
301}
302
0824d6fc 303/***********************************************************/
26aa7d72
FB
304/* x86 ISA bus support */
305
c227f099 306target_phys_addr_t isa_mem_base = 0;
3de388f6 307PicState2 *isa_pic;
0824d6fc 308
0824d6fc 309/***********************************************************/
0824d6fc
FB
310void hw_error(const char *fmt, ...)
311{
312 va_list ap;
6a00d601 313 CPUState *env;
0824d6fc
FB
314
315 va_start(ap, fmt);
316 fprintf(stderr, "qemu: hardware error: ");
317 vfprintf(stderr, fmt, ap);
318 fprintf(stderr, "\n");
6a00d601
FB
319 for(env = first_cpu; env != NULL; env = env->next_cpu) {
320 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
0824d6fc 321#ifdef TARGET_I386
6a00d601 322 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
c45886db 323#else
6a00d601 324 cpu_dump_state(env, stderr, fprintf, 0);
0824d6fc 325#endif
6a00d601 326 }
0824d6fc
FB
327 va_end(ap);
328 abort();
329}
1889465a
AK
330
331static void set_proc_name(const char *s)
332{
6ca8d0fd 333#if defined(__linux__) && defined(PR_SET_NAME)
1889465a
AK
334 char name[16];
335 if (!s)
336 return;
337 name[sizeof(name) - 1] = 0;
338 strncpy(name, s, sizeof(name));
339 /* Could rewrite argv[0] too, but that's a bit more complicated.
340 This simple way is enough for `top'. */
341 prctl(PR_SET_NAME, name);
342#endif
343}
df751fa8
AL
344
345/***************/
346/* ballooning */
347
348static QEMUBalloonEvent *qemu_balloon_event;
349void *qemu_balloon_event_opaque;
350
351void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
352{
353 qemu_balloon_event = func;
354 qemu_balloon_event_opaque = opaque;
355}
356
c227f099 357void qemu_balloon(ram_addr_t target)
df751fa8
AL
358{
359 if (qemu_balloon_event)
360 qemu_balloon_event(qemu_balloon_event_opaque, target);
361}
362
c227f099 363ram_addr_t qemu_balloon_status(void)
df751fa8
AL
364{
365 if (qemu_balloon_event)
366 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
367 return 0;
368}
0824d6fc 369
63066f4f
FB
370/***********************************************************/
371/* keyboard/mouse */
372
373static QEMUPutKBDEvent *qemu_put_kbd_event;
374static void *qemu_put_kbd_event_opaque;
455204eb
TS
375static QEMUPutMouseEntry *qemu_put_mouse_event_head;
376static QEMUPutMouseEntry *qemu_put_mouse_event_current;
63066f4f
FB
377
378void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
379{
380 qemu_put_kbd_event_opaque = opaque;
381 qemu_put_kbd_event = func;
382}
383
455204eb
TS
384QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
385 void *opaque, int absolute,
386 const char *name)
63066f4f 387{
455204eb
TS
388 QEMUPutMouseEntry *s, *cursor;
389
390 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
455204eb
TS
391
392 s->qemu_put_mouse_event = func;
393 s->qemu_put_mouse_event_opaque = opaque;
394 s->qemu_put_mouse_event_absolute = absolute;
395 s->qemu_put_mouse_event_name = qemu_strdup(name);
396 s->next = NULL;
397
398 if (!qemu_put_mouse_event_head) {
399 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
400 return s;
401 }
402
403 cursor = qemu_put_mouse_event_head;
404 while (cursor->next != NULL)
405 cursor = cursor->next;
406
407 cursor->next = s;
408 qemu_put_mouse_event_current = s;
409
410 return s;
411}
412
413void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
414{
415 QEMUPutMouseEntry *prev = NULL, *cursor;
416
417 if (!qemu_put_mouse_event_head || entry == NULL)
418 return;
419
420 cursor = qemu_put_mouse_event_head;
421 while (cursor != NULL && cursor != entry) {
422 prev = cursor;
423 cursor = cursor->next;
424 }
425
426 if (cursor == NULL) // does not exist or list empty
427 return;
428 else if (prev == NULL) { // entry is head
429 qemu_put_mouse_event_head = cursor->next;
430 if (qemu_put_mouse_event_current == entry)
431 qemu_put_mouse_event_current = cursor->next;
432 qemu_free(entry->qemu_put_mouse_event_name);
433 qemu_free(entry);
434 return;
435 }
436
437 prev->next = entry->next;
438
439 if (qemu_put_mouse_event_current == entry)
440 qemu_put_mouse_event_current = prev;
441
442 qemu_free(entry->qemu_put_mouse_event_name);
443 qemu_free(entry);
63066f4f
FB
444}
445
446void kbd_put_keycode(int keycode)
447{
448 if (qemu_put_kbd_event) {
449 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
450 }
451}
452
453void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
454{
455204eb
TS
455 QEMUPutMouseEvent *mouse_event;
456 void *mouse_event_opaque;
a171fe39 457 int width;
455204eb
TS
458
459 if (!qemu_put_mouse_event_current) {
460 return;
461 }
462
463 mouse_event =
464 qemu_put_mouse_event_current->qemu_put_mouse_event;
465 mouse_event_opaque =
466 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
467
468 if (mouse_event) {
a171fe39
AZ
469 if (graphic_rotate) {
470 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
471 width = 0x7fff;
472 else
b94ed577 473 width = graphic_width - 1;
a171fe39
AZ
474 mouse_event(mouse_event_opaque,
475 width - dy, dx, dz, buttons_state);
476 } else
477 mouse_event(mouse_event_opaque,
478 dx, dy, dz, buttons_state);
63066f4f
FB
479 }
480}
481
09b26c5e
FB
482int kbd_mouse_is_absolute(void)
483{
455204eb
TS
484 if (!qemu_put_mouse_event_current)
485 return 0;
486
487 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
488}
489
376253ec 490void do_info_mice(Monitor *mon)
455204eb
TS
491{
492 QEMUPutMouseEntry *cursor;
493 int index = 0;
494
495 if (!qemu_put_mouse_event_head) {
376253ec 496 monitor_printf(mon, "No mouse devices connected\n");
455204eb
TS
497 return;
498 }
499
376253ec 500 monitor_printf(mon, "Mouse devices available:\n");
455204eb
TS
501 cursor = qemu_put_mouse_event_head;
502 while (cursor != NULL) {
376253ec
AL
503 monitor_printf(mon, "%c Mouse #%d: %s\n",
504 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
505 index, cursor->qemu_put_mouse_event_name);
455204eb
TS
506 index++;
507 cursor = cursor->next;
508 }
509}
510
d54908a5 511void do_mouse_set(Monitor *mon, const QDict *qdict)
455204eb
TS
512{
513 QEMUPutMouseEntry *cursor;
514 int i = 0;
d54908a5 515 int index = qdict_get_int(qdict, "index");
455204eb
TS
516
517 if (!qemu_put_mouse_event_head) {
376253ec 518 monitor_printf(mon, "No mouse devices connected\n");
455204eb
TS
519 return;
520 }
521
522 cursor = qemu_put_mouse_event_head;
523 while (cursor != NULL && index != i) {
524 i++;
525 cursor = cursor->next;
526 }
527
528 if (cursor != NULL)
529 qemu_put_mouse_event_current = cursor;
530 else
376253ec 531 monitor_printf(mon, "Mouse at given index not found\n");
09b26c5e
FB
532}
533
1dce7c3c
FB
534/* compute with 96 bit intermediate result: (a*b)/c */
535uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
0824d6fc 536{
1dce7c3c
FB
537 union {
538 uint64_t ll;
539 struct {
e2542fe2 540#ifdef HOST_WORDS_BIGENDIAN
1dce7c3c
FB
541 uint32_t high, low;
542#else
543 uint32_t low, high;
3b46e624 544#endif
1dce7c3c
FB
545 } l;
546 } u, res;
547 uint64_t rl, rh;
0824d6fc 548
1dce7c3c
FB
549 u.ll = a;
550 rl = (uint64_t)u.l.low * (uint64_t)b;
551 rh = (uint64_t)u.l.high * (uint64_t)b;
552 rh += (rl >> 32);
553 res.l.high = rh / c;
554 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
555 return res.ll;
34865134
FB
556}
557
1dce7c3c
FB
558/***********************************************************/
559/* real time host monotonic timer */
34865134 560
21d5d12b
JK
561static int64_t get_clock_realtime(void)
562{
563 struct timeval tv;
564
565 gettimeofday(&tv, NULL);
566 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
567}
568
1dce7c3c 569#ifdef WIN32
0824d6fc 570
1dce7c3c 571static int64_t clock_freq;
1115dde7 572
1dce7c3c 573static void init_get_clock(void)
1115dde7 574{
a8e5ac33
FB
575 LARGE_INTEGER freq;
576 int ret;
1dce7c3c
FB
577 ret = QueryPerformanceFrequency(&freq);
578 if (ret == 0) {
579 fprintf(stderr, "Could not calibrate ticks\n");
580 exit(1);
581 }
582 clock_freq = freq.QuadPart;
1115dde7
FB
583}
584
1dce7c3c 585static int64_t get_clock(void)
b8076a74 586{
1dce7c3c
FB
587 LARGE_INTEGER ti;
588 QueryPerformanceCounter(&ti);
274dfed8 589 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
b8076a74
FB
590}
591
1dce7c3c 592#else
90cb9493 593
1dce7c3c
FB
594static int use_rt_clock;
595
596static void init_get_clock(void)
90cb9493 597{
1dce7c3c 598 use_rt_clock = 0;
c5e97233 599#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
a167ba50 600 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
1dce7c3c
FB
601 {
602 struct timespec ts;
603 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
604 use_rt_clock = 1;
605 }
606 }
607#endif
90cb9493
FB
608}
609
1dce7c3c 610static int64_t get_clock(void)
fdbb4691 611{
c5e97233 612#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
a167ba50 613 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
1dce7c3c
FB
614 if (use_rt_clock) {
615 struct timespec ts;
616 clock_gettime(CLOCK_MONOTONIC, &ts);
617 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
5fafdf24 618 } else
fdbb4691 619#endif
1dce7c3c
FB
620 {
621 /* XXX: using gettimeofday leads to problems if the date
622 changes, so it should be avoided. */
21d5d12b 623 return get_clock_realtime();
1dce7c3c 624 }
fdbb4691 625}
34865134
FB
626#endif
627
2e70f6ef
PB
628/* Return the virtual CPU time, based on the instruction counter. */
629static int64_t cpu_get_icount(void)
630{
631 int64_t icount;
632 CPUState *env = cpu_single_env;;
633 icount = qemu_icount;
634 if (env) {
635 if (!can_do_io(env))
636 fprintf(stderr, "Bad clock read\n");
637 icount -= (env->icount_decr.u16.low + env->icount_extra);
638 }
639 return qemu_icount_bias + (icount << icount_time_shift);
640}
641
1dce7c3c
FB
642/***********************************************************/
643/* guest cycle counter */
644
6f68e33e
JQ
645typedef struct TimersState {
646 int64_t cpu_ticks_prev;
647 int64_t cpu_ticks_offset;
648 int64_t cpu_clock_offset;
649 int32_t cpu_ticks_enabled;
274dfed8 650 int64_t dummy;
6f68e33e
JQ
651} TimersState;
652
653TimersState timers_state;
34865134 654
1dce7c3c
FB
655/* return the host CPU cycle counter and handle stop/restart */
656int64_t cpu_get_ticks(void)
34865134 657{
2e70f6ef
PB
658 if (use_icount) {
659 return cpu_get_icount();
660 }
6f68e33e
JQ
661 if (!timers_state.cpu_ticks_enabled) {
662 return timers_state.cpu_ticks_offset;
8a7ddc38 663 } else {
eade0f19
FB
664 int64_t ticks;
665 ticks = cpu_get_real_ticks();
6f68e33e 666 if (timers_state.cpu_ticks_prev > ticks) {
eade0f19
FB
667 /* Note: non increasing ticks may happen if the host uses
668 software suspend */
6f68e33e 669 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
eade0f19 670 }
6f68e33e
JQ
671 timers_state.cpu_ticks_prev = ticks;
672 return ticks + timers_state.cpu_ticks_offset;
8a7ddc38 673 }
34865134
FB
674}
675
1dce7c3c
FB
676/* return the host CPU monotonic timer and handle stop/restart */
677static int64_t cpu_get_clock(void)
678{
679 int64_t ti;
6f68e33e
JQ
680 if (!timers_state.cpu_ticks_enabled) {
681 return timers_state.cpu_clock_offset;
1dce7c3c
FB
682 } else {
683 ti = get_clock();
6f68e33e 684 return ti + timers_state.cpu_clock_offset;
1dce7c3c
FB
685 }
686}
687
34865134
FB
688/* enable cpu_get_ticks() */
689void cpu_enable_ticks(void)
690{
6f68e33e
JQ
691 if (!timers_state.cpu_ticks_enabled) {
692 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
693 timers_state.cpu_clock_offset -= get_clock();
694 timers_state.cpu_ticks_enabled = 1;
8a7ddc38 695 }
34865134
FB
696}
697
698/* disable cpu_get_ticks() : the clock is stopped. You must not call
699 cpu_get_ticks() after that. */
700void cpu_disable_ticks(void)
701{
6f68e33e
JQ
702 if (timers_state.cpu_ticks_enabled) {
703 timers_state.cpu_ticks_offset = cpu_get_ticks();
704 timers_state.cpu_clock_offset = cpu_get_clock();
705 timers_state.cpu_ticks_enabled = 0;
8a7ddc38 706 }
34865134
FB
707}
708
1dce7c3c
FB
709/***********************************************************/
710/* timers */
5fafdf24 711
0fdddf80
JK
712#define QEMU_CLOCK_REALTIME 0
713#define QEMU_CLOCK_VIRTUAL 1
21d5d12b 714#define QEMU_CLOCK_HOST 2
8a7ddc38
FB
715
716struct QEMUClock {
717 int type;
718 /* XXX: add frequency */
719};
720
721struct QEMUTimer {
722 QEMUClock *clock;
723 int64_t expire_time;
724 QEMUTimerCB *cb;
725 void *opaque;
726 struct QEMUTimer *next;
727};
728
c8994013
TS
729struct qemu_alarm_timer {
730 char const *name;
efe75411 731 unsigned int flags;
c8994013
TS
732
733 int (*start)(struct qemu_alarm_timer *t);
734 void (*stop)(struct qemu_alarm_timer *t);
efe75411 735 void (*rearm)(struct qemu_alarm_timer *t);
c8994013
TS
736 void *priv;
737};
738
efe75411 739#define ALARM_FLAG_DYNTICKS 0x1
d5d08334 740#define ALARM_FLAG_EXPIRED 0x2
efe75411
TS
741
742static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
743{
e332340a 744 return t && (t->flags & ALARM_FLAG_DYNTICKS);
efe75411
TS
745}
746
747static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
748{
749 if (!alarm_has_dynticks(t))
750 return;
751
752 t->rearm(t);
753}
754
755/* TODO: MIN_TIMER_REARM_US should be optimized */
756#define MIN_TIMER_REARM_US 250
757
c8994013 758static struct qemu_alarm_timer *alarm_timer;
8a7ddc38 759
40c3bac3 760#ifdef _WIN32
c8994013
TS
761
762struct qemu_alarm_win32 {
763 MMRESULT timerId;
c8994013 764 unsigned int period;
ef28c4b0 765} alarm_win32_data = {0, -1};
c8994013
TS
766
767static int win32_start_timer(struct qemu_alarm_timer *t);
768static void win32_stop_timer(struct qemu_alarm_timer *t);
efe75411 769static void win32_rearm_timer(struct qemu_alarm_timer *t);
c8994013 770
40c3bac3 771#else
c8994013
TS
772
773static int unix_start_timer(struct qemu_alarm_timer *t);
774static void unix_stop_timer(struct qemu_alarm_timer *t);
775
231c6586
TS
776#ifdef __linux__
777
efe75411
TS
778static int dynticks_start_timer(struct qemu_alarm_timer *t);
779static void dynticks_stop_timer(struct qemu_alarm_timer *t);
780static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
781
c40ec5a9
TS
782static int hpet_start_timer(struct qemu_alarm_timer *t);
783static void hpet_stop_timer(struct qemu_alarm_timer *t);
784
c8994013
TS
785static int rtc_start_timer(struct qemu_alarm_timer *t);
786static void rtc_stop_timer(struct qemu_alarm_timer *t);
787
efe75411 788#endif /* __linux__ */
8a7ddc38 789
c8994013
TS
790#endif /* _WIN32 */
791
2e70f6ef 792/* Correlation between real and virtual time is always going to be
bf20dc07 793 fairly approximate, so ignore small variation.
2e70f6ef
PB
794 When the guest is idle real and virtual time will be aligned in
795 the IO wait loop. */
274dfed8 796#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
2e70f6ef
PB
797
798static void icount_adjust(void)
799{
800 int64_t cur_time;
801 int64_t cur_icount;
802 int64_t delta;
803 static int64_t last_delta;
804 /* If the VM is not running, then do nothing. */
805 if (!vm_running)
806 return;
807
808 cur_time = cpu_get_clock();
809 cur_icount = qemu_get_clock(vm_clock);
810 delta = cur_icount - cur_time;
811 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
812 if (delta > 0
813 && last_delta + ICOUNT_WOBBLE < delta * 2
814 && icount_time_shift > 0) {
815 /* The guest is getting too far ahead. Slow time down. */
816 icount_time_shift--;
817 }
818 if (delta < 0
819 && last_delta - ICOUNT_WOBBLE > delta * 2
820 && icount_time_shift < MAX_ICOUNT_SHIFT) {
821 /* The guest is getting too far behind. Speed time up. */
822 icount_time_shift++;
823 }
824 last_delta = delta;
825 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
826}
827
828static void icount_adjust_rt(void * opaque)
829{
830 qemu_mod_timer(icount_rt_timer,
831 qemu_get_clock(rt_clock) + 1000);
832 icount_adjust();
833}
834
835static void icount_adjust_vm(void * opaque)
836{
837 qemu_mod_timer(icount_vm_timer,
274dfed8 838 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
2e70f6ef
PB
839 icount_adjust();
840}
841
842static void init_icount_adjust(void)
843{
844 /* Have both realtime and virtual time triggers for speed adjustment.
845 The realtime trigger catches emulated time passing too slowly,
846 the virtual time trigger catches emulated time passing too fast.
847 Realtime triggers occur even when idle, so use them less frequently
848 than VM triggers. */
849 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
850 qemu_mod_timer(icount_rt_timer,
851 qemu_get_clock(rt_clock) + 1000);
852 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
853 qemu_mod_timer(icount_vm_timer,
274dfed8 854 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
2e70f6ef
PB
855}
856
c8994013 857static struct qemu_alarm_timer alarm_timers[] = {
efe75411 858#ifndef _WIN32
231c6586 859#ifdef __linux__
efe75411
TS
860 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
861 dynticks_stop_timer, dynticks_rearm_timer, NULL},
c40ec5a9 862 /* HPET - if available - is preferred */
efe75411 863 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
c40ec5a9 864 /* ...otherwise try RTC */
efe75411 865 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
c8994013 866#endif
efe75411 867 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
c8994013 868#else
efe75411
TS
869 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
870 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
871 {"win32", 0, win32_start_timer,
872 win32_stop_timer, NULL, &alarm_win32_data},
c8994013
TS
873#endif
874 {NULL, }
875};
876
3f47aa8c 877static void show_available_alarms(void)
f3dcfada
TS
878{
879 int i;
880
881 printf("Available alarm timers, in order of precedence:\n");
882 for (i = 0; alarm_timers[i].name; i++)
883 printf("%s\n", alarm_timers[i].name);
884}
885
886static void configure_alarms(char const *opt)
887{
888 int i;
889 int cur = 0;
b1503cda 890 int count = ARRAY_SIZE(alarm_timers) - 1;
f3dcfada
TS
891 char *arg;
892 char *name;
2e70f6ef 893 struct qemu_alarm_timer tmp;
f3dcfada 894
3adda04c 895 if (!strcmp(opt, "?")) {
f3dcfada
TS
896 show_available_alarms();
897 exit(0);
898 }
899
73ffc805 900 arg = qemu_strdup(opt);
f3dcfada
TS
901
902 /* Reorder the array */
903 name = strtok(arg, ",");
904 while (name) {
e2b577e5 905 for (i = 0; i < count && alarm_timers[i].name; i++) {
f3dcfada
TS
906 if (!strcmp(alarm_timers[i].name, name))
907 break;
908 }
909
910 if (i == count) {
911 fprintf(stderr, "Unknown clock %s\n", name);
912 goto next;
913 }
914
915 if (i < cur)
916 /* Ignore */
917 goto next;
918
919 /* Swap */
920 tmp = alarm_timers[i];
921 alarm_timers[i] = alarm_timers[cur];
922 alarm_timers[cur] = tmp;
923
924 cur++;
925next:
926 name = strtok(NULL, ",");
927 }
928
73ffc805 929 qemu_free(arg);
f3dcfada
TS
930
931 if (cur) {
2e70f6ef 932 /* Disable remaining timers */
f3dcfada
TS
933 for (i = cur; i < count; i++)
934 alarm_timers[i].name = NULL;
3adda04c
AJ
935 } else {
936 show_available_alarms();
937 exit(1);
f3dcfada 938 }
f3dcfada
TS
939}
940
21d5d12b
JK
941#define QEMU_NUM_CLOCKS 3
942
c8994013
TS
943QEMUClock *rt_clock;
944QEMUClock *vm_clock;
21d5d12b 945QEMUClock *host_clock;
c8994013 946
21d5d12b 947static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
c8994013 948
9596ebb7 949static QEMUClock *qemu_new_clock(int type)
8a7ddc38
FB
950{
951 QEMUClock *clock;
952 clock = qemu_mallocz(sizeof(QEMUClock));
8a7ddc38
FB
953 clock->type = type;
954 return clock;
955}
956
957QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
958{
959 QEMUTimer *ts;
960
961 ts = qemu_mallocz(sizeof(QEMUTimer));
962 ts->clock = clock;
963 ts->cb = cb;
964 ts->opaque = opaque;
965 return ts;
966}
967
968void qemu_free_timer(QEMUTimer *ts)
969{
970 qemu_free(ts);
971}
972
973/* stop a timer, but do not dealloc it */
974void qemu_del_timer(QEMUTimer *ts)
975{
976 QEMUTimer **pt, *t;
977
978 /* NOTE: this code must be signal safe because
979 qemu_timer_expired() can be called from a signal. */
980 pt = &active_timers[ts->clock->type];
981 for(;;) {
982 t = *pt;
983 if (!t)
984 break;
985 if (t == ts) {
986 *pt = t->next;
987 break;
988 }
989 pt = &t->next;
990 }
991}
992
993/* modify the current timer so that it will be fired when current_time
994 >= expire_time. The corresponding callback will be called. */
995void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
996{
997 QEMUTimer **pt, *t;
998
999 qemu_del_timer(ts);
1000
1001 /* add the timer in the sorted list */
1002 /* NOTE: this code must be signal safe because
1003 qemu_timer_expired() can be called from a signal. */
1004 pt = &active_timers[ts->clock->type];
1005 for(;;) {
1006 t = *pt;
1007 if (!t)
1008 break;
5fafdf24 1009 if (t->expire_time > expire_time)
8a7ddc38
FB
1010 break;
1011 pt = &t->next;
1012 }
1013 ts->expire_time = expire_time;
1014 ts->next = *pt;
1015 *pt = ts;
d5d08334
AZ
1016
1017 /* Rearm if necessary */
2e70f6ef
PB
1018 if (pt == &active_timers[ts->clock->type]) {
1019 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1020 qemu_rearm_alarm_timer(alarm_timer);
1021 }
1022 /* Interrupt execution to force deadline recalculation. */
d9f75a4e
AL
1023 if (use_icount)
1024 qemu_notify_event();
2e70f6ef 1025 }
8a7ddc38
FB
1026}
1027
1028int qemu_timer_pending(QEMUTimer *ts)
1029{
1030 QEMUTimer *t;
1031 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1032 if (t == ts)
1033 return 1;
1034 }
1035 return 0;
1036}
1037
2430ffe4 1038int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
8a7ddc38
FB
1039{
1040 if (!timer_head)
1041 return 0;
1042 return (timer_head->expire_time <= current_time);
1043}
1044
1045static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1046{
1047 QEMUTimer *ts;
3b46e624 1048
8a7ddc38
FB
1049 for(;;) {
1050 ts = *ptimer_head;
e95c8d51 1051 if (!ts || ts->expire_time > current_time)
8a7ddc38
FB
1052 break;
1053 /* remove timer from the list before calling the callback */
1054 *ptimer_head = ts->next;
1055 ts->next = NULL;
3b46e624 1056
8a7ddc38
FB
1057 /* run the callback (the timer list can be modified) */
1058 ts->cb(ts->opaque);
1059 }
1060}
1061
1062int64_t qemu_get_clock(QEMUClock *clock)
1063{
1064 switch(clock->type) {
0fdddf80 1065 case QEMU_CLOCK_REALTIME:
1dce7c3c 1066 return get_clock() / 1000000;
8a7ddc38 1067 default:
0fdddf80 1068 case QEMU_CLOCK_VIRTUAL:
2e70f6ef
PB
1069 if (use_icount) {
1070 return cpu_get_icount();
1071 } else {
1072 return cpu_get_clock();
1073 }
21d5d12b
JK
1074 case QEMU_CLOCK_HOST:
1075 return get_clock_realtime();
8a7ddc38
FB
1076 }
1077}
1078
0fdddf80 1079static void init_clocks(void)
1dce7c3c
FB
1080{
1081 init_get_clock();
0fdddf80
JK
1082 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1083 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
21d5d12b 1084 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
6875204c
JK
1085
1086 rtc_clock = host_clock;
1dce7c3c
FB
1087}
1088
8a7ddc38
FB
1089/* save a timer */
1090void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1091{
1092 uint64_t expire_time;
1093
1094 if (qemu_timer_pending(ts)) {
1095 expire_time = ts->expire_time;
1096 } else {
1097 expire_time = -1;
1098 }
1099 qemu_put_be64(f, expire_time);
1100}
1101
1102void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1103{
1104 uint64_t expire_time;
1105
1106 expire_time = qemu_get_be64(f);
1107 if (expire_time != -1) {
1108 qemu_mod_timer(ts, expire_time);
1109 } else {
1110 qemu_del_timer(ts);
1111 }
1112}
1113
2faf58cd
JQ
1114static const VMStateDescription vmstate_timers = {
1115 .name = "timer",
1116 .version_id = 2,
1117 .minimum_version_id = 1,
1118 .minimum_version_id_old = 1,
1119 .fields = (VMStateField []) {
1120 VMSTATE_INT64(cpu_ticks_offset, TimersState),
274dfed8 1121 VMSTATE_INT64(dummy, TimersState),
2faf58cd
JQ
1122 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1123 VMSTATE_END_OF_LIST()
c88676f8 1124 }
2faf58cd 1125};
8a7ddc38 1126
50317c7f
AL
1127static void qemu_event_increment(void);
1128
67b915a5 1129#ifdef _WIN32
b9e82a59
BS
1130static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1131 DWORD_PTR dwUser, DWORD_PTR dw1,
1132 DWORD_PTR dw2)
67b915a5 1133#else
8a7ddc38 1134static void host_alarm_handler(int host_signum)
67b915a5 1135#endif
8a7ddc38 1136{
02ba45c5
FB
1137#if 0
1138#define DISP_FREQ 1000
1139 {
1140 static int64_t delta_min = INT64_MAX;
1141 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1142 static int count;
1143 ti = qemu_get_clock(vm_clock);
1144 if (last_clock != 0) {
1145 delta = ti - last_clock;
1146 if (delta < delta_min)
1147 delta_min = delta;
1148 if (delta > delta_max)
1149 delta_max = delta;
1150 delta_cum += delta;
1151 if (++count == DISP_FREQ) {
26a76461 1152 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
6ee093c9
JQ
1153 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1154 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1155 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1156 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
02ba45c5
FB
1157 count = 0;
1158 delta_min = INT64_MAX;
1159 delta_max = 0;
1160 delta_cum = 0;
1161 }
1162 }
1163 last_clock = ti;
1164 }
1165#endif
efe75411 1166 if (alarm_has_dynticks(alarm_timer) ||
2e70f6ef 1167 (!use_icount &&
0fdddf80 1168 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
2e70f6ef 1169 qemu_get_clock(vm_clock))) ||
0fdddf80 1170 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
21d5d12b
JK
1171 qemu_get_clock(rt_clock)) ||
1172 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1173 qemu_get_clock(host_clock))) {
50317c7f 1174 qemu_event_increment();
e332340a 1175 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
d5d08334 1176
d6dc3d42
AL
1177#ifndef CONFIG_IOTHREAD
1178 if (next_cpu) {
4f8eb8da 1179 /* stop the currently executing cpu because a timer occured */
d6dc3d42 1180 cpu_exit(next_cpu);
4f8eb8da 1181 }
d6dc3d42 1182#endif
43b96858 1183 timer_alarm_pending = 1;
d9f75a4e 1184 qemu_notify_event();
8a7ddc38
FB
1185 }
1186}
1187
2e70f6ef 1188static int64_t qemu_next_deadline(void)
efe75411 1189{
21d5d12b
JK
1190 /* To avoid problems with overflow limit this to 2^32. */
1191 int64_t delta = INT32_MAX;
efe75411 1192
0fdddf80
JK
1193 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1194 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
2e70f6ef 1195 qemu_get_clock(vm_clock);
21d5d12b
JK
1196 }
1197 if (active_timers[QEMU_CLOCK_HOST]) {
1198 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1199 qemu_get_clock(host_clock);
1200 if (hdelta < delta)
1201 delta = hdelta;
efe75411
TS
1202 }
1203
2e70f6ef
PB
1204 if (delta < 0)
1205 delta = 0;
efe75411 1206
2e70f6ef
PB
1207 return delta;
1208}
1209
f64382ba 1210#if defined(__linux__)
2e70f6ef
PB
1211static uint64_t qemu_next_deadline_dyntick(void)
1212{
1213 int64_t delta;
1214 int64_t rtdelta;
1215
1216 if (use_icount)
1217 delta = INT32_MAX;
1218 else
1219 delta = (qemu_next_deadline() + 999) / 1000;
1220
0fdddf80
JK
1221 if (active_timers[QEMU_CLOCK_REALTIME]) {
1222 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
2e70f6ef
PB
1223 qemu_get_clock(rt_clock))*1000;
1224 if (rtdelta < delta)
1225 delta = rtdelta;
1226 }
1227
1228 if (delta < MIN_TIMER_REARM_US)
1229 delta = MIN_TIMER_REARM_US;
1230
1231 return delta;
efe75411 1232}
8632fb9a 1233#endif
efe75411 1234
fd872598
FB
1235#ifndef _WIN32
1236
7183b4b4
AL
1237/* Sets a specific flag */
1238static int fcntl_setfl(int fd, int flag)
1239{
1240 int flags;
1241
1242 flags = fcntl(fd, F_GETFL);
1243 if (flags == -1)
1244 return -errno;
1245
1246 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1247 return -errno;
1248
1249 return 0;
1250}
1251
829309c7
FB
1252#if defined(__linux__)
1253
fd872598
FB
1254#define RTC_FREQ 1024
1255
de9a95f0 1256static void enable_sigio_timer(int fd)
c8994013
TS
1257{
1258 struct sigaction act;
1259
1260 /* timer signal */
1261 sigfillset(&act.sa_mask);
1262 act.sa_flags = 0;
c8994013
TS
1263 act.sa_handler = host_alarm_handler;
1264
1265 sigaction(SIGIO, &act, NULL);
7183b4b4 1266 fcntl_setfl(fd, O_ASYNC);
c8994013
TS
1267 fcntl(fd, F_SETOWN, getpid());
1268}
829309c7 1269
c40ec5a9
TS
1270static int hpet_start_timer(struct qemu_alarm_timer *t)
1271{
1272 struct hpet_info info;
1273 int r, fd;
1274
40ff6d7e 1275 fd = qemu_open("/dev/hpet", O_RDONLY);
c40ec5a9
TS
1276 if (fd < 0)
1277 return -1;
1278
1279 /* Set frequency */
1280 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1281 if (r < 0) {
1282 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy type:\n"
1284 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1285 goto fail;
1286 }
1287
1288 /* Check capabilities */
1289 r = ioctl(fd, HPET_INFO, &info);
1290 if (r < 0)
1291 goto fail;
1292
1293 /* Enable periodic mode */
1294 r = ioctl(fd, HPET_EPI, 0);
1295 if (info.hi_flags && (r < 0))
1296 goto fail;
1297
1298 /* Enable interrupt */
1299 r = ioctl(fd, HPET_IE_ON, 0);
1300 if (r < 0)
1301 goto fail;
1302
1303 enable_sigio_timer(fd);
fcdc2129 1304 t->priv = (void *)(long)fd;
c40ec5a9
TS
1305
1306 return 0;
1307fail:
1308 close(fd);
1309 return -1;
1310}
1311
1312static void hpet_stop_timer(struct qemu_alarm_timer *t)
1313{
fcdc2129 1314 int fd = (long)t->priv;
c40ec5a9
TS
1315
1316 close(fd);
1317}
1318
c8994013 1319static int rtc_start_timer(struct qemu_alarm_timer *t)
fd872598 1320{
c8994013 1321 int rtc_fd;
b5a23ad4 1322 unsigned long current_rtc_freq = 0;
c8994013 1323
40ff6d7e 1324 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
fd872598
FB
1325 if (rtc_fd < 0)
1326 return -1;
b5a23ad4
AZ
1327 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1328 if (current_rtc_freq != RTC_FREQ &&
1329 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
fd872598
FB
1330 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1331 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1332 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1333 goto fail;
1334 }
1335 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1336 fail:
1337 close(rtc_fd);
1338 return -1;
1339 }
c8994013
TS
1340
1341 enable_sigio_timer(rtc_fd);
1342
fcdc2129 1343 t->priv = (void *)(long)rtc_fd;
c8994013 1344
fd872598
FB
1345 return 0;
1346}
1347
c8994013 1348static void rtc_stop_timer(struct qemu_alarm_timer *t)
829309c7 1349{
fcdc2129 1350 int rtc_fd = (long)t->priv;
c8994013
TS
1351
1352 close(rtc_fd);
829309c7
FB
1353}
1354
efe75411
TS
1355static int dynticks_start_timer(struct qemu_alarm_timer *t)
1356{
1357 struct sigevent ev;
1358 timer_t host_timer;
1359 struct sigaction act;
1360
1361 sigfillset(&act.sa_mask);
1362 act.sa_flags = 0;
efe75411
TS
1363 act.sa_handler = host_alarm_handler;
1364
1365 sigaction(SIGALRM, &act, NULL);
1366
9ed415b2
JCD
1367 /*
1368 * Initialize ev struct to 0 to avoid valgrind complaining
1369 * about uninitialized data in timer_create call
1370 */
1371 memset(&ev, 0, sizeof(ev));
efe75411
TS
1372 ev.sigev_value.sival_int = 0;
1373 ev.sigev_notify = SIGEV_SIGNAL;
1374 ev.sigev_signo = SIGALRM;
1375
1376 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1377 perror("timer_create");
1378
1379 /* disable dynticks */
1380 fprintf(stderr, "Dynamic Ticks disabled\n");
1381
1382 return -1;
1383 }
1384
0399bfe0 1385 t->priv = (void *)(long)host_timer;
efe75411
TS
1386
1387 return 0;
1388}
1389
1390static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1391{
0399bfe0 1392 timer_t host_timer = (timer_t)(long)t->priv;
efe75411
TS
1393
1394 timer_delete(host_timer);
1395}
1396
1397static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1398{
0399bfe0 1399 timer_t host_timer = (timer_t)(long)t->priv;
efe75411
TS
1400 struct itimerspec timeout;
1401 int64_t nearest_delta_us = INT64_MAX;
1402 int64_t current_us;
1403
0fdddf80 1404 if (!active_timers[QEMU_CLOCK_REALTIME] &&
21d5d12b
JK
1405 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1406 !active_timers[QEMU_CLOCK_HOST])
d5d08334 1407 return;
efe75411 1408
2e70f6ef 1409 nearest_delta_us = qemu_next_deadline_dyntick();
efe75411
TS
1410
1411 /* check whether a timer is already running */
1412 if (timer_gettime(host_timer, &timeout)) {
1413 perror("gettime");
1414 fprintf(stderr, "Internal timer error: aborting\n");
1415 exit(1);
1416 }
1417 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1418 if (current_us && current_us <= nearest_delta_us)
1419 return;
1420
1421 timeout.it_interval.tv_sec = 0;
1422 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1423 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1424 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1425 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1426 perror("settime");
1427 fprintf(stderr, "Internal timer error: aborting\n");
1428 exit(1);
1429 }
1430}
1431
70744b3a 1432#endif /* defined(__linux__) */
231c6586 1433
c8994013
TS
1434static int unix_start_timer(struct qemu_alarm_timer *t)
1435{
1436 struct sigaction act;
1437 struct itimerval itv;
1438 int err;
1439
1440 /* timer signal */
1441 sigfillset(&act.sa_mask);
1442 act.sa_flags = 0;
c8994013
TS
1443 act.sa_handler = host_alarm_handler;
1444
1445 sigaction(SIGALRM, &act, NULL);
1446
1447 itv.it_interval.tv_sec = 0;
1448 /* for i386 kernel 2.6 to get 1 ms */
1449 itv.it_interval.tv_usec = 999;
1450 itv.it_value.tv_sec = 0;
1451 itv.it_value.tv_usec = 10 * 1000;
1452
1453 err = setitimer(ITIMER_REAL, &itv, NULL);
1454 if (err)
1455 return -1;
1456
1457 return 0;
1458}
1459
1460static void unix_stop_timer(struct qemu_alarm_timer *t)
1461{
1462 struct itimerval itv;
1463
1464 memset(&itv, 0, sizeof(itv));
1465 setitimer(ITIMER_REAL, &itv, NULL);
1466}
1467
829309c7 1468#endif /* !defined(_WIN32) */
fd872598 1469
f49e58dc 1470
c8994013
TS
1471#ifdef _WIN32
1472
1473static int win32_start_timer(struct qemu_alarm_timer *t)
1474{
1475 TIMECAPS tc;
1476 struct qemu_alarm_win32 *data = t->priv;
efe75411 1477 UINT flags;
c8994013 1478
c8994013
TS
1479 memset(&tc, 0, sizeof(tc));
1480 timeGetDevCaps(&tc, sizeof(tc));
1481
1482 if (data->period < tc.wPeriodMin)
1483 data->period = tc.wPeriodMin;
1484
1485 timeBeginPeriod(data->period);
1486
efe75411
TS
1487 flags = TIME_CALLBACK_FUNCTION;
1488 if (alarm_has_dynticks(t))
1489 flags |= TIME_ONESHOT;
1490 else
1491 flags |= TIME_PERIODIC;
1492
c8994013
TS
1493 data->timerId = timeSetEvent(1, // interval (ms)
1494 data->period, // resolution
1495 host_alarm_handler, // function
1496 (DWORD)t, // parameter
efe75411 1497 flags);
c8994013
TS
1498
1499 if (!data->timerId) {
20889d4e 1500 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
705e83f6 1501 GetLastError());
c8994013 1502 timeEndPeriod(data->period);
c8994013
TS
1503 return -1;
1504 }
1505
c8994013
TS
1506 return 0;
1507}
1508
1509static void win32_stop_timer(struct qemu_alarm_timer *t)
1510{
1511 struct qemu_alarm_win32 *data = t->priv;
1512
1513 timeKillEvent(data->timerId);
1514 timeEndPeriod(data->period);
c8994013
TS
1515}
1516
efe75411
TS
1517static void win32_rearm_timer(struct qemu_alarm_timer *t)
1518{
1519 struct qemu_alarm_win32 *data = t->priv;
efe75411 1520
0fdddf80 1521 if (!active_timers[QEMU_CLOCK_REALTIME] &&
21d5d12b
JK
1522 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1523 !active_timers[QEMU_CLOCK_HOST])
d5d08334 1524 return;
efe75411 1525
efe75411
TS
1526 timeKillEvent(data->timerId);
1527
1528 data->timerId = timeSetEvent(1,
1529 data->period,
1530 host_alarm_handler,
1531 (DWORD)t,
1532 TIME_ONESHOT | TIME_PERIODIC);
1533
1534 if (!data->timerId) {
20889d4e 1535 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
705e83f6 1536 GetLastError());
efe75411
TS
1537
1538 timeEndPeriod(data->period);
efe75411
TS
1539 exit(1);
1540 }
1541}
1542
c8994013
TS
1543#endif /* _WIN32 */
1544
7183b4b4 1545static int init_timer_alarm(void)
8a7ddc38 1546{
223f0d72 1547 struct qemu_alarm_timer *t = NULL;
c8994013 1548 int i, err = -1;
f49e58dc 1549
c8994013
TS
1550 for (i = 0; alarm_timers[i].name; i++) {
1551 t = &alarm_timers[i];
1552
c8994013
TS
1553 err = t->start(t);
1554 if (!err)
1555 break;
67b915a5 1556 }
fd872598 1557
c8994013 1558 if (err) {
7183b4b4
AL
1559 err = -ENOENT;
1560 goto fail;
67b915a5 1561 }
c8994013
TS
1562
1563 alarm_timer = t;
7183b4b4 1564
6abfbd79 1565 return 0;
7183b4b4
AL
1566
1567fail:
7183b4b4 1568 return err;
8a7ddc38
FB
1569}
1570
9596ebb7 1571static void quit_timers(void)
40c3bac3 1572{
c8994013
TS
1573 alarm_timer->stop(alarm_timer);
1574 alarm_timer = NULL;
40c3bac3
FB
1575}
1576
f6503059
AZ
1577/***********************************************************/
1578/* host time/date access */
1579void qemu_get_timedate(struct tm *tm, int offset)
1580{
1581 time_t ti;
1582 struct tm *ret;
1583
1584 time(&ti);
1585 ti += offset;
1586 if (rtc_date_offset == -1) {
1587 if (rtc_utc)
1588 ret = gmtime(&ti);
1589 else
1590 ret = localtime(&ti);
1591 } else {
1592 ti -= rtc_date_offset;
1593 ret = gmtime(&ti);
1594 }
1595
1596 memcpy(tm, ret, sizeof(struct tm));
1597}
1598
1599int qemu_timedate_diff(struct tm *tm)
1600{
1601 time_t seconds;
1602
1603 if (rtc_date_offset == -1)
1604 if (rtc_utc)
1605 seconds = mktimegm(tm);
1606 else
1607 seconds = mktime(tm);
1608 else
1609 seconds = mktimegm(tm) + rtc_date_offset;
1610
1611 return seconds - time(NULL);
1612}
1613
1ed2fc1f
JK
1614static void configure_rtc_date_offset(const char *startdate, int legacy)
1615{
1616 time_t rtc_start_date;
1617 struct tm tm;
1618
1619 if (!strcmp(startdate, "now") && legacy) {
1620 rtc_date_offset = -1;
1621 } else {
1622 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1623 &tm.tm_year,
1624 &tm.tm_mon,
1625 &tm.tm_mday,
1626 &tm.tm_hour,
1627 &tm.tm_min,
1628 &tm.tm_sec) == 6) {
1629 /* OK */
1630 } else if (sscanf(startdate, "%d-%d-%d",
1631 &tm.tm_year,
1632 &tm.tm_mon,
1633 &tm.tm_mday) == 3) {
1634 tm.tm_hour = 0;
1635 tm.tm_min = 0;
1636 tm.tm_sec = 0;
1637 } else {
1638 goto date_fail;
1639 }
1640 tm.tm_year -= 1900;
1641 tm.tm_mon--;
1642 rtc_start_date = mktimegm(&tm);
1643 if (rtc_start_date == -1) {
1644 date_fail:
1645 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1646 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1647 exit(1);
1648 }
1649 rtc_date_offset = time(NULL) - rtc_start_date;
1650 }
1651}
1652
1653static void configure_rtc(QemuOpts *opts)
1654{
1655 const char *value;
1656
1657 value = qemu_opt_get(opts, "base");
1658 if (value) {
1659 if (!strcmp(value, "utc")) {
1660 rtc_utc = 1;
1661 } else if (!strcmp(value, "localtime")) {
1662 rtc_utc = 0;
1663 } else {
1664 configure_rtc_date_offset(value, 0);
1665 }
1666 }
6875204c
JK
1667 value = qemu_opt_get(opts, "clock");
1668 if (value) {
1669 if (!strcmp(value, "host")) {
1670 rtc_clock = host_clock;
1671 } else if (!strcmp(value, "vm")) {
1672 rtc_clock = vm_clock;
1673 } else {
1674 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1675 exit(1);
1676 }
1677 }
1ed2fc1f
JK
1678#ifdef CONFIG_TARGET_I386
1679 value = qemu_opt_get(opts, "driftfix");
1680 if (value) {
1681 if (!strcmp(buf, "slew")) {
1682 rtc_td_hack = 1;
1683 } else if (!strcmp(buf, "none")) {
1684 rtc_td_hack = 0;
1685 } else {
1686 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1687 exit(1);
1688 }
1689 }
1690#endif
1691}
1692
fd1dff4b 1693#ifdef _WIN32
fd1dff4b
FB
1694static void socket_cleanup(void)
1695{
1696 WSACleanup();
1697}
82c643ff 1698
fd1dff4b
FB
1699static int socket_init(void)
1700{
1701 WSADATA Data;
1702 int ret, err;
1703
1704 ret = WSAStartup(MAKEWORD(2,2), &Data);
1705 if (ret != 0) {
1706 err = WSAGetLastError();
1707 fprintf(stderr, "WSAStartup: %d\n", err);
1708 return -1;
1709 }
1710 atexit(socket_cleanup);
1711 return 0;
1712}
64b7b733
AJ
1713#endif
1714
1ae26a18
AZ
1715/***********************************************************/
1716/* Bluetooth support */
1717static int nb_hcis;
1718static int cur_hci;
1719static struct HCIInfo *hci_table[MAX_NICS];
dc72ac14 1720
1ae26a18
AZ
1721static struct bt_vlan_s {
1722 struct bt_scatternet_s net;
1723 int id;
1724 struct bt_vlan_s *next;
1725} *first_bt_vlan;
1726
1727/* find or alloc a new bluetooth "VLAN" */
674bb261 1728static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1ae26a18
AZ
1729{
1730 struct bt_vlan_s **pvlan, *vlan;
1731 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1732 if (vlan->id == id)
1733 return &vlan->net;
1734 }
1735 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1736 vlan->id = id;
1737 pvlan = &first_bt_vlan;
1738 while (*pvlan != NULL)
1739 pvlan = &(*pvlan)->next;
1740 *pvlan = vlan;
1741 return &vlan->net;
1742}
1743
1744static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1745{
1746}
1747
1748static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1749{
1750 return -ENOTSUP;
1751}
1752
1753static struct HCIInfo null_hci = {
1754 .cmd_send = null_hci_send,
1755 .sco_send = null_hci_send,
1756 .acl_send = null_hci_send,
1757 .bdaddr_set = null_hci_addr_set,
1758};
1759
1760struct HCIInfo *qemu_next_hci(void)
1761{
1762 if (cur_hci == nb_hcis)
1763 return &null_hci;
1764
1765 return hci_table[cur_hci++];
1766}
1767
dc72ac14
AZ
1768static struct HCIInfo *hci_init(const char *str)
1769{
1770 char *endp;
1771 struct bt_scatternet_s *vlan = 0;
1772
1773 if (!strcmp(str, "null"))
1774 /* null */
1775 return &null_hci;
1776 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1777 /* host[:hciN] */
1778 return bt_host_hci(str[4] ? str + 5 : "hci0");
1779 else if (!strncmp(str, "hci", 3)) {
1780 /* hci[,vlan=n] */
1781 if (str[3]) {
1782 if (!strncmp(str + 3, ",vlan=", 6)) {
1783 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1784 if (*endp)
1785 vlan = 0;
1786 }
1787 } else
1788 vlan = qemu_find_bt_vlan(0);
1789 if (vlan)
1790 return bt_new_hci(vlan);
1791 }
1792
1793 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1794
1795 return 0;
1796}
1797
1798static int bt_hci_parse(const char *str)
1799{
1800 struct HCIInfo *hci;
c227f099 1801 bdaddr_t bdaddr;
dc72ac14
AZ
1802
1803 if (nb_hcis >= MAX_NICS) {
1804 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1805 return -1;
1806 }
1807
1808 hci = hci_init(str);
1809 if (!hci)
1810 return -1;
1811
1812 bdaddr.b[0] = 0x52;
1813 bdaddr.b[1] = 0x54;
1814 bdaddr.b[2] = 0x00;
1815 bdaddr.b[3] = 0x12;
1816 bdaddr.b[4] = 0x34;
1817 bdaddr.b[5] = 0x56 + nb_hcis;
1818 hci->bdaddr_set(hci, bdaddr.b);
1819
1820 hci_table[nb_hcis++] = hci;
1821
1822 return 0;
1823}
1824
1825static void bt_vhci_add(int vlan_id)
1826{
1827 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1828
1829 if (!vlan->slave)
1830 fprintf(stderr, "qemu: warning: adding a VHCI to "
1831 "an empty scatternet %i\n", vlan_id);
1832
1833 bt_vhci_init(bt_new_hci(vlan));
1834}
1835
1836static struct bt_device_s *bt_device_add(const char *opt)
1837{
1838 struct bt_scatternet_s *vlan;
1839 int vlan_id = 0;
1840 char *endp = strstr(opt, ",vlan=");
1841 int len = (endp ? endp - opt : strlen(opt)) + 1;
1842 char devname[10];
1843
1844 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1845
1846 if (endp) {
1847 vlan_id = strtol(endp + 6, &endp, 0);
1848 if (*endp) {
1849 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1850 return 0;
1851 }
1852 }
1853
1854 vlan = qemu_find_bt_vlan(vlan_id);
1855
1856 if (!vlan->slave)
1857 fprintf(stderr, "qemu: warning: adding a slave device to "
1858 "an empty scatternet %i\n", vlan_id);
1859
1860 if (!strcmp(devname, "keyboard"))
1861 return bt_keyboard_init(vlan);
1862
1863 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1864 return 0;
1865}
1866
1867static int bt_parse(const char *opt)
1868{
1869 const char *endp, *p;
1870 int vlan;
1871
1872 if (strstart(opt, "hci", &endp)) {
1873 if (!*endp || *endp == ',') {
1874 if (*endp)
1875 if (!strstart(endp, ",vlan=", 0))
1876 opt = endp + 1;
1877
1878 return bt_hci_parse(opt);
1879 }
1880 } else if (strstart(opt, "vhci", &endp)) {
1881 if (!*endp || *endp == ',') {
1882 if (*endp) {
1883 if (strstart(endp, ",vlan=", &p)) {
1884 vlan = strtol(p, (char **) &endp, 0);
1885 if (*endp) {
1886 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1887 return 1;
1888 }
1889 } else {
1890 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1891 return 1;
1892 }
1893 } else
1894 vlan = 0;
1895
1896 bt_vhci_add(vlan);
1897 return 0;
1898 }
1899 } else if (strstart(opt, "device:", &endp))
1900 return !bt_device_add(endp);
1901
1902 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1903 return 1;
1904}
1905
1ae26a18
AZ
1906/***********************************************************/
1907/* QEMU Block devices */
1908
609497ab 1909#define HD_ALIAS "index=%d,media=disk"
e4bcb14c 1910#define CDROM_ALIAS "index=2,media=cdrom"
e4bcb14c 1911#define FD_ALIAS "index=%d,if=floppy"
609497ab
AZ
1912#define PFLASH_ALIAS "if=pflash"
1913#define MTD_ALIAS "if=mtd"
9d413d1d 1914#define SD_ALIAS "index=0,if=sd"
e4bcb14c 1915
9dfd7c7a 1916QemuOpts *drive_add(const char *file, const char *fmt, ...)
e4bcb14c
TS
1917{
1918 va_list ap;
9dfd7c7a
GH
1919 char optstr[1024];
1920 QemuOpts *opts;
e4bcb14c 1921
e4bcb14c 1922 va_start(ap, fmt);
9dfd7c7a 1923 vsnprintf(optstr, sizeof(optstr), fmt, ap);
e4bcb14c
TS
1924 va_end(ap);
1925
7282a033 1926 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
9dfd7c7a
GH
1927 if (!opts) {
1928 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1929 __FUNCTION__, optstr);
1930 return NULL;
1931 }
1932 if (file)
1933 qemu_opt_set(opts, "file", file);
1934 return opts;
b01b1111
AL
1935}
1936
751c6a17 1937DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
e4bcb14c 1938{
751c6a17 1939 DriveInfo *dinfo;
e4bcb14c
TS
1940
1941 /* seek interface, bus and unit */
1942
72cf2d4f 1943 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1944 if (dinfo->type == type &&
1945 dinfo->bus == bus &&
1946 dinfo->unit == unit)
1947 return dinfo;
1948 }
e4bcb14c 1949
751c6a17 1950 return NULL;
e4bcb14c
TS
1951}
1952
2e810b36 1953DriveInfo *drive_get_by_id(const char *id)
1dae12e6
GH
1954{
1955 DriveInfo *dinfo;
1956
72cf2d4f 1957 QTAILQ_FOREACH(dinfo, &drives, next) {
1dae12e6
GH
1958 if (strcmp(id, dinfo->id))
1959 continue;
1960 return dinfo;
1961 }
1962 return NULL;
1963}
1964
f60d39bc 1965int drive_get_max_bus(BlockInterfaceType type)
e4bcb14c
TS
1966{
1967 int max_bus;
751c6a17 1968 DriveInfo *dinfo;
e4bcb14c
TS
1969
1970 max_bus = -1;
72cf2d4f 1971 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1972 if(dinfo->type == type &&
1973 dinfo->bus > max_bus)
1974 max_bus = dinfo->bus;
e4bcb14c
TS
1975 }
1976 return max_bus;
1977}
1978
fa879c64
AL
1979const char *drive_get_serial(BlockDriverState *bdrv)
1980{
751c6a17 1981 DriveInfo *dinfo;
fa879c64 1982
72cf2d4f 1983 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1984 if (dinfo->bdrv == bdrv)
1985 return dinfo->serial;
1986 }
fa879c64
AL
1987
1988 return "\0";
1989}
1990
f7850099
KW
1991BlockInterfaceErrorAction drive_get_on_error(
1992 BlockDriverState *bdrv, int is_read)
428c5705 1993{
751c6a17 1994 DriveInfo *dinfo;
428c5705 1995
fc072ec4
KW
1996 if (is_read) {
1997 return BLOCK_ERR_REPORT;
1998 }
1999
72cf2d4f 2000 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17 2001 if (dinfo->bdrv == bdrv)
e9b2e818 2002 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
751c6a17 2003 }
428c5705 2004
e9b2e818 2005 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
428c5705
AL
2006}
2007
a1620fac
AJ
2008static void bdrv_format_print(void *opaque, const char *name)
2009{
2010 fprintf(stderr, " %s", name);
2011}
2012
56a14938 2013void drive_uninit(DriveInfo *dinfo)
b01b1111 2014{
56a14938
GH
2015 qemu_opts_del(dinfo->opts);
2016 bdrv_delete(dinfo->bdrv);
2017 QTAILQ_REMOVE(&drives, dinfo, next);
2018 qemu_free(dinfo);
b01b1111
AL
2019}
2020
e9b2e818
KW
2021static int parse_block_error_action(const char *buf, int is_read)
2022{
2023 if (!strcmp(buf, "ignore")) {
2024 return BLOCK_ERR_IGNORE;
2025 } else if (!is_read && !strcmp(buf, "enospc")) {
2026 return BLOCK_ERR_STOP_ENOSPC;
2027 } else if (!strcmp(buf, "stop")) {
2028 return BLOCK_ERR_STOP_ANY;
2029 } else if (!strcmp(buf, "report")) {
2030 return BLOCK_ERR_REPORT;
2031 } else {
2032 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2033 buf, is_read ? "read" : "write");
2034 return -1;
2035 }
2036}
2037
9dfd7c7a 2038DriveInfo *drive_init(QemuOpts *opts, void *opaque,
751c6a17 2039 int *fatal_error)
e4bcb14c 2040{
9dfd7c7a
GH
2041 const char *buf;
2042 const char *file = NULL;
c8522bdf 2043 char devname[128];
9dfd7c7a 2044 const char *serial;
c8522bdf 2045 const char *mediastr = "";
f60d39bc 2046 BlockInterfaceType type;
e4bcb14c
TS
2047 enum { MEDIA_DISK, MEDIA_CDROM } media;
2048 int bus_id, unit_id;
2049 int cyls, heads, secs, translation;
1e72d3b7 2050 BlockDriver *drv = NULL;
4d73cd3b 2051 QEMUMachine *machine = opaque;
e4bcb14c
TS
2052 int max_devs;
2053 int index;
33f00271 2054 int cache;
5c6c3a6c 2055 int aio = 0;
59f2689d 2056 int ro = 0;
e9b2e818
KW
2057 int bdrv_flags;
2058 int on_read_error, on_write_error;
c2cc47a4 2059 const char *devaddr;
751c6a17 2060 DriveInfo *dinfo;
9dfd7c7a 2061 int snapshot = 0;
e4bcb14c 2062
9dfd7c7a 2063 *fatal_error = 1;
e4bcb14c 2064
e4bcb14c 2065 translation = BIOS_ATA_TRANSLATION_AUTO;
0aa217e4 2066 cache = 1;
e4bcb14c 2067
4d007814 2068 if (machine && machine->use_scsi) {
f60d39bc 2069 type = IF_SCSI;
e4bcb14c 2070 max_devs = MAX_SCSI_DEVS;
363a37d5 2071 pstrcpy(devname, sizeof(devname), "scsi");
e4bcb14c 2072 } else {
f60d39bc 2073 type = IF_IDE;
e4bcb14c 2074 max_devs = MAX_IDE_DEVS;
363a37d5 2075 pstrcpy(devname, sizeof(devname), "ide");
e4bcb14c
TS
2076 }
2077 media = MEDIA_DISK;
2078
2079 /* extract parameters */
9dfd7c7a
GH
2080 bus_id = qemu_opt_get_number(opts, "bus", 0);
2081 unit_id = qemu_opt_get_number(opts, "unit", -1);
2082 index = qemu_opt_get_number(opts, "index", -1);
e4bcb14c 2083
9dfd7c7a
GH
2084 cyls = qemu_opt_get_number(opts, "cyls", 0);
2085 heads = qemu_opt_get_number(opts, "heads", 0);
2086 secs = qemu_opt_get_number(opts, "secs", 0);
e4bcb14c 2087
9dfd7c7a 2088 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
59f2689d 2089 ro = qemu_opt_get_bool(opts, "readonly", 0);
e4bcb14c 2090
9dfd7c7a
GH
2091 file = qemu_opt_get(opts, "file");
2092 serial = qemu_opt_get(opts, "serial");
2093
2094 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
ae45d369 2095 pstrcpy(devname, sizeof(devname), buf);
e4bcb14c 2096 if (!strcmp(buf, "ide")) {
f60d39bc 2097 type = IF_IDE;
e4bcb14c
TS
2098 max_devs = MAX_IDE_DEVS;
2099 } else if (!strcmp(buf, "scsi")) {
f60d39bc 2100 type = IF_SCSI;
e4bcb14c
TS
2101 max_devs = MAX_SCSI_DEVS;
2102 } else if (!strcmp(buf, "floppy")) {
f60d39bc 2103 type = IF_FLOPPY;
e4bcb14c
TS
2104 max_devs = 0;
2105 } else if (!strcmp(buf, "pflash")) {
f60d39bc 2106 type = IF_PFLASH;
e4bcb14c
TS
2107 max_devs = 0;
2108 } else if (!strcmp(buf, "mtd")) {
f60d39bc 2109 type = IF_MTD;
e4bcb14c
TS
2110 max_devs = 0;
2111 } else if (!strcmp(buf, "sd")) {
f60d39bc 2112 type = IF_SD;
e4bcb14c 2113 max_devs = 0;
6e02c38d
AL
2114 } else if (!strcmp(buf, "virtio")) {
2115 type = IF_VIRTIO;
2116 max_devs = 0;
62d23efa
AL
2117 } else if (!strcmp(buf, "xen")) {
2118 type = IF_XEN;
2119 max_devs = 0;
a8659e90
GH
2120 } else if (!strcmp(buf, "none")) {
2121 type = IF_NONE;
2122 max_devs = 0;
62d23efa 2123 } else {
9dfd7c7a 2124 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
751c6a17 2125 return NULL;
e4bcb14c
TS
2126 }
2127 }
2128
e4bcb14c 2129 if (cyls || heads || secs) {
5afe3f04 2130 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
9dfd7c7a 2131 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
751c6a17 2132 return NULL;
e4bcb14c 2133 }
5afe3f04 2134 if (heads < 1 || (type == IF_IDE && heads > 16)) {
9dfd7c7a 2135 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
751c6a17 2136 return NULL;
e4bcb14c 2137 }
5afe3f04 2138 if (secs < 1 || (type == IF_IDE && secs > 63)) {
9dfd7c7a 2139 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
751c6a17 2140 return NULL;
e4bcb14c
TS
2141 }
2142 }
2143
9dfd7c7a 2144 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
e4bcb14c
TS
2145 if (!cyls) {
2146 fprintf(stderr,
2147 "qemu: '%s' trans must be used with cyls,heads and secs\n",
9dfd7c7a 2148 buf);
751c6a17 2149 return NULL;
e4bcb14c
TS
2150 }
2151 if (!strcmp(buf, "none"))
2152 translation = BIOS_ATA_TRANSLATION_NONE;
2153 else if (!strcmp(buf, "lba"))
2154 translation = BIOS_ATA_TRANSLATION_LBA;
2155 else if (!strcmp(buf, "auto"))
2156 translation = BIOS_ATA_TRANSLATION_AUTO;
2157 else {
9dfd7c7a 2158 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
751c6a17 2159 return NULL;
e4bcb14c
TS
2160 }
2161 }
2162
9dfd7c7a 2163 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
e4bcb14c
TS
2164 if (!strcmp(buf, "disk")) {
2165 media = MEDIA_DISK;
2166 } else if (!strcmp(buf, "cdrom")) {
2167 if (cyls || secs || heads) {
2168 fprintf(stderr,
9dfd7c7a 2169 "qemu: '%s' invalid physical CHS format\n", buf);
751c6a17 2170 return NULL;
e4bcb14c
TS
2171 }
2172 media = MEDIA_CDROM;
2173 } else {
9dfd7c7a 2174 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
751c6a17 2175 return NULL;
e4bcb14c
TS
2176 }
2177 }
2178
9dfd7c7a 2179 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
9f7965c7 2180 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
33f00271 2181 cache = 0;
9f7965c7 2182 else if (!strcmp(buf, "writethrough"))
33f00271 2183 cache = 1;
9f7965c7
AL
2184 else if (!strcmp(buf, "writeback"))
2185 cache = 2;
33f00271
AZ
2186 else {
2187 fprintf(stderr, "qemu: invalid cache option\n");
751c6a17 2188 return NULL;
33f00271
AZ
2189 }
2190 }
2191
5c6c3a6c
CH
2192#ifdef CONFIG_LINUX_AIO
2193 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2194 if (!strcmp(buf, "threads"))
2195 aio = 0;
2196 else if (!strcmp(buf, "native"))
2197 aio = 1;
2198 else {
2199 fprintf(stderr, "qemu: invalid aio option\n");
2200 return NULL;
2201 }
2202 }
2203#endif
2204
9dfd7c7a 2205 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
a1620fac
AJ
2206 if (strcmp(buf, "?") == 0) {
2207 fprintf(stderr, "qemu: Supported formats:");
2208 bdrv_iterate_format(bdrv_format_print, NULL);
2209 fprintf(stderr, "\n");
751c6a17 2210 return NULL;
a1620fac 2211 }
eb852011 2212 drv = bdrv_find_whitelisted_format(buf);
1e72d3b7
AJ
2213 if (!drv) {
2214 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
751c6a17 2215 return NULL;
1e72d3b7
AJ
2216 }
2217 }
2218
e9b2e818 2219 on_write_error = BLOCK_ERR_STOP_ENOSPC;
9dfd7c7a 2220 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
869a5c6d 2221 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
ea8a5d7f 2222 fprintf(stderr, "werror is no supported by this format\n");
751c6a17 2223 return NULL;
428c5705 2224 }
e9b2e818
KW
2225
2226 on_write_error = parse_block_error_action(buf, 0);
2227 if (on_write_error < 0) {
2228 return NULL;
2229 }
2230 }
2231
2232 on_read_error = BLOCK_ERR_REPORT;
2233 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
f35d68f0 2234 if (type != IF_IDE && type != IF_VIRTIO) {
e9b2e818
KW
2235 fprintf(stderr, "rerror is no supported by this format\n");
2236 return NULL;
2237 }
2238
2239 on_read_error = parse_block_error_action(buf, 1);
2240 if (on_read_error < 0) {
751c6a17 2241 return NULL;
428c5705
AL
2242 }
2243 }
2244
9dfd7c7a 2245 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
c2cc47a4 2246 if (type != IF_VIRTIO) {
9dfd7c7a 2247 fprintf(stderr, "addr is not supported\n");
751c6a17 2248 return NULL;
c2cc47a4 2249 }
c2cc47a4
MA
2250 }
2251
e4bcb14c
TS
2252 /* compute bus and unit according index */
2253
2254 if (index != -1) {
2255 if (bus_id != 0 || unit_id != -1) {
2256 fprintf(stderr,
9dfd7c7a 2257 "qemu: index cannot be used with bus and unit\n");
751c6a17 2258 return NULL;
e4bcb14c
TS
2259 }
2260 if (max_devs == 0)
2261 {
2262 unit_id = index;
2263 bus_id = 0;
2264 } else {
2265 unit_id = index % max_devs;
2266 bus_id = index / max_devs;
2267 }
2268 }
2269
2270 /* if user doesn't specify a unit_id,
2271 * try to find the first free
2272 */
2273
2274 if (unit_id == -1) {
2275 unit_id = 0;
751c6a17 2276 while (drive_get(type, bus_id, unit_id) != NULL) {
e4bcb14c
TS
2277 unit_id++;
2278 if (max_devs && unit_id >= max_devs) {
2279 unit_id -= max_devs;
2280 bus_id++;
2281 }
2282 }
2283 }
2284
2285 /* check unit id */
2286
2287 if (max_devs && unit_id >= max_devs) {
9dfd7c7a
GH
2288 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2289 unit_id, max_devs - 1);
751c6a17 2290 return NULL;
e4bcb14c
TS
2291 }
2292
2293 /*
2294 * ignore multiple definitions
2295 */
2296
751c6a17
GH
2297 if (drive_get(type, bus_id, unit_id) != NULL) {
2298 *fatal_error = 0;
2299 return NULL;
2300 }
e4bcb14c
TS
2301
2302 /* init */
2303
751c6a17 2304 dinfo = qemu_mallocz(sizeof(*dinfo));
e23d9c4d 2305 if ((buf = qemu_opts_id(opts)) != NULL) {
9dfd7c7a
GH
2306 dinfo->id = qemu_strdup(buf);
2307 } else {
1dae12e6 2308 /* no id supplied -> create one */
9dfd7c7a 2309 dinfo->id = qemu_mallocz(32);
1dae12e6
GH
2310 if (type == IF_IDE || type == IF_SCSI)
2311 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2312 if (max_devs)
9dfd7c7a 2313 snprintf(dinfo->id, 32, "%s%i%s%i",
1dae12e6
GH
2314 devname, bus_id, mediastr, unit_id);
2315 else
9dfd7c7a 2316 snprintf(dinfo->id, 32, "%s%s%i",
1dae12e6
GH
2317 devname, mediastr, unit_id);
2318 }
1dae12e6 2319 dinfo->bdrv = bdrv_new(dinfo->id);
751c6a17
GH
2320 dinfo->devaddr = devaddr;
2321 dinfo->type = type;
2322 dinfo->bus = bus_id;
2323 dinfo->unit = unit_id;
e9b2e818
KW
2324 dinfo->on_read_error = on_read_error;
2325 dinfo->on_write_error = on_write_error;
9dfd7c7a
GH
2326 dinfo->opts = opts;
2327 if (serial)
2328 strncpy(dinfo->serial, serial, sizeof(serial));
72cf2d4f 2329 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
e4bcb14c 2330
f60d39bc 2331 switch(type) {
e4bcb14c
TS
2332 case IF_IDE:
2333 case IF_SCSI:
62d23efa 2334 case IF_XEN:
c219331e 2335 case IF_NONE:
e4bcb14c
TS
2336 switch(media) {
2337 case MEDIA_DISK:
2338 if (cyls != 0) {
1dae12e6
GH
2339 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2340 bdrv_set_translation_hint(dinfo->bdrv, translation);
e4bcb14c
TS
2341 }
2342 break;
2343 case MEDIA_CDROM:
1dae12e6 2344 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
e4bcb14c
TS
2345 break;
2346 }
2347 break;
2348 case IF_SD:
2349 /* FIXME: This isn't really a floppy, but it's a reasonable
2350 approximation. */
2351 case IF_FLOPPY:
1dae12e6 2352 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
e4bcb14c
TS
2353 break;
2354 case IF_PFLASH:
2355 case IF_MTD:
2356 break;
d176c495
GH
2357 case IF_VIRTIO:
2358 /* add virtio block device */
2359 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2360 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2361 qemu_opt_set(opts, "drive", dinfo->id);
2362 if (devaddr)
2363 qemu_opt_set(opts, "addr", devaddr);
2364 break;
aae9460e
PB
2365 case IF_COUNT:
2366 abort();
e4bcb14c 2367 }
9dfd7c7a 2368 if (!file) {
751c6a17
GH
2369 *fatal_error = 0;
2370 return NULL;
2371 }
33f00271 2372 bdrv_flags = 0;
9f7965c7 2373 if (snapshot) {
33f00271 2374 bdrv_flags |= BDRV_O_SNAPSHOT;
9f7965c7
AL
2375 cache = 2; /* always use write-back with snapshot */
2376 }
2377 if (cache == 0) /* no caching */
2378 bdrv_flags |= BDRV_O_NOCACHE;
2379 else if (cache == 2) /* write-back */
2380 bdrv_flags |= BDRV_O_CACHE_WB;
5c6c3a6c
CH
2381
2382 if (aio == 1) {
2383 bdrv_flags |= BDRV_O_NATIVE_AIO;
2384 } else {
2385 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2386 }
2387
59f2689d
NS
2388 if (ro == 1) {
2389 if (type == IF_IDE) {
2390 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2391 return NULL;
2392 }
2393 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2394 }
2395
1dae12e6 2396 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
850810d0
JF
2397 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2398 file, strerror(errno));
751c6a17 2399 return NULL;
e4bcb14c 2400 }
5c6c3a6c 2401
1dae12e6 2402 if (bdrv_key_required(dinfo->bdrv))
c0f4ce77 2403 autostart = 0;
751c6a17
GH
2404 *fatal_error = 0;
2405 return dinfo;
e4bcb14c
TS
2406}
2407
9dfd7c7a
GH
2408static int drive_init_func(QemuOpts *opts, void *opaque)
2409{
2410 QEMUMachine *machine = opaque;
2411 int fatal_error = 0;
2412
2413 if (drive_init(opts, machine, &fatal_error) == NULL) {
2414 if (fatal_error)
2415 return 1;
2416 }
2417 return 0;
2418}
2419
2420static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2421{
2422 if (NULL == qemu_opt_get(opts, "snapshot")) {
2423 qemu_opt_set(opts, "snapshot", "on");
2424 }
2425 return 0;
2426}
2427
76e30d0f
JK
2428void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2429{
2430 boot_set_handler = func;
2431 boot_set_opaque = opaque;
2432}
2433
2434int qemu_boot_set(const char *boot_devices)
2435{
2436 if (!boot_set_handler) {
2437 return -EINVAL;
2438 }
2439 return boot_set_handler(boot_set_opaque, boot_devices);
2440}
2441
ef3adf68
JK
2442static int parse_bootdevices(char *devices)
2443{
2444 /* We just do some generic consistency checks */
2445 const char *p;
2446 int bitmap = 0;
2447
2448 for (p = devices; *p != '\0'; p++) {
2449 /* Allowed boot devices are:
2450 * a-b: floppy disk drives
2451 * c-f: IDE disk drives
2452 * g-m: machine implementation dependant drives
2453 * n-p: network devices
2454 * It's up to each machine implementation to check if the given boot
2455 * devices match the actual hardware implementation and firmware
2456 * features.
2457 */
2458 if (*p < 'a' || *p > 'p') {
2459 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2460 exit(1);
2461 }
2462 if (bitmap & (1 << (*p - 'a'))) {
2463 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2464 exit(1);
2465 }
2466 bitmap |= 1 << (*p - 'a');
2467 }
2468 return bitmap;
2469}
2470
e0f084bf
JK
2471static void restore_boot_devices(void *opaque)
2472{
2473 char *standard_boot_devices = opaque;
2474
2475 qemu_boot_set(standard_boot_devices);
2476
2477 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2478 qemu_free(standard_boot_devices);
2479}
2480
268a362c
AL
2481static void numa_add(const char *optarg)
2482{
2483 char option[128];
2484 char *endptr;
2485 unsigned long long value, endvalue;
2486 int nodenr;
2487
2488 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2489 if (!strcmp(option, "node")) {
2490 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2491 nodenr = nb_numa_nodes;
2492 } else {
2493 nodenr = strtoull(option, NULL, 10);
2494 }
2495
2496 if (get_param_value(option, 128, "mem", optarg) == 0) {
2497 node_mem[nodenr] = 0;
2498 } else {
2499 value = strtoull(option, &endptr, 0);
2500 switch (*endptr) {
2501 case 0: case 'M': case 'm':
2502 value <<= 20;
2503 break;
2504 case 'G': case 'g':
2505 value <<= 30;
2506 break;
2507 }
2508 node_mem[nodenr] = value;
2509 }
2510 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2511 node_cpumask[nodenr] = 0;
2512 } else {
2513 value = strtoull(option, &endptr, 10);
2514 if (value >= 64) {
2515 value = 63;
2516 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2517 } else {
2518 if (*endptr == '-') {
2519 endvalue = strtoull(endptr+1, &endptr, 10);
2520 if (endvalue >= 63) {
2521 endvalue = 62;
2522 fprintf(stderr,
2523 "only 63 CPUs in NUMA mode supported.\n");
2524 }
2525 value = (1 << (endvalue + 1)) - (1 << value);
2526 } else {
2527 value = 1 << value;
2528 }
2529 }
2530 node_cpumask[nodenr] = value;
2531 }
2532 nb_numa_nodes++;
2533 }
2534 return;
2535}
2536
dc6b1c09
AP
2537static void smp_parse(const char *optarg)
2538{
2539 int smp, sockets = 0, threads = 0, cores = 0;
2540 char *endptr;
2541 char option[128];
2542
2543 smp = strtoul(optarg, &endptr, 10);
2544 if (endptr != optarg) {
2545 if (*endptr == ',') {
2546 endptr++;
2547 }
2548 }
2549 if (get_param_value(option, 128, "sockets", endptr) != 0)
2550 sockets = strtoull(option, NULL, 10);
2551 if (get_param_value(option, 128, "cores", endptr) != 0)
2552 cores = strtoull(option, NULL, 10);
2553 if (get_param_value(option, 128, "threads", endptr) != 0)
2554 threads = strtoull(option, NULL, 10);
2555 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2556 max_cpus = strtoull(option, NULL, 10);
2557
2558 /* compute missing values, prefer sockets over cores over threads */
2559 if (smp == 0 || sockets == 0) {
2560 sockets = sockets > 0 ? sockets : 1;
2561 cores = cores > 0 ? cores : 1;
2562 threads = threads > 0 ? threads : 1;
2563 if (smp == 0) {
2564 smp = cores * threads * sockets;
2565 } else {
2566 sockets = smp / (cores * threads);
2567 }
2568 } else {
2569 if (cores == 0) {
2570 threads = threads > 0 ? threads : 1;
2571 cores = smp / (sockets * threads);
2572 } else {
2573 if (sockets == 0) {
2574 sockets = smp / (cores * threads);
2575 } else {
2576 threads = smp / (cores * sockets);
2577 }
2578 }
2579 }
2580 smp_cpus = smp;
2581 smp_cores = cores > 0 ? cores : 1;
2582 smp_threads = threads > 0 ? threads : 1;
2583 if (max_cpus == 0)
2584 max_cpus = smp_cpus;
2585}
2586
a594cfbf
FB
2587/***********************************************************/
2588/* USB devices */
2589
c0f4ce77 2590static int usb_device_add(const char *devname, int is_hotplug)
a594cfbf
FB
2591{
2592 const char *p;
a5d2f727 2593 USBDevice *dev = NULL;
a594cfbf 2594
a5d2f727 2595 if (!usb_enabled)
a594cfbf
FB
2596 return -1;
2597
0958b4cc
GH
2598 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2599 dev = usbdevice_create(devname);
2600 if (dev)
2601 goto done;
2602
a5d2f727 2603 /* the other ones */
a594cfbf
FB
2604 if (strstart(devname, "host:", &p)) {
2605 dev = usb_host_device_open(p);
6c9f886c 2606 } else if (strstart(devname, "net:", &p)) {
13cf8f21
MM
2607 QemuOpts *opts;
2608 int idx;
6c9f886c 2609
13cf8f21
MM
2610 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2611 if (!opts) {
6c9f886c 2612 return -1;
13cf8f21
MM
2613 }
2614
2615 qemu_opt_set(opts, "type", "nic");
2616 qemu_opt_set(opts, "model", "usb");
2617
f6b134ac 2618 idx = net_client_init(NULL, opts, 0);
13cf8f21
MM
2619 if (idx == -1) {
2620 return -1;
2621 }
2622
2623 dev = usb_net_init(&nd_table[idx]);
dc72ac14
AZ
2624 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2625 dev = usb_bt_init(devname[2] ? hci_init(p) :
2626 bt_new_hci(qemu_find_bt_vlan(0)));
a594cfbf
FB
2627 } else {
2628 return -1;
2629 }
0d92ed30
PB
2630 if (!dev)
2631 return -1;
2632
a5d2f727 2633done:
a594cfbf
FB
2634 return 0;
2635}
2636
1f3870ab
AL
2637static int usb_device_del(const char *devname)
2638{
2639 int bus_num, addr;
2640 const char *p;
2641
5d0c5750
AL
2642 if (strstart(devname, "host:", &p))
2643 return usb_host_device_close(p);
2644
a5d2f727 2645 if (!usb_enabled)
1f3870ab
AL
2646 return -1;
2647
2648 p = strchr(devname, '.');
2649 if (!p)
2650 return -1;
2651 bus_num = strtoul(devname, NULL, 0);
2652 addr = strtoul(p + 1, NULL, 0);
2653
a5d2f727 2654 return usb_device_delete_addr(bus_num, addr);
1f3870ab
AL
2655}
2656
bd3c948d
GH
2657static int usb_parse(const char *cmdline)
2658{
2659 return usb_device_add(cmdline, 0);
2660}
2661
d54908a5 2662void do_usb_add(Monitor *mon, const QDict *qdict)
a594cfbf 2663{
d54908a5 2664 usb_device_add(qdict_get_str(qdict, "devname"), 1);
a594cfbf
FB
2665}
2666
d54908a5 2667void do_usb_del(Monitor *mon, const QDict *qdict)
a594cfbf 2668{
d54908a5 2669 usb_device_del(qdict_get_str(qdict, "devname"));
a594cfbf
FB
2670}
2671
201a51fc
AZ
2672/***********************************************************/
2673/* PCMCIA/Cardbus */
2674
2675static struct pcmcia_socket_entry_s {
bc24a225 2676 PCMCIASocket *socket;
201a51fc
AZ
2677 struct pcmcia_socket_entry_s *next;
2678} *pcmcia_sockets = 0;
2679
bc24a225 2680void pcmcia_socket_register(PCMCIASocket *socket)
201a51fc
AZ
2681{
2682 struct pcmcia_socket_entry_s *entry;
2683
2684 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2685 entry->socket = socket;
2686 entry->next = pcmcia_sockets;
2687 pcmcia_sockets = entry;
2688}
2689
bc24a225 2690void pcmcia_socket_unregister(PCMCIASocket *socket)
201a51fc
AZ
2691{
2692 struct pcmcia_socket_entry_s *entry, **ptr;
2693
2694 ptr = &pcmcia_sockets;
2695 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2696 if (entry->socket == socket) {
2697 *ptr = entry->next;
2698 qemu_free(entry);
2699 }
2700}
2701
376253ec 2702void pcmcia_info(Monitor *mon)
201a51fc
AZ
2703{
2704 struct pcmcia_socket_entry_s *iter;
376253ec 2705
201a51fc 2706 if (!pcmcia_sockets)
376253ec 2707 monitor_printf(mon, "No PCMCIA sockets\n");
201a51fc
AZ
2708
2709 for (iter = pcmcia_sockets; iter; iter = iter->next)
376253ec
AL
2710 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2711 iter->socket->attached ? iter->socket->card_string :
2712 "Empty");
201a51fc
AZ
2713}
2714
2ff89790 2715/***********************************************************/
3023f332
AL
2716/* register display */
2717
7b5d76da
AL
2718struct DisplayAllocator default_allocator = {
2719 defaultallocator_create_displaysurface,
2720 defaultallocator_resize_displaysurface,
2721 defaultallocator_free_displaysurface
2722};
2723
3023f332
AL
2724void register_displaystate(DisplayState *ds)
2725{
2726 DisplayState **s;
2727 s = &display_state;
2728 while (*s != NULL)
2729 s = &(*s)->next;
2730 ds->next = NULL;
2731 *s = ds;
2732}
2733
2734DisplayState *get_displaystate(void)
2735{
2736 return display_state;
2737}
2738
7b5d76da
AL
2739DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2740{
2741 if(ds->allocator == &default_allocator) ds->allocator = da;
2742 return ds->allocator;
2743}
2744
2ff89790
TS
2745/* dumb display */
2746
8f391ab4 2747static void dumb_display_init(void)
2ff89790 2748{
8f391ab4 2749 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
7b5d76da
AL
2750 ds->allocator = &default_allocator;
2751 ds->surface = qemu_create_displaysurface(ds, 640, 480);
8f391ab4 2752 register_displaystate(ds);
2ff89790
TS
2753}
2754
8a7ddc38
FB
2755/***********************************************************/
2756/* I/O handling */
0824d6fc 2757
c4b1fcc0
FB
2758typedef struct IOHandlerRecord {
2759 int fd;
7c9d8e07
FB
2760 IOCanRWHandler *fd_read_poll;
2761 IOHandler *fd_read;
2762 IOHandler *fd_write;
cafffd40 2763 int deleted;
c4b1fcc0
FB
2764 void *opaque;
2765 /* temporary data */
2766 struct pollfd *ufd;
8a7ddc38 2767 struct IOHandlerRecord *next;
c4b1fcc0
FB
2768} IOHandlerRecord;
2769
8a7ddc38 2770static IOHandlerRecord *first_io_handler;
c4b1fcc0 2771
7c9d8e07
FB
2772/* XXX: fd_read_poll should be suppressed, but an API change is
2773 necessary in the character devices to suppress fd_can_read(). */
5fafdf24
TS
2774int qemu_set_fd_handler2(int fd,
2775 IOCanRWHandler *fd_read_poll,
2776 IOHandler *fd_read,
2777 IOHandler *fd_write,
7c9d8e07 2778 void *opaque)
c4b1fcc0 2779{
7c9d8e07 2780 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 2781
7c9d8e07
FB
2782 if (!fd_read && !fd_write) {
2783 pioh = &first_io_handler;
2784 for(;;) {
2785 ioh = *pioh;
2786 if (ioh == NULL)
2787 break;
2788 if (ioh->fd == fd) {
cafffd40 2789 ioh->deleted = 1;
7c9d8e07
FB
2790 break;
2791 }
2792 pioh = &ioh->next;
2793 }
2794 } else {
2795 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2796 if (ioh->fd == fd)
2797 goto found;
2798 }
2799 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
7c9d8e07
FB
2800 ioh->next = first_io_handler;
2801 first_io_handler = ioh;
2802 found:
2803 ioh->fd = fd;
2804 ioh->fd_read_poll = fd_read_poll;
2805 ioh->fd_read = fd_read;
2806 ioh->fd_write = fd_write;
2807 ioh->opaque = opaque;
cafffd40 2808 ioh->deleted = 0;
7c9d8e07 2809 }
c4b1fcc0
FB
2810 return 0;
2811}
2812
5fafdf24
TS
2813int qemu_set_fd_handler(int fd,
2814 IOHandler *fd_read,
2815 IOHandler *fd_write,
7c9d8e07 2816 void *opaque)
8a7ddc38 2817{
7c9d8e07 2818 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
2819}
2820
56f3a5d0 2821#ifdef _WIN32
f331110f
FB
2822/***********************************************************/
2823/* Polling handling */
2824
2825typedef struct PollingEntry {
2826 PollingFunc *func;
2827 void *opaque;
2828 struct PollingEntry *next;
2829} PollingEntry;
2830
2831static PollingEntry *first_polling_entry;
2832
2833int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2834{
2835 PollingEntry **ppe, *pe;
2836 pe = qemu_mallocz(sizeof(PollingEntry));
f331110f
FB
2837 pe->func = func;
2838 pe->opaque = opaque;
2839 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2840 *ppe = pe;
2841 return 0;
2842}
2843
2844void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2845{
2846 PollingEntry **ppe, *pe;
2847 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2848 pe = *ppe;
2849 if (pe->func == func && pe->opaque == opaque) {
2850 *ppe = pe->next;
2851 qemu_free(pe);
2852 break;
2853 }
2854 }
2855}
2856
a18e524a
FB
2857/***********************************************************/
2858/* Wait objects support */
2859typedef struct WaitObjects {
2860 int num;
2861 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2862 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2863 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2864} WaitObjects;
2865
2866static WaitObjects wait_objects = {0};
3b46e624 2867
a18e524a
FB
2868int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2869{
2870 WaitObjects *w = &wait_objects;
2871
2872 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2873 return -1;
2874 w->events[w->num] = handle;
2875 w->func[w->num] = func;
2876 w->opaque[w->num] = opaque;
2877 w->num++;
2878 return 0;
2879}
2880
2881void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2882{
2883 int i, found;
2884 WaitObjects *w = &wait_objects;
2885
2886 found = 0;
2887 for (i = 0; i < w->num; i++) {
2888 if (w->events[i] == handle)
2889 found = 1;
2890 if (found) {
2891 w->events[i] = w->events[i + 1];
2892 w->func[i] = w->func[i + 1];
2893 w->opaque[i] = w->opaque[i + 1];
3b46e624 2894 }
a18e524a
FB
2895 }
2896 if (found)
2897 w->num--;
2898}
2899#endif
2900
8a7ddc38
FB
2901/***********************************************************/
2902/* ram save/restore */
2903
94fb0909 2904#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
475e4277
AL
2905#define RAM_SAVE_FLAG_COMPRESS 0x02
2906#define RAM_SAVE_FLAG_MEM_SIZE 0x04
2907#define RAM_SAVE_FLAG_PAGE 0x08
2908#define RAM_SAVE_FLAG_EOS 0x10
2909
2910static int is_dup_page(uint8_t *page, uint8_t ch)
8a7ddc38 2911{
475e4277
AL
2912 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2913 uint32_t *array = (uint32_t *)page;
2914 int i;
3b46e624 2915
475e4277
AL
2916 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2917 if (array[i] != val)
2918 return 0;
2919 }
2920
2921 return 1;
2922}
2923
2924static int ram_save_block(QEMUFile *f)
2925{
c227f099
AL
2926 static ram_addr_t current_addr = 0;
2927 ram_addr_t saved_addr = current_addr;
2928 ram_addr_t addr = 0;
475e4277
AL
2929 int found = 0;
2930
94a6b54f 2931 while (addr < last_ram_offset) {
475e4277 2932 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
5579c7f3 2933 uint8_t *p;
475e4277
AL
2934
2935 cpu_physical_memory_reset_dirty(current_addr,
2936 current_addr + TARGET_PAGE_SIZE,
2937 MIGRATION_DIRTY_FLAG);
2938
5579c7f3 2939 p = qemu_get_ram_ptr(current_addr);
475e4277 2940
5579c7f3 2941 if (is_dup_page(p, *p)) {
475e4277 2942 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
5579c7f3 2943 qemu_put_byte(f, *p);
475e4277
AL
2944 } else {
2945 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
5579c7f3 2946 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
c88676f8 2947 }
475e4277
AL
2948
2949 found = 1;
2950 break;
c88676f8 2951 }
475e4277 2952 addr += TARGET_PAGE_SIZE;
94a6b54f 2953 current_addr = (saved_addr + addr) % last_ram_offset;
8a7ddc38 2954 }
475e4277
AL
2955
2956 return found;
8a7ddc38
FB
2957}
2958
84307938 2959static uint64_t bytes_transferred;
475e4277 2960
c227f099 2961static ram_addr_t ram_save_remaining(void)
475e4277 2962{
c227f099
AL
2963 ram_addr_t addr;
2964 ram_addr_t count = 0;
475e4277 2965
94a6b54f 2966 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
2967 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2968 count++;
2969 }
2970
2971 return count;
2972}
2973
9f9e28cd
GC
2974uint64_t ram_bytes_remaining(void)
2975{
2976 return ram_save_remaining() * TARGET_PAGE_SIZE;
2977}
2978
2979uint64_t ram_bytes_transferred(void)
2980{
2981 return bytes_transferred;
2982}
2983
2984uint64_t ram_bytes_total(void)
2985{
2986 return last_ram_offset;
2987}
2988
f327aa0c 2989static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
475e4277 2990{
c227f099 2991 ram_addr_t addr;
a0a3fd60
GC
2992 uint64_t bytes_transferred_last;
2993 double bwidth = 0;
2994 uint64_t expected_time = 0;
475e4277 2995
4ec7fcc7
JK
2996 if (stage < 0) {
2997 cpu_physical_memory_set_dirty_tracking(0);
2998 return 0;
2999 }
3000
9fa06385 3001 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
b0a46a33
JK
3002 qemu_file_set_error(f);
3003 return 0;
3004 }
3005
475e4277 3006 if (stage == 1) {
84307938
JK
3007 bytes_transferred = 0;
3008
475e4277 3009 /* Make sure all dirty bits are set */
94a6b54f 3010 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
3011 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3012 cpu_physical_memory_set_dirty(addr);
3013 }
b0a46a33 3014
475e4277
AL
3015 /* Enable dirty memory tracking */
3016 cpu_physical_memory_set_dirty_tracking(1);
3017
94a6b54f 3018 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
475e4277
AL
3019 }
3020
a0a3fd60
GC
3021 bytes_transferred_last = bytes_transferred;
3022 bwidth = get_clock();
3023
475e4277
AL
3024 while (!qemu_file_rate_limit(f)) {
3025 int ret;
3026
3027 ret = ram_save_block(f);
9f9e28cd 3028 bytes_transferred += ret * TARGET_PAGE_SIZE;
475e4277
AL
3029 if (ret == 0) /* no more blocks */
3030 break;
3031 }
3032
a0a3fd60
GC
3033 bwidth = get_clock() - bwidth;
3034 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3035
3036 /* if we haven't transferred anything this round, force expected_time to a
3037 * a very high value, but without crashing */
3038 if (bwidth == 0)
3039 bwidth = 0.000001;
3040
475e4277 3041 /* try transferring iterative blocks of memory */
475e4277 3042 if (stage == 3) {
475e4277 3043 /* flush all remaining blocks regardless of rate limiting */
9f9e28cd
GC
3044 while (ram_save_block(f) != 0) {
3045 bytes_transferred += TARGET_PAGE_SIZE;
3046 }
8215e914 3047 cpu_physical_memory_set_dirty_tracking(0);
475e4277
AL
3048 }
3049
3050 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3051
a0a3fd60
GC
3052 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3053
3054 return (stage == 2) && (expected_time <= migrate_max_downtime());
475e4277
AL
3055}
3056
475e4277
AL
3057static int ram_load(QEMUFile *f, void *opaque, int version_id)
3058{
c227f099 3059 ram_addr_t addr;
475e4277
AL
3060 int flags;
3061
475e4277
AL
3062 if (version_id != 3)
3063 return -EINVAL;
3064
3065 do {
3066 addr = qemu_get_be64(f);
3067
3068 flags = addr & ~TARGET_PAGE_MASK;
3069 addr &= TARGET_PAGE_MASK;
3070
3071 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
94a6b54f 3072 if (addr != last_ram_offset)
475e4277
AL
3073 return -EINVAL;
3074 }
3075
475e4277
AL
3076 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3077 uint8_t ch = qemu_get_byte(f);
779c6bef
AL
3078 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3079#ifndef _WIN32
30868442
AL
3080 if (ch == 0 &&
3081 (!kvm_enabled() || kvm_has_sync_mmu())) {
3082 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
779c6bef 3083 }
30868442 3084#endif
9a743e5b 3085 } else if (flags & RAM_SAVE_FLAG_PAGE) {
5579c7f3 3086 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
9a743e5b
JK
3087 }
3088 if (qemu_file_has_error(f)) {
3089 return -EIO;
3090 }
475e4277
AL
3091 } while (!(flags & RAM_SAVE_FLAG_EOS));
3092
8a7ddc38
FB
3093 return 0;
3094}
3095
9e472e10
AL
3096void qemu_service_io(void)
3097{
d9f75a4e 3098 qemu_notify_event();
9e472e10
AL
3099}
3100
cc1daa40
FB
3101/***********************************************************/
3102/* machine registration */
3103
bdaf78e0 3104static QEMUMachine *first_machine = NULL;
6f338c34 3105QEMUMachine *current_machine = NULL;
cc1daa40
FB
3106
3107int qemu_register_machine(QEMUMachine *m)
3108{
3109 QEMUMachine **pm;
3110 pm = &first_machine;
3111 while (*pm != NULL)
3112 pm = &(*pm)->next;
3113 m->next = NULL;
3114 *pm = m;
3115 return 0;
3116}
3117
9596ebb7 3118static QEMUMachine *find_machine(const char *name)
cc1daa40
FB
3119{
3120 QEMUMachine *m;
3121
3122 for(m = first_machine; m != NULL; m = m->next) {
3123 if (!strcmp(m->name, name))
3124 return m;
3f6599e6
MM
3125 if (m->alias && !strcmp(m->alias, name))
3126 return m;
cc1daa40
FB
3127 }
3128 return NULL;
3129}
3130
0c257437
AL
3131static QEMUMachine *find_default_machine(void)
3132{
3133 QEMUMachine *m;
3134
3135 for(m = first_machine; m != NULL; m = m->next) {
3136 if (m->is_default) {
3137 return m;
3138 }
3139 }
3140 return NULL;
3141}
3142
8a7ddc38
FB
3143/***********************************************************/
3144/* main execution loop */
3145
9596ebb7 3146static void gui_update(void *opaque)
8a7ddc38 3147{
7d957bd8 3148 uint64_t interval = GUI_REFRESH_INTERVAL;
740733bb 3149 DisplayState *ds = opaque;
7d957bd8
AL
3150 DisplayChangeListener *dcl = ds->listeners;
3151
3152 dpy_refresh(ds);
3153
3154 while (dcl != NULL) {
3155 if (dcl->gui_timer_interval &&
3156 dcl->gui_timer_interval < interval)
3157 interval = dcl->gui_timer_interval;
3158 dcl = dcl->next;
3159 }
3160 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
8a7ddc38
FB
3161}
3162
9043b62d
BS
3163static void nographic_update(void *opaque)
3164{
3165 uint64_t interval = GUI_REFRESH_INTERVAL;
3166
3167 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3168}
3169
0bd48850
FB
3170struct vm_change_state_entry {
3171 VMChangeStateHandler *cb;
3172 void *opaque;
72cf2d4f 3173 QLIST_ENTRY (vm_change_state_entry) entries;
0bd48850
FB
3174};
3175
72cf2d4f 3176static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
0bd48850
FB
3177
3178VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3179 void *opaque)
3180{
3181 VMChangeStateEntry *e;
3182
3183 e = qemu_mallocz(sizeof (*e));
0bd48850
FB
3184
3185 e->cb = cb;
3186 e->opaque = opaque;
72cf2d4f 3187 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
0bd48850
FB
3188 return e;
3189}
3190
3191void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3192{
72cf2d4f 3193 QLIST_REMOVE (e, entries);
0bd48850
FB
3194 qemu_free (e);
3195}
3196
9781e040 3197static void vm_state_notify(int running, int reason)
0bd48850
FB
3198{
3199 VMChangeStateEntry *e;
3200
3201 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
9781e040 3202 e->cb(e->opaque, running, reason);
0bd48850
FB
3203 }
3204}
3205
d6dc3d42
AL
3206static void resume_all_vcpus(void);
3207static void pause_all_vcpus(void);
3208
8a7ddc38
FB
3209void vm_start(void)
3210{
3211 if (!vm_running) {
3212 cpu_enable_ticks();
3213 vm_running = 1;
9781e040 3214 vm_state_notify(1, 0);
efe75411 3215 qemu_rearm_alarm_timer(alarm_timer);
d6dc3d42 3216 resume_all_vcpus();
8a7ddc38
FB
3217 }
3218}
3219
bb0c6722
FB
3220/* reset/shutdown handler */
3221
3222typedef struct QEMUResetEntry {
72cf2d4f 3223 QTAILQ_ENTRY(QEMUResetEntry) entry;
bb0c6722
FB
3224 QEMUResetHandler *func;
3225 void *opaque;
bb0c6722
FB
3226} QEMUResetEntry;
3227
72cf2d4f
BS
3228static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3229 QTAILQ_HEAD_INITIALIZER(reset_handlers);
bb0c6722
FB
3230static int reset_requested;
3231static int shutdown_requested;
3475187d 3232static int powerdown_requested;
e568902a 3233static int debug_requested;
6e29f5da 3234static int vmstop_requested;
bb0c6722 3235
cf7a2fe2
AJ
3236int qemu_shutdown_requested(void)
3237{
3238 int r = shutdown_requested;
3239 shutdown_requested = 0;
3240 return r;
3241}
3242
3243int qemu_reset_requested(void)
3244{
3245 int r = reset_requested;
3246 reset_requested = 0;
3247 return r;
3248}
3249
3250int qemu_powerdown_requested(void)
3251{
3252 int r = powerdown_requested;
3253 powerdown_requested = 0;
3254 return r;
3255}
3256
e568902a
AL
3257static int qemu_debug_requested(void)
3258{
3259 int r = debug_requested;
3260 debug_requested = 0;
3261 return r;
3262}
3263
6e29f5da
AL
3264static int qemu_vmstop_requested(void)
3265{
3266 int r = vmstop_requested;
3267 vmstop_requested = 0;
3268 return r;
3269}
3270
3271static void do_vm_stop(int reason)
3272{
3273 if (vm_running) {
3274 cpu_disable_ticks();
3275 vm_running = 0;
d6dc3d42 3276 pause_all_vcpus();
6e29f5da
AL
3277 vm_state_notify(0, reason);
3278 }
3279}
3280
a08d4367 3281void qemu_register_reset(QEMUResetHandler *func, void *opaque)
bb0c6722 3282{
55ddfe8e 3283 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
bb0c6722 3284
bb0c6722
FB
3285 re->func = func;
3286 re->opaque = opaque;
72cf2d4f 3287 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
bb0c6722
FB
3288}
3289
dda9b29f 3290void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
bb0c6722
FB
3291{
3292 QEMUResetEntry *re;
3293
72cf2d4f 3294 QTAILQ_FOREACH(re, &reset_handlers, entry) {
dda9b29f 3295 if (re->func == func && re->opaque == opaque) {
72cf2d4f 3296 QTAILQ_REMOVE(&reset_handlers, re, entry);
dda9b29f
JK
3297 qemu_free(re);
3298 return;
3299 }
3300 }
3301}
3302
3303void qemu_system_reset(void)
3304{
3305 QEMUResetEntry *re, *nre;
3306
3307 /* reset all devices */
72cf2d4f 3308 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
bb0c6722
FB
3309 re->func(re->opaque);
3310 }
3311}
3312
3313void qemu_system_reset_request(void)
3314{
d1beab82
FB
3315 if (no_reboot) {
3316 shutdown_requested = 1;
3317 } else {
3318 reset_requested = 1;
3319 }
d9f75a4e 3320 qemu_notify_event();
bb0c6722
FB
3321}
3322
3323void qemu_system_shutdown_request(void)
3324{
3325 shutdown_requested = 1;
d9f75a4e 3326 qemu_notify_event();
bb0c6722
FB
3327}
3328
3475187d
FB
3329void qemu_system_powerdown_request(void)
3330{
3331 powerdown_requested = 1;
d9f75a4e
AL
3332 qemu_notify_event();
3333}
3334
d6dc3d42
AL
3335#ifdef CONFIG_IOTHREAD
3336static void qemu_system_vmstop_request(int reason)
d9f75a4e 3337{
d6dc3d42
AL
3338 vmstop_requested = reason;
3339 qemu_notify_event();
bb0c6722 3340}
d6dc3d42 3341#endif
bb0c6722 3342
50317c7f
AL
3343#ifndef _WIN32
3344static int io_thread_fd = -1;
3345
3346static void qemu_event_increment(void)
3fcf7b6b 3347{
50317c7f
AL
3348 static const char byte = 0;
3349
3350 if (io_thread_fd == -1)
3351 return;
3352
3353 write(io_thread_fd, &byte, sizeof(byte));
3354}
3355
3356static void qemu_event_read(void *opaque)
3357{
3358 int fd = (unsigned long)opaque;
3359 ssize_t len;
3360
3361 /* Drain the notify pipe */
3362 do {
3363 char buffer[512];
3364 len = read(fd, buffer, sizeof(buffer));
3365 } while ((len == -1 && errno == EINTR) || len > 0);
3366}
3367
3368static int qemu_event_init(void)
3369{
3370 int err;
3371 int fds[2];
3372
40ff6d7e 3373 err = qemu_pipe(fds);
50317c7f
AL
3374 if (err == -1)
3375 return -errno;
3376
3377 err = fcntl_setfl(fds[0], O_NONBLOCK);
3378 if (err < 0)
3379 goto fail;
3380
3381 err = fcntl_setfl(fds[1], O_NONBLOCK);
3382 if (err < 0)
3383 goto fail;
3384
3385 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3386 (void *)(unsigned long)fds[0]);
3387
3388 io_thread_fd = fds[1];
a7e21219
JK
3389 return 0;
3390
50317c7f
AL
3391fail:
3392 close(fds[0]);
3393 close(fds[1]);
3394 return err;
3395}
3396#else
3397HANDLE qemu_event_handle;
3398
3399static void dummy_event_handler(void *opaque)
3400{
3401}
3402
3403static int qemu_event_init(void)
3404{
3405 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3406 if (!qemu_event_handle) {
20889d4e 3407 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
50317c7f
AL
3408 return -1;
3409 }
3410 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3fcf7b6b
AL
3411 return 0;
3412}
3413
50317c7f
AL
3414static void qemu_event_increment(void)
3415{
de1c90cf 3416 if (!SetEvent(qemu_event_handle)) {
20889d4e 3417 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
de1c90cf 3418 GetLastError());
3419 exit (1);
3420 }
50317c7f
AL
3421}
3422#endif
3423
d6dc3d42
AL
3424static int cpu_can_run(CPUState *env)
3425{
3426 if (env->stop)
3427 return 0;
3428 if (env->stopped)
3429 return 0;
3430 return 1;
3431}
3432
3433#ifndef CONFIG_IOTHREAD
50317c7f
AL
3434static int qemu_init_main_loop(void)
3435{
3436 return qemu_event_init();
3437}
3438
0bf46a40
AL
3439void qemu_init_vcpu(void *_env)
3440{
3441 CPUState *env = _env;
3442
3443 if (kvm_enabled())
3444 kvm_init_vcpu(env);
dc6b1c09
AP
3445 env->nr_cores = smp_cores;
3446 env->nr_threads = smp_threads;
0bf46a40
AL
3447 return;
3448}
3449
8edac960
AL
3450int qemu_cpu_self(void *env)
3451{
3452 return 1;
3453}
3454
d6dc3d42
AL
3455static void resume_all_vcpus(void)
3456{
3457}
3458
3459static void pause_all_vcpus(void)
3460{
3461}
3462
8edac960
AL
3463void qemu_cpu_kick(void *env)
3464{
3465 return;
3466}
3467
d6dc3d42
AL
3468void qemu_notify_event(void)
3469{
3470 CPUState *env = cpu_single_env;
3471
3472 if (env) {
3473 cpu_exit(env);
4a1418e0 3474 }
d6dc3d42
AL
3475}
3476
d549db5a
GC
3477void qemu_mutex_lock_iothread(void) {}
3478void qemu_mutex_unlock_iothread(void) {}
4870852c 3479
6e29f5da
AL
3480void vm_stop(int reason)
3481{
3482 do_vm_stop(reason);
3483}
3484
d6dc3d42
AL
3485#else /* CONFIG_IOTHREAD */
3486
3487#include "qemu-thread.h"
3488
3489QemuMutex qemu_global_mutex;
3490static QemuMutex qemu_fair_mutex;
3491
3492static QemuThread io_thread;
3493
3494static QemuThread *tcg_cpu_thread;
3495static QemuCond *tcg_halt_cond;
3496
3497static int qemu_system_ready;
3498/* cpu creation */
3499static QemuCond qemu_cpu_cond;
3500/* system init */
3501static QemuCond qemu_system_cond;
3502static QemuCond qemu_pause_cond;
3503
3504static void block_io_signals(void);
3505static void unblock_io_signals(void);
3506static int tcg_has_work(void);
3507
3508static int qemu_init_main_loop(void)
3509{
3510 int ret;
3511
3512 ret = qemu_event_init();
3513 if (ret)
3514 return ret;
3515
3516 qemu_cond_init(&qemu_pause_cond);
3517 qemu_mutex_init(&qemu_fair_mutex);
3518 qemu_mutex_init(&qemu_global_mutex);
3519 qemu_mutex_lock(&qemu_global_mutex);
3520
3521 unblock_io_signals();
3522 qemu_thread_self(&io_thread);
3523
3524 return 0;
3525}
3526
3527static void qemu_wait_io_event(CPUState *env)
3528{
3529 while (!tcg_has_work())
3530 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3531
3532 qemu_mutex_unlock(&qemu_global_mutex);
3533
3534 /*
3535 * Users of qemu_global_mutex can be starved, having no chance
3536 * to acquire it since this path will get to it first.
3537 * So use another lock to provide fairness.
3538 */
3539 qemu_mutex_lock(&qemu_fair_mutex);
3540 qemu_mutex_unlock(&qemu_fair_mutex);
3541
3542 qemu_mutex_lock(&qemu_global_mutex);
3543 if (env->stop) {
3544 env->stop = 0;
3545 env->stopped = 1;
3546 qemu_cond_signal(&qemu_pause_cond);
3547 }
3548}
3549
3550static int qemu_cpu_exec(CPUState *env);
3551
3552static void *kvm_cpu_thread_fn(void *arg)
3553{
3554 CPUState *env = arg;
3555
3556 block_io_signals();
3557 qemu_thread_self(env->thread);
321c1cb1
JCD
3558 if (kvm_enabled())
3559 kvm_init_vcpu(env);
d6dc3d42
AL
3560
3561 /* signal CPU creation */
3562 qemu_mutex_lock(&qemu_global_mutex);
3563 env->created = 1;
3564 qemu_cond_signal(&qemu_cpu_cond);
3565
3566 /* and wait for machine initialization */
3567 while (!qemu_system_ready)
3568 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3569
3570 while (1) {
3571 if (cpu_can_run(env))
3572 qemu_cpu_exec(env);
1c3173b9 3573 qemu_wait_io_event(env);
d6dc3d42
AL
3574 }
3575
3576 return NULL;
3577}
3578
3579static void tcg_cpu_exec(void);
3580
3581static void *tcg_cpu_thread_fn(void *arg)
3582{
3583 CPUState *env = arg;
3584
3585 block_io_signals();
3586 qemu_thread_self(env->thread);
3587
3588 /* signal CPU creation */
3589 qemu_mutex_lock(&qemu_global_mutex);
3590 for (env = first_cpu; env != NULL; env = env->next_cpu)
3591 env->created = 1;
3592 qemu_cond_signal(&qemu_cpu_cond);
3593
3594 /* and wait for machine initialization */
3595 while (!qemu_system_ready)
3596 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3597
3598 while (1) {
3599 tcg_cpu_exec();
3600 qemu_wait_io_event(cur_cpu);
3601 }
3602
3603 return NULL;
3604}
3605
3606void qemu_cpu_kick(void *_env)
3607{
3608 CPUState *env = _env;
3609 qemu_cond_broadcast(env->halt_cond);
3610 if (kvm_enabled())
3611 qemu_thread_signal(env->thread, SIGUSR1);
3612}
3613
e5bc201d 3614int qemu_cpu_self(void *_env)
d6dc3d42 3615{
e5bc201d
GC
3616 CPUState *env = _env;
3617 QemuThread this;
3618
3619 qemu_thread_self(&this);
3620
3621 return qemu_thread_equal(&this, env->thread);
d6dc3d42
AL
3622}
3623
3624static void cpu_signal(int sig)
3625{
3626 if (cpu_single_env)
3627 cpu_exit(cpu_single_env);
3628}
3629
3630static void block_io_signals(void)
3631{
3632 sigset_t set;
3633 struct sigaction sigact;
3634
3635 sigemptyset(&set);
3636 sigaddset(&set, SIGUSR2);
3637 sigaddset(&set, SIGIO);
3638 sigaddset(&set, SIGALRM);
3639 pthread_sigmask(SIG_BLOCK, &set, NULL);
3640
3641 sigemptyset(&set);
3642 sigaddset(&set, SIGUSR1);
3643 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3644
3645 memset(&sigact, 0, sizeof(sigact));
3646 sigact.sa_handler = cpu_signal;
3647 sigaction(SIGUSR1, &sigact, NULL);
3648}
3649
3650static void unblock_io_signals(void)
3651{
3652 sigset_t set;
3653
3654 sigemptyset(&set);
3655 sigaddset(&set, SIGUSR2);
3656 sigaddset(&set, SIGIO);
3657 sigaddset(&set, SIGALRM);
3658 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3659
3660 sigemptyset(&set);
3661 sigaddset(&set, SIGUSR1);
3662 pthread_sigmask(SIG_BLOCK, &set, NULL);
3663}
3664
3665static void qemu_signal_lock(unsigned int msecs)
3666{
3667 qemu_mutex_lock(&qemu_fair_mutex);
3668
3669 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3670 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3671 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3672 break;
3673 }
3674 qemu_mutex_unlock(&qemu_fair_mutex);
3675}
3676
d549db5a 3677void qemu_mutex_lock_iothread(void)
d6dc3d42
AL
3678{
3679 if (kvm_enabled()) {
3680 qemu_mutex_lock(&qemu_fair_mutex);
3681 qemu_mutex_lock(&qemu_global_mutex);
3682 qemu_mutex_unlock(&qemu_fair_mutex);
3683 } else
3684 qemu_signal_lock(100);
3685}
3686
d549db5a 3687void qemu_mutex_unlock_iothread(void)
d6dc3d42
AL
3688{
3689 qemu_mutex_unlock(&qemu_global_mutex);
3690}
3691
3692static int all_vcpus_paused(void)
3693{
3694 CPUState *penv = first_cpu;
3695
3696 while (penv) {
3697 if (!penv->stopped)
3698 return 0;
3699 penv = (CPUState *)penv->next_cpu;
3700 }
3701
3702 return 1;
3703}
3704
3705static void pause_all_vcpus(void)
3706{
3707 CPUState *penv = first_cpu;
3708
3709 while (penv) {
3710 penv->stop = 1;
3711 qemu_thread_signal(penv->thread, SIGUSR1);
3712 qemu_cpu_kick(penv);
3713 penv = (CPUState *)penv->next_cpu;
3714 }
3715
3716 while (!all_vcpus_paused()) {
3717 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3718 penv = first_cpu;
3719 while (penv) {
3720 qemu_thread_signal(penv->thread, SIGUSR1);
3721 penv = (CPUState *)penv->next_cpu;
3722 }
3723 }
3724}
3725
3726static void resume_all_vcpus(void)
3727{
3728 CPUState *penv = first_cpu;
3729
3730 while (penv) {
3731 penv->stop = 0;
3732 penv->stopped = 0;
3733 qemu_thread_signal(penv->thread, SIGUSR1);
3734 qemu_cpu_kick(penv);
3735 penv = (CPUState *)penv->next_cpu;
3736 }
3737}
3738
3739static void tcg_init_vcpu(void *_env)
3740{
3741 CPUState *env = _env;
3742 /* share a single thread for all cpus with TCG */
3743 if (!tcg_cpu_thread) {
3744 env->thread = qemu_mallocz(sizeof(QemuThread));
3745 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3746 qemu_cond_init(env->halt_cond);
3747 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3748 while (env->created == 0)
3749 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3750 tcg_cpu_thread = env->thread;
3751 tcg_halt_cond = env->halt_cond;
3752 } else {
3753 env->thread = tcg_cpu_thread;
3754 env->halt_cond = tcg_halt_cond;
3755 }
3756}
3757
3758static void kvm_start_vcpu(CPUState *env)
3759{
d6dc3d42
AL
3760 env->thread = qemu_mallocz(sizeof(QemuThread));
3761 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3762 qemu_cond_init(env->halt_cond);
3763 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3764 while (env->created == 0)
3765 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3766}
3767
3768void qemu_init_vcpu(void *_env)
3769{
3770 CPUState *env = _env;
3771
3772 if (kvm_enabled())
3773 kvm_start_vcpu(env);
3774 else
3775 tcg_init_vcpu(env);
dc6b1c09
AP
3776 env->nr_cores = smp_cores;
3777 env->nr_threads = smp_threads;
d6dc3d42
AL
3778}
3779
3780void qemu_notify_event(void)
3781{
3782 qemu_event_increment();
3783}
3784
3785void vm_stop(int reason)
3786{
3787 QemuThread me;
3788 qemu_thread_self(&me);
3789
3790 if (!qemu_thread_equal(&me, &io_thread)) {
3791 qemu_system_vmstop_request(reason);
3792 /*
3793 * FIXME: should not return to device code in case
3794 * vm_stop() has been requested.
3795 */
3796 if (cpu_single_env) {
3797 cpu_exit(cpu_single_env);
3798 cpu_single_env->stop = 1;
3799 }
3800 return;
3801 }
3802 do_vm_stop(reason);
3803}
3804
3805#endif
3806
3807
877cf882 3808#ifdef _WIN32
69d6451c 3809static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3810{
3811 int ret, ret2, i;
f331110f
FB
3812 PollingEntry *pe;
3813
c4b1fcc0 3814
f331110f
FB
3815 /* XXX: need to suppress polling by better using win32 events */
3816 ret = 0;
3817 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3818 ret |= pe->func(pe->opaque);
3819 }
e6b1e558 3820 if (ret == 0) {
a18e524a
FB
3821 int err;
3822 WaitObjects *w = &wait_objects;
3b46e624 3823
56f3a5d0 3824 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
a18e524a
FB
3825 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3826 if (w->func[ret - WAIT_OBJECT_0])
3827 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3b46e624 3828
5fafdf24 3829 /* Check for additional signaled events */
e6b1e558 3830 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3b46e624 3831
e6b1e558
TS
3832 /* Check if event is signaled */
3833 ret2 = WaitForSingleObject(w->events[i], 0);
3834 if(ret2 == WAIT_OBJECT_0) {
3835 if (w->func[i])
3836 w->func[i](w->opaque[i]);
3837 } else if (ret2 == WAIT_TIMEOUT) {
3838 } else {
3839 err = GetLastError();
3840 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3b46e624
TS
3841 }
3842 }
a18e524a
FB
3843 } else if (ret == WAIT_TIMEOUT) {
3844 } else {
3845 err = GetLastError();
e6b1e558 3846 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 3847 }
f331110f 3848 }
56f3a5d0
AL
3849
3850 *timeout = 0;
3851}
3852#else
69d6451c 3853static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3854{
3855}
fd1dff4b 3856#endif
56f3a5d0
AL
3857
3858void main_loop_wait(int timeout)
3859{
3860 IOHandlerRecord *ioh;
3861 fd_set rfds, wfds, xfds;
3862 int ret, nfds;
3863 struct timeval tv;
3864
3865 qemu_bh_update_timeout(&timeout);
3866
3867 host_main_loop_wait(&timeout);
3868
fd1dff4b
FB
3869 /* poll any events */
3870 /* XXX: separate device handlers from system ones */
6abfbd79 3871 nfds = -1;
fd1dff4b
FB
3872 FD_ZERO(&rfds);
3873 FD_ZERO(&wfds);
e035649e 3874 FD_ZERO(&xfds);
fd1dff4b 3875 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
3876 if (ioh->deleted)
3877 continue;
fd1dff4b
FB
3878 if (ioh->fd_read &&
3879 (!ioh->fd_read_poll ||
3880 ioh->fd_read_poll(ioh->opaque) != 0)) {
3881 FD_SET(ioh->fd, &rfds);
3882 if (ioh->fd > nfds)
3883 nfds = ioh->fd;
3884 }
3885 if (ioh->fd_write) {
3886 FD_SET(ioh->fd, &wfds);
3887 if (ioh->fd > nfds)
3888 nfds = ioh->fd;
3889 }
3890 }
3b46e624 3891
56f3a5d0
AL
3892 tv.tv_sec = timeout / 1000;
3893 tv.tv_usec = (timeout % 1000) * 1000;
3894
d918f23e
JK
3895 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3896
4870852c 3897 qemu_mutex_unlock_iothread();
e035649e 3898 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4870852c 3899 qemu_mutex_lock_iothread();
fd1dff4b 3900 if (ret > 0) {
cafffd40
TS
3901 IOHandlerRecord **pioh;
3902
3903 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6ab43fdc 3904 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
fd1dff4b 3905 ioh->fd_read(ioh->opaque);
7c9d8e07 3906 }
6ab43fdc 3907 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
fd1dff4b 3908 ioh->fd_write(ioh->opaque);
c4b1fcc0 3909 }
b4608c04 3910 }
cafffd40
TS
3911
3912 /* remove deleted IO handlers */
3913 pioh = &first_io_handler;
3914 while (*pioh) {
3915 ioh = *pioh;
3916 if (ioh->deleted) {
3917 *pioh = ioh->next;
3918 qemu_free(ioh);
5fafdf24 3919 } else
cafffd40
TS
3920 pioh = &ioh->next;
3921 }
fd1dff4b 3922 }
d918f23e
JK
3923
3924 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
b4608c04 3925
50317c7f
AL
3926 /* rearm timer, if not periodic */
3927 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3928 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3929 qemu_rearm_alarm_timer(alarm_timer);
3930 }
3931
357c692c 3932 /* vm time timers */
d6dc3d42
AL
3933 if (vm_running) {
3934 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
0fdddf80
JK
3935 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3936 qemu_get_clock(vm_clock));
d6dc3d42 3937 }
357c692c
AL
3938
3939 /* real time timers */
0fdddf80 3940 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
357c692c
AL
3941 qemu_get_clock(rt_clock));
3942
21d5d12b
JK
3943 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3944 qemu_get_clock(host_clock));
3945
423f0742
PB
3946 /* Check bottom-halves last in case any of the earlier events triggered
3947 them. */
3948 qemu_bh_poll();
3b46e624 3949
5905b2e5
FB
3950}
3951
43b96858 3952static int qemu_cpu_exec(CPUState *env)
5905b2e5 3953{
43b96858 3954 int ret;
89bfc105
FB
3955#ifdef CONFIG_PROFILER
3956 int64_t ti;
3957#endif
5905b2e5 3958
89bfc105 3959#ifdef CONFIG_PROFILER
43b96858 3960 ti = profile_getclock();
89bfc105 3961#endif
43b96858
AL
3962 if (use_icount) {
3963 int64_t count;
3964 int decr;
3965 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3966 env->icount_decr.u16.low = 0;
3967 env->icount_extra = 0;
3968 count = qemu_next_deadline();
3969 count = (count + (1 << icount_time_shift) - 1)
3970 >> icount_time_shift;
3971 qemu_icount += count;
3972 decr = (count > 0xffff) ? 0xffff : count;
3973 count -= decr;
3974 env->icount_decr.u16.low = decr;
3975 env->icount_extra = count;
3976 }
3977 ret = cpu_exec(env);
89bfc105 3978#ifdef CONFIG_PROFILER
43b96858 3979 qemu_time += profile_getclock() - ti;
89bfc105 3980#endif
43b96858
AL
3981 if (use_icount) {
3982 /* Fold pending instructions back into the
3983 instruction counter, and clear the interrupt flag. */
3984 qemu_icount -= (env->icount_decr.u16.low
3985 + env->icount_extra);
3986 env->icount_decr.u32 = 0;
3987 env->icount_extra = 0;
3988 }
3989 return ret;
3990}
3991
e6e35b1e
AL
3992static void tcg_cpu_exec(void)
3993{
d6dc3d42 3994 int ret = 0;
e6e35b1e
AL
3995
3996 if (next_cpu == NULL)
3997 next_cpu = first_cpu;
3998 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3999 CPUState *env = cur_cpu = next_cpu;
4000
4001 if (!vm_running)
4002 break;
4003 if (timer_alarm_pending) {
4004 timer_alarm_pending = 0;
4005 break;
4006 }
d6dc3d42
AL
4007 if (cpu_can_run(env))
4008 ret = qemu_cpu_exec(env);
e6e35b1e
AL
4009 if (ret == EXCP_DEBUG) {
4010 gdb_set_stop_cpu(env);
4011 debug_requested = 1;
4012 break;
4013 }
4014 }
4015}
4016
43b96858
AL
4017static int cpu_has_work(CPUState *env)
4018{
d6dc3d42
AL
4019 if (env->stop)
4020 return 1;
4021 if (env->stopped)
4022 return 0;
43b96858
AL
4023 if (!env->halted)
4024 return 1;
4025 if (qemu_cpu_has_work(env))
4026 return 1;
4027 return 0;
4028}
4029
4030static int tcg_has_work(void)
4031{
4032 CPUState *env;
4033
4034 for (env = first_cpu; env != NULL; env = env->next_cpu)
4035 if (cpu_has_work(env))
4036 return 1;
4037 return 0;
4038}
4039
4040static int qemu_calculate_timeout(void)
4041{
b319820d 4042#ifndef CONFIG_IOTHREAD
43b96858
AL
4043 int timeout;
4044
4045 if (!vm_running)
4046 timeout = 5000;
4047 else if (tcg_has_work())
4048 timeout = 0;
4049 else if (!use_icount)
4050 timeout = 5000;
4051 else {
4052 /* XXX: use timeout computed from timers */
4053 int64_t add;
4054 int64_t delta;
4055 /* Advance virtual time to the next event. */
4056 if (use_icount == 1) {
4057 /* When not using an adaptive execution frequency
4058 we tend to get badly out of sync with real time,
4059 so just delay for a reasonable amount of time. */
4060 delta = 0;
4061 } else {
4062 delta = cpu_get_icount() - cpu_get_clock();
4063 }
4064 if (delta > 0) {
4065 /* If virtual time is ahead of real time then just
4066 wait for IO. */
4067 timeout = (delta / 1000000) + 1;
4068 } else {
4069 /* Wait for either IO to occur or the next
4070 timer event. */
4071 add = qemu_next_deadline();
4072 /* We advance the timer before checking for IO.
4073 Limit the amount we advance so that early IO
4074 activity won't get the guest too far ahead. */
4075 if (add > 10000000)
4076 add = 10000000;
4077 delta += add;
4078 add = (add + (1 << icount_time_shift) - 1)
4079 >> icount_time_shift;
4080 qemu_icount += add;
4081 timeout = delta / 1000000;
4082 if (timeout < 0)
4083 timeout = 0;
4084 }
4085 }
4086
4087 return timeout;
b319820d
LC
4088#else /* CONFIG_IOTHREAD */
4089 return 1000;
4090#endif
43b96858
AL
4091}
4092
4093static int vm_can_run(void)
4094{
4095 if (powerdown_requested)
4096 return 0;
4097 if (reset_requested)
4098 return 0;
4099 if (shutdown_requested)
4100 return 0;
e568902a
AL
4101 if (debug_requested)
4102 return 0;
43b96858
AL
4103 return 1;
4104}
4105
d9c32310
BS
4106qemu_irq qemu_system_powerdown;
4107
43b96858
AL
4108static void main_loop(void)
4109{
6e29f5da 4110 int r;
e6e35b1e 4111
d6dc3d42
AL
4112#ifdef CONFIG_IOTHREAD
4113 qemu_system_ready = 1;
4114 qemu_cond_broadcast(&qemu_system_cond);
4115#endif
4116
6e29f5da 4117 for (;;) {
43b96858 4118 do {
e6e35b1e
AL
4119#ifdef CONFIG_PROFILER
4120 int64_t ti;
4121#endif
d6dc3d42 4122#ifndef CONFIG_IOTHREAD
e6e35b1e 4123 tcg_cpu_exec();
d6dc3d42 4124#endif
89bfc105 4125#ifdef CONFIG_PROFILER
43b96858 4126 ti = profile_getclock();
89bfc105 4127#endif
43b96858 4128 main_loop_wait(qemu_calculate_timeout());
89bfc105 4129#ifdef CONFIG_PROFILER
43b96858 4130 dev_time += profile_getclock() - ti;
89bfc105 4131#endif
e568902a 4132 } while (vm_can_run());
43b96858 4133
b1a15e7e 4134 if (qemu_debug_requested()) {
242cd003 4135 monitor_protocol_event(QEVENT_DEBUG, NULL);
e568902a 4136 vm_stop(EXCP_DEBUG);
b1a15e7e 4137 }
43b96858 4138 if (qemu_shutdown_requested()) {
242cd003 4139 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
43b96858
AL
4140 if (no_shutdown) {
4141 vm_stop(0);
4142 no_shutdown = 0;
4143 } else
4144 break;
4145 }
d6dc3d42 4146 if (qemu_reset_requested()) {
242cd003 4147 monitor_protocol_event(QEVENT_RESET, NULL);
d6dc3d42 4148 pause_all_vcpus();
43b96858 4149 qemu_system_reset();
d6dc3d42
AL
4150 resume_all_vcpus();
4151 }
d9c32310 4152 if (qemu_powerdown_requested()) {
242cd003 4153 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
d9c32310
BS
4154 qemu_irq_raise(qemu_system_powerdown);
4155 }
b1a15e7e 4156 if ((r = qemu_vmstop_requested())) {
242cd003 4157 monitor_protocol_event(QEVENT_STOP, NULL);
6e29f5da 4158 vm_stop(r);
b1a15e7e 4159 }
b4608c04 4160 }
d6dc3d42 4161 pause_all_vcpus();
b4608c04
FB
4162}
4163
9bd7e6d9
PB
4164static void version(void)
4165{
4a19f1ec 4166 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
9bd7e6d9
PB
4167}
4168
15f82208 4169static void help(int exitcode)
0824d6fc 4170{
9bd7e6d9
PB
4171 version();
4172 printf("usage: %s [options] [disk_image]\n"
0824d6fc 4173 "\n"
a20dd508 4174 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 4175 "\n"
5824d651
BS
4176#define DEF(option, opt_arg, opt_enum, opt_help) \
4177 opt_help
4178#define DEFHEADING(text) stringify(text) "\n"
4179#include "qemu-options.h"
4180#undef DEF
4181#undef DEFHEADING
4182#undef GEN_DOCS
0824d6fc 4183 "\n"
82c643ff 4184 "During emulation, the following keys are useful:\n"
032a8c9e
FB
4185 "ctrl-alt-f toggle full screen\n"
4186 "ctrl-alt-n switch to virtual console 'n'\n"
4187 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
4188 "\n"
4189 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4190 ,
0db63474 4191 "qemu",
a00bad7e 4192 DEFAULT_RAM_SIZE,
7c9d8e07 4193#ifndef _WIN32
a00bad7e 4194 DEFAULT_NETWORK_SCRIPT,
b46a8906 4195 DEFAULT_NETWORK_DOWN_SCRIPT,
7c9d8e07 4196#endif
6e44ba7f 4197 DEFAULT_GDBSTUB_PORT,
bce61846 4198 "/tmp/qemu.log");
15f82208 4199 exit(exitcode);
0824d6fc
FB
4200}
4201
cd6f1169
FB
4202#define HAS_ARG 0x0001
4203
4204enum {
5824d651
BS
4205#define DEF(option, opt_arg, opt_enum, opt_help) \
4206 opt_enum,
4207#define DEFHEADING(text)
4208#include "qemu-options.h"
4209#undef DEF
4210#undef DEFHEADING
4211#undef GEN_DOCS
cd6f1169
FB
4212};
4213
4214typedef struct QEMUOption {
4215 const char *name;
4216 int flags;
4217 int index;
4218} QEMUOption;
4219
dbed7e40 4220static const QEMUOption qemu_options[] = {
cd6f1169 4221 { "h", 0, QEMU_OPTION_h },
5824d651
BS
4222#define DEF(option, opt_arg, opt_enum, opt_help) \
4223 { option, opt_arg, opt_enum },
4224#define DEFHEADING(text)
4225#include "qemu-options.h"
4226#undef DEF
4227#undef DEFHEADING
4228#undef GEN_DOCS
cd6f1169 4229 { NULL },
fc01f7e7
FB
4230};
4231
1d14ffa9 4232#ifdef HAS_AUDIO
6a36d84e 4233struct soundhw soundhw[] = {
b00052e4 4234#ifdef HAS_AUDIO_CHOICE
4ce7ff6e 4235#if defined(TARGET_I386) || defined(TARGET_MIPS)
fd06c375
FB
4236 {
4237 "pcspk",
4238 "PC speaker",
4239 0,
4240 1,
4241 { .init_isa = pcspk_audio_init }
4242 },
4243#endif
4c9b53e3 4244
4245#ifdef CONFIG_SB16
6a36d84e
FB
4246 {
4247 "sb16",
4248 "Creative Sound Blaster 16",
4249 0,
4250 1,
4251 { .init_isa = SB16_init }
4252 },
4c9b53e3 4253#endif
6a36d84e 4254
cc53d26d 4255#ifdef CONFIG_CS4231A
4256 {
4257 "cs4231a",
4258 "CS4231A",
4259 0,
4260 1,
4261 { .init_isa = cs4231a_init }
4262 },
4263#endif
4264
1d14ffa9 4265#ifdef CONFIG_ADLIB
6a36d84e
FB
4266 {
4267 "adlib",
1d14ffa9 4268#ifdef HAS_YMF262
6a36d84e 4269 "Yamaha YMF262 (OPL3)",
1d14ffa9 4270#else
6a36d84e 4271 "Yamaha YM3812 (OPL2)",
1d14ffa9 4272#endif
6a36d84e
FB
4273 0,
4274 1,
4275 { .init_isa = Adlib_init }
4276 },
1d14ffa9 4277#endif
6a36d84e 4278
1d14ffa9 4279#ifdef CONFIG_GUS
6a36d84e
FB
4280 {
4281 "gus",
4282 "Gravis Ultrasound GF1",
4283 0,
4284 1,
4285 { .init_isa = GUS_init }
4286 },
1d14ffa9 4287#endif
6a36d84e 4288
4c9b53e3 4289#ifdef CONFIG_AC97
e5c9a13e
AZ
4290 {
4291 "ac97",
4292 "Intel 82801AA AC97 Audio",
4293 0,
4294 0,
4295 { .init_pci = ac97_init }
4296 },
4c9b53e3 4297#endif
e5c9a13e 4298
4c9b53e3 4299#ifdef CONFIG_ES1370
6a36d84e
FB
4300 {
4301 "es1370",
4302 "ENSONIQ AudioPCI ES1370",
4303 0,
4304 0,
4305 { .init_pci = es1370_init }
4306 },
b00052e4 4307#endif
6a36d84e 4308
4c9b53e3 4309#endif /* HAS_AUDIO_CHOICE */
4310
6a36d84e
FB
4311 { NULL, NULL, 0, 0, { NULL } }
4312};
4313
4314static void select_soundhw (const char *optarg)
4315{
4316 struct soundhw *c;
4317
4318 if (*optarg == '?') {
4319 show_valid_cards:
4320
4321 printf ("Valid sound card names (comma separated):\n");
4322 for (c = soundhw; c->name; ++c) {
4323 printf ("%-11s %s\n", c->name, c->descr);
4324 }
4325 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
4326 exit (*optarg != '?');
4327 }
4328 else {
6a36d84e 4329 size_t l;
1d14ffa9
FB
4330 const char *p;
4331 char *e;
4332 int bad_card = 0;
4333
6a36d84e
FB
4334 if (!strcmp (optarg, "all")) {
4335 for (c = soundhw; c->name; ++c) {
4336 c->enabled = 1;
4337 }
4338 return;
4339 }
1d14ffa9 4340
6a36d84e 4341 p = optarg;
1d14ffa9
FB
4342 while (*p) {
4343 e = strchr (p, ',');
4344 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
4345
4346 for (c = soundhw; c->name; ++c) {
b3d6fb4a 4347 if (!strncmp (c->name, p, l) && !c->name[l]) {
6a36d84e 4348 c->enabled = 1;
1d14ffa9
FB
4349 break;
4350 }
4351 }
6a36d84e
FB
4352
4353 if (!c->name) {
1d14ffa9
FB
4354 if (l > 80) {
4355 fprintf (stderr,
4356 "Unknown sound card name (too big to show)\n");
4357 }
4358 else {
4359 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4360 (int) l, p);
4361 }
4362 bad_card = 1;
4363 }
4364 p += l + (e != NULL);
4365 }
4366
4367 if (bad_card)
4368 goto show_valid_cards;
4369 }
4370}
4371#endif
4372
3893c124 4373static void select_vgahw (const char *p)
4374{
4375 const char *opts;
4376
64465297 4377 default_vga = 0;
86176759 4378 vga_interface_type = VGA_NONE;
3893c124 4379 if (strstart(p, "std", &opts)) {
86176759 4380 vga_interface_type = VGA_STD;
3893c124 4381 } else if (strstart(p, "cirrus", &opts)) {
86176759 4382 vga_interface_type = VGA_CIRRUS;
3893c124 4383 } else if (strstart(p, "vmware", &opts)) {
86176759 4384 vga_interface_type = VGA_VMWARE;
94909d9f 4385 } else if (strstart(p, "xenfb", &opts)) {
86176759 4386 vga_interface_type = VGA_XENFB;
28b85ed8 4387 } else if (!strstart(p, "none", &opts)) {
3893c124 4388 invalid_vga:
4389 fprintf(stderr, "Unknown vga type: %s\n", p);
4390 exit(1);
4391 }
cb5a7aa8 4392 while (*opts) {
4393 const char *nextopt;
4394
4395 if (strstart(opts, ",retrace=", &nextopt)) {
4396 opts = nextopt;
4397 if (strstart(opts, "dumb", &nextopt))
4398 vga_retrace_method = VGA_RETRACE_DUMB;
4399 else if (strstart(opts, "precise", &nextopt))
4400 vga_retrace_method = VGA_RETRACE_PRECISE;
4401 else goto invalid_vga;
4402 } else goto invalid_vga;
4403 opts = nextopt;
4404 }
3893c124 4405}
4406
7d4c3d53
MA
4407#ifdef TARGET_I386
4408static int balloon_parse(const char *arg)
4409{
382f0743 4410 QemuOpts *opts;
7d4c3d53 4411
382f0743
GH
4412 if (strcmp(arg, "none") == 0) {
4413 return 0;
4414 }
4415
4416 if (!strncmp(arg, "virtio", 6)) {
4417 if (arg[6] == ',') {
4418 /* have params -> parse them */
4419 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4420 if (!opts)
4421 return -1;
4422 } else {
4423 /* create empty opts */
4424 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
7d4c3d53 4425 }
382f0743
GH
4426 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4427 return 0;
7d4c3d53 4428 }
382f0743
GH
4429
4430 return -1;
7d4c3d53
MA
4431}
4432#endif
4433
3587d7e6
FB
4434#ifdef _WIN32
4435static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4436{
4437 exit(STATUS_CONTROL_C_EXIT);
4438 return TRUE;
4439}
4440#endif
4441
c4be29ff 4442int qemu_uuid_parse(const char *str, uint8_t *uuid)
8fcb1b90
BS
4443{
4444 int ret;
4445
4446 if(strlen(str) != 36)
4447 return -1;
4448
4449 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4450 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4451 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4452
4453 if(ret != 16)
4454 return -1;
4455
b6f6e3d3
AL
4456#ifdef TARGET_I386
4457 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4458#endif
4459
8fcb1b90
BS
4460 return 0;
4461}
4462
5b08fc10
AL
4463#ifndef _WIN32
4464
4465static void termsig_handler(int signal)
4466{
4467 qemu_system_shutdown_request();
4468}
4469
7c3370d4
JK
4470static void sigchld_handler(int signal)
4471{
4472 waitpid(-1, NULL, WNOHANG);
4473}
4474
4475static void sighandler_setup(void)
5b08fc10
AL
4476{
4477 struct sigaction act;
4478
4479 memset(&act, 0, sizeof(act));
4480 act.sa_handler = termsig_handler;
4481 sigaction(SIGINT, &act, NULL);
4482 sigaction(SIGHUP, &act, NULL);
4483 sigaction(SIGTERM, &act, NULL);
7c3370d4
JK
4484
4485 act.sa_handler = sigchld_handler;
4486 act.sa_flags = SA_NOCLDSTOP;
4487 sigaction(SIGCHLD, &act, NULL);
5b08fc10
AL
4488}
4489
4490#endif
4491
5cea8590
PB
4492#ifdef _WIN32
4493/* Look for support files in the same directory as the executable. */
4494static char *find_datadir(const char *argv0)
4495{
4496 char *p;
4497 char buf[MAX_PATH];
4498 DWORD len;
4499
4500 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4501 if (len == 0) {
c5947808 4502 return NULL;
5cea8590
PB
4503 }
4504
4505 buf[len] = 0;
4506 p = buf + len - 1;
4507 while (p != buf && *p != '\\')
4508 p--;
4509 *p = 0;
4510 if (access(buf, R_OK) == 0) {
4511 return qemu_strdup(buf);
4512 }
4513 return NULL;
4514}
4515#else /* !_WIN32 */
4516
4517/* Find a likely location for support files using the location of the binary.
4518 For installed binaries this will be "$bindir/../share/qemu". When
4519 running from the build tree this will be "$bindir/../pc-bios". */
4520#define SHARE_SUFFIX "/share/qemu"
4521#define BUILD_SUFFIX "/pc-bios"
4522static char *find_datadir(const char *argv0)
4523{
4524 char *dir;
4525 char *p = NULL;
4526 char *res;
5cea8590 4527 char buf[PATH_MAX];
3a41759d 4528 size_t max_len;
5cea8590
PB
4529
4530#if defined(__linux__)
4531 {
4532 int len;
4533 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4534 if (len > 0) {
4535 buf[len] = 0;
4536 p = buf;
4537 }
4538 }
4539#elif defined(__FreeBSD__)
4540 {
4541 int len;
4542 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4543 if (len > 0) {
4544 buf[len] = 0;
4545 p = buf;
4546 }
4547 }
4548#endif
4549 /* If we don't have any way of figuring out the actual executable
4550 location then try argv[0]. */
4551 if (!p) {
4d224196 4552 p = realpath(argv0, buf);
5cea8590
PB
4553 if (!p) {
4554 return NULL;
4555 }
4556 }
4557 dir = dirname(p);
4558 dir = dirname(dir);
4559
3a41759d
BS
4560 max_len = strlen(dir) +
4561 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4562 res = qemu_mallocz(max_len);
4563 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5cea8590 4564 if (access(res, R_OK)) {
3a41759d 4565 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5cea8590
PB
4566 if (access(res, R_OK)) {
4567 qemu_free(res);
4568 res = NULL;
4569 }
4570 }
4d224196 4571
5cea8590
PB
4572 return res;
4573}
4574#undef SHARE_SUFFIX
4575#undef BUILD_SUFFIX
4576#endif
4577
4578char *qemu_find_file(int type, const char *name)
4579{
4580 int len;
4581 const char *subdir;
4582 char *buf;
4583
4584 /* If name contains path separators then try it as a straight path. */
4585 if ((strchr(name, '/') || strchr(name, '\\'))
4586 && access(name, R_OK) == 0) {
73ffc805 4587 return qemu_strdup(name);
5cea8590
PB
4588 }
4589 switch (type) {
4590 case QEMU_FILE_TYPE_BIOS:
4591 subdir = "";
4592 break;
4593 case QEMU_FILE_TYPE_KEYMAP:
4594 subdir = "keymaps/";
4595 break;
4596 default:
4597 abort();
4598 }
4599 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4600 buf = qemu_mallocz(len);
3a41759d 4601 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5cea8590
PB
4602 if (access(buf, R_OK)) {
4603 qemu_free(buf);
4604 return NULL;
4605 }
4606 return buf;
4607}
4608
f31d07d1
GH
4609static int device_init_func(QemuOpts *opts, void *opaque)
4610{
4611 DeviceState *dev;
4612
4613 dev = qdev_device_add(opts);
4614 if (!dev)
4615 return -1;
4616 return 0;
4617}
4618
1a688d3b
GH
4619static int chardev_init_func(QemuOpts *opts, void *opaque)
4620{
4621 CharDriverState *chr;
4622
4623 chr = qemu_chr_open_opts(opts, NULL);
4624 if (!chr)
4625 return -1;
4626 return 0;
4627}
4628
88589343
GH
4629static int mon_init_func(QemuOpts *opts, void *opaque)
4630{
4631 CharDriverState *chr;
4632 const char *chardev;
4633 const char *mode;
4634 int flags;
4635
4636 mode = qemu_opt_get(opts, "mode");
4637 if (mode == NULL) {
4638 mode = "readline";
4639 }
4640 if (strcmp(mode, "readline") == 0) {
4641 flags = MONITOR_USE_READLINE;
4642 } else if (strcmp(mode, "control") == 0) {
4643 flags = MONITOR_USE_CONTROL;
4644 } else {
4645 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4646 exit(1);
4647 }
4648
4649 if (qemu_opt_get_bool(opts, "default", 0))
4650 flags |= MONITOR_IS_DEFAULT;
4651
4652 chardev = qemu_opt_get(opts, "chardev");
4653 chr = qemu_chr_find(chardev);
4654 if (chr == NULL) {
4655 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4656 exit(1);
4657 }
4658
4659 monitor_init(chr, flags);
4660 return 0;
4661}
4662
4663static void monitor_parse(const char *optarg)
4664{
4665 static int monitor_device_index = 0;
4666 QemuOpts *opts;
4667 const char *p;
4668 char label[32];
4669 int def = 0;
4670
4671 if (strstart(optarg, "chardev:", &p)) {
4672 snprintf(label, sizeof(label), "%s", p);
4673 } else {
4674 if (monitor_device_index) {
4675 snprintf(label, sizeof(label), "monitor%d",
4676 monitor_device_index);
4677 } else {
4678 snprintf(label, sizeof(label), "monitor");
4679 def = 1;
4680 }
4681 opts = qemu_chr_parse_compat(label, optarg);
4682 if (!opts) {
4683 fprintf(stderr, "parse error: %s\n", optarg);
4684 exit(1);
4685 }
4686 }
4687
4688 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4689 if (!opts) {
4690 fprintf(stderr, "duplicate chardev: %s\n", label);
4691 exit(1);
4692 }
4693 qemu_opt_set(opts, "mode", "readline");
4694 qemu_opt_set(opts, "chardev", label);
4695 if (def)
4696 qemu_opt_set(opts, "default", "on");
4697 monitor_device_index++;
4698}
4699
bd3c948d
GH
4700struct device_config {
4701 enum {
bd3c948d
GH
4702 DEV_USB, /* -usbdevice */
4703 DEV_BT, /* -bt */
998bbd74 4704 DEV_SERIAL, /* -serial */
6a5e8b0e 4705 DEV_PARALLEL, /* -parallel */
bd3c948d
GH
4706 } type;
4707 const char *cmdline;
72cf2d4f 4708 QTAILQ_ENTRY(device_config) next;
bd3c948d 4709};
72cf2d4f 4710QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
bd3c948d
GH
4711
4712static void add_device_config(int type, const char *cmdline)
4713{
4714 struct device_config *conf;
4715
4716 conf = qemu_mallocz(sizeof(*conf));
4717 conf->type = type;
4718 conf->cmdline = cmdline;
72cf2d4f 4719 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
bd3c948d
GH
4720}
4721
4722static int foreach_device_config(int type, int (*func)(const char *cmdline))
4723{
4724 struct device_config *conf;
4725 int rc;
4726
72cf2d4f 4727 QTAILQ_FOREACH(conf, &device_configs, next) {
bd3c948d
GH
4728 if (conf->type != type)
4729 continue;
4730 rc = func(conf->cmdline);
4731 if (0 != rc)
4732 return rc;
4733 }
4734 return 0;
4735}
4736
998bbd74
GH
4737static int serial_parse(const char *devname)
4738{
4739 static int index = 0;
4740 char label[32];
4741
4742 if (strcmp(devname, "none") == 0)
4743 return 0;
4744 if (index == MAX_SERIAL_PORTS) {
4745 fprintf(stderr, "qemu: too many serial ports\n");
4746 exit(1);
4747 }
4748 snprintf(label, sizeof(label), "serial%d", index);
4749 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4750 if (!serial_hds[index]) {
4751 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4752 devname, strerror(errno));
4753 return -1;
4754 }
4755 index++;
4756 return 0;
4757}
4758
6a5e8b0e
GH
4759static int parallel_parse(const char *devname)
4760{
4761 static int index = 0;
4762 char label[32];
4763
4764 if (strcmp(devname, "none") == 0)
4765 return 0;
4766 if (index == MAX_PARALLEL_PORTS) {
4767 fprintf(stderr, "qemu: too many parallel ports\n");
4768 exit(1);
4769 }
4770 snprintf(label, sizeof(label), "parallel%d", index);
4771 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4772 if (!parallel_hds[index]) {
4773 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4774 devname, strerror(errno));
4775 return -1;
4776 }
4777 index++;
4778 return 0;
4779}
4780
902b3d5c 4781int main(int argc, char **argv, char **envp)
0824d6fc 4782{
59030a8c 4783 const char *gdbstub_dev = NULL;
28c5af54 4784 uint32_t boot_devices_bitmap = 0;
e4bcb14c 4785 int i;
28c5af54 4786 int snapshot, linux_boot, net_boot;
7f7f9873 4787 const char *initrd_filename;
a20dd508 4788 const char *kernel_filename, *kernel_cmdline;
195325a4 4789 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3023f332 4790 DisplayState *ds;
7d957bd8 4791 DisplayChangeListener *dcl;
46d4767d 4792 int cyls, heads, secs, translation;
f31d07d1 4793 QemuOpts *hda_opts = NULL, *opts;
cd6f1169
FB
4794 int optind;
4795 const char *r, *optarg;
9ede2fde
AL
4796 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4797 int virtio_console_index;
d63d307f 4798 const char *loadvm = NULL;
cc1daa40 4799 QEMUMachine *machine;
94fc95cd 4800 const char *cpu_model;
b9e82a59 4801#ifndef _WIN32
71e3ceb8 4802 int fds[2];
b9e82a59 4803#endif
26a5f13b 4804 int tb_size;
93815bc2 4805 const char *pid_file = NULL;
5bb7910a 4806 const char *incoming = NULL;
b9e82a59 4807#ifndef _WIN32
54042bcf
AL
4808 int fd = 0;
4809 struct passwd *pwd = NULL;
0858532e
AL
4810 const char *chroot_dir = NULL;
4811 const char *run_as = NULL;
b9e82a59 4812#endif
268a362c 4813 CPUState *env;
993fbfdb 4814 int show_vnc_port = 0;
0bd48850 4815
6875204c
JK
4816 init_clocks();
4817
ac7531ec 4818 qemu_errors_to_file(stderr);
902b3d5c 4819 qemu_cache_utils_init(envp);
4820
72cf2d4f 4821 QLIST_INIT (&vm_change_state_head);
be995c27
FB
4822#ifndef _WIN32
4823 {
4824 struct sigaction act;
4825 sigfillset(&act.sa_mask);
4826 act.sa_flags = 0;
4827 act.sa_handler = SIG_IGN;
4828 sigaction(SIGPIPE, &act, NULL);
4829 }
3587d7e6
FB
4830#else
4831 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
4832 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4833 QEMU to run on a single CPU */
4834 {
4835 HANDLE h;
4836 DWORD mask, smask;
4837 int i;
4838 h = GetCurrentProcess();
4839 if (GetProcessAffinityMask(h, &mask, &smask)) {
4840 for(i = 0; i < 32; i++) {
4841 if (mask & (1 << i))
4842 break;
4843 }
4844 if (i != 32) {
4845 mask = 1 << i;
4846 SetProcessAffinityMask(h, mask);
4847 }
4848 }
4849 }
67b915a5 4850#endif
be995c27 4851
f80f9ec9 4852 module_call_init(MODULE_INIT_MACHINE);
0c257437 4853 machine = find_default_machine();
94fc95cd 4854 cpu_model = NULL;
fc01f7e7 4855 initrd_filename = NULL;
4fc5d071 4856 ram_size = 0;
33e3963e 4857 snapshot = 0;
a20dd508
FB
4858 kernel_filename = NULL;
4859 kernel_cmdline = "";
c4b1fcc0 4860 cyls = heads = secs = 0;
46d4767d 4861 translation = BIOS_ATA_TRANSLATION_AUTO;
c4b1fcc0 4862
1b8fc811 4863 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
9ede2fde
AL
4864 virtio_consoles[i] = NULL;
4865 virtio_console_index = 0;
4866
268a362c
AL
4867 for (i = 0; i < MAX_NODES; i++) {
4868 node_mem[i] = 0;
4869 node_cpumask[i] = 0;
4870 }
4871
268a362c 4872 nb_numa_nodes = 0;
7c9d8e07 4873 nb_nics = 0;
3b46e624 4874
26a5f13b 4875 tb_size = 0;
41bd639b
BS
4876 autostart= 1;
4877
cd6f1169 4878 optind = 1;
0824d6fc 4879 for(;;) {
cd6f1169 4880 if (optind >= argc)
0824d6fc 4881 break;
cd6f1169
FB
4882 r = argv[optind];
4883 if (r[0] != '-') {
9dfd7c7a 4884 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
cd6f1169
FB
4885 } else {
4886 const QEMUOption *popt;
4887
4888 optind++;
dff5efc8
PB
4889 /* Treat --foo the same as -foo. */
4890 if (r[1] == '-')
4891 r++;
cd6f1169
FB
4892 popt = qemu_options;
4893 for(;;) {
4894 if (!popt->name) {
5fafdf24 4895 fprintf(stderr, "%s: invalid option -- '%s'\n",
cd6f1169
FB
4896 argv[0], r);
4897 exit(1);
4898 }
4899 if (!strcmp(popt->name, r + 1))
4900 break;
4901 popt++;
4902 }
4903 if (popt->flags & HAS_ARG) {
4904 if (optind >= argc) {
4905 fprintf(stderr, "%s: option '%s' requires an argument\n",
4906 argv[0], r);
4907 exit(1);
4908 }
4909 optarg = argv[optind++];
4910 } else {
4911 optarg = NULL;
4912 }
4913
4914 switch(popt->index) {
cc1daa40
FB
4915 case QEMU_OPTION_M:
4916 machine = find_machine(optarg);
4917 if (!machine) {
4918 QEMUMachine *m;
4919 printf("Supported machines are:\n");
4920 for(m = first_machine; m != NULL; m = m->next) {
3f6599e6
MM
4921 if (m->alias)
4922 printf("%-10s %s (alias of %s)\n",
4923 m->alias, m->desc, m->name);
cc1daa40 4924 printf("%-10s %s%s\n",
5fafdf24 4925 m->name, m->desc,
0c257437 4926 m->is_default ? " (default)" : "");
cc1daa40 4927 }
15f82208 4928 exit(*optarg != '?');
cc1daa40
FB
4929 }
4930 break;
94fc95cd
JM
4931 case QEMU_OPTION_cpu:
4932 /* hw initialization will check this */
15f82208 4933 if (*optarg == '?') {
c732abe2
JM
4934/* XXX: implement xxx_cpu_list for targets that still miss it */
4935#if defined(cpu_list)
4936 cpu_list(stdout, &fprintf);
94fc95cd 4937#endif
15f82208 4938 exit(0);
94fc95cd
JM
4939 } else {
4940 cpu_model = optarg;
4941 }
4942 break;
cd6f1169 4943 case QEMU_OPTION_initrd:
fc01f7e7
FB
4944 initrd_filename = optarg;
4945 break;
cd6f1169 4946 case QEMU_OPTION_hda:
e4bcb14c 4947 if (cyls == 0)
9dfd7c7a 4948 hda_opts = drive_add(optarg, HD_ALIAS, 0);
e4bcb14c 4949 else
9dfd7c7a 4950 hda_opts = drive_add(optarg, HD_ALIAS
e4bcb14c 4951 ",cyls=%d,heads=%d,secs=%d%s",
609497ab 4952 0, cyls, heads, secs,
e4bcb14c
TS
4953 translation == BIOS_ATA_TRANSLATION_LBA ?
4954 ",trans=lba" :
4955 translation == BIOS_ATA_TRANSLATION_NONE ?
4956 ",trans=none" : "");
4957 break;
cd6f1169 4958 case QEMU_OPTION_hdb:
cc1daa40
FB
4959 case QEMU_OPTION_hdc:
4960 case QEMU_OPTION_hdd:
609497ab 4961 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
fc01f7e7 4962 break;
e4bcb14c 4963 case QEMU_OPTION_drive:
609497ab 4964 drive_add(NULL, "%s", optarg);
e4bcb14c 4965 break;
d058fe03
GH
4966 case QEMU_OPTION_set:
4967 if (qemu_set_option(optarg) != 0)
4968 exit(1);
4969 break;
d0fef6fb
GH
4970 case QEMU_OPTION_global:
4971 if (qemu_global_option(optarg) != 0)
4972 exit(1);
4973 break;
3e3d5815 4974 case QEMU_OPTION_mtdblock:
609497ab 4975 drive_add(optarg, MTD_ALIAS);
3e3d5815 4976 break;
a1bb27b1 4977 case QEMU_OPTION_sd:
609497ab 4978 drive_add(optarg, SD_ALIAS);
a1bb27b1 4979 break;
86f55663 4980 case QEMU_OPTION_pflash:
609497ab 4981 drive_add(optarg, PFLASH_ALIAS);
86f55663 4982 break;
cd6f1169 4983 case QEMU_OPTION_snapshot:
33e3963e
FB
4984 snapshot = 1;
4985 break;
cd6f1169 4986 case QEMU_OPTION_hdachs:
330d0414 4987 {
330d0414
FB
4988 const char *p;
4989 p = optarg;
4990 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
4991 if (cyls < 1 || cyls > 16383)
4992 goto chs_fail;
330d0414
FB
4993 if (*p != ',')
4994 goto chs_fail;
4995 p++;
4996 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
4997 if (heads < 1 || heads > 16)
4998 goto chs_fail;
330d0414
FB
4999 if (*p != ',')
5000 goto chs_fail;
5001 p++;
5002 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
5003 if (secs < 1 || secs > 63)
5004 goto chs_fail;
5005 if (*p == ',') {
5006 p++;
5007 if (!strcmp(p, "none"))
5008 translation = BIOS_ATA_TRANSLATION_NONE;
5009 else if (!strcmp(p, "lba"))
5010 translation = BIOS_ATA_TRANSLATION_LBA;
5011 else if (!strcmp(p, "auto"))
5012 translation = BIOS_ATA_TRANSLATION_AUTO;
5013 else
5014 goto chs_fail;
5015 } else if (*p != '\0') {
c4b1fcc0 5016 chs_fail:
46d4767d
FB
5017 fprintf(stderr, "qemu: invalid physical CHS format\n");
5018 exit(1);
c4b1fcc0 5019 }
9dfd7c7a
GH
5020 if (hda_opts != NULL) {
5021 char num[16];
5022 snprintf(num, sizeof(num), "%d", cyls);
5023 qemu_opt_set(hda_opts, "cyls", num);
5024 snprintf(num, sizeof(num), "%d", heads);
5025 qemu_opt_set(hda_opts, "heads", num);
5026 snprintf(num, sizeof(num), "%d", secs);
5027 qemu_opt_set(hda_opts, "secs", num);
5028 if (translation == BIOS_ATA_TRANSLATION_LBA)
5029 qemu_opt_set(hda_opts, "trans", "lba");
5030 if (translation == BIOS_ATA_TRANSLATION_NONE)
5031 qemu_opt_set(hda_opts, "trans", "none");
5032 }
330d0414
FB
5033 }
5034 break;
268a362c
AL
5035 case QEMU_OPTION_numa:
5036 if (nb_numa_nodes >= MAX_NODES) {
5037 fprintf(stderr, "qemu: too many NUMA nodes\n");
5038 exit(1);
5039 }
5040 numa_add(optarg);
5041 break;
cd6f1169 5042 case QEMU_OPTION_nographic:
993fbfdb 5043 display_type = DT_NOGRAPHIC;
a20dd508 5044 break;
4d3b6f6e
AZ
5045#ifdef CONFIG_CURSES
5046 case QEMU_OPTION_curses:
993fbfdb 5047 display_type = DT_CURSES;
4d3b6f6e
AZ
5048 break;
5049#endif
a171fe39
AZ
5050 case QEMU_OPTION_portrait:
5051 graphic_rotate = 1;
5052 break;
cd6f1169 5053 case QEMU_OPTION_kernel:
a20dd508
FB
5054 kernel_filename = optarg;
5055 break;
cd6f1169 5056 case QEMU_OPTION_append:
a20dd508 5057 kernel_cmdline = optarg;
313aa567 5058 break;
cd6f1169 5059 case QEMU_OPTION_cdrom:
609497ab 5060 drive_add(optarg, CDROM_ALIAS);
36b486bb 5061 break;
cd6f1169 5062 case QEMU_OPTION_boot:
28c5af54 5063 {
ef3adf68 5064 static const char * const params[] = {
95387491 5065 "order", "once", "menu", NULL
ef3adf68
JK
5066 };
5067 char buf[sizeof(boot_devices)];
e0f084bf 5068 char *standard_boot_devices;
ef3adf68
JK
5069 int legacy = 0;
5070
5071 if (!strchr(optarg, '=')) {
5072 legacy = 1;
5073 pstrcpy(buf, sizeof(buf), optarg);
5074 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5075 fprintf(stderr,
5076 "qemu: unknown boot parameter '%s' in '%s'\n",
5077 buf, optarg);
5078 exit(1);
5079 }
5080
5081 if (legacy ||
5082 get_param_value(buf, sizeof(buf), "order", optarg)) {
5083 boot_devices_bitmap = parse_bootdevices(buf);
5084 pstrcpy(boot_devices, sizeof(boot_devices), buf);
28c5af54 5085 }
e0f084bf
JK
5086 if (!legacy) {
5087 if (get_param_value(buf, sizeof(buf),
5088 "once", optarg)) {
5089 boot_devices_bitmap |= parse_bootdevices(buf);
5090 standard_boot_devices = qemu_strdup(boot_devices);
5091 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5092 qemu_register_reset(restore_boot_devices,
5093 standard_boot_devices);
5094 }
95387491
JK
5095 if (get_param_value(buf, sizeof(buf),
5096 "menu", optarg)) {
5097 if (!strcmp(buf, "on")) {
5098 boot_menu = 1;
5099 } else if (!strcmp(buf, "off")) {
5100 boot_menu = 0;
5101 } else {
5102 fprintf(stderr,
5103 "qemu: invalid option value '%s'\n",
5104 buf);
5105 exit(1);
5106 }
5107 }
e0f084bf 5108 }
36b486bb
FB
5109 }
5110 break;
cd6f1169 5111 case QEMU_OPTION_fda:
cd6f1169 5112 case QEMU_OPTION_fdb:
609497ab 5113 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
c45886db 5114 break;
52ca8d6a
FB
5115#ifdef TARGET_I386
5116 case QEMU_OPTION_no_fd_bootchk:
5117 fd_bootchk = 0;
5118 break;
5119#endif
a1ea458f
MM
5120 case QEMU_OPTION_netdev:
5121 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5122 exit(1);
5123 }
5124 break;
7c9d8e07 5125 case QEMU_OPTION_net:
7f161aae 5126 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
c4b1fcc0
FB
5127 exit(1);
5128 }
702c651c 5129 break;
c7f74643
FB
5130#ifdef CONFIG_SLIRP
5131 case QEMU_OPTION_tftp:
ad196a9d 5132 legacy_tftp_prefix = optarg;
9bf05444 5133 break;
47d5d01a 5134 case QEMU_OPTION_bootp:
ad196a9d 5135 legacy_bootp_filename = optarg;
47d5d01a 5136 break;
c94c8d64 5137#ifndef _WIN32
9d728e8c 5138 case QEMU_OPTION_smb:
0752706d
MA
5139 if (net_slirp_smb(optarg) < 0)
5140 exit(1);
9d728e8c 5141 break;
c94c8d64 5142#endif
9bf05444 5143 case QEMU_OPTION_redir:
0752706d
MA
5144 if (net_slirp_redir(optarg) < 0)
5145 exit(1);
9bf05444 5146 break;
c7f74643 5147#endif
dc72ac14 5148 case QEMU_OPTION_bt:
bd3c948d 5149 add_device_config(DEV_BT, optarg);
dc72ac14 5150 break;
1d14ffa9 5151#ifdef HAS_AUDIO
1d14ffa9
FB
5152 case QEMU_OPTION_audio_help:
5153 AUD_help ();
5154 exit (0);
5155 break;
5156 case QEMU_OPTION_soundhw:
5157 select_soundhw (optarg);
5158 break;
5159#endif
cd6f1169 5160 case QEMU_OPTION_h:
15f82208 5161 help(0);
cd6f1169 5162 break;
9bd7e6d9
PB
5163 case QEMU_OPTION_version:
5164 version();
5165 exit(0);
5166 break;
00f82b8a
AJ
5167 case QEMU_OPTION_m: {
5168 uint64_t value;
5169 char *ptr;
5170
5171 value = strtoul(optarg, &ptr, 10);
5172 switch (*ptr) {
5173 case 0: case 'M': case 'm':
5174 value <<= 20;
5175 break;
5176 case 'G': case 'g':
5177 value <<= 30;
5178 break;
5179 default:
5180 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
cd6f1169
FB
5181 exit(1);
5182 }
00f82b8a
AJ
5183
5184 /* On 32-bit hosts, QEMU is limited by virtual address space */
4a1418e0 5185 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
00f82b8a
AJ
5186 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5187 exit(1);
5188 }
c227f099 5189 if (value != (uint64_t)(ram_addr_t)value) {
00f82b8a
AJ
5190 fprintf(stderr, "qemu: ram size too large\n");
5191 exit(1);
5192 }
5193 ram_size = value;
cd6f1169 5194 break;
00f82b8a 5195 }
cd6f1169
FB
5196 case QEMU_OPTION_d:
5197 {
5198 int mask;
c7cd6a37 5199 const CPULogItem *item;
3b46e624 5200
cd6f1169
FB
5201 mask = cpu_str_to_log_mask(optarg);
5202 if (!mask) {
5203 printf("Log items (comma separated):\n");
f193c797
FB
5204 for(item = cpu_log_items; item->mask != 0; item++) {
5205 printf("%-10s %s\n", item->name, item->help);
5206 }
5207 exit(1);
cd6f1169
FB
5208 }
5209 cpu_set_log(mask);
f193c797 5210 }
cd6f1169 5211 break;
cd6f1169 5212 case QEMU_OPTION_s:
59030a8c 5213 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
cd6f1169 5214 break;
59030a8c
AL
5215 case QEMU_OPTION_gdb:
5216 gdbstub_dev = optarg;
cd6f1169 5217 break;
cd6f1169 5218 case QEMU_OPTION_L:
5cea8590 5219 data_dir = optarg;
cd6f1169 5220 break;
1192dad8
JM
5221 case QEMU_OPTION_bios:
5222 bios_name = optarg;
5223 break;
1b530a6d
AJ
5224 case QEMU_OPTION_singlestep:
5225 singlestep = 1;
5226 break;
cd6f1169 5227 case QEMU_OPTION_S:
3c07f8e8 5228 autostart = 0;
cd6f1169 5229 break;
3d11d0eb
FB
5230 case QEMU_OPTION_k:
5231 keyboard_layout = optarg;
5232 break;
ee22c2f7
FB
5233 case QEMU_OPTION_localtime:
5234 rtc_utc = 0;
5235 break;
3893c124 5236 case QEMU_OPTION_vga:
5237 select_vgahw (optarg);
1bfe856e 5238 break;
5824d651 5239#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2
FB
5240 case QEMU_OPTION_g:
5241 {
5242 const char *p;
5243 int w, h, depth;
5244 p = optarg;
5245 w = strtol(p, (char **)&p, 10);
5246 if (w <= 0) {
5247 graphic_error:
5248 fprintf(stderr, "qemu: invalid resolution or depth\n");
5249 exit(1);
5250 }
5251 if (*p != 'x')
5252 goto graphic_error;
5253 p++;
5254 h = strtol(p, (char **)&p, 10);
5255 if (h <= 0)
5256 goto graphic_error;
5257 if (*p == 'x') {
5258 p++;
5259 depth = strtol(p, (char **)&p, 10);
5fafdf24 5260 if (depth != 8 && depth != 15 && depth != 16 &&
e9b137c2
FB
5261 depth != 24 && depth != 32)
5262 goto graphic_error;
5263 } else if (*p == '\0') {
5264 depth = graphic_depth;
5265 } else {
5266 goto graphic_error;
5267 }
3b46e624 5268
e9b137c2
FB
5269 graphic_width = w;
5270 graphic_height = h;
5271 graphic_depth = depth;
5272 }
5273 break;
5824d651 5274#endif
20d8a3ed
TS
5275 case QEMU_OPTION_echr:
5276 {
5277 char *r;
5278 term_escape_char = strtol(optarg, &r, 0);
5279 if (r == optarg)
5280 printf("Bad argument to echr\n");
5281 break;
5282 }
82c643ff 5283 case QEMU_OPTION_monitor:
88589343 5284 monitor_parse(optarg);
abdeed06 5285 default_monitor = 0;
82c643ff 5286 break;
191bc01b
GH
5287 case QEMU_OPTION_chardev:
5288 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5289 if (!opts) {
5290 fprintf(stderr, "parse error: %s\n", optarg);
5291 exit(1);
5292 }
191bc01b 5293 break;
82c643ff 5294 case QEMU_OPTION_serial:
998bbd74
GH
5295 add_device_config(DEV_SERIAL, optarg);
5296 default_serial = 0;
82c643ff 5297 break;
9dd986cc 5298 case QEMU_OPTION_watchdog:
09aaa160
MA
5299 if (watchdog) {
5300 fprintf(stderr,
5301 "qemu: only one watchdog option may be given\n");
5302 return 1;
5303 }
5304 watchdog = optarg;
9dd986cc
RJ
5305 break;
5306 case QEMU_OPTION_watchdog_action:
5307 if (select_watchdog_action(optarg) == -1) {
5308 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5309 exit(1);
5310 }
5311 break;
51ecf136
AL
5312 case QEMU_OPTION_virtiocon:
5313 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5314 fprintf(stderr, "qemu: too many virtio consoles\n");
5315 exit(1);
5316 }
5317 virtio_consoles[virtio_console_index] = optarg;
5318 virtio_console_index++;
5319 break;
6508fe59 5320 case QEMU_OPTION_parallel:
6a5e8b0e
GH
5321 add_device_config(DEV_PARALLEL, optarg);
5322 default_parallel = 0;
6508fe59 5323 break;
d63d307f
FB
5324 case QEMU_OPTION_loadvm:
5325 loadvm = optarg;
5326 break;
5327 case QEMU_OPTION_full_screen:
5328 full_screen = 1;
5329 break;
667accab 5330#ifdef CONFIG_SDL
43523e93
TS
5331 case QEMU_OPTION_no_frame:
5332 no_frame = 1;
5333 break;
3780e197
TS
5334 case QEMU_OPTION_alt_grab:
5335 alt_grab = 1;
5336 break;
0ca9f8a4
DK
5337 case QEMU_OPTION_ctrl_grab:
5338 ctrl_grab = 1;
5339 break;
667accab
TS
5340 case QEMU_OPTION_no_quit:
5341 no_quit = 1;
5342 break;
7d957bd8 5343 case QEMU_OPTION_sdl:
993fbfdb 5344 display_type = DT_SDL;
7d957bd8 5345 break;
667accab 5346#endif
f7cce898 5347 case QEMU_OPTION_pidfile:
93815bc2 5348 pid_file = optarg;
f7cce898 5349 break;
a09db21f
FB
5350#ifdef TARGET_I386
5351 case QEMU_OPTION_win2k_hack:
5352 win2k_install_hack = 1;
5353 break;
73822ec8
AL
5354 case QEMU_OPTION_rtc_td_hack:
5355 rtc_td_hack = 1;
5356 break;
8a92ea2f
AL
5357 case QEMU_OPTION_acpitable:
5358 if(acpi_table_add(optarg) < 0) {
5359 fprintf(stderr, "Wrong acpi table provided\n");
5360 exit(1);
5361 }
5362 break;
b6f6e3d3
AL
5363 case QEMU_OPTION_smbios:
5364 if(smbios_entry_add(optarg) < 0) {
5365 fprintf(stderr, "Wrong smbios provided\n");
5366 exit(1);
5367 }
5368 break;
a09db21f 5369#endif
7ba1e619
AL
5370#ifdef CONFIG_KVM
5371 case QEMU_OPTION_enable_kvm:
5372 kvm_allowed = 1;
7ba1e619 5373 break;
d993e026 5374#endif
bb36d470
FB
5375 case QEMU_OPTION_usb:
5376 usb_enabled = 1;
5377 break;
a594cfbf
FB
5378 case QEMU_OPTION_usbdevice:
5379 usb_enabled = 1;
bd3c948d
GH
5380 add_device_config(DEV_USB, optarg);
5381 break;
5382 case QEMU_OPTION_device:
b386becf 5383 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
f31d07d1
GH
5384 exit(1);
5385 }
a594cfbf 5386 break;
6a00d601 5387 case QEMU_OPTION_smp:
dc6b1c09 5388 smp_parse(optarg);
b2097003 5389 if (smp_cpus < 1) {
6a00d601
FB
5390 fprintf(stderr, "Invalid number of CPUs\n");
5391 exit(1);
5392 }
6be68d7e
JS
5393 if (max_cpus < smp_cpus) {
5394 fprintf(stderr, "maxcpus must be equal to or greater than "
5395 "smp\n");
5396 exit(1);
5397 }
5398 if (max_cpus > 255) {
5399 fprintf(stderr, "Unsupported number of maxcpus\n");
5400 exit(1);
5401 }
6a00d601 5402 break;
24236869 5403 case QEMU_OPTION_vnc:
993fbfdb 5404 display_type = DT_VNC;
73fc9742 5405 vnc_display = optarg;
24236869 5406 break;
5824d651 5407#ifdef TARGET_I386
6515b203
FB
5408 case QEMU_OPTION_no_acpi:
5409 acpi_enabled = 0;
5410 break;
16b29ae1
AL
5411 case QEMU_OPTION_no_hpet:
5412 no_hpet = 1;
5413 break;
7d4c3d53
MA
5414 case QEMU_OPTION_balloon:
5415 if (balloon_parse(optarg) < 0) {
5416 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5417 exit(1);
5418 }
df97b920 5419 break;
5824d651 5420#endif
d1beab82
FB
5421 case QEMU_OPTION_no_reboot:
5422 no_reboot = 1;
5423 break;
b2f76161
AJ
5424 case QEMU_OPTION_no_shutdown:
5425 no_shutdown = 1;
5426 break;
9467cd46
AZ
5427 case QEMU_OPTION_show_cursor:
5428 cursor_hide = 0;
5429 break;
8fcb1b90
BS
5430 case QEMU_OPTION_uuid:
5431 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5432 fprintf(stderr, "Fail to parse UUID string."
5433 " Wrong format.\n");
5434 exit(1);
5435 }
5436 break;
5824d651 5437#ifndef _WIN32
71e3ceb8
TS
5438 case QEMU_OPTION_daemonize:
5439 daemonize = 1;
5440 break;
5824d651 5441#endif
9ae02555
TS
5442 case QEMU_OPTION_option_rom:
5443 if (nb_option_roms >= MAX_OPTION_ROMS) {
5444 fprintf(stderr, "Too many option ROMs\n");
5445 exit(1);
5446 }
5447 option_rom[nb_option_roms] = optarg;
5448 nb_option_roms++;
5449 break;
5824d651 5450#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
5451 case QEMU_OPTION_semihosting:
5452 semihosting_enabled = 1;
5453 break;
5824d651 5454#endif
c35734b2 5455 case QEMU_OPTION_name:
1889465a
AK
5456 qemu_name = qemu_strdup(optarg);
5457 {
5458 char *p = strchr(qemu_name, ',');
5459 if (p != NULL) {
5460 *p++ = 0;
5461 if (strncmp(p, "process=", 8)) {
5462 fprintf(stderr, "Unknown subargument %s to -name", p);
5463 exit(1);
5464 }
5465 p += 8;
5466 set_proc_name(p);
5467 }
5468 }
c35734b2 5469 break;
95efd11c 5470#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
5471 case QEMU_OPTION_prom_env:
5472 if (nb_prom_envs >= MAX_PROM_ENVS) {
5473 fprintf(stderr, "Too many prom variables\n");
5474 exit(1);
5475 }
5476 prom_envs[nb_prom_envs] = optarg;
5477 nb_prom_envs++;
5478 break;
2b8f2d41
AZ
5479#endif
5480#ifdef TARGET_ARM
5481 case QEMU_OPTION_old_param:
5482 old_param = 1;
05ebd537 5483 break;
66508601 5484#endif
f3dcfada
TS
5485 case QEMU_OPTION_clock:
5486 configure_alarms(optarg);
5487 break;
7e0af5d0 5488 case QEMU_OPTION_startdate:
1ed2fc1f
JK
5489 configure_rtc_date_offset(optarg, 1);
5490 break;
5491 case QEMU_OPTION_rtc:
5492 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5493 if (!opts) {
5494 fprintf(stderr, "parse error: %s\n", optarg);
5495 exit(1);
7e0af5d0 5496 }
1ed2fc1f 5497 configure_rtc(opts);
7e0af5d0 5498 break;
26a5f13b
FB
5499 case QEMU_OPTION_tb_size:
5500 tb_size = strtol(optarg, NULL, 0);
5501 if (tb_size < 0)
5502 tb_size = 0;
5503 break;
2e70f6ef
PB
5504 case QEMU_OPTION_icount:
5505 use_icount = 1;
5506 if (strcmp(optarg, "auto") == 0) {
5507 icount_time_shift = -1;
5508 } else {
5509 icount_time_shift = strtol(optarg, NULL, 0);
5510 }
5511 break;
5bb7910a
AL
5512 case QEMU_OPTION_incoming:
5513 incoming = optarg;
5514 break;
d8c208dd
GH
5515 case QEMU_OPTION_nodefaults:
5516 default_serial = 0;
5517 default_parallel = 0;
5518 default_monitor = 0;
5519 default_vga = 0;
cb4522cc 5520 default_net = 0;
aa40fc9c 5521 default_drive = 0;
d8c208dd 5522 break;
5824d651 5523#ifndef _WIN32
0858532e
AL
5524 case QEMU_OPTION_chroot:
5525 chroot_dir = optarg;
5526 break;
5527 case QEMU_OPTION_runas:
5528 run_as = optarg;
5529 break;
e37630ca
AL
5530#endif
5531#ifdef CONFIG_XEN
5532 case QEMU_OPTION_xen_domid:
5533 xen_domid = atoi(optarg);
5534 break;
5535 case QEMU_OPTION_xen_create:
5536 xen_mode = XEN_CREATE;
5537 break;
5538 case QEMU_OPTION_xen_attach:
5539 xen_mode = XEN_ATTACH;
5540 break;
5824d651 5541#endif
715a664a
GH
5542 case QEMU_OPTION_readconfig:
5543 {
5544 FILE *fp;
5545 fp = fopen(optarg, "r");
5546 if (fp == NULL) {
5547 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5548 exit(1);
5549 }
5550 if (qemu_config_parse(fp) != 0) {
5551 exit(1);
5552 }
5553 fclose(fp);
5554 break;
5555 }
5556 case QEMU_OPTION_writeconfig:
5557 {
5558 FILE *fp;
5559 if (strcmp(optarg, "-") == 0) {
5560 fp = stdout;
5561 } else {
5562 fp = fopen(optarg, "w");
5563 if (fp == NULL) {
5564 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5565 exit(1);
5566 }
5567 }
5568 qemu_config_write(fp);
5569 fclose(fp);
5570 break;
5571 }
cd6f1169 5572 }
0824d6fc
FB
5573 }
5574 }
330d0414 5575
5cea8590
PB
5576 /* If no data_dir is specified then try to find it relative to the
5577 executable path. */
5578 if (!data_dir) {
5579 data_dir = find_datadir(argv[0]);
5580 }
5581 /* If all else fails use the install patch specified when building. */
5582 if (!data_dir) {
5583 data_dir = CONFIG_QEMU_SHAREDIR;
5584 }
5585
6be68d7e
JS
5586 /*
5587 * Default to max_cpus = smp_cpus, in case the user doesn't
5588 * specify a max_cpus value.
5589 */
5590 if (!max_cpus)
5591 max_cpus = smp_cpus;
5592
3d878caa 5593 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
b2097003
AL
5594 if (smp_cpus > machine->max_cpus) {
5595 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5596 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5597 machine->max_cpus);
5598 exit(1);
5599 }
5600
998bbd74
GH
5601 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5602
993fbfdb 5603 if (display_type == DT_NOGRAPHIC) {
6a5e8b0e
GH
5604 if (default_parallel)
5605 add_device_config(DEV_PARALLEL, "null");
e1c09175
GH
5606 if (default_serial && default_monitor) {
5607 add_device_config(DEV_SERIAL, "mon:stdio");
5608 } else {
5609 if (default_serial)
5610 add_device_config(DEV_SERIAL, "stdio");
5611 if (default_monitor)
88589343 5612 monitor_parse("stdio");
e1c09175 5613 }
998bbd74
GH
5614 } else {
5615 if (default_serial)
5616 add_device_config(DEV_SERIAL, "vc:80Cx24C");
6a5e8b0e
GH
5617 if (default_parallel)
5618 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
abdeed06 5619 if (default_monitor)
88589343 5620 monitor_parse("vc:80Cx24C");
bc0129d9 5621 }
64465297
GH
5622 if (default_vga)
5623 vga_interface_type = VGA_CIRRUS;
bc0129d9 5624
1a688d3b
GH
5625 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5626 exit(1);
5627
71e3ceb8 5628#ifndef _WIN32
71e3ceb8
TS
5629 if (daemonize) {
5630 pid_t pid;
5631
5632 if (pipe(fds) == -1)
5633 exit(1);
5634
5635 pid = fork();
5636 if (pid > 0) {
5637 uint8_t status;
5638 ssize_t len;
5639
5640 close(fds[1]);
5641
5642 again:
93815bc2
TS
5643 len = read(fds[0], &status, 1);
5644 if (len == -1 && (errno == EINTR))
5645 goto again;
5646
5647 if (len != 1)
5648 exit(1);
5649 else if (status == 1) {
850810d0 5650 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
93815bc2
TS
5651 exit(1);
5652 } else
5653 exit(0);
71e3ceb8 5654 } else if (pid < 0)
93815bc2 5655 exit(1);
71e3ceb8 5656
40ff6d7e
KW
5657 close(fds[0]);
5658 qemu_set_cloexec(fds[1]);
5659
71e3ceb8
TS
5660 setsid();
5661
5662 pid = fork();
5663 if (pid > 0)
5664 exit(0);
5665 else if (pid < 0)
5666 exit(1);
5667
5668 umask(027);
71e3ceb8
TS
5669
5670 signal(SIGTSTP, SIG_IGN);
5671 signal(SIGTTOU, SIG_IGN);
5672 signal(SIGTTIN, SIG_IGN);
5673 }
71e3ceb8 5674
aa26bb2d 5675 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
5676 if (daemonize) {
5677 uint8_t status = 1;
5678 write(fds[1], &status, 1);
5679 } else
850810d0 5680 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
93815bc2
TS
5681 exit(1);
5682 }
b9e82a59 5683#endif
93815bc2 5684
214910a7
MT
5685 if (kvm_enabled()) {
5686 int ret;
5687
5688 ret = kvm_init(smp_cpus);
5689 if (ret < 0) {
5690 fprintf(stderr, "failed to initialize KVM\n");
5691 exit(1);
5692 }
5693 }
5694
3fcf7b6b
AL
5695 if (qemu_init_main_loop()) {
5696 fprintf(stderr, "qemu_init_main_loop failed\n");
5697 exit(1);
5698 }
a20dd508 5699 linux_boot = (kernel_filename != NULL);
6c41b272 5700
f8d39c01
TS
5701 if (!linux_boot && *kernel_cmdline != '\0') {
5702 fprintf(stderr, "-append only allowed with -kernel option\n");
5703 exit(1);
5704 }
5705
5706 if (!linux_boot && initrd_filename != NULL) {
5707 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5708 exit(1);
5709 }
5710
bf65f53f
FN
5711#ifndef _WIN32
5712 /* Win32 doesn't support line-buffering and requires size >= 2 */
b118d61e 5713 setvbuf(stdout, NULL, _IOLBF, 0);
bf65f53f 5714#endif
3b46e624 5715
7183b4b4
AL
5716 if (init_timer_alarm() < 0) {
5717 fprintf(stderr, "could not initialize alarm timer\n");
5718 exit(1);
5719 }
2e70f6ef
PB
5720 if (use_icount && icount_time_shift < 0) {
5721 use_icount = 2;
5722 /* 125MIPS seems a reasonable initial guess at the guest speed.
5723 It will be corrected fairly quickly anyway. */
5724 icount_time_shift = 3;
5725 init_icount_adjust();
5726 }
634fce96 5727
fd1dff4b
FB
5728#ifdef _WIN32
5729 socket_init();
5730#endif
5731
dc1c9fe8
MM
5732 if (net_init_clients() < 0) {
5733 exit(1);
702c651c 5734 }
f1510b2c 5735
406c8df3
GC
5736 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5737 net_set_boot_mask(net_boot);
5738
dc72ac14 5739 /* init the bluetooth world */
bd3c948d
GH
5740 if (foreach_device_config(DEV_BT, bt_parse))
5741 exit(1);
dc72ac14 5742
0824d6fc 5743 /* init the memory */
94a6b54f
PB
5744 if (ram_size == 0)
5745 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9ae02555 5746
26a5f13b
FB
5747 /* init the dynamic translator */
5748 cpu_exec_init_all(tb_size * 1024 * 1024);
5749
eb852011 5750 bdrv_init_with_whitelist();
c4b1fcc0 5751
c163b5ca
LS
5752 blk_mig_init();
5753
aa40fc9c
GH
5754 if (default_drive) {
5755 /* we always create the cdrom drive, even if no disk is there */
5756 drive_add(NULL, CDROM_ALIAS);
c4b1fcc0 5757
aa40fc9c
GH
5758 /* we always create at least one floppy */
5759 drive_add(NULL, FD_ALIAS, 0);
86f55663 5760
aa40fc9c
GH
5761 /* we always create one sd slot, even if no card is in it */
5762 drive_add(NULL, SD_ALIAS);
5763 }
9d413d1d 5764
e4bcb14c 5765 /* open the virtual block devices */
9dfd7c7a 5766 if (snapshot)
7282a033
GH
5767 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5768 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
9dfd7c7a 5769 exit(1);
3e3d5815 5770
2faf58cd 5771 vmstate_register(0, &vmstate_timers ,&timers_state);
c163b5ca
LS
5772 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5773 ram_load, NULL);
8a7ddc38 5774
268a362c
AL
5775 if (nb_numa_nodes > 0) {
5776 int i;
5777
5778 if (nb_numa_nodes > smp_cpus) {
5779 nb_numa_nodes = smp_cpus;
5780 }
5781
5782 /* If no memory size if given for any node, assume the default case
5783 * and distribute the available memory equally across all nodes
5784 */
5785 for (i = 0; i < nb_numa_nodes; i++) {
5786 if (node_mem[i] != 0)
5787 break;
5788 }
5789 if (i == nb_numa_nodes) {
5790 uint64_t usedmem = 0;
5791
5792 /* On Linux, the each node's border has to be 8MB aligned,
5793 * the final node gets the rest.
5794 */
5795 for (i = 0; i < nb_numa_nodes - 1; i++) {
5796 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5797 usedmem += node_mem[i];
5798 }
5799 node_mem[i] = ram_size - usedmem;
5800 }
5801
5802 for (i = 0; i < nb_numa_nodes; i++) {
5803 if (node_cpumask[i] != 0)
5804 break;
5805 }
5806 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5807 * must cope with this anyway, because there are BIOSes out there in
5808 * real machines which also use this scheme.
5809 */
5810 if (i == nb_numa_nodes) {
5811 for (i = 0; i < smp_cpus; i++) {
5812 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5813 }
5814 }
5815 }
5816
998bbd74
GH
5817 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5818 exit(1);
6a5e8b0e
GH
5819 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5820 exit(1);
2796dae0
AL
5821
5822 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5823 const char *devname = virtio_consoles[i];
5824 if (devname && strcmp(devname, "none")) {
5825 char label[32];
5826 snprintf(label, sizeof(label), "virtcon%d", i);
ceecf1d1 5827 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0 5828 if (!virtcon_hds[i]) {
850810d0
JF
5829 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5830 devname, strerror(errno));
2796dae0
AL
5831 exit(1);
5832 }
5833 }
5834 }
5835
aae9460e
PB
5836 module_call_init(MODULE_INIT_DEVICE);
5837
09aaa160
MA
5838 if (watchdog) {
5839 i = select_watchdog(watchdog);
5840 if (i > 0)
5841 exit (i == 1 ? 1 : 0);
5842 }
5843
b6b61144 5844 if (machine->compat_props) {
458fb679 5845 qdev_prop_register_global_list(machine->compat_props);
b6b61144 5846 }
d0fef6fb
GH
5847 qemu_add_globals();
5848
fbe1b595 5849 machine->init(ram_size, boot_devices,
3023f332
AL
5850 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5851
268a362c 5852
67b3b71d
JQ
5853#ifndef _WIN32
5854 /* must be after terminal init, SDL library changes signal handlers */
5855 sighandler_setup();
5856#endif
5857
268a362c
AL
5858 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5859 for (i = 0; i < nb_numa_nodes; i++) {
5860 if (node_cpumask[i] & (1 << env->cpu_index)) {
5861 env->numa_node = i;
5862 }
5863 }
5864 }
5865
6f338c34
AL
5866 current_machine = machine;
5867
3023f332
AL
5868 /* init USB devices */
5869 if (usb_enabled) {
0752706d
MA
5870 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5871 exit(1);
3023f332
AL
5872 }
5873
bd3c948d 5874 /* init generic devices */
f31d07d1 5875 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
bd3c948d
GH
5876 exit(1);
5877
8f391ab4
AL
5878 if (!display_state)
5879 dumb_display_init();
3023f332
AL
5880 /* just use the first displaystate for the moment */
5881 ds = display_state;
993fbfdb
AL
5882
5883 if (display_type == DT_DEFAULT) {
5884#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5885 display_type = DT_SDL;
5886#else
5887 display_type = DT_VNC;
5888 vnc_display = "localhost:0,to=99";
5889 show_vnc_port = 1;
5890#endif
5891 }
5892
5893
5894 switch (display_type) {
5895 case DT_NOGRAPHIC:
5896 break;
4d3b6f6e 5897#if defined(CONFIG_CURSES)
993fbfdb
AL
5898 case DT_CURSES:
5899 curses_display_init(ds, full_screen);
5900 break;
4d3b6f6e 5901#endif
5b0753e0 5902#if defined(CONFIG_SDL)
993fbfdb
AL
5903 case DT_SDL:
5904 sdl_display_init(ds, full_screen, no_frame);
5905 break;
5b0753e0 5906#elif defined(CONFIG_COCOA)
993fbfdb
AL
5907 case DT_SDL:
5908 cocoa_display_init(ds, full_screen);
5909 break;
313aa567 5910#endif
993fbfdb
AL
5911 case DT_VNC:
5912 vnc_display_init(ds);
5913 if (vnc_display_open(ds, vnc_display) < 0)
5914 exit(1);
f92f8afe 5915
993fbfdb
AL
5916 if (show_vnc_port) {
5917 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
f92f8afe 5918 }
993fbfdb
AL
5919 break;
5920 default:
5921 break;
313aa567 5922 }
7d957bd8 5923 dpy_resize(ds);
5b08fc10 5924
3023f332
AL
5925 dcl = ds->listeners;
5926 while (dcl != NULL) {
5927 if (dcl->dpy_refresh != NULL) {
5928 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5929 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
20d8a3ed 5930 }
3023f332 5931 dcl = dcl->next;
20d8a3ed 5932 }
3023f332 5933
993fbfdb 5934 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
9043b62d
BS
5935 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5936 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5937 }
5938
2796dae0
AL
5939 text_consoles_set_display(display_state);
5940
88589343
GH
5941 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5942 exit(1);
82c643ff 5943
59030a8c
AL
5944 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5945 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5946 gdbstub_dev);
5947 exit(1);
45669e00 5948 }
45669e00 5949
3418bd25
GH
5950 qdev_machine_creation_done();
5951
45a50b16
GH
5952 rom_load_all();
5953
504c2948 5954 qemu_system_reset();
05f2401e
JQ
5955 if (loadvm) {
5956 if (load_vmstate(cur_mon, loadvm) < 0) {
5957 autostart = 0;
5958 }
5959 }
d63d307f 5960
2bb8c10c 5961 if (incoming) {
5bb7910a 5962 qemu_start_incoming_migration(incoming);
6b99dadc 5963 } else if (autostart) {
c0f4ce77 5964 vm_start();
6b99dadc 5965 }
ffd843bc 5966
b9e82a59 5967#ifndef _WIN32
71e3ceb8
TS
5968 if (daemonize) {
5969 uint8_t status = 0;
5970 ssize_t len;
71e3ceb8
TS
5971
5972 again1:
5973 len = write(fds[1], &status, 1);
5974 if (len == -1 && (errno == EINTR))
5975 goto again1;
5976
5977 if (len != 1)
5978 exit(1);
5979
bd54b863 5980 chdir("/");
40ff6d7e 5981 TFR(fd = qemu_open("/dev/null", O_RDWR));
71e3ceb8
TS
5982 if (fd == -1)
5983 exit(1);
0858532e 5984 }
71e3ceb8 5985
0858532e
AL
5986 if (run_as) {
5987 pwd = getpwnam(run_as);
5988 if (!pwd) {
5989 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5990 exit(1);
5991 }
5992 }
5993
5994 if (chroot_dir) {
5995 if (chroot(chroot_dir) < 0) {
5996 fprintf(stderr, "chroot failed\n");
5997 exit(1);
5998 }
5999 chdir("/");
6000 }
6001
6002 if (run_as) {
6003 if (setgid(pwd->pw_gid) < 0) {
6004 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6005 exit(1);
6006 }
6007 if (setuid(pwd->pw_uid) < 0) {
6008 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6009 exit(1);
6010 }
6011 if (setuid(0) != -1) {
6012 fprintf(stderr, "Dropping privileges failed\n");
6013 exit(1);
6014 }
6015 }
0858532e
AL
6016
6017 if (daemonize) {
6018 dup2(fd, 0);
6019 dup2(fd, 1);
6020 dup2(fd, 2);
71e3ceb8 6021
0858532e 6022 close(fd);
71e3ceb8 6023 }
b9e82a59 6024#endif
71e3ceb8 6025
8a7ddc38 6026 main_loop();
40c3bac3 6027 quit_timers();
63a01ef8 6028 net_cleanup();
b46a8906 6029
0824d6fc
FB
6030 return 0;
6031}