R13 is reserved for small data area pointer by SVR4 PPC ABI
[qemu/mini2440.git] / vl.c
blob36765378a4f4e5803c8a2fea4cd8e41bd63a3663
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <errno.h>
51 #include <sys/time.h>
52 #include <zlib.h>
54 #ifndef _WIN32
55 #include <sys/times.h>
56 #include <sys/wait.h>
57 #include <termios.h>
58 #include <sys/mman.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <net/if.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
66 #endif
67 #ifdef __linux__
68 #include <linux/if_tun.h>
69 #endif
70 #include <arpa/inet.h>
71 #include <dirent.h>
72 #include <netdb.h>
73 #include <sys/select.h>
74 #ifdef _BSD
75 #include <sys/stat.h>
76 #ifdef __FreeBSD__
77 #include <libutil.h>
78 #else
79 #include <util.h>
80 #endif
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
83 #else
84 #ifdef __linux__
85 #include <pty.h>
86 #include <malloc.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
92 #include "hpet.h"
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
96 #endif
97 #ifdef __sun__
98 #include <sys/stat.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
108 #include <net/if.h>
109 #include <syslog.h>
110 #include <stropts.h>
111 #endif
112 #endif
113 #endif
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
119 #endif
121 #if defined(__OpenBSD__)
122 #include <util.h>
123 #endif
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
127 #endif
129 #ifdef _WIN32
130 #include <malloc.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
135 #endif
137 #ifdef CONFIG_SDL
138 #ifdef __APPLE__
139 #include <SDL/SDL.h>
140 #endif
141 #endif /* CONFIG_SDL */
143 #ifdef CONFIG_COCOA
144 #undef main
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
148 #include "disas.h"
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
158 #ifdef DEBUG_IOPORT
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
160 #else
161 # define LOG_IOPORT(...) do { } while (0)
162 #endif
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
183 int nb_drives;
184 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 int nographic;
188 static int curses;
189 static int sdl;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 #ifdef TARGET_ARM
237 int old_param = 0;
238 #endif
239 const char *qemu_name;
240 int alt_grab = 0;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
244 #endif
245 static int nb_drives_opt;
246 static struct drive_opt {
247 const char *file;
248 char opt[1024];
249 } drives_opt[MAX_DRIVES];
251 static CPUState *cur_cpu;
252 static CPUState *next_cpu;
253 static int event_pending = 1;
254 /* Conversion factor from emulated instructions to virtual clock ticks. */
255 static int icount_time_shift;
256 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
257 #define MAX_ICOUNT_SHIFT 10
258 /* Compensate for varying guest execution speed. */
259 static int64_t qemu_icount_bias;
260 static QEMUTimer *icount_rt_timer;
261 static QEMUTimer *icount_vm_timer;
262 static QEMUTimer *nographic_timer;
264 uint8_t qemu_uuid[16];
266 /***********************************************************/
267 /* x86 ISA bus support */
269 target_phys_addr_t isa_mem_base = 0;
270 PicState2 *isa_pic;
272 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
273 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
275 static uint32_t ioport_read(int index, uint32_t address)
277 static IOPortReadFunc *default_func[3] = {
278 default_ioport_readb,
279 default_ioport_readw,
280 default_ioport_readl
282 IOPortReadFunc *func = ioport_read_table[index][address];
283 if (!func)
284 func = default_func[index];
285 return func(ioport_opaque[address], address);
288 static void ioport_write(int index, uint32_t address, uint32_t data)
290 static IOPortWriteFunc *default_func[3] = {
291 default_ioport_writeb,
292 default_ioport_writew,
293 default_ioport_writel
295 IOPortWriteFunc *func = ioport_write_table[index][address];
296 if (!func)
297 func = default_func[index];
298 func(ioport_opaque[address], address, data);
301 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
303 #ifdef DEBUG_UNUSED_IOPORT
304 fprintf(stderr, "unused inb: port=0x%04x\n", address);
305 #endif
306 return 0xff;
309 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
311 #ifdef DEBUG_UNUSED_IOPORT
312 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
313 #endif
316 /* default is to make two byte accesses */
317 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
319 uint32_t data;
320 data = ioport_read(0, address);
321 address = (address + 1) & (MAX_IOPORTS - 1);
322 data |= ioport_read(0, address) << 8;
323 return data;
326 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
328 ioport_write(0, address, data & 0xff);
329 address = (address + 1) & (MAX_IOPORTS - 1);
330 ioport_write(0, address, (data >> 8) & 0xff);
333 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
335 #ifdef DEBUG_UNUSED_IOPORT
336 fprintf(stderr, "unused inl: port=0x%04x\n", address);
337 #endif
338 return 0xffffffff;
341 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
343 #ifdef DEBUG_UNUSED_IOPORT
344 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
345 #endif
348 /* size is the word size in byte */
349 int register_ioport_read(int start, int length, int size,
350 IOPortReadFunc *func, void *opaque)
352 int i, bsize;
354 if (size == 1) {
355 bsize = 0;
356 } else if (size == 2) {
357 bsize = 1;
358 } else if (size == 4) {
359 bsize = 2;
360 } else {
361 hw_error("register_ioport_read: invalid size");
362 return -1;
364 for(i = start; i < start + length; i += size) {
365 ioport_read_table[bsize][i] = func;
366 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
367 hw_error("register_ioport_read: invalid opaque");
368 ioport_opaque[i] = opaque;
370 return 0;
373 /* size is the word size in byte */
374 int register_ioport_write(int start, int length, int size,
375 IOPortWriteFunc *func, void *opaque)
377 int i, bsize;
379 if (size == 1) {
380 bsize = 0;
381 } else if (size == 2) {
382 bsize = 1;
383 } else if (size == 4) {
384 bsize = 2;
385 } else {
386 hw_error("register_ioport_write: invalid size");
387 return -1;
389 for(i = start; i < start + length; i += size) {
390 ioport_write_table[bsize][i] = func;
391 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
392 hw_error("register_ioport_write: invalid opaque");
393 ioport_opaque[i] = opaque;
395 return 0;
398 void isa_unassign_ioport(int start, int length)
400 int i;
402 for(i = start; i < start + length; i++) {
403 ioport_read_table[0][i] = default_ioport_readb;
404 ioport_read_table[1][i] = default_ioport_readw;
405 ioport_read_table[2][i] = default_ioport_readl;
407 ioport_write_table[0][i] = default_ioport_writeb;
408 ioport_write_table[1][i] = default_ioport_writew;
409 ioport_write_table[2][i] = default_ioport_writel;
413 /***********************************************************/
415 void cpu_outb(CPUState *env, int addr, int val)
417 LOG_IOPORT("outb: %04x %02x\n", addr, val);
418 ioport_write(0, addr, val);
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
425 void cpu_outw(CPUState *env, int addr, int val)
427 LOG_IOPORT("outw: %04x %04x\n", addr, val);
428 ioport_write(1, addr, val);
429 #ifdef USE_KQEMU
430 if (env)
431 env->last_io_time = cpu_get_time_fast();
432 #endif
435 void cpu_outl(CPUState *env, int addr, int val)
437 LOG_IOPORT("outl: %04x %08x\n", addr, val);
438 ioport_write(2, addr, val);
439 #ifdef USE_KQEMU
440 if (env)
441 env->last_io_time = cpu_get_time_fast();
442 #endif
445 int cpu_inb(CPUState *env, int addr)
447 int val;
448 val = ioport_read(0, addr);
449 LOG_IOPORT("inb : %04x %02x\n", addr, val);
450 #ifdef USE_KQEMU
451 if (env)
452 env->last_io_time = cpu_get_time_fast();
453 #endif
454 return val;
457 int cpu_inw(CPUState *env, int addr)
459 int val;
460 val = ioport_read(1, addr);
461 LOG_IOPORT("inw : %04x %04x\n", addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
466 return val;
469 int cpu_inl(CPUState *env, int addr)
471 int val;
472 val = ioport_read(2, addr);
473 LOG_IOPORT("inl : %04x %08x\n", addr, val);
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
478 return val;
481 /***********************************************************/
482 void hw_error(const char *fmt, ...)
484 va_list ap;
485 CPUState *env;
487 va_start(ap, fmt);
488 fprintf(stderr, "qemu: hardware error: ");
489 vfprintf(stderr, fmt, ap);
490 fprintf(stderr, "\n");
491 for(env = first_cpu; env != NULL; env = env->next_cpu) {
492 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
493 #ifdef TARGET_I386
494 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
495 #else
496 cpu_dump_state(env, stderr, fprintf, 0);
497 #endif
499 va_end(ap);
500 abort();
503 /***************/
504 /* ballooning */
506 static QEMUBalloonEvent *qemu_balloon_event;
507 void *qemu_balloon_event_opaque;
509 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
511 qemu_balloon_event = func;
512 qemu_balloon_event_opaque = opaque;
515 void qemu_balloon(ram_addr_t target)
517 if (qemu_balloon_event)
518 qemu_balloon_event(qemu_balloon_event_opaque, target);
521 ram_addr_t qemu_balloon_status(void)
523 if (qemu_balloon_event)
524 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
525 return 0;
528 /***********************************************************/
529 /* keyboard/mouse */
531 static QEMUPutKBDEvent *qemu_put_kbd_event;
532 static void *qemu_put_kbd_event_opaque;
533 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
534 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
536 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
538 qemu_put_kbd_event_opaque = opaque;
539 qemu_put_kbd_event = func;
542 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
543 void *opaque, int absolute,
544 const char *name)
546 QEMUPutMouseEntry *s, *cursor;
548 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
549 if (!s)
550 return NULL;
552 s->qemu_put_mouse_event = func;
553 s->qemu_put_mouse_event_opaque = opaque;
554 s->qemu_put_mouse_event_absolute = absolute;
555 s->qemu_put_mouse_event_name = qemu_strdup(name);
556 s->next = NULL;
558 if (!qemu_put_mouse_event_head) {
559 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
560 return s;
563 cursor = qemu_put_mouse_event_head;
564 while (cursor->next != NULL)
565 cursor = cursor->next;
567 cursor->next = s;
568 qemu_put_mouse_event_current = s;
570 return s;
573 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
575 QEMUPutMouseEntry *prev = NULL, *cursor;
577 if (!qemu_put_mouse_event_head || entry == NULL)
578 return;
580 cursor = qemu_put_mouse_event_head;
581 while (cursor != NULL && cursor != entry) {
582 prev = cursor;
583 cursor = cursor->next;
586 if (cursor == NULL) // does not exist or list empty
587 return;
588 else if (prev == NULL) { // entry is head
589 qemu_put_mouse_event_head = cursor->next;
590 if (qemu_put_mouse_event_current == entry)
591 qemu_put_mouse_event_current = cursor->next;
592 qemu_free(entry->qemu_put_mouse_event_name);
593 qemu_free(entry);
594 return;
597 prev->next = entry->next;
599 if (qemu_put_mouse_event_current == entry)
600 qemu_put_mouse_event_current = prev;
602 qemu_free(entry->qemu_put_mouse_event_name);
603 qemu_free(entry);
606 void kbd_put_keycode(int keycode)
608 if (qemu_put_kbd_event) {
609 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
613 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
615 QEMUPutMouseEvent *mouse_event;
616 void *mouse_event_opaque;
617 int width;
619 if (!qemu_put_mouse_event_current) {
620 return;
623 mouse_event =
624 qemu_put_mouse_event_current->qemu_put_mouse_event;
625 mouse_event_opaque =
626 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
628 if (mouse_event) {
629 if (graphic_rotate) {
630 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
631 width = 0x7fff;
632 else
633 width = graphic_width - 1;
634 mouse_event(mouse_event_opaque,
635 width - dy, dx, dz, buttons_state);
636 } else
637 mouse_event(mouse_event_opaque,
638 dx, dy, dz, buttons_state);
642 int kbd_mouse_is_absolute(void)
644 if (!qemu_put_mouse_event_current)
645 return 0;
647 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
650 void do_info_mice(void)
652 QEMUPutMouseEntry *cursor;
653 int index = 0;
655 if (!qemu_put_mouse_event_head) {
656 term_printf("No mouse devices connected\n");
657 return;
660 term_printf("Mouse devices available:\n");
661 cursor = qemu_put_mouse_event_head;
662 while (cursor != NULL) {
663 term_printf("%c Mouse #%d: %s\n",
664 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
665 index, cursor->qemu_put_mouse_event_name);
666 index++;
667 cursor = cursor->next;
671 void do_mouse_set(int index)
673 QEMUPutMouseEntry *cursor;
674 int i = 0;
676 if (!qemu_put_mouse_event_head) {
677 term_printf("No mouse devices connected\n");
678 return;
681 cursor = qemu_put_mouse_event_head;
682 while (cursor != NULL && index != i) {
683 i++;
684 cursor = cursor->next;
687 if (cursor != NULL)
688 qemu_put_mouse_event_current = cursor;
689 else
690 term_printf("Mouse at given index not found\n");
693 /* compute with 96 bit intermediate result: (a*b)/c */
694 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
696 union {
697 uint64_t ll;
698 struct {
699 #ifdef WORDS_BIGENDIAN
700 uint32_t high, low;
701 #else
702 uint32_t low, high;
703 #endif
704 } l;
705 } u, res;
706 uint64_t rl, rh;
708 u.ll = a;
709 rl = (uint64_t)u.l.low * (uint64_t)b;
710 rh = (uint64_t)u.l.high * (uint64_t)b;
711 rh += (rl >> 32);
712 res.l.high = rh / c;
713 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
714 return res.ll;
717 /***********************************************************/
718 /* real time host monotonic timer */
720 #define QEMU_TIMER_BASE 1000000000LL
722 #ifdef WIN32
724 static int64_t clock_freq;
726 static void init_get_clock(void)
728 LARGE_INTEGER freq;
729 int ret;
730 ret = QueryPerformanceFrequency(&freq);
731 if (ret == 0) {
732 fprintf(stderr, "Could not calibrate ticks\n");
733 exit(1);
735 clock_freq = freq.QuadPart;
738 static int64_t get_clock(void)
740 LARGE_INTEGER ti;
741 QueryPerformanceCounter(&ti);
742 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
745 #else
747 static int use_rt_clock;
749 static void init_get_clock(void)
751 use_rt_clock = 0;
752 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
754 struct timespec ts;
755 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
756 use_rt_clock = 1;
759 #endif
762 static int64_t get_clock(void)
764 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
765 if (use_rt_clock) {
766 struct timespec ts;
767 clock_gettime(CLOCK_MONOTONIC, &ts);
768 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
769 } else
770 #endif
772 /* XXX: using gettimeofday leads to problems if the date
773 changes, so it should be avoided. */
774 struct timeval tv;
775 gettimeofday(&tv, NULL);
776 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
779 #endif
781 /* Return the virtual CPU time, based on the instruction counter. */
782 static int64_t cpu_get_icount(void)
784 int64_t icount;
785 CPUState *env = cpu_single_env;;
786 icount = qemu_icount;
787 if (env) {
788 if (!can_do_io(env))
789 fprintf(stderr, "Bad clock read\n");
790 icount -= (env->icount_decr.u16.low + env->icount_extra);
792 return qemu_icount_bias + (icount << icount_time_shift);
795 /***********************************************************/
796 /* guest cycle counter */
798 static int64_t cpu_ticks_prev;
799 static int64_t cpu_ticks_offset;
800 static int64_t cpu_clock_offset;
801 static int cpu_ticks_enabled;
803 /* return the host CPU cycle counter and handle stop/restart */
804 int64_t cpu_get_ticks(void)
806 if (use_icount) {
807 return cpu_get_icount();
809 if (!cpu_ticks_enabled) {
810 return cpu_ticks_offset;
811 } else {
812 int64_t ticks;
813 ticks = cpu_get_real_ticks();
814 if (cpu_ticks_prev > ticks) {
815 /* Note: non increasing ticks may happen if the host uses
816 software suspend */
817 cpu_ticks_offset += cpu_ticks_prev - ticks;
819 cpu_ticks_prev = ticks;
820 return ticks + cpu_ticks_offset;
824 /* return the host CPU monotonic timer and handle stop/restart */
825 static int64_t cpu_get_clock(void)
827 int64_t ti;
828 if (!cpu_ticks_enabled) {
829 return cpu_clock_offset;
830 } else {
831 ti = get_clock();
832 return ti + cpu_clock_offset;
836 /* enable cpu_get_ticks() */
837 void cpu_enable_ticks(void)
839 if (!cpu_ticks_enabled) {
840 cpu_ticks_offset -= cpu_get_real_ticks();
841 cpu_clock_offset -= get_clock();
842 cpu_ticks_enabled = 1;
846 /* disable cpu_get_ticks() : the clock is stopped. You must not call
847 cpu_get_ticks() after that. */
848 void cpu_disable_ticks(void)
850 if (cpu_ticks_enabled) {
851 cpu_ticks_offset = cpu_get_ticks();
852 cpu_clock_offset = cpu_get_clock();
853 cpu_ticks_enabled = 0;
857 /***********************************************************/
858 /* timers */
860 #define QEMU_TIMER_REALTIME 0
861 #define QEMU_TIMER_VIRTUAL 1
863 struct QEMUClock {
864 int type;
865 /* XXX: add frequency */
868 struct QEMUTimer {
869 QEMUClock *clock;
870 int64_t expire_time;
871 QEMUTimerCB *cb;
872 void *opaque;
873 struct QEMUTimer *next;
876 struct qemu_alarm_timer {
877 char const *name;
878 unsigned int flags;
880 int (*start)(struct qemu_alarm_timer *t);
881 void (*stop)(struct qemu_alarm_timer *t);
882 void (*rearm)(struct qemu_alarm_timer *t);
883 void *priv;
886 #define ALARM_FLAG_DYNTICKS 0x1
887 #define ALARM_FLAG_EXPIRED 0x2
889 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
891 return t->flags & ALARM_FLAG_DYNTICKS;
894 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
896 if (!alarm_has_dynticks(t))
897 return;
899 t->rearm(t);
902 /* TODO: MIN_TIMER_REARM_US should be optimized */
903 #define MIN_TIMER_REARM_US 250
905 static struct qemu_alarm_timer *alarm_timer;
906 #ifndef _WIN32
907 static int alarm_timer_rfd, alarm_timer_wfd;
908 #endif
910 #ifdef _WIN32
912 struct qemu_alarm_win32 {
913 MMRESULT timerId;
914 HANDLE host_alarm;
915 unsigned int period;
916 } alarm_win32_data = {0, NULL, -1};
918 static int win32_start_timer(struct qemu_alarm_timer *t);
919 static void win32_stop_timer(struct qemu_alarm_timer *t);
920 static void win32_rearm_timer(struct qemu_alarm_timer *t);
922 #else
924 static int unix_start_timer(struct qemu_alarm_timer *t);
925 static void unix_stop_timer(struct qemu_alarm_timer *t);
927 #ifdef __linux__
929 static int dynticks_start_timer(struct qemu_alarm_timer *t);
930 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
931 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
933 static int hpet_start_timer(struct qemu_alarm_timer *t);
934 static void hpet_stop_timer(struct qemu_alarm_timer *t);
936 static int rtc_start_timer(struct qemu_alarm_timer *t);
937 static void rtc_stop_timer(struct qemu_alarm_timer *t);
939 #endif /* __linux__ */
941 #endif /* _WIN32 */
943 /* Correlation between real and virtual time is always going to be
944 fairly approximate, so ignore small variation.
945 When the guest is idle real and virtual time will be aligned in
946 the IO wait loop. */
947 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
949 static void icount_adjust(void)
951 int64_t cur_time;
952 int64_t cur_icount;
953 int64_t delta;
954 static int64_t last_delta;
955 /* If the VM is not running, then do nothing. */
956 if (!vm_running)
957 return;
959 cur_time = cpu_get_clock();
960 cur_icount = qemu_get_clock(vm_clock);
961 delta = cur_icount - cur_time;
962 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
963 if (delta > 0
964 && last_delta + ICOUNT_WOBBLE < delta * 2
965 && icount_time_shift > 0) {
966 /* The guest is getting too far ahead. Slow time down. */
967 icount_time_shift--;
969 if (delta < 0
970 && last_delta - ICOUNT_WOBBLE > delta * 2
971 && icount_time_shift < MAX_ICOUNT_SHIFT) {
972 /* The guest is getting too far behind. Speed time up. */
973 icount_time_shift++;
975 last_delta = delta;
976 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
979 static void icount_adjust_rt(void * opaque)
981 qemu_mod_timer(icount_rt_timer,
982 qemu_get_clock(rt_clock) + 1000);
983 icount_adjust();
986 static void icount_adjust_vm(void * opaque)
988 qemu_mod_timer(icount_vm_timer,
989 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
990 icount_adjust();
993 static void init_icount_adjust(void)
995 /* Have both realtime and virtual time triggers for speed adjustment.
996 The realtime trigger catches emulated time passing too slowly,
997 the virtual time trigger catches emulated time passing too fast.
998 Realtime triggers occur even when idle, so use them less frequently
999 than VM triggers. */
1000 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1001 qemu_mod_timer(icount_rt_timer,
1002 qemu_get_clock(rt_clock) + 1000);
1003 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1004 qemu_mod_timer(icount_vm_timer,
1005 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1008 static struct qemu_alarm_timer alarm_timers[] = {
1009 #ifndef _WIN32
1010 #ifdef __linux__
1011 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1012 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1013 /* HPET - if available - is preferred */
1014 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1015 /* ...otherwise try RTC */
1016 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1017 #endif
1018 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1019 #else
1020 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1021 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1022 {"win32", 0, win32_start_timer,
1023 win32_stop_timer, NULL, &alarm_win32_data},
1024 #endif
1025 {NULL, }
1028 static void show_available_alarms(void)
1030 int i;
1032 printf("Available alarm timers, in order of precedence:\n");
1033 for (i = 0; alarm_timers[i].name; i++)
1034 printf("%s\n", alarm_timers[i].name);
1037 static void configure_alarms(char const *opt)
1039 int i;
1040 int cur = 0;
1041 int count = ARRAY_SIZE(alarm_timers) - 1;
1042 char *arg;
1043 char *name;
1044 struct qemu_alarm_timer tmp;
1046 if (!strcmp(opt, "?")) {
1047 show_available_alarms();
1048 exit(0);
1051 arg = strdup(opt);
1053 /* Reorder the array */
1054 name = strtok(arg, ",");
1055 while (name) {
1056 for (i = 0; i < count && alarm_timers[i].name; i++) {
1057 if (!strcmp(alarm_timers[i].name, name))
1058 break;
1061 if (i == count) {
1062 fprintf(stderr, "Unknown clock %s\n", name);
1063 goto next;
1066 if (i < cur)
1067 /* Ignore */
1068 goto next;
1070 /* Swap */
1071 tmp = alarm_timers[i];
1072 alarm_timers[i] = alarm_timers[cur];
1073 alarm_timers[cur] = tmp;
1075 cur++;
1076 next:
1077 name = strtok(NULL, ",");
1080 free(arg);
1082 if (cur) {
1083 /* Disable remaining timers */
1084 for (i = cur; i < count; i++)
1085 alarm_timers[i].name = NULL;
1086 } else {
1087 show_available_alarms();
1088 exit(1);
1092 QEMUClock *rt_clock;
1093 QEMUClock *vm_clock;
1095 static QEMUTimer *active_timers[2];
1097 static QEMUClock *qemu_new_clock(int type)
1099 QEMUClock *clock;
1100 clock = qemu_mallocz(sizeof(QEMUClock));
1101 if (!clock)
1102 return NULL;
1103 clock->type = type;
1104 return clock;
1107 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1109 QEMUTimer *ts;
1111 ts = qemu_mallocz(sizeof(QEMUTimer));
1112 ts->clock = clock;
1113 ts->cb = cb;
1114 ts->opaque = opaque;
1115 return ts;
1118 void qemu_free_timer(QEMUTimer *ts)
1120 qemu_free(ts);
1123 /* stop a timer, but do not dealloc it */
1124 void qemu_del_timer(QEMUTimer *ts)
1126 QEMUTimer **pt, *t;
1128 /* NOTE: this code must be signal safe because
1129 qemu_timer_expired() can be called from a signal. */
1130 pt = &active_timers[ts->clock->type];
1131 for(;;) {
1132 t = *pt;
1133 if (!t)
1134 break;
1135 if (t == ts) {
1136 *pt = t->next;
1137 break;
1139 pt = &t->next;
1143 /* modify the current timer so that it will be fired when current_time
1144 >= expire_time. The corresponding callback will be called. */
1145 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1147 QEMUTimer **pt, *t;
1149 qemu_del_timer(ts);
1151 /* add the timer in the sorted list */
1152 /* NOTE: this code must be signal safe because
1153 qemu_timer_expired() can be called from a signal. */
1154 pt = &active_timers[ts->clock->type];
1155 for(;;) {
1156 t = *pt;
1157 if (!t)
1158 break;
1159 if (t->expire_time > expire_time)
1160 break;
1161 pt = &t->next;
1163 ts->expire_time = expire_time;
1164 ts->next = *pt;
1165 *pt = ts;
1167 /* Rearm if necessary */
1168 if (pt == &active_timers[ts->clock->type]) {
1169 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1170 qemu_rearm_alarm_timer(alarm_timer);
1172 /* Interrupt execution to force deadline recalculation. */
1173 if (use_icount && cpu_single_env) {
1174 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1179 int qemu_timer_pending(QEMUTimer *ts)
1181 QEMUTimer *t;
1182 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1183 if (t == ts)
1184 return 1;
1186 return 0;
1189 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1191 if (!timer_head)
1192 return 0;
1193 return (timer_head->expire_time <= current_time);
1196 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1198 QEMUTimer *ts;
1200 for(;;) {
1201 ts = *ptimer_head;
1202 if (!ts || ts->expire_time > current_time)
1203 break;
1204 /* remove timer from the list before calling the callback */
1205 *ptimer_head = ts->next;
1206 ts->next = NULL;
1208 /* run the callback (the timer list can be modified) */
1209 ts->cb(ts->opaque);
1213 int64_t qemu_get_clock(QEMUClock *clock)
1215 switch(clock->type) {
1216 case QEMU_TIMER_REALTIME:
1217 return get_clock() / 1000000;
1218 default:
1219 case QEMU_TIMER_VIRTUAL:
1220 if (use_icount) {
1221 return cpu_get_icount();
1222 } else {
1223 return cpu_get_clock();
1228 static void init_timers(void)
1230 init_get_clock();
1231 ticks_per_sec = QEMU_TIMER_BASE;
1232 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1233 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1236 /* save a timer */
1237 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1239 uint64_t expire_time;
1241 if (qemu_timer_pending(ts)) {
1242 expire_time = ts->expire_time;
1243 } else {
1244 expire_time = -1;
1246 qemu_put_be64(f, expire_time);
1249 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1251 uint64_t expire_time;
1253 expire_time = qemu_get_be64(f);
1254 if (expire_time != -1) {
1255 qemu_mod_timer(ts, expire_time);
1256 } else {
1257 qemu_del_timer(ts);
1261 static void timer_save(QEMUFile *f, void *opaque)
1263 if (cpu_ticks_enabled) {
1264 hw_error("cannot save state if virtual timers are running");
1266 qemu_put_be64(f, cpu_ticks_offset);
1267 qemu_put_be64(f, ticks_per_sec);
1268 qemu_put_be64(f, cpu_clock_offset);
1271 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1273 if (version_id != 1 && version_id != 2)
1274 return -EINVAL;
1275 if (cpu_ticks_enabled) {
1276 return -EINVAL;
1278 cpu_ticks_offset=qemu_get_be64(f);
1279 ticks_per_sec=qemu_get_be64(f);
1280 if (version_id == 2) {
1281 cpu_clock_offset=qemu_get_be64(f);
1283 return 0;
1286 #ifdef _WIN32
1287 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1288 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1289 #else
1290 static void host_alarm_handler(int host_signum)
1291 #endif
1293 #if 0
1294 #define DISP_FREQ 1000
1296 static int64_t delta_min = INT64_MAX;
1297 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1298 static int count;
1299 ti = qemu_get_clock(vm_clock);
1300 if (last_clock != 0) {
1301 delta = ti - last_clock;
1302 if (delta < delta_min)
1303 delta_min = delta;
1304 if (delta > delta_max)
1305 delta_max = delta;
1306 delta_cum += delta;
1307 if (++count == DISP_FREQ) {
1308 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1309 muldiv64(delta_min, 1000000, ticks_per_sec),
1310 muldiv64(delta_max, 1000000, ticks_per_sec),
1311 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1312 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1313 count = 0;
1314 delta_min = INT64_MAX;
1315 delta_max = 0;
1316 delta_cum = 0;
1319 last_clock = ti;
1321 #endif
1322 if (alarm_has_dynticks(alarm_timer) ||
1323 (!use_icount &&
1324 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1325 qemu_get_clock(vm_clock))) ||
1326 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1327 qemu_get_clock(rt_clock))) {
1328 CPUState *env = next_cpu;
1330 #ifdef _WIN32
1331 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1332 SetEvent(data->host_alarm);
1333 #else
1334 static const char byte = 0;
1335 write(alarm_timer_wfd, &byte, sizeof(byte));
1336 #endif
1337 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1339 if (env) {
1340 /* stop the currently executing cpu because a timer occured */
1341 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1342 #ifdef USE_KQEMU
1343 if (env->kqemu_enabled) {
1344 kqemu_cpu_interrupt(env);
1346 #endif
1348 event_pending = 1;
1352 static int64_t qemu_next_deadline(void)
1354 int64_t delta;
1356 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1357 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1358 qemu_get_clock(vm_clock);
1359 } else {
1360 /* To avoid problems with overflow limit this to 2^32. */
1361 delta = INT32_MAX;
1364 if (delta < 0)
1365 delta = 0;
1367 return delta;
1370 #if defined(__linux__) || defined(_WIN32)
1371 static uint64_t qemu_next_deadline_dyntick(void)
1373 int64_t delta;
1374 int64_t rtdelta;
1376 if (use_icount)
1377 delta = INT32_MAX;
1378 else
1379 delta = (qemu_next_deadline() + 999) / 1000;
1381 if (active_timers[QEMU_TIMER_REALTIME]) {
1382 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1383 qemu_get_clock(rt_clock))*1000;
1384 if (rtdelta < delta)
1385 delta = rtdelta;
1388 if (delta < MIN_TIMER_REARM_US)
1389 delta = MIN_TIMER_REARM_US;
1391 return delta;
1393 #endif
1395 #ifndef _WIN32
1397 /* Sets a specific flag */
1398 static int fcntl_setfl(int fd, int flag)
1400 int flags;
1402 flags = fcntl(fd, F_GETFL);
1403 if (flags == -1)
1404 return -errno;
1406 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1407 return -errno;
1409 return 0;
1412 #if defined(__linux__)
1414 #define RTC_FREQ 1024
1416 static void enable_sigio_timer(int fd)
1418 struct sigaction act;
1420 /* timer signal */
1421 sigfillset(&act.sa_mask);
1422 act.sa_flags = 0;
1423 act.sa_handler = host_alarm_handler;
1425 sigaction(SIGIO, &act, NULL);
1426 fcntl_setfl(fd, O_ASYNC);
1427 fcntl(fd, F_SETOWN, getpid());
1430 static int hpet_start_timer(struct qemu_alarm_timer *t)
1432 struct hpet_info info;
1433 int r, fd;
1435 fd = open("/dev/hpet", O_RDONLY);
1436 if (fd < 0)
1437 return -1;
1439 /* Set frequency */
1440 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1441 if (r < 0) {
1442 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1443 "error, but for better emulation accuracy type:\n"
1444 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1445 goto fail;
1448 /* Check capabilities */
1449 r = ioctl(fd, HPET_INFO, &info);
1450 if (r < 0)
1451 goto fail;
1453 /* Enable periodic mode */
1454 r = ioctl(fd, HPET_EPI, 0);
1455 if (info.hi_flags && (r < 0))
1456 goto fail;
1458 /* Enable interrupt */
1459 r = ioctl(fd, HPET_IE_ON, 0);
1460 if (r < 0)
1461 goto fail;
1463 enable_sigio_timer(fd);
1464 t->priv = (void *)(long)fd;
1466 return 0;
1467 fail:
1468 close(fd);
1469 return -1;
1472 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1474 int fd = (long)t->priv;
1476 close(fd);
1479 static int rtc_start_timer(struct qemu_alarm_timer *t)
1481 int rtc_fd;
1482 unsigned long current_rtc_freq = 0;
1484 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1485 if (rtc_fd < 0)
1486 return -1;
1487 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1488 if (current_rtc_freq != RTC_FREQ &&
1489 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1490 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1492 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1493 goto fail;
1495 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1496 fail:
1497 close(rtc_fd);
1498 return -1;
1501 enable_sigio_timer(rtc_fd);
1503 t->priv = (void *)(long)rtc_fd;
1505 return 0;
1508 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1510 int rtc_fd = (long)t->priv;
1512 close(rtc_fd);
1515 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1517 struct sigevent ev;
1518 timer_t host_timer;
1519 struct sigaction act;
1521 sigfillset(&act.sa_mask);
1522 act.sa_flags = 0;
1523 act.sa_handler = host_alarm_handler;
1525 sigaction(SIGALRM, &act, NULL);
1527 ev.sigev_value.sival_int = 0;
1528 ev.sigev_notify = SIGEV_SIGNAL;
1529 ev.sigev_signo = SIGALRM;
1531 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1532 perror("timer_create");
1534 /* disable dynticks */
1535 fprintf(stderr, "Dynamic Ticks disabled\n");
1537 return -1;
1540 t->priv = (void *)(long)host_timer;
1542 return 0;
1545 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1547 timer_t host_timer = (timer_t)(long)t->priv;
1549 timer_delete(host_timer);
1552 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1554 timer_t host_timer = (timer_t)(long)t->priv;
1555 struct itimerspec timeout;
1556 int64_t nearest_delta_us = INT64_MAX;
1557 int64_t current_us;
1559 if (!active_timers[QEMU_TIMER_REALTIME] &&
1560 !active_timers[QEMU_TIMER_VIRTUAL])
1561 return;
1563 nearest_delta_us = qemu_next_deadline_dyntick();
1565 /* check whether a timer is already running */
1566 if (timer_gettime(host_timer, &timeout)) {
1567 perror("gettime");
1568 fprintf(stderr, "Internal timer error: aborting\n");
1569 exit(1);
1571 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1572 if (current_us && current_us <= nearest_delta_us)
1573 return;
1575 timeout.it_interval.tv_sec = 0;
1576 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1577 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1578 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1579 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1580 perror("settime");
1581 fprintf(stderr, "Internal timer error: aborting\n");
1582 exit(1);
1586 #endif /* defined(__linux__) */
1588 static int unix_start_timer(struct qemu_alarm_timer *t)
1590 struct sigaction act;
1591 struct itimerval itv;
1592 int err;
1594 /* timer signal */
1595 sigfillset(&act.sa_mask);
1596 act.sa_flags = 0;
1597 act.sa_handler = host_alarm_handler;
1599 sigaction(SIGALRM, &act, NULL);
1601 itv.it_interval.tv_sec = 0;
1602 /* for i386 kernel 2.6 to get 1 ms */
1603 itv.it_interval.tv_usec = 999;
1604 itv.it_value.tv_sec = 0;
1605 itv.it_value.tv_usec = 10 * 1000;
1607 err = setitimer(ITIMER_REAL, &itv, NULL);
1608 if (err)
1609 return -1;
1611 return 0;
1614 static void unix_stop_timer(struct qemu_alarm_timer *t)
1616 struct itimerval itv;
1618 memset(&itv, 0, sizeof(itv));
1619 setitimer(ITIMER_REAL, &itv, NULL);
1622 #endif /* !defined(_WIN32) */
1624 static void try_to_rearm_timer(void *opaque)
1626 struct qemu_alarm_timer *t = opaque;
1627 #ifndef _WIN32
1628 ssize_t len;
1630 /* Drain the notify pipe */
1631 do {
1632 char buffer[512];
1633 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1634 } while ((len == -1 && errno == EINTR) || len > 0);
1635 #endif
1637 if (t->flags & ALARM_FLAG_EXPIRED) {
1638 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1639 qemu_rearm_alarm_timer(alarm_timer);
1643 #ifdef _WIN32
1645 static int win32_start_timer(struct qemu_alarm_timer *t)
1647 TIMECAPS tc;
1648 struct qemu_alarm_win32 *data = t->priv;
1649 UINT flags;
1651 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1652 if (!data->host_alarm) {
1653 perror("Failed CreateEvent");
1654 return -1;
1657 memset(&tc, 0, sizeof(tc));
1658 timeGetDevCaps(&tc, sizeof(tc));
1660 if (data->period < tc.wPeriodMin)
1661 data->period = tc.wPeriodMin;
1663 timeBeginPeriod(data->period);
1665 flags = TIME_CALLBACK_FUNCTION;
1666 if (alarm_has_dynticks(t))
1667 flags |= TIME_ONESHOT;
1668 else
1669 flags |= TIME_PERIODIC;
1671 data->timerId = timeSetEvent(1, // interval (ms)
1672 data->period, // resolution
1673 host_alarm_handler, // function
1674 (DWORD)t, // parameter
1675 flags);
1677 if (!data->timerId) {
1678 perror("Failed to initialize win32 alarm timer");
1680 timeEndPeriod(data->period);
1681 CloseHandle(data->host_alarm);
1682 return -1;
1685 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1687 return 0;
1690 static void win32_stop_timer(struct qemu_alarm_timer *t)
1692 struct qemu_alarm_win32 *data = t->priv;
1694 timeKillEvent(data->timerId);
1695 timeEndPeriod(data->period);
1697 CloseHandle(data->host_alarm);
1700 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1702 struct qemu_alarm_win32 *data = t->priv;
1703 uint64_t nearest_delta_us;
1705 if (!active_timers[QEMU_TIMER_REALTIME] &&
1706 !active_timers[QEMU_TIMER_VIRTUAL])
1707 return;
1709 nearest_delta_us = qemu_next_deadline_dyntick();
1710 nearest_delta_us /= 1000;
1712 timeKillEvent(data->timerId);
1714 data->timerId = timeSetEvent(1,
1715 data->period,
1716 host_alarm_handler,
1717 (DWORD)t,
1718 TIME_ONESHOT | TIME_PERIODIC);
1720 if (!data->timerId) {
1721 perror("Failed to re-arm win32 alarm timer");
1723 timeEndPeriod(data->period);
1724 CloseHandle(data->host_alarm);
1725 exit(1);
1729 #endif /* _WIN32 */
1731 static int init_timer_alarm(void)
1733 struct qemu_alarm_timer *t = NULL;
1734 int i, err = -1;
1736 #ifndef _WIN32
1737 int fds[2];
1739 err = pipe(fds);
1740 if (err == -1)
1741 return -errno;
1743 err = fcntl_setfl(fds[0], O_NONBLOCK);
1744 if (err < 0)
1745 goto fail;
1747 err = fcntl_setfl(fds[1], O_NONBLOCK);
1748 if (err < 0)
1749 goto fail;
1751 alarm_timer_rfd = fds[0];
1752 alarm_timer_wfd = fds[1];
1753 #endif
1755 for (i = 0; alarm_timers[i].name; i++) {
1756 t = &alarm_timers[i];
1758 err = t->start(t);
1759 if (!err)
1760 break;
1763 if (err) {
1764 err = -ENOENT;
1765 goto fail;
1768 #ifndef _WIN32
1769 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1770 try_to_rearm_timer, NULL, t);
1771 #endif
1773 alarm_timer = t;
1775 return 0;
1777 fail:
1778 #ifndef _WIN32
1779 close(fds[0]);
1780 close(fds[1]);
1781 #endif
1782 return err;
1785 static void quit_timers(void)
1787 alarm_timer->stop(alarm_timer);
1788 alarm_timer = NULL;
1791 /***********************************************************/
1792 /* host time/date access */
1793 void qemu_get_timedate(struct tm *tm, int offset)
1795 time_t ti;
1796 struct tm *ret;
1798 time(&ti);
1799 ti += offset;
1800 if (rtc_date_offset == -1) {
1801 if (rtc_utc)
1802 ret = gmtime(&ti);
1803 else
1804 ret = localtime(&ti);
1805 } else {
1806 ti -= rtc_date_offset;
1807 ret = gmtime(&ti);
1810 memcpy(tm, ret, sizeof(struct tm));
1813 int qemu_timedate_diff(struct tm *tm)
1815 time_t seconds;
1817 if (rtc_date_offset == -1)
1818 if (rtc_utc)
1819 seconds = mktimegm(tm);
1820 else
1821 seconds = mktime(tm);
1822 else
1823 seconds = mktimegm(tm) + rtc_date_offset;
1825 return seconds - time(NULL);
1828 #ifdef _WIN32
1829 static void socket_cleanup(void)
1831 WSACleanup();
1834 static int socket_init(void)
1836 WSADATA Data;
1837 int ret, err;
1839 ret = WSAStartup(MAKEWORD(2,2), &Data);
1840 if (ret != 0) {
1841 err = WSAGetLastError();
1842 fprintf(stderr, "WSAStartup: %d\n", err);
1843 return -1;
1845 atexit(socket_cleanup);
1846 return 0;
1848 #endif
1850 const char *get_opt_name(char *buf, int buf_size, const char *p)
1852 char *q;
1854 q = buf;
1855 while (*p != '\0' && *p != '=') {
1856 if (q && (q - buf) < buf_size - 1)
1857 *q++ = *p;
1858 p++;
1860 if (q)
1861 *q = '\0';
1863 return p;
1866 const char *get_opt_value(char *buf, int buf_size, const char *p)
1868 char *q;
1870 q = buf;
1871 while (*p != '\0') {
1872 if (*p == ',') {
1873 if (*(p + 1) != ',')
1874 break;
1875 p++;
1877 if (q && (q - buf) < buf_size - 1)
1878 *q++ = *p;
1879 p++;
1881 if (q)
1882 *q = '\0';
1884 return p;
1887 int get_param_value(char *buf, int buf_size,
1888 const char *tag, const char *str)
1890 const char *p;
1891 char option[128];
1893 p = str;
1894 for(;;) {
1895 p = get_opt_name(option, sizeof(option), p);
1896 if (*p != '=')
1897 break;
1898 p++;
1899 if (!strcmp(tag, option)) {
1900 (void)get_opt_value(buf, buf_size, p);
1901 return strlen(buf);
1902 } else {
1903 p = get_opt_value(NULL, 0, p);
1905 if (*p != ',')
1906 break;
1907 p++;
1909 return 0;
1912 int check_params(char *buf, int buf_size,
1913 const char * const *params, const char *str)
1915 const char *p;
1916 int i;
1918 p = str;
1919 for(;;) {
1920 p = get_opt_name(buf, buf_size, p);
1921 if (*p != '=')
1922 return -1;
1923 p++;
1924 for(i = 0; params[i] != NULL; i++)
1925 if (!strcmp(params[i], buf))
1926 break;
1927 if (params[i] == NULL)
1928 return -1;
1929 p = get_opt_value(NULL, 0, p);
1930 if (*p != ',')
1931 break;
1932 p++;
1934 return 0;
1937 /***********************************************************/
1938 /* Bluetooth support */
1939 static int nb_hcis;
1940 static int cur_hci;
1941 static struct HCIInfo *hci_table[MAX_NICS];
1943 static struct bt_vlan_s {
1944 struct bt_scatternet_s net;
1945 int id;
1946 struct bt_vlan_s *next;
1947 } *first_bt_vlan;
1949 /* find or alloc a new bluetooth "VLAN" */
1950 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1952 struct bt_vlan_s **pvlan, *vlan;
1953 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1954 if (vlan->id == id)
1955 return &vlan->net;
1957 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1958 vlan->id = id;
1959 pvlan = &first_bt_vlan;
1960 while (*pvlan != NULL)
1961 pvlan = &(*pvlan)->next;
1962 *pvlan = vlan;
1963 return &vlan->net;
1966 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1970 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1972 return -ENOTSUP;
1975 static struct HCIInfo null_hci = {
1976 .cmd_send = null_hci_send,
1977 .sco_send = null_hci_send,
1978 .acl_send = null_hci_send,
1979 .bdaddr_set = null_hci_addr_set,
1982 struct HCIInfo *qemu_next_hci(void)
1984 if (cur_hci == nb_hcis)
1985 return &null_hci;
1987 return hci_table[cur_hci++];
1990 static struct HCIInfo *hci_init(const char *str)
1992 char *endp;
1993 struct bt_scatternet_s *vlan = 0;
1995 if (!strcmp(str, "null"))
1996 /* null */
1997 return &null_hci;
1998 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1999 /* host[:hciN] */
2000 return bt_host_hci(str[4] ? str + 5 : "hci0");
2001 else if (!strncmp(str, "hci", 3)) {
2002 /* hci[,vlan=n] */
2003 if (str[3]) {
2004 if (!strncmp(str + 3, ",vlan=", 6)) {
2005 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2006 if (*endp)
2007 vlan = 0;
2009 } else
2010 vlan = qemu_find_bt_vlan(0);
2011 if (vlan)
2012 return bt_new_hci(vlan);
2015 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2017 return 0;
2020 static int bt_hci_parse(const char *str)
2022 struct HCIInfo *hci;
2023 bdaddr_t bdaddr;
2025 if (nb_hcis >= MAX_NICS) {
2026 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2027 return -1;
2030 hci = hci_init(str);
2031 if (!hci)
2032 return -1;
2034 bdaddr.b[0] = 0x52;
2035 bdaddr.b[1] = 0x54;
2036 bdaddr.b[2] = 0x00;
2037 bdaddr.b[3] = 0x12;
2038 bdaddr.b[4] = 0x34;
2039 bdaddr.b[5] = 0x56 + nb_hcis;
2040 hci->bdaddr_set(hci, bdaddr.b);
2042 hci_table[nb_hcis++] = hci;
2044 return 0;
2047 static void bt_vhci_add(int vlan_id)
2049 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2051 if (!vlan->slave)
2052 fprintf(stderr, "qemu: warning: adding a VHCI to "
2053 "an empty scatternet %i\n", vlan_id);
2055 bt_vhci_init(bt_new_hci(vlan));
2058 static struct bt_device_s *bt_device_add(const char *opt)
2060 struct bt_scatternet_s *vlan;
2061 int vlan_id = 0;
2062 char *endp = strstr(opt, ",vlan=");
2063 int len = (endp ? endp - opt : strlen(opt)) + 1;
2064 char devname[10];
2066 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2068 if (endp) {
2069 vlan_id = strtol(endp + 6, &endp, 0);
2070 if (*endp) {
2071 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2072 return 0;
2076 vlan = qemu_find_bt_vlan(vlan_id);
2078 if (!vlan->slave)
2079 fprintf(stderr, "qemu: warning: adding a slave device to "
2080 "an empty scatternet %i\n", vlan_id);
2082 if (!strcmp(devname, "keyboard"))
2083 return bt_keyboard_init(vlan);
2085 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2086 return 0;
2089 static int bt_parse(const char *opt)
2091 const char *endp, *p;
2092 int vlan;
2094 if (strstart(opt, "hci", &endp)) {
2095 if (!*endp || *endp == ',') {
2096 if (*endp)
2097 if (!strstart(endp, ",vlan=", 0))
2098 opt = endp + 1;
2100 return bt_hci_parse(opt);
2102 } else if (strstart(opt, "vhci", &endp)) {
2103 if (!*endp || *endp == ',') {
2104 if (*endp) {
2105 if (strstart(endp, ",vlan=", &p)) {
2106 vlan = strtol(p, (char **) &endp, 0);
2107 if (*endp) {
2108 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2109 return 1;
2111 } else {
2112 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2113 return 1;
2115 } else
2116 vlan = 0;
2118 bt_vhci_add(vlan);
2119 return 0;
2121 } else if (strstart(opt, "device:", &endp))
2122 return !bt_device_add(endp);
2124 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2125 return 1;
2128 /***********************************************************/
2129 /* QEMU Block devices */
2131 #define HD_ALIAS "index=%d,media=disk"
2132 #ifdef TARGET_PPC
2133 #define CDROM_ALIAS "index=1,media=cdrom"
2134 #else
2135 #define CDROM_ALIAS "index=2,media=cdrom"
2136 #endif
2137 #define FD_ALIAS "index=%d,if=floppy"
2138 #define PFLASH_ALIAS "if=pflash"
2139 #define MTD_ALIAS "if=mtd"
2140 #define SD_ALIAS "index=0,if=sd"
2142 static int drive_add(const char *file, const char *fmt, ...)
2144 va_list ap;
2146 if (nb_drives_opt >= MAX_DRIVES) {
2147 fprintf(stderr, "qemu: too many drives\n");
2148 exit(1);
2151 drives_opt[nb_drives_opt].file = file;
2152 va_start(ap, fmt);
2153 vsnprintf(drives_opt[nb_drives_opt].opt,
2154 sizeof(drives_opt[0].opt), fmt, ap);
2155 va_end(ap);
2157 return nb_drives_opt++;
2160 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2162 int index;
2164 /* seek interface, bus and unit */
2166 for (index = 0; index < nb_drives; index++)
2167 if (drives_table[index].type == type &&
2168 drives_table[index].bus == bus &&
2169 drives_table[index].unit == unit)
2170 return index;
2172 return -1;
2175 int drive_get_max_bus(BlockInterfaceType type)
2177 int max_bus;
2178 int index;
2180 max_bus = -1;
2181 for (index = 0; index < nb_drives; index++) {
2182 if(drives_table[index].type == type &&
2183 drives_table[index].bus > max_bus)
2184 max_bus = drives_table[index].bus;
2186 return max_bus;
2189 const char *drive_get_serial(BlockDriverState *bdrv)
2191 int index;
2193 for (index = 0; index < nb_drives; index++)
2194 if (drives_table[index].bdrv == bdrv)
2195 return drives_table[index].serial;
2197 return "\0";
2200 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2202 int index;
2204 for (index = 0; index < nb_drives; index++)
2205 if (drives_table[index].bdrv == bdrv)
2206 return drives_table[index].onerror;
2208 return BLOCK_ERR_REPORT;
2211 static void bdrv_format_print(void *opaque, const char *name)
2213 fprintf(stderr, " %s", name);
2216 static int drive_init(struct drive_opt *arg, int snapshot,
2217 QEMUMachine *machine)
2219 char buf[128];
2220 char file[1024];
2221 char devname[128];
2222 char serial[21];
2223 const char *mediastr = "";
2224 BlockInterfaceType type;
2225 enum { MEDIA_DISK, MEDIA_CDROM } media;
2226 int bus_id, unit_id;
2227 int cyls, heads, secs, translation;
2228 BlockDriverState *bdrv;
2229 BlockDriver *drv = NULL;
2230 int max_devs;
2231 int index;
2232 int cache;
2233 int bdrv_flags, onerror;
2234 char *str = arg->opt;
2235 static const char * const params[] = { "bus", "unit", "if", "index",
2236 "cyls", "heads", "secs", "trans",
2237 "media", "snapshot", "file",
2238 "cache", "format", "serial", "werror",
2239 NULL };
2241 if (check_params(buf, sizeof(buf), params, str) < 0) {
2242 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2243 buf, str);
2244 return -1;
2247 file[0] = 0;
2248 cyls = heads = secs = 0;
2249 bus_id = 0;
2250 unit_id = -1;
2251 translation = BIOS_ATA_TRANSLATION_AUTO;
2252 index = -1;
2253 cache = 3;
2255 if (machine->use_scsi) {
2256 type = IF_SCSI;
2257 max_devs = MAX_SCSI_DEVS;
2258 pstrcpy(devname, sizeof(devname), "scsi");
2259 } else {
2260 type = IF_IDE;
2261 max_devs = MAX_IDE_DEVS;
2262 pstrcpy(devname, sizeof(devname), "ide");
2264 media = MEDIA_DISK;
2266 /* extract parameters */
2268 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2269 bus_id = strtol(buf, NULL, 0);
2270 if (bus_id < 0) {
2271 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2272 return -1;
2276 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2277 unit_id = strtol(buf, NULL, 0);
2278 if (unit_id < 0) {
2279 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2280 return -1;
2284 if (get_param_value(buf, sizeof(buf), "if", str)) {
2285 pstrcpy(devname, sizeof(devname), buf);
2286 if (!strcmp(buf, "ide")) {
2287 type = IF_IDE;
2288 max_devs = MAX_IDE_DEVS;
2289 } else if (!strcmp(buf, "scsi")) {
2290 type = IF_SCSI;
2291 max_devs = MAX_SCSI_DEVS;
2292 } else if (!strcmp(buf, "floppy")) {
2293 type = IF_FLOPPY;
2294 max_devs = 0;
2295 } else if (!strcmp(buf, "pflash")) {
2296 type = IF_PFLASH;
2297 max_devs = 0;
2298 } else if (!strcmp(buf, "mtd")) {
2299 type = IF_MTD;
2300 max_devs = 0;
2301 } else if (!strcmp(buf, "sd")) {
2302 type = IF_SD;
2303 max_devs = 0;
2304 } else if (!strcmp(buf, "virtio")) {
2305 type = IF_VIRTIO;
2306 max_devs = 0;
2307 } else {
2308 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2309 return -1;
2313 if (get_param_value(buf, sizeof(buf), "index", str)) {
2314 index = strtol(buf, NULL, 0);
2315 if (index < 0) {
2316 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2317 return -1;
2321 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2322 cyls = strtol(buf, NULL, 0);
2325 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2326 heads = strtol(buf, NULL, 0);
2329 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2330 secs = strtol(buf, NULL, 0);
2333 if (cyls || heads || secs) {
2334 if (cyls < 1 || cyls > 16383) {
2335 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2336 return -1;
2338 if (heads < 1 || heads > 16) {
2339 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2340 return -1;
2342 if (secs < 1 || secs > 63) {
2343 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2344 return -1;
2348 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2349 if (!cyls) {
2350 fprintf(stderr,
2351 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2352 str);
2353 return -1;
2355 if (!strcmp(buf, "none"))
2356 translation = BIOS_ATA_TRANSLATION_NONE;
2357 else if (!strcmp(buf, "lba"))
2358 translation = BIOS_ATA_TRANSLATION_LBA;
2359 else if (!strcmp(buf, "auto"))
2360 translation = BIOS_ATA_TRANSLATION_AUTO;
2361 else {
2362 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2363 return -1;
2367 if (get_param_value(buf, sizeof(buf), "media", str)) {
2368 if (!strcmp(buf, "disk")) {
2369 media = MEDIA_DISK;
2370 } else if (!strcmp(buf, "cdrom")) {
2371 if (cyls || secs || heads) {
2372 fprintf(stderr,
2373 "qemu: '%s' invalid physical CHS format\n", str);
2374 return -1;
2376 media = MEDIA_CDROM;
2377 } else {
2378 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2379 return -1;
2383 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2384 if (!strcmp(buf, "on"))
2385 snapshot = 1;
2386 else if (!strcmp(buf, "off"))
2387 snapshot = 0;
2388 else {
2389 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2390 return -1;
2394 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2395 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2396 cache = 0;
2397 else if (!strcmp(buf, "writethrough"))
2398 cache = 1;
2399 else if (!strcmp(buf, "writeback"))
2400 cache = 2;
2401 else {
2402 fprintf(stderr, "qemu: invalid cache option\n");
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "format", str)) {
2408 if (strcmp(buf, "?") == 0) {
2409 fprintf(stderr, "qemu: Supported formats:");
2410 bdrv_iterate_format(bdrv_format_print, NULL);
2411 fprintf(stderr, "\n");
2412 return -1;
2414 drv = bdrv_find_format(buf);
2415 if (!drv) {
2416 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2417 return -1;
2421 if (arg->file == NULL)
2422 get_param_value(file, sizeof(file), "file", str);
2423 else
2424 pstrcpy(file, sizeof(file), arg->file);
2426 if (!get_param_value(serial, sizeof(serial), "serial", str))
2427 memset(serial, 0, sizeof(serial));
2429 onerror = BLOCK_ERR_REPORT;
2430 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2431 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2432 fprintf(stderr, "werror is no supported by this format\n");
2433 return -1;
2435 if (!strcmp(buf, "ignore"))
2436 onerror = BLOCK_ERR_IGNORE;
2437 else if (!strcmp(buf, "enospc"))
2438 onerror = BLOCK_ERR_STOP_ENOSPC;
2439 else if (!strcmp(buf, "stop"))
2440 onerror = BLOCK_ERR_STOP_ANY;
2441 else if (!strcmp(buf, "report"))
2442 onerror = BLOCK_ERR_REPORT;
2443 else {
2444 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2445 return -1;
2449 /* compute bus and unit according index */
2451 if (index != -1) {
2452 if (bus_id != 0 || unit_id != -1) {
2453 fprintf(stderr,
2454 "qemu: '%s' index cannot be used with bus and unit\n", str);
2455 return -1;
2457 if (max_devs == 0)
2459 unit_id = index;
2460 bus_id = 0;
2461 } else {
2462 unit_id = index % max_devs;
2463 bus_id = index / max_devs;
2467 /* if user doesn't specify a unit_id,
2468 * try to find the first free
2471 if (unit_id == -1) {
2472 unit_id = 0;
2473 while (drive_get_index(type, bus_id, unit_id) != -1) {
2474 unit_id++;
2475 if (max_devs && unit_id >= max_devs) {
2476 unit_id -= max_devs;
2477 bus_id++;
2482 /* check unit id */
2484 if (max_devs && unit_id >= max_devs) {
2485 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2486 str, unit_id, max_devs - 1);
2487 return -1;
2491 * ignore multiple definitions
2494 if (drive_get_index(type, bus_id, unit_id) != -1)
2495 return 0;
2497 /* init */
2499 if (type == IF_IDE || type == IF_SCSI)
2500 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2501 if (max_devs)
2502 snprintf(buf, sizeof(buf), "%s%i%s%i",
2503 devname, bus_id, mediastr, unit_id);
2504 else
2505 snprintf(buf, sizeof(buf), "%s%s%i",
2506 devname, mediastr, unit_id);
2507 bdrv = bdrv_new(buf);
2508 drives_table[nb_drives].bdrv = bdrv;
2509 drives_table[nb_drives].type = type;
2510 drives_table[nb_drives].bus = bus_id;
2511 drives_table[nb_drives].unit = unit_id;
2512 drives_table[nb_drives].onerror = onerror;
2513 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2514 nb_drives++;
2516 switch(type) {
2517 case IF_IDE:
2518 case IF_SCSI:
2519 switch(media) {
2520 case MEDIA_DISK:
2521 if (cyls != 0) {
2522 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2523 bdrv_set_translation_hint(bdrv, translation);
2525 break;
2526 case MEDIA_CDROM:
2527 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2528 break;
2530 break;
2531 case IF_SD:
2532 /* FIXME: This isn't really a floppy, but it's a reasonable
2533 approximation. */
2534 case IF_FLOPPY:
2535 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2536 break;
2537 case IF_PFLASH:
2538 case IF_MTD:
2539 case IF_VIRTIO:
2540 break;
2542 if (!file[0])
2543 return 0;
2544 bdrv_flags = 0;
2545 if (snapshot) {
2546 bdrv_flags |= BDRV_O_SNAPSHOT;
2547 cache = 2; /* always use write-back with snapshot */
2549 if (cache == 0) /* no caching */
2550 bdrv_flags |= BDRV_O_NOCACHE;
2551 else if (cache == 2) /* write-back */
2552 bdrv_flags |= BDRV_O_CACHE_WB;
2553 else if (cache == 3) /* not specified */
2554 bdrv_flags |= BDRV_O_CACHE_DEF;
2555 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2556 fprintf(stderr, "qemu: could not open disk image %s\n",
2557 file);
2558 return -1;
2560 return 0;
2563 /***********************************************************/
2564 /* USB devices */
2566 static USBPort *used_usb_ports;
2567 static USBPort *free_usb_ports;
2569 /* ??? Maybe change this to register a hub to keep track of the topology. */
2570 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2571 usb_attachfn attach)
2573 port->opaque = opaque;
2574 port->index = index;
2575 port->attach = attach;
2576 port->next = free_usb_ports;
2577 free_usb_ports = port;
2580 int usb_device_add_dev(USBDevice *dev)
2582 USBPort *port;
2584 /* Find a USB port to add the device to. */
2585 port = free_usb_ports;
2586 if (!port->next) {
2587 USBDevice *hub;
2589 /* Create a new hub and chain it on. */
2590 free_usb_ports = NULL;
2591 port->next = used_usb_ports;
2592 used_usb_ports = port;
2594 hub = usb_hub_init(VM_USB_HUB_SIZE);
2595 usb_attach(port, hub);
2596 port = free_usb_ports;
2599 free_usb_ports = port->next;
2600 port->next = used_usb_ports;
2601 used_usb_ports = port;
2602 usb_attach(port, dev);
2603 return 0;
2606 static int usb_device_add(const char *devname)
2608 const char *p;
2609 USBDevice *dev;
2611 if (!free_usb_ports)
2612 return -1;
2614 if (strstart(devname, "host:", &p)) {
2615 dev = usb_host_device_open(p);
2616 } else if (!strcmp(devname, "mouse")) {
2617 dev = usb_mouse_init();
2618 } else if (!strcmp(devname, "tablet")) {
2619 dev = usb_tablet_init();
2620 } else if (!strcmp(devname, "keyboard")) {
2621 dev = usb_keyboard_init();
2622 } else if (strstart(devname, "disk:", &p)) {
2623 dev = usb_msd_init(p);
2624 } else if (!strcmp(devname, "wacom-tablet")) {
2625 dev = usb_wacom_init();
2626 } else if (strstart(devname, "serial:", &p)) {
2627 dev = usb_serial_init(p);
2628 #ifdef CONFIG_BRLAPI
2629 } else if (!strcmp(devname, "braille")) {
2630 dev = usb_baum_init();
2631 #endif
2632 } else if (strstart(devname, "net:", &p)) {
2633 int nic = nb_nics;
2635 if (net_client_init("nic", p) < 0)
2636 return -1;
2637 nd_table[nic].model = "usb";
2638 dev = usb_net_init(&nd_table[nic]);
2639 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2640 dev = usb_bt_init(devname[2] ? hci_init(p) :
2641 bt_new_hci(qemu_find_bt_vlan(0)));
2642 } else {
2643 return -1;
2645 if (!dev)
2646 return -1;
2648 return usb_device_add_dev(dev);
2651 int usb_device_del_addr(int bus_num, int addr)
2653 USBPort *port;
2654 USBPort **lastp;
2655 USBDevice *dev;
2657 if (!used_usb_ports)
2658 return -1;
2660 if (bus_num != 0)
2661 return -1;
2663 lastp = &used_usb_ports;
2664 port = used_usb_ports;
2665 while (port && port->dev->addr != addr) {
2666 lastp = &port->next;
2667 port = port->next;
2670 if (!port)
2671 return -1;
2673 dev = port->dev;
2674 *lastp = port->next;
2675 usb_attach(port, NULL);
2676 dev->handle_destroy(dev);
2677 port->next = free_usb_ports;
2678 free_usb_ports = port;
2679 return 0;
2682 static int usb_device_del(const char *devname)
2684 int bus_num, addr;
2685 const char *p;
2687 if (strstart(devname, "host:", &p))
2688 return usb_host_device_close(p);
2690 if (!used_usb_ports)
2691 return -1;
2693 p = strchr(devname, '.');
2694 if (!p)
2695 return -1;
2696 bus_num = strtoul(devname, NULL, 0);
2697 addr = strtoul(p + 1, NULL, 0);
2699 return usb_device_del_addr(bus_num, addr);
2702 void do_usb_add(const char *devname)
2704 usb_device_add(devname);
2707 void do_usb_del(const char *devname)
2709 usb_device_del(devname);
2712 void usb_info(void)
2714 USBDevice *dev;
2715 USBPort *port;
2716 const char *speed_str;
2718 if (!usb_enabled) {
2719 term_printf("USB support not enabled\n");
2720 return;
2723 for (port = used_usb_ports; port; port = port->next) {
2724 dev = port->dev;
2725 if (!dev)
2726 continue;
2727 switch(dev->speed) {
2728 case USB_SPEED_LOW:
2729 speed_str = "1.5";
2730 break;
2731 case USB_SPEED_FULL:
2732 speed_str = "12";
2733 break;
2734 case USB_SPEED_HIGH:
2735 speed_str = "480";
2736 break;
2737 default:
2738 speed_str = "?";
2739 break;
2741 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2742 0, dev->addr, speed_str, dev->devname);
2746 /***********************************************************/
2747 /* PCMCIA/Cardbus */
2749 static struct pcmcia_socket_entry_s {
2750 struct pcmcia_socket_s *socket;
2751 struct pcmcia_socket_entry_s *next;
2752 } *pcmcia_sockets = 0;
2754 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2756 struct pcmcia_socket_entry_s *entry;
2758 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2759 entry->socket = socket;
2760 entry->next = pcmcia_sockets;
2761 pcmcia_sockets = entry;
2764 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2766 struct pcmcia_socket_entry_s *entry, **ptr;
2768 ptr = &pcmcia_sockets;
2769 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2770 if (entry->socket == socket) {
2771 *ptr = entry->next;
2772 qemu_free(entry);
2776 void pcmcia_info(void)
2778 struct pcmcia_socket_entry_s *iter;
2779 if (!pcmcia_sockets)
2780 term_printf("No PCMCIA sockets\n");
2782 for (iter = pcmcia_sockets; iter; iter = iter->next)
2783 term_printf("%s: %s\n", iter->socket->slot_string,
2784 iter->socket->attached ? iter->socket->card_string :
2785 "Empty");
2788 /***********************************************************/
2789 /* register display */
2791 void register_displaystate(DisplayState *ds)
2793 DisplayState **s;
2794 s = &display_state;
2795 while (*s != NULL)
2796 s = &(*s)->next;
2797 ds->next = NULL;
2798 *s = ds;
2801 DisplayState *get_displaystate(void)
2803 return display_state;
2806 /* dumb display */
2808 static void dumb_display_init(void)
2810 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2811 if (ds == NULL) {
2812 fprintf(stderr, "dumb_display_init: DisplayState allocation failed\n");
2813 exit(1);
2815 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2816 register_displaystate(ds);
2819 /***********************************************************/
2820 /* I/O handling */
2822 #define MAX_IO_HANDLERS 64
2824 typedef struct IOHandlerRecord {
2825 int fd;
2826 IOCanRWHandler *fd_read_poll;
2827 IOHandler *fd_read;
2828 IOHandler *fd_write;
2829 int deleted;
2830 void *opaque;
2831 /* temporary data */
2832 struct pollfd *ufd;
2833 struct IOHandlerRecord *next;
2834 } IOHandlerRecord;
2836 static IOHandlerRecord *first_io_handler;
2838 /* XXX: fd_read_poll should be suppressed, but an API change is
2839 necessary in the character devices to suppress fd_can_read(). */
2840 int qemu_set_fd_handler2(int fd,
2841 IOCanRWHandler *fd_read_poll,
2842 IOHandler *fd_read,
2843 IOHandler *fd_write,
2844 void *opaque)
2846 IOHandlerRecord **pioh, *ioh;
2848 if (!fd_read && !fd_write) {
2849 pioh = &first_io_handler;
2850 for(;;) {
2851 ioh = *pioh;
2852 if (ioh == NULL)
2853 break;
2854 if (ioh->fd == fd) {
2855 ioh->deleted = 1;
2856 break;
2858 pioh = &ioh->next;
2860 } else {
2861 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2862 if (ioh->fd == fd)
2863 goto found;
2865 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2866 if (!ioh)
2867 return -1;
2868 ioh->next = first_io_handler;
2869 first_io_handler = ioh;
2870 found:
2871 ioh->fd = fd;
2872 ioh->fd_read_poll = fd_read_poll;
2873 ioh->fd_read = fd_read;
2874 ioh->fd_write = fd_write;
2875 ioh->opaque = opaque;
2876 ioh->deleted = 0;
2878 return 0;
2881 int qemu_set_fd_handler(int fd,
2882 IOHandler *fd_read,
2883 IOHandler *fd_write,
2884 void *opaque)
2886 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2889 #ifdef _WIN32
2890 /***********************************************************/
2891 /* Polling handling */
2893 typedef struct PollingEntry {
2894 PollingFunc *func;
2895 void *opaque;
2896 struct PollingEntry *next;
2897 } PollingEntry;
2899 static PollingEntry *first_polling_entry;
2901 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2903 PollingEntry **ppe, *pe;
2904 pe = qemu_mallocz(sizeof(PollingEntry));
2905 if (!pe)
2906 return -1;
2907 pe->func = func;
2908 pe->opaque = opaque;
2909 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2910 *ppe = pe;
2911 return 0;
2914 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2916 PollingEntry **ppe, *pe;
2917 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2918 pe = *ppe;
2919 if (pe->func == func && pe->opaque == opaque) {
2920 *ppe = pe->next;
2921 qemu_free(pe);
2922 break;
2927 /***********************************************************/
2928 /* Wait objects support */
2929 typedef struct WaitObjects {
2930 int num;
2931 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2932 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2933 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2934 } WaitObjects;
2936 static WaitObjects wait_objects = {0};
2938 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2940 WaitObjects *w = &wait_objects;
2942 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2943 return -1;
2944 w->events[w->num] = handle;
2945 w->func[w->num] = func;
2946 w->opaque[w->num] = opaque;
2947 w->num++;
2948 return 0;
2951 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2953 int i, found;
2954 WaitObjects *w = &wait_objects;
2956 found = 0;
2957 for (i = 0; i < w->num; i++) {
2958 if (w->events[i] == handle)
2959 found = 1;
2960 if (found) {
2961 w->events[i] = w->events[i + 1];
2962 w->func[i] = w->func[i + 1];
2963 w->opaque[i] = w->opaque[i + 1];
2966 if (found)
2967 w->num--;
2969 #endif
2971 /***********************************************************/
2972 /* ram save/restore */
2974 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2976 int v;
2978 v = qemu_get_byte(f);
2979 switch(v) {
2980 case 0:
2981 if (qemu_get_buffer(f, buf, len) != len)
2982 return -EIO;
2983 break;
2984 case 1:
2985 v = qemu_get_byte(f);
2986 memset(buf, v, len);
2987 break;
2988 default:
2989 return -EINVAL;
2992 if (qemu_file_has_error(f))
2993 return -EIO;
2995 return 0;
2998 static int ram_load_v1(QEMUFile *f, void *opaque)
3000 int ret;
3001 ram_addr_t i;
3003 if (qemu_get_be32(f) != phys_ram_size)
3004 return -EINVAL;
3005 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3006 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3007 if (ret)
3008 return ret;
3010 return 0;
3013 #define BDRV_HASH_BLOCK_SIZE 1024
3014 #define IOBUF_SIZE 4096
3015 #define RAM_CBLOCK_MAGIC 0xfabe
3017 typedef struct RamDecompressState {
3018 z_stream zstream;
3019 QEMUFile *f;
3020 uint8_t buf[IOBUF_SIZE];
3021 } RamDecompressState;
3023 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3025 int ret;
3026 memset(s, 0, sizeof(*s));
3027 s->f = f;
3028 ret = inflateInit(&s->zstream);
3029 if (ret != Z_OK)
3030 return -1;
3031 return 0;
3034 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3036 int ret, clen;
3038 s->zstream.avail_out = len;
3039 s->zstream.next_out = buf;
3040 while (s->zstream.avail_out > 0) {
3041 if (s->zstream.avail_in == 0) {
3042 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3043 return -1;
3044 clen = qemu_get_be16(s->f);
3045 if (clen > IOBUF_SIZE)
3046 return -1;
3047 qemu_get_buffer(s->f, s->buf, clen);
3048 s->zstream.avail_in = clen;
3049 s->zstream.next_in = s->buf;
3051 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3052 if (ret != Z_OK && ret != Z_STREAM_END) {
3053 return -1;
3056 return 0;
3059 static void ram_decompress_close(RamDecompressState *s)
3061 inflateEnd(&s->zstream);
3064 #define RAM_SAVE_FLAG_FULL 0x01
3065 #define RAM_SAVE_FLAG_COMPRESS 0x02
3066 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3067 #define RAM_SAVE_FLAG_PAGE 0x08
3068 #define RAM_SAVE_FLAG_EOS 0x10
3070 static int is_dup_page(uint8_t *page, uint8_t ch)
3072 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3073 uint32_t *array = (uint32_t *)page;
3074 int i;
3076 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3077 if (array[i] != val)
3078 return 0;
3081 return 1;
3084 static int ram_save_block(QEMUFile *f)
3086 static ram_addr_t current_addr = 0;
3087 ram_addr_t saved_addr = current_addr;
3088 ram_addr_t addr = 0;
3089 int found = 0;
3091 while (addr < phys_ram_size) {
3092 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3093 uint8_t ch;
3095 cpu_physical_memory_reset_dirty(current_addr,
3096 current_addr + TARGET_PAGE_SIZE,
3097 MIGRATION_DIRTY_FLAG);
3099 ch = *(phys_ram_base + current_addr);
3101 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3102 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3103 qemu_put_byte(f, ch);
3104 } else {
3105 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3106 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3109 found = 1;
3110 break;
3112 addr += TARGET_PAGE_SIZE;
3113 current_addr = (saved_addr + addr) % phys_ram_size;
3116 return found;
3119 static ram_addr_t ram_save_threshold = 10;
3121 static ram_addr_t ram_save_remaining(void)
3123 ram_addr_t addr;
3124 ram_addr_t count = 0;
3126 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3127 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3128 count++;
3131 return count;
3134 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3136 ram_addr_t addr;
3138 if (stage == 1) {
3139 /* Make sure all dirty bits are set */
3140 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3141 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3142 cpu_physical_memory_set_dirty(addr);
3145 /* Enable dirty memory tracking */
3146 cpu_physical_memory_set_dirty_tracking(1);
3148 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3151 while (!qemu_file_rate_limit(f)) {
3152 int ret;
3154 ret = ram_save_block(f);
3155 if (ret == 0) /* no more blocks */
3156 break;
3159 /* try transferring iterative blocks of memory */
3161 if (stage == 3) {
3162 cpu_physical_memory_set_dirty_tracking(0);
3164 /* flush all remaining blocks regardless of rate limiting */
3165 while (ram_save_block(f) != 0);
3168 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3170 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3173 static int ram_load_dead(QEMUFile *f, void *opaque)
3175 RamDecompressState s1, *s = &s1;
3176 uint8_t buf[10];
3177 ram_addr_t i;
3179 if (ram_decompress_open(s, f) < 0)
3180 return -EINVAL;
3181 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3182 if (ram_decompress_buf(s, buf, 1) < 0) {
3183 fprintf(stderr, "Error while reading ram block header\n");
3184 goto error;
3186 if (buf[0] == 0) {
3187 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3188 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3189 goto error;
3191 } else {
3192 error:
3193 printf("Error block header\n");
3194 return -EINVAL;
3197 ram_decompress_close(s);
3199 return 0;
3202 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3204 ram_addr_t addr;
3205 int flags;
3207 if (version_id == 1)
3208 return ram_load_v1(f, opaque);
3210 if (version_id == 2) {
3211 if (qemu_get_be32(f) != phys_ram_size)
3212 return -EINVAL;
3213 return ram_load_dead(f, opaque);
3216 if (version_id != 3)
3217 return -EINVAL;
3219 do {
3220 addr = qemu_get_be64(f);
3222 flags = addr & ~TARGET_PAGE_MASK;
3223 addr &= TARGET_PAGE_MASK;
3225 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3226 if (addr != phys_ram_size)
3227 return -EINVAL;
3230 if (flags & RAM_SAVE_FLAG_FULL) {
3231 if (ram_load_dead(f, opaque) < 0)
3232 return -EINVAL;
3235 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3236 uint8_t ch = qemu_get_byte(f);
3237 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3238 } else if (flags & RAM_SAVE_FLAG_PAGE)
3239 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3240 } while (!(flags & RAM_SAVE_FLAG_EOS));
3242 return 0;
3245 void qemu_service_io(void)
3247 CPUState *env = cpu_single_env;
3248 if (env) {
3249 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3250 #ifdef USE_KQEMU
3251 if (env->kqemu_enabled) {
3252 kqemu_cpu_interrupt(env);
3254 #endif
3258 /***********************************************************/
3259 /* bottom halves (can be seen as timers which expire ASAP) */
3261 struct QEMUBH {
3262 QEMUBHFunc *cb;
3263 void *opaque;
3264 int scheduled;
3265 int idle;
3266 int deleted;
3267 QEMUBH *next;
3270 static QEMUBH *first_bh = NULL;
3272 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3274 QEMUBH *bh;
3275 bh = qemu_mallocz(sizeof(QEMUBH));
3276 if (!bh)
3277 return NULL;
3278 bh->cb = cb;
3279 bh->opaque = opaque;
3280 bh->next = first_bh;
3281 first_bh = bh;
3282 return bh;
3285 int qemu_bh_poll(void)
3287 QEMUBH *bh, **bhp;
3288 int ret;
3290 ret = 0;
3291 for (bh = first_bh; bh; bh = bh->next) {
3292 if (!bh->deleted && bh->scheduled) {
3293 bh->scheduled = 0;
3294 if (!bh->idle)
3295 ret = 1;
3296 bh->idle = 0;
3297 bh->cb(bh->opaque);
3301 /* remove deleted bhs */
3302 bhp = &first_bh;
3303 while (*bhp) {
3304 bh = *bhp;
3305 if (bh->deleted) {
3306 *bhp = bh->next;
3307 qemu_free(bh);
3308 } else
3309 bhp = &bh->next;
3312 return ret;
3315 void qemu_bh_schedule_idle(QEMUBH *bh)
3317 if (bh->scheduled)
3318 return;
3319 bh->scheduled = 1;
3320 bh->idle = 1;
3323 void qemu_bh_schedule(QEMUBH *bh)
3325 CPUState *env = cpu_single_env;
3326 if (bh->scheduled)
3327 return;
3328 bh->scheduled = 1;
3329 bh->idle = 0;
3330 /* stop the currently executing CPU to execute the BH ASAP */
3331 if (env) {
3332 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3336 void qemu_bh_cancel(QEMUBH *bh)
3338 bh->scheduled = 0;
3341 void qemu_bh_delete(QEMUBH *bh)
3343 bh->scheduled = 0;
3344 bh->deleted = 1;
3347 static void qemu_bh_update_timeout(int *timeout)
3349 QEMUBH *bh;
3351 for (bh = first_bh; bh; bh = bh->next) {
3352 if (!bh->deleted && bh->scheduled) {
3353 if (bh->idle) {
3354 /* idle bottom halves will be polled at least
3355 * every 10ms */
3356 *timeout = MIN(10, *timeout);
3357 } else {
3358 /* non-idle bottom halves will be executed
3359 * immediately */
3360 *timeout = 0;
3361 break;
3367 /***********************************************************/
3368 /* machine registration */
3370 static QEMUMachine *first_machine = NULL;
3372 int qemu_register_machine(QEMUMachine *m)
3374 QEMUMachine **pm;
3375 pm = &first_machine;
3376 while (*pm != NULL)
3377 pm = &(*pm)->next;
3378 m->next = NULL;
3379 *pm = m;
3380 return 0;
3383 static QEMUMachine *find_machine(const char *name)
3385 QEMUMachine *m;
3387 for(m = first_machine; m != NULL; m = m->next) {
3388 if (!strcmp(m->name, name))
3389 return m;
3391 return NULL;
3394 /***********************************************************/
3395 /* main execution loop */
3397 static void gui_update(void *opaque)
3399 uint64_t interval = GUI_REFRESH_INTERVAL;
3400 DisplayState *ds = opaque;
3401 DisplayChangeListener *dcl = ds->listeners;
3403 dpy_refresh(ds);
3405 while (dcl != NULL) {
3406 if (dcl->gui_timer_interval &&
3407 dcl->gui_timer_interval < interval)
3408 interval = dcl->gui_timer_interval;
3409 dcl = dcl->next;
3411 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3414 static void nographic_update(void *opaque)
3416 uint64_t interval = GUI_REFRESH_INTERVAL;
3418 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3421 struct vm_change_state_entry {
3422 VMChangeStateHandler *cb;
3423 void *opaque;
3424 LIST_ENTRY (vm_change_state_entry) entries;
3427 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3429 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3430 void *opaque)
3432 VMChangeStateEntry *e;
3434 e = qemu_mallocz(sizeof (*e));
3435 if (!e)
3436 return NULL;
3438 e->cb = cb;
3439 e->opaque = opaque;
3440 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3441 return e;
3444 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3446 LIST_REMOVE (e, entries);
3447 qemu_free (e);
3450 static void vm_state_notify(int running, int reason)
3452 VMChangeStateEntry *e;
3454 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3455 e->cb(e->opaque, running, reason);
3459 void vm_start(void)
3461 if (!vm_running) {
3462 cpu_enable_ticks();
3463 vm_running = 1;
3464 vm_state_notify(1, 0);
3465 qemu_rearm_alarm_timer(alarm_timer);
3469 void vm_stop(int reason)
3471 if (vm_running) {
3472 cpu_disable_ticks();
3473 vm_running = 0;
3474 vm_state_notify(0, reason);
3478 /* reset/shutdown handler */
3480 typedef struct QEMUResetEntry {
3481 QEMUResetHandler *func;
3482 void *opaque;
3483 struct QEMUResetEntry *next;
3484 } QEMUResetEntry;
3486 static QEMUResetEntry *first_reset_entry;
3487 static int reset_requested;
3488 static int shutdown_requested;
3489 static int powerdown_requested;
3491 int qemu_shutdown_requested(void)
3493 int r = shutdown_requested;
3494 shutdown_requested = 0;
3495 return r;
3498 int qemu_reset_requested(void)
3500 int r = reset_requested;
3501 reset_requested = 0;
3502 return r;
3505 int qemu_powerdown_requested(void)
3507 int r = powerdown_requested;
3508 powerdown_requested = 0;
3509 return r;
3512 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3514 QEMUResetEntry **pre, *re;
3516 pre = &first_reset_entry;
3517 while (*pre != NULL)
3518 pre = &(*pre)->next;
3519 re = qemu_mallocz(sizeof(QEMUResetEntry));
3520 re->func = func;
3521 re->opaque = opaque;
3522 re->next = NULL;
3523 *pre = re;
3526 void qemu_system_reset(void)
3528 QEMUResetEntry *re;
3530 /* reset all devices */
3531 for(re = first_reset_entry; re != NULL; re = re->next) {
3532 re->func(re->opaque);
3536 void qemu_system_reset_request(void)
3538 if (no_reboot) {
3539 shutdown_requested = 1;
3540 } else {
3541 reset_requested = 1;
3543 if (cpu_single_env)
3544 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3547 void qemu_system_shutdown_request(void)
3549 shutdown_requested = 1;
3550 if (cpu_single_env)
3551 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3554 void qemu_system_powerdown_request(void)
3556 powerdown_requested = 1;
3557 if (cpu_single_env)
3558 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3561 #ifdef _WIN32
3562 static void host_main_loop_wait(int *timeout)
3564 int ret, ret2, i;
3565 PollingEntry *pe;
3568 /* XXX: need to suppress polling by better using win32 events */
3569 ret = 0;
3570 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3571 ret |= pe->func(pe->opaque);
3573 if (ret == 0) {
3574 int err;
3575 WaitObjects *w = &wait_objects;
3577 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3578 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3579 if (w->func[ret - WAIT_OBJECT_0])
3580 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3582 /* Check for additional signaled events */
3583 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3585 /* Check if event is signaled */
3586 ret2 = WaitForSingleObject(w->events[i], 0);
3587 if(ret2 == WAIT_OBJECT_0) {
3588 if (w->func[i])
3589 w->func[i](w->opaque[i]);
3590 } else if (ret2 == WAIT_TIMEOUT) {
3591 } else {
3592 err = GetLastError();
3593 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3596 } else if (ret == WAIT_TIMEOUT) {
3597 } else {
3598 err = GetLastError();
3599 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3603 *timeout = 0;
3605 #else
3606 static void host_main_loop_wait(int *timeout)
3609 #endif
3611 void main_loop_wait(int timeout)
3613 IOHandlerRecord *ioh;
3614 fd_set rfds, wfds, xfds;
3615 int ret, nfds;
3616 struct timeval tv;
3618 qemu_bh_update_timeout(&timeout);
3620 host_main_loop_wait(&timeout);
3622 /* poll any events */
3623 /* XXX: separate device handlers from system ones */
3624 nfds = -1;
3625 FD_ZERO(&rfds);
3626 FD_ZERO(&wfds);
3627 FD_ZERO(&xfds);
3628 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3629 if (ioh->deleted)
3630 continue;
3631 if (ioh->fd_read &&
3632 (!ioh->fd_read_poll ||
3633 ioh->fd_read_poll(ioh->opaque) != 0)) {
3634 FD_SET(ioh->fd, &rfds);
3635 if (ioh->fd > nfds)
3636 nfds = ioh->fd;
3638 if (ioh->fd_write) {
3639 FD_SET(ioh->fd, &wfds);
3640 if (ioh->fd > nfds)
3641 nfds = ioh->fd;
3645 tv.tv_sec = timeout / 1000;
3646 tv.tv_usec = (timeout % 1000) * 1000;
3648 #if defined(CONFIG_SLIRP)
3649 if (slirp_is_inited()) {
3650 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3652 #endif
3653 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3654 if (ret > 0) {
3655 IOHandlerRecord **pioh;
3657 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3658 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3659 ioh->fd_read(ioh->opaque);
3661 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3662 ioh->fd_write(ioh->opaque);
3666 /* remove deleted IO handlers */
3667 pioh = &first_io_handler;
3668 while (*pioh) {
3669 ioh = *pioh;
3670 if (ioh->deleted) {
3671 *pioh = ioh->next;
3672 qemu_free(ioh);
3673 } else
3674 pioh = &ioh->next;
3677 #if defined(CONFIG_SLIRP)
3678 if (slirp_is_inited()) {
3679 if (ret < 0) {
3680 FD_ZERO(&rfds);
3681 FD_ZERO(&wfds);
3682 FD_ZERO(&xfds);
3684 slirp_select_poll(&rfds, &wfds, &xfds);
3686 #endif
3688 /* vm time timers */
3689 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3690 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3691 qemu_get_clock(vm_clock));
3693 /* real time timers */
3694 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3695 qemu_get_clock(rt_clock));
3697 /* Check bottom-halves last in case any of the earlier events triggered
3698 them. */
3699 qemu_bh_poll();
3703 static int main_loop(void)
3705 int ret, timeout;
3706 #ifdef CONFIG_PROFILER
3707 int64_t ti;
3708 #endif
3709 CPUState *env;
3711 cur_cpu = first_cpu;
3712 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3713 for(;;) {
3714 if (vm_running) {
3716 for(;;) {
3717 /* get next cpu */
3718 env = next_cpu;
3719 #ifdef CONFIG_PROFILER
3720 ti = profile_getclock();
3721 #endif
3722 if (use_icount) {
3723 int64_t count;
3724 int decr;
3725 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3726 env->icount_decr.u16.low = 0;
3727 env->icount_extra = 0;
3728 count = qemu_next_deadline();
3729 count = (count + (1 << icount_time_shift) - 1)
3730 >> icount_time_shift;
3731 qemu_icount += count;
3732 decr = (count > 0xffff) ? 0xffff : count;
3733 count -= decr;
3734 env->icount_decr.u16.low = decr;
3735 env->icount_extra = count;
3737 ret = cpu_exec(env);
3738 #ifdef CONFIG_PROFILER
3739 qemu_time += profile_getclock() - ti;
3740 #endif
3741 if (use_icount) {
3742 /* Fold pending instructions back into the
3743 instruction counter, and clear the interrupt flag. */
3744 qemu_icount -= (env->icount_decr.u16.low
3745 + env->icount_extra);
3746 env->icount_decr.u32 = 0;
3747 env->icount_extra = 0;
3749 next_cpu = env->next_cpu ?: first_cpu;
3750 if (event_pending && likely(ret != EXCP_DEBUG)) {
3751 ret = EXCP_INTERRUPT;
3752 event_pending = 0;
3753 break;
3755 if (ret == EXCP_HLT) {
3756 /* Give the next CPU a chance to run. */
3757 cur_cpu = env;
3758 continue;
3760 if (ret != EXCP_HALTED)
3761 break;
3762 /* all CPUs are halted ? */
3763 if (env == cur_cpu)
3764 break;
3766 cur_cpu = env;
3768 if (shutdown_requested) {
3769 ret = EXCP_INTERRUPT;
3770 if (no_shutdown) {
3771 vm_stop(0);
3772 no_shutdown = 0;
3774 else
3775 break;
3777 if (reset_requested) {
3778 reset_requested = 0;
3779 qemu_system_reset();
3780 ret = EXCP_INTERRUPT;
3782 if (powerdown_requested) {
3783 powerdown_requested = 0;
3784 qemu_system_powerdown();
3785 ret = EXCP_INTERRUPT;
3787 if (unlikely(ret == EXCP_DEBUG)) {
3788 gdb_set_stop_cpu(cur_cpu);
3789 vm_stop(EXCP_DEBUG);
3791 /* If all cpus are halted then wait until the next IRQ */
3792 /* XXX: use timeout computed from timers */
3793 if (ret == EXCP_HALTED) {
3794 if (use_icount) {
3795 int64_t add;
3796 int64_t delta;
3797 /* Advance virtual time to the next event. */
3798 if (use_icount == 1) {
3799 /* When not using an adaptive execution frequency
3800 we tend to get badly out of sync with real time,
3801 so just delay for a reasonable amount of time. */
3802 delta = 0;
3803 } else {
3804 delta = cpu_get_icount() - cpu_get_clock();
3806 if (delta > 0) {
3807 /* If virtual time is ahead of real time then just
3808 wait for IO. */
3809 timeout = (delta / 1000000) + 1;
3810 } else {
3811 /* Wait for either IO to occur or the next
3812 timer event. */
3813 add = qemu_next_deadline();
3814 /* We advance the timer before checking for IO.
3815 Limit the amount we advance so that early IO
3816 activity won't get the guest too far ahead. */
3817 if (add > 10000000)
3818 add = 10000000;
3819 delta += add;
3820 add = (add + (1 << icount_time_shift) - 1)
3821 >> icount_time_shift;
3822 qemu_icount += add;
3823 timeout = delta / 1000000;
3824 if (timeout < 0)
3825 timeout = 0;
3827 } else {
3828 timeout = 5000;
3830 } else {
3831 timeout = 0;
3833 } else {
3834 if (shutdown_requested) {
3835 ret = EXCP_INTERRUPT;
3836 break;
3838 timeout = 5000;
3840 #ifdef CONFIG_PROFILER
3841 ti = profile_getclock();
3842 #endif
3843 main_loop_wait(timeout);
3844 #ifdef CONFIG_PROFILER
3845 dev_time += profile_getclock() - ti;
3846 #endif
3848 cpu_disable_ticks();
3849 return ret;
3852 static void help(int exitcode)
3854 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3855 and qemu-doc.texi */
3856 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3857 "usage: %s [options] [disk_image]\n"
3858 "\n"
3859 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3860 "\n"
3861 "Standard options:\n"
3862 "-h or -help display this help and exit\n"
3863 "-M machine select emulated machine (-M ? for list)\n"
3864 "-cpu cpu select CPU (-cpu ? for list)\n"
3865 "-smp n set the number of CPUs to 'n' [default=1]\n"
3866 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3867 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3868 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3869 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3870 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3871 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3872 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3873 " use 'file' as a drive image\n"
3874 "-mtdblock file use 'file' as on-board Flash memory image\n"
3875 "-sd file use 'file' as SecureDigital card image\n"
3876 "-pflash file use 'file' as a parallel flash image\n"
3877 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3878 "-snapshot write to temporary files instead of disk image files\n"
3879 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3880 #ifndef _WIN32
3881 "-k language use keyboard layout (for example \"fr\" for French)\n"
3882 #endif
3883 #ifdef HAS_AUDIO
3884 "-audio-help print list of audio drivers and their options\n"
3885 "-soundhw c1,... enable audio support\n"
3886 " and only specified sound cards (comma separated list)\n"
3887 " use -soundhw ? to get the list of supported cards\n"
3888 " use -soundhw all to enable all of them\n"
3889 #endif
3890 "-usb enable the USB driver (will be the default soon)\n"
3891 "-usbdevice name add the host or guest USB device 'name'\n"
3892 "-name string set the name of the guest\n"
3893 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3894 " specify machine UUID\n"
3895 "\n"
3896 "Display options:\n"
3897 "-nographic disable graphical output and redirect serial I/Os to console\n"
3898 #ifdef CONFIG_CURSES
3899 "-curses use a curses/ncurses interface instead of SDL\n"
3900 #endif
3901 #ifdef CONFIG_SDL
3902 "-no-frame open SDL window without a frame and window decorations\n"
3903 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3904 "-no-quit disable SDL window close capability\n"
3905 "-sdl enable SDL\n"
3906 #endif
3907 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3908 "-vga [std|cirrus|vmware|none]\n"
3909 " select video card type\n"
3910 "-full-screen start in full screen\n"
3911 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3912 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3913 #endif
3914 "-vnc display start a VNC server on display\n"
3915 "\n"
3916 "Network options:\n"
3917 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3918 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3919 #ifdef CONFIG_SLIRP
3920 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3921 " connect the user mode network stack to VLAN 'n' and send\n"
3922 " hostname 'host' to DHCP clients\n"
3923 #endif
3924 #ifdef _WIN32
3925 "-net tap[,vlan=n][,name=str],ifname=name\n"
3926 " connect the host TAP network interface to VLAN 'n'\n"
3927 #else
3928 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3929 " connect the host TAP network interface to VLAN 'n' and use the\n"
3930 " network scripts 'file' (default=%s)\n"
3931 " and 'dfile' (default=%s);\n"
3932 " use '[down]script=no' to disable script execution;\n"
3933 " use 'fd=h' to connect to an already opened TAP interface\n"
3934 #endif
3935 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3936 " connect the vlan 'n' to another VLAN using a socket connection\n"
3937 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3938 " connect the vlan 'n' to multicast maddr and port\n"
3939 #ifdef CONFIG_VDE
3940 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3941 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3942 " on host and listening for incoming connections on 'socketpath'.\n"
3943 " Use group 'groupname' and mode 'octalmode' to change default\n"
3944 " ownership and permissions for communication port.\n"
3945 #endif
3946 "-net none use it alone to have zero network devices; if no -net option\n"
3947 " is provided, the default is '-net nic -net user'\n"
3948 #ifdef CONFIG_SLIRP
3949 "-tftp dir allow tftp access to files in dir [-net user]\n"
3950 "-bootp file advertise file in BOOTP replies\n"
3951 #ifndef _WIN32
3952 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3953 #endif
3954 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3955 " redirect TCP or UDP connections from host to guest [-net user]\n"
3956 #endif
3957 "\n"
3958 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
3959 "-bt hci,host[:id]\n"
3960 " use host's HCI with the given name\n"
3961 "-bt hci[,vlan=n]\n"
3962 " emulate a standard HCI in virtual scatternet 'n'\n"
3963 "-bt vhci[,vlan=n]\n"
3964 " add host computer to virtual scatternet 'n' using VHCI\n"
3965 "-bt device:dev[,vlan=n]\n"
3966 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
3967 "\n"
3968 #ifdef TARGET_I386
3969 "\n"
3970 "i386 target only:\n"
3971 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3972 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
3973 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3974 "-no-acpi disable ACPI\n"
3975 "-no-hpet disable HPET\n"
3976 #endif
3977 "Linux boot specific:\n"
3978 "-kernel bzImage use 'bzImage' as kernel image\n"
3979 "-append cmdline use 'cmdline' as kernel command line\n"
3980 "-initrd file use 'file' as initial ram disk\n"
3981 "\n"
3982 "Debug/Expert options:\n"
3983 "-serial dev redirect the serial port to char device 'dev'\n"
3984 "-parallel dev redirect the parallel port to char device 'dev'\n"
3985 "-monitor dev redirect the monitor to char device 'dev'\n"
3986 "-pidfile file write PID to 'file'\n"
3987 "-S freeze CPU at startup (use 'c' to start execution)\n"
3988 "-s wait gdb connection to port\n"
3989 "-p port set gdb connection port [default=%s]\n"
3990 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3991 "-hdachs c,h,s[,t]\n"
3992 " force hard disk 0 physical geometry and the optional BIOS\n"
3993 " translation (t=none or lba) (usually qemu can guess them)\n"
3994 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
3995 "-bios file set the filename for the BIOS\n"
3996 #ifdef USE_KQEMU
3997 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
3998 "-no-kqemu disable KQEMU kernel module usage\n"
3999 #endif
4000 #ifdef CONFIG_KVM
4001 "-enable-kvm enable KVM full virtualization support\n"
4002 #endif
4003 "-no-reboot exit instead of rebooting\n"
4004 "-no-shutdown stop before shutdown\n"
4005 "-loadvm [tag|id]\n"
4006 " start right away with a saved state (loadvm in monitor)\n"
4007 #ifndef _WIN32
4008 "-daemonize daemonize QEMU after initializing\n"
4009 #endif
4010 "-option-rom rom load a file, rom, into the option ROM space\n"
4011 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4012 "-prom-env variable=value\n"
4013 " set OpenBIOS nvram variables\n"
4014 #endif
4015 "-clock force the use of the given methods for timer alarm.\n"
4016 " To see what timers are available use -clock ?\n"
4017 "-localtime set the real time clock to local time [default=utc]\n"
4018 "-startdate select initial date of the clock\n"
4019 "-icount [N|auto]\n"
4020 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4021 "-echr chr set terminal escape character instead of ctrl-a\n"
4022 "-virtioconsole c\n"
4023 " set virtio console\n"
4024 "-show-cursor show cursor\n"
4025 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4026 "-semihosting semihosting mode\n"
4027 #endif
4028 #if defined(TARGET_ARM)
4029 "-old-param old param mode\n"
4030 #endif
4031 "-tb-size n set TB size\n"
4032 "-incoming p prepare for incoming migration, listen on port p\n"
4033 "\n"
4034 "During emulation, the following keys are useful:\n"
4035 "ctrl-alt-f toggle full screen\n"
4036 "ctrl-alt-n switch to virtual console 'n'\n"
4037 "ctrl-alt toggle mouse and keyboard grab\n"
4038 "\n"
4039 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4041 "qemu",
4042 DEFAULT_RAM_SIZE,
4043 #ifndef _WIN32
4044 DEFAULT_NETWORK_SCRIPT,
4045 DEFAULT_NETWORK_DOWN_SCRIPT,
4046 #endif
4047 DEFAULT_GDBSTUB_PORT,
4048 "/tmp/qemu.log");
4049 exit(exitcode);
4052 #define HAS_ARG 0x0001
4054 enum {
4055 /* Please keep in synch with help, qemu_options[] and
4056 qemu-doc.texi */
4057 /* Standard options: */
4058 QEMU_OPTION_h,
4059 QEMU_OPTION_M,
4060 QEMU_OPTION_cpu,
4061 QEMU_OPTION_smp,
4062 QEMU_OPTION_fda,
4063 QEMU_OPTION_fdb,
4064 QEMU_OPTION_hda,
4065 QEMU_OPTION_hdb,
4066 QEMU_OPTION_hdc,
4067 QEMU_OPTION_hdd,
4068 QEMU_OPTION_cdrom,
4069 QEMU_OPTION_drive,
4070 QEMU_OPTION_mtdblock,
4071 QEMU_OPTION_sd,
4072 QEMU_OPTION_pflash,
4073 QEMU_OPTION_boot,
4074 QEMU_OPTION_snapshot,
4075 QEMU_OPTION_m,
4076 QEMU_OPTION_k,
4077 QEMU_OPTION_audio_help,
4078 QEMU_OPTION_soundhw,
4079 QEMU_OPTION_usb,
4080 QEMU_OPTION_usbdevice,
4081 QEMU_OPTION_name,
4082 QEMU_OPTION_uuid,
4084 /* Display options: */
4085 QEMU_OPTION_nographic,
4086 QEMU_OPTION_curses,
4087 QEMU_OPTION_no_frame,
4088 QEMU_OPTION_alt_grab,
4089 QEMU_OPTION_no_quit,
4090 QEMU_OPTION_sdl,
4091 QEMU_OPTION_portrait,
4092 QEMU_OPTION_vga,
4093 QEMU_OPTION_full_screen,
4094 QEMU_OPTION_g,
4095 QEMU_OPTION_vnc,
4097 /* Network options: */
4098 QEMU_OPTION_net,
4099 QEMU_OPTION_tftp,
4100 QEMU_OPTION_bootp,
4101 QEMU_OPTION_smb,
4102 QEMU_OPTION_redir,
4103 QEMU_OPTION_bt,
4105 /* i386 target only: */
4106 QEMU_OPTION_win2k_hack,
4107 QEMU_OPTION_rtc_td_hack,
4108 QEMU_OPTION_no_fd_bootchk,
4109 QEMU_OPTION_no_acpi,
4110 QEMU_OPTION_no_hpet,
4112 /* Linux boot specific: */
4113 QEMU_OPTION_kernel,
4114 QEMU_OPTION_append,
4115 QEMU_OPTION_initrd,
4117 /* Debug/Expert options: */
4118 QEMU_OPTION_serial,
4119 QEMU_OPTION_parallel,
4120 QEMU_OPTION_monitor,
4121 QEMU_OPTION_pidfile,
4122 QEMU_OPTION_S,
4123 QEMU_OPTION_s,
4124 QEMU_OPTION_p,
4125 QEMU_OPTION_d,
4126 QEMU_OPTION_hdachs,
4127 QEMU_OPTION_L,
4128 QEMU_OPTION_bios,
4129 QEMU_OPTION_kernel_kqemu,
4130 QEMU_OPTION_no_kqemu,
4131 QEMU_OPTION_enable_kvm,
4132 QEMU_OPTION_no_reboot,
4133 QEMU_OPTION_no_shutdown,
4134 QEMU_OPTION_loadvm,
4135 QEMU_OPTION_daemonize,
4136 QEMU_OPTION_option_rom,
4137 QEMU_OPTION_prom_env,
4138 QEMU_OPTION_clock,
4139 QEMU_OPTION_localtime,
4140 QEMU_OPTION_startdate,
4141 QEMU_OPTION_icount,
4142 QEMU_OPTION_echr,
4143 QEMU_OPTION_virtiocon,
4144 QEMU_OPTION_show_cursor,
4145 QEMU_OPTION_semihosting,
4146 QEMU_OPTION_old_param,
4147 QEMU_OPTION_tb_size,
4148 QEMU_OPTION_incoming,
4151 typedef struct QEMUOption {
4152 const char *name;
4153 int flags;
4154 int index;
4155 } QEMUOption;
4157 static const QEMUOption qemu_options[] = {
4158 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4159 qemu-doc.texi */
4160 /* Standard options: */
4161 { "h", 0, QEMU_OPTION_h },
4162 { "help", 0, QEMU_OPTION_h },
4163 { "M", HAS_ARG, QEMU_OPTION_M },
4164 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4165 { "smp", HAS_ARG, QEMU_OPTION_smp },
4166 { "fda", HAS_ARG, QEMU_OPTION_fda },
4167 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4168 { "hda", HAS_ARG, QEMU_OPTION_hda },
4169 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4170 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4171 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4172 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4173 { "drive", HAS_ARG, QEMU_OPTION_drive },
4174 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4175 { "sd", HAS_ARG, QEMU_OPTION_sd },
4176 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4177 { "boot", HAS_ARG, QEMU_OPTION_boot },
4178 { "snapshot", 0, QEMU_OPTION_snapshot },
4179 { "m", HAS_ARG, QEMU_OPTION_m },
4180 #ifndef _WIN32
4181 { "k", HAS_ARG, QEMU_OPTION_k },
4182 #endif
4183 #ifdef HAS_AUDIO
4184 { "audio-help", 0, QEMU_OPTION_audio_help },
4185 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4186 #endif
4187 { "usb", 0, QEMU_OPTION_usb },
4188 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4189 { "name", HAS_ARG, QEMU_OPTION_name },
4190 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4192 /* Display options: */
4193 { "nographic", 0, QEMU_OPTION_nographic },
4194 #ifdef CONFIG_CURSES
4195 { "curses", 0, QEMU_OPTION_curses },
4196 #endif
4197 #ifdef CONFIG_SDL
4198 { "no-frame", 0, QEMU_OPTION_no_frame },
4199 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4200 { "no-quit", 0, QEMU_OPTION_no_quit },
4201 { "sdl", 0, QEMU_OPTION_sdl },
4202 #endif
4203 { "portrait", 0, QEMU_OPTION_portrait },
4204 { "vga", HAS_ARG, QEMU_OPTION_vga },
4205 { "full-screen", 0, QEMU_OPTION_full_screen },
4206 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4207 { "g", 1, QEMU_OPTION_g },
4208 #endif
4209 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4211 /* Network options: */
4212 { "net", HAS_ARG, QEMU_OPTION_net},
4213 #ifdef CONFIG_SLIRP
4214 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4215 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4216 #ifndef _WIN32
4217 { "smb", HAS_ARG, QEMU_OPTION_smb },
4218 #endif
4219 { "redir", HAS_ARG, QEMU_OPTION_redir },
4220 #endif
4221 { "bt", HAS_ARG, QEMU_OPTION_bt },
4222 #ifdef TARGET_I386
4223 /* i386 target only: */
4224 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4225 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4226 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4227 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4228 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4229 #endif
4231 /* Linux boot specific: */
4232 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4233 { "append", HAS_ARG, QEMU_OPTION_append },
4234 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4236 /* Debug/Expert options: */
4237 { "serial", HAS_ARG, QEMU_OPTION_serial },
4238 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4239 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4240 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4241 { "S", 0, QEMU_OPTION_S },
4242 { "s", 0, QEMU_OPTION_s },
4243 { "p", HAS_ARG, QEMU_OPTION_p },
4244 { "d", HAS_ARG, QEMU_OPTION_d },
4245 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4246 { "L", HAS_ARG, QEMU_OPTION_L },
4247 { "bios", HAS_ARG, QEMU_OPTION_bios },
4248 #ifdef USE_KQEMU
4249 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4250 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4251 #endif
4252 #ifdef CONFIG_KVM
4253 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4254 #endif
4255 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4256 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4257 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4258 { "daemonize", 0, QEMU_OPTION_daemonize },
4259 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4260 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4261 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4262 #endif
4263 { "clock", HAS_ARG, QEMU_OPTION_clock },
4264 { "localtime", 0, QEMU_OPTION_localtime },
4265 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4266 { "icount", HAS_ARG, QEMU_OPTION_icount },
4267 { "echr", HAS_ARG, QEMU_OPTION_echr },
4268 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4269 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4270 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4271 { "semihosting", 0, QEMU_OPTION_semihosting },
4272 #endif
4273 #if defined(TARGET_ARM)
4274 { "old-param", 0, QEMU_OPTION_old_param },
4275 #endif
4276 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4277 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4278 { NULL },
4281 /* password input */
4283 int qemu_key_check(BlockDriverState *bs, const char *name)
4285 char password[256];
4286 int i;
4288 if (!bdrv_is_encrypted(bs))
4289 return 0;
4291 term_printf("%s is encrypted.\n", name);
4292 for(i = 0; i < 3; i++) {
4293 monitor_readline("Password: ", 1, password, sizeof(password));
4294 if (bdrv_set_key(bs, password) == 0)
4295 return 0;
4296 term_printf("invalid password\n");
4298 return -EPERM;
4301 static BlockDriverState *get_bdrv(int index)
4303 if (index > nb_drives)
4304 return NULL;
4305 return drives_table[index].bdrv;
4308 static void read_passwords(void)
4310 BlockDriverState *bs;
4311 int i;
4313 for(i = 0; i < 6; i++) {
4314 bs = get_bdrv(i);
4315 if (bs)
4316 qemu_key_check(bs, bdrv_get_device_name(bs));
4320 #ifdef HAS_AUDIO
4321 struct soundhw soundhw[] = {
4322 #ifdef HAS_AUDIO_CHOICE
4323 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4325 "pcspk",
4326 "PC speaker",
4329 { .init_isa = pcspk_audio_init }
4331 #endif
4333 #ifdef CONFIG_SB16
4335 "sb16",
4336 "Creative Sound Blaster 16",
4339 { .init_isa = SB16_init }
4341 #endif
4343 #ifdef CONFIG_CS4231A
4345 "cs4231a",
4346 "CS4231A",
4349 { .init_isa = cs4231a_init }
4351 #endif
4353 #ifdef CONFIG_ADLIB
4355 "adlib",
4356 #ifdef HAS_YMF262
4357 "Yamaha YMF262 (OPL3)",
4358 #else
4359 "Yamaha YM3812 (OPL2)",
4360 #endif
4363 { .init_isa = Adlib_init }
4365 #endif
4367 #ifdef CONFIG_GUS
4369 "gus",
4370 "Gravis Ultrasound GF1",
4373 { .init_isa = GUS_init }
4375 #endif
4377 #ifdef CONFIG_AC97
4379 "ac97",
4380 "Intel 82801AA AC97 Audio",
4383 { .init_pci = ac97_init }
4385 #endif
4387 #ifdef CONFIG_ES1370
4389 "es1370",
4390 "ENSONIQ AudioPCI ES1370",
4393 { .init_pci = es1370_init }
4395 #endif
4397 #endif /* HAS_AUDIO_CHOICE */
4399 { NULL, NULL, 0, 0, { NULL } }
4402 static void select_soundhw (const char *optarg)
4404 struct soundhw *c;
4406 if (*optarg == '?') {
4407 show_valid_cards:
4409 printf ("Valid sound card names (comma separated):\n");
4410 for (c = soundhw; c->name; ++c) {
4411 printf ("%-11s %s\n", c->name, c->descr);
4413 printf ("\n-soundhw all will enable all of the above\n");
4414 exit (*optarg != '?');
4416 else {
4417 size_t l;
4418 const char *p;
4419 char *e;
4420 int bad_card = 0;
4422 if (!strcmp (optarg, "all")) {
4423 for (c = soundhw; c->name; ++c) {
4424 c->enabled = 1;
4426 return;
4429 p = optarg;
4430 while (*p) {
4431 e = strchr (p, ',');
4432 l = !e ? strlen (p) : (size_t) (e - p);
4434 for (c = soundhw; c->name; ++c) {
4435 if (!strncmp (c->name, p, l)) {
4436 c->enabled = 1;
4437 break;
4441 if (!c->name) {
4442 if (l > 80) {
4443 fprintf (stderr,
4444 "Unknown sound card name (too big to show)\n");
4446 else {
4447 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4448 (int) l, p);
4450 bad_card = 1;
4452 p += l + (e != NULL);
4455 if (bad_card)
4456 goto show_valid_cards;
4459 #endif
4461 static void select_vgahw (const char *p)
4463 const char *opts;
4465 if (strstart(p, "std", &opts)) {
4466 std_vga_enabled = 1;
4467 cirrus_vga_enabled = 0;
4468 vmsvga_enabled = 0;
4469 } else if (strstart(p, "cirrus", &opts)) {
4470 cirrus_vga_enabled = 1;
4471 std_vga_enabled = 0;
4472 vmsvga_enabled = 0;
4473 } else if (strstart(p, "vmware", &opts)) {
4474 cirrus_vga_enabled = 0;
4475 std_vga_enabled = 0;
4476 vmsvga_enabled = 1;
4477 } else if (strstart(p, "none", &opts)) {
4478 cirrus_vga_enabled = 0;
4479 std_vga_enabled = 0;
4480 vmsvga_enabled = 0;
4481 } else {
4482 invalid_vga:
4483 fprintf(stderr, "Unknown vga type: %s\n", p);
4484 exit(1);
4486 while (*opts) {
4487 const char *nextopt;
4489 if (strstart(opts, ",retrace=", &nextopt)) {
4490 opts = nextopt;
4491 if (strstart(opts, "dumb", &nextopt))
4492 vga_retrace_method = VGA_RETRACE_DUMB;
4493 else if (strstart(opts, "precise", &nextopt))
4494 vga_retrace_method = VGA_RETRACE_PRECISE;
4495 else goto invalid_vga;
4496 } else goto invalid_vga;
4497 opts = nextopt;
4501 #ifdef _WIN32
4502 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4504 exit(STATUS_CONTROL_C_EXIT);
4505 return TRUE;
4507 #endif
4509 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4511 int ret;
4513 if(strlen(str) != 36)
4514 return -1;
4516 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4517 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4518 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4520 if(ret != 16)
4521 return -1;
4523 return 0;
4526 #define MAX_NET_CLIENTS 32
4528 #ifndef _WIN32
4530 static void termsig_handler(int signal)
4532 qemu_system_shutdown_request();
4535 static void termsig_setup(void)
4537 struct sigaction act;
4539 memset(&act, 0, sizeof(act));
4540 act.sa_handler = termsig_handler;
4541 sigaction(SIGINT, &act, NULL);
4542 sigaction(SIGHUP, &act, NULL);
4543 sigaction(SIGTERM, &act, NULL);
4546 #endif
4548 int main(int argc, char **argv, char **envp)
4550 #ifdef CONFIG_GDBSTUB
4551 int use_gdbstub;
4552 const char *gdbstub_port;
4553 #endif
4554 uint32_t boot_devices_bitmap = 0;
4555 int i;
4556 int snapshot, linux_boot, net_boot;
4557 const char *initrd_filename;
4558 const char *kernel_filename, *kernel_cmdline;
4559 const char *boot_devices = "";
4560 DisplayState *ds;
4561 DisplayChangeListener *dcl;
4562 int cyls, heads, secs, translation;
4563 const char *net_clients[MAX_NET_CLIENTS];
4564 int nb_net_clients;
4565 const char *bt_opts[MAX_BT_CMDLINE];
4566 int nb_bt_opts;
4567 int hda_index;
4568 int optind;
4569 const char *r, *optarg;
4570 CharDriverState *monitor_hd = NULL;
4571 const char *monitor_device;
4572 const char *serial_devices[MAX_SERIAL_PORTS];
4573 int serial_device_index;
4574 const char *parallel_devices[MAX_PARALLEL_PORTS];
4575 int parallel_device_index;
4576 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4577 int virtio_console_index;
4578 const char *loadvm = NULL;
4579 QEMUMachine *machine;
4580 const char *cpu_model;
4581 const char *usb_devices[MAX_USB_CMDLINE];
4582 int usb_devices_index;
4583 int fds[2];
4584 int tb_size;
4585 const char *pid_file = NULL;
4586 int autostart;
4587 const char *incoming = NULL;
4589 qemu_cache_utils_init(envp);
4591 LIST_INIT (&vm_change_state_head);
4592 #ifndef _WIN32
4594 struct sigaction act;
4595 sigfillset(&act.sa_mask);
4596 act.sa_flags = 0;
4597 act.sa_handler = SIG_IGN;
4598 sigaction(SIGPIPE, &act, NULL);
4600 #else
4601 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4602 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4603 QEMU to run on a single CPU */
4605 HANDLE h;
4606 DWORD mask, smask;
4607 int i;
4608 h = GetCurrentProcess();
4609 if (GetProcessAffinityMask(h, &mask, &smask)) {
4610 for(i = 0; i < 32; i++) {
4611 if (mask & (1 << i))
4612 break;
4614 if (i != 32) {
4615 mask = 1 << i;
4616 SetProcessAffinityMask(h, mask);
4620 #endif
4622 register_machines();
4623 machine = first_machine;
4624 cpu_model = NULL;
4625 initrd_filename = NULL;
4626 ram_size = 0;
4627 vga_ram_size = VGA_RAM_SIZE;
4628 #ifdef CONFIG_GDBSTUB
4629 use_gdbstub = 0;
4630 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4631 #endif
4632 snapshot = 0;
4633 nographic = 0;
4634 curses = 0;
4635 kernel_filename = NULL;
4636 kernel_cmdline = "";
4637 cyls = heads = secs = 0;
4638 translation = BIOS_ATA_TRANSLATION_AUTO;
4639 monitor_device = "vc";
4641 serial_devices[0] = "vc:80Cx24C";
4642 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4643 serial_devices[i] = NULL;
4644 serial_device_index = 0;
4646 parallel_devices[0] = "vc:640x480";
4647 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4648 parallel_devices[i] = NULL;
4649 parallel_device_index = 0;
4651 virtio_consoles[0] = "vc:80Cx24C";
4652 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4653 virtio_consoles[i] = NULL;
4654 virtio_console_index = 0;
4656 usb_devices_index = 0;
4658 nb_net_clients = 0;
4659 nb_bt_opts = 0;
4660 nb_drives = 0;
4661 nb_drives_opt = 0;
4662 hda_index = -1;
4664 nb_nics = 0;
4666 tb_size = 0;
4667 autostart= 1;
4669 optind = 1;
4670 for(;;) {
4671 if (optind >= argc)
4672 break;
4673 r = argv[optind];
4674 if (r[0] != '-') {
4675 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4676 } else {
4677 const QEMUOption *popt;
4679 optind++;
4680 /* Treat --foo the same as -foo. */
4681 if (r[1] == '-')
4682 r++;
4683 popt = qemu_options;
4684 for(;;) {
4685 if (!popt->name) {
4686 fprintf(stderr, "%s: invalid option -- '%s'\n",
4687 argv[0], r);
4688 exit(1);
4690 if (!strcmp(popt->name, r + 1))
4691 break;
4692 popt++;
4694 if (popt->flags & HAS_ARG) {
4695 if (optind >= argc) {
4696 fprintf(stderr, "%s: option '%s' requires an argument\n",
4697 argv[0], r);
4698 exit(1);
4700 optarg = argv[optind++];
4701 } else {
4702 optarg = NULL;
4705 switch(popt->index) {
4706 case QEMU_OPTION_M:
4707 machine = find_machine(optarg);
4708 if (!machine) {
4709 QEMUMachine *m;
4710 printf("Supported machines are:\n");
4711 for(m = first_machine; m != NULL; m = m->next) {
4712 printf("%-10s %s%s\n",
4713 m->name, m->desc,
4714 m == first_machine ? " (default)" : "");
4716 exit(*optarg != '?');
4718 break;
4719 case QEMU_OPTION_cpu:
4720 /* hw initialization will check this */
4721 if (*optarg == '?') {
4722 /* XXX: implement xxx_cpu_list for targets that still miss it */
4723 #if defined(cpu_list)
4724 cpu_list(stdout, &fprintf);
4725 #endif
4726 exit(0);
4727 } else {
4728 cpu_model = optarg;
4730 break;
4731 case QEMU_OPTION_initrd:
4732 initrd_filename = optarg;
4733 break;
4734 case QEMU_OPTION_hda:
4735 if (cyls == 0)
4736 hda_index = drive_add(optarg, HD_ALIAS, 0);
4737 else
4738 hda_index = drive_add(optarg, HD_ALIAS
4739 ",cyls=%d,heads=%d,secs=%d%s",
4740 0, cyls, heads, secs,
4741 translation == BIOS_ATA_TRANSLATION_LBA ?
4742 ",trans=lba" :
4743 translation == BIOS_ATA_TRANSLATION_NONE ?
4744 ",trans=none" : "");
4745 break;
4746 case QEMU_OPTION_hdb:
4747 case QEMU_OPTION_hdc:
4748 case QEMU_OPTION_hdd:
4749 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4750 break;
4751 case QEMU_OPTION_drive:
4752 drive_add(NULL, "%s", optarg);
4753 break;
4754 case QEMU_OPTION_mtdblock:
4755 drive_add(optarg, MTD_ALIAS);
4756 break;
4757 case QEMU_OPTION_sd:
4758 drive_add(optarg, SD_ALIAS);
4759 break;
4760 case QEMU_OPTION_pflash:
4761 drive_add(optarg, PFLASH_ALIAS);
4762 break;
4763 case QEMU_OPTION_snapshot:
4764 snapshot = 1;
4765 break;
4766 case QEMU_OPTION_hdachs:
4768 const char *p;
4769 p = optarg;
4770 cyls = strtol(p, (char **)&p, 0);
4771 if (cyls < 1 || cyls > 16383)
4772 goto chs_fail;
4773 if (*p != ',')
4774 goto chs_fail;
4775 p++;
4776 heads = strtol(p, (char **)&p, 0);
4777 if (heads < 1 || heads > 16)
4778 goto chs_fail;
4779 if (*p != ',')
4780 goto chs_fail;
4781 p++;
4782 secs = strtol(p, (char **)&p, 0);
4783 if (secs < 1 || secs > 63)
4784 goto chs_fail;
4785 if (*p == ',') {
4786 p++;
4787 if (!strcmp(p, "none"))
4788 translation = BIOS_ATA_TRANSLATION_NONE;
4789 else if (!strcmp(p, "lba"))
4790 translation = BIOS_ATA_TRANSLATION_LBA;
4791 else if (!strcmp(p, "auto"))
4792 translation = BIOS_ATA_TRANSLATION_AUTO;
4793 else
4794 goto chs_fail;
4795 } else if (*p != '\0') {
4796 chs_fail:
4797 fprintf(stderr, "qemu: invalid physical CHS format\n");
4798 exit(1);
4800 if (hda_index != -1)
4801 snprintf(drives_opt[hda_index].opt,
4802 sizeof(drives_opt[hda_index].opt),
4803 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4804 0, cyls, heads, secs,
4805 translation == BIOS_ATA_TRANSLATION_LBA ?
4806 ",trans=lba" :
4807 translation == BIOS_ATA_TRANSLATION_NONE ?
4808 ",trans=none" : "");
4810 break;
4811 case QEMU_OPTION_nographic:
4812 nographic = 1;
4813 break;
4814 #ifdef CONFIG_CURSES
4815 case QEMU_OPTION_curses:
4816 curses = 1;
4817 break;
4818 #endif
4819 case QEMU_OPTION_portrait:
4820 graphic_rotate = 1;
4821 break;
4822 case QEMU_OPTION_kernel:
4823 kernel_filename = optarg;
4824 break;
4825 case QEMU_OPTION_append:
4826 kernel_cmdline = optarg;
4827 break;
4828 case QEMU_OPTION_cdrom:
4829 drive_add(optarg, CDROM_ALIAS);
4830 break;
4831 case QEMU_OPTION_boot:
4832 boot_devices = optarg;
4833 /* We just do some generic consistency checks */
4835 /* Could easily be extended to 64 devices if needed */
4836 const char *p;
4838 boot_devices_bitmap = 0;
4839 for (p = boot_devices; *p != '\0'; p++) {
4840 /* Allowed boot devices are:
4841 * a b : floppy disk drives
4842 * c ... f : IDE disk drives
4843 * g ... m : machine implementation dependant drives
4844 * n ... p : network devices
4845 * It's up to each machine implementation to check
4846 * if the given boot devices match the actual hardware
4847 * implementation and firmware features.
4849 if (*p < 'a' || *p > 'q') {
4850 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4851 exit(1);
4853 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4854 fprintf(stderr,
4855 "Boot device '%c' was given twice\n",*p);
4856 exit(1);
4858 boot_devices_bitmap |= 1 << (*p - 'a');
4861 break;
4862 case QEMU_OPTION_fda:
4863 case QEMU_OPTION_fdb:
4864 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4865 break;
4866 #ifdef TARGET_I386
4867 case QEMU_OPTION_no_fd_bootchk:
4868 fd_bootchk = 0;
4869 break;
4870 #endif
4871 case QEMU_OPTION_net:
4872 if (nb_net_clients >= MAX_NET_CLIENTS) {
4873 fprintf(stderr, "qemu: too many network clients\n");
4874 exit(1);
4876 net_clients[nb_net_clients] = optarg;
4877 nb_net_clients++;
4878 break;
4879 #ifdef CONFIG_SLIRP
4880 case QEMU_OPTION_tftp:
4881 tftp_prefix = optarg;
4882 break;
4883 case QEMU_OPTION_bootp:
4884 bootp_filename = optarg;
4885 break;
4886 #ifndef _WIN32
4887 case QEMU_OPTION_smb:
4888 net_slirp_smb(optarg);
4889 break;
4890 #endif
4891 case QEMU_OPTION_redir:
4892 net_slirp_redir(optarg);
4893 break;
4894 #endif
4895 case QEMU_OPTION_bt:
4896 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4897 fprintf(stderr, "qemu: too many bluetooth options\n");
4898 exit(1);
4900 bt_opts[nb_bt_opts++] = optarg;
4901 break;
4902 #ifdef HAS_AUDIO
4903 case QEMU_OPTION_audio_help:
4904 AUD_help ();
4905 exit (0);
4906 break;
4907 case QEMU_OPTION_soundhw:
4908 select_soundhw (optarg);
4909 break;
4910 #endif
4911 case QEMU_OPTION_h:
4912 help(0);
4913 break;
4914 case QEMU_OPTION_m: {
4915 uint64_t value;
4916 char *ptr;
4918 value = strtoul(optarg, &ptr, 10);
4919 switch (*ptr) {
4920 case 0: case 'M': case 'm':
4921 value <<= 20;
4922 break;
4923 case 'G': case 'g':
4924 value <<= 30;
4925 break;
4926 default:
4927 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4928 exit(1);
4931 /* On 32-bit hosts, QEMU is limited by virtual address space */
4932 if (value > (2047 << 20)
4933 #ifndef USE_KQEMU
4934 && HOST_LONG_BITS == 32
4935 #endif
4937 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4938 exit(1);
4940 if (value != (uint64_t)(ram_addr_t)value) {
4941 fprintf(stderr, "qemu: ram size too large\n");
4942 exit(1);
4944 ram_size = value;
4945 break;
4947 case QEMU_OPTION_d:
4949 int mask;
4950 const CPULogItem *item;
4952 mask = cpu_str_to_log_mask(optarg);
4953 if (!mask) {
4954 printf("Log items (comma separated):\n");
4955 for(item = cpu_log_items; item->mask != 0; item++) {
4956 printf("%-10s %s\n", item->name, item->help);
4958 exit(1);
4960 cpu_set_log(mask);
4962 break;
4963 #ifdef CONFIG_GDBSTUB
4964 case QEMU_OPTION_s:
4965 use_gdbstub = 1;
4966 break;
4967 case QEMU_OPTION_p:
4968 gdbstub_port = optarg;
4969 break;
4970 #endif
4971 case QEMU_OPTION_L:
4972 bios_dir = optarg;
4973 break;
4974 case QEMU_OPTION_bios:
4975 bios_name = optarg;
4976 break;
4977 case QEMU_OPTION_S:
4978 autostart = 0;
4979 break;
4980 case QEMU_OPTION_k:
4981 keyboard_layout = optarg;
4982 break;
4983 case QEMU_OPTION_localtime:
4984 rtc_utc = 0;
4985 break;
4986 case QEMU_OPTION_vga:
4987 select_vgahw (optarg);
4988 break;
4989 case QEMU_OPTION_g:
4991 const char *p;
4992 int w, h, depth;
4993 p = optarg;
4994 w = strtol(p, (char **)&p, 10);
4995 if (w <= 0) {
4996 graphic_error:
4997 fprintf(stderr, "qemu: invalid resolution or depth\n");
4998 exit(1);
5000 if (*p != 'x')
5001 goto graphic_error;
5002 p++;
5003 h = strtol(p, (char **)&p, 10);
5004 if (h <= 0)
5005 goto graphic_error;
5006 if (*p == 'x') {
5007 p++;
5008 depth = strtol(p, (char **)&p, 10);
5009 if (depth != 8 && depth != 15 && depth != 16 &&
5010 depth != 24 && depth != 32)
5011 goto graphic_error;
5012 } else if (*p == '\0') {
5013 depth = graphic_depth;
5014 } else {
5015 goto graphic_error;
5018 graphic_width = w;
5019 graphic_height = h;
5020 graphic_depth = depth;
5022 break;
5023 case QEMU_OPTION_echr:
5025 char *r;
5026 term_escape_char = strtol(optarg, &r, 0);
5027 if (r == optarg)
5028 printf("Bad argument to echr\n");
5029 break;
5031 case QEMU_OPTION_monitor:
5032 monitor_device = optarg;
5033 break;
5034 case QEMU_OPTION_serial:
5035 if (serial_device_index >= MAX_SERIAL_PORTS) {
5036 fprintf(stderr, "qemu: too many serial ports\n");
5037 exit(1);
5039 serial_devices[serial_device_index] = optarg;
5040 serial_device_index++;
5041 break;
5042 case QEMU_OPTION_virtiocon:
5043 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5044 fprintf(stderr, "qemu: too many virtio consoles\n");
5045 exit(1);
5047 virtio_consoles[virtio_console_index] = optarg;
5048 virtio_console_index++;
5049 break;
5050 case QEMU_OPTION_parallel:
5051 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5052 fprintf(stderr, "qemu: too many parallel ports\n");
5053 exit(1);
5055 parallel_devices[parallel_device_index] = optarg;
5056 parallel_device_index++;
5057 break;
5058 case QEMU_OPTION_loadvm:
5059 loadvm = optarg;
5060 break;
5061 case QEMU_OPTION_full_screen:
5062 full_screen = 1;
5063 break;
5064 #ifdef CONFIG_SDL
5065 case QEMU_OPTION_no_frame:
5066 no_frame = 1;
5067 break;
5068 case QEMU_OPTION_alt_grab:
5069 alt_grab = 1;
5070 break;
5071 case QEMU_OPTION_no_quit:
5072 no_quit = 1;
5073 break;
5074 case QEMU_OPTION_sdl:
5075 sdl = 1;
5076 break;
5077 #endif
5078 case QEMU_OPTION_pidfile:
5079 pid_file = optarg;
5080 break;
5081 #ifdef TARGET_I386
5082 case QEMU_OPTION_win2k_hack:
5083 win2k_install_hack = 1;
5084 break;
5085 case QEMU_OPTION_rtc_td_hack:
5086 rtc_td_hack = 1;
5087 break;
5088 #endif
5089 #ifdef USE_KQEMU
5090 case QEMU_OPTION_no_kqemu:
5091 kqemu_allowed = 0;
5092 break;
5093 case QEMU_OPTION_kernel_kqemu:
5094 kqemu_allowed = 2;
5095 break;
5096 #endif
5097 #ifdef CONFIG_KVM
5098 case QEMU_OPTION_enable_kvm:
5099 kvm_allowed = 1;
5100 #ifdef USE_KQEMU
5101 kqemu_allowed = 0;
5102 #endif
5103 break;
5104 #endif
5105 case QEMU_OPTION_usb:
5106 usb_enabled = 1;
5107 break;
5108 case QEMU_OPTION_usbdevice:
5109 usb_enabled = 1;
5110 if (usb_devices_index >= MAX_USB_CMDLINE) {
5111 fprintf(stderr, "Too many USB devices\n");
5112 exit(1);
5114 usb_devices[usb_devices_index] = optarg;
5115 usb_devices_index++;
5116 break;
5117 case QEMU_OPTION_smp:
5118 smp_cpus = atoi(optarg);
5119 if (smp_cpus < 1) {
5120 fprintf(stderr, "Invalid number of CPUs\n");
5121 exit(1);
5123 break;
5124 case QEMU_OPTION_vnc:
5125 vnc_display = optarg;
5126 break;
5127 case QEMU_OPTION_no_acpi:
5128 acpi_enabled = 0;
5129 break;
5130 case QEMU_OPTION_no_hpet:
5131 no_hpet = 1;
5132 break;
5133 case QEMU_OPTION_no_reboot:
5134 no_reboot = 1;
5135 break;
5136 case QEMU_OPTION_no_shutdown:
5137 no_shutdown = 1;
5138 break;
5139 case QEMU_OPTION_show_cursor:
5140 cursor_hide = 0;
5141 break;
5142 case QEMU_OPTION_uuid:
5143 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5144 fprintf(stderr, "Fail to parse UUID string."
5145 " Wrong format.\n");
5146 exit(1);
5148 break;
5149 case QEMU_OPTION_daemonize:
5150 daemonize = 1;
5151 break;
5152 case QEMU_OPTION_option_rom:
5153 if (nb_option_roms >= MAX_OPTION_ROMS) {
5154 fprintf(stderr, "Too many option ROMs\n");
5155 exit(1);
5157 option_rom[nb_option_roms] = optarg;
5158 nb_option_roms++;
5159 break;
5160 case QEMU_OPTION_semihosting:
5161 semihosting_enabled = 1;
5162 break;
5163 case QEMU_OPTION_name:
5164 qemu_name = optarg;
5165 break;
5166 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5167 case QEMU_OPTION_prom_env:
5168 if (nb_prom_envs >= MAX_PROM_ENVS) {
5169 fprintf(stderr, "Too many prom variables\n");
5170 exit(1);
5172 prom_envs[nb_prom_envs] = optarg;
5173 nb_prom_envs++;
5174 break;
5175 #endif
5176 #ifdef TARGET_ARM
5177 case QEMU_OPTION_old_param:
5178 old_param = 1;
5179 break;
5180 #endif
5181 case QEMU_OPTION_clock:
5182 configure_alarms(optarg);
5183 break;
5184 case QEMU_OPTION_startdate:
5186 struct tm tm;
5187 time_t rtc_start_date;
5188 if (!strcmp(optarg, "now")) {
5189 rtc_date_offset = -1;
5190 } else {
5191 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5192 &tm.tm_year,
5193 &tm.tm_mon,
5194 &tm.tm_mday,
5195 &tm.tm_hour,
5196 &tm.tm_min,
5197 &tm.tm_sec) == 6) {
5198 /* OK */
5199 } else if (sscanf(optarg, "%d-%d-%d",
5200 &tm.tm_year,
5201 &tm.tm_mon,
5202 &tm.tm_mday) == 3) {
5203 tm.tm_hour = 0;
5204 tm.tm_min = 0;
5205 tm.tm_sec = 0;
5206 } else {
5207 goto date_fail;
5209 tm.tm_year -= 1900;
5210 tm.tm_mon--;
5211 rtc_start_date = mktimegm(&tm);
5212 if (rtc_start_date == -1) {
5213 date_fail:
5214 fprintf(stderr, "Invalid date format. Valid format are:\n"
5215 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5216 exit(1);
5218 rtc_date_offset = time(NULL) - rtc_start_date;
5221 break;
5222 case QEMU_OPTION_tb_size:
5223 tb_size = strtol(optarg, NULL, 0);
5224 if (tb_size < 0)
5225 tb_size = 0;
5226 break;
5227 case QEMU_OPTION_icount:
5228 use_icount = 1;
5229 if (strcmp(optarg, "auto") == 0) {
5230 icount_time_shift = -1;
5231 } else {
5232 icount_time_shift = strtol(optarg, NULL, 0);
5234 break;
5235 case QEMU_OPTION_incoming:
5236 incoming = optarg;
5237 break;
5242 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5243 if (kvm_allowed && kqemu_allowed) {
5244 fprintf(stderr,
5245 "You can not enable both KVM and kqemu at the same time\n");
5246 exit(1);
5248 #endif
5250 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5251 if (smp_cpus > machine->max_cpus) {
5252 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5253 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5254 machine->max_cpus);
5255 exit(1);
5258 if (nographic) {
5259 if (serial_device_index == 0)
5260 serial_devices[0] = "stdio";
5261 if (parallel_device_index == 0)
5262 parallel_devices[0] = "null";
5263 if (strncmp(monitor_device, "vc", 2) == 0)
5264 monitor_device = "stdio";
5265 if (virtio_console_index == 0)
5266 virtio_consoles[0] = "null";
5269 #ifndef _WIN32
5270 if (daemonize) {
5271 pid_t pid;
5273 if (pipe(fds) == -1)
5274 exit(1);
5276 pid = fork();
5277 if (pid > 0) {
5278 uint8_t status;
5279 ssize_t len;
5281 close(fds[1]);
5283 again:
5284 len = read(fds[0], &status, 1);
5285 if (len == -1 && (errno == EINTR))
5286 goto again;
5288 if (len != 1)
5289 exit(1);
5290 else if (status == 1) {
5291 fprintf(stderr, "Could not acquire pidfile\n");
5292 exit(1);
5293 } else
5294 exit(0);
5295 } else if (pid < 0)
5296 exit(1);
5298 setsid();
5300 pid = fork();
5301 if (pid > 0)
5302 exit(0);
5303 else if (pid < 0)
5304 exit(1);
5306 umask(027);
5308 signal(SIGTSTP, SIG_IGN);
5309 signal(SIGTTOU, SIG_IGN);
5310 signal(SIGTTIN, SIG_IGN);
5312 #endif
5314 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5315 if (daemonize) {
5316 uint8_t status = 1;
5317 write(fds[1], &status, 1);
5318 } else
5319 fprintf(stderr, "Could not acquire pid file\n");
5320 exit(1);
5323 #ifdef USE_KQEMU
5324 if (smp_cpus > 1)
5325 kqemu_allowed = 0;
5326 #endif
5327 linux_boot = (kernel_filename != NULL);
5328 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5330 if (!linux_boot && net_boot == 0 &&
5331 !machine->nodisk_ok && nb_drives_opt == 0)
5332 help(1);
5334 if (!linux_boot && *kernel_cmdline != '\0') {
5335 fprintf(stderr, "-append only allowed with -kernel option\n");
5336 exit(1);
5339 if (!linux_boot && initrd_filename != NULL) {
5340 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5341 exit(1);
5344 /* boot to floppy or the default cd if no hard disk defined yet */
5345 if (!boot_devices[0]) {
5346 boot_devices = "cad";
5348 setvbuf(stdout, NULL, _IOLBF, 0);
5350 init_timers();
5351 if (init_timer_alarm() < 0) {
5352 fprintf(stderr, "could not initialize alarm timer\n");
5353 exit(1);
5355 if (use_icount && icount_time_shift < 0) {
5356 use_icount = 2;
5357 /* 125MIPS seems a reasonable initial guess at the guest speed.
5358 It will be corrected fairly quickly anyway. */
5359 icount_time_shift = 3;
5360 init_icount_adjust();
5363 #ifdef _WIN32
5364 socket_init();
5365 #endif
5367 /* init network clients */
5368 if (nb_net_clients == 0) {
5369 /* if no clients, we use a default config */
5370 net_clients[nb_net_clients++] = "nic";
5371 #ifdef CONFIG_SLIRP
5372 net_clients[nb_net_clients++] = "user";
5373 #endif
5376 for(i = 0;i < nb_net_clients; i++) {
5377 if (net_client_parse(net_clients[i]) < 0)
5378 exit(1);
5380 net_client_check();
5382 #ifdef TARGET_I386
5383 /* XXX: this should be moved in the PC machine instantiation code */
5384 if (net_boot != 0) {
5385 int netroms = 0;
5386 for (i = 0; i < nb_nics && i < 4; i++) {
5387 const char *model = nd_table[i].model;
5388 char buf[1024];
5389 if (net_boot & (1 << i)) {
5390 if (model == NULL)
5391 model = "ne2k_pci";
5392 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5393 if (get_image_size(buf) > 0) {
5394 if (nb_option_roms >= MAX_OPTION_ROMS) {
5395 fprintf(stderr, "Too many option ROMs\n");
5396 exit(1);
5398 option_rom[nb_option_roms] = strdup(buf);
5399 nb_option_roms++;
5400 netroms++;
5404 if (netroms == 0) {
5405 fprintf(stderr, "No valid PXE rom found for network device\n");
5406 exit(1);
5409 #endif
5411 /* init the bluetooth world */
5412 for (i = 0; i < nb_bt_opts; i++)
5413 if (bt_parse(bt_opts[i]))
5414 exit(1);
5416 /* init the memory */
5417 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5419 if (machine->ram_require & RAMSIZE_FIXED) {
5420 if (ram_size > 0) {
5421 if (ram_size < phys_ram_size) {
5422 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5423 machine->name, (unsigned long long) phys_ram_size);
5424 exit(-1);
5427 phys_ram_size = ram_size;
5428 } else
5429 ram_size = phys_ram_size;
5430 } else {
5431 if (ram_size == 0)
5432 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5434 phys_ram_size += ram_size;
5437 phys_ram_base = qemu_vmalloc(phys_ram_size);
5438 if (!phys_ram_base) {
5439 fprintf(stderr, "Could not allocate physical memory\n");
5440 exit(1);
5443 /* init the dynamic translator */
5444 cpu_exec_init_all(tb_size * 1024 * 1024);
5446 bdrv_init();
5448 /* we always create the cdrom drive, even if no disk is there */
5450 if (nb_drives_opt < MAX_DRIVES)
5451 drive_add(NULL, CDROM_ALIAS);
5453 /* we always create at least one floppy */
5455 if (nb_drives_opt < MAX_DRIVES)
5456 drive_add(NULL, FD_ALIAS, 0);
5458 /* we always create one sd slot, even if no card is in it */
5460 if (nb_drives_opt < MAX_DRIVES)
5461 drive_add(NULL, SD_ALIAS);
5463 /* open the virtual block devices */
5465 for(i = 0; i < nb_drives_opt; i++)
5466 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5467 exit(1);
5469 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5470 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5472 #ifndef _WIN32
5473 /* must be after terminal init, SDL library changes signal handlers */
5474 termsig_setup();
5475 #endif
5477 /* Maintain compatibility with multiple stdio monitors */
5478 if (!strcmp(monitor_device,"stdio")) {
5479 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5480 const char *devname = serial_devices[i];
5481 if (devname && !strcmp(devname,"mon:stdio")) {
5482 monitor_device = NULL;
5483 break;
5484 } else if (devname && !strcmp(devname,"stdio")) {
5485 monitor_device = NULL;
5486 serial_devices[i] = "mon:stdio";
5487 break;
5492 if (kvm_enabled()) {
5493 int ret;
5495 ret = kvm_init(smp_cpus);
5496 if (ret < 0) {
5497 fprintf(stderr, "failed to initialize KVM\n");
5498 exit(1);
5502 if (monitor_device) {
5503 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5504 if (!monitor_hd) {
5505 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5506 exit(1);
5510 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5511 const char *devname = serial_devices[i];
5512 if (devname && strcmp(devname, "none")) {
5513 char label[32];
5514 snprintf(label, sizeof(label), "serial%d", i);
5515 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5516 if (!serial_hds[i]) {
5517 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5518 devname);
5519 exit(1);
5524 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5525 const char *devname = parallel_devices[i];
5526 if (devname && strcmp(devname, "none")) {
5527 char label[32];
5528 snprintf(label, sizeof(label), "parallel%d", i);
5529 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5530 if (!parallel_hds[i]) {
5531 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5532 devname);
5533 exit(1);
5538 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5539 const char *devname = virtio_consoles[i];
5540 if (devname && strcmp(devname, "none")) {
5541 char label[32];
5542 snprintf(label, sizeof(label), "virtcon%d", i);
5543 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5544 if (!virtcon_hds[i]) {
5545 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5546 devname);
5547 exit(1);
5552 machine->init(ram_size, vga_ram_size, boot_devices,
5553 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5555 /* Set KVM's vcpu state to qemu's initial CPUState. */
5556 if (kvm_enabled()) {
5557 int ret;
5559 ret = kvm_sync_vcpus();
5560 if (ret < 0) {
5561 fprintf(stderr, "failed to initialize vcpus\n");
5562 exit(1);
5566 /* init USB devices */
5567 if (usb_enabled) {
5568 for(i = 0; i < usb_devices_index; i++) {
5569 if (usb_device_add(usb_devices[i]) < 0) {
5570 fprintf(stderr, "Warning: could not add USB device %s\n",
5571 usb_devices[i]);
5576 if (!display_state)
5577 dumb_display_init();
5578 /* just use the first displaystate for the moment */
5579 ds = display_state;
5580 /* terminal init */
5581 if (nographic) {
5582 if (curses) {
5583 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5584 exit(1);
5586 } else {
5587 #if defined(CONFIG_CURSES)
5588 if (curses) {
5589 /* At the moment curses cannot be used with other displays */
5590 curses_display_init(ds, full_screen);
5591 } else
5592 #endif
5594 if (vnc_display != NULL) {
5595 vnc_display_init(ds);
5596 if (vnc_display_open(ds, vnc_display) < 0)
5597 exit(1);
5599 #if defined(CONFIG_SDL)
5600 if (sdl || !vnc_display)
5601 sdl_display_init(ds, full_screen, no_frame);
5602 #elif defined(CONFIG_COCOA)
5603 if (sdl || !vnc_display)
5604 cocoa_display_init(ds, full_screen);
5605 #endif
5608 dpy_resize(ds);
5610 dcl = ds->listeners;
5611 while (dcl != NULL) {
5612 if (dcl->dpy_refresh != NULL) {
5613 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5614 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5616 dcl = dcl->next;
5619 if (nographic || (vnc_display && !sdl)) {
5620 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5621 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5624 text_consoles_set_display(display_state);
5626 if (monitor_device && monitor_hd)
5627 monitor_init(monitor_hd, !nographic);
5629 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5630 const char *devname = serial_devices[i];
5631 if (devname && strcmp(devname, "none")) {
5632 char label[32];
5633 snprintf(label, sizeof(label), "serial%d", i);
5634 if (strstart(devname, "vc", 0))
5635 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5639 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5640 const char *devname = parallel_devices[i];
5641 if (devname && strcmp(devname, "none")) {
5642 char label[32];
5643 snprintf(label, sizeof(label), "parallel%d", i);
5644 if (strstart(devname, "vc", 0))
5645 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5649 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5650 const char *devname = virtio_consoles[i];
5651 if (virtcon_hds[i] && devname) {
5652 char label[32];
5653 snprintf(label, sizeof(label), "virtcon%d", i);
5654 if (strstart(devname, "vc", 0))
5655 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5659 #ifdef CONFIG_GDBSTUB
5660 if (use_gdbstub) {
5661 /* XXX: use standard host:port notation and modify options
5662 accordingly. */
5663 if (gdbserver_start(gdbstub_port) < 0) {
5664 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5665 gdbstub_port);
5666 exit(1);
5669 #endif
5671 if (loadvm)
5672 do_loadvm(loadvm);
5674 if (incoming) {
5675 autostart = 0; /* fixme how to deal with -daemonize */
5676 qemu_start_incoming_migration(incoming);
5680 /* XXX: simplify init */
5681 read_passwords();
5682 if (autostart) {
5683 vm_start();
5687 if (daemonize) {
5688 uint8_t status = 0;
5689 ssize_t len;
5690 int fd;
5692 again1:
5693 len = write(fds[1], &status, 1);
5694 if (len == -1 && (errno == EINTR))
5695 goto again1;
5697 if (len != 1)
5698 exit(1);
5700 chdir("/");
5701 TFR(fd = open("/dev/null", O_RDWR));
5702 if (fd == -1)
5703 exit(1);
5705 dup2(fd, 0);
5706 dup2(fd, 1);
5707 dup2(fd, 2);
5709 close(fd);
5712 main_loop();
5713 quit_timers();
5714 net_cleanup();
5716 return 0;