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