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