ia64/xen-unstable

view tools/ioemu/vl.c @ 6552:a9873d384da4

Merge.
author adsharma@los-vmm.sc.intel.com
date Thu Aug 25 12:24:48 2005 -0700 (2005-08-25)
parents 112d44270733 fa0754a9f64f
children dfaf788ab18c
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 va_end(ap);
417 abort();
418 }
420 /***********************************************************/
421 /* keyboard/mouse */
423 static QEMUPutKBDEvent *qemu_put_kbd_event;
424 static void *qemu_put_kbd_event_opaque;
425 static QEMUPutMouseEvent *qemu_put_mouse_event;
426 static void *qemu_put_mouse_event_opaque;
428 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
429 {
430 qemu_put_kbd_event_opaque = opaque;
431 qemu_put_kbd_event = func;
432 }
434 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
435 {
436 qemu_put_mouse_event_opaque = opaque;
437 qemu_put_mouse_event = func;
438 }
440 void kbd_put_keycode(int keycode)
441 {
442 if (qemu_put_kbd_event) {
443 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
444 }
445 }
447 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
448 {
449 if (qemu_put_mouse_event) {
450 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
451 dx, dy, dz, buttons_state);
452 }
453 }
455 /***********************************************************/
456 /* timers */
458 #if defined(__powerpc__)
460 static inline uint32_t get_tbl(void)
461 {
462 uint32_t tbl;
463 asm volatile("mftb %0" : "=r" (tbl));
464 return tbl;
465 }
467 static inline uint32_t get_tbu(void)
468 {
469 uint32_t tbl;
470 asm volatile("mftbu %0" : "=r" (tbl));
471 return tbl;
472 }
474 int64_t cpu_get_real_ticks(void)
475 {
476 uint32_t l, h, h1;
477 /* NOTE: we test if wrapping has occurred */
478 do {
479 h = get_tbu();
480 l = get_tbl();
481 h1 = get_tbu();
482 } while (h != h1);
483 return ((int64_t)h << 32) | l;
484 }
486 #elif defined(__i386__)
488 int64_t cpu_get_real_ticks(void)
489 {
490 int64_t val;
491 asm volatile ("rdtsc" : "=A" (val));
492 return val;
493 }
495 #elif defined(__x86_64__)
497 int64_t cpu_get_real_ticks(void)
498 {
499 uint32_t low,high;
500 int64_t val;
501 asm volatile("rdtsc" : "=a" (low), "=d" (high));
502 val = high;
503 val <<= 32;
504 val |= low;
505 return val;
506 }
508 #else
509 #error unsupported CPU
510 #endif
512 static int64_t cpu_ticks_offset;
513 static int cpu_ticks_enabled;
514 int64_t cpu_virt_tsc;
516 static inline int64_t cpu_get_ticks(void)
517 {
518 if (!cpu_ticks_enabled) {
519 return cpu_ticks_offset;
520 } else {
521 return cpu_get_real_ticks() + cpu_ticks_offset;
522 }
524 }
526 /* enable cpu_get_ticks() */
527 void cpu_enable_ticks(void)
528 {
529 if (!cpu_ticks_enabled) {
530 cpu_ticks_offset -= cpu_get_real_ticks();
531 cpu_ticks_enabled = 1;
532 }
533 }
535 /* disable cpu_get_ticks() : the clock is stopped. You must not call
536 cpu_get_ticks() after that. */
537 void cpu_disable_ticks(void)
538 {
539 if (cpu_ticks_enabled) {
540 cpu_ticks_offset = cpu_get_ticks();
541 cpu_ticks_enabled = 0;
542 }
543 }
545 static int64_t get_clock(void)
546 {
547 #ifdef _WIN32
548 struct _timeb tb;
549 _ftime(&tb);
550 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
551 #else
552 struct timeval tv;
553 gettimeofday(&tv, NULL);
554 return tv.tv_sec * 1000000LL + tv.tv_usec;
555 #endif
556 }
558 void cpu_calibrate_ticks(void)
559 {
560 int64_t usec, ticks;
562 usec = get_clock();
563 ticks = cpu_get_real_ticks();
564 #ifdef _WIN32
565 Sleep(50);
566 #else
567 usleep(50 * 1000);
568 #endif
569 usec = get_clock() - usec;
570 ticks = cpu_get_real_ticks() - ticks;
571 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
572 }
574 /* compute with 96 bit intermediate result: (a*b)/c */
575 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
576 {
577 union {
578 uint64_t ll;
579 struct {
580 #ifdef WORDS_BIGENDIAN
581 uint32_t high, low;
582 #else
583 uint32_t low, high;
584 #endif
585 } l;
586 } u, res;
587 uint64_t rl, rh;
589 u.ll = a;
590 rl = (uint64_t)u.l.low * (uint64_t)b;
591 rh = (uint64_t)u.l.high * (uint64_t)b;
592 rh += (rl >> 32);
593 res.l.high = rh / c;
594 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
595 return res.ll;
596 }
598 #define QEMU_TIMER_REALTIME 0
599 #define QEMU_TIMER_VIRTUAL 1
601 struct QEMUClock {
602 int type;
603 /* XXX: add frequency */
604 };
606 struct QEMUTimer {
607 QEMUClock *clock;
608 int64_t expire_time;
609 QEMUTimerCB *cb;
610 void *opaque;
611 struct QEMUTimer *next;
612 };
614 QEMUClock *rt_clock;
615 QEMUClock *vm_clock;
617 static QEMUTimer *active_timers[2];
618 #ifdef _WIN32
619 static MMRESULT timerID;
620 #else
621 /* frequency of the times() clock tick */
622 static int timer_freq;
623 #endif
625 QEMUClock *qemu_new_clock(int type)
626 {
627 QEMUClock *clock;
628 clock = qemu_mallocz(sizeof(QEMUClock));
629 if (!clock)
630 return NULL;
631 clock->type = type;
632 return clock;
633 }
635 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
636 {
637 QEMUTimer *ts;
639 ts = qemu_mallocz(sizeof(QEMUTimer));
640 ts->clock = clock;
641 ts->cb = cb;
642 ts->opaque = opaque;
643 return ts;
644 }
646 void qemu_free_timer(QEMUTimer *ts)
647 {
648 qemu_free(ts);
649 }
651 /* stop a timer, but do not dealloc it */
652 void qemu_del_timer(QEMUTimer *ts)
653 {
654 QEMUTimer **pt, *t;
656 /* NOTE: this code must be signal safe because
657 qemu_timer_expired() can be called from a signal. */
658 pt = &active_timers[ts->clock->type];
659 for(;;) {
660 t = *pt;
661 if (!t)
662 break;
663 if (t == ts) {
664 *pt = t->next;
665 break;
666 }
667 pt = &t->next;
668 }
669 }
671 /* modify the current timer so that it will be fired when current_time
672 >= expire_time. The corresponding callback will be called. */
673 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
674 {
675 QEMUTimer **pt, *t;
677 qemu_del_timer(ts);
679 /* add the timer in the sorted list */
680 /* NOTE: this code must be signal safe because
681 qemu_timer_expired() can be called from a signal. */
682 pt = &active_timers[ts->clock->type];
683 for(;;) {
684 t = *pt;
685 if (!t)
686 break;
687 if (t->expire_time > expire_time)
688 break;
689 pt = &t->next;
690 }
691 ts->expire_time = expire_time;
692 ts->next = *pt;
693 *pt = ts;
694 }
696 int qemu_timer_pending(QEMUTimer *ts)
697 {
698 QEMUTimer *t;
699 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
700 if (t == ts)
701 return 1;
702 }
703 return 0;
704 }
706 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
707 {
708 if (!timer_head)
709 return 0;
710 return (timer_head->expire_time <= current_time);
711 }
713 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
714 {
715 QEMUTimer *ts;
717 for(;;) {
718 ts = *ptimer_head;
719 if (!ts || ts->expire_time > current_time)
720 break;
721 /* remove timer from the list before calling the callback */
722 *ptimer_head = ts->next;
723 ts->next = NULL;
725 /* run the callback (the timer list can be modified) */
726 ts->cb(ts->opaque);
727 }
728 }
730 int64_t qemu_get_clock(QEMUClock *clock)
731 {
732 switch(clock->type) {
733 case QEMU_TIMER_REALTIME:
734 #ifdef _WIN32
735 return GetTickCount();
736 #else
737 {
738 struct tms tp;
740 /* Note that using gettimeofday() is not a good solution
741 for timers because its value change when the date is
742 modified. */
743 if (timer_freq == 100) {
744 return times(&tp) * 10;
745 } else {
746 return ((int64_t)times(&tp) * 1000) / timer_freq;
747 }
748 }
749 #endif
750 default:
751 case QEMU_TIMER_VIRTUAL:
752 return cpu_get_ticks();
753 }
754 }
756 /* save a timer */
757 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
758 {
759 uint64_t expire_time;
761 if (qemu_timer_pending(ts)) {
762 expire_time = ts->expire_time;
763 } else {
764 expire_time = -1;
765 }
766 qemu_put_be64(f, expire_time);
767 }
769 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
770 {
771 uint64_t expire_time;
773 expire_time = qemu_get_be64(f);
774 if (expire_time != -1) {
775 qemu_mod_timer(ts, expire_time);
776 } else {
777 qemu_del_timer(ts);
778 }
779 }
781 static void init_timers(void)
782 {
783 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
784 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
786 #ifdef _WIN32
787 {
788 int count=0;
789 timerID = timeSetEvent(10, // interval (ms)
790 0, // resolution
791 host_alarm_handler, // function
792 (DWORD)&count, // user parameter
793 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
794 if( !timerID ) {
795 perror("failed timer alarm");
796 exit(1);
797 }
798 }
799 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
800 #else
801 {
802 /* get times() syscall frequency */
803 timer_freq = sysconf(_SC_CLK_TCK);
805 #ifndef TARGET_VMX
806 /* timer signal */
807 sigfillset(&act.sa_mask);
808 act.sa_flags = 0;
809 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
810 act.sa_flags |= SA_ONSTACK;
811 #endif
812 act.sa_handler = host_alarm_handler;
813 sigaction(SIGALRM, &act, NULL);
815 itv.it_interval.tv_sec = 0;
816 itv.it_interval.tv_usec = 1000;
817 itv.it_value.tv_sec = 0;
818 itv.it_value.tv_usec = 10 * 1000;
819 setitimer(ITIMER_REAL, &itv, NULL);
820 /* we probe the tick duration of the kernel to inform the user if
821 the emulated kernel requested a too high timer frequency */
822 getitimer(ITIMER_REAL, &itv);
824 #if defined(__linux__)
825 if (itv.it_interval.tv_usec > 1000) {
826 /* try to use /dev/rtc to have a faster timer */
827 if (start_rtc_timer() < 0)
828 goto use_itimer;
829 /* disable itimer */
830 itv.it_interval.tv_sec = 0;
831 itv.it_interval.tv_usec = 0;
832 itv.it_value.tv_sec = 0;
833 itv.it_value.tv_usec = 0;
834 setitimer(ITIMER_REAL, &itv, NULL);
836 /* use the RTC */
837 sigaction(SIGIO, &act, NULL);
838 fcntl(rtc_fd, F_SETFL, O_ASYNC);
839 fcntl(rtc_fd, F_SETOWN, getpid());
840 } else
841 #endif /* defined(__linux__) */
842 {
843 use_itimer:
844 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
845 PIT_FREQ) / 1000000;
846 }
847 #endif /* TARGET_VMX */
848 }
849 #endif
850 }
852 void quit_timers(void)
853 {
854 #ifdef _WIN32
855 timeKillEvent(timerID);
856 #endif
857 }
859 /***********************************************************/
860 /* character device */
862 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
863 {
864 return s->chr_write(s, buf, len);
865 }
867 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
868 {
869 char buf[4096];
870 va_list ap;
871 va_start(ap, fmt);
872 vsnprintf(buf, sizeof(buf), fmt, ap);
873 qemu_chr_write(s, buf, strlen(buf));
874 va_end(ap);
875 }
877 void qemu_chr_send_event(CharDriverState *s, int event)
878 {
879 if (s->chr_send_event)
880 s->chr_send_event(s, event);
881 }
883 void qemu_chr_add_read_handler(CharDriverState *s,
884 IOCanRWHandler *fd_can_read,
885 IOReadHandler *fd_read, void *opaque)
886 {
887 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
888 }
890 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
891 {
892 s->chr_event = chr_event;
893 }
895 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
896 {
897 return len;
898 }
900 static void null_chr_add_read_handler(CharDriverState *chr,
901 IOCanRWHandler *fd_can_read,
902 IOReadHandler *fd_read, void *opaque)
903 {
904 }
906 CharDriverState *qemu_chr_open_null(void)
907 {
908 CharDriverState *chr;
910 chr = qemu_mallocz(sizeof(CharDriverState));
911 if (!chr)
912 return NULL;
913 chr->chr_write = null_chr_write;
914 chr->chr_add_read_handler = null_chr_add_read_handler;
915 return chr;
916 }
918 #ifndef _WIN32
920 typedef struct {
921 int fd_in, fd_out;
922 /* for nographic stdio only */
923 IOCanRWHandler *fd_can_read;
924 IOReadHandler *fd_read;
925 void *fd_opaque;
926 } FDCharDriver;
928 #define STDIO_MAX_CLIENTS 2
930 static int stdio_nb_clients;
931 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
933 static int unix_write(int fd, const uint8_t *buf, int len1)
934 {
935 int ret, len;
937 len = len1;
938 while (len > 0) {
939 ret = write(fd, buf, len);
940 if (ret < 0) {
941 if (errno != EINTR && errno != EAGAIN)
942 return -1;
943 } else if (ret == 0) {
944 break;
945 } else {
946 buf += ret;
947 len -= ret;
948 }
949 }
950 return len1 - len;
951 }
953 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
954 {
955 FDCharDriver *s = chr->opaque;
956 return unix_write(s->fd_out, buf, len);
957 }
959 static void fd_chr_add_read_handler(CharDriverState *chr,
960 IOCanRWHandler *fd_can_read,
961 IOReadHandler *fd_read, void *opaque)
962 {
963 FDCharDriver *s = chr->opaque;
965 if (nographic && s->fd_in == 0) {
966 s->fd_can_read = fd_can_read;
967 s->fd_read = fd_read;
968 s->fd_opaque = opaque;
969 } else {
970 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
971 }
972 }
974 /* open a character device to a unix fd */
975 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
976 {
977 CharDriverState *chr;
978 FDCharDriver *s;
980 chr = qemu_mallocz(sizeof(CharDriverState));
981 if (!chr)
982 return NULL;
983 s = qemu_mallocz(sizeof(FDCharDriver));
984 if (!s) {
985 free(chr);
986 return NULL;
987 }
988 s->fd_in = fd_in;
989 s->fd_out = fd_out;
990 chr->opaque = s;
991 chr->chr_write = fd_chr_write;
992 chr->chr_add_read_handler = fd_chr_add_read_handler;
993 return chr;
994 }
996 /* for STDIO, we handle the case where several clients use it
997 (nographic mode) */
999 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1001 static int term_got_escape, client_index;
1003 void term_print_help(void)
1005 printf("\n"
1006 "C-a h print this help\n"
1007 "C-a x exit emulator\n"
1008 "C-a s save disk data back to file (if -snapshot)\n"
1009 "C-a b send break (magic sysrq)\n"
1010 "C-a c switch between console and monitor\n"
1011 "C-a C-a send C-a\n"
1012 );
1015 /* called when a char is received */
1016 static void stdio_received_byte(int ch)
1018 if (term_got_escape) {
1019 term_got_escape = 0;
1020 switch(ch) {
1021 case 'h':
1022 term_print_help();
1023 break;
1024 case 'x':
1025 exit(0);
1026 break;
1027 case 's':
1029 int i;
1030 for (i = 0; i < MAX_DISKS; i++) {
1031 if (bs_table[i])
1032 bdrv_commit(bs_table[i]);
1035 break;
1036 case 'b':
1037 if (client_index < stdio_nb_clients) {
1038 CharDriverState *chr;
1039 FDCharDriver *s;
1041 chr = stdio_clients[client_index];
1042 s = chr->opaque;
1043 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1045 break;
1046 case 'c':
1047 client_index++;
1048 if (client_index >= stdio_nb_clients)
1049 client_index = 0;
1050 if (client_index == 0) {
1051 /* send a new line in the monitor to get the prompt */
1052 ch = '\r';
1053 goto send_char;
1055 break;
1056 case TERM_ESCAPE:
1057 goto send_char;
1059 } else if (ch == TERM_ESCAPE) {
1060 term_got_escape = 1;
1061 } else {
1062 send_char:
1063 if (client_index < stdio_nb_clients) {
1064 uint8_t buf[1];
1065 CharDriverState *chr;
1066 FDCharDriver *s;
1068 chr = stdio_clients[client_index];
1069 s = chr->opaque;
1070 buf[0] = ch;
1071 /* XXX: should queue the char if the device is not
1072 ready */
1073 if (s->fd_can_read(s->fd_opaque) > 0)
1074 s->fd_read(s->fd_opaque, buf, 1);
1079 static int stdio_can_read(void *opaque)
1081 /* XXX: not strictly correct */
1082 return 1;
1085 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1087 int i;
1088 for(i = 0; i < size; i++)
1089 stdio_received_byte(buf[i]);
1092 /* init terminal so that we can grab keys */
1093 static struct termios oldtty;
1094 static int old_fd0_flags;
1096 static void term_exit(void)
1098 tcsetattr (0, TCSANOW, &oldtty);
1099 fcntl(0, F_SETFL, old_fd0_flags);
1102 static void term_init(void)
1104 struct termios tty;
1106 tcgetattr (0, &tty);
1107 oldtty = tty;
1108 old_fd0_flags = fcntl(0, F_GETFL);
1110 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1111 |INLCR|IGNCR|ICRNL|IXON);
1112 tty.c_oflag |= OPOST;
1113 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1114 /* if graphical mode, we allow Ctrl-C handling */
1115 if (nographic)
1116 tty.c_lflag &= ~ISIG;
1117 tty.c_cflag &= ~(CSIZE|PARENB);
1118 tty.c_cflag |= CS8;
1119 tty.c_cc[VMIN] = 1;
1120 tty.c_cc[VTIME] = 0;
1122 tcsetattr (0, TCSANOW, &tty);
1124 atexit(term_exit);
1126 fcntl(0, F_SETFL, O_NONBLOCK);
1129 CharDriverState *qemu_chr_open_stdio(void)
1131 CharDriverState *chr;
1133 if (nographic) {
1134 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1135 return NULL;
1136 chr = qemu_chr_open_fd(0, 1);
1137 if (stdio_nb_clients == 0)
1138 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1139 client_index = stdio_nb_clients;
1140 } else {
1141 if (stdio_nb_clients != 0)
1142 return NULL;
1143 chr = qemu_chr_open_fd(0, 1);
1145 stdio_clients[stdio_nb_clients++] = chr;
1146 if (stdio_nb_clients == 1) {
1147 /* set the terminal in raw mode */
1148 term_init();
1150 return chr;
1153 #if defined(__linux__)
1154 CharDriverState *qemu_chr_open_pty(void)
1156 char slave_name[1024];
1157 int master_fd, slave_fd;
1159 /* Not satisfying */
1160 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1161 return NULL;
1163 fprintf(stderr, "char device redirected to %s\n", slave_name);
1164 return qemu_chr_open_fd(master_fd, master_fd);
1166 #else
1167 CharDriverState *qemu_chr_open_pty(void)
1169 return NULL;
1171 #endif
1173 #endif /* !defined(_WIN32) */
1175 CharDriverState *qemu_chr_open(const char *filename)
1177 if (!strcmp(filename, "vc")) {
1178 return text_console_init(&display_state);
1179 } else if (!strcmp(filename, "null")) {
1180 return qemu_chr_open_null();
1181 } else
1182 #ifndef _WIN32
1183 if (!strcmp(filename, "pty")) {
1184 return qemu_chr_open_pty();
1185 } else if (!strcmp(filename, "stdio")) {
1186 return qemu_chr_open_stdio();
1187 } else
1188 #endif
1190 return NULL;
1194 /***********************************************************/
1195 /* Linux network device redirectors */
1197 void hex_dump(FILE *f, const uint8_t *buf, int size)
1199 int len, i, j, c;
1201 for(i=0;i<size;i+=16) {
1202 len = size - i;
1203 if (len > 16)
1204 len = 16;
1205 fprintf(f, "%08x ", i);
1206 for(j=0;j<16;j++) {
1207 if (j < len)
1208 fprintf(f, " %02x", buf[i+j]);
1209 else
1210 fprintf(f, " ");
1212 fprintf(f, " ");
1213 for(j=0;j<len;j++) {
1214 c = buf[i+j];
1215 if (c < ' ' || c > '~')
1216 c = '.';
1217 fprintf(f, "%c", c);
1219 fprintf(f, "\n");
1223 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1225 nd->send_packet(nd, buf, size);
1228 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1229 IOReadHandler *fd_read, void *opaque)
1231 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1234 /* dummy network adapter */
1236 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1240 static void dummy_add_read_packet(NetDriverState *nd,
1241 IOCanRWHandler *fd_can_read,
1242 IOReadHandler *fd_read, void *opaque)
1246 static int net_dummy_init(NetDriverState *nd)
1248 nd->send_packet = dummy_send_packet;
1249 nd->add_read_packet = dummy_add_read_packet;
1250 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1251 return 0;
1254 #if defined(CONFIG_SLIRP)
1256 /* slirp network adapter */
1258 static void *slirp_fd_opaque;
1259 static IOCanRWHandler *slirp_fd_can_read;
1260 static IOReadHandler *slirp_fd_read;
1261 static int slirp_inited;
1263 int slirp_can_output(void)
1265 return slirp_fd_can_read(slirp_fd_opaque);
1268 void slirp_output(const uint8_t *pkt, int pkt_len)
1270 #if 0
1271 printf("output:\n");
1272 hex_dump(stdout, pkt, pkt_len);
1273 #endif
1274 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1277 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1279 #if 0
1280 printf("input:\n");
1281 hex_dump(stdout, buf, size);
1282 #endif
1283 slirp_input(buf, size);
1286 static void slirp_add_read_packet(NetDriverState *nd,
1287 IOCanRWHandler *fd_can_read,
1288 IOReadHandler *fd_read, void *opaque)
1290 slirp_fd_opaque = opaque;
1291 slirp_fd_can_read = fd_can_read;
1292 slirp_fd_read = fd_read;
1295 static int net_slirp_init(NetDriverState *nd)
1297 if (!slirp_inited) {
1298 slirp_inited = 1;
1299 slirp_init();
1301 nd->send_packet = slirp_send_packet;
1302 nd->add_read_packet = slirp_add_read_packet;
1303 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1304 return 0;
1307 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1309 const char *p, *p1;
1310 int len;
1311 p = *pp;
1312 p1 = strchr(p, sep);
1313 if (!p1)
1314 return -1;
1315 len = p1 - p;
1316 p1++;
1317 if (buf_size > 0) {
1318 if (len > buf_size - 1)
1319 len = buf_size - 1;
1320 memcpy(buf, p, len);
1321 buf[len] = '\0';
1323 *pp = p1;
1324 return 0;
1327 static void net_slirp_redir(const char *redir_str)
1329 int is_udp;
1330 char buf[256], *r;
1331 const char *p;
1332 struct in_addr guest_addr;
1333 int host_port, guest_port;
1335 if (!slirp_inited) {
1336 slirp_inited = 1;
1337 slirp_init();
1340 p = redir_str;
1341 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1342 goto fail;
1343 if (!strcmp(buf, "tcp")) {
1344 is_udp = 0;
1345 } else if (!strcmp(buf, "udp")) {
1346 is_udp = 1;
1347 } else {
1348 goto fail;
1351 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1352 goto fail;
1353 host_port = strtol(buf, &r, 0);
1354 if (r == buf)
1355 goto fail;
1357 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1358 goto fail;
1359 if (buf[0] == '\0') {
1360 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1362 if (!inet_aton(buf, &guest_addr))
1363 goto fail;
1365 guest_port = strtol(p, &r, 0);
1366 if (r == p)
1367 goto fail;
1369 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1370 fprintf(stderr, "qemu: could not set up redirection\n");
1371 exit(1);
1373 return;
1374 fail:
1375 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1376 exit(1);
1379 #ifndef _WIN32
1381 char smb_dir[1024];
1383 static void smb_exit(void)
1385 DIR *d;
1386 struct dirent *de;
1387 char filename[1024];
1389 /* erase all the files in the directory */
1390 d = opendir(smb_dir);
1391 for(;;) {
1392 de = readdir(d);
1393 if (!de)
1394 break;
1395 if (strcmp(de->d_name, ".") != 0 &&
1396 strcmp(de->d_name, "..") != 0) {
1397 snprintf(filename, sizeof(filename), "%s/%s",
1398 smb_dir, de->d_name);
1399 unlink(filename);
1402 closedir(d);
1403 rmdir(smb_dir);
1406 /* automatic user mode samba server configuration */
1407 void net_slirp_smb(const char *exported_dir)
1409 char smb_conf[1024];
1410 char smb_cmdline[1024];
1411 FILE *f;
1413 if (!slirp_inited) {
1414 slirp_inited = 1;
1415 slirp_init();
1418 /* XXX: better tmp dir construction */
1419 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1420 if (mkdir(smb_dir, 0700) < 0) {
1421 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1422 exit(1);
1424 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1426 f = fopen(smb_conf, "w");
1427 if (!f) {
1428 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1429 exit(1);
1431 fprintf(f,
1432 "[global]\n"
1433 "pid directory=%s\n"
1434 "lock directory=%s\n"
1435 "log file=%s/log.smbd\n"
1436 "smb passwd file=%s/smbpasswd\n"
1437 "security = share\n"
1438 "[qemu]\n"
1439 "path=%s\n"
1440 "read only=no\n"
1441 "guest ok=yes\n",
1442 smb_dir,
1443 smb_dir,
1444 smb_dir,
1445 smb_dir,
1446 exported_dir
1447 );
1448 fclose(f);
1449 atexit(smb_exit);
1451 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1452 smb_conf);
1454 slirp_add_exec(0, smb_cmdline, 4, 139);
1457 #endif /* !defined(_WIN32) */
1459 #endif /* CONFIG_SLIRP */
1461 #if !defined(_WIN32)
1462 #ifdef _BSD
1463 static int tun_open(char *ifname, int ifname_size)
1465 int fd;
1466 char *dev;
1467 struct stat s;
1469 fd = open("/dev/tap", O_RDWR);
1470 if (fd < 0) {
1471 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1472 return -1;
1475 fstat(fd, &s);
1476 dev = devname(s.st_rdev, S_IFCHR);
1477 pstrcpy(ifname, ifname_size, dev);
1479 fcntl(fd, F_SETFL, O_NONBLOCK);
1480 return fd;
1482 #else
1483 static int tun_open(char *ifname, int ifname_size)
1485 struct ifreq ifr;
1486 int fd, ret;
1488 fd = open("/dev/net/tun", O_RDWR);
1489 if (fd < 0) {
1490 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1491 return -1;
1493 memset(&ifr, 0, sizeof(ifr));
1494 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1495 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1496 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1497 if (ret != 0) {
1498 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1499 close(fd);
1500 return -1;
1502 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1503 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1504 fcntl(fd, F_SETFL, O_NONBLOCK);
1505 return fd;
1507 #endif
1509 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1511 write(nd->fd, buf, size);
1514 static void tun_add_read_packet(NetDriverState *nd,
1515 IOCanRWHandler *fd_can_read,
1516 IOReadHandler *fd_read, void *opaque)
1518 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1521 static int net_tun_init(NetDriverState *nd)
1523 int pid, status;
1524 char *args[3];
1525 char **parg;
1527 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1528 if (nd->fd < 0)
1529 return -1;
1531 /* try to launch network init script */
1532 pid = fork();
1533 if (pid >= 0) {
1534 if (pid == 0) {
1535 parg = args;
1536 *parg++ = network_script;
1537 *parg++ = nd->ifname;
1538 *parg++ = NULL;
1539 execv(network_script, args);
1540 exit(1);
1542 while (waitpid(pid, &status, 0) != pid);
1543 if (!WIFEXITED(status) ||
1544 WEXITSTATUS(status) != 0) {
1545 fprintf(stderr, "%s: could not launch network script\n",
1546 network_script);
1549 nd->send_packet = tun_send_packet;
1550 nd->add_read_packet = tun_add_read_packet;
1551 return 0;
1554 static int net_fd_init(NetDriverState *nd, int fd)
1556 nd->fd = fd;
1557 nd->send_packet = tun_send_packet;
1558 nd->add_read_packet = tun_add_read_packet;
1559 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1560 return 0;
1563 #endif /* !_WIN32 */
1565 /***********************************************************/
1566 /* dumb display */
1568 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1572 static void dumb_resize(DisplayState *ds, int w, int h)
1576 static void dumb_refresh(DisplayState *ds)
1578 vga_update_display();
1581 void dumb_display_init(DisplayState *ds)
1583 ds->data = NULL;
1584 ds->linesize = 0;
1585 ds->depth = 0;
1586 ds->dpy_update = dumb_update;
1587 ds->dpy_resize = dumb_resize;
1588 ds->dpy_refresh = dumb_refresh;
1591 #if !defined(CONFIG_SOFTMMU)
1592 /***********************************************************/
1593 /* cpu signal handler */
1594 static void host_segv_handler(int host_signum, siginfo_t *info,
1595 void *puc)
1597 abort();
1599 #endif
1601 /***********************************************************/
1602 /* I/O handling */
1604 #define MAX_IO_HANDLERS 64
1606 typedef struct IOHandlerRecord {
1607 int fd;
1608 IOCanRWHandler *fd_can_read;
1609 IOReadHandler *fd_read;
1610 void *opaque;
1611 /* temporary data */
1612 struct pollfd *ufd;
1613 int max_size;
1614 struct IOHandlerRecord *next;
1615 } IOHandlerRecord;
1617 static IOHandlerRecord *first_io_handler;
1619 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1620 IOReadHandler *fd_read, void *opaque)
1622 IOHandlerRecord *ioh;
1624 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1625 if (!ioh)
1626 return -1;
1627 ioh->fd = fd;
1628 ioh->fd_can_read = fd_can_read;
1629 ioh->fd_read = fd_read;
1630 ioh->opaque = opaque;
1631 ioh->next = first_io_handler;
1632 first_io_handler = ioh;
1633 return 0;
1636 void qemu_del_fd_read_handler(int fd)
1638 IOHandlerRecord **pioh, *ioh;
1640 pioh = &first_io_handler;
1641 for(;;) {
1642 ioh = *pioh;
1643 if (ioh == NULL)
1644 break;
1645 if (ioh->fd == fd) {
1646 *pioh = ioh->next;
1647 break;
1649 pioh = &ioh->next;
1653 /***********************************************************/
1654 /* savevm/loadvm support */
1656 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1658 fwrite(buf, 1, size, f);
1661 void qemu_put_byte(QEMUFile *f, int v)
1663 fputc(v, f);
1666 void qemu_put_be16(QEMUFile *f, unsigned int v)
1668 qemu_put_byte(f, v >> 8);
1669 qemu_put_byte(f, v);
1672 void qemu_put_be32(QEMUFile *f, unsigned int v)
1674 qemu_put_byte(f, v >> 24);
1675 qemu_put_byte(f, v >> 16);
1676 qemu_put_byte(f, v >> 8);
1677 qemu_put_byte(f, v);
1680 void qemu_put_be64(QEMUFile *f, uint64_t v)
1682 qemu_put_be32(f, v >> 32);
1683 qemu_put_be32(f, v);
1686 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1688 return fread(buf, 1, size, f);
1691 int qemu_get_byte(QEMUFile *f)
1693 int v;
1694 v = fgetc(f);
1695 if (v == EOF)
1696 return 0;
1697 else
1698 return v;
1701 unsigned int qemu_get_be16(QEMUFile *f)
1703 unsigned int v;
1704 v = qemu_get_byte(f) << 8;
1705 v |= qemu_get_byte(f);
1706 return v;
1709 unsigned int qemu_get_be32(QEMUFile *f)
1711 unsigned int v;
1712 v = qemu_get_byte(f) << 24;
1713 v |= qemu_get_byte(f) << 16;
1714 v |= qemu_get_byte(f) << 8;
1715 v |= qemu_get_byte(f);
1716 return v;
1719 uint64_t qemu_get_be64(QEMUFile *f)
1721 uint64_t v;
1722 v = (uint64_t)qemu_get_be32(f) << 32;
1723 v |= qemu_get_be32(f);
1724 return v;
1727 int64_t qemu_ftell(QEMUFile *f)
1729 return ftell(f);
1732 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1734 if (fseek(f, pos, whence) < 0)
1735 return -1;
1736 return ftell(f);
1739 typedef struct SaveStateEntry {
1740 char idstr[256];
1741 int instance_id;
1742 int version_id;
1743 SaveStateHandler *save_state;
1744 LoadStateHandler *load_state;
1745 void *opaque;
1746 struct SaveStateEntry *next;
1747 } SaveStateEntry;
1749 static SaveStateEntry *first_se;
1751 int register_savevm(const char *idstr,
1752 int instance_id,
1753 int version_id,
1754 SaveStateHandler *save_state,
1755 LoadStateHandler *load_state,
1756 void *opaque)
1758 SaveStateEntry *se, **pse;
1760 se = qemu_malloc(sizeof(SaveStateEntry));
1761 if (!se)
1762 return -1;
1763 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1764 se->instance_id = instance_id;
1765 se->version_id = version_id;
1766 se->save_state = save_state;
1767 se->load_state = load_state;
1768 se->opaque = opaque;
1769 se->next = NULL;
1771 /* add at the end of list */
1772 pse = &first_se;
1773 while (*pse != NULL)
1774 pse = &(*pse)->next;
1775 *pse = se;
1776 return 0;
1779 #define QEMU_VM_FILE_MAGIC 0x5145564d
1780 #define QEMU_VM_FILE_VERSION 0x00000001
1782 int qemu_savevm(const char *filename)
1784 SaveStateEntry *se;
1785 QEMUFile *f;
1786 int len, len_pos, cur_pos, saved_vm_running, ret;
1788 saved_vm_running = vm_running;
1789 vm_stop(0);
1791 f = fopen(filename, "wb");
1792 if (!f) {
1793 ret = -1;
1794 goto the_end;
1797 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1798 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1800 for(se = first_se; se != NULL; se = se->next) {
1801 /* ID string */
1802 len = strlen(se->idstr);
1803 qemu_put_byte(f, len);
1804 qemu_put_buffer(f, se->idstr, len);
1806 qemu_put_be32(f, se->instance_id);
1807 qemu_put_be32(f, se->version_id);
1809 /* record size: filled later */
1810 len_pos = ftell(f);
1811 qemu_put_be32(f, 0);
1813 se->save_state(f, se->opaque);
1815 /* fill record size */
1816 cur_pos = ftell(f);
1817 len = ftell(f) - len_pos - 4;
1818 fseek(f, len_pos, SEEK_SET);
1819 qemu_put_be32(f, len);
1820 fseek(f, cur_pos, SEEK_SET);
1823 fclose(f);
1824 ret = 0;
1825 the_end:
1826 if (saved_vm_running)
1827 vm_start();
1828 return ret;
1831 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1833 SaveStateEntry *se;
1835 for(se = first_se; se != NULL; se = se->next) {
1836 if (!strcmp(se->idstr, idstr) &&
1837 instance_id == se->instance_id)
1838 return se;
1840 return NULL;
1843 int qemu_loadvm(const char *filename)
1845 SaveStateEntry *se;
1846 QEMUFile *f;
1847 int len, cur_pos, ret, instance_id, record_len, version_id;
1848 int saved_vm_running;
1849 unsigned int v;
1850 char idstr[256];
1852 saved_vm_running = vm_running;
1853 vm_stop(0);
1855 f = fopen(filename, "rb");
1856 if (!f) {
1857 ret = -1;
1858 goto the_end;
1861 v = qemu_get_be32(f);
1862 if (v != QEMU_VM_FILE_MAGIC)
1863 goto fail;
1864 v = qemu_get_be32(f);
1865 if (v != QEMU_VM_FILE_VERSION) {
1866 fail:
1867 fclose(f);
1868 ret = -1;
1869 goto the_end;
1871 for(;;) {
1872 #if defined (DO_TB_FLUSH)
1873 tb_flush(global_env);
1874 #endif
1875 len = qemu_get_byte(f);
1876 if (feof(f))
1877 break;
1878 qemu_get_buffer(f, idstr, len);
1879 idstr[len] = '\0';
1880 instance_id = qemu_get_be32(f);
1881 version_id = qemu_get_be32(f);
1882 record_len = qemu_get_be32(f);
1883 #if 0
1884 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1885 idstr, instance_id, version_id, record_len);
1886 #endif
1887 cur_pos = ftell(f);
1888 se = find_se(idstr, instance_id);
1889 if (!se) {
1890 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1891 instance_id, idstr);
1892 } else {
1893 ret = se->load_state(f, se->opaque, version_id);
1894 if (ret < 0) {
1895 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1896 instance_id, idstr);
1899 /* always seek to exact end of record */
1900 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1902 fclose(f);
1903 ret = 0;
1904 the_end:
1905 if (saved_vm_running)
1906 vm_start();
1907 return ret;
1910 /***********************************************************/
1911 /* main execution loop */
1913 void gui_update(void *opaque)
1915 display_state.dpy_refresh(&display_state);
1916 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1918 void polling_handler(void *opaque)
1920 #ifndef _WIN32
1921 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1922 IOHandlerRecord *ioh, *ioh_next;
1923 uint8_t buf[4096];
1924 int n, max_size;
1925 #endif
1926 int timeout = 0;
1927 int ret;
1929 #ifdef _WIN32
1930 if (timeout > 0)
1931 Sleep(timeout);
1932 #else
1933 /* poll any events */
1934 /* XXX: separate device handlers from system ones */
1935 pf = ufds;
1936 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1937 if (!ioh->fd_can_read) {
1938 max_size = 0;
1939 pf->fd = ioh->fd;
1940 pf->events = POLLIN;
1941 ioh->ufd = pf;
1942 pf++;
1943 } else {
1944 max_size = ioh->fd_can_read(ioh->opaque);
1945 if (max_size > 0) {
1946 if (max_size > sizeof(buf))
1947 max_size = sizeof(buf);
1948 pf->fd = ioh->fd;
1949 pf->events = POLLIN;
1950 ioh->ufd = pf;
1951 pf++;
1952 } else {
1953 ioh->ufd = NULL;
1956 ioh->max_size = max_size;
1959 ret = poll(ufds, pf - ufds, timeout);
1960 if (ret > 0) {
1961 /* XXX: better handling of removal */
1962 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1963 ioh_next = ioh->next;
1964 pf = ioh->ufd;
1965 if (pf) {
1966 if (pf->revents & POLLIN) {
1967 if (ioh->max_size == 0) {
1968 /* just a read event */
1969 ioh->fd_read(ioh->opaque, NULL, 0);
1970 } else {
1971 n = read(ioh->fd, buf, ioh->max_size);
1972 if (n >= 0) {
1973 ioh->fd_read(ioh->opaque, buf, n);
1974 } else if (errno != EAGAIN) {
1975 ioh->fd_read(ioh->opaque, NULL, -errno);
1982 #endif /* !defined(_WIN32) */
1984 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
1988 /* XXX: support several handlers */
1989 VMStopHandler *vm_stop_cb;
1990 VMStopHandler *vm_stop_opaque;
1992 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1994 vm_stop_cb = cb;
1995 vm_stop_opaque = opaque;
1996 return 0;
1999 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2001 vm_stop_cb = NULL;
2004 void vm_start(void)
2006 if (!vm_running) {
2007 cpu_enable_ticks();
2008 vm_running = 1;
2012 void vm_stop(int reason)
2014 if (vm_running) {
2015 cpu_disable_ticks();
2016 vm_running = 0;
2017 if (reason != 0) {
2018 if (vm_stop_cb) {
2019 vm_stop_cb(vm_stop_opaque, reason);
2025 /* reset/shutdown handler */
2027 typedef struct QEMUResetEntry {
2028 QEMUResetHandler *func;
2029 void *opaque;
2030 struct QEMUResetEntry *next;
2031 } QEMUResetEntry;
2033 static QEMUResetEntry *first_reset_entry;
2034 int reset_requested;
2035 int shutdown_requested;
2037 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2039 QEMUResetEntry **pre, *re;
2041 pre = &first_reset_entry;
2042 while (*pre != NULL)
2043 pre = &(*pre)->next;
2044 re = qemu_mallocz(sizeof(QEMUResetEntry));
2045 re->func = func;
2046 re->opaque = opaque;
2047 re->next = NULL;
2048 *pre = re;
2051 void qemu_system_reset(void)
2053 QEMUResetEntry *re;
2055 /* reset all devices */
2056 for(re = first_reset_entry; re != NULL; re = re->next) {
2057 re->func(re->opaque);
2061 void qemu_system_reset_request(void)
2063 reset_requested = 1;
2064 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2067 void qemu_system_shutdown_request(void)
2069 shutdown_requested = 1;
2070 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2073 void main_loop_wait(int timeout)
2075 if (vm_running) {
2076 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2077 qemu_get_clock(vm_clock));
2078 /* run dma transfers, if any */
2079 DMA_run();
2082 /* real time timers */
2083 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2084 qemu_get_clock(rt_clock));
2087 void help(void)
2089 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2090 "usage: %s [options] [disk_image]\n"
2091 "\n"
2092 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2093 "\n"
2094 "Standard options:\n"
2095 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2096 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2097 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2098 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2099 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2100 "-snapshot write to temporary files instead of disk image files\n"
2101 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2102 "-nographic disable graphical output and redirect serial I/Os to console\n"
2103 #ifdef CONFIG_VNC
2104 "-vnc port use vnc instead of sdl\n"
2105 "-vncport port use a different port\n"
2106 "-vncconnect host:port do a reverse connect\n"
2107 #ifdef CONFIG_SDL
2108 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2109 #endif
2110 #endif
2111 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2112 "-enable-audio enable audio support\n"
2113 "-localtime set the real time clock to local time [default=utc]\n"
2114 "-full-screen start in full screen\n"
2115 #ifdef TARGET_PPC
2116 "-prep Simulate a PREP system (default is PowerMAC)\n"
2117 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2118 #endif
2119 "-nic-pcnet simulate an AMD PC-Net PCI ethernet adaptor\n"
2120 "\n"
2121 "Network options:\n"
2122 "-nics n simulate 'n' network cards [default=1]\n"
2123 "-macaddr addr set the mac address of the first interface\n"
2124 "-n script set tap/tun network init script [default=%s]\n"
2125 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2126 #ifdef CONFIG_SLIRP
2127 "-user-net use user mode network stack [default if no tap/tun script]\n"
2128 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2129 #ifndef _WIN32
2130 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2131 #endif
2132 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2133 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2134 #endif
2135 "-dummy-net use dummy network stack\n"
2136 "\n"
2137 "Linux boot specific:\n"
2138 "-kernel bzImage use 'bzImage' as kernel image\n"
2139 "-append cmdline use 'cmdline' as kernel command line\n"
2140 "-initrd file use 'file' as initial ram disk\n"
2141 "\n"
2142 "Debug/Expert options:\n"
2143 "-monitor dev redirect the monitor to char device 'dev'\n"
2144 "-serial dev redirect the serial port to char device 'dev'\n"
2145 "-S freeze CPU at startup (use 'c' to start execution)\n"
2146 "-s wait gdb connection to port %d\n"
2147 "-p port ioreq port for xen\n"
2148 "-d domain domain that we're serving\n"
2149 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2150 "-L path set the directory for the BIOS and VGA BIOS\n"
2151 #ifdef USE_CODE_COPY
2152 "-no-code-copy disable code copy acceleration\n"
2153 #endif
2154 #ifdef TARGET_I386
2155 "-isa simulate an ISA-only system (default is PCI system)\n"
2156 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2157 " (default is CL-GD5446 PCI VGA)\n"
2158 #endif
2159 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2160 "\n"
2161 "During emulation, the following keys are useful:\n"
2162 "ctrl-alt-f toggle full screen\n"
2163 "ctrl-alt-n switch to virtual console 'n'\n"
2164 "ctrl-alt toggle mouse and keyboard grab\n"
2165 "\n"
2166 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2168 #ifdef CONFIG_SOFTMMU
2169 "qemu",
2170 #else
2171 "qemu-fast",
2172 #endif
2173 DEFAULT_RAM_SIZE,
2174 DEFAULT_NETWORK_SCRIPT,
2175 DEFAULT_GDBSTUB_PORT);
2176 #ifndef CONFIG_SOFTMMU
2177 printf("\n"
2178 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2179 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2180 "PC emulation.\n");
2181 #endif
2182 exit(1);
2185 #define HAS_ARG 0x0001
2187 enum {
2188 QEMU_OPTION_h,
2190 QEMU_OPTION_fda,
2191 QEMU_OPTION_fdb,
2192 QEMU_OPTION_hda,
2193 QEMU_OPTION_hdb,
2194 QEMU_OPTION_hdc,
2195 QEMU_OPTION_hdd,
2196 QEMU_OPTION_cdrom,
2197 QEMU_OPTION_boot,
2198 QEMU_OPTION_snapshot,
2199 QEMU_OPTION_m,
2200 QEMU_OPTION_nographic,
2201 #ifdef CONFIG_VNC
2202 QEMU_OPTION_vnc,
2203 QEMU_OPTION_vncport,
2204 QEMU_OPTION_vncconnect,
2205 #ifdef CONFIG_SDL
2206 QEMU_OPTION_vnc_and_sdl,
2207 #endif
2208 #endif
2209 QEMU_OPTION_enable_audio,
2211 QEMU_OPTION_nics,
2212 QEMU_OPTION_macaddr,
2213 QEMU_OPTION_n,
2214 QEMU_OPTION_tun_fd,
2215 QEMU_OPTION_user_net,
2216 QEMU_OPTION_tftp,
2217 QEMU_OPTION_smb,
2218 QEMU_OPTION_redir,
2219 QEMU_OPTION_dummy_net,
2221 QEMU_OPTION_kernel,
2222 QEMU_OPTION_append,
2223 QEMU_OPTION_initrd,
2225 QEMU_OPTION_S,
2226 QEMU_OPTION_s,
2227 QEMU_OPTION_p,
2228 QEMU_OPTION_d,
2229 QEMU_OPTION_l,
2230 QEMU_OPTION_hdachs,
2231 QEMU_OPTION_L,
2232 QEMU_OPTION_no_code_copy,
2233 QEMU_OPTION_pci,
2234 QEMU_OPTION_nic_pcnet,
2235 QEMU_OPTION_isa,
2236 QEMU_OPTION_prep,
2237 QEMU_OPTION_k,
2238 QEMU_OPTION_localtime,
2239 QEMU_OPTION_cirrusvga,
2240 QEMU_OPTION_g,
2241 QEMU_OPTION_std_vga,
2242 QEMU_OPTION_monitor,
2243 QEMU_OPTION_serial,
2244 QEMU_OPTION_loadvm,
2245 QEMU_OPTION_full_screen,
2246 };
2248 typedef struct QEMUOption {
2249 const char *name;
2250 int flags;
2251 int index;
2252 } QEMUOption;
2254 const QEMUOption qemu_options[] = {
2255 { "h", 0, QEMU_OPTION_h },
2257 { "fda", HAS_ARG, QEMU_OPTION_fda },
2258 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2259 { "hda", HAS_ARG, QEMU_OPTION_hda },
2260 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2261 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2262 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2263 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2264 { "boot", HAS_ARG, QEMU_OPTION_boot },
2265 { "snapshot", 0, QEMU_OPTION_snapshot },
2266 { "m", HAS_ARG, QEMU_OPTION_m },
2267 { "nographic", 0, QEMU_OPTION_nographic },
2268 #ifdef CONFIG_VNC
2269 { "vnc", 0, QEMU_OPTION_vnc },
2270 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2271 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2272 #ifdef CONFIG_SDL
2273 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2274 #endif
2275 #endif
2276 { "k", HAS_ARG, QEMU_OPTION_k },
2277 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2279 { "nics", HAS_ARG, QEMU_OPTION_nics},
2280 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2281 { "n", HAS_ARG, QEMU_OPTION_n },
2282 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2283 #ifdef CONFIG_SLIRP
2284 { "user-net", 0, QEMU_OPTION_user_net },
2285 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2286 #ifndef _WIN32
2287 { "smb", HAS_ARG, QEMU_OPTION_smb },
2288 #endif
2289 { "redir", HAS_ARG, QEMU_OPTION_redir },
2290 #endif
2291 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2293 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2294 { "append", HAS_ARG, QEMU_OPTION_append },
2295 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2297 { "S", 0, QEMU_OPTION_S },
2298 { "s", 0, QEMU_OPTION_s },
2299 { "p", HAS_ARG, QEMU_OPTION_p },
2300 { "d", HAS_ARG, QEMU_OPTION_d },
2301 { "l", HAS_ARG, QEMU_OPTION_l },
2302 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2303 { "L", HAS_ARG, QEMU_OPTION_L },
2304 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2305 #ifdef TARGET_PPC
2306 { "prep", 0, QEMU_OPTION_prep },
2307 { "g", 1, QEMU_OPTION_g },
2308 #endif
2309 { "localtime", 0, QEMU_OPTION_localtime },
2310 { "isa", 0, QEMU_OPTION_isa },
2311 { "std-vga", 0, QEMU_OPTION_std_vga },
2312 { "monitor", 1, QEMU_OPTION_monitor },
2313 { "serial", 1, QEMU_OPTION_serial },
2314 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2315 { "full-screen", 0, QEMU_OPTION_full_screen },
2317 /* temporary options */
2318 { "pci", 0, QEMU_OPTION_pci },
2319 { "nic-pcnet", 0, QEMU_OPTION_nic_pcnet },
2320 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2321 { NULL },
2322 };
2324 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2326 /* this stack is only used during signal handling */
2327 #define SIGNAL_STACK_SIZE 32768
2329 static uint8_t *signal_stack;
2331 #endif
2333 #define NET_IF_TUN 0
2334 #define NET_IF_USER 1
2335 #define NET_IF_DUMMY 2
2337 int main(int argc, char **argv)
2339 #ifdef CONFIG_GDBSTUB
2340 int use_gdbstub, gdbstub_port;
2341 #endif
2342 int i, has_cdrom;
2343 int snapshot, linux_boot;
2344 CPUState *env;
2345 const char *initrd_filename;
2346 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2347 const char *kernel_filename, *kernel_cmdline;
2348 DisplayState *ds = &display_state;
2349 int cyls, heads, secs;
2350 int start_emulation = 1;
2351 uint8_t macaddr[6];
2352 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2353 int optind;
2354 const char *r, *optarg;
2355 CharDriverState *monitor_hd;
2356 char monitor_device[128];
2357 char serial_devices[MAX_SERIAL_PORTS][128];
2358 int serial_device_index;
2359 const char *loadvm = NULL;
2360 unsigned long nr_pages, *page_array;
2361 extern void *shared_page;
2362 /* change the qemu-dm to daemon, just like bochs dm */
2363 // daemon(0, 0);
2365 #if !defined(CONFIG_SOFTMMU)
2366 /* we never want that malloc() uses mmap() */
2367 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2368 #endif
2369 initrd_filename = NULL;
2370 for(i = 0; i < MAX_FD; i++)
2371 fd_filename[i] = NULL;
2372 for(i = 0; i < MAX_DISKS; i++)
2373 hd_filename[i] = NULL;
2374 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2375 vga_ram_size = VGA_RAM_SIZE;
2376 bios_size = BIOS_SIZE;
2377 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2378 #ifdef CONFIG_GDBSTUB
2379 use_gdbstub = 0;
2380 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2381 #endif
2382 snapshot = 0;
2383 nographic = 0;
2384 usevnc = 0;
2385 vncport=0;
2386 vncconnect=NULL;
2387 kernel_filename = NULL;
2388 kernel_cmdline = "";
2389 has_cdrom = 1;
2390 cyls = heads = secs = 0;
2391 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2393 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2394 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2395 serial_devices[i][0] = '\0';
2396 serial_device_index = 0;
2398 nb_tun_fds = 0;
2399 net_if_type = -1;
2400 nb_nics = 1;
2401 /* default mac address of the first network interface */
2402 macaddr[0] = 0x52;
2403 macaddr[1] = 0x54;
2404 macaddr[2] = 0x00;
2405 macaddr[3] = 0x12;
2406 macaddr[4] = 0x34;
2407 macaddr[5] = 0x56;
2409 /* init debug */
2410 cpu_set_log(0);
2412 optind = 1;
2413 for(;;) {
2414 if (optind >= argc)
2415 break;
2416 r = argv[optind];
2417 if (r[0] != '-') {
2418 hd_filename[0] = argv[optind++];
2419 } else {
2420 const QEMUOption *popt;
2422 optind++;
2423 popt = qemu_options;
2424 for(;;) {
2425 if (!popt->name) {
2426 fprintf(stderr, "%s: invalid option -- '%s'\n",
2427 argv[0], r);
2428 exit(1);
2430 if (!strcmp(popt->name, r + 1))
2431 break;
2432 popt++;
2434 if (popt->flags & HAS_ARG) {
2435 if (optind >= argc) {
2436 fprintf(stderr, "%s: option '%s' requires an argument\n",
2437 argv[0], r);
2438 exit(1);
2440 optarg = argv[optind++];
2441 } else {
2442 optarg = NULL;
2445 switch(popt->index) {
2446 case QEMU_OPTION_initrd:
2447 initrd_filename = optarg;
2448 break;
2449 case QEMU_OPTION_hda:
2450 hd_filename[0] = optarg;
2451 break;
2452 case QEMU_OPTION_hdb:
2453 hd_filename[1] = optarg;
2454 break;
2455 case QEMU_OPTION_snapshot:
2456 snapshot = 1;
2457 break;
2458 case QEMU_OPTION_hdachs:
2460 const char *p;
2461 p = optarg;
2462 cyls = strtol(p, (char **)&p, 0);
2463 if (*p != ',')
2464 goto chs_fail;
2465 p++;
2466 heads = strtol(p, (char **)&p, 0);
2467 if (*p != ',')
2468 goto chs_fail;
2469 p++;
2470 secs = strtol(p, (char **)&p, 0);
2471 if (*p != '\0') {
2472 chs_fail:
2473 cyls = 0;
2476 break;
2477 case QEMU_OPTION_nographic:
2478 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2479 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2480 nographic = 1;
2481 break;
2482 #ifdef CONFIG_VNC
2483 case QEMU_OPTION_vnc:
2484 usevnc = 1;
2485 break;
2486 case QEMU_OPTION_vncport:
2488 const char *p;
2489 p = optarg;
2490 vncport= strtol(optarg, (char **)&p, 0);
2492 break;
2493 case QEMU_OPTION_vncconnect:
2495 vncconnect=optarg;
2497 break;
2498 #ifdef CONFIG_SDL
2499 case QEMU_OPTION_vnc_and_sdl:
2500 usevnc = 2;
2501 break;
2502 #endif
2503 #endif
2504 case QEMU_OPTION_kernel:
2505 kernel_filename = optarg;
2506 break;
2507 case QEMU_OPTION_append:
2508 kernel_cmdline = optarg;
2509 break;
2510 case QEMU_OPTION_tun_fd:
2512 const char *p;
2513 int fd;
2514 net_if_type = NET_IF_TUN;
2515 if (nb_tun_fds < MAX_NICS) {
2516 fd = strtol(optarg, (char **)&p, 0);
2517 if (*p != '\0') {
2518 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2519 exit(1);
2521 tun_fds[nb_tun_fds++] = fd;
2524 break;
2525 case QEMU_OPTION_hdc:
2526 hd_filename[2] = optarg;
2527 has_cdrom = 0;
2528 break;
2529 case QEMU_OPTION_hdd:
2530 hd_filename[3] = optarg;
2531 break;
2532 case QEMU_OPTION_cdrom:
2533 hd_filename[2] = optarg;
2534 has_cdrom = 1;
2535 break;
2536 case QEMU_OPTION_boot:
2537 boot_device = optarg[0];
2538 if (boot_device != 'a' &&
2539 boot_device != 'c' && boot_device != 'd') {
2540 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2541 exit(1);
2543 break;
2544 case QEMU_OPTION_fda:
2545 fd_filename[0] = optarg;
2546 break;
2547 case QEMU_OPTION_fdb:
2548 fd_filename[1] = optarg;
2549 break;
2550 case QEMU_OPTION_nics:
2551 nb_nics = atoi(optarg);
2552 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2553 fprintf(stderr, "qemu: invalid number of network interfaces\n");
2554 exit(1);
2556 break;
2557 case QEMU_OPTION_macaddr:
2559 const char *p;
2560 int i;
2561 p = optarg;
2562 for(i = 0; i < 6; i++) {
2563 macaddr[i] = strtol(p, (char **)&p, 16);
2564 if (i == 5) {
2565 if (*p != '\0')
2566 goto macaddr_error;
2567 } else {
2568 if (*p != ':') {
2569 macaddr_error:
2570 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2571 exit(1);
2573 p++;
2577 break;
2578 #ifdef CONFIG_SLIRP
2579 case QEMU_OPTION_tftp:
2580 tftp_prefix = optarg;
2581 break;
2582 #ifndef _WIN32
2583 case QEMU_OPTION_smb:
2584 net_slirp_smb(optarg);
2585 break;
2586 #endif
2587 case QEMU_OPTION_user_net:
2588 net_if_type = NET_IF_USER;
2589 break;
2590 case QEMU_OPTION_redir:
2591 net_slirp_redir(optarg);
2592 break;
2593 #endif
2594 case QEMU_OPTION_dummy_net:
2595 net_if_type = NET_IF_DUMMY;
2596 break;
2597 case QEMU_OPTION_enable_audio:
2598 audio_enabled = 1;
2599 break;
2600 case QEMU_OPTION_h:
2601 help();
2602 break;
2603 case QEMU_OPTION_m:
2604 ram_size = atoi(optarg) * 1024 * 1024;
2605 if (ram_size <= 0)
2606 help();
2607 break;
2608 case QEMU_OPTION_d:
2610 domid = atoi(optarg);
2611 printf("domid: %d\n", domid);
2613 break;
2615 case QEMU_OPTION_p:
2617 extern short ioreq_port;
2618 ioreq_port = atoi(optarg);
2619 printf("port: %d\n", ioreq_port);
2621 break;
2622 case QEMU_OPTION_l:
2624 int mask;
2625 mask = cpu_str_to_log_mask(optarg);
2626 printf("mask: %x\n", mask);
2627 cpu_set_log(mask);
2629 break;
2630 case QEMU_OPTION_n:
2631 pstrcpy(network_script, sizeof(network_script), optarg);
2632 break;
2633 #ifdef CONFIG_GDBSTUB
2634 case QEMU_OPTION_s:
2635 use_gdbstub = 1;
2636 break;
2637 #endif
2638 case QEMU_OPTION_L:
2639 bios_dir = optarg;
2640 break;
2641 case QEMU_OPTION_S:
2642 start_emulation = 0;
2643 break;
2644 case QEMU_OPTION_pci:
2645 pci_enabled = 1;
2646 break;
2647 case QEMU_OPTION_nic_pcnet:
2648 nic_pcnet = 1;
2649 break;
2650 case QEMU_OPTION_isa:
2651 pci_enabled = 0;
2652 break;
2653 case QEMU_OPTION_prep:
2654 prep_enabled = 1;
2655 break;
2656 case QEMU_OPTION_k:
2657 keyboard_layout = optarg;
2658 break;
2659 case QEMU_OPTION_localtime:
2660 rtc_utc = 0;
2661 break;
2662 case QEMU_OPTION_cirrusvga:
2663 cirrus_vga_enabled = 1;
2664 break;
2665 case QEMU_OPTION_std_vga:
2666 cirrus_vga_enabled = 0;
2667 break;
2668 case QEMU_OPTION_g:
2670 const char *p;
2671 int w, h, depth;
2672 p = optarg;
2673 w = strtol(p, (char **)&p, 10);
2674 if (w <= 0) {
2675 graphic_error:
2676 fprintf(stderr, "qemu: invalid resolution or depth\n");
2677 exit(1);
2679 if (*p != 'x')
2680 goto graphic_error;
2681 p++;
2682 h = strtol(p, (char **)&p, 10);
2683 if (h <= 0)
2684 goto graphic_error;
2685 if (*p == 'x') {
2686 p++;
2687 depth = strtol(p, (char **)&p, 10);
2688 if (depth != 8 && depth != 15 && depth != 16 &&
2689 depth != 24 && depth != 32)
2690 goto graphic_error;
2691 } else if (*p == '\0') {
2692 depth = graphic_depth;
2693 } else {
2694 goto graphic_error;
2697 graphic_width = w;
2698 graphic_height = h;
2699 graphic_depth = depth;
2701 break;
2702 case QEMU_OPTION_monitor:
2703 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2704 break;
2705 case QEMU_OPTION_serial:
2706 if (serial_device_index >= MAX_SERIAL_PORTS) {
2707 fprintf(stderr, "qemu: too many serial ports\n");
2708 exit(1);
2710 pstrcpy(serial_devices[serial_device_index],
2711 sizeof(serial_devices[0]), optarg);
2712 serial_device_index++;
2713 break;
2714 case QEMU_OPTION_loadvm:
2715 loadvm = optarg;
2716 break;
2717 case QEMU_OPTION_full_screen:
2718 full_screen = 1;
2719 break;
2724 linux_boot = (kernel_filename != NULL);
2726 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2727 fd_filename[0] == '\0')
2728 help();
2730 /* boot to cd by default if no hard disk */
2731 if (hd_filename[0] == '\0' && boot_device == 'c') {
2732 if (fd_filename[0] != '\0')
2733 boot_device = 'a';
2734 else
2735 boot_device = 'd';
2738 #if !defined(CONFIG_SOFTMMU)
2739 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2741 static uint8_t stdout_buf[4096];
2742 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2744 #else
2745 setvbuf(stdout, NULL, _IOLBF, 0);
2746 #endif
2748 /* init host network redirectors */
2749 if (net_if_type == -1) {
2750 net_if_type = NET_IF_TUN;
2751 #if defined(CONFIG_SLIRP)
2752 if (access(network_script, R_OK) < 0) {
2753 net_if_type = NET_IF_USER;
2755 #endif
2758 for(i = 0; i < nb_nics; i++) {
2759 NetDriverState *nd = &nd_table[i];
2760 nd->index = i;
2761 /* init virtual mac address */
2762 nd->macaddr[0] = macaddr[0];
2763 nd->macaddr[1] = macaddr[1];
2764 nd->macaddr[2] = macaddr[2];
2765 nd->macaddr[3] = macaddr[3];
2766 nd->macaddr[4] = macaddr[4];
2767 nd->macaddr[5] = macaddr[5] + i;
2768 switch(net_if_type) {
2769 #if defined(CONFIG_SLIRP)
2770 case NET_IF_USER:
2771 net_slirp_init(nd);
2772 break;
2773 #endif
2774 #if !defined(_WIN32)
2775 case NET_IF_TUN:
2776 if (i < nb_tun_fds) {
2777 net_fd_init(nd, tun_fds[i]);
2778 } else {
2779 if (net_tun_init(nd) < 0)
2780 net_dummy_init(nd);
2782 break;
2783 #endif
2784 case NET_IF_DUMMY:
2785 default:
2786 net_dummy_init(nd);
2787 break;
2791 /* init the memory */
2792 phys_ram_size = ram_size + vga_ram_size + bios_size;
2794 #define PAGE_SHIFT 12
2795 #define PAGE_SIZE (1 << PAGE_SHIFT)
2797 nr_pages = ram_size/PAGE_SIZE;
2798 xc_handle = xc_interface_open();
2800 if ( (page_array = (unsigned long *)
2801 malloc(nr_pages * sizeof(unsigned long))) == NULL)
2803 perror("malloc");
2804 exit(-1);
2807 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
2809 perror("xc_get_pfn_list");
2810 exit(-1);
2813 if ((phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
2814 PROT_READ|PROT_WRITE,
2815 page_array,
2816 nr_pages - 1)) == 0) {
2817 perror("xc_map_foreign_batch");
2818 exit(-1);
2821 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
2822 PROT_READ|PROT_WRITE,
2823 page_array[nr_pages - 1]);
2826 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
2827 (page_array[nr_pages - 1]));
2829 /* we always create the cdrom drive, even if no disk is there */
2830 bdrv_init();
2831 if (has_cdrom) {
2832 bs_table[2] = bdrv_new("cdrom");
2833 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2836 /* open the virtual block devices */
2837 for(i = 0; i < MAX_DISKS; i++) {
2838 if (hd_filename[i]) {
2839 if (!bs_table[i]) {
2840 char buf[64];
2841 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2842 bs_table[i] = bdrv_new(buf);
2844 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2845 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
2846 hd_filename[i]);
2847 exit(1);
2849 if (i == 0 && cyls != 0)
2850 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2854 /* we always create at least one floppy disk */
2855 fd_table[0] = bdrv_new("fda");
2856 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2858 for(i = 0; i < MAX_FD; i++) {
2859 if (fd_filename[i]) {
2860 if (!fd_table[i]) {
2861 char buf[64];
2862 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2863 fd_table[i] = bdrv_new(buf);
2864 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2866 if (fd_filename[i] != '\0') {
2867 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2868 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2869 fd_filename[i]);
2870 exit(1);
2876 /* init CPU state */
2877 env = cpu_init();
2878 global_env = env;
2879 cpu_single_env = env;
2881 init_ioports();
2882 cpu_calibrate_ticks();
2884 /* terminal init */
2885 if (nographic) {
2886 dumb_display_init(ds);
2887 } else {
2888 if (usevnc) {
2889 #ifdef CONFIG_VNC
2890 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
2891 #else
2892 perror("qemu not configured with vnc support");
2893 #endif
2894 } else {
2895 #ifdef CONFIG_SDL
2896 sdl_display_init(ds, full_screen);
2897 #else
2898 dumb_display_init(ds);
2899 #endif
2903 vga_console = graphic_console_init(ds);
2905 monitor_hd = qemu_chr_open(monitor_device);
2906 if (!monitor_hd) {
2907 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
2908 exit(1);
2910 monitor_init(monitor_hd, !nographic);
2912 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
2913 if (serial_devices[i][0] != '\0') {
2914 serial_hds[i] = qemu_chr_open(serial_devices[i]);
2915 if (!serial_hds[i]) {
2916 fprintf(stderr, "qemu: could not open serial device '%s'\n",
2917 serial_devices[i]);
2918 exit(1);
2920 if (!strcmp(serial_devices[i], "vc"))
2921 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
2925 /* setup cpu signal handlers for MMU / self modifying code handling */
2926 #if !defined(CONFIG_SOFTMMU)
2928 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2930 stack_t stk;
2931 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2932 stk.ss_sp = signal_stack;
2933 stk.ss_size = SIGNAL_STACK_SIZE;
2934 stk.ss_flags = 0;
2936 if (sigaltstack(&stk, NULL) < 0) {
2937 perror("sigaltstack");
2938 exit(1);
2941 #endif
2943 struct sigaction act;
2945 sigfillset(&act.sa_mask);
2946 act.sa_flags = SA_SIGINFO;
2947 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2948 act.sa_flags |= SA_ONSTACK;
2949 #endif
2950 act.sa_sigaction = host_segv_handler;
2951 sigaction(SIGSEGV, &act, NULL);
2952 sigaction(SIGBUS, &act, NULL);
2953 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2954 sigaction(SIGFPE, &act, NULL);
2955 #endif
2957 #endif
2959 #ifndef _WIN32
2961 struct sigaction act;
2962 sigfillset(&act.sa_mask);
2963 act.sa_flags = 0;
2964 act.sa_handler = SIG_IGN;
2965 sigaction(SIGPIPE, &act, NULL);
2967 #endif
2968 init_timers();
2970 #if defined(TARGET_I386)
2971 pc_init(ram_size, vga_ram_size, boot_device,
2972 ds, fd_filename, snapshot,
2973 kernel_filename, kernel_cmdline, initrd_filename);
2974 #elif defined(TARGET_PPC)
2975 ppc_init(ram_size, vga_ram_size, boot_device,
2976 ds, fd_filename, snapshot,
2977 kernel_filename, kernel_cmdline, initrd_filename);
2978 #elif defined(TARGET_SPARC)
2979 sun4m_init(ram_size, vga_ram_size, boot_device,
2980 ds, fd_filename, snapshot,
2981 kernel_filename, kernel_cmdline, initrd_filename);
2982 #endif
2984 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2985 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2987 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
2988 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
2990 #ifdef CONFIG_GDBSTUB
2991 if (use_gdbstub) {
2992 if (gdbserver_start(gdbstub_port) < 0) {
2993 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
2994 gdbstub_port);
2995 exit(1);
2996 } else {
2997 printf("Waiting gdb connection on port %d\n", gdbstub_port);
2999 } else
3000 #endif
3001 if (loadvm)
3002 qemu_loadvm(loadvm);
3005 /* XXX: simplify init */
3006 if (start_emulation) {
3007 vm_start();
3010 main_loop();
3011 quit_timers();
3012 return 0;