custom option parsing to have same behavior on all OSes
[qemu.git] / vl.c
blob2ad182df6233d3e7bb16b661f4989e11cdd0f9a1
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 #ifdef _BSD
42 #include <sys/stat.h>
43 #include <libutil.h>
44 #else
45 #include <linux/if.h>
46 #include <linux/if_tun.h>
47 #include <pty.h>
48 #include <malloc.h>
49 #include <linux/rtc.h>
50 #endif
51 #endif
53 #if defined(CONFIG_SLIRP)
54 #include "libslirp.h"
55 #endif
57 #ifdef _WIN32
58 #include <malloc.h>
59 #include <sys/timeb.h>
60 #include <windows.h>
61 #define getopt_long_only getopt_long
62 #define memalign(align, size) malloc(size)
63 #endif
65 #ifdef CONFIG_SDL
66 #if defined(__linux__)
67 /* SDL use the pthreads and they modify sigaction. We don't
68 want that. */
69 #if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
70 extern void __libc_sigaction();
71 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
72 #else
73 extern void __sigaction();
74 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
75 #endif
76 #endif /* __linux__ */
77 #endif /* CONFIG_SDL */
79 #include "disas.h"
81 #include "exec-all.h"
83 //#define DO_TB_FLUSH
85 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
87 //#define DEBUG_UNUSED_IOPORT
88 //#define DEBUG_IOPORT
90 #if !defined(CONFIG_SOFTMMU)
91 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
92 #else
93 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
94 #endif
96 /* in ms */
97 #define GUI_REFRESH_INTERVAL 30
99 /* XXX: use a two level table to limit memory usage */
100 #define MAX_IOPORTS 65536
102 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
103 char phys_ram_file[1024];
104 CPUState *global_env;
105 CPUState *cpu_single_env;
106 void *ioport_opaque[MAX_IOPORTS];
107 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
108 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
109 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
110 int vga_ram_size;
111 static DisplayState display_state;
112 int nographic;
113 int64_t ticks_per_sec;
114 int boot_device = 'c';
115 static int ram_size;
116 static char network_script[1024];
117 int pit_min_timer_count = 0;
118 int nb_nics;
119 NetDriverState nd_table[MAX_NICS];
120 SerialState *serial_console;
121 QEMUTimer *gui_timer;
122 int vm_running;
123 int audio_enabled = 0;
125 /***********************************************************/
126 /* x86 ISA bus support */
128 target_phys_addr_t isa_mem_base = 0;
130 uint32_t default_ioport_readb(void *opaque, uint32_t address)
132 #ifdef DEBUG_UNUSED_IOPORT
133 fprintf(stderr, "inb: port=0x%04x\n", address);
134 #endif
135 return 0xff;
138 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
140 #ifdef DEBUG_UNUSED_IOPORT
141 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
142 #endif
145 /* default is to make two byte accesses */
146 uint32_t default_ioport_readw(void *opaque, uint32_t address)
148 uint32_t data;
149 data = ioport_read_table[0][address](ioport_opaque[address], address);
150 address = (address + 1) & (MAX_IOPORTS - 1);
151 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
152 return data;
155 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
157 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
158 address = (address + 1) & (MAX_IOPORTS - 1);
159 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
162 uint32_t default_ioport_readl(void *opaque, uint32_t address)
164 #ifdef DEBUG_UNUSED_IOPORT
165 fprintf(stderr, "inl: port=0x%04x\n", address);
166 #endif
167 return 0xffffffff;
170 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
174 #endif
177 void init_ioports(void)
179 int i;
181 for(i = 0; i < MAX_IOPORTS; i++) {
182 ioport_read_table[0][i] = default_ioport_readb;
183 ioport_write_table[0][i] = default_ioport_writeb;
184 ioport_read_table[1][i] = default_ioport_readw;
185 ioport_write_table[1][i] = default_ioport_writew;
186 ioport_read_table[2][i] = default_ioport_readl;
187 ioport_write_table[2][i] = default_ioport_writel;
191 /* size is the word size in byte */
192 int register_ioport_read(int start, int length, int size,
193 IOPortReadFunc *func, void *opaque)
195 int i, bsize;
197 if (size == 1) {
198 bsize = 0;
199 } else if (size == 2) {
200 bsize = 1;
201 } else if (size == 4) {
202 bsize = 2;
203 } else {
204 hw_error("register_ioport_read: invalid size");
205 return -1;
207 for(i = start; i < start + length; i += size) {
208 ioport_read_table[bsize][i] = func;
209 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
210 hw_error("register_ioport_read: invalid opaque");
211 ioport_opaque[i] = opaque;
213 return 0;
216 /* size is the word size in byte */
217 int register_ioport_write(int start, int length, int size,
218 IOPortWriteFunc *func, void *opaque)
220 int i, bsize;
222 if (size == 1) {
223 bsize = 0;
224 } else if (size == 2) {
225 bsize = 1;
226 } else if (size == 4) {
227 bsize = 2;
228 } else {
229 hw_error("register_ioport_write: invalid size");
230 return -1;
232 for(i = start; i < start + length; i += size) {
233 ioport_write_table[bsize][i] = func;
234 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
235 hw_error("register_ioport_read: invalid opaque");
236 ioport_opaque[i] = opaque;
238 return 0;
241 void pstrcpy(char *buf, int buf_size, const char *str)
243 int c;
244 char *q = buf;
246 if (buf_size <= 0)
247 return;
249 for(;;) {
250 c = *str++;
251 if (c == 0 || q >= buf + buf_size - 1)
252 break;
253 *q++ = c;
255 *q = '\0';
258 /* strcat and truncate. */
259 char *pstrcat(char *buf, int buf_size, const char *s)
261 int len;
262 len = strlen(buf);
263 if (len < buf_size)
264 pstrcpy(buf + len, buf_size - len, s);
265 return buf;
268 /* return the size or -1 if error */
269 int load_image(const char *filename, uint8_t *addr)
271 int fd, size;
272 fd = open(filename, O_RDONLY | O_BINARY);
273 if (fd < 0)
274 return -1;
275 size = lseek(fd, 0, SEEK_END);
276 lseek(fd, 0, SEEK_SET);
277 if (read(fd, addr, size) != size) {
278 close(fd);
279 return -1;
281 close(fd);
282 return size;
285 void cpu_outb(CPUState *env, int addr, int val)
287 #ifdef DEBUG_IOPORT
288 if (loglevel & CPU_LOG_IOPORT)
289 fprintf(logfile, "outb: %04x %02x\n", addr, val);
290 #endif
291 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
294 void cpu_outw(CPUState *env, int addr, int val)
296 #ifdef DEBUG_IOPORT
297 if (loglevel & CPU_LOG_IOPORT)
298 fprintf(logfile, "outw: %04x %04x\n", addr, val);
299 #endif
300 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
303 void cpu_outl(CPUState *env, int addr, int val)
305 #ifdef DEBUG_IOPORT
306 if (loglevel & CPU_LOG_IOPORT)
307 fprintf(logfile, "outl: %04x %08x\n", addr, val);
308 #endif
309 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
312 int cpu_inb(CPUState *env, int addr)
314 int val;
315 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
316 #ifdef DEBUG_IOPORT
317 if (loglevel & CPU_LOG_IOPORT)
318 fprintf(logfile, "inb : %04x %02x\n", addr, val);
319 #endif
320 return val;
323 int cpu_inw(CPUState *env, int addr)
325 int val;
326 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
327 #ifdef DEBUG_IOPORT
328 if (loglevel & CPU_LOG_IOPORT)
329 fprintf(logfile, "inw : %04x %04x\n", addr, val);
330 #endif
331 return val;
334 int cpu_inl(CPUState *env, int addr)
336 int val;
337 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
338 #ifdef DEBUG_IOPORT
339 if (loglevel & CPU_LOG_IOPORT)
340 fprintf(logfile, "inl : %04x %08x\n", addr, val);
341 #endif
342 return val;
345 /***********************************************************/
346 void hw_error(const char *fmt, ...)
348 va_list ap;
350 va_start(ap, fmt);
351 fprintf(stderr, "qemu: hardware error: ");
352 vfprintf(stderr, fmt, ap);
353 fprintf(stderr, "\n");
354 #ifdef TARGET_I386
355 cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
356 #else
357 cpu_dump_state(global_env, stderr, 0);
358 #endif
359 va_end(ap);
360 abort();
363 /***********************************************************/
364 /* timers */
366 #if defined(__powerpc__)
368 static inline uint32_t get_tbl(void)
370 uint32_t tbl;
371 asm volatile("mftb %0" : "=r" (tbl));
372 return tbl;
375 static inline uint32_t get_tbu(void)
377 uint32_t tbl;
378 asm volatile("mftbu %0" : "=r" (tbl));
379 return tbl;
382 int64_t cpu_get_real_ticks(void)
384 uint32_t l, h, h1;
385 /* NOTE: we test if wrapping has occurred */
386 do {
387 h = get_tbu();
388 l = get_tbl();
389 h1 = get_tbu();
390 } while (h != h1);
391 return ((int64_t)h << 32) | l;
394 #elif defined(__i386__)
396 int64_t cpu_get_real_ticks(void)
398 int64_t val;
399 asm volatile ("rdtsc" : "=A" (val));
400 return val;
403 #elif defined(__x86_64__)
405 int64_t cpu_get_real_ticks(void)
407 uint32_t low,high;
408 int64_t val;
409 asm volatile("rdtsc" : "=a" (low), "=d" (high));
410 val = high;
411 val <<= 32;
412 val |= low;
413 return val;
416 #else
417 #error unsupported CPU
418 #endif
420 static int64_t cpu_ticks_offset;
421 static int cpu_ticks_enabled;
423 static inline int64_t cpu_get_ticks(void)
425 if (!cpu_ticks_enabled) {
426 return cpu_ticks_offset;
427 } else {
428 return cpu_get_real_ticks() + cpu_ticks_offset;
432 /* enable cpu_get_ticks() */
433 void cpu_enable_ticks(void)
435 if (!cpu_ticks_enabled) {
436 cpu_ticks_offset -= cpu_get_real_ticks();
437 cpu_ticks_enabled = 1;
441 /* disable cpu_get_ticks() : the clock is stopped. You must not call
442 cpu_get_ticks() after that. */
443 void cpu_disable_ticks(void)
445 if (cpu_ticks_enabled) {
446 cpu_ticks_offset = cpu_get_ticks();
447 cpu_ticks_enabled = 0;
451 static int64_t get_clock(void)
453 #ifdef _WIN32
454 struct _timeb tb;
455 _ftime(&tb);
456 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
457 #else
458 struct timeval tv;
459 gettimeofday(&tv, NULL);
460 return tv.tv_sec * 1000000LL + tv.tv_usec;
461 #endif
464 void cpu_calibrate_ticks(void)
466 int64_t usec, ticks;
468 usec = get_clock();
469 ticks = cpu_get_real_ticks();
470 #ifdef _WIN32
471 Sleep(50);
472 #else
473 usleep(50 * 1000);
474 #endif
475 usec = get_clock() - usec;
476 ticks = cpu_get_real_ticks() - ticks;
477 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
480 /* compute with 96 bit intermediate result: (a*b)/c */
481 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
483 union {
484 uint64_t ll;
485 struct {
486 #ifdef WORDS_BIGENDIAN
487 uint32_t high, low;
488 #else
489 uint32_t low, high;
490 #endif
491 } l;
492 } u, res;
493 uint64_t rl, rh;
495 u.ll = a;
496 rl = (uint64_t)u.l.low * (uint64_t)b;
497 rh = (uint64_t)u.l.high * (uint64_t)b;
498 rh += (rl >> 32);
499 res.l.high = rh / c;
500 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
501 return res.ll;
504 #define QEMU_TIMER_REALTIME 0
505 #define QEMU_TIMER_VIRTUAL 1
507 struct QEMUClock {
508 int type;
509 /* XXX: add frequency */
512 struct QEMUTimer {
513 QEMUClock *clock;
514 int64_t expire_time;
515 QEMUTimerCB *cb;
516 void *opaque;
517 struct QEMUTimer *next;
520 QEMUClock *rt_clock;
521 QEMUClock *vm_clock;
523 static QEMUTimer *active_timers[2];
524 #ifdef _WIN32
525 static MMRESULT timerID;
526 #else
527 /* frequency of the times() clock tick */
528 static int timer_freq;
529 #endif
531 QEMUClock *qemu_new_clock(int type)
533 QEMUClock *clock;
534 clock = qemu_mallocz(sizeof(QEMUClock));
535 if (!clock)
536 return NULL;
537 clock->type = type;
538 return clock;
541 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
543 QEMUTimer *ts;
545 ts = qemu_mallocz(sizeof(QEMUTimer));
546 ts->clock = clock;
547 ts->cb = cb;
548 ts->opaque = opaque;
549 return ts;
552 void qemu_free_timer(QEMUTimer *ts)
554 qemu_free(ts);
557 /* stop a timer, but do not dealloc it */
558 void qemu_del_timer(QEMUTimer *ts)
560 QEMUTimer **pt, *t;
562 /* NOTE: this code must be signal safe because
563 qemu_timer_expired() can be called from a signal. */
564 pt = &active_timers[ts->clock->type];
565 for(;;) {
566 t = *pt;
567 if (!t)
568 break;
569 if (t == ts) {
570 *pt = t->next;
571 break;
573 pt = &t->next;
577 /* modify the current timer so that it will be fired when current_time
578 >= expire_time. The corresponding callback will be called. */
579 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
581 QEMUTimer **pt, *t;
583 qemu_del_timer(ts);
585 /* add the timer in the sorted list */
586 /* NOTE: this code must be signal safe because
587 qemu_timer_expired() can be called from a signal. */
588 pt = &active_timers[ts->clock->type];
589 for(;;) {
590 t = *pt;
591 if (!t)
592 break;
593 if (t->expire_time > expire_time)
594 break;
595 pt = &t->next;
597 ts->expire_time = expire_time;
598 ts->next = *pt;
599 *pt = ts;
602 int qemu_timer_pending(QEMUTimer *ts)
604 QEMUTimer *t;
605 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
606 if (t == ts)
607 return 1;
609 return 0;
612 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
614 if (!timer_head)
615 return 0;
616 return (timer_head->expire_time <= current_time);
619 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
621 QEMUTimer *ts;
623 for(;;) {
624 ts = *ptimer_head;
625 if (ts->expire_time > current_time)
626 break;
627 /* remove timer from the list before calling the callback */
628 *ptimer_head = ts->next;
629 ts->next = NULL;
631 /* run the callback (the timer list can be modified) */
632 ts->cb(ts->opaque);
636 int64_t qemu_get_clock(QEMUClock *clock)
638 switch(clock->type) {
639 case QEMU_TIMER_REALTIME:
640 #ifdef _WIN32
641 return GetTickCount();
642 #else
644 struct tms tp;
646 /* Note that using gettimeofday() is not a good solution
647 for timers because its value change when the date is
648 modified. */
649 if (timer_freq == 100) {
650 return times(&tp) * 10;
651 } else {
652 return ((int64_t)times(&tp) * 1000) / timer_freq;
655 #endif
656 default:
657 case QEMU_TIMER_VIRTUAL:
658 return cpu_get_ticks();
662 /* save a timer */
663 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
665 uint64_t expire_time;
667 if (qemu_timer_pending(ts)) {
668 expire_time = ts->expire_time;
669 } else {
670 expire_time = -1;
672 qemu_put_be64(f, expire_time);
675 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
677 uint64_t expire_time;
679 expire_time = qemu_get_be64(f);
680 if (expire_time != -1) {
681 qemu_mod_timer(ts, expire_time);
682 } else {
683 qemu_del_timer(ts);
687 static void timer_save(QEMUFile *f, void *opaque)
689 if (cpu_ticks_enabled) {
690 hw_error("cannot save state if virtual timers are running");
692 qemu_put_be64s(f, &cpu_ticks_offset);
693 qemu_put_be64s(f, &ticks_per_sec);
696 static int timer_load(QEMUFile *f, void *opaque, int version_id)
698 if (version_id != 1)
699 return -EINVAL;
700 if (cpu_ticks_enabled) {
701 return -EINVAL;
703 qemu_get_be64s(f, &cpu_ticks_offset);
704 qemu_get_be64s(f, &ticks_per_sec);
705 return 0;
708 #ifdef _WIN32
709 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
710 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
711 #else
712 static void host_alarm_handler(int host_signum)
713 #endif
715 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
716 qemu_get_clock(vm_clock)) ||
717 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
718 qemu_get_clock(rt_clock))) {
719 /* stop the cpu because a timer occured */
720 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
724 #ifndef _WIN32
726 #define RTC_FREQ 1024
728 static int rtc_fd;
730 static int start_rtc_timer(void)
732 rtc_fd = open("/dev/rtc", O_RDONLY);
733 if (rtc_fd < 0)
734 return -1;
735 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
736 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
737 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
738 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
739 goto fail;
741 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
742 fail:
743 close(rtc_fd);
744 return -1;
746 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
747 return 0;
750 #endif
752 static void init_timers(void)
754 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
755 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
757 #ifdef _WIN32
759 int count=0;
760 timerID = timeSetEvent(10, // interval (ms)
761 0, // resolution
762 host_alarm_handler, // function
763 (DWORD)&count, // user parameter
764 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
765 if( !timerID ) {
766 perror("failed timer alarm");
767 exit(1);
770 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
771 #else
773 struct sigaction act;
774 struct itimerval itv;
776 /* get times() syscall frequency */
777 timer_freq = sysconf(_SC_CLK_TCK);
779 /* timer signal */
780 sigfillset(&act.sa_mask);
781 act.sa_flags = 0;
782 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
783 act.sa_flags |= SA_ONSTACK;
784 #endif
785 act.sa_handler = host_alarm_handler;
786 sigaction(SIGALRM, &act, NULL);
788 itv.it_interval.tv_sec = 0;
789 itv.it_interval.tv_usec = 1000;
790 itv.it_value.tv_sec = 0;
791 itv.it_value.tv_usec = 10 * 1000;
792 setitimer(ITIMER_REAL, &itv, NULL);
793 /* we probe the tick duration of the kernel to inform the user if
794 the emulated kernel requested a too high timer frequency */
795 getitimer(ITIMER_REAL, &itv);
797 if (itv.it_interval.tv_usec > 1000) {
798 /* try to use /dev/rtc to have a faster timer */
799 if (start_rtc_timer() < 0)
800 goto use_itimer;
801 /* disable itimer */
802 itv.it_interval.tv_sec = 0;
803 itv.it_interval.tv_usec = 0;
804 itv.it_value.tv_sec = 0;
805 itv.it_value.tv_usec = 0;
806 setitimer(ITIMER_REAL, &itv, NULL);
808 /* use the RTC */
809 sigaction(SIGIO, &act, NULL);
810 fcntl(rtc_fd, F_SETFL, O_ASYNC);
811 fcntl(rtc_fd, F_SETOWN, getpid());
812 } else {
813 use_itimer:
814 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
815 PIT_FREQ) / 1000000;
818 #endif
821 void quit_timers(void)
823 #ifdef _WIN32
824 timeKillEvent(timerID);
825 #endif
828 /***********************************************************/
829 /* serial device */
831 #ifdef _WIN32
833 int serial_open_device(void)
835 return -1;
838 #else
840 int serial_open_device(void)
842 char slave_name[1024];
843 int master_fd, slave_fd;
845 if (serial_console == NULL && nographic) {
846 /* use console for serial port */
847 return 0;
848 } else {
849 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
850 fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
851 return -1;
853 fprintf(stderr, "Serial port redirected to %s\n", slave_name);
854 return master_fd;
858 #endif
860 /***********************************************************/
861 /* Linux network device redirectors */
863 void hex_dump(FILE *f, const uint8_t *buf, int size)
865 int len, i, j, c;
867 for(i=0;i<size;i+=16) {
868 len = size - i;
869 if (len > 16)
870 len = 16;
871 fprintf(f, "%08x ", i);
872 for(j=0;j<16;j++) {
873 if (j < len)
874 fprintf(f, " %02x", buf[i+j]);
875 else
876 fprintf(f, " ");
878 fprintf(f, " ");
879 for(j=0;j<len;j++) {
880 c = buf[i+j];
881 if (c < ' ' || c > '~')
882 c = '.';
883 fprintf(f, "%c", c);
885 fprintf(f, "\n");
889 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
891 nd->send_packet(nd, buf, size);
894 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
895 IOReadHandler *fd_read, void *opaque)
897 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
900 /* dummy network adapter */
902 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
906 static void dummy_add_read_packet(NetDriverState *nd,
907 IOCanRWHandler *fd_can_read,
908 IOReadHandler *fd_read, void *opaque)
912 static int net_dummy_init(NetDriverState *nd)
914 nd->send_packet = dummy_send_packet;
915 nd->add_read_packet = dummy_add_read_packet;
916 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
917 return 0;
920 #if defined(CONFIG_SLIRP)
922 /* slirp network adapter */
924 static void *slirp_fd_opaque;
925 static IOCanRWHandler *slirp_fd_can_read;
926 static IOReadHandler *slirp_fd_read;
927 static int slirp_inited;
929 int slirp_can_output(void)
931 return slirp_fd_can_read(slirp_fd_opaque);
934 void slirp_output(const uint8_t *pkt, int pkt_len)
936 #if 0
937 printf("output:\n");
938 hex_dump(stdout, pkt, pkt_len);
939 #endif
940 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
943 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
945 #if 0
946 printf("input:\n");
947 hex_dump(stdout, buf, size);
948 #endif
949 slirp_input(buf, size);
952 static void slirp_add_read_packet(NetDriverState *nd,
953 IOCanRWHandler *fd_can_read,
954 IOReadHandler *fd_read, void *opaque)
956 slirp_fd_opaque = opaque;
957 slirp_fd_can_read = fd_can_read;
958 slirp_fd_read = fd_read;
961 static int net_slirp_init(NetDriverState *nd)
963 if (!slirp_inited) {
964 slirp_inited = 1;
965 slirp_init();
967 nd->send_packet = slirp_send_packet;
968 nd->add_read_packet = slirp_add_read_packet;
969 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
970 return 0;
973 #endif /* CONFIG_SLIRP */
975 #if !defined(_WIN32)
976 #ifdef _BSD
977 static int tun_open(char *ifname, int ifname_size)
979 int fd;
980 char *dev;
981 struct stat s;
983 fd = open("/dev/tap", O_RDWR);
984 if (fd < 0) {
985 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
986 return -1;
989 fstat(fd, &s);
990 dev = devname(s.st_rdev, S_IFCHR);
991 pstrcpy(ifname, ifname_size, dev);
993 fcntl(fd, F_SETFL, O_NONBLOCK);
994 return fd;
996 #else
997 static int tun_open(char *ifname, int ifname_size)
999 struct ifreq ifr;
1000 int fd, ret;
1002 fd = open("/dev/net/tun", O_RDWR);
1003 if (fd < 0) {
1004 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1005 return -1;
1007 memset(&ifr, 0, sizeof(ifr));
1008 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1009 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1010 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1011 if (ret != 0) {
1012 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1013 close(fd);
1014 return -1;
1016 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1017 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1018 fcntl(fd, F_SETFL, O_NONBLOCK);
1019 return fd;
1021 #endif
1023 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1025 write(nd->fd, buf, size);
1028 static void tun_add_read_packet(NetDriverState *nd,
1029 IOCanRWHandler *fd_can_read,
1030 IOReadHandler *fd_read, void *opaque)
1032 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1035 static int net_tun_init(NetDriverState *nd)
1037 int pid, status;
1038 char *args[3];
1039 char **parg;
1041 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1042 if (nd->fd < 0)
1043 return -1;
1045 /* try to launch network init script */
1046 pid = fork();
1047 if (pid >= 0) {
1048 if (pid == 0) {
1049 parg = args;
1050 *parg++ = network_script;
1051 *parg++ = nd->ifname;
1052 *parg++ = NULL;
1053 execv(network_script, args);
1054 exit(1);
1056 while (waitpid(pid, &status, 0) != pid);
1057 if (!WIFEXITED(status) ||
1058 WEXITSTATUS(status) != 0) {
1059 fprintf(stderr, "%s: could not launch network script\n",
1060 network_script);
1063 nd->send_packet = tun_send_packet;
1064 nd->add_read_packet = tun_add_read_packet;
1065 return 0;
1068 static int net_fd_init(NetDriverState *nd, int fd)
1070 nd->fd = fd;
1071 nd->send_packet = tun_send_packet;
1072 nd->add_read_packet = tun_add_read_packet;
1073 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1074 return 0;
1077 #endif /* !_WIN32 */
1079 /***********************************************************/
1080 /* dumb display */
1082 #ifdef _WIN32
1084 static void term_exit(void)
1088 static void term_init(void)
1092 #else
1094 /* init terminal so that we can grab keys */
1095 static struct termios oldtty;
1097 static void term_exit(void)
1099 tcsetattr (0, TCSANOW, &oldtty);
1102 static void term_init(void)
1104 struct termios tty;
1106 tcgetattr (0, &tty);
1107 oldtty = tty;
1109 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1110 |INLCR|IGNCR|ICRNL|IXON);
1111 tty.c_oflag |= OPOST;
1112 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1113 /* if graphical mode, we allow Ctrl-C handling */
1114 if (nographic)
1115 tty.c_lflag &= ~ISIG;
1116 tty.c_cflag &= ~(CSIZE|PARENB);
1117 tty.c_cflag |= CS8;
1118 tty.c_cc[VMIN] = 1;
1119 tty.c_cc[VTIME] = 0;
1121 tcsetattr (0, TCSANOW, &tty);
1123 atexit(term_exit);
1125 fcntl(0, F_SETFL, O_NONBLOCK);
1128 #endif
1130 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1134 static void dumb_resize(DisplayState *ds, int w, int h)
1138 static void dumb_refresh(DisplayState *ds)
1140 vga_update_display();
1143 void dumb_display_init(DisplayState *ds)
1145 ds->data = NULL;
1146 ds->linesize = 0;
1147 ds->depth = 0;
1148 ds->dpy_update = dumb_update;
1149 ds->dpy_resize = dumb_resize;
1150 ds->dpy_refresh = dumb_refresh;
1153 #if !defined(CONFIG_SOFTMMU)
1154 /***********************************************************/
1155 /* cpu signal handler */
1156 static void host_segv_handler(int host_signum, siginfo_t *info,
1157 void *puc)
1159 if (cpu_signal_handler(host_signum, info, puc))
1160 return;
1161 term_exit();
1162 abort();
1164 #endif
1166 /***********************************************************/
1167 /* I/O handling */
1169 #define MAX_IO_HANDLERS 64
1171 typedef struct IOHandlerRecord {
1172 int fd;
1173 IOCanRWHandler *fd_can_read;
1174 IOReadHandler *fd_read;
1175 void *opaque;
1176 /* temporary data */
1177 struct pollfd *ufd;
1178 int max_size;
1179 struct IOHandlerRecord *next;
1180 } IOHandlerRecord;
1182 static IOHandlerRecord *first_io_handler;
1184 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1185 IOReadHandler *fd_read, void *opaque)
1187 IOHandlerRecord *ioh;
1189 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1190 if (!ioh)
1191 return -1;
1192 ioh->fd = fd;
1193 ioh->fd_can_read = fd_can_read;
1194 ioh->fd_read = fd_read;
1195 ioh->opaque = opaque;
1196 ioh->next = first_io_handler;
1197 first_io_handler = ioh;
1198 return 0;
1201 void qemu_del_fd_read_handler(int fd)
1203 IOHandlerRecord **pioh, *ioh;
1205 pioh = &first_io_handler;
1206 for(;;) {
1207 ioh = *pioh;
1208 if (ioh == NULL)
1209 break;
1210 if (ioh->fd == fd) {
1211 *pioh = ioh->next;
1212 break;
1214 pioh = &ioh->next;
1218 /***********************************************************/
1219 /* savevm/loadvm support */
1221 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1223 fwrite(buf, 1, size, f);
1226 void qemu_put_byte(QEMUFile *f, int v)
1228 fputc(v, f);
1231 void qemu_put_be16(QEMUFile *f, unsigned int v)
1233 qemu_put_byte(f, v >> 8);
1234 qemu_put_byte(f, v);
1237 void qemu_put_be32(QEMUFile *f, unsigned int v)
1239 qemu_put_byte(f, v >> 24);
1240 qemu_put_byte(f, v >> 16);
1241 qemu_put_byte(f, v >> 8);
1242 qemu_put_byte(f, v);
1245 void qemu_put_be64(QEMUFile *f, uint64_t v)
1247 qemu_put_be32(f, v >> 32);
1248 qemu_put_be32(f, v);
1251 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1253 return fread(buf, 1, size, f);
1256 int qemu_get_byte(QEMUFile *f)
1258 int v;
1259 v = fgetc(f);
1260 if (v == EOF)
1261 return 0;
1262 else
1263 return v;
1266 unsigned int qemu_get_be16(QEMUFile *f)
1268 unsigned int v;
1269 v = qemu_get_byte(f) << 8;
1270 v |= qemu_get_byte(f);
1271 return v;
1274 unsigned int qemu_get_be32(QEMUFile *f)
1276 unsigned int v;
1277 v = qemu_get_byte(f) << 24;
1278 v |= qemu_get_byte(f) << 16;
1279 v |= qemu_get_byte(f) << 8;
1280 v |= qemu_get_byte(f);
1281 return v;
1284 uint64_t qemu_get_be64(QEMUFile *f)
1286 uint64_t v;
1287 v = (uint64_t)qemu_get_be32(f) << 32;
1288 v |= qemu_get_be32(f);
1289 return v;
1292 int64_t qemu_ftell(QEMUFile *f)
1294 return ftell(f);
1297 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1299 if (fseek(f, pos, whence) < 0)
1300 return -1;
1301 return ftell(f);
1304 typedef struct SaveStateEntry {
1305 char idstr[256];
1306 int instance_id;
1307 int version_id;
1308 SaveStateHandler *save_state;
1309 LoadStateHandler *load_state;
1310 void *opaque;
1311 struct SaveStateEntry *next;
1312 } SaveStateEntry;
1314 static SaveStateEntry *first_se;
1316 int register_savevm(const char *idstr,
1317 int instance_id,
1318 int version_id,
1319 SaveStateHandler *save_state,
1320 LoadStateHandler *load_state,
1321 void *opaque)
1323 SaveStateEntry *se, **pse;
1325 se = qemu_malloc(sizeof(SaveStateEntry));
1326 if (!se)
1327 return -1;
1328 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1329 se->instance_id = instance_id;
1330 se->version_id = version_id;
1331 se->save_state = save_state;
1332 se->load_state = load_state;
1333 se->opaque = opaque;
1334 se->next = NULL;
1336 /* add at the end of list */
1337 pse = &first_se;
1338 while (*pse != NULL)
1339 pse = &(*pse)->next;
1340 *pse = se;
1341 return 0;
1344 #define QEMU_VM_FILE_MAGIC 0x5145564d
1345 #define QEMU_VM_FILE_VERSION 0x00000001
1347 int qemu_savevm(const char *filename)
1349 SaveStateEntry *se;
1350 QEMUFile *f;
1351 int len, len_pos, cur_pos, saved_vm_running, ret;
1353 saved_vm_running = vm_running;
1354 vm_stop(0);
1356 f = fopen(filename, "wb");
1357 if (!f) {
1358 ret = -1;
1359 goto the_end;
1362 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1363 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1365 for(se = first_se; se != NULL; se = se->next) {
1366 /* ID string */
1367 len = strlen(se->idstr);
1368 qemu_put_byte(f, len);
1369 qemu_put_buffer(f, se->idstr, len);
1371 qemu_put_be32(f, se->instance_id);
1372 qemu_put_be32(f, se->version_id);
1374 /* record size: filled later */
1375 len_pos = ftell(f);
1376 qemu_put_be32(f, 0);
1378 se->save_state(f, se->opaque);
1380 /* fill record size */
1381 cur_pos = ftell(f);
1382 len = ftell(f) - len_pos - 4;
1383 fseek(f, len_pos, SEEK_SET);
1384 qemu_put_be32(f, len);
1385 fseek(f, cur_pos, SEEK_SET);
1388 fclose(f);
1389 ret = 0;
1390 the_end:
1391 if (saved_vm_running)
1392 vm_start();
1393 return ret;
1396 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1398 SaveStateEntry *se;
1400 for(se = first_se; se != NULL; se = se->next) {
1401 if (!strcmp(se->idstr, idstr) &&
1402 instance_id == se->instance_id)
1403 return se;
1405 return NULL;
1408 int qemu_loadvm(const char *filename)
1410 SaveStateEntry *se;
1411 QEMUFile *f;
1412 int len, cur_pos, ret, instance_id, record_len, version_id;
1413 int saved_vm_running;
1414 unsigned int v;
1415 char idstr[256];
1417 saved_vm_running = vm_running;
1418 vm_stop(0);
1420 f = fopen(filename, "rb");
1421 if (!f) {
1422 ret = -1;
1423 goto the_end;
1426 v = qemu_get_be32(f);
1427 if (v != QEMU_VM_FILE_MAGIC)
1428 goto fail;
1429 v = qemu_get_be32(f);
1430 if (v != QEMU_VM_FILE_VERSION) {
1431 fail:
1432 fclose(f);
1433 ret = -1;
1434 goto the_end;
1436 for(;;) {
1437 #if defined (DO_TB_FLUSH)
1438 tb_flush(global_env);
1439 #endif
1440 len = qemu_get_byte(f);
1441 if (feof(f))
1442 break;
1443 qemu_get_buffer(f, idstr, len);
1444 idstr[len] = '\0';
1445 instance_id = qemu_get_be32(f);
1446 version_id = qemu_get_be32(f);
1447 record_len = qemu_get_be32(f);
1448 #if 0
1449 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1450 idstr, instance_id, version_id, record_len);
1451 #endif
1452 cur_pos = ftell(f);
1453 se = find_se(idstr, instance_id);
1454 if (!se) {
1455 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1456 instance_id, idstr);
1457 } else {
1458 ret = se->load_state(f, se->opaque, version_id);
1459 if (ret < 0) {
1460 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1461 instance_id, idstr);
1464 /* always seek to exact end of record */
1465 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1467 fclose(f);
1468 ret = 0;
1469 the_end:
1470 if (saved_vm_running)
1471 vm_start();
1472 return ret;
1475 /***********************************************************/
1476 /* cpu save/restore */
1478 #if defined(TARGET_I386)
1480 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1482 qemu_put_be32(f, (uint32_t)dt->base);
1483 qemu_put_be32(f, dt->limit);
1484 qemu_put_be32(f, dt->flags);
1487 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1489 dt->base = (uint8_t *)qemu_get_be32(f);
1490 dt->limit = qemu_get_be32(f);
1491 dt->flags = qemu_get_be32(f);
1494 void cpu_save(QEMUFile *f, void *opaque)
1496 CPUState *env = opaque;
1497 uint16_t fptag, fpus, fpuc;
1498 uint32_t hflags;
1499 int i;
1501 for(i = 0; i < 8; i++)
1502 qemu_put_be32s(f, &env->regs[i]);
1503 qemu_put_be32s(f, &env->eip);
1504 qemu_put_be32s(f, &env->eflags);
1505 qemu_put_be32s(f, &env->eflags);
1506 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1507 qemu_put_be32s(f, &hflags);
1509 /* FPU */
1510 fpuc = env->fpuc;
1511 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1512 fptag = 0;
1513 for (i=7; i>=0; i--) {
1514 fptag <<= 2;
1515 if (env->fptags[i]) {
1516 fptag |= 3;
1520 qemu_put_be16s(f, &fpuc);
1521 qemu_put_be16s(f, &fpus);
1522 qemu_put_be16s(f, &fptag);
1524 for(i = 0; i < 8; i++) {
1525 uint64_t mant;
1526 uint16_t exp;
1527 cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1528 qemu_put_be64(f, mant);
1529 qemu_put_be16(f, exp);
1532 for(i = 0; i < 6; i++)
1533 cpu_put_seg(f, &env->segs[i]);
1534 cpu_put_seg(f, &env->ldt);
1535 cpu_put_seg(f, &env->tr);
1536 cpu_put_seg(f, &env->gdt);
1537 cpu_put_seg(f, &env->idt);
1539 qemu_put_be32s(f, &env->sysenter_cs);
1540 qemu_put_be32s(f, &env->sysenter_esp);
1541 qemu_put_be32s(f, &env->sysenter_eip);
1543 qemu_put_be32s(f, &env->cr[0]);
1544 qemu_put_be32s(f, &env->cr[2]);
1545 qemu_put_be32s(f, &env->cr[3]);
1546 qemu_put_be32s(f, &env->cr[4]);
1548 for(i = 0; i < 8; i++)
1549 qemu_put_be32s(f, &env->dr[i]);
1551 /* MMU */
1552 qemu_put_be32s(f, &env->a20_mask);
1555 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1557 CPUState *env = opaque;
1558 int i;
1559 uint32_t hflags;
1560 uint16_t fpus, fpuc, fptag;
1562 if (version_id != 1)
1563 return -EINVAL;
1564 for(i = 0; i < 8; i++)
1565 qemu_get_be32s(f, &env->regs[i]);
1566 qemu_get_be32s(f, &env->eip);
1567 qemu_get_be32s(f, &env->eflags);
1568 qemu_get_be32s(f, &env->eflags);
1569 qemu_get_be32s(f, &hflags);
1571 qemu_get_be16s(f, &fpuc);
1572 qemu_get_be16s(f, &fpus);
1573 qemu_get_be16s(f, &fptag);
1575 for(i = 0; i < 8; i++) {
1576 uint64_t mant;
1577 uint16_t exp;
1578 mant = qemu_get_be64(f);
1579 exp = qemu_get_be16(f);
1580 env->fpregs[i] = cpu_set_fp80(mant, exp);
1583 env->fpuc = fpuc;
1584 env->fpstt = (fpus >> 11) & 7;
1585 env->fpus = fpus & ~0x3800;
1586 for(i = 0; i < 8; i++) {
1587 env->fptags[i] = ((fptag & 3) == 3);
1588 fptag >>= 2;
1591 for(i = 0; i < 6; i++)
1592 cpu_get_seg(f, &env->segs[i]);
1593 cpu_get_seg(f, &env->ldt);
1594 cpu_get_seg(f, &env->tr);
1595 cpu_get_seg(f, &env->gdt);
1596 cpu_get_seg(f, &env->idt);
1598 qemu_get_be32s(f, &env->sysenter_cs);
1599 qemu_get_be32s(f, &env->sysenter_esp);
1600 qemu_get_be32s(f, &env->sysenter_eip);
1602 qemu_get_be32s(f, &env->cr[0]);
1603 qemu_get_be32s(f, &env->cr[2]);
1604 qemu_get_be32s(f, &env->cr[3]);
1605 qemu_get_be32s(f, &env->cr[4]);
1607 for(i = 0; i < 8; i++)
1608 qemu_get_be32s(f, &env->dr[i]);
1610 /* MMU */
1611 qemu_get_be32s(f, &env->a20_mask);
1613 /* XXX: compute hflags from scratch, except for CPL and IIF */
1614 env->hflags = hflags;
1615 tlb_flush(env, 1);
1616 return 0;
1619 #elif defined(TARGET_PPC)
1620 void cpu_save(QEMUFile *f, void *opaque)
1624 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1626 return 0;
1628 #else
1630 #warning No CPU save/restore functions
1632 #endif
1634 /***********************************************************/
1635 /* ram save/restore */
1637 /* we just avoid storing empty pages */
1638 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1640 int i, v;
1642 v = buf[0];
1643 for(i = 1; i < len; i++) {
1644 if (buf[i] != v)
1645 goto normal_save;
1647 qemu_put_byte(f, 1);
1648 qemu_put_byte(f, v);
1649 return;
1650 normal_save:
1651 qemu_put_byte(f, 0);
1652 qemu_put_buffer(f, buf, len);
1655 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1657 int v;
1659 v = qemu_get_byte(f);
1660 switch(v) {
1661 case 0:
1662 if (qemu_get_buffer(f, buf, len) != len)
1663 return -EIO;
1664 break;
1665 case 1:
1666 v = qemu_get_byte(f);
1667 memset(buf, v, len);
1668 break;
1669 default:
1670 return -EINVAL;
1672 return 0;
1675 static void ram_save(QEMUFile *f, void *opaque)
1677 int i;
1678 qemu_put_be32(f, phys_ram_size);
1679 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1680 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1684 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1686 int i, ret;
1688 if (version_id != 1)
1689 return -EINVAL;
1690 if (qemu_get_be32(f) != phys_ram_size)
1691 return -EINVAL;
1692 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1693 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1694 if (ret)
1695 return ret;
1697 return 0;
1700 /***********************************************************/
1701 /* main execution loop */
1703 void gui_update(void *opaque)
1705 display_state.dpy_refresh(&display_state);
1706 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1709 /* XXX: support several handlers */
1710 VMStopHandler *vm_stop_cb;
1711 VMStopHandler *vm_stop_opaque;
1713 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1715 vm_stop_cb = cb;
1716 vm_stop_opaque = opaque;
1717 return 0;
1720 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1722 vm_stop_cb = NULL;
1725 void vm_start(void)
1727 if (!vm_running) {
1728 cpu_enable_ticks();
1729 vm_running = 1;
1733 void vm_stop(int reason)
1735 if (vm_running) {
1736 cpu_disable_ticks();
1737 vm_running = 0;
1738 if (reason != 0) {
1739 if (vm_stop_cb) {
1740 vm_stop_cb(vm_stop_opaque, reason);
1746 int main_loop(void)
1748 #ifndef _WIN32
1749 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1750 IOHandlerRecord *ioh, *ioh_next;
1751 uint8_t buf[4096];
1752 int n, max_size;
1753 #endif
1754 int ret, timeout;
1755 CPUState *env = global_env;
1757 for(;;) {
1758 if (vm_running) {
1759 ret = cpu_exec(env);
1760 if (reset_requested) {
1761 ret = EXCP_INTERRUPT;
1762 break;
1764 if (ret == EXCP_DEBUG) {
1765 vm_stop(EXCP_DEBUG);
1767 /* if hlt instruction, we wait until the next IRQ */
1768 /* XXX: use timeout computed from timers */
1769 if (ret == EXCP_HLT)
1770 timeout = 10;
1771 else
1772 timeout = 0;
1773 } else {
1774 timeout = 10;
1777 #ifdef _WIN32
1778 if (timeout > 0)
1779 Sleep(timeout);
1780 #else
1782 /* poll any events */
1783 /* XXX: separate device handlers from system ones */
1784 pf = ufds;
1785 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1786 if (!ioh->fd_can_read) {
1787 max_size = 0;
1788 pf->fd = ioh->fd;
1789 pf->events = POLLIN;
1790 ioh->ufd = pf;
1791 pf++;
1792 } else {
1793 max_size = ioh->fd_can_read(ioh->opaque);
1794 if (max_size > 0) {
1795 if (max_size > sizeof(buf))
1796 max_size = sizeof(buf);
1797 pf->fd = ioh->fd;
1798 pf->events = POLLIN;
1799 ioh->ufd = pf;
1800 pf++;
1801 } else {
1802 ioh->ufd = NULL;
1805 ioh->max_size = max_size;
1808 ret = poll(ufds, pf - ufds, timeout);
1809 if (ret > 0) {
1810 /* XXX: better handling of removal */
1811 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1812 ioh_next = ioh->next;
1813 pf = ioh->ufd;
1814 if (pf) {
1815 if (pf->revents & POLLIN) {
1816 if (ioh->max_size == 0) {
1817 /* just a read event */
1818 ioh->fd_read(ioh->opaque, NULL, 0);
1819 } else {
1820 n = read(ioh->fd, buf, ioh->max_size);
1821 if (n >= 0) {
1822 ioh->fd_read(ioh->opaque, buf, n);
1823 } else if (errno != -EAGAIN) {
1824 ioh->fd_read(ioh->opaque, NULL, -errno);
1832 #if defined(CONFIG_SLIRP)
1833 /* XXX: merge with poll() */
1834 if (slirp_inited) {
1835 fd_set rfds, wfds, xfds;
1836 int nfds;
1837 struct timeval tv;
1839 nfds = -1;
1840 FD_ZERO(&rfds);
1841 FD_ZERO(&wfds);
1842 FD_ZERO(&xfds);
1843 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1844 tv.tv_sec = 0;
1845 tv.tv_usec = 0;
1846 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1847 if (ret >= 0) {
1848 slirp_select_poll(&rfds, &wfds, &xfds);
1851 #endif
1853 #endif
1855 if (vm_running) {
1856 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1857 qemu_get_clock(vm_clock));
1859 if (audio_enabled) {
1860 /* XXX: add explicit timer */
1861 SB16_run();
1864 /* run dma transfers, if any */
1865 DMA_run();
1868 /* real time timers */
1869 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1870 qemu_get_clock(rt_clock));
1872 cpu_disable_ticks();
1873 return ret;
1876 void help(void)
1878 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1879 "usage: %s [options] [disk_image]\n"
1880 "\n"
1881 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1882 "\n"
1883 "Standard options:\n"
1884 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
1885 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
1886 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
1887 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1888 "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1889 "-snapshot write to temporary files instead of disk image files\n"
1890 "-m megs set virtual RAM size to megs MB\n"
1891 "-nographic disable graphical output and redirect serial I/Os to console\n"
1892 "-enable-audio enable audio support\n"
1893 "\n"
1894 "Network options:\n"
1895 "-nics n simulate 'n' network cards [default=1]\n"
1896 "-macaddr addr set the mac address of the first interface\n"
1897 "-n script set tap/tun network init script [default=%s]\n"
1898 "-tun-fd fd use this fd as already opened tap/tun interface\n"
1899 #ifdef CONFIG_SLIRP
1900 "-user-net use user mode network stack [default if no tap/tun script]\n"
1901 #endif
1902 "-dummy-net use dummy network stack\n"
1903 "\n"
1904 "Linux boot specific:\n"
1905 "-kernel bzImage use 'bzImage' as kernel image\n"
1906 "-append cmdline use 'cmdline' as kernel command line\n"
1907 "-initrd file use 'file' as initial ram disk\n"
1908 "\n"
1909 "Debug/Expert options:\n"
1910 "-S freeze CPU at startup (use 'c' to start execution)\n"
1911 "-s wait gdb connection to port %d\n"
1912 "-p port change gdb connection port\n"
1913 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
1914 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
1915 "-L path set the directory for the BIOS and VGA BIOS\n"
1916 #ifdef USE_CODE_COPY
1917 "-no-code-copy disable code copy acceleration\n"
1918 #endif
1920 "\n"
1921 "During emulation, use C-a h to get terminal commands:\n",
1922 #ifdef CONFIG_SOFTMMU
1923 "qemu",
1924 #else
1925 "qemu-fast",
1926 #endif
1927 DEFAULT_NETWORK_SCRIPT,
1928 DEFAULT_GDBSTUB_PORT,
1929 "/tmp/qemu.log");
1930 term_print_help();
1931 #ifndef CONFIG_SOFTMMU
1932 printf("\n"
1933 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1934 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1935 "PC emulation.\n");
1936 #endif
1937 exit(1);
1940 #define HAS_ARG 0x0001
1942 enum {
1943 QEMU_OPTION_h,
1945 QEMU_OPTION_fda,
1946 QEMU_OPTION_fdb,
1947 QEMU_OPTION_hda,
1948 QEMU_OPTION_hdb,
1949 QEMU_OPTION_hdc,
1950 QEMU_OPTION_hdd,
1951 QEMU_OPTION_cdrom,
1952 QEMU_OPTION_boot,
1953 QEMU_OPTION_snapshot,
1954 QEMU_OPTION_m,
1955 QEMU_OPTION_nographic,
1956 QEMU_OPTION_enable_audio,
1958 QEMU_OPTION_nics,
1959 QEMU_OPTION_macaddr,
1960 QEMU_OPTION_n,
1961 QEMU_OPTION_tun_fd,
1962 QEMU_OPTION_user_net,
1963 QEMU_OPTION_dummy_net,
1965 QEMU_OPTION_kernel,
1966 QEMU_OPTION_append,
1967 QEMU_OPTION_initrd,
1969 QEMU_OPTION_S,
1970 QEMU_OPTION_s,
1971 QEMU_OPTION_p,
1972 QEMU_OPTION_d,
1973 QEMU_OPTION_hdachs,
1974 QEMU_OPTION_L,
1975 QEMU_OPTION_no_code_copy,
1978 typedef struct QEMUOption {
1979 const char *name;
1980 int flags;
1981 int index;
1982 } QEMUOption;
1984 const QEMUOption qemu_options[] = {
1985 { "h", 0, QEMU_OPTION_h },
1987 { "fda", HAS_ARG, QEMU_OPTION_fda },
1988 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
1989 { "hda", HAS_ARG, QEMU_OPTION_hda },
1990 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
1991 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
1992 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
1993 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
1994 { "boot", HAS_ARG, QEMU_OPTION_boot },
1995 { "snapshot", 0, QEMU_OPTION_snapshot },
1996 { "m", HAS_ARG, QEMU_OPTION_m },
1997 { "nographic", 0, QEMU_OPTION_nographic },
1998 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2000 { "nics", HAS_ARG, QEMU_OPTION_nics},
2001 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2002 { "n", HAS_ARG, QEMU_OPTION_d },
2003 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2004 { "user-net", 0, QEMU_OPTION_user_net },
2005 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2007 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2008 { "append", HAS_ARG, QEMU_OPTION_append },
2009 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2011 { "S", 0, QEMU_OPTION_S },
2012 { "s", 0, QEMU_OPTION_s },
2013 { "p", HAS_ARG, QEMU_OPTION_p },
2014 { "d", HAS_ARG, QEMU_OPTION_d },
2015 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2016 { "L", HAS_ARG, QEMU_OPTION_L },
2017 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2018 { NULL },
2021 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2023 /* this stack is only used during signal handling */
2024 #define SIGNAL_STACK_SIZE 32768
2026 static uint8_t *signal_stack;
2028 #endif
2030 #define NET_IF_TUN 0
2031 #define NET_IF_USER 1
2032 #define NET_IF_DUMMY 2
2034 int main(int argc, char **argv)
2036 #ifdef CONFIG_GDBSTUB
2037 int use_gdbstub, gdbstub_port;
2038 #endif
2039 int i, has_cdrom;
2040 int snapshot, linux_boot;
2041 CPUState *env;
2042 const char *initrd_filename;
2043 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2044 const char *kernel_filename, *kernel_cmdline;
2045 DisplayState *ds = &display_state;
2046 int cyls, heads, secs;
2047 int start_emulation = 1;
2048 uint8_t macaddr[6];
2049 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2050 int optind;
2051 const char *r, *optarg;
2053 #if !defined(CONFIG_SOFTMMU)
2054 /* we never want that malloc() uses mmap() */
2055 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2056 #endif
2057 initrd_filename = NULL;
2058 for(i = 0; i < MAX_FD; i++)
2059 fd_filename[i] = NULL;
2060 for(i = 0; i < MAX_DISKS; i++)
2061 hd_filename[i] = NULL;
2062 ram_size = 32 * 1024 * 1024;
2063 vga_ram_size = VGA_RAM_SIZE;
2064 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2065 #ifdef CONFIG_GDBSTUB
2066 use_gdbstub = 0;
2067 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2068 #endif
2069 snapshot = 0;
2070 nographic = 0;
2071 kernel_filename = NULL;
2072 kernel_cmdline = "";
2073 has_cdrom = 1;
2074 cyls = heads = secs = 0;
2076 nb_tun_fds = 0;
2077 net_if_type = -1;
2078 nb_nics = 1;
2079 /* default mac address of the first network interface */
2080 macaddr[0] = 0x52;
2081 macaddr[1] = 0x54;
2082 macaddr[2] = 0x00;
2083 macaddr[3] = 0x12;
2084 macaddr[4] = 0x34;
2085 macaddr[5] = 0x56;
2087 optind = 1;
2088 for(;;) {
2089 if (optind >= argc)
2090 break;
2091 r = argv[optind];
2092 if (r[0] != '-') {
2093 hd_filename[0] = argv[optind++];
2094 } else {
2095 const QEMUOption *popt;
2097 optind++;
2098 popt = qemu_options;
2099 for(;;) {
2100 if (!popt->name) {
2101 fprintf(stderr, "%s: invalid option -- '%s'\n",
2102 argv[0], r);
2103 exit(1);
2105 if (!strcmp(popt->name, r + 1))
2106 break;
2107 popt++;
2109 if (popt->flags & HAS_ARG) {
2110 if (optind >= argc) {
2111 fprintf(stderr, "%s: option '%s' requires an argument\n",
2112 argv[0], r);
2113 exit(1);
2115 optarg = argv[optind++];
2116 } else {
2117 optarg = NULL;
2120 switch(popt->index) {
2121 case QEMU_OPTION_initrd:
2122 initrd_filename = optarg;
2123 break;
2124 case QEMU_OPTION_hda:
2125 hd_filename[0] = optarg;
2126 break;
2127 case QEMU_OPTION_hdb:
2128 hd_filename[1] = optarg;
2129 break;
2130 case QEMU_OPTION_snapshot:
2131 snapshot = 1;
2132 break;
2133 case QEMU_OPTION_hdachs:
2135 const char *p;
2136 p = optarg;
2137 cyls = strtol(p, (char **)&p, 0);
2138 if (*p != ',')
2139 goto chs_fail;
2140 p++;
2141 heads = strtol(p, (char **)&p, 0);
2142 if (*p != ',')
2143 goto chs_fail;
2144 p++;
2145 secs = strtol(p, (char **)&p, 0);
2146 if (*p != '\0') {
2147 chs_fail:
2148 cyls = 0;
2151 break;
2152 case QEMU_OPTION_nographic:
2153 nographic = 1;
2154 break;
2155 case QEMU_OPTION_kernel:
2156 kernel_filename = optarg;
2157 break;
2158 case QEMU_OPTION_append:
2159 kernel_cmdline = optarg;
2160 break;
2161 case QEMU_OPTION_tun_fd:
2163 const char *p;
2164 int fd;
2165 net_if_type = NET_IF_TUN;
2166 if (nb_tun_fds < MAX_NICS) {
2167 fd = strtol(optarg, (char **)&p, 0);
2168 if (*p != '\0') {
2169 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2170 exit(1);
2172 tun_fds[nb_tun_fds++] = fd;
2175 break;
2176 case QEMU_OPTION_hdc:
2177 hd_filename[2] = optarg;
2178 has_cdrom = 0;
2179 break;
2180 case QEMU_OPTION_hdd:
2181 hd_filename[3] = optarg;
2182 break;
2183 case QEMU_OPTION_cdrom:
2184 hd_filename[2] = optarg;
2185 has_cdrom = 1;
2186 break;
2187 case QEMU_OPTION_boot:
2188 boot_device = optarg[0];
2189 if (boot_device != 'a' && boot_device != 'b' &&
2190 boot_device != 'c' && boot_device != 'd') {
2191 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2192 exit(1);
2194 break;
2195 case QEMU_OPTION_fda:
2196 fd_filename[0] = optarg;
2197 break;
2198 case QEMU_OPTION_fdb:
2199 fd_filename[1] = optarg;
2200 break;
2201 case QEMU_OPTION_no_code_copy:
2202 code_copy_enabled = 0;
2203 break;
2204 case QEMU_OPTION_nics:
2205 nb_nics = atoi(optarg);
2206 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2207 fprintf(stderr, "qemu: invalid number of network interfaces\n");
2208 exit(1);
2210 break;
2211 case QEMU_OPTION_macaddr:
2213 const char *p;
2214 int i;
2215 p = optarg;
2216 for(i = 0; i < 6; i++) {
2217 macaddr[i] = strtol(p, (char **)&p, 16);
2218 if (i == 5) {
2219 if (*p != '\0')
2220 goto macaddr_error;
2221 } else {
2222 if (*p != ':') {
2223 macaddr_error:
2224 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2225 exit(1);
2227 p++;
2231 break;
2232 case QEMU_OPTION_user_net:
2233 net_if_type = NET_IF_USER;
2234 break;
2235 case QEMU_OPTION_dummy_net:
2236 net_if_type = NET_IF_DUMMY;
2237 break;
2238 case QEMU_OPTION_enable_audio:
2239 audio_enabled = 1;
2240 break;
2241 case QEMU_OPTION_h:
2242 help();
2243 break;
2244 case QEMU_OPTION_m:
2245 ram_size = atoi(optarg) * 1024 * 1024;
2246 if (ram_size <= 0)
2247 help();
2248 if (ram_size > PHYS_RAM_MAX_SIZE) {
2249 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2250 PHYS_RAM_MAX_SIZE / (1024 * 1024));
2251 exit(1);
2253 break;
2254 case QEMU_OPTION_d:
2256 int mask;
2257 CPULogItem *item;
2259 mask = cpu_str_to_log_mask(optarg);
2260 if (!mask) {
2261 printf("Log items (comma separated):\n");
2262 for(item = cpu_log_items; item->mask != 0; item++) {
2263 printf("%-10s %s\n", item->name, item->help);
2265 exit(1);
2267 cpu_set_log(mask);
2269 break;
2270 case QEMU_OPTION_n:
2271 pstrcpy(network_script, sizeof(network_script), optarg);
2272 break;
2273 #ifdef CONFIG_GDBSTUB
2274 case QEMU_OPTION_s:
2275 use_gdbstub = 1;
2276 break;
2277 case QEMU_OPTION_p:
2278 gdbstub_port = atoi(optarg);
2279 break;
2280 #endif
2281 case QEMU_OPTION_L:
2282 bios_dir = optarg;
2283 break;
2284 case QEMU_OPTION_S:
2285 start_emulation = 0;
2286 break;
2291 linux_boot = (kernel_filename != NULL);
2293 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2294 fd_filename[0] == '\0')
2295 help();
2297 /* boot to cd by default if no hard disk */
2298 if (hd_filename[0] == '\0' && boot_device == 'c') {
2299 if (fd_filename[0] != '\0')
2300 boot_device = 'a';
2301 else
2302 boot_device = 'd';
2305 #if !defined(CONFIG_SOFTMMU)
2306 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2308 static uint8_t stdout_buf[4096];
2309 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2311 #else
2312 setvbuf(stdout, NULL, _IOLBF, 0);
2313 #endif
2315 /* init host network redirectors */
2316 if (net_if_type == -1) {
2317 net_if_type = NET_IF_TUN;
2318 #if defined(CONFIG_SLIRP)
2319 if (access(network_script, R_OK) < 0) {
2320 net_if_type = NET_IF_USER;
2322 #endif
2325 for(i = 0; i < nb_nics; i++) {
2326 NetDriverState *nd = &nd_table[i];
2327 nd->index = i;
2328 /* init virtual mac address */
2329 nd->macaddr[0] = macaddr[0];
2330 nd->macaddr[1] = macaddr[1];
2331 nd->macaddr[2] = macaddr[2];
2332 nd->macaddr[3] = macaddr[3];
2333 nd->macaddr[4] = macaddr[4];
2334 nd->macaddr[5] = macaddr[5] + i;
2335 switch(net_if_type) {
2336 #if defined(CONFIG_SLIRP)
2337 case NET_IF_USER:
2338 net_slirp_init(nd);
2339 break;
2340 #endif
2341 #if !defined(_WIN32)
2342 case NET_IF_TUN:
2343 if (i < nb_tun_fds) {
2344 net_fd_init(nd, tun_fds[i]);
2345 } else {
2346 if (net_tun_init(nd) < 0)
2347 net_dummy_init(nd);
2349 break;
2350 #endif
2351 case NET_IF_DUMMY:
2352 default:
2353 net_dummy_init(nd);
2354 break;
2358 /* init the memory */
2359 phys_ram_size = ram_size + vga_ram_size;
2361 #ifdef CONFIG_SOFTMMU
2362 #ifdef _BSD
2363 /* mallocs are always aligned on BSD. */
2364 phys_ram_base = malloc(phys_ram_size);
2365 #else
2366 phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2367 #endif
2368 if (!phys_ram_base) {
2369 fprintf(stderr, "Could not allocate physical memory\n");
2370 exit(1);
2372 #else
2373 /* as we must map the same page at several addresses, we must use
2374 a fd */
2376 const char *tmpdir;
2378 tmpdir = getenv("QEMU_TMPDIR");
2379 if (!tmpdir)
2380 tmpdir = "/tmp";
2381 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2382 if (mkstemp(phys_ram_file) < 0) {
2383 fprintf(stderr, "Could not create temporary memory file '%s'\n",
2384 phys_ram_file);
2385 exit(1);
2387 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2388 if (phys_ram_fd < 0) {
2389 fprintf(stderr, "Could not open temporary memory file '%s'\n",
2390 phys_ram_file);
2391 exit(1);
2393 ftruncate(phys_ram_fd, phys_ram_size);
2394 unlink(phys_ram_file);
2395 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
2396 phys_ram_size,
2397 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
2398 phys_ram_fd, 0);
2399 if (phys_ram_base == MAP_FAILED) {
2400 fprintf(stderr, "Could not map physical memory\n");
2401 exit(1);
2404 #endif
2406 /* we always create the cdrom drive, even if no disk is there */
2407 if (has_cdrom) {
2408 bs_table[2] = bdrv_new("cdrom");
2409 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2412 /* open the virtual block devices */
2413 for(i = 0; i < MAX_DISKS; i++) {
2414 if (hd_filename[i]) {
2415 if (!bs_table[i]) {
2416 char buf[64];
2417 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2418 bs_table[i] = bdrv_new(buf);
2420 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2421 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2422 hd_filename[i]);
2423 exit(1);
2425 if (i == 0 && cyls != 0)
2426 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2430 /* we always create at least one floppy disk */
2431 fd_table[0] = bdrv_new("fda");
2432 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2434 for(i = 0; i < MAX_FD; i++) {
2435 if (fd_filename[i]) {
2436 if (!fd_table[i]) {
2437 char buf[64];
2438 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2439 fd_table[i] = bdrv_new(buf);
2440 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2442 if (fd_filename[i] != '\0') {
2443 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2444 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2445 fd_filename[i]);
2446 exit(1);
2452 /* init CPU state */
2453 env = cpu_init();
2454 global_env = env;
2455 cpu_single_env = env;
2457 register_savevm("timer", 0, 1, timer_save, timer_load, env);
2458 register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2459 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2461 init_ioports();
2462 cpu_calibrate_ticks();
2464 /* terminal init */
2465 if (nographic) {
2466 dumb_display_init(ds);
2467 } else {
2468 #ifdef CONFIG_SDL
2469 sdl_display_init(ds);
2470 #else
2471 dumb_display_init(ds);
2472 #endif
2475 /* setup cpu signal handlers for MMU / self modifying code handling */
2476 #if !defined(CONFIG_SOFTMMU)
2478 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2480 stack_t stk;
2481 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2482 stk.ss_sp = signal_stack;
2483 stk.ss_size = SIGNAL_STACK_SIZE;
2484 stk.ss_flags = 0;
2486 if (sigaltstack(&stk, NULL) < 0) {
2487 perror("sigaltstack");
2488 exit(1);
2491 #endif
2493 struct sigaction act;
2495 sigfillset(&act.sa_mask);
2496 act.sa_flags = SA_SIGINFO;
2497 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2498 act.sa_flags |= SA_ONSTACK;
2499 #endif
2500 act.sa_sigaction = host_segv_handler;
2501 sigaction(SIGSEGV, &act, NULL);
2502 sigaction(SIGBUS, &act, NULL);
2503 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2504 sigaction(SIGFPE, &act, NULL);
2505 #endif
2507 #endif
2509 #ifndef _WIN32
2511 struct sigaction act;
2512 sigfillset(&act.sa_mask);
2513 act.sa_flags = 0;
2514 act.sa_handler = SIG_IGN;
2515 sigaction(SIGPIPE, &act, NULL);
2517 #endif
2518 init_timers();
2520 #if defined(TARGET_I386)
2521 pc_init(ram_size, vga_ram_size, boot_device,
2522 ds, fd_filename, snapshot,
2523 kernel_filename, kernel_cmdline, initrd_filename);
2524 #elif defined(TARGET_PPC)
2525 ppc_init(ram_size, vga_ram_size, boot_device,
2526 ds, fd_filename, snapshot,
2527 kernel_filename, kernel_cmdline, initrd_filename);
2528 #endif
2530 /* launched after the device init so that it can display or not a
2531 banner */
2532 monitor_init();
2534 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2535 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2537 #ifdef CONFIG_GDBSTUB
2538 if (use_gdbstub) {
2539 if (gdbserver_start(gdbstub_port) < 0) {
2540 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
2541 gdbstub_port);
2542 exit(1);
2543 } else {
2544 printf("Waiting gdb connection on port %d\n", gdbstub_port);
2546 } else
2547 #endif
2548 if (start_emulation)
2550 vm_start();
2552 term_init();
2553 main_loop();
2554 quit_timers();
2555 return 0;