removed unused stuff
[qemu/qemu_0_9_1_stable.git] / vl.c
blob40c0c0afdb28442ac4c7ddb228d9596ef180772d
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 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 #ifdef TARGET_SPARC
139 int graphic_width = 1024;
140 int graphic_height = 768;
141 #else
142 int graphic_width = 800;
143 int graphic_height = 600;
144 #endif
145 int graphic_depth = 15;
146 int full_screen = 0;
147 TextConsole *vga_console;
148 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
149 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
151 /***********************************************************/
152 /* x86 ISA bus support */
154 target_phys_addr_t isa_mem_base = 0;
156 uint32_t default_ioport_readb(void *opaque, uint32_t address)
158 #ifdef DEBUG_UNUSED_IOPORT
159 fprintf(stderr, "inb: port=0x%04x\n", address);
160 #endif
161 return 0xff;
164 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
166 #ifdef DEBUG_UNUSED_IOPORT
167 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
168 #endif
171 /* default is to make two byte accesses */
172 uint32_t default_ioport_readw(void *opaque, uint32_t address)
174 uint32_t data;
175 data = ioport_read_table[0][address](ioport_opaque[address], address);
176 address = (address + 1) & (MAX_IOPORTS - 1);
177 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
178 return data;
181 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
183 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
184 address = (address + 1) & (MAX_IOPORTS - 1);
185 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
188 uint32_t default_ioport_readl(void *opaque, uint32_t address)
190 #ifdef DEBUG_UNUSED_IOPORT
191 fprintf(stderr, "inl: port=0x%04x\n", address);
192 #endif
193 return 0xffffffff;
196 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
200 #endif
203 void init_ioports(void)
205 int i;
207 for(i = 0; i < MAX_IOPORTS; i++) {
208 ioport_read_table[0][i] = default_ioport_readb;
209 ioport_write_table[0][i] = default_ioport_writeb;
210 ioport_read_table[1][i] = default_ioport_readw;
211 ioport_write_table[1][i] = default_ioport_writew;
212 ioport_read_table[2][i] = default_ioport_readl;
213 ioport_write_table[2][i] = default_ioport_writel;
217 /* size is the word size in byte */
218 int register_ioport_read(int start, int length, int size,
219 IOPortReadFunc *func, void *opaque)
221 int i, bsize;
223 if (size == 1) {
224 bsize = 0;
225 } else if (size == 2) {
226 bsize = 1;
227 } else if (size == 4) {
228 bsize = 2;
229 } else {
230 hw_error("register_ioport_read: invalid size");
231 return -1;
233 for(i = start; i < start + length; i += size) {
234 ioport_read_table[bsize][i] = func;
235 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
236 hw_error("register_ioport_read: invalid opaque");
237 ioport_opaque[i] = opaque;
239 return 0;
242 /* size is the word size in byte */
243 int register_ioport_write(int start, int length, int size,
244 IOPortWriteFunc *func, void *opaque)
246 int i, bsize;
248 if (size == 1) {
249 bsize = 0;
250 } else if (size == 2) {
251 bsize = 1;
252 } else if (size == 4) {
253 bsize = 2;
254 } else {
255 hw_error("register_ioport_write: invalid size");
256 return -1;
258 for(i = start; i < start + length; i += size) {
259 ioport_write_table[bsize][i] = func;
260 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
261 hw_error("register_ioport_read: invalid opaque");
262 ioport_opaque[i] = opaque;
264 return 0;
267 void isa_unassign_ioport(int start, int length)
269 int i;
271 for(i = start; i < start + length; i++) {
272 ioport_read_table[0][i] = default_ioport_readb;
273 ioport_read_table[1][i] = default_ioport_readw;
274 ioport_read_table[2][i] = default_ioport_readl;
276 ioport_write_table[0][i] = default_ioport_writeb;
277 ioport_write_table[1][i] = default_ioport_writew;
278 ioport_write_table[2][i] = default_ioport_writel;
282 /***********************************************************/
284 void pstrcpy(char *buf, int buf_size, const char *str)
286 int c;
287 char *q = buf;
289 if (buf_size <= 0)
290 return;
292 for(;;) {
293 c = *str++;
294 if (c == 0 || q >= buf + buf_size - 1)
295 break;
296 *q++ = c;
298 *q = '\0';
301 /* strcat and truncate. */
302 char *pstrcat(char *buf, int buf_size, const char *s)
304 int len;
305 len = strlen(buf);
306 if (len < buf_size)
307 pstrcpy(buf + len, buf_size - len, s);
308 return buf;
311 int strstart(const char *str, const char *val, const char **ptr)
313 const char *p, *q;
314 p = str;
315 q = val;
316 while (*q != '\0') {
317 if (*p != *q)
318 return 0;
319 p++;
320 q++;
322 if (ptr)
323 *ptr = p;
324 return 1;
327 /* return the size or -1 if error */
328 int get_image_size(const char *filename)
330 int fd, size;
331 fd = open(filename, O_RDONLY | O_BINARY);
332 if (fd < 0)
333 return -1;
334 size = lseek(fd, 0, SEEK_END);
335 close(fd);
336 return size;
339 /* return the size or -1 if error */
340 int load_image(const char *filename, uint8_t *addr)
342 int fd, size;
343 fd = open(filename, O_RDONLY | O_BINARY);
344 if (fd < 0)
345 return -1;
346 size = lseek(fd, 0, SEEK_END);
347 lseek(fd, 0, SEEK_SET);
348 if (read(fd, addr, size) != size) {
349 close(fd);
350 return -1;
352 close(fd);
353 return size;
356 void cpu_outb(CPUState *env, int addr, int val)
358 #ifdef DEBUG_IOPORT
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "outb: %04x %02x\n", addr, val);
361 #endif
362 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
365 void cpu_outw(CPUState *env, int addr, int val)
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outw: %04x %04x\n", addr, val);
370 #endif
371 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
374 void cpu_outl(CPUState *env, int addr, int val)
376 #ifdef DEBUG_IOPORT
377 if (loglevel & CPU_LOG_IOPORT)
378 fprintf(logfile, "outl: %04x %08x\n", addr, val);
379 #endif
380 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
383 int cpu_inb(CPUState *env, int addr)
385 int val;
386 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
387 #ifdef DEBUG_IOPORT
388 if (loglevel & CPU_LOG_IOPORT)
389 fprintf(logfile, "inb : %04x %02x\n", addr, val);
390 #endif
391 return val;
394 int cpu_inw(CPUState *env, int addr)
396 int val;
397 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
398 #ifdef DEBUG_IOPORT
399 if (loglevel & CPU_LOG_IOPORT)
400 fprintf(logfile, "inw : %04x %04x\n", addr, val);
401 #endif
402 return val;
405 int cpu_inl(CPUState *env, int addr)
407 int val;
408 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
409 #ifdef DEBUG_IOPORT
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "inl : %04x %08x\n", addr, val);
412 #endif
413 return val;
416 /***********************************************************/
417 void hw_error(const char *fmt, ...)
419 va_list ap;
421 va_start(ap, fmt);
422 fprintf(stderr, "qemu: hardware error: ");
423 vfprintf(stderr, fmt, ap);
424 fprintf(stderr, "\n");
425 #ifdef TARGET_I386
426 cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
427 #else
428 cpu_dump_state(global_env, stderr, fprintf, 0);
429 #endif
430 va_end(ap);
431 abort();
434 /***********************************************************/
435 /* keyboard/mouse */
437 static QEMUPutKBDEvent *qemu_put_kbd_event;
438 static void *qemu_put_kbd_event_opaque;
439 static QEMUPutMouseEvent *qemu_put_mouse_event;
440 static void *qemu_put_mouse_event_opaque;
442 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
444 qemu_put_kbd_event_opaque = opaque;
445 qemu_put_kbd_event = func;
448 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
450 qemu_put_mouse_event_opaque = opaque;
451 qemu_put_mouse_event = func;
454 void kbd_put_keycode(int keycode)
456 if (qemu_put_kbd_event) {
457 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
461 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
463 if (qemu_put_mouse_event) {
464 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
465 dx, dy, dz, buttons_state);
469 /***********************************************************/
470 /* timers */
472 #if defined(__powerpc__)
474 static inline uint32_t get_tbl(void)
476 uint32_t tbl;
477 asm volatile("mftb %0" : "=r" (tbl));
478 return tbl;
481 static inline uint32_t get_tbu(void)
483 uint32_t tbl;
484 asm volatile("mftbu %0" : "=r" (tbl));
485 return tbl;
488 int64_t cpu_get_real_ticks(void)
490 uint32_t l, h, h1;
491 /* NOTE: we test if wrapping has occurred */
492 do {
493 h = get_tbu();
494 l = get_tbl();
495 h1 = get_tbu();
496 } while (h != h1);
497 return ((int64_t)h << 32) | l;
500 #elif defined(__i386__)
502 int64_t cpu_get_real_ticks(void)
504 int64_t val;
505 asm volatile ("rdtsc" : "=A" (val));
506 return val;
509 #elif defined(__x86_64__)
511 int64_t cpu_get_real_ticks(void)
513 uint32_t low,high;
514 int64_t val;
515 asm volatile("rdtsc" : "=a" (low), "=d" (high));
516 val = high;
517 val <<= 32;
518 val |= low;
519 return val;
522 #elif defined(__ia64)
524 int64_t cpu_get_real_ticks(void)
526 int64_t val;
527 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
528 return val;
531 #else
532 #error unsupported CPU
533 #endif
535 static int64_t cpu_ticks_offset;
536 static int cpu_ticks_enabled;
538 static inline int64_t cpu_get_ticks(void)
540 if (!cpu_ticks_enabled) {
541 return cpu_ticks_offset;
542 } else {
543 return cpu_get_real_ticks() + cpu_ticks_offset;
547 /* enable cpu_get_ticks() */
548 void cpu_enable_ticks(void)
550 if (!cpu_ticks_enabled) {
551 cpu_ticks_offset -= cpu_get_real_ticks();
552 cpu_ticks_enabled = 1;
556 /* disable cpu_get_ticks() : the clock is stopped. You must not call
557 cpu_get_ticks() after that. */
558 void cpu_disable_ticks(void)
560 if (cpu_ticks_enabled) {
561 cpu_ticks_offset = cpu_get_ticks();
562 cpu_ticks_enabled = 0;
566 static int64_t get_clock(void)
568 #ifdef _WIN32
569 struct _timeb tb;
570 _ftime(&tb);
571 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
572 #else
573 struct timeval tv;
574 gettimeofday(&tv, NULL);
575 return tv.tv_sec * 1000000LL + tv.tv_usec;
576 #endif
579 void cpu_calibrate_ticks(void)
581 int64_t usec, ticks;
583 usec = get_clock();
584 ticks = cpu_get_real_ticks();
585 #ifdef _WIN32
586 Sleep(50);
587 #else
588 usleep(50 * 1000);
589 #endif
590 usec = get_clock() - usec;
591 ticks = cpu_get_real_ticks() - ticks;
592 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
595 /* compute with 96 bit intermediate result: (a*b)/c */
596 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
598 union {
599 uint64_t ll;
600 struct {
601 #ifdef WORDS_BIGENDIAN
602 uint32_t high, low;
603 #else
604 uint32_t low, high;
605 #endif
606 } l;
607 } u, res;
608 uint64_t rl, rh;
610 u.ll = a;
611 rl = (uint64_t)u.l.low * (uint64_t)b;
612 rh = (uint64_t)u.l.high * (uint64_t)b;
613 rh += (rl >> 32);
614 res.l.high = rh / c;
615 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
616 return res.ll;
619 #define QEMU_TIMER_REALTIME 0
620 #define QEMU_TIMER_VIRTUAL 1
622 struct QEMUClock {
623 int type;
624 /* XXX: add frequency */
627 struct QEMUTimer {
628 QEMUClock *clock;
629 int64_t expire_time;
630 QEMUTimerCB *cb;
631 void *opaque;
632 struct QEMUTimer *next;
635 QEMUClock *rt_clock;
636 QEMUClock *vm_clock;
638 static QEMUTimer *active_timers[2];
639 #ifdef _WIN32
640 static MMRESULT timerID;
641 #else
642 /* frequency of the times() clock tick */
643 static int timer_freq;
644 #endif
646 QEMUClock *qemu_new_clock(int type)
648 QEMUClock *clock;
649 clock = qemu_mallocz(sizeof(QEMUClock));
650 if (!clock)
651 return NULL;
652 clock->type = type;
653 return clock;
656 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
658 QEMUTimer *ts;
660 ts = qemu_mallocz(sizeof(QEMUTimer));
661 ts->clock = clock;
662 ts->cb = cb;
663 ts->opaque = opaque;
664 return ts;
667 void qemu_free_timer(QEMUTimer *ts)
669 qemu_free(ts);
672 /* stop a timer, but do not dealloc it */
673 void qemu_del_timer(QEMUTimer *ts)
675 QEMUTimer **pt, *t;
677 /* NOTE: this code must be signal safe because
678 qemu_timer_expired() can be called from a signal. */
679 pt = &active_timers[ts->clock->type];
680 for(;;) {
681 t = *pt;
682 if (!t)
683 break;
684 if (t == ts) {
685 *pt = t->next;
686 break;
688 pt = &t->next;
692 /* modify the current timer so that it will be fired when current_time
693 >= expire_time. The corresponding callback will be called. */
694 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
696 QEMUTimer **pt, *t;
698 qemu_del_timer(ts);
700 /* add the timer in the sorted list */
701 /* NOTE: this code must be signal safe because
702 qemu_timer_expired() can be called from a signal. */
703 pt = &active_timers[ts->clock->type];
704 for(;;) {
705 t = *pt;
706 if (!t)
707 break;
708 if (t->expire_time > expire_time)
709 break;
710 pt = &t->next;
712 ts->expire_time = expire_time;
713 ts->next = *pt;
714 *pt = ts;
717 int qemu_timer_pending(QEMUTimer *ts)
719 QEMUTimer *t;
720 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
721 if (t == ts)
722 return 1;
724 return 0;
727 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
729 if (!timer_head)
730 return 0;
731 return (timer_head->expire_time <= current_time);
734 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
736 QEMUTimer *ts;
738 for(;;) {
739 ts = *ptimer_head;
740 if (!ts || ts->expire_time > current_time)
741 break;
742 /* remove timer from the list before calling the callback */
743 *ptimer_head = ts->next;
744 ts->next = NULL;
746 /* run the callback (the timer list can be modified) */
747 ts->cb(ts->opaque);
751 int64_t qemu_get_clock(QEMUClock *clock)
753 switch(clock->type) {
754 case QEMU_TIMER_REALTIME:
755 #ifdef _WIN32
756 return GetTickCount();
757 #else
759 struct tms tp;
761 /* Note that using gettimeofday() is not a good solution
762 for timers because its value change when the date is
763 modified. */
764 if (timer_freq == 100) {
765 return times(&tp) * 10;
766 } else {
767 return ((int64_t)times(&tp) * 1000) / timer_freq;
770 #endif
771 default:
772 case QEMU_TIMER_VIRTUAL:
773 return cpu_get_ticks();
777 /* save a timer */
778 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
780 uint64_t expire_time;
782 if (qemu_timer_pending(ts)) {
783 expire_time = ts->expire_time;
784 } else {
785 expire_time = -1;
787 qemu_put_be64(f, expire_time);
790 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
792 uint64_t expire_time;
794 expire_time = qemu_get_be64(f);
795 if (expire_time != -1) {
796 qemu_mod_timer(ts, expire_time);
797 } else {
798 qemu_del_timer(ts);
802 static void timer_save(QEMUFile *f, void *opaque)
804 if (cpu_ticks_enabled) {
805 hw_error("cannot save state if virtual timers are running");
807 qemu_put_be64s(f, &cpu_ticks_offset);
808 qemu_put_be64s(f, &ticks_per_sec);
811 static int timer_load(QEMUFile *f, void *opaque, int version_id)
813 if (version_id != 1)
814 return -EINVAL;
815 if (cpu_ticks_enabled) {
816 return -EINVAL;
818 qemu_get_be64s(f, &cpu_ticks_offset);
819 qemu_get_be64s(f, &ticks_per_sec);
820 return 0;
823 #ifdef _WIN32
824 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
825 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
826 #else
827 static void host_alarm_handler(int host_signum)
828 #endif
830 #if 0
831 #define DISP_FREQ 1000
833 static int64_t delta_min = INT64_MAX;
834 static int64_t delta_max, delta_cum, last_clock, delta, ti;
835 static int count;
836 ti = qemu_get_clock(vm_clock);
837 if (last_clock != 0) {
838 delta = ti - last_clock;
839 if (delta < delta_min)
840 delta_min = delta;
841 if (delta > delta_max)
842 delta_max = delta;
843 delta_cum += delta;
844 if (++count == DISP_FREQ) {
845 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
846 muldiv64(delta_min, 1000000, ticks_per_sec),
847 muldiv64(delta_max, 1000000, ticks_per_sec),
848 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
849 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
850 count = 0;
851 delta_min = INT64_MAX;
852 delta_max = 0;
853 delta_cum = 0;
856 last_clock = ti;
858 #endif
859 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
860 qemu_get_clock(vm_clock)) ||
861 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
862 qemu_get_clock(rt_clock))) {
863 /* stop the cpu because a timer occured */
864 cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
868 #ifndef _WIN32
870 #if defined(__linux__)
872 #define RTC_FREQ 1024
874 static int rtc_fd;
876 static int start_rtc_timer(void)
878 rtc_fd = open("/dev/rtc", O_RDONLY);
879 if (rtc_fd < 0)
880 return -1;
881 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
882 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
883 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
884 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
885 goto fail;
887 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
888 fail:
889 close(rtc_fd);
890 return -1;
892 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
893 return 0;
896 #else
898 static int start_rtc_timer(void)
900 return -1;
903 #endif /* !defined(__linux__) */
905 #endif /* !defined(_WIN32) */
907 static void init_timers(void)
909 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
910 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
912 #ifdef _WIN32
914 int count=0;
915 timerID = timeSetEvent(10, // interval (ms)
916 0, // resolution
917 host_alarm_handler, // function
918 (DWORD)&count, // user parameter
919 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
920 if( !timerID ) {
921 perror("failed timer alarm");
922 exit(1);
925 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
926 #else
928 struct sigaction act;
929 struct itimerval itv;
931 /* get times() syscall frequency */
932 timer_freq = sysconf(_SC_CLK_TCK);
934 /* timer signal */
935 sigfillset(&act.sa_mask);
936 act.sa_flags = 0;
937 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
938 act.sa_flags |= SA_ONSTACK;
939 #endif
940 act.sa_handler = host_alarm_handler;
941 sigaction(SIGALRM, &act, NULL);
943 itv.it_interval.tv_sec = 0;
944 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
945 itv.it_value.tv_sec = 0;
946 itv.it_value.tv_usec = 10 * 1000;
947 setitimer(ITIMER_REAL, &itv, NULL);
948 /* we probe the tick duration of the kernel to inform the user if
949 the emulated kernel requested a too high timer frequency */
950 getitimer(ITIMER_REAL, &itv);
952 #if defined(__linux__)
953 if (itv.it_interval.tv_usec > 1000) {
954 /* try to use /dev/rtc to have a faster timer */
955 if (start_rtc_timer() < 0)
956 goto use_itimer;
957 /* disable itimer */
958 itv.it_interval.tv_sec = 0;
959 itv.it_interval.tv_usec = 0;
960 itv.it_value.tv_sec = 0;
961 itv.it_value.tv_usec = 0;
962 setitimer(ITIMER_REAL, &itv, NULL);
964 /* use the RTC */
965 sigaction(SIGIO, &act, NULL);
966 fcntl(rtc_fd, F_SETFL, O_ASYNC);
967 fcntl(rtc_fd, F_SETOWN, getpid());
968 } else
969 #endif /* defined(__linux__) */
971 use_itimer:
972 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
973 PIT_FREQ) / 1000000;
976 #endif
979 void quit_timers(void)
981 #ifdef _WIN32
982 timeKillEvent(timerID);
983 #endif
986 /***********************************************************/
987 /* character device */
989 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
991 return s->chr_write(s, buf, len);
994 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
996 char buf[4096];
997 va_list ap;
998 va_start(ap, fmt);
999 vsnprintf(buf, sizeof(buf), fmt, ap);
1000 qemu_chr_write(s, buf, strlen(buf));
1001 va_end(ap);
1004 void qemu_chr_send_event(CharDriverState *s, int event)
1006 if (s->chr_send_event)
1007 s->chr_send_event(s, event);
1010 void qemu_chr_add_read_handler(CharDriverState *s,
1011 IOCanRWHandler *fd_can_read,
1012 IOReadHandler *fd_read, void *opaque)
1014 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1017 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1019 s->chr_event = chr_event;
1022 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1024 return len;
1027 static void null_chr_add_read_handler(CharDriverState *chr,
1028 IOCanRWHandler *fd_can_read,
1029 IOReadHandler *fd_read, void *opaque)
1033 CharDriverState *qemu_chr_open_null(void)
1035 CharDriverState *chr;
1037 chr = qemu_mallocz(sizeof(CharDriverState));
1038 if (!chr)
1039 return NULL;
1040 chr->chr_write = null_chr_write;
1041 chr->chr_add_read_handler = null_chr_add_read_handler;
1042 return chr;
1045 #ifndef _WIN32
1047 typedef struct {
1048 int fd_in, fd_out;
1049 /* for nographic stdio only */
1050 IOCanRWHandler *fd_can_read;
1051 IOReadHandler *fd_read;
1052 void *fd_opaque;
1053 } FDCharDriver;
1055 #define STDIO_MAX_CLIENTS 2
1057 static int stdio_nb_clients;
1058 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1060 static int unix_write(int fd, const uint8_t *buf, int len1)
1062 int ret, len;
1064 len = len1;
1065 while (len > 0) {
1066 ret = write(fd, buf, len);
1067 if (ret < 0) {
1068 if (errno != EINTR && errno != EAGAIN)
1069 return -1;
1070 } else if (ret == 0) {
1071 break;
1072 } else {
1073 buf += ret;
1074 len -= ret;
1077 return len1 - len;
1080 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1082 FDCharDriver *s = chr->opaque;
1083 return unix_write(s->fd_out, buf, len);
1086 static void fd_chr_add_read_handler(CharDriverState *chr,
1087 IOCanRWHandler *fd_can_read,
1088 IOReadHandler *fd_read, void *opaque)
1090 FDCharDriver *s = chr->opaque;
1092 if (nographic && s->fd_in == 0) {
1093 s->fd_can_read = fd_can_read;
1094 s->fd_read = fd_read;
1095 s->fd_opaque = opaque;
1096 } else {
1097 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1101 /* open a character device to a unix fd */
1102 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1104 CharDriverState *chr;
1105 FDCharDriver *s;
1107 chr = qemu_mallocz(sizeof(CharDriverState));
1108 if (!chr)
1109 return NULL;
1110 s = qemu_mallocz(sizeof(FDCharDriver));
1111 if (!s) {
1112 free(chr);
1113 return NULL;
1115 s->fd_in = fd_in;
1116 s->fd_out = fd_out;
1117 chr->opaque = s;
1118 chr->chr_write = fd_chr_write;
1119 chr->chr_add_read_handler = fd_chr_add_read_handler;
1120 return chr;
1123 /* for STDIO, we handle the case where several clients use it
1124 (nographic mode) */
1126 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1128 static int term_got_escape, client_index;
1130 void term_print_help(void)
1132 printf("\n"
1133 "C-a h print this help\n"
1134 "C-a x exit emulator\n"
1135 "C-a s save disk data back to file (if -snapshot)\n"
1136 "C-a b send break (magic sysrq)\n"
1137 "C-a c switch between console and monitor\n"
1138 "C-a C-a send C-a\n"
1142 /* called when a char is received */
1143 static void stdio_received_byte(int ch)
1145 if (term_got_escape) {
1146 term_got_escape = 0;
1147 switch(ch) {
1148 case 'h':
1149 term_print_help();
1150 break;
1151 case 'x':
1152 exit(0);
1153 break;
1154 case 's':
1156 int i;
1157 for (i = 0; i < MAX_DISKS; i++) {
1158 if (bs_table[i])
1159 bdrv_commit(bs_table[i]);
1162 break;
1163 case 'b':
1164 if (client_index < stdio_nb_clients) {
1165 CharDriverState *chr;
1166 FDCharDriver *s;
1168 chr = stdio_clients[client_index];
1169 s = chr->opaque;
1170 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1172 break;
1173 case 'c':
1174 client_index++;
1175 if (client_index >= stdio_nb_clients)
1176 client_index = 0;
1177 if (client_index == 0) {
1178 /* send a new line in the monitor to get the prompt */
1179 ch = '\r';
1180 goto send_char;
1182 break;
1183 case TERM_ESCAPE:
1184 goto send_char;
1186 } else if (ch == TERM_ESCAPE) {
1187 term_got_escape = 1;
1188 } else {
1189 send_char:
1190 if (client_index < stdio_nb_clients) {
1191 uint8_t buf[1];
1192 CharDriverState *chr;
1193 FDCharDriver *s;
1195 chr = stdio_clients[client_index];
1196 s = chr->opaque;
1197 buf[0] = ch;
1198 /* XXX: should queue the char if the device is not
1199 ready */
1200 if (s->fd_can_read(s->fd_opaque) > 0)
1201 s->fd_read(s->fd_opaque, buf, 1);
1206 static int stdio_can_read(void *opaque)
1208 /* XXX: not strictly correct */
1209 return 1;
1212 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1214 int i;
1215 for(i = 0; i < size; i++)
1216 stdio_received_byte(buf[i]);
1219 /* init terminal so that we can grab keys */
1220 static struct termios oldtty;
1221 static int old_fd0_flags;
1223 static void term_exit(void)
1225 tcsetattr (0, TCSANOW, &oldtty);
1226 fcntl(0, F_SETFL, old_fd0_flags);
1229 static void term_init(void)
1231 struct termios tty;
1233 tcgetattr (0, &tty);
1234 oldtty = tty;
1235 old_fd0_flags = fcntl(0, F_GETFL);
1237 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1238 |INLCR|IGNCR|ICRNL|IXON);
1239 tty.c_oflag |= OPOST;
1240 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1241 /* if graphical mode, we allow Ctrl-C handling */
1242 if (nographic)
1243 tty.c_lflag &= ~ISIG;
1244 tty.c_cflag &= ~(CSIZE|PARENB);
1245 tty.c_cflag |= CS8;
1246 tty.c_cc[VMIN] = 1;
1247 tty.c_cc[VTIME] = 0;
1249 tcsetattr (0, TCSANOW, &tty);
1251 atexit(term_exit);
1253 fcntl(0, F_SETFL, O_NONBLOCK);
1256 CharDriverState *qemu_chr_open_stdio(void)
1258 CharDriverState *chr;
1260 if (nographic) {
1261 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1262 return NULL;
1263 chr = qemu_chr_open_fd(0, 1);
1264 if (stdio_nb_clients == 0)
1265 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1266 client_index = stdio_nb_clients;
1267 } else {
1268 if (stdio_nb_clients != 0)
1269 return NULL;
1270 chr = qemu_chr_open_fd(0, 1);
1272 stdio_clients[stdio_nb_clients++] = chr;
1273 if (stdio_nb_clients == 1) {
1274 /* set the terminal in raw mode */
1275 term_init();
1277 return chr;
1280 #if defined(__linux__)
1281 CharDriverState *qemu_chr_open_pty(void)
1283 char slave_name[1024];
1284 int master_fd, slave_fd;
1286 /* Not satisfying */
1287 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1288 return NULL;
1290 fprintf(stderr, "char device redirected to %s\n", slave_name);
1291 return qemu_chr_open_fd(master_fd, master_fd);
1293 #else
1294 CharDriverState *qemu_chr_open_pty(void)
1296 return NULL;
1298 #endif
1300 #endif /* !defined(_WIN32) */
1302 CharDriverState *qemu_chr_open(const char *filename)
1304 if (!strcmp(filename, "vc")) {
1305 return text_console_init(&display_state);
1306 } else if (!strcmp(filename, "null")) {
1307 return qemu_chr_open_null();
1308 } else
1309 #ifndef _WIN32
1310 if (!strcmp(filename, "pty")) {
1311 return qemu_chr_open_pty();
1312 } else if (!strcmp(filename, "stdio")) {
1313 return qemu_chr_open_stdio();
1314 } else
1315 #endif
1317 return NULL;
1321 /***********************************************************/
1322 /* Linux network device redirectors */
1324 void hex_dump(FILE *f, const uint8_t *buf, int size)
1326 int len, i, j, c;
1328 for(i=0;i<size;i+=16) {
1329 len = size - i;
1330 if (len > 16)
1331 len = 16;
1332 fprintf(f, "%08x ", i);
1333 for(j=0;j<16;j++) {
1334 if (j < len)
1335 fprintf(f, " %02x", buf[i+j]);
1336 else
1337 fprintf(f, " ");
1339 fprintf(f, " ");
1340 for(j=0;j<len;j++) {
1341 c = buf[i+j];
1342 if (c < ' ' || c > '~')
1343 c = '.';
1344 fprintf(f, "%c", c);
1346 fprintf(f, "\n");
1350 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1352 nd->send_packet(nd, buf, size);
1355 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1356 IOReadHandler *fd_read, void *opaque)
1358 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1361 /* dummy network adapter */
1363 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1367 static void dummy_add_read_packet(NetDriverState *nd,
1368 IOCanRWHandler *fd_can_read,
1369 IOReadHandler *fd_read, void *opaque)
1373 static int net_dummy_init(NetDriverState *nd)
1375 nd->send_packet = dummy_send_packet;
1376 nd->add_read_packet = dummy_add_read_packet;
1377 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1378 return 0;
1381 #if defined(CONFIG_SLIRP)
1383 /* slirp network adapter */
1385 static void *slirp_fd_opaque;
1386 static IOCanRWHandler *slirp_fd_can_read;
1387 static IOReadHandler *slirp_fd_read;
1388 static int slirp_inited;
1390 int slirp_can_output(void)
1392 return slirp_fd_can_read(slirp_fd_opaque);
1395 void slirp_output(const uint8_t *pkt, int pkt_len)
1397 #if 0
1398 printf("output:\n");
1399 hex_dump(stdout, pkt, pkt_len);
1400 #endif
1401 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1404 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1406 #if 0
1407 printf("input:\n");
1408 hex_dump(stdout, buf, size);
1409 #endif
1410 slirp_input(buf, size);
1413 static void slirp_add_read_packet(NetDriverState *nd,
1414 IOCanRWHandler *fd_can_read,
1415 IOReadHandler *fd_read, void *opaque)
1417 slirp_fd_opaque = opaque;
1418 slirp_fd_can_read = fd_can_read;
1419 slirp_fd_read = fd_read;
1422 static int net_slirp_init(NetDriverState *nd)
1424 if (!slirp_inited) {
1425 slirp_inited = 1;
1426 slirp_init();
1428 nd->send_packet = slirp_send_packet;
1429 nd->add_read_packet = slirp_add_read_packet;
1430 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1431 return 0;
1434 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1436 const char *p, *p1;
1437 int len;
1438 p = *pp;
1439 p1 = strchr(p, sep);
1440 if (!p1)
1441 return -1;
1442 len = p1 - p;
1443 p1++;
1444 if (buf_size > 0) {
1445 if (len > buf_size - 1)
1446 len = buf_size - 1;
1447 memcpy(buf, p, len);
1448 buf[len] = '\0';
1450 *pp = p1;
1451 return 0;
1454 static void net_slirp_redir(const char *redir_str)
1456 int is_udp;
1457 char buf[256], *r;
1458 const char *p;
1459 struct in_addr guest_addr;
1460 int host_port, guest_port;
1462 if (!slirp_inited) {
1463 slirp_inited = 1;
1464 slirp_init();
1467 p = redir_str;
1468 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1469 goto fail;
1470 if (!strcmp(buf, "tcp")) {
1471 is_udp = 0;
1472 } else if (!strcmp(buf, "udp")) {
1473 is_udp = 1;
1474 } else {
1475 goto fail;
1478 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1479 goto fail;
1480 host_port = strtol(buf, &r, 0);
1481 if (r == buf)
1482 goto fail;
1484 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1485 goto fail;
1486 if (buf[0] == '\0') {
1487 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1489 if (!inet_aton(buf, &guest_addr))
1490 goto fail;
1492 guest_port = strtol(p, &r, 0);
1493 if (r == p)
1494 goto fail;
1496 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1497 fprintf(stderr, "qemu: could not set up redirection\n");
1498 exit(1);
1500 return;
1501 fail:
1502 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1503 exit(1);
1506 #ifndef _WIN32
1508 char smb_dir[1024];
1510 static void smb_exit(void)
1512 DIR *d;
1513 struct dirent *de;
1514 char filename[1024];
1516 /* erase all the files in the directory */
1517 d = opendir(smb_dir);
1518 for(;;) {
1519 de = readdir(d);
1520 if (!de)
1521 break;
1522 if (strcmp(de->d_name, ".") != 0 &&
1523 strcmp(de->d_name, "..") != 0) {
1524 snprintf(filename, sizeof(filename), "%s/%s",
1525 smb_dir, de->d_name);
1526 unlink(filename);
1529 closedir(d);
1530 rmdir(smb_dir);
1533 /* automatic user mode samba server configuration */
1534 void net_slirp_smb(const char *exported_dir)
1536 char smb_conf[1024];
1537 char smb_cmdline[1024];
1538 FILE *f;
1540 if (!slirp_inited) {
1541 slirp_inited = 1;
1542 slirp_init();
1545 /* XXX: better tmp dir construction */
1546 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1547 if (mkdir(smb_dir, 0700) < 0) {
1548 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1549 exit(1);
1551 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1553 f = fopen(smb_conf, "w");
1554 if (!f) {
1555 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1556 exit(1);
1558 fprintf(f,
1559 "[global]\n"
1560 "private dir=%s\n"
1561 "smb ports=0\n"
1562 "socket address=127.0.0.1\n"
1563 "pid directory=%s\n"
1564 "lock directory=%s\n"
1565 "log file=%s/log.smbd\n"
1566 "smb passwd file=%s/smbpasswd\n"
1567 "security = share\n"
1568 "[qemu]\n"
1569 "path=%s\n"
1570 "read only=no\n"
1571 "guest ok=yes\n",
1572 smb_dir,
1573 smb_dir,
1574 smb_dir,
1575 smb_dir,
1576 smb_dir,
1577 exported_dir
1579 fclose(f);
1580 atexit(smb_exit);
1582 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1583 smb_conf);
1585 slirp_add_exec(0, smb_cmdline, 4, 139);
1588 #endif /* !defined(_WIN32) */
1590 #endif /* CONFIG_SLIRP */
1592 #if !defined(_WIN32)
1593 #ifdef _BSD
1594 static int tun_open(char *ifname, int ifname_size)
1596 int fd;
1597 char *dev;
1598 struct stat s;
1600 fd = open("/dev/tap", O_RDWR);
1601 if (fd < 0) {
1602 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1603 return -1;
1606 fstat(fd, &s);
1607 dev = devname(s.st_rdev, S_IFCHR);
1608 pstrcpy(ifname, ifname_size, dev);
1610 fcntl(fd, F_SETFL, O_NONBLOCK);
1611 return fd;
1613 #else
1614 static int tun_open(char *ifname, int ifname_size)
1616 struct ifreq ifr;
1617 int fd, ret;
1619 fd = open("/dev/net/tun", O_RDWR);
1620 if (fd < 0) {
1621 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1622 return -1;
1624 memset(&ifr, 0, sizeof(ifr));
1625 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1626 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1627 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1628 if (ret != 0) {
1629 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1630 close(fd);
1631 return -1;
1633 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1634 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1635 fcntl(fd, F_SETFL, O_NONBLOCK);
1636 return fd;
1638 #endif
1640 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1642 write(nd->fd, buf, size);
1645 static void tun_add_read_packet(NetDriverState *nd,
1646 IOCanRWHandler *fd_can_read,
1647 IOReadHandler *fd_read, void *opaque)
1649 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1652 static int net_tun_init(NetDriverState *nd)
1654 int pid, status;
1655 char *args[3];
1656 char **parg;
1658 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1659 if (nd->fd < 0)
1660 return -1;
1662 /* try to launch network init script */
1663 pid = fork();
1664 if (pid >= 0) {
1665 if (pid == 0) {
1666 parg = args;
1667 *parg++ = network_script;
1668 *parg++ = nd->ifname;
1669 *parg++ = NULL;
1670 execv(network_script, args);
1671 exit(1);
1673 while (waitpid(pid, &status, 0) != pid);
1674 if (!WIFEXITED(status) ||
1675 WEXITSTATUS(status) != 0) {
1676 fprintf(stderr, "%s: could not launch network script\n",
1677 network_script);
1680 nd->send_packet = tun_send_packet;
1681 nd->add_read_packet = tun_add_read_packet;
1682 return 0;
1685 static int net_fd_init(NetDriverState *nd, int fd)
1687 nd->fd = fd;
1688 nd->send_packet = tun_send_packet;
1689 nd->add_read_packet = tun_add_read_packet;
1690 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1691 return 0;
1694 #endif /* !_WIN32 */
1696 /***********************************************************/
1697 /* pid file */
1699 static char *pid_filename;
1701 /* Remove PID file. Called on normal exit */
1703 static void remove_pidfile(void)
1705 unlink (pid_filename);
1708 static void create_pidfile(const char *filename)
1710 struct stat pidstat;
1711 FILE *f;
1713 /* Try to write our PID to the named file */
1714 if (stat(filename, &pidstat) < 0) {
1715 if (errno == ENOENT) {
1716 if ((f = fopen (filename, "w")) == NULL) {
1717 perror("Opening pidfile");
1718 exit(1);
1720 fprintf(f, "%d\n", getpid());
1721 fclose(f);
1722 pid_filename = qemu_strdup(filename);
1723 if (!pid_filename) {
1724 fprintf(stderr, "Could not save PID filename");
1725 exit(1);
1727 atexit(remove_pidfile);
1729 } else {
1730 fprintf(stderr, "%s already exists. Remove it and try again.\n",
1731 filename);
1732 exit(1);
1736 /***********************************************************/
1737 /* dumb display */
1739 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1743 static void dumb_resize(DisplayState *ds, int w, int h)
1747 static void dumb_refresh(DisplayState *ds)
1749 vga_update_display();
1752 void dumb_display_init(DisplayState *ds)
1754 ds->data = NULL;
1755 ds->linesize = 0;
1756 ds->depth = 0;
1757 ds->dpy_update = dumb_update;
1758 ds->dpy_resize = dumb_resize;
1759 ds->dpy_refresh = dumb_refresh;
1762 #if !defined(CONFIG_SOFTMMU)
1763 /***********************************************************/
1764 /* cpu signal handler */
1765 static void host_segv_handler(int host_signum, siginfo_t *info,
1766 void *puc)
1768 if (cpu_signal_handler(host_signum, info, puc))
1769 return;
1770 if (stdio_nb_clients > 0)
1771 term_exit();
1772 abort();
1774 #endif
1776 /***********************************************************/
1777 /* I/O handling */
1779 #define MAX_IO_HANDLERS 64
1781 typedef struct IOHandlerRecord {
1782 int fd;
1783 IOCanRWHandler *fd_can_read;
1784 IOReadHandler *fd_read;
1785 void *opaque;
1786 /* temporary data */
1787 struct pollfd *ufd;
1788 int max_size;
1789 struct IOHandlerRecord *next;
1790 } IOHandlerRecord;
1792 static IOHandlerRecord *first_io_handler;
1794 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1795 IOReadHandler *fd_read, void *opaque)
1797 IOHandlerRecord *ioh;
1799 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1800 if (!ioh)
1801 return -1;
1802 ioh->fd = fd;
1803 ioh->fd_can_read = fd_can_read;
1804 ioh->fd_read = fd_read;
1805 ioh->opaque = opaque;
1806 ioh->next = first_io_handler;
1807 first_io_handler = ioh;
1808 return 0;
1811 void qemu_del_fd_read_handler(int fd)
1813 IOHandlerRecord **pioh, *ioh;
1815 pioh = &first_io_handler;
1816 for(;;) {
1817 ioh = *pioh;
1818 if (ioh == NULL)
1819 break;
1820 if (ioh->fd == fd) {
1821 *pioh = ioh->next;
1822 break;
1824 pioh = &ioh->next;
1828 /***********************************************************/
1829 /* savevm/loadvm support */
1831 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1833 fwrite(buf, 1, size, f);
1836 void qemu_put_byte(QEMUFile *f, int v)
1838 fputc(v, f);
1841 void qemu_put_be16(QEMUFile *f, unsigned int v)
1843 qemu_put_byte(f, v >> 8);
1844 qemu_put_byte(f, v);
1847 void qemu_put_be32(QEMUFile *f, unsigned int v)
1849 qemu_put_byte(f, v >> 24);
1850 qemu_put_byte(f, v >> 16);
1851 qemu_put_byte(f, v >> 8);
1852 qemu_put_byte(f, v);
1855 void qemu_put_be64(QEMUFile *f, uint64_t v)
1857 qemu_put_be32(f, v >> 32);
1858 qemu_put_be32(f, v);
1861 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1863 return fread(buf, 1, size, f);
1866 int qemu_get_byte(QEMUFile *f)
1868 int v;
1869 v = fgetc(f);
1870 if (v == EOF)
1871 return 0;
1872 else
1873 return v;
1876 unsigned int qemu_get_be16(QEMUFile *f)
1878 unsigned int v;
1879 v = qemu_get_byte(f) << 8;
1880 v |= qemu_get_byte(f);
1881 return v;
1884 unsigned int qemu_get_be32(QEMUFile *f)
1886 unsigned int v;
1887 v = qemu_get_byte(f) << 24;
1888 v |= qemu_get_byte(f) << 16;
1889 v |= qemu_get_byte(f) << 8;
1890 v |= qemu_get_byte(f);
1891 return v;
1894 uint64_t qemu_get_be64(QEMUFile *f)
1896 uint64_t v;
1897 v = (uint64_t)qemu_get_be32(f) << 32;
1898 v |= qemu_get_be32(f);
1899 return v;
1902 int64_t qemu_ftell(QEMUFile *f)
1904 return ftell(f);
1907 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1909 if (fseek(f, pos, whence) < 0)
1910 return -1;
1911 return ftell(f);
1914 typedef struct SaveStateEntry {
1915 char idstr[256];
1916 int instance_id;
1917 int version_id;
1918 SaveStateHandler *save_state;
1919 LoadStateHandler *load_state;
1920 void *opaque;
1921 struct SaveStateEntry *next;
1922 } SaveStateEntry;
1924 static SaveStateEntry *first_se;
1926 int register_savevm(const char *idstr,
1927 int instance_id,
1928 int version_id,
1929 SaveStateHandler *save_state,
1930 LoadStateHandler *load_state,
1931 void *opaque)
1933 SaveStateEntry *se, **pse;
1935 se = qemu_malloc(sizeof(SaveStateEntry));
1936 if (!se)
1937 return -1;
1938 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1939 se->instance_id = instance_id;
1940 se->version_id = version_id;
1941 se->save_state = save_state;
1942 se->load_state = load_state;
1943 se->opaque = opaque;
1944 se->next = NULL;
1946 /* add at the end of list */
1947 pse = &first_se;
1948 while (*pse != NULL)
1949 pse = &(*pse)->next;
1950 *pse = se;
1951 return 0;
1954 #define QEMU_VM_FILE_MAGIC 0x5145564d
1955 #define QEMU_VM_FILE_VERSION 0x00000001
1957 int qemu_savevm(const char *filename)
1959 SaveStateEntry *se;
1960 QEMUFile *f;
1961 int len, len_pos, cur_pos, saved_vm_running, ret;
1963 saved_vm_running = vm_running;
1964 vm_stop(0);
1966 f = fopen(filename, "wb");
1967 if (!f) {
1968 ret = -1;
1969 goto the_end;
1972 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1973 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1975 for(se = first_se; se != NULL; se = se->next) {
1976 /* ID string */
1977 len = strlen(se->idstr);
1978 qemu_put_byte(f, len);
1979 qemu_put_buffer(f, se->idstr, len);
1981 qemu_put_be32(f, se->instance_id);
1982 qemu_put_be32(f, se->version_id);
1984 /* record size: filled later */
1985 len_pos = ftell(f);
1986 qemu_put_be32(f, 0);
1988 se->save_state(f, se->opaque);
1990 /* fill record size */
1991 cur_pos = ftell(f);
1992 len = ftell(f) - len_pos - 4;
1993 fseek(f, len_pos, SEEK_SET);
1994 qemu_put_be32(f, len);
1995 fseek(f, cur_pos, SEEK_SET);
1998 fclose(f);
1999 ret = 0;
2000 the_end:
2001 if (saved_vm_running)
2002 vm_start();
2003 return ret;
2006 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2008 SaveStateEntry *se;
2010 for(se = first_se; se != NULL; se = se->next) {
2011 if (!strcmp(se->idstr, idstr) &&
2012 instance_id == se->instance_id)
2013 return se;
2015 return NULL;
2018 int qemu_loadvm(const char *filename)
2020 SaveStateEntry *se;
2021 QEMUFile *f;
2022 int len, cur_pos, ret, instance_id, record_len, version_id;
2023 int saved_vm_running;
2024 unsigned int v;
2025 char idstr[256];
2027 saved_vm_running = vm_running;
2028 vm_stop(0);
2030 f = fopen(filename, "rb");
2031 if (!f) {
2032 ret = -1;
2033 goto the_end;
2036 v = qemu_get_be32(f);
2037 if (v != QEMU_VM_FILE_MAGIC)
2038 goto fail;
2039 v = qemu_get_be32(f);
2040 if (v != QEMU_VM_FILE_VERSION) {
2041 fail:
2042 fclose(f);
2043 ret = -1;
2044 goto the_end;
2046 for(;;) {
2047 #if defined (DO_TB_FLUSH)
2048 tb_flush(global_env);
2049 #endif
2050 len = qemu_get_byte(f);
2051 if (feof(f))
2052 break;
2053 qemu_get_buffer(f, idstr, len);
2054 idstr[len] = '\0';
2055 instance_id = qemu_get_be32(f);
2056 version_id = qemu_get_be32(f);
2057 record_len = qemu_get_be32(f);
2058 #if 0
2059 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2060 idstr, instance_id, version_id, record_len);
2061 #endif
2062 cur_pos = ftell(f);
2063 se = find_se(idstr, instance_id);
2064 if (!se) {
2065 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
2066 instance_id, idstr);
2067 } else {
2068 ret = se->load_state(f, se->opaque, version_id);
2069 if (ret < 0) {
2070 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2071 instance_id, idstr);
2074 /* always seek to exact end of record */
2075 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2077 fclose(f);
2078 ret = 0;
2079 the_end:
2080 if (saved_vm_running)
2081 vm_start();
2082 return ret;
2085 /***********************************************************/
2086 /* cpu save/restore */
2088 #if defined(TARGET_I386)
2090 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2092 qemu_put_be32(f, dt->selector);
2093 qemu_put_betl(f, dt->base);
2094 qemu_put_be32(f, dt->limit);
2095 qemu_put_be32(f, dt->flags);
2098 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2100 dt->selector = qemu_get_be32(f);
2101 dt->base = qemu_get_betl(f);
2102 dt->limit = qemu_get_be32(f);
2103 dt->flags = qemu_get_be32(f);
2106 void cpu_save(QEMUFile *f, void *opaque)
2108 CPUState *env = opaque;
2109 uint16_t fptag, fpus, fpuc, fpregs_format;
2110 uint32_t hflags;
2111 int i;
2113 for(i = 0; i < CPU_NB_REGS; i++)
2114 qemu_put_betls(f, &env->regs[i]);
2115 qemu_put_betls(f, &env->eip);
2116 qemu_put_betls(f, &env->eflags);
2117 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2118 qemu_put_be32s(f, &hflags);
2120 /* FPU */
2121 fpuc = env->fpuc;
2122 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2123 fptag = 0;
2124 for(i = 0; i < 8; i++) {
2125 fptag |= ((!env->fptags[i]) << i);
2128 qemu_put_be16s(f, &fpuc);
2129 qemu_put_be16s(f, &fpus);
2130 qemu_put_be16s(f, &fptag);
2132 #ifdef USE_X86LDOUBLE
2133 fpregs_format = 0;
2134 #else
2135 fpregs_format = 1;
2136 #endif
2137 qemu_put_be16s(f, &fpregs_format);
2139 for(i = 0; i < 8; i++) {
2140 #ifdef USE_X86LDOUBLE
2142 uint64_t mant;
2143 uint16_t exp;
2144 /* we save the real CPU data (in case of MMX usage only 'mant'
2145 contains the MMX register */
2146 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
2147 qemu_put_be64(f, mant);
2148 qemu_put_be16(f, exp);
2150 #else
2151 /* if we use doubles for float emulation, we save the doubles to
2152 avoid losing information in case of MMX usage. It can give
2153 problems if the image is restored on a CPU where long
2154 doubles are used instead. */
2155 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
2156 #endif
2159 for(i = 0; i < 6; i++)
2160 cpu_put_seg(f, &env->segs[i]);
2161 cpu_put_seg(f, &env->ldt);
2162 cpu_put_seg(f, &env->tr);
2163 cpu_put_seg(f, &env->gdt);
2164 cpu_put_seg(f, &env->idt);
2166 qemu_put_be32s(f, &env->sysenter_cs);
2167 qemu_put_be32s(f, &env->sysenter_esp);
2168 qemu_put_be32s(f, &env->sysenter_eip);
2170 qemu_put_betls(f, &env->cr[0]);
2171 qemu_put_betls(f, &env->cr[2]);
2172 qemu_put_betls(f, &env->cr[3]);
2173 qemu_put_betls(f, &env->cr[4]);
2175 for(i = 0; i < 8; i++)
2176 qemu_put_betls(f, &env->dr[i]);
2178 /* MMU */
2179 qemu_put_be32s(f, &env->a20_mask);
2181 /* XMM */
2182 qemu_put_be32s(f, &env->mxcsr);
2183 for(i = 0; i < CPU_NB_REGS; i++) {
2184 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2185 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2188 #ifdef TARGET_X86_64
2189 qemu_put_be64s(f, &env->efer);
2190 qemu_put_be64s(f, &env->star);
2191 qemu_put_be64s(f, &env->lstar);
2192 qemu_put_be64s(f, &env->cstar);
2193 qemu_put_be64s(f, &env->fmask);
2194 qemu_put_be64s(f, &env->kernelgsbase);
2195 #endif
2198 #ifdef USE_X86LDOUBLE
2199 /* XXX: add that in a FPU generic layer */
2200 union x86_longdouble {
2201 uint64_t mant;
2202 uint16_t exp;
2205 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
2206 #define EXPBIAS1 1023
2207 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
2208 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
2210 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
2212 int e;
2213 /* mantissa */
2214 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
2215 /* exponent + sign */
2216 e = EXPD1(temp) - EXPBIAS1 + 16383;
2217 e |= SIGND1(temp) >> 16;
2218 p->exp = e;
2220 #endif
2222 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2224 CPUState *env = opaque;
2225 int i, guess_mmx;
2226 uint32_t hflags;
2227 uint16_t fpus, fpuc, fptag, fpregs_format;
2229 if (version_id != 3)
2230 return -EINVAL;
2231 for(i = 0; i < CPU_NB_REGS; i++)
2232 qemu_get_betls(f, &env->regs[i]);
2233 qemu_get_betls(f, &env->eip);
2234 qemu_get_betls(f, &env->eflags);
2235 qemu_get_be32s(f, &hflags);
2237 qemu_get_be16s(f, &fpuc);
2238 qemu_get_be16s(f, &fpus);
2239 qemu_get_be16s(f, &fptag);
2240 qemu_get_be16s(f, &fpregs_format);
2242 /* NOTE: we cannot always restore the FPU state if the image come
2243 from a host with a different 'USE_X86LDOUBLE' define. We guess
2244 if we are in an MMX state to restore correctly in that case. */
2245 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
2246 for(i = 0; i < 8; i++) {
2247 uint64_t mant;
2248 uint16_t exp;
2250 switch(fpregs_format) {
2251 case 0:
2252 mant = qemu_get_be64(f);
2253 exp = qemu_get_be16(f);
2254 #ifdef USE_X86LDOUBLE
2255 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2256 #else
2257 /* difficult case */
2258 if (guess_mmx)
2259 env->fpregs[i].mmx.MMX_Q(0) = mant;
2260 else
2261 env->fpregs[i].d = cpu_set_fp80(mant, exp);
2262 #endif
2263 break;
2264 case 1:
2265 mant = qemu_get_be64(f);
2266 #ifdef USE_X86LDOUBLE
2268 union x86_longdouble *p;
2269 /* difficult case */
2270 p = (void *)&env->fpregs[i];
2271 if (guess_mmx) {
2272 p->mant = mant;
2273 p->exp = 0xffff;
2274 } else {
2275 fp64_to_fp80(p, mant);
2278 #else
2279 env->fpregs[i].mmx.MMX_Q(0) = mant;
2280 #endif
2281 break;
2282 default:
2283 return -EINVAL;
2287 env->fpuc = fpuc;
2288 /* XXX: restore FPU round state */
2289 env->fpstt = (fpus >> 11) & 7;
2290 env->fpus = fpus & ~0x3800;
2291 fptag ^= 0xff;
2292 for(i = 0; i < 8; i++) {
2293 env->fptags[i] = (fptag >> i) & 1;
2296 for(i = 0; i < 6; i++)
2297 cpu_get_seg(f, &env->segs[i]);
2298 cpu_get_seg(f, &env->ldt);
2299 cpu_get_seg(f, &env->tr);
2300 cpu_get_seg(f, &env->gdt);
2301 cpu_get_seg(f, &env->idt);
2303 qemu_get_be32s(f, &env->sysenter_cs);
2304 qemu_get_be32s(f, &env->sysenter_esp);
2305 qemu_get_be32s(f, &env->sysenter_eip);
2307 qemu_get_betls(f, &env->cr[0]);
2308 qemu_get_betls(f, &env->cr[2]);
2309 qemu_get_betls(f, &env->cr[3]);
2310 qemu_get_betls(f, &env->cr[4]);
2312 for(i = 0; i < 8; i++)
2313 qemu_get_betls(f, &env->dr[i]);
2315 /* MMU */
2316 qemu_get_be32s(f, &env->a20_mask);
2318 qemu_get_be32s(f, &env->mxcsr);
2319 for(i = 0; i < CPU_NB_REGS; i++) {
2320 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2321 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2324 #ifdef TARGET_X86_64
2325 qemu_get_be64s(f, &env->efer);
2326 qemu_get_be64s(f, &env->star);
2327 qemu_get_be64s(f, &env->lstar);
2328 qemu_get_be64s(f, &env->cstar);
2329 qemu_get_be64s(f, &env->fmask);
2330 qemu_get_be64s(f, &env->kernelgsbase);
2331 #endif
2333 /* XXX: compute hflags from scratch, except for CPL and IIF */
2334 env->hflags = hflags;
2335 tlb_flush(env, 1);
2336 return 0;
2339 #elif defined(TARGET_PPC)
2340 void cpu_save(QEMUFile *f, void *opaque)
2344 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2346 return 0;
2348 #elif defined(TARGET_SPARC)
2349 void cpu_save(QEMUFile *f, void *opaque)
2351 CPUState *env = opaque;
2352 int i;
2353 uint32_t tmp;
2355 for(i = 0; i < 8; i++)
2356 qemu_put_betls(f, &env->gregs[i]);
2357 for(i = 0; i < NWINDOWS * 16; i++)
2358 qemu_put_betls(f, &env->regbase[i]);
2360 /* FPU */
2361 for(i = 0; i < TARGET_FPREGS; i++) {
2362 union {
2363 TARGET_FPREG_T f;
2364 target_ulong i;
2365 } u;
2366 u.f = env->fpr[i];
2367 qemu_put_betl(f, u.i);
2370 qemu_put_betls(f, &env->pc);
2371 qemu_put_betls(f, &env->npc);
2372 qemu_put_betls(f, &env->y);
2373 tmp = GET_PSR(env);
2374 qemu_put_be32(f, tmp);
2375 qemu_put_be32s(f, &env->fsr);
2376 qemu_put_be32s(f, &env->wim);
2377 qemu_put_be32s(f, &env->tbr);
2378 /* MMU */
2379 for(i = 0; i < 16; i++)
2380 qemu_put_be32s(f, &env->mmuregs[i]);
2383 int cpu_load(QEMUFile *f, void *opaque, int version_id)
2385 CPUState *env = opaque;
2386 int i;
2387 uint32_t tmp;
2389 for(i = 0; i < 8; i++)
2390 qemu_get_betls(f, &env->gregs[i]);
2391 for(i = 0; i < NWINDOWS * 16; i++)
2392 qemu_get_betls(f, &env->regbase[i]);
2394 /* FPU */
2395 for(i = 0; i < TARGET_FPREGS; i++) {
2396 union {
2397 TARGET_FPREG_T f;
2398 target_ulong i;
2399 } u;
2400 u.i = qemu_get_betl(f);
2401 env->fpr[i] = u.f;
2404 qemu_get_betls(f, &env->pc);
2405 qemu_get_betls(f, &env->npc);
2406 qemu_get_betls(f, &env->y);
2407 tmp = qemu_get_be32(f);
2408 env->cwp = 0; /* needed to ensure that the wrapping registers are
2409 correctly updated */
2410 PUT_PSR(env, tmp);
2411 qemu_get_be32s(f, &env->fsr);
2412 qemu_get_be32s(f, &env->wim);
2413 qemu_get_be32s(f, &env->tbr);
2414 /* MMU */
2415 for(i = 0; i < 16; i++)
2416 qemu_get_be32s(f, &env->mmuregs[i]);
2418 tlb_flush(env, 1);
2419 return 0;
2421 #else
2423 #warning No CPU save/restore functions
2425 #endif
2427 /***********************************************************/
2428 /* ram save/restore */
2430 /* we just avoid storing empty pages */
2431 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2433 int i, v;
2435 v = buf[0];
2436 for(i = 1; i < len; i++) {
2437 if (buf[i] != v)
2438 goto normal_save;
2440 qemu_put_byte(f, 1);
2441 qemu_put_byte(f, v);
2442 return;
2443 normal_save:
2444 qemu_put_byte(f, 0);
2445 qemu_put_buffer(f, buf, len);
2448 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2450 int v;
2452 v = qemu_get_byte(f);
2453 switch(v) {
2454 case 0:
2455 if (qemu_get_buffer(f, buf, len) != len)
2456 return -EIO;
2457 break;
2458 case 1:
2459 v = qemu_get_byte(f);
2460 memset(buf, v, len);
2461 break;
2462 default:
2463 return -EINVAL;
2465 return 0;
2468 static void ram_save(QEMUFile *f, void *opaque)
2470 int i;
2471 qemu_put_be32(f, phys_ram_size);
2472 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2473 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2477 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2479 int i, ret;
2481 if (version_id != 1)
2482 return -EINVAL;
2483 if (qemu_get_be32(f) != phys_ram_size)
2484 return -EINVAL;
2485 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2486 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2487 if (ret)
2488 return ret;
2490 return 0;
2493 /***********************************************************/
2494 /* main execution loop */
2496 void gui_update(void *opaque)
2498 display_state.dpy_refresh(&display_state);
2499 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2502 /* XXX: support several handlers */
2503 VMStopHandler *vm_stop_cb;
2504 VMStopHandler *vm_stop_opaque;
2506 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2508 vm_stop_cb = cb;
2509 vm_stop_opaque = opaque;
2510 return 0;
2513 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2515 vm_stop_cb = NULL;
2518 void vm_start(void)
2520 if (!vm_running) {
2521 cpu_enable_ticks();
2522 vm_running = 1;
2526 void vm_stop(int reason)
2528 if (vm_running) {
2529 cpu_disable_ticks();
2530 vm_running = 0;
2531 if (reason != 0) {
2532 if (vm_stop_cb) {
2533 vm_stop_cb(vm_stop_opaque, reason);
2539 /* reset/shutdown handler */
2541 typedef struct QEMUResetEntry {
2542 QEMUResetHandler *func;
2543 void *opaque;
2544 struct QEMUResetEntry *next;
2545 } QEMUResetEntry;
2547 static QEMUResetEntry *first_reset_entry;
2548 static int reset_requested;
2549 static int shutdown_requested;
2551 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2553 QEMUResetEntry **pre, *re;
2555 pre = &first_reset_entry;
2556 while (*pre != NULL)
2557 pre = &(*pre)->next;
2558 re = qemu_mallocz(sizeof(QEMUResetEntry));
2559 re->func = func;
2560 re->opaque = opaque;
2561 re->next = NULL;
2562 *pre = re;
2565 void qemu_system_reset(void)
2567 QEMUResetEntry *re;
2569 /* reset all devices */
2570 for(re = first_reset_entry; re != NULL; re = re->next) {
2571 re->func(re->opaque);
2575 void qemu_system_reset_request(void)
2577 reset_requested = 1;
2578 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2581 void qemu_system_shutdown_request(void)
2583 shutdown_requested = 1;
2584 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2587 static void main_cpu_reset(void *opaque)
2589 #if defined(TARGET_I386) || defined(TARGET_SPARC)
2590 CPUState *env = opaque;
2591 cpu_reset(env);
2592 #endif
2595 void main_loop_wait(int timeout)
2597 #ifndef _WIN32
2598 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2599 IOHandlerRecord *ioh, *ioh_next;
2600 uint8_t buf[4096];
2601 int n, max_size;
2602 #endif
2603 int ret;
2605 #ifdef _WIN32
2606 if (timeout > 0)
2607 Sleep(timeout);
2608 #else
2609 /* poll any events */
2610 /* XXX: separate device handlers from system ones */
2611 pf = ufds;
2612 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2613 if (!ioh->fd_can_read) {
2614 max_size = 0;
2615 pf->fd = ioh->fd;
2616 pf->events = POLLIN;
2617 ioh->ufd = pf;
2618 pf++;
2619 } else {
2620 max_size = ioh->fd_can_read(ioh->opaque);
2621 if (max_size > 0) {
2622 if (max_size > sizeof(buf))
2623 max_size = sizeof(buf);
2624 pf->fd = ioh->fd;
2625 pf->events = POLLIN;
2626 ioh->ufd = pf;
2627 pf++;
2628 } else {
2629 ioh->ufd = NULL;
2632 ioh->max_size = max_size;
2635 ret = poll(ufds, pf - ufds, timeout);
2636 if (ret > 0) {
2637 /* XXX: better handling of removal */
2638 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2639 ioh_next = ioh->next;
2640 pf = ioh->ufd;
2641 if (pf) {
2642 if (pf->revents & POLLIN) {
2643 if (ioh->max_size == 0) {
2644 /* just a read event */
2645 ioh->fd_read(ioh->opaque, NULL, 0);
2646 } else {
2647 n = read(ioh->fd, buf, ioh->max_size);
2648 if (n >= 0) {
2649 ioh->fd_read(ioh->opaque, buf, n);
2650 } else if (errno != EAGAIN) {
2651 ioh->fd_read(ioh->opaque, NULL, -errno);
2658 #endif /* !defined(_WIN32) */
2659 #if defined(CONFIG_SLIRP)
2660 /* XXX: merge with poll() */
2661 if (slirp_inited) {
2662 fd_set rfds, wfds, xfds;
2663 int nfds;
2664 struct timeval tv;
2666 nfds = -1;
2667 FD_ZERO(&rfds);
2668 FD_ZERO(&wfds);
2669 FD_ZERO(&xfds);
2670 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2671 tv.tv_sec = 0;
2672 tv.tv_usec = 0;
2673 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2674 if (ret >= 0) {
2675 slirp_select_poll(&rfds, &wfds, &xfds);
2678 #endif
2680 if (vm_running) {
2681 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2682 qemu_get_clock(vm_clock));
2683 /* run dma transfers, if any */
2684 DMA_run();
2687 /* real time timers */
2688 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2689 qemu_get_clock(rt_clock));
2692 int main_loop(void)
2694 int ret, timeout;
2695 CPUState *env = global_env;
2697 for(;;) {
2698 if (vm_running) {
2699 ret = cpu_exec(env);
2700 if (shutdown_requested) {
2701 ret = EXCP_INTERRUPT;
2702 break;
2704 if (reset_requested) {
2705 reset_requested = 0;
2706 qemu_system_reset();
2707 ret = EXCP_INTERRUPT;
2709 if (ret == EXCP_DEBUG) {
2710 vm_stop(EXCP_DEBUG);
2712 /* if hlt instruction, we wait until the next IRQ */
2713 /* XXX: use timeout computed from timers */
2714 if (ret == EXCP_HLT)
2715 timeout = 10;
2716 else
2717 timeout = 0;
2718 } else {
2719 timeout = 10;
2721 main_loop_wait(timeout);
2723 cpu_disable_ticks();
2724 return ret;
2727 void help(void)
2729 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2730 "usage: %s [options] [disk_image]\n"
2731 "\n"
2732 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2733 "\n"
2734 "Standard options:\n"
2735 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2736 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2737 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2738 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2739 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2740 "-snapshot write to temporary files instead of disk image files\n"
2741 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2742 "-nographic disable graphical output and redirect serial I/Os to console\n"
2743 #ifndef _WIN32
2744 "-k language use keyboard layout (for example \"fr\" for French)\n"
2745 #endif
2746 "-enable-audio enable audio support\n"
2747 "-localtime set the real time clock to local time [default=utc]\n"
2748 "-full-screen start in full screen\n"
2749 #ifdef TARGET_PPC
2750 "-prep Simulate a PREP system (default is PowerMAC)\n"
2751 #endif
2752 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2753 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
2754 #endif
2755 "\n"
2756 "Network options:\n"
2757 "-nics n simulate 'n' network cards [default=1]\n"
2758 "-macaddr addr set the mac address of the first interface\n"
2759 "-n script set tap/tun network init script [default=%s]\n"
2760 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2761 #ifdef CONFIG_SLIRP
2762 "-user-net use user mode network stack [default if no tap/tun script]\n"
2763 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2764 #ifndef _WIN32
2765 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2766 #endif
2767 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2768 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2769 #endif
2770 "-dummy-net use dummy network stack\n"
2771 "\n"
2772 "Linux boot specific:\n"
2773 "-kernel bzImage use 'bzImage' as kernel image\n"
2774 "-append cmdline use 'cmdline' as kernel command line\n"
2775 "-initrd file use 'file' as initial ram disk\n"
2776 "\n"
2777 "Debug/Expert options:\n"
2778 "-monitor dev redirect the monitor to char device 'dev'\n"
2779 "-serial dev redirect the serial port to char device 'dev'\n"
2780 "-parallel dev redirect the parallel port to char device 'dev'\n"
2781 "-pidfile file Write PID to 'file'\n"
2782 "-S freeze CPU at startup (use 'c' to start execution)\n"
2783 "-s wait gdb connection to port %d\n"
2784 "-p port change gdb connection port\n"
2785 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
2786 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
2787 " translation (t=none or lba) (usually qemu can guess them)\n"
2788 "-L path set the directory for the BIOS and VGA BIOS\n"
2789 #ifdef USE_KQEMU
2790 "-no-kqemu disable KQEMU kernel module usage\n"
2791 #endif
2792 #ifdef USE_CODE_COPY
2793 "-no-code-copy disable code copy acceleration\n"
2794 #endif
2795 #ifdef TARGET_I386
2796 "-isa simulate an ISA-only system (default is PCI system)\n"
2797 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2798 " (default is CL-GD5446 PCI VGA)\n"
2799 #endif
2800 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2801 "\n"
2802 "During emulation, the following keys are useful:\n"
2803 "ctrl-alt-f toggle full screen\n"
2804 "ctrl-alt-n switch to virtual console 'n'\n"
2805 "ctrl-alt toggle mouse and keyboard grab\n"
2806 "\n"
2807 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2809 #ifdef CONFIG_SOFTMMU
2810 "qemu",
2811 #else
2812 "qemu-fast",
2813 #endif
2814 DEFAULT_RAM_SIZE,
2815 DEFAULT_NETWORK_SCRIPT,
2816 DEFAULT_GDBSTUB_PORT,
2817 "/tmp/qemu.log");
2818 #ifndef CONFIG_SOFTMMU
2819 printf("\n"
2820 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2821 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2822 "PC emulation.\n");
2823 #endif
2824 exit(1);
2827 #define HAS_ARG 0x0001
2829 enum {
2830 QEMU_OPTION_h,
2832 QEMU_OPTION_fda,
2833 QEMU_OPTION_fdb,
2834 QEMU_OPTION_hda,
2835 QEMU_OPTION_hdb,
2836 QEMU_OPTION_hdc,
2837 QEMU_OPTION_hdd,
2838 QEMU_OPTION_cdrom,
2839 QEMU_OPTION_boot,
2840 QEMU_OPTION_snapshot,
2841 QEMU_OPTION_m,
2842 QEMU_OPTION_nographic,
2843 QEMU_OPTION_enable_audio,
2845 QEMU_OPTION_nics,
2846 QEMU_OPTION_macaddr,
2847 QEMU_OPTION_n,
2848 QEMU_OPTION_tun_fd,
2849 QEMU_OPTION_user_net,
2850 QEMU_OPTION_tftp,
2851 QEMU_OPTION_smb,
2852 QEMU_OPTION_redir,
2853 QEMU_OPTION_dummy_net,
2855 QEMU_OPTION_kernel,
2856 QEMU_OPTION_append,
2857 QEMU_OPTION_initrd,
2859 QEMU_OPTION_S,
2860 QEMU_OPTION_s,
2861 QEMU_OPTION_p,
2862 QEMU_OPTION_d,
2863 QEMU_OPTION_hdachs,
2864 QEMU_OPTION_L,
2865 QEMU_OPTION_no_code_copy,
2866 QEMU_OPTION_pci,
2867 QEMU_OPTION_isa,
2868 QEMU_OPTION_prep,
2869 QEMU_OPTION_k,
2870 QEMU_OPTION_localtime,
2871 QEMU_OPTION_cirrusvga,
2872 QEMU_OPTION_g,
2873 QEMU_OPTION_std_vga,
2874 QEMU_OPTION_monitor,
2875 QEMU_OPTION_serial,
2876 QEMU_OPTION_parallel,
2877 QEMU_OPTION_loadvm,
2878 QEMU_OPTION_full_screen,
2879 QEMU_OPTION_pidfile,
2880 QEMU_OPTION_no_kqemu,
2883 typedef struct QEMUOption {
2884 const char *name;
2885 int flags;
2886 int index;
2887 } QEMUOption;
2889 const QEMUOption qemu_options[] = {
2890 { "h", 0, QEMU_OPTION_h },
2892 { "fda", HAS_ARG, QEMU_OPTION_fda },
2893 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2894 { "hda", HAS_ARG, QEMU_OPTION_hda },
2895 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2896 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2897 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2898 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2899 { "boot", HAS_ARG, QEMU_OPTION_boot },
2900 { "snapshot", 0, QEMU_OPTION_snapshot },
2901 { "m", HAS_ARG, QEMU_OPTION_m },
2902 { "nographic", 0, QEMU_OPTION_nographic },
2903 { "k", HAS_ARG, QEMU_OPTION_k },
2904 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2906 { "nics", HAS_ARG, QEMU_OPTION_nics},
2907 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2908 { "n", HAS_ARG, QEMU_OPTION_n },
2909 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2910 #ifdef CONFIG_SLIRP
2911 { "user-net", 0, QEMU_OPTION_user_net },
2912 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2913 #ifndef _WIN32
2914 { "smb", HAS_ARG, QEMU_OPTION_smb },
2915 #endif
2916 { "redir", HAS_ARG, QEMU_OPTION_redir },
2917 #endif
2918 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2920 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2921 { "append", HAS_ARG, QEMU_OPTION_append },
2922 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2924 { "S", 0, QEMU_OPTION_S },
2925 { "s", 0, QEMU_OPTION_s },
2926 { "p", HAS_ARG, QEMU_OPTION_p },
2927 { "d", HAS_ARG, QEMU_OPTION_d },
2928 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2929 { "L", HAS_ARG, QEMU_OPTION_L },
2930 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2931 #ifdef USE_KQEMU
2932 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
2933 #endif
2934 #ifdef TARGET_PPC
2935 { "prep", 0, QEMU_OPTION_prep },
2936 #endif
2937 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
2938 { "g", 1, QEMU_OPTION_g },
2939 #endif
2940 { "localtime", 0, QEMU_OPTION_localtime },
2941 { "isa", 0, QEMU_OPTION_isa },
2942 { "std-vga", 0, QEMU_OPTION_std_vga },
2943 { "monitor", 1, QEMU_OPTION_monitor },
2944 { "serial", 1, QEMU_OPTION_serial },
2945 { "parallel", 1, QEMU_OPTION_parallel },
2946 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2947 { "full-screen", 0, QEMU_OPTION_full_screen },
2948 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
2950 /* temporary options */
2951 { "pci", 0, QEMU_OPTION_pci },
2952 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2953 { NULL },
2956 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2958 /* this stack is only used during signal handling */
2959 #define SIGNAL_STACK_SIZE 32768
2961 static uint8_t *signal_stack;
2963 #endif
2965 /* password input */
2967 static BlockDriverState *get_bdrv(int index)
2969 BlockDriverState *bs;
2971 if (index < 4) {
2972 bs = bs_table[index];
2973 } else if (index < 6) {
2974 bs = fd_table[index - 4];
2975 } else {
2976 bs = NULL;
2978 return bs;
2981 static void read_passwords(void)
2983 BlockDriverState *bs;
2984 int i, j;
2985 char password[256];
2987 for(i = 0; i < 6; i++) {
2988 bs = get_bdrv(i);
2989 if (bs && bdrv_is_encrypted(bs)) {
2990 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2991 for(j = 0; j < 3; j++) {
2992 monitor_readline("Password: ",
2993 1, password, sizeof(password));
2994 if (bdrv_set_key(bs, password) == 0)
2995 break;
2996 term_printf("invalid password\n");
3002 #define NET_IF_TUN 0
3003 #define NET_IF_USER 1
3004 #define NET_IF_DUMMY 2
3006 int main(int argc, char **argv)
3008 #ifdef CONFIG_GDBSTUB
3009 int use_gdbstub, gdbstub_port;
3010 #endif
3011 int i, has_cdrom;
3012 int snapshot, linux_boot;
3013 CPUState *env;
3014 const char *initrd_filename;
3015 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3016 const char *kernel_filename, *kernel_cmdline;
3017 DisplayState *ds = &display_state;
3018 int cyls, heads, secs, translation;
3019 int start_emulation = 1;
3020 uint8_t macaddr[6];
3021 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
3022 int optind;
3023 const char *r, *optarg;
3024 CharDriverState *monitor_hd;
3025 char monitor_device[128];
3026 char serial_devices[MAX_SERIAL_PORTS][128];
3027 int serial_device_index;
3028 char parallel_devices[MAX_PARALLEL_PORTS][128];
3029 int parallel_device_index;
3030 const char *loadvm = NULL;
3032 #if !defined(CONFIG_SOFTMMU)
3033 /* we never want that malloc() uses mmap() */
3034 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3035 #endif
3036 initrd_filename = NULL;
3037 for(i = 0; i < MAX_FD; i++)
3038 fd_filename[i] = NULL;
3039 for(i = 0; i < MAX_DISKS; i++)
3040 hd_filename[i] = NULL;
3041 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3042 vga_ram_size = VGA_RAM_SIZE;
3043 bios_size = BIOS_SIZE;
3044 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3045 #ifdef CONFIG_GDBSTUB
3046 use_gdbstub = 0;
3047 gdbstub_port = DEFAULT_GDBSTUB_PORT;
3048 #endif
3049 snapshot = 0;
3050 nographic = 0;
3051 kernel_filename = NULL;
3052 kernel_cmdline = "";
3053 has_cdrom = 1;
3054 cyls = heads = secs = 0;
3055 translation = BIOS_ATA_TRANSLATION_AUTO;
3056 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
3058 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
3059 for(i = 1; i < MAX_SERIAL_PORTS; i++)
3060 serial_devices[i][0] = '\0';
3061 serial_device_index = 0;
3063 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
3064 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
3065 parallel_devices[i][0] = '\0';
3066 parallel_device_index = 0;
3068 nb_tun_fds = 0;
3069 net_if_type = -1;
3070 nb_nics = 1;
3071 /* default mac address of the first network interface */
3072 macaddr[0] = 0x52;
3073 macaddr[1] = 0x54;
3074 macaddr[2] = 0x00;
3075 macaddr[3] = 0x12;
3076 macaddr[4] = 0x34;
3077 macaddr[5] = 0x56;
3079 optind = 1;
3080 for(;;) {
3081 if (optind >= argc)
3082 break;
3083 r = argv[optind];
3084 if (r[0] != '-') {
3085 hd_filename[0] = argv[optind++];
3086 } else {
3087 const QEMUOption *popt;
3089 optind++;
3090 popt = qemu_options;
3091 for(;;) {
3092 if (!popt->name) {
3093 fprintf(stderr, "%s: invalid option -- '%s'\n",
3094 argv[0], r);
3095 exit(1);
3097 if (!strcmp(popt->name, r + 1))
3098 break;
3099 popt++;
3101 if (popt->flags & HAS_ARG) {
3102 if (optind >= argc) {
3103 fprintf(stderr, "%s: option '%s' requires an argument\n",
3104 argv[0], r);
3105 exit(1);
3107 optarg = argv[optind++];
3108 } else {
3109 optarg = NULL;
3112 switch(popt->index) {
3113 case QEMU_OPTION_initrd:
3114 initrd_filename = optarg;
3115 break;
3116 case QEMU_OPTION_hda:
3117 hd_filename[0] = optarg;
3118 break;
3119 case QEMU_OPTION_hdb:
3120 hd_filename[1] = optarg;
3121 break;
3122 case QEMU_OPTION_snapshot:
3123 snapshot = 1;
3124 break;
3125 case QEMU_OPTION_hdachs:
3127 const char *p;
3128 p = optarg;
3129 cyls = strtol(p, (char **)&p, 0);
3130 if (cyls < 1 || cyls > 16383)
3131 goto chs_fail;
3132 if (*p != ',')
3133 goto chs_fail;
3134 p++;
3135 heads = strtol(p, (char **)&p, 0);
3136 if (heads < 1 || heads > 16)
3137 goto chs_fail;
3138 if (*p != ',')
3139 goto chs_fail;
3140 p++;
3141 secs = strtol(p, (char **)&p, 0);
3142 if (secs < 1 || secs > 63)
3143 goto chs_fail;
3144 if (*p == ',') {
3145 p++;
3146 if (!strcmp(p, "none"))
3147 translation = BIOS_ATA_TRANSLATION_NONE;
3148 else if (!strcmp(p, "lba"))
3149 translation = BIOS_ATA_TRANSLATION_LBA;
3150 else if (!strcmp(p, "auto"))
3151 translation = BIOS_ATA_TRANSLATION_AUTO;
3152 else
3153 goto chs_fail;
3154 } else if (*p != '\0') {
3155 chs_fail:
3156 fprintf(stderr, "qemu: invalid physical CHS format\n");
3157 exit(1);
3160 break;
3161 case QEMU_OPTION_nographic:
3162 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3163 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3164 nographic = 1;
3165 break;
3166 case QEMU_OPTION_kernel:
3167 kernel_filename = optarg;
3168 break;
3169 case QEMU_OPTION_append:
3170 kernel_cmdline = optarg;
3171 break;
3172 case QEMU_OPTION_tun_fd:
3174 const char *p;
3175 int fd;
3176 net_if_type = NET_IF_TUN;
3177 if (nb_tun_fds < MAX_NICS) {
3178 fd = strtol(optarg, (char **)&p, 0);
3179 if (*p != '\0') {
3180 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3181 exit(1);
3183 tun_fds[nb_tun_fds++] = fd;
3186 break;
3187 case QEMU_OPTION_hdc:
3188 hd_filename[2] = optarg;
3189 has_cdrom = 0;
3190 break;
3191 case QEMU_OPTION_hdd:
3192 hd_filename[3] = optarg;
3193 break;
3194 case QEMU_OPTION_cdrom:
3195 hd_filename[2] = optarg;
3196 has_cdrom = 1;
3197 break;
3198 case QEMU_OPTION_boot:
3199 boot_device = optarg[0];
3200 if (boot_device != 'a' &&
3201 #ifdef TARGET_SPARC
3202 // Network boot
3203 boot_device != 'n' &&
3204 #endif
3205 boot_device != 'c' && boot_device != 'd') {
3206 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3207 exit(1);
3209 break;
3210 case QEMU_OPTION_fda:
3211 fd_filename[0] = optarg;
3212 break;
3213 case QEMU_OPTION_fdb:
3214 fd_filename[1] = optarg;
3215 break;
3216 case QEMU_OPTION_no_code_copy:
3217 code_copy_enabled = 0;
3218 break;
3219 case QEMU_OPTION_nics:
3220 nb_nics = atoi(optarg);
3221 if (nb_nics < 0 || nb_nics > MAX_NICS) {
3222 fprintf(stderr, "qemu: invalid number of network interfaces\n");
3223 exit(1);
3225 break;
3226 case QEMU_OPTION_macaddr:
3228 const char *p;
3229 int i;
3230 p = optarg;
3231 for(i = 0; i < 6; i++) {
3232 macaddr[i] = strtol(p, (char **)&p, 16);
3233 if (i == 5) {
3234 if (*p != '\0')
3235 goto macaddr_error;
3236 } else {
3237 if (*p != ':') {
3238 macaddr_error:
3239 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3240 exit(1);
3242 p++;
3246 break;
3247 #ifdef CONFIG_SLIRP
3248 case QEMU_OPTION_tftp:
3249 tftp_prefix = optarg;
3250 break;
3251 #ifndef _WIN32
3252 case QEMU_OPTION_smb:
3253 net_slirp_smb(optarg);
3254 break;
3255 #endif
3256 case QEMU_OPTION_user_net:
3257 net_if_type = NET_IF_USER;
3258 break;
3259 case QEMU_OPTION_redir:
3260 net_slirp_redir(optarg);
3261 break;
3262 #endif
3263 case QEMU_OPTION_dummy_net:
3264 net_if_type = NET_IF_DUMMY;
3265 break;
3266 case QEMU_OPTION_enable_audio:
3267 audio_enabled = 1;
3268 break;
3269 case QEMU_OPTION_h:
3270 help();
3271 break;
3272 case QEMU_OPTION_m:
3273 ram_size = atoi(optarg) * 1024 * 1024;
3274 if (ram_size <= 0)
3275 help();
3276 if (ram_size > PHYS_RAM_MAX_SIZE) {
3277 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3278 PHYS_RAM_MAX_SIZE / (1024 * 1024));
3279 exit(1);
3281 break;
3282 case QEMU_OPTION_d:
3284 int mask;
3285 CPULogItem *item;
3287 mask = cpu_str_to_log_mask(optarg);
3288 if (!mask) {
3289 printf("Log items (comma separated):\n");
3290 for(item = cpu_log_items; item->mask != 0; item++) {
3291 printf("%-10s %s\n", item->name, item->help);
3293 exit(1);
3295 cpu_set_log(mask);
3297 break;
3298 case QEMU_OPTION_n:
3299 pstrcpy(network_script, sizeof(network_script), optarg);
3300 break;
3301 #ifdef CONFIG_GDBSTUB
3302 case QEMU_OPTION_s:
3303 use_gdbstub = 1;
3304 break;
3305 case QEMU_OPTION_p:
3306 gdbstub_port = atoi(optarg);
3307 break;
3308 #endif
3309 case QEMU_OPTION_L:
3310 bios_dir = optarg;
3311 break;
3312 case QEMU_OPTION_S:
3313 start_emulation = 0;
3314 break;
3315 case QEMU_OPTION_pci:
3316 pci_enabled = 1;
3317 break;
3318 case QEMU_OPTION_isa:
3319 pci_enabled = 0;
3320 break;
3321 case QEMU_OPTION_prep:
3322 prep_enabled = 1;
3323 break;
3324 case QEMU_OPTION_k:
3325 keyboard_layout = optarg;
3326 break;
3327 case QEMU_OPTION_localtime:
3328 rtc_utc = 0;
3329 break;
3330 case QEMU_OPTION_cirrusvga:
3331 cirrus_vga_enabled = 1;
3332 break;
3333 case QEMU_OPTION_std_vga:
3334 cirrus_vga_enabled = 0;
3335 break;
3336 case QEMU_OPTION_g:
3338 const char *p;
3339 int w, h, depth;
3340 p = optarg;
3341 w = strtol(p, (char **)&p, 10);
3342 if (w <= 0) {
3343 graphic_error:
3344 fprintf(stderr, "qemu: invalid resolution or depth\n");
3345 exit(1);
3347 if (*p != 'x')
3348 goto graphic_error;
3349 p++;
3350 h = strtol(p, (char **)&p, 10);
3351 if (h <= 0)
3352 goto graphic_error;
3353 if (*p == 'x') {
3354 p++;
3355 depth = strtol(p, (char **)&p, 10);
3356 if (depth != 8 && depth != 15 && depth != 16 &&
3357 depth != 24 && depth != 32)
3358 goto graphic_error;
3359 } else if (*p == '\0') {
3360 depth = graphic_depth;
3361 } else {
3362 goto graphic_error;
3365 graphic_width = w;
3366 graphic_height = h;
3367 graphic_depth = depth;
3369 break;
3370 case QEMU_OPTION_monitor:
3371 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3372 break;
3373 case QEMU_OPTION_serial:
3374 if (serial_device_index >= MAX_SERIAL_PORTS) {
3375 fprintf(stderr, "qemu: too many serial ports\n");
3376 exit(1);
3378 pstrcpy(serial_devices[serial_device_index],
3379 sizeof(serial_devices[0]), optarg);
3380 serial_device_index++;
3381 break;
3382 case QEMU_OPTION_parallel:
3383 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
3384 fprintf(stderr, "qemu: too many parallel ports\n");
3385 exit(1);
3387 pstrcpy(parallel_devices[parallel_device_index],
3388 sizeof(parallel_devices[0]), optarg);
3389 parallel_device_index++;
3390 break;
3391 case QEMU_OPTION_loadvm:
3392 loadvm = optarg;
3393 break;
3394 case QEMU_OPTION_full_screen:
3395 full_screen = 1;
3396 break;
3397 case QEMU_OPTION_pidfile:
3398 create_pidfile(optarg);
3399 break;
3400 #ifdef USE_KQEMU
3401 case QEMU_OPTION_no_kqemu:
3402 kqemu_allowed = 0;
3403 break;
3404 #endif
3409 linux_boot = (kernel_filename != NULL);
3411 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3412 fd_filename[0] == '\0')
3413 help();
3415 /* boot to cd by default if no hard disk */
3416 if (hd_filename[0] == '\0' && boot_device == 'c') {
3417 if (fd_filename[0] != '\0')
3418 boot_device = 'a';
3419 else
3420 boot_device = 'd';
3423 #if !defined(CONFIG_SOFTMMU)
3424 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3426 static uint8_t stdout_buf[4096];
3427 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3429 #else
3430 setvbuf(stdout, NULL, _IOLBF, 0);
3431 #endif
3433 /* init host network redirectors */
3434 if (net_if_type == -1) {
3435 net_if_type = NET_IF_TUN;
3436 #if defined(CONFIG_SLIRP)
3437 if (access(network_script, R_OK) < 0) {
3438 net_if_type = NET_IF_USER;
3440 #endif
3443 for(i = 0; i < nb_nics; i++) {
3444 NetDriverState *nd = &nd_table[i];
3445 nd->index = i;
3446 /* init virtual mac address */
3447 nd->macaddr[0] = macaddr[0];
3448 nd->macaddr[1] = macaddr[1];
3449 nd->macaddr[2] = macaddr[2];
3450 nd->macaddr[3] = macaddr[3];
3451 nd->macaddr[4] = macaddr[4];
3452 nd->macaddr[5] = macaddr[5] + i;
3453 switch(net_if_type) {
3454 #if defined(CONFIG_SLIRP)
3455 case NET_IF_USER:
3456 net_slirp_init(nd);
3457 break;
3458 #endif
3459 #if !defined(_WIN32)
3460 case NET_IF_TUN:
3461 if (i < nb_tun_fds) {
3462 net_fd_init(nd, tun_fds[i]);
3463 } else {
3464 if (net_tun_init(nd) < 0)
3465 net_dummy_init(nd);
3467 break;
3468 #endif
3469 case NET_IF_DUMMY:
3470 default:
3471 net_dummy_init(nd);
3472 break;
3476 /* init the memory */
3477 phys_ram_size = ram_size + vga_ram_size + bios_size;
3479 #ifdef CONFIG_SOFTMMU
3480 phys_ram_base = qemu_vmalloc(phys_ram_size);
3481 if (!phys_ram_base) {
3482 fprintf(stderr, "Could not allocate physical memory\n");
3483 exit(1);
3485 #else
3486 /* as we must map the same page at several addresses, we must use
3487 a fd */
3489 const char *tmpdir;
3491 tmpdir = getenv("QEMU_TMPDIR");
3492 if (!tmpdir)
3493 tmpdir = "/tmp";
3494 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3495 if (mkstemp(phys_ram_file) < 0) {
3496 fprintf(stderr, "Could not create temporary memory file '%s'\n",
3497 phys_ram_file);
3498 exit(1);
3500 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3501 if (phys_ram_fd < 0) {
3502 fprintf(stderr, "Could not open temporary memory file '%s'\n",
3503 phys_ram_file);
3504 exit(1);
3506 ftruncate(phys_ram_fd, phys_ram_size);
3507 unlink(phys_ram_file);
3508 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
3509 phys_ram_size,
3510 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
3511 phys_ram_fd, 0);
3512 if (phys_ram_base == MAP_FAILED) {
3513 fprintf(stderr, "Could not map physical memory\n");
3514 exit(1);
3517 #endif
3519 /* we always create the cdrom drive, even if no disk is there */
3520 bdrv_init();
3521 if (has_cdrom) {
3522 bs_table[2] = bdrv_new("cdrom");
3523 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3526 /* open the virtual block devices */
3527 for(i = 0; i < MAX_DISKS; i++) {
3528 if (hd_filename[i]) {
3529 if (!bs_table[i]) {
3530 char buf[64];
3531 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3532 bs_table[i] = bdrv_new(buf);
3534 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3535 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3536 hd_filename[i]);
3537 exit(1);
3539 if (i == 0 && cyls != 0) {
3540 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3541 bdrv_set_translation_hint(bs_table[i], translation);
3546 /* we always create at least one floppy disk */
3547 fd_table[0] = bdrv_new("fda");
3548 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3550 for(i = 0; i < MAX_FD; i++) {
3551 if (fd_filename[i]) {
3552 if (!fd_table[i]) {
3553 char buf[64];
3554 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3555 fd_table[i] = bdrv_new(buf);
3556 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3558 if (fd_filename[i] != '\0') {
3559 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3560 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3561 fd_filename[i]);
3562 exit(1);
3568 /* init CPU state */
3569 env = cpu_init();
3570 global_env = env;
3571 cpu_single_env = env;
3573 register_savevm("timer", 0, 1, timer_save, timer_load, env);
3574 register_savevm("cpu", 0, 3, cpu_save, cpu_load, env);
3575 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3576 qemu_register_reset(main_cpu_reset, global_env);
3578 init_ioports();
3579 cpu_calibrate_ticks();
3581 /* terminal init */
3582 if (nographic) {
3583 dumb_display_init(ds);
3584 } else {
3585 #if defined(CONFIG_SDL)
3586 sdl_display_init(ds, full_screen);
3587 #elif defined(CONFIG_COCOA)
3588 cocoa_display_init(ds, full_screen);
3589 #else
3590 dumb_display_init(ds);
3591 #endif
3594 vga_console = graphic_console_init(ds);
3596 monitor_hd = qemu_chr_open(monitor_device);
3597 if (!monitor_hd) {
3598 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3599 exit(1);
3601 monitor_init(monitor_hd, !nographic);
3603 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3604 if (serial_devices[i][0] != '\0') {
3605 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3606 if (!serial_hds[i]) {
3607 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3608 serial_devices[i]);
3609 exit(1);
3611 if (!strcmp(serial_devices[i], "vc"))
3612 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3616 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
3617 if (parallel_devices[i][0] != '\0') {
3618 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
3619 if (!parallel_hds[i]) {
3620 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
3621 parallel_devices[i]);
3622 exit(1);
3624 if (!strcmp(parallel_devices[i], "vc"))
3625 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
3629 /* setup cpu signal handlers for MMU / self modifying code handling */
3630 #if !defined(CONFIG_SOFTMMU)
3632 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3634 stack_t stk;
3635 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3636 stk.ss_sp = signal_stack;
3637 stk.ss_size = SIGNAL_STACK_SIZE;
3638 stk.ss_flags = 0;
3640 if (sigaltstack(&stk, NULL) < 0) {
3641 perror("sigaltstack");
3642 exit(1);
3645 #endif
3647 struct sigaction act;
3649 sigfillset(&act.sa_mask);
3650 act.sa_flags = SA_SIGINFO;
3651 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3652 act.sa_flags |= SA_ONSTACK;
3653 #endif
3654 act.sa_sigaction = host_segv_handler;
3655 sigaction(SIGSEGV, &act, NULL);
3656 sigaction(SIGBUS, &act, NULL);
3657 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3658 sigaction(SIGFPE, &act, NULL);
3659 #endif
3661 #endif
3663 #ifndef _WIN32
3665 struct sigaction act;
3666 sigfillset(&act.sa_mask);
3667 act.sa_flags = 0;
3668 act.sa_handler = SIG_IGN;
3669 sigaction(SIGPIPE, &act, NULL);
3671 #endif
3672 init_timers();
3674 #if defined(TARGET_I386)
3675 pc_init(ram_size, vga_ram_size, boot_device,
3676 ds, fd_filename, snapshot,
3677 kernel_filename, kernel_cmdline, initrd_filename);
3678 #elif defined(TARGET_PPC)
3679 ppc_init(ram_size, vga_ram_size, boot_device,
3680 ds, fd_filename, snapshot,
3681 kernel_filename, kernel_cmdline, initrd_filename);
3682 #elif defined(TARGET_SPARC)
3683 sun4m_init(ram_size, vga_ram_size, boot_device,
3684 ds, fd_filename, snapshot,
3685 kernel_filename, kernel_cmdline, initrd_filename);
3686 #endif
3688 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3689 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3691 #ifdef CONFIG_GDBSTUB
3692 if (use_gdbstub) {
3693 if (gdbserver_start(gdbstub_port) < 0) {
3694 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3695 gdbstub_port);
3696 exit(1);
3697 } else {
3698 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3700 } else
3701 #endif
3702 if (loadvm)
3703 qemu_loadvm(loadvm);
3706 /* XXX: simplify init */
3707 read_passwords();
3708 if (start_emulation) {
3709 vm_start();
3712 main_loop();
3713 quit_timers();
3714 return 0;