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