ia64/xen-unstable

view tools/ioemu/vl.c @ 6433:0610add7c3fe

merge?
author cl349@firebug.cl.cam.ac.uk
date Thu Aug 25 16:27:04 2005 +0000 (2005-08-25)
parents b54144915ae6 6e899a3840b2
children b4b3f6be5226
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 sb16_enabled = 1;
129 int adlib_enabled = 1;
130 int gus_enabled = 1;
131 int pci_enabled = 1;
132 int prep_enabled = 0;
133 int rtc_utc = 1;
134 int cirrus_vga_enabled = 1;
135 int graphic_width = 800;
136 int graphic_height = 600;
137 int graphic_depth = 15;
138 int full_screen = 0;
139 TextConsole *vga_console;
140 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
141 int xc_handle;
143 /***********************************************************/
144 /* x86 ISA bus support */
146 target_phys_addr_t isa_mem_base = 0;
148 uint32_t default_ioport_readb(void *opaque, uint32_t address)
149 {
150 #ifdef DEBUG_UNUSED_IOPORT
151 fprintf(stderr, "inb: port=0x%04x\n", address);
152 #endif
153 return 0xff;
154 }
156 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
157 {
158 #ifdef DEBUG_UNUSED_IOPORT
159 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
160 #endif
161 }
163 /* default is to make two byte accesses */
164 uint32_t default_ioport_readw(void *opaque, uint32_t address)
165 {
166 uint32_t data;
167 data = ioport_read_table[0][address](ioport_opaque[address], address);
168 address = (address + 1) & (MAX_IOPORTS - 1);
169 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
170 return data;
171 }
173 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
174 {
175 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
176 address = (address + 1) & (MAX_IOPORTS - 1);
177 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
178 }
180 uint32_t default_ioport_readl(void *opaque, uint32_t address)
181 {
182 #ifdef DEBUG_UNUSED_IOPORT
183 fprintf(stderr, "inl: port=0x%04x\n", address);
184 #endif
185 return 0xffffffff;
186 }
188 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
189 {
190 #ifdef DEBUG_UNUSED_IOPORT
191 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
192 #endif
193 }
195 void init_ioports(void)
196 {
197 int i;
199 for(i = 0; i < MAX_IOPORTS; i++) {
200 ioport_read_table[0][i] = default_ioport_readb;
201 ioport_write_table[0][i] = default_ioport_writeb;
202 ioport_read_table[1][i] = default_ioport_readw;
203 ioport_write_table[1][i] = default_ioport_writew;
204 ioport_read_table[2][i] = default_ioport_readl;
205 ioport_write_table[2][i] = default_ioport_writel;
206 }
207 }
209 /* size is the word size in byte */
210 int register_ioport_read(int start, int length, int size,
211 IOPortReadFunc *func, void *opaque)
212 {
213 int i, bsize;
215 if (size == 1) {
216 bsize = 0;
217 } else if (size == 2) {
218 bsize = 1;
219 } else if (size == 4) {
220 bsize = 2;
221 } else {
222 hw_error("register_ioport_read: invalid size");
223 return -1;
224 }
225 for(i = start; i < start + length; i += size) {
226 ioport_read_table[bsize][i] = func;
227 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
228 hw_error("register_ioport_read: invalid opaque");
229 ioport_opaque[i] = opaque;
230 }
231 return 0;
232 }
234 /* size is the word size in byte */
235 int register_ioport_write(int start, int length, int size,
236 IOPortWriteFunc *func, void *opaque)
237 {
238 int i, bsize;
240 if (size == 1) {
241 bsize = 0;
242 } else if (size == 2) {
243 bsize = 1;
244 } else if (size == 4) {
245 bsize = 2;
246 } else {
247 hw_error("register_ioport_write: invalid size");
248 return -1;
249 }
250 for(i = start; i < start + length; i += size) {
251 ioport_write_table[bsize][i] = func;
252 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
253 hw_error("register_ioport_read: invalid opaque");
254 ioport_opaque[i] = opaque;
255 }
256 return 0;
257 }
259 void isa_unassign_ioport(int start, int length)
260 {
261 int i;
263 for(i = start; i < start + length; i++) {
264 ioport_read_table[0][i] = default_ioport_readb;
265 ioport_read_table[1][i] = default_ioport_readw;
266 ioport_read_table[2][i] = default_ioport_readl;
268 ioport_write_table[0][i] = default_ioport_writeb;
269 ioport_write_table[1][i] = default_ioport_writew;
270 ioport_write_table[2][i] = default_ioport_writel;
271 }
272 }
274 void pstrcpy(char *buf, int buf_size, const char *str)
275 {
276 int c;
277 char *q = buf;
279 if (buf_size <= 0)
280 return;
282 for(;;) {
283 c = *str++;
284 if (c == 0 || q >= buf + buf_size - 1)
285 break;
286 *q++ = c;
287 }
288 *q = '\0';
289 }
291 /* strcat and truncate. */
292 char *pstrcat(char *buf, int buf_size, const char *s)
293 {
294 int len;
295 len = strlen(buf);
296 if (len < buf_size)
297 pstrcpy(buf + len, buf_size - len, s);
298 return buf;
299 }
301 int strstart(const char *str, const char *val, const char **ptr)
302 {
303 const char *p, *q;
304 p = str;
305 q = val;
306 while (*q != '\0') {
307 if (*p != *q)
308 return 0;
309 p++;
310 q++;
311 }
312 if (ptr)
313 *ptr = p;
314 return 1;
315 }
317 /* return the size or -1 if error */
318 int get_image_size(const char *filename)
319 {
320 int fd, size;
321 fd = open(filename, O_RDONLY | O_BINARY);
322 if (fd < 0)
323 return -1;
324 size = lseek(fd, 0, SEEK_END);
325 close(fd);
326 return size;
327 }
329 /* return the size or -1 if error */
330 int load_image(const char *filename, uint8_t *addr)
331 {
332 int fd, size;
333 fd = open(filename, O_RDONLY | O_BINARY);
334 if (fd < 0)
335 return -1;
336 size = lseek(fd, 0, SEEK_END);
337 lseek(fd, 0, SEEK_SET);
338 if (read(fd, addr, size) != size) {
339 close(fd);
340 return -1;
341 }
342 close(fd);
343 return size;
344 }
346 void cpu_outb(CPUState *env, int addr, int val)
347 {
348 #ifdef DEBUG_IOPORT
349 if (loglevel & CPU_LOG_IOPORT)
350 fprintf(logfile, "outb: %04x %02x\n", addr, val);
351 #endif
352 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
353 }
355 void cpu_outw(CPUState *env, int addr, int val)
356 {
357 #ifdef DEBUG_IOPORT
358 if (loglevel & CPU_LOG_IOPORT)
359 fprintf(logfile, "outw: %04x %04x\n", addr, val);
360 #endif
361 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
362 }
364 void cpu_outl(CPUState *env, int addr, int val)
365 {
366 #ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outl: %04x %08x\n", addr, val);
369 #endif
370 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
371 }
373 int cpu_inb(CPUState *env, int addr)
374 {
375 int val;
376 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
377 #ifdef DEBUG_IOPORT
378 if (loglevel & CPU_LOG_IOPORT)
379 fprintf(logfile, "inb : %04x %02x\n", addr, val);
380 #endif
381 return val;
382 }
384 int cpu_inw(CPUState *env, int addr)
385 {
386 int val;
387 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
388 #ifdef DEBUG_IOPORT
389 if (loglevel & CPU_LOG_IOPORT)
390 fprintf(logfile, "inw : %04x %04x\n", addr, val);
391 #endif
392 return val;
393 }
395 int cpu_inl(CPUState *env, int addr)
396 {
397 int val;
398 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
399 #ifdef DEBUG_IOPORT
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inl : %04x %08x\n", addr, val);
402 #endif
403 return val;
404 }
406 /***********************************************************/
407 void hw_error(const char *fmt, ...)
408 {
409 va_list ap;
411 va_start(ap, fmt);
412 fprintf(stderr, "qemu: hardware error: ");
413 vfprintf(stderr, fmt, ap);
414 fprintf(stderr, "\n");
415 va_end(ap);
416 abort();
417 }
419 /***********************************************************/
420 /* keyboard/mouse */
422 static QEMUPutKBDEvent *qemu_put_kbd_event;
423 static void *qemu_put_kbd_event_opaque;
424 static QEMUPutMouseEvent *qemu_put_mouse_event;
425 static void *qemu_put_mouse_event_opaque;
427 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
428 {
429 qemu_put_kbd_event_opaque = opaque;
430 qemu_put_kbd_event = func;
431 }
433 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
434 {
435 qemu_put_mouse_event_opaque = opaque;
436 qemu_put_mouse_event = func;
437 }
439 void kbd_put_keycode(int keycode)
440 {
441 if (qemu_put_kbd_event) {
442 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
443 }
444 }
446 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
447 {
448 if (qemu_put_mouse_event) {
449 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
450 dx, dy, dz, buttons_state);
451 }
452 }
454 /***********************************************************/
455 /* timers */
457 #if defined(__powerpc__)
459 static inline uint32_t get_tbl(void)
460 {
461 uint32_t tbl;
462 asm volatile("mftb %0" : "=r" (tbl));
463 return tbl;
464 }
466 static inline uint32_t get_tbu(void)
467 {
468 uint32_t tbl;
469 asm volatile("mftbu %0" : "=r" (tbl));
470 return tbl;
471 }
473 int64_t cpu_get_real_ticks(void)
474 {
475 uint32_t l, h, h1;
476 /* NOTE: we test if wrapping has occurred */
477 do {
478 h = get_tbu();
479 l = get_tbl();
480 h1 = get_tbu();
481 } while (h != h1);
482 return ((int64_t)h << 32) | l;
483 }
485 #elif defined(__i386__)
487 int64_t cpu_get_real_ticks(void)
488 {
489 int64_t val;
490 asm volatile ("rdtsc" : "=A" (val));
491 return val;
492 }
494 #elif defined(__x86_64__)
496 int64_t cpu_get_real_ticks(void)
497 {
498 uint32_t low,high;
499 int64_t val;
500 asm volatile("rdtsc" : "=a" (low), "=d" (high));
501 val = high;
502 val <<= 32;
503 val |= low;
504 return val;
505 }
507 #else
508 #error unsupported CPU
509 #endif
511 static int64_t cpu_ticks_offset;
512 static int cpu_ticks_enabled;
513 int64_t cpu_virt_tsc;
515 static inline int64_t cpu_get_ticks(void)
516 {
517 if (!cpu_ticks_enabled) {
518 return cpu_ticks_offset;
519 } else {
520 return cpu_get_real_ticks() + cpu_ticks_offset;
521 }
523 }
525 /* enable cpu_get_ticks() */
526 void cpu_enable_ticks(void)
527 {
528 if (!cpu_ticks_enabled) {
529 cpu_ticks_offset -= cpu_get_real_ticks();
530 cpu_ticks_enabled = 1;
531 }
532 }
534 /* disable cpu_get_ticks() : the clock is stopped. You must not call
535 cpu_get_ticks() after that. */
536 void cpu_disable_ticks(void)
537 {
538 if (cpu_ticks_enabled) {
539 cpu_ticks_offset = cpu_get_ticks();
540 cpu_ticks_enabled = 0;
541 }
542 }
544 static int64_t get_clock(void)
545 {
546 #ifdef _WIN32
547 struct _timeb tb;
548 _ftime(&tb);
549 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
550 #else
551 struct timeval tv;
552 gettimeofday(&tv, NULL);
553 return tv.tv_sec * 1000000LL + tv.tv_usec;
554 #endif
555 }
557 void cpu_calibrate_ticks(void)
558 {
559 int64_t usec, ticks;
561 usec = get_clock();
562 ticks = cpu_get_real_ticks();
563 #ifdef _WIN32
564 Sleep(50);
565 #else
566 usleep(50 * 1000);
567 #endif
568 usec = get_clock() - usec;
569 ticks = cpu_get_real_ticks() - ticks;
570 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
571 }
573 /* compute with 96 bit intermediate result: (a*b)/c */
574 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
575 {
576 union {
577 uint64_t ll;
578 struct {
579 #ifdef WORDS_BIGENDIAN
580 uint32_t high, low;
581 #else
582 uint32_t low, high;
583 #endif
584 } l;
585 } u, res;
586 uint64_t rl, rh;
588 u.ll = a;
589 rl = (uint64_t)u.l.low * (uint64_t)b;
590 rh = (uint64_t)u.l.high * (uint64_t)b;
591 rh += (rl >> 32);
592 res.l.high = rh / c;
593 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
594 return res.ll;
595 }
597 #define QEMU_TIMER_REALTIME 0
598 #define QEMU_TIMER_VIRTUAL 1
600 struct QEMUClock {
601 int type;
602 /* XXX: add frequency */
603 };
605 struct QEMUTimer {
606 QEMUClock *clock;
607 int64_t expire_time;
608 QEMUTimerCB *cb;
609 void *opaque;
610 struct QEMUTimer *next;
611 };
613 QEMUClock *rt_clock;
614 QEMUClock *vm_clock;
616 static QEMUTimer *active_timers[2];
617 #ifdef _WIN32
618 static MMRESULT timerID;
619 #else
620 /* frequency of the times() clock tick */
621 static int timer_freq;
622 #endif
624 QEMUClock *qemu_new_clock(int type)
625 {
626 QEMUClock *clock;
627 clock = qemu_mallocz(sizeof(QEMUClock));
628 if (!clock)
629 return NULL;
630 clock->type = type;
631 return clock;
632 }
634 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
635 {
636 QEMUTimer *ts;
638 ts = qemu_mallocz(sizeof(QEMUTimer));
639 ts->clock = clock;
640 ts->cb = cb;
641 ts->opaque = opaque;
642 return ts;
643 }
645 void qemu_free_timer(QEMUTimer *ts)
646 {
647 qemu_free(ts);
648 }
650 /* stop a timer, but do not dealloc it */
651 void qemu_del_timer(QEMUTimer *ts)
652 {
653 QEMUTimer **pt, *t;
655 /* NOTE: this code must be signal safe because
656 qemu_timer_expired() can be called from a signal. */
657 pt = &active_timers[ts->clock->type];
658 for(;;) {
659 t = *pt;
660 if (!t)
661 break;
662 if (t == ts) {
663 *pt = t->next;
664 break;
665 }
666 pt = &t->next;
667 }
668 }
670 /* modify the current timer so that it will be fired when current_time
671 >= expire_time. The corresponding callback will be called. */
672 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
673 {
674 QEMUTimer **pt, *t;
676 qemu_del_timer(ts);
678 /* add the timer in the sorted list */
679 /* NOTE: this code must be signal safe because
680 qemu_timer_expired() can be called from a signal. */
681 pt = &active_timers[ts->clock->type];
682 for(;;) {
683 t = *pt;
684 if (!t)
685 break;
686 if (t->expire_time > expire_time)
687 break;
688 pt = &t->next;
689 }
690 ts->expire_time = expire_time;
691 ts->next = *pt;
692 *pt = ts;
693 }
695 int qemu_timer_pending(QEMUTimer *ts)
696 {
697 QEMUTimer *t;
698 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
699 if (t == ts)
700 return 1;
701 }
702 return 0;
703 }
705 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
706 {
707 if (!timer_head)
708 return 0;
709 return (timer_head->expire_time <= current_time);
710 }
712 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
713 {
714 QEMUTimer *ts;
716 for(;;) {
717 ts = *ptimer_head;
718 if (!ts || ts->expire_time > current_time)
719 break;
720 /* remove timer from the list before calling the callback */
721 *ptimer_head = ts->next;
722 ts->next = NULL;
724 /* run the callback (the timer list can be modified) */
725 ts->cb(ts->opaque);
726 }
727 }
729 int64_t qemu_get_clock(QEMUClock *clock)
730 {
731 switch(clock->type) {
732 case QEMU_TIMER_REALTIME:
733 #ifdef _WIN32
734 return GetTickCount();
735 #else
736 {
737 struct tms tp;
739 /* Note that using gettimeofday() is not a good solution
740 for timers because its value change when the date is
741 modified. */
742 if (timer_freq == 100) {
743 return times(&tp) * 10;
744 } else {
745 return ((int64_t)times(&tp) * 1000) / timer_freq;
746 }
747 }
748 #endif
749 default:
750 case QEMU_TIMER_VIRTUAL:
751 return cpu_get_ticks();
752 }
753 }
755 /* save a timer */
756 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
757 {
758 uint64_t expire_time;
760 if (qemu_timer_pending(ts)) {
761 expire_time = ts->expire_time;
762 } else {
763 expire_time = -1;
764 }
765 qemu_put_be64(f, expire_time);
766 }
768 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
769 {
770 uint64_t expire_time;
772 expire_time = qemu_get_be64(f);
773 if (expire_time != -1) {
774 qemu_mod_timer(ts, expire_time);
775 } else {
776 qemu_del_timer(ts);
777 }
778 }
780 static void init_timers(void)
781 {
782 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
783 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
785 #ifdef _WIN32
786 {
787 int count=0;
788 timerID = timeSetEvent(10, // interval (ms)
789 0, // resolution
790 host_alarm_handler, // function
791 (DWORD)&count, // user parameter
792 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
793 if( !timerID ) {
794 perror("failed timer alarm");
795 exit(1);
796 }
797 }
798 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
799 #else
800 {
801 /* get times() syscall frequency */
802 timer_freq = sysconf(_SC_CLK_TCK);
804 #ifndef TARGET_VMX
805 /* timer signal */
806 sigfillset(&act.sa_mask);
807 act.sa_flags = 0;
808 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
809 act.sa_flags |= SA_ONSTACK;
810 #endif
811 act.sa_handler = host_alarm_handler;
812 sigaction(SIGALRM, &act, NULL);
814 itv.it_interval.tv_sec = 0;
815 itv.it_interval.tv_usec = 1000;
816 itv.it_value.tv_sec = 0;
817 itv.it_value.tv_usec = 10 * 1000;
818 setitimer(ITIMER_REAL, &itv, NULL);
819 /* we probe the tick duration of the kernel to inform the user if
820 the emulated kernel requested a too high timer frequency */
821 getitimer(ITIMER_REAL, &itv);
823 #if defined(__linux__)
824 if (itv.it_interval.tv_usec > 1000) {
825 /* try to use /dev/rtc to have a faster timer */
826 if (start_rtc_timer() < 0)
827 goto use_itimer;
828 /* disable itimer */
829 itv.it_interval.tv_sec = 0;
830 itv.it_interval.tv_usec = 0;
831 itv.it_value.tv_sec = 0;
832 itv.it_value.tv_usec = 0;
833 setitimer(ITIMER_REAL, &itv, NULL);
835 /* use the RTC */
836 sigaction(SIGIO, &act, NULL);
837 fcntl(rtc_fd, F_SETFL, O_ASYNC);
838 fcntl(rtc_fd, F_SETOWN, getpid());
839 } else
840 #endif /* defined(__linux__) */
841 {
842 use_itimer:
843 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
844 PIT_FREQ) / 1000000;
845 }
846 #endif /* TARGET_VMX */
847 }
848 #endif
849 }
851 void quit_timers(void)
852 {
853 #ifdef _WIN32
854 timeKillEvent(timerID);
855 #endif
856 }
858 /***********************************************************/
859 /* character device */
861 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
862 {
863 return s->chr_write(s, buf, len);
864 }
866 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
867 {
868 char buf[4096];
869 va_list ap;
870 va_start(ap, fmt);
871 vsnprintf(buf, sizeof(buf), fmt, ap);
872 qemu_chr_write(s, buf, strlen(buf));
873 va_end(ap);
874 }
876 void qemu_chr_send_event(CharDriverState *s, int event)
877 {
878 if (s->chr_send_event)
879 s->chr_send_event(s, event);
880 }
882 void qemu_chr_add_read_handler(CharDriverState *s,
883 IOCanRWHandler *fd_can_read,
884 IOReadHandler *fd_read, void *opaque)
885 {
886 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
887 }
889 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
890 {
891 s->chr_event = chr_event;
892 }
894 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
895 {
896 return len;
897 }
899 static void null_chr_add_read_handler(CharDriverState *chr,
900 IOCanRWHandler *fd_can_read,
901 IOReadHandler *fd_read, void *opaque)
902 {
903 }
905 CharDriverState *qemu_chr_open_null(void)
906 {
907 CharDriverState *chr;
909 chr = qemu_mallocz(sizeof(CharDriverState));
910 if (!chr)
911 return NULL;
912 chr->chr_write = null_chr_write;
913 chr->chr_add_read_handler = null_chr_add_read_handler;
914 return chr;
915 }
917 #ifndef _WIN32
919 typedef struct {
920 int fd_in, fd_out;
921 /* for nographic stdio only */
922 IOCanRWHandler *fd_can_read;
923 IOReadHandler *fd_read;
924 void *fd_opaque;
925 } FDCharDriver;
927 #define STDIO_MAX_CLIENTS 2
929 static int stdio_nb_clients;
930 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
932 static int unix_write(int fd, const uint8_t *buf, int len1)
933 {
934 int ret, len;
936 len = len1;
937 while (len > 0) {
938 ret = write(fd, buf, len);
939 if (ret < 0) {
940 if (errno != EINTR && errno != EAGAIN)
941 return -1;
942 } else if (ret == 0) {
943 break;
944 } else {
945 buf += ret;
946 len -= ret;
947 }
948 }
949 return len1 - len;
950 }
952 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
953 {
954 FDCharDriver *s = chr->opaque;
955 return unix_write(s->fd_out, buf, len);
956 }
958 static void fd_chr_add_read_handler(CharDriverState *chr,
959 IOCanRWHandler *fd_can_read,
960 IOReadHandler *fd_read, void *opaque)
961 {
962 FDCharDriver *s = chr->opaque;
964 if (nographic && s->fd_in == 0) {
965 s->fd_can_read = fd_can_read;
966 s->fd_read = fd_read;
967 s->fd_opaque = opaque;
968 } else {
969 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
970 }
971 }
973 /* open a character device to a unix fd */
974 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
975 {
976 CharDriverState *chr;
977 FDCharDriver *s;
979 chr = qemu_mallocz(sizeof(CharDriverState));
980 if (!chr)
981 return NULL;
982 s = qemu_mallocz(sizeof(FDCharDriver));
983 if (!s) {
984 free(chr);
985 return NULL;
986 }
987 s->fd_in = fd_in;
988 s->fd_out = fd_out;
989 chr->opaque = s;
990 chr->chr_write = fd_chr_write;
991 chr->chr_add_read_handler = fd_chr_add_read_handler;
992 return chr;
993 }
995 /* for STDIO, we handle the case where several clients use it
996 (nographic mode) */
998 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1000 static int term_got_escape, client_index;
1002 void term_print_help(void)
1004 printf("\n"
1005 "C-a h print this help\n"
1006 "C-a x exit emulator\n"
1007 "C-a s save disk data back to file (if -snapshot)\n"
1008 "C-a b send break (magic sysrq)\n"
1009 "C-a c switch between console and monitor\n"
1010 "C-a C-a send C-a\n"
1011 );
1014 /* called when a char is received */
1015 static void stdio_received_byte(int ch)
1017 if (term_got_escape) {
1018 term_got_escape = 0;
1019 switch(ch) {
1020 case 'h':
1021 term_print_help();
1022 break;
1023 case 'x':
1024 exit(0);
1025 break;
1026 case 's':
1028 int i;
1029 for (i = 0; i < MAX_DISKS; i++) {
1030 if (bs_table[i])
1031 bdrv_commit(bs_table[i]);
1034 break;
1035 case 'b':
1036 if (client_index < stdio_nb_clients) {
1037 CharDriverState *chr;
1038 FDCharDriver *s;
1040 chr = stdio_clients[client_index];
1041 s = chr->opaque;
1042 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1044 break;
1045 case 'c':
1046 client_index++;
1047 if (client_index >= stdio_nb_clients)
1048 client_index = 0;
1049 if (client_index == 0) {
1050 /* send a new line in the monitor to get the prompt */
1051 ch = '\r';
1052 goto send_char;
1054 break;
1055 case TERM_ESCAPE:
1056 goto send_char;
1058 } else if (ch == TERM_ESCAPE) {
1059 term_got_escape = 1;
1060 } else {
1061 send_char:
1062 if (client_index < stdio_nb_clients) {
1063 uint8_t buf[1];
1064 CharDriverState *chr;
1065 FDCharDriver *s;
1067 chr = stdio_clients[client_index];
1068 s = chr->opaque;
1069 buf[0] = ch;
1070 /* XXX: should queue the char if the device is not
1071 ready */
1072 if (s->fd_can_read(s->fd_opaque) > 0)
1073 s->fd_read(s->fd_opaque, buf, 1);
1078 static int stdio_can_read(void *opaque)
1080 /* XXX: not strictly correct */
1081 return 1;
1084 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1086 int i;
1087 for(i = 0; i < size; i++)
1088 stdio_received_byte(buf[i]);
1091 /* init terminal so that we can grab keys */
1092 static struct termios oldtty;
1093 static int old_fd0_flags;
1095 static void term_exit(void)
1097 tcsetattr (0, TCSANOW, &oldtty);
1098 fcntl(0, F_SETFL, old_fd0_flags);
1101 static void term_init(void)
1103 struct termios tty;
1105 tcgetattr (0, &tty);
1106 oldtty = tty;
1107 old_fd0_flags = fcntl(0, F_GETFL);
1109 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1110 |INLCR|IGNCR|ICRNL|IXON);
1111 tty.c_oflag |= OPOST;
1112 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1113 /* if graphical mode, we allow Ctrl-C handling */
1114 if (nographic)
1115 tty.c_lflag &= ~ISIG;
1116 tty.c_cflag &= ~(CSIZE|PARENB);
1117 tty.c_cflag |= CS8;
1118 tty.c_cc[VMIN] = 1;
1119 tty.c_cc[VTIME] = 0;
1121 tcsetattr (0, TCSANOW, &tty);
1123 atexit(term_exit);
1125 fcntl(0, F_SETFL, O_NONBLOCK);
1128 CharDriverState *qemu_chr_open_stdio(void)
1130 CharDriverState *chr;
1132 if (nographic) {
1133 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1134 return NULL;
1135 chr = qemu_chr_open_fd(0, 1);
1136 if (stdio_nb_clients == 0)
1137 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1138 client_index = stdio_nb_clients;
1139 } else {
1140 if (stdio_nb_clients != 0)
1141 return NULL;
1142 chr = qemu_chr_open_fd(0, 1);
1144 stdio_clients[stdio_nb_clients++] = chr;
1145 if (stdio_nb_clients == 1) {
1146 /* set the terminal in raw mode */
1147 term_init();
1149 return chr;
1152 #if defined(__linux__)
1153 CharDriverState *qemu_chr_open_pty(void)
1155 char slave_name[1024];
1156 int master_fd, slave_fd;
1158 /* Not satisfying */
1159 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1160 return NULL;
1162 fprintf(stderr, "char device redirected to %s\n", slave_name);
1163 return qemu_chr_open_fd(master_fd, master_fd);
1165 #else
1166 CharDriverState *qemu_chr_open_pty(void)
1168 return NULL;
1170 #endif
1172 #endif /* !defined(_WIN32) */
1174 CharDriverState *qemu_chr_open(const char *filename)
1176 if (!strcmp(filename, "vc")) {
1177 return text_console_init(&display_state);
1178 } else if (!strcmp(filename, "null")) {
1179 return qemu_chr_open_null();
1180 } else
1181 #ifndef _WIN32
1182 if (!strcmp(filename, "pty")) {
1183 return qemu_chr_open_pty();
1184 } else if (!strcmp(filename, "stdio")) {
1185 return qemu_chr_open_stdio();
1186 } else
1187 #endif
1189 return NULL;
1193 /***********************************************************/
1194 /* Linux network device redirectors */
1196 void hex_dump(FILE *f, const uint8_t *buf, int size)
1198 int len, i, j, c;
1200 for(i=0;i<size;i+=16) {
1201 len = size - i;
1202 if (len > 16)
1203 len = 16;
1204 fprintf(f, "%08x ", i);
1205 for(j=0;j<16;j++) {
1206 if (j < len)
1207 fprintf(f, " %02x", buf[i+j]);
1208 else
1209 fprintf(f, " ");
1211 fprintf(f, " ");
1212 for(j=0;j<len;j++) {
1213 c = buf[i+j];
1214 if (c < ' ' || c > '~')
1215 c = '.';
1216 fprintf(f, "%c", c);
1218 fprintf(f, "\n");
1222 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1224 nd->send_packet(nd, buf, size);
1227 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read, void *opaque)
1230 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1233 /* dummy network adapter */
1235 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1239 static void dummy_add_read_packet(NetDriverState *nd,
1240 IOCanRWHandler *fd_can_read,
1241 IOReadHandler *fd_read, void *opaque)
1245 static int net_dummy_init(NetDriverState *nd)
1247 nd->send_packet = dummy_send_packet;
1248 nd->add_read_packet = dummy_add_read_packet;
1249 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1250 return 0;
1253 #if defined(CONFIG_SLIRP)
1255 /* slirp network adapter */
1257 static void *slirp_fd_opaque;
1258 static IOCanRWHandler *slirp_fd_can_read;
1259 static IOReadHandler *slirp_fd_read;
1260 static int slirp_inited;
1262 int slirp_can_output(void)
1264 return slirp_fd_can_read(slirp_fd_opaque);
1267 void slirp_output(const uint8_t *pkt, int pkt_len)
1269 #if 0
1270 printf("output:\n");
1271 hex_dump(stdout, pkt, pkt_len);
1272 #endif
1273 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1276 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1278 #if 0
1279 printf("input:\n");
1280 hex_dump(stdout, buf, size);
1281 #endif
1282 slirp_input(buf, size);
1285 static void slirp_add_read_packet(NetDriverState *nd,
1286 IOCanRWHandler *fd_can_read,
1287 IOReadHandler *fd_read, void *opaque)
1289 slirp_fd_opaque = opaque;
1290 slirp_fd_can_read = fd_can_read;
1291 slirp_fd_read = fd_read;
1294 static int net_slirp_init(NetDriverState *nd)
1296 if (!slirp_inited) {
1297 slirp_inited = 1;
1298 slirp_init();
1300 nd->send_packet = slirp_send_packet;
1301 nd->add_read_packet = slirp_add_read_packet;
1302 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1303 return 0;
1306 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1308 const char *p, *p1;
1309 int len;
1310 p = *pp;
1311 p1 = strchr(p, sep);
1312 if (!p1)
1313 return -1;
1314 len = p1 - p;
1315 p1++;
1316 if (buf_size > 0) {
1317 if (len > buf_size - 1)
1318 len = buf_size - 1;
1319 memcpy(buf, p, len);
1320 buf[len] = '\0';
1322 *pp = p1;
1323 return 0;
1326 static void net_slirp_redir(const char *redir_str)
1328 int is_udp;
1329 char buf[256], *r;
1330 const char *p;
1331 struct in_addr guest_addr;
1332 int host_port, guest_port;
1334 if (!slirp_inited) {
1335 slirp_inited = 1;
1336 slirp_init();
1339 p = redir_str;
1340 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1341 goto fail;
1342 if (!strcmp(buf, "tcp")) {
1343 is_udp = 0;
1344 } else if (!strcmp(buf, "udp")) {
1345 is_udp = 1;
1346 } else {
1347 goto fail;
1350 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1351 goto fail;
1352 host_port = strtol(buf, &r, 0);
1353 if (r == buf)
1354 goto fail;
1356 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1357 goto fail;
1358 if (buf[0] == '\0') {
1359 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1361 if (!inet_aton(buf, &guest_addr))
1362 goto fail;
1364 guest_port = strtol(p, &r, 0);
1365 if (r == p)
1366 goto fail;
1368 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1369 fprintf(stderr, "qemu: could not set up redirection\n");
1370 exit(1);
1372 return;
1373 fail:
1374 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1375 exit(1);
1378 #ifndef _WIN32
1380 char smb_dir[1024];
1382 static void smb_exit(void)
1384 DIR *d;
1385 struct dirent *de;
1386 char filename[1024];
1388 /* erase all the files in the directory */
1389 d = opendir(smb_dir);
1390 for(;;) {
1391 de = readdir(d);
1392 if (!de)
1393 break;
1394 if (strcmp(de->d_name, ".") != 0 &&
1395 strcmp(de->d_name, "..") != 0) {
1396 snprintf(filename, sizeof(filename), "%s/%s",
1397 smb_dir, de->d_name);
1398 unlink(filename);
1401 closedir(d);
1402 rmdir(smb_dir);
1405 /* automatic user mode samba server configuration */
1406 void net_slirp_smb(const char *exported_dir)
1408 char smb_conf[1024];
1409 char smb_cmdline[1024];
1410 FILE *f;
1412 if (!slirp_inited) {
1413 slirp_inited = 1;
1414 slirp_init();
1417 /* XXX: better tmp dir construction */
1418 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1419 if (mkdir(smb_dir, 0700) < 0) {
1420 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1421 exit(1);
1423 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1425 f = fopen(smb_conf, "w");
1426 if (!f) {
1427 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1428 exit(1);
1430 fprintf(f,
1431 "[global]\n"
1432 "pid directory=%s\n"
1433 "lock directory=%s\n"
1434 "log file=%s/log.smbd\n"
1435 "smb passwd file=%s/smbpasswd\n"
1436 "security = share\n"
1437 "[qemu]\n"
1438 "path=%s\n"
1439 "read only=no\n"
1440 "guest ok=yes\n",
1441 smb_dir,
1442 smb_dir,
1443 smb_dir,
1444 smb_dir,
1445 exported_dir
1446 );
1447 fclose(f);
1448 atexit(smb_exit);
1450 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1451 smb_conf);
1453 slirp_add_exec(0, smb_cmdline, 4, 139);
1456 #endif /* !defined(_WIN32) */
1458 #endif /* CONFIG_SLIRP */
1460 #if !defined(_WIN32)
1461 #ifdef _BSD
1462 static int tun_open(char *ifname, int ifname_size)
1464 int fd;
1465 char *dev;
1466 struct stat s;
1468 fd = open("/dev/tap", O_RDWR);
1469 if (fd < 0) {
1470 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1471 return -1;
1474 fstat(fd, &s);
1475 dev = devname(s.st_rdev, S_IFCHR);
1476 pstrcpy(ifname, ifname_size, dev);
1478 fcntl(fd, F_SETFL, O_NONBLOCK);
1479 return fd;
1481 #else
1482 static int tun_open(char *ifname, int ifname_size)
1484 struct ifreq ifr;
1485 int fd, ret;
1487 fd = open("/dev/net/tun", O_RDWR);
1488 if (fd < 0) {
1489 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1490 return -1;
1492 memset(&ifr, 0, sizeof(ifr));
1493 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1494 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1495 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1496 if (ret != 0) {
1497 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1498 close(fd);
1499 return -1;
1501 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1502 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1503 fcntl(fd, F_SETFL, O_NONBLOCK);
1504 return fd;
1506 #endif
1508 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1510 write(nd->fd, buf, size);
1513 static void tun_add_read_packet(NetDriverState *nd,
1514 IOCanRWHandler *fd_can_read,
1515 IOReadHandler *fd_read, void *opaque)
1517 qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1520 static int net_tun_init(NetDriverState *nd)
1522 int pid, status;
1523 char *args[3];
1524 char **parg;
1526 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1527 if (nd->fd < 0)
1528 return -1;
1530 /* try to launch network init script */
1531 pid = fork();
1532 if (pid >= 0) {
1533 if (pid == 0) {
1534 parg = args;
1535 *parg++ = network_script;
1536 *parg++ = nd->ifname;
1537 *parg++ = NULL;
1538 execv(network_script, args);
1539 exit(1);
1541 while (waitpid(pid, &status, 0) != pid);
1542 if (!WIFEXITED(status) ||
1543 WEXITSTATUS(status) != 0) {
1544 fprintf(stderr, "%s: could not launch network script\n",
1545 network_script);
1548 nd->send_packet = tun_send_packet;
1549 nd->add_read_packet = tun_add_read_packet;
1550 return 0;
1553 static int net_fd_init(NetDriverState *nd, int fd)
1555 nd->fd = fd;
1556 nd->send_packet = tun_send_packet;
1557 nd->add_read_packet = tun_add_read_packet;
1558 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1559 return 0;
1562 #endif /* !_WIN32 */
1564 /***********************************************************/
1565 /* dumb display */
1567 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1571 static void dumb_resize(DisplayState *ds, int w, int h)
1575 static void dumb_refresh(DisplayState *ds)
1577 vga_update_display();
1580 void dumb_display_init(DisplayState *ds)
1582 ds->data = NULL;
1583 ds->linesize = 0;
1584 ds->depth = 0;
1585 ds->dpy_update = dumb_update;
1586 ds->dpy_resize = dumb_resize;
1587 ds->dpy_refresh = dumb_refresh;
1590 #if !defined(CONFIG_SOFTMMU)
1591 /***********************************************************/
1592 /* cpu signal handler */
1593 static void host_segv_handler(int host_signum, siginfo_t *info,
1594 void *puc)
1596 abort();
1598 #endif
1600 /***********************************************************/
1601 /* I/O handling */
1603 #define MAX_IO_HANDLERS 64
1605 typedef struct IOHandlerRecord {
1606 int fd;
1607 IOCanRWHandler *fd_can_read;
1608 IOReadHandler *fd_read;
1609 void *opaque;
1610 /* temporary data */
1611 struct pollfd *ufd;
1612 int max_size;
1613 struct IOHandlerRecord *next;
1614 } IOHandlerRecord;
1616 static IOHandlerRecord *first_io_handler;
1618 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1619 IOReadHandler *fd_read, void *opaque)
1621 IOHandlerRecord *ioh;
1623 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1624 if (!ioh)
1625 return -1;
1626 ioh->fd = fd;
1627 ioh->fd_can_read = fd_can_read;
1628 ioh->fd_read = fd_read;
1629 ioh->opaque = opaque;
1630 ioh->next = first_io_handler;
1631 first_io_handler = ioh;
1632 return 0;
1635 void qemu_del_fd_read_handler(int fd)
1637 IOHandlerRecord **pioh, *ioh;
1639 pioh = &first_io_handler;
1640 for(;;) {
1641 ioh = *pioh;
1642 if (ioh == NULL)
1643 break;
1644 if (ioh->fd == fd) {
1645 *pioh = ioh->next;
1646 break;
1648 pioh = &ioh->next;
1652 /***********************************************************/
1653 /* savevm/loadvm support */
1655 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1657 fwrite(buf, 1, size, f);
1660 void qemu_put_byte(QEMUFile *f, int v)
1662 fputc(v, f);
1665 void qemu_put_be16(QEMUFile *f, unsigned int v)
1667 qemu_put_byte(f, v >> 8);
1668 qemu_put_byte(f, v);
1671 void qemu_put_be32(QEMUFile *f, unsigned int v)
1673 qemu_put_byte(f, v >> 24);
1674 qemu_put_byte(f, v >> 16);
1675 qemu_put_byte(f, v >> 8);
1676 qemu_put_byte(f, v);
1679 void qemu_put_be64(QEMUFile *f, uint64_t v)
1681 qemu_put_be32(f, v >> 32);
1682 qemu_put_be32(f, v);
1685 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1687 return fread(buf, 1, size, f);
1690 int qemu_get_byte(QEMUFile *f)
1692 int v;
1693 v = fgetc(f);
1694 if (v == EOF)
1695 return 0;
1696 else
1697 return v;
1700 unsigned int qemu_get_be16(QEMUFile *f)
1702 unsigned int v;
1703 v = qemu_get_byte(f) << 8;
1704 v |= qemu_get_byte(f);
1705 return v;
1708 unsigned int qemu_get_be32(QEMUFile *f)
1710 unsigned int v;
1711 v = qemu_get_byte(f) << 24;
1712 v |= qemu_get_byte(f) << 16;
1713 v |= qemu_get_byte(f) << 8;
1714 v |= qemu_get_byte(f);
1715 return v;
1718 uint64_t qemu_get_be64(QEMUFile *f)
1720 uint64_t v;
1721 v = (uint64_t)qemu_get_be32(f) << 32;
1722 v |= qemu_get_be32(f);
1723 return v;
1726 int64_t qemu_ftell(QEMUFile *f)
1728 return ftell(f);
1731 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1733 if (fseek(f, pos, whence) < 0)
1734 return -1;
1735 return ftell(f);
1738 typedef struct SaveStateEntry {
1739 char idstr[256];
1740 int instance_id;
1741 int version_id;
1742 SaveStateHandler *save_state;
1743 LoadStateHandler *load_state;
1744 void *opaque;
1745 struct SaveStateEntry *next;
1746 } SaveStateEntry;
1748 static SaveStateEntry *first_se;
1750 int register_savevm(const char *idstr,
1751 int instance_id,
1752 int version_id,
1753 SaveStateHandler *save_state,
1754 LoadStateHandler *load_state,
1755 void *opaque)
1757 SaveStateEntry *se, **pse;
1759 se = qemu_malloc(sizeof(SaveStateEntry));
1760 if (!se)
1761 return -1;
1762 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1763 se->instance_id = instance_id;
1764 se->version_id = version_id;
1765 se->save_state = save_state;
1766 se->load_state = load_state;
1767 se->opaque = opaque;
1768 se->next = NULL;
1770 /* add at the end of list */
1771 pse = &first_se;
1772 while (*pse != NULL)
1773 pse = &(*pse)->next;
1774 *pse = se;
1775 return 0;
1778 #define QEMU_VM_FILE_MAGIC 0x5145564d
1779 #define QEMU_VM_FILE_VERSION 0x00000001
1781 int qemu_savevm(const char *filename)
1783 SaveStateEntry *se;
1784 QEMUFile *f;
1785 int len, len_pos, cur_pos, saved_vm_running, ret;
1787 saved_vm_running = vm_running;
1788 vm_stop(0);
1790 f = fopen(filename, "wb");
1791 if (!f) {
1792 ret = -1;
1793 goto the_end;
1796 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1797 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1799 for(se = first_se; se != NULL; se = se->next) {
1800 /* ID string */
1801 len = strlen(se->idstr);
1802 qemu_put_byte(f, len);
1803 qemu_put_buffer(f, se->idstr, len);
1805 qemu_put_be32(f, se->instance_id);
1806 qemu_put_be32(f, se->version_id);
1808 /* record size: filled later */
1809 len_pos = ftell(f);
1810 qemu_put_be32(f, 0);
1812 se->save_state(f, se->opaque);
1814 /* fill record size */
1815 cur_pos = ftell(f);
1816 len = ftell(f) - len_pos - 4;
1817 fseek(f, len_pos, SEEK_SET);
1818 qemu_put_be32(f, len);
1819 fseek(f, cur_pos, SEEK_SET);
1822 fclose(f);
1823 ret = 0;
1824 the_end:
1825 if (saved_vm_running)
1826 vm_start();
1827 return ret;
1830 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1832 SaveStateEntry *se;
1834 for(se = first_se; se != NULL; se = se->next) {
1835 if (!strcmp(se->idstr, idstr) &&
1836 instance_id == se->instance_id)
1837 return se;
1839 return NULL;
1842 int qemu_loadvm(const char *filename)
1844 SaveStateEntry *se;
1845 QEMUFile *f;
1846 int len, cur_pos, ret, instance_id, record_len, version_id;
1847 int saved_vm_running;
1848 unsigned int v;
1849 char idstr[256];
1851 saved_vm_running = vm_running;
1852 vm_stop(0);
1854 f = fopen(filename, "rb");
1855 if (!f) {
1856 ret = -1;
1857 goto the_end;
1860 v = qemu_get_be32(f);
1861 if (v != QEMU_VM_FILE_MAGIC)
1862 goto fail;
1863 v = qemu_get_be32(f);
1864 if (v != QEMU_VM_FILE_VERSION) {
1865 fail:
1866 fclose(f);
1867 ret = -1;
1868 goto the_end;
1870 for(;;) {
1871 #if defined (DO_TB_FLUSH)
1872 tb_flush(global_env);
1873 #endif
1874 len = qemu_get_byte(f);
1875 if (feof(f))
1876 break;
1877 qemu_get_buffer(f, idstr, len);
1878 idstr[len] = '\0';
1879 instance_id = qemu_get_be32(f);
1880 version_id = qemu_get_be32(f);
1881 record_len = qemu_get_be32(f);
1882 #if 0
1883 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1884 idstr, instance_id, version_id, record_len);
1885 #endif
1886 cur_pos = ftell(f);
1887 se = find_se(idstr, instance_id);
1888 if (!se) {
1889 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1890 instance_id, idstr);
1891 } else {
1892 ret = se->load_state(f, se->opaque, version_id);
1893 if (ret < 0) {
1894 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1895 instance_id, idstr);
1898 /* always seek to exact end of record */
1899 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1901 fclose(f);
1902 ret = 0;
1903 the_end:
1904 if (saved_vm_running)
1905 vm_start();
1906 return ret;
1909 /***********************************************************/
1910 /* main execution loop */
1912 void gui_update(void *opaque)
1914 display_state.dpy_refresh(&display_state);
1915 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1917 void polling_handler(void *opaque)
1919 #ifndef _WIN32
1920 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1921 IOHandlerRecord *ioh, *ioh_next;
1922 uint8_t buf[4096];
1923 int n, max_size;
1924 #endif
1925 int timeout = 0;
1926 int ret;
1928 #ifdef _WIN32
1929 if (timeout > 0)
1930 Sleep(timeout);
1931 #else
1932 /* poll any events */
1933 /* XXX: separate device handlers from system ones */
1934 pf = ufds;
1935 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1936 if (!ioh->fd_can_read) {
1937 max_size = 0;
1938 pf->fd = ioh->fd;
1939 pf->events = POLLIN;
1940 ioh->ufd = pf;
1941 pf++;
1942 } else {
1943 max_size = ioh->fd_can_read(ioh->opaque);
1944 if (max_size > 0) {
1945 if (max_size > sizeof(buf))
1946 max_size = sizeof(buf);
1947 pf->fd = ioh->fd;
1948 pf->events = POLLIN;
1949 ioh->ufd = pf;
1950 pf++;
1951 } else {
1952 ioh->ufd = NULL;
1955 ioh->max_size = max_size;
1958 ret = poll(ufds, pf - ufds, timeout);
1959 if (ret > 0) {
1960 /* XXX: better handling of removal */
1961 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1962 ioh_next = ioh->next;
1963 pf = ioh->ufd;
1964 if (pf) {
1965 if (pf->revents & POLLIN) {
1966 if (ioh->max_size == 0) {
1967 /* just a read event */
1968 ioh->fd_read(ioh->opaque, NULL, 0);
1969 } else {
1970 n = read(ioh->fd, buf, ioh->max_size);
1971 if (n >= 0) {
1972 ioh->fd_read(ioh->opaque, buf, n);
1973 } else if (errno != EAGAIN) {
1974 ioh->fd_read(ioh->opaque, NULL, -errno);
1981 #endif /* !defined(_WIN32) */
1983 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
1987 /* XXX: support several handlers */
1988 VMStopHandler *vm_stop_cb;
1989 VMStopHandler *vm_stop_opaque;
1991 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1993 vm_stop_cb = cb;
1994 vm_stop_opaque = opaque;
1995 return 0;
1998 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2000 vm_stop_cb = NULL;
2003 void vm_start(void)
2005 if (!vm_running) {
2006 cpu_enable_ticks();
2007 vm_running = 1;
2011 void vm_stop(int reason)
2013 if (vm_running) {
2014 cpu_disable_ticks();
2015 vm_running = 0;
2016 if (reason != 0) {
2017 if (vm_stop_cb) {
2018 vm_stop_cb(vm_stop_opaque, reason);
2024 /* reset/shutdown handler */
2026 typedef struct QEMUResetEntry {
2027 QEMUResetHandler *func;
2028 void *opaque;
2029 struct QEMUResetEntry *next;
2030 } QEMUResetEntry;
2032 static QEMUResetEntry *first_reset_entry;
2033 int reset_requested;
2034 int shutdown_requested;
2036 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2038 QEMUResetEntry **pre, *re;
2040 pre = &first_reset_entry;
2041 while (*pre != NULL)
2042 pre = &(*pre)->next;
2043 re = qemu_mallocz(sizeof(QEMUResetEntry));
2044 re->func = func;
2045 re->opaque = opaque;
2046 re->next = NULL;
2047 *pre = re;
2050 void qemu_system_reset(void)
2052 QEMUResetEntry *re;
2054 /* reset all devices */
2055 for(re = first_reset_entry; re != NULL; re = re->next) {
2056 re->func(re->opaque);
2060 void qemu_system_reset_request(void)
2062 reset_requested = 1;
2063 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2066 void qemu_system_shutdown_request(void)
2068 shutdown_requested = 1;
2069 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2072 void main_loop_wait(int timeout)
2074 if (vm_running) {
2075 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2076 qemu_get_clock(vm_clock));
2077 /* run dma transfers, if any */
2078 DMA_run();
2081 /* real time timers */
2082 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2083 qemu_get_clock(rt_clock));
2086 void help(void)
2088 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2089 "usage: %s [options] [disk_image]\n"
2090 "\n"
2091 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2092 "\n"
2093 "Standard options:\n"
2094 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2095 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2096 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2097 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2098 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2099 "-snapshot write to temporary files instead of disk image files\n"
2100 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2101 "-nographic disable graphical output and redirect serial I/Os to console\n"
2102 #ifdef CONFIG_VNC
2103 "-vnc port use vnc instead of sdl\n"
2104 "-vncport port use a different port\n"
2105 "-vncconnect host:port do a reverse connect\n"
2106 #ifdef CONFIG_SDL
2107 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2108 #endif
2109 #endif
2110 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2111 "-enable-audio enable audio support\n"
2112 "-localtime set the real time clock to local time [default=utc]\n"
2113 "-full-screen start in full screen\n"
2114 #ifdef TARGET_PPC
2115 "-prep Simulate a PREP system (default is PowerMAC)\n"
2116 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2117 #endif
2118 "\n"
2119 "Network options:\n"
2120 "-nics n simulate 'n' network cards [default=1]\n"
2121 "-macaddr addr set the mac address of the first interface\n"
2122 "-n script set tap/tun network init script [default=%s]\n"
2123 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2124 #ifdef CONFIG_SLIRP
2125 "-user-net use user mode network stack [default if no tap/tun script]\n"
2126 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2127 #ifndef _WIN32
2128 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2129 #endif
2130 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2131 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2132 #endif
2133 "-dummy-net use dummy network stack\n"
2134 "\n"
2135 "Linux boot specific:\n"
2136 "-kernel bzImage use 'bzImage' as kernel image\n"
2137 "-append cmdline use 'cmdline' as kernel command line\n"
2138 "-initrd file use 'file' as initial ram disk\n"
2139 "\n"
2140 "Debug/Expert options:\n"
2141 "-monitor dev redirect the monitor to char device 'dev'\n"
2142 "-serial dev redirect the serial port to char device 'dev'\n"
2143 "-S freeze CPU at startup (use 'c' to start execution)\n"
2144 "-s wait gdb connection to port %d\n"
2145 "-p port ioreq port for xen\n"
2146 "-d domain domain that we're serving\n"
2147 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2148 "-L path set the directory for the BIOS and VGA BIOS\n"
2149 #ifdef USE_CODE_COPY
2150 "-no-code-copy disable code copy acceleration\n"
2151 #endif
2152 #ifdef TARGET_I386
2153 "-isa simulate an ISA-only system (default is PCI system)\n"
2154 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2155 " (default is CL-GD5446 PCI VGA)\n"
2156 #endif
2157 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2158 "\n"
2159 "During emulation, the following keys are useful:\n"
2160 "ctrl-alt-f toggle full screen\n"
2161 "ctrl-alt-n switch to virtual console 'n'\n"
2162 "ctrl-alt toggle mouse and keyboard grab\n"
2163 "\n"
2164 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2166 #ifdef CONFIG_SOFTMMU
2167 "qemu",
2168 #else
2169 "qemu-fast",
2170 #endif
2171 DEFAULT_RAM_SIZE,
2172 DEFAULT_NETWORK_SCRIPT,
2173 DEFAULT_GDBSTUB_PORT);
2174 #ifndef CONFIG_SOFTMMU
2175 printf("\n"
2176 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2177 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2178 "PC emulation.\n");
2179 #endif
2180 exit(1);
2183 #define HAS_ARG 0x0001
2185 enum {
2186 QEMU_OPTION_h,
2188 QEMU_OPTION_fda,
2189 QEMU_OPTION_fdb,
2190 QEMU_OPTION_hda,
2191 QEMU_OPTION_hdb,
2192 QEMU_OPTION_hdc,
2193 QEMU_OPTION_hdd,
2194 QEMU_OPTION_cdrom,
2195 QEMU_OPTION_boot,
2196 QEMU_OPTION_snapshot,
2197 QEMU_OPTION_m,
2198 QEMU_OPTION_nographic,
2199 #ifdef CONFIG_VNC
2200 QEMU_OPTION_vnc,
2201 QEMU_OPTION_vncport,
2202 QEMU_OPTION_vncconnect,
2203 #ifdef CONFIG_SDL
2204 QEMU_OPTION_vnc_and_sdl,
2205 #endif
2206 #endif
2207 QEMU_OPTION_enable_audio,
2209 QEMU_OPTION_nics,
2210 QEMU_OPTION_macaddr,
2211 QEMU_OPTION_n,
2212 QEMU_OPTION_tun_fd,
2213 QEMU_OPTION_user_net,
2214 QEMU_OPTION_tftp,
2215 QEMU_OPTION_smb,
2216 QEMU_OPTION_redir,
2217 QEMU_OPTION_dummy_net,
2219 QEMU_OPTION_kernel,
2220 QEMU_OPTION_append,
2221 QEMU_OPTION_initrd,
2223 QEMU_OPTION_S,
2224 QEMU_OPTION_s,
2225 QEMU_OPTION_p,
2226 QEMU_OPTION_d,
2227 QEMU_OPTION_l,
2228 QEMU_OPTION_hdachs,
2229 QEMU_OPTION_L,
2230 QEMU_OPTION_no_code_copy,
2231 QEMU_OPTION_pci,
2232 QEMU_OPTION_isa,
2233 QEMU_OPTION_prep,
2234 QEMU_OPTION_k,
2235 QEMU_OPTION_localtime,
2236 QEMU_OPTION_cirrusvga,
2237 QEMU_OPTION_g,
2238 QEMU_OPTION_std_vga,
2239 QEMU_OPTION_monitor,
2240 QEMU_OPTION_serial,
2241 QEMU_OPTION_loadvm,
2242 QEMU_OPTION_full_screen,
2243 };
2245 typedef struct QEMUOption {
2246 const char *name;
2247 int flags;
2248 int index;
2249 } QEMUOption;
2251 const QEMUOption qemu_options[] = {
2252 { "h", 0, QEMU_OPTION_h },
2254 { "fda", HAS_ARG, QEMU_OPTION_fda },
2255 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2256 { "hda", HAS_ARG, QEMU_OPTION_hda },
2257 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2258 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2259 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2260 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2261 { "boot", HAS_ARG, QEMU_OPTION_boot },
2262 { "snapshot", 0, QEMU_OPTION_snapshot },
2263 { "m", HAS_ARG, QEMU_OPTION_m },
2264 { "nographic", 0, QEMU_OPTION_nographic },
2265 #ifdef CONFIG_VNC
2266 { "vnc", 0, QEMU_OPTION_vnc },
2267 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2268 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2269 #ifdef CONFIG_SDL
2270 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2271 #endif
2272 #endif
2273 { "k", HAS_ARG, QEMU_OPTION_k },
2274 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2276 { "nics", HAS_ARG, QEMU_OPTION_nics},
2277 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2278 { "n", HAS_ARG, QEMU_OPTION_n },
2279 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2280 #ifdef CONFIG_SLIRP
2281 { "user-net", 0, QEMU_OPTION_user_net },
2282 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2283 #ifndef _WIN32
2284 { "smb", HAS_ARG, QEMU_OPTION_smb },
2285 #endif
2286 { "redir", HAS_ARG, QEMU_OPTION_redir },
2287 #endif
2288 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2290 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2291 { "append", HAS_ARG, QEMU_OPTION_append },
2292 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2294 { "S", 0, QEMU_OPTION_S },
2295 { "s", 0, QEMU_OPTION_s },
2296 { "p", HAS_ARG, QEMU_OPTION_p },
2297 { "d", HAS_ARG, QEMU_OPTION_d },
2298 { "l", HAS_ARG, QEMU_OPTION_l },
2299 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2300 { "L", HAS_ARG, QEMU_OPTION_L },
2301 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2302 #ifdef TARGET_PPC
2303 { "prep", 0, QEMU_OPTION_prep },
2304 { "g", 1, QEMU_OPTION_g },
2305 #endif
2306 { "localtime", 0, QEMU_OPTION_localtime },
2307 { "isa", 0, QEMU_OPTION_isa },
2308 { "std-vga", 0, QEMU_OPTION_std_vga },
2309 { "monitor", 1, QEMU_OPTION_monitor },
2310 { "serial", 1, QEMU_OPTION_serial },
2311 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2312 { "full-screen", 0, QEMU_OPTION_full_screen },
2314 /* temporary options */
2315 { "pci", 0, QEMU_OPTION_pci },
2316 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2317 { NULL },
2318 };
2320 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2322 /* this stack is only used during signal handling */
2323 #define SIGNAL_STACK_SIZE 32768
2325 static uint8_t *signal_stack;
2327 #endif
2329 #define NET_IF_TUN 0
2330 #define NET_IF_USER 1
2331 #define NET_IF_DUMMY 2
2333 int main(int argc, char **argv)
2335 #ifdef CONFIG_GDBSTUB
2336 int use_gdbstub, gdbstub_port;
2337 #endif
2338 int i, has_cdrom;
2339 int snapshot, linux_boot;
2340 CPUState *env;
2341 const char *initrd_filename;
2342 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2343 const char *kernel_filename, *kernel_cmdline;
2344 DisplayState *ds = &display_state;
2345 int cyls, heads, secs;
2346 int start_emulation = 1;
2347 uint8_t macaddr[6];
2348 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2349 int optind;
2350 const char *r, *optarg;
2351 CharDriverState *monitor_hd;
2352 char monitor_device[128];
2353 char serial_devices[MAX_SERIAL_PORTS][128];
2354 int serial_device_index;
2355 const char *loadvm = NULL;
2356 unsigned long nr_pages, *page_array;
2357 extern void *shared_page;
2358 /* change the qemu-dm to daemon, just like bochs dm */
2359 // daemon(0, 0);
2361 #if !defined(CONFIG_SOFTMMU)
2362 /* we never want that malloc() uses mmap() */
2363 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2364 #endif
2365 initrd_filename = NULL;
2366 for(i = 0; i < MAX_FD; i++)
2367 fd_filename[i] = NULL;
2368 for(i = 0; i < MAX_DISKS; i++)
2369 hd_filename[i] = NULL;
2370 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2371 vga_ram_size = VGA_RAM_SIZE;
2372 bios_size = BIOS_SIZE;
2373 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2374 #ifdef CONFIG_GDBSTUB
2375 use_gdbstub = 0;
2376 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2377 #endif
2378 snapshot = 0;
2379 nographic = 0;
2380 usevnc = 0;
2381 vncport=0;
2382 vncconnect=NULL;
2383 kernel_filename = NULL;
2384 kernel_cmdline = "";
2385 has_cdrom = 1;
2386 cyls = heads = secs = 0;
2387 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2389 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2390 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2391 serial_devices[i][0] = '\0';
2392 serial_device_index = 0;
2394 nb_tun_fds = 0;
2395 net_if_type = -1;
2396 nb_nics = 1;
2397 /* default mac address of the first network interface */
2398 macaddr[0] = 0x52;
2399 macaddr[1] = 0x54;
2400 macaddr[2] = 0x00;
2401 macaddr[3] = 0x12;
2402 macaddr[4] = 0x34;
2403 macaddr[5] = 0x56;
2405 /* init debug */
2406 cpu_set_log(0);
2408 optind = 1;
2409 for(;;) {
2410 if (optind >= argc)
2411 break;
2412 r = argv[optind];
2413 if (r[0] != '-') {
2414 hd_filename[0] = argv[optind++];
2415 } else {
2416 const QEMUOption *popt;
2418 optind++;
2419 popt = qemu_options;
2420 for(;;) {
2421 if (!popt->name) {
2422 fprintf(stderr, "%s: invalid option -- '%s'\n",
2423 argv[0], r);
2424 exit(1);
2426 if (!strcmp(popt->name, r + 1))
2427 break;
2428 popt++;
2430 if (popt->flags & HAS_ARG) {
2431 if (optind >= argc) {
2432 fprintf(stderr, "%s: option '%s' requires an argument\n",
2433 argv[0], r);
2434 exit(1);
2436 optarg = argv[optind++];
2437 } else {
2438 optarg = NULL;
2441 switch(popt->index) {
2442 case QEMU_OPTION_initrd:
2443 initrd_filename = optarg;
2444 break;
2445 case QEMU_OPTION_hda:
2446 hd_filename[0] = optarg;
2447 break;
2448 case QEMU_OPTION_hdb:
2449 hd_filename[1] = optarg;
2450 break;
2451 case QEMU_OPTION_snapshot:
2452 snapshot = 1;
2453 break;
2454 case QEMU_OPTION_hdachs:
2456 const char *p;
2457 p = optarg;
2458 cyls = strtol(p, (char **)&p, 0);
2459 if (*p != ',')
2460 goto chs_fail;
2461 p++;
2462 heads = strtol(p, (char **)&p, 0);
2463 if (*p != ',')
2464 goto chs_fail;
2465 p++;
2466 secs = strtol(p, (char **)&p, 0);
2467 if (*p != '\0') {
2468 chs_fail:
2469 cyls = 0;
2472 break;
2473 case QEMU_OPTION_nographic:
2474 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2475 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
2476 nographic = 1;
2477 break;
2478 #ifdef CONFIG_VNC
2479 case QEMU_OPTION_vnc:
2480 usevnc = 1;
2481 break;
2482 case QEMU_OPTION_vncport:
2484 const char *p;
2485 p = optarg;
2486 vncport= strtol(optarg, (char **)&p, 0);
2488 break;
2489 case QEMU_OPTION_vncconnect:
2491 vncconnect=optarg;
2493 break;
2494 #ifdef CONFIG_SDL
2495 case QEMU_OPTION_vnc_and_sdl:
2496 usevnc = 2;
2497 break;
2498 #endif
2499 #endif
2500 case QEMU_OPTION_kernel:
2501 kernel_filename = optarg;
2502 break;
2503 case QEMU_OPTION_append:
2504 kernel_cmdline = optarg;
2505 break;
2506 case QEMU_OPTION_tun_fd:
2508 const char *p;
2509 int fd;
2510 net_if_type = NET_IF_TUN;
2511 if (nb_tun_fds < MAX_NICS) {
2512 fd = strtol(optarg, (char **)&p, 0);
2513 if (*p != '\0') {
2514 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2515 exit(1);
2517 tun_fds[nb_tun_fds++] = fd;
2520 break;
2521 case QEMU_OPTION_hdc:
2522 hd_filename[2] = optarg;
2523 has_cdrom = 0;
2524 break;
2525 case QEMU_OPTION_hdd:
2526 hd_filename[3] = optarg;
2527 break;
2528 case QEMU_OPTION_cdrom:
2529 hd_filename[2] = optarg;
2530 has_cdrom = 1;
2531 break;
2532 case QEMU_OPTION_boot:
2533 boot_device = optarg[0];
2534 if (boot_device != 'a' &&
2535 boot_device != 'c' && boot_device != 'd') {
2536 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2537 exit(1);
2539 break;
2540 case QEMU_OPTION_fda:
2541 fd_filename[0] = optarg;
2542 break;
2543 case QEMU_OPTION_fdb:
2544 fd_filename[1] = optarg;
2545 break;
2546 case QEMU_OPTION_nics:
2547 nb_nics = atoi(optarg);
2548 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2549 fprintf(stderr, "qemu: invalid number of network interfaces\n");
2550 exit(1);
2552 break;
2553 case QEMU_OPTION_macaddr:
2555 const char *p;
2556 int i;
2557 p = optarg;
2558 for(i = 0; i < 6; i++) {
2559 macaddr[i] = strtol(p, (char **)&p, 16);
2560 if (i == 5) {
2561 if (*p != '\0')
2562 goto macaddr_error;
2563 } else {
2564 if (*p != ':') {
2565 macaddr_error:
2566 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2567 exit(1);
2569 p++;
2573 break;
2574 #ifdef CONFIG_SLIRP
2575 case QEMU_OPTION_tftp:
2576 tftp_prefix = optarg;
2577 break;
2578 #ifndef _WIN32
2579 case QEMU_OPTION_smb:
2580 net_slirp_smb(optarg);
2581 break;
2582 #endif
2583 case QEMU_OPTION_user_net:
2584 net_if_type = NET_IF_USER;
2585 break;
2586 case QEMU_OPTION_redir:
2587 net_slirp_redir(optarg);
2588 break;
2589 #endif
2590 case QEMU_OPTION_dummy_net:
2591 net_if_type = NET_IF_DUMMY;
2592 break;
2593 case QEMU_OPTION_enable_audio:
2594 audio_enabled = 1;
2595 break;
2596 case QEMU_OPTION_h:
2597 help();
2598 break;
2599 case QEMU_OPTION_m:
2600 ram_size = atoi(optarg) * 1024 * 1024;
2601 if (ram_size <= 0)
2602 help();
2603 break;
2604 case QEMU_OPTION_d:
2606 domid = atoi(optarg);
2607 printf("domid: %d\n", domid);
2609 break;
2611 case QEMU_OPTION_p:
2613 extern short ioreq_port;
2614 ioreq_port = atoi(optarg);
2615 printf("port: %d\n", ioreq_port);
2617 break;
2618 case QEMU_OPTION_l:
2620 int mask;
2621 mask = cpu_str_to_log_mask(optarg);
2622 printf("mask: %x\n", mask);
2623 cpu_set_log(mask);
2625 break;
2626 case QEMU_OPTION_n:
2627 pstrcpy(network_script, sizeof(network_script), optarg);
2628 break;
2629 #ifdef CONFIG_GDBSTUB
2630 case QEMU_OPTION_s:
2631 use_gdbstub = 1;
2632 break;
2633 #endif
2634 case QEMU_OPTION_L:
2635 bios_dir = optarg;
2636 break;
2637 case QEMU_OPTION_S:
2638 start_emulation = 0;
2639 break;
2640 case QEMU_OPTION_pci:
2641 pci_enabled = 1;
2642 break;
2643 case QEMU_OPTION_isa:
2644 pci_enabled = 0;
2645 break;
2646 case QEMU_OPTION_prep:
2647 prep_enabled = 1;
2648 break;
2649 case QEMU_OPTION_k:
2650 keyboard_layout = optarg;
2651 break;
2652 case QEMU_OPTION_localtime:
2653 rtc_utc = 0;
2654 break;
2655 case QEMU_OPTION_cirrusvga:
2656 cirrus_vga_enabled = 1;
2657 break;
2658 case QEMU_OPTION_std_vga:
2659 cirrus_vga_enabled = 0;
2660 break;
2661 case QEMU_OPTION_g:
2663 const char *p;
2664 int w, h, depth;
2665 p = optarg;
2666 w = strtol(p, (char **)&p, 10);
2667 if (w <= 0) {
2668 graphic_error:
2669 fprintf(stderr, "qemu: invalid resolution or depth\n");
2670 exit(1);
2672 if (*p != 'x')
2673 goto graphic_error;
2674 p++;
2675 h = strtol(p, (char **)&p, 10);
2676 if (h <= 0)
2677 goto graphic_error;
2678 if (*p == 'x') {
2679 p++;
2680 depth = strtol(p, (char **)&p, 10);
2681 if (depth != 8 && depth != 15 && depth != 16 &&
2682 depth != 24 && depth != 32)
2683 goto graphic_error;
2684 } else if (*p == '\0') {
2685 depth = graphic_depth;
2686 } else {
2687 goto graphic_error;
2690 graphic_width = w;
2691 graphic_height = h;
2692 graphic_depth = depth;
2694 break;
2695 case QEMU_OPTION_monitor:
2696 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2697 break;
2698 case QEMU_OPTION_serial:
2699 if (serial_device_index >= MAX_SERIAL_PORTS) {
2700 fprintf(stderr, "qemu: too many serial ports\n");
2701 exit(1);
2703 pstrcpy(serial_devices[serial_device_index],
2704 sizeof(serial_devices[0]), optarg);
2705 serial_device_index++;
2706 break;
2707 case QEMU_OPTION_loadvm:
2708 loadvm = optarg;
2709 break;
2710 case QEMU_OPTION_full_screen:
2711 full_screen = 1;
2712 break;
2717 linux_boot = (kernel_filename != NULL);
2719 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2720 fd_filename[0] == '\0')
2721 help();
2723 /* boot to cd by default if no hard disk */
2724 if (hd_filename[0] == '\0' && boot_device == 'c') {
2725 if (fd_filename[0] != '\0')
2726 boot_device = 'a';
2727 else
2728 boot_device = 'd';
2731 #if !defined(CONFIG_SOFTMMU)
2732 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2734 static uint8_t stdout_buf[4096];
2735 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2737 #else
2738 setvbuf(stdout, NULL, _IOLBF, 0);
2739 #endif
2741 /* init host network redirectors */
2742 if (net_if_type == -1) {
2743 net_if_type = NET_IF_TUN;
2744 #if defined(CONFIG_SLIRP)
2745 if (access(network_script, R_OK) < 0) {
2746 net_if_type = NET_IF_USER;
2748 #endif
2751 for(i = 0; i < nb_nics; i++) {
2752 NetDriverState *nd = &nd_table[i];
2753 nd->index = i;
2754 /* init virtual mac address */
2755 nd->macaddr[0] = macaddr[0];
2756 nd->macaddr[1] = macaddr[1];
2757 nd->macaddr[2] = macaddr[2];
2758 nd->macaddr[3] = macaddr[3];
2759 nd->macaddr[4] = macaddr[4];
2760 nd->macaddr[5] = macaddr[5] + i;
2761 switch(net_if_type) {
2762 #if defined(CONFIG_SLIRP)
2763 case NET_IF_USER:
2764 net_slirp_init(nd);
2765 break;
2766 #endif
2767 #if !defined(_WIN32)
2768 case NET_IF_TUN:
2769 if (i < nb_tun_fds) {
2770 net_fd_init(nd, tun_fds[i]);
2771 } else {
2772 if (net_tun_init(nd) < 0)
2773 net_dummy_init(nd);
2775 break;
2776 #endif
2777 case NET_IF_DUMMY:
2778 default:
2779 net_dummy_init(nd);
2780 break;
2784 /* init the memory */
2785 phys_ram_size = ram_size + vga_ram_size + bios_size;
2787 #define PAGE_SHIFT 12
2788 #define PAGE_SIZE (1 << PAGE_SHIFT)
2790 nr_pages = ram_size/PAGE_SIZE;
2791 xc_handle = xc_interface_open();
2793 if ( (page_array = (unsigned long *)
2794 malloc(nr_pages * sizeof(unsigned long))) == NULL)
2796 perror("malloc");
2797 exit(-1);
2800 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
2802 perror("xc_get_pfn_list");
2803 exit(-1);
2806 if ((phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
2807 PROT_READ|PROT_WRITE,
2808 page_array,
2809 nr_pages - 1)) == 0) {
2810 perror("xc_map_foreign_batch");
2811 exit(-1);
2814 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
2815 PROT_READ|PROT_WRITE,
2816 page_array[nr_pages - 1]);
2819 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
2820 (page_array[nr_pages - 1]));
2822 /* we always create the cdrom drive, even if no disk is there */
2823 bdrv_init();
2824 if (has_cdrom) {
2825 bs_table[2] = bdrv_new("cdrom");
2826 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2829 /* open the virtual block devices */
2830 for(i = 0; i < MAX_DISKS; i++) {
2831 if (hd_filename[i]) {
2832 if (!bs_table[i]) {
2833 char buf[64];
2834 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2835 bs_table[i] = bdrv_new(buf);
2837 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2838 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
2839 hd_filename[i]);
2840 exit(1);
2842 if (i == 0 && cyls != 0)
2843 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2847 /* we always create at least one floppy disk */
2848 fd_table[0] = bdrv_new("fda");
2849 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2851 for(i = 0; i < MAX_FD; i++) {
2852 if (fd_filename[i]) {
2853 if (!fd_table[i]) {
2854 char buf[64];
2855 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2856 fd_table[i] = bdrv_new(buf);
2857 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2859 if (fd_filename[i] != '\0') {
2860 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2861 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2862 fd_filename[i]);
2863 exit(1);
2869 /* init CPU state */
2870 env = cpu_init();
2871 global_env = env;
2872 cpu_single_env = env;
2874 init_ioports();
2875 cpu_calibrate_ticks();
2877 /* terminal init */
2878 if (nographic) {
2879 dumb_display_init(ds);
2880 } else {
2881 if (usevnc) {
2882 #ifdef CONFIG_VNC
2883 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
2884 #else
2885 perror("qemu not configured with vnc support");
2886 #endif
2887 } else {
2888 #ifdef CONFIG_SDL
2889 sdl_display_init(ds, full_screen);
2890 #else
2891 dumb_display_init(ds);
2892 #endif
2896 vga_console = graphic_console_init(ds);
2898 monitor_hd = qemu_chr_open(monitor_device);
2899 if (!monitor_hd) {
2900 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
2901 exit(1);
2903 monitor_init(monitor_hd, !nographic);
2905 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
2906 if (serial_devices[i][0] != '\0') {
2907 serial_hds[i] = qemu_chr_open(serial_devices[i]);
2908 if (!serial_hds[i]) {
2909 fprintf(stderr, "qemu: could not open serial device '%s'\n",
2910 serial_devices[i]);
2911 exit(1);
2913 if (!strcmp(serial_devices[i], "vc"))
2914 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
2918 /* setup cpu signal handlers for MMU / self modifying code handling */
2919 #if !defined(CONFIG_SOFTMMU)
2921 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2923 stack_t stk;
2924 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2925 stk.ss_sp = signal_stack;
2926 stk.ss_size = SIGNAL_STACK_SIZE;
2927 stk.ss_flags = 0;
2929 if (sigaltstack(&stk, NULL) < 0) {
2930 perror("sigaltstack");
2931 exit(1);
2934 #endif
2936 struct sigaction act;
2938 sigfillset(&act.sa_mask);
2939 act.sa_flags = SA_SIGINFO;
2940 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2941 act.sa_flags |= SA_ONSTACK;
2942 #endif
2943 act.sa_sigaction = host_segv_handler;
2944 sigaction(SIGSEGV, &act, NULL);
2945 sigaction(SIGBUS, &act, NULL);
2946 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2947 sigaction(SIGFPE, &act, NULL);
2948 #endif
2950 #endif
2952 #ifndef _WIN32
2954 struct sigaction act;
2955 sigfillset(&act.sa_mask);
2956 act.sa_flags = 0;
2957 act.sa_handler = SIG_IGN;
2958 sigaction(SIGPIPE, &act, NULL);
2960 #endif
2961 init_timers();
2963 #if defined(TARGET_I386)
2964 pc_init(ram_size, vga_ram_size, boot_device,
2965 ds, fd_filename, snapshot,
2966 kernel_filename, kernel_cmdline, initrd_filename);
2967 #elif defined(TARGET_PPC)
2968 ppc_init(ram_size, vga_ram_size, boot_device,
2969 ds, fd_filename, snapshot,
2970 kernel_filename, kernel_cmdline, initrd_filename);
2971 #elif defined(TARGET_SPARC)
2972 sun4m_init(ram_size, vga_ram_size, boot_device,
2973 ds, fd_filename, snapshot,
2974 kernel_filename, kernel_cmdline, initrd_filename);
2975 #endif
2977 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2978 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2980 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
2981 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
2983 #ifdef CONFIG_GDBSTUB
2984 if (use_gdbstub) {
2985 if (gdbserver_start(gdbstub_port) < 0) {
2986 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
2987 gdbstub_port);
2988 exit(1);
2989 } else {
2990 printf("Waiting gdb connection on port %d\n", gdbstub_port);
2992 } else
2993 #endif
2994 if (loadvm)
2995 qemu_loadvm(loadvm);
2998 /* XXX: simplify init */
2999 if (start_emulation) {
3000 vm_start();
3003 main_loop();
3004 quit_timers();
3005 return 0;