direct-io.hg

view tools/ioemu/vl.c @ 8151:f5b119533cc8

Define explicit evtchn_port_t type (32 bits) and plumb up
to user space thru /dev/xen/evtchn.

Signed-off-by: Keir Fraser <keir@xensource.com>
author kaf24@firebug.cl.cam.ac.uk
date Thu Dec 01 15:22:22 2005 +0100 (2005-12-01)
parents 310746cf9f27
children b8ba1bbba882
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 fprintf(logfile, "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 struct xs_handle *xs;
1180 char *path;
1182 xs = xs_daemon_open();
1183 if (xs == NULL) {
1184 fprintf(logfile, "Could not contact XenStore\n");
1185 return -1;
1188 xc_handle = xc_interface_open();
1189 if (xc_handle == -1) {
1190 fprintf(logfile, "xc_interface_open() error\n");
1191 return -1;
1194 path = xs_get_domain_path(xs, domid);
1195 if (path == NULL) {
1196 fprintf(logfile, "xs_get_domain_path() error\n");
1197 return -1;
1199 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1200 if (path == NULL) {
1201 fprintf(logfile, "realloc error\n");
1202 return -1;
1204 strcat(path, "/console/tty");
1205 if (!xs_write(xs, NULL, path, pts, strlen(pts))) {
1206 fprintf(logfile, "xs_write for console fail");
1207 return -1;
1210 free(path);
1211 xs_daemon_close(xs);
1212 close(xc_handle);
1214 return 0;
1217 #if defined(__linux__)
1218 CharDriverState *qemu_chr_open_pty(void)
1220 int master_fd, slave_fd;
1221 struct termios term;
1223 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0)
1224 return NULL;
1226 /* Set raw attributes on the pty. */
1227 cfmakeraw(&term);
1228 tcsetattr(slave_fd, TCSAFLUSH, &term);
1230 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1231 store_console_dev(domid, ptsname(master_fd));
1233 return qemu_chr_open_fd(master_fd, master_fd);
1235 #else
1236 CharDriverState *qemu_chr_open_pty(void)
1238 return NULL;
1240 #endif
1242 #endif /* !defined(_WIN32) */
1244 CharDriverState *qemu_chr_open(const char *filename)
1246 if (!strcmp(filename, "vc")) {
1247 return text_console_init(&display_state);
1248 } else if (!strcmp(filename, "null")) {
1249 return qemu_chr_open_null();
1250 } else
1251 #ifndef _WIN32
1252 if (!strcmp(filename, "pty")) {
1253 return qemu_chr_open_pty();
1254 } else if (!strcmp(filename, "stdio")) {
1255 return qemu_chr_open_stdio();
1256 } else
1257 #endif
1259 return NULL;
1263 /***********************************************************/
1264 /* Linux network device redirectors */
1266 void hex_dump(FILE *f, const uint8_t *buf, int size)
1268 int len, i, j, c;
1270 for(i=0;i<size;i+=16) {
1271 len = size - i;
1272 if (len > 16)
1273 len = 16;
1274 fprintf(f, "%08x ", i);
1275 for(j=0;j<16;j++) {
1276 if (j < len)
1277 fprintf(f, " %02x", buf[i+j]);
1278 else
1279 fprintf(f, " ");
1281 fprintf(f, " ");
1282 for(j=0;j<len;j++) {
1283 c = buf[i+j];
1284 if (c < ' ' || c > '~')
1285 c = '.';
1286 fprintf(f, "%c", c);
1288 fprintf(f, "\n");
1292 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1294 nd->send_packet(nd, buf, size);
1297 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1298 IOReadHandler *fd_read, void *opaque)
1300 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1303 /* dummy network adapter */
1305 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1309 static void dummy_add_read_packet(NetDriverState *nd,
1310 IOCanRWHandler *fd_can_read,
1311 IOReadHandler *fd_read, void *opaque)
1315 static int net_dummy_init(NetDriverState *nd)
1317 nd->send_packet = dummy_send_packet;
1318 nd->add_read_packet = dummy_add_read_packet;
1319 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1320 return 0;
1323 #if defined(CONFIG_SLIRP)
1325 /* slirp network adapter */
1327 static void *slirp_fd_opaque;
1328 static IOCanRWHandler *slirp_fd_can_read;
1329 static IOReadHandler *slirp_fd_read;
1330 static int slirp_inited;
1332 int slirp_can_output(void)
1334 return slirp_fd_can_read(slirp_fd_opaque);
1337 void slirp_output(const uint8_t *pkt, int pkt_len)
1339 #if 0
1340 printf("output:\n");
1341 hex_dump(stdout, pkt, pkt_len);
1342 #endif
1343 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1346 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1348 #if 0
1349 printf("input:\n");
1350 hex_dump(stdout, buf, size);
1351 #endif
1352 slirp_input(buf, size);
1355 static void slirp_add_read_packet(NetDriverState *nd,
1356 IOCanRWHandler *fd_can_read,
1357 IOReadHandler *fd_read, void *opaque)
1359 slirp_fd_opaque = opaque;
1360 slirp_fd_can_read = fd_can_read;
1361 slirp_fd_read = fd_read;
1364 static int net_slirp_init(NetDriverState *nd)
1366 if (!slirp_inited) {
1367 slirp_inited = 1;
1368 slirp_init();
1370 nd->send_packet = slirp_send_packet;
1371 nd->add_read_packet = slirp_add_read_packet;
1372 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1373 return 0;
1376 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1378 const char *p, *p1;
1379 int len;
1380 p = *pp;
1381 p1 = strchr(p, sep);
1382 if (!p1)
1383 return -1;
1384 len = p1 - p;
1385 p1++;
1386 if (buf_size > 0) {
1387 if (len > buf_size - 1)
1388 len = buf_size - 1;
1389 memcpy(buf, p, len);
1390 buf[len] = '\0';
1392 *pp = p1;
1393 return 0;
1396 static void net_slirp_redir(const char *redir_str)
1398 int is_udp;
1399 char buf[256], *r;
1400 const char *p;
1401 struct in_addr guest_addr;
1402 int host_port, guest_port;
1404 if (!slirp_inited) {
1405 slirp_inited = 1;
1406 slirp_init();
1409 p = redir_str;
1410 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1411 goto fail;
1412 if (!strcmp(buf, "tcp")) {
1413 is_udp = 0;
1414 } else if (!strcmp(buf, "udp")) {
1415 is_udp = 1;
1416 } else {
1417 goto fail;
1420 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1421 goto fail;
1422 host_port = strtol(buf, &r, 0);
1423 if (r == buf)
1424 goto fail;
1426 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1427 goto fail;
1428 if (buf[0] == '\0') {
1429 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1431 if (!inet_aton(buf, &guest_addr))
1432 goto fail;
1434 guest_port = strtol(p, &r, 0);
1435 if (r == p)
1436 goto fail;
1438 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1439 fprintf(stderr, "qemu: could not set up redirection\n");
1440 exit(1);
1442 return;
1443 fail:
1444 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1445 exit(1);
1448 #ifndef _WIN32
1450 char smb_dir[1024];
1452 static void smb_exit(void)
1454 DIR *d;
1455 struct dirent *de;
1456 char filename[1024];
1458 /* erase all the files in the directory */
1459 d = opendir(smb_dir);
1460 for(;;) {
1461 de = readdir(d);
1462 if (!de)
1463 break;
1464 if (strcmp(de->d_name, ".") != 0 &&
1465 strcmp(de->d_name, "..") != 0) {
1466 snprintf(filename, sizeof(filename), "%s/%s",
1467 smb_dir, de->d_name);
1468 unlink(filename);
1471 closedir(d);
1472 rmdir(smb_dir);
1475 /* automatic user mode samba server configuration */
1476 void net_slirp_smb(const char *exported_dir)
1478 char smb_conf[1024];
1479 char smb_cmdline[1024];
1480 FILE *f;
1482 if (!slirp_inited) {
1483 slirp_inited = 1;
1484 slirp_init();
1487 /* XXX: better tmp dir construction */
1488 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1489 if (mkdir(smb_dir, 0700) < 0) {
1490 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1491 exit(1);
1493 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1495 f = fopen(smb_conf, "w");
1496 if (!f) {
1497 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1498 exit(1);
1500 fprintf(f,
1501 "[global]\n"
1502 "pid directory=%s\n"
1503 "lock directory=%s\n"
1504 "log file=%s/log.smbd\n"
1505 "smb passwd file=%s/smbpasswd\n"
1506 "security = share\n"
1507 "[qemu]\n"
1508 "path=%s\n"
1509 "read only=no\n"
1510 "guest ok=yes\n",
1511 smb_dir,
1512 smb_dir,
1513 smb_dir,
1514 smb_dir,
1515 exported_dir
1516 );
1517 fclose(f);
1518 atexit(smb_exit);
1520 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1521 smb_conf);
1523 slirp_add_exec(0, smb_cmdline, 4, 139);
1526 #endif /* !defined(_WIN32) */
1528 #endif /* CONFIG_SLIRP */
1530 #if !defined(_WIN32)
1531 #ifdef _BSD
1532 static int tun_open(char *ifname, int ifname_size)
1534 int fd;
1535 char *dev;
1536 struct stat s;
1538 fd = open("/dev/tap", O_RDWR);
1539 if (fd < 0) {
1540 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1541 return -1;
1544 fstat(fd, &s);
1545 dev = devname(s.st_rdev, S_IFCHR);
1546 pstrcpy(ifname, ifname_size, dev);
1548 fcntl(fd, F_SETFL, O_NONBLOCK);
1549 return fd;
1551 #else
1552 static int tun_open(char *ifname, int ifname_size)
1554 struct ifreq ifr;
1555 int fd, ret;
1557 fd = open("/dev/net/tun", O_RDWR);
1558 if (fd < 0) {
1559 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1560 return -1;
1562 memset(&ifr, 0, sizeof(ifr));
1563 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1564 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1565 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1566 if (ret != 0) {
1567 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1568 close(fd);
1569 return -1;
1571 fprintf(logfile, "Connected to host network interface: %s\n", ifr.ifr_name);
1572 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1573 fcntl(fd, F_SETFL, O_NONBLOCK);
1574 return fd;
1576 #endif
1578 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1580 write(nd->fd, buf, size);
1583 static void tun_add_read_packet(NetDriverState *nd,
1584 IOCanRWHandler *fd_can_read,
1585 IOReadHandler *fd_read, void *opaque)
1587 qemu_add_fd_event_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1590 static int net_tun_init(NetDriverState *nd)
1592 int pid, status;
1593 char *args[4];
1594 char **parg;
1595 extern int highest_fds;
1597 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1598 if (nd->fd < 0)
1599 return -1;
1601 if ( nd->fd > highest_fds ) highest_fds = nd->fd;
1602 /* try to launch network init script */
1603 pid = fork();
1604 if (pid >= 0) {
1605 if (pid == 0) {
1606 parg = args;
1607 *parg++ = network_script;
1608 *parg++ = nd->ifname;
1609 *parg++ = bridge;
1610 *parg++ = NULL;
1611 execv(network_script, args);
1612 exit(1);
1614 while (waitpid(pid, &status, 0) != pid);
1615 if (!WIFEXITED(status) ||
1616 WEXITSTATUS(status) != 0) {
1617 fprintf(stderr, "%s: could not launch network script\n",
1618 network_script);
1621 nd->send_packet = tun_send_packet;
1622 nd->add_read_packet = tun_add_read_packet;
1623 return 0;
1626 static int net_fd_init(NetDriverState *nd, int fd)
1628 nd->fd = fd;
1629 nd->send_packet = tun_send_packet;
1630 nd->add_read_packet = tun_add_read_packet;
1631 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1632 return 0;
1635 #endif /* !_WIN32 */
1637 /***********************************************************/
1638 /* dumb display */
1640 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1644 static void dumb_resize(DisplayState *ds, int w, int h)
1648 static void dumb_refresh(DisplayState *ds)
1650 vga_update_display();
1653 void dumb_display_init(DisplayState *ds)
1655 ds->data = NULL;
1656 ds->linesize = 0;
1657 ds->depth = 0;
1658 ds->dpy_update = dumb_update;
1659 ds->dpy_resize = dumb_resize;
1660 ds->dpy_refresh = dumb_refresh;
1663 #if !defined(CONFIG_SOFTMMU)
1664 /***********************************************************/
1665 /* cpu signal handler */
1666 static void host_segv_handler(int host_signum, siginfo_t *info,
1667 void *puc)
1669 abort();
1671 #endif
1673 /***********************************************************/
1674 /* I/O handling */
1676 #define MAX_IO_HANDLERS 64
1678 typedef struct IOHandlerRecord {
1679 int fd;
1680 IOCanRWHandler *fd_can_read;
1681 IOReadHandler *fd_read;
1682 void *opaque;
1683 /* temporary data */
1684 struct pollfd *ufd;
1685 int max_size;
1686 struct IOHandlerRecord *next;
1687 } IOHandlerRecord;
1689 static IOHandlerRecord *first_io_handler;
1690 static IOHandlerRecord *first_eventio_handler;
1692 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1693 IOReadHandler *fd_read, void *opaque)
1695 IOHandlerRecord *ioh;
1697 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1698 if (!ioh)
1699 return -1;
1700 ioh->fd = fd;
1701 ioh->fd_can_read = fd_can_read;
1702 ioh->fd_read = fd_read;
1703 ioh->opaque = opaque;
1704 ioh->next = first_io_handler;
1705 first_io_handler = ioh;
1706 return 0;
1709 int qemu_add_fd_event_read_handler(int fd, IOCanRWHandler *fd_can_read,
1710 IOReadHandler *fd_read, void *opaque)
1712 IOHandlerRecord *ioh;
1714 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1715 if (!ioh)
1716 return -1;
1717 ioh->fd = fd;
1718 ioh->fd_can_read = fd_can_read;
1719 ioh->fd_read = fd_read;
1720 ioh->opaque = opaque;
1721 ioh->next = first_eventio_handler;
1722 first_eventio_handler = ioh;
1723 return 0;
1726 void qemu_del_fd_read_handler(int fd)
1728 IOHandlerRecord **pioh, *ioh;
1730 pioh = &first_io_handler;
1731 for(;;) {
1732 ioh = *pioh;
1733 if (ioh == NULL)
1734 break;
1735 if (ioh->fd == fd) {
1736 *pioh = ioh->next;
1737 break;
1739 pioh = &ioh->next;
1743 /***********************************************************/
1744 /* savevm/loadvm support */
1746 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1748 fwrite(buf, 1, size, f);
1751 void qemu_put_byte(QEMUFile *f, int v)
1753 fputc(v, f);
1756 void qemu_put_be16(QEMUFile *f, unsigned int v)
1758 qemu_put_byte(f, v >> 8);
1759 qemu_put_byte(f, v);
1762 void qemu_put_be32(QEMUFile *f, unsigned int v)
1764 qemu_put_byte(f, v >> 24);
1765 qemu_put_byte(f, v >> 16);
1766 qemu_put_byte(f, v >> 8);
1767 qemu_put_byte(f, v);
1770 void qemu_put_be64(QEMUFile *f, uint64_t v)
1772 qemu_put_be32(f, v >> 32);
1773 qemu_put_be32(f, v);
1776 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1778 return fread(buf, 1, size, f);
1781 int qemu_get_byte(QEMUFile *f)
1783 int v;
1784 v = fgetc(f);
1785 if (v == EOF)
1786 return 0;
1787 else
1788 return v;
1791 unsigned int qemu_get_be16(QEMUFile *f)
1793 unsigned int v;
1794 v = qemu_get_byte(f) << 8;
1795 v |= qemu_get_byte(f);
1796 return v;
1799 unsigned int qemu_get_be32(QEMUFile *f)
1801 unsigned int v;
1802 v = qemu_get_byte(f) << 24;
1803 v |= qemu_get_byte(f) << 16;
1804 v |= qemu_get_byte(f) << 8;
1805 v |= qemu_get_byte(f);
1806 return v;
1809 uint64_t qemu_get_be64(QEMUFile *f)
1811 uint64_t v;
1812 v = (uint64_t)qemu_get_be32(f) << 32;
1813 v |= qemu_get_be32(f);
1814 return v;
1817 int64_t qemu_ftell(QEMUFile *f)
1819 return ftell(f);
1822 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1824 if (fseek(f, pos, whence) < 0)
1825 return -1;
1826 return ftell(f);
1829 typedef struct SaveStateEntry {
1830 char idstr[256];
1831 int instance_id;
1832 int version_id;
1833 SaveStateHandler *save_state;
1834 LoadStateHandler *load_state;
1835 void *opaque;
1836 struct SaveStateEntry *next;
1837 } SaveStateEntry;
1839 static SaveStateEntry *first_se;
1841 int register_savevm(const char *idstr,
1842 int instance_id,
1843 int version_id,
1844 SaveStateHandler *save_state,
1845 LoadStateHandler *load_state,
1846 void *opaque)
1848 SaveStateEntry *se, **pse;
1850 se = qemu_malloc(sizeof(SaveStateEntry));
1851 if (!se)
1852 return -1;
1853 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1854 se->instance_id = instance_id;
1855 se->version_id = version_id;
1856 se->save_state = save_state;
1857 se->load_state = load_state;
1858 se->opaque = opaque;
1859 se->next = NULL;
1861 /* add at the end of list */
1862 pse = &first_se;
1863 while (*pse != NULL)
1864 pse = &(*pse)->next;
1865 *pse = se;
1866 return 0;
1869 #define QEMU_VM_FILE_MAGIC 0x5145564d
1870 #define QEMU_VM_FILE_VERSION 0x00000001
1872 int qemu_savevm(const char *filename)
1874 SaveStateEntry *se;
1875 QEMUFile *f;
1876 int len, len_pos, cur_pos, saved_vm_running, ret;
1878 saved_vm_running = vm_running;
1879 vm_stop(0);
1881 f = fopen(filename, "wb");
1882 if (!f) {
1883 ret = -1;
1884 goto the_end;
1887 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1888 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1890 for(se = first_se; se != NULL; se = se->next) {
1891 /* ID string */
1892 len = strlen(se->idstr);
1893 qemu_put_byte(f, len);
1894 qemu_put_buffer(f, se->idstr, len);
1896 qemu_put_be32(f, se->instance_id);
1897 qemu_put_be32(f, se->version_id);
1899 /* record size: filled later */
1900 len_pos = ftell(f);
1901 qemu_put_be32(f, 0);
1903 se->save_state(f, se->opaque);
1905 /* fill record size */
1906 cur_pos = ftell(f);
1907 len = ftell(f) - len_pos - 4;
1908 fseek(f, len_pos, SEEK_SET);
1909 qemu_put_be32(f, len);
1910 fseek(f, cur_pos, SEEK_SET);
1913 fclose(f);
1914 ret = 0;
1915 the_end:
1916 if (saved_vm_running)
1917 vm_start();
1918 return ret;
1921 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1923 SaveStateEntry *se;
1925 for(se = first_se; se != NULL; se = se->next) {
1926 if (!strcmp(se->idstr, idstr) &&
1927 instance_id == se->instance_id)
1928 return se;
1930 return NULL;
1933 int qemu_loadvm(const char *filename)
1935 SaveStateEntry *se;
1936 QEMUFile *f;
1937 int len, cur_pos, ret, instance_id, record_len, version_id;
1938 int saved_vm_running;
1939 unsigned int v;
1940 char idstr[256];
1942 saved_vm_running = vm_running;
1943 vm_stop(0);
1945 f = fopen(filename, "rb");
1946 if (!f) {
1947 ret = -1;
1948 goto the_end;
1951 v = qemu_get_be32(f);
1952 if (v != QEMU_VM_FILE_MAGIC)
1953 goto fail;
1954 v = qemu_get_be32(f);
1955 if (v != QEMU_VM_FILE_VERSION) {
1956 fail:
1957 fclose(f);
1958 ret = -1;
1959 goto the_end;
1961 for(;;) {
1962 #if defined (DO_TB_FLUSH)
1963 tb_flush(global_env);
1964 #endif
1965 len = qemu_get_byte(f);
1966 if (feof(f))
1967 break;
1968 qemu_get_buffer(f, idstr, len);
1969 idstr[len] = '\0';
1970 instance_id = qemu_get_be32(f);
1971 version_id = qemu_get_be32(f);
1972 record_len = qemu_get_be32(f);
1973 #if 0
1974 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1975 idstr, instance_id, version_id, record_len);
1976 #endif
1977 cur_pos = ftell(f);
1978 se = find_se(idstr, instance_id);
1979 if (!se) {
1980 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1981 instance_id, idstr);
1982 } else {
1983 ret = se->load_state(f, se->opaque, version_id);
1984 if (ret < 0) {
1985 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1986 instance_id, idstr);
1989 /* always seek to exact end of record */
1990 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1992 fclose(f);
1993 ret = 0;
1994 the_end:
1995 if (saved_vm_running)
1996 vm_start();
1997 return ret;
2000 /***********************************************************/
2001 /* main execution loop */
2003 void gui_update(void *opaque)
2005 display_state.dpy_refresh(&display_state);
2006 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2008 void polling_handler(void *opaque)
2010 #ifndef _WIN32
2011 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2012 IOHandlerRecord *ioh, *ioh_next;
2013 uint8_t buf[4096];
2014 int n, max_size;
2015 #endif
2016 int timeout = 0;
2017 int ret;
2019 #ifdef _WIN32
2020 if (timeout > 0)
2021 Sleep(timeout);
2022 #else
2023 /* poll any events */
2024 /* XXX: separate device handlers from system ones */
2025 pf = ufds;
2026 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2027 if (!ioh->fd_can_read) {
2028 max_size = 0;
2029 pf->fd = ioh->fd;
2030 pf->events = POLLIN;
2031 ioh->ufd = pf;
2032 pf++;
2033 } else {
2034 max_size = ioh->fd_can_read(ioh->opaque);
2035 if (max_size > 0) {
2036 if (max_size > sizeof(buf))
2037 max_size = sizeof(buf);
2038 pf->fd = ioh->fd;
2039 pf->events = POLLIN;
2040 ioh->ufd = pf;
2041 pf++;
2042 } else {
2043 ioh->ufd = NULL;
2046 ioh->max_size = max_size;
2049 ret = poll(ufds, pf - ufds, timeout);
2050 if (ret > 0) {
2051 /* XXX: better handling of removal */
2052 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2053 ioh_next = ioh->next;
2054 pf = ioh->ufd;
2055 if (pf) {
2056 if (pf->revents & POLLIN) {
2057 if (ioh->max_size == 0) {
2058 /* just a read event */
2059 ioh->fd_read(ioh->opaque, NULL, 0);
2060 } else {
2061 n = read(ioh->fd, buf, ioh->max_size);
2062 if (n >= 0) {
2063 ioh->fd_read(ioh->opaque, buf, n);
2064 } else if (errno != EAGAIN) {
2065 ioh->fd_read(ioh->opaque, NULL, -errno);
2072 #endif /* !defined(_WIN32) */
2074 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
2078 /* XXX: support several handlers */
2079 VMStopHandler *vm_stop_cb;
2080 VMStopHandler *vm_stop_opaque;
2082 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2084 vm_stop_cb = cb;
2085 vm_stop_opaque = opaque;
2086 return 0;
2089 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2091 vm_stop_cb = NULL;
2094 void vm_start(void)
2096 if (!vm_running) {
2097 cpu_enable_ticks();
2098 vm_running = 1;
2102 void vm_stop(int reason)
2104 if (vm_running) {
2105 cpu_disable_ticks();
2106 vm_running = 0;
2107 if (reason != 0) {
2108 if (vm_stop_cb) {
2109 vm_stop_cb(vm_stop_opaque, reason);
2115 /* reset/shutdown handler */
2117 typedef struct QEMUResetEntry {
2118 QEMUResetHandler *func;
2119 void *opaque;
2120 struct QEMUResetEntry *next;
2121 } QEMUResetEntry;
2123 static QEMUResetEntry *first_reset_entry;
2124 int reset_requested;
2125 int shutdown_requested;
2127 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2129 QEMUResetEntry **pre, *re;
2131 pre = &first_reset_entry;
2132 while (*pre != NULL)
2133 pre = &(*pre)->next;
2134 re = qemu_mallocz(sizeof(QEMUResetEntry));
2135 re->func = func;
2136 re->opaque = opaque;
2137 re->next = NULL;
2138 *pre = re;
2141 void qemu_system_reset(void)
2143 QEMUResetEntry *re;
2145 /* reset all devices */
2146 for(re = first_reset_entry; re != NULL; re = re->next) {
2147 re->func(re->opaque);
2151 void qemu_system_reset_request(void)
2153 reset_requested = 1;
2154 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2157 void qemu_system_shutdown_request(void)
2159 shutdown_requested = 1;
2160 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2163 void main_loop_wait(int timeout)
2165 if (vm_running) {
2166 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2167 qemu_get_clock(vm_clock));
2168 /* run dma transfers, if any */
2169 DMA_run();
2172 /* real time timers */
2173 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2174 qemu_get_clock(rt_clock));
2177 void help(void)
2179 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2180 "usage: %s [options] [disk_image]\n"
2181 "\n"
2182 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2183 "\n"
2184 "Standard options:\n"
2185 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2186 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2187 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2188 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2189 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2190 "-snapshot write to temporary files instead of disk image files\n"
2191 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2192 "-nographic disable graphical output and redirect serial I/Os to console\n"
2193 "-vcpus set CPU number of guest platform\n"
2194 #ifdef CONFIG_VNC
2195 "-vnc port use vnc instead of sdl\n"
2196 "-vncport port use a different port\n"
2197 "-vncconnect host:port do a reverse connect\n"
2198 #ifdef CONFIG_SDL
2199 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2200 #endif
2201 #endif
2202 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2203 "-enable-audio enable audio support\n"
2204 "-localtime set the real time clock to local time [default=utc]\n"
2205 "-full-screen start in full screen\n"
2206 #ifdef TARGET_PPC
2207 "-prep Simulate a PREP system (default is PowerMAC)\n"
2208 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2209 #endif
2210 "-nic-ne2000 simulate an Realtek ne2k PCI ethernet adaptor\n"
2211 "\n"
2212 "Network options:\n"
2213 "-nics n simulate 'n' network cards [default=1]\n"
2214 "-macaddr addr set the mac address of the first interface\n"
2215 "-bridge br set the bridge interface for nic\n"
2216 "-n script set tap/tun network init script [default=%s]\n"
2217 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2218 #ifdef CONFIG_SLIRP
2219 "-user-net use user mode network stack [default if no tap/tun script]\n"
2220 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2221 #ifndef _WIN32
2222 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2223 #endif
2224 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2225 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2226 #endif
2227 "-dummy-net use dummy network stack\n"
2228 "\n"
2229 "Linux boot specific:\n"
2230 "-kernel bzImage use 'bzImage' as kernel image\n"
2231 "-append cmdline use 'cmdline' as kernel command line\n"
2232 "-initrd file use 'file' as initial ram disk\n"
2233 "\n"
2234 "Debug/Expert options:\n"
2235 "-monitor dev redirect the monitor to char device 'dev'\n"
2236 "-serial dev redirect the serial port to char device 'dev'\n"
2237 "-S freeze CPU at startup (use 'c' to start execution)\n"
2238 "-s wait gdb connection to port %d\n"
2239 "-p port ioreq port for xen\n"
2240 "-d domain domain that we're serving\n"
2241 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2242 "-L path set the directory for the BIOS and VGA BIOS\n"
2243 #ifdef USE_CODE_COPY
2244 "-no-code-copy disable code copy acceleration\n"
2245 #endif
2246 #ifdef TARGET_I386
2247 "-isa simulate an ISA-only system (default is PCI system)\n"
2248 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2249 " (default is CL-GD5446 PCI VGA)\n"
2250 "-vgaacc [0|1] 1 to accelerate CL-GD5446 speed, default is 1\n"
2251 #endif
2252 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2253 "\n"
2254 "During emulation, the following keys are useful:\n"
2255 "ctrl-alt-f toggle full screen\n"
2256 "ctrl-alt-n switch to virtual console 'n'\n"
2257 "ctrl-alt toggle mouse and keyboard grab\n"
2258 "\n"
2259 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2261 #ifdef CONFIG_SOFTMMU
2262 "qemu",
2263 #else
2264 "qemu-fast",
2265 #endif
2266 DEFAULT_RAM_SIZE,
2267 DEFAULT_NETWORK_SCRIPT,
2268 DEFAULT_GDBSTUB_PORT);
2269 #ifndef CONFIG_SOFTMMU
2270 printf("\n"
2271 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2272 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2273 "PC emulation.\n");
2274 #endif
2275 exit(1);
2278 #define HAS_ARG 0x0001
2280 enum {
2281 QEMU_OPTION_h,
2283 QEMU_OPTION_fda,
2284 QEMU_OPTION_fdb,
2285 QEMU_OPTION_hda,
2286 QEMU_OPTION_hdb,
2287 QEMU_OPTION_hdc,
2288 QEMU_OPTION_hdd,
2289 QEMU_OPTION_cdrom,
2290 QEMU_OPTION_boot,
2291 QEMU_OPTION_snapshot,
2292 QEMU_OPTION_m,
2293 QEMU_OPTION_nographic,
2294 #ifdef CONFIG_VNC
2295 QEMU_OPTION_vnc,
2296 QEMU_OPTION_vncport,
2297 QEMU_OPTION_vncconnect,
2298 #ifdef CONFIG_SDL
2299 QEMU_OPTION_vnc_and_sdl,
2300 #endif
2301 #endif
2302 QEMU_OPTION_enable_audio,
2304 QEMU_OPTION_nics,
2305 QEMU_OPTION_macaddr,
2306 QEMU_OPTION_bridge,
2307 QEMU_OPTION_n,
2308 QEMU_OPTION_tun_fd,
2309 QEMU_OPTION_user_net,
2310 QEMU_OPTION_tftp,
2311 QEMU_OPTION_smb,
2312 QEMU_OPTION_redir,
2313 QEMU_OPTION_dummy_net,
2315 QEMU_OPTION_kernel,
2316 QEMU_OPTION_append,
2317 QEMU_OPTION_initrd,
2319 QEMU_OPTION_S,
2320 QEMU_OPTION_s,
2321 QEMU_OPTION_p,
2322 QEMU_OPTION_d,
2323 QEMU_OPTION_l,
2324 QEMU_OPTION_hdachs,
2325 QEMU_OPTION_L,
2326 QEMU_OPTION_no_code_copy,
2327 QEMU_OPTION_vcpus,
2328 QEMU_OPTION_pci,
2329 QEMU_OPTION_nic_ne2000,
2330 QEMU_OPTION_isa,
2331 QEMU_OPTION_prep,
2332 QEMU_OPTION_k,
2333 QEMU_OPTION_localtime,
2334 QEMU_OPTION_cirrusvga,
2335 QEMU_OPTION_g,
2336 QEMU_OPTION_std_vga,
2337 QEMU_OPTION_monitor,
2338 QEMU_OPTION_serial,
2339 QEMU_OPTION_loadvm,
2340 QEMU_OPTION_full_screen,
2341 QEMU_OPTION_vgaacc,
2342 };
2344 typedef struct QEMUOption {
2345 const char *name;
2346 int flags;
2347 int index;
2348 } QEMUOption;
2350 const QEMUOption qemu_options[] = {
2351 { "h", 0, QEMU_OPTION_h },
2353 { "fda", HAS_ARG, QEMU_OPTION_fda },
2354 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2355 { "hda", HAS_ARG, QEMU_OPTION_hda },
2356 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2357 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2358 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2359 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2360 { "boot", HAS_ARG, QEMU_OPTION_boot },
2361 { "snapshot", 0, QEMU_OPTION_snapshot },
2362 { "m", HAS_ARG, QEMU_OPTION_m },
2363 { "nographic", 0, QEMU_OPTION_nographic },
2364 #ifdef CONFIG_VNC
2365 { "vnc", 0, QEMU_OPTION_vnc },
2366 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2367 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2368 #ifdef CONFIG_SDL
2369 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2370 #endif
2371 #endif
2372 { "k", HAS_ARG, QEMU_OPTION_k },
2373 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2375 { "nics", HAS_ARG, QEMU_OPTION_nics},
2376 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2377 { "bridge", HAS_ARG, QEMU_OPTION_bridge},
2378 { "n", HAS_ARG, QEMU_OPTION_n },
2379 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2380 #ifdef CONFIG_SLIRP
2381 { "user-net", 0, QEMU_OPTION_user_net },
2382 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2383 #ifndef _WIN32
2384 { "smb", HAS_ARG, QEMU_OPTION_smb },
2385 #endif
2386 { "redir", HAS_ARG, QEMU_OPTION_redir },
2387 #endif
2388 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2390 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2391 { "append", HAS_ARG, QEMU_OPTION_append },
2392 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2394 { "S", 0, QEMU_OPTION_S },
2395 { "s", 0, QEMU_OPTION_s },
2396 { "p", HAS_ARG, QEMU_OPTION_p },
2397 { "d", HAS_ARG, QEMU_OPTION_d },
2398 { "l", HAS_ARG, QEMU_OPTION_l },
2399 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2400 { "L", HAS_ARG, QEMU_OPTION_L },
2401 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2402 { "vcpus", 1, QEMU_OPTION_vcpus },
2403 #ifdef TARGET_PPC
2404 { "prep", 0, QEMU_OPTION_prep },
2405 { "g", 1, QEMU_OPTION_g },
2406 #endif
2407 { "localtime", 0, QEMU_OPTION_localtime },
2408 { "isa", 0, QEMU_OPTION_isa },
2409 { "std-vga", 0, QEMU_OPTION_std_vga },
2410 { "monitor", 1, QEMU_OPTION_monitor },
2411 { "serial", 1, QEMU_OPTION_serial },
2412 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2413 { "full-screen", 0, QEMU_OPTION_full_screen },
2415 /* temporary options */
2416 { "pci", 0, QEMU_OPTION_pci },
2417 { "nic-ne2000", 0, QEMU_OPTION_nic_ne2000 },
2418 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2419 { "vgaacc", HAS_ARG, QEMU_OPTION_vgaacc },
2420 { NULL },
2421 };
2423 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2425 /* this stack is only used during signal handling */
2426 #define SIGNAL_STACK_SIZE 32768
2428 static uint8_t *signal_stack;
2430 #endif
2432 #define NET_IF_TUN 0
2433 #define NET_IF_USER 1
2434 #define NET_IF_DUMMY 2
2436 #include <xg_private.h>
2438 #if defined(__i386__) || defined (__x86_64__)
2439 #define L1_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_USER)
2440 #define L2_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_DIRTY|_PAGE_USER)
2442 #ifdef __i386__
2443 #define _LEVEL_3_ 0
2444 #else
2445 #define _LEVEL_3_ 1
2446 #endif
2448 #if _LEVEL_3_
2449 #define L3_PROT (_PAGE_PRESENT)
2450 #define L1_PAGETABLE_ENTRIES 512
2451 #else
2452 #define L1_PAGETABLE_ENTRIES 1024
2453 #endif
2455 inline int
2456 get_vl2_table(unsigned long count, unsigned long start)
2458 #if _LEVEL_3_
2459 return ((start + (count << PAGE_SHIFT)) >> L3_PAGETABLE_SHIFT) & 0x3;
2460 #else
2461 return 0;
2462 #endif
2465 int
2466 setup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2467 unsigned long *mem_page_array, unsigned long *page_table_array,
2468 unsigned long v_start, unsigned long v_end)
2470 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2471 l2_pgentry_t *vl2tab[4] = {NULL, NULL, NULL, NULL};
2472 l2_pgentry_t *vl2e=NULL, *vl2_table = NULL;
2473 unsigned long l1tab;
2474 unsigned long ppt_alloc = 0;
2475 unsigned long count;
2476 int i = 0;
2477 #if _LEVEL_3_
2478 l3_pgentry_t *vl3tab = NULL;
2479 unsigned long l2tab;
2481 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2482 PROT_READ|PROT_WRITE,
2483 toptab >> PAGE_SHIFT)) == NULL )
2484 goto error_out;
2485 for (i = 0; i < 4 ; i++) {
2486 l2tab = vl3tab[i] & PAGE_MASK;
2487 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2488 PROT_READ|PROT_WRITE,
2489 l2tab >> PAGE_SHIFT);
2490 if(vl2tab[i] == NULL)
2491 goto error_out;
2493 munmap(vl3tab, PAGE_SIZE);
2494 vl3tab = NULL;
2495 #else
2496 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2497 PROT_READ|PROT_WRITE,
2498 toptab >> PAGE_SHIFT)) == NULL )
2499 goto error_out;
2500 #endif
2502 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ )
2504 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2506 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2507 vl2e = &vl2_table[l2_table_offset(v_start +
2508 (count << PAGE_SHIFT))];
2510 l1tab = page_table_array[ppt_alloc++] << PAGE_SHIFT;
2511 if ( vl1tab != NULL )
2512 munmap(vl1tab, PAGE_SIZE);
2514 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2515 PROT_READ|PROT_WRITE,
2516 l1tab >> PAGE_SHIFT)) == NULL )
2518 goto error_out;
2520 memset(vl1tab, 0, PAGE_SIZE);
2521 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2522 *vl2e = l1tab | L2_PROT;
2525 *vl1e = (mem_page_array[count] << PAGE_SHIFT) | L1_PROT;
2526 vl1e++;
2528 error_out:
2529 if (vl1tab)
2530 munmap(vl1tab, PAGE_SIZE);
2531 for(i = 0; i < 4; i++)
2532 if(vl2tab[i]) munmap(vl2tab[i], PAGE_SIZE);
2533 return ppt_alloc;
2536 void
2537 unsetup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2538 unsigned long v_start, unsigned long v_end)
2540 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2541 l2_pgentry_t *vl2tab[4], *vl2e=NULL, *vl2_table = NULL;
2542 unsigned long l1tab;
2543 unsigned long count;
2544 int i = 0;
2545 #if _LEVEL_3_
2546 l3_pgentry_t *vl3tab = NULL;
2547 unsigned long l2tab;
2549 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2550 PROT_READ|PROT_WRITE,
2551 toptab >> PAGE_SHIFT)) == NULL )
2552 goto error_out;
2553 for (i = 0; i < 4 ; i ++) {
2554 l2tab = vl3tab[i] & PAGE_MASK;
2555 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2556 PROT_READ|PROT_WRITE,
2557 l2tab >> PAGE_SHIFT);
2558 if (vl2tab[i] == NULL)
2559 goto error_out;
2561 munmap(vl3tab, PAGE_SIZE);
2562 vl3tab = NULL;
2563 #else
2564 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2565 PROT_READ|PROT_WRITE,
2566 toptab >> PAGE_SHIFT)) == NULL )
2567 goto error_out;
2568 #endif
2570 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ ) {
2571 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2573 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2574 vl2e = &vl2_table[l2_table_offset(v_start + (count << PAGE_SHIFT))];
2575 l1tab = *vl2e & PAGE_MASK;
2577 if(l1tab == 0)
2578 continue;
2579 if ( vl1tab != NULL )
2580 munmap(vl1tab, PAGE_SIZE);
2582 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2583 PROT_READ|PROT_WRITE,
2584 l1tab >> PAGE_SHIFT)) == NULL )
2586 goto error_out;
2588 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2589 *vl2e = 0;
2592 *vl1e = 0;
2593 vl1e++;
2596 error_out:
2597 if (vl1tab)
2598 munmap(vl1tab, PAGE_SIZE);
2599 for(i = 0; i < 4; i++)
2600 if (vl2tab[i])
2601 munmap(vl2tab[i], PAGE_SIZE);
2604 void set_vram_mapping(unsigned long addr, unsigned long end)
2606 end = addr + VGA_RAM_SIZE;
2607 setup_mapping(xc_handle, domid, toptab,
2608 vgapage_array, freepage_array, addr, end);
2611 void unset_vram_mapping(unsigned long addr, unsigned long end)
2613 end = addr + VGA_RAM_SIZE;
2614 /* FIXME Flush the shadow page */
2615 unsetup_mapping(xc_handle, domid, toptab, addr, end);
2617 #elif defined(__ia64__)
2618 void set_vram_mapping(unsigned long addr, unsigned long end) {}
2619 void unset_vram_mapping(unsigned long addr, unsigned long end) {}
2620 #endif
2622 int main(int argc, char **argv)
2624 #ifdef CONFIG_GDBSTUB
2625 int use_gdbstub, gdbstub_port;
2626 #endif
2627 int i, has_cdrom;
2628 int snapshot, linux_boot;
2629 CPUState *env;
2630 const char *initrd_filename;
2631 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2632 const char *kernel_filename, *kernel_cmdline;
2633 DisplayState *ds = &display_state;
2634 int cyls, heads, secs;
2635 int start_emulation = 1;
2636 uint8_t macaddr[6];
2637 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2638 int optind;
2639 const char *r, *optarg;
2640 CharDriverState *monitor_hd;
2641 char monitor_device[128];
2642 char serial_devices[MAX_SERIAL_PORTS][128];
2643 int serial_device_index;
2644 const char *loadvm = NULL;
2645 unsigned long nr_pages, extra_pages, ram_pages, *page_array;
2646 extern void *shared_page;
2647 extern void *shared_vram;
2649 #if !defined(CONFIG_SOFTMMU)
2650 /* we never want that malloc() uses mmap() */
2651 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2652 #endif
2653 initrd_filename = NULL;
2654 for(i = 0; i < MAX_FD; i++)
2655 fd_filename[i] = NULL;
2656 for(i = 0; i < MAX_DISKS; i++)
2657 hd_filename[i] = NULL;
2658 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2659 vga_ram_size = VGA_RAM_SIZE;
2660 bios_size = BIOS_SIZE;
2661 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2662 #ifdef CONFIG_GDBSTUB
2663 use_gdbstub = 0;
2664 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2665 #endif
2666 snapshot = 0;
2667 nographic = 0;
2668 usevnc = 0;
2669 vncport=0;
2670 vncconnect=NULL;
2671 kernel_filename = NULL;
2672 kernel_cmdline = "";
2673 has_cdrom = 1;
2674 cyls = heads = secs = 0;
2675 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2677 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2678 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2679 serial_devices[i][0] = '\0';
2680 serial_device_index = 0;
2682 nb_tun_fds = 0;
2683 net_if_type = -1;
2684 nb_nics = 1;
2685 /* default mac address of the first network interface */
2686 macaddr[0] = 0x52;
2687 macaddr[1] = 0x54;
2688 macaddr[2] = 0x00;
2689 macaddr[3] = 0x12;
2690 macaddr[4] = 0x34;
2691 macaddr[5] = 0x56;
2693 /* init debug */
2694 cpu_set_log(0);
2696 optind = 1;
2697 for(;;) {
2698 if (optind >= argc)
2699 break;
2700 r = argv[optind];
2701 if (r[0] != '-') {
2702 hd_filename[0] = argv[optind++];
2703 } else {
2704 const QEMUOption *popt;
2706 optind++;
2707 popt = qemu_options;
2708 for(;;) {
2709 if (!popt->name) {
2710 fprintf(stderr, "%s: invalid option -- '%s'\n",
2711 argv[0], r);
2712 exit(1);
2714 if (!strcmp(popt->name, r + 1))
2715 break;
2716 popt++;
2718 if (popt->flags & HAS_ARG) {
2719 if (optind >= argc) {
2720 fprintf(stderr, "%s: option '%s' requires an argument\n",
2721 argv[0], r);
2722 exit(1);
2724 optarg = argv[optind++];
2725 } else {
2726 optarg = NULL;
2729 switch(popt->index) {
2730 case QEMU_OPTION_initrd:
2731 initrd_filename = optarg;
2732 break;
2733 case QEMU_OPTION_hda:
2734 hd_filename[0] = optarg;
2735 break;
2736 case QEMU_OPTION_hdb:
2737 hd_filename[1] = optarg;
2738 break;
2739 case QEMU_OPTION_snapshot:
2740 snapshot = 1;
2741 break;
2742 case QEMU_OPTION_hdachs:
2744 const char *p;
2745 p = optarg;
2746 cyls = strtol(p, (char **)&p, 0);
2747 if (*p != ',')
2748 goto chs_fail;
2749 p++;
2750 heads = strtol(p, (char **)&p, 0);
2751 if (*p != ',')
2752 goto chs_fail;
2753 p++;
2754 secs = strtol(p, (char **)&p, 0);
2755 if (*p != '\0') {
2756 chs_fail:
2757 cyls = 0;
2760 break;
2761 case QEMU_OPTION_nographic:
2762 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2763 if(!strcmp(serial_devices[0], "vc"))
2764 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
2765 "stdio");
2766 nographic = 1;
2767 break;
2768 #ifdef CONFIG_VNC
2769 case QEMU_OPTION_vnc:
2770 usevnc = 1;
2771 break;
2772 case QEMU_OPTION_vncport:
2774 const char *p;
2775 p = optarg;
2776 vncport= strtol(optarg, (char **)&p, 0);
2778 break;
2779 case QEMU_OPTION_vncconnect:
2780 vncconnect = optarg;
2781 break;
2782 #ifdef CONFIG_SDL
2783 case QEMU_OPTION_vnc_and_sdl:
2784 usevnc = 2;
2785 break;
2786 #endif
2787 #endif
2788 case QEMU_OPTION_kernel:
2789 kernel_filename = optarg;
2790 break;
2791 case QEMU_OPTION_append:
2792 kernel_cmdline = optarg;
2793 break;
2794 case QEMU_OPTION_tun_fd:
2796 const char *p;
2797 int fd;
2798 net_if_type = NET_IF_TUN;
2799 if ( nb_tun_fds < MAX_NICS ) {
2800 fd = strtol(optarg, (char **)&p, 0);
2801 if (*p != '\0') {
2802 fprintf(stderr,
2803 "qemu: invalid fd for network interface %d\n",
2804 nb_tun_fds);
2805 exit(1);
2807 tun_fds[nb_tun_fds++] = fd;
2810 break;
2811 case QEMU_OPTION_hdc:
2812 hd_filename[2] = optarg;
2813 has_cdrom = 0;
2814 break;
2815 case QEMU_OPTION_hdd:
2816 hd_filename[3] = optarg;
2817 break;
2818 case QEMU_OPTION_cdrom:
2819 hd_filename[2] = optarg;
2820 has_cdrom = 1;
2821 break;
2822 case QEMU_OPTION_boot:
2823 boot_device = optarg[0];
2824 if ( boot_device != 'a' &&
2825 boot_device != 'c' &&
2826 boot_device != 'd' ) {
2827 fprintf(stderr, "qemu: invalid boot device '%c'\n",
2828 boot_device);
2829 exit(1);
2831 break;
2832 case QEMU_OPTION_fda:
2833 fd_filename[0] = optarg;
2834 break;
2835 case QEMU_OPTION_fdb:
2836 fd_filename[1] = optarg;
2837 break;
2838 case QEMU_OPTION_nics:
2839 nb_nics = atoi(optarg);
2840 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2841 fprintf(stderr,
2842 "qemu: invalid number of network interfaces\n");
2843 exit(1);
2845 break;
2846 case QEMU_OPTION_bridge:
2847 pstrcpy(bridge, sizeof(bridge), optarg);
2848 break;
2849 case QEMU_OPTION_macaddr:
2851 const char *p;
2852 int i;
2854 p = optarg;
2855 for (i = 0; i < 6; i++) {
2856 macaddr[i] = strtol(p, (char **)&p, 16);
2857 if (i == 5) {
2858 if (*p != '\0')
2859 goto macaddr_error;
2860 } else {
2861 if (*p != ':') {
2862 macaddr_error:
2863 fprintf(stderr, "qemu: invalid syntax "
2864 "for ethernet address\n");
2865 exit(1);
2867 p++;
2871 break;
2872 #ifdef CONFIG_SLIRP
2873 case QEMU_OPTION_tftp:
2874 tftp_prefix = optarg;
2875 break;
2876 #ifndef _WIN32
2877 case QEMU_OPTION_smb:
2878 net_slirp_smb(optarg);
2879 break;
2880 #endif
2881 case QEMU_OPTION_user_net:
2882 net_if_type = NET_IF_USER;
2883 break;
2884 case QEMU_OPTION_redir:
2885 net_slirp_redir(optarg);
2886 break;
2887 #endif
2888 case QEMU_OPTION_dummy_net:
2889 net_if_type = NET_IF_DUMMY;
2890 break;
2891 case QEMU_OPTION_enable_audio:
2892 audio_enabled = 1;
2893 break;
2894 case QEMU_OPTION_h:
2895 help();
2896 break;
2897 case QEMU_OPTION_m:
2898 ram_size = atoi(optarg) * 1024 * 1024;
2899 if (ram_size <= 0)
2900 help();
2901 break;
2902 case QEMU_OPTION_d:
2904 domid = atoi(optarg);
2905 fprintf(logfile, "domid: %d\n", domid);
2907 break;
2908 case QEMU_OPTION_p:
2910 extern evtchn_port_t ioreq_remote_port;
2911 ioreq_remote_port = atoi(optarg);
2912 fprintf(logfile, "eport: %d\n", ioreq_remote_port);
2914 break;
2915 case QEMU_OPTION_l:
2917 int mask;
2918 mask = cpu_str_to_log_mask(optarg);
2919 fprintf(logfile, "mask: %x\n", mask);
2920 cpu_set_log(mask);
2922 break;
2923 case QEMU_OPTION_n:
2924 pstrcpy(network_script, sizeof(network_script), optarg);
2925 break;
2926 #ifdef CONFIG_GDBSTUB
2927 case QEMU_OPTION_s:
2928 use_gdbstub = 1;
2929 break;
2930 #endif
2931 case QEMU_OPTION_L:
2932 bios_dir = optarg;
2933 break;
2934 case QEMU_OPTION_S:
2935 start_emulation = 0;
2936 break;
2937 case QEMU_OPTION_vcpus:
2938 vcpus = atoi(optarg);
2939 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
2940 case QEMU_OPTION_pci:
2941 pci_enabled = 1;
2942 break;
2943 case QEMU_OPTION_nic_ne2000:
2944 nic_ne2000 = 1;
2945 break;
2946 case QEMU_OPTION_isa:
2947 pci_enabled = 0;
2948 break;
2949 case QEMU_OPTION_prep:
2950 prep_enabled = 1;
2951 break;
2952 case QEMU_OPTION_k:
2953 keyboard_layout = optarg;
2954 break;
2955 case QEMU_OPTION_localtime:
2956 rtc_utc = 0;
2957 break;
2958 case QEMU_OPTION_cirrusvga:
2959 cirrus_vga_enabled = 1;
2960 break;
2961 case QEMU_OPTION_vgaacc:
2963 const char *p;
2964 p = optarg;
2965 vga_accelerate = strtol(p, (char **)&p, 0);
2966 if (*p != '\0') {
2967 fprintf(stderr, "qemu: invalid vgaacc option\n");
2968 exit(1);
2971 break;
2972 case QEMU_OPTION_std_vga:
2973 cirrus_vga_enabled = 0;
2974 break;
2975 case QEMU_OPTION_g:
2977 const char *p;
2978 int w, h, depth;
2979 p = optarg;
2980 w = strtol(p, (char **)&p, 10);
2981 if (w <= 0) {
2982 graphic_error:
2983 fprintf(stderr, "qemu: invalid resolution or depth\n");
2984 exit(1);
2986 if (*p != 'x')
2987 goto graphic_error;
2988 p++;
2989 h = strtol(p, (char **)&p, 10);
2990 if (h <= 0)
2991 goto graphic_error;
2992 if (*p == 'x') {
2993 p++;
2994 depth = strtol(p, (char **)&p, 10);
2995 if (depth != 8 && depth != 15 && depth != 16 &&
2996 depth != 24 && depth != 32)
2997 goto graphic_error;
2998 } else if (*p == '\0') {
2999 depth = graphic_depth;
3000 } else {
3001 goto graphic_error;
3004 graphic_width = w;
3005 graphic_height = h;
3006 graphic_depth = depth;
3008 break;
3009 case QEMU_OPTION_monitor:
3010 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3011 break;
3012 case QEMU_OPTION_serial:
3013 if (serial_device_index >= MAX_SERIAL_PORTS) {
3014 fprintf(stderr, "qemu: too many serial ports\n");
3015 exit(1);
3017 pstrcpy(serial_devices[serial_device_index],
3018 sizeof(serial_devices[0]), optarg);
3019 serial_device_index++;
3020 break;
3021 case QEMU_OPTION_loadvm:
3022 loadvm = optarg;
3023 break;
3024 case QEMU_OPTION_full_screen:
3025 full_screen = 1;
3026 break;
3031 linux_boot = (kernel_filename != NULL);
3033 if ( !linux_boot && hd_filename[0] == '\0' &&
3034 hd_filename[2] == '\0' && fd_filename[0] == '\0' )
3035 help();
3037 /* boot to cd by default if no hard disk */
3038 if (hd_filename[0] == '\0' && boot_device == 'c') {
3039 if (fd_filename[0] != '\0')
3040 boot_device = 'a';
3041 else
3042 boot_device = 'd';
3045 #if !defined(CONFIG_SOFTMMU)
3046 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3048 static uint8_t stdout_buf[4096];
3049 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3051 #else
3052 setvbuf(stdout, NULL, _IOLBF, 0);
3053 #endif
3055 /* init host network redirectors */
3056 if (net_if_type == -1) {
3057 net_if_type = NET_IF_TUN;
3058 #if defined(CONFIG_SLIRP)
3059 if (access(network_script, R_OK) < 0) {
3060 net_if_type = NET_IF_USER;
3062 #endif
3065 for(i = 0; i < nb_nics; i++) {
3066 NetDriverState *nd = &nd_table[i];
3067 nd->index = i;
3068 /* init virtual mac address */
3069 nd->macaddr[0] = macaddr[0];
3070 nd->macaddr[1] = macaddr[1];
3071 nd->macaddr[2] = macaddr[2];
3072 nd->macaddr[3] = macaddr[3];
3073 nd->macaddr[4] = macaddr[4];
3074 nd->macaddr[5] = macaddr[5] + i;
3075 switch(net_if_type) {
3076 #if defined(CONFIG_SLIRP)
3077 case NET_IF_USER:
3078 net_slirp_init(nd);
3079 break;
3080 #endif
3081 #if !defined(_WIN32)
3082 case NET_IF_TUN:
3083 if (i < nb_tun_fds) {
3084 net_fd_init(nd, tun_fds[i]);
3085 } else {
3086 if (net_tun_init(nd) < 0)
3087 net_dummy_init(nd);
3089 break;
3090 #endif
3091 case NET_IF_DUMMY:
3092 default:
3093 net_dummy_init(nd);
3094 break;
3098 /* init the memory */
3099 phys_ram_size = ram_size + vga_ram_size + bios_size;
3101 ram_pages = ram_size/PAGE_SIZE;
3102 #if defined(__i386__) || defined(__x86_64__)
3103 vgaram_pages = (vga_ram_size -1)/PAGE_SIZE + 1;
3104 free_pages = vgaram_pages / L1_PAGETABLE_ENTRIES;
3105 extra_pages = vgaram_pages + free_pages;
3106 #else
3107 /* Test vga acceleration later */
3108 extra_pages = 0;
3109 #endif
3111 xc_handle = xc_interface_open();
3113 xc_dominfo_t info;
3114 xc_domain_getinfo(xc_handle, domid, 1, &info);
3116 nr_pages = info.nr_pages + extra_pages;
3118 if ( xc_domain_setmaxmem(xc_handle, domid,
3119 (nr_pages) * PAGE_SIZE/1024 ) != 0)
3121 fprintf(logfile, "set maxmem returned error %d\n", errno);
3122 exit(-1);
3125 if ( (page_array = (unsigned long *)
3126 malloc(nr_pages * sizeof(unsigned long))) == NULL)
3128 fprintf(logfile, "malloc returned error %d\n", errno);
3129 exit(-1);
3132 if (xc_domain_memory_increase_reservation(xc_handle, domid,
3133 extra_pages , 0, 0, NULL) != 0)
3135 fprintf(logfile, "increase reservation returned error %d\n", errno);
3136 exit(-1);
3139 #if defined(__i386__) || defined(__x86_64__)
3140 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
3142 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
3143 exit(-1);
3146 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3147 PROT_READ|PROT_WRITE,
3148 page_array,
3149 ram_pages - 1)) == 0 )
3151 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3152 exit(-1);
3155 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3156 PROT_READ|PROT_WRITE,
3157 page_array[ram_pages - 1]);
3159 vgapage_array = &page_array[nr_pages - vgaram_pages];
3161 if ( (shared_vram = xc_map_foreign_batch(xc_handle, domid,
3162 PROT_READ|PROT_WRITE,
3163 vgapage_array,
3164 vgaram_pages)) == 0)
3166 fprintf(logfile,
3167 "xc_map_foreign_batch vgaram returned error %d\n", errno);
3168 exit(-1);
3171 memset(shared_vram, 0, vgaram_pages * PAGE_SIZE);
3172 toptab = page_array[ram_pages] << PAGE_SHIFT;
3174 vtop_table = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3175 PROT_READ|PROT_WRITE,
3176 page_array[ram_pages]);
3178 freepage_array = &page_array[nr_pages - extra_pages];
3179 #elif defined(__ia64__)
3180 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, 0, ram_pages)
3181 != ram_pages )
3183 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3184 exit(-1);
3187 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3188 PROT_READ|PROT_WRITE,
3189 page_array,
3190 ram_pages)) == 0 )
3192 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3193 exit(-1);
3196 if ( xc_ia64_get_pfn_list(xc_handle, domid,
3197 page_array, IO_PAGE_START >> PAGE_SHIFT, 1) != 1 )
3199 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3200 exit(-1);
3203 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3204 PROT_READ|PROT_WRITE,
3205 page_array[0]);
3206 #endif
3208 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
3209 (page_array[nr_pages - 1]));
3211 /* we always create the cdrom drive, even if no disk is there */
3212 bdrv_init();
3213 if (has_cdrom) {
3214 bs_table[2] = bdrv_new("cdrom");
3215 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3218 /* open the virtual block devices */
3219 for(i = 0; i < MAX_DISKS; i++) {
3220 if (hd_filename[i]) {
3221 if (!bs_table[i]) {
3222 char buf[64];
3223 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3224 bs_table[i] = bdrv_new(buf);
3226 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3227 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3228 hd_filename[i]);
3229 exit(1);
3231 if (i == 0 && cyls != 0)
3232 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3236 /* we always create at least one floppy disk */
3237 fd_table[0] = bdrv_new("fda");
3238 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3240 for(i = 0; i < MAX_FD; i++) {
3241 if (fd_filename[i]) {
3242 if (!fd_table[i]) {
3243 char buf[64];
3244 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3245 fd_table[i] = bdrv_new(buf);
3246 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3248 if (fd_filename[i] != '\0') {
3249 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3250 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3251 fd_filename[i]);
3252 exit(1);
3258 /* init CPU state */
3259 env = cpu_init();
3260 global_env = env;
3261 cpu_single_env = env;
3263 init_ioports();
3264 cpu_calibrate_ticks();
3266 /* terminal init */
3267 if (nographic) {
3268 dumb_display_init(ds);
3269 } else {
3270 if (usevnc) {
3271 #ifdef CONFIG_VNC
3272 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
3273 #else
3274 fprintf(logfile, "qemu not configured with vnc support\n");
3275 #endif
3276 } else {
3277 #ifdef CONFIG_SDL
3278 sdl_display_init(ds, full_screen);
3279 #else
3280 dumb_display_init(ds);
3281 #endif
3285 vga_console = graphic_console_init(ds);
3287 monitor_hd = qemu_chr_open(monitor_device);
3288 if (!monitor_hd) {
3289 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3290 exit(1);
3292 monitor_init(monitor_hd, !nographic);
3294 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3295 if (serial_devices[i][0] != '\0') {
3296 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3297 if (!serial_hds[i]) {
3298 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3299 serial_devices[i]);
3300 exit(1);
3302 if (!strcmp(serial_devices[i], "vc"))
3303 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3307 /* setup cpu signal handlers for MMU / self modifying code handling */
3308 #if !defined(CONFIG_SOFTMMU)
3310 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3312 stack_t stk;
3313 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3314 stk.ss_sp = signal_stack;
3315 stk.ss_size = SIGNAL_STACK_SIZE;
3316 stk.ss_flags = 0;
3318 if (sigaltstack(&stk, NULL) < 0) {
3319 fprintf(logfile, "sigaltstack returned error %d\n", errno);
3320 exit(1);
3323 #endif
3325 struct sigaction act;
3327 sigfillset(&act.sa_mask);
3328 act.sa_flags = SA_SIGINFO;
3329 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3330 act.sa_flags |= SA_ONSTACK;
3331 #endif
3332 act.sa_sigaction = host_segv_handler;
3333 sigaction(SIGSEGV, &act, NULL);
3334 sigaction(SIGBUS, &act, NULL);
3335 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3336 sigaction(SIGFPE, &act, NULL);
3337 #endif
3339 #endif
3341 #ifndef _WIN32
3343 struct sigaction act;
3344 sigfillset(&act.sa_mask);
3345 act.sa_flags = 0;
3346 act.sa_handler = SIG_IGN;
3347 sigaction(SIGPIPE, &act, NULL);
3349 #endif
3350 init_timers();
3352 #if defined(TARGET_I386)
3353 pc_init(ram_size, vga_ram_size, boot_device,
3354 ds, fd_filename, snapshot,
3355 kernel_filename, kernel_cmdline, initrd_filename);
3356 #elif defined(TARGET_PPC)
3357 ppc_init(ram_size, vga_ram_size, boot_device,
3358 ds, fd_filename, snapshot,
3359 kernel_filename, kernel_cmdline, initrd_filename);
3360 #elif defined(TARGET_SPARC)
3361 sun4m_init(ram_size, vga_ram_size, boot_device,
3362 ds, fd_filename, snapshot,
3363 kernel_filename, kernel_cmdline, initrd_filename);
3364 #endif
3366 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3367 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3369 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
3370 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
3372 #ifdef CONFIG_GDBSTUB
3373 if (use_gdbstub) {
3374 if (gdbserver_start(gdbstub_port) < 0) {
3375 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3376 gdbstub_port);
3377 exit(1);
3378 } else {
3379 fprintf(logfile, "Waiting gdb connection on port %d\n", gdbstub_port);
3381 } else
3382 #endif
3383 if (loadvm)
3384 qemu_loadvm(loadvm);
3387 /* XXX: simplify init */
3388 if (start_emulation) {
3389 vm_start();
3392 main_loop();
3393 quit_timers();
3394 return 0;
3397 extern fd_set wakeup_rfds;
3398 void tun_receive_handler(fd_set *rfds)
3400 IOHandlerRecord *ioh;
3401 static uint8_t buf[4096];
3402 int n, max_size;
3404 for (ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3405 if ( FD_ISSET(ioh->fd, rfds) ) {
3406 max_size = ioh->fd_can_read(ioh->opaque);
3407 if (max_size > 0) {
3408 if (max_size > sizeof(buf))
3409 max_size = sizeof(buf);
3410 n = read(ioh->fd, buf, max_size);
3411 if (n >= 0) {
3412 ioh->fd_read(ioh->opaque, buf, n);
3417 update_select_wakeup_events();
3420 void update_select_wakeup_events(void)
3422 IOHandlerRecord *ioh;
3423 int max_size;
3425 for(ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3426 FD_CLR(ioh->fd, &wakeup_rfds);
3427 if (ioh->fd_can_read) {
3428 max_size = ioh->fd_can_read(ioh->opaque);
3429 if (max_size > 0) {
3430 FD_SET(ioh->fd, &wakeup_rfds);