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