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