use the generic soft float code
[qemu/qemu_0_9_1_stable.git] / vl.c
bloba815a50fa8c23f2495c3a7077e7b17069b9d770b
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2004 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
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 "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <dirent.h>
43 #ifdef _BSD
44 #include <sys/stat.h>
45 #ifndef __APPLE__
46 #include <libutil.h>
47 #endif
48 #else
49 #include <linux/if.h>
50 #include <linux/if_tun.h>
51 #include <pty.h>
52 #include <malloc.h>
53 #include <linux/rtc.h>
54 #endif
55 #endif
57 #if defined(CONFIG_SLIRP)
58 #include "libslirp.h"
59 #endif
61 #ifdef _WIN32
62 #include <malloc.h>
63 #include <sys/timeb.h>
64 #include <windows.h>
65 #define getopt_long_only getopt_long
66 #define memalign(align, size) malloc(size)
67 #endif
69 #ifdef CONFIG_SDL
70 #ifdef __APPLE__
71 #include <SDL/SDL.h>
72 #endif
73 #endif /* CONFIG_SDL */
75 #ifdef CONFIG_COCOA
76 #undef main
77 #define main qemu_main
78 #endif /* CONFIG_COCOA */
80 #include "disas.h"
82 #include "exec-all.h"
84 //#define DO_TB_FLUSH
86 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
88 //#define DEBUG_UNUSED_IOPORT
89 //#define DEBUG_IOPORT
91 #if !defined(CONFIG_SOFTMMU)
92 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
93 #else
94 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
95 #endif
97 #ifdef TARGET_PPC
98 #define DEFAULT_RAM_SIZE 144
99 #else
100 #define DEFAULT_RAM_SIZE 128
101 #endif
102 /* in ms */
103 #define GUI_REFRESH_INTERVAL 30
105 /* XXX: use a two level table to limit memory usage */
106 #define MAX_IOPORTS 65536
108 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
109 char phys_ram_file[1024];
110 CPUState *global_env;
111 CPUState *cpu_single_env;
112 void *ioport_opaque[MAX_IOPORTS];
113 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
114 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
115 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116 int vga_ram_size;
117 int bios_size;
118 static DisplayState display_state;
119 int nographic;
120 const char* keyboard_layout = NULL;
121 int64_t ticks_per_sec;
122 int boot_device = 'c';
123 int ram_size;
124 static char network_script[1024];
125 int pit_min_timer_count = 0;
126 int nb_nics;
127 NetDriverState nd_table[MAX_NICS];
128 QEMUTimer *gui_timer;
129 int vm_running;
130 int audio_enabled = 0;
131 int sb16_enabled = 1;
132 int adlib_enabled = 1;
133 int gus_enabled = 1;
134 int pci_enabled = 1;
135 int prep_enabled = 0;
136 int rtc_utc = 1;
137 int cirrus_vga_enabled = 1;
138 int graphic_width = 800;
139 int graphic_height = 600;
140 int graphic_depth = 15;
141 int full_screen = 0;
142 TextConsole *vga_console;
143 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
144 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
146 /***********************************************************/
147 /* x86 ISA bus support */
149 target_phys_addr_t isa_mem_base = 0;
151 uint32_t default_ioport_readb(void *opaque, uint32_t address)
153 #ifdef DEBUG_UNUSED_IOPORT
154 fprintf(stderr, "inb: port=0x%04x\n", address);
155 #endif
156 return 0xff;
159 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
161 #ifdef DEBUG_UNUSED_IOPORT
162 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
163 #endif
166 /* default is to make two byte accesses */
167 uint32_t default_ioport_readw(void *opaque, uint32_t address)
169 uint32_t data;
170 data = ioport_read_table[0][address](ioport_opaque[address], address);
171 address = (address + 1) & (MAX_IOPORTS - 1);
172 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
173 return data;
176 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
178 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
179 address = (address + 1) & (MAX_IOPORTS - 1);
180 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
183 uint32_t default_ioport_readl(void *opaque, uint32_t address)
185 #ifdef DEBUG_UNUSED_IOPORT
186 fprintf(stderr, "inl: port=0x%04x\n", address);
187 #endif
188 return 0xffffffff;
191 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
193 #ifdef DEBUG_UNUSED_IOPORT
194 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
195 #endif
198 void init_ioports(void)
200 int i;
202 for(i = 0; i < MAX_IOPORTS; i++) {
203 ioport_read_table[0][i] = default_ioport_readb;
204 ioport_write_table[0][i] = default_ioport_writeb;
205 ioport_read_table[1][i] = default_ioport_readw;
206 ioport_write_table[1][i] = default_ioport_writew;
207 ioport_read_table[2][i] = default_ioport_readl;
208 ioport_write_table[2][i] = default_ioport_writel;
212 /* size is the word size in byte */
213 int register_ioport_read(int start, int length, int size,
214 IOPortReadFunc *func, void *opaque)
216 int i, bsize;
218 if (size == 1) {
219 bsize = 0;
220 } else if (size == 2) {
221 bsize = 1;
222 } else if (size == 4) {
223 bsize = 2;
224 } else {
225 hw_error("register_ioport_read: invalid size");
226 return -1;
228 for(i = start; i < start + length; i += size) {
229 ioport_read_table[bsize][i] = func;
230 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
231 hw_error("register_ioport_read: invalid opaque");
232 ioport_opaque[i] = opaque;
234 return 0;
237 /* size is the word size in byte */
238 int register_ioport_write(int start, int length, int size,
239 IOPortWriteFunc *func, void *opaque)
241 int i, bsize;
243 if (size == 1) {
244 bsize = 0;
245 } else if (size == 2) {
246 bsize = 1;
247 } else if (size == 4) {
248 bsize = 2;
249 } else {
250 hw_error("register_ioport_write: invalid size");
251 return -1;
253 for(i = start; i < start + length; i += size) {
254 ioport_write_table[bsize][i] = func;
255 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
256 hw_error("register_ioport_read: invalid opaque");
257 ioport_opaque[i] = opaque;
259 return 0;
262 void isa_unassign_ioport(int start, int length)
264 int i;
266 for(i = start; i < start + length; i++) {
267 ioport_read_table[0][i] = default_ioport_readb;
268 ioport_read_table[1][i] = default_ioport_readw;
269 ioport_read_table[2][i] = default_ioport_readl;
271 ioport_write_table[0][i] = default_ioport_writeb;
272 ioport_write_table[1][i] = default_ioport_writew;
273 ioport_write_table[2][i] = default_ioport_writel;
277 /***********************************************************/
279 void pstrcpy(char *buf, int buf_size, const char *str)
281 int c;
282 char *q = buf;
284 if (buf_size <= 0)
285 return;
287 for(;;) {
288 c = *str++;
289 if (c == 0 || q >= buf + buf_size - 1)
290 break;
291 *q++ = c;
293 *q = '\0';
296 /* strcat and truncate. */
297 char *pstrcat(char *buf, int buf_size, const char *s)
299 int len;
300 len = strlen(buf);
301 if (len < buf_size)
302 pstrcpy(buf + len, buf_size - len, s);
303 return buf;
306 int strstart(const char *str, const char *val, const char **ptr)
308 const char *p, *q;
309 p = str;
310 q = val;
311 while (*q != '\0') {
312 if (*p != *q)
313 return 0;
314 p++;
315 q++;
317 if (ptr)
318 *ptr = p;
319 return 1;
322 /* return the size or -1 if error */
323 int get_image_size(const char *filename)
325 int fd, size;
326 fd = open(filename, O_RDONLY | O_BINARY);
327 if (fd < 0)
328 return -1;
329 size = lseek(fd, 0, SEEK_END);
330 close(fd);
331 return size;
334 /* return the size or -1 if error */
335 int load_image(const char *filename, uint8_t *addr)
337 int fd, size;
338 fd = open(filename, O_RDONLY | O_BINARY);
339 if (fd < 0)
340 return -1;
341 size = lseek(fd, 0, SEEK_END);
342 lseek(fd, 0, SEEK_SET);
343 if (read(fd, addr, size) != size) {
344 close(fd);
345 return -1;
347 close(fd);
348 return size;
351 void cpu_outb(CPUState *env, int addr, int val)
353 #ifdef DEBUG_IOPORT
354 if (loglevel & CPU_LOG_IOPORT)
355 fprintf(logfile, "outb: %04x %02x\n", addr, val);
356 #endif
357 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
360 void cpu_outw(CPUState *env, int addr, int val)
362 #ifdef DEBUG_IOPORT
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outw: %04x %04x\n", addr, val);
365 #endif
366 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
369 void cpu_outl(CPUState *env, int addr, int val)
371 #ifdef DEBUG_IOPORT
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outl: %04x %08x\n", addr, val);
374 #endif
375 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
378 int cpu_inb(CPUState *env, int addr)
380 int val;
381 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inb : %04x %02x\n", addr, val);
385 #endif
386 return val;
389 int cpu_inw(CPUState *env, int addr)
391 int val;
392 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inw : %04x %04x\n", addr, val);
396 #endif
397 return val;
400 int cpu_inl(CPUState *env, int addr)
402 int val;
403 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
404 #ifdef DEBUG_IOPORT
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "inl : %04x %08x\n", addr, val);
407 #endif
408 return val;
411 /***********************************************************/
412 void hw_error(const char *fmt, ...)
414 va_list ap;
416 va_start(ap, fmt);
417 fprintf(stderr, "qemu: hardware error: ");
418 vfprintf(stderr, fmt, ap);
419 fprintf(stderr, "\n");
420 #ifdef TARGET_I386
421 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
422 #else
423 cpu_dump_state(global_env, stderr, fprintf, 0);
424 #endif
425 va_end(ap);
426 abort();
429 /***********************************************************/
430 /* keyboard/mouse */
432 static QEMUPutKBDEvent *qemu_put_kbd_event;
433 static void *qemu_put_kbd_event_opaque;
434 static QEMUPutMouseEvent *qemu_put_mouse_event;
435 static void *qemu_put_mouse_event_opaque;
437 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
439 qemu_put_kbd_event_opaque = opaque;
440 qemu_put_kbd_event = func;
443 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
445 qemu_put_mouse_event_opaque = opaque;
446 qemu_put_mouse_event = func;
449 void kbd_put_keycode(int keycode)
451 if (qemu_put_kbd_event) {
452 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
456 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
458 if (qemu_put_mouse_event) {
459 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
460 dx, dy, dz, buttons_state);
464 /***********************************************************/
465 /* timers */
467 #if defined(__powerpc__)
469 static inline uint32_t get_tbl(void)
471 uint32_t tbl;
472 asm volatile("mftb %0" : "=r" (tbl));
473 return tbl;
476 static inline uint32_t get_tbu(void)
478 uint32_t tbl;
479 asm volatile("mftbu %0" : "=r" (tbl));
480 return tbl;
483 int64_t cpu_get_real_ticks(void)
485 uint32_t l, h, h1;
486 /* NOTE: we test if wrapping has occurred */
487 do {
488 h = get_tbu();
489 l = get_tbl();
490 h1 = get_tbu();
491 } while (h != h1);
492 return ((int64_t)h << 32) | l;
495 #elif defined(__i386__)
497 int64_t cpu_get_real_ticks(void)
499 int64_t val;
500 asm volatile ("rdtsc" : "=A" (val));
501 return val;
504 #elif defined(__x86_64__)
506 int64_t cpu_get_real_ticks(void)
508 uint32_t low,high;
509 int64_t val;
510 asm volatile("rdtsc" : "=a" (low), "=d" (high));
511 val = high;
512 val <<= 32;
513 val |= low;
514 return val;
517 #else
518 #error unsupported CPU
519 #endif
521 static int64_t cpu_ticks_offset;
522 static int cpu_ticks_enabled;
524 static inline int64_t cpu_get_ticks(void)
526 if (!cpu_ticks_enabled) {
527 return cpu_ticks_offset;
528 } else {
529 return cpu_get_real_ticks() + cpu_ticks_offset;
533 /* enable cpu_get_ticks() */
534 void cpu_enable_ticks(void)
536 if (!cpu_ticks_enabled) {
537 cpu_ticks_offset -= cpu_get_real_ticks();
538 cpu_ticks_enabled = 1;
542 /* disable cpu_get_ticks() : the clock is stopped. You must not call
543 cpu_get_ticks() after that. */
544 void cpu_disable_ticks(void)
546 if (cpu_ticks_enabled) {
547 cpu_ticks_offset = cpu_get_ticks();
548 cpu_ticks_enabled = 0;
552 static int64_t get_clock(void)
554 #ifdef _WIN32
555 struct _timeb tb;
556 _ftime(&tb);
557 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
558 #else
559 struct timeval tv;
560 gettimeofday(&tv, NULL);
561 return tv.tv_sec * 1000000LL + tv.tv_usec;
562 #endif
565 void cpu_calibrate_ticks(void)
567 int64_t usec, ticks;
569 usec = get_clock();
570 ticks = cpu_get_real_ticks();
571 #ifdef _WIN32
572 Sleep(50);
573 #else
574 usleep(50 * 1000);
575 #endif
576 usec = get_clock() - usec;
577 ticks = cpu_get_real_ticks() - ticks;
578 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
581 /* compute with 96 bit intermediate result: (a*b)/c */
582 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
584 union {
585 uint64_t ll;
586 struct {
587 #ifdef WORDS_BIGENDIAN
588 uint32_t high, low;
589 #else
590 uint32_t low, high;
591 #endif
592 } l;
593 } u, res;
594 uint64_t rl, rh;
596 u.ll = a;
597 rl = (uint64_t)u.l.low * (uint64_t)b;
598 rh = (uint64_t)u.l.high * (uint64_t)b;
599 rh += (rl >> 32);
600 res.l.high = rh / c;
601 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
602 return res.ll;
605 #define QEMU_TIMER_REALTIME 0
606 #define QEMU_TIMER_VIRTUAL 1
608 struct QEMUClock {
609 int type;
610 /* XXX: add frequency */
613 struct QEMUTimer {
614 QEMUClock *clock;
615 int64_t expire_time;
616 QEMUTimerCB *cb;
617 void *opaque;
618 struct QEMUTimer *next;
621 QEMUClock *rt_clock;
622 QEMUClock *vm_clock;
624 static QEMUTimer *active_timers[2];
625 #ifdef _WIN32
626 static MMRESULT timerID;
627 #else
628 /* frequency of the times() clock tick */
629 static int timer_freq;
630 #endif
632 QEMUClock *qemu_new_clock(int type)
634 QEMUClock *clock;
635 clock = qemu_mallocz(sizeof(QEMUClock));
636 if (!clock)
637 return NULL;
638 clock->type = type;
639 return clock;
642 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
644 QEMUTimer *ts;
646 ts = qemu_mallocz(sizeof(QEMUTimer));
647 ts->clock = clock;
648 ts->cb = cb;
649 ts->opaque = opaque;
650 return ts;
653 void qemu_free_timer(QEMUTimer *ts)
655 qemu_free(ts);
658 /* stop a timer, but do not dealloc it */
659 void qemu_del_timer(QEMUTimer *ts)
661 QEMUTimer **pt, *t;
663 /* NOTE: this code must be signal safe because
664 qemu_timer_expired() can be called from a signal. */
665 pt = &active_timers[ts->clock->type];
666 for(;;) {
667 t = *pt;
668 if (!t)
669 break;
670 if (t == ts) {
671 *pt = t->next;
672 break;
674 pt = &t->next;
678 /* modify the current timer so that it will be fired when current_time
679 >= expire_time. The corresponding callback will be called. */
680 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
682 QEMUTimer **pt, *t;
684 qemu_del_timer(ts);
686 /* add the timer in the sorted list */
687 /* NOTE: this code must be signal safe because
688 qemu_timer_expired() can be called from a signal. */
689 pt = &active_timers[ts->clock->type];
690 for(;;) {
691 t = *pt;
692 if (!t)
693 break;
694 if (t->expire_time > expire_time)
695 break;
696 pt = &t->next;
698 ts->expire_time = expire_time;
699 ts->next = *pt;
700 *pt = ts;
703 int qemu_timer_pending(QEMUTimer *ts)
705 QEMUTimer *t;
706 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
707 if (t == ts)
708 return 1;
710 return 0;
713 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
715 if (!timer_head)
716 return 0;
717 return (timer_head->expire_time <= current_time);
720 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
722 QEMUTimer *ts;
724 for(;;) {
725 ts = *ptimer_head;
726 if (!ts || ts->expire_time > current_time)
727 break;
728 /* remove timer from the list before calling the callback */
729 *ptimer_head = ts->next;
730 ts->next = NULL;
732 /* run the callback (the timer list can be modified) */
733 ts->cb(ts->opaque);
737 int64_t qemu_get_clock(QEMUClock *clock)
739 switch(clock->type) {
740 case QEMU_TIMER_REALTIME:
741 #ifdef _WIN32
742 return GetTickCount();
743 #else
745 struct tms tp;
747 /* Note that using gettimeofday() is not a good solution
748 for timers because its value change when the date is
749 modified. */
750 if (timer_freq == 100) {
751 return times(&tp) * 10;
752 } else {
753 return ((int64_t)times(&tp) * 1000) / timer_freq;
756 #endif
757 default:
758 case QEMU_TIMER_VIRTUAL:
759 return cpu_get_ticks();
763 /* save a timer */
764 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
766 uint64_t expire_time;
768 if (qemu_timer_pending(ts)) {
769 expire_time = ts->expire_time;
770 } else {
771 expire_time = -1;
773 qemu_put_be64(f, expire_time);
776 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
778 uint64_t expire_time;
780 expire_time = qemu_get_be64(f);
781 if (expire_time != -1) {
782 qemu_mod_timer(ts, expire_time);
783 } else {
784 qemu_del_timer(ts);
788 static void timer_save(QEMUFile *f, void *opaque)
790 if (cpu_ticks_enabled) {
791 hw_error("cannot save state if virtual timers are running");
793 qemu_put_be64s(f, &cpu_ticks_offset);
794 qemu_put_be64s(f, &ticks_per_sec);
797 static int timer_load(QEMUFile *f, void *opaque, int version_id)
799 if (version_id != 1)
800 return -EINVAL;
801 if (cpu_ticks_enabled) {
802 return -EINVAL;
804 qemu_get_be64s(f, &cpu_ticks_offset);
805 qemu_get_be64s(f, &ticks_per_sec);
806 return 0;
809 #ifdef _WIN32
810 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
811 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
812 #else
813 static void host_alarm_handler(int host_signum)
814 #endif
816 #if 0
817 #define DISP_FREQ 1000
819 static int64_t delta_min = INT64_MAX;
820 static int64_t delta_max, delta_cum, last_clock, delta, ti;
821 static int count;
822 ti = qemu_get_clock(vm_clock);
823 if (last_clock != 0) {
824 delta = ti - last_clock;
825 if (delta < delta_min)
826 delta_min = delta;
827 if (delta > delta_max)
828 delta_max = delta;
829 delta_cum += delta;
830 if (++count == DISP_FREQ) {
831 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
832 muldiv64(delta_min, 1000000, ticks_per_sec),
833 muldiv64(delta_max, 1000000, ticks_per_sec),
834 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
835 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
836 count = 0;
837 delta_min = INT64_MAX;
838 delta_max = 0;
839 delta_cum = 0;
842 last_clock = ti;
844 #endif
845 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
846 qemu_get_clock(vm_clock)) ||
847 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
848 qemu_get_clock(rt_clock))) {
849 /* stop the cpu because a timer occured */
850 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
854 #ifndef _WIN32
856 #if defined(__linux__)
858 #define RTC_FREQ 1024
860 static int rtc_fd;
862 static int start_rtc_timer(void)
864 rtc_fd = open("/dev/rtc", O_RDONLY);
865 if (rtc_fd < 0)
866 return -1;
867 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
868 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
869 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
870 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
871 goto fail;
873 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
874 fail:
875 close(rtc_fd);
876 return -1;
878 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
879 return 0;
882 #else
884 static int start_rtc_timer(void)
886 return -1;
889 #endif /* !defined(__linux__) */
891 #endif /* !defined(_WIN32) */
893 static void init_timers(void)
895 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
896 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
898 #ifdef _WIN32
900 int count=0;
901 timerID = timeSetEvent(10, // interval (ms)
902 0, // resolution
903 host_alarm_handler, // function
904 (DWORD)&count, // user parameter
905 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
906 if( !timerID ) {
907 perror("failed timer alarm");
908 exit(1);
911 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
912 #else
914 struct sigaction act;
915 struct itimerval itv;
917 /* get times() syscall frequency */
918 timer_freq = sysconf(_SC_CLK_TCK);
920 /* timer signal */
921 sigfillset(&act.sa_mask);
922 act.sa_flags = 0;
923 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
924 act.sa_flags |= SA_ONSTACK;
925 #endif
926 act.sa_handler = host_alarm_handler;
927 sigaction(SIGALRM, &act, NULL);
929 itv.it_interval.tv_sec = 0;
930 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
931 itv.it_value.tv_sec = 0;
932 itv.it_value.tv_usec = 10 * 1000;
933 setitimer(ITIMER_REAL, &itv, NULL);
934 /* we probe the tick duration of the kernel to inform the user if
935 the emulated kernel requested a too high timer frequency */
936 getitimer(ITIMER_REAL, &itv);
938 #if defined(__linux__)
939 if (itv.it_interval.tv_usec > 1000) {
940 /* try to use /dev/rtc to have a faster timer */
941 if (start_rtc_timer() < 0)
942 goto use_itimer;
943 /* disable itimer */
944 itv.it_interval.tv_sec = 0;
945 itv.it_interval.tv_usec = 0;
946 itv.it_value.tv_sec = 0;
947 itv.it_value.tv_usec = 0;
948 setitimer(ITIMER_REAL, &itv, NULL);
950 /* use the RTC */
951 sigaction(SIGIO, &act, NULL);
952 fcntl(rtc_fd, F_SETFL, O_ASYNC);
953 fcntl(rtc_fd, F_SETOWN, getpid());
954 } else
955 #endif /* defined(__linux__) */
957 use_itimer:
958 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
959 PIT_FREQ) / 1000000;
962 #endif
965 void quit_timers(void)
967 #ifdef _WIN32
968 timeKillEvent(timerID);
969 #endif
972 /***********************************************************/
973 /* character device */
975 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
977 return s->chr_write(s, buf, len);
980 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
982 char buf[4096];
983 va_list ap;
984 va_start(ap, fmt);
985 vsnprintf(buf, sizeof(buf), fmt, ap);
986 qemu_chr_write(s, buf, strlen(buf));
987 va_end(ap);
990 void qemu_chr_send_event(CharDriverState *s, int event)
992 if (s->chr_send_event)
993 s->chr_send_event(s, event);
996 void qemu_chr_add_read_handler(CharDriverState *s,
997 IOCanRWHandler *fd_can_read,
998 IOReadHandler *fd_read, void *opaque)
1000 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1003 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1005 s->chr_event = chr_event;
1008 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1010 return len;
1013 static void null_chr_add_read_handler(CharDriverState *chr,
1014 IOCanRWHandler *fd_can_read,
1015 IOReadHandler *fd_read, void *opaque)
1019 CharDriverState *qemu_chr_open_null(void)
1021 CharDriverState *chr;
1023 chr = qemu_mallocz(sizeof(CharDriverState));
1024 if (!chr)
1025 return NULL;
1026 chr->chr_write = null_chr_write;
1027 chr->chr_add_read_handler = null_chr_add_read_handler;
1028 return chr;
1031 #ifndef _WIN32
1033 typedef struct {
1034 int fd_in, fd_out;
1035 /* for nographic stdio only */
1036 IOCanRWHandler *fd_can_read;
1037 IOReadHandler *fd_read;
1038 void *fd_opaque;
1039 } FDCharDriver;
1041 #define STDIO_MAX_CLIENTS 2
1043 static int stdio_nb_clients;
1044 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1046 static int unix_write(int fd, const uint8_t *buf, int len1)
1048 int ret, len;
1050 len = len1;
1051 while (len > 0) {
1052 ret = write(fd, buf, len);
1053 if (ret < 0) {
1054 if (errno != EINTR && errno != EAGAIN)
1055 return -1;
1056 } else if (ret == 0) {
1057 break;
1058 } else {
1059 buf += ret;
1060 len -= ret;
1063 return len1 - len;
1066 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1068 FDCharDriver *s = chr->opaque;
1069 return unix_write(s->fd_out, buf, len);
1072 static void fd_chr_add_read_handler(CharDriverState *chr,
1073 IOCanRWHandler *fd_can_read,
1074 IOReadHandler *fd_read, void *opaque)
1076 FDCharDriver *s = chr->opaque;
1078 if (nographic && s->fd_in == 0) {
1079 s->fd_can_read = fd_can_read;
1080 s->fd_read = fd_read;
1081 s->fd_opaque = opaque;
1082 } else {
1083 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1087 /* open a character device to a unix fd */
1088 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1090 CharDriverState *chr;
1091 FDCharDriver *s;
1093 chr = qemu_mallocz(sizeof(CharDriverState));
1094 if (!chr)
1095 return NULL;
1096 s = qemu_mallocz(sizeof(FDCharDriver));
1097 if (!s) {
1098 free(chr);
1099 return NULL;
1101 s->fd_in = fd_in;
1102 s->fd_out = fd_out;
1103 chr->opaque = s;
1104 chr->chr_write = fd_chr_write;
1105 chr->chr_add_read_handler = fd_chr_add_read_handler;
1106 return chr;
1109 /* for STDIO, we handle the case where several clients use it
1110 (nographic mode) */
1112 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1114 static int term_got_escape, client_index;
1116 void term_print_help(void)
1118 printf("\n"
1119 "C-a h print this help\n"
1120 "C-a x exit emulator\n"
1121 "C-a s save disk data back to file (if -snapshot)\n"
1122 "C-a b send break (magic sysrq)\n"
1123 "C-a c switch between console and monitor\n"
1124 "C-a C-a send C-a\n"
1128 /* called when a char is received */
1129 static void stdio_received_byte(int ch)
1131 if (term_got_escape) {
1132 term_got_escape = 0;
1133 switch(ch) {
1134 case 'h':
1135 term_print_help();
1136 break;
1137 case 'x':
1138 exit(0);
1139 break;
1140 case 's':
1142 int i;
1143 for (i = 0; i < MAX_DISKS; i++) {
1144 if (bs_table[i])
1145 bdrv_commit(bs_table[i]);
1148 break;
1149 case 'b':
1150 if (client_index < stdio_nb_clients) {
1151 CharDriverState *chr;
1152 FDCharDriver *s;
1154 chr = stdio_clients[client_index];
1155 s = chr->opaque;
1156 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1158 break;
1159 case 'c':
1160 client_index++;
1161 if (client_index >= stdio_nb_clients)
1162 client_index = 0;
1163 if (client_index == 0) {
1164 /* send a new line in the monitor to get the prompt */
1165 ch = '\r';
1166 goto send_char;
1168 break;
1169 case TERM_ESCAPE:
1170 goto send_char;
1172 } else if (ch == TERM_ESCAPE) {
1173 term_got_escape = 1;
1174 } else {
1175 send_char:
1176 if (client_index < stdio_nb_clients) {
1177 uint8_t buf[1];
1178 CharDriverState *chr;
1179 FDCharDriver *s;
1181 chr = stdio_clients[client_index];
1182 s = chr->opaque;
1183 buf[0] = ch;
1184 /* XXX: should queue the char if the device is not
1185 ready */
1186 if (s->fd_can_read(s->fd_opaque) > 0)
1187 s->fd_read(s->fd_opaque, buf, 1);
1192 static int stdio_can_read(void *opaque)
1194 /* XXX: not strictly correct */
1195 return 1;
1198 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1200 int i;
1201 for(i = 0; i < size; i++)
1202 stdio_received_byte(buf[i]);
1205 /* init terminal so that we can grab keys */
1206 static struct termios oldtty;
1207 static int old_fd0_flags;
1209 static void term_exit(void)
1211 tcsetattr (0, TCSANOW, &oldtty);
1212 fcntl(0, F_SETFL, old_fd0_flags);
1215 static void term_init(void)
1217 struct termios tty;
1219 tcgetattr (0, &tty);
1220 oldtty = tty;
1221 old_fd0_flags = fcntl(0, F_GETFL);
1223 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1224 |INLCR|IGNCR|ICRNL|IXON);
1225 tty.c_oflag |= OPOST;
1226 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1227 /* if graphical mode, we allow Ctrl-C handling */
1228 if (nographic)
1229 tty.c_lflag &= ~ISIG;
1230 tty.c_cflag &= ~(CSIZE|PARENB);
1231 tty.c_cflag |= CS8;
1232 tty.c_cc[VMIN] = 1;
1233 tty.c_cc[VTIME] = 0;
1235 tcsetattr (0, TCSANOW, &tty);
1237 atexit(term_exit);
1239 fcntl(0, F_SETFL, O_NONBLOCK);
1242 CharDriverState *qemu_chr_open_stdio(void)
1244 CharDriverState *chr;
1246 if (nographic) {
1247 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1248 return NULL;
1249 chr = qemu_chr_open_fd(0, 1);
1250 if (stdio_nb_clients == 0)
1251 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1252 client_index = stdio_nb_clients;
1253 } else {
1254 if (stdio_nb_clients != 0)
1255 return NULL;
1256 chr = qemu_chr_open_fd(0, 1);
1258 stdio_clients[stdio_nb_clients++] = chr;
1259 if (stdio_nb_clients == 1) {
1260 /* set the terminal in raw mode */
1261 term_init();
1263 return chr;
1266 #if defined(__linux__)
1267 CharDriverState *qemu_chr_open_pty(void)
1269 char slave_name[1024];
1270 int master_fd, slave_fd;
1272 /* Not satisfying */
1273 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1274 return NULL;
1276 fprintf(stderr, "char device redirected to %s\n", slave_name);
1277 return qemu_chr_open_fd(master_fd, master_fd);
1279 #else
1280 CharDriverState *qemu_chr_open_pty(void)
1282 return NULL;
1284 #endif
1286 #endif /* !defined(_WIN32) */
1288 CharDriverState *qemu_chr_open(const char *filename)
1290 if (!strcmp(filename, "vc")) {
1291 return text_console_init(&display_state);
1292 } else if (!strcmp(filename, "null")) {
1293 return qemu_chr_open_null();
1294 } else
1295 #ifndef _WIN32
1296 if (!strcmp(filename, "pty")) {
1297 return qemu_chr_open_pty();
1298 } else if (!strcmp(filename, "stdio")) {
1299 return qemu_chr_open_stdio();
1300 } else
1301 #endif
1303 return NULL;
1307 /***********************************************************/
1308 /* Linux network device redirectors */
1310 void hex_dump(FILE *f, const uint8_t *buf, int size)
1312 int len, i, j, c;
1314 for(i=0;i<size;i+=16) {
1315 len = size - i;
1316 if (len > 16)
1317 len = 16;
1318 fprintf(f, "%08x ", i);
1319 for(j=0;j<16;j++) {
1320 if (j < len)
1321 fprintf(f, " %02x", buf[i+j]);
1322 else
1323 fprintf(f, " ");
1325 fprintf(f, " ");
1326 for(j=0;j<len;j++) {
1327 c = buf[i+j];
1328 if (c < ' ' || c > '~')
1329 c = '.';
1330 fprintf(f, "%c", c);
1332 fprintf(f, "\n");
1336 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1338 nd->send_packet(nd, buf, size);
1341 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1342 IOReadHandler *fd_read, void *opaque)
1344 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1347 /* dummy network adapter */
1349 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1353 static void dummy_add_read_packet(NetDriverState *nd,
1354 IOCanRWHandler *fd_can_read,
1355 IOReadHandler *fd_read, void *opaque)
1359 static int net_dummy_init(NetDriverState *nd)
1361 nd->send_packet = dummy_send_packet;
1362 nd->add_read_packet = dummy_add_read_packet;
1363 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1364 return 0;
1367 #if defined(CONFIG_SLIRP)
1369 /* slirp network adapter */
1371 static void *slirp_fd_opaque;
1372 static IOCanRWHandler *slirp_fd_can_read;
1373 static IOReadHandler *slirp_fd_read;
1374 static int slirp_inited;
1376 int slirp_can_output(void)
1378 return slirp_fd_can_read(slirp_fd_opaque);
1381 void slirp_output(const uint8_t *pkt, int pkt_len)
1383 #if 0
1384 printf("output:\n");
1385 hex_dump(stdout, pkt, pkt_len);
1386 #endif
1387 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1390 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1392 #if 0
1393 printf("input:\n");
1394 hex_dump(stdout, buf, size);
1395 #endif
1396 slirp_input(buf, size);
1399 static void slirp_add_read_packet(NetDriverState *nd,
1400 IOCanRWHandler *fd_can_read,
1401 IOReadHandler *fd_read, void *opaque)
1403 slirp_fd_opaque = opaque;
1404 slirp_fd_can_read = fd_can_read;
1405 slirp_fd_read = fd_read;
1408 static int net_slirp_init(NetDriverState *nd)
1410 if (!slirp_inited) {
1411 slirp_inited = 1;
1412 slirp_init();
1414 nd->send_packet = slirp_send_packet;
1415 nd->add_read_packet = slirp_add_read_packet;
1416 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1417 return 0;
1420 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1422 const char *p, *p1;
1423 int len;
1424 p = *pp;
1425 p1 = strchr(p, sep);
1426 if (!p1)
1427 return -1;
1428 len = p1 - p;
1429 p1++;
1430 if (buf_size > 0) {
1431 if (len > buf_size - 1)
1432 len = buf_size - 1;
1433 memcpy(buf, p, len);
1434 buf[len] = '\0';
1436 *pp = p1;
1437 return 0;
1440 static void net_slirp_redir(const char *redir_str)
1442 int is_udp;
1443 char buf[256], *r;
1444 const char *p;
1445 struct in_addr guest_addr;
1446 int host_port, guest_port;
1448 if (!slirp_inited) {
1449 slirp_inited = 1;
1450 slirp_init();
1453 p = redir_str;
1454 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1455 goto fail;
1456 if (!strcmp(buf, "tcp")) {
1457 is_udp = 0;
1458 } else if (!strcmp(buf, "udp")) {
1459 is_udp = 1;
1460 } else {
1461 goto fail;
1464 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1465 goto fail;
1466 host_port = strtol(buf, &r, 0);
1467 if (r == buf)
1468 goto fail;
1470 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1471 goto fail;
1472 if (buf[0] == '\0') {
1473 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1475 if (!inet_aton(buf, &guest_addr))
1476 goto fail;
1478 guest_port = strtol(p, &r, 0);
1479 if (r == p)
1480 goto fail;
1482 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1483 fprintf(stderr, "qemu: could not set up redirection\n");
1484 exit(1);
1486 return;
1487 fail:
1488 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1489 exit(1);
1492 #ifndef _WIN32
1494 char smb_dir[1024];
1496 static void smb_exit(void)
1498 DIR *d;
1499 struct dirent *de;
1500 char filename[1024];
1502 /* erase all the files in the directory */
1503 d = opendir(smb_dir);
1504 for(;;) {
1505 de = readdir(d);
1506 if (!de)
1507 break;
1508 if (strcmp(de->d_name, ".") != 0 &&
1509 strcmp(de->d_name, "..") != 0) {
1510 snprintf(filename, sizeof(filename), "%s/%s",
1511 smb_dir, de->d_name);
1512 unlink(filename);
1515 closedir(d);
1516 rmdir(smb_dir);
1519 /* automatic user mode samba server configuration */
1520 void net_slirp_smb(const char *exported_dir)
1522 char smb_conf[1024];
1523 char smb_cmdline[1024];
1524 FILE *f;
1526 if (!slirp_inited) {
1527 slirp_inited = 1;
1528 slirp_init();
1531 /* XXX: better tmp dir construction */
1532 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1533 if (mkdir(smb_dir, 0700) < 0) {
1534 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1535 exit(1);
1537 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1539 f = fopen(smb_conf, "w");
1540 if (!f) {
1541 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1542 exit(1);
1544 fprintf(f,
1545 "[global]\n"
1546 "private dir=%s\n"
1547 "smb ports=0\n"
1548 "socket address=127.0.0.1\n"
1549 "pid directory=%s\n"
1550 "lock directory=%s\n"
1551 "log file=%s/log.smbd\n"
1552 "smb passwd file=%s/smbpasswd\n"
1553 "security = share\n"
1554 "[qemu]\n"
1555 "path=%s\n"
1556 "read only=no\n"
1557 "guest ok=yes\n",
1558 smb_dir,
1559 smb_dir,
1560 smb_dir,
1561 smb_dir,
1562 smb_dir,
1563 exported_dir
1565 fclose(f);
1566 atexit(smb_exit);
1568 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1569 smb_conf);
1571 slirp_add_exec(0, smb_cmdline, 4, 139);
1574 #endif /* !defined(_WIN32) */
1576 #endif /* CONFIG_SLIRP */
1578 #if !defined(_WIN32)
1579 #ifdef _BSD
1580 static int tun_open(char *ifname, int ifname_size)
1582 int fd;
1583 char *dev;
1584 struct stat s;
1586 fd = open("/dev/tap", O_RDWR);
1587 if (fd < 0) {
1588 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1589 return -1;
1592 fstat(fd, &s);
1593 dev = devname(s.st_rdev, S_IFCHR);
1594 pstrcpy(ifname, ifname_size, dev);
1596 fcntl(fd, F_SETFL, O_NONBLOCK);
1597 return fd;
1599 #else
1600 static int tun_open(char *ifname, int ifname_size)
1602 struct ifreq ifr;
1603 int fd, ret;
1605 fd = open("/dev/net/tun", O_RDWR);
1606 if (fd < 0) {
1607 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1608 return -1;
1610 memset(&ifr, 0, sizeof(ifr));
1611 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1612 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1613 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1614 if (ret != 0) {
1615 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1616 close(fd);
1617 return -1;
1619 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1620 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1621 fcntl(fd, F_SETFL, O_NONBLOCK);
1622 return fd;
1624 #endif
1626 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1628 write(nd->fd, buf, size);
1631 static void tun_add_read_packet(NetDriverState *nd,
1632 IOCanRWHandler *fd_can_read,
1633 IOReadHandler *fd_read, void *opaque)
1635 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1638 static int net_tun_init(NetDriverState *nd)
1640 int pid, status;
1641 char *args[3];
1642 char **parg;
1644 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1645 if (nd->fd < 0)
1646 return -1;
1648 /* try to launch network init script */
1649 pid = fork();
1650 if (pid >= 0) {
1651 if (pid == 0) {
1652 parg = args;
1653 *parg++ = network_script;
1654 *parg++ = nd->ifname;
1655 *parg++ = NULL;
1656 execv(network_script, args);
1657 exit(1);
1659 while (waitpid(pid, &status, 0) != pid);
1660 if (!WIFEXITED(status) ||
1661 WEXITSTATUS(status) != 0) {
1662 fprintf(stderr, "%s: could not launch network script\n",
1663 network_script);
1666 nd->send_packet = tun_send_packet;
1667 nd->add_read_packet = tun_add_read_packet;
1668 return 0;
1671 static int net_fd_init(NetDriverState *nd, int fd)
1673 nd->fd = fd;
1674 nd->send_packet = tun_send_packet;
1675 nd->add_read_packet = tun_add_read_packet;
1676 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1677 return 0;
1680 #endif /* !_WIN32 */
1682 /***********************************************************/
1683 /* pid file */
1685 static char *pid_filename;
1687 /* Remove PID file. Called on normal exit */
1689 static void remove_pidfile(void)
1691 unlink (pid_filename);
1694 static void create_pidfile(const char *filename)
1696 struct stat pidstat;
1697 FILE *f;
1699 /* Try to write our PID to the named file */
1700 if (stat(filename, &pidstat) < 0) {
1701 if (errno == ENOENT) {
1702 if ((f = fopen (filename, "w")) == NULL) {
1703 perror("Opening pidfile");
1704 exit(1);
1706 fprintf(f, "%d\n", getpid());
1707 fclose(f);
1708 pid_filename = qemu_strdup(filename);
1709 if (!pid_filename) {
1710 fprintf(stderr, "Could not save PID filename");
1711 exit(1);
1713 atexit(remove_pidfile);
1715 } else {
1716 fprintf(stderr, "%s already exists. Remove it and try again.\n",
1717 filename);
1718 exit(1);
1722 /***********************************************************/
1723 /* dumb display */
1725 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1729 static void dumb_resize(DisplayState *ds, int w, int h)
1733 static void dumb_refresh(DisplayState *ds)
1735 vga_update_display();
1738 void dumb_display_init(DisplayState *ds)
1740 ds->data = NULL;
1741 ds->linesize = 0;
1742 ds->depth = 0;
1743 ds->dpy_update = dumb_update;
1744 ds->dpy_resize = dumb_resize;
1745 ds->dpy_refresh = dumb_refresh;
1748 #if !defined(CONFIG_SOFTMMU)
1749 /***********************************************************/
1750 /* cpu signal handler */
1751 static void host_segv_handler(int host_signum, siginfo_t *info,
1752 void *puc)
1754 if (cpu_signal_handler(host_signum, info, puc))
1755 return;
1756 if (stdio_nb_clients > 0)
1757 term_exit();
1758 abort();
1760 #endif
1762 /***********************************************************/
1763 /* I/O handling */
1765 #define MAX_IO_HANDLERS 64
1767 typedef struct IOHandlerRecord {
1768 int fd;
1769 IOCanRWHandler *fd_can_read;
1770 IOReadHandler *fd_read;
1771 void *opaque;
1772 /* temporary data */
1773 struct pollfd *ufd;
1774 int max_size;
1775 struct IOHandlerRecord *next;
1776 } IOHandlerRecord;
1778 static IOHandlerRecord *first_io_handler;
1780 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1781 IOReadHandler *fd_read, void *opaque)
1783 IOHandlerRecord *ioh;
1785 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1786 if (!ioh)
1787 return -1;
1788 ioh->fd = fd;
1789 ioh->fd_can_read = fd_can_read;
1790 ioh->fd_read = fd_read;
1791 ioh->opaque = opaque;
1792 ioh->next = first_io_handler;
1793 first_io_handler = ioh;
1794 return 0;
1797 void qemu_del_fd_read_handler(int fd)
1799 IOHandlerRecord **pioh, *ioh;
1801 pioh = &first_io_handler;
1802 for(;;) {
1803 ioh = *pioh;
1804 if (ioh == NULL)
1805 break;
1806 if (ioh->fd == fd) {
1807 *pioh = ioh->next;
1808 break;
1810 pioh = &ioh->next;
1814 /***********************************************************/
1815 /* savevm/loadvm support */
1817 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1819 fwrite(buf, 1, size, f);
1822 void qemu_put_byte(QEMUFile *f, int v)
1824 fputc(v, f);
1827 void qemu_put_be16(QEMUFile *f, unsigned int v)
1829 qemu_put_byte(f, v >> 8);
1830 qemu_put_byte(f, v);
1833 void qemu_put_be32(QEMUFile *f, unsigned int v)
1835 qemu_put_byte(f, v >> 24);
1836 qemu_put_byte(f, v >> 16);
1837 qemu_put_byte(f, v >> 8);
1838 qemu_put_byte(f, v);
1841 void qemu_put_be64(QEMUFile *f, uint64_t v)
1843 qemu_put_be32(f, v >> 32);
1844 qemu_put_be32(f, v);
1847 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1849 return fread(buf, 1, size, f);
1852 int qemu_get_byte(QEMUFile *f)
1854 int v;
1855 v = fgetc(f);
1856 if (v == EOF)
1857 return 0;
1858 else
1859 return v;
1862 unsigned int qemu_get_be16(QEMUFile *f)
1864 unsigned int v;
1865 v = qemu_get_byte(f) << 8;
1866 v |= qemu_get_byte(f);
1867 return v;
1870 unsigned int qemu_get_be32(QEMUFile *f)
1872 unsigned int v;
1873 v = qemu_get_byte(f) << 24;
1874 v |= qemu_get_byte(f) << 16;
1875 v |= qemu_get_byte(f) << 8;
1876 v |= qemu_get_byte(f);
1877 return v;
1880 uint64_t qemu_get_be64(QEMUFile *f)
1882 uint64_t v;
1883 v = (uint64_t)qemu_get_be32(f) << 32;
1884 v |= qemu_get_be32(f);
1885 return v;
1888 int64_t qemu_ftell(QEMUFile *f)
1890 return ftell(f);
1893 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1895 if (fseek(f, pos, whence) < 0)
1896 return -1;
1897 return ftell(f);
1900 typedef struct SaveStateEntry {
1901 char idstr[256];
1902 int instance_id;
1903 int version_id;
1904 SaveStateHandler *save_state;
1905 LoadStateHandler *load_state;
1906 void *opaque;
1907 struct SaveStateEntry *next;
1908 } SaveStateEntry;
1910 static SaveStateEntry *first_se;
1912 int register_savevm(const char *idstr,
1913 int instance_id,
1914 int version_id,
1915 SaveStateHandler *save_state,
1916 LoadStateHandler *load_state,
1917 void *opaque)
1919 SaveStateEntry *se, **pse;
1921 se = qemu_malloc(sizeof(SaveStateEntry));
1922 if (!se)
1923 return -1;
1924 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1925 se->instance_id = instance_id;
1926 se->version_id = version_id;
1927 se->save_state = save_state;
1928 se->load_state = load_state;
1929 se->opaque = opaque;
1930 se->next = NULL;
1932 /* add at the end of list */
1933 pse = &first_se;
1934 while (*pse != NULL)
1935 pse = &(*pse)->next;
1936 *pse = se;
1937 return 0;
1940 #define QEMU_VM_FILE_MAGIC 0x5145564d
1941 #define QEMU_VM_FILE_VERSION 0x00000001
1943 int qemu_savevm(const char *filename)
1945 SaveStateEntry *se;
1946 QEMUFile *f;
1947 int len, len_pos, cur_pos, saved_vm_running, ret;
1949 saved_vm_running = vm_running;
1950 vm_stop(0);
1952 f = fopen(filename, "wb");
1953 if (!f) {
1954 ret = -1;
1955 goto the_end;
1958 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1959 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1961 for(se = first_se; se != NULL; se = se->next) {
1962 /* ID string */
1963 len = strlen(se->idstr);
1964 qemu_put_byte(f, len);
1965 qemu_put_buffer(f, se->idstr, len);
1967 qemu_put_be32(f, se->instance_id);
1968 qemu_put_be32(f, se->version_id);
1970 /* record size: filled later */
1971 len_pos = ftell(f);
1972 qemu_put_be32(f, 0);
1974 se->save_state(f, se->opaque);
1976 /* fill record size */
1977 cur_pos = ftell(f);
1978 len = ftell(f) - len_pos - 4;
1979 fseek(f, len_pos, SEEK_SET);
1980 qemu_put_be32(f, len);
1981 fseek(f, cur_pos, SEEK_SET);
1984 fclose(f);
1985 ret = 0;
1986 the_end:
1987 if (saved_vm_running)
1988 vm_start();
1989 return ret;
1992 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1994 SaveStateEntry *se;
1996 for(se = first_se; se != NULL; se = se->next) {
1997 if (!strcmp(se->idstr, idstr) &&
1998 instance_id == se->instance_id)
1999 return se;
2001 return NULL;
2004 int qemu_loadvm(const char *filename)
2006 SaveStateEntry *se;
2007 QEMUFile *f;
2008 int len, cur_pos, ret, instance_id, record_len, version_id;
2009 int saved_vm_running;
2010 unsigned int v;
2011 char idstr[256];
2013 saved_vm_running = vm_running;
2014 vm_stop(0);
2016 f = fopen(filename, "rb");
2017 if (!f) {
2018 ret = -1;
2019 goto the_end;
2022 v = qemu_get_be32(f);
2023 if (v != QEMU_VM_FILE_MAGIC)
2024 goto fail;
2025 v = qemu_get_be32(f);
2026 if (v != QEMU_VM_FILE_VERSION) {
2027 fail:
2028 fclose(f);
2029 ret = -1;
2030 goto the_end;
2032 for(;;) {
2033 #if defined (DO_TB_FLUSH)
2034 tb_flush(global_env);
2035 #endif
2036 len = qemu_get_byte(f);
2037 if (feof(f))
2038 break;
2039 qemu_get_buffer(f, idstr, len);
2040 idstr[len] = '\0';
2041 instance_id = qemu_get_be32(f);
2042 version_id = qemu_get_be32(f);
2043 record_len = qemu_get_be32(f);
2044 #if 0
2045 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2046 idstr, instance_id, version_id, record_len);
2047 #endif
2048 cur_pos = ftell(f);
2049 se = find_se(idstr, instance_id);
2050 if (!se) {
2051 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2052 instance_id, idstr);
2053 } else {
2054 ret = se->load_state(f, se->opaque, version_id);
2055 if (ret < 0) {
2056 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2057 instance_id, idstr);
2060 /* always seek to exact end of record */
2061 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2063 fclose(f);
2064 ret = 0;
2065 the_end:
2066 if (saved_vm_running)
2067 vm_start();
2068 return ret;
2071 /***********************************************************/
2072 /* cpu save/restore */
2074 #if defined(TARGET_I386)
2076 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2078 qemu_put_be32(f, dt->selector);
2079 qemu_put_betl(f, dt->base);
2080 qemu_put_be32(f, dt->limit);
2081 qemu_put_be32(f, dt->flags);
2084 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2086 dt->selector = qemu_get_be32(f);
2087 dt->base = qemu_get_betl(f);
2088 dt->limit = qemu_get_be32(f);
2089 dt->flags = qemu_get_be32(f);
2092 void cpu_save(QEMUFile *f, void *opaque)
2094 CPUState *env = opaque;
2095 uint16_t fptag, fpus, fpuc, fpregs_format;
2096 uint32_t hflags;
2097 int i;
2099 for(i = 0; i < CPU_NB_REGS; i++)
2100 qemu_put_betls(f, &env->regs[i]);
2101 qemu_put_betls(f, &env->eip);
2102 qemu_put_betls(f, &env->eflags);
2103 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2104 qemu_put_be32s(f, &hflags);
2106 /* FPU */
2107 fpuc = env->fpuc;
2108 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2109 fptag = 0;
2110 for(i = 0; i < 8; i++) {
2111 fptag |= ((!env->fptags[i]) << i);
2114 qemu_put_be16s(f, &fpuc);
2115 qemu_put_be16s(f, &fpus);
2116 qemu_put_be16s(f, &fptag);
2118 #ifdef USE_X86LDOUBLE
2119 fpregs_format = 0;
2120 #else
2121 fpregs_format = 1;
2122 #endif
2123 qemu_put_be16s(f, &fpregs_format);
2125 for(i = 0; i < 8; i++) {
2126 #ifdef USE_X86LDOUBLE
2128 uint64_t mant;
2129 uint16_t exp;
2130 /* we save the real CPU data (in case of MMX usage only 'mant'
2131 contains the MMX register */
2132 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
2133 qemu_put_be64(f, mant);
2134 qemu_put_be16(f, exp);
2136 #else
2137 /* if we use doubles for float emulation, we save the doubles to
2138 avoid losing information in case of MMX usage. It can give
2139 problems if the image is restored on a CPU where long
2140 doubles are used instead. */
2141 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
2142 #endif
2145 for(i = 0; i < 6; i++)
2146 cpu_put_seg(f, &env->segs[i]);
2147 cpu_put_seg(f, &env->ldt);
2148 cpu_put_seg(f, &env->tr);
2149 cpu_put_seg(f, &env->gdt);
2150 cpu_put_seg(f, &env->idt);
2152 qemu_put_be32s(f, &env->sysenter_cs);
2153 qemu_put_be32s(f, &env->sysenter_esp);
2154 qemu_put_be32s(f, &env->sysenter_eip);
2156 qemu_put_betls(f, &env->cr[0]);
2157 qemu_put_betls(f, &env->cr[2]);
2158 qemu_put_betls(f, &env->cr[3]);
2159 qemu_put_betls(f, &env->cr[4]);
2161 for(i = 0; i < 8; i++)
2162 qemu_put_betls(f, &env->dr[i]);
2164 /* MMU */
2165 qemu_put_be32s(f, &env->a20_mask);
2167 /* XMM */
2168 qemu_put_be32s(f, &env->mxcsr);
2169 for(i = 0; i < CPU_NB_REGS; i++) {
2170 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2171 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2174 #ifdef TARGET_X86_64
2175 qemu_put_be64s(f, &env->efer);
2176 qemu_put_be64s(f, &env->star);
2177 qemu_put_be64s(f, &env->lstar);
2178 qemu_put_be64s(f, &env->cstar);
2179 qemu_put_be64s(f, &env->fmask);
2180 qemu_put_be64s(f, &env->kernelgsbase);
2181 #endif
2184 #ifdef USE_X86LDOUBLE
2185 /* XXX: add that in a FPU generic layer */
2186 union x86_longdouble {
2187 uint64_t mant;
2188 uint16_t exp;
2191 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
2192 #define EXPBIAS1 1023
2193 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
2194 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
2196 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
2198 int e;
2199 /* mantissa */
2200 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
2201 /* exponent + sign */
2202 e = EXPD1(temp) - EXPBIAS1 + 16383;
2203 e |= SIGND1(temp) >> 16;
2204 p->exp = e;
2206 #endif
2208 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2210 CPUState *env = opaque;
2211 int i, guess_mmx;
2212 uint32_t hflags;
2213 uint16_t fpus, fpuc, fptag, fpregs_format;
2215 if (version_id != 3)
2216 return -EINVAL;
2217 for(i = 0; i < CPU_NB_REGS; i++)
2218 qemu_get_betls(f, &env->regs[i]);
2219 qemu_get_betls(f, &env->eip);
2220 qemu_get_betls(f, &env->eflags);
2221 qemu_get_be32s(f, &hflags);
2223 qemu_get_be16s(f, &fpuc);
2224 qemu_get_be16s(f, &fpus);
2225 qemu_get_be16s(f, &fptag);
2226 qemu_get_be16s(f, &fpregs_format);
2228 /* NOTE: we cannot always restore the FPU state if the image come
2229 from a host with a different 'USE_X86LDOUBLE' define. We guess
2230 if we are in an MMX state to restore correctly in that case. */
2231 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
2232 for(i = 0; i < 8; i++) {
2233 uint64_t mant;
2234 uint16_t exp;
2236 switch(fpregs_format) {
2237 case 0:
2238 mant = qemu_get_be64(f);
2239 exp = qemu_get_be16(f);
2240 #ifdef USE_X86LDOUBLE
2241 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2242 #else
2243 /* difficult case */
2244 if (guess_mmx)
2245 env->fpregs[i].mmx.MMX_Q(0) = mant;
2246 else
2247 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2248 #endif
2249 break;
2250 case 1:
2251 mant = qemu_get_be64(f);
2252 #ifdef USE_X86LDOUBLE
2254 union x86_longdouble *p;
2255 /* difficult case */
2256 p = (void *)&env->fpregs[i];
2257 if (guess_mmx) {
2258 p->mant = mant;
2259 p->exp = 0xffff;
2260 } else {
2261 fp64_to_fp80(p, mant);
2264 #else
2265 env->fpregs[i].mmx.MMX_Q(0) = mant;
2266 #endif
2267 break;
2268 default:
2269 return -EINVAL;
2273 env->fpuc = fpuc;
2274 env->fpstt = (fpus >> 11) & 7;
2275 env->fpus = fpus & ~0x3800;
2276 fptag ^= 0xff;
2277 for(i = 0; i < 8; i++) {
2278 env->fptags[i] = (fptag >> i) & 1;
2281 for(i = 0; i < 6; i++)
2282 cpu_get_seg(f, &env->segs[i]);
2283 cpu_get_seg(f, &env->ldt);
2284 cpu_get_seg(f, &env->tr);
2285 cpu_get_seg(f, &env->gdt);
2286 cpu_get_seg(f, &env->idt);
2288 qemu_get_be32s(f, &env->sysenter_cs);
2289 qemu_get_be32s(f, &env->sysenter_esp);
2290 qemu_get_be32s(f, &env->sysenter_eip);
2292 qemu_get_betls(f, &env->cr[0]);
2293 qemu_get_betls(f, &env->cr[2]);
2294 qemu_get_betls(f, &env->cr[3]);
2295 qemu_get_betls(f, &env->cr[4]);
2297 for(i = 0; i < 8; i++)
2298 qemu_get_betls(f, &env->dr[i]);
2300 /* MMU */
2301 qemu_get_be32s(f, &env->a20_mask);
2303 qemu_get_be32s(f, &env->mxcsr);
2304 for(i = 0; i < CPU_NB_REGS; i++) {
2305 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2306 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2309 #ifdef TARGET_X86_64
2310 qemu_get_be64s(f, &env->efer);
2311 qemu_get_be64s(f, &env->star);
2312 qemu_get_be64s(f, &env->lstar);
2313 qemu_get_be64s(f, &env->cstar);
2314 qemu_get_be64s(f, &env->fmask);
2315 qemu_get_be64s(f, &env->kernelgsbase);
2316 #endif
2318 /* XXX: compute hflags from scratch, except for CPL and IIF */
2319 env->hflags = hflags;
2320 tlb_flush(env, 1);
2321 return 0;
2324 #elif defined(TARGET_PPC)
2325 void cpu_save(QEMUFile *f, void *opaque)
2329 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2331 return 0;
2333 #elif defined(TARGET_SPARC)
2334 void cpu_save(QEMUFile *f, void *opaque)
2336 CPUState *env = opaque;
2337 int i;
2338 uint32_t tmp;
2340 for(i = 0; i < 8; i++)
2341 qemu_put_betls(f, &env->gregs[i]);
2342 for(i = 0; i < NWINDOWS * 16; i++)
2343 qemu_put_betls(f, &env->regbase[i]);
2345 /* FPU */
2346 for(i = 0; i < TARGET_FPREGS; i++) {
2347 union {
2348 TARGET_FPREG_T f;
2349 target_ulong i;
2350 } u;
2351 u.f = env->fpr[i];
2352 qemu_put_betl(f, u.i);
2355 qemu_put_betls(f, &env->pc);
2356 qemu_put_betls(f, &env->npc);
2357 qemu_put_betls(f, &env->y);
2358 tmp = GET_PSR(env);
2359 qemu_put_be32(f, tmp);
2360 qemu_put_be32s(f, &env->fsr);
2361 qemu_put_be32s(f, &env->wim);
2362 qemu_put_be32s(f, &env->tbr);
2363 /* MMU */
2364 for(i = 0; i < 16; i++)
2365 qemu_put_be32s(f, &env->mmuregs[i]);
2368 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2370 CPUState *env = opaque;
2371 int i;
2372 uint32_t tmp;
2374 for(i = 0; i < 8; i++)
2375 qemu_get_betls(f, &env->gregs[i]);
2376 for(i = 0; i < NWINDOWS * 16; i++)
2377 qemu_get_betls(f, &env->regbase[i]);
2379 /* FPU */
2380 for(i = 0; i < TARGET_FPREGS; i++) {
2381 union {
2382 TARGET_FPREG_T f;
2383 target_ulong i;
2384 } u;
2385 u.i = qemu_get_betl(f);
2386 env->fpr[i] = u.f;
2389 qemu_get_betls(f, &env->pc);
2390 qemu_get_betls(f, &env->npc);
2391 qemu_get_betls(f, &env->y);
2392 tmp = qemu_get_be32(f);
2393 env->cwp = 0; /* needed to ensure that the wrapping registers are
2394 correctly updated */
2395 PUT_PSR(env, tmp);
2396 qemu_get_be32s(f, &env->fsr);
2397 qemu_get_be32s(f, &env->wim);
2398 qemu_get_be32s(f, &env->tbr);
2399 /* MMU */
2400 for(i = 0; i < 16; i++)
2401 qemu_get_be32s(f, &env->mmuregs[i]);
2403 tlb_flush(env, 1);
2404 return 0;
2406 #else
2408 #warning No CPU save/restore functions
2410 #endif
2412 /***********************************************************/
2413 /* ram save/restore */
2415 /* we just avoid storing empty pages */
2416 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2418 int i, v;
2420 v = buf[0];
2421 for(i = 1; i < len; i++) {
2422 if (buf[i] != v)
2423 goto normal_save;
2425 qemu_put_byte(f, 1);
2426 qemu_put_byte(f, v);
2427 return;
2428 normal_save:
2429 qemu_put_byte(f, 0);
2430 qemu_put_buffer(f, buf, len);
2433 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2435 int v;
2437 v = qemu_get_byte(f);
2438 switch(v) {
2439 case 0:
2440 if (qemu_get_buffer(f, buf, len) != len)
2441 return -EIO;
2442 break;
2443 case 1:
2444 v = qemu_get_byte(f);
2445 memset(buf, v, len);
2446 break;
2447 default:
2448 return -EINVAL;
2450 return 0;
2453 static void ram_save(QEMUFile *f, void *opaque)
2455 int i;
2456 qemu_put_be32(f, phys_ram_size);
2457 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2458 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2462 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2464 int i, ret;
2466 if (version_id != 1)
2467 return -EINVAL;
2468 if (qemu_get_be32(f) != phys_ram_size)
2469 return -EINVAL;
2470 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2471 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2472 if (ret)
2473 return ret;
2475 return 0;
2478 /***********************************************************/
2479 /* main execution loop */
2481 void gui_update(void *opaque)
2483 display_state.dpy_refresh(&display_state);
2484 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2487 /* XXX: support several handlers */
2488 VMStopHandler *vm_stop_cb;
2489 VMStopHandler *vm_stop_opaque;
2491 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2493 vm_stop_cb = cb;
2494 vm_stop_opaque = opaque;
2495 return 0;
2498 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2500 vm_stop_cb = NULL;
2503 void vm_start(void)
2505 if (!vm_running) {
2506 cpu_enable_ticks();
2507 vm_running = 1;
2511 void vm_stop(int reason)
2513 if (vm_running) {
2514 cpu_disable_ticks();
2515 vm_running = 0;
2516 if (reason != 0) {
2517 if (vm_stop_cb) {
2518 vm_stop_cb(vm_stop_opaque, reason);
2524 /* reset/shutdown handler */
2526 typedef struct QEMUResetEntry {
2527 QEMUResetHandler *func;
2528 void *opaque;
2529 struct QEMUResetEntry *next;
2530 } QEMUResetEntry;
2532 static QEMUResetEntry *first_reset_entry;
2533 static int reset_requested;
2534 static int shutdown_requested;
2536 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2538 QEMUResetEntry **pre, *re;
2540 pre = &first_reset_entry;
2541 while (*pre != NULL)
2542 pre = &(*pre)->next;
2543 re = qemu_mallocz(sizeof(QEMUResetEntry));
2544 re->func = func;
2545 re->opaque = opaque;
2546 re->next = NULL;
2547 *pre = re;
2550 void qemu_system_reset(void)
2552 QEMUResetEntry *re;
2554 /* reset all devices */
2555 for(re = first_reset_entry; re != NULL; re = re->next) {
2556 re->func(re->opaque);
2560 void qemu_system_reset_request(void)
2562 reset_requested = 1;
2563 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2566 void qemu_system_shutdown_request(void)
2568 shutdown_requested = 1;
2569 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2572 static void main_cpu_reset(void *opaque)
2574 #if defined(TARGET_I386) || defined(TARGET_SPARC)
2575 CPUState *env = opaque;
2576 cpu_reset(env);
2577 #endif
2580 void main_loop_wait(int timeout)
2582 #ifndef _WIN32
2583 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2584 IOHandlerRecord *ioh, *ioh_next;
2585 uint8_t buf[4096];
2586 int n, max_size;
2587 #endif
2588 int ret;
2590 #ifdef _WIN32
2591 if (timeout > 0)
2592 Sleep(timeout);
2593 #else
2594 /* poll any events */
2595 /* XXX: separate device handlers from system ones */
2596 pf = ufds;
2597 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2598 if (!ioh->fd_can_read) {
2599 max_size = 0;
2600 pf->fd = ioh->fd;
2601 pf->events = POLLIN;
2602 ioh->ufd = pf;
2603 pf++;
2604 } else {
2605 max_size = ioh->fd_can_read(ioh->opaque);
2606 if (max_size > 0) {
2607 if (max_size > sizeof(buf))
2608 max_size = sizeof(buf);
2609 pf->fd = ioh->fd;
2610 pf->events = POLLIN;
2611 ioh->ufd = pf;
2612 pf++;
2613 } else {
2614 ioh->ufd = NULL;
2617 ioh->max_size = max_size;
2620 ret = poll(ufds, pf - ufds, timeout);
2621 if (ret > 0) {
2622 /* XXX: better handling of removal */
2623 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2624 ioh_next = ioh->next;
2625 pf = ioh->ufd;
2626 if (pf) {
2627 if (pf->revents & POLLIN) {
2628 if (ioh->max_size == 0) {
2629 /* just a read event */
2630 ioh->fd_read(ioh->opaque, NULL, 0);
2631 } else {
2632 n = read(ioh->fd, buf, ioh->max_size);
2633 if (n >= 0) {
2634 ioh->fd_read(ioh->opaque, buf, n);
2635 } else if (errno != EAGAIN) {
2636 ioh->fd_read(ioh->opaque, NULL, -errno);
2643 #endif /* !defined(_WIN32) */
2644 #if defined(CONFIG_SLIRP)
2645 /* XXX: merge with poll() */
2646 if (slirp_inited) {
2647 fd_set rfds, wfds, xfds;
2648 int nfds;
2649 struct timeval tv;
2651 nfds = -1;
2652 FD_ZERO(&rfds);
2653 FD_ZERO(&wfds);
2654 FD_ZERO(&xfds);
2655 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2656 tv.tv_sec = 0;
2657 tv.tv_usec = 0;
2658 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2659 if (ret >= 0) {
2660 slirp_select_poll(&rfds, &wfds, &xfds);
2663 #endif
2665 if (vm_running) {
2666 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2667 qemu_get_clock(vm_clock));
2668 /* run dma transfers, if any */
2669 DMA_run();
2672 /* real time timers */
2673 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2674 qemu_get_clock(rt_clock));
2677 int main_loop(void)
2679 int ret, timeout;
2680 CPUState *env = global_env;
2682 for(;;) {
2683 if (vm_running) {
2684 ret = cpu_exec(env);
2685 if (shutdown_requested) {
2686 ret = EXCP_INTERRUPT;
2687 break;
2689 if (reset_requested) {
2690 reset_requested = 0;
2691 qemu_system_reset();
2692 ret = EXCP_INTERRUPT;
2694 if (ret == EXCP_DEBUG) {
2695 vm_stop(EXCP_DEBUG);
2697 /* if hlt instruction, we wait until the next IRQ */
2698 /* XXX: use timeout computed from timers */
2699 if (ret == EXCP_HLT)
2700 timeout = 10;
2701 else
2702 timeout = 0;
2703 } else {
2704 timeout = 10;
2706 main_loop_wait(timeout);
2708 cpu_disable_ticks();
2709 return ret;
2712 void help(void)
2714 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2715 "usage: %s [options] [disk_image]\n"
2716 "\n"
2717 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2718 "\n"
2719 "Standard options:\n"
2720 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2721 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2722 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2723 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2724 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2725 "-snapshot write to temporary files instead of disk image files\n"
2726 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2727 "-nographic disable graphical output and redirect serial I/Os to console\n"
2728 #ifndef _WIN32
2729 "-k language use keyboard layout (for example \"fr\" for French)\n"
2730 #endif
2731 "-enable-audio enable audio support\n"
2732 "-localtime set the real time clock to local time [default=utc]\n"
2733 "-full-screen start in full screen\n"
2734 #ifdef TARGET_PPC
2735 "-prep Simulate a PREP system (default is PowerMAC)\n"
2736 #endif
2737 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2738 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
2739 #endif
2740 "\n"
2741 "Network options:\n"
2742 "-nics n simulate 'n' network cards [default=1]\n"
2743 "-macaddr addr set the mac address of the first interface\n"
2744 "-n script set tap/tun network init script [default=%s]\n"
2745 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2746 #ifdef CONFIG_SLIRP
2747 "-user-net use user mode network stack [default if no tap/tun script]\n"
2748 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2749 #ifndef _WIN32
2750 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2751 #endif
2752 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2753 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2754 #endif
2755 "-dummy-net use dummy network stack\n"
2756 "\n"
2757 "Linux boot specific:\n"
2758 "-kernel bzImage use 'bzImage' as kernel image\n"
2759 "-append cmdline use 'cmdline' as kernel command line\n"
2760 "-initrd file use 'file' as initial ram disk\n"
2761 "\n"
2762 "Debug/Expert options:\n"
2763 "-monitor dev redirect the monitor to char device 'dev'\n"
2764 "-serial dev redirect the serial port to char device 'dev'\n"
2765 "-parallel dev redirect the parallel port to char device 'dev'\n"
2766 "-pidfile file Write PID to 'file'\n"
2767 "-S freeze CPU at startup (use 'c' to start execution)\n"
2768 "-s wait gdb connection to port %d\n"
2769 "-p port change gdb connection port\n"
2770 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
2771 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
2772 " translation (t=none or lba) (usually qemu can guess them)\n"
2773 "-L path set the directory for the BIOS and VGA BIOS\n"
2774 #ifdef USE_KQEMU
2775 "-no-kqemu disable KQEMU kernel module usage\n"
2776 #endif
2777 #ifdef USE_CODE_COPY
2778 "-no-code-copy disable code copy acceleration\n"
2779 #endif
2780 #ifdef TARGET_I386
2781 "-isa simulate an ISA-only system (default is PCI system)\n"
2782 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2783 " (default is CL-GD5446 PCI VGA)\n"
2784 #endif
2785 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2786 "\n"
2787 "During emulation, the following keys are useful:\n"
2788 "ctrl-alt-f toggle full screen\n"
2789 "ctrl-alt-n switch to virtual console 'n'\n"
2790 "ctrl-alt toggle mouse and keyboard grab\n"
2791 "\n"
2792 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2794 #ifdef CONFIG_SOFTMMU
2795 "qemu",
2796 #else
2797 "qemu-fast",
2798 #endif
2799 DEFAULT_RAM_SIZE,
2800 DEFAULT_NETWORK_SCRIPT,
2801 DEFAULT_GDBSTUB_PORT,
2802 "/tmp/qemu.log");
2803 #ifndef CONFIG_SOFTMMU
2804 printf("\n"
2805 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2806 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2807 "PC emulation.\n");
2808 #endif
2809 exit(1);
2812 #define HAS_ARG 0x0001
2814 enum {
2815 QEMU_OPTION_h,
2817 QEMU_OPTION_fda,
2818 QEMU_OPTION_fdb,
2819 QEMU_OPTION_hda,
2820 QEMU_OPTION_hdb,
2821 QEMU_OPTION_hdc,
2822 QEMU_OPTION_hdd,
2823 QEMU_OPTION_cdrom,
2824 QEMU_OPTION_boot,
2825 QEMU_OPTION_snapshot,
2826 QEMU_OPTION_m,
2827 QEMU_OPTION_nographic,
2828 QEMU_OPTION_enable_audio,
2830 QEMU_OPTION_nics,
2831 QEMU_OPTION_macaddr,
2832 QEMU_OPTION_n,
2833 QEMU_OPTION_tun_fd,
2834 QEMU_OPTION_user_net,
2835 QEMU_OPTION_tftp,
2836 QEMU_OPTION_smb,
2837 QEMU_OPTION_redir,
2838 QEMU_OPTION_dummy_net,
2840 QEMU_OPTION_kernel,
2841 QEMU_OPTION_append,
2842 QEMU_OPTION_initrd,
2844 QEMU_OPTION_S,
2845 QEMU_OPTION_s,
2846 QEMU_OPTION_p,
2847 QEMU_OPTION_d,
2848 QEMU_OPTION_hdachs,
2849 QEMU_OPTION_L,
2850 QEMU_OPTION_no_code_copy,
2851 QEMU_OPTION_pci,
2852 QEMU_OPTION_isa,
2853 QEMU_OPTION_prep,
2854 QEMU_OPTION_k,
2855 QEMU_OPTION_localtime,
2856 QEMU_OPTION_cirrusvga,
2857 QEMU_OPTION_g,
2858 QEMU_OPTION_std_vga,
2859 QEMU_OPTION_monitor,
2860 QEMU_OPTION_serial,
2861 QEMU_OPTION_parallel,
2862 QEMU_OPTION_loadvm,
2863 QEMU_OPTION_full_screen,
2864 QEMU_OPTION_pidfile,
2865 QEMU_OPTION_no_kqemu,
2868 typedef struct QEMUOption {
2869 const char *name;
2870 int flags;
2871 int index;
2872 } QEMUOption;
2874 const QEMUOption qemu_options[] = {
2875 { "h", 0, QEMU_OPTION_h },
2877 { "fda", HAS_ARG, QEMU_OPTION_fda },
2878 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2879 { "hda", HAS_ARG, QEMU_OPTION_hda },
2880 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2881 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2882 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2883 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2884 { "boot", HAS_ARG, QEMU_OPTION_boot },
2885 { "snapshot", 0, QEMU_OPTION_snapshot },
2886 { "m", HAS_ARG, QEMU_OPTION_m },
2887 { "nographic", 0, QEMU_OPTION_nographic },
2888 { "k", HAS_ARG, QEMU_OPTION_k },
2889 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2891 { "nics", HAS_ARG, QEMU_OPTION_nics},
2892 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2893 { "n", HAS_ARG, QEMU_OPTION_n },
2894 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2895 #ifdef CONFIG_SLIRP
2896 { "user-net", 0, QEMU_OPTION_user_net },
2897 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2898 #ifndef _WIN32
2899 { "smb", HAS_ARG, QEMU_OPTION_smb },
2900 #endif
2901 { "redir", HAS_ARG, QEMU_OPTION_redir },
2902 #endif
2903 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2905 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2906 { "append", HAS_ARG, QEMU_OPTION_append },
2907 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2909 { "S", 0, QEMU_OPTION_S },
2910 { "s", 0, QEMU_OPTION_s },
2911 { "p", HAS_ARG, QEMU_OPTION_p },
2912 { "d", HAS_ARG, QEMU_OPTION_d },
2913 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2914 { "L", HAS_ARG, QEMU_OPTION_L },
2915 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2916 #ifdef USE_KQEMU
2917 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
2918 #endif
2919 #ifdef TARGET_PPC
2920 { "prep", 0, QEMU_OPTION_prep },
2921 #endif
2922 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2923 { "g", 1, QEMU_OPTION_g },
2924 #endif
2925 { "localtime", 0, QEMU_OPTION_localtime },
2926 { "isa", 0, QEMU_OPTION_isa },
2927 { "std-vga", 0, QEMU_OPTION_std_vga },
2928 { "monitor", 1, QEMU_OPTION_monitor },
2929 { "serial", 1, QEMU_OPTION_serial },
2930 { "parallel", 1, QEMU_OPTION_parallel },
2931 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2932 { "full-screen", 0, QEMU_OPTION_full_screen },
2933 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
2935 /* temporary options */
2936 { "pci", 0, QEMU_OPTION_pci },
2937 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2938 { NULL },
2941 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2943 /* this stack is only used during signal handling */
2944 #define SIGNAL_STACK_SIZE 32768
2946 static uint8_t *signal_stack;
2948 #endif
2950 /* password input */
2952 static BlockDriverState *get_bdrv(int index)
2954 BlockDriverState *bs;
2956 if (index < 4) {
2957 bs = bs_table[index];
2958 } else if (index < 6) {
2959 bs = fd_table[index - 4];
2960 } else {
2961 bs = NULL;
2963 return bs;
2966 static void read_passwords(void)
2968 BlockDriverState *bs;
2969 int i, j;
2970 char password[256];
2972 for(i = 0; i < 6; i++) {
2973 bs = get_bdrv(i);
2974 if (bs && bdrv_is_encrypted(bs)) {
2975 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2976 for(j = 0; j < 3; j++) {
2977 monitor_readline("Password: ",
2978 1, password, sizeof(password));
2979 if (bdrv_set_key(bs, password) == 0)
2980 break;
2981 term_printf("invalid password\n");
2987 #define NET_IF_TUN 0
2988 #define NET_IF_USER 1
2989 #define NET_IF_DUMMY 2
2991 int main(int argc, char **argv)
2993 #ifdef CONFIG_GDBSTUB
2994 int use_gdbstub, gdbstub_port;
2995 #endif
2996 int i, has_cdrom;
2997 int snapshot, linux_boot;
2998 CPUState *env;
2999 const char *initrd_filename;
3000 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3001 const char *kernel_filename, *kernel_cmdline;
3002 DisplayState *ds = &display_state;
3003 int cyls, heads, secs, translation;
3004 int start_emulation = 1;
3005 uint8_t macaddr[6];
3006 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
3007 int optind;
3008 const char *r, *optarg;
3009 CharDriverState *monitor_hd;
3010 char monitor_device[128];
3011 char serial_devices[MAX_SERIAL_PORTS][128];
3012 int serial_device_index;
3013 char parallel_devices[MAX_PARALLEL_PORTS][128];
3014 int parallel_device_index;
3015 const char *loadvm = NULL;
3017 #if !defined(CONFIG_SOFTMMU)
3018 /* we never want that malloc() uses mmap() */
3019 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3020 #endif
3021 initrd_filename = NULL;
3022 for(i = 0; i < MAX_FD; i++)
3023 fd_filename[i] = NULL;
3024 for(i = 0; i < MAX_DISKS; i++)
3025 hd_filename[i] = NULL;
3026 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3027 vga_ram_size = VGA_RAM_SIZE;
3028 bios_size = BIOS_SIZE;
3029 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3030 #ifdef CONFIG_GDBSTUB
3031 use_gdbstub = 0;
3032 gdbstub_port = DEFAULT_GDBSTUB_PORT;
3033 #endif
3034 snapshot = 0;
3035 nographic = 0;
3036 kernel_filename = NULL;
3037 kernel_cmdline = "";
3038 has_cdrom = 1;
3039 cyls = heads = secs = 0;
3040 translation = BIOS_ATA_TRANSLATION_AUTO;
3041 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
3043 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
3044 for(i = 1; i < MAX_SERIAL_PORTS; i++)
3045 serial_devices[i][0] = '\0';
3046 serial_device_index = 0;
3048 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
3049 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
3050 parallel_devices[i][0] = '\0';
3051 parallel_device_index = 0;
3053 nb_tun_fds = 0;
3054 net_if_type = -1;
3055 nb_nics = 1;
3056 /* default mac address of the first network interface */
3057 macaddr[0] = 0x52;
3058 macaddr[1] = 0x54;
3059 macaddr[2] = 0x00;
3060 macaddr[3] = 0x12;
3061 macaddr[4] = 0x34;
3062 macaddr[5] = 0x56;
3064 optind = 1;
3065 for(;;) {
3066 if (optind >= argc)
3067 break;
3068 r = argv[optind];
3069 if (r[0] != '-') {
3070 hd_filename[0] = argv[optind++];
3071 } else {
3072 const QEMUOption *popt;
3074 optind++;
3075 popt = qemu_options;
3076 for(;;) {
3077 if (!popt->name) {
3078 fprintf(stderr, "%s: invalid option -- '%s'\n",
3079 argv[0], r);
3080 exit(1);
3082 if (!strcmp(popt->name, r + 1))
3083 break;
3084 popt++;
3086 if (popt->flags & HAS_ARG) {
3087 if (optind >= argc) {
3088 fprintf(stderr, "%s: option '%s' requires an argument\n",
3089 argv[0], r);
3090 exit(1);
3092 optarg = argv[optind++];
3093 } else {
3094 optarg = NULL;
3097 switch(popt->index) {
3098 case QEMU_OPTION_initrd:
3099 initrd_filename = optarg;
3100 break;
3101 case QEMU_OPTION_hda:
3102 hd_filename[0] = optarg;
3103 break;
3104 case QEMU_OPTION_hdb:
3105 hd_filename[1] = optarg;
3106 break;
3107 case QEMU_OPTION_snapshot:
3108 snapshot = 1;
3109 break;
3110 case QEMU_OPTION_hdachs:
3112 const char *p;
3113 p = optarg;
3114 cyls = strtol(p, (char **)&p, 0);
3115 if (cyls < 1 || cyls > 16383)
3116 goto chs_fail;
3117 if (*p != ',')
3118 goto chs_fail;
3119 p++;
3120 heads = strtol(p, (char **)&p, 0);
3121 if (heads < 1 || heads > 16)
3122 goto chs_fail;
3123 if (*p != ',')
3124 goto chs_fail;
3125 p++;
3126 secs = strtol(p, (char **)&p, 0);
3127 if (secs < 1 || secs > 63)
3128 goto chs_fail;
3129 if (*p == ',') {
3130 p++;
3131 if (!strcmp(p, "none"))
3132 translation = BIOS_ATA_TRANSLATION_NONE;
3133 else if (!strcmp(p, "lba"))
3134 translation = BIOS_ATA_TRANSLATION_LBA;
3135 else if (!strcmp(p, "auto"))
3136 translation = BIOS_ATA_TRANSLATION_AUTO;
3137 else
3138 goto chs_fail;
3139 } else if (*p != '\0') {
3140 chs_fail:
3141 fprintf(stderr, "qemu: invalid physical CHS format\n");
3142 exit(1);
3145 break;
3146 case QEMU_OPTION_nographic:
3147 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3148 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3149 nographic = 1;
3150 break;
3151 case QEMU_OPTION_kernel:
3152 kernel_filename = optarg;
3153 break;
3154 case QEMU_OPTION_append:
3155 kernel_cmdline = optarg;
3156 break;
3157 case QEMU_OPTION_tun_fd:
3159 const char *p;
3160 int fd;
3161 net_if_type = NET_IF_TUN;
3162 if (nb_tun_fds < MAX_NICS) {
3163 fd = strtol(optarg, (char **)&p, 0);
3164 if (*p != '\0') {
3165 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3166 exit(1);
3168 tun_fds[nb_tun_fds++] = fd;
3171 break;
3172 case QEMU_OPTION_hdc:
3173 hd_filename[2] = optarg;
3174 has_cdrom = 0;
3175 break;
3176 case QEMU_OPTION_hdd:
3177 hd_filename[3] = optarg;
3178 break;
3179 case QEMU_OPTION_cdrom:
3180 hd_filename[2] = optarg;
3181 has_cdrom = 1;
3182 break;
3183 case QEMU_OPTION_boot:
3184 boot_device = optarg[0];
3185 if (boot_device != 'a' &&
3186 #ifdef TARGET_SPARC
3187 // Network boot
3188 boot_device != 'n' &&
3189 #endif
3190 boot_device != 'c' && boot_device != 'd') {
3191 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3192 exit(1);
3194 break;
3195 case QEMU_OPTION_fda:
3196 fd_filename[0] = optarg;
3197 break;
3198 case QEMU_OPTION_fdb:
3199 fd_filename[1] = optarg;
3200 break;
3201 case QEMU_OPTION_no_code_copy:
3202 code_copy_enabled = 0;
3203 break;
3204 case QEMU_OPTION_nics:
3205 nb_nics = atoi(optarg);
3206 if (nb_nics < 0 || nb_nics > MAX_NICS) {
3207 fprintf(stderr, "qemu: invalid number of network interfaces\n");
3208 exit(1);
3210 break;
3211 case QEMU_OPTION_macaddr:
3213 const char *p;
3214 int i;
3215 p = optarg;
3216 for(i = 0; i < 6; i++) {
3217 macaddr[i] = strtol(p, (char **)&p, 16);
3218 if (i == 5) {
3219 if (*p != '\0')
3220 goto macaddr_error;
3221 } else {
3222 if (*p != ':') {
3223 macaddr_error:
3224 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3225 exit(1);
3227 p++;
3231 break;
3232 #ifdef CONFIG_SLIRP
3233 case QEMU_OPTION_tftp:
3234 tftp_prefix = optarg;
3235 break;
3236 #ifndef _WIN32
3237 case QEMU_OPTION_smb:
3238 net_slirp_smb(optarg);
3239 break;
3240 #endif
3241 case QEMU_OPTION_user_net:
3242 net_if_type = NET_IF_USER;
3243 break;
3244 case QEMU_OPTION_redir:
3245 net_slirp_redir(optarg);
3246 break;
3247 #endif
3248 case QEMU_OPTION_dummy_net:
3249 net_if_type = NET_IF_DUMMY;
3250 break;
3251 case QEMU_OPTION_enable_audio:
3252 audio_enabled = 1;
3253 break;
3254 case QEMU_OPTION_h:
3255 help();
3256 break;
3257 case QEMU_OPTION_m:
3258 ram_size = atoi(optarg) * 1024 * 1024;
3259 if (ram_size <= 0)
3260 help();
3261 if (ram_size > PHYS_RAM_MAX_SIZE) {
3262 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3263 PHYS_RAM_MAX_SIZE / (1024 * 1024));
3264 exit(1);
3266 break;
3267 case QEMU_OPTION_d:
3269 int mask;
3270 CPULogItem *item;
3272 mask = cpu_str_to_log_mask(optarg);
3273 if (!mask) {
3274 printf("Log items (comma separated):\n");
3275 for(item = cpu_log_items; item->mask != 0; item++) {
3276 printf("%-10s %s\n", item->name, item->help);
3278 exit(1);
3280 cpu_set_log(mask);
3282 break;
3283 case QEMU_OPTION_n:
3284 pstrcpy(network_script, sizeof(network_script), optarg);
3285 break;
3286 #ifdef CONFIG_GDBSTUB
3287 case QEMU_OPTION_s:
3288 use_gdbstub = 1;
3289 break;
3290 case QEMU_OPTION_p:
3291 gdbstub_port = atoi(optarg);
3292 break;
3293 #endif
3294 case QEMU_OPTION_L:
3295 bios_dir = optarg;
3296 break;
3297 case QEMU_OPTION_S:
3298 start_emulation = 0;
3299 break;
3300 case QEMU_OPTION_pci:
3301 pci_enabled = 1;
3302 break;
3303 case QEMU_OPTION_isa:
3304 pci_enabled = 0;
3305 break;
3306 case QEMU_OPTION_prep:
3307 prep_enabled = 1;
3308 break;
3309 case QEMU_OPTION_k:
3310 keyboard_layout = optarg;
3311 break;
3312 case QEMU_OPTION_localtime:
3313 rtc_utc = 0;
3314 break;
3315 case QEMU_OPTION_cirrusvga:
3316 cirrus_vga_enabled = 1;
3317 break;
3318 case QEMU_OPTION_std_vga:
3319 cirrus_vga_enabled = 0;
3320 break;
3321 case QEMU_OPTION_g:
3323 const char *p;
3324 int w, h, depth;
3325 p = optarg;
3326 w = strtol(p, (char **)&p, 10);
3327 if (w <= 0) {
3328 graphic_error:
3329 fprintf(stderr, "qemu: invalid resolution or depth\n");
3330 exit(1);
3332 if (*p != 'x')
3333 goto graphic_error;
3334 p++;
3335 h = strtol(p, (char **)&p, 10);
3336 if (h <= 0)
3337 goto graphic_error;
3338 if (*p == 'x') {
3339 p++;
3340 depth = strtol(p, (char **)&p, 10);
3341 if (depth != 8 && depth != 15 && depth != 16 &&
3342 depth != 24 && depth != 32)
3343 goto graphic_error;
3344 } else if (*p == '\0') {
3345 depth = graphic_depth;
3346 } else {
3347 goto graphic_error;
3350 graphic_width = w;
3351 graphic_height = h;
3352 graphic_depth = depth;
3354 break;
3355 case QEMU_OPTION_monitor:
3356 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3357 break;
3358 case QEMU_OPTION_serial:
3359 if (serial_device_index >= MAX_SERIAL_PORTS) {
3360 fprintf(stderr, "qemu: too many serial ports\n");
3361 exit(1);
3363 pstrcpy(serial_devices[serial_device_index],
3364 sizeof(serial_devices[0]), optarg);
3365 serial_device_index++;
3366 break;
3367 case QEMU_OPTION_parallel:
3368 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3369 fprintf(stderr, "qemu: too many parallel ports\n");
3370 exit(1);
3372 pstrcpy(parallel_devices[parallel_device_index],
3373 sizeof(parallel_devices[0]), optarg);
3374 parallel_device_index++;
3375 break;
3376 case QEMU_OPTION_loadvm:
3377 loadvm = optarg;
3378 break;
3379 case QEMU_OPTION_full_screen:
3380 full_screen = 1;
3381 break;
3382 case QEMU_OPTION_pidfile:
3383 create_pidfile(optarg);
3384 break;
3385 #ifdef USE_KQEMU
3386 case QEMU_OPTION_no_kqemu:
3387 kqemu_allowed = 0;
3388 break;
3389 #endif
3394 linux_boot = (kernel_filename != NULL);
3396 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3397 fd_filename[0] == '\0')
3398 help();
3400 /* boot to cd by default if no hard disk */
3401 if (hd_filename[0] == '\0' && boot_device == 'c') {
3402 if (fd_filename[0] != '\0')
3403 boot_device = 'a';
3404 else
3405 boot_device = 'd';
3408 #if !defined(CONFIG_SOFTMMU)
3409 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3411 static uint8_t stdout_buf[4096];
3412 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3414 #else
3415 setvbuf(stdout, NULL, _IOLBF, 0);
3416 #endif
3418 /* init host network redirectors */
3419 if (net_if_type == -1) {
3420 net_if_type = NET_IF_TUN;
3421 #if defined(CONFIG_SLIRP)
3422 if (access(network_script, R_OK) < 0) {
3423 net_if_type = NET_IF_USER;
3425 #endif
3428 for(i = 0; i < nb_nics; i++) {
3429 NetDriverState *nd = &nd_table[i];
3430 nd->index = i;
3431 /* init virtual mac address */
3432 nd->macaddr[0] = macaddr[0];
3433 nd->macaddr[1] = macaddr[1];
3434 nd->macaddr[2] = macaddr[2];
3435 nd->macaddr[3] = macaddr[3];
3436 nd->macaddr[4] = macaddr[4];
3437 nd->macaddr[5] = macaddr[5] + i;
3438 switch(net_if_type) {
3439 #if defined(CONFIG_SLIRP)
3440 case NET_IF_USER:
3441 net_slirp_init(nd);
3442 break;
3443 #endif
3444 #if !defined(_WIN32)
3445 case NET_IF_TUN:
3446 if (i < nb_tun_fds) {
3447 net_fd_init(nd, tun_fds[i]);
3448 } else {
3449 if (net_tun_init(nd) < 0)
3450 net_dummy_init(nd);
3452 break;
3453 #endif
3454 case NET_IF_DUMMY:
3455 default:
3456 net_dummy_init(nd);
3457 break;
3461 /* init the memory */
3462 phys_ram_size = ram_size + vga_ram_size + bios_size;
3464 #ifdef CONFIG_SOFTMMU
3465 phys_ram_base = qemu_vmalloc(phys_ram_size);
3466 if (!phys_ram_base) {
3467 fprintf(stderr, "Could not allocate physical memory\n");
3468 exit(1);
3470 #else
3471 /* as we must map the same page at several addresses, we must use
3472 a fd */
3474 const char *tmpdir;
3476 tmpdir = getenv("QEMU_TMPDIR");
3477 if (!tmpdir)
3478 tmpdir = "/tmp";
3479 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3480 if (mkstemp(phys_ram_file) < 0) {
3481 fprintf(stderr, "Could not create temporary memory file '%s'\n",
3482 phys_ram_file);
3483 exit(1);
3485 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3486 if (phys_ram_fd < 0) {
3487 fprintf(stderr, "Could not open temporary memory file '%s'\n",
3488 phys_ram_file);
3489 exit(1);
3491 ftruncate(phys_ram_fd, phys_ram_size);
3492 unlink(phys_ram_file);
3493 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
3494 phys_ram_size,
3495 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
3496 phys_ram_fd, 0);
3497 if (phys_ram_base == MAP_FAILED) {
3498 fprintf(stderr, "Could not map physical memory\n");
3499 exit(1);
3502 #endif
3504 /* we always create the cdrom drive, even if no disk is there */
3505 bdrv_init();
3506 if (has_cdrom) {
3507 bs_table[2] = bdrv_new("cdrom");
3508 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3511 /* open the virtual block devices */
3512 for(i = 0; i < MAX_DISKS; i++) {
3513 if (hd_filename[i]) {
3514 if (!bs_table[i]) {
3515 char buf[64];
3516 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3517 bs_table[i] = bdrv_new(buf);
3519 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3520 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3521 hd_filename[i]);
3522 exit(1);
3524 if (i == 0 && cyls != 0) {
3525 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3526 bdrv_set_translation_hint(bs_table[i], translation);
3531 /* we always create at least one floppy disk */
3532 fd_table[0] = bdrv_new("fda");
3533 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3535 for(i = 0; i < MAX_FD; i++) {
3536 if (fd_filename[i]) {
3537 if (!fd_table[i]) {
3538 char buf[64];
3539 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3540 fd_table[i] = bdrv_new(buf);
3541 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3543 if (fd_filename[i] != '\0') {
3544 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3545 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3546 fd_filename[i]);
3547 exit(1);
3553 /* init CPU state */
3554 env = cpu_init();
3555 global_env = env;
3556 cpu_single_env = env;
3558 register_savevm("timer", 0, 1, timer_save, timer_load, env);
3559 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
3560 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3561 qemu_register_reset(main_cpu_reset, global_env);
3563 init_ioports();
3564 cpu_calibrate_ticks();
3566 /* terminal init */
3567 if (nographic) {
3568 dumb_display_init(ds);
3569 } else {
3570 #if defined(CONFIG_SDL)
3571 sdl_display_init(ds, full_screen);
3572 #elif defined(CONFIG_COCOA)
3573 cocoa_display_init(ds, full_screen);
3574 #else
3575 dumb_display_init(ds);
3576 #endif
3579 vga_console = graphic_console_init(ds);
3581 monitor_hd = qemu_chr_open(monitor_device);
3582 if (!monitor_hd) {
3583 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3584 exit(1);
3586 monitor_init(monitor_hd, !nographic);
3588 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3589 if (serial_devices[i][0] != '\0') {
3590 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3591 if (!serial_hds[i]) {
3592 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3593 serial_devices[i]);
3594 exit(1);
3596 if (!strcmp(serial_devices[i], "vc"))
3597 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3601 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
3602 if (parallel_devices[i][0] != '\0') {
3603 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
3604 if (!parallel_hds[i]) {
3605 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
3606 parallel_devices[i]);
3607 exit(1);
3609 if (!strcmp(parallel_devices[i], "vc"))
3610 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
3614 /* setup cpu signal handlers for MMU / self modifying code handling */
3615 #if !defined(CONFIG_SOFTMMU)
3617 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3619 stack_t stk;
3620 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3621 stk.ss_sp = signal_stack;
3622 stk.ss_size = SIGNAL_STACK_SIZE;
3623 stk.ss_flags = 0;
3625 if (sigaltstack(&stk, NULL) < 0) {
3626 perror("sigaltstack");
3627 exit(1);
3630 #endif
3632 struct sigaction act;
3634 sigfillset(&act.sa_mask);
3635 act.sa_flags = SA_SIGINFO;
3636 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3637 act.sa_flags |= SA_ONSTACK;
3638 #endif
3639 act.sa_sigaction = host_segv_handler;
3640 sigaction(SIGSEGV, &act, NULL);
3641 sigaction(SIGBUS, &act, NULL);
3642 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3643 sigaction(SIGFPE, &act, NULL);
3644 #endif
3646 #endif
3648 #ifndef _WIN32
3650 struct sigaction act;
3651 sigfillset(&act.sa_mask);
3652 act.sa_flags = 0;
3653 act.sa_handler = SIG_IGN;
3654 sigaction(SIGPIPE, &act, NULL);
3656 #endif
3657 init_timers();
3659 #if defined(TARGET_I386)
3660 pc_init(ram_size, vga_ram_size, boot_device,
3661 ds, fd_filename, snapshot,
3662 kernel_filename, kernel_cmdline, initrd_filename);
3663 #elif defined(TARGET_PPC)
3664 ppc_init(ram_size, vga_ram_size, boot_device,
3665 ds, fd_filename, snapshot,
3666 kernel_filename, kernel_cmdline, initrd_filename);
3667 #elif defined(TARGET_SPARC)
3668 sun4m_init(ram_size, vga_ram_size, boot_device,
3669 ds, fd_filename, snapshot,
3670 kernel_filename, kernel_cmdline, initrd_filename);
3671 #endif
3673 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3674 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3676 #ifdef CONFIG_GDBSTUB
3677 if (use_gdbstub) {
3678 if (gdbserver_start(gdbstub_port) < 0) {
3679 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3680 gdbstub_port);
3681 exit(1);
3682 } else {
3683 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3685 } else
3686 #endif
3687 if (loadvm)
3688 qemu_loadvm(loadvm);
3691 /* XXX: simplify init */
3692 read_passwords();
3693 if (start_emulation) {
3694 vm_start();
3697 main_loop();
3698 quit_timers();
3699 return 0;