ia64/xen-unstable

view tools/ioemu/vl.c @ 8741:da6297243495

There is a known "xm console" issue related with VMX. When "serial" is
enabled in script and no once uses "xm console" to read the console,
VMX boting will hang due to the buffer is full.
I added a "select" before "write". If it could not be written,
unix_write will Return immediately and it will not block the VMX
booting. With this fix, we can make VMX's serial enable by default.

Signed-off-by: Yu Ping <ping.y.yu@intel.com>

Modified to patch xmexample.hvm. Put through xenrt on a VMX box.

Signed-off-by: James Bulpin <james@xensource.com>
author jrb44@plym.cl.cam.ac.uk
date Thu Feb 02 19:15:22 2006 +0100 (2006-02-02)
parents f1b361b05bf3
children 40d7eef7d3f5
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 uint64_t 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 char domain_name[1024] = { 'H','V', 'M', 'X', 'E', 'N', '-'};
129 NetDriverState nd_table[MAX_NICS];
130 QEMUTimer *gui_timer;
131 QEMUTimer *polling_timer;
132 int vm_running;
133 int audio_enabled = 0;
134 int nic_ne2000 = 0;
135 int vcpus = 1;
136 int sb16_enabled = 1;
137 int adlib_enabled = 1;
138 int gus_enabled = 1;
139 int pci_enabled = 1;
140 int prep_enabled = 0;
141 int rtc_utc = 0;
142 int cirrus_vga_enabled = 1;
143 int vga_accelerate = 1;
144 int graphic_width = 800;
145 int graphic_height = 600;
146 int graphic_depth = 15;
147 int full_screen = 0;
148 int repeat_key = 1;
149 TextConsole *vga_console;
150 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
151 int xc_handle;
152 unsigned long *vgapage_array;
153 unsigned long *freepage_array;
154 unsigned long free_pages;
155 void *vtop_table;
156 unsigned long toptab;
157 unsigned long vgaram_pages;
159 /***********************************************************/
160 /* x86 ISA bus support */
162 target_phys_addr_t isa_mem_base = 0;
164 uint32_t default_ioport_readb(void *opaque, uint32_t address)
165 {
166 #ifdef DEBUG_UNUSED_IOPORT
167 fprintf(stderr, "inb: port=0x%04x\n", address);
168 #endif
169 return 0xff;
170 }
172 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
173 {
174 #ifdef DEBUG_UNUSED_IOPORT
175 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
176 #endif
177 }
179 /* default is to make two byte accesses */
180 uint32_t default_ioport_readw(void *opaque, uint32_t address)
181 {
182 uint32_t data;
183 data = ioport_read_table[0][address](ioport_opaque[address], address);
184 address = (address + 1) & (MAX_IOPORTS - 1);
185 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
186 return data;
187 }
189 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
190 {
191 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
192 address = (address + 1) & (MAX_IOPORTS - 1);
193 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
194 }
196 uint32_t default_ioport_readl(void *opaque, uint32_t address)
197 {
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr, "inl: port=0x%04x\n", address);
200 #endif
201 return 0xffffffff;
202 }
204 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
205 {
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
208 #endif
209 }
211 void init_ioports(void)
212 {
213 int i;
215 for(i = 0; i < MAX_IOPORTS; i++) {
216 ioport_read_table[0][i] = default_ioport_readb;
217 ioport_write_table[0][i] = default_ioport_writeb;
218 ioport_read_table[1][i] = default_ioport_readw;
219 ioport_write_table[1][i] = default_ioport_writew;
220 ioport_read_table[2][i] = default_ioport_readl;
221 ioport_write_table[2][i] = default_ioport_writel;
222 }
223 }
225 /* size is the word size in byte */
226 int register_ioport_read(int start, int length, int size,
227 IOPortReadFunc *func, void *opaque)
228 {
229 int i, bsize;
231 if (size == 1) {
232 bsize = 0;
233 } else if (size == 2) {
234 bsize = 1;
235 } else if (size == 4) {
236 bsize = 2;
237 } else {
238 hw_error("register_ioport_read: invalid size");
239 return -1;
240 }
241 for(i = start; i < start + length; i += size) {
242 ioport_read_table[bsize][i] = func;
243 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
244 hw_error("register_ioport_read: invalid opaque");
245 ioport_opaque[i] = opaque;
246 }
247 return 0;
248 }
250 /* size is the word size in byte */
251 int register_ioport_write(int start, int length, int size,
252 IOPortWriteFunc *func, void *opaque)
253 {
254 int i, bsize;
256 if (size == 1) {
257 bsize = 0;
258 } else if (size == 2) {
259 bsize = 1;
260 } else if (size == 4) {
261 bsize = 2;
262 } else {
263 hw_error("register_ioport_write: invalid size");
264 return -1;
265 }
266 for(i = start; i < start + length; i += size) {
267 ioport_write_table[bsize][i] = func;
268 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
269 hw_error("register_ioport_read: invalid opaque");
270 ioport_opaque[i] = opaque;
271 }
272 return 0;
273 }
275 void isa_unassign_ioport(int start, int length)
276 {
277 int i;
279 for(i = start; i < start + length; i++) {
280 ioport_read_table[0][i] = default_ioport_readb;
281 ioport_read_table[1][i] = default_ioport_readw;
282 ioport_read_table[2][i] = default_ioport_readl;
284 ioport_write_table[0][i] = default_ioport_writeb;
285 ioport_write_table[1][i] = default_ioport_writew;
286 ioport_write_table[2][i] = default_ioport_writel;
287 }
288 }
290 void pstrcpy(char *buf, int buf_size, const char *str)
291 {
292 int c;
293 char *q = buf;
295 if (buf_size <= 0)
296 return;
298 for(;;) {
299 c = *str++;
300 if (c == 0 || q >= buf + buf_size - 1)
301 break;
302 *q++ = c;
303 }
304 *q = '\0';
305 }
307 /* strcat and truncate. */
308 char *pstrcat(char *buf, int buf_size, const char *s)
309 {
310 int len;
311 len = strlen(buf);
312 if (len < buf_size)
313 pstrcpy(buf + len, buf_size - len, s);
314 return buf;
315 }
317 int strstart(const char *str, const char *val, const char **ptr)
318 {
319 const char *p, *q;
320 p = str;
321 q = val;
322 while (*q != '\0') {
323 if (*p != *q)
324 return 0;
325 p++;
326 q++;
327 }
328 if (ptr)
329 *ptr = p;
330 return 1;
331 }
333 /* return the size or -1 if error */
334 int get_image_size(const char *filename)
335 {
336 int fd, size;
337 fd = open(filename, O_RDONLY | O_BINARY);
338 if (fd < 0)
339 return -1;
340 size = lseek(fd, 0, SEEK_END);
341 close(fd);
342 return size;
343 }
345 /* return the size or -1 if error */
346 int load_image(const char *filename, uint8_t *addr)
347 {
348 int fd, size;
349 fd = open(filename, O_RDONLY | O_BINARY);
350 if (fd < 0)
351 return -1;
352 size = lseek(fd, 0, SEEK_END);
353 lseek(fd, 0, SEEK_SET);
354 if (read(fd, addr, size) != size) {
355 close(fd);
356 return -1;
357 }
358 close(fd);
359 return size;
360 }
362 void cpu_outb(CPUState *env, int addr, int val)
363 {
364 #ifdef DEBUG_IOPORT
365 if (loglevel & CPU_LOG_IOPORT)
366 fprintf(logfile, "outb: %04x %02x\n", addr, val);
367 #endif
368 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
369 }
371 void cpu_outw(CPUState *env, int addr, int val)
372 {
373 #ifdef DEBUG_IOPORT
374 if (loglevel & CPU_LOG_IOPORT)
375 fprintf(logfile, "outw: %04x %04x\n", addr, val);
376 #endif
377 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
378 }
380 void cpu_outl(CPUState *env, int addr, int val)
381 {
382 #ifdef DEBUG_IOPORT
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "outl: %04x %08x\n", addr, val);
385 #endif
386 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
387 }
389 int cpu_inb(CPUState *env, int addr)
390 {
391 int val;
392 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inb : %04x %02x\n", addr, val);
396 #endif
397 return val;
398 }
400 int cpu_inw(CPUState *env, int addr)
401 {
402 int val;
403 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
404 #ifdef DEBUG_IOPORT
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "inw : %04x %04x\n", addr, val);
407 #endif
408 return val;
409 }
411 int cpu_inl(CPUState *env, int addr)
412 {
413 int val;
414 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
415 #ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "inl : %04x %08x\n", addr, val);
418 #endif
419 return val;
420 }
422 /***********************************************************/
423 void hw_error(const char *fmt, ...)
424 {
425 va_list ap;
427 va_start(ap, fmt);
428 fprintf(stderr, "qemu: hardware error: ");
429 vfprintf(stderr, fmt, ap);
430 fprintf(stderr, "\n");
431 if (logfile) {
432 fprintf(logfile, "qemu: hardware error: ");
433 vfprintf(logfile, fmt, ap);
434 fprintf(logfile, "\n");
435 }
436 va_end(ap);
437 abort();
438 }
440 /***********************************************************/
441 /* keyboard/mouse */
443 static QEMUPutKBDEvent *qemu_put_kbd_event;
444 static void *qemu_put_kbd_event_opaque;
445 static QEMUPutMouseEvent *qemu_put_mouse_event;
446 static void *qemu_put_mouse_event_opaque;
448 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
449 {
450 qemu_put_kbd_event_opaque = opaque;
451 qemu_put_kbd_event = func;
452 }
454 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
455 {
456 qemu_put_mouse_event_opaque = opaque;
457 qemu_put_mouse_event = func;
458 }
460 void kbd_put_keycode(int keycode)
461 {
462 if (qemu_put_kbd_event) {
463 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
464 }
465 }
467 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
468 {
469 if (qemu_put_mouse_event) {
470 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
471 dx, dy, dz, buttons_state);
472 }
473 }
475 /***********************************************************/
476 /* timers */
478 #if defined(__powerpc__)
480 static inline uint32_t get_tbl(void)
481 {
482 uint32_t tbl;
483 asm volatile("mftb %0" : "=r" (tbl));
484 return tbl;
485 }
487 static inline uint32_t get_tbu(void)
488 {
489 uint32_t tbl;
490 asm volatile("mftbu %0" : "=r" (tbl));
491 return tbl;
492 }
494 int64_t cpu_get_real_ticks(void)
495 {
496 uint32_t l, h, h1;
497 /* NOTE: we test if wrapping has occurred */
498 do {
499 h = get_tbu();
500 l = get_tbl();
501 h1 = get_tbu();
502 } while (h != h1);
503 return ((int64_t)h << 32) | l;
504 }
506 #elif defined(__i386__)
508 int64_t cpu_get_real_ticks(void)
509 {
510 int64_t val;
511 asm volatile ("rdtsc" : "=A" (val));
512 return val;
513 }
515 #elif defined(__x86_64__)
517 int64_t cpu_get_real_ticks(void)
518 {
519 uint32_t low,high;
520 int64_t val;
521 asm volatile("rdtsc" : "=a" (low), "=d" (high));
522 val = high;
523 val <<= 32;
524 val |= low;
525 return val;
526 }
528 #elif defined(__ia64__)
529 #include "ia64_intrinsic.h"
530 #define cpu_get_real_ticks() \
531 __ia64_getreg(_IA64_REG_AR_ITC)
533 #else
534 #error unsupported CPU
535 #endif
537 static int64_t cpu_ticks_offset;
538 static int cpu_ticks_enabled;
539 int64_t cpu_virt_tsc;
541 static inline int64_t cpu_get_ticks(void)
542 {
543 if (!cpu_ticks_enabled) {
544 return cpu_ticks_offset;
545 } else {
546 return cpu_get_real_ticks() + cpu_ticks_offset;
547 }
549 }
551 /* enable cpu_get_ticks() */
552 void cpu_enable_ticks(void)
553 {
554 if (!cpu_ticks_enabled) {
555 cpu_ticks_offset -= cpu_get_real_ticks();
556 cpu_ticks_enabled = 1;
557 }
558 }
560 /* disable cpu_get_ticks() : the clock is stopped. You must not call
561 cpu_get_ticks() after that. */
562 void cpu_disable_ticks(void)
563 {
564 if (cpu_ticks_enabled) {
565 cpu_ticks_offset = cpu_get_ticks();
566 cpu_ticks_enabled = 0;
567 }
568 }
570 static int64_t get_clock(void)
571 {
572 #ifdef _WIN32
573 struct _timeb tb;
574 _ftime(&tb);
575 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
576 #else
577 struct timeval tv;
578 gettimeofday(&tv, NULL);
579 return tv.tv_sec * 1000000LL + tv.tv_usec;
580 #endif
581 }
583 void cpu_calibrate_ticks(void)
584 {
585 int64_t usec, ticks;
587 usec = get_clock();
588 ticks = cpu_get_real_ticks();
589 #ifdef _WIN32
590 Sleep(50);
591 #else
592 usleep(50 * 1000);
593 #endif
594 usec = get_clock() - usec;
595 ticks = cpu_get_real_ticks() - ticks;
596 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
597 }
599 /* compute with 96 bit intermediate result: (a*b)/c */
600 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
601 {
602 union {
603 uint64_t ll;
604 struct {
605 #ifdef WORDS_BIGENDIAN
606 uint32_t high, low;
607 #else
608 uint32_t low, high;
609 #endif
610 } l;
611 } u, res;
612 uint64_t rl, rh;
614 u.ll = a;
615 rl = (uint64_t)u.l.low * (uint64_t)b;
616 rh = (uint64_t)u.l.high * (uint64_t)b;
617 rh += (rl >> 32);
618 res.l.high = rh / c;
619 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
620 return res.ll;
621 }
623 #define QEMU_TIMER_REALTIME 0
624 #define QEMU_TIMER_VIRTUAL 1
626 struct QEMUClock {
627 int type;
628 /* XXX: add frequency */
629 };
631 struct QEMUTimer {
632 QEMUClock *clock;
633 int64_t expire_time;
634 QEMUTimerCB *cb;
635 void *opaque;
636 struct QEMUTimer *next;
637 };
639 QEMUClock *rt_clock;
640 QEMUClock *vm_clock;
642 static QEMUTimer *active_timers[2];
643 #ifdef _WIN32
644 static MMRESULT timerID;
645 #else
646 /* frequency of the times() clock tick */
647 static int timer_freq;
648 #endif
650 QEMUClock *qemu_new_clock(int type)
651 {
652 QEMUClock *clock;
653 clock = qemu_mallocz(sizeof(QEMUClock));
654 if (!clock)
655 return NULL;
656 clock->type = type;
657 return clock;
658 }
660 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
661 {
662 QEMUTimer *ts;
664 ts = qemu_mallocz(sizeof(QEMUTimer));
665 ts->clock = clock;
666 ts->cb = cb;
667 ts->opaque = opaque;
668 return ts;
669 }
671 void qemu_free_timer(QEMUTimer *ts)
672 {
673 qemu_free(ts);
674 }
676 /* stop a timer, but do not dealloc it */
677 void qemu_del_timer(QEMUTimer *ts)
678 {
679 QEMUTimer **pt, *t;
681 /* NOTE: this code must be signal safe because
682 qemu_timer_expired() can be called from a signal. */
683 pt = &active_timers[ts->clock->type];
684 for(;;) {
685 t = *pt;
686 if (!t)
687 break;
688 if (t == ts) {
689 *pt = t->next;
690 break;
691 }
692 pt = &t->next;
693 }
694 }
696 /* modify the current timer so that it will be fired when current_time
697 >= expire_time. The corresponding callback will be called. */
698 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
699 {
700 QEMUTimer **pt, *t;
702 qemu_del_timer(ts);
704 /* add the timer in the sorted list */
705 /* NOTE: this code must be signal safe because
706 qemu_timer_expired() can be called from a signal. */
707 pt = &active_timers[ts->clock->type];
708 for(;;) {
709 t = *pt;
710 if (!t)
711 break;
712 if (t->expire_time > expire_time)
713 break;
714 pt = &t->next;
715 }
716 ts->expire_time = expire_time;
717 ts->next = *pt;
718 *pt = ts;
719 }
721 int qemu_timer_pending(QEMUTimer *ts)
722 {
723 QEMUTimer *t;
724 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
725 if (t == ts)
726 return 1;
727 }
728 return 0;
729 }
731 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
732 {
733 if (!timer_head)
734 return 0;
735 return (timer_head->expire_time <= current_time);
736 }
738 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
739 {
740 QEMUTimer *ts;
742 for(;;) {
743 ts = *ptimer_head;
744 if (!ts || ts->expire_time > current_time)
745 break;
746 /* remove timer from the list before calling the callback */
747 *ptimer_head = ts->next;
748 ts->next = NULL;
750 /* run the callback (the timer list can be modified) */
751 ts->cb(ts->opaque);
752 }
753 }
755 int64_t qemu_get_clock(QEMUClock *clock)
756 {
757 switch(clock->type) {
758 case QEMU_TIMER_REALTIME:
759 #ifdef _WIN32
760 return GetTickCount();
761 #else
762 {
763 struct tms tp;
765 /* Note that using gettimeofday() is not a good solution
766 for timers because its value change when the date is
767 modified. */
768 if (timer_freq == 100) {
769 return times(&tp) * 10;
770 } else {
771 return ((int64_t)times(&tp) * 1000) / timer_freq;
772 }
773 }
774 #endif
775 default:
776 case QEMU_TIMER_VIRTUAL:
777 return cpu_get_ticks();
778 }
779 }
781 /* save a timer */
782 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
783 {
784 uint64_t expire_time;
786 if (qemu_timer_pending(ts)) {
787 expire_time = ts->expire_time;
788 } else {
789 expire_time = -1;
790 }
791 qemu_put_be64(f, expire_time);
792 }
794 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
795 {
796 uint64_t expire_time;
798 expire_time = qemu_get_be64(f);
799 if (expire_time != -1) {
800 qemu_mod_timer(ts, expire_time);
801 } else {
802 qemu_del_timer(ts);
803 }
804 }
806 static void init_timers(void)
807 {
808 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
809 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
811 #ifdef _WIN32
812 {
813 int count=0;
814 timerID = timeSetEvent(10, // interval (ms)
815 0, // resolution
816 host_alarm_handler, // function
817 (DWORD)&count, // user parameter
818 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
819 if( !timerID ) {
820 fprintf(logfile, "failed timer alarm");
821 exit(1);
822 }
823 }
824 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
825 #else
826 {
827 /* get times() syscall frequency */
828 timer_freq = sysconf(_SC_CLK_TCK);
830 #ifndef TARGET_HVM
831 /* timer signal */
832 sigfillset(&act.sa_mask);
833 act.sa_flags = 0;
834 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
835 act.sa_flags |= SA_ONSTACK;
836 #endif
837 act.sa_handler = host_alarm_handler;
838 sigaction(SIGALRM, &act, NULL);
840 itv.it_interval.tv_sec = 0;
841 itv.it_interval.tv_usec = 1000;
842 itv.it_value.tv_sec = 0;
843 itv.it_value.tv_usec = 10 * 1000;
844 setitimer(ITIMER_REAL, &itv, NULL);
845 /* we probe the tick duration of the kernel to inform the user if
846 the emulated kernel requested a too high timer frequency */
847 getitimer(ITIMER_REAL, &itv);
849 #if defined(__linux__)
850 if (itv.it_interval.tv_usec > 1000) {
851 /* try to use /dev/rtc to have a faster timer */
852 if (start_rtc_timer() < 0)
853 goto use_itimer;
854 /* disable itimer */
855 itv.it_interval.tv_sec = 0;
856 itv.it_interval.tv_usec = 0;
857 itv.it_value.tv_sec = 0;
858 itv.it_value.tv_usec = 0;
859 setitimer(ITIMER_REAL, &itv, NULL);
861 /* use the RTC */
862 sigaction(SIGIO, &act, NULL);
863 fcntl(rtc_fd, F_SETFL, O_ASYNC);
864 fcntl(rtc_fd, F_SETOWN, getpid());
865 } else
866 #endif /* defined(__linux__) */
867 {
868 use_itimer:
869 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
870 PIT_FREQ) / 1000000;
871 }
872 #endif /* TARGET_HVM */
873 }
874 #endif
875 }
877 void quit_timers(void)
878 {
879 #ifdef _WIN32
880 timeKillEvent(timerID);
881 #endif
882 }
884 /***********************************************************/
885 /* character device */
887 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
888 {
889 return s->chr_write(s, buf, len);
890 }
892 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
893 {
894 char buf[4096];
895 va_list ap;
896 va_start(ap, fmt);
897 vsnprintf(buf, sizeof(buf), fmt, ap);
898 qemu_chr_write(s, buf, strlen(buf));
899 va_end(ap);
900 }
902 void qemu_chr_send_event(CharDriverState *s, int event)
903 {
904 if (s->chr_send_event)
905 s->chr_send_event(s, event);
906 }
908 void qemu_chr_add_read_handler(CharDriverState *s,
909 IOCanRWHandler *fd_can_read,
910 IOReadHandler *fd_read, void *opaque)
911 {
912 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
913 }
915 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
916 {
917 s->chr_event = chr_event;
918 }
920 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
921 {
922 return len;
923 }
925 static void null_chr_add_read_handler(CharDriverState *chr,
926 IOCanRWHandler *fd_can_read,
927 IOReadHandler *fd_read, void *opaque)
928 {
929 }
931 CharDriverState *qemu_chr_open_null(void)
932 {
933 CharDriverState *chr;
935 chr = qemu_mallocz(sizeof(CharDriverState));
936 if (!chr)
937 return NULL;
938 chr->chr_write = null_chr_write;
939 chr->chr_add_read_handler = null_chr_add_read_handler;
940 return chr;
941 }
943 #ifndef _WIN32
945 typedef struct {
946 int fd_in, fd_out;
947 /* for nographic stdio only */
948 IOCanRWHandler *fd_can_read;
949 IOReadHandler *fd_read;
950 void *fd_opaque;
951 } FDCharDriver;
953 #define STDIO_MAX_CLIENTS 2
955 static int stdio_nb_clients;
956 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
958 static int unix_write(int fd, const uint8_t *buf, int len1)
959 {
960 int ret,sel_ret,len;
961 int max_fd;
962 fd_set writefds;
963 struct timeval timeout;
965 max_fd = fd;
967 len = len1;
968 while (len > 0) {
969 FD_ZERO(&writefds);
970 FD_SET(fd, &writefds);
971 timeout.tv_sec = 0;
972 timeout.tv_usec = 0;
973 sel_ret = select(max_fd + 1, NULL, &writefds, 0, &timeout);
974 if (sel_ret <= 0) {
975 /* Timeout or select error */
976 return -1;
977 } else {
978 ret = write(fd, buf, len);
979 if (ret < 0) {
980 if (errno != EINTR && errno != EAGAIN)
981 return -1;
982 } else if (ret == 0) {
983 break;
984 } else {
985 buf += ret;
986 len -= ret;
987 }
988 }
989 }
990 return len1 - len;
991 }
993 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
994 {
995 FDCharDriver *s = chr->opaque;
996 return unix_write(s->fd_out, buf, len);
997 }
999 static void fd_chr_add_read_handler(CharDriverState *chr,
1000 IOCanRWHandler *fd_can_read,
1001 IOReadHandler *fd_read, void *opaque)
1003 FDCharDriver *s = chr->opaque;
1005 if (nographic && s->fd_in == 0) {
1006 s->fd_can_read = fd_can_read;
1007 s->fd_read = fd_read;
1008 s->fd_opaque = opaque;
1009 } else {
1010 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1014 /* open a character device to a unix fd */
1015 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1017 CharDriverState *chr;
1018 FDCharDriver *s;
1020 chr = qemu_mallocz(sizeof(CharDriverState));
1021 if (!chr)
1022 return NULL;
1023 s = qemu_mallocz(sizeof(FDCharDriver));
1024 if (!s) {
1025 free(chr);
1026 return NULL;
1028 s->fd_in = fd_in;
1029 s->fd_out = fd_out;
1030 chr->opaque = s;
1031 chr->chr_write = fd_chr_write;
1032 chr->chr_add_read_handler = fd_chr_add_read_handler;
1033 return chr;
1036 /* for STDIO, we handle the case where several clients use it
1037 (nographic mode) */
1039 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1041 static int term_got_escape, client_index;
1043 void term_print_help(void)
1045 printf("\n"
1046 "C-a h print this help\n"
1047 "C-a x exit emulator\n"
1048 "C-a s save disk data back to file (if -snapshot)\n"
1049 "C-a b send break (magic sysrq)\n"
1050 "C-a c switch between console and monitor\n"
1051 "C-a C-a send C-a\n"
1052 );
1055 /* called when a char is received */
1056 static void stdio_received_byte(int ch)
1058 if (term_got_escape) {
1059 term_got_escape = 0;
1060 switch(ch) {
1061 case 'h':
1062 term_print_help();
1063 break;
1064 case 'x':
1065 exit(0);
1066 break;
1067 case 's':
1069 int i;
1070 for (i = 0; i < MAX_DISKS; i++) {
1071 if (bs_table[i])
1072 bdrv_commit(bs_table[i]);
1075 break;
1076 case 'b':
1077 if (client_index < stdio_nb_clients) {
1078 CharDriverState *chr;
1079 FDCharDriver *s;
1081 chr = stdio_clients[client_index];
1082 s = chr->opaque;
1083 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1085 break;
1086 case 'c':
1087 client_index++;
1088 if (client_index >= stdio_nb_clients)
1089 client_index = 0;
1090 if (client_index == 0) {
1091 /* send a new line in the monitor to get the prompt */
1092 ch = '\r';
1093 goto send_char;
1095 break;
1096 case TERM_ESCAPE:
1097 goto send_char;
1099 } else if (ch == TERM_ESCAPE) {
1100 term_got_escape = 1;
1101 } else {
1102 send_char:
1103 if (client_index < stdio_nb_clients) {
1104 uint8_t buf[1];
1105 CharDriverState *chr;
1106 FDCharDriver *s;
1108 chr = stdio_clients[client_index];
1109 s = chr->opaque;
1110 buf[0] = ch;
1111 /* XXX: should queue the char if the device is not
1112 ready */
1113 if (s->fd_can_read(s->fd_opaque) > 0)
1114 s->fd_read(s->fd_opaque, buf, 1);
1119 static int stdio_can_read(void *opaque)
1121 /* XXX: not strictly correct */
1122 return 1;
1125 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1127 int i;
1128 for(i = 0; i < size; i++)
1129 stdio_received_byte(buf[i]);
1132 /* init terminal so that we can grab keys */
1133 static struct termios oldtty;
1134 static int old_fd0_flags;
1136 static void term_exit(void)
1138 tcsetattr (0, TCSANOW, &oldtty);
1139 fcntl(0, F_SETFL, old_fd0_flags);
1142 static void term_init(void)
1144 struct termios tty;
1146 tcgetattr (0, &tty);
1147 oldtty = tty;
1148 old_fd0_flags = fcntl(0, F_GETFL);
1150 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1151 |INLCR|IGNCR|ICRNL|IXON);
1152 tty.c_oflag |= OPOST;
1153 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1154 /* if graphical mode, we allow Ctrl-C handling */
1155 if (nographic)
1156 tty.c_lflag &= ~ISIG;
1157 tty.c_cflag &= ~(CSIZE|PARENB);
1158 tty.c_cflag |= CS8;
1159 tty.c_cc[VMIN] = 1;
1160 tty.c_cc[VTIME] = 0;
1162 tcsetattr (0, TCSANOW, &tty);
1164 atexit(term_exit);
1166 fcntl(0, F_SETFL, O_NONBLOCK);
1169 CharDriverState *qemu_chr_open_stdio(void)
1171 CharDriverState *chr;
1173 if (nographic) {
1174 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1175 return NULL;
1176 chr = qemu_chr_open_fd(0, 1);
1177 if (stdio_nb_clients == 0)
1178 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1179 client_index = stdio_nb_clients;
1180 } else {
1181 if (stdio_nb_clients != 0)
1182 return NULL;
1183 chr = qemu_chr_open_fd(0, 1);
1185 stdio_clients[stdio_nb_clients++] = chr;
1186 if (stdio_nb_clients == 1) {
1187 /* set the terminal in raw mode */
1188 term_init();
1190 return chr;
1193 int store_console_dev(int domid, char *pts)
1195 int xc_handle;
1196 struct xs_handle *xs;
1197 char *path;
1199 xs = xs_daemon_open();
1200 if (xs == NULL) {
1201 fprintf(logfile, "Could not contact XenStore\n");
1202 return -1;
1205 xc_handle = xc_interface_open();
1206 if (xc_handle == -1) {
1207 fprintf(logfile, "xc_interface_open() error\n");
1208 return -1;
1211 path = xs_get_domain_path(xs, domid);
1212 if (path == NULL) {
1213 fprintf(logfile, "xs_get_domain_path() error\n");
1214 return -1;
1216 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1217 if (path == NULL) {
1218 fprintf(logfile, "realloc error\n");
1219 return -1;
1221 strcat(path, "/console/tty");
1222 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1223 fprintf(logfile, "xs_write for console fail");
1224 return -1;
1227 free(path);
1228 xs_daemon_close(xs);
1229 close(xc_handle);
1231 return 0;
1234 #if defined(__linux__)
1235 CharDriverState *qemu_chr_open_pty(void)
1237 int master_fd, slave_fd;
1238 struct termios term;
1240 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0)
1241 return NULL;
1243 /* Set raw attributes on the pty. */
1244 cfmakeraw(&term);
1245 tcsetattr(slave_fd, TCSAFLUSH, &term);
1247 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1248 store_console_dev(domid, ptsname(master_fd));
1250 return qemu_chr_open_fd(master_fd, master_fd);
1252 #else
1253 CharDriverState *qemu_chr_open_pty(void)
1255 return NULL;
1257 #endif
1259 #endif /* !defined(_WIN32) */
1261 CharDriverState *qemu_chr_open(const char *filename)
1263 if (!strcmp(filename, "vc")) {
1264 return text_console_init(&display_state);
1265 } else if (!strcmp(filename, "null")) {
1266 return qemu_chr_open_null();
1267 } else
1268 #ifndef _WIN32
1269 if (!strcmp(filename, "pty")) {
1270 return qemu_chr_open_pty();
1271 } else if (!strcmp(filename, "stdio")) {
1272 return qemu_chr_open_stdio();
1273 } else
1274 #endif
1276 return NULL;
1280 /***********************************************************/
1281 /* Linux network device redirectors */
1283 void hex_dump(FILE *f, const uint8_t *buf, int size)
1285 int len, i, j, c;
1287 for(i=0;i<size;i+=16) {
1288 len = size - i;
1289 if (len > 16)
1290 len = 16;
1291 fprintf(f, "%08x ", i);
1292 for(j=0;j<16;j++) {
1293 if (j < len)
1294 fprintf(f, " %02x", buf[i+j]);
1295 else
1296 fprintf(f, " ");
1298 fprintf(f, " ");
1299 for(j=0;j<len;j++) {
1300 c = buf[i+j];
1301 if (c < ' ' || c > '~')
1302 c = '.';
1303 fprintf(f, "%c", c);
1305 fprintf(f, "\n");
1309 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1311 nd->send_packet(nd, buf, size);
1314 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1315 IOReadHandler *fd_read, void *opaque)
1317 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1320 /* dummy network adapter */
1322 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1326 static void dummy_add_read_packet(NetDriverState *nd,
1327 IOCanRWHandler *fd_can_read,
1328 IOReadHandler *fd_read, void *opaque)
1332 static int net_dummy_init(NetDriverState *nd)
1334 nd->send_packet = dummy_send_packet;
1335 nd->add_read_packet = dummy_add_read_packet;
1336 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1337 return 0;
1340 #if defined(CONFIG_SLIRP)
1342 /* slirp network adapter */
1344 static void *slirp_fd_opaque;
1345 static IOCanRWHandler *slirp_fd_can_read;
1346 static IOReadHandler *slirp_fd_read;
1347 static int slirp_inited;
1349 int slirp_can_output(void)
1351 return slirp_fd_can_read(slirp_fd_opaque);
1354 void slirp_output(const uint8_t *pkt, int pkt_len)
1356 #if 0
1357 printf("output:\n");
1358 hex_dump(stdout, pkt, pkt_len);
1359 #endif
1360 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1363 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1365 #if 0
1366 printf("input:\n");
1367 hex_dump(stdout, buf, size);
1368 #endif
1369 slirp_input(buf, size);
1372 static void slirp_add_read_packet(NetDriverState *nd,
1373 IOCanRWHandler *fd_can_read,
1374 IOReadHandler *fd_read, void *opaque)
1376 slirp_fd_opaque = opaque;
1377 slirp_fd_can_read = fd_can_read;
1378 slirp_fd_read = fd_read;
1381 static int net_slirp_init(NetDriverState *nd)
1383 if (!slirp_inited) {
1384 slirp_inited = 1;
1385 slirp_init();
1387 nd->send_packet = slirp_send_packet;
1388 nd->add_read_packet = slirp_add_read_packet;
1389 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1390 return 0;
1393 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1395 const char *p, *p1;
1396 int len;
1397 p = *pp;
1398 p1 = strchr(p, sep);
1399 if (!p1)
1400 return -1;
1401 len = p1 - p;
1402 p1++;
1403 if (buf_size > 0) {
1404 if (len > buf_size - 1)
1405 len = buf_size - 1;
1406 memcpy(buf, p, len);
1407 buf[len] = '\0';
1409 *pp = p1;
1410 return 0;
1413 static void net_slirp_redir(const char *redir_str)
1415 int is_udp;
1416 char buf[256], *r;
1417 const char *p;
1418 struct in_addr guest_addr;
1419 int host_port, guest_port;
1421 if (!slirp_inited) {
1422 slirp_inited = 1;
1423 slirp_init();
1426 p = redir_str;
1427 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1428 goto fail;
1429 if (!strcmp(buf, "tcp")) {
1430 is_udp = 0;
1431 } else if (!strcmp(buf, "udp")) {
1432 is_udp = 1;
1433 } else {
1434 goto fail;
1437 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1438 goto fail;
1439 host_port = strtol(buf, &r, 0);
1440 if (r == buf)
1441 goto fail;
1443 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1444 goto fail;
1445 if (buf[0] == '\0') {
1446 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1448 if (!inet_aton(buf, &guest_addr))
1449 goto fail;
1451 guest_port = strtol(p, &r, 0);
1452 if (r == p)
1453 goto fail;
1455 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1456 fprintf(stderr, "qemu: could not set up redirection\n");
1457 exit(1);
1459 return;
1460 fail:
1461 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1462 exit(1);
1465 #ifndef _WIN32
1467 char smb_dir[1024];
1469 static void smb_exit(void)
1471 DIR *d;
1472 struct dirent *de;
1473 char filename[1024];
1475 /* erase all the files in the directory */
1476 d = opendir(smb_dir);
1477 for(;;) {
1478 de = readdir(d);
1479 if (!de)
1480 break;
1481 if (strcmp(de->d_name, ".") != 0 &&
1482 strcmp(de->d_name, "..") != 0) {
1483 snprintf(filename, sizeof(filename), "%s/%s",
1484 smb_dir, de->d_name);
1485 unlink(filename);
1488 closedir(d);
1489 rmdir(smb_dir);
1492 /* automatic user mode samba server configuration */
1493 void net_slirp_smb(const char *exported_dir)
1495 char smb_conf[1024];
1496 char smb_cmdline[1024];
1497 FILE *f;
1499 if (!slirp_inited) {
1500 slirp_inited = 1;
1501 slirp_init();
1504 /* XXX: better tmp dir construction */
1505 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1506 if (mkdir(smb_dir, 0700) < 0) {
1507 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1508 exit(1);
1510 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1512 f = fopen(smb_conf, "w");
1513 if (!f) {
1514 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1515 exit(1);
1517 fprintf(f,
1518 "[global]\n"
1519 "pid directory=%s\n"
1520 "lock directory=%s\n"
1521 "log file=%s/log.smbd\n"
1522 "smb passwd file=%s/smbpasswd\n"
1523 "security = share\n"
1524 "[qemu]\n"
1525 "path=%s\n"
1526 "read only=no\n"
1527 "guest ok=yes\n",
1528 smb_dir,
1529 smb_dir,
1530 smb_dir,
1531 smb_dir,
1532 exported_dir
1533 );
1534 fclose(f);
1535 atexit(smb_exit);
1537 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1538 smb_conf);
1540 slirp_add_exec(0, smb_cmdline, 4, 139);
1543 #endif /* !defined(_WIN32) */
1545 #endif /* CONFIG_SLIRP */
1547 #if !defined(_WIN32)
1548 #ifdef _BSD
1549 static int tun_open(char *ifname, int ifname_size)
1551 int fd;
1552 char *dev;
1553 struct stat s;
1555 fd = open("/dev/tap", O_RDWR);
1556 if (fd < 0) {
1557 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1558 return -1;
1561 fstat(fd, &s);
1562 dev = devname(s.st_rdev, S_IFCHR);
1563 pstrcpy(ifname, ifname_size, dev);
1565 fcntl(fd, F_SETFL, O_NONBLOCK);
1566 return fd;
1568 #else
1569 static int tun_open(char *ifname, int ifname_size)
1571 struct ifreq ifr;
1572 int fd, ret;
1574 fd = open("/dev/net/tun", O_RDWR);
1575 if (fd < 0) {
1576 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1577 return -1;
1579 memset(&ifr, 0, sizeof(ifr));
1580 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1581 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1582 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1583 if (ret != 0) {
1584 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1585 close(fd);
1586 return -1;
1588 fprintf(logfile, "Connected to host network interface: %s\n", ifr.ifr_name);
1589 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1590 fcntl(fd, F_SETFL, O_NONBLOCK);
1591 return fd;
1593 #endif
1595 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1597 write(nd->fd, buf, size);
1600 static void tun_add_read_packet(NetDriverState *nd,
1601 IOCanRWHandler *fd_can_read,
1602 IOReadHandler *fd_read, void *opaque)
1604 qemu_add_fd_event_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1607 static int net_tun_init(NetDriverState *nd)
1609 int pid, status;
1610 char *args[4];
1611 char **parg;
1612 extern int highest_fds;
1614 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1615 if (nd->fd < 0)
1616 return -1;
1618 if ( nd->fd > highest_fds ) highest_fds = nd->fd;
1619 /* try to launch network init script */
1620 pid = fork();
1621 if (pid >= 0) {
1622 if (pid == 0) {
1623 parg = args;
1624 *parg++ = network_script;
1625 *parg++ = nd->ifname;
1626 *parg++ = bridge;
1627 *parg++ = NULL;
1628 execv(network_script, args);
1629 exit(1);
1631 while (waitpid(pid, &status, 0) != pid);
1632 if (!WIFEXITED(status) ||
1633 WEXITSTATUS(status) != 0) {
1634 fprintf(stderr, "%s: could not launch network script\n",
1635 network_script);
1638 nd->send_packet = tun_send_packet;
1639 nd->add_read_packet = tun_add_read_packet;
1640 return 0;
1643 static int net_fd_init(NetDriverState *nd, int fd)
1645 nd->fd = fd;
1646 nd->send_packet = tun_send_packet;
1647 nd->add_read_packet = tun_add_read_packet;
1648 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1649 return 0;
1652 #endif /* !_WIN32 */
1654 /***********************************************************/
1655 /* dumb display */
1657 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1661 static void dumb_resize(DisplayState *ds, int w, int h)
1665 static void dumb_refresh(DisplayState *ds)
1667 vga_update_display();
1670 void dumb_display_init(DisplayState *ds)
1672 ds->data = NULL;
1673 ds->linesize = 0;
1674 ds->depth = 0;
1675 ds->dpy_update = dumb_update;
1676 ds->dpy_resize = dumb_resize;
1677 ds->dpy_refresh = dumb_refresh;
1680 #if !defined(CONFIG_SOFTMMU)
1681 /***********************************************************/
1682 /* cpu signal handler */
1683 static void host_segv_handler(int host_signum, siginfo_t *info,
1684 void *puc)
1686 abort();
1688 #endif
1690 /***********************************************************/
1691 /* I/O handling */
1693 #define MAX_IO_HANDLERS 64
1695 typedef struct IOHandlerRecord {
1696 int fd;
1697 IOCanRWHandler *fd_can_read;
1698 IOReadHandler *fd_read;
1699 void *opaque;
1700 /* temporary data */
1701 struct pollfd *ufd;
1702 int max_size;
1703 struct IOHandlerRecord *next;
1704 } IOHandlerRecord;
1706 static IOHandlerRecord *first_io_handler;
1707 static IOHandlerRecord *first_eventio_handler;
1709 int qemu_add_fd_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_io_handler;
1722 first_io_handler = ioh;
1723 return 0;
1726 int qemu_add_fd_event_read_handler(int fd, IOCanRWHandler *fd_can_read,
1727 IOReadHandler *fd_read, void *opaque)
1729 IOHandlerRecord *ioh;
1731 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1732 if (!ioh)
1733 return -1;
1734 ioh->fd = fd;
1735 ioh->fd_can_read = fd_can_read;
1736 ioh->fd_read = fd_read;
1737 ioh->opaque = opaque;
1738 ioh->next = first_eventio_handler;
1739 first_eventio_handler = ioh;
1740 return 0;
1743 void qemu_del_fd_read_handler(int fd)
1745 IOHandlerRecord **pioh, *ioh;
1747 pioh = &first_io_handler;
1748 for(;;) {
1749 ioh = *pioh;
1750 if (ioh == NULL)
1751 break;
1752 if (ioh->fd == fd) {
1753 *pioh = ioh->next;
1754 break;
1756 pioh = &ioh->next;
1760 /***********************************************************/
1761 /* savevm/loadvm support */
1763 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1765 fwrite(buf, 1, size, f);
1768 void qemu_put_byte(QEMUFile *f, int v)
1770 fputc(v, f);
1773 void qemu_put_be16(QEMUFile *f, unsigned int v)
1775 qemu_put_byte(f, v >> 8);
1776 qemu_put_byte(f, v);
1779 void qemu_put_be32(QEMUFile *f, unsigned int v)
1781 qemu_put_byte(f, v >> 24);
1782 qemu_put_byte(f, v >> 16);
1783 qemu_put_byte(f, v >> 8);
1784 qemu_put_byte(f, v);
1787 void qemu_put_be64(QEMUFile *f, uint64_t v)
1789 qemu_put_be32(f, v >> 32);
1790 qemu_put_be32(f, v);
1793 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1795 return fread(buf, 1, size, f);
1798 int qemu_get_byte(QEMUFile *f)
1800 int v;
1801 v = fgetc(f);
1802 if (v == EOF)
1803 return 0;
1804 else
1805 return v;
1808 unsigned int qemu_get_be16(QEMUFile *f)
1810 unsigned int v;
1811 v = qemu_get_byte(f) << 8;
1812 v |= qemu_get_byte(f);
1813 return v;
1816 unsigned int qemu_get_be32(QEMUFile *f)
1818 unsigned int v;
1819 v = qemu_get_byte(f) << 24;
1820 v |= qemu_get_byte(f) << 16;
1821 v |= qemu_get_byte(f) << 8;
1822 v |= qemu_get_byte(f);
1823 return v;
1826 uint64_t qemu_get_be64(QEMUFile *f)
1828 uint64_t v;
1829 v = (uint64_t)qemu_get_be32(f) << 32;
1830 v |= qemu_get_be32(f);
1831 return v;
1834 int64_t qemu_ftell(QEMUFile *f)
1836 return ftell(f);
1839 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1841 if (fseek(f, pos, whence) < 0)
1842 return -1;
1843 return ftell(f);
1846 typedef struct SaveStateEntry {
1847 char idstr[256];
1848 int instance_id;
1849 int version_id;
1850 SaveStateHandler *save_state;
1851 LoadStateHandler *load_state;
1852 void *opaque;
1853 struct SaveStateEntry *next;
1854 } SaveStateEntry;
1856 static SaveStateEntry *first_se;
1858 int register_savevm(const char *idstr,
1859 int instance_id,
1860 int version_id,
1861 SaveStateHandler *save_state,
1862 LoadStateHandler *load_state,
1863 void *opaque)
1865 SaveStateEntry *se, **pse;
1867 se = qemu_malloc(sizeof(SaveStateEntry));
1868 if (!se)
1869 return -1;
1870 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1871 se->instance_id = instance_id;
1872 se->version_id = version_id;
1873 se->save_state = save_state;
1874 se->load_state = load_state;
1875 se->opaque = opaque;
1876 se->next = NULL;
1878 /* add at the end of list */
1879 pse = &first_se;
1880 while (*pse != NULL)
1881 pse = &(*pse)->next;
1882 *pse = se;
1883 return 0;
1886 #define QEMU_VM_FILE_MAGIC 0x5145564d
1887 #define QEMU_VM_FILE_VERSION 0x00000001
1889 int qemu_savevm(const char *filename)
1891 SaveStateEntry *se;
1892 QEMUFile *f;
1893 int len, len_pos, cur_pos, saved_vm_running, ret;
1895 saved_vm_running = vm_running;
1896 vm_stop(0);
1898 f = fopen(filename, "wb");
1899 if (!f) {
1900 ret = -1;
1901 goto the_end;
1904 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1905 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1907 for(se = first_se; se != NULL; se = se->next) {
1908 /* ID string */
1909 len = strlen(se->idstr);
1910 qemu_put_byte(f, len);
1911 qemu_put_buffer(f, se->idstr, len);
1913 qemu_put_be32(f, se->instance_id);
1914 qemu_put_be32(f, se->version_id);
1916 /* record size: filled later */
1917 len_pos = ftell(f);
1918 qemu_put_be32(f, 0);
1920 se->save_state(f, se->opaque);
1922 /* fill record size */
1923 cur_pos = ftell(f);
1924 len = ftell(f) - len_pos - 4;
1925 fseek(f, len_pos, SEEK_SET);
1926 qemu_put_be32(f, len);
1927 fseek(f, cur_pos, SEEK_SET);
1930 fclose(f);
1931 ret = 0;
1932 the_end:
1933 if (saved_vm_running)
1934 vm_start();
1935 return ret;
1938 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1940 SaveStateEntry *se;
1942 for(se = first_se; se != NULL; se = se->next) {
1943 if (!strcmp(se->idstr, idstr) &&
1944 instance_id == se->instance_id)
1945 return se;
1947 return NULL;
1950 int qemu_loadvm(const char *filename)
1952 SaveStateEntry *se;
1953 QEMUFile *f;
1954 int len, cur_pos, ret, instance_id, record_len, version_id;
1955 int saved_vm_running;
1956 unsigned int v;
1957 char idstr[256];
1959 saved_vm_running = vm_running;
1960 vm_stop(0);
1962 f = fopen(filename, "rb");
1963 if (!f) {
1964 ret = -1;
1965 goto the_end;
1968 v = qemu_get_be32(f);
1969 if (v != QEMU_VM_FILE_MAGIC)
1970 goto fail;
1971 v = qemu_get_be32(f);
1972 if (v != QEMU_VM_FILE_VERSION) {
1973 fail:
1974 fclose(f);
1975 ret = -1;
1976 goto the_end;
1978 for(;;) {
1979 #if defined (DO_TB_FLUSH)
1980 tb_flush(global_env);
1981 #endif
1982 len = qemu_get_byte(f);
1983 if (feof(f))
1984 break;
1985 qemu_get_buffer(f, idstr, len);
1986 idstr[len] = '\0';
1987 instance_id = qemu_get_be32(f);
1988 version_id = qemu_get_be32(f);
1989 record_len = qemu_get_be32(f);
1990 #if 0
1991 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1992 idstr, instance_id, version_id, record_len);
1993 #endif
1994 cur_pos = ftell(f);
1995 se = find_se(idstr, instance_id);
1996 if (!se) {
1997 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1998 instance_id, idstr);
1999 } else {
2000 ret = se->load_state(f, se->opaque, version_id);
2001 if (ret < 0) {
2002 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2003 instance_id, idstr);
2006 /* always seek to exact end of record */
2007 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2009 fclose(f);
2010 ret = 0;
2011 the_end:
2012 if (saved_vm_running)
2013 vm_start();
2014 return ret;
2017 /***********************************************************/
2018 /* main execution loop */
2020 void gui_update(void *opaque)
2022 display_state.dpy_refresh(&display_state);
2023 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2025 void polling_handler(void *opaque)
2027 #ifndef _WIN32
2028 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2029 IOHandlerRecord *ioh, *ioh_next;
2030 uint8_t buf[4096];
2031 int n, max_size;
2032 #endif
2033 int timeout = 0;
2034 int ret;
2036 #ifdef _WIN32
2037 if (timeout > 0)
2038 Sleep(timeout);
2039 #else
2040 /* poll any events */
2041 /* XXX: separate device handlers from system ones */
2042 pf = ufds;
2043 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2044 if (!ioh->fd_can_read) {
2045 max_size = 0;
2046 pf->fd = ioh->fd;
2047 pf->events = POLLIN;
2048 ioh->ufd = pf;
2049 pf++;
2050 } else {
2051 max_size = ioh->fd_can_read(ioh->opaque);
2052 if (max_size > 0) {
2053 if (max_size > sizeof(buf))
2054 max_size = sizeof(buf);
2055 pf->fd = ioh->fd;
2056 pf->events = POLLIN;
2057 ioh->ufd = pf;
2058 pf++;
2059 } else {
2060 ioh->ufd = NULL;
2063 ioh->max_size = max_size;
2066 ret = poll(ufds, pf - ufds, timeout);
2067 if (ret > 0) {
2068 /* XXX: better handling of removal */
2069 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2070 ioh_next = ioh->next;
2071 pf = ioh->ufd;
2072 if (pf) {
2073 if (pf->revents & POLLIN) {
2074 if (ioh->max_size == 0) {
2075 /* just a read event */
2076 ioh->fd_read(ioh->opaque, NULL, 0);
2077 } else {
2078 n = read(ioh->fd, buf, ioh->max_size);
2079 if (n >= 0) {
2080 ioh->fd_read(ioh->opaque, buf, n);
2081 } else if (errno != EAGAIN) {
2082 ioh->fd_read(ioh->opaque, NULL, -errno);
2089 #endif /* !defined(_WIN32) */
2091 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
2095 /* XXX: support several handlers */
2096 VMStopHandler *vm_stop_cb;
2097 VMStopHandler *vm_stop_opaque;
2099 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2101 vm_stop_cb = cb;
2102 vm_stop_opaque = opaque;
2103 return 0;
2106 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2108 vm_stop_cb = NULL;
2111 void vm_start(void)
2113 if (!vm_running) {
2114 cpu_enable_ticks();
2115 vm_running = 1;
2119 void vm_stop(int reason)
2121 if (vm_running) {
2122 cpu_disable_ticks();
2123 vm_running = 0;
2124 if (reason != 0) {
2125 if (vm_stop_cb) {
2126 vm_stop_cb(vm_stop_opaque, reason);
2132 /* reset/shutdown handler */
2134 typedef struct QEMUResetEntry {
2135 QEMUResetHandler *func;
2136 void *opaque;
2137 struct QEMUResetEntry *next;
2138 } QEMUResetEntry;
2140 static QEMUResetEntry *first_reset_entry;
2141 int reset_requested;
2142 int shutdown_requested;
2144 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2146 QEMUResetEntry **pre, *re;
2148 pre = &first_reset_entry;
2149 while (*pre != NULL)
2150 pre = &(*pre)->next;
2151 re = qemu_mallocz(sizeof(QEMUResetEntry));
2152 re->func = func;
2153 re->opaque = opaque;
2154 re->next = NULL;
2155 *pre = re;
2158 void qemu_system_reset(void)
2160 QEMUResetEntry *re;
2162 /* reset all devices */
2163 for(re = first_reset_entry; re != NULL; re = re->next) {
2164 re->func(re->opaque);
2168 void qemu_system_reset_request(void)
2170 reset_requested = 1;
2171 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2174 void qemu_system_shutdown_request(void)
2176 shutdown_requested = 1;
2177 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2180 void main_loop_wait(int timeout)
2182 if (vm_running) {
2183 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2184 qemu_get_clock(vm_clock));
2185 /* run dma transfers, if any */
2186 DMA_run();
2189 /* real time timers */
2190 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2191 qemu_get_clock(rt_clock));
2194 void help(void)
2196 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2197 "usage: %s [options] [disk_image]\n"
2198 "\n"
2199 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2200 "\n"
2201 "Standard options:\n"
2202 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2203 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2204 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2205 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2206 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2207 "-snapshot write to temporary files instead of disk image files\n"
2208 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2209 "-nographic disable graphical output and redirect serial I/Os to console\n"
2210 "-vcpus set CPU number of guest platform\n"
2211 #ifdef CONFIG_VNC
2212 "-vnc port use vnc instead of sdl\n"
2213 "-vncport port use a different port\n"
2214 "-vncconnect host:port do a reverse connect\n"
2215 #ifdef CONFIG_SDL
2216 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2217 #endif
2218 #endif
2219 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2220 "-enable-audio enable audio support\n"
2221 "-localtime set the real time clock to local time [default=utc]\n"
2222 "-full-screen start in full screen\n"
2223 #ifdef TARGET_PPC
2224 "-prep Simulate a PREP system (default is PowerMAC)\n"
2225 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2226 #endif
2227 "-nic-ne2000 simulate an Realtek ne2k PCI ethernet adaptor\n"
2228 "\n"
2229 "Network options:\n"
2230 "-nics n simulate 'n' network cards [default=1]\n"
2231 "-macaddr addr set the mac address of the first interface\n"
2232 "-bridge br set the bridge interface for nic\n"
2233 "-n script set tap/tun network init script [default=%s]\n"
2234 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2235 #ifdef CONFIG_SLIRP
2236 "-user-net use user mode network stack [default if no tap/tun script]\n"
2237 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2238 #ifndef _WIN32
2239 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2240 #endif
2241 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2242 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2243 #endif
2244 "-dummy-net use dummy network stack\n"
2245 "\n"
2246 "Linux boot specific:\n"
2247 "-kernel bzImage use 'bzImage' as kernel image\n"
2248 "-append cmdline use 'cmdline' as kernel command line\n"
2249 "-initrd file use 'file' as initial ram disk\n"
2250 "\n"
2251 "Debug/Expert options:\n"
2252 "-monitor dev redirect the monitor to char device 'dev'\n"
2253 "-serial dev redirect the serial port to char device 'dev'\n"
2254 "-S freeze CPU at startup (use 'c' to start execution)\n"
2255 "-s wait gdb connection to port %d\n"
2256 "-p port ioreq port for xen\n"
2257 "-d domain domain that we're serving\n"
2258 "-domain-namn domain name that we're serving\n"
2259 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2260 "-L path set the directory for the BIOS and VGA BIOS\n"
2261 #ifdef USE_CODE_COPY
2262 "-no-code-copy disable code copy acceleration\n"
2263 #endif
2264 #ifdef TARGET_I386
2265 "-isa simulate an ISA-only system (default is PCI system)\n"
2266 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2267 " (default is CL-GD5446 PCI VGA)\n"
2268 "-vgaacc [0|1] 1 to accelerate CL-GD5446 speed, default is 1\n"
2269 "-no-repeatkey disable key repeat feature for SDL keyboard simulation"
2270 #endif
2271 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2272 "\n"
2273 "During emulation, the following keys are useful:\n"
2274 "ctrl-alt-f toggle full screen\n"
2275 "ctrl-alt-n switch to virtual console 'n'\n"
2276 "ctrl-alt toggle mouse and keyboard grab\n"
2277 "\n"
2278 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2280 #ifdef CONFIG_SOFTMMU
2281 "qemu",
2282 #else
2283 "qemu-fast",
2284 #endif
2285 DEFAULT_RAM_SIZE,
2286 DEFAULT_NETWORK_SCRIPT,
2287 DEFAULT_GDBSTUB_PORT);
2288 #ifndef CONFIG_SOFTMMU
2289 printf("\n"
2290 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2291 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2292 "PC emulation.\n");
2293 #endif
2294 exit(1);
2297 #define HAS_ARG 0x0001
2299 enum {
2300 QEMU_OPTION_h,
2302 QEMU_OPTION_fda,
2303 QEMU_OPTION_fdb,
2304 QEMU_OPTION_hda,
2305 QEMU_OPTION_hdb,
2306 QEMU_OPTION_hdc,
2307 QEMU_OPTION_hdd,
2308 QEMU_OPTION_cdrom,
2309 QEMU_OPTION_boot,
2310 QEMU_OPTION_snapshot,
2311 QEMU_OPTION_m,
2312 QEMU_OPTION_nographic,
2313 #ifdef CONFIG_VNC
2314 QEMU_OPTION_vnc,
2315 QEMU_OPTION_vncport,
2316 QEMU_OPTION_vncconnect,
2317 #ifdef CONFIG_SDL
2318 QEMU_OPTION_vnc_and_sdl,
2319 #endif
2320 #endif
2321 QEMU_OPTION_enable_audio,
2323 QEMU_OPTION_nics,
2324 QEMU_OPTION_macaddr,
2325 QEMU_OPTION_bridge,
2326 QEMU_OPTION_n,
2327 QEMU_OPTION_tun_fd,
2328 QEMU_OPTION_user_net,
2329 QEMU_OPTION_tftp,
2330 QEMU_OPTION_smb,
2331 QEMU_OPTION_redir,
2332 QEMU_OPTION_dummy_net,
2334 QEMU_OPTION_kernel,
2335 QEMU_OPTION_append,
2336 QEMU_OPTION_initrd,
2338 QEMU_OPTION_S,
2339 QEMU_OPTION_s,
2340 QEMU_OPTION_p,
2341 QEMU_OPTION_d,
2342 QEMU_OPTION_l,
2343 QEMU_OPTION_hdachs,
2344 QEMU_OPTION_L,
2345 QEMU_OPTION_no_code_copy,
2346 QEMU_OPTION_vcpus,
2347 QEMU_OPTION_pci,
2348 QEMU_OPTION_nic_ne2000,
2349 QEMU_OPTION_isa,
2350 QEMU_OPTION_prep,
2351 QEMU_OPTION_k,
2352 QEMU_OPTION_localtime,
2353 QEMU_OPTION_cirrusvga,
2354 QEMU_OPTION_g,
2355 QEMU_OPTION_std_vga,
2356 QEMU_OPTION_monitor,
2357 QEMU_OPTION_domainname,
2358 QEMU_OPTION_serial,
2359 QEMU_OPTION_loadvm,
2360 QEMU_OPTION_full_screen,
2361 QEMU_OPTION_vgaacc,
2362 QEMU_OPTION_repeatkey,
2363 };
2365 typedef struct QEMUOption {
2366 const char *name;
2367 int flags;
2368 int index;
2369 } QEMUOption;
2371 const QEMUOption qemu_options[] = {
2372 { "h", 0, QEMU_OPTION_h },
2374 { "fda", HAS_ARG, QEMU_OPTION_fda },
2375 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2376 { "hda", HAS_ARG, QEMU_OPTION_hda },
2377 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2378 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2379 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2380 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2381 { "boot", HAS_ARG, QEMU_OPTION_boot },
2382 { "snapshot", 0, QEMU_OPTION_snapshot },
2383 { "m", HAS_ARG, QEMU_OPTION_m },
2384 { "nographic", 0, QEMU_OPTION_nographic },
2385 #ifdef CONFIG_VNC
2386 { "vnc", 0, QEMU_OPTION_vnc },
2387 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2388 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2389 #ifdef CONFIG_SDL
2390 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2391 #endif
2392 #endif
2393 { "k", HAS_ARG, QEMU_OPTION_k },
2394 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2396 { "nics", HAS_ARG, QEMU_OPTION_nics},
2397 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2398 { "bridge", HAS_ARG, QEMU_OPTION_bridge},
2399 { "n", HAS_ARG, QEMU_OPTION_n },
2400 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2401 #ifdef CONFIG_SLIRP
2402 { "user-net", 0, QEMU_OPTION_user_net },
2403 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2404 #ifndef _WIN32
2405 { "smb", HAS_ARG, QEMU_OPTION_smb },
2406 #endif
2407 { "redir", HAS_ARG, QEMU_OPTION_redir },
2408 #endif
2409 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2411 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2412 { "append", HAS_ARG, QEMU_OPTION_append },
2413 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2415 { "S", 0, QEMU_OPTION_S },
2416 { "s", 0, QEMU_OPTION_s },
2417 { "p", HAS_ARG, QEMU_OPTION_p },
2418 { "d", HAS_ARG, QEMU_OPTION_d },
2419 { "l", HAS_ARG, QEMU_OPTION_l },
2420 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2421 { "L", HAS_ARG, QEMU_OPTION_L },
2422 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2423 { "vcpus", 1, QEMU_OPTION_vcpus },
2424 #ifdef TARGET_PPC
2425 { "prep", 0, QEMU_OPTION_prep },
2426 { "g", 1, QEMU_OPTION_g },
2427 #endif
2428 { "localtime", 0, QEMU_OPTION_localtime },
2429 { "isa", 0, QEMU_OPTION_isa },
2430 { "std-vga", 0, QEMU_OPTION_std_vga },
2431 { "monitor", 1, QEMU_OPTION_monitor },
2432 { "domain-name", 1, QEMU_OPTION_domainname },
2433 { "serial", 1, QEMU_OPTION_serial },
2434 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2435 { "full-screen", 0, QEMU_OPTION_full_screen },
2437 /* temporary options */
2438 { "pci", 0, QEMU_OPTION_pci },
2439 { "nic-ne2000", 0, QEMU_OPTION_nic_ne2000 },
2440 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2441 { "vgaacc", HAS_ARG, QEMU_OPTION_vgaacc },
2442 { "no-repeatkey", 0, QEMU_OPTION_repeatkey },
2443 { NULL },
2444 };
2446 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2448 /* this stack is only used during signal handling */
2449 #define SIGNAL_STACK_SIZE 32768
2451 static uint8_t *signal_stack;
2453 #endif
2455 #define NET_IF_TUN 0
2456 #define NET_IF_USER 1
2457 #define NET_IF_DUMMY 2
2459 #include <xg_private.h>
2461 #if defined(__i386__) || defined (__x86_64__)
2462 #define L1_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_USER)
2463 #define L2_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_DIRTY|_PAGE_USER)
2465 #ifdef __i386__
2466 #define _LEVEL_3_ 0
2467 #else
2468 #define _LEVEL_3_ 1
2469 #endif
2471 #if _LEVEL_3_
2472 #define L3_PROT (_PAGE_PRESENT)
2473 #define L1_PAGETABLE_ENTRIES 512
2474 #else
2475 #define L1_PAGETABLE_ENTRIES 1024
2476 #endif
2478 inline int
2479 get_vl2_table(unsigned long count, unsigned long start)
2481 #if _LEVEL_3_
2482 return ((start + (count << PAGE_SHIFT)) >> L3_PAGETABLE_SHIFT) & 0x3;
2483 #else
2484 return 0;
2485 #endif
2488 int
2489 setup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2490 unsigned long *mem_page_array, unsigned long *page_table_array,
2491 unsigned long v_start, unsigned long v_end)
2493 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2494 l2_pgentry_t *vl2tab[4] = {NULL, NULL, NULL, NULL};
2495 l2_pgentry_t *vl2e=NULL, *vl2_table = NULL;
2496 unsigned long l1tab;
2497 unsigned long ppt_alloc = 0;
2498 unsigned long count;
2499 int i = 0;
2500 #if _LEVEL_3_
2501 l3_pgentry_t *vl3tab = NULL;
2502 unsigned long l2tab;
2504 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2505 PROT_READ|PROT_WRITE,
2506 toptab >> PAGE_SHIFT)) == NULL )
2507 goto error_out;
2508 for (i = 0; i < 4 ; i++) {
2509 l2tab = vl3tab[i] & PAGE_MASK;
2510 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2511 PROT_READ|PROT_WRITE,
2512 l2tab >> PAGE_SHIFT);
2513 if(vl2tab[i] == NULL)
2514 goto error_out;
2516 munmap(vl3tab, PAGE_SIZE);
2517 vl3tab = NULL;
2518 #else
2519 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2520 PROT_READ|PROT_WRITE,
2521 toptab >> PAGE_SHIFT)) == NULL )
2522 goto error_out;
2523 #endif
2525 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ )
2527 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2529 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2530 vl2e = &vl2_table[l2_table_offset(v_start +
2531 (count << PAGE_SHIFT))];
2533 l1tab = page_table_array[ppt_alloc++] << PAGE_SHIFT;
2534 if ( vl1tab != NULL )
2535 munmap(vl1tab, PAGE_SIZE);
2537 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2538 PROT_READ|PROT_WRITE,
2539 l1tab >> PAGE_SHIFT)) == NULL )
2541 goto error_out;
2543 memset(vl1tab, 0, PAGE_SIZE);
2544 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2545 *vl2e = l1tab | L2_PROT;
2548 *vl1e = (mem_page_array[count] << PAGE_SHIFT) | L1_PROT;
2549 vl1e++;
2551 error_out:
2552 if (vl1tab)
2553 munmap(vl1tab, PAGE_SIZE);
2554 for(i = 0; i < 4; i++)
2555 if(vl2tab[i]) munmap(vl2tab[i], PAGE_SIZE);
2556 return ppt_alloc;
2559 void
2560 unsetup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2561 unsigned long v_start, unsigned long v_end)
2563 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2564 l2_pgentry_t *vl2tab[4], *vl2e=NULL, *vl2_table = NULL;
2565 unsigned long l1tab;
2566 unsigned long count;
2567 int i = 0;
2568 #if _LEVEL_3_
2569 l3_pgentry_t *vl3tab = NULL;
2570 unsigned long l2tab;
2572 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2573 PROT_READ|PROT_WRITE,
2574 toptab >> PAGE_SHIFT)) == NULL )
2575 goto error_out;
2576 for (i = 0; i < 4 ; i ++) {
2577 l2tab = vl3tab[i] & PAGE_MASK;
2578 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2579 PROT_READ|PROT_WRITE,
2580 l2tab >> PAGE_SHIFT);
2581 if (vl2tab[i] == NULL)
2582 goto error_out;
2584 munmap(vl3tab, PAGE_SIZE);
2585 vl3tab = NULL;
2586 #else
2587 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2588 PROT_READ|PROT_WRITE,
2589 toptab >> PAGE_SHIFT)) == NULL )
2590 goto error_out;
2591 #endif
2593 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ ) {
2594 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2596 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2597 vl2e = &vl2_table[l2_table_offset(v_start + (count << PAGE_SHIFT))];
2598 l1tab = *vl2e & PAGE_MASK;
2600 if(l1tab == 0)
2601 continue;
2602 if ( vl1tab != NULL )
2603 munmap(vl1tab, PAGE_SIZE);
2605 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2606 PROT_READ|PROT_WRITE,
2607 l1tab >> PAGE_SHIFT)) == NULL )
2609 goto error_out;
2611 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2612 *vl2e = 0;
2615 *vl1e = 0;
2616 vl1e++;
2619 error_out:
2620 if (vl1tab)
2621 munmap(vl1tab, PAGE_SIZE);
2622 for(i = 0; i < 4; i++)
2623 if (vl2tab[i])
2624 munmap(vl2tab[i], PAGE_SIZE);
2627 void set_vram_mapping(unsigned long addr, unsigned long end)
2629 end = addr + VGA_RAM_SIZE;
2630 setup_mapping(xc_handle, domid, toptab,
2631 vgapage_array, freepage_array, addr, end);
2634 void unset_vram_mapping(unsigned long addr, unsigned long end)
2636 end = addr + VGA_RAM_SIZE;
2637 /* FIXME Flush the shadow page */
2638 unsetup_mapping(xc_handle, domid, toptab, addr, end);
2640 #elif defined(__ia64__)
2641 void set_vram_mapping(unsigned long addr, unsigned long end) {}
2642 void unset_vram_mapping(unsigned long addr, unsigned long end) {}
2643 #endif
2645 int main(int argc, char **argv)
2647 #ifdef CONFIG_GDBSTUB
2648 int use_gdbstub, gdbstub_port;
2649 #endif
2650 int i, has_cdrom;
2651 int snapshot, linux_boot;
2652 CPUState *env;
2653 const char *initrd_filename;
2654 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2655 const char *kernel_filename, *kernel_cmdline;
2656 DisplayState *ds = &display_state;
2657 int cyls, heads, secs;
2658 int start_emulation = 1;
2659 uint8_t macaddr[6];
2660 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2661 int optind;
2662 const char *r, *optarg;
2663 CharDriverState *monitor_hd;
2664 char monitor_device[128];
2665 char serial_devices[MAX_SERIAL_PORTS][128];
2666 int serial_device_index;
2667 char qemu_dm_logfilename[64];
2668 const char *loadvm = NULL;
2669 unsigned long nr_pages, extra_pages, ram_pages, *page_array;
2670 extern void *shared_page;
2671 extern void *shared_vram;
2673 #if !defined(CONFIG_SOFTMMU)
2674 /* we never want that malloc() uses mmap() */
2675 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2676 #endif
2677 initrd_filename = NULL;
2678 for(i = 0; i < MAX_FD; i++)
2679 fd_filename[i] = NULL;
2680 for(i = 0; i < MAX_DISKS; i++)
2681 hd_filename[i] = NULL;
2682 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2683 vga_ram_size = VGA_RAM_SIZE;
2684 bios_size = BIOS_SIZE;
2685 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2686 #ifdef CONFIG_GDBSTUB
2687 use_gdbstub = 0;
2688 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2689 #endif
2690 snapshot = 0;
2691 nographic = 0;
2692 usevnc = 0;
2693 vncport=0;
2694 vncconnect=NULL;
2695 kernel_filename = NULL;
2696 kernel_cmdline = "";
2697 has_cdrom = 1;
2698 cyls = heads = secs = 0;
2699 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2701 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2702 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2703 serial_devices[i][0] = '\0';
2704 serial_device_index = 0;
2706 nb_tun_fds = 0;
2707 net_if_type = -1;
2708 nb_nics = 1;
2709 /* default mac address of the first network interface */
2710 macaddr[0] = 0x52;
2711 macaddr[1] = 0x54;
2712 macaddr[2] = 0x00;
2713 macaddr[3] = 0x12;
2714 macaddr[4] = 0x34;
2715 macaddr[5] = 0x56;
2717 /* init debug */
2718 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
2719 cpu_set_log_filename(qemu_dm_logfilename);
2720 cpu_set_log(0);
2722 optind = 1;
2723 for(;;) {
2724 if (optind >= argc)
2725 break;
2726 r = argv[optind];
2727 if (r[0] != '-') {
2728 hd_filename[0] = argv[optind++];
2729 } else {
2730 const QEMUOption *popt;
2732 optind++;
2733 popt = qemu_options;
2734 for(;;) {
2735 if (!popt->name) {
2736 fprintf(stderr, "%s: invalid option -- '%s'\n",
2737 argv[0], r);
2738 exit(1);
2740 if (!strcmp(popt->name, r + 1))
2741 break;
2742 popt++;
2744 if (popt->flags & HAS_ARG) {
2745 if (optind >= argc) {
2746 fprintf(stderr, "%s: option '%s' requires an argument\n",
2747 argv[0], r);
2748 exit(1);
2750 optarg = argv[optind++];
2751 } else {
2752 optarg = NULL;
2755 switch(popt->index) {
2756 case QEMU_OPTION_initrd:
2757 initrd_filename = optarg;
2758 break;
2759 case QEMU_OPTION_hda:
2760 hd_filename[0] = optarg;
2761 break;
2762 case QEMU_OPTION_hdb:
2763 hd_filename[1] = optarg;
2764 break;
2765 case QEMU_OPTION_snapshot:
2766 snapshot = 1;
2767 break;
2768 case QEMU_OPTION_hdachs:
2770 const char *p;
2771 p = optarg;
2772 cyls = strtol(p, (char **)&p, 0);
2773 if (*p != ',')
2774 goto chs_fail;
2775 p++;
2776 heads = strtol(p, (char **)&p, 0);
2777 if (*p != ',')
2778 goto chs_fail;
2779 p++;
2780 secs = strtol(p, (char **)&p, 0);
2781 if (*p != '\0') {
2782 chs_fail:
2783 cyls = 0;
2786 break;
2787 case QEMU_OPTION_nographic:
2788 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2789 if(!strcmp(serial_devices[0], "vc"))
2790 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
2791 "stdio");
2792 nographic = 1;
2793 break;
2794 #ifdef CONFIG_VNC
2795 case QEMU_OPTION_vnc:
2796 usevnc = 1;
2797 break;
2798 case QEMU_OPTION_vncport:
2800 const char *p;
2801 p = optarg;
2802 vncport= strtol(optarg, (char **)&p, 0);
2804 break;
2805 case QEMU_OPTION_vncconnect:
2806 vncconnect = optarg;
2807 break;
2808 #ifdef CONFIG_SDL
2809 case QEMU_OPTION_vnc_and_sdl:
2810 usevnc = 2;
2811 break;
2812 #endif
2813 #endif
2814 case QEMU_OPTION_kernel:
2815 kernel_filename = optarg;
2816 break;
2817 case QEMU_OPTION_append:
2818 kernel_cmdline = optarg;
2819 break;
2820 case QEMU_OPTION_tun_fd:
2822 const char *p;
2823 int fd;
2824 net_if_type = NET_IF_TUN;
2825 if ( nb_tun_fds < MAX_NICS ) {
2826 fd = strtol(optarg, (char **)&p, 0);
2827 if (*p != '\0') {
2828 fprintf(stderr,
2829 "qemu: invalid fd for network interface %d\n",
2830 nb_tun_fds);
2831 exit(1);
2833 tun_fds[nb_tun_fds++] = fd;
2836 break;
2837 case QEMU_OPTION_hdc:
2838 hd_filename[2] = optarg;
2839 has_cdrom = 0;
2840 break;
2841 case QEMU_OPTION_hdd:
2842 hd_filename[3] = optarg;
2843 break;
2844 case QEMU_OPTION_cdrom:
2845 hd_filename[2] = optarg;
2846 has_cdrom = 1;
2847 break;
2848 case QEMU_OPTION_boot:
2849 boot_device = optarg[0];
2850 if ( boot_device != 'a' &&
2851 boot_device != 'c' &&
2852 boot_device != 'd' ) {
2853 fprintf(stderr, "qemu: invalid boot device '%c'\n",
2854 boot_device);
2855 exit(1);
2857 break;
2858 case QEMU_OPTION_fda:
2859 fd_filename[0] = optarg;
2860 break;
2861 case QEMU_OPTION_fdb:
2862 fd_filename[1] = optarg;
2863 break;
2864 case QEMU_OPTION_nics:
2865 nb_nics = atoi(optarg);
2866 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2867 fprintf(stderr,
2868 "qemu: invalid number of network interfaces\n");
2869 exit(1);
2871 break;
2872 case QEMU_OPTION_bridge:
2873 pstrcpy(bridge, sizeof(bridge), optarg);
2874 break;
2875 case QEMU_OPTION_macaddr:
2877 const char *p;
2878 int i;
2880 p = optarg;
2881 for (i = 0; i < 6; i++) {
2882 macaddr[i] = strtol(p, (char **)&p, 16);
2883 if (i == 5) {
2884 if (*p != '\0')
2885 goto macaddr_error;
2886 } else {
2887 if (*p != ':') {
2888 macaddr_error:
2889 fprintf(stderr, "qemu: invalid syntax "
2890 "for ethernet address\n");
2891 exit(1);
2893 p++;
2897 break;
2898 #ifdef CONFIG_SLIRP
2899 case QEMU_OPTION_tftp:
2900 tftp_prefix = optarg;
2901 break;
2902 #ifndef _WIN32
2903 case QEMU_OPTION_smb:
2904 net_slirp_smb(optarg);
2905 break;
2906 #endif
2907 case QEMU_OPTION_user_net:
2908 net_if_type = NET_IF_USER;
2909 break;
2910 case QEMU_OPTION_redir:
2911 net_slirp_redir(optarg);
2912 break;
2913 #endif
2914 case QEMU_OPTION_dummy_net:
2915 net_if_type = NET_IF_DUMMY;
2916 break;
2917 case QEMU_OPTION_enable_audio:
2918 audio_enabled = 1;
2919 break;
2920 case QEMU_OPTION_h:
2921 help();
2922 break;
2923 case QEMU_OPTION_m:
2924 ram_size = atol(optarg) * 1024 * 1024;
2925 if (ram_size <= 0)
2926 help();
2927 break;
2928 case QEMU_OPTION_d:
2930 domid = atoi(optarg);
2931 fprintf(logfile, "domid: %d\n", domid);
2933 break;
2934 case QEMU_OPTION_p:
2936 extern evtchn_port_t ioreq_remote_port;
2937 ioreq_remote_port = atoi(optarg);
2938 fprintf(logfile, "eport: %d\n", ioreq_remote_port);
2940 break;
2941 case QEMU_OPTION_l:
2943 int mask;
2944 mask = cpu_str_to_log_mask(optarg);
2945 fprintf(logfile, "mask: %x\n", mask);
2946 cpu_set_log(mask);
2948 break;
2949 case QEMU_OPTION_n:
2950 pstrcpy(network_script, sizeof(network_script), optarg);
2951 break;
2952 #ifdef CONFIG_GDBSTUB
2953 case QEMU_OPTION_s:
2954 use_gdbstub = 1;
2955 break;
2956 #endif
2957 case QEMU_OPTION_L:
2958 bios_dir = optarg;
2959 break;
2960 case QEMU_OPTION_S:
2961 start_emulation = 0;
2962 break;
2963 case QEMU_OPTION_vcpus:
2964 vcpus = atoi(optarg);
2965 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
2966 break;
2967 case QEMU_OPTION_pci:
2968 pci_enabled = 1;
2969 break;
2970 case QEMU_OPTION_nic_ne2000:
2971 nic_ne2000 = 1;
2972 break;
2973 case QEMU_OPTION_isa:
2974 pci_enabled = 0;
2975 break;
2976 case QEMU_OPTION_prep:
2977 prep_enabled = 1;
2978 break;
2979 case QEMU_OPTION_k:
2980 keyboard_layout = optarg;
2981 break;
2982 case QEMU_OPTION_localtime:
2983 rtc_utc = 0;
2984 break;
2985 case QEMU_OPTION_cirrusvga:
2986 cirrus_vga_enabled = 1;
2987 break;
2988 case QEMU_OPTION_vgaacc:
2990 const char *p;
2991 p = optarg;
2992 vga_accelerate = strtol(p, (char **)&p, 0);
2993 if (*p != '\0') {
2994 fprintf(stderr, "qemu: invalid vgaacc option\n");
2995 exit(1);
2998 break;
2999 case QEMU_OPTION_repeatkey:
3000 repeat_key = 0;
3001 break;
3002 case QEMU_OPTION_std_vga:
3003 cirrus_vga_enabled = 0;
3004 break;
3005 case QEMU_OPTION_g:
3007 const char *p;
3008 int w, h, depth;
3009 p = optarg;
3010 w = strtol(p, (char **)&p, 10);
3011 if (w <= 0) {
3012 graphic_error:
3013 fprintf(stderr, "qemu: invalid resolution or depth\n");
3014 exit(1);
3016 if (*p != 'x')
3017 goto graphic_error;
3018 p++;
3019 h = strtol(p, (char **)&p, 10);
3020 if (h <= 0)
3021 goto graphic_error;
3022 if (*p == 'x') {
3023 p++;
3024 depth = strtol(p, (char **)&p, 10);
3025 if (depth != 8 && depth != 15 && depth != 16 &&
3026 depth != 24 && depth != 32)
3027 goto graphic_error;
3028 } else if (*p == '\0') {
3029 depth = graphic_depth;
3030 } else {
3031 goto graphic_error;
3034 graphic_width = w;
3035 graphic_height = h;
3036 graphic_depth = depth;
3038 break;
3039 case QEMU_OPTION_monitor:
3040 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3041 break;
3042 case QEMU_OPTION_serial:
3043 if (serial_device_index >= MAX_SERIAL_PORTS) {
3044 fprintf(stderr, "qemu: too many serial ports\n");
3045 exit(1);
3047 pstrcpy(serial_devices[serial_device_index],
3048 sizeof(serial_devices[0]), optarg);
3049 serial_device_index++;
3050 break;
3051 case QEMU_OPTION_loadvm:
3052 loadvm = optarg;
3053 break;
3054 case QEMU_OPTION_full_screen:
3055 full_screen = 1;
3056 break;
3057 case QEMU_OPTION_domainname:
3058 strncat(domain_name, optarg, sizeof(domain_name) - 20);
3059 break;
3065 linux_boot = (kernel_filename != NULL);
3067 if ( !linux_boot && hd_filename[0] == '\0' &&
3068 hd_filename[2] == '\0' && fd_filename[0] == '\0' )
3069 help();
3071 /* boot to cd by default if no hard disk */
3072 if (hd_filename[0] == '\0' && boot_device == 'c') {
3073 if (fd_filename[0] != '\0')
3074 boot_device = 'a';
3075 else
3076 boot_device = 'd';
3079 #if !defined(CONFIG_SOFTMMU)
3080 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3082 static uint8_t stdout_buf[4096];
3083 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3085 #else
3086 setvbuf(stdout, NULL, _IOLBF, 0);
3087 #endif
3089 /* init host network redirectors */
3090 if (net_if_type == -1) {
3091 net_if_type = NET_IF_TUN;
3092 #if defined(CONFIG_SLIRP)
3093 if (access(network_script, R_OK) < 0) {
3094 net_if_type = NET_IF_USER;
3096 #endif
3099 for(i = 0; i < nb_nics; i++) {
3100 NetDriverState *nd = &nd_table[i];
3101 nd->index = i;
3102 /* init virtual mac address */
3103 nd->macaddr[0] = macaddr[0];
3104 nd->macaddr[1] = macaddr[1];
3105 nd->macaddr[2] = macaddr[2];
3106 nd->macaddr[3] = macaddr[3];
3107 nd->macaddr[4] = macaddr[4];
3108 nd->macaddr[5] = macaddr[5] + i;
3109 switch(net_if_type) {
3110 #if defined(CONFIG_SLIRP)
3111 case NET_IF_USER:
3112 net_slirp_init(nd);
3113 break;
3114 #endif
3115 #if !defined(_WIN32)
3116 case NET_IF_TUN:
3117 if (i < nb_tun_fds) {
3118 net_fd_init(nd, tun_fds[i]);
3119 } else {
3120 if (net_tun_init(nd) < 0)
3121 net_dummy_init(nd);
3123 break;
3124 #endif
3125 case NET_IF_DUMMY:
3126 default:
3127 net_dummy_init(nd);
3128 break;
3132 /* init the memory */
3133 phys_ram_size = ram_size + vga_ram_size + bios_size;
3135 ram_pages = ram_size/PAGE_SIZE;
3136 #if defined(__i386__) || defined(__x86_64__)
3137 vgaram_pages = (vga_ram_size -1)/PAGE_SIZE + 1;
3138 free_pages = vgaram_pages / L1_PAGETABLE_ENTRIES;
3139 extra_pages = vgaram_pages + free_pages;
3140 #else
3141 /* Test vga acceleration later */
3142 extra_pages = 0;
3143 #endif
3145 xc_handle = xc_interface_open();
3147 xc_dominfo_t info;
3148 xc_domain_getinfo(xc_handle, domid, 1, &info);
3150 nr_pages = info.nr_pages + extra_pages;
3152 if ( xc_domain_setmaxmem(xc_handle, domid,
3153 (nr_pages) * PAGE_SIZE/1024 ) != 0)
3155 fprintf(logfile, "set maxmem returned error %d\n", errno);
3156 exit(-1);
3159 if ( (page_array = (unsigned long *)
3160 malloc(nr_pages * sizeof(unsigned long))) == NULL)
3162 fprintf(logfile, "malloc returned error %d\n", errno);
3163 exit(-1);
3166 if (xc_domain_memory_increase_reservation(xc_handle, domid,
3167 extra_pages , 0, 0, NULL) != 0)
3169 fprintf(logfile, "increase reservation returned error %d\n", errno);
3170 exit(-1);
3173 #if defined(__i386__) || defined(__x86_64__)
3174 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
3176 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
3177 exit(-1);
3180 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3181 PROT_READ|PROT_WRITE,
3182 page_array,
3183 ram_pages - 1)) == 0 )
3185 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3186 exit(-1);
3189 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3190 PROT_READ|PROT_WRITE,
3191 page_array[ram_pages - 1]);
3193 vgapage_array = &page_array[nr_pages - vgaram_pages];
3195 if ( (shared_vram = xc_map_foreign_batch(xc_handle, domid,
3196 PROT_READ|PROT_WRITE,
3197 vgapage_array,
3198 vgaram_pages)) == 0)
3200 fprintf(logfile,
3201 "xc_map_foreign_batch vgaram returned error %d\n", errno);
3202 exit(-1);
3205 memset(shared_vram, 0, vgaram_pages * PAGE_SIZE);
3206 toptab = page_array[ram_pages] << PAGE_SHIFT;
3208 vtop_table = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3209 PROT_READ|PROT_WRITE,
3210 page_array[ram_pages]);
3212 freepage_array = &page_array[nr_pages - extra_pages];
3213 #elif defined(__ia64__)
3214 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, 0, ram_pages)
3215 != ram_pages )
3217 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3218 exit(-1);
3221 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3222 PROT_READ|PROT_WRITE,
3223 page_array,
3224 ram_pages)) == 0 )
3226 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3227 exit(-1);
3230 if ( xc_ia64_get_pfn_list(xc_handle, domid,
3231 page_array, IO_PAGE_START >> PAGE_SHIFT, 1) != 1 )
3233 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3234 exit(-1);
3237 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3238 PROT_READ|PROT_WRITE,
3239 page_array[0]);
3240 #endif
3242 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
3243 (page_array[nr_pages - 1]));
3245 /* we always create the cdrom drive, even if no disk is there */
3246 bdrv_init();
3247 if (has_cdrom) {
3248 bs_table[2] = bdrv_new("cdrom");
3249 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3252 /* open the virtual block devices */
3253 for(i = 0; i < MAX_DISKS; i++) {
3254 if (hd_filename[i]) {
3255 if (!bs_table[i]) {
3256 char buf[64];
3257 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3258 bs_table[i] = bdrv_new(buf);
3260 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3261 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3262 hd_filename[i]);
3263 exit(1);
3265 if (i == 0 && cyls != 0)
3266 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3270 /* we always create at least one floppy disk */
3271 fd_table[0] = bdrv_new("fda");
3272 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3274 for(i = 0; i < MAX_FD; i++) {
3275 if (fd_filename[i]) {
3276 if (!fd_table[i]) {
3277 char buf[64];
3278 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3279 fd_table[i] = bdrv_new(buf);
3280 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3282 if (fd_filename[i] != '\0') {
3283 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3284 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3285 fd_filename[i]);
3286 exit(1);
3292 /* init CPU state */
3293 env = cpu_init();
3294 global_env = env;
3295 cpu_single_env = env;
3297 init_ioports();
3298 cpu_calibrate_ticks();
3300 /* terminal init */
3301 if (nographic) {
3302 dumb_display_init(ds);
3303 } else {
3304 if (usevnc) {
3305 #ifdef CONFIG_VNC
3306 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
3307 #else
3308 fprintf(logfile, "qemu not configured with vnc support\n");
3309 #endif
3310 } else {
3311 #ifdef CONFIG_SDL
3312 sdl_display_init(ds, full_screen);
3313 #else
3314 dumb_display_init(ds);
3315 #endif
3319 vga_console = graphic_console_init(ds);
3321 monitor_hd = qemu_chr_open(monitor_device);
3322 if (!monitor_hd) {
3323 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3324 exit(1);
3326 monitor_init(monitor_hd, !nographic);
3328 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3329 if (serial_devices[i][0] != '\0') {
3330 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3331 if (!serial_hds[i]) {
3332 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3333 serial_devices[i]);
3334 exit(1);
3336 if (!strcmp(serial_devices[i], "vc"))
3337 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3341 /* setup cpu signal handlers for MMU / self modifying code handling */
3342 #if !defined(CONFIG_SOFTMMU)
3344 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3346 stack_t stk;
3347 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3348 stk.ss_sp = signal_stack;
3349 stk.ss_size = SIGNAL_STACK_SIZE;
3350 stk.ss_flags = 0;
3352 if (sigaltstack(&stk, NULL) < 0) {
3353 fprintf(logfile, "sigaltstack returned error %d\n", errno);
3354 exit(1);
3357 #endif
3359 struct sigaction act;
3361 sigfillset(&act.sa_mask);
3362 act.sa_flags = SA_SIGINFO;
3363 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3364 act.sa_flags |= SA_ONSTACK;
3365 #endif
3366 act.sa_sigaction = host_segv_handler;
3367 sigaction(SIGSEGV, &act, NULL);
3368 sigaction(SIGBUS, &act, NULL);
3369 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3370 sigaction(SIGFPE, &act, NULL);
3371 #endif
3373 #endif
3375 #ifndef _WIN32
3377 struct sigaction act;
3378 sigfillset(&act.sa_mask);
3379 act.sa_flags = 0;
3380 act.sa_handler = SIG_IGN;
3381 sigaction(SIGPIPE, &act, NULL);
3383 #endif
3384 init_timers();
3386 #if defined(TARGET_I386)
3387 pc_init(ram_size, vga_ram_size, boot_device,
3388 ds, fd_filename, snapshot,
3389 kernel_filename, kernel_cmdline, initrd_filename);
3390 #elif defined(TARGET_PPC)
3391 ppc_init(ram_size, vga_ram_size, boot_device,
3392 ds, fd_filename, snapshot,
3393 kernel_filename, kernel_cmdline, initrd_filename);
3394 #elif defined(TARGET_SPARC)
3395 sun4m_init(ram_size, vga_ram_size, boot_device,
3396 ds, fd_filename, snapshot,
3397 kernel_filename, kernel_cmdline, initrd_filename);
3398 #endif
3400 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3401 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3403 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
3404 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
3406 #ifdef CONFIG_GDBSTUB
3407 if (use_gdbstub) {
3408 if (gdbserver_start(gdbstub_port) < 0) {
3409 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3410 gdbstub_port);
3411 exit(1);
3412 } else {
3413 fprintf(logfile, "Waiting gdb connection on port %d\n", gdbstub_port);
3415 } else
3416 #endif
3417 if (loadvm)
3418 qemu_loadvm(loadvm);
3421 /* XXX: simplify init */
3422 if (start_emulation) {
3423 vm_start();
3426 main_loop();
3427 quit_timers();
3428 return 0;
3431 extern fd_set wakeup_rfds;
3432 void tun_receive_handler(fd_set *rfds)
3434 IOHandlerRecord *ioh;
3435 static uint8_t buf[4096];
3436 int n, max_size;
3438 for (ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3439 if ( FD_ISSET(ioh->fd, rfds) ) {
3440 max_size = ioh->fd_can_read(ioh->opaque);
3441 if (max_size > 0) {
3442 if (max_size > sizeof(buf))
3443 max_size = sizeof(buf);
3444 n = read(ioh->fd, buf, max_size);
3445 if (n >= 0) {
3446 ioh->fd_read(ioh->opaque, buf, n);
3451 update_select_wakeup_events();
3454 void update_select_wakeup_events(void)
3456 IOHandlerRecord *ioh;
3457 int max_size;
3459 for(ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3460 FD_CLR(ioh->fd, &wakeup_rfds);
3461 if (ioh->fd_can_read) {
3462 max_size = ioh->fd_can_read(ioh->opaque);
3463 if (max_size > 0) {
3464 FD_SET(ioh->fd, &wakeup_rfds);