blob: aa5b3cf34445b14654f25bc32303f30775dba972 [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);
2241
2242 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 }
4464 ret = cpu_exec(env);
4465#ifdef CONFIG_PROFILER
4466 qemu_time += profile_getclock() - ti;
4467#endif
4468 if (use_icount) {
4469 /* Fold pending instructions back into the
4470 instruction counter, and clear the interrupt flag. */
4471 qemu_icount -= (env->icount_decr.u16.low
4472 + env->icount_extra);
4473 env->icount_decr.u32 = 0;
4474 env->icount_extra = 0;
4475 }
4476 return ret;
4477}
4478
4479static void tcg_cpu_exec(void)
4480{
4481 int ret = 0;
4482
4483 if (next_cpu == NULL)
4484 next_cpu = first_cpu;
4485 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4486 CPUState *env = cur_cpu = next_cpu;
4487
4488 if (!vm_running)
4489 break;
4490 if (timer_alarm_pending) {
4491 timer_alarm_pending = 0;
4492 break;
4493 }
4494 if (cpu_can_run(env))
4495 ret = qemu_cpu_exec(env);
4496 if (ret == EXCP_DEBUG) {
4497 gdb_set_stop_cpu(env);
4498 debug_requested = 1;
4499 break;
4500 }
4501 }
4502}
4503
4504static int cpu_has_work(CPUState *env)
4505{
4506 if (env->stop)
4507 return 1;
4508 if (env->stopped)
4509 return 0;
4510 if (!env->halted)
4511 return 1;
4512 if (qemu_cpu_has_work(env))
4513 return 1;
4514 return 0;
4515}
4516
4517static int tcg_has_work(void)
4518{
4519 CPUState *env;
4520
4521 for (env = first_cpu; env != NULL; env = env->next_cpu)
4522 if (cpu_has_work(env))
4523 return 1;
4524 return 0;
4525}
4526
4527static int qemu_calculate_timeout(void)
4528{
4529#ifndef CONFIG_IOTHREAD
4530 int timeout;
4531
4532 if (!vm_running)
4533 timeout = 5000;
4534 else if (tcg_has_work())
4535 timeout = 0;
4536 else if (!use_icount)
4537 timeout = 5000;
4538 else {
4539 /* XXX: use timeout computed from timers */
4540 int64_t add;
4541 int64_t delta;
4542 /* Advance virtual time to the next event. */
4543 if (use_icount == 1) {
4544 /* When not using an adaptive execution frequency
4545 we tend to get badly out of sync with real time,
4546 so just delay for a reasonable amount of time. */
4547 delta = 0;
4548 } else {
4549 delta = cpu_get_icount() - cpu_get_clock();
4550 }
4551 if (delta > 0) {
4552 /* If virtual time is ahead of real time then just
4553 wait for IO. */
4554 timeout = (delta / 1000000) + 1;
4555 } else {
4556 /* Wait for either IO to occur or the next
4557 timer event. */
4558 add = qemu_next_deadline();
4559 /* We advance the timer before checking for IO.
4560 Limit the amount we advance so that early IO
4561 activity won't get the guest too far ahead. */
4562 if (add > 10000000)
4563 add = 10000000;
4564 delta += add;
4565 add = (add + (1 << icount_time_shift) - 1)
4566 >> icount_time_shift;
4567 qemu_icount += add;
4568 timeout = delta / 1000000;
4569 if (timeout < 0)
4570 timeout = 0;
4571 }
4572 }
4573
4574 return timeout;
4575#else /* CONFIG_IOTHREAD */
4576 return 1000;
4577#endif
4578}
4579
4580static int vm_can_run(void)
4581{
4582 if (powerdown_requested)
4583 return 0;
4584 if (reset_requested)
4585 return 0;
4586 if (shutdown_requested)
4587 return 0;
4588 if (debug_requested)
4589 return 0;
4590 return 1;
4591}
4592
4593static void main_loop(void)
4594{
4595 int r;
4596
4597#ifdef CONFIG_IOTHREAD
4598 qemu_system_ready = 1;
4599 qemu_cond_broadcast(&qemu_system_cond);
4600#endif
4601
4602 for (;;) {
4603 do {
4604#ifdef CONFIG_PROFILER
4605 int64_t ti;
4606#endif
4607#ifndef CONFIG_IOTHREAD
4608 tcg_cpu_exec();
4609#endif
4610#ifdef CONFIG_PROFILER
4611 ti = profile_getclock();
4612#endif
4613 main_loop_wait(qemu_calculate_timeout());
4614#ifdef CONFIG_PROFILER
4615 dev_time += profile_getclock() - ti;
4616#endif
4617 } while (vm_can_run());
4618
4619 if (qemu_debug_requested())
4620 vm_stop(EXCP_DEBUG);
4621 if (qemu_shutdown_requested()) {
4622 if (no_shutdown) {
4623 vm_stop(0);
4624 no_shutdown = 0;
4625 } else
4626 break;
4627 }
4628 if (qemu_reset_requested()) {
4629 pause_all_vcpus();
4630 qemu_system_reset();
4631 resume_all_vcpus();
4632 }
4633 if (qemu_powerdown_requested())
4634 qemu_system_powerdown();
4635 if ((r = qemu_vmstop_requested()))
4636 vm_stop(r);
4637 }
4638 pause_all_vcpus();
4639}
4640
4641static void version(void)
4642{
4643 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4644}
4645
4646void qemu_help(int exitcode)
4647{
4648 version();
4649 printf("usage: %s [options] [disk_image]\n"
4650 "\n"
4651 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4652 "\n"
4653#define DEF(option, opt_arg, opt_enum, opt_help) \
4654 opt_help
4655#define DEFHEADING(text) stringify(text) "\n"
4656#include "qemu-options.h"
4657#undef DEF
4658#undef DEFHEADING
4659#undef GEN_DOCS
4660 "\n"
4661 "During emulation, the following keys are useful:\n"
4662 "ctrl-alt-f toggle full screen\n"
4663 "ctrl-alt-n switch to virtual console 'n'\n"
4664 "ctrl-alt toggle mouse and keyboard grab\n"
4665 "\n"
4666 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4667 ,
4668 "qemu",
4669 DEFAULT_RAM_SIZE,
4670#ifndef _WIN32
4671 DEFAULT_NETWORK_SCRIPT,
4672 DEFAULT_NETWORK_DOWN_SCRIPT,
4673#endif
4674 DEFAULT_GDBSTUB_PORT,
4675 "/tmp/qemu.log");
4676 exit(exitcode);
4677}
4678
4679#define HAS_ARG 0x0001
4680
4681enum {
4682#define DEF(option, opt_arg, opt_enum, opt_help) \
4683 opt_enum,
4684#define DEFHEADING(text)
4685#include "qemu-options.h"
4686#undef DEF
4687#undef DEFHEADING
4688#undef GEN_DOCS
4689};
4690
4691typedef struct QEMUOption {
4692 const char *name;
4693 int flags;
4694 int index;
4695} QEMUOption;
4696
4697static const QEMUOption qemu_options[] = {
4698 { "h", 0, QEMU_OPTION_h },
4699#define DEF(option, opt_arg, opt_enum, opt_help) \
4700 { option, opt_arg, opt_enum },
4701#define DEFHEADING(text)
4702#include "qemu-options.h"
4703#undef DEF
4704#undef DEFHEADING
4705#undef GEN_DOCS
4706 { NULL, 0, 0 },
4707};
4708
4709#ifdef HAS_AUDIO
4710struct soundhw soundhw[] = {
4711#ifdef HAS_AUDIO_CHOICE
4712#if defined(TARGET_I386) || defined(TARGET_MIPS)
4713 {
4714 "pcspk",
4715 "PC speaker",
4716 0,
4717 1,
4718 { .init_isa = pcspk_audio_init }
4719 },
4720#endif
4721
4722#ifdef CONFIG_SB16
4723 {
4724 "sb16",
4725 "Creative Sound Blaster 16",
4726 0,
4727 1,
4728 { .init_isa = SB16_init }
4729 },
4730#endif
4731
4732#ifdef CONFIG_CS4231A
4733 {
4734 "cs4231a",
4735 "CS4231A",
4736 0,
4737 1,
4738 { .init_isa = cs4231a_init }
4739 },
4740#endif
4741
4742#ifdef CONFIG_ADLIB
4743 {
4744 "adlib",
4745#ifdef HAS_YMF262
4746 "Yamaha YMF262 (OPL3)",
4747#else
4748 "Yamaha YM3812 (OPL2)",
4749#endif
4750 0,
4751 1,
4752 { .init_isa = Adlib_init }
4753 },
4754#endif
4755
4756#ifdef CONFIG_GUS
4757 {
4758 "gus",
4759 "Gravis Ultrasound GF1",
4760 0,
4761 1,
4762 { .init_isa = GUS_init }
4763 },
4764#endif
4765
4766#ifdef CONFIG_AC97
4767 {
4768 "ac97",
4769 "Intel 82801AA AC97 Audio",
4770 0,
4771 0,
4772 { .init_pci = ac97_init }
4773 },
4774#endif
4775
4776#ifdef CONFIG_ES1370
4777 {
4778 "es1370",
4779 "ENSONIQ AudioPCI ES1370",
4780 0,
4781 0,
4782 { .init_pci = es1370_init }
4783 },
4784#endif
4785
4786#endif /* HAS_AUDIO_CHOICE */
4787
4788 { NULL, NULL, 0, 0, { NULL } }
4789};
4790
4791static void select_soundhw (const char *optarg)
4792{
4793 struct soundhw *c;
4794
4795 if (*optarg == '?') {
4796 show_valid_cards:
4797
4798 printf ("Valid sound card names (comma separated):\n");
4799 for (c = soundhw; c->name; ++c) {
4800 printf ("%-11s %s\n", c->name, c->descr);
4801 }
4802 printf ("\n-soundhw all will enable all of the above\n");
4803 exit (*optarg != '?');
4804 }
4805 else {
4806 size_t l;
4807 const char *p;
4808 char *e;
4809 int bad_card = 0;
4810
4811 if (!strcmp (optarg, "all")) {
4812 for (c = soundhw; c->name; ++c) {
4813 c->enabled = 1;
4814 }
4815 return;
4816 }
4817
4818 p = optarg;
4819 while (*p) {
4820 e = strchr (p, ',');
4821 l = !e ? strlen (p) : (size_t) (e - p);
4822
4823 for (c = soundhw; c->name; ++c) {
4824 if (!strncmp (c->name, p, l)) {
4825 c->enabled = 1;
4826 break;
4827 }
4828 }
4829
4830 if (!c->name) {
4831 if (l > 80) {
4832 fprintf (stderr,
4833 "Unknown sound card name (too big to show)\n");
4834 }
4835 else {
4836 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4837 (int) l, p);
4838 }
4839 bad_card = 1;
4840 }
4841 p += l + (e != NULL);
4842 }
4843
4844 if (bad_card)
4845 goto show_valid_cards;
4846 }
4847}
4848#endif
4849
4850static void select_vgahw (const char *p)
4851{
4852 const char *opts;
4853
4854 cirrus_vga_enabled = 0;
4855 std_vga_enabled = 0;
4856 vmsvga_enabled = 0;
4857 xenfb_enabled = 0;
4858 if (strstart(p, "std", &opts)) {
4859 std_vga_enabled = 1;
4860 } else if (strstart(p, "cirrus", &opts)) {
4861 cirrus_vga_enabled = 1;
4862 } else if (strstart(p, "vmware", &opts)) {
4863 vmsvga_enabled = 1;
4864 } else if (strstart(p, "xenfb", &opts)) {
4865 xenfb_enabled = 1;
4866 } else if (!strstart(p, "none", &opts)) {
4867 invalid_vga:
4868 fprintf(stderr, "Unknown vga type: %s\n", p);
4869 exit(1);
4870 }
4871 while (*opts) {
4872 const char *nextopt;
4873
4874 if (strstart(opts, ",retrace=", &nextopt)) {
4875 opts = nextopt;
4876 if (strstart(opts, "dumb", &nextopt))
4877 vga_retrace_method = VGA_RETRACE_DUMB;
4878 else if (strstart(opts, "precise", &nextopt))
4879 vga_retrace_method = VGA_RETRACE_PRECISE;
4880 else goto invalid_vga;
4881 } else goto invalid_vga;
4882 opts = nextopt;
4883 }
4884}
4885
4886#ifdef _WIN32
4887static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4888{
4889 exit(STATUS_CONTROL_C_EXIT);
4890 return TRUE;
4891}
4892#endif
4893
4894int qemu_uuid_parse(const char *str, uint8_t *uuid)
4895{
4896 int ret;
4897
4898 if(strlen(str) != 36)
4899 return -1;
4900
4901 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4902 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4903 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4904
4905 if(ret != 16)
4906 return -1;
4907
4908#ifdef TARGET_I386
4909 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4910#endif
4911
4912 return 0;
4913}
4914
4915#define MAX_NET_CLIENTS 32
4916
4917#ifndef _WIN32
4918
4919static void termsig_handler(int signal)
4920{
4921 qemu_system_shutdown_request();
4922}
4923
4924static void sigchld_handler(int signal)
4925{
4926 waitpid(-1, NULL, WNOHANG);
4927}
4928
4929static void sighandler_setup(void)
4930{
4931 struct sigaction act;
4932
4933 memset(&act, 0, sizeof(act));
4934 act.sa_handler = termsig_handler;
4935 sigaction(SIGINT, &act, NULL);
4936 sigaction(SIGHUP, &act, NULL);
4937 sigaction(SIGTERM, &act, NULL);
4938
4939 act.sa_handler = sigchld_handler;
4940 act.sa_flags = SA_NOCLDSTOP;
4941 sigaction(SIGCHLD, &act, NULL);
4942}
4943
4944#endif
4945
4946#ifdef _WIN32
4947/* Look for support files in the same directory as the executable. */
4948static char *find_datadir(const char *argv0)
4949{
4950 char *p;
4951 char buf[MAX_PATH];
4952 DWORD len;
4953
4954 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4955 if (len == 0) {
4956 return NULL;
4957 }
4958
4959 buf[len] = 0;
4960 p = buf + len - 1;
4961 while (p != buf && *p != '\\')
4962 p--;
4963 *p = 0;
4964 if (access(buf, R_OK) == 0) {
4965 return qemu_strdup(buf);
4966 }
4967 return NULL;
4968}
4969#else /* !_WIN32 */
4970
4971/* Find a likely location for support files using the location of the binary.
4972 For installed binaries this will be "$bindir/../share/qemu". When
4973 running from the build tree this will be "$bindir/../pc-bios". */
4974#define SHARE_SUFFIX "/share/qemu"
4975#define BUILD_SUFFIX "/pc-bios"
4976static char *find_datadir(const char *argv0)
4977{
4978 char *dir;
4979 char *p = NULL;
4980 char *res;
4981#ifdef PATH_MAX
4982 char buf[PATH_MAX];
4983#endif
4984 size_t max_len;
4985
4986#if defined(__linux__)
4987 {
4988 int len;
4989 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4990 if (len > 0) {
4991 buf[len] = 0;
4992 p = buf;
4993 }
4994 }
4995#elif defined(__FreeBSD__)
4996 {
4997 int len;
4998 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4999 if (len > 0) {
5000 buf[len] = 0;
5001 p = buf;
5002 }
5003 }
5004#endif
5005 /* If we don't have any way of figuring out the actual executable
5006 location then try argv[0]. */
5007 if (!p) {
5008#ifdef PATH_MAX
5009 p = buf;
5010#endif
5011 p = realpath(argv0, p);
5012 if (!p) {
5013 return NULL;
5014 }
5015 }
5016 dir = dirname(p);
5017 dir = dirname(dir);
5018
5019 max_len = strlen(dir) +
5020 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
5021 res = qemu_mallocz(max_len);
5022 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5023 if (access(res, R_OK)) {
5024 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5025 if (access(res, R_OK)) {
5026 qemu_free(res);
5027 res = NULL;
5028 }
5029 }
5030#ifndef PATH_MAX
5031 free(p);
5032#endif
5033 return res;
5034}
5035#undef SHARE_SUFFIX
5036#undef BUILD_SUFFIX
5037#endif
5038
5039char *qemu_find_file(int type, const char *name)
5040{
5041 int len;
5042 const char *subdir;
5043 char *buf;
5044
5045 /* If name contains path separators then try it as a straight path. */
5046 if ((strchr(name, '/') || strchr(name, '\\'))
5047 && access(name, R_OK) == 0) {
5048 return strdup(name);
5049 }
5050 switch (type) {
5051 case QEMU_FILE_TYPE_BIOS:
5052 subdir = "";
5053 break;
5054 case QEMU_FILE_TYPE_KEYMAP:
5055 subdir = "keymaps/";
5056 break;
5057 default:
5058 abort();
5059 }
5060 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5061 buf = qemu_mallocz(len);
5062 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5063 if (access(buf, R_OK)) {
5064 qemu_free(buf);
5065 return NULL;
5066 }
5067 return buf;
5068}
5069
5070int main(int argc, char **argv, char **envp)
5071{
5072 const char *gdbstub_dev = NULL;
5073 uint32_t boot_devices_bitmap = 0;
5074 int i;
5075 int snapshot, linux_boot, net_boot;
5076 const char *initrd_filename;
5077 const char *kernel_filename, *kernel_cmdline;
5078 const char *boot_devices = "";
5079 DisplayState *ds;
5080 DisplayChangeListener *dcl;
5081 int cyls, heads, secs, translation;
5082 const char *net_clients[MAX_NET_CLIENTS];
5083 int nb_net_clients;
5084 const char *bt_opts[MAX_BT_CMDLINE];
5085 int nb_bt_opts;
5086 int hda_index;
5087 int optind;
5088 const char *r, *optarg;
5089 CharDriverState *monitor_hd = NULL;
5090 const char *monitor_device;
5091 const char *serial_devices[MAX_SERIAL_PORTS];
5092 int serial_device_index;
5093 const char *parallel_devices[MAX_PARALLEL_PORTS];
5094 int parallel_device_index;
5095 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5096 int virtio_console_index;
5097 const char *loadvm = NULL;
5098 QEMUMachine *machine;
5099 const char *cpu_model;
5100 const char *usb_devices[MAX_USB_CMDLINE];
5101 int usb_devices_index;
5102#ifndef _WIN32
5103 int fds[2];
5104#endif
5105 int tb_size;
5106 const char *pid_file = NULL;
5107 const char *incoming = NULL;
5108#ifndef _WIN32
5109 int fd = 0;
5110 struct passwd *pwd = NULL;
5111 const char *chroot_dir = NULL;
5112 const char *run_as = NULL;
5113#endif
5114 CPUState *env;
5115 int show_vnc_port = 0;
5116
5117 qemu_cache_utils_init(envp);
5118
5119 LIST_INIT (&vm_change_state_head);
5120#ifndef _WIN32
5121 {
5122 struct sigaction act;
5123 sigfillset(&act.sa_mask);
5124 act.sa_flags = 0;
5125 act.sa_handler = SIG_IGN;
5126 sigaction(SIGPIPE, &act, NULL);
5127 }
5128#else
5129 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5130 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5131 QEMU to run on a single CPU */
5132 {
5133 HANDLE h;
5134 DWORD mask, smask;
5135 int i;
5136 h = GetCurrentProcess();
5137 if (GetProcessAffinityMask(h, &mask, &smask)) {
5138 for(i = 0; i < 32; i++) {
5139 if (mask & (1 << i))
5140 break;
5141 }
5142 if (i != 32) {
5143 mask = 1 << i;
5144 SetProcessAffinityMask(h, mask);
5145 }
5146 }
5147 }
5148#endif
5149
5150 module_call_init(MODULE_INIT_MACHINE);
5151 machine = find_default_machine();
5152 cpu_model = NULL;
5153 initrd_filename = NULL;
5154 ram_size = 0;
5155 snapshot = 0;
5156 kernel_filename = NULL;
5157 kernel_cmdline = "";
5158 cyls = heads = secs = 0;
5159 translation = BIOS_ATA_TRANSLATION_AUTO;
5160 monitor_device = "vc:80Cx24C";
5161
5162 serial_devices[0] = "vc:80Cx24C";
5163 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5164 serial_devices[i] = NULL;
5165 serial_device_index = 0;
5166
5167 parallel_devices[0] = "vc:80Cx24C";
5168 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5169 parallel_devices[i] = NULL;
5170 parallel_device_index = 0;
5171
5172 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5173 virtio_consoles[i] = NULL;
5174 virtio_console_index = 0;
5175
5176 for (i = 0; i < MAX_NODES; i++) {
5177 node_mem[i] = 0;
5178 node_cpumask[i] = 0;
5179 }
5180
5181 usb_devices_index = 0;
5182
5183 nb_net_clients = 0;
5184 nb_bt_opts = 0;
5185 nb_drives = 0;
5186 nb_drives_opt = 0;
5187 nb_numa_nodes = 0;
5188 hda_index = -1;
5189
5190 nb_nics = 0;
5191
5192 tb_size = 0;
5193 autostart= 1;
5194
5195 register_watchdogs();
5196
5197 optind = 1;
5198 for(;;) {
5199 if (optind >= argc)
5200 break;
5201 r = argv[optind];
5202 if (r[0] != '-') {
5203 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5204 } else {
5205 const QEMUOption *popt;
5206
5207 optind++;
5208 /* Treat --foo the same as -foo. */
5209 if (r[1] == '-')
5210 r++;
5211 popt = qemu_options;
5212 for(;;) {
5213 if (!popt->name) {
5214 fprintf(stderr, "%s: invalid option -- '%s'\n",
5215 argv[0], r);
5216 exit(1);
5217 }
5218 if (!strcmp(popt->name, r + 1))
5219 break;
5220 popt++;
5221 }
5222 if (popt->flags & HAS_ARG) {
5223 if (optind >= argc) {
5224 fprintf(stderr, "%s: option '%s' requires an argument\n",
5225 argv[0], r);
5226 exit(1);
5227 }
5228 optarg = argv[optind++];
5229 } else {
5230 optarg = NULL;
5231 }
5232
5233 switch(popt->index) {
5234 case QEMU_OPTION_M:
5235 machine = find_machine(optarg);
5236 if (!machine) {
5237 QEMUMachine *m;
5238 printf("Supported machines are:\n");
5239 for(m = first_machine; m != NULL; m = m->next) {
5240 printf("%-10s %s%s\n",
5241 m->name, m->desc,
5242 m->is_default ? " (default)" : "");
5243 }
5244 exit(*optarg != '?');
5245 }
5246 break;
5247 case QEMU_OPTION_cpu:
5248 /* hw initialization will check this */
5249 if (*optarg == '?') {
5250/* XXX: implement xxx_cpu_list for targets that still miss it */
5251#if defined(cpu_list)
5252 cpu_list(stdout, &fprintf);
5253#endif
5254 exit(0);
5255 } else {
5256 cpu_model = optarg;
5257 }
5258 break;
5259 case QEMU_OPTION_initrd:
5260 initrd_filename = optarg;
5261 break;
5262 case QEMU_OPTION_hda:
5263 if (cyls == 0)
5264 hda_index = drive_add(optarg, HD_ALIAS, 0);
5265 else
5266 hda_index = drive_add(optarg, HD_ALIAS
5267 ",cyls=%d,heads=%d,secs=%d%s",
5268 0, cyls, heads, secs,
5269 translation == BIOS_ATA_TRANSLATION_LBA ?
5270 ",trans=lba" :
5271 translation == BIOS_ATA_TRANSLATION_NONE ?
5272 ",trans=none" : "");
5273 break;
5274 case QEMU_OPTION_hdb:
5275 case QEMU_OPTION_hdc:
5276 case QEMU_OPTION_hdd:
5277 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5278 break;
5279 case QEMU_OPTION_drive:
5280 drive_add(NULL, "%s", optarg);
5281 break;
5282 case QEMU_OPTION_mtdblock:
5283 drive_add(optarg, MTD_ALIAS);
5284 break;
5285 case QEMU_OPTION_sd:
5286 drive_add(optarg, SD_ALIAS);
5287 break;
5288 case QEMU_OPTION_pflash:
5289 drive_add(optarg, PFLASH_ALIAS);
5290 break;
5291 case QEMU_OPTION_snapshot:
5292 snapshot = 1;
5293 break;
5294 case QEMU_OPTION_hdachs:
5295 {
5296 const char *p;
5297 p = optarg;
5298 cyls = strtol(p, (char **)&p, 0);
5299 if (cyls < 1 || cyls > 16383)
5300 goto chs_fail;
5301 if (*p != ',')
5302 goto chs_fail;
5303 p++;
5304 heads = strtol(p, (char **)&p, 0);
5305 if (heads < 1 || heads > 16)
5306 goto chs_fail;
5307 if (*p != ',')
5308 goto chs_fail;
5309 p++;
5310 secs = strtol(p, (char **)&p, 0);
5311 if (secs < 1 || secs > 63)
5312 goto chs_fail;
5313 if (*p == ',') {
5314 p++;
5315 if (!strcmp(p, "none"))
5316 translation = BIOS_ATA_TRANSLATION_NONE;
5317 else if (!strcmp(p, "lba"))
5318 translation = BIOS_ATA_TRANSLATION_LBA;
5319 else if (!strcmp(p, "auto"))
5320 translation = BIOS_ATA_TRANSLATION_AUTO;
5321 else
5322 goto chs_fail;
5323 } else if (*p != '\0') {
5324 chs_fail:
5325 fprintf(stderr, "qemu: invalid physical CHS format\n");
5326 exit(1);
5327 }
5328 if (hda_index != -1)
5329 snprintf(drives_opt[hda_index].opt,
5330 sizeof(drives_opt[hda_index].opt),
5331 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5332 0, cyls, heads, secs,
5333 translation == BIOS_ATA_TRANSLATION_LBA ?
5334 ",trans=lba" :
5335 translation == BIOS_ATA_TRANSLATION_NONE ?
5336 ",trans=none" : "");
5337 }
5338 break;
5339 case QEMU_OPTION_numa:
5340 if (nb_numa_nodes >= MAX_NODES) {
5341 fprintf(stderr, "qemu: too many NUMA nodes\n");
5342 exit(1);
5343 }
5344 numa_add(optarg);
5345 break;
5346 case QEMU_OPTION_nographic:
5347 display_type = DT_NOGRAPHIC;
5348 break;
5349#ifdef CONFIG_CURSES
5350 case QEMU_OPTION_curses:
5351 display_type = DT_CURSES;
5352 break;
5353#endif
5354 case QEMU_OPTION_portrait:
5355 graphic_rotate = 1;
5356 break;
5357 case QEMU_OPTION_kernel:
5358 kernel_filename = optarg;
5359 break;
5360 case QEMU_OPTION_append:
5361 kernel_cmdline = optarg;
5362 break;
5363 case QEMU_OPTION_cdrom:
5364 drive_add(optarg, CDROM_ALIAS);
5365 break;
5366 case QEMU_OPTION_boot:
5367 boot_devices = optarg;
5368 /* We just do some generic consistency checks */
5369 {
5370 /* Could easily be extended to 64 devices if needed */
5371 const char *p;
5372
5373 boot_devices_bitmap = 0;
5374 for (p = boot_devices; *p != '\0'; p++) {
5375 /* Allowed boot devices are:
5376 * a b : floppy disk drives
5377 * c ... f : IDE disk drives
5378 * g ... m : machine implementation dependant drives
5379 * n ... p : network devices
5380 * It's up to each machine implementation to check
5381 * if the given boot devices match the actual hardware
5382 * implementation and firmware features.
5383 */
5384 if (*p < 'a' || *p > 'q') {
5385 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5386 exit(1);
5387 }
5388 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5389 fprintf(stderr,
5390 "Boot device '%c' was given twice\n",*p);
5391 exit(1);
5392 }
5393 boot_devices_bitmap |= 1 << (*p - 'a');
5394 }
5395 }
5396 break;
5397 case QEMU_OPTION_fda:
5398 case QEMU_OPTION_fdb:
5399 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5400 break;
5401#ifdef TARGET_I386
5402 case QEMU_OPTION_no_fd_bootchk:
5403 fd_bootchk = 0;
5404 break;
5405#endif
5406 case QEMU_OPTION_net:
5407 if (nb_net_clients >= MAX_NET_CLIENTS) {
5408 fprintf(stderr, "qemu: too many network clients\n");
5409 exit(1);
5410 }
5411 net_clients[nb_net_clients] = optarg;
5412 nb_net_clients++;
5413 break;
5414#ifdef CONFIG_SLIRP
5415 case QEMU_OPTION_tftp:
5416 tftp_prefix = optarg;
5417 break;
5418 case QEMU_OPTION_bootp:
5419 bootp_filename = optarg;
5420 break;
5421#if 0 /* ANDROID disabled */
5422#ifndef _WIN32
5423 case QEMU_OPTION_smb:
5424 net_slirp_smb(optarg);
5425 break;
5426#endif
5427#endif /* ANDROID */
5428 case QEMU_OPTION_redir:
5429 net_slirp_redir(NULL, optarg, NULL);
5430 break;
5431#endif
5432 case QEMU_OPTION_bt:
5433 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5434 fprintf(stderr, "qemu: too many bluetooth options\n");
5435 exit(1);
5436 }
5437 bt_opts[nb_bt_opts++] = optarg;
5438 break;
5439#ifdef HAS_AUDIO
5440 case QEMU_OPTION_audio_help:
5441 AUD_help ();
5442 exit (0);
5443 break;
5444 case QEMU_OPTION_soundhw:
5445 select_soundhw (optarg);
5446 break;
5447#endif
5448 case QEMU_OPTION_h:
5449 qemu_help(0);
5450 break;
5451 case QEMU_OPTION_version:
5452 version();
5453 exit(0);
5454 break;
5455 case QEMU_OPTION_m: {
5456 uint64_t value;
5457 char *ptr;
5458
5459 value = strtoul(optarg, &ptr, 10);
5460 switch (*ptr) {
5461 case 0: case 'M': case 'm':
5462 value <<= 20;
5463 break;
5464 case 'G': case 'g':
5465 value <<= 30;
5466 break;
5467 default:
5468 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5469 exit(1);
5470 }
5471
5472 /* On 32-bit hosts, QEMU is limited by virtual address space */
5473 if (value > (2047 << 20)
5474#ifndef CONFIG_KQEMU
5475 && HOST_LONG_BITS == 32
5476#endif
5477 ) {
5478 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5479 exit(1);
5480 }
5481 if (value != (uint64_t)(ram_addr_t)value) {
5482 fprintf(stderr, "qemu: ram size too large\n");
5483 exit(1);
5484 }
5485 ram_size = value;
5486 break;
5487 }
5488 case QEMU_OPTION_d:
5489 {
5490 int mask;
5491 const CPULogItem *item;
5492
5493 mask = cpu_str_to_log_mask(optarg);
5494 if (!mask) {
5495 printf("Log items (comma separated):\n");
5496 for(item = cpu_log_items; item->mask != 0; item++) {
5497 printf("%-10s %s\n", item->name, item->help);
5498 }
5499 exit(1);
5500 }
5501 cpu_set_log(mask);
5502 }
5503 break;
5504 case QEMU_OPTION_s:
5505 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5506 break;
5507 case QEMU_OPTION_gdb:
5508 gdbstub_dev = optarg;
5509 break;
5510 case QEMU_OPTION_L:
5511 data_dir = optarg;
5512 break;
5513 case QEMU_OPTION_bios:
5514 bios_name = optarg;
5515 break;
5516 case QEMU_OPTION_singlestep:
5517 singlestep = 1;
5518 break;
5519 case QEMU_OPTION_S:
5520#if 0 /* ANDROID */
5521 fprintf(stderr, "Sorry, stopped launch is not supported in the Android emulator\n" );
5522 exit(1);
5523#endif
5524 autostart = 0;
5525 break;
5526#ifndef _WIN32
5527 case QEMU_OPTION_k:
5528 keyboard_layout = optarg;
5529 break;
5530#endif
5531 case QEMU_OPTION_localtime:
5532 rtc_utc = 0;
5533 break;
5534 case QEMU_OPTION_vga:
5535 select_vgahw (optarg);
5536 break;
5537#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5538 case QEMU_OPTION_g:
5539 {
5540 const char *p;
5541 int w, h, depth;
5542 p = optarg;
5543 w = strtol(p, (char **)&p, 10);
5544 if (w <= 0) {
5545 graphic_error:
5546 fprintf(stderr, "qemu: invalid resolution or depth\n");
5547 exit(1);
5548 }
5549 if (*p != 'x')
5550 goto graphic_error;
5551 p++;
5552 h = strtol(p, (char **)&p, 10);
5553 if (h <= 0)
5554 goto graphic_error;
5555 if (*p == 'x') {
5556 p++;
5557 depth = strtol(p, (char **)&p, 10);
5558 if (depth != 8 && depth != 15 && depth != 16 &&
5559 depth != 24 && depth != 32)
5560 goto graphic_error;
5561 } else if (*p == '\0') {
5562 depth = graphic_depth;
5563 } else {
5564 goto graphic_error;
5565 }
5566
5567 graphic_width = w;
5568 graphic_height = h;
5569 graphic_depth = depth;
5570 }
5571 break;
5572#endif
5573 case QEMU_OPTION_echr:
5574 {
5575 char *r;
5576 term_escape_char = strtol(optarg, &r, 0);
5577 if (r == optarg)
5578 printf("Bad argument to echr\n");
5579 break;
5580 }
5581 case QEMU_OPTION_monitor:
5582 monitor_device = optarg;
5583 break;
5584 case QEMU_OPTION_serial:
5585 if (serial_device_index >= MAX_SERIAL_PORTS) {
5586 fprintf(stderr, "qemu: too many serial ports\n");
5587 exit(1);
5588 }
5589 serial_devices[serial_device_index] = optarg;
5590 serial_device_index++;
5591 break;
5592 case QEMU_OPTION_watchdog:
5593 i = select_watchdog(optarg);
5594 if (i > 0)
5595 exit (i == 1 ? 1 : 0);
5596 break;
5597 case QEMU_OPTION_watchdog_action:
5598 if (select_watchdog_action(optarg) == -1) {
5599 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5600 exit(1);
5601 }
5602 break;
5603 case QEMU_OPTION_virtiocon:
5604 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5605 fprintf(stderr, "qemu: too many virtio consoles\n");
5606 exit(1);
5607 }
5608 virtio_consoles[virtio_console_index] = optarg;
5609 virtio_console_index++;
5610 break;
5611 case QEMU_OPTION_parallel:
5612 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5613 fprintf(stderr, "qemu: too many parallel ports\n");
5614 exit(1);
5615 }
5616 parallel_devices[parallel_device_index] = optarg;
5617 parallel_device_index++;
5618 break;
5619 case QEMU_OPTION_loadvm:
5620 loadvm = optarg;
5621 break;
5622 case QEMU_OPTION_full_screen:
5623 full_screen = 1;
5624 break;
5625#ifdef CONFIG_SDL
5626 case QEMU_OPTION_no_frame:
5627 no_frame = 1;
5628 break;
5629 case QEMU_OPTION_alt_grab:
5630 alt_grab = 1;
5631 break;
5632 case QEMU_OPTION_no_quit:
5633 no_quit = 1;
5634 break;
5635 case QEMU_OPTION_sdl:
5636 display_type = DT_SDL;
5637 break;
5638#endif
5639 case QEMU_OPTION_pidfile:
5640 pid_file = optarg;
5641 break;
5642#ifdef TARGET_I386
5643 case QEMU_OPTION_win2k_hack:
5644 win2k_install_hack = 1;
5645 break;
5646 case QEMU_OPTION_rtc_td_hack:
5647 rtc_td_hack = 1;
5648 break;
5649 case QEMU_OPTION_acpitable:
5650 if(acpi_table_add(optarg) < 0) {
5651 fprintf(stderr, "Wrong acpi table provided\n");
5652 exit(1);
5653 }
5654 break;
5655 case QEMU_OPTION_smbios:
5656 if(smbios_entry_add(optarg) < 0) {
5657 fprintf(stderr, "Wrong smbios provided\n");
5658 exit(1);
5659 }
5660 break;
5661#endif
5662#ifdef CONFIG_KQEMU
5663 case QEMU_OPTION_no_kqemu:
5664 kqemu_allowed = 0;
5665 break;
5666 case QEMU_OPTION_kernel_kqemu:
5667 kqemu_allowed = 2;
5668 break;
5669#endif
5670#ifdef CONFIG_KVM
5671 case QEMU_OPTION_enable_kvm:
5672 kvm_allowed = 1;
5673#ifdef CONFIG_KQEMU
5674 kqemu_allowed = 0;
5675#endif
5676 break;
5677#endif
5678 case QEMU_OPTION_usb:
5679 usb_enabled = 1;
5680 break;
5681 case QEMU_OPTION_usbdevice:
5682 usb_enabled = 1;
5683 if (usb_devices_index >= MAX_USB_CMDLINE) {
5684 fprintf(stderr, "Too many USB devices\n");
5685 exit(1);
5686 }
5687 usb_devices[usb_devices_index] = optarg;
5688 usb_devices_index++;
5689 break;
5690 case QEMU_OPTION_smp:
5691 smp_cpus = atoi(optarg);
5692 if (smp_cpus < 1) {
5693 fprintf(stderr, "Invalid number of CPUs\n");
5694 exit(1);
5695 }
5696 break;
5697 case QEMU_OPTION_vnc:
5698 display_type = DT_VNC;
5699 vnc_display = optarg;
5700 break;
5701#ifdef TARGET_I386
5702 case QEMU_OPTION_no_acpi:
5703 acpi_enabled = 0;
5704 break;
5705 case QEMU_OPTION_no_hpet:
5706 no_hpet = 1;
5707 break;
5708 case QEMU_OPTION_no_virtio_balloon:
5709 no_virtio_balloon = 1;
5710 break;
5711#endif
5712 case QEMU_OPTION_no_reboot:
5713 no_reboot = 1;
5714 break;
5715 case QEMU_OPTION_no_shutdown:
5716 no_shutdown = 1;
5717 break;
5718 case QEMU_OPTION_show_cursor:
5719 cursor_hide = 0;
5720 break;
5721 case QEMU_OPTION_uuid:
5722 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5723 fprintf(stderr, "Fail to parse UUID string."
5724 " Wrong format.\n");
5725 exit(1);
5726 }
5727 break;
5728#ifndef _WIN32
5729 case QEMU_OPTION_daemonize:
5730 daemonize = 1;
5731 break;
5732#endif
5733 case QEMU_OPTION_option_rom:
5734 if (nb_option_roms >= MAX_OPTION_ROMS) {
5735 fprintf(stderr, "Too many option ROMs\n");
5736 exit(1);
5737 }
5738 option_rom[nb_option_roms] = optarg;
5739 nb_option_roms++;
5740 break;
5741#if defined(TARGET_ARM) || defined(TARGET_M68K)
5742 case QEMU_OPTION_semihosting:
5743 semihosting_enabled = 1;
5744 break;
5745#endif
5746 case QEMU_OPTION_name:
5747 qemu_name = optarg;
5748 break;
5749#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5750 case QEMU_OPTION_prom_env:
5751 if (nb_prom_envs >= MAX_PROM_ENVS) {
5752 fprintf(stderr, "Too many prom variables\n");
5753 exit(1);
5754 }
5755 prom_envs[nb_prom_envs] = optarg;
5756 nb_prom_envs++;
5757 break;
5758#endif
5759#ifdef TARGET_ARM
5760 case QEMU_OPTION_old_param:
5761 old_param = 1;
5762 break;
5763#endif
5764 case QEMU_OPTION_clock:
5765 configure_alarms(optarg);
5766 break;
5767 case QEMU_OPTION_startdate:
5768 {
5769 struct tm tm;
5770 time_t rtc_start_date;
5771 if (!strcmp(optarg, "now")) {
5772 rtc_date_offset = -1;
5773 } else {
5774 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5775 &tm.tm_year,
5776 &tm.tm_mon,
5777 &tm.tm_mday,
5778 &tm.tm_hour,
5779 &tm.tm_min,
5780 &tm.tm_sec) == 6) {
5781 /* OK */
5782 } else if (sscanf(optarg, "%d-%d-%d",
5783 &tm.tm_year,
5784 &tm.tm_mon,
5785 &tm.tm_mday) == 3) {
5786 tm.tm_hour = 0;
5787 tm.tm_min = 0;
5788 tm.tm_sec = 0;
5789 } else {
5790 goto date_fail;
5791 }
5792 tm.tm_year -= 1900;
5793 tm.tm_mon--;
5794 rtc_start_date = mktimegm(&tm);
5795 if (rtc_start_date == -1) {
5796 date_fail:
5797 fprintf(stderr, "Invalid date format. Valid format are:\n"
5798 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5799 exit(1);
5800 }
5801 rtc_date_offset = time(NULL) - rtc_start_date;
5802 }
5803 }
5804 break;
5805 case QEMU_OPTION_tb_size:
5806 tb_size = strtol(optarg, NULL, 0);
5807 if (tb_size < 0)
5808 tb_size = 0;
5809 break;
5810 case QEMU_OPTION_icount:
5811 use_icount = 1;
5812 if (strcmp(optarg, "auto") == 0) {
5813 icount_time_shift = -1;
5814 } else {
5815 icount_time_shift = strtol(optarg, NULL, 0);
5816 }
5817 break;
5818 case QEMU_OPTION_incoming:
5819 incoming = optarg;
5820 break;
5821#ifndef _WIN32
5822 case QEMU_OPTION_chroot:
5823 chroot_dir = optarg;
5824 break;
5825 case QEMU_OPTION_runas:
5826 run_as = optarg;
5827 break;
5828#endif
5829#ifdef CONFIG_XEN
5830 case QEMU_OPTION_xen_domid:
5831 xen_domid = atoi(optarg);
5832 break;
5833 case QEMU_OPTION_xen_create:
5834 xen_mode = XEN_CREATE;
5835 break;
5836 case QEMU_OPTION_xen_attach:
5837 xen_mode = XEN_ATTACH;
5838 break;
5839#endif
5840
5841
5842 case QEMU_OPTION_mic:
5843 audio_input_source = (char*)optarg;
5844 break;
5845#ifdef CONFIG_TRACE
5846 case QEMU_OPTION_trace_file:
5847 trace_filename = optarg;
5848 tracing = 1;
5849 break;
5850#if 0
5851 case QEMU_OPTION_trace_miss:
5852 trace_cache_miss = 1;
5853 break;
5854 case QEMU_OPTION_trace_addr:
5855 trace_all_addr = 1;
5856 break;
5857#endif
5858 case QEMU_OPTION_tracing:
5859 if (strcmp(optarg, "off") == 0)
5860 tracing = 0;
5861 else if (strcmp(optarg, "on") == 0 && trace_filename)
5862 tracing = 1;
5863 else {
5864 fprintf(stderr, "Unexpected option to -tracing ('%s')\n",
5865 optarg);
5866 exit(1);
5867 }
5868 break;
5869#if 0
5870 case QEMU_OPTION_dcache_load_miss:
5871 dcache_load_miss_penalty = atoi(optarg);
5872 break;
5873 case QEMU_OPTION_dcache_store_miss:
5874 dcache_store_miss_penalty = atoi(optarg);
5875 break;
5876#endif
5877#endif
5878#ifdef CONFIG_NAND
5879 case QEMU_OPTION_nand:
5880 nand_add_dev(optarg);
5881 break;
5882#endif
5883 }
5884 }
5885 }
5886
5887 /* If no data_dir is specified then try to find it relative to the
5888 executable path. */
5889 if (!data_dir) {
5890 data_dir = find_datadir(argv[0]);
5891 }
5892 /* If all else fails use the install patch specified when building. */
5893 if (!data_dir) {
5894 data_dir = CONFIG_QEMU_SHAREDIR;
5895 }
5896
5897#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5898 if (kvm_allowed && kqemu_allowed) {
5899 fprintf(stderr,
5900 "You can not enable both KVM and kqemu at the same time\n");
5901 exit(1);
5902 }
5903#endif
5904
5905 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5906 if (smp_cpus > machine->max_cpus) {
5907 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5908 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5909 machine->max_cpus);
5910 exit(1);
5911 }
5912
5913 if (display_type == DT_NOGRAPHIC) {
5914 if (serial_device_index == 0)
5915 serial_devices[0] = "stdio";
5916 if (parallel_device_index == 0)
5917 parallel_devices[0] = "null";
5918 if (strncmp(monitor_device, "vc", 2) == 0)
5919 monitor_device = "stdio";
5920 }
5921
5922#ifndef _WIN32
5923 if (daemonize) {
5924 pid_t pid;
5925
5926 if (pipe(fds) == -1)
5927 exit(1);
5928
5929 pid = fork();
5930 if (pid > 0) {
5931 uint8_t status;
5932 ssize_t len;
5933
5934 close(fds[1]);
5935
5936 again:
5937 len = read(fds[0], &status, 1);
5938 if (len == -1 && (errno == EINTR))
5939 goto again;
5940
5941 if (len != 1)
5942 exit(1);
5943 else if (status == 1) {
5944 fprintf(stderr, "Could not acquire pidfile\n");
5945 exit(1);
5946 } else
5947 exit(0);
5948 } else if (pid < 0)
5949 exit(1);
5950
5951 setsid();
5952
5953 pid = fork();
5954 if (pid > 0)
5955 exit(0);
5956 else if (pid < 0)
5957 exit(1);
5958
5959 umask(027);
5960
5961 signal(SIGTSTP, SIG_IGN);
5962 signal(SIGTTOU, SIG_IGN);
5963 signal(SIGTTIN, SIG_IGN);
5964 }
5965
5966 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5967 if (daemonize) {
5968 uint8_t status = 1;
5969 write(fds[1], &status, 1);
5970 } else
5971 fprintf(stderr, "Could not acquire pid file\n");
5972 exit(1);
5973 }
5974#endif
5975
5976#ifdef CONFIG_KQEMU
5977 if (smp_cpus > 1)
5978 kqemu_allowed = 0;
5979#endif
5980 if (qemu_init_main_loop()) {
5981 fprintf(stderr, "qemu_init_main_loop failed\n");
5982 exit(1);
5983 }
5984 linux_boot = (kernel_filename != NULL);
5985 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5986
5987 if (!linux_boot && *kernel_cmdline != '\0') {
5988 fprintf(stderr, "-append only allowed with -kernel option\n");
5989 exit(1);
5990 }
5991
5992 if (!linux_boot && initrd_filename != NULL) {
5993 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5994 exit(1);
5995 }
5996
5997 /* boot to floppy or the default cd if no hard disk defined yet */
5998 if (!boot_devices[0]) {
5999 boot_devices = "cad";
6000 }
6001 setvbuf(stdout, NULL, _IOLBF, 0);
6002
6003 init_timers();
6004 if (init_timer_alarm() < 0) {
6005 fprintf(stderr, "could not initialize alarm timer\n");
6006 exit(1);
6007 }
6008 if (use_icount && icount_time_shift < 0) {
6009 use_icount = 2;
6010 /* 125MIPS seems a reasonable initial guess at the guest speed.
6011 It will be corrected fairly quickly anyway. */
6012 icount_time_shift = 3;
6013 init_icount_adjust();
6014 }
6015
6016#ifdef _WIN32
6017 socket_init();
6018#endif
6019
6020 /* init network clients */
6021 if (nb_net_clients == 0) {
6022 /* if no clients, we use a default config */
6023 net_clients[nb_net_clients++] = "nic";
6024#ifdef CONFIG_SLIRP
6025 net_clients[nb_net_clients++] = "user";
6026#endif
6027 }
6028
6029 for(i = 0;i < nb_net_clients; i++) {
6030 if (net_client_parse(net_clients[i]) < 0)
6031 exit(1);
6032 }
6033 net_client_check();
6034
6035#ifdef TARGET_I386
6036 /* XXX: this should be moved in the PC machine instantiation code */
6037 if (net_boot != 0) {
6038 int netroms = 0;
6039 for (i = 0; i < nb_nics && i < 4; i++) {
6040 const char *model = nd_table[i].model;
6041 char buf[1024];
6042 char *filename;
6043 if (net_boot & (1 << i)) {
6044 if (model == NULL)
6045 model = "ne2k_pci";
6046 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
6047 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
6048 if (filename && get_image_size(filename) > 0) {
6049 if (nb_option_roms >= MAX_OPTION_ROMS) {
6050 fprintf(stderr, "Too many option ROMs\n");
6051 exit(1);
6052 }
6053 option_rom[nb_option_roms] = qemu_strdup(buf);
6054 nb_option_roms++;
6055 netroms++;
6056 }
6057 if (filename) {
6058 qemu_free(filename);
6059 }
6060 }
6061 }
6062 if (netroms == 0) {
6063 fprintf(stderr, "No valid PXE rom found for network device\n");
6064 exit(1);
6065 }
6066 }
6067#endif
6068
6069 /* init the bluetooth world */
6070 for (i = 0; i < nb_bt_opts; i++)
6071 if (bt_parse(bt_opts[i]))
6072 exit(1);
6073
6074 /* init the memory */
6075 if (ram_size == 0)
6076 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6077
6078#ifdef CONFIG_KQEMU
6079 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6080 guest ram allocation. It needs to go away. */
6081 if (kqemu_allowed) {
6082 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6083 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6084 if (!kqemu_phys_ram_base) {
6085 fprintf(stderr, "Could not allocate physical memory\n");
6086 exit(1);
6087 }
6088 }
6089#endif
6090
6091 /* init the dynamic translator */
6092 cpu_exec_init_all(tb_size * 1024 * 1024);
6093
6094 bdrv_init();
6095
6096 /* we always create the cdrom drive, even if no disk is there */
6097
6098 if (nb_drives_opt < MAX_DRIVES)
6099 drive_add(NULL, CDROM_ALIAS);
6100
6101 /* we always create at least one floppy */
6102
6103 if (nb_drives_opt < MAX_DRIVES)
6104 drive_add(NULL, FD_ALIAS, 0);
6105
6106 /* we always create one sd slot, even if no card is in it */
6107
6108 if (nb_drives_opt < MAX_DRIVES)
6109 drive_add(NULL, SD_ALIAS);
6110
6111 /* open the virtual block devices */
6112
6113 for(i = 0; i < nb_drives_opt; i++)
6114 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6115 exit(1);
6116
6117 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6118 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6119
6120#ifndef _WIN32
6121 /* must be after terminal init, SDL library changes signal handlers */
6122 sighandler_setup();
6123#endif
6124
6125 /* Maintain compatibility with multiple stdio monitors */
6126 if (!strcmp(monitor_device,"stdio")) {
6127 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6128 const char *devname = serial_devices[i];
6129 if (devname && !strcmp(devname,"mon:stdio")) {
6130 monitor_device = NULL;
6131 break;
6132 } else if (devname && !strcmp(devname,"stdio")) {
6133 monitor_device = NULL;
6134 serial_devices[i] = "mon:stdio";
6135 break;
6136 }
6137 }
6138 }
6139
6140 if (nb_numa_nodes > 0) {
6141 int i;
6142
6143 if (nb_numa_nodes > smp_cpus) {
6144 nb_numa_nodes = smp_cpus;
6145 }
6146
6147 /* If no memory size if given for any node, assume the default case
6148 * and distribute the available memory equally across all nodes
6149 */
6150 for (i = 0; i < nb_numa_nodes; i++) {
6151 if (node_mem[i] != 0)
6152 break;
6153 }
6154 if (i == nb_numa_nodes) {
6155 uint64_t usedmem = 0;
6156
6157 /* On Linux, the each node's border has to be 8MB aligned,
6158 * the final node gets the rest.
6159 */
6160 for (i = 0; i < nb_numa_nodes - 1; i++) {
6161 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6162 usedmem += node_mem[i];
6163 }
6164 node_mem[i] = ram_size - usedmem;
6165 }
6166
6167 for (i = 0; i < nb_numa_nodes; i++) {
6168 if (node_cpumask[i] != 0)
6169 break;
6170 }
6171 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6172 * must cope with this anyway, because there are BIOSes out there in
6173 * real machines which also use this scheme.
6174 */
6175 if (i == nb_numa_nodes) {
6176 for (i = 0; i < smp_cpus; i++) {
6177 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6178 }
6179 }
6180 }
6181
6182 if (kvm_enabled()) {
6183 int ret;
6184
6185 ret = kvm_init(smp_cpus);
6186 if (ret < 0) {
6187 fprintf(stderr, "failed to initialize KVM\n");
6188 exit(1);
6189 }
6190 }
6191
6192 if (monitor_device) {
6193 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6194 if (!monitor_hd) {
6195 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6196 exit(1);
6197 }
6198 }
6199
6200 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6201 const char *devname = serial_devices[i];
6202 if (devname && strcmp(devname, "none")) {
6203 char label[32];
6204 snprintf(label, sizeof(label), "serial%d", i);
6205 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6206 if (!serial_hds[i]) {
6207 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6208 devname);
6209 exit(1);
6210 }
6211 }
6212 }
6213
6214 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6215 const char *devname = parallel_devices[i];
6216 if (devname && strcmp(devname, "none")) {
6217 char label[32];
6218 snprintf(label, sizeof(label), "parallel%d", i);
6219 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6220 if (!parallel_hds[i]) {
6221 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6222 devname);
6223 exit(1);
6224 }
6225 }
6226 }
6227
6228 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6229 const char *devname = virtio_consoles[i];
6230 if (devname && strcmp(devname, "none")) {
6231 char label[32];
6232 snprintf(label, sizeof(label), "virtcon%d", i);
6233 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6234 if (!virtcon_hds[i]) {
6235 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6236 devname);
6237 exit(1);
6238 }
6239 }
6240 }
6241
6242 module_call_init(MODULE_INIT_DEVICE);
6243
6244
6245#ifdef CONFIG_TRACE
6246 if (trace_filename) {
6247 trace_init(trace_filename);
6248#if 0
6249 // We don't need the dcache code until we can get load and store tracing
6250 // working again.
6251 dcache_init(dcache_size, dcache_ways, dcache_line_size,
6252 dcache_replace_policy, dcache_load_miss_penalty,
6253 dcache_store_miss_penalty);
6254#endif
6255 fprintf(stderr, "-- When done tracing, exit the emulator. --\n");
6256 }
6257#endif
6258
6259 machine->init(ram_size, boot_devices,
6260 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6261
6262
6263 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6264 for (i = 0; i < nb_numa_nodes; i++) {
6265 if (node_cpumask[i] & (1 << env->cpu_index)) {
6266 env->numa_node = i;
6267 }
6268 }
6269 }
6270
6271 current_machine = machine;
6272
6273 /* Set KVM's vcpu state to qemu's initial CPUState. */
6274 if (kvm_enabled()) {
6275 int ret;
6276
6277 ret = kvm_sync_vcpus();
6278 if (ret < 0) {
6279 fprintf(stderr, "failed to initialize vcpus\n");
6280 exit(1);
6281 }
6282 }
6283
6284 /* init USB devices */
6285 if (usb_enabled) {
6286 for(i = 0; i < usb_devices_index; i++) {
6287 if (usb_device_add(usb_devices[i], 0) < 0) {
6288 fprintf(stderr, "Warning: could not add USB device %s\n",
6289 usb_devices[i]);
6290 }
6291 }
6292 }
6293
6294 if (!display_state)
6295 dumb_display_init();
6296 /* just use the first displaystate for the moment */
6297 ds = display_state;
6298
6299 if (display_type == DT_DEFAULT) {
6300#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6301 display_type = DT_SDL;
6302#else
6303 display_type = DT_VNC;
6304 vnc_display = "localhost:0,to=99";
6305 show_vnc_port = 1;
6306#endif
6307 }
6308
6309
6310 switch (display_type) {
6311 case DT_NOGRAPHIC:
6312 break;
6313#if defined(CONFIG_CURSES)
6314 case DT_CURSES:
6315 curses_display_init(ds, full_screen);
6316 break;
6317#endif
6318#if defined(CONFIG_SDL)
6319 case DT_SDL:
6320 sdl_display_init(ds, full_screen, no_frame);
6321 break;
6322#elif defined(CONFIG_COCOA)
6323 case DT_SDL:
6324 cocoa_display_init(ds, full_screen);
6325 break;
6326#endif
6327 case DT_VNC:
6328 vnc_display_init(ds);
6329 if (vnc_display_open(ds, vnc_display) < 0)
6330 exit(1);
6331
6332 if (show_vnc_port) {
6333 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6334 }
6335 break;
6336 default:
6337 break;
6338 }
6339 dpy_resize(ds);
6340
6341 dcl = ds->listeners;
6342 while (dcl != NULL) {
6343 if (dcl->dpy_refresh != NULL) {
6344 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6345 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6346 }
6347 dcl = dcl->next;
6348 }
6349
6350 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6351 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6352 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6353 }
6354
6355 text_consoles_set_display(display_state);
6356 qemu_chr_initial_reset();
6357
6358 if (monitor_device && monitor_hd)
6359 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6360
6361 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6362 const char *devname = serial_devices[i];
6363 if (devname && strcmp(devname, "none")) {
6364 if (strstart(devname, "vc", 0))
6365 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6366 }
6367 }
6368
6369 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6370 const char *devname = parallel_devices[i];
6371 if (devname && strcmp(devname, "none")) {
6372 if (strstart(devname, "vc", 0))
6373 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6374 }
6375 }
6376
6377 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6378 const char *devname = virtio_consoles[i];
6379 if (virtcon_hds[i] && devname) {
6380 if (strstart(devname, "vc", 0))
6381 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6382 }
6383 }
6384
6385 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6386 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6387 gdbstub_dev);
6388 exit(1);
6389 }
6390
6391 if (loadvm)
6392 do_loadvm(cur_mon, loadvm);
6393
6394 /* call android-specific setup function */
6395 android_emulation_setup();
6396
6397 if (incoming) {
6398 autostart = 0; /* fixme how to deal with -daemonize */
6399 qemu_start_incoming_migration(incoming);
6400 }
6401
6402 if (autostart)
6403 vm_start();
6404
6405#ifndef _WIN32
6406 if (daemonize) {
6407 uint8_t status = 0;
6408 ssize_t len;
6409
6410 again1:
6411 len = write(fds[1], &status, 1);
6412 if (len == -1 && (errno == EINTR))
6413 goto again1;
6414
6415 if (len != 1)
6416 exit(1);
6417
6418 chdir("/");
6419 TFR(fd = open("/dev/null", O_RDWR));
6420 if (fd == -1)
6421 exit(1);
6422 }
6423
6424 if (run_as) {
6425 pwd = getpwnam(run_as);
6426 if (!pwd) {
6427 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6428 exit(1);
6429 }
6430 }
6431
6432 if (chroot_dir) {
6433 if (chroot(chroot_dir) < 0) {
6434 fprintf(stderr, "chroot failed\n");
6435 exit(1);
6436 }
6437 chdir("/");
6438 }
6439
6440 if (run_as) {
6441 if (setgid(pwd->pw_gid) < 0) {
6442 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6443 exit(1);
6444 }
6445 if (setuid(pwd->pw_uid) < 0) {
6446 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6447 exit(1);
6448 }
6449 if (setuid(0) != -1) {
6450 fprintf(stderr, "Dropping privileges failed\n");
6451 exit(1);
6452 }
6453 }
6454
6455 if (daemonize) {
6456 dup2(fd, 0);
6457 dup2(fd, 1);
6458 dup2(fd, 2);
6459
6460 close(fd);
6461 }
6462#endif
6463
6464 main_loop();
6465 quit_timers();
6466 net_cleanup();
6467 android_emulation_teardown();
6468 return 0;
6469}