debuggers.hg

view tools/ioemu/vl.c @ 6641:f27205ea60ef

merge?
author cl349@firebug.cl.cam.ac.uk
date Sat Sep 03 16:58:50 2005 +0000 (2005-09-03)
parents dd668f7527cb 0c0d929e787c
children 29808fef9148 b6c98fe62e1a
line source
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #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 #include "xenctrl.h"
76 #include "exec-all.h"
78 //#define DO_TB_FLUSH
80 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
82 #if !defined(CONFIG_SOFTMMU)
83 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
84 #else
85 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
86 #endif
88 #ifdef TARGET_PPC
89 #define DEFAULT_RAM_SIZE 144
90 #else
91 #define DEFAULT_RAM_SIZE 128
92 #endif
93 /* in ms */
94 #define GUI_REFRESH_INTERVAL 30
95 #define POLLING_INTERVAL 5
97 /* XXX: use a two level table to limit memory usage */
98 #define MAX_IOPORTS 65536
100 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
101 char phys_ram_file[1024];
102 CPUState *global_env;
103 CPUState *cpu_single_env;
104 void *ioport_opaque[MAX_IOPORTS];
105 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
106 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
107 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
108 int vga_ram_size;
109 int bios_size;
110 static DisplayState display_state;
111 int nographic;
112 int usevnc; /* 1=vnc only, 2=vnc and sdl */
113 long vncport; /* server port */
114 const char* vncconnect; /* do a reverse connect to this host*/
115 const char* keyboard_layout = 0;
116 int64_t ticks_per_sec;
117 int boot_device = 'c';
118 int ram_size;
119 int domid = -1;
120 static char network_script[1024];
121 int pit_min_timer_count = 0;
122 int nb_nics;
123 NetDriverState nd_table[MAX_NICS];
124 QEMUTimer *gui_timer;
125 QEMUTimer *polling_timer;
126 int vm_running;
127 int audio_enabled = 0;
128 int nic_pcnet = 1;
129 int sb16_enabled = 1;
130 int adlib_enabled = 1;
131 int gus_enabled = 1;
132 int pci_enabled = 1;
133 int prep_enabled = 0;
134 int rtc_utc = 1;
135 int cirrus_vga_enabled = 1;
136 int graphic_width = 800;
137 int graphic_height = 600;
138 int graphic_depth = 15;
139 int full_screen = 0;
140 TextConsole *vga_console;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 int xc_handle;
144 /***********************************************************/
145 /* x86 ISA bus support */
147 target_phys_addr_t isa_mem_base = 0;
149 uint32_t default_ioport_readb(void *opaque, uint32_t address)
150 {
151 #ifdef DEBUG_UNUSED_IOPORT
152 fprintf(stderr, "inb: port=0x%04x\n", address);
153 #endif
154 return 0xff;
155 }
157 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
158 {
159 #ifdef DEBUG_UNUSED_IOPORT
160 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
161 #endif
162 }
164 /* default is to make two byte accesses */
165 uint32_t default_ioport_readw(void *opaque, uint32_t address)
166 {
167 uint32_t data;
168 data = ioport_read_table[0][address](ioport_opaque[address], address);
169 address = (address + 1) & (MAX_IOPORTS - 1);
170 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
171 return data;
172 }
174 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
175 {
176 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
177 address = (address + 1) & (MAX_IOPORTS - 1);
178 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
179 }
181 uint32_t default_ioport_readl(void *opaque, uint32_t address)
182 {
183 #ifdef DEBUG_UNUSED_IOPORT
184 fprintf(stderr, "inl: port=0x%04x\n", address);
185 #endif
186 return 0xffffffff;
187 }
189 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
190 {
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
193 #endif
194 }
196 void init_ioports(void)
197 {
198 int i;
200 for(i = 0; i < MAX_IOPORTS; i++) {
201 ioport_read_table[0][i] = default_ioport_readb;
202 ioport_write_table[0][i] = default_ioport_writeb;
203 ioport_read_table[1][i] = default_ioport_readw;
204 ioport_write_table[1][i] = default_ioport_writew;
205 ioport_read_table[2][i] = default_ioport_readl;
206 ioport_write_table[2][i] = default_ioport_writel;
207 }
208 }
210 /* size is the word size in byte */
211 int register_ioport_read(int start, int length, int size,
212 IOPortReadFunc *func, void *opaque)
213 {
214 int i, bsize;
216 if (size == 1) {
217 bsize = 0;
218 } else if (size == 2) {
219 bsize = 1;
220 } else if (size == 4) {
221 bsize = 2;
222 } else {
223 hw_error("register_ioport_read: invalid size");
224 return -1;
225 }
226 for(i = start; i < start + length; i += size) {
227 ioport_read_table[bsize][i] = func;
228 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
229 hw_error("register_ioport_read: invalid opaque");
230 ioport_opaque[i] = opaque;
231 }
232 return 0;
233 }
235 /* size is the word size in byte */
236 int register_ioport_write(int start, int length, int size,
237 IOPortWriteFunc *func, void *opaque)
238 {
239 int i, bsize;
241 if (size == 1) {
242 bsize = 0;
243 } else if (size == 2) {
244 bsize = 1;
245 } else if (size == 4) {
246 bsize = 2;
247 } else {
248 hw_error("register_ioport_write: invalid size");
249 return -1;
250 }
251 for(i = start; i < start + length; i += size) {
252 ioport_write_table[bsize][i] = func;
253 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
254 hw_error("register_ioport_read: invalid opaque");
255 ioport_opaque[i] = opaque;
256 }
257 return 0;
258 }
260 void isa_unassign_ioport(int start, int length)
261 {
262 int i;
264 for(i = start; i < start + length; i++) {
265 ioport_read_table[0][i] = default_ioport_readb;
266 ioport_read_table[1][i] = default_ioport_readw;
267 ioport_read_table[2][i] = default_ioport_readl;
269 ioport_write_table[0][i] = default_ioport_writeb;
270 ioport_write_table[1][i] = default_ioport_writew;
271 ioport_write_table[2][i] = default_ioport_writel;
272 }
273 }
275 void pstrcpy(char *buf, int buf_size, const char *str)
276 {
277 int c;
278 char *q = buf;
280 if (buf_size <= 0)
281 return;
283 for(;;) {
284 c = *str++;
285 if (c == 0 || q >= buf + buf_size - 1)
286 break;
287 *q++ = c;
288 }
289 *q = '\0';
290 }
292 /* strcat and truncate. */
293 char *pstrcat(char *buf, int buf_size, const char *s)
294 {
295 int len;
296 len = strlen(buf);
297 if (len < buf_size)
298 pstrcpy(buf + len, buf_size - len, s);
299 return buf;
300 }
302 int strstart(const char *str, const char *val, const char **ptr)
303 {
304 const char *p, *q;
305 p = str;
306 q = val;
307 while (*q != '\0') {
308 if (*p != *q)
309 return 0;
310 p++;
311 q++;
312 }
313 if (ptr)
314 *ptr = p;
315 return 1;
316 }
318 /* return the size or -1 if error */
319 int get_image_size(const char *filename)
320 {
321 int fd, size;
322 fd = open(filename, O_RDONLY | O_BINARY);
323 if (fd < 0)
324 return -1;
325 size = lseek(fd, 0, SEEK_END);
326 close(fd);
327 return size;
328 }
330 /* return the size or -1 if error */
331 int load_image(const char *filename, uint8_t *addr)
332 {
333 int fd, size;
334 fd = open(filename, O_RDONLY | O_BINARY);
335 if (fd < 0)
336 return -1;
337 size = lseek(fd, 0, SEEK_END);
338 lseek(fd, 0, SEEK_SET);
339 if (read(fd, addr, size) != size) {
340 close(fd);
341 return -1;
342 }
343 close(fd);
344 return size;
345 }
347 void cpu_outb(CPUState *env, int addr, int val)
348 {
349 #ifdef DEBUG_IOPORT
350 if (loglevel & CPU_LOG_IOPORT)
351 fprintf(logfile, "outb: %04x %02x\n", addr, val);
352 #endif
353 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
354 }
356 void cpu_outw(CPUState *env, int addr, int val)
357 {
358 #ifdef DEBUG_IOPORT
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "outw: %04x %04x\n", addr, val);
361 #endif
362 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
363 }
365 void cpu_outl(CPUState *env, int addr, int val)
366 {
367 #ifdef DEBUG_IOPORT
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outl: %04x %08x\n", addr, val);
370 #endif
371 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
372 }
374 int cpu_inb(CPUState *env, int addr)
375 {
376 int val;
377 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "inb : %04x %02x\n", addr, val);
381 #endif
382 return val;
383 }
385 int cpu_inw(CPUState *env, int addr)
386 {
387 int val;
388 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
389 #ifdef DEBUG_IOPORT
390 if (loglevel & CPU_LOG_IOPORT)
391 fprintf(logfile, "inw : %04x %04x\n", addr, val);
392 #endif
393 return val;
394 }
396 int cpu_inl(CPUState *env, int addr)
397 {
398 int val;
399 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
400 #ifdef DEBUG_IOPORT
401 if (loglevel & CPU_LOG_IOPORT)
402 fprintf(logfile, "inl : %04x %08x\n", addr, val);
403 #endif
404 return val;
405 }
407 /***********************************************************/
408 void hw_error(const char *fmt, ...)
409 {
410 va_list ap;
412 va_start(ap, fmt);
413 fprintf(stderr, "qemu: hardware error: ");
414 vfprintf(stderr, fmt, ap);
415 fprintf(stderr, "\n");
416 if (logfile) {
417 fprintf(logfile, "qemu: hardware error: ");
418 vfprintf(logfile, fmt, ap);
419 fprintf(logfile, "\n");
420 }
421 va_end(ap);
422 abort();
423 }
425 /***********************************************************/
426 /* keyboard/mouse */
428 static QEMUPutKBDEvent *qemu_put_kbd_event;
429 static void *qemu_put_kbd_event_opaque;
430 static QEMUPutMouseEvent *qemu_put_mouse_event;
431 static void *qemu_put_mouse_event_opaque;
433 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
434 {
435 qemu_put_kbd_event_opaque = opaque;
436 qemu_put_kbd_event = func;
437 }
439 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
440 {
441 qemu_put_mouse_event_opaque = opaque;
442 qemu_put_mouse_event = func;
443 }
445 void kbd_put_keycode(int keycode)
446 {
447 if (qemu_put_kbd_event) {
448 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
449 }
450 }
452 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
453 {
454 if (qemu_put_mouse_event) {
455 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
456 dx, dy, dz, buttons_state);
457 }
458 }
460 /***********************************************************/
461 /* timers */
463 #if defined(__powerpc__)
465 static inline uint32_t get_tbl(void)
466 {
467 uint32_t tbl;
468 asm volatile("mftb %0" : "=r" (tbl));
469 return tbl;
470 }
472 static inline uint32_t get_tbu(void)
473 {
474 uint32_t tbl;
475 asm volatile("mftbu %0" : "=r" (tbl));
476 return tbl;
477 }
479 int64_t cpu_get_real_ticks(void)
480 {
481 uint32_t l, h, h1;
482 /* NOTE: we test if wrapping has occurred */
483 do {
484 h = get_tbu();
485 l = get_tbl();
486 h1 = get_tbu();
487 } while (h != h1);
488 return ((int64_t)h << 32) | l;
489 }
491 #elif defined(__i386__)
493 int64_t cpu_get_real_ticks(void)
494 {
495 int64_t val;
496 asm volatile ("rdtsc" : "=A" (val));
497 return val;
498 }
500 #elif defined(__x86_64__)
502 int64_t cpu_get_real_ticks(void)
503 {
504 uint32_t low,high;
505 int64_t val;
506 asm volatile("rdtsc" : "=a" (low), "=d" (high));
507 val = high;
508 val <<= 32;
509 val |= low;
510 return val;
511 }
513 #else
514 #error unsupported CPU
515 #endif
517 static int64_t cpu_ticks_offset;
518 static int cpu_ticks_enabled;
519 int64_t cpu_virt_tsc;
521 static inline int64_t cpu_get_ticks(void)
522 {
523 if (!cpu_ticks_enabled) {
524 return cpu_ticks_offset;
525 } else {
526 return cpu_get_real_ticks() + cpu_ticks_offset;
527 }
529 }
531 /* enable cpu_get_ticks() */
532 void cpu_enable_ticks(void)
533 {
534 if (!cpu_ticks_enabled) {
535 cpu_ticks_offset -= cpu_get_real_ticks();
536 cpu_ticks_enabled = 1;
537 }
538 }
540 /* disable cpu_get_ticks() : the clock is stopped. You must not call
541 cpu_get_ticks() after that. */
542 void cpu_disable_ticks(void)
543 {
544 if (cpu_ticks_enabled) {
545 cpu_ticks_offset = cpu_get_ticks();
546 cpu_ticks_enabled = 0;
547 }
548 }
550 static int64_t get_clock(void)
551 {
552 #ifdef _WIN32
553 struct _timeb tb;
554 _ftime(&tb);
555 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
556 #else
557 struct timeval tv;
558 gettimeofday(&tv, NULL);
559 return tv.tv_sec * 1000000LL + tv.tv_usec;
560 #endif
561 }
563 void cpu_calibrate_ticks(void)
564 {
565 int64_t usec, ticks;
567 usec = get_clock();
568 ticks = cpu_get_real_ticks();
569 #ifdef _WIN32
570 Sleep(50);
571 #else
572 usleep(50 * 1000);
573 #endif
574 usec = get_clock() - usec;
575 ticks = cpu_get_real_ticks() - ticks;
576 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
577 }
579 /* compute with 96 bit intermediate result: (a*b)/c */
580 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
581 {
582 union {
583 uint64_t ll;
584 struct {
585 #ifdef WORDS_BIGENDIAN
586 uint32_t high, low;
587 #else
588 uint32_t low, high;
589 #endif
590 } l;
591 } u, res;
592 uint64_t rl, rh;
594 u.ll = a;
595 rl = (uint64_t)u.l.low * (uint64_t)b;
596 rh = (uint64_t)u.l.high * (uint64_t)b;
597 rh += (rl >> 32);
598 res.l.high = rh / c;
599 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
600 return res.ll;
601 }
603 #define QEMU_TIMER_REALTIME 0
604 #define QEMU_TIMER_VIRTUAL 1
606 struct QEMUClock {
607 int type;
608 /* XXX: add frequency */
609 };
611 struct QEMUTimer {
612 QEMUClock *clock;
613 int64_t expire_time;
614 QEMUTimerCB *cb;
615 void *opaque;
616 struct QEMUTimer *next;
617 };
619 QEMUClock *rt_clock;
620 QEMUClock *vm_clock;
622 static QEMUTimer *active_timers[2];
623 #ifdef _WIN32
624 static MMRESULT timerID;
625 #else
626 /* frequency of the times() clock tick */
627 static int timer_freq;
628 #endif
630 QEMUClock *qemu_new_clock(int type)
631 {
632 QEMUClock *clock;
633 clock = qemu_mallocz(sizeof(QEMUClock));
634 if (!clock)
635 return NULL;
636 clock->type = type;
637 return clock;
638 }
640 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
641 {
642 QEMUTimer *ts;
644 ts = qemu_mallocz(sizeof(QEMUTimer));
645 ts->clock = clock;
646 ts->cb = cb;
647 ts->opaque = opaque;
648 return ts;
649 }
651 void qemu_free_timer(QEMUTimer *ts)
652 {
653 qemu_free(ts);
654 }
656 /* stop a timer, but do not dealloc it */
657 void qemu_del_timer(QEMUTimer *ts)
658 {
659 QEMUTimer **pt, *t;
661 /* NOTE: this code must be signal safe because
662 qemu_timer_expired() can be called from a signal. */
663 pt = &active_timers[ts->clock->type];
664 for(;;) {
665 t = *pt;
666 if (!t)
667 break;
668 if (t == ts) {
669 *pt = t->next;
670 break;
671 }
672 pt = &t->next;
673 }
674 }
676 /* modify the current timer so that it will be fired when current_time
677 >= expire_time. The corresponding callback will be called. */
678 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
679 {
680 QEMUTimer **pt, *t;
682 qemu_del_timer(ts);
684 /* add the timer in the sorted list */
685 /* NOTE: this code must be signal safe because
686 qemu_timer_expired() can be called from a signal. */
687 pt = &active_timers[ts->clock->type];
688 for(;;) {
689 t = *pt;
690 if (!t)
691 break;
692 if (t->expire_time > expire_time)
693 break;
694 pt = &t->next;
695 }
696 ts->expire_time = expire_time;
697 ts->next = *pt;
698 *pt = ts;
699 }
701 int qemu_timer_pending(QEMUTimer *ts)
702 {
703 QEMUTimer *t;
704 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
705 if (t == ts)
706 return 1;
707 }
708 return 0;
709 }
711 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
712 {
713 if (!timer_head)
714 return 0;
715 return (timer_head->expire_time <= current_time);
716 }
718 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
719 {
720 QEMUTimer *ts;
722 for(;;) {
723 ts = *ptimer_head;
724 if (!ts || ts->expire_time > current_time)
725 break;
726 /* remove timer from the list before calling the callback */
727 *ptimer_head = ts->next;
728 ts->next = NULL;
730 /* run the callback (the timer list can be modified) */
731 ts->cb(ts->opaque);
732 }
733 }
735 int64_t qemu_get_clock(QEMUClock *clock)
736 {
737 switch(clock->type) {
738 case QEMU_TIMER_REALTIME:
739 #ifdef _WIN32
740 return GetTickCount();
741 #else
742 {
743 struct tms tp;
745 /* Note that using gettimeofday() is not a good solution
746 for timers because its value change when the date is
747 modified. */
748 if (timer_freq == 100) {
749 return times(&tp) * 10;
750 } else {
751 return ((int64_t)times(&tp) * 1000) / timer_freq;
752 }
753 }
754 #endif
755 default:
756 case QEMU_TIMER_VIRTUAL:
757 return cpu_get_ticks();
758 }
759 }
761 /* save a timer */
762 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
763 {
764 uint64_t expire_time;
766 if (qemu_timer_pending(ts)) {
767 expire_time = ts->expire_time;
768 } else {
769 expire_time = -1;
770 }
771 qemu_put_be64(f, expire_time);
772 }
774 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
775 {
776 uint64_t expire_time;
778 expire_time = qemu_get_be64(f);
779 if (expire_time != -1) {
780 qemu_mod_timer(ts, expire_time);
781 } else {
782 qemu_del_timer(ts);
783 }
784 }
786 static void init_timers(void)
787 {
788 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
789 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
791 #ifdef _WIN32
792 {
793 int count=0;
794 timerID = timeSetEvent(10, // interval (ms)
795 0, // resolution
796 host_alarm_handler, // function
797 (DWORD)&count, // user parameter
798 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
799 if( !timerID ) {
800 perror("failed timer alarm");
801 exit(1);
802 }
803 }
804 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
805 #else
806 {
807 /* get times() syscall frequency */
808 timer_freq = sysconf(_SC_CLK_TCK);
810 #ifndef TARGET_VMX
811 /* timer signal */
812 sigfillset(&act.sa_mask);
813 act.sa_flags = 0;
814 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
815 act.sa_flags |= SA_ONSTACK;
816 #endif
817 act.sa_handler = host_alarm_handler;
818 sigaction(SIGALRM, &act, NULL);
820 itv.it_interval.tv_sec = 0;
821 itv.it_interval.tv_usec = 1000;
822 itv.it_value.tv_sec = 0;
823 itv.it_value.tv_usec = 10 * 1000;
824 setitimer(ITIMER_REAL, &itv, NULL);
825 /* we probe the tick duration of the kernel to inform the user if
826 the emulated kernel requested a too high timer frequency */
827 getitimer(ITIMER_REAL, &itv);
829 #if defined(__linux__)
830 if (itv.it_interval.tv_usec > 1000) {
831 /* try to use /dev/rtc to have a faster timer */
832 if (start_rtc_timer() < 0)
833 goto use_itimer;
834 /* disable itimer */
835 itv.it_interval.tv_sec = 0;
836 itv.it_interval.tv_usec = 0;
837 itv.it_value.tv_sec = 0;
838 itv.it_value.tv_usec = 0;
839 setitimer(ITIMER_REAL, &itv, NULL);
841 /* use the RTC */
842 sigaction(SIGIO, &act, NULL);
843 fcntl(rtc_fd, F_SETFL, O_ASYNC);
844 fcntl(rtc_fd, F_SETOWN, getpid());
845 } else
846 #endif /* defined(__linux__) */
847 {
848 use_itimer:
849 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
850 PIT_FREQ) / 1000000;
851 }
852 #endif /* TARGET_VMX */
853 }
854 #endif
855 }
857 void quit_timers(void)
858 {
859 #ifdef _WIN32
860 timeKillEvent(timerID);
861 #endif
862 }
864 /***********************************************************/
865 /* character device */
867 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
868 {
869 return s->chr_write(s, buf, len);
870 }
872 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
873 {
874 char buf[4096];
875 va_list ap;
876 va_start(ap, fmt);
877 vsnprintf(buf, sizeof(buf), fmt, ap);
878 qemu_chr_write(s, buf, strlen(buf));
879 va_end(ap);
880 }
882 void qemu_chr_send_event(CharDriverState *s, int event)
883 {
884 if (s->chr_send_event)
885 s->chr_send_event(s, event);
886 }
888 void qemu_chr_add_read_handler(CharDriverState *s,
889 IOCanRWHandler *fd_can_read,
890 IOReadHandler *fd_read, void *opaque)
891 {
892 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
893 }
895 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
896 {
897 s->chr_event = chr_event;
898 }
900 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
901 {
902 return len;
903 }
905 static void null_chr_add_read_handler(CharDriverState *chr,
906 IOCanRWHandler *fd_can_read,
907 IOReadHandler *fd_read, void *opaque)
908 {
909 }
911 CharDriverState *qemu_chr_open_null(void)
912 {
913 CharDriverState *chr;
915 chr = qemu_mallocz(sizeof(CharDriverState));
916 if (!chr)
917 return NULL;
918 chr->chr_write = null_chr_write;
919 chr->chr_add_read_handler = null_chr_add_read_handler;
920 return chr;
921 }
923 #ifndef _WIN32
925 typedef struct {
926 int fd_in, fd_out;
927 /* for nographic stdio only */
928 IOCanRWHandler *fd_can_read;
929 IOReadHandler *fd_read;
930 void *fd_opaque;
931 } FDCharDriver;
933 #define STDIO_MAX_CLIENTS 2
935 static int stdio_nb_clients;
936 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
938 static int unix_write(int fd, const uint8_t *buf, int len1)
939 {
940 int ret, len;
942 len = len1;
943 while (len > 0) {
944 ret = write(fd, buf, len);
945 if (ret < 0) {
946 if (errno != EINTR && errno != EAGAIN)
947 return -1;
948 } else if (ret == 0) {
949 break;
950 } else {
951 buf += ret;
952 len -= ret;
953 }
954 }
955 return len1 - len;
956 }
958 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
959 {
960 FDCharDriver *s = chr->opaque;
961 return unix_write(s->fd_out, buf, len);
962 }
964 static void fd_chr_add_read_handler(CharDriverState *chr,
965 IOCanRWHandler *fd_can_read,
966 IOReadHandler *fd_read, void *opaque)
967 {
968 FDCharDriver *s = chr->opaque;
970 if (nographic && s->fd_in == 0) {
971 s->fd_can_read = fd_can_read;
972 s->fd_read = fd_read;
973 s->fd_opaque = opaque;
974 } else {
975 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
976 }
977 }
979 /* open a character device to a unix fd */
980 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
981 {
982 CharDriverState *chr;
983 FDCharDriver *s;
985 chr = qemu_mallocz(sizeof(CharDriverState));
986 if (!chr)
987 return NULL;
988 s = qemu_mallocz(sizeof(FDCharDriver));
989 if (!s) {
990 free(chr);
991 return NULL;
992 }
993 s->fd_in = fd_in;
994 s->fd_out = fd_out;
995 chr->opaque = s;
996 chr->chr_write = fd_chr_write;
997 chr->chr_add_read_handler = fd_chr_add_read_handler;
998 return chr;
999 }
1001 /* for STDIO, we handle the case where several clients use it
1002 (nographic mode) */
1004 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1006 static int term_got_escape, client_index;
1008 void term_print_help(void)
1010 printf("\n"
1011 "C-a h print this help\n"
1012 "C-a x exit emulator\n"
1013 "C-a s save disk data back to file (if -snapshot)\n"
1014 "C-a b send break (magic sysrq)\n"
1015 "C-a c switch between console and monitor\n"
1016 "C-a C-a send C-a\n"
1017 );
1020 /* called when a char is received */
1021 static void stdio_received_byte(int ch)
1023 if (term_got_escape) {
1024 term_got_escape = 0;
1025 switch(ch) {
1026 case 'h':
1027 term_print_help();
1028 break;
1029 case 'x':
1030 exit(0);
1031 break;
1032 case 's':
1034 int i;
1035 for (i = 0; i < MAX_DISKS; i++) {
1036 if (bs_table[i])
1037 bdrv_commit(bs_table[i]);
1040 break;
1041 case 'b':
1042 if (client_index < stdio_nb_clients) {
1043 CharDriverState *chr;
1044 FDCharDriver *s;
1046 chr = stdio_clients[client_index];
1047 s = chr->opaque;
1048 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1050 break;
1051 case 'c':
1052 client_index++;
1053 if (client_index >= stdio_nb_clients)
1054 client_index = 0;
1055 if (client_index == 0) {
1056 /* send a new line in the monitor to get the prompt */
1057 ch = '\r';
1058 goto send_char;
1060 break;
1061 case TERM_ESCAPE:
1062 goto send_char;
1064 } else if (ch == TERM_ESCAPE) {
1065 term_got_escape = 1;
1066 } else {
1067 send_char:
1068 if (client_index < stdio_nb_clients) {
1069 uint8_t buf[1];
1070 CharDriverState *chr;
1071 FDCharDriver *s;
1073 chr = stdio_clients[client_index];
1074 s = chr->opaque;
1075 buf[0] = ch;
1076 /* XXX: should queue the char if the device is not
1077 ready */
1078 if (s->fd_can_read(s->fd_opaque) > 0)
1079 s->fd_read(s->fd_opaque, buf, 1);
1084 static int stdio_can_read(void *opaque)
1086 /* XXX: not strictly correct */
1087 return 1;
1090 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1092 int i;
1093 for(i = 0; i < size; i++)
1094 stdio_received_byte(buf[i]);
1097 /* init terminal so that we can grab keys */
1098 static struct termios oldtty;
1099 static int old_fd0_flags;
1101 static void term_exit(void)
1103 tcsetattr (0, TCSANOW, &oldtty);
1104 fcntl(0, F_SETFL, old_fd0_flags);
1107 static void term_init(void)
1109 struct termios tty;
1111 tcgetattr (0, &tty);
1112 oldtty = tty;
1113 old_fd0_flags = fcntl(0, F_GETFL);
1115 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1116 |INLCR|IGNCR|ICRNL|IXON);
1117 tty.c_oflag |= OPOST;
1118 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1119 /* if graphical mode, we allow Ctrl-C handling */
1120 if (nographic)
1121 tty.c_lflag &= ~ISIG;
1122 tty.c_cflag &= ~(CSIZE|PARENB);
1123 tty.c_cflag |= CS8;
1124 tty.c_cc[VMIN] = 1;
1125 tty.c_cc[VTIME] = 0;
1127 tcsetattr (0, TCSANOW, &tty);
1129 atexit(term_exit);
1131 fcntl(0, F_SETFL, O_NONBLOCK);
1134 CharDriverState *qemu_chr_open_stdio(void)
1136 CharDriverState *chr;
1138 if (nographic) {
1139 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1140 return NULL;
1141 chr = qemu_chr_open_fd(0, 1);
1142 if (stdio_nb_clients == 0)
1143 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1144 client_index = stdio_nb_clients;
1145 } else {
1146 if (stdio_nb_clients != 0)
1147 return NULL;
1148 chr = qemu_chr_open_fd(0, 1);
1150 stdio_clients[stdio_nb_clients++] = chr;
1151 if (stdio_nb_clients == 1) {
1152 /* set the terminal in raw mode */
1153 term_init();
1155 return chr;
1158 #if defined(__linux__)
1159 CharDriverState *qemu_chr_open_pty(void)
1161 char slave_name[1024];
1162 int master_fd, slave_fd;
1164 /* Not satisfying */
1165 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1166 return NULL;
1168 fprintf(stderr, "char device redirected to %s\n", slave_name);
1169 return qemu_chr_open_fd(master_fd, master_fd);
1171 #else
1172 CharDriverState *qemu_chr_open_pty(void)
1174 return NULL;
1176 #endif
1178 #endif /* !defined(_WIN32) */
1180 CharDriverState *qemu_chr_open(const char *filename)
1182 if (!strcmp(filename, "vc")) {
1183 return text_console_init(&display_state);
1184 } else if (!strcmp(filename, "null")) {
1185 return qemu_chr_open_null();
1186 } else
1187 #ifndef _WIN32
1188 if (!strcmp(filename, "pty")) {
1189 return qemu_chr_open_pty();
1190 } else if (!strcmp(filename, "stdio")) {
1191 return qemu_chr_open_stdio();
1192 } else
1193 #endif
1195 return NULL;
1199 /***********************************************************/
1200 /* Linux network device redirectors */
1202 void hex_dump(FILE *f, const uint8_t *buf, int size)
1204 int len, i, j, c;
1206 for(i=0;i<size;i+=16) {
1207 len = size - i;
1208 if (len > 16)
1209 len = 16;
1210 fprintf(f, "%08x ", i);
1211 for(j=0;j<16;j++) {
1212 if (j < len)
1213 fprintf(f, " %02x", buf[i+j]);
1214 else
1215 fprintf(f, " ");
1217 fprintf(f, " ");
1218 for(j=0;j<len;j++) {
1219 c = buf[i+j];
1220 if (c < ' ' || c > '~')
1221 c = '.';
1222 fprintf(f, "%c", c);
1224 fprintf(f, "\n");
1228 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1230 nd->send_packet(nd, buf, size);
1233 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1234 IOReadHandler *fd_read, void *opaque)
1236 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1239 /* dummy network adapter */
1241 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1245 static void dummy_add_read_packet(NetDriverState *nd,
1246 IOCanRWHandler *fd_can_read,
1247 IOReadHandler *fd_read, void *opaque)
1251 static int net_dummy_init(NetDriverState *nd)
1253 nd->send_packet = dummy_send_packet;
1254 nd->add_read_packet = dummy_add_read_packet;
1255 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1256 return 0;
1259 #if defined(CONFIG_SLIRP)
1261 /* slirp network adapter */
1263 static void *slirp_fd_opaque;
1264 static IOCanRWHandler *slirp_fd_can_read;
1265 static IOReadHandler *slirp_fd_read;
1266 static int slirp_inited;
1268 int slirp_can_output(void)
1270 return slirp_fd_can_read(slirp_fd_opaque);
1273 void slirp_output(const uint8_t *pkt, int pkt_len)
1275 #if 0
1276 printf("output:\n");
1277 hex_dump(stdout, pkt, pkt_len);
1278 #endif
1279 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1282 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1284 #if 0
1285 printf("input:\n");
1286 hex_dump(stdout, buf, size);
1287 #endif
1288 slirp_input(buf, size);
1291 static void slirp_add_read_packet(NetDriverState *nd,
1292 IOCanRWHandler *fd_can_read,
1293 IOReadHandler *fd_read, void *opaque)
1295 slirp_fd_opaque = opaque;
1296 slirp_fd_can_read = fd_can_read;
1297 slirp_fd_read = fd_read;
1300 static int net_slirp_init(NetDriverState *nd)
1302 if (!slirp_inited) {
1303 slirp_inited = 1;
1304 slirp_init();
1306 nd->send_packet = slirp_send_packet;
1307 nd->add_read_packet = slirp_add_read_packet;
1308 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1309 return 0;
1312 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1314 const char *p, *p1;
1315 int len;
1316 p = *pp;
1317 p1 = strchr(p, sep);
1318 if (!p1)
1319 return -1;
1320 len = p1 - p;
1321 p1++;
1322 if (buf_size > 0) {
1323 if (len > buf_size - 1)
1324 len = buf_size - 1;
1325 memcpy(buf, p, len);
1326 buf[len] = '\0';
1328 *pp = p1;
1329 return 0;
1332 static void net_slirp_redir(const char *redir_str)
1334 int is_udp;
1335 char buf[256], *r;
1336 const char *p;
1337 struct in_addr guest_addr;
1338 int host_port, guest_port;
1340 if (!slirp_inited) {
1341 slirp_inited = 1;
1342 slirp_init();
1345 p = redir_str;
1346 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1347 goto fail;
1348 if (!strcmp(buf, "tcp")) {
1349 is_udp = 0;
1350 } else if (!strcmp(buf, "udp")) {
1351 is_udp = 1;
1352 } else {
1353 goto fail;
1356 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1357 goto fail;
1358 host_port = strtol(buf, &r, 0);
1359 if (r == buf)
1360 goto fail;
1362 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1363 goto fail;
1364 if (buf[0] == '\0') {
1365 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1367 if (!inet_aton(buf, &guest_addr))
1368 goto fail;
1370 guest_port = strtol(p, &r, 0);
1371 if (r == p)
1372 goto fail;
1374 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1375 fprintf(stderr, "qemu: could not set up redirection\n");
1376 exit(1);
1378 return;
1379 fail:
1380 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1381 exit(1);
1384 #ifndef _WIN32
1386 char smb_dir[1024];
1388 static void smb_exit(void)
1390 DIR *d;
1391 struct dirent *de;
1392 char filename[1024];
1394 /* erase all the files in the directory */
1395 d = opendir(smb_dir);
1396 for(;;) {
1397 de = readdir(d);
1398 if (!de)
1399 break;
1400 if (strcmp(de->d_name, ".") != 0 &&
1401 strcmp(de->d_name, "..") != 0) {
1402 snprintf(filename, sizeof(filename), "%s/%s",
1403 smb_dir, de->d_name);
1404 unlink(filename);
1407 closedir(d);
1408 rmdir(smb_dir);
1411 /* automatic user mode samba server configuration */
1412 void net_slirp_smb(const char *exported_dir)
1414 char smb_conf[1024];
1415 char smb_cmdline[1024];
1416 FILE *f;
1418 if (!slirp_inited) {
1419 slirp_inited = 1;
1420 slirp_init();
1423 /* XXX: better tmp dir construction */
1424 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1425 if (mkdir(smb_dir, 0700) < 0) {
1426 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1427 exit(1);
1429 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1431 f = fopen(smb_conf, "w");
1432 if (!f) {
1433 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1434 exit(1);
1436 fprintf(f,
1437 "[global]\n"
1438 "pid directory=%s\n"
1439 "lock directory=%s\n"
1440 "log file=%s/log.smbd\n"
1441 "smb passwd file=%s/smbpasswd\n"
1442 "security = share\n"
1443 "[qemu]\n"
1444 "path=%s\n"
1445 "read only=no\n"
1446 "guest ok=yes\n",
1447 smb_dir,
1448 smb_dir,
1449 smb_dir,
1450 smb_dir,
1451 exported_dir
1452 );
1453 fclose(f);
1454 atexit(smb_exit);
1456 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1457 smb_conf);
1459 slirp_add_exec(0, smb_cmdline, 4, 139);
1462 #endif /* !defined(_WIN32) */
1464 #endif /* CONFIG_SLIRP */
1466 #if !defined(_WIN32)
1467 #ifdef _BSD
1468 static int tun_open(char *ifname, int ifname_size)
1470 int fd;
1471 char *dev;
1472 struct stat s;
1474 fd = open("/dev/tap", O_RDWR);
1475 if (fd < 0) {
1476 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1477 return -1;
1480 fstat(fd, &s);
1481 dev = devname(s.st_rdev, S_IFCHR);
1482 pstrcpy(ifname, ifname_size, dev);
1484 fcntl(fd, F_SETFL, O_NONBLOCK);
1485 return fd;
1487 #else
1488 static int tun_open(char *ifname, int ifname_size)
1490 struct ifreq ifr;
1491 int fd, ret;
1493 fd = open("/dev/net/tun", O_RDWR);
1494 if (fd < 0) {
1495 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1496 return -1;
1498 memset(&ifr, 0, sizeof(ifr));
1499 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1500 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1501 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1502 if (ret != 0) {
1503 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1504 close(fd);
1505 return -1;
1507 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1508 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1509 fcntl(fd, F_SETFL, O_NONBLOCK);
1510 return fd;
1512 #endif
1514 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1516 write(nd->fd, buf, size);
1519 static void tun_add_read_packet(NetDriverState *nd,
1520 IOCanRWHandler *fd_can_read,
1521 IOReadHandler *fd_read, void *opaque)
1523 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1526 static int net_tun_init(NetDriverState *nd)
1528 int pid, status;
1529 char *args[3];
1530 char **parg;
1532 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1533 if (nd->fd < 0)
1534 return -1;
1536 /* try to launch network init script */
1537 pid = fork();
1538 if (pid >= 0) {
1539 if (pid == 0) {
1540 parg = args;
1541 *parg++ = network_script;
1542 *parg++ = nd->ifname;
1543 *parg++ = NULL;
1544 execv(network_script, args);
1545 exit(1);
1547 while (waitpid(pid, &status, 0) != pid);
1548 if (!WIFEXITED(status) ||
1549 WEXITSTATUS(status) != 0) {
1550 fprintf(stderr, "%s: could not launch network script\n",
1551 network_script);
1554 nd->send_packet = tun_send_packet;
1555 nd->add_read_packet = tun_add_read_packet;
1556 return 0;
1559 static int net_fd_init(NetDriverState *nd, int fd)
1561 nd->fd = fd;
1562 nd->send_packet = tun_send_packet;
1563 nd->add_read_packet = tun_add_read_packet;
1564 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1565 return 0;
1568 #endif /* !_WIN32 */
1570 /***********************************************************/
1571 /* dumb display */
1573 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1577 static void dumb_resize(DisplayState *ds, int w, int h)
1581 static void dumb_refresh(DisplayState *ds)
1583 vga_update_display();
1586 void dumb_display_init(DisplayState *ds)
1588 ds->data = NULL;
1589 ds->linesize = 0;
1590 ds->depth = 0;
1591 ds->dpy_update = dumb_update;
1592 ds->dpy_resize = dumb_resize;
1593 ds->dpy_refresh = dumb_refresh;
1596 #if !defined(CONFIG_SOFTMMU)
1597 /***********************************************************/
1598 /* cpu signal handler */
1599 static void host_segv_handler(int host_signum, siginfo_t *info,
1600 void *puc)
1602 abort();
1604 #endif
1606 /***********************************************************/
1607 /* I/O handling */
1609 #define MAX_IO_HANDLERS 64
1611 typedef struct IOHandlerRecord {
1612 int fd;
1613 IOCanRWHandler *fd_can_read;
1614 IOReadHandler *fd_read;
1615 void *opaque;
1616 /* temporary data */
1617 struct pollfd *ufd;
1618 int max_size;
1619 struct IOHandlerRecord *next;
1620 } IOHandlerRecord;
1622 static IOHandlerRecord *first_io_handler;
1624 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1625 IOReadHandler *fd_read, void *opaque)
1627 IOHandlerRecord *ioh;
1629 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1630 if (!ioh)
1631 return -1;
1632 ioh->fd = fd;
1633 ioh->fd_can_read = fd_can_read;
1634 ioh->fd_read = fd_read;
1635 ioh->opaque = opaque;
1636 ioh->next = first_io_handler;
1637 first_io_handler = ioh;
1638 return 0;
1641 void qemu_del_fd_read_handler(int fd)
1643 IOHandlerRecord **pioh, *ioh;
1645 pioh = &first_io_handler;
1646 for(;;) {
1647 ioh = *pioh;
1648 if (ioh == NULL)
1649 break;
1650 if (ioh->fd == fd) {
1651 *pioh = ioh->next;
1652 break;
1654 pioh = &ioh->next;
1658 /***********************************************************/
1659 /* savevm/loadvm support */
1661 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1663 fwrite(buf, 1, size, f);
1666 void qemu_put_byte(QEMUFile *f, int v)
1668 fputc(v, f);
1671 void qemu_put_be16(QEMUFile *f, unsigned int v)
1673 qemu_put_byte(f, v >> 8);
1674 qemu_put_byte(f, v);
1677 void qemu_put_be32(QEMUFile *f, unsigned int v)
1679 qemu_put_byte(f, v >> 24);
1680 qemu_put_byte(f, v >> 16);
1681 qemu_put_byte(f, v >> 8);
1682 qemu_put_byte(f, v);
1685 void qemu_put_be64(QEMUFile *f, uint64_t v)
1687 qemu_put_be32(f, v >> 32);
1688 qemu_put_be32(f, v);
1691 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1693 return fread(buf, 1, size, f);
1696 int qemu_get_byte(QEMUFile *f)
1698 int v;
1699 v = fgetc(f);
1700 if (v == EOF)
1701 return 0;
1702 else
1703 return v;
1706 unsigned int qemu_get_be16(QEMUFile *f)
1708 unsigned int v;
1709 v = qemu_get_byte(f) << 8;
1710 v |= qemu_get_byte(f);
1711 return v;
1714 unsigned int qemu_get_be32(QEMUFile *f)
1716 unsigned int v;
1717 v = qemu_get_byte(f) << 24;
1718 v |= qemu_get_byte(f) << 16;
1719 v |= qemu_get_byte(f) << 8;
1720 v |= qemu_get_byte(f);
1721 return v;
1724 uint64_t qemu_get_be64(QEMUFile *f)
1726 uint64_t v;
1727 v = (uint64_t)qemu_get_be32(f) << 32;
1728 v |= qemu_get_be32(f);
1729 return v;
1732 int64_t qemu_ftell(QEMUFile *f)
1734 return ftell(f);
1737 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1739 if (fseek(f, pos, whence) < 0)
1740 return -1;
1741 return ftell(f);
1744 typedef struct SaveStateEntry {
1745 char idstr[256];
1746 int instance_id;
1747 int version_id;
1748 SaveStateHandler *save_state;
1749 LoadStateHandler *load_state;
1750 void *opaque;
1751 struct SaveStateEntry *next;
1752 } SaveStateEntry;
1754 static SaveStateEntry *first_se;
1756 int register_savevm(const char *idstr,
1757 int instance_id,
1758 int version_id,
1759 SaveStateHandler *save_state,
1760 LoadStateHandler *load_state,
1761 void *opaque)
1763 SaveStateEntry *se, **pse;
1765 se = qemu_malloc(sizeof(SaveStateEntry));
1766 if (!se)
1767 return -1;
1768 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1769 se->instance_id = instance_id;
1770 se->version_id = version_id;
1771 se->save_state = save_state;
1772 se->load_state = load_state;
1773 se->opaque = opaque;
1774 se->next = NULL;
1776 /* add at the end of list */
1777 pse = &first_se;
1778 while (*pse != NULL)
1779 pse = &(*pse)->next;
1780 *pse = se;
1781 return 0;
1784 #define QEMU_VM_FILE_MAGIC 0x5145564d
1785 #define QEMU_VM_FILE_VERSION 0x00000001
1787 int qemu_savevm(const char *filename)
1789 SaveStateEntry *se;
1790 QEMUFile *f;
1791 int len, len_pos, cur_pos, saved_vm_running, ret;
1793 saved_vm_running = vm_running;
1794 vm_stop(0);
1796 f = fopen(filename, "wb");
1797 if (!f) {
1798 ret = -1;
1799 goto the_end;
1802 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1803 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1805 for(se = first_se; se != NULL; se = se->next) {
1806 /* ID string */
1807 len = strlen(se->idstr);
1808 qemu_put_byte(f, len);
1809 qemu_put_buffer(f, se->idstr, len);
1811 qemu_put_be32(f, se->instance_id);
1812 qemu_put_be32(f, se->version_id);
1814 /* record size: filled later */
1815 len_pos = ftell(f);
1816 qemu_put_be32(f, 0);
1818 se->save_state(f, se->opaque);
1820 /* fill record size */
1821 cur_pos = ftell(f);
1822 len = ftell(f) - len_pos - 4;
1823 fseek(f, len_pos, SEEK_SET);
1824 qemu_put_be32(f, len);
1825 fseek(f, cur_pos, SEEK_SET);
1828 fclose(f);
1829 ret = 0;
1830 the_end:
1831 if (saved_vm_running)
1832 vm_start();
1833 return ret;
1836 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1838 SaveStateEntry *se;
1840 for(se = first_se; se != NULL; se = se->next) {
1841 if (!strcmp(se->idstr, idstr) &&
1842 instance_id == se->instance_id)
1843 return se;
1845 return NULL;
1848 int qemu_loadvm(const char *filename)
1850 SaveStateEntry *se;
1851 QEMUFile *f;
1852 int len, cur_pos, ret, instance_id, record_len, version_id;
1853 int saved_vm_running;
1854 unsigned int v;
1855 char idstr[256];
1857 saved_vm_running = vm_running;
1858 vm_stop(0);
1860 f = fopen(filename, "rb");
1861 if (!f) {
1862 ret = -1;
1863 goto the_end;
1866 v = qemu_get_be32(f);
1867 if (v != QEMU_VM_FILE_MAGIC)
1868 goto fail;
1869 v = qemu_get_be32(f);
1870 if (v != QEMU_VM_FILE_VERSION) {
1871 fail:
1872 fclose(f);
1873 ret = -1;
1874 goto the_end;
1876 for(;;) {
1877 #if defined (DO_TB_FLUSH)
1878 tb_flush(global_env);
1879 #endif
1880 len = qemu_get_byte(f);
1881 if (feof(f))
1882 break;
1883 qemu_get_buffer(f, idstr, len);
1884 idstr[len] = '\0';
1885 instance_id = qemu_get_be32(f);
1886 version_id = qemu_get_be32(f);
1887 record_len = qemu_get_be32(f);
1888 #if 0
1889 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1890 idstr, instance_id, version_id, record_len);
1891 #endif
1892 cur_pos = ftell(f);
1893 se = find_se(idstr, instance_id);
1894 if (!se) {
1895 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1896 instance_id, idstr);
1897 } else {
1898 ret = se->load_state(f, se->opaque, version_id);
1899 if (ret < 0) {
1900 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1901 instance_id, idstr);
1904 /* always seek to exact end of record */
1905 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1907 fclose(f);
1908 ret = 0;
1909 the_end:
1910 if (saved_vm_running)
1911 vm_start();
1912 return ret;
1915 /***********************************************************/
1916 /* main execution loop */
1918 void gui_update(void *opaque)
1920 display_state.dpy_refresh(&display_state);
1921 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1923 void polling_handler(void *opaque)
1925 #ifndef _WIN32
1926 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1927 IOHandlerRecord *ioh, *ioh_next;
1928 uint8_t buf[4096];
1929 int n, max_size;
1930 #endif
1931 int timeout = 0;
1932 int ret;
1934 #ifdef _WIN32
1935 if (timeout > 0)
1936 Sleep(timeout);
1937 #else
1938 /* poll any events */
1939 /* XXX: separate device handlers from system ones */
1940 pf = ufds;
1941 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1942 if (!ioh->fd_can_read) {
1943 max_size = 0;
1944 pf->fd = ioh->fd;
1945 pf->events = POLLIN;
1946 ioh->ufd = pf;
1947 pf++;
1948 } else {
1949 max_size = ioh->fd_can_read(ioh->opaque);
1950 if (max_size > 0) {
1951 if (max_size > sizeof(buf))
1952 max_size = sizeof(buf);
1953 pf->fd = ioh->fd;
1954 pf->events = POLLIN;
1955 ioh->ufd = pf;
1956 pf++;
1957 } else {
1958 ioh->ufd = NULL;
1961 ioh->max_size = max_size;
1964 ret = poll(ufds, pf - ufds, timeout);
1965 if (ret > 0) {
1966 /* XXX: better handling of removal */
1967 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1968 ioh_next = ioh->next;
1969 pf = ioh->ufd;
1970 if (pf) {
1971 if (pf->revents & POLLIN) {
1972 if (ioh->max_size == 0) {
1973 /* just a read event */
1974 ioh->fd_read(ioh->opaque, NULL, 0);
1975 } else {
1976 n = read(ioh->fd, buf, ioh->max_size);
1977 if (n >= 0) {
1978 ioh->fd_read(ioh->opaque, buf, n);
1979 } else if (errno != EAGAIN) {
1980 ioh->fd_read(ioh->opaque, NULL, -errno);
1987 #endif /* !defined(_WIN32) */
1989 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
1993 /* XXX: support several handlers */
1994 VMStopHandler *vm_stop_cb;
1995 VMStopHandler *vm_stop_opaque;
1997 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1999 vm_stop_cb = cb;
2000 vm_stop_opaque = opaque;
2001 return 0;
2004 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2006 vm_stop_cb = NULL;
2009 void vm_start(void)
2011 if (!vm_running) {
2012 cpu_enable_ticks();
2013 vm_running = 1;
2017 void vm_stop(int reason)
2019 if (vm_running) {
2020 cpu_disable_ticks();
2021 vm_running = 0;
2022 if (reason != 0) {
2023 if (vm_stop_cb) {
2024 vm_stop_cb(vm_stop_opaque, reason);
2030 /* reset/shutdown handler */
2032 typedef struct QEMUResetEntry {
2033 QEMUResetHandler *func;
2034 void *opaque;
2035 struct QEMUResetEntry *next;
2036 } QEMUResetEntry;
2038 static QEMUResetEntry *first_reset_entry;
2039 int reset_requested;
2040 int shutdown_requested;
2042 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2044 QEMUResetEntry **pre, *re;
2046 pre = &first_reset_entry;
2047 while (*pre != NULL)
2048 pre = &(*pre)->next;
2049 re = qemu_mallocz(sizeof(QEMUResetEntry));
2050 re->func = func;
2051 re->opaque = opaque;
2052 re->next = NULL;
2053 *pre = re;
2056 void qemu_system_reset(void)
2058 QEMUResetEntry *re;
2060 /* reset all devices */
2061 for(re = first_reset_entry; re != NULL; re = re->next) {
2062 re->func(re->opaque);
2066 void qemu_system_reset_request(void)
2068 reset_requested = 1;
2069 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2072 void qemu_system_shutdown_request(void)
2074 shutdown_requested = 1;
2075 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2078 void main_loop_wait(int timeout)
2080 if (vm_running) {
2081 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2082 qemu_get_clock(vm_clock));
2083 /* run dma transfers, if any */
2084 DMA_run();
2087 /* real time timers */
2088 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2089 qemu_get_clock(rt_clock));
2092 void help(void)
2094 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2095 "usage: %s [options] [disk_image]\n"
2096 "\n"
2097 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2098 "\n"
2099 "Standard options:\n"
2100 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2101 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2102 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2103 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2104 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2105 "-snapshot write to temporary files instead of disk image files\n"
2106 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2107 "-nographic disable graphical output and redirect serial I/Os to console\n"
2108 #ifdef CONFIG_VNC
2109 "-vnc port use vnc instead of sdl\n"
2110 "-vncport port use a different port\n"
2111 "-vncconnect host:port do a reverse connect\n"
2112 #ifdef CONFIG_SDL
2113 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2114 #endif
2115 #endif
2116 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2117 "-enable-audio enable audio support\n"
2118 "-localtime set the real time clock to local time [default=utc]\n"
2119 "-full-screen start in full screen\n"
2120 #ifdef TARGET_PPC
2121 "-prep Simulate a PREP system (default is PowerMAC)\n"
2122 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2123 #endif
2124 "-nic-pcnet simulate an AMD PC-Net PCI ethernet adaptor\n"
2125 "\n"
2126 "Network options:\n"
2127 "-nics n simulate 'n' network cards [default=1]\n"
2128 "-macaddr addr set the mac address of the first interface\n"
2129 "-n script set tap/tun network init script [default=%s]\n"
2130 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2131 #ifdef CONFIG_SLIRP
2132 "-user-net use user mode network stack [default if no tap/tun script]\n"
2133 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2134 #ifndef _WIN32
2135 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2136 #endif
2137 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2138 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2139 #endif
2140 "-dummy-net use dummy network stack\n"
2141 "\n"
2142 "Linux boot specific:\n"
2143 "-kernel bzImage use 'bzImage' as kernel image\n"
2144 "-append cmdline use 'cmdline' as kernel command line\n"
2145 "-initrd file use 'file' as initial ram disk\n"
2146 "\n"
2147 "Debug/Expert options:\n"
2148 "-monitor dev redirect the monitor to char device 'dev'\n"
2149 "-serial dev redirect the serial port to char device 'dev'\n"
2150 "-S freeze CPU at startup (use 'c' to start execution)\n"
2151 "-s wait gdb connection to port %d\n"
2152 "-p port ioreq port for xen\n"
2153 "-d domain domain that we're serving\n"
2154 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2155 "-L path set the directory for the BIOS and VGA BIOS\n"
2156 #ifdef USE_CODE_COPY
2157 "-no-code-copy disable code copy acceleration\n"
2158 #endif
2159 #ifdef TARGET_I386
2160 "-isa simulate an ISA-only system (default is PCI system)\n"
2161 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2162 " (default is CL-GD5446 PCI VGA)\n"
2163 #endif
2164 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2165 "\n"
2166 "During emulation, the following keys are useful:\n"
2167 "ctrl-alt-f toggle full screen\n"
2168 "ctrl-alt-n switch to virtual console 'n'\n"
2169 "ctrl-alt toggle mouse and keyboard grab\n"
2170 "\n"
2171 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2173 #ifdef CONFIG_SOFTMMU
2174 "qemu",
2175 #else
2176 "qemu-fast",
2177 #endif
2178 DEFAULT_RAM_SIZE,
2179 DEFAULT_NETWORK_SCRIPT,
2180 DEFAULT_GDBSTUB_PORT);
2181 #ifndef CONFIG_SOFTMMU
2182 printf("\n"
2183 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2184 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2185 "PC emulation.\n");
2186 #endif
2187 exit(1);
2190 #define HAS_ARG 0x0001
2192 enum {
2193 QEMU_OPTION_h,
2195 QEMU_OPTION_fda,
2196 QEMU_OPTION_fdb,
2197 QEMU_OPTION_hda,
2198 QEMU_OPTION_hdb,
2199 QEMU_OPTION_hdc,
2200 QEMU_OPTION_hdd,
2201 QEMU_OPTION_cdrom,
2202 QEMU_OPTION_boot,
2203 QEMU_OPTION_snapshot,
2204 QEMU_OPTION_m,
2205 QEMU_OPTION_nographic,
2206 #ifdef CONFIG_VNC
2207 QEMU_OPTION_vnc,
2208 QEMU_OPTION_vncport,
2209 QEMU_OPTION_vncconnect,
2210 #ifdef CONFIG_SDL
2211 QEMU_OPTION_vnc_and_sdl,
2212 #endif
2213 #endif
2214 QEMU_OPTION_enable_audio,
2216 QEMU_OPTION_nics,
2217 QEMU_OPTION_macaddr,
2218 QEMU_OPTION_n,
2219 QEMU_OPTION_tun_fd,
2220 QEMU_OPTION_user_net,
2221 QEMU_OPTION_tftp,
2222 QEMU_OPTION_smb,
2223 QEMU_OPTION_redir,
2224 QEMU_OPTION_dummy_net,
2226 QEMU_OPTION_kernel,
2227 QEMU_OPTION_append,
2228 QEMU_OPTION_initrd,
2230 QEMU_OPTION_S,
2231 QEMU_OPTION_s,
2232 QEMU_OPTION_p,
2233 QEMU_OPTION_d,
2234 QEMU_OPTION_l,
2235 QEMU_OPTION_hdachs,
2236 QEMU_OPTION_L,
2237 QEMU_OPTION_no_code_copy,
2238 QEMU_OPTION_pci,
2239 QEMU_OPTION_nic_pcnet,
2240 QEMU_OPTION_isa,
2241 QEMU_OPTION_prep,
2242 QEMU_OPTION_k,
2243 QEMU_OPTION_localtime,
2244 QEMU_OPTION_cirrusvga,
2245 QEMU_OPTION_g,
2246 QEMU_OPTION_std_vga,
2247 QEMU_OPTION_monitor,
2248 QEMU_OPTION_serial,
2249 QEMU_OPTION_loadvm,
2250 QEMU_OPTION_full_screen,
2251 };
2253 typedef struct QEMUOption {
2254 const char *name;
2255 int flags;
2256 int index;
2257 } QEMUOption;
2259 const QEMUOption qemu_options[] = {
2260 { "h", 0, QEMU_OPTION_h },
2262 { "fda", HAS_ARG, QEMU_OPTION_fda },
2263 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2264 { "hda", HAS_ARG, QEMU_OPTION_hda },
2265 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2266 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2267 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2268 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2269 { "boot", HAS_ARG, QEMU_OPTION_boot },
2270 { "snapshot", 0, QEMU_OPTION_snapshot },
2271 { "m", HAS_ARG, QEMU_OPTION_m },
2272 { "nographic", 0, QEMU_OPTION_nographic },
2273 #ifdef CONFIG_VNC
2274 { "vnc", 0, QEMU_OPTION_vnc },
2275 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2276 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2277 #ifdef CONFIG_SDL
2278 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2279 #endif
2280 #endif
2281 { "k", HAS_ARG, QEMU_OPTION_k },
2282 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2284 { "nics", HAS_ARG, QEMU_OPTION_nics},
2285 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2286 { "n", HAS_ARG, QEMU_OPTION_n },
2287 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2288 #ifdef CONFIG_SLIRP
2289 { "user-net", 0, QEMU_OPTION_user_net },
2290 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2291 #ifndef _WIN32
2292 { "smb", HAS_ARG, QEMU_OPTION_smb },
2293 #endif
2294 { "redir", HAS_ARG, QEMU_OPTION_redir },
2295 #endif
2296 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2298 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2299 { "append", HAS_ARG, QEMU_OPTION_append },
2300 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2302 { "S", 0, QEMU_OPTION_S },
2303 { "s", 0, QEMU_OPTION_s },
2304 { "p", HAS_ARG, QEMU_OPTION_p },
2305 { "d", HAS_ARG, QEMU_OPTION_d },
2306 { "l", HAS_ARG, QEMU_OPTION_l },
2307 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2308 { "L", HAS_ARG, QEMU_OPTION_L },
2309 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2310 #ifdef TARGET_PPC
2311 { "prep", 0, QEMU_OPTION_prep },
2312 { "g", 1, QEMU_OPTION_g },
2313 #endif
2314 { "localtime", 0, QEMU_OPTION_localtime },
2315 { "isa", 0, QEMU_OPTION_isa },
2316 { "std-vga", 0, QEMU_OPTION_std_vga },
2317 { "monitor", 1, QEMU_OPTION_monitor },
2318 { "serial", 1, QEMU_OPTION_serial },
2319 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2320 { "full-screen", 0, QEMU_OPTION_full_screen },
2322 /* temporary options */
2323 { "pci", 0, QEMU_OPTION_pci },
2324 { "nic-pcnet", 0, QEMU_OPTION_nic_pcnet },
2325 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2326 { NULL },
2327 };
2329 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2331 /* this stack is only used during signal handling */
2332 #define SIGNAL_STACK_SIZE 32768
2334 static uint8_t *signal_stack;
2336 #endif
2338 #define NET_IF_TUN 0
2339 #define NET_IF_USER 1
2340 #define NET_IF_DUMMY 2
2342 int main(int argc, char **argv)
2344 #ifdef CONFIG_GDBSTUB
2345 int use_gdbstub, gdbstub_port;
2346 #endif
2347 int i, has_cdrom;
2348 int snapshot, linux_boot;
2349 CPUState *env;
2350 const char *initrd_filename;
2351 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2352 const char *kernel_filename, *kernel_cmdline;
2353 DisplayState *ds = &display_state;
2354 int cyls, heads, secs;
2355 int start_emulation = 1;
2356 uint8_t macaddr[6];
2357 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2358 int optind;
2359 const char *r, *optarg;
2360 CharDriverState *monitor_hd;
2361 char monitor_device[128];
2362 char serial_devices[MAX_SERIAL_PORTS][128];
2363 int serial_device_index;
2364 const char *loadvm = NULL;
2365 unsigned long nr_pages, *page_array;
2366 extern void *shared_page;
2367 /* change the qemu-dm to daemon, just like bochs dm */
2368 // daemon(0, 0);
2370 #if !defined(CONFIG_SOFTMMU)
2371 /* we never want that malloc() uses mmap() */
2372 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2373 #endif
2374 initrd_filename = NULL;
2375 for(i = 0; i < MAX_FD; i++)
2376 fd_filename[i] = NULL;
2377 for(i = 0; i < MAX_DISKS; i++)
2378 hd_filename[i] = NULL;
2379 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2380 vga_ram_size = VGA_RAM_SIZE;
2381 bios_size = BIOS_SIZE;
2382 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2383 #ifdef CONFIG_GDBSTUB
2384 use_gdbstub = 0;
2385 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2386 #endif
2387 snapshot = 0;
2388 nographic = 0;
2389 usevnc = 0;
2390 vncport=0;
2391 vncconnect=NULL;
2392 kernel_filename = NULL;
2393 kernel_cmdline = "";
2394 has_cdrom = 1;
2395 cyls = heads = secs = 0;
2396 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2398 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2399 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2400 serial_devices[i][0] = '\0';
2401 serial_device_index = 0;
2403 nb_tun_fds = 0;
2404 net_if_type = -1;
2405 nb_nics = 1;
2406 /* default mac address of the first network interface */
2407 macaddr[0] = 0x52;
2408 macaddr[1] = 0x54;
2409 macaddr[2] = 0x00;
2410 macaddr[3] = 0x12;
2411 macaddr[4] = 0x34;
2412 macaddr[5] = 0x56;
2414 /* init debug */
2415 cpu_set_log(0);
2417 optind = 1;
2418 for(;;) {
2419 if (optind >= argc)
2420 break;
2421 r = argv[optind];
2422 if (r[0] != '-') {
2423 hd_filename[0] = argv[optind++];
2424 } else {
2425 const QEMUOption *popt;
2427 optind++;
2428 popt = qemu_options;
2429 for(;;) {
2430 if (!popt->name) {
2431 fprintf(stderr, "%s: invalid option -- '%s'\n",
2432 argv[0], r);
2433 exit(1);
2435 if (!strcmp(popt->name, r + 1))
2436 break;
2437 popt++;
2439 if (popt->flags & HAS_ARG) {
2440 if (optind >= argc) {
2441 fprintf(stderr, "%s: option '%s' requires an argument\n",
2442 argv[0], r);
2443 exit(1);
2445 optarg = argv[optind++];
2446 } else {
2447 optarg = NULL;
2450 switch(popt->index) {
2451 case QEMU_OPTION_initrd:
2452 initrd_filename = optarg;
2453 break;
2454 case QEMU_OPTION_hda:
2455 hd_filename[0] = optarg;
2456 break;
2457 case QEMU_OPTION_hdb:
2458 hd_filename[1] = optarg;
2459 break;
2460 case QEMU_OPTION_snapshot:
2461 snapshot = 1;
2462 break;
2463 case QEMU_OPTION_hdachs:
2465 const char *p;
2466 p = optarg;
2467 cyls = strtol(p, (char **)&p, 0);
2468 if (*p != ',')
2469 goto chs_fail;
2470 p++;
2471 heads = strtol(p, (char **)&p, 0);
2472 if (*p != ',')
2473 goto chs_fail;
2474 p++;
2475 secs = strtol(p, (char **)&p, 0);
2476 if (*p != '\0') {
2477 chs_fail:
2478 cyls = 0;
2481 break;
2482 case QEMU_OPTION_nographic:
2483 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2484 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2485 nographic = 1;
2486 break;
2487 #ifdef CONFIG_VNC
2488 case QEMU_OPTION_vnc:
2489 usevnc = 1;
2490 break;
2491 case QEMU_OPTION_vncport:
2493 const char *p;
2494 p = optarg;
2495 vncport= strtol(optarg, (char **)&p, 0);
2497 break;
2498 case QEMU_OPTION_vncconnect:
2500 vncconnect=optarg;
2502 break;
2503 #ifdef CONFIG_SDL
2504 case QEMU_OPTION_vnc_and_sdl:
2505 usevnc = 2;
2506 break;
2507 #endif
2508 #endif
2509 case QEMU_OPTION_kernel:
2510 kernel_filename = optarg;
2511 break;
2512 case QEMU_OPTION_append:
2513 kernel_cmdline = optarg;
2514 break;
2515 case QEMU_OPTION_tun_fd:
2517 const char *p;
2518 int fd;
2519 net_if_type = NET_IF_TUN;
2520 if (nb_tun_fds < MAX_NICS) {
2521 fd = strtol(optarg, (char **)&p, 0);
2522 if (*p != '\0') {
2523 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2524 exit(1);
2526 tun_fds[nb_tun_fds++] = fd;
2529 break;
2530 case QEMU_OPTION_hdc:
2531 hd_filename[2] = optarg;
2532 has_cdrom = 0;
2533 break;
2534 case QEMU_OPTION_hdd:
2535 hd_filename[3] = optarg;
2536 break;
2537 case QEMU_OPTION_cdrom:
2538 hd_filename[2] = optarg;
2539 has_cdrom = 1;
2540 break;
2541 case QEMU_OPTION_boot:
2542 boot_device = optarg[0];
2543 if (boot_device != 'a' &&
2544 boot_device != 'c' && boot_device != 'd') {
2545 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2546 exit(1);
2548 break;
2549 case QEMU_OPTION_fda:
2550 fd_filename[0] = optarg;
2551 break;
2552 case QEMU_OPTION_fdb:
2553 fd_filename[1] = optarg;
2554 break;
2555 case QEMU_OPTION_nics:
2556 nb_nics = atoi(optarg);
2557 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2558 fprintf(stderr, "qemu: invalid number of network interfaces\n");
2559 exit(1);
2561 break;
2562 case QEMU_OPTION_macaddr:
2564 const char *p;
2565 int i;
2566 p = optarg;
2567 for(i = 0; i < 6; i++) {
2568 macaddr[i] = strtol(p, (char **)&p, 16);
2569 if (i == 5) {
2570 if (*p != '\0')
2571 goto macaddr_error;
2572 } else {
2573 if (*p != ':') {
2574 macaddr_error:
2575 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2576 exit(1);
2578 p++;
2582 break;
2583 #ifdef CONFIG_SLIRP
2584 case QEMU_OPTION_tftp:
2585 tftp_prefix = optarg;
2586 break;
2587 #ifndef _WIN32
2588 case QEMU_OPTION_smb:
2589 net_slirp_smb(optarg);
2590 break;
2591 #endif
2592 case QEMU_OPTION_user_net:
2593 net_if_type = NET_IF_USER;
2594 break;
2595 case QEMU_OPTION_redir:
2596 net_slirp_redir(optarg);
2597 break;
2598 #endif
2599 case QEMU_OPTION_dummy_net:
2600 net_if_type = NET_IF_DUMMY;
2601 break;
2602 case QEMU_OPTION_enable_audio:
2603 audio_enabled = 1;
2604 break;
2605 case QEMU_OPTION_h:
2606 help();
2607 break;
2608 case QEMU_OPTION_m:
2609 ram_size = atoi(optarg) * 1024 * 1024;
2610 if (ram_size <= 0)
2611 help();
2612 break;
2613 case QEMU_OPTION_d:
2615 domid = atoi(optarg);
2616 printf("domid: %d\n", domid);
2618 break;
2620 case QEMU_OPTION_p:
2622 extern short ioreq_port;
2623 ioreq_port = atoi(optarg);
2624 printf("port: %d\n", ioreq_port);
2626 break;
2627 case QEMU_OPTION_l:
2629 int mask;
2630 mask = cpu_str_to_log_mask(optarg);
2631 printf("mask: %x\n", mask);
2632 cpu_set_log(mask);
2634 break;
2635 case QEMU_OPTION_n:
2636 pstrcpy(network_script, sizeof(network_script), optarg);
2637 break;
2638 #ifdef CONFIG_GDBSTUB
2639 case QEMU_OPTION_s:
2640 use_gdbstub = 1;
2641 break;
2642 #endif
2643 case QEMU_OPTION_L:
2644 bios_dir = optarg;
2645 break;
2646 case QEMU_OPTION_S:
2647 start_emulation = 0;
2648 break;
2649 case QEMU_OPTION_pci:
2650 pci_enabled = 1;
2651 break;
2652 case QEMU_OPTION_nic_pcnet:
2653 nic_pcnet = 1;
2654 break;
2655 case QEMU_OPTION_isa:
2656 pci_enabled = 0;
2657 break;
2658 case QEMU_OPTION_prep:
2659 prep_enabled = 1;
2660 break;
2661 case QEMU_OPTION_k:
2662 keyboard_layout = optarg;
2663 break;
2664 case QEMU_OPTION_localtime:
2665 rtc_utc = 0;
2666 break;
2667 case QEMU_OPTION_cirrusvga:
2668 cirrus_vga_enabled = 1;
2669 break;
2670 case QEMU_OPTION_std_vga:
2671 cirrus_vga_enabled = 0;
2672 break;
2673 case QEMU_OPTION_g:
2675 const char *p;
2676 int w, h, depth;
2677 p = optarg;
2678 w = strtol(p, (char **)&p, 10);
2679 if (w <= 0) {
2680 graphic_error:
2681 fprintf(stderr, "qemu: invalid resolution or depth\n");
2682 exit(1);
2684 if (*p != 'x')
2685 goto graphic_error;
2686 p++;
2687 h = strtol(p, (char **)&p, 10);
2688 if (h <= 0)
2689 goto graphic_error;
2690 if (*p == 'x') {
2691 p++;
2692 depth = strtol(p, (char **)&p, 10);
2693 if (depth != 8 && depth != 15 && depth != 16 &&
2694 depth != 24 && depth != 32)
2695 goto graphic_error;
2696 } else if (*p == '\0') {
2697 depth = graphic_depth;
2698 } else {
2699 goto graphic_error;
2702 graphic_width = w;
2703 graphic_height = h;
2704 graphic_depth = depth;
2706 break;
2707 case QEMU_OPTION_monitor:
2708 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2709 break;
2710 case QEMU_OPTION_serial:
2711 if (serial_device_index >= MAX_SERIAL_PORTS) {
2712 fprintf(stderr, "qemu: too many serial ports\n");
2713 exit(1);
2715 pstrcpy(serial_devices[serial_device_index],
2716 sizeof(serial_devices[0]), optarg);
2717 serial_device_index++;
2718 break;
2719 case QEMU_OPTION_loadvm:
2720 loadvm = optarg;
2721 break;
2722 case QEMU_OPTION_full_screen:
2723 full_screen = 1;
2724 break;
2729 linux_boot = (kernel_filename != NULL);
2731 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2732 fd_filename[0] == '\0')
2733 help();
2735 /* boot to cd by default if no hard disk */
2736 if (hd_filename[0] == '\0' && boot_device == 'c') {
2737 if (fd_filename[0] != '\0')
2738 boot_device = 'a';
2739 else
2740 boot_device = 'd';
2743 #if !defined(CONFIG_SOFTMMU)
2744 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2746 static uint8_t stdout_buf[4096];
2747 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2749 #else
2750 setvbuf(stdout, NULL, _IOLBF, 0);
2751 #endif
2753 /* init host network redirectors */
2754 if (net_if_type == -1) {
2755 net_if_type = NET_IF_TUN;
2756 #if defined(CONFIG_SLIRP)
2757 if (access(network_script, R_OK) < 0) {
2758 net_if_type = NET_IF_USER;
2760 #endif
2763 for(i = 0; i < nb_nics; i++) {
2764 NetDriverState *nd = &nd_table[i];
2765 nd->index = i;
2766 /* init virtual mac address */
2767 nd->macaddr[0] = macaddr[0];
2768 nd->macaddr[1] = macaddr[1];
2769 nd->macaddr[2] = macaddr[2];
2770 nd->macaddr[3] = macaddr[3];
2771 nd->macaddr[4] = macaddr[4];
2772 nd->macaddr[5] = macaddr[5] + i;
2773 switch(net_if_type) {
2774 #if defined(CONFIG_SLIRP)
2775 case NET_IF_USER:
2776 net_slirp_init(nd);
2777 break;
2778 #endif
2779 #if !defined(_WIN32)
2780 case NET_IF_TUN:
2781 if (i < nb_tun_fds) {
2782 net_fd_init(nd, tun_fds[i]);
2783 } else {
2784 if (net_tun_init(nd) < 0)
2785 net_dummy_init(nd);
2787 break;
2788 #endif
2789 case NET_IF_DUMMY:
2790 default:
2791 net_dummy_init(nd);
2792 break;
2796 /* init the memory */
2797 phys_ram_size = ram_size + vga_ram_size + bios_size;
2799 #define PAGE_SHIFT 12
2800 #define PAGE_SIZE (1 << PAGE_SHIFT)
2802 nr_pages = ram_size/PAGE_SIZE;
2803 xc_handle = xc_interface_open();
2805 if ( (page_array = (unsigned long *)
2806 malloc(nr_pages * sizeof(unsigned long))) == NULL)
2808 perror("malloc");
2809 exit(-1);
2812 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
2814 perror("xc_get_pfn_list");
2815 exit(-1);
2818 if ((phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
2819 PROT_READ|PROT_WRITE,
2820 page_array,
2821 nr_pages - 1)) == 0) {
2822 perror("xc_map_foreign_batch");
2823 exit(-1);
2826 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
2827 PROT_READ|PROT_WRITE,
2828 page_array[nr_pages - 1]);
2831 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
2832 (page_array[nr_pages - 1]));
2834 /* we always create the cdrom drive, even if no disk is there */
2835 bdrv_init();
2836 if (has_cdrom) {
2837 bs_table[2] = bdrv_new("cdrom");
2838 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2841 /* open the virtual block devices */
2842 for(i = 0; i < MAX_DISKS; i++) {
2843 if (hd_filename[i]) {
2844 if (!bs_table[i]) {
2845 char buf[64];
2846 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2847 bs_table[i] = bdrv_new(buf);
2849 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2850 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
2851 hd_filename[i]);
2852 exit(1);
2854 if (i == 0 && cyls != 0)
2855 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2859 /* we always create at least one floppy disk */
2860 fd_table[0] = bdrv_new("fda");
2861 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2863 for(i = 0; i < MAX_FD; i++) {
2864 if (fd_filename[i]) {
2865 if (!fd_table[i]) {
2866 char buf[64];
2867 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2868 fd_table[i] = bdrv_new(buf);
2869 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2871 if (fd_filename[i] != '\0') {
2872 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2873 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2874 fd_filename[i]);
2875 exit(1);
2881 /* init CPU state */
2882 env = cpu_init();
2883 global_env = env;
2884 cpu_single_env = env;
2886 init_ioports();
2887 cpu_calibrate_ticks();
2889 /* terminal init */
2890 if (nographic) {
2891 dumb_display_init(ds);
2892 } else {
2893 if (usevnc) {
2894 #ifdef CONFIG_VNC
2895 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
2896 #else
2897 perror("qemu not configured with vnc support");
2898 #endif
2899 } else {
2900 #ifdef CONFIG_SDL
2901 sdl_display_init(ds, full_screen);
2902 #else
2903 dumb_display_init(ds);
2904 #endif
2908 vga_console = graphic_console_init(ds);
2910 monitor_hd = qemu_chr_open(monitor_device);
2911 if (!monitor_hd) {
2912 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
2913 exit(1);
2915 monitor_init(monitor_hd, !nographic);
2917 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
2918 if (serial_devices[i][0] != '\0') {
2919 serial_hds[i] = qemu_chr_open(serial_devices[i]);
2920 if (!serial_hds[i]) {
2921 fprintf(stderr, "qemu: could not open serial device '%s'\n",
2922 serial_devices[i]);
2923 exit(1);
2925 if (!strcmp(serial_devices[i], "vc"))
2926 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
2930 /* setup cpu signal handlers for MMU / self modifying code handling */
2931 #if !defined(CONFIG_SOFTMMU)
2933 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2935 stack_t stk;
2936 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2937 stk.ss_sp = signal_stack;
2938 stk.ss_size = SIGNAL_STACK_SIZE;
2939 stk.ss_flags = 0;
2941 if (sigaltstack(&stk, NULL) < 0) {
2942 perror("sigaltstack");
2943 exit(1);
2946 #endif
2948 struct sigaction act;
2950 sigfillset(&act.sa_mask);
2951 act.sa_flags = SA_SIGINFO;
2952 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2953 act.sa_flags |= SA_ONSTACK;
2954 #endif
2955 act.sa_sigaction = host_segv_handler;
2956 sigaction(SIGSEGV, &act, NULL);
2957 sigaction(SIGBUS, &act, NULL);
2958 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2959 sigaction(SIGFPE, &act, NULL);
2960 #endif
2962 #endif
2964 #ifndef _WIN32
2966 struct sigaction act;
2967 sigfillset(&act.sa_mask);
2968 act.sa_flags = 0;
2969 act.sa_handler = SIG_IGN;
2970 sigaction(SIGPIPE, &act, NULL);
2972 #endif
2973 init_timers();
2975 #if defined(TARGET_I386)
2976 pc_init(ram_size, vga_ram_size, boot_device,
2977 ds, fd_filename, snapshot,
2978 kernel_filename, kernel_cmdline, initrd_filename);
2979 #elif defined(TARGET_PPC)
2980 ppc_init(ram_size, vga_ram_size, boot_device,
2981 ds, fd_filename, snapshot,
2982 kernel_filename, kernel_cmdline, initrd_filename);
2983 #elif defined(TARGET_SPARC)
2984 sun4m_init(ram_size, vga_ram_size, boot_device,
2985 ds, fd_filename, snapshot,
2986 kernel_filename, kernel_cmdline, initrd_filename);
2987 #endif
2989 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2990 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2992 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
2993 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
2995 #ifdef CONFIG_GDBSTUB
2996 if (use_gdbstub) {
2997 if (gdbserver_start(gdbstub_port) < 0) {
2998 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
2999 gdbstub_port);
3000 exit(1);
3001 } else {
3002 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3004 } else
3005 #endif
3006 if (loadvm)
3007 qemu_loadvm(loadvm);
3010 /* XXX: simplify init */
3011 if (start_emulation) {
3012 vm_start();
3015 main_loop();
3016 quit_timers();
3017 return 0;