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