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