]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
Use Little Endian for Dirty Log
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
1df912cf
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
0824d6fc 23 */
0824d6fc 24#include <unistd.h>
0824d6fc
FB
25#include <fcntl.h>
26#include <signal.h>
27#include <time.h>
0824d6fc 28#include <errno.h>
67b915a5 29#include <sys/time.h>
c88676f8 30#include <zlib.h>
67b915a5 31
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
9dfd7c7a
GH
1803static QemuOptsList drive_opt_list = {
1804 .name = "drive",
1805 .head = TAILQ_HEAD_INITIALIZER(drive_opt_list.head),
1806 .desc = {
1807 {
1808 .name = "bus",
1809 .type = QEMU_OPT_NUMBER,
1810 .help = "bus number",
1811 },{
1812 .name = "unit",
1813 .type = QEMU_OPT_NUMBER,
1814 .help = "unit number (i.e. lun for scsi)",
1815 },{
1816 .name = "if",
1817 .type = QEMU_OPT_STRING,
1818 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1819 },{
1820 .name = "index",
1821 .type = QEMU_OPT_NUMBER,
1822 },{
1823 .name = "cyls",
1824 .type = QEMU_OPT_NUMBER,
1825 .help = "number of cylinders (ide disk geometry)",
1826 },{
1827 .name = "heads",
1828 .type = QEMU_OPT_NUMBER,
1829 .help = "number of heads (ide disk geometry)",
1830 },{
1831 .name = "secs",
1832 .type = QEMU_OPT_NUMBER,
1833 .help = "number of sectors (ide disk geometry)",
1834 },{
1835 .name = "trans",
1836 .type = QEMU_OPT_STRING,
1837 .help = "chs translation (auto, lba. none)",
1838 },{
1839 .name = "media",
1840 .type = QEMU_OPT_STRING,
1841 .help = "media type (disk, cdrom)",
1842 },{
1843 .name = "snapshot",
1844 .type = QEMU_OPT_BOOL,
1845 },{
1846 .name = "file",
1847 .type = QEMU_OPT_STRING,
1848 .help = "disk image",
1849 },{
1850 .name = "cache",
1851 .type = QEMU_OPT_STRING,
1852 .help = "host cache usage (none, writeback, writethrough)",
1853 },{
1854 .name = "format",
1855 .type = QEMU_OPT_STRING,
1856 .help = "disk format (raw, qcow2, ...)",
1857 },{
1858 .name = "serial",
1859 .type = QEMU_OPT_STRING,
1860 },{
1861 .name = "werror",
1862 .type = QEMU_OPT_STRING,
1863 },{
1864 .name = "addr",
1865 .type = QEMU_OPT_STRING,
1866 .help = "pci address (virtio only)",
1867 },
1868 { /* end if list */ }
1869 },
1870};
1871
1872QemuOpts *drive_add(const char *file, const char *fmt, ...)
e4bcb14c
TS
1873{
1874 va_list ap;
9dfd7c7a
GH
1875 char optstr[1024];
1876 QemuOpts *opts;
e4bcb14c 1877
e4bcb14c 1878 va_start(ap, fmt);
9dfd7c7a 1879 vsnprintf(optstr, sizeof(optstr), fmt, ap);
e4bcb14c
TS
1880 va_end(ap);
1881
9dfd7c7a
GH
1882 opts = qemu_opts_parse(&drive_opt_list, optstr, NULL);
1883 if (!opts) {
1884 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1885 __FUNCTION__, optstr);
1886 return NULL;
1887 }
1888 if (file)
1889 qemu_opt_set(opts, "file", file);
1890 return opts;
b01b1111
AL
1891}
1892
751c6a17 1893DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
e4bcb14c 1894{
751c6a17 1895 DriveInfo *dinfo;
e4bcb14c
TS
1896
1897 /* seek interface, bus and unit */
1898
751c6a17
GH
1899 TAILQ_FOREACH(dinfo, &drives, next) {
1900 if (dinfo->type == type &&
1901 dinfo->bus == bus &&
1902 dinfo->unit == unit)
1903 return dinfo;
1904 }
e4bcb14c 1905
751c6a17 1906 return NULL;
e4bcb14c
TS
1907}
1908
1dae12e6
GH
1909DriveInfo *drive_get_by_id(char *id)
1910{
1911 DriveInfo *dinfo;
1912
1913 TAILQ_FOREACH(dinfo, &drives, next) {
1914 if (strcmp(id, dinfo->id))
1915 continue;
1916 return dinfo;
1917 }
1918 return NULL;
1919}
1920
f60d39bc 1921int drive_get_max_bus(BlockInterfaceType type)
e4bcb14c
TS
1922{
1923 int max_bus;
751c6a17 1924 DriveInfo *dinfo;
e4bcb14c
TS
1925
1926 max_bus = -1;
751c6a17
GH
1927 TAILQ_FOREACH(dinfo, &drives, next) {
1928 if(dinfo->type == type &&
1929 dinfo->bus > max_bus)
1930 max_bus = dinfo->bus;
e4bcb14c
TS
1931 }
1932 return max_bus;
1933}
1934
fa879c64
AL
1935const char *drive_get_serial(BlockDriverState *bdrv)
1936{
751c6a17 1937 DriveInfo *dinfo;
fa879c64 1938
751c6a17
GH
1939 TAILQ_FOREACH(dinfo, &drives, next) {
1940 if (dinfo->bdrv == bdrv)
1941 return dinfo->serial;
1942 }
fa879c64
AL
1943
1944 return "\0";
1945}
1946
428c5705
AL
1947BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1948{
751c6a17 1949 DriveInfo *dinfo;
428c5705 1950
751c6a17
GH
1951 TAILQ_FOREACH(dinfo, &drives, next) {
1952 if (dinfo->bdrv == bdrv)
1953 return dinfo->onerror;
1954 }
428c5705 1955
cdad4bd8 1956 return BLOCK_ERR_STOP_ENOSPC;
428c5705
AL
1957}
1958
a1620fac
AJ
1959static void bdrv_format_print(void *opaque, const char *name)
1960{
1961 fprintf(stderr, " %s", name);
1962}
1963
b01b1111
AL
1964void drive_uninit(BlockDriverState *bdrv)
1965{
751c6a17 1966 DriveInfo *dinfo;
b01b1111 1967
751c6a17
GH
1968 TAILQ_FOREACH(dinfo, &drives, next) {
1969 if (dinfo->bdrv != bdrv)
1970 continue;
9dfd7c7a 1971 qemu_opts_del(dinfo->opts);
751c6a17
GH
1972 TAILQ_REMOVE(&drives, dinfo, next);
1973 qemu_free(dinfo);
1974 break;
1975 }
b01b1111
AL
1976}
1977
9dfd7c7a 1978DriveInfo *drive_init(QemuOpts *opts, void *opaque,
751c6a17 1979 int *fatal_error)
e4bcb14c 1980{
9dfd7c7a
GH
1981 const char *buf;
1982 const char *file = NULL;
c8522bdf 1983 char devname[128];
9dfd7c7a 1984 const char *serial;
c8522bdf 1985 const char *mediastr = "";
f60d39bc 1986 BlockInterfaceType type;
e4bcb14c
TS
1987 enum { MEDIA_DISK, MEDIA_CDROM } media;
1988 int bus_id, unit_id;
1989 int cyls, heads, secs, translation;
1e72d3b7 1990 BlockDriver *drv = NULL;
4d73cd3b 1991 QEMUMachine *machine = opaque;
e4bcb14c
TS
1992 int max_devs;
1993 int index;
33f00271 1994 int cache;
428c5705 1995 int bdrv_flags, onerror;
c2cc47a4 1996 const char *devaddr;
751c6a17 1997 DriveInfo *dinfo;
9dfd7c7a 1998 int snapshot = 0;
e4bcb14c 1999
9dfd7c7a 2000 *fatal_error = 1;
e4bcb14c 2001
e4bcb14c 2002 translation = BIOS_ATA_TRANSLATION_AUTO;
0aa217e4 2003 cache = 1;
e4bcb14c 2004
c9b1ae2c 2005 if (machine->use_scsi) {
f60d39bc 2006 type = IF_SCSI;
e4bcb14c 2007 max_devs = MAX_SCSI_DEVS;
363a37d5 2008 pstrcpy(devname, sizeof(devname), "scsi");
e4bcb14c 2009 } else {
f60d39bc 2010 type = IF_IDE;
e4bcb14c 2011 max_devs = MAX_IDE_DEVS;
363a37d5 2012 pstrcpy(devname, sizeof(devname), "ide");
e4bcb14c
TS
2013 }
2014 media = MEDIA_DISK;
2015
2016 /* extract parameters */
9dfd7c7a
GH
2017 bus_id = qemu_opt_get_number(opts, "bus", 0);
2018 unit_id = qemu_opt_get_number(opts, "unit", -1);
2019 index = qemu_opt_get_number(opts, "index", -1);
e4bcb14c 2020
9dfd7c7a
GH
2021 cyls = qemu_opt_get_number(opts, "cyls", 0);
2022 heads = qemu_opt_get_number(opts, "heads", 0);
2023 secs = qemu_opt_get_number(opts, "secs", 0);
e4bcb14c 2024
9dfd7c7a 2025 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
e4bcb14c 2026
9dfd7c7a
GH
2027 file = qemu_opt_get(opts, "file");
2028 serial = qemu_opt_get(opts, "serial");
2029
2030 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
ae45d369 2031 pstrcpy(devname, sizeof(devname), buf);
e4bcb14c 2032 if (!strcmp(buf, "ide")) {
f60d39bc 2033 type = IF_IDE;
e4bcb14c
TS
2034 max_devs = MAX_IDE_DEVS;
2035 } else if (!strcmp(buf, "scsi")) {
f60d39bc 2036 type = IF_SCSI;
e4bcb14c
TS
2037 max_devs = MAX_SCSI_DEVS;
2038 } else if (!strcmp(buf, "floppy")) {
f60d39bc 2039 type = IF_FLOPPY;
e4bcb14c
TS
2040 max_devs = 0;
2041 } else if (!strcmp(buf, "pflash")) {
f60d39bc 2042 type = IF_PFLASH;
e4bcb14c
TS
2043 max_devs = 0;
2044 } else if (!strcmp(buf, "mtd")) {
f60d39bc 2045 type = IF_MTD;
e4bcb14c
TS
2046 max_devs = 0;
2047 } else if (!strcmp(buf, "sd")) {
f60d39bc 2048 type = IF_SD;
e4bcb14c 2049 max_devs = 0;
6e02c38d
AL
2050 } else if (!strcmp(buf, "virtio")) {
2051 type = IF_VIRTIO;
2052 max_devs = 0;
62d23efa
AL
2053 } else if (!strcmp(buf, "xen")) {
2054 type = IF_XEN;
2055 max_devs = 0;
2056 } else {
9dfd7c7a 2057 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
751c6a17 2058 return NULL;
e4bcb14c
TS
2059 }
2060 }
2061
e4bcb14c
TS
2062 if (cyls || heads || secs) {
2063 if (cyls < 1 || cyls > 16383) {
9dfd7c7a 2064 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
751c6a17 2065 return NULL;
e4bcb14c
TS
2066 }
2067 if (heads < 1 || heads > 16) {
9dfd7c7a 2068 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
751c6a17 2069 return NULL;
e4bcb14c
TS
2070 }
2071 if (secs < 1 || secs > 63) {
9dfd7c7a 2072 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
751c6a17 2073 return NULL;
e4bcb14c
TS
2074 }
2075 }
2076
9dfd7c7a 2077 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
e4bcb14c
TS
2078 if (!cyls) {
2079 fprintf(stderr,
2080 "qemu: '%s' trans must be used with cyls,heads and secs\n",
9dfd7c7a 2081 buf);
751c6a17 2082 return NULL;
e4bcb14c
TS
2083 }
2084 if (!strcmp(buf, "none"))
2085 translation = BIOS_ATA_TRANSLATION_NONE;
2086 else if (!strcmp(buf, "lba"))
2087 translation = BIOS_ATA_TRANSLATION_LBA;
2088 else if (!strcmp(buf, "auto"))
2089 translation = BIOS_ATA_TRANSLATION_AUTO;
2090 else {
9dfd7c7a 2091 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
751c6a17 2092 return NULL;
e4bcb14c
TS
2093 }
2094 }
2095
9dfd7c7a 2096 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
e4bcb14c
TS
2097 if (!strcmp(buf, "disk")) {
2098 media = MEDIA_DISK;
2099 } else if (!strcmp(buf, "cdrom")) {
2100 if (cyls || secs || heads) {
2101 fprintf(stderr,
9dfd7c7a 2102 "qemu: '%s' invalid physical CHS format\n", buf);
751c6a17 2103 return NULL;
e4bcb14c
TS
2104 }
2105 media = MEDIA_CDROM;
2106 } else {
9dfd7c7a 2107 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
751c6a17 2108 return NULL;
e4bcb14c
TS
2109 }
2110 }
2111
9dfd7c7a 2112 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
9f7965c7 2113 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
33f00271 2114 cache = 0;
9f7965c7 2115 else if (!strcmp(buf, "writethrough"))
33f00271 2116 cache = 1;
9f7965c7
AL
2117 else if (!strcmp(buf, "writeback"))
2118 cache = 2;
33f00271
AZ
2119 else {
2120 fprintf(stderr, "qemu: invalid cache option\n");
751c6a17 2121 return NULL;
33f00271
AZ
2122 }
2123 }
2124
9dfd7c7a 2125 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
a1620fac
AJ
2126 if (strcmp(buf, "?") == 0) {
2127 fprintf(stderr, "qemu: Supported formats:");
2128 bdrv_iterate_format(bdrv_format_print, NULL);
2129 fprintf(stderr, "\n");
751c6a17 2130 return NULL;
a1620fac 2131 }
1e72d3b7
AJ
2132 drv = bdrv_find_format(buf);
2133 if (!drv) {
2134 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
751c6a17 2135 return NULL;
1e72d3b7
AJ
2136 }
2137 }
2138
cdad4bd8 2139 onerror = BLOCK_ERR_STOP_ENOSPC;
9dfd7c7a 2140 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
869a5c6d 2141 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
ea8a5d7f 2142 fprintf(stderr, "werror is no supported by this format\n");
751c6a17 2143 return NULL;
428c5705
AL
2144 }
2145 if (!strcmp(buf, "ignore"))
2146 onerror = BLOCK_ERR_IGNORE;
2147 else if (!strcmp(buf, "enospc"))
2148 onerror = BLOCK_ERR_STOP_ENOSPC;
2149 else if (!strcmp(buf, "stop"))
2150 onerror = BLOCK_ERR_STOP_ANY;
2151 else if (!strcmp(buf, "report"))
2152 onerror = BLOCK_ERR_REPORT;
2153 else {
2154 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
751c6a17 2155 return NULL;
428c5705
AL
2156 }
2157 }
2158
9dfd7c7a 2159 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
c2cc47a4 2160 if (type != IF_VIRTIO) {
9dfd7c7a 2161 fprintf(stderr, "addr is not supported\n");
751c6a17 2162 return NULL;
c2cc47a4 2163 }
c2cc47a4
MA
2164 }
2165
e4bcb14c
TS
2166 /* compute bus and unit according index */
2167
2168 if (index != -1) {
2169 if (bus_id != 0 || unit_id != -1) {
2170 fprintf(stderr,
9dfd7c7a 2171 "qemu: index cannot be used with bus and unit\n");
751c6a17 2172 return NULL;
e4bcb14c
TS
2173 }
2174 if (max_devs == 0)
2175 {
2176 unit_id = index;
2177 bus_id = 0;
2178 } else {
2179 unit_id = index % max_devs;
2180 bus_id = index / max_devs;
2181 }
2182 }
2183
2184 /* if user doesn't specify a unit_id,
2185 * try to find the first free
2186 */
2187
2188 if (unit_id == -1) {
2189 unit_id = 0;
751c6a17 2190 while (drive_get(type, bus_id, unit_id) != NULL) {
e4bcb14c
TS
2191 unit_id++;
2192 if (max_devs && unit_id >= max_devs) {
2193 unit_id -= max_devs;
2194 bus_id++;
2195 }
2196 }
2197 }
2198
2199 /* check unit id */
2200
2201 if (max_devs && unit_id >= max_devs) {
9dfd7c7a
GH
2202 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2203 unit_id, max_devs - 1);
751c6a17 2204 return NULL;
e4bcb14c
TS
2205 }
2206
2207 /*
2208 * ignore multiple definitions
2209 */
2210
751c6a17
GH
2211 if (drive_get(type, bus_id, unit_id) != NULL) {
2212 *fatal_error = 0;
2213 return NULL;
2214 }
e4bcb14c
TS
2215
2216 /* init */
2217
751c6a17 2218 dinfo = qemu_mallocz(sizeof(*dinfo));
9dfd7c7a
GH
2219 if ((buf = qemu_opt_get(opts, "id")) != NULL) {
2220 dinfo->id = qemu_strdup(buf);
2221 } else {
1dae12e6 2222 /* no id supplied -> create one */
9dfd7c7a 2223 dinfo->id = qemu_mallocz(32);
1dae12e6
GH
2224 if (type == IF_IDE || type == IF_SCSI)
2225 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2226 if (max_devs)
9dfd7c7a 2227 snprintf(dinfo->id, 32, "%s%i%s%i",
1dae12e6
GH
2228 devname, bus_id, mediastr, unit_id);
2229 else
9dfd7c7a 2230 snprintf(dinfo->id, 32, "%s%s%i",
1dae12e6
GH
2231 devname, mediastr, unit_id);
2232 }
1dae12e6 2233 dinfo->bdrv = bdrv_new(dinfo->id);
751c6a17
GH
2234 dinfo->devaddr = devaddr;
2235 dinfo->type = type;
2236 dinfo->bus = bus_id;
2237 dinfo->unit = unit_id;
2238 dinfo->onerror = onerror;
9dfd7c7a
GH
2239 dinfo->opts = opts;
2240 if (serial)
2241 strncpy(dinfo->serial, serial, sizeof(serial));
751c6a17 2242 TAILQ_INSERT_TAIL(&drives, dinfo, next);
e4bcb14c 2243
f60d39bc 2244 switch(type) {
e4bcb14c
TS
2245 case IF_IDE:
2246 case IF_SCSI:
62d23efa 2247 case IF_XEN:
e4bcb14c
TS
2248 switch(media) {
2249 case MEDIA_DISK:
2250 if (cyls != 0) {
1dae12e6
GH
2251 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2252 bdrv_set_translation_hint(dinfo->bdrv, translation);
e4bcb14c
TS
2253 }
2254 break;
2255 case MEDIA_CDROM:
1dae12e6 2256 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
e4bcb14c
TS
2257 break;
2258 }
2259 break;
2260 case IF_SD:
2261 /* FIXME: This isn't really a floppy, but it's a reasonable
2262 approximation. */
2263 case IF_FLOPPY:
1dae12e6 2264 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
e4bcb14c
TS
2265 break;
2266 case IF_PFLASH:
2267 case IF_MTD:
6e02c38d 2268 case IF_VIRTIO:
e4bcb14c 2269 break;
aae9460e
PB
2270 case IF_COUNT:
2271 abort();
e4bcb14c 2272 }
9dfd7c7a 2273 if (!file) {
751c6a17
GH
2274 *fatal_error = 0;
2275 return NULL;
2276 }
33f00271 2277 bdrv_flags = 0;
9f7965c7 2278 if (snapshot) {
33f00271 2279 bdrv_flags |= BDRV_O_SNAPSHOT;
9f7965c7
AL
2280 cache = 2; /* always use write-back with snapshot */
2281 }
2282 if (cache == 0) /* no caching */
2283 bdrv_flags |= BDRV_O_NOCACHE;
2284 else if (cache == 2) /* write-back */
2285 bdrv_flags |= BDRV_O_CACHE_WB;
1dae12e6 2286 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
e4bcb14c
TS
2287 fprintf(stderr, "qemu: could not open disk image %s\n",
2288 file);
751c6a17 2289 return NULL;
e4bcb14c 2290 }
1dae12e6 2291 if (bdrv_key_required(dinfo->bdrv))
c0f4ce77 2292 autostart = 0;
751c6a17
GH
2293 *fatal_error = 0;
2294 return dinfo;
e4bcb14c
TS
2295}
2296
9dfd7c7a
GH
2297static int drive_init_func(QemuOpts *opts, void *opaque)
2298{
2299 QEMUMachine *machine = opaque;
2300 int fatal_error = 0;
2301
2302 if (drive_init(opts, machine, &fatal_error) == NULL) {
2303 if (fatal_error)
2304 return 1;
2305 }
2306 return 0;
2307}
2308
2309static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2310{
2311 if (NULL == qemu_opt_get(opts, "snapshot")) {
2312 qemu_opt_set(opts, "snapshot", "on");
2313 }
2314 return 0;
2315}
2316
76e30d0f
JK
2317void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2318{
2319 boot_set_handler = func;
2320 boot_set_opaque = opaque;
2321}
2322
2323int qemu_boot_set(const char *boot_devices)
2324{
2325 if (!boot_set_handler) {
2326 return -EINVAL;
2327 }
2328 return boot_set_handler(boot_set_opaque, boot_devices);
2329}
2330
ef3adf68
JK
2331static int parse_bootdevices(char *devices)
2332{
2333 /* We just do some generic consistency checks */
2334 const char *p;
2335 int bitmap = 0;
2336
2337 for (p = devices; *p != '\0'; p++) {
2338 /* Allowed boot devices are:
2339 * a-b: floppy disk drives
2340 * c-f: IDE disk drives
2341 * g-m: machine implementation dependant drives
2342 * n-p: network devices
2343 * It's up to each machine implementation to check if the given boot
2344 * devices match the actual hardware implementation and firmware
2345 * features.
2346 */
2347 if (*p < 'a' || *p > 'p') {
2348 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2349 exit(1);
2350 }
2351 if (bitmap & (1 << (*p - 'a'))) {
2352 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2353 exit(1);
2354 }
2355 bitmap |= 1 << (*p - 'a');
2356 }
2357 return bitmap;
2358}
2359
e0f084bf
JK
2360static void restore_boot_devices(void *opaque)
2361{
2362 char *standard_boot_devices = opaque;
2363
2364 qemu_boot_set(standard_boot_devices);
2365
2366 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2367 qemu_free(standard_boot_devices);
2368}
2369
268a362c
AL
2370static void numa_add(const char *optarg)
2371{
2372 char option[128];
2373 char *endptr;
2374 unsigned long long value, endvalue;
2375 int nodenr;
2376
2377 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2378 if (!strcmp(option, "node")) {
2379 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2380 nodenr = nb_numa_nodes;
2381 } else {
2382 nodenr = strtoull(option, NULL, 10);
2383 }
2384
2385 if (get_param_value(option, 128, "mem", optarg) == 0) {
2386 node_mem[nodenr] = 0;
2387 } else {
2388 value = strtoull(option, &endptr, 0);
2389 switch (*endptr) {
2390 case 0: case 'M': case 'm':
2391 value <<= 20;
2392 break;
2393 case 'G': case 'g':
2394 value <<= 30;
2395 break;
2396 }
2397 node_mem[nodenr] = value;
2398 }
2399 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2400 node_cpumask[nodenr] = 0;
2401 } else {
2402 value = strtoull(option, &endptr, 10);
2403 if (value >= 64) {
2404 value = 63;
2405 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2406 } else {
2407 if (*endptr == '-') {
2408 endvalue = strtoull(endptr+1, &endptr, 10);
2409 if (endvalue >= 63) {
2410 endvalue = 62;
2411 fprintf(stderr,
2412 "only 63 CPUs in NUMA mode supported.\n");
2413 }
2414 value = (1 << (endvalue + 1)) - (1 << value);
2415 } else {
2416 value = 1 << value;
2417 }
2418 }
2419 node_cpumask[nodenr] = value;
2420 }
2421 nb_numa_nodes++;
2422 }
2423 return;
2424}
2425
a594cfbf
FB
2426/***********************************************************/
2427/* USB devices */
2428
0d92ed30
PB
2429static USBPort *used_usb_ports;
2430static USBPort *free_usb_ports;
2431
2432/* ??? Maybe change this to register a hub to keep track of the topology. */
2433void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2434 usb_attachfn attach)
2435{
2436 port->opaque = opaque;
2437 port->index = index;
2438 port->attach = attach;
2439 port->next = free_usb_ports;
2440 free_usb_ports = port;
2441}
2442
4b096fc9
AL
2443int usb_device_add_dev(USBDevice *dev)
2444{
2445 USBPort *port;
2446
2447 /* Find a USB port to add the device to. */
2448 port = free_usb_ports;
2449 if (!port->next) {
2450 USBDevice *hub;
2451
2452 /* Create a new hub and chain it on. */
2453 free_usb_ports = NULL;
2454 port->next = used_usb_ports;
2455 used_usb_ports = port;
2456
2457 hub = usb_hub_init(VM_USB_HUB_SIZE);
2458 usb_attach(port, hub);
2459 port = free_usb_ports;
2460 }
2461
2462 free_usb_ports = port->next;
2463 port->next = used_usb_ports;
2464 used_usb_ports = port;
2465 usb_attach(port, dev);
2466 return 0;
2467}
2468
bb5fc20f
AL
2469static void usb_msd_password_cb(void *opaque, int err)
2470{
2471 USBDevice *dev = opaque;
2472
2473 if (!err)
2474 usb_device_add_dev(dev);
2475 else
2476 dev->handle_destroy(dev);
2477}
2478
c0f4ce77 2479static int usb_device_add(const char *devname, int is_hotplug)
a594cfbf
FB
2480{
2481 const char *p;
2482 USBDevice *dev;
a594cfbf 2483
0d92ed30 2484 if (!free_usb_ports)
a594cfbf
FB
2485 return -1;
2486
2487 if (strstart(devname, "host:", &p)) {
2488 dev = usb_host_device_open(p);
a594cfbf
FB
2489 } else if (!strcmp(devname, "mouse")) {
2490 dev = usb_mouse_init();
09b26c5e 2491 } else if (!strcmp(devname, "tablet")) {
47b2d338
AZ
2492 dev = usb_tablet_init();
2493 } else if (!strcmp(devname, "keyboard")) {
2494 dev = usb_keyboard_init();
2e5d83bb 2495 } else if (strstart(devname, "disk:", &p)) {
c0f4ce77
AL
2496 BlockDriverState *bs;
2497
bb5fc20f 2498 dev = usb_msd_init(p);
c0f4ce77
AL
2499 if (!dev)
2500 return -1;
bb5fc20f 2501 bs = usb_msd_get_bdrv(dev);
c0f4ce77
AL
2502 if (bdrv_key_required(bs)) {
2503 autostart = 0;
bb5fc20f 2504 if (is_hotplug) {
376253ec
AL
2505 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2506 dev);
bb5fc20f 2507 return 0;
c0f4ce77
AL
2508 }
2509 }
f6d2a316
AZ
2510 } else if (!strcmp(devname, "wacom-tablet")) {
2511 dev = usb_wacom_init();
a7954218
AZ
2512 } else if (strstart(devname, "serial:", &p)) {
2513 dev = usb_serial_init(p);
2e4d9fb1
AJ
2514#ifdef CONFIG_BRLAPI
2515 } else if (!strcmp(devname, "braille")) {
2516 dev = usb_baum_init();
2517#endif
6c9f886c 2518 } else if (strstart(devname, "net:", &p)) {
9ad97e65 2519 int nic = nb_nics;
6c9f886c 2520
10ae5a7a 2521 if (net_client_init(NULL, "nic", p) < 0)
6c9f886c 2522 return -1;
9ad97e65
AZ
2523 nd_table[nic].model = "usb";
2524 dev = usb_net_init(&nd_table[nic]);
dc72ac14
AZ
2525 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2526 dev = usb_bt_init(devname[2] ? hci_init(p) :
2527 bt_new_hci(qemu_find_bt_vlan(0)));
a594cfbf
FB
2528 } else {
2529 return -1;
2530 }
0d92ed30
PB
2531 if (!dev)
2532 return -1;
2533
4b096fc9 2534 return usb_device_add_dev(dev);
a594cfbf
FB
2535}
2536
1f3870ab 2537int usb_device_del_addr(int bus_num, int addr)
a594cfbf 2538{
0d92ed30
PB
2539 USBPort *port;
2540 USBPort **lastp;
059809e4 2541 USBDevice *dev;
a594cfbf 2542
0d92ed30 2543 if (!used_usb_ports)
a594cfbf
FB
2544 return -1;
2545
a594cfbf
FB
2546 if (bus_num != 0)
2547 return -1;
0d92ed30
PB
2548
2549 lastp = &used_usb_ports;
2550 port = used_usb_ports;
2551 while (port && port->dev->addr != addr) {
2552 lastp = &port->next;
2553 port = port->next;
a594cfbf 2554 }
0d92ed30
PB
2555
2556 if (!port)
a594cfbf 2557 return -1;
0d92ed30 2558
059809e4 2559 dev = port->dev;
0d92ed30
PB
2560 *lastp = port->next;
2561 usb_attach(port, NULL);
059809e4 2562 dev->handle_destroy(dev);
0d92ed30
PB
2563 port->next = free_usb_ports;
2564 free_usb_ports = port;
a594cfbf
FB
2565 return 0;
2566}
2567
1f3870ab
AL
2568static int usb_device_del(const char *devname)
2569{
2570 int bus_num, addr;
2571 const char *p;
2572
5d0c5750
AL
2573 if (strstart(devname, "host:", &p))
2574 return usb_host_device_close(p);
2575
1f3870ab
AL
2576 if (!used_usb_ports)
2577 return -1;
2578
2579 p = strchr(devname, '.');
2580 if (!p)
2581 return -1;
2582 bus_num = strtoul(devname, NULL, 0);
2583 addr = strtoul(p + 1, NULL, 0);
2584
2585 return usb_device_del_addr(bus_num, addr);
2586}
2587
bd3c948d
GH
2588static int usb_parse(const char *cmdline)
2589{
2590 return usb_device_add(cmdline, 0);
2591}
2592
376253ec 2593void do_usb_add(Monitor *mon, const char *devname)
a594cfbf 2594{
c0f4ce77 2595 usb_device_add(devname, 1);
a594cfbf
FB
2596}
2597
376253ec 2598void do_usb_del(Monitor *mon, const char *devname)
a594cfbf 2599{
4b096fc9 2600 usb_device_del(devname);
a594cfbf
FB
2601}
2602
376253ec 2603void usb_info(Monitor *mon)
a594cfbf
FB
2604{
2605 USBDevice *dev;
0d92ed30 2606 USBPort *port;
a594cfbf
FB
2607 const char *speed_str;
2608
0d92ed30 2609 if (!usb_enabled) {
376253ec 2610 monitor_printf(mon, "USB support not enabled\n");
a594cfbf
FB
2611 return;
2612 }
2613
0d92ed30
PB
2614 for (port = used_usb_ports; port; port = port->next) {
2615 dev = port->dev;
2616 if (!dev)
2617 continue;
2618 switch(dev->speed) {
5fafdf24
TS
2619 case USB_SPEED_LOW:
2620 speed_str = "1.5";
0d92ed30 2621 break;
5fafdf24
TS
2622 case USB_SPEED_FULL:
2623 speed_str = "12";
0d92ed30 2624 break;
5fafdf24
TS
2625 case USB_SPEED_HIGH:
2626 speed_str = "480";
0d92ed30
PB
2627 break;
2628 default:
5fafdf24 2629 speed_str = "?";
0d92ed30 2630 break;
a594cfbf 2631 }
376253ec
AL
2632 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2633 0, dev->addr, speed_str, dev->devname);
a594cfbf
FB
2634 }
2635}
2636
201a51fc
AZ
2637/***********************************************************/
2638/* PCMCIA/Cardbus */
2639
2640static struct pcmcia_socket_entry_s {
bc24a225 2641 PCMCIASocket *socket;
201a51fc
AZ
2642 struct pcmcia_socket_entry_s *next;
2643} *pcmcia_sockets = 0;
2644
bc24a225 2645void pcmcia_socket_register(PCMCIASocket *socket)
201a51fc
AZ
2646{
2647 struct pcmcia_socket_entry_s *entry;
2648
2649 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2650 entry->socket = socket;
2651 entry->next = pcmcia_sockets;
2652 pcmcia_sockets = entry;
2653}
2654
bc24a225 2655void pcmcia_socket_unregister(PCMCIASocket *socket)
201a51fc
AZ
2656{
2657 struct pcmcia_socket_entry_s *entry, **ptr;
2658
2659 ptr = &pcmcia_sockets;
2660 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2661 if (entry->socket == socket) {
2662 *ptr = entry->next;
2663 qemu_free(entry);
2664 }
2665}
2666
376253ec 2667void pcmcia_info(Monitor *mon)
201a51fc
AZ
2668{
2669 struct pcmcia_socket_entry_s *iter;
376253ec 2670
201a51fc 2671 if (!pcmcia_sockets)
376253ec 2672 monitor_printf(mon, "No PCMCIA sockets\n");
201a51fc
AZ
2673
2674 for (iter = pcmcia_sockets; iter; iter = iter->next)
376253ec
AL
2675 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2676 iter->socket->attached ? iter->socket->card_string :
2677 "Empty");
201a51fc
AZ
2678}
2679
2ff89790 2680/***********************************************************/
3023f332
AL
2681/* register display */
2682
7b5d76da
AL
2683struct DisplayAllocator default_allocator = {
2684 defaultallocator_create_displaysurface,
2685 defaultallocator_resize_displaysurface,
2686 defaultallocator_free_displaysurface
2687};
2688
3023f332
AL
2689void register_displaystate(DisplayState *ds)
2690{
2691 DisplayState **s;
2692 s = &display_state;
2693 while (*s != NULL)
2694 s = &(*s)->next;
2695 ds->next = NULL;
2696 *s = ds;
2697}
2698
2699DisplayState *get_displaystate(void)
2700{
2701 return display_state;
2702}
2703
7b5d76da
AL
2704DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2705{
2706 if(ds->allocator == &default_allocator) ds->allocator = da;
2707 return ds->allocator;
2708}
2709
2ff89790
TS
2710/* dumb display */
2711
8f391ab4 2712static void dumb_display_init(void)
2ff89790 2713{
8f391ab4 2714 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
7b5d76da
AL
2715 ds->allocator = &default_allocator;
2716 ds->surface = qemu_create_displaysurface(ds, 640, 480);
8f391ab4 2717 register_displaystate(ds);
2ff89790
TS
2718}
2719
8a7ddc38
FB
2720/***********************************************************/
2721/* I/O handling */
0824d6fc 2722
c4b1fcc0
FB
2723typedef struct IOHandlerRecord {
2724 int fd;
7c9d8e07
FB
2725 IOCanRWHandler *fd_read_poll;
2726 IOHandler *fd_read;
2727 IOHandler *fd_write;
cafffd40 2728 int deleted;
c4b1fcc0
FB
2729 void *opaque;
2730 /* temporary data */
2731 struct pollfd *ufd;
8a7ddc38 2732 struct IOHandlerRecord *next;
c4b1fcc0
FB
2733} IOHandlerRecord;
2734
8a7ddc38 2735static IOHandlerRecord *first_io_handler;
c4b1fcc0 2736
7c9d8e07
FB
2737/* XXX: fd_read_poll should be suppressed, but an API change is
2738 necessary in the character devices to suppress fd_can_read(). */
5fafdf24
TS
2739int qemu_set_fd_handler2(int fd,
2740 IOCanRWHandler *fd_read_poll,
2741 IOHandler *fd_read,
2742 IOHandler *fd_write,
7c9d8e07 2743 void *opaque)
c4b1fcc0 2744{
7c9d8e07 2745 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 2746
7c9d8e07
FB
2747 if (!fd_read && !fd_write) {
2748 pioh = &first_io_handler;
2749 for(;;) {
2750 ioh = *pioh;
2751 if (ioh == NULL)
2752 break;
2753 if (ioh->fd == fd) {
cafffd40 2754 ioh->deleted = 1;
7c9d8e07
FB
2755 break;
2756 }
2757 pioh = &ioh->next;
2758 }
2759 } else {
2760 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2761 if (ioh->fd == fd)
2762 goto found;
2763 }
2764 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
7c9d8e07
FB
2765 ioh->next = first_io_handler;
2766 first_io_handler = ioh;
2767 found:
2768 ioh->fd = fd;
2769 ioh->fd_read_poll = fd_read_poll;
2770 ioh->fd_read = fd_read;
2771 ioh->fd_write = fd_write;
2772 ioh->opaque = opaque;
cafffd40 2773 ioh->deleted = 0;
7c9d8e07 2774 }
c4b1fcc0
FB
2775 return 0;
2776}
2777
5fafdf24
TS
2778int qemu_set_fd_handler(int fd,
2779 IOHandler *fd_read,
2780 IOHandler *fd_write,
7c9d8e07 2781 void *opaque)
8a7ddc38 2782{
7c9d8e07 2783 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
2784}
2785
56f3a5d0 2786#ifdef _WIN32
f331110f
FB
2787/***********************************************************/
2788/* Polling handling */
2789
2790typedef struct PollingEntry {
2791 PollingFunc *func;
2792 void *opaque;
2793 struct PollingEntry *next;
2794} PollingEntry;
2795
2796static PollingEntry *first_polling_entry;
2797
2798int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2799{
2800 PollingEntry **ppe, *pe;
2801 pe = qemu_mallocz(sizeof(PollingEntry));
f331110f
FB
2802 pe->func = func;
2803 pe->opaque = opaque;
2804 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2805 *ppe = pe;
2806 return 0;
2807}
2808
2809void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2810{
2811 PollingEntry **ppe, *pe;
2812 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2813 pe = *ppe;
2814 if (pe->func == func && pe->opaque == opaque) {
2815 *ppe = pe->next;
2816 qemu_free(pe);
2817 break;
2818 }
2819 }
2820}
2821
a18e524a
FB
2822/***********************************************************/
2823/* Wait objects support */
2824typedef struct WaitObjects {
2825 int num;
2826 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2827 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2828 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2829} WaitObjects;
2830
2831static WaitObjects wait_objects = {0};
3b46e624 2832
a18e524a
FB
2833int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2834{
2835 WaitObjects *w = &wait_objects;
2836
2837 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2838 return -1;
2839 w->events[w->num] = handle;
2840 w->func[w->num] = func;
2841 w->opaque[w->num] = opaque;
2842 w->num++;
2843 return 0;
2844}
2845
2846void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2847{
2848 int i, found;
2849 WaitObjects *w = &wait_objects;
2850
2851 found = 0;
2852 for (i = 0; i < w->num; i++) {
2853 if (w->events[i] == handle)
2854 found = 1;
2855 if (found) {
2856 w->events[i] = w->events[i + 1];
2857 w->func[i] = w->func[i + 1];
2858 w->opaque[i] = w->opaque[i + 1];
3b46e624 2859 }
a18e524a
FB
2860 }
2861 if (found)
2862 w->num--;
2863}
2864#endif
2865
8a7ddc38
FB
2866/***********************************************************/
2867/* ram save/restore */
2868
8a7ddc38
FB
2869static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2870{
2871 int v;
2872
2873 v = qemu_get_byte(f);
2874 switch(v) {
2875 case 0:
2876 if (qemu_get_buffer(f, buf, len) != len)
2877 return -EIO;
2878 break;
2879 case 1:
2880 v = qemu_get_byte(f);
2881 memset(buf, v, len);
2882 break;
2883 default:
2884 return -EINVAL;
2885 }
871d2f07
AL
2886
2887 if (qemu_file_has_error(f))
2888 return -EIO;
2889
8a7ddc38
FB
2890 return 0;
2891}
2892
c88676f8
FB
2893static int ram_load_v1(QEMUFile *f, void *opaque)
2894{
00f82b8a
AJ
2895 int ret;
2896 ram_addr_t i;
c88676f8 2897
94a6b54f 2898 if (qemu_get_be32(f) != last_ram_offset)
c88676f8 2899 return -EINVAL;
94a6b54f 2900 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
5579c7f3 2901 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
c88676f8
FB
2902 if (ret)
2903 return ret;
2904 }
2905 return 0;
2906}
2907
2908#define BDRV_HASH_BLOCK_SIZE 1024
2909#define IOBUF_SIZE 4096
2910#define RAM_CBLOCK_MAGIC 0xfabe
2911
c88676f8
FB
2912typedef struct RamDecompressState {
2913 z_stream zstream;
2914 QEMUFile *f;
2915 uint8_t buf[IOBUF_SIZE];
2916} RamDecompressState;
2917
2918static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2919{
2920 int ret;
2921 memset(s, 0, sizeof(*s));
2922 s->f = f;
2923 ret = inflateInit(&s->zstream);
2924 if (ret != Z_OK)
2925 return -1;
2926 return 0;
2927}
2928
2929static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2930{
2931 int ret, clen;
2932
2933 s->zstream.avail_out = len;
2934 s->zstream.next_out = buf;
2935 while (s->zstream.avail_out > 0) {
2936 if (s->zstream.avail_in == 0) {
2937 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2938 return -1;
2939 clen = qemu_get_be16(s->f);
2940 if (clen > IOBUF_SIZE)
2941 return -1;
2942 qemu_get_buffer(s->f, s->buf, clen);
2943 s->zstream.avail_in = clen;
2944 s->zstream.next_in = s->buf;
2945 }
2946 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2947 if (ret != Z_OK && ret != Z_STREAM_END) {
2948 return -1;
2949 }
2950 }
2951 return 0;
2952}
2953
2954static void ram_decompress_close(RamDecompressState *s)
2955{
2956 inflateEnd(&s->zstream);
2957}
2958
475e4277
AL
2959#define RAM_SAVE_FLAG_FULL 0x01
2960#define RAM_SAVE_FLAG_COMPRESS 0x02
2961#define RAM_SAVE_FLAG_MEM_SIZE 0x04
2962#define RAM_SAVE_FLAG_PAGE 0x08
2963#define RAM_SAVE_FLAG_EOS 0x10
2964
2965static int is_dup_page(uint8_t *page, uint8_t ch)
8a7ddc38 2966{
475e4277
AL
2967 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2968 uint32_t *array = (uint32_t *)page;
2969 int i;
3b46e624 2970
475e4277
AL
2971 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2972 if (array[i] != val)
2973 return 0;
2974 }
2975
2976 return 1;
2977}
2978
2979static int ram_save_block(QEMUFile *f)
2980{
2981 static ram_addr_t current_addr = 0;
2982 ram_addr_t saved_addr = current_addr;
2983 ram_addr_t addr = 0;
2984 int found = 0;
2985
94a6b54f 2986 while (addr < last_ram_offset) {
475e4277 2987 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
5579c7f3 2988 uint8_t *p;
475e4277
AL
2989
2990 cpu_physical_memory_reset_dirty(current_addr,
2991 current_addr + TARGET_PAGE_SIZE,
2992 MIGRATION_DIRTY_FLAG);
2993
5579c7f3 2994 p = qemu_get_ram_ptr(current_addr);
475e4277 2995
5579c7f3 2996 if (is_dup_page(p, *p)) {
475e4277 2997 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
5579c7f3 2998 qemu_put_byte(f, *p);
475e4277
AL
2999 } else {
3000 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
5579c7f3 3001 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
c88676f8 3002 }
475e4277
AL
3003
3004 found = 1;
3005 break;
c88676f8 3006 }
475e4277 3007 addr += TARGET_PAGE_SIZE;
94a6b54f 3008 current_addr = (saved_addr + addr) % last_ram_offset;
8a7ddc38 3009 }
475e4277
AL
3010
3011 return found;
8a7ddc38
FB
3012}
3013
9f9e28cd 3014static uint64_t bytes_transferred = 0;
475e4277
AL
3015
3016static ram_addr_t ram_save_remaining(void)
3017{
3018 ram_addr_t addr;
3019 ram_addr_t count = 0;
3020
94a6b54f 3021 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
3022 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3023 count++;
3024 }
3025
3026 return count;
3027}
3028
9f9e28cd
GC
3029uint64_t ram_bytes_remaining(void)
3030{
3031 return ram_save_remaining() * TARGET_PAGE_SIZE;
3032}
3033
3034uint64_t ram_bytes_transferred(void)
3035{
3036 return bytes_transferred;
3037}
3038
3039uint64_t ram_bytes_total(void)
3040{
3041 return last_ram_offset;
3042}
3043
475e4277
AL
3044static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3045{
3046 ram_addr_t addr;
a0a3fd60
GC
3047 uint64_t bytes_transferred_last;
3048 double bwidth = 0;
3049 uint64_t expected_time = 0;
475e4277 3050
9fa06385 3051 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
b0a46a33
JK
3052 qemu_file_set_error(f);
3053 return 0;
3054 }
3055
475e4277
AL
3056 if (stage == 1) {
3057 /* Make sure all dirty bits are set */
94a6b54f 3058 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
3059 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3060 cpu_physical_memory_set_dirty(addr);
3061 }
b0a46a33 3062
475e4277
AL
3063 /* Enable dirty memory tracking */
3064 cpu_physical_memory_set_dirty_tracking(1);
3065
94a6b54f 3066 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
475e4277
AL
3067 }
3068
a0a3fd60
GC
3069 bytes_transferred_last = bytes_transferred;
3070 bwidth = get_clock();
3071
475e4277
AL
3072 while (!qemu_file_rate_limit(f)) {
3073 int ret;
3074
3075 ret = ram_save_block(f);
9f9e28cd 3076 bytes_transferred += ret * TARGET_PAGE_SIZE;
475e4277
AL
3077 if (ret == 0) /* no more blocks */
3078 break;
3079 }
3080
a0a3fd60
GC
3081 bwidth = get_clock() - bwidth;
3082 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3083
3084 /* if we haven't transferred anything this round, force expected_time to a
3085 * a very high value, but without crashing */
3086 if (bwidth == 0)
3087 bwidth = 0.000001;
3088
475e4277
AL
3089 /* try transferring iterative blocks of memory */
3090
3091 if (stage == 3) {
475e4277
AL
3092
3093 /* flush all remaining blocks regardless of rate limiting */
9f9e28cd
GC
3094 while (ram_save_block(f) != 0) {
3095 bytes_transferred += TARGET_PAGE_SIZE;
3096 }
8215e914 3097 cpu_physical_memory_set_dirty_tracking(0);
475e4277
AL
3098 }
3099
3100 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3101
a0a3fd60
GC
3102 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3103
3104 return (stage == 2) && (expected_time <= migrate_max_downtime());
475e4277
AL
3105}
3106
3107static int ram_load_dead(QEMUFile *f, void *opaque)
8a7ddc38 3108{
c88676f8
FB
3109 RamDecompressState s1, *s = &s1;
3110 uint8_t buf[10];
00f82b8a 3111 ram_addr_t i;
8a7ddc38 3112
c88676f8
FB
3113 if (ram_decompress_open(s, f) < 0)
3114 return -EINVAL;
94a6b54f 3115 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
c88676f8
FB
3116 if (ram_decompress_buf(s, buf, 1) < 0) {
3117 fprintf(stderr, "Error while reading ram block header\n");
3118 goto error;
3119 }
3120 if (buf[0] == 0) {
5579c7f3
PB
3121 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3122 BDRV_HASH_BLOCK_SIZE) < 0) {
00f82b8a 3123 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
c88676f8
FB
3124 goto error;
3125 }
475e4277 3126 } else {
c88676f8
FB
3127 error:
3128 printf("Error block header\n");
3129 return -EINVAL;
3130 }
8a7ddc38 3131 }
c88676f8 3132 ram_decompress_close(s);
475e4277
AL
3133
3134 return 0;
3135}
3136
3137static int ram_load(QEMUFile *f, void *opaque, int version_id)
3138{
3139 ram_addr_t addr;
3140 int flags;
3141
3142 if (version_id == 1)
3143 return ram_load_v1(f, opaque);
3144
3145 if (version_id == 2) {
94a6b54f 3146 if (qemu_get_be32(f) != last_ram_offset)
475e4277
AL
3147 return -EINVAL;
3148 return ram_load_dead(f, opaque);
3149 }
3150
3151 if (version_id != 3)
3152 return -EINVAL;
3153
3154 do {
3155 addr = qemu_get_be64(f);
3156
3157 flags = addr & ~TARGET_PAGE_MASK;
3158 addr &= TARGET_PAGE_MASK;
3159
3160 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
94a6b54f 3161 if (addr != last_ram_offset)
475e4277
AL
3162 return -EINVAL;
3163 }
3164
3165 if (flags & RAM_SAVE_FLAG_FULL) {
3166 if (ram_load_dead(f, opaque) < 0)
3167 return -EINVAL;
3168 }
3169
3170 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3171 uint8_t ch = qemu_get_byte(f);
779c6bef
AL
3172 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3173#ifndef _WIN32
30868442
AL
3174 if (ch == 0 &&
3175 (!kvm_enabled() || kvm_has_sync_mmu())) {
3176 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
779c6bef 3177 }
30868442 3178#endif
475e4277 3179 } else if (flags & RAM_SAVE_FLAG_PAGE)
5579c7f3 3180 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
475e4277
AL
3181 } while (!(flags & RAM_SAVE_FLAG_EOS));
3182
8a7ddc38
FB
3183 return 0;
3184}
3185
9e472e10
AL
3186void qemu_service_io(void)
3187{
d9f75a4e 3188 qemu_notify_event();
9e472e10
AL
3189}
3190
83f64091
FB
3191/***********************************************************/
3192/* bottom halves (can be seen as timers which expire ASAP) */
3193
3194struct QEMUBH {
3195 QEMUBHFunc *cb;
3196 void *opaque;
3197 int scheduled;
1b435b10
AL
3198 int idle;
3199 int deleted;
83f64091
FB
3200 QEMUBH *next;
3201};
3202
3203static QEMUBH *first_bh = NULL;
3204
3205QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3206{
3207 QEMUBH *bh;
3208 bh = qemu_mallocz(sizeof(QEMUBH));
83f64091
FB
3209 bh->cb = cb;
3210 bh->opaque = opaque;
1b435b10
AL
3211 bh->next = first_bh;
3212 first_bh = bh;
83f64091
FB
3213 return bh;
3214}
3215
6eb5733a 3216int qemu_bh_poll(void)
83f64091 3217{
1b435b10 3218 QEMUBH *bh, **bhp;
6eb5733a 3219 int ret;
83f64091 3220
6eb5733a 3221 ret = 0;
1b435b10
AL
3222 for (bh = first_bh; bh; bh = bh->next) {
3223 if (!bh->deleted && bh->scheduled) {
3224 bh->scheduled = 0;
3225 if (!bh->idle)
3226 ret = 1;
3227 bh->idle = 0;
3228 bh->cb(bh->opaque);
3229 }
83f64091 3230 }
1b435b10
AL
3231
3232 /* remove deleted bhs */
3233 bhp = &first_bh;
3234 while (*bhp) {
3235 bh = *bhp;
3236 if (bh->deleted) {
3237 *bhp = bh->next;
3238 qemu_free(bh);
3239 } else
3240 bhp = &bh->next;
3241 }
3242
6eb5733a 3243 return ret;
83f64091
FB
3244}
3245
1b435b10
AL
3246void qemu_bh_schedule_idle(QEMUBH *bh)
3247{
3248 if (bh->scheduled)
3249 return;
3250 bh->scheduled = 1;
3251 bh->idle = 1;
3252}
3253
83f64091
FB
3254void qemu_bh_schedule(QEMUBH *bh)
3255{
83f64091
FB
3256 if (bh->scheduled)
3257 return;
3258 bh->scheduled = 1;
1b435b10 3259 bh->idle = 0;
83f64091 3260 /* stop the currently executing CPU to execute the BH ASAP */
d9f75a4e 3261 qemu_notify_event();
83f64091
FB
3262}
3263
3264void qemu_bh_cancel(QEMUBH *bh)
3265{
1b435b10 3266 bh->scheduled = 0;
83f64091
FB
3267}
3268
3269void qemu_bh_delete(QEMUBH *bh)
3270{
1b435b10
AL
3271 bh->scheduled = 0;
3272 bh->deleted = 1;
83f64091
FB
3273}
3274
56f3a5d0
AL
3275static void qemu_bh_update_timeout(int *timeout)
3276{
3277 QEMUBH *bh;
3278
3279 for (bh = first_bh; bh; bh = bh->next) {
3280 if (!bh->deleted && bh->scheduled) {
3281 if (bh->idle) {
3282 /* idle bottom halves will be polled at least
3283 * every 10ms */
3284 *timeout = MIN(10, *timeout);
3285 } else {
3286 /* non-idle bottom halves will be executed
3287 * immediately */
3288 *timeout = 0;
3289 break;
3290 }
3291 }
3292 }
3293}
3294
cc1daa40
FB
3295/***********************************************************/
3296/* machine registration */
3297
bdaf78e0 3298static QEMUMachine *first_machine = NULL;
6f338c34 3299QEMUMachine *current_machine = NULL;
cc1daa40
FB
3300
3301int qemu_register_machine(QEMUMachine *m)
3302{
3303 QEMUMachine **pm;
3304 pm = &first_machine;
3305 while (*pm != NULL)
3306 pm = &(*pm)->next;
3307 m->next = NULL;
3308 *pm = m;
3309 return 0;
3310}
3311
9596ebb7 3312static QEMUMachine *find_machine(const char *name)
cc1daa40
FB
3313{
3314 QEMUMachine *m;
3315
3316 for(m = first_machine; m != NULL; m = m->next) {
3317 if (!strcmp(m->name, name))
3318 return m;
3f6599e6
MM
3319 if (m->alias && !strcmp(m->alias, name))
3320 return m;
cc1daa40
FB
3321 }
3322 return NULL;
3323}
3324
0c257437
AL
3325static QEMUMachine *find_default_machine(void)
3326{
3327 QEMUMachine *m;
3328
3329 for(m = first_machine; m != NULL; m = m->next) {
3330 if (m->is_default) {
3331 return m;
3332 }
3333 }
3334 return NULL;
3335}
3336
8a7ddc38
FB
3337/***********************************************************/
3338/* main execution loop */
3339
9596ebb7 3340static void gui_update(void *opaque)
8a7ddc38 3341{
7d957bd8 3342 uint64_t interval = GUI_REFRESH_INTERVAL;
740733bb 3343 DisplayState *ds = opaque;
7d957bd8
AL
3344 DisplayChangeListener *dcl = ds->listeners;
3345
3346 dpy_refresh(ds);
3347
3348 while (dcl != NULL) {
3349 if (dcl->gui_timer_interval &&
3350 dcl->gui_timer_interval < interval)
3351 interval = dcl->gui_timer_interval;
3352 dcl = dcl->next;
3353 }
3354 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
8a7ddc38
FB
3355}
3356
9043b62d
BS
3357static void nographic_update(void *opaque)
3358{
3359 uint64_t interval = GUI_REFRESH_INTERVAL;
3360
3361 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3362}
3363
0bd48850
FB
3364struct vm_change_state_entry {
3365 VMChangeStateHandler *cb;
3366 void *opaque;
3367 LIST_ENTRY (vm_change_state_entry) entries;
3368};
3369
3370static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3371
3372VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3373 void *opaque)
3374{
3375 VMChangeStateEntry *e;
3376
3377 e = qemu_mallocz(sizeof (*e));
0bd48850
FB
3378
3379 e->cb = cb;
3380 e->opaque = opaque;
3381 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3382 return e;
3383}
3384
3385void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3386{
3387 LIST_REMOVE (e, entries);
3388 qemu_free (e);
3389}
3390
9781e040 3391static void vm_state_notify(int running, int reason)
0bd48850
FB
3392{
3393 VMChangeStateEntry *e;
3394
3395 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
9781e040 3396 e->cb(e->opaque, running, reason);
0bd48850
FB
3397 }
3398}
3399
d6dc3d42
AL
3400static void resume_all_vcpus(void);
3401static void pause_all_vcpus(void);
3402
8a7ddc38
FB
3403void vm_start(void)
3404{
3405 if (!vm_running) {
3406 cpu_enable_ticks();
3407 vm_running = 1;
9781e040 3408 vm_state_notify(1, 0);
efe75411 3409 qemu_rearm_alarm_timer(alarm_timer);
d6dc3d42 3410 resume_all_vcpus();
8a7ddc38
FB
3411 }
3412}
3413
bb0c6722
FB
3414/* reset/shutdown handler */
3415
3416typedef struct QEMUResetEntry {
55ddfe8e 3417 TAILQ_ENTRY(QEMUResetEntry) entry;
bb0c6722
FB
3418 QEMUResetHandler *func;
3419 void *opaque;
bb0c6722
FB
3420} QEMUResetEntry;
3421
55ddfe8e
JK
3422static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3423 TAILQ_HEAD_INITIALIZER(reset_handlers);
bb0c6722
FB
3424static int reset_requested;
3425static int shutdown_requested;
3475187d 3426static int powerdown_requested;
e568902a 3427static int debug_requested;
6e29f5da 3428static int vmstop_requested;
bb0c6722 3429
cf7a2fe2
AJ
3430int qemu_shutdown_requested(void)
3431{
3432 int r = shutdown_requested;
3433 shutdown_requested = 0;
3434 return r;
3435}
3436
3437int qemu_reset_requested(void)
3438{
3439 int r = reset_requested;
3440 reset_requested = 0;
3441 return r;
3442}
3443
3444int qemu_powerdown_requested(void)
3445{
3446 int r = powerdown_requested;
3447 powerdown_requested = 0;
3448 return r;
3449}
3450
e568902a
AL
3451static int qemu_debug_requested(void)
3452{
3453 int r = debug_requested;
3454 debug_requested = 0;
3455 return r;
3456}
3457
6e29f5da
AL
3458static int qemu_vmstop_requested(void)
3459{
3460 int r = vmstop_requested;
3461 vmstop_requested = 0;
3462 return r;
3463}
3464
3465static void do_vm_stop(int reason)
3466{
3467 if (vm_running) {
3468 cpu_disable_ticks();
3469 vm_running = 0;
d6dc3d42 3470 pause_all_vcpus();
6e29f5da
AL
3471 vm_state_notify(0, reason);
3472 }
3473}
3474
a08d4367 3475void qemu_register_reset(QEMUResetHandler *func, void *opaque)
bb0c6722 3476{
55ddfe8e 3477 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
bb0c6722 3478
bb0c6722
FB
3479 re->func = func;
3480 re->opaque = opaque;
55ddfe8e 3481 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
bb0c6722
FB
3482}
3483
dda9b29f 3484void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
bb0c6722
FB
3485{
3486 QEMUResetEntry *re;
3487
55ddfe8e 3488 TAILQ_FOREACH(re, &reset_handlers, entry) {
dda9b29f
JK
3489 if (re->func == func && re->opaque == opaque) {
3490 TAILQ_REMOVE(&reset_handlers, re, entry);
3491 qemu_free(re);
3492 return;
3493 }
3494 }
3495}
3496
3497void qemu_system_reset(void)
3498{
3499 QEMUResetEntry *re, *nre;
3500
3501 /* reset all devices */
3502 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
bb0c6722
FB
3503 re->func(re->opaque);
3504 }
3505}
3506
3507void qemu_system_reset_request(void)
3508{
d1beab82
FB
3509 if (no_reboot) {
3510 shutdown_requested = 1;
3511 } else {
3512 reset_requested = 1;
3513 }
d9f75a4e 3514 qemu_notify_event();
bb0c6722
FB
3515}
3516
3517void qemu_system_shutdown_request(void)
3518{
3519 shutdown_requested = 1;
d9f75a4e 3520 qemu_notify_event();
bb0c6722
FB
3521}
3522
3475187d
FB
3523void qemu_system_powerdown_request(void)
3524{
3525 powerdown_requested = 1;
d9f75a4e
AL
3526 qemu_notify_event();
3527}
3528
d6dc3d42
AL
3529#ifdef CONFIG_IOTHREAD
3530static void qemu_system_vmstop_request(int reason)
d9f75a4e 3531{
d6dc3d42
AL
3532 vmstop_requested = reason;
3533 qemu_notify_event();
bb0c6722 3534}
d6dc3d42 3535#endif
bb0c6722 3536
50317c7f
AL
3537#ifndef _WIN32
3538static int io_thread_fd = -1;
3539
3540static void qemu_event_increment(void)
3fcf7b6b 3541{
50317c7f
AL
3542 static const char byte = 0;
3543
3544 if (io_thread_fd == -1)
3545 return;
3546
3547 write(io_thread_fd, &byte, sizeof(byte));
3548}
3549
3550static void qemu_event_read(void *opaque)
3551{
3552 int fd = (unsigned long)opaque;
3553 ssize_t len;
3554
3555 /* Drain the notify pipe */
3556 do {
3557 char buffer[512];
3558 len = read(fd, buffer, sizeof(buffer));
3559 } while ((len == -1 && errno == EINTR) || len > 0);
3560}
3561
3562static int qemu_event_init(void)
3563{
3564 int err;
3565 int fds[2];
3566
3567 err = pipe(fds);
3568 if (err == -1)
3569 return -errno;
3570
3571 err = fcntl_setfl(fds[0], O_NONBLOCK);
3572 if (err < 0)
3573 goto fail;
3574
3575 err = fcntl_setfl(fds[1], O_NONBLOCK);
3576 if (err < 0)
3577 goto fail;
3578
3579 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3580 (void *)(unsigned long)fds[0]);
3581
3582 io_thread_fd = fds[1];
a7e21219
JK
3583 return 0;
3584
50317c7f
AL
3585fail:
3586 close(fds[0]);
3587 close(fds[1]);
3588 return err;
3589}
3590#else
3591HANDLE qemu_event_handle;
3592
3593static void dummy_event_handler(void *opaque)
3594{
3595}
3596
3597static int qemu_event_init(void)
3598{
3599 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3600 if (!qemu_event_handle) {
3601 perror("Failed CreateEvent");
3602 return -1;
3603 }
3604 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3fcf7b6b
AL
3605 return 0;
3606}
3607
50317c7f
AL
3608static void qemu_event_increment(void)
3609{
3610 SetEvent(qemu_event_handle);
3611}
3612#endif
3613
d6dc3d42
AL
3614static int cpu_can_run(CPUState *env)
3615{
3616 if (env->stop)
3617 return 0;
3618 if (env->stopped)
3619 return 0;
3620 return 1;
3621}
3622
3623#ifndef CONFIG_IOTHREAD
50317c7f
AL
3624static int qemu_init_main_loop(void)
3625{
3626 return qemu_event_init();
3627}
3628
0bf46a40
AL
3629void qemu_init_vcpu(void *_env)
3630{
3631 CPUState *env = _env;
3632
3633 if (kvm_enabled())
3634 kvm_init_vcpu(env);
3635 return;
3636}
3637
8edac960
AL
3638int qemu_cpu_self(void *env)
3639{
3640 return 1;
3641}
3642
d6dc3d42
AL
3643static void resume_all_vcpus(void)
3644{
3645}
3646
3647static void pause_all_vcpus(void)
3648{
3649}
3650
8edac960
AL
3651void qemu_cpu_kick(void *env)
3652{
3653 return;
3654}
3655
d6dc3d42
AL
3656void qemu_notify_event(void)
3657{
3658 CPUState *env = cpu_single_env;
3659
3660 if (env) {
3661 cpu_exit(env);
3662#ifdef USE_KQEMU
3663 if (env->kqemu_enabled)
3664 kqemu_cpu_interrupt(env);
3665#endif
3666 }
3667}
3668
4870852c
AL
3669#define qemu_mutex_lock_iothread() do { } while (0)
3670#define qemu_mutex_unlock_iothread() do { } while (0)
3671
6e29f5da
AL
3672void vm_stop(int reason)
3673{
3674 do_vm_stop(reason);
3675}
3676
d6dc3d42
AL
3677#else /* CONFIG_IOTHREAD */
3678
3679#include "qemu-thread.h"
3680
3681QemuMutex qemu_global_mutex;
3682static QemuMutex qemu_fair_mutex;
3683
3684static QemuThread io_thread;
3685
3686static QemuThread *tcg_cpu_thread;
3687static QemuCond *tcg_halt_cond;
3688
3689static int qemu_system_ready;
3690/* cpu creation */
3691static QemuCond qemu_cpu_cond;
3692/* system init */
3693static QemuCond qemu_system_cond;
3694static QemuCond qemu_pause_cond;
3695
3696static void block_io_signals(void);
3697static void unblock_io_signals(void);
3698static int tcg_has_work(void);
3699
3700static int qemu_init_main_loop(void)
3701{
3702 int ret;
3703
3704 ret = qemu_event_init();
3705 if (ret)
3706 return ret;
3707
3708 qemu_cond_init(&qemu_pause_cond);
3709 qemu_mutex_init(&qemu_fair_mutex);
3710 qemu_mutex_init(&qemu_global_mutex);
3711 qemu_mutex_lock(&qemu_global_mutex);
3712
3713 unblock_io_signals();
3714 qemu_thread_self(&io_thread);
3715
3716 return 0;
3717}
3718
3719static void qemu_wait_io_event(CPUState *env)
3720{
3721 while (!tcg_has_work())
3722 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3723
3724 qemu_mutex_unlock(&qemu_global_mutex);
3725
3726 /*
3727 * Users of qemu_global_mutex can be starved, having no chance
3728 * to acquire it since this path will get to it first.
3729 * So use another lock to provide fairness.
3730 */
3731 qemu_mutex_lock(&qemu_fair_mutex);
3732 qemu_mutex_unlock(&qemu_fair_mutex);
3733
3734 qemu_mutex_lock(&qemu_global_mutex);
3735 if (env->stop) {
3736 env->stop = 0;
3737 env->stopped = 1;
3738 qemu_cond_signal(&qemu_pause_cond);
3739 }
3740}
3741
3742static int qemu_cpu_exec(CPUState *env);
3743
3744static void *kvm_cpu_thread_fn(void *arg)
3745{
3746 CPUState *env = arg;
3747
3748 block_io_signals();
3749 qemu_thread_self(env->thread);
3750
3751 /* signal CPU creation */
3752 qemu_mutex_lock(&qemu_global_mutex);
3753 env->created = 1;
3754 qemu_cond_signal(&qemu_cpu_cond);
3755
3756 /* and wait for machine initialization */
3757 while (!qemu_system_ready)
3758 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3759
3760 while (1) {
3761 if (cpu_can_run(env))
3762 qemu_cpu_exec(env);
3763 qemu_wait_io_event(env);
3764 }
3765
3766 return NULL;
3767}
3768
3769static void tcg_cpu_exec(void);
3770
3771static void *tcg_cpu_thread_fn(void *arg)
3772{
3773 CPUState *env = arg;
3774
3775 block_io_signals();
3776 qemu_thread_self(env->thread);
3777
3778 /* signal CPU creation */
3779 qemu_mutex_lock(&qemu_global_mutex);
3780 for (env = first_cpu; env != NULL; env = env->next_cpu)
3781 env->created = 1;
3782 qemu_cond_signal(&qemu_cpu_cond);
3783
3784 /* and wait for machine initialization */
3785 while (!qemu_system_ready)
3786 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3787
3788 while (1) {
3789 tcg_cpu_exec();
3790 qemu_wait_io_event(cur_cpu);
3791 }
3792
3793 return NULL;
3794}
3795
3796void qemu_cpu_kick(void *_env)
3797{
3798 CPUState *env = _env;
3799 qemu_cond_broadcast(env->halt_cond);
3800 if (kvm_enabled())
3801 qemu_thread_signal(env->thread, SIGUSR1);
3802}
3803
3804int qemu_cpu_self(void *env)
3805{
3806 return (cpu_single_env != NULL);
3807}
3808
3809static void cpu_signal(int sig)
3810{
3811 if (cpu_single_env)
3812 cpu_exit(cpu_single_env);
3813}
3814
3815static void block_io_signals(void)
3816{
3817 sigset_t set;
3818 struct sigaction sigact;
3819
3820 sigemptyset(&set);
3821 sigaddset(&set, SIGUSR2);
3822 sigaddset(&set, SIGIO);
3823 sigaddset(&set, SIGALRM);
3824 pthread_sigmask(SIG_BLOCK, &set, NULL);
3825
3826 sigemptyset(&set);
3827 sigaddset(&set, SIGUSR1);
3828 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3829
3830 memset(&sigact, 0, sizeof(sigact));
3831 sigact.sa_handler = cpu_signal;
3832 sigaction(SIGUSR1, &sigact, NULL);
3833}
3834
3835static void unblock_io_signals(void)
3836{
3837 sigset_t set;
3838
3839 sigemptyset(&set);
3840 sigaddset(&set, SIGUSR2);
3841 sigaddset(&set, SIGIO);
3842 sigaddset(&set, SIGALRM);
3843 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3844
3845 sigemptyset(&set);
3846 sigaddset(&set, SIGUSR1);
3847 pthread_sigmask(SIG_BLOCK, &set, NULL);
3848}
3849
3850static void qemu_signal_lock(unsigned int msecs)
3851{
3852 qemu_mutex_lock(&qemu_fair_mutex);
3853
3854 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3855 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3856 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3857 break;
3858 }
3859 qemu_mutex_unlock(&qemu_fair_mutex);
3860}
3861
3862static void qemu_mutex_lock_iothread(void)
3863{
3864 if (kvm_enabled()) {
3865 qemu_mutex_lock(&qemu_fair_mutex);
3866 qemu_mutex_lock(&qemu_global_mutex);
3867 qemu_mutex_unlock(&qemu_fair_mutex);
3868 } else
3869 qemu_signal_lock(100);
3870}
3871
3872static void qemu_mutex_unlock_iothread(void)
3873{
3874 qemu_mutex_unlock(&qemu_global_mutex);
3875}
3876
3877static int all_vcpus_paused(void)
3878{
3879 CPUState *penv = first_cpu;
3880
3881 while (penv) {
3882 if (!penv->stopped)
3883 return 0;
3884 penv = (CPUState *)penv->next_cpu;
3885 }
3886
3887 return 1;
3888}
3889
3890static void pause_all_vcpus(void)
3891{
3892 CPUState *penv = first_cpu;
3893
3894 while (penv) {
3895 penv->stop = 1;
3896 qemu_thread_signal(penv->thread, SIGUSR1);
3897 qemu_cpu_kick(penv);
3898 penv = (CPUState *)penv->next_cpu;
3899 }
3900
3901 while (!all_vcpus_paused()) {
3902 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3903 penv = first_cpu;
3904 while (penv) {
3905 qemu_thread_signal(penv->thread, SIGUSR1);
3906 penv = (CPUState *)penv->next_cpu;
3907 }
3908 }
3909}
3910
3911static void resume_all_vcpus(void)
3912{
3913 CPUState *penv = first_cpu;
3914
3915 while (penv) {
3916 penv->stop = 0;
3917 penv->stopped = 0;
3918 qemu_thread_signal(penv->thread, SIGUSR1);
3919 qemu_cpu_kick(penv);
3920 penv = (CPUState *)penv->next_cpu;
3921 }
3922}
3923
3924static void tcg_init_vcpu(void *_env)
3925{
3926 CPUState *env = _env;
3927 /* share a single thread for all cpus with TCG */
3928 if (!tcg_cpu_thread) {
3929 env->thread = qemu_mallocz(sizeof(QemuThread));
3930 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3931 qemu_cond_init(env->halt_cond);
3932 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3933 while (env->created == 0)
3934 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3935 tcg_cpu_thread = env->thread;
3936 tcg_halt_cond = env->halt_cond;
3937 } else {
3938 env->thread = tcg_cpu_thread;
3939 env->halt_cond = tcg_halt_cond;
3940 }
3941}
3942
3943static void kvm_start_vcpu(CPUState *env)
3944{
3945 kvm_init_vcpu(env);
3946 env->thread = qemu_mallocz(sizeof(QemuThread));
3947 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3948 qemu_cond_init(env->halt_cond);
3949 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3950 while (env->created == 0)
3951 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3952}
3953
3954void qemu_init_vcpu(void *_env)
3955{
3956 CPUState *env = _env;
3957
3958 if (kvm_enabled())
3959 kvm_start_vcpu(env);
3960 else
3961 tcg_init_vcpu(env);
3962}
3963
3964void qemu_notify_event(void)
3965{
3966 qemu_event_increment();
3967}
3968
3969void vm_stop(int reason)
3970{
3971 QemuThread me;
3972 qemu_thread_self(&me);
3973
3974 if (!qemu_thread_equal(&me, &io_thread)) {
3975 qemu_system_vmstop_request(reason);
3976 /*
3977 * FIXME: should not return to device code in case
3978 * vm_stop() has been requested.
3979 */
3980 if (cpu_single_env) {
3981 cpu_exit(cpu_single_env);
3982 cpu_single_env->stop = 1;
3983 }
3984 return;
3985 }
3986 do_vm_stop(reason);
3987}
3988
3989#endif
3990
3991
877cf882 3992#ifdef _WIN32
69d6451c 3993static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3994{
3995 int ret, ret2, i;
f331110f
FB
3996 PollingEntry *pe;
3997
c4b1fcc0 3998
f331110f
FB
3999 /* XXX: need to suppress polling by better using win32 events */
4000 ret = 0;
4001 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4002 ret |= pe->func(pe->opaque);
4003 }
e6b1e558 4004 if (ret == 0) {
a18e524a
FB
4005 int err;
4006 WaitObjects *w = &wait_objects;
3b46e624 4007
56f3a5d0 4008 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
a18e524a
FB
4009 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4010 if (w->func[ret - WAIT_OBJECT_0])
4011 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3b46e624 4012
5fafdf24 4013 /* Check for additional signaled events */
e6b1e558 4014 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3b46e624 4015
e6b1e558
TS
4016 /* Check if event is signaled */
4017 ret2 = WaitForSingleObject(w->events[i], 0);
4018 if(ret2 == WAIT_OBJECT_0) {
4019 if (w->func[i])
4020 w->func[i](w->opaque[i]);
4021 } else if (ret2 == WAIT_TIMEOUT) {
4022 } else {
4023 err = GetLastError();
4024 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3b46e624
TS
4025 }
4026 }
a18e524a
FB
4027 } else if (ret == WAIT_TIMEOUT) {
4028 } else {
4029 err = GetLastError();
e6b1e558 4030 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 4031 }
f331110f 4032 }
56f3a5d0
AL
4033
4034 *timeout = 0;
4035}
4036#else
69d6451c 4037static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
4038{
4039}
fd1dff4b 4040#endif
56f3a5d0
AL
4041
4042void main_loop_wait(int timeout)
4043{
4044 IOHandlerRecord *ioh;
4045 fd_set rfds, wfds, xfds;
4046 int ret, nfds;
4047 struct timeval tv;
4048
4049 qemu_bh_update_timeout(&timeout);
4050
4051 host_main_loop_wait(&timeout);
4052
fd1dff4b
FB
4053 /* poll any events */
4054 /* XXX: separate device handlers from system ones */
6abfbd79 4055 nfds = -1;
fd1dff4b
FB
4056 FD_ZERO(&rfds);
4057 FD_ZERO(&wfds);
e035649e 4058 FD_ZERO(&xfds);
fd1dff4b 4059 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
4060 if (ioh->deleted)
4061 continue;
fd1dff4b
FB
4062 if (ioh->fd_read &&
4063 (!ioh->fd_read_poll ||
4064 ioh->fd_read_poll(ioh->opaque) != 0)) {
4065 FD_SET(ioh->fd, &rfds);
4066 if (ioh->fd > nfds)
4067 nfds = ioh->fd;
4068 }
4069 if (ioh->fd_write) {
4070 FD_SET(ioh->fd, &wfds);
4071 if (ioh->fd > nfds)
4072 nfds = ioh->fd;
4073 }
4074 }
3b46e624 4075
56f3a5d0
AL
4076 tv.tv_sec = timeout / 1000;
4077 tv.tv_usec = (timeout % 1000) * 1000;
4078
d918f23e
JK
4079 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4080
4870852c 4081 qemu_mutex_unlock_iothread();
e035649e 4082 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4870852c 4083 qemu_mutex_lock_iothread();
fd1dff4b 4084 if (ret > 0) {
cafffd40
TS
4085 IOHandlerRecord **pioh;
4086
4087 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6ab43fdc 4088 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
fd1dff4b 4089 ioh->fd_read(ioh->opaque);
7c9d8e07 4090 }
6ab43fdc 4091 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
fd1dff4b 4092 ioh->fd_write(ioh->opaque);
c4b1fcc0 4093 }
b4608c04 4094 }
cafffd40
TS
4095
4096 /* remove deleted IO handlers */
4097 pioh = &first_io_handler;
4098 while (*pioh) {
4099 ioh = *pioh;
4100 if (ioh->deleted) {
4101 *pioh = ioh->next;
4102 qemu_free(ioh);
5fafdf24 4103 } else
cafffd40
TS
4104 pioh = &ioh->next;
4105 }
fd1dff4b 4106 }
d918f23e
JK
4107
4108 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
b4608c04 4109
50317c7f
AL
4110 /* rearm timer, if not periodic */
4111 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4112 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4113 qemu_rearm_alarm_timer(alarm_timer);
4114 }
4115
357c692c 4116 /* vm time timers */
d6dc3d42
AL
4117 if (vm_running) {
4118 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4119 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4120 qemu_get_clock(vm_clock));
4121 }
357c692c
AL
4122
4123 /* real time timers */
4124 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4125 qemu_get_clock(rt_clock));
4126
423f0742
PB
4127 /* Check bottom-halves last in case any of the earlier events triggered
4128 them. */
4129 qemu_bh_poll();
3b46e624 4130
5905b2e5
FB
4131}
4132
43b96858 4133static int qemu_cpu_exec(CPUState *env)
5905b2e5 4134{
43b96858 4135 int ret;
89bfc105
FB
4136#ifdef CONFIG_PROFILER
4137 int64_t ti;
4138#endif
5905b2e5 4139
89bfc105 4140#ifdef CONFIG_PROFILER
43b96858 4141 ti = profile_getclock();
89bfc105 4142#endif
43b96858
AL
4143 if (use_icount) {
4144 int64_t count;
4145 int decr;
4146 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4147 env->icount_decr.u16.low = 0;
4148 env->icount_extra = 0;
4149 count = qemu_next_deadline();
4150 count = (count + (1 << icount_time_shift) - 1)
4151 >> icount_time_shift;
4152 qemu_icount += count;
4153 decr = (count > 0xffff) ? 0xffff : count;
4154 count -= decr;
4155 env->icount_decr.u16.low = decr;
4156 env->icount_extra = count;
4157 }
4158 ret = cpu_exec(env);
89bfc105 4159#ifdef CONFIG_PROFILER
43b96858 4160 qemu_time += profile_getclock() - ti;
89bfc105 4161#endif
43b96858
AL
4162 if (use_icount) {
4163 /* Fold pending instructions back into the
4164 instruction counter, and clear the interrupt flag. */
4165 qemu_icount -= (env->icount_decr.u16.low
4166 + env->icount_extra);
4167 env->icount_decr.u32 = 0;
4168 env->icount_extra = 0;
4169 }
4170 return ret;
4171}
4172
e6e35b1e
AL
4173static void tcg_cpu_exec(void)
4174{
d6dc3d42 4175 int ret = 0;
e6e35b1e
AL
4176
4177 if (next_cpu == NULL)
4178 next_cpu = first_cpu;
4179 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4180 CPUState *env = cur_cpu = next_cpu;
4181
4182 if (!vm_running)
4183 break;
4184 if (timer_alarm_pending) {
4185 timer_alarm_pending = 0;
4186 break;
4187 }
d6dc3d42
AL
4188 if (cpu_can_run(env))
4189 ret = qemu_cpu_exec(env);
e6e35b1e
AL
4190 if (ret == EXCP_DEBUG) {
4191 gdb_set_stop_cpu(env);
4192 debug_requested = 1;
4193 break;
4194 }
4195 }
4196}
4197
43b96858
AL
4198static int cpu_has_work(CPUState *env)
4199{
d6dc3d42
AL
4200 if (env->stop)
4201 return 1;
4202 if (env->stopped)
4203 return 0;
43b96858
AL
4204 if (!env->halted)
4205 return 1;
4206 if (qemu_cpu_has_work(env))
4207 return 1;
4208 return 0;
4209}
4210
4211static int tcg_has_work(void)
4212{
4213 CPUState *env;
4214
4215 for (env = first_cpu; env != NULL; env = env->next_cpu)
4216 if (cpu_has_work(env))
4217 return 1;
4218 return 0;
4219}
4220
4221static int qemu_calculate_timeout(void)
4222{
b319820d 4223#ifndef CONFIG_IOTHREAD
43b96858
AL
4224 int timeout;
4225
4226 if (!vm_running)
4227 timeout = 5000;
4228 else if (tcg_has_work())
4229 timeout = 0;
4230 else if (!use_icount)
4231 timeout = 5000;
4232 else {
4233 /* XXX: use timeout computed from timers */
4234 int64_t add;
4235 int64_t delta;
4236 /* Advance virtual time to the next event. */
4237 if (use_icount == 1) {
4238 /* When not using an adaptive execution frequency
4239 we tend to get badly out of sync with real time,
4240 so just delay for a reasonable amount of time. */
4241 delta = 0;
4242 } else {
4243 delta = cpu_get_icount() - cpu_get_clock();
4244 }
4245 if (delta > 0) {
4246 /* If virtual time is ahead of real time then just
4247 wait for IO. */
4248 timeout = (delta / 1000000) + 1;
4249 } else {
4250 /* Wait for either IO to occur or the next
4251 timer event. */
4252 add = qemu_next_deadline();
4253 /* We advance the timer before checking for IO.
4254 Limit the amount we advance so that early IO
4255 activity won't get the guest too far ahead. */
4256 if (add > 10000000)
4257 add = 10000000;
4258 delta += add;
4259 add = (add + (1 << icount_time_shift) - 1)
4260 >> icount_time_shift;
4261 qemu_icount += add;
4262 timeout = delta / 1000000;
4263 if (timeout < 0)
4264 timeout = 0;
4265 }
4266 }
4267
4268 return timeout;
b319820d
LC
4269#else /* CONFIG_IOTHREAD */
4270 return 1000;
4271#endif
43b96858
AL
4272}
4273
4274static int vm_can_run(void)
4275{
4276 if (powerdown_requested)
4277 return 0;
4278 if (reset_requested)
4279 return 0;
4280 if (shutdown_requested)
4281 return 0;
e568902a
AL
4282 if (debug_requested)
4283 return 0;
43b96858
AL
4284 return 1;
4285}
4286
4287static void main_loop(void)
4288{
6e29f5da 4289 int r;
e6e35b1e 4290
d6dc3d42
AL
4291#ifdef CONFIG_IOTHREAD
4292 qemu_system_ready = 1;
4293 qemu_cond_broadcast(&qemu_system_cond);
4294#endif
4295
6e29f5da 4296 for (;;) {
43b96858 4297 do {
e6e35b1e
AL
4298#ifdef CONFIG_PROFILER
4299 int64_t ti;
4300#endif
d6dc3d42 4301#ifndef CONFIG_IOTHREAD
e6e35b1e 4302 tcg_cpu_exec();
d6dc3d42 4303#endif
89bfc105 4304#ifdef CONFIG_PROFILER
43b96858 4305 ti = profile_getclock();
89bfc105 4306#endif
43b96858 4307 main_loop_wait(qemu_calculate_timeout());
89bfc105 4308#ifdef CONFIG_PROFILER
43b96858 4309 dev_time += profile_getclock() - ti;
89bfc105 4310#endif
e568902a 4311 } while (vm_can_run());
43b96858 4312
e568902a
AL
4313 if (qemu_debug_requested())
4314 vm_stop(EXCP_DEBUG);
43b96858
AL
4315 if (qemu_shutdown_requested()) {
4316 if (no_shutdown) {
4317 vm_stop(0);
4318 no_shutdown = 0;
4319 } else
4320 break;
4321 }
d6dc3d42
AL
4322 if (qemu_reset_requested()) {
4323 pause_all_vcpus();
43b96858 4324 qemu_system_reset();
d6dc3d42
AL
4325 resume_all_vcpus();
4326 }
43b96858
AL
4327 if (qemu_powerdown_requested())
4328 qemu_system_powerdown();
6e29f5da
AL
4329 if ((r = qemu_vmstop_requested()))
4330 vm_stop(r);
b4608c04 4331 }
d6dc3d42 4332 pause_all_vcpus();
b4608c04
FB
4333}
4334
9bd7e6d9
PB
4335static void version(void)
4336{
4a19f1ec 4337 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
9bd7e6d9
PB
4338}
4339
15f82208 4340static void help(int exitcode)
0824d6fc 4341{
9bd7e6d9
PB
4342 version();
4343 printf("usage: %s [options] [disk_image]\n"
0824d6fc 4344 "\n"
a20dd508 4345 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 4346 "\n"
5824d651
BS
4347#define DEF(option, opt_arg, opt_enum, opt_help) \
4348 opt_help
4349#define DEFHEADING(text) stringify(text) "\n"
4350#include "qemu-options.h"
4351#undef DEF
4352#undef DEFHEADING
4353#undef GEN_DOCS
0824d6fc 4354 "\n"
82c643ff 4355 "During emulation, the following keys are useful:\n"
032a8c9e
FB
4356 "ctrl-alt-f toggle full screen\n"
4357 "ctrl-alt-n switch to virtual console 'n'\n"
4358 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
4359 "\n"
4360 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4361 ,
0db63474 4362 "qemu",
a00bad7e 4363 DEFAULT_RAM_SIZE,
7c9d8e07 4364#ifndef _WIN32
a00bad7e 4365 DEFAULT_NETWORK_SCRIPT,
b46a8906 4366 DEFAULT_NETWORK_DOWN_SCRIPT,
7c9d8e07 4367#endif
6e44ba7f 4368 DEFAULT_GDBSTUB_PORT,
bce61846 4369 "/tmp/qemu.log");
15f82208 4370 exit(exitcode);
0824d6fc
FB
4371}
4372
cd6f1169
FB
4373#define HAS_ARG 0x0001
4374
4375enum {
5824d651
BS
4376#define DEF(option, opt_arg, opt_enum, opt_help) \
4377 opt_enum,
4378#define DEFHEADING(text)
4379#include "qemu-options.h"
4380#undef DEF
4381#undef DEFHEADING
4382#undef GEN_DOCS
cd6f1169
FB
4383};
4384
4385typedef struct QEMUOption {
4386 const char *name;
4387 int flags;
4388 int index;
4389} QEMUOption;
4390
dbed7e40 4391static const QEMUOption qemu_options[] = {
cd6f1169 4392 { "h", 0, QEMU_OPTION_h },
5824d651
BS
4393#define DEF(option, opt_arg, opt_enum, opt_help) \
4394 { option, opt_arg, opt_enum },
4395#define DEFHEADING(text)
4396#include "qemu-options.h"
4397#undef DEF
4398#undef DEFHEADING
4399#undef GEN_DOCS
cd6f1169 4400 { NULL },
fc01f7e7
FB
4401};
4402
1d14ffa9 4403#ifdef HAS_AUDIO
6a36d84e 4404struct soundhw soundhw[] = {
b00052e4 4405#ifdef HAS_AUDIO_CHOICE
4ce7ff6e 4406#if defined(TARGET_I386) || defined(TARGET_MIPS)
fd06c375
FB
4407 {
4408 "pcspk",
4409 "PC speaker",
4410 0,
4411 1,
4412 { .init_isa = pcspk_audio_init }
4413 },
4414#endif
4c9b53e3 4415
4416#ifdef CONFIG_SB16
6a36d84e
FB
4417 {
4418 "sb16",
4419 "Creative Sound Blaster 16",
4420 0,
4421 1,
4422 { .init_isa = SB16_init }
4423 },
4c9b53e3 4424#endif
6a36d84e 4425
cc53d26d 4426#ifdef CONFIG_CS4231A
4427 {
4428 "cs4231a",
4429 "CS4231A",
4430 0,
4431 1,
4432 { .init_isa = cs4231a_init }
4433 },
4434#endif
4435
1d14ffa9 4436#ifdef CONFIG_ADLIB
6a36d84e
FB
4437 {
4438 "adlib",
1d14ffa9 4439#ifdef HAS_YMF262
6a36d84e 4440 "Yamaha YMF262 (OPL3)",
1d14ffa9 4441#else
6a36d84e 4442 "Yamaha YM3812 (OPL2)",
1d14ffa9 4443#endif
6a36d84e
FB
4444 0,
4445 1,
4446 { .init_isa = Adlib_init }
4447 },
1d14ffa9 4448#endif
6a36d84e 4449
1d14ffa9 4450#ifdef CONFIG_GUS
6a36d84e
FB
4451 {
4452 "gus",
4453 "Gravis Ultrasound GF1",
4454 0,
4455 1,
4456 { .init_isa = GUS_init }
4457 },
1d14ffa9 4458#endif
6a36d84e 4459
4c9b53e3 4460#ifdef CONFIG_AC97
e5c9a13e
AZ
4461 {
4462 "ac97",
4463 "Intel 82801AA AC97 Audio",
4464 0,
4465 0,
4466 { .init_pci = ac97_init }
4467 },
4c9b53e3 4468#endif
e5c9a13e 4469
4c9b53e3 4470#ifdef CONFIG_ES1370
6a36d84e
FB
4471 {
4472 "es1370",
4473 "ENSONIQ AudioPCI ES1370",
4474 0,
4475 0,
4476 { .init_pci = es1370_init }
4477 },
b00052e4 4478#endif
6a36d84e 4479
4c9b53e3 4480#endif /* HAS_AUDIO_CHOICE */
4481
6a36d84e
FB
4482 { NULL, NULL, 0, 0, { NULL } }
4483};
4484
4485static void select_soundhw (const char *optarg)
4486{
4487 struct soundhw *c;
4488
4489 if (*optarg == '?') {
4490 show_valid_cards:
4491
4492 printf ("Valid sound card names (comma separated):\n");
4493 for (c = soundhw; c->name; ++c) {
4494 printf ("%-11s %s\n", c->name, c->descr);
4495 }
4496 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
4497 exit (*optarg != '?');
4498 }
4499 else {
6a36d84e 4500 size_t l;
1d14ffa9
FB
4501 const char *p;
4502 char *e;
4503 int bad_card = 0;
4504
6a36d84e
FB
4505 if (!strcmp (optarg, "all")) {
4506 for (c = soundhw; c->name; ++c) {
4507 c->enabled = 1;
4508 }
4509 return;
4510 }
1d14ffa9 4511
6a36d84e 4512 p = optarg;
1d14ffa9
FB
4513 while (*p) {
4514 e = strchr (p, ',');
4515 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
4516
4517 for (c = soundhw; c->name; ++c) {
4518 if (!strncmp (c->name, p, l)) {
4519 c->enabled = 1;
1d14ffa9
FB
4520 break;
4521 }
4522 }
6a36d84e
FB
4523
4524 if (!c->name) {
1d14ffa9
FB
4525 if (l > 80) {
4526 fprintf (stderr,
4527 "Unknown sound card name (too big to show)\n");
4528 }
4529 else {
4530 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4531 (int) l, p);
4532 }
4533 bad_card = 1;
4534 }
4535 p += l + (e != NULL);
4536 }
4537
4538 if (bad_card)
4539 goto show_valid_cards;
4540 }
4541}
4542#endif
4543
3893c124 4544static void select_vgahw (const char *p)
4545{
4546 const char *opts;
4547
28b85ed8
AL
4548 cirrus_vga_enabled = 0;
4549 std_vga_enabled = 0;
4550 vmsvga_enabled = 0;
94909d9f 4551 xenfb_enabled = 0;
3893c124 4552 if (strstart(p, "std", &opts)) {
c2b3b41a 4553 std_vga_enabled = 1;
3893c124 4554 } else if (strstart(p, "cirrus", &opts)) {
4555 cirrus_vga_enabled = 1;
3893c124 4556 } else if (strstart(p, "vmware", &opts)) {
3893c124 4557 vmsvga_enabled = 1;
94909d9f
AL
4558 } else if (strstart(p, "xenfb", &opts)) {
4559 xenfb_enabled = 1;
28b85ed8 4560 } else if (!strstart(p, "none", &opts)) {
3893c124 4561 invalid_vga:
4562 fprintf(stderr, "Unknown vga type: %s\n", p);
4563 exit(1);
4564 }
cb5a7aa8 4565 while (*opts) {
4566 const char *nextopt;
4567
4568 if (strstart(opts, ",retrace=", &nextopt)) {
4569 opts = nextopt;
4570 if (strstart(opts, "dumb", &nextopt))
4571 vga_retrace_method = VGA_RETRACE_DUMB;
4572 else if (strstart(opts, "precise", &nextopt))
4573 vga_retrace_method = VGA_RETRACE_PRECISE;
4574 else goto invalid_vga;
4575 } else goto invalid_vga;
4576 opts = nextopt;
4577 }
3893c124 4578}
4579
7d4c3d53
MA
4580#ifdef TARGET_I386
4581static int balloon_parse(const char *arg)
4582{
4583 char buf[128];
4584 const char *p;
4585
4586 if (!strcmp(arg, "none")) {
4587 virtio_balloon = 0;
4588 } else if (!strncmp(arg, "virtio", 6)) {
4589 virtio_balloon = 1;
4590 if (arg[6] == ',') {
4591 p = arg + 7;
4592 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4593 virtio_balloon_devaddr = strdup(buf);
4594 }
4595 }
4596 } else {
4597 return -1;
4598 }
4599 return 0;
4600}
4601#endif
4602
3587d7e6
FB
4603#ifdef _WIN32
4604static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4605{
4606 exit(STATUS_CONTROL_C_EXIT);
4607 return TRUE;
4608}
4609#endif
4610
c4be29ff 4611int qemu_uuid_parse(const char *str, uint8_t *uuid)
8fcb1b90
BS
4612{
4613 int ret;
4614
4615 if(strlen(str) != 36)
4616 return -1;
4617
4618 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4619 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4620 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4621
4622 if(ret != 16)
4623 return -1;
4624
b6f6e3d3
AL
4625#ifdef TARGET_I386
4626 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4627#endif
4628
8fcb1b90
BS
4629 return 0;
4630}
4631
7c9d8e07 4632#define MAX_NET_CLIENTS 32
c20709aa 4633
5b08fc10
AL
4634#ifndef _WIN32
4635
4636static void termsig_handler(int signal)
4637{
4638 qemu_system_shutdown_request();
4639}
4640
7c3370d4
JK
4641static void sigchld_handler(int signal)
4642{
4643 waitpid(-1, NULL, WNOHANG);
4644}
4645
4646static void sighandler_setup(void)
5b08fc10
AL
4647{
4648 struct sigaction act;
4649
4650 memset(&act, 0, sizeof(act));
4651 act.sa_handler = termsig_handler;
4652 sigaction(SIGINT, &act, NULL);
4653 sigaction(SIGHUP, &act, NULL);
4654 sigaction(SIGTERM, &act, NULL);
7c3370d4
JK
4655
4656 act.sa_handler = sigchld_handler;
4657 act.sa_flags = SA_NOCLDSTOP;
4658 sigaction(SIGCHLD, &act, NULL);
5b08fc10
AL
4659}
4660
4661#endif
4662
5cea8590
PB
4663#ifdef _WIN32
4664/* Look for support files in the same directory as the executable. */
4665static char *find_datadir(const char *argv0)
4666{
4667 char *p;
4668 char buf[MAX_PATH];
4669 DWORD len;
4670
4671 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4672 if (len == 0) {
c5947808 4673 return NULL;
5cea8590
PB
4674 }
4675
4676 buf[len] = 0;
4677 p = buf + len - 1;
4678 while (p != buf && *p != '\\')
4679 p--;
4680 *p = 0;
4681 if (access(buf, R_OK) == 0) {
4682 return qemu_strdup(buf);
4683 }
4684 return NULL;
4685}
4686#else /* !_WIN32 */
4687
4688/* Find a likely location for support files using the location of the binary.
4689 For installed binaries this will be "$bindir/../share/qemu". When
4690 running from the build tree this will be "$bindir/../pc-bios". */
4691#define SHARE_SUFFIX "/share/qemu"
4692#define BUILD_SUFFIX "/pc-bios"
4693static char *find_datadir(const char *argv0)
4694{
4695 char *dir;
4696 char *p = NULL;
4697 char *res;
4698#ifdef PATH_MAX
4699 char buf[PATH_MAX];
4700#endif
3a41759d 4701 size_t max_len;
5cea8590
PB
4702
4703#if defined(__linux__)
4704 {
4705 int len;
4706 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4707 if (len > 0) {
4708 buf[len] = 0;
4709 p = buf;
4710 }
4711 }
4712#elif defined(__FreeBSD__)
4713 {
4714 int len;
4715 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4716 if (len > 0) {
4717 buf[len] = 0;
4718 p = buf;
4719 }
4720 }
4721#endif
4722 /* If we don't have any way of figuring out the actual executable
4723 location then try argv[0]. */
4724 if (!p) {
4725#ifdef PATH_MAX
4726 p = buf;
4727#endif
4728 p = realpath(argv0, p);
4729 if (!p) {
4730 return NULL;
4731 }
4732 }
4733 dir = dirname(p);
4734 dir = dirname(dir);
4735
3a41759d
BS
4736 max_len = strlen(dir) +
4737 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4738 res = qemu_mallocz(max_len);
4739 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5cea8590 4740 if (access(res, R_OK)) {
3a41759d 4741 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5cea8590
PB
4742 if (access(res, R_OK)) {
4743 qemu_free(res);
4744 res = NULL;
4745 }
4746 }
4747#ifndef PATH_MAX
4748 free(p);
4749#endif
4750 return res;
4751}
4752#undef SHARE_SUFFIX
4753#undef BUILD_SUFFIX
4754#endif
4755
4756char *qemu_find_file(int type, const char *name)
4757{
4758 int len;
4759 const char *subdir;
4760 char *buf;
4761
4762 /* If name contains path separators then try it as a straight path. */
4763 if ((strchr(name, '/') || strchr(name, '\\'))
4764 && access(name, R_OK) == 0) {
4765 return strdup(name);
4766 }
4767 switch (type) {
4768 case QEMU_FILE_TYPE_BIOS:
4769 subdir = "";
4770 break;
4771 case QEMU_FILE_TYPE_KEYMAP:
4772 subdir = "keymaps/";
4773 break;
4774 default:
4775 abort();
4776 }
4777 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4778 buf = qemu_mallocz(len);
3a41759d 4779 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5cea8590
PB
4780 if (access(buf, R_OK)) {
4781 qemu_free(buf);
4782 return NULL;
4783 }
4784 return buf;
4785}
4786
bd3c948d
GH
4787struct device_config {
4788 enum {
4789 DEV_GENERIC, /* -device */
4790 DEV_USB, /* -usbdevice */
4791 DEV_BT, /* -bt */
4792 } type;
4793 const char *cmdline;
4794 TAILQ_ENTRY(device_config) next;
4795};
4796TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4797
4798static void add_device_config(int type, const char *cmdline)
4799{
4800 struct device_config *conf;
4801
4802 conf = qemu_mallocz(sizeof(*conf));
4803 conf->type = type;
4804 conf->cmdline = cmdline;
4805 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4806}
4807
4808static int foreach_device_config(int type, int (*func)(const char *cmdline))
4809{
4810 struct device_config *conf;
4811 int rc;
4812
4813 TAILQ_FOREACH(conf, &device_configs, next) {
4814 if (conf->type != type)
4815 continue;
4816 rc = func(conf->cmdline);
4817 if (0 != rc)
4818 return rc;
4819 }
4820 return 0;
4821}
4822
4823static int generic_parse(const char *cmdline)
4824{
4825 DeviceState *dev;
4826
4827 dev = qdev_device_add(cmdline);
4828 if (!dev)
4829 return -1;
4830 return 0;
4831}
4832
902b3d5c 4833int main(int argc, char **argv, char **envp)
0824d6fc 4834{
59030a8c 4835 const char *gdbstub_dev = NULL;
28c5af54 4836 uint32_t boot_devices_bitmap = 0;
e4bcb14c 4837 int i;
28c5af54 4838 int snapshot, linux_boot, net_boot;
7f7f9873 4839 const char *initrd_filename;
a20dd508 4840 const char *kernel_filename, *kernel_cmdline;
ef3adf68 4841 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3023f332 4842 DisplayState *ds;
7d957bd8 4843 DisplayChangeListener *dcl;
46d4767d 4844 int cyls, heads, secs, translation;
fd5f393a 4845 const char *net_clients[MAX_NET_CLIENTS];
7c9d8e07 4846 int nb_net_clients;
9dfd7c7a 4847 QemuOpts *hda_opts = NULL;
cd6f1169
FB
4848 int optind;
4849 const char *r, *optarg;
4c621805 4850 CharDriverState *monitor_hd = NULL;
fd5f393a
PB
4851 const char *monitor_device;
4852 const char *serial_devices[MAX_SERIAL_PORTS];
8d11df9e 4853 int serial_device_index;
fd5f393a 4854 const char *parallel_devices[MAX_PARALLEL_PORTS];
6508fe59 4855 int parallel_device_index;
9ede2fde
AL
4856 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4857 int virtio_console_index;
d63d307f 4858 const char *loadvm = NULL;
cc1daa40 4859 QEMUMachine *machine;
94fc95cd 4860 const char *cpu_model;
b9e82a59 4861#ifndef _WIN32
71e3ceb8 4862 int fds[2];
b9e82a59 4863#endif
26a5f13b 4864 int tb_size;
93815bc2 4865 const char *pid_file = NULL;
5bb7910a 4866 const char *incoming = NULL;
b9e82a59 4867#ifndef _WIN32
54042bcf
AL
4868 int fd = 0;
4869 struct passwd *pwd = NULL;
0858532e
AL
4870 const char *chroot_dir = NULL;
4871 const char *run_as = NULL;
b9e82a59 4872#endif
268a362c 4873 CPUState *env;
993fbfdb 4874 int show_vnc_port = 0;
0bd48850 4875
902b3d5c 4876 qemu_cache_utils_init(envp);
4877
0bd48850 4878 LIST_INIT (&vm_change_state_head);
be995c27
FB
4879#ifndef _WIN32
4880 {
4881 struct sigaction act;
4882 sigfillset(&act.sa_mask);
4883 act.sa_flags = 0;
4884 act.sa_handler = SIG_IGN;
4885 sigaction(SIGPIPE, &act, NULL);
4886 }
3587d7e6
FB
4887#else
4888 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
4889 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4890 QEMU to run on a single CPU */
4891 {
4892 HANDLE h;
4893 DWORD mask, smask;
4894 int i;
4895 h = GetCurrentProcess();
4896 if (GetProcessAffinityMask(h, &mask, &smask)) {
4897 for(i = 0; i < 32; i++) {
4898 if (mask & (1 << i))
4899 break;
4900 }
4901 if (i != 32) {
4902 mask = 1 << i;
4903 SetProcessAffinityMask(h, mask);
4904 }
4905 }
4906 }
67b915a5 4907#endif
be995c27 4908
f80f9ec9 4909 module_call_init(MODULE_INIT_MACHINE);
0c257437 4910 machine = find_default_machine();
94fc95cd 4911 cpu_model = NULL;
fc01f7e7 4912 initrd_filename = NULL;
4fc5d071 4913 ram_size = 0;
33e3963e 4914 snapshot = 0;
a20dd508
FB
4915 kernel_filename = NULL;
4916 kernel_cmdline = "";
c4b1fcc0 4917 cyls = heads = secs = 0;
46d4767d 4918 translation = BIOS_ATA_TRANSLATION_AUTO;
d47d13b9 4919 monitor_device = "vc:80Cx24C";
c4b1fcc0 4920
c75a823c 4921 serial_devices[0] = "vc:80Cx24C";
8d11df9e 4922 for(i = 1; i < MAX_SERIAL_PORTS; i++)
fd5f393a 4923 serial_devices[i] = NULL;
8d11df9e 4924 serial_device_index = 0;
3b46e624 4925
8290edda 4926 parallel_devices[0] = "vc:80Cx24C";
6508fe59 4927 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
fd5f393a 4928 parallel_devices[i] = NULL;
6508fe59 4929 parallel_device_index = 0;
3b46e624 4930
1b8fc811 4931 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
9ede2fde
AL
4932 virtio_consoles[i] = NULL;
4933 virtio_console_index = 0;
4934
268a362c
AL
4935 for (i = 0; i < MAX_NODES; i++) {
4936 node_mem[i] = 0;
4937 node_cpumask[i] = 0;
4938 }
4939
7c9d8e07 4940 nb_net_clients = 0;
268a362c 4941 nb_numa_nodes = 0;
7c9d8e07 4942 nb_nics = 0;
3b46e624 4943
26a5f13b 4944 tb_size = 0;
41bd639b
BS
4945 autostart= 1;
4946
9dd986cc
RJ
4947 register_watchdogs();
4948
cd6f1169 4949 optind = 1;
0824d6fc 4950 for(;;) {
cd6f1169 4951 if (optind >= argc)
0824d6fc 4952 break;
cd6f1169
FB
4953 r = argv[optind];
4954 if (r[0] != '-') {
9dfd7c7a 4955 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
cd6f1169
FB
4956 } else {
4957 const QEMUOption *popt;
4958
4959 optind++;
dff5efc8
PB
4960 /* Treat --foo the same as -foo. */
4961 if (r[1] == '-')
4962 r++;
cd6f1169
FB
4963 popt = qemu_options;
4964 for(;;) {
4965 if (!popt->name) {
5fafdf24 4966 fprintf(stderr, "%s: invalid option -- '%s'\n",
cd6f1169
FB
4967 argv[0], r);
4968 exit(1);
4969 }
4970 if (!strcmp(popt->name, r + 1))
4971 break;
4972 popt++;
4973 }
4974 if (popt->flags & HAS_ARG) {
4975 if (optind >= argc) {
4976 fprintf(stderr, "%s: option '%s' requires an argument\n",
4977 argv[0], r);
4978 exit(1);
4979 }
4980 optarg = argv[optind++];
4981 } else {
4982 optarg = NULL;
4983 }
4984
4985 switch(popt->index) {
cc1daa40
FB
4986 case QEMU_OPTION_M:
4987 machine = find_machine(optarg);
4988 if (!machine) {
4989 QEMUMachine *m;
4990 printf("Supported machines are:\n");
4991 for(m = first_machine; m != NULL; m = m->next) {
3f6599e6
MM
4992 if (m->alias)
4993 printf("%-10s %s (alias of %s)\n",
4994 m->alias, m->desc, m->name);
cc1daa40 4995 printf("%-10s %s%s\n",
5fafdf24 4996 m->name, m->desc,
0c257437 4997 m->is_default ? " (default)" : "");
cc1daa40 4998 }
15f82208 4999 exit(*optarg != '?');
cc1daa40
FB
5000 }
5001 break;
94fc95cd
JM
5002 case QEMU_OPTION_cpu:
5003 /* hw initialization will check this */
15f82208 5004 if (*optarg == '?') {
c732abe2
JM
5005/* XXX: implement xxx_cpu_list for targets that still miss it */
5006#if defined(cpu_list)
5007 cpu_list(stdout, &fprintf);
94fc95cd 5008#endif
15f82208 5009 exit(0);
94fc95cd
JM
5010 } else {
5011 cpu_model = optarg;
5012 }
5013 break;
cd6f1169 5014 case QEMU_OPTION_initrd:
fc01f7e7
FB
5015 initrd_filename = optarg;
5016 break;
cd6f1169 5017 case QEMU_OPTION_hda:
e4bcb14c 5018 if (cyls == 0)
9dfd7c7a 5019 hda_opts = drive_add(optarg, HD_ALIAS, 0);
e4bcb14c 5020 else
9dfd7c7a 5021 hda_opts = drive_add(optarg, HD_ALIAS
e4bcb14c 5022 ",cyls=%d,heads=%d,secs=%d%s",
609497ab 5023 0, cyls, heads, secs,
e4bcb14c
TS
5024 translation == BIOS_ATA_TRANSLATION_LBA ?
5025 ",trans=lba" :
5026 translation == BIOS_ATA_TRANSLATION_NONE ?
5027 ",trans=none" : "");
5028 break;
cd6f1169 5029 case QEMU_OPTION_hdb:
cc1daa40
FB
5030 case QEMU_OPTION_hdc:
5031 case QEMU_OPTION_hdd:
609497ab 5032 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
fc01f7e7 5033 break;
e4bcb14c 5034 case QEMU_OPTION_drive:
609497ab 5035 drive_add(NULL, "%s", optarg);
e4bcb14c 5036 break;
3e3d5815 5037 case QEMU_OPTION_mtdblock:
609497ab 5038 drive_add(optarg, MTD_ALIAS);
3e3d5815 5039 break;
a1bb27b1 5040 case QEMU_OPTION_sd:
609497ab 5041 drive_add(optarg, SD_ALIAS);
a1bb27b1 5042 break;
86f55663 5043 case QEMU_OPTION_pflash:
609497ab 5044 drive_add(optarg, PFLASH_ALIAS);
86f55663 5045 break;
cd6f1169 5046 case QEMU_OPTION_snapshot:
33e3963e
FB
5047 snapshot = 1;
5048 break;
cd6f1169 5049 case QEMU_OPTION_hdachs:
330d0414 5050 {
330d0414
FB
5051 const char *p;
5052 p = optarg;
5053 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
5054 if (cyls < 1 || cyls > 16383)
5055 goto chs_fail;
330d0414
FB
5056 if (*p != ',')
5057 goto chs_fail;
5058 p++;
5059 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
5060 if (heads < 1 || heads > 16)
5061 goto chs_fail;
330d0414
FB
5062 if (*p != ',')
5063 goto chs_fail;
5064 p++;
5065 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
5066 if (secs < 1 || secs > 63)
5067 goto chs_fail;
5068 if (*p == ',') {
5069 p++;
5070 if (!strcmp(p, "none"))
5071 translation = BIOS_ATA_TRANSLATION_NONE;
5072 else if (!strcmp(p, "lba"))
5073 translation = BIOS_ATA_TRANSLATION_LBA;
5074 else if (!strcmp(p, "auto"))
5075 translation = BIOS_ATA_TRANSLATION_AUTO;
5076 else
5077 goto chs_fail;
5078 } else if (*p != '\0') {
c4b1fcc0 5079 chs_fail:
46d4767d
FB
5080 fprintf(stderr, "qemu: invalid physical CHS format\n");
5081 exit(1);
c4b1fcc0 5082 }
9dfd7c7a
GH
5083 if (hda_opts != NULL) {
5084 char num[16];
5085 snprintf(num, sizeof(num), "%d", cyls);
5086 qemu_opt_set(hda_opts, "cyls", num);
5087 snprintf(num, sizeof(num), "%d", heads);
5088 qemu_opt_set(hda_opts, "heads", num);
5089 snprintf(num, sizeof(num), "%d", secs);
5090 qemu_opt_set(hda_opts, "secs", num);
5091 if (translation == BIOS_ATA_TRANSLATION_LBA)
5092 qemu_opt_set(hda_opts, "trans", "lba");
5093 if (translation == BIOS_ATA_TRANSLATION_NONE)
5094 qemu_opt_set(hda_opts, "trans", "none");
5095 }
330d0414
FB
5096 }
5097 break;
268a362c
AL
5098 case QEMU_OPTION_numa:
5099 if (nb_numa_nodes >= MAX_NODES) {
5100 fprintf(stderr, "qemu: too many NUMA nodes\n");
5101 exit(1);
5102 }
5103 numa_add(optarg);
5104 break;
cd6f1169 5105 case QEMU_OPTION_nographic:
993fbfdb 5106 display_type = DT_NOGRAPHIC;
a20dd508 5107 break;
4d3b6f6e
AZ
5108#ifdef CONFIG_CURSES
5109 case QEMU_OPTION_curses:
993fbfdb 5110 display_type = DT_CURSES;
4d3b6f6e
AZ
5111 break;
5112#endif
a171fe39
AZ
5113 case QEMU_OPTION_portrait:
5114 graphic_rotate = 1;
5115 break;
cd6f1169 5116 case QEMU_OPTION_kernel:
a20dd508
FB
5117 kernel_filename = optarg;
5118 break;
cd6f1169 5119 case QEMU_OPTION_append:
a20dd508 5120 kernel_cmdline = optarg;
313aa567 5121 break;
cd6f1169 5122 case QEMU_OPTION_cdrom:
609497ab 5123 drive_add(optarg, CDROM_ALIAS);
36b486bb 5124 break;
cd6f1169 5125 case QEMU_OPTION_boot:
28c5af54 5126 {
ef3adf68 5127 static const char * const params[] = {
95387491 5128 "order", "once", "menu", NULL
ef3adf68
JK
5129 };
5130 char buf[sizeof(boot_devices)];
e0f084bf 5131 char *standard_boot_devices;
ef3adf68
JK
5132 int legacy = 0;
5133
5134 if (!strchr(optarg, '=')) {
5135 legacy = 1;
5136 pstrcpy(buf, sizeof(buf), optarg);
5137 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5138 fprintf(stderr,
5139 "qemu: unknown boot parameter '%s' in '%s'\n",
5140 buf, optarg);
5141 exit(1);
5142 }
5143
5144 if (legacy ||
5145 get_param_value(buf, sizeof(buf), "order", optarg)) {
5146 boot_devices_bitmap = parse_bootdevices(buf);
5147 pstrcpy(boot_devices, sizeof(boot_devices), buf);
28c5af54 5148 }
e0f084bf
JK
5149 if (!legacy) {
5150 if (get_param_value(buf, sizeof(buf),
5151 "once", optarg)) {
5152 boot_devices_bitmap |= parse_bootdevices(buf);
5153 standard_boot_devices = qemu_strdup(boot_devices);
5154 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5155 qemu_register_reset(restore_boot_devices,
5156 standard_boot_devices);
5157 }
95387491
JK
5158 if (get_param_value(buf, sizeof(buf),
5159 "menu", optarg)) {
5160 if (!strcmp(buf, "on")) {
5161 boot_menu = 1;
5162 } else if (!strcmp(buf, "off")) {
5163 boot_menu = 0;
5164 } else {
5165 fprintf(stderr,
5166 "qemu: invalid option value '%s'\n",
5167 buf);
5168 exit(1);
5169 }
5170 }
e0f084bf 5171 }
36b486bb
FB
5172 }
5173 break;
cd6f1169 5174 case QEMU_OPTION_fda:
cd6f1169 5175 case QEMU_OPTION_fdb:
609497ab 5176 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
c45886db 5177 break;
52ca8d6a
FB
5178#ifdef TARGET_I386
5179 case QEMU_OPTION_no_fd_bootchk:
5180 fd_bootchk = 0;
5181 break;
5182#endif
7c9d8e07
FB
5183 case QEMU_OPTION_net:
5184 if (nb_net_clients >= MAX_NET_CLIENTS) {
5185 fprintf(stderr, "qemu: too many network clients\n");
c4b1fcc0
FB
5186 exit(1);
5187 }
fd5f393a 5188 net_clients[nb_net_clients] = optarg;
7c9d8e07 5189 nb_net_clients++;
702c651c 5190 break;
c7f74643
FB
5191#ifdef CONFIG_SLIRP
5192 case QEMU_OPTION_tftp:
ad196a9d 5193 legacy_tftp_prefix = optarg;
9bf05444 5194 break;
47d5d01a 5195 case QEMU_OPTION_bootp:
ad196a9d 5196 legacy_bootp_filename = optarg;
47d5d01a 5197 break;
c94c8d64 5198#ifndef _WIN32
9d728e8c 5199 case QEMU_OPTION_smb:
ad196a9d 5200 net_slirp_smb(optarg);
9d728e8c 5201 break;
c94c8d64 5202#endif
9bf05444 5203 case QEMU_OPTION_redir:
f3546deb 5204 net_slirp_redir(optarg);
9bf05444 5205 break;
c7f74643 5206#endif
dc72ac14 5207 case QEMU_OPTION_bt:
bd3c948d 5208 add_device_config(DEV_BT, optarg);
dc72ac14 5209 break;
1d14ffa9 5210#ifdef HAS_AUDIO
1d14ffa9
FB
5211 case QEMU_OPTION_audio_help:
5212 AUD_help ();
5213 exit (0);
5214 break;
5215 case QEMU_OPTION_soundhw:
5216 select_soundhw (optarg);
5217 break;
5218#endif
cd6f1169 5219 case QEMU_OPTION_h:
15f82208 5220 help(0);
cd6f1169 5221 break;
9bd7e6d9
PB
5222 case QEMU_OPTION_version:
5223 version();
5224 exit(0);
5225 break;
00f82b8a
AJ
5226 case QEMU_OPTION_m: {
5227 uint64_t value;
5228 char *ptr;
5229
5230 value = strtoul(optarg, &ptr, 10);
5231 switch (*ptr) {
5232 case 0: case 'M': case 'm':
5233 value <<= 20;
5234 break;
5235 case 'G': case 'g':
5236 value <<= 30;
5237 break;
5238 default:
5239 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
cd6f1169
FB
5240 exit(1);
5241 }
00f82b8a
AJ
5242
5243 /* On 32-bit hosts, QEMU is limited by virtual address space */
5244 if (value > (2047 << 20)
640f42e4 5245#ifndef CONFIG_KQEMU
00f82b8a
AJ
5246 && HOST_LONG_BITS == 32
5247#endif
5248 ) {
5249 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5250 exit(1);
5251 }
5252 if (value != (uint64_t)(ram_addr_t)value) {
5253 fprintf(stderr, "qemu: ram size too large\n");
5254 exit(1);
5255 }
5256 ram_size = value;
cd6f1169 5257 break;
00f82b8a 5258 }
cd6f1169
FB
5259 case QEMU_OPTION_d:
5260 {
5261 int mask;
c7cd6a37 5262 const CPULogItem *item;
3b46e624 5263
cd6f1169
FB
5264 mask = cpu_str_to_log_mask(optarg);
5265 if (!mask) {
5266 printf("Log items (comma separated):\n");
f193c797
FB
5267 for(item = cpu_log_items; item->mask != 0; item++) {
5268 printf("%-10s %s\n", item->name, item->help);
5269 }
5270 exit(1);
cd6f1169
FB
5271 }
5272 cpu_set_log(mask);
f193c797 5273 }
cd6f1169 5274 break;
cd6f1169 5275 case QEMU_OPTION_s:
59030a8c 5276 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
cd6f1169 5277 break;
59030a8c
AL
5278 case QEMU_OPTION_gdb:
5279 gdbstub_dev = optarg;
cd6f1169 5280 break;
cd6f1169 5281 case QEMU_OPTION_L:
5cea8590 5282 data_dir = optarg;
cd6f1169 5283 break;
1192dad8
JM
5284 case QEMU_OPTION_bios:
5285 bios_name = optarg;
5286 break;
1b530a6d
AJ
5287 case QEMU_OPTION_singlestep:
5288 singlestep = 1;
5289 break;
cd6f1169 5290 case QEMU_OPTION_S:
3c07f8e8 5291 autostart = 0;
cd6f1169 5292 break;
5824d651 5293#ifndef _WIN32
3d11d0eb
FB
5294 case QEMU_OPTION_k:
5295 keyboard_layout = optarg;
5296 break;
5824d651 5297#endif
ee22c2f7
FB
5298 case QEMU_OPTION_localtime:
5299 rtc_utc = 0;
5300 break;
3893c124 5301 case QEMU_OPTION_vga:
5302 select_vgahw (optarg);
1bfe856e 5303 break;
5824d651 5304#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2
FB
5305 case QEMU_OPTION_g:
5306 {
5307 const char *p;
5308 int w, h, depth;
5309 p = optarg;
5310 w = strtol(p, (char **)&p, 10);
5311 if (w <= 0) {
5312 graphic_error:
5313 fprintf(stderr, "qemu: invalid resolution or depth\n");
5314 exit(1);
5315 }
5316 if (*p != 'x')
5317 goto graphic_error;
5318 p++;
5319 h = strtol(p, (char **)&p, 10);
5320 if (h <= 0)
5321 goto graphic_error;
5322 if (*p == 'x') {
5323 p++;
5324 depth = strtol(p, (char **)&p, 10);
5fafdf24 5325 if (depth != 8 && depth != 15 && depth != 16 &&
e9b137c2
FB
5326 depth != 24 && depth != 32)
5327 goto graphic_error;
5328 } else if (*p == '\0') {
5329 depth = graphic_depth;
5330 } else {
5331 goto graphic_error;
5332 }
3b46e624 5333
e9b137c2
FB
5334 graphic_width = w;
5335 graphic_height = h;
5336 graphic_depth = depth;
5337 }
5338 break;
5824d651 5339#endif
20d8a3ed
TS
5340 case QEMU_OPTION_echr:
5341 {
5342 char *r;
5343 term_escape_char = strtol(optarg, &r, 0);
5344 if (r == optarg)
5345 printf("Bad argument to echr\n");
5346 break;
5347 }
82c643ff 5348 case QEMU_OPTION_monitor:
fd5f393a 5349 monitor_device = optarg;
82c643ff
FB
5350 break;
5351 case QEMU_OPTION_serial:
8d11df9e
FB
5352 if (serial_device_index >= MAX_SERIAL_PORTS) {
5353 fprintf(stderr, "qemu: too many serial ports\n");
5354 exit(1);
5355 }
fd5f393a 5356 serial_devices[serial_device_index] = optarg;
8d11df9e 5357 serial_device_index++;
82c643ff 5358 break;
9dd986cc
RJ
5359 case QEMU_OPTION_watchdog:
5360 i = select_watchdog(optarg);
5361 if (i > 0)
5362 exit (i == 1 ? 1 : 0);
5363 break;
5364 case QEMU_OPTION_watchdog_action:
5365 if (select_watchdog_action(optarg) == -1) {
5366 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5367 exit(1);
5368 }
5369 break;
51ecf136
AL
5370 case QEMU_OPTION_virtiocon:
5371 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5372 fprintf(stderr, "qemu: too many virtio consoles\n");
5373 exit(1);
5374 }
5375 virtio_consoles[virtio_console_index] = optarg;
5376 virtio_console_index++;
5377 break;
6508fe59
FB
5378 case QEMU_OPTION_parallel:
5379 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5380 fprintf(stderr, "qemu: too many parallel ports\n");
5381 exit(1);
5382 }
fd5f393a 5383 parallel_devices[parallel_device_index] = optarg;
6508fe59
FB
5384 parallel_device_index++;
5385 break;
d63d307f
FB
5386 case QEMU_OPTION_loadvm:
5387 loadvm = optarg;
5388 break;
5389 case QEMU_OPTION_full_screen:
5390 full_screen = 1;
5391 break;
667accab 5392#ifdef CONFIG_SDL
43523e93
TS
5393 case QEMU_OPTION_no_frame:
5394 no_frame = 1;
5395 break;
3780e197
TS
5396 case QEMU_OPTION_alt_grab:
5397 alt_grab = 1;
5398 break;
667accab
TS
5399 case QEMU_OPTION_no_quit:
5400 no_quit = 1;
5401 break;
7d957bd8 5402 case QEMU_OPTION_sdl:
993fbfdb 5403 display_type = DT_SDL;
7d957bd8 5404 break;
667accab 5405#endif
f7cce898 5406 case QEMU_OPTION_pidfile:
93815bc2 5407 pid_file = optarg;
f7cce898 5408 break;
a09db21f
FB
5409#ifdef TARGET_I386
5410 case QEMU_OPTION_win2k_hack:
5411 win2k_install_hack = 1;
5412 break;
73822ec8
AL
5413 case QEMU_OPTION_rtc_td_hack:
5414 rtc_td_hack = 1;
5415 break;
8a92ea2f
AL
5416 case QEMU_OPTION_acpitable:
5417 if(acpi_table_add(optarg) < 0) {
5418 fprintf(stderr, "Wrong acpi table provided\n");
5419 exit(1);
5420 }
5421 break;
b6f6e3d3
AL
5422 case QEMU_OPTION_smbios:
5423 if(smbios_entry_add(optarg) < 0) {
5424 fprintf(stderr, "Wrong smbios provided\n");
5425 exit(1);
5426 }
5427 break;
a09db21f 5428#endif
640f42e4 5429#ifdef CONFIG_KQEMU
52249f0f
AL
5430 case QEMU_OPTION_enable_kqemu:
5431 kqemu_allowed = 1;
d993e026 5432 break;
89bfc105
FB
5433 case QEMU_OPTION_kernel_kqemu:
5434 kqemu_allowed = 2;
5435 break;
7ba1e619
AL
5436#endif
5437#ifdef CONFIG_KVM
5438 case QEMU_OPTION_enable_kvm:
5439 kvm_allowed = 1;
640f42e4 5440#ifdef CONFIG_KQEMU
7ba1e619
AL
5441 kqemu_allowed = 0;
5442#endif
5443 break;
d993e026 5444#endif
bb36d470
FB
5445 case QEMU_OPTION_usb:
5446 usb_enabled = 1;
5447 break;
a594cfbf
FB
5448 case QEMU_OPTION_usbdevice:
5449 usb_enabled = 1;
bd3c948d
GH
5450 add_device_config(DEV_USB, optarg);
5451 break;
5452 case QEMU_OPTION_device:
5453 add_device_config(DEV_GENERIC, optarg);
a594cfbf 5454 break;
6a00d601
FB
5455 case QEMU_OPTION_smp:
5456 smp_cpus = atoi(optarg);
b2097003 5457 if (smp_cpus < 1) {
6a00d601
FB
5458 fprintf(stderr, "Invalid number of CPUs\n");
5459 exit(1);
5460 }
5461 break;
24236869 5462 case QEMU_OPTION_vnc:
993fbfdb 5463 display_type = DT_VNC;
73fc9742 5464 vnc_display = optarg;
24236869 5465 break;
5824d651 5466#ifdef TARGET_I386
6515b203
FB
5467 case QEMU_OPTION_no_acpi:
5468 acpi_enabled = 0;
5469 break;
16b29ae1
AL
5470 case QEMU_OPTION_no_hpet:
5471 no_hpet = 1;
5472 break;
7d4c3d53
MA
5473 case QEMU_OPTION_balloon:
5474 if (balloon_parse(optarg) < 0) {
5475 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5476 exit(1);
5477 }
df97b920 5478 break;
5824d651 5479#endif
d1beab82
FB
5480 case QEMU_OPTION_no_reboot:
5481 no_reboot = 1;
5482 break;
b2f76161
AJ
5483 case QEMU_OPTION_no_shutdown:
5484 no_shutdown = 1;
5485 break;
9467cd46
AZ
5486 case QEMU_OPTION_show_cursor:
5487 cursor_hide = 0;
5488 break;
8fcb1b90
BS
5489 case QEMU_OPTION_uuid:
5490 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5491 fprintf(stderr, "Fail to parse UUID string."
5492 " Wrong format.\n");
5493 exit(1);
5494 }
5495 break;
5824d651 5496#ifndef _WIN32
71e3ceb8
TS
5497 case QEMU_OPTION_daemonize:
5498 daemonize = 1;
5499 break;
5824d651 5500#endif
9ae02555
TS
5501 case QEMU_OPTION_option_rom:
5502 if (nb_option_roms >= MAX_OPTION_ROMS) {
5503 fprintf(stderr, "Too many option ROMs\n");
5504 exit(1);
5505 }
5506 option_rom[nb_option_roms] = optarg;
5507 nb_option_roms++;
5508 break;
5824d651 5509#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
5510 case QEMU_OPTION_semihosting:
5511 semihosting_enabled = 1;
5512 break;
5824d651 5513#endif
c35734b2 5514 case QEMU_OPTION_name:
1889465a
AK
5515 qemu_name = qemu_strdup(optarg);
5516 {
5517 char *p = strchr(qemu_name, ',');
5518 if (p != NULL) {
5519 *p++ = 0;
5520 if (strncmp(p, "process=", 8)) {
5521 fprintf(stderr, "Unknown subargument %s to -name", p);
5522 exit(1);
5523 }
5524 p += 8;
5525 set_proc_name(p);
5526 }
5527 }
c35734b2 5528 break;
95efd11c 5529#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
5530 case QEMU_OPTION_prom_env:
5531 if (nb_prom_envs >= MAX_PROM_ENVS) {
5532 fprintf(stderr, "Too many prom variables\n");
5533 exit(1);
5534 }
5535 prom_envs[nb_prom_envs] = optarg;
5536 nb_prom_envs++;
5537 break;
2b8f2d41
AZ
5538#endif
5539#ifdef TARGET_ARM
5540 case QEMU_OPTION_old_param:
5541 old_param = 1;
05ebd537 5542 break;
66508601 5543#endif
f3dcfada
TS
5544 case QEMU_OPTION_clock:
5545 configure_alarms(optarg);
5546 break;
7e0af5d0
FB
5547 case QEMU_OPTION_startdate:
5548 {
5549 struct tm tm;
f6503059 5550 time_t rtc_start_date;
7e0af5d0 5551 if (!strcmp(optarg, "now")) {
f6503059 5552 rtc_date_offset = -1;
7e0af5d0
FB
5553 } else {
5554 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5555 &tm.tm_year,
5556 &tm.tm_mon,
5557 &tm.tm_mday,
5558 &tm.tm_hour,
5559 &tm.tm_min,
5560 &tm.tm_sec) == 6) {
5561 /* OK */
5562 } else if (sscanf(optarg, "%d-%d-%d",
5563 &tm.tm_year,
5564 &tm.tm_mon,
5565 &tm.tm_mday) == 3) {
5566 tm.tm_hour = 0;
5567 tm.tm_min = 0;
5568 tm.tm_sec = 0;
5569 } else {
5570 goto date_fail;
5571 }
5572 tm.tm_year -= 1900;
5573 tm.tm_mon--;
3c6b2088 5574 rtc_start_date = mktimegm(&tm);
7e0af5d0
FB
5575 if (rtc_start_date == -1) {
5576 date_fail:
5577 fprintf(stderr, "Invalid date format. Valid format are:\n"
5578 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5579 exit(1);
5580 }
f6503059 5581 rtc_date_offset = time(NULL) - rtc_start_date;
7e0af5d0
FB
5582 }
5583 }
5584 break;
26a5f13b
FB
5585 case QEMU_OPTION_tb_size:
5586 tb_size = strtol(optarg, NULL, 0);
5587 if (tb_size < 0)
5588 tb_size = 0;
5589 break;
2e70f6ef
PB
5590 case QEMU_OPTION_icount:
5591 use_icount = 1;
5592 if (strcmp(optarg, "auto") == 0) {
5593 icount_time_shift = -1;
5594 } else {
5595 icount_time_shift = strtol(optarg, NULL, 0);
5596 }
5597 break;
5bb7910a
AL
5598 case QEMU_OPTION_incoming:
5599 incoming = optarg;
5600 break;
5824d651 5601#ifndef _WIN32
0858532e
AL
5602 case QEMU_OPTION_chroot:
5603 chroot_dir = optarg;
5604 break;
5605 case QEMU_OPTION_runas:
5606 run_as = optarg;
5607 break;
e37630ca
AL
5608#endif
5609#ifdef CONFIG_XEN
5610 case QEMU_OPTION_xen_domid:
5611 xen_domid = atoi(optarg);
5612 break;
5613 case QEMU_OPTION_xen_create:
5614 xen_mode = XEN_CREATE;
5615 break;
5616 case QEMU_OPTION_xen_attach:
5617 xen_mode = XEN_ATTACH;
5618 break;
5824d651 5619#endif
cd6f1169 5620 }
0824d6fc
FB
5621 }
5622 }
330d0414 5623
5cea8590
PB
5624 /* If no data_dir is specified then try to find it relative to the
5625 executable path. */
5626 if (!data_dir) {
5627 data_dir = find_datadir(argv[0]);
5628 }
5629 /* If all else fails use the install patch specified when building. */
5630 if (!data_dir) {
5631 data_dir = CONFIG_QEMU_SHAREDIR;
5632 }
5633
640f42e4 5634#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
7ba1e619
AL
5635 if (kvm_allowed && kqemu_allowed) {
5636 fprintf(stderr,
5637 "You can not enable both KVM and kqemu at the same time\n");
5638 exit(1);
5639 }
5640#endif
5641
3d878caa 5642 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
b2097003
AL
5643 if (smp_cpus > machine->max_cpus) {
5644 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5645 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5646 machine->max_cpus);
5647 exit(1);
5648 }
5649
993fbfdb 5650 if (display_type == DT_NOGRAPHIC) {
bc0129d9
AL
5651 if (serial_device_index == 0)
5652 serial_devices[0] = "stdio";
5653 if (parallel_device_index == 0)
5654 parallel_devices[0] = "null";
5655 if (strncmp(monitor_device, "vc", 2) == 0)
5656 monitor_device = "stdio";
5657 }
5658
71e3ceb8 5659#ifndef _WIN32
71e3ceb8
TS
5660 if (daemonize) {
5661 pid_t pid;
5662
5663 if (pipe(fds) == -1)
5664 exit(1);
5665
5666 pid = fork();
5667 if (pid > 0) {
5668 uint8_t status;
5669 ssize_t len;
5670
5671 close(fds[1]);
5672
5673 again:
93815bc2
TS
5674 len = read(fds[0], &status, 1);
5675 if (len == -1 && (errno == EINTR))
5676 goto again;
5677
5678 if (len != 1)
5679 exit(1);
5680 else if (status == 1) {
5681 fprintf(stderr, "Could not acquire pidfile\n");
5682 exit(1);
5683 } else
5684 exit(0);
71e3ceb8 5685 } else if (pid < 0)
93815bc2 5686 exit(1);
71e3ceb8
TS
5687
5688 setsid();
5689
5690 pid = fork();
5691 if (pid > 0)
5692 exit(0);
5693 else if (pid < 0)
5694 exit(1);
5695
5696 umask(027);
71e3ceb8
TS
5697
5698 signal(SIGTSTP, SIG_IGN);
5699 signal(SIGTTOU, SIG_IGN);
5700 signal(SIGTTIN, SIG_IGN);
5701 }
71e3ceb8 5702
aa26bb2d 5703 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
5704 if (daemonize) {
5705 uint8_t status = 1;
5706 write(fds[1], &status, 1);
5707 } else
5708 fprintf(stderr, "Could not acquire pid file\n");
5709 exit(1);
5710 }
b9e82a59 5711#endif
93815bc2 5712
640f42e4 5713#ifdef CONFIG_KQEMU
ff3fbb30
FB
5714 if (smp_cpus > 1)
5715 kqemu_allowed = 0;
5716#endif
3fcf7b6b
AL
5717 if (qemu_init_main_loop()) {
5718 fprintf(stderr, "qemu_init_main_loop failed\n");
5719 exit(1);
5720 }
a20dd508 5721 linux_boot = (kernel_filename != NULL);
6c41b272 5722
f8d39c01
TS
5723 if (!linux_boot && *kernel_cmdline != '\0') {
5724 fprintf(stderr, "-append only allowed with -kernel option\n");
5725 exit(1);
5726 }
5727
5728 if (!linux_boot && initrd_filename != NULL) {
5729 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5730 exit(1);
5731 }
5732
b118d61e 5733 setvbuf(stdout, NULL, _IOLBF, 0);
3b46e624 5734
634fce96 5735 init_timers();
7183b4b4
AL
5736 if (init_timer_alarm() < 0) {
5737 fprintf(stderr, "could not initialize alarm timer\n");
5738 exit(1);
5739 }
2e70f6ef
PB
5740 if (use_icount && icount_time_shift < 0) {
5741 use_icount = 2;
5742 /* 125MIPS seems a reasonable initial guess at the guest speed.
5743 It will be corrected fairly quickly anyway. */
5744 icount_time_shift = 3;
5745 init_icount_adjust();
5746 }
634fce96 5747
fd1dff4b
FB
5748#ifdef _WIN32
5749 socket_init();
5750#endif
5751
7c9d8e07
FB
5752 /* init network clients */
5753 if (nb_net_clients == 0) {
5754 /* if no clients, we use a default config */
f441b28b
AL
5755 net_clients[nb_net_clients++] = "nic";
5756#ifdef CONFIG_SLIRP
5757 net_clients[nb_net_clients++] = "user";
5758#endif
c20709aa
FB
5759 }
5760
7c9d8e07 5761 for(i = 0;i < nb_net_clients; i++) {
9ad97e65 5762 if (net_client_parse(net_clients[i]) < 0)
7c9d8e07 5763 exit(1);
702c651c 5764 }
f1510b2c 5765
406c8df3
GC
5766 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5767 net_set_boot_mask(net_boot);
5768
5769 net_client_check();
eec85c2a 5770
dc72ac14 5771 /* init the bluetooth world */
bd3c948d
GH
5772 if (foreach_device_config(DEV_BT, bt_parse))
5773 exit(1);
dc72ac14 5774
0824d6fc 5775 /* init the memory */
94a6b54f
PB
5776 if (ram_size == 0)
5777 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9ae02555 5778
640f42e4 5779#ifdef CONFIG_KQEMU
94a6b54f
PB
5780 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5781 guest ram allocation. It needs to go away. */
5782 if (kqemu_allowed) {
4cfce484 5783 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
94a6b54f
PB
5784 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5785 if (!kqemu_phys_ram_base) {
5786 fprintf(stderr, "Could not allocate physical memory\n");
5787 exit(1);
5788 }
0824d6fc 5789 }
94a6b54f 5790#endif
0824d6fc 5791
26a5f13b
FB
5792 /* init the dynamic translator */
5793 cpu_exec_init_all(tb_size * 1024 * 1024);
5794
5905b2e5 5795 bdrv_init();
c4b1fcc0 5796
e4bcb14c 5797 /* we always create the cdrom drive, even if no disk is there */
3b0ba927 5798 drive_add(NULL, CDROM_ALIAS);
c4b1fcc0 5799
9d413d1d 5800 /* we always create at least one floppy */
3b0ba927 5801 drive_add(NULL, FD_ALIAS, 0);
86f55663 5802
9d413d1d 5803 /* we always create one sd slot, even if no card is in it */
3b0ba927 5804 drive_add(NULL, SD_ALIAS);
9d413d1d 5805
e4bcb14c 5806 /* open the virtual block devices */
9dfd7c7a
GH
5807 if (snapshot)
5808 qemu_opts_foreach(&drive_opt_list, drive_enable_snapshot, NULL, 0);
5809 if (qemu_opts_foreach(&drive_opt_list, drive_init_func, machine, 1) != 0)
5810 exit(1);
3e3d5815 5811
c88676f8 5812 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
475e4277 5813 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
8a7ddc38 5814
3023f332
AL
5815#ifndef _WIN32
5816 /* must be after terminal init, SDL library changes signal handlers */
7c3370d4 5817 sighandler_setup();
3023f332
AL
5818#endif
5819
5820 /* Maintain compatibility with multiple stdio monitors */
5821 if (!strcmp(monitor_device,"stdio")) {
5822 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5823 const char *devname = serial_devices[i];
5824 if (devname && !strcmp(devname,"mon:stdio")) {
5825 monitor_device = NULL;
5826 break;
5827 } else if (devname && !strcmp(devname,"stdio")) {
5828 monitor_device = NULL;
5829 serial_devices[i] = "mon:stdio";
5830 break;
5831 }
5832 }
5833 }
5834
268a362c
AL
5835 if (nb_numa_nodes > 0) {
5836 int i;
5837
5838 if (nb_numa_nodes > smp_cpus) {
5839 nb_numa_nodes = smp_cpus;
5840 }
5841
5842 /* If no memory size if given for any node, assume the default case
5843 * and distribute the available memory equally across all nodes
5844 */
5845 for (i = 0; i < nb_numa_nodes; i++) {
5846 if (node_mem[i] != 0)
5847 break;
5848 }
5849 if (i == nb_numa_nodes) {
5850 uint64_t usedmem = 0;
5851
5852 /* On Linux, the each node's border has to be 8MB aligned,
5853 * the final node gets the rest.
5854 */
5855 for (i = 0; i < nb_numa_nodes - 1; i++) {
5856 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5857 usedmem += node_mem[i];
5858 }
5859 node_mem[i] = ram_size - usedmem;
5860 }
5861
5862 for (i = 0; i < nb_numa_nodes; i++) {
5863 if (node_cpumask[i] != 0)
5864 break;
5865 }
5866 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5867 * must cope with this anyway, because there are BIOSes out there in
5868 * real machines which also use this scheme.
5869 */
5870 if (i == nb_numa_nodes) {
5871 for (i = 0; i < smp_cpus; i++) {
5872 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5873 }
5874 }
5875 }
5876
3023f332
AL
5877 if (kvm_enabled()) {
5878 int ret;
5879
5880 ret = kvm_init(smp_cpus);
5881 if (ret < 0) {
5882 fprintf(stderr, "failed to initialize KVM\n");
5883 exit(1);
5884 }
5885 }
5886
4c621805 5887 if (monitor_device) {
ceecf1d1 5888 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
4c621805
AL
5889 if (!monitor_hd) {
5890 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5891 exit(1);
5892 }
5893 }
5894
2796dae0
AL
5895 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5896 const char *devname = serial_devices[i];
5897 if (devname && strcmp(devname, "none")) {
5898 char label[32];
5899 snprintf(label, sizeof(label), "serial%d", i);
ceecf1d1 5900 serial_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0
AL
5901 if (!serial_hds[i]) {
5902 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5903 devname);
5904 exit(1);
5905 }
5906 }
5907 }
5908
5909 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5910 const char *devname = parallel_devices[i];
5911 if (devname && strcmp(devname, "none")) {
5912 char label[32];
5913 snprintf(label, sizeof(label), "parallel%d", i);
ceecf1d1 5914 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0
AL
5915 if (!parallel_hds[i]) {
5916 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5917 devname);
5918 exit(1);
5919 }
5920 }
5921 }
5922
5923 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5924 const char *devname = virtio_consoles[i];
5925 if (devname && strcmp(devname, "none")) {
5926 char label[32];
5927 snprintf(label, sizeof(label), "virtcon%d", i);
ceecf1d1 5928 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0
AL
5929 if (!virtcon_hds[i]) {
5930 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5931 devname);
5932 exit(1);
5933 }
5934 }
5935 }
5936
aae9460e
PB
5937 module_call_init(MODULE_INIT_DEVICE);
5938
b6b61144
GH
5939 if (machine->compat_props) {
5940 qdev_prop_register_compat(machine->compat_props);
5941 }
fbe1b595 5942 machine->init(ram_size, boot_devices,
3023f332
AL
5943 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5944
268a362c
AL
5945
5946 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5947 for (i = 0; i < nb_numa_nodes; i++) {
5948 if (node_cpumask[i] & (1 << env->cpu_index)) {
5949 env->numa_node = i;
5950 }
5951 }
5952 }
5953
6f338c34
AL
5954 current_machine = machine;
5955
3023f332
AL
5956 /* init USB devices */
5957 if (usb_enabled) {
bd3c948d 5958 foreach_device_config(DEV_USB, usb_parse);
3023f332
AL
5959 }
5960
bd3c948d
GH
5961 /* init generic devices */
5962 if (foreach_device_config(DEV_GENERIC, generic_parse))
5963 exit(1);
5964
8f391ab4
AL
5965 if (!display_state)
5966 dumb_display_init();
3023f332
AL
5967 /* just use the first displaystate for the moment */
5968 ds = display_state;
993fbfdb
AL
5969
5970 if (display_type == DT_DEFAULT) {
5971#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5972 display_type = DT_SDL;
5973#else
5974 display_type = DT_VNC;
5975 vnc_display = "localhost:0,to=99";
5976 show_vnc_port = 1;
5977#endif
5978 }
5979
5980
5981 switch (display_type) {
5982 case DT_NOGRAPHIC:
5983 break;
4d3b6f6e 5984#if defined(CONFIG_CURSES)
993fbfdb
AL
5985 case DT_CURSES:
5986 curses_display_init(ds, full_screen);
5987 break;
4d3b6f6e 5988#endif
5b0753e0 5989#if defined(CONFIG_SDL)
993fbfdb
AL
5990 case DT_SDL:
5991 sdl_display_init(ds, full_screen, no_frame);
5992 break;
5b0753e0 5993#elif defined(CONFIG_COCOA)
993fbfdb
AL
5994 case DT_SDL:
5995 cocoa_display_init(ds, full_screen);
5996 break;
313aa567 5997#endif
993fbfdb
AL
5998 case DT_VNC:
5999 vnc_display_init(ds);
6000 if (vnc_display_open(ds, vnc_display) < 0)
6001 exit(1);
f92f8afe 6002
993fbfdb
AL
6003 if (show_vnc_port) {
6004 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
f92f8afe 6005 }
993fbfdb
AL
6006 break;
6007 default:
6008 break;
313aa567 6009 }
7d957bd8 6010 dpy_resize(ds);
5b08fc10 6011
3023f332
AL
6012 dcl = ds->listeners;
6013 while (dcl != NULL) {
6014 if (dcl->dpy_refresh != NULL) {
6015 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6016 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
20d8a3ed 6017 }
3023f332 6018 dcl = dcl->next;
20d8a3ed 6019 }
3023f332 6020
993fbfdb 6021 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
9043b62d
BS
6022 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6023 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6024 }
6025
2796dae0 6026 text_consoles_set_display(display_state);
2970a6c9 6027 qemu_chr_initial_reset();
2796dae0 6028
4c621805 6029 if (monitor_device && monitor_hd)
cde76ee1 6030 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
82c643ff 6031
8d11df9e 6032 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
c03b0f0f 6033 const char *devname = serial_devices[i];
fd5f393a 6034 if (devname && strcmp(devname, "none")) {
af3a9031 6035 if (strstart(devname, "vc", 0))
7ba1260a 6036 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8d11df9e 6037 }
82c643ff 6038 }
82c643ff 6039
6508fe59 6040 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
c03b0f0f 6041 const char *devname = parallel_devices[i];
fd5f393a 6042 if (devname && strcmp(devname, "none")) {
af3a9031 6043 if (strstart(devname, "vc", 0))
7ba1260a 6044 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6508fe59
FB
6045 }
6046 }
6047
9ede2fde
AL
6048 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6049 const char *devname = virtio_consoles[i];
2796dae0 6050 if (virtcon_hds[i] && devname) {
9ede2fde
AL
6051 if (strstart(devname, "vc", 0))
6052 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6053 }
6054 }
6055
59030a8c
AL
6056 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6057 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6058 gdbstub_dev);
6059 exit(1);
45669e00 6060 }
45669e00 6061
d63d307f 6062 if (loadvm)
376253ec 6063 do_loadvm(cur_mon, loadvm);
d63d307f 6064
89befdd1 6065 if (incoming)
5bb7910a 6066 qemu_start_incoming_migration(incoming);
5bb7910a 6067
c0f4ce77
AL
6068 if (autostart)
6069 vm_start();
ffd843bc 6070
b9e82a59 6071#ifndef _WIN32
71e3ceb8
TS
6072 if (daemonize) {
6073 uint8_t status = 0;
6074 ssize_t len;
71e3ceb8
TS
6075
6076 again1:
6077 len = write(fds[1], &status, 1);
6078 if (len == -1 && (errno == EINTR))
6079 goto again1;
6080
6081 if (len != 1)
6082 exit(1);
6083
bd54b863 6084 chdir("/");
aeb30be6 6085 TFR(fd = open("/dev/null", O_RDWR));
71e3ceb8
TS
6086 if (fd == -1)
6087 exit(1);
0858532e 6088 }
71e3ceb8 6089
0858532e
AL
6090 if (run_as) {
6091 pwd = getpwnam(run_as);
6092 if (!pwd) {
6093 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6094 exit(1);
6095 }
6096 }
6097
6098 if (chroot_dir) {
6099 if (chroot(chroot_dir) < 0) {
6100 fprintf(stderr, "chroot failed\n");
6101 exit(1);
6102 }
6103 chdir("/");
6104 }
6105
6106 if (run_as) {
6107 if (setgid(pwd->pw_gid) < 0) {
6108 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6109 exit(1);
6110 }
6111 if (setuid(pwd->pw_uid) < 0) {
6112 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6113 exit(1);
6114 }
6115 if (setuid(0) != -1) {
6116 fprintf(stderr, "Dropping privileges failed\n");
6117 exit(1);
6118 }
6119 }
0858532e
AL
6120
6121 if (daemonize) {
6122 dup2(fd, 0);
6123 dup2(fd, 1);
6124 dup2(fd, 2);
71e3ceb8 6125
0858532e 6126 close(fd);
71e3ceb8 6127 }
b9e82a59 6128#endif
71e3ceb8 6129
8a7ddc38 6130 main_loop();
40c3bac3 6131 quit_timers();
63a01ef8 6132 net_cleanup();
b46a8906 6133
0824d6fc
FB
6134 return 0;
6135}