ia64/xen-unstable

view tools/ioemu/vl.c @ 7888:5b5f1b0aca33

Set up fully-virtualised RTC time zone default to local
time (not UTC).

Signed-off-by: Winston Wang <winston.l.wang@intel.com>
author kaf24@firebug.cl.cam.ac.uk
date Fri Nov 18 12:42:59 2005 +0100 (2005-11-18)
parents 6a593de2f8ba
children f7c7575695b3
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"
25 #ifdef __ia64__
26 #include <xen/arch-ia64.h>
27 #endif
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <sys/time.h>
36 #ifndef _WIN32
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/poll.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <dirent.h>
46 #ifdef _BSD
47 #include <sys/stat.h>
48 #ifndef __APPLE__
49 #include <libutil.h>
50 #endif
51 #else
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #endif
58 #endif
60 #if defined(CONFIG_SLIRP)
61 #include "libslirp.h"
62 #endif
64 #ifdef _WIN32
65 #include <malloc.h>
66 #include <sys/timeb.h>
67 #include <windows.h>
68 #define getopt_long_only getopt_long
69 #define memalign(align, size) malloc(size)
70 #endif
72 #ifdef CONFIG_SDL
73 #ifdef __APPLE__
74 #include <SDL/SDL.h>
75 #endif
76 #endif /* CONFIG_SDL */
78 #include "xenctrl.h"
79 #include "xs.h"
80 #include "exec-all.h"
82 //#define DO_TB_FLUSH
84 #define DEFAULT_NETWORK_SCRIPT "/etc/xen/qemu-ifup"
86 #if !defined(CONFIG_SOFTMMU)
87 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
88 #else
89 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
90 #endif
92 #ifdef TARGET_PPC
93 #define DEFAULT_RAM_SIZE 144
94 #else
95 #define DEFAULT_RAM_SIZE 128
96 #endif
97 /* in ms */
98 #define GUI_REFRESH_INTERVAL 30
99 #define POLLING_INTERVAL 5
101 /* XXX: use a two level table to limit memory usage */
102 #define MAX_IOPORTS 65536
104 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
105 char phys_ram_file[1024];
106 CPUState *global_env;
107 CPUState *cpu_single_env;
108 void *ioport_opaque[MAX_IOPORTS];
109 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
110 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
111 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
112 int vga_ram_size;
113 int bios_size;
114 static DisplayState display_state;
115 int nographic;
116 int usevnc; /* 1=vnc only, 2=vnc and sdl */
117 long vncport; /* server port */
118 const char* vncconnect; /* do a reverse connect to this host*/
119 const char* keyboard_layout = 0;
120 int64_t ticks_per_sec;
121 int boot_device = 'c';
122 int ram_size;
123 int domid = -1;
124 static char network_script[1024];
125 int pit_min_timer_count = 0;
126 int nb_nics;
127 char bridge[16];
128 NetDriverState nd_table[MAX_NICS];
129 QEMUTimer *gui_timer;
130 QEMUTimer *polling_timer;
131 int vm_running;
132 int audio_enabled = 0;
133 int nic_ne2000 = 0;
134 int vcpus = 1;
135 int sb16_enabled = 1;
136 int adlib_enabled = 1;
137 int gus_enabled = 1;
138 int pci_enabled = 1;
139 int prep_enabled = 0;
140 int rtc_utc = 0;
141 int cirrus_vga_enabled = 1;
142 int vga_accelerate = 1;
143 int graphic_width = 800;
144 int graphic_height = 600;
145 int graphic_depth = 15;
146 int full_screen = 0;
147 TextConsole *vga_console;
148 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
149 int xc_handle;
150 unsigned long *vgapage_array;
151 unsigned long *freepage_array;
152 unsigned long free_pages;
153 void *vtop_table;
154 unsigned long toptab;
155 unsigned long vgaram_pages;
157 /***********************************************************/
158 /* x86 ISA bus support */
160 target_phys_addr_t isa_mem_base = 0;
162 uint32_t default_ioport_readb(void *opaque, uint32_t address)
163 {
164 #ifdef DEBUG_UNUSED_IOPORT
165 fprintf(stderr, "inb: port=0x%04x\n", address);
166 #endif
167 return 0xff;
168 }
170 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
171 {
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
174 #endif
175 }
177 /* default is to make two byte accesses */
178 uint32_t default_ioport_readw(void *opaque, uint32_t address)
179 {
180 uint32_t data;
181 data = ioport_read_table[0][address](ioport_opaque[address], address);
182 address = (address + 1) & (MAX_IOPORTS - 1);
183 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
184 return data;
185 }
187 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
188 {
189 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
192 }
194 uint32_t default_ioport_readl(void *opaque, uint32_t address)
195 {
196 #ifdef DEBUG_UNUSED_IOPORT
197 fprintf(stderr, "inl: port=0x%04x\n", address);
198 #endif
199 return 0xffffffff;
200 }
202 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
203 {
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
206 #endif
207 }
209 void init_ioports(void)
210 {
211 int i;
213 for(i = 0; i < MAX_IOPORTS; i++) {
214 ioport_read_table[0][i] = default_ioport_readb;
215 ioport_write_table[0][i] = default_ioport_writeb;
216 ioport_read_table[1][i] = default_ioport_readw;
217 ioport_write_table[1][i] = default_ioport_writew;
218 ioport_read_table[2][i] = default_ioport_readl;
219 ioport_write_table[2][i] = default_ioport_writel;
220 }
221 }
223 /* size is the word size in byte */
224 int register_ioport_read(int start, int length, int size,
225 IOPortReadFunc *func, void *opaque)
226 {
227 int i, bsize;
229 if (size == 1) {
230 bsize = 0;
231 } else if (size == 2) {
232 bsize = 1;
233 } else if (size == 4) {
234 bsize = 2;
235 } else {
236 hw_error("register_ioport_read: invalid size");
237 return -1;
238 }
239 for(i = start; i < start + length; i += size) {
240 ioport_read_table[bsize][i] = func;
241 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
242 hw_error("register_ioport_read: invalid opaque");
243 ioport_opaque[i] = opaque;
244 }
245 return 0;
246 }
248 /* size is the word size in byte */
249 int register_ioport_write(int start, int length, int size,
250 IOPortWriteFunc *func, void *opaque)
251 {
252 int i, bsize;
254 if (size == 1) {
255 bsize = 0;
256 } else if (size == 2) {
257 bsize = 1;
258 } else if (size == 4) {
259 bsize = 2;
260 } else {
261 hw_error("register_ioport_write: invalid size");
262 return -1;
263 }
264 for(i = start; i < start + length; i += size) {
265 ioport_write_table[bsize][i] = func;
266 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
267 hw_error("register_ioport_read: invalid opaque");
268 ioport_opaque[i] = opaque;
269 }
270 return 0;
271 }
273 void isa_unassign_ioport(int start, int length)
274 {
275 int i;
277 for(i = start; i < start + length; i++) {
278 ioport_read_table[0][i] = default_ioport_readb;
279 ioport_read_table[1][i] = default_ioport_readw;
280 ioport_read_table[2][i] = default_ioport_readl;
282 ioport_write_table[0][i] = default_ioport_writeb;
283 ioport_write_table[1][i] = default_ioport_writew;
284 ioport_write_table[2][i] = default_ioport_writel;
285 }
286 }
288 void pstrcpy(char *buf, int buf_size, const char *str)
289 {
290 int c;
291 char *q = buf;
293 if (buf_size <= 0)
294 return;
296 for(;;) {
297 c = *str++;
298 if (c == 0 || q >= buf + buf_size - 1)
299 break;
300 *q++ = c;
301 }
302 *q = '\0';
303 }
305 /* strcat and truncate. */
306 char *pstrcat(char *buf, int buf_size, const char *s)
307 {
308 int len;
309 len = strlen(buf);
310 if (len < buf_size)
311 pstrcpy(buf + len, buf_size - len, s);
312 return buf;
313 }
315 int strstart(const char *str, const char *val, const char **ptr)
316 {
317 const char *p, *q;
318 p = str;
319 q = val;
320 while (*q != '\0') {
321 if (*p != *q)
322 return 0;
323 p++;
324 q++;
325 }
326 if (ptr)
327 *ptr = p;
328 return 1;
329 }
331 /* return the size or -1 if error */
332 int get_image_size(const char *filename)
333 {
334 int fd, size;
335 fd = open(filename, O_RDONLY | O_BINARY);
336 if (fd < 0)
337 return -1;
338 size = lseek(fd, 0, SEEK_END);
339 close(fd);
340 return size;
341 }
343 /* return the size or -1 if error */
344 int load_image(const char *filename, uint8_t *addr)
345 {
346 int fd, size;
347 fd = open(filename, O_RDONLY | O_BINARY);
348 if (fd < 0)
349 return -1;
350 size = lseek(fd, 0, SEEK_END);
351 lseek(fd, 0, SEEK_SET);
352 if (read(fd, addr, size) != size) {
353 close(fd);
354 return -1;
355 }
356 close(fd);
357 return size;
358 }
360 void cpu_outb(CPUState *env, int addr, int val)
361 {
362 #ifdef DEBUG_IOPORT
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outb: %04x %02x\n", addr, val);
365 #endif
366 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
367 }
369 void cpu_outw(CPUState *env, int addr, int val)
370 {
371 #ifdef DEBUG_IOPORT
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outw: %04x %04x\n", addr, val);
374 #endif
375 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
376 }
378 void cpu_outl(CPUState *env, int addr, int val)
379 {
380 #ifdef DEBUG_IOPORT
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "outl: %04x %08x\n", addr, val);
383 #endif
384 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
385 }
387 int cpu_inb(CPUState *env, int addr)
388 {
389 int val;
390 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
391 #ifdef DEBUG_IOPORT
392 if (loglevel & CPU_LOG_IOPORT)
393 fprintf(logfile, "inb : %04x %02x\n", addr, val);
394 #endif
395 return val;
396 }
398 int cpu_inw(CPUState *env, int addr)
399 {
400 int val;
401 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
402 #ifdef DEBUG_IOPORT
403 if (loglevel & CPU_LOG_IOPORT)
404 fprintf(logfile, "inw : %04x %04x\n", addr, val);
405 #endif
406 return val;
407 }
409 int cpu_inl(CPUState *env, int addr)
410 {
411 int val;
412 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
413 #ifdef DEBUG_IOPORT
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "inl : %04x %08x\n", addr, val);
416 #endif
417 return val;
418 }
420 /***********************************************************/
421 void hw_error(const char *fmt, ...)
422 {
423 va_list ap;
425 va_start(ap, fmt);
426 fprintf(stderr, "qemu: hardware error: ");
427 vfprintf(stderr, fmt, ap);
428 fprintf(stderr, "\n");
429 if (logfile) {
430 fprintf(logfile, "qemu: hardware error: ");
431 vfprintf(logfile, fmt, ap);
432 fprintf(logfile, "\n");
433 }
434 va_end(ap);
435 abort();
436 }
438 /***********************************************************/
439 /* keyboard/mouse */
441 static QEMUPutKBDEvent *qemu_put_kbd_event;
442 static void *qemu_put_kbd_event_opaque;
443 static QEMUPutMouseEvent *qemu_put_mouse_event;
444 static void *qemu_put_mouse_event_opaque;
446 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
447 {
448 qemu_put_kbd_event_opaque = opaque;
449 qemu_put_kbd_event = func;
450 }
452 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
453 {
454 qemu_put_mouse_event_opaque = opaque;
455 qemu_put_mouse_event = func;
456 }
458 void kbd_put_keycode(int keycode)
459 {
460 if (qemu_put_kbd_event) {
461 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
462 }
463 }
465 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
466 {
467 if (qemu_put_mouse_event) {
468 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
469 dx, dy, dz, buttons_state);
470 }
471 }
473 /***********************************************************/
474 /* timers */
476 #if defined(__powerpc__)
478 static inline uint32_t get_tbl(void)
479 {
480 uint32_t tbl;
481 asm volatile("mftb %0" : "=r" (tbl));
482 return tbl;
483 }
485 static inline uint32_t get_tbu(void)
486 {
487 uint32_t tbl;
488 asm volatile("mftbu %0" : "=r" (tbl));
489 return tbl;
490 }
492 int64_t cpu_get_real_ticks(void)
493 {
494 uint32_t l, h, h1;
495 /* NOTE: we test if wrapping has occurred */
496 do {
497 h = get_tbu();
498 l = get_tbl();
499 h1 = get_tbu();
500 } while (h != h1);
501 return ((int64_t)h << 32) | l;
502 }
504 #elif defined(__i386__)
506 int64_t cpu_get_real_ticks(void)
507 {
508 int64_t val;
509 asm volatile ("rdtsc" : "=A" (val));
510 return val;
511 }
513 #elif defined(__x86_64__)
515 int64_t cpu_get_real_ticks(void)
516 {
517 uint32_t low,high;
518 int64_t val;
519 asm volatile("rdtsc" : "=a" (low), "=d" (high));
520 val = high;
521 val <<= 32;
522 val |= low;
523 return val;
524 }
526 #elif defined(__ia64__)
527 #include "ia64_intrinsic.h"
528 #define cpu_get_real_ticks() \
529 __ia64_getreg(_IA64_REG_AR_ITC)
531 #else
532 #error unsupported CPU
533 #endif
535 static int64_t cpu_ticks_offset;
536 static int cpu_ticks_enabled;
537 int64_t cpu_virt_tsc;
539 static inline int64_t cpu_get_ticks(void)
540 {
541 if (!cpu_ticks_enabled) {
542 return cpu_ticks_offset;
543 } else {
544 return cpu_get_real_ticks() + cpu_ticks_offset;
545 }
547 }
549 /* enable cpu_get_ticks() */
550 void cpu_enable_ticks(void)
551 {
552 if (!cpu_ticks_enabled) {
553 cpu_ticks_offset -= cpu_get_real_ticks();
554 cpu_ticks_enabled = 1;
555 }
556 }
558 /* disable cpu_get_ticks() : the clock is stopped. You must not call
559 cpu_get_ticks() after that. */
560 void cpu_disable_ticks(void)
561 {
562 if (cpu_ticks_enabled) {
563 cpu_ticks_offset = cpu_get_ticks();
564 cpu_ticks_enabled = 0;
565 }
566 }
568 static int64_t get_clock(void)
569 {
570 #ifdef _WIN32
571 struct _timeb tb;
572 _ftime(&tb);
573 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
574 #else
575 struct timeval tv;
576 gettimeofday(&tv, NULL);
577 return tv.tv_sec * 1000000LL + tv.tv_usec;
578 #endif
579 }
581 void cpu_calibrate_ticks(void)
582 {
583 int64_t usec, ticks;
585 usec = get_clock();
586 ticks = cpu_get_real_ticks();
587 #ifdef _WIN32
588 Sleep(50);
589 #else
590 usleep(50 * 1000);
591 #endif
592 usec = get_clock() - usec;
593 ticks = cpu_get_real_ticks() - ticks;
594 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
595 }
597 /* compute with 96 bit intermediate result: (a*b)/c */
598 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
599 {
600 union {
601 uint64_t ll;
602 struct {
603 #ifdef WORDS_BIGENDIAN
604 uint32_t high, low;
605 #else
606 uint32_t low, high;
607 #endif
608 } l;
609 } u, res;
610 uint64_t rl, rh;
612 u.ll = a;
613 rl = (uint64_t)u.l.low * (uint64_t)b;
614 rh = (uint64_t)u.l.high * (uint64_t)b;
615 rh += (rl >> 32);
616 res.l.high = rh / c;
617 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
618 return res.ll;
619 }
621 #define QEMU_TIMER_REALTIME 0
622 #define QEMU_TIMER_VIRTUAL 1
624 struct QEMUClock {
625 int type;
626 /* XXX: add frequency */
627 };
629 struct QEMUTimer {
630 QEMUClock *clock;
631 int64_t expire_time;
632 QEMUTimerCB *cb;
633 void *opaque;
634 struct QEMUTimer *next;
635 };
637 QEMUClock *rt_clock;
638 QEMUClock *vm_clock;
640 static QEMUTimer *active_timers[2];
641 #ifdef _WIN32
642 static MMRESULT timerID;
643 #else
644 /* frequency of the times() clock tick */
645 static int timer_freq;
646 #endif
648 QEMUClock *qemu_new_clock(int type)
649 {
650 QEMUClock *clock;
651 clock = qemu_mallocz(sizeof(QEMUClock));
652 if (!clock)
653 return NULL;
654 clock->type = type;
655 return clock;
656 }
658 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
659 {
660 QEMUTimer *ts;
662 ts = qemu_mallocz(sizeof(QEMUTimer));
663 ts->clock = clock;
664 ts->cb = cb;
665 ts->opaque = opaque;
666 return ts;
667 }
669 void qemu_free_timer(QEMUTimer *ts)
670 {
671 qemu_free(ts);
672 }
674 /* stop a timer, but do not dealloc it */
675 void qemu_del_timer(QEMUTimer *ts)
676 {
677 QEMUTimer **pt, *t;
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 == ts) {
687 *pt = t->next;
688 break;
689 }
690 pt = &t->next;
691 }
692 }
694 /* modify the current timer so that it will be fired when current_time
695 >= expire_time. The corresponding callback will be called. */
696 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
697 {
698 QEMUTimer **pt, *t;
700 qemu_del_timer(ts);
702 /* add the timer in the sorted list */
703 /* NOTE: this code must be signal safe because
704 qemu_timer_expired() can be called from a signal. */
705 pt = &active_timers[ts->clock->type];
706 for(;;) {
707 t = *pt;
708 if (!t)
709 break;
710 if (t->expire_time > expire_time)
711 break;
712 pt = &t->next;
713 }
714 ts->expire_time = expire_time;
715 ts->next = *pt;
716 *pt = ts;
717 }
719 int qemu_timer_pending(QEMUTimer *ts)
720 {
721 QEMUTimer *t;
722 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
723 if (t == ts)
724 return 1;
725 }
726 return 0;
727 }
729 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
730 {
731 if (!timer_head)
732 return 0;
733 return (timer_head->expire_time <= current_time);
734 }
736 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
737 {
738 QEMUTimer *ts;
740 for(;;) {
741 ts = *ptimer_head;
742 if (!ts || ts->expire_time > current_time)
743 break;
744 /* remove timer from the list before calling the callback */
745 *ptimer_head = ts->next;
746 ts->next = NULL;
748 /* run the callback (the timer list can be modified) */
749 ts->cb(ts->opaque);
750 }
751 }
753 int64_t qemu_get_clock(QEMUClock *clock)
754 {
755 switch(clock->type) {
756 case QEMU_TIMER_REALTIME:
757 #ifdef _WIN32
758 return GetTickCount();
759 #else
760 {
761 struct tms tp;
763 /* Note that using gettimeofday() is not a good solution
764 for timers because its value change when the date is
765 modified. */
766 if (timer_freq == 100) {
767 return times(&tp) * 10;
768 } else {
769 return ((int64_t)times(&tp) * 1000) / timer_freq;
770 }
771 }
772 #endif
773 default:
774 case QEMU_TIMER_VIRTUAL:
775 return cpu_get_ticks();
776 }
777 }
779 /* save a timer */
780 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
781 {
782 uint64_t expire_time;
784 if (qemu_timer_pending(ts)) {
785 expire_time = ts->expire_time;
786 } else {
787 expire_time = -1;
788 }
789 qemu_put_be64(f, expire_time);
790 }
792 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
793 {
794 uint64_t expire_time;
796 expire_time = qemu_get_be64(f);
797 if (expire_time != -1) {
798 qemu_mod_timer(ts, expire_time);
799 } else {
800 qemu_del_timer(ts);
801 }
802 }
804 static void init_timers(void)
805 {
806 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
807 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
809 #ifdef _WIN32
810 {
811 int count=0;
812 timerID = timeSetEvent(10, // interval (ms)
813 0, // resolution
814 host_alarm_handler, // function
815 (DWORD)&count, // user parameter
816 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
817 if( !timerID ) {
818 perror("failed timer alarm");
819 exit(1);
820 }
821 }
822 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
823 #else
824 {
825 /* get times() syscall frequency */
826 timer_freq = sysconf(_SC_CLK_TCK);
828 #ifndef TARGET_VMX
829 /* timer signal */
830 sigfillset(&act.sa_mask);
831 act.sa_flags = 0;
832 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
833 act.sa_flags |= SA_ONSTACK;
834 #endif
835 act.sa_handler = host_alarm_handler;
836 sigaction(SIGALRM, &act, NULL);
838 itv.it_interval.tv_sec = 0;
839 itv.it_interval.tv_usec = 1000;
840 itv.it_value.tv_sec = 0;
841 itv.it_value.tv_usec = 10 * 1000;
842 setitimer(ITIMER_REAL, &itv, NULL);
843 /* we probe the tick duration of the kernel to inform the user if
844 the emulated kernel requested a too high timer frequency */
845 getitimer(ITIMER_REAL, &itv);
847 #if defined(__linux__)
848 if (itv.it_interval.tv_usec > 1000) {
849 /* try to use /dev/rtc to have a faster timer */
850 if (start_rtc_timer() < 0)
851 goto use_itimer;
852 /* disable itimer */
853 itv.it_interval.tv_sec = 0;
854 itv.it_interval.tv_usec = 0;
855 itv.it_value.tv_sec = 0;
856 itv.it_value.tv_usec = 0;
857 setitimer(ITIMER_REAL, &itv, NULL);
859 /* use the RTC */
860 sigaction(SIGIO, &act, NULL);
861 fcntl(rtc_fd, F_SETFL, O_ASYNC);
862 fcntl(rtc_fd, F_SETOWN, getpid());
863 } else
864 #endif /* defined(__linux__) */
865 {
866 use_itimer:
867 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
868 PIT_FREQ) / 1000000;
869 }
870 #endif /* TARGET_VMX */
871 }
872 #endif
873 }
875 void quit_timers(void)
876 {
877 #ifdef _WIN32
878 timeKillEvent(timerID);
879 #endif
880 }
882 /***********************************************************/
883 /* character device */
885 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
886 {
887 return s->chr_write(s, buf, len);
888 }
890 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
891 {
892 char buf[4096];
893 va_list ap;
894 va_start(ap, fmt);
895 vsnprintf(buf, sizeof(buf), fmt, ap);
896 qemu_chr_write(s, buf, strlen(buf));
897 va_end(ap);
898 }
900 void qemu_chr_send_event(CharDriverState *s, int event)
901 {
902 if (s->chr_send_event)
903 s->chr_send_event(s, event);
904 }
906 void qemu_chr_add_read_handler(CharDriverState *s,
907 IOCanRWHandler *fd_can_read,
908 IOReadHandler *fd_read, void *opaque)
909 {
910 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
911 }
913 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
914 {
915 s->chr_event = chr_event;
916 }
918 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
919 {
920 return len;
921 }
923 static void null_chr_add_read_handler(CharDriverState *chr,
924 IOCanRWHandler *fd_can_read,
925 IOReadHandler *fd_read, void *opaque)
926 {
927 }
929 CharDriverState *qemu_chr_open_null(void)
930 {
931 CharDriverState *chr;
933 chr = qemu_mallocz(sizeof(CharDriverState));
934 if (!chr)
935 return NULL;
936 chr->chr_write = null_chr_write;
937 chr->chr_add_read_handler = null_chr_add_read_handler;
938 return chr;
939 }
941 #ifndef _WIN32
943 typedef struct {
944 int fd_in, fd_out;
945 /* for nographic stdio only */
946 IOCanRWHandler *fd_can_read;
947 IOReadHandler *fd_read;
948 void *fd_opaque;
949 } FDCharDriver;
951 #define STDIO_MAX_CLIENTS 2
953 static int stdio_nb_clients;
954 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
956 static int unix_write(int fd, const uint8_t *buf, int len1)
957 {
958 int ret, len;
960 len = len1;
961 while (len > 0) {
962 ret = write(fd, buf, len);
963 if (ret < 0) {
964 if (errno != EINTR && errno != EAGAIN)
965 return -1;
966 } else if (ret == 0) {
967 break;
968 } else {
969 buf += ret;
970 len -= ret;
971 }
972 }
973 return len1 - len;
974 }
976 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
977 {
978 FDCharDriver *s = chr->opaque;
979 return unix_write(s->fd_out, buf, len);
980 }
982 static void fd_chr_add_read_handler(CharDriverState *chr,
983 IOCanRWHandler *fd_can_read,
984 IOReadHandler *fd_read, void *opaque)
985 {
986 FDCharDriver *s = chr->opaque;
988 if (nographic && s->fd_in == 0) {
989 s->fd_can_read = fd_can_read;
990 s->fd_read = fd_read;
991 s->fd_opaque = opaque;
992 } else {
993 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
994 }
995 }
997 /* open a character device to a unix fd */
998 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
999 {
1000 CharDriverState *chr;
1001 FDCharDriver *s;
1003 chr = qemu_mallocz(sizeof(CharDriverState));
1004 if (!chr)
1005 return NULL;
1006 s = qemu_mallocz(sizeof(FDCharDriver));
1007 if (!s) {
1008 free(chr);
1009 return NULL;
1011 s->fd_in = fd_in;
1012 s->fd_out = fd_out;
1013 chr->opaque = s;
1014 chr->chr_write = fd_chr_write;
1015 chr->chr_add_read_handler = fd_chr_add_read_handler;
1016 return chr;
1019 /* for STDIO, we handle the case where several clients use it
1020 (nographic mode) */
1022 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1024 static int term_got_escape, client_index;
1026 void term_print_help(void)
1028 printf("\n"
1029 "C-a h print this help\n"
1030 "C-a x exit emulator\n"
1031 "C-a s save disk data back to file (if -snapshot)\n"
1032 "C-a b send break (magic sysrq)\n"
1033 "C-a c switch between console and monitor\n"
1034 "C-a C-a send C-a\n"
1035 );
1038 /* called when a char is received */
1039 static void stdio_received_byte(int ch)
1041 if (term_got_escape) {
1042 term_got_escape = 0;
1043 switch(ch) {
1044 case 'h':
1045 term_print_help();
1046 break;
1047 case 'x':
1048 exit(0);
1049 break;
1050 case 's':
1052 int i;
1053 for (i = 0; i < MAX_DISKS; i++) {
1054 if (bs_table[i])
1055 bdrv_commit(bs_table[i]);
1058 break;
1059 case 'b':
1060 if (client_index < stdio_nb_clients) {
1061 CharDriverState *chr;
1062 FDCharDriver *s;
1064 chr = stdio_clients[client_index];
1065 s = chr->opaque;
1066 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1068 break;
1069 case 'c':
1070 client_index++;
1071 if (client_index >= stdio_nb_clients)
1072 client_index = 0;
1073 if (client_index == 0) {
1074 /* send a new line in the monitor to get the prompt */
1075 ch = '\r';
1076 goto send_char;
1078 break;
1079 case TERM_ESCAPE:
1080 goto send_char;
1082 } else if (ch == TERM_ESCAPE) {
1083 term_got_escape = 1;
1084 } else {
1085 send_char:
1086 if (client_index < stdio_nb_clients) {
1087 uint8_t buf[1];
1088 CharDriverState *chr;
1089 FDCharDriver *s;
1091 chr = stdio_clients[client_index];
1092 s = chr->opaque;
1093 buf[0] = ch;
1094 /* XXX: should queue the char if the device is not
1095 ready */
1096 if (s->fd_can_read(s->fd_opaque) > 0)
1097 s->fd_read(s->fd_opaque, buf, 1);
1102 static int stdio_can_read(void *opaque)
1104 /* XXX: not strictly correct */
1105 return 1;
1108 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1110 int i;
1111 for(i = 0; i < size; i++)
1112 stdio_received_byte(buf[i]);
1115 /* init terminal so that we can grab keys */
1116 static struct termios oldtty;
1117 static int old_fd0_flags;
1119 static void term_exit(void)
1121 tcsetattr (0, TCSANOW, &oldtty);
1122 fcntl(0, F_SETFL, old_fd0_flags);
1125 static void term_init(void)
1127 struct termios tty;
1129 tcgetattr (0, &tty);
1130 oldtty = tty;
1131 old_fd0_flags = fcntl(0, F_GETFL);
1133 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1134 |INLCR|IGNCR|ICRNL|IXON);
1135 tty.c_oflag |= OPOST;
1136 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1137 /* if graphical mode, we allow Ctrl-C handling */
1138 if (nographic)
1139 tty.c_lflag &= ~ISIG;
1140 tty.c_cflag &= ~(CSIZE|PARENB);
1141 tty.c_cflag |= CS8;
1142 tty.c_cc[VMIN] = 1;
1143 tty.c_cc[VTIME] = 0;
1145 tcsetattr (0, TCSANOW, &tty);
1147 atexit(term_exit);
1149 fcntl(0, F_SETFL, O_NONBLOCK);
1152 CharDriverState *qemu_chr_open_stdio(void)
1154 CharDriverState *chr;
1156 if (nographic) {
1157 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1158 return NULL;
1159 chr = qemu_chr_open_fd(0, 1);
1160 if (stdio_nb_clients == 0)
1161 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1162 client_index = stdio_nb_clients;
1163 } else {
1164 if (stdio_nb_clients != 0)
1165 return NULL;
1166 chr = qemu_chr_open_fd(0, 1);
1168 stdio_clients[stdio_nb_clients++] = chr;
1169 if (stdio_nb_clients == 1) {
1170 /* set the terminal in raw mode */
1171 term_init();
1173 return chr;
1176 int store_console_dev(int domid, char *pts)
1178 int xc_handle;
1179 unsigned int len = 0;
1180 struct xs_handle *xs;
1181 char *path;
1183 xs = xs_daemon_open();
1184 if (xs == NULL) {
1185 fprintf(logfile, "Could not contact XenStore\n");
1186 return -1;
1189 xc_handle = xc_interface_open();
1190 if (xc_handle == -1) {
1191 fprintf(logfile, "xc_interface_open() error\n");
1192 return -1;
1195 path = xs_get_domain_path(xs, domid);
1196 if (path == NULL) {
1197 fprintf(logfile, "xs_get_domain_path() error\n");
1198 return -1;
1200 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1201 if (path == NULL) {
1202 fprintf(logfile, "realloc error\n");
1203 return -1;
1205 strcat(path, "/console/tty");
1206 if (!xs_write(xs, NULL, path, pts, strlen(pts))) {
1207 fprintf(logfile, "xs_write for console fail");
1208 return -1;
1211 free(path);
1212 xs_daemon_close(xs);
1213 close(xc_handle);
1215 return 0;
1218 #if defined(__linux__)
1219 CharDriverState *qemu_chr_open_pty(void)
1221 char slave_name[1024];
1222 int master_fd, slave_fd;
1224 /* Not satisfying */
1225 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1226 return NULL;
1228 fprintf(stderr, "char device redirected to %s\n", slave_name);
1229 store_console_dev(domid, slave_name);
1230 return qemu_chr_open_fd(master_fd, master_fd);
1232 #else
1233 CharDriverState *qemu_chr_open_pty(void)
1235 return NULL;
1237 #endif
1239 #endif /* !defined(_WIN32) */
1241 CharDriverState *qemu_chr_open(const char *filename)
1243 if (!strcmp(filename, "vc")) {
1244 return text_console_init(&display_state);
1245 } else if (!strcmp(filename, "null")) {
1246 return qemu_chr_open_null();
1247 } else
1248 #ifndef _WIN32
1249 if (!strcmp(filename, "pty")) {
1250 return qemu_chr_open_pty();
1251 } else if (!strcmp(filename, "stdio")) {
1252 return qemu_chr_open_stdio();
1253 } else
1254 #endif
1256 return NULL;
1260 /***********************************************************/
1261 /* Linux network device redirectors */
1263 void hex_dump(FILE *f, const uint8_t *buf, int size)
1265 int len, i, j, c;
1267 for(i=0;i<size;i+=16) {
1268 len = size - i;
1269 if (len > 16)
1270 len = 16;
1271 fprintf(f, "%08x ", i);
1272 for(j=0;j<16;j++) {
1273 if (j < len)
1274 fprintf(f, " %02x", buf[i+j]);
1275 else
1276 fprintf(f, " ");
1278 fprintf(f, " ");
1279 for(j=0;j<len;j++) {
1280 c = buf[i+j];
1281 if (c < ' ' || c > '~')
1282 c = '.';
1283 fprintf(f, "%c", c);
1285 fprintf(f, "\n");
1289 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1291 nd->send_packet(nd, buf, size);
1294 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1295 IOReadHandler *fd_read, void *opaque)
1297 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1300 /* dummy network adapter */
1302 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1306 static void dummy_add_read_packet(NetDriverState *nd,
1307 IOCanRWHandler *fd_can_read,
1308 IOReadHandler *fd_read, void *opaque)
1312 static int net_dummy_init(NetDriverState *nd)
1314 nd->send_packet = dummy_send_packet;
1315 nd->add_read_packet = dummy_add_read_packet;
1316 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1317 return 0;
1320 #if defined(CONFIG_SLIRP)
1322 /* slirp network adapter */
1324 static void *slirp_fd_opaque;
1325 static IOCanRWHandler *slirp_fd_can_read;
1326 static IOReadHandler *slirp_fd_read;
1327 static int slirp_inited;
1329 int slirp_can_output(void)
1331 return slirp_fd_can_read(slirp_fd_opaque);
1334 void slirp_output(const uint8_t *pkt, int pkt_len)
1336 #if 0
1337 printf("output:\n");
1338 hex_dump(stdout, pkt, pkt_len);
1339 #endif
1340 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1343 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1345 #if 0
1346 printf("input:\n");
1347 hex_dump(stdout, buf, size);
1348 #endif
1349 slirp_input(buf, size);
1352 static void slirp_add_read_packet(NetDriverState *nd,
1353 IOCanRWHandler *fd_can_read,
1354 IOReadHandler *fd_read, void *opaque)
1356 slirp_fd_opaque = opaque;
1357 slirp_fd_can_read = fd_can_read;
1358 slirp_fd_read = fd_read;
1361 static int net_slirp_init(NetDriverState *nd)
1363 if (!slirp_inited) {
1364 slirp_inited = 1;
1365 slirp_init();
1367 nd->send_packet = slirp_send_packet;
1368 nd->add_read_packet = slirp_add_read_packet;
1369 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1370 return 0;
1373 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1375 const char *p, *p1;
1376 int len;
1377 p = *pp;
1378 p1 = strchr(p, sep);
1379 if (!p1)
1380 return -1;
1381 len = p1 - p;
1382 p1++;
1383 if (buf_size > 0) {
1384 if (len > buf_size - 1)
1385 len = buf_size - 1;
1386 memcpy(buf, p, len);
1387 buf[len] = '\0';
1389 *pp = p1;
1390 return 0;
1393 static void net_slirp_redir(const char *redir_str)
1395 int is_udp;
1396 char buf[256], *r;
1397 const char *p;
1398 struct in_addr guest_addr;
1399 int host_port, guest_port;
1401 if (!slirp_inited) {
1402 slirp_inited = 1;
1403 slirp_init();
1406 p = redir_str;
1407 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1408 goto fail;
1409 if (!strcmp(buf, "tcp")) {
1410 is_udp = 0;
1411 } else if (!strcmp(buf, "udp")) {
1412 is_udp = 1;
1413 } else {
1414 goto fail;
1417 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1418 goto fail;
1419 host_port = strtol(buf, &r, 0);
1420 if (r == buf)
1421 goto fail;
1423 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1424 goto fail;
1425 if (buf[0] == '\0') {
1426 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1428 if (!inet_aton(buf, &guest_addr))
1429 goto fail;
1431 guest_port = strtol(p, &r, 0);
1432 if (r == p)
1433 goto fail;
1435 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1436 fprintf(stderr, "qemu: could not set up redirection\n");
1437 exit(1);
1439 return;
1440 fail:
1441 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1442 exit(1);
1445 #ifndef _WIN32
1447 char smb_dir[1024];
1449 static void smb_exit(void)
1451 DIR *d;
1452 struct dirent *de;
1453 char filename[1024];
1455 /* erase all the files in the directory */
1456 d = opendir(smb_dir);
1457 for(;;) {
1458 de = readdir(d);
1459 if (!de)
1460 break;
1461 if (strcmp(de->d_name, ".") != 0 &&
1462 strcmp(de->d_name, "..") != 0) {
1463 snprintf(filename, sizeof(filename), "%s/%s",
1464 smb_dir, de->d_name);
1465 unlink(filename);
1468 closedir(d);
1469 rmdir(smb_dir);
1472 /* automatic user mode samba server configuration */
1473 void net_slirp_smb(const char *exported_dir)
1475 char smb_conf[1024];
1476 char smb_cmdline[1024];
1477 FILE *f;
1479 if (!slirp_inited) {
1480 slirp_inited = 1;
1481 slirp_init();
1484 /* XXX: better tmp dir construction */
1485 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1486 if (mkdir(smb_dir, 0700) < 0) {
1487 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1488 exit(1);
1490 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1492 f = fopen(smb_conf, "w");
1493 if (!f) {
1494 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1495 exit(1);
1497 fprintf(f,
1498 "[global]\n"
1499 "pid directory=%s\n"
1500 "lock directory=%s\n"
1501 "log file=%s/log.smbd\n"
1502 "smb passwd file=%s/smbpasswd\n"
1503 "security = share\n"
1504 "[qemu]\n"
1505 "path=%s\n"
1506 "read only=no\n"
1507 "guest ok=yes\n",
1508 smb_dir,
1509 smb_dir,
1510 smb_dir,
1511 smb_dir,
1512 exported_dir
1513 );
1514 fclose(f);
1515 atexit(smb_exit);
1517 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1518 smb_conf);
1520 slirp_add_exec(0, smb_cmdline, 4, 139);
1523 #endif /* !defined(_WIN32) */
1525 #endif /* CONFIG_SLIRP */
1527 #if !defined(_WIN32)
1528 #ifdef _BSD
1529 static int tun_open(char *ifname, int ifname_size)
1531 int fd;
1532 char *dev;
1533 struct stat s;
1535 fd = open("/dev/tap", O_RDWR);
1536 if (fd < 0) {
1537 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1538 return -1;
1541 fstat(fd, &s);
1542 dev = devname(s.st_rdev, S_IFCHR);
1543 pstrcpy(ifname, ifname_size, dev);
1545 fcntl(fd, F_SETFL, O_NONBLOCK);
1546 return fd;
1548 #else
1549 static int tun_open(char *ifname, int ifname_size)
1551 struct ifreq ifr;
1552 int fd, ret;
1554 fd = open("/dev/net/tun", O_RDWR);
1555 if (fd < 0) {
1556 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1557 return -1;
1559 memset(&ifr, 0, sizeof(ifr));
1560 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1561 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1562 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1563 if (ret != 0) {
1564 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1565 close(fd);
1566 return -1;
1568 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1569 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1570 fcntl(fd, F_SETFL, O_NONBLOCK);
1571 return fd;
1573 #endif
1575 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1577 write(nd->fd, buf, size);
1580 static void tun_add_read_packet(NetDriverState *nd,
1581 IOCanRWHandler *fd_can_read,
1582 IOReadHandler *fd_read, void *opaque)
1584 qemu_add_fd_event_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1587 static int net_tun_init(NetDriverState *nd)
1589 int pid, status;
1590 char *args[4];
1591 char **parg;
1592 extern int highest_fds;
1594 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1595 if (nd->fd < 0)
1596 return -1;
1598 if ( nd->fd > highest_fds ) highest_fds = nd->fd;
1599 /* try to launch network init script */
1600 pid = fork();
1601 if (pid >= 0) {
1602 if (pid == 0) {
1603 parg = args;
1604 *parg++ = network_script;
1605 *parg++ = nd->ifname;
1606 *parg++ = bridge;
1607 *parg++ = NULL;
1608 execv(network_script, args);
1609 exit(1);
1611 while (waitpid(pid, &status, 0) != pid);
1612 if (!WIFEXITED(status) ||
1613 WEXITSTATUS(status) != 0) {
1614 fprintf(stderr, "%s: could not launch network script\n",
1615 network_script);
1618 nd->send_packet = tun_send_packet;
1619 nd->add_read_packet = tun_add_read_packet;
1620 return 0;
1623 static int net_fd_init(NetDriverState *nd, int fd)
1625 nd->fd = fd;
1626 nd->send_packet = tun_send_packet;
1627 nd->add_read_packet = tun_add_read_packet;
1628 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1629 return 0;
1632 #endif /* !_WIN32 */
1634 /***********************************************************/
1635 /* dumb display */
1637 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1641 static void dumb_resize(DisplayState *ds, int w, int h)
1645 static void dumb_refresh(DisplayState *ds)
1647 vga_update_display();
1650 void dumb_display_init(DisplayState *ds)
1652 ds->data = NULL;
1653 ds->linesize = 0;
1654 ds->depth = 0;
1655 ds->dpy_update = dumb_update;
1656 ds->dpy_resize = dumb_resize;
1657 ds->dpy_refresh = dumb_refresh;
1660 #if !defined(CONFIG_SOFTMMU)
1661 /***********************************************************/
1662 /* cpu signal handler */
1663 static void host_segv_handler(int host_signum, siginfo_t *info,
1664 void *puc)
1666 abort();
1668 #endif
1670 /***********************************************************/
1671 /* I/O handling */
1673 #define MAX_IO_HANDLERS 64
1675 typedef struct IOHandlerRecord {
1676 int fd;
1677 IOCanRWHandler *fd_can_read;
1678 IOReadHandler *fd_read;
1679 void *opaque;
1680 /* temporary data */
1681 struct pollfd *ufd;
1682 int max_size;
1683 struct IOHandlerRecord *next;
1684 } IOHandlerRecord;
1686 static IOHandlerRecord *first_io_handler;
1687 static IOHandlerRecord *first_eventio_handler;
1689 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1690 IOReadHandler *fd_read, void *opaque)
1692 IOHandlerRecord *ioh;
1694 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1695 if (!ioh)
1696 return -1;
1697 ioh->fd = fd;
1698 ioh->fd_can_read = fd_can_read;
1699 ioh->fd_read = fd_read;
1700 ioh->opaque = opaque;
1701 ioh->next = first_io_handler;
1702 first_io_handler = ioh;
1703 return 0;
1706 int qemu_add_fd_event_read_handler(int fd, IOCanRWHandler *fd_can_read,
1707 IOReadHandler *fd_read, void *opaque)
1709 IOHandlerRecord *ioh;
1711 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1712 if (!ioh)
1713 return -1;
1714 ioh->fd = fd;
1715 ioh->fd_can_read = fd_can_read;
1716 ioh->fd_read = fd_read;
1717 ioh->opaque = opaque;
1718 ioh->next = first_eventio_handler;
1719 first_eventio_handler = ioh;
1720 return 0;
1723 void qemu_del_fd_read_handler(int fd)
1725 IOHandlerRecord **pioh, *ioh;
1727 pioh = &first_io_handler;
1728 for(;;) {
1729 ioh = *pioh;
1730 if (ioh == NULL)
1731 break;
1732 if (ioh->fd == fd) {
1733 *pioh = ioh->next;
1734 break;
1736 pioh = &ioh->next;
1740 /***********************************************************/
1741 /* savevm/loadvm support */
1743 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1745 fwrite(buf, 1, size, f);
1748 void qemu_put_byte(QEMUFile *f, int v)
1750 fputc(v, f);
1753 void qemu_put_be16(QEMUFile *f, unsigned int v)
1755 qemu_put_byte(f, v >> 8);
1756 qemu_put_byte(f, v);
1759 void qemu_put_be32(QEMUFile *f, unsigned int v)
1761 qemu_put_byte(f, v >> 24);
1762 qemu_put_byte(f, v >> 16);
1763 qemu_put_byte(f, v >> 8);
1764 qemu_put_byte(f, v);
1767 void qemu_put_be64(QEMUFile *f, uint64_t v)
1769 qemu_put_be32(f, v >> 32);
1770 qemu_put_be32(f, v);
1773 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1775 return fread(buf, 1, size, f);
1778 int qemu_get_byte(QEMUFile *f)
1780 int v;
1781 v = fgetc(f);
1782 if (v == EOF)
1783 return 0;
1784 else
1785 return v;
1788 unsigned int qemu_get_be16(QEMUFile *f)
1790 unsigned int v;
1791 v = qemu_get_byte(f) << 8;
1792 v |= qemu_get_byte(f);
1793 return v;
1796 unsigned int qemu_get_be32(QEMUFile *f)
1798 unsigned int v;
1799 v = qemu_get_byte(f) << 24;
1800 v |= qemu_get_byte(f) << 16;
1801 v |= qemu_get_byte(f) << 8;
1802 v |= qemu_get_byte(f);
1803 return v;
1806 uint64_t qemu_get_be64(QEMUFile *f)
1808 uint64_t v;
1809 v = (uint64_t)qemu_get_be32(f) << 32;
1810 v |= qemu_get_be32(f);
1811 return v;
1814 int64_t qemu_ftell(QEMUFile *f)
1816 return ftell(f);
1819 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1821 if (fseek(f, pos, whence) < 0)
1822 return -1;
1823 return ftell(f);
1826 typedef struct SaveStateEntry {
1827 char idstr[256];
1828 int instance_id;
1829 int version_id;
1830 SaveStateHandler *save_state;
1831 LoadStateHandler *load_state;
1832 void *opaque;
1833 struct SaveStateEntry *next;
1834 } SaveStateEntry;
1836 static SaveStateEntry *first_se;
1838 int register_savevm(const char *idstr,
1839 int instance_id,
1840 int version_id,
1841 SaveStateHandler *save_state,
1842 LoadStateHandler *load_state,
1843 void *opaque)
1845 SaveStateEntry *se, **pse;
1847 se = qemu_malloc(sizeof(SaveStateEntry));
1848 if (!se)
1849 return -1;
1850 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1851 se->instance_id = instance_id;
1852 se->version_id = version_id;
1853 se->save_state = save_state;
1854 se->load_state = load_state;
1855 se->opaque = opaque;
1856 se->next = NULL;
1858 /* add at the end of list */
1859 pse = &first_se;
1860 while (*pse != NULL)
1861 pse = &(*pse)->next;
1862 *pse = se;
1863 return 0;
1866 #define QEMU_VM_FILE_MAGIC 0x5145564d
1867 #define QEMU_VM_FILE_VERSION 0x00000001
1869 int qemu_savevm(const char *filename)
1871 SaveStateEntry *se;
1872 QEMUFile *f;
1873 int len, len_pos, cur_pos, saved_vm_running, ret;
1875 saved_vm_running = vm_running;
1876 vm_stop(0);
1878 f = fopen(filename, "wb");
1879 if (!f) {
1880 ret = -1;
1881 goto the_end;
1884 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1885 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1887 for(se = first_se; se != NULL; se = se->next) {
1888 /* ID string */
1889 len = strlen(se->idstr);
1890 qemu_put_byte(f, len);
1891 qemu_put_buffer(f, se->idstr, len);
1893 qemu_put_be32(f, se->instance_id);
1894 qemu_put_be32(f, se->version_id);
1896 /* record size: filled later */
1897 len_pos = ftell(f);
1898 qemu_put_be32(f, 0);
1900 se->save_state(f, se->opaque);
1902 /* fill record size */
1903 cur_pos = ftell(f);
1904 len = ftell(f) - len_pos - 4;
1905 fseek(f, len_pos, SEEK_SET);
1906 qemu_put_be32(f, len);
1907 fseek(f, cur_pos, SEEK_SET);
1910 fclose(f);
1911 ret = 0;
1912 the_end:
1913 if (saved_vm_running)
1914 vm_start();
1915 return ret;
1918 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1920 SaveStateEntry *se;
1922 for(se = first_se; se != NULL; se = se->next) {
1923 if (!strcmp(se->idstr, idstr) &&
1924 instance_id == se->instance_id)
1925 return se;
1927 return NULL;
1930 int qemu_loadvm(const char *filename)
1932 SaveStateEntry *se;
1933 QEMUFile *f;
1934 int len, cur_pos, ret, instance_id, record_len, version_id;
1935 int saved_vm_running;
1936 unsigned int v;
1937 char idstr[256];
1939 saved_vm_running = vm_running;
1940 vm_stop(0);
1942 f = fopen(filename, "rb");
1943 if (!f) {
1944 ret = -1;
1945 goto the_end;
1948 v = qemu_get_be32(f);
1949 if (v != QEMU_VM_FILE_MAGIC)
1950 goto fail;
1951 v = qemu_get_be32(f);
1952 if (v != QEMU_VM_FILE_VERSION) {
1953 fail:
1954 fclose(f);
1955 ret = -1;
1956 goto the_end;
1958 for(;;) {
1959 #if defined (DO_TB_FLUSH)
1960 tb_flush(global_env);
1961 #endif
1962 len = qemu_get_byte(f);
1963 if (feof(f))
1964 break;
1965 qemu_get_buffer(f, idstr, len);
1966 idstr[len] = '\0';
1967 instance_id = qemu_get_be32(f);
1968 version_id = qemu_get_be32(f);
1969 record_len = qemu_get_be32(f);
1970 #if 0
1971 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1972 idstr, instance_id, version_id, record_len);
1973 #endif
1974 cur_pos = ftell(f);
1975 se = find_se(idstr, instance_id);
1976 if (!se) {
1977 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1978 instance_id, idstr);
1979 } else {
1980 ret = se->load_state(f, se->opaque, version_id);
1981 if (ret < 0) {
1982 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1983 instance_id, idstr);
1986 /* always seek to exact end of record */
1987 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1989 fclose(f);
1990 ret = 0;
1991 the_end:
1992 if (saved_vm_running)
1993 vm_start();
1994 return ret;
1997 /***********************************************************/
1998 /* main execution loop */
2000 void gui_update(void *opaque)
2002 display_state.dpy_refresh(&display_state);
2003 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2005 void polling_handler(void *opaque)
2007 #ifndef _WIN32
2008 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2009 IOHandlerRecord *ioh, *ioh_next;
2010 uint8_t buf[4096];
2011 int n, max_size;
2012 #endif
2013 int timeout = 0;
2014 int ret;
2016 #ifdef _WIN32
2017 if (timeout > 0)
2018 Sleep(timeout);
2019 #else
2020 /* poll any events */
2021 /* XXX: separate device handlers from system ones */
2022 pf = ufds;
2023 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2024 if (!ioh->fd_can_read) {
2025 max_size = 0;
2026 pf->fd = ioh->fd;
2027 pf->events = POLLIN;
2028 ioh->ufd = pf;
2029 pf++;
2030 } else {
2031 max_size = ioh->fd_can_read(ioh->opaque);
2032 if (max_size > 0) {
2033 if (max_size > sizeof(buf))
2034 max_size = sizeof(buf);
2035 pf->fd = ioh->fd;
2036 pf->events = POLLIN;
2037 ioh->ufd = pf;
2038 pf++;
2039 } else {
2040 ioh->ufd = NULL;
2043 ioh->max_size = max_size;
2046 ret = poll(ufds, pf - ufds, timeout);
2047 if (ret > 0) {
2048 /* XXX: better handling of removal */
2049 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2050 ioh_next = ioh->next;
2051 pf = ioh->ufd;
2052 if (pf) {
2053 if (pf->revents & POLLIN) {
2054 if (ioh->max_size == 0) {
2055 /* just a read event */
2056 ioh->fd_read(ioh->opaque, NULL, 0);
2057 } else {
2058 n = read(ioh->fd, buf, ioh->max_size);
2059 if (n >= 0) {
2060 ioh->fd_read(ioh->opaque, buf, n);
2061 } else if (errno != EAGAIN) {
2062 ioh->fd_read(ioh->opaque, NULL, -errno);
2069 #endif /* !defined(_WIN32) */
2071 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
2075 /* XXX: support several handlers */
2076 VMStopHandler *vm_stop_cb;
2077 VMStopHandler *vm_stop_opaque;
2079 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2081 vm_stop_cb = cb;
2082 vm_stop_opaque = opaque;
2083 return 0;
2086 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2088 vm_stop_cb = NULL;
2091 void vm_start(void)
2093 if (!vm_running) {
2094 cpu_enable_ticks();
2095 vm_running = 1;
2099 void vm_stop(int reason)
2101 if (vm_running) {
2102 cpu_disable_ticks();
2103 vm_running = 0;
2104 if (reason != 0) {
2105 if (vm_stop_cb) {
2106 vm_stop_cb(vm_stop_opaque, reason);
2112 /* reset/shutdown handler */
2114 typedef struct QEMUResetEntry {
2115 QEMUResetHandler *func;
2116 void *opaque;
2117 struct QEMUResetEntry *next;
2118 } QEMUResetEntry;
2120 static QEMUResetEntry *first_reset_entry;
2121 int reset_requested;
2122 int shutdown_requested;
2124 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2126 QEMUResetEntry **pre, *re;
2128 pre = &first_reset_entry;
2129 while (*pre != NULL)
2130 pre = &(*pre)->next;
2131 re = qemu_mallocz(sizeof(QEMUResetEntry));
2132 re->func = func;
2133 re->opaque = opaque;
2134 re->next = NULL;
2135 *pre = re;
2138 void qemu_system_reset(void)
2140 QEMUResetEntry *re;
2142 /* reset all devices */
2143 for(re = first_reset_entry; re != NULL; re = re->next) {
2144 re->func(re->opaque);
2148 void qemu_system_reset_request(void)
2150 reset_requested = 1;
2151 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2154 void qemu_system_shutdown_request(void)
2156 shutdown_requested = 1;
2157 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2160 void main_loop_wait(int timeout)
2162 if (vm_running) {
2163 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2164 qemu_get_clock(vm_clock));
2165 /* run dma transfers, if any */
2166 DMA_run();
2169 /* real time timers */
2170 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2171 qemu_get_clock(rt_clock));
2174 void help(void)
2176 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2177 "usage: %s [options] [disk_image]\n"
2178 "\n"
2179 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2180 "\n"
2181 "Standard options:\n"
2182 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2183 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2184 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2185 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2186 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2187 "-snapshot write to temporary files instead of disk image files\n"
2188 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2189 "-nographic disable graphical output and redirect serial I/Os to console\n"
2190 "-vcpus set CPU number of guest platform\n"
2191 #ifdef CONFIG_VNC
2192 "-vnc port use vnc instead of sdl\n"
2193 "-vncport port use a different port\n"
2194 "-vncconnect host:port do a reverse connect\n"
2195 #ifdef CONFIG_SDL
2196 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2197 #endif
2198 #endif
2199 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2200 "-enable-audio enable audio support\n"
2201 "-localtime set the real time clock to local time [default=utc]\n"
2202 "-full-screen start in full screen\n"
2203 #ifdef TARGET_PPC
2204 "-prep Simulate a PREP system (default is PowerMAC)\n"
2205 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2206 #endif
2207 "-nic-ne2000 simulate an Realtek ne2k PCI ethernet adaptor\n"
2208 "\n"
2209 "Network options:\n"
2210 "-nics n simulate 'n' network cards [default=1]\n"
2211 "-macaddr addr set the mac address of the first interface\n"
2212 "-bridge br set the bridge interface for nic\n"
2213 "-n script set tap/tun network init script [default=%s]\n"
2214 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2215 #ifdef CONFIG_SLIRP
2216 "-user-net use user mode network stack [default if no tap/tun script]\n"
2217 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2218 #ifndef _WIN32
2219 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2220 #endif
2221 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2222 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2223 #endif
2224 "-dummy-net use dummy network stack\n"
2225 "\n"
2226 "Linux boot specific:\n"
2227 "-kernel bzImage use 'bzImage' as kernel image\n"
2228 "-append cmdline use 'cmdline' as kernel command line\n"
2229 "-initrd file use 'file' as initial ram disk\n"
2230 "\n"
2231 "Debug/Expert options:\n"
2232 "-monitor dev redirect the monitor to char device 'dev'\n"
2233 "-serial dev redirect the serial port to char device 'dev'\n"
2234 "-S freeze CPU at startup (use 'c' to start execution)\n"
2235 "-s wait gdb connection to port %d\n"
2236 "-p port ioreq port for xen\n"
2237 "-d domain domain that we're serving\n"
2238 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2239 "-L path set the directory for the BIOS and VGA BIOS\n"
2240 #ifdef USE_CODE_COPY
2241 "-no-code-copy disable code copy acceleration\n"
2242 #endif
2243 #ifdef TARGET_I386
2244 "-isa simulate an ISA-only system (default is PCI system)\n"
2245 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2246 " (default is CL-GD5446 PCI VGA)\n"
2247 "-vgaacc [0|1] 1 to accelerate CL-GD5446 speed, default is 1\n"
2248 #endif
2249 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2250 "\n"
2251 "During emulation, the following keys are useful:\n"
2252 "ctrl-alt-f toggle full screen\n"
2253 "ctrl-alt-n switch to virtual console 'n'\n"
2254 "ctrl-alt toggle mouse and keyboard grab\n"
2255 "\n"
2256 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2258 #ifdef CONFIG_SOFTMMU
2259 "qemu",
2260 #else
2261 "qemu-fast",
2262 #endif
2263 DEFAULT_RAM_SIZE,
2264 DEFAULT_NETWORK_SCRIPT,
2265 DEFAULT_GDBSTUB_PORT);
2266 #ifndef CONFIG_SOFTMMU
2267 printf("\n"
2268 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2269 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2270 "PC emulation.\n");
2271 #endif
2272 exit(1);
2275 #define HAS_ARG 0x0001
2277 enum {
2278 QEMU_OPTION_h,
2280 QEMU_OPTION_fda,
2281 QEMU_OPTION_fdb,
2282 QEMU_OPTION_hda,
2283 QEMU_OPTION_hdb,
2284 QEMU_OPTION_hdc,
2285 QEMU_OPTION_hdd,
2286 QEMU_OPTION_cdrom,
2287 QEMU_OPTION_boot,
2288 QEMU_OPTION_snapshot,
2289 QEMU_OPTION_m,
2290 QEMU_OPTION_nographic,
2291 #ifdef CONFIG_VNC
2292 QEMU_OPTION_vnc,
2293 QEMU_OPTION_vncport,
2294 QEMU_OPTION_vncconnect,
2295 #ifdef CONFIG_SDL
2296 QEMU_OPTION_vnc_and_sdl,
2297 #endif
2298 #endif
2299 QEMU_OPTION_enable_audio,
2301 QEMU_OPTION_nics,
2302 QEMU_OPTION_macaddr,
2303 QEMU_OPTION_bridge,
2304 QEMU_OPTION_n,
2305 QEMU_OPTION_tun_fd,
2306 QEMU_OPTION_user_net,
2307 QEMU_OPTION_tftp,
2308 QEMU_OPTION_smb,
2309 QEMU_OPTION_redir,
2310 QEMU_OPTION_dummy_net,
2312 QEMU_OPTION_kernel,
2313 QEMU_OPTION_append,
2314 QEMU_OPTION_initrd,
2316 QEMU_OPTION_S,
2317 QEMU_OPTION_s,
2318 QEMU_OPTION_p,
2319 QEMU_OPTION_d,
2320 QEMU_OPTION_l,
2321 QEMU_OPTION_hdachs,
2322 QEMU_OPTION_L,
2323 QEMU_OPTION_no_code_copy,
2324 QEMU_OPTION_vcpus,
2325 QEMU_OPTION_pci,
2326 QEMU_OPTION_nic_ne2000,
2327 QEMU_OPTION_isa,
2328 QEMU_OPTION_prep,
2329 QEMU_OPTION_k,
2330 QEMU_OPTION_localtime,
2331 QEMU_OPTION_cirrusvga,
2332 QEMU_OPTION_g,
2333 QEMU_OPTION_std_vga,
2334 QEMU_OPTION_monitor,
2335 QEMU_OPTION_serial,
2336 QEMU_OPTION_loadvm,
2337 QEMU_OPTION_full_screen,
2338 QEMU_OPTION_vgaacc,
2339 };
2341 typedef struct QEMUOption {
2342 const char *name;
2343 int flags;
2344 int index;
2345 } QEMUOption;
2347 const QEMUOption qemu_options[] = {
2348 { "h", 0, QEMU_OPTION_h },
2350 { "fda", HAS_ARG, QEMU_OPTION_fda },
2351 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2352 { "hda", HAS_ARG, QEMU_OPTION_hda },
2353 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2354 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2355 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2356 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2357 { "boot", HAS_ARG, QEMU_OPTION_boot },
2358 { "snapshot", 0, QEMU_OPTION_snapshot },
2359 { "m", HAS_ARG, QEMU_OPTION_m },
2360 { "nographic", 0, QEMU_OPTION_nographic },
2361 #ifdef CONFIG_VNC
2362 { "vnc", 0, QEMU_OPTION_vnc },
2363 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2364 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2365 #ifdef CONFIG_SDL
2366 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2367 #endif
2368 #endif
2369 { "k", HAS_ARG, QEMU_OPTION_k },
2370 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2372 { "nics", HAS_ARG, QEMU_OPTION_nics},
2373 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2374 { "bridge", HAS_ARG, QEMU_OPTION_bridge},
2375 { "n", HAS_ARG, QEMU_OPTION_n },
2376 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2377 #ifdef CONFIG_SLIRP
2378 { "user-net", 0, QEMU_OPTION_user_net },
2379 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2380 #ifndef _WIN32
2381 { "smb", HAS_ARG, QEMU_OPTION_smb },
2382 #endif
2383 { "redir", HAS_ARG, QEMU_OPTION_redir },
2384 #endif
2385 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2387 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2388 { "append", HAS_ARG, QEMU_OPTION_append },
2389 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2391 { "S", 0, QEMU_OPTION_S },
2392 { "s", 0, QEMU_OPTION_s },
2393 { "p", HAS_ARG, QEMU_OPTION_p },
2394 { "d", HAS_ARG, QEMU_OPTION_d },
2395 { "l", HAS_ARG, QEMU_OPTION_l },
2396 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2397 { "L", HAS_ARG, QEMU_OPTION_L },
2398 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2399 { "vcpus", 1, QEMU_OPTION_vcpus },
2400 #ifdef TARGET_PPC
2401 { "prep", 0, QEMU_OPTION_prep },
2402 { "g", 1, QEMU_OPTION_g },
2403 #endif
2404 { "localtime", 0, QEMU_OPTION_localtime },
2405 { "isa", 0, QEMU_OPTION_isa },
2406 { "std-vga", 0, QEMU_OPTION_std_vga },
2407 { "monitor", 1, QEMU_OPTION_monitor },
2408 { "serial", 1, QEMU_OPTION_serial },
2409 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2410 { "full-screen", 0, QEMU_OPTION_full_screen },
2412 /* temporary options */
2413 { "pci", 0, QEMU_OPTION_pci },
2414 { "nic-ne2000", 0, QEMU_OPTION_nic_ne2000 },
2415 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2416 { "vgaacc", HAS_ARG, QEMU_OPTION_vgaacc },
2417 { NULL },
2418 };
2420 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2422 /* this stack is only used during signal handling */
2423 #define SIGNAL_STACK_SIZE 32768
2425 static uint8_t *signal_stack;
2427 #endif
2429 #define NET_IF_TUN 0
2430 #define NET_IF_USER 1
2431 #define NET_IF_DUMMY 2
2433 #include <xg_private.h>
2435 #if defined(__i386__) || defined (__x86_64__)
2436 #define L1_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_USER)
2437 #define L2_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_DIRTY|_PAGE_USER)
2439 #ifdef __i386__
2440 #define _LEVEL_3_ 0
2441 #else
2442 #define _LEVEL_3_ 1
2443 #endif
2445 #if _LEVEL_3_
2446 #define L3_PROT (_PAGE_PRESENT)
2447 #define L1_PAGETABLE_ENTRIES 512
2448 #else
2449 #define L1_PAGETABLE_ENTRIES 1024
2450 #endif
2452 inline int
2453 get_vl2_table(unsigned long count, unsigned long start)
2455 #if _LEVEL_3_
2456 return ((start + (count << PAGE_SHIFT)) >> L3_PAGETABLE_SHIFT) & 0x3;
2457 #else
2458 return 0;
2459 #endif
2462 int
2463 setup_mapping(int xc_handle, uint32_t dom, unsigned long toptab, unsigned long *mem_page_array, unsigned long *page_table_array, unsigned long v_start, unsigned long v_end)
2465 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2466 l2_pgentry_t *vl2tab[4] = {NULL, NULL, NULL, NULL};
2467 l2_pgentry_t *vl2e=NULL, *vl2_table = NULL;
2468 unsigned long l1tab;
2469 unsigned long ppt_alloc = 0;
2470 unsigned long count;
2471 int i = 0;
2472 #if _LEVEL_3_
2473 l3_pgentry_t *vl3tab = NULL;
2474 unsigned long l2tab;
2475 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2476 PROT_READ|PROT_WRITE,
2477 toptab >> PAGE_SHIFT)) == NULL )
2478 goto error_out;
2479 for (i = 0; i < 4 ; i++) {
2480 l2tab = vl3tab[i] & PAGE_MASK;
2481 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2482 PROT_READ|PROT_WRITE,
2483 l2tab >> PAGE_SHIFT);
2484 if(vl2tab[i] == NULL)
2485 goto error_out;
2487 munmap(vl3tab, PAGE_SIZE);
2488 vl3tab = NULL;
2489 #else
2490 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2491 PROT_READ|PROT_WRITE,
2492 toptab >> PAGE_SHIFT)) == NULL )
2493 goto error_out;
2494 #endif
2496 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ )
2498 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2500 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2501 vl2e = &vl2_table[l2_table_offset(
2502 v_start + (count << PAGE_SHIFT))];
2504 l1tab = page_table_array[ppt_alloc++] << PAGE_SHIFT;
2505 if ( vl1tab != NULL )
2506 munmap(vl1tab, PAGE_SIZE);
2508 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2509 PROT_READ|PROT_WRITE,
2510 l1tab >> PAGE_SHIFT)) == NULL )
2512 goto error_out;
2514 memset(vl1tab, 0, PAGE_SIZE);
2515 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2516 *vl2e = l1tab | L2_PROT;
2519 *vl1e = (mem_page_array[count] << PAGE_SHIFT) | L1_PROT;
2520 vl1e++;
2522 error_out:
2523 if(vl1tab) munmap(vl1tab, PAGE_SIZE);
2524 for(i = 0; i < 4; i++)
2525 if(vl2tab[i]) munmap(vl2tab[i], PAGE_SIZE);
2526 return ppt_alloc;
2529 void
2530 unsetup_mapping(int xc_handle, uint32_t dom, unsigned long toptab, unsigned long v_start, unsigned long v_end)
2532 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2533 l2_pgentry_t *vl2tab[4], *vl2e=NULL, *vl2_table = NULL;
2534 unsigned long l1tab;
2535 unsigned long count;
2536 int i = 0;
2537 #if _LEVEL_3_
2538 l3_pgentry_t *vl3tab = NULL;
2539 unsigned long l2tab;
2540 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2541 PROT_READ|PROT_WRITE,
2542 toptab >> PAGE_SHIFT)) == NULL )
2543 goto error_out;
2544 for (i = 0; i < 4 ; i ++){
2545 l2tab = vl3tab[i] & PAGE_MASK;
2546 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2547 PROT_READ|PROT_WRITE,
2548 l2tab >> PAGE_SHIFT);
2549 if(vl2tab[i] == NULL)
2550 goto error_out;
2552 munmap(vl3tab, PAGE_SIZE);
2553 vl3tab = NULL;
2554 #else
2555 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2556 PROT_READ|PROT_WRITE,
2557 toptab >> PAGE_SHIFT)) == NULL )
2558 goto error_out;
2559 #endif
2561 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ ){
2562 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2564 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2565 vl2e = &vl2_table[l2_table_offset(v_start + (count << PAGE_SHIFT))];
2566 l1tab = *vl2e & PAGE_MASK;
2568 if(l1tab == 0)
2569 continue;
2570 if ( vl1tab != NULL )
2571 munmap(vl1tab, PAGE_SIZE);
2573 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2574 PROT_READ|PROT_WRITE,
2575 l1tab >> PAGE_SHIFT)) == NULL )
2577 goto error_out;
2579 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2580 *vl2e = 0;
2583 *vl1e = 0;
2584 vl1e++;
2586 error_out:
2587 if(vl1tab) munmap(vl1tab, PAGE_SIZE);
2588 for(i = 0; i < 4; i++)
2589 if(vl2tab[i]) munmap(vl2tab[i], PAGE_SIZE);
2592 void set_vram_mapping(unsigned long addr, unsigned long end)
2594 end = addr + VGA_RAM_SIZE;
2595 setup_mapping(xc_handle, domid, toptab,
2596 vgapage_array, freepage_array, addr, end);
2599 void unset_vram_mapping(unsigned long addr, unsigned long end)
2601 end = addr + VGA_RAM_SIZE;
2602 /* FIXME Flush the shadow page */
2603 unsetup_mapping(xc_handle, domid, toptab, addr, end);
2605 #elif defined(__ia64__)
2606 void set_vram_mapping(unsigned long addr, unsigned long end) {}
2607 void unset_vram_mapping(unsigned long addr, unsigned long end) {}
2608 #endif
2610 int main(int argc, char **argv)
2612 #ifdef CONFIG_GDBSTUB
2613 int use_gdbstub, gdbstub_port;
2614 #endif
2615 int i, has_cdrom;
2616 int snapshot, linux_boot;
2617 CPUState *env;
2618 const char *initrd_filename;
2619 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2620 const char *kernel_filename, *kernel_cmdline;
2621 DisplayState *ds = &display_state;
2622 int cyls, heads, secs;
2623 int start_emulation = 1;
2624 uint8_t macaddr[6];
2625 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2626 int optind;
2627 const char *r, *optarg;
2628 CharDriverState *monitor_hd;
2629 char monitor_device[128];
2630 char serial_devices[MAX_SERIAL_PORTS][128];
2631 int serial_device_index;
2632 const char *loadvm = NULL;
2633 unsigned long nr_pages, extra_pages, ram_pages, *page_array;
2634 extern void *shared_page;
2635 extern void *shared_vram;
2636 /* change the qemu-dm to daemon, just like bochs dm */
2637 // daemon(0, 0);
2639 #if !defined(CONFIG_SOFTMMU)
2640 /* we never want that malloc() uses mmap() */
2641 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2642 #endif
2643 initrd_filename = NULL;
2644 for(i = 0; i < MAX_FD; i++)
2645 fd_filename[i] = NULL;
2646 for(i = 0; i < MAX_DISKS; i++)
2647 hd_filename[i] = NULL;
2648 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2649 vga_ram_size = VGA_RAM_SIZE;
2650 bios_size = BIOS_SIZE;
2651 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2652 #ifdef CONFIG_GDBSTUB
2653 use_gdbstub = 0;
2654 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2655 #endif
2656 snapshot = 0;
2657 nographic = 0;
2658 usevnc = 0;
2659 vncport=0;
2660 vncconnect=NULL;
2661 kernel_filename = NULL;
2662 kernel_cmdline = "";
2663 has_cdrom = 1;
2664 cyls = heads = secs = 0;
2665 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2667 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2668 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2669 serial_devices[i][0] = '\0';
2670 serial_device_index = 0;
2672 nb_tun_fds = 0;
2673 net_if_type = -1;
2674 nb_nics = 1;
2675 /* default mac address of the first network interface */
2676 macaddr[0] = 0x52;
2677 macaddr[1] = 0x54;
2678 macaddr[2] = 0x00;
2679 macaddr[3] = 0x12;
2680 macaddr[4] = 0x34;
2681 macaddr[5] = 0x56;
2683 /* init debug */
2684 cpu_set_log(0);
2686 optind = 1;
2687 for(;;) {
2688 if (optind >= argc)
2689 break;
2690 r = argv[optind];
2691 if (r[0] != '-') {
2692 hd_filename[0] = argv[optind++];
2693 } else {
2694 const QEMUOption *popt;
2696 optind++;
2697 popt = qemu_options;
2698 for(;;) {
2699 if (!popt->name) {
2700 fprintf(stderr, "%s: invalid option -- '%s'\n",
2701 argv[0], r);
2702 exit(1);
2704 if (!strcmp(popt->name, r + 1))
2705 break;
2706 popt++;
2708 if (popt->flags & HAS_ARG) {
2709 if (optind >= argc) {
2710 fprintf(stderr, "%s: option '%s' requires an argument\n",
2711 argv[0], r);
2712 exit(1);
2714 optarg = argv[optind++];
2715 } else {
2716 optarg = NULL;
2719 switch(popt->index) {
2720 case QEMU_OPTION_initrd:
2721 initrd_filename = optarg;
2722 break;
2723 case QEMU_OPTION_hda:
2724 hd_filename[0] = optarg;
2725 break;
2726 case QEMU_OPTION_hdb:
2727 hd_filename[1] = optarg;
2728 break;
2729 case QEMU_OPTION_snapshot:
2730 snapshot = 1;
2731 break;
2732 case QEMU_OPTION_hdachs:
2734 const char *p;
2735 p = optarg;
2736 cyls = strtol(p, (char **)&p, 0);
2737 if (*p != ',')
2738 goto chs_fail;
2739 p++;
2740 heads = strtol(p, (char **)&p, 0);
2741 if (*p != ',')
2742 goto chs_fail;
2743 p++;
2744 secs = strtol(p, (char **)&p, 0);
2745 if (*p != '\0') {
2746 chs_fail:
2747 cyls = 0;
2750 break;
2751 case QEMU_OPTION_nographic:
2752 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2753 if(!strcmp(serial_devices[0], "vc"))
2754 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
2755 "stdio");
2756 nographic = 1;
2757 break;
2758 #ifdef CONFIG_VNC
2759 case QEMU_OPTION_vnc:
2760 usevnc = 1;
2761 break;
2762 case QEMU_OPTION_vncport:
2764 const char *p;
2765 p = optarg;
2766 vncport= strtol(optarg, (char **)&p, 0);
2768 break;
2769 case QEMU_OPTION_vncconnect:
2771 vncconnect=optarg;
2773 break;
2774 #ifdef CONFIG_SDL
2775 case QEMU_OPTION_vnc_and_sdl:
2776 usevnc = 2;
2777 break;
2778 #endif
2779 #endif
2780 case QEMU_OPTION_kernel:
2781 kernel_filename = optarg;
2782 break;
2783 case QEMU_OPTION_append:
2784 kernel_cmdline = optarg;
2785 break;
2786 case QEMU_OPTION_tun_fd:
2788 const char *p;
2789 int fd;
2790 net_if_type = NET_IF_TUN;
2791 if (nb_tun_fds < MAX_NICS) {
2792 fd = strtol(optarg, (char **)&p, 0);
2793 if (*p != '\0') {
2794 fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2795 exit(1);
2797 tun_fds[nb_tun_fds++] = fd;
2800 break;
2801 case QEMU_OPTION_hdc:
2802 hd_filename[2] = optarg;
2803 has_cdrom = 0;
2804 break;
2805 case QEMU_OPTION_hdd:
2806 hd_filename[3] = optarg;
2807 break;
2808 case QEMU_OPTION_cdrom:
2809 hd_filename[2] = optarg;
2810 has_cdrom = 1;
2811 break;
2812 case QEMU_OPTION_boot:
2813 boot_device = optarg[0];
2814 if (boot_device != 'a' &&
2815 boot_device != 'c' && boot_device != 'd') {
2816 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2817 exit(1);
2819 break;
2820 case QEMU_OPTION_fda:
2821 fd_filename[0] = optarg;
2822 break;
2823 case QEMU_OPTION_fdb:
2824 fd_filename[1] = optarg;
2825 break;
2826 case QEMU_OPTION_nics:
2827 nb_nics = atoi(optarg);
2828 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2829 fprintf(stderr, "qemu: invalid number of network interfaces\n");
2830 exit(1);
2832 break;
2833 case QEMU_OPTION_bridge:
2834 pstrcpy(bridge, sizeof(bridge), optarg);
2835 break;
2836 case QEMU_OPTION_macaddr:
2838 const char *p;
2839 int i;
2840 p = optarg;
2841 for(i = 0; i < 6; i++) {
2842 macaddr[i] = strtol(p, (char **)&p, 16);
2843 if (i == 5) {
2844 if (*p != '\0')
2845 goto macaddr_error;
2846 } else {
2847 if (*p != ':') {
2848 macaddr_error:
2849 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2850 exit(1);
2852 p++;
2856 break;
2857 #ifdef CONFIG_SLIRP
2858 case QEMU_OPTION_tftp:
2859 tftp_prefix = optarg;
2860 break;
2861 #ifndef _WIN32
2862 case QEMU_OPTION_smb:
2863 net_slirp_smb(optarg);
2864 break;
2865 #endif
2866 case QEMU_OPTION_user_net:
2867 net_if_type = NET_IF_USER;
2868 break;
2869 case QEMU_OPTION_redir:
2870 net_slirp_redir(optarg);
2871 break;
2872 #endif
2873 case QEMU_OPTION_dummy_net:
2874 net_if_type = NET_IF_DUMMY;
2875 break;
2876 case QEMU_OPTION_enable_audio:
2877 audio_enabled = 1;
2878 break;
2879 case QEMU_OPTION_h:
2880 help();
2881 break;
2882 case QEMU_OPTION_m:
2883 ram_size = atoi(optarg) * 1024 * 1024;
2884 if (ram_size <= 0)
2885 help();
2886 break;
2887 case QEMU_OPTION_d:
2889 domid = atoi(optarg);
2890 printf("domid: %d\n", domid);
2892 break;
2894 case QEMU_OPTION_p:
2896 extern uint16_t ioreq_remote_port;
2897 ioreq_remote_port = atoi(optarg);
2898 printf("port: %d\n", ioreq_remote_port);
2900 break;
2901 case QEMU_OPTION_l:
2903 int mask;
2904 mask = cpu_str_to_log_mask(optarg);
2905 printf("mask: %x\n", mask);
2906 cpu_set_log(mask);
2908 break;
2909 case QEMU_OPTION_n:
2910 pstrcpy(network_script, sizeof(network_script), optarg);
2911 break;
2912 #ifdef CONFIG_GDBSTUB
2913 case QEMU_OPTION_s:
2914 use_gdbstub = 1;
2915 break;
2916 #endif
2917 case QEMU_OPTION_L:
2918 bios_dir = optarg;
2919 break;
2920 case QEMU_OPTION_S:
2921 start_emulation = 0;
2922 break;
2923 case QEMU_OPTION_vcpus:
2924 vcpus = atoi(optarg);
2925 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
2926 case QEMU_OPTION_pci:
2927 pci_enabled = 1;
2928 break;
2929 case QEMU_OPTION_nic_ne2000:
2930 nic_ne2000 = 1;
2931 break;
2932 case QEMU_OPTION_isa:
2933 pci_enabled = 0;
2934 break;
2935 case QEMU_OPTION_prep:
2936 prep_enabled = 1;
2937 break;
2938 case QEMU_OPTION_k:
2939 keyboard_layout = optarg;
2940 break;
2941 case QEMU_OPTION_localtime:
2942 rtc_utc = 0;
2943 break;
2944 case QEMU_OPTION_cirrusvga:
2945 cirrus_vga_enabled = 1;
2946 break;
2947 case QEMU_OPTION_vgaacc:
2949 const char *p;
2950 p = optarg;
2951 vga_accelerate = strtol(p, (char **)&p, 0);
2952 if (*p != '\0') {
2953 fprintf(stderr, "qemu: invalid vgaacc option\n");
2954 exit(1);
2956 break;
2958 case QEMU_OPTION_std_vga:
2959 cirrus_vga_enabled = 0;
2960 break;
2961 case QEMU_OPTION_g:
2963 const char *p;
2964 int w, h, depth;
2965 p = optarg;
2966 w = strtol(p, (char **)&p, 10);
2967 if (w <= 0) {
2968 graphic_error:
2969 fprintf(stderr, "qemu: invalid resolution or depth\n");
2970 exit(1);
2972 if (*p != 'x')
2973 goto graphic_error;
2974 p++;
2975 h = strtol(p, (char **)&p, 10);
2976 if (h <= 0)
2977 goto graphic_error;
2978 if (*p == 'x') {
2979 p++;
2980 depth = strtol(p, (char **)&p, 10);
2981 if (depth != 8 && depth != 15 && depth != 16 &&
2982 depth != 24 && depth != 32)
2983 goto graphic_error;
2984 } else if (*p == '\0') {
2985 depth = graphic_depth;
2986 } else {
2987 goto graphic_error;
2990 graphic_width = w;
2991 graphic_height = h;
2992 graphic_depth = depth;
2994 break;
2995 case QEMU_OPTION_monitor:
2996 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
2997 break;
2998 case QEMU_OPTION_serial:
2999 if (serial_device_index >= MAX_SERIAL_PORTS) {
3000 fprintf(stderr, "qemu: too many serial ports\n");
3001 exit(1);
3003 pstrcpy(serial_devices[serial_device_index],
3004 sizeof(serial_devices[0]), optarg);
3005 serial_device_index++;
3006 break;
3007 case QEMU_OPTION_loadvm:
3008 loadvm = optarg;
3009 break;
3010 case QEMU_OPTION_full_screen:
3011 full_screen = 1;
3012 break;
3017 linux_boot = (kernel_filename != NULL);
3019 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3020 fd_filename[0] == '\0')
3021 help();
3023 /* boot to cd by default if no hard disk */
3024 if (hd_filename[0] == '\0' && boot_device == 'c') {
3025 if (fd_filename[0] != '\0')
3026 boot_device = 'a';
3027 else
3028 boot_device = 'd';
3031 #if !defined(CONFIG_SOFTMMU)
3032 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3034 static uint8_t stdout_buf[4096];
3035 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3037 #else
3038 setvbuf(stdout, NULL, _IOLBF, 0);
3039 #endif
3041 /* init host network redirectors */
3042 if (net_if_type == -1) {
3043 net_if_type = NET_IF_TUN;
3044 #if defined(CONFIG_SLIRP)
3045 if (access(network_script, R_OK) < 0) {
3046 net_if_type = NET_IF_USER;
3048 #endif
3051 for(i = 0; i < nb_nics; i++) {
3052 NetDriverState *nd = &nd_table[i];
3053 nd->index = i;
3054 /* init virtual mac address */
3055 nd->macaddr[0] = macaddr[0];
3056 nd->macaddr[1] = macaddr[1];
3057 nd->macaddr[2] = macaddr[2];
3058 nd->macaddr[3] = macaddr[3];
3059 nd->macaddr[4] = macaddr[4];
3060 nd->macaddr[5] = macaddr[5] + i;
3061 switch(net_if_type) {
3062 #if defined(CONFIG_SLIRP)
3063 case NET_IF_USER:
3064 net_slirp_init(nd);
3065 break;
3066 #endif
3067 #if !defined(_WIN32)
3068 case NET_IF_TUN:
3069 if (i < nb_tun_fds) {
3070 net_fd_init(nd, tun_fds[i]);
3071 } else {
3072 if (net_tun_init(nd) < 0)
3073 net_dummy_init(nd);
3075 break;
3076 #endif
3077 case NET_IF_DUMMY:
3078 default:
3079 net_dummy_init(nd);
3080 break;
3084 /* init the memory */
3085 phys_ram_size = ram_size + vga_ram_size + bios_size;
3087 ram_pages = ram_size/PAGE_SIZE;
3088 #if defined(__i386__) || defined(__x86_64__)
3089 vgaram_pages = (vga_ram_size -1)/PAGE_SIZE + 1;
3090 free_pages = vgaram_pages / L1_PAGETABLE_ENTRIES;
3091 extra_pages = vgaram_pages + free_pages;
3092 #else
3093 /* Test vga acceleration later */
3094 extra_pages = 0;
3095 #endif
3097 xc_handle = xc_interface_open();
3099 xc_dominfo_t info;
3100 xc_domain_getinfo(xc_handle, domid, 1, &info);
3102 nr_pages = info.nr_pages + extra_pages;
3104 if ( xc_domain_setmaxmem(xc_handle, domid,
3105 (nr_pages) * PAGE_SIZE/1024 ) != 0)
3107 perror("set maxmem");
3108 exit(-1);
3111 if ( (page_array = (unsigned long *)
3112 malloc(nr_pages * sizeof(unsigned long))) == NULL)
3114 perror("malloc");
3115 exit(-1);
3118 if (xc_domain_memory_increase_reservation(xc_handle, domid,
3119 extra_pages , 0, 0, NULL) != 0) {
3120 perror("increase reservation");
3121 exit(-1);
3124 #if defined(__i386__) || defined(__x86_64__)
3125 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
3127 perror("xc_get_pfn_list");
3128 exit(-1);
3131 if ((phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3132 PROT_READ|PROT_WRITE,
3133 page_array,
3134 ram_pages - 1)) == 0) {
3135 perror("xc_map_foreign_batch");
3136 exit(-1);
3139 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3140 PROT_READ|PROT_WRITE,
3141 page_array[ram_pages - 1]);
3143 vgapage_array = &page_array[nr_pages - vgaram_pages];
3145 if ((shared_vram = xc_map_foreign_batch(xc_handle, domid,
3146 PROT_READ|PROT_WRITE,
3147 vgapage_array,
3148 vgaram_pages)) == 0) {
3149 perror("xc_map_foreign_batch vgaram ");
3150 exit(-1);
3153 memset(shared_vram, 0, vgaram_pages * PAGE_SIZE);
3154 toptab = page_array[ram_pages] << PAGE_SHIFT;
3156 vtop_table = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3157 PROT_READ|PROT_WRITE,
3158 page_array[ram_pages]);
3160 freepage_array = &page_array[nr_pages - extra_pages];
3161 #elif defined(__ia64__)
3162 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, 0, ram_pages) != ram_pages)
3164 perror("xc_ia64_get_pfn_list");
3165 exit(-1);
3168 if ((phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3169 PROT_READ|PROT_WRITE,
3170 page_array,
3171 ram_pages)) == 0) {
3172 perror("xc_map_foreign_batch");
3173 exit(-1);
3176 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, IO_PAGE_START>>PAGE_SHIFT, 1) != 1)
3178 perror("xc_ia64_get_pfn_list");
3179 exit(-1);
3182 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3183 PROT_READ|PROT_WRITE,
3184 page_array[0]);
3185 #endif
3187 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
3188 (page_array[nr_pages - 1]));
3190 /* we always create the cdrom drive, even if no disk is there */
3191 bdrv_init();
3192 if (has_cdrom) {
3193 bs_table[2] = bdrv_new("cdrom");
3194 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3197 /* open the virtual block devices */
3198 for(i = 0; i < MAX_DISKS; i++) {
3199 if (hd_filename[i]) {
3200 if (!bs_table[i]) {
3201 char buf[64];
3202 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3203 bs_table[i] = bdrv_new(buf);
3205 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3206 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3207 hd_filename[i]);
3208 exit(1);
3210 if (i == 0 && cyls != 0)
3211 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3215 /* we always create at least one floppy disk */
3216 fd_table[0] = bdrv_new("fda");
3217 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3219 for(i = 0; i < MAX_FD; i++) {
3220 if (fd_filename[i]) {
3221 if (!fd_table[i]) {
3222 char buf[64];
3223 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3224 fd_table[i] = bdrv_new(buf);
3225 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3227 if (fd_filename[i] != '\0') {
3228 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3229 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3230 fd_filename[i]);
3231 exit(1);
3237 /* init CPU state */
3238 env = cpu_init();
3239 global_env = env;
3240 cpu_single_env = env;
3242 init_ioports();
3243 cpu_calibrate_ticks();
3245 /* terminal init */
3246 if (nographic) {
3247 dumb_display_init(ds);
3248 } else {
3249 if (usevnc) {
3250 #ifdef CONFIG_VNC
3251 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
3252 #else
3253 perror("qemu not configured with vnc support");
3254 #endif
3255 } else {
3256 #ifdef CONFIG_SDL
3257 sdl_display_init(ds, full_screen);
3258 #else
3259 dumb_display_init(ds);
3260 #endif
3264 vga_console = graphic_console_init(ds);
3266 monitor_hd = qemu_chr_open(monitor_device);
3267 if (!monitor_hd) {
3268 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3269 exit(1);
3271 monitor_init(monitor_hd, !nographic);
3273 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3274 if (serial_devices[i][0] != '\0') {
3275 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3276 if (!serial_hds[i]) {
3277 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3278 serial_devices[i]);
3279 exit(1);
3281 if (!strcmp(serial_devices[i], "vc"))
3282 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3286 /* setup cpu signal handlers for MMU / self modifying code handling */
3287 #if !defined(CONFIG_SOFTMMU)
3289 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3291 stack_t stk;
3292 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3293 stk.ss_sp = signal_stack;
3294 stk.ss_size = SIGNAL_STACK_SIZE;
3295 stk.ss_flags = 0;
3297 if (sigaltstack(&stk, NULL) < 0) {
3298 perror("sigaltstack");
3299 exit(1);
3302 #endif
3304 struct sigaction act;
3306 sigfillset(&act.sa_mask);
3307 act.sa_flags = SA_SIGINFO;
3308 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3309 act.sa_flags |= SA_ONSTACK;
3310 #endif
3311 act.sa_sigaction = host_segv_handler;
3312 sigaction(SIGSEGV, &act, NULL);
3313 sigaction(SIGBUS, &act, NULL);
3314 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3315 sigaction(SIGFPE, &act, NULL);
3316 #endif
3318 #endif
3320 #ifndef _WIN32
3322 struct sigaction act;
3323 sigfillset(&act.sa_mask);
3324 act.sa_flags = 0;
3325 act.sa_handler = SIG_IGN;
3326 sigaction(SIGPIPE, &act, NULL);
3328 #endif
3329 init_timers();
3331 #if defined(TARGET_I386)
3332 pc_init(ram_size, vga_ram_size, boot_device,
3333 ds, fd_filename, snapshot,
3334 kernel_filename, kernel_cmdline, initrd_filename);
3335 #elif defined(TARGET_PPC)
3336 ppc_init(ram_size, vga_ram_size, boot_device,
3337 ds, fd_filename, snapshot,
3338 kernel_filename, kernel_cmdline, initrd_filename);
3339 #elif defined(TARGET_SPARC)
3340 sun4m_init(ram_size, vga_ram_size, boot_device,
3341 ds, fd_filename, snapshot,
3342 kernel_filename, kernel_cmdline, initrd_filename);
3343 #endif
3345 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3346 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3348 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
3349 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
3351 #ifdef CONFIG_GDBSTUB
3352 if (use_gdbstub) {
3353 if (gdbserver_start(gdbstub_port) < 0) {
3354 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3355 gdbstub_port);
3356 exit(1);
3357 } else {
3358 printf("Waiting gdb connection on port %d\n", gdbstub_port);
3360 } else
3361 #endif
3362 if (loadvm)
3363 qemu_loadvm(loadvm);
3366 /* XXX: simplify init */
3367 if (start_emulation) {
3368 vm_start();
3371 main_loop();
3372 quit_timers();
3373 return 0;
3376 extern fd_set wakeup_rfds;
3377 void tun_receive_handler(fd_set *rfds)
3379 IOHandlerRecord *ioh;
3380 static uint8_t buf[4096];
3381 int n, max_size;
3383 for (ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3384 if ( FD_ISSET(ioh->fd, rfds) ) {
3385 max_size = ioh->fd_can_read(ioh->opaque);
3386 if (max_size > 0) {
3387 if (max_size > sizeof(buf))
3388 max_size = sizeof(buf);
3389 n = read(ioh->fd, buf, max_size);
3390 if (n >= 0) {
3391 ioh->fd_read(ioh->opaque, buf, n);
3396 update_select_wakeup_events();
3399 void update_select_wakeup_events(void)
3401 IOHandlerRecord *ioh;
3402 int max_size;
3404 for(ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3405 FD_CLR(ioh->fd, &wakeup_rfds);
3406 if (ioh->fd_can_read) {
3407 max_size = ioh->fd_can_read(ioh->opaque);
3408 if (max_size > 0) {
3409 FD_SET(ioh->fd, &wakeup_rfds);