ia64/xen-unstable

view tools/ioemu/vl.c @ 8740:3d7ea7972b39

Update patches for linux 2.6.15.

Signed-off-by: Christian Limpach <Christian.Limpach@cl.cam.ac.uk>
author cl349@firebug.cl.cam.ac.uk
date Thu Feb 02 17:16:00 2006 +0000 (2006-02-02)
parents f1b361b05bf3
children da6297243495
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, len;
962 len = len1;
963 while (len > 0) {
964 ret = write(fd, buf, len);
965 if (ret < 0) {
966 if (errno != EINTR && errno != EAGAIN)
967 return -1;
968 } else if (ret == 0) {
969 break;
970 } else {
971 buf += ret;
972 len -= ret;
973 }
974 }
975 return len1 - len;
976 }
978 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
979 {
980 FDCharDriver *s = chr->opaque;
981 return unix_write(s->fd_out, buf, len);
982 }
984 static void fd_chr_add_read_handler(CharDriverState *chr,
985 IOCanRWHandler *fd_can_read,
986 IOReadHandler *fd_read, void *opaque)
987 {
988 FDCharDriver *s = chr->opaque;
990 if (nographic && s->fd_in == 0) {
991 s->fd_can_read = fd_can_read;
992 s->fd_read = fd_read;
993 s->fd_opaque = opaque;
994 } else {
995 qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
996 }
997 }
999 /* open a character device to a unix fd */
1000 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1002 CharDriverState *chr;
1003 FDCharDriver *s;
1005 chr = qemu_mallocz(sizeof(CharDriverState));
1006 if (!chr)
1007 return NULL;
1008 s = qemu_mallocz(sizeof(FDCharDriver));
1009 if (!s) {
1010 free(chr);
1011 return NULL;
1013 s->fd_in = fd_in;
1014 s->fd_out = fd_out;
1015 chr->opaque = s;
1016 chr->chr_write = fd_chr_write;
1017 chr->chr_add_read_handler = fd_chr_add_read_handler;
1018 return chr;
1021 /* for STDIO, we handle the case where several clients use it
1022 (nographic mode) */
1024 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1026 static int term_got_escape, client_index;
1028 void term_print_help(void)
1030 printf("\n"
1031 "C-a h print this help\n"
1032 "C-a x exit emulator\n"
1033 "C-a s save disk data back to file (if -snapshot)\n"
1034 "C-a b send break (magic sysrq)\n"
1035 "C-a c switch between console and monitor\n"
1036 "C-a C-a send C-a\n"
1037 );
1040 /* called when a char is received */
1041 static void stdio_received_byte(int ch)
1043 if (term_got_escape) {
1044 term_got_escape = 0;
1045 switch(ch) {
1046 case 'h':
1047 term_print_help();
1048 break;
1049 case 'x':
1050 exit(0);
1051 break;
1052 case 's':
1054 int i;
1055 for (i = 0; i < MAX_DISKS; i++) {
1056 if (bs_table[i])
1057 bdrv_commit(bs_table[i]);
1060 break;
1061 case 'b':
1062 if (client_index < stdio_nb_clients) {
1063 CharDriverState *chr;
1064 FDCharDriver *s;
1066 chr = stdio_clients[client_index];
1067 s = chr->opaque;
1068 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1070 break;
1071 case 'c':
1072 client_index++;
1073 if (client_index >= stdio_nb_clients)
1074 client_index = 0;
1075 if (client_index == 0) {
1076 /* send a new line in the monitor to get the prompt */
1077 ch = '\r';
1078 goto send_char;
1080 break;
1081 case TERM_ESCAPE:
1082 goto send_char;
1084 } else if (ch == TERM_ESCAPE) {
1085 term_got_escape = 1;
1086 } else {
1087 send_char:
1088 if (client_index < stdio_nb_clients) {
1089 uint8_t buf[1];
1090 CharDriverState *chr;
1091 FDCharDriver *s;
1093 chr = stdio_clients[client_index];
1094 s = chr->opaque;
1095 buf[0] = ch;
1096 /* XXX: should queue the char if the device is not
1097 ready */
1098 if (s->fd_can_read(s->fd_opaque) > 0)
1099 s->fd_read(s->fd_opaque, buf, 1);
1104 static int stdio_can_read(void *opaque)
1106 /* XXX: not strictly correct */
1107 return 1;
1110 static void stdio_read(void *opaque, const uint8_t *buf, int size)
1112 int i;
1113 for(i = 0; i < size; i++)
1114 stdio_received_byte(buf[i]);
1117 /* init terminal so that we can grab keys */
1118 static struct termios oldtty;
1119 static int old_fd0_flags;
1121 static void term_exit(void)
1123 tcsetattr (0, TCSANOW, &oldtty);
1124 fcntl(0, F_SETFL, old_fd0_flags);
1127 static void term_init(void)
1129 struct termios tty;
1131 tcgetattr (0, &tty);
1132 oldtty = tty;
1133 old_fd0_flags = fcntl(0, F_GETFL);
1135 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1136 |INLCR|IGNCR|ICRNL|IXON);
1137 tty.c_oflag |= OPOST;
1138 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1139 /* if graphical mode, we allow Ctrl-C handling */
1140 if (nographic)
1141 tty.c_lflag &= ~ISIG;
1142 tty.c_cflag &= ~(CSIZE|PARENB);
1143 tty.c_cflag |= CS8;
1144 tty.c_cc[VMIN] = 1;
1145 tty.c_cc[VTIME] = 0;
1147 tcsetattr (0, TCSANOW, &tty);
1149 atexit(term_exit);
1151 fcntl(0, F_SETFL, O_NONBLOCK);
1154 CharDriverState *qemu_chr_open_stdio(void)
1156 CharDriverState *chr;
1158 if (nographic) {
1159 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1160 return NULL;
1161 chr = qemu_chr_open_fd(0, 1);
1162 if (stdio_nb_clients == 0)
1163 qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1164 client_index = stdio_nb_clients;
1165 } else {
1166 if (stdio_nb_clients != 0)
1167 return NULL;
1168 chr = qemu_chr_open_fd(0, 1);
1170 stdio_clients[stdio_nb_clients++] = chr;
1171 if (stdio_nb_clients == 1) {
1172 /* set the terminal in raw mode */
1173 term_init();
1175 return chr;
1178 int store_console_dev(int domid, char *pts)
1180 int xc_handle;
1181 struct xs_handle *xs;
1182 char *path;
1184 xs = xs_daemon_open();
1185 if (xs == NULL) {
1186 fprintf(logfile, "Could not contact XenStore\n");
1187 return -1;
1190 xc_handle = xc_interface_open();
1191 if (xc_handle == -1) {
1192 fprintf(logfile, "xc_interface_open() error\n");
1193 return -1;
1196 path = xs_get_domain_path(xs, domid);
1197 if (path == NULL) {
1198 fprintf(logfile, "xs_get_domain_path() error\n");
1199 return -1;
1201 path = realloc(path, strlen(path) + strlen("/console/tty") + 1);
1202 if (path == NULL) {
1203 fprintf(logfile, "realloc error\n");
1204 return -1;
1206 strcat(path, "/console/tty");
1207 if (!xs_write(xs, XBT_NULL, path, pts, strlen(pts))) {
1208 fprintf(logfile, "xs_write for console fail");
1209 return -1;
1212 free(path);
1213 xs_daemon_close(xs);
1214 close(xc_handle);
1216 return 0;
1219 #if defined(__linux__)
1220 CharDriverState *qemu_chr_open_pty(void)
1222 int master_fd, slave_fd;
1223 struct termios term;
1225 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0)
1226 return NULL;
1228 /* Set raw attributes on the pty. */
1229 cfmakeraw(&term);
1230 tcsetattr(slave_fd, TCSAFLUSH, &term);
1232 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
1233 store_console_dev(domid, ptsname(master_fd));
1235 return qemu_chr_open_fd(master_fd, master_fd);
1237 #else
1238 CharDriverState *qemu_chr_open_pty(void)
1240 return NULL;
1242 #endif
1244 #endif /* !defined(_WIN32) */
1246 CharDriverState *qemu_chr_open(const char *filename)
1248 if (!strcmp(filename, "vc")) {
1249 return text_console_init(&display_state);
1250 } else if (!strcmp(filename, "null")) {
1251 return qemu_chr_open_null();
1252 } else
1253 #ifndef _WIN32
1254 if (!strcmp(filename, "pty")) {
1255 return qemu_chr_open_pty();
1256 } else if (!strcmp(filename, "stdio")) {
1257 return qemu_chr_open_stdio();
1258 } else
1259 #endif
1261 return NULL;
1265 /***********************************************************/
1266 /* Linux network device redirectors */
1268 void hex_dump(FILE *f, const uint8_t *buf, int size)
1270 int len, i, j, c;
1272 for(i=0;i<size;i+=16) {
1273 len = size - i;
1274 if (len > 16)
1275 len = 16;
1276 fprintf(f, "%08x ", i);
1277 for(j=0;j<16;j++) {
1278 if (j < len)
1279 fprintf(f, " %02x", buf[i+j]);
1280 else
1281 fprintf(f, " ");
1283 fprintf(f, " ");
1284 for(j=0;j<len;j++) {
1285 c = buf[i+j];
1286 if (c < ' ' || c > '~')
1287 c = '.';
1288 fprintf(f, "%c", c);
1290 fprintf(f, "\n");
1294 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1296 nd->send_packet(nd, buf, size);
1299 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read,
1300 IOReadHandler *fd_read, void *opaque)
1302 nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1305 /* dummy network adapter */
1307 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1311 static void dummy_add_read_packet(NetDriverState *nd,
1312 IOCanRWHandler *fd_can_read,
1313 IOReadHandler *fd_read, void *opaque)
1317 static int net_dummy_init(NetDriverState *nd)
1319 nd->send_packet = dummy_send_packet;
1320 nd->add_read_packet = dummy_add_read_packet;
1321 pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1322 return 0;
1325 #if defined(CONFIG_SLIRP)
1327 /* slirp network adapter */
1329 static void *slirp_fd_opaque;
1330 static IOCanRWHandler *slirp_fd_can_read;
1331 static IOReadHandler *slirp_fd_read;
1332 static int slirp_inited;
1334 int slirp_can_output(void)
1336 return slirp_fd_can_read(slirp_fd_opaque);
1339 void slirp_output(const uint8_t *pkt, int pkt_len)
1341 #if 0
1342 printf("output:\n");
1343 hex_dump(stdout, pkt, pkt_len);
1344 #endif
1345 slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1348 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1350 #if 0
1351 printf("input:\n");
1352 hex_dump(stdout, buf, size);
1353 #endif
1354 slirp_input(buf, size);
1357 static void slirp_add_read_packet(NetDriverState *nd,
1358 IOCanRWHandler *fd_can_read,
1359 IOReadHandler *fd_read, void *opaque)
1361 slirp_fd_opaque = opaque;
1362 slirp_fd_can_read = fd_can_read;
1363 slirp_fd_read = fd_read;
1366 static int net_slirp_init(NetDriverState *nd)
1368 if (!slirp_inited) {
1369 slirp_inited = 1;
1370 slirp_init();
1372 nd->send_packet = slirp_send_packet;
1373 nd->add_read_packet = slirp_add_read_packet;
1374 pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1375 return 0;
1378 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1380 const char *p, *p1;
1381 int len;
1382 p = *pp;
1383 p1 = strchr(p, sep);
1384 if (!p1)
1385 return -1;
1386 len = p1 - p;
1387 p1++;
1388 if (buf_size > 0) {
1389 if (len > buf_size - 1)
1390 len = buf_size - 1;
1391 memcpy(buf, p, len);
1392 buf[len] = '\0';
1394 *pp = p1;
1395 return 0;
1398 static void net_slirp_redir(const char *redir_str)
1400 int is_udp;
1401 char buf[256], *r;
1402 const char *p;
1403 struct in_addr guest_addr;
1404 int host_port, guest_port;
1406 if (!slirp_inited) {
1407 slirp_inited = 1;
1408 slirp_init();
1411 p = redir_str;
1412 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1413 goto fail;
1414 if (!strcmp(buf, "tcp")) {
1415 is_udp = 0;
1416 } else if (!strcmp(buf, "udp")) {
1417 is_udp = 1;
1418 } else {
1419 goto fail;
1422 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1423 goto fail;
1424 host_port = strtol(buf, &r, 0);
1425 if (r == buf)
1426 goto fail;
1428 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1429 goto fail;
1430 if (buf[0] == '\0') {
1431 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1433 if (!inet_aton(buf, &guest_addr))
1434 goto fail;
1436 guest_port = strtol(p, &r, 0);
1437 if (r == p)
1438 goto fail;
1440 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1441 fprintf(stderr, "qemu: could not set up redirection\n");
1442 exit(1);
1444 return;
1445 fail:
1446 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1447 exit(1);
1450 #ifndef _WIN32
1452 char smb_dir[1024];
1454 static void smb_exit(void)
1456 DIR *d;
1457 struct dirent *de;
1458 char filename[1024];
1460 /* erase all the files in the directory */
1461 d = opendir(smb_dir);
1462 for(;;) {
1463 de = readdir(d);
1464 if (!de)
1465 break;
1466 if (strcmp(de->d_name, ".") != 0 &&
1467 strcmp(de->d_name, "..") != 0) {
1468 snprintf(filename, sizeof(filename), "%s/%s",
1469 smb_dir, de->d_name);
1470 unlink(filename);
1473 closedir(d);
1474 rmdir(smb_dir);
1477 /* automatic user mode samba server configuration */
1478 void net_slirp_smb(const char *exported_dir)
1480 char smb_conf[1024];
1481 char smb_cmdline[1024];
1482 FILE *f;
1484 if (!slirp_inited) {
1485 slirp_inited = 1;
1486 slirp_init();
1489 /* XXX: better tmp dir construction */
1490 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1491 if (mkdir(smb_dir, 0700) < 0) {
1492 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1493 exit(1);
1495 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1497 f = fopen(smb_conf, "w");
1498 if (!f) {
1499 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1500 exit(1);
1502 fprintf(f,
1503 "[global]\n"
1504 "pid directory=%s\n"
1505 "lock directory=%s\n"
1506 "log file=%s/log.smbd\n"
1507 "smb passwd file=%s/smbpasswd\n"
1508 "security = share\n"
1509 "[qemu]\n"
1510 "path=%s\n"
1511 "read only=no\n"
1512 "guest ok=yes\n",
1513 smb_dir,
1514 smb_dir,
1515 smb_dir,
1516 smb_dir,
1517 exported_dir
1518 );
1519 fclose(f);
1520 atexit(smb_exit);
1522 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1523 smb_conf);
1525 slirp_add_exec(0, smb_cmdline, 4, 139);
1528 #endif /* !defined(_WIN32) */
1530 #endif /* CONFIG_SLIRP */
1532 #if !defined(_WIN32)
1533 #ifdef _BSD
1534 static int tun_open(char *ifname, int ifname_size)
1536 int fd;
1537 char *dev;
1538 struct stat s;
1540 fd = open("/dev/tap", O_RDWR);
1541 if (fd < 0) {
1542 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1543 return -1;
1546 fstat(fd, &s);
1547 dev = devname(s.st_rdev, S_IFCHR);
1548 pstrcpy(ifname, ifname_size, dev);
1550 fcntl(fd, F_SETFL, O_NONBLOCK);
1551 return fd;
1553 #else
1554 static int tun_open(char *ifname, int ifname_size)
1556 struct ifreq ifr;
1557 int fd, ret;
1559 fd = open("/dev/net/tun", O_RDWR);
1560 if (fd < 0) {
1561 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1562 return -1;
1564 memset(&ifr, 0, sizeof(ifr));
1565 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1566 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1567 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1568 if (ret != 0) {
1569 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1570 close(fd);
1571 return -1;
1573 fprintf(logfile, "Connected to host network interface: %s\n", ifr.ifr_name);
1574 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1575 fcntl(fd, F_SETFL, O_NONBLOCK);
1576 return fd;
1578 #endif
1580 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1582 write(nd->fd, buf, size);
1585 static void tun_add_read_packet(NetDriverState *nd,
1586 IOCanRWHandler *fd_can_read,
1587 IOReadHandler *fd_read, void *opaque)
1589 qemu_add_fd_event_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1592 static int net_tun_init(NetDriverState *nd)
1594 int pid, status;
1595 char *args[4];
1596 char **parg;
1597 extern int highest_fds;
1599 nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1600 if (nd->fd < 0)
1601 return -1;
1603 if ( nd->fd > highest_fds ) highest_fds = nd->fd;
1604 /* try to launch network init script */
1605 pid = fork();
1606 if (pid >= 0) {
1607 if (pid == 0) {
1608 parg = args;
1609 *parg++ = network_script;
1610 *parg++ = nd->ifname;
1611 *parg++ = bridge;
1612 *parg++ = NULL;
1613 execv(network_script, args);
1614 exit(1);
1616 while (waitpid(pid, &status, 0) != pid);
1617 if (!WIFEXITED(status) ||
1618 WEXITSTATUS(status) != 0) {
1619 fprintf(stderr, "%s: could not launch network script\n",
1620 network_script);
1623 nd->send_packet = tun_send_packet;
1624 nd->add_read_packet = tun_add_read_packet;
1625 return 0;
1628 static int net_fd_init(NetDriverState *nd, int fd)
1630 nd->fd = fd;
1631 nd->send_packet = tun_send_packet;
1632 nd->add_read_packet = tun_add_read_packet;
1633 pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1634 return 0;
1637 #endif /* !_WIN32 */
1639 /***********************************************************/
1640 /* dumb display */
1642 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1646 static void dumb_resize(DisplayState *ds, int w, int h)
1650 static void dumb_refresh(DisplayState *ds)
1652 vga_update_display();
1655 void dumb_display_init(DisplayState *ds)
1657 ds->data = NULL;
1658 ds->linesize = 0;
1659 ds->depth = 0;
1660 ds->dpy_update = dumb_update;
1661 ds->dpy_resize = dumb_resize;
1662 ds->dpy_refresh = dumb_refresh;
1665 #if !defined(CONFIG_SOFTMMU)
1666 /***********************************************************/
1667 /* cpu signal handler */
1668 static void host_segv_handler(int host_signum, siginfo_t *info,
1669 void *puc)
1671 abort();
1673 #endif
1675 /***********************************************************/
1676 /* I/O handling */
1678 #define MAX_IO_HANDLERS 64
1680 typedef struct IOHandlerRecord {
1681 int fd;
1682 IOCanRWHandler *fd_can_read;
1683 IOReadHandler *fd_read;
1684 void *opaque;
1685 /* temporary data */
1686 struct pollfd *ufd;
1687 int max_size;
1688 struct IOHandlerRecord *next;
1689 } IOHandlerRecord;
1691 static IOHandlerRecord *first_io_handler;
1692 static IOHandlerRecord *first_eventio_handler;
1694 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read,
1695 IOReadHandler *fd_read, void *opaque)
1697 IOHandlerRecord *ioh;
1699 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1700 if (!ioh)
1701 return -1;
1702 ioh->fd = fd;
1703 ioh->fd_can_read = fd_can_read;
1704 ioh->fd_read = fd_read;
1705 ioh->opaque = opaque;
1706 ioh->next = first_io_handler;
1707 first_io_handler = ioh;
1708 return 0;
1711 int qemu_add_fd_event_read_handler(int fd, IOCanRWHandler *fd_can_read,
1712 IOReadHandler *fd_read, void *opaque)
1714 IOHandlerRecord *ioh;
1716 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1717 if (!ioh)
1718 return -1;
1719 ioh->fd = fd;
1720 ioh->fd_can_read = fd_can_read;
1721 ioh->fd_read = fd_read;
1722 ioh->opaque = opaque;
1723 ioh->next = first_eventio_handler;
1724 first_eventio_handler = ioh;
1725 return 0;
1728 void qemu_del_fd_read_handler(int fd)
1730 IOHandlerRecord **pioh, *ioh;
1732 pioh = &first_io_handler;
1733 for(;;) {
1734 ioh = *pioh;
1735 if (ioh == NULL)
1736 break;
1737 if (ioh->fd == fd) {
1738 *pioh = ioh->next;
1739 break;
1741 pioh = &ioh->next;
1745 /***********************************************************/
1746 /* savevm/loadvm support */
1748 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1750 fwrite(buf, 1, size, f);
1753 void qemu_put_byte(QEMUFile *f, int v)
1755 fputc(v, f);
1758 void qemu_put_be16(QEMUFile *f, unsigned int v)
1760 qemu_put_byte(f, v >> 8);
1761 qemu_put_byte(f, v);
1764 void qemu_put_be32(QEMUFile *f, unsigned int v)
1766 qemu_put_byte(f, v >> 24);
1767 qemu_put_byte(f, v >> 16);
1768 qemu_put_byte(f, v >> 8);
1769 qemu_put_byte(f, v);
1772 void qemu_put_be64(QEMUFile *f, uint64_t v)
1774 qemu_put_be32(f, v >> 32);
1775 qemu_put_be32(f, v);
1778 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1780 return fread(buf, 1, size, f);
1783 int qemu_get_byte(QEMUFile *f)
1785 int v;
1786 v = fgetc(f);
1787 if (v == EOF)
1788 return 0;
1789 else
1790 return v;
1793 unsigned int qemu_get_be16(QEMUFile *f)
1795 unsigned int v;
1796 v = qemu_get_byte(f) << 8;
1797 v |= qemu_get_byte(f);
1798 return v;
1801 unsigned int qemu_get_be32(QEMUFile *f)
1803 unsigned int v;
1804 v = qemu_get_byte(f) << 24;
1805 v |= qemu_get_byte(f) << 16;
1806 v |= qemu_get_byte(f) << 8;
1807 v |= qemu_get_byte(f);
1808 return v;
1811 uint64_t qemu_get_be64(QEMUFile *f)
1813 uint64_t v;
1814 v = (uint64_t)qemu_get_be32(f) << 32;
1815 v |= qemu_get_be32(f);
1816 return v;
1819 int64_t qemu_ftell(QEMUFile *f)
1821 return ftell(f);
1824 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1826 if (fseek(f, pos, whence) < 0)
1827 return -1;
1828 return ftell(f);
1831 typedef struct SaveStateEntry {
1832 char idstr[256];
1833 int instance_id;
1834 int version_id;
1835 SaveStateHandler *save_state;
1836 LoadStateHandler *load_state;
1837 void *opaque;
1838 struct SaveStateEntry *next;
1839 } SaveStateEntry;
1841 static SaveStateEntry *first_se;
1843 int register_savevm(const char *idstr,
1844 int instance_id,
1845 int version_id,
1846 SaveStateHandler *save_state,
1847 LoadStateHandler *load_state,
1848 void *opaque)
1850 SaveStateEntry *se, **pse;
1852 se = qemu_malloc(sizeof(SaveStateEntry));
1853 if (!se)
1854 return -1;
1855 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1856 se->instance_id = instance_id;
1857 se->version_id = version_id;
1858 se->save_state = save_state;
1859 se->load_state = load_state;
1860 se->opaque = opaque;
1861 se->next = NULL;
1863 /* add at the end of list */
1864 pse = &first_se;
1865 while (*pse != NULL)
1866 pse = &(*pse)->next;
1867 *pse = se;
1868 return 0;
1871 #define QEMU_VM_FILE_MAGIC 0x5145564d
1872 #define QEMU_VM_FILE_VERSION 0x00000001
1874 int qemu_savevm(const char *filename)
1876 SaveStateEntry *se;
1877 QEMUFile *f;
1878 int len, len_pos, cur_pos, saved_vm_running, ret;
1880 saved_vm_running = vm_running;
1881 vm_stop(0);
1883 f = fopen(filename, "wb");
1884 if (!f) {
1885 ret = -1;
1886 goto the_end;
1889 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1890 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1892 for(se = first_se; se != NULL; se = se->next) {
1893 /* ID string */
1894 len = strlen(se->idstr);
1895 qemu_put_byte(f, len);
1896 qemu_put_buffer(f, se->idstr, len);
1898 qemu_put_be32(f, se->instance_id);
1899 qemu_put_be32(f, se->version_id);
1901 /* record size: filled later */
1902 len_pos = ftell(f);
1903 qemu_put_be32(f, 0);
1905 se->save_state(f, se->opaque);
1907 /* fill record size */
1908 cur_pos = ftell(f);
1909 len = ftell(f) - len_pos - 4;
1910 fseek(f, len_pos, SEEK_SET);
1911 qemu_put_be32(f, len);
1912 fseek(f, cur_pos, SEEK_SET);
1915 fclose(f);
1916 ret = 0;
1917 the_end:
1918 if (saved_vm_running)
1919 vm_start();
1920 return ret;
1923 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1925 SaveStateEntry *se;
1927 for(se = first_se; se != NULL; se = se->next) {
1928 if (!strcmp(se->idstr, idstr) &&
1929 instance_id == se->instance_id)
1930 return se;
1932 return NULL;
1935 int qemu_loadvm(const char *filename)
1937 SaveStateEntry *se;
1938 QEMUFile *f;
1939 int len, cur_pos, ret, instance_id, record_len, version_id;
1940 int saved_vm_running;
1941 unsigned int v;
1942 char idstr[256];
1944 saved_vm_running = vm_running;
1945 vm_stop(0);
1947 f = fopen(filename, "rb");
1948 if (!f) {
1949 ret = -1;
1950 goto the_end;
1953 v = qemu_get_be32(f);
1954 if (v != QEMU_VM_FILE_MAGIC)
1955 goto fail;
1956 v = qemu_get_be32(f);
1957 if (v != QEMU_VM_FILE_VERSION) {
1958 fail:
1959 fclose(f);
1960 ret = -1;
1961 goto the_end;
1963 for(;;) {
1964 #if defined (DO_TB_FLUSH)
1965 tb_flush(global_env);
1966 #endif
1967 len = qemu_get_byte(f);
1968 if (feof(f))
1969 break;
1970 qemu_get_buffer(f, idstr, len);
1971 idstr[len] = '\0';
1972 instance_id = qemu_get_be32(f);
1973 version_id = qemu_get_be32(f);
1974 record_len = qemu_get_be32(f);
1975 #if 0
1976 printf("idstr=%s instance=0x%x version=%d len=%d\n",
1977 idstr, instance_id, version_id, record_len);
1978 #endif
1979 cur_pos = ftell(f);
1980 se = find_se(idstr, instance_id);
1981 if (!se) {
1982 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1983 instance_id, idstr);
1984 } else {
1985 ret = se->load_state(f, se->opaque, version_id);
1986 if (ret < 0) {
1987 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1988 instance_id, idstr);
1991 /* always seek to exact end of record */
1992 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1994 fclose(f);
1995 ret = 0;
1996 the_end:
1997 if (saved_vm_running)
1998 vm_start();
1999 return ret;
2002 /***********************************************************/
2003 /* main execution loop */
2005 void gui_update(void *opaque)
2007 display_state.dpy_refresh(&display_state);
2008 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2010 void polling_handler(void *opaque)
2012 #ifndef _WIN32
2013 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2014 IOHandlerRecord *ioh, *ioh_next;
2015 uint8_t buf[4096];
2016 int n, max_size;
2017 #endif
2018 int timeout = 0;
2019 int ret;
2021 #ifdef _WIN32
2022 if (timeout > 0)
2023 Sleep(timeout);
2024 #else
2025 /* poll any events */
2026 /* XXX: separate device handlers from system ones */
2027 pf = ufds;
2028 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2029 if (!ioh->fd_can_read) {
2030 max_size = 0;
2031 pf->fd = ioh->fd;
2032 pf->events = POLLIN;
2033 ioh->ufd = pf;
2034 pf++;
2035 } else {
2036 max_size = ioh->fd_can_read(ioh->opaque);
2037 if (max_size > 0) {
2038 if (max_size > sizeof(buf))
2039 max_size = sizeof(buf);
2040 pf->fd = ioh->fd;
2041 pf->events = POLLIN;
2042 ioh->ufd = pf;
2043 pf++;
2044 } else {
2045 ioh->ufd = NULL;
2048 ioh->max_size = max_size;
2051 ret = poll(ufds, pf - ufds, timeout);
2052 if (ret > 0) {
2053 /* XXX: better handling of removal */
2054 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2055 ioh_next = ioh->next;
2056 pf = ioh->ufd;
2057 if (pf) {
2058 if (pf->revents & POLLIN) {
2059 if (ioh->max_size == 0) {
2060 /* just a read event */
2061 ioh->fd_read(ioh->opaque, NULL, 0);
2062 } else {
2063 n = read(ioh->fd, buf, ioh->max_size);
2064 if (n >= 0) {
2065 ioh->fd_read(ioh->opaque, buf, n);
2066 } else if (errno != EAGAIN) {
2067 ioh->fd_read(ioh->opaque, NULL, -errno);
2074 #endif /* !defined(_WIN32) */
2076 qemu_mod_timer(polling_timer, POLLING_INTERVAL + qemu_get_clock(rt_clock));
2080 /* XXX: support several handlers */
2081 VMStopHandler *vm_stop_cb;
2082 VMStopHandler *vm_stop_opaque;
2084 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2086 vm_stop_cb = cb;
2087 vm_stop_opaque = opaque;
2088 return 0;
2091 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2093 vm_stop_cb = NULL;
2096 void vm_start(void)
2098 if (!vm_running) {
2099 cpu_enable_ticks();
2100 vm_running = 1;
2104 void vm_stop(int reason)
2106 if (vm_running) {
2107 cpu_disable_ticks();
2108 vm_running = 0;
2109 if (reason != 0) {
2110 if (vm_stop_cb) {
2111 vm_stop_cb(vm_stop_opaque, reason);
2117 /* reset/shutdown handler */
2119 typedef struct QEMUResetEntry {
2120 QEMUResetHandler *func;
2121 void *opaque;
2122 struct QEMUResetEntry *next;
2123 } QEMUResetEntry;
2125 static QEMUResetEntry *first_reset_entry;
2126 int reset_requested;
2127 int shutdown_requested;
2129 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2131 QEMUResetEntry **pre, *re;
2133 pre = &first_reset_entry;
2134 while (*pre != NULL)
2135 pre = &(*pre)->next;
2136 re = qemu_mallocz(sizeof(QEMUResetEntry));
2137 re->func = func;
2138 re->opaque = opaque;
2139 re->next = NULL;
2140 *pre = re;
2143 void qemu_system_reset(void)
2145 QEMUResetEntry *re;
2147 /* reset all devices */
2148 for(re = first_reset_entry; re != NULL; re = re->next) {
2149 re->func(re->opaque);
2153 void qemu_system_reset_request(void)
2155 reset_requested = 1;
2156 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2159 void qemu_system_shutdown_request(void)
2161 shutdown_requested = 1;
2162 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2165 void main_loop_wait(int timeout)
2167 if (vm_running) {
2168 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
2169 qemu_get_clock(vm_clock));
2170 /* run dma transfers, if any */
2171 DMA_run();
2174 /* real time timers */
2175 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
2176 qemu_get_clock(rt_clock));
2179 void help(void)
2181 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2182 "usage: %s [options] [disk_image]\n"
2183 "\n"
2184 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2185 "\n"
2186 "Standard options:\n"
2187 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
2188 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
2189 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
2190 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2191 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2192 "-snapshot write to temporary files instead of disk image files\n"
2193 "-m megs set virtual RAM size to megs MB [default=%d]\n"
2194 "-nographic disable graphical output and redirect serial I/Os to console\n"
2195 "-vcpus set CPU number of guest platform\n"
2196 #ifdef CONFIG_VNC
2197 "-vnc port use vnc instead of sdl\n"
2198 "-vncport port use a different port\n"
2199 "-vncconnect host:port do a reverse connect\n"
2200 #ifdef CONFIG_SDL
2201 "-vnc-and-sdl use vnc and sdl simultaneously\n"
2202 #endif
2203 #endif
2204 "-k <language> use keyboard layout (for example \"fr\" for french)\n"
2205 "-enable-audio enable audio support\n"
2206 "-localtime set the real time clock to local time [default=utc]\n"
2207 "-full-screen start in full screen\n"
2208 #ifdef TARGET_PPC
2209 "-prep Simulate a PREP system (default is PowerMAC)\n"
2210 "-g WxH[xDEPTH] Set the initial VGA graphic mode\n"
2211 #endif
2212 "-nic-ne2000 simulate an Realtek ne2k PCI ethernet adaptor\n"
2213 "\n"
2214 "Network options:\n"
2215 "-nics n simulate 'n' network cards [default=1]\n"
2216 "-macaddr addr set the mac address of the first interface\n"
2217 "-bridge br set the bridge interface for nic\n"
2218 "-n script set tap/tun network init script [default=%s]\n"
2219 "-tun-fd fd use this fd as already opened tap/tun interface\n"
2220 #ifdef CONFIG_SLIRP
2221 "-user-net use user mode network stack [default if no tap/tun script]\n"
2222 "-tftp prefix allow tftp access to files starting with prefix [-user-net]\n"
2223 #ifndef _WIN32
2224 "-smb dir allow SMB access to files in 'dir' [-user-net]\n"
2225 #endif
2226 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2227 " redirect TCP or UDP connections from host to guest [-user-net]\n"
2228 #endif
2229 "-dummy-net use dummy network stack\n"
2230 "\n"
2231 "Linux boot specific:\n"
2232 "-kernel bzImage use 'bzImage' as kernel image\n"
2233 "-append cmdline use 'cmdline' as kernel command line\n"
2234 "-initrd file use 'file' as initial ram disk\n"
2235 "\n"
2236 "Debug/Expert options:\n"
2237 "-monitor dev redirect the monitor to char device 'dev'\n"
2238 "-serial dev redirect the serial port to char device 'dev'\n"
2239 "-S freeze CPU at startup (use 'c' to start execution)\n"
2240 "-s wait gdb connection to port %d\n"
2241 "-p port ioreq port for xen\n"
2242 "-d domain domain that we're serving\n"
2243 "-domain-namn domain name that we're serving\n"
2244 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
2245 "-L path set the directory for the BIOS and VGA BIOS\n"
2246 #ifdef USE_CODE_COPY
2247 "-no-code-copy disable code copy acceleration\n"
2248 #endif
2249 #ifdef TARGET_I386
2250 "-isa simulate an ISA-only system (default is PCI system)\n"
2251 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
2252 " (default is CL-GD5446 PCI VGA)\n"
2253 "-vgaacc [0|1] 1 to accelerate CL-GD5446 speed, default is 1\n"
2254 "-no-repeatkey disable key repeat feature for SDL keyboard simulation"
2255 #endif
2256 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
2257 "\n"
2258 "During emulation, the following keys are useful:\n"
2259 "ctrl-alt-f toggle full screen\n"
2260 "ctrl-alt-n switch to virtual console 'n'\n"
2261 "ctrl-alt toggle mouse and keyboard grab\n"
2262 "\n"
2263 "When using -nographic, press 'ctrl-a h' to get some help.\n"
2265 #ifdef CONFIG_SOFTMMU
2266 "qemu",
2267 #else
2268 "qemu-fast",
2269 #endif
2270 DEFAULT_RAM_SIZE,
2271 DEFAULT_NETWORK_SCRIPT,
2272 DEFAULT_GDBSTUB_PORT);
2273 #ifndef CONFIG_SOFTMMU
2274 printf("\n"
2275 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2276 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2277 "PC emulation.\n");
2278 #endif
2279 exit(1);
2282 #define HAS_ARG 0x0001
2284 enum {
2285 QEMU_OPTION_h,
2287 QEMU_OPTION_fda,
2288 QEMU_OPTION_fdb,
2289 QEMU_OPTION_hda,
2290 QEMU_OPTION_hdb,
2291 QEMU_OPTION_hdc,
2292 QEMU_OPTION_hdd,
2293 QEMU_OPTION_cdrom,
2294 QEMU_OPTION_boot,
2295 QEMU_OPTION_snapshot,
2296 QEMU_OPTION_m,
2297 QEMU_OPTION_nographic,
2298 #ifdef CONFIG_VNC
2299 QEMU_OPTION_vnc,
2300 QEMU_OPTION_vncport,
2301 QEMU_OPTION_vncconnect,
2302 #ifdef CONFIG_SDL
2303 QEMU_OPTION_vnc_and_sdl,
2304 #endif
2305 #endif
2306 QEMU_OPTION_enable_audio,
2308 QEMU_OPTION_nics,
2309 QEMU_OPTION_macaddr,
2310 QEMU_OPTION_bridge,
2311 QEMU_OPTION_n,
2312 QEMU_OPTION_tun_fd,
2313 QEMU_OPTION_user_net,
2314 QEMU_OPTION_tftp,
2315 QEMU_OPTION_smb,
2316 QEMU_OPTION_redir,
2317 QEMU_OPTION_dummy_net,
2319 QEMU_OPTION_kernel,
2320 QEMU_OPTION_append,
2321 QEMU_OPTION_initrd,
2323 QEMU_OPTION_S,
2324 QEMU_OPTION_s,
2325 QEMU_OPTION_p,
2326 QEMU_OPTION_d,
2327 QEMU_OPTION_l,
2328 QEMU_OPTION_hdachs,
2329 QEMU_OPTION_L,
2330 QEMU_OPTION_no_code_copy,
2331 QEMU_OPTION_vcpus,
2332 QEMU_OPTION_pci,
2333 QEMU_OPTION_nic_ne2000,
2334 QEMU_OPTION_isa,
2335 QEMU_OPTION_prep,
2336 QEMU_OPTION_k,
2337 QEMU_OPTION_localtime,
2338 QEMU_OPTION_cirrusvga,
2339 QEMU_OPTION_g,
2340 QEMU_OPTION_std_vga,
2341 QEMU_OPTION_monitor,
2342 QEMU_OPTION_domainname,
2343 QEMU_OPTION_serial,
2344 QEMU_OPTION_loadvm,
2345 QEMU_OPTION_full_screen,
2346 QEMU_OPTION_vgaacc,
2347 QEMU_OPTION_repeatkey,
2348 };
2350 typedef struct QEMUOption {
2351 const char *name;
2352 int flags;
2353 int index;
2354 } QEMUOption;
2356 const QEMUOption qemu_options[] = {
2357 { "h", 0, QEMU_OPTION_h },
2359 { "fda", HAS_ARG, QEMU_OPTION_fda },
2360 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2361 { "hda", HAS_ARG, QEMU_OPTION_hda },
2362 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2363 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2364 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2365 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2366 { "boot", HAS_ARG, QEMU_OPTION_boot },
2367 { "snapshot", 0, QEMU_OPTION_snapshot },
2368 { "m", HAS_ARG, QEMU_OPTION_m },
2369 { "nographic", 0, QEMU_OPTION_nographic },
2370 #ifdef CONFIG_VNC
2371 { "vnc", 0, QEMU_OPTION_vnc },
2372 { "vncport", HAS_ARG, QEMU_OPTION_vncport },
2373 { "vncconnect", HAS_ARG, QEMU_OPTION_vncconnect },
2374 #ifdef CONFIG_SDL
2375 { "vnc-and-sdl", 0, QEMU_OPTION_vnc_and_sdl },
2376 #endif
2377 #endif
2378 { "k", HAS_ARG, QEMU_OPTION_k },
2379 { "enable-audio", 0, QEMU_OPTION_enable_audio },
2381 { "nics", HAS_ARG, QEMU_OPTION_nics},
2382 { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2383 { "bridge", HAS_ARG, QEMU_OPTION_bridge},
2384 { "n", HAS_ARG, QEMU_OPTION_n },
2385 { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2386 #ifdef CONFIG_SLIRP
2387 { "user-net", 0, QEMU_OPTION_user_net },
2388 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2389 #ifndef _WIN32
2390 { "smb", HAS_ARG, QEMU_OPTION_smb },
2391 #endif
2392 { "redir", HAS_ARG, QEMU_OPTION_redir },
2393 #endif
2394 { "dummy-net", 0, QEMU_OPTION_dummy_net },
2396 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2397 { "append", HAS_ARG, QEMU_OPTION_append },
2398 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2400 { "S", 0, QEMU_OPTION_S },
2401 { "s", 0, QEMU_OPTION_s },
2402 { "p", HAS_ARG, QEMU_OPTION_p },
2403 { "d", HAS_ARG, QEMU_OPTION_d },
2404 { "l", HAS_ARG, QEMU_OPTION_l },
2405 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2406 { "L", HAS_ARG, QEMU_OPTION_L },
2407 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2408 { "vcpus", 1, QEMU_OPTION_vcpus },
2409 #ifdef TARGET_PPC
2410 { "prep", 0, QEMU_OPTION_prep },
2411 { "g", 1, QEMU_OPTION_g },
2412 #endif
2413 { "localtime", 0, QEMU_OPTION_localtime },
2414 { "isa", 0, QEMU_OPTION_isa },
2415 { "std-vga", 0, QEMU_OPTION_std_vga },
2416 { "monitor", 1, QEMU_OPTION_monitor },
2417 { "domain-name", 1, QEMU_OPTION_domainname },
2418 { "serial", 1, QEMU_OPTION_serial },
2419 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2420 { "full-screen", 0, QEMU_OPTION_full_screen },
2422 /* temporary options */
2423 { "pci", 0, QEMU_OPTION_pci },
2424 { "nic-ne2000", 0, QEMU_OPTION_nic_ne2000 },
2425 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2426 { "vgaacc", HAS_ARG, QEMU_OPTION_vgaacc },
2427 { "no-repeatkey", 0, QEMU_OPTION_repeatkey },
2428 { NULL },
2429 };
2431 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2433 /* this stack is only used during signal handling */
2434 #define SIGNAL_STACK_SIZE 32768
2436 static uint8_t *signal_stack;
2438 #endif
2440 #define NET_IF_TUN 0
2441 #define NET_IF_USER 1
2442 #define NET_IF_DUMMY 2
2444 #include <xg_private.h>
2446 #if defined(__i386__) || defined (__x86_64__)
2447 #define L1_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_USER)
2448 #define L2_PROT (_PAGE_PRESENT|_PAGE_RW|_PAGE_ACCESSED|_PAGE_DIRTY|_PAGE_USER)
2450 #ifdef __i386__
2451 #define _LEVEL_3_ 0
2452 #else
2453 #define _LEVEL_3_ 1
2454 #endif
2456 #if _LEVEL_3_
2457 #define L3_PROT (_PAGE_PRESENT)
2458 #define L1_PAGETABLE_ENTRIES 512
2459 #else
2460 #define L1_PAGETABLE_ENTRIES 1024
2461 #endif
2463 inline int
2464 get_vl2_table(unsigned long count, unsigned long start)
2466 #if _LEVEL_3_
2467 return ((start + (count << PAGE_SHIFT)) >> L3_PAGETABLE_SHIFT) & 0x3;
2468 #else
2469 return 0;
2470 #endif
2473 int
2474 setup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2475 unsigned long *mem_page_array, unsigned long *page_table_array,
2476 unsigned long v_start, unsigned long v_end)
2478 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2479 l2_pgentry_t *vl2tab[4] = {NULL, NULL, NULL, NULL};
2480 l2_pgentry_t *vl2e=NULL, *vl2_table = NULL;
2481 unsigned long l1tab;
2482 unsigned long ppt_alloc = 0;
2483 unsigned long count;
2484 int i = 0;
2485 #if _LEVEL_3_
2486 l3_pgentry_t *vl3tab = NULL;
2487 unsigned long l2tab;
2489 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2490 PROT_READ|PROT_WRITE,
2491 toptab >> PAGE_SHIFT)) == NULL )
2492 goto error_out;
2493 for (i = 0; i < 4 ; i++) {
2494 l2tab = vl3tab[i] & PAGE_MASK;
2495 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2496 PROT_READ|PROT_WRITE,
2497 l2tab >> PAGE_SHIFT);
2498 if(vl2tab[i] == NULL)
2499 goto error_out;
2501 munmap(vl3tab, PAGE_SIZE);
2502 vl3tab = NULL;
2503 #else
2504 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2505 PROT_READ|PROT_WRITE,
2506 toptab >> PAGE_SHIFT)) == NULL )
2507 goto error_out;
2508 #endif
2510 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ )
2512 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2514 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2515 vl2e = &vl2_table[l2_table_offset(v_start +
2516 (count << PAGE_SHIFT))];
2518 l1tab = page_table_array[ppt_alloc++] << PAGE_SHIFT;
2519 if ( vl1tab != NULL )
2520 munmap(vl1tab, PAGE_SIZE);
2522 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2523 PROT_READ|PROT_WRITE,
2524 l1tab >> PAGE_SHIFT)) == NULL )
2526 goto error_out;
2528 memset(vl1tab, 0, PAGE_SIZE);
2529 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2530 *vl2e = l1tab | L2_PROT;
2533 *vl1e = (mem_page_array[count] << PAGE_SHIFT) | L1_PROT;
2534 vl1e++;
2536 error_out:
2537 if (vl1tab)
2538 munmap(vl1tab, PAGE_SIZE);
2539 for(i = 0; i < 4; i++)
2540 if(vl2tab[i]) munmap(vl2tab[i], PAGE_SIZE);
2541 return ppt_alloc;
2544 void
2545 unsetup_mapping(int xc_handle, uint32_t dom, unsigned long toptab,
2546 unsigned long v_start, unsigned long v_end)
2548 l1_pgentry_t *vl1tab=NULL, *vl1e=NULL;
2549 l2_pgentry_t *vl2tab[4], *vl2e=NULL, *vl2_table = NULL;
2550 unsigned long l1tab;
2551 unsigned long count;
2552 int i = 0;
2553 #if _LEVEL_3_
2554 l3_pgentry_t *vl3tab = NULL;
2555 unsigned long l2tab;
2557 if ( (vl3tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2558 PROT_READ|PROT_WRITE,
2559 toptab >> PAGE_SHIFT)) == NULL )
2560 goto error_out;
2561 for (i = 0; i < 4 ; i ++) {
2562 l2tab = vl3tab[i] & PAGE_MASK;
2563 vl2tab[i] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2564 PROT_READ|PROT_WRITE,
2565 l2tab >> PAGE_SHIFT);
2566 if (vl2tab[i] == NULL)
2567 goto error_out;
2569 munmap(vl3tab, PAGE_SIZE);
2570 vl3tab = NULL;
2571 #else
2572 if ( (vl2tab[0] = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2573 PROT_READ|PROT_WRITE,
2574 toptab >> PAGE_SHIFT)) == NULL )
2575 goto error_out;
2576 #endif
2578 for ( count = 0; count < ((v_end-v_start)>>PAGE_SHIFT); count++ ) {
2579 if ( ((unsigned long)vl1e & (PAGE_SIZE-1)) == 0 )
2581 vl2_table = vl2tab[get_vl2_table(count, v_start)];
2582 vl2e = &vl2_table[l2_table_offset(v_start + (count << PAGE_SHIFT))];
2583 l1tab = *vl2e & PAGE_MASK;
2585 if(l1tab == 0)
2586 continue;
2587 if ( vl1tab != NULL )
2588 munmap(vl1tab, PAGE_SIZE);
2590 if ( (vl1tab = xc_map_foreign_range(xc_handle, dom, PAGE_SIZE,
2591 PROT_READ|PROT_WRITE,
2592 l1tab >> PAGE_SHIFT)) == NULL )
2594 goto error_out;
2596 vl1e = &vl1tab[l1_table_offset(v_start + (count<<PAGE_SHIFT))];
2597 *vl2e = 0;
2600 *vl1e = 0;
2601 vl1e++;
2604 error_out:
2605 if (vl1tab)
2606 munmap(vl1tab, PAGE_SIZE);
2607 for(i = 0; i < 4; i++)
2608 if (vl2tab[i])
2609 munmap(vl2tab[i], PAGE_SIZE);
2612 void set_vram_mapping(unsigned long addr, unsigned long end)
2614 end = addr + VGA_RAM_SIZE;
2615 setup_mapping(xc_handle, domid, toptab,
2616 vgapage_array, freepage_array, addr, end);
2619 void unset_vram_mapping(unsigned long addr, unsigned long end)
2621 end = addr + VGA_RAM_SIZE;
2622 /* FIXME Flush the shadow page */
2623 unsetup_mapping(xc_handle, domid, toptab, addr, end);
2625 #elif defined(__ia64__)
2626 void set_vram_mapping(unsigned long addr, unsigned long end) {}
2627 void unset_vram_mapping(unsigned long addr, unsigned long end) {}
2628 #endif
2630 int main(int argc, char **argv)
2632 #ifdef CONFIG_GDBSTUB
2633 int use_gdbstub, gdbstub_port;
2634 #endif
2635 int i, has_cdrom;
2636 int snapshot, linux_boot;
2637 CPUState *env;
2638 const char *initrd_filename;
2639 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2640 const char *kernel_filename, *kernel_cmdline;
2641 DisplayState *ds = &display_state;
2642 int cyls, heads, secs;
2643 int start_emulation = 1;
2644 uint8_t macaddr[6];
2645 int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2646 int optind;
2647 const char *r, *optarg;
2648 CharDriverState *monitor_hd;
2649 char monitor_device[128];
2650 char serial_devices[MAX_SERIAL_PORTS][128];
2651 int serial_device_index;
2652 char qemu_dm_logfilename[64];
2653 const char *loadvm = NULL;
2654 unsigned long nr_pages, extra_pages, ram_pages, *page_array;
2655 extern void *shared_page;
2656 extern void *shared_vram;
2658 #if !defined(CONFIG_SOFTMMU)
2659 /* we never want that malloc() uses mmap() */
2660 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2661 #endif
2662 initrd_filename = NULL;
2663 for(i = 0; i < MAX_FD; i++)
2664 fd_filename[i] = NULL;
2665 for(i = 0; i < MAX_DISKS; i++)
2666 hd_filename[i] = NULL;
2667 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2668 vga_ram_size = VGA_RAM_SIZE;
2669 bios_size = BIOS_SIZE;
2670 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2671 #ifdef CONFIG_GDBSTUB
2672 use_gdbstub = 0;
2673 gdbstub_port = DEFAULT_GDBSTUB_PORT;
2674 #endif
2675 snapshot = 0;
2676 nographic = 0;
2677 usevnc = 0;
2678 vncport=0;
2679 vncconnect=NULL;
2680 kernel_filename = NULL;
2681 kernel_cmdline = "";
2682 has_cdrom = 1;
2683 cyls = heads = secs = 0;
2684 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2686 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2687 for(i = 1; i < MAX_SERIAL_PORTS; i++)
2688 serial_devices[i][0] = '\0';
2689 serial_device_index = 0;
2691 nb_tun_fds = 0;
2692 net_if_type = -1;
2693 nb_nics = 1;
2694 /* default mac address of the first network interface */
2695 macaddr[0] = 0x52;
2696 macaddr[1] = 0x54;
2697 macaddr[2] = 0x00;
2698 macaddr[3] = 0x12;
2699 macaddr[4] = 0x34;
2700 macaddr[5] = 0x56;
2702 /* init debug */
2703 sprintf(qemu_dm_logfilename, "/var/log/qemu-dm.%d.log", getpid());
2704 cpu_set_log_filename(qemu_dm_logfilename);
2705 cpu_set_log(0);
2707 optind = 1;
2708 for(;;) {
2709 if (optind >= argc)
2710 break;
2711 r = argv[optind];
2712 if (r[0] != '-') {
2713 hd_filename[0] = argv[optind++];
2714 } else {
2715 const QEMUOption *popt;
2717 optind++;
2718 popt = qemu_options;
2719 for(;;) {
2720 if (!popt->name) {
2721 fprintf(stderr, "%s: invalid option -- '%s'\n",
2722 argv[0], r);
2723 exit(1);
2725 if (!strcmp(popt->name, r + 1))
2726 break;
2727 popt++;
2729 if (popt->flags & HAS_ARG) {
2730 if (optind >= argc) {
2731 fprintf(stderr, "%s: option '%s' requires an argument\n",
2732 argv[0], r);
2733 exit(1);
2735 optarg = argv[optind++];
2736 } else {
2737 optarg = NULL;
2740 switch(popt->index) {
2741 case QEMU_OPTION_initrd:
2742 initrd_filename = optarg;
2743 break;
2744 case QEMU_OPTION_hda:
2745 hd_filename[0] = optarg;
2746 break;
2747 case QEMU_OPTION_hdb:
2748 hd_filename[1] = optarg;
2749 break;
2750 case QEMU_OPTION_snapshot:
2751 snapshot = 1;
2752 break;
2753 case QEMU_OPTION_hdachs:
2755 const char *p;
2756 p = optarg;
2757 cyls = strtol(p, (char **)&p, 0);
2758 if (*p != ',')
2759 goto chs_fail;
2760 p++;
2761 heads = strtol(p, (char **)&p, 0);
2762 if (*p != ',')
2763 goto chs_fail;
2764 p++;
2765 secs = strtol(p, (char **)&p, 0);
2766 if (*p != '\0') {
2767 chs_fail:
2768 cyls = 0;
2771 break;
2772 case QEMU_OPTION_nographic:
2773 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
2774 if(!strcmp(serial_devices[0], "vc"))
2775 pstrcpy(serial_devices[0], sizeof(serial_devices[0]),
2776 "stdio");
2777 nographic = 1;
2778 break;
2779 #ifdef CONFIG_VNC
2780 case QEMU_OPTION_vnc:
2781 usevnc = 1;
2782 break;
2783 case QEMU_OPTION_vncport:
2785 const char *p;
2786 p = optarg;
2787 vncport= strtol(optarg, (char **)&p, 0);
2789 break;
2790 case QEMU_OPTION_vncconnect:
2791 vncconnect = optarg;
2792 break;
2793 #ifdef CONFIG_SDL
2794 case QEMU_OPTION_vnc_and_sdl:
2795 usevnc = 2;
2796 break;
2797 #endif
2798 #endif
2799 case QEMU_OPTION_kernel:
2800 kernel_filename = optarg;
2801 break;
2802 case QEMU_OPTION_append:
2803 kernel_cmdline = optarg;
2804 break;
2805 case QEMU_OPTION_tun_fd:
2807 const char *p;
2808 int fd;
2809 net_if_type = NET_IF_TUN;
2810 if ( nb_tun_fds < MAX_NICS ) {
2811 fd = strtol(optarg, (char **)&p, 0);
2812 if (*p != '\0') {
2813 fprintf(stderr,
2814 "qemu: invalid fd for network interface %d\n",
2815 nb_tun_fds);
2816 exit(1);
2818 tun_fds[nb_tun_fds++] = fd;
2821 break;
2822 case QEMU_OPTION_hdc:
2823 hd_filename[2] = optarg;
2824 has_cdrom = 0;
2825 break;
2826 case QEMU_OPTION_hdd:
2827 hd_filename[3] = optarg;
2828 break;
2829 case QEMU_OPTION_cdrom:
2830 hd_filename[2] = optarg;
2831 has_cdrom = 1;
2832 break;
2833 case QEMU_OPTION_boot:
2834 boot_device = optarg[0];
2835 if ( boot_device != 'a' &&
2836 boot_device != 'c' &&
2837 boot_device != 'd' ) {
2838 fprintf(stderr, "qemu: invalid boot device '%c'\n",
2839 boot_device);
2840 exit(1);
2842 break;
2843 case QEMU_OPTION_fda:
2844 fd_filename[0] = optarg;
2845 break;
2846 case QEMU_OPTION_fdb:
2847 fd_filename[1] = optarg;
2848 break;
2849 case QEMU_OPTION_nics:
2850 nb_nics = atoi(optarg);
2851 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2852 fprintf(stderr,
2853 "qemu: invalid number of network interfaces\n");
2854 exit(1);
2856 break;
2857 case QEMU_OPTION_bridge:
2858 pstrcpy(bridge, sizeof(bridge), optarg);
2859 break;
2860 case QEMU_OPTION_macaddr:
2862 const char *p;
2863 int i;
2865 p = optarg;
2866 for (i = 0; i < 6; i++) {
2867 macaddr[i] = strtol(p, (char **)&p, 16);
2868 if (i == 5) {
2869 if (*p != '\0')
2870 goto macaddr_error;
2871 } else {
2872 if (*p != ':') {
2873 macaddr_error:
2874 fprintf(stderr, "qemu: invalid syntax "
2875 "for ethernet address\n");
2876 exit(1);
2878 p++;
2882 break;
2883 #ifdef CONFIG_SLIRP
2884 case QEMU_OPTION_tftp:
2885 tftp_prefix = optarg;
2886 break;
2887 #ifndef _WIN32
2888 case QEMU_OPTION_smb:
2889 net_slirp_smb(optarg);
2890 break;
2891 #endif
2892 case QEMU_OPTION_user_net:
2893 net_if_type = NET_IF_USER;
2894 break;
2895 case QEMU_OPTION_redir:
2896 net_slirp_redir(optarg);
2897 break;
2898 #endif
2899 case QEMU_OPTION_dummy_net:
2900 net_if_type = NET_IF_DUMMY;
2901 break;
2902 case QEMU_OPTION_enable_audio:
2903 audio_enabled = 1;
2904 break;
2905 case QEMU_OPTION_h:
2906 help();
2907 break;
2908 case QEMU_OPTION_m:
2909 ram_size = atol(optarg) * 1024 * 1024;
2910 if (ram_size <= 0)
2911 help();
2912 break;
2913 case QEMU_OPTION_d:
2915 domid = atoi(optarg);
2916 fprintf(logfile, "domid: %d\n", domid);
2918 break;
2919 case QEMU_OPTION_p:
2921 extern evtchn_port_t ioreq_remote_port;
2922 ioreq_remote_port = atoi(optarg);
2923 fprintf(logfile, "eport: %d\n", ioreq_remote_port);
2925 break;
2926 case QEMU_OPTION_l:
2928 int mask;
2929 mask = cpu_str_to_log_mask(optarg);
2930 fprintf(logfile, "mask: %x\n", mask);
2931 cpu_set_log(mask);
2933 break;
2934 case QEMU_OPTION_n:
2935 pstrcpy(network_script, sizeof(network_script), optarg);
2936 break;
2937 #ifdef CONFIG_GDBSTUB
2938 case QEMU_OPTION_s:
2939 use_gdbstub = 1;
2940 break;
2941 #endif
2942 case QEMU_OPTION_L:
2943 bios_dir = optarg;
2944 break;
2945 case QEMU_OPTION_S:
2946 start_emulation = 0;
2947 break;
2948 case QEMU_OPTION_vcpus:
2949 vcpus = atoi(optarg);
2950 fprintf(logfile, "qemu: the number of cpus is %d\n", vcpus);
2951 break;
2952 case QEMU_OPTION_pci:
2953 pci_enabled = 1;
2954 break;
2955 case QEMU_OPTION_nic_ne2000:
2956 nic_ne2000 = 1;
2957 break;
2958 case QEMU_OPTION_isa:
2959 pci_enabled = 0;
2960 break;
2961 case QEMU_OPTION_prep:
2962 prep_enabled = 1;
2963 break;
2964 case QEMU_OPTION_k:
2965 keyboard_layout = optarg;
2966 break;
2967 case QEMU_OPTION_localtime:
2968 rtc_utc = 0;
2969 break;
2970 case QEMU_OPTION_cirrusvga:
2971 cirrus_vga_enabled = 1;
2972 break;
2973 case QEMU_OPTION_vgaacc:
2975 const char *p;
2976 p = optarg;
2977 vga_accelerate = strtol(p, (char **)&p, 0);
2978 if (*p != '\0') {
2979 fprintf(stderr, "qemu: invalid vgaacc option\n");
2980 exit(1);
2983 break;
2984 case QEMU_OPTION_repeatkey:
2985 repeat_key = 0;
2986 break;
2987 case QEMU_OPTION_std_vga:
2988 cirrus_vga_enabled = 0;
2989 break;
2990 case QEMU_OPTION_g:
2992 const char *p;
2993 int w, h, depth;
2994 p = optarg;
2995 w = strtol(p, (char **)&p, 10);
2996 if (w <= 0) {
2997 graphic_error:
2998 fprintf(stderr, "qemu: invalid resolution or depth\n");
2999 exit(1);
3001 if (*p != 'x')
3002 goto graphic_error;
3003 p++;
3004 h = strtol(p, (char **)&p, 10);
3005 if (h <= 0)
3006 goto graphic_error;
3007 if (*p == 'x') {
3008 p++;
3009 depth = strtol(p, (char **)&p, 10);
3010 if (depth != 8 && depth != 15 && depth != 16 &&
3011 depth != 24 && depth != 32)
3012 goto graphic_error;
3013 } else if (*p == '\0') {
3014 depth = graphic_depth;
3015 } else {
3016 goto graphic_error;
3019 graphic_width = w;
3020 graphic_height = h;
3021 graphic_depth = depth;
3023 break;
3024 case QEMU_OPTION_monitor:
3025 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3026 break;
3027 case QEMU_OPTION_serial:
3028 if (serial_device_index >= MAX_SERIAL_PORTS) {
3029 fprintf(stderr, "qemu: too many serial ports\n");
3030 exit(1);
3032 pstrcpy(serial_devices[serial_device_index],
3033 sizeof(serial_devices[0]), optarg);
3034 serial_device_index++;
3035 break;
3036 case QEMU_OPTION_loadvm:
3037 loadvm = optarg;
3038 break;
3039 case QEMU_OPTION_full_screen:
3040 full_screen = 1;
3041 break;
3042 case QEMU_OPTION_domainname:
3043 strncat(domain_name, optarg, sizeof(domain_name) - 20);
3044 break;
3050 linux_boot = (kernel_filename != NULL);
3052 if ( !linux_boot && hd_filename[0] == '\0' &&
3053 hd_filename[2] == '\0' && fd_filename[0] == '\0' )
3054 help();
3056 /* boot to cd by default if no hard disk */
3057 if (hd_filename[0] == '\0' && boot_device == 'c') {
3058 if (fd_filename[0] != '\0')
3059 boot_device = 'a';
3060 else
3061 boot_device = 'd';
3064 #if !defined(CONFIG_SOFTMMU)
3065 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3067 static uint8_t stdout_buf[4096];
3068 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3070 #else
3071 setvbuf(stdout, NULL, _IOLBF, 0);
3072 #endif
3074 /* init host network redirectors */
3075 if (net_if_type == -1) {
3076 net_if_type = NET_IF_TUN;
3077 #if defined(CONFIG_SLIRP)
3078 if (access(network_script, R_OK) < 0) {
3079 net_if_type = NET_IF_USER;
3081 #endif
3084 for(i = 0; i < nb_nics; i++) {
3085 NetDriverState *nd = &nd_table[i];
3086 nd->index = i;
3087 /* init virtual mac address */
3088 nd->macaddr[0] = macaddr[0];
3089 nd->macaddr[1] = macaddr[1];
3090 nd->macaddr[2] = macaddr[2];
3091 nd->macaddr[3] = macaddr[3];
3092 nd->macaddr[4] = macaddr[4];
3093 nd->macaddr[5] = macaddr[5] + i;
3094 switch(net_if_type) {
3095 #if defined(CONFIG_SLIRP)
3096 case NET_IF_USER:
3097 net_slirp_init(nd);
3098 break;
3099 #endif
3100 #if !defined(_WIN32)
3101 case NET_IF_TUN:
3102 if (i < nb_tun_fds) {
3103 net_fd_init(nd, tun_fds[i]);
3104 } else {
3105 if (net_tun_init(nd) < 0)
3106 net_dummy_init(nd);
3108 break;
3109 #endif
3110 case NET_IF_DUMMY:
3111 default:
3112 net_dummy_init(nd);
3113 break;
3117 /* init the memory */
3118 phys_ram_size = ram_size + vga_ram_size + bios_size;
3120 ram_pages = ram_size/PAGE_SIZE;
3121 #if defined(__i386__) || defined(__x86_64__)
3122 vgaram_pages = (vga_ram_size -1)/PAGE_SIZE + 1;
3123 free_pages = vgaram_pages / L1_PAGETABLE_ENTRIES;
3124 extra_pages = vgaram_pages + free_pages;
3125 #else
3126 /* Test vga acceleration later */
3127 extra_pages = 0;
3128 #endif
3130 xc_handle = xc_interface_open();
3132 xc_dominfo_t info;
3133 xc_domain_getinfo(xc_handle, domid, 1, &info);
3135 nr_pages = info.nr_pages + extra_pages;
3137 if ( xc_domain_setmaxmem(xc_handle, domid,
3138 (nr_pages) * PAGE_SIZE/1024 ) != 0)
3140 fprintf(logfile, "set maxmem returned error %d\n", errno);
3141 exit(-1);
3144 if ( (page_array = (unsigned long *)
3145 malloc(nr_pages * sizeof(unsigned long))) == NULL)
3147 fprintf(logfile, "malloc returned error %d\n", errno);
3148 exit(-1);
3151 if (xc_domain_memory_increase_reservation(xc_handle, domid,
3152 extra_pages , 0, 0, NULL) != 0)
3154 fprintf(logfile, "increase reservation returned error %d\n", errno);
3155 exit(-1);
3158 #if defined(__i386__) || defined(__x86_64__)
3159 if ( xc_get_pfn_list(xc_handle, domid, page_array, nr_pages) != nr_pages )
3161 fprintf(logfile, "xc_get_pfn_list returned error %d\n", errno);
3162 exit(-1);
3165 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3166 PROT_READ|PROT_WRITE,
3167 page_array,
3168 ram_pages - 1)) == 0 )
3170 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3171 exit(-1);
3174 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3175 PROT_READ|PROT_WRITE,
3176 page_array[ram_pages - 1]);
3178 vgapage_array = &page_array[nr_pages - vgaram_pages];
3180 if ( (shared_vram = xc_map_foreign_batch(xc_handle, domid,
3181 PROT_READ|PROT_WRITE,
3182 vgapage_array,
3183 vgaram_pages)) == 0)
3185 fprintf(logfile,
3186 "xc_map_foreign_batch vgaram returned error %d\n", errno);
3187 exit(-1);
3190 memset(shared_vram, 0, vgaram_pages * PAGE_SIZE);
3191 toptab = page_array[ram_pages] << PAGE_SHIFT;
3193 vtop_table = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3194 PROT_READ|PROT_WRITE,
3195 page_array[ram_pages]);
3197 freepage_array = &page_array[nr_pages - extra_pages];
3198 #elif defined(__ia64__)
3199 if ( xc_ia64_get_pfn_list(xc_handle, domid, page_array, 0, ram_pages)
3200 != ram_pages )
3202 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3203 exit(-1);
3206 if ( (phys_ram_base = xc_map_foreign_batch(xc_handle, domid,
3207 PROT_READ|PROT_WRITE,
3208 page_array,
3209 ram_pages)) == 0 )
3211 fprintf(logfile, "xc_map_foreign_batch returned error %d\n", errno);
3212 exit(-1);
3215 if ( xc_ia64_get_pfn_list(xc_handle, domid,
3216 page_array, IO_PAGE_START >> PAGE_SHIFT, 1) != 1 )
3218 fprintf(logfile, "xc_ia64_get_pfn_list returned error %d\n", errno);
3219 exit(-1);
3222 shared_page = xc_map_foreign_range(xc_handle, domid, PAGE_SIZE,
3223 PROT_READ|PROT_WRITE,
3224 page_array[0]);
3225 #endif
3227 fprintf(logfile, "shared page at pfn:%lx, mfn: %lx\n", (nr_pages-1),
3228 (page_array[nr_pages - 1]));
3230 /* we always create the cdrom drive, even if no disk is there */
3231 bdrv_init();
3232 if (has_cdrom) {
3233 bs_table[2] = bdrv_new("cdrom");
3234 bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3237 /* open the virtual block devices */
3238 for(i = 0; i < MAX_DISKS; i++) {
3239 if (hd_filename[i]) {
3240 if (!bs_table[i]) {
3241 char buf[64];
3242 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3243 bs_table[i] = bdrv_new(buf);
3245 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3246 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3247 hd_filename[i]);
3248 exit(1);
3250 if (i == 0 && cyls != 0)
3251 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3255 /* we always create at least one floppy disk */
3256 fd_table[0] = bdrv_new("fda");
3257 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3259 for(i = 0; i < MAX_FD; i++) {
3260 if (fd_filename[i]) {
3261 if (!fd_table[i]) {
3262 char buf[64];
3263 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3264 fd_table[i] = bdrv_new(buf);
3265 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3267 if (fd_filename[i] != '\0') {
3268 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3269 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3270 fd_filename[i]);
3271 exit(1);
3277 /* init CPU state */
3278 env = cpu_init();
3279 global_env = env;
3280 cpu_single_env = env;
3282 init_ioports();
3283 cpu_calibrate_ticks();
3285 /* terminal init */
3286 if (nographic) {
3287 dumb_display_init(ds);
3288 } else {
3289 if (usevnc) {
3290 #ifdef CONFIG_VNC
3291 vnc_display_init(ds, (usevnc==2), vncport, vncconnect);
3292 #else
3293 fprintf(logfile, "qemu not configured with vnc support\n");
3294 #endif
3295 } else {
3296 #ifdef CONFIG_SDL
3297 sdl_display_init(ds, full_screen);
3298 #else
3299 dumb_display_init(ds);
3300 #endif
3304 vga_console = graphic_console_init(ds);
3306 monitor_hd = qemu_chr_open(monitor_device);
3307 if (!monitor_hd) {
3308 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3309 exit(1);
3311 monitor_init(monitor_hd, !nographic);
3313 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3314 if (serial_devices[i][0] != '\0') {
3315 serial_hds[i] = qemu_chr_open(serial_devices[i]);
3316 if (!serial_hds[i]) {
3317 fprintf(stderr, "qemu: could not open serial device '%s'\n",
3318 serial_devices[i]);
3319 exit(1);
3321 if (!strcmp(serial_devices[i], "vc"))
3322 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3326 /* setup cpu signal handlers for MMU / self modifying code handling */
3327 #if !defined(CONFIG_SOFTMMU)
3329 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3331 stack_t stk;
3332 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3333 stk.ss_sp = signal_stack;
3334 stk.ss_size = SIGNAL_STACK_SIZE;
3335 stk.ss_flags = 0;
3337 if (sigaltstack(&stk, NULL) < 0) {
3338 fprintf(logfile, "sigaltstack returned error %d\n", errno);
3339 exit(1);
3342 #endif
3344 struct sigaction act;
3346 sigfillset(&act.sa_mask);
3347 act.sa_flags = SA_SIGINFO;
3348 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3349 act.sa_flags |= SA_ONSTACK;
3350 #endif
3351 act.sa_sigaction = host_segv_handler;
3352 sigaction(SIGSEGV, &act, NULL);
3353 sigaction(SIGBUS, &act, NULL);
3354 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3355 sigaction(SIGFPE, &act, NULL);
3356 #endif
3358 #endif
3360 #ifndef _WIN32
3362 struct sigaction act;
3363 sigfillset(&act.sa_mask);
3364 act.sa_flags = 0;
3365 act.sa_handler = SIG_IGN;
3366 sigaction(SIGPIPE, &act, NULL);
3368 #endif
3369 init_timers();
3371 #if defined(TARGET_I386)
3372 pc_init(ram_size, vga_ram_size, boot_device,
3373 ds, fd_filename, snapshot,
3374 kernel_filename, kernel_cmdline, initrd_filename);
3375 #elif defined(TARGET_PPC)
3376 ppc_init(ram_size, vga_ram_size, boot_device,
3377 ds, fd_filename, snapshot,
3378 kernel_filename, kernel_cmdline, initrd_filename);
3379 #elif defined(TARGET_SPARC)
3380 sun4m_init(ram_size, vga_ram_size, boot_device,
3381 ds, fd_filename, snapshot,
3382 kernel_filename, kernel_cmdline, initrd_filename);
3383 #endif
3385 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3386 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3388 polling_timer = qemu_new_timer(rt_clock, polling_handler, NULL);
3389 qemu_mod_timer(polling_timer, qemu_get_clock(rt_clock));
3391 #ifdef CONFIG_GDBSTUB
3392 if (use_gdbstub) {
3393 if (gdbserver_start(gdbstub_port) < 0) {
3394 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
3395 gdbstub_port);
3396 exit(1);
3397 } else {
3398 fprintf(logfile, "Waiting gdb connection on port %d\n", gdbstub_port);
3400 } else
3401 #endif
3402 if (loadvm)
3403 qemu_loadvm(loadvm);
3406 /* XXX: simplify init */
3407 if (start_emulation) {
3408 vm_start();
3411 main_loop();
3412 quit_timers();
3413 return 0;
3416 extern fd_set wakeup_rfds;
3417 void tun_receive_handler(fd_set *rfds)
3419 IOHandlerRecord *ioh;
3420 static uint8_t buf[4096];
3421 int n, max_size;
3423 for (ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3424 if ( FD_ISSET(ioh->fd, rfds) ) {
3425 max_size = ioh->fd_can_read(ioh->opaque);
3426 if (max_size > 0) {
3427 if (max_size > sizeof(buf))
3428 max_size = sizeof(buf);
3429 n = read(ioh->fd, buf, max_size);
3430 if (n >= 0) {
3431 ioh->fd_read(ioh->opaque, buf, n);
3436 update_select_wakeup_events();
3439 void update_select_wakeup_events(void)
3441 IOHandlerRecord *ioh;
3442 int max_size;
3444 for(ioh = first_eventio_handler; ioh != NULL; ioh = ioh->next) {
3445 FD_CLR(ioh->fd, &wakeup_rfds);
3446 if (ioh->fd_can_read) {
3447 max_size = ioh->fd_can_read(ioh->opaque);
3448 if (max_size > 0) {
3449 FD_SET(ioh->fd, &wakeup_rfds);