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