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