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